\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename python.info
@documentencoding UTF-8
@ifinfo
@*Generated by Sphinx 2.4.4.@*
@end ifinfo
@settitle Python
@defindex ge
@paragraphindent 0
@exampleindent 4
@finalout
@dircategory Miscellaneous
@direntry
* python: (python.info). One line description of project
@end direntry

@definfoenclose strong,`,'
@definfoenclose emph,`,'
@c %**end of header

@copying
@quotation
Python 3.9.17, 七月 04, 2023

unknown

Copyright @copyright{} 2001-2023, Python Software Foundation
@end quotation

@end copying

@titlepage
@title Python
@insertcopying
@end titlepage
@contents

@c %** start of user preamble

@c %** end of user preamble

@ifnottex
@node Top
@top Python
@insertcopying
@end ifnottex

@c %**start of body
@anchor{contents doc}@anchor{14f}
@menu
* Python 有什么新变化？:: 
* Python 教程:: 
* 安装和使用 Python:: 
* Python 语言参考手册:: 
* Python 标准库:: 
* 扩展和嵌入 Python 解释器:: 
* Python/C API 参考手册:: 
* 分发 Python 模块:: 
* 安装 Python 模块:: 
* Python 常用指引:: 
* Python 常见问题:: 
* 术语对照表:: 
* 文档说明:: 
* 解决 Bug:: 
* 版权:: 
* 历史和许可证:: 
* 分发 Python 模块（遗留版本）:: 
* 安装Python模块（旧版）:: 
* Python 模块索引:: 
* 索引:: 

@detailmenu
 --- The Detailed Node Listing ---

Python 有什么新变化？

* Python 3.9 有什么新变化: Python 3 9 有什么新变化. 
* Python 3.8 有什么新变化: Python 3 8 有什么新变化. 
* Python 3.7 有什么新变化: Python 3 7 有什么新变化. 
* Python 3.6 有什么新变化: Python 3 6 有什么新变化. 
* Python 3.5 有什么新变化: Python 3 5 有什么新变化. 
* Python 3.4 有什么新变化: Python 3 4 有什么新变化. 
* Python 3.3 有什么新变化: Python 3 3 有什么新变化. 
* Python 3.2 有什么新变化: Python 3 2 有什么新变化. 
* Python 3.1 有什么新变化: Python 3 1 有什么新变化. 
* Python 3.0 有什么新变化: Python 3 0 有什么新变化. 
* Python 2.7 有什么新变化: Python 2 7 有什么新变化. 
* Python 2.6 有什么新变化: Python 2 6 有什么新变化. 
* Python 2.5 有什么新变化: Python 2 5 有什么新变化. 
* Python 2.4 有什么新变化: Python 2 4 有什么新变化. 
* Python 2.3 有什么新变化: Python 2 3 有什么新变化. 
* Python 2.2 有什么新变化: Python 2 2 有什么新变化. 
* Python 2.1 有什么新变化: Python 2 1 有什么新变化. 
* Python 2.0 有什么新变化: Python 2 0 有什么新变化. 
* 更新日志:: 

Python 3.9 有什么新变化

* 摘要 - 发布重点:: 
* 请检查代码中的 DeprecationWarning。:: 
* 新的特性:: 
* 其他语言特性修改:: 
* 新增模块:: 
* 改进的模块:: 
* 性能优化:: 
* 弃用:: 
* 移除:: 
* 移植到 Python 3.9: 移植到 Python 3 9. 
* 构建的改变:: 
* C API 的改变:: 
* Python 3.9.1 中的重要变化: Python 3 9 1 中的重要变化. 
* Python 3.9.2 中的重要变化: Python 3 9 2 中的重要变化. 
* Python 3.9.3 中的重要变化: Python 3 9 3 中的重要变化. 
* Python 3.9.5 中的重要变化: Python 3 9 5 中的重要变化. 
* Notable security feature in 3.9.14: Notable security feature in 3 9 14. 
* Notable Changes in 3.9.17: Notable Changes in 3 9 17. 

新的特性

* 字典合并与更新运算符:: 
* 新增用于移除前缀和后缀的字符串方法:: 
* 标准多项集中的类型标注泛型:: 
* 新的解析器:: 

新增模块

* zoneinfo:: 
* graphlib:: 

改进的模块

* ast:: 
* asyncio:: 
* compileall:: 
* concurrent.futures: concurrent futures. 
* curses:: 
* datetime:: 
* distutils:: 
* fcntl:: 
* ftplib:: 
* gc:: 
* hashlib:: 
* http:: 
* IDLE 与 idlelib:: 
* imaplib:: 
* importlib:: 
* inspect:: 
* ipaddress:: 
* math:: 
* multiprocessing:: 
* nntplib:: 
* os:: 
* pathlib:: 
* pdb:: 
* poplib:: 
* pprint:: 
* pydoc:: 
* random:: 
* signal:: 
* smtplib:: 
* socket:: 
* time:: 
* sys:: 
* tracemalloc:: 
* typing:: 
* unicodedata:: 
* venv:: 
* xml:: 

移植到 Python 3.9

* Python API 的变化:: 
* C API 的变化:: 
* CPython 字节码的改变:: 

C API 的改变

* 新的特性: 新的特性<2>. 
* 移植到 Python 3.9: 移植到 Python 3 9<2>. 
* 移除: 移除<2>. 

Python 3.9.1 中的重要变化

* typing: typing<2>. 
* macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持. 

Python 3.9.2 中的重要变化

* collections.abc: collections abc. 
* urllib.parse: urllib parse. 

Python 3.9.5 中的重要变化

* urllib.parse: urllib parse<2>. 

Notable Changes in 3.9.17

* tarfile:: 

Python 3.8 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<2>. 
* 新的特性: 新的特性<3>. 
* 其他语言特性修改: 其他语言特性修改<2>. 
* 新增模块: 新增模块<2>. 
* 改进的模块: 改进的模块<2>. 
* 性能优化: 性能优化<2>. 
* 构建和 C API 的改变:: 
* 弃用: 弃用<2>. 
* API 与特性的移除:: 
* 移植到 Python 3.8: 移植到 Python 3 8. 
* Python 3.8.1 中的重要变化: Python 3 8 1 中的重要变化. 
* Python 3.8.8 中的重要变化: Python 3 8 8 中的重要变化. 
* Python 3.8.12 中的重要变化: Python 3 8 12 中的重要变化. 

新的特性

* 赋值表达式:: 
* 仅限位置形参:: 
* 用于已编译字节码文件的并行文件系统缓存:: 
* 调试构建使用与发布构建相同的 ABI:: 
* f-字符串支持 = 用于自动记录表达式和调试文档:: 
* PEP 578; Python 运行时审核钩子: PEP 578 Python 运行时审核钩子. 
* PEP 587; Python 初始化配置: PEP 587 Python 初始化配置. 
* PEP 590; Vectorcall; 用于 CPython 的快速调用协议: PEP 590 Vectorcall 用于 CPython 的快速调用协议. 
* 具有外部数据缓冲区的 pickle 协议 5:: 

改进的模块

* ast: ast<2>. 
* asyncio: asyncio<2>. 
* builtins:: 
* collections:: 
* cProfile:: 
* csv:: 
* curses: curses<2>. 
* ctypes:: 
* datetime: datetime<2>. 
* functools:: 
* gc: gc<2>. 
* gettext:: 
* gzip:: 
* IDLE 与 idlelib: IDLE 与 idlelib<2>. 
* inspect: inspect<2>. 
* io:: 
* itertools:: 
* json.tool: json tool. 
* logging:: 
* math: math<2>. 
* mmap:: 
* multiprocessing: multiprocessing<2>. 
* os: os<2>. 
* os.path: os path. 
* pathlib: pathlib<2>. 
* pickle:: 
* plistlib:: 
* pprint: pprint<2>. 
* py_compile:: 
* shlex:: 
* shutil:: 
* socket: socket<2>. 
* ssl:: 
* statistics:: 
* sys: sys<2>. 
* tarfile: tarfile<2>. 
* threading:: 
* tokenize:: 
* tkinter:: 
* time: time<2>. 
* typing: typing<3>. 
* unicodedata: unicodedata<2>. 
* unittest:: 
* venv: venv<2>. 
* weakref:: 
* xml: xml<2>. 
* xmlrpc:: 

移植到 Python 3.8

* Python 行为的改变:: 
* 更改的Python API:: 
* C API 中的改变:: 
* CPython 字节码的改变: CPython 字节码的改变<2>. 
* 演示和工具:: 

Python 3.7 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<3>. 
* 新的特性: 新的特性<4>. 
* 其他语言特性修改: 其他语言特性修改<3>. 
* 新增模块: 新增模块<3>. 
* 改进的模块: 改进的模块<3>. 
* C API 的改变: C API 的改变<2>. 
* 构建的改变: 构建的改变<2>. 
* 性能优化: 性能优化<3>. 
* 其他 CPython 实现的改变:: 
* 已弃用的 Python 行为:: 
* 已弃用的 Python 模块、函数和方法:: 
* 已弃用的 C API 函数和类型:: 
* 平台支持的移除:: 
* API 与特性的移除: API 与特性的移除<2>. 
* 移除的模块:: 
* Windows 专属的改变:: 
* 移植到 Python 3.7: 移植到 Python 3 7. 
* Python 3.7.1 中的重要变化: Python 3 7 1 中的重要变化. 
* Python 3.7.2 中的重要变化: Python 3 7 2 中的重要变化. 
* Python 3.7.6 中的重要变化: Python 3 7 6 中的重要变化. 
* Python 3.7.10 中的重要变化: Python 3 7 10 中的重要变化. 

新的特性

* PEP 563：延迟的标注求值:: 
* PEP 538; 传统 C 区域强制转换: PEP 538 传统 C 区域强制转换. 
* PEP 540; 强制 UTF-8 运行时模式: PEP 540 强制 UTF-8 运行时模式. 
* PEP 553; 内置的 breakpoint(): PEP 553 内置的 breakpoint. 
* PEP 539; 用于线程局部存储的新 C API: PEP 539 用于线程局部存储的新 C API. 
* PEP 562; 定制对模块属性的访问: PEP 562 定制对模块属性的访问. 
* PEP 564; 具有纳秒级精度的新时间函数: PEP 564 具有纳秒级精度的新时间函数. 
* PEP 565; 在 __main__ 中显示 DeprecationWarning: PEP 565 在 __main__ 中显示 DeprecationWarning. 
* PEP 560; 对 typing 模块和泛型类型的核心支持: PEP 560 对 typing 模块和泛型类型的核心支持. 
* PEP 552; 基于哈希值的 .pyc 文件: PEP 552 基于哈希值的 pyc 文件. 
* PEP 545; Python 文档翻译: PEP 545 Python 文档翻译. 
* Python 开发模式 (-X dev): Python 开发模式 -X dev. 

新增模块

* contextvars:: 
* dataclasses:: 
* importlib.resources: importlib resources. 

改进的模块

* argparse:: 
* asyncio: asyncio<3>. 
* binascii:: 
* calendar:: 
* collections: collections<2>. 
* compileall: compileall<2>. 
* concurrent.futures: concurrent futures<2>. 
* contextlib:: 
* cProfile: cProfile<2>. 
* crypt:: 
* datetime: datetime<3>. 
* dbm:: 
* decimal:: 
* dis:: 
* distutils: distutils<2>. 
* enum:: 
* functools: functools<2>. 
* gc: gc<3>. 
* hmac:: 
* http.client: http client. 
* http.server: http server. 
* idlelib 与 IDLE:: 
* importlib: importlib<2>. 
* io: io<2>. 
* ipaddress: ipaddress<2>. 
* itertools: itertools<2>. 
* locale:: 
* logging: logging<2>. 
* math: math<3>. 
* mimetypes:: 
* msilib:: 
* multiprocessing: multiprocessing<3>. 
* os: os<3>. 
* pathlib: pathlib<3>. 
* pdb: pdb<2>. 
* py_compile: py_compile<2>. 
* pydoc: pydoc<2>. 
* queue:: 
* re:: 
* signal: signal<2>. 
* socket: socket<3>. 
* socketserver:: 
* sqlite3:: 
* ssl: ssl<2>. 
* string:: 
* subprocess:: 
* sys: sys<3>. 
* time: time<3>. 
* tkinter: tkinter<2>. 
* tracemalloc: tracemalloc<2>. 
* types:: 
* unicodedata: unicodedata<3>. 
* unittest: unittest<2>. 
* unittest.mock: unittest mock. 
* urllib.parse: urllib parse<3>. 
* uu:: 
* uuid:: 
* warnings:: 
* xml.etree: xml etree. 
* xmlrpc.server: xmlrpc server. 
* zipapp:: 
* zipfile:: 

已弃用的 Python 模块、函数和方法

* aifc:: 
* asyncio: asyncio<4>. 
* collections: collections<3>. 
* dbm: dbm<2>. 
* enum: enum<2>. 
* gettext: gettext<2>. 
* importlib: importlib<3>. 
* locale: locale<2>. 
* macpath:: 
* threading: threading<2>. 
* socket: socket<4>. 
* ssl: ssl<3>. 
* sunau:: 
* sys: sys<4>. 
* wave:: 

移植到 Python 3.7

* Python 行为的更改:: 
* 更改的Python API: 更改的Python API<2>. 
* C API 中的改变: C API 中的改变<2>. 
* CPython 字节码的改变: CPython 字节码的改变<3>. 
* Windows 专属的改变: Windows 专属的改变<2>. 
* 其他 CPython 实现的改变: 其他 CPython 实现的改变<2>. 

Python 3.6 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<4>. 
* 新的特性: 新的特性<5>. 
* 其他语言特性修改: 其他语言特性修改<4>. 
* 新增模块: 新增模块<4>. 
* 改进的模块: 改进的模块<4>. 
* 性能优化: 性能优化<4>. 
* 构建和 C API 的改变: 构建和 C API 的改变<2>. 
* 其他改进:: 
* 弃用: 弃用<3>. 
* 移除: 移除<3>. 
* 移植到Python 3.6: 移植到Python 3 6. 
* Python 3.6.2 中的重要变化: Python 3 6 2 中的重要变化. 
* Python 3.6.4 中的重要变化: Python 3 6 4 中的重要变化. 
* Python 3.6.5 中的重要变化: Python 3 6 5 中的重要变化. 
* Python 3.6.7 中的重要变化: Python 3 6 7 中的重要变化. 
* Python 3.6.10 中的重要变化: Python 3 6 10 中的重要变化. 
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13. 

新的特性

* PEP 498; 格式化字符串字面值: PEP 498 格式化字符串字面值. 
* PEP 526; 变量标注的语法: PEP 526 变量标注的语法. 
* PEP 515; 数字字面值中的下划线。: PEP 515 数字字面值中的下划线。. 
* PEP 525; 异步生成器: PEP 525 异步生成器. 
* PEP 530; 异步推导式: PEP 530 异步推导式. 
* PEP 487; 更简单的自定义类创建: PEP 487 更简单的自定义类创建. 
* PEP 487; 描述器协议的增强: PEP 487 描述器协议的增强. 
* PEP 519; 添加文件系统路径协议: PEP 519 添加文件系统路径协议. 
* PEP 495; 消除本地时间的歧义: PEP 495 消除本地时间的歧义. 
* PEP 529; 将Windows文件系统编码更改为UTF-8: PEP 529 将Windows文件系统编码更改为UTF-8. 
* PEP 528; 将Windows控制台编码更改为UTF-8: PEP 528 将Windows控制台编码更改为UTF-8. 
* PEP 520; 保留类属性定义顺序: PEP 520 保留类属性定义顺序. 
* PEP 468; 保留关键字参数顺序: PEP 468 保留关键字参数顺序. 
* 新的 dict 实现:: 
* PEP 523; 向CPython 添加框架评估API: PEP 523 向CPython 添加框架评估API. 
* PYTHONMALLOC 环境变量:: 
* DTrace 和 SystemTap 探测支持:: 

新增模块

* secrets:: 

改进的模块

* array:: 
* ast: ast<3>. 
* asyncio: asyncio<5>. 
* binascii: binascii<2>. 
* cmath:: 
* collections: collections<4>. 
* concurrent.futures: concurrent futures<3>. 
* contextlib: contextlib<2>. 
* datetime: datetime<4>. 
* decimal: decimal<2>. 
* distutils: distutils<3>. 
* email:: 
* encodings:: 
* enum: enum<3>. 
* faulthandler:: 
* fileinput:: 
* hashlib: hashlib<2>. 
* http.client: http client<2>. 
* idlelib 与 IDLE: idlelib 与 IDLE<2>. 
* importlib: importlib<4>. 
* inspect: inspect<3>. 
* json:: 
* logging: logging<3>. 
* math: math<4>. 
* multiprocessing: multiprocessing<4>. 
* os: os<4>. 
* pathlib: pathlib<4>. 
* pdb: pdb<3>. 
* pickle: pickle<2>. 
* pickletools:: 
* pydoc: pydoc<3>. 
* random: random<2>. 
* re: re<2>. 
* readline:: 
* rlcompleter:: 
* shlex: shlex<2>. 
* site:: 
* sqlite3: sqlite3<2>. 
* socket: socket<5>. 
* socketserver: socketserver<2>. 
* ssl: ssl<4>. 
* statistics: statistics<2>. 
* struct:: 
* subprocess: subprocess<2>. 
* sys: sys<5>. 
* telnetlib:: 
* time: time<4>. 
* timeit:: 
* tkinter: tkinter<3>. 
* traceback:: 
* tracemalloc: tracemalloc<3>. 
* typing: typing<4>. 
* unicodedata: unicodedata<4>. 
* unittest.mock: unittest mock<2>. 
* urllib.request: urllib request. 
* urllib.robotparser: urllib robotparser. 
* venv: venv<3>. 
* warnings: warnings<2>. 
* winreg:: 
* winsound:: 
* xmlrpc.client: xmlrpc client. 
* zipfile: zipfile<2>. 
* zlib:: 

弃用

* 新关键字:: 
* 已弃用的 Python 行为: 已弃用的 Python 行为<2>. 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<2>. 
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<2>. 
* 弃用的构建选项:: 

已弃用的 Python 模块、函数和方法

* asynchat:: 
* asyncore:: 
* dbm: dbm<3>. 
* distutils: distutils<4>. 
* grp:: 
* importlib: importlib<5>. 
* os: os<5>. 
* re: re<3>. 
* ssl: ssl<5>. 
* tkinter: tkinter<4>. 
* venv: venv<4>. 

移除

* API 与特性的移除: API 与特性的移除<3>. 

移植到Python 3.6

* 'python' 命令行为的变化:: 
* Python API 的更改:: 
* C API 中的改变: C API 中的改变<3>. 
* CPython 字节码的改变: CPython 字节码的改变<4>. 

Python 3.6.2 中的重要变化

* New make regen-all build target:: 
* Removal of make touch build target:: 

Python 3.5 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<5>. 
* 新的特性: 新的特性<6>. 
* 其他语言特性修改: 其他语言特性修改<5>. 
* 新增模块: 新增模块<5>. 
* 改进的模块: 改进的模块<5>. 
* 其他模块级更改:: 
* 性能优化: 性能优化<5>. 
* 构建和 C API 的改变: 构建和 C API 的改变<3>. 
* 弃用: 弃用<4>. 
* 移除: 移除<4>. 
* 移植到Python 3.5: 移植到Python 3 5. 
* Python 3.5.4 的显著变化: Python 3 5 4 的显著变化. 

新的特性

* PEP 492 - 使用 async 和 await 语法实现协程:: 
* PEP 465 - 用于矩阵乘法的专用中缀运算符:: 
* PEP 448 - Additional Unpacking Generalizations:: 
* PEP 461 - percent formatting support for bytes and bytearray:: 
* PEP 484 - 类型提示:: 
* PEP 471 - os.scandir() function: PEP 471 - os scandir function -- a better and faster directory iterator. a better and faster directory iterator
* PEP 475; Retry system calls failing with EINTR: PEP 475 Retry system calls failing with EINTR. 
* PEP 479; Change StopIteration handling inside generators: PEP 479 Change StopIteration handling inside generators. 
* PEP 485; A function for testing approximate equality: PEP 485 A function for testing approximate equality. 
* PEP 486; Make the Python Launcher aware of virtual environments: PEP 486 Make the Python Launcher aware of virtual environments. 
* PEP 488; Elimination of PYO files: PEP 488 Elimination of PYO files. 
* PEP 489; Multi-phase extension module initialization: PEP 489 Multi-phase extension module initialization. 

新增模块

* typing: typing<5>. 
* zipapp: zipapp<2>. 

改进的模块

* argparse: argparse<2>. 
* asyncio: asyncio<6>. 
* bz2:: 
* cgi:: 
* cmath: cmath<2>. 
* code:: 
* collections: collections<5>. 
* collections.abc: collections abc<2>. 
* compileall: compileall<3>. 
* concurrent.futures: concurrent futures<4>. 
* configparser:: 
* contextlib: contextlib<3>. 
* csv: csv<2>. 
* curses: curses<3>. 
* dbm: dbm<4>. 
* difflib:: 
* distutils: distutils<5>. 
* doctest:: 
* email: email<2>. 
* enum: enum<4>. 
* faulthandler: faulthandler<2>. 
* functools: functools<3>. 
* glob:: 
* gzip: gzip<2>. 
* heapq:: 
* http: http<2>. 
* http.client: http client<3>. 
* idlelib 与 IDLE: idlelib 与 IDLE<3>. 
* imaplib: imaplib<2>. 
* imghdr:: 
* importlib: importlib<6>. 
* inspect: inspect<4>. 
* io: io<3>. 
* ipaddress: ipaddress<3>. 
* json: json<2>. 
* linecache:: 
* locale: locale<3>. 
* logging: logging<4>. 
* lzma:: 
* math: math<5>. 
* multiprocessing: multiprocessing<5>. 
* operator:: 
* os: os<6>. 
* pathlib: pathlib<5>. 
* pickle: pickle<3>. 
* poplib: poplib<2>. 
* re: re<4>. 
* readline: readline<2>. 
* selectors:: 
* shutil: shutil<2>. 
* signal: signal<3>. 
* smtpd:: 
* smtplib: smtplib<2>. 
* sndhdr:: 
* socket: socket<6>. 
* ssl: ssl<6>. 
* sqlite3: sqlite3<3>. 
* subprocess: subprocess<3>. 
* sys: sys<6>. 
* sysconfig:: 
* tarfile: tarfile<3>. 
* threading: threading<3>. 
* time: time<5>. 
* timeit: timeit<2>. 
* tkinter: tkinter<5>. 
* traceback: traceback<2>. 
* types: types<2>. 
* unicodedata: unicodedata<5>. 
* unittest: unittest<3>. 
* unittest.mock: unittest mock<3>. 
* urllib:: 
* wsgiref:: 
* xmlrpc: xmlrpc<2>. 
* xml.sax: xml sax. 
* zipfile: zipfile<3>. 

ssl

* 内存 BIO 支持:: 
* Application-Layer Protocol Negotiation Support:: 
* Other Changes:: 

弃用

* 新关键字: 新关键字<2>. 
* 已弃用的 Python 行为: 已弃用的 Python 行为<3>. 
* 不支持的操作系统:: 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<3>. 

移除

* API 与特性的移除: API 与特性的移除<4>. 

移植到Python 3.5

* Python 行为的改变: Python 行为的改变<2>. 
* 改变了的Python API:: 
* C API 中的改变: C API 中的改变<4>. 

Python 3.5.4 的显著变化

* New make regen-all build target: New make regen-all build target<2>. 
* Removal of make touch build target: Removal of make touch build target<2>. 

Python 3.4 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<6>. 
* 新的特性: 新的特性<7>. 
* 新增模块: 新增模块<6>. 
* 改进的模块: 改进的模块<6>. 
* CPython Implementation Changes:: 
* 弃用: 弃用<5>. 
* 移除: 移除<5>. 
* 移植到 Python 3.4: 移植到 Python 3 4. 
* 3.4.3 的变化: 3 4 3 的变化. 

新的特性

* PEP 453; Explicit Bootstrapping of PIP in Python Installations: PEP 453 Explicit Bootstrapping of PIP in Python Installations. 
* PEP 446; Newly Created File Descriptors Are Non-Inheritable: PEP 446 Newly Created File Descriptors Are Non-Inheritable. 
* Improvements to Codec Handling:: 
* PEP 451; A ModuleSpec Type for the Import System: PEP 451 A ModuleSpec Type for the Import System. 
* 其他语言特性修改: 其他语言特性修改<6>. 

PEP 453: Explicit Bootstrapping of PIP in Python Installations

* Bootstrapping pip By Default:: 
* 文档更改:: 

新增模块

* asyncio: asyncio<7>. 
* ensurepip:: 
* enum: enum<5>. 
* pathlib: pathlib<6>. 
* selectors: selectors<2>. 
* statistics: statistics<3>. 
* tracemalloc: tracemalloc<4>. 

改进的模块

* abc:: 
* aifc: aifc<2>. 
* argparse: argparse<3>. 
* audioop:: 
* base64:: 
* collections: collections<6>. 
* colorsys:: 
* contextlib: contextlib<4>. 
* dbm: dbm<5>. 
* dis: dis<2>. 
* doctest: doctest<2>. 
* email: email<3>. 
* filecmp:: 
* functools: functools<4>. 
* gc: gc<4>. 
* glob: glob<2>. 
* hashlib: hashlib<3>. 
* hmac: hmac<2>. 
* html:: 
* http: http<3>. 
* idlelib 与 IDLE: idlelib 与 IDLE<4>. 
* importlib: importlib<7>. 
* inspect: inspect<5>. 
* ipaddress: ipaddress<4>. 
* logging: logging<5>. 
* marshal:: 
* mmap: mmap<2>. 
* multiprocessing: multiprocessing<6>. 
* operator: operator<2>. 
* os: os<7>. 
* pdb: pdb<4>. 
* pickle: pickle<4>. 
* plistlib: plistlib<2>. 
* poplib: poplib<3>. 
* pprint: pprint<3>. 
* pty:: 
* pydoc: pydoc<4>. 
* re: re<5>. 
* resource:: 
* select:: 
* shelve:: 
* shutil: shutil<3>. 
* smtpd: smtpd<2>. 
* smtplib: smtplib<3>. 
* socket: socket<7>. 
* sqlite3: sqlite3<4>. 
* ssl: ssl<7>. 
* stat:: 
* struct: struct<2>. 
* subprocess: subprocess<4>. 
* sunau: sunau<2>. 
* sys: sys<7>. 
* tarfile: tarfile<4>. 
* textwrap:: 
* threading: threading<4>. 
* traceback: traceback<3>. 
* types: types<3>. 
* urllib: urllib<2>. 
* unittest: unittest<4>. 
* venv: venv<5>. 
* wave: wave<2>. 
* weakref: weakref<2>. 
* xml.etree: xml etree<2>. 
* zipfile: zipfile<4>. 

CPython Implementation Changes

* PEP 445; Customization of CPython Memory Allocators: PEP 445 Customization of CPython Memory Allocators. 
* PEP 442; Safe Object Finalization: PEP 442 Safe Object Finalization. 
* PEP 456; Secure and Interchangeable Hash Algorithm: PEP 456 Secure and Interchangeable Hash Algorithm. 
* PEP 436; Argument Clinic: PEP 436 Argument Clinic. 
* Other Build and C API Changes:: 
* 其他改进: 其他改进<2>. 
* Significant Optimizations:: 

弃用

* Deprecations in the Python API:: 
* Deprecated Features:: 

移除

* 不再支持的操作系统:: 
* API 与特性的移除: API 与特性的移除<5>. 
* Code Cleanups:: 

移植到 Python 3.4

* 'python' 命令行为的变化: 'python' 命令行为的变化<2>. 
* Python API 的变化: Python API 的变化<2>. 
* C API 的变化: C API 的变化<2>. 

3.4.3 的变化

* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients. 

Python 3.3 有什么新变化

* 摘要 - 发布重点: 摘要 - 发布重点<7>. 
* PEP 405; 虚拟环境: PEP 405 虚拟环境. 
* PEP 420; 隐式命名空间包: PEP 420 隐式命名空间包. 
* PEP 3118; 新的内存视图实现和缓冲协议文档: PEP 3118 新的内存视图实现和缓冲协议文档. 
* PEP 393; 灵活的字符串表示: PEP 393 灵活的字符串表示. 
* PEP 397; 适用于Windows的Python启动器: PEP 397 适用于Windows的Python启动器. 
* PEP 3151; 重写 OS 和 IO 异常的层次结构: PEP 3151 重写 OS 和 IO 异常的层次结构. 
* PEP 380; 委托给子生成器的语法: PEP 380 委托给子生成器的语法. 
* PEP 409; 清除异常上下文: PEP 409 清除异常上下文. 
* PEP 414; 显式的Unicode文本: PEP 414 显式的Unicode文本. 
* PEP 3155; 类和函数的限定名称: PEP 3155 类和函数的限定名称. 
* PEP 412; Key-Sharing Dictionary: PEP 412 Key-Sharing Dictionary. 
* PEP 362; 函数签名对象: PEP 362 函数签名对象. 
* PEP 421; 添加 sys.implementation: PEP 421 添加 sys implementation. 
* Using importlib as the Implementation of Import:: 
* 其他语言特性修改: 其他语言特性修改<7>. 
* A Finer-Grained Import Lock:: 
* Builtin functions and types:: 
* 新增模块: 新增模块<7>. 
* 改进的模块: 改进的模块<7>. 
* 性能优化: 性能优化<6>. 
* 构建和 C API 的改变: 构建和 C API 的改变<4>. 
* 弃用: 弃用<6>. 
* 移植到 Python 3.3: 移植到 Python 3 3. 

PEP 3118: 新的内存视图实现和缓冲协议文档

* 相关特性:: 
* API 的变化:: 

PEP 393: 灵活的字符串表示

* 功能:: 
* Performance and resource usage:: 

PEP 421: 添加 sys.implementation

* SimpleNamespace:: 

Using importlib as the Implementation of Import

* New APIs:: 
* 可见的改变:: 

新增模块

* faulthandler: faulthandler<3>. 
* ipaddress: ipaddress<5>. 
* lzma: lzma<2>. 

改进的模块

* abc: abc<2>. 
* array: array<2>. 
* base64: base64<2>. 
* binascii: binascii<3>. 
* bz2: bz2<2>. 
* 编码器:: 
* collections: collections<7>. 
* contextlib: contextlib<5>. 
* crypt: crypt<2>. 
* curses: curses<4>. 
* datetime: datetime<5>. 
* decimal: decimal<3>. 
* email: email<4>. 
* ftplib: ftplib<2>. 
* functools: functools<5>. 
* gc: gc<5>. 
* hmac: hmac<3>. 
* http: http<4>. 
* html: html<2>. 
* imaplib: imaplib<3>. 
* inspect: inspect<6>. 
* io: io<4>. 
* itertools: itertools<3>. 
* logging: logging<6>. 
* math: math<6>. 
* mmap: mmap<3>. 
* multiprocessing: multiprocessing<7>. 
* nntplib: nntplib<2>. 
* os: os<8>. 
* pdb: pdb<5>. 
* pickle: pickle<5>. 
* pydoc: pydoc<5>. 
* re: re<6>. 
* sched:: 
* select: select<2>. 
* shlex: shlex<3>. 
* shutil: shutil<4>. 
* signal: signal<4>. 
* smtpd: smtpd<3>. 
* smtplib: smtplib<4>. 
* socket: socket<8>. 
* socketserver: socketserver<3>. 
* sqlite3: sqlite3<5>. 
* ssl: ssl<8>. 
* stat: stat<2>. 
* struct: struct<3>. 
* subprocess: subprocess<5>. 
* sys: sys<8>. 
* tarfile: tarfile<5>. 
* tempfile:: 
* textwrap: textwrap<2>. 
* threading: threading<5>. 
* time: time<6>. 
* types: types<4>. 
* unittest: unittest<5>. 
* urllib: urllib<3>. 
* webbrowser:: 
* xml.etree.ElementTree: xml etree ElementTree. 
* zlib: zlib<2>. 

decimal

* 相关特性: 相关特性<2>. 
* API 的变化: API 的变化<2>. 

email

* Policy Framework:: 
* Provisional Policy with New Header API:: 
* Other API Changes:: 

弃用

* 不支持的操作系统: 不支持的操作系统<2>. 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<4>. 
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<3>. 
* 弃用的功能:: 

移植到 Python 3.3

* Porting Python code:: 
* Porting C code:: 
* Building C extensions:: 
* Command Line Switch Changes:: 

Python 3.2 有什么新变化

* PEP 384; 定义稳定的ABI: PEP 384 定义稳定的ABI. 
* PEP 389; Argparse 命令行解析模块: PEP 389 Argparse 命令行解析模块. 
* PEP 391; 基于字典的日志配置: PEP 391 基于字典的日志配置. 
* PEP 3148; concurrent.futures 模块: PEP 3148 concurrent futures 模块. 
* PEP 3147; PYC 仓库目录: PEP 3147 PYC 仓库目录. 
* PEP 3149; ABI Version Tagged .so Files: PEP 3149 ABI Version Tagged so Files. 
* PEP 3333; Python Web服务器网关接口v1.0.1: PEP 3333 Python Web服务器网关接口v1 0 1. 
* 其他语言特性修改: 其他语言特性修改<8>. 
* 新增，改进和弃用的模块:: 
* 多线程:: 
* 性能优化: 性能优化<7>. 
* Unicode:: 
* 编解码器:: 
* 文档:: 
* IDLE:: 
* 代码库:: 
* 构建和 C API 的改变: 构建和 C API 的改变<5>. 
* 移植到 Python 3.2: 移植到 Python 3 2. 

新增，改进和弃用的模块

* email: email<5>. 
* elementtree:: 
* functools: functools<6>. 
* itertools: itertools<4>. 
* collections: collections<8>. 
* threading: threading<6>. 
* datetime 和 time:: 
* math: math<7>. 
* abc: abc<3>. 
* io: io<5>. 
* reprlib:: 
* logging: logging<7>. 
* csv: csv<3>. 
* contextlib: contextlib<6>. 
* decimal and fractions:: 
* ftp:: 
* popen:: 
* select: select<3>. 
* gzip 和 zipfile:: 
* tarfile: tarfile<6>. 
* hashlib: hashlib<4>. 
* ast: ast<4>. 
* os: os<9>. 
* shutil: shutil<5>. 
* sqlite3: sqlite3<6>. 
* html: html<3>. 
* socket: socket<9>. 
* ssl: ssl<9>. 
* nntp:: 
* certificates:: 
* imaplib: imaplib<4>. 
* http.client: http client<4>. 
* unittest: unittest<6>. 
* random: random<3>. 
* poplib: poplib<4>. 
* asyncore: asyncore<2>. 
* tempfile: tempfile<2>. 
* inspect: inspect<7>. 
* pydoc: pydoc<6>. 
* dis: dis<3>. 
* dbm: dbm<6>. 
* ctypes: ctypes<2>. 
* site: site<2>. 
* sysconfig: sysconfig<2>. 
* pdb: pdb<6>. 
* configparser: configparser<2>. 
* urllib.parse: urllib parse<4>. 
* mailbox:: 
* turtledemo:: 

Python 3.1 有什么新变化

* PEP 372; 有序字典: PEP 372 有序字典. 
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符. 
* 其他语言特性修改: 其他语言特性修改<9>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<2>. 
* 性能优化: 性能优化<8>. 
* IDLE: IDLE<2>. 
* 构建和 C API 的改变: 构建和 C API 的改变<6>. 
* 移植到 Python 3.1: 移植到 Python 3 1. 

Python 3.0 有什么新变化

* 常见的绊脚石:: 
* 语法变化概述:: 
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6. 
* 库的修改:: 
* PEP 3101; A New Approach To String Formatting: PEP 3101 A New Approach To String Formatting. 
* Changes To Exceptions:: 
* Miscellaneous Other Changes:: 
* 构建和 C API 的改变: 构建和 C API 的改变<7>. 
* 性能:: 
* 移植到 Python 3.0: 移植到 Python 3 0. 

常见的绊脚石

* Print 是函数:: 
* 用视图和迭代器取代列表:: 
* Ordering Comparisons:: 
* 整数:: 
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit. 

语法变化概述

* 新语法:: 
* 修改的语法:: 
* 移除的语法:: 

Miscellaneous Other Changes

* Operators And Special Methods:: 
* Builtins:: 

Python 2.7 有什么新变化

* Python 2.x的未来: Python 2 x的未来. 
* 对于弃用警告处理方式的改变:: 
* Python 3.1 特性: Python 3 1 特性. 
* PEP 372; Adding an Ordered Dictionary to collections: PEP 372 Adding an Ordered Dictionary to collections. 
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符<2>. 
* PEP 389; The argparse Module for Parsing Command Lines: PEP 389 The argparse Module for Parsing Command Lines. 
* PEP 391; Dictionary-Based Configuration For Logging: PEP 391 Dictionary-Based Configuration For Logging. 
* PEP 3106; 字典视图: PEP 3106 字典视图. 
* PEP 3137; memoryview 对象: PEP 3137 memoryview 对象. 
* 其他语言特性修改: 其他语言特性修改<10>. 
* 新增和改进的模块:: 
* 构建和 C API 的改变: 构建和 C API 的改变<8>. 
* 其他的改变和修正:: 
* 移植到 Python 2.7: 移植到 Python 2 7. 
* New Features Added to Python 2.7 Maintenance Releases: New Features Added to Python 2 7 Maintenance Releases. 
* 致谢:: 

其他语言特性修改

* Interpreter Changes:: 
* 性能优化: 性能优化<9>. 

新增和改进的模块

* 新模块：importlib:: 
* 新模块：sysconfig:: 
* ttk; Themed Widgets for Tk: ttk Themed Widgets for Tk. 
* 更新的模块：unittest:: 
* 更新的模块：ElementTree 1.3: 更新的模块：ElementTree 1 3. 

构建和 C API 的改变

* 胶囊:: 
* 特定于 Windows 的更改：:: 
* 特定于 Mac OS X 的更改：:: 
* 特定于 FreeBSD 的更改：:: 

New Features Added to Python 2.7 Maintenance Releases

* Two new environment variables for debug mode:: 
* PEP 434; IDLE Enhancement Exception for All Branches: PEP 434 IDLE Enhancement Exception for All Branches. 
* PEP 466; Network Security Enhancements for Python 2.7: PEP 466 Network Security Enhancements for Python 2 7. 
* PEP 477; Backport ensurepip (PEP 453) to Python 2.7: PEP 477 Backport ensurepip PEP 453 to Python 2 7. 
* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients<2>. 
* PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具. 
* New make regen-all build target: New make regen-all build target<3>. 
* Removal of make touch build target: Removal of make touch build target<3>. 

PEP 477: Backport ensurepip (PEP 453) to Python 2.7

* Bootstrapping pip By Default: Bootstrapping pip By Default<2>. 
* 文档更改: 文档更改<2>. 

Python 2.6 有什么新变化

* Python 3.0: Python 3 0. 
* 开发过程的变化:: 
* PEP 343; "with" 语句: PEP 343 "with" 语句. 
* PEP 366; 从主模块显式相对导入: PEP 366 从主模块显式相对导入. 
* PEP 370; 分用户的 site-packages 目录: PEP 370 分用户的 site-packages 目录. 
* PEP 371; 多任务处理包: PEP 371 多任务处理包. 
* PEP 3101; 高级字符串格式: PEP 3101 高级字符串格式. 
* PEP 3105; print 改为函数: PEP 3105 print 改为函数. 
* PEP 3110; 异常处理的变更: PEP 3110 异常处理的变更. 
* PEP 3112; 字节字面值: PEP 3112 字节字面值. 
* PEP 3116; 新 I/O 库: PEP 3116 新 I/O 库. 
* PEP 3118; 修改缓冲区协议: PEP 3118 修改缓冲区协议. 
* PEP 3119; 抽象基类: PEP 3119 抽象基类. 
* PEP 3127; 整型文字支持和语法: PEP 3127 整型文字支持和语法. 
* PEP 3129; 类装饰器: PEP 3129 类装饰器. 
* PEP 3141; A Type Hierarchy for Numbers: PEP 3141 A Type Hierarchy for Numbers. 
* 其他语言特性修改: 其他语言特性修改<11>. 
* 新增和改进的模块: 新增和改进的模块<2>. 
* Deprecations and Removals:: 
* 构建和 C API 的改变: 构建和 C API 的改变<9>. 
* 移植到Python 2.6: 移植到Python 2 6. 
* 致谢: 致谢<2>. 

开发过程的变化

* 新问题追踪：简述:: 
* 新的文档格式：使用 Sphinx 的 reStructuredText:: 

PEP 343: "with" 语句

* 编写上下文管理器:: 
* contextlib 模块:: 

PEP 3141: A Type Hierarchy for Numbers

* fractions 模块:: 

其他语言特性修改

* 性能优化: 性能优化<10>. 
* Interpreter Changes: Interpreter Changes<2>. 

新增和改进的模块

* ast 模块:: 
* future_builtins 模块:: 
* The json module; JavaScript Object Notation: The json module JavaScript Object Notation. 
* plistlib 模块：属性列表解析器:: 
* ctypes Enhancements:: 
* Improved SSL Support:: 

构建和 C API 的改变

* 特定于 Windows 的更改：: 特定于 Windows 的更改：<2>. 
* 特定于 Mac OS X 的更改：Mac OS X:: 
* 特定于 IRIX 的更改：:: 

Python 2.5 有什么新变化

* PEP 308; 条件表达式: PEP 308 条件表达式. 
* PEP 309; 部分功能应用: PEP 309 部分功能应用. 
* PEP 314; Python软件包的元数据 v1.1: PEP 314 Python软件包的元数据 v1 1. 
* PEP 328; 绝对导入和相对导入: PEP 328 绝对导入和相对导入. 
* PEP 338; 将模块作为脚本执行: PEP 338 将模块作为脚本执行. 
* PEP 341; 统一 try/except/finally: PEP 341 统一 try/except/finally. 
* PEP 342; 生成器的新特性: PEP 342 生成器的新特性. 
* PEP 343; "with" 语句: PEP 343 "with" 语句<2>. 
* PEP 352; 异常作为新型的类: PEP 352 异常作为新型的类. 
* PEP 353; 使用ssize_t作为索引类型: PEP 353 使用ssize_t作为索引类型. 
* PEP 357; '__index__' 方法: PEP 357 '__index__' 方法. 
* 其他语言特性修改: 其他语言特性修改<12>. 
* 新增，改进和删除的模块:: 
* 构建和 C API 的改变: 构建和 C API 的改变<10>. 
* 移植到Python 2.5: 移植到Python 2 5. 
* 致谢: 致谢<3>. 

PEP 343: "with" 语句

* 编写上下文管理器: 编写上下文管理器<2>. 
* contextlib 模块: contextlib 模块<2>. 

其他语言特性修改

* 交互解释器变更:: 
* 性能优化: 性能优化<11>. 

新增，改进和删除的模块

* ctypes 包:: 
* ElementTree 包:: 
* hashlib 包:: 
* sqlite3 包:: 
* wsgiref 包:: 

构建和 C API 的改变

* Port-Specific Changes:: 

Python 2.4 有什么新变化

* PEP 218; 内置集合对象: PEP 218 内置集合对象. 
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数. 
* PEP 289; 生成器表达式: PEP 289 生成器表达式. 
* PEP 292; 更简单的字符串替换: PEP 292 更简单的字符串替换. 
* PEP 318; 函数和方法的装饰器: PEP 318 函数和方法的装饰器. 
* PEP 322; 反向迭代: PEP 322 反向迭代. 
* PEP 324; 新的子进程模块: PEP 324 新的子进程模块. 
* PEP 327; 十进制数据类型: PEP 327 十进制数据类型. 
* PEP 328; 多行导入: PEP 328 多行导入. 
* PEP 331; Locale-Independent Float/String Conversions: PEP 331 Locale-Independent Float/String Conversions. 
* 其他语言特性修改: 其他语言特性修改<13>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<3>. 
* 构建和 C API 的改变: 构建和 C API 的改变<11>. 
* 移植到 Python 2.4: 移植到 Python 2 4. 
* 致谢: 致谢<4>. 

PEP 327: 十进制数据类型

* 为什么需要十进制？:: 
* Decimal 类型:: 
* Context 类型:: 

其他语言特性修改

* 性能优化: 性能优化<12>. 

新增，改进和弃用的模块

* cookielib:: 
* doctest: doctest<3>. 

构建和 C API 的改变

* Port-Specific Changes: Port-Specific Changes<2>. 

Python 2.3 有什么新变化

* PEP 218; 标准集合数据类型: PEP 218 标准集合数据类型. 
* PEP 255; 简单的生成器: PEP 255 简单的生成器. 
* PEP 263; 源代码的字符编码格式: PEP 263 源代码的字符编码格式. 
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块. 
* PEP 277; 针对 Windows NT 的 Unicode 文件名支持: PEP 277 针对 Windows NT 的 Unicode 文件名支持. 
* PEP 278; 通用换行支持: PEP 278 通用换行支持. 
* PEP 279; enumerate(): PEP 279 enumerate. 
* PEP 282; logging 包: PEP 282 logging 包. 
* PEP 285; 布尔类型: PEP 285 布尔类型. 
* PEP 293; Codec Error Handling Callbacks: PEP 293 Codec Error Handling Callbacks. 
* PEP 301; Distutils的软件包索引和元数据: PEP 301 Distutils的软件包索引和元数据. 
* PEP 302; 新导入钩子: PEP 302 新导入钩子. 
* PEP 305; 逗号分隔文件: PEP 305 逗号分隔文件. 
* PEP 307; Pickle Enhancements: PEP 307 Pickle Enhancements. 
* 扩展切片:: 
* 其他语言特性修改: 其他语言特性修改<14>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<4>. 
* Pymalloc; A Specialized Object Allocator: Pymalloc A Specialized Object Allocator. 
* 构建和 C API 的改变: 构建和 C API 的改变<12>. 
* 其他的改变和修正: 其他的改变和修正<2>. 
* 移植到 Python 2.3: 移植到 Python 2 3. 
* 致谢: 致谢<5>. 

其他语言特性修改

* String Changes:: 
* 性能优化: 性能优化<13>. 

新增，改进和弃用的模块

* Date/Time 类型:: 
* optparse 模块:: 

构建和 C API 的改变

* Port-Specific Changes: Port-Specific Changes<3>. 

Python 2.2 有什么新变化

* 概述:: 
* PEP 252 和 253：类型和类的修改:: 
* PEP 234; 迭代器: PEP 234 迭代器. 
* PEP 255; 简单的生成器: PEP 255 简单的生成器<2>. 
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>. 
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator. 
* Unicode Changes:: 
* PEP 227; 嵌套的作用域: PEP 227 嵌套的作用域. 
* 新增和改进的模块: 新增和改进的模块<3>. 
* 解释器的改变和修正:: 
* 其他的改变和修正: 其他的改变和修正<3>. 
* 致谢: 致谢<6>. 

PEP 252 和 253：类型和类的修改

* 旧式类和新式类:: 
* 描述器:: 
* 多重继承：钻石规则:: 
* 属性访问:: 
* 相关链接:: 

Python 2.1 有什么新变化

* 概述: 概述<2>. 
* PEP 227; 嵌套的作用域: PEP 227 嵌套的作用域<2>. 
* PEP 236; __future__ 指令: PEP 236 __future__ 指令. 
* PEP 207; 富比较: PEP 207 富比较. 
* PEP 230; 警告框架: PEP 230 警告框架. 
* PEP 229; 新的构建系统: PEP 229 新的构建系统. 
* PEP 205; 弱引用: PEP 205 弱引用. 
* PEP 232; 函数属性: PEP 232 函数属性. 
* PEP 235; 在大小写不敏感的平台上导入模块: PEP 235 在大小写不敏感的平台上导入模块. 
* PEP 217; Interactive Display Hook: PEP 217 Interactive Display Hook. 
* PEP 208; New Coercion Model: PEP 208 New Coercion Model. 
* PEP 241; Metadata in Python Packages: PEP 241 Metadata in Python Packages. 
* 新增和改进的模块: 新增和改进的模块<4>. 
* 其他的改变和修正: 其他的改变和修正<4>. 
* 致谢: 致谢<7>. 

Python 2.0 有什么新变化

* 概述: 概述<3>. 
* What About Python 1.6?: What About Python 1 6?. 
* 新开发流程:: 
* Unicode: Unicode<2>. 
* 列表推导式:: 
* Augmented Assignment:: 
* 字符串的方法:: 
* Garbage Collection of Cycles:: 
* 其他核心变化:: 
* 移植 Python 2.0: 移植 Python 2 0. 
* 扩展/嵌入更改:: 
* Distutils：使模块易于安装:: 
* XML 模块:: 
* 模块更改:: 
* 新增模块: 新增模块<8>. 
* IDLE 改进:: 
* 删除和弃用的模块:: 
* 致谢: 致谢<8>. 

其他核心变化

* 细微的语言特性修改:: 
* 对于内置函数的修改:: 

XML 模块

* SAX2 Support:: 
* DOM Support:: 
* Relationship to PyXML:: 

更新日志

* Python 3.9.17 final: Python 3 9 17 final. 
* Python 3.9.16 final: Python 3 9 16 final. 
* Python 3.9.15 final: Python 3 9 15 final. 
* Python 3.9.14 final: Python 3 9 14 final. 
* Python 3.9.13 final: Python 3 9 13 final. 
* Python 3.9.12 final: Python 3 9 12 final. 
* Python 3.9.11 final: Python 3 9 11 final. 
* Python 3.9.10 final: Python 3 9 10 final. 
* Python 3.9.9 final: Python 3 9 9 final. 
* Python 3.9.8 final: Python 3 9 8 final. 
* Python 3.9.7 final: Python 3 9 7 final. 
* Python 3.9.6 final: Python 3 9 6 final. 
* Python 3.9.5 final: Python 3 9 5 final. 
* Python 3.9.4 final: Python 3 9 4 final. 
* Python 3.9.3 final: Python 3 9 3 final. 
* Python 3.9.2 final: Python 3 9 2 final. 
* Python 3.9.2 release candidate 1: Python 3 9 2 release candidate 1. 
* Python 3.9.1 final: Python 3 9 1 final. 
* Python 3.9.1 release candidate 1: Python 3 9 1 release candidate 1. 
* Python 3.9.0 final: Python 3 9 0 final. 
* Python 3.9.0 release candidate 2: Python 3 9 0 release candidate 2. 
* Python 3.9.0 release candidate 1: Python 3 9 0 release candidate 1. 
* Python 3.9.0 beta 5: Python 3 9 0 beta 5. 
* Python 3.9.0 beta 4: Python 3 9 0 beta 4. 
* Python 3.9.0 beta 3: Python 3 9 0 beta 3. 
* Python 3.9.0 beta 2: Python 3 9 0 beta 2. 
* Python 3.9.0 beta 1: Python 3 9 0 beta 1. 
* Python 3.9.0 alpha 6: Python 3 9 0 alpha 6. 
* Python 3.9.0 alpha 5: Python 3 9 0 alpha 5. 
* Python 3.9.0 alpha 4: Python 3 9 0 alpha 4. 
* Python 3.9.0 alpha 3: Python 3 9 0 alpha 3. 
* Python 3.9.0 alpha 2: Python 3 9 0 alpha 2. 
* Python 3.9.0 alpha 1: Python 3 9 0 alpha 1. 
* Python 3.8.0 beta 1: Python 3 8 0 beta 1. 
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4. 
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3. 
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2. 
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1. 
* Python 3.7.0 final: Python 3 7 0 final. 
* Python 3.7.0 release candidate 1: Python 3 7 0 release candidate 1. 
* Python 3.7.0 beta 5: Python 3 7 0 beta 5. 
* Python 3.7.0 beta 4: Python 3 7 0 beta 4. 
* Python 3.7.0 beta 3: Python 3 7 0 beta 3. 
* Python 3.7.0 beta 2: Python 3 7 0 beta 2. 
* Python 3.7.0 beta 1: Python 3 7 0 beta 1. 
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4. 
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3. 
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2. 
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1. 
* Python 3.6.6 final: Python 3 6 6 final. 
* Python 3.6.6 release candidate 1: Python 3 6 6 release candidate 1. 
* Python 3.6.5 final: Python 3 6 5 final. 
* Python 3.6.5 release candidate 1: Python 3 6 5 release candidate 1. 
* Python 3.6.4 final: Python 3 6 4 final. 
* Python 3.6.4 release candidate 1: Python 3 6 4 release candidate 1. 
* Python 3.6.3 final: Python 3 6 3 final. 
* Python 3.6.3 release candidate 1: Python 3 6 3 release candidate 1. 
* Python 3.6.2 final: Python 3 6 2 final. 
* Python 3.6.2 release candidate 2: Python 3 6 2 release candidate 2. 
* Python 3.6.2 release candidate 1: Python 3 6 2 release candidate 1. 
* Python 3.6.1 final: Python 3 6 1 final. 
* Python 3.6.1 release candidate 1: Python 3 6 1 release candidate 1. 
* Python 3.6.0 final: Python 3 6 0 final. 
* Python 3.6.0 release candidate 2: Python 3 6 0 release candidate 2. 
* Python 3.6.0 release candidate 1: Python 3 6 0 release candidate 1. 
* Python 3.6.0 beta 4: Python 3 6 0 beta 4. 
* Python 3.6.0 beta 3: Python 3 6 0 beta 3. 
* Python 3.6.0 beta 2: Python 3 6 0 beta 2. 
* Python 3.6.0 beta 1: Python 3 6 0 beta 1. 
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4. 
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3. 
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2. 
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1. 
* Python 3.5.5 final: Python 3 5 5 final. 
* Python 3.5.5 release candidate 1: Python 3 5 5 release candidate 1. 
* Python 3.5.4 final: Python 3 5 4 final. 
* Python 3.5.4 release candidate 1: Python 3 5 4 release candidate 1. 
* Python 3.5.3 final: Python 3 5 3 final. 
* Python 3.5.3 release candidate 1: Python 3 5 3 release candidate 1. 
* Python 3.5.2 final: Python 3 5 2 final. 
* Python 3.5.2 release candidate 1: Python 3 5 2 release candidate 1. 
* Python 3.5.1 final: Python 3 5 1 final. 
* Python 3.5.1 release candidate 1: Python 3 5 1 release candidate 1. 
* Python 3.5.0 final: Python 3 5 0 final. 
* Python 3.5.0 release candidate 4: Python 3 5 0 release candidate 4. 
* Python 3.5.0 release candidate 3: Python 3 5 0 release candidate 3. 
* Python 3.5.0 release candidate 2: Python 3 5 0 release candidate 2. 
* Python 3.5.0 release candidate 1: Python 3 5 0 release candidate 1. 
* Python 3.5.0 beta 4: Python 3 5 0 beta 4. 
* Python 3.5.0 beta 3: Python 3 5 0 beta 3. 
* Python 3.5.0 beta 2: Python 3 5 0 beta 2. 
* Python 3.5.0 beta 1: Python 3 5 0 beta 1. 
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4. 
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3. 
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2. 
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1. 

Python 3.9.17 final

* Security:: 
* Core and Builtins:: 
* Library:: 
* Windows:: 
* macOS:: 

Python 3.9.16 final

* Security: Security<2>. 

Python 3.9.15 final

* Security: Security<3>. 
* Core and Builtins: Core and Builtins<2>. 
* Library: Library<2>. 
* Windows: Windows<2>. 
* macOS: macOS<2>. 

Python 3.9.14 final

* Security: Security<4>. 
* Core and Builtins: Core and Builtins<3>. 
* Library: Library<3>. 
* Tests:: 

Python 3.9.13 final

* Core and Builtins: Core and Builtins<4>. 
* Library: Library<4>. 
* Documentation:: 
* Tests: Tests<2>. 
* Build:: 
* Windows: Windows<3>. 
* Tools/Demos:: 

Python 3.9.12 final

* Core and Builtins: Core and Builtins<5>. 
* Library: Library<5>. 

Python 3.9.11 final

* Core and Builtins: Core and Builtins<6>. 
* Library: Library<6>. 
* Documentation: Documentation<2>. 
* Tests: Tests<3>. 
* Build: Build<2>. 
* Windows: Windows<4>. 
* macOS: macOS<3>. 
* IDLE: IDLE<3>. 

Python 3.9.10 final

* Core and Builtins: Core and Builtins<7>. 
* Library: Library<7>. 
* Documentation: Documentation<3>. 
* Tests: Tests<4>. 
* Build: Build<3>. 
* Windows: Windows<5>. 
* macOS: macOS<4>. 
* Tools/Demos: Tools/Demos<2>. 
* C API:: 

Python 3.9.9 final

* Core and Builtins: Core and Builtins<8>. 
* Library: Library<8>. 
* Documentation: Documentation<4>. 
* Windows: Windows<6>. 

Python 3.9.8 final

* Core and Builtins: Core and Builtins<9>. 
* Library: Library<9>. 
* Documentation: Documentation<5>. 
* Tests: Tests<5>. 
* Build: Build<4>. 
* Windows: Windows<7>. 
* macOS: macOS<5>. 
* IDLE: IDLE<4>. 
* C API: C API<2>. 

Python 3.9.7 final

* Security: Security<5>. 
* Core and Builtins: Core and Builtins<10>. 
* Library: Library<10>. 
* Documentation: Documentation<6>. 
* Tests: Tests<6>. 
* Build: Build<5>. 
* Windows: Windows<8>. 
* macOS: macOS<6>. 

Python 3.9.6 final

* Security: Security<6>. 
* Core and Builtins: Core and Builtins<11>. 
* Library: Library<11>. 
* Documentation: Documentation<7>. 
* Tests: Tests<7>. 
* Build: Build<6>. 
* Windows: Windows<9>. 
* macOS: macOS<7>. 
* IDLE: IDLE<5>. 
* Tools/Demos: Tools/Demos<3>. 
* C API: C API<3>. 

Python 3.9.5 final

* Security: Security<7>. 
* Core and Builtins: Core and Builtins<12>. 
* Library: Library<12>. 
* Documentation: Documentation<8>. 
* Tests: Tests<8>. 
* Windows: Windows<10>. 
* macOS: macOS<8>. 
* IDLE: IDLE<6>. 

Python 3.9.4 final

* Core and Builtins: Core and Builtins<13>. 
* Library: Library<13>. 

Python 3.9.3 final

* Security: Security<8>. 
* Core and Builtins: Core and Builtins<14>. 
* Library: Library<14>. 
* Documentation: Documentation<9>. 
* Tests: Tests<9>. 
* Build: Build<7>. 
* macOS: macOS<9>. 
* IDLE: IDLE<7>. 

Python 3.9.2 final

* Windows: Windows<11>. 

Python 3.9.2 release candidate 1

* Security: Security<9>. 
* Core and Builtins: Core and Builtins<15>. 
* Library: Library<15>. 
* Documentation: Documentation<10>. 
* Tests: Tests<10>. 
* Build: Build<8>. 
* Windows: Windows<12>. 
* macOS: macOS<10>. 
* IDLE: IDLE<8>. 
* Tools/Demos: Tools/Demos<4>. 
* C API: C API<4>. 

Python 3.9.1 final

* Core and Builtins: Core and Builtins<16>. 
* Library: Library<16>. 
* Tests: Tests<11>. 
* macOS: macOS<11>. 
* IDLE: IDLE<9>. 

Python 3.9.1 release candidate 1

* Security: Security<10>. 
* Core and Builtins: Core and Builtins<17>. 
* Library: Library<17>. 
* Documentation: Documentation<11>. 
* Tests: Tests<12>. 
* Build: Build<9>. 
* Windows: Windows<13>. 
* macOS: macOS<12>. 
* IDLE: IDLE<10>. 
* C API: C API<5>. 

Python 3.9.0 final

* Library: Library<18>. 
* Tests: Tests<13>. 
* Build: Build<10>. 

Python 3.9.0 release candidate 2

* Core and Builtins: Core and Builtins<18>. 
* Library: Library<19>. 
* Documentation: Documentation<12>. 
* Tests: Tests<14>. 
* Build: Build<11>. 
* Windows: Windows<14>. 
* C API: C API<6>. 

Python 3.9.0 release candidate 1

* Core and Builtins: Core and Builtins<19>. 
* Library: Library<20>. 
* Documentation: Documentation<13>. 
* Windows: Windows<15>. 
* IDLE: IDLE<11>. 

Python 3.9.0 beta 5

* Security: Security<11>. 
* Core and Builtins: Core and Builtins<20>. 
* Library: Library<21>. 
* Documentation: Documentation<14>. 
* macOS: macOS<13>. 
* IDLE: IDLE<12>. 
* C API: C API<7>. 

Python 3.9.0 beta 4

* Security: Security<12>. 
* Core and Builtins: Core and Builtins<21>. 
* Library: Library<22>. 
* Tests: Tests<15>. 
* Build: Build<12>. 
* Windows: Windows<16>. 
* macOS: macOS<14>. 
* IDLE: IDLE<13>. 
* C API: C API<8>. 

Python 3.9.0 beta 3

* Library: Library<23>. 
* Build: Build<13>. 

Python 3.9.0 beta 2

* Core and Builtins: Core and Builtins<22>. 
* Library: Library<24>. 
* Tests: Tests<16>. 
* Build: Build<14>. 
* Windows: Windows<17>. 
* macOS: macOS<15>. 
* IDLE: IDLE<14>. 
* C API: C API<9>. 

Python 3.9.0 beta 1

* Security: Security<13>. 
* Core and Builtins: Core and Builtins<23>. 
* Library: Library<25>. 
* Documentation: Documentation<15>. 
* Tests: Tests<17>. 
* Build: Build<15>. 
* Windows: Windows<18>. 
* macOS: macOS<16>. 
* Tools/Demos: Tools/Demos<5>. 
* C API: C API<10>. 

Python 3.9.0 alpha 6

* Security: Security<14>. 
* Core and Builtins: Core and Builtins<24>. 
* Library: Library<26>. 
* Documentation: Documentation<16>. 
* Tests: Tests<18>. 
* Build: Build<16>. 
* Windows: Windows<19>. 
* macOS: macOS<17>. 
* IDLE: IDLE<15>. 
* Tools/Demos: Tools/Demos<6>. 
* C API: C API<11>. 

Python 3.9.0 alpha 5

* Security: Security<15>. 
* Core and Builtins: Core and Builtins<25>. 
* Library: Library<27>. 
* Documentation: Documentation<17>. 
* Tests: Tests<19>. 
* Build: Build<17>. 
* Windows: Windows<20>. 
* macOS: macOS<18>. 
* IDLE: IDLE<16>. 
* Tools/Demos: Tools/Demos<7>. 
* C API: C API<12>. 

Python 3.9.0 alpha 4

* Security: Security<16>. 
* Core and Builtins: Core and Builtins<26>. 
* Library: Library<28>. 
* Documentation: Documentation<18>. 
* Tests: Tests<20>. 
* Build: Build<18>. 
* Windows: Windows<21>. 
* IDLE: IDLE<17>. 
* C API: C API<13>. 

Python 3.9.0 alpha 3

* Core and Builtins: Core and Builtins<27>. 
* Library: Library<29>. 
* Documentation: Documentation<19>. 
* Build: Build<19>. 
* IDLE: IDLE<18>. 
* C API: C API<14>. 

Python 3.9.0 alpha 2

* Security: Security<17>. 
* Core and Builtins: Core and Builtins<28>. 
* Library: Library<30>. 
* Documentation: Documentation<20>. 
* Tests: Tests<21>. 
* Build: Build<20>. 
* Windows: Windows<22>. 
* macOS: macOS<19>. 
* IDLE: IDLE<19>. 
* C API: C API<15>. 

Python 3.9.0 alpha 1

* Security: Security<18>. 
* Core and Builtins: Core and Builtins<29>. 
* Library: Library<31>. 
* Documentation: Documentation<21>. 
* Tests: Tests<22>. 
* Build: Build<21>. 
* Windows: Windows<23>. 
* macOS: macOS<20>. 
* IDLE: IDLE<20>. 
* Tools/Demos: Tools/Demos<8>. 
* C API: C API<16>. 

Python 3.8.0 beta 1

* Security: Security<19>. 
* Core and Builtins: Core and Builtins<30>. 
* Library: Library<32>. 
* Documentation: Documentation<22>. 
* Tests: Tests<23>. 
* Build: Build<22>. 
* Windows: Windows<24>. 
* macOS: macOS<21>. 
* IDLE: IDLE<21>. 
* Tools/Demos: Tools/Demos<9>. 
* C API: C API<17>. 

Python 3.8.0 alpha 4

* Security: Security<20>. 
* Core and Builtins: Core and Builtins<31>. 
* Library: Library<33>. 
* Documentation: Documentation<23>. 
* Tests: Tests<24>. 
* Build: Build<23>. 
* Windows: Windows<25>. 
* macOS: macOS<22>. 
* IDLE: IDLE<22>. 
* Tools/Demos: Tools/Demos<10>. 
* C API: C API<18>. 

Python 3.8.0 alpha 3

* Security: Security<21>. 
* Core and Builtins: Core and Builtins<32>. 
* Library: Library<34>. 
* Documentation: Documentation<24>. 
* Tests: Tests<25>. 
* Build: Build<24>. 
* Windows: Windows<26>. 
* IDLE: IDLE<23>. 
* Tools/Demos: Tools/Demos<11>. 
* C API: C API<19>. 

Python 3.8.0 alpha 2

* Core and Builtins: Core and Builtins<33>. 
* Library: Library<35>. 
* Documentation: Documentation<25>. 
* Tests: Tests<26>. 
* Windows: Windows<27>. 
* IDLE: IDLE<24>. 

Python 3.8.0 alpha 1

* Security: Security<22>. 
* Core and Builtins: Core and Builtins<34>. 
* Library: Library<36>. 
* Documentation: Documentation<26>. 
* Tests: Tests<27>. 
* Build: Build<25>. 
* Windows: Windows<28>. 
* macOS: macOS<23>. 
* IDLE: IDLE<25>. 
* Tools/Demos: Tools/Demos<12>. 
* C API: C API<20>. 

Python 3.7.0 final

* Library: Library<37>. 
* C API: C API<21>. 

Python 3.7.0 release candidate 1

* Core and Builtins: Core and Builtins<35>. 
* Library: Library<38>. 
* Documentation: Documentation<27>. 
* Build: Build<26>. 
* Windows: Windows<29>. 
* IDLE: IDLE<26>. 

Python 3.7.0 beta 5

* Core and Builtins: Core and Builtins<36>. 
* Library: Library<39>. 
* Documentation: Documentation<28>. 
* Tests: Tests<28>. 
* Build: Build<27>. 
* macOS: macOS<24>. 
* IDLE: IDLE<27>. 

Python 3.7.0 beta 4

* Core and Builtins: Core and Builtins<37>. 
* Library: Library<40>. 
* Documentation: Documentation<29>. 
* Tests: Tests<29>. 
* Build: Build<28>. 
* Windows: Windows<30>. 
* macOS: macOS<25>. 
* IDLE: IDLE<28>. 
* Tools/Demos: Tools/Demos<13>. 

Python 3.7.0 beta 3

* Security: Security<23>. 
* Core and Builtins: Core and Builtins<38>. 
* Library: Library<41>. 
* Documentation: Documentation<30>. 
* Tests: Tests<30>. 
* Build: Build<29>. 
* Windows: Windows<31>. 
* macOS: macOS<26>. 
* IDLE: IDLE<29>. 
* Tools/Demos: Tools/Demos<14>. 
* C API: C API<22>. 

Python 3.7.0 beta 2

* Security: Security<24>. 
* Core and Builtins: Core and Builtins<39>. 
* Library: Library<42>. 
* Documentation: Documentation<31>. 
* Tests: Tests<31>. 
* Build: Build<30>. 
* Windows: Windows<32>. 
* macOS: macOS<27>. 
* IDLE: IDLE<30>. 
* Tools/Demos: Tools/Demos<15>. 

Python 3.7.0 beta 1

* Core and Builtins: Core and Builtins<40>. 
* Library: Library<43>. 
* Documentation: Documentation<32>. 
* Tests: Tests<32>. 
* Build: Build<31>. 
* Windows: Windows<33>. 
* macOS: macOS<28>. 
* C API: C API<23>. 

Python 3.7.0 alpha 4

* Core and Builtins: Core and Builtins<41>. 
* Library: Library<44>. 
* Documentation: Documentation<33>. 
* Tests: Tests<33>. 
* Windows: Windows<34>. 
* Tools/Demos: Tools/Demos<16>. 
* C API: C API<24>. 

Python 3.7.0 alpha 3

* Core and Builtins: Core and Builtins<42>. 
* Library: Library<45>. 
* Documentation: Documentation<34>. 
* Tests: Tests<34>. 
* Build: Build<32>. 
* Windows: Windows<35>. 
* macOS: macOS<29>. 
* IDLE: IDLE<31>. 
* Tools/Demos: Tools/Demos<17>. 
* C API: C API<25>. 

Python 3.7.0 alpha 2

* Core and Builtins: Core and Builtins<43>. 
* Library: Library<46>. 
* Documentation: Documentation<35>. 
* Build: Build<33>. 
* IDLE: IDLE<32>. 
* C API: C API<26>. 

Python 3.7.0 alpha 1

* Security: Security<25>. 
* Core and Builtins: Core and Builtins<44>. 
* Library: Library<47>. 
* Documentation: Documentation<36>. 
* Tests: Tests<35>. 
* Build: Build<34>. 
* Windows: Windows<36>. 
* IDLE: IDLE<33>. 
* Tools/Demos: Tools/Demos<18>. 
* C API: C API<27>. 

Python 3.6.6 release candidate 1

* Core and Builtins: Core and Builtins<45>. 
* Library: Library<48>. 
* Documentation: Documentation<37>. 
* Tests: Tests<36>. 
* Build: Build<35>. 
* Windows: Windows<37>. 
* macOS: macOS<30>. 
* IDLE: IDLE<34>. 
* Tools/Demos: Tools/Demos<19>. 
* C API: C API<28>. 

Python 3.6.5 final

* Tests: Tests<37>. 
* Build: Build<36>. 

Python 3.6.5 release candidate 1

* Security: Security<26>. 
* Core and Builtins: Core and Builtins<46>. 
* Library: Library<49>. 
* Documentation: Documentation<38>. 
* Tests: Tests<38>. 
* Build: Build<37>. 
* Windows: Windows<38>. 
* macOS: macOS<31>. 
* IDLE: IDLE<35>. 
* Tools/Demos: Tools/Demos<20>. 
* C API: C API<29>. 

Python 3.6.4 release candidate 1

* Core and Builtins: Core and Builtins<47>. 
* Library: Library<50>. 
* Documentation: Documentation<39>. 
* Tests: Tests<39>. 
* Build: Build<38>. 
* Windows: Windows<39>. 
* macOS: macOS<32>. 
* IDLE: IDLE<36>. 
* Tools/Demos: Tools/Demos<21>. 
* C API: C API<30>. 

Python 3.6.3 final

* Library: Library<51>. 
* Build: Build<39>. 

Python 3.6.3 release candidate 1

* Security: Security<27>. 
* Core and Builtins: Core and Builtins<48>. 
* Library: Library<52>. 
* Documentation: Documentation<40>. 
* Tests: Tests<40>. 
* Build: Build<40>. 
* Windows: Windows<40>. 
* IDLE: IDLE<37>. 
* Tools/Demos: Tools/Demos<22>. 

Python 3.6.2 release candidate 2

* Security: Security<28>. 

Python 3.6.2 release candidate 1

* Security: Security<29>. 
* Core and Builtins: Core and Builtins<49>. 
* Library: Library<53>. 
* IDLE: IDLE<38>. 
* C API: C API<31>. 
* Build: Build<41>. 
* Documentation: Documentation<41>. 
* Tools/Demos: Tools/Demos<23>. 
* Tests: Tests<41>. 
* Windows: Windows<41>. 

Python 3.6.1 final

* Core and Builtins: Core and Builtins<50>. 
* Build: Build<42>. 

Python 3.6.1 release candidate 1

* Core and Builtins: Core and Builtins<51>. 
* Library: Library<54>. 
* IDLE: IDLE<39>. 
* Windows: Windows<42>. 
* C API: C API<32>. 
* Documentation: Documentation<42>. 
* Tests: Tests<42>. 
* Build: Build<43>. 

Python 3.6.0 release candidate 2

* Core and Builtins: Core and Builtins<52>. 
* Tools/Demos: Tools/Demos<24>. 
* Windows: Windows<43>. 
* Build: Build<44>. 

Python 3.6.0 release candidate 1

* Core and Builtins: Core and Builtins<53>. 
* Library: Library<55>. 
* C API: C API<33>. 
* Documentation: Documentation<43>. 
* Tools/Demos: Tools/Demos<25>. 

Python 3.6.0 beta 4

* Core and Builtins: Core and Builtins<54>. 
* Library: Library<56>. 
* Documentation: Documentation<44>. 
* Tests: Tests<43>. 
* Build: Build<45>. 

Python 3.6.0 beta 3

* Core and Builtins: Core and Builtins<55>. 
* Library: Library<57>. 
* Windows: Windows<44>. 
* Build: Build<46>. 
* Tests: Tests<44>. 

Python 3.6.0 beta 2

* Core and Builtins: Core and Builtins<56>. 
* Library: Library<58>. 
* Windows: Windows<45>. 
* C API: C API<34>. 
* Build: Build<47>. 
* Tests: Tests<45>. 

Python 3.6.0 beta 1

* Core and Builtins: Core and Builtins<57>. 
* Library: Library<59>. 
* IDLE: IDLE<40>. 
* C API: C API<35>. 
* Tests: Tests<46>. 
* Build: Build<48>. 
* Tools/Demos: Tools/Demos<26>. 
* Windows: Windows<46>. 

Python 3.6.0 alpha 4

* Core and Builtins: Core and Builtins<58>. 
* Library: Library<60>. 
* IDLE: IDLE<41>. 
* Tests: Tests<47>. 
* Windows: Windows<47>. 
* Build: Build<49>. 

Python 3.6.0 alpha 3

* Security: Security<30>. 
* Core and Builtins: Core and Builtins<59>. 
* Library: Library<61>. 
* IDLE: IDLE<42>. 
* C API: C API<36>. 
* Build: Build<50>. 
* Tools/Demos: Tools/Demos<27>. 
* Documentation: Documentation<45>. 
* Tests: Tests<48>. 

Python 3.6.0 alpha 2

* Security: Security<31>. 
* Core and Builtins: Core and Builtins<60>. 
* Library: Library<62>. 
* IDLE: IDLE<43>. 
* Documentation: Documentation<46>. 
* Tests: Tests<49>. 
* Windows: Windows<48>. 
* Build: Build<51>. 
* C API: C API<37>. 
* Tools/Demos: Tools/Demos<28>. 

Python 3.6.0 alpha 1

* Security: Security<32>. 
* Core and Builtins: Core and Builtins<61>. 
* Library: Library<63>. 
* IDLE: IDLE<44>. 
* Documentation: Documentation<47>. 
* Tests: Tests<50>. 
* Build: Build<52>. 
* Windows: Windows<49>. 
* Tools/Demos: Tools/Demos<29>. 
* C API: C API<38>. 

Python 3.5.5 release candidate 1

* Security: Security<33>. 
* Core and Builtins: Core and Builtins<62>. 
* Library: Library<64>. 

Python 3.5.4 final

* Library: Library<65>. 

Python 3.5.4 release candidate 1

* Security: Security<34>. 
* Core and Builtins: Core and Builtins<63>. 
* Library: Library<66>. 
* Documentation: Documentation<48>. 
* Tests: Tests<51>. 
* Build: Build<53>. 
* Windows: Windows<50>. 
* C API: C API<39>. 

Python 3.5.3 release candidate 1

* Security: Security<35>. 
* Core and Builtins: Core and Builtins<64>. 
* Library: Library<67>. 
* IDLE: IDLE<45>. 
* C API: C API<40>. 
* Documentation: Documentation<49>. 
* Tests: Tests<52>. 
* Tools/Demos: Tools/Demos<30>. 
* Windows: Windows<51>. 
* Build: Build<54>. 

Python 3.5.2 final

* Core and Builtins: Core and Builtins<65>. 
* Tests: Tests<53>. 
* IDLE: IDLE<46>. 

Python 3.5.2 release candidate 1

* Security: Security<36>. 
* Core and Builtins: Core and Builtins<66>. 
* Library: Library<68>. 
* IDLE: IDLE<47>. 
* Documentation: Documentation<50>. 
* Tests: Tests<54>. 
* Build: Build<55>. 
* Windows: Windows<52>. 
* Tools/Demos: Tools/Demos<31>. 

Python 3.5.1 final

* Core and Builtins: Core and Builtins<67>. 
* Windows: Windows<53>. 

Python 3.5.1 release candidate 1

* Core and Builtins: Core and Builtins<68>. 
* Library: Library<69>. 
* IDLE: IDLE<48>. 
* Documentation: Documentation<51>. 
* Tests: Tests<55>. 
* Build: Build<56>. 
* Windows: Windows<54>. 
* Tools/Demos: Tools/Demos<32>. 

Python 3.5.0 final

* Build: Build<57>. 

Python 3.5.0 release candidate 4

* Library: Library<70>. 
* Build: Build<58>. 

Python 3.5.0 release candidate 3

* Core and Builtins: Core and Builtins<69>. 
* Library: Library<71>. 

Python 3.5.0 release candidate 2

* Core and Builtins: Core and Builtins<70>. 
* Library: Library<72>. 

Python 3.5.0 release candidate 1

* Core and Builtins: Core and Builtins<71>. 
* Library: Library<73>. 
* IDLE: IDLE<49>. 
* Documentation: Documentation<52>. 
* Tests: Tests<56>. 

Python 3.5.0 beta 4

* Core and Builtins: Core and Builtins<72>. 
* Library: Library<74>. 
* Build: Build<59>. 

Python 3.5.0 beta 3

* Core and Builtins: Core and Builtins<73>. 
* Library: Library<75>. 
* Tests: Tests<57>. 
* Documentation: Documentation<53>. 
* Build: Build<60>. 

Python 3.5.0 beta 2

* Core and Builtins: Core and Builtins<74>. 
* Library: Library<76>. 

Python 3.5.0 beta 1

* Core and Builtins: Core and Builtins<75>. 
* Library: Library<77>. 
* IDLE: IDLE<50>. 
* Tests: Tests<58>. 
* Documentation: Documentation<54>. 
* Tools/Demos: Tools/Demos<33>. 

Python 3.5.0 alpha 4

* Core and Builtins: Core and Builtins<76>. 
* Library: Library<78>. 
* Build: Build<61>. 
* Tests: Tests<59>. 
* Tools/Demos: Tools/Demos<34>. 
* C API: C API<41>. 

Python 3.5.0 alpha 3

* Core and Builtins: Core and Builtins<77>. 
* Library: Library<79>. 
* Build: Build<62>. 
* Tests: Tests<60>. 
* Tools/Demos: Tools/Demos<35>. 

Python 3.5.0 alpha 2

* Core and Builtins: Core and Builtins<78>. 
* Library: Library<80>. 
* Build: Build<63>. 
* C API: C API<42>. 
* Windows: Windows<55>. 

Python 3.5.0 alpha 1

* Core and Builtins: Core and Builtins<79>. 
* Library: Library<81>. 
* IDLE: IDLE<51>. 
* Build: Build<64>. 
* C API: C API<43>. 
* Documentation: Documentation<55>. 
* Tests: Tests<61>. 
* Tools/Demos: Tools/Demos<36>. 
* Windows: Windows<56>. 

Python 教程

* 课前甜点:: 
* Python 解释器:: 
* Python 速览:: 
* 其他流程控制工具:: 
* 数据结构:: 
* 模块:: 
* 输入与输出:: 
* 错误和异常:: 
* 类:: 
* 标准库简介:: 
* 标准库简介 —— 第二部分:: 
* 虚拟环境和包:: 
* 接下来？:: 
* 交互式编辑和编辑历史:: 
* 浮点算术：争议和限制:: 
* 附录:: 

Python 解释器

* 调用解释器:: 
* 解释器的运行环境:: 

调用解释器

* 传入参数:: 
* 交互模式:: 

解释器的运行环境

* 源文件的字符编码:: 

Python 速览

* Python 用作计算器:: 
* 走向编程的第一步:: 

Python 用作计算器

* 数字:: 
* 字符串:: 
* 列表:: 

其他流程控制工具

* if 语句:: 
* for 语句:: 
* range() 函数: range 函数. 
* 循环中的 break、continue 语句及 else 子句:: 
* pass 语句:: 
* 定义函数:: 
* 函数定义详解:: 
* 小插曲：编码风格:: 

函数定义详解

* 默认值参数:: 
* 关键字参数:: 
* 特殊参数:: 
* 任意实参列表:: 
* 解包实参列表:: 
* Lambda 表达式:: 
* 文档字符串:: 
* 函数注解:: 

特殊参数

* 位置或关键字参数:: 
* 仅位置参数:: 
* 仅限关键字参数:: 
* 函数示例:: 
* 小结:: 

数据结构

* 列表详解:: 
* del 语句:: 
* 元组和序列:: 
* 集合:: 
* 字典:: 
* 循环的技巧:: 
* 深入条件控制:: 
* 序列和其他类型的比较:: 

列表详解

* 用列表实现堆栈:: 
* 用列表实现队列:: 
* 列表推导式: 列表推导式<2>. 
* 嵌套的列表推导式:: 

模块

* 模块详解:: 
* 标准模块:: 
* dir() 函数: dir 函数. 
* 包:: 

模块详解

* 以脚本方式执行模块:: 
* 模块搜索路径:: 
* “已编译的” Python 文件:: 

包

* 从包中导入 *:: 
* 子包参考:: 
* 多目录中的包:: 

输入与输出

* 更复杂的输出格式:: 
* 读写文件:: 

更复杂的输出格式

* 格式化字符串字面值:: 
* 字符串 format() 方法: 字符串 format 方法. 
* 手动格式化字符串:: 
* 旧式字符串格式化方法:: 

读写文件

* 文件对象的方法:: 
* 使用 json 保存结构化数据:: 

错误和异常

* 句法错误:: 
* 异常:: 
* 处理异常:: 
* 触发异常:: 
* 异常链:: 
* 用户自定义异常:: 
* 定义清理操作:: 
* 预定义的清理操作:: 

类

* 名称和对象:: 
* Python 作用域和命名空间:: 
* 初探类:: 
* 补充说明:: 
* 继承:: 
* 私有变量:: 
* 杂项说明:: 
* 迭代器:: 
* 生成器:: 
* 生成器表达式:: 

Python 作用域和命名空间

* 作用域和命名空间示例:: 

初探类

* 类定义语法:: 
* 类对象:: 
* 实例对象:: 
* 方法对象:: 
* 类和实例变量:: 

继承

* 多重继承:: 

标准库简介

* 操作系统接口:: 
* 文件通配符:: 
* 命令行参数:: 
* 错误输出重定向和程序终止:: 
* 字符串模式匹配:: 
* 数学:: 
* 互联网访问:: 
* 日期和时间:: 
* 数据压缩:: 
* 性能测量:: 
* 质量控制:: 
* 自带电池:: 

标准库简介 —— 第二部分

* 格式化输出:: 
* 模板:: 
* 使用二进制数据记录格式:: 
* 多线程: 多线程<2>. 
* 日志:: 
* 弱引用:: 
* 用于操作列表的工具:: 
* 十进制浮点运算:: 

虚拟环境和包

* 概述: 概述<4>. 
* 创建虚拟环境:: 
* 使用pip管理包:: 

交互式编辑和编辑历史

* Tab 补全和编辑历史:: 
* 默认交互式解释器的替代品:: 

浮点算术：争议和限制

* 表示性错误:: 

附录

* 交互模式: 交互模式<2>. 

交互模式

* 错误处理:: 
* 可执行的Python脚本:: 
* 交互式启动文件:: 
* 定制模块:: 

安装和使用 Python

* 命令行与环境:: 
* 在Unix平台中使用Python:: 
* 在Windows上使用 Python:: 
* 在 Mac 上使用 Python:: 
* 编辑器和集成开发环境:: 

命令行与环境

* 命令行:: 
* 环境变量:: 

命令行

* 接口选项:: 
* 通用选项:: 
* 其他选项:: 
* 不应当使用的选项:: 

环境变量

* 调试模式变量:: 

在Unix平台中使用Python

* 获取最新版本的Python:: 
* 构建Python:: 
* 与Python相关的路径和文件:: 
* 杂项:: 

获取最新版本的Python

* 在Linux中:: 
* 在FreeBSD和OpenBSD上:: 
* 在OpenSolaris系统上:: 

在Windows上使用 Python

* 完整安装程序:: 
* Microsoft Store包:: 
* nuget.org 安装包: nuget org 安装包. 
* 可嵌入的包:: 
* 替代捆绑包:: 
* 配置Python:: 
* UTF-8 模式:: 
* 适用于Windows的Python启动器:: 
* 查找模块:: 
* 附加模块:: 
* 在Windows上编译Python:: 
* 其他平台:: 

完整安装程序

* 安装步骤:: 
* 删除 MAX_PATH 限制:: 
* 无UI 安装:: 
* 免下载安装:: 
* 修改安装:: 

Microsoft Store包

* 已知的问题:: 

可嵌入的包

* Python应用程序:: 
* 嵌入Python:: 

配置Python

* 附录：设置环境变量:: 
* 查找Python可执行文件:: 

适用于Windows的Python启动器

* 入门:: 
* Shebang Lines:: 
* shebang lines 的参数:: 
* 自定义:: 
* 诊断:: 

入门

* 从命令行:: 
* 从虚拟环境:: 
* 从脚本:: 
* 从文件关联:: 

自定义

* 通过INI文件自定义:: 
* 自定义默认的Python版本:: 

附加模块

* PyWin32:: 
* cx_Freeze:: 

在 Mac 上使用 Python

* 获取和安装 MacPython:: 
* IDE:: 
* 安装额外的 Python 包:: 
* Mac 上的图形界面编程:: 
* 在 Mac 上分发 Python 应用程序:: 
* 其他资源:: 

获取和安装 MacPython

* 如何运行 Python 脚本:: 
* 运行有图形界面的脚本:: 
* 配置:: 

Python 语言参考手册

* 概述: 概述<5>. 
* 词法分析:: 
* 数据模型:: 
* 执行模型:: 
* 导入系统:: 
* 表达式:: 
* 简单语句:: 
* 复合语句:: 
* 顶级组件:: 
* 完整的语法规范:: 

概述

* 其他实现:: 
* 标注:: 

词法分析

* 行结构:: 
* 其他形符:: 
* 标识符和关键字:: 
* 字面值:: 
* 运算符:: 
* 分隔符:: 

行结构

* 逻辑行:: 
* 物理行:: 
* 注释:: 
* 编码声明:: 
* 显式拼接行:: 
* 隐式拼接行:: 
* 空白行:: 
* 缩进:: 
* 形符间的空白字符:: 

标识符和关键字

* 关键字:: 
* 保留的标识符类:: 

字面值

* 字符串与字节串字面值:: 
* 字符串字面值合并:: 
* 格式字符串字面值:: 
* 数值字面值:: 
* 整数字面值:: 
* 浮点数字面值:: 
* 虚数字面值:: 

数据模型

* 对象、值与类型:: 
* 标准类型层级结构:: 
* 特殊方法名称:: 
* 协程:: 

特殊方法名称

* 基本定制:: 
* 自定义属性访问:: 
* 自定义类创建:: 
* 自定义实例及子类检查:: 
* 模拟泛型类型:: 
* 模拟可调用对象:: 
* 模拟容器类型:: 
* 模拟数字类型:: 
* with 语句上下文管理器:: 
* 特殊方法查找:: 

自定义属性访问

* 自定义模块属性访问:: 
* 实现描述器:: 
* 发起调用描述器:: 
* __slots__:: 

__slots__

* 使用 __slots__ 的注意事项:: 

自定义类创建

* 元类:: 
* 解析 MRO 条目:: 
* 确定适当的元类:: 
* 准备类命名空间:: 
* 执行类主体:: 
* 创建类对象:: 
* 元类的作用:: 

模拟泛型类型

* __class_getitem__ 的目的:: 
* __class_getitem__ 与 __getitem__:: 

协程

* 可等待对象:: 
* 协程对象:: 
* 异步迭代器:: 
* 异步上下文管理器:: 

执行模型

* 程序的结构:: 
* 命名与绑定:: 
* 异常: 异常<2>. 

命名与绑定

* 名称的绑定:: 
* 名称的解析:: 
* 内置命名空间和受限的执行:: 
* 与动态特性的交互:: 

导入系统

* importlib: importlib<8>. 
* 包: 包<2>. 
* 搜索:: 
* 加载:: 
* 基于路径的查找器:: 
* 替换标准导入系统:: 
* 包相对导入:: 
* 有关 __main__ 的特殊事项:: 
* 开放问题项:: 
* 参考文献:: 

包

* 常规包:: 
* 命名空间包:: 

搜索

* 模块缓存:: 
* 查找器和加载器:: 
* 导入钩子:: 
* 元路径:: 

加载

* 加载器:: 
* 子模块:: 
* 模块规格说明:: 
* 导入相关的模块属性:: 
* module.__path__: module __path__. 
* 模块的 repr:: 
* 已缓存字节码的失效:: 

基于路径的查找器

* 路径条目查找器:: 
* 路径条目查找器协议:: 

有关 __main__ 的特殊事项

* __main__.__spec__: __main__ __spec__. 

表达式

* 算术转换:: 
* 原子:: 
* 原型:: 
* await 表达式:: 
* 幂运算符:: 
* 一元算术和位运算:: 
* 二元算术运算符:: 
* 移位运算:: 
* 二元位运算:: 
* 比较运算:: 
* 布尔运算:: 
* 赋值表达式: 赋值表达式<2>. 
* 条件表达式:: 
* lambda 表达式:: 
* 表达式列表:: 
* 求值顺序:: 
* 运算符优先级:: 

原子

* 标识符（名称）:: 
* 字面值: 字面值<2>. 
* 带圆括号的形式:: 
* 列表、集合与字典的显示:: 
* 列表显示:: 
* 集合显示:: 
* 字典显示:: 
* 生成器表达式: 生成器表达式<2>. 
* yield 表达式:: 

yield 表达式

* 生成器-迭代器的方法:: 
* 示例:: 
* 异步生成器函数:: 
* 异步生成器-迭代器方法:: 

原型

* 属性引用:: 
* 抽取:: 
* 切片:: 
* 调用:: 

比较运算

* 值比较:: 
* 成员检测运算:: 
* 标识号比较:: 

简单语句

* 表达式语句:: 
* 赋值语句:: 
* assert 语句:: 
* pass 语句: pass 语句<2>. 
* del 语句: del 语句<2>. 
* return 语句:: 
* yield 语句:: 
* raise 语句:: 
* break 语句:: 
* continue 语句:: 
* import 语句:: 
* global 语句:: 
* nonlocal 语句:: 

赋值语句

* 增强赋值语句:: 
* 带标注的赋值语句:: 

import 语句

* future 语句:: 

复合语句

* if 语句: if 语句<2>. 
* while 语句:: 
* for 语句: for 语句<2>. 
* try 语句:: 
* with 语句:: 
* 函数定义:: 
* 类定义:: 
* 协程: 协程<2>. 

协程

* 协程函数定义:: 
* async for 语句:: 
* async with 语句:: 

顶级组件

* 完整的 Python 程序:: 
* 文件输入:: 
* 交互式输入:: 
* 表达式输入:: 

Python 标准库

* 概述: 概述<6>. 
* 内置函数:: 
* 内置常量:: 
* 内置类型:: 
* 内置异常:: 
* 文本处理服务:: 
* 二进制数据服务:: 
* 数据类型:: 
* 数字和数学模块:: 
* 函数式编程模块:: 
* 文件和目录访问:: 
* 数据持久化:: 
* 数据压缩和存档:: 
* 文件格式:: 
* 加密服务:: 
* 通用操作系统服务:: 
* 并发执行:: 
* 网络和进程间通信:: 
* 互联网数据处理:: 
* 结构化标记处理工具:: 
* 互联网协议和支持:: 
* 多媒体服务:: 
* 国际化:: 
* 程序框架:: 
* Tk图形用户界面(GUI): Tk图形用户界面 GUI. 
* 开发工具:: 
* 调试和分析:: 
* 软件打包和分发:: 
* Python运行时服务:: 
* 自定义 Python 解释器:: 
* 导入模块:: 
* Python 语言服务:: 
* 杂项服务:: 
* Windows系统相关模块:: 
* Unix 专有服务:: 
* 被取代的模块:: 
* Security Considerations:: 

概述

* 可用性注释:: 

内置常量

* 由 site 模块添加的常量:: 

内置类型

* 逻辑值检测:: 
* 布尔运算: 布尔运算 --- and or not. and, or, not
* 比较:: 
* 数字类型: 数字类型 --- int float complex. int, float, complex
* 迭代器类型:: 
* 序列类型: 序列类型 --- list tuple range. list, tuple, range
* 文本序列类型: 文本序列类型 --- str. str
* 二进制序列类型: 二进制序列类型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* 集合类型: 集合类型 --- set frozenset. set, frozenset
* 映射类型: 映射类型 --- dict. dict
* 上下文管理器类型:: 
* GenericAlias 类型:: 
* 其他内置类型:: 
* 特殊属性:: 
* Integer string conversion length limitation:: 

数字类型 --- int, float, complex

* 整数类型的按位运算:: 
* 整数类型的附加方法:: 
* 浮点类型的附加方法:: 
* 数字类型的哈希运算:: 

迭代器类型

* 生成器类型:: 

序列类型 --- list, tuple, range

* 通用序列操作:: 
* 不可变序列类型:: 
* 可变序列类型:: 
* 列表: 列表<2>. 
* 元组:: 
* range 对象:: 

文本序列类型 --- str

* 字符串的方法: 字符串的方法<2>. 
* printf 风格的字符串格式化:: 

二进制序列类型 --- bytes, bytearray, memoryview

* bytes 对象:: 
* bytearray 对象:: 
* bytes 和 bytearray 操作:: 
* printf 风格的字节串格式化:: 
* 内存视图:: 

映射类型 --- dict

* 字典视图对象:: 

GenericAlias 类型

* 标准泛型类:: 
* GenericAlias 对象的特殊属性:: 

其他内置类型

* 模块: 模块<2>. 
* 类与类实例:: 
* 函数:: 
* 方法:: 
* 代码对象:: 
* 类型对象:: 
* 空对象:: 
* 省略符对象:: 
* 未实现对象:: 
* 布尔值:: 
* 内部对象:: 

Integer string conversion length limitation

* Affected APIs:: 
* Configuring the limit:: 
* Recommended configuration:: 

内置异常

* 异常上下文:: 
* 从内置异常继承:: 
* 基类:: 
* 具体异常:: 
* 警告:: 
* 异常层次结构:: 

具体异常

* OS 异常:: 

文本处理服务

* string: string --- 常见的字符串操作. 常见的字符串操作
* re: re --- 正则表达式操作. 正则表达式操作
* difflib: difflib --- 计算差异的辅助工具. 计算差异的辅助工具
* textwrap: textwrap --- 文本自动换行与填充. 文本自动换行与填充
* unicodedata: unicodedata --- Unicode 数据库. Unicode 数据库
* stringprep: stringprep --- 因特网字符串预备. 因特网字符串预备
* readline: readline --- GNU readline 接口. GNU readline 接口
* rlcompleter: rlcompleter --- GNU readline 的补全函数. GNU readline 的补全函数

string --- 常见的字符串操作

* 字符串常量:: 
* 自定义字符串格式化:: 
* 格式字符串语法:: 
* 模板字符串:: 
* 辅助函数:: 

格式字符串语法

* 格式规格迷你语言:: 
* 格式示例:: 

re --- 正则表达式操作

* 正则表达式语法:: 
* 模块内容:: 
* 正则表达式对象 （正则对象）:: 
* 匹配对象:: 
* 正则表达式例子:: 

正则表达式例子

* 检查对子:: 
* 模拟 scanf(): 模拟 scanf. 
* search() vs. match(): search vs match. 
* 制作一个电话本:: 
* 文字整理:: 
* 查找所有副词:: 
* 查找所有的副词及其位置:: 
* 原始字符串标记:: 
* 写一个词法分析器:: 

difflib --- 计算差异的辅助工具

* SequenceMatcher 对象:: 
* SequenceMatcher 的示例:: 
* Differ 对象:: 
* Differ 示例:: 
* difflib 的命令行接口:: 

readline --- GNU readline 接口

* 初始化文件:: 
* 行缓冲区:: 
* 历史文件:: 
* 历史列表:: 
* 启动钩子:: 
* Completion:: 
* 示例: 示例<2>. 

rlcompleter --- GNU readline 的补全函数

* Completer 对象:: 

二进制数据服务

* struct: struct --- 将字节串解读为打包的二进制数据. 将字节串解读为打包的二进制数据
* codecs: codecs --- 编解码器注册和相关基类. 编解码器注册和相关基类

struct --- 将字节串解读为打包的二进制数据

* 函数和异常:: 
* 格式字符串:: 
* 类: 类<2>. 

格式字符串

* 字节顺序，大小和对齐方式:: 
* 格式字符:: 
* 示例: 示例<3>. 

codecs --- 编解码器注册和相关基类

* 编解码器基类:: 
* 编码格式与 Unicode:: 
* 标准编码:: 
* Python 专属的编码格式:: 
* encodings.idna: encodings idna --- 应用程序中的国际化域名. 应用程序中的国际化域名
* encodings.mbcs: encodings mbcs --- Windows ANSI代码页. Windows ANSI代码页
* encodings.utf_8_sig: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器. 带BOM签名的UTF-8编解码器

编解码器基类

* 错误处理方案:: 
* 无状态的编码和解码:: 
* 增量式的编码和解码:: 
* 流式的编码和解码:: 

增量式的编码和解码

* IncrementalEncoder 对象:: 
* IncrementalDecoder 对象:: 

流式的编码和解码

* StreamWriter 对象:: 
* StreamReader 对象:: 
* StreamReaderWriter 对象:: 
* StreamRecoder 对象:: 

Python 专属的编码格式

* 文字编码:: 
* 二进制转换:: 
* 文字转换:: 

数据类型

* datetime: datetime --- 基本日期和时间类型. 基本日期和时间类型
* zoneinfo: zoneinfo --- IANA 时区支持. IANA 时区支持
* calendar: calendar --- 日历相关函数. 日历相关函数
* collections: collections --- 容器数据类型. 容器数据类型
* collections.abc: collections abc --- 容器的抽象基类. 容器的抽象基类
* heapq: heapq --- 堆队列算法. 堆队列算法
* bisect: bisect --- 数组二分查找算法. 数组二分查找算法
* array: array --- 高效的数值数组. 高效的数值数组
* weakref: weakref --- 弱引用. 弱引用
* types: types --- 动态类型创建和内置类型名称. 动态类型创建和内置类型名称
* copy: copy --- 浅层 shallow 和深层 deep 复制操作. 浅层 (shallow) 和深层 (deep) 复制操作
* pprint: pprint --- 数据美化输出. 数据美化输出
* reprlib: reprlib --- 另一种 repr 实现. 另一种 repr() 实现
* enum: enum --- 对枚举的支持. 对枚举的支持
* graphlib: graphlib --- 操作类似图的结构的功能. 操作类似图的结构的功能

datetime --- 基本日期和时间类型

* 感知型对象和简单型对象:: 
* 常量:: 
* 有效的类型:: 
* timedelta 类对象:: 
* date 对象:: 
* datetime 对象:: 
* time 对象:: 
* tzinfo 对象:: 
* timezone 对象:: 
* strftime() 和 strptime() 的行为: strftime 和 strptime 的行为. 

有效的类型

* 通用的特征属性:: 
* 确定一个对象是感知型还是简单型:: 

timedelta 类对象

* class;timedelta 用法示例: class timedelta 用法示例. 

date 对象

* class;date 用法示例: class date 用法示例. 

datetime 对象

* 用法示例; datetime: 用法示例 datetime. 

time 对象

* 用法示例; time: 用法示例 time. 

strftime() 和 strptime() 的行为

* strftime() 和 strptime() Format Codes: strftime 和 strptime Format Codes. 
* 技术细节:: 

zoneinfo --- IANA 时区支持

* 使用 ZoneInfo:: 
* 数据源:: 
* ZoneInfo 类:: 
* 函数: 函数<2>. 
* 全局变量:: 
* 异常与警告:: 

数据源

* 配置数据源:: 

配置数据源

* 编译时配置:: 
* 环境配置:: 
* 运行时配置:: 

ZoneInfo 类

* 字符串表示:: 
* 封存序列化:: 

collections --- 容器数据类型

* ChainMap 对象:: 
* Counter 对象:: 
* deque 对象:: 
* defaultdict 对象:: 
* namedtuple() 命名元组的工厂函数: namedtuple 命名元组的工厂函数. 
* OrderedDict 对象:: 
* UserDict 对象:: 
* UserList 对象:: 
* UserString 对象:: 

ChainMap 对象

* ChainMap 例子和方法:: 

deque 对象

* deque 用法:: 

defaultdict 对象

* defaultdict 例子:: 

OrderedDict 对象

* OrderedDict 例子和用法:: 

collections.abc --- 容器的抽象基类

* 容器抽象基类:: 

heapq --- 堆队列算法

* 基本示例:: 
* 优先队列实现说明:: 
* 理论:: 

bisect --- 数组二分查找算法

* 搜索有序列表:: 
* 其他示例:: 

weakref --- 弱引用

* 弱引用对象:: 
* 示例: 示例<4>. 
* 终结器对象:: 
* 比较终结器与 __del__() 方法: 比较终结器与 __del__ 方法. 

types --- 动态类型创建和内置类型名称

* 动态类型创建:: 
* 标准解释器类型:: 
* 附加工具类和函数:: 
* 协程工具函数:: 

pprint --- 数据美化输出

* PrettyPrinter 对象:: 
* 示例: 示例<5>. 

reprlib --- 另一种 repr() 实现

* Repr 对象:: 
* 子类化 Repr 对象:: 

enum --- 对枚举的支持

* 模块内容: 模块内容<2>. 
* 创建 Enum:: 
* 枚举成员及其属性的编程访问:: 
* 重复的枚举成员和值:: 
* 确保唯一枚举值:: 
* 使用自动设定的值:: 
* 迭代:: 
* 比较: 比较<2>. 
* 允许的枚举成员和属性:: 
* 受限的 Enum 子类化:: 
* 封存:: 
* 功能性 API:: 
* 派生的枚举:: 
* 何时使用 __new__() 与 __init__(): 何时使用 __new__ 与 __init__. 
* 有趣的示例:: 
* 各种枚举有何区别？:: 

派生的枚举

* IntEnum:: 
* IntFlag:: 
* Flag:: 
* 其他事项:: 

有趣的示例

* 省略值:: 
* OrderedEnum:: 
* DuplicateFreeEnum:: 
* Planet:: 
* TimePeriod:: 

省略值

* 使用 auto:: 
* 使用 object:: 
* 使用描述性字符串:: 
* 使用自定义的 __new__(): 使用自定义的 __new__. 

各种枚举有何区别？

* 枚举类:: 
* 枚举成员（即实例）:: 
* 细节要点:: 

细节要点

* 支持的 __dunder__ 名称:: 
* 支持的 _sunder_ 名称:: 
* _Private__names:: 
* Enum 成员类型:: 
* Enum 类和成员的布尔值:: 
* 带有方法的 Enum 类:: 
* 组合 Flag 的成员:: 

graphlib --- 操作类似图的结构的功能

* 异常: 异常<3>. 

数字和数学模块

* numbers: numbers --- 数字的抽象基类. 数字的抽象基类
* math: math --- 数学函数. 数学函数
* cmath: cmath --- 关于复数的数学函数. 关于复数的数学函数
* decimal: decimal --- 十进制定点和浮点运算. 十进制定点和浮点运算
* fractions: fractions --- 分数. 分数
* random: random --- 生成伪随机数. 生成伪随机数
* statistics: statistics --- 数学统计函数. 数学统计函数

numbers --- 数字的抽象基类

* 数字的层次:: 
* 类型接口注释。:: 

类型接口注释。

* 加入更多数字的ABC:: 
* 实现算术运算:: 

math --- 数学函数

* 数论与表示函数:: 
* 幂函数与对数函数:: 
* 三角函数:: 
* 角度转换:: 
* 双曲函数:: 
* 特殊函数:: 
* 常数:: 

cmath --- 关于复数的数学函数

* 到极坐标和从极坐标的转换:: 
* 幂函数与对数函数: 幂函数与对数函数<2>. 
* 三角函数: 三角函数<2>. 
* 双曲函数: 双曲函数<2>. 
* 分类函数:: 
* 常数: 常数<2>. 

decimal --- 十进制定点和浮点运算

* 快速入门教程:: 
* Decimal 对象:: 
* 上下文对象:: 
* 常数: 常数<3>. 
* 舍入模式:: 
* 信号:: 
* 浮点数说明:: 
* 使用线程:: 
* 例程:: 
* Decimal 常见问题:: 

Decimal 对象

* 逻辑操作数:: 

浮点数说明

* 通过提升精度来解决舍入错误:: 
* 特殊的值:: 

random --- 生成伪随机数

* 簿记功能:: 
* 用于字节数据的函数:: 
* 整数用函数:: 
* 序列用函数:: 
* 实值分布:: 
* 替代生成器:: 
* 关于再现性的说明:: 
* 例子:: 
* 例程: 例程<2>. 

statistics --- 数学统计函数

* 平均值以及对中心位置的评估:: 
* 对分散程度的评估:: 
* 函数细节:: 
* 异常: 异常<4>. 
* NormalDist 对象:: 

NormalDist 对象

* NormalDist 示例和用法:: 

函数式编程模块

* itertools: itertools --- 为高效循环而创建迭代器的函数. 为高效循环而创建迭代器的函数
* functools: functools --- 高阶函数和可调用对象上的操作. 高阶函数和可调用对象上的操作
* operator: operator --- 标准运算符替代函数. 标准运算符替代函数

itertools --- 为高效循环而创建迭代器的函数

* Itertool函数:: 
* itertools 配方:: 

functools --- 高阶函数和可调用对象上的操作

* partial 对象:: 

operator --- 标准运算符替代函数

* 将运算符映射到函数:: 
* 原地运算符:: 

文件和目录访问

* pathlib: pathlib --- 面向对象的文件系统路径. 面向对象的文件系统路径
* os.path: os path --- 常用路径操作. 常用路径操作
* fileinput: fileinput --- 迭代来自多个输入流的行. 迭代来自多个输入流的行
* stat: stat --- 解析 stat 结果. 解析 stat() 结果
* filecmp: filecmp --- 文件及目录的比较. 文件及目录的比较
* tempfile: tempfile --- 生成临时文件和目录. 生成临时文件和目录
* glob: glob --- Unix 风格路径名模式扩展. Unix 风格路径名模式扩展
* fnmatch: fnmatch --- Unix 文件名模式匹配. Unix 文件名模式匹配
* linecache: linecache --- 随机读写文本行. 随机读写文本行
* shutil: shutil --- 高阶文件操作. 高阶文件操作

pathlib --- 面向对象的文件系统路径

* 基础使用:: 
* 纯路径:: 
* 具体路径:: 
* 对应的 os 模块的工具:: 

纯路径

* 通用性质:: 
* 运算符: 运算符<2>. 
* 访问个别部分:: 
* 方法和特征属性:: 

具体路径

* 方法: 方法<2>. 

filecmp --- 文件及目录的比较

* dircmp 类:: 

tempfile --- 生成临时文件和目录

* 示例: 示例<6>. 
* 已弃用的函数和变量:: 

shutil --- 高阶文件操作

* 目录和文件操作:: 
* 归档操作:: 
* 查询输出终端的尺寸:: 

目录和文件操作

* 依赖于具体平台的高效拷贝操作:: 
* copytree 示例:: 
* rmtree 示例:: 

归档操作

* 归档程序示例:: 
* 使用 base_dir 的归档程序示例:: 

数据持久化

* pickle: pickle --- Python 对象序列化. Python 对象序列化
* copyreg: copyreg --- 注册配合 pickle 模块使用的函数. 注册配合 pickle 模块使用的函数
* shelve: shelve --- Python 对象持久化. Python 对象持久化
* marshal: marshal --- 内部 Python 对象序列化. 内部 Python 对象序列化
* dbm: dbm --- Unix "数据库" 接口. Unix "数据库" 接口
* sqlite3: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块. SQLite 数据库 DB-API 2.0 接口模块

pickle --- Python 对象序列化

* 与其他 Python 模块间的关系:: 
* 数据流格式:: 
* 模块接口:: 
* 可以被封存/解封的对象:: 
* 封存类实例:: 
* 类型，函数和其他对象的自定义归约:: 
* 外部缓冲区:: 
* 限制全局变量:: 
* 性能: 性能<2>. 
* 示例: 示例<8>. 

与其他 Python 模块间的关系

* 与 marshal 间的关系:: 
* 与 json 模块的比较:: 

封存类实例

* 持久化外部对象:: 
* Dispatch 表:: 
* 处理有状态的对象:: 

外部缓冲区

* 提供方 API:: 
* 使用方 API:: 
* 示例: 示例<7>. 

copyreg --- 注册配合 pickle 模块使用的函数

* 示例: 示例<9>. 

shelve --- Python 对象持久化

* 限制:: 
* 示例: 示例<10>. 

dbm --- Unix "数据库" 接口

* dbm.gnu: dbm gnu --- GNU 对 dbm 的重解析. GNU 对 dbm 的重解析
* dbm.ndbm: dbm ndbm --- 基于 ndbm 的接口. 基于 ndbm 的接口
* dbm.dumb: dbm dumb --- 便携式 DBM 实现. 便携式 DBM 实现

sqlite3 --- SQLite 数据库 DB-API 2.0 接口模块

* 模块函数和常量:: 
* 连接对象（Connection）:: 
* Cursor 对象:: 
* 行对象:: 
* 异常: 异常<5>. 
* SQLite 与 Python 类型:: 
* 控制事务:: 
* 有效使用 sqlite3:: 

SQLite 与 Python 类型

* 概述: 概述<7>. 
* 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。:: 
* 将SQLite 值转换为自定义Python 类型:: 
* 默认适配器和转换器:: 

使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

* 让对象自行适配:: 
* 注册可调用的适配器:: 

有效使用 sqlite3

* 使用快捷方式:: 
* 通过名称而不是索引访问索引:: 
* 使用连接作为上下文管理器:: 

数据压缩和存档

* zlib: zlib --- 与 gzip 兼容的压缩. 与 gzip 兼容的压缩
* gzip: gzip --- 对 gzip 格式的支持. 对 gzip 格式的支持
* bz2: bz2 --- 对 bzip2 压缩算法的支持. 对 bzip2 压缩算法的支持
* lzma: lzma --- 用 LZMA 算法压缩. 用 LZMA 算法压缩
* zipfile: zipfile --- 使用ZIP存档. 使用ZIP存档
* tarfile: tarfile --- 读写tar归档文件. 读写tar归档文件

gzip --- 对 gzip 格式的支持

* 用法示例:: 
* 命令行界面:: 

命令行界面

* 命令行选项:: 

bz2 --- 对 bzip2 压缩算法的支持

* 文件压缩和解压:: 
* 增量压缩和解压:: 
* 一次性压缩或解压缩:: 
* 用法示例: 用法示例<2>. 

lzma --- 用 LZMA 算法压缩

* 读写压缩文件:: 
* 在内存中压缩和解压缩数据:: 
* 杂项: 杂项<2>. 
* 指定自定义的过滤器链:: 
* 示例: 示例<11>. 

zipfile --- 使用ZIP存档

* ZipFile 对象:: 
* Path 对象:: 
* PyZipFile 对象:: 
* ZipInfo 对象:: 
* 命令行界面: 命令行界面<2>. 
* 解压缩的障碍:: 

命令行界面

* 命令行选项: 命令行选项<2>. 

解压缩的障碍

* 由于文件本身:: 
* 文件系统限制:: 
* 资源限制:: 
* 中断:: 
* 提取的默认行为:: 

tarfile --- 读写tar归档文件

* TarFile 对象:: 
* TarInfo 对象:: 
* Extraction filters:: 
* 命令行界面: 命令行界面<3>. 
* 示例: 示例<12>. 
* 受支持的 tar 格式:: 
* Unicode 问题:: 

Extraction filters

* Default named filters:: 
* Filter errors:: 
* Hints for further verification:: 
* Supporting older Python versions:: 
* Stateful extraction filter example:: 

命令行界面

* 命令行选项: 命令行选项<3>. 

文件格式

* csv: csv --- CSV 文件读写. CSV 文件读写
* configparser: configparser --- 配置文件解析器. 配置文件解析器
* netrc: netrc --- netrc 文件处理. netrc 文件处理
* plistlib: plistlib --- 生成与解析 Apple plist 文件. 生成与解析 Apple .plist 文件

csv --- CSV 文件读写

* 模块内容: 模块内容<3>. 
* 变种与格式参数:: 
* Reader 对象:: 
* Writer 对象:: 
* 示例: 示例<13>. 

configparser --- 配置文件解析器

* 快速起步:: 
* 支持的数据类型:: 
* 回退值:: 
* 受支持的 INI 文件结构:: 
* 值的插值:: 
* 映射协议访问:: 
* 定制解析器行为:: 
* 旧式 API 示例:: 
* ConfigParser 对象:: 
* RawConfigParser 对象:: 
* 异常: 异常<6>. 

netrc --- netrc 文件处理

* netrc 对象:: 

plistlib --- 生成与解析 Apple .plist 文件

* 示例: 示例<14>. 

加密服务

* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 生成管理密码的安全随机数. 生成管理密码的安全随机数

hashlib --- 安全哈希与消息摘要

* 哈希算法:: 
* SHAKE 可变长度摘要:: 
* 密钥派生:: 
* BLAKE2:: 

BLAKE2

* 创建哈希对象:: 
* 常数: 常数<4>. 
* 示例: 示例<15>. 
* 开发人员:: 

示例

* 简单哈希:: 
* 使用不同的摘要大小:: 
* 密钥哈希:: 
* 随机哈希:: 
* 个性化:: 
* 树形模式:: 

secrets --- 生成管理密码的安全随机数

* 随机数:: 
* 生成 Token:: 
* 其他功能:: 
* 应用技巧与最佳实践:: 

生成 Token

* Token 应当使用多少个字节？:: 

通用操作系统服务

* os: os --- 多种操作系统接口. 多种操作系统接口
* io: io --- 处理流的核心工具. 处理流的核心工具
* time: time --- 时间的访问和转换. 时间的访问和转换
* argparse: argparse --- 命令行选项、参数和子命令解析器. 命令行选项、参数和子命令解析器
* getopt: getopt --- C 风格的命令行选项解析器. C 风格的命令行选项解析器
* logging: logging --- Python 的日志记录工具. Python 的日志记录工具
* logging.config: logging config --- 日志记录配置. 日志记录配置
* logging.handlers: logging handlers --- 日志处理程序. 日志处理程序
* getpass: getpass --- 便携式密码输入工具. 便携式密码输入工具
* curses: curses --- 终端字符单元显示的处理. 终端字符单元显示的处理
* curses.textpad: curses textpad --- 用于 curses 程序的文本输入控件. 用于 curses 程序的文本输入控件
* curses.ascii: curses ascii --- 用于 ASCII 字符的工具. 用于 ASCII 字符的工具
* curses.panel: curses panel --- curses 的面板栈扩展. curses 的面板栈扩展
* platform: platform --- 获取底层平台的标识数据. 获取底层平台的标识数据
* errno: errno --- 标准 errno 系统符号. 标准 errno 系统符号
* ctypes: ctypes --- Python 的外部函数库. Python 的外部函数库

os --- 多种操作系统接口

* 文件名，命令行参数，以及环境变量。:: 
* 进程参数:: 
* 创建文件对象:: 
* 文件描述符操作:: 
* 文件和目录:: 
* 进程管理:: 
* 调度器接口:: 
* 其他系统信息:: 
* 随机数: 随机数<2>. 

文件描述符操作

* 查询终端的尺寸:: 
* 文件描述符的继承:: 

文件和目录

* Linux 扩展属性:: 

io --- 处理流的核心工具

* 概述: 概述<8>. 
* 高阶模块接口:: 
* 类的层次结构:: 
* 性能: 性能<3>. 

概述

* 文本 I/O:: 
* 二进制 I/O:: 
* 原始 I/O:: 

类的层次结构

* I/O 基类:: 
* 原始文件 I/O:: 
* 缓冲流:: 
* 文本 I/O: 文本 I/O<2>. 

性能

* 二进制 I/O: 二进制 I/O<2>. 
* 文本 I/O: 文本 I/O<3>. 
* 多线程: 多线程<3>. 
* 可重入性:: 

time --- 时间的访问和转换

* 函数: 函数<3>. 
* Clock ID 常量:: 
* 时区常量:: 

argparse --- 命令行选项、参数和子命令解析器

* 示例: 示例<16>. 
* ArgumentParser 对象:: 
* add_argument() 方法: add_argument 方法. 
* parse_args() 方法: parse_args 方法. 
* 其它实用工具:: 
* 升级 optparse 代码:: 

示例

* 创建一个解析器:: 
* 添加参数:: 
* 解析参数:: 

ArgumentParser 对象

* prog:: 
* usage:: 
* description:: 
* epilog:: 
* parents:: 
* formatter_class:: 
* prefix_chars:: 
* fromfile_prefix_chars:: 
* argument_default:: 
* allow_abbrev:: 
* conflict_handler:: 
* add_help:: 
* exit_on_error:: 

add_argument() 方法

* name or flags:: 
* action:: 
* nargs:: 
* const:: 
* default:: 
* type:: 
* choices:: 
* required:: 
* help:: 
* metavar:: 
* dest:: 
* Action 类:: 

parse_args() 方法

* 选项值语法:: 
* 无效的参数:: 
* 包含 - 的参数:: 
* 参数缩写（前缀匹配）:: 
* 在 sys.argv 以外: 在 sys argv 以外. 
* 命名空间对象:: 

其它实用工具

* 子命令:: 
* FileType 对象:: 
* 参数组:: 
* 互斥:: 
* 解析器默认值:: 
* 打印帮助:: 
* 部分解析:: 
* 自定义文件解析:: 
* 退出方法:: 
* 混合解析:: 

logging --- Python 的日志记录工具

* 记录器对象:: 
* 日志级别:: 
* 处理器对象:: 
* 格式器对象:: 
* 过滤器对象:: 
* LogRecord 属性:: 
* LogRecord 属性: LogRecord 属性<2>. 
* LoggerAdapter 对象:: 
* 线程安全:: 
* 模块级函数:: 
* 模块级属性:: 
* 与警告模块集成:: 

logging.config --- 日志记录配置

* 配置函数:: 
* 安全考量:: 
* 配置字典架构:: 
* 配置文件格式:: 

配置字典架构

* 字典架构细节:: 
* 增量配置:: 
* 对象连接:: 
* 用户定义对象:: 
* 访问外部对象:: 
* 访问内部对象:: 
* 导入解析与定制导入器:: 

logging.handlers --- 日志处理程序

* StreamHandler:: 
* FileHandler:: 
* NullHandler:: 
* WatchedFileHandler:: 
* BaseRotatingHandler:: 
* RotatingFileHandler:: 
* TimedRotatingFileHandler:: 
* SocketHandler:: 
* DatagramHandler:: 
* SysLogHandler:: 
* NTEventLogHandler:: 
* SMTPHandler:: 
* MemoryHandler:: 
* HTTPHandler:: 
* QueueHandler:: 
* QueueListener:: 

curses --- 终端字符单元显示的处理

* 函数: 函数<4>. 
* Window 对象:: 
* 常量: 常量<2>. 

curses.textpad --- 用于 curses 程序的文本输入控件

* 文本框对象:: 

curses.panel --- curses 的面板栈扩展

* 函数: 函数<5>. 
* Panel 对象:: 

platform ---  获取底层平台的标识数据

* 跨平台:: 
* Java平台:: 
* Windows平台:: 
* macOS 平台:: 
* Unix 平台:: 

ctypes --- Python 的外部函数库

* ctypes 教程:: 
* ctypes 参考手册:: 

ctypes 教程

* 载入动态连接库:: 
* 操作导入的动态链接库中的函数:: 
* 调用函数:: 
* 基础数据类型:: 
* 调用函数，继续:: 
* 使用自定义的数据类型调用函数:: 
* 指定必选参数的类型(函数原型): 指定必选参数的类型 函数原型. 
* 返回类型:: 
* 传递指针（或以引用方式传递形参）:: 
* 结构体和联合:: 
* 结构体/联合字段对齐及字节顺序:: 
* 结构体和联合中的位域:: 
* 数组:: 
* 指针:: 
* 类型转换:: 
* 不完整类型:: 
* 回调函数:: 
* 访问 dll 的导出变量:: 
* 意外:: 
* 变长数据类型:: 

ctypes 参考手册

* 寻找动态链接库:: 
* 加载动态链接库:: 
* 外部函数:: 
* 函数原型:: 
* 工具函数:: 
* 数据类型: 数据类型<2>. 
* 基础数据类型: 基础数据类型<2>. 
* 结构化数据类型:: 
* 数组与指针:: 

并发执行

* threading: threading --- 基于线程的并行. 基于线程的并行
* multiprocessing: multiprocessing --- 基于进程的并行. 基于进程的并行
* multiprocessing.shared_memory: multiprocessing shared_memory --- 可从进程直接访问的共享内存. 可从进程直接访问的共享内存
* concurrent 包:: 
* concurrent.futures: concurrent futures --- 启动并行任务. 启动并行任务
* subprocess: subprocess --- 子进程管理. 子进程管理
* sched: sched --- 事件调度器. 事件调度器
* queue: queue --- 一个同步的队列类. 一个同步的队列类
* contextvars: contextvars --- 上下文变量. 上下文变量
* _thread: _thread --- 底层多线程 API. 底层多线程 API

threading --- 基于线程的并行

* 线程本地数据:: 
* 线程对象:: 
* 锁对象:: 
* 递归锁对象:: 
* 条件对象:: 
* 信号量对象:: 
* 事件对象:: 
* 定时器对象:: 
* 栅栏对象:: 
* 在 with 语句中使用锁、条件和信号量:: 

信号量对象

* Semaphore 例子:: 

multiprocessing --- 基于进程的并行

* 概述: 概述<9>. 
* 参考:: 
* 编程指导:: 
* 示例: 示例<17>. 

概述

* Process 类:: 
* 上下文和启动方法:: 
* 在进程之间交换对象:: 
* 进程间同步:: 
* 进程间共享状态:: 
* 使用工作进程:: 

参考

* Process 和异常:: 
* 管道和队列:: 
* 杂项: 杂项<3>. 
* 连接（Connection）对象:: 
* 同步原语:: 
* 共享 ctypes 对象:: 
* 管理器:: 
* 代理对象:: 
* 进程池:: 
* 监听器及客户端:: 
* 认证密码:: 
* 日志: 日志<2>. 
* multiprocessing.dummy 模块: multiprocessing dummy 模块. 

共享 ctypes 对象

* multiprocessing.sharedctypes 模块: multiprocessing sharedctypes 模块. 

管理器

* 自定义管理器:: 
* 使用远程管理器:: 

代理对象

* 清理:: 

监听器及客户端

* 地址格式:: 

编程指导

* 所有start方法:: 
* spawn 和 forkserver 启动方式:: 

concurrent.futures --- 启动并行任务

* Executor 对象:: 
* ThreadPoolExecutor:: 
* ProcessPoolExecutor:: 
* Future 对象:: 
* 模块函数:: 
* Exception 类:: 

ThreadPoolExecutor

* ThreadPoolExecutor 例子:: 

ProcessPoolExecutor

* ProcessPoolExecutor 例子:: 

subprocess --- 子进程管理

* 使用 subprocess 模块:: 
* 安全考量: 安全考量<2>. 
* Popen 对象:: 
* Windows Popen 助手:: 
* 较旧的高阶 API:: 
* 使用 subprocess 模块替换旧函数:: 
* 旧式的 Shell 发起函数:: 
* 注释: 注释<2>. 

使用 subprocess 模块

* 常用参数:: 
* Popen 构造函数:: 
* 异常: 异常<7>. 

Windows Popen 助手

* Windows 常数:: 

使用 subprocess 模块替换旧函数

* 替代 /bin/sh shell 命令替换:: 
* 替代 shell 管道:: 
* 替代 os.system(): 替代 os system. 
* 替代 os.spawn 函数族: 替代 os spawn 函数族. 
* 替代 os.popen()@comma{} os.popen2()@comma{} os.popen3(): 替代 os popen os popen2 os popen3. 
* 来自 popen2 模块的替代函数:: 

注释

* 在 Windows 上将参数列表转换为一个字符串:: 

sched --- 事件调度器

* 调度器对象:: 

queue --- 一个同步的队列类

* Queue对象:: 
* SimpleQueue 对象:: 

contextvars --- 上下文变量

* 上下文变量:: 
* 手动上下文管理:: 
* asyncio 支持:: 

网络和进程间通信

* asyncio: asyncio --- 异步 I/O. 异步 I/O
* socket: socket --- 底层网络接口. 底层网络接口
* ssl: ssl --- 套接字对象的 TLS/SSL 包装器. 套接字对象的 TLS/SSL 包装器
* select: select --- 等待 I/O 完成. 等待 I/O 完成
* selectors: selectors --- 高级 I/O 复用库. 高级 I/O 复用库
* signal: signal --- 设置异步事件处理程序. 设置异步事件处理程序
* mmap: mmap --- 内存映射文件支持. 内存映射文件支持

asyncio --- 异步 I/O

* 协程与任务:: 
* 流:: 
* 同步原语: 同步原语<2>. 
* 子进程:: 
* 队列集:: 
* 异常: 异常<9>. 
* 事件循环:: 
* Futures:: 
* 传输和协议:: 
* 策略:: 
* 平台支持:: 
* 高层级 API 索引:: 
* 低层级 API 索引:: 
* 用 asyncio 开发:: 

协程与任务

* 协程: 协程<3>. 
* 可等待对象: 可等待对象<2>. 
* 运行 asyncio 程序:: 
* 创建任务:: 
* 休眠:: 
* 并发运行任务:: 
* 屏蔽取消操作:: 
* 超时:: 
* 简单等待:: 
* 在线程中运行:: 
* 跨线程调度:: 
* 内省:: 
* Task 对象:: 
* 基于生成器的协程:: 

流

* StreamReader:: 
* StreamWriter:: 
* 示例: 示例<18>. 

示例

* 使用流的 TCP 回显客户端:: 
* 使用流的 TCP 回显服务器:: 
* 获取 HTTP 标头:: 
* 注册一个打开的套接字以等待使用流的数据:: 

同步原语

* Lock:: 
* Event:: 
* Condition:: 
* Semaphore:: 
* BoundedSemaphore:: 

子进程

* 创建子进程:: 
* 常数: 常数<5>. 
* 与子进程交互:: 

与子进程交互

* 子进程和线程:: 
* 示例: 示例<19>. 

队列集

* 队列:: 
* 优先级队列:: 
* 后进先出队列:: 
* 异常: 异常<8>. 
* 示例: 示例<20>. 

事件循环

* 事件循环方法集:: 
* 回调处理:: 
* Server 对象:: 
* 事件循环实现:: 
* 示例: 示例<21>. 

事件循环方法集

* 运行和停止循环:: 
* 安排回调:: 
* 调度延迟回调:: 
* 创建 Future 和 Task:: 
* 打开网络连接:: 
* 创建网络服务:: 
* 传输文件:: 
* TLS 升级:: 
* 监控文件描述符:: 
* 直接使用 socket 对象:: 
* DNS:: 
* 使用管道:: 
* Unix 信号:: 
* 在线程或者进程池中执行代码。:: 
* 错误处理API:: 
* 开启调试模式:: 
* 运行子进程:: 

示例

* call_soon() 的 Hello World 示例。: call_soon 的 Hello World 示例。. 
* 使用 call_later() 来展示当前的日期: 使用 call_later 来展示当前的日期. 
* 监控一个文件描述符的读事件:: 
* 为SIGINT和SIGTERM设置信号处理器:: 

Futures

* Future 函数:: 
* Future 对象: Future 对象<2>. 

传输和协议

* 传输:: 
* 协议:: 
* 示例: 示例<22>. 

传输

* 传输层级:: 
* 基础传输:: 
* 只读传输:: 
* 只写传输:: 
* 数据报传输:: 
* 子进程传输:: 

协议

* 基础协议:: 
* 基础协议: 基础协议<2>. 
* 流式协议:: 
* 缓冲流协议:: 
* 数据报协议:: 
* 子进程协议:: 

示例

* TCP 回显服务器:: 
* TCP 回显客户端:: 
* UDP 回显服务器:: 
* UDP 回显客户端:: 
* 链接已存在的套接字:: 
* loop.subprocess_exec() 与 SubprocessProtocol: loop subprocess_exec 与 SubprocessProtocol. 

策略

* 获取和设置策略:: 
* 策略对象:: 
* 进程监视器:: 
* 自定义策略:: 

平台支持

* 所有平台:: 
* Windows: Windows<57>. 
* macOS: macOS<33>. 

Windows

* Windows的子进程支持:: 

高层级 API 索引

* Tasks:: 
* 队列集: 队列集<2>. 
* 子进程集:: 
* 流: 流<2>. 
* 同步:: 
* 异常: 异常<10>. 

低层级 API 索引

* 获取事件循环:: 
* 事件循环方法集: 事件循环方法集<2>. 
* 传输: 传输<2>. 
* 协议: 协议<2>. 
* 事件循环策略:: 

用 asyncio 开发

* Debug 模式:: 
* 并发性和多线程:: 
* 运行阻塞的代码:: 
* 日志: 日志<3>. 
* 检测 never-awaited 协同程序:: 
* 检测就再也没异常:: 

socket --- 底层网络接口

* 套接字协议族:: 
* 模块内容: 模块内容<4>. 
* 套接字对象:: 
* 关于套接字超时的说明:: 
* 示例: 示例<23>. 

模块内容

* 异常: 异常<11>. 
* 常数: 常数<6>. 
* 函数: 函数<6>. 

函数

* 创建套接字:: 
* 其他功能: 其他功能<2>. 

关于套接字超时的说明

* 超时与 connect 方法:: 
* 超时与 accept 方法:: 

ssl --- 套接字对象的 TLS/SSL 包装器

* 方法、常量和异常处理:: 
* SSL 套接字:: 
* SSL 上下文:: 
* 证书:: 
* 示例: 示例<24>. 
* 关于非阻塞套接字的说明:: 
* 内存 BIO 支持: 内存 BIO 支持<2>. 
* SSL 会话:: 
* 安全考量: 安全考量<3>. 
* TLS 1.3: TLS 1 3. 
* LibreSSL 支持:: 

方法、常量和异常处理

* 套接字创建:: 
* 上下文创建:: 
* 异常: 异常<12>. 
* 随机生成:: 
* 证书处理:: 
* 常量: 常量<3>. 

证书

* 证书链:: 
* CA 证书:: 
* 合并的密钥和证书:: 
* 自签名证书:: 

示例

* 检测 SSL 支持:: 
* 客户端操作:: 
* 服务器端操作:: 

安全考量

* 最佳默认值:: 
* 手动设置:: 
* 多进程:: 

手动设置

* 验证证书:: 
* 协议版本:: 
* 密码选择:: 

select --- 等待 I/O 完成

* /dev/poll 轮询对象:: 
* 边缘触发和水平触发的轮询 (epoll) 对象: 边缘触发和水平触发的轮询 epoll 对象. 
* Poll 对象:: 
* Kqueue 对象:: 
* Kevent 对象:: 

selectors --- 高级 I/O 复用库

* 概述: 概述<10>. 
* 类: 类<3>. 
* 示例: 示例<25>. 

signal --- 设置异步事件处理程序

* 一般规则:: 
* 模块内容: 模块内容<5>. 
* 示例: 示例<26>. 
* 对于 SIGPIPE 的说明:: 
* 有关信号处理句柄和异常的注释:: 

一般规则

* 执行 Python 信号处理程序:: 
* 信号与线程:: 

mmap --- 内存映射文件支持

* MADV_* 常量:: 

互联网数据处理

* email: email --- 电子邮件与 MIME 处理包. 电子邮件与 MIME 处理包
* json: json --- JSON 编码和解码器. JSON 编码和解码器
* mailbox: mailbox --- 操作多种格式的邮箱. 操作多种格式的邮箱
* mimetypes: mimetypes --- 映射文件名到 MIME 类型. 映射文件名到 MIME 类型
* base64: base64 --- Base16 Base32 Base64 Base85 数据编码. Base16, Base32, Base64, Base85 数据编码
* binhex: binhex --- 对binhex4文件进行编码和解码. 对binhex4文件进行编码和解码
* binascii: binascii --- 二进制和 ASCII 码互转. 二进制和 ASCII 码互转
* quopri: quopri --- 编码与解码经过 MIME 转码的可打印数据. 编码与解码经过 MIME 转码的可打印数据

email --- 电子邮件与 MIME 处理包

* email.message; 表示一封电子邮件信息: email message 表示一封电子邮件信息. 
* email.parser; 解析电子邮件信息: email parser 解析电子邮件信息. 
* email.generator; 生成 MIME 文档: email generator 生成 MIME 文档. 
* email.policy; Policy 对象: email policy Policy 对象. 
* email.errors; 异常和缺陷类: email errors 异常和缺陷类. 
* email.headerregistry; 自定义标头对象: email headerregistry 自定义标头对象. 
* email.contentmanager; 管理 MIME 内容: email contentmanager 管理 MIME 内容. 
* email; 示例: email 示例. 
* email.message.Message; 使用 compat32 API 来表示电子邮件消息: email message Message 使用 compat32 API 来表示电子邮件消息. 
* email.mime; 从头创建电子邮件和 MIME 对象: email mime 从头创建电子邮件和 MIME 对象. 
* email.header; 国际化标头: email header 国际化标头. 
* email.charset; 表示字符集: email charset 表示字符集. 
* email.encoders; 编码器: email encoders 编码器. 
* email.utils; 其他工具: email utils 其他工具. 
* email.iterators; 迭代器: email iterators 迭代器. 

email.parser: 解析电子邮件信息

* FeedParser API:: 
* Parser API:: 
* 附加说明:: 

email.contentmanager: 管理 MIME 内容

* 内容管理器实例:: 

json --- JSON 编码和解码器

* 基本使用:: 
* 编码器和解码器:: 
* 异常: 异常<13>. 
* 标准符合性和互操作性:: 
* 命令行界面: 命令行界面<4>. 

标准符合性和互操作性

* 字符编码:: 
* Infinite 和 NaN 数值:: 
* 对象中的重复名称:: 
* 顶级非对象，非数组值:: 
* 实现限制:: 

命令行界面

* 命令行选项: 命令行选项<4>. 

mailbox --- 操作多种格式的邮箱

* Mailbox 对象:: 
* Message 对象:: 
* 异常: 异常<14>. 
* 示例: 示例<27>. 

Mailbox 对象

* Maildir:: 
* mbox:: 
* MH:: 
* Babyl:: 
* MMDF:: 

Message 对象

* MaildirMessage:: 
* mboxMessage:: 
* MHMessage:: 
* BabylMessage:: 
* MMDFMessage:: 

mimetypes --- 映射文件名到 MIME 类型

* MimeTypes 对象:: 

binhex --- 对binhex4文件进行编码和解码

* 注释: 注释<3>. 

结构化标记处理工具

* html: html --- 超文本标记语言支持. 超文本标记语言支持
* html.parser: html parser --- 简单的 HTML 和 XHTML 解析器. 简单的 HTML 和 XHTML 解析器
* html.entities: html entities --- HTML 一般实体的定义. HTML 一般实体的定义
* XML处理模块:: 
* xml.etree.ElementTree: xml etree ElementTree --- ElementTree XML API. ElementTree XML API
* xml.dom: xml dom --- 文档对象模型 API. 文档对象模型 API
* xml.dom.minidom: xml dom minidom --- 最小化的 DOM 实现. 最小化的 DOM 实现
* xml.dom.pulldom: xml dom pulldom --- 支持构建部分 DOM 树. 支持构建部分 DOM 树
* xml.sax: xml sax --- 支持 SAX2 解析器. 支持 SAX2 解析器
* xml.sax.handler: xml sax handler --- SAX 处理句柄的基类. SAX 处理句柄的基类
* xml.sax.saxutils: xml sax saxutils --- SAX 工具集. SAX 工具集
* xml.sax.xmlreader: xml sax xmlreader --- 用于 XML 解析器的接口. 用于 XML 解析器的接口
* xml.parsers.expat: xml parsers expat --- 使用 Expat 的快速 XML 解析. 使用 Expat 的快速 XML 解析

html.parser --- 简单的 HTML 和 XHTML 解析器

* HTML 解析器的示例程序:: 
* HTMLParser 方法:: 
* 示例: 示例<28>. 

XML处理模块

* XML 漏洞:: 
* defusedxml 包:: 

xml.etree.ElementTree ---  ElementTree XML API

* 教程:: 
* XPath支持:: 
* 参考引用:: 
* XInclude 支持:: 
* 参考引用: 参考引用<2>. 

教程

* XML 树和元素:: 
* 解析 XML:: 
* 用于非阻塞解析的拉取 API:: 
* 查找感兴趣的元素:: 
* 修改XML文件:: 
* 构建 XML 文档:: 
* 解析带有命名空间的 XML:: 

XPath支持

* 示例: 示例<29>. 
* 支持的XPath语法:: 

参考引用

* 函数: 函数<7>. 

XInclude 支持

* 示例: 示例<30>. 

参考引用

* 函数: 函数<8>. 
* 元素对象:: 
* ElementTree 对象:: 
* QName 对象:: 
* TreeBuilder 对象:: 
* XMLParser对象:: 
* XMLPullParser对象:: 
* 异常: 异常<15>. 

xml.dom --- 文档对象模型 API

* 模块内容: 模块内容<6>. 
* DOM 中的对象:: 
* 一致性:: 

DOM 中的对象

* DOMImplementation 对象:: 
* 节点对象:: 
* 节点列表对象:: 
* 文档类型对象:: 
* Document 对象:: 
* 元素对象: 元素对象<2>. 
* Attr 对象:: 
* NamedNodeMap 对象:: 
* 注释对象:: 
* Text 和 CDATASection 对象:: 
* ProcessingInstruction 对象:: 
* 异常: 异常<16>. 

一致性

* 类型映射:: 
* 访问器方法:: 

xml.dom.minidom --- 最小化的 DOM 实现

* DOM 对象:: 
* DOM 示例:: 
* minidom 和 DOM 标准:: 

xml.dom.pulldom --- 支持构建部分 DOM 树

* DOMEventStream 对象:: 

xml.sax --- 支持 SAX2 解析器

* SAXException 对象:: 

xml.sax.handler --- SAX 处理句柄的基类

* ContentHandler 对象:: 
* DTDHandler 对象:: 
* EntityResolver 对象:: 
* ErrorHandler 对象:: 

xml.sax.xmlreader --- 用于 XML 解析器的接口

* XMLReader 对象:: 
* IncrementalParser 对象:: 
* Locator 对象:: 
* InputSource 对象:: 
* Attributes 接口:: 
* AttributesNS 接口:: 

xml.parsers.expat ---  使用 Expat 的快速 XML 解析

* XMLParser对象: XMLParser对象<2>. 
* ExpatError 异常:: 
* 示例: 示例<31>. 
* 内容模型描述:: 
* Expat 错误常量:: 

互联网协议和支持

* webbrowser: webbrowser --- 方便的Web浏览器控制器. 方便的Web浏览器控制器
* wsgiref: wsgiref --- WSGI 工具和引用的实现. WSGI 工具和引用的实现
* urllib: urllib --- URL 处理模块. URL 处理模块
* urllib.request: urllib request --- 用于打开 URL 的可扩展库. 用于打开 URL 的可扩展库
* urllib.response: urllib response --- urllib 使用的 Response 类. urllib 使用的 Response 类
* urllib.parse 用于解析 URL: urllib parse 用于解析 URL. 
* urllib.error: urllib error --- urllib request 引发的异常类. urllib.request 引发的异常类
* urllib.robotparser: urllib robotparser --- robots txt 语法分析程序. robots.txt 语法分析程序
* http: http --- HTTP 模块. HTTP 模块
* http.client: http client --- HTTP 协议客户端. HTTP 协议客户端
* ftplib: ftplib --- FTP 协议客户端. FTP 协议客户端
* poplib: poplib --- POP3 协议客户端. POP3 协议客户端
* imaplib: imaplib --- IMAP4 协议客户端. IMAP4 协议客户端
* smtplib ---SMTP协议客户端:: 
* uuid: uuid --- RFC 4122 定义的UUID对象. RFC 4122 定义的UUID对象
* socketserver: socketserver --- 用于网络服务器的框架. 用于网络服务器的框架
* http.server: http server --- HTTP 服务器. HTTP 服务器
* http.cookies: http cookies --- HTTP状态管理. HTTP状态管理
* http.cookiejar —— HTTP 客户端的 Cookie 处理: http cookiejar —— HTTP 客户端的 Cookie 处理. 
* xmlrpc: xmlrpc --- XMLRPC 服务端与客户端模块. XMLRPC 服务端与客户端模块
* xmlrpc.client: xmlrpc client --- XML-RPC 客户端访问. XML-RPC 客户端访问
* xmlrpc.server: xmlrpc server --- 基本 XML-RPC 服务器. 基本 XML-RPC 服务器
* ipaddress: ipaddress --- IPv4/IPv6 操作库. IPv4/IPv6 操作库

webbrowser --- 方便的Web浏览器控制器

* 浏览器控制器对象:: 

wsgiref --- WSGI 工具和引用的实现

* wsgiref.util: wsgiref util -- WSGI 环境工具. WSGI 环境工具
* wsgiref.headers: wsgiref headers -- WSGI 响应标头工具. WSGI 响应标头工具
* wsgiref.simple_server: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器. 一个简单的 WSGI HTTP 服务器
* wsgiref.validate: wsgiref validate --- WSGI 一致性检查器. WSGI 一致性检查器
* wsgiref.handlers: wsgiref handlers -- 服务器/网关基类. 服务器/网关基类
* 示例: 示例<32>. 

urllib.request --- 用于打开 URL 的可扩展库

* Request 对象:: 
* OpenerDirector 对象:: 
* BaseHandler 对象:: 
* HTTPRedirectHandler 对象:: 
* HTTPCookieProcessor 对象:: 
* ProxyHandler 对象:: 
* HTTPPasswordMgr 对象:: 
* HTTPPasswordMgrWithPriorAuth 对象:: 
* AbstractBasicAuthHandler 对象:: 
* HTTPBasicAuthHandler 对象:: 
* ProxyBasicAuthHandler 对象:: 
* AbstractDigestAuthHandler 对象:: 
* HTTPDigestAuthHandler 对象:: 
* ProxyDigestAuthHandler 对象:: 
* HTTPHandler 对象:: 
* HTTPSHandler 对象:: 
* FileHandler 对象:: 
* DataHandler 对象:: 
* FTPHandler 对象:: 
* CacheFTPHandler 对象:: 
* UnknownHandler 对象:: 
* HTTPErrorProcessor 对象:: 
* 示例: 示例<33>. 
* 沿袭的接口:: 
* urllib.request 的限制: urllib request 的限制. 

urllib.parse  用于解析 URL

* URL 解析:: 
* URL parsing security:: 
* 解析ASCII编码字节:: 
* 结构化解析结果:: 
* URL 转码:: 

http --- HTTP 模块

* HTTP 状态码:: 

http.client --- HTTP 协议客户端

* HTTPConnection 对象:: 
* HTTPResponse 对象:: 
* 示例: 示例<34>. 
* HTTPMessage 对象:: 

ftplib --- FTP 协议客户端

* FTP 对象:: 
* FTP_TLS 对象:: 

poplib --- POP3 协议客户端

* POP3 对象:: 
* POP3 示例:: 

imaplib --- IMAP4 协议客户端

* IMAP4 对象:: 
* IMAP4 示例:: 

smtplib ---SMTP协议客户端

* SMTP 对象:: 
* SMTP 示例:: 

uuid --- RFC 4122 定义的UUID对象

* 示例: 示例<35>. 

socketserver --- 用于网络服务器的框架

* 服务器创建的说明:: 
* Server 对象: Server 对象<2>. 
* 请求处理句柄对象:: 
* 示例: 示例<36>. 

示例

* socketserver.TCPServer 示例: socketserver TCPServer 示例. 
* socketserver.UDPServer 示例: socketserver UDPServer 示例. 
* 异步混合类:: 

http.server --- HTTP 服务器

* 安全考量: 安全考量<4>. 

http.cookies --- HTTP状态管理

* Cookie 对象:: 
* Morsel 对象:: 
* 示例: 示例<37>. 

http.cookiejar —— HTTP 客户端的 Cookie 处理

* CookieJar 和 FileCookieJar 对象:: 
* FileCookieJar 的子类及其与 Web 浏览器的协同:: 
* CookiePolicy 对象:: 
* DefaultCookiePolicy 对象:: 
* Cookie 对象: Cookie 对象<2>. 
* 示例: 示例<38>. 

xmlrpc.client --- XML-RPC 客户端访问

* ServerProxy 对象:: 
* DateTime 对象:: 
* Binary 对象:: 
* Fault 对象:: 
* ProtocolError 对象:: 
* MultiCall 对象:: 
* 便捷函数:: 
* 客户端用法的示例:: 
* 客户端与服务器用法的示例:: 

xmlrpc.server --- 基本 XML-RPC 服务器

* SimpleXMLRPCServer 对象:: 
* CGIXMLRPCRequestHandler:: 
* XMLRPC 服务器文档:: 
* DocXMLRPCServer 对象:: 
* DocCGIXMLRPCRequestHandler:: 

SimpleXMLRPCServer 对象

* SimpleXMLRPCServer 示例:: 

ipaddress --- IPv4/IPv6 操作库

* 方便的工厂函数:: 
* IP 地址:: 
* IP网络的定义:: 
* 接口对象:: 
* 其他模块级别函数:: 
* 自定义异常:: 

IP 地址

* 地址对象:: 
* 转换字符串和整数:: 
* 运算符: 运算符<3>. 

运算符

* 比较运算符:: 
* 算术运算符:: 

IP网络的定义

* 前缀、网络掩码和主机掩码:: 
* 网络对象:: 
* 运算符: 运算符<4>. 

运算符

* 逻辑操作符:: 
* 迭代: 迭代<2>. 
* 作为地址容器的网络:: 

接口对象

* 运算符: 运算符<5>. 

运算符

* 逻辑操作符: 逻辑操作符<2>. 

多媒体服务

* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换

wave --- 读写WAV格式文件

* Wave_read对象:: 
* Wave_write 对象:: 

国际化

* gettext: gettext --- 多语种国际化服务. 多语种国际化服务
* locale: locale --- 国际化服务. 国际化服务

gettext --- 多语种国际化服务

* GNU gettext API:: 
* 基于类的 API:: 
* 国际化 (I18N) 你的程序和模块: 国际化 I18N 你的程序和模块. 
* 致谢: 致谢<9>. 

基于类的 API

* NullTranslations 类:: 
* GNUTranslations 类:: 
* Solaris 消息编目支持:: 
* 编目构造器:: 

国际化 (I18N) 你的程序和模块

* 本地化你的模块:: 
* 本地化你的应用程序:: 
* 即时更改语言:: 
* 延迟翻译:: 

locale --- 国际化服务

* 背景、细节、提示、技巧和注意事项:: 
* 针对扩展程序编写人员和嵌入Python 运行的程序:: 
* 访问信息目录:: 

程序框架

* turtle: turtle --- 海龟绘图. 海龟绘图
* cmd: cmd --- 支持面向行的命令解释器. 支持面向行的命令解释器
* shlex —— 简单的词义分析:: 

turtle --- 海龟绘图

* 概述: 概述<11>. 
* 可用的 Turtle 和 Screen 方法概览:: 
* RawTurtle/Turtle 方法和对应函数:: 
* TurtleScreen/Screen 方法及对应函数:: 
* 公共类:: 
* 帮助与配置:: 
* turtledemo: turtledemo --- 演示脚本集. 演示脚本集
* Python 2.6 之后的变化: Python 2 6 之后的变化. 
* Python 3.0 之后的变化: Python 3 0 之后的变化. 

可用的 Turtle 和 Screen 方法概览

* Turtle 方法:: 
* TurtleScreen/Screen 方法:: 

RawTurtle/Turtle 方法和对应函数

* 海龟动作:: 
* 获取海龟的状态:: 
* 度量单位设置:: 
* 画笔控制:: 
* 海龟状态:: 
* 使用事件:: 
* 特殊海龟方法:: 
* 复合形状:: 

画笔控制

* 绘图状态:: 
* 颜色控制:: 
* 填充:: 
* 更多绘图控制:: 

海龟状态

* 可见性:: 
* 外观:: 

TurtleScreen/Screen 方法及对应函数

* 窗口控制:: 
* 动画控制:: 
* 使用屏幕事件:: 
* 输入方法:: 
* 设置与特殊方法:: 
* Screen 专有方法@comma{} 而非继承自 TurtleScreen: Screen 专有方法 而非继承自 TurtleScreen. 

帮助与配置

* 如何使用帮助:: 
* 文档字符串翻译为不同的语言:: 
* 如何配置 Screen 和 Turtle:: 

cmd --- 支持面向行的命令解释器

* Cmd 对象:: 
* Cmd 例子:: 

shlex —— 简单的词义分析

* shlex 对象:: 
* 解析规则:: 
* 改进的 shell 兼容性:: 

Tk图形用户界面(GUI)

* tkinter: tkinter --- Tcl/Tk的Python接口. Tcl/Tk的Python接口
* tkinter.colorchooser: tkinter colorchooser --- 颜色选择对话框. 颜色选择对话框
* tkinter.font: tkinter font --- Tkinter 字体封装. Tkinter 字体封装
* Tkinter 对话框:: 
* tkinter.messagebox: tkinter messagebox --- Tkinter 消息提示. Tkinter 消息提示
* tkinter.scrolledtext: tkinter scrolledtext --- 滚动文字控件. 滚动文字控件
* tkinter.dnd: tkinter dnd --- 拖放操作支持. 拖放操作支持
* tkinter.ttk: tkinter ttk --- Tk主题部件. Tk主题部件
* tkinter.tix: tkinter tix --- TK扩展包. TK扩展包
* IDLE: IDLE<52>. 

tkinter --- Tcl/Tk的Python接口

* Tkinter 模块:: 
* Tkinter 拾遗:: 
* Tcl/Tk 速览:: 
* 将简单的 Tk 映射到 Tkinter:: 
* Tk 和 Tkinter 如何关联:: 
* 快速参考:: 
* 文件句柄:: 

Tkinter 拾遗

* 本节内容的用法:: 
* 简单的 Hello World 程序:: 

快速参考

* 可选配置项:: 
* 包装器:: 
* 包装器的参数:: 
* 部件与变量的关联:: 
* 窗口管理器:: 
* Tk 参数的数据类型:: 
* 绑定和事件:: 
* index 参数:: 
* 图片:: 

Tkinter 对话框

* tkinter.simpledialog: tkinter simpledialog --- 标准 Tkinter 输入对话框. 标准 Tkinter 输入对话框
* tkinter.filedialog: tkinter filedialog --- 文件选择对话框. 文件选择对话框.
* tkinter.commondialog: tkinter commondialog --- 对话窗口模板. 对话窗口模板

tkinter.filedialog --- 文件选择对话框.

* 原生 加载/保存 对话框.: 原生 加载/保存 对话框. 

tkinter.ttk --- Tk主题部件

* 使用 Ttk:: 
* Ttk 控件:: 
* 控件:: 
* 组合框:: 
* Spinbox:: 
* 笔记本:: 
* Progressbar:: 
* Separator:: 
* Sizegrip:: 
* Treeview:: 
* Ttk 风格:: 

控件

* 标准选项:: 
* 可滚动控件选项:: 
* 标签选项:: 
* 兼容性选项:: 
* 控件状态:: 
* ttk.Widget: ttk Widget. 

组合框

* 选项:: 
* 虚拟事件:: 
* ttk.Combobox: ttk Combobox. 

Spinbox

* 选项: 选项<2>. 
* 虚拟事件: 虚拟事件<2>. 
* ttk.Spinbox: ttk Spinbox. 

笔记本

* 选项: 选项<3>. 
* Tab 选项:: 
* Tab 标识:: 
* 虚拟事件: 虚拟事件<3>. 
* ttk.Notebook: ttk Notebook. 

Progressbar

* 选项: 选项<4>. 
* ttk.Progressbar: ttk Progressbar. 

Separator

* 选项: 选项<5>. 

Sizegrip

* 与平台相关的注意事项:: 
* Bug:: 

Treeview

* 选项: 选项<6>. 
* 数据项的属性:: 
* tag 属性:: 
* 列标识:: 
* 虚拟事件: 虚拟事件<4>. 
* ttk.Treeview: ttk Treeview. 

Ttk 风格

* 布局:: 

tkinter.tix --- TK扩展包

* 使用 Tix:: 
* Tix 部件:: 
* Tix 命令:: 

Tix 部件

* 基本部件:: 
* 文件选择器:: 
* 层级式列表框:: 
* 表格式列表框:: 
* 管理器部件:: 
* 图像类型:: 
* 其他部件:: 
* 表单布局管理器:: 

IDLE

* 目录:: 
* 编辑和导航:: 
* 启动和代码执行:: 
* 帮助和偏好:: 

目录

* 文件菜单 （命令行和编辑器）:: 
* 编辑菜单（命令行和编辑器）:: 
* 格式菜单（仅 window 编辑器）:: 
* 运行菜单（仅 window 编辑器）:: 
* Shell 菜单（仅 window 编辑器）:: 
* 调试菜单（仅 window 编辑器）:: 
* 选项菜单（命令行和编辑器）:: 
* Window 菜单（命令行和编辑器）:: 
* 帮助菜单（命令行和编辑器）:: 
* 上下文菜单:: 

编辑和导航

* 编辑窗口:: 
* 按键绑定:: 
* 自动缩进:: 
* 完成:: 
* 提示:: 
* 代码上下文:: 
* Python Shell 窗口:: 
* 文本颜色:: 

启动和代码执行

* 命令行语法:: 
* 启动失败:: 
* 运行用户代码:: 
* Shell中的用户输出:: 
* 开发 tkinter 应用程序:: 
* 在没有子进程的情况下运行:: 

帮助和偏好

* 帮助源:: 
* 首选项设置:: 
* macOS 上的IDLE:: 
* 扩展:: 

开发工具

* typing: typing --- 类型提示支持. 类型提示支持
* pydoc: pydoc --- 文档生成器和在线帮助系统. 文档生成器和在线帮助系统
* Python 开发模式:: 
* Python 开发模式的效果:: 
* ResourceWarning 示例:: 
* 文件描述符错误示例:: 
* doctest: doctest --- 测试交互性的Python示例. 测试交互性的Python示例
* unittest: unittest --- 单元测试框架. 单元测试框架
* unittest.mock: unittest mock --- mock对象库. mock对象库
* unittest.mock 上手指南: unittest mock 上手指南. 
* 2to3 - 自动将 Python 2 代码转为 Python 3 代码:: 
* test: test --- Python回归测试包. Python回归测试包
* test.support: test support --- 针对 Python 测试套件的工具. 针对 Python 测试套件的工具
* test.support.socket_helper: test support socket_helper --- 用于套接字测试的工具. 用于套接字测试的工具
* test.support.script_helper: test support script_helper --- 用于 Python 执行测试工具. 用于 Python 执行测试工具
* test.support.bytecode_helper: test support bytecode_helper --- 用于测试正确字节码生成的支持工具. 用于测试正确字节码生成的支持工具

typing --- 类型提示支持

* 相关的 PEP:: 
* 类型别名:: 
* NewType:: 
* 可调对象（Callable）:: 
* 泛型（Generic）:: 
* 用户定义的泛型类型:: 
* Any 类型:: 
* 名义子类型 vs 结构子类型:: 
* 模块内容: 模块内容<7>. 

模块内容

* 特殊类型原语:: 
* 泛型具象容器:: 
* 抽象基类:: 
* 协议: 协议<3>. 
* 函数与装饰器:: 
* 内省辅助器:: 
* 常量: 常量<4>. 

特殊类型原语

* 特殊类型:: 
* 特殊形式:: 
* 构建泛型类型:: 
* 其他特殊指令:: 

泛型具象容器

* 对应的内置类型:: 
* collections 对应类型:: 
* 其他具象类型:: 

抽象基类

* collections.abc 对应的容器: collections abc 对应的容器. 
* collections.abc 对应的其他类型: collections abc 对应的其他类型. 
* 异步编程:: 
* 上下文管理器类型: 上下文管理器类型<2>. 

doctest --- 测试交互性的Python示例

* 简单用法：检查Docstrings中的示例:: 
* 简单的用法：检查文本文件中的例子:: 
* 它是如何工作的:: 
* 基本API:: 
* Unittest API:: 
* 高级 API:: 
* 调试:: 
* 肥皂盒:: 

它是如何工作的

* 哪些文件串被检查了？:: 
* 文档串的例子是如何被识别的？:: 
* 什么是执行上下文:: 
* 异常如何处理？:: 
* 选项标记:: 
* 指令:: 
* 警告: 警告<2>. 

高级 API

* DocTest 对象:: 
* Example 对象:: 
* DocTestFinder 对象:: 
* DocTestParser 对象:: 
* DocTestRunner 对象:: 
* OutputChecker 对象:: 

unittest --- 单元测试框架

* 基本实例:: 
* 命令行界面: 命令行界面<5>. 
* 探索性测试:: 
* 组织你的测试代码:: 
* 复用已有的测试代码:: 
* 跳过测试与预计的失败:: 
* 使用子测试区分测试迭代:: 
* 类与函数:: 
* 类与模块设定:: 
* 信号处理:: 

命令行界面

* 命令行选项: 命令行选项<5>. 

类与函数

* 测试用例:: 
* 分组测试:: 
* 加载和运行测试:: 

测试用例

* 已弃用的别名:: 

加载和运行测试

* load_tests 协议:: 

类与模块设定

* setUpClass 和 tearDownClass:: 
* setUpModule 和 tearDownModule:: 

unittest.mock --- mock对象库

* 快速上手:: 
* Mock 类:: 
* patch 装饰器:: 
* MagicMock 与魔术方法支持:: 
* 辅助对象:: 

Mock 类

* 调用: 调用<2>. 
* 删除属性:: 
* Mock 的名称与 name 属性:: 
* 附加 Mock 作为属性:: 

patch 装饰器

* patch:: 
* patch.object: patch object. 
* patch.dict: patch dict. 
* patch.multiple: patch multiple. 
* 补丁方法; start 和 stop: 补丁方法 start 和 stop. 
* 为内置对象打补丁:: 
* TEST_PREFIX:: 
* 嵌套补丁装饰器:: 
* 补丁的位置:: 
* 对描述器和代理对象打补丁:: 

MagicMock 与魔术方法支持

* 模拟魔术方法:: 
* MagicMock:: 

辅助对象

* sentinel:: 
* DEFAULT:: 
* call:: 
* create_autospec:: 
* ANY:: 
* FILTER_DIR:: 
* mock_open:: 
* 自动 spec:: 
* 将 mock 封包:: 

unittest.mock 上手指南

* 使用 mock:: 
* 补丁装饰器:: 
* 更多示例:: 

使用 mock

* 模拟方法调用:: 
* 对象上的方法调用的 mock:: 
* 模拟类:: 
* 命名你的 mock:: 
* 追踪所有的调用:: 
* 设置返回值和属性:: 
* 通过 mock 引发异常:: 
* 附带影响函数和可迭代对象:: 
* 模拟异步迭代器:: 
* 模拟异步上下文管理器:: 
* 基于现有对象创建模拟对象:: 

更多示例

* 模拟链式调用:: 
* 部分模拟:: 
* 模拟生成器方法:: 
* 对每个测试方法应用相同的补丁:: 
* 模拟未绑定方法:: 
* 通过 mock 检查多次调用:: 
* 处理可变参数:: 
* 嵌套补丁:: 
* 使用 MagicMock 模拟字典:: 
* 模拟子类及其属性:: 
* 通过 patch.dict 模拟导入: 通过 patch dict 模拟导入. 
* 追踪调用顺序和不太冗长的调用断言:: 
* 更复杂的参数匹配:: 

2to3 - 自动将 Python 2 代码转为 Python 3 代码

* 使用 2to3:: 
* 修复器:: 
* lib2to3 —— 2to3 支持库:: 

test ---  Python回归测试包

* 为 test 包编写单元测试:: 
* 使用命令行界面运行测试:: 

调试和分析

* 审计事件表:: 
* bdb: bdb --- 调试器框架. 调试器框架
* faulthandler —— 转储 Python 的跟踪信息:: 
* pdb: pdb --- Python 的调试器. Python 的调试器
* Python Profilers 分析器:: 
* timeit: timeit --- 测量小代码片段的执行时间. 测量小代码片段的执行时间
* trace: trace --- 跟踪Python语句执行. 跟踪Python语句执行
* tracemalloc: tracemalloc --- 跟踪内存分配. 跟踪内存分配

faulthandler —— 转储 Python 的跟踪信息

* 转储跟踪信息:: 
* 错误处理程序的状态:: 
* 一定时间后转储跟踪数据。:: 
* 转储用户信号的跟踪信息。:: 
* 文件描述符相关话题:: 
* 示例: 示例<39>. 

pdb --- Python 的调试器

* 调试器命令:: 

Python Profilers 分析器

* profile分析器简介:: 
* 实时用户手册:: 
* profile 和 cProfile 模块参考:: 
* Stats 类:: 
* 什么是确定性性能分析？:: 
* 局限性:: 
* 准确估量:: 
* 使用自定义计时器:: 

timeit --- 测量小代码片段的执行时间

* 基本示例: 基本示例<2>. 
* Python 接口:: 
* 命令行界面: 命令行界面<6>. 
* 示例: 示例<40>. 

trace --- 跟踪Python语句执行

* 命令行用法:: 
* 编程接口:: 

命令行用法

* 主要的可选参数:: 
* 修饰器:: 
* 过滤器:: 

tracemalloc --- 跟踪内存分配

* 示例: 示例<41>. 
* API:: 

示例

* 显示前10项:: 
* 计算差异:: 
* 获取一个内存块的溯源:: 
* Pretty top:: 

Pretty top

* Record the current and peak size of all traced memory blocks:: 

API

* 函数: 函数<9>. 
* 域过滤器:: 
* 过滤器: 过滤器<2>. 
* Frame:: 
* 快照:: 
* 统计:: 
* StatisticDiff:: 
* 跟踪:: 
* 回溯:: 

软件打包和分发

* distutils: distutils --- 构建和安装 Python 模块. 构建和安装 Python 模块
* ensurepip: ensurepip --- 引导 pip 安装器. 引导 pip 安装器
* venv: venv --- 创建虚拟环境. 创建虚拟环境
* zipapp —— 管理可执行的 Python zip 打包文件:: 

ensurepip --- 引导 pip 安装器

* 命令行界面: 命令行界面<7>. 
* 模块 API:: 

venv --- 创建虚拟环境

* 创建虚拟环境: 创建虚拟环境<2>. 
* API: API<2>. 
* 一个扩展 EnvBuilder 的例子:: 

zipapp —— 管理可执行的 Python zip 打包文件

* 简单示例:: 
* 命令行接口:: 
* Python API:: 
* 示例: 示例<42>. 
* 指定解释器程序:: 
* 用 zipapp 创建独立运行的应用程序:: 
* Python 打包应用程序的格式:: 

用 zipapp 创建独立运行的应用程序

* 制作 Windows 可执行文件:: 
* 注意事项:: 

Python运行时服务

* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig —— 提供对 Python 配置信息的访问支持:: 
* builtins: builtins --- 内建对象. 内建对象
* __main__: __main__ --- 顶层脚本环境. 顶层脚本环境
* warnings —— 警告信息的控制:: 
* dataclasses: dataclasses --- 数据类. 数据类
* contextlib: contextlib --- 为 with语句上下文提供的工具. 为 with语句上下文提供的工具
* abc: abc --- 抽象基类. 抽象基类
* atexit: atexit --- 退出处理器. 退出处理器
* traceback: traceback --- 打印或检索堆栈回溯. 打印或检索堆栈回溯
* __future__: __future__ --- Future 语句定义. Future 语句定义
* gc: gc --- 垃圾回收器接口. 垃圾回收器接口
* inspect: inspect --- 检查对象. 检查对象
* site —— 指定域的配置钩子:: 

sysconfig —— 提供对 Python 配置信息的访问支持

* 配置变量:: 
* 安装路径:: 
* 其他功能: 其他功能<3>. 
* 使用 sysconfig 作为脚本as a script:: 

warnings —— 警告信息的控制

* 警告类别:: 
* 警告过滤器:: 
* 暂时禁止警告:: 
* 测试警告:: 
* 为新版本的依赖关系更新代码:: 
* 可用的函数:: 
* 可用的上下文管理器:: 

警告过滤器

* 警告过滤器的介绍:: 
* 默认警告过滤器:: 
* 重写默认的过滤器:: 

dataclasses --- 数据类

* 模块级装饰器、类和函数:: 
* 初始化后处理:: 
* 类变量:: 
* 仅初始化变量:: 
* 冻结的实例:: 
* 继承: 继承<2>. 
* 默认工厂函数:: 
* 可变的默认值:: 
* 异常: 异常<17>. 

contextlib --- 为 with语句上下文提供的工具

* 工具:: 
* 例子和配方:: 
* 单独使用，可重用并可重进入的上下文管理器:: 

例子和配方

* 支持可变数量的上下文管理器:: 
* 捕获 __enter__ 方法产生的异常:: 
* 在一个 __enter__ 方法的实现中进行清理:: 
* 替换任何对 try-finally 和旗标变量的使用:: 
* 将上下文管理器作为函数装饰器使用:: 

单独使用，可重用并可重进入的上下文管理器

* 重进入上下文管理器:: 
* 可重用的上下文管理器:: 

atexit --- 退出处理器

* atexit 示例:: 

traceback --- 打印或检索堆栈回溯

* TracebackException 对象:: 
* StackSummary 对象:: 
* FrameSummary 对象:: 
* 回溯示例:: 

inspect --- 检查对象

* 类型和成员:: 
* 获取源代码:: 
* 使用 Signature 对象对可调用对象进行内省:: 
* 类与函数: 类与函数<2>. 
* 解释器栈:: 
* 静态地获取属性:: 
* 生成器和协程的当前状态:: 
* 代码对象位标志:: 
* 命令行界面: 命令行界面<8>. 

site —— 指定域的配置钩子

* Readline 配置:: 
* 模块内容: 模块内容<8>. 
* 命令行界面: 命令行界面<9>. 

自定义 Python 解释器

* code: code --- 解释器基类. 解释器基类
* codeop: codeop --- 编译Python代码. 编译Python代码

code --- 解释器基类

* 交互解释器对象:: 
* 交互式控制台对象:: 

导入模块

* zipimport: zipimport --- 从 Zip 存档中导入模块. 从 Zip 存档中导入模块
* pkgutil: pkgutil --- 包扩展工具. 包扩展工具
* modulefinder: modulefinder --- 查找脚本使用的模块. 查找脚本使用的模块
* runpy ——查找并执行 Python 模块:: 
* importlib: importlib --- import 的实现. import 的实现
* 使用 importlib.metadata: 使用 importlib metadata. 

zipimport --- 从 Zip 存档中导入模块

* zipimporter 对象:: 
* 示例: 示例<43>. 

modulefinder --- 查找脚本使用的模块

* ModuleFinder 的示例用法:: 

importlib --- import 的实现

* 概述: 概述<12>. 
* 函数: 函数<10>. 
* importlib.abc —— 关于导入的抽象基类: importlib abc —— 关于导入的抽象基类. 
* importlib.resources: importlib resources -- 资源. 资源
* importlib.machinery —— 导入器和路径钩子函数。: importlib machinery —— 导入器和路径钩子函数。. 
* importlib.util —— 导入器的工具程序代码: importlib util —— 导入器的工具程序代码. 
* 示例: 示例<44>. 

示例

* 用编程方式导入:: 
* 检查某模块可否导入。:: 
* 直接导入源文件。:: 
* 设置导入器:: 
* importlib.import_module() 的近似实现: importlib import_module 的近似实现. 

使用 importlib.metadata

* 概述: 概述<13>. 
* 可用 API:: 
* 分发:: 
* 扩展搜索算法:: 

可用 API

* 入口点:: 
* 分发的元数据:: 
* 分发的版本:: 
* 分发的文件:: 
* 分发的依赖:: 

Python 语言服务

* parser: parser --- 访问 Python 解析树. 访问 Python 解析树
* ast: ast --- 抽象语法树. 抽象语法树
* symtable ——访问编译器的符号表:: 
* symbol: symbol --- 与 Python 解析树一起使用的常量. 与 Python 解析树一起使用的常量
* token: token --- 与Python解析树一起使用的常量. 与Python解析树一起使用的常量
* keyword: keyword --- 检验Python关键字. 检验Python关键字
* tokenize: tokenize --- 对 Python 代码使用的标记解析器. 对 Python 代码使用的标记解析器
* tabnanny: tabnanny --- 模糊缩进检测. 模糊缩进检测
* pyclbr: pyclbr --- Python 模块浏览器支持. Python 模块浏览器支持
* py_compile: py_compile --- 编译 Python 源文件. 编译 Python 源文件
* compileall: compileall --- 字节编译 Python 库. 字节编译 Python 库
* dis: dis --- Python 字节码反汇编器. Python 字节码反汇编器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集

parser --- 访问 Python 解析树

* 创建 ST 对象:: 
* 转换 ST 对象:: 
* Queries on ST Objects:: 
* 异常和错误处理:: 
* ST 对象:: 
* 示例; compile() 的模拟: 示例 compile 的模拟. 

ast --- 抽象语法树

* 抽象文法:: 
* 节点类:: 
* ast 中的辅助函数:: 
* 编译器旗标:: 
* 命令行用法: 命令行用法<2>. 

节点类

* 字面值: 字面值<3>. 
* 变量:: 
* 表达式: 表达式<2>. 
* 语句:: 
* 控制流:: 
* 函数与类定义:: 
* async 与 await:: 

表达式

* 抽取: 抽取<2>. 
* 推导式:: 

语句

* 导入:: 

symtable ——访问编译器的符号表

* 符号表的生成:: 
* 符号表的查看:: 

tokenize --- 对 Python 代码使用的标记解析器

* 对输入进行解析标记:: 
* 命令行用法: 命令行用法<3>. 
* 示例: 示例<45>. 

pyclbr --- Python 模块浏览器支持

* Function 对象:: 
* Class 对象:: 

compileall --- 字节编译 Python 库

* 使用命令行:: 
* 公有函数:: 

dis --- Python 字节码反汇编器

* 字节码分析:: 
* 分析函数:: 
* Python字节码说明:: 
* 操作码集合:: 

pickletools --- pickle 开发者工具集

* 命令行语法: 命令行语法<2>. 
* 编程接口: 编程接口<2>. 

命令行语法

* 命令行选项: 命令行选项<6>. 

杂项服务

* formatter: formatter --- 通用格式化输出. 通用格式化输出

formatter --- 通用格式化输出

* The Formatter Interface:: 
* Formatter Implementations:: 
* The Writer Interface:: 
* Writer Implementations:: 

Windows系统相关模块

* msvcrt: msvcrt --- 来自 MS VC++ 运行时的有用例程. 来自 MS VC++ 运行时的有用例程
* winreg: winreg --- Windows 注册表访问. Windows 注册表访问
* winsound —— Windows 系统的声音播放接口:: 

msvcrt --- 来自 MS VC++ 运行时的有用例程

* 文件操作:: 
* 控制台 I/O:: 
* 其他函数:: 

winreg --- Windows 注册表访问

* 函数: 函数<11>. 
* 常数: 常数<7>. 
* 注册表句柄对象:: 

常数

* HKEY_* 常量:: 
* 访问权限:: 
* 注册表值的类型:: 

访问权限

* 64 位系统特有:: 

Unix 专有服务

* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* grp: grp --- 组数据库. 组数据库
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl —— 系统调用 fcntl 和 ioctl:: 
* resource: resource --- 资源使用信息. 资源使用信息
* Unix syslog 库例程:: 

posix --- 最常见的 POSIX 系统调用

* 大文件支持:: 
* 重要的模块内容:: 

termios --- POSIX 风格的 tty 控制

* 示例: 示例<46>. 

pty --- 伪终端工具

* 示例: 示例<47>. 

resource --- 资源使用信息

* 资源限制: 资源限制<2>. 
* 资源用量:: 

Unix syslog 库例程

* 示例: 示例<48>. 

示例

* 简单示例: 简单示例<2>. 

被取代的模块

* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* asynchat: asynchat --- 异步套接字指令/响应处理程序. 异步套接字指令/响应处理程序
* asyncore: asyncore --- 异步套接字处理器. 异步套接字处理器
* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* crypt —— 检查 Unix 口令的函数:: 
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* imp —— 由代码内部访问 import 。:: 
* mailcap: mailcap --- Mailcap 文件处理. Mailcap 文件处理
* msilib: msilib --- 读写 Microsoft Installer 文件. 读写 Microsoft Installer 文件
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* nntplib: nntplib --- NNTP 协议客户端. NNTP 协议客户端
* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备
* pipes: pipes --- 终端管道接口. 终端管道接口
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* spwd —— shadow 密码库:: 
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* uu: uu --- 对 uuencode 文件进行编码与解码. 对 uuencode 文件进行编码与解码
* xdrlib: xdrlib --- 编码与解码 XDR 数据. 编码与解码 XDR 数据

asynchat --- 异步套接字指令/响应处理程序

* asynchat 示例:: 

asyncore --- 异步套接字处理器

* asyncore 示例基本 HTTP 客户端:: 
* asyncore 示例基本回显服务器:: 

cgi --- 通用网关接口支持

* 概述: 概述<14>. 
* 使用cgi模块。:: 
* 更高层级的接口:: 
* 函数: 函数<12>. 
* 对于安全性的关注:: 
* 在 Unix 系统上安装你的 CGI 脚本:: 
* 测试你的 CGI 脚本:: 
* 调试 CGI 脚本:: 
* 常见问题和解决方案:: 

crypt —— 检查 Unix 口令的函数

* 哈希方法:: 
* 模块属性:: 
* 模块函数: 模块函数<2>. 
* 示例: 示例<49>. 

imp —— 由代码内部访问 import 。

* 示例: 示例<50>. 

msilib --- 读写 Microsoft Installer 文件

* Database Objects:: 
* View Objects:: 
* Summary Information Objects:: 
* Record Objects:: 
* Errors:: 
* CAB Objects:: 
* Directory Objects:: 
* 相关特性: 相关特性<3>. 
* GUI classes:: 
* Precomputed tables:: 

nntplib --- NNTP 协议客户端

* NNTP 对象:: 
* 工具函数: 工具函数<2>. 

NNTP 对象

* 属性:: 
* 方法: 方法<3>. 

optparse --- 解析器的命令行选项

* 背景:: 
* 教程: 教程<2>. 
* 参考指南:: 
* Option Callbacks:: 
* Extending optparse:: 

背景

* 术语:: 
* What are options for?:: 
* 位置位置:: 

教程

* Understanding option actions:: 
* The store action:: 
* Handling boolean (flag) options: Handling boolean flag options. 
* Other actions:: 
* 默认值:: 
* Generating help:: 
* Printing a version string:: 
* How optparse handles errors:: 
* Putting it all together:: 

Generating help

* Grouping Options:: 

参考指南

* 创建解析器:: 
* 填充解析器:: 
* 定义选项:: 
* Option attributes:: 
* Standard option actions:: 
* Standard option types:: 
* 解析参数: 解析参数<2>. 
* Querying and manipulating your option parser:: 
* Conflicts between options:: 
* 清理: 清理<2>. 
* Other methods:: 

Option Callbacks

* Defining a callback option:: 
* How callbacks are called:: 
* Raising errors in a callback:: 
* Callback example 1; trivial callback: Callback example 1 trivial callback. 
* Callback example 2; check option order: Callback example 2 check option order. 
* Callback example 3; check option order (generalized): Callback example 3 check option order generalized. 
* Callback example 4; check arbitrary condition: Callback example 4 check arbitrary condition. 
* Callback example 5; fixed arguments: Callback example 5 fixed arguments. 
* Callback example 6; variable arguments: Callback example 6 variable arguments. 

Extending optparse

* Adding new types:: 
* Adding new actions:: 

ossaudiodev  --- 访问兼容OSS的音频设备

* 音频设备对象:: 
* 混音器设备对象:: 

pipes --- 终端管道接口

* 模板对象:: 

smtpd --- SMTP 服务器

* SMTPServer 对象:: 
* DebuggingServer 对象:: 
* PureProxy对象:: 
* MailmanProxy 对象:: 
* SMTPChannel 对象:: 

sunau --- 读写 Sun AU 文件

* AU_read 对象:: 
* AU_write 对象:: 

telnetlib -- Telnet 客户端

* Telnet 对象:: 
* Telnet 示例:: 

xdrlib --- 编码与解码 XDR 数据

* Packer 对象:: 
* Unpacker 对象:: 
* 异常: 异常<18>. 

扩展和嵌入 Python 解释器

* 推荐的第三方工具:: 
* 不使用第三方工具创建扩展:: 
* 在更大的应用程序中嵌入 CPython 运行时:: 

不使用第三方工具创建扩展

* 使用 C 或 C++ 扩展 Python:: 
* 自定义扩展类型：教程:: 
* 定义扩展类型：已分类主题:: 
* 构建C/C++扩展:: 
* 在 Windows 上构建 C 和 C++ 扩展:: 

使用 C 或 C++ 扩展 Python

* 一个简单的例子:: 
* 关于错误和异常:: 
* 回到例子:: 
* 模块方法表和初始化函数:: 
* 编译和链接:: 
* 在C中调用Python函数:: 
* 提取扩展函数的参数:: 
* 给扩展函数的关键字参数:: 
* 构造任意值:: 
* 引用计数:: 
* 在C++中编写扩展:: 
* 给扩展模块提供C API:: 

引用计数

* Python中的引用计数:: 
* 拥有规则:: 
* 危险的薄冰:: 
* NULL指针:: 

自定义扩展类型：教程

* 基础:: 
* Adding data and methods to the Basic example:: 
* Providing finer control over data attributes:: 
* Supporting cyclic garbage collection:: 
* Subclassing other types:: 

定义扩展类型：已分类主题

* 终结和内存释放:: 
* 对象展示:: 
* 属性管理:: 
* 对象比较:: 
* 抽象协议支持:: 
* 弱引用支持:: 
* 更多建议:: 

属性管理

* 泛型属性管理:: 
* 类型专属的属性管理:: 

构建C/C++扩展

* 使用distutils构建C和C++扩展:: 
* 发布你的扩展模块:: 

在 Windows 上构建 C 和 C++ 扩展

* 菜谱式说明:: 
* Unix 和 Windows 之间的差异:: 
* DLL 的实际使用:: 

在更大的应用程序中嵌入 CPython 运行时

* 在其它应用程序嵌入 Python:: 

在其它应用程序嵌入 Python

* 高层次的嵌入:: 
* 突破高层次嵌入的限制：概述:: 
* 纯嵌入:: 
* 对嵌入 Python 功能进行扩展:: 
* 在 C++ 中嵌入 Python:: 
* 在类 Unix 系统中编译和链接:: 

Python/C API 参考手册

* 概述: 概述<15>. 
* 稳定的应用程序二进制接口:: 
* 极高层级:: 
* 引用计数: 引用计数<3>. 
* 异常处理:: 
* 工具: 工具<2>. 
* 抽象对象层:: 
* 具体的对象层:: 
* 初始化，终结和线程:: 
* Python初始化配置:: 
* 内存管理:: 
* 对象实现支持:: 
* API 和 ABI 版本管理:: 

概述

* 代码标准:: 
* 包含文件:: 
* 有用的宏:: 
* 对象、类型和引用计数:: 
* 异常: 异常<19>. 
* 嵌入Python: 嵌入Python<2>. 
* 调试构建:: 

对象、类型和引用计数

* 引用计数: 引用计数<2>. 
* 类型:: 

引用计数

* 引用计数细节:: 

异常处理

* 打印和清理:: 
* 抛出异常:: 
* 发出警告:: 
* 查询错误指示器:: 
* 信号处理: 信号处理<2>. 
* Exception 类: Exception 类<2>. 
* 异常对象:: 
* Unicode 异常对象:: 
* 递归控制:: 
* 标准异常:: 
* 标准警告类别:: 

工具

* 操作系统实用程序:: 
* 系统功能:: 
* 过程控制:: 
* 导入模块: 导入模块<2>. 
* 数据 marshal 操作支持:: 
* 语句解释及变量编译:: 
* 字符串转换与格式化:: 
* 反射:: 
* 编解码器注册与支持功能:: 

语句解释及变量编译

* 解析参数: 解析参数<3>. 
* 创建变量:: 

解析参数

* 字符串和缓存区:: 
* 数字: 数字<2>. 
* 其他对象:: 
* API 函数:: 

编解码器注册与支持功能

* Codec 查找API:: 
* 用于Unicode编码错误处理程序的注册表API:: 

抽象对象层

* 对象协议:: 
* 调用协议:: 
* 数字协议:: 
* 序列协议:: 
* 映射协议:: 
* 迭代器协议:: 
* 缓冲协议:: 
* 旧缓冲协议:: 

调用协议

* tp_call 协议:: 
* Vectorcall 协议:: 
* 调用对象的 API:: 
* 调用支持 API:: 

Vectorcall 协议

* 递归控制: 递归控制<2>. 
* Vectorcall 支持 API:: 

缓冲协议

* 缓冲区结构:: 
* 缓冲区请求的类型:: 
* 复杂数组:: 
* 缓冲区相关函数:: 

缓冲区请求的类型

* 与请求无关的字段:: 
* 只读，格式:: 
* 形状，步幅，子偏移量:: 
* 连续性的请求:: 
* 复合请求:: 

复杂数组

* NumPy-风格：形状和步幅:: 
* PIL-风格：形状，步幅和子偏移量:: 

具体的对象层

* 基本对象:: 
* 数值对象:: 
* 序列对象:: 
* 容器对象:: 
* 函数对象:: 
* 其他对象: 其他对象<2>. 

基本对象

* Type 对象:: 
* None 对象:: 

Type 对象

* 创建堆分配类型:: 

数值对象

* 整数型对象:: 
* 布尔对象:: 
* 浮点数对象:: 
* 复数对象:: 

复数对象

* 表示复数的C结构体:: 
* 表示复数的Python对象:: 

序列对象

* 字节对象:: 
* 字节数组对象:: 
* Unicode对象和编码解码器:: 
* 元组对象:: 
* 结构序列对象:: 
* 列表对象:: 

字节数组对象

* 类型检查宏:: 
* 直接 API 函数:: 
* 宏:: 

Unicode对象和编码解码器

* Unicode对象:: 
* Built-in Codecs:: 
* 方法与槽位函数:: 

Unicode对象

* Unicode类型:: 
* Unicode字符属性:: 
* Creating and accessing Unicode strings:: 
* Deprecated Py_UNICODE APIs:: 
* Locale Encoding:: 
* 文件系统编码格式:: 
* wchar_t Support:: 

Built-in Codecs

* Generic Codecs:: 
* UTF-8 编解码器:: 
* UTF-32 Codecs:: 
* UTF-16 Codecs:: 
* UTF-7 Codecs:: 
* Unicode-Escape 编解码器:: 
* Raw-Unicode-Escape Codecs:: 
* Latin-1 Codecs:: 
* ASCII Codecs:: 
* Character Map Codecs:: 
* MBCS codecs for Windows:: 
* Methods & Slots:: 

容器对象

* 字典对象:: 
* 集合对象:: 

函数对象

* 函数对象: 函数对象<2>. 
* 实例方法对象:: 
* 方法对象: 方法对象<2>. 
* Cell 对象:: 
* 代码对象: 代码对象<2>. 

其他对象

* 文件对象:: 
* 模块对象:: 
* 迭代器对象:: 
* 描述符对象:: 
* 切片对象:: 
* Ellipsis 对象:: 
* MemoryView 对象:: 
* 弱引用对象: 弱引用对象<2>. 
* Capsule 对象:: 
* 生成器对象:: 
* 协程对象: 协程对象<2>. 
* 上下文变量对象:: 
* DateTime 对象: DateTime 对象<2>. 
* 类型注解对象:: 

模块对象

* 初始化 C 模块:: 
* Module lookup:: 

初始化 C 模块

* Single-phase initialization:: 
* Multi-phase initialization:: 
* Low-level module creation functions:: 
* Support functions:: 

初始化，终结和线程

* 在Python初始化之前:: 
* 全局配置变量:: 
* Initializing and finalizing the interpreter:: 
* Process-wide parameters:: 
* 线程状态和全局解释器锁:: 
* 子解释器支持:: 
* 异步通知:: 
* 分析和跟踪:: 
* 高级调试器支持:: 
* 线程本地存储支持:: 

线程状态和全局解释器锁

* Releasing the GIL from extension code:: 
* 非Python创建的线程:: 
* Cautions about fork(): Cautions about fork. 
* 高阶 API:: 
* Low-level API:: 

子解释器支持

* 错误和警告:: 

线程本地存储支持

* Thread Specific Storage (TSS) API: Thread Specific Storage TSS API. 
* Thread Local Storage (TLS) API: Thread Local Storage TLS API. 

Thread Specific Storage (TSS) API

* Dynamic Allocation:: 
* 方法: 方法<4>. 

Python初始化配置

* PyWideStringList:: 
* PyStatus:: 
* PyPreConfig:: 
* Preinitialization with PyPreConfig:: 
* PyConfig:: 
* Initialization with PyConfig:: 
* Isolated Configuration:: 
* Python Configuration:: 
* 路径配置:: 
* Py_RunMain(): Py_RunMain. 
* Py_GetArgcArgv(): Py_GetArgcArgv. 
* Multi-Phase Initialization Private Provisional API:: 

内存管理

* 概述: 概述<16>. 
* 原始内存接口:: 
* 内存接口:: 
* 对象分配器:: 
* 默认内存分配器:: 
* 自定义内存分配器:: 
* pymalloc 分配器:: 
* tracemalloc C API:: 
* 示例: 示例<51>. 

pymalloc 分配器

* 自定义 pymalloc Arena 分配器:: 

对象实现支持

* 在堆中分配对象:: 
* 公用对象的结构:: 
* Type 对象: Type 对象<2>. 
* Number Object Structures:: 
* Mapping Object Structures:: 
* Sequence Object Structures:: 
* Buffer Object Structures:: 
* Async Object Structures:: 
* Slot Type typedefs:: 
* 例子: 例子<2>. 
* 使对象类型支持循环垃圾回收:: 

公用对象的结构

* 基本的对象类型和宏:: 
* Implementing functions and methods:: 
* Accessing attributes of extension types:: 

Type 对象

* 快速参考: 快速参考<2>. 
* PyTypeObject 定义:: 
* PyObject 槽位:: 
* PyVarObject 槽位:: 
* PyTypeObject 槽:: 
* Heap Types:: 

快速参考

* "tp 槽":: 
* 子方法槽（方法域）:: 
* 槽位 typedef:: 

分发 Python 模块

* 关键术语:: 
* 开源许可与协作:: 
* 安装相关工具:: 
* 阅读 Python 打包用户指南:: 
* 我该如何...？: 我该如何 ？. 

我该如何...？

* ...为我的项目选择一个名字？: 为我的项目选择一个名字？. 
* ...创建和分发二进制扩展？: 创建和分发二进制扩展？. 

安装 Python 模块

* 关键术语: 关键术语<2>. 
* 基本使用: 基本使用<2>. 
* 我应如何 ...？: 我应如何 ？. 
* 常见的安装问题:: 

我应如何 ...？

* ... 在 Python 3.4 之前的 Python 版本中安装 pip ？: 在 Python 3 4 之前的 Python 版本中安装 pip ？. 
* ... 只为当前用户安装软件包？: 只为当前用户安装软件包？. 
* ... 安装科学计算类 Python 软件包？: 安装科学计算类 Python 软件包？. 
* ... 使用并行安装的多个 Python 版本？: 使用并行安装的多个 Python 版本？. 

常见的安装问题

* 在 Linux 的系统 Python 版本上安装:: 
* 未安装 pip:: 
* 安装二进制编译扩展:: 

Python 常用指引

* 将 Python 2 代码迁移到 Python 3:: 
* 将扩展模块移植到 Python 3:: 
* 用 Python 进行 Curses 编程:: 
* 描述器使用指南:: 
* 函数式编程指引:: 
* 日志 HOWTO:: 
* 日志操作手册:: 
* 正则表达式HOWTO:: 
* 套接字编程指南:: 
* 排序指南:: 
* Unicode 指南:: 
* 如何利用 urllib 包获取网络资源:: 
* Argparse 教程:: 
* ipaddress模块介绍:: 
* Argument Clinic 的用法:: 
* 使用 DTrace 和 SystemTap 检测CPython:: 

将 Python 2 代码迁移到 Python 3

* 简要说明:: 
* 详情:: 

详情

* 删除对Python 2.6及更早版本的支持: 删除对Python 2 6及更早版本的支持. 
* 确保你在你的`@w{`}setup.py`@w{`}文件中指定适当的版本支持: 确保你在你的`@w{`}setup py`@w{`}文件中指定适当的版本支持. 
* 良好的测试覆盖率:: 
* 了解Python 2 和 3之间的区别:: 
* 更新代码:: 
* 防止兼容性退步:: 
* 检查哪些依赖性会阻碍你的过渡:: 
* 更新你的`@w{`}setup.py`@w{`}文件以表示对Python 3的兼容: 更新你的`@w{`}setup py`@w{`}文件以表示对Python 3的兼容. 
* 使用持续集成以保持兼容:: 
* 考虑使用可选的静态类型检查:: 

更新代码

* 除法:: 
* 文本与二进制数据:: 
* 使用特征检测而不是版本检测:: 

用 Python 进行 Curses 编程

* curses 是什么？:: 
* 开始和结束 curses 应用程序:: 
* 窗口和面板:: 
* 显示文字:: 
* 用户输入:: 
* 更多的信息:: 

curses 是什么？

* Python 的 curses 模块:: 

显示文字

* 属性和颜色:: 

描述器使用指南

* 入门: 入门<2>. 
* 完整的实际例子:: 
* 技术教程:: 
* 纯 Python 等价实现:: 

入门

* 简单示例：返回常量的描述器:: 
* 动态查找:: 
* 托管属性:: 
* 定制名称:: 
* 结束语:: 

完整的实际例子

* 验证器类:: 
* 自定义验证器:: 
* 实际应用:: 

技术教程

* 摘要:: 
* 定义与介绍:: 
* 描述器协议:: 
* 描述器调用概述:: 
* 通过实例调用:: 
* 通过类调用:: 
* 通过 super 调用:: 
* 调用逻辑总结:: 
* 自动名称通知:: 
* ORM （对象关系映射）示例:: 

纯 Python 等价实现

* 属性: 属性<2>. 
* 函数和方法:: 
* 方法的种类:: 
* 静态方法:: 
* 类方法:: 
* 成员对象和 __slots__:: 

函数式编程指引

* 概述: 概述<17>. 
* 迭代器: 迭代器<2>. 
* 生成器表达式和列表推导式:: 
* 生成器: 生成器<2>. 
* 内置函数: 内置函数<2>. 
* itertools 模块:: 
* functools 模块:: 
* 小函数和 lambda 表达式:: 
* 修订记录和致谢:: 
* 引用文献:: 

概述

* 形式证明:: 
* 模块化:: 
* 易于调试和测试:: 
* 组合性:: 

迭代器

* 支持迭代器的数据类型:: 

生成器

* 向生成器传递值:: 

itertools 模块

* 创建新的迭代器:: 
* 对元素使用函数:: 
* 选择元素:: 
* 组合函数:: 
* 为元素分组:: 

functools 模块

* operator 模块:: 

引用文献

* 通用文献:: 
* Python 相关:: 
* Python 文档:: 

日志 HOWTO

* 日志基础教程:: 
* 进阶日志教程:: 
* 日志级别: 日志级别<2>. 
* 有用的处理器:: 
* 记录日志时引发的异常:: 
* 使用任意对象作为消息:: 
* 优化:: 

日志基础教程

* 什么时候使用日志:: 
* 一个简单的例子: 一个简单的例子<2>. 
* 记录日志到文件:: 
* 从多个模块记录日志:: 
* 记录变量数据:: 
* 更改显示消息的格式:: 
* 在消息中显示日期/时间:: 
* 后续步骤:: 

进阶日志教程

* 记录流程:: 
* 记录器:: 
* 处理器:: 
* 格式器:: 
* 配置日志记录:: 
* 如果没有提供配置会发生什么:: 
* 配置库的日志记录:: 

日志级别

* 自定义级别:: 

日志操作手册

* 在多个模块中使用日志:: 
* 在多个线程中记录日志:: 
* 多个 handler 和多种 formatter:: 
* 在多个地方记录日志:: 
* 日志配置服务器示例:: 
* 处理日志 handler 的阻塞:: 
* 通过网络收发日志事件:: 
* 在自己的输出日志中添加上下文信息:: 
* 在单个文件中记录多个进程的日志:: 
* 利用日志文件轮换机制:: 
* 日志的其他格式:: 
* 自定义 LogRecord:: 
* 子类化 QueueHandler - ZeroMQ 示例:: 
* 子类化 QueueListener —— ZeroMQ 示例:: 
* 基于字典进行日志配置的示例:: 
* 利用 rotator 和 namer 自定义日志轮换操作:: 
* 更详细的多进程日志示例:: 
* 在发送给 SysLogHandler 的信息中插入一个 BOM。:: 
* 结构化日志的实现代码:: 
* 利用 dictConfig() 自定义 handler: 利用 dictConfig 自定义 handler. 
* 生效于整个应用程序的格式化样式:: 
* 用 dictConfig() 配置过滤器: 用 dictConfig 配置过滤器. 
* 异常信息的自定义格式化:: 
* 语音播报日志信息:: 
* 缓冲日志信息并按条件输出:: 
* 通过配置将时间格式化为 UTC（GMT）格式:: 
* 用上下文管理器选择性记录日志:: 
* 命令行日志应用起步:: 
* 用作日志的 Qt GUI 程序:: 
* 理应避免的用法:: 

通过网络收发日志事件

* 在生产中运行日志套接字侦听器:: 

在自己的输出日志中添加上下文信息

* 利用 LoggerAdapter 传递上下文信息:: 
* 利用 Filter 传递上下文信息:: 

利用 LoggerAdapter 传递上下文信息

* 利用非字典对象传入上下文信息:: 

在单个文件中记录多个进程的日志

* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法. 
* 使用 Gunicorn 和 uWSGI 来部署 Web 应用程序:: 

生效于整个应用程序的格式化样式

* LogRecord 工厂的用法:: 
* 自定义日志信息对象的使用:: 

理应避免的用法

* 多次打开同一个日志文件:: 
* 将日志对象用作属性或传递参数:: 
* 给日志库代码添加 NullHandler 之外的其他 handler:: 
* 创建大量的日志对象:: 

正则表达式HOWTO

* 概述: 概述<18>. 
* 简单模式:: 
* 使用正则表达式:: 
* 更多模式能力:: 
* 修改字符串:: 
* 常见问题:: 
* 反馈:: 

简单模式

* 匹配字符:: 
* 重复:: 

使用正则表达式

* 编译正则表达式:: 
* 反斜杠灾难:: 
* 应用匹配:: 
* 模块级别函数:: 
* 编译标志:: 

更多模式能力

* 更多元字符:: 
* 分组:: 
* 非捕获和命名组:: 
* 前向断言:: 

修改字符串

* 分割字符串:: 
* 搜索和替换:: 

常见问题

* 使用字符串方法:: 
* match() 和 search(): match 和 search. 
* 贪婪与非贪婪:: 
* 使用 re.VERBOSE: 使用 re VERBOSE. 

套接字编程指南

* 套接字:: 
* 创建套接字: 创建套接字<2>. 
* 使用一个套接字:: 
* 断开连接:: 
* 非阻塞的套接字:: 

套接字

* 历史:: 

创建套接字

* 进程间通信:: 

使用一个套接字

* 二进制数据:: 

断开连接

* 套接字何时销毁:: 

排序指南

* 基本排序:: 
* 关键函数:: 
* Operator 模块函数:: 
* 升序和降序:: 
* 排序稳定性和排序复杂度:: 
* 使用装饰-排序-去装饰的旧方法:: 
* 使用 cmp 参数的旧方法:: 
* 其它:: 

Unicode 指南

* Unicode 概述:: 
* Python对Unicode的支持:: 
* Unicode 数据的读写:: 
* 致谢: 致谢<10>. 

Unicode 概述

* 定义:: 
* 编码:: 
* 引用文献: 引用文献<2>. 

Python对Unicode的支持

* 字符串类型:: 
* 转换为字节:: 
* Python 源代码中的 Unicode 文字:: 
* Unicode属性:: 
* 字符串比较:: 
* Unicode 正则表达式:: 
* 引用文献: 引用文献<3>. 

Unicode 数据的读写

* Unicode 文件名:: 
* 识别 Unicode 的编程技巧:: 
* 引用文献: 引用文献<4>. 

识别 Unicode 的编程技巧

* 在文件编码格式之间进行转换:: 
* 编码格式未知的文件:: 

如何利用 urllib 包获取网络资源

* 概述: 概述<19>. 
* 获取 URL 资源:: 
* 异常的处理:: 
* info 和 geturl 方法:: 
* Opener 和 Handler:: 
* 基本认证:: 
* 代理:: 
* 套接字与分层:: 
* 脚注:: 

获取 URL 资源

* 数据:: 
* HTTP 头部信息:: 

异常的处理

* URLError:: 
* HTTPError:: 
* 总之:: 

HTTPError

* 错误代码:: 

总之

* 第一种方案:: 
* 第二种方案:: 

Argparse 教程

* 概念:: 
* 基础: 基础<2>. 
* 位置参数介绍:: 
* 可选参数介绍:: 
* 结合位置参数和可选参数:: 
* 进行一些小小的改进:: 
* 后记:: 

可选参数介绍

* 短选项:: 

进行一些小小的改进

* 矛盾的选项:: 

ipaddress模块介绍

* 创建 Address/Network/Interface 对象:: 
* 审查 Address/Network/Interface 对象:: 
* Network 作为 Address 列表:: 
* 比较: 比较<3>. 
* 将IP地址与其他模块一起使用:: 
* 实例创建失败时获取更多详细信息:: 

创建 Address/Network/Interface 对象

* 关于IP版本的说明:: 
* IP主机地址:: 
* 定义网络:: 
* 主机接口:: 

Argument Clinic 的用法

* Argument Clinic 的设计目标:: 
* 基本概念和用法:: 
* 函数的转换:: 
* 进阶:: 

进阶

* 符号化默认值:: 
* 对 Argument Clinic 生成的 C 函数和变量进行重命名:: 
* 利用 PyArg_UnpackTuple 对函数进行转换:: 
* 可选参数组:: 
* 采用真正的 Argument Clinic 转换器，而不是 “传统转换器”:: 
* Py_buffer:: 
* 高级转换器:: 
* 参数的默认值:: 
* 默认值 NULL:: 
* 设为默认值的表达式:: 
* 返回转换器:: 
* 复制已有的函数:: 
* 调用 Python 代码:: 
* 参数 self 转换器的用法:: 
* 编写自定义转换器:: 
* 编写自定义的返回转换器:: 
* METH_O 和 METH_NOARGS:: 
* tp_new 和 tp_init functions:: 
* 改变和重定向 Clinic 的输出:: 
* #ifdef 使用技巧:: 
* 在 Python 文件中使用 Argument Clinic:: 

使用 DTrace 和 SystemTap 检测CPython

* 启用静态标记:: 
* 静态DTrace探针:: 
* 静态SystemTap标记:: 
* 可用的静态标记:: 
* SystemTap Tapsets:: 
* 示例: 示例<52>. 

Python 常见问题

* Python常见问题:: 
* 编程常见问题:: 
* 设计和历史常见问题:: 
* 代码库和插件 FAQ:: 
* 扩展/嵌入常见问题:: 
* Python在Windows上的常见问题:: 
* 图形用户界面（GUI）常见问题:: 
* “为什么我的电脑上安装了 Python ？”:: 

Python常见问题

* 一般信息:: 
* 现实世界中的 Python:: 

一般信息

* 什么是 Python？:: 
* 什么是 Python 软件基金会？:: 
* 使用 Python 是否存在版权限制？:: 
* 创造 Python 的最初理由是什么？:: 
* Python 适合做什么？:: 
* Python 版本的编号形式是怎样的？:: 
* 我应如何获取一份 Python 源代码的副本？:: 
* 我应如何获取 Python 的文档？:: 
* 我之前从未接触过编程。 哪里有 Python 的教程？:: 
* 是否有专门针对 Python 的新闻组或邮件列表？:: 
* 我应如何获取 Python 的公开测试版本？:: 
* 我应如何为 Python 提交错误报告和补丁？:: 
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？:: 
* 是否有任何 Python 相关的书籍？:: 
* www.python.org 具体位于世界上的哪个地点？: www python org 具体位于世界上的哪个地点？. 
* 为何命名为 Python？:: 
* 我必须喜欢 "Monty Python 的飞行马戏团" 吗？:: 

现实世界中的 Python

* Python 有多稳定？:: 
* 有多少人在使用 Python？:: 
* 有哪些重要的项目是用 Python 开发的？:: 
* 在未来可以期待 Python 将有什么新进展？:: 
* 提议对 Python 加入不兼容的更改是否合理？:: 
* Python 是一种对编程初学者友好的语言吗？:: 

编程常见问题

* 一般问题:: 
* 语言核心内容:: 
* 数字和字符串:: 
* 性能: 性能<4>. 
* 序列（元组/列表）:: 
* 对象:: 
* 模块: 模块<3>. 

一般问题

* Python 有没有提供带有断点、单步调试等功能的源码级调试器？:: 
* 是否有能帮助寻找漏洞或执行静态分析的工具？:: 
* 如何由 Python 脚本创建能独立运行的二进制程序？:: 
* 是否有 Python 编码标准或风格指南？:: 

语言核心内容

* 变量明明有值，为什么还会出现 UnboundLocalError？:: 
* Python 的局部变量和全局变量有哪些规则？:: 
* 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？:: 
* 如何跨模块共享全局变量？:: 
* 导入模块的“最佳实践”是什么？:: 
* 为什么对象之间会共享默认值？:: 
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？:: 
* 形参和实参之间有什么区别？:: 
* 为什么修改列表 'y' 也会更改列表 'x'？:: 
* 如何编写带有输出参数的函数（按照引用调用）？:: 
* 如何在 Python 中创建高阶函数？:: 
* 如何复制 Python 对象？:: 
* 如何找到对象的方法或属性？:: 
* 如何用代码获取对象的名称？:: 
* 逗号运算符的优先级是什么？:: 
* 是否提供等价于 C 语言 "?;" 三目运算符的东西？: 是否提供等价于 C 语言 "? " 三目运算符的东西？. 
* 是否可以用 Python 编写让人眼晕的单行程序?:: 
* 函数形参列表中的斜杠（/）是什么意思？:: 

数字和字符串

* 如何给出十六进制和八进制整数？:: 
* 为什么 -22 // 10 会返回 -3 ？:: 
* 我如何获得 int 字面属性而不是 SyntaxError ？:: 
* 如何将字符串转换为数字？:: 
* 如何将数字转换为字符串？:: 
* 如何修改字符串？:: 
* 如何使用字符串调用函数/方法？:: 
* 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？. 
* 是否有 scanf() 或 sscanf() 的等价函数？: 是否有 scanf 或 sscanf 的等价函数？. 
* 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？:: 

性能

* 我的程序太慢了。该如何加快速度？:: 
* 将多个字符串连接在一起的最有效方法是什么？:: 

序列（元组/列表）

* 如何在元组和列表之间进行转换？:: 
* 什么是负数索引？:: 
* 序列如何以逆序遍历？:: 
* 如何从列表中删除重复项？:: 
* 如何从列表中删除多个项？:: 
* 如何在 Python 中创建数组？:: 
* 如何创建多维列表？:: 
* 如何将方法应用于一系列对象？:: 
* 为什么 a_tuple[i] += ['item'] 会引发异常？:: 
* 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？:: 
* 如何根据另一个列表的值对某列表进行排序？:: 

对象

* 什么是类？:: 
* 什么是方法？:: 
* 什么是 self ？:: 
* 如何检查对象是否为给定类或其子类的一个实例？:: 
* 什么是委托？:: 
* 如何在派生类中调用被重载的基类方法?:: 
* 如何让代码更容易对基类进行修改？:: 
* 如何创建静态类数据和静态类方法？:: 
* 在 Python 中如何重载构造函数（或方法）？:: 
* 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。:: 
* 类定义了 __del__ 方法，但是删除对象时没有调用它。:: 
* 如何获取给定类的所有实例的列表？:: 
* 为什么 id() 的结果看起来不是唯一的？: 为什么 id 的结果看起来不是唯一的？. 
* 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？:: 
* 一个子类如何控制哪些数据被存储在一个不可变的实例中？:: 

模块

* 如何创建 .pyc 文件？: 如何创建 pyc 文件？. 
* 如何找到当前模块名称？:: 
* 如何让模块相互导入？:: 
* __import__('x.y.z') 返回的是 <module 'x'> ；该如何得到 z 呢？: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？. 
* 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？:: 

设计和历史常见问题

* 为什么Python使用缩进来分组语句？:: 
* 为什么简单的算术运算得到奇怪的结果？:: 
* 为什么浮点计算不准确？:: 
* 为什么Python字符串是不可变的？:: 
* 为什么必须在方法定义和调用中显式使用“self”？:: 
* 为什么不能在表达式中赋值？:: 
* 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？. 
* 为什么 join()是一个字符串方法而不是列表或元组方法？: 为什么 join 是一个字符串方法而不是列表或元组方法？. 
* 异常有多快？:: 
* 为什么Python中没有switch或case语句？:: 
* 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？:: 
* 为什么lambda表达式不能包含语句？:: 
* 可以将Python编译为机器代码，C或其他语言吗？:: 
* Python如何管理内存？:: 
* 为什么CPython不使用更传统的垃圾回收方案？:: 
* CPython退出时为什么不释放所有内存？:: 
* 为什么有单独的元组和列表数据类型？:: 
* 列表是如何在CPython中实现的？:: 
* 字典是如何在CPython中实现的？:: 
* 为什么字典key必须是不可变的？:: 
* 为什么 list.sort() 没有返回排序列表？: 为什么 list sort 没有返回排序列表？. 
* 如何在Python中指定和实施接口规范？:: 
* 为什么没有goto？:: 
* 为什么原始字符串（r-strings）不能以反斜杠结尾？:: 
* 为什么Python没有属性赋值的“with”语句？:: 
* 生成器为什么不支持 with 语句？:: 
* 为什么 if/while/def/class语句需要冒号？:: 
* 为什么Python在列表和元组的末尾允许使用逗号？:: 

代码库和插件 FAQ

* 通用的代码库问题:: 
* 通用任务:: 
* 线程相关:: 
* 输入输出:: 
* 网络 / Internet 编程:: 
* 数据库:: 
* 数学和数字:: 

通用的代码库问题

* 如何找到可以用来做 XXX 的模块或应用？:: 
* math.py（socket.py，regex.py 等）的源文件在哪？: math py（socket py，regex py 等）的源文件在哪？. 
* 在 Unix 中怎样让 Python 脚本可执行？:: 
* Python 中有 curses/termcap 包吗？:: 
* Python 中存在类似 C 的 onexit() 函数的东西吗？: Python 中存在类似 C 的 onexit 函数的东西吗？. 
* 为什么我的信号处理函数不能工作？:: 

通用任务

* 怎样测试 Python 程序或组件？:: 
* 怎样用 docstring 创建文档？:: 
* 怎样一次只获取一个按键？:: 

线程相关

* 程序中怎样使用线程？:: 
* 我的线程都没有运行，为什么？:: 
* 如何将任务分配给多个工作线程？:: 
* 怎样修改全局变量是线程安全的？:: 
* 不能删除全局解释器锁吗？:: 

输入输出

* 怎样删除文件？（以及其他文件相关的问题……）:: 
* 怎样复制文件？:: 
* 怎样读取（或写入）二进制数据？:: 
* 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？. 
* 怎样访问（RS232）串口？:: 
* 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？. 

网络 / Internet 编程

* Python 中的 WWW 工具是什么？:: 
* 怎样模拟发送 CGI 表单（METHOD=POST）？:: 
* 生成 HTML 需要使用什么模块？:: 
* 怎样使用 Python 脚本发送邮件？:: 
* socket 的 connect() 方法怎样避免阻塞？: socket 的 connect 方法怎样避免阻塞？. 

数据库

* Python 中有数据库包的接口吗？:: 
* 在 Python 中如何实现持久化对象？:: 

数学和数字

* Python 中怎样生成随机数？:: 

扩展/嵌入常见问题

* 可以使用 C 语言创建自己的函数吗？:: 
* 可以使用 C++ 语言创建自己的函数吗？:: 
* C很难写，有没有其他选择？:: 
* 如何在 C 中执行任意 Python 语句？:: 
* 如何在 C 中对任意 Python 表达式求值？:: 
* 如何从Python对象中提取C的值？:: 
* 如何使用Py_BuildValue()创建任意长度的元组？: 如何使用Py_BuildValue 创建任意长度的元组？. 
* 如何从C调用对象的方法？:: 
* 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？. 
* 如何从C访问用Python编写的模块？:: 
* 如何在 Python 中对接 C ++ 对象？:: 
* 我使用Setup文件添加了一个模块，为什么make失败了？:: 
* 如何调试扩展？:: 
* 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?:: 
* 如何区分“输入不完整”和“输入无效”？:: 
* 如何找到未定义的g++符号__builtin_new或__pure_virtual？:: 
* 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？:: 

Python在Windows上的常见问题

* 我怎样在Windows下运行一个Python程序？:: 
* 我怎么让 Python 脚本可执行？:: 
* 为什么有时候 Python 程序会启动缓慢？:: 
* 我怎样使用 Python 脚本制作可执行文件？:: 
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？. 
* 我怎样将 Python 嵌入一个 Windows 程序？:: 
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？:: 
* 如何在不阻塞的情况下检查按键？:: 

图形用户界面（GUI）常见问题

* 图形界面常见问题:: 
* Python 有哪些 GUI 工具包？:: 
* 有关Tkinter的问题:: 

有关Tkinter的问题

* 我怎样“冻结”Tkinter程序？:: 
* 在等待 I/O 操作时能够处理 Tk 事件吗？:: 
* 在Tkinter中键绑定不工作：为什么？:: 

“为什么我的电脑上安装了 Python ？”

* 什么是Python？:: 
* 为什么我的电脑上安装了 Python ？:: 
* 我能删除 Python 吗？:: 

文档说明

* Python 文档贡献者:: 

解决 Bug

* 文档错误:: 
* 使用 Python 的问题追踪系统:: 
* 开始为 Python 贡献您的知识:: 

历史和许可证

* 该软件的历史:: 
* 获取或以其他方式使用 Python 的条款和条件:: 
* 被收录软件的许可证与鸣谢:: 

获取或以其他方式使用 Python 的条款和条件

* 用于 PYTHON 3.9.17 的 PSF 许可协议: 用于 PYTHON 3 9 17 的 PSF 许可协议. 
* 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议. 
* 用于 PYTHON 1.6.1 的 CNRI 许可协议: 用于 PYTHON 1 6 1 的 CNRI 许可协议. 
* 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议. 
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.17 DOCUMENTATION: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 9 17 DOCUMENTATION. 

被收录软件的许可证与鸣谢

* Mersenne Twister:: 
* 套接字: 套接字<2>. 
* 异步套接字服务:: 
* Cookie 管理:: 
* 执行追踪:: 
* UUencode 与 UUdecode 函数:: 
* XML 远程过程调用:: 
* test_epoll:: 
* Select kqueue:: 
* SipHash24:: 
* strtod 和 dtoa:: 
* OpenSSL:: 
* expat:: 
* libffi:: 
* zlib: zlib<3>. 
* cfuhash:: 
* libmpdec:: 
* W3C C14N 测试套件:: 

分发 Python 模块（遗留版本）

* Distutils 模块介绍:: 
* 编写安装脚本:: 
* 编写设置脚本的配置文件:: 
* 创建源代码分发包:: 
* 创建构建分布:: 
* Distutils 示例:: 
* 扩展 Distutils:: 
* 命令参考:: 
* API参考引用:: 

Distutils 模块介绍

* 概念和术语:: 
* 一个简单的例子: 一个简单的例子<3>. 
* 通用的 Python 术语:: 
* Distutils 特定的术语:: 

编写安装脚本

* 列出全部的包:: 
* 列出单独的模块:: 
* 描述扩展模块:: 
* Relationships between Distributions and Packages:: 
* Installing Scripts:: 
* Installing Package Data:: 
* Installing Additional Files:: 
* Additional meta-data:: 
* Debugging the setup script:: 

描述扩展模块

* 扩展名和软件包:: 
* 扩展资源文件:: 
* 预处理器选项:: 
* 库选项:: 
* 其他选项: 其他选项<2>. 

创建源代码分发包

* 指定要分发的文件:: 
* 声明相关选项:: 

创建构建分布

* 创建RPM软件包:: 
* Creating Windows Installers:: 
* 在 Windows 上的交叉编译:: 
* Vista User Access Control (UAC): Vista User Access Control UAC. 

在 Windows 上的交叉编译

* 安装后脚本:: 

Distutils 示例

* 纯 Python 分发（通过 module）:: 
* 纯 Python 分发（通过 包）:: 
* 单个扩展模块:: 
* 检查一个包:: 
* 读取元数据:: 

扩展 Distutils

* 集成新的命令:: 
* 添加新的发布类型:: 

命令参考

* 安装模块; install 命令族: 安装模块 install 命令族. 
* 创建源码发行包; sdist 命令: 创建源码发行包 sdist 命令. 

安装模块: install 命令族

* install_data:: 
* install_scripts:: 

API参考引用

* distutils.core: distutils core --- 分发包功能的核心. 分发包功能的核心
* distutils.ccompiler: distutils ccompiler --- CCompiler基类. CCompiler基类
* distutils.unixccompiler: distutils unixccompiler --- Unix C Compiler. Unix C Compiler
* distutils.msvccompiler: distutils msvccompiler --- Microsoft Compiler. Microsoft Compiler
* distutils.bcppcompiler: distutils bcppcompiler --- Borland Compiler. Borland Compiler
* distutils.cygwincompiler: distutils cygwincompiler --- Cygwin Compiler. Cygwin Compiler
* distutils.archive_util: distutils archive_util --- Archiving utilities. Archiving utilities
* distutils.dep_util: distutils dep_util --- Dependency checking. Dependency checking
* distutils.dir_util: distutils dir_util --- Directory tree operations. Directory tree operations
* distutils.file_util: distutils file_util --- Single file operations. Single file operations
* distutils.util: distutils util --- Miscellaneous other utility functions. Miscellaneous other utility functions
* distutils.dist: distutils dist --- The Distribution class. The Distribution class
* distutils.extension: distutils extension --- The Extension class. The Extension class
* distutils.debug: distutils debug --- Distutils debug mode. Distutils debug mode
* distutils.errors: distutils errors --- Distutils exceptions. Distutils exceptions
* distutils.fancy_getopt: distutils fancy_getopt --- Wrapper around the standard getopt module. Wrapper around the standard getopt module
* distutils.filelist: distutils filelist --- The FileList class. The FileList class
* distutils.log: distutils log --- Simple PEP 282-style logging. Simple PEP 282-style logging
* distutils.spawn: distutils spawn --- Spawn a sub-process. Spawn a sub-process
* distutils.sysconfig: distutils sysconfig --- System configuration information. System configuration information
* distutils.text_file: distutils text_file --- The TextFile class. The TextFile class
* distutils.version: distutils version --- Version number classes. Version number classes
* distutils.cmd: distutils cmd --- Abstract base class for Distutils commands. Abstract base class for Distutils commands
* Creating a new Distutils command:: 
* distutils.command: distutils command --- Individual Distutils commands. Individual Distutils commands
* distutils.command.bdist: distutils command bdist --- Build a binary installer. Build a binary installer
* distutils.command.bdist_packager: distutils command bdist_packager --- Abstract base class for packagers. Abstract base class for packagers
* distutils.command.bdist_dumb: distutils command bdist_dumb --- Build a "dumb" installer. Build a "dumb" installer
* distutils.command.bdist_msi: distutils command bdist_msi --- Build a Microsoft Installer binary package. Build a Microsoft Installer binary package
* distutils.command.bdist_rpm: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: distutils command bdist_wininst --- Build a Windows installer. Build a Windows installer
* distutils.command.sdist: distutils command sdist --- Build a source distribution. Build a source distribution
* distutils.command.build: distutils command build --- Build all files of a package. Build all files of a package
* distutils.command.build_clib: distutils command build_clib --- Build any C libraries in a package. Build any C libraries in a package
* distutils.command.build_ext: distutils command build_ext --- Build any extensions in a package. Build any extensions in a package
* distutils.command.build_py: distutils command build_py --- Build the py/ pyc files of a package. Build the .py/.pyc files of a package
* distutils.command.build_scripts: distutils command build_scripts --- Build the scripts of a package. Build the scripts of a package
* distutils.command.clean: distutils command clean --- Clean a package build area. Clean a package build area
* distutils.command.config: distutils command config --- Perform package configuration. Perform package configuration
* distutils.command.install: distutils command install --- Install a package. Install a package
* distutils.command.install_data: distutils command install_data --- Install data files from a package. Install data files from a package
* distutils.command.install_headers: distutils command install_headers --- Install C/C++ header files from a package. Install C/C++ header files from a package
* distutils.command.install_lib: distutils command install_lib --- Install library files from a package. Install library files from a package
* distutils.command.install_scripts: distutils command install_scripts --- Install script files from a package. Install script files from a package
* distutils.command.register: distutils command register --- Register a module with the Python Package Index. Register a module with the Python Package Index
* distutils.command.check: distutils command check --- Check the meta-data of a package. Check the meta-data of a package

安装Python模块（旧版）

* 概述: 概述<20>. 
* 标准构建及安装:: 
* Alternate Installation:: 
* 自定义安装:: 
* Distutils 配置文件Configuration Files:: 
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks. 

概述

* 基于分布式系统的源代码分发:: 

标准构建及安装

* 平台差异:: 
* 拆分任务:: 
* How building works:: 
* How installation works:: 

Alternate Installation

* Alternate installation; the user scheme: Alternate installation the user scheme. 
* Alternate installation; the home scheme: Alternate installation the home scheme. 
* Alternate installation; Unix (the prefix scheme): Alternate installation Unix the prefix scheme. 
* Alternate installation; Windows (the prefix scheme): Alternate installation Windows the prefix scheme. 

自定义安装

* 修改 Python 的搜索路径:: 

Distutils 配置文件Configuration Files

* Location and names of config files:: 
* Syntax of config files:: 

Building Extensions: Tips and Tricks

* Tweaking compiler/linker flags:: 
* Using non-Microsoft compilers on Windows:: 

Using non-Microsoft compilers on Windows

* Borland/CodeGear C++:: 
* GNU C / Cygwin / MinGW:: 

GNU C / Cygwin / MinGW

* Older Versions of Python and MinGW:: 

@end detailmenu
@end menu

@node Python 有什么新变化？,Python 教程,Top,Top
@anchor{whatsnew/index doc}@anchor{150}@anchor{whatsnew/index python-documentation-contents}@anchor{151}@anchor{whatsnew/index what-s-new-in-python}@anchor{152}@anchor{whatsnew/index whatsnew-index}@anchor{153}
@chapter Python 有什么新变化？


这个“Python 有什么新变化？”系列内容会带您浏览 Python 大版本之间重要的变化。在新版发布后，如果您希望掌握最新变化，请务必阅读这些内容。

@menu
* Python 3.9 有什么新变化: Python 3 9 有什么新变化. 
* Python 3.8 有什么新变化: Python 3 8 有什么新变化. 
* Python 3.7 有什么新变化: Python 3 7 有什么新变化. 
* Python 3.6 有什么新变化: Python 3 6 有什么新变化. 
* Python 3.5 有什么新变化: Python 3 5 有什么新变化. 
* Python 3.4 有什么新变化: Python 3 4 有什么新变化. 
* Python 3.3 有什么新变化: Python 3 3 有什么新变化. 
* Python 3.2 有什么新变化: Python 3 2 有什么新变化. 
* Python 3.1 有什么新变化: Python 3 1 有什么新变化. 
* Python 3.0 有什么新变化: Python 3 0 有什么新变化. 
* Python 2.7 有什么新变化: Python 2 7 有什么新变化. 
* Python 2.6 有什么新变化: Python 2 6 有什么新变化. 
* Python 2.5 有什么新变化: Python 2 5 有什么新变化. 
* Python 2.4 有什么新变化: Python 2 4 有什么新变化. 
* Python 2.3 有什么新变化: Python 2 3 有什么新变化. 
* Python 2.2 有什么新变化: Python 2 2 有什么新变化. 
* Python 2.1 有什么新变化: Python 2 1 有什么新变化. 
* Python 2.0 有什么新变化: Python 2 0 有什么新变化. 
* 更新日志:: 

@end menu

@node Python 3 9 有什么新变化,Python 3 8 有什么新变化,,Python 有什么新变化？
@anchor{whatsnew/3 9 doc}@anchor{154}@anchor{whatsnew/3 9 what-s-new-in-python-3-9}@anchor{155}
@section Python 3.9 有什么新变化


@*发布版本: 
3.9.17


@*日期: 
七月 04, 2023


@*编者: 
Łukasz Langa


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Your text might get
@c rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes will be too small
@c or esoteric to include.  If such a change is added to the text,
@c it might get removed during final editing.
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

本文介绍了 Python 3.9 相比 3.8 的新特性。 Python 3.9 发布于 2020 年 10 月 5 日。

详情请参阅 @ref{156,,更新日志}。


@subsubheading 参见


@geindex Python 提高建议; PEP 596
PEP 596@footnote{https://www.python.org/dev/peps/pep-0596} - Python 3.9 发布计划


@menu
* 摘要 - 发布重点:: 
* 请检查代码中的 DeprecationWarning。:: 
* 新的特性:: 
* 其他语言特性修改:: 
* 新增模块:: 
* 改进的模块:: 
* 性能优化:: 
* 弃用:: 
* 移除:: 
* 移植到 Python 3.9: 移植到 Python 3 9. 
* 构建的改变:: 
* C API 的改变:: 
* Python 3.9.1 中的重要变化: Python 3 9 1 中的重要变化. 
* Python 3.9.2 中的重要变化: Python 3 9 2 中的重要变化. 
* Python 3.9.3 中的重要变化: Python 3 9 3 中的重要变化. 
* Python 3.9.5 中的重要变化: Python 3 9 5 中的重要变化. 
* Notable security feature in 3.9.14: Notable security feature in 3 9 14. 
* Notable Changes in 3.9.17: Notable Changes in 3 9 17. 

@end menu

@node 摘要 - 发布重点,请检查代码中的 DeprecationWarning。,,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 summary-release-highlights}@anchor{157}
@subsection 摘要 - 发布重点


@c This section singles out the most important changes in Python 3.9.
@c Brevity is key.

新的语法特性：


@itemize *

@item 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}，为 @code{dict} 增加合并运算符；

@item 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585}，标准多项集中的类型标注泛型。

@item 
@geindex Python 提高建议; PEP 614
PEP 614@footnote{https://www.python.org/dev/peps/pep-0614}，放宽对装饰器的语法限制。
@end itemize

新的内置特性：


@itemize *

@item 
@geindex Python 提高建议; PEP 616
PEP 616@footnote{https://www.python.org/dev/peps/pep-0616}，移除前缀和后缀的字符串方法。
@end itemize

标准库中的新特性:


@itemize *

@item 
@geindex Python 提高建议; PEP 593
PEP 593@footnote{https://www.python.org/dev/peps/pep-0593}，灵活函数和变量注解；

@item 
添加了 @ref{158,,os.pidfd_open()} 以允许不带竞争和信号的进程管理。
@end itemize

解释器的改进:


@itemize *

@item 
@geindex Python 提高建议; PEP 573
PEP 573@footnote{https://www.python.org/dev/peps/pep-0573}，从 C 扩展类型的方法快速访问模块状态；

@item 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617}，CPython 现在使用基于 PEG 的新解析器；

@item 
一些 Python 内置类型（range、tuple、set、frozenset、list、dict）现已使用 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590} vectorcall 加速；

@item 
垃圾回收不会因恢复的对象而阻塞；

@item 
一些 Python 模块（@code{_abc}、@ref{c,,audioop}、@code{_bz2}、@code{_codecs}、@code{_contextvars}、@code{_crypt}、@code{_functools}、@code{_json}、@code{_locale}、@ref{b1,,math}、@ref{c2,,operator}、@ref{e0,,resource}、@ref{10c,,time}、@code{_weakref}）现已使用 PEP 489 中定义的多段初始化；

@item 
一些标准库模块 (@ref{c,,audioop}、@ref{7,,ast}、@ref{8a,,grp}、@code{_hashlib}、@ref{d6,,pwd}、@code{_posixsubprocess}、@ref{dc,,random}、@ref{e5,,select}、@ref{f8,,struct}、@ref{104,,termios}、@ref{14d,,zlib}) 现已使用 PEP 384 中定义的稳定 ABI。
@end itemize

新的库模块：


@itemize *

@item 
@geindex Python 提高建议; PEP 615
PEP 615@footnote{https://www.python.org/dev/peps/pep-0615}，标准库的 @ref{14e,,zoneinfo} 模块现已支持 IANA 时区数据库；

@item 
图的拓扑排序实现现在已由新的 @ref{89,,graphlib} 模块提供。
@end itemize

发布进程的变化:


@itemize *

@item 
@geindex Python 提高建议; PEP 602
PEP 602@footnote{https://www.python.org/dev/peps/pep-0602}，CPython 采用年度发布周期。
@end itemize

@node 请检查代码中的 DeprecationWarning。,新的特性,摘要 - 发布重点,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 you-should-check-for-deprecationwarning-in-your-code}@anchor{159}
@subsection 请检查代码中的 DeprecationWarning。


Python 2.7 支持未终止时，为了实现向下兼容 Python 2.7，Python 3  保留了许多旧版功能。Python 2 的支持终止后，已经移除了一部分向下兼容层，剩余部分很快也会被移除。这几年，大部分兼容层都会触发 @ref{15a,,DeprecationWarning} 警告。例如，2012 年发布 Python 3.3 后，用 @code{collections.Mapping} 替代 @code{collections.abc.Mapping} 就会触发 @ref{15a,,DeprecationWarning}。

请用 @ref{15b,,-W} @code{default} 命令行选项测试应用程序来查看 @ref{15a,,DeprecationWarning} 和 @ref{15c,,PendingDeprecationWarning}，甚至可以用 @ref{15b,,-W} @code{error} 将它们视为错误。 可以用 @ref{15d,,警告过滤器} 忽略来自第三方代码的警告。

Python 3.9 是最后一个提供 Python 2 向下兼容层的版本，以给予 Python 项目维护者更多时间移除 Python 2 支持，添加 Python 3.9 支持。

@ref{1d,,collections} 模块中 @ref{15e,,抽象基类} 的别名，例如 @ref{15f,,collections.abc.Mapping} 的别名 @code{collections.Mapping} 会为向下兼容最后保留一个发行版。 这些内容将在 Python 3.10 中移除。

更通俗的说法是，请在 @ref{160,,Python 开发模式} 下运行测试，这样做有助于让代码兼容 Python 的后续版本。

注：一些前期已弃用的内容也将在此 Python 版本中移除。 详见 @ref{161,,移除} 一节。

@node 新的特性,其他语言特性修改,请检查代码中的 DeprecationWarning。,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 new-features}@anchor{162}
@subsection 新的特性


@menu
* 字典合并与更新运算符:: 
* 新增用于移除前缀和后缀的字符串方法:: 
* 标准多项集中的类型标注泛型:: 
* 新的解析器:: 

@end menu

@node 字典合并与更新运算符,新增用于移除前缀和后缀的字符串方法,,新的特性
@anchor{whatsnew/3 9 dictionary-merge-update-operators}@anchor{163}
@subsubsection 字典合并与更新运算符


合并 (@code{|}) 与更新 (@code{|=}) 运算符已被加入内置的 @ref{164,,dict} 类。 它们为现有的 @code{dict.update} 和 @code{@{**d1, **d2@}} 字典合并方法提供了补充。

示例:

@example
>>> x = @{"key1": "value1 from x", "key2": "value2 from x"@}
>>> y = @{"key2": "value2 from y", "key3": "value3 from y"@}
>>> x | y
@{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'@}
>>> y | x
@{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'@}
@end example

详见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。（Brandt Bucher 在 bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144} 中的贡献。）

@node 新增用于移除前缀和后缀的字符串方法,标准多项集中的类型标注泛型,字典合并与更新运算符,新的特性
@anchor{whatsnew/3 9 new-string-methods-to-remove-prefixes-and-suffixes}@anchor{165}
@subsubsection 新增用于移除前缀和后缀的字符串方法


增加了 @ref{166,,str.removeprefix(prefix)} 和 @ref{167,,str.removesuffix(suffix)} 用于方便地从字符串移除不需要的前缀或后缀。 也增加了 @code{bytes}, @code{bytearray} 以及 @code{collections.UserString} 的对应方法。 请参阅 
@geindex Python 提高建议; PEP 616
PEP 616@footnote{https://www.python.org/dev/peps/pep-0616} 了解详情。 （由 Dennis Sweeney 在 bpo-39939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39939} 中贡献。）

@node 标准多项集中的类型标注泛型,新的解析器,新增用于移除前缀和后缀的字符串方法,新的特性
@anchor{whatsnew/3 9 type-hinting-generics-in-standard-collections}@anchor{168}
@subsubsection 标准多项集中的类型标注泛型


在类型标注中现在你可以使用内置多项集类型例如 @code{list} 和 @code{dict} 作为通用类型而不必从 @code{typing} 导入对应的大写形式类型名 (例如 @code{List} 和 @code{Dict})。 标准库中的其他一些类型现在同样也是通用的，例如 @code{queue.Queue}。

示例:

@example
def greet_all(names: list[str]) -> None:
    for name in names:
        print("Hello", name)
@end example

详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585}。（由 Guido van Rossum、Ethan Smith 和 Batuhan Taşkaya 在 bpo-39481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39481} 中贡献。）

@node 新的解析器,,标准多项集中的类型标注泛型,新的特性
@anchor{whatsnew/3 9 new-parser}@anchor{169}
@subsubsection 新的解析器


Python 3.9 使用于基于 PEG@footnote{https://en.wikipedia.org/wiki/Parsing_expression_grammar} 的新解析器替代 LL(1)@footnote{https://en.wikipedia.org/wiki/LL_parser}。 新解析器的性能与旧解析器大致相当，但 PEG 在设计新语言特性时的形式化比 LL(1) 更灵活。 我们将在 Python 3.10 及之后版本中开始使用这种灵活性。

@ref{7,,ast} 模块会使用新解析器并会生成与旧解析器一致的 AST。

在 Python 3.10 中，旧解析器将被移除，依赖于它的所有功能也将被移除（主要是 @ref{c7,,parser} 模块，它早已被弃用）。  @emph{只有} 在 Python 3.9 中，你可以使用命令行开关 (@code{-X oldparser}) 或环境变量 (@code{PYTHONOLDPARSER=1}) 切换回 LL(1) 解析器。

请参阅 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617} 了解详情。 （由 Guido van Rossum, Pablo Galindo 和 Lysandros Nikolaou 在 bpo-40334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40334} 中贡献。）

@node 其他语言特性修改,新增模块,新的特性,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 other-language-changes}@anchor{16a}
@subsection 其他语言特性修改



@itemize *

@item 
@ref{16b,,__import__()} 现在会引发 @ref{16c,,ImportError} 而不是 @ref{16d,,ValueError}，后者曾经会在相对导入超出其最高层级包时发生。 （由 Ngalim Siregar 在 bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444} 中贡献。）

@item 
Python 现在会获取命令行中指定的脚本文件名 (例如: @code{python3 script.py}) 的绝对路径: @ref{1,,__main__} 模块的 @code{__file__} 属性将是一个绝对路径，而不是相对路径。 现在此路径在当前目录通过 @ref{16e,,os.chdir()} 被改变后仍将保持有效。 作为附带效果，回溯信息也将在此情况下为 @ref{1,,__main__} 模块帧显示绝对路径。 （由 Victor Stinner 在 bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443} 中贡献。）

@item 
在 @ref{160,,Python 开发模式} 以及调试编译版本中，现在会针对字符串编码和解码操作检查 @emph{encoding} 和 @emph{errors} 参数。 例如: @ref{16f,,open()}, @ref{170,,str.encode()} 和 @ref{171,,bytes.decode()}。

默认设置下，为保证性能，@emph{errors} 参数只会在第一次发生编码/解码错误时被检查，并且对于空字符串 @emph{encoding} 参数有时会被忽略。 （由 Victor Stinner 在 bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388} 中贡献。）

@item 
@code{"".replace("", s, n)} 对于所有非零的 @code{n} 都将返回 @code{s} 而不是空字符串。 现在此方法会与 @code{"".replace("", s)} 保持一致。 对于 @ref{172,,bytes} 和 @ref{173,,bytearray} 对象也有类似的修改。 （由 Serhiy Storchaka 在 bpo-28029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28029} 中贡献。）

@item 
任何有效的表达式现在都可被用作 @ref{174,,decorator}。 在之前版本中，相关语法则更为严格。 请参阅 
@geindex Python 提高建议; PEP 614
PEP 614@footnote{https://www.python.org/dev/peps/pep-0614} 了解详情。 （由 Brandt Bucher 在 bpo-39702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39702} 中贡献。）

@item 
改进了 @ref{122,,typing} 模块的帮助信息。 现在将为所有特殊形式和特殊通用别名 (例如 @code{Union} 和 @code{List}) 显示文档字符串。 使用 @ref{175,,help()} 时传入通用别名例如 @code{List[int]} 将显示对应实体类型 (这里对应的是 @code{list}) 的帮助信息。 （由 Serhiy Storchaka 在 bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257} 中贡献。）

@item 
@ref{176,,aclose()} / @ref{177,,asend()} / @ref{178,,athrow()} 的并行运行现在已被禁止，且 @code{ag_running} 现在会反映异步生成器的实际运行状态。 （由 Yury Selivanov 在 bpo-30773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30773} 中贡献。）

@item 
调用 @code{__iter__} 方法时发生的非预期错误不会再被 @ref{179,,in} 运算符以及 @ref{c2,,operator} 的 @ref{17a,,contains()}, @ref{17b,,indexOf()} 和 @ref{17c,,countOf()} 中的 @code{TypeError} 所掩盖。 （由 Serhiy Storchaka 在 bpo-40824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40824} 中贡献。）

@item 
未加圆括号的 lambda 表达式不能再作为推导式和生成器表达式的 @code{if} 子句的表达式部分。 请参阅 bpo-41848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41848} 和 bpo-43755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43755} 了解详情。
@end itemize

@node 新增模块,改进的模块,其他语言特性修改,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 new-modules}@anchor{17d}
@subsection 新增模块


@menu
* zoneinfo:: 
* graphlib:: 

@end menu

@node zoneinfo,graphlib,,新增模块
@anchor{whatsnew/3 9 zoneinfo}@anchor{17e}
@subsubsection zoneinfo


@ref{14e,,zoneinfo} 模块为标准库引入了 IANA 时区数据库。 它添加了 @ref{17f,,zoneinfo.ZoneInfo}，这是一个基于系统时区数据的实体 @ref{180,,datetime.tzinfo} 实现。

示例:

@example
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> # Daylight saving time
>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00
>>> dt.tzname()
'PDT'

>>> # Standard time
>>> dt += timedelta(days=7)
>>> print(dt)
2020-11-07 12:00:00-08:00
>>> print(dt.tzname())
PST
@end example

作为不包含 IANA 数据库的平台的一个回退数据源，还以第一方软件包的形式发布了 tzdata@footnote{https://pypi.org/project/tzdata/} 模块 -- 通过 PyPI 发行并由 CPython 核心团队维护。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 615

@item PEP 615@footnote{https://www.python.org/dev/peps/pep-0615} -- 在标准库中支持 IANA 时区数据库

PEP 由 Paul Ganssle 撰写并实现
@end table


@node graphlib,,zoneinfo,新增模块
@anchor{whatsnew/3 9 graphlib}@anchor{181}
@subsubsection graphlib


添加了新的 @ref{89,,graphlib} 模块，其中包含 @ref{182,,graphlib.TopologicalSorter} 类来提供图的拓扑排序功能。 （由 Pablo Galindo, Tim Peters 和 Larry Hastings 在 bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005} 中贡献。）

@node 改进的模块,性能优化,新增模块,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 improved-modules}@anchor{183}
@subsection 改进的模块


@menu
* ast:: 
* asyncio:: 
* compileall:: 
* concurrent.futures: concurrent futures. 
* curses:: 
* datetime:: 
* distutils:: 
* fcntl:: 
* ftplib:: 
* gc:: 
* hashlib:: 
* http:: 
* IDLE 与 idlelib:: 
* imaplib:: 
* importlib:: 
* inspect:: 
* ipaddress:: 
* math:: 
* multiprocessing:: 
* nntplib:: 
* os:: 
* pathlib:: 
* pdb:: 
* poplib:: 
* pprint:: 
* pydoc:: 
* random:: 
* signal:: 
* smtplib:: 
* socket:: 
* time:: 
* sys:: 
* tracemalloc:: 
* typing:: 
* unicodedata:: 
* venv:: 
* xml:: 

@end menu

@node ast,asyncio,,改进的模块
@anchor{whatsnew/3 9 ast}@anchor{184}
@subsubsection ast


将 @emph{indent} 选项添加到 @ref{185,,dump()}，这允许它产生多行缩进的输出。 （由 Serhiy Storchaka 在 bpo-37995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37995} 中贡献。）

添加了 @ref{186,,ast.unparse()} 作为 @ref{7,,ast} 模块中的一个函数，它可被用来反解析 @ref{187,,ast.AST} 对象并产生相应的代码字符串，当它被解析时将会产生一个等价的 @ref{187,,ast.AST} 对象。 （由 Pablo Galindo 和 Batuhan Taskaya 在 bpo-38870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38870} 中贡献。）

为 AST 节点添加了文档字符串，其中包含 ASDL 签名，可被用来构造对应的节点。 （由 Batuhan Taskaya 在 bpo-39638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39638} 中贡献。）

@node asyncio,compileall,ast,改进的模块
@anchor{whatsnew/3 9 asyncio}@anchor{188}
@subsubsection asyncio


出于重要的安全性考量，@ref{189,,asyncio.loop.create_datagram_endpoint()} 的 @emph{reuse_address} 形参不再被支持。 这是由 UDP 中的套接字选项 @code{SO_REUSEADDR} 的行为导致的。 更多细节请参阅 @code{loop.create_datagram_endpoint()} 的文档。 （由 Kyle Stanley, Antoine Pitrou 和 Yury Selivanov 在 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228} 中贡献。。）

添加了新的 @ref{18a,,coroutine} @ref{18b,,shutdown_default_executor()}，它可为等待 @ref{18c,,ThreadPoolExecutor} 结束关闭的默认执行器安排关闭日程操作。 此外，@ref{18d,,asyncio.run()} 已被更新以使用新的 @ref{18a,,coroutine}。 （由 Kyle Stanley 在 bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037} 中贡献。）

添加了 @ref{18e,,asyncio.PidfdChildWatcher}，这是一个 Linux 专属的子监视器实现，它负责轮询进程的文件描述符。 (bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692})

添加了新的 @ref{18a,,coroutine} @ref{18f,,asyncio.to_thread()}。 它主要被用于在单独线程中运行 IO 密集型函数以避免阻塞事件循环，实质上就相当于是 @ref{190,,run_in_executor()} 的高层级版本，可直接接受关键字参数。 （由 Kyle Stanley 和 Yury Selivanov 在 bpo-32309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32309} 中贡献。）

当由于超时而取消任务时，@ref{191,,asyncio.wait_for()} 现在将会等待直到也在 @emph{timeout} 值 <= 0 的情况下完成取消。 就像 timeout 值为正数时一样。 （由 Elvis Pranskevichus 在 bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751} 中贡献。）

当附带 @ref{192,,ssl.SSLSocket} 套接字调用不兼容的方法时 @ref{9,,asyncio} 现在会引发 @code{TyperError}。 （由 Ido Michael 在 bpo-37404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37404} 中贡献。）

@node compileall,concurrent futures,asyncio,改进的模块
@anchor{whatsnew/3 9 compileall}@anchor{193}
@subsubsection compileall


为重复的 @code{.pyc} 文件添加了使用硬软件的可能性: @emph{hardlink_dupes} 形参以及 --hardlink-dupes 命令行选项。 （由 Lumír 'Frenzy' Balhar 在 bpo-40495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40495} 中贡献。）

新增了一些用于在结果 @code{.pyc} 文件中操纵路径的选项: @emph{stripdir}, @emph{prependdir}, @emph{limit_sl_dest} 形参以及 -s, -p, -e 命令行选项。 并使得为优化等级多次指定选项成为可能。 （由 Lumír 'Frenzy' Balhar 在 bpo-38112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38112} 中贡献。）

@node concurrent futures,curses,compileall,改进的模块
@anchor{whatsnew/3 9 concurrent-futures}@anchor{194}
@subsubsection concurrent.futures


将新的 @emph{cancel_futures} 形参添加到 @ref{195,,concurrent.futures.Executor.shutdown()}，可以取消尚未开始运行的所有挂起的 Future，而不必等待它们完成运行再关闭执行器。 （由 Kyle Stanley 在 bpo-39349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39349} 中贡献。）

从 @ref{18c,,ThreadPoolExecutor} 和 @ref{196,,ProcessPoolExecutor} 中移除了守护线程。 这改善与与子解释器的兼容性及它们在关闭进程时的可预测性。 （由 Kyle Stanley 在 bpo-39812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39812} 中贡献。）

现在 @ref{196,,ProcessPoolExecutor} 中的工作进程仅会在没有可重用的空闲工作进程时按需产生。 这优化了启动开销并减少了由空闲工作进程导致的 CPU 时间损失。 （由 Kyle Stanley 在 bpo-39207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39207} 中贡献。）

@node curses,datetime,concurrent futures,改进的模块
@anchor{whatsnew/3 9 curses}@anchor{197}
@subsubsection curses


增加了 @ref{198,,curses.get_escdelay()}, @ref{199,,curses.set_escdelay()}, @ref{19a,,curses.get_tabsize()} 以及 @ref{19b,,curses.set_tabsize()} 函数。（由 Anthony Sottile 在 bpo-38312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38312} 中贡献。）

@node datetime,distutils,curses,改进的模块
@anchor{whatsnew/3 9 datetime}@anchor{19c}
@subsubsection datetime


@ref{19d,,datetime.date} 的 @ref{19e,,isocalendar()} 以及 @ref{19f,,datetime.datetime} 的 @ref{1a0,,isocalendar()} 等方法现在将返回 @ref{1a1,,namedtuple()} 而不是 @ref{1a2,,tuple}。 （由 Dong-hee Na 在 bpo-24416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24416} 中贡献。）

@node distutils,fcntl,datetime,改进的模块
@anchor{whatsnew/3 9 distutils}@anchor{1a3}
@subsubsection distutils


@code{upload} 命令现在会创建 SHA2-256 和 Blake2b-256 哈希摘要。 它会在禁用 MD5 摘要的平台上跳过 MD5。 （由 Christian Heimes 在 bpo-40698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40698} 中贡献。）

@node fcntl,ftplib,distutils,改进的模块
@anchor{whatsnew/3 9 fcntl}@anchor{1a4}
@subsubsection fcntl


增加了 @code{F_OFD_GETLK}, @code{F_OFD_SETLK} 和 @code{F_OFD_SETLKW} 等常量。 （由 Dong-hee Na 在 bpo-38602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38602} 中贡献。）

@node ftplib,gc,fcntl,改进的模块
@anchor{whatsnew/3 9 ftplib}@anchor{1a5}
@subsubsection ftplib


现在 @ref{1a6,,FTP} 和 @ref{1a7,,FTP_TLS} 当它们的构造器所给定的超时参数为零以防止创建非阻塞套接字时会引发 @ref{16d,,ValueError}。 （由 Dong-hee Na 在 bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259} 中贡献。）

@node gc,hashlib,ftplib,改进的模块
@anchor{whatsnew/3 9 gc}@anchor{1a8}
@subsubsection gc


当垃圾回收器进行某些复活对象的收集时（在终结器被执行之后这些对象可以在隔离周期之外被访问），不会阻止对所有仍然无法访问的对象的收集。 （由 Pablo Galindo 和 Tim Peters 在 bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379} 中贡献。）

增加了一个新的函数 @ref{1a9,,gc.is_finalized()} 用来检测一个对象是否已被垃圾回收器所终结。 （由 Pablo Galindo 在 bpo-39322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39322} 中贡献。）

@node hashlib,http,gc,改进的模块
@anchor{whatsnew/3 9 hashlib}@anchor{1aa}
@subsubsection hashlib


@ref{8c,,hashlib} 模块现在会在可能的情况下使用 OpenSSL 中的 SHA3 哈希和 SHAKE XOF。 （由 Christian Heimes 在 bpo-37630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37630} 中贡献。）

内置的哈希模块现在可通过 @code{./configure --without-builtin-hashlib-hashes} 禁用或通过 @code{./configure --with-builtin-hashlib-hashes=sha3,blake2} 这样的形式有选择地启用以强制使用基于 OpenSSL 的实现。 （由 Christian Heimes 在 bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479} 中贡献）

@node http,IDLE 与 idlelib,hashlib,改进的模块
@anchor{whatsnew/3 9 http}@anchor{1ab}
@subsubsection http


添加 HTTP 状态码 @code{103 EARLY_HINTS}, @code{418 IM_A_TEAPOT} 和 @code{425 TOO_EARLY} 到 @ref{1ac,,http.HTTPStatus}。 （由 Dong-hee Na 在 bpo-39509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39509} 以及 Ross Rhodes 在 bpo-39507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39507} 中贡献。）

@node IDLE 与 idlelib,imaplib,http,改进的模块
@anchor{whatsnew/3 9 idle-and-idlelib}@anchor{1ad}
@subsubsection IDLE 与 idlelib


添加了切换光标闪烁停止的选项。 （由 Zackery Spytz 在 bpo-4603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4603} 中贡献。）

Esc 键现在会关闭 IDLE 补全提示窗口。 （由 Johnny Najera 在 bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944} 中贡献。）

添加关键字到模块名称补全列表。 （由 Terry J. Reedy 在 bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765} 中贡献。）

3.9 维护版本中的新内容

使 IDLE 调用 @ref{1ae,,sys.excepthook()} （当启动时没有 '-n' ）。用户钩子以前是被忽略的。 (由 Ken Hilton 在 bpo-43008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43008} 中贡献。)

上述修改已被反向移植到 3.8 维护发行版中。

重新安排设置对话框。 将常规选项卡分成 Windows 和 Shell/Ed 选项卡。 将扩展帮助菜单的帮助源移至扩展标签。为新选项留出空间，并缩短对话框。后者使对话框更适合小屏幕。 (由 Terry Jan Reedy 贡献于 bpo-40468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40468} 。) 将缩进空间设置从字体标签移到新的 Windows 标签。 (由 Mark Roseman 和 Terry Jan Reedy 在 bpo-33962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33962} 中提供)。

对 @cite{.pyi} 文件应用语法高亮。(由 Alex Waygood 和 Terry Jan Reedy 在 bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447} 中贡献。)

@node imaplib,importlib,IDLE 与 idlelib,改进的模块
@anchor{whatsnew/3 9 imaplib}@anchor{1af}
@subsubsection imaplib


现在 @ref{1b0,,IMAP4} 和 @ref{1b1,,IMAP4_SSL} 的构造器具有可选的 @emph{timeout} 形参。 并且，现在 @ref{1b2,,open()} 方法也具有可选的 @emph{timeout} 形参提供同样的修改。 @ref{1b1,,IMAP4_SSL} 和 @ref{1b3,,IMAP4_stream} 中被重载的方法也应用了这个修改。 （由 Dong-hee Na 在 bpo-38615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38615} 中贡献。）

增加了 @ref{1b4,,imaplib.IMAP4.unselect()}。 @ref{1b4,,imaplib.IMAP4.unselect()} 会释放关联到选定邮箱的服务器资源并将服务器返回到已认证状态。 此命令会执行与 @ref{1b5,,imaplib.IMAP4.close()} 相同的动作，区别在于它不会从当前选定邮箱中永久性地移除消息。 （由 Dong-hee Na 在 bpo-40375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40375} 中贡献。）

@node importlib,inspect,imaplib,改进的模块
@anchor{whatsnew/3 9 importlib}@anchor{1b6}
@subsubsection importlib


为提升与 import 语句的一致性，现在 @ref{1b7,,importlib.util.resolve_name()} 对于无效的相对导入尝试会引发 @ref{16c,,ImportError} 而不是 @ref{16d,,ValueError}。 （由 Ngalim Siregar 在 bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444} 中贡献。）

发布不可变模块对象的导入加载器除了发布单独模块以外现在也可以发布不可变包。 （由 Dino Viehland 在 bpo-39336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39336} 中贡献。）

添加了带有对包数据中子目录支持的 @ref{1b8,,importlib.resources.files()} 函数，与 @code{importlib_resources} 1.5 版的反向端口相匹配。（由 Jason R. Coombs 在 bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791} 中贡献。）

来自 @code{importlib_metadata} 1.6.1 版的已更新 @code{importlib.metadata}。

@node inspect,ipaddress,importlib,改进的模块
@anchor{whatsnew/3 9 inspect}@anchor{1b9}
@subsubsection inspect


@ref{1ba,,inspect.BoundArguments.arguments} 已从 @code{OrderedDict} 改为常规字典。 （由 Inada Naoki 在 bpo-36350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36350} 和 bpo-39775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39775} 中贡献。）

@node ipaddress,math,inspect,改进的模块
@anchor{whatsnew/3 9 ipaddress}@anchor{1bb}
@subsubsection ipaddress


@ref{a2,,ipaddress} 现在支持 IPv6 作用域地址（即带有 @code{%<scope_id>} 前缀的 IPv6 地址）。

IPv6 作用域地址可使用 @ref{1bc,,ipaddress.IPv6Address} 来解析。 作用域的区 ID 如果存在，可通过 @ref{1bd,,scope_id} 属性来获取。 （由 Oleksandr Pavliuk 在 bpo-34788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34788} 中贡献。）

从 Python 3.9.5 开始 @ref{a2,,ipaddress} 模块不再接受 IPv4 地址字符串中有任何前缀的零。 （由 Christian Heimes 在 bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384} 中贡献。）

@node math,multiprocessing,ipaddress,改进的模块
@anchor{whatsnew/3 9 math}@anchor{1be}
@subsubsection math


对 @ref{1bf,,math.gcd()} 函数进行了扩展以处理多个参数。 在之前版本中，它只支持两个参数。 （由 Serhiy Storchaka 在 bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648} 中贡献。）

增加了 @ref{1c0,,math.lcm()}: 返回指定参数的最小公倍数。 （由 Mark Dickinson, Ananthakrishnan 和 Serhiy Storchaka 在 bpo-39479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39479} 和 bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648} 中贡献。）

增加了 @ref{1c1,,math.nextafter()}: 返回从 @emph{x} 往 @emph{y} 方向的下一个浮点数值。 （由 Victor Stinner 在 bpo-39288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39288} 中贡献。）

增加了 @ref{1c2,,math.ulp()}: 返回一个浮点数的最小有效比特位。 （由 Victor Stinner 在 bpo-39310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39310} 中贡献。）

@node multiprocessing,nntplib,math,改进的模块
@anchor{whatsnew/3 9 multiprocessing}@anchor{1c3}
@subsubsection multiprocessing


@ref{1c4,,multiprocessing.SimpleQueue} 类新增了 @ref{1c5,,close()} 方法用来显式地关闭队列。 （由 Victor Stinner 在 bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966} 中贡献。）

@node nntplib,os,multiprocessing,改进的模块
@anchor{whatsnew/3 9 nntplib}@anchor{1c6}
@subsubsection nntplib


现在 @ref{1c7,,NNTP} 和 @ref{1c8,,NNTP_SSL} 当它们的构造器所给定的超时参数为零以防止创建非阻塞套接字时会引发 @ref{16d,,ValueError}。 （由 Dong-hee Na 在 bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259} 中贡献。）

@node os,pathlib,nntplib,改进的模块
@anchor{whatsnew/3 9 os}@anchor{1c9}
@subsubsection os


增加了 @ref{1ca,,CLD_KILLED} 和 @ref{1cb,,CLD_STOPPED} 作为 @code{si_code}。 （由 Dong-hee Na 在 bpo-38493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38493} 中贡献。）

对外公开了 Linux 专属的 @ref{158,,os.pidfd_open()} (bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}) 和 @ref{1cc,,os.P_PIDFD} (bpo-38713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38713}) 用于文件描述符的进程管理。

现在 @ref{1cd,,os.unsetenv()} 函数在 Windows 上也已可用。 （由 Victor Stinner 在 bpo-39413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39413} 中贡献。）

现在 @ref{1ce,,os.putenv()} 和 @ref{1cd,,os.unsetenv()} 函数将总是可用。 （由 Victor Stinner 在 bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395} 中贡献。）

增加了 @ref{1cf,,os.waitstatus_to_exitcode()} 函数：将等待状态转换为退出码。 （由 Victor Stinner 在 bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094} 中贡献。）

@node pathlib,pdb,os,改进的模块
@anchor{whatsnew/3 9 pathlib}@anchor{1d0}
@subsubsection pathlib


增加了 @ref{1d1,,pathlib.Path.readlink()}，其行为类似于 @ref{1d2,,os.readlink()}。 （由 Girts Folkmanis 在 bpo-30618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30618} 中贡献。）

@node pdb,poplib,pathlib,改进的模块
@anchor{whatsnew/3 9 pdb}@anchor{1d3}
@subsubsection pdb


在 Windows 上 @ref{1d4,,Pdb} 现在支持 @code{~/.pdbrc}。 （由 Tim Hopper 和 Dan Lidral-Porter 在 bpo-20523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20523} 中贡献。）

@node poplib,pprint,pdb,改进的模块
@anchor{whatsnew/3 9 poplib}@anchor{1d5}
@subsubsection poplib


现在 @ref{1d6,,POP3} 和 @ref{1d7,,POP3_SSL} 当它们的构造器所给定的超时参数为零以防止创建非阻塞套接字时会引发 @ref{16d,,ValueError}。 （由 Dong-hee Na 在 bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259} 中贡献。）

@node pprint,pydoc,poplib,改进的模块
@anchor{whatsnew/3 9 pprint}@anchor{1d8}
@subsubsection pprint


现在 @ref{d2,,pprint} 能美化打印 @ref{1d9,,types.SimpleNamespace}。 （由 Carl Bordum Hansen 在 bpo-37376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37376} 中贡献。）

@node pydoc,random,pprint,改进的模块
@anchor{whatsnew/3 9 pydoc}@anchor{1da}
@subsubsection pydoc


文档字符串的显示现在不仅针对类、函数、方法等，也针对任何具有自己的 @code{__doc__} 属性的对象。 （由 Serhiy Storchaka 在 bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257} 中贡献。）

@node random,signal,pydoc,改进的模块
@anchor{whatsnew/3 9 random}@anchor{1db}
@subsubsection random


增加了新的 @code{random.Random.randbytes} 方法：生成随机字节串。 （由 Victor Stinner 在 bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286} 中贡献。）

@node signal,smtplib,random,改进的模块
@anchor{whatsnew/3 9 signal}@anchor{1dc}
@subsubsection signal


对外公开了 Linux 专属的 @ref{1dd,,signal.pidfd_send_signal()} 用于向使用文件描述符而非 pid 的进程发送信号。 (bpo-38712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38712})

@node smtplib,socket,signal,改进的模块
@anchor{whatsnew/3 9 smtplib}@anchor{1de}
@subsubsection smtplib


现在 @ref{1df,,SMTP} 和 @ref{1e0,,SMTP_SSL} 当它们的构造器所给定的超时参数为零以防止创建非阻塞套接字时会引发 @ref{16d,,ValueError}。 （由 Dong-hee Na 在 bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259} 中贡献。）

现在 @ref{1e1,,LMTP} 构造器具有可选的 @emph{timeout} 形参。 （由 Dong-hee Na 在 bpo-39329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39329} 中贡献。）

@node socket,time,smtplib,改进的模块
@anchor{whatsnew/3 9 socket}@anchor{1e2}
@subsubsection socket


@ref{ef,,socket} 模块现在会在 Linux 4.1 或更高版本上导出 @ref{1e3,,CAN_RAW_JOIN_FILTERS} 常量。 （由 Stefan Tatschner 和 Zackery Spytz 在 bpo-25780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25780} 中贡献。）

现在 socket 模块会在支持的平台上支持 @ref{1e4,,CAN_J1939} 协议。 （由 Karl Ding 在 bpo-40291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40291} 上贡献。）

现在 socket 模块具有 @ref{1e5,,socket.send_fds()} 和 @ref{1e6,,socket.recv_fds()} 函数。 （由 Joannah Nanjekye, Shinya Okano 和 Victor Stinner 在 bpo-28724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28724} 中贡献。）

@node time,sys,socket,改进的模块
@anchor{whatsnew/3 9 time}@anchor{1e7}
@subsubsection time


在 AIX 上，现在 @ref{1e8,,thread_time()} 是使用具有纳秒级精度的 @code{thread_cputime()} 实现，而不再是只有 10 毫秒精度的 @code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)}。 （由 Batuhan Taskaya 在 bpo-40192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40192} 中贡献。）

@node sys,tracemalloc,time,改进的模块
@anchor{whatsnew/3 9 sys}@anchor{1e9}
@subsubsection sys


增加了新的 @ref{1ea,,sys.platlibdir} 属性：平台专属库目录的名称。 它被用于构建标准库的路径以及已安装扩展模块的路径。 它在大多数平台上等于 @code{"lib"}。 在 Fedora 和 SuSE 上，它等于 64 位平台上的 @code{"lib64"}。 （由 Jan Matějek, Matěj Cepl, Charalampos Stratakis 和 Victor Stinner 在 bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959} 中贡献。）

之前的版本中，@ref{1eb,,sys.stderr} 在非交互模式时是带块缓冲的。 现在 @code{stderr} 默认总是为行缓冲的。 （由 Jendrik Seipp 在 bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601} 中贡献。）

@node tracemalloc,typing,sys,改进的模块
@anchor{whatsnew/3 9 tracemalloc}@anchor{1ec}
@subsubsection tracemalloc


增加了 @ref{1ed,,tracemalloc.reset_peak()} 用于将跟踪的内存块峰值大小设为当前大小，以测量特定代码段的峰值。 （由 Huon Wilson 在 bpo-40630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40630} 中贡献。）

@node typing,unicodedata,tracemalloc,改进的模块
@anchor{whatsnew/3 9 typing}@anchor{1ee}
@subsubsection typing


@geindex Python 提高建议; PEP 593
PEP 593@footnote{https://www.python.org/dev/peps/pep-0593} 引入了一种 @ref{1ef,,typing.Annotated} 类型以使用上下文专属的元数据来装饰现有类型，并将新的 @code{include_extras} 形参添加到 @ref{1f0,,typing.get_type_hints()} 以在运行时访问元数据。 （由 Till Varoquaux 和 Konstantin Kashin 贡献。）

@node unicodedata,venv,typing,改进的模块
@anchor{whatsnew/3 9 unicodedata}@anchor{1f1}
@subsubsection unicodedata


Unicode 数据库已更新到 13.0.0 版。 (bpo-39926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39926})。

@node venv,xml,unicodedata,改进的模块
@anchor{whatsnew/3 9 venv}@anchor{1f2}
@subsubsection venv


由 @ref{12e,,venv} 所提供的激活脚本现在总是会使用 @code{__VENV_PROMPT__} 设置的值来一致地指明它们的自定义提示符。 在之前版本中某些脚本会无条件地使用 @code{__VENV_PROMPT__}，而另一些脚本只在其恰好被设置时（这是默认情况）才会使用，还有的脚本会改用 @code{__VENV_NAME__}。 （由 Brett Cannon 在 bpo-37663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37663} 中贡献。）

@node xml,,venv,改进的模块
@anchor{whatsnew/3 9 xml}@anchor{1f3}
@subsubsection xml


当把 @ref{140,,xml.etree.ElementTree} 序列化为 XML 文件时属性内部的空白字符现在将被保留。 不同的行结束符不会再被正规化为 "n"。 这是对于如何解读 XML 规范 2.11 节的相关讨论的最终结果。 （由 Mefistotelis 在 bpo-39011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39011} 中贡献。）

@node 性能优化,弃用,改进的模块,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 optimizations}@anchor{1f4}
@subsection 性能优化



@itemize *

@item 
优化了在推导式中为临时变量赋值的惯用方式。 现在推导式中的 @code{for y in [expr]} 会与简单赋值语句 @code{y = expr} 一样快速。 例如:

@quotation

sums = [s for s in [0] for x in data for s in [s + x]]
@end quotation

不同于 @code{:=} 运算符，这个惯用方式不会使变量泄露到外部作用域中。

（由 Serhiy Storchaka 在 bpo-32856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32856} 中贡献。）

@item 
优化了多线程应用中的信号处理。 如果一个线程不是获得信号的主线程，字节码求值循环不会在每条字节码指令上被打断以检查无法被处理的挂起信号。 只有主解释器的主线程能够处理信号。

在之前版本中，字节码求值循环会在每条指令上被打断直到主线程处理了信号。 （由 Victor Stinner 在 bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010} 上贡献。）

@item 
在 FreeBSD 上使用 @code{closefrom()} 优化了 @ref{f9,,subprocess} 模块。 （由 Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak 和 Victor Stinner 在 bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061} 中贡献。）

@item 
@ref{1f5,,PyLong_FromDouble()} 对于匹配 @code{long} 的值执行速度现在加快了 1.87 倍。 （由 Sergey Fedoseev d  bpo-37986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37986} 中贡献。）

@item 
多个 Python 内置类型 (@ref{1f6,,range}, @ref{1a2,,tuple}, @ref{1f7,,set}, @ref{1f8,,frozenset}, @ref{1f9,,list}, @ref{164,,dict}) 现在通过使用 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590} 向量调用协议得到加速。 （由 Dong-hee Na, Mark Shannon, Jeroen Demeyer 和 Petr Viktorin 在 bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207} 中贡献。）

@item 
当另一集合远大于基础集合的情况下优化了 @code{difference_update()} 的性能。 （由 Evgeny Kapun 提议，由 Michele Orrù 在 bpo-8425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8425} 中贡献代码。）

@item 
Python 的小对象分配器 (@code{obmalloc.c}) 现在允许（至多）一个空位可用于立即重用，而不必将其返回给 OS。 这可以防止简单循环中的多余消耗，在每次迭代中可以创建和销毁全新的空位。 （由 Tim Peters 在 bpo-37257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37257} 中贡献。）

@item 
浮点数运算中的 @ref{1fa,,floor division} 现在会有更好的性能。 并且此运算的 @ref{1fb,,ZeroDivisionError} 的消息也已更新。 （由 Dong-hee Na 在 bpo-39434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39434} 中贡献。）

@item 
使用 UTF-8 和 ascii 编解码器解码短 ASCII 字符串现在会加快大约 15%。 （由 Inada Naoki 在 bpo-37348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37348} 中贡献。）
@end itemize

以下是对从 Python 3.4 到 Python 3.9 的提升提升情况的总结:

@example
Python version                       3.4     3.5     3.6     3.7     3.8    3.9
--------------                       ---     ---     ---     ---     ---    ---

Variable and attribute read access:
    read_local                       7.1     7.1     5.4     5.1     3.9    3.9
    read_nonlocal                    7.1     8.1     5.8     5.4     4.4    4.5
    read_global                     15.5    19.0    14.3    13.6     7.6    7.8
    read_builtin                    21.1    21.6    18.5    19.0     7.5    7.8
    read_classvar_from_class        25.6    26.5    20.7    19.5    18.4   17.9
    read_classvar_from_instance     22.8    23.5    18.8    17.1    16.4   16.9
    read_instancevar                32.4    33.1    28.0    26.3    25.4   25.3
    read_instancevar_slots          27.8    31.3    20.8    20.8    20.2   20.5
    read_namedtuple                 73.8    57.5    45.0    46.8    18.4   18.7
    read_boundmethod                37.6    37.9    29.6    26.9    27.7   41.1

Variable and attribute write access:
    write_local                      8.7     9.3     5.5     5.3     4.3    4.3
    write_nonlocal                  10.5    11.1     5.6     5.5     4.7    4.8
    write_global                    19.7    21.2    18.0    18.0    15.8   16.7
    write_classvar                  92.9    96.0   104.6   102.1    39.2   39.8
    write_instancevar               44.6    45.8    40.0    38.9    35.5   37.4
    write_instancevar_slots         35.6    36.1    27.3    26.6    25.7   25.8

Data structure read access:
    read_list                       24.2    24.5    20.8    20.8    19.0   19.5
    read_deque                      24.7    25.5    20.2    20.6    19.8   20.2
    read_dict                       24.3    25.7    22.3    23.0    21.0   22.4
    read_strdict                    22.6    24.3    19.5    21.2    18.9   21.5

Data structure write access:
    write_list                      27.1    28.5    22.5    21.6    20.0   20.0
    write_deque                     28.7    30.1    22.7    21.8    23.5   21.7
    write_dict                      31.4    33.3    29.3    29.2    24.7   25.4
    write_strdict                   28.4    29.9    27.5    25.2    23.1   24.5

Stack (or queue) operations:
    list_append_pop                 93.4   112.7    75.4    74.2    50.8   50.6
    deque_append_pop                43.5    57.0    49.4    49.2    42.5   44.2
    deque_append_popleft            43.7    57.3    49.7    49.7    42.8   46.4

Timing loop:
    loop_overhead                    0.5     0.6     0.4     0.3     0.3    0.3
@end example

以上结果是由以下变量访问基准测试脚本所生成的: @code{Tools/scripts/var_access_benchmark.py}。 该基准测试脚本以纳秒为单位显示时间。 基准测试数据是在一块 Intel® Core™ i7-4960HQ 处理器@footnote{https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html} 运行从 python.org@footnote{https://www.python.org/downloads/mac-osx/} 获取的 macOS 64 位编译版本所得到的。

@node 弃用,移除,性能优化,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 deprecated}@anchor{1fc}
@subsection 弃用



@itemize *

@item 
distutils 的 @code{bdist_msi} 命令现在已被弃用，请改用 @code{bdist_wheel} (wheel 包)。 （由 Hugo van Kemenade 在 bpo-39586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39586} 中贡献。）

@item 
目前 @ref{1fd,,math.factorial()} 接受具有非负整数值的 @ref{1fe,,float} 实例 (如 @code{5.0})。 对于非整数和负浮点数它会引发 @ref{16d,,ValueError}。 此行为现在已被弃用。 在未来的 Python 版本中对所有浮点数都将引发 @ref{1ff,,TypeError}。 （由 Serhiy Storchaka 在 bpo-37315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37315} 中贡献。）

@item 
@ref{c7,,parser} 和 @ref{fb,,symbol} 模块已被弃用并将在未来的 Python 版本中移除。 对于大多数用例，用户都可以使用 @ref{7,,ast} 模块来控制抽象语法树 (AST) 的生成和编译阶段。

@item 
公有 C API 函数 @ref{200,,PyParser_SimpleParseStringFlags()}, @ref{201,,PyParser_SimpleParseStringFlagsFilename()}, @ref{202,,PyParser_SimpleParseFileFlags()} 和 @code{PyNode_Compile()} 已被弃用并将在 Python 3.10 版与旧解析器一起被移除。

@item 
在布尔运算中使用 @ref{203,,NotImplemented} 已被弃用，因为它几乎必定是不正确的富比较运算符实现的结果。 它将在未来的 Python 版本中引发 @ref{1ff,,TypeError}。 （由 Josh Rosenberg 在 bpo-35712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35712} 中贡献。）

@item 
@ref{dc,,random} 模块目前接受任何可哈希类型作为可能的种子值。 不幸的是，某些这样的类型并不保证具有确定性的哈希值。 在 Python 3.9 之后，该模块将限定其种子值为 @ref{204,,None}, @ref{205,,int}, @ref{1fe,,float}, @ref{206,,str}, @ref{172,,bytes} 以及 @ref{173,,bytearray}。

@item 
打开 @ref{207,,GzipFile} 文件用于写入而不指定 @emph{mode} 参数的特性已被弃用。 在未来的 Python 版本中将总是默认打开用于读取。 在打开文件用于写入时请指定 @emph{mode} 参数以静默相关警告信息。 （由 Serhiy Storchaka 在 bpo-28286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28286} 中贡献。）

@item 
弃用了 @code{_tkinter.TkappType} 的 @code{split()} 方法而改用 @code{splitlist()} 方法，此方法具有更稳定且可预测的行为。 （由 Serhiy Storchaka 在 bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371} 中贡献。）

@item 
将协程对象显式传递给 @ref{208,,asyncio.wait()} 的做法已被弃用并且将在 3.11 版中被移除。 （由 Yury Selivanov 和 Kyle Stanley 在 bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790} 中贡献。）

@item 
binhex4 和 hexbin4 标准现已被弃用。 @ref{10,,binhex} 模块和下列 @ref{f,,binascii} 函数现已被弃用:


@itemize *

@item 
@ref{209,,b2a_hqx()}, @ref{20a,,a2b_hqx()}

@item 
@ref{20b,,rlecode_hqx()}, @ref{20c,,rledecode_hqx()}
@end itemize

（由 Victor Stinner 在 bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353} 中贡献。）

@item 
@ref{7,,ast} 类 @code{slice}, @code{Index} 和 @code{ExtSlice} 被视为已弃用并将在未来的 Python 版本中被移除。 应当使用 @code{value} 本身而不再是 @code{Index(value)}。 应当使用 @code{Tuple(slices, Load())} 而不再是 @code{ExtSlice(slices)}。 （由 Serhiy Storchaka 在 bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822} 中贡献。）

@item 
@ref{7,,ast} 类 @code{Suite}, @code{Param}, @code{AugLoad} 和 @code{AugStore} 被视为已弃用并将在未来的 Python 版本中被移除。 它们不会被解析器所生成且不会被 Python 3 中的代码生成器所接受。 （由 Batuhan Taskaya 在 bpo-39639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39639} 和 bpo-39969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39969} 中以及 Serhiy Storchaka 在 bpo-39988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39988} 中贡献。）

@item 
@ref{20d,,PyEval_InitThreads()} 和 @ref{20e,,PyEval_ThreadsInitialized()} 函数现已被弃用并将在 Python 3.11 中被移除。 调用 @ref{20d,,PyEval_InitThreads()} 现在没有任何效果。 自 Python 3.7 起 @ref{20f,,GIL} 会由 @ref{210,,Py_Initialize()} 初始化。 （由 Victor Stinner 在 bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877} 中贡献。）

@item 
传入 @code{None} 作为 @ref{211,,shlex.split()} 函数的第一个参数的做法已被弃用。 （由 Zackery Spytz 在 bpo-33262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33262} 中贡献。）

@item 
@ref{212,,smtpd.MailmanProxy()} 现在已被弃用，因为它在没有外部模块 @code{mailman} 的情况下无法使用。 （由 Samuel Colvin 在 bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800} 中贡献。）

@item 
现在 @ref{a7,,lib2to3} 模块将发出 @ref{15c,,PendingDeprecationWarning}。 Python 3.9 已切换到 PEG 解析器 (参见 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617})，Python 3.10 可以会包含 lib2to3 的 LL(1) 解析器所不能解析的新语法。 @code{lib2to3} 模块可能会在未来的 Python 版本中被移出标准库。 请考虑使用第三方替换例如 LibCST@footnote{https://libcst.readthedocs.io/} 或 parso@footnote{https://parso.readthedocs.io/}。 （由 Carl Meyer 在 bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360} 中贡献。）

@item 
@ref{213,,random.shuffle()} 的 @emph{random} 形参已被弃用。 （由 Raymond Hettinger 在 bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465} 中贡献。）
@end itemize

@node 移除,移植到 Python 3 9,弃用,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 removed}@anchor{214}@anchor{whatsnew/3 9 removed-in-python-39}@anchor{161}
@subsection 移除



@itemize *

@item 
@code{unittest.mock.__version__} 上的错误版本已经被移除。

@item 
@ref{1c7,,nntplib.NNTP}: @code{xpath()} 和 @code{xgtitle()} 方法已被移除。 这些方法自 Python 3.3 起已被弃用。 一般来说，这些扩展都不再为 NNTP 服务管理员所支持或启用。 对于 @code{xgtitle()}，请改用 @ref{215,,nntplib.NNTP.descriptions()} 或 @ref{216,,nntplib.NNTP.description()}。 （由 Dong-hee Na 在 bpo-39366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39366} 中贡献。）

@item 
@ref{217,,array.array}: @code{tostring()} 和 @code{fromstring()} 方法已被移除。 它们分别是 @code{tobytes()} 和 @code{frombytes()} 的别名，自 Python 3.2 起已被弃用。 （由 Victor Stinner 在 bpo-38916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38916} 中贡献。）

@item 
未写入文档的 @code{sys.callstats()} 函数已被移除。 自 Python 3.7 起它就已被弃用并且总是会返回 @ref{204,,None}。 它需要一个特殊的构建选项 @code{CALL_PROFILE} 而该选项在 Python 3.7 中已被移除。 （由 Victor Stinner 在 bpo-37414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37414} 中贡献。）

@item 
@code{sys.getcheckinterval()} 和 @code{sys.setcheckinterval()} 函数已被移除。 它们自 Python 3.2 起已被弃用。 请改用 @ref{218,,sys.getswitchinterval()} 和 @ref{219,,sys.setswitchinterval()}。 （由 Victor Stinner 在 bpo-37392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37392} 中贡献。）

@item 
C 函数 @code{PyImport_Cleanup()} 已被移除。 它原本的文档为: "清空模块表。 仅限内部使用。" （由 Victor Stinner 在 bpo-36710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36710} 中贡献。）

@item 
@code{_dummy_thread} 和 @code{dummy_threading} 模块已被移除。 这些模块自 Python 3.7 起已被弃用，它们需要线程支持。 （由 Victor Stinner 在 bpo-37312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37312} 中贡献。）

@item 
@code{aifc.open()} 的别名 @code{aifc.openfp()}，@code{sunau.open()} 的别名 @code{sunau.openfp()}，以及 @ref{21a,,wave.open()} 的别名 @code{wave.openfp()} 已被移除。 它们自 Python 3.7 起已被弃用。 （由 Victor Stinner 在 bpo-37320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37320} 中贡献。）

@item 
@ref{21b,,threading.Thread} 的 @code{isAlive()} 方法已被移除。 它自 Python 3.8 起已被弃用。 请改用 @ref{21c,,is_alive()}。 （由 Dong-hee Na 在 bpo-37804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37804} 中贡献。）

@item 
@ref{140,,ElementTree} 模块中 @ref{21d,,ElementTree} 和 @ref{21e,,Element} 等类的 @code{getchildren()} 和 @code{getiterator()} 方法已被移除。 它们在 Python 3.2 中已被弃用。 请使用 @code{iter(x)} 或 @code{list(x)} 替代 @code{x.getchildren()} 并用 @code{x.iter()} 或 @code{list(x.iter())} 替代 @code{x.getiterator()}。 （由 Serhiy Storchaka 在 bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543} 中贡献。）

@item 
旧的 @ref{cf,,plistlib} API 已被移除，它自 Python 3.4 起已被弃用。 请使用 @ref{21f,,load()}, @ref{220,,loads()}, @ref{221,,dump()} 和 @ref{222,,dumps()} 等函数。 此外，@emph{use_builtin_types} 形参已被移除而总是会使用 @ref{172,,bytes} 对象。 （由 Jon Janzen 在 bpo-36409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36409} 中贡献。）

@item 
C 函数 @code{PyGen_NeedsFinalizing} 已被移除。 它未被写入文档、未经测试，且自 
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442} 实现之后未在 CPython 的任何地方被使用。 由 Joannah Nanjekye 提供补丁。 （由 Joannah Nanjekye 在 bpo-15088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15088} 中贡献。）

@item 
自 Python 3.1 起被弃用的别名 @code{base64.encodestring()} 和 @code{base64.decodestring()} 已被移除：请改用 @ref{223,,base64.encodebytes()} 和 @ref{224,,base64.decodebytes()}。 （由 Victor Stinner 在 bpo-39351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39351} 中贡献。）

@item 
@code{fractions.gcd()} 函数已被移除，它自 Python 3.5 起被弃用 (bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486})：请改用 @ref{1bf,,math.gcd()}。 （由 Victor Stinner 在 bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350} 中贡献。）

@item 
@ref{225,,bz2.BZ2File} 的 @emph{buffering} 形参已被移除。 它自 Python 3.0 起即被忽略，使用它将会引发 @ref{15a,,DeprecationWarning}。 请传入一个打开文件对象来控制文件的打开方式。 （由 Victor Stinner 在 bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357} 中贡献。）

@item 
@ref{226,,json.loads()} 的 @emph{encoding} 形参已被移除。 它在 Python 3.1 中已被弃用和忽略；自 Python 3.8 起使用它将会引发 @ref{15a,,DeprecationWarning}。 （由 Inada Naoki 在 bpo-39377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39377} 中贡献。）

@item 
@code{with (await asyncio.lock):} 和 @code{with (yield from asyncio.lock):} 语句已不再受支持，请改用 @code{async with lock}。 @code{asyncio.Condition} 和 @code{asyncio.Semaphore} 也同样如此。 （由 Andrew Svetlov 在 bpo-34793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34793} 中贡献。）

@item 
@code{sys.getcounts()} 函数，@code{-X showalloccount} 命令行选项以及 C 结构体 @ref{227,,PyConfig} 的 @code{show_alloc_count} 字段已被移除。 它们需要使用定义了 @code{COUNT_ALLOCS} 宏的特殊 Python 编译版本。 （由 Victor Stinner 在 bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489} 中贡献。）

@item 
@ref{228,,typing.NamedTuple} 类的 @code{_field_types} 属性已被移除。 它自 Python 3.8 起已被弃用。 请改用 @code{__annotations__} 属性。 （由 Serhiy Storchaka 在 bpo-40182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40182} 中贡献。）

@item 
@code{symtable.SymbolTable.has_exec()} 方法已被移除。 它自 2006 年起已被弃用，当被调用时仅会返回 @code{False}。 （由 Batuhan Taskaya 在 bpo-40208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40208} 中贡献。）

@item 
@code{asyncio.Task.current_task()} 和 @code{asyncio.Task.all_tasks()} 已被移除。 它们自 Python 3.7 起已被弃用，你可以改用 @ref{229,,asyncio.current_task()} 和 @ref{22a,,asyncio.all_tasks()}。 （由 Rémi Lapeyre 在 bpo-40967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40967} 中贡献。）

@item 
@ref{22b,,html.parser.HTMLParser} 类的 @code{unescape()} 方法已被移除（它自 Python 3.4 起已被弃用）。 应当使用 @ref{22c,,html.unescape()} 来将字符引用转换为对应的 unicode 字符。
@end itemize

@node 移植到 Python 3 9,构建的改变,移除,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 porting-to-python-3-9}@anchor{22d}
@subsection 移植到 Python 3.9


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* Python API 的变化:: 
* C API 的变化:: 
* CPython 字节码的改变:: 

@end menu

@node Python API 的变化,C API 的变化,,移植到 Python 3 9
@anchor{whatsnew/3 9 changes-in-the-python-api}@anchor{22e}
@subsubsection Python API 的变化



@itemize *

@item 
@ref{16b,,__import__()} 和 @ref{1b7,,importlib.util.resolve_name()} 现在会引发 @ref{16c,,ImportError} 取代之前所引发的 @ref{16d,,ValueError}。 捕获特定异常类型并同时支持 Python 3.9 和更早版本的调用者将需要使用 @code{except (ImportError, ValueError):} 来同时捕获两者。

@item 
@ref{12e,,venv} 激活脚本不再将 @code{__VENV_PROMPT__} 被设为 @code{""} 的情况作为特例处理。

@item 
@ref{22f,,select.epoll.unregister()} 方法不会再忽略 @ref{230,,EBADF} 错误。 （由 Victor Stinner 在 bpo-39239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39239} 中贡献。）

@item 
@ref{225,,bz2.BZ2File} 的 @emph{compresslevel} 形参已成为仅限关键字形参，因为 @emph{buffering} 形参已被移除。 （由 Victor Stinner 在 bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357} 中贡献。）

@item 
简化了 AST 的抽取操作。 简单索引将以它们的值来代表，扩展切片将以元组形式来代表。 @code{Index(value)} 将返回 @code{value} 本身，@code{ExtSlice(slices)} 将返回 @code{Tuple(slices, Load())}。 （由 Serhiy Storchaka 在 bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822} 中贡献。）

@item 
当使用了 @ref{231,,-E} 或 @ref{232,,-I} 命令行参数时 @ref{9a,,importlib} 模块现在会忽略 
@geindex PYTHONCASEOK
@geindex 环境变量; PYTHONCASEOK
@ref{233,,PYTHONCASEOK} 环境变量。

@item 
@emph{encoding} 形参已作为仅限关键字形参被添加到 @ref{1a6,,ftplib.FTP} 和 @ref{1a7,,ftplib.FTP_TLS} 类，并且默认编码格式由 Latin-1 改为 UTF-8 以遵循 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://tools.ietf.org/html/rfc2640.html}。

@item 
@ref{18b,,asyncio.loop.shutdown_default_executor()} 已被添加到 @ref{234,,AbstractEventLoop}，这意味着继承自它的替代事件循环应当定义此方法。 （由 Kyle Stanley 在 bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037} 中贡献。）

@item 
更新了 @ref{0,,__future__} 模块中未来特性旗标的常量值以防止与编译器旗标相冲突。 在之前版本中 @code{PyCF_ALLOW_TOP_LEVEL_AWAIT} 会与 @code{CO_FUTURE_DIVISION} 发生冲突。 （由 Batuhan Taskaya 在 bpo-39562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39562} 中贡献。）

@item 
@code{array('u')} 现在使用 @code{wchar_t} 作为 C 类型而不是 @code{Py_UNICODE}。 这个改变不会影响其行为，因为自 Python 3.3 起 @code{Py_UNICODE} 是 @code{wchar_t} 的别名。 （由 Inada Naoki 在 bpo-34538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34538} 中贡献。）

@item 
现在 @ref{235,,logging.getLogger()} API 当传入名称 @code{'root'} 时将返回根日志记录器，而在之前它则返回一个名为 @code{'root'} 的非根日志记录器。 这可能会影响到用户代码明确希望使用一个名为 @code{'root'} 的非根日志记录器，或在某个名为 @code{'root.py'} 的最高层级模块中使用 @code{logging.getLogger(__name__)} 来实例化日志记录器的情况。 （由 Vinay Sajip 在 bpo-37742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37742} 中贡献。）

@item 
现在 @ref{236,,PurePath} 的拆分处理当传入 @code{str} 或 @ref{236,,PurePath} 的实例以外的对象时会返回 @code{NotImplemented} 而不是引发 @ref{1ff,,TypeError}。 这将允许创建不继承自上述类型的兼容类。 （由 Roger Aiudi 在 bpo-34775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34775} 中贡献。）

@item 
从 Python 3.9.5 开始 @ref{a2,,ipaddress} 模块不再接受 IPv4 地址字符串中有任何前缀的零。 前缀的零有歧义且会被某些库解读为八进制数字。 例如旧版函数 @ref{237,,socket.inet_aton()} 就瘵前缀的零视为八进制数字。 最新 @ref{238,,inet_pton()} 的 glibc 实现则不接受任何前缀的零。 （由 Christian Heimes 在 bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384} 中贡献）。

@item 
@ref{239,,codecs.lookup()} 现在会以与 @code{encodings.normalize_encoding()} 相同的方式正规化编码格式名称，不同之处在于 @ref{239,,codecs.lookup()} 还会将名称转换为小写形式。 例如`@w{`}"latex+latin1"`@w{`} 编写格式名称现在会被正规化为 @code{"latex_latin1"}。 （由 Jordon Xu 在 bpo-37751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37751} 中贡献。）
@end itemize

@node C API 的变化,CPython 字节码的改变,Python API 的变化,移植到 Python 3 9
@anchor{whatsnew/3 9 changes-in-the-c-api}@anchor{23a}
@subsubsection C API 的变化



@itemize *

@item 
堆分配类型的实例（例如使用 @ref{23b,,PyType_FromSpec()} 和类似 API 创建的实例）自 Python 3.8 起会带有一个对其类型对象的引用。 正如 Python 3.8 的 "C API 中的改变" 部分所述，对于大部分情况来说，这应当不会有任何副作用，但对于具有自定义 @ref{23c,,tp_traverse} 函数的类型来说，则要确保所有堆分配类型的自定义 @code{tp_traverse} 函数可访问对象的类型。

@quotation

示例:

@example
int
foo_traverse(foo_struct *self, visitproc visit, void *arg) @{
// Rest of the traverse function
#if PY_VERSION_HEX >= 0x03090000
    // This was not needed before Python 3.9 (Python issue 35810 and 40217)
    Py_VISIT(Py_TYPE(self));
#endif
@}
@end example
@end quotation

如果你的遍历函数委托给了基类（或其他类）的 @code{tp_traverse}，则要确保 @code{Py_TYPE(self)} 只被访问一次。 请注意应当只有堆类型可访问 @code{tp_traverse} 中的类型。

@quotation

举例来说，如果你的 @code{tp_traverse} 函数包括以下内容:

@example
base->tp_traverse(self, visit, arg)
@end example

则要添加:

@example
#if PY_VERSION_HEX >= 0x03090000
    // This was not needed before Python 3.9 (Python issue 35810 and 40217)
    if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) @{
        // a heap type's tp_traverse already visited Py_TYPE(self)
    @} else @{
        Py_VISIT(Py_TYPE(self));
    @}
#else
@end example
@end quotation

（参阅 bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810} 和 bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217} 了解更多信息。）

@item 
@code{PyEval_CallObject}, @code{PyEval_CallFunction}, @code{PyEval_CallMethod} 和 @code{PyEval_CallObjectWithKeywords} 函数已被弃用。 请改用 @ref{23d,,PyObject_Call()} 及其变化形式。 （详情参见 bpo-29548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29548}。）
@end itemize

@node CPython 字节码的改变,,C API 的变化,移植到 Python 3 9
@anchor{whatsnew/3 9 cpython-bytecode-changes}@anchor{23e}
@subsubsection CPython 字节码的改变



@itemize *

@item 
添加了 @ref{23f,,LOAD_ASSERTION_ERROR} 操作码用于处理 @ref{240,,assert} 语句。 在之前的版本中，如果 @ref{241,,AssertionError} 异常被屏蔽则 assert 语句将不能正常运作。 （由 Zackery Spytz 在 bpo-34880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34880} 中贡献。）

@item 
@ref{242,,COMPARE_OP} 操作码已被拆分为四个单独指令:


@itemize *

@item 
@code{COMPARE_OP} 用于富比较

@item 
@code{IS_OP} 用于 'is' 和 'is not' 检测

@item 
@code{CONTAINS_OP} 用于 'in' 和 'not in' 检测

@item 
@code{JUMP_IF_NOT_EXC_MATCH} 用于检查 'try-except' 语句中的异常。
@end itemize

（由 Mark Shannon 在 bpo-39156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39156} 中贡献。）
@end itemize

@node 构建的改变,C API 的改变,移植到 Python 3 9,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 build-changes}@anchor{243}
@subsection 构建的改变



@itemize *

@item 
将 @code{--with-platlibdir} 选项添加到 @code{configure} 脚本：平台专属库目录的名称，保存在新的 @ref{1ea,,sys.platlibdir} 属性中。 请参阅 @ref{1ea,,sys.platlibdir} 属性了解详情。 （由 Jan Matějek, Matěj Cepl, Charalampos Stratakis 和 Victor Stinner 在 bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959} 中贡献。）

@item 
@code{COUNT_ALLOCS} 特殊构建宏已被移除。 （由 Victor Stinner 在 bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489} 中贡献。）

@item 
在非 Windows 平台上，现在需要用 @code{setenv()} 和 @code{unsetenv()} 函数来构建 Python。 （由 Victor Stinner 在 bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395} 中贡献。）

@item 
在非 Windows 平台上，创建 @code{bdist_wininst} 安装器现在已不受官方支持。 （详情参见 bpo-10945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10945}。）

@item 
当在 macOS 上用源代码编译 Python 时，@code{_tkinter} 现在会链接到非系统的 Tcl 和 Tk 框架，如果它们被安装到 @code{/Library/Frameworks} 的话，就如在较旧的 macOS 发行版上的情况一样。 如果通过使用 @code{--enable-universalsdk=} 或 @code{-isysroot} 明确地配置了 macOS SDK，则只会搜索 SDK 本身。 默认行为仍然可以通过 @code{--with-tcltk-includes} 和 @code{--with-tcltk-libs} 来覆盖。 （由 Ned Deily 在 bpo-34956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34956} 中贡献。）

@item 
Python 现在可以针对 Windows 10 ARM64 进行编译。 （由 Steve Dower 在 bpo-33125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33125} 中贡献。）

@item 
现在当使用 @code{--pgo} 时一些单独的测试会被跳过。 这些测试显著增加了 PGO 任务的时间并且可能无助于提升最终可执行文件的优化程度。 这样能使任务加速大约 15 倍。 运行完整的单元测试是很慢的。 这个改变可能导致优化程序稍差的构建，因为将被执行的代码分支不够多。 如果你愿意等待更缓慢的构建，则可以使用 @code{./configure [..] PROFILE_TASK="-m test --pgo-extended"} 来恢复旧版本的行为。 我们不保证哪个 PGO 任务集能产生更快的构建。 关心此问题的用户应当自行运行相关基准测试，因为结果可能取决于具体环境、工作负载以及编译工具链。 （请参阅 bpo-36044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36044} 和 bpo-37707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37707} 了解详情。）
@end itemize

@node C API 的改变,Python 3 9 1 中的重要变化,构建的改变,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 c-api-changes}@anchor{244}
@subsection C API 的改变


@menu
* 新的特性: 新的特性<2>. 
* 移植到 Python 3.9: 移植到 Python 3 9<2>. 
* 移除: 移除<2>. 

@end menu

@node 新的特性<2>,移植到 Python 3 9<2>,,C API 的改变
@anchor{whatsnew/3 9 id1}@anchor{245}
@subsubsection 新的特性



@itemize *

@item 
@geindex Python 提高建议; PEP 573
PEP 573@footnote{https://www.python.org/dev/peps/pep-0573}: 添加了 @ref{246,,PyType_FromModuleAndSpec()} 用于通过类来关联一个模块；@ref{247,,PyType_GetModule()} 和 @ref{248,,PyType_GetModuleState()} 用于获取模块及其状态；以及 @ref{249,,PyCMethod} 和 @code{METH_METHOD} 用于允许一个方法访问其定义所在的类。 （由 Marcel Plch 和 Petr Viktorin 在 bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787} 中贡献。）

@item 
增加了 @ref{24a,,PyFrame_GetCode()} 函数：获取帧代码。 增加了 @ref{24b,,PyFrame_GetBack()} 函数：获取帧的下一个外部帧。 （由 Victor Stinner 在 bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421} 中贡献。）

@item 
将 @ref{24c,,PyFrame_GetLineNumber()} 添加到受限的 C API。 （由 Victor Stinner 在 bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421} 中贡献。）

@item 
增加了 @ref{24d,,PyThreadState_GetInterpreter()} 和 @ref{24e,,PyInterpreterState_Get()} 函数用于获取解释器。 增加了 @ref{24f,,PyThreadState_GetFrame()} 函数用于获取 Python 线程状态的当前帧。 增加了 @ref{250,,PyThreadState_GetID()} 函数：获取 Python 线程状态的唯一标识符。 （由 Victor Stinner 在 bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947} 中贡献。）

@item 
将新的公有 @ref{251,,PyObject_CallNoArgs()} 函数添加到 C API，该函数可不带任何参数调用一个 Python 可调用对象。 它是不带参数调用 Python 可调用对象最有效率的方式。 （由 Victor Stinner 在 bpo-37194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37194} 中贡献。）

@item 
受限 C API 中的改变（如果定义了 @code{Py_LIMITED_API} 宏）:


@itemize *

@item 
提供 @ref{252,,Py_EnterRecursiveCall()} 和 @ref{253,,Py_LeaveRecursiveCall()} 作为常规函数用于受限 API。 在之前版本中是使用宏定义，但这些宏不能与无法访问 @code{PyThreadState.recursion_depth} 字段的受限 C API 一同编译（该结构体在受限 C API 中是不透明的）。

@item 
@code{PyObject_INIT()} 和 @code{PyObject_INIT_VAR()} 已成为常规“不透明”函数以隐藏实现细节。
@end itemize

（由 Victor Stinner 在 bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644} 和 bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542} 中贡献。）

@item 
增加了 @ref{254,,PyModule_AddType()} 函数以协助将类型加入到模块中。 （由 Dong-hee Na 在 bpo-40024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40024} 中贡献。）

@item 
将 @ref{255,,PyObject_GC_IsTracked()} 和 @ref{256,,PyObject_GC_IsFinalized()} 函数添加到公有 API 以允许分别查询 Python 对象当前是正在被追踪还是已经被垃圾回收器所终结。 （由 Pablo Galindo Salgado 在 bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241} 中贡献。）

@item 
增加了 @code{_PyObject_FunctionStr()} 以获取函数类对象的用户友好的表示形式。 （由 Jeroen Demeyer 在 bpo-37645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37645} 中修正。）

@item 
增加了 @ref{257,,PyObject_CallOneArg()} 用于调用具有一个位置参数的对象（由 Jeroen Demeyer 在 bpo-37483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37483} 中修正。）
@end itemize

@node 移植到 Python 3 9<2>,移除<2>,新的特性<2>,C API 的改变
@anchor{whatsnew/3 9 id2}@anchor{258}
@subsubsection 移植到 Python 3.9



@itemize *

@item 
@code{PyInterpreterState.eval_frame} (
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523}) 现在需要有新的强制性形参 @emph{tstate} (@code{PyThreadState*})。 （由 Victor Stinner 在 bpo-38500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38500} 中贡献。）

@item 
扩展模块: @ref{259,,PyModuleDef} 的 @ref{25a,,m_traverse}, @ref{25b,,m_clear} 和 @ref{25c,,m_free} 等函数在模块状态被请求但尚未被分配时将不会再被调用。 这种情况出现在模块被创建之后且模块被执行 (@ref{25d,,Py_mod_exec} 函数) 之前的时刻。 更准确地说，这些函数在 @ref{25e,,m_size} 大于 0 并且模块状态（即 @ref{25f,,PyModule_GetState()} 的返回值）为 @code{NULL} 时将不会被调用。

没有模块状态的扩展模块 (@code{m_size <= 0}) 不会受到影响。

@item 
现在如果 @ref{260,,Py_AddPendingCall()} 是在子解释器内部被调用，该函数会被排入子解释器的调用日程，而不是由主解释器调用。 每个子解释器现在都拥有它们自己的调用日程列表。 （由 Victor Stinner 在 bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984} 中贡献。）

@item 
当 @code{-E} 选项被使用 (如果 @ref{261,,PyConfig.use_environment} 设为 @code{0}) 时将不再使用 Windows 注册表来初始化 @ref{262,,sys.path}。 这会影响在 Windows 上嵌入 Python 的操作。 （由 Zackery Spytz 在 bpo-8901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8901} 中贡献。）

@item 
全局变量 @ref{263,,PyStructSequence_UnnamedField} 现在为常量并且指向一个字符串常量。 （由 Serhiy Storchaka 在 bpo-38650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38650} 中贡献。）

@item 
现在 @code{PyGC_Head} 结构是不透明的。 它只在内部 C API (@code{pycore_gc.h}) 中定义。 （由 Victor Stinner 在 bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241} 中贡献。）

@item 
@code{Py_UNICODE_COPY}, @code{Py_UNICODE_FILL}, @code{PyUnicode_WSTR_LENGTH}, @ref{264,,PyUnicode_FromUnicode()}, @ref{265,,PyUnicode_AsUnicode()}, @code{_PyUnicode_AsUnicode} 以及 @ref{266,,PyUnicode_AsUnicodeAndSize()} 在 C 中被标记为已弃用。 它们自 Python 3.3 起就已被 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 弃用。 （由 Inada Naoki 在 bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346} 中贡献。）

@item 
@ref{267,,Py_FatalError()} 函数会被一个自动记录当前函数名称的宏所替代，除非已定义了 @code{Py_LIMITED_API} 宏。 （由 Victor Stinner 在 bpo-39882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39882} 中贡献。）

@item 
vectorcall 协议现在要求调用者只传入字符串作为键名。 （请参阅 bpo-37540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37540} 了解详情。）

@item 
多个宏和函数的实现细节现在已被隐藏:


@itemize *

@item 
@ref{268,,PyObject_IS_GC()} 宏已被转换为函数。

@item 
@code{PyObject_NEW()} 宏已成为 @ref{269,,PyObject_New()} 宏的别名，而 @code{PyObject_NEW_VAR()} 宏已成为 @ref{26a,,PyObject_NewVar()} 宏的别名。  它们将不再直接访问 @ref{26b,,PyTypeObject.tp_basicsize} 成员。

@item 
@code{PyObject_GET_WEAKREFS_LISTPTR()} 宏已被转换为函数：该宏会直接访问 @ref{26c,,PyTypeObject.tp_weaklistoffset} 成员。

@item 
@ref{26d,,PyObject_CheckBuffer()} 宏已被转换为函数：该宏会直接访问 @ref{26e,,PyTypeObject.tp_as_buffer} 成员。

@item 
现在 @ref{26f,,PyIndex_Check()} 总是被声明为不透明函数以隐藏实现细节；@code{PyIndex_Check()} 宏已被移除。 该宏会直接访问 @ref{270,,PyTypeObject.tp_as_number} 成员。
@end itemize

（详情请参阅 bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}。）
@end itemize

@node 移除<2>,,移植到 Python 3 9<2>,C API 的改变
@anchor{whatsnew/3 9 id3}@anchor{271}
@subsubsection 移除



@itemize *

@item 
@code{pyfpe.h} 的 @code{PyFPE_START_PROTECT()} 和 @code{PyFPE_END_PROTECT()} 宏已从受限的 C API 中被排除。 （由 Victor Stinner 在 bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835} 中贡献。）

@item 
@ref{272,,PyTypeObject} 的 @code{tp_print} 空位已被移除。 它在 Python 2.7 及之前的版本中被用来将对象打印到文件。 自 Python 3.0 起，它已被忽略并且不再使用。 （由 Jeroen Demeyer 在 bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974} 中贡献。）

@item 
受限 C API 中的改变（如果定义了 @code{Py_LIMITED_API} 宏）:


@itemize *

@item 
以下函数已从受限 C API 中排除:


@itemize *

@item 
@code{PyThreadState_DeleteCurrent()} （由 Joannah Nanjekye 在 bpo-37878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37878} 中贡献。）

@item 
@code{_Py_CheckRecursionLimit}

@item 
@code{_Py_NewReference()}

@item 
@code{_Py_ForgetReference()}

@item 
@code{_PyTraceMalloc_NewReference()}

@item 
@code{_Py_GetRefTotal()}

@item 
在受限 C API 中从未使用的垃圾箱机制。

@item 
@code{PyTrash_UNWIND_LEVEL}

@item 
@code{Py_TRASHCAN_BEGIN_CONDITION}

@item 
@code{Py_TRASHCAN_BEGIN}

@item 
@code{Py_TRASHCAN_END}

@item 
@code{Py_TRASHCAN_SAFE_BEGIN}

@item 
@code{Py_TRASHCAN_SAFE_END}
@end itemize

@item 
已将下列函数和定义移至内部 C API:


@itemize *

@item 
@code{_PyDebug_PrintTotalRefs()}

@item 
@code{_Py_PrintReferences()}

@item 
@code{_Py_PrintReferenceAddresses()}

@item 
@code{_Py_tracemalloc_config}

@item 
@code{_Py_AddToAllObjects()} (@code{Py_TRACE_REFS} 构建专属)
@end itemize
@end itemize

（由 Victor Stinner 在 bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644} 和 bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542} 中贡献。）

@item 
移除了 @code{_PyRuntime.getframe} 钩子并移除了 @code{_PyThreadState_GetFrame} 宏，该宏是 @code{_PyRuntime.getframe} 的一个别名。 它们仅由内部 C API 对外公开。 同样地移除了 @code{PyThreadFrameGetter} 类型。 （由 Victor Stinner 在 bpo-39946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39946} 中贡献。）

@item 
从 C API 移除了下列函数。 请显式地调用 @code{PyGC_Collect()} 来清空所有自由列表。 （由 Inada Naoki 和 Victor Stinner 在 bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340}, bpo-38896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38896} 和 bpo-40428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40428} 中贡献。）


@itemize *

@item 
@code{PyAsyncGen_ClearFreeLists()}

@item 
@code{PyContext_ClearFreeList()}

@item 
@code{PyDict_ClearFreeList()}

@item 
@code{PyFloat_ClearFreeList()}

@item 
@code{PyFrame_ClearFreeList()}

@item 
@code{PyList_ClearFreeList()}

@item 
@code{PyMethod_ClearFreeList()} 和 @code{PyCFunction_ClearFreeList()}: 绑定方法对象的自由列表已被移除。

@item 
@code{PySet_ClearFreeList()}: 集合自由列表已在 Python 3.4 中被移除。

@item 
@code{PyTuple_ClearFreeList()}

@item 
@code{PyUnicode_ClearFreeList()}: Unicode 自由列表已在 Python 3.3 中被移除。
@end itemize

@item 
移除了 @code{_PyUnicode_ClearStaticStrings()} 函数。 （由 Victor Stinner 在 bpo-39465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39465} 中贡献。）

@item 
移除了 @code{Py_UNICODE_MATCH}。 它已被 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 所弃用，并自 Python 3.3 起不再可用。 可以改用 @ref{273,,PyUnicode_Tailmatch()} 函数。 （由 Inada Naoki 在 bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346} 中贡献。）

@item 
清除了已定义但未实现的接口的头文件。 被移除了公共 API 符号有: @code{_PyBytes_InsertThousandsGroupingLocale}, @code{_PyBytes_InsertThousandsGrouping}, @code{_Py_InitializeFromArgs}, @code{_Py_InitializeFromWideArgs}, @code{_PyFloat_Repr}, @code{_PyFloat_Digits}, @code{_PyFloat_DigitsInit}, @code{PyFrame_ExtendStack}, @code{_PyAIterWrapper_Type}, @code{PyNullImporter_Type}, @code{PyCmpWrapper_Type}, @code{PySortWrapper_Type}, @code{PyNoArgsFunction}。 （由 Pablo Galindo Salgado 在 bpo-39372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39372} 中贡献。）
@end itemize

@node Python 3 9 1 中的重要变化,Python 3 9 2 中的重要变化,C API 的改变,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-1}@anchor{274}
@subsection Python 3.9.1 中的重要变化


@menu
* typing: typing<2>. 
* macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持. 

@end menu

@node typing<2>,macOS 11 0 Big Sur 与 Apple Silicon Mac 支持,,Python 3 9 1 中的重要变化
@anchor{whatsnew/3 9 id4}@anchor{275}
@subsubsection typing


@ref{276,,typing.Literal} 的行为被改为遵循 
@geindex Python 提高建议; PEP 586
PEP 586@footnote{https://www.python.org/dev/peps/pep-0586} 并匹配该 PEP 所描述的静态类型检查器的行为。


@enumerate 

@item 
@code{Literal} 现在将是去重复的形参。

@item 
@code{Literal} 对象间的相等性比较现在将是顺序无关的。

@item 
@code{Literal} 比较现在会考虑类型。 例如 @code{Literal[0] == Literal[False]} 之前的结果值为 @code{True}。 现在则为 @code{False}。 为支持此改变，内部使用的类型缓存现在也支持区分类型。

@item 
现在如果有任何一个参数不为 @ref{277,,hashable}，@code{Literal} 对象将在相等性比较期间引发 @ref{1ff,,TypeError}。 请注意使用可变参数声明 @code{Literal} 将不会抛出异常:

@example
>>> from typing import Literal
>>> Literal[@{0@}]
>>> Literal[@{0@}] == Literal[@{False@}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
@end example
@end enumerate

（由 Yurii Karabas 在 bpo-42345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42345} 中贡献。）

@node macOS 11 0 Big Sur 与 Apple Silicon Mac 支持,,typing<2>,Python 3 9 1 中的重要变化
@anchor{whatsnew/3 9 macos-11-0-big-sur-and-apple-silicon-mac-support}@anchor{278}
@subsubsection macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持


对于 3.9.1 版来说，Python 现在完全支持在 macOS 11.0 (Big Sur) 和 Apple Silicon Macs (基于 @code{ARM64} 架构) 上构建和运行。 现在提供了一个新的通用构建类型 @code{universal2}，用于在一组可执行文件上原生支持 @code{ARM64} 和 @code{Intel 64}。 二进制文件现在也可以在当前版本的 macOS 上编译以部署到多种较旧的 macOS 版本上 (已测试 10.9)，同时会基于运行时所使用的操作系统版本让某些较新的 OS 功能和选项有条件地可用 ("弱链接") 。

（由 Ronald Oussoren 和 Lawrence D'Anna 在 bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100} 中贡献。）

@node Python 3 9 2 中的重要变化,Python 3 9 3 中的重要变化,Python 3 9 1 中的重要变化,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-2}@anchor{279}
@subsection Python 3.9.2 中的重要变化


@menu
* collections.abc: collections abc. 
* urllib.parse: urllib parse. 

@end menu

@node collections abc,urllib parse,,Python 3 9 2 中的重要变化
@anchor{whatsnew/3 9 collections-abc}@anchor{27a}
@subsubsection collections.abc


现在 @ref{27b,,collections.abc.Callable} 泛型会将类型形参展平，类似于 @ref{27c,,typing.Callable} 当前所做的那样。 这意味着 @code{collections.abc.Callable[[int, str], str]} 的 @code{__args__} 将为 @code{(int, str, str)}；之前则为 @code{([int, str], str)}。 为了允许这个改变，@ref{27d,,types.GenericAlias} 现在可以被子类化，并且在抽取 @ref{27b,,collections.abc.Callable} 类型时将返回一个子类。 通过 @ref{27e,,typing.get_args()} 或 @code{__args__} 访问参数的代码需要考虑到这个改变。 对于无效的 @ref{27b,,collections.abc.Callable} 参数化形式可能会发出 @ref{15a,,DeprecationWarning}，这在 Python 3.9.1 中可能会静默地传递。 这个 @ref{15a,,DeprecationWarning} 将在 Python 3.10 中变为 @ref{1ff,,TypeError}。 （由 Ken Jin 在 bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195} 中贡献。）

@node urllib parse,,collections abc,Python 3 9 2 中的重要变化
@anchor{whatsnew/3 9 urllib-parse}@anchor{27f}
@subsubsection urllib.parse


早先的 Python 版本允许使用 @code{;} 和 @code{&} 作为 @ref{280,,urllib.parse.parse_qs()} 和 @ref{281,,urllib.parse.parse_qsl()} 中 query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被改为只允许单个分隔键，默认为 @code{&}。 这一改变还会影响 @ref{282,,cgi.parse()} 和 @ref{283,,cgi.parse_multipart()} 因为它们在内部使用了受影响的函数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt, Senthil Kumaran 和 Ken Jin 在 bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967} 中贡献。）

@node Python 3 9 3 中的重要变化,Python 3 9 5 中的重要变化,Python 3 9 2 中的重要变化,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-3}@anchor{284}
@subsection Python 3.9.3 中的重要变化


新的安全修正将A security fix alters the @ref{1a6,,ftplib.FTP} 的行为改成当设置被动数据通道时不信任远程服务器所发送的 IPv4 地址。 我们会改为重用 FTP 服务器的 IP 地址。  对于需要原先行为的不常见代码，请在你的 FTP 实例上设置 @code{trust_server_pasv_ipv4_address} 属性为 @code{True}。 (参见 bpo-43285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43285})

@node Python 3 9 5 中的重要变化,Notable security feature in 3 9 14,Python 3 9 3 中的重要变化,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-changes-in-python-3-9-5}@anchor{285}
@subsection Python 3.9.5 中的重要变化


@menu
* urllib.parse: urllib parse<2>. 

@end menu

@node urllib parse<2>,,,Python 3 9 5 中的重要变化
@anchor{whatsnew/3 9 id5}@anchor{286}
@subsubsection urllib.parse


在 URL 部分中存在换行符或制表符可导致某些形式的攻击。 跟随更新了 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html}  的 WHATWG 规格描述，ASCII 换行 @code{\n}, @code{\r} 和制表 @code{\t} 等字符会被 @ref{128,,urllib.parse} 的解析器从 URL 中移除以防止此类攻击。 移除字符操作是由新的模块级变量 @code{urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE} 来控制的。 (参见 bpo-43882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43882})

@node Notable security feature in 3 9 14,Notable Changes in 3 9 17,Python 3 9 5 中的重要变化,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-security-feature-in-3-9-14}@anchor{287}
@subsection Notable security feature in 3.9.14


Converting between @ref{205,,int} and @ref{206,,str} in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a @ref{16d,,ValueError} if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for CVE-2020-10735@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735}.
This limit can be configured or disabled by environment variable, command
line flag, or @ref{fd,,sys} APIs. See the @ref{288,,integer string conversion length limitation} documentation.  The default limit
is 4300 digits in string form.

@node Notable Changes in 3 9 17,,Notable security feature in 3 9 14,Python 3 9 有什么新变化
@anchor{whatsnew/3 9 notable-changes-in-3-9-17}@anchor{289}
@subsection Notable Changes in 3.9.17


@menu
* tarfile:: 

@end menu

@node tarfile,,,Notable Changes in 3 9 17
@anchor{whatsnew/3 9 tarfile}@anchor{28a}
@subsubsection tarfile



@itemize *

@item 
The extraction methods in @ref{101,,tarfile}, and @ref{28b,,shutil.unpack_archive()},
have a new a @emph{filter} argument that allows limiting tar features than may be
surprising or dangerous, such as creating files outside the destination
directory.
See @ref{28c,,Extraction filters} for details.
In Python 3.12, use without the @emph{filter} argument will show a
@ref{15a,,DeprecationWarning}.
In Python 3.14, the default will switch to @code{'data'}.
(Contributed by Petr Viktorin in 
@geindex Python 提高建议; PEP 706
PEP 706@footnote{https://www.python.org/dev/peps/pep-0706}.)
@end itemize

@node Python 3 8 有什么新变化,Python 3 7 有什么新变化,Python 3 9 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 8 doc}@anchor{28d}@anchor{whatsnew/3 8 what-s-new-in-python-3-8}@anchor{28e}
@section Python 3.8 有什么新变化


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Git log
@c when researching a change.

@*编者: 
Raymond Hettinger


本文解释了 Python 3.8 相比 3.7 的新增特性。 完整的详情可参阅 @ref{156,,更新日志}。

@c from datetime import date
@c from math import cos, radians
@c from unicodedata import normalize
@c import re
@c import math

@menu
* 摘要 - 发布重点: 摘要 - 发布重点<2>. 
* 新的特性: 新的特性<3>. 
* 其他语言特性修改: 其他语言特性修改<2>. 
* 新增模块: 新增模块<2>. 
* 改进的模块: 改进的模块<2>. 
* 性能优化: 性能优化<2>. 
* 构建和 C API 的改变:: 
* 弃用: 弃用<2>. 
* API 与特性的移除:: 
* 移植到 Python 3.8: 移植到 Python 3 8. 
* Python 3.8.1 中的重要变化: Python 3 8 1 中的重要变化. 
* Python 3.8.8 中的重要变化: Python 3 8 8 中的重要变化. 
* Python 3.8.12 中的重要变化: Python 3 8 12 中的重要变化. 

@end menu

@node 摘要 - 发布重点<2>,新的特性<3>,,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 summary-release-highlights}@anchor{28f}
@subsection 摘要 - 发布重点


@c This section singles out the most important changes in Python 3.8.
@c Brevity is key.

@c PEP-sized items next.

@node 新的特性<3>,其他语言特性修改<2>,摘要 - 发布重点<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 new-features}@anchor{290}
@subsection 新的特性


@menu
* 赋值表达式:: 
* 仅限位置形参:: 
* 用于已编译字节码文件的并行文件系统缓存:: 
* 调试构建使用与发布构建相同的 ABI:: 
* f-字符串支持 = 用于自动记录表达式和调试文档:: 
* PEP 578; Python 运行时审核钩子: PEP 578 Python 运行时审核钩子. 
* PEP 587; Python 初始化配置: PEP 587 Python 初始化配置. 
* PEP 590; Vectorcall; 用于 CPython 的快速调用协议: PEP 590 Vectorcall 用于 CPython 的快速调用协议. 
* 具有外部数据缓冲区的 pickle 协议 5:: 

@end menu

@node 赋值表达式,仅限位置形参,,新的特性<3>
@anchor{whatsnew/3 8 assignment-expressions}@anchor{291}
@subsubsection 赋值表达式


新增的语法 @code{:=} 可在表达式内部为变量赋值。 它被昵称为“海象运算符”因为它很像是 海象的眼睛和长牙@footnote{https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg}。

在这个示例中，赋值表达式可以避免调用 @ref{292,,len()} 两次:

@example
if (n := len(a)) > 10:
    print(f"List is too long (@{n@} elements, expected <= 10)")
@end example

类似的益处还可出现在正则表达式匹配中需要使用两次匹配对象的情况中，一次检测用于匹配是否发生，另一次用于提取子分组:

@example
discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0
@end example

此运算符也适用于配合 while 循环计算一个值来检测循环是否终止，而同一个值又在循环体中再次被使用的情况:

@example
# Loop over fixed length blocks
while (block := f.read(256)) != '@w{'}:
    process(block)
@end example

另一个值得介绍的用例出现于列表推导式中，在筛选条件中计算一个值，而同一个值又在表达式中需要被使用:

@example
[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]
@end example

请尽量将海象运算符的使用限制在清晰的场合中，以降低复杂性并提升可读性。

请参阅 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} 了解详情。

（由 Morehouse 在 bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224} 中贡献。）

@node 仅限位置形参,用于已编译字节码文件的并行文件系统缓存,赋值表达式,新的特性<3>
@anchor{whatsnew/3 8 positional-only-parameters}@anchor{293}
@subsubsection 仅限位置形参


新增了一个函数形参语法 @code{/} 用来指明某些函数形参必须使用仅限位置而非关键字参数的形式。 这种标记语法与通过 @code{help()} 所显示的使用 Larry Hastings 的 Argument Clinic@footnote{https://docs.python.org/3/howto/clinic.html} 工具标记的 C 函数相同。

在下面的例子中，形参 @emph{a} 和 @emph{b} 为仅限位置形参，@emph{c} 或 @emph{d} 可以是位置形参或关键字形参，而 @emph{e} 或 @emph{f} 要求为关键字形参:

@example
def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)
@end example

以下均为合法的调用:

@example
f(10, 20, 30, d=40, e=50, f=60)
@end example

但是，以下均为不合法的调用:

@example
f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60)           # e must be a keyword argument
@end example

这种标记形式的一个用例是它允许纯 Python 函数完整模拟现有的用 C 代码编写的函数的行为。 例如，内置的 @ref{294,,divmod()} 函数不接受关键字参数:

@example
def divmod(a, b, /):
    "Emulate the built in divmod() function"
    return (a // b, a % b)
@end example

另一个用例是在不需要形参名称时排除关键字参数。 例如，内置的 @ref{292,,len()} 函数的签名为 @code{len(obj, /)}。 这可以排除如下这种笨拙的调用形式:

@example
len(obj='hello')  # The "obj" keyword argument impairs readability
@end example

另一个益处是将形参标记为仅限位置形参将允许在未来修改形参名而不会破坏客户的代码。 例如，在 @ref{f5,,statistics} 模块中，形参名 @emph{dist} 在未来可能被修改。 这使得以下函数描述成为可能:

@example
def quantiles(dist, /, *, n=4, method='exclusive')
    ...
@end example

由于在 @code{/} 左侧的形参不会被公开为可用关键字，其他形参名仍可在 @code{**kwargs} 中使用:

@example
>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 @{'a': 1, 'b': 2, 'c': 3@}
@end example

这极大地简化了需要接受任意关键字参数的函数和方法的实现。 例如，以下是一段摘自 @ref{1d,,collections} 模块的代码:

@example
class Counter(dict):

    def __init__(self, iterable=None, /, **kwds):
        # Note "iterable" is a possible keyword argument
@end example

请参阅 
@geindex Python 提高建议; PEP 570
PEP 570@footnote{https://www.python.org/dev/peps/pep-0570} 了解详情。

（由 Pablo Galindo 在 bpo-36540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36540} 中贡献。）

@c TODO: Pablo will sprint on docs at PyCon US 2019.

@node 用于已编译字节码文件的并行文件系统缓存,调试构建使用与发布构建相同的 ABI,仅限位置形参,新的特性<3>
@anchor{whatsnew/3 8 parallel-filesystem-cache-for-compiled-bytecode-files}@anchor{295}
@subsubsection 用于已编译字节码文件的并行文件系统缓存


新增的 
@geindex PYTHONPYCACHEPREFIX
@geindex 环境变量; PYTHONPYCACHEPREFIX
@ref{296,,PYTHONPYCACHEPREFIX} 设置 (也可使用 @ref{297,,-X} @code{pycache_prefix}) 可将隐式的字节码缓存配置为使用单独的并行文件系统树，而不是默认的每个源代码目录下的 @code{__pycache__} 子目录。

缓存的位置会在 @ref{298,,sys.pycache_prefix} 中报告 (@ref{204,,None} 表示默认位置即 @code{__pycache__} 子目录)。

（由 Carl Meyer 在 bpo-33499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33499} 中贡献。）

@node 调试构建使用与发布构建相同的 ABI,f-字符串支持 = 用于自动记录表达式和调试文档,用于已编译字节码文件的并行文件系统缓存,新的特性<3>
@anchor{whatsnew/3 8 debug-build-uses-the-same-abi-as-release-build}@anchor{299}
@subsubsection 调试构建使用与发布构建相同的 ABI


Python 现在不论是以发布模式还是调试模式进行构建都将使用相同的 ABI。 在 Unix 上，当 Python 以调试模式构建时，现在将可以加载以发布模式构建的 C 扩展和使用稳定版 ABI 构建的 C 扩展。

发布构建和调试构建现在都是 ABI 兼容的：定义 @code{Py_DEBUG} 宏不会再启用 @code{Py_TRACE_REFS} 宏，它引入了唯一的 ABI 不兼容性。 @code{Py_TRACE_REFS} 宏添加了 @code{sys.getobjects()} 函数和 
@geindex PYTHONDUMPREFS
@geindex 环境变量; PYTHONDUMPREFS
@ref{29a,,PYTHONDUMPREFS} 环境变量，它可以使用新的 @code{./configure --with-trace-refs} 构建选项来设置。 （由 Victor Stinner 在 bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465} 中贡献。）

在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例外。 现在静态链接的 Python 将可以加载使用共享库 Python 构建的 C 扩展。 （由 Victor Stinner 在 bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536} 中贡献。）

在 Unix 上，当 Python 以调试模式构建时，导入操作现在也会查找在发布模式下编译的 C 扩展以及使用稳定版 ABI 编译的 C 扩展。 （由 Victor Stinner 在 bpo-36722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36722} 中贡献。）

要将 Python 嵌入到一个应用中，必须将新增的 @code{--embed} 选项传给 @code{python3-config --libs --embed} 以获得 @code{-lpython3.8} (将应用链接到 libpython)。 要同时支持 3.8 和旧版本，请先尝试 @code{python3-config --libs --embed} 并在此命令失败时回退到 @code{python3-config --libs} (即不带 @code{--embed})。

增加一个 pkg-config @code{python-3.8-embed} 模块用来将 Python 嵌入到一个应用中: @code{pkg-config python-3.8-embed --libs} 包含 @code{-lpython3.8}。 要同时支持 3.8 和旧版本，请先尝试 @code{pkg-config python-X.Y-embed --libs} 并在此命令失败时回退到 @code{pkg-config python-X.Y --libs} (即不带 @code{--embed}) （请将 @code{X.Y} 替换为 Python 版本号）。

另一方面，@code{pkg-config python3.8 --libs} 不再包含 @code{-lpython3.8}。 C 扩展不可被链接到 libpython (但 Android 和 Cygwin 例外，这两者的情况由脚本处理)；此改变是故意被设为向下不兼容的。 （由 Victor Stinner 在 bpo-36721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36721} 中贡献。）

@node f-字符串支持 = 用于自动记录表达式和调试文档,PEP 578 Python 运行时审核钩子,调试构建使用与发布构建相同的 ABI,新的特性<3>
@anchor{whatsnew/3 8 f-strings-support-for-self-documenting-expressions-and-debugging}@anchor{29b}
@subsubsection f-字符串支持 @code{=} 用于自动记录表达式和调试文档


增加 @code{=} 说明符用于 @ref{29c,,f-string}。 形式为 @code{f'@{expr=@}'} 的 f-字符串将扩展表示为表达式文本，加一个等于号，再加表达式的求值结果。 例如：

@example
>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'@{user=@} @{member_since=@}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"
@end example

通常的 @ref{29d,,f-字符串格式说明符} 允许更细致地控制所要显示的表达式结果:

@example
>>> delta = date.today() - member_since
>>> f'@{user=!s@}  @{delta.days=:,d@}'
'user=eric_idle  delta.days=16,075'
@end example

@code{=} 说明符将输出整个表达式，以便详细演示计算过程:

@example
>>> print(f'@{theta=@}  @{cos(radians(theta))=:.3f@}')
theta=30  cos(radians(theta))=0.866
@end example

（由 Eric V. Smith 和 Larry Hastings 在 bpo-36817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36817} 中贡献。）

@node PEP 578 Python 运行时审核钩子,PEP 587 Python 初始化配置,f-字符串支持 = 用于自动记录表达式和调试文档,新的特性<3>
@anchor{whatsnew/3 8 pep-578-python-runtime-audit-hooks}@anchor{29e}
@subsubsection PEP 578: Python 运行时审核钩子


此 PEP 添加了审核钩子和已验证开放钩子。 两者在 Python 与本机代码中均可用。允许以纯 Python 代码编写的应用和框架利用额外的通知，同时允许嵌入开发人员或系统管理员部署始终启用审核的 Python 版本。

请参阅 
@geindex Python 提高建议; PEP 578
PEP 578@footnote{https://www.python.org/dev/peps/pep-0578} 了解详情。

@node PEP 587 Python 初始化配置,PEP 590 Vectorcall 用于 CPython 的快速调用协议,PEP 578 Python 运行时审核钩子,新的特性<3>
@anchor{whatsnew/3 8 pep-587-python-initialization-configuration}@anchor{29f}
@subsubsection PEP 587: Python 初始化配置


@geindex Python 提高建议; PEP 587
PEP 587@footnote{https://www.python.org/dev/peps/pep-0587} 增加了一个新的 C API 用来配置 Python 初始化，提供对整个配置过程的更细致控制以及更好的错误报告。

新的结构：


@itemize *

@item 
@ref{227,,PyConfig}

@item 
@ref{2a0,,PyPreConfig}

@item 
@ref{2a1,,PyStatus}

@item 
@ref{2a2,,PyWideStringList}
@end itemize

新的函数：


@itemize *

@item 
@ref{2a3,,PyConfig_Clear()}

@item 
@ref{2a4,,PyConfig_InitIsolatedConfig()}

@item 
@ref{2a5,,PyConfig_InitPythonConfig()}

@item 
@ref{2a6,,PyConfig_Read()}

@item 
@ref{2a7,,PyConfig_SetArgv()}

@item 
@ref{2a8,,PyConfig_SetBytesArgv()}

@item 
@ref{2a9,,PyConfig_SetBytesString()}

@item 
@ref{2aa,,PyConfig_SetString()}

@item 
@ref{2ab,,PyPreConfig_InitIsolatedConfig()}

@item 
@ref{2ac,,PyPreConfig_InitPythonConfig()}

@item 
@ref{2ad,,PyStatus_Error()}

@item 
@ref{2ae,,PyStatus_Exception()}

@item 
@ref{2af,,PyStatus_Exit()}

@item 
@ref{2b0,,PyStatus_IsError()}

@item 
@ref{2b1,,PyStatus_IsExit()}

@item 
@ref{2b2,,PyStatus_NoMemory()}

@item 
@ref{2b3,,PyStatus_Ok()}

@item 
@ref{2b4,,PyWideStringList_Append()}

@item 
@ref{2b5,,PyWideStringList_Insert()}

@item 
@ref{2b6,,Py_BytesMain()}

@item 
@ref{2b7,,Py_ExitStatusException()}

@item 
@ref{2b8,,Py_InitializeFromConfig()}

@item 
@ref{2b9,,Py_PreInitialize()}

@item 
@ref{2ba,,Py_PreInitializeFromArgs()}

@item 
@ref{2bb,,Py_PreInitializeFromBytesArgs()}

@item 
@ref{2bc,,Py_RunMain()}
@end itemize

此 PEP 还为这些内部结构添加了 @code{_PyRuntimeState.preconfig} (@ref{2a0,,PyPreConfig} 类型) 和 @code{PyInterpreterState.config} (@ref{227,,PyConfig} 类型) 字段。 @code{PyInterpreterState.config} 成为新的引用配置，替代全局配置变量和其他私有变量。

请参阅 @ref{2bd,,Python 初始化配置} 获取详细文档。

请参阅 
@geindex Python 提高建议; PEP 587
PEP 587@footnote{https://www.python.org/dev/peps/pep-0587} 了解详情。

（由 Victor Stinner 在 bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763} 中贡献。）

@node PEP 590 Vectorcall 用于 CPython 的快速调用协议,具有外部数据缓冲区的 pickle 协议 5,PEP 587 Python 初始化配置,新的特性<3>
@anchor{whatsnew/3 8 pep-590-vectorcall-a-fast-calling-protocol-for-cpython}@anchor{2be}
@subsubsection PEP 590: Vectorcall: 用于 CPython 的快速调用协议


将 @ref{2bf,,Vectorcall 协议} 添加到 Python/C API。 它的目标是对已被应用于许多类的现有优化进行正式化。 任何实现可调用对象的静态类型均可使用此协议。

此特性目前为暂定状态，计划在 Python 3.9 将其完全公开。

请参阅 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590} 了解详情。

（由 Jeroen Demeyer, Mark Shannon 和 Petr Viktorin 在 bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974} 中贡献。）

@node 具有外部数据缓冲区的 pickle 协议 5,,PEP 590 Vectorcall 用于 CPython 的快速调用协议,新的特性<3>
@anchor{whatsnew/3 8 pickle-protocol-5-with-out-of-band-data-buffers}@anchor{2c0}
@subsubsection 具有外部数据缓冲区的 pickle 协议 5


当使用 @ref{ca,,pickle} 在 Python 进程间传输大量数据以充分发挥多核或多机处理的优势时，非常重要一点是通过减少内存拷贝来优化传输效率，并可能应用一些定制技巧例如针对特定数据的压缩。

@ref{ca,,pickle} 协议 5 引入了对于外部缓冲区的支持，这样 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} 兼容的数据可以与主 pickle 流分开进行传输，这是由通信层来确定的。

请参阅 
@geindex Python 提高建议; PEP 574
PEP 574@footnote{https://www.python.org/dev/peps/pep-0574} 了解详情。

（由 Antoine Pitrou 在 bpo-36785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36785} 中贡献。）

@node 其他语言特性修改<2>,新增模块<2>,新的特性<3>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 other-language-changes}@anchor{2c1}
@subsection 其他语言特性修改



@itemize *

@item 
在之前版本中 @ref{2c2,,continue} 语句不允许在 @ref{2c3,,finally} 子句中使用，这是因为具体实现存在一个问题。 在 Python 3.8 中此限制已被取消。 （由 Serhiy Storchaka 在 bpo-32489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32489} 中贡献。）

@item 
@ref{2c4,,bool}, @ref{205,,int} 和 @ref{2c5,,fractions.Fraction} 类型现在都有一个 @ref{2c6,,as_integer_ratio()} 方法，与 @ref{1fe,,float} 和 @ref{2c7,,decimal.Decimal} 中的已有方法类似。 这个微小的 API 扩展使得 @code{numerator, denominator = x.as_integer_ratio()} 这样的写法在多种数字类型上通用成为可能。 （由 Lisa Roach 在 bpo-33073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33073} 和 Raymond Hettinger 在 bpo-37819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37819} 中贡献。）

@item 
@ref{205,,int}, @ref{1fe,,float} 和 @ref{2c8,,complex} 的构造器现在会使用 @ref{2c9,,__index__()} 特殊方法，如果该方法可用而对应的方法 method @ref{2ca,,__int__()}, @ref{2cb,,__float__()} 或 @ref{2cc,,__complex__()} 方法不可用的话。 （由 Serhiy Storchaka 在 bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092} 中贡献。）

@item 
添加 @code{\N@{name@}} 转义符在 @ref{dd,,正则表达式} 中的支持:

@example
>>> notice = 'Copyright © 2019'
>>> copyright_year_pattern = re.compile(r'\N@{copyright sign@}\s*(\d@{4@})')
>>> int(copyright_year_pattern.search(notice).group(1))
2019
@end example

（由 Jonathan Eunice 和 Serhiy Storchaka 在 bpo-30688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30688} 中贡献。）

@item 
现在 dict 和 dictview 可以使用 @ref{2cd,,reversed()} 按插入顺序反向迭代。 （由 Rémi Lapeyre 在 bpo-33462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33462} 中贡献。）

@item 
在函数调用中允许使用的关键字名称语法受到进一步的限制。 特别地，@code{f((keyword)=arg)} 不再被允许。 关键字参数赋值形式的左侧绝不允许一般标识符以外的其他内容。 （由 Benjamin Peterson 在 bpo-34641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34641} 中贡献。）

@item 
在 @ref{2ce,,yield} 和 @ref{2cf,,return} 语句中的一般可迭代对象解包不再要求加圆括号。 这使得 @emph{yield} 和 @emph{return} 的语法与正常的赋值语法更为一致:

@example
>>> def parse(family):
        lastname, *members = family.split()
        return lastname.upper(), *members

>>> parse('simpsons homer marge bart lisa maggie')
('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')
@end example

（由 David Cuthbert 和 Jordan Chapman 在 bpo-32117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32117} 中贡献。）

@item 
当类似 @code{[(10, 20) (30, 40)]} 这样在代码中少了一个逗号时，编译器将显示 @ref{2d0,,SyntaxWarning} 并附带更有帮助的提示。 这相比原来用 @ref{1ff,,TypeError} 来提示第一个元组是不可调用的更容易被理解。 （由 Serhiy Storchaka 在 bpo-15248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15248} 中贡献。）

@item 
@ref{19d,,datetime.date} 或 @ref{19f,,datetime.datetime} 和 @ref{2d1,,datetime.timedelta} 对象之间的算术运算现在将返回相应子类的实例而不是基类的实例。 这也会影响到在具体实现中（直接或间接地）使用了 @ref{2d1,,datetime.timedelta} 算术运算的返回类型，例如 @ref{2d2,,astimezone()}。 （由 Paul Ganssle 在 bpo-32417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32417} 中贡献。）

@item 
当 Python 解释器通过 Ctrl-C (SIGINT) 被中断并且所产生的 @ref{2d3,,KeyboardInterrupt} 异常未被捕获，Python 进程现在会通过一个 SIGINT 信号或是使得发起调用的进程能检测到它是由 Ctrl-C 操作杀死的正确退出代码来退出。 POSIX 和 Windows 上的终端会相应地使用此代码在交互式会话中终止脚本。 （由 Google 的 Gregory P. Smith 在 bpo-1054041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1054041} 中贡献。）

@item 
某些高级编程风格要求为现有的函数更新 @ref{2d4,,types.CodeType} 对象。 由于代码对象是不可变的，需要基于现有代码对象模型创建一个新的代码对象。 使用 19 个形参将会相当繁琐。 现在，新的 @code{replace()} 方法使得通过少量修改的形参创建克隆对象成为可能。

下面是一个修改 @ref{2d5,,statistics.mean()} 函数来防止 @emph{data} 形参被用作关键字参数的例子:

@example
>>> from statistics import mean
>>> mean(data=[10, 20, 90])
40
>>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
>>> mean(data=[10, 20, 90])
Traceback (most recent call last):
  ...
TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'
@end example

（由 Victor Stinner 在 bpo-37032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37032} 中贡献。）

@item 
对于整数，现在 @ref{2d6,,pow()} 函数的三参数形式在底数与模数不可约的情况下允许指数为负值。 随后它会在指数为 @code{-1} 时计算底数的模乘逆元，并对其他负指数计算反模的适当幂次。 例如，要计算 38 模 137 的 模乘逆元@footnote{https://en.wikipedia.org/wiki/Modular_multiplicative_inverse} 则可写为:

@example
>>> pow(38, -1, 137)
119
>>> 119 * 38 % 137
1
@end example

模乘逆元在求解 线性丢番图方程@footnote{https://en.wikipedia.org/wiki/Diophantine_equation} 会被用到。 例如，想要求出 @code{4258𝑥 + 147𝑦 = 369} 的整数解，首先应重写为 @code{4258𝑥 ≡ 369 (mod 147)} 然后求解：

@example
>>> x = 369 * pow(4258, -1, 147) % 147
>>> y = (4258 * x - 369) // -147
>>> 4258 * x + 147 * y
369
@end example

（由 Mark Dickinson 在 bpo-36027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36027} 中贡献。）

@item 
字典推导式已与字典字面值实现同步，会先计算键再计算值:

@example
>>> # Dict comprehension
>>> cast = @{input('role? '): input('actor? ') for i in range(2)@}
role? King Arthur
actor? Chapman
role? Black Knight
actor? Cleese

>>> # Dict literal
>>> cast = @{input('role? '): input('actor? ')@}
role? Sir Robin
actor? Eric Idle
@end example

对执行顺序的保证对赋值表达式来说很有用，因为在键表达式中赋值的变量将可在值表达式中被使用:

@example
>>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
>>> @{(n := normalize('NFC', name)).casefold() : n for name in names@}
@{'martin von löwis': 'Martin von Löwis',
 'łukasz langa': 'Łukasz Langa',
 'walter dörwald': 'Walter Dörwald'@}
@end example

（由 Jörn Heissler 在 bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224} 中贡献。）

@item 
@ref{2d7,,object.__reduce__()} 方法现在可返回长度为二至六个元素的元组。 之前的上限为五个。 新增的第六个可选元素是签名为 @code{(obj, state)} 的可调用对象。 这样就允许直接控制特定对象的状态更新。 如果元素值不为 @emph{None}，该可调用对象将优先于对象的 @ref{2d8,,__setstate__()} 方法。 （由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900} 中贡献。）
@end itemize

@node 新增模块<2>,改进的模块<2>,其他语言特性修改<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 new-modules}@anchor{2d9}
@subsection 新增模块



@itemize *

@item 
新增的 @ref{9d,,importlib.metadata} 模块提供了从第三方包读取元数据的（临时）支持。 例如，它可以提取一个已安装软件包的版本号、入口点列表等等:

@example
>>> # Note following example requires that the popular "requests"
>>> # package has been installed.
>>>
>>> from importlib.metadata import version, requires, files
>>> version('requests')
'2.22.0'
>>> list(requires('requests'))
['chardet (<3.1.0,>=3.0.2)']
>>> list(files('requests'))[:5]
[PackagePath('requests-2.22.0.dist-info/INSTALLER'),
 PackagePath('requests-2.22.0.dist-info/LICENSE'),
 PackagePath('requests-2.22.0.dist-info/METADATA'),
 PackagePath('requests-2.22.0.dist-info/RECORD'),
 PackagePath('requests-2.22.0.dist-info/WHEEL')]
@end example

（由 Barry Warsaw 和 Jason R. Coombs 在 bpo-34632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34632} 中贡献）。
@end itemize

@node 改进的模块<2>,性能优化<2>,新增模块<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 improved-modules}@anchor{2da}
@subsection 改进的模块


@menu
* ast: ast<2>. 
* asyncio: asyncio<2>. 
* builtins:: 
* collections:: 
* cProfile:: 
* csv:: 
* curses: curses<2>. 
* ctypes:: 
* datetime: datetime<2>. 
* functools:: 
* gc: gc<2>. 
* gettext:: 
* gzip:: 
* IDLE 与 idlelib: IDLE 与 idlelib<2>. 
* inspect: inspect<2>. 
* io:: 
* itertools:: 
* json.tool: json tool. 
* logging:: 
* math: math<2>. 
* mmap:: 
* multiprocessing: multiprocessing<2>. 
* os: os<2>. 
* os.path: os path. 
* pathlib: pathlib<2>. 
* pickle:: 
* plistlib:: 
* pprint: pprint<2>. 
* py_compile:: 
* shlex:: 
* shutil:: 
* socket: socket<2>. 
* ssl:: 
* statistics:: 
* sys: sys<2>. 
* tarfile: tarfile<2>. 
* threading:: 
* tokenize:: 
* tkinter:: 
* time: time<2>. 
* typing: typing<3>. 
* unicodedata: unicodedata<2>. 
* unittest:: 
* venv: venv<2>. 
* weakref:: 
* xml: xml<2>. 
* xmlrpc:: 

@end menu

@node ast<2>,asyncio<2>,,改进的模块<2>
@anchor{whatsnew/3 8 ast}@anchor{2db}
@subsubsection ast


AST 节点现在具有 @code{end_lineno} 和 @code{end_col_offset} 属性，它们给出节点结束的精确位置。 （这只适用于具有 @code{lineno} 和 @code{col_offset} 属性的节点。）

新增函数 @ref{2dc,,ast.get_source_segment()} 返回指定 AST 节点的源代码。

（由 Ivan Levkivskyi 在 bpo-33416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33416} 中贡献。）

@ref{2dd,,ast.parse()} 函数具有一些新的旗标：


@itemize *

@item 
@code{type_comments=True} 导致其返回与特定 AST 节点相关联的 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 类型注释文本；

@item 
@code{mode='func_type'} 可被用于解析 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} "签名类型注释" (为函数定义 AST 节点而返回)；

@item 
@code{feature_version=(3, N)} 允许指定一个更早的 Python 3 版本。 例如，@code{feature_version=(3, 4)} 将把 @ref{2de,,async} 和 @ref{2df,,await} 视为非保留字。
@end itemize

（由 Guido van Rossum 在 bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766} 中贡献。）

@node asyncio<2>,builtins,ast<2>,改进的模块<2>
@anchor{whatsnew/3 8 asyncio}@anchor{2e0}
@subsubsection asyncio


@ref{18d,,asyncio.run()} 已经从暂定状态晋级为稳定 API。 此函数可被用于执行一个 @ref{18a,,coroutine} 并返回结果，同时自动管理事件循环。 例如:

@example
import asyncio

async def main():
    await asyncio.sleep(0)
    return 42

asyncio.run(main())
@end example

这 @emph{大致} 等价于:

@example
import asyncio

async def main():
    await asyncio.sleep(0)
    return 42

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    asyncio.set_event_loop(None)
    loop.close()
@end example

实际的实现要更复杂许多。 因此 @ref{18d,,asyncio.run()} 应该作为运行 asyncio 程序的首选方式。

（由 Yury Selivanov 在 bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314} 中贡献。）

运行 @code{python -m asyncio} 将启动一个原生异步 REPL。 这允许快速体验具有最高层级 @ref{2df,,await} 的代码。 这时不再需要直接调用 @code{asyncio.run()}，因为此操作会在每次发起调用时产生一个新事件循环：

@example
$ python -m asyncio
asyncio REPL 3.8.0
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
hello
@end example

（由 Yury Selivanov 在 bpo-37028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37028} 中贡献。）

异常 @ref{2e1,,asyncio.CancelledError} 现在继承自 @ref{2e2,,BaseException} 而不是 @ref{2e3,,Exception} 并且不再继承自 @ref{2e4,,concurrent.futures.CancelledError}。 （由 Yury Selivanov 在 bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528} 中贡献。）

在 Windows 上，现在默认的事件循环为 @ref{2e5,,ProactorEventLoop}。 （由 Victor Stinner 在 bpo-34687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34687} 中贡献。）

@ref{2e5,,ProactorEventLoop} 现在也支持 UDP。 （由 Adam Meily 和 Andrew Svetlov 在 bpo-29883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29883} 中贡献。）

@ref{2e5,,ProactorEventLoop} 现在可通过 @ref{2d3,,KeyboardInterrupt} ("CTRL+C") 来中断。 （由 Vladimir Matveev 在 bpo-23057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23057} 中贡献。）

添加了 @ref{2e6,,asyncio.Task.get_coro()} 用来获取 @ref{2e7,,asyncio.Task} 中的已包装协程。 （由 Alex Grönholm 在 bpo-36999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36999} 中贡献。）

asyncio 任务现在可以被命名，或者是通过将 @code{name} 关键字参数传给 @ref{2e8,,asyncio.create_task()} 或 @ref{2e9,,create_task()} 事件循环方法，或者是通过在任务对象上调用 @ref{2ea,,set_name()} 方法。 任务名称在 @ref{2e7,,asyncio.Task} 的 @code{repr()} 输出中可见，并且还可以使用 @ref{2eb,,get_name()} 方法来获取。 （由 Alex Grönholm 在 bpo-34270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34270} 中贡献。）

将对 Happy Eyeballs@footnote{https://en.wikipedia.org/wiki/Happy_Eyeballs} 的支持添加到 @ref{2ec,,asyncio.loop.create_connection()}。 要指定此行为，已增加了两个新的形参: @emph{happy_eyeballs_delay} 和 @emph{interleave}。 Happy Eyeballs 算法可提升支持 IPv4 和 IPv6 的应用的响应速度，具体做法是尝试同时使用两者进行连接。 （由 twisteroid ambassador 在 bpo-33530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33530} 中贡献。）

@node builtins,collections,asyncio<2>,改进的模块<2>
@anchor{whatsnew/3 8 builtins}@anchor{2ed}
@subsubsection builtins


内置的 @ref{2ee,,compile()} 已改进为可接受 @code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} 旗标。 当传入此新旗标时，@ref{2ee,,compile()} 将允许通常被视为无效语法的最高层级 @code{await}, @code{async for} 和 @code{async with} 构造。 此后将可返回带有 @code{CO_COROUTINE} 旗标的异步代码对象。 （由 Matthias Bussonnier 在 bpo-34616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34616} 中贡献。）

@node collections,cProfile,builtins,改进的模块<2>
@anchor{whatsnew/3 8 collections}@anchor{2ef}
@subsubsection collections


@ref{1a1,,collections.namedtuple()} 的 @ref{2f0,,_asdict()} 方法现在将返回 @ref{164,,dict} 而不是 @ref{2f1,,collections.OrderedDict}。 此项更改是由于普通字典自 Python 3.7 起已保证具有确定的元素顺序。 如果还需要 @code{OrderedDict} 的额外特性，建议的解决方案是将结果转换为需要的类型: @code{OrderedDict(nt._asdict())}。 （由 Raymond Hettinger 在 bpo-35864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35864} 中贡献。）

@node cProfile,csv,collections,改进的模块<2>
@anchor{whatsnew/3 8 cprofile}@anchor{2f2}
@subsubsection cProfile


@ref{2f3,,cProfile.Profile} 类现在可被用作上下文管理器。 在运行时对一个代码块实现性能分析:

@example
import cProfile

with cProfile.Profile() as profiler:
      # code to be profiled
      ...
@end example

（由 Scott Sanderson 在 bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235} 中贡献。）

@node csv,curses<2>,cProfile,改进的模块<2>
@anchor{whatsnew/3 8 csv}@anchor{2f4}
@subsubsection csv


@ref{2f5,,csv.DictReader} 现在将返回 @ref{164,,dict} 而不是 @ref{2f1,,collections.OrderedDict}。 此工具现在会更快速且消耗更少内存同时仍然保留字段顺序。 （由 Michael Selik 在 bpo-34003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34003} 中贡献。）

@node curses<2>,ctypes,csv,改进的模块<2>
@anchor{whatsnew/3 8 curses}@anchor{2f6}
@subsubsection curses


添加了一个新变量用于保存下层 ncurses 库的结构版信息: @ref{2f7,,ncurses_version}。 （由 Serhiy Storchaka 在 bpo-31680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31680} 中贡献。）

@node ctypes,datetime<2>,curses<2>,改进的模块<2>
@anchor{whatsnew/3 8 ctypes}@anchor{2f8}
@subsubsection ctypes


在 Windows 上，@ref{2f9,,CDLL} 及其子类现在接受 @emph{winmode} 形参来指定用于底层 @code{LoadLibraryEx} 调用的旗标。 默认旗标被设为仅加载来自可信任位置的 DLL 依赖项，包括 DLL 的存放路径（如果加载初始 DLL 时使用了完整或部分路径）以及通过 @ref{2fa,,add_dll_directory()} 添加的路径。 （由 Steve Dower 在 bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085} 中贡献。）

@node datetime<2>,functools,ctypes,改进的模块<2>
@anchor{whatsnew/3 8 datetime}@anchor{2fb}
@subsubsection datetime


添加了新的替代构造器 @ref{2fc,,datetime.date.fromisocalendar()} 和 @ref{2fd,,datetime.datetime.fromisocalendar()}，它们分别基于 ISO 年份、周序号和周内日序号来构造 @code{date} 和 @ref{30,,datetime} 对象；这两者分别是其所对应类中 @code{isocalendar} 方法的逆操作。 （由 Paul Ganssle 在 bpo-36004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36004} 中贡献。）

@node functools,gc<2>,datetime<2>,改进的模块<2>
@anchor{whatsnew/3 8 functools}@anchor{2fe}
@subsubsection functools


@ref{2ff,,functools.lru_cache()} 现在可直接作为装饰器而不是作为返回装饰器的函数。 因此这两种写法现在都被支持:

@example
@@lru_cache
def f(x):
    ...

@@lru_cache(maxsize=256)
def f(x):
    ...
@end example

（由 Raymond Hettinger 在 bpo-36772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36772} 中贡献。）

添加了新的 @ref{300,,functools.cached_property()} 装饰器，用于在实例生命周期内缓存的已计算特征属性。

@example
import functools
import statistics

class Dataset:
   def __init__(self, sequence_of_numbers):
      self.data = sequence_of_numbers

   @@functools.cached_property
   def variance(self):
      return statistics.variance(self.data)
@end example

（由 Carl Meyer 在 bpo-21145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21145} 中贡献）

添加了新的 @ref{301,,functools.singledispatchmethod()} 装饰器可使用 @ref{302,,single dispatch} 将方法转换为 @ref{303,,泛型函数}:

@example
from functools import singledispatchmethod
from contextlib import suppress

class TaskManager:

    def __init__(self, tasks):
        self.tasks = list(tasks)

    @@singledispatchmethod
    def discard(self, value):
        with suppress(ValueError):
            self.tasks.remove(value)

    @@discard.register(list)
    def _(self, tasks):
        targets = set(tasks)
        self.tasks = [x for x in self.tasks if x not in targets]
@end example

（由 Ethan Smith 在 bpo-32380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32380} 中贡献）

@node gc<2>,gettext,functools,改进的模块<2>
@anchor{whatsnew/3 8 gc}@anchor{304}
@subsubsection gc


@ref{305,,get_objects()} 现在能接受一个可选的 @emph{generation} 形参来指定一个用于获取对象的生成器。 （由 Pablo Galindo 在 bpo-36016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36016} 中贡献。）

@node gettext,gzip,gc<2>,改进的模块<2>
@anchor{whatsnew/3 8 gettext}@anchor{306}
@subsubsection gettext


添加了 @ref{307,,pgettext()} 及其变化形式。 （由 Franz Glasner, Éric Araujo 和 Cheryl Sabella 在 bpo-2504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2504} 中贡献。）

@node gzip,IDLE 与 idlelib<2>,gettext,改进的模块<2>
@anchor{whatsnew/3 8 gzip}@anchor{308}
@subsubsection gzip


添加 @emph{mtime} 形参到 @ref{309,,gzip.compress()} 用于可重现的输出。 （由 Guo Ci Teo 在 bpo-34898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34898} 中贡献。）

对于特定类型的无效或已损坏 gzip 文件现在将引发 @ref{30a,,BadGzipFile} 而不是 @ref{30b,,OSError}。 （由 Filip Gruszczyński, Michele Orrù 和 Zackery Spytz 在 bpo-6584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6584} 中贡献。）

@node IDLE 与 idlelib<2>,inspect<2>,gzip,改进的模块<2>
@anchor{whatsnew/3 8 idle-and-idlelib}@anchor{30c}
@subsubsection IDLE 与 idlelib


超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353} 中贡献。）

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella, Terry Jan Reedy 等人在 bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680} 和 bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627} 中贡献。）

在 IDLE 编辑器窗口中增加了可选的行号。 窗口打开时默认不显示行号，除非在配置对话框的 General 选项卡中特别设置。 已打开窗口中的行号可以在 Options 菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在 bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535} 中贡献。）

现在会使用 OS 本机编码格式在 Python 字符串和 Tcl 对象间进行转换。 这允许在 IDLE 中处理 emoji 和其他非 BMP 字符。 这些字符将可被显示或是从剪贴板复制和粘贴。 字符串从 Tcl 到 Python 的来回转换现在不会再发生失败。 （过去八年有许多人都为此付出过努力，问题最终由 Serhiy Storchaka 在 bpo-13153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13153} 中解决。）

在 3.8.1 中新增:

添加切换光标闪烁停止的选项。 （由 Zackery Spytz 在 bpo-4603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4603} 中贡献。）

Esc 键现在会关闭 IDLE 补全提示窗口。 （由 Johnny Najera 在 bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944} 中贡献。）

上述修改已被反向移植到 3.7 维护发行版中。

添加关键字到模块名称补全列表。 （由 Terry J. Reedy 在 bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765} 中贡献。）

@node inspect<2>,io,IDLE 与 idlelib<2>,改进的模块<2>
@anchor{whatsnew/3 8 inspect}@anchor{30d}
@subsubsection inspect


@ref{30e,,inspect.getdoc()} 函数现在可以找到 @code{__slots__} 的文档字符串，如果该属性是一个元素值为文档字符串的 @ref{164,,dict} 的话。 这提供了类似于目前已有的 @ref{30f,,property()}, @ref{310,,classmethod()} 和 @ref{311,,staticmethod()} 等函数的文档选项:

@example
class AudioClip:
    __slots__ = @{'bit_rate': 'expressed in kilohertz to one decimal place',
                 'duration': 'in seconds, rounded up to an integer'@}
    def __init__(self, bit_rate, duration):
        self.bit_rate = round(bit_rate / 1000.0, 1)
        self.duration = ceil(duration)
@end example

（由 Raymond Hettinger 在 bpo-36326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36326} 中贡献。）

@node io,itertools,inspect<2>,改进的模块<2>
@anchor{whatsnew/3 8 io}@anchor{312}
@subsubsection io


在开发模式 (@ref{297,,-X} @code{env}) 和调试构建中，@ref{313,,io.IOBase} 终结器现在会在 @code{close()} 方法失败时将异常写入日志。 发生的异常在发布构建中默认会被静默忽略。 （由 Victor Stinner 在 bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748} 中贡献。）

@node itertools,json tool,io,改进的模块<2>
@anchor{whatsnew/3 8 itertools}@anchor{314}
@subsubsection itertools


@ref{315,,itertools.accumulate()} 函数增加了可选的 @emph{initial} 关键字参数用来指定一个初始值:

@example
>>> from itertools import accumulate
>>> list(accumulate([10, 5, 30, 15], initial=1000))
[1000, 1010, 1015, 1045, 1060]
@end example

（由 Lisa Roach 在 bpo-34659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34659} 中贡献。）

@node json tool,logging,itertools,改进的模块<2>
@anchor{whatsnew/3 8 json-tool}@anchor{316}
@subsubsection json.tool


添加选项 @code{--json-lines} 用于将每个输入行解析为单独的 JSON 对象。 （由 Weipeng Hong 在 bpo-31553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31553} 中贡献。）

@node logging,math<2>,json tool,改进的模块<2>
@anchor{whatsnew/3 8 logging}@anchor{317}
@subsubsection logging


为 @ref{318,,logging.basicConfig()} 添加了 @emph{force} 关键字参数，当设为真值时，关联到根日志记录器的任何现有处理程序都将在执行由其他参数所指定的配置之前被移除并关闭。

这解决了一个长期存在的问题。 当一个日志处理器或 @emph{basicConfig()} 被调用时，对 @emph{basicConfig()} 的后续调用会被静默地忽略。 这导致使用交互提示符或 Jupyter 笔记本更新、试验或讲解各种日志配置选项变得相当困难。

（由 Raymond Hettinger 提议，由 Dong-hee Na 实现，并由 Vinay Sajip 在 bpo-33897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33897} 中完成审核。）

@node math<2>,mmap,logging,改进的模块<2>
@anchor{whatsnew/3 8 math}@anchor{319}
@subsubsection math


添加了新的函数 @ref{31a,,math.dist()} 用于计算两点之间的欧几里得距离。 （由 Raymond Hettinger 在 bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089} 中贡献。）

扩展了 @ref{31b,,math.hypot()} 函数以便处理更多的维度。 之前它仅支持 2-D 的情况。 （由 Raymond Hettinger 在 bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089} 中贡献。）

添加了新的函数 @ref{31c,,math.prod()} 作为的 @ref{31d,,sum()} 同类，该函数返回 'start' 值 (默认值: 1) 乘以一个数字可迭代对象的积:

@example
>>> prior = 0.8
>>> likelihoods = [0.625, 0.84, 0.30]
>>> math.prod(likelihoods, start=prior)
0.126
@end example

（由 Pablo Galindo 在 bpo-35606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35606} 中贡献。）

添加了两个新的组合函数 @ref{31e,,math.perm()} 和 @ref{31f,,math.comb()}:

@example
>>> math.perm(10, 3)    # Permutations of 10 things taken 3 at a time
720
>>> math.comb(10, 3)    # Combinations of 10 things taken 3 at a time
120
@end example

（由 Yash Aggarwal, Keller Fuchs, Serhiy Storchaka 和 Raymond Hettinger 在 bpo-37128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37128}, bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178} 和 bpo-35431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35431} 中贡献。）

添加了一个新函数 @ref{320,,math.isqrt()} 用于计算精确整数平方根而无需转换为浮点数。 该新函数支持任意大整数。 它的执行速度比 @code{floor(sqrt(n))} 快但是比 @ref{321,,math.sqrt()} 慢:

@example
>>> r = 650320427
>>> s = r ** 2
>>> isqrt(s - 1)         # correct
650320426
>>> floor(sqrt(s - 1))   # incorrect
650320427
@end example

（由 Mark Dickinson 在 bpo-36887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36887} 中贡献。）

函数 @ref{1fd,,math.factorial()} 不再接受非整数类参数。 （由 Pablo Galindo 在 bpo-33083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33083} 中贡献。）

@node mmap,multiprocessing<2>,math<2>,改进的模块<2>
@anchor{whatsnew/3 8 mmap}@anchor{322}
@subsubsection mmap


@ref{323,,mmap.mmap} 类现在具有一个 @ref{324,,madvise()} 方法用于访问 @code{madvise()} 系统调用。 （由 Zackery Spytz 在 bpo-32941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32941} 中贡献。）

@node multiprocessing<2>,os<2>,mmap,改进的模块<2>
@anchor{whatsnew/3 8 multiprocessing}@anchor{325}
@subsubsection multiprocessing


添加了新的 @ref{bc,,multiprocessing.shared_memory} 模块。 （由 Davin Potts 在 bpo-35813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35813} 中贡献。）

在macOS上，现在默认使用的启动方式是*spawn*启动方式。
（由 Victor Stinner 在 bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725} 中贡献。）

@node os<2>,os path,multiprocessing<2>,改进的模块<2>
@anchor{whatsnew/3 8 os}@anchor{326}
@subsubsection os


在 Windows 上添加了新函数 @ref{2fa,,add_dll_directory()} 用于在导入扩展模块或使用 @ref{2a,,ctypes} 加载 DLL 时为本机依赖提供额外搜索路径 。 （由 Steve Dower 在 bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085} 中贡献。）

添加了新的 @ref{327,,os.memfd_create()} 函数用于包装 @code{memfd_create()} 系统调用。 （由 Zackery Spytz 和 Christian Heimes 在 bpo-26836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26836} 中贡献。）

在 Windows 上，大部分用于处理重解析点,（包括符号链接和目录连接）的手动逻辑已被委托给操作系统。 特别地，@ref{328,,os.stat()} 现在将会遍历操作系统所支持的任何内容，而 @ref{329,,os.lstat()} 将只打开被标识为“名称代理”的重解析点，而其要由 @ref{328,,os.stat()} 打开其他的重解析点。 在所有情况下，@code{stat_result.st_mode} 将只为符号链接而非其他种类的重解析点设置 @code{S_IFLNK}。 要标识其他种类的重解析点，请检查新的 @code{stat_result.st_reparse_tag} 属性。

在 Windows 上，@ref{1d2,,os.readlink()} 现在能够读取目录连接。 请注意 @ref{32a,,islink()} 会对目录连接返回 @code{False}，因此首先检查 @code{islink} 的代码将连续把连接视为目录，而会处理 @ref{1d2,,os.readlink()} 所引发错误的代码现在会把连接视为链接。

（由 Steve Dower 在 bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834} 中贡献。）

@node os path,pathlib<2>,os<2>,改进的模块<2>
@anchor{whatsnew/3 8 os-path}@anchor{32b}
@subsubsection os.path


返回布尔值结果的 @ref{c5,,os.path} 函数例如 @ref{32c,,exists()}, @ref{32d,,lexists()}, @ref{32e,,isdir()}, @ref{32f,,isfile()}, @ref{32a,,islink()}, 以及 @ref{330,,ismount()} 现在对于包含在 OS 层级无法表示的字符或字节的路径将会返回 @code{False} 而不是引发 @ref{16d,,ValueError} 或其子类 @ref{331,,UnicodeEncodeError} 和 @ref{332,,UnicodeDecodeError}。 （由 Serhiy Storchaka 在 bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721} 中贡献。）

@ref{333,,expanduser()} 在 Windows 上现在改用 
@geindex USERPROFILE
@geindex 环境变量; USERPROFILE
@code{USERPROFILE} 环境变量而不再使用 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME}，后者通常不会为一般用户账户设置。 （由 Anthony Sottile 在 bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264} 中贡献。）

@ref{32e,,isdir()} 在 Windows 上将不再为不存在的目录的链接返回 @code{True}。

@ref{334,,realpath()} 在 Windows 上现在会识别重解析点，包括符号链接和目录连接。

（由 Steve Dower 在 bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834} 中贡献。）

@node pathlib<2>,pickle,os path,改进的模块<2>
@anchor{whatsnew/3 8 pathlib}@anchor{335}
@subsubsection pathlib


返回布尔值结果的 @ref{336,,pathlib.Path} 方法例如 @ref{337,,exists()}, @ref{338,,is_dir()}, @ref{339,,is_file()}, @ref{33a,,is_mount()}, @ref{33b,,is_symlink()}, @ref{33c,,is_block_device()}, @ref{33d,,is_char_device()}, @ref{33e,,is_fifo()}, @ref{33f,,is_socket()} 现在对于包含在 OS 层级无法表示的字符或字节的路径将会返回 @code{False} 而不是引发 @ref{16d,,ValueError} 或其子类 @ref{331,,UnicodeEncodeError}。 （由 Serhiy Storchaka 在 bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721} 中贡献。）

添加了 @ref{340,,pathlib.Path.link_to()} 用于创建指向某个路径的硬链接。 （由 Joannah Nanjekye 在 bpo-26978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26978} 中贡献。）

@node pickle,plistlib,pathlib<2>,改进的模块<2>
@anchor{whatsnew/3 8 pickle}@anchor{341}
@subsubsection pickle


@ref{ca,,pickle} 扩展子类化针对 C 优化的 @ref{342,,Pickler} 现在可通过定义特殊的 @ref{343,,reducer_override()} 方法来重载函数和类的封存逻辑。 （由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900} 中贡献。）

@node plistlib,pprint<2>,pickle,改进的模块<2>
@anchor{whatsnew/3 8 plistlib}@anchor{344}
@subsubsection plistlib


添加了新的 @ref{345,,plistlib.UID} 并启动了对读取和写入经过 NSKeyedArchiver 编码的二进制 plists 的支持。 （由 Jon Janzen 在 bpo-26707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26707} 中贡献。）

@node pprint<2>,py_compile,plistlib,改进的模块<2>
@anchor{whatsnew/3 8 pprint}@anchor{346}
@subsubsection pprint


@ref{d2,,pprint} 模块为一些函数添加了 @emph{sort_dicts} 形参。 默认情况下，这些函数会继续在渲染或打印之前对字典进行排序。 但是，如果 @emph{sort_dicts} 设为假值，则字典将保持键插入时的顺序。 这在调试期间与 JSON 输入进行比较时会很有用。

除此之外，还增加了一个方便的新函数 @ref{347,,pprint.pp()}，它类似于 @ref{348,,pprint.pprint()} 但它的 @emph{sort_dicts} 默认为 @code{False}:

@example
>>> from pprint import pprint, pp
>>> d = dict(source='input.txt', operation='filter', destination='output.txt')
>>> pp(d, width=40)                  # Original order
@{'source': 'input.txt',
 'operation': 'filter',
 'destination': 'output.txt'@}
>>> pprint(d, width=40)              # Keys sorted alphabetically
@{'destination': 'output.txt',
 'operation': 'filter',
 'source': 'input.txt'@}
@end example

（由 Rémi Lapeyre 在 bpo-30670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30670} 中贡献。）

@node py_compile,shlex,pprint<2>,改进的模块<2>
@anchor{whatsnew/3 8 py-compile}@anchor{349}
@subsubsection py_compile


@ref{34a,,py_compile.compile()} 现在支持静默模式。 （由 Joannah Nanjekye 在 bpo-22640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22640} 中贡献。）

@node shlex,shutil,py_compile,改进的模块<2>
@anchor{whatsnew/3 8 shlex}@anchor{34b}
@subsubsection shlex


新增了 @ref{34c,,shlex.join()} 函数作为 @ref{211,,shlex.split()} 的逆操作。 （由 Bo Bayles 在 bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102} 中贡献。）

@node shutil,socket<2>,shlex,改进的模块<2>
@anchor{whatsnew/3 8 shutil}@anchor{34d}
@subsubsection shutil


@ref{34e,,shutil.copytree()} 现在接受新的 @code{dirs_exist_ok} 关键字参数。 （由 Josh Bronson 在 bpo-20849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20849} 中贡献。）

@ref{34f,,shutil.make_archive()} 现在对新的归档默认使用 modern pax (POSIX.1-2001) 格式以提升可移植性和标准一致性，此特性继承自对 @ref{101,,tarfile} 模块的相应更改。 （由 C.A.M. Gerlach 在 bpo-30661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30661} 中贡献。）

@ref{350,,shutil.rmtree()} 在 Windows 上现在会移除目录连接而不会递归地先移除其中的内容。 （由 Steve Dower 在 bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834} 中贡献。）

@node socket<2>,ssl,shutil,改进的模块<2>
@anchor{whatsnew/3 8 socket}@anchor{351}
@subsubsection socket


添加了便捷的 @ref{352,,create_server()} 和 @ref{353,,has_dualstack_ipv6()} 函数以自动化在创建服务器套接字时通常情况下所必须的任务，包括在同一套接字中同时接受 IPv4 和 IPv6 连接。 （由 Giampaolo Rodolà 在 bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561} 中贡献。）

@ref{354,,socket.if_nameindex()}, @ref{355,,socket.if_nametoindex()} 和 @ref{356,,socket.if_indextoname()} 函数已经在 Windows 上实现。 （由 Zackery Spytz 在 bpo-37007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37007} 中贡献。）

@node ssl,statistics,socket<2>,改进的模块<2>
@anchor{whatsnew/3 8 ssl}@anchor{357}
@subsubsection ssl


增加了 @ref{358,,post_handshake_auth} 和 @ref{359,,verify_client_post_handshake()} 分别启用和初始化 TLS 1.3 握手后验证。 （由 Christian Heimes 在 bpo-34670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34670} 中贡献。）

@node statistics,sys<2>,ssl,改进的模块<2>
@anchor{whatsnew/3 8 statistics}@anchor{35a}
@subsubsection statistics


添加了 @ref{35b,,statistics.fmean()} 作为 @ref{2d5,,statistics.mean()} 的更快速的浮点数版版本。 （由 Raymond Hettinger 和 Steven D'Aprano 在 bpo-35904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35904} 中贡献。）

添加了 @ref{35c,,statistics.geometric_mean()} （由 Raymond Hettinger 在 bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181} 中贡献。）

添加了 @ref{35d,,statistics.multimode()} 用于返回最常见值的列表。 （由 Raymond Hettinger 在 bpo-35892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35892} 中贡献。）

添加了 @ref{35e,,statistics.quantiles()} 用于将数据或分布划分为多个等概率区间（例如四分位、十分位或百分位）。 （由 Raymond Hettinger 在 bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546} 中贡献。）

添加了 @ref{35f,,statistics.NormalDist} 用于创建和操纵随机变量的正态分布。 （由 Raymond Hettinger 在 bpo-36018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36018} 中贡献。）

@example
>>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
>>> temperature_feb.mean
6.0
>>> temperature_feb.stdev
6.356099432828281

>>> temperature_feb.cdf(3)            # Chance of being under 3 degrees
0.3184678262814532
>>> # Relative chance of being 7 degrees versus 10 degrees
>>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
1.2039930378537762

>>> el_niño = NormalDist(4, 2.5)
>>> temperature_feb += el_niño        # Add in a climate effect
>>> temperature_feb
NormalDist(mu=10.0, sigma=6.830080526611674)

>>> temperature_feb * (9/5) + 32      # Convert to Fahrenheit
NormalDist(mu=50.0, sigma=12.294144947901014)
>>> temperature_feb.samples(3)        # Generate random samples
[7.672102882379219, 12.000027119750287, 4.647488369766392]
@end example

@node sys<2>,tarfile<2>,statistics,改进的模块<2>
@anchor{whatsnew/3 8 sys}@anchor{360}
@subsubsection sys


添加了新的 @ref{361,,sys.unraisablehook()} 函数，可被重载以便控制如何处理“不可引发的异常”。 它会在发生了一个异常但 Python 没有办法处理时被调用。 例如，当一个析构器在垃圾回收时 (@ref{362,,gc.collect()}) 所引发的异常。 （由 Victor Stinner 在 bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829} 中贡献。）

@node tarfile<2>,threading,sys<2>,改进的模块<2>
@anchor{whatsnew/3 8 tarfile}@anchor{363}
@subsubsection tarfile


@ref{101,,tarfile} 模块现在对新的归档默认使用 modern pax (POSIX.1-2001) 格式而不再是之前的 GNU 专属格式。 这通过标准化和可扩展格式的统一编码 (UTF-8) 提升了跨平台可移植性，还提供了其他一些益处。 （由 C.A.M. Gerlach 在 bpo-36268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36268} 中贡献。）

@node threading,tokenize,tarfile<2>,改进的模块<2>
@anchor{whatsnew/3 8 threading}@anchor{364}
@subsubsection threading


添加了新的 @ref{365,,threading.excepthook()} 函数用来处理未捕获的 @ref{366,,threading.Thread.run()} 异常。 它可被重载以便控制如何处理未捕获的 @ref{366,,threading.Thread.run()} 异常。 （由 Victor Stinner 在 bpo-1230540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1230540} 中贡献。）

添加了新的 @ref{367,,threading.get_native_id()} 函数以及 @ref{21b,,threading.Thread} 类的 @ref{368,,native_id} 属性。 它们会返回内核所分配给当前线程的原生整数线程 ID。 此特性仅在特定平台上可用，参见 @ref{367,,get_native_id} 了解详情。 （由 Jake Tesler 在 bpo-36084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36084} 中贡献。）

@node tokenize,tkinter,threading,改进的模块<2>
@anchor{whatsnew/3 8 tokenize}@anchor{369}
@subsubsection tokenize


当提供不带末尾新行的输入时，@ref{11a,,tokenize} 模块现在会隐式地添加 @code{NEWLINE} 形符。 此行为现在已与 C 词法分析器的内部行为相匹配。 （由 Ammar Askar 在 bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899} 中贡献。）

@node tkinter,time<2>,tokenize,改进的模块<2>
@anchor{whatsnew/3 8 tkinter}@anchor{36a}
@subsubsection tkinter


在 @code{tkinter.Spinbox} 中添加了方法 @code{selection_from()}, @code{selection_present()}, @code{selection_range()} 和 @code{selection_to()}。 （由 Juliette Monsel 在 bpo-34829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34829} 中贡献。）

在 @code{tkinter.Canvas} 类中添加了方法 @code{moveto()}。 （由 Juliette Monsel 在 bpo-23831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23831} 中贡献。）

@code{tkinter.PhotoImage} 类现在具有 @code{transparency_get()} 和 @code{transparency_set()} 方法。 （由 Zackery Spytz 在 bpo-25451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25451} 中贡献。）

@node time<2>,typing<3>,tkinter,改进的模块<2>
@anchor{whatsnew/3 8 time}@anchor{36b}
@subsubsection time


为 macOS 10.12 添加了新的时钟 @ref{36c,,CLOCK_UPTIME_RAW}。 （由 Joannah Nanjekye 在 bpo-35702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35702} 中贡献。）

@node typing<3>,unicodedata<2>,time<2>,改进的模块<2>
@anchor{whatsnew/3 8 typing}@anchor{36d}
@subsubsection typing


@ref{122,,typing} 模块加入了一些新特性：


@itemize *

@item 
一个带有键专属类型的字典类型。 参见 
@geindex Python 提高建议; PEP 589
PEP 589@footnote{https://www.python.org/dev/peps/pep-0589} 和 @ref{36e,,typing.TypedDict}。 TypedDict 只使用字符串作为键。 默认情况下每个键都要求提供。 指定 "total=False" 以允许键作为可选项:

@example
class Location(TypedDict, total=False):
    lat_long: tuple
    grid_square: str
    xy_coordinate: tuple
@end example

@item 
Literal 类型。 参见 
@geindex Python 提高建议; PEP 586
PEP 586@footnote{https://www.python.org/dev/peps/pep-0586} 和 @ref{276,,typing.Literal}。 Literal 类型指明一个形参或返回值被限定为一个或多个特定的字面值:

@example
def get_status(port: int) -> Literal['connected', 'disconnected']:
    ...
@end example

@item 
"Final" 变量、函数、方法和类。 参见 
@geindex Python 提高建议; PEP 591
PEP 591@footnote{https://www.python.org/dev/peps/pep-0591}, @ref{36f,,typing.Final} 和 @ref{370,,typing.final()}。 final 限定符会指示静态类型检查器限制进行子类化、重载或重新赋值:

@example
pi: Final[float] = 3.1415926536
@end example

@item 
协议定义。 参见 
@geindex Python 提高建议; PEP 544
PEP 544@footnote{https://www.python.org/dev/peps/pep-0544}, @ref{371,,typing.Protocol} 和 @ref{372,,typing.runtime_checkable()}。 简单的 ABC 例如 @ref{373,,typing.SupportsInt} 现在是 @code{Protocol} 的子类。

@item 
新的协议类 @ref{374,,typing.SupportsIndex}。

@item 
新的函数 @ref{375,,typing.get_origin()} 和 @ref{27e,,typing.get_args()}。
@end itemize

@node unicodedata<2>,unittest,typing<3>,改进的模块<2>
@anchor{whatsnew/3 8 unicodedata}@anchor{376}
@subsubsection unicodedata


@ref{123,,unicodedata} 模块现在已升级为使用 Unicode 12.1.0@footnote{http://blog.unicode.org/2019/05/unicode-12-1-en.html} 发布版。

新的函数 @ref{377,,is_normalized()} 可被用来验证字符串是否为特定正规形式，通常会比实际进行字符串正规化要快得多。 （由 Max Belanger, David Euresti 和 Greg Price 在 bpo-32285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32285} 和 bpo-37966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37966} 中贡献。）

@node unittest,venv<2>,unicodedata<2>,改进的模块<2>
@anchor{whatsnew/3 8 unittest}@anchor{378}
@subsubsection unittest


添加了 @ref{379,,AsyncMock} 以支持异步版本的 @ref{37a,,Mock}。 同时也添加了相应的断言函数用于测试。 （由 Lisa Roach 在 bpo-26467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26467} 中贡献。）

unittest 添加了 @ref{37b,,addModuleCleanup()} 和 @ref{37c,,addClassCleanup()} 以支持对 @code{setUpModule()} 和 @ref{37d,,setUpClass()} 进行清理。 （由 Lisa Roach 在 bpo-24412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24412} 中贡献。）

一些模拟断言函数现在也会在失败时打印一个实际调用列表。 （由 Petter Strandmark 在 bpo-35047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35047} 中贡献。）

@ref{124,,unittest} 模块已支持通过 @ref{37e,,unittest.IsolatedAsyncioTestCase} 来使用协程作为测试用例。 （由 Andrew Svetlov 在 bpo-32972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32972} 中贡献。）

示例:

@example
import unittest


class TestRequest(unittest.IsolatedAsyncioTestCase):

    async def asyncSetUp(self):
        self.connection = await AsyncConnection()

    async def test_get(self):
        response = await self.connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)

    async def asyncTearDown(self):
        await self.connection.close()


if __name__ == "__main__":
    unittest.main()
@end example

@node venv<2>,weakref,unittest,改进的模块<2>
@anchor{whatsnew/3 8 venv}@anchor{37f}
@subsubsection venv


现在 @ref{12e,,venv} 在所有平台上都会包含 @code{Activate.ps1} 脚本用于在 PowerShell Core 6.1 下激活虚拟环境。 （由 Brett Cannon 在 bpo-32718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32718} 中贡献。）

@node weakref,xml<2>,venv<2>,改进的模块<2>
@anchor{whatsnew/3 8 weakref}@anchor{380}
@subsubsection weakref


由 @ref{381,,weakref.proxy()} 返回的代理对象现在除其他算术运算符外也支持矩阵乘法运算符 @code{@@} 和 @code{@@=}。 （由 Mark Dickinson 在 bpo-36669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36669} 中贡献。）

@node xml<2>,xmlrpc,weakref,改进的模块<2>
@anchor{whatsnew/3 8 xml}@anchor{382}
@subsubsection xml


作为对 DTD 和外部实体检索的缓解，在默认情况下 @ref{13e,,xml.dom.minidom} 和 @ref{144,,xml.sax} 模块不再处理外部实体。 （由 Christian Heimes 在 bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239} 中贡献。）

@ref{140,,xml.etree.ElementTree} 模块中的 @code{.find*()} 方法支持通配符搜索例如 @code{@{*@}tag}，此搜索会忽略命名空间以及返回给定命名空间中所有标签的 @code{@{namespace@}*}。 （由 Stefan Behnel 在 bpo-28238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28238} 中贡献。）

@ref{140,,xml.etree.ElementTree} 模块提供了实现 C14N 2.0 的新函数 @code{–xml.etree.ElementTree.canonicalize()}。 （由 Stefan Behnel 在 bpo-13611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13611} 中贡献。）

@ref{383,,xml.etree.ElementTree.XMLParser} 的目标对象可通过新的回调方法 @code{start_ns()} 和 @code{end_ns()} 来接受命名空间声明事件。 此外，@ref{384,,xml.etree.ElementTree.TreeBuilder} 目标可被配置为处理有关注释和处理指令事件以将它们包含在所生成的树当中。 （由 Stefan Behnel 在 bpo-36676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36676} 和 bpo-36673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36673} 中贡献。）

@node xmlrpc,,xml<2>,改进的模块<2>
@anchor{whatsnew/3 8 xmlrpc}@anchor{385}
@subsubsection xmlrpc


@ref{386,,xmlrpc.client.ServerProxy} 现在支持可选的 @emph{headers} 关键字参数作为随同每次请求发送的 HTTP 标头序列。 此特征的作用之一是使得从默认的基础认证升级到更快速的会话认证成为可能。 （由 Cédric Krier 在 bpo-35153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35153} 中贡献。）

@node 性能优化<2>,构建和 C API 的改变,改进的模块<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 optimizations}@anchor{387}
@subsection 性能优化



@itemize *

@item 
@ref{f9,,subprocess} 模块现在能在某些情况下使用 @ref{388,,os.posix_spawn()} 函数以获得更好的性能。 目前，它的使用仅限 macOS 和 Linux（使用 glibc 2.24 或更新版本），并要求满足以下条件：


@itemize *

@item 
@emph{close_fds} 为假值；

@item 
@emph{preexec_fn}, @emph{pass_fds}, @emph{cwd} 和 @emph{start_new_session} 形参未设置；

@item 
@emph{executable} 路径包含一个目录。
@end itemize

（由 Joannah Nanjekye 和 Victor Stinner 在 bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537} 中贡献。）

@item 
@ref{389,,shutil.copyfile()}, @ref{38a,,shutil.copy()}, @ref{38b,,shutil.copy2()}, @ref{34e,,shutil.copytree()} 和 @ref{38c,,shutil.move()} 在 Linux 和 macOS 上会使用平台专属的 "fast-copy" 系统调用以提高效率。 "fast-copy" 意味着拷贝操作发生于内核中，从而避免在进行 "@code{outfd.write(infd.read())}" 等操作时使用 Python 中的用户空间缓冲区。 在 Windows 上 @ref{389,,shutil.copyfile()} 会使用更大的默认缓冲区（1 MiB 而不是 16 KiB）并且使用基于 @ref{38d,,memoryview()} 的 @ref{38e,,shutil.copyfileobj()} 版本。 在同一分区内拷贝一个 512 MiB 文件的速度提升在 Linux 上约为 +26%，在 macOS 上为 +50%，在 Windows 上为 +40%。 此外还将消耗更少的 CPU 周期。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。 （由 Giampaolo Rodolà 在 bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671} 中贡献。）

@item 
@ref{34e,,shutil.copytree()} 会根据其所用缓存的 @ref{328,,os.stat()} 值使用 @ref{390,,os.scandir()} 函数及所有拷贝函数。 拷贝一个包含 8000 文件的目录的速度提升在 Linux 上约为 +9%，在 Windows 上为 +20%，对于 Windows SMB 共享目录则为 +30%。 此外 @ref{328,,os.stat()} 系统调用的次数也减少了 38%，使得 @ref{34e,,shutil.copytree()} 在网络文件系统上会特别快速。 （由Giampaolo Rodolà 在 bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695} 中贡献。）

@item 
@ref{ca,,pickle} 模块使用的默认协议现在为 Protocol 4，最早在 Python 3.4 中被引入。 它提供了比自 Python 3.0 起可用的 Protocol 3 更好的性能和更小的数据尺寸。

@item 
从 @code{PyGC_Head} 移除了一个 @ref{391,,Py_ssize_t} 成员。 所有跟踪 GC 的对象（例如 tuple, list, dict）大小减少了 4 或 8 字节。 （由 Inada Naoki 在 bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597} 中贡献。）

@item 
@ref{392,,uuid.UUID} 现在会使用 @code{__slots__} 以减少内存足迹。 （由 Wouter Bolsterlee 和 Tal Einat 在 bpo-30977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30977} 中贡献。）

@item 
@ref{393,,operator.itemgetter()} 的性能提升了 33%。 优化了参数处理，并为常见的在元组中单个非负整数索引的情况新增了一条快速路径（这是标准库中的典型用例）。 （由 Raymond Hettinger 在 bpo-35664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35664} 中贡献。

@item 
加快了在 @ref{1a1,,collections.namedtuple()} 中的字段查找。 它们现在的速度快了两倍以上，成为 Python 中最快的实例变量查找形式。 （由 Raymond Hettinger, Pablo Galindo 和 Joe Jevnik, Serhiy Storchaka 在 bpo-32492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32492} 中贡献。）

@item 
如果输入的可迭代对象的长度已知 (即输入对象实现了 @code{__len__})，@ref{1f9,,list} 构造器不会过度分配内部项缓冲区。 这使得所创建的列表资源占用平均减少了 12%。 （由 Raymond Hettinger 和 Pablo Galindo 在 bpo-33234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33234} 中贡献。）

@item 
类变量写入速度加倍。 当一个非冗余属性被更新时，之前存在一个更新 slots 的非必要调用。 （由 Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger, Neil Schemenauer, 和 Serhiy Storchaka 在 bpo-36012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36012} 中贡献。）

@item 
减少了传递给许多内置函数和方法的参数转换的开销。 这使得某些简单内置函数和方法的速度提升了 20--50%。 （由 Serhiy Storchaka 在 bpo-23867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23867}, bpo-35582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35582} 和 bpo-36127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36127} 中贡献。）

@item 
@code{LOAD_GLOBAL} 指令现在会使用新的 "per opcode cache" 机制。 它的速度现在提升了大约 40%。 （由 Yury Selivanov 和 Inada Naoki 在 bpo-26219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26219} 中贡献。）
@end itemize

@node 构建和 C API 的改变,弃用<2>,性能优化<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 build-and-c-api-changes}@anchor{394}
@subsection 构建和 C API 的改变



@itemize *

@item 
默认的 @ref{395,,sys.abiflags} 成为一个空字符串：pymalloc 的 @code{m} 旗标不再有意义（无论是否启用 pymalloc 构建都是兼容 ABI 的）因此已被移除。 （由 Victor Stinner 在 bpo-36707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36707} 中贡献。）

改变的例子：


@itemize *

@item 
只会安装 @code{python3.8} 程序，不再有 @code{python3.8m} 程序。

@item 
只会安装 @code{python3.8-config} 脚本，不再有 @code{python3.8m-config} 脚本。

@item 
@code{m} 旗标已经从动态库文件名后缀中移除：包括标准库中的扩展模块以及第三方包所产生和安装的模块例如从 PyPI 下载的模块。 以 Linux 为例，Python 3.7 的后缀 @code{.cpython-37m-x86_64-linux-gnu.so} 在 Python 3.8 中改为 @code{.cpython-38-x86_64-linux-gnu.so}。
@end itemize

@item 
重新组织了所有头文件以更好地区分不同种类的 API：


@itemize *

@item 
@code{Include/*.h} 应为可移植的公有稳定版 C API。

@item 
@code{Include/cpython/*.h} 应为 CPython 专属的不稳定版 C API；公有 API，部分私有 API 附加 @code{_Py} or @code{_PY} 前缀。

@item 
@code{Include/internal/*.h} 应为 CPython 特别专属的私有内部 C API。 此 API 不具备向下兼容保证并且不应在 CPython 以外被使用。 它们的公开仅适用于特别限定的需求例如调试器和性能分析等必须直接访问 CPython 内部数据而不通过调用函数的应用。 此 API 现在是通过 @code{make install} 安装的。
@end itemize

（由 Victor Stinner 在 bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134} 和 bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081} 中贡献，相关工作由 Eric Snow 在 Python 3.7 中发起。）

@item 
某些宏已被转换为静态内联函数：形参类型和返回类型定义良好，它们不再会有与宏相关的问题，变量具有局部作用域。 例如：


@itemize *

@item 
@ref{396,,Py_INCREF()}, @ref{397,,Py_DECREF()}

@item 
@ref{398,,Py_XINCREF()}, @ref{399,,Py_XDECREF()}

@item 
@code{PyObject_INIT()}, @code{PyObject_INIT_VAR()}

@item 
私有函数: @code{_PyObject_GC_TRACK()}, @code{_PyObject_GC_UNTRACK()}, @code{_Py_Dealloc()}
@end itemize

（由 Victor Stinner 在 bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059} 中贡献。）

@item 
@code{PyByteArray_Init()} 和 @code{PyByteArray_Fini()} 函数已被移除。 它们自 Python 2.7.4 和 Python 3.2.0 起就没有任何用处，被排除在受限 API (稳定版 ABI) 之外，并且未被写入文档。 （由 Victor Stinner 在 bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713} 中贡献。）

@item 
@code{PyExceptionClass_Name()} 的结果类型现在是 @code{const char *} 而非 @code{char *}。 （由 Serhiy Storchaka 在 bpo-33818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33818} 中贡献。）

@item 
@code{Modules/Setup.dist} 与 @code{Modules/Setup} 两者的共存已被移除。 之前在更新 CPython 源码树时，开发者必须手动拷贝 @code{Modules/Setup.dist} (在源码树内) 到 @code{Modules/Setup} (在构建树内) 以反映上游的任何改变。 旧特性对打包者来说有一点益处，但代价是对追踪 CPython 开发进程的开发者造成经常性的麻烦，因为忘记拷贝该文件可能导致构建失败。

现在构建系统总是会从源码树内的 @code{Modules/Setup} 读取数据。 建议希望定制该文件的开发者在 CPython 的一个 git 分叉或补丁文件中维护他们的更改，就如他们对源码树做任何其他改变时一样。

（由 Antoine Pitrou 在 bpo-32430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32430} 中贡献。）

@item 
将 Python 数字转换为 C 整型的函数例如 @ref{39a,,PyLong_AsLong()} 以及带有 @code{'i'} 之类整型转换格式单元的参数解析函数例如 @ref{39b,,PyArg_ParseTuple()} 现在如果可能将会使用 @ref{2c9,,__index__()} 特殊方法而不是 @ref{2ca,,__int__()}。 对于带有 @code{__int__()} 方法但没有 @code{__index__()} 方法的对象 (例如 @ref{2c7,,Decimal} 和 @ref{2c5,,Fraction}) 将会发出弃用警告。 对于实现了 @code{__index__()} 的对象 @ref{39c,,PyNumber_Check()} 现在将返回 @code{1}。 @ref{39d,,PyNumber_Long()}, @ref{39e,,PyNumber_Float()} 和 @ref{39f,,PyFloat_AsDouble()} 现在如果可能也将会使用 @code{__index__()} 方法。 （由 Serhiy Storchaka 在 bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048} 和 bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092} 中贡献。）

@item 
堆分配类型对象现在将增加它们在 @ref{3a0,,PyObject_Init()} (及其对应的宏 @code{PyObject_INIT}) 中的引用计数而不是在 @ref{3a1,,PyType_GenericAlloc()} 中。 修改实例分配或中止分配的类型可能需要进行调整。 （由 Elizondo 在 bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810} 中贡献。）

@item 
新增函数 @ref{3a2,,PyCode_NewWithPosOnlyArgs()} 允许创建代码对象例如 @ref{3a3,,PyCode_New()}，但带有一个额外的 @emph{posonlyargcount} 形参以指明仅限位置参数的数量。 （由 Pablo Galindo 在 bpo-37221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37221} 中贡献。）

@item 
@ref{3a4,,Py_SetPath()} 现在会将 @ref{3a5,,sys.executable} 设为程序完整路径 (@ref{3a6,,Py_GetProgramFullPath()}) 而不是程序名称 (@ref{3a7,,Py_GetProgramName()})。 （由 Victor Stinner 在 bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234} 中贡献。）
@end itemize

@node 弃用<2>,API 与特性的移除,构建和 C API 的改变,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 deprecated}@anchor{3a8}
@subsection 弃用



@itemize *

@item 
distutils 的 @code{bdist_wininst} 命令现在已弃用，请改用 @code{bdist_wheel} (wheel 包)。 （由 Victor Stinner 在 bpo-37481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37481} 中贡献。）

@item 
@ref{140,,ElementTree} 模块中的已弃用方法 @code{getchildren()} 和 @code{getiterator()} 现在会引发 @ref{15a,,DeprecationWarning} 而不是 @ref{15c,,PendingDeprecationWarning}。 它们将在 Python 3.9 中被移除。 （由 Serhiy Storchaka 在 bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209} 中贡献。）

@item 
将不是 @ref{18c,,concurrent.futures.ThreadPoolExecutor} 的实例的对象传给 @ref{3a9,,loop.set_default_executor()} 已被弃用，并将在 Python 3.9 中被禁止。 （由 Elvis Pranskevichus 在 bpo-34075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34075} 中贡献。）

@item 
@ref{3aa,,xml.dom.pulldom.DOMEventStream}, @ref{3ab,,wsgiref.util.FileWrapper} 和 @ref{3ac,,fileinput.FileInput} 的 @ref{3ad,,__getitem__()} 方法已被弃用。

这些方法的实现会忽略它们的 @emph{index} 形参，并改为返回下一条目。 （由 Berker Peksag 在 bpo-9372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9372} 中贡献。）

@item 
@ref{228,,typing.NamedTuple} 类已弃用了 @code{_field_types} 属性而改用具有同样信息的 @code{__annotations__} 属性。 （由 Raymond Hettinger 在 bpo-36320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36320} 中贡献。）

@item 
@ref{7,,ast} 类 @code{Num}, @code{Str}, @code{Bytes}, @code{NameConstant} 和 @code{Ellipsis} 被视为已弃用并将在未来的 Python 版本中被移除。 应当改用 @ref{3ae,,Constant}。 （由 Serhiy Storchaka 在 bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892} 中贡献。）

@item 
@ref{3af,,ast.NodeVisitor} 的方法 @code{visit_Num()}, @code{visit_Str()}, @code{visit_Bytes()}, @code{visit_NameConstant()} 和 @code{visit_Ellipsis()} 现在已被弃用，并且在未来的 Python 版本中将不再被调用。 添加 @code{visit_Constant()} 方法来处理所有常量节点。 （由 Serhiy Storchaka 在 bpo-36917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36917} 中贡献。）

@item 
@ref{3b0,,asyncio.coroutine()} @ref{174,,decorator} 已弃用并将在 3.10 版中被移除。 原有的 @code{@@asyncio.coroutine} 请改用 @ref{3b1,,async def} 来替代。 （由 Andrew Svetlov 在 bpo-36921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36921} 中贡献。）

@item 
在 @ref{9,,asyncio} 中，@emph{loop} 参数的显式传递已被弃用并且到 3.10 版时将会在以下函数中被移除: @ref{3b2,,asyncio.sleep()}, @ref{3b3,,asyncio.gather()}, @ref{3b4,,asyncio.shield()}, @ref{191,,asyncio.wait_for()}, @ref{208,,asyncio.wait()}, @ref{3b5,,asyncio.as_completed()}, @ref{2e7,,asyncio.Task}, @ref{3b6,,asyncio.Lock}, @ref{3b7,,asyncio.Event}, @ref{3b8,,asyncio.Condition}, @ref{3b9,,asyncio.Semaphore}, @ref{3ba,,asyncio.BoundedSemaphore}, @ref{3bb,,asyncio.Queue}, @ref{3bc,,asyncio.create_subprocess_exec()} 以及 @ref{3bd,,asyncio.create_subprocess_shell()}。

@item 
将协程对象显式传递给 @ref{208,,asyncio.wait()} 的做法已被弃用并且将在 3.11 版中被移除。 （由 Yury Selivanov 在 bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790} 中贡献。）

@item 
@ref{87,,gettext} 模块中的下列函数和方法已被弃用: @ref{3be,,lgettext()}, @ref{3bf,,ldgettext()}, @ref{3c0,,lngettext()} 和 @ref{3c1,,ldngettext()}。 它们返回已编码的字节串，如果转换后的字符串存在编码问题你将可能遭遇预期之外的异常。 更好的做法是使用 Python 3 中返回 Unicode 字符串的操作作为替代。 前面的函数都早已不宜使用。

函数 @ref{3c2,,bind_textdomain_codeset()}，方法 @ref{3c3,,output_charset()} 和 @ref{3c4,,set_output_charset()}，以及函数 @ref{3c5,,translation()} 和 @ref{3c6,,install()} 的 @emph{codeset} 形参也已被弃用，因为它们仅适用于 @code{l*gettext()} 函数。 （由 Serhiy Storchaka 在 bpo-33710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33710} 中贡献。）

@item 
@ref{21b,,threading.Thread} 的 @code{isAlive()} 方法已弃用。 （由 Dong-hee Na 在 bpo-35283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35283} 中贡献。）

@item 
许多接受整数参数的内置和扩展模块的函数现在将对传入 @ref{2c7,,Decimal}, @ref{2c5,,Fraction} 以及任何其他可被转换为整数但会丢失精度（即具有 @ref{2ca,,__int__()} 方法但没有 @ref{2c9,,__index__()} 方法）的对象发出弃用警告。 在未来的版本中则将报错。 （由 Serhiy Storchaka 在 bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048} 中贡献。）

@item 
以下参数作为关键字参数传递的方式已被弃用：


@itemize -

@item 
@ref{3c7,,functools.partialmethod()}, @ref{3c8,,weakref.finalize()}, @ref{3c9,,profile.Profile.runcall()}, @code{cProfile.Profile.runcall()}, @ref{3ca,,bdb.Bdb.runcall()}, @ref{3cb,,trace.Trace.runfunc()} 与 @ref{3cc,,curses.wrapper()} 中的 @emph{func}。

@item 
@ref{3cd,,unittest.TestCase.addCleanup()} 中的 @emph{function}。

@item 
@ref{18c,,concurrent.futures.ThreadPoolExecutor} 和 @ref{196,,concurrent.futures.ProcessPoolExecutor} 的  @ref{3ce,,submit()} 方法中的 @emph{fn}。

@item 
@ref{3cf,,contextlib.ExitStack.callback()}, @code{contextlib.AsyncExitStack.callback()} 和 @ref{3d0,,contextlib.AsyncExitStack.push_async_callback()} 中的 @emph{callback}。

@item 
@code{multiprocessing.managers.Server} 和 @code{multiprocessing.managers.SharedMemoryServer} 的 @code{create()} 方法中的 @emph{c} 和 @emph{typeid}。

@item 
@ref{3c8,,weakref.finalize()} 中的 @emph{obj}。
@end itemize

在未来版本的 Python 中，它们将成为 @ref{3d1,,仅限位置参数}。 （由 Serhiy Storchaka 在 bpo-36492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36492} 中贡献。）
@end itemize

@node API 与特性的移除,移植到 Python 3 8,弃用<2>,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 api-and-feature-removals}@anchor{3d2}
@subsection API 与特性的移除


下列特性与 API 已从 Python 3.8 中移除：


@itemize *

@item 
自 Python 3.3 起，从 @ref{1d,,collections} 导入 ABC 的做法已弃用，而应当从 @ref{1e,,collections.abc} 执行导入。 从 collections 导入的操作在 3.8 中已标记为被移除，但将推迟到 3.9 中实施。 （参见 bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952}。）

@item 
@code{macpath} 模块，在 Python 3.7 中弃用，现已被移除。 （由 Victor Stinner 在 bpo-35471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35471} 中贡献。）

@item 
函数 @code{platform.popen()} 已被移除，它自 Python 3.3 起就已被弃用：请改用 @ref{3d3,,os.popen()}。 （由 Victor Stinner 在 bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345} 中贡献。）

@item 
函数 @code{time.clock()} 已被移除，它自 Python 3.3 起就已被弃用：请根据具体需求改用 @ref{3d4,,time.perf_counter()} 或 @ref{3d5,,time.process_time()} 以获得具有良好定义的行为。 （由 Matthias Bussonnier 在 bpo-36895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36895} 中贡献。）

@item 
@code{pyvenv} 脚本已被移除，推荐改用 @code{python3.8 -m venv} 来帮助消除容易混淆 @code{pyvenv} 脚本所关联的 Python 解释器这一问题。 （由 Brett Cannon 在 bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427} 中贡献。）

@item 
@code{parse_qs}, @code{parse_qsl} 和 @code{escape} 已从 @ref{15,,cgi} 模块中被移除。 这些函数自 Python 3.2 或更早就已被弃用。 它们应改为从 @code{urllib.parse} 和 @code{html} 模块导入。

@item 
@code{filemode} 函数已从 @ref{101,,tarfile} 模块中被移除。 该函数未被写入文档，自 Python 3.3 起就已弃用。

@item 
@ref{383,,XMLParser} 构造器不再接受 @emph{html} 参数。 它从来没有任何作用并在 Python 3.4 中已被弃用。 所有其他形参现在都是 @ref{3d6,,仅限关键字参数}。 （由 Serhiy Storchaka 在 bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209} 中贡献。）

@item 
@ref{383,,XMLParser} 的 @code{doctype()} 方法已被移除。 （由 Serhiy Storchaka 在 bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209} 中贡献。）

@item 
"unicode_internal" 编解码器已被移除。 （由 Inada Naoki 在 bpo-36297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36297} 中贡献。）

@item 
@ref{f2,,sqlite3} 模块的 @code{Cache} 和 @code{Statement} 对象已不再公开给用户。 （由 Aviv Palivoda 在 bpo-30262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30262} 中贡献。）

@item 
@ref{3d7,,fileinput.input()} 和 @ref{3ac,,fileinput.FileInput()} 中自 Python 3.6 起就已被忽略并弃用的 @code{bufsize} 关键字参数已被移除。 由 Matthias Bussonnier 在 bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952} 中贡献。）

@item 
在 Python 3.7 中弃用的函数 @code{sys.set_coroutine_wrapper()} 和 @code{sys.get_coroutine_wrapper()} 已被移除。 （由 Matthias Bussonnier 在 bpo-36933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36933} 中贡献。）
@end itemize

@node 移植到 Python 3 8,Python 3 8 1 中的重要变化,API 与特性的移除,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 porting-to-python-3-8}@anchor{3d8}
@subsection 移植到 Python 3.8


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* Python 行为的改变:: 
* 更改的Python API:: 
* C API 中的改变:: 
* CPython 字节码的改变: CPython 字节码的改变<2>. 
* 演示和工具:: 

@end menu

@node Python 行为的改变,更改的Python API,,移植到 Python 3 8
@anchor{whatsnew/3 8 changes-in-python-behavior}@anchor{3d9}
@subsubsection Python 行为的改变



@itemize *

@item 
yield 表达式（包括 @code{yield} 和 @code{yield from} 子句）现在不允许在推导式和生成器表达式中使用（但 @code{for} 子句最左边的可迭代对象表达式除外）。 （由 Serhiy Storchaka 在 bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544} 中贡献。）

@item 
当标识号检测 (@code{is} 和 @code{is not}) 与特定类型的字面值 (例如字符串和数字) 一同使用时编译器现在会产生 @ref{2d0,,SyntaxWarning}。  这在 CPython 中通常是可行的，但并不被语言定义所保证。 该警告会建议用户改用相等性检测 (@code{==} and @code{!=})。 （由 Serhiy Storchaka 在 bpo-34850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34850} 中贡献。）

@item 
CPython 解释器在某些情况下可以忽略异常。 在 Python 3.8 中这种情况会更少发生。 特别地，从类型字典获取属性时引发的异常不会再被忽略。 （由 Serhiy Storchaka 在 bpo-35459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35459} 中贡献。）

@item 
从内置类型 @ref{2c4,,bool}, @ref{205,,int}, @ref{1fe,,float}, @ref{2c8,,complex} 和标准库的一些类中移除了 @code{__str__} 实现。 它们现在会从 @ref{3da,,object} 继承 @code{__str__()}。 作为结果，在这些类的子类中定义 @code{__repr__()} 方法将会影响它们的字符串表示。 （由 Serhiy Storchaka 在 bpo-36793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36793} 中贡献。）

@item 
在 AIX 上，@ref{3db,,sys.platform} 将不再包含主要版本号。 它将总是 @code{'aix'} 而不再是 @code{'aix3'} .. @code{'aix7'}。 由于较旧的 Python 版本会包含该版本号，因此推荐总是使用 @code{sys.platform.startswith('aix')}。 （由 M. Felt 在 bpo-36588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36588} 中贡献。）

@item 
现在 @ref{3dc,,PyEval_AcquireLock()} 和 @ref{3dd,,PyEval_AcquireThread()} 如果当解释器终结化时被调用将会终结当前线程，以使它们与 @ref{3de,,PyEval_RestoreThread()}, @ref{3df,,Py_END_ALLOW_THREADS()} 以及 @ref{3e0,,PyGILState_Ensure()} 保持一致。 如果不想要这样的行为，请通过检测 @code{_Py_IsFinalizing()} 或 @code{sys.is_finalizing()} 来保护该调用。 （由 Joannah Nanjekye 在 bpo-36475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36475} 中贡献。）
@end itemize

@node 更改的Python API,C API 中的改变,Python 行为的改变,移植到 Python 3 8
@anchor{whatsnew/3 8 changes-in-the-python-api}@anchor{3e1}
@subsubsection 更改的Python API



@itemize *

@item 
在 Windows 上 @ref{3e2,,os.getcwdb()} 函数现在会使用 UTF-8 编码格式而不是 ANSI 代码页：请参看 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} 了解具体原因。 该函数在 Windows 上不再被弃用。 （由 Victor Stinner 在 bpo-37412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37412} 中贡献。）

@item 
现在 @ref{3e3,,subprocess.Popen} 在某些情况下会使用 @ref{388,,os.posix_spawn()} 以获得更好的性能。 在适用于 Linux 的 Windows 子系统和 QEMU 用户模拟器上，使用 @ref{388,,os.posix_spawn()} 的 @code{Popen} 构造器不会再因为“找不到程序”这样的错误引发异常。 而是让子进程失败并返回一个非零的 @code{returncode}。 （由 Joannah Nanjekye 和 Victor Stinner 在 bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537} 中贡献。）

@item 
The @emph{preexec_fn} argument of * @ref{3e3,,subprocess.Popen} is no longer
compatible with subinterpreters. The use of the parameter in a
subinterpreter now raises @ref{3e4,,RuntimeError}.
(Contributed by Eric Snow in bpo-34651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34651}, modified by Christian Heimes
in bpo-37951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37951}.)

@item 
@code{imap.IMAP4.logout()} 方法不会再静默地忽略任意异常。 （由 Victor Stinner 在 bpo-36348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36348} 中贡献。）

@item 
函数 @code{platform.popen()} 已被移除，它自 Python 3.3 起就已被弃用：请改用 @ref{3d3,,os.popen()}。 （由 Victor Stinner 在 bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345} 中贡献。）

@item 
当传入多模数据时 @ref{3e5,,statistics.mode()} 函数不会再引发异常。 它将改为返回在输入数据中遇到的第一个模式。 （由 Raymond Hettinger 在 bpo-35892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35892} 中贡献。）

@item 
@ref{3e6,,tkinter.ttk.Treeview} 类的 @ref{3e7,,selection()} 方法不再接受参数。 带参数调用该方法来改变选择在 Python 3.6 中已弃用。 请使用专门方法例如 @ref{3e8,,selection_set()} 来改变选择。 （由 Serhiy Storchaka 在 bpo-31508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31508} 中贡献。）

@item 
@ref{13e,,xml.dom.minidom} 的 @code{writexml()}, @code{toxml()} 和 @code{toprettyxml()} 方法以及 @code{xml.etree} 的 @code{write()} 方法现在会保留用户指定的属性顺序。 （由 Diego Rojas 和 Raymond Hettinger 在 bpo-34160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34160} 中贡献。）

@item 
附带 @code{'r'} 旗标打开的 @ref{32,,dbm.dumb} 数据库现在将是只读的。 如果数据库不存在，附带 @code{'r'} 和 @code{'w'} 旗标的 @ref{3e9,,dbm.dumb.open()} 不会再创建数据库。 （由 Serhiy Storchaka 在 bpo-32749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32749} 中贡献。）

@item 
在 @ref{383,,XMLParser} 的子类中定义的 @code{doctype()} 方法将不会再被调用，并将导致发出 @ref{3ea,,RuntimeWarning} 而不是 @ref{15a,,DeprecationWarning}。 请在目标上定义 @ref{3eb,,doctype()} 方法来处理 XML doctype 声明。 （由 Serhiy Storchaka 在 bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209} 中贡献。）

@item 
现在当自定义元类未在传给 @code{type.__new__} 的命名空间中提供 @code{__classcell__} 入口时将引发 @ref{3e4,,RuntimeError}。 在 Python 3.6--3.7 中是则是引发 @ref{15a,,DeprecationWarning}。 （由 Serhiy Storchaka 在 bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722} 中贡献。）

@item 
@code{cProfile.Profile} 类现在可被用作上下文管理器。 （由 Scott Sanderson 在 bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235} 中贡献。）

@item 
@ref{389,,shutil.copyfile()}, @ref{38a,,shutil.copy()}, @ref{38b,,shutil.copy2()}, @ref{34e,,shutil.copytree()} 和 @ref{38c,,shutil.move()} 会使用平台专属的 "fast-copy" 系统调用（参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节）。

@item 
@ref{389,,shutil.copyfile()} 在 Windows 上的默认缓冲区大小从 16 KiB 改为 1 MiB。

@item 
@code{PyGC_Head} 结构已被完全改变。 所有接触到该结构的代码都应当被重写。 （参见 bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597}。）

@item 
@ref{3ec,,PyInterpreterState} 结构已被移入 "internal" 头文件（特别是 Include/internal/pycore_pystate.h）。 不透明的 @code{PyInterpreterState} 作为仅有 API（以及稳定版 ABI）的一部分仍然可用。 文档指明该结构的任何字段都不是公有的，因此我们希望没人在使用它们。 但是，如果你确实依赖其中某一个或更多个私有字段并且没有其他替代选项，则请开一个 BPO 问题。 我们将尽力帮助你进行调整（可能包括向公有 API 添加访问器函数）。 （参见 bpo-35886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35886}。）

@item 
现在所有平台下的 @ref{3ed,,mmap.flush()} 方法都会在成功时返回 @code{None} 并在错误时引发异常。 之前它的行为取决于具体平台： Windows 下会在成功时返回非零值；在失败时返回零。 Unix 下会在成功时返回零；在失败时引发错误。 （由 Berker Peksag 在 bpo-2122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2122} 中贡献。）

@item 
@ref{13e,,xml.dom.minidom} 和 @ref{144,,xml.sax} 模块默认将不再处理外部实体。 （由 Christian Heimes 在 bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239} 中贡献。）

@item 
从只读的 @ref{31,,dbm} 数据库 (@ref{32,,dbm.dumb}, @ref{33,,dbm.gnu} 或 @ref{34,,dbm.ndbm}) 删除键将会引发 @code{error} (@ref{3ee,,dbm.dumb.error}, @ref{3ef,,dbm.gnu.error} 或 @ref{3f0,,dbm.ndbm.error}) 而不是 @ref{3f1,,KeyError}。 （由 Xiang Zhang 在 bpo-33106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33106} 中贡献。）

@item 
简化了字面值的 AST。 所有常量将被表示为 @ref{3ae,,ast.Constant} 的实例。 实例化旧类 @code{Num}, @code{Str}, @code{Bytes}, @code{NameConstant} 和 @code{Ellipsis} 都将返回 @code{Constant} 的实例。 （由 Serhiy Storchaka 在 bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892} 中贡献。）

@item 
@ref{333,,expanduser()} 在 Windows 上现在改用 
@geindex USERPROFILE
@geindex 环境变量; USERPROFILE
@code{USERPROFILE} 环境变量而不再使用 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME}，后者通常不会为一般用户账户设置。 （由 Anthony Sottile 在 bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264} 中贡献。）

@item 
异常 @ref{2e1,,asyncio.CancelledError} 现在继承自 @ref{2e2,,BaseException} 而不是 @ref{2e3,,Exception} 并且不再继承自 @ref{2e4,,concurrent.futures.CancelledError}。 （由 Yury Selivanov 在 bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528} 中贡献。）

@item 
当使用 @ref{2e7,,asyncio.Task} 的实例时，函数 @ref{191,,asyncio.wait_for()} 现在会正确地等待撤销。 在此之前当达到 @emph{timeout} 时，它会被撤销并立即返回。 （由 Elvis Pranskevichus 在 bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751} 中贡献。）

@item 
当将 'socket' 作为 @emph{name} 形参传入时，函数 @ref{3f2,,asyncio.BaseTransport.get_extra_info()} 现在会返回一个可安全使用的套接字对象。 （由 Yury Selivanov 在 bpo-37027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37027} 中贡献。）

@item 
@ref{3f3,,asyncio.BufferedProtocol} 已经晋级为稳定 API。
@end itemize
@anchor{whatsnew/3 8 bpo-36085-whatsnew}@anchor{3f4}

@itemize *

@item 
在 Windows 上对扩展模块的 DLL 依赖以及通过 @ref{2a,,ctypes}  加载的 DLL 的解析现在将更为安全。 只有系统路径、包含相信 DLL 或 PYD 文件的路径以及通过 @ref{2fa,,add_dll_directory()} 添加的目录才会被作为加载时依赖的搜索位置。 特别地，
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 和当前工作目录将不再被使用，对它们的修改将不再对正常的 DLL 解析产生影响。 如果你的应用依赖于这些机制，你应当先检查 @ref{2fa,,add_dll_directory()}，如果它存在就用它在加载你的库时添加你的 DLL 目录。 请注意 Windows 7 用户还需要确保 Windows 更新包 KB2533623 已安装（这一点也会由安装器进行验证）。 （由 Steve Dower 在 bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085} 中贡献。）

@item 
关联到 pgen 的头文件和函数在其被纯 Python 实现取代后已被移除。 （由 Pablo Galindo 在 bpo-36623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36623} 中贡献。）

@item 
@ref{2d4,,types.CodeType} 在构造器的第二个位置新增了一个形参 (@emph{posonlyargcount}) 以支持在 
@geindex Python 提高建议; PEP 570
PEP 570@footnote{https://www.python.org/dev/peps/pep-0570} 中定义的仅限位置参数。 第一个参数 (@emph{argcount}) 现在表示位置参数的总数量 (包括仅限位置参数)。 @ref{2d4,,types.CodeType} 中新增的 @code{replace()} 方法可用于让代码支持 future 特性。

@item 
@ref{3f5,,hmac.new()} 的 @code{digestmod} 形参不再默认使用 MD5 摘要。
@end itemize

@node C API 中的改变,CPython 字节码的改变<2>,更改的Python API,移植到 Python 3 8
@anchor{whatsnew/3 8 changes-in-the-c-api}@anchor{3f6}
@subsubsection C API 中的改变



@itemize *

@item 
@ref{3f7,,PyCompilerFlags} 结构体添加了一个新的 @emph{cf_feature_version} 字段。 它应当被初始化为 @code{PY_MINOR_VERSION}。 该字段默认会被忽略，当且仅当 @code{PyCF_ONLY_AST} 在 @emph{cf_flags} 中设置旗标时才会被使用。 （由 Guido van Rossum 在 bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766} 中贡献。）

@item 
@code{PyEval_ReInitThreads()} 函数已从 C API 中移除。 它不应当被显式地调用；请改用 @ref{3f8,,PyOS_AfterFork_Child()}。 （由 Victor Stinner 在 bpo-36728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36728} 中贡献。）

@item 
在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例外。 当 Python 被嵌入时，@code{libpython} 不可使用 @code{RTLD_LOCAL} 加载，而要改用 @code{RTLD_GLOBAL}。 之前使用 @code{RTLD_LOCAL} 已经不可能加载未链接到 @code{libpython} 的 C 扩展了，例如通过 @code{Modules/Setup} 的 @code{*shared*} 部分构建的标准库 C 扩展。 （由 Victor Stinner 在 bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536} 中贡献。）

@item 
在解析或构建值时（例如 @ref{39b,,PyArg_ParseTuple()}, @ref{3f9,,Py_BuildValue()}, @ref{3fa,,PyObject_CallFunction()} 等等）使用形如 @code{#} 的格式而不定义 @code{PY_SSIZE_T_CLEAN} 现在将会引发 @code{DeprecationWarning}。 它将在 3.10 或 4.0 中被移除。 请参阅 @ref{3fb,,语句解释及变量编译} 了解详情。 （由 Inada Naoki 在 bpo-36381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36381} 中贡献。）

@item 
堆分配类型的实例（例如使用 @ref{23b,,PyType_FromSpec()} 创建的实例）会保存一个对其类型对象的引用。 提升这些类型对象引用计数的操作已从 @ref{3a1,,PyType_GenericAlloc()} 移至更低层级的函数 @ref{3a0,,PyObject_Init()} 和 @code{PyObject_INIT()}。 这使用通过This makes types created through @ref{23b,,PyType_FromSpec()} 所创建类型的行为与管理代码中的其他类保持一致。

静态分配类型将不受影响。

在大部分情况下，这应该都不会有附带影响。 但是，在分配实例后手动提升引用计数的类型（也许是为了绕过漏洞）现在可能永远不会被销毁。 要避免这种情况，这些类需要在实例撤销分配期间在类型对象上调用 Py_DECREF。

要正确地将这些类型移植到 3.8，请应用以下修改：


@itemize *

@item 
在分配实例之后在类型对象上移除 @ref{396,,Py_INCREF} —— 如果有的话。 这可以发生在调用 @ref{269,,PyObject_New()}, @ref{26a,,PyObject_NewVar()}, @ref{3fc,,PyObject_GC_New()}, @ref{3fd,,PyObject_GC_NewVar()} 或任何其他使用 @ref{3a0,,PyObject_Init()} 或 @code{PyObject_INIT()} 的自定义分配器之后。

示例:

@example
static foo_struct *
foo_new(PyObject *type) @{
    foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
    if (foo == NULL)
        return NULL;
#if PY_VERSION_HEX < 0x03080000
    // Workaround for Python issue 35810; no longer necessary in Python 3.8
    PY_INCREF(type)
#endif
    return foo;
@}
@end example

@item 
确保所有堆分配类型的自定义 @code{tp_dealloc} 函数会减少类型的引用计数。

示例:

@example
static void
foo_dealloc(foo_struct *instance) @{
    PyObject *type = Py_TYPE(instance);
    PyObject_GC_Del(instance);
#if PY_VERSION_HEX >= 0x03080000
    // This was not needed before Python 3.8 (Python issue 35810)
    Py_DECREF(type);
#endif
@}
@end example
@end itemize

（由 Eddie Elizondo 在 bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810} 中贡献。）

@item 
@code{Py_DEPRECATED()} 宏已经针对 MSVC 实现。 这个宏现在必须放在符号名称之前。

示例:

@example
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
@end example

（由 Zackery Spytz 在 bpo-33407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33407} 中贡献。）

@item 
解释器将不再假装支持跨发布版本的扩展类型二进制兼容性。 由第三方扩展模块所导出的 @ref{3fe,,PyTypeObject} 应该具有当前 Python 版本所要求的所有空位，包括 @ref{3ff,,tp_finalize} (@ref{400,,Py_TPFLAGS_HAVE_FINALIZE} 不会再在读取 @ref{3ff,,tp_finalize} 之前被检查)。

（由 Antoine Pitrou 在 bpo-32388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32388} 中贡献。）

@item 
函数 @code{PyNode_AddChild()} 和 @code{PyParser_AddToken()} 现在接受两个额外的 @code{int} 参数 @emph{end_lineno} 和 @emph{end_col_offset}。

@item 
允许 MinGW 工具直接链接到 @code{python38.dll} 的 @code{libpython38.a} 文件已不再包含于标准的 Windows 分发包中。 如果你需要此文件，可使用 @code{gendef} 和 @code{dlltool} 工具来生成它，这些工具是 MinGW binutils 包的一部分：

@example
gendef - python38.dll > tmp.def
dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a
@end example

已安装的 @code{pythonXY.dll} 所在位置将取决于安装选项以及 Windows 的版本和语言。 请参阅 @ref{401,,在Windows上使用 Python} 了解更多信息。 该结果库应当放在与 @code{pythonXY.lib} 相同的目录下，这通常是你的 Python 安装路径下的 @code{libs} 目录。

（由 Steve Dower 在 bpo-37351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37351} 中贡献。）
@end itemize

@node CPython 字节码的改变<2>,演示和工具,C API 中的改变,移植到 Python 3 8
@anchor{whatsnew/3 8 cpython-bytecode-changes}@anchor{402}
@subsubsection CPython 字节码的改变



@itemize *

@item 
解释器循环已通过将块堆栈展开逻辑移入编译器获得了简化。 编译器现在会发出显式指令来调整值堆栈并为 @ref{403,,break}, @ref{2c2,,continue} 和 @ref{2cf,,return} 调用清除代码。

移除了操作码 @code{BREAK_LOOP}, @code{CONTINUE_LOOP}, @code{SETUP_LOOP} 和 @code{SETUP_EXCEPT}。 添加了新的操作码 @ref{404,,ROT_FOUR}, @code{BEGIN_FINALLY}, @code{CALL_FINALLY} 和 @code{POP_FINALLY}。 修改了 @code{END_FINALLY} 和 @code{WITH_CLEANUP_START} 的行为。

（由 Mark Shannon, Antoine Pitrou 和 Serhiy Storchaka 在 bpo-17611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17611} 中贡献。）

@item 
添加了新的操作码 @ref{405,,END_ASYNC_FOR} 用于处理当等待 @ref{406,,async for} 循环的下一项时引发的异常。 （由 Serhiy Storchaka 在 bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041} 中贡献。）

@item 
@ref{407,,MAP_ADD} 现在会预期值为栈的第一个元素而键为第二个元素。 作出此改变以使得字典推导式能如 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} 所提议的那样，键总是会在值之前被求值。 （由 Jörn Heissler 在 bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224} 中贡献。）
@end itemize

@node 演示和工具,,CPython 字节码的改变<2>,移植到 Python 3 8
@anchor{whatsnew/3 8 demos-and-tools}@anchor{408}
@subsubsection 演示和工具


添加了一个检测脚本用于对访问变量的不同方式进行计时: @code{Tools/scripts/var_access_benchmark.py}。 （由 Raymond Hettinger 在 bpo-35884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35884} 中贡献。）

以下是自 Python 3.3 以来性能提升情况的总结:

@example
Python version                       3.3     3.4     3.5     3.6     3.7     3.8
--------------                       ---     ---     ---     ---     ---     ---

Variable and attribute read access:
    read_local                       4.0     7.1     7.1     5.4     5.1     3.9
    read_nonlocal                    5.3     7.1     8.1     5.8     5.4     4.4
    read_global                     13.3    15.5    19.0    14.3    13.6     7.6
    read_builtin                    20.0    21.1    21.6    18.5    19.0     7.5
    read_classvar_from_class        20.5    25.6    26.5    20.7    19.5    18.4
    read_classvar_from_instance     18.5    22.8    23.5    18.8    17.1    16.4
    read_instancevar                26.8    32.4    33.1    28.0    26.3    25.4
    read_instancevar_slots          23.7    27.8    31.3    20.8    20.8    20.2
    read_namedtuple                 68.5    73.8    57.5    45.0    46.8    18.4
    read_boundmethod                29.8    37.6    37.9    29.6    26.9    27.7

Variable and attribute write access:
    write_local                      4.6     8.7     9.3     5.5     5.3     4.3
    write_nonlocal                   7.3    10.5    11.1     5.6     5.5     4.7
    write_global                    15.9    19.7    21.2    18.0    18.0    15.8
    write_classvar                  81.9    92.9    96.0   104.6   102.1    39.2
    write_instancevar               36.4    44.6    45.8    40.0    38.9    35.5
    write_instancevar_slots         28.7    35.6    36.1    27.3    26.6    25.7

Data structure read access:
    read_list                       19.2    24.2    24.5    20.8    20.8    19.0
    read_deque                      19.9    24.7    25.5    20.2    20.6    19.8
    read_dict                       19.7    24.3    25.7    22.3    23.0    21.0
    read_strdict                    17.9    22.6    24.3    19.5    21.2    18.9

Data structure write access:
    write_list                      21.2    27.1    28.5    22.5    21.6    20.0
    write_deque                     23.8    28.7    30.1    22.7    21.8    23.5
    write_dict                      25.9    31.4    33.3    29.3    29.2    24.7
    write_strdict                   22.9    28.4    29.9    27.5    25.2    23.1

Stack (or queue) operations:
    list_append_pop                144.2    93.4   112.7    75.4    74.2    50.8
    deque_append_pop                30.4    43.5    57.0    49.4    49.2    42.5
    deque_append_popleft            30.8    43.7    57.3    49.7    49.7    42.8

Timing loop:
    loop_overhead                    0.3     0.5     0.6     0.4     0.3     0.3
@end example

基准测试是在 Intel® Core™ i7-4960HQ 处理器@footnote{https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html} 上运行从 python.org@footnote{https://www.python.org/downloads/mac-osx/} 获取的 macOS 64 位版得到的数据。 基准测试脚本显示时间以纳秒为单位。

@node Python 3 8 1 中的重要变化,Python 3 8 8 中的重要变化,移植到 Python 3 8,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-1}@anchor{409}
@subsection Python 3.8.1 中的重要变化


出于重要的安全性考量，@ref{189,,asyncio.loop.create_datagram_endpoint()} 的 @emph{reuse_address} 形参不再被支持。 这是由 UDP 中的套接字选项 @code{SO_REUSEADDR} 的行为导致的。 更多细节请参阅 @code{loop.create_datagram_endpoint()} 的文档。 （由 Kyle Stanley, Antoine Pitrou 和 Yury Selivanov 在 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228} 中贡献。。）

@node Python 3 8 8 中的重要变化,Python 3 8 12 中的重要变化,Python 3 8 1 中的重要变化,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-8}@anchor{40a}
@subsection Python 3.8.8 中的重要变化


早先的 Python 版本允许使用 @code{;} 和 @code{&} 作为 @ref{280,,urllib.parse.parse_qs()} 和 @ref{281,,urllib.parse.parse_qsl()} 中 query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被改为只允许单个分隔键，默认为 @code{&}。 这一改变还会影响 @ref{282,,cgi.parse()} 和 @ref{283,,cgi.parse_multipart()} 因为它们在内部使用了受影响的函数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt, Senthil Kumaran 和 Ken Jin 在 bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967} 中贡献。）

@node Python 3 8 12 中的重要变化,,Python 3 8 8 中的重要变化,Python 3 8 有什么新变化
@anchor{whatsnew/3 8 notable-changes-in-python-3-8-12}@anchor{40b}
@subsection Python 3.8.12 中的重要变化


从 Python 3.8.12 开始 @ref{a2,,ipaddress} 模块不再接受 IPv4 地址字符串中有任何前缀的零。 前缀的零有歧义且会被某些库解读为八进制数字。 例如旧版函数 @ref{237,,socket.inet_aton()} 就将前缀的零视为八进制数字。 最新 @ref{238,,inet_pton()} 的 glibc 实现则不接受任何前缀的零。

（最初由 Christian Heimes 在 bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384} 中贡献，并由 Achraf Merzouki 向下移植到 3.8。）

@node Python 3 7 有什么新变化,Python 3 6 有什么新变化,Python 3 8 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 7 doc}@anchor{40c}@anchor{whatsnew/3 7 what-s-new-in-python-3-7}@anchor{40d}
@section Python 3.7 有什么新变化


@*编者: 
Elvis Pranskevichus <@email{elvis@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Git log
@c when researching a change.

本文解释了 Python 3.7 相比 3.6 的新增特性。Python 3.7 于 2018 年 6 月 27 日发布。完整的详情可参阅 @ref{156,,更新日志}。

@menu
* 摘要 - 发布重点: 摘要 - 发布重点<3>. 
* 新的特性: 新的特性<4>. 
* 其他语言特性修改: 其他语言特性修改<3>. 
* 新增模块: 新增模块<3>. 
* 改进的模块: 改进的模块<3>. 
* C API 的改变: C API 的改变<2>. 
* 构建的改变: 构建的改变<2>. 
* 性能优化: 性能优化<3>. 
* 其他 CPython 实现的改变:: 
* 已弃用的 Python 行为:: 
* 已弃用的 Python 模块、函数和方法:: 
* 已弃用的 C API 函数和类型:: 
* 平台支持的移除:: 
* API 与特性的移除: API 与特性的移除<2>. 
* 移除的模块:: 
* Windows 专属的改变:: 
* 移植到 Python 3.7: 移植到 Python 3 7. 
* Python 3.7.1 中的重要变化: Python 3 7 1 中的重要变化. 
* Python 3.7.2 中的重要变化: Python 3 7 2 中的重要变化. 
* Python 3.7.6 中的重要变化: Python 3 7 6 中的重要变化. 
* Python 3.7.10 中的重要变化: Python 3 7 10 中的重要变化. 

@end menu

@node 摘要 - 发布重点<3>,新的特性<4>,,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 summary-release-highlights}@anchor{40e}
@subsection 摘要 - 发布重点


@c This section singles out the most important changes in Python 3.7.
@c Brevity is key.

新的语法特性：


@itemize *

@item 
@ref{40f,,PEP 563}，类型标注延迟求值。
@end itemize

向后不兼容的语法更改：


@itemize *

@item 
@ref{2de,,async} 和 @ref{2df,,await} 现在是保留的关键字。
@end itemize

新的库模块：


@itemize *

@item 
@ref{24,,contextvars}: @ref{410,,PEP 567 -- 上下文变量}

@item 
@ref{2f,,dataclasses}: @ref{411,,PEP 557 -- 数据类}

@item 
@ref{412,,importlib.resources}
@end itemize

新的内置特性：


@itemize *

@item 
@ref{413,,PEP 553}, 新的 @ref{414,,breakpoint()} 函数。
@end itemize

对 Python 数据模型的改进：


@itemize *

@item 
@ref{415,,PEP 562}, 自定义可访问的模块属性。

@item 
@ref{416,,PEP 560}, typing模块和泛型类型的核心支持。

@item 
@ref{417,,dict} 对象会保持插入时的顺序这个特性 正式宣布@footnote{https://mail.python.org/pipermail/python-dev/2017-December/151283.html} 成为 Python 语言官方规范的一部分。
@end itemize

标准库中的重大改进：


@itemize *

@item 
@ref{9,,asyncio} 模块添加了新的功能，重大改进请参阅 @ref{418,,可用性与性能提升}。

@item 
@ref{10c,,time} 模块现在提供 @ref{419,,纳秒级精度函数} 的支持。
@end itemize

CPython 实现的改进：


@itemize *

@item 
避免使用 ASCII 作为默认的文本编码：


@itemize *

@item 
@ref{41a,,PEP 538}，传统 C 区域强制转换

@item 
@ref{41b,,PEP 540}，强制 UTF-8 运行时模式
@end itemize

@item 
@ref{41c,,PEP 552}，确定性的 .pyc 文件

@item 
@ref{41d,,新的 Python 开发模式}

@item 
@ref{41e,,PEP 565}，改进的 @ref{15a,,DeprecationWarning} 处理
@end itemize

C API 的改进：


@itemize *

@item 
@ref{41f,,PEP 539}，用于线程本地存储的新 C API
@end itemize

文档的改进：


@itemize *

@item 
@ref{420,,PEP 545}, Python 文档翻译

@item 
新的文档翻译：Japanese@footnote{https://docs.python.org/ja/}，French@footnote{https://docs.python.org/fr/} 和 Korean@footnote{https://docs.python.org/ko/}。
@end itemize

此版本在诸多方面有显著的性能改进。@ref{421,,性能优化} 章节详细列出了它们。

和之前的 Python 版本存在兼容性的更改列表，请参阅 @ref{422,,移植到 Python 3.7} 章节。

@node 新的特性<4>,其他语言特性修改<3>,摘要 - 发布重点<3>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 new-features}@anchor{423}
@subsection 新的特性


@menu
* PEP 563：延迟的标注求值:: 
* PEP 538; 传统 C 区域强制转换: PEP 538 传统 C 区域强制转换. 
* PEP 540; 强制 UTF-8 运行时模式: PEP 540 强制 UTF-8 运行时模式. 
* PEP 553; 内置的 breakpoint(): PEP 553 内置的 breakpoint. 
* PEP 539; 用于线程局部存储的新 C API: PEP 539 用于线程局部存储的新 C API. 
* PEP 562; 定制对模块属性的访问: PEP 562 定制对模块属性的访问. 
* PEP 564; 具有纳秒级精度的新时间函数: PEP 564 具有纳秒级精度的新时间函数. 
* PEP 565; 在 __main__ 中显示 DeprecationWarning: PEP 565 在 __main__ 中显示 DeprecationWarning. 
* PEP 560; 对 typing 模块和泛型类型的核心支持: PEP 560 对 typing 模块和泛型类型的核心支持. 
* PEP 552; 基于哈希值的 .pyc 文件: PEP 552 基于哈希值的 pyc 文件. 
* PEP 545; Python 文档翻译: PEP 545 Python 文档翻译. 
* Python 开发模式 (-X dev): Python 开发模式 -X dev. 

@end menu

@node PEP 563：延迟的标注求值,PEP 538 传统 C 区域强制转换,,新的特性<4>
@anchor{whatsnew/3 7 pep-563-postponed-evaluation-of-annotations}@anchor{424}@anchor{whatsnew/3 7 whatsnew37-pep563}@anchor{40f}
@subsubsection PEP 563：延迟的标注求值


随着 
@geindex Python 提高建议; PEP 3107
PEP 3107@footnote{https://www.python.org/dev/peps/pep-3107} 加入标注功能并在 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 进一步细化，Python 中类型提示的出现揭示了两个明显的可用性问题：


@itemize *

@item 
标注只能使用在当前作用域中已经存在的名称，也就是说，它们不支持任何形式的前向引用；而且——

@item 
标注源码对 Python 程序的启动时间有不利的影响。
@end itemize

这两个问题都可以通过延迟标注求值来解决。在定义标注的时候，编译器并不会编译执行相应表达式的代码，而是保存与相应表达式的 AST 等价的字符串形式。如果有需要，标注可以在运行时使用 @ref{1f0,,typing.get_type_hints()} 进行解析。在不需要这种解析的通常情况下，标注的存储成本更低（因为解析器只需处理较短的字符串）且启动时间更短。

在可用性方面，标注现在支持向前引用，以使以下句法有效:

@example
class C:
    @@classmethod
    def from_string(cls, source: str) -> C:
        ...

    def validate_b(self, obj: B) -> bool:
        ...

class B:
    ...
@end example

由于此修改会破坏兼容性，在 Python 3.7 中此种新的行为需要在每个模块层级上使用 @ref{0,,__future__} 导入来启用:

@example
from __future__ import annotations
@end example

它将在 Python 3.10 中成为默认行为。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 563

@item PEP 563@footnote{https://www.python.org/dev/peps/pep-0563} -- 延迟的标注求值

PEP 由 Łukasz Langa 撰写并实现。
@end table


@node PEP 538 传统 C 区域强制转换,PEP 540 强制 UTF-8 运行时模式,PEP 563：延迟的标注求值,新的特性<4>
@anchor{whatsnew/3 7 pep-538-legacy-c-locale-coercion}@anchor{425}@anchor{whatsnew/3 7 whatsnew37-pep538}@anchor{41a}
@subsubsection PEP 538: 传统 C 区域强制转换


Python 3 系列有一个持续的挑战就是为处理 7 比特位 ASCII 文本的假定编码确定合理的默认策略，目前的设定是在非 Windows 平台上使用默认的 C 或 POSIX 区域设置。

@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} 更新了默认的解释器命令行接口，以自动将上述区域强制转换为可用的基于 UTF-8 的区域，具体描述可参见有关新增环境变量 
@geindex PYTHONCOERCECLOCALE
@geindex 环境变量; PYTHONCOERCECLOCALE
@ref{426,,PYTHONCOERCECLOCALE} 的文档。 以这种方式自动设置 @code{LC_CTYPE} 意味着核心解释器和能感知区域的 C 扩展 (例如 @ref{de,,readline}) 都将会假定 UTF-8 已被用作默认的文本编码，而不再是 ASCII。

@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011} 中的平台支持定义也已被更新以限制完整文本处理支持适当配置的基于非 ASCII 的语言区域。

作为此更改的一部分，当使用任何已定义的强制转换目标区域时 (目前为 @code{C.UTF-8}, @code{C.utf8} 和 @code{UTF-8}) @ref{427,,stdin} 和 @ref{428,,stdout} 默认的处理器现在将为 @code{surrogateescape} (而不是 @code{strict})。 而无论是什么区域，@ref{1eb,,stderr} 默认的处理器仍为 @code{backslashreplace}。

默认情况下区域强制转换会静默进行，但为了辅助调试潜在的区域相关集成问题，可以通过设置 @code{PYTHONCOERCECLOCALE=warn} 来请求显式地启用警告信息（直接在 @ref{1eb,,stderr} 上发出）。 此设置还会使得 Python 运行时在核心解释器初始化时如果传统 C 区域仍然处于激活状态时发出警告。

虽然 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} 的区域强制转换的好处在于它还会同时影响扩展模块 (例如 GNU @code{readline}) 以及子进程 (包括运行非 Python 应用和旧版本 Python 的子进程)，但它也存在需要所运行系统必须存在适合的目标区域的缺点。 为了更好地处理没有可用适合的目标区域的情况 (例如在 RHEL/CentOS 7 上就会出现此情况)，Python 3.7 还实现了 @ref{41b,,PEP 540; 强制 UTF-8 运行时模式}。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 538

@item PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} -- 强制转换传统 C 区域到基于 UTF-8 的区域

PEP 由 Nick Coghlan 撰写并实现。
@end table


@node PEP 540 强制 UTF-8 运行时模式,PEP 553 内置的 breakpoint,PEP 538 传统 C 区域强制转换,新的特性<4>
@anchor{whatsnew/3 7 pep-540-forced-utf-8-runtime-mode}@anchor{429}@anchor{whatsnew/3 7 whatsnew37-pep540}@anchor{41b}
@subsubsection PEP 540: 强制 UTF-8 运行时模式


新的 @ref{297,,-X} @code{utf8} 命令行选项和 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} 环境变量可被用来启用 CPython 的 @emph{UTF-8 模式}。

当处于 UTF-8 模式时，CPython 会忽略区域设置，并默认使用 UTF-8 编码。 用于 @ref{427,,sys.stdin} 和 @ref{428,,sys.stdout} 流的错误处理器将设置为 @code{surrogateescape}。

强制 UTF-8 模式可被用来在嵌入的 Python 解释器中改变文本处理行为，而不会改变嵌入方应用的区域设置。

@geindex Python 提高建议; PEP 540
PEP 540@footnote{https://www.python.org/dev/peps/pep-0540} 的 UTF-8 模式的好处是不必关心运行所在系统中有哪些可用区域即可工作，但它也存在对扩展模块 (例如 GNU @code{readline})、运行非 Python 应用的子进程以及运行旧版本 Python 的子进程不起作用的缺点。 为了减小与这些组件通信时破坏文本数据的风险，Python 3.7 还实现了 @ref{41b,,PEP 540; 强制 UTF-8 运行时模式})。

UTF-8 模式在语言区域为 @code{C} 或 @code{POSIX} 并且 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} 区域强制转换特性无法将其修改为某种基于 UTF-8 的替代项时会被默认启用（无论修改失败是由于设置了 @code{PYTHONCOERCECLOCALE=0}, @code{LC_ALL} 还是由于缺少适合的目标区域）。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 540

@item PEP 540@footnote{https://www.python.org/dev/peps/pep-0540} -- 增加了新的 UTF-8 模式

PEP 由 Victor Stinner 撰写并实现
@end table


@node PEP 553 内置的 breakpoint,PEP 539 用于线程局部存储的新 C API,PEP 540 强制 UTF-8 运行时模式,新的特性<4>
@anchor{whatsnew/3 7 pep-553-built-in-breakpoint}@anchor{42b}@anchor{whatsnew/3 7 whatsnew37-pep553}@anchor{413}
@subsubsection PEP 553: 内置的 @code{breakpoint()}


Python 3.7 包含了新的内置 @ref{414,,breakpoint()} 函数，作为一种简单方便地进入 Python 调试器的方式。

内置 @code{breakpoint()} 会调用 @ref{42c,,sys.breakpointhook()}。 在默认情况下后者会导入 @ref{c9,,pdb} 然后再调用 @code{pdb.set_trace()}，但是通过将 @code{sys.breakpointhook()} 绑定到你选定的函数，@code{breakpoint()} 可以进入任何调试器。 此外，环境变量 
@geindex PYTHONBREAKPOINT
@geindex 环境变量; PYTHONBREAKPOINT
@ref{42d,,PYTHONBREAKPOINT} 可被设置为你选定的调试器的可调用对象。 设置 @code{PYTHONBREAKPOINT=0} 会完全禁用内置 @code{breakpoint()}。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 553

@item PEP 553@footnote{https://www.python.org/dev/peps/pep-0553} -- 内置的 breakpoint()

PEP 由 Barry Warsaw 撰写并实现
@end table


@node PEP 539 用于线程局部存储的新 C API,PEP 562 定制对模块属性的访问,PEP 553 内置的 breakpoint,新的特性<4>
@anchor{whatsnew/3 7 pep-539-new-c-api-for-thread-local-storage}@anchor{42e}@anchor{whatsnew/3 7 whatsnew37-pep539}@anchor{41f}
@subsubsection PEP 539: 用于线程局部存储的新 C API


虽然 Python 已提供了用于线程局部存储支持的 C API；但原有的 @ref{42f,,线程局部存储 (TLS) API} 使用 @code{int} 来表示所有平台上的 TLS 密钥。 对于官方支持的平台而言这通常不是问题，但这既不符合 POSIX 标准，也不具备任何实际意义上的可移植性。

@geindex Python 提高建议; PEP 539
PEP 539@footnote{https://www.python.org/dev/peps/pep-0539} 通过向 CPython 提供了一个新的 @ref{430,,线程特定存储 (TSS) API} 来改变这一点，它取代了原有的 CPython 内部 TLS API 的使用，并且原有 API 已弃用。 TSS API 使用一种新类型 @ref{431,,Py_tss_t} 而非 @code{int} 来表示 TSS 密钥 -- 这是一种不透明类型，其定义可能依赖于下层的 TLS 实现。 因此，这将允许在以无法安全地转换为 @code{int} 的方式定义原生 TLS 密钥的平台上构建 CPython。

请注意在原生 TLS 密钥定义方式无法被安全地转换为 @code{int} 的平台上，原有 TLS API 中的全部函数将无法执行并会立即返回失败信息。 这样能清楚地表明原有 API 在无法可靠使用的平台上不受支持，并且不会再尝试添加此类支持。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 539

@item PEP 539@footnote{https://www.python.org/dev/peps/pep-0539} -- 在 CPython 中用于线程局部存储的新 C-API

PEP 由 Erik M. Bray 撰写；由 Masayuki Yamamoto 实现。
@end table


@node PEP 562 定制对模块属性的访问,PEP 564 具有纳秒级精度的新时间函数,PEP 539 用于线程局部存储的新 C API,新的特性<4>
@anchor{whatsnew/3 7 pep-562-customization-of-access-to-module-attributes}@anchor{432}@anchor{whatsnew/3 7 whatsnew37-pep562}@anchor{415}
@subsubsection PEP 562: 定制对模块属性的访问


Python 3.7 允许在模块上定义 @ref{433,,__getattr__()} 并且当以其他方式找不到某个模块属性时将会调用它。 在模块上定义 @ref{434,,__dir__()} 现在也是允许的。

一个典型的可能有用的例子是已弃用模块属性和惰性加载。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 562

@item PEP 562@footnote{https://www.python.org/dev/peps/pep-0562} -- 模块的 @code{__getattr__} 和 @code{__dir__}

PEP 由 Ivan Levkivskyi 撰写并实现
@end table


@node PEP 564 具有纳秒级精度的新时间函数,PEP 565 在 __main__ 中显示 DeprecationWarning,PEP 562 定制对模块属性的访问,新的特性<4>
@anchor{whatsnew/3 7 pep-564-new-time-functions-with-nanosecond-resolution}@anchor{435}@anchor{whatsnew/3 7 whatsnew37-pep564}@anchor{419}
@subsubsection PEP 564: 具有纳秒级精度的新时间函数


现代系统的时钟精度可以超过由 @ref{436,,time.time()} 函数及其变化形式所返回的浮点数的有限精度。 为了避免精度损失，
@geindex Python 提高建议; PEP 564
PEP 564@footnote{https://www.python.org/dev/peps/pep-0564} 在 @ref{10c,,time} 模块中增加了原有计时器函数的六个新“纳秒版”变化形式:


@itemize *

@item 
@ref{437,,time.clock_gettime_ns()}

@item 
@ref{438,,time.clock_settime_ns()}

@item 
@ref{439,,time.monotonic_ns()}

@item 
@ref{43a,,time.perf_counter_ns()}

@item 
@ref{43b,,time.process_time_ns()}

@item 
@ref{43c,,time.time_ns()}
@end itemize

这些新函数会以整数值的形式返回纳秒数。

测量@footnote{https://www.python.org/dev/peps/pep-0564/#annex-clocks-resolution-in-python} 表明在 Linux 和 Windows 上 @ref{43c,,time.time_ns()} 的精度大约比 @ref{436,,time.time()} 要高 3 倍。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 564

@item PEP 564@footnote{https://www.python.org/dev/peps/pep-0564} -- 增加具有纳秒级精度的新时间函数

PEP 由 Victor Stinner 撰写并实现
@end table


@node PEP 565 在 __main__ 中显示 DeprecationWarning,PEP 560 对 typing 模块和泛型类型的核心支持,PEP 564 具有纳秒级精度的新时间函数,新的特性<4>
@anchor{whatsnew/3 7 pep-565-show-deprecationwarning-in-main}@anchor{43d}@anchor{whatsnew/3 7 whatsnew37-pep565}@anchor{41e}
@subsubsection PEP 565: 在 @code{__main__} 中显示 DeprecationWarning


@ref{15a,,DeprecationWarning} 的默认处理方式已经被更改，这此警告默认只显示一次，仅有当直接在 @ref{1,,__main__} 模块中运行的代码触发它们时才会再次显示。 因此，单文件脚本开发者以及 Python 交互模式使用者应该会再次开始看到针对他们所使用 API 的已弃用警告，但被导入应用、库和框架模块所触发的已弃用警告默认将继续隐藏。

作为此项更改的结果，标准库现在允许开发者在三种不同的已弃用警告行为之间进行选择:


@itemize *

@item 
@ref{43e,,FutureWarning}: 默认情况下总是会显示，建议用于应用程序最终用户应该看到的警告信息（例如对于已弃用的应用程序配置的设置选项）。

@item 
@ref{15a,,DeprecationWarning}: 默认情况下仅在 @ref{1,,__main__} 中以及当运行测试时会显示，建议用于其他 Python 开发者应该看到的警告信息，提示版本升级可能导致行为改变或者错误。

@item 
@ref{15c,,PendingDeprecationWarning}: 默认情况下仅在运行测试时会显示，可用于提示未来版本升级将会改变警告类别为 @ref{15a,,DeprecationWarning} 或 @ref{43e,,FutureWarning} 的情况。
@end itemize

在此之前 @ref{15a,,DeprecationWarning} 和 @ref{15c,,PendingDeprecationWarning} 都仅在运行测试时可见，这意味着主要编写单文件脚本或使用 Python 交互模式的开发者可能会因他们所用 API 突然出现的改变而感到惊讶。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 565

@item PEP 565@footnote{https://www.python.org/dev/peps/pep-0565} -- 在 @code{__main__} 中显示 DeprecationWarning

PEP 由 Nick Coghlan 撰写并实现
@end table


@node PEP 560 对 typing 模块和泛型类型的核心支持,PEP 552 基于哈希值的 pyc 文件,PEP 565 在 __main__ 中显示 DeprecationWarning,新的特性<4>
@anchor{whatsnew/3 7 pep-560-core-support-for-typing-module-and-generic-types}@anchor{43f}@anchor{whatsnew/3 7 whatsnew37-pep560}@anchor{416}
@subsubsection PEP 560: 对 @code{typing} 模块和泛型类型的核心支持


@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 最初的设计方式使其不会向核心 CPython 解释器引入 @emph{任何} 更改。 现在类型提示和 @ref{122,,typing} 模块已被社区广泛使用，因此这个限制已被取消。 这个 PEP 引入了两个特殊方法 @ref{440,,__class_getitem__()} 和 @code{__mro_entries__}，这些方法现在被 @ref{122,,typing} 中的大多数类和特殊构造所使用。 结果就是与类型相关的各类操作的速度提升了 7 倍，泛型类型可以在没有元类冲突的情况下被使用，而 @ref{122,,typing} 模块中几个长期存在的错误也已被修正。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 560

@item PEP 560@footnote{https://www.python.org/dev/peps/pep-0560} -- 对 typing 模块和泛型类型的核心支持

PEP 由 Ivan Levkivskyi 撰写并实现
@end table


@node PEP 552 基于哈希值的 pyc 文件,PEP 545 Python 文档翻译,PEP 560 对 typing 模块和泛型类型的核心支持,新的特性<4>
@anchor{whatsnew/3 7 pep-552-hash-based-pyc-files}@anchor{441}@anchor{whatsnew/3 7 whatsnew37-pep552}@anchor{41c}
@subsubsection PEP 552: 基于哈希值的 .pyc 文件


传统上 Python 检查字节码缓存文件 (即 @code{.pyc} 文件) 是否最新的方式是通过对源码元数据 (最后更改的时间戳和大小）和生成缓存时保存在其文件头中的源码元数据进行比较。 这种检查方法虽然有效，但也存在缺点。 当文件系统的时间戳太粗糙时，Python 有可能错过源码更新，导致用户感到困惑。 此外，在缓存文件中存在时间戳对于 构建可再现@footnote{https://reproducible-builds.org/} 并且基于内容的构建系统来说是有问题的。

@geindex Python 提高建议; PEP 552
PEP 552@footnote{https://www.python.org/dev/peps/pep-0552} 扩展了 pyc 格式以允许使用源文件的哈希值而非源文件的时间戳来检查有效性。 这种 @code{.pyc} 文件就称为“基于哈希值的”。 默认情况下，Python 仍然使用基于时间戳的有效性检查，不会在运行时生成基于哈希值的 @code{.pyc} 文件。 基于哈希值的 @code{.pyc} 文件可以使用 @ref{d7,,py_compile} 或 @ref{20,,compileall} 来生成。

基于哈希值的 @code{.pyc} 文件包含两种变体：已选定和未选定。 Python 会在运行时针对相应源码文件验证已选定基于哈希值的 @code{.pyc} 文件，但对未选定基于哈希值的 pyc 文件则不会这样做。 未选定基于哈希值的 @code{.pyc} 文件对于需要由 Python 外部的系统（例如构建系统）负责使 @code{.pyc} 文件保持最新的环境来说是一种有用的性能优化。

请参阅 @ref{442,,已缓存字节码的失效} 了解更多信息。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 552

@item PEP 552@footnote{https://www.python.org/dev/peps/pep-0552} -- 确定性的 pyc 文件

PEP 由 Benjamin Peterson 撰写并实现
@end table


@node PEP 545 Python 文档翻译,Python 开发模式 -X dev,PEP 552 基于哈希值的 pyc 文件,新的特性<4>
@anchor{whatsnew/3 7 pep-545-python-documentation-translations}@anchor{443}@anchor{whatsnew/3 7 whatsnew37-pep545}@anchor{420}
@subsubsection PEP 545: Python 文档翻译


@geindex Python 提高建议; PEP 545
PEP 545@footnote{https://www.python.org/dev/peps/pep-0545} 描述了创建和维护 Python 文档翻译的整个过程。

新增了三个新的翻译版本:


@itemize -

@item 
日语: @indicateurl{https://docs.python.org/ja/}

@item 
法语: @indicateurl{https://docs.python.org/fr/}

@item 
韩语: @indicateurl{https://docs.python.org/ko/}
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 545

@item PEP 545@footnote{https://www.python.org/dev/peps/pep-0545} -- Python 文档翻译

PEP 由 Julien Palard, Inada Naoki 和 Victor Stinner 撰写并实现。
@end table


@node Python 开发模式 -X dev,,PEP 545 Python 文档翻译,新的特性<4>
@anchor{whatsnew/3 7 python-development-mode-x-dev}@anchor{444}@anchor{whatsnew/3 7 whatsnew37-devmode}@anchor{41d}
@subsubsection Python 开发模式 (-X dev)


新的 @ref{297,,-X} @code{dev} 命令行选项或新的 
@geindex PYTHONDEVMODE
@geindex 环境变量; PYTHONDEVMODE
@ref{445,,PYTHONDEVMODE} 环境变量可被用来启用 @ref{160,,Python 开发模式}。 在开发模式下，Python 将执行额外的如果默认启用会导致开销过大的运行时检查。 请参阅 @ref{160,,Python 开发模式} 文档查看完整说明。

@node 其他语言特性修改<3>,新增模块<3>,新的特性<4>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 other-language-changes}@anchor{446}
@subsection 其他语言特性修改



@itemize *

@item 
@ref{2df,,await} 表达式和包含 @ref{406,,async for} 子句的推导式不允许在 @ref{29d,,格式化字符串字面值} 的表达式中使用。 在 Python 3.7 中此限制已被取消。

@item 
现在可以将超过 255 个参数传递给一个函数，而现在一个函数也可以拥有超过 255 个形参。 （由 Serhiy Storchaka 在 bpo-12844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12844} 和 bpo-18896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18896} 中贡献。）

@item 
现在 @ref{447,,bytes.fromhex()} 和 @ref{448,,bytearray.fromhex()} 会忽略所有 ASCII 空白符，而非仅是空格符. （由 Robert Xiao 在 bpo-28927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28927} 中贡献。）

@item 
@ref{206,,str}, @ref{172,,bytes} 和 @ref{173,,bytearray} 获得了对新 @ref{449,,isascii()} 方法的支持，该方法可被用来测试是个字符串或字节串是否仅包含 ASCII 字符。 （由 INADA Naoki 在 bpo-32677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32677} 中贡献。）

@item 
现在当 @code{from ... import ...} 失败时 @ref{16c,,ImportError} 会显示模块名称和模块 @code{__file__} 路径。 （由 Matthias Bussonnier 在 bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546} 中贡献。）

@item 
现在已支持涉及将子模块绑定到一个名称的绝对导入的循环导入。 （由 Serhiy Storchaka 在 bpo-30024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30024} 中贡献。）

@item 
现在 @code{object.__format__(x, '@w{'})} 等价于 @code{str(x)} 而非 @code{format(str(self), '@w{'})}。 （由 Serhiy Storchaka d  bpo-28974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28974} 中贡献。）

@item 
为更好地支持栈跟踪的动态创建，现在 @ref{44a,,types.TracebackType} 可以从 Python 代码中被实例化，并且 @ref{44b,,回溯对象} 的 @code{tb_next} 属性现在是可写的。 （由 Nathaniel J. Smith 在 bpo-30579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30579} 中贡献。）

@item 
当使用 @ref{44c,,-m} 开关时，现在 @code{sys.path[0]} 会主动扩展为完整的起始目录路径，而不是保持为空目录（这将允许在发生导入时从 @emph{当前} 工作目录导入） （由 Nick Coghlan 在 bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053} 中贡献。）

@item 
新的 @ref{297,,-X} @code{importtime} 选项或 
@geindex PYTHONPROFILEIMPORTTIME
@geindex 环境变量; PYTHONPROFILEIMPORTTIME
@ref{44d,,PYTHONPROFILEIMPORTTIME} 环境变量可被用来显示每次模块导入的时间。 （由 Inada Naoki 在 bpo-31415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31415} 中贡献。）
@end itemize

@node 新增模块<3>,改进的模块<3>,其他语言特性修改<3>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 new-modules}@anchor{44e}
@subsection 新增模块


@menu
* contextvars:: 
* dataclasses:: 
* importlib.resources: importlib resources. 

@end menu

@node contextvars,dataclasses,,新增模块<3>
@anchor{whatsnew/3 7 contextvars}@anchor{44f}@anchor{whatsnew/3 7 whatsnew37-pep567}@anchor{410}
@subsubsection contextvars


新的 @ref{24,,contextvars} 模块和一组 @ref{450,,新的 C API} 引入了对 @emph{上下文变量} 的支持。 上下文变量在概念上类似于线程局部变量。 与 TLS 不同，上下文变量能正确地支持异步代码。

@ref{9,,asyncio} 和 @ref{35,,decimal} 已得到更新以使用和支持开箱即用的上下文变量。 特别是激活的 decimal 上下文现在将存储在上下文变量中，它允许十进制运算在异步代码中使用正确的上下文。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 567

@item PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} -- 上下文变量

PEP 由 Yury Selivanov 撰写并实现
@end table


@node dataclasses,importlib resources,contextvars,新增模块<3>
@anchor{whatsnew/3 7 dataclasses}@anchor{451}@anchor{whatsnew/3 7 whatsnew37-pep557}@anchor{411}
@subsubsection dataclasses


新的 @ref{452,,dataclass()} 装饰器提供了一种声明 @emph{数据类} 的方式。  数据类使用变量标注来描述其属性。 它的构造器和其他魔术方法例如 @ref{453,,__repr__()}, @ref{454,,__eq__()} 以及 @ref{455,,__hash__()} 会自动地生成。

示例:

@example
@@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # produces "Point(x=1.5, y=2.5, z=0.0)"
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 557

@item PEP 557@footnote{https://www.python.org/dev/peps/pep-0557} -- 数据类

PEP 由 Eric V. Smith 撰写并实现
@end table


@node importlib resources,,dataclasses,新增模块<3>
@anchor{whatsnew/3 7 importlib-resources}@anchor{456}@anchor{whatsnew/3 7 whatsnew37-importlib-resources}@anchor{412}
@subsubsection importlib.resources


新的 @ref{9e,,importlib.resources} 模块提供了一些新的 API 和一个新的 ABC 用于访问、打开和读取包内的 @emph{资源}。 资源基本上类似于包内的文件，但它们不一定是物理文件系统中实际的文件。 模块加载器可以提供 @code{get_resource_reader()} 函数，它会返回一个 @ref{457,,importlib.abc.ResourceReader} 实例来支持这个新 API。 内置的文件路径加载器和 zip 文件加载器都支持此特性。

由 Barry Warsaw 和 Brett Cannon 在 bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248} 中贡献。


@subsubheading 参见


importlib_resources@footnote{http://importlib-resources.readthedocs.io/en/latest/} -- 用于先前 Python 版本的 PyPI 下层接口。


@node 改进的模块<3>,C API 的改变<2>,新增模块<3>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 improved-modules}@anchor{458}
@subsection 改进的模块


@menu
* argparse:: 
* asyncio: asyncio<3>. 
* binascii:: 
* calendar:: 
* collections: collections<2>. 
* compileall: compileall<2>. 
* concurrent.futures: concurrent futures<2>. 
* contextlib:: 
* cProfile: cProfile<2>. 
* crypt:: 
* datetime: datetime<3>. 
* dbm:: 
* decimal:: 
* dis:: 
* distutils: distutils<2>. 
* enum:: 
* functools: functools<2>. 
* gc: gc<3>. 
* hmac:: 
* http.client: http client. 
* http.server: http server. 
* idlelib 与 IDLE:: 
* importlib: importlib<2>. 
* io: io<2>. 
* ipaddress: ipaddress<2>. 
* itertools: itertools<2>. 
* locale:: 
* logging: logging<2>. 
* math: math<3>. 
* mimetypes:: 
* msilib:: 
* multiprocessing: multiprocessing<3>. 
* os: os<3>. 
* pathlib: pathlib<3>. 
* pdb: pdb<2>. 
* py_compile: py_compile<2>. 
* pydoc: pydoc<2>. 
* queue:: 
* re:: 
* signal: signal<2>. 
* socket: socket<3>. 
* socketserver:: 
* sqlite3:: 
* ssl: ssl<2>. 
* string:: 
* subprocess:: 
* sys: sys<3>. 
* time: time<3>. 
* tkinter: tkinter<2>. 
* tracemalloc: tracemalloc<2>. 
* types:: 
* unicodedata: unicodedata<3>. 
* unittest: unittest<2>. 
* unittest.mock: unittest mock. 
* urllib.parse: urllib parse<3>. 
* uu:: 
* uuid:: 
* warnings:: 
* xml.etree: xml etree. 
* xmlrpc.server: xmlrpc server. 
* zipapp:: 
* zipfile:: 

@end menu

@node argparse,asyncio<3>,,改进的模块<3>
@anchor{whatsnew/3 7 argparse}@anchor{459}
@subsubsection argparse


新的 @ref{45a,,ArgumentParser.parse_intermixed_args()} 方法允许混合选项与位置参数。 （由 paul.j3 在 bpo-14191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14191} 中提供。）

@node asyncio<3>,binascii,argparse,改进的模块<3>
@anchor{whatsnew/3 7 asyncio}@anchor{45b}@anchor{whatsnew/3 7 whatsnew37-asyncio}@anchor{418}
@subsubsection asyncio


@ref{9,,asyncio} 模块获得了许多新的特性、可用性和 @ref{45c,,性能提升}。 重要的改变包括:


@itemize *

@item 
新的 @ref{45d,,暂定} @ref{18d,,asyncio.run()} 函数可被用于通过自动创建和销毁事件循环来基于同步代码运行协程。 （由 Yury Selivanov 在 bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314} 中贡献。）

@item 
asyncio 增加支持 @ref{24,,contextvars}. @ref{45e,,loop.call_soon()}, @ref{45f,,loop.call_soon_threadsafe()}, @ref{460,,loop.call_later()}, @ref{461,,loop.call_at()} 并且 @ref{462,,Future.add_done_callback()} 具有新的可选仅关键字参数 @emph{context}。 现在 @ref{2e7,,Tasks} 会自动跟踪其上下文。 详情参见 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567}。 （由 Yury Selivanov 在 bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436} 中贡献。）

@item 
增加了新的 @ref{2e8,,asyncio.create_task()} 函数作为 @code{asyncio.get_event_loop().create_task()} 的快捷方式。 （由 Andrew Svetlov 在 bpo-32311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32311} 中贡献。）

@item 
新的 @ref{463,,loop.start_tls()} 方法可用于升级现有的 TLS 连接。 （由 Yury Selivanov 在 bpo-23749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23749} 中贡献。）

@item 
新的 @ref{464,,loop.sock_recv_into()} 方法允许直接从套接字读取数据放入所提供的缓冲区，从而可以减少数据复制。 （由 Antoine Pitrou 在 bpo-31819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31819} 中贡献。）

@item 
新的 @ref{229,,asyncio.current_task()} 函数可返回当前运行的 @ref{2e7,,Task} 实例，以及新的 @ref{22a,,asyncio.all_tasks()} 函数可返回给定循环中所有现存 @code{Task} 实例的集合。 @code{Task.current_task()} 和 @code{Task.all_tasks()} 方法已弃用。 （由 Andrew Svetlov 在 bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250} 中贡献。）

@item 
新的 @emph{暂定} @ref{3f3,,BufferedProtocol} 类允许通过手动控制接收缓冲区来实现流式协议。 （由 Yury Selivanov 在 bpo-32251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32251} 中贡献。）

@item 
新的 @ref{465,,asyncio.get_running_loop()} 函数可返回当前运行的循环，如果没有循环在运行则引发 @ref{3e4,,RuntimeError}。 这与 @ref{466,,asyncio.get_event_loop()} 不同，后者在没有循环在运行时将 @emph{创建} 一个新的事件循环。 （由 Yury Selivanov 在 bpo-32269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32269} 中提供。）

@item 
新的 @ref{467,,StreamWriter.wait_closed()} 协程方法允许执行等待直到流写入器被关闭。 新的 @ref{468,,StreamWriter.is_closing()} 方法可用于确定写入器是否被关闭。 （由 Andrew Svetlov 在 bpo-32391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32391} 中贡献。）

@item 
新的 @ref{469,,loop.sock_sendfile()} 协程方法允许在可能的情况下使用 @ref{46a,,os.sendfile} 发送文件。 （由 Andrew Svetlov 在 bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410} 中贡献。）

@item 
新的 @ref{46b,,Future.get_loop()} 和 @code{Task.get_loop()} 方法会返回创建 task 或 future 对象的事件循环的实例。 @ref{46c,,Server.get_loop()} 允许为 @ref{46d,,asyncio.Server} 对象执行同样操作。 （由 Yury Selivanov 在 bpo-32415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32415} 中，以及由 Srinivas Reddy Thatiparthy 在 bpo-32418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32418} 中贡献。）

@item 
现在可以控制 @ref{46d,,asyncio.Server} 的实例如何开启服务。 之前，服务在创建后将立即开启服务。 新的 @emph{start_serving} 关键字参数已添加到 @ref{46e,,loop.create_server()} 和 @ref{46f,,loop.create_unix_server()}，并且 @ref{470,,Server.start_serving()}, 和 @ref{471,,Server.serve_forever()} 可被用来分离服务的实例化和服务的开启。 新的 @ref{472,,Server.is_serving()} 方法会在服务开启时返回 @code{True}。 现在 @ref{46d,,Server} 对象已是异步上下文管理器:

@example
srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
@end example

（由 Yury Selivanov 在 bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662} 中贡献。）

@item 
由 @ref{460,,loop.call_later()} 所返回的回调对象已获得新的 @ref{473,,when()} 方法，该方法会返回一个排入计划日程的绝对时间戳。 （由 Andrew Svetlov 在 bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741} 中贡献。）

@item 
@ref{189,,loop.create_datagram_endpoint()} 方法已获得对 Unix 套接字的支持。 （由 Quentin Dawans 在 bpo-31245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31245} 中贡献。）

@item 
@ref{474,,asyncio.open_connection()}, @ref{475,,asyncio.start_server()} functions, @ref{2ec,,loop.create_connection()}, @ref{46e,,loop.create_server()}, @ref{476,,loop.create_accepted_socket()} 方法及其对应的 UNIX 套接字变体现在接受 @emph{ssl_handshake_timeout} 关键字参数。 （由 Neil Aspinall 在 bpo-29970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29970} 中贡献。）

@item 
新的 @ref{477,,Handle.cancelled()} 方法会在回调被取消时返回 @code{True}。 （由 Marat Sharafutdinov 在 bpo-31943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31943} 中贡献。）

@item 
asyncio 源已被转换为使用 @ref{2de,,async}/@ref{2df,,await} 语法。 （由 Andrew Svetlov 在 bpo-32193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32193} 中贡献。）

@item 
新的 @ref{478,,ReadTransport.is_reading()} 方法可用于确定传输的读取状态。 此外，对 @ref{479,,ReadTransport.resume_reading()} 和 @ref{47a,,ReadTransport.pause_reading()} 的调用现在是幂等的。 （由 Yury Selivanov 在 bpo-32356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32356} 中贡献。）

@item 
接受套接字路径的循环方法现在支持传入 @ref{47b,,路径类对象}。 （由 Yury Selivanov 在 bpo-32066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32066} 中贡献。）

@item 
在 @ref{9,,asyncio} 中，Linux 上的 TCP 套接字现在创建时默认带有 @code{TCP_NODELAY} 旗标设置。 （由 Yury Selivanov 和 Victor Stinner 在 bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456} 中贡献。）

@item 
在被取消任务中发生的异常不会再被记录。 （由 Yury Selivanov 在 bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508} 中贡献。）

@item 
新的 @code{WindowsSelectorEventLoopPolicy} 和 @code{WindowsProactorEventLoopPolicy} 类。 （由 Yury Selivanov 在 bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792} 中贡献。）
@end itemize

部分 @code{asyncio} API 改为 @ref{47c,,已弃用}。

@node binascii,calendar,asyncio<3>,改进的模块<3>
@anchor{whatsnew/3 7 binascii}@anchor{47d}
@subsubsection binascii


@ref{47e,,b2a_uu()} 函数现在接受可选的 @emph{backtick} 关键字参数。 当其为真值时，零会以 @code{'`'} 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103} 中贡献。）

@node calendar,collections<2>,binascii,改进的模块<3>
@anchor{whatsnew/3 7 calendar}@anchor{47f}
@subsubsection calendar


@ref{480,,HTMLCalendar} 类具有新的类属性，可以简化所生成 HTML 日历中 CSS 类的自定义。 （由 Oz Tiram 在 bpo-30095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30095} 中贡献。）

@node collections<2>,compileall<2>,calendar,改进的模块<3>
@anchor{whatsnew/3 7 collections}@anchor{481}
@subsubsection collections


@code{collections.namedtuple()} 现在支持默认值。 （由 Raymond Hettinger 在 bpo-32320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32320} 中贡献。）

@node compileall<2>,concurrent futures<2>,collections<2>,改进的模块<3>
@anchor{whatsnew/3 7 compileall}@anchor{482}
@subsubsection compileall


@ref{483,,compileall.compile_dir()} 增加了新的 @emph{invalidation_mode} 形参，可用于启用 @ref{41c,,基于哈希值的 .pyc 有效性检测}。 失效模式也可以在命令行中使用新的 @code{--invalidation-mode} 参数来指定。 （由 Benjamin Peterson 在 bpo-31650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31650} 中贡献。）

@node concurrent futures<2>,contextlib,compileall<2>,改进的模块<3>
@anchor{whatsnew/3 7 concurrent-futures}@anchor{484}
@subsubsection concurrent.futures


@ref{196,,ProcessPoolExecutor} 和 @ref{18c,,ThreadPoolExecutor} 现在支持新的 @emph{初始化器} 以及 @emph{initargs} 构造器参数。 （由 Antoine Pitrou 在 bpo-21423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21423} 中贡献。）

@ref{196,,ProcessPoolExecutor} 现在能通过新的 @emph{mp_context} 参数来接受多进程上下文。 （由 Thomas Moreau 在 bpo-31540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31540} 中贡献。）

@node contextlib,cProfile<2>,concurrent futures<2>,改进的模块<3>
@anchor{whatsnew/3 7 contextlib}@anchor{485}
@subsubsection contextlib


新的 @ref{486,,nullcontext()} 是一个比 @ref{487,,ExitStack} 更简单和快速的无操作上下文管理器。 （由 Jesse-Bakker 在 bpo-10049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10049} 中贡献。）

增加了新的 @ref{488,,asynccontextmanager()}, @ref{489,,AbstractAsyncContextManager} 和 @ref{48a,,AsyncExitStack} 以补充它们所对应的同步项。 （由 Jelle Zijlstra 在 bpo-29679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29679} 和 bpo-30241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30241} 中，以及由 Alexander Mohr 和 Ilya Kulakov 在 bpo-29302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29302} 中贡献。）

@node cProfile<2>,crypt,contextlib,改进的模块<3>
@anchor{whatsnew/3 7 cprofile}@anchor{48b}
@subsubsection cProfile


@ref{27,,cProfile} 命令行现在接受 @code{-m module_name} 作为脚本路径的替代。 （由 Sanyam Khurana 在 bpo-21862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21862} 中贡献。）

@node crypt,datetime<3>,cProfile<2>,改进的模块<3>
@anchor{whatsnew/3 7 crypt}@anchor{48c}
@subsubsection crypt


@ref{28,,crypt} 模块现在支持 Blowfish 哈希方法。 （由 Serhiy Storchaka 在 bpo-31664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31664} 中贡献。）

@ref{48d,,mksalt()} 函数现在允许指定哈希操作的轮数。 （由 Serhiy Storchaka 在 bpo-31702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31702} 中贡献。）

@node datetime<3>,dbm,crypt,改进的模块<3>
@anchor{whatsnew/3 7 datetime}@anchor{48e}
@subsubsection datetime


新的 @ref{48f,,datetime.fromisoformat()} 方法会基于由 @code{datetime.isoformat()} 所输出的某一特定格式字符串构建 @ref{19f,,datetime} 对象。 （由 Paul Ganssle 在 bpo-15873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15873} 中贡献。）

@ref{180,,tzinfo} 类现在支持小于一分钟的偏移量。 （由 Alexander Belopolsky 在 bpo-5288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5288} 中贡献。）

@node dbm,decimal,datetime<3>,改进的模块<3>
@anchor{whatsnew/3 7 dbm}@anchor{490}
@subsubsection dbm


@ref{32,,dbm.dumb} 现在支持读取只读文件，并且在其未改变时不再写入索引文件。

@node decimal,dis,dbm,改进的模块<3>
@anchor{whatsnew/3 7 decimal}@anchor{491}
@subsubsection decimal


@ref{35,,decimal} 模块现在使用 @ref{410,,上下文变量} 来储存十进制值上下文。 （由 Yury Selivanov 在 bpo-32630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32630} 中贡献。）

@node dis,distutils<2>,decimal,改进的模块<3>
@anchor{whatsnew/3 7 dis}@anchor{492}
@subsubsection dis


@ref{493,,dis()} 函数现在能够反汇编嵌套的代码对象（推导式、生成器表达式和嵌套函数的代码，以及用于构建嵌套类的代码）。 反汇编递归的最大深度由新的 @emph{depth} 形参来控制。 （由 Serhiy Storchaka 在 bpo-11822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11822} 中贡献。）

@node distutils<2>,enum,dis,改进的模块<3>
@anchor{whatsnew/3 7 distutils}@anchor{494}
@subsubsection distutils


@code{README.rst} 现在包含在 distutils 的标准 README 列表之中，因而也包含在源码发布之中。 （由 Ryan Gonzalez 在 bpo-11913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11913} 中贡献。）

@node enum,functools<2>,distutils<2>,改进的模块<3>
@anchor{whatsnew/3 7 enum}@anchor{495}
@subsubsection enum


@ref{496,,Enum} 增加了新的 @code{_ignore_} 类特征属性，该属性允许列出不应当成为枚举成员的特征属性名称。 （由 Ethan Furman 在 bpo-31801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31801} 中贡献。）

在 Python 3.8 中，尝试在 @code{Enum} 类中检查非 Enum 对象将引发 @ref{1ff,,TypeError} (例如 @code{1 in Color})；类似地，尝试在 @code{Flag} 成员中检查非 Flag 对象也将引发 @ref{1ff,,TypeError} (例如 @code{1 in Perm.RW})；目前，两种操作均会返回 @ref{497,,False} 并且已弃用。 （由 Ethan Furman 在 bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217} 中贡献。）

@node functools<2>,gc<3>,enum,改进的模块<3>
@anchor{whatsnew/3 7 functools}@anchor{498}
@subsubsection functools


@ref{499,,functools.singledispatch()} 现在支持使用类型标注来注册实现。 （由 Łukasz Langa 在 bpo-32227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32227} 中贡献。）

@node gc<3>,hmac,functools<2>,改进的模块<3>
@anchor{whatsnew/3 7 gc}@anchor{49a}
@subsubsection gc


新的 @ref{49b,,gc.freeze()} 函数允许冻结由垃圾回收器所跟踪的所有对象，并将它们从未来的集合中排除。 这可以在 POSIX @code{fork()} 调用之前使用以令 GC 友好地进行写入时复制或加速收集。 新的 @ref{49c,,gc.unfreeze()} 函数会反转此操作。 此外，@ref{49d,,gc.get_freeze_count()} 可被用于获取冻结对象的数量。 （由 Li Zekun 在 bpo-31558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31558} 中贡献。）

@node hmac,http client,gc<3>,改进的模块<3>
@anchor{whatsnew/3 7 hmac}@anchor{49e}
@subsubsection hmac


@ref{8e,,hmac} 现在具有经优化的一次性 @ref{49f,,digest()} 函数，其速度比 @code{HMAC()} 要快三倍。 （由 Christian Heimes 在 bpo-32433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32433} 中贡献。）

@node http client,http server,hmac,改进的模块<3>
@anchor{whatsnew/3 7 http-client}@anchor{4a0}
@subsubsection http.client


@ref{4a1,,HTTPConnection} 和 @ref{4a2,,HTTPSConnection} 现在支持新的 @emph{blocksize} 参数以提升上传吞吐量。 （由 Nir Soffer 在 bpo-31945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31945} 中贡献。）

@node http server,idlelib 与 IDLE,http client,改进的模块<3>
@anchor{whatsnew/3 7 http-server}@anchor{4a3}
@subsubsection http.server


@ref{4a4,,SimpleHTTPRequestHandler} 现在支持 HTTP @code{If-Modified-Since} 标头。 如果目标文件在该标点指定的时间之后未被修改则服务器会返回 304 响应状态。 （由 Pierre Quentel 在 bpo-29654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29654} 中贡献。）

@ref{4a4,,SimpleHTTPRequestHandler} 接受新的 @emph{directory} 参数并增加了新的 @code{--directory} 命令行参数。 通过此形参，服务器可以对服务指定目录，默认情况下它使用当前工作目录。 （由 Stéphane Wirtel 和 Julien Palard 在 bpo-28707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28707} 中贡献。）

新的 @ref{4a5,,ThreadingHTTPServer} 类使用线程来处理使用 @code{ThreadingMixin} 的请求。 它会在 @code{http.server} 附带 @code{-m} 运行时被使用。 （由 Julien Palard 在 bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639} 中贡献。）

@node idlelib 与 IDLE,importlib<2>,http server,改进的模块<3>
@anchor{whatsnew/3 7 idlelib-and-idle}@anchor{4a6}
@subsubsection idlelib 与 IDLE


多个对自动补全的修正。 （由 Louie Lu 在 bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786} 中贡献。）

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和 Terry Jan Reedy 在 bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262} 中贡献。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （由 Terry Jan Reedy 在 bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802} 中贡献。） 样本可以被修改以包括其他字符。 （由 Serhiy Storchaka 在 bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860} 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从 Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry Jan Reedy 在 bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099} 中实现。）

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到 Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan Reedy 在 bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}, bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768} 和 bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679} 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在 Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成影响。 （由 Terry Jan Reedy 在 bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656} 中贡献。）

在 3.7.1 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353} 中贡献。）

上述修改已被反向移植到 3.6 维护发行版中。

在 3.7.4 中新增:

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella, Terry Jan Reedy 等人在 bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680} 和 bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627} 中贡献。）

在 3.7.5 中新增:

在 IDLE 编辑器窗口中增加了可选的行序号。 窗口打开时默认不带行序号，除非在配置对话框的 General 选项卡中进行设置。 已打开窗口中的行序号可以在 Options 菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在 bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535} 中贡献。）

@node importlib<2>,io<2>,idlelib 与 IDLE,改进的模块<3>
@anchor{whatsnew/3 7 importlib}@anchor{4a7}
@subsubsection importlib


引入了 @ref{457,,importlib.abc.ResourceReader} ABC 以支持从包中加载资源。 另请参阅 @ref{412,,importlib.resources}。 （由 Barry Warsaw, Brett Cannon 在 bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248} 中贡献。）

如果模块缺少规格描述 @ref{4a8,,importlib.reload()} 现在会引发 @ref{4a9,,ModuleNotFoundError}。 （由 Garvit Khatri 在 bpo-29851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29851} 中贡献。）

如果指定的父模块不是一个包 (即缺少 @code{__path__} 属性) @code{importlib.find_spec()} 现在会引发 @ref{4a9,,ModuleNotFoundError} 而非 @ref{4aa,,AttributeError}。 （由 Milan Oberkirch 在 bpo-30436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30436} 中贡献。）

新的 @code{importlib.source_hash()} 可被用来计算传入源的哈希值。 @ref{41c,,基于哈希值的 .pyc 文件} 会嵌入此函数所返回的值。

@node io<2>,ipaddress<2>,importlib<2>,改进的模块<3>
@anchor{whatsnew/3 7 io}@anchor{4ab}
@subsubsection io


新的 @ref{4ac,,TextIOWrapper.reconfigure()} 方法可用于根据新的设置重新配置文本流。 （由 Antoine Pitrou 在 bpo-30526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30526} 以及 INADA Naoki 在 bpo-15216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15216} 中贡献。）

@node ipaddress<2>,itertools<2>,io<2>,改进的模块<3>
@anchor{whatsnew/3 7 ipaddress}@anchor{4ad}
@subsubsection ipaddress


methods of @ref{4ae,,ipaddress.IPv6Network} 和 @ref{4af,,ipaddress.IPv4Network} 中新的 @code{subnet_of()} 以及 @code{supernet_of()} 方法可用于网络包含测试。 （由 Michel Albert 和 Cheryl Sabella 在 bpo-20825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20825} 中贡献。）

@node itertools<2>,locale,ipaddress<2>,改进的模块<3>
@anchor{whatsnew/3 7 itertools}@anchor{4b0}
@subsubsection itertools


@ref{4b1,,itertools.islice()} 现在接受 @ref{2c9,,类整数对象} 作为 start, stop 和 slice 参数。 （由 Will Roberts 在 bpo-30537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30537} 中贡献。）

@node locale,logging<2>,itertools<2>,改进的模块<3>
@anchor{whatsnew/3 7 locale}@anchor{4b2}
@subsubsection locale


@ref{4b3,,locale.format_string()} 中新的 @emph{monetary} 参数可用于转换所使用的千位分隔符和分组字符串。 （由 Garvit 在 bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379} 中贡献。）

现在 @ref{4b4,,locale.getpreferredencoding()} 函数在 Android 上或是在 @ref{41b,,强制 UTF-8 模式} 下总是返回 @code{'UTF-8'} 。

@node logging<2>,math<3>,locale,改进的模块<3>
@anchor{whatsnew/3 7 logging}@anchor{4b5}
@subsubsection logging


@ref{4b6,,Logger} 实例现在可以被 pickle。 （由 Vinay Sajip 在 bpo-30520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30520} 中贡献。）

新的 @ref{4b7,,StreamHandler.setStream()} 方法可用于在句柄创建之后替换日志流。 （由 Vinay Sajip 在 bpo-30522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30522} 中创建。）

现在可以在传递给 @ref{4b8,,logging.config.fileConfig()} 的配置信息中对句柄构造器指定关键字参数。 （由 Preston Landers 在 bpo-31080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31080} 中贡献。)

@node math<3>,mimetypes,logging<2>,改进的模块<3>
@anchor{whatsnew/3 7 math}@anchor{4b9}
@subsubsection math


新的 @ref{4ba,,math.remainder()} 函数实现了 IEEE 754 风格的余数运算。 （由 Mark Dickinson 在 bpo-29962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29962} 中贡献。）

@node mimetypes,msilib,math<3>,改进的模块<3>
@anchor{whatsnew/3 7 mimetypes}@anchor{4bb}
@subsubsection mimetypes


.bmp 的 MIME type 从 @code{'image/x-ms-bmp'} 改为 @code{'image/bmp'}。 （由 Nitish Chandra 在 bpo-22589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22589} 中贡献。）

@node msilib,multiprocessing<3>,mimetypes,改进的模块<3>
@anchor{whatsnew/3 7 msilib}@anchor{4bc}
@subsubsection msilib


新的 @ref{4bd,,Database.Close()} 方法可用于关闭 @abbr{MSI,last-in@comma{} first-out} 数据库。 （由 Berker Peksag 在 bpo-20486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20486} 中贡献。）

@node multiprocessing<3>,os<3>,msilib,改进的模块<3>
@anchor{whatsnew/3 7 multiprocessing}@anchor{4be}
@subsubsection multiprocessing


新的 @ref{4bf,,Process.close()} 方法会显式地关闭进程对象并释放与其关联的所有资源。 如果底层进程仍在运行则将引发 @ref{16d,,ValueError}。 （由 Antoine Pitrou 在 bpo-30596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30596} 中贡献。）

新的 @ref{4c0,,Process.kill()} 方法可用于在 Unix 上使用 @code{SIGKILL} 信号来终止进程。 （由 Vitor Pereira 在 bpo-30794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30794} 中贡献。）

由 @ref{4c1,,Process} 所创建的非守护线程现在会在进程退出时被合并。 （由 Antoine Pitrou 在 bpo-18966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18966} 中贡献。）

@node os<3>,pathlib<3>,multiprocessing<3>,改进的模块<3>
@anchor{whatsnew/3 7 os}@anchor{4c2}
@subsubsection os


@ref{4c3,,os.fwalk()} 现在接受 @ref{172,,bytes} 类型的 @emph{path} 参数。 （由 Serhiy Storchaka 在 bpo-28682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28682} 中贡献。）

@ref{390,,os.scandir()} 已获得对 @ref{4c4,,文件描述器} 的支持。 （由 Serhiy Storchaka 在 bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996} 中贡献。）

新的 @ref{4c5,,register_at_fork()} 函数允许注册 Python 回调以便在进程分叉中执行。 （由 Antoine Pitrou 在 bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500} 中贡献。）

增加了 @ref{4c6,,os.preadv()} (结合了 @ref{4c7,,os.readv()} 与 @ref{4c8,,os.pread()} 的功能) 以及 @ref{4c9,,os.pwritev()} 函数 (结合了 @ref{4ca,,os.writev()} 和 @ref{4cb,,os.pwrite()} 的功能)。 （由 Pablo Galindo 在 bpo-31368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31368} 中贡献。）

@ref{4cc,,os.makedirs()} 的 mode 参数不再影响新创建的中间层级目录的文件权限。 （由 Serhiy Storchaka 在 bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930} 中贡献。）

@ref{4cd,,os.dup2()} 现在会返回新的文件描述器。 之前，返回的总是 @code{None}。 （由 Benjamin Peterson 在 bpo-32441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32441} 中贡献。）

在 Solaris 及其派生系统上 @ref{328,,os.stat()} 所返回的结构现在会包含 @ref{4ce,,st_fstype} 属性。 （由 Jesús Cea Avión 在 bpo-32659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32659} 中贡献。）

@node pathlib<3>,pdb<2>,os<3>,改进的模块<3>
@anchor{whatsnew/3 7 pathlib}@anchor{4cf}
@subsubsection pathlib


在 POSIX 类系统上新的 @ref{33a,,Path.is_mount()} 方法现在可用于确定一个路径是否为挂载点。 （由 Cooper Ry Lees 在 bpo-30897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30897} 中贡献。）

@node pdb<2>,py_compile<2>,pathlib<3>,改进的模块<3>
@anchor{whatsnew/3 7 pdb}@anchor{4d0}
@subsubsection pdb


@ref{4d1,,pdb.set_trace()} 现在接受一个可选的限关键字参数 @emph{header}。 如果给出，它会在调试开始之前被打印到控制台。 （由 Barry Warsaw 在 bpo-31389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31389} 中贡献。）

@ref{c9,,pdb} 命令行现在接受 @code{-m module_name} 作为对脚本文件的替代。 （由 Mario Corchero 在 bpo-32206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32206} 中贡献。）

@node py_compile<2>,pydoc<2>,pdb<2>,改进的模块<3>
@anchor{whatsnew/3 7 py-compile}@anchor{4d2}
@subsubsection py_compile


@ref{34a,,py_compile.compile()} -- 及其扩展形式 @ref{20,,compileall} -- 现在会通过无条件地为基于哈希值的有效性验证创建 @code{.pyc} 文件来支持 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 环境变量。 这样可以确保当 @code{.pyc} 文件被主动创建时 可重现的生成@footnote{https://reproducible-builds.org/}。 （由 Bernhard M. Wiedemann 在 bpo-29708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29708} 中贡献。）

@node pydoc<2>,queue,py_compile<2>,改进的模块<3>
@anchor{whatsnew/3 7 pydoc}@anchor{4d3}
@subsubsection pydoc


pydoc 服务器现在可以绑定到由新的 @code{-n} 命令行参数所指定的任意主机名。 （由 Feanil Patel 在 bpo-31128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31128} 中贡献。）

@node queue,re,pydoc<2>,改进的模块<3>
@anchor{whatsnew/3 7 queue}@anchor{4d4}
@subsubsection queue


新的 @ref{4d5,,SimpleQueue} 类是一个无界的 @abbr{FIFO,last-in@comma{} first-out} 队列。 （由 Antoine Pitrou 在 bpo-14976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14976} 中贡献。）

@node re,signal<2>,queue,改进的模块<3>
@anchor{whatsnew/3 7 re}@anchor{4d6}
@subsubsection re


旗标 @ref{4d7,,re.ASCII}, @ref{4d8,,re.LOCALE} 和 @code{re.UNICODE} 可以在组的范围内设置。 （由 Serhiy Storchaka 在 bpo-31690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31690} 中贡献。）

@ref{4d9,,re.split()} 现在支持基于匹配一个空字符串的模式例如 @code{r'\b'}, @code{'^$'} 或 @code{(?=-)} 进行拆分。 （由 Serhiy Storchaka 在 bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054} 中贡献。）

使用 @ref{4d8,,re.LOCALE} 旗标编译的正则表达式不再依赖于编译时的区域设置。 区域设置仅在已编译正则表达式被使用时才被应用。 （由 Serhiy Storchaka 在 bpo-30215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30215} 中贡献。）

现在如果一个正则表达式包含语义将在未来发生改变的字符集构造，则会引发 @ref{43e,,FutureWarning}，例如嵌套集与集合操作等。 （由 Serhiy Storchaka 在 bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349} 中贡献。）

已编译正则表达式和匹配对象现在可以使用 @ref{4da,,copy.copy()} 和 @ref{4db,,copy.deepcopy()} 进行拷贝。 （由 Serhiy Storchaka 在 bpo-10076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10076} 中贡献。）

@node signal<2>,socket<3>,re,改进的模块<3>
@anchor{whatsnew/3 7 signal}@anchor{4dc}
@subsubsection signal


@ref{4dd,,signal.set_wakeup_fd()} 函数新增的 @emph{warn_on_full_buffer} 参数可以指定当唤醒缓冲区溢出时 Python 是否要在 stderr 上打印警告信息。 （由 Nathaniel J. Smith 在 bpo-30050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30050} 中贡献。）

@node socket<3>,socketserver,signal<2>,改进的模块<3>
@anchor{whatsnew/3 7 socket}@anchor{4de}
@subsubsection socket


新增的 @ref{4df,,socket.getblocking()} 方法会在套接字处于阻塞模式时返回 @code{True}，否则返回 @code{False}。 （由 Yury Selivanov 在 bpo-32373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32373} 中贡献。）

新的 @ref{4e0,,socket.close()} 函数可关闭所传入的套接字文件描述符。 应该用此函数来代替 @ref{4e1,,os.close()} 以获得更好的跨平台兼容性。 （由 Christian Heimes 在 bpo-32454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32454} 中贡献。）

@ref{ef,,socket} 模块现在会公开 @code{socket.TCP_CONGESTION} (Linux 2.6.13), @code{socket.TCP_USER_TIMEOUT} (Linux 2.6.37) 以及 @code{socket.TCP_NOTSENT_LOWAT} (Linux 3.12) 常量。 （由 Omar Sandoval 在 bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273} 以及 Nathaniel J. Smith 在 bpo-29728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29728} 中贡献。）

已加入对 @ref{4e2,,socket.AF_VSOCK} 套接字的支持以允许在虚拟机及其宿主机之间进行通讯。 （由 Cathy Avery 在 bpo-27584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27584} 中贡献。）

套接字现在默认会根据文件描述符自动检测所属族、类型和协议。 （由 Christian Heimes 在 bpo-28134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28134} 中贡献。）

@node socketserver,sqlite3,socket<3>,改进的模块<3>
@anchor{whatsnew/3 7 socketserver}@anchor{4e3}
@subsubsection socketserver


@code{socketserver.ThreadingMixIn.server_close()} 现在会等待所有非守护线程完成。 @code{socketserver.ForkingMixIn.server_close()} 现在会等待所有子进程完成。

为 @ref{4e4,,socketserver.ForkingMixIn} 和 @ref{4e5,,socketserver.ThreadingMixIn} 类增加了新的 @code{socketserver.ForkingMixIn.block_on_close} 类属性。 该类属性值设为 @code{False} 以保持 3.7 之前的行为。

@node sqlite3,ssl<2>,socketserver,改进的模块<3>
@anchor{whatsnew/3 7 sqlite3}@anchor{4e6}
@subsubsection sqlite3


现在当下层的 SQLite 库版本为 3.6.11 及以上时 @ref{4e7,,sqlite3.Connection} 会开放 @ref{4e8,,backup()} 方法。 （由 Lele Gaifax 在 bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645} 中贡献。）

@ref{4e9,,sqlite3.connect()} 的 @emph{database} 参数现在接受任何 @ref{47b,,path-like object}，而不是只接受字符串。 （由 Anders Lorentsen 在 bpo-31843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31843} 中贡献。）

@node ssl<2>,string,sqlite3,改进的模块<3>
@anchor{whatsnew/3 7 ssl}@anchor{4ea}
@subsubsection ssl


@ref{f3,,ssl} 模块现在使用 OpenSSL 的内置 API 代替 @ref{4eb,,match_hostname()} 来检查主机名或 IP 地址。 值的验证会在 TLS 握手期间进行。 任何证书验证错误包括主机名检查失败现在将引发 @ref{4ec,,SSLCertVerificationError} 并使用正确的 TLS Alert 消息中止握手过程。 这个新异常包含有额外的信息。 主机名验证可通过 @ref{4ed,,SSLContext.hostname_checks_common_name} 进行自定义。 （由 Christian Heimes 在 bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399} 中贡献。）

@cartouche
@quotation 注解 
改进的主机名检测需要有兼容 OpenSSL 1.0.2 或 1.1 的 @emph{libssl} 实现。 因此，OpenSSL 0.9.8 和 1.0.1 不再被支持（请参阅 @ref{4ee,,平台支持的移除} 了解详情）。 目前 ssl 模块主要兼容 LibreSSL 2.7.2 及更高版本。
@end quotation
@end cartouche

@code{ssl} 模块不再以 SNI TLS 扩展发送 IP 地址。 （由 Christian Heimes 在 bpo-32185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32185} 中贡献。）

@ref{4eb,,match_hostname()} 不再支持部分通配符例如 @code{www*.example.org}。 （由 Mandeep Singh 在 bpo-23033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23033} 以及 Christian Heimes 在 bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399} 中贡献。）

@code{ssl} 模块默认的加密套件选择现在是使用黑名单方式而非硬编码的白名单。 Python 不会再重新启用已经被 OpenSSL 安全更新所阻止的加密。 默认的加密套件选择可以在编译时进行配置。 （由 Christian Heimes 在 bpo-31429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31429} 中贡献。）

现在已支持包含国际化域名 (IDN) 的服务器证书验证。 作为此更改的一部分，@ref{4ef,,SSLSocket.server_hostname} 属性现在会以预期的 A 标签形式 (@code{"xn--pythn-mua.org"}) 而不是以 U 标签形式 (@code{"pythön.org"}) 存储。 （由 Nathaniel J. Smith 与 Christian Heimes 在 bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414} 中贡献。）

@code{ssl} 模块对 TLS 1.3 和 OpenSSL 1.1.1 具有初步和实验性的支持。 在 Python 3.7.0 发布的时刻，OpenSSL 1.1.1 仍在开发中，而 TLS 1.3 尚未最终确定。 TLS 1.3 握手和协议行为与 TLS 1.2 及更早的版本略有差异，请参阅 @ref{4f0,,TLS 1.3}。 （由 Christian Heimes 在 bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}, bpo-20995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20995}, bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}, bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622} 以及 bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618} 中贡献。）

@ref{192,,SSLSocket} 和 @ref{4f1,,SSLObject} 不再具有公共构造器。 直接实例化从未成为有文档和受支持的特性。 实际必须通过 @ref{4f2,,SSLContext} 的方法 @ref{4f3,,wrap_socket()} 和 @ref{4f4,,wrap_bio()} 来创建。 （由 Christian Heimes 在 bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951} 中贡献。）

用于设置最小和最大 TLS 协议版本的 OpenSSL 1.1 API 现已可用，名称分别为 @ref{4f5,,SSLContext.minimum_version} 和 @ref{4f6,,SSLContext.maximum_version}。 受支持的协议由几个新增旗标指定，例如 @ref{4f7,,HAS_TLSv1_1}。 （由 Christian Heimes 在 bpo-32609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32609} 中贡献。）

@node string,subprocess,ssl<2>,改进的模块<3>
@anchor{whatsnew/3 7 string}@anchor{4f8}
@subsubsection string


@ref{4f9,,string.Template} 现在允许你有选择地分别修改带大括号的占位符和不带大括号的占位符所对应的正则表达式模式。 （由 Barry Warsaw 在 bpo-1198569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1198569} 中贡献。）

@node subprocess,sys<3>,string,改进的模块<3>
@anchor{whatsnew/3 7 subprocess}@anchor{4fa}
@subsubsection subprocess


@ref{4fb,,subprocess.run()} 函数接受新的 @emph{capture_output} 关键字参数。 当其为真值时，将会捕获 stdout 和 stderr。 这相当于将 @ref{4fc,,subprocess.PIPE} 作为 @emph{stdout} 和 @emph{stderr} 参数传入。 （由 Bo Bayles 在 bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102} 中贡献。）

@code{subprocess.run} 函数和 @ref{3e3,,subprocess.Popen} 构造器现在接受 @emph{text} 关键字参数作为 @emph{universal_newlines} 的别名。 （由 Andrew Clegg 在 bpo-31756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31756} 中贡献。）

在 Windows 中当重定向标准句柄时 @emph{close_fds} 的默认值由 @code{False} 改为 @code{True}。 现在可以在重定向标准句柄时将 @emph{close_fds} 设为真值。 参阅 @ref{3e3,,subprocess.Popen}。 这意味着现在 @emph{close_fds} 在所有受支持的平台上默认值均为 @code{True}。 （由 Segev Finer 在 bpo-19764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19764} 中贡献。）

在 @ref{4fd,,subprocess.call()}, @ref{4fb,,subprocess.run()} 期间或在 @ref{3e3,,Popen} 上下文管理器中，subprocess 模块现在能更优雅地处理 @ref{2d3,,KeyboardInterrupt}。 它现在会等待一小段时间以便子进程退出，然后再继续处理 @code{KeyboardInterrupt} 异常。 （由 Gregory P. Smith 在 bpo-25942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25942} 中贡献。）

@node sys<3>,time<3>,subprocess,改进的模块<3>
@anchor{whatsnew/3 7 sys}@anchor{4fe}
@subsubsection sys


新增 @ref{42c,,sys.breakpointhook()} 钩子函数，供内置的 @ref{414,,breakpoint()} 进行调用。 （由 Barry Warsaw 在 bpo-31353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31353} 中贡献。）

在 Android 中新增的 @ref{4ff,,sys.getandroidapilevel()} 会返回构建时的 Android API 版本。 （由 Victor Stinner 在 bpo-28740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28740} 中贡献。）

新的 @ref{500,,sys.get_coroutine_origin_tracking_depth()} 函数会返回当前协程的由新的 @ref{501,,sys.set_coroutine_origin_tracking_depth()} 所设定的原始跟踪深度。 @ref{9,,asyncio} 已转换为使用这个新 API 代替已弃用的 @code{sys.set_coroutine_wrapper()}。 （由 Nathaniel J. Smith 在 bpo-32591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32591} 中贡献。）

@node time<3>,tkinter<2>,sys<3>,改进的模块<3>
@anchor{whatsnew/3 7 time}@anchor{502}
@subsubsection time


@geindex Python 提高建议; PEP 564
PEP 564@footnote{https://www.python.org/dev/peps/pep-0564}  向 @ref{10c,,time} 模块增加六个具有纳秒级精度的新函数:


@itemize *

@item 
@ref{437,,time.clock_gettime_ns()}

@item 
@ref{438,,time.clock_settime_ns()}

@item 
@ref{439,,time.monotonic_ns()}

@item 
@ref{43a,,time.perf_counter_ns()}

@item 
@ref{43b,,time.process_time_ns()}

@item 
@ref{43c,,time.time_ns()}
@end itemize

增加了新的时钟标识符:


@itemize *

@item 
@ref{503,,time.CLOCK_BOOTTIME} (Linux): 与 @ref{504,,time.CLOCK_MONOTONIC} 相似，不同点在于它还包括任何系统挂起的时间。

@item 
@ref{505,,time.CLOCK_PROF} (FreeBSD, NetBSD 和 OpenBSD): 高精度的分进程 CPU 计时器。

@item 
@ref{506,,time.CLOCK_UPTIME} (FreeBSD, OpenBSD): 该时间的绝对值是系统运行且未挂起的时间，提供准确的正常运行时间度量。
@end itemize

新的 @ref{1e8,,time.thread_time()} 和 @ref{507,,time.thread_time_ns()} 函数可用于获取每线程的 CPU 时间度量。 （由 Antoine Pitrou 在 bpo-32025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32025} 中贡献。）

新的 @ref{508,,time.pthread_getcpuclockid()} 函数会返回特定线程中 CPU 时钟的时钟 ID。

@node tkinter<2>,tracemalloc<2>,time<3>,改进的模块<3>
@anchor{whatsnew/3 7 tkinter}@anchor{509}
@subsubsection tkinter


新的 @ref{50a,,tkinter.ttk.Spinbox} 类现已可用。 （由 Alan Moore 在 bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585} 中贡献。）

@node tracemalloc<2>,types,tkinter<2>,改进的模块<3>
@anchor{whatsnew/3 7 tracemalloc}@anchor{50b}
@subsubsection tracemalloc


@ref{50c,,tracemalloc.Traceback} 的行为更接近正规的回溯，会对所有帧按从最旧到最新来排序。 @ref{50d,,Traceback.format()} 现在接受负的 @emph{limit}，并会将结果截短至排在第 @code{abs(limit)} 位的旧帧。 如果要获得旧的行为，请在 @code{Traceback.format()} 中使用新的  @emph{most_recent_first} 参数。 （由 Jesse Bakker 在 bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121} 中贡献。）

@node types,unicodedata<3>,tracemalloc<2>,改进的模块<3>
@anchor{whatsnew/3 7 types}@anchor{50e}
@subsubsection types


新的 @ref{50f,,WrapperDescriptorType}, @ref{510,,MethodWrapperType}, @ref{511,,MethodDescriptorType} 和 @ref{512,,ClassMethodDescriptorType} 类现已可用。 （由 Manuel Krebber 和 Guido van Rossum 在 bpo-29377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29377} 以及 Serhiy Storchaka 在 bpo-32265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32265} 中贡献。）

新的 @ref{513,,types.resolve_bases()} 函数会以 
@geindex Python 提高建议; PEP 560
PEP 560@footnote{https://www.python.org/dev/peps/pep-0560} 所规定的方式动态解析 MRO 条目。 （由 Ivan Levkivskyi 在 bpo-32717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32717} 中贡献。）

@node unicodedata<3>,unittest<2>,types,改进的模块<3>
@anchor{whatsnew/3 7 unicodedata}@anchor{514}
@subsubsection unicodedata


内部的 @ref{123,,unicodedata} 数据库已升级为使用 Unicode 11@footnote{http://www.unicode.org/versions/Unicode11.0.0/}。 （由 Benjamin Peterson 贡献。）

@node unittest<2>,unittest mock,unicodedata<3>,改进的模块<3>
@anchor{whatsnew/3 7 unittest}@anchor{515}
@subsubsection unittest


新的 @code{-k} 命令行选项允许通过名称子字符串或类似于 Unix shell 的模式来筛选测试项。 例如，@code{python -m unittest -k foo} 将运行 @code{foo_tests.SomeTest.test_something}, @code{bar_tests.SomeTest.test_foo}，但不会运行 @code{bar_tests.FooTest.test_something}。 （由 Jonas Haag 在 bpo-32071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32071} 中贡献。）

@node unittest mock,urllib parse<3>,unittest<2>,改进的模块<3>
@anchor{whatsnew/3 7 unittest-mock}@anchor{516}
@subsubsection unittest.mock


现在 @ref{517,,sentinel} 属性会在它们被 @ref{25,,复制} 或 @ref{ca,,封存} 时保存其标识。 （由 Serhiy Storchaka 在 bpo-20804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20804} 中贡献。）

新的 @ref{518,,seal()} 函数允许 @ref{37a,,Mock} 对实例进行密封，这将禁止进一步创建属性模拟。 密封会以递归方式应用于自身模拟的所有属性。 （由 Mario Corchero 在 bpo-30541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30541} 中贡献。）

@node urllib parse<3>,uu,unittest mock,改进的模块<3>
@anchor{whatsnew/3 7 urllib-parse}@anchor{519}
@subsubsection urllib.parse


@ref{51a,,urllib.parse.quote()} 已经从 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://tools.ietf.org/html/rfc2396.html} 更新为 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html}，将 @code{~} 添加到默认情况下从未引用的字符集。 （由 Christian Theune 和 Ratnadeep Debnath 在 bpo-16285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16285} 中贡献。）

@node uu,uuid,urllib parse<3>,改进的模块<3>
@anchor{whatsnew/3 7 uu}@anchor{51b}
@subsubsection uu


@ref{51c,,uu.encode()} 函数现在接受可选的 @emph{backtick} 关键字参数。 当其为真时，零会以 @code{'`'} 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103} 中贡献。）

@node uuid,warnings,uu,改进的模块<3>
@anchor{whatsnew/3 7 uuid}@anchor{51d}
@subsubsection uuid


新的 @ref{51e,,UUID.is_safe} 属性会从平台中继有关是否使用多进程安全模式来生成所需  UUID 的信息。 （由 Barry Warsaw 在 bpo-22807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22807} 中贡献。）

@ref{51f,,uuid.getnode()} 现在更倾向于统一管理的 MAC 地址而不是本地管理的 MAC 地址。 这样可以更好地保证从 @ref{520,,uuid.uuid1()} 返回的 UUID 的全局唯一性。 如果只有本地管理的 MAC 地址可用，则返回首个找到的此类地址。 （由 Barry Warsaw 在 bpo-32107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32107} 中贡献。）

@node warnings,xml etree,uuid,改进的模块<3>
@anchor{whatsnew/3 7 warnings}@anchor{521}
@subsubsection warnings


默认警告过滤器的初始化已进行以下更改:


@itemize *

@item 
通过命令行选项（包括 @ref{522,,-b} 以及新的 CPython 专属的 @ref{297,,-X} @code{dev} 选项）启用的警告总是会通过 @ref{523,,sys.warnoptions} 属性被传递给警告机制。

@item 
通过命令行或环境变量启用的警告过滤器现在具有以下优先顺序:

@quotation


@itemize *

@item 
用于 @ref{522,,-b} (或 @code{-bb}) 的 @code{BytesWarning} 过滤器

@item 
通过 @ref{15b,,-W} 选项指定的任何过滤器

@item 
通过 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS} 环境变量指定的任何过滤器

@item 
任何其他 CPython 专属过滤器（例如 @code{-X dev} 模式中新增的 @code{default} 过滤器）

@item 
由警告机制所定义的任何隐式过滤器
@end itemize
@end quotation

@item 
在 CPython 调试版本中，现在默认情况下会显示所有警告（隐式过滤器列表为空）
@end itemize

（由 Nick Coghlan 和 Victor Stinner 在 bpo-20361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20361}, bpo-32043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32043} 以及 bpo-32230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32230} 中贡献。）

在单文件脚本和交互式提示符中，默认情况下会再次显示已弃用警告。 详情参见 @ref{41e,,PEP 565; 在 __main__ 中显示 DeprecationWarning}。 （由 Nick Coghlan 在 bpo-31975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31975} 中贡献。）

@node xml etree,xmlrpc server,warnings,改进的模块<3>
@anchor{whatsnew/3 7 xml-etree}@anchor{525}
@subsubsection xml.etree


@code{find()} 方法中的 @ref{526,,ElementPath} 描述词现在可以将当前节点文本与 @code{[. = "text"]} 进行比较，而不仅是子节点中的文本。 描述词还允许添加空格以提高可读性。 （由 Stefan Behnel 在 bpo-31648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31648} 中贡献。）

@node xmlrpc server,zipapp,xml etree,改进的模块<3>
@anchor{whatsnew/3 7 xmlrpc-server}@anchor{527}
@subsubsection xmlrpc.server


@code{SimpleXMLRPCDispatcher.register_function} 现在可以被用作装饰器。 （由 Xiang Zhang 在 bpo-7769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7769} 中贡献。）

@node zipapp,zipfile,xmlrpc server,改进的模块<3>
@anchor{whatsnew/3 7 zipapp}@anchor{528}
@subsubsection zipapp


函数 @ref{529,,create_archive()} 现在接受可选的 @emph{filter} 参数，以允许用户选择哪些文件应被加入归档包。 （由 Irmen de Jong 在 bpo-31072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31072} 中贡献。）

函数 @ref{529,,create_archive()} 现在接受可选的 @emph{compressed} 参数，以生成压缩归档包。 另外也加入了命令行选项 @code{--compress} 以支持压缩。 （由 Zhiming Wang 在 bpo-31638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31638} 中贡献。）

@node zipfile,,zipapp,改进的模块<3>
@anchor{whatsnew/3 7 zipfile}@anchor{52a}
@subsubsection zipfile


@ref{52b,,ZipFile} 现在接受新的 @emph{compresslevel} 形参，以控制压缩级别。 （由 Bo Bayles 在 bpo-21417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21417} 中贡献。）

@code{ZipFile} 所创建的归档包中的子目录现在会按字母表顺序保存。 （由 Bernhard M. Wiedemann 在 bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693} 中贡献。）

@node C API 的改变<2>,构建的改变<2>,改进的模块<3>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 c-api-changes}@anchor{52c}
@subsection C API 的改变


已实现了用于线程本地存储的新 API。 相关概述请参阅 @ref{41f,,PEP 539; 用于线程局部存储的新 C API}，完整参考文档请查看 @ref{430,,Thread Specific Storage (TSS) API}。 （由 Masayuki Yamamoto 在 bpo-25658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25658} 中贡献。)

新的 @ref{410,,上下文变量} 功能开放了许多 @ref{450,,新的 C API}。

新的 @ref{52d,,PyImport_GetModule()} 函数会返回之前所导入的具有给定名称的模块。 （由 Eric Snow 在 bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411} 中贡献。）

新的 @ref{52e,,Py_RETURN_RICHCOMPARE} 宏可以简化丰富比较函数的编写。 （由 Petr Victorin 在 bpo-23699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23699} 中贡献。）

新的 @ref{52f,,Py_UNREACHABLE} 宏可用于标记不可到达的代码路径。 （由 Barry Warsaw 在 bpo-31338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31338} 中贡献。）

@ref{11d,,tracemalloc} 现在通过新的 @ref{530,,PyTraceMalloc_Track()} 和 @ref{531,,PyTraceMalloc_Untrack()} 函数公开了一个 C API。 （由 Victor Stinner 在 bpo-30054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30054} 中贡献。）

新的 @code{import__find__load__start()} 和 @code{import__find__load__done()} 静态标记可用于跟踪模块导入。 （由 Christian Heimes 在 bpo-31574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31574} 中贡献。）

结构体 @ref{532,,PyMemberDef}, @ref{533,,PyGetSetDef}, @ref{534,,PyStructSequence_Field}, @ref{535,,PyStructSequence_Desc} 和 @code{wrapperbase} 的字段 @code{name} 和 @code{doc} 现在的类型为 @code{const char *} 而不是 @code{char *}。 （由 Serhiy Storchaka 在 bpo-28761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28761} 中贡献。）

@ref{536,,PyUnicode_AsUTF8AndSize()} 和 @ref{537,,PyUnicode_AsUTF8()} 的结果类型现在是 @code{const char *} 而非 @code{char *}。 （由 Serhiy Storchaka 在 bpo-28769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28769} 中贡献。）

@ref{538,,PyMapping_Keys()}, @ref{539,,PyMapping_Values()} 和 @ref{53a,,PyMapping_Items()} 的结果现在肯定是列表，而非可能是列表也可能是元组。 （由 Oren Milman 在 bpo-28280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28280} 中贡献。）

添加了函数 @ref{53b,,PySlice_Unpack()} 和 @ref{53c,,PySlice_AdjustIndices()}。 （由 Serhiy Storchaka 在 bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867} 中贡献。）

@ref{53d,,PyOS_AfterFork()} 已弃用，建议改用新的 functions @ref{53e,,PyOS_BeforeFork()}, @ref{53f,,PyOS_AfterFork_Parent()} 和 @ref{3f8,,PyOS_AfterFork_Child()}。 （由 Antoine Pitrou 在 bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500} 中贡献。）

曾经作为公共 API 一部分的 @code{PyExc_RecursionErrorInst} 单例已被移除，因为它的成员永远不会被清理，可能在解释器的最终化过程中导致段错误。 由 Xavier de Gaye 在 bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898} 和 bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697} 中贡献。

添加 C API 对使用 timezone 的构造器 @ref{540,,PyTimeZone_FromOffset()} 和 @ref{541,,PyTimeZone_FromOffsetAndName()} 的时区的支持，以及通常 @ref{542,,PyDateTime_TimeZone_UTC} 使用 UTC 单例。 由 Paul Ganssle 在 bpo-10381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10381} 中贡献。

@code{PyThread_start_new_thread()} 和 @code{PyThread_get_thread_ident()} 的结果类型以及 @ref{543,,PyThreadState_SetAsyncExc()} 的 @emph{id} 参数类型由 @code{long} 改为 @code{unsigned long}。 （由 Serhiy Storchaka 在 bpo-6532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6532} 中贡献。）

现在 @ref{544,,PyUnicode_AsWideCharString()} 如果第二个参数为 @code{NULL} 并且 @code{wchar_t*} 字符串包含空字符则会引发 @ref{16d,,ValueError}。 （由 Serhiy Storchaka 在 bpo-30708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30708} 中贡献。）

对启动顺序以及动态内存分配器管理的更改意味着早已记录在案的，对在调用大多数 C API 函数之前调用 @ref{210,,Py_Initialize()} 的要求的依赖现在变得更加强烈，未遵循此要求可能导致嵌入式应用程序中的段错误。 请参阅此文档的 @ref{422,,移植到 Python 3.7} 一节以及 C API 文档的 @ref{545,,在Python初始化之前} 一节了解更多细节。

新的 @ref{546,,PyInterpreterState_GetID()} 会返回给定解释器的唯一 ID。 （由 Eric Snow 在 bpo-29102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29102} 中贡献。）

现在当启用 @ref{41b,,UTF-8 模式} 时 @ref{547,,Py_DecodeLocale()}, @ref{548,,Py_EncodeLocale()} 会使用 UTF-8 编码。 （由 Victor Stinner 在 bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240} 中贡献。）

@ref{549,,PyUnicode_DecodeLocaleAndSize()} 和 @ref{54a,,PyUnicode_EncodeLocale()} 现在会为 @code{surrogateescape} 错误句柄使用当前区域编码。 （由 Victor Stinner 在 bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240} 中贡献。）

@ref{54b,,PyUnicode_FindChar()} 的 @emph{start} 和 @emph{end} 形参的行为现在调整为与字符串切片类似。 （由 Xiang Zhang 在 bpo-28822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28822} 中贡献。）

@node 构建的改变<2>,性能优化<3>,C API 的改变<2>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 build-changes}@anchor{54c}
@subsection 构建的改变


对于 @code{--without-threads} 构建的支持已被移除。 @ref{10b,,threading} 模块现在将总是可用。 （由 Antoine Pitrou 在 bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370} 中贡献。）

在非 OSX UNIX 平台上已不再包含用于构建 @ref{2a,,_ctypes} 模块的完整 libffi 副本。 现在当在此类平台上构建 @code{_ctypes} 时需要事先装有 libffi 的副本。 （由 Zachary Ware 在 bpo-27979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27979} 中贡献。）

Windows 构建过程不再依赖 Subversion 来拉取外部源码，而是改用一段 Python 脚本从 GitHub 下载 zip 文件。 如果未在系统中找到 Python 3.6 (通过 @code{py -3.6})，则会使用 NuGet 下载一份 32 位的 Python 副本用于此目的。 （由 Zachary Ware 在 bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450} 中贡献。）

@ref{f3,,ssl} 模块需要兼容 OpenSSL 1.0.2 或 1.1 的 libssl。 OpenSSL 1.0.1 的生命期已于 2016-12-31 终止且不再受支持。 LibreSSL 暂时也不受支持。 LibreSSL 发布版直到 2.6.4 版还缺少所需的 OpenSSL 1.0.2 API。

@node 性能优化<3>,其他 CPython 实现的改变,构建的改变<2>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 optimizations}@anchor{54d}@anchor{whatsnew/3 7 whatsnew37-perf}@anchor{421}
@subsection 性能优化


通过移植更多代码来使用 @code{METH_FASTCALL} 的约定，可以显著地减少调用 C 代码中实现的各类标准库的很多方法的开销。 （由 Victor Stinner 在 bpo-29300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29300}、bpo-29507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29507}、bpo-29452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29452} 以及 bpo-29286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29286} 中贡献。）

通过各种优化方式，使 Python 在 Linux 上的启动时间缩短了 10%，在 macOS 上缩短了 30%。 （由 Victor Stinner, INADA Naoki 在 bpo-29585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29585} 中，以及 Ivan Levkivskyi 在 bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333} 中贡献。）

由于避免创建绑定方法案例的字节码更改，方法调用速度现在加快了 20%。 （由 Yury Selivanov 和 INADA Naoki 在 bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110} 中贡献。）
@anchor{whatsnew/3 7 whatsnew37-asyncio-perf}@anchor{45c}
对 @ref{9,,asyncio} 模块里面的一些常用函数做了显著的性能优化。


@itemize *

@item 
@ref{466,,asyncio.get_event_loop()} 函数已经改用 C 重新实现，使其执行速度加快了 15 倍。 （由 Yury Selivanov 在 bpo-32296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32296} 中贡献。）

@item 
@ref{54e,,asyncio.Future} 回调管理已经过优化。 （由 Yury Selivanov 在 bpo-32348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32348} 中贡献。）

@item 
@ref{3b3,,asyncio.gather()} 的执行速度现在加快了 15%。 （由 Yury Selivanov 在 bpo-32355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32355} 中贡献。）

@item 
当 @emph{delay} 参数为零或负值时 @ref{3b2,,asyncio.sleep()} 的执行速度现在加快了 2 倍。 （由 Andrew Svetlov 在 bpo-32351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32351} 中贡献。）

@item 
asyncio 调试模式的执行开销已获减轻。 （由 Antoine Pitrou 在 bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970} 中贡献。）
@end itemize

作为 @ref{416,,PEP 560 工作} 的结果，@ref{122,,typing} 的导入时间已减少了 7 倍，许多与类型相关的操作现在会执行得更快。 （由 Ivan Levkivskyi 在 bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226} 中贡献。）

@ref{54f,,sorted()} 和 @ref{550,,list.sort()} 已经过优化，在通常情况下执行速度可提升 40-75%。 （由 Elliot Gorokhovsky 在 bpo-28685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28685} 中贡献。）

@ref{551,,dict.copy()} 的执行速度现在加快了 5.5 倍。 （由 Yury Selivanov 在 bpo-31179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31179} 中贡献。）

当 @emph{name} 未找到并且 @emph{obj} 未重载 @ref{433,,object.__getattr__()} 或 @ref{552,,object.__getattribute__()} 时 @ref{553,,hasattr()} 和 @ref{554,,getattr()} 现在会比原来快大约 4 倍。 （由 INADA Naoki 在 bpo-32544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32544} 中贡献。）

在字符串中搜索特定的 Unicode 字符（例如乌克兰语字母“Є”）会比搜索其他字符慢上 25 倍。 而现在最坏情况下也只会慢上 3 倍。 （由 Serhiy Storchaka 在 bpo-24821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24821} 中贡献。）

@ref{1a1,,collections.namedtuple()} 工厂对象已经重写实现，使得创建具名元组的速度加快了 4 到 6 倍。 （由 Jelle Zijlstra 在 bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638} 中贡献，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger 贡献。）

现在 @code{date.fromordinal()} 和 @code{date.fromtimestamp()} 在通常情况下执行速度可提升 30%。 （由 Paul Ganssle 在 bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403} 中贡献。）

由于使用了 @ref{390,,os.scandir()}，现在 @ref{4c3,,os.fwalk()} 函数执行速度提升了 2 倍。 （由 Serhiy Storchaka 在 bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996} 中贡献。）

由于使用了 @ref{390,,os.scandir()} 函数，@ref{350,,shutil.rmtree()} 函数的执行速度已经提升了 20--40%。 （由 Serhiy Storchaka 在 bpo-28564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28564} 中贡献。）

@ref{dd,,正则表达式} 忽略大小写的匹配和搜索已获得优化。 现在搜索某些模式的速度提升了 20 倍。 （由 Serhiy Storchaka 在 bpo-30285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30285} 中贡献。）

@ref{555,,re.compile()} 现在会将 @code{flags} 形参转换为 int 对象，如果它是 @code{RegexFlag} 的话。 它现在会和 Python 3.5 一样快，而比 Python 3.6 快大约 10%，实际速度取决于具体的模式。 （由 INADA Naoki 在 bpo-31671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31671} 中贡献。）

@ref{556,,selectors.EpollSelector}, @ref{557,,selectors.PollSelector} 和 @ref{558,,selectors.DevpollSelector} 这几个类的 @ref{559,,modify()} 方法在重负载下可以加快 10% 左右。 （由 Giampaolo Rodola' 在 bpo-30014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30014} 中贡献。）

常量折叠已经从窥孔优化器迁移至新的 AST 优化器，后者可以以更高的一致性来执行优化。 （由 Eugene Toder 和 INADA Naoki 在 bpo-29469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29469} 和 bpo-11549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11549} 中贡献。）

@ref{3,,abc} 中的大部分函数和方法已经用 C 重写。 这使得创建抽像基类以及调用其 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 的速度加快了 1.5 倍。 这也使得 Python 启动耗时减少了 10%。 （由 Ivan Levkivskyi 和 INADA Naoki 在 bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333} 中贡献。）

在不构造子类时，通过使用快速路径构造器使得 @ref{19d,,datetime.date} 和 @ref{19f,,datetime.datetime} 的替代构造器获得了显著的速度提升。 （由 Paul Ganssle 在 bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403} 中贡献。）

在特定情况下 @ref{217,,array.array} 实例的比较速度已获得很大提升。 现在当比较存放相同的整数类型的值的数组时会比原来快 10 到 70 倍。 （由 Adrian Wielgosik 在 bpo-24700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24700} 中贡献。）

在大多数平台上 @ref{55c,,math.erf()} 和 @ref{55d,,math.erfc()} 函数现在使用（更快的）C 库实现。 （由 Serhiy Storchaka 在 bpo-26121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26121} 中贡献。）

@node 其他 CPython 实现的改变,已弃用的 Python 行为,性能优化<3>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 other-cpython-implementation-changes}@anchor{55e}
@subsection 其他 CPython 实现的改变



@itemize *

@item 
跟踪钩子现在可以选择不接收 @code{line} 而是选择从解释器接收 @code{opcode} 事件，具体做法是在被跟踪的帧上相应地设置新的 @code{f_trace_lines} 和 @code{f_trace_opcodes} 属性。 （由 Nick Coghlan 在 bpo-31344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31344} 中贡献。）

@item 
修复了一些命名空间包模块属性的一致性问题。 命名空间模块对象的 @code{__file__} 被设置为 @code{None}  (原先未设置)，对象的 @code{__spec__.origin} 也被设置为 @code{None} (之前为字符串 @code{"namespace"})。 参见 bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}。 而且，命名空间模块对象的 @code{__spec__.loader} 被设置的值与 @code{__loader__} 相同 (原先前者被设置为 @code{None})。 参见 bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}。

@item 
@ref{55f,,locals()} 字典现在以变量定义的词法顺序显示。 原先未定义顺序。 （由 Raymond Hettinger 在 bpo-32690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32690} 中贡献。）

@item 
@ref{38,,distutils} @code{upload} 命令不会再试图将行结束字符 CR 改为 CRLF。 这修复了 sdists 的一个以与 CR 等价的字节结束的数据损坏问题。 （由 Bo Bayles 在 bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304} 中贡献。）
@end itemize

@node 已弃用的 Python 行为,已弃用的 Python 模块、函数和方法,其他 CPython 实现的改变,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 deprecated-python-behavior}@anchor{560}
@subsection 已弃用的 Python 行为


在推导式和生成器表达式中的 yield 语句（包括 @code{yield} 和 @code{yield from} 子句）现在已弃用（最左端的 @code{for} 子句中的可迭代对象表达式除外）。 这确保了推导式总是立即返回适当类型的容器（而不是有可能返回 @ref{561,,generator iterator} 对象），这样生成器表达式不会试图将它们的隐式输出与任何来自显式 yield 表达式的输出交错起来。 在 Python 3.7 中，这样的表达式会在编译时引发 @ref{15a,,DeprecationWarning}，在 Python 3.8 中则将引发 @ref{562,,SyntaxError}。 （由 Serhiy Storchaka 在 bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544} 中贡献。）

从 @ref{2cc,,object.__complex__()} 返回一个 @ref{2c8,,complex} 的子类的行为已弃用并将在未来的 Python 版本中引发错误。 这使得 @code{__complex__()} 的行为与 @ref{2ca,,object.__int__()} 和 @ref{2cb,,object.__float__()} 保持一致。 （由 Serhiy Storchaka 在 bpo-28894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28894} 中贡献。）

@node 已弃用的 Python 模块、函数和方法,已弃用的 C API 函数和类型,已弃用的 Python 行为,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 deprecated-python-modules-functions-and-methods}@anchor{563}
@subsection 已弃用的 Python 模块、函数和方法


@menu
* aifc:: 
* asyncio: asyncio<4>. 
* collections: collections<3>. 
* dbm: dbm<2>. 
* enum: enum<2>. 
* gettext: gettext<2>. 
* importlib: importlib<3>. 
* locale: locale<2>. 
* macpath:: 
* threading: threading<2>. 
* socket: socket<4>. 
* ssl: ssl<3>. 
* sunau:: 
* sys: sys<4>. 
* wave:: 

@end menu

@node aifc,asyncio<4>,,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 aifc}@anchor{564}
@subsubsection aifc


@code{aifc.openfp()} 已弃用并将在 Python 3.9 中被移除。 请改用 @ref{565,,aifc.open()}。 （由 Brian Curtin 在 bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985} 中贡献。）

@node asyncio<4>,collections<3>,aifc,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id2}@anchor{566}@anchor{whatsnew/3 7 whatsnew37-asyncio-deprecated}@anchor{47c}
@subsubsection asyncio


对 @ref{3b6,,asyncio.Lock} 和其他 asyncio 同步原语的 @code{await} 实例的直接支持已弃用。 想要获取并释放同步资源必须使用异步上下文管理器。 （由 Andrew Svetlov 在 bpo-32253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32253} 中贡献。）

@code{asyncio.Task.current_task()} 和 @code{asyncio.Task.all_tasks()} 方法已弃用。 （由 Andrew Svetlov 在 bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250} 中贡献。）

@node collections<3>,dbm<2>,asyncio<4>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id3}@anchor{567}
@subsubsection collections


在 Python 3.8 中，@ref{1e,,collections.abc} 内的抽象基类将不会再通过常规的 @ref{1d,,collections} 模块公开。 这有助于更清晰地区别具体类与抽象基类。 （由 Serhiy Storchaka 在 bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988} 中贡献。）

@node dbm<2>,enum<2>,collections<3>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id4}@anchor{568}
@subsubsection dbm


@ref{32,,dbm.dumb} 现在支持读取只读文件，且当其未被更改时不会再写入索引文件。 现在如果索引文件丢失并在 @code{'r'} 与 @code{'w'} 模式下被重新创建，则会发出已弃用警告（在未来的 Python 发布版中将改为错误）。 （由 Serhiy Storchaka 在 bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847} 中贡献。）

@node enum<2>,gettext<2>,dbm<2>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id5}@anchor{569}
@subsubsection enum


在 Python 3.8 中，尝试在 @code{Enum} 类中检查非 Enum 对象将引发 @ref{1ff,,TypeError} (例如 @code{1 in Color})；类似地，尝试在 @code{Flag} 成员中检查非 Flag 对象也将引发 @ref{1ff,,TypeError} (例如 @code{1 in Perm.RW})；目前，两种操作均会返回 @ref{497,,False}。 （由 Ethan Furman 在 bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217} 中贡献。）

@node gettext<2>,importlib<3>,enum<2>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 gettext}@anchor{56a}
@subsubsection gettext


使用非整数值在 @ref{87,,gettext} 中选择复数形式现在已弃用。 它从未正确地发挥作用。 （由 Serhiy Storchaka 在 bpo-28692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28692} 中贡献。）

@node importlib<3>,locale<2>,gettext<2>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id6}@anchor{56b}
@subsubsection importlib


下列方法 @ref{56c,,MetaPathFinder.find_module()} (被 @ref{56d,,MetaPathFinder.find_spec() 替代}) 和 @ref{56e,,PathEntryFinder.find_loader()} (被 @ref{56f,,PathEntryFinder.find_spec() 替代}) 都在 Python 3.4 中已弃用，现在会引发 @ref{15a,,DeprecationWarning}。 （由 Matthias Bussonnier 在 bpo-29576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29576} 中贡献）

@ref{570,,importlib.abc.ResourceLoader} ABC 已弃用，推荐改用 @ref{457,,importlib.abc.ResourceReader}。

@node locale<2>,macpath,importlib<3>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id7}@anchor{571}
@subsubsection locale


@ref{572,,locale.format()} 已弃用，请改用 @ref{4b3,,locale.format_string()}。 （由 Garvit 在 bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379} 中贡献。）

@node macpath,threading<2>,locale<2>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 macpath}@anchor{573}
@subsubsection macpath


@code{macpath} 现在已弃用，将在 Python 3.8 中被移除。 （由 Chi Hsuan Yen 在 bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850} 中贡献。）

@node threading<2>,socket<4>,macpath,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 threading}@anchor{574}
@subsubsection threading


@code{dummy_threading} 和 @code{_dummy_thread} 已弃用。 构建禁用线程的 Python 已不再可能。 请改用 @ref{10b,,threading}。 （由 Antoine Pitrou 在 bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370} 中贡献。）

@node socket<4>,ssl<3>,threading<2>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id8}@anchor{575}
@subsubsection socket


@ref{576,,socket.htons()} 和 @ref{577,,socket.ntohs()} 中的静默参数截断已弃用。 在未来的 Python 版本中，如果传入的参数长度大于 16 比特位，将会引发异常。 （由 Oren Milman 在 bpo-28332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28332} 中贡献。）

@node ssl<3>,sunau,socket<4>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id9}@anchor{578}
@subsubsection ssl


@ref{579,,ssl.wrap_socket()} 已弃用。 请改用 @ref{4f3,,ssl.SSLContext.wrap_socket()}。 （由 Christian Heimes 在 bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124} 中贡献。）

@node sunau,sys<4>,ssl<3>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 sunau}@anchor{57a}
@subsubsection sunau


@code{sunau.openfp()} 已弃用并将在 Python 3.9 中被移除。 请改用 @ref{57b,,sunau.open()}。 （由 Brian Curtin 在 bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985} 中贡献。）

@node sys<4>,wave,sunau,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 id10}@anchor{57c}
@subsubsection sys


已弃用 @code{sys.set_coroutine_wrapper()} 和 @code{sys.get_coroutine_wrapper()}。

未写入文档的 @code{sys.callstats()} 函数已弃用并将在未来的 Python 版本中被移除。 （由 Victor Stinner 在 bpo-28799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28799} 中贡献。）

@node wave,,sys<4>,已弃用的 Python 模块、函数和方法
@anchor{whatsnew/3 7 wave}@anchor{57d}
@subsubsection wave


@code{wave.openfp()} 已弃用并将在 Python 3.9 中被移除。 请改用 @ref{21a,,wave.open()}。 （由 Brian Curtin 在 bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985} 中贡献。）

@node 已弃用的 C API 函数和类型,平台支持的移除,已弃用的 Python 模块、函数和方法,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 deprecated-functions-and-types-of-the-c-api}@anchor{57e}
@subsection 已弃用的 C API 函数和类型


如果 @code{Py_LIMITED_API} 未设定或设定为范围在 @code{0x03050400} 和 @code{0x03060000} (不含) 之间，或为 @code{0x03060100} 或更高的值，函数 @ref{57f,,PySlice_GetIndicesEx()} 已弃用并被一个宏所替代。 （由 Serhiy Storchaka 在 bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867} 中贡献。）

@ref{53d,,PyOS_AfterFork()} 已弃用。 请改用 @ref{53e,,PyOS_BeforeFork()}, @ref{53f,,PyOS_AfterFork_Parent()} 或 @ref{3f8,,PyOS_AfterFork_Child()}。 （由 Antoine Pitrou 在 bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500} 中贡献。）

@node 平台支持的移除,API 与特性的移除<2>,已弃用的 C API 函数和类型,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 id11}@anchor{580}@anchor{whatsnew/3 7 platform-support-removals}@anchor{4ee}
@subsection 平台支持的移除



@itemize *

@item 
官方已不再支持 FreeBSD 9 及更旧的版本。

@item 
为了完整的 Unicode 支持，包括在扩展模块之内，*nix 平台现在至少应当提供 @code{C.UTF-8} (完整区域), @code{C.utf8} (完整区域) 或 @code{UTF-8} (@code{LC_CTYPE} 专属区域) 中的一个作为基于 @code{ASCII} 的传统 @code{C} 区域的替代。

@item 
OpenSSL 0.9.8 和 1.0.1 已不再受支持，这意味着在仍然使用这些版本的旧平台上构建带有 SSL/TLS 支持的 CPython 3.7 时，需要自定义构建选项以链接到更新的 OpenSSL 版本。

注意，此问题会影响到 Debian 8 (代号“jessie”) 和 Ubuntu 14.04 (代号“Trusty”) 等长期支持 Linux 发行版，因为它们默认仍然使用 OpenSSL 1.0.1。

Debian 9 (“stretch”) 和 Ubuntu 16.04 (“xenial”) 以及其他最新的长期支持 Linux 发行版 (例如 RHEL/CentOS 7.5, SLES 12-SP3) 都使用 OpenSSL 1.0.2 或更新的版本，因此继续在默认的构建配置中受到支持。

CPython 自己的 CI 配置文件@footnote{https://github.com/python/cpython/tree/3.9/.travis.yml} 提供了一个使用 CPython 测试套件中的 SSL 兼容性测试架构@footnote{https://github.com/python/cpython/tree/3.9/Tools/ssl/multissltests.py} 基于 OpenSSL 1.1.0 进行构建和链接的例子，而不是使用过时的系统所提供的 OpenSSL。
@end itemize

@node API 与特性的移除<2>,移除的模块,平台支持的移除,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 api-and-feature-removals}@anchor{581}
@subsection API 与特性的移除


下列特性与 API 已从 Python 3.7 中移除:


@itemize *

@item 
@code{os.stat_float_times()} 函数已被移除。 它在 Python 2.3 中被引入用于向下兼容 Python 2.2，并自 Python 3.1 起就已弃用。

@item 
在 @ref{582,,re.sub()} 的替换模块中由 @code{'\'} 与一个 ASCII 字母构成的未知转义在 Python 3.5 中已弃用，现在将会引发错误。

@item 
在 @ref{583,,tarfile.TarFile.add()} 中移除了对 @emph{exclude} 参数的支持。 它在 Python 2.7 和 3.2 中已弃用。 请改用 @emph{filter} 参数。

@item 
@code{ntpath} 模块中的 @code{splitunc()} 函数在 Python 3.1 中已弃用，现在已被移除。 请改用 @ref{584,,splitdrive()} 函数。

@item 
@ref{1a1,,collections.namedtuple()} 不再支持 @emph{verbose} 形参或 @code{_source} 属性，该属性会显示为具名元组类所生成的源代码。 这是加速类创建的设计优化的一部分。 （由 Jelle Zijlstra 在 bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638} 中贡献，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger 贡献。）

@item 
函数 @ref{2c4,,bool()}, @ref{1fe,,float()}, @ref{1f9,,list()} 和 @ref{1a2,,tuple()} 不再接受关键字参数。 @ref{205,,int()} 的第一个参数现在只能作为位置参数传入。

@item 
移除了之前在 Python 2.4 中已弃用的 @ref{cf,,plistlib} 模块的类 @code{Plist}, @code{Dict} 和 @code{_InternalDict}。 作为函数 @code{readPlist()} 和 @code{readPlistFromBytes()} 返回结果的 Dict 值现在为普通 dict。 你不能再使用属性访问来获取这些字典的项。

@item 
@code{asyncio.windows_utils.socketpair()} 函数已被移除。 请改用 @ref{585,,socket.socketpair()} 函数，它自 Python 3.5 起就在所有平台上可用。 @code{asyncio.windows_utils.socketpair} 在 Python 3.5 及更新版本上只是 @code{socket.socketpair} 的别名。

@item 
@ref{9,,asyncio} 不再将 @ref{e6,,selectors} 和 @code{_overlapped} 模块导出为 @code{asyncio.selectors} 和 @code{asyncio._overlapped}。 请将 @code{from asyncio import selectors} 替换为 @code{import selectors}。

@item 
现在已禁止直接实例化 @ref{192,,ssl.SSLSocket} 和 @ref{4f1,,ssl.SSLObject} 对象。 相应构造器从未写入文档、也从未作为公有构造器进行测试或设计。 用户应当使用 @ref{579,,ssl.wrap_socket()} 或 @ref{4f2,,ssl.SSLContext}。 （由 Christian Heimes 在 bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951} 中贡献。）

@item 
未被使用的 @ref{38,,distutils} @code{install_misc} 命令已被移除。 （由 Eric N. Vander Weele 在 bpo-29218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29218} 中贡献。）
@end itemize

@node 移除的模块,Windows 专属的改变,API 与特性的移除<2>,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 module-removals}@anchor{586}
@subsection 移除的模块


@code{fpectl} 模块已被移除。 它从未被默认启用，从未在 x86-64 上正确发挥效果，并且它对 Python ABI 的改变会导致 C 扩展的意外损坏。 （由 Nathaniel J. Smith 在 bpo-29137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29137} 中贡献。）

@node Windows 专属的改变,移植到 Python 3 7,移除的模块,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 windows-only-changes}@anchor{587}
@subsection Windows 专属的改变


Python 启动器（py.exe）可以接受 32 位或 64 位标记而 @strong{不必} 同时指定一个小版本。 因此 @code{py -3-32} 和 @code{py -3-64} 与 @code{py -3.7-32} 均为有效，并且现在还接受 -@emph{m}-64 和 -@emph{m.n}-64 来强制使用 64 位 python 命令，即使是本应使用 32 位的时候。 如果指定版本不可用则 py.exe 将报错退出。 （由 Steve Barnes 在 bpo-30291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30291} 中贡献。）

启动器可以运行 @code{py -0} 来列出已安装的所有 python，@emph{默认版本会以星号标出}。 运行 @code{py -0p} 将同时列出相应的路径。 如果运行 py 时指定了无法匹配的版本，它将显示 @emph{简短形式} 的可用版本列表。 （由 Steve Barnes 在 bpo-30362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30362} 中贡献。）

@node 移植到 Python 3 7,Python 3 7 1 中的重要变化,Windows 专属的改变,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 porting-to-python-3-7}@anchor{588}@anchor{whatsnew/3 7 porting-to-python-37}@anchor{422}
@subsection 移植到 Python 3.7


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* Python 行为的更改:: 
* 更改的Python API: 更改的Python API<2>. 
* C API 中的改变: C API 中的改变<2>. 
* CPython 字节码的改变: CPython 字节码的改变<3>. 
* Windows 专属的改变: Windows 专属的改变<2>. 
* 其他 CPython 实现的改变: 其他 CPython 实现的改变<2>. 

@end menu

@node Python 行为的更改,更改的Python API<2>,,移植到 Python 3 7
@anchor{whatsnew/3 7 changes-in-python-behavior}@anchor{589}
@subsubsection Python 行为的更改



@itemize *

@item 
@ref{2de,,async} 和 @ref{2df,,await} 现在是保留关键字。 使用了这些名称作为标识符的代码现在将引发 @ref{562,,SyntaxError}。 （由 Jelle Zijlstra 在 bpo-30406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30406} 中贡献。）

@item 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} 在 Python 3.7 中对所有代码启用，在协程和生成器中直接或间接引发的 @ref{58a,,StopIteration} 异常会被转换为 @ref{3e4,,RuntimeError} 异常。 （由 Yury Selivanov 在 bpo-32670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32670} 中贡献。）

@item 
@ref{58b,,object.__aiter__()} 方法不再能被声明为异步的。 （由 Yury Selivanov 在 bpo-31709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31709} 中贡献。）

@item 
由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

@example
f(1 for x in [1],)

class C(1 for x in [1]):
    pass
@end example

现在 Python 3.7 会正确地引发 @ref{562,,SyntaxError}，因为生成器表达式总是必须直接包含于一对括号之内， 且前后都不能有逗号，仅在调用时可以忽略重复的括号。 （由 Serhiy Storchaka 在 bpo-32012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32012} 和 bpo-32023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32023} 中贡献。）

@item 
现在当使用 @ref{44c,,-m} 开关时，会将初始工作目录添加到 @ref{262,,sys.path}，而不再是一个空字符串（即在每次导入时动态地指明当前工作目录）。 任何会检测该空字符串，或是以其他方式依赖之前行为的的程序将需要进行相应的更新（例如改为还要检测 @code{os.getcwd()} 或 @code{os.path.dirname(__main__.__file__)}，具体做法首先要取决于为何要对代码执行空字符串检测）。
@end itemize

@node 更改的Python API<2>,C API 中的改变<2>,Python 行为的更改,移植到 Python 3 7
@anchor{whatsnew/3 7 changes-in-the-python-api}@anchor{58c}
@subsubsection 更改的Python API



@itemize *

@item 
@code{socketserver.ThreadingMixIn.server_close()} 现在会等待所有非守护线程完成。 将新增的 @code{socketserver.ThreadingMixIn.block_on_close} 类属性设为 @code{False} 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在 bpo-31233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31233} 和 bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540} 中贡献。）

@item 
@code{socketserver.ForkingMixIn.server_close()} 现在会等等所有子进程完成。 将新增的 @code{socketserver.ForkingMixIn.block_on_close} 类属性设为 @code{False} 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在 bpo-31151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31151} 和 bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540} 中贡献。）

@item 
某些情况下 @ref{58d,,locale.localeconv()} 函数现在会临时将 @code{LC_CTYPE} 区域设置为 @code{LC_NUMERIC} 的值。 （由 Victor Stinner 在 bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900} 中贡献。）

@item 
如果 @emph{path} 为字符串 @ref{58e,,pkgutil.walk_packages()} 现在会引发 @ref{16d,,ValueError}。 之前则是返回一个空列表。 （由 Sanyam Khurana 在 bpo-24744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24744} 中贡献。）

@item 
@ref{58f,,string.Formatter.format()} 的格式字符串参数现在为 @ref{3d1,,仅限位置} 参数。 将其作为关键字参数传入的方式自 Python 3.5 起已弃用。 （由 Serhiy Storchaka 在 bpo-29193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29193} 中贡献。）

@item 
类 @ref{590,,http.cookies.Morsel} 的属性 @ref{591,,key}, @ref{592,,value} 和 @ref{593,,coded_value} 现在均为只读。 对其赋值的操作自 Python 3.5 起已弃用。 要设置它们的值请使用 @ref{594,,set()} 方法。 （由 Serhiy Storchaka 在 bpo-29192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29192} 中贡献。）

@item 
@ref{4cc,,os.makedirs()} 的 @emph{mode} 参数不会再影响新建中间层级目录的文件权限位。 要设置它们的文件权限位你可以在发起调用 @code{makedirs()} 之前设置 umask。 （由 Serhiy Storchaka 在 bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930} 中贡献。）

@item 
@ref{595,,struct.Struct.format} 的类型现在是 @ref{206,,str} 而非 @ref{172,,bytes}。 （由 Victor Stinner 在 bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071} 中贡献。）

@item 
@ref{283,,parse_multipart()} 现在接受 @emph{encoding} 和 @emph{errors} 参数并返回与 @code{FieldStorage} 同样的结果：对于非文件字段，与键相关联的值是一个字符串列表，而非字节串。 （由 Pierre Quentel 在 bpo-29979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29979} 中贡献。）

@item 
由于 @ref{ef,,socket} 中的内部更改，在由旧版 Python 中的 @ref{596,,socket.share} 所创建的套接字上调用 @ref{597,,socket.fromshare()} 已不受支持。

@item 
@ref{2e2,,BaseException} 的 @code{repr} 已更改为不包含末尾的逗号。 大多数异常都会受此更改影响。 （由 Serhiy Storchaka 在 bpo-30399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30399} 中贡献。）

@item 
@ref{2d1,,datetime.timedelta} 的 @code{repr} 已更改为在输出中包含关键字参数。 （由 Utkarsh Upadhyay 在 bpo-30302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30302} 中贡献。）

@item 
因为 @ref{350,,shutil.rmtree()} 现在是使用 @ref{390,,os.scandir()} 函数实现的，用户指定的句柄 @emph{onerror} 现在被调用时如果列目录失败会附带第一个参数 @code{os.scandir} 而不是 @code{os.listdir}。

@item 
未来可能加入在正则表达式中对 Unicode 技术标准 #18@footnote{https://unicode.org/reports/tr18/} 中嵌套集合与集合操作的支持。 这会改变现有语法。 为了推动这项未来的改变，目前在有歧义的情况下会引发 @ref{43e,,FutureWarning}。 这包括以字面值 @code{'['} 开头或包含字面值字符序列 @code{'--'}, @code{'&&'}, @code{'~~'} 以及 @code{'||'}  的集合。 要避免警告，请用反斜杠对其进行转义。 （由 Serhiy Storchaka 在 bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349} 中贡献。）

@item 
基于可以匹配空字符串的 @ref{dd,,正则表达式} 对字符串进行拆分的结果已被更改。 例如基于 @code{r'\s*'} 的拆分现在不仅会像原先那样拆分空格符，而且会拆分所有非空格字符之前和字符串结尾处的空字符串。 通过将模式修改为 @code{r'\s+'} 可以恢复原先的行为。 自 Python 3.5 开始此类模式将会引发 @ref{43e,,FutureWarning}。

对于同时匹配空字符串和非空字符串的模式，在其他情况下搜索所有匹配的结果也可能会被更改。 例如在字符串 @code{'a\n\n'} 中，模式 @code{r'(?m)^\s*?$'} 将不仅会匹配位置 2 和 3 上的空字符串，还会匹配位置 2--3 上的字符串 @code{'\n'}。 想要只匹配空行，模式应当改写为 @code{r'(?m)^[^\S\n]*$'}。

@ref{582,,re.sub()} 现在会替换与前一个的非空匹配相邻的空匹配。 例如 @code{re.sub('x*', '-', 'abxd')} 现在会返回 @code{'-a-b--d-'} 而不是 @code{'-a-b-d-'} ('b' 和 'd' 之间的第一个减号是替换 'x'，而第二个减号则是替换 'x' 和 'd' 之间的空字符串)。

（由 Serhiy Storchaka 在 bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054} 和 bpo-32308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32308} 中贡献。）

@item 
@ref{598,,re.escape()} 更改为只转义正则表达式特殊字符，而不转义 ASCII 字母、数字和 @code{'_'} 以外的所有字符。 （由 Serhiy Storchaka 在 bpo-29995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29995} 中贡献。）

@item 
@ref{50c,,tracemalloc.Traceback} 帧现在是按从最旧到最新排序，以便与 @ref{11c,,traceback} 更为一致。 （由 Jesse Bakker 在 bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121} 中贡献。）

@item 
在支持 @ref{599,,socket.SOCK_NONBLOCK} 或 @ref{59a,,socket.SOCK_CLOEXEC} 标志位的操作系统上，@ref{59b,,socket.type} 不再应用它们。 因此，像 @code{if sock.type == socket.SOCK_STREAM} 之类的检测会在所有平台上按预期的方式工作。 （由 Yury Selivanov 在 bpo-32331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32331} 中贡献。）

@item 
在 Windows 上当重定向标准句柄时，@ref{3e3,,subprocess.Popen} 的 @emph{close_fds} 参数的默认值从 @ref{497,,False} 更改为 @ref{59c,,True}。 如果你以前依赖于在使用带有标准 io 重定向的 @ref{3e3,,subprocess.Popen} 时所继承的句柄，则必须传入 @code{close_fds=False} 以保留原先的行为，或是使用 @ref{59d,,STARTUPINFO.lpAttributeList}。

@item 
@ref{59e,,importlib.machinery.PathFinder.invalidate_caches()} -- 此方法隐式地影响 @ref{59f,,importlib.invalidate_caches()} -- 现在会删除 @ref{5a0,,sys.path_importer_cache} 中被设为 @code{None} 的条目。 （由 Brett Cannon 在 bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169} 中贡献。）

@item 
在 @ref{9,,asyncio} 中，@ref{5a1,,loop.sock_recv()}, @ref{5a2,,loop.sock_sendall()}, @ref{5a3,,loop.sock_accept()}, @ref{5a4,,loop.getaddrinfo()}, @ref{5a5,,loop.getnameinfo()} 已被更改为正确的协程方法以与培训五日文档相匹配。 之前，这些方法会返回 @ref{54e,,asyncio.Future} 实例。 （由 Yury Selivanov 在 bpo-32327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32327} 中贡献。）

@item 
@ref{5a6,,asyncio.Server.sockets} 现在会返回服务器套接字列表的副本，而不是直接地返回它。 （由 Yury Selivanov 在 bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662} 中贡献。）

@item 
@ref{595,,Struct.format} 现在是一个 @ref{206,,str} 实例而非 @ref{172,,bytes} 实例。 （由 Victor Stinner 在 bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071} 中贡献。）

@item 
现在可以通过将 @code{required=True} 传给 @ref{5a7,,ArgumentParser.add_subparsers()} 使得 @ref{5,,argparse} 子解析器成为必需的。 （由 Anthony Sottile 在 bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510} 中贡献。）

@item 
@ref{5a8,,ast.literal_eval()} 现在更为严格。 任意地加减数字已不再被允许。 （由 Serhiy Storchaka 在 bpo-31778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31778} 中贡献。）

@item 
当一个日期超出 @code{0001-01-01} 到 @code{9999-12-31} 范围时 @ref{5a9,,Calendar.itermonthdates} 现在将始终如一地引发异常，以便支持不能容忍此类异常的应用程序，可以使用新增的 @ref{5aa,,Calendar.itermonthdays3} 和 @ref{5ab,,Calendar.itermonthdays4}。 这些新方法返回元组，并且其不受 @ref{19d,,datetime.date} 所支持的范围限制。 （由 Alexander Belopolsky 在 bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292} 中贡献。）

@item 
@ref{5ac,,collections.ChainMap} 现在会保留底层映射的顺序。 （由 Raymond Hettinger 在 bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792} 中贡献。）

@item 
如果在解释器关闭期间被调用，@ref{18c,,concurrent.futures.ThreadPoolExecutor} 和 @ref{196,,concurrent.futures.ProcessPoolExecutor} 的 @code{submit()} 方法现在会引发 @ref{3e4,,RuntimeError}。 （由 Mark Nemec 在 bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097} 中贡献。）

@item 
@ref{5ad,,configparser.ConfigParser} 构造器现在使用 @code{read_dict()} 来处理默认值，以使其行为与解析器的其余部分保持致。 在默认字典中的非字符串键和值现在会被隐式地转换为字符串。 （由 James Tocknell 在 bpo-23835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23835} 中贡献。）

@item 
一些未写入文档的内部导入已被移除。 一个例子是 @code{os.errno} 已不再可用；应改为直接使用 @code{import errno}。 请注意此类未写入文档的内部导入可能未经通知地随时被移除，甚至是在微版本号发行版中移除。
@end itemize

@node C API 中的改变<2>,CPython 字节码的改变<3>,更改的Python API<2>,移植到 Python 3 7
@anchor{whatsnew/3 7 changes-in-the-c-api}@anchor{5ae}
@subsubsection C API 中的改变


函数 @ref{57f,,PySlice_GetIndicesEx()} 被认为对于大小可变的序列来说并不安全。 如果切片索引不是 @ref{205,,int} 的实例，而是实现了 @code{__index__()} 方法的对象，则序列可以在其长度被传给 @code{PySlice_GetIndicesEx()} 之后调整大小。 这可能导致返回超出序列长度的索引号。 为了避免可能的问题，请使用新增的函数 @ref{53b,,PySlice_Unpack()} 和 @ref{53c,,PySlice_AdjustIndices()}。 （由 Serhiy Storchaka 在 bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867} 中贡献。）

@node CPython 字节码的改变<3>,Windows 专属的改变<2>,C API 中的改变<2>,移植到 Python 3 7
@anchor{whatsnew/3 7 cpython-bytecode-changes}@anchor{5af}
@subsubsection CPython 字节码的改变


新增了两个操作码: @ref{5b0,,LOAD_METHOD} 和 @ref{5b1,,CALL_METHOD}。 （由 Yury Selivanov 和 INADA Naoki 在 bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110} 中贡献。）

@code{STORE_ANNOTATION} 操作码已被移除。 （由 Mark Shannon 在 bpo-32550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32550} 中贡献。）

@node Windows 专属的改变<2>,其他 CPython 实现的改变<2>,CPython 字节码的改变<3>,移植到 Python 3 7
@anchor{whatsnew/3 7 id12}@anchor{5b2}
@subsubsection Windows 专属的改变


用于重载 @ref{262,,sys.path} 的文件现在命名为 @code{<python-executable>._pth} 而不是 @code{'sys.path'}。 请参阅 @ref{5b3,,查找模块} 了解更多信息。 （由 Steve Dower 在 bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137} 中贡献。）

@node 其他 CPython 实现的改变<2>,,Windows 专属的改变<2>,移植到 Python 3 7
@anchor{whatsnew/3 7 id13}@anchor{5b4}
@subsubsection 其他 CPython 实现的改变


为了准备在未来对公开的 CPython 运行时初始化 API 进行潜在更改（请参阅 
@geindex Python 提高建议; PEP 432
PEP 432@footnote{https://www.python.org/dev/peps/pep-0432} 获取最初但略为过时的文稿），CPython 内部的启动和配置管理逻辑已经过大幅重构。 虽然这些更新旨在对嵌入式应用程序和常规的 CPython CLI 用户都完全透明，但它们在这里被提及是因为重构会改变解释器启动期间许多操作的内部顺序，因此可能提示出原先隐藏的缺陷，这可能存在于嵌入式应用程序中，或是在 CPython 自身内部。 （最初由 Nick Coghlan 和 Eric Snow 作为 bpo-22257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22257} 的一部分贡献，并由 Nick, Eric 和 Victor Stinner 在一系列其他问题报告中进一步更新）。 已知会受到影响的一些细节：


@itemize *

@item 
@ref{5b5,,PySys_AddWarnOptionUnicode()} 目前对嵌入式应用程序不可用，因为在调用 @cite{Py_Initialize} 之前需要创建  Unicode 对象。 请改用 @ref{5b6,,PySys_AddWarnOption()}。

@item 
嵌入式应用程序通过 @ref{5b6,,PySys_AddWarnOption()} 所添加的警告过滤器现在应该以更高的一致性优先于由解释器所设置的默认过滤器
@end itemize

由于默认警告过滤器的配置方式发生了变化，将 @ref{5b7,,Py_BytesWarningFlag} 设置为大于一的值不再足以在发出 @ref{5b8,,BytesWarning} 消息的同时将其转换为异常。 而是改为必须设置旗标（以便首先发出警告），以及添加显式的 @code{error::BytesWarning} 警告过滤器来将其转换为异常。

由于编译器处理文档字符串的方式发生了变化，一个仅由文档字符串构成的函数体中隐式的 @code{return None} 现在被标记为在与文档字符串相同的行，而不是在函数的标题行。

当前异常状态已从帧对象移到协程对象。 这会简化解释器并修正由于在进入或退出生成器时具有交换异常状态而导致的一些模糊错误。 （由 Mark Shannon 在 bpo-25612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25612} 中贡献。）

@node Python 3 7 1 中的重要变化,Python 3 7 2 中的重要变化,移植到 Python 3 7,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-1}@anchor{5b9}
@subsection Python 3.7.1 中的重要变化


从 3.7.1 开始，@ref{210,,Py_Initialize()} 现在始终会读取并遵循与 @ref{5ba,,Py_Main()} 相同的环境设置（在更早的 Python 版本中，它会遵循一个错误定义的环境变量子集，而在 Python 3.7.0 中则会由于 bpo-34247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34247} 而完全不读取它们）。 如果不想要此行为，请在调用 @ref{210,,Py_Initialize()} 之前将 @ref{5bb,,Py_IgnoreEnvironmentFlag} 设为 1。

在 3.7.1 中，上下文变量的 C API 已 @ref{5bc,,获得更新} 以使用 @ref{5bd,,PyObject} 指针。 另请参阅 bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762}。

在 3.7.1 中，当提供不带末尾新行的输入时 @ref{11a,,tokenize} 模块现在会隐式地添加 @code{NEWLINE} 形符。 此行为现在已与 C 词法分析器的内部行为相匹配。 （由 Ammar Askar 在 bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899} 中贡献。）

@node Python 3 7 2 中的重要变化,Python 3 7 6 中的重要变化,Python 3 7 1 中的重要变化,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-2}@anchor{5be}
@subsection Python 3.7.2 中的重要变化


在 3.7.2 中，Windows 下的 @ref{12e,,venv} 不再复制原来的二进制文件，而是改为创建名为 @code{python.exe} 和 @code{pythonw.exe} 的重定向脚本。 这解决了一个长期存在的问题，即所有虚拟环境在每次 Python 升级后都必须进行升级或是重新创建。 然而，要注意此发布版仍然要求重新创建虚拟环境以获得新的脚本。

@node Python 3 7 6 中的重要变化,Python 3 7 10 中的重要变化,Python 3 7 2 中的重要变化,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-6}@anchor{5bf}
@subsection Python 3.7.6 中的重要变化


出于重要的安全性考量，@ref{189,,asyncio.loop.create_datagram_endpoint()} 的 @emph{reuse_address} 形参不再被支持。 这是由 UDP 中的套接字选项 @code{SO_REUSEADDR} 的行为导致的。 更多细节请参阅 @code{loop.create_datagram_endpoint()} 的文档。 （由 Kyle Stanley, Antoine Pitrou 和 Yury Selivanov 在 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228} 中贡献。。）

@node Python 3 7 10 中的重要变化,,Python 3 7 6 中的重要变化,Python 3 7 有什么新变化
@anchor{whatsnew/3 7 notable-changes-in-python-3-7-10}@anchor{5c0}
@subsection Python 3.7.10 中的重要变化


早先的 Python 版本允许使用 @code{;} 和 @code{&} 作为 @ref{280,,urllib.parse.parse_qs()} 和 @ref{281,,urllib.parse.parse_qsl()} 中 query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被改为只允许单个分隔键，默认为 @code{&}。 这一改变还会影响 @ref{282,,cgi.parse()} 和 @ref{283,,cgi.parse_multipart()} 因为它们在内部使用了受影响的函数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt, Senthil Kumaran 和 Ken Jin 在 bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967} 中贡献。）

@node Python 3 6 有什么新变化,Python 3 5 有什么新变化,Python 3 7 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 6 doc}@anchor{5c1}@anchor{whatsnew/3 6 what-s-new-in-python-3-6}@anchor{5c2}
@section Python 3.6 有什么新变化


@*编者: 
Elvis Pranskevichus <@email{elvis@@magic.io}>, Yury Selivanov <@email{yury@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

本文解释了与3.5相比，Python 3.6中的新功能。 Python 3.6于2016年12月23日发布。请参阅 changelog@footnote{https://docs.python.org/3.6/whatsnew/changelog.html} 以获取完整的更改列表。


@subsubheading 参见


@geindex Python 提高建议; PEP 494
PEP 494@footnote{https://www.python.org/dev/peps/pep-0494} - Python 3.6发布计划


@menu
* 摘要 - 发布重点: 摘要 - 发布重点<4>. 
* 新的特性: 新的特性<5>. 
* 其他语言特性修改: 其他语言特性修改<4>. 
* 新增模块: 新增模块<4>. 
* 改进的模块: 改进的模块<4>. 
* 性能优化: 性能优化<4>. 
* 构建和 C API 的改变: 构建和 C API 的改变<2>. 
* 其他改进:: 
* 弃用: 弃用<3>. 
* 移除: 移除<3>. 
* 移植到Python 3.6: 移植到Python 3 6. 
* Python 3.6.2 中的重要变化: Python 3 6 2 中的重要变化. 
* Python 3.6.4 中的重要变化: Python 3 6 4 中的重要变化. 
* Python 3.6.5 中的重要变化: Python 3 6 5 中的重要变化. 
* Python 3.6.7 中的重要变化: Python 3 6 7 中的重要变化. 
* Python 3.6.10 中的重要变化: Python 3 6 10 中的重要变化. 
* Notable changes in Python 3.6.13: Notable changes in Python 3 6 13. 

@end menu

@node 摘要 - 发布重点<4>,新的特性<5>,,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 summary-release-highlights}@anchor{5c3}
@subsection 摘要 - 发布重点


新的语法特性：


@itemize *

@item 
@ref{5c4,,PEP 498}, 格式化字符串字面值

@item 
@ref{5c5,,PEP 515}, 数字字面值中的下划线。

@item 
@ref{5c6,,PEP 526} , 变量标注语法。

@item 
@ref{5c7,,PEP 525}, 异步生成器。

@item 
@ref{5c8,,PEP 530}: 异步推导式。
@end itemize

新的库模块：


@itemize *

@item 
@ref{e4,,secrets}: @ref{5c9,,PEP 506 -- Secret模块被加入Python标准库}。
@end itemize

CPython 实现的改进：


@itemize *

@item 
根据 Raymond Hettinger 的提议@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html}  已将 @ref{417,,dict} 类型重新实现为使用 @ref{5ca,,更紧凑的表示形式} 并类似于 PyPy dict implementation@footnote{https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html}。 这使得字典所使用的内存相对于 Python 3.5 版减少了 20% 到 25%。

@item 
类创建的定制过程通过 @ref{5cb,,新协议} 得到了简化。

@item 
类属性的定义顺序 @ref{5cc,,现在会被保留}。

@item 
现在 @code{**kwargs} 中的元素会与传给函数的关键字参数 @ref{5cd,,保持对应顺序}。

@item 
添加了 DTrace 和 SystemTap @ref{5ce,,探测支持}

@item 
新的 @ref{5cf,,PYTHONMALLOC} 环境变量可被用来调试解释器的内存分配和访问错误。
@end itemize

标准库中的重大改进：


@itemize *

@item 
@ref{9,,asyncio} 模块获得了许多新特性，显著的可用性和性能提升，以及大量的问题修正。 从 Python 3.6 开始 @code{asyncio} 模块不再处于待定状态，它已被视为稳定 API。

@item 
实现了新的 @ref{5d0,,文件系统路径协议} 以支持 @ref{47b,,路径类对象}。 所有操作路径的标准库函数已被更新为使用新的协议。

@item 
@ref{30,,datetime} 模块已获得对 @ref{5d1,,本地时间消歧义} 的支持。

@item 
@ref{122,,typing} 模块获得了大量的 @ref{5d2,,改进}。

@item 
@ref{11d,,tracemalloc} 模块已被大幅重写，现在将被用于为 @ref{5d3,,ResourceWarning} 提供更好的输出，并为内存分配错误提供更好的诊断。 请参阅 @ref{5cf,,PYTHONMALLOC 一节} 来了解详情。
@end itemize

安全改进：


@itemize *

@item 
添加了 @ref{e4,,secrets} 模块以简化适用于密码管理的高加密强度伪随机数的生成，例如账户验证、安全凭据等场景。

@item 
在 Linux 上，现在 @ref{5d4,,os.urandom()} 会阻塞直到系统的 urandom 熵池被初始化以提升安全性。 其理由参见 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524}。

@item 
@ref{8c,,hashlib} 和 @ref{f3,,ssl} 模块现在支持 OpenSSL 1.1.0。

@item 
@ref{f3,,ssl} 模块的默认设置和特性集已得到改进。

@item 
@ref{8c,,hashlib} 模块获得了对 BLAKE2, SHA-3 和 SHAKE 哈希算法以及 @ref{5d5,,scrypt()} 密钥派生函数的支持。
@end itemize

Windows改进：


@itemize *

@item 
@ref{5d6,,PEP 528} 和 @ref{5d7,,PEP 529}, 将Windows文件系统和控制台的编码更改为UTF-8

@item 
在交互式地使用 @code{py.exe} 启动器时，当用户未（通过命令行参数或配置文件）指定版本时不再优先选择 Python 2 而是选择 Python 3。 对声明行的处理则保持不变 —— 在这种情况下 "python" 还是指 Python 2。

@item 
@code{python.exe} 和 @code{pythonw.exe} 已被标记为支持长路径，这意味着不再有 260 个字符的路径长度限制。 详情参见 @ref{5d8,,移除 MAX_PATH 限制}。

@item 
可以添加一个 @code{._pth} 文件来强制使用隔离模式和完整指定所有搜索路径来避免注册表和环境查找。 更多信息请参阅 @ref{5b3,,相关文档}。

@item 
现在 @code{python36.zip} 文件可以作为推断 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 的标志。 更多信息请参阅 @ref{5b3,,相关文档}。
@end itemize

@node 新的特性<5>,其他语言特性修改<4>,摘要 - 发布重点<4>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 new-features}@anchor{5da}@anchor{whatsnew/3 6 pypy-dict-implementation}@anchor{5db}
@subsection 新的特性


@menu
* PEP 498; 格式化字符串字面值: PEP 498 格式化字符串字面值. 
* PEP 526; 变量标注的语法: PEP 526 变量标注的语法. 
* PEP 515; 数字字面值中的下划线。: PEP 515 数字字面值中的下划线。. 
* PEP 525; 异步生成器: PEP 525 异步生成器. 
* PEP 530; 异步推导式: PEP 530 异步推导式. 
* PEP 487; 更简单的自定义类创建: PEP 487 更简单的自定义类创建. 
* PEP 487; 描述器协议的增强: PEP 487 描述器协议的增强. 
* PEP 519; 添加文件系统路径协议: PEP 519 添加文件系统路径协议. 
* PEP 495; 消除本地时间的歧义: PEP 495 消除本地时间的歧义. 
* PEP 529; 将Windows文件系统编码更改为UTF-8: PEP 529 将Windows文件系统编码更改为UTF-8. 
* PEP 528; 将Windows控制台编码更改为UTF-8: PEP 528 将Windows控制台编码更改为UTF-8. 
* PEP 520; 保留类属性定义顺序: PEP 520 保留类属性定义顺序. 
* PEP 468; 保留关键字参数顺序: PEP 468 保留关键字参数顺序. 
* 新的 dict 实现:: 
* PEP 523; 向CPython 添加框架评估API: PEP 523 向CPython 添加框架评估API. 
* PYTHONMALLOC 环境变量:: 
* DTrace 和 SystemTap 探测支持:: 

@end menu

@node PEP 498 格式化字符串字面值,PEP 526 变量标注的语法,,新的特性<5>
@anchor{whatsnew/3 6 pep-498-formatted-string-literals}@anchor{5dc}@anchor{whatsnew/3 6 whatsnew36-pep498}@anchor{5c4}
@subsubsection PEP 498: 格式化字符串字面值


@geindex Python 提高建议; PEP 498
PEP 498@footnote{https://www.python.org/dev/peps/pep-0498} 引入了一种新型的字符串字面值: @emph{f-字符串}，或称 @ref{29d,,格式化字符串字面值}。

格式化字符串字面值带有 @code{'f'} 前缀并且类似于 @ref{5dd,,str.format()} 所接受的格式字符串。 其中包含由花括号包围的替换字段。 替换字段属于表达式，它们会在运行时被求值，然后使用 @ref{5de,,format()} 协议进行格式化:

@example
>>> name = "Fred"
>>> f"He said his name is @{name@}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: @{value:@{width@}.@{precision@}@}"  # nested fields
'result:      12.35'
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 498

@item PEP 498@footnote{https://www.python.org/dev/peps/pep-0498} -- 字符串字面值插值。

PEP 由 Eric V. Smith 撰写并实现
@end table

@ref{29d,,特性文档}。


@node PEP 526 变量标注的语法,PEP 515 数字字面值中的下划线。,PEP 498 格式化字符串字面值,新的特性<5>
@anchor{whatsnew/3 6 pep-526-syntax-for-variable-annotations}@anchor{5df}@anchor{whatsnew/3 6 whatsnew36-pep526}@anchor{5c6}
@subsubsection PEP 526: 变量标注的语法


@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 引入了函数形参类型标注即类型提示的标准。 这个 PEP 为 Python 添加了标注变量类型的语法，包括类变量和实例变量:

@example
primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
    stats: Dict[str, int] = @{@}
@end example

与函数标注一样，Python 解释器不会为变量标注附加任何特殊含义，仅会将其保存在类或模块的 @code{__annotations__} 属性中。

与静态类型语法的变量声明不同，标注语法的目的是通过抽象语法树和 @code{__annotations__} 属性提供一个简单方式来为第三方工具和库指定结构化类型元数据。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 526

@item PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} -- 变量标注的语法。

PEP 由 Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, 和 Guido van Rossum 撰写，由 Ivan Levkivskyi 实现。
@end table

使用或将要使用此新语法的工具有: mypy@footnote{http://www.mypy-lang.org/}, pytype@footnote{https://github.com/google/pytype}, PyCharm 等等。


@node PEP 515 数字字面值中的下划线。,PEP 525 异步生成器,PEP 526 变量标注的语法,新的特性<5>
@anchor{whatsnew/3 6 pep-515-underscores-in-numeric-literals}@anchor{5e0}@anchor{whatsnew/3 6 whatsnew36-pep515}@anchor{5c5}
@subsubsection PEP 515: 数字字面值中的下划线。


@geindex Python 提高建议; PEP 515
PEP 515@footnote{https://www.python.org/dev/peps/pep-0515} 增加了在数字字面值中使用下划线的能力以改善可读性。 例如:

@example
>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295
@end example

单个下划线允许用在数码之间和任何数制指示符之后。 一行内不允许有开头、末尾或多个下划线。

@ref{5e1,,字符串格式化} 微语言现在也支持以 @code{'_'} 选项来表示用下划线作为浮点表示类型和整数表示类型 @code{'d'} 的千位分隔符。 对于整数表示类型 @code{'b'}, @code{'o'}, @code{'x'} 和 @code{'X'}，将每隔 4 个数码插入一个下划线:

@example
>>> '@{:_@}'.format(1000000)
'1_000_000'
>>> '@{:_x@}'.format(0xFFFFFFFF)
'ffff_ffff'
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 515

@item PEP 515@footnote{https://www.python.org/dev/peps/pep-0515} -- 数字字面值中的下划线。

PEP 由 Georg Brandl 和 Serhiy Storchaka 撰写
@end table


@node PEP 525 异步生成器,PEP 530 异步推导式,PEP 515 数字字面值中的下划线。,新的特性<5>
@anchor{whatsnew/3 6 pep-525-asynchronous-generators}@anchor{5e2}@anchor{whatsnew/3 6 whatsnew36-pep525}@anchor{5c7}
@subsubsection PEP 525: 异步生成器


@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 将对原生协程和 @code{async} / @code{await} 语法的支持引入到 Python 3.5 中。 但 Python 3.5 实现的一个明显限制是不可能在同一函数体中同时使用 @code{await} 和 @code{yield}。 在 Python 3.6 中此限制已被解除，这样就就能够定义 @emph{异步生成器}:

@example
async def ticker(delay, to):
    """Yield numbers from 0 to *to* every *delay* seconds."""
    for i in range(to):
        yield i
        await asyncio.sleep(delay)
@end example

这个新语法允许更快速且更精简的代码。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 525

@item PEP 525@footnote{https://www.python.org/dev/peps/pep-0525} -- 异步生成器

PEP 由 Yury Selivanov 撰写并实现
@end table


@node PEP 530 异步推导式,PEP 487 更简单的自定义类创建,PEP 525 异步生成器,新的特性<5>
@anchor{whatsnew/3 6 pep-530-asynchronous-comprehensions}@anchor{5e3}@anchor{whatsnew/3 6 whatsnew36-pep530}@anchor{5c8}
@subsubsection PEP 530: 异步推导式


@geindex Python 提高建议; PEP 530
PEP 530@footnote{https://www.python.org/dev/peps/pep-0530} 添加了对在列表、集合与字典推导式和生成器表达式中使用 @code{async for} 的支持:

@example
result = [i async for i in aiter() if i % 2]
@end example

此外，@code{await} 表达式也在所有种类的推导式中得到支持:

@example
result = [await fun() for fun in funcs if await condition()]
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 530

@item PEP 530@footnote{https://www.python.org/dev/peps/pep-0530} -- 异步推导式

PEP 由 Yury Selivanov 撰写并实现
@end table


@node PEP 487 更简单的自定义类创建,PEP 487 描述器协议的增强,PEP 530 异步推导式,新的特性<5>
@anchor{whatsnew/3 6 pep-487-simpler-customization-of-class-creation}@anchor{5e4}@anchor{whatsnew/3 6 whatsnew36-pep487}@anchor{5cb}
@subsubsection PEP 487: 更简单的自定义类创建


现在可以在不使用元类的情况下自定义子类的创建。 当一个新的子类被创建时将在基类上调用新的 @code{__init_subclass__} 类方法:

@example
class PluginBase:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass
@end example

为了让来自 @ref{5e5,,__init_subclass__()} 实现的零参数 @ref{5e6,,super()} 调用能正确工作，自定义元类必须保证新的 @code{__classcell__} 命名空间入口被传播到 @code{type.__new__} (如 @ref{5e7,,创建类对象} 中所描述)。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 487

@item PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} -- 更简单的自定义类创建

PEP 由 Martin Teichmann 撰写并实现。
@end table

@ref{5e8,,特性文档}


@node PEP 487 描述器协议的增强,PEP 519 添加文件系统路径协议,PEP 487 更简单的自定义类创建,新的特性<5>
@anchor{whatsnew/3 6 pep-487-descriptor-protocol-enhancements}@anchor{5e9}@anchor{whatsnew/3 6 whatsnew36-pep487-descriptors}@anchor{5ea}
@subsubsection PEP 487: 描述器协议的增强


@geindex Python 提高建议; PEP 487
PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} 扩展了描述器协议以包括新的可选方法 @ref{5eb,,__set_name__()}。 当创建一个新类时，这个新方法将在定义中包括的所有描述器上被调用，为它们提供对所定义类的引用以及在类命名中间中给予描述器的名称。 换句话说，描述器的实例现在能知道描述器在所有者类中的属性名称:

@example
class IntField:
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError(f'expecting integer in @{self.name@}')
        instance.__dict__[self.name] = value

    # this is the new initializer:
    def __set_name__(self, owner, name):
        self.name = name

class Model:
    int_field = IntField()
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 487

@item PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} -- 更简单的自定义类创建

PEP 由 Martin Teichmann 撰写并实现。
@end table

@ref{5ec,,特性文档}


@node PEP 519 添加文件系统路径协议,PEP 495 消除本地时间的歧义,PEP 487 描述器协议的增强,新的特性<5>
@anchor{whatsnew/3 6 pep-519-adding-a-file-system-path-protocol}@anchor{5ed}@anchor{whatsnew/3 6 whatsnew36-pep519}@anchor{5d0}
@subsubsection PEP 519: 添加文件系统路径协议


File system paths have historically been represented as @ref{206,,str}
or @ref{172,,bytes} objects. This has led to people who write code which
operate on file system paths to assume that such objects are only one
of those two types (an @ref{205,,int} representing a file descriptor
does not count as that is not a file path). Unfortunately that
assumption prevents alternative object representations of file system
paths like @ref{c8,,pathlib} from working with pre-existing code,
including Python's standard library.

To fix this situation, a new interface represented by
@ref{5ee,,os.PathLike} has been defined. By implementing the
@ref{5ef,,__fspath__()} method, an object signals that it
represents a path. An object can then provide a low-level
representation of a file system path as a @ref{206,,str} or
@ref{172,,bytes} object. This means an object is considered
@ref{47b,,path-like} if it implements
@ref{5ee,,os.PathLike} or is a @ref{206,,str} or @ref{172,,bytes} object
which represents a file system path. Code can use @ref{5f0,,os.fspath()},
@ref{5f1,,os.fsdecode()}, or @ref{5f2,,os.fsencode()} to explicitly get a
@ref{206,,str} and/or @ref{172,,bytes} representation of a path-like
object.

The built-in @ref{16f,,open()} function has been updated to accept
@ref{5ee,,os.PathLike} objects, as have all relevant functions in the
@ref{c4,,os} and @ref{c5,,os.path} modules, and most other functions and
classes in the standard library.  The @ref{5f3,,os.DirEntry} class
and relevant classes in @ref{c8,,pathlib} have also been updated to
implement @ref{5ee,,os.PathLike}.

The hope is that updating the fundamental functions for operating
on file system paths will lead to third-party code to implicitly
support all @ref{47b,,path-like objects} without any
code changes, or at least very minimal ones (e.g. calling
@ref{5f0,,os.fspath()} at the beginning of code before operating on a
path-like object).

Here are some examples of how the new interface allows for
@ref{336,,pathlib.Path} to be used more easily and transparently with
pre-existing code:

@example
>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
...     contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'
@end example

（由 Brett Cannon, Ethan Furman, Dusty Phillips 和 Jelle Zijlstra 实现。）


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 519

@item PEP 519@footnote{https://www.python.org/dev/peps/pep-0519} -- 添加文件系统路径协议

PEP 由 Brett Cannon 和 Koos Zevenhoven 撰写。
@end table


@node PEP 495 消除本地时间的歧义,PEP 529 将Windows文件系统编码更改为UTF-8,PEP 519 添加文件系统路径协议,新的特性<5>
@anchor{whatsnew/3 6 pep-495-local-time-disambiguation}@anchor{5f4}@anchor{whatsnew/3 6 whatsnew36-pep495}@anchor{5d1}
@subsubsection PEP 495: 消除本地时间的歧义


In most world locations, there have been and will be times when local clocks
are moved back.  In those times, intervals are introduced in which local
clocks show the same time twice in the same day. In these situations, the
information displayed on a local clock (or stored in a Python datetime
instance) is insufficient to identify a particular moment in time.

@geindex Python 提高建议; PEP 495
PEP 495@footnote{https://www.python.org/dev/peps/pep-0495} adds the new @emph{fold} attribute to instances of
@ref{19f,,datetime.datetime} and @ref{5f5,,datetime.time} classes to differentiate
between two moments in time for which local times are the same:

@example
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
@end example

The values of the @ref{5f6,,fold} attribute have the
value @code{0} for all instances except those that represent the second
(chronologically) moment in time in an ambiguous case.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 495

@item PEP 495@footnote{https://www.python.org/dev/peps/pep-0495} -- 消除本地时间的歧义

PEP 由 Alexander Belopolsky 和 Tim Peters 撰写，由 Alexander Belopolsky 实现。
@end table


@node PEP 529 将Windows文件系统编码更改为UTF-8,PEP 528 将Windows控制台编码更改为UTF-8,PEP 495 消除本地时间的歧义,新的特性<5>
@anchor{whatsnew/3 6 pep-529-change-windows-filesystem-encoding-to-utf-8}@anchor{5f7}@anchor{whatsnew/3 6 whatsnew36-pep529}@anchor{5d7}
@subsubsection PEP 529: 将Windows文件系统编码更改为UTF-8


Representing filesystem paths is best performed with str (Unicode) rather than
bytes. However, there are some situations where using bytes is sufficient and
correct.

Prior to Python 3.6, data loss could result when using bytes paths on Windows.
With this change, using bytes to represent paths is now supported on Windows,
provided those bytes are encoded with the encoding returned by
@ref{5f8,,sys.getfilesystemencoding()}, which now defaults to @code{'utf-8'}.

Applications that do not use str to represent paths should use
@ref{5f2,,os.fsencode()} and @ref{5f1,,os.fsdecode()} to ensure their bytes are
correctly encoded. To revert to the previous behaviour, set
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 环境变量; PYTHONLEGACYWINDOWSFSENCODING
@ref{5f9,,PYTHONLEGACYWINDOWSFSENCODING} or call
@ref{5fa,,sys._enablelegacywindowsfsencoding()}.

有关详细信息和可能需要的代码修改的讨论，请参见 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} 。

@node PEP 528 将Windows控制台编码更改为UTF-8,PEP 520 保留类属性定义顺序,PEP 529 将Windows文件系统编码更改为UTF-8,新的特性<5>
@anchor{whatsnew/3 6 pep-528-change-windows-console-encoding-to-utf-8}@anchor{5fb}@anchor{whatsnew/3 6 whatsnew36-pep528}@anchor{5d6}
@subsubsection PEP 528: 将Windows控制台编码更改为UTF-8


The default console on Windows will now accept all Unicode characters and
provide correctly read str objects to Python code. @code{sys.stdin},
@code{sys.stdout} and @code{sys.stderr} now default to utf-8 encoding.

This change only applies when using an interactive console, and not when
redirecting files or pipes. To revert to the previous behaviour for interactive
console use, set 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 环境变量; PYTHONLEGACYWINDOWSSTDIO
@ref{5fc,,PYTHONLEGACYWINDOWSSTDIO}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 528

@item PEP 528@footnote{https://www.python.org/dev/peps/pep-0528} -- 将Windows控制台编码更改为UTF-8

PEP 由 Steve Dower 撰写并实现。
@end table


@node PEP 520 保留类属性定义顺序,PEP 468 保留关键字参数顺序,PEP 528 将Windows控制台编码更改为UTF-8,新的特性<5>
@anchor{whatsnew/3 6 pep-520-preserving-class-attribute-definition-order}@anchor{5fd}@anchor{whatsnew/3 6 whatsnew36-pep520}@anchor{5cc}
@subsubsection PEP 520: 保留类属性定义顺序


Attributes in a class definition body have a natural ordering: the same
order in which the names appear in the source.  This order is now
preserved in the new class's @ref{5fe,,__dict__} attribute.

Also, the effective default class @emph{execution} namespace (returned from
@ref{5ff,,type.__prepare__()}) is now an insertion-order-preserving
mapping.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 520

@item PEP 520@footnote{https://www.python.org/dev/peps/pep-0520} -- 保留类属性定义顺序

PEP 由 Eric Snow 撰写并实现
@end table


@node PEP 468 保留关键字参数顺序,新的 dict 实现,PEP 520 保留类属性定义顺序,新的特性<5>
@anchor{whatsnew/3 6 pep-468-preserving-keyword-argument-order}@anchor{600}@anchor{whatsnew/3 6 whatsnew36-pep468}@anchor{5cd}
@subsubsection PEP 468: 保留关键字参数顺序


@code{**kwargs} in a function signature is now guaranteed to be an
insertion-order-preserving mapping.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 468

@item PEP 468@footnote{https://www.python.org/dev/peps/pep-0468} -- 保留关键字参数顺序

PEP 由 Eric Snow 撰写并实现
@end table


@node 新的 dict 实现,PEP 523 向CPython 添加框架评估API,PEP 468 保留关键字参数顺序,新的特性<5>
@anchor{whatsnew/3 6 new-dict-implementation}@anchor{601}@anchor{whatsnew/3 6 whatsnew36-compactdict}@anchor{5ca}
@subsubsection 新的 dict 实现


The @ref{417,,dict} type now uses a "compact" representation
based on a proposal by Raymond Hettinger@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html}
which was first implemented by PyPy@footnote{https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html}.
The memory usage of the new @ref{164,,dict()} is between 20% and 25% smaller
compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an
implementation detail and should not be relied upon (this may change in
the future, but it is desired to have this new dict implementation in
the language for a few releases before changing the language spec to mandate
order-preserving semantics for all current and future Python
implementations; this also helps preserve backwards-compatibility
with older versions of the language where random iteration order is
still in effect, e.g. Python 3.5).

(Contributed by INADA Naoki in bpo-27350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27350}. Idea
originally suggested by Raymond Hettinger@footnote{https://mail.python.org/pipermail/python-dev/2012-December/123028.html}.)

@node PEP 523 向CPython 添加框架评估API,PYTHONMALLOC 环境变量,新的 dict 实现,新的特性<5>
@anchor{whatsnew/3 6 pep-523-adding-a-frame-evaluation-api-to-cpython}@anchor{602}@anchor{whatsnew/3 6 whatsnew36-pep523}@anchor{603}
@subsubsection PEP 523: 向CPython 添加框架评估API


While Python provides extensive support to customize how code
executes, one place it has not done so is in the evaluation of frame
objects.  If you wanted some way to intercept frame evaluation in
Python there really wasn't any way without directly manipulating
function pointers for defined functions.

@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} changes this by providing an API to make frame
evaluation pluggable at the C level. This will allow for tools such
as debuggers and JITs to intercept frame evaluation before the
execution of Python code begins. This enables the use of alternative
evaluation implementations for Python code, tracking frame
evaluation, etc.

This API is not part of the limited C API and is marked as private to
signal that usage of this API is expected to be limited and only
applicable to very select, low-level use-cases. Semantics of the
API will change with Python as necessary.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 523

@item PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} -- 向CPython 添加框架评估API

PEP 由 Brett Cannon 和 Dino Viehland 撰写。
@end table


@node PYTHONMALLOC 环境变量,DTrace 和 SystemTap 探测支持,PEP 523 向CPython 添加框架评估API,新的特性<5>
@anchor{whatsnew/3 6 pythonmalloc-environment-variable}@anchor{604}@anchor{whatsnew/3 6 whatsnew36-pythonmalloc}@anchor{5cf}
@subsubsection PYTHONMALLOC 环境变量


新的 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 环境变量允许设置 Python 内存分配器并安装调试钩子。

现在将可以使用 @code{PYTHONMALLOC=debug} 在以发布模式编译的 Python 上为 Python 内存分配器安装调试钩子。 调试钩子的效果:


@itemize *

@item 
新分配的内存中填充字节 @code{0xCB}

@item 
释放的内存中填充了字节 @code{0xDB}

@item 
检测违反 Python 内存分配器 API 的操作。 例如，@ref{606,,PyObject_Free()} 在 @ref{607,,PyMem_Malloc()} 所分配的内存块上被调用。

@item 
在缓冲区开始之前检测写操作（缓冲区下溢）

@item 
在缓冲区结束后检测写操作（缓冲区溢出）

@item 
检测当调用 @ref{608,,PYMEM_DOMAIN_OBJ} (如: @ref{609,,PyObject_Malloc()}) 和 @ref{60a,,PYMEM_DOMAIN_MEM} (如: @ref{607,,PyMem_Malloc()}) 域的分配器函数时 @ref{60b,,GIL} 已被持有。
@end itemize

检查是否保留了 GIL 也是Python 3.6 的新特性。

请参阅 @ref{60c,,PyMem_SetupDebugHooks()} 函数来了解 Python 内存分配器上的调试钩子。

现在还可以使用 @code{PYTHONMALLOC=malloc} 为所有的 Python 内存分配强制使用 C 库的 @code{malloc()} 分配器。 这在以发布模式编译的 Python 上使用外部内存调试器如 Valgrind 时会很有用处。

发生错误时，Python 内存分配器上的调试钩子现在会使用 @ref{11d,,tracemalloc} 模块来获取内存块被分配所在位置上的回溯。

使用 @code{python3.6 -X tracemalloc=5} (在回溯中存储 5 帧) 的缓冲区溢出的致命错误示例:

@example
Debug memory block at address p=0x7fbcd41666f8: API 'o'
    4 bytes originally requested
    The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
    The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
        at tail+0: 0x02 *** OUCH
        at tail+1: 0xfb
        at tail+2: 0xfb
        at tail+3: 0xfb
        at tail+4: 0xfb
        at tail+5: 0xfb
        at tail+6: 0xfb
        at tail+7: 0xfb
    The block was made by call #1233329 to debug malloc/realloc.
    Data at p: 1a 2b 30 00

Memory block allocated at (most recent call first):
  File "test/test_bytes.py", line 323
  File "unittest/case.py", line 600
  File "unittest/case.py", line 648
  File "unittest/suite.py", line 122
  File "unittest/suite.py", line 84

Fatal Python error: bad trailing pad byte

Current thread 0x00007fbcdbd32700 (most recent call first):
  File "test/test_bytes.py", line 323 in test_hex
  File "unittest/case.py", line 600 in run
  File "unittest/case.py", line 648 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  ...
@end example

（由 Victor Stinner 在 bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516} 和 bpo-26564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26564} 中贡献。）

@node DTrace 和 SystemTap 探测支持,,PYTHONMALLOC 环境变量,新的特性<5>
@anchor{whatsnew/3 6 dtrace-and-systemtap-probing-support}@anchor{60d}@anchor{whatsnew/3 6 whatsnew36-tracing}@anchor{5ce}
@subsubsection DTrace 和 SystemTap 探测支持


Python 现在可以附带 @code{--with-dtrace} 来构建以便为解释器中的下列事件启用静态标记:


@itemize *

@item 
函数调用/返回

@item 
垃圾收集开始/完成

@item 
执行的代码行。
@end itemize

This can be used to instrument running interpreters in production,
without the need to recompile specific debug builds or providing
application-specific profiling/debugging code.

更多信息，请参见 @ref{60e,,使用 DTrace 和 SystemTap 检测CPython} 。

当前的实现已在 Linux 和 macOS 上进行了测试。将来可能会添加其他标记。

（由 Łukasz Langa 在 bpo-21590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21590} 中贡献，基于 Jesús Cea Avión, David Malcolm 和 Nikhil Benesch 的补丁。）

@node 其他语言特性修改<4>,新增模块<4>,新的特性<5>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 other-language-changes}@anchor{60f}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
A @code{global} or @code{nonlocal} statement must now textually appear
before the first use of the affected name in the same scope.
Previously this was a @ref{2d0,,SyntaxWarning}.

@item 
It is now possible to set a @ref{610,,special method} to
@code{None} to indicate that the corresponding operation is not available.
For example, if a class sets @ref{611,,__iter__()} to @code{None}, the class
is not iterable.
(Contributed by Andrew Barnert and Ivan Levkivskyi in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}.)

@item 
Long sequences of repeated traceback lines are now abbreviated as
@code{"[Previous line repeated @{count@} more times]"} (see
@ref{612,,traceback} for an example).
(Contributed by Emanuel Barry in bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}.)

@item 
Import now raises the new exception @ref{4a9,,ModuleNotFoundError}
(subclass of @ref{16c,,ImportError}) when it cannot find a module.  Code
that currently checks for ImportError (in try-except) will still work.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@item 
Class methods relying on zero-argument @code{super()} will now work correctly
when called from metaclass methods during class creation.
(Contributed by Martin Teichmann in bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}.)
@end itemize

@node 新增模块<4>,改进的模块<4>,其他语言特性修改<4>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 new-modules}@anchor{613}
@subsection 新增模块


@menu
* secrets:: 

@end menu

@node secrets,,,新增模块<4>
@anchor{whatsnew/3 6 secrets}@anchor{614}@anchor{whatsnew/3 6 whatsnew36-pep506}@anchor{5c9}
@subsubsection secrets


The main purpose of the new @ref{e4,,secrets} module is to provide an obvious way
to reliably generate cryptographically strong pseudo-random values suitable
for managing secrets, such as account authentication, tokens, and similar.

@cartouche
@quotation 警告 
Note that the pseudo-random generators in the @ref{dc,,random} module
should @emph{NOT} be used for security purposes.  Use @ref{e4,,secrets}
on Python 3.6+ and @ref{5d4,,os.urandom()} on Python 3.5 and earlier.
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 506

@item PEP 506@footnote{https://www.python.org/dev/peps/pep-0506} -- Secrets模块被加入Python标准库

PEP 由 Steven D'Aprano 撰写并实现。
@end table


@node 改进的模块<4>,性能优化<4>,新增模块<4>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 improved-modules}@anchor{615}
@subsection 改进的模块


@menu
* array:: 
* ast: ast<3>. 
* asyncio: asyncio<5>. 
* binascii: binascii<2>. 
* cmath:: 
* collections: collections<4>. 
* concurrent.futures: concurrent futures<3>. 
* contextlib: contextlib<2>. 
* datetime: datetime<4>. 
* decimal: decimal<2>. 
* distutils: distutils<3>. 
* email:: 
* encodings:: 
* enum: enum<3>. 
* faulthandler:: 
* fileinput:: 
* hashlib: hashlib<2>. 
* http.client: http client<2>. 
* idlelib 与 IDLE: idlelib 与 IDLE<2>. 
* importlib: importlib<4>. 
* inspect: inspect<3>. 
* json:: 
* logging: logging<3>. 
* math: math<4>. 
* multiprocessing: multiprocessing<4>. 
* os: os<4>. 
* pathlib: pathlib<4>. 
* pdb: pdb<3>. 
* pickle: pickle<2>. 
* pickletools:: 
* pydoc: pydoc<3>. 
* random: random<2>. 
* re: re<2>. 
* readline:: 
* rlcompleter:: 
* shlex: shlex<2>. 
* site:: 
* sqlite3: sqlite3<2>. 
* socket: socket<5>. 
* socketserver: socketserver<2>. 
* ssl: ssl<4>. 
* statistics: statistics<2>. 
* struct:: 
* subprocess: subprocess<2>. 
* sys: sys<5>. 
* telnetlib:: 
* time: time<4>. 
* timeit:: 
* tkinter: tkinter<3>. 
* traceback:: 
* tracemalloc: tracemalloc<3>. 
* typing: typing<4>. 
* unicodedata: unicodedata<4>. 
* unittest.mock: unittest mock<2>. 
* urllib.request: urllib request. 
* urllib.robotparser: urllib robotparser. 
* venv: venv<3>. 
* warnings: warnings<2>. 
* winreg:: 
* winsound:: 
* xmlrpc.client: xmlrpc client. 
* zipfile: zipfile<2>. 
* zlib:: 

@end menu

@node array,ast<3>,,改进的模块<4>
@anchor{whatsnew/3 6 array}@anchor{616}
@subsubsection array


Exhausted iterators of @ref{217,,array.array} will now stay exhausted even
if the iterated array is extended.  This is consistent with the behavior
of other mutable sequences.

由 Serhiy Storchaka 在 bpo-26492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26492} 中贡献。

@node ast<3>,asyncio<5>,array,改进的模块<4>
@anchor{whatsnew/3 6 ast}@anchor{617}
@subsubsection ast


The new @ref{3ae,,ast.Constant} AST node has been added.  It can be used
by external AST optimizers for the purposes of constant folding.

由 Victor Stinner 在 bpo-26146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26146} 中贡献。

@node asyncio<5>,binascii<2>,ast<3>,改进的模块<4>
@anchor{whatsnew/3 6 asyncio}@anchor{618}
@subsubsection asyncio


Starting with Python 3.6 the @code{asyncio} module is no longer provisional and its
API is considered stable.

Notable changes in the @ref{9,,asyncio} module since Python 3.5.0
(all backported to 3.5.x due to the provisional status):


@itemize *

@item 
The @ref{466,,get_event_loop()} function has been changed to
always return the currently running loop when called from coroutines
and callbacks.
(Contributed by Yury Selivanov in bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}.)

@item 
The @ref{619,,ensure_future()} function and all functions that
use it, such as @ref{61a,,loop.run_until_complete()},
now accept all kinds of @ref{61b,,awaitable objects}.
(Contributed by Yury Selivanov.)

@item 
新增 @ref{61c,,run_coroutine_threadsafe()} 函数用于从其他线程向事件循环提交协程。（由 Vincent Michel 贡献。）

@item 
新增 @ref{61d,,Transport.is_closing()} 方法用于检查传输是否正在关闭或已经关闭。 （由 Yury Selivanov 贡献。）

@item 
@ref{46e,,loop.create_server()} 方法现在可以接受一个主机列表。 （由 Yann Sionneau 贡献。）

@item 
New @ref{61e,,loop.create_future()}
method to create Future objects.  This allows alternative event
loop implementations, such as
uvloop@footnote{https://github.com/MagicStack/uvloop}, to provide a faster
@ref{54e,,asyncio.Future} implementation.
(Contributed by Yury Selivanov in bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}.)

@item 
New @ref{61f,,loop.get_exception_handler()}
method to get the current exception handler.
(Contributed by Yury Selivanov in bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}.)

@item 
New @ref{620,,StreamReader.readuntil()}
method to read data from the stream until a separator bytes
sequence appears.
(Contributed by Mark Korenberg.)

@item 
The performance of @ref{621,,StreamReader.readexactly()}
has been improved.
(Contributed by Mark Korenberg in bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}.)

@item 
The @ref{5a4,,loop.getaddrinfo()}
method is optimized to avoid calling the system @code{getaddrinfo}
function if the address is already resolved.
(Contributed by A. Jesse Jiryu Davis.)

@item 
The @ref{622,,loop.stop()}
method has been changed to stop the loop immediately after
the current iteration.  Any new callbacks scheduled as a result
of the last iteration will be discarded.
(Contributed by Guido van Rossum in bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}.)

@item 
@code{Future.set_exception}
will now raise @ref{1ff,,TypeError} when passed an instance of
the @ref{58a,,StopIteration} exception.
(Contributed by Chris Angelico in bpo-26221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26221}.)

@item 
New @ref{476,,loop.connect_accepted_socket()}
method to be used by servers that accept connections outside of asyncio,
but that use asyncio to handle them.
(Contributed by Jim Fulton in bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}.)

@item 
@code{TCP_NODELAY} flag is now set for all TCP transports by default.
(Contributed by Yury Selivanov in bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}.)

@item 
New @ref{623,,loop.shutdown_asyncgens()}
to properly close pending asynchronous generators before closing the
loop.
(Contributed by Yury Selivanov in bpo-28003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28003}.)

@item 
@ref{54e,,Future} and @ref{2e7,,Task}
classes now have an optimized C implementation which makes asyncio
code up to 30% faster.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}
and bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}.)
@end itemize

@node binascii<2>,cmath,asyncio<5>,改进的模块<4>
@anchor{whatsnew/3 6 binascii}@anchor{624}
@subsubsection binascii


The @ref{625,,b2a_base64()} function now accepts an optional @emph{newline}
keyword argument to control whether the newline character is appended to the
return value.
(Contributed by Victor Stinner in bpo-25357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25357}.)

@node cmath,collections<4>,binascii<2>,改进的模块<4>
@anchor{whatsnew/3 6 cmath}@anchor{626}
@subsubsection cmath


The new @ref{627,,cmath.tau} (@emph{τ}) constant has been added.
(Contributed by Lisa Roach in bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}, see 
@geindex Python 提高建议; PEP 628
PEP 628@footnote{https://www.python.org/dev/peps/pep-0628} for details.)

New constants: @ref{628,,cmath.inf} and @ref{629,,cmath.nan} to
match @ref{62a,,math.inf} and @ref{62b,,math.nan}, and also @ref{62c,,cmath.infj}
and @ref{62d,,cmath.nanj} to match the format used by complex repr.
(Contributed by Mark Dickinson in bpo-23229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23229}.)

@node collections<4>,concurrent futures<3>,cmath,改进的模块<4>
@anchor{whatsnew/3 6 collections}@anchor{62e}
@subsubsection collections


The new @ref{62f,,Collection} abstract base class has been
added to represent sized iterable container classes.
(Contributed by Ivan Levkivskyi, docs by Neil Girdhar in bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}.)

The new @ref{630,,Reversible} abstract base class represents
iterable classes that also provide the @ref{631,,__reversed__()} method.
(Contributed by Ivan Levkivskyi in bpo-25987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25987}.)

新增代表异步生成器的 @ref{632,,AsyncGenerator} 抽象基类。 （由 Yury Selivanov 在 bpo-28720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28720} 中贡献。）

The @ref{1a1,,namedtuple()} function now accepts an optional
keyword argument @emph{module}, which, when specified, is used for
the @code{__module__} attribute of the returned named tuple class.
(Contributed by Raymond Hettinger in bpo-17941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17941}.)

The @emph{verbose} and @emph{rename} arguments for
@ref{1a1,,namedtuple()} are now keyword-only.
(Contributed by Raymond Hettinger in bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}.)

Recursive @ref{633,,collections.deque} instances can now be pickled.
(Contributed by Serhiy Storchaka in bpo-26482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26482}.)

@node concurrent futures<3>,contextlib<2>,collections<4>,改进的模块<4>
@anchor{whatsnew/3 6 concurrent-futures}@anchor{634}
@subsubsection concurrent.futures


The @ref{18c,,ThreadPoolExecutor}
class constructor now accepts an optional @emph{thread_name_prefix} argument
to make it possible to customize the names of the threads created by the
pool.
(Contributed by Gregory P. Smith in bpo-27664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27664}.)

@node contextlib<2>,datetime<4>,concurrent futures<3>,改进的模块<4>
@anchor{whatsnew/3 6 contextlib}@anchor{635}
@subsubsection contextlib


The @ref{636,,contextlib.AbstractContextManager} class has been added to
provide an abstract base class for context managers.  It provides a
sensible default implementation for @cite{__enter__()} which returns
@code{self} and leaves @cite{__exit__()} an abstract method.  A matching
class has been added to the @ref{122,,typing} module as
@ref{637,,typing.ContextManager}.
(Contributed by Brett Cannon in bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}.)

@node datetime<4>,decimal<2>,contextlib<2>,改进的模块<4>
@anchor{whatsnew/3 6 datetime}@anchor{638}
@subsubsection datetime


The @ref{19f,,datetime} and @ref{5f5,,time} classes have
the new @code{fold} attribute used to disambiguate local time
when necessary.  Many functions in the @ref{30,,datetime} have been
updated to support local time disambiguation.
See @ref{5d1,,Local Time Disambiguation} section for more
information.
(Contributed by Alexander Belopolsky in bpo-24773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24773}.)

The @ref{639,,datetime.strftime()} and
@ref{63a,,date.strftime()} methods now support
ISO 8601 date directives @code{%G}, @code{%u} and @code{%V}.
(Contributed by Ashley Anderson in bpo-12006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12006}.)

The @ref{63b,,datetime.isoformat()} function
now accepts an optional @emph{timespec} argument that specifies the number
of additional components of the time value to include.
(Contributed by Alessandro Cucci and Alexander Belopolsky in bpo-19475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19475}.)

The @ref{63c,,datetime.combine()} now
accepts an optional @emph{tzinfo} argument.
(Contributed by Alexander Belopolsky in bpo-27661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27661}.)

@node decimal<2>,distutils<3>,datetime<4>,改进的模块<4>
@anchor{whatsnew/3 6 decimal}@anchor{63d}
@subsubsection decimal


New @ref{63e,,Decimal.as_integer_ratio()}
method that returns a pair @code{(n, d)} of integers that represent the given
@ref{2c7,,Decimal} instance as a fraction, in lowest terms and
with a positive denominator:

@example
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
@end example

（由 Stefan Krah 和 Mark Dickinson  在 bpo-25928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25928} 中贡献。）

@node distutils<3>,email,decimal<2>,改进的模块<4>
@anchor{whatsnew/3 6 distutils}@anchor{63f}
@subsubsection distutils


The @code{default_format} attribute has been removed from
@code{distutils.command.sdist.sdist} and the @code{formats}
attribute defaults to @code{['gztar']}. Although not anticipated,
any code relying on the presence of @code{default_format} may
need to be adapted. See bpo-27819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27819} for more details.

@node email,encodings,distutils<3>,改进的模块<4>
@anchor{whatsnew/3 6 email}@anchor{640}
@subsubsection email


The new email API, enabled via the @emph{policy} keyword to various constructors, is
no longer provisional.  The @ref{67,,email} documentation has been reorganized and
rewritten to focus on the new API, while retaining the old documentation for
the legacy API.  (Contributed by R. David Murray in bpo-24277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24277}.)

The @ref{71,,email.mime} classes now all accept an optional @emph{policy} keyword.
(Contributed by Berker Peksag in bpo-27331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27331}.)

@ref{641,,DecodedGenerator} 现在支持 @emph{policy} 关键字。

There is a new @ref{73,,policy} attribute,
@ref{642,,message_factory}, that controls what class is used
by default when the parser creates new message objects.  For the
@ref{643,,email.policy.compat32} policy this is @ref{644,,Message},
for the new policies it is @ref{645,,EmailMessage}.
(Contributed by R. David Murray in bpo-20476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20476}.)

@node encodings,enum<3>,email,改进的模块<4>
@anchor{whatsnew/3 6 encodings}@anchor{646}
@subsubsection encodings


On Windows, added the @code{'oem'} encoding to use @code{CP_OEMCP}, and the @code{'ansi'}
alias for the existing @code{'mbcs'} encoding, which uses the @code{CP_ACP} code page.
(Contributed by Steve Dower in bpo-27959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27959}.)

@node enum<3>,faulthandler,encodings,改进的模块<4>
@anchor{whatsnew/3 6 enum}@anchor{647}
@subsubsection enum


Two new enumeration base classes have been added to the @ref{79,,enum} module:
@ref{648,,Flag} and @code{IntFlags}.  Both are used to define
constants that can be combined using the bitwise operators.
(Contributed by Ethan Furman in bpo-23591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23591}.)

Many standard library modules have been updated to use the
@code{IntFlags} class for their constants.

The new @ref{649,,enum.auto} value can be used to assign values to enum
members automatically:

@example
>>> from enum import Enum, auto
>>> class Color(Enum):
...     red = auto()
...     blue = auto()
...     green = auto()
...
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
@end example

@node faulthandler,fileinput,enum<3>,改进的模块<4>
@anchor{whatsnew/3 6 faulthandler}@anchor{64a}
@subsubsection faulthandler


On Windows, the @ref{7b,,faulthandler} module now installs a handler for Windows
exceptions: see @ref{64b,,faulthandler.enable()}. (Contributed by Victor Stinner in
bpo-23848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23848}.)

@node fileinput,hashlib<2>,faulthandler,改进的模块<4>
@anchor{whatsnew/3 6 fileinput}@anchor{64c}
@subsubsection fileinput


@ref{64d,,hook_encoded()} 现在支持 @emph{errors} 参数。 （由 Joseph Hackman 在 bpo-25788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25788} 中贡献。）

@node hashlib<2>,http client<2>,fileinput,改进的模块<4>
@anchor{whatsnew/3 6 hashlib}@anchor{64e}
@subsubsection hashlib


@ref{8c,,hashlib} supports OpenSSL 1.1.0.  The minimum recommend version is 1.0.2.
(Contributed by Christian Heimes in bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

BLAKE2 hash functions were added to the module. @ref{64f,,blake2b()}
and @ref{650,,blake2s()} are always available and support the full
feature set of BLAKE2.
(Contributed by Christian Heimes in bpo-26798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26798} based on code by
Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)

The SHA-3 hash functions @code{sha3_224()}, @code{sha3_256()},
@code{sha3_384()}, @code{sha3_512()}, and SHAKE hash functions
@code{shake_128()} and @code{shake_256()} were added.
(Contributed by Christian Heimes in bpo-16113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16113}. Keccak Code Package
by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and
Ronny Van Keer.)

The password-based key derivation function @ref{5d5,,scrypt()} is now
available with OpenSSL 1.1.0 and newer.
(Contributed by Christian Heimes in bpo-27928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27928}.)

@node http client<2>,idlelib 与 IDLE<2>,hashlib<2>,改进的模块<4>
@anchor{whatsnew/3 6 http-client}@anchor{651}
@subsubsection http.client


@ref{652,,HTTPConnection.request()} and
@ref{653,,endheaders()} both now support
chunked encoding request bodies.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@node idlelib 与 IDLE<2>,importlib<4>,http client<2>,改进的模块<4>
@anchor{whatsnew/3 6 idlelib-and-idle}@anchor{654}
@subsubsection idlelib 与 IDLE


The idlelib package is being modernized and refactored to make IDLE look and
work better and to make the code easier to understand, test, and improve. Part
of making IDLE look better, especially on Linux and Mac, is using ttk widgets,
mostly in the dialogs.  As a result, IDLE no longer runs with tcl/tk 8.4.  It
now requires tcl/tk 8.5 or 8.6.  We recommend running the latest release of
either.

'Modernizing' includes renaming and consolidation of idlelib modules. The
renaming of files with partial uppercase names is similar to the renaming of,
for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0.  As a
result, imports of idlelib files that worked in 3.5 will usually not work in
3.6.  At least a module name change will be needed (see idlelib/README.txt),
sometimes more.  (Name changes contributed by Al Swiegart and Terry Reedy in
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}.  Most idlelib patches since have been and will be part of the
process.)

In compensation, the eventual result with be that some idlelib classes will be
easier to use, with better APIs and docstrings explaining them.  Additional
useful information will be added to idlelib when available.

在 3.6.2 中新增:

多个对自动补全的修正。 （由 Louie Lu 在 bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786} 中贡献。）

在 3.6.3 中新增:

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和 Terry Jan Reedy 在 bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262} 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从 Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry Jan Reedy 在 bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099} 中实现。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

在 3.6.4 中新增:

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （由 Terry Jan Reedy 在 bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802} 中贡献。） 样本可以被修改以包括其他字符。 （由 Serhiy Storchaka 在 bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860} 中贡献。）

在 3.6.6 中新增:

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到 Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan Reedy 在 bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}, bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768} 和 bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679} 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在 Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成影响。 （由 Terry Jan Reedy 在 bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656} 中贡献。）

在 3.6.7 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353} 中贡献。）

@node importlib<4>,inspect<3>,idlelib 与 IDLE<2>,改进的模块<4>
@anchor{whatsnew/3 6 importlib}@anchor{655}
@subsubsection importlib


Import now raises the new exception @ref{4a9,,ModuleNotFoundError}
(subclass of @ref{16c,,ImportError}) when it cannot find a module.  Code
that current checks for @code{ImportError} (in try-except) will still work.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@ref{656,,importlib.util.LazyLoader} now calls
@ref{657,,create_module()} on the wrapped loader, removing the
restriction that @ref{658,,importlib.machinery.BuiltinImporter} and
@ref{659,,importlib.machinery.ExtensionFileLoader} couldn't be used with
@ref{656,,importlib.util.LazyLoader}.

@ref{65a,,importlib.util.cache_from_source()},
@ref{65b,,importlib.util.source_from_cache()}, and
@ref{65c,,importlib.util.spec_from_file_location()} now accept a
@ref{47b,,path-like object}.

@node inspect<3>,json,importlib<4>,改进的模块<4>
@anchor{whatsnew/3 6 inspect}@anchor{65d}
@subsubsection inspect


The @ref{65e,,inspect.signature()} function now reports the
implicit @code{.0} parameters generated by the compiler for comprehension and
generator expression scopes as if they were positional-only parameters called
@code{implicit0}. (Contributed by Jelle Zijlstra in bpo-19611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19611}.)

To reduce code churn when upgrading from Python 2.7 and the legacy
@ref{65f,,inspect.getargspec()} API, the previously documented deprecation of
@ref{660,,inspect.getfullargspec()} has been reversed. While this function is
convenient for single/source Python 2/3 code bases, the richer
@ref{65e,,inspect.signature()} interface remains the recommended approach for new
code. (Contributed by Nick Coghlan in bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172})

@node json,logging<3>,inspect<3>,改进的模块<4>
@anchor{whatsnew/3 6 json}@anchor{661}
@subsubsection json


@ref{662,,json.load()} and @ref{226,,json.loads()} now support binary input.  Encoded
JSON should be represented using either UTF-8, UTF-16, or UTF-32.
(Contributed by Serhiy Storchaka in bpo-17909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17909}.)

@node logging<3>,math<4>,json,改进的模块<4>
@anchor{whatsnew/3 6 logging}@anchor{663}
@subsubsection logging


The new @ref{664,,WatchedFileHandler.reopenIfNeeded()}
method has been added to add the ability to check if the log file needs to
be reopened.
(Contributed by Marian Horban in bpo-24884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24884}.)

@node math<4>,multiprocessing<4>,logging<3>,改进的模块<4>
@anchor{whatsnew/3 6 math}@anchor{665}
@subsubsection math


The tau (@emph{τ}) constant has been added to the @ref{b1,,math} and @ref{18,,cmath}
modules.
(Contributed by Lisa Roach in bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}, see 
@geindex Python 提高建议; PEP 628
PEP 628@footnote{https://www.python.org/dev/peps/pep-0628} for details.)

@node multiprocessing<4>,os<4>,math<4>,改进的模块<4>
@anchor{whatsnew/3 6 multiprocessing}@anchor{666}
@subsubsection multiprocessing


@ref{667,,Proxy Objects} returned by
@ref{668,,multiprocessing.Manager()} can now be nested.
(Contributed by Davin Potts in bpo-6766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6766}.)

@node os<4>,pathlib<4>,multiprocessing<4>,改进的模块<4>
@anchor{whatsnew/3 6 os}@anchor{669}
@subsubsection os


See the summary of @ref{5d0,,PEP 519} for details on how the
@ref{c4,,os} and @ref{c5,,os.path} modules now support
@ref{47b,,path-like objects}.

@ref{390,,scandir()} now supports @ref{172,,bytes} paths on Windows.

A new @ref{66a,,close()} method allows explicitly closing a
@ref{390,,scandir()} iterator.  The @ref{390,,scandir()} iterator now
supports the @ref{66b,,context manager} protocol.  If a @code{scandir()}
iterator is neither exhausted nor explicitly closed a @ref{5d3,,ResourceWarning}
will be emitted in its destructor.
(Contributed by Serhiy Storchaka in bpo-25994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25994}.)

在 Linux 上，现在 @ref{5d4,,os.urandom()} 会阻塞直到系统的 urandom 熵池被初始化以提升安全性。 其理由参见 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524}。

The Linux @code{getrandom()} syscall (get random bytes) is now exposed as the new
@ref{66c,,os.getrandom()} function.
(Contributed by Victor Stinner, part of the 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524})

@node pathlib<4>,pdb<3>,os<4>,改进的模块<4>
@anchor{whatsnew/3 6 pathlib}@anchor{66d}
@subsubsection pathlib


@ref{c8,,pathlib} now supports @ref{47b,,path-like objects}.
(Contributed by Brett Cannon in bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}.)

See the summary of @ref{5d0,,PEP 519} for details.

@node pdb<3>,pickle<2>,pathlib<4>,改进的模块<4>
@anchor{whatsnew/3 6 pdb}@anchor{66e}
@subsubsection pdb


The @ref{1d4,,Pdb} class constructor has a new optional @emph{readrc} argument
to control whether @code{.pdbrc} files should be read.

@node pickle<2>,pickletools,pdb<3>,改进的模块<4>
@anchor{whatsnew/3 6 pickle}@anchor{66f}
@subsubsection pickle


Objects that need @code{__new__} called with keyword arguments can now be pickled
using @ref{670,,pickle protocols} older than protocol version 4.
Protocol version 4 already supports this case.  (Contributed by Serhiy
Storchaka in bpo-24164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24164}.)

@node pickletools,pydoc<3>,pickle<2>,改进的模块<4>
@anchor{whatsnew/3 6 pickletools}@anchor{671}
@subsubsection pickletools


@ref{672,,pickletools.dis()} now outputs the implicit memo index for the
@code{MEMOIZE} opcode.
(Contributed by Serhiy Storchaka in bpo-25382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25382}.)

@node pydoc<3>,random<2>,pickletools,改进的模块<4>
@anchor{whatsnew/3 6 pydoc}@anchor{673}
@subsubsection pydoc


The @ref{d9,,pydoc} module has learned to respect the @code{MANPAGER}
environment variable.
(Contributed by Matthias Klose in bpo-8637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8637}.)

@ref{175,,help()} and @ref{d9,,pydoc} can now list named tuple fields in the
order they were defined rather than alphabetically.
(Contributed by Raymond Hettinger in bpo-24879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24879}.)

@node random<2>,re<2>,pydoc<3>,改进的模块<4>
@anchor{whatsnew/3 6 random}@anchor{674}
@subsubsection random


The new @ref{675,,choices()} function returns a list of elements of
specified size from the given population with optional weights.
(Contributed by Raymond Hettinger in bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}.)

@node re<2>,readline,random<2>,改进的模块<4>
@anchor{whatsnew/3 6 re}@anchor{676}
@subsubsection re


Added support of modifier spans in regular expressions.  Examples:
@code{'(?i:p)ython'} matches @code{'python'} and @code{'Python'}, but not @code{'PYTHON'};
@code{'(?i)g(?-i:v)r'} matches @code{'GvR'} and @code{'gvr'}, but not @code{'GVR'}.
(Contributed by Serhiy Storchaka in bpo-433028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433028}.)

Match object groups can be accessed by @code{__getitem__}, which is
equivalent to @code{group()}.  So @code{mo['name']} is now equivalent to
@code{mo.group('name')}.  (Contributed by Eric Smith in bpo-24454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24454}.)

@code{Match} objects now support
@ref{2c9,,index-like objects} as group
indices.
(Contributed by Jeroen Demeyer and Xiang Zhang in bpo-27177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27177}.)

@node readline,rlcompleter,re<2>,改进的模块<4>
@anchor{whatsnew/3 6 readline}@anchor{677}
@subsubsection readline


Added @ref{678,,set_auto_history()} to enable or disable
automatic addition of input to the history list.  (Contributed by
Tyler Crompton in bpo-26870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26870}.)

@node rlcompleter,shlex<2>,readline,改进的模块<4>
@anchor{whatsnew/3 6 rlcompleter}@anchor{679}
@subsubsection rlcompleter


Private and special attribute names now are omitted unless the prefix starts
with underscores.  A space or a colon is added after some completed keywords.
(Contributed by Serhiy Storchaka in bpo-25011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25011} and bpo-25209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25209}.)

@node shlex<2>,site,rlcompleter,改进的模块<4>
@anchor{whatsnew/3 6 shlex}@anchor{67a}
@subsubsection shlex


The @ref{67b,,shlex} has much
@ref{67c,,improved shell compatibility}
through the new @emph{punctuation_chars} argument to control which characters
are treated as punctuation.
(Contributed by Vinay Sajip in bpo-1521950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1521950}.)

@node site,sqlite3<2>,shlex<2>,改进的模块<4>
@anchor{whatsnew/3 6 site}@anchor{67d}
@subsubsection site


When specifying paths to add to @ref{262,,sys.path} in a @cite{.pth} file,
you may now specify file paths on top of directories (e.g. zip files).
(Contributed by Wolfgang Langner in bpo-26587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26587}).

@node sqlite3<2>,socket<5>,site,改进的模块<4>
@anchor{whatsnew/3 6 sqlite3}@anchor{67e}
@subsubsection sqlite3


@ref{67f,,sqlite3.Cursor.lastrowid} now supports the @code{REPLACE} statement.
(Contributed by Alex LordThorsen in bpo-16864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16864}.)

@node socket<5>,socketserver<2>,sqlite3<2>,改进的模块<4>
@anchor{whatsnew/3 6 socket}@anchor{680}
@subsubsection socket


The @ref{681,,ioctl()} function now supports the
@ref{682,,SIO_LOOPBACK_FAST_PATH} control code.
(Contributed by Daniel Stokes in bpo-26536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26536}.)

The @ref{683,,getsockopt()} constants @code{SO_DOMAIN},
@code{SO_PROTOCOL}, @code{SO_PEERSEC}, and @code{SO_PASSSEC} are now supported.
(Contributed by Christian Heimes in bpo-26907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26907}.)

The @ref{684,,setsockopt()} now supports the
@code{setsockopt(level, optname, None, optlen: int)} form.
(Contributed by Christian Heimes in bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744}.)

The socket module now supports the address family
@ref{685,,AF_ALG} to interface with Linux Kernel crypto API. @code{ALG_*},
@code{SOL_ALG} and @ref{686,,sendmsg_afalg()} were added.
(Contributed by Christian Heimes in bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744} with support from
Victor Stinner.)

New Linux constants @code{TCP_USER_TIMEOUT} and @code{TCP_CONGESTION} were added.
(Contributed by Omar Sandoval, issue:@cite{26273}).

@node socketserver<2>,ssl<4>,socket<5>,改进的模块<4>
@anchor{whatsnew/3 6 socketserver}@anchor{687}
@subsubsection socketserver


Servers based on the @ref{f0,,socketserver} module, including those
defined in @ref{96,,http.server}, @ref{149,,xmlrpc.server} and
@ref{138,,wsgiref.simple_server}, now support the @ref{66b,,context manager}
protocol.
(Contributed by Aviv Palivoda in bpo-26404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26404}.)

The @code{wfile} attribute of
@ref{688,,StreamRequestHandler} classes now implements
the @ref{689,,io.BufferedIOBase} writable interface.  In particular,
calling @ref{68a,,write()} is now guaranteed to send the
data in full.  (Contributed by Martin Panter in bpo-26721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26721}.)

@node ssl<4>,statistics<2>,socketserver<2>,改进的模块<4>
@anchor{whatsnew/3 6 ssl}@anchor{68b}
@subsubsection ssl


@ref{f3,,ssl} supports OpenSSL 1.1.0.  The minimum recommend version is 1.0.2.
(Contributed by Christian Heimes in bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

3DES has been removed from the default cipher suites and ChaCha20 Poly1305
cipher suites have been added.
(Contributed by Christian Heimes in bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850} and bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}.)

@ref{4f2,,SSLContext} has better default configuration for options
and ciphers.
(Contributed by Christian Heimes in bpo-28043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28043}.)

SSL session can be copied from one client-side connection to another
with the new @ref{68c,,SSLSession} class.  TLS session resumption can
speed up the initial handshake, reduce latency and improve performance
(Contributed by Christian Heimes in bpo-19500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19500} based on a draft by
Alex Warhawk.)

The new @ref{68d,,get_ciphers()} method can be used to
get a list of enabled ciphers in order of cipher priority.

All constants and flags have been converted to @ref{68e,,IntEnum} and
@code{IntFlags}.
(Contributed by Christian Heimes in bpo-28025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28025}.)

Server and client-side specific TLS protocols for @ref{4f2,,SSLContext}
were added.
(Contributed by Christian Heimes in bpo-28085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28085}.)

@node statistics<2>,struct,ssl<4>,改进的模块<4>
@anchor{whatsnew/3 6 statistics}@anchor{68f}
@subsubsection statistics


A new @ref{690,,harmonic_mean()} function has been added.
(Contributed by Steven D'Aprano in bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}.)

@node struct,subprocess<2>,statistics<2>,改进的模块<4>
@anchor{whatsnew/3 6 struct}@anchor{691}
@subsubsection struct


@ref{f8,,struct} now supports IEEE 754 half-precision floats via the @code{'e'}
format specifier.
(Contributed by Eli Stevens, Mark Dickinson in bpo-11734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11734}.)

@node subprocess<2>,sys<5>,struct,改进的模块<4>
@anchor{whatsnew/3 6 subprocess}@anchor{692}
@subsubsection subprocess


@ref{3e3,,subprocess.Popen} destructor now emits a @ref{5d3,,ResourceWarning} warning
if the child process is still running. Use the context manager protocol (@code{with
proc: ...}) or explicitly call the @ref{693,,wait()} method to
read the exit status of the child process. (Contributed by Victor Stinner in
bpo-26741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26741}.)

The @ref{3e3,,subprocess.Popen} constructor and all functions that pass arguments
through to it now accept @emph{encoding} and @emph{errors} arguments. Specifying either
of these will enable text mode for the @emph{stdin}, @emph{stdout} and @emph{stderr} streams.
(Contributed by Steve Dower in bpo-6135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6135}.)

@node sys<5>,telnetlib,subprocess<2>,改进的模块<4>
@anchor{whatsnew/3 6 sys}@anchor{694}
@subsubsection sys


The new @ref{695,,getfilesystemencodeerrors()} function returns the name of
the error mode used to convert between Unicode filenames and bytes filenames.
(Contributed by Steve Dower in bpo-27781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27781}.)

On Windows the return value of the @ref{696,,getwindowsversion()} function
now includes the @emph{platform_version} field which contains the accurate major
version, minor version and build number of the current operating system,
rather than the version that is being emulated for the process
(Contributed by Steve Dower in bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}.)

@node telnetlib,time<4>,sys<5>,改进的模块<4>
@anchor{whatsnew/3 6 telnetlib}@anchor{697}
@subsubsection telnetlib


@ref{698,,Telnet} is now a context manager (contributed by
Stéphane Wirtel in bpo-25485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25485}).

@node time<4>,timeit,telnetlib,改进的模块<4>
@anchor{whatsnew/3 6 time}@anchor{699}
@subsubsection time


The @ref{69a,,struct_time} attributes @code{tm_gmtoff} and
@code{tm_zone} are now available on all platforms.

@node timeit,tkinter<3>,time<4>,改进的模块<4>
@anchor{whatsnew/3 6 timeit}@anchor{69b}
@subsubsection timeit


The new @ref{69c,,Timer.autorange()} convenience
method has been added to call @ref{69d,,Timer.timeit()}
repeatedly so that the total run time is greater or equal to 200 milliseconds.
(Contributed by Steven D'Aprano in bpo-6422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6422}.)

@ref{10d,,timeit} now warns when there is substantial (4x) variance
between best and worst times.
(Contributed by Serhiy Storchaka in bpo-23552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23552}.)

@node tkinter<3>,traceback,timeit,改进的模块<4>
@anchor{whatsnew/3 6 tkinter}@anchor{69e}
@subsubsection tkinter


Added methods @code{trace_add()},
@code{trace_remove()} and @code{trace_info()}
in the @code{tkinter.Variable} class.  They replace old methods
@code{trace_variable()}, @code{trace()},
@code{trace_vdelete()} and
@code{trace_vinfo()} that use obsolete Tcl commands and might
not work in future versions of Tcl.
(Contributed by Serhiy Storchaka in bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}).

@node traceback,tracemalloc<3>,tkinter<3>,改进的模块<4>
@anchor{whatsnew/3 6 traceback}@anchor{69f}@anchor{whatsnew/3 6 whatsnew36-traceback}@anchor{612}
@subsubsection traceback


Both the traceback module and the interpreter's builtin exception display now
abbreviate long sequences of repeated lines in tracebacks as shown in the
following example:

@example
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
@end example

（由  Emanuel Barry在 bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823} 中贡献。）

@node tracemalloc<3>,typing<4>,traceback,改进的模块<4>
@anchor{whatsnew/3 6 tracemalloc}@anchor{6a0}
@subsubsection tracemalloc


The @ref{11d,,tracemalloc} module now supports tracing memory allocations in
multiple different address spaces.

The new @ref{6a1,,DomainFilter} filter class has been added
to filter block traces by their address space (domain).

（由 Victor Stinner 在 bpo-26588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26588} 中贡献。）

@node typing<4>,unicodedata<4>,tracemalloc<3>,改进的模块<4>
@anchor{whatsnew/3 6 typing}@anchor{6a2}@anchor{whatsnew/3 6 whatsnew36-typing}@anchor{5d2}
@subsubsection typing


Since the @ref{122,,typing} module is @ref{45d,,provisional},
all changes introduced in Python 3.6 have also been
backported to Python 3.5.x.

The @ref{122,,typing} module has a much improved support for generic type
aliases.  For example @code{Dict[str, Tuple[S, T]]} is now a valid
type annotation.
(Contributed by Guido van Rossum in Github #195@footnote{https://github.com/python/typing/pull/195}.)

The @ref{637,,typing.ContextManager} class has been added for
representing @ref{636,,contextlib.AbstractContextManager}.
(Contributed by Brett Cannon in bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}.)

The @ref{6a3,,typing.Collection} class has been added for
representing @ref{62f,,collections.abc.Collection}.
(Contributed by Ivan Levkivskyi in bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}.)

The @ref{6a4,,typing.ClassVar} type construct has been added to
mark class variables.  As introduced in 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526}, a variable annotation
wrapped in ClassVar indicates that a given attribute is intended to be used as
a class variable and should not be set on instances of that class.
(Contributed by Ivan Levkivskyi in Github #280@footnote{https://github.com/python/typing/pull/280}.)

A new @ref{6a5,,TYPE_CHECKING} constant that is assumed to be
@code{True} by the static type checkers, but is @code{False} at runtime.
(Contributed by Guido van Rossum in Github #230@footnote{https://github.com/python/typing/issues/230}.)

A new @ref{6a6,,NewType()} helper function has been added to create
lightweight distinct types for annotations:

@example
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
@end example

The static type checker will treat the new type as if it were a subclass
of the original type.  (Contributed by Ivan Levkivskyi in Github #189@footnote{https://github.com/python/typing/issues/189}.)

@node unicodedata<4>,unittest mock<2>,typing<4>,改进的模块<4>
@anchor{whatsnew/3 6 unicodedata}@anchor{6a7}
@subsubsection unicodedata


The @ref{123,,unicodedata} module now uses data from Unicode 9.0.0@footnote{http://unicode.org/versions/Unicode9.0.0/}.
(Contributed by Benjamin Peterson.)

@node unittest mock<2>,urllib request,unicodedata<4>,改进的模块<4>
@anchor{whatsnew/3 6 unittest-mock}@anchor{6a8}
@subsubsection unittest.mock


The @ref{37a,,Mock} class has the following improvements:


@itemize *

@item 
Two new methods, @ref{6a9,,Mock.assert_called()} and @ref{6aa,,Mock.assert_called_once()} to check if the mock object
was called.
(Contributed by Amit Saha in bpo-26323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26323}.)

@item 
The @ref{6ab,,Mock.reset_mock()} method
now has two optional keyword only arguments: @emph{return_value} and
@emph{side_effect}.
(Contributed by Kushal Das in bpo-21271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21271}.)
@end itemize

@node urllib request,urllib robotparser,unittest mock<2>,改进的模块<4>
@anchor{whatsnew/3 6 urllib-request}@anchor{6ac}
@subsubsection urllib.request


If a HTTP request has a file or iterable body (other than a
bytes object) but no @code{Content-Length} header, rather than
throwing an error, @code{AbstractHTTPHandler} now
falls back to use chunked transfer encoding.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@node urllib robotparser,venv<3>,urllib request,改进的模块<4>
@anchor{whatsnew/3 6 urllib-robotparser}@anchor{6ad}
@subsubsection urllib.robotparser


@ref{6ae,,RobotFileParser} now supports the @code{Crawl-delay} and
@code{Request-rate} extensions.
(Contributed by Nikolay Bogoychev in bpo-16099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16099}.)

@node venv<3>,warnings<2>,urllib robotparser,改进的模块<4>
@anchor{whatsnew/3 6 venv}@anchor{6af}
@subsubsection venv


@ref{12e,,venv} accepts a new parameter @code{--prompt}. This parameter provides an
alternative prefix for the virtual environment. (Proposed by Łukasz Balcerzak
and ported to 3.6 by Stéphane Wirtel in bpo-22829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22829}.)

@node warnings<2>,winreg,venv<3>,改进的模块<4>
@anchor{whatsnew/3 6 warnings}@anchor{6b0}
@subsubsection warnings


A new optional @emph{source} parameter has been added to the
@ref{6b1,,warnings.warn_explicit()} function: the destroyed object which emitted a
@ref{5d3,,ResourceWarning}. A @emph{source} attribute has also been added to
@code{warnings.WarningMessage} (contributed by Victor Stinner in
bpo-26568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26568} and bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}).

When a @ref{5d3,,ResourceWarning} warning is logged, the @ref{11d,,tracemalloc} module is now
used to try to retrieve the traceback where the destroyed object was allocated.

Example with the script @code{example.py}:

@example
import warnings

def func():
    return open(__file__)

f = func()
f = None
@end example

Output of the command @code{python3.6 -Wd -X tracemalloc=5 example.py}:

@example
example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
  f = None
Object allocated at (most recent call first):
  File "example.py", lineno 4
    return open(__file__)
  File "example.py", lineno 6
    f = func()
@end example

The "Object allocated at" traceback is new and is only displayed if
@ref{11d,,tracemalloc} is tracing Python memory allocations and if the
@ref{12f,,warnings} module was already imported.

@node winreg,winsound,warnings<2>,改进的模块<4>
@anchor{whatsnew/3 6 winreg}@anchor{6b2}
@subsubsection winreg


Added the 64-bit integer type @ref{6b3,,REG_QWORD}.
(Contributed by Clement Rouault in bpo-23026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23026}.)

@node winsound,xmlrpc client,winreg,改进的模块<4>
@anchor{whatsnew/3 6 winsound}@anchor{6b4}
@subsubsection winsound


Allowed keyword arguments to be passed to @ref{6b5,,Beep},
@ref{6b6,,MessageBeep}, and @ref{6b7,,PlaySound} (bpo-27982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27982}).

@node xmlrpc client,zipfile<2>,winsound,改进的模块<4>
@anchor{whatsnew/3 6 xmlrpc-client}@anchor{6b8}
@subsubsection xmlrpc.client


The @ref{148,,xmlrpc.client} module now supports unmarshalling
additional data types used by the Apache XML-RPC implementation
for numerics and @code{None}.
(Contributed by Serhiy Storchaka in bpo-26885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26885}.)

@node zipfile<2>,zlib,xmlrpc client,改进的模块<4>
@anchor{whatsnew/3 6 zipfile}@anchor{6b9}
@subsubsection zipfile


A new @ref{6ba,,ZipInfo.from_file()} class method
allows making a @ref{6bb,,ZipInfo} instance from a filesystem file.
A new @ref{6bc,,ZipInfo.is_dir()} method can be used
to check if the @ref{6bb,,ZipInfo} instance represents a directory.
(Contributed by Thomas Kluyver in bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}.)

The @ref{6bd,,ZipFile.open()} method can now be used to
write data into a ZIP file, as well as for extracting data.
(Contributed by Thomas Kluyver in bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}.)

@node zlib,,zipfile<2>,改进的模块<4>
@anchor{whatsnew/3 6 zlib}@anchor{6be}
@subsubsection zlib


The @ref{6bf,,compress()} and @ref{6c0,,decompress()} functions now accept
keyword arguments.
(Contributed by Aviv Palivoda in bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243} and
Xiang Zhang in bpo-16764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16764} respectively.)

@node 性能优化<4>,构建和 C API 的改变<2>,改进的模块<4>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 optimizations}@anchor{6c1}
@subsection 性能优化



@itemize *

@item 
The Python interpreter now uses a 16-bit wordcode instead of bytecode which
made a number of opcode optimizations possible.
(Contributed by Demur Rumed with input and reviews from
Serhiy Storchaka and Victor Stinner in bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647} and bpo-28050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28050}.)

@item 
The @ref{54e,,asyncio.Future} class now has an optimized C implementation.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}.)

@item 
The @ref{2e7,,asyncio.Task} class now has an optimized
C implementation. (Contributed by Yury Selivanov in bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}.)

@item 
Various implementation improvements in the @ref{122,,typing} module
(such as caching of generic types) allow up to 30 times performance
improvements and reduced memory footprint.

@item 
The ASCII decoder is now up to 60 times as fast for error handlers
@code{surrogateescape}, @code{ignore} and @code{replace} (Contributed
by Victor Stinner in bpo-24870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24870}).

@item 
The ASCII and the Latin1 encoders are now up to 3 times as fast for the
error handler @code{surrogateescape}
(Contributed by Victor Stinner in bpo-25227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25227}).

@item 
The UTF-8 encoder is now up to 75 times as fast for error handlers
@code{ignore}, @code{replace}, @code{surrogateescape}, @code{surrogatepass} (Contributed
by Victor Stinner in bpo-25267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25267}).

@item 
The UTF-8 decoder is now up to 15 times as fast for error handlers
@code{ignore}, @code{replace} and @code{surrogateescape} (Contributed
by Victor Stinner in bpo-25301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25301}).

@item 
@code{bytes % args} is now up to 2 times faster. (Contributed by Victor Stinner
in bpo-25349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25349}).

@item 
@code{bytearray % args} is now between 2.5 and 5 times faster. (Contributed by
Victor Stinner in bpo-25399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25399}).

@item 
Optimize @ref{447,,bytes.fromhex()} and @ref{448,,bytearray.fromhex()}: they are now
between 2x and 3.5x faster. (Contributed by Victor Stinner in bpo-25401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25401}).

@item 
Optimize @code{bytes.replace(b'@w{'}, b'.')} and @code{bytearray.replace(b'@w{'}, b'.')}:
up to 80% faster. (Contributed by Josh Snider in bpo-26574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26574}).

@item 
Allocator functions of the @ref{607,,PyMem_Malloc()} domain
(@ref{60a,,PYMEM_DOMAIN_MEM}) now use the @ref{6c2,,pymalloc memory allocator} instead of @code{malloc()} function of the C library. The
pymalloc allocator is optimized for objects smaller or equal to 512 bytes
with a short lifetime, and use @code{malloc()} for larger memory blocks.
(Contributed by Victor Stinner in bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}).

@item 
@ref{6c3,,pickle.load()} and @ref{6c4,,pickle.loads()} are now up to 10% faster when
deserializing many small objects (Contributed by Victor Stinner in
bpo-27056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27056}).

@item 
Passing @ref{6c5,,keyword arguments} to a function has an
overhead in comparison with passing @ref{6c6,,positional arguments}.  Now in extension functions implemented with using
Argument Clinic this overhead is significantly decreased.
(Contributed by Serhiy Storchaka in bpo-27574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27574}).

@item 
Optimized @ref{6c7,,glob()} and @ref{6c8,,iglob()} functions in the
@ref{88,,glob} module; they are now about 3--6 times faster.
(Contributed by Serhiy Storchaka in bpo-25596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25596}).

@item 
Optimized globbing in @ref{c8,,pathlib} by using @ref{390,,os.scandir()};
it is now about 1.5--4 times faster.
(Contributed by Serhiy Storchaka in bpo-26032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26032}).

@item 
@ref{140,,xml.etree.ElementTree} parsing, iteration and deepcopy performance
has been significantly improved.
(Contributed by Serhiy Storchaka in bpo-25638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25638}, bpo-25873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25873},
and bpo-25869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25869}.)

@item 
Creation of @ref{2c5,,fractions.Fraction} instances from floats and
decimals is now 2 to 3 times faster.
(Contributed by Serhiy Storchaka in bpo-25971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25971}.)
@end itemize

@node 构建和 C API 的改变<2>,其他改进,性能优化<4>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 build-and-c-api-changes}@anchor{6c9}
@subsection 构建和 C API 的改变



@itemize *

@item 
Python now requires some C99 support in the toolchain to build.
Most notably, Python now uses standard integer types and macros in
place of custom macros like @code{PY_LONG_LONG}.
For more information, see 
@geindex Python 提高建议; PEP 7
PEP 7@footnote{https://www.python.org/dev/peps/pep-0007} and bpo-17884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17884}.

@item 
Cross-compiling CPython with the Android NDK and the Android API level set to
21 (Android 5.0 Lollipop) or greater runs successfully. While Android is not
yet a supported platform, the Python test suite runs on the Android emulator
with only about 16 tests failures. See the Android meta-issue bpo-26865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26865}.

@item 
The @code{--enable-optimizations} configure flag has been added. Turning it on
will activate expensive optimizations like PGO.
(Original patch by Alecsandru Patrascu of Intel in bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}.)

@item 
The @ref{60b,,GIL} must now be held when allocator
functions of @ref{608,,PYMEM_DOMAIN_OBJ} (ex: @ref{609,,PyObject_Malloc()}) and
@ref{60a,,PYMEM_DOMAIN_MEM} (ex: @ref{607,,PyMem_Malloc()}) domains are called.

@item 
New @ref{6ca,,Py_FinalizeEx()} API which indicates if flushing buffered data
failed.
(Contributed by Martin Panter in bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}.)

@item 
@ref{6cb,,PyArg_ParseTupleAndKeywords()} now supports @ref{3d1,,positional-only parameters}.  Positional-only parameters are
defined by empty names.
(Contributed by Serhiy Storchaka in bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}).

@item 
@code{PyTraceback_Print} method now abbreviates long sequences of repeated lines
as @code{"[Previous line repeated @{count@} more times]"}.
(Contributed by Emanuel Barry in bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}.)

@item 
The new @ref{6cc,,PyErr_SetImportErrorSubclass()} function allows for
specifying a subclass of @ref{16c,,ImportError} to raise.
(Contributed by Eric Snow in bpo-15767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15767}.)

@item 
The new @ref{6cd,,PyErr_ResourceWarning()} function can be used to generate
a @ref{5d3,,ResourceWarning} providing the source of the resource allocation.
(Contributed by Victor Stinner in bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}.)

@item 
The new @ref{6ce,,PyOS_FSPath()} function returns the file system
representation of a @ref{47b,,path-like object}.
(Contributed by Brett Cannon in bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}.)

@item 
The @ref{6cf,,PyUnicode_FSConverter()} and @ref{6d0,,PyUnicode_FSDecoder()}
functions will now accept @ref{47b,,path-like objects}.
@end itemize

@node 其他改进,弃用<3>,构建和 C API 的改变<2>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 other-improvements}@anchor{6d1}
@subsection 其他改进



@itemize *

@item 
When @ref{6d2,,--version} (short form: @ref{6d3,,-V}) is supplied twice,
Python prints @ref{6d4,,sys.version} for detailed information.

@example
$ ./python -VV
Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
@end example
@end itemize

@node 弃用<3>,移除<3>,其他改进,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 deprecated}@anchor{6d5}
@subsection 弃用


@menu
* 新关键字:: 
* 已弃用的 Python 行为: 已弃用的 Python 行为<2>. 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<2>. 
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<2>. 
* 弃用的构建选项:: 

@end menu

@node 新关键字,已弃用的 Python 行为<2>,,弃用<3>
@anchor{whatsnew/3 6 new-keywords}@anchor{6d6}
@subsubsection 新关键字


@code{async} and @code{await} are not recommended to be used as variable, class,
function or module names.  Introduced by 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} in Python 3.5, they will
become proper keywords in Python 3.7.  Starting in Python 3.6, the use of
@code{async} or @code{await} as names will generate a @ref{15a,,DeprecationWarning}.

@node 已弃用的 Python 行为<2>,已弃用的 Python 模块、函数和方法<2>,新关键字,弃用<3>
@anchor{whatsnew/3 6 deprecated-python-behavior}@anchor{6d7}
@subsubsection 已弃用的 Python 行为


Raising the @ref{58a,,StopIteration} exception inside a generator will now
generate a @ref{15a,,DeprecationWarning}, and will trigger a @ref{3e4,,RuntimeError}
in Python 3.7.  See @ref{6d8,,PEP 479; Change StopIteration handling inside generators} for details.

The @ref{58b,,__aiter__()} method is now expected to return an asynchronous
iterator directly instead of returning an awaitable as previously.
Doing the former will trigger a @ref{15a,,DeprecationWarning}.  Backward
compatibility will be removed in Python 3.7.
(Contributed by Yury Selivanov in bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}.)

A backslash-character pair that is not a valid escape sequence now generates
a @ref{15a,,DeprecationWarning}.  Although this will eventually become a
@ref{562,,SyntaxError}, that will not be for several Python releases.
(Contributed by Emanuel Barry in bpo-27364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27364}.)

When performing a relative import, falling back on @code{__name__} and
@code{__path__} from the calling module when @code{__spec__} or
@code{__package__} are not defined now raises an @ref{6d9,,ImportWarning}.
(Contributed by Rose Ames in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}.)

@node 已弃用的 Python 模块、函数和方法<2>,已弃用的 C API 函数和类型<2>,已弃用的 Python 行为<2>,弃用<3>
@anchor{whatsnew/3 6 deprecated-python-modules-functions-and-methods}@anchor{6da}
@subsubsection 已弃用的 Python 模块、函数和方法


@menu
* asynchat:: 
* asyncore:: 
* dbm: dbm<3>. 
* distutils: distutils<4>. 
* grp:: 
* importlib: importlib<5>. 
* os: os<5>. 
* re: re<3>. 
* ssl: ssl<5>. 
* tkinter: tkinter<4>. 
* venv: venv<4>. 

@end menu

@node asynchat,asyncore,,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 asynchat}@anchor{6db}
@subsubsection asynchat


The @ref{8,,asynchat} has been deprecated in favor of @ref{9,,asyncio}.
(Contributed by Mariatta in bpo-25002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25002}.)

@node asyncore,dbm<3>,asynchat,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 asyncore}@anchor{6dc}
@subsubsection asyncore


The @ref{a,,asyncore} has been deprecated in favor of @ref{9,,asyncio}.
(Contributed by Mariatta in bpo-25002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25002}.)

@node dbm<3>,distutils<4>,asyncore,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 dbm}@anchor{6dd}
@subsubsection dbm


Unlike other @ref{31,,dbm} implementations, the @ref{32,,dbm.dumb} module
creates databases with the @code{'rw'} mode and allows modifying the database
opened with the @code{'r'} mode.  This behavior is now deprecated and will
be removed in 3.8.
(Contributed by Serhiy Storchaka in bpo-21708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21708}.)

@node distutils<4>,grp,dbm<3>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id2}@anchor{6de}
@subsubsection distutils


The undocumented @code{extra_path} argument to the
@code{Distribution} constructor is now considered deprecated
and will raise a warning if set.   Support for this parameter will be
removed in a future Python release.  See bpo-27919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27919} for details.

@node grp,importlib<5>,distutils<4>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 grp}@anchor{6df}
@subsubsection grp


The support of non-integer arguments in @ref{6e0,,getgrgid()} has been
deprecated.
(Contributed by Serhiy Storchaka in bpo-26129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26129}.)

@node importlib<5>,os<5>,grp,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id3}@anchor{6e1}
@subsubsection importlib


The @ref{6e2,,importlib.machinery.SourceFileLoader.load_module()} and
@ref{6e3,,importlib.machinery.SourcelessFileLoader.load_module()} methods
are now deprecated. They were the only remaining implementations of
@ref{6e4,,importlib.abc.Loader.load_module()} in @ref{9a,,importlib} that had not
been deprecated in previous versions of Python in favour of
@ref{6e5,,importlib.abc.Loader.exec_module()}.

The @ref{6e6,,importlib.machinery.WindowsRegistryFinder} class is now
deprecated. As of 3.6.0, it is still added to @ref{6e7,,sys.meta_path} by
default (on Windows), but this may change in future releases.

@node os<5>,re<3>,importlib<5>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id4}@anchor{6e8}
@subsubsection os


Undocumented support of general @ref{6e9,,bytes-like objects}
as paths in @ref{c4,,os} functions, @ref{2ee,,compile()} and similar functions is
now deprecated.
(Contributed by Serhiy Storchaka in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791} and bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}.)

@node re<3>,ssl<5>,os<5>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id5}@anchor{6ea}
@subsubsection re


Support for inline flags @code{(?letters)} in the middle of the regular
expression has been deprecated and will be removed in a future Python
version.  Flags at the start of a regular expression are still allowed.
(Contributed by Serhiy Storchaka in bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}.)

@node ssl<5>,tkinter<4>,re<3>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id6}@anchor{6eb}
@subsubsection ssl


OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.
In the future the @ref{f3,,ssl} module will require at least OpenSSL 1.0.2 or
1.1.0.

SSL-related arguments like @code{certfile}, @code{keyfile} and @code{check_hostname}
in @ref{82,,ftplib}, @ref{93,,http.client}, @ref{97,,imaplib}, @ref{d0,,poplib},
and @ref{ed,,smtplib} have been deprecated in favor of @code{context}.
(Contributed by Christian Heimes in bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022}.)

A couple of protocols and functions of the @ref{f3,,ssl} module are now
deprecated. Some features will no longer be available in future versions
of OpenSSL. Other features are deprecated in favor of a different API.
(Contributed by Christian Heimes in bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022} and bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}.)

@node tkinter<4>,venv<4>,ssl<5>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id7}@anchor{6ec}
@subsubsection tkinter


The @ref{117,,tkinter.tix} module is now deprecated.  @ref{10e,,tkinter} users
should use @ref{118,,tkinter.ttk} instead.

@node venv<4>,,tkinter<4>,已弃用的 Python 模块、函数和方法<2>
@anchor{whatsnew/3 6 id8}@anchor{6ed}
@subsubsection venv


The @code{pyvenv} script has been deprecated in favour of @code{python3 -m venv}.
This prevents confusion as to what Python interpreter @code{pyvenv} is
connected to and thus what Python interpreter will be used by the virtual
environment.  (Contributed by Brett Cannon in bpo-25154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25154}.)

@node 已弃用的 C API 函数和类型<2>,弃用的构建选项,已弃用的 Python 模块、函数和方法<2>,弃用<3>
@anchor{whatsnew/3 6 deprecated-functions-and-types-of-the-c-api}@anchor{6ee}
@subsubsection 已弃用的 C API 函数和类型


Undocumented functions @code{PyUnicode_AsEncodedObject()},
@code{PyUnicode_AsDecodedObject()}, @code{PyUnicode_AsEncodedUnicode()}
and @code{PyUnicode_AsDecodedUnicode()} are deprecated now.
Use the @ref{6ef,,generic codec based API} instead.

@node 弃用的构建选项,,已弃用的 C API 函数和类型<2>,弃用<3>
@anchor{whatsnew/3 6 deprecated-build-options}@anchor{6f0}
@subsubsection 弃用的构建选项


The @code{--with-system-ffi} configure flag is now on by default on non-macOS
UNIX platforms.  It may be disabled by using @code{--without-system-ffi}, but
using the flag is deprecated and will not be accepted in Python 3.7.
macOS is unaffected by this change.  Note that many OS distributors already
use the @code{--with-system-ffi} flag when building their system Python.

@node 移除<3>,移植到Python 3 6,弃用<3>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 removed}@anchor{6f1}
@subsection 移除


@menu
* API 与特性的移除: API 与特性的移除<3>. 

@end menu

@node API 与特性的移除<3>,,,移除<3>
@anchor{whatsnew/3 6 api-and-feature-removals}@anchor{6f2}
@subsubsection API 与特性的移除



@itemize *

@item 
Unknown escapes consisting of @code{'\'} and an ASCII letter in
regular expressions will now cause an error.  In replacement templates for
@ref{582,,re.sub()} they are still allowed, but deprecated.
The @ref{4d8,,re.LOCALE} flag can now only be used with binary patterns.

@item 
@code{inspect.getmoduleinfo()} was removed (was deprecated since CPython 3.3).
@ref{6f3,,inspect.getmodulename()} should be used for obtaining the module
name for a given path.
(Contributed by Yury Selivanov in bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}.)

@item 
@code{traceback.Ignore} class and @code{traceback.usage}, @code{traceback.modname},
@code{traceback.fullmodname}, @code{traceback.find_lines_from_code},
@code{traceback.find_lines}, @code{traceback.find_strings},
@code{traceback.find_executable_lines} methods were removed from the
@ref{11c,,traceback} module. They were undocumented methods deprecated since
Python 3.2 and equivalent functionality is available from private methods.

@item 
The @code{tk_menuBar()} and @code{tk_bindForTraversal()} dummy methods in
@ref{10e,,tkinter} widget classes were removed (corresponding Tk commands
were obsolete since Tk 4.0).

@item 
The @ref{6bd,,open()} method of the @ref{52b,,zipfile.ZipFile}
class no longer supports the @code{'U'} mode (was deprecated since Python 3.4).
Use @ref{6f4,,io.TextIOWrapper} for reading compressed text files in
@ref{6f5,,universal newlines} mode.

@item 
The undocumented @code{IN}, @code{CDROM}, @code{DLFCN}, @code{TYPES}, @code{CDIO}, and
@code{STROPTS} modules have been removed.  They had been available in the
platform specific @code{Lib/plat-*/} directories, but were chronically out of
date, inconsistently available across platforms, and unmaintained.  The
script that created these modules is still available in the source
distribution at Tools/scripts/h2py.py@footnote{https://github.com/python/cpython/tree/3.9/Tools/scripts/h2py.py}.

@item 
The deprecated @code{asynchat.fifo} class has been removed.
@end itemize

@node 移植到Python 3 6,Python 3 6 2 中的重要变化,移除<3>,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 porting-to-python-3-6}@anchor{6f6}
@subsection 移植到Python 3.6


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* 'python' 命令行为的变化:: 
* Python API 的更改:: 
* C API 中的改变: C API 中的改变<3>. 
* CPython 字节码的改变: CPython 字节码的改变<4>. 

@end menu

@node 'python' 命令行为的变化,Python API 的更改,,移植到Python 3 6
@anchor{whatsnew/3 6 changes-in-python-command-behavior}@anchor{6f7}
@subsubsection  'python' 命令行为的变化



@itemize *

@item 
The output of a special Python build with defined @code{COUNT_ALLOCS},
@code{SHOW_ALLOC_COUNT} or @code{SHOW_TRACK_COUNT} macros is now off by
default.  It can be re-enabled using the @code{-X showalloccount} option.
It now outputs to @code{stderr} instead of @code{stdout}.
(Contributed by Serhiy Storchaka in bpo-23034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23034}.)
@end itemize

@node Python API 的更改,C API 中的改变<3>,'python' 命令行为的变化,移植到Python 3 6
@anchor{whatsnew/3 6 changes-in-the-python-api}@anchor{6f8}
@subsubsection Python API 的更改



@itemize *

@item 
@ref{16f,,open()} will no longer allow combining the @code{'U'} mode flag
with @code{'+'}.
(Contributed by Jeff Balogh and John O'Connor in bpo-2091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2091}.)

@item 
@ref{f2,,sqlite3} no longer implicitly commits an open transaction before DDL
statements.

@item 
On Linux, @ref{5d4,,os.urandom()} now blocks until the system urandom entropy pool
is initialized to increase the security.

@item 
When @ref{6e5,,importlib.abc.Loader.exec_module()} is defined,
@ref{657,,importlib.abc.Loader.create_module()} must also be defined.

@item 
@ref{6f9,,PyErr_SetImportError()} now sets @ref{1ff,,TypeError} when its @strong{msg}
argument is not set. Previously only @code{NULL} was returned.

@item 
The format of the @code{co_lnotab} attribute of code objects changed to support
a negative line number delta. By default, Python does not emit bytecode with
a negative line number delta. Functions using @code{frame.f_lineno},
@code{PyFrame_GetLineNumber()} or @code{PyCode_Addr2Line()} are not affected.
Functions directly decoding @code{co_lnotab} should be updated to use a signed
8-bit integer type for the line number delta, but this is only required to
support applications using a negative line number delta. See
@code{Objects/lnotab_notes.txt} for the @code{co_lnotab} format and how to decode
it, and see the 
@geindex Python 提高建议; PEP 511
PEP 511@footnote{https://www.python.org/dev/peps/pep-0511} for the rationale.

@item 
The functions in the @ref{20,,compileall} module now return booleans instead
of @code{1} or @code{0} to represent success or failure, respectively. Thanks to
booleans being a subclass of integers, this should only be an issue if you
were doing identity checks for @code{1} or @code{0}. See bpo-25768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25768}.

@item 
Reading the @code{port} attribute of
@ref{6fa,,urllib.parse.urlsplit()} and @ref{6fb,,urlparse()} results
now raises @ref{16d,,ValueError} for out-of-range values, rather than
returning @ref{204,,None}.  See bpo-20059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20059}.

@item 
The @ref{99,,imp} module now raises a @ref{15a,,DeprecationWarning} instead of
@ref{15c,,PendingDeprecationWarning}.

@item 
The following modules have had missing APIs added to their @code{__all__}
attributes to match the documented APIs:
@ref{14,,calendar}, @ref{15,,cgi}, @ref{29,,csv},
@ref{140,,ElementTree}, @ref{79,,enum},
@ref{7e,,fileinput}, @ref{82,,ftplib}, @ref{aa,,logging}, @ref{ae,,mailbox},
@ref{b2,,mimetypes}, @ref{c3,,optparse}, @ref{cf,,plistlib}, @ref{ec,,smtpd},
@ref{f9,,subprocess}, @ref{101,,tarfile}, @ref{10b,,threading} and
@ref{130,,wave}.  This means they will export new symbols when @code{import *}
is used.
(Contributed by Joel Taddei and Jacek Kołodziej in bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}.)

@item 
When performing a relative import, if @code{__package__} does not compare equal
to @code{__spec__.parent} then @ref{6d9,,ImportWarning} is raised.
(Contributed by Brett Cannon in bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}.)

@item 
When a relative import is performed and no parent package is known, then
@ref{16c,,ImportError} will be raised. Previously, @ref{6fc,,SystemError} could be
raised. (Contributed by Brett Cannon in bpo-18018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18018}.)

@item 
Servers based on the @ref{f0,,socketserver} module, including those
defined in @ref{96,,http.server}, @ref{149,,xmlrpc.server} and
@ref{138,,wsgiref.simple_server}, now only catch exceptions derived
from @ref{2e3,,Exception}. Therefore if a request handler raises
an exception like @ref{6fd,,SystemExit} or @ref{2d3,,KeyboardInterrupt},
@ref{6fe,,handle_error()} is no longer called, and
the exception will stop a single-threaded server. (Contributed by
Martin Panter in bpo-23430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23430}.)

@item 
如果用户没有权限， @ref{6ff,,spwd.getspnam()} 现在会引发 @ref{700,,PermissionError} 而不是 @ref{3f1,,KeyError} 。

@item 
The @ref{701,,socket.socket.close()} method now raises an exception if
an error (e.g. @code{EBADF}) was reported by the underlying system call.
(Contributed by Martin Panter in bpo-26685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26685}.)

@item 
The @emph{decode_data} argument for the @ref{702,,smtpd.SMTPChannel} and
@ref{703,,smtpd.SMTPServer} constructors is now @code{False} by default.
This means that the argument passed to
@ref{704,,process_message()} is now a bytes object by
default, and @code{process_message()} will be passed keyword arguments.
Code that has already been updated in accordance with the deprecation
warning generated by 3.5 will not be affected.

@item 
All optional arguments of the @ref{705,,dump()}, @ref{706,,dumps()},
@ref{662,,load()} and @ref{226,,loads()} functions and
@ref{707,,JSONEncoder} and @ref{708,,JSONDecoder} class
constructors in the @ref{a4,,json} module are now @ref{3d6,,keyword-only}.
(Contributed by Serhiy Storchaka in bpo-18726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18726}.)

@item 
@ref{709,,type} 的子类如果未重载 @code{type.__new__}，将不再能使用一个参数的形式来获取对象的类型。

@item 
As part of 
@geindex Python 提高建议; PEP 487
PEP 487@footnote{https://www.python.org/dev/peps/pep-0487}, the handling of keyword arguments passed to
@ref{709,,type} (other than the metaclass hint, @code{metaclass}) is now
consistently delegated to @ref{5e5,,object.__init_subclass__()}. This means that
@code{type.__new__()} and @code{type.__init__()} both now accept arbitrary
keyword arguments, but @ref{5e5,,object.__init_subclass__()} (which is called from
@code{type.__new__()}) will reject them by default. Custom metaclasses
accepting additional keyword arguments will need to adjust their calls to
@code{type.__new__()} (whether direct or via @ref{5e6,,super}) accordingly.

@item 
In @code{distutils.command.sdist.sdist}, the @code{default_format}
attribute has been removed and is no longer honored. Instead, the
gzipped tarfile format is the default on all platforms and no
platform-specific selection is made.
In environments where distributions are
built on Windows and zip distributions are required, configure
the project with a @code{setup.cfg} file containing the following:

@example
[sdist]
formats=zip
@end example

This behavior has also been backported to earlier Python versions
by Setuptools 26.0.0.

@item 
In the @ref{129,,urllib.request} module and the
@ref{652,,http.client.HTTPConnection.request()} method, if no Content-Length
header field has been specified and the request body is a file object,
it is now sent with HTTP 1.1 chunked encoding. If a file object has to
be sent to a HTTP 1.0 server, the Content-Length value now has to be
specified by the caller.
(Contributed by Demian Brecht and Rolf Krahl with tweaks from
Martin Panter in bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}.)

@item 
The @ref{2f5,,DictReader} now returns rows of type
@ref{2f1,,OrderedDict}.
(Contributed by Steve Holden in bpo-27842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27842}.)

@item 
The @ref{70a,,crypt.METHOD_CRYPT} will no longer be added to @code{crypt.methods}
if unsupported by the platform.
(Contributed by Victor Stinner in bpo-25287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25287}.)

@item 
The @emph{verbose} and @emph{rename} arguments for
@ref{1a1,,namedtuple()} are now keyword-only.
(Contributed by Raymond Hettinger in bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}.)

@item 
On Linux, @ref{70b,,ctypes.util.find_library()} now looks in
@code{LD_LIBRARY_PATH} for shared libraries.
(Contributed by Vinay Sajip in bpo-9998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9998}.)

@item 
The @ref{1b0,,imaplib.IMAP4} class now handles flags containing the
@code{']'} character in messages sent from the server to improve
real-world compatibility.
(Contributed by Lita Cho in bpo-21815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21815}.)

@item 
The @code{mmap.write()} function now returns the number
of bytes written like other write methods.
(Contributed by Jakub Stasiak in bpo-26335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26335}.)

@item 
The @ref{70c,,pkgutil.iter_modules()} and @ref{58e,,pkgutil.walk_packages()}
functions now return @ref{70d,,ModuleInfo} named tuples.
(Contributed by Ramchandra Apte in bpo-17211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17211}.)

@item 
@ref{582,,re.sub()} now raises an error for invalid numerical group
references in replacement templates even if the pattern is not
found in the string.  The error message for invalid group references
now includes the group index and the position of the reference.
(Contributed by SilentGhost, Serhiy Storchaka in bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}.)

@item 
@ref{52b,,zipfile.ZipFile} will now raise @ref{70e,,NotImplementedError} for
unrecognized compression values.  Previously a plain @ref{3e4,,RuntimeError}
was raised.  Additionally, calling @ref{52b,,ZipFile} methods
on a closed ZipFile or calling the @ref{70f,,write()} method
on a ZipFile created with mode @code{'r'} will raise a @ref{16d,,ValueError}.
Previously, a @ref{3e4,,RuntimeError} was raised in those scenarios.

@item 
when custom metaclasses are combined with zero-argument @ref{5e6,,super()} or
direct references from methods to the implicit @code{__class__} closure
variable, the implicit @code{__classcell__} namespace entry must now be passed
up to @code{type.__new__} for initialisation. Failing to do so will result in
a @ref{15a,,DeprecationWarning} in Python 3.6 and a @ref{3e4,,RuntimeError} in
Python 3.8.

@item 
With the introduction of @ref{4a9,,ModuleNotFoundError}, import system consumers
may start expecting import system replacements to raise that more specific
exception when appropriate, rather than the less-specific @ref{16c,,ImportError}.
To provide future compatibility with such consumers, implementors of
alternative import systems that completely replace @ref{16b,,__import__()} will
need to update their implementations to raise the new subclass when a module
can't be found at all. Implementors of compliant plugins to the default
import system shouldn't need to make any changes, as the default import
system will raise the new subclass when appropriate.
@end itemize

@node C API 中的改变<3>,CPython 字节码的改变<4>,Python API 的更改,移植到Python 3 6
@anchor{whatsnew/3 6 changes-in-the-c-api}@anchor{710}
@subsubsection C API 中的改变



@itemize *

@item 
The @ref{607,,PyMem_Malloc()} allocator family now uses the @ref{6c2,,pymalloc allocator} rather than the system @code{malloc()}. Applications calling
@ref{607,,PyMem_Malloc()} without holding the GIL can now crash. Set the
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} environment variable to @code{debug} to validate the
usage of memory allocators in your application. See bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}.

@item 
@ref{711,,Py_Exit()} (and the main interpreter) now override the exit status
with 120 if flushing buffered data failed.  See bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}.
@end itemize

@node CPython 字节码的改变<4>,,C API 中的改变<3>,移植到Python 3 6
@anchor{whatsnew/3 6 cpython-bytecode-changes}@anchor{712}
@subsubsection CPython 字节码的改变


There have been several major changes to the @ref{713,,bytecode} in Python 3.6.


@itemize *

@item 
The Python interpreter now uses a 16-bit wordcode instead of bytecode.
(Contributed by Demur Rumed with input and reviews from
Serhiy Storchaka and Victor Stinner in bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647} and bpo-28050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28050}.)

@item 
The new @ref{714,,FORMAT_VALUE} and @ref{715,,BUILD_STRING} opcodes as part
of the  @ref{5c4,,formatted string literal} implementation.
(Contributed by Eric Smith in bpo-25483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25483} and
Serhiy Storchaka in bpo-27078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27078}.)

@item 
The new @ref{716,,BUILD_CONST_KEY_MAP} opcode to optimize the creation
of dictionaries with constant keys.
(Contributed by Serhiy Storchaka in bpo-27140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27140}.)

@item 
The function call opcodes have been heavily reworked for better performance
and simpler implementation.
The @ref{717,,MAKE_FUNCTION}, @ref{718,,CALL_FUNCTION},
@ref{719,,CALL_FUNCTION_KW} and @code{BUILD_MAP_UNPACK_WITH_CALL} opcodes
have been modified, the new @ref{71a,,CALL_FUNCTION_EX} and
@code{BUILD_TUPLE_UNPACK_WITH_CALL} have been added, and
@code{CALL_FUNCTION_VAR}, @code{CALL_FUNCTION_VAR_KW} and @code{MAKE_CLOSURE} opcodes
have been removed.
(Contributed by Demur Rumed in bpo-27095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27095}, and Serhiy Storchaka in
bpo-27213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27213}, bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}.)

@item 
The new @ref{71b,,SETUP_ANNOTATIONS} and @code{STORE_ANNOTATION} opcodes
have been added to support the new @ref{71c,,variable annotation} syntax.
(Contributed by Ivan Levkivskyi in bpo-27985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27985}.)
@end itemize

@node Python 3 6 2 中的重要变化,Python 3 6 4 中的重要变化,移植到Python 3 6,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-2}@anchor{71d}
@subsection Python 3.6.2 中的重要变化


@menu
* New make regen-all build target:: 
* Removal of make touch build target:: 

@end menu

@node New make regen-all build target,Removal of make touch build target,,Python 3 6 2 中的重要变化
@anchor{whatsnew/3 6 new-make-regen-all-build-target}@anchor{71e}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.9/Makefile.pre.in} for details.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


3.6.2 新版功能.


@node Removal of make touch build target,,New make regen-all build target,Python 3 6 2 中的重要变化
@anchor{whatsnew/3 6 removal-of-make-touch-build-target}@anchor{71f}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


在 3.6.2 版更改.


@node Python 3 6 4 中的重要变化,Python 3 6 5 中的重要变化,Python 3 6 2 中的重要变化,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-4}@anchor{720}
@subsection Python 3.6.4 中的重要变化


The @code{PyExc_RecursionErrorInst} singleton that was part of the public API
has been removed as its members being never cleared may cause a segfault
during finalization of the interpreter.
(Contributed by Xavier de Gaye in bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898} and bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}.)

@node Python 3 6 5 中的重要变化,Python 3 6 7 中的重要变化,Python 3 6 4 中的重要变化,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-5}@anchor{721}
@subsection Python 3.6.5 中的重要变化


The @ref{58d,,locale.localeconv()} function now sets temporarily the @code{LC_CTYPE}
locale to the @code{LC_NUMERIC} locale in some cases.
(Contributed by Victor Stinner in bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}.)

@node Python 3 6 7 中的重要变化,Python 3 6 10 中的重要变化,Python 3 6 5 中的重要变化,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-7}@anchor{722}
@subsection Python 3.6.7 中的重要变化


In 3.6.7 the @ref{11a,,tokenize} module now implicitly emits a @code{NEWLINE} token
when provided with input that does not have a trailing new line.  This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}.)

@node Python 3 6 10 中的重要变化,Notable changes in Python 3 6 13,Python 3 6 7 中的重要变化,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-10}@anchor{723}
@subsection Python 3.6.10 中的重要变化


出于重要的安全性考量，@ref{189,,asyncio.loop.create_datagram_endpoint()} 的 @emph{reuse_address} 形参不再被支持。 这是由 UDP 中的套接字选项 @code{SO_REUSEADDR} 的行为导致的。 更多细节请参阅 @code{loop.create_datagram_endpoint()} 的文档。 （由 Kyle Stanley, Antoine Pitrou 和 Yury Selivanov 在 bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228} 中贡献。。）

@node Notable changes in Python 3 6 13,,Python 3 6 10 中的重要变化,Python 3 6 有什么新变化
@anchor{whatsnew/3 6 notable-changes-in-python-3-6-13}@anchor{724}
@subsection Notable changes in Python 3.6.13


早先的 Python 版本允许使用 @code{;} 和 @code{&} 作为 @ref{280,,urllib.parse.parse_qs()} 和 @ref{281,,urllib.parse.parse_qsl()} 中 query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被改为只允许单个分隔键，默认为 @code{&}。 这一改变还会影响 @ref{282,,cgi.parse()} 和 @ref{283,,cgi.parse_multipart()} 因为它们在内部使用了受影响的函数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt, Senthil Kumaran 和 Ken Jin 在 bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967} 中贡献。）

@node Python 3 5 有什么新变化,Python 3 4 有什么新变化,Python 3 6 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 5 doc}@anchor{725}@anchor{whatsnew/3 5 what-s-new-in-python-3-5}@anchor{726}
@section Python 3.5 有什么新变化


@*编者: 
Elvis Pranskevichus <@email{elvis@@magic.io}>, Yury Selivanov <@email{yury@@magic.io}>


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

这篇文章介绍了 Python 3.5 相比 3.4 增加的新特性。 Python 3.5 发布于 2015 年 9 月 13 日。 更完成的变化清单请参阅 changelog@footnote{https://docs.python.org/3.5/whatsnew/changelog.html}。


@subsubheading 参见


@geindex Python 提高建议; PEP 478
PEP 478@footnote{https://www.python.org/dev/peps/pep-0478} - Python 3.5 发布计划


@menu
* 摘要 - 发布重点: 摘要 - 发布重点<5>. 
* 新的特性: 新的特性<6>. 
* 其他语言特性修改: 其他语言特性修改<5>. 
* 新增模块: 新增模块<5>. 
* 改进的模块: 改进的模块<5>. 
* 其他模块级更改:: 
* 性能优化: 性能优化<5>. 
* 构建和 C API 的改变: 构建和 C API 的改变<3>. 
* 弃用: 弃用<4>. 
* 移除: 移除<4>. 
* 移植到Python 3.5: 移植到Python 3 5. 
* Python 3.5.4 的显著变化: Python 3 5 4 的显著变化. 

@end menu

@node 摘要 - 发布重点<5>,新的特性<6>,,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 summary-release-highlights}@anchor{727}
@subsection 摘要 - 发布重点


新的语法特性：


@itemize *

@item 
@ref{728,,PEP 492}, 使用 async 和 await 语法实现协程。

@item 
@ref{729,,PEP 465}, 新的矩阵乘法运算符: @code{a @@ b}.

@item 
@ref{72a,,PEP 448}, 额外的解包通用化。
@end itemize

新的库模块：


@itemize *

@item 
@ref{122,,typing}: @ref{72b,,PEP 484 -- 类型提示}.

@item 
@ref{14a,,zipapp}: @ref{72c,,PEP 441 改进Python ZIP应用程序支持}.
@end itemize

新的内置特性：


@itemize *

@item 
@code{bytes % args}, @code{bytearray % args}: @ref{72d,,PEP 461} -- 为字节串和字节数组增加 @code{%} 格式化。

@item 
新增 @ref{72e,,bytes.hex()}, @ref{72f,,bytearray.hex()} 和 @ref{730,,memoryview.hex()} 方法。 （由 Arnon Yaari 在 bpo-9951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9951} 中贡献。）

@item 
@ref{38d,,memoryview} 现在支持元组索引（包括多维度）。 （由 Antoine Pitrou 在 bpo-23632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23632} 中贡献。）

@item 
生成器具有一个新的 @code{gi_yieldfrom} 属性，它将返回 @code{yield from} 表达式所迭代的对象。 （由 Benno Leslie 和 Yury Selivanov 在 bpo-24450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24450} 中贡献。）

@item 
现在当达到最大递归尝试时将引发新的 @ref{731,,RecursionError} 异常。 （由 Georg Brandl 在 bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235} 中贡献。）
@end itemize

CPython 实现的改进：


@itemize *

@item 
当 @code{LC_TYPE} 语言区域为 POSIX 语言区域（即 @code{C} 语言区域）时，@ref{427,,sys.stdin} 和 @ref{428,,sys.stdout} 现在将使用 @code{surrogateescape} 错误处理句柄，而不是 @code{strict} 错误处理句柄。 （由 Victor Stinner 在 bpo-19977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19977} 中贡献。）

@item 
@code{.pyo} 文件已不再被使用而是被替换为一个更灵活的方案即在 @code{.pyc} 名称中显式地包括优化级别。 （参见 @ref{732,,PEP 488 概览}。）

@item 
内置与扩展模块现在将经过多阶段的过程被初始化，这类似于 Python 模块的加载方式。 （参见 @ref{733,,PEP 489 概览}。）
@end itemize

标准库中的重大改进：


@itemize *

@item 
@ref{2f1,,collections.OrderedDict} 现在已 @ref{734,,用 C 实现}，这使它的速度快了 4 到 100 部。

@item 
The @ref{f3,,ssl} 模块获得了 @ref{735,,对内存 BIO 的支持}，它使得 SSL 协议处理与网络 IO 实现了解耦。

@item 
新的 @ref{390,,os.scandir()} 函数提供了对于目录遍历 @ref{736,,更好和明显更快速的方式}。

@item 
@ref{2ff,,functools.lru_cache()} 已经大部分 @ref{737,,用 C 重新实现}，产生了更好的性能。

@item 
新的 @ref{4fb,,subprocess.run()} 函数提供了一个 @ref{738,,运行子进程的简便方式}。

@item 
@ref{11c,,traceback} 模块已被显著 @ref{739,,增强} 以改善性能和开发者便捷度。
@end itemize

安全改进：


@itemize *

@item 
SSLv3 目前在整个标准库中被禁用。 它仍然可以通过手动实例化一个 @ref{4f2,,ssl.SSLContext} 来启用。 （请参阅 bpo-22638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22638} 了解详情；此修改已向下移植到 CPython 3.4 和 2.7。）

@item 
HTTP cookie 解析现在将更严格，以防止潜在的注入攻击。 （由 Antoine Pitrou 在 bpo-22796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22796} 中贡献。）
@end itemize

Windows改进：


@itemize *

@item 
使用新的 Windows 安装器替代了旧版 MSI。 请参阅 @ref{401,,在Windows上使用 Python} 了解详情。

@item 
Windows 编译版现在使用 Microsoft Visual C++ 14.0，扩展模块也应当使用同一版本。
@end itemize

请继续阅读有关针对用户的改变的完整清单，包括许多其他较小的改进、CPython 优化、弃用以及潜在的移植问题。

@node 新的特性<6>,其他语言特性修改<5>,摘要 - 发布重点<5>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 new-features}@anchor{73a}
@subsection 新的特性


@menu
* PEP 492 - 使用 async 和 await 语法实现协程:: 
* PEP 465 - 用于矩阵乘法的专用中缀运算符:: 
* PEP 448 - Additional Unpacking Generalizations:: 
* PEP 461 - percent formatting support for bytes and bytearray:: 
* PEP 484 - 类型提示:: 
* PEP 471 - os.scandir() function: PEP 471 - os scandir function -- a better and faster directory iterator. a better and faster directory iterator
* PEP 475; Retry system calls failing with EINTR: PEP 475 Retry system calls failing with EINTR. 
* PEP 479; Change StopIteration handling inside generators: PEP 479 Change StopIteration handling inside generators. 
* PEP 485; A function for testing approximate equality: PEP 485 A function for testing approximate equality. 
* PEP 486; Make the Python Launcher aware of virtual environments: PEP 486 Make the Python Launcher aware of virtual environments. 
* PEP 488; Elimination of PYO files: PEP 488 Elimination of PYO files. 
* PEP 489; Multi-phase extension module initialization: PEP 489 Multi-phase extension module initialization. 

@end menu

@node PEP 492 - 使用 async 和 await 语法实现协程,PEP 465 - 用于矩阵乘法的专用中缀运算符,,新的特性<6>
@anchor{whatsnew/3 5 pep-492-coroutines-with-async-and-await-syntax}@anchor{73b}@anchor{whatsnew/3 5 whatsnew-pep-492}@anchor{728}
@subsubsection PEP 492 - 使用 async 和 await 语法实现协程


@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 通过添加 @ref{61b,,可等待对象}, @ref{73c,,协程函数}, @ref{73d,,异步迭代} 和 @ref{73e,,异步上下文管理器} 极大地改善了 Python 对异步编程的支持。

协程函数是使用新的 @ref{3b1,,async def} 语法来声明的:

@example
>>> async def coro():
...     return 'spam'
@end example

在协程函数内部，新的 @ref{2df,,await} 表达式可用于挂起协程的执行直到其结果可用。 任何对象都可以被 @emph{等待}，只要它通过定义 @ref{73f,,__await__()} 方法实现了 @ref{61b,,awaitable} 协议。

PEP 492 还增加了 @ref{406,,async for} 语句用于方便地迭代异步可迭代对象。

An example of a rudimentary HTTP client written using the new syntax:

@example
import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'@w{'}, b'@w{'}
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()
@end example

Similarly to asynchronous iteration, there is a new syntax for asynchronous
context managers.  The following script:

@example
import asyncio

async def coro(name, lock):
    print('coro @{@}: waiting for lock'.format(name))
    async with lock:
        print('coro @{@}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro @{@}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()
@end example

将输出：

@example
coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock
@end example

Note that both @ref{406,,async for} and @ref{740,,async with} can only
be used inside a coroutine function declared with @ref{3b1,,async def}.

Coroutine functions are intended to be run inside a compatible event loop,
such as the @ref{741,,asyncio loop}.

@cartouche
@quotation 注解 

在 3.5.2 版更改: Starting with CPython 3.5.2, @code{__aiter__} can directly return
@ref{742,,asynchronous iterators}.  Returning
an @ref{61b,,awaitable} object will result in a
@ref{15c,,PendingDeprecationWarning}.

See more details in the @ref{743,,异步迭代器} documentation
section.

@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 492

@item PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} -- 使用 async 和 await 语法实现协程

PEP 由 Yury Selivanov 撰写并实现
@end table


@node PEP 465 - 用于矩阵乘法的专用中缀运算符,PEP 448 - Additional Unpacking Generalizations,PEP 492 - 使用 async 和 await 语法实现协程,新的特性<6>
@anchor{whatsnew/3 5 pep-465-a-dedicated-infix-operator-for-matrix-multiplication}@anchor{744}@anchor{whatsnew/3 5 whatsnew-pep-465}@anchor{729}
@subsubsection PEP 465 - 用于矩阵乘法的专用中缀运算符


@geindex Python 提高建议; PEP 465
PEP 465@footnote{https://www.python.org/dev/peps/pep-0465} adds the @code{@@} infix operator for matrix multiplication.
Currently, no builtin Python types implement the new operator, however, it
can be implemented by defining @ref{745,,__matmul__()}, @ref{746,,__rmatmul__()},
and @ref{747,,__imatmul__()} for regular, reflected, and in-place matrix
multiplication.  The semantics of these methods is similar to that of
methods defining other infix arithmetic operators.

矩阵乘法在数学，科学，工程学的许多领域中是一种常见的操作，使用 @code{@@} 运算符可以编写更简洁的代码：

@example
S = (H @@ beta - r).T @@ inv(H @@ V @@ H.T) @@ (H @@ beta - r)
@end example

代替：

@example
S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))
@end example

NumPy 1.10 支持新的运算符：

@example
>>> import numpy

>>> x = numpy.ones(3)
>>> x
array([ 1., 1., 1.])

>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
       [ 0., 1., 0.],
       [ 0., 0., 1.]])

>>> x @@ m
array([ 1., 1., 1.])
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 465

@item PEP 465@footnote{https://www.python.org/dev/peps/pep-0465} -- 用于矩阵乘法的专用中缀运算符

PEP 由 Nathaniel J. Smith 撰写，由 Benjamin Peterson 实现。
@end table


@node PEP 448 - Additional Unpacking Generalizations,PEP 461 - percent formatting support for bytes and bytearray,PEP 465 - 用于矩阵乘法的专用中缀运算符,新的特性<6>
@anchor{whatsnew/3 5 pep-448-additional-unpacking-generalizations}@anchor{748}@anchor{whatsnew/3 5 whatsnew-pep-448}@anchor{72a}
@subsubsection PEP 448 - Additional Unpacking Generalizations


@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} extends the allowed uses of the @code{*} iterable unpacking
operator and @code{**} dictionary unpacking operator.  It is now possible
to use an arbitrary number of unpackings in @ref{749,,function calls}:

@example
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)
...

>>> fn(**@{'a': 1, 'c': 3@}, **@{'b': 2, 'd': 4@})
1 2 3 4
@end example

Similarly, tuple, list, set, and dictionary displays allow multiple
unpackings (see @ref{74a,,表达式列表} and @ref{74b,,字典显示}):

@example
>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> @{*range(4), 4, *(5, 6, 7)@}
@{0, 1, 2, 3, 4, 5, 6, 7@}

>>> @{'x': 1, **@{'y': 2@}@}
@{'x': 1, 'y': 2@}
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 448

@item PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} -- Additional Unpacking Generalizations

PEP 由 Joshua Landau 撰写 ，由 Neil Girdhar，Thomas Wouters 和 Joshua Landau 实现。
@end table


@node PEP 461 - percent formatting support for bytes and bytearray,PEP 484 - 类型提示,PEP 448 - Additional Unpacking Generalizations,新的特性<6>
@anchor{whatsnew/3 5 pep-461-percent-formatting-support-for-bytes-and-bytearray}@anchor{74c}@anchor{whatsnew/3 5 whatsnew-pep-461}@anchor{72d}
@subsubsection PEP 461 - percent formatting support for bytes and bytearray


@geindex Python 提高建议; PEP 461
PEP 461@footnote{https://www.python.org/dev/peps/pep-0461} adds support for the @code{%}
@ref{74d,,interpolation operator} to @ref{172,,bytes}
and @ref{173,,bytearray}.

While interpolation is usually thought of as a string operation, there are
cases where interpolation on @code{bytes} or @code{bytearrays} makes sense, and the
work needed to make up for this missing functionality detracts from the
overall readability of the code.  This issue is particularly important when
dealing with wire format protocols, which are often a mixture of binary
and ASCII compatible text.

例如:

@example
>>> b'Hello %b!' % b'World'
b'Hello World!'

>>> b'x=%i y=%f' % (1, 2.5)
b'x=1 y=2.500000'
@end example

Unicode is not allowed for @code{%b}, but it is accepted by @code{%a} (equivalent of
@code{repr(obj).encode('ascii', 'backslashreplace')}):

@example
>>> b'Hello %b!' % 'World'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

>>> b'price: %a' % '10€'
b"price: '10\\u20ac'"
@end example

Note that @code{%s} and @code{%r} conversion types, although supported, should
only be used in codebases that need compatibility with Python 2.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 461

@item PEP 461@footnote{https://www.python.org/dev/peps/pep-0461} -- Adding % formatting to bytes and bytearray

PEP 由 Ethan Furman 撰写 ，由 Neil Schemenauer 和 Ethan Furman 实现。
@end table


@node PEP 484 - 类型提示,PEP 471 - os scandir function -- a better and faster directory iterator,PEP 461 - percent formatting support for bytes and bytearray,新的特性<6>
@anchor{whatsnew/3 5 pep-484-type-hints}@anchor{74e}@anchor{whatsnew/3 5 whatsnew-pep-484}@anchor{72b}
@subsubsection PEP 484 - 类型提示


Function annotation syntax has been a Python feature since version 3.0
(
@geindex Python 提高建议; PEP 3107
PEP 3107@footnote{https://www.python.org/dev/peps/pep-3107}), however the semantics of annotations has been left undefined.

Experience has shown that the majority of function annotation
uses were to provide type hints to function parameters and return values.  It
became evident that it would be beneficial for Python users, if the
standard library included the base definitions and tools for type annotations.

@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} introduces a @ref{45d,,provisional module} to
provide these standard definitions and tools, along with some conventions
for situations where annotations are not available.

For example, here is a simple function whose argument and return type
are declared in the annotations:

@example
def greeting(name: str) -> str:
    return 'Hello ' + name
@end example

While these annotations are available at runtime through the usual
@code{__annotations__} attribute, @emph{no automatic type checking happens at
runtime}.  Instead, it is assumed that a separate off-line type checker
(e.g. mypy@footnote{http://mypy-lang.org}) will be used for on-demand
source code analysis.

The type system supports unions, generic types, and a special type
named @ref{74f,,Any} which is consistent with (i.e. assignable to
and from) all types.


@subsubheading 参见



@itemize *

@item 
@ref{122,,typing} 模块文档

@item 

@table @asis

@geindex Python 提高建议; PEP 484

@item PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} -- 类型提示

PEP 由 Guido van Rossum，Jukka Lehtosalo 和 Łukasz Langa 撰写，由 Guido van Rossum 实现。
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 483

@item PEP 483@footnote{https://www.python.org/dev/peps/pep-0483} -- 类型提示理论

PEP 由 Yury Selivanov 撰写
@end table
@end itemize


@node PEP 471 - os scandir function -- a better and faster directory iterator,PEP 475 Retry system calls failing with EINTR,PEP 484 - 类型提示,新的特性<6>
@anchor{whatsnew/3 5 pep-471-os-scandir-function-a-better-and-faster-directory-iterator}@anchor{750}@anchor{whatsnew/3 5 whatsnew-pep-471}@anchor{736}
@subsubsection PEP 471 - os.scandir() function -- a better and faster directory iterator


@geindex Python 提高建议; PEP 471
PEP 471@footnote{https://www.python.org/dev/peps/pep-0471} adds a new directory iteration function, @ref{390,,os.scandir()},
to the standard library.  Additionally, @ref{751,,os.walk()} is now
implemented using @code{scandir}, which makes it 3 to 5 times faster
on POSIX systems and 7 to 20 times faster on Windows systems.  This is
largely achieved by greatly reducing the number of calls to @ref{328,,os.stat()}
required to walk a directory tree.

Additionally, @code{scandir} returns an iterator, as opposed to returning
a list of file names, which improves memory efficiency when iterating
over very large directories.

The following example shows a simple use of @ref{390,,os.scandir()} to display all
the files (excluding directories) in the given @emph{path} that don't start with
@code{'.'}. The @ref{752,,entry.is_file()} call will generally
not make an additional system call:

@example
for entry in os.scandir(path):
    if not entry.name.startswith('.') and entry.is_file():
        print(entry.name)
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 471

@item PEP 471@footnote{https://www.python.org/dev/peps/pep-0471} -- os.scandir() function -- a better and faster directory iterator

PEP 由 Ben Hoyt 在 Victor Stinner 的帮助下撰写并实现
@end table


@node PEP 475 Retry system calls failing with EINTR,PEP 479 Change StopIteration handling inside generators,PEP 471 - os scandir function -- a better and faster directory iterator,新的特性<6>
@anchor{whatsnew/3 5 pep-475-retry-system-calls-failing-with-eintr}@anchor{753}@anchor{whatsnew/3 5 whatsnew-pep-475}@anchor{754}
@subsubsection PEP 475: Retry system calls failing with EINTR


An @ref{755,,errno.EINTR} error code is returned whenever a system call, that
is waiting for I/O, is interrupted by a signal.  Previously, Python would
raise @ref{756,,InterruptedError} in such cases.  This meant that, when writing a
Python application, the developer had two choices:


@enumerate 

@item 
Ignore the @code{InterruptedError}.

@item 
Handle the @code{InterruptedError} and attempt to restart the interrupted
system call at every call site.
@end enumerate

The first option makes an application fail intermittently.
The second option adds a large amount of boilerplate that makes the
code nearly unreadable.  Compare:

@example
print("Hello World")
@end example

和:

@example
while True:
    try:
        print("Hello World")
        break
    except InterruptedError:
        continue
@end example

@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} implements automatic retry of system calls on
@code{EINTR}.  This removes the burden of dealing with @code{EINTR}
or @ref{756,,InterruptedError} in user code in most situations and makes
Python programs, including the standard library, more robust.  Note that
the system call is only retried if the signal handler does not raise an
exception.

Below is a list of functions which are now retried when interrupted
by a signal:


@itemize *

@item 
@ref{16f,,open()} 和 @ref{757,,io.open()};

@item 
@ref{7b,,faulthandler} 模块的功能

@item 
@ref{c4,,os} 函数: @ref{758,,fchdir()}, @ref{759,,fchmod()}, @ref{75a,,fchown()}, @ref{75b,,fdatasync()}, @ref{75c,,fstat()}, @ref{75d,,fstatvfs()}, @ref{75e,,fsync()}, @ref{75f,,ftruncate()}, @ref{760,,mkfifo()}, @ref{761,,mknod()}, @ref{762,,open()}, @ref{763,,posix_fadvise()}, @ref{764,,posix_fallocate()}, @ref{4c8,,pread()}, @ref{4cb,,pwrite()}, @ref{765,,read()}, @ref{4c7,,readv()}, @ref{46a,,sendfile()}, @ref{766,,wait3()}, @ref{767,,wait4()}, @ref{768,,wait()}, @ref{769,,waitid()}, @ref{76a,,waitpid()}, @ref{76b,,write()}, @ref{4ca,,writev()};

@item 
特例: @ref{4e1,,os.close()} 和 @ref{4cd,,os.dup2()} 现在会忽略 @ref{755,,EINTR} 错误; 不重试系统调用（请参阅PEP了解基本原理）

@item 
@ref{e5,,select} 函数: @ref{76c,,devpoll.poll()}, @ref{76d,,epoll.poll()}, @ref{76e,,kqueue.control()}, @ref{76f,,poll.poll()}, @ref{770,,select()};

@item 
@ref{771,,socket} 类的方法: @ref{772,,accept()}, @ref{773,,connect()} （除了非阻塞套接字）, @ref{774,,recv()}, @ref{775,,recvfrom()}, @ref{776,,recvmsg()}, @ref{777,,send()}, @ref{778,,sendall()}, @ref{779,,sendmsg()}, @ref{77a,,sendto()};

@item 
@ref{77b,,signal.sigtimedwait()} 和 @ref{77c,,signal.sigwaitinfo()};

@item 
@ref{77d,,time.sleep()}.
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 475

@item PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} -- Retry system calls failing with EINTR

PEP and implementation written by Charles-François Natali and
Victor Stinner, with the help of Antoine Pitrou (the French connection).
@end table


@node PEP 479 Change StopIteration handling inside generators,PEP 485 A function for testing approximate equality,PEP 475 Retry system calls failing with EINTR,新的特性<6>
@anchor{whatsnew/3 5 pep-479-change-stopiteration-handling-inside-generators}@anchor{77e}@anchor{whatsnew/3 5 whatsnew-pep-479}@anchor{6d8}
@subsubsection PEP 479: Change StopIteration handling inside generators


The interaction of generators and @ref{58a,,StopIteration} in Python 3.4 and
earlier was sometimes surprising, and could conceal obscure bugs.  Previously,
@code{StopIteration} raised accidentally inside a generator function was
interpreted as the end of the iteration by the loop construct driving the
generator.

@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} changes the behavior of generators: when a @code{StopIteration}
exception is raised inside a generator, it is replaced with a
@ref{3e4,,RuntimeError} before it exits the generator frame.  The main goal of
this change is to ease debugging in the situation where an unguarded
@ref{77f,,next()} call raises @code{StopIteration} and causes the iteration controlled
by the generator to terminate silently. This is particularly pernicious in
combination with the @code{yield from} construct.

This is a backwards incompatible change, so to enable the new behavior,
a @ref{780,,__future__} import is necessary:

@example
>>> from __future__ import generator_stop

>>> def gen():
...     next(iter([]))
...     yield
...
>>> next(gen())
Traceback (most recent call last):
  File "<stdin>", line 2, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
@end example

Without a @code{__future__} import, a @ref{15c,,PendingDeprecationWarning} will be
raised whenever a @ref{58a,,StopIteration} exception is raised inside a generator.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 479

@item PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} -- Change StopIteration handling inside generators

PEP 由 Chris Angelico 和 Guido van Rossum 撰写，由 Chris Angelico，Yury Selivanov 和 Nick Coghlan 实现。
@end table


@node PEP 485 A function for testing approximate equality,PEP 486 Make the Python Launcher aware of virtual environments,PEP 479 Change StopIteration handling inside generators,新的特性<6>
@anchor{whatsnew/3 5 pep-485-a-function-for-testing-approximate-equality}@anchor{781}@anchor{whatsnew/3 5 whatsnew-pep-485}@anchor{782}
@subsubsection PEP 485: A function for testing approximate equality


@geindex Python 提高建议; PEP 485
PEP 485@footnote{https://www.python.org/dev/peps/pep-0485} adds the @ref{783,,math.isclose()} and @ref{784,,cmath.isclose()}
functions which tell whether two values are approximately equal or
"close" to each other.  Whether or not two values are considered
close is determined according to given absolute and relative tolerances.
Relative tolerance is the maximum allowed difference between @code{isclose}
arguments, relative to the larger absolute value:

@example
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False
@end example

It is also possible to compare two values using absolute tolerance, which
must be a non-negative value:

@example
>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 485

@item PEP 485@footnote{https://www.python.org/dev/peps/pep-0485} —— 用于测试近似相等的函数

PEP 由 Christopher Barker 撰写，由 Chris Barker 和 Tal Einat 实现。
@end table


@node PEP 486 Make the Python Launcher aware of virtual environments,PEP 488 Elimination of PYO files,PEP 485 A function for testing approximate equality,新的特性<6>
@anchor{whatsnew/3 5 pep-486-make-the-python-launcher-aware-of-virtual-environments}@anchor{785}@anchor{whatsnew/3 5 whatsnew-pep-486}@anchor{786}
@subsubsection PEP 486: Make the Python Launcher aware of virtual environments


@geindex Python 提高建议; PEP 486
PEP 486@footnote{https://www.python.org/dev/peps/pep-0486} makes the Windows launcher (see 
@geindex Python 提高建议; PEP 397
PEP 397@footnote{https://www.python.org/dev/peps/pep-0397}) aware of an active
virtual environment. When the default interpreter would be used and the
@code{VIRTUAL_ENV} environment variable is set, the interpreter in the virtual
environment will be used.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 486

@item PEP 486@footnote{https://www.python.org/dev/peps/pep-0486} -- Make the Python Launcher aware of virtual environments

PEP 由 Paul Moore 撰写并实现
@end table


@node PEP 488 Elimination of PYO files,PEP 489 Multi-phase extension module initialization,PEP 486 Make the Python Launcher aware of virtual environments,新的特性<6>
@anchor{whatsnew/3 5 pep-488-elimination-of-pyo-files}@anchor{787}@anchor{whatsnew/3 5 whatsnew-pep-488}@anchor{732}
@subsubsection PEP 488: Elimination of PYO files


@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} does away with the concept of @code{.pyo} files. This means that
@code{.pyc} files represent both unoptimized and optimized bytecode. To prevent the
need to constantly regenerate bytecode files, @code{.pyc} files now have an
optional @code{opt-} tag in their name when the bytecode is optimized. This has the
side-effect of no more bytecode file name clashes when running under either
@ref{788,,-O} or @ref{789,,-OO}. Consequently, bytecode files generated from
@ref{788,,-O}, and @ref{789,,-OO} may now exist simultaneously.
@ref{65a,,importlib.util.cache_from_source()} has an updated API to help with
this change.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 488

@item PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} -- Elimination of PYO files

PEP 由 Brett Cannon 撰写并实现。
@end table


@node PEP 489 Multi-phase extension module initialization,,PEP 488 Elimination of PYO files,新的特性<6>
@anchor{whatsnew/3 5 pep-489-multi-phase-extension-module-initialization}@anchor{78a}@anchor{whatsnew/3 5 whatsnew-pep-489}@anchor{733}
@subsubsection PEP 489: Multi-phase extension module initialization


@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} updates extension module initialization to take advantage of the
two step module loading mechanism introduced by 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} in Python 3.4.

This change brings the import semantics of extension modules that opt-in to
using the new mechanism much closer to those of Python source and bytecode
modules, including the ability to use any valid identifier as a module name,
rather than being restricted to ASCII.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 489

@item PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} -- Multi-phase extension module initialization

PEP 由 Petr Viktorin , Stefan Behnel 和 Nick Coghlan 撰写，由 Petr Viktorin 实现。
@end table


@node 其他语言特性修改<5>,新增模块<5>,新的特性<6>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 other-language-changes}@anchor{78b}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
Added the @code{"namereplace"} error handlers.  The @code{"backslashreplace"}
error handlers now work with decoding and translating.
(Contributed by Serhiy Storchaka in bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676} and bpo-22286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22286}.)

@item 
The @ref{522,,-b} option now affects comparisons of @ref{172,,bytes} with
@ref{205,,int}.  (Contributed by Serhiy Storchaka in bpo-23681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23681}.)

@item 
New Kazakh @code{kz1048} and Tajik @code{koi8_t} @ref{78c,,codecs}.
(Contributed by Serhiy Storchaka in bpo-22682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22682} and bpo-22681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22681}.)

@item 
Property docstrings are now writable. This is especially useful for
@ref{1a1,,collections.namedtuple()} docstrings.
(Contributed by Berker Peksag in bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064}.)

@item 
Circular imports involving relative imports are now supported.
(Contributed by Brett Cannon and Antoine Pitrou in bpo-17636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17636}.)
@end itemize

@node 新增模块<5>,改进的模块<5>,其他语言特性修改<5>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 new-modules}@anchor{78d}
@subsection 新增模块


@menu
* typing: typing<5>. 
* zipapp: zipapp<2>. 

@end menu

@node typing<5>,zipapp<2>,,新增模块<5>
@anchor{whatsnew/3 5 typing}@anchor{78e}
@subsubsection typing


The new @ref{122,,typing} @ref{45d,,provisional} module
provides standard definitions and tools for function type annotations.
See @ref{72b,,Type Hints} for more information.

@node zipapp<2>,,typing<5>,新增模块<5>
@anchor{whatsnew/3 5 whatsnew-zipapp}@anchor{72c}@anchor{whatsnew/3 5 zipapp}@anchor{78f}
@subsubsection zipapp


The new @ref{14a,,zipapp} module (specified in 
@geindex Python 提高建议; PEP 441
PEP 441@footnote{https://www.python.org/dev/peps/pep-0441}) provides an API and
command line tool for creating executable Python Zip Applications, which
were introduced in Python 2.6 in bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468}, but which were not well
publicized, either at the time or since.

With the new module, bundling your application is as simple as putting all
the files, including a @code{__main__.py} file, into a directory @code{myapp}
and running:

@example
$ python -m zipapp myapp
$ python myapp.pyz
@end example

The module implementation has been contributed by Paul Moore in
bpo-23491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23491}.


@subsubheading 参见


@geindex Python 提高建议; PEP 441
PEP 441@footnote{https://www.python.org/dev/peps/pep-0441} -- Improving Python ZIP Application Support


@node 改进的模块<5>,其他模块级更改,新增模块<5>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 improved-modules}@anchor{790}
@subsection 改进的模块


@menu
* argparse: argparse<2>. 
* asyncio: asyncio<6>. 
* bz2:: 
* cgi:: 
* cmath: cmath<2>. 
* code:: 
* collections: collections<5>. 
* collections.abc: collections abc<2>. 
* compileall: compileall<3>. 
* concurrent.futures: concurrent futures<4>. 
* configparser:: 
* contextlib: contextlib<3>. 
* csv: csv<2>. 
* curses: curses<3>. 
* dbm: dbm<4>. 
* difflib:: 
* distutils: distutils<5>. 
* doctest:: 
* email: email<2>. 
* enum: enum<4>. 
* faulthandler: faulthandler<2>. 
* functools: functools<3>. 
* glob:: 
* gzip: gzip<2>. 
* heapq:: 
* http: http<2>. 
* http.client: http client<3>. 
* idlelib 与 IDLE: idlelib 与 IDLE<3>. 
* imaplib: imaplib<2>. 
* imghdr:: 
* importlib: importlib<6>. 
* inspect: inspect<4>. 
* io: io<3>. 
* ipaddress: ipaddress<3>. 
* json: json<2>. 
* linecache:: 
* locale: locale<3>. 
* logging: logging<4>. 
* lzma:: 
* math: math<5>. 
* multiprocessing: multiprocessing<5>. 
* operator:: 
* os: os<6>. 
* pathlib: pathlib<5>. 
* pickle: pickle<3>. 
* poplib: poplib<2>. 
* re: re<4>. 
* readline: readline<2>. 
* selectors:: 
* shutil: shutil<2>. 
* signal: signal<3>. 
* smtpd:: 
* smtplib: smtplib<2>. 
* sndhdr:: 
* socket: socket<6>. 
* ssl: ssl<6>. 
* sqlite3: sqlite3<3>. 
* subprocess: subprocess<3>. 
* sys: sys<6>. 
* sysconfig:: 
* tarfile: tarfile<3>. 
* threading: threading<3>. 
* time: time<5>. 
* timeit: timeit<2>. 
* tkinter: tkinter<5>. 
* traceback: traceback<2>. 
* types: types<2>. 
* unicodedata: unicodedata<5>. 
* unittest: unittest<3>. 
* unittest.mock: unittest mock<3>. 
* urllib:: 
* wsgiref:: 
* xmlrpc: xmlrpc<2>. 
* xml.sax: xml sax. 
* zipfile: zipfile<3>. 

@end menu

@node argparse<2>,asyncio<6>,,改进的模块<5>
@anchor{whatsnew/3 5 argparse}@anchor{791}
@subsubsection argparse


The @ref{792,,ArgumentParser} class now allows disabling
@ref{793,,abbreviated usage} of long options by setting
@ref{794,,allow_abbrev} to @code{False}.  (Contributed by Jonathan Paugh,
Steven Bethard, paul j3 and Daniel Eriksson in bpo-14910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14910}.)

@node asyncio<6>,bz2,argparse<2>,改进的模块<5>
@anchor{whatsnew/3 5 asyncio}@anchor{795}
@subsubsection asyncio


Since the @ref{9,,asyncio} module is @ref{45d,,provisional},
all changes introduced in Python 3.5 have also been backported to Python 3.4.x.

Notable changes in the @ref{9,,asyncio} module since Python 3.4.0:


@itemize *

@item 
New debugging APIs: @ref{796,,loop.set_debug()}
and @ref{797,,loop.get_debug()} methods.
(Contributed by Victor Stinner.)

@item 
The proactor event loop now supports SSL.
(Contributed by Antoine Pitrou and Victor Stinner in bpo-22560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22560}.)

@item 
A new @ref{798,,loop.is_closed()} method to
check if the event loop is closed.
(Contributed by Victor Stinner in bpo-21326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21326}.)

@item 
A new @ref{2e9,,loop.create_task()}
to conveniently create and schedule a new @ref{2e7,,Task}
for a coroutine.  The @code{create_task} method is also used by all
asyncio functions that wrap coroutines into tasks, such as
@ref{208,,asyncio.wait()}, @ref{3b3,,asyncio.gather()}, etc.
(Contributed by Victor Stinner.)

@item 
A new @ref{799,,transport.get_write_buffer_limits()}
method to inquire for @emph{high-} and @emph{low-} water limits of the flow
control.
(Contributed by Victor Stinner.)

@item 
The @code{async()} function is deprecated in favor of
@ref{619,,ensure_future()}.
(Contributed by Yury Selivanov.)

@item 
New @ref{79a,,loop.set_task_factory()} and
@ref{79b,,loop.get_task_factory()}
methods to customize the task factory that @ref{2e9,,loop.create_task()} method uses.  (Contributed by Yury
Selivanov.)

@item 
New @ref{79c,,Queue.join()} and
@ref{79d,,Queue.task_done()} queue methods.
(Contributed by Victor Stinner.)

@item 
The @code{JoinableQueue} class was removed, in favor of the
@ref{3bb,,asyncio.Queue} class.
(Contributed by Victor Stinner.)
@end itemize

3.5.1 中的更新：


@itemize *

@item 
The @ref{619,,ensure_future()} function and all functions that
use it, such as @ref{61a,,loop.run_until_complete()},
now accept all kinds of @ref{61b,,awaitable objects}.
(Contributed by Yury Selivanov.)

@item 
新增 @ref{61c,,run_coroutine_threadsafe()} 函数用于从其他线程向事件循环提交协程。（由 Vincent Michel 贡献。）

@item 
新增 @ref{61d,,Transport.is_closing()} 方法用于检查传输是否正在关闭或已经关闭。 （由 Yury Selivanov 贡献。）

@item 
@ref{46e,,loop.create_server()} 方法现在可以接受一个主机列表。 （由 Yann Sionneau 贡献。）
@end itemize

3.5.2 中的更新：


@itemize *

@item 
New @ref{61e,,loop.create_future()}
method to create Future objects.  This allows alternative event
loop implementations, such as
uvloop@footnote{https://github.com/MagicStack/uvloop}, to provide a faster
@ref{54e,,asyncio.Future} implementation.
(Contributed by Yury Selivanov.)

@item 
New @ref{61f,,loop.get_exception_handler()}
method to get the current exception handler.
(Contributed by Yury Selivanov.)

@item 
New @ref{620,,StreamReader.readuntil()}
method to read data from the stream until a separator bytes
sequence appears.
(Contributed by Mark Korenberg.)

@item 
The @ref{2ec,,loop.create_connection()}
and @ref{46e,,loop.create_server()}
methods are optimized to avoid calling the system @code{getaddrinfo}
function if the address is already resolved.
(Contributed by A. Jesse Jiryu Davis.)

@item 
The @ref{79e,,loop.sock_connect(sock@comma{} address)}
no longer requires the @emph{address} to be resolved prior to the call.
(Contributed by A. Jesse Jiryu Davis.)
@end itemize

@node bz2,cgi,asyncio<6>,改进的模块<5>
@anchor{whatsnew/3 5 bz2}@anchor{79f}
@subsubsection bz2


The @ref{7a0,,BZ2Decompressor.decompress}
method now accepts an optional @emph{max_length} argument to limit the maximum
size of decompressed data. (Contributed by Nikolaus Rath in bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}.)

@node cgi,cmath<2>,bz2,改进的模块<5>
@anchor{whatsnew/3 5 cgi}@anchor{7a1}
@subsubsection cgi


The @code{FieldStorage} class now supports the @ref{66b,,context manager}
protocol.  (Contributed by Berker Peksag in bpo-20289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20289}.)

@node cmath<2>,code,cgi,改进的模块<5>
@anchor{whatsnew/3 5 cmath}@anchor{7a2}
@subsubsection cmath


A new function @ref{784,,isclose()} provides a way to test for approximate
equality.  (Contributed by Chris Barker and Tal Einat in bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}.)

@node code,collections<5>,cmath<2>,改进的模块<5>
@anchor{whatsnew/3 5 code}@anchor{7a3}
@subsubsection code


The @ref{7a4,,InteractiveInterpreter.showtraceback()}
method now prints the full chained traceback, just like the interactive
interpreter.  (Contributed by Claudiu Popa in bpo-17442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17442}.)

@node collections<5>,collections abc<2>,code,改进的模块<5>
@anchor{whatsnew/3 5 collections}@anchor{7a5}
@subsubsection collections

@anchor{whatsnew/3 5 whatsnew-ordereddict}@anchor{734}
The @ref{2f1,,OrderedDict} class is now implemented in C, which
makes it 4 to 100 times faster.  (Contributed by Eric Snow in bpo-16991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16991}.)

@code{OrderedDict.items()},
@code{OrderedDict.keys()},
@code{OrderedDict.values()} views now support
@ref{2cd,,reversed()} iteration.
(Contributed by Serhiy Storchaka in bpo-19505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19505}.)

The @ref{633,,deque} class now defines
@ref{7a6,,index()}, @ref{7a7,,insert()}, and
@ref{7a8,,copy()}, and supports the @code{+} and @code{*} operators.
This allows deques to be recognized as a @ref{7a9,,MutableSequence}
and improves their substitutability for lists.
(Contributed by Raymond Hettinger in bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}.)

Docstrings produced by @ref{1a1,,namedtuple()} can now be updated:

@example
Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coodinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'
@end example

（由 Berker Peksag 在 bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064} 中贡献。）

The @ref{7aa,,UserString} class now implements the
@ref{7ab,,__getnewargs__()}, @ref{7ac,,__rmod__()}, @ref{7ad,,casefold()},
@ref{7ae,,format_map()}, @ref{7af,,isprintable()}, and @ref{7b0,,maketrans()}
methods to match the corresponding methods of @ref{206,,str}.
(Contributed by Joe Jevnik in bpo-22189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22189}.)

@node collections abc<2>,compileall<3>,collections<5>,改进的模块<5>
@anchor{whatsnew/3 5 collections-abc}@anchor{7b1}
@subsubsection collections.abc


The @code{Sequence.index()} method now
accepts @emph{start} and @emph{stop} arguments to match the corresponding methods
of @ref{1a2,,tuple}, @ref{1f9,,list}, etc.
(Contributed by Devin Jeanpierre in bpo-23086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23086}.)

A new @ref{7b2,,Generator} abstract base class. (Contributed
by Stefan Behnel in bpo-24018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24018}.)

New @ref{7b3,,Awaitable}, @ref{7b4,,Coroutine},
@ref{7b5,,AsyncIterator}, and
@ref{7b6,,AsyncIterable} abstract base classes.
(Contributed by Yury Selivanov in bpo-24184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24184}.)

For earlier Python versions, a backport of the new ABCs is available in an
external PyPI package@footnote{https://pypi.org/project/backports_abc}.

@node compileall<3>,concurrent futures<4>,collections abc<2>,改进的模块<5>
@anchor{whatsnew/3 5 compileall}@anchor{7b7}
@subsubsection compileall


A new @ref{20,,compileall} option, @code{-j @emph{N}}, allows running @emph{N} workers
simultaneously to perform parallel bytecode compilation.
The @ref{483,,compile_dir()} function has a corresponding @code{workers}
parameter.  (Contributed by Claudiu Popa in bpo-16104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16104}.)

Another new option, @code{-r}, allows controlling the maximum recursion
level for subdirectories.  (Contributed by Claudiu Popa in bpo-19628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19628}.)

The @code{-q} command line option can now be specified more than once, in
which case all output, including errors, will be suppressed.  The corresponding
@code{quiet} parameter in @ref{483,,compile_dir()},
@ref{7b8,,compile_file()}, and @ref{7b9,,compile_path()} can now
accept an integer value indicating the level of output suppression.
(Contributed by Thomas Kluyver in bpo-21338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21338}.)

@node concurrent futures<4>,configparser,compileall<3>,改进的模块<5>
@anchor{whatsnew/3 5 concurrent-futures}@anchor{7ba}
@subsubsection concurrent.futures


The @ref{7bb,,Executor.map()} method now accepts a
@emph{chunksize} argument to allow batching of tasks to improve performance when
@ref{196,,ProcessPoolExecutor()} is used.
(Contributed by Dan O'Reilly in bpo-11271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11271}.)

The number of workers in the @ref{18c,,ThreadPoolExecutor}
constructor is optional now.  The default value is 5 times the number of CPUs.
(Contributed by Claudiu Popa in bpo-21527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21527}.)

@node configparser,contextlib<3>,concurrent futures<4>,改进的模块<5>
@anchor{whatsnew/3 5 configparser}@anchor{7bc}
@subsubsection configparser


@ref{22,,configparser} now provides a way to customize the conversion
of values by specifying a dictionary of converters in the
@ref{5ad,,ConfigParser} constructor, or by defining them
as methods in @code{ConfigParser} subclasses.  Converters defined in
a parser instance are inherited by its section proxies.

示例:

@example
>>> import configparser
>>> conv = @{@}
>>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
>>> cfg = configparser.ConfigParser(converters=conv)
>>> cfg.read_string("""
... [s]
... list = a b c d e f g
... """)
>>> cfg.get('s', 'list')
'a b c d e f g'
>>> cfg.getlist('s', 'list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> section = cfg['s']
>>> section.getlist('list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
@end example

（由 Łukasz Langa 在 bpo-18159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18159} 中贡献。）

@node contextlib<3>,csv<2>,configparser,改进的模块<5>
@anchor{whatsnew/3 5 contextlib}@anchor{7bd}
@subsubsection contextlib


The new @ref{7be,,redirect_stderr()} @ref{66b,,context manager} (similar to
@ref{7bf,,redirect_stdout()}) makes it easier for utility scripts to
handle inflexible APIs that write their output to @ref{1eb,,sys.stderr} and
don't provide any options to redirect it:

@example
>>> import contextlib, io, logging
>>> f = io.StringIO()
>>> with contextlib.redirect_stderr(f):
...     logging.warning('warning')
...
>>> f.getvalue()
'WARNING:root:warning\n'
@end example

（由 Berker Peksag 在 bpo-22389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22389} 中贡献。）

@node csv<2>,curses<3>,contextlib<3>,改进的模块<5>
@anchor{whatsnew/3 5 csv}@anchor{7c0}
@subsubsection csv


The @ref{7c1,,writerow()} method now supports arbitrary iterables,
not just sequences.  (Contributed by Serhiy Storchaka in bpo-23171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23171}.)

@node curses<3>,dbm<4>,csv<2>,改进的模块<5>
@anchor{whatsnew/3 5 curses}@anchor{7c2}
@subsubsection curses


The new @ref{7c3,,update_lines_cols()} function updates the 
@geindex LINES
@geindex 环境变量; LINES
@code{LINES}
and 
@geindex COLS
@geindex 环境变量; COLS
@code{COLS} environment variables.  This is useful for detecting
manual screen resizing.  (Contributed by Arnon Yaari in bpo-4254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4254}.)

@node dbm<4>,difflib,curses<3>,改进的模块<5>
@anchor{whatsnew/3 5 dbm}@anchor{7c4}
@subsubsection dbm


@ref{3e9,,dumb.open} always creates a new database when the flag
has the value @code{"n"}.  (Contributed by Claudiu Popa in bpo-18039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18039}.)

@node difflib,distutils<5>,dbm<4>,改进的模块<5>
@anchor{whatsnew/3 5 difflib}@anchor{7c5}
@subsubsection difflib


The charset of HTML documents generated by
@ref{7c6,,HtmlDiff.make_file()}
can now be customized by using a new @emph{charset} keyword-only argument.
The default charset of HTML document changed from @code{"ISO-8859-1"}
to @code{"utf-8"}.
(Contributed by Berker Peksag in bpo-2052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2052}.)

The @ref{7c7,,diff_bytes()} function can now compare lists of byte
strings.  This fixes a regression from Python 2.
(Contributed by Terry J. Reedy and Greg Ward in bpo-17445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17445}.)

@node distutils<5>,doctest,difflib,改进的模块<5>
@anchor{whatsnew/3 5 distutils}@anchor{7c8}
@subsubsection distutils


Both the @code{build} and @code{build_ext} commands now accept a @code{-j} option to
enable parallel building of extension modules.
(Contributed by Antoine Pitrou in bpo-5309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5309}.)

The @ref{38,,distutils} module now supports @code{xz} compression, and can be
enabled by passing @code{xztar} as an argument to @code{bdist --format}.
(Contributed by Serhiy Storchaka in bpo-16314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16314}.)

@node doctest,email<2>,distutils<5>,改进的模块<5>
@anchor{whatsnew/3 5 doctest}@anchor{7c9}
@subsubsection doctest


The @ref{7ca,,DocTestSuite()} function returns an empty
@ref{7cb,,unittest.TestSuite} if @emph{module} contains no docstrings, instead of
raising @ref{16d,,ValueError}.  (Contributed by Glenn Jones in bpo-15916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15916}.)

@node email<2>,enum<4>,doctest,改进的模块<5>
@anchor{whatsnew/3 5 email}@anchor{7cc}
@subsubsection email


A new policy option @ref{7cd,,Policy.mangle_from_}
controls whether or not lines that start with @code{"From "} in email bodies are
prefixed with a @code{">"} character by generators.  The default is @code{True} for
@ref{643,,compat32} and @code{False} for all other policies.
(Contributed by Milan Oberkirch in bpo-20098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20098}.)

A new
@ref{7ce,,Message.get_content_disposition()}
method provides easy access to a canonical value for the
@code{Content-Disposition} header.
(Contributed by Abhilash Raj in bpo-21083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21083}.)

A new policy option @ref{7cf,,EmailPolicy.utf8}
can be set to @code{True} to encode email headers using the UTF-8 charset instead
of using encoded words.  This allows @code{Messages} to be formatted according to
@geindex RFC; RFC 6532
RFC 6532@footnote{https://tools.ietf.org/html/rfc6532.html} and used with an SMTP server that supports the 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html}
@code{SMTPUTF8} extension.  (Contributed by R. David Murray in
bpo-24211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24211}.)

The @ref{7d0,,mime.text.MIMEText} constructor now
accepts a @ref{7d1,,charset.Charset} instance.
(Contributed by Claude Paroz and Berker Peksag in bpo-16324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16324}.)

@node enum<4>,faulthandler<2>,email<2>,改进的模块<5>
@anchor{whatsnew/3 5 enum}@anchor{7d2}
@subsubsection enum


The @ref{496,,Enum} callable has a new parameter @emph{start} to
specify the initial number of enum values if only @emph{names} are provided:

@example
>>> Animal = enum.Enum('Animal', 'cat dog', start=10)
>>> Animal.cat
<Animal.cat: 10>
>>> Animal.dog
<Animal.dog: 11>
@end example

（由 Ethan Furman 在 bpo-21706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21706} 中贡献。）

@node faulthandler<2>,functools<3>,enum<4>,改进的模块<5>
@anchor{whatsnew/3 5 faulthandler}@anchor{7d3}
@subsubsection faulthandler


The @ref{64b,,enable()}, @ref{7d4,,register()},
@ref{7d5,,dump_traceback()} and
@ref{7d6,,dump_traceback_later()} functions now accept file
descriptors in addition to file-like objects.
(Contributed by Wei Wu in bpo-23566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23566}.)

@node functools<3>,glob,faulthandler<2>,改进的模块<5>
@anchor{whatsnew/3 5 functools}@anchor{7d7}
@subsubsection functools

@anchor{whatsnew/3 5 whatsnew-lrucache}@anchor{737}
Most of the @ref{2ff,,lru_cache()} machinery is now implemented in C, making
it significantly faster.  (Contributed by Matt Joiner, Alexey Kachayev, and
Serhiy Storchaka in bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}.)

@node glob,gzip<2>,functools<3>,改进的模块<5>
@anchor{whatsnew/3 5 glob}@anchor{7d8}
@subsubsection glob


The @ref{6c8,,iglob()} and @ref{6c7,,glob()} functions now support recursive
search in subdirectories, using the @code{"**"} pattern.
(Contributed by Serhiy Storchaka in bpo-13968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13968}.)

@node gzip<2>,heapq,glob,改进的模块<5>
@anchor{whatsnew/3 5 gzip}@anchor{7d9}
@subsubsection gzip


The @emph{mode} argument of the @ref{207,,GzipFile} constructor now
accepts @code{"x"} to request exclusive creation.
(Contributed by Tim Heaney in bpo-19222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19222}.)

@node heapq,http<2>,gzip<2>,改进的模块<5>
@anchor{whatsnew/3 5 heapq}@anchor{7da}
@subsubsection heapq


Element comparison in @ref{7db,,merge()} can now be customized by
passing a @ref{7dc,,key function} in a new optional @emph{key} keyword argument,
and a new optional @emph{reverse} keyword argument can be used to reverse element
comparison:

@example
>>> import heapq
>>> a = ['9', '777', '55555']
>>> b = ['88', '6666']
>>> list(heapq.merge(a, b, key=len))
['9', '88', '777', '6666', '55555']
>>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
['55555', '6666', '777', '88', '9']
@end example

（由 Raymond Hettinger 在 bpo-13742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13742} 中贡献。）

@node http<2>,http client<3>,heapq,改进的模块<5>
@anchor{whatsnew/3 5 http}@anchor{7dd}
@subsubsection http


A new @ref{1ac,,HTTPStatus} enum that defines a set of
HTTP status codes, reason phrases and long descriptions written in English.
(Contributed by Demian Brecht in bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}.)

@node http client<3>,idlelib 与 IDLE<3>,http<2>,改进的模块<5>
@anchor{whatsnew/3 5 http-client}@anchor{7de}
@subsubsection http.client


@ref{7df,,HTTPConnection.getresponse()}
now raises a @ref{7e0,,RemoteDisconnected} exception when a
remote server connection is closed unexpectedly.  Additionally, if a
@ref{7e1,,ConnectionError} (of which @code{RemoteDisconnected}
is a subclass) is raised, the client socket is now closed automatically,
and will reconnect on the next request:

@example
import http.client
conn = http.client.HTTPConnection('www.python.org')
for retries in range(3):
    try:
        conn.request('GET', '/')
        resp = conn.getresponse()
    except http.client.RemoteDisconnected:
        pass
@end example

（由 Martin Panter 在 bpo-3566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3566} 中贡献。）

@node idlelib 与 IDLE<3>,imaplib<2>,http client<3>,改进的模块<5>
@anchor{whatsnew/3 5 idlelib-and-idle}@anchor{7e2}
@subsubsection idlelib 与 IDLE


Since idlelib implements the IDLE shell and editor and is not intended for
import by other programs, it gets improvements with every release.  See
@code{Lib/idlelib/NEWS.txt} for a cumulative list of changes since 3.4.0,
as well as changes made in future 3.5.x releases. This file is also available
from the IDLE Help ‣ About IDLE dialog.

@node imaplib<2>,imghdr,idlelib 与 IDLE<3>,改进的模块<5>
@anchor{whatsnew/3 5 imaplib}@anchor{7e3}
@subsubsection imaplib


The @ref{1b0,,IMAP4} class now supports the @ref{66b,,context manager} protocol.
When used in a @ref{7e4,,with} statement, the IMAP4 @code{LOGOUT}
command will be called automatically at the end of the block.
(Contributed by Tarek Ziadé and Serhiy Storchaka in bpo-4972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4972}.)

The @ref{97,,imaplib} module now supports 
@geindex RFC; RFC 5161
RFC 5161@footnote{https://tools.ietf.org/html/rfc5161.html} (ENABLE Extension)
and 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://tools.ietf.org/html/rfc6855.html} (UTF-8 Support) via the @ref{7e5,,IMAP4.enable()}
method.  A new @ref{7e6,,IMAP4.utf8_enabled}
attribute tracks whether or not 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://tools.ietf.org/html/rfc6855.html} support is enabled.
(Contributed by Milan Oberkirch, R. David Murray, and Maciej Szulik in
bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}.)

The @ref{97,,imaplib} module now automatically encodes non-ASCII string usernames
and passwords using UTF-8, as recommended by the RFCs.  (Contributed by Milan
Oberkirch in bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}.)

@node imghdr,importlib<6>,imaplib<2>,改进的模块<5>
@anchor{whatsnew/3 5 imghdr}@anchor{7e7}
@subsubsection imghdr


The @ref{7e8,,what()} function now recognizes the
OpenEXR@footnote{http://www.openexr.com} format
(contributed by Martin Vignali and Claudiu Popa in bpo-20295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20295}),
and the WebP@footnote{https://en.wikipedia.org/wiki/WebP} format
(contributed by Fabrice Aneche and Claudiu Popa in bpo-20197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20197}.)

@node importlib<6>,inspect<4>,imghdr,改进的模块<5>
@anchor{whatsnew/3 5 importlib}@anchor{7e9}
@subsubsection importlib


The @ref{656,,util.LazyLoader} class allows for
lazy loading of modules in applications where startup time is important.
(Contributed by Brett Cannon in bpo-17621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17621}.)

The @ref{7ea,,abc.InspectLoader.source_to_code()}
method is now a static method.  This makes it easier to initialize a module
object with code compiled from a string by running
@code{exec(code, module.__dict__)}.
(Contributed by Brett Cannon in bpo-21156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21156}.)

The new @ref{7eb,,util.module_from_spec()}
function is now the preferred way to create a new module.  As opposed to
creating a @ref{7ec,,types.ModuleType} instance directly, this new function
will set the various import-controlled attributes based on the passed-in
spec object.  (Contributed by Brett Cannon in bpo-20383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20383}.)

@node inspect<4>,io<3>,importlib<6>,改进的模块<5>
@anchor{whatsnew/3 5 inspect}@anchor{7ed}
@subsubsection inspect


Both the @ref{7ee,,Signature} and @ref{7ef,,Parameter} classes are
now picklable and hashable.  (Contributed by Yury Selivanov in bpo-20726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20726}
and bpo-20334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20334}.)

A new
@ref{7f0,,BoundArguments.apply_defaults()}
method provides a way to set default values for missing arguments:

@example
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
@end example

（由 Yury Selivanov 在 bpo-24190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24190} 中贡献。）

A new class method
@ref{7f1,,Signature.from_callable()} makes
subclassing of @ref{7ee,,Signature} easier.  (Contributed
by Yury Selivanov and Eric Snow in bpo-17373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17373}.)

The @ref{65e,,signature()} function now accepts a @emph{follow_wrapped}
optional keyword argument, which, when set to @code{False}, disables automatic
following of @code{__wrapped__} links.
(Contributed by Yury Selivanov in bpo-20691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20691}.)

A set of new functions to inspect
@ref{73c,,coroutine functions} and
@ref{18a,,coroutine objects} has been added:
@ref{7f2,,iscoroutine()}, @ref{7f3,,iscoroutinefunction()},
@ref{7f4,,isawaitable()}, @ref{7f5,,getcoroutinelocals()},
and @ref{7f6,,getcoroutinestate()}.
(Contributed by Yury Selivanov in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017} and bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}.)

The @ref{7f7,,stack()}, @ref{7f8,,trace()},
@ref{7f9,,getouterframes()}, and @ref{7fa,,getinnerframes()}
functions now return a list of named tuples.
(Contributed by Daniel Shahaf in bpo-16808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16808}.)

@node io<3>,ipaddress<3>,inspect<4>,改进的模块<5>
@anchor{whatsnew/3 5 io}@anchor{7fb}
@subsubsection io


A new @ref{7fc,,BufferedIOBase.readinto1()}
method, that uses at most one call to the underlying raw stream's
@ref{7fd,,RawIOBase.read()} or
@ref{7fe,,RawIOBase.readinto()} methods.
(Contributed by Nikolaus Rath in bpo-20578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20578}.)

@node ipaddress<3>,json<2>,io<3>,改进的模块<5>
@anchor{whatsnew/3 5 ipaddress}@anchor{7ff}
@subsubsection ipaddress


Both the @ref{4af,,IPv4Network} and @ref{4ae,,IPv6Network} classes
now accept an @code{(address, netmask)} tuple argument, so as to easily construct
network objects from existing addresses:

@example
>>> import ipaddress
>>> ipaddress.IPv4Network(('127.0.0.0', 8))
IPv4Network('127.0.0.0/8')
>>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
IPv4Network('127.0.0.0/8')
@end example

（由 Peter Moody 和 Antoine Pitrou 在 bpo-16531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16531} 中贡献。）

A new @code{reverse_pointer} attribute for the
@ref{4af,,IPv4Network} and @ref{4ae,,IPv6Network} classes
returns the name of the reverse DNS PTR record:

@example
>>> import ipaddress
>>> addr = ipaddress.IPv4Address('127.0.0.1')
>>> addr.reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> addr6 = ipaddress.IPv6Address('::1')
>>> addr6.reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'
@end example

（由 Leon Weber 在 bpo-20480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20480} 中贡献。）

@node json<2>,linecache,ipaddress<3>,改进的模块<5>
@anchor{whatsnew/3 5 json}@anchor{800}
@subsubsection json


The @ref{a5,,json.tool} command line interface now preserves the order of keys in
JSON objects passed in input.  The new @code{--sort-keys} option can be used
to sort the keys alphabetically. (Contributed by Berker Peksag
in bpo-21650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21650}.)

JSON decoder now raises @ref{801,,JSONDecodeError} instead of
@ref{16d,,ValueError} to provide better context information about the error.
(Contributed by Serhiy Storchaka in bpo-19361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19361}.)

@node linecache,locale<3>,json<2>,改进的模块<5>
@anchor{whatsnew/3 5 linecache}@anchor{802}
@subsubsection linecache


A new @ref{803,,lazycache()} function can be used to capture information
about a non-file-based module to permit getting its lines later via
@ref{804,,getline()}. This avoids doing I/O until a line is actually
needed, without having to carry the module globals around indefinitely.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

@node locale<3>,logging<4>,linecache,改进的模块<5>
@anchor{whatsnew/3 5 locale}@anchor{805}
@subsubsection locale


A new @ref{806,,delocalize()} function can be used to convert a string into
a normalized number string, taking the @code{LC_NUMERIC} settings into account:

@example
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> locale.delocalize('1.234,56')
'1234.56'
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.delocalize('1,234.56')
'1234.56'
@end example

（由 Cédric Krier 在 bpo-13918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13918} 中贡献。）

@node logging<4>,lzma,locale<3>,改进的模块<5>
@anchor{whatsnew/3 5 logging}@anchor{807}
@subsubsection logging


All logging methods (@ref{4b6,,Logger} @ref{808,,log()},
@ref{809,,exception()}, @ref{80a,,critical()},
@ref{80b,,debug()}, etc.), now accept exception instances
as an @emph{exc_info} argument, in addition to boolean values and exception
tuples:

@example
>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError as ex:
...     logging.error('exception', exc_info=ex)
ERROR:root:exception
@end example

（由 Yury Selivanov 在 bpo-20537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20537} 中贡献。）

The @ref{80c,,handlers.HTTPHandler} class now
accepts an optional @ref{4f2,,ssl.SSLContext} instance to configure SSL
settings used in an HTTP connection.
(Contributed by Alex Gaynor in bpo-22788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22788}.)

The @ref{80d,,handlers.QueueListener} class now
takes a @emph{respect_handler_level} keyword argument which, if set to @code{True},
will pass messages to handlers taking handler levels into account.
(Contributed by Vinay Sajip.)

@node lzma,math<5>,logging<4>,改进的模块<5>
@anchor{whatsnew/3 5 lzma}@anchor{80e}
@subsubsection lzma


The @ref{80f,,LZMADecompressor.decompress()}
method now accepts an optional @emph{max_length} argument to limit the maximum
size of decompressed data.
(Contributed by Martin Panter in bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}.)

@node math<5>,multiprocessing<5>,lzma,改进的模块<5>
@anchor{whatsnew/3 5 math}@anchor{810}
@subsubsection math


Two new constants have been added to the @ref{b1,,math} module: @ref{62a,,inf}
and @ref{62b,,nan}.  (Contributed by Mark Dickinson in bpo-23185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23185}.)

A new function @ref{783,,isclose()} provides a way to test for approximate
equality. (Contributed by Chris Barker and Tal Einat in bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}.)

A new @ref{1bf,,gcd()} function has been added.  The @code{fractions.gcd()}
function is now deprecated. (Contributed by Mark Dickinson and Serhiy
Storchaka in bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}.)

@node multiprocessing<5>,operator,math<5>,改进的模块<5>
@anchor{whatsnew/3 5 multiprocessing}@anchor{811}
@subsubsection multiprocessing


@ref{812,,sharedctypes.synchronized()}
objects now support the @ref{66b,,context manager} protocol.
(Contributed by Charles-François Natali in bpo-21565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21565}.)

@node operator,os<6>,multiprocessing<5>,改进的模块<5>
@anchor{whatsnew/3 5 operator}@anchor{813}
@subsubsection operator


@ref{814,,attrgetter()}, @ref{393,,itemgetter()},
and @ref{815,,methodcaller()} objects now support pickling.
(Contributed by Josh Rosenberg and Serhiy Storchaka in bpo-22955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22955}.)

New @ref{816,,matmul()} and @ref{817,,imatmul()} functions
to perform matrix multiplication.
(Contributed by Benjamin Peterson in bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}.)

@node os<6>,pathlib<5>,operator,改进的模块<5>
@anchor{whatsnew/3 5 os}@anchor{818}
@subsubsection os


The new @ref{390,,scandir()} function returning an iterator of
@ref{5f3,,DirEntry} objects has been added.  If possible, @ref{390,,scandir()}
extracts file attributes while scanning a directory, removing the need to
perform subsequent system calls to determine file type or attributes, which may
significantly improve performance.  (Contributed by Ben Hoyt with the help
of Victor Stinner in bpo-22524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22524}.)

On Windows, a new
@ref{819,,stat_result.st_file_attributes}
attribute is now available.  It corresponds to the @code{dwFileAttributes} member
of the @code{BY_HANDLE_FILE_INFORMATION} structure returned by
@code{GetFileInformationByHandle()}.  (Contributed by Ben Hoyt in bpo-21719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21719}.)

The @ref{5d4,,urandom()} function now uses the @code{getrandom()} syscall on Linux 3.17
or newer, and @code{getentropy()} on OpenBSD 5.6 and newer, removing the need to
use @code{/dev/urandom} and avoiding failures due to potential file descriptor
exhaustion.  (Contributed by Victor Stinner in bpo-22181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22181}.)

New @ref{81a,,get_blocking()} and @ref{81b,,set_blocking()} functions allow
getting and setting a file descriptor's blocking mode (@ref{81c,,O_NONBLOCK}.)
(Contributed by Victor Stinner in bpo-22054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22054}.)

The @ref{81d,,truncate()} and @ref{75f,,ftruncate()} functions are now supported
on Windows.  (Contributed by Steve Dower in bpo-23668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23668}.)

There is a new @ref{81e,,os.path.commonpath()} function returning the longest
common sub-path of each passed pathname.  Unlike the
@ref{81f,,os.path.commonprefix()} function, it always returns a valid
path:

@example
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
@end example

（由 Rafik Draoui 和 Serhiy Storchaka 在 bpo-10395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10395} 中贡献。）

@node pathlib<5>,pickle<3>,os<6>,改进的模块<5>
@anchor{whatsnew/3 5 pathlib}@anchor{820}
@subsubsection pathlib


The new @ref{821,,Path.samefile()} method can be used
to check whether the path points to the same file as another path, which can
be either another @ref{336,,Path} object, or a string:

@example
>>> import pathlib
>>> p1 = pathlib.Path('/etc/hosts')
>>> p2 = pathlib.Path('/etc/../etc/hosts')
>>> p1.samefile(p2)
True
@end example

（由 Vajrasky Kok 和 Antoine Pitrou 在 bpo-19775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19775} 中贡献。）

The @ref{822,,Path.mkdir()} method now accepts a new optional
@emph{exist_ok} argument to match @code{mkdir -p} and @ref{4cc,,os.makedirs()}
functionality.  (Contributed by Berker Peksag in bpo-21539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21539}.)

There is a new @ref{823,,Path.expanduser()} method to
expand @code{~} and @code{~user} prefixes.  (Contributed by Serhiy Storchaka and
Claudiu Popa in bpo-19776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19776}.)

A new @ref{824,,Path.home()} class method can be used to get
a @ref{336,,Path} instance representing the user’s home
directory.
(Contributed by Victor Salgado and Mayank Tripathi in bpo-19777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19777}.)

New @ref{825,,Path.write_text()},
@ref{826,,Path.read_text()},
@ref{827,,Path.write_bytes()},
@ref{828,,Path.read_bytes()} methods to simplify
read/write operations on files.

The following code snippet will create or rewrite existing file
@code{~/spam42}:

@example
>>> import pathlib
>>> p = pathlib.Path('~/spam42')
>>> p.expanduser().write_text('ham')
3
@end example

（由 Christopher Welborn 在 bpo-20218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20218} 中贡献。）

@node pickle<3>,poplib<2>,pathlib<5>,改进的模块<5>
@anchor{whatsnew/3 5 pickle}@anchor{829}
@subsubsection pickle


Nested objects, such as unbound methods or nested classes, can now be pickled
using @ref{670,,pickle protocols} older than protocol version 4.
Protocol version 4 already supports these cases.  (Contributed by Serhiy
Storchaka in bpo-23611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23611}.)

@node poplib<2>,re<4>,pickle<3>,改进的模块<5>
@anchor{whatsnew/3 5 poplib}@anchor{82a}
@subsubsection poplib


A new @ref{82b,,POP3.utf8()} command enables 
@geindex RFC; RFC 6856
RFC 6856@footnote{https://tools.ietf.org/html/rfc6856.html}
(Internationalized Email) support, if a POP server supports it.
(Contributed by Milan OberKirch in bpo-21804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21804}.)

@node re<4>,readline<2>,poplib<2>,改进的模块<5>
@anchor{whatsnew/3 5 re}@anchor{82c}
@subsubsection re


References and conditional references to groups with fixed length are now
allowed in lookbehind assertions:

@example
>>> import re
>>> pat = re.compile(r'(a|b).(?<=\1)c')
>>> pat.match('aac')
<_sre.SRE_Match object; span=(0, 3), match='aac'>
>>> pat.match('bbc')
<_sre.SRE_Match object; span=(0, 3), match='bbc'>
@end example

（由 Serhiy Storchaka 在 bpo-9179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9179} 中贡献。）

The number of capturing groups in regular expressions is no longer limited to
100.  (Contributed by Serhiy Storchaka in bpo-22437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22437}.)

The @ref{582,,sub()} and @ref{82d,,subn()} functions now replace unmatched
groups with empty strings instead of raising an exception.
(Contributed by Serhiy Storchaka in bpo-1519638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1519638}.)

The @ref{82e,,re.error} exceptions have new attributes,
@ref{82f,,msg}, @ref{830,,pattern},
@ref{831,,pos}, @ref{832,,lineno},
and @ref{833,,colno}, that provide better context
information about the error:

@example
>>> re.compile("""
...     (?x)
...     .++
... """)
Traceback (most recent call last):
   ...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)
@end example

（由 Serhiy Storchaka 在 bpo-22578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22578} 中贡献。）

@node readline<2>,selectors,re<4>,改进的模块<5>
@anchor{whatsnew/3 5 readline}@anchor{834}
@subsubsection readline


A new @ref{835,,append_history_file()} function can be used to append
the specified number of trailing elements in history to the given file.
(Contributed by Bruno Cauet in bpo-22940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22940}.)

@node selectors,shutil<2>,readline<2>,改进的模块<5>
@anchor{whatsnew/3 5 selectors}@anchor{836}
@subsubsection selectors


The new @ref{558,,DevpollSelector} supports efficient
@code{/dev/poll} polling on Solaris.
(Contributed by Giampaolo Rodola' in bpo-18931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18931}.)

@node shutil<2>,signal<3>,selectors,改进的模块<5>
@anchor{whatsnew/3 5 shutil}@anchor{837}
@subsubsection shutil


The @ref{38c,,move()} function now accepts a @emph{copy_function} argument,
allowing, for example, the @ref{38a,,copy()} function to be used instead of
the default @ref{38b,,copy2()} if there is a need to ignore file metadata
when moving.
(Contributed by Claudiu Popa in bpo-19840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19840}.)

The @ref{34f,,make_archive()} function now supports the @emph{xztar} format.
(Contributed by Serhiy Storchaka in bpo-5411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5411}.)

@node signal<3>,smtpd,shutil<2>,改进的模块<5>
@anchor{whatsnew/3 5 signal}@anchor{838}
@subsubsection signal


On Windows, the @ref{4dd,,set_wakeup_fd()} function now also supports
socket handles.  (Contributed by Victor Stinner in bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}.)

Various @code{SIG*} constants in the @ref{ea,,signal} module have been converted into
@ref{79,,Enums}.  This allows meaningful names to be printed
during debugging, instead of integer "magic numbers".
(Contributed by Giampaolo Rodola' in bpo-21076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21076}.)

@node smtpd,smtplib<2>,signal<3>,改进的模块<5>
@anchor{whatsnew/3 5 smtpd}@anchor{839}
@subsubsection smtpd


Both the @ref{703,,SMTPServer} and @ref{702,,SMTPChannel} classes now
accept a @emph{decode_data} keyword argument to determine if the @code{DATA} portion of
the SMTP transaction is decoded using the @code{"utf-8"} codec or is instead
provided to the
@ref{704,,SMTPServer.process_message()}
method as a byte string.  The default is @code{True} for backward compatibility
reasons, but will change to @code{False} in Python 3.6.  If @emph{decode_data} is set
to @code{False}, the @code{process_message} method must be prepared to accept keyword
arguments.
(Contributed by Maciej Szulik in bpo-19662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19662}.)

The @ref{703,,SMTPServer} class now advertises the @code{8BITMIME} extension
(
@geindex RFC; RFC 6152
RFC 6152@footnote{https://tools.ietf.org/html/rfc6152.html}) if @emph{decode_data} has been set @code{True}.  If the client
specifies @code{BODY=8BITMIME} on the @code{MAIL} command, it is passed to
@ref{704,,SMTPServer.process_message()}
via the @emph{mail_options} keyword.
(Contributed by Milan Oberkirch and R.  David Murray in bpo-21795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21795}.)

The @ref{703,,SMTPServer} class now also supports the @code{SMTPUTF8}
extension (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html}: Internationalized Email).  If the client specified
@code{SMTPUTF8 BODY=8BITMIME} on the @code{MAIL} command, they are passed to
@ref{704,,SMTPServer.process_message()}
via the @emph{mail_options} keyword.  It is the responsibility of the
@code{process_message} method to correctly handle the @code{SMTPUTF8} data.
(Contributed by Milan Oberkirch in bpo-21725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21725}.)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the @ref{703,,SMTPServer} constructor, and have it
successfully connect.  (Contributed by Milan Oberkirch in bpo-14758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14758}.)

@node smtplib<2>,sndhdr,smtpd,改进的模块<5>
@anchor{whatsnew/3 5 smtplib}@anchor{83a}
@subsubsection smtplib


A new @ref{83b,,SMTP.auth()} method provides a convenient way to
implement custom authentication mechanisms. (Contributed by Milan
Oberkirch in bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}.)

The @ref{83c,,SMTP.set_debuglevel()} method now
accepts an additional debuglevel (2), which enables timestamps in debug
messages. (Contributed by Gavin Chappell and Maciej Szulik in bpo-16914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16914}.)

Both the @ref{83d,,SMTP.sendmail()} and
@ref{83e,,SMTP.send_message()} methods now
support 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html} (SMTPUTF8).
(Contributed by Milan Oberkirch and R. David Murray in bpo-22027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22027}.)

@node sndhdr,socket<6>,smtplib<2>,改进的模块<5>
@anchor{whatsnew/3 5 sndhdr}@anchor{83f}
@subsubsection sndhdr


The @ref{840,,what()} and @ref{841,,whathdr()} functions  now return
a @ref{1a1,,namedtuple()}.  (Contributed by Claudiu Popa in
bpo-18615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18615}.)

@node socket<6>,ssl<6>,sndhdr,改进的模块<5>
@anchor{whatsnew/3 5 socket}@anchor{842}
@subsubsection socket


Functions with timeouts now use a monotonic clock, instead of a system clock.
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

A new @ref{843,,socket.sendfile()} method allows
sending a file over a socket by using the high-performance @ref{46a,,os.sendfile()}
function on UNIX, resulting in uploads being from 2 to 3 times faster than when
using plain @ref{777,,socket.send()}.
(Contributed by Giampaolo Rodola' in bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}.)

The @ref{778,,socket.sendall()} method no longer resets the
socket timeout every time bytes are received or sent.  The socket timeout is
now the maximum total duration to send all data.
(Contributed by Victor Stinner in bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}.)

The @emph{backlog} argument of the @ref{844,,socket.listen()}
method is now optional.  By default it is set to
@ref{845,,SOMAXCONN} or to @code{128}, whichever is less.
(Contributed by Charles-François Natali in bpo-21455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21455}.)

@node ssl<6>,sqlite3<3>,socket<6>,改进的模块<5>
@anchor{whatsnew/3 5 ssl}@anchor{846}
@subsubsection ssl


@menu
* 内存 BIO 支持:: 
* Application-Layer Protocol Negotiation Support:: 
* Other Changes:: 

@end menu

@node 内存 BIO 支持,Application-Layer Protocol Negotiation Support,,ssl<6>
@anchor{whatsnew/3 5 memory-bio-support}@anchor{847}@anchor{whatsnew/3 5 whatsnew-sslmemorybio}@anchor{735}
@subsubsection 内存 BIO 支持


（由 Geert Jansen 在 bpo-21965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21965} 中贡献。）

The new @ref{4f1,,SSLObject} class has been added to provide SSL protocol
support for cases when the network I/O capabilities of @ref{192,,SSLSocket}
are not necessary or are suboptimal.  @code{SSLObject} represents
an SSL protocol instance, but does not implement any network I/O methods, and
instead provides a memory buffer interface.  The new @ref{848,,MemoryBIO}
class can be used to pass data between Python and an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in frameworks
implementing asynchronous I/O for which @ref{192,,SSLSocket}'s readiness
model ("select/poll") is inefficient.

A new @ref{4f4,,SSLContext.wrap_bio()} method can be used
to create a new @code{SSLObject} instance.

@node Application-Layer Protocol Negotiation Support,Other Changes,内存 BIO 支持,ssl<6>
@anchor{whatsnew/3 5 application-layer-protocol-negotiation-support}@anchor{849}
@subsubsection Application-Layer Protocol Negotiation Support


（由 Benjamin Peterson 在 bpo-20188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20188} 中贡献。）

Where OpenSSL support is present, the @ref{f3,,ssl} module now implements
the @emph{Application-Layer Protocol Negotiation} TLS extension as described
in 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://tools.ietf.org/html/rfc7301.html}.

The new @ref{84a,,SSLContext.set_alpn_protocols()}
can be used to specify which protocols a socket should advertise during
the TLS handshake.

The new
@ref{84b,,SSLSocket.selected_alpn_protocol()}
returns the protocol that was selected during the TLS handshake.
The @ref{84c,,HAS_ALPN} flag indicates whether ALPN support is present.

@node Other Changes,,Application-Layer Protocol Negotiation Support,ssl<6>
@anchor{whatsnew/3 5 other-changes}@anchor{84d}
@subsubsection Other Changes


There is a new @ref{84e,,SSLSocket.version()} method to
query the actual protocol version in use.
(Contributed by Antoine Pitrou in bpo-20421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20421}.)

The @ref{192,,SSLSocket} class now implements
a @code{SSLSocket.sendfile()} method.
(Contributed by Giampaolo Rodola' in bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}.)

The @code{SSLSocket.send()} method now raises either
the @ref{84f,,ssl.SSLWantReadError} or @ref{850,,ssl.SSLWantWriteError} exception on a
non-blocking socket if the operation would block. Previously, it would return
@code{0}.  (Contributed by Nikolaus Rath in bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}.)

The @ref{851,,cert_time_to_seconds()} function now interprets the input time
as UTC and not as local time, per 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://tools.ietf.org/html/rfc5280.html}.  Additionally, the return
value is always an @ref{205,,int}. (Contributed by Akira Li in bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}.)

New @code{SSLObject.shared_ciphers()} and
@ref{852,,SSLSocket.shared_ciphers()} methods return
the list of ciphers sent by the client during the handshake.
(Contributed by Benjamin Peterson in bpo-23186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23186}.)

The @ref{853,,SSLSocket.do_handshake()},
@ref{854,,SSLSocket.read()},
@code{SSLSocket.shutdown()}, and
@ref{855,,SSLSocket.write()} methods of the @ref{192,,SSLSocket}
class no longer reset the socket timeout every time bytes are received or sent.
The socket timeout is now the maximum total duration of the method.
(Contributed by Victor Stinner in bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}.)

The @ref{4eb,,match_hostname()} function now supports matching of IP addresses.
(Contributed by Antoine Pitrou in bpo-23239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23239}.)

@node sqlite3<3>,subprocess<3>,ssl<6>,改进的模块<5>
@anchor{whatsnew/3 5 sqlite3}@anchor{856}
@subsubsection sqlite3


The @ref{857,,Row} class now fully supports the sequence protocol,
in particular @ref{2cd,,reversed()} iteration and slice indexing.
(Contributed by Claudiu Popa in bpo-10203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10203}; by Lucas Sinclair,
Jessica McKellar, and  Serhiy Storchaka in bpo-13583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13583}.)

@node subprocess<3>,sys<6>,sqlite3<3>,改进的模块<5>
@anchor{whatsnew/3 5 subprocess}@anchor{858}@anchor{whatsnew/3 5 whatsnew-subprocess}@anchor{738}
@subsubsection subprocess


The new @ref{4fb,,run()} function has been added.
It runs the specified command and returns a
@ref{859,,CompletedProcess} object, which describes a finished
process.  The new API is more consistent and is the recommended approach
to invoking subprocesses in Python code that does not need to maintain
compatibility with earlier Python versions.
(Contributed by Thomas Kluyver in bpo-23342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23342}.)

例如:

@example
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
@end example

@node sys<6>,sysconfig,subprocess<3>,改进的模块<5>
@anchor{whatsnew/3 5 sys}@anchor{85a}
@subsubsection sys


A new @code{set_coroutine_wrapper()} function allows setting a global
hook that will be called whenever a @ref{18a,,coroutine object}
is created by an @ref{3b1,,async def} function.  A corresponding
@code{get_coroutine_wrapper()} can be used to obtain a currently set
wrapper.  Both functions are @ref{45d,,provisional},
and are intended for debugging purposes only.  (Contributed by Yury Selivanov
in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}.)

A new @ref{85b,,is_finalizing()} function can be used to check if the Python
interpreter is @ref{85c,,shutting down}.
(Contributed by Antoine Pitrou in bpo-22696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22696}.)

@node sysconfig,tarfile<3>,sys<6>,改进的模块<5>
@anchor{whatsnew/3 5 sysconfig}@anchor{85d}
@subsubsection sysconfig


The name of the user scripts directory on Windows now includes the first
two components of the Python version. (Contributed by Paul Moore
in bpo-23437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23437}.)

@node tarfile<3>,threading<3>,sysconfig,改进的模块<5>
@anchor{whatsnew/3 5 tarfile}@anchor{85e}
@subsubsection tarfile


The @emph{mode} argument of the @ref{85f,,open()} function now accepts @code{"x"}
to request exclusive creation.  (Contributed by Berker Peksag in bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}.)

The @ref{860,,TarFile.extractall()} and
@ref{861,,TarFile.extract()} methods now take a keyword
argument @emph{numeric_owner}.  If set to @code{True}, the extracted files and
directories will be owned by the numeric @code{uid} and @code{gid} from the tarfile.
If set to @code{False} (the default, and the behavior in versions prior to 3.5),
they will be owned by the named user and group in the tarfile.
(Contributed by Michael Vogt and Eric Smith in bpo-23193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23193}.)

The @ref{862,,TarFile.list()} now accepts an optional
@emph{members} keyword argument that can be set to a subset of the list returned
by @ref{863,,TarFile.getmembers()}.
(Contributed by Serhiy Storchaka in bpo-21549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21549}.)

@node threading<3>,time<5>,tarfile<3>,改进的模块<5>
@anchor{whatsnew/3 5 threading}@anchor{864}
@subsubsection threading


Both the @ref{865,,Lock.acquire()} and
@ref{866,,RLock.acquire()} methods
now use a monotonic clock for timeout management.
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

@node time<5>,timeit<2>,threading<3>,改进的模块<5>
@anchor{whatsnew/3 5 time}@anchor{867}
@subsubsection time


The @ref{868,,monotonic()} function is now always available.
(Contributed by Victor Stinner in bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}.)

@node timeit<2>,tkinter<5>,time<5>,改进的模块<5>
@anchor{whatsnew/3 5 timeit}@anchor{869}
@subsubsection timeit


A new command line option @code{-u} or @code{--unit=@emph{U}} can be used to specify the time
unit for the timer output.  Supported options are @code{usec}, @code{msec},
or @code{sec}.  (Contributed by Julian Gindi in bpo-18983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18983}.)

The @ref{86a,,timeit()} function has a new @emph{globals} parameter for
specifying the namespace in which the code will be running.
(Contributed by Ben Roberts in bpo-2527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2527}.)

@node tkinter<5>,traceback<2>,timeit<2>,改进的模块<5>
@anchor{whatsnew/3 5 tkinter}@anchor{86b}
@subsubsection tkinter


The @code{tkinter._fix} module used for setting up the Tcl/Tk environment
on Windows has been replaced by a private function in the @code{_tkinter}
module which makes no permanent changes to environment variables.
(Contributed by Zachary Ware in bpo-20035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20035}.)

@node traceback<2>,types<2>,tkinter<5>,改进的模块<5>
@anchor{whatsnew/3 5 traceback}@anchor{86c}@anchor{whatsnew/3 5 whatsnew-traceback}@anchor{739}
@subsubsection traceback


New @ref{86d,,walk_stack()} and @ref{86e,,walk_tb()}
functions to conveniently traverse frame and traceback objects.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

New lightweight classes: @ref{86f,,TracebackException},
@ref{870,,StackSummary}, and @ref{871,,FrameSummary}.
(Contributed by Robert Collins in bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}.)

Both the @ref{872,,print_tb()} and @ref{873,,print_stack()} functions
now support negative values for the @emph{limit} argument.
(Contributed by Dmitry Kazakov in bpo-22619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22619}.)

@node types<2>,unicodedata<5>,traceback<2>,改进的模块<5>
@anchor{whatsnew/3 5 types}@anchor{874}
@subsubsection types


A new @ref{875,,coroutine()} function to transform
@ref{561,,generator} and
@ref{7b2,,generator-like} objects into
@ref{61b,,awaitables}.
(Contributed by Yury Selivanov in bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}.)

A new type called @ref{876,,CoroutineType}, which is used for
@ref{18a,,coroutine} objects created by @ref{3b1,,async def} functions.
(Contributed by Yury Selivanov in bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}.)

@node unicodedata<5>,unittest<3>,types<2>,改进的模块<5>
@anchor{whatsnew/3 5 unicodedata}@anchor{877}
@subsubsection unicodedata


The @ref{123,,unicodedata} module now uses data from Unicode 8.0.0@footnote{http://unicode.org/versions/Unicode8.0.0/}.

@node unittest<3>,unittest mock<3>,unicodedata<5>,改进的模块<5>
@anchor{whatsnew/3 5 unittest}@anchor{878}
@subsubsection unittest


The @ref{879,,TestLoader.loadTestsFromModule()}
method now accepts a keyword-only argument @emph{pattern} which is passed to
@code{load_tests} as the third argument.  Found packages are now checked for
@code{load_tests} regardless of whether their path matches @emph{pattern}, because it
is impossible for a package name to match the default pattern.
(Contributed by Robert Collins and Barry A. Warsaw in bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}.)

Unittest discovery errors now are exposed in the
@ref{87a,,TestLoader.errors} attribute of the
@ref{87b,,TestLoader} instance.
(Contributed by Robert Collins in bpo-19746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19746}.)

A new command line option @code{--locals} to show local variables in
tracebacks.  (Contributed by Robert Collins in bpo-22936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22936}.)

@node unittest mock<3>,urllib,unittest<3>,改进的模块<5>
@anchor{whatsnew/3 5 unittest-mock}@anchor{87c}
@subsubsection unittest.mock


The @ref{37a,,Mock} class has the following improvements:


@itemize *

@item 
The class constructor has a new @emph{unsafe} parameter, which causes mock
objects to raise @ref{4aa,,AttributeError} on attribute names starting
with @code{"assert"}.
(Contributed by Kushal Das in bpo-21238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21238}.)

@item 
A new @ref{87d,,Mock.assert_not_called()}
method to check if the mock object was called.
(Contributed by Kushal Das in bpo-21262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21262}.)
@end itemize

The @ref{87e,,MagicMock} class now supports @ref{87f,,__truediv__()},
@ref{880,,__divmod__()} and @ref{745,,__matmul__()} operators.
(Contributed by Johannes Baiter in bpo-20968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20968}, and Håkan Lövdahl
in bpo-23581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23581} and bpo-23568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23568}.)

It is no longer necessary to explicitly pass @code{create=True} to the
@ref{881,,patch()} function when patching builtin names.
(Contributed by Kushal Das in bpo-17660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17660}.)

@node urllib,wsgiref,unittest mock<3>,改进的模块<5>
@anchor{whatsnew/3 5 urllib}@anchor{882}
@subsubsection urllib


A new
@ref{883,,request.HTTPPasswordMgrWithPriorAuth}
class allows HTTP Basic Authentication credentials to be managed so as to
eliminate unnecessary @code{401} response handling, or to unconditionally send
credentials on the first request in order to communicate with servers that
return a @code{404} response instead of a @code{401} if the @code{Authorization} header
is not sent. (Contributed by Matej Cepl in bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494} and Akshit Khurana in
bpo-7159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7159}.)

A new @emph{quote_via} argument for the
@ref{884,,parse.urlencode()}
function provides a way to control the encoding of query parts if needed.
(Contributed by Samwyse and Arnon Yaari in bpo-13866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13866}.)

The @ref{885,,request.urlopen()} function accepts an
@ref{4f2,,ssl.SSLContext} object as a @emph{context} argument, which will be used for
the HTTPS connection.  (Contributed by Alex Gaynor in bpo-22366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22366}.)

The @ref{886,,parse.urljoin()} was updated to use the
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html} semantics for the resolution of relative URLs, rather than
@geindex RFC; RFC 1808
RFC 1808@footnote{https://tools.ietf.org/html/rfc1808.html} and 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://tools.ietf.org/html/rfc2396.html}.
(Contributed by Demian Brecht and Senthil Kumaran in bpo-22118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22118}.)

@node wsgiref,xmlrpc<2>,urllib,改进的模块<5>
@anchor{whatsnew/3 5 wsgiref}@anchor{887}
@subsubsection wsgiref


The @emph{headers} argument of the @ref{888,,headers.Headers}
class constructor is now optional.
(Contributed by Pablo Torres Navarrete and SilentGhost in bpo-5800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5800}.)

@node xmlrpc<2>,xml sax,wsgiref,改进的模块<5>
@anchor{whatsnew/3 5 xmlrpc}@anchor{889}
@subsubsection xmlrpc


The @ref{386,,client.ServerProxy} class now supports
the @ref{66b,,context manager} protocol.
(Contributed by Claudiu Popa in bpo-20627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20627}.)

The @ref{386,,client.ServerProxy} constructor now accepts
an optional @ref{4f2,,ssl.SSLContext} instance.
(Contributed by Alex Gaynor in bpo-22960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22960}.)

@node xml sax,zipfile<3>,xmlrpc<2>,改进的模块<5>
@anchor{whatsnew/3 5 xml-sax}@anchor{88a}
@subsubsection xml.sax


SAX parsers now support a character stream of the
@ref{88b,,xmlreader.InputSource} object.
(Contributed by Serhiy Storchaka in bpo-2175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2175}.)

@ref{88c,,parseString()} now accepts a @ref{206,,str} instance.
(Contributed by Serhiy Storchaka in bpo-10590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10590}.)

@node zipfile<3>,,xml sax,改进的模块<5>
@anchor{whatsnew/3 5 zipfile}@anchor{88d}
@subsubsection zipfile


ZIP output can now be written to unseekable streams.
(Contributed by Serhiy Storchaka in bpo-23252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23252}.)

The @emph{mode} argument of @ref{6bd,,ZipFile.open()} method now
accepts @code{"x"} to request exclusive creation.
(Contributed by Serhiy Storchaka in bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}.)

@node 其他模块级更改,性能优化<5>,改进的模块<5>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 other-module-level-changes}@anchor{88e}
@subsection 其他模块级更改


Many functions in the @ref{b3,,mmap}, @ref{c6,,ossaudiodev}, @ref{ef,,socket},
@ref{f3,,ssl}, and @ref{1b,,codecs} modules now accept writable
@ref{6e9,,bytes-like objects}.
(Contributed by Serhiy Storchaka in bpo-23001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23001}.)

@node 性能优化<5>,构建和 C API 的改变<3>,其他模块级更改,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 optimizations}@anchor{88f}
@subsection 性能优化


The @ref{751,,os.walk()} function has been sped up by 3 to 5 times on POSIX systems,
and by 7 to 20 times on Windows.  This was done using the new @ref{390,,os.scandir()}
function, which exposes file information from the underlying @code{readdir} or
@code{FindFirstFile}/@code{FindNextFile} system calls.  (Contributed by
Ben Hoyt with help from Victor Stinner in bpo-23605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23605}.)

Construction of @code{bytes(int)} (filled by zero bytes) is faster and uses less
memory for large objects. @code{calloc()} is used instead of @code{malloc()} to
allocate memory for these objects.
(Contributed by Victor Stinner in bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}.)

Some operations on @ref{a2,,ipaddress} @ref{4af,,IPv4Network} and
@ref{4ae,,IPv6Network} have been massively sped up, such as
@ref{890,,subnets()}, @ref{891,,supernet()},
@ref{892,,summarize_address_range()}, @ref{893,,collapse_addresses()}.
The speed up can range from 3 to 15 times.
(Contributed by Antoine Pitrou, Michel Albert, and Markus in
bpo-21486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21486}, bpo-21487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21487}, bpo-20826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20826}, bpo-23266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23266}.)

Pickling of @ref{a2,,ipaddress} objects was optimized to produce significantly
smaller output.  (Contributed by Serhiy Storchaka in bpo-23133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23133}.)

Many operations on @ref{894,,io.BytesIO} are now 50% to 100% faster.
(Contributed by Serhiy Storchaka in bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381} and David Wilson in
bpo-22003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22003}.)

The @ref{895,,marshal.dumps()} function is now faster: 65--85% with versions 3
and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times in
best cases.
(Contributed by Serhiy Storchaka in bpo-20416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20416} and bpo-23344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23344}.)

The UTF-32 encoder is now 3 to 7 times faster.
(Contributed by Serhiy Storchaka in bpo-15027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15027}.)

Regular expressions are now parsed up to 10% faster.
(Contributed by Serhiy Storchaka in bpo-19380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19380}.)

The @ref{706,,json.dumps()} function was optimized to run with
@code{ensure_ascii=False} as fast as with @code{ensure_ascii=True}.
(Contributed by Naoki Inada in bpo-23206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23206}.)

The @ref{896,,PyObject_IsInstance()} and @ref{897,,PyObject_IsSubclass()}
functions have been sped up in the common case that the second argument
has @ref{709,,type} as its metaclass.
(Contributed Georg Brandl by in bpo-22540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22540}.)

Method caching was slightly improved, yielding up to 5% performance
improvement in some benchmarks.
(Contributed by Antoine Pitrou in bpo-22847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22847}.)

Objects from the @ref{dc,,random} module now use 50% less memory on 64-bit
builds.  (Contributed by Serhiy Storchaka in bpo-23488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23488}.)

The @ref{30f,,property()} getter calls are up to 25% faster.
(Contributed by Joe Jevnik in bpo-23910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23910}.)

Instantiation of @ref{2c5,,fractions.Fraction} is now up to 30% faster.
(Contributed by Stefan Behnel in bpo-22464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22464}.)

String methods @ref{898,,find()}, @ref{899,,rfind()}, @ref{89a,,split()},
@ref{89b,,partition()} and the @ref{179,,in} string operator are now significantly
faster for searching 1-character substrings.
(Contributed by Serhiy Storchaka in bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}.)

@node 构建和 C API 的改变<3>,弃用<4>,性能优化<5>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 build-and-c-api-changes}@anchor{89c}
@subsection 构建和 C API 的改变


增加了 @code{calloc} 函数


@itemize *

@item 
@ref{89d,,PyMem_RawCalloc()},

@item 
@ref{89e,,PyMem_Calloc()},

@item 
@ref{89f,,PyObject_Calloc()}.
@end itemize

(Victor Stinner 贡献于 bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}.)

新的 encoding/decoding 帮助函数:


@itemize *

@item 
@ref{547,,Py_DecodeLocale()} (替代 @code{_Py_char2wchar()}),

@item 
@ref{548,,Py_EncodeLocale()} (替代 @code{_Py_wchar2char()}).
@end itemize

（由 Victor Stinner 在 bpo-18395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18395} 中贡献。）

A new @ref{8a0,,PyCodec_NameReplaceErrors()} function to replace the unicode
encode error with @code{\N@{...@}} escapes.
(Contributed by Serhiy Storchaka in bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676}.)

A new @ref{8a1,,PyErr_FormatV()} function similar to @ref{8a2,,PyErr_Format()},
but accepts a @code{va_list} argument.
(Contributed by Antoine Pitrou in bpo-18711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18711}.)

A new @code{PyExc_RecursionError} exception.
(Contributed by Georg Brandl in bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235}.)

New @ref{8a3,,PyModule_FromDefAndSpec()}, @ref{8a4,,PyModule_FromDefAndSpec2()},
and @ref{8a5,,PyModule_ExecDef()} functions introduced by 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} --
multi-phase extension module initialization.
(Contributed by Petr Viktorin in bpo-24268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24268}.)

New @ref{8a6,,PyNumber_MatrixMultiply()} and
@ref{8a7,,PyNumber_InPlaceMatrixMultiply()} functions to perform matrix
multiplication.
(Contributed by Benjamin Peterson in bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}.  See also 
@geindex Python 提高建议; PEP 465
PEP 465@footnote{https://www.python.org/dev/peps/pep-0465}
for details.)

The @ref{3ff,,PyTypeObject.tp_finalize} slot is now part of the stable ABI.

Windows builds now require Microsoft Visual C++ 14.0, which
is available as part of Visual Studio 2015@footnote{https://www.visualstudio.com/}.

Extension modules now include a platform information tag in their filename on
some platforms (the tag is optional, and CPython will import extensions without
it, although if the tag is present and mismatched, the extension won't be
loaded):


@itemize *

@item 
On Linux, extension module filenames end with
@code{.cpython-<major><minor>m-<architecture>-<os>.pyd}:


@itemize *

@item 
@code{<major>} is the major number of the Python version;
for Python 3.5 this is @code{3}.

@item 
@code{<minor>} is the minor number of the Python version;
for Python 3.5 this is @code{5}.

@item 
@code{<architecture>} is the hardware architecture the extension module
was built to run on. It's most commonly either @code{i386} for 32-bit Intel
platforms or @code{x86_64} for 64-bit Intel (and AMD) platforms.

@item 
@code{<os>} is always @code{linux-gnu}, except for extensions built to
talk to the 32-bit ABI on 64-bit platforms, in which case it is
@code{linux-gnu32} (and @code{<architecture>} will be @code{x86_64}).
@end itemize

@item 
On Windows, extension module filenames end with
@code{<debug>.cp<major><minor>-<platform>.pyd}:


@itemize *

@item 
@code{<major>} is the major number of the Python version;
for Python 3.5 this is @code{3}.

@item 
@code{<minor>} is the minor number of the Python version;
for Python 3.5 this is @code{5}.

@item 
@code{<platform>} is the platform the extension module was built for,
either @code{win32} for Win32, @code{win_amd64} for Win64, @code{win_ia64} for
Windows Itanium 64, and @code{win_arm} for Windows on ARM.

@item 
If built in debug mode, @code{<debug>} will be @code{_d},
otherwise it will be blank.
@end itemize

@item 
On OS X platforms, extension module filenames now end with @code{-darwin.so}.

@item 
On all other platforms, extension module filenames are the same as they were
with Python 3.4.
@end itemize

@node 弃用<4>,移除<4>,构建和 C API 的改变<3>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 deprecated}@anchor{8a8}
@subsection 弃用


@menu
* 新关键字: 新关键字<2>. 
* 已弃用的 Python 行为: 已弃用的 Python 行为<3>. 
* 不支持的操作系统:: 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<3>. 

@end menu

@node 新关键字<2>,已弃用的 Python 行为<3>,,弃用<4>
@anchor{whatsnew/3 5 new-keywords}@anchor{8a9}
@subsubsection 新关键字


@code{async} and @code{await} are not recommended to be used as variable, class,
function or module names.  Introduced by 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} in Python 3.5, they will
become proper keywords in Python 3.7.

@node 已弃用的 Python 行为<3>,不支持的操作系统,新关键字<2>,弃用<4>
@anchor{whatsnew/3 5 deprecated-python-behavior}@anchor{8aa}
@subsubsection 已弃用的 Python 行为


Raising the @ref{58a,,StopIteration} exception inside a generator will now generate a silent
@ref{15c,,PendingDeprecationWarning}, which will become a non-silent deprecation
warning in Python 3.6 and will trigger a @ref{3e4,,RuntimeError} in Python 3.7.
See @ref{6d8,,PEP 479; Change StopIteration handling inside generators}
for details.

@node 不支持的操作系统,已弃用的 Python 模块、函数和方法<3>,已弃用的 Python 行为<3>,弃用<4>
@anchor{whatsnew/3 5 unsupported-operating-systems}@anchor{8ab}
@subsubsection 不支持的操作系统


Windows XP is no longer supported by Microsoft, thus, per 
@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011}, CPython
3.5 is no longer officially supported on this OS.

@node 已弃用的 Python 模块、函数和方法<3>,,不支持的操作系统,弃用<4>
@anchor{whatsnew/3 5 deprecated-python-modules-functions-and-methods}@anchor{8ac}
@subsubsection 已弃用的 Python 模块、函数和方法


The @ref{80,,formatter} module has now graduated to full deprecation and is still
slated for removal in Python 3.6.

The @code{asyncio.async()} function is deprecated in favor of
@ref{619,,ensure_future()}.

The @ref{ec,,smtpd} module has in the past always decoded the DATA portion of
email messages using the @code{utf-8} codec.  This can now be controlled by the
new @emph{decode_data} keyword to @ref{703,,SMTPServer}.  The default value is
@code{True}, but this default is deprecated.  Specify the @emph{decode_data} keyword
with an appropriate value to avoid the deprecation warning.

Directly assigning values to the @ref{591,,key},
@ref{592,,value} and
@ref{593,,coded_value} of @ref{590,,http.cookies.Morsel}
objects is deprecated.  Use the @ref{594,,set()} method
instead.  In addition, the undocumented @emph{LegalChars} parameter of
@ref{594,,set()} is deprecated, and is now ignored.

Passing a format string as keyword argument @emph{format_string} to the
@ref{58f,,format()} method of the @ref{8ad,,string.Formatter}
class has been deprecated.
(Contributed by Serhiy Storchaka in bpo-23671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23671}.)

The @code{platform.dist()} and @code{platform.linux_distribution()} functions
are now deprecated.  Linux distributions use too many different ways of
describing themselves, so the functionality is left to a package.
(Contributed by Vajrasky Kok and Berker Peksag in bpo-1322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1322}.)

The previously undocumented @code{from_function} and @code{from_builtin} methods of
@ref{7ee,,inspect.Signature} are deprecated.  Use the new
@ref{7f1,,Signature.from_callable()}
method instead. (Contributed by Yury Selivanov in bpo-24248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24248}.)

The @ref{65f,,inspect.getargspec()} function is deprecated and scheduled to be
removed in Python 3.6.  (See bpo-20438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20438} for details.)

The @ref{a0,,inspect} @ref{660,,getfullargspec()},
@ref{8ae,,getcallargs()}, and @ref{8af,,formatargspec()} functions are
deprecated in favor of the @ref{65e,,inspect.signature()} API. (Contributed by Yury
Selivanov in bpo-20438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20438}.)

@ref{8b0,,getargvalues()} and @ref{8b1,,formatargvalues()} functions
were inadvertently marked as deprecated with the release of Python 3.5.0.

Use of @ref{4d8,,re.LOCALE} flag with str patterns or @ref{4d7,,re.ASCII} is now
deprecated.  (Contributed by Serhiy Storchaka in bpo-22407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22407}.)

Use of unrecognized special sequences consisting of @code{'\'} and an ASCII letter
in regular expression patterns and replacement patterns now raises a
deprecation warning and will be forbidden in Python 3.6.
(Contributed by Serhiy Storchaka in bpo-23622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23622}.)

The undocumented and unofficial @emph{use_load_tests} default argument of the
@ref{879,,unittest.TestLoader.loadTestsFromModule()} method now is
deprecated and ignored.
(Contributed by Robert Collins and Barry A. Warsaw in bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}.)

@node 移除<4>,移植到Python 3 5,弃用<4>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 removed}@anchor{8b2}
@subsection 移除


@menu
* API 与特性的移除: API 与特性的移除<4>. 

@end menu

@node API 与特性的移除<4>,,,移除<4>
@anchor{whatsnew/3 5 api-and-feature-removals}@anchor{8b3}
@subsubsection API 与特性的移除


The following obsolete and previously deprecated APIs and features have been
removed:


@itemize *

@item 
The @code{__version__} attribute has been dropped from the email package.  The
email code hasn't been shipped separately from the stdlib for a long time,
and the @code{__version__} string was not updated in the last few releases.

@item 
The internal @code{Netrc} class in the @ref{82,,ftplib} module was deprecated in
3.4, and has now been removed.
(Contributed by Matt Chaput in bpo-6623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6623}.)

@item 
The concept of @code{.pyo} files has been removed.

@item 
The JoinableQueue class in the provisional @ref{9,,asyncio} module was
deprecated in 3.4.4 and is now removed.
(Contributed by A. Jesse Jiryu Davis in bpo-23464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23464}.)
@end itemize

@node 移植到Python 3 5,Python 3 5 4 的显著变化,移除<4>,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 porting-to-python-3-5}@anchor{8b4}
@subsection 移植到Python 3.5


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* Python 行为的改变: Python 行为的改变<2>. 
* 改变了的Python API:: 
* C API 中的改变: C API 中的改变<4>. 

@end menu

@node Python 行为的改变<2>,改变了的Python API,,移植到Python 3 5
@anchor{whatsnew/3 5 changes-in-python-behavior}@anchor{8b5}
@subsubsection Python 行为的改变



@itemize *

@item 
由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

@example
f(1 for x in [1], *args)
f(1 for x in [1], **kwargs)
@end example

Python 3.5 now correctly raises a @ref{562,,SyntaxError}, as generator
expressions must be put in parentheses if not a sole argument to a function.
@end itemize

@node 改变了的Python API,C API 中的改变<4>,Python 行为的改变<2>,移植到Python 3 5
@anchor{whatsnew/3 5 changes-in-the-python-api}@anchor{8b6}
@subsubsection 改变了的Python API



@itemize *

@item 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}: System calls are now retried when interrupted by a signal instead
of raising @ref{756,,InterruptedError} if the Python signal handler does not
raise an exception.

@item 
Before Python 3.5, a @ref{5f5,,datetime.time} object was considered to be false
if it represented midnight in UTC.  This behavior was considered obscure and
error-prone and has been removed in Python 3.5.  See bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936} for full
details.

@item 
The @code{ssl.SSLSocket.send()} method now raises either
@ref{84f,,ssl.SSLWantReadError} or @ref{850,,ssl.SSLWantWriteError}
on a non-blocking socket if the operation would block.  Previously,
it would return @code{0}.  (Contributed by Nikolaus Rath in bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}.)

@item 
The @code{__name__} attribute of generators is now set from the function name,
instead of being set from the code name. Use @code{gen.gi_code.co_name} to
retrieve the code name. Generators also have a new @code{__qualname__}
attribute, the qualified name, which is now used for the representation
of a generator (@code{repr(gen)}).
(Contributed by Victor Stinner in bpo-21205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21205}.)

@item 
The deprecated "strict" mode and argument of @ref{22b,,HTMLParser},
@code{HTMLParser.error()}, and the @code{HTMLParserError} exception have been
removed.  (Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}.)
The @emph{convert_charrefs} argument of @ref{22b,,HTMLParser} is
now @code{True} by default.  (Contributed by Berker Peksag in bpo-21047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21047}.)

@item 
Although it is not formally part of the API, it is worth noting for porting
purposes (ie: fixing tests) that error messages that were previously of the
form "'sometype' does not support the buffer protocol" are now of the form "a
@ref{6e9,,bytes-like object} is required, not 'sometype'".
(Contributed by Ezio Melotti in bpo-16518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16518}.)

@item 
If the current directory is set to a directory that no longer exists then
@ref{8b7,,FileNotFoundError} will no longer be raised and instead
@ref{8b8,,find_spec()} will return @code{None}
@strong{without} caching @code{None} in @ref{5a0,,sys.path_importer_cache}, which is
different than the typical case (bpo-22834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22834}).

@item 
HTTP status code and messages from @ref{93,,http.client} and @ref{96,,http.server}
were refactored into a common @ref{1ac,,HTTPStatus} enum.  The values in
@ref{93,,http.client} and @ref{96,,http.server} remain available for backwards
compatibility.  (Contributed by Demian Brecht in bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}.)

@item 
When an import loader defines @code{importlib.machinery.Loader.exec_module()}
it is now expected to also define
@code{create_module()} (raises a
@ref{15a,,DeprecationWarning} now, will be an error in Python 3.6). If the loader
inherits from @ref{8b9,,importlib.abc.Loader} then there is nothing to do, else
simply define @code{create_module()} to return
@code{None}.  (Contributed by Brett Cannon in bpo-23014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23014}.)

@item 
The @ref{4d9,,re.split()} function always ignored empty pattern matches, so the
@code{"x*"} pattern worked the same as @code{"x+"}, and the @code{"\b"} pattern never
worked.  Now @ref{4d9,,re.split()} raises a warning if the pattern could match
an empty string.  For compatibility, use patterns that never match an empty
string (e.g. @code{"x+"} instead of @code{"x*"}).  Patterns that could only match
an empty string (such as @code{"\b"}) now raise an error.
(Contributed by Serhiy Storchaka in bpo-22818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22818}.)

@item 
The @ref{590,,http.cookies.Morsel} dict-like interface has been made self
consistent:  morsel comparison now takes the @ref{591,,key}
and @ref{592,,value} into account,
@ref{8ba,,copy()} now results in a
@ref{590,,Morsel} instance rather than a @ref{164,,dict}, and
@ref{8bb,,update()} will now raise an exception if any of the
keys in the update dictionary are invalid.  In addition, the undocumented
@emph{LegalChars} parameter of @ref{594,,set()} is deprecated and
is now ignored.  (Contributed by Demian Brecht in bpo-2211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2211}.)

@item 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} has removed @code{.pyo} files from Python and introduced the optional
@code{opt-} tag in @code{.pyc} file names. The
@ref{65a,,importlib.util.cache_from_source()} has gained an @emph{optimization}
parameter to help control the @code{opt-} tag. Because of this, the
@emph{debug_override} parameter of the function is now deprecated. @cite{.pyo} files
are also no longer supported as a file argument to the Python interpreter and
thus serve no purpose when distributed on their own (i.e. sourceless code
distribution). Due to the fact that the magic number for bytecode has changed
in Python 3.5, all old @cite{.pyo} files from previous versions of Python are
invalid regardless of this PEP.

@item 
The @ref{ef,,socket} module now exports the @ref{8bc,,CAN_RAW_FD_FRAMES}
constant on linux 3.6 and greater.

@item 
The @ref{851,,ssl.cert_time_to_seconds()} function now interprets the input time
as UTC and not as local time, per 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://tools.ietf.org/html/rfc5280.html}.  Additionally, the return
value is always an @ref{205,,int}. (Contributed by Akira Li in bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}.)

@item 
The @code{pygettext.py} Tool now uses the standard +NNNN format for timezones in
the POT-Creation-Date header.

@item 
The @ref{ed,,smtplib} module now uses @ref{1eb,,sys.stderr} instead of the previous
module-level @code{stderr} variable for debug output.  If your (test)
program depends on patching the module-level variable to capture the debug
output, you will need to update it to capture sys.stderr instead.

@item 
The @ref{8bd,,str.startswith()} and @ref{8be,,str.endswith()} methods no longer return
@code{True} when finding the empty string and the indexes are completely out of
range.  (Contributed by Serhiy Storchaka in bpo-24284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24284}.)

@item 
The @ref{30e,,inspect.getdoc()} function now returns documentation strings
inherited from base classes.  Documentation strings no longer need to be
duplicated if the inherited documentation is appropriate.  To suppress an
inherited string, an empty string must be specified (or the documentation
may be filled in).  This change affects the output of the @ref{d9,,pydoc}
module and the @ref{175,,help()} function.
(Contributed by Serhiy Storchaka in bpo-15582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15582}.)

@item 
Nested @ref{8bf,,functools.partial()} calls are now flattened.  If you were
relying on the previous behavior, you can now either add an attribute to a
@ref{8bf,,functools.partial()} object or you can create a subclass of
@ref{8bf,,functools.partial()}.
(Contributed by Alexander Belopolsky in bpo-7830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7830}.)
@end itemize

@node C API 中的改变<4>,,改变了的Python API,移植到Python 3 5
@anchor{whatsnew/3 5 changes-in-the-c-api}@anchor{8c0}
@subsubsection C API 中的改变



@itemize *

@item 
The undocumented @code{format} member of the
(non-public) @code{PyMemoryViewObject} structure has been removed.
All extensions relying on the relevant parts in @code{memoryobject.h}
must be rebuilt.

@item 
The @code{PyMemAllocator} structure was renamed to
@ref{8c1,,PyMemAllocatorEx} and a new @code{calloc} field was added.

@item 
Removed non-documented macro @code{PyObject_REPR} which leaked references.
Use format character @code{%R} in @ref{8c2,,PyUnicode_FromFormat()}-like functions
to format the @ref{8c3,,repr()} of the object.
(Contributed by Serhiy Storchaka in bpo-22453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22453}.)

@item 
Because the lack of the @code{__module__} attribute breaks pickling and
introspection, a deprecation warning is now raised for builtin types without
the @code{__module__} attribute.  This would be an AttributeError in
the future.
(Contributed by Serhiy Storchaka in bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}.)

@item 
As part of the 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} implementation, the @code{tp_reserved} slot of
@ref{3fe,,PyTypeObject} was replaced with a
@code{tp_as_async} slot.  Refer to @ref{8c4,,协程对象} for
new types, structures and functions.
@end itemize

@node Python 3 5 4 的显著变化,,移植到Python 3 5,Python 3 5 有什么新变化
@anchor{whatsnew/3 5 notable-changes-in-python-3-5-4}@anchor{8c5}
@subsection Python 3.5.4 的显著变化


@menu
* New make regen-all build target: New make regen-all build target<2>. 
* Removal of make touch build target: Removal of make touch build target<2>. 

@end menu

@node New make regen-all build target<2>,Removal of make touch build target<2>,,Python 3 5 4 的显著变化
@anchor{whatsnew/3 5 new-make-regen-all-build-target}@anchor{8c6}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.9/Makefile.pre.in} for details.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


3.5.4 新版功能.


@node Removal of make touch build target<2>,,New make regen-all build target<2>,Python 3 5 4 的显著变化
@anchor{whatsnew/3 5 removal-of-make-touch-build-target}@anchor{8c7}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


在 3.5.4 版更改.


@node Python 3 4 有什么新变化,Python 3 3 有什么新变化,Python 3 5 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 4 doc}@anchor{8c8}@anchor{whatsnew/3 4 what-s-new-in-python-3-4}@anchor{8c9}
@section Python 3.4 有什么新变化


@*作者: 
R. David Murray <@email{rdmurray@@bitdance.com}> (Editor)


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document, but the maintainer reserves the
@c right to rewrite any additions. In particular, for obscure or esoteric
@c features, the maintainer may reduce any addition to a simple reference to
@c the new documentation rather than explaining the feature inline.
@c 
@c * While the maintainer will periodically go through Misc/NEWS
@c and add changes, it's best not to rely on this. We know from experience
@c that any changes that aren't in the What's New documentation around the
@c time of the original release will remain largely unknown to the community
@c for years, even if they're added later. We also know from experience that
@c other priorities can arise, and the maintainer will run out of time to do
@c updates -- in such cases, end users will be much better served by partial
@c notifications that at least give a hint about new features to
@c investigate.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS. The What's New should focus on changes that
@c are visible to Python *users* and that *require* a feature release (i.e.
@c most bug fixes should only be recorded in Misc/NEWS)
@c 
@c * PEPs should not be marked Final until they have an entry in What's New.
@c A placeholder entry that is just a section header and a link to the PEP
@c (e.g ":pep:`397` has been implemented") is acceptable. If a PEP has been
@c implemented and noted in What's New, don't forget to mark it as Final!
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to add just a very brief note about a change.  For
@c example: "The :ref:`~socket.transmogrify()` function was added to the
@c :mod:`socket` module."  The maintainer will research the change and
@c write the necessary text (if appropriate). The advantage of doing this
@c is that even if no more descriptive text is ever added, readers will at
@c least have a notification that the new feature exists and a link to the
@c relevant documentation.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c The :ref:`~socket.transmogrify()` function was added to the
@c :mod:`socket` module.  (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.
@c 
@c * Cross referencing tip: :ref:`mod.attr` will display as ``mod.attr``,
@c while :ref:`~mod.attr` will display as ``attr``.

这篇文章介绍了 Python 3.4 相比 3.3 增加的新特性。 Python 3.4 发布于 2014 年 3 月 16 日。 对于完整的细节，请参见 更新日志@footnote{https://docs.python.org/3.4/whatsnew/changelog.html}。


@subsubheading 参见


@geindex Python 提高建议; PEP 429
PEP 429@footnote{https://www.python.org/dev/peps/pep-0429} -- Python 3.4 发布计划


@menu
* 摘要 - 发布重点: 摘要 - 发布重点<6>. 
* 新的特性: 新的特性<7>. 
* 新增模块: 新增模块<6>. 
* 改进的模块: 改进的模块<6>. 
* CPython Implementation Changes:: 
* 弃用: 弃用<5>. 
* 移除: 移除<5>. 
* 移植到 Python 3.4: 移植到 Python 3 4. 
* 3.4.3 的变化: 3 4 3 的变化. 

@end menu

@node 摘要 - 发布重点<6>,新的特性<7>,,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 summary-release-highlights}@anchor{8ca}
@subsection 摘要 - 发布重点


@c This section singles out the most important changes in Python 3.4.
@c Brevity is key.

新的语法特性：


@itemize *

@item 
Python 3.4 中没有增加新的语法特性。
@end itemize

其他的新特性


@itemize *

@item 
@ref{8cb,,pip 能够随时可用} (
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453}).

@item 
@ref{8cc,,新创建的文件描述符是不可继承的} (
@geindex Python 提高建议; PEP 446
PEP 446@footnote{https://www.python.org/dev/peps/pep-0446})。

@item 
对应 @ref{8cd,,隔离模式} 的命令行选项 (bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499})。

@item 
针对非文本编码格式的 @ref{8ce,,编解码器处理方式的改进} (多个相关问题)。

@item 
针对导入系统的 @ref{8cf,,ModuleSpec 类型} (
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451})。 （将影响导入器的作者。）

@item 
@ref{b0,,marshal} 格式已被改进为 @ref{8d0,,更为紧凑与高效} (bpo-16475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16475})。
@end itemize

新的库模块：


@itemize *

@item 
@ref{9,,asyncio}: @ref{8d1,,针对异步 IO 的新版暂定 API} (
@geindex Python 提高建议; PEP 3156
PEP 3156@footnote{https://www.python.org/dev/peps/pep-3156})。

@item 
@ref{78,,ensurepip}: @ref{8d2,,引导设置 pip 安装器} (
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453})。

@item 
@ref{79,,enum}: @ref{8d3,,对枚举类型的支持} (
@geindex Python 提高建议; PEP 435
PEP 435@footnote{https://www.python.org/dev/peps/pep-0435})。

@item 
@ref{c8,,pathlib}: @ref{8d4,,面向对象的文件系统路径} (
@geindex Python 提高建议; PEP 428
PEP 428@footnote{https://www.python.org/dev/peps/pep-0428})。

@item 
@ref{e6,,selectors}: @ref{8d5,,高层级且高效率的 I/O 复用}，在 @ref{e5,,select} 模块的基础之上建立（为 
@geindex Python 提高建议; PEP 3156
PEP 3156@footnote{https://www.python.org/dev/peps/pep-3156} 的组成部分）。

@item 
@ref{f5,,statistics}: 基础 @ref{8d6,,数字领域稳定统计库} (
@geindex Python 提高建议; PEP 450
PEP 450@footnote{https://www.python.org/dev/peps/pep-0450})。

@item 
@ref{11d,,tracemalloc}: @ref{8d7,,追踪 Python 内存分配} (
@geindex Python 提高建议; PEP 454
PEP 454@footnote{https://www.python.org/dev/peps/pep-0454})。
@end itemize

显著改进的库模块:


@itemize *

@item 
@ref{83,,functools} 中的 @ref{8d8,,单一调度泛型函数} (
@geindex Python 提高建议; PEP 443
PEP 443@footnote{https://www.python.org/dev/peps/pep-0443})。

@item 
新的 @ref{ca,,pickle} @ref{8d9,,协议 4} (
@geindex Python 提高建议; PEP 3154
PEP 3154@footnote{https://www.python.org/dev/peps/pep-3154})。

@item 
@ref{b7,,multiprocessing} 现在包含 @ref{8da,,一个避免在 Unix 上使用 os.fork 的选项} (bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713})。

@item 
@ref{67,,email} 增加新的子模块 @ref{69,,contentmanager} 和新的子类型 @ref{644,,Message} (@code{EmailMessage}) 用以 @ref{8db,,简化 MIME 处理} (bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891})。

@item 
@ref{a0,,inspect} 和 @ref{d9,,pydoc} 模块现在能够自省更多种类的可调用对象，这改进了 Python @ref{175,,help()} 系统的输出。

@item 
The @ref{a2,,ipaddress} module API has been declared stable
@end itemize

安全改进：


@itemize *

@item 
@ref{8dc,,Secure and interchangeable hash algorithm}
(
@geindex Python 提高建议; PEP 456
PEP 456@footnote{https://www.python.org/dev/peps/pep-0456}).

@item 
@ref{8cc,,Make newly created file descriptors non-inheritable}
(
@geindex Python 提高建议; PEP 446
PEP 446@footnote{https://www.python.org/dev/peps/pep-0446}) to avoid leaking file descriptors to child processes.

@item 
New command line option for @ref{8cd,,isolated mode},
(bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499}).

@item 
@ref{b7,,multiprocessing} now has @ref{8da,,an option to avoid using os.fork on Unix}.  @emph{spawn} and @emph{forkserver} are
more secure because they avoid sharing data with child processes.

@item 
@ref{b7,,multiprocessing} child processes on Windows no longer inherit
all of the parent's inheritable handles, only the necessary ones.

@item 
A new @ref{8dd,,hashlib.pbkdf2_hmac()} function provides
the PKCS#5 password-based key derivation function 2@footnote{https://en.wikipedia.org/wiki/PBKDF2}.

@item 
@ref{8de,,TLSv1.1 and TLSv1.2 support} for @ref{f3,,ssl}.

@item 
@ref{8df,,Retrieving certificates from the Windows system cert store support} for @ref{f3,,ssl}.

@item 
@ref{8e0,,Server-side SNI (Server Name Indication) support} for @ref{f3,,ssl}.

@item 
The @ref{4f2,,ssl.SSLContext} class has a @ref{8e1,,lot of improvements}.

@item 
All modules in the standard library that support SSL now support server
certificate verification, including hostname matching
(@ref{4eb,,ssl.match_hostname()}) and CRLs (Certificate Revocation lists, see
@ref{8e2,,ssl.SSLContext.load_verify_locations()}).
@end itemize

CPython 实现的改进：


@itemize *

@item 
@ref{8e3,,Safe object finalization} (
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442}).

@item 
Leveraging 
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442}, in most cases @ref{8e3,,module globals are no longer set to None during finalization} (bpo-18214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18214}).

@item 
@ref{8e4,,Configurable memory allocators} (
@geindex Python 提高建议; PEP 445
PEP 445@footnote{https://www.python.org/dev/peps/pep-0445}).

@item 
@ref{8e5,,Argument Clinic} (
@geindex Python 提高建议; PEP 436
PEP 436@footnote{https://www.python.org/dev/peps/pep-0436}).
@end itemize

请继续阅读有关针对用户的改变的完整清单，包括许多其他较小的改进、CPython 优化、弃用以及潜在的移植问题。

@node 新的特性<7>,新增模块<6>,摘要 - 发布重点<6>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 new-features}@anchor{8e6}
@subsection 新的特性


@menu
* PEP 453; Explicit Bootstrapping of PIP in Python Installations: PEP 453 Explicit Bootstrapping of PIP in Python Installations. 
* PEP 446; Newly Created File Descriptors Are Non-Inheritable: PEP 446 Newly Created File Descriptors Are Non-Inheritable. 
* Improvements to Codec Handling:: 
* PEP 451; A ModuleSpec Type for the Import System: PEP 451 A ModuleSpec Type for the Import System. 
* 其他语言特性修改: 其他语言特性修改<6>. 

@end menu

@node PEP 453 Explicit Bootstrapping of PIP in Python Installations,PEP 446 Newly Created File Descriptors Are Non-Inheritable,,新的特性<7>
@anchor{whatsnew/3 4 pep-453-explicit-bootstrapping-of-pip-in-python-installations}@anchor{8e7}@anchor{whatsnew/3 4 whatsnew-pep-453}@anchor{8cb}
@subsubsection PEP 453: Explicit Bootstrapping of PIP in Python Installations


@menu
* Bootstrapping pip By Default:: 
* 文档更改:: 

@end menu

@node Bootstrapping pip By Default,文档更改,,PEP 453 Explicit Bootstrapping of PIP in Python Installations
@anchor{whatsnew/3 4 bootstrapping-pip-by-default}@anchor{8e8}
@subsubsection Bootstrapping pip By Default


The new @ref{78,,ensurepip} module (defined in 
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453}) provides a standard
cross-platform mechanism to bootstrap the pip installer into Python
installations and virtual environments. The version of @code{pip} included
with Python 3.4.0 is @code{pip} 1.5.4, and future 3.4.x maintenance releases
will update the bundled version to the latest version of @code{pip} that is
available at the time of creating the release candidate.

By default, the commands @code{pipX} and @code{pipX.Y} will be installed on all
platforms (where X.Y stands for the version of the Python installation),
along with the @code{pip} Python package and its dependencies. On Windows and
in virtual environments on all platforms, the unversioned @code{pip} command
will also be installed. On other platforms, the system wide unversioned
@code{pip} command typically refers to the separately installed Python 2
version.

The @code{pyvenv} command line utility and the @ref{12e,,venv}
module make use of the @ref{78,,ensurepip} module to make @code{pip} readily
available in virtual environments. When using the command line utility,
@code{pip} is installed by default, while when using the @ref{12e,,venv} module
@ref{8e9,,API} installation of @code{pip} must be requested explicitly.

For CPython @ref{8ea,,source builds on POSIX systems},
the @code{make install} and @code{make altinstall} commands bootstrap @code{pip} by
default.  This behaviour can be controlled through configure options, and
overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing
@code{pip} along with CPython itself (users may opt out of installing it
during the installation process). Window users will need to opt in to the
automatic @code{PATH} modifications to have @code{pip} available from the command
line by default, otherwise it can still be accessed through the Python
launcher for Windows as @code{py -m pip}.

As discussed in the PEP@footnote{https://www.python.org/dev/peps/pep-0453/#recommendations-for-downstream-distributors}, platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).

@cartouche
@quotation 注解 
To avoid conflicts between parallel Python 2 and Python 3 installations,
only the versioned @code{pip3} and @code{pip3.4} commands are bootstrapped by
default when @code{ensurepip} is invoked directly - the @code{--default-pip}
option is needed to also request the unversioned @code{pip} command.
@code{pyvenv} and the Windows installer ensure that the unqualified @code{pip}
command is made available in those environments, and @code{pip} can always be
invoked via the @code{-m} switch rather than directly to avoid ambiguity on
systems with multiple Python installations.
@end quotation
@end cartouche

@node 文档更改,,Bootstrapping pip By Default,PEP 453 Explicit Bootstrapping of PIP in Python Installations
@anchor{whatsnew/3 4 documentation-changes}@anchor{8eb}
@subsubsection 文档更改


As part of this change, the @ref{8ec,,安装 Python 模块} and
@ref{8ed,,分发 Python 模块} sections of the documentation have been
completely redesigned as short getting started and FAQ documents. Most
packaging documentation has now been moved out to the Python Packaging
Authority maintained Python Packaging User Guide@footnote{https://packaging.python.org} and the documentation of the individual
projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as @ref{8ee,,安装Python模块（旧版）}
and @ref{8ef,,分发 Python 模块（遗留版本）}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 453

@item PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} -- Python安装中pip的显式引导

PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick Coghlan，Martin von Löwis 和 Ned Deily 实现。
@end table


@node PEP 446 Newly Created File Descriptors Are Non-Inheritable,Improvements to Codec Handling,PEP 453 Explicit Bootstrapping of PIP in Python Installations,新的特性<7>
@anchor{whatsnew/3 4 pep-446-newly-created-file-descriptors-are-non-inheritable}@anchor{8f0}@anchor{whatsnew/3 4 whatsnew-pep-446}@anchor{8cc}
@subsubsection PEP 446: Newly Created File Descriptors Are Non-Inheritable


@geindex Python 提高建议; PEP 446
PEP 446@footnote{https://www.python.org/dev/peps/pep-0446} makes newly created file descriptors @ref{8f1,,non-inheritable}.  In general, this is the behavior an application will
want: when launching a new process, having currently open files also
open in the new process can lead to all sorts of hard to find bugs,
and potentially to security issues.

However, there are occasions when inheritance is desired.  To support
these cases, the following new functions and methods are available:


@itemize *

@item 
@ref{8f2,,os.get_inheritable()}, @ref{8f3,,os.set_inheritable()}

@item 
@ref{8f4,,os.get_handle_inheritable()}, @ref{8f5,,os.set_handle_inheritable()}

@item 
@ref{8f6,,socket.socket.get_inheritable()}, @ref{8f7,,socket.socket.set_inheritable()}
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 446

@item PEP 446@footnote{https://www.python.org/dev/peps/pep-0446} -- Make newly created file descriptors non-inheritable

PEP 由 Victor Stinner 撰写并实现。
@end table


@node Improvements to Codec Handling,PEP 451 A ModuleSpec Type for the Import System,PEP 446 Newly Created File Descriptors Are Non-Inheritable,新的特性<7>
@anchor{whatsnew/3 4 codec-handling-improvements}@anchor{8ce}@anchor{whatsnew/3 4 improvements-to-codec-handling}@anchor{8f8}
@subsubsection Improvements to Codec Handling


Since it was first introduced, the @ref{1b,,codecs} module has always been
intended to operate as a type-neutral dynamic encoding and decoding
system. However, its close coupling with the Python text model, especially
the type restricted convenience methods on the builtin @ref{206,,str},
@ref{172,,bytes} and @ref{173,,bytearray} types, has historically obscured that
fact.

As a key step in clarifying the situation, the @ref{8f9,,codecs.encode()} and
@ref{8fa,,codecs.decode()} convenience functions are now properly documented in
Python 2.7, 3.3 and 3.4. These functions have existed in the @ref{1b,,codecs}
module (and have been covered by the regression test suite) since Python 2.4,
but were previously only discoverable through runtime introspection.

Unlike the convenience methods on @ref{206,,str}, @ref{172,,bytes} and
@ref{173,,bytearray}, the @ref{1b,,codecs} convenience functions support arbitrary
codecs in both Python 2 and Python 3, rather than being limited to Unicode text
encodings (in Python 3) or @code{basestring} <-> @code{basestring} conversions (in
Python 2).

In Python 3.4, the interpreter is able to identify the known non-text
encodings provided in the standard library and direct users towards these
general purpose convenience functions when appropriate:

@example
>>> b"abcdef".decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

>>> "hello".encode("rot13")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs
@end example

In a related change, whenever it is feasible without breaking backwards
compatibility, exceptions raised during encoding and decoding operations
are wrapped in a chained exception of the same type that mentions the
name of the codec responsible for producing the error:

@example
>>> import codecs

>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
    return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
    return (bz2.compress(input), len(input))
  File "/usr/lib/python3.4/bz2.py", line 498, in compress
    return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)
@end example

Finally, as the examples above show, these improvements have permitted
the restoration of the convenience aliases for the non-Unicode codecs that
were themselves restored in Python 3.2. This means that encoding binary data
to and from its hexadecimal representation (for example) can now be written
as:

@example
>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'
@end example

The binary and text transforms provided in the standard library are detailed
in @ref{8fb,,二进制转换} and @ref{8fc,,文字转换}.

(Contributed by Nick Coghlan in bpo-7475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7475}, bpo-17827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17827},
bpo-17828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17828} and bpo-19619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19619}.)

@node PEP 451 A ModuleSpec Type for the Import System,其他语言特性修改<6>,Improvements to Codec Handling,新的特性<7>
@anchor{whatsnew/3 4 pep-451-a-modulespec-type-for-the-import-system}@anchor{8fd}@anchor{whatsnew/3 4 whatsnew-pep-451}@anchor{8cf}
@subsubsection PEP 451: A ModuleSpec Type for the Import System


@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} provides an encapsulation of the information about a module that the
import machinery will use to load it (that is, a module specification).  This
helps simplify both the import implementation and several import-related APIs.
The change is also a stepping stone for several future import-related improvements@footnote{https://mail.python.org/pipermail/python-dev/2013-November/130111.html}.

The public-facing changes from the PEP are entirely backward-compatible.
Furthermore, they should be transparent to everyone but importer authors.  Key
finder and loader methods have been deprecated, but they will continue working.
New importers should use the new methods described in the PEP.  Existing
importers should be updated to implement the new methods.  See the
@ref{8fe,,弃用} section for a list of methods that should be replaced and
their replacements.

@node 其他语言特性修改<6>,,PEP 451 A ModuleSpec Type for the Import System,新的特性<7>
@anchor{whatsnew/3 4 other-language-changes}@anchor{8ff}
@subsubsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
Unicode database updated to UCD version 6.3.

@item 
@ref{900,,min()} and @ref{901,,max()} now accept a @emph{default} keyword-only argument that
can be used to specify the value they return if the iterable they are
evaluating has no elements.  (Contributed by Julian Berman in
bpo-18111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18111}.)

@item 
Module objects are now @ref{131,,weakref}'able.

@item 
Module @code{__file__} attributes (and related values) should now always
contain absolute paths by default, with the sole exception of
@code{__main__.__file__} when a script has been executed directly using
a relative path.  (Contributed by Brett Cannon in bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416}.)

@item 
All the UTF-* codecs (except UTF-7) now reject surrogates during both
encoding and decoding unless the @code{surrogatepass} error handler is used,
with the exception of the UTF-16 decoder (which accepts valid surrogate pairs)
and the UTF-16 encoder (which produces them while encoding non-BMP characters).
(Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in
bpo-12892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12892}.)

@item 
New German EBCDIC @ref{78c,,codec} @code{cp273}.  (Contributed
by Michael Bierenfeld and Andrew Kuchling in bpo-1097797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1097797}.)

@item 
New Ukrainian @ref{78c,,codec} @code{cp1125}.  (Contributed by
Serhiy Storchaka in bpo-19668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19668}.)

@item 
@ref{172,,bytes}.join() and @ref{173,,bytearray}.join() now accept arbitrary
buffer objects as arguments.  (Contributed by Antoine Pitrou in
bpo-15958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15958}.)

@item 
The @ref{205,,int} constructor now accepts any object that has an @code{__index__}
method for its @emph{base} argument.  (Contributed by Mark Dickinson in
bpo-16772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16772}.)

@item 
Frame objects now have a @ref{902,,clear()} method that clears all
references to local variables from the frame.  (Contributed by Antoine Pitrou
in bpo-17934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17934}.)

@item 
@ref{38d,,memoryview} is now registered as a @ref{1e,,Sequence},
and supports the @ref{2cd,,reversed()} builtin.  (Contributed by Nick Coghlan
and Claudiu Popa in bpo-18690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18690} and bpo-19078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19078}.)

@item 
Signatures reported by @ref{175,,help()} have been modified and improved in
several cases as a result of the introduction of Argument Clinic and other
changes to the @ref{a0,,inspect} and @ref{d9,,pydoc} modules.

@item 
@ref{903,,__length_hint__()} is now part of the formal language
specification (see 
@geindex Python 提高建议; PEP 424
PEP 424@footnote{https://www.python.org/dev/peps/pep-0424}).  (Contributed by Armin Ronacher in
bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)
@end itemize

@node 新增模块<6>,改进的模块<6>,新的特性<7>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 new-modules}@anchor{904}
@subsection 新增模块


@menu
* asyncio: asyncio<7>. 
* ensurepip:: 
* enum: enum<5>. 
* pathlib: pathlib<6>. 
* selectors: selectors<2>. 
* statistics: statistics<3>. 
* tracemalloc: tracemalloc<4>. 

@end menu

@node asyncio<7>,ensurepip,,新增模块<6>
@anchor{whatsnew/3 4 asyncio}@anchor{905}@anchor{whatsnew/3 4 whatsnew-asyncio}@anchor{8d1}
@subsubsection asyncio


The new @ref{9,,asyncio} module (defined in 
@geindex Python 提高建议; PEP 3156
PEP 3156@footnote{https://www.python.org/dev/peps/pep-3156}) provides a standard
pluggable event loop model for Python, providing solid asynchronous IO
support in the standard library, and making it easier for other event loop
implementations to interoperate with the standard library and each other.

For Python 3.4, this module is considered a @ref{45d,,provisional API}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3156

@item PEP 3156@footnote{https://www.python.org/dev/peps/pep-3156} -- Asynchronous IO Support Rebooted: the "asyncio" Module

PEP 由 Guido van Rossum 领导编写和实现。
@end table


@node ensurepip,enum<5>,asyncio<7>,新增模块<6>
@anchor{whatsnew/3 4 ensurepip}@anchor{906}@anchor{whatsnew/3 4 whatsnew-ensurepip}@anchor{8d2}
@subsubsection ensurepip


The new @ref{78,,ensurepip} module is the primary infrastructure for the
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} implementation.  In the normal course of events end users will not
need to interact with this module, but it can be used to manually bootstrap
@code{pip} if the automated bootstrapping into an installation or virtual
environment was declined.

@ref{78,,ensurepip} includes a bundled copy of @code{pip}, up-to-date as of the first
release candidate of the release of CPython with which it ships (this applies
to both maintenance releases and feature releases).  @code{ensurepip} does not
access the internet.  If the installation has Internet access, after
@code{ensurepip} is run the bundled @code{pip} can be used to upgrade @code{pip} to a
more recent release than the bundled one.  (Note that such an upgraded version
of @code{pip} is considered to be a separately installed package and will not be
removed if Python is uninstalled.)

The module is named @emph{ensure}pip because if called when @code{pip} is already
installed, it does nothing.  It also has an @code{--upgrade} option that will
cause it to install the bundled copy of @code{pip} if the existing installed
version of @code{pip} is older than the bundled copy.

@node enum<5>,pathlib<6>,ensurepip,新增模块<6>
@anchor{whatsnew/3 4 enum}@anchor{907}@anchor{whatsnew/3 4 whatsnew-enum}@anchor{8d3}
@subsubsection enum


The new @ref{79,,enum} module (defined in 
@geindex Python 提高建议; PEP 435
PEP 435@footnote{https://www.python.org/dev/peps/pep-0435}) provides a standard
implementation of enumeration types, allowing other modules (such as
@ref{ef,,socket}) to provide more informative error messages and better
debugging support by replacing opaque integer constants with backwards
compatible enumeration values.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 435

@item PEP 435@footnote{https://www.python.org/dev/peps/pep-0435} -- Adding an Enum type to the Python standard library

PEP 由 Barry Warsaw，Eli Bendersky 和 Ethan Furman 撰写 ，由 Ethan Furman 实现。
@end table


@node pathlib<6>,selectors<2>,enum<5>,新增模块<6>
@anchor{whatsnew/3 4 pathlib}@anchor{908}@anchor{whatsnew/3 4 whatsnew-pathlib}@anchor{8d4}
@subsubsection pathlib


The new @ref{c8,,pathlib} module offers classes representing filesystem paths
with semantics appropriate for different operating systems.  Path classes are
divided between @emph{pure paths}, which provide purely computational operations
without I/O, and @emph{concrete paths}, which inherit from pure paths but also
provide I/O operations.

For Python 3.4, this module is considered a @ref{45d,,provisional API}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 428

@item PEP 428@footnote{https://www.python.org/dev/peps/pep-0428} -- The pathlib module -- object-oriented filesystem paths

PEP 由 Antoine Pitrou 撰写并实现
@end table


@node selectors<2>,statistics<3>,pathlib<6>,新增模块<6>
@anchor{whatsnew/3 4 selectors}@anchor{909}@anchor{whatsnew/3 4 whatsnew-selectors}@anchor{8d5}
@subsubsection selectors


The new @ref{e6,,selectors} module (created as part of implementing 
@geindex Python 提高建议; PEP 3156
PEP 3156@footnote{https://www.python.org/dev/peps/pep-3156})
allows high-level and efficient I/O multiplexing, built upon the
@ref{e5,,select} module primitives.

@node statistics<3>,tracemalloc<4>,selectors<2>,新增模块<6>
@anchor{whatsnew/3 4 statistics}@anchor{90a}@anchor{whatsnew/3 4 whatsnew-statistics}@anchor{8d6}
@subsubsection statistics


The new @ref{f5,,statistics} module (defined in 
@geindex Python 提高建议; PEP 450
PEP 450@footnote{https://www.python.org/dev/peps/pep-0450}) offers some core
statistics functionality directly in the standard library. This module
supports calculation of the mean, median, mode, variance and standard
deviation of a data series.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 450

@item PEP 450@footnote{https://www.python.org/dev/peps/pep-0450} -- Adding A Statistics Module To The Standard Library

PEP 由 Steven D'Aprano 撰写并实现。
@end table


@node tracemalloc<4>,,statistics<3>,新增模块<6>
@anchor{whatsnew/3 4 tracemalloc}@anchor{90b}@anchor{whatsnew/3 4 whatsnew-tracemalloc}@anchor{8d7}
@subsubsection tracemalloc


The new @ref{11d,,tracemalloc} module (defined in 
@geindex Python 提高建议; PEP 454
PEP 454@footnote{https://www.python.org/dev/peps/pep-0454}) is a debug tool to
trace memory blocks allocated by Python. It provides the following information:


@itemize *

@item 
Trace where an object was allocated

@item 
按文件、按行统计python的内存块分配情况: 总大小、块的数量以及块平均大小。

@item 
对比两个内存快照的差异，以便排查内存泄漏
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 454

@item PEP 454@footnote{https://www.python.org/dev/peps/pep-0454} -- Add a new tracemalloc module to trace Python memory allocations

PEP 由 Victor Stinner 撰写并实现
@end table


@node 改进的模块<6>,CPython Implementation Changes,新增模块<6>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 improved-modules}@anchor{90c}
@subsection 改进的模块


@menu
* abc:: 
* aifc: aifc<2>. 
* argparse: argparse<3>. 
* audioop:: 
* base64:: 
* collections: collections<6>. 
* colorsys:: 
* contextlib: contextlib<4>. 
* dbm: dbm<5>. 
* dis: dis<2>. 
* doctest: doctest<2>. 
* email: email<3>. 
* filecmp:: 
* functools: functools<4>. 
* gc: gc<4>. 
* glob: glob<2>. 
* hashlib: hashlib<3>. 
* hmac: hmac<2>. 
* html:: 
* http: http<3>. 
* idlelib 与 IDLE: idlelib 与 IDLE<4>. 
* importlib: importlib<7>. 
* inspect: inspect<5>. 
* ipaddress: ipaddress<4>. 
* logging: logging<5>. 
* marshal:: 
* mmap: mmap<2>. 
* multiprocessing: multiprocessing<6>. 
* operator: operator<2>. 
* os: os<7>. 
* pdb: pdb<4>. 
* pickle: pickle<4>. 
* plistlib: plistlib<2>. 
* poplib: poplib<3>. 
* pprint: pprint<3>. 
* pty:: 
* pydoc: pydoc<4>. 
* re: re<5>. 
* resource:: 
* select:: 
* shelve:: 
* shutil: shutil<3>. 
* smtpd: smtpd<2>. 
* smtplib: smtplib<3>. 
* socket: socket<7>. 
* sqlite3: sqlite3<4>. 
* ssl: ssl<7>. 
* stat:: 
* struct: struct<2>. 
* subprocess: subprocess<4>. 
* sunau: sunau<2>. 
* sys: sys<7>. 
* tarfile: tarfile<4>. 
* textwrap:: 
* threading: threading<4>. 
* traceback: traceback<3>. 
* types: types<3>. 
* urllib: urllib<2>. 
* unittest: unittest<4>. 
* venv: venv<5>. 
* wave: wave<2>. 
* weakref: weakref<2>. 
* xml.etree: xml etree<2>. 
* zipfile: zipfile<4>. 

@end menu

@node abc,aifc<2>,,改进的模块<6>
@anchor{whatsnew/3 4 abc}@anchor{90d}
@subsubsection abc


New function @ref{90e,,abc.get_cache_token()} can be used to know when to invalidate
caches that are affected by changes in the object graph.  (Contributed
by Łukasz Langa in bpo-16832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16832}.)

New class @ref{90f,,ABC} has @ref{910,,ABCMeta} as its meta class.
Using @code{ABC} as a base class has essentially the same effect as specifying
@code{metaclass=abc.ABCMeta}, but is simpler to type and easier to read.
(Contributed by Bruno Dupuis in bpo-16049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16049}.)

@node aifc<2>,argparse<3>,abc,改进的模块<6>
@anchor{whatsnew/3 4 aifc}@anchor{911}
@subsubsection aifc


The @ref{912,,getparams()} method now returns a namedtuple rather than a
plain tuple.  (Contributed by Claudiu Popa in bpo-17818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17818}.)

@ref{565,,aifc.open()} now supports the context management protocol: when used in a
@ref{7e4,,with} block, the @ref{913,,close()} method of the returned
object will be called automatically at the end of the block.  (Contributed by
Serhiy Storchacha in bpo-16486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16486}.)

The @ref{914,,writeframesraw()} and @ref{915,,writeframes()}
methods now accept any @ref{6e9,,bytes-like object}.  (Contributed by Serhiy
Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node argparse<3>,audioop,aifc<2>,改进的模块<6>
@anchor{whatsnew/3 4 argparse}@anchor{916}
@subsubsection argparse


The @ref{917,,FileType} class now accepts @emph{encoding} and
@emph{errors} arguments, which are passed through to @ref{16f,,open()}.  (Contributed
by Lucas Maystre in bpo-11175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11175}.)

@node audioop,base64,argparse<3>,改进的模块<6>
@anchor{whatsnew/3 4 audioop}@anchor{918}
@subsubsection audioop


@ref{c,,audioop} now supports 24-bit samples.  (Contributed by Serhiy Storchaka
in bpo-12866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12866}.)

New @ref{919,,byteswap()} function converts big-endian samples to
little-endian and vice versa.  (Contributed by Serhiy Storchaka in
bpo-19641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19641}.)

All @ref{c,,audioop} functions now accept any @ref{6e9,,bytes-like object}.  Strings
are not accepted: they didn't work before, now they raise an error right away.
(Contributed by Serhiy Storchaka in bpo-16685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16685}.)

@node base64,collections<6>,audioop,改进的模块<6>
@anchor{whatsnew/3 4 base64}@anchor{91a}
@subsubsection base64


The encoding and decoding functions in @ref{d,,base64} now accept any
@ref{6e9,,bytes-like object} in cases where it previously required a
@ref{172,,bytes} or @ref{173,,bytearray} instance.  (Contributed by Nick Coghlan in
bpo-17839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17839}.)

New functions @ref{91b,,a85encode()}, @ref{91c,,a85decode()},
@ref{91d,,b85encode()}, and @ref{91e,,b85decode()} provide the ability to
encode and decode binary data from and to @code{Ascii85} and the git/mercurial
@code{Base85} formats, respectively.  The @code{a85} functions have options that can
be used to make them compatible with the variants of the @code{Ascii85} encoding,
including the Adobe variant.  (Contributed by Martin Morrison, the Mercurial
project, Serhiy Storchaka, and Antoine Pitrou in bpo-17618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17618}.)

@node collections<6>,colorsys,base64,改进的模块<6>
@anchor{whatsnew/3 4 collections}@anchor{91f}
@subsubsection collections


The @ref{920,,ChainMap.new_child()} method now accepts an @emph{m} argument specifying
the child map to add to the chain.  This allows an existing mapping and/or a
custom mapping type to be used for the child.  (Contributed by Vinay Sajip in
bpo-16613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16613}.)

@node colorsys,contextlib<4>,collections<6>,改进的模块<6>
@anchor{whatsnew/3 4 colorsys}@anchor{921}
@subsubsection colorsys


The number of digits in the coefficients for the RGB --- YIQ conversions have
been expanded so that they match the FCC NTSC versions.  The change in
results should be less than 1% and may better match results found elsewhere.
(Contributed by Brian Landers and Serhiy Storchaka in bpo-14323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14323}.)

@node contextlib<4>,dbm<5>,colorsys,改进的模块<6>
@anchor{whatsnew/3 4 contextlib}@anchor{922}
@subsubsection contextlib


The new @ref{923,,contextlib.suppress} context manager helps to clarify the
intent of code that deliberately suppresses exceptions from a single
statement.  (Contributed by Raymond Hettinger in bpo-15806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15806} and
Zero Piraeus in bpo-19266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19266}.)

The new @ref{7bf,,contextlib.redirect_stdout()} context manager makes it easier
for utility scripts to handle inflexible APIs that write their output to
@ref{428,,sys.stdout} and don't provide any options to redirect it.  Using the
context manager, the @ref{428,,sys.stdout} output can be redirected to any
other stream or, in conjunction with @ref{924,,io.StringIO}, to a string.
The latter can be especially useful, for example, to capture output
from a function that was written to implement a command line interface.
It is recommended only for utility scripts because it affects the
global state of @ref{428,,sys.stdout}.  (Contributed by Raymond Hettinger
in bpo-15805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15805}.)

The @ref{23,,contextlib} documentation has also been updated to include a
@ref{925,,discussion} of the
differences between single use, reusable and reentrant context managers.

@node dbm<5>,dis<2>,contextlib<4>,改进的模块<6>
@anchor{whatsnew/3 4 dbm}@anchor{926}
@subsubsection dbm


@ref{927,,dbm.open()} objects now support the context management protocol.  When
used in a @ref{7e4,,with} statement, the @code{close} method of the database
object will be called automatically at the end of the block.  (Contributed by
Claudiu Popa and Nick Coghlan in bpo-19282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19282}.)

@node dis<2>,doctest<2>,dbm<5>,改进的模块<6>
@anchor{whatsnew/3 4 dis}@anchor{928}
@subsubsection dis


Functions @ref{929,,show_code()}, @ref{493,,dis()}, @ref{92a,,distb()}, and
@ref{92b,,disassemble()} now accept a keyword-only @emph{file} argument that
controls where they write their output.

The @ref{37,,dis} module is now built around an @ref{92c,,Instruction} class
that provides object oriented access to the details of each individual bytecode
operation.

A new method, @ref{92d,,get_instructions()}, provides an iterator that emits
the Instruction stream for a given piece of Python code.  Thus it is now
possible to write a program that inspects and manipulates a bytecode
object in ways different from those provided by the @ref{37,,dis} module
itself.  For example:

@example
>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
...     print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE
@end example

The various display tools in the @ref{37,,dis} module have been rewritten to use
these new components.

In addition, a new application-friendly class @ref{92e,,Bytecode} provides
an object-oriented API for inspecting bytecode in both in human-readable form
and for iterating over instructions.  The @ref{92e,,Bytecode} constructor
takes the same arguments that @code{get_instruction()} does (plus an
optional @emph{current_offset}), and the resulting object can be iterated to produce
@ref{92c,,Instruction} objects.  But it also has a @ref{92f,,dis}
method, equivalent to calling @ref{493,,dis} on the constructor argument, but
returned as a multi-line string:

@example
>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
...     print('@{@} (@{@})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines()       
['  1           0 LOAD_FAST                0 (x)',
 '      -->     3 LOAD_CONST               1 (1)',
 '              6 BINARY_ADD',
 '              7 RETURN_VALUE']
@end example

@ref{92e,,Bytecode} also has a class method,
@ref{930,,from_traceback()}, that provides the ability to manipulate a
traceback (that is, @code{print(Bytecode.from_traceback(tb).dis())} is equivalent
to @code{distb(tb)}).

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in bpo-11816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11816}
and Claudiu Popa in bpo-17916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17916}.)

New function @ref{931,,stack_effect()} computes the effect on the Python stack
of a given opcode and argument, information that is not otherwise available.
(Contributed by Larry Hastings in bpo-19722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19722}.)

@node doctest<2>,email<3>,dis<2>,改进的模块<6>
@anchor{whatsnew/3 4 doctest}@anchor{932}
@subsubsection doctest


A new @ref{933,,option flag}, @ref{934,,FAIL_FAST}, halts
test running as soon as the first failure is detected.  (Contributed by R.
David Murray and Daniel Urban in bpo-16522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16522}.)

The @ref{66,,doctest} command line interface now uses @ref{5,,argparse}, and has two
new options, @code{-o} and @code{-f}.  @code{-o} allows @ref{933,,doctest options} to be specified on the command line, and @code{-f} is a
shorthand for @code{-o FAIL_FAST} (to parallel the similar option supported by the
@ref{124,,unittest} CLI).  (Contributed by R. David Murray in bpo-11390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11390}.)

@ref{66,,doctest} will now find doctests in extension module @code{__doc__} strings.
(Contributed by Zachary Ware in bpo-3158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3158}.)

@node email<3>,filecmp,doctest<2>,改进的模块<6>
@anchor{whatsnew/3 4 email}@anchor{935}
@subsubsection email


@ref{936,,as_string()} now accepts a @emph{policy} argument to
override the default policy of the message when generating a string
representation of it.  This means that @code{as_string} can now be used in more
circumstances, instead of having to create and use a @ref{6c,,generator} in
order to pass formatting parameters to its @code{flatten} method.  (Contributed by
R. David Murray in bpo-18600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18600}.)

New method @ref{937,,as_bytes()} added to produce a bytes
representation of the message in a fashion similar to how @code{as_string}
produces a string representation.  It does not accept the @emph{maxheaderlen}
argument, but does accept the @emph{unixfrom} and @emph{policy} arguments. The
@ref{644,,Message} @ref{938,,__bytes__()} method
calls it, meaning that @code{bytes(mymsg)} will now produce the intuitive
result:  a bytes object containing the fully formatted message.  (Contributed
by R. David Murray in bpo-18600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18600}.)

The @ref{939,,Message.set_param()} message now accepts a @emph{replace} keyword argument.
When specified, the associated header will be updated without changing
its location in the list of headers.  For backward compatibility, the default
is @code{False}.  (Contributed by R. David Murray in bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891}.)
@anchor{whatsnew/3 4 whatsnew-email-contentmanager}@anchor{8db}
A pair of new subclasses of @ref{644,,Message} have been added
(@ref{645,,EmailMessage} and @ref{93a,,MIMEPart}), along with a new sub-module,
@ref{69,,contentmanager} and a new @ref{73,,policy} attribute
@ref{93b,,content_manager}.  All documentation is
currently in the new module, which is being added as part of email's new
@ref{45d,,provisional API}.  These classes provide a number of new methods that
make extracting content from and inserting content into email messages much
easier.  For details, see the @ref{69,,contentmanager} documentation and
the @ref{93c,,email; 示例}.  These API additions complete the
bulk of the work that was planned as part of the email6 project.  The currently
provisional API is scheduled to become final in Python 3.5 (possibly with a few
minor additions in the area of error handling).  (Contributed by R. David
Murray in bpo-18891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18891}.)

@node filecmp,functools<4>,email<3>,改进的模块<6>
@anchor{whatsnew/3 4 filecmp}@anchor{93d}
@subsubsection filecmp


A new @ref{93e,,clear_cache()} function provides the ability to clear the
@ref{7d,,filecmp} comparison cache, which uses @ref{328,,os.stat()} information to
determine if the file has changed since the last compare.  This can be used,
for example, if the file might have been changed and re-checked in less time
than the resolution of a particular filesystem's file modification time field.
(Contributed by Mark Levitt in bpo-18149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18149}.)

New module attribute @ref{93f,,DEFAULT_IGNORES} provides the list of
directories that are used as the default value for the @emph{ignore} parameter of
the @ref{940,,dircmp()} function.  (Contributed by Eli Bendersky in
bpo-15442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15442}.)

@node functools<4>,gc<4>,filecmp,改进的模块<6>
@anchor{whatsnew/3 4 functools}@anchor{941}
@subsubsection functools


The new @ref{3c7,,partialmethod()} descriptor brings partial argument
application to descriptors, just as @ref{8bf,,partial()} provides
for normal callables. The new descriptor also makes it easier to get
arbitrary callables (including @ref{8bf,,partial()} instances)
to behave like normal instance methods when included in a class definition.
(Contributed by Alon Horev and Nick Coghlan in bpo-4331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4331}.)
@anchor{whatsnew/3 4 whatsnew-singledispatch}@anchor{8d8}
The new @ref{499,,singledispatch()} decorator brings support for
single-dispatch generic functions to the Python standard library. Where
object oriented programming focuses on grouping multiple operations on a
common set of data into a class, a generic function focuses on grouping
multiple implementations of an operation that allows it to work with
@emph{different} kinds of data.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 443

@item PEP 443@footnote{https://www.python.org/dev/peps/pep-0443} -- Single-dispatch generic functions

PEP 由 Łukasz Langa 撰写并实现。
@end table


@ref{942,,total_ordering()} now supports a return value of
@ref{203,,NotImplemented} from the underlying comparison function.  (Contributed
by Katie Miller in bpo-10042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10042}.)

A pure-python version of the @ref{8bf,,partial()} function is now in the
stdlib; in CPython it is overridden by the C accelerated version, but it is
available for other implementations to use.  (Contributed by Brian Thorne in
bpo-12428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12428}.)

@node gc<4>,glob<2>,functools<4>,改进的模块<6>
@anchor{whatsnew/3 4 gc}@anchor{943}
@subsubsection gc


New function @ref{944,,get_stats()} returns a list of three per-generation
dictionaries containing the collections statistics since interpreter startup.
(Contributed by Antoine Pitrou in bpo-16351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16351}.)

@node glob<2>,hashlib<3>,gc<4>,改进的模块<6>
@anchor{whatsnew/3 4 glob}@anchor{945}
@subsubsection glob


A new function @ref{946,,escape()} provides a way to escape special characters
in a filename so that they do not become part of the globbing expansion but are
instead matched literally.  (Contributed by Serhiy Storchaka in bpo-8402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8402}.)

@node hashlib<3>,hmac<2>,glob<2>,改进的模块<6>
@anchor{whatsnew/3 4 hashlib}@anchor{947}
@subsubsection hashlib


A new @ref{8dd,,hashlib.pbkdf2_hmac()} function provides
the PKCS#5 password-based key derivation function 2@footnote{https://en.wikipedia.org/wiki/PBKDF2}.  (Contributed by Christian
Heimes in bpo-18582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18582}.)

The @ref{948,,name} attribute of @ref{8c,,hashlib} hash objects is now
a formally supported interface.  It has always existed in CPython's
@ref{8c,,hashlib} (although it did not return lower case names for all supported
hashes), but it was not a public interface and so some other Python
implementations have not previously supported it.  (Contributed by Jason R.
Coombs in bpo-18532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18532}.)

@node hmac<2>,html,hashlib<3>,改进的模块<6>
@anchor{whatsnew/3 4 hmac}@anchor{949}
@subsubsection hmac


@ref{8e,,hmac} now accepts @code{bytearray} as well as @code{bytes} for the @emph{key}
argument to the @ref{3f5,,new()} function, and the @emph{msg} parameter to both the
@ref{3f5,,new()} function and the @ref{94a,,update()} method now
accepts any type supported by the @ref{8c,,hashlib} module.  (Contributed
by Jonas Borgström in bpo-18240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18240}.)

The @emph{digestmod} argument to the @ref{3f5,,hmac.new()} function may now be any hash
digest name recognized by @ref{8c,,hashlib}.  In addition, the current behavior in
which the value of @emph{digestmod} defaults to @code{MD5} is deprecated: in a
future version of Python there will be no default value.  (Contributed by
Christian Heimes in bpo-17276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17276}.)

With the addition of @ref{94b,,block_size} and @ref{94c,,name}
attributes (and the formal documentation of the @ref{94d,,digest_size}
attribute), the @ref{8e,,hmac} module now conforms fully to the 
@geindex Python 提高建议; PEP 247
PEP 247@footnote{https://www.python.org/dev/peps/pep-0247} API.
(Contributed by Christian Heimes in bpo-18775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18775}.)

@node html,http<3>,hmac<2>,改进的模块<6>
@anchor{whatsnew/3 4 html}@anchor{94e}
@subsubsection html


New function @ref{22c,,unescape()} function converts HTML5 character references to
the corresponding Unicode characters.  (Contributed by Ezio Melotti in
bpo-2927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2927}.)

@ref{22b,,HTMLParser} accepts a new keyword argument
@emph{convert_charrefs} that, when @code{True}, automatically converts all character
references.  For backward-compatibility, its value defaults to @code{False}, but
it will change to @code{True} in a future version of Python, so you are invited to
set it explicitly and update your code to use this new feature.  (Contributed
by Ezio Melotti in bpo-13633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13633}.)

The @emph{strict} argument of @ref{22b,,HTMLParser} is now deprecated.
(Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}.)

@node http<3>,idlelib 与 IDLE<4>,html,改进的模块<6>
@anchor{whatsnew/3 4 http}@anchor{94f}
@subsubsection http


@ref{950,,send_error()} now accepts an
optional additional @emph{explain} parameter which can be used to provide an
extended error description, overriding the hardcoded default if there is one.
This extended error description will be formatted using the
@code{error_message_format} attribute and sent as the body
of the error response.  (Contributed by Karl Cow in bpo-12921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12921}.)

The @ref{96,,http.server} @ref{951,,command line interface} now has
a @code{-b/--bind} option that causes the server to listen on a specific address.
(Contributed by Malte Swart in bpo-17764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17764}.)

@node idlelib 与 IDLE<4>,importlib<7>,http<3>,改进的模块<6>
@anchor{whatsnew/3 4 idlelib-and-idle}@anchor{952}
@subsubsection idlelib 与 IDLE


Since idlelib implements the IDLE shell and editor and is not intended for
import by other programs, it gets improvements with every release. See
@code{Lib/idlelib/NEWS.txt} for a cumulative list of changes since 3.3.0,
as well as changes made in future 3.4.x releases. This file is also available
from the IDLE Help ‣ About IDLE dialog.

@node importlib<7>,inspect<5>,idlelib 与 IDLE<4>,改进的模块<6>
@anchor{whatsnew/3 4 importlib}@anchor{953}
@subsubsection importlib


The @ref{954,,InspectLoader} ABC defines a new method,
@ref{7ea,,source_to_code()} that accepts source
data and a path and returns a code object.  The default implementation
is equivalent to @code{compile(data, path, 'exec', dont_inherit=True)}.
(Contributed by Eric Snow and Brett Cannon in bpo-15627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15627}.)

@ref{954,,InspectLoader} also now has a default implementation
for the @ref{955,,get_code()} method.  However,
it will normally be desirable to override the default implementation
for performance reasons.  (Contributed by Brett Cannon in bpo-18072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18072}.)

The @ref{4a8,,reload()} function has been moved from @ref{99,,imp} to
@ref{9a,,importlib} as part of the @ref{99,,imp} module deprecation.  (Contributed by
Berker Peksag in bpo-18193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18193}.)

@ref{9f,,importlib.util} now has a @ref{956,,MAGIC_NUMBER} attribute
providing access to the bytecode version number.  This replaces the
@ref{957,,get_magic()} function in the deprecated @ref{99,,imp} module.
(Contributed by Brett Cannon in bpo-18192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18192}.)

New @ref{9f,,importlib.util} functions @ref{65a,,cache_from_source()}
and @ref{65b,,source_from_cache()} replace the same-named functions
in the deprecated @ref{99,,imp} module.  (Contributed by Brett Cannon in
bpo-18194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18194}.)

The @ref{9a,,importlib} bootstrap @code{NamespaceLoader} now conforms to
the @ref{954,,InspectLoader} ABC, which means that @code{runpy} and
@code{python -m} can now be used with namespace packages.  (Contributed
by Brett Cannon in bpo-18058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18058}.)

@ref{9f,,importlib.util} has a new function @ref{958,,decode_source()}
that decodes source from bytes using universal newline processing.  This is
useful for implementing @ref{959,,InspectLoader.get_source()} methods.

@ref{659,,importlib.machinery.ExtensionFileLoader} now has a
@ref{95a,,get_filename()} method.  This was
inadvertently omitted in the original implementation.  (Contributed by Eric
Snow in bpo-19152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19152}.)

@node inspect<5>,ipaddress<4>,importlib<7>,改进的模块<6>
@anchor{whatsnew/3 4 inspect}@anchor{95b}
@subsubsection inspect


The @ref{a0,,inspect} module now offers a basic @ref{95c,,command line interface} to quickly display source code and other
information for modules, classes and functions.  (Contributed by Claudiu Popa
and Nick Coghlan in bpo-18626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18626}.)

@ref{95d,,unwrap()} makes it easy to unravel wrapper function chains
created by @ref{95e,,functools.wraps()} (and any other API that sets the
@code{__wrapped__} attribute on a wrapper function).  (Contributed by
Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13266}.)

As part of the implementation of the new @ref{79,,enum} module, the
@ref{a0,,inspect} module now has substantially better support for custom
@code{__dir__} methods and dynamic class attributes provided through
metaclasses.  (Contributed by Ethan Furman in bpo-18929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18929} and
bpo-19030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19030}.)

@ref{660,,getfullargspec()} and @ref{65f,,getargspec()}
now use the @ref{65e,,signature()} API. This allows them to
support a much broader range of callables, including those with
@code{__signature__} attributes, those with metadata provided by argument
clinic, @ref{8bf,,functools.partial()} objects and more. Note that, unlike
@ref{65e,,signature()}, these functions still ignore @code{__wrapped__}
attributes, and report the already bound first argument for bound methods,
so it is still necessary to update your code to use
@ref{65e,,signature()} directly if those features are desired.
(Contributed by Yury Selivanov in bpo-17481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17481}.)

@ref{65e,,signature()} now supports duck types of CPython functions,
which adds support for functions compiled with Cython.  (Contributed
by Stefan Behnel and Yury Selivanov in bpo-17159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17159}.)

@node ipaddress<4>,logging<5>,inspect<5>,改进的模块<6>
@anchor{whatsnew/3 4 ipaddress}@anchor{95f}
@subsubsection ipaddress


@ref{a2,,ipaddress} was added to the standard library in Python 3.3 as a
@ref{45d,,provisional API}. With the release of Python 3.4, this qualification
has been removed: @ref{a2,,ipaddress} is now considered a stable API, covered
by the normal standard library requirements to maintain backwards
compatibility.

A new @ref{960,,is_global} property is @code{True} if
an address is globally routeable.  (Contributed by Peter Moody in
bpo-17400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17400}.)

@node logging<5>,marshal,ipaddress<4>,改进的模块<6>
@anchor{whatsnew/3 4 logging}@anchor{961}
@subsubsection logging


The @ref{962,,TimedRotatingFileHandler} has a new @emph{atTime}
parameter that can be used to specify the time of day when rollover should
happen.  (Contributed by Ronald Oussoren in bpo-9556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9556}.)

@ref{963,,SocketHandler} and
@ref{964,,DatagramHandler} now support Unix domain sockets (by
setting @emph{port} to @code{None}).  (Contributed by Vinay Sajip in commit
ce46195b56a9.)

@ref{4b8,,fileConfig()} now accepts a
@ref{965,,configparser.RawConfigParser} subclass instance for the @emph{fname}
parameter.  This facilitates using a configuration file when logging
configuration is just a part of the overall application configuration, or where
the application modifies the configuration before passing it to
@ref{4b8,,fileConfig()}.  (Contributed by Vinay Sajip in
bpo-16110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16110}.)

Logging configuration data received from a socket via the
@ref{966,,logging.config.listen()} function can now be validated before being
processed by supplying a verification function as the argument to the new
@emph{verify} keyword argument.  (Contributed by Vinay Sajip in bpo-15452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15452}.)

@node marshal,mmap<2>,logging<5>,改进的模块<6>
@anchor{whatsnew/3 4 marshal}@anchor{967}@anchor{whatsnew/3 4 whatsnew-marshal-3}@anchor{8d0}
@subsubsection marshal


The default @ref{b0,,marshal} version has been bumped to 3.  The code implementing
the new version restores the Python2 behavior of recording only one copy of
interned strings and preserving the interning on deserialization, and extends
this "one copy" ability to any object type (including handling recursive
references).  This reduces both the size of @code{.pyc} files and the amount of
memory a module occupies in memory when it is loaded from a @code{.pyc} (or
@code{.pyo}) file.  (Contributed by Kristján Valur Jónsson in bpo-16475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16475},
with additional speedups by Antoine Pitrou in bpo-19219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19219}.)

@node mmap<2>,multiprocessing<6>,marshal,改进的模块<6>
@anchor{whatsnew/3 4 mmap}@anchor{968}
@subsubsection mmap


mmap objects can now be @ref{131,,weakref}ed.  (Contributed by Valerie Lambert in
bpo-4885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4885}.)

@node multiprocessing<6>,operator<2>,mmap<2>,改进的模块<6>
@anchor{whatsnew/3 4 multiprocessing}@anchor{969}
@subsubsection multiprocessing

@anchor{whatsnew/3 4 whatsnew-multiprocessing-no-fork}@anchor{8da}
On Unix two new @ref{96a,,start methods},
@code{spawn} and @code{forkserver}, have been added for starting processes using
@ref{b7,,multiprocessing}.  These make the mixing of processes with threads more
robust, and the @code{spawn} method matches the semantics that multiprocessing has
always used on Windows.  New function
@ref{96b,,get_all_start_methods()} reports all start methods
available on the platform, @ref{96c,,get_start_method()} reports
the current start method, and @ref{96d,,set_start_method()} sets
the start method.  (Contributed by Richard Oudkerk in bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713}.)

@ref{b7,,multiprocessing} also now has the concept of a @code{context}, which
determines how child processes are created.  New function
@ref{96e,,get_context()} returns a context that uses a specified
start method.  It has the same API as the @ref{b7,,multiprocessing} module itself,
so you can use it to create @ref{96f,,Pool}s and other
objects that will operate within that context.  This allows a framework and an
application or different parts of the same application to use multiprocessing
without interfering with each other.  (Contributed by Richard Oudkerk in
bpo-18999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18999}.)

Except when using the old @emph{fork} start method, child processes no longer
inherit unneeded handles/file descriptors from their parents (part of
bpo-8713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8713}).

@ref{b7,,multiprocessing} now relies on @ref{e2,,runpy} (which implements the
@code{-m} switch) to initialise @code{__main__} appropriately in child processes
when using the @code{spawn} or @code{forkserver} start methods. This resolves some
edge cases where combining multiprocessing, the @code{-m} command line switch,
and explicit relative imports could cause obscure failures in child
processes.  (Contributed by Nick Coghlan in bpo-19946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19946}.)

@node operator<2>,os<7>,multiprocessing<6>,改进的模块<6>
@anchor{whatsnew/3 4 operator}@anchor{970}
@subsubsection operator


New function @ref{971,,length_hint()} provides an implementation of the
specification for how the @ref{903,,__length_hint__()} special method should
be used, as part of the 
@geindex Python 提高建议; PEP 424
PEP 424@footnote{https://www.python.org/dev/peps/pep-0424} formal specification of this language
feature.  (Contributed by Armin Ronacher in bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)

There is now a pure-python version of the @ref{c2,,operator} module available for
reference and for use by alternate implementations of Python.  (Contributed by
Zachary Ware in bpo-16694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16694}.)

@node os<7>,pdb<4>,operator<2>,改进的模块<6>
@anchor{whatsnew/3 4 os}@anchor{972}
@subsubsection os


There are new functions to get and set the @ref{8f1,,inheritable flag} of a file descriptor (@ref{8f2,,os.get_inheritable()},
@ref{8f3,,os.set_inheritable()}) or a Windows handle
(@ref{8f4,,os.get_handle_inheritable()}, @ref{8f5,,os.set_handle_inheritable()}).

New function @ref{973,,cpu_count()} reports the number of CPUs available on the
platform on which Python is running (or @code{None} if the count can't be
determined).  The @ref{974,,multiprocessing.cpu_count()} function is now implemented
in terms of this function).  (Contributed by Trent Nelson, Yogesh Chaudhari,
Victor Stinner, and Charles-François Natali in bpo-17914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17914}.)

@ref{975,,os.path.samestat()} is now available on the Windows platform (and the
@ref{976,,os.path.samefile()} implementation is now shared between Unix and
Windows).  (Contributed by Brian Curtin in bpo-11939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11939}.)

@ref{330,,os.path.ismount()} now recognizes volumes mounted below a drive
root on Windows.  (Contributed by Tim Golden in bpo-9035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9035}.)

@ref{762,,os.open()} supports two new flags on platforms that provide them,
@ref{977,,O_PATH} (un-opened file descriptor), and @ref{978,,O_TMPFILE}
(unnamed temporary file; as of 3.4.0 release available only on Linux systems
with a kernel version of 3.11 or newer that have uapi headers).  (Contributed
by Christian Heimes in bpo-18673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18673} and Benjamin Peterson, respectively.)

@node pdb<4>,pickle<4>,os<7>,改进的模块<6>
@anchor{whatsnew/3 4 pdb}@anchor{979}
@subsubsection pdb


@ref{c9,,pdb} has been enhanced to handle generators, @ref{2ce,,yield}, and
@code{yield from} in a more useful fashion.  This is especially helpful when
debugging @ref{9,,asyncio} based programs.  (Contributed by Andrew Svetlov and
Xavier de Gaye in bpo-16596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16596}.)

The @code{print} command has been removed from @ref{c9,,pdb}, restoring access to the
Python @ref{97a,,print()} function from the pdb command line.  Python2's @code{pdb} did
not have a @code{print} command; instead, entering @code{print} executed the
@code{print} statement.  In Python3 @code{print} was mistakenly made an alias for the
pdb @ref{97b,,p} command.  @code{p}, however, prints the @code{repr} of its argument,
not the @code{str} like the Python2 @code{print} command did.  Worse, the Python3
@code{pdb print} command shadowed the Python3 @code{print} function, making it
inaccessible at the @code{pdb} prompt.  (Contributed by Connor Osborn in
bpo-18764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18764}.)

@node pickle<4>,plistlib<2>,pdb<4>,改进的模块<6>
@anchor{whatsnew/3 4 pickle}@anchor{97c}@anchor{whatsnew/3 4 whatsnew-protocol-4}@anchor{8d9}
@subsubsection pickle


@ref{ca,,pickle} now supports (but does not use by default) a new pickle protocol,
protocol 4.  This new protocol addresses a number of issues that were present
in previous protocols, such as the serialization of nested classes, very large
strings and containers, and classes whose @ref{97d,,__new__()} method takes
keyword-only arguments.  It also provides some efficiency improvements.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3154

@item PEP 3154@footnote{https://www.python.org/dev/peps/pep-3154} -- Pickle protocol 4

PEP 由 Antoine Pitrou 撰写，并由 Alexandre Vassalotti 实现
@end table


@node plistlib<2>,poplib<3>,pickle<4>,改进的模块<6>
@anchor{whatsnew/3 4 plistlib}@anchor{97e}
@subsubsection plistlib


@ref{cf,,plistlib} now has an API that is similar to the standard pattern for
stdlib serialization protocols, with new @ref{21f,,load()},
@ref{221,,dump()}, @ref{220,,loads()}, and @ref{222,,dumps()}
functions.  (The older API is now deprecated.)  In addition to the already
supported XML plist format (@ref{97f,,FMT_XML}), it also now supports
the binary plist format (@ref{980,,FMT_BINARY}).  (Contributed by Ronald
Oussoren and others in bpo-14455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14455}.)

@node poplib<3>,pprint<3>,plistlib<2>,改进的模块<6>
@anchor{whatsnew/3 4 poplib}@anchor{981}
@subsubsection poplib


Two new methods have been added to @ref{d0,,poplib}: @ref{982,,capa()},
which returns the list of capabilities advertised by the POP server, and
@ref{983,,stls()}, which switches a clear-text POP3 session into an
encrypted POP3 session if the POP server supports it.  (Contributed by Lorenzo
Catucci in bpo-4473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4473}.)

@node pprint<3>,pty,poplib<3>,改进的模块<6>
@anchor{whatsnew/3 4 pprint}@anchor{984}
@subsubsection pprint


The @ref{d2,,pprint} module's @ref{985,,PrettyPrinter} class and its
@ref{986,,pformat()}, and @ref{348,,pprint()} functions have a new
option, @emph{compact}, that controls how the output is formatted.  Currently
setting @emph{compact} to @code{True} means that sequences will be printed with as many
sequence elements as will fit within @emph{width} on each (indented) line.
(Contributed by Serhiy Storchaka in bpo-19132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19132}.)

Long strings are now wrapped using Python's normal line continuation
syntax.  (Contributed by Antoine Pitrou in bpo-17150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17150}.)

@node pty,pydoc<4>,pprint<3>,改进的模块<6>
@anchor{whatsnew/3 4 pty}@anchor{987}
@subsubsection pty


@ref{988,,pty.spawn()} now returns the status value from @ref{76a,,os.waitpid()} on
the child process, instead of @code{None}.  (Contributed by Gregory P. Smith.)

@node pydoc<4>,re<5>,pty,改进的模块<6>
@anchor{whatsnew/3 4 pydoc}@anchor{989}
@subsubsection pydoc


The @ref{d9,,pydoc} module is now based directly on the @ref{65e,,inspect.signature()}
introspection API, allowing it to provide signature information for a wider
variety of callable objects. This change also means that @code{__wrapped__}
attributes are now taken into account when displaying help information.
(Contributed by Larry Hastings in bpo-19674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19674}.)

The @ref{d9,,pydoc} module no longer displays the @code{self} parameter for
already bound methods. Instead, it aims to always display the exact current
signature of the supplied callable.  (Contributed by Larry Hastings in
bpo-20710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20710}.)

In addition to the changes that have been made to @ref{d9,,pydoc} directly,
its handling of custom @code{__dir__} methods and various descriptor
behaviours has also been improved substantially by the underlying changes in
the @ref{a0,,inspect} module.

As the @ref{175,,help()} builtin is based on @ref{d9,,pydoc}, the above changes also
affect the behaviour of @ref{175,,help()}.

@node re<5>,resource,pydoc<4>,改进的模块<6>
@anchor{whatsnew/3 4 re}@anchor{98a}
@subsubsection re


New @ref{98b,,fullmatch()} function and @code{regex.fullmatch()} method anchor
the pattern at both ends of the string to match.  This provides a way to be
explicit about the goal of the match, which avoids a class of subtle bugs where
@code{$} characters get lost during code changes or the addition of alternatives
to an existing regular expression.  (Contributed by Matthew Barnett in
bpo-16203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16203}.)

The repr of @ref{98c,,regex objects} now includes the pattern
and the flags; the repr of @ref{98d,,match objects} now
includes the start, end, and the part of the string that matched.  (Contributed
by Hugo Lopes Tavares and Serhiy Storchaka in bpo-13592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13592} and
bpo-17087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17087}.)

@node resource,select,re<5>,改进的模块<6>
@anchor{whatsnew/3 4 resource}@anchor{98e}
@subsubsection resource


New @ref{98f,,prlimit()} function, available on Linux platforms with a
kernel version of 2.6.36 or later and glibc of 2.13 or later, provides the
ability to query or set the resource limits for processes other than the one
making the call.  (Contributed by Christian Heimes in bpo-16595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16595}.)

On Linux kernel version 2.6.36 or later, there are also some new
Linux specific constants: @ref{990,,RLIMIT_MSGQUEUE},
@ref{991,,RLIMIT_NICE}, @ref{992,,RLIMIT_RTPRIO},
@ref{993,,RLIMIT_RTTIME}, and @ref{994,,RLIMIT_SIGPENDING}.
(Contributed by Christian Heimes in bpo-19324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19324}.)

On FreeBSD version 9 and later, there some new FreeBSD specific constants:
@ref{995,,RLIMIT_SBSIZE}, @ref{996,,RLIMIT_SWAP}, and
@ref{997,,RLIMIT_NPTS}.  (Contributed by Claudiu Popa in
bpo-19343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19343}.)

@node select,shelve,resource,改进的模块<6>
@anchor{whatsnew/3 4 select}@anchor{998}
@subsubsection select


@ref{999,,epoll} objects now support the context management protocol.
When used in a @ref{7e4,,with} statement, the @ref{99a,,close()}
method will be called automatically at the end of the block.  (Contributed
by Serhiy Storchaka in bpo-16488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16488}.)

@ref{99b,,devpoll} objects now have @ref{99c,,fileno()} and
@ref{99d,,close()} methods, as well as a new attribute
@ref{99e,,closed}.  (Contributed by Victor Stinner in
bpo-18794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18794}.)

@node shelve,shutil<3>,select,改进的模块<6>
@anchor{whatsnew/3 4 shelve}@anchor{99f}
@subsubsection shelve


@ref{9a0,,Shelf} instances may now be used in @ref{7e4,,with} statements,
and will be automatically closed at the end of the @code{with} block.
(Contributed by Filip Gruszczyński in bpo-13896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13896}.)

@node shutil<3>,smtpd<2>,shelve,改进的模块<6>
@anchor{whatsnew/3 4 shutil}@anchor{9a1}
@subsubsection shutil


@ref{389,,copyfile()} now raises a specific @ref{9a2,,Error} subclass,
@ref{9a3,,SameFileError}, when the source and destination are the same
file, which allows an application to take appropriate action on this specific
error.  (Contributed by Atsuo Ishimoto and Hynek Schlawack in
bpo-1492704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1492704}.)

@node smtpd<2>,smtplib<3>,shutil<3>,改进的模块<6>
@anchor{whatsnew/3 4 smtpd}@anchor{9a4}
@subsubsection smtpd


The @ref{703,,SMTPServer} and @ref{702,,SMTPChannel} classes now
accept a @emph{map} keyword argument which, if specified, is passed in to
@ref{9a5,,asynchat.async_chat} as its @emph{map} argument.  This allows an application
to avoid affecting the global socket map.  (Contributed by Vinay Sajip in
bpo-11959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11959}.)

@node smtplib<3>,socket<7>,smtpd<2>,改进的模块<6>
@anchor{whatsnew/3 4 smtplib}@anchor{9a6}
@subsubsection smtplib


@ref{9a7,,SMTPException} is now a subclass of @ref{30b,,OSError}, which allows
both socket level errors and SMTP protocol level errors to be caught in one
try/except statement by code that only cares whether or not an error occurred.
(Contributed by Ned Jackson Lovely in bpo-2118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2118}.)

@node socket<7>,sqlite3<4>,smtplib<3>,改进的模块<6>
@anchor{whatsnew/3 4 socket}@anchor{9a8}
@subsubsection socket


The socket module now supports the @ref{9a9,,CAN_BCM} protocol on
platforms that support it.  (Contributed by Brian Thorne in bpo-15359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15359}.)

Socket objects have new methods to get or set their @ref{8f1,,inheritable flag}, @ref{8f6,,get_inheritable()} and
@ref{8f7,,set_inheritable()}.

The @code{socket.AF_*} and @code{socket.SOCK_*} constants are now enumeration values
using the new @ref{79,,enum} module.  This allows meaningful names to be printed
during debugging, instead of integer "magic numbers".

The @ref{9aa,,AF_LINK} constant is now available on BSD and OSX.

@ref{238,,inet_pton()} and @ref{9ab,,inet_ntop()} are now supported
on Windows.  (Contributed by Atsuo Ishimoto in bpo-7171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7171}.)

@node sqlite3<4>,ssl<7>,socket<7>,改进的模块<6>
@anchor{whatsnew/3 4 sqlite3}@anchor{9ac}
@subsubsection sqlite3


A new boolean parameter to the @ref{4e9,,connect()} function, @emph{uri}, can be
used to indicate that the @emph{database} parameter is a @code{uri} (see the SQLite URI documentation@footnote{https://www.sqlite.org/uri.html}).  (Contributed by poq in
bpo-13773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13773}.)

@node ssl<7>,stat,sqlite3<4>,改进的模块<6>
@anchor{whatsnew/3 4 ssl}@anchor{9ad}
@subsubsection ssl

@anchor{whatsnew/3 4 whatsnew-tls-11-12}@anchor{8de}
@ref{9ae,,PROTOCOL_TLSv1_1} and @ref{9af,,PROTOCOL_TLSv1_2} (TLSv1.1 and
TLSv1.2 support) have been added; support for these protocols is only available if
Python is linked with OpenSSL 1.0.1 or later.  (Contributed by Michele Orrù and
Antoine Pitrou in bpo-16692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16692}.)
@anchor{whatsnew/3 4 whatsnew34-sslcontext}@anchor{8e1}
New function @ref{9b0,,create_default_context()} provides a standard way to
obtain an @ref{4f2,,SSLContext} whose settings are intended to be a
reasonable balance between compatibility and security.  These settings are
more stringent than the defaults provided by the @ref{4f2,,SSLContext}
constructor, and may be adjusted in the future, without prior deprecation, if
best-practice security requirements change.  The new recommended best
practice for using stdlib libraries that support SSL is to use
@ref{9b0,,create_default_context()} to obtain an @ref{4f2,,SSLContext}
object, modify it if needed, and then pass it as the @emph{context} argument
of the appropriate stdlib API.  (Contributed by Christian Heimes
in bpo-19689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19689}.)

@ref{4f2,,SSLContext} method @ref{8e2,,load_verify_locations()}
accepts a new optional argument @emph{cadata}, which can be used to provide PEM or
DER encoded certificates directly via strings or bytes, respectively.
(Contributed by Christian Heimes in bpo-18138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18138}.)

New function @ref{9b1,,get_default_verify_paths()} returns
a named tuple of the paths and environment variables that the
@ref{9b2,,set_default_verify_paths()} method uses to set
OpenSSL's default @code{cafile} and @code{capath}.  This can be an aid in
debugging default verification issues.  (Contributed by Christian Heimes
in bpo-18143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18143}.)

@ref{4f2,,SSLContext} has a new method,
@ref{9b3,,cert_store_stats()}, that reports the number of loaded
@code{X.509} certs, @code{X.509 CA} certs, and certificate revocation lists
(@code{crl}s), as well as a @ref{9b4,,get_ca_certs()} method that
returns a list of the loaded @code{CA} certificates.  (Contributed by Christian
Heimes in bpo-18147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18147}.)

If OpenSSL 0.9.8 or later is available, @ref{4f2,,SSLContext} has a new
attribute @ref{9b5,,verify_flags} that can be used to control the
certificate verification process by setting it to some combination of the new
constants @ref{9b6,,VERIFY_DEFAULT}, @ref{9b7,,VERIFY_CRL_CHECK_LEAF},
@ref{9b8,,VERIFY_CRL_CHECK_CHAIN}, or @ref{9b9,,VERIFY_X509_STRICT}.
OpenSSL does not do any CRL verification by default.  (Contributed by
Christien Heimes in bpo-8813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8813}.)

New @ref{4f2,,SSLContext} method @ref{9ba,,load_default_certs()}
loads a set of default "certificate authority" (CA) certificates from default
locations, which vary according to the platform.  It can be used to load both
TLS web server authentication certificates
(@code{purpose=}@ref{9bb,,SERVER_AUTH}) for a client to use to verify a
server, and certificates for a server to use in verifying client certificates
(@code{purpose=}@ref{9bc,,CLIENT_AUTH}).  (Contributed by Christian
Heimes in bpo-19292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19292}.)
@anchor{whatsnew/3 4 whatsnew34-win-cert-store}@anchor{8df}
Two new windows-only functions, @ref{9bd,,enum_certificates()} and
@ref{9be,,enum_crls()} provide the ability to retrieve certificates,
certificate information, and CRLs from the Windows cert store.  (Contributed
by Christian Heimes in bpo-17134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17134}.)
@anchor{whatsnew/3 4 whatsnew34-sni}@anchor{8e0}
Support for server-side SNI (Server Name Indication) using the new
@ref{9bf,,ssl.SSLContext.set_servername_callback()} method.
(Contributed by Daniel Black in bpo-8109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8109}.)

The dictionary returned by @ref{9c0,,SSLSocket.getpeercert()} contains additional
@code{X509v3} extension items: @code{crlDistributionPoints}, @code{calIssuers}, and
@code{OCSP} URIs.  (Contributed by Christian Heimes in bpo-18379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18379}.)

@node stat,struct<2>,ssl<7>,改进的模块<6>
@anchor{whatsnew/3 4 stat}@anchor{9c1}
@subsubsection stat


The @ref{f4,,stat} module is now backed by a C implementation in @code{_stat}. A C
implementation is required as most of the values aren't standardized and
are platform-dependent.  (Contributed by Christian Heimes in bpo-11016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11016}.)

The module supports new @ref{9c2,,ST_MODE} flags, @ref{9c3,,S_IFDOOR},
@ref{9c4,,S_IFPORT}, and @ref{9c5,,S_IFWHT}.  (Contributed by
Christian Hiemes in bpo-11016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11016}.)

@node struct<2>,subprocess<4>,stat,改进的模块<6>
@anchor{whatsnew/3 4 struct}@anchor{9c6}
@subsubsection struct


New function @ref{9c7,,iter_unpack} and a new
@ref{9c8,,struct.Struct.iter_unpack()} method on compiled formats provide streamed
unpacking of a buffer containing repeated instances of a given format of data.
(Contributed by Antoine Pitrou in bpo-17804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17804}.)

@node subprocess<4>,sunau<2>,struct<2>,改进的模块<6>
@anchor{whatsnew/3 4 subprocess}@anchor{9c9}
@subsubsection subprocess


@ref{9ca,,check_output()} now accepts an @emph{input} argument that can
be used to provide the contents of @code{stdin} for the command that is run.
(Contributed by Zack Weinberg in bpo-16624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16624}.)

@code{getstatus()} and @ref{9cb,,getstatusoutput()} now
work on Windows.  This change was actually inadvertently made in 3.3.4.
(Contributed by Tim Golden in bpo-10197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10197}.)

@node sunau<2>,sys<7>,subprocess<4>,改进的模块<6>
@anchor{whatsnew/3 4 sunau}@anchor{9cc}
@subsubsection sunau


The @code{getparams()} method now returns a namedtuple rather than a
plain tuple.  (Contributed by Claudiu Popa in bpo-18901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18901}.)

@ref{57b,,sunau.open()} now supports the context management protocol: when used in a
@ref{7e4,,with} block, the @code{close} method of the returned object will be
called automatically at the end of the block.  (Contributed by Serhiy Storchaka
in bpo-18878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18878}.)

@ref{9cd,,AU_write.setsampwidth()} now supports 24 bit samples, thus adding
support for writing 24 sample using the module.  (Contributed by
Serhiy Storchaka in bpo-19261@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19261}.)

The @ref{9ce,,writeframesraw()} and
@ref{9cf,,writeframes()} methods now accept any @ref{6e9,,bytes-like object}.  (Contributed by Serhiy Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node sys<7>,tarfile<4>,sunau<2>,改进的模块<6>
@anchor{whatsnew/3 4 sys}@anchor{9d0}
@subsubsection sys


New function @ref{9d1,,sys.getallocatedblocks()} returns the current number of
blocks allocated by the interpreter.  (In CPython with the default
@code{--with-pymalloc} setting, this is allocations made through the
@ref{609,,PyObject_Malloc()} API.)  This can be useful for tracking memory leaks,
especially if automated via a test suite.  (Contributed by Antoine Pitrou
in bpo-13390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13390}.)

When the Python interpreter starts in @ref{9d2,,interactive mode}, it checks for an @ref{9d3,,__interactivehook__} attribute
on the @ref{fd,,sys} module.  If the attribute exists, its value is called with no
arguments just before interactive mode is started.  The check is made after the
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} file is read, so it can be set there.  The @ref{eb,,site}
module @ref{9d5,,sets it} to a function that enables tab
completion and history saving (in @code{~/.python-history}) if the platform
supports @ref{de,,readline}.  If you do not want this (new) behavior, you can
override it in 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP}, @code{sitecustomize}, or
@code{usercustomize} by deleting this attribute from @ref{fd,,sys} (or setting it
to some other callable).  (Contributed by Éric Araujo and Antoine Pitrou in
bpo-5845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5845}.)

@node tarfile<4>,textwrap,sys<7>,改进的模块<6>
@anchor{whatsnew/3 4 tarfile}@anchor{9d6}
@subsubsection tarfile


The @ref{101,,tarfile} module now supports a simple @ref{9d7,,命令行界面} when
called as a script directly or via @code{-m}.  This can be used to create and
extract tarfile archives.  (Contributed by Berker Peksag in bpo-13477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13477}.)

@node textwrap,threading<4>,tarfile<4>,改进的模块<6>
@anchor{whatsnew/3 4 textwrap}@anchor{9d8}
@subsubsection textwrap


The @ref{9d9,,TextWrapper} class has two new attributes/constructor
arguments: @ref{9da,,max_lines}, which limits the number of
lines in the output, and @ref{9db,,placeholder}, which is a
string that will appear at the end of the output if it has been truncated
because of @emph{max_lines}.  Building on these capabilities, a new convenience
function @ref{9dc,,shorten()} collapses all of the whitespace in the input
to single spaces and produces a single line of a given @emph{width} that ends with
the @emph{placeholder} (by default, @code{[...]}).  (Contributed by Antoine Pitrou and
Serhiy Storchaka in bpo-18585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18585} and bpo-18725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18725}.)

@node threading<4>,traceback<3>,textwrap,改进的模块<6>
@anchor{whatsnew/3 4 threading}@anchor{9dd}
@subsubsection threading


The @ref{21b,,Thread} object representing the main thread can be
obtained from the new @ref{9de,,main_thread()} function.  In normal
conditions this will be the thread from which the Python interpreter was
started.  (Contributed by Andrew Svetlov in bpo-18882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18882}.)

@node traceback<3>,types<3>,threading<4>,改进的模块<6>
@anchor{whatsnew/3 4 traceback}@anchor{9df}
@subsubsection traceback


A new @ref{9e0,,traceback.clear_frames()} function takes a traceback object
and clears the local variables in all of the frames it references,
reducing the amount of memory consumed.  (Contributed by Andrew Kuchling in
bpo-1565525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1565525}.)

@node types<3>,urllib<2>,traceback<3>,改进的模块<6>
@anchor{whatsnew/3 4 types}@anchor{9e1}
@subsubsection types


A new @ref{9e2,,DynamicClassAttribute()} descriptor provides a way to define
an attribute that acts normally when looked up through an instance object, but
which is routed to the @emph{class} @code{__getattr__} when looked up through the
class.  This allows one to have properties active on a class, and have virtual
attributes on the class with the same name (see @code{Enum} for an example).
(Contributed by Ethan Furman in bpo-19030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19030}.)

@node urllib<2>,unittest<4>,types<3>,改进的模块<6>
@anchor{whatsnew/3 4 urllib}@anchor{9e3}
@subsubsection urllib


@ref{129,,urllib.request} now supports @code{data:} URLs via the
@ref{9e4,,DataHandler} class.  (Contributed by Mathias Panzenböck
in bpo-16423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16423}.)

The http method that will be used by a @ref{9e5,,Request} class
can now be specified by setting a @ref{9e6,,method}
class attribute on the subclass.  (Contributed by Jason R Coombs in
bpo-18978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18978}.)

@ref{9e5,,Request} objects are now reusable: if the
@ref{9e7,,full_url} or @ref{9e8,,data}
attributes are modified, all relevant internal properties are updated.  This
means, for example, that it is now possible to use the same
@ref{9e5,,Request} object in more than one
@ref{9e9,,OpenerDirector.open()} call with different @emph{data} arguments, or to
modify a @ref{9e5,,Request}'s @code{url} rather than recomputing it
from scratch.  There is also a new
@ref{9ea,,remove_header()} method that can be used to remove
headers from a @ref{9e5,,Request}.  (Contributed by Alexey
Kachayev in bpo-16464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16464}, Daniel Wozniak in bpo-17485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17485}, and Damien Brecht
and Senthil Kumaran in bpo-17272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17272}.)

@ref{9eb,,HTTPError} objects now have a
@ref{9ec,,headers} attribute that provides access to the
HTTP response headers associated with the error.  (Contributed by
Berker Peksag in bpo-15701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15701}.)

@node unittest<4>,venv<5>,urllib<2>,改进的模块<6>
@anchor{whatsnew/3 4 unittest}@anchor{9ed}
@subsubsection unittest


The @ref{9ee,,TestCase} class has a new method,
@ref{9ef,,subTest()}, that produces a context manager whose
@ref{7e4,,with} block becomes a "sub-test".  This context manager allows a test
method to dynamically generate subtests  by, say, calling the @code{subTest}
context manager inside a loop.  A single test method can thereby produce an
indefinite number of separately-identified and separately-counted tests, all of
which will run even if one or more of them fail.  For example:

@example
class NumbersTest(unittest.TestCase):
    def test_even(self):
        for i in range(6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
@end example

will result in six subtests, each identified in the unittest verbose output
with a label consisting of the variable name @code{i} and a particular value for
that variable (@code{i=0}, @code{i=1}, etc).  See @ref{9f0,,使用子测试区分测试迭代} for the full
version of this example.  (Contributed by Antoine Pitrou in bpo-16997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16997}.)

@ref{9f1,,unittest.main()} now accepts an iterable of test names for
@emph{defaultTest}, where previously it only accepted a single test name as a
string.  (Contributed by Jyrki Pulliainen in bpo-15132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15132}.)

If @ref{9f2,,SkipTest} is raised during test discovery (that is, at the
module level in the test file), it is now reported as a skip instead of an
error.  (Contributed by Zach Ware in bpo-16935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16935}.)

@ref{9f3,,discover()} now sorts the discovered files to provide
consistent test ordering.  (Contributed by Martin Melin and Jeff Ramnani in
bpo-16709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16709}.)

@ref{7cb,,TestSuite} now drops references to tests as soon as the test
has been run, if the test is successful.  On Python interpreters that do
garbage collection, this allows the tests to be garbage collected if nothing
else is holding a reference to the test.  It is possible to override this
behavior by creating a @ref{7cb,,TestSuite} subclass that defines a
custom @code{_removeTestAtIndex} method.  (Contributed by Tom Wardill, Matt
McClure, and Andrew Svetlov in bpo-11798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11798}.)

A new test assertion context-manager, @ref{9f4,,assertLogs()},
will ensure that a given block of code emits a log message using the
@ref{aa,,logging} module.  By default the message can come from any logger and
have a priority of @code{INFO} or higher, but both the logger name and an
alternative minimum logging level may be specified.  The object returned by the
context manager can be queried for the @ref{9f5,,LogRecord}s and/or
formatted messages that were logged.  (Contributed by Antoine Pitrou in
bpo-18937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18937}.)

Test discovery now works with namespace packages (Contributed by Claudiu Popa
in bpo-17457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17457}.)

@ref{125,,unittest.mock} objects now inspect their specification signatures when
matching calls, which means an argument can now be matched by either position
or name, instead of only by position.  (Contributed by Antoine Pitrou in
bpo-17015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17015}.)

@code{mock_open()} objects now have @code{readline} and @code{readlines}
methods.  (Contributed by Toshio Kuratomi in bpo-17467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17467}.)

@node venv<5>,wave<2>,unittest<4>,改进的模块<6>
@anchor{whatsnew/3 4 venv}@anchor{9f6}
@subsubsection venv


@ref{12e,,venv} now includes activation scripts for the @code{csh} and @code{fish}
shells.  (Contributed by Andrew Svetlov in bpo-15417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15417}.)

@ref{9f7,,EnvBuilder} and the @ref{9f8,,create()} convenience function
take a new keyword argument @emph{with_pip}, which defaults to @code{False}, that
controls whether or not @ref{9f7,,EnvBuilder} ensures that @code{pip} is
installed in the virtual environment.  (Contributed by Nick Coghlan in
bpo-19552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19552} as part of the 
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} implementation.)

@node wave<2>,weakref<2>,venv<5>,改进的模块<6>
@anchor{whatsnew/3 4 wave}@anchor{9f9}
@subsubsection wave


The @code{getparams()} method now returns a namedtuple rather than a
plain tuple.  (Contributed by Claudiu Popa in bpo-17487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17487}.)

@ref{21a,,wave.open()} now supports the context management protocol.  (Contributed
by Claudiu Popa in bpo-17616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17616}.)

@ref{130,,wave} can now @ref{9fa,,write output to unseekable files}.  (Contributed by David Jones, Guilherme Polo, and Serhiy
Storchaka in bpo-5202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5202}.)

The @ref{9fb,,writeframesraw()} and
@ref{9fc,,writeframes()} methods now accept any @ref{6e9,,bytes-like object}.  (Contributed by Serhiy Storchaka in bpo-8311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8311}.)

@node weakref<2>,xml etree<2>,wave<2>,改进的模块<6>
@anchor{whatsnew/3 4 weakref}@anchor{9fd}
@subsubsection weakref


New @ref{9fe,,WeakMethod} class simulates weak references to bound
methods.  (Contributed by Antoine Pitrou in bpo-14631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14631}.)

New @ref{3c8,,finalize} class makes it possible to register a callback
to be invoked when an object is garbage collected, without needing to
carefully manage the lifecycle of the weak reference itself.  (Contributed by
Richard Oudkerk in bpo-15528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15528}.)

The callback, if any, associated with a @ref{9ff,,ref} is now
exposed via the @ref{a00,,__callback__} attribute.  (Contributed
by Mark Dickinson in bpo-17643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17643}.)

@node xml etree<2>,zipfile<4>,weakref<2>,改进的模块<6>
@anchor{whatsnew/3 4 xml-etree}@anchor{a01}
@subsubsection xml.etree


A new parser, @ref{a02,,XMLPullParser}, allows a
non-blocking applications to parse XML documents.  An example can be
seen at @ref{a03,,用于非阻塞解析的拉取 API}.  (Contributed by Antoine
Pitrou in bpo-17741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17741}.)

The @ref{140,,xml.etree.ElementTree} @ref{a04,,tostring()} and
@ref{a05,,tostringlist()} functions, and the
@ref{21d,,ElementTree}
@ref{a06,,write()} method, now have a
@emph{short_empty_elements} @ref{3d6,,keyword-only parameter}
providing control over whether elements with no content are written in
abbreviated (@code{<tag />}) or expanded (@code{<tag></tag>}) form.  (Contributed by
Ariel Poliak and Serhiy Storchaka in bpo-14377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14377}.)

@node zipfile<4>,,xml etree<2>,改进的模块<6>
@anchor{whatsnew/3 4 zipfile}@anchor{a07}
@subsubsection zipfile


The @ref{a08,,writepy()} method of the
@ref{a09,,PyZipFile} class has a new @emph{filterfunc} option that can be
used to control which directories and files are added to the archive.  For
example, this could be used to exclude test files from the archive.
(Contributed by Christian Tismer in bpo-19274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19274}.)

The @emph{allowZip64} parameter to @ref{52b,,ZipFile} and
@code{PyZipfile} is now @code{True} by default.  (Contributed by
William Mallard in bpo-17201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17201}.)

@node CPython Implementation Changes,弃用<5>,改进的模块<6>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 cpython-implementation-changes}@anchor{a0a}
@subsection CPython Implementation Changes


@menu
* PEP 445; Customization of CPython Memory Allocators: PEP 445 Customization of CPython Memory Allocators. 
* PEP 442; Safe Object Finalization: PEP 442 Safe Object Finalization. 
* PEP 456; Secure and Interchangeable Hash Algorithm: PEP 456 Secure and Interchangeable Hash Algorithm. 
* PEP 436; Argument Clinic: PEP 436 Argument Clinic. 
* Other Build and C API Changes:: 
* 其他改进: 其他改进<2>. 
* Significant Optimizations:: 

@end menu

@node PEP 445 Customization of CPython Memory Allocators,PEP 442 Safe Object Finalization,,CPython Implementation Changes
@anchor{whatsnew/3 4 pep-445-customization-of-cpython-memory-allocators}@anchor{a0b}@anchor{whatsnew/3 4 whatsnew-pep-445}@anchor{8e4}
@subsubsection PEP 445: Customization of CPython Memory Allocators


@geindex Python 提高建议; PEP 445
PEP 445@footnote{https://www.python.org/dev/peps/pep-0445} adds new C level interfaces to customize memory allocation in
the CPython interpreter.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 445

@item PEP 445@footnote{https://www.python.org/dev/peps/pep-0445} -- Add new APIs to customize Python memory allocators

PEP 由 Victor Stinner 撰写并实现。
@end table


@node PEP 442 Safe Object Finalization,PEP 456 Secure and Interchangeable Hash Algorithm,PEP 445 Customization of CPython Memory Allocators,CPython Implementation Changes
@anchor{whatsnew/3 4 pep-442-safe-object-finalization}@anchor{a0c}@anchor{whatsnew/3 4 whatsnew-pep-442}@anchor{8e3}
@subsubsection PEP 442: Safe Object Finalization


@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442} removes the current limitations and quirks of object finalization
in CPython. With it, objects with @ref{a0d,,__del__()} methods, as well as
generators with @ref{2c3,,finally} clauses, can be finalized when they are
part of a reference cycle.

As part of this change, module globals are no longer forcibly set to
@ref{204,,None} during interpreter shutdown in most cases, instead relying
on the normal operation of the cyclic garbage collector.  This avoids a
whole class of interpreter-shutdown-time errors, usually involving
@code{__del__} methods, that have plagued Python since the cyclic GC
was first introduced.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 442

@item PEP 442@footnote{https://www.python.org/dev/peps/pep-0442} -- Safe object finalization

PEP 由 Antoine Pitrou 撰写并实现
@end table


@node PEP 456 Secure and Interchangeable Hash Algorithm,PEP 436 Argument Clinic,PEP 442 Safe Object Finalization,CPython Implementation Changes
@anchor{whatsnew/3 4 pep-456-secure-and-interchangeable-hash-algorithm}@anchor{a0e}@anchor{whatsnew/3 4 whatsnew-pep-456}@anchor{8dc}
@subsubsection PEP 456: Secure and Interchangeable Hash Algorithm


@geindex Python 提高建议; PEP 456
PEP 456@footnote{https://www.python.org/dev/peps/pep-0456} follows up on earlier security fix work done on Python's hash
algorithm to address certain DOS attacks to which public facing APIs backed by
dictionary lookups may be subject.  (See bpo-14621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14621} for the start of the
current round of improvements.)  The PEP unifies CPython's hash code to make it
easier for a packager to substitute a different hash algorithm, and switches
Python's default implementation to a SipHash implementation on platforms that
have a 64 bit data type.  Any performance differences in comparison with the
older FNV algorithm are trivial.

The PEP adds additional fields to the @ref{a0f,,sys.hash_info} named tuple to
describe the hash algorithm in use by the currently executing binary.  Otherwise,
the PEP does not alter any existing CPython APIs.

@node PEP 436 Argument Clinic,Other Build and C API Changes,PEP 456 Secure and Interchangeable Hash Algorithm,CPython Implementation Changes
@anchor{whatsnew/3 4 pep-436-argument-clinic}@anchor{a10}@anchor{whatsnew/3 4 whatsnew-pep-436}@anchor{8e5}
@subsubsection PEP 436: Argument Clinic


"Argument Clinic" (
@geindex Python 提高建议; PEP 436
PEP 436@footnote{https://www.python.org/dev/peps/pep-0436}) is now part of the CPython build process
and can be used to simplify the process of defining and maintaining
accurate signatures for builtins and standard library extension modules
implemented in C.

Some standard library extension modules have been converted to use Argument
Clinic in Python 3.4, and @ref{d9,,pydoc} and @ref{a0,,inspect} have been updated
accordingly.

It is expected that signature metadata for programmatic introspection will
be added to additional callables implemented in C as part of Python 3.4
maintenance releases.

@cartouche
@quotation 注解 
The Argument Clinic PEP is not fully up to date with the state of the
implementation. This has been deemed acceptable by the release manager
and core development team in this case, as Argument Clinic will not
be made available as a public API for third party use in Python 3.4.
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 436

@item PEP 436@footnote{https://www.python.org/dev/peps/pep-0436} -- The Argument Clinic DSL

PEP 由 Larry Hastings 撰写并实现
@end table


@node Other Build and C API Changes,其他改进<2>,PEP 436 Argument Clinic,CPython Implementation Changes
@anchor{whatsnew/3 4 other-build-and-c-api-changes}@anchor{a11}
@subsubsection Other Build and C API Changes



@itemize *

@item 
The new @ref{a12,,PyType_GetSlot()} function has been added to the stable ABI,
allowing retrieval of function pointers from named type slots when using
the limited API.  (Contributed by Martin von Löwis in bpo-17162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17162}.)

@item 
The new @ref{a13,,Py_SetStandardStreamEncoding()} pre-initialization API
allows applications embedding the CPython interpreter to reliably force
a particular encoding and error handler for the standard streams.
(Contributed by Bastien Montagne and Nick Coghlan in bpo-16129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16129}.)

@item 
Most Python C APIs that don't mutate string arguments are now correctly
marked as accepting @code{const char *} rather than @code{char *}.  (Contributed
by Serhiy Storchaka in bpo-1772673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1772673}.)

@item 
A new shell version of @code{python-config} can be used even when a python
interpreter is not available (for example, in cross compilation scenarios).

@item 
@ref{8c2,,PyUnicode_FromFormat()} now supports width and precision
specifications for @code{%s}, @code{%A}, @code{%U}, @code{%V}, @code{%S}, and @code{%R}.
(Contributed by Ysj Ray and Victor Stinner in bpo-7330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7330}.)

@item 
New function @ref{a14,,PyStructSequence_InitType2()} supplements the
existing @ref{a15,,PyStructSequence_InitType()} function.  The difference
is that it returns @code{0} on success and @code{-1} on failure.

@item 
The CPython source can now be compiled using the address sanity checking
features of recent versions of GCC and clang:  the false alarms in the small
object allocator have been silenced.  (Contributed by Dhiru Kholia in
bpo-18596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18596}.)

@item 
The Windows build now uses Address Space Layout Randomization@footnote{https://en.wikipedia.org/wiki/Address_space_layout_randomization} and Data Execution Prevention@footnote{https://en.wikipedia.org/wiki/Data_Execution_Prevention}.  (Contributed by
Christian Heimes in bpo-16632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16632}.)

@item 
New function @ref{a16,,PyObject_LengthHint()} is the C API equivalent
of @ref{971,,operator.length_hint()}.  (Contributed by Armin Ronacher in
bpo-16148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16148}.)
@end itemize

@node 其他改进<2>,Significant Optimizations,Other Build and C API Changes,CPython Implementation Changes
@anchor{whatsnew/3 4 other-improvements}@anchor{a17}@anchor{whatsnew/3 4 other-improvements-3-4}@anchor{a18}
@subsubsection 其他改进

@anchor{whatsnew/3 4 whatsnew-isolated-mode}@anchor{8cd}

@itemize *

@item 
The @ref{a19,,python} command has a new @ref{a1a,,option}, @code{-I}, which causes it to run in "isolated mode",
which means that @ref{262,,sys.path} contains neither the script's directory nor
the user's @code{site-packages} directory, and all 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} environment
variables are ignored (it implies both @code{-s} and @code{-E}).  Other
restrictions may also be applied in the future, with the goal being to
isolate the execution of a script from the user's environment.  This is
appropriate, for example, when Python is used to run a system script.  On
most POSIX systems it can and should be used in the @code{#!} line of system
scripts.  (Contributed by Christian Heimes in bpo-16499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16499}.)

@item 
Tab-completion is now enabled by default in the interactive interpreter
on systems that support @ref{de,,readline}.  History is also enabled by default,
and is written to (and read from) the file @code{~/.python-history}.
(Contributed by Antoine Pitrou and Éric Araujo in bpo-5845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5845}.)

@item 
Invoking the Python interpreter with @code{--version} now outputs the version to
standard output instead of standard error (bpo-18338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18338}). Similar changes
were made to @ref{5,,argparse} (bpo-18920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18920}) and other modules that have
script-like invocation capabilities (bpo-18922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18922}).

@item 
The CPython Windows installer now adds @code{.py} to the 
@geindex PATHEXT
@geindex 环境变量; PATHEXT
@code{PATHEXT}
variable when extensions are registered, allowing users to run a python
script at the windows command prompt by just typing its name without the
@code{.py} extension.  (Contributed by Paul Moore in bpo-18569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18569}.)

@item 
A new @code{make} target coverage-report@footnote{https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov}
will build python, run the test suite, and generate an HTML coverage report
for the C codebase using @code{gcov} and lcov@footnote{http://ltp.sourceforge.net/coverage/lcov.php}.

@item 
The @code{-R} option to the @ref{a1b,,python regression test suite} now
also checks for memory allocation leaks, using
@ref{9d1,,sys.getallocatedblocks()}.  (Contributed by Antoine Pitrou in
bpo-13390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13390}.)

@item 
@code{python -m} now works with namespace packages.

@item 
The @ref{f4,,stat} module is now implemented in C, which means it gets the
values for its constants from the C header files, instead of having the
values hard-coded in the python module as was previously the case.

@item 
Loading multiple python modules from a single OS module (@code{.so}, @code{.dll})
now works correctly (previously it silently returned the first python
module in the file).  (Contributed by Václav Šmilauer in bpo-16421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16421}.)

@item 
A new opcode, @ref{a1c,,LOAD_CLASSDEREF}, has been added to fix a bug in the
loading of free variables in class bodies that could be triggered by certain
uses of @ref{5ff,,__prepare__}.  (Contributed by Benjamin Peterson in
bpo-17853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17853}.)

@item 
A number of MemoryError-related crashes were identified and fixed by Victor
Stinner using his 
@geindex Python 提高建议; PEP 445
PEP 445@footnote{https://www.python.org/dev/peps/pep-0445}-based @code{pyfailmalloc} tool (bpo-18408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18408},
bpo-18520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18520}).

@item 
The @code{pyvenv} command now accepts a @code{--copies} option
to use copies rather than symlinks even on systems where symlinks are the
default.  (Contributed by Vinay Sajip in bpo-18807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18807}.)

@item 
The @code{pyvenv} command also accepts a @code{--without-pip}
option to suppress the otherwise-automatic bootstrapping of pip into
the virtual environment.  (Contributed by Nick Coghlan in bpo-19552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19552}
as part of the 
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} implementation.)

@item 
The encoding name is now optional in the value set for the
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} environment variable.  This makes it possible to
set just the error handler, without changing the default encoding.
(Contributed by Serhiy Storchaka in bpo-18818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18818}.)

@item 
The @ref{13,,bz2}, @ref{ad,,lzma}, and @ref{8b,,gzip} module @code{open} functions now
support @code{x} (exclusive creation) mode.  (Contributed by Tim Heaney and
Vajrasky Kok in bpo-19201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19201}, bpo-19222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19222}, and bpo-19223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19223}.)
@end itemize

@node Significant Optimizations,,其他改进<2>,CPython Implementation Changes
@anchor{whatsnew/3 4 significant-optimizations}@anchor{a1e}
@subsubsection Significant Optimizations



@itemize *

@item 
The UTF-32 decoder is now 3x to 4x faster.  (Contributed by Serhiy Storchaka
in bpo-14625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14625}.)

@item 
The cost of hash collisions for sets is now reduced.  Each hash table
probe now checks a series of consecutive, adjacent key/hash pairs before
continuing to make random probes through the hash table.  This exploits
cache locality to make collision resolution less expensive.
The collision resolution scheme can be described as a hybrid of linear
probing and open addressing.  The number of additional linear probes
defaults to nine.  This can be changed at compile-time by defining
LINEAR_PROBES to be any value.  Set LINEAR_PROBES=0 to turn-off
linear probing entirely.  (Contributed by Raymond Hettinger in
bpo-18771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18771}.)

@item 
The interpreter starts about 30% faster. A couple of measures lead to the
speedup. The interpreter loads fewer modules on startup, e.g. the @ref{dd,,re},
@ref{1d,,collections} and @ref{a9,,locale} modules and their dependencies are no
longer imported by default. The marshal module has been improved to load
compiled Python code faster.  (Contributed by Antoine Pitrou, Christian
Heimes and Victor Stinner in bpo-19219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19219}, bpo-19218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19218}, bpo-19209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19209},
bpo-19205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19205} and bpo-9548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9548}.)

@item 
@ref{225,,bz2.BZ2File} is now as fast or faster than the Python2 version for
most cases.  @ref{a1f,,lzma.LZMAFile} has also been optimized.  (Contributed by
Serhiy Storchaka and Nadeem Vawda in bpo-16034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16034}.)

@item 
@ref{a20,,random.getrandbits()} is 20%-40% faster for small integers (the most
common use case).  (Contributed by Serhiy Storchaka in bpo-16674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16674}.)

@item 
By taking advantage of the new storage format for strings, pickling of
strings is now significantly faster.  (Contributed by Victor Stinner and
Antoine Pitrou in bpo-15596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15596}.)

@item 
A performance issue in @code{io.FileIO.readall()} has been solved.  This
particularly affects Windows, and significantly speeds up the case of piping
significant amounts of data through @ref{f9,,subprocess}.  (Contributed
by Richard Oudkerk in bpo-15758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15758}.)

@item 
@ref{a21,,html.escape()} is now 10x faster.  (Contributed by Matt Bryant in
bpo-18020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18020}.)

@item 
On Windows, the native @code{VirtualAlloc} is now used instead of the CRT
@code{malloc} in @code{obmalloc}.  Artificial benchmarks show about a 3% memory
savings.

@item 
@ref{5d4,,os.urandom()} now uses a lazily-opened persistent file descriptor
so as to avoid using many file descriptors when run in parallel from
multiple threads.  (Contributed by Antoine Pitrou in bpo-18756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18756}.)
@end itemize

@node 弃用<5>,移除<5>,CPython Implementation Changes,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 deprecated}@anchor{a22}@anchor{whatsnew/3 4 deprecated-3-4}@anchor{8fe}
@subsection 弃用


This section covers various APIs and other features that have been deprecated
in Python 3.4, and will be removed in Python 3.5 or later.  In most (but not
all) cases, using the deprecated APIs will produce a @ref{15a,,DeprecationWarning}
when the interpreter is run with deprecation warnings enabled (for example, by
using @code{-Wd}).

@menu
* Deprecations in the Python API:: 
* Deprecated Features:: 

@end menu

@node Deprecations in the Python API,Deprecated Features,,弃用<5>
@anchor{whatsnew/3 4 deprecations-in-the-python-api}@anchor{a23}
@subsubsection Deprecations in the Python API



@itemize *

@item 
As mentioned in @ref{8cf,,PEP 451; A ModuleSpec Type for the Import System}, a number of @ref{9a,,importlib}
methods and functions are deprecated: @ref{a24,,importlib.find_loader()} is
replaced by @ref{a25,,importlib.util.find_spec()};
@ref{a26,,importlib.machinery.PathFinder.find_module()} is replaced by
@ref{a27,,importlib.machinery.PathFinder.find_spec()};
@ref{56c,,importlib.abc.MetaPathFinder.find_module()} is replaced by
@ref{56d,,importlib.abc.MetaPathFinder.find_spec()};
@ref{56e,,importlib.abc.PathEntryFinder.find_loader()} and
@ref{a28,,find_module()} are replaced by
@ref{56f,,importlib.abc.PathEntryFinder.find_spec()}; all of the @code{xxxLoader} ABC
@code{load_module} methods (@ref{6e4,,importlib.abc.Loader.load_module()},
@ref{a29,,importlib.abc.InspectLoader.load_module()},
@ref{a2a,,importlib.abc.FileLoader.load_module()},
@ref{a2b,,importlib.abc.SourceLoader.load_module()}) should no longer be
implemented, instead loaders should implement an
@code{exec_module} method
(@ref{6e5,,importlib.abc.Loader.exec_module()},
@ref{a2c,,importlib.abc.InspectLoader.exec_module()}
@ref{a2d,,importlib.abc.SourceLoader.exec_module()}) and let the import system
take care of the rest; and
@ref{a2e,,importlib.abc.Loader.module_repr()},
@ref{a2f,,importlib.util.module_for_loader()}, @ref{a30,,importlib.util.set_loader()},
and @ref{a31,,importlib.util.set_package()} are no longer needed because their
functions are now handled automatically by the import system.

@item 
The @ref{99,,imp} module is pending deprecation. To keep compatibility with
Python 2/3 code bases, the module's removal is currently not scheduled.

@item 
The @ref{80,,formatter} module is pending deprecation and is slated for removal
in Python 3.6.

@item 
@code{MD5} as the default @emph{digestmod} for the @ref{3f5,,hmac.new()} function is
deprecated.  Python 3.6 will require an explicit digest name or constructor as
@emph{digestmod} argument.

@item 
The internal @code{Netrc} class in the @ref{82,,ftplib} module has been documented
as deprecated in its docstring for quite some time.  It now emits a
@ref{15a,,DeprecationWarning} and will be removed completely in Python 3.5.

@item 
The undocumented @emph{endtime} argument to @ref{693,,subprocess.Popen.wait()} should
not have been exposed and is hopefully not in use; it is deprecated and
will mostly likely be removed in Python 3.5.

@item 
The @emph{strict} argument of @ref{22b,,HTMLParser} is deprecated.

@item 
The @ref{cf,,plistlib} @code{readPlist()},
@code{writePlist()}, @code{readPlistFromBytes()}, and
@code{writePlistToBytes()} functions are deprecated in favor of the
corresponding new functions @ref{21f,,load()}, @ref{221,,dump()},
@ref{220,,loads()}, and @ref{222,,dumps()}.  @code{Data()}
is deprecated in favor of just using the @ref{172,,bytes} constructor.

@item 
The @ref{fe,,sysconfig} key @code{SO} is deprecated, it has been replaced by
@code{EXT_SUFFIX}.

@item 
The @code{U} mode accepted by various @code{open} functions is deprecated.
In Python3 it does not do anything useful, and should be replaced by
appropriate uses of @ref{6f4,,io.TextIOWrapper} (if needed) and its @emph{newline}
argument.

@item 
The @emph{parser} argument of @ref{a32,,xml.etree.ElementTree.iterparse()} has
been deprecated, as has the @emph{html} argument of
@ref{383,,XMLParser()}.  To prepare for the removal of the
latter, all arguments to @code{XMLParser} should be passed by keyword.
@end itemize

@node Deprecated Features,,Deprecations in the Python API,弃用<5>
@anchor{whatsnew/3 4 deprecated-features}@anchor{a33}
@subsubsection Deprecated Features



@itemize *

@item 
Running @ref{a34,,IDLE} with the @code{-n} flag (no subprocess) is deprecated.
However, the feature will not be removed until bpo-18823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18823} is resolved.

@item 
The site module adding a "site-python" directory to sys.path, if it
exists, is deprecated (bpo-19375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19375}).
@end itemize

@node 移除<5>,移植到 Python 3 4,弃用<5>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 removed}@anchor{a35}
@subsection 移除


@menu
* 不再支持的操作系统:: 
* API 与特性的移除: API 与特性的移除<5>. 
* Code Cleanups:: 

@end menu

@node 不再支持的操作系统,API 与特性的移除<5>,,移除<5>
@anchor{whatsnew/3 4 operating-systems-no-longer-supported}@anchor{a36}
@subsubsection 不再支持的操作系统


从源代码和构建工具中删除了对以下操作系统的支持：


@itemize *

@item 
OS/2 (bpo-16135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16135}).

@item 
Windows 2000（变更集e52df05b496a）。

@item 
Windows系统中 @code{COMSPEC} 指向 @code{command.com} 的版本（ bpo-14470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14470} ）。

@item 
VMS (bpo-16136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16136}).
@end itemize

@node API 与特性的移除<5>,Code Cleanups,不再支持的操作系统,移除<5>
@anchor{whatsnew/3 4 api-and-feature-removals}@anchor{a37}
@subsubsection API 与特性的移除


The following obsolete and previously deprecated APIs and features have been
removed:


@itemize *

@item 
The unmaintained @code{Misc/TextMate} and @code{Misc/vim} directories have been
removed (see the devguide@footnote{https://devguide.python.org}
for suggestions on what to use instead).

@item 
The @code{SO} makefile macro is removed (it was replaced by the
@code{SHLIB_SUFFIX} and @code{EXT_SUFFIX} macros) (bpo-16754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16754}).

@item 
The @code{PyThreadState.tick_counter} field has been removed; its value has
been meaningless since Python 3.2, when the "new GIL" was introduced
(bpo-19199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19199}).

@item 
@code{PyLoader} and @code{PyPycLoader} have been removed from @ref{9a,,importlib}.
(Contributed by Taras Lyapun in bpo-15641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15641}.)

@item 
The @emph{strict} argument to @ref{4a1,,HTTPConnection} and
@ref{4a2,,HTTPSConnection} has been removed.  HTTP 0.9-style
"Simple Responses" are no longer supported.

@item 
The deprecated @ref{9e5,,urllib.request.Request} getter and setter methods
@code{add_data}, @code{has_data}, @code{get_data}, @code{get_type}, @code{get_host},
@code{get_selector}, @code{set_proxy}, @code{get_origin_req_host}, and
@code{is_unverifiable} have been removed (use direct attribute access instead).

@item 
Support for loading the deprecated @code{TYPE_INT64} has been removed from
@ref{b0,,marshal}.  (Contributed by Dan Riti in bpo-15480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15480}.)

@item 
@ref{7ee,,inspect.Signature}: positional-only parameters are now required
to have a valid name.

@item 
@ref{a38,,object.__format__()} no longer accepts non-empty format strings, it now
raises a @ref{1ff,,TypeError} instead.  Using a non-empty string has been
deprecated since Python 3.2.  This change has been made to prevent a
situation where previously working (but incorrect) code would start failing
if an object gained a __format__ method, which means that your code may now
raise a @ref{1ff,,TypeError} if you are using an @code{'s'} format code with objects
that do not have a __format__ method that handles it.  See bpo-7994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7994} for
background.

@item 
@code{difflib.SequenceMatcher.isbjunk()} and
@code{difflib.SequenceMatcher.isbpopular()} were deprecated in 3.2, and have
now been removed: use @code{x in sm.bjunk} and
@code{x in sm.bpopular}, where @emph{sm} is a @ref{a39,,SequenceMatcher} object
(bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}).
@end itemize

@node Code Cleanups,,API 与特性的移除<5>,移除<5>
@anchor{whatsnew/3 4 code-cleanups}@anchor{a3a}
@subsubsection Code Cleanups



@itemize *

@item 
The unused and undocumented internal @code{Scanner} class has been removed from
the @ref{d9,,pydoc} module.

@item 
The private and effectively unused @code{_gestalt} module has been removed,
along with the private @ref{ce,,platform} functions @code{_mac_ver_lookup},
@code{_mac_ver_gstalt}, and @code{_bcd2str}, which would only have ever been called
on badly broken OSX systems (see bpo-18393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18393}).

@item 
The hardcoded copies of certain @ref{f4,,stat} constants that were included in
the @ref{101,,tarfile} module namespace have been removed.
@end itemize

@node 移植到 Python 3 4,3 4 3 的变化,移除<5>,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 porting-to-python-3-4}@anchor{a3b}
@subsection 移植到 Python 3.4


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* 'python' 命令行为的变化: 'python' 命令行为的变化<2>. 
* Python API 的变化: Python API 的变化<2>. 
* C API 的变化: C API 的变化<2>. 

@end menu

@node 'python' 命令行为的变化<2>,Python API 的变化<2>,,移植到 Python 3 4
@anchor{whatsnew/3 4 changes-in-python-command-behavior}@anchor{a3c}
@subsubsection  'python' 命令行为的变化



@itemize *

@item 
In a posix shell, setting the 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} environment variable to
an empty value is equivalent to not setting it at all.  However, setting
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} to an empty value was @emph{not} equivalent to not setting it
at all: setting 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} to an empty value was equivalent to
setting it to @code{.}, which leads to confusion when reasoning by analogy to
how 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} works.  The behavior now conforms to the posix convention
for 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}.

@item 
The [X refs, Y blocks] output of a debug (@code{--with-pydebug}) build of the
CPython interpreter is now off by default.  It can be re-enabled using the
@code{-X showrefcount} option.  (Contributed by Ezio Melotti in bpo-17323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17323}.)

@item 
The python command and most stdlib scripts (as well as @ref{5,,argparse}) now
output @code{--version} information to @code{stdout} instead of @code{stderr} (for
issue list see @ref{a18,,其他改进} above).
@end itemize

@node Python API 的变化<2>,C API 的变化<2>,'python' 命令行为的变化<2>,移植到 Python 3 4
@anchor{whatsnew/3 4 changes-in-the-python-api}@anchor{a3e}
@subsubsection Python API 的变化



@itemize *

@item 
The ABCs defined in @ref{9b,,importlib.abc} now either raise the appropriate
exception or return a default value instead of raising
@ref{70e,,NotImplementedError} blindly. This will only affect code calling
@ref{5e6,,super()} and falling through all the way to the ABCs. For compatibility,
catch both @ref{70e,,NotImplementedError} or the appropriate exception as needed.

@item 
The module type now initializes the @ref{a3f,,__package__} and @ref{a40,,__loader__}
attributes to @code{None} by default. To determine if these attributes were set
in a backwards-compatible fashion, use e.g.
@code{getattr(module, '__loader__', None) is not None}.  (bpo-17115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17115}.)

@item 
@ref{a2f,,importlib.util.module_for_loader()} now sets @code{__loader__} and
@code{__package__} unconditionally to properly support reloading. If this is not
desired then you will need to set these attributes manually. You can use
@code{importlib.util.module_to_load()} for module management.

@item 
Import now resets relevant attributes (e.g. @code{__name__}, @code{__loader__},
@code{__package__}, @code{__file__}, @code{__cached__}) unconditionally when reloading.
Note that this restores a pre-3.3 behavior in that it means a module is
re-found when re-loaded (bpo-19413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19413}).

@item 
Frozen packages no longer set @code{__path__} to a list containing the package
name, they now set it to an empty list.  The previous behavior could cause
the import system to do the wrong thing on submodule imports if there was
also a directory with the same name as the frozen package.  The correct way
to determine if a module is a package or not is to use @code{hasattr(module,
'__path__')} (bpo-18065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18065}).

@item 
Frozen modules no longer define a @code{__file__} attribute. It's semantically
incorrect for frozen modules to set the attribute as they are not loaded from
any explicit location. If you must know that a module comes from frozen code
then you can see if the module's @code{__spec__.location} is set to @code{'frozen'},
check if the loader is a subclass of
@ref{a41,,importlib.machinery.FrozenImporter},
or if Python 2 compatibility is necessary you can use @code{imp.is_frozen()}.

@item 
@ref{34a,,py_compile.compile()} now raises @ref{a42,,FileExistsError} if the file path
it would write to is a symlink or a non-regular file. This is to act as a
warning that import will overwrite those files with a regular file regardless
of what type of file path they were originally.

@item 
@ref{a43,,importlib.abc.SourceLoader.get_source()} no longer raises
@ref{16c,,ImportError} when the source code being loaded triggers a
@ref{562,,SyntaxError} or @ref{332,,UnicodeDecodeError}. As @ref{16c,,ImportError} is
meant to be raised only when source code cannot be found but it should, it was
felt to be over-reaching/overloading of that meaning when the source code is
found but improperly structured. If you were catching ImportError before and
wish to continue to ignore syntax or decoding issues, catch all three
exceptions now.

@item 
@ref{a44,,functools.update_wrapper()} and @ref{95e,,functools.wraps()} now correctly
set the @code{__wrapped__} attribute to the function being wrapped, even if
that function also had its @code{__wrapped__} attribute set. This means
@code{__wrapped__} attributes now correctly link a stack of decorated
functions rather than every @code{__wrapped__} attribute in the chain
referring to the innermost function. Introspection libraries that
assumed the previous behaviour was intentional can use
@ref{95d,,inspect.unwrap()} to access the first function in the chain that has
no @code{__wrapped__} attribute.

@item 
@ref{660,,inspect.getfullargspec()} has been reimplemented on top of
@ref{65e,,inspect.signature()} and hence handles a much wider variety of callable
objects than it did in the past. It is expected that additional builtin and
extension module callables will gain signature metadata over the course of
the Python 3.4 series. Code that assumes that
@ref{660,,inspect.getfullargspec()} will fail on non-Python callables may need
to be adjusted accordingly.

@item 
@ref{a45,,importlib.machinery.PathFinder} now passes on the current working
directory to objects in @ref{a46,,sys.path_hooks} for the empty string. This
results in @ref{5a0,,sys.path_importer_cache} never containing @code{'@w{'}}, thus
iterating through @ref{5a0,,sys.path_importer_cache} based on @ref{262,,sys.path}
will not find all keys. A module's @code{__file__} when imported in the current
working directory will also now have an absolute path, including when using
@code{-m} with the interpreter (except for @code{__main__.__file__} when a script
has been executed directly using a relative path) (Contributed by Brett
Cannon in bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416}).  is specified on the command-line)
(bpo-18416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18416}).

@item 
The removal of the @emph{strict} argument to @ref{4a1,,HTTPConnection}
and @ref{4a2,,HTTPSConnection} changes the meaning of the
remaining arguments if you are specifying them positionally rather than by
keyword.  If you've been paying attention to deprecation warnings your code
should already be specifying any additional arguments via keywords.

@item 
Strings between @code{from __future__ import ...} statements now @emph{always} raise
a @ref{562,,SyntaxError}.  Previously if there was no leading docstring, an
interstitial string would sometimes be ignored.  This brings CPython into
compliance with the language spec; Jython and PyPy already were.
(bpo-17434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17434}).

@item 
@ref{9c0,,ssl.SSLSocket.getpeercert()} and @ref{853,,ssl.SSLSocket.do_handshake()}
now raise an @ref{30b,,OSError} with @code{ENOTCONN} when the @code{SSLSocket} is not
connected, instead of the previous behavior of raising an
@ref{4aa,,AttributeError}.  In addition, @ref{9c0,,getpeercert()}
will raise a @ref{16d,,ValueError} if the handshake has not yet been done.

@item 
@ref{a47,,base64.b32decode()} now raises a @ref{a48,,binascii.Error} when the
input string contains non-b32-alphabet characters, instead of a
@ref{1ff,,TypeError}.  This particular @ref{1ff,,TypeError} was missed when the other
@ref{1ff,,TypeError}s were converted.  (Contributed by Serhiy Storchaka in
bpo-18011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18011}.)  Note: this change was also inadvertently applied in Python
3.3.3.

@item 
The @code{file} attribute is now automatically closed when
the creating @code{cgi.FieldStorage} instance is garbage collected. If you
were pulling the file object out separately from the @code{cgi.FieldStorage}
instance and not keeping the instance alive, then you should either store the
entire @code{cgi.FieldStorage} instance or read the contents of the file
before the @code{cgi.FieldStorage} instance is garbage collected.

@item 
Calling @code{read} or @code{write} on a closed SSL socket now raises an
informative @ref{16d,,ValueError} rather than the previous more mysterious
@ref{4aa,,AttributeError} (bpo-9177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9177}).

@item 
@ref{a49,,slice.indices()} no longer produces an @ref{a4a,,OverflowError} for huge
values.  As a consequence of this fix, @ref{a49,,slice.indices()} now raises a
@ref{16d,,ValueError} if given a negative length; previously it returned nonsense
values (bpo-14794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14794}).

@item 
The @ref{2c8,,complex} constructor, unlike the @ref{18,,cmath} functions, was
incorrectly accepting @ref{1fe,,float} values if an object's @code{__complex__}
special method returned one.  This now raises a @ref{1ff,,TypeError}.
(bpo-16290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16290}.)

@item 
The @ref{205,,int} constructor in 3.2 and 3.3 erroneously accepts @ref{1fe,,float}
values for the @emph{base} parameter.  It is unlikely anyone was doing this, but
if so, it will now raise a @ref{1ff,,TypeError} (bpo-16772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16772}).

@item 
Defaults for keyword-only arguments are now evaluated @emph{after} defaults for
regular keyword arguments, instead of before.  Hopefully no one wrote any
code that depends on the previous buggy behavior (bpo-16967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16967}).

@item 
Stale thread states are now cleared after @ref{a4b,,fork()}.  This may cause
some system resources to be released that previously were incorrectly kept
perpetually alive (for example, database connections kept in thread-local
storage).  (bpo-17094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17094}.)

@item 
Parameter names in @code{__annotations__} dicts are now mangled properly,
similarly to @code{__kwdefaults__}.  (Contributed by Yury Selivanov in
bpo-20625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20625}.)

@item 
@ref{948,,hashlib.hash.name} now always returns the identifier in lower case.
Previously some builtin hashes had uppercase names, but now that it is a
formal public interface the naming has been made consistent (bpo-18532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18532}).

@item 
Because @ref{7cb,,unittest.TestSuite} now drops references to tests after they
are run, test harnesses that re-use a @ref{7cb,,TestSuite} to re-run
a set of tests may fail.   Test suites should not be re-used in this fashion
since it means state is retained between test runs, breaking the test
isolation that @ref{124,,unittest} is designed to provide.  However, if the lack
of isolation is considered acceptable, the old behavior can be restored by
creating a @ref{7cb,,TestSuite} subclass that defines a
@code{_removeTestAtIndex} method that does nothing (see
@ref{a4c,,TestSuite.__iter__()}) (bpo-11798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11798}).

@item 
@ref{124,,unittest} now uses @ref{5,,argparse} for command line parsing.  There are
certain invalid command forms that used to work that are no longer allowed;
in theory this should not cause backward compatibility issues since the
disallowed command forms didn't make any sense and are unlikely to be in use.

@item 
The @ref{4d9,,re.split()}, @ref{a4d,,re.findall()}, and @ref{582,,re.sub()} functions, and
the @code{group()} and @code{groups()} methods of
@code{match} objects now always return a @emph{bytes} object when the string
to be matched is a @ref{6e9,,bytes-like object}.  Previously the return type
matched the input type, so if your code was depending on the return value
being, say, a @code{bytearray}, you will need to change your code.

@item 
@ref{c,,audioop} functions now raise an error immediately if passed string
input, instead of failing randomly later on (bpo-16685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16685}).

@item 
The new @emph{convert_charrefs} argument to @ref{22b,,HTMLParser}
currently defaults to @code{False} for backward compatibility, but will
eventually be changed to default to @code{True}.  It is recommended that you add
this keyword, with the appropriate value, to any
@ref{22b,,HTMLParser} calls in your code (bpo-13633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13633}).

@item 
Since the @emph{digestmod} argument to the @ref{3f5,,hmac.new()} function will in the
future have no default, all calls to @ref{3f5,,hmac.new()} should be changed to
explicitly specify a @emph{digestmod} (bpo-17276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17276}).

@item 
Calling @ref{a4e,,sysconfig.get_config_var()} with the @code{SO} key, or looking
@code{SO} up in the results of a call to @ref{a4f,,sysconfig.get_config_vars()}
is deprecated.  This key should be replaced by @code{EXT_SUFFIX} or
@code{SHLIB_SUFFIX}, depending on the context (bpo-19555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19555}).

@item 
Any calls to @code{open} functions that specify @code{U} should be modified.
@code{U} is ineffective in Python3 and will eventually raise an error if used.
Depending on the function, the equivalent of its old Python2 behavior can be
achieved using either a @emph{newline} argument, or if necessary by wrapping the
stream in @ref{6f4,,TextIOWrapper} to use its @emph{newline} argument
(bpo-15204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15204}).

@item 
If you use @code{pyvenv} in a script and desire that pip
@emph{not} be installed, you must add @code{--without-pip} to your command
invocation.

@item 
The default behavior of @ref{705,,json.dump()} and @ref{706,,json.dumps()} when
an indent is specified has changed: it no longer produces trailing
spaces after the item separating commas at the ends of lines.  This
will matter only if you have tests that are doing white-space-sensitive
comparisons of such output (bpo-16333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16333}).

@item 
@ref{66,,doctest} now looks for doctests in extension module @code{__doc__}
strings, so if your doctest test discovery includes extension modules that
have things that look like doctests in them you may see test failures you've
never seen before when running your tests (bpo-3158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3158}).

@item 
The @ref{1e,,collections.abc} module has been slightly refactored as
part of the Python startup improvements.  As a consequence of this, it is no
longer the case that importing @ref{1d,,collections} automatically imports
@ref{1e,,collections.abc}.  If your program depended on the (undocumented)
implicit import, you will need to add an explicit @code{import collections.abc}
(bpo-20784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20784}).
@end itemize

@node C API 的变化<2>,,Python API 的变化<2>,移植到 Python 3 4
@anchor{whatsnew/3 4 changes-in-the-c-api}@anchor{a50}
@subsubsection C API 的变化



@itemize *

@item 
@ref{a51,,PyEval_EvalFrameEx()}, @ref{a52,,PyObject_Repr()}, and
@ref{a53,,PyObject_Str()}, along with some other internal C APIs, now include
a debugging assertion that ensures they are not used in situations where
they may silently discard a currently active exception. In cases where
discarding the active exception is expected and desired (for example,
because it has already been saved locally with @ref{a54,,PyErr_Fetch()} or
is being deliberately replaced with a different exception), an explicit
@ref{a55,,PyErr_Clear()} call will be needed to avoid triggering the
assertion when invoking these operations (directly or indirectly) and
running against a version of Python that is compiled with assertions
enabled.

@item 
@ref{6f9,,PyErr_SetImportError()} now sets @ref{1ff,,TypeError} when its @strong{msg}
argument is not set. Previously only @code{NULL} was returned with no exception
set.

@item 
The result of the @ref{a56,,PyOS_ReadlineFunctionPointer} callback must
now be a string allocated by @ref{a57,,PyMem_RawMalloc()} or
@ref{a58,,PyMem_RawRealloc()}, or @code{NULL} if an error occurred, instead of a
string allocated by @ref{607,,PyMem_Malloc()} or @ref{a59,,PyMem_Realloc()}
(bpo-16742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16742})

@item 
@ref{a5a,,PyThread_set_key_value()} now always set the value. In Python
3.3, the function did nothing if the key already exists (if the current
value is a non-@code{NULL} pointer).

@item 
The @code{f_tstate} (thread state) field of the @ref{a5b,,PyFrameObject}
structure has been removed to fix a bug: see bpo-14432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14432} for the
rationale.
@end itemize

@node 3 4 3 的变化,,移植到 Python 3 4,Python 3 4 有什么新变化
@anchor{whatsnew/3 4 changed-in-3-4-3}@anchor{a5c}
@subsection 3.4.3 的变化


@menu
* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients. 

@end menu

@node PEP 476 Enabling certificate verification by default for stdlib http clients,,,3 4 3 的变化
@anchor{whatsnew/3 4 pep-476}@anchor{a5d}@anchor{whatsnew/3 4 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients}@anchor{a5e}
@subsubsection PEP 476: Enabling certificate verification by default for stdlib http clients


@ref{93,,http.client} and modules which use it, such as @ref{129,,urllib.request} and
@ref{148,,xmlrpc.client}, will now verify that the server presents a certificate
which is signed by a CA in the platform trust store and whose hostname matches
the hostname being requested by default, significantly improving security for
many applications.

For applications which require the old previous behavior, they can pass an
alternate context:

@example
import urllib.request
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib.request.urlopen("https://invalid-cert", context=context)
@end example

@node Python 3 3 有什么新变化,Python 3 2 有什么新变化,Python 3 4 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 3 doc}@anchor{a5f}@anchor{whatsnew/3 3 what-s-new-in-python-3-3}@anchor{a60}
@section Python 3.3 有什么新变化


@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer in :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the Mercurial log
@c when researching a change.

本文介绍了Python 3.3相比 3.2 的新增特性。Python 3.3于2012年9月29日发布。有关完整详细信息，请参见 changelog@footnote{https://docs.python.org/3.3/whatsnew/changelog.html}。


@subsubheading 参见


@geindex Python 提高建议; PEP 398
PEP 398@footnote{https://www.python.org/dev/peps/pep-0398} - Python 3.3 发布计划


@menu
* 摘要 - 发布重点: 摘要 - 发布重点<7>. 
* PEP 405; 虚拟环境: PEP 405 虚拟环境. 
* PEP 420; 隐式命名空间包: PEP 420 隐式命名空间包. 
* PEP 3118; 新的内存视图实现和缓冲协议文档: PEP 3118 新的内存视图实现和缓冲协议文档. 
* PEP 393; 灵活的字符串表示: PEP 393 灵活的字符串表示. 
* PEP 397; 适用于Windows的Python启动器: PEP 397 适用于Windows的Python启动器. 
* PEP 3151; 重写 OS 和 IO 异常的层次结构: PEP 3151 重写 OS 和 IO 异常的层次结构. 
* PEP 380; 委托给子生成器的语法: PEP 380 委托给子生成器的语法. 
* PEP 409; 清除异常上下文: PEP 409 清除异常上下文. 
* PEP 414; 显式的Unicode文本: PEP 414 显式的Unicode文本. 
* PEP 3155; 类和函数的限定名称: PEP 3155 类和函数的限定名称. 
* PEP 412; Key-Sharing Dictionary: PEP 412 Key-Sharing Dictionary. 
* PEP 362; 函数签名对象: PEP 362 函数签名对象. 
* PEP 421; 添加 sys.implementation: PEP 421 添加 sys implementation. 
* Using importlib as the Implementation of Import:: 
* 其他语言特性修改: 其他语言特性修改<7>. 
* A Finer-Grained Import Lock:: 
* Builtin functions and types:: 
* 新增模块: 新增模块<7>. 
* 改进的模块: 改进的模块<7>. 
* 性能优化: 性能优化<6>. 
* 构建和 C API 的改变: 构建和 C API 的改变<4>. 
* 弃用: 弃用<6>. 
* 移植到 Python 3.3: 移植到 Python 3 3. 

@end menu

@node 摘要 - 发布重点<7>,PEP 405 虚拟环境,,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 summary-release-highlights}@anchor{a61}
@subsection 摘要 - 发布重点


@c This section singles out the most important changes in Python 3.3.
@c Brevity is key.

新的语法特性：


@itemize *

@item 
新增 @code{yield from} 表达式用于 @ref{a62,,生成器委托}。

@item 
@code{u'unicode'} 语法重新被接受用于 @ref{206,,str} 对象。
@end itemize

新的库模块：


@itemize *

@item 
@ref{7b,,faulthandler} （帮助调试低级崩溃）

@item 
@ref{a2,,ipaddress} (代表 IP 地址和掩码的高层级对象)

@item 
@ref{ad,,lzma} (使用 XZ / LZMA 算法压缩数据)

@item 
@ref{125,,unittest.mock} (使用模拟对象替换你的受测试系统中的某些部分)

@item 
@ref{12e,,venv} (Python @ref{a63,,虚拟环境}，类似于流行的 @code{virtualenv} 包)
@end itemize

新的内置特性：


@itemize *

@item 
重写 @ref{a64,,I/O 异常的层次结构}.
@end itemize

实现的改进：


@itemize *

@item 
基于 @ref{9a,,importlib} 重写 @ref{a65,,import machinery}

@item 
更紧凑的 @ref{a66,,Unicode 字符串}。

@item 
更紧凑的 @ref{a67,,属性字典}。
@end itemize

显着改进的库模块：


@itemize *

@item 
针对 @ref{a68,,decimal} 模块的 C 加速器。

@item 
@ref{a69,,email} 模块中更好的 Unicode 处理 (@ref{a6a,,暂定})。
@end itemize

安全改进：


@itemize *

@item 
哈希随机化被默认启用。
@end itemize

请继续阅读有关面向用户的改变的详细清单。

@node PEP 405 虚拟环境,PEP 420 隐式命名空间包,摘要 - 发布重点<7>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-405}@anchor{a63}@anchor{whatsnew/3 3 pep-405-virtual-environments}@anchor{a6b}
@subsection PEP 405: 虚拟环境


Virtual environments help create separate Python setups while sharing a
system-wide base install, for ease of maintenance.  Virtual environments
have their own set of private site packages (i.e. locally-installed
libraries), and are optionally segregated from the system-wide site
packages.  Their concept and implementation are inspired by the popular
@code{virtualenv} third-party package, but benefit from tighter integration
with the interpreter core.

This PEP adds the @ref{12e,,venv} module for programmatic access, and the
@code{pyvenv} script for command-line access and
administration.  The Python interpreter checks for a @code{pyvenv.cfg},
file whose existence signals the base of a virtual environment's directory
tree.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 405

@item PEP 405@footnote{https://www.python.org/dev/peps/pep-0405} - Python虚拟环境

PEP 由 Carl Meyer 撰写 ; 由 Carl Meyer 和 Vinay Sajip 实现。
@end table


@node PEP 420 隐式命名空间包,PEP 3118 新的内存视图实现和缓冲协议文档,PEP 405 虚拟环境,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-420-implicit-namespace-packages}@anchor{a6c}
@subsection PEP 420: 隐式命名空间包


Native support for package directories that don't require @code{__init__.py}
marker files and can automatically span multiple path segments (inspired by
various third party approaches to namespace packages, as described in
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420})


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 420

@item PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} - 隐式命名空间包

PEP 由 Eric V. Smith 撰写，由 Eric V. Smith 和 Barry Warsaw 实现
@end table


@node PEP 3118 新的内存视图实现和缓冲协议文档,PEP 393 灵活的字符串表示,PEP 420 隐式命名空间包,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-3118-new-memoryview-implementation-and-buffer-protocol-documentation}@anchor{a6d}@anchor{whatsnew/3 3 pep-3118-update}@anchor{a6e}
@subsection PEP 3118: 新的内存视图实现和缓冲协议文档


@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} 的实现已获得大幅改进。

The new memoryview implementation comprehensively fixes all ownership and
lifetime issues of dynamically allocated fields in the Py_buffer struct
that led to multiple crash reports. Additionally, several functions that
crashed or returned incorrect results for non-contiguous or multi-dimensional
input have been fixed.

The memoryview object now has a PEP-3118 compliant getbufferproc()
that checks the consumer's request type. Many new features have been
added, most of them work in full generality for non-contiguous arrays
and arrays with suboffsets.

The documentation has been updated, clearly spelling out responsibilities
for both exporters and consumers. Buffer request flags are grouped into
basic and compound flags. The memory layout of non-contiguous and
multi-dimensional NumPy-style arrays is explained.

@menu
* 相关特性:: 
* API 的变化:: 

@end menu

@node 相关特性,API 的变化,,PEP 3118 新的内存视图实现和缓冲协议文档
@anchor{whatsnew/3 3 features}@anchor{a6f}
@subsubsection 相关特性



@itemize *

@item 
All native single character format specifiers in struct module syntax
(optionally prefixed with '@@') are now supported.

@item 
With some restrictions, the cast() method allows changing of format and
shape of C-contiguous arrays.

@item 
Multi-dimensional list representations are supported for any array type.

@item 
Multi-dimensional comparisons are supported for any array type.

@item 
One-dimensional memoryviews of hashable (read-only) types with formats B,
b or c are now hashable.  (Contributed by Antoine Pitrou in bpo-13411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13411}.)

@item 
Arbitrary slicing of any 1-D arrays type is supported. For example, it
is now possible to reverse a memoryview in O(1) by using a negative step.
@end itemize

@node API 的变化,,相关特性,PEP 3118 新的内存视图实现和缓冲协议文档
@anchor{whatsnew/3 3 api-changes}@anchor{a70}
@subsubsection API 的变化



@itemize *

@item 
官方的最大维度数量限制已更改为 64。

@item 
The representation of empty shape, strides and suboffsets is now
an empty tuple instead of @code{None}.

@item 
Accessing a memoryview element with format 'B' (unsigned bytes)
now returns an integer (in accordance with the struct module syntax).
For returning a bytes object the view must be cast to 'c' first.

@item 
memoryview comparisons now use the logical structure of the operands
and compare all array elements by value. All format strings in struct
module syntax are supported. Views with unrecognised format strings
are still permitted, but will always compare as unequal, regardless
of view contents.

@item 
For further changes see @ref{a71,,Build and C API Changes} and @ref{a72,,Porting C code}.
@end itemize

（由 Stefan Krah 在 bpo-10181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10181} 中贡献。）


@subsubheading 参见


@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} - 修改缓冲区协议


@node PEP 393 灵活的字符串表示,PEP 397 适用于Windows的Python启动器,PEP 3118 新的内存视图实现和缓冲协议文档,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-393}@anchor{a66}@anchor{whatsnew/3 3 pep-393-flexible-string-representation}@anchor{a73}
@subsection PEP 393: 灵活的字符串表示


The Unicode string type is changed to support multiple internal
representations, depending on the character with the largest Unicode ordinal
(1, 2, or 4 bytes) in the represented string.  This allows a space-efficient
representation in common cases, but gives access to full UCS-4 on all
systems.  For compatibility with existing APIs, several representations may
exist in parallel; over time, this compatibility should be phased out.

On the Python side, there should be no downside to this change.

On the C API side, 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} is fully backward compatible.  The legacy API
should remain available at least five years.  Applications using the legacy
API will not fully benefit of the memory reduction, or - worse - may use
a bit more memory, because Python may have to maintain two versions of each
string (in the legacy format and in the new efficient storage).

@menu
* 功能:: 
* Performance and resource usage:: 

@end menu

@node 功能,Performance and resource usage,,PEP 393 灵活的字符串表示
@anchor{whatsnew/3 3 functionality}@anchor{a74}
@subsubsection 功能


由 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 引入的改变如下:


@itemize *

@item 
Python now always supports the full range of Unicode code points, including
non-BMP ones (i.e. from @code{U+0000} to @code{U+10FFFF}).  The distinction between
narrow and wide builds no longer exists and Python now behaves like a wide
build, even under Windows.

@item 
With the death of narrow builds, the problems specific to narrow builds have
also been fixed, for example:


@itemize *

@item 
@ref{292,,len()} now always returns 1 for non-BMP characters,
so @code{len('\U0010FFFF') == 1};

@item 
surrogate pairs are not recombined in string literals,
so @code{'\uDBFF\uDFFF' != '\U0010FFFF'};

@item 
indexing or slicing non-BMP characters returns the expected value,
so @code{'\U0010FFFF'[0]} now returns @code{'\U0010FFFF'} and not @code{'\uDBFF'};

@item 
all other functions in the standard library now correctly handle
non-BMP code points.
@end itemize

@item 
The value of @ref{a75,,sys.maxunicode} is now always @code{1114111} (@code{0x10FFFF}
in hexadecimal).  The @code{PyUnicode_GetMax()} function still returns
either @code{0xFFFF} or @code{0x10FFFF} for backward compatibility, and it should
not be used with the new Unicode API (see bpo-13054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13054}).

@item 
The @code{./configure} flag @code{--with-wide-unicode} has been removed.
@end itemize

@node Performance and resource usage,,功能,PEP 393 灵活的字符串表示
@anchor{whatsnew/3 3 performance-and-resource-usage}@anchor{a76}
@subsubsection Performance and resource usage


The storage of Unicode strings now depends on the highest code point in the string:


@itemize *

@item 
pure ASCII and Latin1 strings (@code{U+0000-U+00FF}) use 1 byte per code point;

@item 
BMP strings (@code{U+0000-U+FFFF}) use 2 bytes per code point;

@item 
non-BMP strings (@code{U+10000-U+10FFFF}) use 4 bytes per code point.
@end itemize

The net effect is that for most applications, memory usage of string
storage should decrease significantly - especially compared to former
wide unicode builds - as, in many cases, strings will be pure ASCII
even in international contexts (because many strings store non-human
language data, such as XML fragments, HTTP headers, JSON-encoded data,
etc.).  We also hope that it will, for the same reasons, increase CPU
cache efficiency on non-trivial applications. The memory usage of
Python 3.3 is two to three times smaller than Python 3.2, and a little
bit better than Python 2.7, on a Django benchmark (see the PEP for
details).


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 393

@item PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} - 灵活的字符串表示

PEP 由 Martin von Löwis 撰写 ; 由 Torsten Becker 和 Martin von Löwis 实现。
@end table


@node PEP 397 适用于Windows的Python启动器,PEP 3151 重写 OS 和 IO 异常的层次结构,PEP 393 灵活的字符串表示,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-397}@anchor{a77}@anchor{whatsnew/3 3 pep-397-python-launcher-for-windows}@anchor{a78}
@subsection PEP 397: 适用于Windows的Python启动器


The Python 3.3 Windows installer now includes a @code{py} launcher application
that can be used to launch Python applications in a version independent
fashion.

This launcher is invoked implicitly when double-clicking @code{*.py} files.
If only a single Python version is installed on the system, that version
will be used to run the file. If multiple versions are installed, the most
recent version is used by default, but this can be overridden by including
a Unix-style "shebang line" in the Python script.

The launcher can also be used explicitly from the command line as the @code{py}
application. Running @code{py} follows the same version selection rules as
implicitly launching scripts, but a more specific version can be selected
by passing appropriate arguments (such as @code{-3} to request Python 3 when
Python 2 is also installed, or @code{-2.6} to specifically request an earlier
Python version when a more recent version is installed).

In addition to the launcher, the Windows installer now includes an
option to add the newly installed Python to the system PATH.  (Contributed
by Brian Curtin in bpo-3561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3561}.)


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 397

@item PEP 397@footnote{https://www.python.org/dev/peps/pep-0397} - 适用于Windows的Python启动器

PEP 由 Mark Hammond 和 Martin v. Löwis 撰写 ; 由 Vinay Sajip实现。
@end table

Launcher documentation: @ref{a79,,适用于Windows的Python启动器}

安装器 PATH 修改: @ref{a7a,,查找Python可执行文件}


@node PEP 3151 重写 OS 和 IO 异常的层次结构,PEP 380 委托给子生成器的语法,PEP 397 适用于Windows的Python启动器,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-3151}@anchor{a64}@anchor{whatsnew/3 3 pep-3151-reworking-the-os-and-io-exception-hierarchy}@anchor{a7b}
@subsection PEP 3151: 重写 OS 和 IO 异常的层次结构


The hierarchy of exceptions raised by operating system errors is now both
simplified and finer-grained.

You don't have to worry anymore about choosing the appropriate exception
type between @ref{30b,,OSError}, @ref{a7c,,IOError}, @ref{a7d,,EnvironmentError},
@ref{a7e,,WindowsError}, @code{mmap.error}, @ref{a7f,,socket.error} or
@ref{a80,,select.error}.  All these exception types are now only one:
@ref{30b,,OSError}.  The other names are kept as aliases for compatibility
reasons.

Also, it is now easier to catch a specific error condition.  Instead of
inspecting the @code{errno} attribute (or @code{args[0]}) for a particular
constant from the @ref{7a,,errno} module, you can catch the adequate
@ref{30b,,OSError} subclass.  The available subclasses are the following:


@itemize *

@item 
@ref{a81,,BlockingIOError}

@item 
@ref{a82,,ChildProcessError}

@item 
@ref{7e1,,ConnectionError}

@item 
@ref{a42,,FileExistsError}

@item 
@ref{8b7,,FileNotFoundError}

@item 
@ref{756,,InterruptedError}

@item 
@ref{a83,,IsADirectoryError}

@item 
@ref{a84,,NotADirectoryError}

@item 
@ref{700,,PermissionError}

@item 
@ref{a85,,ProcessLookupError}

@item 
@ref{a86,,TimeoutError}
@end itemize

And the @ref{7e1,,ConnectionError} itself has finer-grained subclasses:


@itemize *

@item 
@ref{a87,,BrokenPipeError}

@item 
@ref{a88,,ConnectionAbortedError}

@item 
@ref{a89,,ConnectionRefusedError}

@item 
@ref{a8a,,ConnectionResetError}
@end itemize

Thanks to the new exceptions, common usages of the @ref{7a,,errno} can now be
avoided.  For example, the following code written for Python 3.2:

@example
from errno import ENOENT, EACCES, EPERM

try:
    with open("document.txt") as f:
        content = f.read()
except IOError as err:
    if err.errno == ENOENT:
        print("document.txt file is missing")
    elif err.errno in (EACCES, EPERM):
        print("You are not allowed to read document.txt")
    else:
        raise
@end example

can now be written without the @ref{7a,,errno} import and without manual
inspection of exception attributes:

@example
try:
    with open("document.txt") as f:
        content = f.read()
except FileNotFoundError:
    print("document.txt file is missing")
except PermissionError:
    print("You are not allowed to read document.txt")
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3151

@item PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151} - 重写 OS 和 IO 异常的层次结构

PEP 由 Antoine Pitrou 撰写并实现
@end table


@geindex yield; yield from (in What's New)

@node PEP 380 委托给子生成器的语法,PEP 409 清除异常上下文,PEP 3151 重写 OS 和 IO 异常的层次结构,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-380}@anchor{a62}@anchor{whatsnew/3 3 pep-380-syntax-for-delegating-to-a-subgenerator}@anchor{a8b}
@subsection PEP 380: 委托给子生成器的语法


PEP 380 adds the @code{yield from} expression, allowing a @ref{a8c,,generator} to
delegate
part of its operations to another generator. This allows a section of code
containing @ref{2ce,,yield} to be factored out and placed in another generator.
Additionally, the subgenerator is allowed to return with a value, and the
value is made available to the delegating generator.

While designed primarily for use in delegating to a subgenerator, the @code{yield
from} expression actually allows delegation to arbitrary subiterators.

For simple iterators, @code{yield from iterable} is essentially just a shortened
form of @code{for item in iterable: yield item}:

@example
>>> def g(x):
...     yield from range(x, 0, -1)
...     yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
@end example

However, unlike an ordinary loop, @code{yield from} allows subgenerators to
receive sent and thrown values directly from the calling scope, and
return a final value to the outer generator:

@example
>>> def accumulate():
...     tally = 0
...     while 1:
...         next = yield
...         if next is None:
...             return tally
...         tally += next
...
>>> def gather_tallies(tallies):
...     while 1:
...         tally = yield from accumulate()
...         tallies.append(tally)
...
>>> tallies = []
>>> acc = gather_tallies(tallies)
>>> next(acc)  # Ensure the accumulator is ready to accept values
>>> for i in range(4):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the first tally
>>> for i in range(5):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the second tally
>>> tallies
[6, 10]
@end example

The main principle driving this change is to allow even generators that are
designed to be used with the @code{send} and @code{throw} methods to be split into
multiple subgenerators as easily as a single large function can be split into
multiple subfunctions.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 380

@item PEP 380@footnote{https://www.python.org/dev/peps/pep-0380} - 委托给子生成器的语法

PEP 由 Greg Ewing 撰写，由 Greg Ewing 实现。由 Renaud Blanch，Ryan Kelly 和 Nick Coghlan 集成到3.3，由 Zbigniew Jędrzejewski-Szmek 和 Nick Coghlan 编写文档
@end table


@node PEP 409 清除异常上下文,PEP 414 显式的Unicode文本,PEP 380 委托给子生成器的语法,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-409-suppressing-exception-context}@anchor{a8d}
@subsection PEP 409: 清除异常上下文


PEP 409 introduces new syntax that allows the display of the chained
exception context to be disabled. This allows cleaner error messages in
applications that convert between exception types:

@example
>>> class D:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr) from None
...
>>> D(@{@}).x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x
@end example

Without the @code{from None} suffix to suppress the cause, the original
exception would be displayed by default:

@example
>>> class C:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr)
...
>>> C(@{@}).x
Traceback (most recent call last):
  File "<stdin>", line 6, in __getattr__
KeyError: 'x'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x
@end example

No debugging capability is lost, as the original exception context remains
available if needed (for example, if an intervening library has incorrectly
suppressed valuable underlying details):

@example
>>> try:
...     D(@{@}).x
... except AttributeError as exc:
...     print(repr(exc.__context__))
...
KeyError('x',)
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 409

@item PEP 409@footnote{https://www.python.org/dev/peps/pep-0409} - 清除异常上下文

PEP 由 Ethan Furman 撰写 ，由 Ethan Furman 和 Nick Coghlan 实现。
@end table


@node PEP 414 显式的Unicode文本,PEP 3155 类和函数的限定名称,PEP 409 清除异常上下文,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-414-explicit-unicode-literals}@anchor{a8e}
@subsection PEP 414: 显式的Unicode文本


To ease the transition from Python 2 for Unicode aware Python applications
that make heavy use of Unicode literals, Python 3.3 once again supports the
"@code{u}" prefix for string literals. This prefix has no semantic significance
in Python 3, it is provided solely to reduce the number of purely mechanical
changes in migrating to Python 3, making it easier for developers to focus on
the more significant semantic changes (such as the stricter default
separation of binary and text data).


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 414

@item PEP 414@footnote{https://www.python.org/dev/peps/pep-0414} - 显式的Unicode文本

PEP 由 Armin Ronacher 撰写
@end table


@node PEP 3155 类和函数的限定名称,PEP 412 Key-Sharing Dictionary,PEP 414 显式的Unicode文本,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-3155-qualified-name-for-classes-and-functions}@anchor{a8f}
@subsection PEP 3155: 类和函数的限定名称


Functions and class objects have a new @code{__qualname__} attribute representing
the "path" from the module top-level to their definition.  For global functions
and classes, this is the same as @code{__name__}.  For other functions and classes,
it provides better information about where they were actually defined, and
how they might be accessible from the global scope.

Example with (non-bound) methods:

@example
>>> class C:
...     def meth(self):
...         pass
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__
'C.meth'
@end example

Example with nested classes:

@example
>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.D.__name__
'D'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__name__
'meth'
>>> C.D.meth.__qualname__
'C.D.meth'
@end example

Example with nested functions:

@example
>>> def outer():
...     def inner():
...         pass
...     return inner
...
>>> outer().__name__
'inner'
>>> outer().__qualname__
'outer.<locals>.inner'
@end example

The string representation of those objects is also changed to include the
new, more precise information:

@example
>>> str(C.D)
"<class '__main__.C.D'>"
>>> str(C.D.meth)
'<function C.D.meth at 0x7f46b9fe31e0>'
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3155

@item PEP 3155@footnote{https://www.python.org/dev/peps/pep-3155} - 类和函数的限定名称

PEP 由 Antoine Pitrou 撰写并实现
@end table


@node PEP 412 Key-Sharing Dictionary,PEP 362 函数签名对象,PEP 3155 类和函数的限定名称,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-412}@anchor{a67}@anchor{whatsnew/3 3 pep-412-key-sharing-dictionary}@anchor{a90}
@subsection PEP 412: Key-Sharing Dictionary


Dictionaries used for the storage of objects' attributes are now able to
share part of their internal storage between each other (namely, the part
which stores the keys and their respective hashes).  This reduces the memory
consumption of programs creating many instances of non-builtin types.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 412

@item PEP 412@footnote{https://www.python.org/dev/peps/pep-0412} - Key-Sharing Dictionary

PEP 由 Mark Shannon 撰写并实现。
@end table


@node PEP 362 函数签名对象,PEP 421 添加 sys implementation,PEP 412 Key-Sharing Dictionary,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-362-function-signature-object}@anchor{a91}
@subsection PEP 362: 函数签名对象


A new function @ref{65e,,inspect.signature()} makes introspection of python
callables easy and straightforward.  A broad range of callables is supported:
python functions, decorated or not, classes, and @ref{8bf,,functools.partial()}
objects.  New classes @ref{7ee,,inspect.Signature}, @ref{7ef,,inspect.Parameter}
and @ref{a92,,inspect.BoundArguments} hold information about the call signatures,
such as, annotations, default values, parameters kinds, and bound arguments,
which considerably simplifies writing decorators and any code that validates
or amends calling signatures or arguments.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 362

@item PEP 362@footnote{https://www.python.org/dev/peps/pep-0362}: -  函数签名对象

PEP 由 Brett Cannon，Yury Selivanov，Larry Hastings，Jiwon Seo 撰写，由 Yury Selivanov 实现
@end table


@node PEP 421 添加 sys implementation,Using importlib as the Implementation of Import,PEP 362 函数签名对象,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 pep-421-adding-sys-implementation}@anchor{a93}
@subsection PEP 421: 添加 sys.implementation


A new attribute on the @ref{fd,,sys} module exposes details specific to the
implementation of the currently running interpreter.  The initial set of
attributes on @ref{a94,,sys.implementation} are @code{name}, @code{version},
@code{hexversion}, and @code{cache_tag}.

The intention of @code{sys.implementation} is to consolidate into one namespace
the implementation-specific data used by the standard library.  This allows
different Python implementations to share a single standard library code base
much more easily.  In its initial state, @code{sys.implementation} holds only a
small portion of the implementation-specific data.  Over time that ratio will
shift in order to make the standard library more portable.

One example of improved standard library portability is @code{cache_tag}.  As of
Python 3.3, @code{sys.implementation.cache_tag} is used by @ref{9a,,importlib} to
support 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} compliance.  Any Python implementation that uses
@code{importlib} for its built-in import system may use @code{cache_tag} to control
the caching behavior for modules.

@menu
* SimpleNamespace:: 

@end menu

@node SimpleNamespace,,,PEP 421 添加 sys implementation
@anchor{whatsnew/3 3 simplenamespace}@anchor{a95}
@subsubsection SimpleNamespace


The implementation of @code{sys.implementation} also introduces a new type to
Python: @ref{1d9,,types.SimpleNamespace}.  In contrast to a mapping-based
namespace, like @ref{164,,dict}, @code{SimpleNamespace} is attribute-based, like
@ref{3da,,object}.  However, unlike @code{object}, @code{SimpleNamespace} instances
are writable.  This means that you can add, remove, and modify the namespace
through normal attribute access.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 421

@item PEP 421@footnote{https://www.python.org/dev/peps/pep-0421} - 添加 sys.implementation

PEP 由 Eric Snow 撰写并实现
@end table


@node Using importlib as the Implementation of Import,其他语言特性修改<7>,PEP 421 添加 sys implementation,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 importlib}@anchor{a65}@anchor{whatsnew/3 3 using-importlib-as-the-implementation-of-import}@anchor{a96}
@subsection Using importlib as the Implementation of Import


bpo-2377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2377} - Replace __import__ w/ importlib.__import__
bpo-13959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13959} - Re-implement parts of @ref{99,,imp} in pure Python
bpo-14605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14605} - Make import machinery explicit
bpo-14646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14646} - Require loaders set __loader__ and __package__

The @ref{16b,,__import__()} function is now powered by @ref{a97,,importlib.__import__()}.
This work leads to the completion of "phase 2" of 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}. There are
multiple benefits to this change. First, it has allowed for more of the
machinery powering import to be exposed instead of being implicit and hidden
within the C code. It also provides a single implementation for all Python VMs
supporting Python 3.3 to use, helping to end any VM-specific deviations in
import semantics. And finally it eases the maintenance of import, allowing for
future growth to occur.

For the common user, there should be no visible change in semantics.  For
those whose code currently manipulates import or calls import
programmatically, the code changes that might possibly be required are covered
in the @ref{a98,,Porting Python code} section of this document.

@menu
* New APIs:: 
* 可见的改变:: 

@end menu

@node New APIs,可见的改变,,Using importlib as the Implementation of Import
@anchor{whatsnew/3 3 new-apis}@anchor{a99}
@subsubsection New APIs


One of the large benefits of this work is the exposure of what goes into
making the import statement work. That means the various importers that were
once implicit are now fully exposed as part of the @ref{9a,,importlib} package.

The abstract base classes defined in @ref{9b,,importlib.abc} have been expanded
to properly delineate between @ref{a9a,,meta path finders}
and @ref{a9b,,path entry finders} by introducing
@ref{a9c,,importlib.abc.MetaPathFinder} and
@ref{a9d,,importlib.abc.PathEntryFinder}, respectively. The old ABC of
@ref{a9e,,importlib.abc.Finder} is now only provided for backwards-compatibility
and does not enforce any method requirements.

In terms of finders, @ref{a9f,,importlib.machinery.FileFinder} exposes the
mechanism used to search for source and bytecode files of a module. Previously
this class was an implicit member of @ref{a46,,sys.path_hooks}.

For loaders, the new abstract base class @ref{aa0,,importlib.abc.FileLoader} helps
write a loader that uses the file system as the storage mechanism for a module's
code. The loader for source files
(@ref{aa1,,importlib.machinery.SourceFileLoader}), sourceless bytecode files
(@ref{aa2,,importlib.machinery.SourcelessFileLoader}), and extension modules
(@ref{659,,importlib.machinery.ExtensionFileLoader}) are now available for
direct use.

@ref{16c,,ImportError} now has @code{name} and @code{path} attributes which are set when
there is relevant data to provide. The message for failed imports will also
provide the full name of the module now instead of just the tail end of the
module's name.

The @ref{59f,,importlib.invalidate_caches()} function will now call the method with
the same name on all finders cached in @ref{5a0,,sys.path_importer_cache} to help
clean up any stored state as necessary.

@node 可见的改变,,New APIs,Using importlib as the Implementation of Import
@anchor{whatsnew/3 3 visible-changes}@anchor{aa3}
@subsubsection 可见的改变


For potential required changes to code, see the @ref{a98,,Porting Python code}
section.

Beyond the expanse of what @ref{9a,,importlib} now exposes, there are other
visible changes to import. The biggest is that @ref{6e7,,sys.meta_path} and
@ref{a46,,sys.path_hooks} now store all of the meta path finders and path entry
hooks used by import.  Previously the finders were implicit and hidden within
the C code of import instead of being directly exposed. This means that one can
now easily remove or change the order of the various finders to fit one's needs.

Another change is that all modules have a @code{__loader__} attribute, storing the
loader used to create the module. 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} has been updated to make this
attribute mandatory for loaders to implement, so in the future once 3rd-party
loaders have been updated people will be able to rely on the existence of the
attribute. Until such time, though, import is setting the module post-load.

Loaders are also now expected to set the @code{__package__} attribute from
@geindex Python 提高建议; PEP 366
PEP 366@footnote{https://www.python.org/dev/peps/pep-0366}. Once again, import itself is already setting this on all loaders
from @ref{9a,,importlib} and import itself is setting the attribute post-load.

@code{None} is now inserted into @ref{5a0,,sys.path_importer_cache} when no finder
can be found on @ref{a46,,sys.path_hooks}. Since @ref{aa4,,imp.NullImporter} is not
directly exposed on @ref{a46,,sys.path_hooks} it could no longer be relied upon to
always be available to use as a value representing no finder found.

All other changes relate to semantic changes which should be taken into
consideration when updating code for Python 3.3, and thus should be read about
in the @ref{a98,,Porting Python code} section of this document.

(Implementation by Brett Cannon)

@node 其他语言特性修改<7>,A Finer-Grained Import Lock,Using importlib as the Implementation of Import,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 other-language-changes}@anchor{aa5}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
Added support for Unicode name aliases and named sequences.
Both @ref{aa6,,unicodedata.lookup()} and @code{'\N@{...@}'} now resolve name aliases,
and @ref{aa6,,unicodedata.lookup()} resolves named sequences too.

（由 Ezio Melotti 在 bpo-12753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12753} 中贡献。）

@item 
Unicode database updated to UCD version 6.1.0

@item 
Equality comparisons on @ref{1f6,,range()} objects now return a result reflecting
the equality of the underlying sequences generated by those range objects.
(bpo-13201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13201})

@item 
The @code{count()}, @code{find()}, @code{rfind()}, @code{index()} and @code{rindex()}
methods of @ref{172,,bytes} and @ref{173,,bytearray} objects now accept an
integer between 0 and 255 as their first argument.

（由 Petri Lehtinen 在 bpo-12170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12170} 中贡献。）

@item 
The @code{rjust()}, @code{ljust()}, and @code{center()} methods of @ref{172,,bytes}
and @ref{173,,bytearray} now accept a @ref{173,,bytearray} for the @code{fill}
argument.  (Contributed by Petri Lehtinen in bpo-12380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12380}.)

@item 
New methods have been added to @ref{1f9,,list} and @ref{173,,bytearray}:
@code{copy()} and @code{clear()} (bpo-10516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10516}).  Consequently,
@ref{7a9,,MutableSequence} now also defines a
@code{clear()} method (bpo-11388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11388}).

@item 
Raw bytes literals can now be written @code{rb"..."} as well as @code{br"..."}.

（由 Antoine Pitrou 在 bpo-13748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13748} 中贡献。）

@item 
@ref{aa7,,dict.setdefault()} now does only one lookup for the given key, making
it atomic when used with built-in types.

（由 Filip Gruszczyński 在 bpo-13521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13521} 中贡献。）

@item 
The error messages produced when a function call does not match the function
signature have been significantly improved.

（由 Benjamin Peterson 贡献。）
@end itemize

@node A Finer-Grained Import Lock,Builtin functions and types,其他语言特性修改<7>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 a-finer-grained-import-lock}@anchor{aa8}
@subsection A Finer-Grained Import Lock


Previous versions of CPython have always relied on a global import lock.
This led to unexpected annoyances, such as deadlocks when importing a module
would trigger code execution in a different thread as a side-effect.
Clumsy workarounds were sometimes employed, such as the
@ref{aa9,,PyImport_ImportModuleNoBlock()} C API function.

In Python 3.3, importing a module takes a per-module lock.  This correctly
serializes importation of a given module from multiple threads (preventing
the exposure of incompletely initialized modules), while eliminating the
aforementioned annoyances.

（由 Antoine Pitrou 在 bpo-9260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9260} 中贡献。）

@node Builtin functions and types,新增模块<7>,A Finer-Grained Import Lock,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 builtin-functions-and-types}@anchor{aaa}
@subsection Builtin functions and types



@itemize *

@item 
@ref{16f,,open()} gets a new @emph{opener} parameter: the underlying file descriptor
for the file object is then obtained by calling @emph{opener} with (@emph{file},
@emph{flags}). It can be used to use custom flags like @ref{aab,,os.O_CLOEXEC} for
example. The @code{'x'} mode was added: open for exclusive creation, failing if
the file already exists.

@item 
@ref{97a,,print()}: added the @emph{flush} keyword argument. If the @emph{flush} keyword
argument is true, the stream is forcibly flushed.

@item 
@ref{aac,,hash()}: hash randomization is enabled by default, see
@ref{455,,object.__hash__()} and 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED}.

@item 
The @ref{206,,str} type gets a new @ref{7ad,,casefold()} method: return a
casefolded copy of the string, casefolded strings may be used for caseless
matching. For example, @code{'ß'.casefold()} returns @code{'ss'}.

@item 
The sequence documentation has been substantially rewritten to better
explain the binary/text sequence distinction and to provide specific
documentation sections for the individual builtin sequence types
(bpo-4966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4966}).
@end itemize

@node 新增模块<7>,改进的模块<7>,Builtin functions and types,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 new-modules}@anchor{aae}
@subsection 新增模块


@menu
* faulthandler: faulthandler<3>. 
* ipaddress: ipaddress<5>. 
* lzma: lzma<2>. 

@end menu

@node faulthandler<3>,ipaddress<5>,,新增模块<7>
@anchor{whatsnew/3 3 faulthandler}@anchor{aaf}
@subsubsection faulthandler


This new debug module @ref{7b,,faulthandler} contains functions to dump Python tracebacks explicitly,
on a fault (a crash like a segmentation fault), after a timeout, or on a user
signal. Call @ref{64b,,faulthandler.enable()} to install fault handlers for the
@code{SIGSEGV}, @code{SIGFPE}, @code{SIGABRT}, @code{SIGBUS}, and
@code{SIGILL} signals. You can also enable them at startup by setting the
@geindex PYTHONFAULTHANDLER
@geindex 环境变量; PYTHONFAULTHANDLER
@ref{ab0,,PYTHONFAULTHANDLER} environment variable or by using @ref{297,,-X}
@code{faulthandler} command line option.

Example of a segmentation fault on Linux:

@example
$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700:
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault
@end example

@node ipaddress<5>,lzma<2>,faulthandler<3>,新增模块<7>
@anchor{whatsnew/3 3 ipaddress}@anchor{ab1}
@subsubsection ipaddress


The new @ref{a2,,ipaddress} module provides tools for creating and manipulating
objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e.
an IP address associated with a specific IP subnet).

（由 Google 和 Peter Moody 在 bpo-3144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3144} 中贡献。）

@node lzma<2>,,ipaddress<5>,新增模块<7>
@anchor{whatsnew/3 3 lzma}@anchor{ab2}
@subsubsection lzma


The newly-added @ref{ad,,lzma} module provides data compression and decompression
using the LZMA algorithm, including support for the @code{.xz} and @code{.lzma}
file formats.

（由 Nadeem Vawda 和 Per Øyvind Karlsen 在 bpo-6715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6715} 中贡献。）

@node 改进的模块<7>,性能优化<6>,新增模块<7>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 improved-modules}@anchor{ab3}
@subsection 改进的模块


@menu
* abc: abc<2>. 
* array: array<2>. 
* base64: base64<2>. 
* binascii: binascii<3>. 
* bz2: bz2<2>. 
* 编码器:: 
* collections: collections<7>. 
* contextlib: contextlib<5>. 
* crypt: crypt<2>. 
* curses: curses<4>. 
* datetime: datetime<5>. 
* decimal: decimal<3>. 
* email: email<4>. 
* ftplib: ftplib<2>. 
* functools: functools<5>. 
* gc: gc<5>. 
* hmac: hmac<3>. 
* http: http<4>. 
* html: html<2>. 
* imaplib: imaplib<3>. 
* inspect: inspect<6>. 
* io: io<4>. 
* itertools: itertools<3>. 
* logging: logging<6>. 
* math: math<6>. 
* mmap: mmap<3>. 
* multiprocessing: multiprocessing<7>. 
* nntplib: nntplib<2>. 
* os: os<8>. 
* pdb: pdb<5>. 
* pickle: pickle<5>. 
* pydoc: pydoc<5>. 
* re: re<6>. 
* sched:: 
* select: select<2>. 
* shlex: shlex<3>. 
* shutil: shutil<4>. 
* signal: signal<4>. 
* smtpd: smtpd<3>. 
* smtplib: smtplib<4>. 
* socket: socket<8>. 
* socketserver: socketserver<3>. 
* sqlite3: sqlite3<5>. 
* ssl: ssl<8>. 
* stat: stat<2>. 
* struct: struct<3>. 
* subprocess: subprocess<5>. 
* sys: sys<8>. 
* tarfile: tarfile<5>. 
* tempfile:: 
* textwrap: textwrap<2>. 
* threading: threading<5>. 
* time: time<6>. 
* types: types<4>. 
* unittest: unittest<5>. 
* urllib: urllib<3>. 
* webbrowser:: 
* xml.etree.ElementTree: xml etree ElementTree. 
* zlib: zlib<2>. 

@end menu

@node abc<2>,array<2>,,改进的模块<7>
@anchor{whatsnew/3 3 abc}@anchor{ab4}
@subsubsection abc


Improved support for abstract base classes containing descriptors composed with
abstract methods. The recommended approach to declaring abstract descriptors is
now to provide @code{__isabstractmethod__} as a dynamically updated
property. The built-in descriptors have been updated accordingly.

@quotation


@itemize *

@item 
@ref{ab5,,abc.abstractproperty} has been deprecated, use @ref{30f,,property}
with @ref{ab6,,abc.abstractmethod()} instead.

@item 
@ref{ab7,,abc.abstractclassmethod} has been deprecated, use
@ref{310,,classmethod} with @ref{ab6,,abc.abstractmethod()} instead.

@item 
@ref{ab8,,abc.abstractstaticmethod} has been deprecated, use
@ref{311,,staticmethod} with @ref{ab6,,abc.abstractmethod()} instead.
@end itemize
@end quotation

（由 Pablo Galindo 在 bpo-11610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11610} 中贡献。）

@ref{ab9,,abc.ABCMeta.register()} now returns the registered subclass, which means
it can now be used as a class decorator (bpo-10868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10868}).

@node array<2>,base64<2>,abc<2>,改进的模块<7>
@anchor{whatsnew/3 3 array}@anchor{aba}
@subsubsection array


The @ref{6,,array} module supports the @code{long long} type using @code{q} and
@code{Q} type codes.

（由 Oren Tirosh 和 Hirokazu Yamamoto 在 bpo-1172711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1172711} 中贡献。）

@node base64<2>,binascii<3>,array<2>,改进的模块<7>
@anchor{whatsnew/3 3 base64}@anchor{abb}
@subsubsection base64


ASCII-only Unicode strings are now accepted by the decoding functions of the
@ref{d,,base64} modern interface. For example, @code{base64.b64decode('YWJj')}
returns @code{b'abc'}.  (Contributed by Catalin Iacob in bpo-13641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13641}.)

@node binascii<3>,bz2<2>,base64<2>,改进的模块<7>
@anchor{whatsnew/3 3 binascii}
@subsubsection binascii


In addition to the binary objects they normally accept, the @code{a2b_} functions
now all also accept ASCII-only strings as input.  (Contributed by Antoine
Pitrou in bpo-13637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13637}.)

@node bz2<2>,编码器,binascii<3>,改进的模块<7>
@anchor{whatsnew/3 3 bz2}@anchor{abd}
@subsubsection bz2


The @ref{13,,bz2} module has been rewritten from scratch. In the process, several
new features have been added:


@itemize *

@item 
New @ref{abe,,bz2.open()} function: open a bzip2-compressed file in binary or
text mode.

@item 
@ref{225,,bz2.BZ2File} 现在可以读写任意文件类对象，具体方式是通过其构造器的 @emph{fileobj} 参数。

（由 Nadeem Vawda 在 bpo-5863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5863} 中贡献。）

@item 
@ref{225,,bz2.BZ2File} and @ref{abf,,bz2.decompress()} can now decompress
multi-stream inputs (such as those produced by the @code{pbzip2} tool).
@ref{225,,bz2.BZ2File} can now also be used to create this type of file, using
the @code{'a'} (append) mode.

（由 Nir Aides 在 bpo-1625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1625} 中贡献。）

@item 
@ref{225,,bz2.BZ2File} now implements all of the @ref{689,,io.BufferedIOBase} API,
except for the @code{detach()} and @code{truncate()} methods.
@end itemize

@node 编码器,collections<7>,bz2<2>,改进的模块<7>
@anchor{whatsnew/3 3 codecs}@anchor{ac0}
@subsubsection 编码器


The @ref{76,,mbcs} codec has been rewritten to handle correctly
@code{replace} and @code{ignore} error handlers on all Windows versions.  The
@ref{76,,mbcs} codec now supports all error handlers, instead of only
@code{replace} to encode and @code{ignore} to decode.

A new Windows-only codec has been added: @code{cp65001} (bpo-13216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13216}). It is the
Windows code page 65001 (Windows UTF-8, @code{CP_UTF8}).  For example, it is used
by @code{sys.stdout} if the console output code page is set to cp65001 (e.g., using
@code{chcp 65001} command).

Multibyte CJK decoders now resynchronize faster.  They only ignore the first
byte of an invalid byte sequence. For example, @code{b'\xff\n'.decode('gb2312',
'replace')} now returns a @code{\n} after the replacement character.

(bpo-12016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12016})

Incremental CJK codec encoders are no longer reset at each call to their
encode() methods. For example:

@example
>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b'@w{'}.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
b'~@{NpJ)l6HK!#~@} Bye.'
@end example

This example gives @code{b'~@{Np~@}~@{J)~@}~@{l6~@}~@{HK~@}~@{!#~@} Bye.'} with older Python
versions.

(bpo-12100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12100})

The @code{unicode_internal} codec has been deprecated.

@node collections<7>,contextlib<5>,编码器,改进的模块<7>
@anchor{whatsnew/3 3 collections}@anchor{ac1}
@subsubsection collections


Addition of a new @ref{5ac,,ChainMap} class to allow treating a
number of mappings as a single unit.  (Written by Raymond Hettinger for
bpo-11089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11089}, made public in bpo-11297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11297}.)

The abstract base classes have been moved in a new @ref{1e,,collections.abc}
module, to better differentiate between the abstract and the concrete
collections classes.  Aliases for ABCs are still present in the
@ref{1d,,collections} module to preserve existing imports.  (bpo-11085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11085})

@c XXX addition of __slots__ to ABCs not recorded here: internal detail

The @ref{ac2,,Counter} class now supports the unary @code{+} and @code{-}
operators, as well as the in-place operators @code{+=}, @code{-=}, @code{|=}, and
@code{&=}.  (Contributed by Raymond Hettinger in bpo-13121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13121}.)

@node contextlib<5>,crypt<2>,collections<7>,改进的模块<7>
@anchor{whatsnew/3 3 contextlib}@anchor{ac3}
@subsubsection contextlib


@ref{487,,ExitStack} now provides a solid foundation for
programmatic manipulation of context managers and similar cleanup
functionality. Unlike the previous @code{contextlib.nested} API (which was
deprecated and removed), the new API is designed to work correctly
regardless of whether context managers acquire their resources in
their @code{__init__} method (for example, file objects) or in their
@code{__enter__} method (for example, synchronisation objects from the
@ref{10b,,threading} module).

(bpo-13585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13585})

@node crypt<2>,curses<4>,contextlib<5>,改进的模块<7>
@anchor{whatsnew/3 3 crypt}@anchor{ac4}
@subsubsection crypt


Addition of salt and modular crypt format (hashing method) and the @ref{48d,,mksalt()}
function to the @ref{28,,crypt} module.

(bpo-10924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10924})

@node curses<4>,datetime<5>,crypt<2>,改进的模块<7>
@anchor{whatsnew/3 3 curses}@anchor{ac5}
@subsubsection curses


@quotation


@itemize *

@item 
If the @ref{2b,,curses} module is linked to the ncursesw library, use Unicode
functions when Unicode strings or characters are passed (e.g.
@code{waddwstr()}), and bytes functions otherwise (e.g. @code{waddstr()}).

@item 
Use the locale encoding instead of @code{utf-8} to encode Unicode strings.

@item 
@code{curses.window} has a new @ref{ac6,,curses.window.encoding} attribute.

@item 
@code{curses.window} 类有一个新的 @ref{ac7,,get_wch()} 方法用来获取一个宽字符。

@item 
@ref{2b,,curses} 模块有一个新的 @ref{ac8,,unget_wch()} 函数用来推入一个宽字符以便下一个 @ref{ac7,,get_wch()} 将返回它。
@end itemize
@end quotation

（由 Iñigo Serna 在 bpo-6755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6755} 中贡献。）

@node datetime<5>,decimal<3>,curses<4>,改进的模块<7>
@anchor{whatsnew/3 3 datetime}@anchor{ac9}
@subsubsection datetime


@quotation


@itemize *

@item 
Equality comparisons between naive and aware @ref{19f,,datetime}
instances now return @ref{497,,False} instead of raising @ref{1ff,,TypeError}
(bpo-15006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15006}).

@item 
New @ref{aca,,datetime.datetime.timestamp()} method: Return POSIX timestamp
corresponding to the @ref{19f,,datetime} instance.

@item 
The @ref{639,,datetime.datetime.strftime()} method supports formatting years
older than 1000.

@item 
The @ref{2d2,,datetime.datetime.astimezone()} method can now be
called without arguments to convert datetime instance to the system
timezone.
@end itemize
@end quotation

@node decimal<3>,email<4>,datetime<5>,改进的模块<7>
@anchor{whatsnew/3 3 decimal}@anchor{acb}@anchor{whatsnew/3 3 new-decimal}@anchor{a68}
@subsubsection decimal



@table @asis

@item bpo-7652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7652} - integrate fast native decimal arithmetic.

C-module and libmpdec written by Stefan Krah.
@end table

The new C version of the decimal module integrates the high speed libmpdec
library for arbitrary precision correctly-rounded decimal floating point
arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.

Performance gains range from 10x for database applications to 100x for
numerically intensive applications. These numbers are expected gains
for standard precisions used in decimal floating point arithmetic. Since
the precision is user configurable, the exact figures may vary. For example,
in integer bignum arithmetic the differences can be significantly higher.

The following table is meant as an illustration. Benchmarks are available
at @indicateurl{http://www.bytereef.org/mpdecimal/quickstart.html}.

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} 
@headitem

@tab

decimal.py

@tab

_decimal

@tab

加速

@item

pi

@tab

42.02秒

@tab

0.345秒

@tab

120倍

@item

telco

@tab

172.19秒

@tab

5.68秒

@tab

30倍

@item

psycopg

@tab

3.57秒

@tab

0.29秒

@tab

12倍

@end multitable

@end quotation

@menu
* 相关特性: 相关特性<2>. 
* API 的变化: API 的变化<2>. 

@end menu

@node 相关特性<2>,API 的变化<2>,,decimal<3>
@anchor{whatsnew/3 3 id1}@anchor{acc}
@subsubsection 相关特性



@itemize *

@item 
The @ref{acd,,FloatOperation} signal optionally enables stricter
semantics for mixing floats and Decimals.

@item 
If Python is compiled without threads, the C version automatically
disables the expensive thread local context machinery. In this case,
the variable @ref{ace,,HAVE_THREADS} is set to @code{False}.
@end itemize

@node API 的变化<2>,,相关特性<2>,decimal<3>
@anchor{whatsnew/3 3 id2}@anchor{acf}
@subsubsection API 的变化



@itemize *

@item 
C模块上下文限制（如下表），具体取决于计算机体系结构：

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

32位

@tab

64位

@item

@code{MAX_PREC}

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@code{MAX_EMAX}

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@code{MIN_EMIN}

@tab

@code{-425000000}

@tab

@code{-999999999999999999}

@end multitable

@end quotation

@item 
In the context templates (@ref{ad0,,DefaultContext},
@ref{ad1,,BasicContext} and @ref{ad2,,ExtendedContext})
the magnitude of @code{Emax} and
@code{Emin} has changed to @code{999999}.

@item 
The @ref{2c7,,Decimal} constructor in decimal.py does not observe
the context limits and converts values with arbitrary exponents or precision
exactly. Since the C version has internal limits, the following scheme is
used: If possible, values are converted exactly, otherwise
@ref{ad3,,InvalidOperation} is raised and the result is NaN. In the
latter case it is always possible to use @ref{ad4,,create_decimal()}
in order to obtain a rounded or inexact value.

@item 
The power function in decimal.py is always correctly-rounded. In the
C version, it is defined in terms of the correctly-rounded
@ref{ad5,,exp()} and @ref{ad6,,ln()} functions,
but the final result is only "almost always correctly rounded".

@item 
In the C version, the context dictionary containing the signals is a
@ref{ad7,,MutableMapping}.  For speed reasons,
@code{flags} and @code{traps} always
refer to the same @ref{ad7,,MutableMapping} that the context
was initialized with. If a new signal dictionary is assigned,
@code{flags} and @code{traps}
are updated with the new values, but they do not reference the RHS
dictionary.

@item 
Pickling a @ref{ad8,,Context} produces a different output in order
to have a common interchange format for the Python and C versions.

@item 
The order of arguments in the @ref{ad8,,Context} constructor has been
changed to match the order displayed by @ref{8c3,,repr()}.

@item 
The @code{watchexp} parameter in the @ref{ad9,,quantize()} method
is deprecated.
@end itemize

@node email<4>,ftplib<2>,decimal<3>,改进的模块<7>
@anchor{whatsnew/3 3 email}@anchor{ada}@anchor{whatsnew/3 3 new-email}@anchor{a69}
@subsubsection email


@menu
* Policy Framework:: 
* Provisional Policy with New Header API:: 
* Other API Changes:: 

@end menu

@node Policy Framework,Provisional Policy with New Header API,,email<4>
@anchor{whatsnew/3 3 policy-framework}@anchor{adb}
@subsubsection Policy Framework


The email package now has a @ref{73,,policy} framework.  A
@ref{adc,,Policy} is an object with several methods and properties
that control how the email package behaves.  The primary policy for Python 3.3
is the @ref{add,,Compat32} policy, which provides backward
compatibility with the email package in Python 3.2.  A @code{policy} can be
specified when an email message is parsed by a @ref{72,,parser}, or when a
@ref{644,,Message} object is created, or when an email is
serialized using a @ref{6c,,generator}.  Unless overridden, a policy passed
to a @code{parser} is inherited by all the @code{Message} object and sub-objects
created by the @code{parser}.  By default a @code{generator} will use the policy of
the @code{Message} object it is serializing.  The default policy is
@ref{643,,compat32}.

The minimum set of controls implemented by all @code{policy} objects are:

@quotation


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

max_line_length

@tab

The maximum length, excluding the linesep character(s),
individual lines may have when a @code{Message} is
serialized.  Defaults to 78.

@item

linesep

@tab

The character used to separate individual lines when a
@code{Message} is serialized.  Defaults to @code{\n}.

@item

cte_type

@tab

@code{7bit} or @code{8bit}.  @code{8bit} applies only to a
@code{Bytes} @code{generator}, and means that non-ASCII may
be used where allowed by the protocol (or where it
exists in the original input).

@item

raise_on_defect

@tab

导致一个 @code{parser} 在遇到缺陷时引发错误而不是将它们添加到 @code{Message} 对象的 @code{defects} 列表。

@end multitable

@end quotation

A new policy instance, with new settings, is created using the
@ref{ade,,clone()} method of policy objects.  @code{clone} takes
any of the above controls as keyword arguments.  Any control not specified in
the call retains its default value.  Thus you can create a policy that uses
@code{\r\n} linesep characters like this:

@example
mypolicy = compat32.clone(linesep='\r\n')
@end example

Policies can be used to make the generation of messages in the format needed by
your application simpler.  Instead of having to remember to specify
@code{linesep='\r\n'} in all the places you call a @code{generator}, you can specify
it once, when you set the policy used by the @code{parser} or the @code{Message},
whichever your program uses to create @code{Message} objects.  On the other hand,
if you need to generate messages in multiple forms, you can still specify the
parameters in the appropriate @code{generator} call.  Or you can have custom
policy instances for your different cases, and pass those in when you create
the @code{generator}.

@node Provisional Policy with New Header API,Other API Changes,Policy Framework,email<4>
@anchor{whatsnew/3 3 provisional-policy-with-new-header-api}@anchor{adf}
@subsubsection Provisional Policy with New Header API


While the policy framework is worthwhile all by itself, the main motivation for
introducing it is to allow the creation of new policies that implement new
features for the email package in a way that maintains backward compatibility
for those who do not use the new policies.  Because the new policies introduce a
new API, we are releasing them in Python 3.3 as a @ref{a6a,,provisional policy}.  Backwards incompatible changes (up to and including
removal of the code) may occur if deemed necessary by the core developers.

The new policies are instances of @ref{ae0,,EmailPolicy},
and add the following additional controls:

@quotation


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

refold_source

@tab

Controls whether or not headers parsed by a
@ref{72,,parser} are refolded by the
@ref{6c,,generator}.  It can be @code{none}, @code{long},
or @code{all}.  The default is @code{long}, which means that
source headers with a line longer than
@code{max_line_length} get refolded.  @code{none} means no
line get refolded, and @code{all} means that all lines
get refolded.

@item

header_factory

@tab

A callable that take a @code{name} and @code{value} and
produces a custom header object.

@end multitable

@end quotation

The @code{header_factory} is the key to the new features provided by the new
policies.  When one of the new policies is used, any header retrieved from
a @code{Message} object is an object produced by the @code{header_factory}, and any
time you set a header on a @code{Message} it becomes an object produced by
@code{header_factory}.  All such header objects have a @code{name} attribute equal
to the header name.  Address and Date headers have additional attributes
that give you access to the parsed data of the header.  This means you can now
do things like this:

@example
>>> m = Message(policy=SMTP)
>>> m['To'] = 'Éric <foo@@example.com>'
>>> m['to']
'Éric <foo@@example.com>'
>>> m['to'].addresses
(Address(display_name='Éric', username='foo', domain='example.com'),)
>>> m['to'].addresses[0].username
'foo'
>>> m['to'].addresses[0].display_name
'Éric'
>>> m['Date'] = email.utils.localtime()
>>> m['Date'].datetime
datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
>>> m['Date']
'Fri, 25 May 2012 21:44:27 -0400'
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
@end example

You will note that the unicode display name is automatically encoded as
@code{utf-8} when the message is serialized, but that when the header is accessed
directly, you get the unicode version.  This eliminates any need to deal with
the @ref{6d,,email.header} @ref{ae1,,decode_header()} or
@ref{ae2,,make_header()} functions.

You can also create addresses from parts:

@example
>>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
...                           Address('Sally', 'sally', 'example.com')]),
...            Address('Bonzo', addr_spec='bonz@@laugh.com')]
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
cc: pals: Bob <bob@@example.com>, Sally <sally@@example.com>;, Bonzo <bonz@@laugh.com>
@end example

Decoding to unicode is done automatically:

@example
>>> m2 = message_from_string(str(m))
>>> m2['to']
'Éric <foo@@example.com>'
@end example

When you parse a message, you can use the @code{addresses} and @code{groups}
attributes of the header objects to access the groups and individual
addresses:

@example
>>> m2['cc'].addresses
(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
>>> m2['cc'].groups
(Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))
@end example

In summary, if you use one of the new policies, header manipulation works the
way it ought to:  your application works with unicode strings, and the email
package transparently encodes and decodes the unicode to and from the RFC
standard Content Transfer Encodings.

@node Other API Changes,,Provisional Policy with New Header API,email<4>
@anchor{whatsnew/3 3 other-api-changes}@anchor{ae3}
@subsubsection Other API Changes


New @ref{ae4,,BytesHeaderParser}, added to the @ref{72,,parser}
module to complement @ref{ae5,,HeaderParser} and complete the Bytes
API.

New utility functions:

@quotation


@itemize *

@item 
@ref{ae6,,format_datetime()}: given a @ref{19f,,datetime},
produce a string formatted for use in an email header.

@item 
@ref{ae7,,parsedate_to_datetime()}: given a date string from
an email header, convert it into an aware @ref{19f,,datetime},
or a naive @ref{19f,,datetime} if the offset is @code{-0000}.

@item 
@ref{ae8,,localtime()}: With no argument, returns the
current local time as an aware @ref{19f,,datetime} using the local
@ref{ae9,,timezone}.  Given an aware @ref{19f,,datetime},
converts it into an aware @ref{19f,,datetime} using the
local @ref{ae9,,timezone}.
@end itemize
@end quotation

@node ftplib<2>,functools<5>,email<4>,改进的模块<7>
@anchor{whatsnew/3 3 ftplib}@anchor{aea}
@subsubsection ftplib



@itemize *

@item 
@ref{1a6,,ftplib.FTP} now accepts a @code{source_address} keyword argument to
specify the @code{(host, port)} to use as the source address in the bind call
when creating the outgoing socket.  (Contributed by Giampaolo Rodolà
in bpo-8594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8594}.)

@item 
The @ref{1a7,,FTP_TLS} class now provides a new
@ref{aeb,,ccc()} function to revert control channel back to
plaintext.  This can be useful to take advantage of firewalls that know how
to handle NAT with non-secure FTP without opening fixed ports.  (Contributed
by Giampaolo Rodolà in bpo-12139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12139}.)

@item 
Added @ref{aec,,ftplib.FTP.mlsd()} method which provides a parsable directory
listing format and deprecates @ref{aed,,ftplib.FTP.nlst()} and
@ref{aee,,ftplib.FTP.dir()}.  (Contributed by Giampaolo Rodolà in bpo-11072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11072}.)
@end itemize

@node functools<5>,gc<5>,ftplib<2>,改进的模块<7>
@anchor{whatsnew/3 3 functools}@anchor{aef}
@subsubsection functools


The @ref{2ff,,functools.lru_cache()} decorator now accepts a @code{typed} keyword
argument (that defaults to @code{False} to ensure that it caches values of
different types that compare equal in separate cache slots.  (Contributed
by Raymond Hettinger in bpo-13227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13227}.)

@node gc<5>,hmac<3>,functools<5>,改进的模块<7>
@anchor{whatsnew/3 3 gc}@anchor{af0}
@subsubsection gc


It is now possible to register callbacks invoked by the garbage collector
before and after collection using the new @ref{af1,,callbacks} list.

@node hmac<3>,http<4>,gc<5>,改进的模块<7>
@anchor{whatsnew/3 3 hmac}@anchor{af2}
@subsubsection hmac


A new @ref{af3,,compare_digest()} function has been added to prevent side
channel attacks on digests through timing analysis.  (Contributed by Nick
Coghlan and Christian Heimes in bpo-15061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15061}.)

@node http<4>,html<2>,hmac<3>,改进的模块<7>
@anchor{whatsnew/3 3 http}@anchor{af4}
@subsubsection http


@ref{af5,,http.server.BaseHTTPRequestHandler} now buffers the headers and writes
them all at once when @ref{af6,,end_headers()} is
called.  A new method @ref{af7,,flush_headers()}
can be used to directly manage when the accumulated headers are sent.
(Contributed by Andrew Schaaf in bpo-3709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3709}.)

@ref{96,,http.server} now produces valid @code{HTML 4.01 strict} output.
(Contributed by Ezio Melotti in bpo-13295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13295}.)

@ref{af8,,http.client.HTTPResponse} now has a
@ref{af9,,readinto()} method, which means it can be used
as an @ref{afa,,io.RawIOBase} class.  (Contributed by John Kuhn in
bpo-13464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13464}.)

@node html<2>,imaplib<3>,http<4>,改进的模块<7>
@anchor{whatsnew/3 3 html}@anchor{afb}
@subsubsection html


@ref{22b,,html.parser.HTMLParser} is now able to parse broken markup without
raising errors, therefore the @emph{strict} argument of the constructor and the
@code{HTMLParseError} exception are now deprecated.
The ability to parse broken markup is the result of a number of bug fixes that
are also available on the latest bug fix releases of Python 2.7/3.2.
(Contributed by Ezio Melotti in bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}, and bpo-14538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14538},
bpo-13993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13993}, bpo-13960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13960}, bpo-13358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13358}, bpo-1745761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1745761},
bpo-755670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=755670}, bpo-13357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13357}, bpo-12629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12629}, bpo-1200313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1200313},
bpo-670664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=670664}, bpo-13273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13273}, bpo-12888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12888}, bpo-7311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7311}.)

A new @ref{afc,,html5} dictionary that maps HTML5 named character
references to the equivalent Unicode character(s) (e.g. @code{html5['gt;'] ==
'>'}) has been added to the @ref{90,,html.entities} module.  The dictionary is
now also used by @ref{22b,,HTMLParser}.  (Contributed by Ezio
Melotti in bpo-11113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11113} and bpo-15156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15156}.)

@node imaplib<3>,inspect<6>,html<2>,改进的模块<7>
@anchor{whatsnew/3 3 imaplib}@anchor{afd}
@subsubsection imaplib


The @ref{1b1,,IMAP4_SSL} constructor now accepts an SSLContext
parameter to control parameters of the secure channel.

（由 Sijin Joseph 在 bpo-8808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8808} 中贡献。）

@node inspect<6>,io<4>,imaplib<3>,改进的模块<7>
@anchor{whatsnew/3 3 inspect}@anchor{afe}
@subsubsection inspect


A new @ref{aff,,getclosurevars()} function has been added. This function
reports the current binding of all names referenced from the function body and
where those names were resolved, making it easier to verify correct internal
state when testing code that relies on stateful closures.

（由  Meador Inge 和 Nick Coghlan 在 bpo-13062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13062} 中贡献。）

A new @ref{b00,,getgeneratorlocals()} function has been added. This
function reports the current binding of local variables in the generator's
stack frame, making it easier to verify correct internal state when testing
generators.

（由 Meador Inge 在 bpo-15153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15153} 中贡献。）

@node io<4>,itertools<3>,inspect<6>,改进的模块<7>
@anchor{whatsnew/3 3 io}@anchor{b01}
@subsubsection io


The @ref{757,,open()} function has a new @code{'x'} mode that can be used to
exclusively create a new file, and raise a @ref{a42,,FileExistsError} if the file
already exists. It is based on the C11 'x' mode to fopen().

（由 David Townshend 在 bpo-12760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12760} 中贡献。）

The constructor of the @ref{6f4,,TextIOWrapper} class has a new
@emph{write_through} optional argument. If @emph{write_through} is @code{True}, calls to
@code{write()} are guaranteed not to be buffered: any data
written on the @ref{6f4,,TextIOWrapper} object is immediately handled to its
underlying binary buffer.

@node itertools<3>,logging<6>,io<4>,改进的模块<7>
@anchor{whatsnew/3 3 itertools}@anchor{b02}
@subsubsection itertools


@ref{315,,accumulate()} now takes an optional @code{func} argument for
providing a user-supplied binary function.

@node logging<6>,math<6>,itertools<3>,改进的模块<7>
@anchor{whatsnew/3 3 logging}@anchor{b03}
@subsubsection logging


The @ref{318,,basicConfig()} function now supports an optional @code{handlers}
argument taking an iterable of handlers to be added to the root logger.

A class level attribute @code{append_nul} has
been added to @ref{b04,,SysLogHandler} to allow control of the
appending of the @code{NUL} (@code{\000}) byte to syslog records, since for some
daemons it is required while for others it is passed through to the log.

@node math<6>,mmap<3>,logging<6>,改进的模块<7>
@anchor{whatsnew/3 3 math}@anchor{b05}
@subsubsection math


The @ref{b1,,math} module has a new function, @ref{b06,,log2()},  which returns
the base-2 logarithm of @emph{x}.

(Written by Mark Dickinson in bpo-11888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11888}.)

@node mmap<3>,multiprocessing<7>,math<6>,改进的模块<7>
@anchor{whatsnew/3 3 mmap}@anchor{b07}
@subsubsection mmap


The @ref{b08,,read()} method is now more compatible with other file-like
objects: if the argument is omitted or specified as @code{None}, it returns the
bytes from the current file position to the end of the mapping.  (Contributed
by Petri Lehtinen in bpo-12021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12021}.)

@node multiprocessing<7>,nntplib<2>,mmap<3>,改进的模块<7>
@anchor{whatsnew/3 3 multiprocessing}@anchor{b09}
@subsubsection multiprocessing


The new @ref{b0a,,multiprocessing.connection.wait()} function allows polling
multiple objects (such as connections, sockets and pipes) with a timeout.
(Contributed by Richard Oudkerk in bpo-12328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12328}.)

@code{multiprocessing.Connection} objects can now be transferred over
multiprocessing connections.
(Contributed by Richard Oudkerk in bpo-4892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4892}.)

@ref{4c1,,multiprocessing.Process} now accepts a @code{daemon} keyword argument
to override the default behavior of inheriting the @code{daemon} flag from
the parent process (bpo-6064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6064}).

New attribute @ref{b0b,,multiprocessing.Process.sentinel} allows a
program to wait on multiple @ref{4c1,,Process} objects at one
time using the appropriate OS primitives (for example, @ref{e5,,select} on
posix systems).

New methods @ref{b0c,,multiprocessing.pool.Pool.starmap()} and
@ref{b0d,,starmap_async()} provide
@ref{b0e,,itertools.starmap()} equivalents to the existing
@ref{b0f,,multiprocessing.pool.Pool.map()} and
@ref{b10,,map_async()} functions.  (Contributed by Hynek
Schlawack in bpo-12708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12708}.)

@node nntplib<2>,os<8>,multiprocessing<7>,改进的模块<7>
@anchor{whatsnew/3 3 nntplib}@anchor{b11}
@subsubsection nntplib


The @ref{1c7,,nntplib.NNTP} class now supports the context management protocol to
unconditionally consume @ref{a7f,,socket.error} exceptions and to close the NNTP
connection when done:

@example
>>> from nntplib import NNTP
>>> with NNTP('news.gmane.org') as n:
...     n.group('gmane.comp.python.committers')
...
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>
@end example

（由 Giampaolo Rodolà 在 bpo-9795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9795} 中贡献。）

@node os<8>,pdb<5>,nntplib<2>,改进的模块<7>
@anchor{whatsnew/3 3 os}@anchor{b12}
@subsubsection os



@itemize *

@item 
The @ref{c4,,os} module has a new @ref{b13,,pipe2()} function that makes it
possible to create a pipe with @ref{aab,,O_CLOEXEC} or
@ref{81c,,O_NONBLOCK} flags set atomically. This is especially useful to
avoid race conditions in multi-threaded programs.

@item 
The @ref{c4,,os} module has a new @ref{46a,,sendfile()} function which provides
an efficient "zero-copy" way for copying data from one file (or socket)
descriptor to another. The phrase "zero-copy" refers to the fact that all of
the copying of data between the two descriptors is done entirely by the
kernel, with no copying of data into userspace buffers. @ref{46a,,sendfile()}
can be used to efficiently copy data from a file on disk to a network socket,
e.g. for downloading a file.

(Patch submitted by Ross Lagerwall and Giampaolo Rodolà in bpo-10882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10882}.)

@item 
To avoid race conditions like symlink attacks and issues with temporary
files and directories, it is more reliable (and also faster) to manipulate
file descriptors instead of file names. Python 3.3 enhances existing functions
and introduces new functions to work on file descriptors (bpo-4761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4761},
bpo-10755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10755} and bpo-14626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14626}).


@itemize -

@item 
The @ref{c4,,os} module has a new @ref{4c3,,fwalk()} function similar to
@ref{751,,walk()} except that it also yields file descriptors referring to the
directories visited. This is especially useful to avoid symlink races.

@item 
The following functions get new optional @emph{dir_fd} (@ref{b14,,paths relative to directory descriptors}) and/or @emph{follow_symlinks} (@ref{b15,,not following symlinks}):
@ref{b16,,access()}, @ref{b17,,chflags()}, @ref{b18,,chmod()}, @ref{b19,,chown()},
@ref{b1a,,link()}, @ref{329,,lstat()}, @ref{b1b,,mkdir()}, @ref{760,,mkfifo()},
@ref{761,,mknod()}, @ref{762,,open()}, @ref{1d2,,readlink()}, @ref{b1c,,remove()},
@ref{b1d,,rename()}, @ref{b1e,,replace()}, @ref{b1f,,rmdir()}, @ref{328,,stat()},
@ref{b20,,symlink()}, @ref{b21,,unlink()}, @ref{b22,,utime()}.  Platform
support for using these parameters can be checked via the sets
@ref{b23,,os.supports_dir_fd} and @code{os.supports_follows_symlinks}.

@item 
The following functions now support a file descriptor for their path argument:
@ref{16e,,chdir()}, @ref{b18,,chmod()}, @ref{b19,,chown()},
@ref{b24,,execve()}, @ref{b25,,listdir()}, @ref{b26,,pathconf()}, @ref{32c,,exists()},
@ref{328,,stat()}, @ref{b27,,statvfs()}, @ref{b22,,utime()}.  Platform support
for this can be checked via the @ref{b28,,os.supports_fd} set.
@end itemize

@item 
@ref{b16,,access()} accepts an @code{effective_ids} keyword argument to turn on
using the effective uid/gid rather than the real uid/gid in the access check.
Platform support for this can be checked via the
@ref{b29,,supports_effective_ids} set.

@item 
The @ref{c4,,os} module has two new functions: @ref{b2a,,getpriority()} and
@ref{b2b,,setpriority()}. They can be used to get or set process
niceness/priority in a fashion similar to @ref{b2c,,os.nice()} but extended to all
processes instead of just the current one.

(Patch submitted by Giampaolo Rodolà in bpo-10784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10784}.)

@item 
The new @ref{b1e,,os.replace()} function allows cross-platform renaming of a
file with overwriting the destination.  With @ref{b1d,,os.rename()}, an existing
destination file is overwritten under POSIX, but raises an error under
Windows.
(Contributed by Antoine Pitrou in bpo-8828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8828}.)

@item 
The stat family of functions (@ref{328,,stat()}, @ref{75c,,fstat()},
and @ref{329,,lstat()}) now support reading a file's timestamps
with nanosecond precision.  Symmetrically, @ref{b22,,utime()}
can now write file timestamps with nanosecond precision.  (Contributed by
Larry Hastings in bpo-14127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14127}.)

@item 
The new @ref{b2d,,os.get_terminal_size()} function queries the size of the
terminal attached to a file descriptor. See also
@ref{b2e,,shutil.get_terminal_size()}.
(Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13609}.)
@end itemize

@c XXX sort out this mess after beta1


@itemize *

@item 
New functions to support Linux extended attributes (bpo-12720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12720}):
@ref{b2f,,getxattr()}, @ref{b30,,listxattr()}, @ref{b31,,removexattr()},
@ref{b32,,setxattr()}.

@item 
New interface to the scheduler. These functions
control how a process is allocated CPU time by the operating system. New
functions:
@ref{b33,,sched_get_priority_max()}, @ref{b34,,sched_get_priority_min()},
@ref{b35,,sched_getaffinity()}, @ref{b36,,sched_getparam()},
@ref{b37,,sched_getscheduler()}, @ref{b38,,sched_rr_get_interval()},
@ref{b39,,sched_setaffinity()}, @ref{b3a,,sched_setparam()},
@ref{b3b,,sched_setscheduler()}, @ref{b3c,,sched_yield()},

@item 
New functions to control the file system:


@itemize *

@item 
@ref{763,,posix_fadvise()}: Announces an intention to access data in a
specific pattern thus allowing the kernel to make optimizations.

@item 
@ref{764,,posix_fallocate()}: Ensures that enough disk space is allocated
for a file.

@item 
@ref{b3d,,sync()}: Force write of everything to disk.
@end itemize

@item 
Additional new  posix functions:


@itemize *

@item 
@ref{b3e,,lockf()}: Apply, test or remove a POSIX lock on an open file descriptor.

@item 
@ref{4c8,,pread()}: Read from a file descriptor at an offset, the file
offset remains unchanged.

@item 
@ref{4cb,,pwrite()}: Write to a file descriptor from an offset, leaving
the file offset unchanged.

@item 
@ref{4c7,,readv()}: Read from a file descriptor into a number of writable buffers.

@item 
@ref{81d,,truncate()}: Truncate the file corresponding to @emph{path}, so that
it is at most @emph{length} bytes in size.

@item 
@ref{769,,waitid()}: Wait for the completion of one or more child processes.

@item 
@ref{4ca,,writev()}: Write the contents of @emph{buffers} to a file descriptor,
where @emph{buffers} is an arbitrary sequence of buffers.

@item 
@ref{b3f,,getgrouplist()} (bpo-9344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9344}): Return list of group ids that
specified user belongs to.
@end itemize

@item 
@ref{b40,,times()} and @ref{b41,,uname()}: Return type changed from a tuple to
a tuple-like object with named attributes.

@item 
Some platforms now support additional constants for the @ref{b42,,lseek()}
function, such as @code{os.SEEK_HOLE} and @code{os.SEEK_DATA}.

@item 
New constants @ref{b43,,RTLD_LAZY}, @ref{b44,,RTLD_NOW},
@ref{b45,,RTLD_GLOBAL}, @ref{b46,,RTLD_LOCAL}, @ref{b47,,RTLD_NODELETE},
@ref{b48,,RTLD_NOLOAD}, and @ref{b49,,RTLD_DEEPBIND} are available on
platforms that support them.   These are for use with the
@ref{b4a,,sys.setdlopenflags()} function, and supersede the similar constants
defined in @ref{2a,,ctypes} and @code{DLFCN}.  (Contributed by Victor Stinner
in bpo-13226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13226}.)

@item 
@ref{b20,,os.symlink()} now accepts (and ignores) the @code{target_is_directory}
keyword argument on non-Windows platforms, to ease cross-platform support.
@end itemize

@node pdb<5>,pickle<5>,os<8>,改进的模块<7>
@anchor{whatsnew/3 3 pdb}@anchor{b4b}
@subsubsection pdb


Tab-completion is now available not only for command names, but also their
arguments.  For example, for the @code{break} command, function and file names
are completed.

（由 Georg Brandl 在 bpo-14210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14210} 中贡献）

@node pickle<5>,pydoc<5>,pdb<5>,改进的模块<7>
@anchor{whatsnew/3 3 pickle}@anchor{b4c}
@subsubsection pickle


@ref{342,,pickle.Pickler} objects now have an optional
@ref{b4d,,dispatch_table} attribute allowing per-pickler
reduction functions to be set.

（由 Richard Oudkerk 在 bpo-14166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14166} 中贡献。）

@node pydoc<5>,re<6>,pickle<5>,改进的模块<7>
@anchor{whatsnew/3 3 pydoc}@anchor{b4e}
@subsubsection pydoc


The Tk GUI and the @code{serve()} function have been removed from the
@ref{d9,,pydoc} module: @code{pydoc -g} and @code{serve()} have been deprecated
in Python 3.2.

@node re<6>,sched,pydoc<5>,改进的模块<7>
@anchor{whatsnew/3 3 re}@anchor{b4f}
@subsubsection re


@ref{206,,str} regular expressions now support @code{\u} and @code{\U} escapes.

（由 Serhiy Storchaka 在 bpo-3665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3665} 中贡献。）

@node sched,select<2>,re<6>,改进的模块<7>
@anchor{whatsnew/3 3 sched}@anchor{b50}
@subsubsection sched



@itemize *

@item 
@ref{b51,,run()} now accepts a @emph{blocking} parameter which when
set to false makes the method execute the scheduled events due to expire
soonest (if any) and then return immediately.
This is useful in case you want to use the @ref{b52,,scheduler} in
non-blocking applications.  (Contributed by Giampaolo Rodolà in bpo-13449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13449}.)

@item 
@ref{b52,,scheduler} class can now be safely used in multi-threaded
environments.  (Contributed by Josiah Carlson and Giampaolo Rodolà in
bpo-8684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8684}.)

@item 
@emph{timefunc} and @emph{delayfunct} parameters of @ref{b52,,scheduler} class
constructor are now optional and defaults to @ref{436,,time.time()} and
@ref{77d,,time.sleep()} respectively.  (Contributed by Chris Clark in
bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)

@item 
@ref{b53,,enter()} and @ref{b54,,enterabs()}
@emph{argument} parameter is now optional.  (Contributed by Chris Clark in
bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)

@item 
@ref{b53,,enter()} and @ref{b54,,enterabs()}
now accept a @emph{kwargs} parameter.  (Contributed by Chris Clark in
bpo-13245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13245}.)
@end itemize

@node select<2>,shlex<3>,sched,改进的模块<7>
@anchor{whatsnew/3 3 select}@anchor{b55}
@subsubsection select


Solaris and derivative platforms have a new class @ref{99b,,select.devpoll}
for high performance asynchronous sockets via @code{/dev/poll}.
(Contributed by Jesús Cea Avión in bpo-6397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6397}.)

@node shlex<3>,shutil<4>,select<2>,改进的模块<7>
@anchor{whatsnew/3 3 shlex}@anchor{b56}
@subsubsection shlex


The previously undocumented helper function @code{quote} from the
@ref{cc,,pipes} modules has been moved to the @ref{e8,,shlex} module and
documented.  @ref{b57,,quote()} properly escapes all characters in a string
that might be otherwise given special meaning by the shell.

@node shutil<4>,signal<4>,shlex<3>,改进的模块<7>
@anchor{whatsnew/3 3 shutil}@anchor{b58}
@subsubsection shutil



@itemize *

@item 
新的函数：


@itemize *

@item 
@ref{b59,,disk_usage()}: provides total, used and free disk space
statistics.  (Contributed by Giampaolo Rodolà in bpo-12442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12442}.)

@item 
@ref{b5a,,chown()}: allows one to change user and/or group of the given
path also specifying the user/group names and not only their numeric
ids.  (Contributed by Sandro Tosi in bpo-12191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12191}.)

@item 
@ref{b2e,,shutil.get_terminal_size()}: returns the size of the terminal window
to which the interpreter is attached.  (Contributed by Zbigniew
Jędrzejewski-Szmek in bpo-13609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13609}.)
@end itemize

@item 
@ref{38b,,copy2()} and @ref{b5b,,copystat()} now preserve file
timestamps with nanosecond precision on platforms that support it.
They also preserve file "extended attributes" on Linux.  (Contributed
by Larry Hastings in bpo-14127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14127} and  bpo-15238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15238}.)

@item 
Several functions now take an optional @code{symlinks} argument: when that
parameter is true, symlinks aren't dereferenced and the operation instead
acts on the symlink itself (or creates one, if relevant).
(Contributed by Hynek Schlawack in bpo-12715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12715}.)

@item 
When copying files to a different file system, @ref{38c,,move()} now
handles symlinks the way the posix @code{mv} command does, recreating the
symlink rather than copying the target file contents.  (Contributed by
Jonathan Niehof in bpo-9993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9993}.)  @ref{38c,,move()} now also returns
the @code{dst} argument as its result.

@item 
@ref{350,,rmtree()} is now resistant to symlink attacks on platforms
which support the new @code{dir_fd} parameter in @ref{762,,os.open()} and
@ref{b21,,os.unlink()}.  (Contributed by Martin von Löwis and Hynek Schlawack
in bpo-4489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4489}.)
@end itemize

@node signal<4>,smtpd<3>,shutil<4>,改进的模块<7>
@anchor{whatsnew/3 3 signal}@anchor{b5c}
@subsubsection signal



@itemize *

@item 
The @ref{ea,,signal} module has new functions:


@itemize *

@item 
@ref{b5d,,pthread_sigmask()}: fetch and/or change the signal mask of the
calling thread (Contributed by Jean-Paul Calderone in bpo-8407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8407});

@item 
@ref{b5e,,pthread_kill()}: send a signal to a thread;

@item 
@ref{b5f,,sigpending()}: examine pending functions;

@item 
@ref{b60,,sigwait()}: 等待一个信号;

@item 
@ref{77c,,sigwaitinfo()}: wait for a signal, returning detailed
information about it;

@item 
@ref{77b,,sigtimedwait()}: like @ref{77c,,sigwaitinfo()} but with a
timeout.
@end itemize

@item 
The signal handler writes the signal number as a single byte instead of
a nul byte into the wakeup file descriptor. So it is possible to wait more
than one signal and know which signals were raised.

@item 
@ref{b61,,signal.signal()} and @ref{b62,,signal.siginterrupt()} raise an OSError,
instead of a RuntimeError: OSError has an errno attribute.
@end itemize

@node smtpd<3>,smtplib<4>,signal<4>,改进的模块<7>
@anchor{whatsnew/3 3 smtpd}@anchor{b63}
@subsubsection smtpd


The @ref{ec,,smtpd} module now supports 
@geindex RFC; RFC 5321
RFC 5321@footnote{https://tools.ietf.org/html/rfc5321.html} (extended SMTP) and 
@geindex RFC; RFC 1870
RFC 1870@footnote{https://tools.ietf.org/html/rfc1870.html}
(size extension).  Per the standard, these extensions are enabled if and only
if the client initiates the session with an @code{EHLO} command.

(Initial @code{ELHO} support by Alberto Trevino.  Size extension by Juhana
Jauhiainen.  Substantial additional work on the patch contributed by Michele
Orrù and Dan Boswell.  bpo-8739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8739})

@node smtplib<4>,socket<8>,smtpd<3>,改进的模块<7>
@anchor{whatsnew/3 3 smtplib}@anchor{b64}
@subsubsection smtplib


The @ref{1df,,SMTP}, @ref{1e0,,SMTP_SSL}, and
@ref{1e1,,LMTP} classes now accept a @code{source_address} keyword argument
to specify the @code{(host, port)} to use as the source address in the bind call
when creating the outgoing socket.  (Contributed by Paulo Scardine in
bpo-11281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11281}.)

@ref{1df,,SMTP} now supports the context management protocol, allowing an
@code{SMTP} instance to be used in a @code{with} statement.  (Contributed
by Giampaolo Rodolà in bpo-11289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11289}.)

The @ref{1e0,,SMTP_SSL} constructor and the @ref{b65,,starttls()}
method now accept an SSLContext parameter to control parameters of the secure
channel.  (Contributed by Kasun Herath in bpo-8809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8809}.)

@node socket<8>,socketserver<3>,smtplib<4>,改进的模块<7>
@anchor{whatsnew/3 3 socket}@anchor{b66}
@subsubsection socket



@itemize *

@item 
The @ref{771,,socket} class now exposes additional methods to process
ancillary data when supported by the underlying platform:


@itemize *

@item 
@ref{779,,sendmsg()}

@item 
@ref{776,,recvmsg()}

@item 
@ref{b67,,recvmsg_into()}
@end itemize

(Contributed by David Watson in bpo-6560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6560}, based on an earlier patch by
Heiko Wundram)

@item 
The @ref{771,,socket} class now supports the PF_CAN protocol family
(@indicateurl{https://en.wikipedia.org/wiki/Socketcan}), on Linux
(@indicateurl{https://lwn.net/Articles/253425}).

(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in bpo-10141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10141}.)

@item 
The @ref{771,,socket} class now supports the PF_RDS protocol family
(@indicateurl{https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets} and
@indicateurl{https://oss.oracle.com/projects/rds/}).

@item 
The @ref{771,,socket} class now supports the @code{PF_SYSTEM} protocol
family on OS X.  (Contributed by Michael Goderbauer in bpo-13777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13777}.)

@item 
New function @ref{b68,,sethostname()} allows the hostname to be set
on unix systems if the calling process has sufficient privileges.
(Contributed by Ross Lagerwall in bpo-10866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10866}.)
@end itemize

@node socketserver<3>,sqlite3<5>,socket<8>,改进的模块<7>
@anchor{whatsnew/3 3 socketserver}@anchor{b69}
@subsubsection socketserver


@ref{b6a,,BaseServer} now has an overridable method
@ref{b6b,,service_actions()} that is called by the
@ref{b6c,,serve_forever()} method in the service loop.
@ref{4e4,,ForkingMixIn} now uses this to clean up zombie
child processes.  (Contributed by Justin Warkentin in bpo-11109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11109}.)

@node sqlite3<5>,ssl<8>,socketserver<3>,改进的模块<7>
@anchor{whatsnew/3 3 sqlite3}@anchor{b6d}
@subsubsection sqlite3


New @ref{4e7,,sqlite3.Connection} method
@ref{b6e,,set_trace_callback()} can be used to capture a trace of
all sql commands processed by sqlite.  (Contributed by Torsten Landschoff
in bpo-11688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11688}.)

@node ssl<8>,stat<2>,sqlite3<5>,改进的模块<7>
@anchor{whatsnew/3 3 ssl}@anchor{b6f}
@subsubsection ssl



@itemize *

@item 
The @ref{f3,,ssl} module has two new random generation functions:


@itemize *

@item 
@ref{b70,,RAND_bytes()}: generate cryptographically strong
pseudo-random bytes.

@item 
@ref{b71,,RAND_pseudo_bytes()}: generate pseudo-random bytes.
@end itemize

（由 Victor Stinner 在 bpo-12049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12049} 中贡献。）

@item 
The @ref{f3,,ssl} module now exposes a finer-grained exception hierarchy
in order to make it easier to inspect the various kinds of errors.
(Contributed by Antoine Pitrou in bpo-11183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11183}.)

@item 
@ref{b72,,load_cert_chain()} now accepts a @emph{password} argument
to be used if the private key is encrypted.
(Contributed by Adam Simpkins in bpo-12803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12803}.)

@item 
Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is
now supported through the @ref{b73,,load_dh_params()} and
@ref{b74,,set_ecdh_curve()} methods.
(Contributed by Antoine Pitrou in bpo-13626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13626} and bpo-13627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13627}.)

@item 
SSL sockets have a new @ref{b75,,get_channel_binding()} method
allowing the implementation of certain authentication mechanisms such as
SCRAM-SHA-1-PLUS.  (Contributed by Jacek Konieczny in bpo-12551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12551}.)

@item 
You can query the SSL compression algorithm used by an SSL socket, thanks
to its new @ref{b76,,compression()} method.  The new attribute
@ref{b77,,OP_NO_COMPRESSION} can be used to disable compression.
(Contributed by Antoine Pitrou in bpo-13634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13634}.)

@item 
Support has been added for the Next Protocol Negotiation extension using
the @ref{b78,,ssl.SSLContext.set_npn_protocols()} method.
(Contributed by Colin Marc in bpo-14204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14204}.)

@item 
SSL errors can now be introspected more easily thanks to
@ref{b79,,library} and @ref{b7a,,reason} attributes.
(Contributed by Antoine Pitrou in bpo-14837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14837}.)

@item 
The @ref{b7b,,get_server_certificate()} function now supports IPv6.
(Contributed by Charles-François Natali in bpo-11811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11811}.)

@item 
New attribute @ref{b7c,,OP_CIPHER_SERVER_PREFERENCE} allows setting
SSLv3 server sockets to use the server's cipher ordering preference rather
than the client's (bpo-13635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13635}).
@end itemize

@node stat<2>,struct<3>,ssl<8>,改进的模块<7>
@anchor{whatsnew/3 3 stat}@anchor{b7d}
@subsubsection stat


The undocumented tarfile.filemode function has been moved to
@ref{b7e,,stat.filemode()}. It can be used to convert a file's mode to a string of
the form '-rwxrwxrwx'.

（由 Giampaolo Rodolà 在 bpo-14807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14807} 中贡献。）

@node struct<3>,subprocess<5>,stat<2>,改进的模块<7>
@anchor{whatsnew/3 3 struct}@anchor{b7f}
@subsubsection struct


The @ref{f8,,struct} module now supports @code{ssize_t} and @code{size_t} via the
new codes @code{n} and @code{N}, respectively.  (Contributed by Antoine Pitrou
in bpo-3163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3163}.)

@node subprocess<5>,sys<8>,struct<3>,改进的模块<7>
@anchor{whatsnew/3 3 subprocess}@anchor{b80}
@subsubsection subprocess


Command strings can now be bytes objects on posix platforms.  (Contributed by
Victor Stinner in bpo-8513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8513}.)

A new constant @ref{b81,,DEVNULL} allows suppressing output in a
platform-independent fashion.  (Contributed by Ross Lagerwall in
bpo-5870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5870}.)

@node sys<8>,tarfile<5>,subprocess<5>,改进的模块<7>
@anchor{whatsnew/3 3 sys}@anchor{b82}
@subsubsection sys


The @ref{fd,,sys} module has a new @ref{b83,,thread_info} @ref{b84,,named tuple} holding information about the thread implementation
(bpo-11223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11223}).

@node tarfile<5>,tempfile,sys<8>,改进的模块<7>
@anchor{whatsnew/3 3 tarfile}@anchor{b85}
@subsubsection tarfile


@ref{101,,tarfile} now supports @code{lzma} encoding via the @ref{ad,,lzma} module.
(Contributed by Lars Gustäbel in bpo-5689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5689}.)

@node tempfile,textwrap<2>,tarfile<5>,改进的模块<7>
@anchor{whatsnew/3 3 tempfile}@anchor{b86}
@subsubsection tempfile


@ref{b87,,tempfile.SpooledTemporaryFile}'s
@code{truncate()} method now accepts
a @code{size} parameter.  (Contributed by Ryan Kelly in bpo-9957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9957}.)

@node textwrap<2>,threading<5>,tempfile,改进的模块<7>
@anchor{whatsnew/3 3 textwrap}@anchor{b88}
@subsubsection textwrap


The @ref{10a,,textwrap} module has a new @ref{b89,,indent()} that makes
it straightforward to add a common prefix to selected lines in a block
of text  (bpo-13857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13857}).

@node threading<5>,time<6>,textwrap<2>,改进的模块<7>
@anchor{whatsnew/3 3 threading}@anchor{b8a}
@subsubsection threading


@ref{b8b,,threading.Condition}, @ref{b8c,,threading.Semaphore},
@ref{b8d,,threading.BoundedSemaphore}, @ref{b8e,,threading.Event}, and
@ref{b8f,,threading.Timer}, all of which used to be factory functions returning a
class instance, are now classes and may be subclassed.  (Contributed by Éric
Araujo in bpo-10968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10968}.)

The @ref{21b,,threading.Thread} constructor now accepts a @code{daemon} keyword
argument to override the default behavior of inheriting the @code{daemon} flag
value from the parent thread (bpo-6064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6064}).

The formerly private function @code{_thread.get_ident} is now available as the
public function @ref{b90,,threading.get_ident()}.  This eliminates several cases of
direct access to the @code{_thread} module in the stdlib.  Third party code that
used @code{_thread.get_ident} should likewise be changed to use the new public
interface.

@node time<6>,types<4>,threading<5>,改进的模块<7>
@anchor{whatsnew/3 3 time}@anchor{b91}
@subsubsection time


The 
@geindex Python 提高建议; PEP 418
PEP 418@footnote{https://www.python.org/dev/peps/pep-0418} added new functions to the @ref{10c,,time} module:


@itemize *

@item 
@ref{b92,,get_clock_info()}: Get information on a clock.

@item 
@ref{868,,monotonic()}: Monotonic clock (cannot go backward), not affected
by system clock updates.

@item 
@ref{3d4,,perf_counter()}: Performance counter with the highest available
resolution to measure a short duration.

@item 
@ref{3d5,,process_time()}: Sum of the system and user CPU time of the
current process.
@end itemize

Other new functions:


@itemize *

@item 
@ref{b93,,clock_getres()}, @ref{b94,,clock_gettime()} and
@ref{b95,,clock_settime()} functions with @code{CLOCK_xxx} constants.
(Contributed by Victor Stinner in bpo-10278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10278}.)
@end itemize

To improve cross platform consistency, @ref{77d,,sleep()} now raises a
@ref{16d,,ValueError} when passed a negative sleep value.  Previously this was an
error on posix, but produced an infinite sleep on Windows.

@node types<4>,unittest<5>,time<6>,改进的模块<7>
@anchor{whatsnew/3 3 types}@anchor{b96}
@subsubsection types


Add a new @ref{b97,,types.MappingProxyType} class: Read-only proxy of a mapping.
(bpo-14386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14386})

The new functions @ref{b98,,types.new_class()} and @ref{b99,,types.prepare_class()} provide support
for 
@geindex Python 提高建议; PEP 3115
PEP 3115@footnote{https://www.python.org/dev/peps/pep-3115} compliant dynamic type creation. (bpo-14588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14588})

@node unittest<5>,urllib<3>,types<4>,改进的模块<7>
@anchor{whatsnew/3 3 unittest}@anchor{b9a}
@subsubsection unittest


@ref{b9b,,assertRaises()}, @ref{b9c,,assertRaisesRegex()}, @ref{b9d,,assertWarns()}, and
@ref{b9e,,assertWarnsRegex()} now accept a keyword argument @emph{msg} when used as
context managers.  (Contributed by Ezio Melotti and Winston Ewert in
bpo-10775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10775}.)

@ref{b9f,,unittest.TestCase.run()} now returns the @ref{ba0,,TestResult}
object.

@node urllib<3>,webbrowser,unittest<5>,改进的模块<7>
@anchor{whatsnew/3 3 urllib}@anchor{ba1}
@subsubsection urllib


The @ref{9e5,,Request} class, now accepts a @emph{method} argument
used by @ref{ba2,,get_method()} to determine what HTTP method
should be used.  For example, this will send a @code{'HEAD'} request:

@example
>>> urlopen(Request('https://www.python.org', method='HEAD'))
@end example

(bpo-1673007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1673007})

@node webbrowser,xml etree ElementTree,urllib<3>,改进的模块<7>
@anchor{whatsnew/3 3 webbrowser}@anchor{ba3}
@subsubsection webbrowser


The @ref{132,,webbrowser} module supports more "browsers": Google Chrome (named
@code{chrome}, @code{chromium}, @code{chrome-browser} or
@code{chromium-browser} depending on the version and operating system),
and the generic launchers @code{xdg-open}, from the FreeDesktop.org
project, and @code{gvfs-open}, which is the default URI handler for GNOME
3.  (The former contributed by Arnaud Calmettes in bpo-13620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13620}, the latter
by Matthias Klose in bpo-14493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14493}.)

@node xml etree ElementTree,zlib<2>,webbrowser,改进的模块<7>
@anchor{whatsnew/3 3 xml-etree-elementtree}@anchor{ba4}
@subsubsection xml.etree.ElementTree


The @ref{140,,xml.etree.ElementTree} module now imports its C accelerator by
default; there is no longer a need to explicitly import
@code{xml.etree.cElementTree} (this module stays for backwards compatibility,
but is now deprecated).  In addition,  the @code{iter} family of methods of
@ref{21e,,Element} has been optimized (rewritten in C).
The module's documentation has also been greatly improved with added examples
and a more detailed reference.

@node zlib<2>,,xml etree ElementTree,改进的模块<7>
@anchor{whatsnew/3 3 zlib}@anchor{ba5}
@subsubsection zlib


New attribute @ref{ba6,,zlib.Decompress.eof} makes it possible to distinguish
between a properly-formed compressed stream and an incomplete or truncated one.
(Contributed by Nadeem Vawda in bpo-12646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12646}.)

New attribute @ref{ba7,,zlib.ZLIB_RUNTIME_VERSION} reports the version string of
the underlying @code{zlib} library that is loaded at runtime.  (Contributed by
Torsten Landschoff in bpo-12306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12306}.)

@node 性能优化<6>,构建和 C API 的改变<4>,改进的模块<7>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 optimizations}@anchor{ba8}
@subsection 性能优化


Major performance enhancements have been added:


@itemize *

@item 
Thanks to 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393}, some operations on Unicode strings have been optimized:


@itemize *

@item 
the memory footprint is divided by 2 to 4 depending on the text

@item 
encode an ASCII string to UTF-8 doesn't need to encode characters anymore,
the UTF-8 representation is shared with the ASCII representation

@item 
the UTF-8 encoder has been optimized

@item 
repeating a single ASCII letter and getting a substring of an ASCII string
is 4 times faster
@end itemize

@item 
UTF-8 is now 2x to 4x faster.  UTF-16 encoding is now up to 10x faster.

(Contributed by Serhiy Storchaka, bpo-14624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14624}, bpo-14738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14738} and
bpo-15026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15026}.)
@end itemize

@node 构建和 C API 的改变<4>,弃用<6>,性能优化<6>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 build-and-c-api-changes}@anchor{a71}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
新的 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} 相关功能：


@itemize *

@item 
@ref{ba9,,PyMemoryView_FromMemory()}
@end itemize

@item 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 添加了新的 Unicode 类型，宏和函数


@itemize *

@item 
高阶 API


@itemize *

@item 
@ref{baa,,PyUnicode_CopyCharacters()}

@item 
@ref{54b,,PyUnicode_FindChar()}

@item 
@ref{bab,,PyUnicode_GetLength()}, @ref{bac,,PyUnicode_GET_LENGTH}

@item 
@ref{bad,,PyUnicode_New()}

@item 
@ref{bae,,PyUnicode_Substring()}

@item 
@ref{baf,,PyUnicode_ReadChar()}, @ref{bb0,,PyUnicode_WriteChar()}
@end itemize

@item 
低阶 API:


@itemize *

@item 
@ref{bb1,,Py_UCS1}, @ref{bb2,,Py_UCS2}, @ref{bb3,,Py_UCS4} 类型

@item 
@ref{bb4,,PyASCIIObject} 和 @ref{bb5,,PyCompactUnicodeObject} 结构

@item 
@ref{bb6,,PyUnicode_READY}

@item 
@ref{bb7,,PyUnicode_FromKindAndData()}

@item 
@ref{bb8,,PyUnicode_AsUCS4()}, @ref{bb9,,PyUnicode_AsUCS4Copy()}

@item 
@ref{bba,,PyUnicode_DATA}, @ref{bbb,,PyUnicode_1BYTE_DATA},
@ref{bbc,,PyUnicode_2BYTE_DATA}, @ref{bbd,,PyUnicode_4BYTE_DATA}

@item 
@ref{bbe,,PyUnicode_KIND} 使用 @code{PyUnicode_Kind} 枚举: @ref{bbf,,PyUnicode_WCHAR_KIND}, @ref{bc0,,PyUnicode_1BYTE_KIND}, @ref{bc1,,PyUnicode_2BYTE_KIND}, @ref{bc2,,PyUnicode_4BYTE_KIND}

@item 
@ref{bc3,,PyUnicode_READ}, @ref{bc4,,PyUnicode_READ_CHAR}, @ref{bc5,,PyUnicode_WRITE}

@item 
@ref{bc6,,PyUnicode_MAX_CHAR_VALUE}
@end itemize
@end itemize

@item 
@ref{39b,,PyArg_ParseTuple} 现在接受 @code{c} 格式的 @ref{173,,bytearray} (bpo-12380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12380})。
@end itemize

@node 弃用<6>,移植到 Python 3 3,构建和 C API 的改变<4>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 deprecated}@anchor{bc7}
@subsection 弃用


@menu
* 不支持的操作系统: 不支持的操作系统<2>. 
* 已弃用的 Python 模块、函数和方法: 已弃用的 Python 模块、函数和方法<4>. 
* 已弃用的 C API 函数和类型: 已弃用的 C API 函数和类型<3>. 
* 弃用的功能:: 

@end menu

@node 不支持的操作系统<2>,已弃用的 Python 模块、函数和方法<4>,,弃用<6>
@anchor{whatsnew/3 3 unsupported-operating-systems}@anchor{bc8}
@subsubsection 不支持的操作系统


由于缺少维护人员，不再支持 OS/2 和 VMS 系统 。

由于维护负担，将 @code{COMSPEC} 设置为 @code{command.com} 的 Windows平台（含Windows 2000）不再受支持。

OSF支持在3.2中被弃用，现在已经被完全删除。

@node 已弃用的 Python 模块、函数和方法<4>,已弃用的 C API 函数和类型<3>,不支持的操作系统<2>,弃用<6>
@anchor{whatsnew/3 3 deprecated-python-modules-functions-and-methods}@anchor{bc9}
@subsubsection 已弃用的 Python 模块、函数和方法



@itemize *

@item 
Passing a non-empty string to @code{object.__format__()} is deprecated, and
will produce a @ref{1ff,,TypeError} in Python 3.4 (bpo-9856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9856}).

@item 
The @code{unicode_internal} codec has been deprecated because of the
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393}, use UTF-8, UTF-16 (@code{utf-16-le} or @code{utf-16-be}), or UTF-32
(@code{utf-32-le} or @code{utf-32-be})

@item 
@ref{aed,,ftplib.FTP.nlst()} and @ref{aee,,ftplib.FTP.dir()}: use
@ref{aec,,ftplib.FTP.mlsd()}

@item 
@code{platform.popen()}: use the @ref{f9,,subprocess} module. Check especially
the @ref{bca,,使用 subprocess 模块替换旧函数} section (bpo-11377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11377}).

@item 
bpo-13374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13374}: The Windows bytes API has been deprecated in the @ref{c4,,os}
module. Use Unicode filenames, instead of bytes filenames, to not depend on
the ANSI code page anymore and to support any filename.

@item 
bpo-13988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13988}: The @code{xml.etree.cElementTree} module is deprecated.  The
accelerator is used automatically whenever available.

@item 
The behaviour of @code{time.clock()} depends on the platform: use the new
@ref{3d4,,time.perf_counter()} or @ref{3d5,,time.process_time()} function instead,
depending on your requirements, to have a well defined behaviour.

@item 
The @code{os.stat_float_times()} function is deprecated.

@item 
@ref{3,,abc} module:


@itemize *

@item 
@ref{ab5,,abc.abstractproperty} has been deprecated, use @ref{30f,,property}
with @ref{ab6,,abc.abstractmethod()} instead.

@item 
@ref{ab7,,abc.abstractclassmethod} has been deprecated, use
@ref{310,,classmethod} with @ref{ab6,,abc.abstractmethod()} instead.

@item 
@ref{ab8,,abc.abstractstaticmethod} has been deprecated, use
@ref{311,,staticmethod} with @ref{ab6,,abc.abstractmethod()} instead.
@end itemize

@item 
@ref{9a,,importlib} package:


@itemize *

@item 
@ref{bcb,,importlib.abc.SourceLoader.path_mtime()} is now deprecated in favour of
@ref{bcc,,importlib.abc.SourceLoader.path_stats()} as bytecode files now store
both the modification time and size of the source file the bytecode file was
compiled from.
@end itemize
@end itemize

@node 已弃用的 C API 函数和类型<3>,弃用的功能,已弃用的 Python 模块、函数和方法<4>,弃用<6>
@anchor{whatsnew/3 3 deprecated-functions-and-types-of-the-c-api}@anchor{bcd}
@subsubsection 已弃用的 C API 函数和类型


@ref{bce,,Py_UNICODE} 已经在 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 弃用，并将于 Python 4 中移除。所有使用此类型的函数都已弃用：

Unicode functions and methods using @ref{bce,,Py_UNICODE} and
@ref{bce,,Py_UNICODE*} types:


@itemize *

@item 
@ref{264,,PyUnicode_FromUnicode}: 使用 @ref{bcf,,PyUnicode_FromWideChar()} 或 @ref{bb7,,PyUnicode_FromKindAndData()}

@item 
@ref{bd0,,PyUnicode_AS_UNICODE}, @ref{265,,PyUnicode_AsUnicode()}, @ref{266,,PyUnicode_AsUnicodeAndSize()}: 使用 @ref{544,,PyUnicode_AsWideCharString()}

@item 
@ref{bd1,,PyUnicode_AS_DATA}: 使用 @ref{bba,,PyUnicode_DATA} 以及 @ref{bc3,,PyUnicode_READ}  和 @ref{bc5,,PyUnicode_WRITE}

@item 
@ref{bd2,,PyUnicode_GET_SIZE}, @ref{bd3,,PyUnicode_GetSize()}: 使用 @ref{bac,,PyUnicode_GET_LENGTH} 或 @ref{bab,,PyUnicode_GetLength()}

@item 
@ref{bd4,,PyUnicode_GET_DATA_SIZE}: 使用 @code{PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)} (仅适用于现成的字符串)

@item 
@ref{bd5,,PyUnicode_AsUnicodeCopy()}: 使用 @ref{bb9,,PyUnicode_AsUCS4Copy()} 或 @ref{544,,PyUnicode_AsWideCharString()}

@item 
@code{PyUnicode_GetMax()}
@end itemize

Functions and macros manipulating Py_UNICODE* strings:


@itemize *

@item 
@code{Py_UNICODE_strlen}: 使用 @ref{bab,,PyUnicode_GetLength()} 或 @ref{bac,,PyUnicode_GET_LENGTH}

@item 
@code{Py_UNICODE_strcat}: 使用 @ref{baa,,PyUnicode_CopyCharacters()} 或 @ref{8c2,,PyUnicode_FromFormat()}

@item 
@code{Py_UNICODE_strcpy}, @code{Py_UNICODE_strncpy}, @code{Py_UNICODE_COPY}: 使用 @ref{baa,,PyUnicode_CopyCharacters()} 或 @ref{bae,,PyUnicode_Substring()}

@item 
@code{Py_UNICODE_strcmp}: 使用 @ref{bd6,,PyUnicode_Compare()}

@item 
@code{Py_UNICODE_strncmp}: 使用 @ref{273,,PyUnicode_Tailmatch()}

@item 
@code{Py_UNICODE_strchr}, @code{Py_UNICODE_strrchr}: 使用 @ref{54b,,PyUnicode_FindChar()}

@item 
@code{Py_UNICODE_FILL}: 使用 @ref{bd7,,PyUnicode_Fill()}

@item 
@code{Py_UNICODE_MATCH}
@end itemize

编码器:


@itemize *

@item 
@ref{bd8,,PyUnicode_Encode()}: 使用 @code{PyUnicode_AsEncodedObject()}

@item 
@ref{bd9,,PyUnicode_EncodeUTF7()}

@item 
@ref{bda,,PyUnicode_EncodeUTF8()}: 使用 @ref{537,,PyUnicode_AsUTF8()} 或 @ref{bdb,,PyUnicode_AsUTF8String()}

@item 
@ref{bdc,,PyUnicode_EncodeUTF32()}

@item 
@ref{bdd,,PyUnicode_EncodeUTF16()}

@item 
@ref{bde,,PyUnicode_EncodeUnicodeEscape()} use
@ref{bdf,,PyUnicode_AsUnicodeEscapeString()}

@item 
@ref{be0,,PyUnicode_EncodeRawUnicodeEscape()} use
@ref{be1,,PyUnicode_AsRawUnicodeEscapeString()}

@item 
@ref{be2,,PyUnicode_EncodeLatin1()}: 使用 @ref{be3,,PyUnicode_AsLatin1String()}

@item 
@ref{be4,,PyUnicode_EncodeASCII()}: 使用 @ref{be5,,PyUnicode_AsASCIIString()}

@item 
@ref{be6,,PyUnicode_EncodeCharmap()}

@item 
@ref{be7,,PyUnicode_TranslateCharmap()}

@item 
@ref{be8,,PyUnicode_EncodeMBCS()}: 使用 @ref{be9,,PyUnicode_AsMBCSString()} 或 @ref{bea,,PyUnicode_EncodeCodePage()} (和 @code{CP_ACP} code_page)

@item 
@code{PyUnicode_EncodeDecimal()},
@ref{beb,,PyUnicode_TransformDecimalToASCII()}
@end itemize

@node 弃用的功能,,已弃用的 C API 函数和类型<3>,弃用<6>
@anchor{whatsnew/3 3 deprecated-features}@anchor{bec}
@subsubsection 弃用的功能


The @ref{6,,array} module's @code{'u'} format code is now deprecated and will be
removed in Python 4 together with the rest of the (@ref{bce,,Py_UNICODE}) API.

@node 移植到 Python 3 3,,弃用<6>,Python 3 3 有什么新变化
@anchor{whatsnew/3 3 porting-to-python-3-3}@anchor{bed}
@subsection 移植到 Python 3.3


本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

@menu
* Porting Python code:: 
* Porting C code:: 
* Building C extensions:: 
* Command Line Switch Changes:: 

@end menu

@node Porting Python code,Porting C code,,移植到 Python 3 3
@anchor{whatsnew/3 3 porting-python-code}@anchor{a98}@anchor{whatsnew/3 3 portingpythoncode}@anchor{bee}
@subsubsection Porting Python code



@itemize *

@item 
Hash randomization is enabled by default. Set the 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED}
environment variable to @code{0} to disable hash randomization. See also the
@ref{455,,object.__hash__()} method.

@item 
bpo-12326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12326}: On Linux, sys.platform doesn't contain the major version
anymore. It is now always 'linux', instead of 'linux2' or 'linux3' depending
on the Linux version used to build Python. Replace sys.platform == 'linux2'
with sys.platform.startswith('linux'), or directly sys.platform == 'linux' if
you don't need to support older Python versions.

@item 
bpo-13847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13847}, bpo-14180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14180}: @ref{10c,,time} and @ref{30,,datetime}:
@ref{a4a,,OverflowError} is now raised instead of @ref{16d,,ValueError} if a
timestamp is out of range. @ref{30b,,OSError} is now raised if C functions
@code{gmtime()} or @code{localtime()} failed.

@item 
The default finders used by import now utilize a cache of what is contained
within a specific directory. If you create a Python source file or sourceless
bytecode file, make sure to call @ref{59f,,importlib.invalidate_caches()} to clear
out the cache for the finders to notice the new file.

@item 
@ref{16c,,ImportError} now uses the full name of the module that was attempted to
be imported. Doctests that check ImportErrors' message will need to be
updated to use the full name of the module instead of just the tail of the
name.

@item 
The @emph{index} argument to @ref{16b,,__import__()} now defaults to 0 instead of -1
and no longer support negative values. It was an oversight when 
@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328} was
implemented that the default value remained -1. If you need to continue to
perform a relative import followed by an absolute import, then perform the
relative import using an index of 1, followed by another import using an
index of 0. It is preferred, though, that you use
@ref{bef,,importlib.import_module()} rather than call @ref{16b,,__import__()} directly.

@item 
@ref{16b,,__import__()} no longer allows one to use an index value other than 0
for top-level modules. E.g. @code{__import__('sys', level=1)} is now an error.

@item 
Because @ref{6e7,,sys.meta_path} and @ref{a46,,sys.path_hooks} now have finders on
them by default, you will most likely want to use @code{list.insert()} instead
of @code{list.append()} to add to those lists.

@item 
Because @code{None} is now inserted into @ref{5a0,,sys.path_importer_cache}, if you
are clearing out entries in the dictionary of paths that do not have a
finder, you will need to remove keys paired with values of @code{None} @strong{and}
@ref{aa4,,imp.NullImporter} to be backwards-compatible. This will lead to extra
overhead on older versions of Python that re-insert @code{None} into
@ref{5a0,,sys.path_importer_cache} where it represents the use of implicit
finders, but semantically it should not change anything.

@item 
@ref{a9e,,importlib.abc.Finder} no longer specifies a @cite{find_module()} abstract
method that must be implemented. If you were relying on subclasses to
implement that method, make sure to check for the method's existence first.
You will probably want to check for @cite{find_loader()} first, though, in the
case of working with @ref{a9b,,path entry finders}.

@item 
@ref{cd,,pkgutil} has been converted to use @ref{9a,,importlib} internally. This
eliminates many edge cases where the old behaviour of the 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} import
emulation failed to match the behaviour of the real import system. The
import emulation itself is still present, but is now deprecated. The
@ref{bf0,,pkgutil.iter_importers()} and @ref{58e,,pkgutil.walk_packages()} functions
special case the standard import hooks so they are still supported even
though they do not provide the non-standard @code{iter_modules()} method.

@item 
A longstanding RFC-compliance bug (bpo-1079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1079}) in the parsing done by
@ref{ae1,,email.header.decode_header()} has been fixed.  Code that uses the
standard idiom to convert encoded headers into unicode
(@code{str(make_header(decode_header(h))}) will see no change, but code that
looks at the individual tuples returned by decode_header will see that
whitespace that precedes or follows @code{ASCII} sections is now included in the
@code{ASCII} section.  Code that builds headers using @code{make_header} should
also continue to work without change, since @code{make_header} continues to add
whitespace between @code{ASCII} and non-@code{ASCII} sections if it is not already
present in the input strings.

@item 
@ref{bf1,,email.utils.formataddr()} now does the correct content transfer
encoding when passed non-@code{ASCII} display names.  Any code that depended on
the previous buggy behavior that preserved the non-@code{ASCII} unicode in the
formatted output string will need to be changed (bpo-1690608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1690608}).

@item 
@ref{bf2,,poplib.POP3.quit()} may now raise protocol errors like all other
@code{poplib} methods.  Code that assumes @code{quit} does not raise
@ref{bf3,,poplib.error_proto} errors may need to be changed if errors on @code{quit}
are encountered by a particular application (bpo-11291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11291}).

@item 
The @code{strict} argument to @ref{bf4,,email.parser.Parser}, deprecated since
Python 2.4, has finally been removed.

@item 
The deprecated method @code{unittest.TestCase.assertSameElements} has been
removed.

@item 
The deprecated variable @code{time.accept2dyear} has been removed.

@item 
被弃用的 @code{Context._clamp} 属性已从 @ref{35,,decimal} 模块中移除。 在此之前它已被公有属性 @code{clamp} 取代。 （参见 bpo-8540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8540}。）

@item 
The undocumented internal helper class @code{SSLFakeFile} has been removed
from @ref{ed,,smtplib}, since its functionality has long been provided directly
by @ref{bf5,,socket.socket.makefile()}.

@item 
Passing a negative value to @ref{77d,,time.sleep()} on Windows now raises an
error instead of sleeping forever.  It has always raised an error on posix.

@item 
The @code{ast.__version__} constant has been removed.  If you need to
make decisions affected by the AST version, use @ref{bf6,,sys.version_info}
to make the decision.

@item 
Code that used to work around the fact that the @ref{10b,,threading} module used
factory functions by subclassing the private classes will need to change to
subclass the now-public classes.

@item 
The undocumented debugging machinery in the threading module has been
removed, simplifying the code.  This should have no effect on production
code, but is mentioned here in case any application debug frameworks were
interacting with it (bpo-13550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13550}).
@end itemize

@node Porting C code,Building C extensions,Porting Python code,移植到 Python 3 3
@anchor{whatsnew/3 3 porting-c-code}@anchor{a72}
@subsubsection Porting C code



@itemize *

@item 
In the course of changes to the buffer API the undocumented
@code{smalltable} member of the
@ref{bf7,,Py_buffer} structure has been removed and the
layout of the @code{PyMemoryViewObject} has changed.

All extensions relying on the relevant parts in @code{memoryobject.h}
or @code{object.h} must be rebuilt.

@item 
Due to @ref{a66,,PEP 393}, the @ref{bce,,Py_UNICODE} type and all
functions using this type are deprecated (but will stay available for
at least five years).  If you were using low-level Unicode APIs to
construct and access unicode objects and you want to benefit of the
memory footprint reduction provided by 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393}, you have to convert
your code to the new @ref{bf8,,Unicode API}.

However, if you only have been using high-level functions such as
@ref{bf9,,PyUnicode_Concat()}, @ref{bfa,,PyUnicode_Join()} or
@ref{8c2,,PyUnicode_FromFormat()}, your code will automatically take
advantage of the new unicode representations.

@item 
@ref{bfb,,PyImport_GetMagicNumber()} now returns @code{-1} upon failure.

@item 
As a negative value for the @emph{level} argument to @ref{16b,,__import__()} is no
longer valid, the same now holds for @ref{bfc,,PyImport_ImportModuleLevel()}.
This also means that the value of @emph{level} used by
@ref{bfd,,PyImport_ImportModuleEx()} is now @code{0} instead of @code{-1}.
@end itemize

@node Building C extensions,Command Line Switch Changes,Porting C code,移植到 Python 3 3
@anchor{whatsnew/3 3 building-c-extensions}@anchor{bfe}
@subsubsection Building C extensions



@itemize *

@item 
The range of possible file names for C extensions has been narrowed.
Very rarely used spellings have been suppressed: under POSIX, files
named @code{xxxmodule.so}, @code{xxxmodule.abi3.so} and
@code{xxxmodule.cpython-*.so} are no longer recognized as implementing
the @code{xxx} module.  If you had been generating such files, you have
to switch to the other spellings (i.e., remove the @code{module} string
from the file names).

(implemented in bpo-14040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14040}.)
@end itemize

@node Command Line Switch Changes,,Building C extensions,移植到 Python 3 3
@anchor{whatsnew/3 3 command-line-switch-changes}@anchor{bff}
@subsubsection Command Line Switch Changes



@itemize *

@item 
The -Q command-line flag and related artifacts have been removed.  Code
checking sys.flags.division_warning will need updating.

（bpo-10998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10998}，由 Éric Araujo 贡献。）

@item 
When @code{python} is started with @ref{c00,,-S}, @code{import site}
will no longer add site-specific paths to the module search paths.  In
previous versions, it did.

(bpo-11591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11591}, contributed by Carl Meyer with editions by Éric Araujo.)
@end itemize

@node Python 3 2 有什么新变化,Python 3 1 有什么新变化,Python 3 3 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 2 doc}@anchor{c01}@anchor{whatsnew/3 2 what-s-new-in-python-3-2}@anchor{c02}
@section Python 3.2 有什么新变化


@*作者: 
Raymond Hettinger


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten.  (Note, during release candidate phase or just before
@c a beta release, please use the tracker instead -- this helps avoid
@c merge conflicts.   If you must add a suggested entry directly,
@c please put it in an XXX comment and the maintainer will take notice).
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.  It's helpful to
@c add the issue number:
@c 
@c   XXX Describe the transmogrify() function added to the socket
@c   module.
@c 
@c   (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.

This article explains the new features in Python 3.2 as compared to 3.1.  It
focuses on a few highlights and gives a few examples.  For full details, see the
Misc/NEWS@footnote{https://github.com/python/cpython/blob/076ca6c3c8df3030307e548d9be792ce3c1c6eea/Misc/NEWS}
file.


@subsubheading 参见


@geindex Python 提高建议; PEP 392
PEP 392@footnote{https://www.python.org/dev/peps/pep-0392} - Python 3.2 发布计划


@menu
* PEP 384; 定义稳定的ABI: PEP 384 定义稳定的ABI. 
* PEP 389; Argparse 命令行解析模块: PEP 389 Argparse 命令行解析模块. 
* PEP 391; 基于字典的日志配置: PEP 391 基于字典的日志配置. 
* PEP 3148; concurrent.futures 模块: PEP 3148 concurrent futures 模块. 
* PEP 3147; PYC 仓库目录: PEP 3147 PYC 仓库目录. 
* PEP 3149; ABI Version Tagged .so Files: PEP 3149 ABI Version Tagged so Files. 
* PEP 3333; Python Web服务器网关接口v1.0.1: PEP 3333 Python Web服务器网关接口v1 0 1. 
* 其他语言特性修改: 其他语言特性修改<8>. 
* 新增，改进和弃用的模块:: 
* 多线程:: 
* 性能优化: 性能优化<7>. 
* Unicode:: 
* 编解码器:: 
* 文档:: 
* IDLE:: 
* 代码库:: 
* 构建和 C API 的改变: 构建和 C API 的改变<5>. 
* 移植到 Python 3.2: 移植到 Python 3 2. 

@end menu

@node PEP 384 定义稳定的ABI,PEP 389 Argparse 命令行解析模块,,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-384-defining-a-stable-abi}@anchor{c03}
@subsection PEP 384: 定义稳定的ABI


In the past, extension modules built for one Python version were often
not usable with other Python versions. Particularly on Windows, every
feature release of Python required rebuilding all extension modules that
one wanted to use. This requirement was the result of the free access to
Python interpreter internals that extension modules could use.

With Python 3.2, an alternative approach becomes available: extension
modules which restrict themselves to a limited API (by defining
Py_LIMITED_API) cannot use many of the internals, but are constrained
to a set of API functions that are promised to be stable for several
releases. As a consequence, extension modules built for 3.2 in that
mode will also work with 3.3, 3.4, and so on. Extension modules that
make use of details of memory structures can still be built, but will
need to be recompiled for every feature release.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 384

@item PEP 384@footnote{https://www.python.org/dev/peps/pep-0384} - 定义稳定的ABI

PEP 由  Martin von Löwis 撰写
@end table


@node PEP 389 Argparse 命令行解析模块,PEP 391 基于字典的日志配置,PEP 384 定义稳定的ABI,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-389-argparse-command-line-parsing-module}@anchor{c04}
@subsection PEP 389: Argparse 命令行解析模块


A new module for command line parsing, @ref{5,,argparse}, was introduced to
overcome the limitations of @ref{c3,,optparse} which did not provide support for
positional arguments (not just options), subcommands, required options and other
common patterns of specifying and validating options.

This module has already had widespread success in the community as a
third-party module.  Being more fully featured than its predecessor, the
@ref{5,,argparse} module is now the preferred module for command-line processing.
The older module is still being kept available because of the substantial amount
of legacy code that depends on it.

Here's an annotated example parser showing features like limiting results to a
set of choices, specifying a @emph{metavar} in the help screen, validating that one
or more positional arguments is present, and making a required option:

@example
import argparse
parser = argparse.ArgumentParser(
            description = 'Manage servers',         # main description for help
            epilog = 'Tested on Solaris and Linux') # displayed after help
parser.add_argument('action',                       # argument name
            choices = ['deploy', 'start', 'stop'],  # three allowed values
            help = 'action on each target')         # help msg
parser.add_argument('targets',
            metavar = 'HOSTNAME',                   # var name used in help msg
            nargs = '+',                            # require one or more targets
            help = 'url for target machines')       # help msg explanation
parser.add_argument('-u', '--user',                 # -u or --user option
            required = True,                        # make it a required argument
            help = 'login as user')
@end example

在命令字符串中调用解析器的示例:

@example
>>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
>>> result = parser.parse_args(cmd.split())
>>> result.action
'deploy'
>>> result.targets
['sneezy.example.com', 'sleepy.example.com']
>>> result.user
'skycaptain'
@end example

解释器自动生成的帮助示例:

@example
>>> parser.parse_args('-h'.split())

usage: manage_cloud.py [-h] -u USER
                       @{deploy,start,stop@} HOSTNAME [HOSTNAME ...]

Manage servers

positional arguments:
  @{deploy,start,stop@}   action on each target
  HOSTNAME              url for target machines

optional arguments:
  -h, --help            show this help message and exit
  -u USER, --user USER  login as user

Tested on Solaris and Linux
@end example

一个非常好的 @ref{5,,argparse} 特性是可以定义子解析器，每个子解析器拥有它们自己的参数模式和帮助显示:

@example
import argparse
parser = argparse.ArgumentParser(prog='HELM')
subparsers = parser.add_subparsers()

parser_l = subparsers.add_parser('launch', help='Launch Control')   # first subgroup
parser_l.add_argument('-m', '--missiles', action='store_true')
parser_l.add_argument('-t', '--torpedos', action='store_true')

parser_m = subparsers.add_parser('move', help='Move Vessel',        # second subgroup
                                 aliases=('steer', 'turn'))         # equivalent names
parser_m.add_argument('-c', '--course', type=int, required=True)
parser_m.add_argument('-s', '--speed', type=int, default=0)
@end example

@example
$ ./helm.py --help                         # top level help (launch and move)
$ ./helm.py launch --help                  # help for launch options
$ ./helm.py launch --missiles              # set missiles=True and torpedos=False
$ ./helm.py steer --course 180 --speed 5   # set movement parameters
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 389

@item PEP 389@footnote{https://www.python.org/dev/peps/pep-0389} - 新的命令行解析模块

PEP 由 Steven Bethard 撰写
@end table

参阅 @ref{c05,,升级 optparse 代码} 了解与 @ref{c3,,optparse} 的差异的细节。


@node PEP 391 基于字典的日志配置,PEP 3148 concurrent futures 模块,PEP 389 Argparse 命令行解析模块,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-391-dictionary-based-configuration-for-logging}@anchor{c06}
@subsection PEP 391:  基于字典的日志配置


The @ref{aa,,logging} module provided two kinds of configuration, one style with
function calls for each option or another style driven by an external file saved
in a @code{ConfigParser} format.  Those options did not provide the flexibility
to create configurations from JSON or YAML files, nor did they support
incremental configuration, which is needed for specifying logger options from a
command line.

To support a more flexible style, the module now offers
@ref{c07,,logging.config.dictConfig()} for specifying logging configuration with
plain Python dictionaries.  The configuration options include formatters,
handlers, filters, and loggers.  Here's a working example of a configuration
dictionary:

@example
@{"version": 1,
 "formatters": @{"brief": @{"format": "%(levelname)-8s: %(name)-15s: %(message)s"@},
                "full": @{"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"@}
                @},
 "handlers": @{"console": @{
                   "class": "logging.StreamHandler",
                   "formatter": "brief",
                   "level": "INFO",
                   "stream": "ext://sys.stdout"@},
              "console_priority": @{
                   "class": "logging.StreamHandler",
                   "formatter": "full",
                   "level": "ERROR",
                   "stream": "ext://sys.stderr"@}
              @},
 "root": @{"level": "DEBUG", "handlers": ["console", "console_priority"]@}@}
@end example

If that dictionary is stored in a file called @code{conf.json}, it can be
loaded and called with code like this:

@example
>>> import json, logging.config
>>> with open('conf.json') as f:
...     conf = json.load(f)
...
>>> logging.config.dictConfig(conf)
>>> logging.info("Transaction completed normally")
INFO    : root           : Transaction completed normally
>>> logging.critical("Abnormal termination")
2011-02-17 11:14:36,694 root            CRITICAL Abnormal termination
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 391

@item PEP 391@footnote{https://www.python.org/dev/peps/pep-0391} - 基于字典的日志配置

PEP 由 Vinay Sajip 撰写
@end table


@node PEP 3148 concurrent futures 模块,PEP 3147 PYC 仓库目录,PEP 391 基于字典的日志配置,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-3148-the-concurrent-futures-module}@anchor{c08}
@subsection PEP 3148:  @code{concurrent.futures} 模块


Code for creating and managing concurrency is being collected in a new top-level
namespace, @emph{concurrent}.  Its first member is a @emph{futures} package which provides
a uniform high-level interface for managing threads and processes.

The design for @ref{21,,concurrent.futures} was inspired by the
@emph{java.util.concurrent} package.  In that model, a running call and its result
are represented by a @ref{c09,,Future} object that abstracts
features common to threads, processes, and remote procedure calls.  That object
supports status checks (running or done), timeouts, cancellations, adding
callbacks, and access to results or exceptions.

The primary offering of the new module is a pair of executor classes for
launching and managing calls.  The goal of the executors is to make it easier to
use existing tools for making parallel calls. They save the effort needed to
setup a pool of resources, launch the calls, create a results queue, add
time-out handling, and limit the total number of threads, processes, or remote
procedure calls.

Ideally, each application should share a single executor across multiple
components so that process and thread limits can be centrally managed.  This
solves the design challenge that arises when each component has its own
competing strategy for resource management.

Both classes share a common interface with three methods:
@ref{3ce,,submit()} for scheduling a callable and
returning a @ref{c09,,Future} object;
@ref{7bb,,map()} for scheduling many asynchronous calls
at a time, and @ref{195,,shutdown()} for freeing
resources.  The class is a @ref{66b,,context manager} and can be used in a
@ref{7e4,,with} statement to assure that resources are automatically released
when currently pending futures are done executing.

A simple of example of @ref{18c,,ThreadPoolExecutor} is a
launch of four parallel threads for copying files:

@example
import concurrent.futures, shutil
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3148

@item PEP 3148@footnote{https://www.python.org/dev/peps/pep-3148} -- futures - 异步执行指令

PEP 由 Brian Quinlan 撰写
@end table

@ref{c0a,,Code for Threaded Parallel URL reads}, an
example using threads to fetch multiple web pages in parallel.

@ref{c0b,,Code for computing prime numbers in parallel}, an example demonstrating
@ref{196,,ProcessPoolExecutor}.


@node PEP 3147 PYC 仓库目录,PEP 3149 ABI Version Tagged so Files,PEP 3148 concurrent futures 模块,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-3147-pyc-repository-directories}@anchor{c0c}
@subsection PEP 3147:  PYC 仓库目录


Python's scheme for caching bytecode in @emph{.pyc} files did not work well in
environments with multiple Python interpreters.  If one interpreter encountered
a cached file created by another interpreter, it would recompile the source and
overwrite the cached file, thus losing the benefits of caching.

The issue of "pyc fights" has become more pronounced as it has become
commonplace for Linux distributions to ship with multiple versions of Python.
These conflicts also arise with CPython alternatives such as Unladen Swallow.

To solve this problem, Python's import machinery has been extended to use
distinct filenames for each interpreter.  Instead of Python 3.2 and Python 3.3 and
Unladen Swallow each competing for a file called "mymodule.pyc", they will now
look for "mymodule.cpython-32.pyc", "mymodule.cpython-33.pyc", and
"mymodule.unladen10.pyc".  And to prevent all of these new files from
cluttering source directories, the @emph{pyc} files are now collected in a
"__pycache__" directory stored under the package directory.

Aside from the filenames and target directories, the new scheme has a few
aspects that are visible to the programmer:


@itemize *

@item 
Imported modules now have a @ref{c0d,,__cached__} attribute which stores the name
of the actual file that was imported:

@example
>>> import collections
>>> collections.__cached__ 
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
@end example

@item 
针对每个解释器的唯一标签可以从 @ref{99,,imp} 模块访问:

@example
>>> import imp
>>> imp.get_tag() 
'cpython-32'
@end example

@item 
Scripts that try to deduce source filename from the imported file now need to
be smarter.  It is no longer sufficient to simply strip the "c" from a ".pyc"
filename.  Instead, use the new functions in the @ref{99,,imp} module:

@example
>>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc')
'c:/py32/lib/collections.py'
>>> imp.cache_from_source('c:/py32/lib/collections.py') 
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
@end example

@item 
The @ref{d7,,py_compile} and @ref{20,,compileall} modules have been updated to
reflect the new naming convention and target directory.  The command-line
invocation of @emph{compileall} has new options: @code{-i} for
specifying a list of files and directories to compile and @code{-b} which causes
bytecode files to be written to their legacy location rather than
@emph{__pycache__}.

@item 
The @ref{9b,,importlib.abc} module has been updated with new @ref{c0e,,abstract base classes} for loading bytecode files.  The obsolete
ABCs, @code{PyLoader} and
@code{PyPycLoader}, have been deprecated (instructions on how
to stay Python 3.1 compatible are included with the documentation).
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3147

@item PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} - PYC 仓库目录

PEP 由 Barry Warsaw 撰写
@end table


@node PEP 3149 ABI Version Tagged so Files,PEP 3333 Python Web服务器网关接口v1 0 1,PEP 3147 PYC 仓库目录,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-3149-abi-version-tagged-so-files}@anchor{c0f}
@subsection PEP 3149: ABI Version Tagged .so Files


The PYC repository directory allows multiple bytecode cache files to be
co-located.  This PEP implements a similar mechanism for shared object files by
giving them a common directory and distinct names for each version.

The common directory is "pyshared" and the file names are made distinct by
identifying the Python implementation (such as CPython, PyPy, Jython, etc.), the
major and minor version numbers, and optional build flags (such as "d" for
debug, "m" for pymalloc, "u" for wide-unicode).  For an arbitrary package "foo",
you may see these files when the distribution package is installed:

@example
/usr/share/pyshared/foo.cpython-32m.so
/usr/share/pyshared/foo.cpython-33md.so
@end example

In Python itself, the tags are accessible from functions in the @ref{fe,,sysconfig}
module:

@example
>>> import sysconfig
>>> sysconfig.get_config_var('SOABI')       # find the version tag
'cpython-32mu'
>>> sysconfig.get_config_var('EXT_SUFFIX')  # find the full filename extension
'.cpython-32mu.so'
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3149

@item PEP 3149@footnote{https://www.python.org/dev/peps/pep-3149} - 带有 ABI 版本标签的 .so 文件

PEP 由 Barry Warsaw 撰写
@end table


@node PEP 3333 Python Web服务器网关接口v1 0 1,其他语言特性修改<8>,PEP 3149 ABI Version Tagged so Files,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 pep-3333-python-web-server-gateway-interface-v1-0-1}@anchor{c10}
@subsection PEP 3333: Python Web服务器网关接口v1.0.1


This informational PEP clarifies how bytes/text issues are to be handled by the
WSGI protocol.  The challenge is that string handling in Python 3 is most
conveniently handled with the @ref{206,,str} type even though the HTTP protocol
is itself bytes oriented.

The PEP differentiates so-called @emph{native strings} that are used for
request/response headers and metadata versus @emph{byte strings} which are used for
the bodies of requests and responses.

The @emph{native strings} are always of type @ref{206,,str} but are restricted to code
points between @emph{U+0000} through @emph{U+00FF} which are translatable to bytes using
@emph{Latin-1} encoding.  These strings are used for the keys and values in the
environment dictionary and for response headers and statuses in the
@code{start_response()} function.  They must follow 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} with respect to
encoding. That is, they must either be @emph{ISO-8859-1} characters or use
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} MIME encoding.

For developers porting WSGI applications from Python 2, here are the salient
points:


@itemize *

@item 
If the app already used strings for headers in Python 2, no change is needed.

@item 
If instead, the app encoded output headers or decoded input headers, then the
headers will need to be re-encoded to Latin-1.  For example, an output header
encoded in utf-8 was using @code{h.encode('utf-8')} now needs to convert from
bytes to native strings using @code{h.encode('utf-8').decode('latin-1')}.

@item 
Values yielded by an application or sent using the @code{write()} method
must be byte strings.  The @code{start_response()} function and environ
must use native strings.  The two cannot be mixed.
@end itemize

For server implementers writing CGI-to-WSGI pathways or other CGI-style
protocols, the users must to be able access the environment using native strings
even though the underlying platform may have a different convention.  To bridge
this gap, the @ref{135,,wsgiref} module has a new function,
@ref{c11,,wsgiref.handlers.read_environ()} for transcoding CGI variables from
@ref{c12,,os.environ} into native strings and returning a new dictionary.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3333

@item PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} - Python Web服务器网关接口v1.0.1

PEP 由 Phillip Eby 撰写
@end table


@node 其他语言特性修改<8>,新增，改进和弃用的模块,PEP 3333 Python Web服务器网关接口v1 0 1,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 other-language-changes}@anchor{c13}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
String formatting for @ref{5de,,format()} and @ref{5dd,,str.format()} gained new
capabilities for the format character @strong{#}.  Previously, for integers in
binary, octal, or hexadecimal, it caused the output to be prefixed with '0b',
'0o', or '0x' respectively.  Now it can also handle floats, complex, and
Decimal, causing the output to always have a decimal point even when no digits
follow it.

@example
>>> format(20, '#o')
'0o24'
>>> format(12.34, '#5.0f')
'  12.'
@end example

(Suggested by Mark Dickinson and implemented by Eric Smith in bpo-7094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7094}.)

@item 
There is also a new @ref{7ae,,str.format_map()} method that extends the
capabilities of the existing @ref{5dd,,str.format()} method by accepting arbitrary
@ref{c14,,mapping} objects.  This new method makes it possible to use string
formatting with any of Python's many dictionary-like objects such as
@ref{c15,,defaultdict}, @ref{9a0,,Shelf},
@ref{5ad,,ConfigParser}, or @ref{31,,dbm}.  It is also useful with
custom @ref{164,,dict} subclasses that normalize keys before look-up or that
supply a @ref{c16,,__missing__()} method for unknown keys:

@example
>>> import shelve
>>> d = shelve.open('tmp.shl')
>>> 'The @{project_name@} status is @{status@} as of @{date@}'.format_map(d)
'The testing project status is green as of February 15, 2011'

>>> class LowerCasedDict(dict):
...     def __getitem__(self, key):
...         return dict.__getitem__(self, key.lower())
>>> lcd = LowerCasedDict(part='widgets', quantity=10)
>>> 'There are @{QUANTITY@} @{Part@} in stock'.format_map(lcd)
'There are 10 widgets in stock'

>>> class PlaceholderDict(dict):
...     def __missing__(self, key):
...         return '<@{@}>'.format(key)
>>> 'Hello @{name@}, welcome to @{location@}'.format_map(PlaceholderDict())
'Hello <name>, welcome to <location>'
@end example
@end itemize

@quotation

（由 Raymond Hettinger 提议并由 Eric Smith 在 bpo-6081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6081} 中贡献。）
@end quotation


@itemize *

@item 
The interpreter can now be started with a quiet option, @code{-q}, to prevent
the copyright and version information from being displayed in the interactive
mode.  The option can be introspected using the @ref{c17,,sys.flags} attribute:

@example
$ python -q
>>> sys.flags
sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,
optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)
@end example

（由 Marcin Wojdyr 在 bpo-1772833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1772833} 中贡献。）

@item 
The @ref{553,,hasattr()} function works by calling @ref{554,,getattr()} and detecting
whether an exception is raised.  This technique allows it to detect methods
created dynamically by @ref{433,,__getattr__()} or @ref{552,,__getattribute__()} which
would otherwise be absent from the class dictionary.  Formerly, @emph{hasattr}
would catch any exception, possibly masking genuine errors.  Now, @emph{hasattr}
has been tightened to only catch @ref{4aa,,AttributeError} and let other
exceptions pass through:

@example
>>> class A:
...     @@property
...     def f(self):
...         return 1 // 0
...
>>> a = A()
>>> hasattr(a, 'f')
Traceback (most recent call last):
  ...
ZeroDivisionError: integer division or modulo by zero
@end example

（由 Yury Selivanov 发现并由 Benjamin Peterson 修正；bpo-9666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9666}。）

@item 
The @ref{206,,str()} of a float or complex number is now the same as its
@ref{8c3,,repr()}. Previously, the @ref{206,,str()} form was shorter but that just
caused confusion and is no longer needed now that the shortest possible
@ref{8c3,,repr()} is displayed by default:

@example
>>> import math
>>> repr(math.pi)
'3.141592653589793'
>>> str(math.pi)
'3.141592653589793'
@end example

（由 Mark Dickinson 提议并实现；bpo-9337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9337}。）

@item 
@ref{38d,,memoryview} objects now have a @ref{c18,,release()} method
and they also now support the context management protocol.  This allows timely
release of any resources that were acquired when requesting a buffer from the
original object.

@example
>>> with memoryview(b'abcdefgh') as v:
...     print(v.tolist())
[97, 98, 99, 100, 101, 102, 103, 104]
@end example

（由 Antoine Pitrou 添加；bpo-9757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9757}。）

@item 
Previously it was illegal to delete a name from the local namespace if it
occurs as a free variable in a nested block:

@example
def outer(x):
    def inner():
        return x
    inner()
    del x
@end example

This is now allowed.  Remember that the target of an @ref{c19,,except} clause
is cleared, so this code which used to work with Python 2.6, raised a
@ref{562,,SyntaxError} with Python 3.1 and now works again:

@example
def f():
    def print_error():
        print(e)
    try:
        something
    except Exception as e:
        print_error()
        # implicit "del e" here
@end example

（参见 bpo-4617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4617}。）

@item 
The internal @code{structsequence} tool now creates subclasses of tuple.
This means that C structures like those returned by @ref{328,,os.stat()},
@ref{c1a,,time.gmtime()}, and @ref{bf6,,sys.version_info} now work like a
@ref{b84,,named tuple} and now work with functions and methods that
expect a tuple as an argument.  This is a big step forward in making the C
structures as flexible as their pure Python counterparts:

@example
>>> import sys
>>> isinstance(sys.version_info, tuple)
True
>>> 'Version %d.%d.%d %s(%d)' % sys.version_info 
'Version 3.2.0 final(0)'
@end example

(Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
by Benjamin Peterson in bpo-8413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8413}.)

@item 
Warnings are now easier to control using the 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS}
environment variable as an alternative to using @code{-W} at the command line:

@example
$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'
@end example

(Suggested by Barry Warsaw and implemented by Philip Jenvey in bpo-7301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7301}.)

@item 
A new warning category, @ref{5d3,,ResourceWarning}, has been added.  It is
emitted when potential issues with resource consumption or cleanup
are detected.  It is silenced by default in normal release builds but
can be enabled through the means provided by the @ref{12f,,warnings}
module, or on the command line.

A @ref{5d3,,ResourceWarning} is issued at interpreter shutdown if the
@ref{c1b,,gc.garbage} list isn't empty, and if @ref{c1c,,gc.DEBUG_UNCOLLECTABLE} is
set, all uncollectable objects are printed.  This is meant to make the
programmer aware that their code contains object finalization issues.

A @ref{5d3,,ResourceWarning} is also issued when a @ref{c1d,,file object} is destroyed
without having been explicitly closed.  While the deallocator for such
object ensures it closes the underlying operating system resource
(usually, a file descriptor), the delay in deallocating the object could
produce various issues, especially under Windows.  Here is an example
of enabling the warning from the command line:

@example
$ python -q -Wdefault
>>> f = open("foo", "wb")
>>> del f
__main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>
@end example

(Added by Antoine Pitrou and Georg Brandl in bpo-10093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10093} and bpo-477863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=477863}.)

@item 
@ref{1f6,,range} objects now support @emph{index} and @emph{count} methods. This is part
of an effort to make more objects fully implement the
@code{collections.Sequence} @ref{c0e,,abstract base class}.  As a result, the
language will have a more uniform API.  In addition, @ref{1f6,,range} objects
now support slicing and negative indices, even with values larger than
@ref{c1e,,sys.maxsize}.  This makes @emph{range} more interoperable with lists:

@example
>>> range(0, 100, 2).count(10)
1
>>> range(0, 100, 2).index(10)
5
>>> range(0, 100, 2)[5]
10
>>> range(0, 100, 2)[0:5]
range(0, 10, 2)
@end example

（由 Daniel Stutzbach 在 bpo-9213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9213} 中贡献，由 Alexander Belopolsky 在 bpo-2690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2690} 中贡献，由 Nick Coghlan 在 bpo-10889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10889} 中贡献。）

@item 
The @ref{c1f,,callable()} builtin function from Py2.x was resurrected.  It provides
a concise, readable alternative to using an @ref{c0e,,abstract base class} in an
expression like @code{isinstance(x, collections.Callable)}:

@example
>>> callable(max)
True
>>> callable(20)
False
@end example

（见 bpo-10518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10518} ）

@item 
Python's import mechanism can now load modules installed in directories with
non-ASCII characters in the path name.  This solved an aggravating problem
with home directories for users with non-ASCII characters in their usernames.
@end itemize

@quotation

(Required extensive work by Victor Stinner in bpo-9425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9425}.)
@end quotation

@node 新增，改进和弃用的模块,多线程,其他语言特性修改<8>,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 new-improved-and-deprecated-modules}@anchor{c20}
@subsection 新增，改进和弃用的模块


Python's standard library has undergone significant maintenance efforts and
quality improvements.

The biggest news for Python 3.2 is that the @ref{67,,email} package, @ref{ae,,mailbox}
module, and @ref{c0,,nntplib} modules now work correctly with the bytes/text model
in Python 3.  For the first time, there is correct handling of messages with
mixed encodings.

Throughout the standard library, there has been more careful attention to
encodings and text versus bytes issues.  In particular, interactions with the
operating system are now better able to exchange non-ASCII data using the
Windows MBCS encoding, locale-aware encodings, or UTF-8.

Another significant win is the addition of substantially better support for
@emph{SSL} connections and security certificates.

In addition, more classes now implement a @ref{66b,,context manager} to support
convenient and reliable resource clean-up using a @ref{7e4,,with} statement.

@menu
* email: email<5>. 
* elementtree:: 
* functools: functools<6>. 
* itertools: itertools<4>. 
* collections: collections<8>. 
* threading: threading<6>. 
* datetime 和 time:: 
* math: math<7>. 
* abc: abc<3>. 
* io: io<5>. 
* reprlib:: 
* logging: logging<7>. 
* csv: csv<3>. 
* contextlib: contextlib<6>. 
* decimal and fractions:: 
* ftp:: 
* popen:: 
* select: select<3>. 
* gzip 和 zipfile:: 
* tarfile: tarfile<6>. 
* hashlib: hashlib<4>. 
* ast: ast<4>. 
* os: os<9>. 
* shutil: shutil<5>. 
* sqlite3: sqlite3<6>. 
* html: html<3>. 
* socket: socket<9>. 
* ssl: ssl<9>. 
* nntp:: 
* certificates:: 
* imaplib: imaplib<4>. 
* http.client: http client<4>. 
* unittest: unittest<6>. 
* random: random<3>. 
* poplib: poplib<4>. 
* asyncore: asyncore<2>. 
* tempfile: tempfile<2>. 
* inspect: inspect<7>. 
* pydoc: pydoc<6>. 
* dis: dis<3>. 
* dbm: dbm<6>. 
* ctypes: ctypes<2>. 
* site: site<2>. 
* sysconfig: sysconfig<2>. 
* pdb: pdb<6>. 
* configparser: configparser<2>. 
* urllib.parse: urllib parse<4>. 
* mailbox:: 
* turtledemo:: 

@end menu

@node email<5>,elementtree,,新增，改进和弃用的模块
@anchor{whatsnew/3 2 email}@anchor{c21}
@subsubsection email


The usability of the @ref{67,,email} package in Python 3 has been mostly fixed by
the extensive efforts of R. David Murray.  The problem was that emails are
typically read and stored in the form of @ref{172,,bytes} rather than @ref{206,,str}
text, and they may contain multiple encodings within a single email.  So, the
email package had to be extended to parse and generate email messages in bytes
format.


@itemize *

@item 
New functions @ref{c22,,message_from_bytes()} and
@ref{c23,,message_from_binary_file()}, and new classes
@ref{c24,,BytesFeedParser} and @ref{c25,,BytesParser}
allow binary message data to be parsed into model objects.

@item 
Given bytes input to the model, @ref{c26,,get_payload()}
will by default decode a message body that has a
@code{Content-Transfer-Encoding} of @emph{8bit} using the charset
specified in the MIME headers and return the resulting string.

@item 
Given bytes input to the model, @ref{c27,,Generator} will
convert message bodies that have a @code{Content-Transfer-Encoding} of
@emph{8bit} to instead have a @emph{7bit} @code{Content-Transfer-Encoding}.

Headers with unencoded non-ASCII bytes are deemed to be 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html}-encoded
using the @emph{unknown-8bit} character set.

@item 
A new class @ref{c28,,BytesGenerator} produces bytes as output,
preserving any unchanged non-ASCII data that was present in the input used to
build the model, including message bodies with a
@code{Content-Transfer-Encoding} of @emph{8bit}.

@item 
The @ref{ed,,smtplib} @ref{1df,,SMTP} class now accepts a byte string
for the @emph{msg} argument to the @ref{83d,,sendmail()} method,
and a new method, @ref{83e,,send_message()} accepts a
@ref{644,,Message} object and can optionally obtain the
@emph{from_addr} and @emph{to_addrs} addresses directly from the object.
@end itemize

(Proposed and implemented by R. David Murray, bpo-4661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4661} and bpo-10321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10321}.)

@node elementtree,functools<6>,email<5>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 elementtree}@anchor{c29}
@subsubsection elementtree


The @ref{140,,xml.etree.ElementTree} package and its @code{xml.etree.cElementTree}
counterpart have been updated to version 1.3.

Several new and useful functions and methods have been added:


@itemize *

@item 
@ref{c2a,,xml.etree.ElementTree.fromstringlist()} which builds an XML document
from a sequence of fragments

@item 
@ref{c2b,,xml.etree.ElementTree.register_namespace()} for registering a global
namespace prefix

@item 
@ref{a05,,xml.etree.ElementTree.tostringlist()} for string representation
including all sublists

@item 
@ref{c2c,,xml.etree.ElementTree.Element.extend()} for appending a sequence of zero
or more elements

@item 
@ref{c2d,,xml.etree.ElementTree.Element.iterfind()} searches an element and
subelements

@item 
@ref{c2e,,xml.etree.ElementTree.Element.itertext()} creates a text iterator over
an element and its subelements

@item 
@ref{c2f,,xml.etree.ElementTree.TreeBuilder.end()} closes the current element

@item 
@ref{3eb,,xml.etree.ElementTree.TreeBuilder.doctype()} handles a doctype
declaration
@end itemize

两个方法被弃用：


@itemize *

@item 
@code{xml.etree.ElementTree.getchildren()} 被 @code{list(elem)} 替代。

@item 
@code{xml.etree.ElementTree.getiterator()} 被 @code{Element.iter} 替代。
@end itemize

For details of the update, see Introducing ElementTree@footnote{https://web.archive.org/web/20200703234532/http://effbot.org/zone/elementtree-13-intro.htm}
on Fredrik Lundh's website.

（由 Florent Xicluna 和 Fredrik Lundh 在 bpo-6472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6472} 中贡献。）

@node functools<6>,itertools<4>,elementtree,新增，改进和弃用的模块
@anchor{whatsnew/3 2 functools}@anchor{c30}
@subsubsection functools



@itemize *

@item 
The @ref{83,,functools} module includes a new decorator for caching function
calls.  @ref{2ff,,functools.lru_cache()} can save repeated queries to an external
resource whenever the results are expected to be the same.

For example, adding a caching decorator to a database query function can save
database accesses for popular searches:

@example
>>> import functools
>>> @@functools.lru_cache(maxsize=300)
... def get_phone_number(name):
...     c = conn.cursor()
...     c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
...     return c.fetchone()[0]
@end example

@example
>>> for name in user_requests:        
...     get_phone_number(name)        # cached lookup
@end example

To help with choosing an effective cache size, the wrapped function is
instrumented for tracking cache statistics:

@example
>>> get_phone_number.cache_info()     
CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)
@end example

If the phonelist table gets updated, the outdated contents of the cache can be
cleared with:

@example
>>> get_phone_number.cache_clear()
@end example

(Contributed by Raymond Hettinger and incorporating design ideas from Jim
Baker, Miki Tebeka, and Nick Coghlan; see recipe 498245@footnote{https://code.activestate.com/recipes/498245}, recipe 577479@footnote{https://code.activestate.com/recipes/577479}, bpo-10586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10586}, and
bpo-10593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10593}.)

@item 
The @ref{95e,,functools.wraps()} decorator now adds a @code{__wrapped__} attribute
pointing to the original callable function.  This allows wrapped functions to
be introspected.  It also copies @code{__annotations__} if defined.  And now
it also gracefully skips over missing attributes such as @code{__doc__} which
might not be defined for the wrapped callable.

In the above example, the cache can be removed by recovering the original
function:

@example
>>> get_phone_number = get_phone_number.__wrapped__    # uncached function
@end example

(By Nick Coghlan and Terrence Cole; bpo-9567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9567}, bpo-3445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3445}, and
bpo-8814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8814}.)

@item 
To help write classes with rich comparison methods, a new decorator
@ref{942,,functools.total_ordering()} will use existing equality and inequality
methods to fill in the remaining methods.

For example, supplying @emph{__eq__} and @emph{__lt__} will enable
@ref{942,,total_ordering()} to fill-in @emph{__le__}, @emph{__gt__} and @emph{__ge__}:

@example
@@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))

    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
@end example

With the @emph{total_ordering} decorator, the remaining comparison methods
are filled in automatically.

（由 Raymond Hettinger 贡献。）

@item 
To aid in porting programs from Python 2, the @ref{c31,,functools.cmp_to_key()}
function converts an old-style comparison function to
modern @ref{7dc,,key function}:

@example
>>> # locale-aware sort order
>>> sorted(iterable, key=cmp_to_key(locale.strcoll)) 
@end example

For sorting examples and a brief sorting tutorial, see the Sorting HowTo@footnote{https://wiki.python.org/moin/HowTo/Sorting/} tutorial.

（由 Raymond Hettinger 贡献。）
@end itemize

@node itertools<4>,collections<8>,functools<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 itertools}@anchor{c32}
@subsubsection itertools



@itemize *

@item 
The @ref{a3,,itertools} module has a new @ref{315,,accumulate()} function
modeled on APL's @emph{scan} operator and Numpy's @emph{accumulate} function:

@example
>>> from itertools import accumulate
>>> list(accumulate([8, 2, 50]))
[8, 10, 60]
@end example

@example
>>> prob_dist = [0.1, 0.4, 0.2, 0.3]
>>> list(accumulate(prob_dist))      # cumulative probability distribution
[0.1, 0.5, 0.7, 1.0]
@end example

For an example using @ref{315,,accumulate()}, see the @ref{c33,,examples for the random module}.

(Contributed by Raymond Hettinger and incorporating design suggestions
from Mark Dickinson.)
@end itemize

@node collections<8>,threading<6>,itertools<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 collections}@anchor{c34}
@subsubsection collections



@itemize *

@item 
The @ref{ac2,,collections.Counter} class now has two forms of in-place
subtraction, the existing @emph{-=} operator for saturating subtraction@footnote{https://en.wikipedia.org/wiki/Saturation_arithmetic} and the new
@ref{c35,,subtract()} method for regular subtraction.  The
former is suitable for multisets@footnote{https://en.wikipedia.org/wiki/Multiset}
which only have positive counts, and the latter is more suitable for use cases
that allow negative counts:

@example
>>> from collections import Counter
>>> tally = Counter(dogs=5, cats=3)
>>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
>>> tally
Counter(@{'dogs': 3@})
@end example

@example
>>> tally = Counter(dogs=5, cats=3)
>>> tally.subtract(dogs=2, cats=8)      # regular subtraction
>>> tally
Counter(@{'dogs': 3, 'cats': -5@})
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @ref{2f1,,collections.OrderedDict} class has a new method
@ref{c36,,move_to_end()} which takes an existing key and
moves it to either the first or last position in the ordered sequence.

The default is to move an item to the last position.  This is equivalent of
renewing an entry with @code{od[k] = od.pop(k)}.

A fast move-to-end operation is useful for resequencing entries.  For example,
an ordered dictionary can be used to track order of access by aging entries
from the oldest to the most recently accessed.

@example
>>> from collections import OrderedDict
>>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
>>> list(d)
['a', 'b', 'X', 'd', 'e']
>>> d.move_to_end('X')
>>> list(d)
['a', 'b', 'd', 'e', 'X']
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @ref{633,,collections.deque} class grew two new methods
@ref{c37,,count()} and @ref{c38,,reverse()} that
make them more substitutable for @ref{1f9,,list} objects:

@example
>>> from collections import deque
>>> d = deque('simsalabim')
>>> d.count('s')
2
>>> d.reverse()
>>> d
deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])
@end example

（由 Raymond Hettinger 贡献。）
@end itemize

@node threading<6>,datetime 和 time,collections<8>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 threading}@anchor{c39}
@subsubsection threading


The @ref{10b,,threading} module has a new @ref{c3a,,Barrier}
synchronization class for making multiple threads wait until all of them have
reached a common barrier point.  Barriers are useful for making sure that a task
with multiple preconditions does not run until all of the predecessor tasks are
complete.

Barriers can work with an arbitrary number of threads.  This is a generalization
of a Rendezvous@footnote{https://en.wikipedia.org/wiki/Synchronous_rendezvous} which
is defined for only two threads.

Implemented as a two-phase cyclic barrier, @ref{c3a,,Barrier} objects
are suitable for use in loops.  The separate @emph{filling} and @emph{draining} phases
assure that all threads get released (drained) before any one of them can loop
back and re-enter the barrier.  The barrier fully resets after each cycle.

Example of using barriers:

@example
from threading import Barrier, Thread

def get_votes(site):
    ballots = conduct_election(site)
    all_polls_closed.wait()        # do not count until all polls are closed
    totals = summarize(ballots)
    publish(site, totals)

all_polls_closed = Barrier(len(sites))
for site in sites:
    Thread(target=get_votes, args=(site,)).start()
@end example

In this example, the barrier enforces a rule that votes cannot be counted at any
polling site until all polls are closed.  Notice how a solution with a barrier
is similar to one with @ref{c3b,,threading.Thread.join()}, but the threads stay alive
and continue to do work (summarizing ballots) after the barrier point is
crossed.

If any of the predecessor tasks can hang or be delayed, a barrier can be created
with an optional @emph{timeout} parameter.  Then if the timeout period elapses before
all the predecessor tasks reach the barrier point, all waiting threads are
released and a @ref{c3c,,BrokenBarrierError} exception is raised:

@example
def get_votes(site):
    ballots = conduct_election(site)
    try:
        all_polls_closed.wait(timeout=midnight - time.now())
    except BrokenBarrierError:
        lockbox = seal_ballots(ballots)
        queue.put(lockbox)
    else:
        totals = summarize(ballots)
        publish(site, totals)
@end example

In this example, the barrier enforces a more robust rule.  If some election
sites do not finish before midnight, the barrier times-out and the ballots are
sealed and deposited in a queue for later handling.

See Barrier Synchronization Patterns@footnote{http://osl.cs.illinois.edu/media/papers/karmani-2009-barrier_synchronization_pattern.pdf}
for more examples of how barriers can be used in parallel computing.  Also, there is
a simple but thorough explanation of barriers in The Little Book of Semaphores@footnote{https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf}, @emph{section 3.6}.

(Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in
bpo-8777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8777}.)

@node datetime 和 time,math<7>,threading<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 datetime-and-time}@anchor{c3d}
@subsubsection datetime 和 time



@itemize *

@item 
The @ref{30,,datetime} module has a new type @ref{ae9,,timezone} that
implements the @ref{180,,tzinfo} interface by returning a fixed UTC
offset and timezone name. This makes it easier to create timezone-aware
datetime objects:

@example
>>> from datetime import datetime, timezone

>>> datetime.now(timezone.utc)
datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)

>>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
@end example

@item 
Also, @ref{2d1,,timedelta} objects can now be multiplied by
@ref{1fe,,float} and divided by @ref{1fe,,float} and @ref{205,,int} objects.
And @ref{2d1,,timedelta} objects can now divide one another.

@item 
The @ref{63a,,datetime.date.strftime()} method is no longer restricted to years
after 1900.  The new supported year range is from 1000 to 9999 inclusive.

@item 
Whenever a two-digit year is used in a time tuple, the interpretation has been
governed by @code{time.accept2dyear}.  The default is @code{True} which means that
for a two-digit year, the century is guessed according to the POSIX rules
governing the @code{%y} strptime format.

Starting with Py3.2, use of the century guessing heuristic will emit a
@ref{15a,,DeprecationWarning}.  Instead, it is recommended that
@code{time.accept2dyear} be set to @code{False} so that large date ranges
can be used without guesswork:

@example
>>> import time, warnings
>>> warnings.resetwarnings()      # remove the default warning filters

>>> time.accept2dyear = True      # guess whether 11 means 11 or 2011
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
Warning (from warnings module):
  ...
DeprecationWarning: Century info guessed for a 2-digit year.
'Fri Jan  1 12:34:56 2011'

>>> time.accept2dyear = False     # use the full range of allowable dates
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
'Fri Jan  1 12:34:56 11'
@end example

Several functions now have significantly expanded date ranges.  When
@code{time.accept2dyear} is false, the @ref{c3e,,time.asctime()} function will
accept any year that fits in a C int, while the @ref{c3f,,time.mktime()} and
@ref{c40,,time.strftime()} functions will accept the full range supported by the
corresponding operating system functions.
@end itemize

（由 Alexander Belopolsky 和 Victor Stinner 在 bpo-1289118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1289118}, bpo-5094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5094}, bpo-6641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6641}, bpo-2706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2706}, bpo-1777412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1777412}, bpo-8013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8013} 和 bpo-10827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10827} 中贡献。）

@c XXX https://bugs.python.org/issue?%40search_text=datetime&%40sort=-activity

@node math<7>,abc<3>,datetime 和 time,新增，改进和弃用的模块
@anchor{whatsnew/3 2 math}@anchor{c41}
@subsubsection math


@ref{b1,,math} 模块基于 C99 标准增加了六个新函数。

The @ref{c42,,isfinite()} function provides a reliable and fast way to detect
special values.  It returns @code{True} for regular numbers and @code{False} for @emph{Nan} or
@emph{Infinity}:

@example
>>> from math import isfinite
>>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
[True, True, False, False]
@end example

The @ref{c43,,expm1()} function computes @code{e**x-1} for small values of @emph{x}
without incurring the loss of precision that usually accompanies the subtraction
of nearly equal quantities:

@example
>>> from math import expm1
>>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
0.013765762467652909
@end example

The @ref{55c,,erf()} function computes a probability integral or Gaussian error function@footnote{https://en.wikipedia.org/wiki/Error_function}.  The
complementary error function, @ref{55d,,erfc()}, is @code{1 - erf(x)}:

@example
>>> from math import erf, erfc, sqrt
>>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
0.682689492137086
>>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
0.31731050786291404
>>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))
1.0
@end example

The @ref{c44,,gamma()} function is a continuous extension of the factorial
function.  See @indicateurl{https://en.wikipedia.org/wiki/Gamma_function} for details.  Because
the function is related to factorials, it grows large even for small values of
@emph{x}, so there is also a @ref{c45,,lgamma()} function for computing the natural
logarithm of the gamma function:

@example
>>> from math import gamma, lgamma
>>> gamma(7.0)           # six factorial
720.0
>>> lgamma(801.0)        # log(800 factorial)
4551.950730698041
@end example

（由 Mark Dickinson 贡献）

@node abc<3>,io<5>,math<7>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 abc}@anchor{c46}
@subsubsection abc


The @ref{3,,abc} module now supports @ref{ab7,,abstractclassmethod()} and
@ref{ab8,,abstractstaticmethod()}.

These tools make it possible to define an @ref{c0e,,abstract base class} that
requires a particular @ref{310,,classmethod()} or @ref{311,,staticmethod()} to be
implemented:

@example
class Temperature(metaclass=abc.ABCMeta):
    @@abc.abstractclassmethod
    def from_fahrenheit(cls, t):
        ...
    @@abc.abstractclassmethod
    def from_celsius(cls, t):
        ...
@end example

(Patch submitted by Daniel Urban; bpo-5867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5867}.)

@node io<5>,reprlib,abc<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 io}@anchor{c47}
@subsubsection io


The @ref{894,,io.BytesIO} has a new method, @ref{c48,,getbuffer()}, which
provides functionality similar to @ref{38d,,memoryview()}.  It creates an editable
view of the data without making a copy.  The buffer's random access and support
for slice notation are well-suited to in-place editing:

@example
>>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11

>>> def change_location(buffer, record_number, location):
...     start = record_number * REC_LEN + LOC_START
...     buffer[start: start+LOC_LEN] = location

>>> import io

>>> byte_stream = io.BytesIO(
...     b'G3805  storeroom  Main chassis    '
...     b'X7899  shipping   Reserve cog     '
...     b'L6988  receiving  Primary sprocket'
... )
>>> buffer = byte_stream.getbuffer()
>>> change_location(buffer, 1, b'warehouse  ')
>>> change_location(buffer, 0, b'showroom   ')
>>> print(byte_stream.getvalue())
b'G3805  showroom   Main chassis    '
b'X7899  warehouse  Reserve cog     '
b'L6988  receiving  Primary sprocket'
@end example

（由 Antoine Pitrou 在 bpo-5506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5506} 中贡献。）

@node reprlib,logging<7>,io<5>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 reprlib}@anchor{c49}
@subsubsection reprlib


When writing a @ref{453,,__repr__()} method for a custom container, it is easy to
forget to handle the case where a member refers back to the container itself.
Python's builtin objects such as @ref{1f9,,list} and @ref{1f7,,set} handle
self-reference by displaying "..." in the recursive part of the representation
string.

To help write such @ref{453,,__repr__()} methods, the @ref{df,,reprlib} module has a new
decorator, @ref{c4a,,recursive_repr()}, for detecting recursive calls to
@ref{453,,__repr__()} and substituting a placeholder string instead:

@example
>>> class MyList(list):
...     @@recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
@end example

（由 Raymond Hettinger 在 bpo-9826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9826} 和  bpo-9840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9840} 中贡献。）

@node logging<7>,csv<3>,reprlib,新增，改进和弃用的模块
@anchor{whatsnew/3 2 logging}@anchor{c4b}
@subsubsection logging


In addition to dictionary-based configuration described above, the
@ref{aa,,logging} package has many other improvements.

The logging documentation has been augmented by a @ref{c4c,,basic tutorial}, an @ref{c4d,,advanced tutorial}, and a @ref{c4e,,cookbook} of
logging recipes.  These documents are the fastest way to learn about logging.

The @ref{318,,logging.basicConfig()} set-up function gained a @emph{style} argument to
support three different types of string formatting.  It defaults to "%" for
traditional %-formatting, can be set to "@{" for the new @ref{5dd,,str.format()} style, or
can be set to "$" for the shell-style formatting provided by
@ref{4f9,,string.Template}.  The following three configurations are equivalent:

@example
>>> from logging import basicConfig
>>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
>>> basicConfig(style='@{', format="@{name@} -> @{levelname@} @{message@}")
>>> basicConfig(style='$', format="$name -> $levelname: $message")
@end example

If no configuration is set-up before a logging event occurs, there is now a
default configuration using a @ref{c4f,,StreamHandler} directed to
@ref{1eb,,sys.stderr} for events of @code{WARNING} level or higher.  Formerly, an
event occurring before a configuration was set-up would either raise an
exception or silently drop the event depending on the value of
@code{logging.raiseExceptions}.  The new default handler is stored in
@ref{c50,,logging.lastResort}.

The use of filters has been simplified.  Instead of creating a
@ref{c51,,Filter} object, the predicate can be any Python callable that
returns @code{True} or @code{False}.

There were a number of other improvements that add flexibility and simplify
configuration.  See the module documentation for a full listing of changes in
Python 3.2.

@node csv<3>,contextlib<6>,logging<7>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 csv}@anchor{c52}
@subsubsection csv


The @ref{29,,csv} module now supports a new dialect, @ref{c53,,unix_dialect},
which applies quoting for all fields and a traditional Unix style with @code{'\n'} as
the line terminator.  The registered dialect name is @code{unix}.

The @ref{c54,,csv.DictWriter} has a new method,
@ref{c55,,writeheader()} for writing-out an initial row to document
the field names:

@example
>>> import csv, sys
>>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
>>> w.writeheader()
"name","dept"
>>> w.writerows([
...     @{'name': 'tom', 'dept': 'accounting'@},
...     @{'name': 'susan', 'dept': 'Salesl'@}])
"tom","accounting"
"susan","sales"
@end example

(New dialect suggested by Jay Talbot in bpo-5975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5975}, and the new method
suggested by Ed Abraham in bpo-1537721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537721}.)

@node contextlib<6>,decimal and fractions,csv<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 contextlib}@anchor{c56}
@subsubsection contextlib


There is a new and slightly mind-blowing tool
@ref{c57,,ContextDecorator} that is helpful for creating a
@ref{66b,,context manager} that does double duty as a function decorator.

As a convenience, this new functionality is used by
@ref{c58,,contextmanager()} so that no extra effort is needed to support
both roles.

The basic idea is that both context managers and function decorators can be used
for pre-action and post-action wrappers.  Context managers wrap a group of
statements using a @ref{7e4,,with} statement, and function decorators wrap a
group of statements enclosed in a function.  So, occasionally there is a need to
write a pre-action or post-action wrapper that can be used in either role.

For example, it is sometimes useful to wrap functions or groups of statements
with a logger that can track the time of entry and time of exit.  Rather than
writing both a function decorator and a context manager for the task, the
@ref{c58,,contextmanager()} provides both capabilities in a single
definition:

@example
from contextlib import contextmanager
import logging

logging.basicConfig(level=logging.INFO)

@@contextmanager
def track_entry_and_exit(name):
    logging.info('Entering: %s', name)
    yield
    logging.info('Exiting: %s', name)
@end example

Formerly, this would have only been usable as a context manager:

@example
with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()
@end example

Now, it can be used as a decorator as well:

@example
@@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()
@end example

Trying to fulfill two roles at once places some limitations on the technique.
Context managers normally have the flexibility to return an argument usable by
a @ref{7e4,,with} statement, but there is no parallel for function decorators.

In the above example, there is not a clean way for the @emph{track_entry_and_exit}
context manager to return a logging instance for use in the body of enclosed
statements.

（由 Michael Foord 在 bpo-9110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9110} 中贡献。）

@node decimal and fractions,ftp,contextlib<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 decimal-and-fractions}@anchor{c59}
@subsubsection decimal and fractions


Mark Dickinson crafted an elegant and efficient scheme for assuring that
different numeric datatypes will have the same hash value whenever their actual
values are equal (bpo-8188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8188}):

@example
assert hash(Fraction(3, 2)) == hash(1.5) == \
       hash(Decimal("1.5")) == hash(complex(1.5, 0))
@end example

Some of the hashing details are exposed through a new attribute,
@ref{a0f,,sys.hash_info}, which describes the bit width of the hash value, the
prime modulus, the hash values for @emph{infinity} and @emph{nan}, and the multiplier
used for the imaginary part of a number:

@example
>>> sys.hash_info 
sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)
@end example

An early decision to limit the inter-operability of various numeric types has
been relaxed.  It is still unsupported (and ill-advised) to have implicit
mixing in arithmetic expressions such as @code{Decimal('1.1') + float('1.1')}
because the latter loses information in the process of constructing the binary
float.  However, since existing floating point value can be converted losslessly
to either a decimal or rational representation, it makes sense to add them to
the constructor and to support mixed-type comparisons.


@itemize *

@item 
The @ref{2c7,,decimal.Decimal} constructor now accepts @ref{1fe,,float} objects
directly so there in no longer a need to use the @ref{c5a,,from_float()}
method (bpo-8257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8257}).

@item 
Mixed type comparisons are now fully supported so that
@ref{2c7,,Decimal} objects can be directly compared with @ref{1fe,,float}
and @ref{2c5,,fractions.Fraction} (bpo-2531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2531} and bpo-8188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8188}).
@end itemize

Similar changes were made to @ref{2c5,,fractions.Fraction} so that the
@ref{c5b,,from_float()} and @ref{c5c,,from_decimal()}
methods are no longer needed (bpo-8294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8294}):

@example
>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
@end example

Another useful change for the @ref{35,,decimal} module is that the
@code{Context.clamp} attribute is now public.  This is useful in creating
contexts that correspond to the decimal interchange formats specified in IEEE
754 (see bpo-8540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8540}).

（由 Mark Dickinson 和 Raymond Hettinger贡献。）

@node ftp,popen,decimal and fractions,新增，改进和弃用的模块
@anchor{whatsnew/3 2 ftp}@anchor{c5d}
@subsubsection ftp


The @ref{1a6,,ftplib.FTP} class now supports the context management protocol to
unconditionally consume @ref{a7f,,socket.error} exceptions and to close the FTP
connection when done:

@example
>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
        ftp.login()
        ftp.dir()

'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
@end example

其他文件类对象如 @ref{323,,mmap.mmap} 和 @ref{3d7,,fileinput.input()} 也有了支持自动关闭的上下文管理器:

@example
with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
    for line in f:
        process(line)
@end example

（由 Tarek Ziadé 和 Giampaolo Rodolà 在 bpo-4972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4972} 贡献，由 Georg Brandl 在 bpo-8046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8046} 和 bpo-1286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1286} 贡献。）

The @ref{1a7,,FTP_TLS} class now accepts a @emph{context} parameter, which is a
@ref{4f2,,ssl.SSLContext} object allowing bundling SSL configuration options,
certificates and private keys into a single (potentially long-lived) structure.

（由 Giampaolo Rodolà 在 bpo-8806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8806} 中贡献。）

@node popen,select<3>,ftp,新增，改进和弃用的模块
@anchor{whatsnew/3 2 popen}@anchor{c5e}
@subsubsection popen


@ref{3d3,,os.popen()} 和 @ref{3e3,,subprocess.Popen()} 函数现在支持使用 @ref{7e4,,with} 语句来自动关闭文件描述符。

（由 Antoine Pitrou 和 Brian Curtin 在 bpo-7461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7461} 和 bpo-10554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10554} 中贡献。）

@node select<3>,gzip 和 zipfile,popen,新增，改进和弃用的模块
@anchor{whatsnew/3 2 select}@anchor{c5f}
@subsubsection select


The @ref{e5,,select} module now exposes a new, constant attribute,
@ref{c60,,PIPE_BUF}, which gives the minimum number of bytes which are
guaranteed not to block when @ref{770,,select.select()} says a pipe is ready
for writing.

@example
>>> import select
>>> select.PIPE_BUF  
512
@end example

(Available on Unix systems. Patch by Sébastien Sablé in bpo-9862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9862})

@node gzip 和 zipfile,tarfile<6>,select<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 gzip-and-zipfile}@anchor{c61}
@subsubsection gzip 和 zipfile


@ref{207,,gzip.GzipFile} now implements the @ref{689,,io.BufferedIOBase}
@ref{c0e,,abstract base class} (except for @code{truncate()}).  It also has a
@ref{c62,,peek()} method and supports unseekable as well as
zero-padded file objects.

The @ref{8b,,gzip} module also gains the @ref{309,,compress()} and
@ref{c63,,decompress()} functions for easier in-memory compression and
decompression.  Keep in mind that text needs to be encoded as @ref{172,,bytes}
before compressing and decompressing:

@example
>>> import gzip
>>> s = 'Three shall be the number thou shalt count, '
>>> s += 'and the number of the counting shall be three'
>>> b = s.encode()                        # convert to utf-8
>>> len(b)
89
>>> c = gzip.compress(b)
>>> len(c)
77
>>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
'Three shall be the number thou shalt count'
@end example

（由 Anand B. Pillai 在 bpo-3488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3488} 中贡献，由Antoine Pitrou, Nir Aides 和 Brian Curtin 在 bpo-9962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9962}，bpo-1675951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1675951} ，bpo-7471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7471} 和 bpo-2846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2846} 中贡献。）

Also, the @code{zipfile.ZipExtFile} class was reworked internally to represent
files stored inside an archive.  The new implementation is significantly faster
and can be wrapped in an @ref{c64,,io.BufferedReader} object for more speedups.  It
also solves an issue where interleaved calls to @emph{read} and @emph{readline} gave the
wrong results.

（补丁由 Nir Aides 在 bpo-7610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7610} 中提交。）

@node tarfile<6>,hashlib<4>,gzip 和 zipfile,新增，改进和弃用的模块
@anchor{whatsnew/3 2 tarfile}@anchor{c65}
@subsubsection tarfile


The @ref{c66,,TarFile} class can now be used as a context manager.  In
addition, its @ref{583,,add()} method has a new option, @emph{filter},
that controls which files are added to the archive and allows the file metadata
to be edited.

The new @emph{filter} option replaces the older, less flexible @emph{exclude} parameter
which is now deprecated.  If specified, the optional @emph{filter} parameter needs to
be a @ref{6c5,,keyword argument}.  The user-supplied filter function accepts a
@ref{c67,,TarInfo} object and returns an updated
@ref{c67,,TarInfo} object, or if it wants the file to be excluded, the
function can return @code{None}:

@example
>>> import tarfile, glob

>>> def myfilter(tarinfo):
...     if tarinfo.isfile():             # only save real files
...         tarinfo.uname = 'monty'      # redact the user name
...         return tarinfo

>>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
...     for filename in glob.glob('*.txt'):
...         tf.add(filename, filter=myfilter)
...     tf.list()
-rw-r--r-- monty/501        902 2011-01-26 17:59:11 annotations.txt
-rw-r--r-- monty/501        123 2011-01-26 17:59:11 general_questions.txt
-rw-r--r-- monty/501       3514 2011-01-26 17:59:11 prion.txt
-rw-r--r-- monty/501        124 2011-01-26 17:59:11 py_todo.txt
-rw-r--r-- monty/501       1399 2011-01-26 17:59:11 semaphore_notes.txt
@end example

(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in bpo-6856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6856}.)

@node hashlib<4>,ast<4>,tarfile<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 hashlib}@anchor{c68}
@subsubsection hashlib


The @ref{8c,,hashlib} module has two new constant attributes listing the hashing
algorithms guaranteed to be present in all implementations and those available
on the current implementation:

@example
>>> import hashlib

>>> hashlib.algorithms_guaranteed
@{'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'@}

>>> hashlib.algorithms_available
@{'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'@}
@end example

（由 Carl Chenet 在 bpo-7418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7418} 中建议。）

@node ast<4>,os<9>,hashlib<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 ast}@anchor{c69}
@subsubsection ast


The @ref{7,,ast} module has a wonderful a general-purpose tool for safely
evaluating expression strings using the Python literal
syntax.  The @ref{5a8,,ast.literal_eval()} function serves as a secure alternative to
the builtin @ref{c6a,,eval()} function which is easily abused.  Python 3.2 adds
@ref{172,,bytes} and @ref{1f7,,set} literals to the list of supported types:
strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and @code{None}.

@example
>>> from ast import literal_eval

>>> request = "@{'req': 3, 'func': 'pow', 'args': (2, 0.5)@}"
>>> literal_eval(request)
@{'args': (2, 0.5), 'req': 3, 'func': 'pow'@}

>>> request = "os.system('do something harmful')"
>>> literal_eval(request)
Traceback (most recent call last):
  ...
ValueError: malformed node or string: <_ast.Call object at 0x101739a10>
@end example

（由Benjamin Peterson 和 Georg Brandl 实现。）

@node os<9>,shutil<5>,ast<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 os}@anchor{c6b}
@subsubsection os


Different operating systems use various encodings for filenames and environment
variables.  The @ref{c4,,os} module provides two new functions,
@ref{5f2,,fsencode()} and @ref{5f1,,fsdecode()}, for encoding and decoding
filenames:

@example
>>> import os
>>> filename = 'Sehenswürdigkeiten'
>>> os.fsencode(filename)
b'Sehensw\xc3\xbcrdigkeiten'
@end example

Some operating systems allow direct access to encoded bytes in the
environment.  If so, the @ref{c6c,,os.supports_bytes_environ} constant will be
true.

For direct access to encoded environment variables (if available),
use the new @ref{c6d,,os.getenvb()} function or use @ref{c6e,,os.environb}
which is a bytes version of @ref{c12,,os.environ}.

（由 Victor Stinner 贡献。）

@node shutil<5>,sqlite3<6>,os<9>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 shutil}@anchor{c6f}
@subsubsection shutil


The @ref{34e,,shutil.copytree()} function has two new options:


@itemize *

@item 
@emph{ignore_dangling_symlinks}: when @code{symlinks=False} so that the function
copies a file pointed to by a symlink, not the symlink itself. This option
will silence the error raised if the file doesn't exist.

@item 
@emph{copy_function}: is a callable that will be used to copy files.
@ref{38b,,shutil.copy2()} is used by default.
@end itemize

（由 Tarek Ziadé 贡献。）

In addition, the @ref{e9,,shutil} module now supports @ref{c70,,archiving operations} for zipfiles, uncompressed tarfiles, gzipped tarfiles,
and bzipped tarfiles.  And there are functions for registering additional
archiving file formats (such as xz compressed tarfiles or custom formats).

The principal functions are @ref{34f,,make_archive()} and
@ref{28b,,unpack_archive()}.  By default, both operate on the current
directory (which can be set by @ref{16e,,os.chdir()}) and on any sub-directories.
The archive filename needs to be specified with a full pathname.  The archiving
step is non-destructive (the original files are left unchanged).

@example
>>> import shutil, pprint

>>> os.chdir('mydata')  # change to the source directory
>>> f = shutil.make_archive('/var/backup/mydata',
...                         'zip')      # archive the current directory
>>> f                                   # show the name of archive
'/var/backup/mydata.zip'
>>> os.chdir('tmp')                     # change to an unpacking
>>> shutil.unpack_archive('/var/backup/mydata.zip')  # recover the data

>>> pprint.pprint(shutil.get_archive_formats())  # display known formats
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('zip', 'ZIP file')]

>>> shutil.register_archive_format(     # register a new archive format
...     name='xz',
...     function=xz.compress,           # callable archiving function
...     extra_args=[('level', 8)],      # arguments to the function
...     description='xz compression'
... )
@end example

（由 Tarek Ziadé 贡献。）

@node sqlite3<6>,html<3>,shutil<5>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 sqlite3}@anchor{c71}
@subsubsection sqlite3


@ref{f2,,sqlite3} 模块被更新至 pysqlite 2.6.0 版。 它拥有两个新功能。


@itemize *

@item 
The @code{sqlite3.Connection.in_transit} attribute is true if there is an
active transaction for uncommitted changes.

@item 
The @ref{c72,,sqlite3.Connection.enable_load_extension()} and
@ref{c73,,sqlite3.Connection.load_extension()} methods allows you to load SQLite
extensions from ".so" files.  One well-known extension is the fulltext-search
extension distributed with SQLite.
@end itemize

（由 R. David Murray 和 Shashwat Anand 在 bpo-8845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8845} 中贡献。）

@node html<3>,socket<9>,sqlite3<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 html}@anchor{c74}
@subsubsection html


A new @ref{8f,,html} module was introduced with only a single function,
@ref{a21,,escape()}, which is used for escaping reserved characters from HTML
markup:

@example
>>> import html
>>> html.escape('x > 2 && x < 7')
'x &gt; 2 &amp;&amp; x &lt; 7'
@end example

@node socket<9>,ssl<9>,html<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 socket}@anchor{c75}
@subsubsection socket


@ref{ef,,socket} 模块有两项新改进。


@itemize *

@item 
Socket objects now have a @ref{c76,,detach()} method which puts
the socket into closed state without actually closing the underlying file
descriptor.  The latter can then be reused for other purposes.
(Added by Antoine Pitrou; bpo-8524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8524}.)

@item 
@ref{c77,,socket.create_connection()} now supports the context management protocol
to unconditionally consume @ref{a7f,,socket.error} exceptions and to close the
socket when done.
(Contributed by Giampaolo Rodolà; bpo-9794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9794}.)
@end itemize

@node ssl<9>,nntp,socket<9>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 ssl}@anchor{c78}
@subsubsection ssl


The @ref{f3,,ssl} module added a number of features to satisfy common requirements
for secure (encrypted, authenticated) internet connections:


@itemize *

@item 
A new class, @ref{4f2,,SSLContext}, serves as a container for persistent
SSL data, such as protocol settings, certificates, private keys, and various
other options. It includes a @ref{4f3,,wrap_socket()} for creating
an SSL socket from an SSL context.

@item 
A new function, @ref{4eb,,ssl.match_hostname()}, supports server identity
verification for higher-level protocols by implementing the rules of HTTPS
(from 
@geindex RFC; RFC 2818
RFC 2818@footnote{https://tools.ietf.org/html/rfc2818.html}) which are also suitable for other protocols.

@item 
The @ref{579,,ssl.wrap_socket()} constructor function now takes a @emph{ciphers}
argument.  The @emph{ciphers} string lists the allowed encryption algorithms using
the format described in the OpenSSL documentation@footnote{https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT}.

@item 
When linked against recent versions of OpenSSL, the @ref{f3,,ssl} module now
supports the Server Name Indication extension to the TLS protocol, allowing
multiple "virtual hosts" using different certificates on a single IP port.
This extension is only supported in client mode, and is activated by passing
the @emph{server_hostname} argument to @ref{4f3,,ssl.SSLContext.wrap_socket()}.

@item 
Various options have been added to the @ref{f3,,ssl} module, such as
@ref{c79,,OP_NO_SSLv2} which disables the insecure and obsolete SSLv2
protocol.

@item 
The extension now loads all the OpenSSL ciphers and digest algorithms.  If
some SSL certificates cannot be verified, they are reported as an "unknown
algorithm" error.

@item 
The version of OpenSSL being used is now accessible using the module
attributes @ref{c7a,,ssl.OPENSSL_VERSION} (a string),
@ref{c7b,,ssl.OPENSSL_VERSION_INFO} (a 5-tuple), and
@ref{c7c,,ssl.OPENSSL_VERSION_NUMBER} (an integer).
@end itemize

（由 Antoine Pitrou 在 bpo-8850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8850},  bpo-1589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1589}, bpo-8322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8322}, bpo-5639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5639}, bpo-4870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4870}, bpo-8484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8484} 和 bpo-8321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8321} 中贡献。）

@node nntp,certificates,ssl<9>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 nntp}@anchor{c7d}
@subsubsection nntp


The @ref{c0,,nntplib} module has a revamped implementation with better bytes and
text semantics as well as more practical APIs.  These improvements break
compatibility with the nntplib version in Python 3.1, which was partly
dysfunctional in itself.

Support for secure connections through both implicit (using
@ref{1c8,,nntplib.NNTP_SSL}) and explicit (using @ref{c7e,,nntplib.NNTP.starttls()})
TLS has also been added.

（由 Antoine Pitrou 在 bpo-9360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9360} 中贡献，由 Andrew Vant 在 bpo-1926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1926} 中贡献。）

@node certificates,imaplib<4>,nntp,新增，改进和弃用的模块
@anchor{whatsnew/3 2 certificates}@anchor{c7f}
@subsubsection certificates


@ref{4a2,,http.client.HTTPSConnection}, @ref{c80,,urllib.request.HTTPSHandler}
and @ref{885,,urllib.request.urlopen()} now take optional arguments to allow for
server certificate checking against a set of Certificate Authorities,
as recommended in public uses of HTTPS.

（由 Antoine Pitrou 添加，bpo-9003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9003}。）

@node imaplib<4>,http client<4>,certificates,新增，改进和弃用的模块
@anchor{whatsnew/3 2 imaplib}@anchor{c81}
@subsubsection imaplib


Support for explicit TLS on standard IMAP4 connections has been added through
the new @ref{c82,,imaplib.IMAP4.starttls} method.

（由 Lorenzo M. Catucci 和 Antoine Pitrou 在 bpo-4471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4471} 中贡献。）

@node http client<4>,unittest<6>,imaplib<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 http-client}@anchor{c83}
@subsubsection http.client


There were a number of small API improvements in the @ref{93,,http.client} module.
The old-style HTTP 0.9 simple responses are no longer supported and the @emph{strict}
parameter is deprecated in all classes.

The @ref{4a1,,HTTPConnection} and
@ref{4a2,,HTTPSConnection} classes now have a @emph{source_address}
parameter for a (host, port) tuple indicating where the HTTP connection is made
from.

Support for certificate checking and HTTPS virtual hosts were added to
@ref{4a2,,HTTPSConnection}.

The @ref{652,,request()} method on connection objects
allowed an optional @emph{body} argument so that a @ref{c1d,,file object} could be used
to supply the content of the request.  Conveniently, the @emph{body} argument now
also accepts an @ref{c84,,iterable} object so long as it includes an explicit
@code{Content-Length} header.  This extended interface is much more flexible than
before.

To establish an HTTPS connection through a proxy server, there is a new
@ref{c85,,set_tunnel()} method that sets the host and
port for HTTP Connect tunneling.

To match the behavior of @ref{96,,http.server}, the HTTP client library now also
encodes headers with ISO-8859-1 (Latin-1) encoding.  It was already doing that
for incoming headers, so now the behavior is consistent for both incoming and
outgoing traffic. (See work by Armin Ronacher in bpo-10980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10980}.)

@node unittest<6>,random<3>,http client<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 unittest}@anchor{c86}
@subsubsection unittest


The unittest module has a number of improvements supporting test discovery for
packages, easier experimentation at the interactive prompt, new testcase
methods, improved diagnostic messages for test failures, and better method
names.


@itemize *

@item 
The command-line call @code{python -m unittest} can now accept file paths
instead of module names for running specific tests (bpo-10620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10620}).  The new
test discovery can find tests within packages, locating any test importable
from the top-level directory.  The top-level directory can be specified with
the @cite{-t} option, a pattern for matching files with @code{-p}, and a directory to
start discovery with @code{-s}:

@example
$ python -m unittest discover -s my_proj_dir -p _test.py
@end example

（由 Michael Foord 贡献）

@item 
Experimentation at the interactive prompt is now easier because the
@code{unittest.case.TestCase} class can now be instantiated without
arguments:

@example
>>> from unittest import TestCase
>>> TestCase().assertEqual(pow(2, 3), 8)
@end example

（由 Michael Foord 贡献）

@item 
The @ref{124,,unittest} module has two new methods,
@ref{b9d,,assertWarns()} and
@ref{b9e,,assertWarnsRegex()} to verify that a given warning type
is triggered by the code under test:

@example
with self.assertWarns(DeprecationWarning):
    legacy_function('XYZ')
@end example

（由 Antoine Pitrou 在 bpo-9754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9754} 中贡献。）

Another new method, @ref{c87,,assertCountEqual()} is used to
compare two iterables to determine if their element counts are equal (whether
the same elements are present with the same number of occurrences regardless
of order):

@example
def test_anagram(self):
    self.assertCountEqual('algorithm', 'logarithm')
@end example

（由 Raymond Hettinger 贡献。）

@item 
A principal feature of the unittest module is an effort to produce meaningful
diagnostics when a test fails.  When possible, the failure is recorded along
with a diff of the output.  This is especially helpful for analyzing log files
of failed test runs. However, since diffs can sometime be voluminous, there is
a new @ref{c88,,maxDiff} attribute that sets maximum length of
diffs displayed.

@item 
In addition, the method names in the module have undergone a number of clean-ups.

For example, @ref{c89,,assertRegex()} is the new name for
@code{assertRegexpMatches()} which was misnamed because the
test uses @ref{c8a,,re.search()}, not @ref{c8b,,re.match()}.  Other methods using
regular expressions are now named using short form "Regex" in preference to
"Regexp" -- this matches the names used in other unittest implementations,
matches Python's old name for the @ref{dd,,re} module, and it has unambiguous
camel-casing.

（由 Raymond Hettinger 贡献并由 Ezio Melotti 实现。）

@item 
To improve consistency, some long-standing method aliases are being
deprecated in favor of the preferred names:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

旧名称

@tab

首选名称

@item

@code{assert_()}

@tab

@ref{c8c,,assertTrue()}

@item

@code{assertEquals()}

@tab

@ref{c8d,,assertEqual()}

@item

@code{assertNotEquals()}

@tab

@ref{c8e,,assertNotEqual()}

@item

@code{assertAlmostEquals()}

@tab

@ref{c8f,,assertAlmostEqual()}

@item

@code{assertNotAlmostEquals()}

@tab

@ref{c90,,assertNotAlmostEqual()}

@end multitable

@end quotation

Likewise, the @code{TestCase.fail*} methods deprecated in Python 3.1 are expected
to be removed in Python 3.3.  Also see the @ref{c91,,已弃用的别名} section in
the @ref{124,,unittest} documentation.

（由 Ezio Melotti 在 bpo-9424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9424} 中贡献。）

@item 
The @code{assertDictContainsSubset()} method was deprecated
because it was misimplemented with the arguments in the wrong order.  This
created hard-to-debug optical illusions where tests like
@code{TestCase().assertDictContainsSubset(@{'a':1, 'b':2@}, @{'a':1@})} would fail.

（由 Raymond Hettinger 贡献。）
@end itemize

@node random<3>,poplib<4>,unittest<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 random}@anchor{c92}
@subsubsection random


The integer methods in the @ref{dc,,random} module now do a better job of producing
uniform distributions.  Previously, they computed selections with
@code{int(n*random())} which had a slight bias whenever @emph{n} was not a power of two.
Now, multiple selections are made from a range up to the next power of two and a
selection is kept only when it falls within the range @code{0 <= x < n}.  The
functions and methods affected are @ref{c93,,randrange()},
@ref{c94,,randint()}, @ref{c95,,choice()}, @ref{213,,shuffle()} and
@ref{c96,,sample()}.

（由 Raymond Hettinger 在 bpo-9025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9025} 中贡献。）

@node poplib<4>,asyncore<2>,random<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 poplib}@anchor{c97}
@subsubsection poplib


@ref{1d7,,POP3_SSL} class now accepts a @emph{context} parameter, which is a
@ref{4f2,,ssl.SSLContext} object allowing bundling SSL configuration options,
certificates and private keys into a single (potentially long-lived)
structure.

（由 Giampaolo Rodolà 在 bpo-8807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8807} 中贡献。）

@node asyncore<2>,tempfile<2>,poplib<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 asyncore}@anchor{c98}
@subsubsection asyncore


@ref{c99,,asyncore.dispatcher} now provides a
@ref{c9a,,handle_accepted()} method
returning a @cite{(sock@comma{} addr)} pair which is called when a connection has actually
been established with a new remote endpoint. This is supposed to be used as a
replacement for old @ref{c9b,,handle_accept()} and avoids
the user  to call @ref{c9c,,accept()} directly.

（由 Giampaolo Rodolà 在 bpo-6706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6706} 中贡献。）

@node tempfile<2>,inspect<7>,asyncore<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 tempfile}@anchor{c9d}
@subsubsection tempfile


The @ref{103,,tempfile} module has a new context manager,
@ref{c9e,,TemporaryDirectory} which provides easy deterministic
cleanup of temporary directories:

@example
with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary dir:', tmpdirname)
@end example

（由 Neil Schemenauer 和 Nick Coghlan 在 bpo-5178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5178} 中贡献。）

@node inspect<7>,pydoc<6>,tempfile<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 inspect}@anchor{c9f}
@subsubsection inspect



@itemize *

@item 
@ref{a0,,inspect} 模块有一个新函数 @ref{ca0,,getgeneratorstate()} 用来方便地标识一个生成器迭代器的当前状态:

@example
>>> from inspect import getgeneratorstate
>>> def gen():
...     yield 'demo'
>>> g = gen()
>>> getgeneratorstate(g)
'GEN_CREATED'
>>> next(g)
'demo'
>>> getgeneratorstate(g)
'GEN_SUSPENDED'
>>> next(g, None)
>>> getgeneratorstate(g)
'GEN_CLOSED'
@end example

（由 Rodolpho Eckhardt 和 Nick Coghlan 在 bpo-10220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10220} 中贡献。）

@item 
To support lookups without the possibility of activating a dynamic attribute,
the @ref{a0,,inspect} module has a new function, @ref{ca1,,getattr_static()}.
Unlike @ref{553,,hasattr()}, this is a true read-only search, guaranteed not to
change state while it is searching:

@example
>>> class A:
...     @@property
...     def f(self):
...         print('Running')
...         return 10
...
>>> a = A()
>>> getattr(a, 'f')
Running
10
>>> inspect.getattr_static(a, 'f')
<property object at 0x1022bd788>
@end example
@end itemize

@quotation

（由 Michael Foord 贡献）
@end quotation

@node pydoc<6>,dis<3>,inspect<7>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 pydoc}@anchor{ca2}
@subsubsection pydoc


The @ref{d9,,pydoc} module now provides a much-improved Web server interface, as
well as a new command-line option @code{-b} to automatically open a browser window
to display that server:

@example
$ pydoc3.2 -b
@end example

（由 Ron Adam 在 bpo-2001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2001} 中贡献。）

@node dis<3>,dbm<6>,pydoc<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 dis}@anchor{ca3}
@subsubsection dis


The @ref{37,,dis} module gained two new functions for inspecting code,
@ref{ca4,,code_info()} and @ref{929,,show_code()}.  Both provide detailed code
object information for the supplied function, method, source code string or code
object.  The former returns a string and the latter prints it:

@example
>>> import dis, random
>>> dis.show_code(random.choice)
Name:              choice
Filename:          /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
Argument count:    2
Kw-only arguments: 0
Number of locals:  3
Stack size:        11
Flags:             OPTIMIZED, NEWLOCALS, NOFREE
Constants:
   0: 'Choose a random element from a non-empty sequence.'
   1: 'Cannot choose from an empty sequence'
Names:
   0: _randbelow
   1: len
   2: ValueError
   3: IndexError
Variable names:
   0: self
   1: seq
   2: i
@end example

In addition, the @ref{493,,dis()} function now accepts string arguments
so that the common idiom @code{dis(compile(s, '@w{'}, 'eval'))} can be shortened
to @code{dis(s)}:

@example
>>> dis('3*x+1 if x%2==1 else x//2')
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (2)
              6 BINARY_MODULO
              7 LOAD_CONST               1 (1)
             10 COMPARE_OP               2 (==)
             13 POP_JUMP_IF_FALSE       28
             16 LOAD_CONST               2 (3)
             19 LOAD_NAME                0 (x)
             22 BINARY_MULTIPLY
             23 LOAD_CONST               1 (1)
             26 BINARY_ADD
             27 RETURN_VALUE
        >>   28 LOAD_NAME                0 (x)
             31 LOAD_CONST               0 (2)
             34 BINARY_FLOOR_DIVIDE
             35 RETURN_VALUE
@end example

Taken together, these improvements make it easier to explore how CPython is
implemented and to see for yourself what the language syntax does
under-the-hood.

（由 Nick Coghlan 在 bpo-9147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9147} 中贡献。）

@node dbm<6>,ctypes<2>,dis<3>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 dbm}@anchor{ca5}
@subsubsection dbm


所有数据库模块现在都支持 @code{get()} 和 @code{setdefault()} 方法。

（由 Ray Allen 在 bpo-9523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9523} 中建议。）

@node ctypes<2>,site<2>,dbm<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 ctypes}@anchor{ca6}
@subsubsection ctypes


一个新类型 @ref{ca7,,ctypes.c_ssize_t} 用来表示 C @code{ssize_t} 数据类型。

@node site<2>,sysconfig<2>,ctypes<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 site}@anchor{ca8}
@subsubsection site


The @ref{eb,,site} module has three new functions useful for reporting on the
details of a given Python installation.


@itemize *

@item 
@ref{ca9,,getsitepackages()} lists all global site-packages directories.

@item 
@ref{caa,,getuserbase()} reports on the user's base directory where data can
be stored.

@item 
@ref{cab,,getusersitepackages()} reveals the user-specific site-packages
directory path.
@end itemize

@example
>>> import site
>>> site.getsitepackages()
['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
 '/Library/Python/3.2/site-packages']
>>> site.getuserbase()
'/Users/raymondhettinger/Library/Python/3.2'
>>> site.getusersitepackages()
'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
@end example

Conveniently, some of site's functionality is accessible directly from the
command-line:

@example
$ python -m site --user-base
/Users/raymondhettinger/.local
$ python -m site --user-site
/Users/raymondhettinger/.local/lib/python3.2/site-packages
@end example

（由 Tarek Ziadé 在 bpo-6693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6693} 中贡献。）

@node sysconfig<2>,pdb<6>,site<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 sysconfig}@anchor{cac}
@subsubsection sysconfig


The new @ref{fe,,sysconfig} module makes it straightforward to discover
installation paths and configuration variables that vary across platforms and
installations.

The module offers access simple access functions for platform and version
information:


@itemize *

@item 
@ref{cad,,get_platform()} returning values like @emph{linux-i586} or
@emph{macosx-10.6-ppc}.

@item 
@ref{cae,,get_python_version()} returns a Python version string
such as "3.2".
@end itemize

It also provides access to the paths and variables corresponding to one of
seven named schemes used by @ref{38,,distutils}.  Those include @emph{posix_prefix},
@emph{posix_home}, @emph{posix_user}, @emph{nt}, @emph{nt_user}, @emph{os2}, @emph{os2_home}:


@itemize *

@item 
@ref{caf,,get_paths()} makes a dictionary containing installation paths
for the current installation scheme.

@item 
@ref{a4f,,get_config_vars()} returns a dictionary of platform specific
variables.
@end itemize

还有一个方便的命令行界面：

@example
C:\Python32>python -m sysconfig
Platform: "win32"
Python version: "3.2"
Current installation scheme: "nt"

Paths:
        data = "C:\Python32"
        include = "C:\Python32\Include"
        platinclude = "C:\Python32\Include"
        platlib = "C:\Python32\Lib\site-packages"
        platstdlib = "C:\Python32\Lib"
        purelib = "C:\Python32\Lib\site-packages"
        scripts = "C:\Python32\Scripts"
        stdlib = "C:\Python32\Lib"

Variables:
        BINDIR = "C:\Python32"
        BINLIBDEST = "C:\Python32\Lib"
        EXE = ".exe"
        INCLUDEPY = "C:\Python32\Include"
        LIBDEST = "C:\Python32\Lib"
        SO = ".pyd"
        VERSION = "32"
        abiflags = ""
        base = "C:\Python32"
        exec_prefix = "C:\Python32"
        platbase = "C:\Python32"
        prefix = "C:\Python32"
        projectbase = "C:\Python32"
        py_version = "3.2"
        py_version_nodot = "32"
        py_version_short = "3.2"
        srcdir = "C:\Python32"
        userbase = "C:\Documents and Settings\Raymond\Application Data\Python"
@end example

（由TarekZiadé 移出Distutils。）

@node pdb<6>,configparser<2>,sysconfig<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 pdb}@anchor{cb0}
@subsubsection pdb


The @ref{c9,,pdb} debugger module gained a number of usability improvements:


@itemize *

@item 
@code{pdb.py} now has a @code{-c} option that executes commands as given in a
@code{.pdbrc} script file.

@item 
A @code{.pdbrc} script file can contain @code{continue} and @code{next} commands
that continue debugging.

@item 
The @code{Pdb} class constructor now accepts a @emph{nosigint} argument.

@item 
New commands: @code{l(list)}, @code{ll(long list)} and @code{source} for
listing source code.

@item 
New commands: @code{display} and @code{undisplay} for showing or hiding
the value of an expression if it has changed.

@item 
New command: @code{interact} for starting an interactive interpreter containing
the global and local  names found in the current scope.

@item 
Breakpoints can be cleared by breakpoint number.
@end itemize

（由Georg Brandl, Antonio Cuni 和 Ilya Sandler 贡献。）

@node configparser<2>,urllib parse<4>,pdb<6>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 configparser}@anchor{cb1}
@subsubsection configparser


The @ref{22,,configparser} module was modified to improve usability and
predictability of the default parser and its supported INI syntax.  The old
@code{ConfigParser} class was removed in favor of @code{SafeConfigParser}
which has in turn been renamed to @ref{5ad,,ConfigParser}. Support
for inline comments is now turned off by default and section or option
duplicates are not allowed in a single configuration source.

Config parsers gained a new API based on the mapping protocol:

@example
>>> parser = ConfigParser()
>>> parser.read_string("""
... [DEFAULT]
... location = upper left
... visible = yes
... editable = no
... color = blue
...
... [main]
... title = Main Menu
... color = green
...
... [options]
... title = Options
... """)
>>> parser['main']['color']
'green'
>>> parser['main']['editable']
'no'
>>> section = parser['options']
>>> section['title']
'Options'
>>> section['title'] = 'Options (editable: %(editable)s)'
>>> section['title']
'Options (editable: no)'
@end example

The new API is implemented on top of the classical API, so custom parser
subclasses should be able to use it without modifications.

The INI file structure accepted by config parsers can now be customized. Users
can specify alternative option/value delimiters and comment prefixes, change the
name of the @emph{DEFAULT} section or switch the interpolation syntax.

There is support for pluggable interpolation including an additional interpolation
handler @ref{cb2,,ExtendedInterpolation}:

@example
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> parser.read_dict(@{'buildout': @{'directory': '/home/ambv/zope9'@},
...                   'custom': @{'prefix': '/usr/local'@}@})
>>> parser.read_string("""
... [buildout]
... parts =
...   zope9
...   instance
... find-links =
...   $@{buildout:directory@}/downloads/dist
...
... [zope9]
... recipe = plone.recipe.zope9install
... location = /opt/zope
...
... [instance]
... recipe = plone.recipe.zope9instance
... zope9-location = $@{zope9:location@}
... zope-conf = $@{custom:prefix@}/etc/zope.conf
... """)
>>> parser['buildout']['find-links']
'\n/home/ambv/zope9/downloads/dist'
>>> parser['instance']['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance = parser['instance']
>>> instance['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance['zope9-location']
'/opt/zope'
@end example

A number of smaller features were also introduced, like support for specifying
encoding in read operations, specifying fallback values for get-functions, or
reading directly from dictionaries and strings.

（所有改变均由 Łukasz Langa 贡献。）

@c XXX consider showing a difflib example

@node urllib parse<4>,mailbox,configparser<2>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 urllib-parse}@anchor{cb3}
@subsubsection urllib.parse


A number of usability improvements were made for the @ref{128,,urllib.parse} module.

The @ref{6fb,,urlparse()} function now supports IPv6@footnote{https://en.wikipedia.org/wiki/IPv6} addresses as described in 
@geindex RFC; RFC 2732
RFC 2732@footnote{https://tools.ietf.org/html/rfc2732.html}:

@example
>>> import urllib.parse
>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') 
ParseResult(scheme='http',
            netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
            path='/foo/',
            params='@w{'},
            query='@w{'},
            fragment='@w{'})
@end example

The @ref{cb4,,urldefrag()} function now returns a @ref{b84,,named tuple}:

@example
>>> r = urllib.parse.urldefrag('http://python.org/about/#target')
>>> r
DefragResult(url='http://python.org/about/', fragment='target')
>>> r[0]
'http://python.org/about/'
>>> r.fragment
'target'
@end example

And, the @ref{884,,urlencode()} function is now much more flexible,
accepting either a string or bytes type for the @emph{query} argument.  If it is a
string, then the @emph{safe}, @emph{encoding}, and @emph{error} parameters are sent to
@ref{cb5,,quote_plus()} for encoding:

@example
>>> urllib.parse.urlencode([
...      ('type', 'telenovela'),
...      ('name', '¿Dónde Está Elisa?')],
...      encoding='latin-1')
'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'
@end example

As detailed in @ref{cb6,,解析ASCII编码字节}, all the @ref{128,,urllib.parse}
functions now accept ASCII-encoded byte strings as input, so long as they are
not mixed with regular strings.  If ASCII-encoded byte strings are given as
parameters, the return types will also be an ASCII-encoded byte strings:

@example
>>> urllib.parse.urlparse(b'http://www.python.org:80/about/') 
ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
                 path=b'/about/', params=b'@w{'}, query=b'@w{'}, fragment=b'@w{'})
@end example

(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in bpo-2987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2987},
bpo-5468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5468}, and bpo-9873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9873}.)

@node mailbox,turtledemo,urllib parse<4>,新增，改进和弃用的模块
@anchor{whatsnew/3 2 mailbox}@anchor{cb7}
@subsubsection mailbox


Thanks to a concerted effort by R. David Murray, the @ref{ae,,mailbox} module has
been fixed for Python 3.2.  The challenge was that mailbox had been originally
designed with a text interface, but email messages are best represented with
@ref{172,,bytes} because various parts of a message may have different encodings.

The solution harnessed the @ref{67,,email} package's binary support for parsing
arbitrary email messages.  In addition, the solution required a number of API
changes.

As expected, the @ref{cb8,,add()} method for
@ref{cb9,,mailbox.Mailbox} objects now accepts binary input.

@ref{924,,StringIO} and text file input are deprecated.  Also, string input
will fail early if non-ASCII characters are used.  Previously it would fail when
the email was processed in a later step.

There is also support for binary output.  The @ref{cba,,get_file()}
method now returns a file in the binary mode (where it used to incorrectly set
the file to text-mode).  There is also a new @ref{cbb,,get_bytes()}
method that returns a @ref{172,,bytes} representation of a message corresponding
to a given @emph{key}.

It is still possible to get non-binary output using the old API's
@ref{cbc,,get_string()} method, but that approach
is not very useful.  Instead, it is best to extract messages from
a @ref{cbd,,Message} object or to load them from binary input.

(Contributed by R. David Murray, with efforts from Steffen Daode Nurpmeso and an
initial patch by Victor Stinner in bpo-9124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9124}.)

@node turtledemo,,mailbox,新增，改进和弃用的模块
@anchor{whatsnew/3 2 turtledemo}@anchor{cbe}
@subsubsection turtledemo


The demonstration code for the @ref{11f,,turtle} module was moved from the @emph{Demo}
directory to main library.  It includes over a dozen sample scripts with
lively displays.  Being on @ref{262,,sys.path}, it can now be run directly
from the command-line:

@example
$ python -m turtledemo
@end example

(Moved from the Demo directory by Alexander Belopolsky in bpo-10199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10199}.)

@node 多线程,性能优化<7>,新增，改进和弃用的模块,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 multi-threading}@anchor{cbf}
@subsection 多线程



@itemize *

@item 
The mechanism for serializing execution of concurrently running Python threads
(generally known as the @ref{20f,,GIL} or Global Interpreter Lock) has
been rewritten.  Among the objectives were more predictable switching
intervals and reduced overhead due to lock contention and the number of
ensuing system calls.  The notion of a "check interval" to allow thread
switches has been abandoned and replaced by an absolute duration expressed in
seconds.  This parameter is tunable through @ref{219,,sys.setswitchinterval()}.
It currently defaults to 5 milliseconds.

Additional details about the implementation can be read from a python-dev mailing-list message@footnote{https://mail.python.org/pipermail/python-dev/2009-October/093321.html}
(however, "priority requests" as exposed in this message have not been kept
for inclusion).

（由 Antoine Pitrou 贡献。）

@item 
Regular and recursive locks now accept an optional @emph{timeout} argument to their
@ref{865,,acquire()} method.  (Contributed by Antoine Pitrou;
bpo-7316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7316}.)

@item 
Similarly, @ref{cc0,,threading.Semaphore.acquire()} also gained a @emph{timeout}
argument.  (Contributed by Torsten Landschoff; bpo-850728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=850728}.)

@item 
Regular and recursive lock acquisitions can now be interrupted by signals on
platforms using Pthreads.  This means that Python programs that deadlock while
acquiring locks can be successfully killed by repeatedly sending SIGINT to the
process (by pressing @code{Ctrl+C} in most shells).
(Contributed by Reid Kleckner; bpo-8844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8844}.)
@end itemize

@node 性能优化<7>,Unicode,多线程,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 optimizations}@anchor{cc1}
@subsection 性能优化


A number of small performance enhancements have been added:


@itemize *

@item 
Python's peephole optimizer now recognizes patterns such @code{x in @{1, 2, 3@}} as
being a test for membership in a set of constants.  The optimizer recasts the
@ref{1f7,,set} as a @ref{1f8,,frozenset} and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing
membership tests using set-notation.  This style is both semantically clear
and operationally fast:

@example
extension = name.rpartition('.')[2]
if extension in @{'xml', 'html', 'xhtml', 'css'@}:
    handle(name)
@end example

(Patch and additional tests contributed by Dave Malcolm; bpo-6690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6690}).

@item 
Serializing and unserializing data using the @ref{ca,,pickle} module is now
several times faster.

（由 Alexandre Vassalotti, Antoine Pitrou 和 Unladen Swallow 团队在 bpo-9410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9410} 和 bpo-3873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3873} 中贡献。）

@item 
The Timsort algorithm@footnote{https://en.wikipedia.org/wiki/Timsort} used in
@ref{550,,list.sort()} and @ref{54f,,sorted()} now runs faster and uses less memory
when called with a @ref{7dc,,key function}.  Previously, every element of
a list was wrapped with a temporary object that remembered the key value
associated with each element.  Now, two arrays of keys and values are
sorted in parallel.  This saves the memory consumed by the sort wrappers,
and it saves time lost to delegating comparisons.

(Patch by Daniel Stutzbach in bpo-9915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9915}.)

@item 
JSON decoding performance is improved and memory consumption is reduced
whenever the same string is repeated for multiple keys.  Also, JSON encoding
now uses the C speedups when the @code{sort_keys} argument is true.

（由Antoine Pitrou 在 bpo-7451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7451} 中贡献，由 Raymond Hettinger 和 Antoine Pitrou 在 bpo-10314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10314} 中贡献。）

@item 
Recursive locks (created with the @ref{cc2,,threading.RLock()} API) now benefit
from a C implementation which makes them as fast as regular locks, and between
10x and 15x faster than their previous pure Python implementation.

（由 Antoine Pitrou 在 bpo-3001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3001} 中贡献。）

@item 
The fast-search algorithm in stringlib is now used by the @code{split()},
@code{rsplit()}, @code{splitlines()} and @code{replace()} methods on
@ref{172,,bytes}, @ref{173,,bytearray} and @ref{206,,str} objects. Likewise, the
algorithm is also used by @code{rfind()}, @code{rindex()}, @code{rsplit()} and
@code{rpartition()}.

(Patch by Florent Xicluna in bpo-7622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7622} and bpo-7462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7462}.)

@item 
Integer to string conversions now work two "digits" at a time, reducing the
number of division and modulo operations.

(bpo-6713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6713} by Gawain Bolton, Mark Dickinson, and Victor Stinner.)
@end itemize

There were several other minor optimizations. Set differencing now runs faster
when one operand is much larger than the other (patch by Andress Bennetts in
bpo-8685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8685}).  The @code{array.repeat()} method has a faster implementation
(bpo-1569291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1569291} by Alexander Belopolsky). The @code{BaseHTTPRequestHandler}
has more efficient buffering (bpo-3709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3709} by Andrew Schaaf).  The
@ref{814,,operator.attrgetter()} function has been sped-up (bpo-10160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10160} by
Christos Georgiou).  And @code{ConfigParser} loads multi-line arguments a bit
faster (bpo-7113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7113} by Łukasz Langa).

@node Unicode,编解码器,性能优化<7>,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 unicode}@anchor{cc3}
@subsection Unicode


Python has been updated to Unicode 6.0.0@footnote{http://unicode.org/versions/Unicode6.0.0/}.  The update to the standard adds
over 2,000 new characters including emoji@footnote{https://en.wikipedia.org/wiki/Emoji}
symbols which are important for mobile phones.

In addition, the updated standard has altered the character properties for two
Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric character
(U+19DA), making the former eligible for use in identifiers while disqualifying
the latter.  For more information, see Unicode Character Database Changes@footnote{http://www.unicode.org/versions/Unicode6.0.0/#Database_Changes}.

@node 编解码器,文档,Unicode,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 codecs}@anchor{cc4}
@subsection 编解码器


Support was added for @emph{cp720} Arabic DOS encoding (bpo-1616979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1616979}).

MBCS encoding no longer ignores the error handler argument. In the default
strict mode, it raises an @ref{332,,UnicodeDecodeError} when it encounters an
undecodable byte sequence and an @ref{331,,UnicodeEncodeError} for an unencodable
character.

The MBCS codec supports @code{'strict'} and @code{'ignore'} error handlers for
decoding, and @code{'strict'} and @code{'replace'} for encoding.

To emulate Python3.1 MBCS encoding, select the @code{'ignore'} handler for decoding
and the @code{'replace'} handler for encoding.

On Mac OS X, Python decodes command line arguments with @code{'utf-8'} rather than
the locale encoding.

By default, @ref{101,,tarfile} uses @code{'utf-8'} encoding on Windows (instead of
@code{'mbcs'}) and the @code{'surrogateescape'} error handler on all operating
systems.

@node 文档,IDLE,编解码器,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 documentation}@anchor{cc5}
@subsection 文档


The documentation continues to be improved.


@itemize *

@item 
A table of quick links has been added to the top of lengthy sections such as
@ref{cc6,,内置函数}.  In the case of @ref{a3,,itertools}, the links are
accompanied by tables of cheatsheet-style summaries to provide an overview and
memory jog without having to read all of the docs.

@item 
In some cases, the pure Python source code can be a helpful adjunct to the
documentation, so now many modules now feature quick links to the latest
version of the source code.  For example, the @ref{83,,functools} module
documentation has a quick link at the top labeled:

@quotation

@strong{源代码} Lib/functools.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/functools.py}.
@end quotation

（由 Raymond Hettinger 贡献，参见 rationale@footnote{https://rhettinger.wordpress.com/2011/01/28/open-your-source-more/}。）

@item 
The docs now contain more examples and recipes.  In particular, @ref{dd,,re}
module has an extensive section, @ref{cc7,,正则表达式例子}.  Likewise, the
@ref{a3,,itertools} module continues to be updated with new
@ref{cc8,,itertools 配方}.

@item 
The @ref{30,,datetime} module now has an auxiliary implementation in pure Python.
No functionality was changed.  This just provides an easier-to-read alternate
implementation.

（由 Alexander Belopolsky 在 bpo-9528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9528} 中贡献。）

@item 
The unmaintained @code{Demo} directory has been removed.  Some demos were
integrated into the documentation, some were moved to the @code{Tools/demo}
directory, and others were removed altogether.

（由 Georg Brandl 在 bpo-7962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7962} 中贡献）
@end itemize

@node IDLE,代码库,文档,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 idle}@anchor{cc9}
@subsection IDLE



@itemize *

@item 
The format menu now has an option to clean source files by stripping
trailing whitespace.

（由 Raymond Hettinger 在 bpo-5150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5150} 中贡献。）

@item 
IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa AquaTk.

（由 Kevin Walzer, Ned Deily 和 Ronald Oussoren 在 bpo-6075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6075} 中贡献。）
@end itemize

@node 代码库,构建和 C API 的改变<5>,IDLE,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 code-repository}@anchor{cca}
@subsection 代码库


In addition to the existing Subversion code repository at @indicateurl{http://svn.python.org}
there is now a Mercurial@footnote{https://www.mercurial-scm.org/} repository at
@indicateurl{https://hg.python.org/}.

After the 3.2 release, there are plans to switch to Mercurial as the primary
repository.  This distributed version control system should make it easier for
members of the community to create and share external changesets.  See
@geindex Python 提高建议; PEP 385
PEP 385@footnote{https://www.python.org/dev/peps/pep-0385} for details.

To learn to use the new version control system, see the Quick Start@footnote{https://www.mercurial-scm.org/wiki/QuickStart} or the Guide to Mercurial Workflows@footnote{https://www.mercurial-scm.org/guide}.

@node 构建和 C API 的改变<5>,移植到 Python 3 2,代码库,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 build-and-c-api-changes}@anchor{ccb}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
The @emph{idle}, @emph{pydoc} and @emph{2to3} scripts are now installed with a
version-specific suffix on @code{make altinstall} (bpo-10679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10679}).

@item 
The C functions that access the Unicode Database now accept and return
characters from the full Unicode range, even on narrow unicode builds
(Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others).  A visible difference
in Python is that @ref{ccc,,unicodedata.numeric()} now returns the correct value
for large code points, and @ref{8c3,,repr()} may consider more characters as
printable.

(Reported by Bupjoe Lee and fixed by Amaury Forgeot D'Arc; bpo-5127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5127}.)

@item 
Computed gotos are now enabled by default on supported compilers (which are
detected by the configure script).  They can still be disabled selectively by
specifying @code{--without-computed-gotos}.

（由 Antoine Pitrou 在 bpo-9203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9203} 中贡献。）

@item 
The option @code{--with-wctype-functions} was removed.  The built-in unicode
database is now used for all functions.

（由 Amaury Forgeot d'Arc 在 bpo-9210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9210} 中贡献。）

@item 
Hash values are now values of a new type, @code{Py_hash_t}, which is
defined to be the same size as a pointer.  Previously they were of type long,
which on some 64-bit operating systems is still only 32 bits long.  As a
result of this fix, @ref{1f7,,set} and @ref{164,,dict} can now hold more than
@code{2**32} entries on builds with 64-bit pointers (previously, they could grow
to that size but their performance degraded catastrophically).

(Suggested by Raymond Hettinger and implemented by Benjamin Peterson;
bpo-9778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9778}.)

@item 
A new macro @code{Py_VA_COPY} copies the state of the variable argument
list.  It is equivalent to C99 @emph{va_copy} but available on all Python platforms
(bpo-2443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2443}).

@item 
A new C API function @ref{ccd,,PySys_SetArgvEx()} allows an embedded interpreter
to set @ref{cce,,sys.argv} without also modifying @ref{262,,sys.path}
(bpo-5753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5753}).

@item 
@code{PyEval_CallObject} is now only available in macro form.  The
function declaration, which was kept for backwards compatibility reasons, is
now removed -- the macro was introduced in 1997 (bpo-8276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8276}).

@item 
There is a new function @ref{ccf,,PyLong_AsLongLongAndOverflow()} which
is analogous to @ref{cd0,,PyLong_AsLongAndOverflow()}.  They both serve to
convert Python @ref{205,,int} into a native fixed-width type while providing
detection of cases where the conversion won't fit (bpo-7767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7767}).

@item 
The @ref{cd1,,PyUnicode_CompareWithASCIIString()} function now returns @emph{not
equal} if the Python string is @emph{NUL} terminated.

@item 
There is a new function @ref{cd2,,PyErr_NewExceptionWithDoc()} that is
like @ref{cd3,,PyErr_NewException()} but allows a docstring to be specified.
This lets C exceptions have the same self-documenting capabilities as
their pure Python counterparts (bpo-7033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7033}).

@item 
When compiled with the @code{--with-valgrind} option, the pymalloc
allocator will be automatically disabled when running under Valgrind.  This
gives improved memory leak detection when running under Valgrind, while taking
advantage of pymalloc at other times (bpo-2422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2422}).

@item 
Removed the @code{O?} format from the @emph{PyArg_Parse} functions.  The format is no
longer used and it had never been documented (bpo-8837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8837}).
@end itemize

There were a number of other small changes to the C-API.  See the
Misc/NEWS@footnote{https://github.com/python/cpython/tree/3.9/Misc/NEWS} file for a complete list.

Also, there were a number of updates to the Mac OS X build, see
Mac/BuildScript/README.txt@footnote{https://github.com/python/cpython/tree/3.9/Mac/BuildScript/README.txt} for details.  For users running a 32/64-bit
build, there is a known problem with the default Tcl/Tk on Mac OS X 10.6.
Accordingly, we recommend installing an updated alternative such as
ActiveState Tcl/Tk 8.5.9@footnote{https://www.activestate.com/activetcl/downloads}.
See @indicateurl{https://www.python.org/download/mac/tcltk/} for additional details.

@node 移植到 Python 3 2,,构建和 C API 的改变<5>,Python 3 2 有什么新变化
@anchor{whatsnew/3 2 porting-to-python-3-2}@anchor{cd4}
@subsection 移植到 Python 3.2


This section lists previously described changes and other bugfixes that may
require changes to your code:


@itemize *

@item 
The @ref{22,,configparser} module has a number of clean-ups.  The major change is
to replace the old @code{ConfigParser} class with long-standing preferred
alternative @code{SafeConfigParser}.  In addition there are a number of
smaller incompatibilities:


@itemize *

@item 
The interpolation syntax is now validated on
@ref{cd5,,get()} and
@ref{cd6,,set()} operations. In the default
interpolation scheme, only two tokens with percent signs are valid: @code{%(name)s}
and @code{%%}, the latter being an escaped percent sign.

@item 
The @ref{cd6,,set()} and
@ref{cd7,,add_section()} methods now verify that
values are actual strings.  Formerly, unsupported types could be introduced
unintentionally.

@item 
Duplicate sections or options from a single source now raise either
@ref{cd8,,DuplicateSectionError} or
@ref{cd9,,DuplicateOptionError}.  Formerly, duplicates would
silently overwrite a previous entry.

@item 
Inline comments are now disabled by default so now the @strong{;} character
can be safely used in values.

@item 
Comments now can be indented.  Consequently, for @strong{;} or @strong{#} to appear at
the start of a line in multiline values, it has to be interpolated.  This
keeps comment prefix characters in values from being mistaken as comments.

@item 
@code{""} is now a valid value and is no longer automatically converted to an
empty string. For empty strings, use @code{"option ="} in a line.
@end itemize

@item 
The @ref{c0,,nntplib} module was reworked extensively, meaning that its APIs
are often incompatible with the 3.1 APIs.

@item 
@ref{173,,bytearray} objects can no longer be used as filenames; instead,
they should be converted to @ref{172,,bytes}.

@item 
The @code{array.tostring()} and @code{array.fromstring()} have been renamed to
@code{array.tobytes()} and @code{array.frombytes()} for clarity.  The old names
have been deprecated. (See bpo-8990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8990}.)

@item 
@code{PyArg_Parse*()} 函数:


@itemize *

@item 
"t#" format has been removed: use "s#" or "s*" instead

@item 
"w" and "w#" formats has been removed: use "w*" instead
@end itemize

@item 
The @code{PyCObject} type, deprecated in 3.1, has been removed.  To wrap
opaque C pointers in Python objects, the @ref{cda,,PyCapsule} API should be used
instead; the new type has a well-defined interface for passing typing safety
information and a less complicated signature for calling a destructor.

@item 
The @code{sys.setfilesystemencoding()} function was removed because
it had a flawed design.

@item 
The @ref{cdb,,random.seed()} function and method now salt string seeds with an
sha512 hash function.  To access the previous version of @emph{seed} in order to
reproduce Python 3.1 sequences, set the @emph{version} argument to @emph{1},
@code{random.seed(s, version=1)}.

@item 
The previously deprecated @code{string.maketrans()} function has been removed
in favor of the static methods @ref{cdc,,bytes.maketrans()} and
@ref{cdd,,bytearray.maketrans()}.  This change solves the confusion around which
types were supported by the @ref{f6,,string} module.  Now, @ref{206,,str},
@ref{172,,bytes}, and @ref{173,,bytearray} each have their own @strong{maketrans} and
@strong{translate} methods with intermediate translation tables of the appropriate
type.

（由Georg Brandl在 bpo-5675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5675} 中贡献）

@item 
The previously deprecated @code{contextlib.nested()} function has been removed
in favor of a plain @ref{7e4,,with} statement which can accept multiple
context managers.  The latter technique is faster (because it is built-in),
and it does a better job finalizing multiple context managers when one of them
raises an exception:

@example
with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
    for line in infile:
        if '<critical>' in line:
            outfile.write(line)
@end example

（由 Georg Brandl 和 Mattias Brändström 贡献; appspot issue 53094@footnote{https://codereview.appspot.com/53094}。）

@item 
@ref{cde,,struct.pack()} now only allows bytes for the @code{s} string pack code.
Formerly, it would accept text arguments and implicitly encode them to bytes
using UTF-8.  This was problematic because it made assumptions about the
correct encoding and because a variable-length encoding can fail when writing
to fixed length segment of a structure.

Code such as @code{struct.pack('<6sHHBBB', 'GIF87a', x, y)} should be rewritten
with to use bytes instead of text, @code{struct.pack('<6sHHBBB', b'GIF87a', x, y)}.

(Discovered by David Beazley and fixed by Victor Stinner; bpo-10783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10783}.)

@item 
The @ref{140,,xml.etree.ElementTree} class now raises an
@ref{cdf,,xml.etree.ElementTree.ParseError} when a parse fails. Previously it
raised an @ref{ce0,,xml.parsers.expat.ExpatError}.

@item 
The new, longer @ref{206,,str()} value on floats may break doctests which rely on
the old output format.

@item 
In @ref{3e3,,subprocess.Popen}, the default value for @emph{close_fds} is now
@code{True} under Unix; under Windows, it is @code{True} if the three standard
streams are set to @code{None}, @code{False} otherwise.  Previously, @emph{close_fds}
was always @code{False} by default, which produced difficult to solve bugs
or race conditions when open file descriptors would leak into the child
process.

@item 
Support for legacy HTTP 0.9 has been removed from @ref{129,,urllib.request}
and @ref{93,,http.client}.  Such support is still present on the server side
(in @ref{96,,http.server}).

（由 Antoine Pitrou 在 bpo-10711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10711} 中贡献。）

@item 
SSL sockets in timeout mode now raise @ref{ce1,,socket.timeout} when a timeout
occurs, rather than a generic @ref{ce2,,SSLError}.

（由 Antoine Pitrou 在 bpo-10272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10272} 中贡献。）

@item 
The misleading functions @ref{3dc,,PyEval_AcquireLock()} and
@ref{ce3,,PyEval_ReleaseLock()} have been officially deprecated.  The
thread-state aware APIs (such as @ref{ce4,,PyEval_SaveThread()}
and @ref{3de,,PyEval_RestoreThread()}) should be used instead.

@item 
Due to security risks, @code{asyncore.handle_accept()} has been deprecated, and
a new function, @code{asyncore.handle_accepted()}, was added to replace it.

（由 Giampaolo Rodola 在 bpo-6706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6706} 中贡献。）

@item 
Due to the new @ref{20f,,GIL} implementation, @ref{20d,,PyEval_InitThreads()}
cannot be called before @ref{210,,Py_Initialize()} anymore.
@end itemize

@node Python 3 1 有什么新变化,Python 3 0 有什么新变化,Python 3 2 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 1 doc}@anchor{ce5}@anchor{whatsnew/3 1 what-s-new-in-python-3-1}@anchor{ce6}
@section Python 3.1 有什么新变化


@*作者: 
Raymond Hettinger


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c % Patch 12345
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.

This article explains the new features in Python 3.1, compared to 3.0.

@menu
* PEP 372; 有序字典: PEP 372 有序字典. 
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符. 
* 其他语言特性修改: 其他语言特性修改<9>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<2>. 
* 性能优化: 性能优化<8>. 
* IDLE: IDLE<2>. 
* 构建和 C API 的改变: 构建和 C API 的改变<6>. 
* 移植到 Python 3.1: 移植到 Python 3 1. 

@end menu

@node PEP 372 有序字典,PEP 378 千位分隔符的格式说明符,,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 pep-372-ordered-dictionaries}@anchor{ce7}
@subsection PEP 372: 有序字典


常规的 Python 字典会以任意顺序迭代键/值对。 多年以来，有好几位作者编写了可以记住键的初始插入顺序的替代实现。 基于这些实现的经验，现在引入了新的 @ref{2f1,,collections.OrderedDict} 类。

The OrderedDict API is substantially the same as regular dictionaries
but will iterate over keys and values in a guaranteed order depending on
when a key was first inserted.  If a new entry overwrites an existing entry,
the original insertion position is left unchanged.  Deleting an entry and
reinserting it will move it to the end.

The standard library now supports use of ordered dictionaries in several
modules.  The @ref{22,,configparser} module uses them by default.  This lets
configuration files be read, modified, and then written back in their original
order.  The @emph{_asdict()} method for @ref{1a1,,collections.namedtuple()} now
returns an ordered dictionary with the values appearing in the same order as
the underlying tuple indices.  The @ref{a4,,json} module is being built-out with
an @emph{object_pairs_hook} to allow OrderedDicts to be built by the decoder.
Support was also added for third-party tools like PyYAML@footnote{http://pyyaml.org/}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 372

@item PEP 372@footnote{https://www.python.org/dev/peps/pep-0372} - 有序字典

PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond Hettinger 实现。
@end table


@node PEP 378 千位分隔符的格式说明符,其他语言特性修改<9>,PEP 372 有序字典,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 pep-378-format-specifier-for-thousands-separator}@anchor{ce8}
@subsection PEP 378: 千位分隔符的格式说明符


The built-in @ref{5de,,format()} function and the @ref{5dd,,str.format()} method use
a mini-language that now includes a simple, non-locale aware way to format
a number with a thousands separator.  That provides a way to humanize a
program's output, improving its professional appearance and readability:

@example
>>> format(1234567, ',d')
'1,234,567'
>>> format(1234567.89, ',.2f')
'1,234,567.89'
>>> format(12345.6 + 8901234.12j, ',f')
'12,345.600000+8,901,234.120000j'
>>> format(Decimal('1234567.89'), ',f')
'1,234,567.89'
@end example

支持的类型有 @ref{205,,int}, @ref{1fe,,float}, @ref{2c8,,complex} 和 @ref{2c7,,decimal.Decimal}。

Discussions are underway about how to specify alternative separators
like dots, spaces, apostrophes, or underscores.  Locale-aware applications
should use the existing @emph{n} format specifier which already has some support
for thousands separators.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 378

@item PEP 378@footnote{https://www.python.org/dev/peps/pep-0378} - 千位分隔符的格式说明符

PEP 由 Raymond Hettinger 撰写，并由 Eric Smith 和 Mark Dickinson 实现
@end table


@node 其他语言特性修改<9>,新增，改进和弃用的模块<2>,PEP 378 千位分隔符的格式说明符,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 other-language-changes}@anchor{ce9}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
Directories and zip archives containing a @code{__main__.py}
file can now be executed directly by passing their name to the
interpreter. The directory/zipfile is automatically inserted as the
first entry in sys.path.  (Suggestion and initial patch by Andy Chu;
revised patch by Phillip J. Eby and Nick Coghlan; bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468}.)

@item 
@ref{205,,int()} 类型增加了一个 @code{bit_length} 方法用来返回以二进制代表其参数值所需的比特位数量:

@example
>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124
@end example

（由 Fredrik Johansson, Victor Stinner, Raymond Hettinger 和 Mark Dickinson 在 bpo-3439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3439} 中贡献。）

@item 
@ref{5de,,format()} 字符串中的字段现在可被自动编号:

@example
>>> 'Sir @{@} of @{@}'.format('Gallahad', 'Camelot')
'Sir Gallahad of Camelot'
@end example

之前，字符串应当具有所需的编号字段例如: @code{'Sir @{0@} of @{1@}'}。

（由 Eric Smith在 bpo-5237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5237} 中贡献）

@item 
The @code{string.maketrans()} function is deprecated and is replaced by new
static methods, @ref{cdc,,bytes.maketrans()} and @ref{cdd,,bytearray.maketrans()}.
This change solves the confusion around which types were supported by the
@ref{f6,,string} module. Now, @ref{206,,str}, @ref{172,,bytes}, and
@ref{173,,bytearray} each have their own @strong{maketrans} and @strong{translate}
methods with intermediate translation tables of the appropriate type.

（由Georg Brandl在 bpo-5675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5675} 中贡献）

@item 
The syntax of the @ref{7e4,,with} 语句的语法现在允许单个语句中存在多个上下文管理器:

@example
>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
...     for line in infile:
...         if '<critical>' in line:
...             outfile.write(line)
@end example

有了这个新语法，@code{contextlib.nested()} 函数已不再必要因而现在已被弃用。

（由 Georg Brandl 和 Mattias Brändström 贡献; appspot issue 53094@footnote{https://codereview.appspot.com/53094}。）

@item 
现在 @code{round(x, n)} 当 @emph{x} 为整数时将返回整数。 之前是返回浮点数:

@example
>>> round(1123, -2)
1100
@end example

（由 Mark Dickinson在 bpo-4707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4707} 贡献）

@item 
Python now uses David Gay's algorithm for finding the shortest floating
point representation that doesn't change its value.  This should help
mitigate some of the confusion surrounding binary floating point
numbers.

The significance is easily seen with a number like @code{1.1} which does not
have an exact equivalent in binary floating point.  Since there is no exact
equivalent, an expression like @code{float('1.1')} evaluates to the nearest
representable value which is @code{0x1.199999999999ap+0} in hex or
@code{1.100000000000000088817841970012523233890533447265625} in decimal. That
nearest value was and still is used in subsequent floating point
calculations.

What is new is how the number gets displayed.  Formerly, Python used a
simple approach.  The value of @code{repr(1.1)} was computed as @code{format(1.1,
'.17g')} which evaluated to @code{'1.1000000000000001'}. The advantage of
using 17 digits was that it relied on IEEE-754 guarantees to assure that
@code{eval(repr(1.1))} would round-trip exactly to its original value.  The
disadvantage is that many people found the output to be confusing (mistaking
intrinsic limitations of binary floating point representation as being a
problem with Python itself).

The new algorithm for @code{repr(1.1)} is smarter and returns @code{'1.1'}.
Effectively, it searches all equivalent string representations (ones that
get stored with the same underlying float value) and returns the shortest
representation.

The new algorithm tends to emit cleaner representations when possible, but
it does not change the underlying values.  So, it is still the case that
@code{1.1 + 2.2 != 3.3} even though the representations may suggest otherwise.

The new algorithm depends on certain features in the underlying floating
point implementation.  If the required features are not found, the old
algorithm will continue to be used.  Also, the text pickle protocols
assure cross-platform portability by using the old algorithm.

（由 Eric Smith 和 Mark Dickinson 在 bpo-1580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1580} 贡献）
@end itemize

@node 新增，改进和弃用的模块<2>,性能优化<8>,其他语言特性修改<9>,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 new-improved-and-deprecated-modules}@anchor{cea}
@subsection 新增，改进和弃用的模块



@itemize *

@item 
增加了一个 @ref{ac2,,collections.Counter} 类以支持方便地统计一个序列或可迭代对象中的唯一条目数量。:

@example
>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter(@{'blue': 3, 'red': 2, 'green': 1@})
@end example

（由 Raymond Hettinger 在 bpo-1696199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1696199} 中贡献。）

@item 
Added a new module, @ref{118,,tkinter.ttk} for access to the Tk themed widget set.
The basic idea of ttk is to separate, to the extent possible, the code
implementing a widget's behavior from the code implementing its appearance.

（由 Guilherme Polo 在 bpo-2983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2983} 中贡献。）

@item 
@ref{207,,gzip.GzipFile} 和 @ref{225,,bz2.BZ2File} 类现在已支持上下文管理协议:

@example
>>> # Automatically close file after writing
>>> with gzip.GzipFile(filename, "wb") as f:
...     f.write(b"xxx")
@end example

（由 Antoine Pitrou 贡献。）

@item 
@ref{35,,decimal} 模块现在支持基于一个二进制 @ref{1fe,,float} 来创建 decimal 对象。 转换是准确的但有时也会令人吃惊:

@example
>>> Decimal.from_float(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
@end example

这个长长的 decimal 结果值显示了 @emph{1.1} 所保存的实际二进制分数。 这个分数有许多位因为 @emph{1.1} 无法用二进制来精确表示。

（由Raymond Hettinger 和 Mark Dickinson贡献。）

@item 
The @ref{a3,,itertools} module grew two new functions.  The
@ref{ceb,,itertools.combinations_with_replacement()} function is one of
four for generating combinatorics including permutations and Cartesian
products.  The @ref{cec,,itertools.compress()} function mimics its namesake
from APL.  Also, the existing @ref{ced,,itertools.count()} function now has
an optional @emph{step} argument and can accept any type of counting
sequence including @ref{2c5,,fractions.Fraction} and
@ref{2c7,,decimal.Decimal}:

@example
>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']

>>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]

>>> c = count(start=Fraction(1,2), step=Fraction(1,6))
>>> [next(c), next(c), next(c), next(c)]
[Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]
@end example

（由 Raymond Hettinger 贡献。）

@item 
@ref{1a1,,collections.namedtuple()} now supports a keyword argument
@emph{rename} which lets invalid fieldnames be automatically converted to
positional names in the form _0, _1, etc.  This is useful when
the field names are being created by an external source such as a
CSV header, SQL field list, or user input:

@example
>>> query = input()
SELECT region, dept, count(*) FROM main GROUPBY region, dept

>>> cursor.execute(query)
>>> query_fields = [desc[0] for desc in cursor.description]
>>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)
>>> pprint.pprint([UserQuery(*row) for row in cursor])
[UserQuery(region='South', dept='Shipping', _2=185),
 UserQuery(region='North', dept='Accounting', _2=37),
 UserQuery(region='West', dept='Sales', _2=419)]
@end example

（由 Raymond Hettinger 在 bpo-1818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1818} 中贡献。）

@item 
@ref{582,,re.sub()}, @ref{82d,,re.subn()} 和 @ref{4d9,,re.split()} 函数现在可接受一个 flags 形参。

（由 Gregory Smith 贡献）

@item 
The @ref{aa,,logging} module now implements a simple @ref{cee,,logging.NullHandler}
class for applications that are not using logging but are calling
library code that does.  Setting-up a null handler will suppress
spurious warnings such as "No handlers could be found for logger foo":

@example
>>> h = logging.NullHandler()
>>> logging.getLogger("foo").addHandler(h)
@end example

（由 Vinay Sajip 在 bpo-4384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4384} 中贡献。）

@item 
支持 @code{-m} 命令行开关的 @ref{e2,,runpy} 模块现在也支持当提供包名称时通过查找并执行 @code{__main__} 子模块来执行包。

（由 Andi Vajda 在 bpo-4195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4195} 中贡献。）

@item 
@ref{c9,,pdb} 模块现在可以访问并显示通过 @ref{14c,,zipimport} (或其他符合规范的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 加载器) 加载的源代码。

（由 Alexander Belopolsky 在 bpo-4201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4201} 中贡献。）

@item 
@ref{8bf,,functools.partial} 对象现在可以被封存。
@end itemize

@quotation

（由 Antoine Pitrou 和 Jesse Noller 提议，由 Jack Diederich 实现; bpo-5228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5228}。）
@end quotation


@itemize *

@item 
为符号增加 @ref{d9,,pydoc} 帮助主题以使得在交互环境下 @code{help('@@')} 能符合预期的效果。

（由 David Laban 在 bpo-4739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4739} 中贡献。）

@item 
The @ref{124,,unittest} module now supports skipping individual tests or classes
of tests. And it supports marking a test as an expected failure, a test that
is known to be broken, but shouldn't be counted as a failure on a
TestResult:

@example
class TestGizmo(unittest.TestCase):

    @@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_gizmo_on_windows(self):
        ...

    @@unittest.expectedFailure
    def test_gimzo_without_required_library(self):
        ...
@end example

Also, tests for exceptions have been builtout to work with context managers
using the @ref{7e4,,with} statement:

@example
def test_division_by_zero(self):
    with self.assertRaises(ZeroDivisionError):
        x / 0
@end example

In addition, several new assertion methods were added including
@code{assertSetEqual()}, @code{assertDictEqual()},
@code{assertDictContainsSubset()}, @code{assertListEqual()},
@code{assertTupleEqual()}, @code{assertSequenceEqual()},
@code{assertRaisesRegexp()}, @code{assertIsNone()},
and @code{assertIsNotNone()}.

（由Benjamin Peterson 和 Antoine Pitrou 贡献。）

@item 
@ref{a1,,io} 模块新增了三个常量来代表 @code{seek()} 方法  @code{SEEK_SET}, @code{SEEK_CUR} 和 @code{SEEK_END}。

@item 
@ref{bf6,,sys.version_info} 元组现在是一个具名元组:

@example
>>> sys.version_info
sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)
@end example

（由 Ross Light 在 bpo-4285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4285} 中贡献。）

@item 
The @ref{c0,,nntplib} and @ref{97,,imaplib} modules now support IPv6.

（由 Derek Morr 在 bpo-1655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1655} 和 bpo-1664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1664} 中贡献。）

@item 
The @ref{ca,,pickle} module has been adapted for better interoperability with
Python 2.x when used with protocol 2 or lower.  The reorganization of the
standard library changed the formal reference for many objects.  For
example, @code{__builtin__.set} in Python 2 is called @code{builtins.set} in Python
3. This change confounded efforts to share data between different versions of
Python.  But now when protocol 2 or lower is selected, the pickler will
automatically use the old Python 2 names for both loading and dumping. This
remapping is turned-on by default but can be disabled with the @emph{fix_imports}
option:

@example
>>> s = @{1, 2, 3@}
>>> pickle.dumps(s, protocol=0)
b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
>>> pickle.dumps(s, protocol=0, fix_imports=False)
b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
@end example

An unfortunate but unavoidable side-effect of this change is that protocol 2
pickles produced by Python 3.1 won't be readable with Python 3.0. The latest
pickle protocol, protocol 3, should be used when migrating data between
Python 3.x implementations, as it doesn't attempt to remain compatible with
Python 2.x.

（由 Alexandre Vassalotti 和 Antoine Pitrou 在 bpo-6137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6137} 中贡献。）

@item 
A new module, @ref{9a,,importlib} was added.  It provides a complete, portable,
pure Python reference implementation of the @ref{cef,,import} statement and its
counterpart, the @ref{16b,,__import__()} function.  It represents a substantial
step forward in documenting and defining the actions that take place during
imports.

（由 Brett Cannon 贡献。）
@end itemize

@node 性能优化<8>,IDLE<2>,新增，改进和弃用的模块<2>,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 optimizations}@anchor{cf0}
@subsection 性能优化


Major performance enhancements have been added:


@itemize *

@item 
The new I/O library (as defined in 
@geindex Python 提高建议; PEP 3116
PEP 3116@footnote{https://www.python.org/dev/peps/pep-3116}) was mostly written in
Python and quickly proved to be a problematic bottleneck in Python 3.0.
In Python 3.1, the I/O library has been entirely rewritten in C and is
2 to 20 times faster depending on the task at hand. The pure Python
version is still available for experimentation purposes through
the @code{_pyio} module.

（由 Amaury Forgeot d'Arc 和 Antoine Pitrou 贡献。）

@item 
Added a heuristic so that tuples and dicts containing only untrackable objects
are not tracked by the garbage collector. This can reduce the size of
collections and therefore the garbage collection overhead on long-running
programs, depending on their particular use of datatypes.

（由 Antoine Pitrou 在 bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688} 中贡献。）

@item 
Enabling a configure option named @code{--with-computed-gotos}
on compilers that support it (notably: gcc, SunPro, icc), the bytecode
evaluation loop is compiled with a new dispatch mechanism which gives
speedups of up to 20%, depending on the system, the compiler, and
the benchmark.

（由 Antoine Pitrou 以及其他一些参与者在 bpo-4753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4753} 中贡献。）

@item 
The decoding of UTF-8, UTF-16 and LATIN-1 is now two to four times
faster.

（由 Antoine Pitrou 和 Amaury Forgeot d'Arc 在 bpo-4868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4868} 中贡献。）

@item 
The @ref{a4,,json} module now has a C extension to substantially improve
its performance.  In addition, the API was modified so that json works
only with @ref{206,,str}, not with @ref{172,,bytes}.  That change makes the
module closely match the JSON specification@footnote{http://json.org/}
which is defined in terms of Unicode.

（由 Bob Ippolito 在 bpo-4136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4136} 中贡献。并由 Antoine Pitrou 和 Benjamin Peterson 转换为Py3.1）

@item 
Unpickling now interns the attribute names of pickled objects.  This saves
memory and allows pickles to be smaller.

（由 Jake McGuire 和 Antoine Pitrou 在 bpo-5084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5084} 中贡献。）
@end itemize

@node IDLE<2>,构建和 C API 的改变<6>,性能优化<8>,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 idle}@anchor{cf1}
@subsection IDLE



@itemize *

@item 
IDLE's format menu now provides an option to strip trailing whitespace
from a source file.

（由 Roger D. Serwy 在 bpo-5150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5150} 中贡献。）
@end itemize

@node 构建和 C API 的改变<6>,移植到 Python 3 1,IDLE<2>,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 build-and-c-api-changes}@anchor{cf2}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
Integers are now stored internally either in base @code{2**15} or in base
@code{2**30}, the base being determined at build time.  Previously, they
were always stored in base @code{2**15}.  Using base @code{2**30} gives
significant performance improvements on 64-bit machines, but
benchmark results on 32-bit machines have been mixed.  Therefore,
the default is to use base @code{2**30} on 64-bit machines and base @code{2**15}
on 32-bit machines; on Unix, there's a new configure option
@code{--enable-big-digits} that can be used to override this default.

Apart from the performance improvements this change should be invisible to
end users, with one exception: for testing and debugging purposes there's a
new @ref{cf3,,sys.int_info} that provides information about the
internal format, giving the number of bits per digit and the size in bytes
of the C type used to store each digit:

@example
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
@end example

（由 Mark Dickinson在 bpo-4258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4258} 贡献）

@item 
The @ref{cf4,,PyLong_AsUnsignedLongLong()} function now handles a negative
@emph{pylong} by raising @ref{a4a,,OverflowError} instead of @ref{1ff,,TypeError}.

（由 Mark Dickinson 和 Lisandro Dalcrin 在 bpo-5175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5175} 中贡献。）

@item 
Deprecated @code{PyNumber_Int()}.  Use @ref{39d,,PyNumber_Long()} instead.

（由 Mark Dickinson在 bpo-4910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4910} 贡献）

@item 
Added a new @ref{cf5,,PyOS_string_to_double()} function to replace the
deprecated functions @code{PyOS_ascii_strtod()} and @code{PyOS_ascii_atof()}.

（由 Mark Dickinson 在 bpo-5914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5914} 贡献）

@item 
Added @ref{cda,,PyCapsule} as a replacement for the @code{PyCObject} API.
The principal difference is that the new type has a well defined interface
for passing typing safety information and a less complicated signature
for calling a destructor.  The old type had a problematic API and is now
deprecated.

（由 Larry Hastings 在 bpo-5630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5630} 中贡献。）
@end itemize

@node 移植到 Python 3 1,,构建和 C API 的改变<6>,Python 3 1 有什么新变化
@anchor{whatsnew/3 1 porting-to-python-3-1}@anchor{cf6}
@subsection 移植到 Python 3.1


This section lists previously described changes and other bugfixes
that may require changes to your code:


@itemize *

@item 
The new floating point string representations can break existing doctests.
For example:

@example
def e():
    '@w{'}'Compute the base of natural logarithms.

    >>> e()
    2.7182818284590451

    '@w{'}'
    return sum(1/math.factorial(x) for x in reversed(range(30)))

doctest.testmod()

**********************************************************************
Failed example:
    e()
Expected:
    2.7182818284590451
Got:
    2.718281828459045
**********************************************************************
@end example

@item 
The automatic name remapping in the pickle module for protocol 2 or lower can
make Python 3.1 pickles unreadable in Python 3.0.  One solution is to use
protocol 3.  Another solution is to set the @emph{fix_imports} option to @code{False}.
See the discussion above for more details.
@end itemize

@node Python 3 0 有什么新变化,Python 2 7 有什么新变化,Python 3 1 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/3 0 doc}@anchor{cf7}@anchor{whatsnew/3 0 what-s-new-in-python-3-0}@anchor{cf8}
@section Python 3.0 有什么新变化


@c XXX Add trademark info for Apple, Microsoft.

@*作者: 
Guido van Rossum


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.  (Note: I didn't get to this for 3.0.
@c GvR.)
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.  (Due to time
@c constraints I haven't managed to do this for 3.0.  GvR.)
@c 
@c * It's helpful to add the bug/patch number as a comment:
@c 
@c % Patch 12345
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer.)
@c 
@c This saves the maintainer the effort of going through the SVN log
@c when researching a change.  (Again, I didn't get to this for 3.0.
@c GvR.)

This article explains the new features in Python 3.0, compared to 2.6.
Python 3.0, also known as "Python 3000" or "Py3K", is the first ever
@emph{intentionally backwards incompatible} Python release.  There are more
changes than in a typical release, and more that are important for all
Python users.  Nevertheless, after digesting the changes, you'll find
that Python really hasn't changed all that much -- by and large, we're
mostly fixing well-known annoyances and warts, and removing a lot of
old cruft.

This article doesn't attempt to provide a complete specification of
all new features, but instead tries to give a convenient overview.
For full details, you should refer to the documentation for Python
3.0, and/or the many PEPs referenced in the text. If you want to
understand the complete implementation and design rationale for a
particular feature, PEPs usually have more details than the regular
documentation; but note that PEPs usually are not kept up-to-date once
a feature has been fully implemented.

Due to time constraints this document is not as complete as it should
have been.  As always for a new release, the @code{Misc/NEWS} file in the
source distribution contains a wealth of detailed information about
every small thing that was changed.

@c Compare with previous release in 2 - 3 sentences here.

@c add hyperlink when the documentation becomes available online.

@c ======================================================================

@c Large, PEP-level features and changes should be described here.

@c Should there be a new section here for 3k migration?

@c Or perhaps a more general section describing module changes/deprecation?

@c sets module deprecated

@c ======================================================================

@menu
* 常见的绊脚石:: 
* 语法变化概述:: 
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6. 
* 库的修改:: 
* PEP 3101; A New Approach To String Formatting: PEP 3101 A New Approach To String Formatting. 
* Changes To Exceptions:: 
* Miscellaneous Other Changes:: 
* 构建和 C API 的改变: 构建和 C API 的改变<7>. 
* 性能:: 
* 移植到 Python 3.0: 移植到 Python 3 0. 

@end menu

@node 常见的绊脚石,语法变化概述,,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 common-stumbling-blocks}@anchor{cf9}
@subsection 常见的绊脚石


This section lists those few changes that are most likely to trip you
up if you're used to Python 2.5.

@menu
* Print 是函数:: 
* 用视图和迭代器取代列表:: 
* Ordering Comparisons:: 
* 整数:: 
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit. 

@end menu

@node Print 是函数,用视图和迭代器取代列表,,常见的绊脚石
@anchor{whatsnew/3 0 print-is-a-function}@anchor{cfa}
@subsubsection Print 是函数


The @code{print} statement has been replaced with a @ref{97a,,print()}
function, with keyword arguments to replace most of the special syntax
of the old @code{print} statement (
@geindex Python 提高建议; PEP 3105
PEP 3105@footnote{https://www.python.org/dev/peps/pep-3105}).  Examples:

@example
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!
@end example

你还可以自定义条目间的分隔符，例如

@example
print("There are <", 2**32, "> possibilities!", sep="")
@end example

这将产生如下结果:

@example
There are <4294967296> possibilities!
@end example

注意


@itemize *

@item 
The @ref{97a,,print()} function doesn't support the "softspace" feature of
the old @code{print} statement.  For example, in Python 2.x,
@code{print "A\n", "B"} would write @code{"A\nB\n"}; but in Python 3.0,
@code{print("A\n", "B")} writes @code{"A\n B\n"}.

@item 
Initially, you'll be finding yourself typing the old @code{print x}
a lot in interactive mode.  Time to retrain your fingers to type
@code{print(x)} instead!

@item 
When using the @code{2to3} source-to-source conversion tool, all
@code{print} statements are automatically converted to
@ref{97a,,print()} function calls, so this is mostly a non-issue for
larger projects.
@end itemize

@node 用视图和迭代器取代列表,Ordering Comparisons,Print 是函数,常见的绊脚石
@anchor{whatsnew/3 0 views-and-iterators-instead-of-lists}@anchor{cfb}
@subsubsection 用视图和迭代器取代列表


某些知名的 API 将不再返回列表:


@itemize *

@item 
@ref{164,,dict} methods @ref{cfc,,dict.keys()}, @ref{cfd,,dict.items()} and
@ref{cfe,,dict.values()} return "views" instead of lists.  For example,
this no longer works: @code{k = d.keys(); k.sort()}.  Use @code{k =
sorted(d)} instead (this works in Python 2.5 too and is just
as efficient).

@item 
Also, the @code{dict.iterkeys()}, @code{dict.iteritems()} and
@code{dict.itervalues()} methods are no longer supported.

@item 
@ref{cff,,map()} and @ref{d00,,filter()} return iterators.  If you really need
a list and the input sequences are all of equal length, a quick
fix is to wrap @ref{cff,,map()} in @ref{1f9,,list()}, e.g. @code{list(map(...))},
but a better fix is
often to use a list comprehension (especially when the original code
uses @ref{d01,,lambda}), or rewriting the code so it doesn't need a
list at all.  Particularly tricky is @ref{cff,,map()} invoked for the
side effects of the function; the correct transformation is to use a
regular @ref{d02,,for} loop (since creating a list would just be
wasteful).

If the input sequences are not of equal length, @ref{cff,,map()} will
stop at the termination of the shortest of the sequences. For full
compatibility with @ref{cff,,map()} from Python 2.x, also wrap the sequences in
@ref{d03,,itertools.zip_longest()}, e.g. @code{map(func, *sequences)} becomes
@code{list(map(func, itertools.zip_longest(*sequences)))}.

@item 
@ref{1f6,,range()} now behaves like @code{xrange()} used to behave, except
it works with values of arbitrary size.  The latter no longer
exists.

@item 
@ref{d04,,zip()} now returns an iterator.
@end itemize

@node Ordering Comparisons,整数,用视图和迭代器取代列表,常见的绊脚石
@anchor{whatsnew/3 0 ordering-comparisons}@anchor{d05}
@subsubsection Ordering Comparisons


Python 3.0 has simplified the rules for ordering comparisons:


@itemize *

@item 
The ordering comparison operators (@code{<}, @code{<=}, @code{>=}, @code{>})
raise a TypeError exception when the operands don't have a
meaningful natural ordering.  Thus, expressions like @code{1 < '@w{'}}, @code{0
> None} or @code{len <= len} are no longer valid, and e.g. @code{None <
None} raises @ref{1ff,,TypeError} instead of returning
@code{False}.  A corollary is that sorting a heterogeneous list
no longer makes sense -- all the elements must be comparable to each
other.  Note that this does not apply to the @code{==} and @code{!=}
operators: objects of different incomparable types always compare
unequal to each other.

@item 
@code{builtin.sorted()} and @ref{550,,list.sort()} no longer accept the
@emph{cmp} argument providing a comparison function.  Use the @emph{key}
argument instead. N.B. the @emph{key} and @emph{reverse} arguments are now
"keyword-only".

@item 
The @code{cmp()} function should be treated as gone, and the @code{__cmp__()}
special method is no longer supported.  Use @ref{d06,,__lt__()} for sorting,
@ref{454,,__eq__()} with @ref{455,,__hash__()}, and other rich comparisons as needed.
(If you really need the @code{cmp()} functionality, you could use the
expression @code{(a > b) - (a < b)} as the equivalent for @code{cmp(a, b)}.)
@end itemize

@node 整数,Text Vs Data Instead Of Unicode Vs 8-bit,Ordering Comparisons,常见的绊脚石
@anchor{whatsnew/3 0 integers}@anchor{d07}
@subsubsection 整数



@itemize *

@item 
@geindex Python 提高建议; PEP 237
PEP 237@footnote{https://www.python.org/dev/peps/pep-0237}: Essentially, @code{long} renamed to @ref{205,,int}.
That is, there is only one built-in integral type, named
@ref{205,,int}; but it behaves mostly like the old @code{long} type.

@item 
@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238}: An expression like @code{1/2} returns a float.  Use
@code{1//2} to get the truncating behavior.  (The latter syntax has
existed for years, at least since Python 2.2.)

@item 
The @code{sys.maxint} constant was removed, since there is no
longer a limit to the value of integers.  However, @ref{c1e,,sys.maxsize}
can be used as an integer larger than any practical list or string
index.  It conforms to the implementation's "natural" integer size
and is typically the same as @code{sys.maxint} in previous releases
on the same platform (assuming the same build options).

@item 
The @ref{8c3,,repr()} of a long integer doesn't include the trailing @code{L}
anymore, so code that unconditionally strips that character will
chop off the last digit instead.  (Use @ref{206,,str()} instead.)

@item 
Octal literals are no longer of the form @code{0720}; use @code{0o720}
instead.
@end itemize

@node Text Vs Data Instead Of Unicode Vs 8-bit,,整数,常见的绊脚石
@anchor{whatsnew/3 0 text-vs-data-instead-of-unicode-vs-8-bit}@anchor{d08}
@subsubsection Text Vs. Data Instead Of Unicode Vs. 8-bit


Everything you thought you knew about binary data and Unicode has
changed.


@itemize *

@item 
Python 3.0 uses the concepts of @emph{text} and (binary) @emph{data} instead
of Unicode strings and 8-bit strings.  All text is Unicode; however
@emph{encoded} Unicode is represented as binary data.  The type used to
hold text is @ref{206,,str}, the type used to hold data is
@ref{172,,bytes}.  The biggest difference with the 2.x situation is
that any attempt to mix text and data in Python 3.0 raises
@ref{1ff,,TypeError}, whereas if you were to mix Unicode and 8-bit
strings in Python 2.x, it would work if the 8-bit string happened to
contain only 7-bit (ASCII) bytes, but you would get
@ref{332,,UnicodeDecodeError} if it contained non-ASCII values.  This
value-specific behavior has caused numerous sad faces over the
years.

@item 
As a consequence of this change in philosophy, pretty much all code
that uses Unicode, encodings or binary data most likely has to
change.  The change is for the better, as in the 2.x world there
were numerous bugs having to do with mixing encoded and unencoded
text.  To be prepared in Python 2.x, start using @code{unicode}
for all unencoded text, and @ref{206,,str} for binary or encoded data
only.  Then the @code{2to3} tool will do most of the work for you.

@item 
You can no longer use @code{u"..."} literals for Unicode text.
However, you must use @code{b"..."} literals for binary data.

@item 
As the @ref{206,,str} and @ref{172,,bytes} types cannot be mixed, you
must always explicitly convert between them.  Use @ref{170,,str.encode()}
to go from @ref{206,,str} to @ref{172,,bytes}, and @ref{171,,bytes.decode()}
to go from @ref{172,,bytes} to @ref{206,,str}.  You can also use
@code{bytes(s, encoding=...)} and @code{str(b, encoding=...)},
respectively.

@item 
Like @ref{206,,str}, the @ref{172,,bytes} type is immutable.  There is a
separate @emph{mutable} type to hold buffered binary data,
@ref{173,,bytearray}.  Nearly all APIs that accept @ref{172,,bytes} also
accept @ref{173,,bytearray}.  The mutable API is based on
@code{collections.MutableSequence}.

@item 
All backslashes in raw string literals are interpreted literally.
This means that @code{'\U'} and @code{'\u'} escapes in raw strings are not
treated specially.  For example, @code{r'\u20ac'} is a string of 6
characters in Python 3.0, whereas in 2.6, @code{ur'\u20ac'} was the
single "euro" character.  (Of course, this change only affects raw
string literals; the euro character is @code{'\u20ac'} in Python 3.0.)

@item 
The built-in @code{basestring} abstract type was removed.  Use
@ref{206,,str} instead.  The @ref{206,,str} and @ref{172,,bytes} types
don't have functionality enough in common to warrant a shared base
class.  The @code{2to3} tool (see below) replaces every occurrence of
@code{basestring} with @ref{206,,str}.

@item 
Files opened as text files (still the default mode for @ref{16f,,open()})
always use an encoding to map between strings (in memory) and bytes
(on disk).  Binary files (opened with a @code{b} in the mode argument)
always use bytes in memory.  This means that if a file is opened
using an incorrect mode or encoding, I/O will likely fail loudly,
instead of silently producing incorrect data.  It also means that
even Unix users will have to specify the correct mode (text or
binary) when opening a file.  There is a platform-dependent default
encoding, which on Unixy platforms can be set with the @code{LANG}
environment variable (and sometimes also with some other
platform-specific locale-related environment variables).  In many
cases, but not all, the system default is UTF-8; you should never
count on this default.  Any application reading or writing more than
pure ASCII text should probably have a way to override the encoding.
There is no longer any need for using the encoding-aware streams
in the @ref{1b,,codecs} module.

@item 
The initial values of @ref{427,,sys.stdin}, @ref{428,,sys.stdout} and
@ref{1eb,,sys.stderr} are now unicode-only text files (i.e., they are
instances of @ref{d09,,io.TextIOBase}).  To read and write bytes data
with these streams, you need to use their @ref{d0a,,io.TextIOBase.buffer}
attribute.

@item 
Filenames are passed to and returned from APIs as (Unicode) strings.
This can present platform-specific problems because on some
platforms filenames are arbitrary byte strings.  (On the other hand,
on Windows filenames are natively stored as Unicode.)  As a
work-around, most APIs (e.g. @ref{16f,,open()} and many functions in the
@ref{c4,,os} module) that take filenames accept @ref{172,,bytes} objects
as well as strings, and a few APIs have a way to ask for a
@ref{172,,bytes} return value.  Thus, @ref{b25,,os.listdir()} returns a
list of @ref{172,,bytes} instances if the argument is a @ref{172,,bytes}
instance, and @ref{3e2,,os.getcwdb()} returns the current working
directory as a @ref{172,,bytes} instance.  Note that when
@ref{b25,,os.listdir()} returns a list of strings, filenames that
cannot be decoded properly are omitted rather than raising
@ref{d0b,,UnicodeError}.

@item 
Some system APIs like @ref{c12,,os.environ} and @ref{cce,,sys.argv} can
also present problems when the bytes made available by the system is
not interpretable using the default encoding.  Setting the @code{LANG}
variable and rerunning the program is probably the best approach.

@item 
@geindex Python 提高建议; PEP 3138
PEP 3138@footnote{https://www.python.org/dev/peps/pep-3138}: The @ref{8c3,,repr()} of a string no longer escapes
non-ASCII characters.  It still escapes control characters and code
points with non-printable status in the Unicode standard, however.

@item 
@geindex Python 提高建议; PEP 3120
PEP 3120@footnote{https://www.python.org/dev/peps/pep-3120}：现在默认的源码编码格式是UTF-8。

@item 
@geindex Python 提高建议; PEP 3131
PEP 3131@footnote{https://www.python.org/dev/peps/pep-3131}: Non-ASCII letters are now allowed in identifiers.
(However, the standard library remains ASCII-only with the exception
of contributor names in comments.)

@item 
The @code{StringIO} and @code{cStringIO} modules are gone.  Instead,
import the @ref{a1,,io} module and use @ref{924,,io.StringIO} or
@ref{894,,io.BytesIO} for text and data respectively.

@item 
See also the @ref{d0c,,Unicode 指南}, which was updated for Python 3.0.
@end itemize

@node 语法变化概述,Changes Already Present In Python 2 6,常见的绊脚石,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 overview-of-syntax-changes}@anchor{d0d}
@subsection 语法变化概述


This section gives a brief overview of every @emph{syntactic} change in
Python 3.0.

@menu
* 新语法:: 
* 修改的语法:: 
* 移除的语法:: 

@end menu

@node 新语法,修改的语法,,语法变化概述
@anchor{whatsnew/3 0 new-syntax}@anchor{d0e}
@subsubsection 新语法



@itemize *

@item 
@geindex Python 提高建议; PEP 3107
PEP 3107@footnote{https://www.python.org/dev/peps/pep-3107}: Function argument and return value annotations.  This
provides a standardized way of annotating a function's parameters
and return value.  There are no semantics attached to such
annotations except that they can be introspected at runtime using
the @code{__annotations__} attribute.  The intent is to encourage
experimentation through metaclasses, decorators or frameworks.

@item 
@geindex Python 提高建议; PEP 3102
PEP 3102@footnote{https://www.python.org/dev/peps/pep-3102}: Keyword-only arguments.  Named parameters occurring
after @code{*args} in the parameter list @emph{must} be specified using
keyword syntax in the call.  You can also use a bare @code{*} in the
parameter list to indicate that you don't accept a variable-length
argument list, but you do have keyword-only arguments.

@item 
Keyword arguments are allowed after the list of base classes in a
class definition.  This is used by the new convention for specifying
a metaclass (see next section), but can be used for other purposes
as well, as long as the metaclass supports it.

@item 
@geindex Python 提高建议; PEP 3104
PEP 3104@footnote{https://www.python.org/dev/peps/pep-3104}: @ref{d0f,,nonlocal} statement.  Using @code{nonlocal x}
you can now assign directly to a variable in an outer (but
non-global) scope.  @code{nonlocal} is a new reserved word.

@item 
@geindex Python 提高建议; PEP 3132
PEP 3132@footnote{https://www.python.org/dev/peps/pep-3132}: Extended Iterable Unpacking.  You can now write things
like @code{a, b, *rest = some_sequence}.  And even @code{*rest, a =
stuff}.  The @code{rest} object is always a (possibly empty) list; the
right-hand side may be any iterable.  Example:

@example
(a, *rest, b) = range(5)
@end example

This sets @emph{a} to @code{0}, @emph{b} to @code{4}, and @emph{rest} to @code{[1, 2, 3]}.

@item 
Dictionary comprehensions: @code{@{k: v for k, v in stuff@}} means the
same thing as @code{dict(stuff)} but is more flexible.  (This is
@geindex Python 提高建议; PEP 274
PEP 274@footnote{https://www.python.org/dev/peps/pep-0274} vindicated. :-)

@item 
Set literals, e.g. @code{@{1, 2@}}.  Note that @code{@{@}} is an empty
dictionary; use @code{set()} for an empty set.  Set comprehensions are
also supported; e.g., @code{@{x for x in stuff@}} means the same thing as
@code{set(stuff)} but is more flexible.

@item 
New octal literals, e.g. @code{0o720} (already in 2.6).  The old octal
literals (@code{0720}) are gone.

@item 
New binary literals, e.g. @code{0b1010} (already in 2.6), and
there is a new corresponding built-in function, @ref{d10,,bin()}.

@item 
Bytes literals are introduced with a leading @code{b} or @code{B}, and
there is a new corresponding built-in function, @ref{172,,bytes()}.
@end itemize

@node 修改的语法,移除的语法,新语法,语法变化概述
@anchor{whatsnew/3 0 changed-syntax}@anchor{d11}
@subsubsection 修改的语法



@itemize *

@item 
@geindex Python 提高建议; PEP 3109
PEP 3109@footnote{https://www.python.org/dev/peps/pep-3109} and 
@geindex Python 提高建议; PEP 3134
PEP 3134@footnote{https://www.python.org/dev/peps/pep-3134}: new @ref{d12,,raise} statement syntax:
@code{raise [@emph{expr} [from @emph{expr}]]}.  See below.

@item 
@code{as} and @ref{7e4,,with} are now reserved words.  (Since
2.6, actually.)

@item 
@code{True}, @code{False}, and @code{None} are reserved words.  (2.6 partially enforced
the restrictions on @code{None} already.)

@item 
Change from @ref{c19,,except} @emph{exc}, @emph{var} to
@code{except} @emph{exc} @code{as} @emph{var}.  See 
@geindex Python 提高建议; PEP 3110
PEP 3110@footnote{https://www.python.org/dev/peps/pep-3110}.

@item 
@geindex Python 提高建议; PEP 3115
PEP 3115@footnote{https://www.python.org/dev/peps/pep-3115}: New Metaclass Syntax.  Instead of:

@example
class C:
    __metaclass__ = M
    ...
@end example

你现在需要使用:

@example
class C(metaclass=M):
    ...
@end example

The module-global @code{__metaclass__} variable is no longer
supported.  (It was a crutch to make it easier to default to
new-style classes without deriving every class from
@ref{3da,,object}.)

@item 
List comprehensions no longer support the syntactic form
@code{[... for @emph{var} in @emph{item1}, @emph{item2}, ...]}.  Use
@code{[... for @emph{var} in (@emph{item1}, @emph{item2}, ...)]} instead.
Also note that list comprehensions have different semantics: they
are closer to syntactic sugar for a generator expression inside a
@ref{1f9,,list()} constructor, and in particular the loop control
variables are no longer leaked into the surrounding scope.

@item 
The @emph{ellipsis} (@code{...}) can be used as an atomic expression
anywhere.  (Previously it was only allowed in slices.)  Also, it
@emph{must} now be spelled as @code{...}.  (Previously it could also be
spelled as @code{. . .}, by a mere accident of the grammar.)
@end itemize

@node 移除的语法,,修改的语法,语法变化概述
@anchor{whatsnew/3 0 removed-syntax}@anchor{d13}
@subsubsection 移除的语法



@itemize *

@item 
@geindex Python 提高建议; PEP 3113
PEP 3113@footnote{https://www.python.org/dev/peps/pep-3113}: Tuple parameter unpacking removed.  You can no longer
write @code{def foo(a, (b, c)): ...}.
Use @code{def foo(a, b_c): b, c = b_c} instead.

@item 
Removed backticks (use @ref{8c3,,repr()} instead).

@item 
Removed @code{<>} (use @code{!=} instead).

@item 
Removed keyword: @ref{d14,,exec()} is no longer a keyword; it remains as
a function.  (Fortunately the function syntax was also accepted in
2.x.)  Also note that @ref{d14,,exec()} no longer takes a stream argument;
instead of @code{exec(f)} you can use @code{exec(f.read())}.

@item 
Integer literals no longer support a trailing @code{l} or @code{L}.

@item 
String literals no longer support a leading @code{u} or @code{U}.

@item 
The @ref{d15,,from} @emph{module} @ref{cef,,import} @code{*} syntax is only
allowed at the module level, no longer inside functions.

@item 
The only acceptable syntax for relative imports is @code{from .[@emph{module}]
import @emph{name}}.  All @ref{cef,,import} forms not starting with @code{.} are
interpreted as absolute imports.  (
@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328})

@item 
Classic classes are gone.
@end itemize

@node Changes Already Present In Python 2 6,库的修改,语法变化概述,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 changes-already-present-in-python-2-6}@anchor{d16}
@subsection Changes Already Present In Python 2.6


Since many users presumably make the jump straight from Python 2.5 to
Python 3.0, this section reminds the reader of new features that were
originally designed for Python 3.0 but that were back-ported to Python
2.6.  The corresponding sections in @ref{d17,,Python 2.6 有什么新变化} should be
consulted for longer descriptions.


@itemize *

@item 
@ref{d18,,PEP 343; "with" 语句}.  The @ref{7e4,,with} statement is now a standard
feature and no longer needs to be imported from the @ref{0,,__future__}.
Also check out @ref{d19,,编写上下文管理器} and
@ref{d1a,,contextlib 模块}.

@item 
@ref{d1b,,PEP 366; 从主模块显式相对导入}.  This enhances the usefulness of the @ref{44c,,-m}
option when the referenced module lives in a package.

@item 
@ref{d1c,,PEP 370; 分用户的 site-packages 目录}.

@item 
@ref{d1d,,PEP 371; 多任务处理包}.

@item 
@ref{d1e,,PEP 3101; 高级字符串格式}.  Note: the 2.6 description mentions the
@ref{5de,,format()} method for both 8-bit and Unicode strings.  In 3.0,
only the @ref{206,,str} type (text strings with Unicode support)
supports this method; the @ref{172,,bytes} type does not.  The plan is
to eventually make this the only API for string formatting, and to
start deprecating the @code{%} operator in Python 3.1.

@item 
@ref{d1f,,PEP 3105; print 改为函数}.  This is now a standard feature and no longer needs
to be imported from @ref{0,,__future__}.  More details were given above.

@item 
@ref{d20,,PEP 3110; 异常处理的变更}.  The @ref{c19,,except} @emph{exc} @code{as} @emph{var}
syntax is now standard and @code{except} @emph{exc}, @emph{var} is no
longer supported.  (Of course, the @code{as} @emph{var} part is still
optional.)

@item 
@ref{d21,,PEP 3112; 字节字面值}.  The @code{b"..."} string literal notation (and its
variants like @code{b'...'}, @code{b"""..."""}, and @code{br"..."}) now
produces a literal of type @ref{172,,bytes}.

@item 
@ref{d22,,PEP 3116; 新 I/O 库}.  The @ref{a1,,io} module is now the standard way of
doing file I/O.  The built-in @ref{16f,,open()} function is now an
alias for @ref{757,,io.open()} and has additional keyword arguments
@emph{encoding}, @emph{errors}, @emph{newline} and @emph{closefd}.  Also note that an
invalid @emph{mode} argument now raises @ref{16d,,ValueError}, not
@ref{a7c,,IOError}.  The binary file object underlying a text file
object can be accessed as @code{f.buffer} (but beware that the
text object maintains a buffer of itself in order to speed up
the encoding and decoding operations).

@item 
@ref{d23,,PEP 3118; 修改缓冲区协议}.  The old builtin @code{buffer()} is now really gone;
the new builtin @ref{38d,,memoryview()} provides (mostly) similar
functionality.

@item 
@ref{d24,,PEP 3119; 抽象基类}.  The @ref{3,,abc} module and the ABCs defined in the
@ref{1d,,collections} module plays a somewhat more prominent role in
the language now, and built-in collection types like @ref{164,,dict}
and @ref{1f9,,list} conform to the @code{collections.MutableMapping}
and @code{collections.MutableSequence} ABCs, respectively.

@item 
@ref{d25,,PEP 3127; 整型文字支持和语法}.  As mentioned above, the new octal literal
notation is the only one supported, and binary literals have been
added.

@item 
@ref{d26,,PEP 3129; 类装饰器}.

@item 
@ref{d27,,PEP 3141; A Type Hierarchy for Numbers}.  The @ref{c1,,numbers} module is another new use of
ABCs, defining Python's "numeric tower".  Also note the new
@ref{81,,fractions} module which implements @ref{d28,,numbers.Rational}.
@end itemize

@node 库的修改,PEP 3101 A New Approach To String Formatting,Changes Already Present In Python 2 6,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 library-changes}@anchor{d29}
@subsection 库的修改


Due to time constraints, this document does not exhaustively cover the
very extensive changes to the standard library.  
@geindex Python 提高建议; PEP 3108
PEP 3108@footnote{https://www.python.org/dev/peps/pep-3108} is the
reference for the major changes to the library.  Here's a capsule
review:


@itemize *

@item 
Many old modules were removed.  Some, like @code{gopherlib} (no
longer used) and @code{md5} (replaced by @ref{8c,,hashlib}), were
already deprecated by 
@geindex Python 提高建议; PEP 4
PEP 4@footnote{https://www.python.org/dev/peps/pep-0004}.  Others were removed as a result
of the removal of support for various platforms such as Irix, BeOS
and Mac OS 9 (see 
@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011}).  Some modules were also selected for
removal in Python 3.0 due to lack of use or because a better
replacement exists.  See 
@geindex Python 提高建议; PEP 3108
PEP 3108@footnote{https://www.python.org/dev/peps/pep-3108} for an exhaustive list.

@item 
The @code{bsddb3} package was removed because its presence in the
core standard library has proved over time to be a particular burden
for the core developers due to testing instability and Berkeley DB's
release schedule.  However, the package is alive and well,
externally maintained at @indicateurl{https://www.jcea.es/programacion/pybsddb.htm}.

@item 
Some modules were renamed because their old name disobeyed
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008}, or for various other reasons.  Here's the list:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

旧名称

@tab

新名称

@item

_winreg

@tab

winreg

@item

ConfigParser

@tab

configparser

@item

copy_reg

@tab

copyreg

@item

Queue

@tab

queue

@item

SocketServer

@tab

socketserver

@item

markupbase

@tab

_markupbase

@item

repr

@tab

reprlib

@item

test.test_support

@tab

test.support

@end multitable


@item 
A common pattern in Python 2.x is to have one version of a module
implemented in pure Python, with an optional accelerated version
implemented as a C extension; for example, @ref{ca,,pickle} and
@code{cPickle}.  This places the burden of importing the accelerated
version and falling back on the pure Python version on each user of
these modules.  In Python 3.0, the accelerated versions are
considered implementation details of the pure Python versions.
Users should always import the standard version, which attempts to
import the accelerated version and falls back to the pure Python
version.  The @ref{ca,,pickle} / @code{cPickle} pair received this
treatment.  The @ref{d3,,profile} module is on the list for 3.1.  The
@code{StringIO} module has been turned into a class in the @ref{a1,,io}
module.

@item 
Some related modules have been grouped into packages, and usually
the submodule names have been simplified.  The resulting new
packages are:


@itemize *

@item 
@ref{31,,dbm} (@code{anydbm}, @code{dbhash}, @ref{31,,dbm},
@code{dumbdbm}, @code{gdbm}, @code{whichdb}).

@item 
@ref{8f,,html} (@code{HTMLParser}, @code{htmlentitydefs}).

@item 
@ref{92,,http} (@code{httplib}, @code{BaseHTTPServer},
@code{CGIHTTPServer}, @code{SimpleHTTPServer}, @code{Cookie},
@code{cookielib}).

@item 
@ref{10e,,tkinter} (all @code{Tkinter}-related modules except
@ref{11f,,turtle}).  The target audience of @ref{11f,,turtle} doesn't
really care about @ref{10e,,tkinter}.  Also note that as of Python
2.6, the functionality of @ref{11f,,turtle} has been greatly enhanced.

@item 
@ref{126,,urllib} (@ref{126,,urllib}, @code{urllib2}, @code{urlparse},
@code{robotparse}).

@item 
@code{xmlrpc} (@code{xmlrpclib}, @code{DocXMLRPCServer},
@code{SimpleXMLRPCServer}).
@end itemize
@end itemize

Some other changes to standard library modules, not covered by
@geindex Python 提高建议; PEP 3108
PEP 3108@footnote{https://www.python.org/dev/peps/pep-3108}:


@itemize *

@item 
Killed @code{sets}.  Use the built-in @ref{1f7,,set()} class.

@item 
Cleanup of the @ref{fd,,sys} module: removed @code{sys.exitfunc()},
@code{sys.exc_clear()}, @code{sys.exc_type}, @code{sys.exc_value},
@code{sys.exc_traceback}.  (Note that @ref{d2a,,sys.last_type}
etc. remain.)

@item 
Cleanup of the @ref{217,,array.array} type: the @code{read()} and
@code{write()} methods are gone; use @code{fromfile()} and
@code{tofile()} instead.  Also, the @code{'c'} typecode for array is
gone -- use either @code{'b'} for bytes or @code{'u'} for Unicode
characters.

@item 
Cleanup of the @ref{c2,,operator} module: removed
@code{sequenceIncludes()} and @code{isCallable()}.

@item 
Cleanup of the @code{thread} module: @code{acquire_lock()} and
@code{release_lock()} are gone; use @code{acquire()} and
@code{release()} instead.

@item 
Cleanup of the @ref{dc,,random} module: removed the @code{jumpahead()} API.

@item 
The @code{new} module is gone.

@item 
The functions @code{os.tmpnam()}, @code{os.tempnam()} and
@code{os.tmpfile()} have been removed in favor of the @ref{103,,tempfile}
module.

@item 
The @ref{11a,,tokenize} module has been changed to work with bytes.  The
main entry point is now @ref{d2b,,tokenize.tokenize()}, instead of
generate_tokens.

@item 
@code{string.letters} and its friends (@code{string.lowercase} and
@code{string.uppercase}) are gone.  Use
@ref{d2c,,string.ascii_letters} etc. instead.  (The reason for the
removal is that @code{string.letters} and friends had
locale-specific behavior, which is a bad idea for such
attractively-named global "constants".)

@item 
Renamed module @code{__builtin__} to @ref{12,,builtins} (removing the
underscores, adding an 's').  The @code{__builtins__} variable
found in most global namespaces is unchanged.  To modify a builtin,
you should use @ref{12,,builtins}, not @code{__builtins__}!
@end itemize

@node PEP 3101 A New Approach To String Formatting,Changes To Exceptions,库的修改,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 pep-3101-a-new-approach-to-string-formatting}@anchor{d2d}
@subsection @strong{PEP 3101}: A New Approach To String Formatting


@geindex Python 提高建议; PEP 3101


@itemize *

@item 
A new system for  built-in string formatting operations replaces the
@code{%} string  formatting operator.   (However, the @code{%}  operator is
still supported;  it will  be deprecated in  Python 3.1  and removed
from the language at some later time.)  Read 
@geindex Python 提高建议; PEP 3101
PEP 3101@footnote{https://www.python.org/dev/peps/pep-3101} for the full
scoop.
@end itemize

@node Changes To Exceptions,Miscellaneous Other Changes,PEP 3101 A New Approach To String Formatting,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 changes-to-exceptions}@anchor{d2e}
@subsection Changes To Exceptions


The APIs for raising and catching exception have been cleaned up and
new powerful features added:


@itemize *

@item 
@geindex Python 提高建议; PEP 352
PEP 352@footnote{https://www.python.org/dev/peps/pep-0352}: All exceptions must be derived (directly or indirectly)
from @ref{2e2,,BaseException}.  This is the root of the exception
hierarchy.  This is not new as a recommendation, but the
@emph{requirement} to inherit from @ref{2e2,,BaseException} is new.  (Python
2.6 still allowed classic classes to be raised, and placed no
restriction on what you can catch.)  As a consequence, string
exceptions are finally truly and utterly dead.

@item 
Almost all exceptions should actually derive from @ref{2e3,,Exception};
@ref{2e2,,BaseException} should only be used as a base class for
exceptions that should only be handled at the top level, such as
@ref{6fd,,SystemExit} or @ref{2d3,,KeyboardInterrupt}.  The recommended
idiom for handling all exceptions except for this latter category is
to use @ref{c19,,except} @ref{2e3,,Exception}.

@item 
@code{StandardError} was removed.

@item 
Exceptions no longer behave as sequences.  Use the @code{args}
attribute instead.

@item 
@geindex Python 提高建议; PEP 3109
PEP 3109@footnote{https://www.python.org/dev/peps/pep-3109}: Raising exceptions.  You must now use @code{raise
@emph{Exception}(@emph{args})} instead of @code{raise @emph{Exception}, @emph{args}}.
Additionally, you can no longer explicitly specify a traceback;
instead, if you @emph{have} to do this, you can assign directly to the
@code{__traceback__} attribute (see below).

@item 
@geindex Python 提高建议; PEP 3110
PEP 3110@footnote{https://www.python.org/dev/peps/pep-3110}: Catching exceptions.  You must now use
@code{except @emph{SomeException} as @emph{variable}} instead
of @code{except @emph{SomeException}, @emph{variable}}.  Moreover, the
@emph{variable} is explicitly deleted when the @ref{c19,,except} block
is left.

@item 
@geindex Python 提高建议; PEP 3134
PEP 3134@footnote{https://www.python.org/dev/peps/pep-3134}: Exception chaining.  There are two cases: implicit
chaining and explicit chaining.  Implicit chaining happens when an
exception is raised in an @ref{c19,,except} or @ref{2c3,,finally}
handler block.  This usually happens due to a bug in the handler
block; we call this a @emph{secondary} exception.  In this case, the
original exception (that was being handled) is saved as the
@code{__context__} attribute of the secondary exception.
Explicit chaining is invoked with this syntax:

@example
raise SecondaryException() from primary_exception
@end example

(where @emph{primary_exception} is any expression that produces an
exception object, probably an exception that was previously caught).
In this case, the primary exception is stored on the
@code{__cause__} attribute of the secondary exception.  The
traceback printed when an unhandled exception occurs walks the chain
of @code{__cause__} and @code{__context__} attributes and prints a
separate traceback for each component of the chain, with the primary
exception at the top.  (Java users may recognize this behavior.)

@item 
@geindex Python 提高建议; PEP 3134
PEP 3134@footnote{https://www.python.org/dev/peps/pep-3134}: Exception objects now store their traceback as the
@code{__traceback__} attribute.  This means that an exception
object now contains all the information pertaining to an exception,
and there are fewer reasons to use @ref{d2f,,sys.exc_info()} (though the
latter is not removed).

@item 
A few exception messages are improved when Windows fails to load an
extension module.  For example, @code{error code 193} is now @code{%1 is
not a valid Win32 application}.  Strings now deal with non-English
locales.
@end itemize

@node Miscellaneous Other Changes,构建和 C API 的改变<7>,Changes To Exceptions,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 miscellaneous-other-changes}@anchor{d30}
@subsection Miscellaneous Other Changes


@menu
* Operators And Special Methods:: 
* Builtins:: 

@end menu

@node Operators And Special Methods,Builtins,,Miscellaneous Other Changes
@anchor{whatsnew/3 0 operators-and-special-methods}@anchor{d31}
@subsubsection Operators And Special Methods



@itemize *

@item 
@code{!=} now returns the opposite of @code{==}, unless @code{==} returns
@ref{203,,NotImplemented}.

@item 
The concept of "unbound methods" has been removed from the language.
When referencing a method as a class attribute, you now get a plain
function object.

@item 
@code{__getslice__()}, @code{__setslice__()} and @code{__delslice__()}
were killed.  The syntax @code{a[i:j]} now translates to
@code{a.__getitem__(slice(i, j))} (or @ref{d32,,__setitem__()} or
@ref{d33,,__delitem__()}, when used as an assignment or deletion target,
respectively).

@item 
@geindex Python 提高建议; PEP 3114
PEP 3114@footnote{https://www.python.org/dev/peps/pep-3114}: the standard @ref{77f,,next()} method has been renamed to
@ref{d34,,__next__()}.

@item 
The @code{__oct__()} and @code{__hex__()} special methods are removed
-- @ref{d35,,oct()} and @ref{d36,,hex()} use @ref{2c9,,__index__()} now to convert
the argument to an integer.

@item 
Removed support for @code{__members__} and @code{__methods__}.

@item 
The function attributes named @code{func_X} have been renamed to
use the @code{__X__} form, freeing up these names in the function
attribute namespace for user-defined attributes.  To wit,
@code{func_closure}, @code{func_code}, @code{func_defaults},
@code{func_dict}, @code{func_doc}, @code{func_globals},
@code{func_name} were renamed to @code{__closure__},
@code{__code__}, @code{__defaults__}, @ref{5fe,,__dict__},
@code{__doc__}, @code{__globals__}, @ref{d37,,__name__},
respectively.

@item 
@code{__nonzero__()} is now @ref{d38,,__bool__()}.
@end itemize

@node Builtins,,Operators And Special Methods,Miscellaneous Other Changes
@anchor{whatsnew/3 0 builtins}@anchor{d39}
@subsubsection Builtins



@itemize *

@item 
@geindex Python 提高建议; PEP 3135
PEP 3135@footnote{https://www.python.org/dev/peps/pep-3135}: New @ref{5e6,,super()}.  You can now invoke @ref{5e6,,super()}
without arguments and (assuming this is in a regular instance method
defined inside a @ref{d3a,,class} statement) the right class and
instance will automatically be chosen.  With arguments, the behavior
of @ref{5e6,,super()} is unchanged.

@item 
@geindex Python 提高建议; PEP 3111
PEP 3111@footnote{https://www.python.org/dev/peps/pep-3111}: @code{raw_input()} was renamed to @ref{d3b,,input()}.  That
is, the new @ref{d3b,,input()} function reads a line from
@ref{427,,sys.stdin} and returns it with the trailing newline stripped.
It raises @ref{d3c,,EOFError} if the input is terminated prematurely.
To get the old behavior of @ref{d3b,,input()}, use @code{eval(input())}.

@item 
A new built-in function @ref{77f,,next()} was added to call the
@ref{d34,,__next__()} method on an object.

@item 
The @ref{d3d,,round()} function rounding strategy and return type have
changed.  Exact halfway cases are now rounded to the nearest even
result instead of away from zero.  (For example, @code{round(2.5)} now
returns @code{2} rather than @code{3}.)  @code{round(x[, n])} now
delegates to @code{x.__round__([n])} instead of always returning a
float.  It generally returns an integer when called with a single
argument and a value of the same type as @code{x} when called with two
arguments.

@item 
Moved @code{intern()} to @ref{d3e,,sys.intern()}.

@item 
Removed: @code{apply()}.  Instead of @code{apply(f, args)} use
@code{f(*args)}.

@item 
Removed @ref{c1f,,callable()}.  Instead of @code{callable(f)} you can use
@code{isinstance(f, collections.Callable)}.  The @code{operator.isCallable()}
function is also gone.

@item 
Removed @code{coerce()}.  This function no longer serves a purpose
now that classic classes are gone.

@item 
Removed @code{execfile()}.  Instead of @code{execfile(fn)} use
@code{exec(open(fn).read())}.

@item 
Removed the @code{file} type.  Use @ref{16f,,open()}.  There are now several
different kinds of streams that open can return in the @ref{a1,,io} module.

@item 
Removed @code{reduce()}.  Use @ref{d3f,,functools.reduce()} if you really
need it; however, 99 percent of the time an explicit @ref{d02,,for}
loop is more readable.

@item 
Removed @code{reload()}.  Use @ref{d40,,imp.reload()}.

@item 
Removed. @code{dict.has_key()} -- use the @ref{179,,in} operator
instead.
@end itemize

@c ======================================================================

@node 构建和 C API 的改变<7>,性能,Miscellaneous Other Changes,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 build-and-c-api-changes}@anchor{d41}
@subsection 构建和 C API 的改变


Due to time constraints, here is a @emph{very} incomplete list of changes
to the C API.


@itemize *

@item 
Support for several platforms was dropped, including but not limited
to Mac OS 9, BeOS, RISCOS, Irix, and Tru64.

@item 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118}: 新的缓冲区 API.

@item 
@geindex Python 提高建议; PEP 3121
PEP 3121@footnote{https://www.python.org/dev/peps/pep-3121}: Extension Module Initialization & Finalization.

@item 
@geindex Python 提高建议; PEP 3123
PEP 3123@footnote{https://www.python.org/dev/peps/pep-3123}: Making @ref{d42,,PyObject_HEAD} conform to standard C.

@item 
No more C API support for restricted execution.

@item 
@code{PyNumber_Coerce()}, @code{PyNumber_CoerceEx()}, @code{PyMember_Get()}, and @code{PyMember_Set()} C API 已被移除。

@item 
New C API @ref{aa9,,PyImport_ImportModuleNoBlock()}, works like
@ref{d43,,PyImport_ImportModule()} but won't block on the import lock
(returning an error instead).

@item 
Renamed the boolean conversion C-level slot and method:
@code{nb_nonzero} is now @code{nb_bool}.

@item 
从 C API 中移除 @code{METH_OLDARGS} 和 @code{WITH_CYCLE_GC}。
@end itemize

@c ======================================================================

@node 性能,移植到 Python 3 0,构建和 C API 的改变<7>,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 performance}@anchor{d44}
@subsection 性能


The net result of the 3.0 generalizations is that Python 3.0 runs the
pystone benchmark around 10% slower than Python 2.5.  Most likely the
biggest cause is the removal of special-casing for small integers.
There's room for improvement, but it will happen after 3.0 is
released!

@c ======================================================================

@node 移植到 Python 3 0,,性能,Python 3 0 有什么新变化
@anchor{whatsnew/3 0 porting-to-python-3-0}@anchor{d45}
@subsection 移植到 Python 3.0


For porting existing Python 2.5 or 2.6 source code to Python 3.0, the
best strategy is the following:


@enumerate 0

@item 
(Prerequisite:) Start with excellent test coverage.

@item 
Port to Python 2.6.  This should be no more work than the average
port from Python 2.x to Python 2.(x+1).  Make sure all your tests
pass.

@item 
(Still using 2.6:) Turn on the @code{-3} command line switch.
This enables warnings about features that will be removed (or
change) in 3.0.  Run your test suite again, and fix code that you
get warnings about until there are no warnings left, and all your
tests still pass.

@item 
Run the @code{2to3} source-to-source translator over your source code
tree.  (See @ref{d46,,2to3 - 自动将 Python 2 代码转为 Python 3 代码} for more on this tool.)  Run the
result of the translation under Python 3.0.  Manually fix up any
remaining issues, fixing problems until all tests pass again.
@end enumerate

It is not recommended to try to write source code that runs unchanged
under both Python 2.6 and 3.0; you'd have to use a very contorted
coding style, e.g. avoiding @code{print} statements, metaclasses,
and much more.  If you are maintaining a library that needs to support
both Python 2.6 and Python 3.0, the best approach is to modify step 3
above by editing the 2.6 version of the source code and running the
@code{2to3} translator again, rather than editing the 3.0 version of the
source code.

For porting C extensions to Python 3.0, please see @ref{d47,,将扩展模块移植到 Python 3}.

@c ======================================================================

@node Python 2 7 有什么新变化,Python 2 6 有什么新变化,Python 3 0 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 7 doc}@anchor{d48}@anchor{whatsnew/2 7 what-s-new-in-python-2-7}@anchor{d49}
@section Python 2.7 有什么新变化


@*作者: 
A.M. Kuchling (amk at amk.ca)


@c hyperlink all the methods & functions.

@c T_STRING_INPLACE not described in main docs

@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.  Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number in a parenthetical comment.
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer some effort going through the SVN logs
@c when researching a change.

本文介绍了Python 2.7 的新功能。 Python 2.7 于2010年7月3日发布。

Numeric handling has been improved in many ways, for both
floating-point numbers and for the @ref{2c7,,Decimal} class.
There are some useful additions to the standard library, such as a
greatly enhanced @ref{124,,unittest} module, the @ref{5,,argparse} module
for parsing command-line options, convenient @ref{2f1,,OrderedDict}
and @ref{ac2,,Counter} classes in the @ref{1d,,collections} module,
and many other improvements.

Python 2.7 is planned to be the last of the 2.x releases, so we worked
on making it a good release for the long term.  To help with porting
to Python 3, several new features from the Python 3.x series have been
included in 2.7.

This article doesn't attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.7 at
@indicateurl{https://docs.python.org}. If you want to understand the rationale for
the design and implementation, refer to the PEP for a particular new
feature or the issue on @indicateurl{https://bugs.python.org} in which a change was
discussed.  Whenever possible, "What's New in Python" links to the
bug/patch item for each change.

@menu
* Python 2.x的未来: Python 2 x的未来. 
* 对于弃用警告处理方式的改变:: 
* Python 3.1 特性: Python 3 1 特性. 
* PEP 372; Adding an Ordered Dictionary to collections: PEP 372 Adding an Ordered Dictionary to collections. 
* PEP 378; 千位分隔符的格式说明符: PEP 378 千位分隔符的格式说明符<2>. 
* PEP 389; The argparse Module for Parsing Command Lines: PEP 389 The argparse Module for Parsing Command Lines. 
* PEP 391; Dictionary-Based Configuration For Logging: PEP 391 Dictionary-Based Configuration For Logging. 
* PEP 3106; 字典视图: PEP 3106 字典视图. 
* PEP 3137; memoryview 对象: PEP 3137 memoryview 对象. 
* 其他语言特性修改: 其他语言特性修改<10>. 
* 新增和改进的模块:: 
* 构建和 C API 的改变: 构建和 C API 的改变<8>. 
* 其他的改变和修正:: 
* 移植到 Python 2.7: 移植到 Python 2 7. 
* New Features Added to Python 2.7 Maintenance Releases: New Features Added to Python 2 7 Maintenance Releases. 
* 致谢:: 

@end menu

@node Python 2 x的未来,对于弃用警告处理方式的改变,,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 the-future-for-python-2-x}@anchor{d4a}@anchor{whatsnew/2 7 whatsnew27-python31}@anchor{d4b}
@subsection Python 2.x的未来


Python 2.7 是 2.x 系列中的最后一个主版本，因为Python 维护人员已将新功能开发工作的重点转移到了 Python 3.x 系列中。这意味着，尽管 Python 2 会继续修复bug并更新，以便在新的硬件和支持操作系统版本上正确构建，但不会有新的功能发布。

然而，尽管在 Python 2.7 和 Python 3 之间有一个很大的公共子集，并且迁移到该公共子集或直接迁移到 Python 3 所涉及的许多更改可以安全地自动化完成。但是一些其他更改（特别是那些与Unicode处理相关的更改）可能需要仔细考虑，并且最好用自动化回归测试套件进行健壮性测试，以便有效地迁移。

这意味着 Python2.7 将长期保留，为尚未移植到 Python 3 的生产系统提供一个稳定且受支持的基础平台。Python 2.7系列的预期完整生命周期在 
@geindex Python 提高建议; PEP 373
PEP 373@footnote{https://www.python.org/dev/peps/pep-0373} 中有详细介绍。

长期保留 2.7 版的的一些关键后果：


@itemize *

@item 
如上所述，与早期的2.x版本相比，2.7版本的维护时间更长。目前，预计核心开发团队将继续支持Python 2.7（接收安全更新和其他错误修复），直到至少2020年（首次发布后10年，相比之下，通常的支持期为18--24个月）。

@item 
随着 Python 2.7 标准库的老化，有效地利用 Python 包索引（直接或通过重新分发者）对 Python 2 用户来说变得更加重要。除了各种任务的第三方包之外，可用的包还包括与 Python 2 兼容的 Python 3 标准库中的新模块和功能的后端移植，以及各种工具和库，这些工具和库可以让用户更容易迁移到 Python 3。 Python 包用户指南@footnote{https://packaging.python.org} 提供了从 Python 包索引的下载和安装软件的指导。

@item 
虽然现在增强 Python 2 的首选方法是在Python包索引上发布新包，但这种方法不一定适用于所有情况，尤其是与网络安全相关的情况。在一些特殊情况下，如果在PyPI上发布新的或更新的包无法得到充分的处理，则可以使用Python增强建议过程来提出直接在Python 2标准库中添加新功能。任何此类添加及其添加的维护版本将在下面的 @ref{d4c,,New Features Added to Python 2.7 Maintenance Releases} 部分中注明。
@end itemize

对于希望从 Python2 迁移到 Python3 的项目，或者对于希望同时支持 Python2 和 Python3 用户的库和框架开发人员，可以使用各种工具和指南来帮助决定合适的方法并管理所涉及的一些技术细节。建议从 @ref{d4d,,将 Python 2 代码迁移到 Python 3} 操作指南开始。

@node 对于弃用警告处理方式的改变,Python 3 1 特性,Python 2 x的未来,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 changes-to-the-handling-of-deprecation-warnings}@anchor{d4e}
@subsection 对于弃用警告处理方式的改变


For Python 2.7, a policy decision was made to silence warnings only of
interest to developers by default.  @ref{15a,,DeprecationWarning} and its
descendants are now ignored unless otherwise requested, preventing
users from seeing warnings triggered by an application.  This change
was also made in the branch that became Python 3.2. (Discussed
on stdlib-sig and carried out in bpo-7319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7319}.)

In previous releases, @ref{15a,,DeprecationWarning} messages were
enabled by default, providing Python developers with a clear
indication of where their code may break in a future major version
of Python.

However, there are increasingly many users of Python-based
applications who are not directly involved in the development of
those applications.  @ref{15a,,DeprecationWarning} messages are
irrelevant to such users, making them worry about an application
that's actually working correctly and burdening application developers
with responding to these concerns.

You can re-enable display of @ref{15a,,DeprecationWarning} messages by
running Python with the @ref{15b,,-Wdefault} (short form:
@ref{15b,,-Wd}) switch, or by setting the 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS}
environment variable to @code{"default"} (or @code{"d"}) before running
Python.  Python code can also re-enable them
by calling @code{warnings.simplefilter('default')}.

The @code{unittest} module also automatically reenables deprecation warnings
when running tests.

@node Python 3 1 特性,PEP 372 Adding an Ordered Dictionary to collections,对于弃用警告处理方式的改变,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 python-3-1-features}@anchor{d4f}
@subsection Python 3.1 特性


就像 Python2.6 集成了 Python3.0 的特性一样，2.7版也集成了 Python3.1 中的一些新特性。2.x 系列继续提供迁移到3.x系列的工具。

3.1 功能的部分列表，这些功能已反向移植到 2.7：


@itemize *

@item 
用于集合字面值的语法 (@code{@{1,2,3@}} 是一个可变集合)。

@item 
字典与集合推导式 (@code{@{i: i*2 for i in range(3)@}})。

@item 
单个 @ref{7e4,,with} 语句中使用多个上下文管理器。

@item 
一个 @ref{a1,,io} 库的新版本，用 C 重写以提升性能。

@item 
@ref{d50,,PEP 372; Adding an Ordered Dictionary to collections} 所描述的有序字典类型。

@item 
@ref{d51,,PEP 378; 千位分隔符的格式说明符} 所描述的新的 @code{","} 格式说明符。

@item 
@ref{38d,,memoryview} 对象。

@item 
@ref{9a,,importlib} 模块的一个较小子集，@ref{d52,,described below}。

@item 
The @ref{8c3,,repr()} of a float @code{x} is shorter in many cases: it's now
based on the shortest decimal string that's guaranteed to round back
to @code{x}.  As in previous versions of Python, it's guaranteed that
@code{float(repr(x))} recovers @code{x}.

@item 
Float-to-string and string-to-float conversions are correctly rounded.
The @ref{d3d,,round()} function is also now correctly rounded.

@item 
The @ref{cda,,PyCapsule} type, used to provide a C API for extension modules.

@item 
The @ref{cd0,,PyLong_AsLongAndOverflow()} C API function.
@end itemize

Other new Python3-mode warnings include:


@itemize *

@item 
@code{operator.isCallable()} and @code{operator.sequenceIncludes()},
which are not supported in 3.x, now trigger warnings.

@item 
The @code{-3} switch now automatically
enables the @code{-Qwarn} switch that causes warnings
about using classic division with integers and long integers.
@end itemize

@c ========================================================================

@c Large, PEP-level features and changes should be described here.

@c ========================================================================

@node PEP 372 Adding an Ordered Dictionary to collections,PEP 378 千位分隔符的格式说明符<2>,Python 3 1 特性,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-0372}@anchor{d50}@anchor{whatsnew/2 7 pep-372-adding-an-ordered-dictionary-to-collections}@anchor{d53}
@subsection PEP 372: Adding an Ordered Dictionary to collections


Regular Python dictionaries iterate over key/value pairs in arbitrary order.
Over the years, a number of authors have written alternative implementations
that remember the order that the keys were originally inserted.  Based on
the experiences from those implementations, 2.7 introduces a new
@ref{2f1,,OrderedDict} class in the @ref{1d,,collections} module.

The @ref{2f1,,OrderedDict} API provides the same interface as regular
dictionaries but iterates over keys and values in a guaranteed order
depending on when a key was first inserted:

@example
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
...                  ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
@end example

If a new entry overwrites an existing entry, the original insertion
position is left unchanged:

@example
>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]
@end example

Deleting an entry and reinserting it will move it to the end:

@example
>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]
@end example

The @ref{d54,,popitem()} method has an optional @emph{last}
argument that defaults to @code{True}.  If @emph{last} is true, the most recently
added key is returned and removed; if it's false, the
oldest key is selected:

@example
>>> od = OrderedDict([(x,0) for x in range(20)])
>>> od.popitem()
(19, 0)
>>> od.popitem()
(18, 0)
>>> od.popitem(last=False)
(0, 0)
>>> od.popitem(last=False)
(1, 0)
@end example

Comparing two ordered dictionaries checks both the keys and values,
and requires that the insertion order was the same:

@example
>>> od1 = OrderedDict([('first', 1),
...                    ('second', 2),
...                    ('third', 3)])
>>> od2 = OrderedDict([('third', 3),
...                    ('first', 1),
...                    ('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True
@end example

Comparing an @ref{2f1,,OrderedDict} with a regular dictionary
ignores the insertion order and just compares the keys and values.

How does the @ref{2f1,,OrderedDict} work?  It maintains a
doubly-linked list of keys, appending new keys to the list as they're inserted.
A secondary dictionary maps keys to their corresponding list node, so
deletion doesn't have to traverse the entire linked list and therefore
remains O(1).

The standard library now supports use of ordered dictionaries in several
modules.


@itemize *

@item 
The @code{ConfigParser} module uses them by default, meaning that
configuration files can now be read, modified, and then written back
in their original order.

@item 
The @ref{2f0,,_asdict()} method for
@ref{1a1,,collections.namedtuple()} now returns an ordered dictionary with the
values appearing in the same order as the underlying tuple indices.

@item 
The @ref{a4,,json} module's @ref{708,,JSONDecoder} class
constructor was extended with an @emph{object_pairs_hook} parameter to
allow @code{OrderedDict} instances to be built by the decoder.
Support was also added for third-party tools like
PyYAML@footnote{http://pyyaml.org/}.
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 372

@item PEP 372@footnote{https://www.python.org/dev/peps/pep-0372} - 将有序词典添加到集合中

PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond Hettinger 实现。
@end table


@node PEP 378 千位分隔符的格式说明符<2>,PEP 389 The argparse Module for Parsing Command Lines,PEP 372 Adding an Ordered Dictionary to collections,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-0378}@anchor{d51}@anchor{whatsnew/2 7 pep-378-format-specifier-for-thousands-separator}@anchor{d55}
@subsection PEP 378: 千位分隔符的格式说明符


To make program output more readable, it can be useful to add
separators to large numbers, rendering them as
18,446,744,073,709,551,616 instead of 18446744073709551616.

The fully general solution for doing this is the @ref{a9,,locale} module,
which can use different separators ("," in North America, "." in
Europe) and different grouping sizes, but @ref{a9,,locale} is complicated
to use and unsuitable for multi-threaded applications where different
threads are producing output for different locales.

Therefore, a simple comma-grouping mechanism has been added to the
mini-language used by the @ref{5dd,,str.format()} method.  When
formatting a floating-point number, simply include a comma between the
width and the precision:

@example
>>> '@{:20,.2f@}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
@end example

When formatting an integer, include the comma after the width:

@example
>>> '@{:20,d@}'.format(18446744073709551616)
'18,446,744,073,709,551,616'
@end example

This mechanism is not adaptable at all; commas are always used as the
separator and the grouping is always into three-digit groups.  The
comma-formatting mechanism isn't as general as the @ref{a9,,locale}
module, but it's easier to use.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 378

@item PEP 378@footnote{https://www.python.org/dev/peps/pep-0378} - 千位分隔符的格式说明符

PEP 由 Raymond Hettinger 撰写，由 Eric Smith 实现
@end table


@node PEP 389 The argparse Module for Parsing Command Lines,PEP 391 Dictionary-Based Configuration For Logging,PEP 378 千位分隔符的格式说明符<2>,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-389-the-argparse-module-for-parsing-command-lines}@anchor{d56}
@subsection PEP 389: The argparse Module for Parsing Command Lines


The @ref{5,,argparse} module for parsing command-line arguments was
added as a more powerful replacement for the
@ref{c3,,optparse} module.

This means Python now supports three different modules for parsing
command-line arguments: @ref{85,,getopt}, @ref{c3,,optparse}, and
@ref{5,,argparse}.  The @ref{85,,getopt} module closely resembles the C
library's @code{getopt()} function, so it remains useful if you're writing a
Python prototype that will eventually be rewritten in C.
@ref{c3,,optparse} becomes redundant, but there are no plans to remove it
because there are many scripts still using it, and there's no
automated way to update these scripts.  (Making the @ref{5,,argparse}
API consistent with @ref{c3,,optparse}'s interface was discussed but
rejected as too messy and difficult.)

In short, if you're writing a new script and don't need to worry
about compatibility with earlier versions of Python, use
@ref{5,,argparse} instead of @ref{c3,,optparse}.

以下是为示例代码:

@example
import argparse

parser = argparse.ArgumentParser(description='Command-line example.')

# Add optional switches
parser.add_argument('-v', action='store_true', dest='is_verbose',
                    help='produce verbose output')
parser.add_argument('-o', action='store', dest='output',
                    metavar='FILE',
                    help='direct output to FILE instead of stdout')
parser.add_argument('-C', action='store', type=int, dest='context',
                    metavar='NUM', default=0,
                    help='display NUM lines of added context')

# Allow any number of additional arguments.
parser.add_argument(nargs='*', action='store', dest='inputs',
                    help='input filenames (default is stdin)')

args = parser.parse_args()
print args.__dict__
@end example

Unless you override it, @code{-h} and @code{--help} switches
are automatically added, and produce neatly formatted output:

@example
-> ./python.exe argparse-example.py --help
usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]

Command-line example.

positional arguments:
  inputs      input filenames (default is stdin)

optional arguments:
  -h, --help  show this help message and exit
  -v          produce verbose output
  -o FILE     direct output to FILE instead of stdout
  -C NUM      display NUM lines of added context
@end example

As with @ref{c3,,optparse}, the command-line switches and arguments
are returned as an object with attributes named by the @emph{dest} parameters:

@example
-> ./python.exe argparse-example.py -v
@{'output': None,
 'is_verbose': True,
 'context': 0,
 'inputs': []@}

-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
@{'output': '/tmp/output',
 'is_verbose': True,
 'context': 4,
 'inputs': ['file1', 'file2']@}
@end example

@ref{5,,argparse} has much fancier validation than @ref{c3,,optparse}; you
can specify an exact number of arguments as an integer, 0 or more
arguments by passing @code{'*'}, 1 or more by passing @code{'+'}, or an
optional argument with @code{'?'}.  A top-level parser can contain
sub-parsers to define subcommands that have different sets of
switches, as in @code{svn commit}, @code{svn checkout}, etc.  You can
specify an argument's type as @ref{917,,FileType}, which will
automatically open files for you and understands that @code{'-'} means
standard input or output.


@subsubheading 参见



@table @asis

@item @ref{5,,argparse} documentation

argparse 模块的文档页面。

@item @ref{c05,,升级 optparse 代码}

Part of the Python documentation, describing how to convert
code that uses @ref{c3,,optparse}.

@geindex Python 提高建议; PEP 389

@item PEP 389@footnote{https://www.python.org/dev/peps/pep-0389} - argparse - 新的命令行解析模块

PEP 由 Steven Bethard 撰写并实现。
@end table


@node PEP 391 Dictionary-Based Configuration For Logging,PEP 3106 字典视图,PEP 389 The argparse Module for Parsing Command Lines,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-391-dictionary-based-configuration-for-logging}@anchor{d57}
@subsection PEP 391: Dictionary-Based Configuration For Logging


The @ref{aa,,logging} module is very flexible; applications can define
a tree of logging subsystems, and each logger in this tree can filter
out certain messages, format them differently, and direct messages to
a varying number of handlers.

All this flexibility can require a lot of configuration.  You can
write Python statements to create objects and set their properties,
but a complex set-up requires verbose but boring code.
@ref{aa,,logging} also supports a @code{fileConfig()}
function that parses a file, but the file format doesn't support
configuring filters, and it's messier to generate programmatically.

Python 2.7 adds a @code{dictConfig()} function that
uses a dictionary to configure logging.  There are many ways to
produce a dictionary from different sources: construct one with code;
parse a file containing JSON; or use a YAML parsing library if one is
installed.  For more information see @ref{d58,,配置函数}.

The following example configures two loggers, the root logger and a
logger named "network".  Messages sent to the root logger will be
sent to the system log using the syslog protocol, and messages
to the "network" logger will be written to a @code{network.log} file
that will be rotated once the log reaches 1MB.

@example
import logging
import logging.config

configdict = @{
 'version': 1,    # Configuration schema in use; must be 1 for now
 'formatters': @{
     'standard': @{
         'format': ('%(asctime)s %(name)-15s '
                    '%(levelname)-8s %(message)s')@}@},

 'handlers': @{'netlog': @{'backupCount': 10,
                     'class': 'logging.handlers.RotatingFileHandler',
                     'filename': '/logs/network.log',
                     'formatter': 'standard',
                     'level': 'INFO',
                     'maxBytes': 1000000@},
              'syslog': @{'class': 'logging.handlers.SysLogHandler',
                         'formatter': 'standard',
                         'level': 'ERROR'@}@},

 # Specify all the subordinate loggers
 'loggers': @{
             'network': @{
                         'handlers': ['netlog']
             @}
 @},
 # Specify properties of the root logger
 'root': @{
          'handlers': ['syslog']
 @},
@}

# Set up configuration
logging.config.dictConfig(configdict)

# As an example, log two error messages
logger = logging.getLogger('/')
logger.error('Database not found')

netlogger = logging.getLogger('network')
netlogger.error('Connection failed')
@end example

Three smaller enhancements to the @ref{aa,,logging} module, all
implemented by Vinay Sajip, are:

@c rev79293


@itemize *

@item 
The @ref{b04,,SysLogHandler} class now supports
syslogging over TCP.  The constructor has a @emph{socktype} parameter
giving the type of socket to use, either @ref{d59,,socket.SOCK_DGRAM}
for UDP or @ref{d5a,,socket.SOCK_STREAM} for TCP.  The default
protocol remains UDP.

@item 
@ref{4b6,,Logger} instances gained a @ref{d5b,,getChild()}
method that retrieves a descendant logger using a relative path.
For example, once you retrieve a logger by doing @code{log = getLogger('app')},
calling @code{log.getChild('network.listen')} is equivalent to
@code{getLogger('app.network.listen')}.

@item 
The @ref{d5c,,LoggerAdapter} class gained an
@code{isEnabledFor()} method that takes a
@emph{level} and returns whether the underlying logger would
process a message of that level of importance.
@end itemize

@c XXX: Logger objects don't have a class declaration so the link don't work


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 391

@item PEP 391@footnote{https://www.python.org/dev/peps/pep-0391} - 基于字典的日志配置

PEP 由 Vinay Sajip 撰写并实现
@end table


@node PEP 3106 字典视图,PEP 3137 memoryview 对象,PEP 391 Dictionary-Based Configuration For Logging,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-3106-dictionary-views}@anchor{d5d}
@subsection PEP 3106: 字典视图


The dictionary methods @ref{cfc,,keys()}, @ref{cfe,,values()}, and
@ref{cfd,,items()} are different in Python 3.x.  They return an object
called a @emph{view} instead of a fully materialized list.

It's not possible to change the return values of @ref{cfc,,keys()},
@ref{cfe,,values()}, and @ref{cfd,,items()} in Python 2.7 because
too much code would break.  Instead the 3.x versions were added
under the new names @code{viewkeys()}, @code{viewvalues()},
and @code{viewitems()}.

@example
>>> d = dict((i*10, chr(65+i)) for i in range(26))
>>> d
@{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'@}
>>> d.viewkeys()
dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
@end example

Views can be iterated over, but the key and item views also behave
like sets.  The @code{&} operator performs intersection, and @code{|}
performs a union:

@example
>>> d1 = dict((i*10, chr(65+i)) for i in range(26))
>>> d2 = dict((i**.5, i) for i in range(1000))
>>> d1.viewkeys() & d2.viewkeys()
set([0.0, 10.0, 20.0, 30.0])
>>> d1.viewkeys() | range(0, 30)
set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
@end example

The view keeps track of the dictionary and its contents change as the
dictionary is modified:

@example
>>> vk = d.viewkeys()
>>> vk
dict_keys([0, 130, 10, ..., 250])
>>> d[260] = '&'
>>> vk
dict_keys([0, 130, 260, 10, ..., 250])
@end example

However, note that you can't add or remove keys while you're iterating
over the view:

@example
>>> for k in vk:
...     d[k*2] = k
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
@end example

You can use the view methods in Python 2.x code, and the 2to3
converter will change them to the standard @ref{cfc,,keys()},
@ref{cfe,,values()}, and @ref{cfd,,items()} methods.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3106

@item PEP 3106@footnote{https://www.python.org/dev/peps/pep-3106} - 改造 dict.keys(), .values() 和 .items()

PEP written by Guido van Rossum.
Backported to 2.7 by Alexandre Vassalotti; bpo-1967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1967}.
@end table


@node PEP 3137 memoryview 对象,其他语言特性修改<10>,PEP 3106 字典视图,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 pep-3137-the-memoryview-object}@anchor{d5e}
@subsection PEP 3137: memoryview 对象


The @ref{38d,,memoryview} object provides a view of another object's
memory content that matches the @ref{172,,bytes} type's interface.

@example
>>> import string
>>> m = memoryview(string.letters)
>>> m
<memory at 0x37f850>
>>> len(m)           # Returns length of underlying object
52
>>> m[0], m[25], m[26]   # Indexing returns one byte
('a', 'z', 'A')
>>> m2 = m[0:26]         # Slicing returns another memoryview
>>> m2
<memory at 0x37f080>
@end example

The content of the view can be converted to a string of bytes or
a list of integers:

@example
>>> m2.tobytes()
'abcdefghijklmnopqrstuvwxyz'
>>> m2.tolist()
[97, 98, 99, 100, 101, 102, 103, ... 121, 122]
>>>
@end example

@ref{38d,,memoryview} objects allow modifying the underlying object if
it's a mutable object.

@example
>>> m2[0] = 75
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> b = bytearray(string.letters)  # Creating a mutable object
>>> b
bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> mb = memoryview(b)
>>> mb[0] = '*'         # Assign to view, changing the bytearray.
>>> b[0:5]              # The bytearray has been changed.
bytearray(b'*bcde')
>>>
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3137

@item PEP 3137@footnote{https://www.python.org/dev/peps/pep-3137} - 不变字节和可变缓冲区

PEP written by Guido van Rossum.
Implemented by Travis Oliphant, Antoine Pitrou and others.
Backported to 2.7 by Antoine Pitrou; bpo-2396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2396}.
@end table


@node 其他语言特性修改<10>,新增和改进的模块,PEP 3137 memoryview 对象,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 other-language-changes}@anchor{d5f}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
The syntax for set literals has been backported from Python 3.x.
Curly brackets are used to surround the contents of the resulting
mutable set; set literals are
distinguished from dictionaries by not containing colons and values.
@code{@{@}} continues to represent an empty dictionary; use
@code{set()} for an empty set.

@example
>>> @{1, 2, 3, 4, 5@}
set([1, 2, 3, 4, 5])
>>> set() # empty set
set([])
>>> @{@}    # empty dict
@{@}
@end example

Backported by Alexandre Vassalotti; bpo-2335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2335}.

@item 
Dictionary and set comprehensions are another feature backported from
3.x, generalizing list/generator comprehensions to use
the literal syntax for sets and dictionaries.

@example
>>> @{x: x*x for x in range(6)@}
@{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25@}
>>> @{('a'*x) for x in range(6)@}
set(['@w{'}, 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
@end example

Backported by Alexandre Vassalotti; bpo-2333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2333}.

@item 
The @ref{7e4,,with} statement can now use multiple context managers
in one statement.  Context managers are processed from left to right
and each one is treated as beginning a new @code{with} statement.
This means that:

@example
with A() as a, B() as b:
    ... suite of statements ...
@end example

相当于:

@example
with A() as a:
    with B() as b:
        ... suite of statements ...
@end example

The @code{contextlib.nested()} function provides a very similar
function, so it's no longer necessary and has been deprecated.

(Proposed in @indicateurl{https://codereview.appspot.com/53094}; implemented by
Georg Brandl.)

@item 
Conversions between floating-point numbers and strings are
now correctly rounded on most platforms.  These conversions occur
in many different places: @ref{206,,str()} on
floats and complex numbers; the @ref{1fe,,float} and @ref{2c8,,complex}
constructors;
numeric formatting; serializing and
deserializing floats and complex numbers using the
@ref{b0,,marshal}, @ref{ca,,pickle}
and @ref{a4,,json} modules;
parsing of float and imaginary literals in Python code;
and @ref{2c7,,Decimal}-to-float conversion.

Related to this, the @ref{8c3,,repr()} of a floating-point number @emph{x}
now returns a result based on the shortest decimal string that's
guaranteed to round back to @emph{x} under correct rounding (with
round-half-to-even rounding mode).  Previously it gave a string
based on rounding x to 17 decimal digits.

@c maybe add an example?

The rounding library responsible for this improvement works on
Windows and on Unix platforms using the gcc, icc, or suncc
compilers.  There may be a small number of platforms where correct
operation of this code cannot be guaranteed, so the code is not
used on such systems.  You can find out which code is being used
by checking @ref{d60,,sys.float_repr_style},  which will be @code{short}
if the new code is in use and @code{legacy} if it isn't.

Implemented by Eric Smith and Mark Dickinson, using David Gay's
@code{dtoa.c} library; bpo-7117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7117}.

@item 
Conversions from long integers and regular integers to floating
point now round differently, returning the floating-point number
closest to the number.  This doesn't matter for small integers that
can be converted exactly, but for large numbers that will
unavoidably lose precision, Python 2.7 now approximates more
closely.  For example, Python 2.6 computed the following:

@example
>>> n = 295147905179352891391
>>> float(n)
2.9514790517935283e+20
>>> n - long(float(n))
65535L
@end example

Python 2.7's floating-point result is larger, but much closer to the
true value:

@example
>>> n = 295147905179352891391
>>> float(n)
2.9514790517935289e+20
>>> n - long(float(n))
-1L
@end example

(Implemented by Mark Dickinson; bpo-3166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3166}.)

Integer division is also more accurate in its rounding behaviours.  (Also
implemented by Mark Dickinson; bpo-1811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1811}.)

@item 
Implicit coercion for complex numbers has been removed; the interpreter
will no longer ever attempt to call a @code{__coerce__()} method on complex
objects.  (Removed by Meador Inge and Mark Dickinson; bpo-5211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5211}.)

@item 
The @ref{5dd,,str.format()} method now supports automatic numbering of the replacement
fields.  This makes using @ref{5dd,,str.format()} more closely resemble using
@code{%s} formatting:

@example
>>> '@{@}:@{@}:@{@}'.format(2009, 04, 'Sunday')
'2009:4:Sunday'
>>> '@{@}:@{@}:@{day@}'.format(2009, 4, day='Sunday')
'2009:4:Sunday'
@end example

The auto-numbering takes the fields from left to right, so the first @code{@{...@}}
specifier will use the first argument to @ref{5dd,,str.format()}, the next
specifier will use the next argument, and so on.  You can't mix auto-numbering
and explicit numbering -- either number all of your specifier fields or none
of them -- but you can mix auto-numbering and named fields, as in the second
example above.  (Contributed by Eric Smith; bpo-5237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5237}.)

Complex numbers now correctly support usage with @ref{5de,,format()},
and default to being right-aligned.
Specifying a precision or comma-separation applies to both the real
and imaginary parts of the number, but a specified field width and
alignment is applied to the whole of the resulting @code{1.5+3j}
output.  (Contributed by Eric Smith; bpo-1588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1588} and bpo-7988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7988}.)

The 'F' format code now always formats its output using uppercase characters,
so it will now produce 'INF' and 'NAN'.
(Contributed by Eric Smith; bpo-3382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3382}.)

A low-level change: the @ref{a38,,object.__format__()} method now triggers
a @ref{15c,,PendingDeprecationWarning} if it's passed a format string,
because the @ref{a38,,__format__()} method for @ref{3da,,object} converts
the object to a string representation and formats that.  Previously
the method silently applied the format string to the string
representation, but that could hide mistakes in Python code.  If
you're supplying formatting information such as an alignment or
precision, presumably you're expecting the formatting to be applied
in some object-specific way.  (Fixed by Eric Smith; bpo-7994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7994}.)

@item 
The @ref{205,,int()} and @code{long()} types gained a @code{bit_length}
method that returns the number of bits necessary to represent
its argument in binary:

@example
>>> n = 37
>>> bin(n)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124
@end example

(Contributed by Fredrik Johansson and Victor Stinner; bpo-3439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3439}.)

@item 
The @ref{cef,,import} statement will no longer try an absolute import
if a relative import (e.g. @code{from .os import sep}) fails.  This
fixes a bug, but could possibly break certain @code{import}
statements that were only working by accident.  (Fixed by Meador Inge;
bpo-7902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7902}.)

@item 
It's now possible for a subclass of the built-in @code{unicode} type
to override the @code{__unicode__()} method.  (Implemented by
Victor Stinner; bpo-1583863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1583863}.)

@item 
The @ref{173,,bytearray} type's @ref{d61,,translate()} method now accepts
@code{None} as its first argument.  (Fixed by Georg Brandl;
bpo-4759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4759}.)

@c XXX bytearray doesn't seem to be documented

@item 
When using @code{@@classmethod} and @code{@@staticmethod} to wrap
methods as class or static methods, the wrapper object now
exposes the wrapped function as their @code{__func__} attribute.
(Contributed by Amaury Forgeot d'Arc, after a suggestion by
George Sakkis; bpo-5982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5982}.)

@item 
When a restricted set of attributes were set using @code{__slots__},
deleting an unset attribute would not raise @ref{4aa,,AttributeError}
as you would expect.  Fixed by Benjamin Peterson; bpo-7604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7604}.)

@item 
Two new encodings are now supported: "cp720", used primarily for
Arabic text; and "cp858", a variant of CP 850 that adds the euro
symbol.  (CP720 contributed by Alexander Belchenko and Amaury
Forgeot d'Arc in bpo-1616979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1616979}; CP858 contributed by Tim Hatch in
bpo-8016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8016}.)

@item 
The @code{file} object will now set the @code{filename} attribute
on the @ref{a7c,,IOError} exception when trying to open a directory
on POSIX platforms (noted by Jan Kaliszewski; bpo-4764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4764}), and
now explicitly checks for and forbids writing to read-only file objects
instead of trusting the C library to catch and report the error
(fixed by Stefan Krah; bpo-5677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5677}).

@item 
The Python tokenizer now translates line endings itself, so the
@ref{2ee,,compile()} built-in function now accepts code using any
line-ending convention.  Additionally, it no longer requires that the
code end in a newline.

@item 
Extra parentheses in function definitions are illegal in Python 3.x,
meaning that you get a syntax error from @code{def f((x)): pass}.  In
Python3-warning mode, Python 2.7 will now warn about this odd usage.
(Noted by James Lingard; bpo-7362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7362}.)

@item 
It's now possible to create weak references to old-style class
objects.  New-style classes were always weak-referenceable.  (Fixed
by Antoine Pitrou; bpo-8268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8268}.)

@item 
When a module object is garbage-collected, the module's dictionary is
now only cleared if no one else is holding a reference to the
dictionary (bpo-7140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7140}).
@end itemize

@c ======================================================================

@menu
* Interpreter Changes:: 
* 性能优化: 性能优化<9>. 

@end menu

@node Interpreter Changes,性能优化<9>,,其他语言特性修改<10>
@anchor{whatsnew/2 7 interpreter-changes}@anchor{d62}@anchor{whatsnew/2 7 new-27-interpreter}@anchor{d63}
@subsubsection Interpreter Changes


A new environment variable, 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS},
allows controlling warnings.  It should be set to a string
containing warning settings, equivalent to those
used with the @ref{15b,,-W} switch, separated by commas.
(Contributed by Brian Curtin; bpo-7301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7301}.)

For example, the following setting will print warnings every time
they occur, but turn warnings from the @code{Cookie} module into an
error.  (The exact syntax for setting an environment variable varies
across operating systems and shells.)

@example
export PYTHONWARNINGS=all,error:::Cookie:0
@end example

@c ======================================================================

@node 性能优化<9>,,Interpreter Changes,其他语言特性修改<10>
@anchor{whatsnew/2 7 optimizations}@anchor{d64}
@subsubsection 性能优化


Several performance enhancements have been added:


@itemize *

@item 
A new opcode was added to perform the initial setup for
@ref{7e4,,with} statements, looking up the @ref{d65,,__enter__()} and
@ref{d66,,__exit__()} methods.  (Contributed by Benjamin Peterson.)

@item 
The garbage collector now performs better for one common usage
pattern: when many objects are being allocated without deallocating
any of them.  This would previously take quadratic
time for garbage collection, but now the number of full garbage collections
is reduced as the number of objects on the heap grows.
The new logic only performs a full garbage collection pass when
the middle generation has been collected 10 times and when the
number of survivor objects from the middle generation exceeds 10% of
the number of objects in the oldest generation.  (Suggested by Martin
von Löwis and implemented by Antoine Pitrou; bpo-4074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4074}.)

@item 
The garbage collector tries to avoid tracking simple containers
which can't be part of a cycle. In Python 2.7, this is now true for
tuples and dicts containing atomic types (such as ints, strings,
etc.). Transitively, a dict containing tuples of atomic types won't
be tracked either. This helps reduce the cost of each
garbage collection by decreasing the number of objects to be
considered and traversed by the collector.
(Contributed by Antoine Pitrou; bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688}.)

@item 
Long integers are now stored internally either in base @code{2**15} or in base
@code{2**30}, the base being determined at build time.  Previously, they
were always stored in base @code{2**15}.  Using base @code{2**30} gives
significant performance improvements on 64-bit machines, but
benchmark results on 32-bit machines have been mixed.  Therefore,
the default is to use base @code{2**30} on 64-bit machines and base @code{2**15}
on 32-bit machines; on Unix, there's a new configure option
@code{--enable-big-digits} that can be used to override this default.

Apart from the performance improvements this change should be
invisible to end users, with one exception: for testing and
debugging purposes there's a new structseq @code{sys.long_info} that
provides information about the internal format, giving the number of
bits per digit and the size in bytes of the C type used to store
each digit:

@example
>>> import sys
>>> sys.long_info
sys.long_info(bits_per_digit=30, sizeof_digit=4)
@end example

（由 Mark Dickinson在 bpo-4258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4258} 贡献）

Another set of changes made long objects a few bytes smaller: 2 bytes
smaller on 32-bit systems and 6 bytes on 64-bit.
(Contributed by Mark Dickinson; bpo-5260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5260}.)

@item 
The division algorithm for long integers has been made faster
by tightening the inner loop, doing shifts instead of multiplications,
and fixing an unnecessary extra iteration.
Various benchmarks show speedups of between 50% and 150% for long
integer divisions and modulo operations.
(Contributed by Mark Dickinson; bpo-5512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5512}.)
Bitwise operations are also significantly faster (initial patch by
Gregory Smith; bpo-1087418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1087418}).

@item 
The implementation of @code{%} checks for the left-side operand being
a Python string and special-cases it; this results in a 1--3%
performance increase for applications that frequently use @code{%}
with strings, such as templating libraries.
(Implemented by Collin Winter; bpo-5176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5176}.)

@item 
List comprehensions with an @code{if} condition are compiled into
faster bytecode.  (Patch by Antoine Pitrou, back-ported to 2.7
by Jeffrey Yasskin; bpo-4715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4715}.)

@item 
Converting an integer or long integer to a decimal string was made
faster by special-casing base 10 instead of using a generalized
conversion function that supports arbitrary bases.
(Patch by Gawain Bolton; bpo-6713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6713}.)

@item 
The @code{split()}, @code{replace()}, @code{rindex()},
@code{rpartition()}, and @code{rsplit()} methods of string-like types
(strings, Unicode strings, and @ref{173,,bytearray} objects) now use a
fast reverse-search algorithm instead of a character-by-character
scan.  This is sometimes faster by a factor of 10.  (Added by
Florent Xicluna; bpo-7462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7462} and bpo-7622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7622}.)

@item 
The @ref{ca,,pickle} and @code{cPickle} modules now automatically
intern the strings used for attribute names, reducing memory usage
of the objects resulting from unpickling.  (Contributed by Jake
McGuire; bpo-5084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5084}.)

@item 
The @code{cPickle} module now special-cases dictionaries,
nearly halving the time required to pickle them.
(Contributed by Collin Winter; bpo-5670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5670}.)
@end itemize

@c ======================================================================

@node 新增和改进的模块,构建和 C API 的改变<8>,其他语言特性修改<10>,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 new-and-improved-modules}@anchor{d67}
@subsection 新增和改进的模块


As in every release, Python's standard library received a number of
enhancements and bug fixes.  Here's a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
@code{Misc/NEWS} file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.


@itemize *

@item 
The @ref{e,,bdb} module's base debugging class @ref{d68,,Bdb}
gained a feature for skipping modules.  The constructor
now takes an iterable containing glob-style patterns such as
@code{django.*}; the debugger will not step into stack frames
from a module that matches one of these patterns.
(Contributed by Maru Newby after a suggestion by
Senthil Kumaran; bpo-5142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5142}.)

@item 
The @ref{f,,binascii} module now supports the buffer API, so it can be
used with @ref{38d,,memoryview} instances and other similar buffer objects.
(Backported from 3.x by Florent Xicluna; bpo-7703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7703}.)

@item 
Updated module: the @code{bsddb} module has been updated from 4.7.2devel9
to version 4.8.4 of
the pybsddb package@footnote{https://www.jcea.es/programacion/pybsddb.htm}.
The new version features better Python 3.x compatibility, various bug fixes,
and adds several new BerkeleyDB flags and methods.
(Updated by Jesús Cea Avión; bpo-8156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8156}.  The pybsddb
changelog can be read at @indicateurl{http://hg.jcea.es/pybsddb/file/tip/ChangeLog}.)

@item 
The @ref{13,,bz2} module's @ref{225,,BZ2File} now supports the context
management protocol, so you can write @code{with bz2.BZ2File(...) as f:}.
(Contributed by Hagen Fürstenau; bpo-3860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3860}.)

@item 
New class: the @ref{ac2,,Counter} class in the @ref{1d,,collections}
module is useful for tallying data.  @ref{ac2,,Counter} instances
behave mostly like dictionaries but return zero for missing keys instead of
raising a @ref{3f1,,KeyError}:

@example
>>> from collections import Counter
>>> c = Counter()
>>> for letter in 'here is a sample of english text':
...   c[letter] += 1
...
>>> c 
Counter(@{' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
'p': 1, 'r': 1, 'x': 1@})
>>> c['e']
5
>>> c['z']
0
@end example

There are three additional @ref{ac2,,Counter} methods.
@ref{d69,,most_common()} returns the N most common
elements and their counts.  @ref{d6a,,elements()}
returns an iterator over the contained elements, repeating each
element as many times as its count.
@ref{c35,,subtract()} takes an iterable and
subtracts one for each element instead of adding; if the argument is
a dictionary or another @code{Counter}, the counts are
subtracted.

@example
>>> c.most_common(5)
[(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
>>> c.elements() ->
   'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
   'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
   'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
   's', 's', 'r', 't', 't', 'x'
>>> c['e']
5
>>> c.subtract('very heavy on the letter e')
>>> c['e']    # Count is now lower
-1
@end example

Contributed by Raymond Hettinger; bpo-1696199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1696199}.

@c revision 79660

New class: @ref{2f1,,OrderedDict} is described in the earlier
section @ref{d50,,PEP 372; Adding an Ordered Dictionary to collections}.

New method: The @ref{633,,deque} data type now has a
@ref{c37,,count()} method that returns the number of
contained elements equal to the supplied argument @emph{x}, and a
@ref{c38,,reverse()} method that reverses the elements
of the deque in-place.  @ref{633,,deque} also exposes its maximum
length as the read-only @ref{d6b,,maxlen} attribute.
(Both features added by Raymond Hettinger.)

The @ref{1a1,,namedtuple} class now has an optional @emph{rename} parameter.
If @emph{rename} is true, field names that are invalid because they've
been repeated or aren't legal Python identifiers will be
renamed to legal names that are derived from the field's
position within the list of fields:

@example
>>> from collections import namedtuple
>>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
>>> T._fields
('field1', '_1', '_2', 'field2')
@end example

(Added by Raymond Hettinger; bpo-1818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1818}.)

Finally, the @code{Mapping} abstract base class now
returns @ref{203,,NotImplemented} if a mapping is compared to
another type that isn't a @code{Mapping}.
(Fixed by Daniel Stutzbach; bpo-8729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8729}.)

@item 
Constructors for the parsing classes in the @code{ConfigParser} module now
take an @emph{allow_no_value} parameter, defaulting to false; if true,
options without values will be allowed.  For example:

@example
>>> import ConfigParser, StringIO
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-bdb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(StringIO.StringIO(sample_config))
>>> config.get('mysqld', 'user')
'mysql'
>>> print config.get('mysqld', 'skip-bdb')
None
>>> print config.get('mysqld', 'unknown')
Traceback (most recent call last):
  ...
NoOptionError: No option 'unknown' in section: 'mysqld'
@end example

(Contributed by Mats Kindahl; bpo-7005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7005}.)

@item 
Deprecated function: @code{contextlib.nested()}, which allows
handling more than one context manager with a single @ref{7e4,,with}
statement, has been deprecated, because the @code{with} statement
now supports multiple context managers.

@item 
The @code{cookielib} module now ignores cookies that have an invalid
version field, one that doesn't contain an integer value.  (Fixed by
John J. Lee; bpo-3924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3924}.)

@item 
The @ref{25,,copy} module's @ref{4db,,deepcopy()} function will now
correctly copy bound instance methods.  (Implemented by
Robert Collins; bpo-1515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1515}.)

@item 
The @ref{2a,,ctypes} module now always converts @code{None} to a C @code{NULL}
pointer for arguments declared as pointers.  (Changed by Thomas
Heller; bpo-4606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4606}.)  The underlying libffi library@footnote{https://sourceware.org/libffi/} has been updated to version
3.0.9, containing various fixes for different platforms.  (Updated
by Matthias Klose; bpo-8142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8142}.)

@item 
New method: the @ref{30,,datetime} module's @ref{2d1,,timedelta} class
gained a @ref{d6c,,total_seconds()} method that returns the
number of seconds in the duration.  (Contributed by Brian Quinlan; bpo-5788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5788}.)

@item 
New method: the @ref{2c7,,Decimal} class gained a
@ref{c5a,,from_float()} class method that performs an exact
conversion of a floating-point number to a @ref{2c7,,Decimal}.
This exact conversion strives for the
closest decimal approximation to the floating-point representation's value;
the resulting decimal value will therefore still include the inaccuracy,
if any.
For example, @code{Decimal.from_float(0.1)} returns
@code{Decimal('0.1000000000000000055511151231257827021181583404541015625')}.
(Implemented by Raymond Hettinger; bpo-4796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4796}.)

Comparing instances of @ref{2c7,,Decimal} with floating-point
numbers now produces sensible results based on the numeric values
of the operands.  Previously such comparisons would fall back to
Python's default rules for comparing objects, which produced arbitrary
results based on their type.  Note that you still cannot combine
@code{Decimal} and floating-point in other operations such as addition,
since you should be explicitly choosing how to convert between float and
@ref{2c7,,Decimal}.  (Fixed by Mark Dickinson; bpo-2531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2531}.)

The constructor for @ref{2c7,,Decimal} now accepts
floating-point numbers (added by Raymond Hettinger; bpo-8257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8257})
and non-European Unicode characters such as Arabic-Indic digits
(contributed by Mark Dickinson; bpo-6595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6595}).

Most of the methods of the @ref{ad8,,Context} class now accept integers
as well as @ref{2c7,,Decimal} instances; the only exceptions are the
@ref{d6d,,canonical()} and @ref{d6e,,is_canonical()}
methods.  (Patch by Juan José Conti; bpo-7633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7633}.)

When using @ref{2c7,,Decimal} instances with a string's
@ref{5dd,,format()} method, the default alignment was previously
left-alignment.  This has been changed to right-alignment, which is
more sensible for numeric types.  (Changed by Mark Dickinson; bpo-6857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6857}.)

Comparisons involving a signaling NaN value (or @code{sNAN}) now signal
@code{InvalidOperation} instead of silently returning a true or
false value depending on the comparison operator.  Quiet NaN values
(or @code{NaN}) are now hashable.  (Fixed by Mark Dickinson;
bpo-7279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7279}.)

@item 
The @ref{36,,difflib} module now produces output that is more
compatible with modern @code{diff}/@code{patch} tools
through one small change, using a tab character instead of spaces as
a separator in the header giving the filename.  (Fixed by Anatoly
Techtonik; bpo-7585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7585}.)

@item 
The Distutils @code{sdist} command now always regenerates the
@code{MANIFEST} file, since even if the @code{MANIFEST.in} or
@code{setup.py} files haven't been modified, the user might have
created some new files that should be included.
(Fixed by Tarek Ziadé; bpo-8688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8688}.)

@item 
The @ref{66,,doctest} module's @code{IGNORE_EXCEPTION_DETAIL} flag
will now ignore the name of the module containing the exception
being tested.  (Patch by Lennart Regebro; bpo-7490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7490}.)

@item 
The @ref{67,,email} module's @ref{644,,Message} class will
now accept a Unicode-valued payload, automatically converting the
payload to the encoding specified by @code{output_charset}.
(Added by R. David Murray; bpo-1368247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1368247}.)

@item 
The @ref{2c5,,Fraction} class now accepts a single float or
@ref{2c7,,Decimal} instance, or two rational numbers, as
arguments to its constructor.  (Implemented by Mark Dickinson;
rationals added in bpo-5812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5812}, and float/decimal in
bpo-8294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8294}.)

Ordering comparisons (@code{<}, @code{<=}, @code{>}, @code{>=}) between
fractions and complex numbers now raise a @ref{1ff,,TypeError}.
This fixes an oversight, making the @ref{2c5,,Fraction}
match the other numeric types.

@c revision 79455

@item 
New class: @ref{1a7,,FTP_TLS} in
the @ref{82,,ftplib} module provides secure FTP
connections using TLS encapsulation of authentication as well as
subsequent control and data transfers.
(Contributed by Giampaolo Rodola; bpo-2054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2054}.)

The @ref{d6f,,storbinary()} method for binary uploads can now restart
uploads thanks to an added @emph{rest} parameter (patch by Pablo Mouzo;
bpo-6845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6845}.)

@item 
New class decorator: @ref{942,,total_ordering()} in the @ref{83,,functools}
module takes a class that defines an @ref{454,,__eq__()} method and one of
@ref{d06,,__lt__()}, @ref{d70,,__le__()}, @ref{d71,,__gt__()}, or @ref{d72,,__ge__()},
and generates the missing comparison methods.  Since the
@code{__cmp__()} method is being deprecated in Python 3.x,
this decorator makes it easier to define ordered classes.
(Added by Raymond Hettinger; bpo-5479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5479}.)

New function: @ref{c31,,cmp_to_key()} will take an old-style comparison
function that expects two arguments and return a new callable that
can be used as the @emph{key} parameter to functions such as
@ref{54f,,sorted()}, @ref{900,,min()} and @ref{901,,max()}, etc.  The primary
intended use is to help with making code compatible with Python 3.x.
(Added by Raymond Hettinger.)

@item 
New function: the @ref{84,,gc} module's @ref{d73,,is_tracked()} returns
true if a given instance is tracked by the garbage collector, false
otherwise. (Contributed by Antoine Pitrou; bpo-4688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4688}.)

@item 
The @ref{8b,,gzip} module's @ref{207,,GzipFile} now supports the context
management protocol, so you can write @code{with gzip.GzipFile(...) as f:}
(contributed by Hagen Fürstenau; bpo-3860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3860}), and it now implements
the @ref{689,,io.BufferedIOBase} ABC, so you can wrap it with
@ref{c64,,io.BufferedReader} for faster processing
(contributed by Nir Aides; bpo-7471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7471}).
It's also now possible to override the modification time
recorded in a gzipped file by providing an optional timestamp to
the constructor.  (Contributed by Jacques Frechet; bpo-4272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4272}.)

Files in gzip format can be padded with trailing zero bytes; the
@ref{8b,,gzip} module will now consume these trailing bytes.  (Fixed by
Tadek Pietraszek and Brian Curtin; bpo-2846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2846}.)

@item 
New attribute: the @ref{8c,,hashlib} module now has an @code{algorithms}
attribute containing a tuple naming the supported algorithms.
In Python 2.7, @code{hashlib.algorithms} contains
@code{('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')}.
(Contributed by Carl Chenet; bpo-7418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7418}.)

@item 
The default @code{HTTPResponse} class used by the @code{httplib} module now
supports buffering, resulting in much faster reading of HTTP responses.
(Contributed by Kristján Valur Jónsson; bpo-4879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4879}.)

The @code{HTTPConnection} and @code{HTTPSConnection} classes
now support a @emph{source_address} parameter, a @code{(host, port)} 2-tuple
giving the source address that will be used for the connection.
(Contributed by Eldon Ziegler; bpo-3972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3972}.)

@item 
The @code{ihooks} module now supports relative imports.  Note that
@code{ihooks} is an older module for customizing imports,
superseded by the @code{imputil} module added in Python 2.0.
(Relative import support added by Neil Schemenauer.)

@c revision 75423

@item 
The @ref{97,,imaplib} module now supports IPv6 addresses.
(Contributed by Derek Morr; bpo-1655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1655}.)

@item 
New function: the @ref{a0,,inspect} module's @ref{8ae,,getcallargs()}
takes a callable and its positional and keyword arguments,
and figures out which of the callable's parameters will receive each argument,
returning a dictionary mapping argument names to their values.  For example:

@example
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
>>> getcallargs(f, 1, 2, 3)
@{'a': 1, 'b': 2, 'pos': (3,), 'named': @{@}@}
>>> getcallargs(f, a=2, x=4)
@{'a': 2, 'b': 1, 'pos': (), 'named': @{'x': 4@}@}
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() takes at least 1 argument (0 given)
@end example

由 Georg Sakkis 在 bpo-3135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3135} 中贡献。

@item 
Updated module: The @ref{a1,,io} library has been upgraded to the version shipped with
Python 3.1.  For 3.1, the I/O library was entirely rewritten in C
and is 2 to 20 times faster depending on the task being performed.  The
original Python version was renamed to the @code{_pyio} module.

One minor resulting change: the @ref{d09,,io.TextIOBase} class now
has an @code{errors} attribute giving the error setting
used for encoding and decoding errors (one of @code{'strict'}, @code{'replace'},
@code{'ignore'}).

The @ref{d74,,io.FileIO} class now raises an @ref{30b,,OSError} when passed
an invalid file descriptor.  (Implemented by Benjamin Peterson;
bpo-4991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4991}.)  The @ref{d75,,truncate()} method now preserves the
file position; previously it would change the file position to the
end of the new file.  (Fixed by Pascal Chambon; bpo-6939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6939}.)

@item 
New function: @code{itertools.compress(data, selectors)} takes two
iterators.  Elements of @emph{data} are returned if the corresponding
value in @emph{selectors} is true:

@example
itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F
@end example

@c maybe here is better to use >>> list(itertools.compress(...)) instead

New function: @code{itertools.combinations_with_replacement(iter, r)}
returns all the possible @emph{r}-length combinations of elements from the
iterable @emph{iter}.  Unlike @ref{d76,,combinations()}, individual elements
can be repeated in the generated combinations:

@example
itertools.combinations_with_replacement('abc', 2) =>
  ('a', 'a'), ('a', 'b'), ('a', 'c'),
  ('b', 'b'), ('b', 'c'), ('c', 'c')
@end example

Note that elements are treated as unique depending on their position
in the input, not their actual values.

The @ref{ced,,itertools.count()} function now has a @emph{step} argument that
allows incrementing by values other than 1.  @ref{ced,,count()} also
now allows keyword arguments, and using non-integer values such as
floats or @ref{2c7,,Decimal} instances.  (Implemented by Raymond
Hettinger; bpo-5032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5032}.)

@ref{d76,,itertools.combinations()} and @ref{d77,,itertools.product()}
previously raised @ref{16d,,ValueError} for values of @emph{r} larger than
the input iterable.  This was deemed a specification error, so they
now return an empty iterator.  (Fixed by Raymond Hettinger; bpo-4816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4816}.)

@item 
Updated module: The @ref{a4,,json} module was upgraded to version 2.0.9 of the
simplejson package, which includes a C extension that makes
encoding and decoding faster.
(Contributed by Bob Ippolito; bpo-4136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4136}.)

To support the new @ref{2f1,,collections.OrderedDict} type, @ref{662,,json.load()}
now has an optional @emph{object_pairs_hook} parameter that will be called
with any object literal that decodes to a list of pairs.
(Contributed by Raymond Hettinger; bpo-5381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5381}.)

@item 
The @ref{ae,,mailbox} module's @ref{d78,,Maildir} class now records the
timestamp on the directories it reads, and only re-reads them if the
modification time has subsequently changed.  This improves
performance by avoiding unneeded directory scans.  (Fixed by
A.M. Kuchling and Antoine Pitrou; bpo-1607951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1607951}, bpo-6896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6896}.)

@item 
New functions: the @ref{b1,,math} module gained
@ref{55c,,erf()} and @ref{55d,,erfc()} for the error function and the complementary error function,
@ref{c43,,expm1()} which computes @code{e**x - 1} with more precision than
using @ref{d79,,exp()} and subtracting 1,
@ref{c44,,gamma()} for the Gamma function, and
@ref{c45,,lgamma()} for the natural log of the Gamma function.
(Contributed by Mark Dickinson and nirinA raseliarison; bpo-3366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3366}.)

@item 
The @ref{b7,,multiprocessing} module's @code{Manager*} classes
can now be passed a callable that will be called whenever
a subprocess is started, along with a set of arguments that will be
passed to the callable.
(Contributed by lekma; bpo-5585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5585}.)

The @code{Pool} class, which controls a pool of worker processes,
now has an optional @emph{maxtasksperchild} parameter.  Worker processes
will perform the specified number of tasks and then exit, causing the
@code{Pool} to start a new worker.  This is useful if tasks may leak
memory or other resources, or if some tasks will cause the worker to
become very large.
(Contributed by Charles Cazabon; bpo-6963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6963}.)

@item 
The @ref{c0,,nntplib} module now supports IPv6 addresses.
(Contributed by Derek Morr; bpo-1664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1664}.)

@item 
New functions: the @ref{c4,,os} module wraps the following POSIX system
calls: @ref{d7a,,getresgid()} and @ref{d7b,,getresuid()}, which return the
real, effective, and saved GIDs and UIDs;
@ref{d7c,,setresgid()} and @ref{d7d,,setresuid()}, which set
real, effective, and saved GIDs and UIDs to new values;
@ref{d7e,,initgroups()}, which initialize the group access list
for the current process.  (GID/UID functions
contributed by Travis H.; bpo-6508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6508}.  Support for initgroups added
by Jean-Paul Calderone; bpo-7333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7333}.)

The @ref{a4b,,os.fork()} function now re-initializes the import lock in
the child process; this fixes problems on Solaris when @ref{a4b,,fork()}
is called from a thread.  (Fixed by Zsolt Cserna; bpo-7242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7242}.)

@item 
In the @ref{c5,,os.path} module, the @ref{d7f,,normpath()} and
@ref{d80,,abspath()} functions now preserve Unicode; if their input path
is a Unicode string, the return value is also a Unicode string.
(@ref{d7f,,normpath()} fixed by Matt Giuca in bpo-5827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5827};
@ref{d80,,abspath()} fixed by Ezio Melotti in bpo-3426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3426}.)

@item 
The @ref{d9,,pydoc} module now has help for the various symbols that Python
uses.  You can now do @code{help('<<')} or @code{help('@@')}, for example.
(Contributed by David Laban; bpo-4739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4739}.)

@item 
The @ref{dd,,re} module's @ref{4d9,,split()}, @ref{582,,sub()}, and @ref{82d,,subn()}
now accept an optional @emph{flags} argument, for consistency with the
other functions in the module.  (Added by Gregory P. Smith.)

@item 
New function: @ref{d81,,run_path()} in the @ref{e2,,runpy} module
will execute the code at a provided @emph{path} argument.  @emph{path} can be
the path of a Python source file (@code{example.py}), a compiled
bytecode file (@code{example.pyc}), a directory
(@code{./package/}), or a zip archive (@code{example.zip}).  If a
directory or zip path is provided, it will be added to the front of
@code{sys.path} and the module @ref{1,,__main__} will be imported.  It's
expected that the directory or zip contains a @code{__main__.py};
if it doesn't, some other @code{__main__.py} might be imported from
a location later in @code{sys.path}.  This makes more of the machinery
of @ref{e2,,runpy} available to scripts that want to mimic the way
Python's command line processes an explicit path name.
(Added by Nick Coghlan; bpo-6816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6816}.)

@item 
New function: in the @ref{e9,,shutil} module, @ref{34f,,make_archive()}
takes a filename, archive type (zip or tar-format), and a directory
path, and creates an archive containing the directory's contents.
(Added by Tarek Ziadé.)

@ref{e9,,shutil}'s @ref{389,,copyfile()} and @ref{34e,,copytree()}
functions now raise a @code{SpecialFileError} exception when
asked to copy a named pipe.  Previously the code would treat
named pipes like a regular file by opening them for reading, and
this would block indefinitely.  (Fixed by Antoine Pitrou; bpo-3002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3002}.)

@item 
The @ref{ea,,signal} module no longer re-installs the signal handler
unless this is truly necessary, which fixes a bug that could make it
impossible to catch the EINTR signal robustly.  (Fixed by
Charles-Francois Natali; bpo-8354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8354}.)

@item 
New functions: in the @ref{eb,,site} module, three new functions
return various site- and user-specific paths.
@ref{ca9,,getsitepackages()} returns a list containing all
global site-packages directories,
@ref{cab,,getusersitepackages()} returns the path of the user's
site-packages directory, and
@ref{caa,,getuserbase()} returns the value of the 
@geindex USER_BASE
@geindex 环境变量; USER_BASE
@code{USER_BASE}
environment variable, giving the path to a directory that can be used
to store data.
(Contributed by Tarek Ziadé; bpo-6693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6693}.)

The @ref{eb,,site} module now reports exceptions occurring
when the @code{sitecustomize} module is imported, and will no longer
catch and swallow the @ref{2d3,,KeyboardInterrupt} exception.  (Fixed by
Victor Stinner; bpo-3137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3137}.)

@item 
The @ref{c77,,create_connection()} function
gained a @emph{source_address} parameter, a @code{(host, port)} 2-tuple
giving the source address that will be used for the connection.
(Contributed by Eldon Ziegler; bpo-3972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3972}.)

The @ref{d82,,recv_into()} and @ref{d83,,recvfrom_into()}
methods will now write into objects that support the buffer API, most usefully
the @ref{173,,bytearray} and @ref{38d,,memoryview} objects.  (Implemented by
Antoine Pitrou; bpo-8104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8104}.)

@item 
The @code{SocketServer} module's @code{TCPServer} class now
supports socket timeouts and disabling the Nagle algorithm.
The @code{disable_nagle_algorithm} class attribute
defaults to @code{False}; if overridden to be true,
new request connections will have the TCP_NODELAY option set to
prevent buffering many small sends into a single TCP packet.
The @code{timeout} class attribute can hold
a timeout in seconds that will be applied to the request socket; if
no request is received within that time, @code{handle_timeout()}
will be called and @code{handle_request()} will return.
(Contributed by Kristján Valur Jónsson; bpo-6192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6192} and bpo-6267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6267}.)

@item 
Updated module: the @ref{f2,,sqlite3} module has been updated to
version 2.6.0 of the pysqlite package@footnote{https://github.com/ghaering/pysqlite}. Version 2.6.0 includes a number of bugfixes, and adds
the ability to load SQLite extensions from shared libraries.
Call the @code{enable_load_extension(True)} method to enable extensions,
and then call @ref{c73,,load_extension()} to load a particular shared library.
(Updated by Gerhard Häring.)

@item 
The @ref{f3,,ssl} module's @ref{192,,SSLSocket} objects now support the
buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
bpo-7133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7133}) and automatically set
OpenSSL's @code{SSL_MODE_AUTO_RETRY}, which will prevent an error
code being returned from @code{recv()} operations that trigger an SSL
renegotiation (fix by Antoine Pitrou; bpo-8222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8222}).

The @ref{579,,ssl.wrap_socket()} constructor function now takes a
@emph{ciphers} argument that's a string listing the encryption algorithms
to be allowed; the format of the string is described
in the OpenSSL documentation@footnote{https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT}.
(Added by Antoine Pitrou; bpo-8322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8322}.)

Another change makes the extension load all of OpenSSL's ciphers and
digest algorithms so that they're all available.  Some SSL
certificates couldn't be verified, reporting an "unknown algorithm"
error.  (Reported by Beda Kosata, and fixed by Antoine Pitrou;
bpo-8484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8484}.)

The version of OpenSSL being used is now available as the module
attributes @ref{c7a,,ssl.OPENSSL_VERSION} (a string),
@ref{c7b,,ssl.OPENSSL_VERSION_INFO} (a 5-tuple), and
@ref{c7c,,ssl.OPENSSL_VERSION_NUMBER} (an integer).  (Added by Antoine
Pitrou; bpo-8321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8321}.)

@item 
The @ref{f8,,struct} module will no longer silently ignore overflow
errors when a value is too large for a particular integer format
code (one of @code{bBhHiIlLqQ}); it now always raises a
@ref{d84,,struct.error} exception.  (Changed by Mark Dickinson;
bpo-1523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1523}.)  The @ref{cde,,pack()} function will also
attempt to use @ref{2c9,,__index__()} to convert and pack non-integers
before trying the @ref{2ca,,__int__()} method or reporting an error.
(Changed by Mark Dickinson; bpo-8300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8300}.)

@item 
New function: the @ref{f9,,subprocess} module's
@ref{9ca,,check_output()} runs a command with a specified set of arguments
and returns the command's output as a string when the command runs without
error, or raises a @ref{d85,,CalledProcessError} exception otherwise.

@example
>>> subprocess.check_output(['df', '-h', '.'])
'Filesystem     Size   Used  Avail Capacity  Mounted on\n
/dev/disk0s2    52G    49G   3.0G    94%    /\n'

>>> subprocess.check_output(['df', '-h', '/bogus'])
  ...
subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
@end example

（由 Gregory P. Smith 贡献）

The @ref{f9,,subprocess} module will now retry its internal system calls
on receiving an @code{EINTR} signal.  (Reported by several people; final
patch by Gregory P. Smith in bpo-1068268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1068268}.)

@item 
New function: @ref{d86,,is_declared_global()} in the @ref{fc,,symtable} module
returns true for variables that are explicitly declared to be global,
false for ones that are implicitly global.
(Contributed by Jeremy Hylton.)

@item 
The @ref{ff,,syslog} module will now use the value of @code{sys.argv[0]} as the
identifier instead of the previous default value of @code{'python'}.
(Changed by Sean Reifschneider; bpo-8451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8451}.)

@item 
The @code{sys.version_info} value is now a named tuple, with attributes
named @code{major}, @code{minor}, @code{micro},
@code{releaselevel}, and @code{serial}.  (Contributed by Ross
Light; bpo-4285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4285}.)

@ref{696,,sys.getwindowsversion()} also returns a named tuple,
with attributes named @code{major}, @code{minor}, @code{build},
@ref{ce,,platform}, @code{service_pack}, @code{service_pack_major},
@code{service_pack_minor}, @code{suite_mask}, and
@code{product_type}.  (Contributed by Brian Curtin; bpo-7766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7766}.)

@item 
The @ref{101,,tarfile} module's default error handling has changed, to
no longer suppress fatal errors.  The default error level was previously 0,
which meant that errors would only result in a message being written to the
debug log, but because the debug log is not activated by default,
these errors go unnoticed.  The default error level is now 1,
which raises an exception if there's an error.
(Changed by Lars Gustäbel; bpo-7357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7357}.)

@ref{101,,tarfile} now supports filtering the @ref{c67,,TarInfo}
objects being added to a tar file.  When you call @ref{583,,add()},
you may supply an optional @emph{filter} argument
that's a callable.  The @emph{filter} callable will be passed the
@ref{c67,,TarInfo} for every file being added, and can modify and return it.
If the callable returns @code{None}, the file will be excluded from the
resulting archive.  This is more powerful than the existing
@emph{exclude} argument, which has therefore been deprecated.
(Added by Lars Gustäbel; bpo-6856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6856}.)
The @ref{c66,,TarFile} class also now supports the context management protocol.
(Added by Lars Gustäbel; bpo-7232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7232}.)

@item 
The @ref{d87,,wait()} method of the @ref{b8e,,threading.Event} class
now returns the internal flag on exit.  This means the method will usually
return true because @ref{d87,,wait()} is supposed to block until the
internal flag becomes true.  The return value will only be false if
a timeout was provided and the operation timed out.
(Contributed by Tim Lesher; bpo-1674032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1674032}.)

@item 
The Unicode database provided by the @ref{123,,unicodedata} module is
now used internally to determine which characters are numeric,
whitespace, or represent line breaks.  The database also
includes information from the @code{Unihan.txt} data file (patch
by Anders Chrigström and Amaury Forgeot d'Arc; bpo-1571184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1571184})
and has been updated to version 5.2.0 (updated by
Florent Xicluna; bpo-8024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8024}).

@item 
The @code{urlparse} module's @code{urlsplit()} now handles
unknown URL schemes in a fashion compliant with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html}: if the
URL is of the form @code{"<something>://..."}, the text before the
@code{://} is treated as the scheme, even if it's a made-up scheme that
the module doesn't know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '@w{'}, '//host/filename?query', '@w{'}, '@w{'})
@end example

Python 2.7 (and Python 2.6.5) will return:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '@w{'}, '@w{'})
@end example

(Python 2.7 actually produces slightly different output, since it
returns a named tuple instead of a standard tuple.)

The @code{urlparse} module also supports IPv6 literal addresses as defined by
@geindex RFC; RFC 2732
RFC 2732@footnote{https://tools.ietf.org/html/rfc2732.html} (contributed by Senthil Kumaran; bpo-2987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2987}).

@example
>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
            path='/foo', params='@w{'}, query='@w{'}, fragment='@w{'})
@end example

@item 
New class: the @ref{d88,,WeakSet} class in the @ref{131,,weakref}
module is a set that only holds weak references to its elements; elements
will be removed once there are no references pointing to them.
(Originally implemented in Python 3.x by Raymond Hettinger, and backported
to 2.7 by Michael Foord.)

@item 
The ElementTree library, @code{xml.etree}, no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like @code{<?xml-stylesheet href="#style1"?>})
or comment (which looks like @code{<!-- comment -->}).
(Patch by Neil Muller; bpo-2746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2746}.)

@item 
The XML-RPC client and server, provided by the @code{xmlrpclib} and
@code{SimpleXMLRPCServer} modules, have improved performance by
supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
to compress the XML being exchanged.  The gzip compression is
controlled by the @code{encode_threshold} attribute of
@code{SimpleXMLRPCRequestHandler}, which contains a size in bytes;
responses larger than this will be compressed.
(Contributed by Kristján Valur Jónsson; bpo-6267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6267}.)

@item 
The @ref{14b,,zipfile} module's @ref{52b,,ZipFile} now supports the context
management protocol, so you can write @code{with zipfile.ZipFile(...) as f:}.
(Contributed by Brian Curtin; bpo-5511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5511}.)

@ref{14b,,zipfile} now also supports archiving empty directories and
extracts them correctly.  (Fixed by Kuba Wieczorek; bpo-4710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4710}.)
Reading files out of an archive is faster, and interleaving
@ref{d89,,read()} and @code{readline()} now works correctly.
(Contributed by Nir Aides; bpo-7610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7610}.)

The @ref{d8a,,is_zipfile()} function now
accepts a file object, in addition to the path names accepted in earlier
versions.  (Contributed by Gabriel Genellina; bpo-4756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4756}.)

The @ref{d8b,,writestr()} method now has an optional @emph{compress_type} parameter
that lets you override the default compression method specified in the
@ref{52b,,ZipFile} constructor.  (Contributed by Ronald Oussoren;
bpo-6003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6003}.)
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@menu
* 新模块：importlib:: 
* 新模块：sysconfig:: 
* ttk; Themed Widgets for Tk: ttk Themed Widgets for Tk. 
* 更新的模块：unittest:: 
* 更新的模块：ElementTree 1.3: 更新的模块：ElementTree 1 3. 

@end menu

@node 新模块：importlib,新模块：sysconfig,,新增和改进的模块
@anchor{whatsnew/2 7 importlib-section}@anchor{d52}@anchor{whatsnew/2 7 new-module-importlib}@anchor{d8c}
@subsubsection 新模块：importlib


Python 3.1 includes the @ref{9a,,importlib} package, a re-implementation
of the logic underlying Python's @ref{cef,,import} statement.
@ref{9a,,importlib} is useful for implementors of Python interpreters and
to users who wish to write new importers that can participate in the
import process.  Python 2.7 doesn't contain the complete
@ref{9a,,importlib} package, but instead has a tiny subset that contains
a single function, @ref{bef,,import_module()}.

@code{import_module(name, package=None)} imports a module.  @emph{name} is
a string containing the module or package's name.  It's possible to do
relative imports by providing a string that begins with a @code{.}
character, such as @code{..utils.errors}.  For relative imports, the
@emph{package} argument must be provided and is the name of the package that
will be used as the anchor for
the relative import.  @ref{bef,,import_module()} both inserts the imported
module into @code{sys.modules} and returns the module object.

这是一些例子:

@example
>>> from importlib import import_module
>>> anydbm = import_module('anydbm')  # Standard absolute import
>>> anydbm
<module 'anydbm' from '/p/python/Lib/anydbm.py'>
>>> # Relative import
>>> file_util = import_module('..file_util', 'distutils.command')
>>> file_util
<module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
@end example

@ref{9a,,importlib} was implemented by Brett Cannon and introduced in
Python 3.1.

@node 新模块：sysconfig,ttk Themed Widgets for Tk,新模块：importlib,新增和改进的模块
@anchor{whatsnew/2 7 new-module-sysconfig}@anchor{d8d}
@subsubsection 新模块：sysconfig


The @ref{fe,,sysconfig} module has been pulled out of the Distutils
package, becoming a new top-level module in its own right.
@ref{fe,,sysconfig} provides functions for getting information about
Python's build process: compiler switches, installation paths, the
platform name, and whether Python is running from its source
directory.

Some of the functions in the module are:


@itemize *

@item 
@ref{a4e,,get_config_var()} returns variables from Python's
Makefile and the @code{pyconfig.h} file.

@item 
@ref{a4f,,get_config_vars()} returns a dictionary containing
all of the configuration variables.

@item 
@ref{d8e,,get_path()} returns the configured path for
a particular type of module: the standard library,
site-specific modules, platform-specific modules, etc.

@item 
@ref{d8f,,is_python_build()} returns true if you're running a
binary from a Python source tree, and false otherwise.
@end itemize

Consult the @ref{fe,,sysconfig} documentation for more details and for
a complete list of functions.

The Distutils package and @ref{fe,,sysconfig} are now maintained by Tarek
Ziadé, who has also started a Distutils2 package (source repository at
@indicateurl{https://hg.python.org/distutils2/}) for developing a next-generation
version of Distutils.

@node ttk Themed Widgets for Tk,更新的模块：unittest,新模块：sysconfig,新增和改进的模块
@anchor{whatsnew/2 7 ttk-themed-widgets-for-tk}@anchor{d90}
@subsubsection ttk: Themed Widgets for Tk


Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
widgets but have a more customizable appearance and can therefore more
closely resemble the native platform's widgets.  This widget
set was originally called Tile, but was renamed to Ttk (for "themed Tk")
on being added to Tcl/Tck release 8.5.

To learn more, read the @code{ttk} module documentation.  You may also
wish to read the Tcl/Tk manual page describing the
Ttk theme engine, available at
@indicateurl{https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm}. Some
screenshots of the Python/Ttk code in use are at
@indicateurl{https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki}.

The @code{ttk} module was written by Guilherme Polo and added in
bpo-2983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2983}.  An alternate version called @code{Tile.py}, written by
Martin Franklin and maintained by Kevin Walzer, was proposed for
inclusion in bpo-2618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2618}, but the authors argued that Guilherme
Polo's work was more comprehensive.

@node 更新的模块：unittest,更新的模块：ElementTree 1 3,ttk Themed Widgets for Tk,新增和改进的模块
@anchor{whatsnew/2 7 unittest-section}@anchor{d91}@anchor{whatsnew/2 7 updated-module-unittest}@anchor{d92}
@subsubsection 更新的模块：unittest


The @ref{124,,unittest} module was greatly enhanced; many
new features were added.  Most of these features were implemented
by Michael Foord, unless otherwise noted.  The enhanced version of
the module is downloadable separately for use with Python versions 2.4 to 2.6,
packaged as the @code{unittest2} package, from
@indicateurl{https://pypi.org/project/unittest2}.

When used from the command line, the module can automatically discover
tests.  It's not as fancy as py.test@footnote{http://pytest.org} or
nose@footnote{https://nose.readthedocs.io/}, but provides a
simple way to run tests kept within a set of package directories.  For example,
the following command will search the @code{test/} subdirectory for
any importable test files named @code{test*.py}:

@example
python -m unittest discover -s test
@end example

Consult the @ref{124,,unittest} module documentation for more details.
(Developed in bpo-6001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6001}.)

The @ref{9f1,,main()} function supports some other new options:


@itemize *

@item 
@ref{d93,,-b} or @code{--buffer} will buffer the standard output
and standard error streams during each test.  If the test passes,
any resulting output will be discarded; on failure, the buffered
output will be displayed.

@item 
@ref{d94,,-c} or @code{--catch} will cause the control-C interrupt
to be handled more gracefully.  Instead of interrupting the test
process immediately, the currently running test will be completed
and then the partial results up to the interruption will be reported.
If you're impatient, a second press of control-C will cause an immediate
interruption.

This control-C handler tries to avoid causing problems when the code
being tested or the tests being run have defined a signal handler of
their own, by noticing that a signal handler was already set and
calling it.  If this doesn't work for you, there's a
@ref{d95,,removeHandler()} decorator that can be used to mark tests that
should have the control-C handling disabled.

@item 
@ref{d96,,-f} or @code{--failfast} makes
test execution stop immediately when a test fails instead of
continuing to execute further tests.  (Suggested by Cliff Dyer and
implemented by Michael Foord; bpo-8074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8074}.)
@end itemize

The progress messages now show 'x' for expected failures
and 'u' for unexpected successes when run in verbose mode.
(Contributed by Benjamin Peterson.)

Test cases can raise the @ref{9f2,,SkipTest} exception to skip a
test (bpo-1034053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1034053}).

The error messages for @ref{c8d,,assertEqual()},
@ref{c8c,,assertTrue()}, and @ref{d97,,assertFalse()}
failures now provide more information.  If you set the
@ref{d98,,longMessage} attribute of your @ref{9ee,,TestCase} classes to
true, both the standard error message and any additional message you
provide will be printed for failures.  (Added by Michael Foord; bpo-5663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5663}.)

The @ref{b9b,,assertRaises()} method now
returns a context handler when called without providing a callable
object to run.  For example, you can write this:

@example
with self.assertRaises(KeyError):
    @{@}['foo']
@end example

(Implemented by Antoine Pitrou; bpo-4444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4444}.)

@c rev 78774

Module- and class-level setup and teardown fixtures are now supported.
Modules can contain @code{setUpModule()} and @code{tearDownModule()}
functions.  Classes can have @ref{37d,,setUpClass()} and
@ref{d99,,tearDownClass()} methods that must be defined as class methods
(using @code{@@classmethod} or equivalent).  These functions and
methods are invoked when the test runner switches to a test case in a
different module or class.

The methods @ref{3cd,,addCleanup()} and
@ref{d9a,,doCleanups()} were added.
@ref{3cd,,addCleanup()} lets you add cleanup functions that
will be called unconditionally (after @ref{d9b,,setUp()} if
@ref{d9b,,setUp()} fails, otherwise after @ref{d9c,,tearDown()}). This allows
for much simpler resource allocation and deallocation during tests
(bpo-5679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5679}).

A number of new methods were added that provide more specialized
tests.  Many of these methods were written by Google engineers
for use in their test suites; Gregory P. Smith, Michael Foord, and
GvR worked on merging them into Python's version of @ref{124,,unittest}.


@itemize *

@item 
@ref{d9d,,assertIsNone()} and @ref{d9e,,assertIsNotNone()} take one
expression and verify that the result is or is not @code{None}.

@item 
@ref{d9f,,assertIs()} and @ref{da0,,assertIsNot()}
take two values and check whether the two values evaluate to the same object or not.
(Added by Michael Foord; bpo-2578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2578}.)

@item 
@ref{da1,,assertIsInstance()} and
@ref{da2,,assertNotIsInstance()} check whether
the resulting object is an instance of a particular class, or of
one of a tuple of classes.  (Added by Georg Brandl; bpo-7031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7031}.)

@item 
@ref{da3,,assertGreater()}, @ref{da4,,assertGreaterEqual()},
@ref{da5,,assertLess()}, and @ref{da6,,assertLessEqual()} compare
two quantities.

@item 
@ref{da7,,assertMultiLineEqual()} compares two strings, and if they're
not equal, displays a helpful comparison that highlights the
differences in the two strings.  This comparison is now used by
default when Unicode strings are compared with @ref{c8d,,assertEqual()}.

@item 
@code{assertRegexpMatches()} and
@code{assertNotRegexpMatches()} checks whether the
first argument is a string matching or not matching the regular
expression provided as the second argument (bpo-8038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8038}).

@item 
@code{assertRaisesRegexp()} checks whether a particular exception
is raised, and then also checks that the string representation of
the exception matches the provided regular expression.

@item 
@ref{da8,,assertIn()} and @ref{da9,,assertNotIn()}
tests whether @emph{first} is or is not in  @emph{second}.

@item 
@code{assertItemsEqual()} tests whether two provided sequences
contain the same elements.

@item 
@ref{daa,,assertSetEqual()} compares whether two sets are equal, and
only reports the differences between the sets in case of error.

@item 
Similarly, @ref{dab,,assertListEqual()} and @ref{dac,,assertTupleEqual()}
compare the specified types and explain any differences without necessarily
printing their full values; these methods are now used by default
when comparing lists and tuples using @ref{c8d,,assertEqual()}.
More generally, @ref{dad,,assertSequenceEqual()} compares two sequences
and can optionally check whether both sequences are of a
particular type.

@item 
@ref{dae,,assertDictEqual()} compares two dictionaries and reports the
differences; it's now used by default when you compare two dictionaries
using @ref{c8d,,assertEqual()}.  @code{assertDictContainsSubset()} checks whether
all of the key/value pairs in @emph{first} are found in @emph{second}.

@item 
@ref{c8f,,assertAlmostEqual()} and @ref{c90,,assertNotAlmostEqual()} test
whether @emph{first} and @emph{second} are approximately equal.  This method
can either round their difference to an optionally-specified number
of @emph{places} (the default is 7) and compare it to zero, or require
the difference to be smaller than a supplied @emph{delta} value.

@item 
@ref{daf,,loadTestsFromName()} properly honors the
@ref{db0,,suiteClass} attribute of
the @ref{87b,,TestLoader}. (Fixed by Mark Roddy; bpo-6866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6866}.)

@item 
A new hook lets you extend the @ref{c8d,,assertEqual()} method to handle
new data types.  The @ref{db1,,addTypeEqualityFunc()} method takes a type
object and a function. The function will be used when both of the
objects being compared are of the specified type.  This function
should compare the two objects and raise an exception if they don't
match; it's a good idea for the function to provide additional
information about why the two objects aren't matching, much as the new
sequence comparison methods do.
@end itemize

@ref{9f1,,unittest.main()} now takes an optional @code{exit} argument.  If
false, @ref{9f1,,main()} doesn't call @ref{db2,,sys.exit()}, allowing
@ref{9f1,,main()} to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; bpo-3379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3379}.)

@ref{ba0,,TestResult} has new @ref{db3,,startTestRun()} and
@ref{db4,,stopTestRun()} methods that are called immediately before
and after a test run.  (Contributed by Robert Collins; bpo-5728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5728}.)

With all these changes, the @code{unittest.py} was becoming awkwardly
large, so the module was turned into a package and the code split into
several files (by Benjamin Peterson).  This doesn't affect how the
module is imported or used.


@subsubheading 参见



@table @asis

@item @indicateurl{http://www.voidspace.org.uk/python/articles/unittest2.shtml}

Describes the new features, how to use them, and the
rationale for various design decisions.  (By Michael Foord.)
@end table


@node 更新的模块：ElementTree 1 3,,更新的模块：unittest,新增和改进的模块
@anchor{whatsnew/2 7 elementtree-section}@anchor{db5}@anchor{whatsnew/2 7 updated-module-elementtree-1-3}@anchor{db6}
@subsubsection 更新的模块：ElementTree 1.3


The version of the ElementTree library included with Python was updated to
version 1.3.  Some of the new features are:


@itemize *

@item 
The various parsing functions now take a @emph{parser} keyword argument
giving an @ref{383,,XMLParser} instance that will
be used.  This makes it possible to override the file's internal encoding:

@example
p = ET.XMLParser(encoding='utf-8')
t = ET.XML("""<root/>""", parser=p)
@end example

Errors in parsing XML now raise a @code{ParseError} exception, whose
instances have a @code{position} attribute
containing a (@emph{line}, @emph{column}) tuple giving the location of the problem.

@item 
ElementTree's code for converting trees to a string has been
significantly reworked, making it roughly twice as fast in many
cases.  The @ref{a06,,ElementTree.write()}
and @code{Element.write()} methods now have a @emph{method} parameter that can be
"xml" (the default), "html", or "text".  HTML mode will output empty
elements as @code{<empty></empty>} instead of @code{<empty/>}, and text
mode will skip over elements and only output the text chunks.  If
you set the @code{tag} attribute of an element to @code{None} but
leave its children in place, the element will be omitted when the
tree is written out, so you don't need to do more extensive rearrangement
to remove a single element.

Namespace handling has also been improved.  All @code{xmlns:<whatever>}
declarations are now output on the root element, not scattered throughout
the resulting XML.  You can set the default namespace for a tree
by setting the @code{default_namespace} attribute and can
register new prefixes with @ref{c2b,,register_namespace()}.  In XML mode,
you can use the true/false @emph{xml_declaration} parameter to suppress the
XML declaration.

@item 
New @ref{21e,,Element} method:
@ref{c2c,,extend()} appends the items from a
sequence to the element's children.  Elements themselves behave like
sequences, so it's easy to move children from one element to
another:

@example
from xml.etree import ElementTree as ET

t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")
new = ET.XML('<root/>')
new.extend(t)

# Outputs <root><item>1</item>...</root>
print ET.tostring(new)
@end example

@item 
New @code{Element} method:
@ref{db7,,iter()} yields the children of the
element as a generator.  It's also possible to write @code{for child in
elem:} to loop over an element's children.  The existing method
@code{getiterator()} is now deprecated, as is @code{getchildren()}
which constructs and returns a list of children.

@item 
New @code{Element} method:
@ref{c2e,,itertext()} yields all chunks of
text that are descendants of the element.  For example:

@example
t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")

# Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
print list(t.itertext())
@end example

@item 
Deprecated: using an element as a Boolean (i.e., @code{if elem:}) would
return true if the element had any children, or false if there were
no children.  This behaviour is confusing -- @code{None} is false, but
so is a childless element? -- so it will now trigger a
@ref{43e,,FutureWarning}.  In your code, you should be explicit: write
@code{len(elem) != 0} if you're interested in the number of children,
or @code{elem is not None}.
@end itemize

Fredrik Lundh develops ElementTree and produced the 1.3 version;
you can read his article describing 1.3 at
@indicateurl{https://web.archive.org/web/20200703234532/http://effbot.org/zone/elementtree-13-intro.htm}.
Florent Xicluna updated the version included with
Python, after discussions on python-dev and in bpo-6472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6472}.)

@c ======================================================================

@node 构建和 C API 的改变<8>,其他的改变和修正,新增和改进的模块,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 build-and-c-api-changes}@anchor{db8}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
The latest release of the GNU Debugger, GDB 7, can be scripted using Python@footnote{https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html}.
When you begin debugging an executable program P, GDB will look for
a file named @code{P-gdb.py} and automatically read it.  Dave Malcolm
contributed a @code{python-gdb.py} that adds a number of
commands useful when debugging Python itself.  For example,
@code{py-up} and @code{py-down} go up or down one Python stack frame,
which usually corresponds to several C stack frames.  @code{py-print}
prints the value of a Python variable, and @code{py-bt} prints the
Python stack trace.  (Added as a result of bpo-8032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8032}.)

@item 
If you use the @code{.gdbinit} file provided with Python,
the "pyo" macro in the 2.7 version now works correctly when the thread being
debugged doesn't hold the GIL; the macro now acquires it before printing.
(Contributed by Victor Stinner; bpo-3632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3632}.)

@item 
@ref{260,,Py_AddPendingCall()} is now thread-safe, letting any
worker thread submit notifications to the main Python thread.  This
is particularly useful for asynchronous IO operations.
(Contributed by Kristján Valur Jónsson; bpo-4293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4293}.)

@item 
New function: @ref{db9,,PyCode_NewEmpty()} creates an empty code object;
only the filename, function name, and first line number are required.
This is useful for extension modules that are attempting to
construct a more useful traceback stack.  Previously such
extensions needed to call @ref{3a3,,PyCode_New()}, which had many
more arguments.  (Added by Jeffrey Yasskin.)

@item 
New function: @ref{cd2,,PyErr_NewExceptionWithDoc()} creates a new
exception class, just as the existing @ref{cd3,,PyErr_NewException()} does,
but takes an extra @code{char *} argument containing the docstring for the
new exception class.  (Added by 'lekma' on the Python bug tracker;
bpo-7033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7033}.)

@item 
New function: @ref{24c,,PyFrame_GetLineNumber()} takes a frame object
and returns the line number that the frame is currently executing.
Previously code would need to get the index of the bytecode
instruction currently executing, and then look up the line number
corresponding to that address.  (Added by Jeffrey Yasskin.)

@item 
New functions: @ref{cd0,,PyLong_AsLongAndOverflow()} and
@ref{ccf,,PyLong_AsLongLongAndOverflow()}  approximates a Python long
integer as a C @code{long} or @code{long long}.
If the number is too large to fit into
the output type, an @emph{overflow} flag is set and returned to the caller.
(Contributed by Case Van Horsen; bpo-7528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7528} and bpo-7767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7767}.)

@item 
New function: stemming from the rewrite of string-to-float conversion,
a new @ref{cf5,,PyOS_string_to_double()} function was added.  The old
@code{PyOS_ascii_strtod()} and @code{PyOS_ascii_atof()} functions
are now deprecated.

@item 
New function: @ref{ccd,,PySys_SetArgvEx()} sets the value of
@code{sys.argv} and can optionally update @code{sys.path} to include the
directory containing the script named by @code{sys.argv[0]} depending
on the value of an @emph{updatepath} parameter.

This function was added to close a security hole for applications
that embed Python.  The old function, @ref{dba,,PySys_SetArgv()}, would
always update @code{sys.path}, and sometimes it would add the current
directory.  This meant that, if you ran an application embedding
Python in a directory controlled by someone else, attackers could
put a Trojan-horse module in the directory (say, a file named
@code{os.py}) that your application would then import and run.

If you maintain a C/C++ application that embeds Python, check
whether you're calling @ref{dba,,PySys_SetArgv()} and carefully consider
whether the application should be using @ref{ccd,,PySys_SetArgvEx()}
with @emph{updatepath} set to false.

Security issue reported as CVE-2008-5983@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983};
discussed in bpo-5753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5753}, and fixed by Antoine Pitrou.

@item 
New macros: the Python header files now define the following macros:
@code{Py_ISALNUM},
@code{Py_ISALPHA},
@code{Py_ISDIGIT},
@code{Py_ISLOWER},
@code{Py_ISSPACE},
@code{Py_ISUPPER},
@code{Py_ISXDIGIT},
@code{Py_TOLOWER}, and @code{Py_TOUPPER}.
All of these functions are analogous to the C
standard macros for classifying characters, but ignore the current
locale setting, because in
several places Python needs to analyze characters in a
locale-independent way.  (Added by Eric Smith;
bpo-5793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5793}.)

@c XXX these macros don't seem to be described in the c-api docs.

@item 
Removed function: @code{PyEval_CallObject} is now only available
as a macro.  A function version was being kept around to preserve
ABI linking compatibility, but that was in 1997; it can certainly be
deleted by now.  (Removed by Antoine Pitrou; bpo-8276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8276}.)

@item 
New format codes: the @code{PyFormat_FromString()},
@code{PyFormat_FromStringV()}, and @ref{8a2,,PyErr_Format()} functions now
accept @code{%lld} and @code{%llu} format codes for displaying
C's @code{long long} types.
(Contributed by Mark Dickinson; bpo-7228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7228}.)

@item 
The complicated interaction between threads and process forking has
been changed.  Previously, the child process created by
@ref{a4b,,os.fork()} might fail because the child is created with only a
single thread running, the thread performing the @ref{a4b,,os.fork()}.
If other threads were holding a lock, such as Python's import lock,
when the fork was performed, the lock would still be marked as
"held" in the new process.  But in the child process nothing would
ever release the lock, since the other threads weren't replicated,
and the child process would no longer be able to perform imports.

Python 2.7 acquires the import lock before performing an
@ref{a4b,,os.fork()}, and will also clean up any locks created using the
@ref{10b,,threading} module.  C extension modules that have internal
locks, or that call @code{fork()} themselves, will not benefit
from this clean-up.

(Fixed by Thomas Wouters; bpo-1590864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1590864}.)

@item 
The @ref{dbb,,Py_Finalize()} function now calls the internal
@code{threading._shutdown()} function; this prevents some exceptions from
being raised when an interpreter shuts down.
(Patch by Adam Olsen; bpo-1722344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1722344}.)

@item 
When using the @ref{532,,PyMemberDef} structure to define attributes
of a type, Python will no longer let you try to delete or set a
@code{T_STRING_INPLACE} attribute.

@c rev 79644

@item 
Global symbols defined by the @ref{2a,,ctypes} module are now prefixed
with @code{Py}, or with @code{_ctypes}.  (Implemented by Thomas
Heller; bpo-3102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3102}.)

@item 
New configure option: the @code{--with-system-expat} switch allows
building the @code{pyexpat} module to use the system Expat library.
(Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7609}.)

@item 
New configure option: the
@code{--with-valgrind} option will now disable the pymalloc
allocator, which is difficult for the Valgrind memory-error detector
to analyze correctly.
Valgrind will therefore be better at detecting memory leaks and
overruns. (Contributed by James Henstridge; bpo-2422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2422}.)

@item 
New configure option: you can now supply an empty string to
@code{--with-dbmliborder=} in order to disable all of the various
DBM modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
bpo-6491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6491}.)

@item 
The @code{configure} script now checks for floating-point rounding bugs
on certain 32-bit Intel chips and defines a @code{X87_DOUBLE_ROUNDING}
preprocessor definition.  No code currently uses this definition,
but it's available if anyone wishes to use it.
(Added by Mark Dickinson; bpo-2937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2937}.)

@code{configure} also now sets a 
@geindex LDCXXSHARED
@geindex 环境变量; LDCXXSHARED
@code{LDCXXSHARED} Makefile
variable for supporting C++ linking.  (Contributed by Arfrever
Frehtes Taifersar Arahesis; bpo-1222585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1222585}.)

@item 
The build process now creates the necessary files for pkg-config
support.  (Contributed by Clinton Roy; bpo-3585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3585}.)

@item 
The build process now supports Subversion 1.7.  (Contributed by
Arfrever Frehtes Taifersar Arahesis; bpo-6094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6094}.)
@end itemize

@menu
* 胶囊:: 
* 特定于 Windows 的更改：:: 
* 特定于 Mac OS X 的更改：:: 
* 特定于 FreeBSD 的更改：:: 

@end menu

@node 胶囊,特定于 Windows 的更改：,,构建和 C API 的改变<8>
@anchor{whatsnew/2 7 capsules}@anchor{dbc}@anchor{whatsnew/2 7 whatsnew27-capsules}@anchor{dbd}
@subsubsection 胶囊


Python 3.1 adds a new C datatype, @ref{cda,,PyCapsule}, for providing a
C API to an extension module.  A capsule is essentially the holder of
a C @code{void *} pointer, and is made available as a module attribute; for
example, the @ref{ef,,socket} module's API is exposed as @code{socket.CAPI},
and @ref{123,,unicodedata} exposes @code{ucnhash_CAPI}.  Other extensions
can import the module, access its dictionary to get the capsule
object, and then get the @code{void *} pointer, which will usually point
to an array of pointers to the module's various API functions.

There is an existing data type already used for this,
@code{PyCObject}, but it doesn't provide type safety.  Evil code
written in pure Python could cause a segmentation fault by taking a
@code{PyCObject} from module A and somehow substituting it for the
@code{PyCObject} in module B.   Capsules know their own name,
and getting the pointer requires providing the name:

@example
void *vtable;

if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") @{
        PyErr_SetString(PyExc_ValueError, "argument type invalid");
        return NULL;
@}

vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
@end example

You are assured that @code{vtable} points to whatever you're expecting.
If a different capsule was passed in, @ref{dbe,,PyCapsule_IsValid()} would
detect the mismatched name and return false.  Refer to
@ref{dbf,,给扩展模块提供C API} for more information on using these objects.

Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the @code{PyCObject_AsVoidPtr()} was
modified to handle capsules, preserving compile-time compatibility
with the @code{CObject} interface.  Use of
@code{PyCObject_AsVoidPtr()} will signal a
@ref{15c,,PendingDeprecationWarning}, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in bpo-5630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5630}.

@c ======================================================================

@node 特定于 Windows 的更改：,特定于 Mac OS X 的更改：,胶囊,构建和 C API 的改变<8>
@anchor{whatsnew/2 7 port-specific-changes-windows}@anchor{dc0}
@subsubsection 特定于 Windows 的更改：



@itemize *

@item 
The @ref{b6,,msvcrt} module now contains some constants from
the @code{crtassem.h} header file:
@code{CRT_ASSEMBLY_VERSION},
@code{VC_ASSEMBLY_PUBLICKEYTOKEN},
and @code{LIBRARIES_ASSEMBLY_NAME_PREFIX}.
(Contributed by David Cournapeau; bpo-4365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4365}.)

@item 
The @code{_winreg} module for accessing the registry now implements
the @code{CreateKeyEx()} and @code{DeleteKeyEx()}
functions, extended versions of previously-supported functions that
take several extra arguments.  The @code{DisableReflectionKey()},
@code{EnableReflectionKey()}, and @code{QueryReflectionKey()}
were also tested and documented.
(Implemented by Brian Curtin: bpo-7347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7347}.)

@item 
The new @code{_beginthreadex()} API is used to start threads, and
the native thread-local storage functions are now used.
(Contributed by Kristján Valur Jónsson; bpo-3582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3582}.)

@item 
The @ref{dc1,,os.kill()} function now works on Windows.  The signal value
can be the constants @code{CTRL_C_EVENT},
@code{CTRL_BREAK_EVENT}, or any integer.  The first two constants
will send @code{Control-C} and @code{Control-Break} keystroke events to
subprocesses; any other value will use the @code{TerminateProcess()}
API.  (Contributed by Miki Tebeka; bpo-1220212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1220212}.)

@item 
The @ref{b25,,os.listdir()} function now correctly fails
for an empty path.  (Fixed by Hirokazu Yamamoto; bpo-5913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5913}.)

@item 
The @code{mimelib} module will now read the MIME database from
the Windows registry when initializing.
(Patch by Gabriel Genellina; bpo-4969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4969}.)
@end itemize

@c ======================================================================

@node 特定于 Mac OS X 的更改：,特定于 FreeBSD 的更改：,特定于 Windows 的更改：,构建和 C API 的改变<8>
@anchor{whatsnew/2 7 port-specific-changes-mac-os-x}@anchor{dc2}
@subsubsection 特定于 Mac OS X 的更改：



@itemize *

@item 
The path @code{/Library/Python/2.7/site-packages} is now appended to
@code{sys.path}, in order to share added packages between the system
installation and a user-installed copy of the same version.
(Changed by Ronald Oussoren; bpo-4865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4865}.)

@quotation


在 2.7.13 版更改: As of 2.7.13, this change was removed.
@code{/Library/Python/2.7/site-packages}, the site-packages directory
used by the Apple-supplied system Python 2.7 is no longer appended to
@code{sys.path} for user-installed Pythons such as from the python.org
installers.  As of macOS 10.12, Apple changed how the system
site-packages directory is configured, which could cause installation
of pip components, like setuptools, to fail.  Packages installed for
the system Python will no longer be shared with user-installed
Pythons. (bpo-28440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28440})

@end quotation
@end itemize

@node 特定于 FreeBSD 的更改：,,特定于 Mac OS X 的更改：,构建和 C API 的改变<8>
@anchor{whatsnew/2 7 port-specific-changes-freebsd}@anchor{dc3}
@subsubsection 特定于 FreeBSD 的更改：



@itemize *

@item 
FreeBSD 7.1's @code{SO_SETFIB} constant, used with
@code{getsockopt()}/@code{setsockopt()} to select an
alternate routing table, is now available in the @ref{ef,,socket}
module.  (Added by Kyle VanderBeek; bpo-8235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8235}.)
@end itemize

@node 其他的改变和修正,移植到 Python 2 7,构建和 C API 的改变<8>,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 other-changes-and-fixes}@anchor{dc4}
@subsection 其他的改变和修正



@itemize *

@item 
Two benchmark scripts, @code{iobench} and @code{ccbench}, were
added to the @code{Tools} directory.  @code{iobench} measures the
speed of the built-in file I/O objects returned by @ref{16f,,open()}
while performing various operations, and @code{ccbench} is a
concurrency benchmark that tries to measure computing throughput,
thread switching latency, and IO processing bandwidth when
performing several tasks using a varying number of threads.

@item 
The @code{Tools/i18n/msgfmt.py} script now understands plural
forms in @code{.po} files.  (Fixed by Martin von Löwis;
bpo-5464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5464}.)

@item 
When importing a module from a @code{.pyc} or @code{.pyo} file
with an existing @code{.py} counterpart, the @code{co_filename}
attributes of the resulting code objects are overwritten when the
original filename is obsolete.  This can happen if the file has been
renamed, moved, or is accessed through different paths.  (Patch by
Ziga Seilnacht and Jean-Paul Calderone; bpo-1180193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1180193}.)

@item 
The @code{regrtest.py} script now takes a @code{--randseed=}
switch that takes an integer that will be used as the random seed
for the @code{-r} option that executes tests in random order.
The @code{-r} option also reports the seed that was used
(Added by Collin Winter.)

@item 
Another @code{regrtest.py} switch is @code{-j}, which
takes an integer specifying how many tests run in parallel. This
allows reducing the total runtime on multi-core machines.
This option is compatible with several other options, including the
@code{-R} switch which is known to produce long runtimes.
(Added by Antoine Pitrou, bpo-6152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6152}.)  This can also be used
with a new @code{-F} switch that runs selected tests in a loop
until they fail.  (Added by Antoine Pitrou; bpo-7312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7312}.)

@item 
When executed as a script, the @code{py_compile.py} module now
accepts @code{'-'} as an argument, which will read standard input for
the list of filenames to be compiled.  (Contributed by Piotr
Ożarowski; bpo-8233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8233}.)
@end itemize

@c ======================================================================

@node 移植到 Python 2 7,New Features Added to Python 2 7 Maintenance Releases,其他的改变和修正,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 porting-to-python-2-7}@anchor{dc5}
@subsection 移植到 Python 2.7


This section lists previously described changes and other bugfixes
that may require changes to your code:


@itemize *

@item 
The @ref{1f6,,range()} function processes its arguments more
consistently; it will now call @ref{2ca,,__int__()} on non-float,
non-integer arguments that are supplied to it.  (Fixed by Alexander
Belopolsky; bpo-1533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1533}.)

@item 
The string @ref{5de,,format()} method changed the default precision used
for floating-point and complex numbers from 6 decimal
places to 12, which matches the precision used by @ref{206,,str()}.
(Changed by Eric Smith; bpo-5920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5920}.)

@item 
Because of an optimization for the @ref{7e4,,with} statement, the special
methods @ref{d65,,__enter__()} and @ref{d66,,__exit__()} must belong to the object's
type, and cannot be directly attached to the object's instance.  This
affects new-style classes (derived from @ref{3da,,object}) and C extension
types.  (bpo-6101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6101}.)

@item 
Due to a bug in Python 2.6, the @emph{exc_value} parameter to
@ref{d66,,__exit__()} methods was often the string representation of the
exception, not an instance.  This was fixed in 2.7, so @emph{exc_value}
will be an instance as expected.  (Fixed by Florent Xicluna;
bpo-7853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7853}.)

@item 
When a restricted set of attributes were set using @code{__slots__},
deleting an unset attribute would not raise @ref{4aa,,AttributeError}
as you would expect.  Fixed by Benjamin Peterson; bpo-7604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7604}.)
@end itemize

In the standard library:


@itemize *

@item 
Operations with @ref{19f,,datetime} instances that resulted in a year
falling outside the supported range didn't always raise
@ref{a4a,,OverflowError}.  Such errors are now checked more carefully
and will now raise the exception. (Reported by Mark Leander, patch
by Anand B. Pillai and Alexander Belopolsky; bpo-7150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7150}.)

@item 
When using @ref{2c7,,Decimal} instances with a string's
@ref{5de,,format()} method, the default alignment was previously
left-alignment.  This has been changed to right-alignment, which might
change the output of your programs.
(Changed by Mark Dickinson; bpo-6857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6857}.)

Comparisons involving a signaling NaN value (or @code{sNAN}) now signal
@ref{ad3,,InvalidOperation} instead of silently returning a true or
false value depending on the comparison operator.  Quiet NaN values
(or @code{NaN}) are now hashable.  (Fixed by Mark Dickinson;
bpo-7279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7279}.)

@item 
The ElementTree library, @code{xml.etree}, no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like @cite{<?xml-stylesheet href="#style1"?>})
or comment (which looks like @cite{<!-- comment -->}).
(Patch by Neil Muller; bpo-2746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2746}.)

@item 
The @code{readline()} method of @code{StringIO} objects now does
nothing when a negative length is requested, as other file-like
objects do.  (bpo-7348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7348}).

@item 
The @ref{ff,,syslog} module will now use the value of @code{sys.argv[0]} as the
identifier instead of the previous default value of @code{'python'}.
(Changed by Sean Reifschneider; bpo-8451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8451}.)

@item 
The @ref{101,,tarfile} module's default error handling has changed, to
no longer suppress fatal errors.  The default error level was previously 0,
which meant that errors would only result in a message being written to the
debug log, but because the debug log is not activated by default,
these errors go unnoticed.  The default error level is now 1,
which raises an exception if there's an error.
(Changed by Lars Gustäbel; bpo-7357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7357}.)

@item 
The @code{urlparse} module's @code{urlsplit()} now handles
unknown URL schemes in a fashion compliant with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html}: if the
URL is of the form @code{"<something>://..."}, the text before the
@code{://} is treated as the scheme, even if it's a made-up scheme that
the module doesn't know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '@w{'}, '//host/filename?query', '@w{'}, '@w{'})
@end example

Python 2.7 (and Python 2.6.5) will return:

@example
>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '@w{'}, '@w{'})
@end example

(Python 2.7 actually produces slightly different output, since it
returns a named tuple instead of a standard tuple.)
@end itemize

对于C 扩展模块：


@itemize *

@item 
C extensions that use integer format codes with the @code{PyArg_Parse*}
family of functions will now raise a @ref{1ff,,TypeError} exception
instead of triggering a @ref{15a,,DeprecationWarning} (bpo-5080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5080}).

@item 
Use the new @ref{cf5,,PyOS_string_to_double()} function instead of the old
@code{PyOS_ascii_strtod()} and @code{PyOS_ascii_atof()} functions,
which are now deprecated.
@end itemize

对于嵌入Python的应用程序：


@itemize *

@item 
The @ref{ccd,,PySys_SetArgvEx()} function was added, letting
applications close a security hole when the existing
@ref{dba,,PySys_SetArgv()} function was used.  Check whether you're
calling @ref{dba,,PySys_SetArgv()} and carefully consider whether the
application should be using @ref{ccd,,PySys_SetArgvEx()} with
@emph{updatepath} set to false.
@end itemize

@c ======================================================================

@node New Features Added to Python 2 7 Maintenance Releases,致谢,移植到 Python 2 7,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 new-features-added-to-python-2-7-maintenance-releases}@anchor{dc6}@anchor{whatsnew/2 7 py27-maintenance-enhancements}@anchor{d4c}
@subsection New Features Added to Python 2.7 Maintenance Releases


New features may be added to Python 2.7 maintenance releases when the
situation genuinely calls for it. Any such additions must go through
the Python Enhancement Proposal process, and make a compelling case for why
they can't be adequately addressed by either adding the new feature solely to
Python 3, or else by publishing it on the Python Package Index.

In addition to the specific proposals listed below, there is a general
exemption allowing new @code{-3} warnings to be added in any Python 2.7
maintenance release.

@menu
* Two new environment variables for debug mode:: 
* PEP 434; IDLE Enhancement Exception for All Branches: PEP 434 IDLE Enhancement Exception for All Branches. 
* PEP 466; Network Security Enhancements for Python 2.7: PEP 466 Network Security Enhancements for Python 2 7. 
* PEP 477; Backport ensurepip (PEP 453) to Python 2.7: PEP 477 Backport ensurepip PEP 453 to Python 2 7. 
* PEP 476; Enabling certificate verification by default for stdlib http clients: PEP 476 Enabling certificate verification by default for stdlib http clients<2>. 
* PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具. 
* New make regen-all build target: New make regen-all build target<3>. 
* Removal of make touch build target: Removal of make touch build target<3>. 

@end menu

@node Two new environment variables for debug mode,PEP 434 IDLE Enhancement Exception for All Branches,,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 two-new-environment-variables-for-debug-mode}@anchor{dc7}
@subsubsection Two new environment variables for debug mode


In debug mode, the @code{[xxx refs]} statistic is not written by default, the
@geindex PYTHONSHOWREFCOUNT
@geindex 环境变量; PYTHONSHOWREFCOUNT
@code{PYTHONSHOWREFCOUNT} environment variable now must also be set.
(Contributed by Victor Stinner; bpo-31733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31733}.)

When Python is compiled with @code{COUNT_ALLOC} defined, allocation counts are no
longer dumped by default anymore: the 
@geindex PYTHONSHOWALLOCCOUNT
@geindex 环境变量; PYTHONSHOWALLOCCOUNT
@code{PYTHONSHOWALLOCCOUNT} environment
variable must now also be set. Moreover, allocation counts are now dumped into
stderr, rather than stdout. (Contributed by Victor Stinner; bpo-31692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31692}.)


2.7.15 新版功能.


@node PEP 434 IDLE Enhancement Exception for All Branches,PEP 466 Network Security Enhancements for Python 2 7,Two new environment variables for debug mode,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 pep-434-idle-enhancement-exception-for-all-branches}@anchor{dc8}
@subsubsection PEP 434: IDLE Enhancement Exception for All Branches


@geindex Python 提高建议; PEP 434
PEP 434@footnote{https://www.python.org/dev/peps/pep-0434} describes a general exemption for changes made to the IDLE
development environment shipped along with Python. This exemption makes it
possible for the IDLE developers to provide a more consistent user
experience across all supported versions of Python 2 and 3.

For details of any IDLE changes, refer to the NEWS file for the specific
release.

@node PEP 466 Network Security Enhancements for Python 2 7,PEP 477 Backport ensurepip PEP 453 to Python 2 7,PEP 434 IDLE Enhancement Exception for All Branches,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 pep-466-network-security-enhancements-for-python-2-7}@anchor{dc9}
@subsubsection PEP 466: Network Security Enhancements for Python 2.7


@geindex Python 提高建议; PEP 466
PEP 466@footnote{https://www.python.org/dev/peps/pep-0466} describes a number of network security enhancement proposals
that have been approved for inclusion in Python 2.7 maintenance releases,
with the first of those changes appearing in the Python 2.7.7 release.

@geindex Python 提高建议; PEP 466
PEP 466@footnote{https://www.python.org/dev/peps/pep-0466} Python 2.7.7 中添加的相关功能：


@itemize *

@item 
@ref{af3,,hmac.compare_digest()} was backported from Python 3 to make a timing
attack resistant comparison operation available to Python 2 applications.
(Contributed by Alex Gaynor; bpo-21306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21306}.)

@item 
OpenSSL 1.0.1g was upgraded in the official Windows installers published on
python.org. (Contributed by Zachary Ware; bpo-21462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21462}.)
@end itemize

@geindex Python 提高建议; PEP 466
PEP 466@footnote{https://www.python.org/dev/peps/pep-0466} Python 2.7.8 中添加的相关功能：


@itemize *

@item 
@ref{8dd,,hashlib.pbkdf2_hmac()} was backported from Python 3 to make a hashing
algorithm suitable for secure password storage broadly available to Python
2 applications. (Contributed by Alex Gaynor; bpo-21304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21304}.)

@item 
OpenSSL 1.0.1h was upgraded for the official Windows installers published on
python.org. (contributed by Zachary Ware in bpo-21671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21671} for CVE-2014-0224)
@end itemize

@geindex Python 提高建议; PEP 466
PEP 466@footnote{https://www.python.org/dev/peps/pep-0466} Python 2.7.9 中添加的相关功能：


@itemize *

@item 
Most of Python 3.4's @ref{f3,,ssl} module was backported. This means @ref{f3,,ssl}
now supports Server Name Indication, TLS1.x settings, access to the platform
certificate store, the @ref{4f2,,SSLContext} class, and other
features. (Contributed by Alex Gaynor and David Reid; bpo-21308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21308}.)

Refer to the "Version added: 2.7.9" notes in the module documentation for
specific details.

@item 
@ref{5d4,,os.urandom()} was changed to cache a file descriptor to @code{/dev/urandom}
instead of reopening @code{/dev/urandom} on every call. (Contributed by Alex
Gaynor; bpo-21305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21305}.)

@item 
@ref{dca,,hashlib.algorithms_guaranteed} and
@ref{dcb,,hashlib.algorithms_available} were backported from Python 3 to make
it easier for Python 2 applications to select the strongest available hash
algorithm. (Contributed by Alex Gaynor in bpo-21307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21307})
@end itemize

@node PEP 477 Backport ensurepip PEP 453 to Python 2 7,PEP 476 Enabling certificate verification by default for stdlib http clients<2>,PEP 466 Network Security Enhancements for Python 2 7,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 pep-477-backport-ensurepip-pep-453-to-python-2-7}@anchor{dcc}
@subsubsection PEP 477: Backport ensurepip (PEP 453) to Python 2.7


@geindex Python 提高建议; PEP 477
PEP 477@footnote{https://www.python.org/dev/peps/pep-0477} approves the inclusion of the 
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} ensurepip module and the
improved documentation that was enabled by it in the Python 2.7 maintenance
releases, appearing first in the Python 2.7.9 release.

@menu
* Bootstrapping pip By Default: Bootstrapping pip By Default<2>. 
* 文档更改: 文档更改<2>. 

@end menu

@node Bootstrapping pip By Default<2>,文档更改<2>,,PEP 477 Backport ensurepip PEP 453 to Python 2 7
@anchor{whatsnew/2 7 bootstrapping-pip-by-default}@anchor{dcd}
@subsubsection Bootstrapping pip By Default


The new @ref{78,,ensurepip} module (defined in 
@geindex Python 提高建议; PEP 453
PEP 453@footnote{https://www.python.org/dev/peps/pep-0453}) provides a standard
cross-platform mechanism to bootstrap the pip installer into Python
installations. The version of @code{pip} included with Python 2.7.9 is @code{pip}
1.5.6, and future 2.7.x maintenance releases will update the bundled version to
the latest version of @code{pip} that is available at the time of creating the
release candidate.

By default, the commands @code{pip}, @code{pipX} and @code{pipX.Y} will be installed on
all platforms (where X.Y stands for the version of the Python installation),
along with the @code{pip} Python package and its dependencies.

For CPython @ref{8ea,,source builds on POSIX systems},
the @code{make install} and @code{make altinstall} commands do not bootstrap @code{pip}
by default.  This behaviour can be controlled through configure options, and
overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing
@code{pip} along with CPython itself (users may opt out of installing it
during the installation process). Window users will need to opt in to the
automatic @code{PATH} modifications to have @code{pip} available from the command
line by default, otherwise it can still be accessed through the Python
launcher for Windows as @code{py -m pip}.

As discussed in the PEP@footnote{https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors}, platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).

@node 文档更改<2>,,Bootstrapping pip By Default<2>,PEP 477 Backport ensurepip PEP 453 to Python 2 7
@anchor{whatsnew/2 7 documentation-changes}@anchor{dce}@anchor{whatsnew/2 7 id1}@anchor{dcf}
@subsubsection 文档更改


As part of this change, the @ref{8ec,,安装 Python 模块} and
@ref{8ed,,分发 Python 模块} sections of the documentation have been
completely redesigned as short getting started and FAQ documents. Most
packaging documentation has now been moved out to the Python Packaging
Authority maintained Python Packaging User Guide@footnote{http://packaging.python.org} and the documentation of the individual
projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as @ref{8ee,,安装Python模块（旧版）}
and @ref{8ef,,分发 Python 模块（遗留版本）}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 453

@item PEP 453@footnote{https://www.python.org/dev/peps/pep-0453} -- Python安装中pip的显式引导

PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick Coghlan，Martin von Löwis 和 Ned Deily 实现。
@end table


@node PEP 476 Enabling certificate verification by default for stdlib http clients<2>,PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,PEP 477 Backport ensurepip PEP 453 to Python 2 7,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients}@anchor{dd0}
@subsubsection PEP 476: Enabling certificate verification by default for stdlib http clients


@geindex Python 提高建议; PEP 476
PEP 476@footnote{https://www.python.org/dev/peps/pep-0476} updated @code{httplib} and modules which use it, such as
@code{urllib2} and @code{xmlrpclib}, to now verify that the server
presents a certificate which is signed by a Certificate Authority in the
platform trust store and whose hostname matches the hostname being requested
by default, significantly improving security for many applications. This
change was made in the Python 2.7.9 release.

For applications which require the old previous behavior, they can pass an
alternate context:

@example
import urllib2
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib2.urlopen("https://invalid-cert", context=context)
@end example

@node PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,New make regen-all build target<3>,PEP 476 Enabling certificate verification by default for stdlib http clients<2>,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 pep-493-https-verification-migration-tools-for-python-2-7}@anchor{dd1}
@subsubsection PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具


@geindex Python 提高建议; PEP 493
PEP 493@footnote{https://www.python.org/dev/peps/pep-0493} provides additional migration tools to support a more incremental
infrastructure upgrade process for environments containing applications and
services relying on the historically permissive processing of server
certificates when establishing client HTTPS connections.  These additions were
made in the Python 2.7.12 release.

These tools are intended for use in cases where affected applications and
services can't be modified to explicitly pass a more permissive SSL context
when establishing the connection.

For applications and services which can't be modified at all, the new
@code{PYTHONHTTPSVERIFY} environment variable may be set to @code{0} to revert an
entire Python process back to the default permissive behaviour of Python 2.7.8
and earlier.

For cases where the connection establishment code can't be modified, but the
overall application can be, the new @code{ssl._https_verify_certificates()}
function can be used to adjust the default behaviour at runtime.

@node New make regen-all build target<3>,Removal of make touch build target<3>,PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 new-make-regen-all-build-target}@anchor{dd2}
@subsubsection New @code{make regen-all} build target


To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new @code{make regen-all} command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
Makefile.pre.in@footnote{https://github.com/python/cpython/tree/3.9/Makefile.pre.in} for details.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


2.7.14 新版功能.


@node Removal of make touch build target<3>,,New make regen-all build target<3>,New Features Added to Python 2 7 Maintenance Releases
@anchor{whatsnew/2 7 removal-of-make-touch-build-target}@anchor{dd3}
@subsubsection Removal of @code{make touch} build target


The @code{make touch} build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new @code{make regen-all} target.

（由 Victor Stinner 在 bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404} 中贡献。）


在 2.7.14 版更改.


@c ======================================================================

@node 致谢,,New Features Added to Python 2 7 Maintenance Releases,Python 2 7 有什么新变化
@anchor{whatsnew/2 7 acknowledgements}@anchor{dd4}@anchor{whatsnew/2 7 acks27}@anchor{dd5}
@subsection 致谢


作者要感谢以下人员为本文的各种草案提供建议，更正和帮助： Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray, Hugh Secker-Walker.

@node Python 2 6 有什么新变化,Python 2 5 有什么新变化,Python 2 7 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 6 doc}@anchor{dd6}@anchor{whatsnew/2 6 what-s-new-in-python-2-6}@anchor{dd7}@anchor{whatsnew/2 6 whats-new-in-2-6}@anchor{d17}
@section Python 2.6 有什么新变化


@c XXX add trademark info for Apple, Microsoft, SourceForge.

@*作者: 
A.M. Kuchling (amk at amk.ca)


@c $Id$
@c Rules for maintenance:
@c 
@c * Anyone can add text to this document.  Do not spend very much time
@c on the wording of your changes, because your text will probably
@c get rewritten to some degree.
@c 
@c * The maintainer will go through Misc/NEWS periodically and add
@c changes; it's therefore more important to add your changes to
@c Misc/NEWS than to this file.
@c 
@c * This is not a complete list of every single change; completeness
@c is the purpose of Misc/NEWS.  Some changes I consider too small
@c or esoteric to include.  If such a change is added to the text,
@c I'll just remove it.  (This is another reason you shouldn't spend
@c too much time on writing your addition.)
@c 
@c * If you want to draw your new text to the attention of the
@c maintainer, add 'XXX' to the beginning of the paragraph or
@c section.
@c 
@c * It's OK to just add a fragmentary note about a change.  For
@c example: "XXX Describe the transmogrify() function added to the
@c socket module."  The maintainer will research the change and
@c write the necessary text.
@c 
@c * You can comment out your additions if you like, but it's not
@c necessary (especially when a final release is some months away).
@c 
@c * Credit the author of a patch or bugfix.   Just the name is
@c sufficient; the e-mail address isn't necessary.
@c 
@c * It's helpful to add the bug/patch number in a parenthetical comment.
@c 
@c XXX Describe the transmogrify() function added to the socket
@c module.
@c (Contributed by P.Y. Developer; :issue:`12345`.)
@c 
@c This saves the maintainer some effort going through the SVN logs
@c when researching a change.

本文介绍了 Python 2.6 的新特性，它发布于 2008 年 10 月 1 日。 发布日程说明见 
@geindex Python 提高建议; PEP 361
PEP 361@footnote{https://www.python.org/dev/peps/pep-0361}。

The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it's not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
@code{future_builtins} module and a @code{-3} switch to warn about
usages that will become unsupported in 3.0.

Some significant new packages have been added to the standard library,
such as the @ref{b7,,multiprocessing} and @ref{a4,,json} modules, but
there aren't many new features that aren't related to Python 3.0 in
some way.

Python 2.6 also sees a number of improvements and bugfixes throughout
the source.  A search through the change logs finds there were 259
patches applied and 612 bugs fixed between Python 2.5 and 2.6.  Both
figures are likely to be underestimates.

This article doesn't attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.6. If
you want to understand the rationale for the design and
implementation, refer to the PEP for a particular new feature.
Whenever possible, "What's New in Python" links to the bug/patch item
for each change.

@c Compare with previous release in 2 - 3 sentences here.
@c add hyperlink when the documentation becomes available online.

@c ========================================================================

@c Large, PEP-level features and changes should be described here.

@c ========================================================================

@menu
* Python 3.0: Python 3 0. 
* 开发过程的变化:: 
* PEP 343; "with" 语句: PEP 343 "with" 语句. 
* PEP 366; 从主模块显式相对导入: PEP 366 从主模块显式相对导入. 
* PEP 370; 分用户的 site-packages 目录: PEP 370 分用户的 site-packages 目录. 
* PEP 371; 多任务处理包: PEP 371 多任务处理包. 
* PEP 3101; 高级字符串格式: PEP 3101 高级字符串格式. 
* PEP 3105; print 改为函数: PEP 3105 print 改为函数. 
* PEP 3110; 异常处理的变更: PEP 3110 异常处理的变更. 
* PEP 3112; 字节字面值: PEP 3112 字节字面值. 
* PEP 3116; 新 I/O 库: PEP 3116 新 I/O 库. 
* PEP 3118; 修改缓冲区协议: PEP 3118 修改缓冲区协议. 
* PEP 3119; 抽象基类: PEP 3119 抽象基类. 
* PEP 3127; 整型文字支持和语法: PEP 3127 整型文字支持和语法. 
* PEP 3129; 类装饰器: PEP 3129 类装饰器. 
* PEP 3141; A Type Hierarchy for Numbers: PEP 3141 A Type Hierarchy for Numbers. 
* 其他语言特性修改: 其他语言特性修改<11>. 
* 新增和改进的模块: 新增和改进的模块<2>. 
* Deprecations and Removals:: 
* 构建和 C API 的改变: 构建和 C API 的改变<9>. 
* 移植到Python 2.6: 移植到Python 2 6. 
* 致谢: 致谢<2>. 

@end menu

@node Python 3 0,开发过程的变化,,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 python-3-0}@anchor{dd8}
@subsection Python 3.0


The development cycle for Python versions 2.6 and 3.0 was
synchronized, with the alpha and beta releases for both versions being
made on the same days.  The development of 3.0 has influenced many
features in 2.6.

Python 3.0 is a far-ranging redesign of Python that breaks
compatibility with the 2.x series.  This means that existing Python
code will need some conversion in order to run on
Python 3.0.  However, not all the changes in 3.0 necessarily break
compatibility.  In cases where new features won't cause existing code
to break, they've been backported to 2.6 and are described in this
document in the appropriate place.  Some of the 3.0-derived features
are:


@itemize *

@item 
用于将对象转换为复数的 @ref{2cc,,__complex__()} 方法。

@item 
用于捕获异常的替代语法: @code{except TypeError as exc}。

@item 
增加 @ref{d3f,,functools.reduce()} 作为内置 @code{reduce()} 函数的同义词。
@end itemize

Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as @ref{d10,,bin()} have simply been added to Python 2.6, but existing
builtins haven't been changed; instead, the @code{future_builtins}
module has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do @code{from future_builtins import hex, map} as
necessary.

A new command-line switch, @code{-3}, enables warnings
about features that will be removed in Python 3.0.  You can run code
with this switch to see how much work will be necessary to port
code to 3.0.  The value of this switch is available
to Python code as the boolean variable @code{sys.py3kwarning},
and to C extension code as @code{Py_Py3kWarningFlag}.


@subsubheading 参见


The 3xxx series of PEPs, which contains proposals for Python 3.0.
@geindex Python 提高建议; PEP 3000
PEP 3000@footnote{https://www.python.org/dev/peps/pep-3000} describes the development process for Python 3.0.
Start with 
@geindex Python 提高建议; PEP 3100
PEP 3100@footnote{https://www.python.org/dev/peps/pep-3100} that describes the general goals for Python
3.0, and then explore the higher-numbered PEPS that propose
specific features.


@node 开发过程的变化,PEP 343 "with" 语句,Python 3 0,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 changes-to-the-development-process}@anchor{dd9}
@subsection 开发过程的变化


While 2.6 was being developed, the Python development process
underwent two significant changes: we switched from SourceForge's
issue tracker to a customized Roundup installation, and the
documentation was converted from LaTeX to reStructuredText.

@menu
* 新问题追踪：简述:: 
* 新的文档格式：使用 Sphinx 的 reStructuredText:: 

@end menu

@node 新问题追踪：简述,新的文档格式：使用 Sphinx 的 reStructuredText,,开发过程的变化
@anchor{whatsnew/2 6 new-issue-tracker-roundup}@anchor{dda}
@subsubsection 新问题追踪：简述


For a long time, the Python developers had been growing increasingly
annoyed by SourceForge's bug tracker.  SourceForge's hosted solution
doesn't permit much customization; for example, it wasn't possible to
customize the life cycle of issues.

The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: Jira@footnote{https://www.atlassian.com/software/jira/},
Launchpad@footnote{https://launchpad.net/},
Roundup@footnote{http://roundup.sourceforge.net/}, and
Trac@footnote{https://trac.edgewall.org/}.
The committee eventually settled on Jira
and Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.

After posting a call for volunteers, a new Roundup installation was
set up at @indicateurl{https://bugs.python.org}.  One installation of Roundup can
host multiple trackers, and this server now also hosts issue trackers
for Jython and for the Python web site.  It will surely find
other uses in the future.  Where possible,
this edition of "What's New in Python" links to the bug/patch
item for each change.

Hosting of the Python bug tracker is kindly provided by
Upfront Systems@footnote{http://www.upfrontsoftware.co.za}
of Stellenbosch, South Africa.  Martin von Löwis put a
lot of effort into importing existing bugs and patches from
SourceForge; his scripts for this import operation are at
@indicateurl{http://svn.python.org/view/tracker/importer/} and may be useful to
other projects wishing to move from SourceForge to Roundup.


@subsubheading 参见



@table @asis

@item @indicateurl{https://bugs.python.org}

Python 的错误追踪器

@item @indicateurl{http://bugs.jython.org}:

Jython 的错误追踪器

@item @indicateurl{http://roundup.sourceforge.net/}

Roundup 下载和文档。

@item @indicateurl{http://svn.python.org/view/tracker/importer/}

Martin von Löwis 的转换脚本。
@end table


@node 新的文档格式：使用 Sphinx 的 reStructuredText,,新问题追踪：简述,开发过程的变化
@anchor{whatsnew/2 6 new-documentation-format-restructuredtext-using-sphinx}@anchor{ddb}
@subsubsection 新的文档格式：使用 Sphinx 的 reStructuredText


The Python documentation was written using LaTeX since the project
started around 1989.  In the 1980s and early 1990s, most documentation
was printed out for later study, not viewed online. LaTeX was widely
used because it provided attractive printed output while remaining
straightforward to write once the basic rules of the markup were
learned.

Today LaTeX is still used for writing publications destined for
printing, but the landscape for programming tools has shifted.  We no
longer print out reams of documentation; instead, we browse through it
online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
L. Drake Jr., the long-time Python documentation editor, spent a lot
of time maintaining the conversion process.  Occasionally people would
suggest converting the documentation into SGML and later XML, but
performing a good conversion is a major task and no one ever committed
the time required to finish the job.

During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
@indicateurl{http://sphinx-doc.org/}.

Sphinx concentrates on HTML output, producing attractively styled and
modern HTML; printed output is still supported through conversion to
LaTeX.  The input format is reStructuredText, a markup syntax
supporting custom extensions and directives that is commonly used in
the Python community.

Sphinx is a standalone package that can be used for writing, and
almost two dozen other projects
(listed on the Sphinx web site@footnote{https://www.sphinx-doc.org/en/master/examples.html})
have adopted Sphinx as their documentation tool.


@subsubheading 参见



@table @asis

@item Documenting Python@footnote{https://devguide.python.org/documenting/}

描述如何编写Python文档。

@item Sphinx@footnote{http://sphinx-doc.org/}

Sphinx工具链的文档和代码。

@item Docutils@footnote{http://docutils.sourceforge.net}

reStructuredText 的基础解析器和工具集。
@end table


@node PEP 343 "with" 语句,PEP 366 从主模块显式相对导入,开发过程的变化,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-0343}@anchor{d18}@anchor{whatsnew/2 6 pep-343-the-with-statement}@anchor{ddc}
@subsection PEP 343: "with" 语句


The previous version, Python 2.5, added the '@ref{7e4,,with}'
statement as an optional feature, to be enabled by a @code{from __future__
import with_statement} directive.  In 2.6 the statement no longer needs to
be specially enabled; this means that @code{with} is now always a
keyword.  The rest of this section is a copy of the corresponding
section from the "What's New in Python 2.5" document; if you're
familiar with the '@code{with}' statement
from Python 2.5, you can skip this section.

The '@ref{7e4,,with}' statement clarifies code that previously would use
@code{try...finally} blocks to ensure that clean-up code is executed.  In this
section, I'll discuss the statement as it will commonly be used.  In the next
section, I'll examine the implementation details and show how to write objects
for use with this statement.

The '@ref{7e4,,with}' 语是一种基本结构如下所示的流程控制结构:

@example
with expression [as variable]:
    with-block
@end example

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has @ref{d65,,__enter__()} and @ref{d66,,__exit__()}
methods).

The object's @ref{d65,,__enter__()} is called before @emph{with-block} is executed and
therefore can run set-up code. It also may return a value that is bound to the
name @emph{variable}, if given.  (Note carefully that @emph{variable} is @emph{not} assigned
the result of @emph{expression}.)

After execution of the @emph{with-block} is finished, the object's @ref{d66,,__exit__()}
method is called, even if the block raised an exception, and can therefore run
clean-up code.

Some standard Python objects now support the context management protocol and can
be used with the '@ref{7e4,,with}' statement. File objects are one example:

@example
with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...
@end example

After this statement has executed, the file object in @emph{f} will have been
automatically closed, even if the @ref{d02,,for} loop raised an exception
part-way through the block.

@cartouche
@quotation 注解 
In this case, @emph{f} is the same object created by @ref{16f,,open()}, because
@code{file.__enter__()} returns @emph{self}.
@end quotation
@end cartouche

The @ref{10b,,threading} module's locks and condition variables  also support the
'@ref{7e4,,with}' statement:

@example
lock = threading.Lock()
with lock:
    # Critical section of code
    ...
@end example

The lock is acquired before the block is executed and always released once  the
block is complete.

The @code{localcontext()} function in the @ref{35,,decimal} module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:

@example
from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()
@end example

@menu
* 编写上下文管理器:: 
* contextlib 模块:: 

@end menu

@node 编写上下文管理器,contextlib 模块,,PEP 343 "with" 语句
@anchor{whatsnew/2 6 new-26-context-managers}@anchor{d19}@anchor{whatsnew/2 6 writing-context-managers}@anchor{ddd}
@subsubsection 编写上下文管理器


Under the hood, the '@ref{7e4,,with}' statement is fairly complicated. Most
people will only use '@code{with}' in company with existing objects and
don't need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.

在更高层级上对于上下文管理器协议的解释:


@itemize *

@item 
The expression is evaluated and should result in an object called a "context
manager".  The context manager must have @ref{d65,,__enter__()} and @ref{d66,,__exit__()}
methods.

@item 
The context manager's @ref{d65,,__enter__()} method is called.  The value returned
is assigned to @emph{VAR}.  If no @code{as VAR} clause is present, the value is simply
discarded.

@item 
@emph{BLOCK} 中的代码会被执行。

@item 
If @emph{BLOCK} raises an exception, the context manager's @ref{d66,,__exit__()} method
is called with three arguments, the exception details (@code{type, value, traceback},
the same values returned by @ref{d2f,,sys.exc_info()}, which can also be @code{None}
if no exception occurred).  The method's return value controls whether an exception
is re-raised: any false value re-raises the exception, and @code{True} will result
in suppressing it.  You'll only rarely want to suppress the exception, because
if you do the author of the code containing the '@ref{7e4,,with}' statement will
never realize anything went wrong.

@item 
If @emph{BLOCK} didn't raise an exception,  the @ref{d66,,__exit__()} method is still
called, but @emph{type}, @emph{value}, and @emph{traceback} are all @code{None}.
@end itemize

Let's think through an example.  I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)

Let's assume there's an object representing a database connection. Our goal will
be to let the user write code like this:

@example
db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
@end example

The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
@code{DatabaseConnection} that I'll assume:

@example
class DatabaseConnection:
    # Database interface
    def cursor(self):
        "Returns a cursor object and starts a new transaction"
    def commit(self):
        "Commits current transaction"
    def rollback(self):
        "Rolls back current transaction"
@end example

The @ref{d65,,__enter__()} method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add @code{as cursor} to
their '@ref{7e4,,with}' statement to bind the cursor to a variable name.

@example
class DatabaseConnection:
    ...
    def __enter__(self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor
@end example

The @ref{d66,,__exit__()} method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of @code{None}.  @code{None} is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a @ref{2cf,,return} statement at the marked location.

@example
class DatabaseConnection:
    ...
    def __exit__(self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False
@end example

@node contextlib 模块,,编写上下文管理器,PEP 343 "with" 语句
@anchor{whatsnew/2 6 new-module-contextlib}@anchor{d1a}@anchor{whatsnew/2 6 the-contextlib-module}@anchor{dde}
@subsubsection contextlib 模块


The @ref{23,,contextlib} module provides some functions and a decorator that
are useful when writing objects for use with the '@ref{7e4,,with}' statement.

The decorator is called @code{contextmanager()}, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the @ref{2ce,,yield} will be executed as the
@ref{d65,,__enter__()} method, and the value yielded will be the method's return
value that will get bound to the variable in the '@ref{7e4,,with}' statement's
@code{as} clause, if any.  The code after the @code{yield} will be
executed in the @ref{d66,,__exit__()} method.  Any exception raised in the block will
be raised by the @code{yield} statement.

Using this decorator, our database example from the previous section
could be written as:

@example
from contextlib import contextmanager

@@contextmanager
def db_transaction(connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...
@end example

The @ref{23,,contextlib} module also has a @code{nested(mgr1, mgr2, ...)} function
that combines a number of context managers so you don't need to write nested
'@ref{7e4,,with}' statements.  In this example, the single '@code{with}'
statement both starts a database transaction and acquires a thread lock:

@example
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...
@end example

Finally, the @code{closing()} function returns its argument so that it can be
bound to a variable, and calls the argument's @code{.close()} method at the end
of the block.

@example
import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 343

@item PEP 343@footnote{https://www.python.org/dev/peps/pep-0343} - "with" 语句

PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
'@ref{7e4,,with}' statement, which can be helpful in learning how the statement
works.
@end table

@ref{23,,contextlib} 模块的文档。


@c ======================================================================

@node PEP 366 从主模块显式相对导入,PEP 370 分用户的 site-packages 目录,PEP 343 "with" 语句,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-0366}@anchor{d1b}@anchor{whatsnew/2 6 pep-366-explicit-relative-imports-from-a-main-module}@anchor{ddf}
@subsection PEP 366: 从主模块显式相对导入


Python's @ref{44c,,-m} switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn't work correctly.

The fix for Python 2.6 adds a @ref{a3f,,__package__} attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the
@ref{de0,,__name__} attribute.

PEP 302-style importers can then set @ref{a3f,,__package__} as necessary.
The @ref{e2,,runpy} module that implements the @ref{44c,,-m} switch now
does this, so relative imports will now work correctly in scripts
running from inside a package.

@c ======================================================================

@node PEP 370 分用户的 site-packages 目录,PEP 371 多任务处理包,PEP 366 从主模块显式相对导入,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-0370}@anchor{d1c}@anchor{whatsnew/2 6 pep-370-per-user-site-packages-directory}@anchor{de1}
@subsection PEP 370: 分用户的 site-packages 目录


When you run Python, the module search path @code{sys.path} usually
includes a directory whose path ends in @code{"site-packages"}.  This
directory is intended to hold locally-installed packages available to
all users using a machine or a particular site installation.

Python 2.6 引入了一个用于用户专属站点目录的惯例。 该目录根据具体系统平台各不相同:


@itemize *

@item 
Unix 和 Mac OS X: @code{~/.local/}

@item 
Windows: @code{%APPDATA%/Python}
@end itemize

Within this directory, there will be version-specific subdirectories,
such as @code{lib/python2.6/site-packages} on Unix/Mac OS and
@code{Python26/site-packages} on Windows.

If you don't like the default directory, it can be overridden by an
environment variable.  
@geindex PYTHONUSERBASE
@geindex 环境变量; PYTHONUSERBASE
@ref{de2,,PYTHONUSERBASE} sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the 
@geindex APPDATA
@geindex 环境变量; APPDATA
@code{APPDATA} environment variable.  You can also
modify the @code{site.py} file for your Python installation.

The feature can be disabled entirely by running Python with the
@ref{de3,,-s} option or setting the 
@geindex PYTHONNOUSERSITE
@geindex 环境变量; PYTHONNOUSERSITE
@ref{de4,,PYTHONNOUSERSITE}
environment variable.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 370

@item PEP 370@footnote{https://www.python.org/dev/peps/pep-0370} - 分用户的 site-packages 目录

PEP 由 Christian Heimes 撰写并实现
@end table


@c ======================================================================

@node PEP 371 多任务处理包,PEP 3101 高级字符串格式,PEP 370 分用户的 site-packages 目录,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-0371}@anchor{d1d}@anchor{whatsnew/2 6 pep-371-the-multiprocessing-package}@anchor{de5}
@subsection PEP 371: 多任务处理包


The new @ref{b7,,multiprocessing} package lets Python programs create new
processes that will perform a computation and return a result to the
parent.  The parent and child processes can communicate using queues
and pipes, synchronize their operations using locks and semaphores,
and can share simple arrays of data.

The @ref{b7,,multiprocessing} module started out as an exact emulation of
the @ref{10b,,threading} module using processes instead of threads.  That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class
is the @code{Process}, which is passed a callable object and
a collection of arguments.  The @code{start()} method
sets the callable running in a subprocess, after which you can call
the @code{is_alive()} method to check whether the subprocess is still running
and the @code{join()} method to wait for the process to exit.

Here's a simple example where the subprocess will calculate a
factorial.  The function doing the calculation is written strangely so
that it takes significantly longer when the input argument is a
multiple of 4.

@example
import time
from multiprocessing import Process, Queue


def factorial(queue, N):
    "Compute a factorial."
    # If N is a multiple of 4, this function will take much longer.
    if (N % 4) == 0:
        time.sleep(.05 * N/4)

    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Put the result on the queue
    queue.put(fact)

if __name__ == '__main__':
    queue = Queue()

    N = 5

    p = Process(target=factorial, args=(queue, N))
    p.start()
    p.join()

    result = queue.get()
    print 'Factorial', N, '=', result
@end example

A @ref{de6,,Queue} is used to communicate the result of the factorial.
The @ref{de6,,Queue} object is stored in a global variable.
The child process will use the value of the variable when the child
was created; because it's a @ref{de6,,Queue}, parent and child can use
the object to communicate.  (If the parent were to change the value of
the global variable, the child's value would be unaffected, and vice
versa.)

Two other classes, @code{Pool} and @code{Manager}, provide
higher-level interfaces.  @code{Pool} will create a fixed number of
worker processes, and requests can then be distributed to the workers
by calling @code{apply()} or @code{apply_async()} to add a single request,
and @ref{cff,,map()} or @code{map_async()} to add a number of
requests.  The following code uses a @code{Pool} to spread requests
across 5 worker processes and retrieve a list of results:

@example
from multiprocessing import Pool

def factorial(N, dictionary):
    "Compute a factorial."
    ...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
    print v
@end example

这会产生以下输出:

@example
1
39916800
51090942171709440000
8222838654177922817725562880000000
33452526613163807108170062053440751665152000000000
...
@end example

The other high-level interface, the @code{Manager} class, creates a
separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the @ref{164,,dict()} method; the worker
processes then insert values into the dictionary.  (Locking is not
done for you automatically, which doesn't matter in this example.
@code{Manager}'s methods also include @code{Lock()}, @code{RLock()},
and @code{Semaphore()} to create shared locks.)

@example
import time
from multiprocessing import Pool, Manager

def factorial(N, dictionary):
    "Compute a factorial."
    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Store result in dictionary
    dictionary[N] = fact

if __name__ == '__main__':
    p = Pool(5)
    mgr = Manager()
    d = mgr.dict()         # Create shared dictionary

    # Run tasks using the pool
    for N in range(1, 1000, 10):
        p.apply_async(factorial, (N, d))

    # Mark pool as closed -- no more tasks can be added.
    p.close()

    # Wait for tasks to exit
    p.join()

    # Output results
    for k, v in sorted(d.items()):
        print k, v
@end example

这将产生如下输出:

@example
1 1
11 39916800
21 51090942171709440000
31 8222838654177922817725562880000000
41 33452526613163807108170062053440751665152000000000
51 15511187532873822802242430164693032110632597200169861120000...
@end example


@subsubheading 参见


@ref{b7,,multiprocessing} 模块的文档。


@table @asis

@geindex Python 提高建议; PEP 371

@item PEP 371@footnote{https://www.python.org/dev/peps/pep-0371} - 添加多任务处理包

PEP 由 Jesse Noller 和 Richard Oudkerk 撰写，由 Richard Oudkerk 和 Jesse Noller 实现
@end table


@c ======================================================================

@node PEP 3101 高级字符串格式,PEP 3105 print 改为函数,PEP 371 多任务处理包,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3101}@anchor{d1e}@anchor{whatsnew/2 6 pep-3101-advanced-string-formatting}@anchor{de7}
@subsection PEP 3101: 高级字符串格式


In Python 3.0, the @cite{%} operator is supplemented by a more powerful string
formatting method, @ref{5de,,format()}.  Support for the @ref{5dd,,str.format()} method
has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a @cite{.format()} method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (@cite{@{}, @cite{@}}) as special characters:

@example
>>> # Substitute positional argument 0 into the string.
>>> "User ID: @{0@}".format("root")
'User ID: root'
>>> # Use the named keyword arguments
>>> "User ID: @{uid@}   Last seen: @{last_login@}".format(
...    uid="root",
...    last_login = "5 Mar 2008 07:20")
'User ID: root   Last seen: 5 Mar 2008 07:20'
@end example

Curly brackets can be escaped by doubling them:

@example
>>> "Empty dict: @{@{@}@}".format()
"Empty dict: @{@}"
@end example

Field names can be integers indicating positional arguments, such as
@code{@{0@}}, @code{@{1@}}, etc. or names of keyword arguments.  You can also
supply compound field names that read attributes or access dictionary keys:

@example
>>> import sys
>>> print 'Platform: @{0.platform@}\nPython version: @{0.version@}'.format(sys)
Platform: darwin
Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

>>> import mimetypes
>>> 'Content-type: @{0[.mp4]@}'.format(mimetypes.types_map)
'Content-type: video/mp4'
@end example

Note that when using dictionary-style notation such as @code{[.mp4]}, you
don't need to put any quotation marks around the string; it will look
up the value using @code{.mp4} as the key.  Strings beginning with a
number will be converted to an integer.  You can't write more
complicated expressions inside a format string.

So far we've shown how to specify which field to substitute into the
resulting string.  The precise formatting used is also controllable by
adding a colon followed by a format specifier.  For example:

@example
>>> # Field 0: left justify, pad to 15 characters
>>> # Field 1: right justify, pad to 6 characters
>>> fmt = '@{0:15@} $@{1:>6@}'
>>> fmt.format('Registration', 35)
'Registration    $    35'
>>> fmt.format('Tutorial', 50)
'Tutorial        $    50'
>>> fmt.format('Banquet', 125)
'Banquet         $   125'
@end example

Format specifiers can reference other fields through nesting:

@example
>>> fmt = '@{0:@{1@}@}'
>>> width = 15
>>> fmt.format('Invoice #1234', width)
'Invoice #1234  '
>>> width = 35
>>> fmt.format('Invoice #1234', width)
'Invoice #1234                      '
@end example

可以指定所需宽度内的字段对齐方式：


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

字符

@tab

效果

@item

< (默认)

@tab

左对齐

@item

>

@tab

右对齐

@item

^

@tab

居中对齐

@item

=

@tab

（仅适用于数字类型）在符号后加空格。

@end multitable


Format specifiers can also include a presentation type, which
controls how the value is formatted.  For example, floating-point numbers
can be formatted as a general number or in exponential notation:

@example
>>> '@{0:g@}'.format(3.75)
'3.75'
>>> '@{0:e@}'.format(3.75)
'3.750000e+00'
@end example

A variety of presentation types are available.  Consult the 2.6
documentation for a @ref{de8,,complete list}; here's a sample:


@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{b}

@tab

二进制。输出以2为底的数字。

@item

@code{c}

@tab

字符。在打印之前将整数转换为相应的Unicode字符。

@item

@code{d}

@tab

十进制整数。输出基数为10的数字。

@item

@code{o}

@tab

八进制格式。输出基数为8的数字。

@item

@code{x}

@tab

十六进制格式输出基数为16的数字，使用小写字母表示9以上的数字。

@item

@code{e}

@tab

指数表示法。用字母 'e' 以科学计数法打印数字以表示指数。

@item

@code{g}

@tab

General format. This prints the number as a fixed-point number, unless
the number is too large, in which case it switches to 'e' exponent
notation.

@item

@code{n}

@tab

Number. This is the same as 'g' (for floats) or 'd' (for integers),
except that it uses the current locale setting to insert the appropriate
number separator characters.

@item

@code{%}

@tab

Percentage. Multiplies the number by 100 and displays in fixed ('f')
format, followed by a percent sign.

@end multitable


Classes and types can define a @ref{a38,,__format__()} method to control how they're
formatted.  It receives a single argument, the format specifier:

@example
def __format__(self, format_spec):
    if isinstance(format_spec, unicode):
        return unicode(str(self))
    else:
        return str(self)
@end example

There's also a @ref{5de,,format()} builtin that will format a single
value.  It calls the type's @ref{a38,,__format__()} method with the
provided specifier:

@example
>>> format(75.6564, '.2f')
'75.66'
@end example


@subsubheading 参见



@table @asis

@item @ref{de8,,格式字符串语法}

格式字段的参考文档。

@geindex Python 提高建议; PEP 3101

@item PEP 3101@footnote{https://www.python.org/dev/peps/pep-3101} - 高级字符串格式

PEP 由 Eric V. Smith 撰写并实现
@end table


@c ======================================================================

@node PEP 3105 print 改为函数,PEP 3110 异常处理的变更,PEP 3101 高级字符串格式,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3105}@anchor{d1f}@anchor{whatsnew/2 6 pep-3105-print-as-a-function}@anchor{de9}
@subsection PEP 3105: @code{print} 改为函数


The @code{print} statement becomes the @ref{97a,,print()} function in Python 3.0.
Making @ref{97a,,print()} a function makes it possible to replace the function
by doing @code{def print(...)} or importing a new function from somewhere else.

Python 2.6 has a @code{__future__} import that removes @code{print} as language
syntax, letting you use the functional form instead.  For example:

@example
>>> from __future__ import print_function
>>> print('# of entries', len(dictionary), file=sys.stderr)
@end example

The signature of the new function is:

@example
def print(*args, sep=' ', end='\n', file=None)
@end example

形参包括:

@quotation


@itemize *

@item 
@emph{args}: positional arguments whose values will be printed out.

@item 
@emph{sep}: the separator, which will be printed between arguments.

@item 
@emph{end}: the ending text, which will be printed after all of the
arguments have been output.

@item 
@emph{file}: the file object to which the output will be sent.
@end itemize
@end quotation


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3105

@item PEP 3105@footnote{https://www.python.org/dev/peps/pep-3105} - print 改为函数

PEP 由 Georg Brandl 撰写
@end table


@c ======================================================================

@node PEP 3110 异常处理的变更,PEP 3112 字节字面值,PEP 3105 print 改为函数,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3110}@anchor{d20}@anchor{whatsnew/2 6 pep-3110-exception-handling-changes}@anchor{dea}
@subsection PEP 3110: 异常处理的变更


One error that Python programmers occasionally make
is writing the following code:

@example
try:
    ...
except TypeError, ValueError:  # Wrong!
    ...
@end example

The author is probably trying to catch both @ref{1ff,,TypeError} and
@ref{16d,,ValueError} exceptions, but this code actually does something
different: it will catch @ref{1ff,,TypeError} and bind the resulting
exception object to the local name @code{"ValueError"}.  The
@ref{16d,,ValueError} exception will not be caught at all.  The correct
code specifies a tuple of exceptions:

@example
try:
    ...
except (TypeError, ValueError):
    ...
@end example

This error happens because the use of the comma here is ambiguous:
does it indicate two different nodes in the parse tree, or a single
node that's a tuple?

Python 3.0 makes this unambiguous by replacing the comma with the word
"as".  To catch an exception and store the exception object in the
variable @code{exc}, you must write:

@example
try:
    ...
except TypeError as exc:
    ...
@end example

Python 3.0 will only support the use of "as", and therefore interprets
the first example as catching two different exceptions.  Python 2.6
supports both the comma and "as", so existing code will continue to
work.  We therefore suggest using "as" when writing new Python code
that will only be executed with 2.6.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3110

@item PEP 3110@footnote{https://www.python.org/dev/peps/pep-3110} - 在 Python 3000 中捕获异常

PEP 由 Collin Winter 撰写并实现
@end table


@c ======================================================================

@node PEP 3112 字节字面值,PEP 3116 新 I/O 库,PEP 3110 异常处理的变更,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3112}@anchor{d21}@anchor{whatsnew/2 6 pep-3112-byte-literals}@anchor{deb}
@subsection PEP 3112: 字节字面值


Python 3.0 adopts Unicode as the language's fundamental string type and
denotes 8-bit literals differently, either as @code{b'string'}
or using a @ref{172,,bytes} constructor.  For future compatibility,
Python 2.6 adds @ref{172,,bytes} as a synonym for the @ref{206,,str} type,
and it also supports the @code{b'@w{'}} notation.

The 2.6 @ref{206,,str} differs from 3.0's @ref{172,,bytes} type in various
ways; most notably, the constructor is completely different.  In 3.0,
@code{bytes([65, 66, 67])} is 3 elements long, containing the bytes
representing @code{ABC}; in 2.6, @code{bytes([65, 66, 67])} returns the
12-byte string representing the @ref{206,,str()} of the list.

The primary use of @ref{172,,bytes} in 2.6 will be to write tests of
object type such as @code{isinstance(x, bytes)}.  This will help the 2to3
converter, which can't tell whether 2.x code intends strings to
contain either characters or 8-bit bytes; you can now
use either @ref{172,,bytes} or @ref{206,,str} to represent your intention
exactly, and the resulting code will also be correct in Python 3.0.

There's also a @code{__future__} import that causes all string literals
to become Unicode strings.  This means that @code{\u} escape sequences
can be used to include Unicode characters:

@example
from __future__ import unicode_literals

s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
     '\u3081\u3000\u751f\u305f\u307e\u3054')

print len(s)               # 12 Unicode characters
@end example

At the C level, Python 3.0 will rename the existing 8-bit
string type, called @code{PyStringObject} in Python 2.x,
to @ref{dec,,PyBytesObject}.  Python 2.6 uses @code{#define}
to support using the names @ref{dec,,PyBytesObject()},
@ref{ded,,PyBytes_Check()}, @ref{dee,,PyBytes_FromStringAndSize()},
and all the other functions and macros used with strings.

Instances of the @ref{172,,bytes} type are immutable just
as strings are.  A new @ref{173,,bytearray} type stores a mutable
sequence of bytes:

@example
>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> b = bytearray(u'\u21ef\u3244', 'utf-8')
>>> b
bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
>>> b[0] = '\xe3'
>>> b
bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
>>> unicode(str(b), 'utf-8')
u'\u31ef \u3244'
@end example

Byte arrays support most of the methods of string types, such as
@code{startswith()}/@code{endswith()}, @code{find()}/@code{rfind()},
and some of the methods of lists, such as @code{append()},
@code{pop()},  and @code{reverse()}.

@example
>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')
@end example

There's also a corresponding C API, with
@ref{def,,PyByteArray_FromObject()},
@ref{df0,,PyByteArray_FromStringAndSize()},
and various other functions.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3112

@item PEP 3112@footnote{https://www.python.org/dev/peps/pep-3112} - Python 3000 中的字节字面值

PEP 由 Jason Orendorff 撰写， 补丁2.6 由 Christian Heimes 撰写。
@end table


@c ======================================================================

@node PEP 3116 新 I/O 库,PEP 3118 修改缓冲区协议,PEP 3112 字节字面值,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3116}@anchor{d22}@anchor{whatsnew/2 6 pep-3116-new-i-o-library}@anchor{df1}
@subsection PEP 3116: 新 I/O 库


Python's built-in file objects support a number of methods, but
file-like objects don't necessarily support all of them.  Objects that
imitate files usually support @code{read()} and @code{write()}, but they
may not support @ref{de,,readline()}, for example.  Python 3.0 introduces
a layered I/O library in the @ref{a1,,io} module that separates buffering
and text-handling features from the fundamental read and write
operations.

There are three levels of abstract base classes provided by
the @ref{a1,,io} module:


@itemize *

@item 
@code{RawIOBase} defines raw I/O operations: @code{read()},
@code{readinto()},
@code{write()}, @code{seek()}, @code{tell()}, @code{truncate()},
and @code{close()}.
Most of the methods of this class will often map to a single system call.
There are also @code{readable()}, @code{writable()}, and @code{seekable()}
methods for determining what operations a given object will allow.

Python 3.0 has concrete implementations of this class for files and
sockets, but Python 2.6 hasn't restructured its file and socket objects
in this way.

@c XXX should 2.6 register them in io.py?

@item 
@code{BufferedIOBase} is an abstract base class that
buffers data in memory to reduce the number of
system calls used, making I/O processing more efficient.
It supports all of the methods of @code{RawIOBase},
and adds a @code{raw} attribute holding the underlying raw object.

There are five concrete classes implementing this ABC.
@code{BufferedWriter} and @code{BufferedReader} are for objects
that support write-only or read-only usage that have a @code{seek()}
method for random access.  @code{BufferedRandom} objects support
read and write access upon the same underlying stream, and
@code{BufferedRWPair} is for objects such as TTYs that have both
read and write operations acting upon unconnected streams of data.
The @code{BytesIO} class supports reading, writing, and seeking
over an in-memory buffer.

@geindex universal newlines; What's new

@item 
@code{TextIOBase}: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
and supporting @ref{6f5,,universal newlines}.  @code{TextIOBase} defines
the @ref{de,,readline()} method and supports iteration upon
objects.

There are two concrete implementations.  @code{TextIOWrapper}
wraps a buffered I/O object, supporting all of the methods for
text I/O and adding a @code{buffer} attribute for access
to the underlying object.  @code{StringIO} simply buffers
everything in memory without ever writing anything to disk.

(In Python 2.6, @ref{924,,io.StringIO} is implemented in
pure Python, so it's pretty slow.   You should therefore stick with the
existing @code{StringIO} module or @code{cStringIO} for now.  At some
point Python 3.0's @ref{a1,,io} module will be rewritten into C for speed,
and perhaps the C implementation will be  backported to the 2.x releases.)
@end itemize

In Python 2.6, the underlying implementations haven't been
restructured to build on top of the @ref{a1,,io} module's classes.  The
module is being provided to make it easier to write code that's
forward-compatible with 3.0, and to save developers the effort of writing
their own implementations of buffering and text I/O.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3116

@item PEP 3116@footnote{https://www.python.org/dev/peps/pep-3116} - 新 I/O

PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.
@end table


@c ======================================================================

@node PEP 3118 修改缓冲区协议,PEP 3119 抽象基类,PEP 3116 新 I/O 库,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3118}@anchor{d23}@anchor{whatsnew/2 6 pep-3118-revised-buffer-protocol}@anchor{df2}
@subsection PEP 3118: 修改缓冲区协议


The buffer protocol is a C-level API that lets Python types
exchange pointers into their internal representations.  A
memory-mapped file can be viewed as a buffer of characters, for
example, and this lets another module such as @ref{dd,,re}
treat memory-mapped files as a string of characters to be searched.

The primary users of the buffer protocol are numeric-processing
packages such as NumPy, which expose the internal representation
of arrays so that callers can write data directly into an array instead
of going through a slower API.  This PEP updates the buffer protocol in light of experience
from NumPy development, adding a number of new features
such as indicating the shape of an array or locking a memory region.

The most important new C API function is
@code{PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)}, which
takes an object and a set of flags, and fills in the
@code{Py_buffer} structure with information
about the object's memory representation.  Objects
can use this operation to lock memory in place
while an external caller could be modifying the contents,
so there's a corresponding @code{PyBuffer_Release(Py_buffer *view)} to
indicate that the external caller is done.

@c XXX PyObject_GetBuffer not documented in c-api

The @emph{flags} argument to @ref{df3,,PyObject_GetBuffer()} specifies
constraints upon the memory returned.  Some examples are:

@quotation


@itemize *

@item 
@code{PyBUF_WRITABLE} 指定内存必须为可写。

@item 
@code{PyBUF_LOCK} requests a read-only or exclusive lock on the memory.

@item 
@code{PyBUF_C_CONTIGUOUS} and @code{PyBUF_F_CONTIGUOUS}
requests a C-contiguous (last dimension varies the fastest) or
Fortran-contiguous (first dimension varies the fastest) array layout.
@end itemize
@end quotation

Two new argument codes for @ref{39b,,PyArg_ParseTuple()},
@code{s*} and @code{z*}, return locked buffer objects for a parameter.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3118

@item PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} - 修改缓冲区协议

PEP 由 Travis Oliphant 和 Carl Banks 撰写，由 Travis Oliphant 实现。
@end table


@c ======================================================================

@node PEP 3119 抽象基类,PEP 3127 整型文字支持和语法,PEP 3118 修改缓冲区协议,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3119}@anchor{d24}@anchor{whatsnew/2 6 pep-3119-abstract-base-classes}@anchor{df4}
@subsection PEP 3119: 抽象基类


Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an @ref{3,,abc} module
containing a metaclass called @code{ABCMeta}, special handling of
this metaclass by the @ref{55a,,isinstance()} and @ref{55b,,issubclass()}
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful.  Future versions of Python will probably
add more ABCs.

Let's say you have a particular class and wish to know whether it supports
dictionary-style access.  The phrase "dictionary-style" is vague, however.
It probably means that accessing items with @code{obj[1]} works.
Does it imply that setting items with @code{obj[2] = value} works?
Or that the object will have @code{keys()}, @code{values()}, and @code{items()}
methods?  What about the iterative variants  such as @code{iterkeys()}?  @ref{25,,copy()}
and @code{update()}?  Iterating over the object with @ref{df5,,iter()}?

The Python 2.6 @ref{1d,,collections} module includes a number of
different ABCs that represent these distinctions.  @code{Iterable}
indicates that a class defines @ref{611,,__iter__()}, and
@code{Container} means the class defines a @ref{df6,,__contains__()}
method and therefore supports @code{x in y} expressions.  The basic
dictionary interface of getting items, setting items, and
@code{keys()}, @code{values()}, and @code{items()}, is defined by the
@code{MutableMapping} ABC.

You can derive your own classes from a particular ABC
to indicate they support that ABC's interface:

@example
import collections

class Storage(collections.MutableMapping):
    ...
@end example

Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
calling the ABC's @code{register()} method:

@example
import collections

class Storage:
    ...

collections.MutableMapping.register(Storage)
@end example

For classes that you write, deriving from the ABC is probably clearer.
The @code{register()}  method is useful when you've written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
For example, if you defined a @code{PrintableType} ABC,
it's legal to do:

@example
# Register Python's types
PrintableType.register(int)
PrintableType.register(float)
PrintableType.register(str)
@end example

Classes should obey the semantics specified by an ABC, but
Python can't check this; it's up to the class author to
understand the ABC's requirements and to implement the code accordingly.

To check whether an object supports a particular interface, you can
now write:

@example
def func(d):
    if not isinstance(d, collections.MutableMapping):
        raise ValueError("Mapping object expected, not %r" % d)
@end example

Don't feel that you must now begin writing lots of checks as in the
above example.  Python has a strong tradition of duck-typing, where
explicit type-checking is never done and code simply calls methods on
an object, trusting that those methods will be there and raising an
exception if they aren't.  Be judicious in checking for ABCs and only
do it where it's absolutely necessary.

You can write your own ABCs by using @code{abc.ABCMeta} as the
metaclass in a class definition:

@example
from abc import ABCMeta, abstractmethod

class Drawable():
    __metaclass__ = ABCMeta

    @@abstractmethod
    def draw(self, x, y, scale=1.0):
        pass

    def draw_doubled(self, x, y):
        self.draw(x, y, scale=2.0)


class Square(Drawable):
    def draw(self, x, y, scale):
        ...
@end example

In the @code{Drawable} ABC above, the @code{draw_doubled()} method
renders the object at twice its size and can be implemented in terms
of other methods described in @code{Drawable}.  Classes implementing
this ABC therefore don't need to provide their own implementation
of @code{draw_doubled()}, though they can do so.  An implementation
of @code{draw()} is necessary, though; the ABC can't provide
a useful generic implementation.

You can apply the @code{@@abstractmethod} decorator to methods such as
@code{draw()} that must be implemented; Python will then raise an
exception for classes that don't define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method:

@example
>>> class Circle(Drawable):
...     pass
...
>>> c = Circle()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
>>>
@end example

Abstract data attributes can be declared using the
@code{@@abstractproperty} decorator:

@example
from abc import abstractproperty
...

@@abstractproperty
def readonly(self):
   return self._x
@end example

Subclasses must then define a @code{readonly()} property.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3119

@item PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119} - 引入抽象基类

PEP written by Guido van Rossum and Talin.
Implemented by Guido van Rossum.
Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
@end table


@c ======================================================================

@node PEP 3127 整型文字支持和语法,PEP 3129 类装饰器,PEP 3119 抽象基类,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3127}@anchor{d25}@anchor{whatsnew/2 6 pep-3127-integer-literal-support-and-syntax}@anchor{df7}
@subsection PEP 3127: 整型文字支持和语法


Python 3.0 changes the syntax for octal (base-8) integer literals,
prefixing them with "0o" or "0O" instead of a leading zero, and adds
support for binary (base-2) integer literals, signalled by a "0b" or
"0B" prefix.

Python 2.6 doesn't drop support for a leading 0 signalling
an octal number, but it does add support for "0o" and "0b":

@example
>>> 0o21, 2*8 + 1
(17, 17)
>>> 0b101111
47
@end example

The @ref{d35,,oct()} builtin still returns numbers
prefixed with a leading zero, and a new @ref{d10,,bin()}
builtin returns the binary representation for a number:

@example
>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'
@end example

The @ref{205,,int()} and @code{long()} builtins will now accept the "0o"
and "0b" prefixes when base-8 or base-2 are requested, or when the
@emph{base} argument is zero (signalling that the base used should be
determined from the string):

@example
>>> int ('0o52', 0)
42
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0b1101', 0)
13
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3127

@item PEP 3127@footnote{https://www.python.org/dev/peps/pep-3127} - 整型文字支持和语法

PEP written by Patrick Maupin; backported to 2.6 by
Eric Smith.
@end table


@c ======================================================================

@node PEP 3129 类装饰器,PEP 3141 A Type Hierarchy for Numbers,PEP 3127 整型文字支持和语法,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3129}@anchor{d26}@anchor{whatsnew/2 6 pep-3129-class-decorators}@anchor{df8}
@subsection PEP 3129: 类装饰器


Decorators have been extended from functions to classes.  It's now legal to
write:

@example
@@foo
@@bar
class A:
  pass
@end example

这相当于:

@example
class A:
  pass

A = foo(bar(A))
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3129

@item PEP 3129@footnote{https://www.python.org/dev/peps/pep-3129} - 类装饰器

PEP 由 Collin Winter 撰写
@end table


@c ======================================================================

@node PEP 3141 A Type Hierarchy for Numbers,其他语言特性修改<11>,PEP 3129 类装饰器,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 pep-3141}@anchor{d27}@anchor{whatsnew/2 6 pep-3141-a-type-hierarchy-for-numbers}@anchor{df9}
@subsection PEP 3141: A Type Hierarchy for Numbers


Python 3.0 adds several abstract base classes for numeric types
inspired by Scheme's numeric tower.  These classes were backported to
2.6 as the @ref{c1,,numbers} module.

The most general ABC is @code{Number}.  It defines no operations at
all, and only exists to allow checking if an object is a number by
doing @code{isinstance(obj, Number)}.

@code{Complex} is a subclass of @code{Number}.  Complex numbers
can undergo the basic operations of addition, subtraction,
multiplication, division, and exponentiation, and you can retrieve the
real and imaginary parts and obtain a number's conjugate.  Python's built-in
complex type is an implementation of @code{Complex}.

@code{Real} further derives from @code{Complex}, and adds
operations that only work on real numbers: @code{floor()}, @code{trunc()},
rounding, taking the remainder mod N, floor division,
and comparisons.

@code{Rational} numbers derive from @code{Real}, have
@code{numerator} and @code{denominator} properties, and can be
converted to floats.  Python 2.6 adds a simple rational-number class,
@code{Fraction}, in the @ref{81,,fractions} module.  (It's called
@code{Fraction} instead of @code{Rational} to avoid
a name clash with @ref{d28,,numbers.Rational}.)

@code{Integral} numbers derive from @code{Rational}, and
can be shifted left and right with @code{<<} and @code{>>},
combined using bitwise operations such as @code{&} and @code{|},
and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins
@ref{d3d,,round()}, @ref{dfa,,math.floor()}, @ref{dfb,,math.ceil()}, and adds a new
one, @ref{dfc,,math.trunc()}, that's been backported to Python 2.6.
@ref{dfc,,math.trunc()} rounds toward zero, returning the closest
@code{Integral} that's between the function's argument and zero.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3141

@item PEP 3141@footnote{https://www.python.org/dev/peps/pep-3141} - A Type Hierarchy for Numbers

PEP 由 Jeffrey Yasskin 撰写
@end table

Scheme's numerical tower@footnote{https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower}, from the Guile manual.

Scheme's number datatypes@footnote{http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2} from the R5RS Scheme specification.


@menu
* fractions 模块:: 

@end menu

@node fractions 模块,,,PEP 3141 A Type Hierarchy for Numbers
@anchor{whatsnew/2 6 the-fractions-module}@anchor{dfd}
@subsubsection @code{fractions} 模块


To fill out the hierarchy of numeric types, the @ref{81,,fractions}
module provides a rational-number class.  Rational numbers store their
values as a numerator and denominator forming a fraction, and can
exactly represent numbers such as @code{2/3} that floating-point numbers
can only approximate.

The @code{Fraction} constructor takes two @code{Integral} values
that will be the numerator and denominator of the resulting fraction.

@example
>>> from fractions import Fraction
>>> a = Fraction(2, 3)
>>> b = Fraction(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
Fraction(16, 15)
>>> a/b
Fraction(5, 3)
@end example

For converting floating-point numbers to rationals,
the float type now has an @code{as_integer_ratio()} method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value:

@example
>>> (2.5) .as_integer_ratio()
(5, 2)
>>> (3.1415) .as_integer_ratio()
(7074029114692207L, 2251799813685248L)
>>> (1./3) .as_integer_ratio()
(6004799503160661L, 18014398509481984L)
@end example

Note that values that can only be approximated by floating-point
numbers, such as 1./3, are not simplified to the number being
approximated; the fraction attempts to match the floating-point value
@strong{exactly}.

The @ref{81,,fractions} module is based upon an implementation by Sjoerd
Mullender that was in Python's @code{Demo/classes/} directory for a
long time.  This implementation was significantly updated by Jeffrey
Yasskin.

@node 其他语言特性修改<11>,新增和改进的模块<2>,PEP 3141 A Type Hierarchy for Numbers,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 other-language-changes}@anchor{dfe}
@subsection 其他语言特性修改


对Python 语言核心进行的小改动：


@itemize *

@item 
Directories and zip archives containing a @code{__main__.py} file
can now be executed directly by passing their name to the
interpreter. The directory or zip archive is automatically inserted
as the first entry in sys.path.  (Suggestion and initial patch by
Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
bpo-1739468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739468}.)

@item 
The @ref{553,,hasattr()} function was catching and ignoring all errors,
under the assumption that they meant a @ref{433,,__getattr__()} method
was failing somehow and the return value of @ref{553,,hasattr()} would
therefore be @code{False}.  This logic shouldn't be applied to
@ref{2d3,,KeyboardInterrupt} and @ref{6fd,,SystemExit}, however; Python 2.6
will no longer discard such exceptions when @ref{553,,hasattr()}
encounters them.  (Fixed by Benjamin Peterson; bpo-2196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2196}.)

@item 
When calling a function using the @code{**} syntax to provide keyword
arguments, you are no longer required to use a Python dictionary;
any mapping will now work:

@example
>>> def f(**kw):
...    print sorted(kw)
...
>>> ud=UserDict.UserDict()
>>> ud['a'] = 1
>>> ud['b'] = 'string'
>>> f(**ud)
['a', 'b']
@end example

（由 Alexander Belopolsky 在 bpo-1686487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1686487} 中贡献。）

It's also become legal to provide keyword arguments after a @code{*args} argument
to a function call.

@example
>>> def f(*args, **kw):
...     print args, kw
...
>>> f(1,2,3, *(4,5,6), keyword=13)
(1, 2, 3, 4, 5, 6) @{'keyword': 13@}
@end example

Previously this would have been a syntax error.
(Contributed by Amaury Forgeot d'Arc; bpo-3473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3473}.)

@item 
A new builtin, @code{next(iterator, [default])} returns the next item
from the specified iterator.  If the @emph{default} argument is supplied,
it will be returned if @emph{iterator} has been exhausted; otherwise,
the @ref{58a,,StopIteration} exception will be raised.  (Backported
in bpo-2719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2719}.)

@item 
Tuples now have @code{index()} and @code{count()} methods matching the
list type's @code{index()} and @code{count()} methods:

@example
>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.count(0)
2
@end example

（由 Raymond Hettinger 贡献）

@item 
The built-in types now have improved support for extended slicing syntax,
accepting various combinations of @code{(start, stop, step)}.
Previously, the support was partial and certain corner cases wouldn't work.
(Implemented by Thomas Wouters.)

@c Revision 57619

@item 
Properties now have three attributes, @code{getter}, @code{setter}
and @code{deleter}, that are decorators providing useful shortcuts
for adding a getter, setter or deleter function to an existing
property. You would use them like this:

@example
class C(object):
    @@property
    def x(self):
        return self._x

    @@x.setter
    def x(self, value):
        self._x = value

    @@x.deleter
    def x(self):
        del self._x

class D(C):
    @@C.x.getter
    def x(self):
        return self._x * 2

    @@x.setter
    def x(self, value):
        self._x = value / 2
@end example

@item 
Several methods of the built-in set types now accept multiple iterables:
@code{intersection()},
@code{intersection_update()},
@code{union()}, @code{update()},
@code{difference()} and @code{difference_update()}.

@example
>>> s=set('1234567890')
>>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
set(['2'])
>>> s.difference('246', '789')
set(['1', '0', '3', '5'])
@end example

（由 Raymond Hettinger 贡献。）

@item 
Many floating-point features were added.  The @ref{1fe,,float()} function
will now turn the string @code{nan} into an
IEEE 754 Not A Number value, and @code{+inf} and @code{-inf} into
positive or negative infinity.  This works on any platform with
IEEE 754 semantics.  (Contributed by Christian Heimes; bpo-1635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635}.)

Other functions in the @ref{b1,,math} module, @code{isinf()} and
@code{isnan()}, return true if their floating-point argument is
infinite or Not A Number.  (bpo-1640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1640})

Conversion functions were added to convert floating-point numbers
into hexadecimal strings (bpo-3008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3008}).  These functions
convert floats to and from a string representation without
introducing rounding errors from the conversion between decimal and
binary.  Floats have a @ref{d36,,hex()} method that returns a string
representation, and the @code{float.fromhex()} method converts a string
back into a number:

@example
>>> a = 3.75
>>> a.hex()
'0x1.e000000000000p+1'
>>> float.fromhex('0x1.e000000000000p+1')
3.75
>>> b=1./3
>>> b.hex()
'0x1.5555555555555p-2'
@end example

@item 
A numerical nicety: when creating a complex number from two floats
on systems that support signed zeros (-0 and +0), the
@ref{2c8,,complex()} constructor will now preserve the sign
of the zero.  (Fixed by Mark T. Dickinson; bpo-1507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1507}.)

@item 
Classes that inherit a @ref{455,,__hash__()} method from a parent class
can set @code{__hash__ = None} to indicate that the class isn't
hashable.  This will make @code{hash(obj)} raise a @ref{1ff,,TypeError}
and the class will not be indicated as implementing the
@code{Hashable} ABC.

You should do this when you've defined a @code{__cmp__()} or
@ref{454,,__eq__()} method that compares objects by their value rather
than by identity.  All objects have a default hash method that uses
@code{id(obj)} as the hash value.  There's no tidy way to remove the
@ref{455,,__hash__()} method inherited from a parent class, so
assigning @code{None} was implemented as an override.  At the
C level, extensions can set @code{tp_hash} to
@ref{dff,,PyObject_HashNotImplemented()}.
(Fixed by Nick Coghlan and Amaury Forgeot d'Arc; bpo-2235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2235}.)

@item 
The @ref{e00,,GeneratorExit} exception now subclasses
@ref{2e2,,BaseException} instead of @ref{2e3,,Exception}.  This means
that an exception handler that does @code{except Exception:}
will not inadvertently catch @ref{e00,,GeneratorExit}.
(Contributed by Chad Austin; bpo-1537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537}.)

@item 
Generator objects now have a @code{gi_code} attribute that refers to
the original code object backing the generator.
(Contributed by Collin Winter; bpo-1473257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1473257}.)

@item 
The @ref{2ee,,compile()} built-in function now accepts keyword arguments
as well as positional parameters.  (Contributed by Thomas Wouters;
bpo-1444529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1444529}.)

@item 
The @ref{2c8,,complex()} constructor now accepts strings containing
parenthesized complex numbers, meaning that @code{complex(repr(cplx))}
will now round-trip values.  For example, @code{complex('(3+4j)')}
now returns the value (3+4j).  (bpo-1491866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1491866})

@item 
The string @code{translate()} method now accepts @code{None} as the
translation table parameter, which is treated as the identity
transformation.   This makes it easier to carry out operations
that only delete characters.  (Contributed by Bengt Richter and
implemented by Raymond Hettinger; bpo-1193128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1193128}.)

@item 
The built-in @ref{e01,,dir()} function now checks for a @ref{434,,__dir__()}
method on the objects it receives.  This method must return a list
of strings containing the names of valid attributes for the object,
and lets the object control the value that @ref{e01,,dir()} produces.
Objects that have @ref{433,,__getattr__()} or @ref{552,,__getattribute__()}
methods can use this to advertise pseudo-attributes they will honor.
(bpo-1591665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1591665})

@item 
Instance method objects have new attributes for the object and function
comprising the method; the new synonym for @code{im_self} is
@code{__self__}, and @code{im_func} is also available as @code{__func__}.
The old names are still supported in Python 2.6, but are gone in 3.0.

@item 
An obscure change: when you use the @ref{55f,,locals()} function inside a
@ref{d3a,,class} statement, the resulting dictionary no longer returns free
variables.  (Free variables, in this case, are variables referenced in the
@code{class} statement  that aren't attributes of the class.)
@end itemize

@c ======================================================================

@menu
* 性能优化: 性能优化<10>. 
* Interpreter Changes: Interpreter Changes<2>. 

@end menu

@node 性能优化<10>,Interpreter Changes<2>,,其他语言特性修改<11>
@anchor{whatsnew/2 6 optimizations}@anchor{e02}
@subsubsection 性能优化



@itemize *

@item 
The @ref{12f,,warnings} module has been rewritten in C.  This makes
it possible to invoke warnings from the parser, and may also
make the interpreter's startup faster.
(Contributed by Neal Norwitz and Brett Cannon; bpo-1631171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1631171}.)

@item 
Type objects now have a cache of methods that can reduce
the work required to find the correct method implementation
for a particular class; once cached, the interpreter doesn't need to
traverse base classes to figure out the right method to call.
The cache is cleared if a base class or the class itself is modified,
so the cache should remain correct even in the face of Python's dynamic
nature.
(Original optimization implemented by Armin Rigo, updated for
Python 2.6 by Kevin Jacobs; bpo-1700288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1700288}.)

By default, this change is only applied to types that are included with
the Python core.  Extension modules may not necessarily be compatible with
this cache,
so they must explicitly add @code{Py_TPFLAGS_HAVE_VERSION_TAG}
to the module's @code{tp_flags} field to enable the method cache.
(To be compatible with the method cache, the extension module's code
must not directly access and modify the @code{tp_dict} member of
any of the types it implements.  Most modules don't do this,
but it's impossible for the Python interpreter to determine that.
See bpo-1878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1878} for some discussion.)

@item 
Function calls that use keyword arguments are significantly faster
by doing a quick pointer comparison, usually saving the time of a
full string comparison.  (Contributed by Raymond Hettinger, after an
initial implementation by Antoine Pitrou; bpo-1819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1819}.)

@item 
All of the functions in the @ref{f8,,struct} module have been rewritten in
C, thanks to work at the Need For Speed sprint.
(Contributed by Raymond Hettinger.)

@item 
Some of the standard built-in types now set a bit in their type
objects.  This speeds up checking whether an object is a subclass of
one of these types.  (Contributed by Neal Norwitz.)

@item 
Unicode strings now use faster code for detecting
whitespace and line breaks; this speeds up the @code{split()} method
by about 25% and @code{splitlines()} by 35%.
(Contributed by Antoine Pitrou.)  Memory usage is reduced
by using pymalloc for the Unicode string's data.

@item 
The @code{with} statement now stores the @ref{d66,,__exit__()} method on the stack,
producing a small speedup.  (Implemented by Jeffrey Yasskin.)

@item 
To reduce memory usage, the garbage collector will now clear internal
free lists when garbage-collecting the highest generation of objects.
This may return memory to the operating system sooner.
@end itemize

@c ======================================================================

@node Interpreter Changes<2>,,性能优化<10>,其他语言特性修改<11>
@anchor{whatsnew/2 6 interpreter-changes}@anchor{e03}@anchor{whatsnew/2 6 new-26-interpreter}@anchor{e04}
@subsubsection Interpreter Changes


Two command-line options have been reserved for use by other Python
implementations.  The @ref{e05,,-J} switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM.  @ref{297,,-X} has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython.  If either option is used with Python 2.6, the
interpreter will report that the option isn't currently used.

Python can now be prevented from writing @code{.pyc} or @code{.pyo}
files by supplying the @ref{e06,,-B} switch to the Python interpreter,
or by setting the 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE} environment
variable before running the interpreter.  This setting is available to
Python programs as the @code{sys.dont_write_bytecode} variable, and
Python code can change the value to modify the interpreter's
behaviour.  (Contributed by Neal Norwitz and Georg Brandl.)

The encoding used for standard input, output, and standard error can
be specified by setting the 
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} environment
variable before running the interpreter.  The value should be a string
in the form @code{<encoding>} or @code{<encoding>:<errorhandler>}.
The @emph{encoding} part specifies the encoding's name, e.g. @code{utf-8} or
@code{latin-1}; the optional @emph{errorhandler} part specifies
what to do with characters that can't be handled by the encoding,
and  should be one of "error", "ignore", or "replace".   (Contributed
by Martin von Löwis.)

@c ======================================================================

@node 新增和改进的模块<2>,Deprecations and Removals,其他语言特性修改<11>,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 new-and-improved-modules}@anchor{e08}
@subsection 新增和改进的模块


As in every release, Python's standard library received a number of
enhancements and bug fixes.  Here's a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
@code{Misc/NEWS} file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.


@itemize *

@item 
The @ref{a,,asyncore} and @ref{8,,asynchat} modules are
being actively maintained again, and a number of patches and bugfixes
were applied.  (Maintained by Josiah Carlson; see bpo-1736190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1736190} for
one patch.)

@item 
The @code{bsddb} module also has a new maintainer, Jesús Cea Avión, and the package
is now available as a standalone package.  The web page for the package is
www.jcea.es/programacion/pybsddb.htm@footnote{https://www.jcea.es/programacion/pybsddb.htm}.
The plan is to remove the package from the standard library
in Python 3.0, because its pace of releases is much more frequent than
Python's.

The @code{bsddb.dbshelve} module now uses the highest pickling protocol
available, instead of restricting itself to protocol 1.
(Contributed by W. Barnes.)

@item 
The @ref{15,,cgi} module will now read variables from the query string
of an HTTP POST request.  This makes it possible to use form actions
with URLs that include query strings such as
"/cgi-bin/add.py?category=1".  (Contributed by Alexandre Fiori and
Nubis; bpo-1817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1817}.)

The @code{parse_qs()} and @code{parse_qsl()} functions have been
relocated from the @ref{15,,cgi} module to the @code{urlparse} module.
The versions still available in the @ref{15,,cgi} module will
trigger @ref{15c,,PendingDeprecationWarning} messages in 2.6
(bpo-600362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=600362}).

@item 
The @ref{18,,cmath} module underwent extensive revision,
contributed by Mark Dickinson and Christian Heimes.
Five new functions were added:


@itemize *

@item 
@code{polar()} converts a complex number to polar form, returning
the modulus and argument of the complex number.

@item 
@code{rect()} does the opposite, turning a modulus, argument pair
back into the corresponding complex number.

@item 
@code{phase()} returns the argument (also called the angle) of a complex
number.

@item 
@code{isnan()} returns True if either
the real or imaginary part of its argument is a NaN.

@item 
@code{isinf()} returns True if either the real or imaginary part of
its argument is infinite.
@end itemize

The revisions also improved the numerical soundness of the
@ref{18,,cmath} module.  For all functions, the real and imaginary
parts of the results are accurate to within a few units of least
precision (ulps) whenever possible.  See bpo-1381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1381} for the
details.  The branch cuts for @code{asinh()}, @code{atanh()}: and
@code{atan()} have also been corrected.

The tests for the module have been greatly expanded; nearly 2000 new
test cases exercise the algebraic functions.

On IEEE 754 platforms, the @ref{18,,cmath} module now handles IEEE 754
special values and floating-point exceptions in a manner consistent
with Annex 'G' of the C99 standard.

@item 
A new data type in the @ref{1d,,collections} module: @code{namedtuple(typename,
fieldnames)} is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index.  For example:

@example
>>> var_type = collections.namedtuple('variable',
...             'id name type size')
>>> # Names are separated by spaces or commas.
>>> # 'id, name, type, size' would also work.
>>> var_type._fields
('id', 'name', 'type', 'size')

>>> var = var_type(1, 'frequency', 'int', 4)
>>> print var[0], var.id    # Equivalent
1 1
>>> print var[2], var.type  # Equivalent
int int
>>> var._asdict()
@{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'@}
>>> v2 = var._replace(name='amplitude')
>>> v2
variable(id=1, name='amplitude', type='int', size=4)
@end example

Several places in the standard library that returned tuples have
been modified to return @code{namedtuple} instances.  For example,
the @code{Decimal.as_tuple()} method now returns a named tuple with
@code{sign}, @code{digits}, and @code{exponent} fields.

（由 Raymond Hettinger 贡献。）

@item 
Another change to the @ref{1d,,collections} module is that the
@code{deque} type now supports an optional @emph{maxlen} parameter;
if supplied, the deque's size will be restricted to no more
than @emph{maxlen} items.  Adding more items to a full deque causes
old items to be discarded.

@example
>>> from collections import deque
>>> dq=deque(maxlen=3)
>>> dq
deque([], maxlen=3)
>>> dq.append(1); dq.append(2); dq.append(3)
>>> dq
deque([1, 2, 3], maxlen=3)
>>> dq.append(4)
>>> dq
deque([2, 3, 4], maxlen=3)
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @code{Cookie} module's @code{Morsel} objects now support an
@code{httponly} attribute.  In some browsers. cookies with this attribute
set cannot be accessed or manipulated by JavaScript code.
(Contributed by Arvin Schnell; bpo-1638033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1638033}.)

@item 
A new window method in the @ref{2b,,curses} module,
@code{chgat()}, changes the display attributes for a certain number of
characters on a single line.  (Contributed by Fabian Kreutz.)

@example
# Boldface text starting at y=0,x=21
# and affecting the rest of the line.
stdscr.chgat(0, 21, curses.A_BOLD)
@end example

The @code{Textbox} class in the @ref{2e,,curses.textpad} module
now supports editing in insert mode as well as overwrite mode.
Insert mode is enabled by supplying a true value for the @emph{insert_mode}
parameter when creating the @code{Textbox} instance.

@item 
The @ref{30,,datetime} module's @code{strftime()} methods now support a
@code{%f} format code that expands to the number of microseconds in the
object, zero-padded on
the left to six places.  (Contributed by Skip Montanaro; bpo-1158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1158}.)

@item 
The @ref{35,,decimal} module was updated to version 1.66 of
the General Decimal Specification@footnote{http://speleotrove.com/decimal/decarith.html}.  New features
include some methods for some basic mathematical functions such as
@code{exp()} and @code{log10()}:

@example
>>> Decimal(1).exp()
Decimal("2.718281828459045235360287471")
>>> Decimal("2.7182818").ln()
Decimal("0.9999999895305022877376682436")
>>> Decimal(1000).log10()
Decimal("3")
@end example

The @code{as_tuple()} method of @code{Decimal} objects now returns a
named tuple with @code{sign}, @code{digits}, and @code{exponent} fields.

（由 Facundo Batista 和 Mark Dickinson 实现。 具名元组支持由 Raymond Hettinger 添加。）

@item 
The @ref{36,,difflib} module's @code{SequenceMatcher} class
now returns named tuples representing matches,
with @code{a}, @code{b}, and @code{size} attributes.
(Contributed by Raymond Hettinger.)

@item 
An optional @code{timeout} parameter, specifying a timeout measured in
seconds, was added to the @ref{1a6,,ftplib.FTP} class constructor as
well as the @code{connect()} method.  (Added by Facundo Batista.)
Also, the @code{FTP} class's @code{storbinary()} and
@code{storlines()} now take an optional @emph{callback} parameter that
will be called with each block of data after the data has been sent.
(Contributed by Phil Schwartz; bpo-1221598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1221598}.)

@item 
The @code{reduce()} built-in function is also available in the
@ref{83,,functools} module.  In Python 3.0, the builtin has been
dropped and @code{reduce()} is only available from @ref{83,,functools};
currently there are no plans to drop the builtin in the 2.x series.
(Patched by Christian Heimes; bpo-1739906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1739906}.)

@item 
When possible, the @ref{86,,getpass} module will now use
@code{/dev/tty} to print a prompt message and read the password,
falling back to standard error and standard input.  If the
password may be echoed to the terminal, a warning is printed before
the prompt is displayed.  (Contributed by Gregory P. Smith.)

@item 
The @ref{6c7,,glob.glob()} function can now return Unicode filenames if
a Unicode path was used and Unicode filenames are matched within the
directory.  (bpo-1001604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1001604})

@item 
A new function in the @ref{8d,,heapq} module, @code{merge(iter1, iter2, ...)},
takes any number of iterables returning data in sorted
order, and returns a new generator that returns the contents of all
the iterators, also in sorted order.  For example:

@example
>>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
[1, 2, 3, 5, 8, 9, 16]
@end example

Another new function, @code{heappushpop(heap, item)},
pushes @emph{item} onto @emph{heap}, then pops off and returns the smallest item.
This is more efficient than making a call to @code{heappush()} and then
@code{heappop()}.

@ref{8d,,heapq} is now implemented to only use less-than comparison,
instead of the less-than-or-equal comparison it previously used.
This makes @ref{8d,,heapq}'s usage of a type match the
@ref{550,,list.sort()} method.
(Contributed by Raymond Hettinger.)

@item 
An optional @code{timeout} parameter, specifying a timeout measured in
seconds, was added to the @code{httplib.HTTPConnection} and
@code{HTTPSConnection} class constructors.  (Added by Facundo
Batista.)

@item 
Most of the @ref{a0,,inspect} module's functions, such as
@code{getmoduleinfo()} and @code{getargs()}, now return named tuples.
In addition to behaving like tuples, the elements of the  return value
can also be accessed as attributes.
(Contributed by Raymond Hettinger.)

此模块中的新增函数包括 @code{isgenerator()}, @code{isgeneratorfunction()} 和 @code{isabstract()}。

@item 
@ref{a3,,itertools} 模块增加了几个新函数。

@code{izip_longest(iter1, iter2, ...[, fillvalue])} makes tuples from
each of the elements; if some of the iterables are shorter than
others, the missing values are set to @emph{fillvalue}.  For example:

@example
>>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
@end example

@code{product(iter1, iter2, ..., [repeat=N])} returns the Cartesian product
of the supplied iterables, a set of tuples containing
every possible combination of the elements returned from each iterable.

@example
>>> list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
 (2, 4), (2, 5), (2, 6),
 (3, 4), (3, 5), (3, 6)]
@end example

The optional @emph{repeat} keyword argument is used for taking the
product of an iterable or a set of iterables with themselves,
repeated @emph{N} times.  With a single iterable argument, @emph{N}-tuples
are returned:

@example
>>> list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
@end example

With two iterables, @emph{2N}-tuples are returned.

@example
>>> list(itertools.product([1,2], [3,4], repeat=2))
[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
@end example

@code{combinations(iterable, r)} 基于 @emph{iterable} 的元素返回长度为 @emph{r} 的子序列。

@example
>>> list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
>>> list(itertools.combinations('123', 3))
[('1', '2', '3')]
>>> list(itertools.combinations('1234', 3))
[('1', '2', '3'), ('1', '2', '4'),
 ('1', '3', '4'), ('2', '3', '4')]
@end example

@code{permutations(iter[, r])} returns all the permutations of length @emph{r} of
the iterable's elements.  If @emph{r} is not specified, it will default to the
number of elements produced by the iterable.

@example
>>> list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
 (2, 1), (2, 3), (2, 4),
 (3, 1), (3, 2), (3, 4),
 (4, 1), (4, 2), (4, 3)]
@end example

@code{itertools.chain(*iterables)} is an existing function in
@ref{a3,,itertools} that gained a new constructor in Python 2.6.
@code{itertools.chain.from_iterable(iterable)} takes a single
iterable that should return other iterables.  @code{chain()} will
then return all the elements of the first iterable, then
all the elements of the second, and so on.

@example
>>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
[1, 2, 3, 4, 5, 6]
@end example

（全部由 Raymond Hettinger 贡献。）

@item 
The @ref{aa,,logging} module's @code{FileHandler} class
and its subclasses @code{WatchedFileHandler}, @code{RotatingFileHandler},
and @code{TimedRotatingFileHandler} now
have an optional @emph{delay} parameter to their constructors.  If @emph{delay}
is true, opening of the log file is deferred until the first
@code{emit()} call is made.  (Contributed by Vinay Sajip.)

@code{TimedRotatingFileHandler} also has a @emph{utc} constructor
parameter.  If the argument is true, UTC time will be used
in determining when midnight occurs and in generating filenames;
otherwise local time will be used.

@item 
为 @ref{b1,,math} 模块添加了一些新函数:


@itemize *

@item 
@ref{e09,,isinf()} and @ref{e0a,,isnan()} determine whether a given float
is a (positive or negative) infinity or a NaN (Not a Number), respectively.

@item 
@ref{e0b,,copysign()} copies the sign bit of an IEEE 754 number,
returning the absolute value of @emph{x} combined with the sign bit of
@emph{y}.  For example, @code{math.copysign(1, -0.0)} returns -1.0.
(Contributed by Christian Heimes.)

@item 
@ref{1fd,,factorial()} computes the factorial of a number.
(Contributed by Raymond Hettinger; bpo-2138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2138}.)

@item 
@ref{e0c,,fsum()} adds up the stream of numbers from an iterable,
and is careful to avoid loss of precision through using partial sums.
(Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
bpo-2819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2819}.)

@item 
@ref{e0d,,acosh()}, @ref{e0e,,asinh()}
and @ref{e0f,,atanh()} compute the inverse hyperbolic functions.

@item 
@ref{e10,,log1p()} returns the natural logarithm of @emph{1+x}
(base @emph{e}).

@item 
@code{trunc()} rounds a number toward zero, returning the closest
@code{Integral} that's between the function's argument and zero.
Added as part of the backport of
@ref{d27,,PEP 3141's type hierarchy for numbers}.
@end itemize

@item 
The @ref{b1,,math} module has been improved to give more consistent
behaviour across platforms, especially with respect to handling of
floating-point exceptions and IEEE 754 special values.

Whenever possible, the module follows the recommendations of the C99
standard about 754's special values.  For example, @code{sqrt(-1.)}
should now give a @ref{16d,,ValueError} across almost all platforms,
while @code{sqrt(float('NaN'))} should return a NaN on all IEEE 754
platforms.  Where Annex 'F' of the C99 standard recommends signaling
'divide-by-zero' or 'invalid', Python will raise @ref{16d,,ValueError}.
Where Annex 'F' of the C99 standard recommends signaling 'overflow',
Python will raise @ref{a4a,,OverflowError}.  (See bpo-711019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=711019} and
bpo-1640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1640}.)

（由 Christian Heimes 和 Mark Dickinson 贡献。）

@item 
@ref{323,,mmap} objects now have a @code{rfind()} method that searches for a
substring beginning at the end of the string and searching
backwards.  The @code{find()} method also gained an @emph{end} parameter
giving an index at which to stop searching.
(Contributed by John Lenton.)

@item 
The @ref{c2,,operator} module gained a
@code{methodcaller()} function that takes a name and an optional
set of arguments, returning a callable that will call
the named function on any arguments passed to it.  For example:

@example
>>> # Equivalent to lambda s: s.replace('old', 'new')
>>> replacer = operator.methodcaller('replace', 'old', 'new')
>>> replacer('old wine in old bottles')
'new wine in new bottles'
@end example

（由 Gregory Petrosyan 提供建议，之后由 Georg Brandl 贡献。）

The @code{attrgetter()} function now accepts dotted names and performs
the corresponding attribute lookups:

@example
>>> inst_name = operator.attrgetter(
...        '__class__.__name__')
>>> inst_name('@w{'})
'str'
>>> inst_name(help)
'_Helper'
@end example

（由 Barry Warsaw 提供建议，之后由 Georg Brandl 贡献。）

@item 
The @ref{c4,,os} module now wraps several new system calls.
@code{fchmod(fd, mode)} and @code{fchown(fd, uid, gid)} change the mode
and ownership of an opened file, and @code{lchmod(path, mode)} changes
the mode of a symlink.  (Contributed by Georg Brandl and Christian
Heimes.)

@code{chflags()} and @code{lchflags()} are wrappers for the
corresponding system calls (where they're available), changing the
flags set on a file.  Constants for the flag values are defined in
the @ref{f4,,stat} module; some possible values include
@code{UF_IMMUTABLE} to signal the file may not be changed and
@code{UF_APPEND} to indicate that data can only be appended to the
file.  (Contributed by M. Levinson.)

@code{os.closerange(low, high)} efficiently closes all file descriptors
from @emph{low} to @emph{high}, ignoring any errors and not including @emph{high} itself.
This function is now used by the @ref{f9,,subprocess} module to make starting
processes faster.  (Contributed by Georg Brandl; bpo-1663329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1663329}.)

@item 
The @code{os.environ} object's @code{clear()} method will now unset the
environment variables using @ref{1cd,,os.unsetenv()} in addition to clearing
the object's keys.  (Contributed by Martin Horcicka; bpo-1181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1181}.)

@item 
The @ref{751,,os.walk()} function now has a @code{followlinks} parameter. If
set to True, it will follow symlinks pointing to directories and
visit the directory's contents.  For backward compatibility, the
parameter's default value is false.  Note that the function can fall
into an infinite recursion if there's a symlink that points to a
parent directory.  (bpo-1273829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1273829})

@item 
In the @ref{c5,,os.path} module, the @code{splitext()} function
has been changed to not split on leading period characters.
This produces better results when operating on Unix's dot-files.
For example, @code{os.path.splitext('.ipython')}
now returns @code{('.ipython', '@w{'})} instead of @code{('@w{'}, '.ipython')}.
(bpo-1115886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1115886})

A new function, @code{os.path.relpath(path, start='.')}, returns a relative path
from the @code{start} path, if it's supplied, or from the current
working directory to the destination @code{path}.  (Contributed by
Richard Barran; bpo-1339796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1339796}.)

On Windows, @ref{e11,,os.path.expandvars()} will now expand environment variables
given in the form "%var%", and "~user" will be expanded into the
user's home directory path.  (Contributed by Josiah Carlson;
bpo-957650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957650}.)

@item 
The Python debugger provided by the @ref{c9,,pdb} module
gained a new command: "run" restarts the Python program being debugged
and can optionally take new command-line arguments for the program.
(Contributed by Rocky Bernstein; bpo-1393667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1393667}.)

@item 
The @ref{e12,,pdb.post_mortem()} function, used to begin debugging a
traceback, will now use the traceback returned by @ref{d2f,,sys.exc_info()}
if no traceback is supplied.   (Contributed by Facundo Batista;
bpo-1106316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1106316}.)

@item 
The @ref{cb,,pickletools} module now has an @code{optimize()} function
that takes a string containing a pickle and removes some unused
opcodes, returning a shorter pickle that contains the same data structure.
(Contributed by Raymond Hettinger.)

@item 
A @code{get_data()} function was added to the @ref{cd,,pkgutil}
module that returns the contents of resource files included
with an installed Python package.  For example:

@example
>>> import pkgutil
>>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
 ...
@end example

（由 Paul Moore 在 bpo-2439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2439} 中贡献。）

@item 
The @code{pyexpat} module's @code{Parser} objects now allow setting
their @code{buffer_size} attribute to change the size of the buffer
used to hold character data.
(Contributed by Achim Gaedke; bpo-1137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1137}.)

@item 
The @code{Queue} module now provides queue variants that retrieve entries
in different orders.  The @code{PriorityQueue} class stores
queued items in a heap and retrieves them in priority order,
and @code{LifoQueue} retrieves the most recently added entries first,
meaning that it behaves like a stack.
(Contributed by Raymond Hettinger.)

@item 
The @ref{dc,,random} module's @code{Random} objects can
now be pickled on a 32-bit system and unpickled on a 64-bit
system, and vice versa.  Unfortunately, this change also means
that Python 2.6's @code{Random} objects can't be unpickled correctly
on earlier versions of Python.
(Contributed by Shawn Ligocki; bpo-1727780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1727780}.)

The new @code{triangular(low, high, mode)} function returns random
numbers following a triangular distribution.   The returned values
are between @emph{low} and @emph{high}, not including @emph{high} itself, and
with @emph{mode} as the most frequently occurring value
in the distribution.  (Contributed by Wladmir van der Laan and
Raymond Hettinger; bpo-1681432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1681432}.)

@item 
Long regular expression searches carried out by the  @ref{dd,,re}
module will check for signals being delivered, so
time-consuming searches can now be interrupted.
(Contributed by Josh Hoyt and Ralf Schmitt; bpo-846388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=846388}.)

The regular expression module is implemented by compiling bytecodes
for a tiny regex-specific virtual machine.  Untrusted code
could create malicious strings of bytecode directly and cause crashes,
so Python 2.6 includes a verifier for the regex bytecode.
(Contributed by Guido van Rossum from work for Google App Engine;
bpo-3487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3487}.)

@item 
The @ref{e1,,rlcompleter} module's @code{Completer.complete()} method
will now ignore exceptions triggered while evaluating a name.
(Fixed by Lorenz Quack; bpo-2250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2250}.)

@item 
The @ref{e3,,sched} module's @code{scheduler} instances now
have a read-only @ref{da,,queue} attribute that returns the
contents of the scheduler's queue, represented as a list of
named tuples with the fields @code{(time, priority, action, argument)}.
(Contributed by Raymond Hettinger; bpo-1861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1861}.)

@item 
The @ref{e5,,select} module now has wrapper functions
for the Linux @code{epoll()} and BSD @code{kqueue()} system calls.
@code{modify()} method was added to the existing @code{poll}
objects; @code{pollobj.modify(fd, eventmask)} takes a file descriptor
or file object and an event mask, modifying the recorded event mask
for that file.
(Contributed by Christian Heimes; bpo-1657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1657}.)

@item 
The @ref{34e,,shutil.copytree()} function now has an optional @emph{ignore} argument
that takes a callable object.  This callable will receive each directory path
and a list of the directory's contents, and returns a list of names that
will be ignored, not copied.

The @ref{e9,,shutil} module also provides an @code{ignore_patterns()}
function for use with this new parameter.  @code{ignore_patterns()}
takes an arbitrary number of glob-style patterns and returns a
callable that will ignore any files and directories that match any
of these patterns.  The following example copies a directory tree,
but skips both @code{.svn} directories and Emacs backup files,
which have names ending with '~':

@example
shutil.copytree('Doc/library', '/tmp/library',
                ignore=shutil.ignore_patterns('*~', '.svn'))
@end example

（由 Tarek Ziadé 在 bpo-2663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2663} 中贡献。）

@item 
Integrating signal handling with GUI handling event loops
like those used by Tkinter or GTk+ has long been a problem; most
software ends up polling, waking up every fraction of a second to check
if any GUI events have occurred.
The @ref{ea,,signal} module can now make this more efficient.
Calling @code{signal.set_wakeup_fd(fd)} sets a file descriptor
to be used; when a signal is received, a byte is written to that
file descriptor.  There's also a C-level function,
@ref{e13,,PySignal_SetWakeupFd()}, for setting the descriptor.

Event loops will use this by opening a pipe to create two descriptors,
one for reading and one for writing.  The writable descriptor
will be passed to @code{set_wakeup_fd()}, and the readable descriptor
will be added to the list of descriptors monitored by the event loop via
@code{select()} or @code{poll()}.
On receiving a signal, a byte will be written and the main event loop
will be woken up, avoiding the need to poll.

（由 Adam Olsen 在 bpo-1583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1583} 中贡献。）

The @code{siginterrupt()} function is now available from Python code,
and allows changing whether signals can interrupt system calls or not.
(Contributed by Ralf Schmitt.)

The @code{setitimer()} and @code{getitimer()} functions have also been
added (where they're available).  @code{setitimer()}
allows setting interval timers that will cause a signal to be
delivered to the process after a specified time, measured in
wall-clock time, consumed process time, or combined process+system
time.  (Contributed by Guilherme Polo; bpo-2240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2240}.)

@item 
The @ref{ed,,smtplib} module now supports SMTP over SSL thanks to the
addition of the @code{SMTP_SSL} class. This class supports an
interface identical to the existing @code{SMTP} class.
(Contributed by Monty Taylor.)  Both class constructors also have an
optional @code{timeout} parameter that specifies a timeout for the
initial connection attempt, measured in seconds.  (Contributed by
Facundo Batista.)

An implementation of the LMTP protocol (
@geindex RFC; RFC 2033
RFC 2033@footnote{https://tools.ietf.org/html/rfc2033.html}) was also added
to the module.  LMTP is used in place of SMTP when transferring
e-mail between agents that don't manage a mail queue.  (LMTP
implemented by Leif Hedstrom; bpo-957003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957003}.)

@code{SMTP.starttls()} now complies with 
@geindex RFC; RFC 3207
RFC 3207@footnote{https://tools.ietf.org/html/rfc3207.html} and forgets any
knowledge obtained from the server not obtained from the TLS
negotiation itself.  (Patch contributed by Bill Fenner;
bpo-829951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=829951}.)

@item 
The @ref{ef,,socket} module now supports TIPC (@indicateurl{http://tipc.sourceforge.net/}),
a high-performance non-IP-based protocol designed for use in clustered
environments.  TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli; bpo-1646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1646}.)

A new function, @code{create_connection()}, takes an address and
connects to it using an optional timeout value, returning the
connected socket object.  This function also looks up the address's
type and connects to it using IPv4 or IPv6 as appropriate.  Changing
your code to use @code{create_connection()} instead of
@code{socket(socket.AF_INET, ...)} may be all that's required to make
your code work with IPv6.

@item 
The base classes in the @code{SocketServer} module now support
calling a @code{handle_timeout()} method after a span of inactivity
specified by the server's @code{timeout} attribute.  (Contributed
by Michael Pomraning.)  The @code{serve_forever()} method
now takes an optional poll interval measured in seconds,
controlling how often the server will check for a shutdown request.
(Contributed by Pedro Werneck and Jeffrey Yasskin;
bpo-742598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=742598}, bpo-1193577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1193577}.)

@item 
The @ref{f2,,sqlite3} module, maintained by Gerhard Häring,
has been updated from version 2.3.2 in Python 2.5 to
version 2.4.1.

@item 
The @ref{f8,,struct} module now supports the C99 @code{_Bool} type,
using the format character @code{'?'}.
(Contributed by David Remahl.)

@item 
The @code{Popen} objects provided by the @ref{f9,,subprocess} module
now have @code{terminate()}, @code{kill()}, and @code{send_signal()} methods.
On Windows, @code{send_signal()} only supports the @code{SIGTERM}
signal, and all these methods are aliases for the Win32 API function
@code{TerminateProcess()}.
(Contributed by Christian Heimes.)

@item 
A new variable in the @ref{fd,,sys} module, @code{float_info}, is an
object containing information derived from the @code{float.h} file
about the platform's floating-point support.  Attributes of this
object include @code{mant_dig} (number of digits in the mantissa),
@code{epsilon} (smallest difference between 1.0 and the next
largest value representable), and several others.  (Contributed by
Christian Heimes; bpo-1534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1534}.)

Another new variable, @code{dont_write_bytecode}, controls whether Python
writes any @code{.pyc} or @code{.pyo} files on importing a module.
If this variable is true, the compiled files are not written.  The
variable is initially set on start-up by supplying the @ref{e06,,-B}
switch to the Python interpreter, or by setting the
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE} environment variable before
running the interpreter.  Python code can subsequently
change the value of this variable to control whether bytecode files
are written or not.
(Contributed by Neal Norwitz and Georg Brandl.)

Information about the command-line arguments supplied to the Python
interpreter is available by reading attributes of a named
tuple available as @code{sys.flags}.  For example, the @code{verbose}
attribute is true if Python
was executed in verbose mode, @code{debug} is true in debugging mode, etc.
These attributes are all read-only.
(Contributed by Christian Heimes.)

A new function, @code{getsizeof()}, takes a Python object and returns
the amount of memory used by the object, measured in bytes.  Built-in
objects return correct results; third-party extensions may not,
but can define a @code{__sizeof__()} method to return the
object's size.
(Contributed by Robert Schuppenies; bpo-2898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2898}.)

It's now possible to determine the current profiler and tracer functions
by calling @ref{e14,,sys.getprofile()} and @ref{e15,,sys.gettrace()}.
(Contributed by Georg Brandl; bpo-1648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1648}.)

@item 
The @ref{101,,tarfile} module now supports POSIX.1-2001 (pax) tarfiles in
addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
already supported.  The default format is GNU tar; specify the
@code{format} parameter to open a file using a different format:

@example
tar = tarfile.open("output.tar", "w",
                   format=tarfile.PAX_FORMAT)
@end example

The new @code{encoding} and @code{errors} parameters specify an encoding and
an error handling scheme for character conversions.  @code{'strict'},
@code{'ignore'}, and @code{'replace'} are the three standard ways Python can
handle errors,;
@code{'utf-8'} is a special value that replaces bad characters with
their UTF-8 representation.  (Character conversions occur because the
PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)

The @code{TarFile.add()} method now accepts an @code{exclude} argument that's
a function that can be used to exclude certain filenames from
an archive.
The function must take a filename and return true if the file
should be excluded or false if it should be archived.
The function is applied to both the name initially passed to @code{add()}
and to the names of files in recursively-added directories.

(All changes contributed by Lars Gustäbel).

@item 
为 @ref{698,,telnetlib.Telnet} 类构造器增加了可选的 @code{timeout} 形参，指定以秒为单位的超时设置。 （由 Facundo Batista 添加。）

@item 
The @ref{e16,,tempfile.NamedTemporaryFile} class usually deletes
the temporary file it created when the file is closed.  This
behaviour can now be changed by passing @code{delete=False} to the
constructor.  (Contributed by Damien Miller; bpo-1537850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1537850}.)

A new class, @code{SpooledTemporaryFile}, behaves like
a temporary file but stores its data in memory until a maximum size is
exceeded.  On reaching that limit, the contents will be written to
an on-disk temporary file.  (Contributed by Dustin J. Mitchell.)

The @code{NamedTemporaryFile} and @code{SpooledTemporaryFile} classes
both work as context managers, so you can write
@code{with tempfile.NamedTemporaryFile() as tmp: ...}.
(Contributed by Alexander Belopolsky; bpo-2021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2021}.)

@item 
The @code{test.test_support} module gained a number
of context managers useful for writing tests.
@code{EnvironmentVarGuard()} is a
context manager that temporarily changes environment variables and
automatically restores them to their old values.

Another context manager, @code{TransientResource}, can surround calls
to resources that may or may not be available; it will catch and
ignore a specified list of exceptions.  For example,
a network test may ignore certain failures when connecting to an
external web site:

@example
with test_support.TransientResource(IOError,
                                errno=errno.ETIMEDOUT):
    f = urllib.urlopen('https://sf.net')
    ...
@end example

Finally, @code{check_warnings()} resets the @code{warning} module's
warning filters and returns an object that will record all warning
messages triggered (bpo-3781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3781}):

@example
with test_support.check_warnings() as wrec:
    warnings.simplefilter("always")
    # ... code that triggers a warning ...
    assert str(wrec.message) == "function is outdated"
    assert len(wrec.warnings) == 1, "Multiple warnings raised"
@end example

（由 Brett Cannon 贡献。）

@item 
The @ref{10a,,textwrap} module can now preserve existing whitespace
at the beginnings and ends of the newly-created lines
by specifying @code{drop_whitespace=False}
as an argument:

@example
>>> S = """This  sentence  has a bunch   of
...   extra   whitespace."""
>>> print textwrap.fill(S, width=15)
This  sentence
has a bunch
of    extra
whitespace.
>>> print textwrap.fill(S, drop_whitespace=False, width=15)
This  sentence
  has a bunch
   of    extra
   whitespace.
>>>
@end example

（由 Dwayne Bailey 在 bpo-1581073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1581073} 中贡献。）

@item 
The @ref{10b,,threading} module API is being changed to use properties
such as @code{daemon} instead of @code{setDaemon()} and
@code{isDaemon()} methods, and some methods have been renamed to use
underscores instead of camel-case; for example, the
@code{activeCount()} method is renamed to @code{active_count()}.  Both
the 2.6 and 3.0 versions of the module support the same properties
and renamed methods, but don't remove the old methods.  No date has been set
for the deprecation of the old APIs in Python 3.x; the old APIs won't
be removed in any 2.x version.
(Carried out by several people, most notably Benjamin Peterson.)

The @ref{10b,,threading} module's @code{Thread} objects
gained an @code{ident} property that returns the thread's
identifier, a nonzero integer.  (Contributed by Gregory P. Smith;
bpo-2871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2871}.)

@item 
The @ref{10d,,timeit} module now accepts callables as well as strings
for the statement being timed and for the setup code.
Two convenience functions were added for creating
@code{Timer} instances:
@code{repeat(stmt, setup, time, repeat, number)} and
@code{timeit(stmt, setup, time, number)} create an instance and call
the corresponding method. (Contributed by Erik Demaine;
bpo-1533909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1533909}.)

@item 
The @code{Tkinter} module now accepts lists and tuples for options,
separating the elements by spaces before passing the resulting value to
Tcl/Tk.
(Contributed by Guilherme Polo; bpo-2906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2906}.)

@item 
The @ref{11f,,turtle} module for turtle graphics was greatly enhanced by
Gregor Lingl.  New features in the module include:


@itemize *

@item 
Better animation of turtle movement and rotation.

@item 
Control over turtle movement using the new @code{delay()},
@code{tracer()}, and @code{speed()} methods.

@item 
The ability to set new shapes for the turtle, and to
define a new coordinate system.

@item 
Turtles now have an @code{undo()} method that can roll back actions.

@item 
Simple support for reacting to input events such as mouse and keyboard
activity, making it possible to write simple games.

@item 
@code{turtle.cfg} 文件可被用来定制海龟绘图屏幕的初始外观。

@item 
The module's docstrings can be replaced by new docstrings that have been
translated into another language.
@end itemize

(bpo-1513695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1513695})

@item 
An optional @code{timeout} parameter was added to the
@code{urllib.urlopen()} function and the
@code{urllib.ftpwrapper} class constructor, as well as the
@code{urllib2.urlopen()} function.  The parameter specifies a timeout
measured in seconds.   For example:

@example
>>> u = urllib2.urlopen("http://slow.example.com",
                        timeout=3)
Traceback (most recent call last):
  ...
urllib2.URLError: <urlopen error timed out>
>>>
@end example

（由 Facundo Batista 添加。）

@item 
The Unicode database provided by the @ref{123,,unicodedata} module
has been updated to version 5.1.0.  (Updated by
Martin von Löwis; bpo-3811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3811}.)

@item 
The @ref{12f,,warnings} module's @code{formatwarning()} and @code{showwarning()}
gained an optional @emph{line} argument that can be used to supply the
line of source code.  (Added as part of bpo-1631171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1631171}, which re-implemented
part of the @ref{12f,,warnings} module in C code.)

A new function, @code{catch_warnings()}, is a context manager
intended for testing purposes that lets you temporarily modify the
warning filters and then restore their original values (bpo-3781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3781}).

@item 
The XML-RPC @code{SimpleXMLRPCServer} and @code{DocXMLRPCServer}
classes can now be prevented from immediately opening and binding to
their socket by passing @code{False} as the @emph{bind_and_activate}
constructor parameter.  This can be used to modify the instance's
@code{allow_reuse_address} attribute before calling the
@code{server_bind()} and @code{server_activate()} methods to
open the socket and begin listening for connections.
(Contributed by Peter Parente; bpo-1599845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1599845}.)

@code{SimpleXMLRPCServer} also has a @code{_send_traceback_header}
attribute; if true, the exception and formatted traceback are returned
as HTTP headers "X-Exception" and "X-Traceback".  This feature is
for debugging purposes only and should not be used on production servers
because the tracebacks might reveal passwords or other sensitive
information.  (Contributed by Alan McIntyre as part of his
project for Google's Summer of Code 2007.)

@item 
The @code{xmlrpclib} module no longer automatically converts
@ref{19d,,datetime.date} and @ref{5f5,,datetime.time} to the
@code{xmlrpclib.DateTime} type; the conversion semantics were
not necessarily correct for all applications.  Code using
@code{xmlrpclib} should convert @code{date} and @ref{5f5,,time}
instances. (bpo-1330538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1330538})  The code can also handle
dates before 1900 (contributed by Ralf Schmitt; bpo-2014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2014})
and 64-bit integers represented by using @code{<i8>} in XML-RPC responses
(contributed by Riku Lindblad; bpo-2985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2985}).

@item 
The @ref{14b,,zipfile} module's @code{ZipFile} class now has
@code{extract()} and @code{extractall()} methods that will unpack
a single file or all the files in the archive to the current directory, or
to a specified directory:

@example
z = zipfile.ZipFile('python-251.zip')

# Unpack a single file, writing it relative
# to the /tmp directory.
z.extract('Python/sysmodule.c', '/tmp')

# Unpack all the files in the archive.
z.extractall()
@end example

（由 Alan McIntyre 在 bpo-467924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=467924} 中贡献。）

The @ref{16f,,open()}, @code{read()} and @code{extract()} methods can now
take either a filename or a @code{ZipInfo} object.  This is useful when an
archive accidentally contains a duplicated filename.
(Contributed by Graham Horler; bpo-1775025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1775025}.)

Finally, @ref{14b,,zipfile} now supports using Unicode filenames
for archived files.  (Contributed by Alexey Borzenkov; bpo-1734346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1734346}.)
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@menu
* ast 模块:: 
* future_builtins 模块:: 
* The json module; JavaScript Object Notation: The json module JavaScript Object Notation. 
* plistlib 模块：属性列表解析器:: 
* ctypes Enhancements:: 
* Improved SSL Support:: 

@end menu

@node ast 模块,future_builtins 模块,,新增和改进的模块<2>
@anchor{whatsnew/2 6 the-ast-module}@anchor{e17}
@subsubsection @code{ast} 模块


The @ref{7,,ast} module provides an Abstract Syntax Tree
representation of Python code, and Armin Ronacher
contributed a set of helper functions that perform a variety of
common tasks.  These will be useful for HTML templating
packages, code analyzers, and similar tools that process
Python code.

The @code{parse()} function takes an expression and returns an AST.
The @code{dump()} function outputs a representation of a tree, suitable
for debugging:

@example
import ast

t = ast.parse("""
d = @{@}
for i in 'abcdefghijklm':
    d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)
@end example

输出是一棵深度嵌套的树:

@example
Module(body=[
  Assign(targets=[
    Name(id='d', ctx=Store())
   ], value=Dict(keys=[], values=[]))
  For(target=Name(id='i', ctx=Store()),
      iter=Str(s='abcdefghijklm'), body=[
    Assign(targets=[
      Subscript(value=
        Name(id='d', ctx=Load()),
          slice=
          Index(value=
            BinOp(left=Name(id='i', ctx=Load()), op=Add(),
             right=Name(id='i', ctx=Load()))), ctx=Store())
     ], value=
     BinOp(left=
      BinOp(left=
       Call(func=
        Name(id='ord', ctx=Load()), args=[
          Name(id='i', ctx=Load())
         ], keywords=[], starargs=None, kwargs=None),
       op=Sub(), right=Call(func=
        Name(id='ord', ctx=Load()), args=[
          Str(s='a')
         ], keywords=[], starargs=None, kwargs=None)),
       op=Add(), right=Num(n=1)))
    ], orelse=[])
   Print(dest=None, values=[
     Name(id='d', ctx=Load())
   ], nl=True)
 ])
@end example

The @code{literal_eval()} method takes a string or an AST
representing a literal expression, parses and evaluates it, and
returns the resulting value.  A literal expression is a Python
expression containing only strings, numbers, dictionaries,
etc. but no statements or function calls.  If you need to
evaluate an expression but cannot accept the security risk of using an
@ref{c6a,,eval()} call, @code{literal_eval()} will handle it safely:

@example
>>> literal = '("a", "b", @{2:4, 3:8, 1:2@})'
>>> print ast.literal_eval(literal)
('a', 'b', @{1: 2, 2: 4, 3: 8@})
>>> print ast.literal_eval('"a" + "b"')
Traceback (most recent call last):
  ...
ValueError: malformed string
@end example

The module also includes @code{NodeVisitor} and
@code{NodeTransformer} classes for traversing and modifying an AST,
and functions for common transformations such as changing line
numbers.

@c ======================================================================

@node future_builtins 模块,The json module JavaScript Object Notation,ast 模块,新增和改进的模块<2>
@anchor{whatsnew/2 6 the-future-builtins-module}@anchor{e18}
@subsubsection @code{future_builtins} 模块


Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can't be introduced in the Python
2.x series because they would break compatibility.
The @code{future_builtins} module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.

The functions in this module currently include:


@itemize *

@item 
@code{ascii(obj)}: equivalent to @ref{8c3,,repr()}.  In Python 3.0,
@ref{8c3,,repr()} will return a Unicode string, while @ref{e19,,ascii()} will
return a pure ASCII bytestring.

@item 
@code{filter(predicate, iterable)},
@code{map(func, iterable1, ...)}: the 3.0 versions
return iterators, unlike the 2.x builtins which return lists.

@item 
@code{hex(value)}, @code{oct(value)}: instead of calling the
@code{__hex__()} or @code{__oct__()} methods, these versions will
call the @ref{2c9,,__index__()} method and convert the result to hexadecimal
or octal.  @ref{d35,,oct()} will use the new @code{0o} notation for its
result.
@end itemize

@c ======================================================================

@node The json module JavaScript Object Notation,plistlib 模块：属性列表解析器,future_builtins 模块,新增和改进的模块<2>
@anchor{whatsnew/2 6 the-json-module-javascript-object-notation}@anchor{e1a}
@subsubsection The @code{json} module: JavaScript Object Notation


The new @ref{a4,,json} module supports the encoding and decoding of Python types in
JSON (Javascript Object Notation). JSON is a lightweight interchange format
often used in web applications. For more information about JSON, see
@indicateurl{http://www.json.org}.

@ref{a4,,json} comes with support for decoding and encoding most built-in Python
types. The following example encodes and decodes a dictionary:

@example
>>> import json
>>> data = @{"spam": "foo", "parrot": 42@}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'@{"parrot": 42, "spam": "foo"@}'
>>> json.loads(in_json) # Decode into a Python object
@{"spam": "foo", "parrot": 42@}
@end example

It's also possible to write your own decoders and encoders to support
more types. Pretty-printing of the JSON strings is also supported.

@ref{a4,,json} (originally called simplejson) was written by Bob
Ippolito.

@c ======================================================================

@node plistlib 模块：属性列表解析器,ctypes Enhancements,The json module JavaScript Object Notation,新增和改进的模块<2>
@anchor{whatsnew/2 6 the-plistlib-module-a-property-list-parser}@anchor{e1b}
@subsubsection @code{plistlib} 模块：属性列表解析器


The @code{.plist} format is commonly used on Mac OS X to
store basic data types (numbers, strings, lists,
and dictionaries) by serializing them into an XML-based format.
It resembles the XML-RPC serialization of data types.

Despite being primarily used on Mac OS X, the format
has nothing Mac-specific about it and the Python implementation works
on any platform that Python supports, so the @ref{cf,,plistlib} module
has been promoted to the standard library.

Using the module is simple:

@example
import sys
import plistlib
import datetime

# Create data structure
data_struct = dict(lastAccessed=datetime.datetime.now(),
                   version=1,
                   categories=('Personal','Shared','Private'))

# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)
new_struct = plistlib.readPlistFromString(plist_str)
print data_struct
print new_struct

# Write data structure to a file and read it back.
plistlib.writePlist(data_struct, '/tmp/customizations.plist')
new_struct = plistlib.readPlist('/tmp/customizations.plist')

# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)
@end example

@c ======================================================================

@node ctypes Enhancements,Improved SSL Support,plistlib 模块：属性列表解析器,新增和改进的模块<2>
@anchor{whatsnew/2 6 ctypes-enhancements}@anchor{e1c}
@subsubsection ctypes Enhancements


Thomas Heller continued to maintain and enhance the
@ref{2a,,ctypes} module.

@ref{2a,,ctypes} now supports a @code{c_bool} datatype
that represents the C99 @code{bool} type.  (Contributed by David Remahl;
bpo-1649190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1649190}.)

The @ref{2a,,ctypes} string, buffer and array types have improved
support for extended slicing syntax,
where various combinations of @code{(start, stop, step)} are supplied.
(Implemented by Thomas Wouters.)

@c Revision 57769

All @ref{2a,,ctypes} data types now support
@code{from_buffer()} and @code{from_buffer_copy()}
methods that create a ctypes instance based on a
provided buffer object.  @code{from_buffer_copy()} copies
the contents of the object,
while @code{from_buffer()} will share the same memory area.

A new calling convention tells @ref{2a,,ctypes} to clear the @code{errno} or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; bpo-1798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1798}.)

You can now retrieve the Unix @code{errno} variable after a function
call.  When creating a wrapped function, you can supply
@code{use_errno=True} as a keyword parameter to the @code{DLL()} function
and then call the module-level methods @code{set_errno()} and
@code{get_errno()} to set and retrieve the error value.

The Win32 LastError variable is similarly supported by
the @code{DLL()}, @code{OleDLL()}, and @code{WinDLL()} functions.
You supply @code{use_last_error=True} as a keyword parameter
and then call the module-level methods @code{set_last_error()}
and @code{get_last_error()}.

The @code{byref()} function, used to retrieve a pointer to a ctypes
instance, now has an optional @emph{offset} parameter that is a byte
count that will be added to the returned pointer.

@c ======================================================================

@node Improved SSL Support,,ctypes Enhancements,新增和改进的模块<2>
@anchor{whatsnew/2 6 improved-ssl-support}@anchor{e1d}
@subsubsection Improved SSL Support


Bill Janssen made extensive improvements to Python 2.6's support for
the Secure Sockets Layer by adding a new module, @ref{f3,,ssl}, that's
built atop the OpenSSL@footnote{https://www.openssl.org/} library.
This new module provides more control over the protocol negotiated,
the X.509 certificates used, and has better support for writing SSL
servers (as opposed to clients) in Python.  The existing SSL support
in the @ref{ef,,socket} module hasn't been removed and continues to work,
though it will be removed in Python 3.0.

To use the new module, you must first create a TCP connection in the
usual way and then pass it to the @ref{579,,ssl.wrap_socket()} function.
It's possible to specify whether a certificate is required, and to
obtain certificate info by calling the @code{getpeercert()} method.


@subsubheading 参见


@ref{f3,,ssl} 模块的文档。


@c ======================================================================

@node Deprecations and Removals,构建和 C API 的改变<9>,新增和改进的模块<2>,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 deprecations-and-removals}@anchor{e1e}
@subsection Deprecations and Removals



@itemize *

@item 
String exceptions have been removed.  Attempting to use them raises a
@ref{1ff,,TypeError}.

@item 
Changes to the @ref{2e3,,Exception} interface
as dictated by 
@geindex Python 提高建议; PEP 352
PEP 352@footnote{https://www.python.org/dev/peps/pep-0352} continue to be made.  For 2.6,
the @code{message} attribute is being deprecated in favor of the
@code{args} attribute.

@item 
(3.0-warning mode) Python 3.0 will feature a reorganized standard
library that will drop many outdated modules and rename others.
Python 2.6 running in 3.0-warning mode will warn about these modules
when they are imported.

The list of deprecated modules is:
@code{audiodev},
@code{bgenlocations},
@code{buildtools},
@code{bundlebuilder},
@code{Canvas},
@code{compiler},
@code{dircache},
@code{dl},
@code{fpformat},
@code{gensuitemodule},
@code{ihooks},
@code{imageop},
@code{imgfile},
@code{linuxaudiodev},
@code{mhlib},
@code{mimetools},
@code{multifile},
@code{new},
@code{pure},
@code{statvfs},
@code{sunaudiodev},
@code{test.testall}, and
@code{toaiff}.

@item 
@code{gopherlib} 模块已被移除。

@item 
The @code{MimeWriter} module and @code{mimify} module
have been deprecated; use the @ref{67,,email}
package instead.

@item 
The @code{md5} module has been deprecated; use the @ref{8c,,hashlib} module
instead.

@item 
The @code{posixfile} module has been deprecated; @ref{e1f,,fcntl.lockf()}
provides better locking.

@item 
The @code{popen2} module has been deprecated; use the @ref{f9,,subprocess}
module.

@item 
@code{rgbimg} 模块已被移除。

@item 
The @code{sets} module has been deprecated; it's better to
use the built-in @ref{1f7,,set} and @ref{1f8,,frozenset} types.

@item 
The @code{sha} module has been deprecated; use the @ref{8c,,hashlib} module
instead.
@end itemize

@c ======================================================================

@node 构建和 C API 的改变<9>,移植到Python 2 6,Deprecations and Removals,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 build-and-c-api-changes}@anchor{e20}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
Python now must be compiled with C89 compilers (after 19
years!).  This means that the Python source tree has dropped its
own implementations of @code{memmove()} and @code{strerror()}, which
are in the C89 standard library.

@item 
Python 2.6 can be built with Microsoft Visual Studio 2008 (version
9.0), and this is the new default compiler.  See the
@code{PCbuild} directory for the build files.  (Implemented by
Christian Heimes.)

@item 
On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
The @code{configure} script
can take a @code{--with-universal-archs=[32-bit|64-bit|all]}
switch, controlling whether the binaries are built for 32-bit
architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
(Contributed by Ronald Oussoren.)

@item 
The BerkeleyDB module now has a C API object, available as
@code{bsddb.db.api}.   This object can be used by other C extensions
that wish to use the @code{bsddb} module for their own purposes.
(Contributed by Duncan Grisby.)

@item 
The new buffer interface, previously described in
@ref{df2,,the PEP 3118 section},
adds @ref{df3,,PyObject_GetBuffer()} and @ref{e21,,PyBuffer_Release()},
as well as a few other functions.

@item 
Python's use of the C stdio library is now thread-safe, or at least
as thread-safe as the underlying library is.  A long-standing potential
bug occurred if one thread closed a file object while another thread
was reading from or writing to the object.  In 2.6 file objects
have a reference count, manipulated by the
@code{PyFile_IncUseCount()} and @code{PyFile_DecUseCount()}
functions.  File objects can't be closed unless the reference count
is zero.  @code{PyFile_IncUseCount()} should be called while the GIL
is still held, before carrying out an I/O operation using the
@code{FILE *} pointer, and @code{PyFile_DecUseCount()} should be called
immediately after the GIL is re-acquired.
(Contributed by Antoine Pitrou and Gregory P. Smith.)

@item 
Importing modules simultaneously in two different threads no longer
deadlocks; it will now raise an @ref{16c,,ImportError}.  A new API
function, @ref{aa9,,PyImport_ImportModuleNoBlock()}, will look for a
module in @code{sys.modules} first, then try to import it after
acquiring an import lock.  If the import lock is held by another
thread, an @ref{16c,,ImportError} is raised.
(Contributed by Christian Heimes.)

@item 
Several functions return information about the platform's
floating-point support.  @ref{e22,,PyFloat_GetMax()} returns
the maximum representable floating point value,
and @ref{e23,,PyFloat_GetMin()} returns the minimum
positive value.  @ref{e24,,PyFloat_GetInfo()} returns an object
containing more information from the @code{float.h} file, such as
@code{"mant_dig"} (number of digits in the mantissa), @code{"epsilon"}
(smallest difference between 1.0 and the next largest value
representable), and several others.
(Contributed by Christian Heimes; bpo-1534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1534}.)

@item 
C functions and methods that use
@ref{e25,,PyComplex_AsCComplex()} will now accept arguments that
have a @ref{2cc,,__complex__()} method.  In particular, the functions in the
@ref{18,,cmath} module will now accept objects with this method.
This is a backport of a Python 3.0 change.
(Contributed by Mark Dickinson; bpo-1675423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1675423}.)

@item 
Python's C API now includes two functions for case-insensitive string
comparisons, @code{PyOS_stricmp(char*, char*)}
and @code{PyOS_strnicmp(char*, char*, Py_ssize_t)}.
(Contributed by Christian Heimes; bpo-1635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635}.)

@item 
Many C extensions define their own little macro for adding
integers and strings to the module's dictionary in the
@code{init*} function.  Python 2.6 finally defines standard macros
for adding values to a module, @ref{e26,,PyModule_AddStringMacro}
and @code{PyModule_AddIntMacro()}.  (Contributed by
Christian Heimes.)

@item 
Some macros were renamed in both 3.0 and 2.6 to make it clearer that
they are macros,
not functions.  @code{Py_Size()} became @code{Py_SIZE()},
@code{Py_Type()} became @code{Py_TYPE()}, and
@code{Py_Refcnt()} became @code{Py_REFCNT()}.
The mixed-case macros are still available
in Python 2.6 for backward compatibility.
(bpo-1629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1629})

@item 
Distutils now places C extensions it builds in a
different directory when running on a debug version of Python.
(Contributed by Collin Winter; bpo-1530959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1530959}.)

@item 
Several basic data types, such as integers and strings, maintain
internal free lists of objects that can be re-used.  The data
structures for these free lists now follow a naming convention: the
variable is always named @code{free_list}, the counter is always named
@code{numfree}, and a macro @code{Py<typename>_MAXFREELIST} is
always defined.

@item 
A new Makefile target, "make patchcheck", prepares the Python source tree
for making a patch: it fixes trailing whitespace in all modified
@code{.py} files, checks whether the documentation has been changed,
and reports whether the @code{Misc/ACKS} and @code{Misc/NEWS} files
have been updated.
(Contributed by Brett Cannon.)

Another new target, "make profile-opt", compiles a Python binary
using GCC's profile-guided optimization.  It compiles Python with
profiling enabled, runs the test suite to obtain a set of profiling
results, and then compiles using these results for optimization.
(Contributed by Gregory P. Smith.)
@end itemize

@c ======================================================================

@menu
* 特定于 Windows 的更改：: 特定于 Windows 的更改：<2>. 
* 特定于 Mac OS X 的更改：Mac OS X:: 
* 特定于 IRIX 的更改：:: 

@end menu

@node 特定于 Windows 的更改：<2>,特定于 Mac OS X 的更改：Mac OS X,,构建和 C API 的改变<9>
@anchor{whatsnew/2 6 port-specific-changes-windows}@anchor{e27}
@subsubsection 特定于 Windows 的更改：



@itemize *

@item 
The support for Windows 95, 98, ME and NT4 has been dropped.
Python 2.6 requires at least Windows 2000 SP4.

@item 
The new default compiler on Windows is Visual Studio 2008 (version
9.0). The build directories for Visual Studio 2003 (version 7.1) and
2005 (version 8.0) were moved into the PC/ directory. The new
@code{PCbuild} directory supports cross compilation for X64, debug
builds and Profile Guided Optimization (PGO). PGO builds are roughly
10% faster than normal builds.  (Contributed by Christian Heimes
with help from Amaury Forgeot d'Arc and Martin von Löwis.)

@item 
The @ref{b6,,msvcrt} module now supports
both the normal and wide char variants of the console I/O
API.  The @code{getwch()} function reads a keypress and returns a Unicode
value, as does the @code{getwche()} function.  The @code{putwch()} function
takes a Unicode character and writes it to the console.
(Contributed by Christian Heimes.)

@item 
@ref{e11,,os.path.expandvars()} will now expand environment variables in
the form "%var%", and "~user" will be expanded into the user's home
directory path.  (Contributed by Josiah Carlson; bpo-957650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=957650}.)

@item 
The @ref{ef,,socket} module's socket objects now have an
@code{ioctl()} method that provides a limited interface to the
@code{WSAIoctl()} system interface.

@item 
The @code{_winreg} module now has a function,
@code{ExpandEnvironmentStrings()},
that expands environment variable references such as @code{%NAME%}
in an input string.  The handle objects provided by this
module now support the context protocol, so they can be used
in @ref{7e4,,with} statements. (Contributed by Christian Heimes.)

@code{_winreg} also has better support for x64 systems,
exposing the @code{DisableReflectionKey()}, @code{EnableReflectionKey()},
and @code{QueryReflectionKey()} functions, which enable and disable
registry reflection for 32-bit processes running on 64-bit systems.
(bpo-1753245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1753245})

@item 
The @ref{b5,,msilib} module's @code{Record} object
gained @code{GetInteger()} and @code{GetString()} methods that
return field values as an integer or a string.
(Contributed by Floris Bruynooghe; bpo-2125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2125}.)
@end itemize

@c ======================================================================

@node 特定于 Mac OS X 的更改：Mac OS X,特定于 IRIX 的更改：,特定于 Windows 的更改：<2>,构建和 C API 的改变<9>
@anchor{whatsnew/2 6 port-specific-changes-mac-os-x}@anchor{e28}
@subsubsection 特定于 Mac OS X 的更改：Mac OS X



@itemize *

@item 
现在，在编译Python的框架版本时，可以为 @code{configure} 脚本添加 @code{--with-framework-name=} 选项来指定要使用的框架名称。

@item 
@code{macfs} 模块已被删除。这反过来要求删除 @code{macostools.touched()} 函数，因为它依赖于 @code{macfs} 模块。 (bpo-1490190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1490190})

@item 
许多其他 Mac OS 模块已弃用并将在 Python 3.0 中被删除: @code{_builtinSuites}, @code{aepack}, @code{aetools}, @code{aetypes}, @code{applesingle}, @code{appletrawmain}, @code{appletrunner}, @code{argvemulator}, @code{Audio_mac}, @code{autoGIL}, @code{Carbon}, @code{cfmfile}, @code{CodeWarrior}, @code{ColorPicker}, @code{EasyDialogs}, @code{Explorer}, @code{Finder}, @code{FrameWork}, @code{findertools}, @code{ic}, @code{icglue}, @code{icopen}, @code{macerrors}, @code{MacOS}, @code{macfs}, @code{macostools}, @code{macresource}, @code{MiniAEFrame}, @code{Nav}, @code{Netscape}, @code{OSATerminology}, @code{pimp}, @code{PixMapWrapper}, @code{StdSuites}, @code{SystemEvents}, @code{Terminal} 和 @code{terminalcommand}。
@end itemize

@c ======================================================================

@node 特定于 IRIX 的更改：,,特定于 Mac OS X 的更改：Mac OS X,构建和 C API 的改变<9>
@anchor{whatsnew/2 6 port-specific-changes-irix}@anchor{e29}
@subsubsection 特定于 IRIX 的更改：


许多旧的 IRIX 专用模块已被弃用，并将在Python 3.0中删除： @code{al} 和 @code{AL}, @code{cd}, @code{cddb}, @code{cdplayer}, @code{CL} 和 @code{cl}, @code{DEVICE}, @code{ERRNO}, @code{FILE}, @code{FL} 和 @code{fl}, @code{flp}, @code{fm}, @code{GET}, @code{GLWS}, @code{GL} 和 @code{gl}, @code{IN}, @code{IOCTL}, @code{jpeg}, @code{panelparser}, @code{readcd}, @code{SV} 和 @code{sv}, @code{torgb}, @code{videoreader}, 和 @code{WAIT}.

@c ======================================================================

@node 移植到Python 2 6,致谢<2>,构建和 C API 的改变<9>,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 porting-to-python-2-6}@anchor{e2a}
@subsection 移植到Python 2.6


This section lists previously described changes and other bugfixes
that may require changes to your code:


@itemize *

@item 
Classes that aren't supposed to be hashable should
set @code{__hash__ = None} in their definitions to indicate
the fact.

@item 
String exceptions have been removed.  Attempting to use them raises a
@ref{1ff,,TypeError}.

@item 
The @ref{e2b,,__init__()} method of @ref{633,,collections.deque}
now clears any existing contents of the deque
before adding elements from the iterable.  This change makes the
behavior match @code{list.__init__()}.

@item 
@ref{e2b,,object.__init__()} previously accepted arbitrary arguments and
keyword arguments, ignoring them.  In Python 2.6, this is no longer
allowed and will result in a @ref{1ff,,TypeError}.  This will affect
@ref{e2b,,__init__()} methods that end up calling the corresponding
method on @ref{3da,,object} (perhaps through using @ref{5e6,,super()}).
See bpo-1683368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1683368} for discussion.

@item 
The @code{Decimal} constructor now accepts leading and trailing
whitespace when passed a string.  Previously it would raise an
@code{InvalidOperation} exception.  On the other hand, the
@code{create_decimal()} method of @code{Context} objects now
explicitly disallows extra whitespace, raising a
@code{ConversionSyntax} exception.

@item 
Due to an implementation accident, if you passed a file path to
the built-in  @ref{16b,,__import__()} function, it would actually import
the specified file.  This was never intended to work, however, and
the implementation now explicitly checks for this case and raises
an @ref{16c,,ImportError}.

@item 
C API: the @ref{e2c,,PyImport_Import()} and @ref{d43,,PyImport_ImportModule()}
functions now default to absolute imports, not relative imports.
This will affect C extensions that import other modules.

@item 
C API: extension data types that shouldn't be hashable
should define their @code{tp_hash} slot to
@ref{dff,,PyObject_HashNotImplemented()}.

@item 
The @ref{ef,,socket} module exception @ref{a7f,,socket.error} now inherits
from @ref{a7c,,IOError}.  Previously it wasn't a subclass of
@code{StandardError} but now it is, through @ref{a7c,,IOError}.
(Implemented by Gregory P. Smith; bpo-1706815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1706815}.)

@item 
The @code{xmlrpclib} module no longer automatically converts
@ref{19d,,datetime.date} and @ref{5f5,,datetime.time} to the
@code{xmlrpclib.DateTime} type; the conversion semantics were
not necessarily correct for all applications.  Code using
@code{xmlrpclib} should convert @code{date} and @ref{5f5,,time}
instances. (bpo-1330538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1330538})

@item 
(3.0-warning mode) The @ref{2e3,,Exception} class now warns
when accessed using slicing or index access; having
@ref{2e3,,Exception} behave like a tuple is being phased out.

@item 
(3.0-warning mode) inequality comparisons between two dictionaries
or two objects that don't implement comparison methods are reported
as warnings.  @code{dict1 == dict2} still works, but @code{dict1 < dict2}
is being phased out.

Comparisons between cells, which are an implementation detail of Python's
scoping rules, also cause warnings because such comparisons are forbidden
entirely in 3.0.
@end itemize

@c ======================================================================

@node 致谢<2>,,移植到Python 2 6,Python 2 6 有什么新变化
@anchor{whatsnew/2 6 acknowledgements}@anchor{e2d}@anchor{whatsnew/2 6 acks}@anchor{e2e}
@subsection 致谢


作者感谢以下人员对本文各种草稿给予的建议，更正和协助： Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher,  Martin Michlmayr, Antoine Pitrou, Brian Warner.

@node Python 2 5 有什么新变化,Python 2 4 有什么新变化,Python 2 6 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 5 doc}@anchor{e2f}@anchor{whatsnew/2 5 what-s-new-in-python-2-5}@anchor{e30}
@section Python 2.5 有什么新变化


@*作者: 
A.M. Kuchling


@c $Id: whatsnew25.tex 56611 2007-07-29 08:26:10Z georg.brandl $

@c Fix XXX comments

This article explains the new features in Python 2.5.  The final release of
Python 2.5 is scheduled for August 2006; 
@geindex Python 提高建议; PEP 356
PEP 356@footnote{https://www.python.org/dev/peps/pep-0356} describes the planned
release schedule.

The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python's user
community, I think, because several widely-useful packages were added.  New
modules include ElementTree for XML processing (@code{xml.etree}),
the SQLite database module (@code{sqlite}), and the @ref{2a,,ctypes}
module for calling C functions.

The language changes are of middling significance.  Some pleasant new features
were added, but most of them aren't features that you'll use every day.
Conditional expressions were finally added to the language using a novel syntax;
see section @ref{e31,,PEP 308; 条件表达式}.  The new '@ref{7e4,,with}' statement will make
writing cleanup code easier (section @ref{e32,,PEP 343; "with" 语句}).  Values can now be passed
into generators (section @ref{e33,,PEP 342; 生成器的新特性}).  Imports are now visible as either
absolute or relative (section @ref{e34,,PEP 328; 绝对导入和相对导入}).  Some corner cases of exception
handling are handled better (section @ref{e35,,PEP 341; 统一 try/except/finally}).  All these improvements
are worthwhile, but they're improvements to one specific language feature or
another; none of them are broad modifications to Python's semantics.

As well as the language and library additions, other improvements and bugfixes
were made throughout the source tree.  A search through the SVN change logs
finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
2.5.  (Both figures are likely to be underestimates.)

This article doesn't try to be a complete specification of the new features;
instead changes are briefly introduced using helpful examples.  For full
details, you should always refer to the documentation for Python 2.5 at
@indicateurl{https://docs.python.org}. If you want to understand the complete implementation
and design rationale, refer to the PEP for a particular new feature.

Comments, suggestions, and error reports for this document are welcome; please
e-mail them to the author or open a bug in the Python bug tracker.

@c ======================================================================

@menu
* PEP 308; 条件表达式: PEP 308 条件表达式. 
* PEP 309; 部分功能应用: PEP 309 部分功能应用. 
* PEP 314; Python软件包的元数据 v1.1: PEP 314 Python软件包的元数据 v1 1. 
* PEP 328; 绝对导入和相对导入: PEP 328 绝对导入和相对导入. 
* PEP 338; 将模块作为脚本执行: PEP 338 将模块作为脚本执行. 
* PEP 341; 统一 try/except/finally: PEP 341 统一 try/except/finally. 
* PEP 342; 生成器的新特性: PEP 342 生成器的新特性. 
* PEP 343; "with" 语句: PEP 343 "with" 语句<2>. 
* PEP 352; 异常作为新型的类: PEP 352 异常作为新型的类. 
* PEP 353; 使用ssize_t作为索引类型: PEP 353 使用ssize_t作为索引类型. 
* PEP 357; '__index__' 方法: PEP 357 '__index__' 方法. 
* 其他语言特性修改: 其他语言特性修改<12>. 
* 新增，改进和删除的模块:: 
* 构建和 C API 的改变: 构建和 C API 的改变<10>. 
* 移植到Python 2.5: 移植到Python 2 5. 
* 致谢: 致谢<3>. 

@end menu

@node PEP 308 条件表达式,PEP 309 部分功能应用,,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-308}@anchor{e31}@anchor{whatsnew/2 5 pep-308-conditional-expressions}@anchor{e36}
@subsection PEP 308: 条件表达式


For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B depending on
whether a Boolean value is true or false.  A conditional expression lets you
write a single assignment statement that has the same effect as the following:

@example
if condition:
    x = true_value
else:
    x = false_value
@end example

There have been endless tedious discussions of syntax on both python-dev and
comp.lang.python.  A vote was even held that found the majority of voters wanted
conditional expressions in some form, but there was no syntax that was preferred
by a clear majority. Candidates included C's @code{cond ? true_v : false_v}, @code{if
cond then true_v else false_v}, and 16 other variations.

Guido van Rossum 最终选择了一种令人惊讶的语法：

@example
x = true_value if condition else false_value
@end example

Evaluation is still lazy as in existing Boolean expressions, so the order of
evaluation jumps around a bit.  The @emph{condition} expression in the middle is
evaluated first, and the @emph{true_value} expression is evaluated only if the
condition was true.  Similarly, the @emph{false_value} expression is only evaluated
when the condition is false.

This syntax may seem strange and backwards; why does the condition go in the
@emph{middle} of the expression, and not in the front as in C's @code{c ? x : y}?  The
decision was checked by applying the new syntax to the modules in the standard
library and seeing how the resulting code read.  In many cases where a
conditional expression is used, one value seems to be the 'common case' and one
value is an 'exceptional case', used only on rarer occasions when the condition
isn't met.  The conditional syntax makes this pattern a bit more obvious:

@example
contents = ((doc + '\n') if doc else '@w{'})
@end example

I read the above statement as meaning "here @emph{contents} is  usually assigned a
value of @code{doc+'\n'}; sometimes  @emph{doc} is empty, in which special case an empty
string is returned."   I doubt I will use conditional expressions very often
where there  isn't a clear common and uncommon case.

There was some discussion of whether the language should require surrounding
conditional expressions with parentheses.  The decision was made to @emph{not}
require parentheses in the Python language's grammar, but as a matter of style I
think you should always use them. Consider these two statements:

@example
# First version -- no parens
level = 1 if logging else 0

# Second version -- with parens
level = (1 if logging else 0)
@end example

In the first version, I think a reader's eye might group the statement into
'level = 1', 'if logging', 'else 0', and think that the condition decides
whether the assignment to @emph{level} is performed.  The second version reads
better, in my opinion, because it makes it clear that the assignment is always
performed and the choice is being made between two values.

Another reason for including the brackets: a few odd combinations of list
comprehensions and lambdas could look like incorrect conditional expressions.
See 
@geindex Python 提高建议; PEP 308
PEP 308@footnote{https://www.python.org/dev/peps/pep-0308} for some examples.  If you put parentheses around your
conditional expressions, you won't run into this case.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 308

@item PEP 308@footnote{https://www.python.org/dev/peps/pep-0308} - 条件表达式

PEP 由 Guido van Rossum 和 Raymond D 撰写，由 Thomas Wouters 实现。
@end table


@c ======================================================================

@node PEP 309 部分功能应用,PEP 314 Python软件包的元数据 v1 1,PEP 308 条件表达式,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-309}@anchor{e37}@anchor{whatsnew/2 5 pep-309-partial-function-application}@anchor{e38}
@subsection PEP 309: 部分功能应用


@ref{83,,functools} 模块旨在包含用于函数式编程风格的工具。

One useful tool in this module is the @code{partial()} function. For programs
written in a functional style, you'll sometimes want to construct variants of
existing functions that have some of the parameters filled in.  Consider a
Python function @code{f(a, b, c)}; you could create a new function @code{g(b, c)} that
was equivalent to @code{f(1, b, c)}.  This is called "partial function
application".

@code{partial()} takes the arguments @code{(function, arg1, arg2, ... kwarg1=value1,
kwarg2=value2)}.  The resulting object is callable, so you can just call it to
invoke @emph{function} with the filled-in arguments.

这里有一个很小但很现实的例子:

@example
import functools

def log (message, subsystem):
    "Write the contents of 'message' to the specified subsystem."
    print '%s: %s' % (subsystem, message)
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
@end example

Here's another example, from a program that uses PyGTK.  Here a context-sensitive
pop-up menu is being constructed dynamically.  The callback provided
for the menu option is a partially applied version of the @code{open_item()}
method, where the first argument has been provided.

@example
...
class Application:
    def open_item(self, path):
       ...
    def init (self):
        open_func = functools.partial(self.open_item, item_path)
        popup_menu.append( ("Open", open_func, 1) )
@end example

Another function in the @ref{83,,functools} module is the
@code{update_wrapper(wrapper, wrapped)} function that helps you write
well-behaved decorators.  @code{update_wrapper()} copies the name, module, and
docstring attribute to a wrapper function so that tracebacks inside the wrapped
function are easier to understand.  For example, you might write:

@example
def my_decorator(f):
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    functools.update_wrapper(wrapper, f)
    return wrapper
@end example

@code{wraps()} is a decorator that can be used inside your own decorators to copy
the wrapped function's information.  An alternate  version of the previous
example would be:

@example
def my_decorator(f):
    @@functools.wraps(f)
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    return wrapper
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 309

@item PEP 309@footnote{https://www.python.org/dev/peps/pep-0309} - 部分函数应用

PEP由 Peter Harris 提出并撰写；由 Hye-Shik Chang 和 Nick Coghlan 实现，并由 Raymond Hettinger 适配。
@end table


@c ======================================================================

@node PEP 314 Python软件包的元数据 v1 1,PEP 328 绝对导入和相对导入,PEP 309 部分功能应用,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-314}@anchor{e39}@anchor{whatsnew/2 5 pep-314-metadata-for-python-software-packages-v1-1}@anchor{e3a}
@subsection PEP 314: Python软件包的元数据 v1.1


Some simple dependency support was added to Distutils.  The @code{setup()}
function now has @code{requires}, @code{provides}, and @code{obsoletes} keyword
parameters.  When you build a source distribution using the @code{sdist} command,
the dependency information will be recorded in the @code{PKG-INFO} file.

Another new keyword parameter is @code{download_url}, which should be set to a URL
for the package's source code.  This means it's now possible to look up an entry
in the package index, determine the dependencies for a package, and download the
required packages.

@example
VERSION = '1.0'
setup(name='PyPackage',
      version=VERSION,
      requires=['numarray', 'zlib (>=1.1.4)'],
      obsoletes=['OldPackage']
      download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
                    % VERSION),
     )
@end example

Another new enhancement to the Python package index at
@indicateurl{https://pypi.org} is storing source and binary archives for a
package.  The new @code{upload} Distutils command will upload a package to
the repository.

Before a package can be uploaded, you must be able to build a distribution using
the @code{sdist} Distutils command.  Once that works, you can run @code{python
setup.py upload} to add your package to the PyPI archive.  Optionally you can
GPG-sign the package by supplying the @code{--sign} and @code{--identity}
options.

包上传操作由 Martin von Löwis 和 Richard Jones 实现。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 314

@item PEP 314@footnote{https://www.python.org/dev/peps/pep-0314} - Python软件包的元数据 v1.1

PEP 由 A.M. Kuchling, Richard Jones 和 Fred Drake 提出并撰写，由 Richard Jones 和 Fred Drake 实现
@end table


@c ======================================================================

@node PEP 328 绝对导入和相对导入,PEP 338 将模块作为脚本执行,PEP 314 Python软件包的元数据 v1 1,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-328}@anchor{e34}@anchor{whatsnew/2 5 pep-328-absolute-and-relative-imports}@anchor{e3b}
@subsection PEP 328: 绝对导入和相对导入


The simpler part of 
@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328} was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the @code{from ... import
...} statement, making it easier to import many different names.

The more complicated part has been implemented in Python 2.5: importing a module
can be specified to use absolute or package-relative imports.  The plan is to
move toward making absolute imports the default in future versions of Python.

Let's say you have a package directory like this:

@example
pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py
@end example

This defines a package named @code{pkg} containing the @code{pkg.main} and
@code{pkg.string} submodules.

Consider the code in the @code{main.py} module.  What happens if it executes
the statement @code{import string}?  In Python 2.4 and earlier, it will first look
in the package's directory to perform a relative import, finds
@code{pkg/string.py}, imports the contents of that file as the
@code{pkg.string} module, and that module is bound to the name @code{string} in the
@code{pkg.main} module's namespace.

That's fine if @code{pkg.string} was what you wanted.  But what if you wanted
Python's standard @ref{f6,,string} module?  There's no clean way to ignore
@code{pkg.string} and look for the standard module; generally you had to look at
the contents of @code{sys.modules}, which is slightly unclean.    Holger Krekel's
@code{py.std} package provides a tidier way to perform imports from the standard
library, @code{import py; py.std.string.join()}, but that package isn't available
on all Python installations.

Reading code which relies on relative imports is also less clear, because a
reader may be confused about which module, @ref{f6,,string} or @code{pkg.string},
is intended to be used.  Python users soon learned not to duplicate the names of
standard library modules in the names of their packages' submodules, but you
can't protect against having your submodule's name being used for a new module
added in a future version of Python.

In Python 2.5, you can switch @ref{cef,,import}'s behaviour to  absolute imports
using a @code{from __future__ import absolute_import} directive.  This absolute-import
behaviour will become the default in a future version (probably Python
2.7).  Once absolute imports  are the default, @code{import string} will always
find the standard library's version. It's suggested that users should begin
using absolute imports as much as possible, so it's preferable to begin writing
@code{from pkg import string} in your code.

Relative imports are still possible by adding a leading period  to the module
name when using the @code{from ... import} form:

@example
# Import names from pkg.string
from .string import name1, name2
# Import pkg.string
from . import string
@end example

This imports the @ref{f6,,string} module relative to the current package, so in
@code{pkg.main} this will import @emph{name1} and @emph{name2} from @code{pkg.string}.
Additional leading periods perform the relative import starting from the parent
of the current package.  For example, code in the @code{A.B.C} module can do:

@example
from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G
@end example

Leading periods cannot be used with the @code{import modname}  form of the import
statement, only the @code{from ... import} form.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 328

@item PEP 328@footnote{https://www.python.org/dev/peps/pep-0328} - 导入：多行和绝对/相对导入

PEP 由 Aahz 撰写，由 Thomas Wouters 实现。

@item @indicateurl{https://pylib.readthedocs.io/}

由 Holger Krekel 编写 py 库，其中包含 @code{py.std} 包。
@end table


@c ======================================================================

@node PEP 338 将模块作为脚本执行,PEP 341 统一 try/except/finally,PEP 328 绝对导入和相对导入,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-338}@anchor{e3c}@anchor{whatsnew/2 5 pep-338-executing-modules-as-scripts}@anchor{e3d}
@subsection PEP 338: 将模块作为脚本执行


The @ref{44c,,-m} switch added in Python 2.4 to execute a module as a script
gained a few more abilities.  Instead of being implemented in C code inside the
Python interpreter, the switch now uses an implementation in a new module,
@ref{e2,,runpy}.

The @ref{e2,,runpy} module implements a more sophisticated import mechanism so that
it's now possible to run modules in a package such as @code{pychecker.checker}.
The module also supports alternative import mechanisms such as the
@ref{14c,,zipimport} module.  This means you can add a .zip archive's path to
@code{sys.path} and then use the @ref{44c,,-m} switch to execute code from the
archive.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 338

@item PEP 338@footnote{https://www.python.org/dev/peps/pep-0338} - 将模块作为脚本执行

PEP 由 Nick Coghlan 撰写并实现。
@end table


@c ======================================================================

@node PEP 341 统一 try/except/finally,PEP 342 生成器的新特性,PEP 338 将模块作为脚本执行,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-341}@anchor{e35}@anchor{whatsnew/2 5 pep-341-unified-try-except-finally}@anchor{e3e}
@subsection PEP 341: 统一 try/except/finally


Until Python 2.5, the @ref{e3f,,try} statement came in two flavours. You could
use a @ref{2c3,,finally} block to ensure that code is always executed, or one or
more @ref{c19,,except} blocks to catch  specific exceptions.  You couldn't
combine both @code{except} blocks and a @code{finally} block, because
generating the right bytecode for the combined version was complicated and it
wasn't clear what the semantics of the combined statement should be.

Guido van Rossum spent some time working with Java, which does support the
equivalent of combining @ref{c19,,except} blocks and a @ref{2c3,,finally} block,
and this clarified what the statement should mean.  In Python 2.5, you can now
write:

@example
try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block
@end example

The code in @emph{block-1} is executed.  If the code raises an exception, the various
@ref{c19,,except} blocks are tested: if the exception is of class
@code{Exception1}, @emph{handler-1} is executed; otherwise if it's of class
@code{Exception2}, @emph{handler-2} is executed, and so forth.  If no exception is
raised, the @emph{else-block} is executed.

No matter what happened previously, the @emph{final-block} is executed once the code
block is complete and any raised exceptions handled. Even if there's an error in
an exception handler or the @emph{else-block} and a new exception is raised, the code
in the @emph{final-block} is still run.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 341

@item PEP 341@footnote{https://www.python.org/dev/peps/pep-0341} - 统一 try-except 和 try-finally

PEP 由 Georg Brandl 撰写，由 Thomas Lee 实现。
@end table


@c ======================================================================

@node PEP 342 生成器的新特性,PEP 343 "with" 语句<2>,PEP 341 统一 try/except/finally,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-342}@anchor{e33}@anchor{whatsnew/2 5 pep-342-new-generator-features}@anchor{e40}
@subsection PEP 342: 生成器的新特性


Python 2.5 adds a simple way to pass values @emph{into} a generator. As introduced in
Python 2.3, generators only produce output; once a generator's code was invoked
to create an iterator, there was no way to pass any new information into the
function when its execution is resumed.  Sometimes the ability to pass in some
information would be useful.  Hackish solutions to this include making the
generator's code look at a global variable and then changing the global
variable's value, or passing in some mutable object that callers then modify.

To refresh your memory of basic generators, here's a simple example:

@example
def counter (maximum):
    i = 0
    while i < maximum:
        yield i
        i += 1
@end example

When you call @code{counter(10)}, the result is an iterator that returns the values
from 0 up to 9.  On encountering the @ref{2ce,,yield} statement, the iterator
returns the provided value and suspends the function's execution, preserving the
local variables. Execution resumes on the following call to the iterator's
@ref{77f,,next()} method, picking up after the @code{yield} statement.

In Python 2.3, @ref{2ce,,yield} was a statement; it didn't return any value.  In
2.5, @code{yield} is now an expression, returning a value that can be
assigned to a variable or otherwise operated on:

@example
val = (yield i)
@end example

I recommend that you always put parentheses around a @ref{2ce,,yield} expression
when you're doing something with the returned value, as in the above example.
The parentheses aren't always necessary, but it's easier to always add them
instead of having to remember when they're needed.

(
@geindex Python 提高建议; PEP 342
PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} explains the exact rules, which are that a
@ref{2ce,,yield}-expression must always be parenthesized except when it
occurs at the top-level
expression on the right-hand side of an assignment.  This means you can write
@code{val = yield i} but have to use parentheses when there's an operation, as in
@code{val = (yield i) + 12}.)

Values are sent into a generator by calling its @code{send(value)} method.  The
generator's code is then resumed and the @ref{2ce,,yield} expression returns the
specified @emph{value}.  If the regular @ref{77f,,next()} method is called, the
@code{yield} returns @ref{204,,None}.

Here's the previous example, modified to allow changing the value of the
internal counter.

@example
def counter (maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1
@end example

And here's an example of changing the counter:

@example
>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
  File "t.py", line 15, in ?
    print it.next()
StopIteration
@end example

@ref{2ce,,yield} will usually return @ref{204,,None}, so you should always check
for this case.  Don't just use its value in expressions unless you're sure that
the @code{send()} method will be the only method used to resume your generator
function.

In addition to @code{send()}, there are two other new methods on generators:


@itemize *

@item 
@code{throw(type, value=None, traceback=None)} is used to raise an exception
inside the generator; the exception is raised by the @ref{2ce,,yield} expression
where the generator's execution is paused.

@item 
@code{close()} raises a new @ref{e00,,GeneratorExit} exception inside the generator
to terminate the iteration.  On receiving this exception, the generator's code
must either raise @ref{e00,,GeneratorExit} or @ref{58a,,StopIteration}.  Catching the
@ref{e00,,GeneratorExit} exception and returning a value is illegal and will trigger
a @ref{3e4,,RuntimeError}; if the function raises some other exception, that
exception is propagated to the caller.  @code{close()} will also be called by
Python's garbage collector when the generator is garbage-collected.

If you need to run cleanup code when a @ref{e00,,GeneratorExit} occurs, I suggest
using a @code{try: ... finally:} suite instead of  catching @ref{e00,,GeneratorExit}.
@end itemize

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消费者。

Generators also become @emph{coroutines}, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a @ref{2cf,,return} statement), but coroutines can be entered,
exited, and resumed at many different points (the @ref{2ce,,yield} statements).
We'll have to figure out patterns for using coroutines effectively in Python.

The addition of the @code{close()} method has one side effect that isn't obvious.
@code{close()} is called when a generator is garbage-collected, so this means the
generator's code gets one last chance to run before the generator is destroyed.
This last chance means that @code{try...finally} statements in generators can now
be guaranteed to work; the @ref{2c3,,finally} clause will now always get a
chance to run.  The syntactic restriction that you couldn't mix @ref{2ce,,yield}
statements with a @code{try...finally} suite has therefore been removed.  This
seems like a minor bit of language trivia, but using generators and
@code{try...finally} is actually necessary in order to implement the
@ref{7e4,,with} statement described by 
@geindex Python 提高建议; PEP 343
PEP 343@footnote{https://www.python.org/dev/peps/pep-0343}.  I'll look at this new statement
in the following  section.

Another even more esoteric effect of this change: previously, the
@code{gi_frame} attribute of a generator was always a frame object. It's now
possible for @code{gi_frame} to be @code{None} once the generator has been
exhausted.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 342

@item PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} - 通过增强型生成器实现协程

PEP 由 Guido van Rossum 和 Phillip J. Eby 撰写，由 Phillip J. Eby 实现。包括一些更高级的使用生成器作为协程的示例。

这些功能的早期版本在 
@geindex Python 提高建议; PEP 288
PEP 288@footnote{https://www.python.org/dev/peps/pep-0288} （由 Raymond Hettinger 撰写） 和 
@geindex Python 提高建议; PEP 325
PEP 325@footnote{https://www.python.org/dev/peps/pep-0325} （由 Samuele Pedroni 撰写）中提出。

@item @indicateurl{https://en.wikipedia.org/wiki/Coroutine}

协程的Wikipedia条目。

@item @indicateurl{http://www.sidhe.org/~dan/blog/archives/000178.html}

An explanation of coroutines from a Perl point of view, written by Dan Sugalski.
@end table


@c ======================================================================

@node PEP 343 "with" 语句<2>,PEP 352 异常作为新型的类,PEP 342 生成器的新特性,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-343}@anchor{e32}@anchor{whatsnew/2 5 pep-343-the-with-statement}@anchor{e41}
@subsection PEP 343: "with" 语句


The '@ref{7e4,,with}' statement clarifies code that previously would use
@code{try...finally} blocks to ensure that clean-up code is executed.  In this
section, I'll discuss the statement as it will commonly be used.  In the next
section, I'll examine the implementation details and show how to write objects
for use with this statement.

The '@ref{7e4,,with}' statement is a new control-flow structure whose basic
structure is:

@example
with expression [as variable]:
    with-block
@end example

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has @ref{d65,,__enter__()} and @ref{d66,,__exit__()}
methods.

The object's @ref{d65,,__enter__()} is called before @emph{with-block} is executed and
therefore can run set-up code. It also may return a value that is bound to the
name @emph{variable}, if given.  (Note carefully that @emph{variable} is @emph{not} assigned
the result of @emph{expression}.)

After execution of the @emph{with-block} is finished, the object's @ref{d66,,__exit__()}
method is called, even if the block raised an exception, and can therefore run
clean-up code.

To enable the statement in Python 2.5, you need to add the following directive
to your module:

@example
from __future__ import with_statement
@end example

该语句在Python 2.6 中始终启用。

Some standard Python objects now support the context management protocol and can
be used with the '@ref{7e4,,with}' statement. File objects are one example:

@example
with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...
@end example

After this statement has executed, the file object in @emph{f} will have been
automatically closed, even if the @ref{d02,,for} loop raised an exception
part-way through the block.

@cartouche
@quotation 注解 
In this case, @emph{f} is the same object created by @ref{16f,,open()}, because
@code{file.__enter__()} returns @emph{self}.
@end quotation
@end cartouche

The @ref{10b,,threading} module's locks and condition variables  also support the
'@ref{7e4,,with}' statement:

@example
lock = threading.Lock()
with lock:
    # Critical section of code
    ...
@end example

The lock is acquired before the block is executed and always released once  the
block is complete.

The new @code{localcontext()} function in the @ref{35,,decimal} module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:

@example
from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()
@end example

@menu
* 编写上下文管理器: 编写上下文管理器<2>. 
* contextlib 模块: contextlib 模块<2>. 

@end menu

@node 编写上下文管理器<2>,contextlib 模块<2>,,PEP 343 "with" 语句<2>
@anchor{whatsnew/2 5 new-25-context-managers}@anchor{e42}@anchor{whatsnew/2 5 writing-context-managers}@anchor{e43}
@subsubsection 编写上下文管理器


Under the hood, the '@ref{7e4,,with}' statement is fairly complicated. Most
people will only use '@code{with}' in company with existing objects and
don't need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.

在更高层级上对于上下文管理器协议的解释:


@itemize *

@item 
The expression is evaluated and should result in an object called a "context
manager".  The context manager must have @ref{d65,,__enter__()} and @ref{d66,,__exit__()}
methods.

@item 
The context manager's @ref{d65,,__enter__()} method is called.  The value returned
is assigned to @emph{VAR}.  If no @code{'as VAR'} clause is present, the value is simply
discarded.

@item 
@emph{BLOCK} 中的代码会被执行。

@item 
If @emph{BLOCK} raises an exception, the @code{__exit__(type, value, traceback)}
is called with the exception details, the same values returned by
@ref{d2f,,sys.exc_info()}.  The method's return value controls whether the exception
is re-raised: any false value re-raises the exception, and @code{True} will result
in suppressing it.  You'll only rarely want to suppress the exception, because
if you do the author of the code containing the '@ref{7e4,,with}' statement will
never realize anything went wrong.

@item 
If @emph{BLOCK} didn't raise an exception,  the @ref{d66,,__exit__()} method is still
called, but @emph{type}, @emph{value}, and @emph{traceback} are all @code{None}.
@end itemize

Let's think through an example.  I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)

Let's assume there's an object representing a database connection. Our goal will
be to let the user write code like this:

@example
db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...
@end example

The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
@code{DatabaseConnection} that I'll assume:

@example
class DatabaseConnection:
    # Database interface
    def cursor (self):
        "Returns a cursor object and starts a new transaction"
    def commit (self):
        "Commits current transaction"
    def rollback (self):
        "Rolls back current transaction"
@end example

The @ref{d65,,__enter__()} method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add @code{as cursor} to
their '@ref{7e4,,with}' statement to bind the cursor to a variable name.

@example
class DatabaseConnection:
    ...
    def __enter__ (self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor
@end example

The @ref{d66,,__exit__()} method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of @code{None}.  @code{None} is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a @ref{2cf,,return} statement at the marked location.

@example
class DatabaseConnection:
    ...
    def __exit__ (self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False
@end example

@node contextlib 模块<2>,,编写上下文管理器<2>,PEP 343 "with" 语句<2>
@anchor{whatsnew/2 5 contextlibmod}@anchor{e44}@anchor{whatsnew/2 5 the-contextlib-module}@anchor{e45}
@subsubsection contextlib 模块


The new @ref{23,,contextlib} module provides some functions and a decorator that
are useful for writing objects for use with the '@ref{7e4,,with}' statement.

The decorator is called @code{contextmanager()}, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the @ref{2ce,,yield} will be executed as the
@ref{d65,,__enter__()} method, and the value yielded will be the method's return
value that will get bound to the variable in the '@ref{7e4,,with}' statement's
@code{as} clause, if any.  The code after the @ref{2ce,,yield} will be
executed in the @ref{d66,,__exit__()} method.  Any exception raised in the block will
be raised by the @code{yield} statement.

Our database example from the previous section could be written  using this
decorator as:

@example
from contextlib import contextmanager

@@contextmanager
def db_transaction (connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...
@end example

The @ref{23,,contextlib} module also has a @code{nested(mgr1, mgr2, ...)} function
that combines a number of context managers so you don't need to write nested
'@ref{7e4,,with}' statements.  In this example, the single '@code{with}'
statement both starts a database transaction and acquires a thread lock:

@example
lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...
@end example

Finally, the @code{closing(object)} function returns @emph{object} so that it can be
bound to a variable, and calls @code{object.close} at the end of the block.

@example
import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 343

@item PEP 343@footnote{https://www.python.org/dev/peps/pep-0343} - "with" 语句

PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
'@ref{7e4,,with}' statement, which can be helpful in learning how the statement
works.
@end table

@ref{23,,contextlib} 模块的文档。


@c ======================================================================

@node PEP 352 异常作为新型的类,PEP 353 使用ssize_t作为索引类型,PEP 343 "with" 语句<2>,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-352}@anchor{e46}@anchor{whatsnew/2 5 pep-352-exceptions-as-new-style-classes}@anchor{e47}
@subsection PEP 352: 异常作为新型的类


Exception classes can now be new-style classes, not just classic classes, and
the built-in @ref{2e3,,Exception} class and all the standard built-in exceptions
(@ref{e48,,NameError}, @ref{16d,,ValueError}, etc.) are now new-style classes.

The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
inheritance relationships are:

@example
BaseException       # New in Python 2.5
|- KeyboardInterrupt
|- SystemExit
|- Exception
   |- (all other current built-in exceptions)
@end example

This rearrangement was done because people often want to catch all exceptions
that indicate program errors.  @ref{2d3,,KeyboardInterrupt} and @ref{6fd,,SystemExit}
aren't errors, though, and usually represent an explicit action such as the user
hitting @code{Control-C} or code calling @ref{db2,,sys.exit()}.  A bare @code{except:} will
catch all exceptions, so you commonly need to list @ref{2d3,,KeyboardInterrupt} and
@ref{6fd,,SystemExit} in order to re-raise them.  The usual pattern is:

@example
try:
    ...
except (KeyboardInterrupt, SystemExit):
    raise
except:
    # Log error...
    # Continue running program...
@end example

In Python 2.5, you can now write @code{except Exception} to achieve the same
result, catching all the exceptions that usually indicate errors  but leaving
@ref{2d3,,KeyboardInterrupt} and @ref{6fd,,SystemExit} alone.  As in previous versions,
a bare @code{except:} still catches all exceptions.

The goal for Python 3.0 is to require any class raised as an exception to derive
from @ref{2e2,,BaseException} or some descendant of @ref{2e2,,BaseException}, and future
releases in the Python 2.x series may begin to enforce this constraint.
Therefore, I suggest you begin making all your exception classes derive from
@ref{2e3,,Exception} now.  It's been suggested that the bare @code{except:} form should
be removed in Python 3.0, but Guido van Rossum hasn't decided whether to do this
or not.

Raising of strings as exceptions, as in the statement @code{raise "Error
occurred"}, is deprecated in Python 2.5 and will trigger a warning.  The aim is
to be able to remove the string-exception feature in a few releases.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 352

@item PEP 352@footnote{https://www.python.org/dev/peps/pep-0352} - 异常所需的超类

PEP 由 Brett Cannon 和 Guido van Rossum 撰写，由 Brett Cannon 实现
@end table


@c ======================================================================

@node PEP 353 使用ssize_t作为索引类型,PEP 357 '__index__' 方法,PEP 352 异常作为新型的类,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-353}@anchor{e49}@anchor{whatsnew/2 5 pep-353-using-ssize-t-as-the-index-type}@anchor{e4a}
@subsection PEP 353: 使用ssize_t作为索引类型


A wide-ranging change to Python's C API, using a new  @ref{391,,Py_ssize_t} type
definition instead of @code{int},  will permit the interpreter to handle more
data on 64-bit platforms. This change doesn't affect Python's capacity on 32-bit
platforms.

Various pieces of the Python interpreter used C's @code{int} type to store
sizes or counts; for example, the number of items in a list or tuple were stored
in an @code{int}.  The C compilers for most 64-bit platforms still define
@code{int} as a 32-bit type, so that meant that lists could only hold up to
@code{2**31 - 1} = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use -- see
@indicateurl{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a discussion -- but the
most commonly available model leaves @code{int} as 32 bits.)

A limit of 2147483647 items doesn't really matter on a 32-bit platform because
you'll run out of memory before hitting the length limit. Each list item
requires space for a pointer, which is 4 bytes, plus space for a
@ref{5bd,,PyObject} representing the item.  2147483647*4 is already more bytes
than a 32-bit address space can contain.

It's possible to address that much memory on a 64-bit platform, however.  The
pointers for a list that size would only require 16 GiB of space, so it's not
unreasonable that Python programmers might construct lists that large.
Therefore, the Python interpreter had to be changed to use some type other than
@code{int}, and this will be a 64-bit type on 64-bit platforms.  The change
will cause incompatibilities on 64-bit machines, so it was deemed worth making
the transition now, while the number of 64-bit users is still relatively small.
(In 5 or 10 years, we may @emph{all} be on 64-bit machines, and the transition would
be more painful then.)

This change most strongly affects authors of C extension modules.   Python
strings and container types such as lists and tuples  now use
@ref{391,,Py_ssize_t} to store their size.   Functions such as
@ref{e4b,,PyList_Size()}  now return @ref{391,,Py_ssize_t}.  Code in extension modules
may therefore need to have some variables changed to @ref{391,,Py_ssize_t}.

The @ref{39b,,PyArg_ParseTuple()} and @ref{3f9,,Py_BuildValue()} functions have a new
conversion code, @code{n}, for @ref{391,,Py_ssize_t}.   @ref{39b,,PyArg_ParseTuple()}'s
@code{s#} and @code{t#} still output @code{int} by default, but you can define the
macro  @code{PY_SSIZE_T_CLEAN} before including @code{Python.h}  to make
them return @ref{391,,Py_ssize_t}.

@geindex Python 提高建议; PEP 353
PEP 353@footnote{https://www.python.org/dev/peps/pep-0353} has a section on conversion guidelines that  extension authors should
read to learn about supporting 64-bit platforms.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 353

@item PEP 353@footnote{https://www.python.org/dev/peps/pep-0353} - 使用ssize_t作为索引类型

PEP 由 Martin von Löwis 撰写并实现。
@end table


@c ======================================================================

@node PEP 357 '__index__' 方法,其他语言特性修改<12>,PEP 353 使用ssize_t作为索引类型,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 pep-357}@anchor{e4c}@anchor{whatsnew/2 5 pep-357-the-index-method}@anchor{e4d}
@subsection PEP 357: '__index__' 方法


The NumPy developers had a problem that could only be solved by adding a new
special method, @ref{2c9,,__index__()}.  When using slice notation, as in
@code{[start:stop:step]}, the values of the @emph{start}, @emph{stop}, and @emph{step} indexes
must all be either integers or long integers.  NumPy defines a variety of
specialized integer types corresponding to unsigned and signed integers of 8,
16, 32, and 64 bits, but there was no way to signal that these types could be
used as slice indexes.

Slicing can't just use the existing @ref{2ca,,__int__()} method because that method
is also used to implement coercion to integers.  If slicing used
@ref{2ca,,__int__()}, floating-point numbers would also become legal slice indexes
and that's clearly an undesirable behaviour.

Instead, a new special method called @ref{2c9,,__index__()} was added.  It takes no
arguments and returns an integer giving the slice index to use.  For example:

@example
class C:
    def __index__ (self):
        return self.value
@end example

The return value must be either a Python integer or long integer. The
interpreter will check that the type returned is correct, and raises a
@ref{1ff,,TypeError} if this requirement isn't met.

A corresponding @code{nb_index} slot was added to the C-level
@ref{e4e,,PyNumberMethods} structure to let C extensions implement this protocol.
@code{PyNumber_Index(obj)} can be used in extension code to call the
@ref{2c9,,__index__()} function and retrieve its result.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 357

@item PEP 357@footnote{https://www.python.org/dev/peps/pep-0357} - 允许将任何对象用于切片

PEP 由 Travis Oliphant 撰写并实现。
@end table


@c ======================================================================

@node 其他语言特性修改<12>,新增，改进和删除的模块,PEP 357 '__index__' 方法,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 other-lang}@anchor{e4f}@anchor{whatsnew/2 5 other-language-changes}@anchor{e50}
@subsection 其他语言特性修改


以下是 Python 2.5 针对核心 Python 语言的所有改变。


@itemize *

@item 
The @ref{164,,dict} type has a new hook for letting subclasses provide a default
value when a key isn't contained in the dictionary. When a key isn't found, the
dictionary's @code{__missing__(key)} method will be called.  This hook is used
to implement the new @code{defaultdict} class in the @ref{1d,,collections}
module.  The following example defines a dictionary  that returns zero for any
missing key:

@example
class zerodict (dict):
    def __missing__ (self, key):
        return 0

d = zerodict(@{1:1, 2:2@})
print d[1], d[2]   # Prints 1, 2
print d[3], d[4]   # Prints 0, 0
@end example

@item 
Both 8-bit and Unicode strings have new @code{partition(sep)}  and
@code{rpartition(sep)} methods that simplify a common use case.

The @code{find(S)} method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the separator.
@code{partition(sep)} condenses this pattern into a single method call that
returns a 3-tuple containing the substring before the separator, the separator
itself, and the substring after the separator.  If the separator isn't found,
the first element of the tuple is the entire string and the other two elements
are empty.  @code{rpartition(sep)} also returns a 3-tuple but starts searching
from the end of the string; the @code{r} stands for 'reverse'.

几个例子：

@example
>>> ('http://www.python.org').partition('://')
('http', '://', 'www.python.org')
>>> ('file:/usr/share/doc/index.html').partition('://')
('file:/usr/share/doc/index.html', '@w{'}, '@w{'})
>>> (u'Subject: a quick question').partition(':')
(u'Subject', u':', u' a quick question')
>>> 'www.python.org'.rpartition('.')
('www.python', '.', 'org')
>>> 'www.python.org'.rpartition(':')
('@w{'}, '@w{'}, 'www.python.org')
@end example

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)

@item 
The @code{startswith()} and @code{endswith()} methods of string types now accept
tuples of strings to check for.

@example
def is_image_file (filename):
    return filename.endswith(('.gif', '.jpg', '.tiff'))
@end example

(Implemented by Georg Brandl following a suggestion by Tom Lynn.)

@c RFE #1491485

@item 
The @ref{900,,min()} and @ref{901,,max()} built-in functions gained a @code{key} keyword
parameter analogous to the @code{key} argument for @code{sort()}.  This parameter
supplies a function that takes a single argument and is called for every value
in the list; @ref{900,,min()}/@ref{901,,max()} will return the element with the
smallest/largest return value from this function. For example, to find the
longest string in a list, you can do:

@example
L = ['medium', 'longest', 'short']
# Prints 'longest'
print max(L, key=len)
# Prints 'short', because lexicographically 'short' has the largest value
print max(L)
@end example

（由 Steven Bethard 和 Raymond Hettinger 贡献。）

@item 
Two new built-in functions, @ref{e51,,any()} and @ref{e52,,all()}, evaluate whether an
iterator contains any true or false values.  @ref{e51,,any()} returns @ref{59c,,True}
if any value returned by the iterator is true; otherwise it will return
@ref{497,,False}.  @ref{e52,,all()} returns @ref{59c,,True} only if all of the values
returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and
implemented by Raymond Hettinger.)

@item 
The result of a class's @ref{455,,__hash__()} method can now be either a long
integer or a regular integer.  If a long integer is returned, the hash of that
value is taken.  In earlier versions the hash value was required to be a
regular integer, but in 2.5 the @ref{e53,,id()} built-in was changed to always
return non-negative numbers, and users often seem to use @code{id(self)} in
@ref{455,,__hash__()} methods (though this is discouraged).

@c Bug #1536021

@item 
ASCII is now the default encoding for modules.  It's now  a syntax error if a
module contains string literals with 8-bit characters but doesn't have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.  See 
@geindex Python 提高建议; PEP 263
PEP 263@footnote{https://www.python.org/dev/peps/pep-0263}  for how to declare a module's encoding; for example, you
might add  a line like this near the top of the source file:

@example
# -*- coding: latin1 -*-
@end example

@item 
A new warning, @ref{e54,,UnicodeWarning}, is triggered when  you attempt to
compare a Unicode string and an 8-bit string  that can't be converted to Unicode
using the default ASCII encoding.   The result of the comparison is false:

@example
>>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
__main__:1: UnicodeWarning: Unicode equal comparison failed
  to convert both arguments to Unicode - interpreting them
  as being unequal
False
>>> chr(127) == unichr(127)   # chr(127) can be converted
True
@end example

Previously this would raise a @ref{332,,UnicodeDecodeError} exception, but in 2.5
this could result in puzzling problems when accessing a dictionary.  If you
looked up @code{unichr(128)} and @code{chr(128)} was being used as a key, you'd get a
@ref{332,,UnicodeDecodeError} exception.  Other changes in 2.5 resulted in this
exception being raised instead of suppressed by the code in @code{dictobject.c}
that implements dictionaries.

Raising an exception for such a comparison is strictly correct, but the change
might have broken code, so instead  @ref{e54,,UnicodeWarning} was introduced.

（由 Marc-André Lemburg 实现。）

@item 
One error that Python programmers sometimes make is forgetting to include an
@code{__init__.py} module in a package directory. Debugging this mistake can be
confusing, and usually requires running Python with the @ref{e55,,-v} switch to
log all the paths searched. In Python 2.5, a new @ref{6d9,,ImportWarning} warning is
triggered when an import would have picked up a directory as a package but no
@code{__init__.py} was found.  This warning is silently ignored by default;
provide the @ref{15b,,-Wd} option when running the Python executable to display
the warning message. (Implemented by Thomas Wouters.)

@item 
The list of base classes in a class definition can now be empty.   As an
example, this is now legal:

@example
class C():
    pass
@end example

（由 Brett Cannon 实现。）
@end itemize

@c ======================================================================

@menu
* 交互解释器变更:: 
* 性能优化: 性能优化<11>. 

@end menu

@node 交互解释器变更,性能优化<11>,,其他语言特性修改<12>
@anchor{whatsnew/2 5 interactive}@anchor{e56}@anchor{whatsnew/2 5 interactive-interpreter-changes}@anchor{e57}
@subsubsection 交互解释器变更


In the interactive interpreter, @code{quit} and @code{exit}  have long been strings so
that new users get a somewhat helpful message when they try to quit:

@example
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
@end example

In Python 2.5, @code{quit} and @code{exit} are now objects that still produce string
representations of themselves, but are also callable. Newbies who try @code{quit()}
or @code{exit()} will now exit the interpreter as they expect.  (Implemented by
Georg Brandl.)

The Python executable now accepts the standard long options  @ref{e58,,--help}
and @ref{6d2,,--version}; on Windows,  it also accepts the @ref{e59,,/?} option
for displaying a help message. (Implemented by Georg Brandl.)

@c ======================================================================

@node 性能优化<11>,,交互解释器变更,其他语言特性修改<12>
@anchor{whatsnew/2 5 optimizations}@anchor{e5a}@anchor{whatsnew/2 5 opts}@anchor{e5b}
@subsubsection 性能优化


Several of the optimizations were developed at the NeedForSpeed sprint, an event
held in Reykjavik, Iceland, from May 21--28 2006. The sprint focused on speed
enhancements to the CPython implementation and was funded by EWT LLC with local
support from CCP Games.  Those optimizations added at this sprint are specially
marked in the following list.


@itemize *

@item 
When they were introduced  in Python 2.4, the built-in @ref{1f7,,set} and
@ref{1f8,,frozenset} types were built on top of Python's dictionary type.   In 2.5
the internal data structure has been customized for implementing sets, and as a
result sets will use a third less memory and are somewhat faster. (Implemented
by Raymond Hettinger.)

@item 
The speed of some Unicode operations, such as finding substrings, string
splitting, and character map encoding and decoding, has been improved.
(Substring search and splitting improvements were added by Fredrik Lundh and
Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter
Dörwald and Martin von Löwis.)

@c Patch 1313939, 1359618

@item 
The @code{long(str, base)} function is now faster on long digit strings
because fewer intermediate results are calculated.  The peak is for strings of
around 800--1000 digits where  the function is 6 times faster. (Contributed by
Alan McIntyre and committed at the NeedForSpeed sprint.)

@c Patch 1442927

@item 
It's now illegal to mix iterating over a file  with @code{for line in file} and
calling  the file object's @code{read()}/@ref{de,,readline()}/@code{readlines()}
methods.  Iteration uses an internal buffer and the  @code{read*()} methods
don't use that buffer.   Instead they would return the data following the
buffer, causing the data to appear out of order.  Mixing iteration and these
methods will now trigger a @ref{16d,,ValueError} from the @code{read*()} method.
(Implemented by Thomas Wouters.)

@c Patch 1397960

@item 
The @ref{f8,,struct} module now compiles structure format  strings into an
internal representation and caches this representation, yielding a 20% speedup.
(Contributed by Bob Ippolito at the NeedForSpeed sprint.)

@item 
The @ref{dd,,re} module got a 1 or 2% speedup by switching to  Python's allocator
functions instead of the system's  @code{malloc()} and @code{free()}.
(Contributed by Jack Diederich at the NeedForSpeed sprint.)

@item 
The code generator's peephole optimizer now performs simple constant folding
in expressions.  If you write something like @code{a = 2+3}, the code generator
will do the arithmetic and produce code corresponding to @code{a = 5}.  (Proposed
and implemented  by Raymond Hettinger.)

@item 
Function calls are now faster because code objects now keep  the most recently
finished frame (a "zombie frame") in an internal field of the code object,
reusing it the next time the code object is invoked.  (Original patch by Michael
Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
sprint.)  Frame objects are also slightly smaller, which may improve cache
locality and reduce memory usage a bit.  (Contributed by Neal Norwitz.)

@c Patch 876206

@c Patch 1337051

@item 
Python's built-in exceptions are now new-style classes, a change that speeds
up instantiation considerably.  Exception handling in Python 2.5 is therefore
about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
Sean Reifschneider at the NeedForSpeed sprint.)

@item 
Importing now caches the paths tried, recording whether  they exist or not so
that the interpreter makes fewer  @code{open()} and @code{stat()} calls on
startup. (Contributed by Martin von Löwis and Georg Brandl.)

@c Patch 921466
@end itemize

@c ======================================================================

@node 新增，改进和删除的模块,构建和 C API 的改变<10>,其他语言特性修改<12>,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 modules}@anchor{e5c}@anchor{whatsnew/2 5 new-improved-and-removed-modules}@anchor{e5d}
@subsection 新增，改进和删除的模块


The standard library received many enhancements and bug fixes in Python 2.5.
Here's a partial list of the most notable changes, sorted alphabetically by
module name. Consult the @code{Misc/NEWS} file in the source tree for a more
complete list of changes, or look through the SVN logs for all the details.


@itemize *

@item 
The @ref{c,,audioop} module now supports the a-LAW encoding, and the code for
u-LAW encoding has been improved.  (Contributed by Lars Immisch.)

@item 
The @ref{1b,,codecs} module gained support for incremental codecs.  The
@code{codec.lookup()} function now returns a @code{CodecInfo} instance instead
of a tuple. @code{CodecInfo} instances behave like a 4-tuple to preserve
backward compatibility but also have the attributes @code{encode},
@code{decode}, @code{incrementalencoder}, @code{incrementaldecoder},
@code{streamwriter}, and @code{streamreader}.  Incremental codecs  can receive
input and produce output in multiple chunks; the output is the same as if the
entire input was fed to the non-incremental codec. See the @ref{1b,,codecs} module
documentation for details. (Designed and implemented by Walter Dörwald.)

@c Patch  1436130

@item 
The @ref{1d,,collections} module gained a new type, @code{defaultdict}, that
subclasses the standard @ref{164,,dict} type.  The new type mostly behaves like a
dictionary but constructs a default value when a key isn't present,
automatically adding it to the dictionary for the requested key value.

The first argument to @code{defaultdict}'s constructor is a factory function
that gets called whenever a key is requested but not found. This factory
function receives no arguments, so you can use built-in type constructors such
as @ref{1f9,,list()} or @ref{205,,int()}.  For example,  you can make an index of words
based on their initial letter like this:

@example
words = """Nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura
che la diritta via era smarrita""".lower().split()

index = defaultdict(list)

for w in words:
    init_letter = w[0]
    index[init_letter].append(w)
@end example

打印 @code{index} 导致以下输出:

@example
defaultdict(<type 'list'>, @{'c': ['cammin', 'che'], 'e': ['era'],
        'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
        'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
        'p': ['per'], 's': ['selva', 'smarrita'],
        'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']@}
@end example

（由 Guido van Rossum 贡献。）

@item 
The @code{deque} double-ended queue type supplied by the @ref{1d,,collections}
module now has a @code{remove(value)} method that removes the first occurrence
of @emph{value} in the queue, raising @ref{16d,,ValueError} if the value isn't found.
(Contributed by Raymond Hettinger.)

@item 
New module: The @ref{23,,contextlib} module contains helper functions for use
with the new '@ref{7e4,,with}' statement.  See section @ref{e44,,contextlib 模块}
for more about this module.

@item 
New module: The @ref{27,,cProfile} module is a C implementation of  the existing
@ref{d3,,profile} module that has much lower overhead. The module's interface is
the same as @ref{d3,,profile}: you run @code{cProfile.run('main()')} to profile a
function, can save profile data to a file, etc.  It's not yet known if the
Hotshot profiler, which is also written in C but doesn't match the
@ref{d3,,profile} module's interface, will continue to be maintained in future
versions of Python.  (Contributed by Armin Rigo.)

Also, the @ref{d4,,pstats} module for analyzing the data measured by the profiler
now supports directing the output to any file object by supplying a @emph{stream}
argument to the @code{Stats} constructor. (Contributed by Skip Montanaro.)

@item 
The @ref{29,,csv} module, which parses files in comma-separated value format,
received several enhancements and a number of bugfixes.  You can now set the
maximum size in bytes of a field by calling the
@code{csv.field_size_limit(new_limit)} function; omitting the @emph{new_limit}
argument will return the currently-set limit.  The @code{reader} class now has
a @code{line_num} attribute that counts the number of physical lines read from
the source; records can span multiple physical lines, so @code{line_num} is not
the same as the number of records read.

The CSV parser is now stricter about multi-line quoted fields. Previously, if a
line ended within a quoted field without a terminating newline character, a
newline would be inserted into the returned field. This behavior caused problems
when reading files that contained carriage return characters within fields, so
the code was changed to return the field without inserting newlines. As a
consequence, if newlines embedded within fields are important, the input should
be split into lines in a manner that preserves the newline characters.

（由Skip Montanaro 和 Andrew McNamara 贡献。）

@item 
The @ref{19f,,datetime} class in the @ref{30,,datetime}  module now has a
@code{strptime(string, format)}  method for parsing date strings, contributed
by Josh Spoerri. It uses the same format characters as @ref{e5e,,time.strptime()} and
@ref{c40,,time.strftime()}:

@example
from datetime import datetime

ts = datetime.strptime('10:13:15 2006-03-07',
                       '%H:%M:%S %Y-%m-%d')
@end example

@item 
The @code{SequenceMatcher.get_matching_blocks()} method in the @ref{36,,difflib}
module now guarantees to return a minimal list of blocks describing matching
subsequences.  Previously, the algorithm would occasionally break a block of
matching elements into two list entries. (Enhancement by Tim Peters.)

@item 
The @ref{66,,doctest} module gained a @code{SKIP} option that keeps an example from
being executed at all.  This is intended for code snippets that are usage
examples intended for the reader and aren't actually test cases.

An @emph{encoding} parameter was added to the @code{testfile()} function and the
@code{DocFileSuite} class to specify the file's encoding.  This makes it
easier to use non-ASCII characters in  tests contained within a docstring.
(Contributed by Bjorn Tillenius.)

@c Patch 1080727

@item 
@ref{67,,email} 包已经升级到 4.0版 （由 Barry Warsaw 贡献）

@c XXX need to provide some more detail here

@geindex universal newlines; What's new

@item 
The @ref{7e,,fileinput} module was made more flexible. Unicode filenames are now
supported, and a @emph{mode} parameter that defaults to @code{"r"} was added to the
@ref{d3b,,input()} function to allow opening files in binary or @ref{6f5,,universal newlines} mode.  Another new parameter, @emph{openhook}, lets you use a function
other than @ref{16f,,open()}  to open the input files.  Once you're iterating over
the set of files, the @code{FileInput} object's new @code{fileno()} returns
the file descriptor for the currently opened file. (Contributed by Georg
Brandl.)

@item 
In the @ref{84,,gc} module, the new @code{get_count()} function returns a 3-tuple
containing the current collection counts for the three GC generations.  This is
accounting information for the garbage collector; when these counts reach a
specified threshold, a garbage collection sweep will be made.  The existing
@ref{362,,gc.collect()} function now takes an optional @emph{generation} argument of 0, 1,
or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)

@item 
The @code{nsmallest()} and  @code{nlargest()} functions in the @ref{8d,,heapq}
module  now support a @code{key} keyword parameter similar to the one provided by
the @ref{900,,min()}/@ref{901,,max()} functions and the @code{sort()} methods.  For
example:

@example
>>> import heapq
>>> L = ["short", 'medium', 'longest', 'longer still']
>>> heapq.nsmallest(2, L)  # Return two lowest elements, lexicographically
['longer still', 'longest']
>>> heapq.nsmallest(2, L, key=len)   # Return two shortest elements
['short', 'medium']
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @ref{4b1,,itertools.islice()} function now accepts @code{None} for the start and
step arguments.  This makes it more compatible with the attributes of slice
objects, so that you can now write the following:

@example
s = slice(5)     # Create slice object
itertools.islice(iterable, s.start, s.stop, s.step)
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @ref{5de,,format()} function in the @ref{a9,,locale} module has been modified and
two new functions were added, @code{format_string()} and @code{currency()}.

The @ref{5de,,format()} function's @emph{val} parameter could previously be a string as
long as no more than one %char specifier appeared; now the parameter must be
exactly one %char specifier with no surrounding text.  An optional @emph{monetary}
parameter was also added which, if @code{True}, will use the locale's rules for
formatting currency in placing a separator between groups of three digits.

To format strings with multiple %char specifiers, use the new
@code{format_string()} function that works like @ref{5de,,format()} but also supports
mixing %char specifiers with arbitrary text.

A new @code{currency()} function was also added that formats a number according
to the current locale's settings.

（由Georg Brandl 贡献。）

@c Patch 1180296

@item 
The @ref{ae,,mailbox} module underwent a massive rewrite to add the capability to
modify mailboxes in addition to reading them.  A new set of classes that include
@code{mbox}, @code{MH}, and @code{Maildir} are used to read mailboxes, and
have an @code{add(message)} method to add messages, @code{remove(key)} to
remove messages, and @code{lock()}/@code{unlock()} to lock/unlock the mailbox.
The following example converts a maildir-format mailbox into an mbox-format
one:

@example
import mailbox

# 'factory=None' uses email.Message.Message as the class representing
# individual messages.
src = mailbox.Maildir('maildir', factory=None)
dest = mailbox.mbox('/tmp/mbox')

for msg in src:
    dest.add(msg)
@end example

(Contributed by Gregory K. Johnson.  Funding was provided by Google's 2005
Summer of Code.)

@item 
New module: the @ref{b5,,msilib} module allows creating Microsoft Installer
@code{.msi} files and CAB files.  Some support for reading the @code{.msi}
database is also included. (Contributed by Martin von Löwis.)

@item 
The @ref{bf,,nis} module now supports accessing domains other than the system
default domain by supplying a @emph{domain} argument to the @ref{e5f,,nis.match()} and
@ref{e60,,nis.maps()} functions. (Contributed by Ben Bell.)

@item 
The @ref{c2,,operator} module's @code{itemgetter()}  and @code{attrgetter()}
functions now support multiple fields.   A call such as
@code{operator.attrgetter('a', 'b')} will return a function  that retrieves the
@code{a} and @code{b} attributes.  Combining  this new feature with the
@code{sort()} method's @code{key} parameter  lets you easily sort lists using
multiple fields. (Contributed by Raymond Hettinger.)

@item 
The @ref{c3,,optparse} module was updated to version 1.5.1 of the Optik library.
The @code{OptionParser} class gained an @code{epilog} attribute, a string
that will be printed after the help message, and a @code{destroy()} method to
break reference cycles created by the object. (Contributed by Greg Ward.)

@item 
The @ref{c4,,os} module underwent several changes.  The @code{stat_float_times}
variable now defaults to true, meaning that @ref{328,,os.stat()} will now return time
values as floats.  (This doesn't necessarily mean that @ref{328,,os.stat()} will
return times that are precise to fractions of a second; not all systems support
such precision.)

Constants named @ref{e61,,os.SEEK_SET}, @ref{e62,,os.SEEK_CUR}, and
@ref{e63,,os.SEEK_END} have been added; these are the parameters to the
@ref{b42,,os.lseek()} function.  Two new constants for locking are
@ref{e64,,os.O_SHLOCK} and @ref{e65,,os.O_EXLOCK}.

Two new functions, @code{wait3()} and @code{wait4()}, were added.  They're similar
the @code{waitpid()} function which waits for a child process to exit and returns
a tuple of the process ID and its exit status, but @code{wait3()} and
@code{wait4()} return additional information.  @code{wait3()} doesn't take a
process ID as input, so it waits for any child process to exit and returns a
3-tuple of @emph{process-id}, @emph{exit-status}, @emph{resource-usage} as returned from the
@ref{e66,,resource.getrusage()} function. @code{wait4(pid)} does take a process ID.
(Contributed by Chad J. Schroeder.)

On FreeBSD, the @ref{328,,os.stat()} function now returns  times with nanosecond
resolution, and the returned object now has @code{st_gen} and
@code{st_birthtime}. The @code{st_flags} attribute is also available, if the
platform supports it. (Contributed by Antti Louko and  Diego Pettenò.)

@c (Patch 1180695, 1212117)

@item 
The Python debugger provided by the @ref{c9,,pdb} module can now store lists of
commands to execute when a breakpoint is reached and execution stops.  Once
breakpoint #1 has been created, enter @code{commands 1} and enter a series of
commands to be executed, finishing the list with @code{end}.  The command list can
include commands that resume execution, such as @code{continue} or @code{next}.
(Contributed by Grégoire Dooms.)

@c Patch 790710

@item 
The @ref{ca,,pickle} and @code{cPickle} modules no longer accept a return value
of @code{None} from the @ref{2d7,,__reduce__()} method; the method must return a tuple
of arguments instead.  The ability to return @code{None} was deprecated in Python
2.4, so this completes the removal of the feature.

@item 
The @ref{cd,,pkgutil} module, containing various utility functions for finding
packages, was enhanced to support 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}'s import hooks and now also works for
packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)

@item 
The pybench benchmark suite by Marc-André Lemburg is now included in the
@code{Tools/pybench} directory.  The pybench suite is an improvement on the
commonly used @code{pystone.py} program because pybench provides a more
detailed measurement of the interpreter's speed.  It times particular operations
such as function calls, tuple slicing, method lookups, and numeric operations,
instead of performing many different operations and reducing the result to a
single number as @code{pystone.py} does.

@item 
@code{pyexpat} 模块现在使用 Expat 解析器的 2.0 版。 （由 Trent Mick 贡献。）

@item 
The @ref{de6,,Queue} class provided by the @code{Queue} module gained two new
methods.  @code{join()} blocks until all items in the queue have been retrieved
and all processing work on the items  have been completed.  Worker threads call
the other new method,  @code{task_done()}, to signal that processing for an item
has been completed.  (Contributed by Raymond Hettinger.)

@item 
The old @code{regex} and @code{regsub} modules, which have been  deprecated
ever since Python 2.0, have finally been deleted.   Other deleted modules:
@code{statcache}, @code{tzparse}, @code{whrandom}.

@item 
Also deleted: the @code{lib-old} directory, which includes ancient modules
such as @code{dircmp} and @code{ni}, was removed.  @code{lib-old} wasn't on the
default @code{sys.path}, so unless your programs explicitly added the directory to
@code{sys.path}, this removal shouldn't affect your code.

@item 
The @ref{e1,,rlcompleter} module is no longer  dependent on importing the
@ref{de,,readline} module and therefore now works on non-Unix platforms. (Patch
from Robert Kiendl.)

@c Patch #1472854

@item 
The @code{SimpleXMLRPCServer} and @code{DocXMLRPCServer}  classes now have a
@code{rpc_paths} attribute that constrains XML-RPC operations to a limited set
of URL paths; the default is to allow only @code{'/'} and @code{'/RPC2'}.  Setting
@code{rpc_paths} to @code{None} or an empty tuple disables  this path checking.

@c Bug #1473048

@item 
The @ref{ef,,socket} module now supports @code{AF_NETLINK} sockets on Linux,
thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
mechanism for communications between a user-space process and kernel code; an
introductory  article about them is at @indicateurl{https://www.linuxjournal.com/article/7356}.
In Python code, netlink addresses are represented as a tuple of 2 integers,
@code{(pid, group_mask)}.

Two new methods on socket objects, @code{recv_into(buffer)} and
@code{recvfrom_into(buffer)}, store the received data in an object  that
supports the buffer protocol instead of returning the data as a string.  This
means you can put the data directly into an array or a memory-mapped file.

Socket objects also gained @code{getfamily()}, @code{gettype()}, and
@code{getproto()} accessor methods to retrieve the family, type, and protocol
values for the socket.

@item 
New module: the @ref{f1,,spwd} module provides functions for accessing the shadow
password database on systems that support  shadow passwords.

@item 
The @ref{f8,,struct} is now faster because it  compiles format strings into
@code{Struct} objects with @code{pack()} and @code{unpack()} methods.  This is
similar to how the @ref{dd,,re} module lets you create compiled regular expression
objects.  You can still use the module-level  @code{pack()} and @code{unpack()}
functions; they'll create  @code{Struct} objects and cache them.  Or you can
use  @code{Struct} instances directly:

@example
s = struct.Struct('ih3s')

data = s.pack(1972, 187, 'abc')
year, number, name = s.unpack(data)
@end example

You can also pack and unpack data to and from buffer objects directly using the
@code{pack_into(buffer, offset, v1, v2, ...)} and @code{unpack_from(buffer,
offset)} methods.  This lets you store data directly into an array or a
memory-mapped file.

(@code{Struct} objects were implemented by Bob Ippolito at the NeedForSpeed
sprint.  Support for buffer objects was added by Martin Blais, also at the
NeedForSpeed sprint.)

@item 
The Python developers switched from CVS to Subversion during the 2.5
development process.  Information about the exact build version is available as
the @code{sys.subversion} variable, a 3-tuple of @code{(interpreter-name, branch-name,
revision-range)}.  For example, at the time of writing my copy of 2.5 was
reporting @code{('CPython', 'trunk', '45313:45315')}.

This information is also available to C extensions via the
@ref{e67,,Py_GetBuildInfo()} function that returns a  string of build information
like this: @code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.   (Contributed by
Barry Warsaw.)

@item 
Another new function, @ref{e68,,sys._current_frames()}, returns the current stack
frames for all running threads as a dictionary mapping thread identifiers to the
topmost stack frame currently active in that thread at the time the function is
called.  (Contributed by Tim Peters.)

@item 
The @code{TarFile} class in the @ref{101,,tarfile} module now has an
@code{extractall()} method that extracts all members from the archive into the
current working directory.  It's also possible to set a different directory as
the extraction target, and to unpack only a subset of the archive's members.

The compression used for a tarfile opened in stream mode can now be autodetected
using the mode @code{'r|*'}. (Contributed by Lars Gustäbel.)

@c patch 918101

@item 
The @ref{10b,,threading} module now lets you set the stack size used when new
threads are created. The @code{stack_size([*size*])} function returns the
currently configured stack size, and supplying the optional @emph{size} parameter
sets a new value.  Not all platforms support changing the stack size, but
Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)

@c Patch 1454481

@item 
The @ref{123,,unicodedata} module has been updated to use version 4.1.0 of the
Unicode character database.  Version 3.2.0 is required  by some specifications,
so it's still available as  @ref{e69,,unicodedata.ucd_3_2_0}.

@item 
New module: the  @ref{12d,,uuid} module generates  universally unique identifiers
(UUIDs) according to 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html}.  The RFC defines several different UUID
versions that are generated from a starting string, from system properties, or
purely randomly.  This module contains a @code{UUID} class and  functions
named @code{uuid1()}, @code{uuid3()}, @code{uuid4()},  and  @code{uuid5()} to
generate different versions of UUID.  (Version 2 UUIDs  are not specified in
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} and are not supported by this module.)

@example
>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
@end example

（由 Ka-Ping Yee 贡献。）

@item 
The @ref{131,,weakref} module's @code{WeakKeyDictionary} and
@code{WeakValueDictionary} types gained new methods for iterating over the
weak references contained in the dictionary.  @code{iterkeyrefs()} and
@code{keyrefs()} methods were added to @code{WeakKeyDictionary}, and
@code{itervaluerefs()} and @code{valuerefs()} were added to
@code{WeakValueDictionary}.  (Contributed by Fred L. Drake, Jr.)

@item 
The @ref{132,,webbrowser} module received a number of enhancements. It's now
usable as a script with @code{python -m webbrowser}, taking a URL as the argument;
there are a number of switches  to control the behaviour (@code{-n} for a new
browser window,  @code{-t} for a new tab).  New module-level functions,
@code{open_new()} and @code{open_new_tab()}, were added  to support this.  The
module's @ref{16f,,open()} function supports an additional feature, an @emph{autoraise}
parameter that signals whether to raise the open window when possible. A number
of additional browsers were added to the supported list such as Firefox, Opera,
Konqueror, and elinks.  (Contributed by Oleg Broytmann and Georg Brandl.)

@c Patch #754022

@item 
The @code{xmlrpclib} module now supports returning  @ref{19f,,datetime} objects
for the XML-RPC date type.  Supply  @code{use_datetime=True} to the @code{loads()}
function or the @code{Unmarshaller} class to enable this feature. (Contributed
by Skip Montanaro.)

@c Patch 1120353

@item 
The @ref{14b,,zipfile} module now supports the ZIP64 version of the  format,
meaning that a .zip archive can now be larger than 4 GiB and can contain
individual files larger than 4 GiB.  (Contributed by Ronald Oussoren.)

@c Patch 1446489

@item 
The @ref{14d,,zlib} module's @code{Compress} and @code{Decompress} objects now
support a @ref{25,,copy()} method that makes a copy of the  object's internal state
and returns a new  @code{Compress} or @code{Decompress} object.
(Contributed by Chris AtLee.)

@c Patch 1435422
@end itemize

@c ======================================================================

@menu
* ctypes 包:: 
* ElementTree 包:: 
* hashlib 包:: 
* sqlite3 包:: 
* wsgiref 包:: 

@end menu

@node ctypes 包,ElementTree 包,,新增，改进和删除的模块
@anchor{whatsnew/2 5 module-ctypes}@anchor{e6a}@anchor{whatsnew/2 5 the-ctypes-package}@anchor{e6b}
@subsubsection ctypes 包


The @ref{2a,,ctypes} package, written by Thomas Heller, has been added  to the
standard library.  @ref{2a,,ctypes} lets you call arbitrary functions  in shared
libraries or DLLs.  Long-time users may remember the @code{dl} module, which
provides functions for loading shared libraries and calling functions in them.
The @ref{2a,,ctypes} package is much fancier.

To load a shared library or DLL, you must create an instance of the
@code{CDLL} class and provide the name or path of the shared library or DLL.
Once that's done, you can call arbitrary functions by accessing them as
attributes of the @code{CDLL} object.

@example
import ctypes

libc = ctypes.CDLL('libc.so.6')
result = libc.printf("Line of output\n")
@end example

Type constructors for the various C types are provided: @code{c_int()},
@code{c_float()}, @code{c_double()}, @code{c_char_p()} (equivalent to @code{char
*}), and so forth.  Unlike Python's types, the C versions are all mutable; you
can assign to their @code{value} attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the corresponding C
types, but for other types you  must call the correct type constructor.  (And I
mean @emph{must};  getting it wrong will often result in the interpreter crashing
with a segmentation fault.)

You shouldn't use @code{c_char_p()} with a Python string when the C function will
be modifying the memory area, because Python strings are  supposed to be
immutable; breaking this rule will cause puzzling bugs.  When you need a
modifiable memory area, use @code{create_string_buffer()}:

@example
s = "this is a string"
buf = ctypes.create_string_buffer(s)
libc.strfry(buf)
@end example

C functions are assumed to return integers, but you can set the @code{restype}
attribute of the function object to  change this:

@example
>>> libc.atof('2.71828')
-1783957616
>>> libc.atof.restype = ctypes.c_double
>>> libc.atof('2.71828')
2.71828
@end example

@ref{2a,,ctypes} also provides a wrapper for Python's C API  as the
@code{ctypes.pythonapi} object.  This object does @emph{not}  release the global
interpreter lock before calling a function, because the lock must be held when
calling into the interpreter's code.   There's a @code{py_object()} type
constructor that will create a  @ref{5bd,,PyObject *} pointer.  A simple usage:

@example
import ctypes

d = @{@}
ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
          ctypes.py_object("abc"),  ctypes.py_object(1))
# d is now @{'abc', 1@}.
@end example

Don't forget to use @code{py_object()}; if it's omitted you end  up with a
segmentation fault.

@ref{2a,,ctypes} has been around for a while, but people still write  and
distribution hand-coded extension modules because you can't rely on
@ref{2a,,ctypes} being present. Perhaps developers will begin to write  Python
wrappers atop a library accessed through @ref{2a,,ctypes} instead of extension
modules, now that @ref{2a,,ctypes} is included with core Python.


@subsubheading 参见



@table @asis

@item @indicateurl{http://starship.python.net/crew/theller/ctypes/}

ctypes的主页，含教程， 参考和常见问题解答。
@end table

@ref{2a,,ctypes} 模块的文档。


@c ======================================================================

@node ElementTree 包,hashlib 包,ctypes 包,新增，改进和删除的模块
@anchor{whatsnew/2 5 module-etree}@anchor{e6c}@anchor{whatsnew/2 5 the-elementtree-package}@anchor{e6d}
@subsubsection ElementTree 包


A subset of Fredrik Lundh's ElementTree library for processing XML has been
added to the standard library as @code{xml.etree}.  The available modules are
@code{ElementTree}, @code{ElementPath}, and @code{ElementInclude} from
ElementTree 1.2.6.    The @code{cElementTree} accelerator module is also
included.

The rest of this section will provide a brief overview of using ElementTree.
Full documentation for ElementTree is available at
@indicateurl{https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm}.

ElementTree represents an XML document as a tree of element nodes. The text
content of the document is stored as the @code{text} and @code{tail}
attributes of  (This is one of the major differences between ElementTree and
the Document Object Model; in the DOM there are many different types of node,
including @code{TextNode}.)

The most commonly used parsing function is @code{parse()}, that takes either a
string (assumed to contain a filename) or a file-like object and returns an
@code{ElementTree} instance:

@example
from xml.etree import ElementTree as ET

tree = ET.parse('ex-1.xml')

feed = urllib.urlopen(
          'http://planet.python.org/rss10.xml')
tree = ET.parse(feed)
@end example

Once you have an @code{ElementTree} instance, you can call its @code{getroot()}
method to get the root @code{Element} node.

There's also an @code{XML()} function that takes a string literal and returns an
@code{Element} node (not an @code{ElementTree}).   This function provides a
tidy way to incorporate XML fragments, approaching the convenience of an XML
literal:

@example
svg = ET.XML("""<svg width="10px" version="1.0">
             </svg>""")
svg.set('height', '320px')
svg.append(elem1)
@end example

Each XML element supports some dictionary-like and some list-like access
methods.  Dictionary-like operations are used to access attribute values, and
list-like operations are used to access child nodes.


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@item

@code{elem[n]}

@tab

返回第n个子元素

@item

@code{elem[m:n]}

@tab

返回第m至第n个子元素的列表。

@item

@code{len(elem)}

@tab

返回子元素的个数

@item

@code{list(elem)}

@tab

返回子元素的列表

@item

@code{elem.append(elem2)}

@tab

将 @emph{elem2} 添加为子级。

@item

@code{elem.insert(index, elem2)}

@tab

在指定位置插入 @emph{elem2} 。

@item

@code{del elem[n]}

@tab

删除第n个子元素

@item

@code{elem.keys()}

@tab

返回属性名称的列表。

@item

@code{elem.get(name)}

@tab

返回 @emph{name} 属性的值。

@item

@code{elem.set(name, value)}

@tab

为 @emph{name} 属性设置新值

@item

@code{elem.attrib}

@tab

检索包含属性的字典。

@item

@code{del elem.attrib[name]}

@tab

删除 元素 @emph{name} 的属性

@end multitable


Comments and processing instructions are also represented as @code{Element}
nodes.  To check if a node is a comment or processing instructions:

@example
if elem.tag is ET.Comment:
    ...
elif elem.tag is ET.ProcessingInstruction:
    ...
@end example

To generate XML output, you should call the @code{ElementTree.write()} method.
Like @code{parse()}, it can take either a string or a file-like object:

@example
# Encoding is US-ASCII
tree.write('output.xml')

# Encoding is UTF-8
f = open('output.xml', 'w')
tree.write(f, encoding='utf-8')
@end example

(Caution: the default encoding used for output is ASCII.  For general XML work,
where an element's name may contain arbitrary Unicode characters, ASCII isn't a
very useful encoding because it will raise an exception if an element's name
contains any characters with values greater than 127.  Therefore, it's best to
specify a different encoding such as UTF-8 that can handle any Unicode
character.)

This section is only a partial description of the ElementTree interfaces. Please
read the package's official documentation for more details.


@subsubheading 参见



@table @asis

@item @indicateurl{https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm}

ElementTree 的官方文档
@end table


@c ======================================================================

@node hashlib 包,sqlite3 包,ElementTree 包,新增，改进和删除的模块
@anchor{whatsnew/2 5 module-hashlib}@anchor{e6e}@anchor{whatsnew/2 5 the-hashlib-package}@anchor{e6f}
@subsubsection hashlib 包


A new @ref{8c,,hashlib} module, written by Gregory P. Smith,  has been added to
replace the @code{md5} and @code{sha} modules.  @ref{8c,,hashlib} adds support for
additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
available, the module uses OpenSSL for fast platform optimized implementations
of algorithms.

The old @code{md5} and @code{sha} modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module's interface is very close
to that of the old modules, but not identical. The most significant difference
is that the constructor functions for creating new hashing objects are named
differently.

@example
# Old versions
h = md5.md5()
h = md5.new()

# New version
h = hashlib.md5()

# Old versions
h = sha.sha()
h = sha.new()

# New version
h = hashlib.sha1()

# Hash that weren't previously available
h = hashlib.sha224()
h = hashlib.sha256()
h = hashlib.sha384()
h = hashlib.sha512()

# Alternative form
h = hashlib.new('md5')          # Provide algorithm as a string
@end example

Once a hash object has been created, its methods are the same as before:
@code{update(string)} hashes the specified string into the  current digest
state, @code{digest()} and @code{hexdigest()} return the digest value as a binary
string or a string of hex digits, and @ref{25,,copy()} returns a new hashing object
with the same digest state.


@subsubheading 参见


@ref{8c,,hashlib} 模块的文档。


@c ======================================================================

@node sqlite3 包,wsgiref 包,hashlib 包,新增，改进和删除的模块
@anchor{whatsnew/2 5 module-sqlite}@anchor{e70}@anchor{whatsnew/2 5 the-sqlite3-package}@anchor{e71}
@subsubsection sqlite3 包


pysqlite 模块 (@indicateurl{http://www.pysqlite.org})，一个针对 SQLite 嵌入式数据库的包装器，已使用包名 @ref{f2,,sqlite3} 被添加到标准库中。

SQLite 是一个C语言库，它可以提供一种轻量级的基于磁盘的数据库，这种数据库不需要独立的服务器进程，也允许需要使用一种非标准的 SQL 查询语言来访问它。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程序原型，然后再迁移到更大的数据库，比如 PostgreSQL 或 Oracle。

pysqlite was written by Gerhard Häring and provides a SQL interface compliant
with the DB-API 2.0 specification described by 
@geindex Python 提高建议; PEP 249
PEP 249@footnote{https://www.python.org/dev/peps/pep-0249}.

If you're compiling the Python source yourself, note that the source tree
doesn't include the SQLite code, only the wrapper module. You'll need to have
the SQLite libraries and headers installed before compiling Python, and the
build process will compile the module when the necessary headers are available.

To use the module, you must first create a @code{Connection} object that
represents the database.  Here the data will be stored in the
@code{/tmp/example} file:

@example
conn = sqlite3.connect('/tmp/example')
@end example

你也可以使用 @code{:memory:} 来创建一个内存中的数据库

Once you have a @code{Connection}, you can create a @code{Cursor}  object
and call its @code{execute()} method to perform SQL commands:

@example
c = conn.cursor()

# Create table
c.execute('@w{'}'create table stocks
(date text, trans text, symbol text,
 qty real, price real)'@w{'}')

# Insert a row of data
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")
@end example

Usually your SQL operations will need to use values from Python variables.  You
shouldn't assemble your query using Python's string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack.

Instead, use the DB-API's parameter substitution.  Put @code{?} as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor's @code{execute()} method.  (Other database modules
may use a different placeholder, such as @code{%s} or @code{:1}.) For example:

@example
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)

# Larger example
for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ):
    c.execute('insert into stocks values (?,?,?,?,?)', t)
@end example

To retrieve data after executing a SELECT statement, you can either  treat the
cursor as an iterator, call the cursor's @code{fetchone()} method to retrieve a
single matching row,  or call @code{fetchall()} to get a list of the matching
rows.

下面是一个使用迭代器形式的例子：

@example
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
>>> for row in c:
...    print row
...
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
>>>
@end example

有关 SQLite 所支持的 SQL 方法的更多信息，请参阅 @indicateurl{https://www.sqlite.org}。


@subsubheading 参见



@table @asis

@item @indicateurl{http://www.pysqlite.org}

pysqlite 的主页

@item @indicateurl{https://www.sqlite.org}

SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数据类型。
@end table

@ref{f2,,sqlite3} 模块的文档。


@table @asis

@geindex Python 提高建议; PEP 249

@item PEP 249@footnote{https://www.python.org/dev/peps/pep-0249} - DB-API 2.0 规范

PEP 由 Marc-André Lemburg 撰写。
@end table


@c ======================================================================

@node wsgiref 包,,sqlite3 包,新增，改进和删除的模块
@anchor{whatsnew/2 5 module-wsgiref}@anchor{e72}@anchor{whatsnew/2 5 the-wsgiref-package}@anchor{e73}
@subsubsection wsgiref 包


The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface
between web servers and Python web applications and is described in 
@geindex Python 提高建议; PEP 333
PEP 333@footnote{https://www.python.org/dev/peps/pep-0333}.
The @ref{135,,wsgiref} package is a reference implementation of the WSGI
specification.

@c XXX should this be in a :pep:`333` section instead?

The package includes a basic HTTP server that will run a WSGI application; this
server is useful for debugging but isn't intended for  production use.  Setting
up a server takes only a few lines of code:

@example
from wsgiref import simple_server

wsgi_app = ...

host = '@w{'}
port = 8000
httpd = simple_server.make_server(host, port, wsgi_app)
httpd.serve_forever()
@end example

@c XXX discuss structure of WSGI applications?

@c XXX provide an example using Django or some other framework?


@subsubheading 参见



@table @asis

@item @indicateurl{http://www.wsgi.org}

WSGI相关资源的核心网站。

@geindex Python 提高建议; PEP 333

@item PEP 333@footnote{https://www.python.org/dev/peps/pep-0333} - Python Web服务器网关接口 v1.0

PEP 由 Phillip J. Eby 撰写
@end table


@c ======================================================================

@node 构建和 C API 的改变<10>,移植到Python 2 5,新增，改进和删除的模块,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 build-and-c-api-changes}@anchor{e74}@anchor{whatsnew/2 5 build-api}@anchor{e75}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
The Python source tree was converted from CVS to Subversion,  in a complex
migration procedure that was supervised and flawlessly carried out by Martin von
Löwis.  The procedure was developed as 
@geindex Python 提高建议; PEP 347
PEP 347@footnote{https://www.python.org/dev/peps/pep-0347}.

@item 
Coverity, a company that markets a source code analysis tool called Prevent,
provided the results of their examination of the Python source code.  The
analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
refcounting problems, often occurring in error-handling code.  See
@indicateurl{https://scan.coverity.com} for the statistics.

@item 
The largest change to the C API came from 
@geindex Python 提高建议; PEP 353
PEP 353@footnote{https://www.python.org/dev/peps/pep-0353}, which modifies the
interpreter to use a @ref{391,,Py_ssize_t} type definition instead of
@code{int}.  See the earlier section @ref{e49,,PEP 353; 使用ssize_t作为索引类型} for a discussion of this
change.

@item 
The design of the bytecode compiler has changed a great deal,  no longer
generating bytecode by traversing the parse tree.  Instead the parse tree is
converted to an abstract syntax tree (or AST), and it is  the abstract syntax
tree that's traversed to produce the bytecode.

It's possible for Python code to obtain AST objects by using the
@ref{2ee,,compile()} built-in and specifying @code{_ast.PyCF_ONLY_AST} as the value of
the  @emph{flags} parameter:

@example
from _ast import PyCF_ONLY_AST
ast = compile("""a=0
for i in range(10):
    a += i
""", "<string>", 'exec', PyCF_ONLY_AST)

assignment = ast.body[0]
for_loop = ast.body[1]
@end example

No official documentation has been written for the AST code yet, but 
@geindex Python 提高建议; PEP 339
PEP 339@footnote{https://www.python.org/dev/peps/pep-0339}
discusses the design.  To start learning about the code, read the definition of
the various AST nodes in @code{Parser/Python.asdl}.  A Python script reads this
file and generates a set of C structure definitions in
@code{Include/Python-ast.h}.  The @code{PyParser_ASTFromString()} and
@code{PyParser_ASTFromFile()}, defined in @code{Include/pythonrun.h}, take
Python source as input and return the root of an AST representing the contents.
This AST can then be turned into a code object by @code{PyAST_Compile()}.  For
more information, read the source code, and then ask questions on python-dev.

The AST code was developed under Jeremy Hylton's management, and implemented by
(in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
Schemenauer, plus the participants in a number of AST sprints at conferences
such as PyCon.

@c List of names taken from Jeremy's python-dev post at

@c https://mail.python.org/pipermail/python-dev/2005-October/057500.html

@item 
Evan Jones's patch to obmalloc, first described in a talk at PyCon DC 2005,
was applied.  Python 2.4 allocated small objects in 256K-sized arenas, but never
freed arenas.  With this patch, Python will free arenas when they're empty.  The
net effect is that on some platforms, when you allocate many objects, Python's
memory usage may actually drop when you delete them and the memory may be
returned to the operating system.  (Implemented by Evan Jones, and reworked by
Tim Peters.)

Note that this change means extension modules must be more careful when
allocating memory.  Python's API has many different functions for allocating
memory that are grouped into families.  For example, @ref{607,,PyMem_Malloc()},
@ref{a59,,PyMem_Realloc()}, and @ref{e76,,PyMem_Free()} are one family that allocates
raw memory, while @ref{609,,PyObject_Malloc()}, @ref{e77,,PyObject_Realloc()}, and
@ref{606,,PyObject_Free()} are another family that's supposed to be used for
creating Python objects.

Previously these different families all reduced to the platform's
@code{malloc()} and @code{free()} functions.  This meant  it didn't matter if
you got things wrong and allocated memory with the @code{PyMem()} function but
freed it with the @ref{5bd,,PyObject()} function.  With 2.5's changes to obmalloc,
these families now do different things and mismatches will probably result in a
segfault.  You should carefully test your C extension modules with Python 2.5.

@item 
The built-in set types now have an official C API.  Call @ref{e78,,PySet_New()}
and @ref{e79,,PyFrozenSet_New()} to create a new set, @ref{e7a,,PySet_Add()} and
@ref{e7b,,PySet_Discard()} to add and remove elements, and @ref{e7c,,PySet_Contains()}
and @ref{e7d,,PySet_Size()} to examine the set's state. (Contributed by Raymond
Hettinger.)

@item 
C code can now obtain information about the exact revision of the Python
interpreter by calling the  @ref{e67,,Py_GetBuildInfo()} function that returns a
string of build information like this: @code{"trunk:45355:45356M, Apr 13 2006,
07:42:19"}.   (Contributed by Barry Warsaw.)

@item 
Two new macros can be used to indicate C functions that are local to the
current file so that a faster calling convention can be used.
@code{Py_LOCAL(type)} declares the function as returning a value of the
specified @emph{type} and uses a fast-calling qualifier.
@code{Py_LOCAL_INLINE(type)} does the same thing and also requests the
function be inlined.  If @code{PY_LOCAL_AGGRESSIVE()} is defined before
@code{python.h} is included, a set of more aggressive optimizations are enabled
for the module; you should benchmark the results to find out if these
optimizations actually make the code faster.  (Contributed by Fredrik Lundh at
the NeedForSpeed sprint.)

@item 
@code{PyErr_NewException(name, base, dict)} can now accept a tuple of base
classes as its @emph{base} argument.  (Contributed by Georg Brandl.)

@item 
The @code{PyErr_Warn()} function for issuing warnings is now deprecated in
favour of @code{PyErr_WarnEx(category, message, stacklevel)} which lets you
specify the number of stack frames separating this function and the caller.  A
@emph{stacklevel} of 1 is the function calling @ref{e7e,,PyErr_WarnEx()}, 2 is the
function above that, and so forth.  (Added by Neal Norwitz.)

@item 
The CPython interpreter is still written in C, but  the code can now be
compiled with a C++ compiler without errors.   (Implemented by Anthony Baxter,
Martin von Löwis, Skip Montanaro.)

@item 
The @code{PyRange_New()} function was removed.  It was never documented, never
used in the core code, and had dangerously lax error checking.  In the unlikely
case that your extensions were using it, you can replace it by something like
the following:

@example
range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                              start, stop, step);
@end example
@end itemize

@c ======================================================================

@menu
* Port-Specific Changes:: 

@end menu

@node Port-Specific Changes,,,构建和 C API 的改变<10>
@anchor{whatsnew/2 5 port-specific-changes}@anchor{e7f}@anchor{whatsnew/2 5 ports}@anchor{e80}
@subsubsection Port-Specific Changes



@itemize *

@item 
MacOS X (10.3 and higher): dynamic loading of modules now uses the
@code{dlopen()} function instead of MacOS-specific functions.

@item 
MacOS X: an @code{--enable-universalsdk} switch was added to the
@code{configure} script that compiles the interpreter as a universal binary
able to run on both PowerPC and Intel processors. (Contributed by Ronald
Oussoren; bpo-2573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2573}.)

@item 
Windows: @code{.dll} is no longer supported as a filename extension for
extension modules.  @code{.pyd} is now the only filename extension that will be
searched for.
@end itemize

@c ======================================================================

@node 移植到Python 2 5,致谢<3>,构建和 C API 的改变<10>,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 porting}@anchor{e81}@anchor{whatsnew/2 5 porting-to-python-2-5}@anchor{e82}
@subsection 移植到Python 2.5


This section lists previously described changes that may require changes to your
code:


@itemize *

@item 
ASCII is now the default encoding for modules.  It's now  a syntax error if a
module contains string literals with 8-bit characters but doesn't have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.

@item 
Previously, the @code{gi_frame} attribute of a generator was always a frame
object.  Because of the 
@geindex Python 提高建议; PEP 342
PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} changes described in section @ref{e33,,PEP 342; 生成器的新特性},
it's now possible for @code{gi_frame} to be @code{None}.

@item 
A new warning, @ref{e54,,UnicodeWarning}, is triggered when  you attempt to
compare a Unicode string and an 8-bit string that can't be converted to Unicode
using the default ASCII encoding.  Previously such comparisons would raise a
@ref{332,,UnicodeDecodeError} exception.

@item 
Library: the @ref{29,,csv} module is now stricter about multi-line quoted fields.
If your files contain newlines embedded within fields, the input should be split
into lines in a manner which preserves the newline characters.

@item 
Library: the @ref{a9,,locale} module's  @ref{5de,,format()} function's would
previously  accept any string as long as no more than one %char specifier
appeared.  In Python 2.5, the argument must be exactly one %char specifier with
no surrounding text.

@item 
Library: The @ref{ca,,pickle} and @code{cPickle} modules no longer accept a
return value of @code{None} from the @ref{2d7,,__reduce__()} method; the method must
return a tuple of arguments instead.  The modules also no longer accept the
deprecated @emph{bin} keyword parameter.

@item 
Library: The @code{SimpleXMLRPCServer} and @code{DocXMLRPCServer}  classes now
have a @code{rpc_paths} attribute that constrains XML-RPC operations to a
limited set of URL paths; the default is to allow only @code{'/'} and @code{'/RPC2'}.
Setting  @code{rpc_paths} to @code{None} or an empty tuple disables  this path
checking.

@item 
C API: Many functions now use @ref{391,,Py_ssize_t}  instead of @code{int} to
allow processing more data on 64-bit machines.  Extension code may need to make
the same change to avoid warnings and to support 64-bit machines.  See the
earlier section @ref{e49,,PEP 353; 使用ssize_t作为索引类型} for a discussion of this change.

@item 
C API:  The obmalloc changes mean that  you must be careful to not mix usage
of the @code{PyMem_*()} and @code{PyObject_*()} families of functions. Memory
allocated with  one family's @code{*_Malloc()} must be  freed with the
corresponding family's @code{*_Free()} function.
@end itemize

@c ======================================================================

@node 致谢<3>,,移植到Python 2 5,Python 2 5 有什么新变化
@anchor{whatsnew/2 5 acknowledgements}@anchor{e83}
@subsection 致谢


作者感谢以下人员对本文各种草稿给予的建议，更正和协助： Georg Brandl, Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W. Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.

@node Python 2 4 有什么新变化,Python 2 3 有什么新变化,Python 2 5 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 4 doc}@anchor{e84}@anchor{whatsnew/2 4 what-s-new-in-python-2-4}@anchor{e85}
@section Python 2.4 有什么新变化


@*作者: 
A.M. Kuchling


@c $Id: whatsnew24.tex 54632 2007-03-31 11:59:54Z georg.brandl $

@c Don't write extensive text for new sections; I'll do that.

@c Feel free to add commented-out reminders of things that need

@c to be covered.  --amk

本文介绍了2005年3月30日发布的 Python 2.4.1 的新功能。

Python 2.4 is a medium-sized release.  It doesn't introduce as many changes as
the radical Python 2.2, but introduces more features than the conservative 2.3
release.  The most significant new language features are function decorators and
generator expressions; most other changes are to the standard library.

According to the CVS change logs, there were 481 patches applied and 502 bugs
fixed between Python 2.3 and 2.4.  Both figures are likely to be underestimates.

This article doesn't attempt to provide a complete specification of every single
new feature, but instead provides a brief introduction to each feature.  For
full details, you should refer to the documentation for Python 2.4, such as the
Python Library Reference and the Python Reference Manual.  Often you will be
referred to the PEP for a particular new feature for explanations of the
implementation and design rationale.

@c ======================================================================

@menu
* PEP 218; 内置集合对象: PEP 218 内置集合对象. 
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数. 
* PEP 289; 生成器表达式: PEP 289 生成器表达式. 
* PEP 292; 更简单的字符串替换: PEP 292 更简单的字符串替换. 
* PEP 318; 函数和方法的装饰器: PEP 318 函数和方法的装饰器. 
* PEP 322; 反向迭代: PEP 322 反向迭代. 
* PEP 324; 新的子进程模块: PEP 324 新的子进程模块. 
* PEP 327; 十进制数据类型: PEP 327 十进制数据类型. 
* PEP 328; 多行导入: PEP 328 多行导入. 
* PEP 331; Locale-Independent Float/String Conversions: PEP 331 Locale-Independent Float/String Conversions. 
* 其他语言特性修改: 其他语言特性修改<13>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<3>. 
* 构建和 C API 的改变: 构建和 C API 的改变<11>. 
* 移植到 Python 2.4: 移植到 Python 2 4. 
* 致谢: 致谢<4>. 

@end menu

@node PEP 218 内置集合对象,PEP 237 统一长整数和整数,,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-218-built-in-set-objects}@anchor{e86}
@subsection PEP 218: 内置集合对象


Python 2.3 introduced the @code{sets} module.  C implementations of set data
types have now been added to the Python core as two new built-in types,
@code{set(iterable)} and @code{frozenset(iterable)}.  They provide high speed
operations for membership testing, for eliminating duplicates from sequences,
and for mathematical operations like unions, intersections, differences, and
symmetric differences.

@example
>>> a = set('abracadabra')              # form a set from a string
>>> 'z' in a                            # fast membership testing
False
>>> a                                   # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> '@w{'}.join(a)                          # convert back into a string
'arbcd'

>>> b = set('alacazam')                 # form a second set
>>> a - b                               # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                               # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                               # letters in both a and b
set(['a', 'c'])
>>> a ^ b                               # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

>>> a.add('z')                          # add a new element
>>> a.update('wxy')                     # add multiple new elements
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
>>> a.remove('x')                       # take one element out
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
@end example

The @ref{1f8,,frozenset()} type is an immutable version of @ref{1f7,,set()}. Since it is
immutable and hashable, it may be used as a dictionary key or as a member of
another set.

The @code{sets} module remains in the standard library, and may be useful if you
wish to subclass the @code{Set} or @code{ImmutableSet} classes.  There are
currently no plans to deprecate the module.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 218

@item PEP 218@footnote{https://www.python.org/dev/peps/pep-0218} - 添加内置Set对象类型

最初由 Greg Wilson 提出，由 Raymond Hettinger 最终实现。
@end table


@c ======================================================================

@node PEP 237 统一长整数和整数,PEP 289 生成器表达式,PEP 218 内置集合对象,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-237-unifying-long-integers-and-integers}@anchor{e87}
@subsection PEP 237: 统一长整数和整数


The lengthy transition process for this PEP, begun in Python 2.2, takes another
step forward in Python 2.4.  In 2.3, certain integer operations that would
behave differently after int/long unification triggered @ref{43e,,FutureWarning}
warnings and returned values limited to 32 or 64 bits (depending on your
platform).  In 2.4, these expressions no longer produce a warning and instead
produce a different result that's usually a long integer.

The problematic expressions are primarily left shifts and lengthy hexadecimal
and octal constants.  For example, @code{2 << 32} results in a warning in 2.3,
evaluating to 0 on 32-bit platforms.  In Python 2.4, this expression now returns
the correct answer, 8589934592.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 237

@item PEP 237@footnote{https://www.python.org/dev/peps/pep-0237} - 统一长整数和整数

原始PEP由 Moshe Zadka 和 GvR 撰写，2.4 的变更由 Kalle Svensson 实现。
@end table


@c ======================================================================

@node PEP 289 生成器表达式,PEP 292 更简单的字符串替换,PEP 237 统一长整数和整数,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-289-generator-expressions}@anchor{e88}
@subsection PEP 289: 生成器表达式


The iterator feature introduced in Python 2.2 and the @ref{a3,,itertools} module
make it easier to write programs that loop through large data sets without
having the entire data set in memory at one time.  List comprehensions don't fit
into this picture very well because they produce a Python list object containing
all of the items.  This unavoidably pulls all of the objects into memory, which
can be a problem if your data set is very large.  When trying to write a
functionally-styled program, it would be natural to write something like:

@example
links = [link for link in get_all_links() if not link.followed]
for link in links:
    ...
@end example

代替：

@example
for link in get_all_links():
    if link.followed:
        continue
    ...
@end example

The first form is more concise and perhaps more readable, but if you're dealing
with a large number of link objects you'd have to write the second form to avoid
having all link objects in memory at the same time.

Generator expressions work similarly to list comprehensions but don't
materialize the entire list; instead they create a generator that will return
elements one by one.  The above example could be written as:

@example
links = (link for link in get_all_links() if not link.followed)
for link in links:
    ...
@end example

Generator expressions always have to be written inside parentheses, as in the
above example.  The parentheses signalling a function call also count, so if you
want to create an iterator that will be immediately passed to a function you
could write:

@example
print sum(obj.count for obj in list_all_objects())
@end example

Generator expressions differ from list comprehensions in various small ways.
Most notably, the loop variable (@emph{obj} in the above example) is not accessible
outside of the generator expression.  List comprehensions leave the variable
assigned to its last value; future versions of Python will change this, making
list comprehensions match generator expressions in this respect.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 289

@item PEP 289@footnote{https://www.python.org/dev/peps/pep-0289} - 生成器表达式

Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts
steered by Hye-Shik Chang.
@end table


@c ======================================================================

@node PEP 292 更简单的字符串替换,PEP 318 函数和方法的装饰器,PEP 289 生成器表达式,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-292-simpler-string-substitutions}@anchor{e89}
@subsection PEP 292: 更简单的字符串替换


Some new classes in the standard library provide an alternative mechanism for
substituting variables into strings; this style of substitution may be better
for applications where untrained users need to edit templates.

按名称替换变量的常用方式是 @code{%} 运算符:

@example
>>> '%(page)i: %(title)s' % @{'page':2, 'title': 'The Best of Times'@}
'2: The Best of Times'
@end example

When writing the template string, it can be easy to forget the @code{i} or @code{s}
after the closing parenthesis.  This isn't a big problem if the template is in a
Python module, because you run the code, get an "Unsupported format character"
@ref{16d,,ValueError}, and fix the problem.  However, consider an application such
as Mailman where template strings or translations are being edited by users who
aren't aware of the Python language.  The format string's syntax is complicated
to explain to such users, and if they make a mistake, it's difficult to provide
helpful feedback to them.

PEP 292 adds a @code{Template} class to the @ref{f6,,string} module that uses
@code{$} to indicate a substitution:

@example
>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute(@{'page':2, 'title': 'The Best of Times'@})
'2: The Best of Times'
@end example

If a key is missing from the dictionary, the @code{substitute()} method will
raise a @ref{3f1,,KeyError}.  There's also a @code{safe_substitute()} method that
ignores missing keys:

@example
>>> t = string.Template('$page: $title')
>>> t.safe_substitute(@{'page':3@})
'3: $title'
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 292

@item PEP 292@footnote{https://www.python.org/dev/peps/pep-0292} - 更简单的字符串替换

由 Barry Warsaw 撰写并实现
@end table


@c ======================================================================

@node PEP 318 函数和方法的装饰器,PEP 322 反向迭代,PEP 292 更简单的字符串替换,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-318-decorators-for-functions-and-methods}@anchor{e8a}
@subsection PEP 318: 函数和方法的装饰器


Python 2.2 extended Python's object model by adding static methods and class
methods, but it didn't extend Python's syntax to provide any new way of defining
static or class methods.  Instead, you had to write a @ref{e8b,,def} statement
in the usual way, and pass the resulting method to a @ref{311,,staticmethod()} or
@ref{310,,classmethod()} function that would wrap up the function as a method of the
new type. Your code would look like this:

@example
class C:
   def meth (cls):
       ...

   meth = classmethod(meth)   # Rebind name to wrapped-up class method
@end example

If the method was very long, it would be easy to miss or forget the
@ref{310,,classmethod()} invocation after the function body.

The intention was always to add some syntax to make such definitions more
readable, but at the time of 2.2's release a good syntax was not obvious.  Today
a good syntax @emph{still} isn't obvious but users are asking for easier access to
the feature; a new syntactic feature has been added to meet this need.

The new feature is called "function decorators".  The name comes from the idea
that @ref{310,,classmethod()}, @ref{311,,staticmethod()}, and friends are storing
additional information on a function object; they're @emph{decorating} functions with
more details.

The notation borrows from Java and uses the @code{'@@'} character as an indicator.
Using the new syntax, the example above would be written:

@example
class C:

   @@classmethod
   def meth (cls):
       ...
@end example

The @code{@@classmethod} is shorthand for the @code{meth=classmethod(meth)} assignment.
More generally, if you have the following:

@example
@@A
@@B
@@C
def f ():
    ...
@end example

它等价于以下无装饰器的代码:

@example
def f(): ...
f = A(B(C(f)))
@end example

Decorators must come on the line before a function definition, one decorator per
line, and can't be on the same line as the def statement, meaning that @code{@@A def
f(): ...} is illegal.  You can only decorate function definitions, either at
the module level or inside a class; you can't decorate class definitions.

A decorator is just a function that takes the function to be decorated as an
argument and returns either the same function or some new object.  The return
value of the decorator need not be callable (though it typically is), unless
further decorators will be applied to the result.  It's easy to write your own
decorators.  The following simple example just sets an attribute on the function
object:

@example
>>> def deco(func):
...    func.attr = 'decorated'
...    return func
...
>>> @@deco
... def f(): pass
...
>>> f
<function f at 0x402ef0d4>
>>> f.attr
'decorated'
>>>
@end example

As a slightly more realistic example, the following decorator checks that the
supplied argument is an integer:

@example
def require_int (func):
    def wrapper (arg):
        assert isinstance(arg, int)
        return func(arg)

    return wrapper

@@require_int
def p1 (arg):
    print arg

@@require_int
def p2(arg):
    print arg*2
@end example

An example in 
@geindex Python 提高建议; PEP 318
PEP 318@footnote{https://www.python.org/dev/peps/pep-0318} contains a fancier version of this idea that lets you
both specify the required type and check the returned type.

Decorator functions can take arguments.  If arguments are supplied, your
decorator function is called with only those arguments and must return a new
decorator function; this function must take a single function and return a
function, as previously described.  In other words, @code{@@A @@B @@C(args)} becomes:

@example
def f(): ...
_deco = C(args)
f = A(B(_deco(f)))
@end example

Getting this right can be slightly brain-bending, but it's not too difficult.

A small related change makes the @code{func_name} attribute of functions
writable.  This attribute is used to display function names in tracebacks, so
decorators should change the name of any new function that's constructed and
returned.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 318

@item PEP 318@footnote{https://www.python.org/dev/peps/pep-0318} - 函数、方法和类的装饰器

Written  by Kevin D. Smith, Jim Jewett, and Skip Montanaro.  Several people
wrote patches implementing function decorators, but the one that was actually
checked in was patch #979728, written by Mark Russell.

@item @indicateurl{https://wiki.python.org/moin/PythonDecoratorLibrary}

该Wiki页面包含几个装饰器示例。
@end table


@c ======================================================================

@node PEP 322 反向迭代,PEP 324 新的子进程模块,PEP 318 函数和方法的装饰器,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-322-reverse-iteration}@anchor{e8c}
@subsection PEP 322: 反向迭代


A new built-in function, @code{reversed(seq)}, takes a sequence and returns an
iterator that loops over the elements of the sequence  in reverse order.

@example
>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1
@end example

Compared to extended slicing, such as @code{range(1,4)[::-1]}, @ref{2cd,,reversed()} is
easier to read, runs faster, and uses substantially less memory.

Note that @ref{2cd,,reversed()} only accepts sequences, not arbitrary iterators.  If
you want to reverse an iterator, first convert it to  a list with @ref{1f9,,list()}.

@example
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
root:*:0:0:System Administrator:/var/root:/bin/tcsh
  ...
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 322

@item PEP 322@footnote{https://www.python.org/dev/peps/pep-0322} - 反向迭代

由 Raymond Hettinger 撰写并实现。
@end table


@c ======================================================================

@node PEP 324 新的子进程模块,PEP 327 十进制数据类型,PEP 322 反向迭代,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-324-new-subprocess-module}@anchor{e8d}
@subsection PEP 324: 新的子进程模块


The standard library provides a number of ways to execute a subprocess, offering
different features and different levels of complexity.
@code{os.system(command)} is easy to use, but slow (it runs a shell process
which executes the command) and dangerous (you have to be careful about escaping
the shell's metacharacters).  The @code{popen2} module offers classes that can
capture standard output and standard error from the subprocess, but the naming
is confusing.  The @ref{f9,,subprocess} module cleans  this up, providing a unified
interface that offers all the features you might need.

Instead of @code{popen2}'s collection of classes, @ref{f9,,subprocess} contains a
single class called @code{Popen}  whose constructor supports a number of
different keyword arguments.

@example
class Popen(args, bufsize=0, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=False, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0):
@end example

@emph{args} is commonly a sequence of strings that will be the arguments to the
program executed as the subprocess.  (If the @emph{shell} argument is true, @emph{args}
can be a string which will then be passed on to the shell for interpretation,
just as @ref{e8e,,os.system()} does.)

@emph{stdin}, @emph{stdout}, and @emph{stderr} specify what the subprocess's input, output, and
error streams will be.  You can provide a file object or a file descriptor, or
you can use the constant @code{subprocess.PIPE} to create a pipe between the
subprocess and the parent.

@geindex universal newlines; What's new

此构造器有几个方便的选项:


@itemize *

@item 
@emph{close_fds} requests that all file descriptors be closed before running the
subprocess.

@item 
@emph{cwd} specifies the working directory in which the subprocess will be executed
(defaulting to whatever the parent's working directory is).

@item 
@emph{env} is a dictionary specifying environment variables.

@item 
@emph{preexec_fn} is a function that gets called before the child is started.

@item 
@emph{universal_newlines} opens the child's input and output using Python's
@ref{6f5,,universal newlines} feature.
@end itemize

Once you've created the @code{Popen} instance,  you can call its @code{wait()}
method to pause until the subprocess has exited, @code{poll()} to check if it's
exited without pausing,  or @code{communicate(data)} to send the string @emph{data}
to the subprocess's standard input.   @code{communicate(data)}  then reads any
data that the subprocess has sent to its standard output  or standard error,
returning a tuple @code{(stdout_data, stderr_data)}.

@code{call()} is a shortcut that passes its arguments along to the @code{Popen}
constructor, waits for the command to complete, and returns the status code of
the subprocess.  It can serve as a safer analog to @ref{e8e,,os.system()}:

@example
sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
if sts == 0:
    # Success
    ...
else:
    # dpkg returned an error
    ...
@end example

The command is invoked without use of the shell.  If you really do want to  use
the shell, you can add @code{shell=True} as a keyword argument and provide a string
instead of a sequence:

@example
sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)
@end example

The PEP takes various examples of shell and Python code and shows how they'd be
translated into Python code that uses @ref{f9,,subprocess}.  Reading this section
of the PEP is highly recommended.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 324

@item PEP 324@footnote{https://www.python.org/dev/peps/pep-0324} - 子进程 - 新的进程模块

由 Peter Åstrand 在 Fredrik Lundh 等人的协助下撰写并实现。
@end table


@c ======================================================================

@node PEP 327 十进制数据类型,PEP 328 多行导入,PEP 324 新的子进程模块,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-327-decimal-data-type}@anchor{e8f}
@subsection PEP 327: 十进制数据类型


Python has always supported floating-point (FP) numbers, based on the underlying
C @code{double} type, as a data type.  However, while most programming
languages provide a floating-point type, many people (even programmers) are
unaware that floating-point numbers don't represent certain decimal fractions
accurately.  The new @code{Decimal} type can represent these fractions
accurately, up to a user-specified precision limit.

@menu
* 为什么需要十进制？:: 
* Decimal 类型:: 
* Context 类型:: 

@end menu

@node 为什么需要十进制？,Decimal 类型,,PEP 327 十进制数据类型
@anchor{whatsnew/2 4 why-is-decimal-needed}@anchor{e90}
@subsubsection 为什么需要十进制？


The limitations arise from the representation used for floating-point numbers.
FP numbers are made up of three components:


@itemize *

@item 
The sign, which is positive or negative.

@item 
The mantissa, which is a single-digit binary number   followed by a fractional
part.  For example, @code{1.01} in base-2 notation is @code{1 + 0/2 + 1/4}, or 1.25 in
decimal notation.

@item 
The exponent, which tells where the decimal point is located in the number
represented.
@end itemize

For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in
binary), and an exponent of 0 (the decimal point doesn't need to be shifted).
The number 5 has the same sign and mantissa, but the exponent is 2 because the
mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals
5.

Modern systems usually provide floating-point support that conforms to a
standard called IEEE 754.  C's @code{double} type is usually implemented as a
64-bit IEEE 754 number, which uses 52 bits of space for the mantissa.  This
means that numbers can only be specified to 52 bits of precision.  If you're
trying to represent numbers whose expansion repeats endlessly, the expansion is
cut off after 52 bits. Unfortunately, most software needs to produce output in
base 10, and common fractions in base 10 are often repeating decimals in binary.
For example, 1.1 decimal is binary @code{1.0001100110011 ...}; .1 = 1/16 + 1/32 +
1/256 plus an infinite number of additional terms.  IEEE 754 has to chop off
that infinitely repeated decimal after 52 digits, so the representation is
slightly inaccurate.

Sometimes you can see this inaccuracy when the number is printed:

@example
>>> 1.1
1.1000000000000001
@end example

The inaccuracy isn't always visible when you print the number because the
FP-to-decimal-string conversion is provided by the C library, and most C libraries try
to produce sensible output.  Even if it's not displayed, however, the inaccuracy
is still there and subsequent operations can magnify the error.

For many applications this doesn't matter.  If I'm plotting points and
displaying them on my monitor, the difference between 1.1 and 1.1000000000000001
is too small to be visible.  Reports often limit output to a certain number of
decimal places, and if you round the number to two or three or even eight
decimal places, the error is never apparent.  However, for applications where it
does matter,  it's a lot of work to implement your own custom arithmetic
routines.

因此，创建了 @code{Decimal} 类型。

@node Decimal 类型,Context 类型,为什么需要十进制？,PEP 327 十进制数据类型
@anchor{whatsnew/2 4 the-decimal-type}@anchor{e91}
@subsubsection @code{Decimal} 类型


A new module, @ref{35,,decimal}, was added to Python's standard library.  It
contains two classes, @code{Decimal} and @code{Context}.  @code{Decimal}
instances represent numbers, and @code{Context} instances are used to wrap up
various settings such as the precision and default rounding mode.

@code{Decimal} instances are immutable, like regular Python integers and FP
numbers; once it's been created, you can't change the value an instance
represents.  @code{Decimal} instances can be created from integers or
strings:

@example
>>> import decimal
>>> decimal.Decimal(1972)
Decimal("1972")
>>> decimal.Decimal("1.1")
Decimal("1.1")
@end example

You can also provide tuples containing the sign, the mantissa represented  as a
tuple of decimal digits, and the exponent:

@example
>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal("-14.75")
@end example

Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is
negative.

Converting from floating-point numbers poses a bit of a problem: should the FP
number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1
plus whatever inaccuracies are introduced? The decision was to dodge the issue
and leave such a conversion out of the API.  Instead, you should convert the
floating-point number into a string using the desired precision and pass the
string to the @code{Decimal} constructor:

@example
>>> f = 1.1
>>> decimal.Decimal(str(f))
Decimal("1.1")
>>> decimal.Decimal('%.12f' % f)
Decimal("1.100000000000")
@end example

Once you have @code{Decimal} instances, you can perform the usual mathematical
operations on them.  One limitation: exponentiation requires an integer
exponent:

@example
>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
>>> a ** 2
Decimal("1275.9184")
>>> a**b
Traceback (most recent call last):
  ...
decimal.InvalidOperation: x ** (non-integer)
@end example

You can combine @code{Decimal} instances with integers, but not with
floating-point numbers:

@example
>>> a + 4
Decimal("39.72")
>>> a + 4.5
Traceback (most recent call last):
  ...
TypeError: You can interact Decimal only with int, long or Decimal data types.
>>>
@end example

@code{Decimal} numbers can be used with the @ref{b1,,math} and @ref{18,,cmath}
modules, but note that they'll be immediately converted to  floating-point
numbers before the operation is performed, resulting in a possible loss of
precision and accuracy.  You'll also get back a regular floating-point number
and not a @code{Decimal}.

@example
>>> import math, cmath
>>> d = decimal.Decimal('123456789012.345')
>>> math.sqrt(d)
351364.18288201344
>>> cmath.sqrt(-d)
351364.18288201344j
@end example

@code{Decimal} instances have a @code{sqrt()} method that returns a
@code{Decimal}, but if you need other things such as trigonometric functions
you'll have to implement them.

@example
>>> d.sqrt()
Decimal("351364.1828820134592177245001")
@end example

@node Context 类型,,Decimal 类型,PEP 327 十进制数据类型
@anchor{whatsnew/2 4 the-context-type}@anchor{e92}
@subsubsection @code{Context} 类型


Instances of the @code{Context} class encapsulate several settings for
decimal operations:


@itemize *

@item 
@code{prec} is the precision, the number of decimal places.

@item 
@code{rounding} specifies the rounding mode.  The @ref{35,,decimal} module has
constants for the various possibilities: @code{ROUND_DOWN},
@code{ROUND_CEILING},  @code{ROUND_HALF_EVEN}, and various others.

@item 
@code{traps} is a dictionary specifying what happens on encountering certain
error conditions: either  an exception is raised or  a value is returned.  Some
examples of error conditions are division by zero, loss of precision, and
overflow.
@end itemize

There's a thread-local default context available by calling @code{getcontext()};
you can change the properties of this context to alter the default precision,
rounding, or trap handling.  The following example shows the effect of changing
the precision of the default context:

@example
>>> decimal.getcontext().prec
28
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 9
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.142857143")
@end example

The default action for error conditions is selectable; the module can either
return a special value such as infinity or not-a-number, or exceptions can be
raised:

@example
>>> decimal.Decimal(1) / decimal.Decimal(0)
Traceback (most recent call last):
  ...
decimal.DivisionByZero: x / 0
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal("Infinity")
>>>
@end example

The @code{Context} instance also has various methods for formatting  numbers
such as @code{to_eng_string()} and @code{to_sci_string()}.

For more information, see the documentation for the @ref{35,,decimal} module, which
includes a quick-start tutorial and a reference.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 327

@item PEP 327@footnote{https://www.python.org/dev/peps/pep-0327} - 十进数据类型

由 Facundo Batista 撰写，由Facundo Batista, Eric Price, Raymond Hettinger, Aahz 和 Tim Peters 实现。

@item @indicateurl{http://www.lahey.com/float.htm}

The article uses Fortran code to illustrate many of the problems that
floating-point inaccuracy can cause.

@item @indicateurl{http://speleotrove.com/decimal/}

A description of a decimal-based representation.  This representation is being
proposed as a standard, and underlies the new Python decimal type.  Much of this
material was written by Mike Cowlishaw, designer of the Rexx language.
@end table


@c ======================================================================

@node PEP 328 多行导入,PEP 331 Locale-Independent Float/String Conversions,PEP 327 十进制数据类型,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-328-multi-line-imports}@anchor{e93}
@subsection PEP 328: 多行导入


One language change is a small syntactic tweak aimed at making it easier to
import many names from a module.  In a @code{from module import names} statement,
@emph{names} is a sequence of names separated by commas.  If the sequence is  very
long, you can either write multiple imports from the same module, or you can use
backslashes to escape the line endings like this:

@example
from SimpleXMLRPCServer import SimpleXMLRPCServer,\
            SimpleXMLRPCRequestHandler,\
            CGIXMLRPCRequestHandler,\
            resolve_dotted_attribute
@end example

The syntactic change in Python 2.4 simply allows putting the names within
parentheses.  Python ignores newlines within a parenthesized expression, so the
backslashes are no longer needed:

@example
from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                SimpleXMLRPCRequestHandler,
                                CGIXMLRPCRequestHandler,
                                resolve_dotted_attribute)
@end example

The PEP also proposes that all @ref{cef,,import} statements be absolute imports,
with a leading @code{.} character to indicate a relative import.  This part of the
PEP was not implemented for Python 2.4, but was completed for Python 2.5.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 328

@item PEP 328@footnote{https://www.python.org/dev/peps/pep-0328} - 导入：多行和绝对/相对导入

由 Aahz 撰写，多行导入由 Dima Dorfman 实现。
@end table


@c ======================================================================

@node PEP 331 Locale-Independent Float/String Conversions,其他语言特性修改<13>,PEP 328 多行导入,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 pep-331-locale-independent-float-string-conversions}@anchor{e94}
@subsection PEP 331: Locale-Independent Float/String Conversions


The @ref{a9,,locale} modules lets Python software select various conversions and
display conventions that are localized to a particular country or language.
However, the module was careful to not change the numeric locale because various
functions in Python's implementation required that the numeric locale remain set
to the @code{'C'} locale.  Often this was because the code was using the C
library's @code{atof()} function.

Not setting the numeric locale caused trouble for extensions that used third-party
C libraries, however, because they wouldn't have the correct locale set.
The motivating example was GTK+, whose user interface widgets weren't displaying
numbers in the current locale.

The solution described in the PEP is to add three new functions to the Python
API that perform ASCII-only conversions, ignoring the locale setting:


@itemize *

@item 
@code{PyOS_ascii_strtod(str, ptr)}  and @code{PyOS_ascii_atof(str, ptr)}
both convert a string to a C @code{double}.

@item 
@code{PyOS_ascii_formatd(buffer, buf_len, format, d)} converts a
@code{double} to an ASCII string.
@end itemize

The code for these functions came from the GLib library
(@indicateurl{https://developer.gnome.org/glib/stable/}), whose developers kindly
relicensed the relevant functions and donated them to the Python Software
Foundation.  The @ref{a9,,locale} module  can now change the numeric locale,
letting extensions such as GTK+  produce the correct results.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 331

@item PEP 331@footnote{https://www.python.org/dev/peps/pep-0331} - Locale-Independent Float/String Conversions

由Christian R. Reis撰写，由 Gustavo Carneiro 实现。
@end table


@c ======================================================================

@node 其他语言特性修改<13>,新增，改进和弃用的模块<3>,PEP 331 Locale-Independent Float/String Conversions,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 other-language-changes}@anchor{e95}
@subsection 其他语言特性修改


Here are all of the changes that Python 2.4 makes to the core Python language.


@itemize *

@item 
Decorators for functions and methods were added (
@geindex Python 提高建议; PEP 318
PEP 318@footnote{https://www.python.org/dev/peps/pep-0318}).

@item 
Built-in @ref{1f7,,set()} and @ref{1f8,,frozenset()} types were  added (
@geindex Python 提高建议; PEP 218
PEP 218@footnote{https://www.python.org/dev/peps/pep-0218}).
Other new built-ins include the @code{reversed(seq)} function (
@geindex Python 提高建议; PEP 322
PEP 322@footnote{https://www.python.org/dev/peps/pep-0322}).

@item 
Generator expressions were added (
@geindex Python 提高建议; PEP 289
PEP 289@footnote{https://www.python.org/dev/peps/pep-0289}).

@item 
Certain numeric expressions no longer return values restricted to 32 or 64
bits (
@geindex Python 提高建议; PEP 237
PEP 237@footnote{https://www.python.org/dev/peps/pep-0237}).

@item 
You can now put parentheses around the list of names in a @code{from module import
names} statement (
@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328}).

@item 
The @ref{e96,,dict.update()} method now accepts the same argument forms as the
@ref{164,,dict} constructor.  This includes any mapping, any iterable of key/value
pairs, and keyword arguments. (Contributed by Raymond Hettinger.)

@item 
The string methods @code{ljust()}, @code{rjust()}, and @code{center()} now take
an optional argument for specifying a fill character other than a space.
(Contributed by Raymond Hettinger.)

@item 
Strings also gained an @code{rsplit()} method that works like the @code{split()}
method but splits from the end of the string.   (Contributed by Sean
Reifschneider.)

@example
>>> 'www.python.org'.split('.', 1)
['www', 'python.org']
'www.python.org'.rsplit('.', 1)
['www.python', 'org']
@end example

@item 
Three keyword parameters, @emph{cmp}, @emph{key}, and @emph{reverse}, were added to the
@code{sort()} method of lists. These parameters make some common usages of
@code{sort()} simpler. All of these parameters are optional.

For the @emph{cmp} parameter, the value should be a comparison function that takes
two parameters and returns -1, 0, or +1 depending on how the parameters compare.
This function will then be used to sort the list.  Previously this was the only
parameter that could be provided to @code{sort()}.

@emph{key} should be a single-parameter function that takes a list element and
returns a comparison key for the element.  The list is then sorted using the
comparison keys.  The following example sorts a list case-insensitively:

@example
>>> L = ['A', 'b', 'c', 'D']
>>> L.sort()                 # Case-sensitive sort
>>> L
['A', 'D', 'b', 'c']
>>> # Using 'key' parameter to sort list
>>> L.sort(key=lambda x: x.lower())
>>> L
['A', 'b', 'c', 'D']
>>> # Old-fashioned way
>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
>>> L
['A', 'b', 'c', 'D']
@end example

The last example, which uses the @emph{cmp} parameter, is the old way to perform a
case-insensitive sort.  It works but is slower than using a @emph{key} parameter.
Using @emph{key} calls @code{lower()} method once for each element in the list while
using @emph{cmp} will call it twice for each comparison, so using @emph{key} saves on
invocations of the @code{lower()} method.

For simple key functions and comparison functions, it is often possible to avoid
a @ref{d01,,lambda} expression by using an unbound method instead.  For example,
the above case-insensitive sort is best written as:

@example
>>> L.sort(key=str.lower)
>>> L
['A', 'b', 'c', 'D']
@end example

Finally, the @emph{reverse} parameter takes a Boolean value.  If the value is true,
the list will be sorted into reverse order. Instead of @code{L.sort();
L.reverse()}, you can now write @code{L.sort(reverse=True)}.

The results of sorting are now guaranteed to be stable.  This means that two
entries with equal keys will be returned in the same order as they were input.
For example, you can sort a list of people by name, and then sort the list by
age, resulting in a list sorted by age where people with the same age are in
name-sorted order.

(All changes to @code{sort()} contributed by Raymond Hettinger.)

@item 
There is a new built-in function @code{sorted(iterable)} that works like the
in-place @ref{550,,list.sort()} method but can be used in expressions.  The
differences are:

@item 
输入可以是任意可迭代对象;

@item 
a newly formed copy is sorted, leaving the original intact; and

@item 
the expression returns the new sorted copy

@example
>>> L = [9,7,8,3,2,4,1,6,5]
>>> [10+i for i in sorted(L)]       # usable in a list comprehension
[11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> L                               # original is left unchanged
[9,7,8,3,2,4,1,6,5]
>>> sorted('Monty Python')          # any iterable may be an input
[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

>>> # List the contents of a dict sorted by key values
>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
>>> for k, v in sorted(colormap.iteritems()):
...     print k, v
...
black 4
blue 2
green 3
red 1
yellow 5
@end example

（由 Raymond Hettinger 贡献。）

@item 
Integer operations will no longer trigger an @code{OverflowWarning}. The
@code{OverflowWarning} warning will disappear in Python 2.5.

@item 
The interpreter gained a new switch, @ref{44c,,-m}, that takes a name, searches
for the corresponding  module on @code{sys.path}, and runs the module as a script.
For example,  you can now run the Python profiler with @code{python -m profile}.
(Contributed by Nick Coghlan.)

@item 
The @code{eval(expr, globals, locals)} and @code{execfile(filename, globals,
locals)} functions and the @code{exec} statement now accept any mapping type
for the @emph{locals} parameter.  Previously this had to be a regular Python
dictionary.  (Contributed by Raymond Hettinger.)

@item 
The @ref{d04,,zip()} built-in function and @code{itertools.izip()} now return an
empty list if called with no arguments. Previously they raised a
@ref{1ff,,TypeError} exception.  This makes them more suitable for use with variable
length argument lists:

@example
>>> def transpose(array):
...    return zip(*array)
...
>>> transpose([(1,2,3), (4,5,6)])
[(1, 4), (2, 5), (3, 6)]
>>> transpose([])
[]
@end example

（由 Raymond Hettinger 贡献。）

@item 
Encountering a failure while importing a module no longer leaves a partially-initialized
module object in @code{sys.modules}.  The incomplete module object left
behind would fool further imports of the same module into succeeding, leading to
confusing errors.   (Fixed by Tim Peters.)

@item 
@ref{204,,None} 现在是一个常量；将一个新值绑定到名称 @code{None} 的代码现在会造成语法错误。 （由 Raymond Hettinger 贡献。）
@end itemize

@c ======================================================================

@menu
* 性能优化: 性能优化<12>. 

@end menu

@node 性能优化<12>,,,其他语言特性修改<13>
@anchor{whatsnew/2 4 optimizations}@anchor{e97}
@subsubsection 性能优化



@itemize *

@item 
The inner loops for list and tuple slicing were optimized and now run about
one-third faster.  The inner loops for dictionaries were also optimized,
resulting in performance boosts for @code{keys()}, @code{values()}, @code{items()},
@code{iterkeys()}, @code{itervalues()}, and @code{iteritems()}. (Contributed by
Raymond Hettinger.)

@item 
The machinery for growing and shrinking lists was optimized for speed and for
space efficiency.  Appending and popping from lists now runs faster due to more
efficient code paths and less frequent use of the underlying system
@code{realloc()}.  List comprehensions also benefit.   @code{list.extend()} was
also optimized and no longer converts its argument into a temporary list before
extending the base list.  (Contributed by Raymond Hettinger.)

@item 
@ref{1f9,,list()}, @ref{1a2,,tuple()}, @ref{cff,,map()}, @ref{d00,,filter()}, and @ref{d04,,zip()} now
run several times faster with non-sequence arguments that supply a
@ref{e98,,__len__()} method.  (Contributed by Raymond Hettinger.)

@item 
The methods @code{list.__getitem__()}, @code{dict.__getitem__()}, and
@code{dict.__contains__()} are now implemented as @code{method_descriptor}
objects rather than @code{wrapper_descriptor} objects.  This form of  access
doubles their performance and makes them more suitable for use as arguments to
functionals: @code{map(mydict.__getitem__, keylist)}. (Contributed by Raymond
Hettinger.)

@item 
Added a new opcode, @code{LIST_APPEND}, that simplifies the generated bytecode
for list comprehensions and speeds them up by about a third.  (Contributed by
Raymond Hettinger.)

@item 
The peephole bytecode optimizer has been improved to  produce shorter, faster
bytecode; remarkably, the resulting bytecode is  more readable.  (Enhanced by
Raymond Hettinger.)

@item 
String concatenations in statements of the form @code{s = s + "abc"} and @code{s +=
"abc"} are now performed more efficiently in certain circumstances.  This
optimization won't be present in other Python implementations such as Jython, so
you shouldn't rely on it; using the @code{join()} method of strings is still
recommended when you want to efficiently glue a large number of strings
together. (Contributed by Armin Rigo.)
@end itemize

The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
(pystone is not a particularly good benchmark, but it's the most commonly used
measurement of Python's performance.  Your own applications may show greater or
smaller benefits from Python 2.4.)

@c pystone is almost useless for comparing different versions of Python;
@c instead, it excels at predicting relative Python performance on different
@c machines.  So, this section would be more informative if it used other tools
@c such as pybench and parrotbench.  For a more application oriented benchmark,
@c try comparing the timings of test_decimal.py under 2.3 and 2.4.

@c ======================================================================

@node 新增，改进和弃用的模块<3>,构建和 C API 的改变<11>,其他语言特性修改<13>,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 new-improved-and-deprecated-modules}@anchor{e99}
@subsection 新增，改进和弃用的模块


As usual, Python's standard library received a number of enhancements and bug
fixes.  Here's a partial list of the most notable changes, sorted alphabetically
by module name. Consult the @code{Misc/NEWS} file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.


@itemize *

@item 
The @ref{a,,asyncore} module's @code{loop()} function now has a @emph{count} parameter
that lets you perform a limited number of passes through the polling loop.  The
default is still to loop forever.

@item 
The @ref{d,,base64} module now has more complete 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://tools.ietf.org/html/rfc3548.html} support for Base64,
Base32, and Base16 encoding and decoding, including optional case folding and
optional alternative alphabets. (Contributed by Barry Warsaw.)

@item 
The @ref{11,,bisect} module now has an underlying C implementation for improved
performance. (Contributed by Dmitry Vasiliev.)

@item 
由 Hye-Shik Chang 维护的东亚编解码器的 CJKCodecs 集合已集成到 2.4 中。新的编码为：

@item 
汉语（大陆）: gb2312, gbk, gb18030, big5hkscs, hz

@item 
汉语（台湾）: big5, cp950

@item 

@table @asis

@item 日语: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,

iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
shift-jis, shift-jisx0213, shift-jis-2004
@end table

@item 
韩语: cp949, euc-kr, johab, iso-2022-kr

@item 
添加了其他一些新的编码：HP Roman8, ISO_8859-11, ISO_8859-16, PCTP-154 和 TIS-620

@item 
The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
Previously the @code{StreamReader} class would try to read more data, making
it impossible to resume decoding from the stream.  The @code{read()} method will
now return as much data as it can and future calls will resume decoding where
previous ones left off.  (Implemented by Walter Dörwald.)

@item 
There is a new @ref{1d,,collections} module for  various specialized collection
datatypes.  Currently it contains just one type, @code{deque}, a double-ended
queue that supports efficiently adding and removing elements from either
end:

@example
>>> from collections import deque
>>> d = deque('ghi')        # make a new deque with three items
>>> d.append('j')           # add a new entry to the right side
>>> d.appendleft('f')       # add a new entry to the left side
>>> d                       # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop()                 # return and remove the rightmost item
'j'
>>> d.popleft()             # return and remove the leftmost item
'f'
>>> list(d)                 # list the contents of the deque
['g', 'h', 'i']
>>> 'h' in d                # search the deque
True
@end example

Several modules, such as the @code{Queue} and @ref{10b,,threading} modules, now take
advantage of @ref{633,,collections.deque} for improved performance.  (Contributed
by Raymond Hettinger.)

@item 
The @code{ConfigParser} classes have been enhanced slightly. The @code{read()}
method now returns a list of the files that were successfully parsed, and the
@ref{1f7,,set()} method raises @ref{1ff,,TypeError} if passed a @emph{value} argument that
isn't a string.   (Contributed by John Belmonte and David Goodger.)

@item 
The @ref{2b,,curses} module now supports the ncurses extension
@code{use_default_colors()}.  On platforms where the terminal supports
transparency, this makes it possible to use a transparent background.
(Contributed by Jörg Lehmann.)

@item 
The @ref{36,,difflib} module now includes an @code{HtmlDiff} class that creates
an HTML table showing a side by side comparison of two versions of a text.
(Contributed by Dan Gass.)

@item 
The @ref{67,,email} package was updated to version 3.0,  which dropped various
deprecated APIs and removes support for Python versions earlier than 2.3.  The
3.0 version of the package uses a new incremental parser for MIME messages,
available in the @code{email.FeedParser} module.  The new parser doesn't require
reading the entire message into memory, and doesn't raise exceptions if a
message is malformed; instead it records any problems in the  @code{defect}
attribute of the message.  (Developed by Anthony Baxter, Barry Warsaw, Thomas
Wouters, and others.)

@item 
The @ref{8d,,heapq} module has been converted to C.  The resulting tenfold
improvement in speed makes the module suitable for handling high volumes of
data.  In addition, the module has two new functions @code{nlargest()} and
@code{nsmallest()} that use heaps to find the N largest or smallest values in a
dataset without the expense of a full sort.  (Contributed by Raymond Hettinger.)

@item 
The @code{httplib} module now contains constants for HTTP status codes defined
in various HTTP-related RFC documents.  Constants have names such as
@code{OK}, @code{CREATED}, @code{CONTINUE}, and
@code{MOVED_PERMANENTLY}; use pydoc to get a full list.  (Contributed by
Andrew Eland.)

@item 
The @ref{97,,imaplib} module now supports IMAP's THREAD command (contributed by
Yves Dionne) and new @code{deleteacl()} and @code{myrights()} methods (contributed
by Arnaud Mazin).

@item 
The @ref{a3,,itertools} module gained a @code{groupby(iterable[, *func*])}
function. @emph{iterable} is something that can be iterated over to return a stream
of elements, and the optional @emph{func} parameter is a function that takes an
element and returns a key value; if omitted, the key is simply the element
itself.  @code{groupby()} then groups the elements into subsequences which have
matching values of the key, and returns a series of 2-tuples containing the key
value and an iterator over the subsequence.

Here's an example to make this clearer.  The @emph{key} function simply returns
whether a number is even or odd, so the result of @code{groupby()} is to return
consecutive runs of odd or even numbers.

@example
>>> import itertools
>>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
...    print key_val, list(it)
...
0 [2, 4, 6]
1 [7]
0 [8]
1 [9, 11]
0 [12, 14]
>>>
@end example

@code{groupby()} is typically used with sorted input.  The logic for
@code{groupby()} is similar to the Unix @code{uniq} filter which makes it handy for
eliminating, counting, or identifying duplicate elements:

@example
>>> word = 'abracadabra'
>>> letters = sorted(word)   # Turn string into a sorted list of letters
>>> letters
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
>>> for k, g in itertools.groupby(letters):
...    print k, list(g)
...
a ['a', 'a', 'a', 'a', 'a']
b ['b', 'b']
c ['c']
d ['d']
r ['r', 'r']
>>> # List unique letters
>>> [k for k, g in groupby(letters)]
['a', 'b', 'c', 'd', 'r']
>>> # Count letter occurrences
>>> [(k, len(list(g))) for k, g in groupby(letters)]
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
@end example

（由 Hye-Shik Chang 贡献。）

@item 
@ref{a3,,itertools} also gained a function named @code{tee(iterator, N)} that
returns @emph{N} independent iterators that replicate @emph{iterator}.  If @emph{N} is omitted,
the default is 2.

@example
>>> L = [1,2,3]
>>> i1, i2 = itertools.tee(L)
>>> i1,i2
(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
>>> list(i1)               # Run the first iterator to exhaustion
[1, 2, 3]
>>> list(i2)               # Run the second iterator to exhaustion
[1, 2, 3]
@end example

Note that @code{tee()} has to keep copies of the values returned  by the
iterator; in the worst case, it may need to keep all of them.   This should
therefore be used carefully if the leading iterator can run far ahead of the
trailing iterator in a long stream of inputs. If the separation is large, then
you might as well use  @ref{1f9,,list()} instead.  When the iterators track closely
with one another, @code{tee()} is ideal.  Possible applications include
bookmarking, windowing, or lookahead iterators. (Contributed by Raymond
Hettinger.)

@item 
A number of functions were added to the @ref{a9,,locale}  module, such as
@code{bind_textdomain_codeset()} to specify a particular encoding and a family of
@code{l*gettext()} functions that return messages in the chosen encoding.
(Contributed by Gustavo Niemeyer.)

@item 
Some keyword arguments were added to the @ref{aa,,logging} package's
@code{basicConfig()} function to simplify log configuration.  The default
behavior is to log messages to standard error, but various keyword arguments can
be specified to log to a particular file, change the logging format, or set the
logging level. For example:

@example
import logging
logging.basicConfig(filename='/var/log/application.log',
    level=0,  # Log all messages
    format='%(levelname):%(process):%(thread):%(message)')
@end example

Other additions to the @ref{aa,,logging} package include a @code{log(level, msg)}
convenience method, as well as a @code{TimedRotatingFileHandler} class that
rotates its log files at a timed interval.  The module already had
@code{RotatingFileHandler}, which rotated logs once the file exceeded a
certain size.  Both classes derive from a new @code{BaseRotatingHandler} class
that can be used to implement other rotating handlers.

（更改由 Vinay Sajip 实现。）

@item 
The @ref{b0,,marshal} module now shares interned strings on unpacking a  data
structure.  This may shrink the size of certain pickle strings, but the primary
effect is to make @code{.pyc} files significantly smaller. (Contributed by
Martin von Löwis.)

@item 
The @ref{c0,,nntplib} module's @code{NNTP} class gained @code{description()} and
@code{descriptions()} methods to retrieve  newsgroup descriptions for a single
group or for a range of groups. (Contributed by Jürgen A. Erhard.)

@item 
Two new functions were added to the @ref{c2,,operator} module,
@code{attrgetter(attr)} and @code{itemgetter(index)}. Both functions return
callables that take a single argument and return the corresponding attribute or
item; these callables make excellent data extractors when used with @ref{cff,,map()}
or @ref{54f,,sorted()}.  For example:

@example
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
@end example

（由 Raymond Hettinger 贡献。）

@item 
The @ref{c3,,optparse} module was updated in various ways.  The module now passes
its messages through @ref{e9a,,gettext.gettext()}, making it possible to
internationalize Optik's help and error messages.  Help messages for options can
now include the string @code{'%default'}, which will be replaced by the option's
default value.  (Contributed by Greg Ward.)

@item 
The long-term plan is to deprecate the @code{rfc822} module in some future
Python release in favor of the @ref{67,,email} package. To this end, the
@code{email.Utils.formatdate()} function has been changed to make it usable as a
replacement for @code{rfc822.formatdate()}.  You may want to write new e-mail
processing code with this in mind.  (Change implemented by Anthony Baxter.)

@item 
A new @code{urandom(n)} function was added to the @ref{c4,,os} module, returning
a string containing @emph{n} bytes of random data.  This function provides access to
platform-specific sources of randomness such as @code{/dev/urandom} on Linux or
the Windows CryptoAPI.  (Contributed by Trevor Perrin.)

@item 
Another new function: @code{os.path.lexists(path)}  returns true if the file
specified by @emph{path} exists, whether or not it's a symbolic link.  This differs
from the existing @code{os.path.exists(path)} function, which returns false if
@emph{path} is a symlink that points to a destination that doesn't exist.
(Contributed by Beni Cherniavsky.)

@item 
A new @code{getsid()} function was added to the @ref{d1,,posix} module that
underlies the @ref{c4,,os} module. (Contributed by J. Raynor.)

@item 
The @ref{d0,,poplib} module now supports POP over SSL.  (Contributed by Hector
Urtubia.)

@item 
The @ref{d3,,profile} module can now profile C extension functions. (Contributed
by Nick Bastin.)

@item 
The @ref{dc,,random} module has a new method called @code{getrandbits(N)} that
returns a long integer @emph{N} bits in length.  The existing @code{randrange()}
method now uses @code{getrandbits()} where appropriate, making generation of
arbitrarily large random numbers more efficient.  (Contributed by Raymond
Hettinger.)

@item 
The regular expression language accepted by the @ref{dd,,re} module was extended
with simple conditional expressions, written as @code{(?(group)A|B)}.  @emph{group} is
either a numeric group ID or a group name defined with @code{(?P<group>...)}
earlier in the expression.  If the specified group matched, the regular
expression pattern @emph{A} will be tested against the string; if the group didn't
match, the pattern @emph{B} will be used instead. (Contributed by Gustavo Niemeyer.)

@item 
The @ref{dd,,re} module is also no longer recursive, thanks to a massive amount
of work by Gustavo Niemeyer.  In a recursive regular expression engine, certain
patterns result in a large amount of C stack space being consumed, and it was
possible to overflow the stack. For example, if you matched a 30000-byte string
of @code{a} characters against the expression @code{(a|b)+}, one stack frame was
consumed per character.  Python 2.3 tried to check for stack overflow and raise
a @ref{3e4,,RuntimeError} exception, but certain patterns could sidestep the
checking and if you were unlucky Python could segfault. Python 2.4's regular
expression engine can match this pattern without problems.

@item 
The @ref{ea,,signal} module now performs tighter error-checking on the parameters
to the @ref{b61,,signal.signal()} function.  For example, you can't set a handler on
the @code{SIGKILL} signal; previous versions of Python would quietly accept
this, but 2.4 will raise a @ref{3e4,,RuntimeError} exception.

@item 
Two new functions were added to the @ref{ef,,socket} module. @code{socketpair()}
returns a pair of connected sockets and @code{getservbyport(port)} looks up the
service name for a given port number. (Contributed by Dave Cole and Barry
Warsaw.)

@item 
The @code{sys.exitfunc()} function has been deprecated.  Code should be using
the existing @ref{b,,atexit} module, which correctly handles calling multiple exit
functions.  Eventually @code{sys.exitfunc()} will become a purely internal
interface, accessed only by @ref{b,,atexit}.

@item 
The @ref{101,,tarfile} module now generates GNU-format tar files by default.
(Contributed by Lars Gustäbel.)

@item 
The @ref{10b,,threading} module now has an elegantly simple way to support
thread-local data.  The module contains a @code{local} class whose attribute
values are local to different threads.

@example
import threading

data = threading.local()
data.number = 42
data.url = ('www.python.org', 80)
@end example

Other threads can assign and retrieve their own values for the @code{number}
and @code{url} attributes.  You can subclass @code{local} to initialize
attributes or to add methods. (Contributed by Jim Fulton.)

@item 
The @ref{10d,,timeit} module now automatically disables periodic garbage
collection during the timing loop.  This change makes consecutive timings more
comparable.  (Contributed by Raymond Hettinger.)

@item 
The @ref{131,,weakref} module now supports a wider variety of objects including
Python functions, class instances, sets, frozensets, deques, arrays, files,
sockets, and regular expression pattern objects. (Contributed by Raymond
Hettinger.)

@item 
The @code{xmlrpclib} module now supports a multi-call extension for
transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
Brian Quinlan.)

@item 
@code{mpz}, @code{rotor} 和 @code{xreadlines} 模块已被移除。
@end itemize

@c ======================================================================

@c whole new modules get described in subsections here

@c =====================

@menu
* cookielib:: 
* doctest: doctest<3>. 

@end menu

@node cookielib,doctest<3>,,新增，改进和弃用的模块<3>
@anchor{whatsnew/2 4 cookielib}@anchor{e9b}
@subsubsection cookielib


The @code{cookielib} library supports client-side handling for HTTP cookies,
mirroring the @code{Cookie} module's server-side cookie support. Cookies are
stored in cookie jars; the library transparently stores cookies offered by the
web server in the cookie jar, and fetches the cookie from the jar when
connecting to the server. As in web browsers, policy objects control whether
cookies are accepted or not.

In order to store cookies across sessions, two implementations of cookie jars
are provided: one that stores cookies in the Netscape format so applications can
use the Mozilla or Lynx cookie files, and one that stores cookies in the same
format as the Perl libwww library.

@code{urllib2} has been changed to interact with @code{cookielib}:
@code{HTTPCookieProcessor} manages a cookie jar that is used when accessing
URLs.

该模块由  John J. Lee 贡献。

@c ==================

@node doctest<3>,,cookielib,新增，改进和弃用的模块<3>
@anchor{whatsnew/2 4 doctest}@anchor{e9c}
@subsubsection doctest


The @ref{66,,doctest} module underwent considerable refactoring thanks to Edward
Loper and Tim Peters.  Testing can still be as simple as running
@ref{e9d,,doctest.testmod()}, but the refactorings allow customizing the module's
operation in various ways

The new @code{DocTestFinder} class extracts the tests from a given  object's
docstrings:

@example
def f (x, y):
    """>>> f(2,2)
4
>>> f(3,2)
6
    """
    return x*y

finder = doctest.DocTestFinder()

# Get list of DocTest instances
tests = finder.find(f)
@end example

The new @code{DocTestRunner} class then runs individual tests and can produce
a summary of the results:

@example
runner = doctest.DocTestRunner()
for t in tests:
    tried, failed = runner.run(t)

runner.summarize(verbose=1)
@end example

The above example produces the following output:

@example
1 items passed all tests:
   2 tests in f
2 tests in 1 items.
2 passed and 0 failed.
Test passed.
@end example

@code{DocTestRunner} uses an instance of the @code{OutputChecker} class to
compare the expected output with the actual output.  This class takes a number
of different flags that customize its behaviour; ambitious users can also write
a completely new subclass of @code{OutputChecker}.

The default output checker provides a number of handy features. For example,
with the @ref{e9e,,doctest.ELLIPSIS} option flag, an ellipsis (@code{...}) in the
expected output matches any substring,  making it easier to accommodate outputs
that vary in minor ways:

@example
def o (n):
    """>>> o(1)
<__main__.C instance at 0x...>
>>>
"""
@end example

Another special string, @code{<BLANKLINE>}, matches a blank line:

@example
def p (n):
    """>>> p(1)
<BLANKLINE>
>>>
"""
@end example

Another new capability is producing a diff-style display of the output by
specifying the @ref{e9f,,doctest.REPORT_UDIFF} (unified diffs),
@ref{ea0,,doctest.REPORT_CDIFF} (context diffs), or @ref{ea1,,doctest.REPORT_NDIFF}
(delta-style) option flags.  For example:

@example
def g (n):
    """>>> g(4)
here
is
a
lengthy
>>>"""
    L = 'here is a rather lengthy list of words'.split()
    for word in L[:n]:
        print word
@end example

Running the above function's tests with @ref{e9f,,doctest.REPORT_UDIFF} specified,
you get the following output:

@example
**********************************************************************
File "t.py", line 15, in g
Failed example:
    g(4)
Differences (unified diff with -expected +actual):
    @@@@ -2,3 +2,3 @@@@
     is
     a
    -lengthy
    +rather
**********************************************************************
@end example

@c ======================================================================

@node 构建和 C API 的改变<11>,移植到 Python 2 4,新增，改进和弃用的模块<3>,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 build-and-c-api-changes}@anchor{ea2}
@subsection 构建和 C API 的改变


对于 Python 构建过程和 C API 的一些修改:


@itemize *

@item 
Three new convenience macros were added for common return values from
extension functions: @ref{ea3,,Py_RETURN_NONE}, @ref{ea4,,Py_RETURN_TRUE}, and
@ref{ea5,,Py_RETURN_FALSE}. (Contributed by Brett Cannon.)

@item 
Another new macro, @code{Py_CLEAR(obj)},  decreases the reference count of
@emph{obj} and sets @emph{obj} to the null pointer.  (Contributed by Jim Fulton.)

@item 
A new function, @code{PyTuple_Pack(N, obj1, obj2, ..., objN)}, constructs
tuples from a variable length argument list of Python objects.  (Contributed by
Raymond Hettinger.)

@item 
A new function, @code{PyDict_Contains(d, k)}, implements fast dictionary
lookups without masking exceptions raised during the look-up process.
(Contributed by Raymond Hettinger.)

@item 
The @code{Py_IS_NAN(X)} macro returns 1 if  its float or double argument
@emph{X} is a NaN.   (Contributed by Tim Peters.)

@item 
C code can avoid unnecessary locking by using the new
@ref{20e,,PyEval_ThreadsInitialized()} function to tell  if any thread operations
have been performed.  If this function  returns false, no lock operations are
needed. (Contributed by Nick Coghlan.)

@item 
A new function, @ref{ea6,,PyArg_VaParseTupleAndKeywords()}, is the same as
@ref{6cb,,PyArg_ParseTupleAndKeywords()} but takes a  @code{va_list} instead of a
number of arguments. (Contributed by Greg Chapman.)

@item 
A new method flag, @code{METH_COEXISTS}, allows a function defined in slots
to co-exist with a @ref{ea7,,PyCFunction} having the same name.  This can halve
the access time for a method such as @code{set.__contains__()}.  (Contributed by
Raymond Hettinger.)

@item 
Python can now be built with additional profiling for the interpreter itself,
intended as an aid to people developing the Python core.  Providing
@code{--enable-profiling} to the @code{configure} script will let you
profile the interpreter with @code{gprof}, and providing the
@code{--with-tsc} switch enables profiling using the Pentium's
Time-Stamp-Counter register.  Note that the @code{--with-tsc} switch is slightly
misnamed, because the profiling feature also works on the PowerPC platform,
though that processor architecture doesn't call that register "the TSC
register".  (Contributed by Jeremy Hylton.)

@item 
The @code{tracebackobject} type has been renamed to
@code{PyTracebackObject}.
@end itemize

@c ======================================================================

@menu
* Port-Specific Changes: Port-Specific Changes<2>. 

@end menu

@node Port-Specific Changes<2>,,,构建和 C API 的改变<11>
@anchor{whatsnew/2 4 port-specific-changes}@anchor{ea8}
@subsubsection Port-Specific Changes



@itemize *

@item 
The Windows port now builds under MSVC++ 7.1 as well as version 6.
(Contributed by Martin von Löwis.)
@end itemize

@c ======================================================================

@node 移植到 Python 2 4,致谢<4>,构建和 C API 的改变<11>,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 porting-to-python-2-4}@anchor{ea9}
@subsection 移植到 Python 2.4


This section lists previously described changes that may require changes to your
code:


@itemize *

@item 
Left shifts and hexadecimal/octal constants that are too  large no longer
trigger a @ref{43e,,FutureWarning} and return  a value limited to 32 or 64 bits;
instead they return a long integer.

@item 
Integer operations will no longer trigger an @code{OverflowWarning}. The
@code{OverflowWarning} warning will disappear in Python 2.5.

@item 
The @ref{d04,,zip()} built-in function and @code{itertools.izip()} now return  an
empty list instead of raising a @ref{1ff,,TypeError} exception if called with no
arguments.

@item 
You can no longer compare the @code{date} and @ref{19f,,datetime} instances
provided by the @ref{30,,datetime} module.  Two  instances of different classes
will now always be unequal, and  relative comparisons (@code{<}, @code{>}) will raise
a @ref{1ff,,TypeError}.

@item 
@code{dircache.listdir()} now passes exceptions to the caller instead of
returning empty lists.

@item 
@code{LexicalHandler.startDTD()} used to receive the public and system IDs in
the wrong order.  This has been corrected; applications relying on the wrong
order need to be fixed.

@item 
@ref{eaa,,fcntl.ioctl()} now warns if the @emph{mutate}  argument is omitted and
relevant.

@item 
The @ref{101,,tarfile} module now generates GNU-format tar files by default.

@item 
Encountering a failure while importing a module no longer leaves a
partially-initialized module object in @code{sys.modules}.

@item 
@ref{204,,None} is now a constant; code that binds a new value to  the name
@code{None} is now a syntax error.

@item 
The @code{signals.signal()} function now raises a @ref{3e4,,RuntimeError} exception
for certain illegal values; previously these errors would pass silently.  For
example, you can no longer set a handler on the @code{SIGKILL} signal.
@end itemize

@c ======================================================================

@node 致谢<4>,,移植到 Python 2 4,Python 2 4 有什么新变化
@anchor{whatsnew/2 4 acknowledgements}@anchor{eab}@anchor{whatsnew/2 4 acks}@anchor{eac}
@subsection 致谢


作者感谢以下人员对本文各种草稿给予的建议，更正和协助：Koray Can, Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.

@node Python 2 3 有什么新变化,Python 2 2 有什么新变化,Python 2 4 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 3 doc}@anchor{ead}@anchor{whatsnew/2 3 what-s-new-in-python-2-3}@anchor{eae}
@section Python 2.3 有什么新变化


@*作者: 
A.M. Kuchling


@c $Id: whatsnew23.tex 54631 2007-03-31 11:58:36Z georg.brandl $

本文介绍了 Python 2.3 的新特性。 Python 2.3 发布于 2003 年 7 月 29 日。

The main themes for Python 2.3 are polishing some of the features added in 2.2,
adding various small but useful enhancements to the core language, and expanding
the standard library.  The new object model introduced in the previous version
has benefited from 18 months of bugfixes and from optimization efforts that have
improved the performance of new-style classes.  A few new built-in functions
have been added such as @ref{31d,,sum()} and @ref{eaf,,enumerate()}.  The @ref{179,,in}
operator can now be used for substring searches (e.g. @code{"ab" in "abc"} returns
@ref{59c,,True}).

Some of the many new library features include Boolean, set, heap, and date/time
data types, the ability to import modules from ZIP-format archives, metadata
support for the long-awaited Python catalog, an updated version of IDLE, and
modules for logging messages, wrapping text, parsing CSV files, processing
command-line options, using BerkeleyDB databases...  the list of new and
enhanced modules is lengthy.

This article doesn't attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.3, such as the Python Library
Reference and the Python Reference Manual.  If you want to understand the
complete implementation and design rationale, refer to the PEP for a particular
new feature.

@c ======================================================================

@menu
* PEP 218; 标准集合数据类型: PEP 218 标准集合数据类型. 
* PEP 255; 简单的生成器: PEP 255 简单的生成器. 
* PEP 263; 源代码的字符编码格式: PEP 263 源代码的字符编码格式. 
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块. 
* PEP 277; 针对 Windows NT 的 Unicode 文件名支持: PEP 277 针对 Windows NT 的 Unicode 文件名支持. 
* PEP 278; 通用换行支持: PEP 278 通用换行支持. 
* PEP 279; enumerate(): PEP 279 enumerate. 
* PEP 282; logging 包: PEP 282 logging 包. 
* PEP 285; 布尔类型: PEP 285 布尔类型. 
* PEP 293; Codec Error Handling Callbacks: PEP 293 Codec Error Handling Callbacks. 
* PEP 301; Distutils的软件包索引和元数据: PEP 301 Distutils的软件包索引和元数据. 
* PEP 302; 新导入钩子: PEP 302 新导入钩子. 
* PEP 305; 逗号分隔文件: PEP 305 逗号分隔文件. 
* PEP 307; Pickle Enhancements: PEP 307 Pickle Enhancements. 
* 扩展切片:: 
* 其他语言特性修改: 其他语言特性修改<14>. 
* 新增，改进和弃用的模块: 新增，改进和弃用的模块<4>. 
* Pymalloc; A Specialized Object Allocator: Pymalloc A Specialized Object Allocator. 
* 构建和 C API 的改变: 构建和 C API 的改变<12>. 
* 其他的改变和修正: 其他的改变和修正<2>. 
* 移植到 Python 2.3: 移植到 Python 2 3. 
* 致谢: 致谢<5>. 

@end menu

@node PEP 218 标准集合数据类型,PEP 255 简单的生成器,,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-218-a-standard-set-datatype}@anchor{eb0}
@subsection PEP 218: 标准集合数据类型


The new @code{sets} module contains an implementation of a set datatype.  The
@code{Set} class is for mutable sets, sets that can have members added and
removed.  The @code{ImmutableSet} class is for sets that can't be modified,
and instances of @code{ImmutableSet} can therefore be used as dictionary keys.
Sets are built on top of dictionaries, so the elements within a set must be
hashable.

这是一个简单的示例：

@example
>>> import sets
>>> S = sets.Set([1,2,3])
>>> S
Set([1, 2, 3])
>>> 1 in S
True
>>> 0 in S
False
>>> S.add(5)
>>> S.remove(3)
>>> S
Set([1, 2, 5])
>>>
@end example

The union and intersection of sets can be computed with the @code{union()} and
@code{intersection()} methods; an alternative notation uses the bitwise operators
@code{&} and @code{|}. Mutable sets also have in-place versions of these methods,
@code{union_update()} and @code{intersection_update()}.

@example
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
>>> S1.union(S2)
Set([1, 2, 3, 4, 5, 6])
>>> S1 | S2                  # Alternative notation
Set([1, 2, 3, 4, 5, 6])
>>> S1.intersection(S2)
Set([])
>>> S1 & S2                  # Alternative notation
Set([])
>>> S1.union_update(S2)
>>> S1
Set([1, 2, 3, 4, 5, 6])
>>>
@end example

It's also possible to take the symmetric difference of two sets.  This is the
set of all elements in the union that aren't in the intersection.  Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set.  Again, there's an alternative notation (@code{^}), and an
in-place version with the ungainly name @code{symmetric_difference_update()}.

@example
>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
>>> S1.symmetric_difference(S2)
Set([1, 2, 5, 6])
>>> S1 ^ S2
Set([1, 2, 5, 6])
>>>
@end example

另外还有 @code{issubset()} 和 @code{issuperset()} 方法用来检查一个集合是否为另一个集合的子集或超集:

@example
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([2,3])
>>> S2.issubset(S1)
True
>>> S1.issubset(S2)
False
>>> S1.issuperset(S2)
True
>>>
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 218

@item PEP 218@footnote{https://www.python.org/dev/peps/pep-0218} - 添加内置Set对象类型

PEP 由 Greg V. Wilson 撰写 ; 由 Greg V. Wilson, Alex Martelli 和 GvR 实现。
@end table


@c ======================================================================

@node PEP 255 简单的生成器,PEP 263 源代码的字符编码格式,PEP 218 标准集合数据类型,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-255-simple-generators}@anchor{eb1}@anchor{whatsnew/2 3 section-generators}@anchor{eb2}
@subsection PEP 255: 简单的生成器


In Python 2.2, generators were added as an optional feature, to be enabled by a
@code{from __future__ import generators} directive.  In 2.3 generators no longer
need to be specially enabled, and are now always present; this means that
@ref{2ce,,yield} is now always a keyword.  The rest of this section is a copy of
the description of generators from the "What's New in Python 2.2" document; if
you read it back when Python 2.2 came out, you can skip the rest of this
section.

You're doubtless familiar with how function calls work in Python or C. When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a @ref{2cf,,return} statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren't thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.

这里是一个生成器函数的最简示例:

@example
def generate_ints(N):
    for i in range(N):
        yield i
@end example

A new keyword, @ref{2ce,,yield}, was introduced for generators.  Any function
containing a @code{yield} statement is a generator function; this is
detected by Python's bytecode compiler which compiles the function specially as
a result.

When you call a generator function, it doesn't return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the @ref{2ce,,yield} statement, the generator outputs the value of @code{i},
similar to a @ref{2cf,,return} statement.  The big difference between
@code{yield} and a @code{return} statement is that on reaching a
@code{yield} the generator's state of execution is suspended and local
variables are preserved.  On the next call to the generator's @code{.next()}
method, the function will resume executing immediately after the
@code{yield} statement.  (For complicated reasons, the @code{yield}
statement isn't allowed inside the @ref{e3f,,try} block of a
@code{try}...@code{finally} statement; read 
@geindex Python 提高建议; PEP 255
PEP 255@footnote{https://www.python.org/dev/peps/pep-0255} for a full
explanation of the interaction between @code{yield} and exceptions.)

这里是 @code{generate_ints()} 生成器的用法示例:

@example
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "stdin", line 1, in ?
  File "stdin", line 2, in generate_ints
StopIteration
@end example

你可以等价地写成 @code{for i in generate_ints(5)} 或 @code{a,b,c = generate_ints(3)}。

Inside a generator function, the @ref{2cf,,return} statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. @code{return} with a value, such
as @code{return 5}, is a syntax error inside a generator function.  The end of the
generator's results can also be indicated by raising @ref{58a,,StopIteration}
manually, or by just letting the flow of execution fall off the bottom of the
function.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting @code{self.count} to
0, and having the @ref{77f,,next()} method increment @code{self.count} and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. @code{Lib/test/test_generators.py} contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively.

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x
@end example

Two other examples in @code{Lib/test/test_generators.py} produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight's Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon
(@indicateurl{https://www.cs.arizona.edu/icon/}), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from "An Overview of the Icon Programming Language" at
@indicateurl{https://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of what this looks
like:

@example
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
@end example

In Icon the @code{find()} function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the @ref{eb3,,if} statement, @code{i} is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.

Python doesn't go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered part of the core Python language, but
learning or using them isn't compulsory; if they don't solve any problems that
you have, feel free to ignore them. One novel feature of Python's interface as
compared to Icon's is that a generator's state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 255

@item PEP 255@footnote{https://www.python.org/dev/peps/pep-0255} - 简单生成器

Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
@end table


@c ======================================================================

@node PEP 263 源代码的字符编码格式,PEP 273 从ZIP压缩包导入模块,PEP 255 简单的生成器,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-263-source-code-encodings}@anchor{eb4}@anchor{whatsnew/2 3 section-encodings}@anchor{eb5}
@subsection PEP 263: 源代码的字符编码格式


Python source files can now be declared as being in different character set
encodings.  Encodings are declared by including a specially formatted comment in
the first or second line of the source file.  For example, a UTF-8 file can be
declared with:

@example
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
@end example

Without such an encoding declaration, the default encoding used is 7-bit ASCII.
Executing or importing modules that contain string literals with 8-bit
characters and have no encoding declaration will result in a
@ref{15a,,DeprecationWarning} being signalled by Python 2.3; in 2.4 this will be a
syntax error.

The encoding declaration only affects Unicode string literals, which will be
converted to Unicode using the specified encoding.  Note that Python identifiers
are still restricted to ASCII characters, so you can't have variable names that
use characters outside of the usual alphanumerics.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 263

@item PEP 263@footnote{https://www.python.org/dev/peps/pep-0263} - 定义 Python 源代码的编码格式

由 Marc-André Lemburg 和 Martin von Löwis 撰写 ; 由 Suzuki Hisao 和 Martin von Löwis 实现。
@end table


@c ======================================================================

@node PEP 273 从ZIP压缩包导入模块,PEP 277 针对 Windows NT 的 Unicode 文件名支持,PEP 263 源代码的字符编码格式,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-273-importing-modules-from-zip-archives}@anchor{eb6}
@subsection PEP 273: 从ZIP压缩包导入模块


The new @ref{14c,,zipimport} module adds support for importing modules from a
ZIP-format archive.  You don't need to import the module explicitly; it will be
automatically imported if a ZIP archive's filename is added to @code{sys.path}.
For example:

@example
amk@@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive:  /tmp/example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
amk@@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>>
@end example

An entry in @code{sys.path} can now be the filename of a ZIP archive. The ZIP
archive can contain any kind of files, but only files named @code{*.py},
@code{*.pyc}, or @code{*.pyo} can be imported.  If an archive only contains
@code{*.py} files, Python will not attempt to modify the archive by adding the
corresponding @code{*.pyc} file, meaning that if a ZIP archive doesn't contain
@code{*.pyc} files, importing may be rather slow.

A path within the archive can also be specified to only import from a
subdirectory; for example, the path @code{/tmp/example.zip/lib/} would only
import from the @code{lib/} subdirectory within the archive.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 273

@item PEP 273@footnote{https://www.python.org/dev/peps/pep-0273} -  从ZIP压缩包导入模块

Written by James C. Ahlstrom,  who also provided an implementation. Python 2.3
follows the specification in 
@geindex Python 提高建议; PEP 273
PEP 273@footnote{https://www.python.org/dev/peps/pep-0273},  but uses an implementation written by
Just van Rossum  that uses the import hooks described in 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}. See section
@ref{eb7,,PEP 302; 新导入钩子} for a description of the new import hooks.
@end table


@c ======================================================================

@node PEP 277 针对 Windows NT 的 Unicode 文件名支持,PEP 278 通用换行支持,PEP 273 从ZIP压缩包导入模块,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-277-unicode-file-name-support-for-windows-nt}@anchor{eb8}
@subsection PEP 277: 针对 Windows NT 的 Unicode 文件名支持


On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
Traditionally, Python has represented file names as byte strings, which is
inadequate because it renders some file names inaccessible.

Python now allows using arbitrary Unicode strings (within the limitations of the
file system) for all functions that expect file names, most notably the
@ref{16f,,open()} built-in function. If a Unicode string is passed to
@ref{b25,,os.listdir()}, Python now returns a list of Unicode strings.  A new
function, @code{os.getcwdu()}, returns the current directory as a Unicode string.

字节串仍可被用作文件名，并且在 Windows 上 Python 将透明地使用 @code{mbcs} 编码格式将其转换为 Unicode。

Other systems also allow Unicode strings as file names but convert them to byte
strings before passing them to the system, which can cause a @ref{d0b,,UnicodeError}
to be raised. Applications can test whether arbitrary Unicode strings are
supported as file names by checking @ref{eb9,,os.path.supports_unicode_filenames},
a Boolean value.

在 MacOS 下，@ref{b25,,os.listdir()} 现在可以返回 Unicode 文件名。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 277

@item PEP 277@footnote{https://www.python.org/dev/peps/pep-0277} - 针对 Windows NT 的 Unicode 文件名支持

由 Neil Hodgson 撰写 ; 由 Neil Hodgson, Martin von Löwis 和 Mark Hammond 实现。
@end table


@c ======================================================================

@geindex universal newlines; What's new

@node PEP 278 通用换行支持,PEP 279 enumerate,PEP 277 针对 Windows NT 的 Unicode 文件名支持,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-278-universal-newline-support}@anchor{eba}
@subsection PEP 278: 通用换行支持


The three major operating systems used today are Microsoft Windows, Apple's
Macintosh OS, and the various Unix derivatives.  A minor irritation of
cross-platform work  is that these three platforms all use different characters to
mark the ends of lines in text files.  Unix uses the linefeed (ASCII character
10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
two-character sequence of a carriage return plus a newline.

Python's file objects can now support end of line conventions other than the
one followed by the platform on which Python is running. Opening a file with
the mode @code{'U'} or @code{'rU'} will open a file for reading in @ref{6f5,,universal newlines} mode.  All three line ending conventions will be translated to a
@code{'\n'} in the strings returned by the various file methods such as
@code{read()} and @ref{de,,readline()}.

Universal newline support is also used when importing modules and when executing
a file with the @code{execfile()} function.  This means that Python modules can
be shared between all three operating systems without needing to convert the
line-endings.

This feature can be disabled when compiling Python by specifying the
@code{--without-universal-newlines} switch when running Python's
@code{configure} script.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 278

@item PEP 278@footnote{https://www.python.org/dev/peps/pep-0278} - 通用换行支持

由 Jack Jansen 撰写并实现。
@end table


@c ======================================================================

@node PEP 279 enumerate,PEP 282 logging 包,PEP 278 通用换行支持,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-279-enumerate}@anchor{ebb}@anchor{whatsnew/2 3 section-enumerate}@anchor{ebc}
@subsection PEP 279: enumerate()


A new built-in function, @ref{eaf,,enumerate()}, will make certain loops a bit
clearer.  @code{enumerate(thing)}, where @emph{thing} is either an iterator or a
sequence, returns an iterator that will return @code{(0, thing[0])}, @code{(1,
thing[1])}, @code{(2, thing[2])}, and so forth.

A common idiom to change every element of a list looks like this:

@example
for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result
@end example

可以使用 @ref{eaf,,enumerate()} 重写为：

@example
for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 279

@item PEP 279@footnote{https://www.python.org/dev/peps/pep-0279} - 内置函数 enumerate()

由 Raymond D. Hettinger 撰写并实现。
@end table


@c ======================================================================

@node PEP 282 logging 包,PEP 285 布尔类型,PEP 279 enumerate,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-282-the-logging-package}@anchor{ebd}
@subsection PEP 282: logging 包


A standard package for writing logs, @ref{aa,,logging}, has been added to Python
2.3.  It provides a powerful and flexible mechanism for generating logging
output which can then be filtered and processed in various ways.  A
configuration file written in a standard format can be used to control the
logging behavior of a program.  Python includes handlers that will write log
records to standard error or to a file or socket, send them to the system log,
or even e-mail them to a particular address; of course, it's also possible to
write your own handler classes.

The @code{Logger} class is the primary class. Most application code will deal
with one or more @code{Logger} objects, each one used by a particular
subsystem of the application. Each @code{Logger} is identified by a name, and
names are organized into a hierarchy using @code{.}  as the component separator.
For example, you might have @code{Logger} instances named @code{server},
@code{server.auth} and @code{server.network}.  The latter two instances are below
@code{server} in the hierarchy.  This means that if you turn up the verbosity for
@code{server} or direct @code{server} messages to a different handler, the changes
will also apply to records logged to @code{server.auth} and @code{server.network}.
There's also a root @code{Logger} that's the parent of all other loggers.

For simple uses, the @ref{aa,,logging} package contains some convenience functions
that always use the root log:

@example
import logging

logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
@end example

这会产生以下输出:

@example
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
@end example

In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable the display
of informational and debugging messages by calling the @code{setLevel()} method
on the root logger.

Notice the @code{warning()} call's use of string formatting operators; all of the
functions for logging messages take the arguments @code{(msg, arg1, arg2, ...)} and
log the string resulting from @code{msg % (arg1, arg2, ...)}.

There's also an @code{exception()} function that records the most recent
traceback.  Any of the other functions will also record the traceback if you
specify a true value for the keyword argument @emph{exc_info}.

@example
def f():
    try:    1/0
    except: logging.exception('Problem recorded')

f()
@end example

这会产生以下输出:

@example
ERROR:root:Problem recorded
Traceback (most recent call last):
  File "t.py", line 6, in f
    1/0
ZeroDivisionError: integer division or modulo by zero
@end example

Slightly more advanced programs will use a logger other than the root logger.
The @code{getLogger(name)} function is used to get a particular log, creating
it if it doesn't exist yet. @code{getLogger(None)} returns the root logger.

@example
log = logging.getLogger('server')
 ...
log.info('Listening on port %i', port)
 ...
log.critical('Disk full')
 ...
@end example

Log records are usually propagated up the hierarchy, so a message logged to
@code{server.auth} is also seen by @code{server} and @code{root}, but a @code{Logger}
can prevent this by setting its @code{propagate} attribute to @ref{497,,False}.

There are more classes provided by the @ref{aa,,logging} package that can be
customized.  When a @code{Logger} instance is told to log a message, it
creates a @code{LogRecord} instance that is sent to any number of different
@code{Handler} instances.  Loggers and handlers can also have an attached list
of filters, and each filter can cause the @code{LogRecord} to be ignored or
can modify the record before passing it along.  When they're finally output,
@code{LogRecord} instances are converted to text by a @code{Formatter}
class.  All of these classes can be replaced by your own specially-written
classes.

With all of these features the @ref{aa,,logging} package should provide enough
flexibility for even the most complicated applications.  This is only an
incomplete overview of its features, so please see the package's reference
documentation for all of the details.  Reading 
@geindex Python 提高建议; PEP 282
PEP 282@footnote{https://www.python.org/dev/peps/pep-0282} will also be helpful.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 282

@item PEP 282@footnote{https://www.python.org/dev/peps/pep-0282} - Logging 系统

由 Vinay Sajip 和 Trent Mick 撰写 ; 由 Vinay Sajip 实现。
@end table


@c ======================================================================

@node PEP 285 布尔类型,PEP 293 Codec Error Handling Callbacks,PEP 282 logging 包,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-285-a-boolean-type}@anchor{ebe}@anchor{whatsnew/2 3 section-bool}@anchor{ebf}
@subsection PEP 285: 布尔类型


A Boolean type was added to Python 2.3.  Two new constants were added to the
@code{__builtin__} module, @ref{59c,,True} and @ref{497,,False}.  (@ref{59c,,True} and
@ref{497,,False} constants were added to the built-ins in Python 2.2.1, but the
2.2.1 versions are simply set to integer values of 1 and 0 and aren't a
different type.)

The type object for this new type is named @ref{2c4,,bool}; the constructor for it
takes any Python value and converts it to @ref{59c,,True} or @ref{497,,False}.

@example
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True
@end example

Most of the standard library modules and built-in functions have been changed to
return Booleans.

@example
>>> obj = []
>>> hasattr(obj, 'append')
True
>>> isinstance(obj, list)
True
>>> isinstance(obj, tuple)
False
@end example

Python's Booleans were added with the primary goal of making code clearer.  For
example, if you're reading a function and encounter the statement @code{return 1},
you might wonder whether the @code{1} represents a Boolean truth value, an index,
or a coefficient that multiplies some other quantity.  If the statement is
@code{return True}, however, the meaning of the return value is quite clear.

Python's Booleans were @emph{not} added for the sake of strict type-checking.  A very
strict language such as Pascal would also prevent you performing arithmetic with
Booleans, and would require that the expression in an @ref{eb3,,if} statement
always evaluate to a Boolean result.  Python is not this strict and never will
be, as 
@geindex Python 提高建议; PEP 285
PEP 285@footnote{https://www.python.org/dev/peps/pep-0285} explicitly says.  This means you can still use any expression
in an @code{if} statement, even ones that evaluate to a list or tuple or
some random object.  The Boolean type is a subclass of the @ref{205,,int} class so
that arithmetic using a Boolean still works.

@example
>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75
@end example

To sum up @ref{59c,,True} and @ref{497,,False} in a sentence: they're alternative
ways to spell the integer values 1 and 0, with the single difference that
@ref{206,,str()} and @ref{8c3,,repr()} return the strings @code{'True'} and @code{'False'}
instead of @code{'1'} and @code{'0'}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 285

@item PEP 285@footnote{https://www.python.org/dev/peps/pep-0285} - 添加布尔类型

由 GvR 撰写并实现。
@end table


@c ======================================================================

@node PEP 293 Codec Error Handling Callbacks,PEP 301 Distutils的软件包索引和元数据,PEP 285 布尔类型,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-293-codec-error-handling-callbacks}@anchor{ec0}
@subsection PEP 293: Codec Error Handling Callbacks


When encoding a Unicode string into a byte string, unencodable characters may be
encountered.  So far, Python has allowed specifying the error processing as
either "strict" (raising @ref{d0b,,UnicodeError}), "ignore" (skipping the
character), or "replace" (using a question mark in the output string), with
"strict" being the default behavior. It may be desirable to specify alternative
processing of such errors, such as inserting an XML character reference or HTML
entity reference into the converted string.

Python now has a flexible framework to add different processing strategies.  New
error handlers can be added with @ref{ec1,,codecs.register_error()}, and codecs then
can access the error handler with @ref{ec2,,codecs.lookup_error()}. An equivalent C
API has been added for codecs written in C. The error handler gets the necessary
state information such as the string being converted, the position in the string
where the error was detected, and the target encoding.  The handler can then
either raise an exception or return a replacement string.

Two additional error handlers have been implemented using this framework:
"backslashreplace" uses Python backslash quoting to represent unencodable
characters and "xmlcharrefreplace" emits XML character references.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 293

@item PEP 293@footnote{https://www.python.org/dev/peps/pep-0293} - Codec Error Handling Callbacks

由 Walter Dörwald 撰写并实现。
@end table


@c ======================================================================

@node PEP 301 Distutils的软件包索引和元数据,PEP 302 新导入钩子,PEP 293 Codec Error Handling Callbacks,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-301-package-index-and-metadata-for-distutils}@anchor{ec3}@anchor{whatsnew/2 3 section-pep301}@anchor{ec4}
@subsection PEP 301: Distutils的软件包索引和元数据


Support for the long-requested Python catalog makes its first appearance in 2.3.

The heart of the catalog is the new Distutils @code{register} command.
Running @code{python setup.py register} will collect the metadata describing a
package, such as its name, version, maintainer, description, &c., and send it to
a central catalog server.  The resulting catalog is available from
@indicateurl{https://pypi.org}.

To make the catalog a bit more useful, a new optional @emph{classifiers} keyword
argument has been added to the Distutils @code{setup()} function.  A list of
Trove@footnote{http://catb.org/~esr/trove/}-style strings can be supplied to help
classify the software.

Here's an example @code{setup.py} with classifiers, written to be compatible
with older versions of the Distutils:

@example
from distutils import core
kw = @{'name': "Quixote",
      'version': "0.5.1",
      'description': "A highly Pythonic Web application framework",
      # ...
      @}

if (hasattr(core, 'setup_keywords') and
    'classifiers' in core.setup_keywords):
    kw['classifiers'] = \
        ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
         'Environment :: No Input/Output (Daemon)',
         'Intended Audience :: Developers'],

core.setup(**kw)
@end example

The full list of classifiers can be obtained by running  @code{python setup.py
register --list-classifiers}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 301

@item PEP 301@footnote{https://www.python.org/dev/peps/pep-0301} - Distutils 的软件包索引和元数据

由 Richard Jones 撰写并实现。
@end table


@c ======================================================================

@node PEP 302 新导入钩子,PEP 305 逗号分隔文件,PEP 301 Distutils的软件包索引和元数据,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-302-new-import-hooks}@anchor{ec5}@anchor{whatsnew/2 3 section-pep302}@anchor{eb7}
@subsection PEP 302: 新导入钩子


While it's been possible to write custom import hooks ever since the
@code{ihooks} module was introduced in Python 1.3, no one has ever been really
happy with it because writing new import hooks is difficult and messy.  There
have been various proposed alternatives such as the @code{imputil} and @code{iu}
modules, but none of them has ever gained much acceptance, and none of them were
easily usable from C code.

@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} borrows ideas from its predecessors, especially from Gordon
McMillan's @code{iu} module.  Three new items  are added to the @ref{fd,,sys}
module:


@itemize *

@item 
@code{sys.path_hooks} is a list of callable objects; most  often they'll be
classes.  Each callable takes a string containing a path and either returns an
importer object that will handle imports from this path or raises an
@ref{16c,,ImportError} exception if it can't handle this path.

@item 
@code{sys.path_importer_cache} caches importer objects for each path, so
@code{sys.path_hooks} will only need to be traversed once for each path.

@item 
@code{sys.meta_path} is a list of importer objects that will be traversed before
@code{sys.path} is checked.  This list is initially empty, but user code can add
objects to it.  Additional built-in and frozen modules can be imported by an
object added to this list.
@end itemize

Importer objects must have a single method, @code{find_module(fullname,
path=None)}.  @emph{fullname} will be a module or package name, e.g. @code{string} or
@code{distutils.core}.  @code{find_module()} must return a loader object that has a
single method, @code{load_module(fullname)}, that creates and returns the
corresponding module object.

Pseudo-code for Python's new import logic, therefore, looks something like this
(simplified a bit; see 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} for the full details):

@example
for mp in sys.meta_path:
    loader = mp(fullname)
    if loader is not None:
        <module> = loader.load_module(fullname)

for path in sys.path:
    for hook in sys.path_hooks:
        try:
            importer = hook(path)
        except ImportError:
            # ImportError, so try the other path hooks
            pass
        else:
            loader = importer.find_module(fullname)
            <module> = loader.load_module(fullname)

# Not found!
raise ImportError
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 302

@item PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} - 新导入钩

由 Just van Rossum 和 Paul Moore 撰写 ; 由 Just van Rossum 实现。
@end table


@c ======================================================================

@node PEP 305 逗号分隔文件,PEP 307 Pickle Enhancements,PEP 302 新导入钩子,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-305-comma-separated-files}@anchor{ec6}@anchor{whatsnew/2 3 section-pep305}@anchor{ec7}
@subsection PEP 305: 逗号分隔文件


Comma-separated files are a format frequently used for exporting data from
databases and spreadsheets.  Python 2.3 adds a parser for comma-separated files.

Comma-separated format is deceptively simple at first glance:

@example
Costs,150,200,3.95
@end example

Read a line and call @code{line.split(',')}: what could be simpler? But toss in
string data that can contain commas, and things get more complicated:

@example
"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
@end example

A big ugly regular expression can parse this, but using the new  @ref{29,,csv}
package is much simpler:

@example
import csv

input = open('datafile', 'rb')
reader = csv.reader(input)
for line in reader:
    print line
@end example

The @code{reader()} function takes a number of different options. The field
separator isn't limited to the comma and can be changed to any character, and so
can the quoting and line-ending characters.

Different dialects of comma-separated files can be defined and registered;
currently there are two dialects, both used by Microsoft Excel. A separate
@ref{ec8,,csv.writer} class will generate comma-separated files from a succession
of tuples or lists, quoting strings that contain the delimiter.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 305

@item PEP 305@footnote{https://www.python.org/dev/peps/pep-0305} - CSV 文件 API

由 Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells 撰写并实现。
@end table


@c ======================================================================

@node PEP 307 Pickle Enhancements,扩展切片,PEP 305 逗号分隔文件,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pep-307-pickle-enhancements}@anchor{ec9}@anchor{whatsnew/2 3 section-pep307}@anchor{eca}
@subsection PEP 307: Pickle Enhancements


The @ref{ca,,pickle} and @code{cPickle} modules received some attention during the
2.3 development cycle.  In 2.2, new-style classes could be pickled without
difficulty, but they weren't pickled very compactly; 
@geindex Python 提高建议; PEP 307
PEP 307@footnote{https://www.python.org/dev/peps/pep-0307} quotes a trivial
example where a new-style class results in a pickled string three times longer
than that for a classic class.

The solution was to invent a new pickle protocol.  The @ref{ecb,,pickle.dumps()}
function has supported a text-or-binary flag  for a long time.  In 2.3, this
flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
format, 1 is the old binary format, and now 2 is a new 2.3-specific format.  A
new constant, @ref{ecc,,pickle.HIGHEST_PROTOCOL}, can be used to select the
fanciest protocol available.

Unpickling is no longer considered a safe operation.  2.2's @ref{ca,,pickle}
provided hooks for trying to prevent unsafe classes from being unpickled
(specifically, a @code{__safe_for_unpickling__} attribute), but none of this
code was ever audited and therefore it's all been ripped out in 2.3.  You should
not unpickle untrusted data in any version of Python.

To reduce the pickling overhead for new-style classes, a new interface for
customizing pickling was added using three special methods:
@ref{ecd,,__getstate__()}, @ref{2d8,,__setstate__()}, and @ref{7ab,,__getnewargs__()}.  Consult
@geindex Python 提高建议; PEP 307
PEP 307@footnote{https://www.python.org/dev/peps/pep-0307} for the full semantics  of these methods.

As a way to compress pickles yet further, it's now possible to use integer codes
instead of long strings to identify pickled classes. The Python Software
Foundation will maintain a list of standardized codes; there's also a range of
codes for private use.  Currently no codes have been specified.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 307

@item PEP 307@footnote{https://www.python.org/dev/peps/pep-0307} - Extensions to the pickle protocol

PEP 由 Guido van Rossum 和 Tim Peters 撰写和实现。
@end table


@c ======================================================================

@node 扩展切片,其他语言特性修改<14>,PEP 307 Pickle Enhancements,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 extended-slices}@anchor{ece}@anchor{whatsnew/2 3 section-slices}@anchor{ecf}
@subsection 扩展切片


Ever since Python 1.4, the slicing syntax has supported an optional third "step"
or "stride" argument.  For example, these are all legal Python syntax:
@code{L[1:10:2]}, @code{L[:-1:1]}, @code{L[::-1]}.  This was added to Python at the
request of the developers of Numerical Python, which uses the third argument
extensively.  However, Python's built-in list, tuple, and string sequence types
have never supported this feature, raising a @ref{1ff,,TypeError} if you tried it.
Michael Hudson contributed a patch to fix this shortcoming.

For example, you can now easily extract the elements of a list that have even
indexes:

@example
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
@end example

Negative values also work to make a copy of the same list in reverse order:

@example
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
@end example

This also works for tuples, arrays, and strings:

@example
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
@end example

If you have a mutable sequence such as a list or an array you can assign to or
delete an extended slice, but there are some differences between assignment to
extended and regular slices.  Assignment to a regular slice can be used to
change the length of the sequence:

@example
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
@end example

Extended slices aren't this flexible.  When assigning to an extended slice, the
list on the right hand side of the statement must contain the same number of
items as the slice it is replacing:

@example
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
@end example

Deletion is more straightforward:

@example
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
@end example

One can also now pass slice objects to the @ref{3ad,,__getitem__()} methods of the
built-in sequences:

@example
>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]
@end example

Or use slice objects directly in subscripts:

@example
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]
@end example

To simplify implementing sequences that support extended slicing, slice objects
now have a method @code{indices(length)} which, given the length of a sequence,
returns a @code{(start, stop, step)} tuple that can be passed directly to
@ref{1f6,,range()}. @code{indices()} handles omitted and out-of-bounds indices in a
manner consistent with regular slices (and this innocuous phrase hides a welter
of confusing details!).  The method is intended to be used like this:

@example
class FakeSeq:
    ...
    def calc_item(self, i):
        ...
    def __getitem__(self, item):
        if isinstance(item, slice):
            indices = item.indices(len(self))
            return FakeSeq([self.calc_item(i) for i in range(*indices)])
        else:
            return self.calc_item(i)
@end example

From this example you can also see that the built-in @ref{ed0,,slice} object is
now the type object for the slice type, and is no longer a function.  This is
consistent with Python 2.2, where @ref{205,,int}, @ref{206,,str}, etc., underwent
the same change.

@c ======================================================================

@node 其他语言特性修改<14>,新增，改进和弃用的模块<4>,扩展切片,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 other-language-changes}@anchor{ed1}
@subsection 其他语言特性修改


Here are all of the changes that Python 2.3 makes to the core Python language.


@itemize *

@item 
The @ref{2ce,,yield} statement is now always a keyword, as described in
section @ref{eb2,,PEP 255; 简单的生成器} of this document.

@item 
A new built-in function @ref{eaf,,enumerate()} was added, as described in section
@ref{ebc,,PEP 279; enumerate()} of this document.

@item 
Two new constants, @ref{59c,,True} and @ref{497,,False} were added along with the
built-in @ref{2c4,,bool} type, as described in section @ref{ebf,,PEP 285; 布尔类型} of this
document.

@item 
The @ref{205,,int()} type constructor will now return a long integer instead of
raising an @ref{a4a,,OverflowError} when a string or floating-point number is too
large to fit into an integer.  This can lead to the paradoxical result that
@code{isinstance(int(expression), int)} is false, but that seems unlikely to cause
problems in practice.

@item 
Built-in types now support the extended slicing syntax, as described in
section @ref{ecf,,扩展切片} of this document.

@item 
A new built-in function, @code{sum(iterable, start=0)},  adds up the numeric
items in the iterable object and returns their sum.  @ref{31d,,sum()} only accepts
numbers, meaning that you can't use it to concatenate a bunch of strings.
(Contributed by Alex Martelli.)

@item 
@code{list.insert(pos, value)} used to  insert @emph{value} at the front of the list
when @emph{pos} was negative.  The behaviour has now been changed to be consistent
with slice indexing, so when @emph{pos} is -1 the value will be inserted before the
last element, and so forth.

@item 
@code{list.index(value)}, which searches for @emph{value}  within the list and returns
its index, now takes optional  @emph{start} and @emph{stop} arguments to limit the search
to  only part of the list.

@item 
Dictionaries have a new method, @code{pop(key[, *default*])}, that returns
the value corresponding to @emph{key} and removes that key/value pair from the
dictionary.  If the requested key isn't present in the dictionary, @emph{default} is
returned if it's specified and @ref{3f1,,KeyError} raised if it isn't.

@example
>>> d = @{1:2@}
>>> d
@{1: 2@}
>>> d.pop(4)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 4
>>> d.pop(1)
2
>>> d.pop(1)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 'pop(): dictionary is empty'
>>> d
@{@}
>>>
@end example

There's also a new class method,  @code{dict.fromkeys(iterable, value)}, that
creates a dictionary with keys taken from the supplied iterator @emph{iterable} and
all values set to @emph{value}, defaulting to @code{None}.

(Patches contributed by Raymond Hettinger.)

Also, the @ref{164,,dict()} constructor now accepts keyword arguments to simplify
creating small dictionaries:

@example
>>> dict(red=1, blue=2, green=3, black=4)
@{'blue': 2, 'black': 4, 'green': 3, 'red': 1@}
@end example

（由 Just van Rossum 贡献。）

@item 
The @ref{240,,assert} statement no longer checks the @code{__debug__} flag, so
you can no longer disable assertions by assigning to @code{__debug__}. Running
Python with the @ref{788,,-O} switch will still generate code that doesn't
execute any assertions.

@item 
Most type objects are now callable, so you can use them to create new objects
such as functions, classes, and modules.  (This means that the @code{new} module
can be deprecated in a future Python version, because you can now use the type
objects available in the @ref{121,,types} module.) For example, you can create a new
module object with the following code:

@example
>>> import types
>>> m = types.ModuleType('abc','docstring')
>>> m
<module 'abc' (built-in)>
>>> m.__doc__
'docstring'
@end example

@item 
A new warning, @ref{15c,,PendingDeprecationWarning} was added to indicate features
which are in the process of being deprecated.  The warning will @emph{not} be printed
by default.  To check for use of features that will be deprecated in the future,
supply @ref{15b,,-Walways;;PendingDeprecationWarning;;} on the command line or
use @ref{ed2,,warnings.filterwarnings()}.

@item 
The process of deprecating string-based exceptions, as in @code{raise "Error
occurred"}, has begun.  Raising a string will now trigger
@ref{15c,,PendingDeprecationWarning}.

@item 
现在使用 @code{None} 作为变量名将导致 @ref{2d0,,SyntaxWarning} 警告。 在未来的 Python 版本中，@code{None} 将最终成为一个保留关键字。

@item 
The @code{xreadlines()} method of file objects, introduced in Python 2.1, is no
longer necessary because files now behave as their own iterator.
@code{xreadlines()} was originally introduced as a faster way to loop over all
the lines in a file, but now you can simply write @code{for line in file_obj}.
File objects also have a new read-only @code{encoding} attribute that gives the
encoding used by the file; Unicode strings written to the file will be
automatically  converted to bytes using the given encoding.

@item 
The method resolution order used by new-style classes has changed, though
you'll only notice the difference if you have a really complicated inheritance
hierarchy.  Classic classes are unaffected by this change.  Python 2.2
originally used a topological sort of a class's ancestors, but 2.3 now uses the
C3 algorithm as described in the paper "A Monotonic Superclass Linearization for Dylan"@footnote{http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910}. To
understand the motivation for this change,  read Michele Simionato's article
"Python 2.3 Method Resolution Order"@footnote{http://www.phyast.pitt.edu/~micheles/mro.html}, or
read the thread on python-dev starting with the message at
@indicateurl{https://mail.python.org/pipermail/python-dev/2002-October/029035.html}. Samuele
Pedroni first pointed out the problem and also implemented the fix by coding the
C3 algorithm.

@item 
Python runs multithreaded programs by switching between threads after
executing N bytecodes.  The default value for N has been increased from 10 to
100 bytecodes, speeding up single-threaded applications by reducing the
switching overhead.  Some multithreaded applications may suffer slower response
time, but that's easily fixed by setting the limit back to a lower number using
@code{sys.setcheckinterval(N)}. The limit can be retrieved with the new
@code{sys.getcheckinterval()} function.

@item 
One minor but far-reaching change is that the names of extension types defined
by the modules included with Python now contain the module and a @code{'.'} in
front of the type name.  For example, in Python 2.2, if you created a socket and
printed its @code{__class__}, you'd get this output:

@example
>>> s = socket.socket()
>>> s.__class__
<type 'socket'>
@end example

In 2.3, you get this:

@example
>>> s.__class__
<type '_socket.socket'>
@end example

@item 
One of the noted incompatibilities between old- and new-style classes has been
removed: you can now assign to the @ref{d37,,__name__} and @ref{ed3,,__bases__}
attributes of new-style classes.  There are some restrictions on what can be
assigned to @ref{ed3,,__bases__} along the lines of those relating to assigning to
an instance's @ref{ed4,,__class__} attribute.
@end itemize

@c ======================================================================

@menu
* String Changes:: 
* 性能优化: 性能优化<13>. 

@end menu

@node String Changes,性能优化<13>,,其他语言特性修改<14>
@anchor{whatsnew/2 3 string-changes}@anchor{ed5}
@subsubsection String Changes



@itemize *

@item 
The @ref{179,,in} operator now works differently for strings. Previously, when
evaluating @code{X in Y} where @emph{X} and @emph{Y} are strings, @emph{X} could only be a single
character. That's now changed; @emph{X} can be a string of any length, and @code{X in Y}
will return @ref{59c,,True} if @emph{X} is a substring of @emph{Y}.  If @emph{X} is the empty
string, the result is always @ref{59c,,True}.

@example
>>> 'ab' in 'abcd'
True
>>> 'ad' in 'abcd'
False
>>> '@w{'} in 'abcd'
True
@end example

Note that this doesn't tell you where the substring starts; if you need that
information, use the @code{find()} string method.

@item 
The @code{strip()}, @code{lstrip()}, and @code{rstrip()} string methods now have
an optional argument for specifying the characters to strip.  The default is
still to remove all whitespace characters:

@example
>>> '   abc '.strip()
'abc'
>>> '><><abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>>
@end example

(Suggested by Simon Brunning and implemented by Walter Dörwald.)

@item 
The @code{startswith()} and @code{endswith()} string methods now accept negative
numbers for the @emph{start} and @emph{end} parameters.

@item 
Another new string method is @code{zfill()}, originally a function in the
@ref{f6,,string} module.  @code{zfill()} pads a numeric string with zeros on the
left until it's the specified width. Note that the @code{%} operator is still more
flexible and powerful than @code{zfill()}.

@example
>>> '45'.zfill(4)
'0045'
>>> '12345'.zfill(4)
'12345'
>>> 'goofy'.zfill(6)
'0goofy'
@end example

（由 Walter Dörwald 贡献。）

@item 
A new type object, @code{basestring}, has been added. Both 8-bit strings and
Unicode strings inherit from this type, so @code{isinstance(obj, basestring)} will
return @ref{59c,,True} for either kind of string.  It's a completely abstract
type, so you can't create @code{basestring} instances.

@item 
Interned strings are no longer immortal and will now be garbage-collected in
the usual way when the only reference to them is from the internal dictionary of
interned strings.  (Implemented by Oren Tirosh.)
@end itemize

@c ======================================================================

@node 性能优化<13>,,String Changes,其他语言特性修改<14>
@anchor{whatsnew/2 3 optimizations}@anchor{ed6}
@subsubsection 性能优化



@itemize *

@item 
The creation of new-style class instances has been made much faster; they're
now faster than classic classes!

@item 
The @code{sort()} method of list objects has been extensively rewritten by Tim
Peters, and the implementation is significantly faster.

@item 
Multiplication of large long integers is now much faster thanks to an
implementation of Karatsuba multiplication, an algorithm that scales better than
the O(n*n) required for the grade-school multiplication algorithm.  (Original
patch by Christopher A. Craig, and significantly reworked by Tim Peters.)

@item 
The @code{SET_LINENO} opcode is now gone.  This may provide a small speed
increase, depending on your compiler's idiosyncrasies. See section
@ref{ed7,,其他的改变和修正} for a longer explanation. (Removed by Michael Hudson.)

@item 
@code{xrange()} objects now have their own iterator, making @code{for i in
xrange(n)} slightly faster than @code{for i in range(n)}.  (Patch by Raymond
Hettinger.)

@item 
A number of small rearrangements have been made in various hotspots to improve
performance, such as inlining a function or removing some code.  (Implemented
mostly by GvR, but lots of people have contributed single changes.)
@end itemize

The net result of the 2.3 optimizations is that Python 2.3 runs the  pystone
benchmark around 25% faster than Python 2.2.

@c ======================================================================

@node 新增，改进和弃用的模块<4>,Pymalloc A Specialized Object Allocator,其他语言特性修改<14>,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 new-improved-and-deprecated-modules}@anchor{ed8}
@subsection 新增，改进和弃用的模块


As usual, Python's standard library received a number of enhancements and bug
fixes.  Here's a partial list of the most notable changes, sorted alphabetically
by module name. Consult the @code{Misc/NEWS} file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.


@itemize *

@item 
The @ref{6,,array} module now supports arrays of Unicode characters using the
@code{'u'} format character.  Arrays also now support using the @code{+=} assignment
operator to add another array's contents, and the @code{*=} assignment operator to
repeat an array. (Contributed by Jason Orendorff.)

@item 
The @code{bsddb} module has been replaced by version 4.1.6 of the PyBSDDB@footnote{http://pybsddb.sourceforge.net} package, providing a more complete interface
to the transactional features of the BerkeleyDB library.

The old version of the module has been renamed to  @code{bsddb185} and is no
longer built automatically; you'll  have to edit @code{Modules/Setup} to enable
it.  Note that the new @code{bsddb} package is intended to be compatible with
the  old module, so be sure to file bugs if you discover any incompatibilities.
When upgrading to Python 2.3, if the new interpreter is compiled with a new
version of  the underlying BerkeleyDB library, you will almost certainly have to
convert your database files to the new version.  You can do this fairly easily
with the new scripts @code{db2pickle.py} and @code{pickle2db.py} which you
will find in the distribution's @code{Tools/scripts} directory.  If you've
already been using the PyBSDDB package and importing it as @code{bsddb3}, you
will have to change your @code{import} statements to import it as @code{bsddb}.

@item 
The new @ref{13,,bz2} module is an interface to the bz2 data compression library.
bz2-compressed data is usually smaller than  corresponding
@ref{14d,,zlib}-compressed data. (Contributed by Gustavo Niemeyer.)

@item 
A set of standard date/time types has been added in the new @ref{30,,datetime}
module.  See the following section for more details.

@item 
The Distutils @code{Extension} class now supports an extra constructor
argument named @emph{depends} for listing additional source files that an extension
depends on.  This lets Distutils recompile the module if any of the dependency
files are modified.  For example, if @code{sampmodule.c} includes the header
file @code{sample.h}, you would create the @code{Extension} object like
this:

@example
ext = Extension("samp",
                sources=["sampmodule.c"],
                depends=["sample.h"])
@end example

Modifying @code{sample.h} would then cause the module to be recompiled.
(Contributed by Jeremy Hylton.)

@item 
Other minor changes to Distutils: it now checks for the 
@geindex CC
@geindex 环境变量; CC
@code{CC},
@geindex CFLAGS
@geindex 环境变量; CFLAGS
@code{CFLAGS}, 
@geindex CPP
@geindex 环境变量; CPP
@code{CPP}, 
@geindex LDFLAGS
@geindex 环境变量; LDFLAGS
@code{LDFLAGS}, and 
@geindex CPPFLAGS
@geindex 环境变量; CPPFLAGS
@code{CPPFLAGS}
environment variables, using them to override the settings in Python's
configuration (contributed by Robert Weber).

@item 
Previously the @ref{66,,doctest} module would only search the docstrings of
public methods and functions for test cases, but it now also examines private
ones as well.  The @code{DocTestSuite()} function creates a
@ref{7cb,,unittest.TestSuite} object from a set of @ref{66,,doctest} tests.

@item 
新的 @code{gc.get_referents(object)} 函数将返回由 @emph{object} 引用的所有对象组成的列表。

@item 
The @ref{85,,getopt} module gained a new function, @code{gnu_getopt()}, that
supports the same arguments as the existing @ref{85,,getopt()} function but uses
GNU-style scanning mode. The existing @ref{85,,getopt()} stops processing options as
soon as a non-option argument is encountered, but in GNU-style mode processing
continues, meaning that options and arguments can be mixed.  For example:

@example
>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename')], ['output', '-v'])
>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename'), ('-v', '@w{'})], ['output'])
@end example

（由 Peter Åstrand 贡献。）

@item 
The @ref{8a,,grp}, @ref{d6,,pwd}, and @ref{e0,,resource} modules now return enhanced
tuples:

@example
>>> import grp
>>> g = grp.getgrnam('amk')
>>> g.gr_name, g.gr_gid
('amk', 500)
@end example

@item 
The @ref{8b,,gzip} module can now handle files exceeding 2 GiB.

@item 
The new @ref{8d,,heapq} module contains an implementation of a heap queue
algorithm.  A heap is an array-like data structure that keeps items in a
partially sorted order such that, for every index @emph{k}, @code{heap[k] <=
heap[2*k+1]} and @code{heap[k] <= heap[2*k+2]}.  This makes it quick to remove the
smallest item, and inserting a new item while maintaining the heap property is
O(lg n).  (See @indicateurl{https://xlinux.nist.gov/dads//HTML/priorityque.html} for more
information about the priority queue data structure.)

The @ref{8d,,heapq} module provides @code{heappush()} and @code{heappop()} functions
for adding and removing items while maintaining the heap property on top of some
other mutable Python sequence type.  Here's an example that uses a Python list:

@example
>>> import heapq
>>> heap = []
>>> for item in [3, 7, 5, 11, 1]:
...    heapq.heappush(heap, item)
...
>>> heap
[1, 3, 5, 11, 7]
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
3
>>> heap
[5, 7, 11]
@end example

（由 Kevin O'Connor 贡献。）

@item 
The IDLE integrated development environment has been updated using the code
from the IDLEfork project (@indicateurl{http://idlefork.sourceforge.net}).  The most notable feature is
that the code being developed is now executed in a subprocess, meaning that
there's no longer any need for manual @code{reload()} operations. IDLE's core code
has been incorporated into the standard library as the @code{idlelib} package.

@item 
The @ref{97,,imaplib} module now supports IMAP over SSL. (Contributed by Piers
Lauder and Tino Lange.)

@item 
The @ref{a3,,itertools} contains a number of useful functions for use with
iterators, inspired by various functions provided by the ML and Haskell
languages.  For example, @code{itertools.ifilter(predicate, iterator)} returns all
elements in the iterator for which the function @code{predicate()} returns
@ref{59c,,True}, and @code{itertools.repeat(obj, N)} returns @code{obj} @emph{N} times.
There are a number of other functions in the module; see the package's reference
documentation for details.
(Contributed by Raymond Hettinger.)

@item 
Two new functions in the @ref{b1,,math} module, @code{degrees(rads)} and
@code{radians(degs)}, convert between radians and degrees.  Other functions in
the @ref{b1,,math} module such as @ref{ed9,,math.sin()} and @ref{eda,,math.cos()} have always
required input values measured in radians.  Also, an optional @emph{base} argument
was added to @ref{edb,,math.log()} to make it easier to compute logarithms for bases
other than @code{e} and @code{10}.  (Contributed by Raymond Hettinger.)

@item 
Several new POSIX functions (@code{getpgid()}, @code{killpg()}, @code{lchown()},
@code{loadavg()}, @code{major()}, @code{makedev()}, @code{minor()}, and
@code{mknod()}) were added to the @ref{d1,,posix} module that underlies the
@ref{c4,,os} module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
Otkidach.)

@item 
In the @ref{c4,,os} module, the @code{*stat()} family of functions can now report
fractions of a second in a timestamp.  Such time stamps are represented as
floats, similar to the value returned by @ref{436,,time.time()}.

During testing, it was found that some applications will break if time stamps
are floats.  For compatibility, when using the tuple interface of the
@code{stat_result} time stamps will be represented as integers. When using
named fields (a feature first introduced in Python 2.2), time stamps are still
represented as integers, unless @code{os.stat_float_times()} is invoked to enable
float return values:

@example
>>> os.stat("/tmp").st_mtime
1034791200
>>> os.stat_float_times(True)
>>> os.stat("/tmp").st_mtime
1034791200.6335014
@end example

在 Python 2.4 中，默认将改为总是返回浮点数。

Application developers should enable this feature only if all their libraries
work properly when confronted with floating point time stamps, or if they use
the tuple API. If used, the feature should be activated on an application level
instead of trying to enable it on a per-use basis.

@item 
The @ref{c3,,optparse} module contains a new parser for command-line arguments
that can convert option values to a particular Python type  and will
automatically generate a usage message.  See the following section for  more
details.

@item 
The old and never-documented @code{linuxaudiodev} module has been deprecated,
and a new version named @ref{c6,,ossaudiodev} has been added.  The module was
renamed because the OSS sound drivers can be used on platforms other than Linux,
and the interface has also been tidied and brought up to date in various ways.
(Contributed by Greg Ward and Nicholas FitzRoy-Dale.)

@item 
The new @ref{ce,,platform} module contains a number of functions that try to
determine various properties of the platform you're running on.  There are
functions for getting the architecture, CPU type, the Windows OS version, and
even the Linux distribution version. (Contributed by Marc-André Lemburg.)

@item 
The parser objects provided by the @code{pyexpat} module can now optionally
buffer character data, resulting in fewer calls to your character data handler
and therefore faster performance.  Setting the parser object's
@code{buffer_text} attribute to @ref{59c,,True} will enable buffering.

@item 
The @code{sample(population, k)} function was added to the @ref{dc,,random}
module.  @emph{population} is a sequence or @code{xrange} object containing the
elements of a population, and @code{sample()} chooses @emph{k} elements from the
population without replacing chosen elements.  @emph{k} can be any value up to
@code{len(population)}. For example:

@example
>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
>>> random.sample(days, 3)      # Choose 3 elements
['St', 'Sn', 'Th']
>>> random.sample(days, 7)      # Choose 7 elements
['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
>>> random.sample(days, 7)      # Choose 7 again
['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
>>> random.sample(days, 8)      # Can't choose eight
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "random.py", line 414, in sample
      raise ValueError, "sample larger than population"
ValueError: sample larger than population
>>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
@end example

The @ref{dc,,random} module now uses a new algorithm, the Mersenne Twister,
implemented in C.  It's faster and more extensively studied than the previous
algorithm.

（所有改变均由 Raymond Hettinger 贡献。）

@item 
The @ref{de,,readline} module also gained a number of new functions:
@code{get_history_item()}, @code{get_current_history_length()}, and
@code{redisplay()}.

@item 
The @code{rexec} and @code{Bastion} modules have been declared dead, and
attempts to import them will fail with a @ref{3e4,,RuntimeError}.  New-style classes
provide new ways to break out of the restricted execution environment provided
by @code{rexec}, and no one has interest in fixing them or time to do so.  If
you have applications using @code{rexec}, rewrite them to use something else.

(Sticking with Python 2.2 or 2.1 will not make your applications any safer
because there are known bugs in the @code{rexec} module in those versions.  To
repeat: if you're using @code{rexec}, stop using it immediately.)

@item 
The @code{rotor} module has been deprecated because the  algorithm it uses for
encryption is not believed to be secure.  If you need encryption, use one of the
several AES Python modules that are available separately.

@item 
The @ref{e9,,shutil} module gained a @code{move(src, dest)} function that
recursively moves a file or directory to a new location.

@item 
Support for more advanced POSIX signal handling was added to the @ref{ea,,signal}
but then removed again as it proved impossible to make it work reliably across
platforms.

@item 
The @ref{ef,,socket} module now supports timeouts.  You can call the
@code{settimeout(t)} method on a socket object to set a timeout of @emph{t} seconds.
Subsequent socket operations that take longer than @emph{t} seconds to complete will
abort and raise a @ref{ce1,,socket.timeout} exception.

The original timeout implementation was by Tim O'Malley.  Michael Gilfix
integrated it into the Python @ref{ef,,socket} module and shepherded it through a
lengthy review.  After the code was checked in, Guido van Rossum rewrote parts
of it.  (This is a good example of a collaborative development process in
action.)

@item 
在 Windows，@ref{ef,,socket} 模块现在将附带安全套接字层（SSL）支持。

@item 
现在 C @code{PYTHON_API_VERSION} 宏的值将在 Python 层级上暴露为 @code{sys.api_version}。 当前的异常可通过调用新的 @code{sys.exc_clear()} 函数来清除。

@item 
The new @ref{101,,tarfile} module  allows reading from and writing to
@code{tar}-format archive files. (Contributed by Lars Gustäbel.)

@item 
The new @ref{10a,,textwrap} module contains functions for wrapping strings
containing paragraphs of text.  The @code{wrap(text, width)} function takes a
string and returns a list containing the text split into lines of no more than
the chosen width.  The @code{fill(text, width)} function returns a single
string, reformatted to fit into lines no longer than the chosen width. (As you
can guess, @code{fill()} is built on top of @code{wrap()}.  For example:

@example
>>> import textwrap
>>> paragraph = "Not a whit, we defy augury: ... more text ..."
>>> textwrap.wrap(paragraph, 60)
["Not a whit, we defy augury: there's a special providence in",
 "the fall of a sparrow. If it be now, 'tis not to come; if it",
 ...]
>>> print textwrap.fill(paragraph, 35)
Not a whit, we defy augury: there's
a special providence in the fall of
a sparrow. If it be now, 'tis not
to come; if it be not to come, it
will be now; if it be not now, yet
it will come: the readiness is all.
>>>
@end example

The module also contains a @code{TextWrapper} class that actually implements
the text wrapping strategy.   Both the @code{TextWrapper} class and the
@code{wrap()} and @code{fill()} functions support a number of additional keyword
arguments for fine-tuning the formatting; consult the module's documentation
for details. (Contributed by Greg Ward.)

@item 
The @code{thread} and @ref{10b,,threading} modules now have companion modules,
@code{dummy_thread} and @code{dummy_threading}, that provide a do-nothing
implementation of the @code{thread} module's interface for platforms where
threads are not supported.  The intention is to simplify thread-aware modules
(ones that @emph{don't} rely on threads to run) by putting the following code at the
top:

@example
try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading
@end example

In this example, @code{_threading} is used as the module name to make it clear
that the module being used is not necessarily the actual @ref{10b,,threading}
module. Code can call functions and use classes in @code{_threading} whether or
not threads are supported, avoiding an @ref{eb3,,if} statement and making the
code slightly clearer.  This module will not magically make multithreaded code
run without threads; code that waits for another thread to return or to do
something will simply hang forever.

@item 
The @ref{10c,,time} module's @code{strptime()} function has long been an annoyance
because it uses the platform C library's @code{strptime()} implementation, and
different platforms sometimes have odd bugs.  Brett Cannon contributed a
portable implementation that's written in pure Python and should behave
identically on all platforms.

@item 
The new @ref{10d,,timeit} module helps measure how long snippets of Python code
take to execute.  The @code{timeit.py} file can be run directly from the
command line, or the module's @code{Timer} class can be imported and used
directly.  Here's a short example that figures out whether it's faster to
convert an 8-bit string to Unicode by appending an empty Unicode string to it or
by using the @code{unicode()} function:

@example
import timeit

timer1 = timeit.Timer('unicode("abc")')
timer2 = timeit.Timer('"abc" + u""')

# Run three trials
print timer1.repeat(repeat=3, number=100000)
print timer2.repeat(repeat=3, number=100000)

# On my laptop this outputs:
# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
@end example

@item 
The @code{Tix} module has received various bug fixes and updates for the
current version of the Tix package.

@item 
The @code{Tkinter} module now works with a thread-enabled  version of Tcl.
Tcl's threading model requires that widgets only be accessed from the thread in
which they're created; accesses from another thread can cause Tcl to panic.  For
certain Tcl interfaces, @code{Tkinter} will now automatically avoid this  when a
widget is accessed from a different thread by marshalling a command, passing it
to the correct thread, and waiting for the results.  Other interfaces can't be
handled automatically but @code{Tkinter} will now raise an exception on such an
access so that you can at least find out about the problem.  See
@indicateurl{https://mail.python.org/pipermail/python-dev/2002-December/031107.html} for a more
detailed explanation of this change.  (Implemented by Martin von Löwis.)

@item 
Calling Tcl methods through @code{_tkinter} no longer  returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a @code{_tkinter.Tcl_Obj}
object if no Python equivalent exists. This behavior can be controlled through
the @code{wantobjects()} method of @code{tkapp} objects.

When using @code{_tkinter} through the @code{Tkinter} module (as most Tkinter
applications will), this feature is always activated. It should not cause
compatibility problems, since Tkinter would always convert string results to
Python types where possible.

If any incompatibilities are found, the old behavior can be restored by setting
the @code{wantobjects} variable in the @code{Tkinter} module to false before
creating the first @code{tkapp} object.

@example
import Tkinter
Tkinter.wantobjects = 0
@end example

Any breakage caused by this change should be reported as a bug.

@item 
The @code{UserDict} module has a new @code{DictMixin} class which defines
all dictionary methods for classes that already have a minimum mapping
interface.  This greatly simplifies writing classes that need to be
substitutable for dictionaries, such as the classes in  the @ref{e7,,shelve}
module.

Adding the mix-in as a superclass provides the full dictionary interface
whenever the class defines @ref{3ad,,__getitem__()}, @ref{d32,,__setitem__()},
@ref{d33,,__delitem__()}, and @code{keys()}. For example:

@example
>>> import UserDict
>>> class SeqDict(UserDict.DictMixin):
...     """Dictionary lookalike implemented with lists."""
...     def __init__(self):
...         self.keylist = []
...         self.valuelist = []
...     def __getitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         return self.valuelist[i]
...     def __setitem__(self, key, value):
...         try:
...             i = self.keylist.index(key)
...             self.valuelist[i] = value
...         except ValueError:
...             self.keylist.append(key)
...             self.valuelist.append(value)
...     def __delitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         self.keylist.pop(i)
...         self.valuelist.pop(i)
...     def keys(self):
...         return list(self.keylist)
...
>>> s = SeqDict()
>>> dir(s)      # See that other dictionary methods are implemented
['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
 '__init__', '__iter__', '__len__', '__module__', '__repr__',
 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
 'setdefault', 'update', 'valuelist', 'values']
@end example

（由 Raymond Hettinger 贡献。）

@item 
The DOM implementation in @ref{13e,,xml.dom.minidom} can now generate XML output
in a particular encoding by providing an optional encoding argument to the
@code{toxml()} and @code{toprettyxml()} methods of DOM nodes.

@item 
The @code{xmlrpclib} module now supports an XML-RPC extension for handling nil
data values such as Python's @code{None}.  Nil values are always supported on
unmarshalling an XML-RPC response.  To generate requests containing @code{None},
you must supply a true value for the @emph{allow_none} parameter when creating a
@code{Marshaller} instance.

@item 
The new @code{DocXMLRPCServer} module allows writing self-documenting XML-RPC
servers. Run it in demo mode (as a program) to see it in action.   Pointing the
Web browser to the RPC server produces pydoc-style documentation; pointing
xmlrpclib to the server allows invoking the actual methods. (Contributed by
Brian Quinlan.)

@item 
Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
has been added. The "idna" encoding can be used to convert between a Unicode
domain name and the ASCII-compatible encoding (ACE) of that name.

@example
>@{@}>@{@}> u"www.Alliancefrançaise.nu".encode("idna")
'www.xn--alliancefranaise-npb.nu'
@end example

The @ref{ef,,socket} module has also been extended to transparently convert
Unicode hostnames to the ACE version before passing them to the C library.
Modules that deal with hostnames such as @code{httplib} and @ref{82,,ftplib})
also support Unicode host names; @code{httplib} also sends HTTP @code{Host}
headers using the ACE version of the domain name.  @ref{126,,urllib} supports
Unicode URLs with non-ASCII host names as long as the @code{path} part of the URL
is ASCII only.

To implement this change, the @ref{f7,,stringprep} module, the  @code{mkstringprep}
tool and the @code{punycode} encoding have been added.
@end itemize

@c ======================================================================

@menu
* Date/Time 类型:: 
* optparse 模块:: 

@end menu

@node Date/Time 类型,optparse 模块,,新增，改进和弃用的模块<4>
@anchor{whatsnew/2 3 date-time-type}@anchor{edc}
@subsubsection Date/Time 类型


Date and time types suitable for expressing timestamps were added as the
@ref{30,,datetime} module.  The types don't support different calendars or many
fancy features, and just stick to the basics of representing time.

The three primary types are: @code{date}, representing a day, month, and year;
@ref{5f5,,time}, consisting of hour, minute, and second; and @ref{19f,,datetime},
which contains all the attributes of both @code{date} and @ref{5f5,,time}.
There's also a @code{timedelta} class representing differences between two
points in time, and time zone logic is implemented by classes inheriting from
the abstract @code{tzinfo} class.

You can create instances of @code{date} and @ref{5f5,,time} by either supplying
keyword arguments to the appropriate constructor, e.g.
@code{datetime.date(year=1972, month=10, day=15)}, or by using one of a number of
class methods.  For example, the @code{date.today()} class method returns the
current local date.

Once created, instances of the date/time classes are all immutable. There are a
number of methods for producing formatted strings from objects:

@example
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.isoformat()
'2002-12-30T21:27:03.994956'
>>> now.ctime()  # Only available on date, datetime
'Mon Dec 30 21:27:03 2002'
>>> now.strftime('%Y %d %b')
'2002 30 Dec'
@end example

The @code{replace()} method allows modifying one or more fields  of a
@code{date} or @ref{19f,,datetime} instance, returning a new instance:

@example
>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
>>> d.replace(year=2001, hour = 12)
datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
>>>
@end example

Instances can be compared, hashed, and converted to strings (the result is the
same as that of @code{isoformat()}).  @code{date} and @ref{19f,,datetime}
instances can be subtracted from each other, and added to @code{timedelta}
instances.  The largest missing feature is that there's no standard library
support for parsing strings and getting back a @code{date} or
@ref{19f,,datetime}.

For more information, refer to the module's reference documentation.
(Contributed by Tim Peters.)

@c ======================================================================

@node optparse 模块,,Date/Time 类型,新增，改进和弃用的模块<4>
@anchor{whatsnew/2 3 the-optparse-module}@anchor{edd}
@subsubsection optparse 模块


The @ref{85,,getopt} module provides simple parsing of command-line arguments.  The
new @ref{c3,,optparse} module (originally named Optik) provides more elaborate
command-line parsing that follows the Unix conventions, automatically creates
the output for @code{--help}, and can perform different actions for different
options.

You start by creating an instance of @code{OptionParser} and telling it what
your program's options are.

@example
import sys
from optparse import OptionParser

op = OptionParser()
op.add_option('-i', '--input',
              action='store', type='string', dest='input',
              help='set input filename')
op.add_option('-l', '--length',
              action='store', type='int', dest='length',
              help='set maximum length of output')
@end example

Parsing a command line is then done by calling the @code{parse_args()} method.

@example
options, args = op.parse_args(sys.argv[1:])
print options
print args
@end example

This returns an object containing all of the option values, and a list of
strings containing the remaining arguments.

Invoking the script with the various arguments now works as you'd expect it to.
Note that the length argument is automatically converted to an integer.

@example
$ ./python opt.py -i data arg1
<Values at 0x400cad4c: @{'input': 'data', 'length': None@}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: @{'input': 'data', 'length': 4@}>
[]
$
@end example

The help message is automatically generated for you:

@example
$ ./python opt.py --help
usage: opt.py [options]

options:
  -h, --help            show this help message and exit
  -iINPUT, --input=INPUT
                        set input filename
  -lLENGTH, --length=LENGTH
                        set maximum length of output
$
@end example

有关更多详细信息，请参见模块的文档。

Optik was written by Greg Ward, with suggestions from the readers of the Getopt
SIG.

@c ======================================================================

@node Pymalloc A Specialized Object Allocator,构建和 C API 的改变<12>,新增，改进和弃用的模块<4>,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 pymalloc-a-specialized-object-allocator}@anchor{ede}@anchor{whatsnew/2 3 section-pymalloc}@anchor{edf}
@subsection Pymalloc: A Specialized Object Allocator


Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
feature added to Python 2.1.  Pymalloc is intended to be faster than the system
@code{malloc()} and to have less memory overhead for allocation patterns typical
of Python programs. The allocator uses C's @code{malloc()} function to get large
pools of memory and then fulfills smaller memory requests from these pools.

In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by
default; you had to explicitly enable it when compiling Python by providing the
@code{--with-pymalloc} option to the @code{configure} script.  In 2.3,
pymalloc has had further enhancements and is now enabled by default; you'll have
to supply @code{--without-pymalloc} to disable it.

This change is transparent to code written in Python; however, pymalloc may
expose bugs in C extensions.  Authors of C extension modules should test their
code with pymalloc enabled, because some incorrect code may cause core dumps at
runtime.

There's one particularly common error that causes problems.  There are a number
of memory allocation functions in Python's C API that have previously just been
aliases for the C library's @code{malloc()} and @code{free()}, meaning that if
you accidentally called mismatched functions the error wouldn't be noticeable.
When the object allocator is enabled, these functions aren't aliases of
@code{malloc()} and @code{free()} any more, and calling the wrong function to
free memory may get you a core dump.  For example, if memory was allocated using
@ref{609,,PyObject_Malloc()}, it has to be freed using @ref{606,,PyObject_Free()}, not
@code{free()}.  A few modules included with Python fell afoul of this and had to
be fixed; doubtless there are more third-party modules that will have the same
problem.

As part of this change, the confusing multiple interfaces for allocating memory
have been consolidated down into two API families. Memory allocated with one
family must not be manipulated with functions from the other family.  There is
one family for allocating chunks of memory and another family of functions
specifically for allocating Python objects.


@itemize *

@item 
To allocate and free an undistinguished chunk of memory use the "raw memory"
family: @ref{607,,PyMem_Malloc()}, @ref{a59,,PyMem_Realloc()}, and @ref{e76,,PyMem_Free()}.

@item 
The "object memory" family is the interface to the pymalloc facility described
above and is biased towards a large number of "small" allocations:
@ref{609,,PyObject_Malloc()}, @ref{e77,,PyObject_Realloc()}, and @ref{606,,PyObject_Free()}.

@item 
To allocate and free Python objects, use the "object" family
@ref{269,,PyObject_New()}, @ref{26a,,PyObject_NewVar()}, and @ref{ee0,,PyObject_Del()}.
@end itemize

Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
features to catch memory overwrites and doubled frees in both extension modules
and in the interpreter itself.  To enable this support, compile a debugging
version of the Python interpreter by running @code{configure} with
@code{--with-pydebug}.

To aid extension writers, a header file @code{Misc/pymemcompat.h} is
distributed with the source to Python 2.3 that allows Python extensions to use
the 2.3 interfaces to memory allocation while compiling against any version of
Python since 1.5.2.  You would copy the file from Python's source distribution
and bundle it with the source of your extension.


@subsubheading 参见



@table @asis

@item @indicateurl{https://hg.python.org/cpython/file/default/Objects/obmalloc.c}

For the full details of the pymalloc implementation, see the comments at
the top of the file @code{Objects/obmalloc.c} in the Python source code.
The above link points to the file within the python.org SVN browser.
@end table


@c ======================================================================

@node 构建和 C API 的改变<12>,其他的改变和修正<2>,Pymalloc A Specialized Object Allocator,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 build-and-c-api-changes}@anchor{ee1}
@subsection 构建和 C API 的改变


针对 Python 构建过程和 C API 的改变包括:


@itemize *

@item 
The cycle detection implementation used by the garbage collection has proven
to be stable, so it's now been made mandatory.  You can no longer compile Python
without it, and the @code{--with-cycle-gc} switch to @code{configure} has
been removed.

@item 
Python can now optionally be built as a shared library
(@code{libpython2.3.so}) by supplying @code{--enable-shared} when running
Python's @code{configure} script.  (Contributed by Ondrej Palkovsky.)

@item 
The @code{DL_EXPORT} and @code{DL_IMPORT} macros are now deprecated.
Initialization functions for Python extension modules should now be declared
using the new macro @code{PyMODINIT_FUNC}, while the Python core will
generally use the @code{PyAPI_FUNC} and @code{PyAPI_DATA} macros.

@item 
The interpreter can be compiled without any docstrings for the built-in
functions and modules by supplying @code{--without-doc-strings} to the
@code{configure} script. This makes the Python executable about 10% smaller,
but will also mean that you can't get help for Python's built-ins.  (Contributed
by Gustavo Niemeyer.)

@item 
The @code{PyArg_NoArgs()} macro is now deprecated, and code that uses it
should be changed.  For Python 2.2 and later, the method definition table can
specify the @ref{ee2,,METH_NOARGS} flag, signalling that there are no arguments,
and the argument checking can then be removed.  If compatibility with pre-2.2
versions of Python is important, the code could use @code{PyArg_ParseTuple(args,
"")} instead, but this will be slower than using @ref{ee2,,METH_NOARGS}.

@item 
@ref{39b,,PyArg_ParseTuple()} accepts new format characters for various sizes of
unsigned integers: @code{B} for @code{unsigned char}, @code{H} for @code{unsigned
short int},  @code{I} for @code{unsigned int},  and @code{K} for @code{unsigned
long long}.

@item 
A new function, @code{PyObject_DelItemString(mapping, char *key)} was added
as shorthand for @code{PyObject_DelItem(mapping, PyString_New(key))}.

@item 
File objects now manage their internal string buffer differently, increasing
it exponentially when needed.  This results in the benchmark tests in
@code{Lib/test/test_bufio.py} speeding up considerably (from 57 seconds to 1.7
seconds, according to one measurement).

@item 
It's now possible to define class and static methods for a C extension type by
setting either the @ref{ee3,,METH_CLASS} or @ref{ee4,,METH_STATIC} flags in a
method's @ref{ee5,,PyMethodDef} structure.

@item 
Python now includes a copy of the Expat XML parser's source code, removing any
dependence on a system version or local installation of Expat.

@item 
If you dynamically allocate type objects in your extension, you should be
aware of a change in the rules relating to the @code{__module__} and
@ref{d37,,__name__} attributes.  In summary, you will want to ensure the type's
dictionary contains a @code{'__module__'} key; making the module name the part of
the type name leading up to the final period will no longer have the desired
effect.  For more detail, read the API reference documentation or the  source.
@end itemize

@c ======================================================================

@menu
* Port-Specific Changes: Port-Specific Changes<3>. 

@end menu

@node Port-Specific Changes<3>,,,构建和 C API 的改变<12>
@anchor{whatsnew/2 3 port-specific-changes}@anchor{ee6}
@subsubsection Port-Specific Changes


Support for a port to IBM's OS/2 using the EMX runtime environment was merged
into the main Python source tree.  EMX is a POSIX emulation layer over the OS/2
system APIs.  The Python port for EMX tries to support all the POSIX-like
capability exposed by the EMX runtime, and mostly succeeds; @code{fork()} and
@ref{7c,,fcntl()} are restricted by the limitations of the underlying emulation
layer.  The standard OS/2 port, which uses IBM's Visual Age compiler, also
gained support for case-sensitive import semantics as part of the integration of
the EMX port into CVS.  (Contributed by Andrew MacIntyre.)

On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility.  This means that modules will no longer fail to load if a single
routine is missing on the current OS version. Instead calling the missing
routine will raise an exception. (Contributed by Jack Jansen.)

The RPM spec files, found in the @code{Misc/RPM/} directory in the Python
source distribution, were updated for 2.3.  (Contributed by Sean Reifschneider.)

Other new platforms now supported by Python include AtheOS
(@indicateurl{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.

@c ======================================================================

@node 其他的改变和修正<2>,移植到 Python 2 3,构建和 C API 的改变<12>,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 other-changes-and-fixes}@anchor{ee7}@anchor{whatsnew/2 3 section-other}@anchor{ed7}
@subsection 其他的改变和修正


As usual, there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3.  Both
figures are likely to be underestimates.

一些较为重要的改变:


@itemize *

@item 
If the 
@geindex PYTHONINSPECT
@geindex 环境变量; PYTHONINSPECT
@ref{ee8,,PYTHONINSPECT} environment variable is set, the Python
interpreter will enter the interactive prompt after running a Python program, as
if Python had been invoked with the @ref{ee9,,-i} option. The environment
variable can be set before running the Python interpreter, or it can be set by
the Python program as part of its execution.

@item 
The @code{regrtest.py} script now provides a way to allow "all resources
except @emph{foo}."  A resource name passed to the @code{-u} option can now be
prefixed with a hyphen (@code{'-'}) to mean "remove this resource."  For example,
the option '@code{-uall,-bsddb}' could be used to enable the use of all resources
except @code{bsddb}.

@item 
The tools used to build the documentation now work under Cygwin as well as
Unix.

@item 
The @code{SET_LINENO} opcode has been removed.  Back in the mists of time, this
opcode was needed to produce line numbers in tracebacks and support trace
functions (for, e.g., @ref{c9,,pdb}). Since Python 1.5, the line numbers in
tracebacks have been computed using a different mechanism that works with
"python -O".  For Python 2.3 Michael Hudson implemented a similar scheme to
determine when to call the trace function, removing the need for @code{SET_LINENO}
entirely.

It would be difficult to detect any resulting difference from Python code, apart
from a slight speed up when Python is run without @ref{788,,-O}.

C extensions that access the @code{f_lineno} field of frame objects should
instead call @code{PyCode_Addr2Line(f->f_code, f->f_lasti)}. This will have the
added effect of making the code work as desired under "python -O" in earlier
versions of Python.

A nifty new feature is that trace functions can now assign to the
@code{f_lineno} attribute of frame objects, changing the line that will be
executed next.  A @code{jump} command has been added to the @ref{c9,,pdb} debugger
taking advantage of this new feature. (Implemented by Richie Hindle.)
@end itemize

@c ======================================================================

@node 移植到 Python 2 3,致谢<5>,其他的改变和修正<2>,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 porting-to-python-2-3}@anchor{eea}
@subsection 移植到 Python 2.3


This section lists previously described changes that may require changes to your
code:


@itemize *

@item 
@ref{2ce,,yield} is now always a keyword; if it's used as a variable name in
your code, a different name must be chosen.

@item 
For strings @emph{X} and @emph{Y}, @code{X in Y} now works if @emph{X} is more than one
character long.

@item 
The @ref{205,,int()} type constructor will now return a long integer instead of
raising an @ref{a4a,,OverflowError} when a string or floating-point number is too
large to fit into an integer.

@item 
If you have Unicode strings that contain 8-bit characters, you must declare
the file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
of the file.  See section @ref{eb5,,PEP 263; 源代码的字符编码格式} for more information.

@item 
Calling Tcl methods through @code{_tkinter} no longer  returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a @code{_tkinter.Tcl_Obj}
object if no Python equivalent exists.

@item 
Large octal and hex literals such as @code{0xffffffff} now trigger a
@ref{43e,,FutureWarning}. Currently they're stored as 32-bit numbers and result in a
negative value, but in Python 2.4 they'll become positive long integers.

There are a few ways to fix this warning.  If you really need a positive number,
just add an @code{L} to the end of the literal.  If you're trying to get a 32-bit
integer with low bits set and have previously used an expression such as @code{~(1
<< 31)}, it's probably clearest to start with all bits set and clear the
desired upper bits. For example, to clear just the top bit (bit 31), you could
write @code{0xffffffffL &~(1L<<31)}.

@item 
You can no longer disable assertions by assigning to @code{__debug__}.

@item 
The Distutils @code{setup()} function has gained various new keyword arguments
such as @emph{depends}.  Old versions of the Distutils will abort if passed unknown
keywords.  A solution is to check for the presence of the new
@code{get_distutil_options()} function in your @code{setup.py} and only uses the
new keywords with a version of the Distutils that supports them:

@example
from distutils import core

kw = @{'sources': 'foo.c', ...@}
if hasattr(core, 'get_distutil_options'):
    kw['depends'] = ['foo.h']
ext = Extension(**kw)
@end example

@item 
Using @code{None} as a variable name will now result in a @ref{2d0,,SyntaxWarning}
warning.

@item 
Names of extension types defined by the modules included with Python now
contain the module and a @code{'.'} in front of the type name.
@end itemize

@c ======================================================================

@node 致谢<5>,,移植到 Python 2 3,Python 2 3 有什么新变化
@anchor{whatsnew/2 3 acknowledgements}@anchor{eeb}@anchor{whatsnew/2 3 acks}@anchor{eec}
@subsection 致谢


作者感谢以下人员为本文的各种草案提供建议，更正和帮助： Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred L. Drake, Jr., David Fraser,  Kelly Gerber, Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler, Just van Rossum.

@node Python 2 2 有什么新变化,Python 2 1 有什么新变化,Python 2 3 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 2 doc}@anchor{eed}@anchor{whatsnew/2 2 what-s-new-in-python-2-2}@anchor{eee}
@section Python 2.2 有什么新变化


@*作者: 
A.M. Kuchling


@c $Id: whatsnew22.tex 37315 2004-09-10 19:33:00Z akuchling $

@menu
* 概述:: 
* PEP 252 和 253：类型和类的修改:: 
* PEP 234; 迭代器: PEP 234 迭代器. 
* PEP 255; 简单的生成器: PEP 255 简单的生成器<2>. 
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>. 
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator. 
* Unicode Changes:: 
* PEP 227; 嵌套的作用域: PEP 227 嵌套的作用域. 
* 新增和改进的模块: 新增和改进的模块<3>. 
* 解释器的改变和修正:: 
* 其他的改变和修正: 其他的改变和修正<3>. 
* 致谢: 致谢<6>. 

@end menu

@node 概述,PEP 252 和 253：类型和类的修改,,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 introduction}@anchor{eef}
@subsection 概述


本文本介绍了 Python 2.2.2 的新增特性，该版本发布于 2002 年 10 月 14日。 Python 2.2.2 是 Python 2.2 的问题修正发布版，最初发布于 2001 年 12 月 21 日。

Python 2.2 can be thought of as the "cleanup release".  There are some features
such as generators and iterators that are completely new, but most of the
changes, significant and far-reaching though they may be, are aimed at cleaning
up irregularities and dark corners of the language design.

This article doesn't attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.2, such as the Python Library Reference@footnote{https://docs.python.org/2.2/lib/lib.html} and the Python Reference Manual@footnote{https://docs.python.org/2.2/ref/ref.html}.  If you want to
understand the complete implementation and design rationale for a change, refer
to the PEP for a particular new feature.

@c see also, now defunct
@c 
@c http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm
@c    "What's So Special About Python 2.2?" is also about the new 2.2 features, and
@c    was written by Cameron Laird and Kathryn Soraiz.

@c ======================================================================

@node PEP 252 和 253：类型和类的修改,PEP 234 迭代器,概述,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 peps-252-and-253-type-and-class-changes}@anchor{ef0}
@subsection PEP 252 和 253：类型和类的修改


The largest and most far-reaching changes in Python 2.2 are to Python's model of
objects and classes.  The changes should be backward compatible, so it's likely
that your code will continue to run unchanged, but the changes provide some
amazing new capabilities. Before beginning this, the longest and most
complicated section of this article, I'll provide an overview of the changes and
offer some comments.

A long time ago I wrote a Web page listing flaws in Python's design.  One of the
most significant flaws was that it's impossible to subclass Python types
implemented in C.  In particular, it's not possible to subclass built-in types,
so you can't just subclass, say, lists in order to add a single useful method to
them. The @code{UserList} module provides a class that supports all of the
methods of lists and that can be subclassed further, but there's lots of C code
that expects a regular Python list and won't accept a @code{UserList}
instance.

Python 2.2 修正了此问题，并在此过程中添加了一些令人激动的新功能。 简明概述如下:


@itemize *

@item 
You can subclass built-in types such as lists and even integers, and your
subclasses should work in every place that requires the original type.

@item 
It's now possible to define static and class methods, in addition to the
instance methods available in previous versions of Python.

@item 
It's also possible to automatically call methods on accessing or setting an
instance attribute by using a new mechanism called @emph{properties}.  Many uses
of @ref{433,,__getattr__()} can be rewritten to use properties instead, making the
resulting code simpler and faster.  As a small side benefit, attributes can now
have docstrings, too.

@item 
The list of legal attributes for an instance can be limited to a particular
set using @emph{slots}, making it possible to safeguard against typos and
perhaps make more optimizations possible in future versions of Python.
@end itemize

Some users have voiced concern about all these changes.  Sure, they say, the new
features are neat and lend themselves to all sorts of tricks that weren't
possible in previous versions of Python, but they also make the language more
complicated.  Some people have said that they've always recommended Python for
its simplicity, and feel that its simplicity is being lost.

Personally, I think there's no need to worry.  Many of the new features are
quite esoteric, and you can write a lot of Python code without ever needed to be
aware of them.  Writing a simple class is no more difficult than it ever was, so
you don't need to bother learning or teaching them unless they're actually
needed.  Some very complicated tasks that were previously only possible from C
will now be possible in pure Python, and to my mind that's all for the better.

I'm not going to attempt to cover every single corner case and small change that
were required to make the new features work.  Instead this section will paint
only the broad strokes.  See section @ref{ef1,,相关链接}, "Related Links", for
further sources of information about Python 2.2's new object model.

@menu
* 旧式类和新式类:: 
* 描述器:: 
* 多重继承：钻石规则:: 
* 属性访问:: 
* 相关链接:: 

@end menu

@node 旧式类和新式类,描述器,,PEP 252 和 253：类型和类的修改
@anchor{whatsnew/2 2 old-and-new-classes}@anchor{ef2}
@subsubsection 旧式类和新式类


First, you should know that Python 2.2 really has two kinds of classes: classic
or old-style classes, and new-style classes.  The old-style class model is
exactly the same as the class model in earlier versions of Python.  All the new
features described in this section apply only to new-style classes. This
divergence isn't intended to last forever; eventually old-style classes will be
dropped, possibly in Python 3.0.

So how do you define a new-style class?  You do it by subclassing an existing
new-style class.  Most of Python's built-in types, such as integers, lists,
dictionaries, and even files, are new-style classes now.  A new-style class
named @ref{3da,,object}, the base class for all built-in types, has also been
added so if no built-in type is suitable, you can just subclass
@ref{3da,,object}:

@example
class C(object):
    def __init__ (self):
        ...
    ...
@end example

This means that @ref{d3a,,class} statements that don't have any base classes are
always classic classes in Python 2.2.  (Actually you can also change this by
setting a module-level variable named @code{__metaclass__} --- see 
@geindex Python 提高建议; PEP 253
PEP 253@footnote{https://www.python.org/dev/peps/pep-0253}
for the details --- but it's easier to just subclass @ref{3da,,object}.)

The type objects for the built-in types are available as built-ins, named using
a clever trick.  Python has always had built-in functions named @ref{205,,int()},
@ref{1fe,,float()}, and @ref{206,,str()}.  In 2.2, they aren't functions any more, but
type objects that behave as factories when called.

@example
>>> int
<type 'int'>
>>> int('123')
123
@end example

To make the set of types complete, new type objects such as @ref{164,,dict()} and
@code{file()} have been added.  Here's a more interesting example, adding a
@code{lock()} method to file objects:

@example
class LockableFile(file):
    def lock (self, operation, length=0, start=0, whence=0):
        import fcntl
        return fcntl.lockf(self.fileno(), operation,
                           length, start, whence)
@end example

The now-obsolete @code{posixfile} module contained a class that emulated all of
a file object's methods and also added a @code{lock()} method, but this class
couldn't be passed to internal functions that expected a built-in file,
something which is possible with our new @code{LockableFile}.

@node 描述器,多重继承：钻石规则,旧式类和新式类,PEP 252 和 253：类型和类的修改
@anchor{whatsnew/2 2 descriptors}@anchor{ef3}
@subsubsection 描述器


In previous versions of Python, there was no consistent way to discover what
attributes and methods were supported by an object. There were some informal
conventions, such as defining @code{__members__} and @code{__methods__}
attributes that were lists of names, but often the author of an extension type
or a class wouldn't bother to define them.  You could fall back on inspecting
the @ref{5fe,,__dict__} of an object, but when class inheritance or an arbitrary
@ref{433,,__getattr__()} hook were in use this could still be inaccurate.

The one big idea underlying the new class model is that an API for describing
the attributes of an object using @emph{descriptors} has been formalized.
Descriptors specify the value of an attribute, stating whether it's a method or
a field.  With the descriptor API, static methods and class methods become
possible, as well as more exotic constructs.

Attribute descriptors are objects that live inside class objects, and have a few
attributes of their own:


@itemize *

@item 
@ref{d37,,__name__} 是属性的名称。

@item 
@code{__doc__} 是属性的文档字符串。

@item 
@code{__get__(object)} 是一个从 @emph{object} 中提取属性值的方法。

@item 
@code{__set__(object, value)} 将 @emph{object} 上的属性设为 @emph{value}。

@item 
@code{__delete__(object, value)} 将删除 @emph{object} 的 @emph{value} 属性。
@end itemize

例如，当你写下 @code{obj.x}，Python 实际要执行的步骤是:

@example
descriptor = obj.__class__.x
descriptor.__get__(obj)
@end example

For methods, @code{descriptor.__get__()} returns a temporary object that's
callable, and wraps up the instance and the method to be called on it. This is
also why static methods and class methods are now possible; they have
descriptors that wrap up just the method, or the method and the class.  As a
brief explanation of these new kinds of methods, static methods aren't passed
the instance, and therefore resemble regular functions.  Class methods are
passed the class of the object, but not the object itself.  Static and class
methods are defined like this:

@example
class C(object):
    def f(arg1, arg2):
        ...
    f = staticmethod(f)

    def g(cls, arg1, arg2):
        ...
    g = classmethod(g)
@end example

The @ref{311,,staticmethod()} function takes the function @code{f()}, and returns it
wrapped up in a descriptor so it can be stored in the class object.  You might
expect there to be special syntax for creating such methods (@code{def static f},
@code{defstatic f()}, or something like that) but no such syntax has been defined
yet; that's been left for future versions of Python.

More new features, such as slots and properties, are also implemented as new
kinds of descriptors, and it's not difficult to write a descriptor class that
does something novel.  For example, it would be possible to write a descriptor
class that made it possible to write Eiffel-style preconditions and
postconditions for a method.  A class that used this feature might be defined
like this:

@example
from eiffel import eiffelmethod

class C(object):
    def f(self, arg1, arg2):
        # The actual function
        ...
    def pre_f(self):
        # Check preconditions
        ...
    def post_f(self):
        # Check postconditions
        ...

    f = eiffelmethod(f, pre_f, post_f)
@end example

Note that a person using the new @code{eiffelmethod()} doesn't have to understand
anything about descriptors.  This is why I think the new features don't increase
the basic complexity of the language. There will be a few wizards who need to
know about it in order to write @code{eiffelmethod()} or the ZODB or whatever,
but most users will just write code on top of the resulting libraries and ignore
the implementation details.

@node 多重继承：钻石规则,属性访问,描述器,PEP 252 和 253：类型和类的修改
@anchor{whatsnew/2 2 multiple-inheritance-the-diamond-rule}@anchor{ef4}
@subsubsection 多重继承：钻石规则


Multiple inheritance has also been made more useful through changing the rules
under which names are resolved.  Consider this set of classes (diagram taken
from 
@geindex Python 提高建议; PEP 253
PEP 253@footnote{https://www.python.org/dev/peps/pep-0253} by Guido van Rossum):

@example
      class A:
        ^ ^  def save(self): ...
       /   \
      /     \
     /       \
    /         \
class B     class C:
    ^         ^  def save(self): ...
     \       /
      \     /
       \   /
        \ /
      class D
@end example

The lookup rule for classic classes is simple but not very smart; the base
classes are searched depth-first, going from left to right.  A reference to
@code{D.save()} will search the classes @code{D}, @code{B}, and then
@code{A}, where @code{save()} would be found and returned.  @code{C.save()}
would never be found at all.  This is bad, because if @code{C}'s @code{save()}
method is saving some internal state specific to @code{C}, not calling it will
result in that state never getting saved.

New-style classes follow a different algorithm that's a bit more complicated to
explain, but does the right thing in this situation. (Note that Python 2.3
changes this algorithm to one that produces the same results in most cases, but
produces more useful results for really complicated inheritance graphs.)


@enumerate 

@item 
List all the base classes, following the classic lookup rule and include a
class multiple times if it's visited repeatedly.  In the above example, the list
of visited classes is [@code{D}, @code{B}, @code{A}, @code{C},
@code{A}].

@item 
Scan the list for duplicated classes.  If any are found, remove all but one
occurrence, leaving the @emph{last} one in the list.  In the above example, the list
becomes [@code{D}, @code{B}, @code{C}, @code{A}] after dropping
duplicates.
@end enumerate

Following this rule, referring to @code{D.save()} will return @code{C.save()},
which is the behaviour we're after.  This lookup rule is the same as the one
followed by Common Lisp.  A new built-in function, @ref{5e6,,super()}, provides a way
to get at a class's superclasses without having to reimplement Python's
algorithm. The most commonly used form will be  @code{super(class, obj)}, which
returns  a bound superclass object (not the actual class object).  This form
will be used in methods to call a method in the superclass; for example,
@code{D}'s @code{save()} method would look like this:

@example
class D (B,C):
    def save (self):
        # Call superclass .save()
        super(D, self).save()
        # Save D's private information here
        ...
@end example

@ref{5e6,,super()} can also return unbound superclass objects when called as
@code{super(class)} or @code{super(class1, class2)}, but this probably won't
often be useful.

@node 属性访问,相关链接,多重继承：钻石规则,PEP 252 和 253：类型和类的修改
@anchor{whatsnew/2 2 attribute-access}@anchor{ef5}
@subsubsection 属性访问


A fair number of sophisticated Python classes define hooks for attribute access
using @ref{433,,__getattr__()}; most commonly this is done for convenience, to make
code more readable by automatically mapping an attribute access such as
@code{obj.parent} into a method call such as @code{obj.get_parent}.  Python 2.2 adds
some new ways of controlling attribute access.

First, @code{__getattr__(attr_name)} is still supported by new-style classes,
and nothing about it has changed.  As before, it will be called when an attempt
is made to access @code{obj.foo} and no attribute named @code{foo} is found in the
instance's dictionary.

New-style classes also support a new method,
@code{__getattribute__(attr_name)}.  The difference between the two methods is
that @ref{552,,__getattribute__()} is @emph{always} called whenever any attribute is
accessed, while the old @ref{433,,__getattr__()} is only called if @code{foo} isn't
found in the instance's dictionary.

However, Python 2.2's support for @emph{properties} will often be a simpler way
to trap attribute references.  Writing a @ref{433,,__getattr__()} method is
complicated because to avoid recursion you can't use regular attribute accesses
inside them, and instead have to mess around with the contents of
@ref{5fe,,__dict__}. @ref{433,,__getattr__()} methods also end up being called by Python
when it checks for other methods such as @ref{453,,__repr__()} or @code{__coerce__()},
and so have to be written with this in mind. Finally, calling a function on
every attribute access results in a sizable performance loss.

@ref{30f,,property} is a new built-in type that packages up three functions that
get, set, or delete an attribute, and a docstring.  For example, if you want to
define a @code{size} attribute that's computed, but also settable, you could
write:

@example
class C(object):
    def get_size (self):
        result = ... computation ...
        return result
    def set_size (self, size):
        ... compute something based on the size
        and set internal state appropriately ...

    # Define a property.  The 'delete this attribute'
    # method is defined as None, so the attribute
    # can't be deleted.
    size = property(get_size, set_size,
                    None,
                    "Storage size of this instance")
@end example

That is certainly clearer and easier to write than a pair of
@ref{433,,__getattr__()}/@ref{ef6,,__setattr__()} methods that check for the @code{size}
attribute and handle it specially while retrieving all other attributes from the
instance's @ref{5fe,,__dict__}.  Accesses to @code{size} are also the only ones
which have to perform the work of calling a function, so references to other
attributes run at their usual speed.

Finally, it's possible to constrain the list of attributes that can be
referenced on an object using the new @ref{ef7,,__slots__} class attribute. Python
objects are usually very dynamic; at any time it's possible to define a new
attribute on an instance by just doing @code{obj.new_attr=1}.   A new-style class
can define a class attribute named @ref{ef7,,__slots__} to limit the legal
attributes  to a particular set of names.  An example will make this clear:

@example
>>> class C(object):
...     __slots__ = ('template', 'name')
...
>>> obj = C()
>>> print obj.template
None
>>> obj.template = 'Test'
>>> print obj.template
Test
>>> obj.newattr = None
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'newattr'
@end example

Note how you get an @ref{4aa,,AttributeError} on the attempt to assign to an
attribute not listed in @ref{ef7,,__slots__}.

@node 相关链接,,属性访问,PEP 252 和 253：类型和类的修改
@anchor{whatsnew/2 2 related-links}@anchor{ef8}@anchor{whatsnew/2 2 sect-rellinks}@anchor{ef1}
@subsubsection 相关链接


This section has just been a quick overview of the new features, giving enough
of an explanation to start you programming, but many details have been
simplified or ignored.  Where should you go to get a more complete picture?

@indicateurl{https://docs.python.org/dev/howto/descriptor.html} is a lengthy tutorial introduction to
the descriptor features, written by Guido van Rossum. If my description has
whetted your appetite, go read this tutorial next, because it goes into much
more detail about the new features while still remaining quite easy to read.

Next, there are two relevant PEPs, 
@geindex Python 提高建议; PEP 252
PEP 252@footnote{https://www.python.org/dev/peps/pep-0252} and 
@geindex Python 提高建议; PEP 253
PEP 253@footnote{https://www.python.org/dev/peps/pep-0253}.  
@geindex Python 提高建议; PEP 252
PEP 252@footnote{https://www.python.org/dev/peps/pep-0252} is
titled "Making Types Look More Like Classes", and covers the descriptor API.
@geindex Python 提高建议; PEP 253
PEP 253@footnote{https://www.python.org/dev/peps/pep-0253} is titled "Subtyping Built-in Types", and describes the changes to
type objects that make it possible to subtype built-in objects.  
@geindex Python 提高建议; PEP 253
PEP 253@footnote{https://www.python.org/dev/peps/pep-0253} is
the more complicated PEP of the two, and at a few points the necessary
explanations of types and meta-types may cause your head to explode.  Both PEPs
were written and implemented by Guido van Rossum, with substantial assistance
from the rest of the Zope Corp. team.

Finally, there's the ultimate authority: the source code.  Most of the machinery
for the type handling is in @code{Objects/typeobject.c}, but you should only
resort to it after all other avenues have been exhausted, including posting a
question to python-list or python-dev.

@c ======================================================================

@node PEP 234 迭代器,PEP 255 简单的生成器<2>,PEP 252 和 253：类型和类的修改,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 pep-234-iterators}@anchor{ef9}
@subsection PEP 234: 迭代器


Another significant addition to 2.2 is an iteration interface at both the C and
Python levels.  Objects can define how they can be looped over by callers.

In Python versions up to 2.1, the usual way to make @code{for item in obj} work is
to define a @ref{3ad,,__getitem__()} method that looks something like this:

@example
def __getitem__(self, index):
    return <next item>
@end example

@ref{3ad,,__getitem__()} is more properly used to define an indexing operation on an
object so that you can write @code{obj[5]} to retrieve the sixth element.  It's a
bit misleading when you're using this only to support @ref{d02,,for} loops.
Consider some file-like object that wants to be looped over; the @emph{index}
parameter is essentially meaningless, as the class probably assumes that a
series of @ref{3ad,,__getitem__()} calls will be made with @emph{index} incrementing by
one each time.  In other words, the presence of the @ref{3ad,,__getitem__()} method
doesn't mean that using @code{file[5]}  to randomly access the sixth element will
work, though it really should.

In Python 2.2, iteration can be implemented separately, and @ref{3ad,,__getitem__()}
methods can be limited to classes that really do support random access.  The
basic idea of iterators is  simple.  A new built-in function, @code{iter(obj)}
or @code{iter(C, sentinel)}, is used to get an iterator. @code{iter(obj)} returns
an iterator for the object @emph{obj}, while @code{iter(C, sentinel)} returns an
iterator that will invoke the callable object @emph{C} until it returns @emph{sentinel} to
signal that the iterator is done.

Python classes can define an @ref{611,,__iter__()} method, which should create and
return a new iterator for the object; if the object is its own iterator, this
method can just return @code{self}.  In particular, iterators will usually be their
own iterators.  Extension types implemented in C can implement a @ref{efa,,tp_iter}
function in order to return an iterator, and extension types that want to behave
as iterators can define a @ref{efb,,tp_iternext} function.

So, after all this, what do iterators actually do?  They have one required
method, @ref{77f,,next()}, which takes no arguments and returns the next value.  When
there are no more values to be returned, calling @ref{77f,,next()} should raise the
@ref{58a,,StopIteration} exception.

@example
>>> L = [1,2,3]
>>> i = iter(L)
>>> print i
<iterator object at 0x8116870>
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>
@end example

In 2.2, Python's @ref{d02,,for} statement no longer expects a sequence; it
expects something for which @ref{df5,,iter()} will return an iterator. For backward
compatibility and convenience, an iterator is automatically constructed for
sequences that don't implement @ref{611,,__iter__()} or a @ref{efa,,tp_iter} slot, so
@code{for i in [1,2,3]} will still work.  Wherever the Python interpreter loops
over a sequence, it's been changed to use the iterator protocol.  This means you
can do things like this:

@example
>>> L = [1,2,3]
>>> i = iter(L)
>>> a,b,c = i
>>> a,b,c
(1, 2, 3)
@end example

Iterator support has been added to some of Python's basic types.   Calling
@ref{df5,,iter()} on a dictionary will return an iterator which loops over its keys:

@example
>>> m = @{'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12@}
>>> for key in m: print key, m[key]
...
Mar 3
Feb 2
Aug 8
Sep 9
May 5
Jun 6
Jul 7
Jan 1
Apr 4
Nov 11
Dec 12
Oct 10
@end example

That's just the default behaviour.  If you want to iterate over keys, values, or
key/value pairs, you can explicitly call the @code{iterkeys()},
@code{itervalues()}, or @code{iteritems()} methods to get an appropriate iterator.
In a minor related change, the @ref{179,,in} operator now works on dictionaries,
so @code{key in dict} is now equivalent to @code{dict.has_key(key)}.

Files also provide an iterator, which calls the @ref{de,,readline()} method until
there are no more lines in the file.  This means you can now read each line of a
file using code like this:

@example
for line in file:
    # do something for each line
    ...
@end example

Note that you can only go forward in an iterator; there's no way to get the
previous element, reset the iterator, or make a copy of it. An iterator object
could provide such additional capabilities, but the iterator protocol only
requires a @ref{77f,,next()} method.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 234

@item PEP 234@footnote{https://www.python.org/dev/peps/pep-0234} - Iterators

由 Ka-Ping Yee 和 GvR 撰写；由 Python Labs 小组（主要由 GvR 和 Tim Peters）实现。
@end table


@c ======================================================================

@node PEP 255 简单的生成器<2>,PEP 237 统一长整数和整数<2>,PEP 234 迭代器,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 pep-255-simple-generators}@anchor{efc}
@subsection PEP 255: 简单的生成器


Generators are another new feature, one that interacts with the introduction of
iterators.

You're doubtless familiar with how function calls work in Python or C.  When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a @ref{2cf,,return} statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren't thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.

这里是一个生成器函数的最简示例:

@example
def generate_ints(N):
    for i in range(N):
        yield i
@end example

A new keyword, @ref{2ce,,yield}, was introduced for generators.  Any function
containing a @code{yield} statement is a generator function; this is
detected by Python's bytecode compiler which compiles the function specially as
a result.  Because a new keyword was introduced, generators must be explicitly
enabled in a module by including a @code{from __future__ import generators}
statement near the top of the module's source code.  In Python 2.3 this
statement will become unnecessary.

When you call a generator function, it doesn't return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the @ref{2ce,,yield} statement, the generator outputs the value of @code{i},
similar to a @ref{2cf,,return} statement.  The big difference between
@code{yield} and a @code{return} statement is that on reaching a
@code{yield} the generator's state of execution is suspended and local
variables are preserved.  On the next call to the generator's @code{next()} method,
the function will resume executing immediately after the @code{yield}
statement.  (For complicated reasons, the @code{yield} statement isn't
allowed inside the @code{try} block of a
@ref{e3f,,try}...@ref{2c3,,finally} statement; read 
@geindex Python 提高建议; PEP 255
PEP 255@footnote{https://www.python.org/dev/peps/pep-0255} for a full
explanation of the interaction between @code{yield} and exceptions.)

这里是 @code{generate_ints()} 生成器的用法示例:

@example
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in generate_ints
StopIteration
@end example

你可以等价地写成 @code{for i in generate_ints(5)} 或 @code{a,b,c = generate_ints(3)}。

Inside a generator function, the @ref{2cf,,return} statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. @code{return} with a value, such
as @code{return 5}, is a syntax error inside a generator function.  The end of the
generator's results can also be indicated by raising @ref{58a,,StopIteration}
manually, or by just letting the flow of execution fall off the bottom of the
function.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting @code{self.count} to
0, and having the @ref{77f,,next()} method increment @code{self.count} and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. @code{Lib/test/test_generators.py} contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively.

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x
@end example

Two other examples in @code{Lib/test/test_generators.py} produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight's Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon
(@indicateurl{https://www.cs.arizona.edu/icon/}), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from "An Overview of the Icon Programming Language" at
@indicateurl{https://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of what this looks
like:

@example
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
@end example

In Icon the @code{find()} function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the @ref{eb3,,if} statement, @code{i} is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.

Python doesn't go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered a new part of the core Python language, but
learning or using them isn't compulsory; if they don't solve any problems that
you have, feel free to ignore them. One novel feature of Python's interface as
compared to Icon's is that a generator's state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 255

@item PEP 255@footnote{https://www.python.org/dev/peps/pep-0255} - 简单生成器

Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
@end table


@c ======================================================================

@node PEP 237 统一长整数和整数<2>,PEP 238 Changing the Division Operator,PEP 255 简单的生成器<2>,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 pep-237-unifying-long-integers-and-integers}@anchor{efd}
@subsection PEP 237: 统一长整数和整数


In recent versions, the distinction between regular integers, which are 32-bit
values on most machines, and long integers, which can be of arbitrary size, was
becoming an annoyance.  For example, on platforms that support files larger than
@code{2**32} bytes, the @code{tell()} method of file objects has to return a long
integer. However, there were various bits of Python that expected plain integers
and would raise an error if a long integer was provided instead.  For example,
in Python 1.5, only regular integers could be used as a slice index, and
@code{'abc'[1L:]} would raise a @ref{1ff,,TypeError} exception with the message 'slice
index must be int'.

Python 2.2 will shift values from short to long integers as required. The 'L'
suffix is no longer needed to indicate a long integer literal, as now the
compiler will choose the appropriate type.  (Using the 'L' suffix will be
discouraged in future 2.x versions of Python, triggering a warning in Python
2.4, and probably dropped in Python 3.0.)  Many operations that used to raise an
@ref{a4a,,OverflowError} will now return a long integer as their result.  For
example:

@example
>>> 1234567890123
1234567890123L
>>> 2 ** 64
18446744073709551616L
@end example

In most cases, integers and long integers will now be treated identically.  You
can still distinguish them with the @ref{709,,type()} built-in function, but that's
rarely needed.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 237

@item PEP 237@footnote{https://www.python.org/dev/peps/pep-0237} - 统一长整数和整数

由 Moshe Zadka 和 Guido van Rossum 撰写 ; 大部分由 Guido van Rossum 实现。
@end table


@c ======================================================================

@node PEP 238 Changing the Division Operator,Unicode Changes,PEP 237 统一长整数和整数<2>,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 pep-238-changing-the-division-operator}@anchor{efe}
@subsection PEP 238: Changing the Division Operator


The most controversial change in Python 2.2 heralds the start of an effort to
fix an old design flaw that's been in Python from the beginning. Currently
Python's division operator, @code{/}, behaves like C's division operator when
presented with two integer arguments: it returns an integer result that's
truncated down when there would be a fractional part.  For example, @code{3/2} is
1, not 1.5, and @code{(-1)/2} is -1, not -0.5.  This means that the results of
division can vary unexpectedly depending on the type of the two operands and
because Python is dynamically typed, it can be difficult to determine the
possible types of the operands.

(The controversy is over whether this is @emph{really} a design flaw, and whether
it's worth breaking existing code to fix this.  It's caused endless discussions
on python-dev, and in July 2001 erupted into a storm of acidly sarcastic
postings on @code{comp.lang.python}. I won't argue for either side here
and will stick to describing what's  implemented in 2.2.  Read 
@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238} for a
summary of arguments and counter-arguments.)

Because this change might break code, it's being introduced very gradually.
Python 2.2 begins the transition, but the switch won't be complete until Python
3.0.

First, I'll borrow some terminology from 
@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238}.  "True division" is the
division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is 0.25,
and so forth.  "Floor division" is what Python's @code{/} operator currently does
when given integer operands; the result is the floor of the value returned by
true division.  "Classic division" is the current mixed behaviour of @code{/}; it
returns the result of floor division when the operands are integers, and returns
the result of true division when one of the operands is a floating-point number.

Here are the changes 2.2 introduces:


@itemize *

@item 
A new operator, @code{//}, is the floor division operator. (Yes, we know it looks
like C++'s comment symbol.)  @code{//} @emph{always} performs floor division no matter
what the types of its operands are, so @code{1 // 2} is 0 and @code{1.0 // 2.0} is
also 0.0.

@code{//} is always available in Python 2.2; you don't need to enable it using a
@code{__future__} statement.

@item 
By including a @code{from __future__ import division} in a module, the @code{/}
operator will be changed to return the result of true division, so @code{1/2} is
0.5.  Without the @code{__future__} statement, @code{/} still means classic division.
The default meaning of @code{/} will not change until Python 3.0.

@item 
Classes can define methods called @ref{87f,,__truediv__()} and @ref{eff,,__floordiv__()}
to overload the two division operators.  At the C level, there are also slots in
the @ref{e4e,,PyNumberMethods} structure so extension types can define the two
operators.

@item 
Python 2.2 supports some command-line arguments for testing whether code will
work with the changed division semantics.  Running python with @code{-Q
warn} will cause a warning to be issued whenever division is applied to two
integers.  You can use this to find code that's affected by the change and fix
it.  By default, Python 2.2 will simply perform classic division without a
warning; the warning will be turned on by default in Python 2.3.
@end itemize


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 238

@item PEP 238@footnote{https://www.python.org/dev/peps/pep-0238} - Changing the Division Operator

由 Moshe Zadka 和 Guido van Rossum 撰写 ; 由 Guido van Rossum 实现。
@end table


@c ======================================================================

@node Unicode Changes,PEP 227 嵌套的作用域,PEP 238 Changing the Division Operator,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 unicode-changes}@anchor{f00}
@subsection Unicode Changes


Python's Unicode support has been enhanced a bit in 2.2.  Unicode strings are
usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be
compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by
supplying @code{--enable-unicode=ucs4} to the configure script.   (It's also
possible to specify @code{--disable-unicode} to completely disable Unicode
support.)

When built to use UCS-4 (a "wide Python"), the interpreter can natively handle
Unicode characters from U+000000 to U+110000, so the range of legal values for
the @code{unichr()} function is expanded accordingly.  Using an interpreter
compiled to use UCS-2 (a "narrow Python"), values greater than 65535 will still
cause @code{unichr()} to raise a @ref{16d,,ValueError} exception. This is all
described in 
@geindex Python 提高建议; PEP 261
PEP 261@footnote{https://www.python.org/dev/peps/pep-0261}, "Support for 'wide' Unicode characters"; consult it for
further details.

Another change is simpler to explain. Since their introduction, Unicode strings
have supported an @code{encode()} method to convert the string to a selected
encoding such as UTF-8 or Latin-1.  A symmetric @code{decode([*encoding*])}
method has been added to 8-bit strings (though not to Unicode strings) in 2.2.
@code{decode()} assumes that the string is in the specified encoding and decodes
it, returning whatever is returned by the codec.

Using this new feature, codecs have been added for tasks not directly related to
Unicode.  For example, codecs have been added for uu-encoding, MIME's base64
encoding, and compression with the @ref{14d,,zlib} module:

@example
>>> s = """Here is a lengthy piece of redundant, overly verbose,
... and repetitive text.
... """
>>> data = s.encode('zlib')
>>> data
'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
>>> data.decode('zlib')
'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
>>> print s.encode('uu')
begin 666 <data>
M2&5R92!I<R!A(&QE;F=T:'D@@<&EE8V4@@;V8@@<F5D=6YD86YT+"!O=F5R;'D@@
>=F5R8F]S92P*86YD(')E<&5T:71I=F4@@=&5X="X*

end
>>> "sheesh".encode('rot-13')
'furrfu'
@end example

To convert a class instance to Unicode, a @code{__unicode__()} method can be
defined by a class, analogous to @ref{f01,,__str__()}.

@code{encode()}, @code{decode()}, and @code{__unicode__()} were implemented by
Marc-André Lemburg.  The changes to support using UCS-4 internally were
implemented by Fredrik Lundh and Martin von Löwis.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 261

@item PEP 261@footnote{https://www.python.org/dev/peps/pep-0261} - 对 '宽' Unicode 字符的支持

由 Paul Prescod 编写。
@end table


@c ======================================================================

@node PEP 227 嵌套的作用域,新增和改进的模块<3>,Unicode Changes,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 pep-227-nested-scopes}@anchor{f02}
@subsection PEP 227: 嵌套的作用域


In Python 2.1, statically nested scopes were added as an optional feature, to be
enabled by a @code{from __future__ import nested_scopes} directive.  In 2.2 nested
scopes no longer need to be specially enabled, and are now always present.  The
rest of this section is a copy of the description of nested scopes from my
"What's New in Python 2.1" document; if you read it when 2.1 came out, you can
skip the rest of this section.

The largest change introduced in Python 2.1, and made complete in 2.2, is to
Python's scoping rules.  In Python 2.0, at any given time there are at most
three namespaces used to look up variable names: local, module-level, and the
built-in namespace.  This often surprised people because it didn't match their
intuitive expectations.  For example, a nested recursive function definition
doesn't work:

@example
def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...
@end example

The function @code{g()} will always raise a @ref{e48,,NameError} exception, because
the binding of the name @code{g} isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the @ref{d01,,lambda} expression clumsier, and this was a problem in practice.
In code which uses @code{lambda} you can often find local variables being
copied by passing them as the default values of arguments.

@example
def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L
@end example

The readability of Python code written in a strongly functional style suffers
greatly as a result.

The most significant change to Python 2.2 is that static scoping has been added
to the language to fix this problem.  As a first effect, the @code{name=name}
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the @ref{e8b,,def}, @ref{d3a,,class}, or @ref{cef,,import} statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.

One side effect of the change is that the @code{from module import *} and
@code{exec} statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that @code{from
module import *} is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  @code{from
module import *} and @code{exec} make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or @ref{d01,,lambda} expressions with free variables, the compiler
will flag this by raising a @ref{562,,SyntaxError} exception.

为了使前面的解释更清楚，下面是一个例子:

@example
x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x
@end example

Line 4 containing the @code{exec} statement is a syntax error, since
@code{exec} would define a new local variable named @code{x} whose value should
be accessed by @code{g()}.

This shouldn't be much of a limitation, since @code{exec} is rarely used in
most Python code (and when it is used, it's often a sign of a poor design
anyway).


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 227

@item PEP 227@footnote{https://www.python.org/dev/peps/pep-0227} - 静态嵌套作用域

由 Jeremy Hylton 撰写并实现。
@end table


@c ======================================================================

@node 新增和改进的模块<3>,解释器的改变和修正,PEP 227 嵌套的作用域,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 new-and-improved-modules}@anchor{f03}
@subsection 新增和改进的模块



@itemize *

@item 
The @code{xmlrpclib} module was contributed to the standard library by Fredrik
Lundh, providing support for writing XML-RPC clients.  XML-RPC is a simple
remote procedure call protocol built on top of HTTP and XML. For example, the
following snippet retrieves a list of RSS channels from the O'Reilly Network,
and then  lists the recent headlines for one channel:

@example
import xmlrpclib
s = xmlrpclib.Server(
      'http://www.oreillynet.com/meerkat/xml-rpc/server.php')
channels = s.meerkat.getChannels()
# channels is a list of dictionaries, like this:
# [@{'id': 4, 'title': 'Freshmeat Daily News'@}
#  @{'id': 190, 'title': '32Bits Online'@},
#  @{'id': 4549, 'title': '3DGamers'@}, ... ]

# Get the items for one channel
items = s.meerkat.getItems( @{'channel': 4@} )

# 'items' is another list of dictionaries, like this:
# [@{'link': 'http://freshmeat.net/releases/52719/',
#   'description': 'A utility which converts HTML to XSL FO.',
#   'title': 'html2fo 0.3 (Default)'@}, ... ]
@end example

The @code{SimpleXMLRPCServer} module makes it easy to create straightforward
XML-RPC servers.  See @indicateurl{http://xmlrpc.scripting.com/} for more information about XML-RPC.

@item 
The new @ref{8e,,hmac} module implements the HMAC algorithm described by
@geindex RFC; RFC 2104
RFC 2104@footnote{https://tools.ietf.org/html/rfc2104.html}. (Contributed by Gerhard Häring.)

@item 
Several functions that originally returned lengthy tuples now return
pseudo-sequences that still behave like tuples but also have mnemonic attributes such
as memberst_mtime or @code{tm_year}. The enhanced functions include
@ref{f4,,stat()}, @code{fstat()}, @code{statvfs()}, and @code{fstatvfs()} in the
@ref{c4,,os} module, and @code{localtime()}, @code{gmtime()}, and @code{strptime()} in
the @ref{10c,,time} module.

For example, to obtain a file's size using the old tuples, you'd end up writing
something like @code{file_size = os.stat(filename)[stat.ST_SIZE]}, but now this can
be written more clearly as @code{file_size = os.stat(filename).st_size}.

此特性的初始补丁由 Nick Mathewson 贡献。

@item 
The Python profiler has been extensively reworked and various errors in its
output have been corrected.  (Contributed by Fred L. Drake, Jr. and Tim Peters.)

@item 
The @ref{ef,,socket} module can be compiled to support IPv6; specify the
@code{--enable-ipv6} option to Python's configure script.  (Contributed by
Jun-ichiro "itojun" Hagino.)

@item 
Two new format characters were added to the @ref{f8,,struct} module for 64-bit
integers on platforms that support the C @code{long long} type.  @code{q} is for
a signed 64-bit integer, and @code{Q} is for an unsigned one.  The value is
returned in Python's long integer type.  (Contributed by Tim Peters.)

@item 
In the interpreter's interactive mode, there's a new built-in function
@ref{175,,help()} that uses the @ref{d9,,pydoc} module introduced in Python 2.1 to
provide interactive help. @code{help(object)} displays any available help text
about @emph{object}.  @ref{175,,help()} with no argument puts you in an online help
utility, where you can enter the names of functions, classes, or modules to read
their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee's
@ref{d9,,pydoc} module.)

@item 
Various bugfixes and performance improvements have been made to the SRE engine
underlying the @ref{dd,,re} module.  For example, the @ref{582,,re.sub()} and
@ref{4d9,,re.split()} functions have been rewritten in C.  Another contributed patch
speeds up certain Unicode character ranges by a factor of two, and a new
@code{finditer()}  method that returns an iterator over all the non-overlapping
matches in  a given string.  (SRE is maintained by Fredrik Lundh.  The
BIGCHARSET patch was contributed by Martin von Löwis.)

@item 
The @ref{ed,,smtplib} module now supports 
@geindex RFC; RFC 2487
RFC 2487@footnote{https://tools.ietf.org/html/rfc2487.html}, "Secure SMTP over TLS", so
it's now possible to encrypt the SMTP traffic between a Python program and the
mail transport agent being handed a message.  @ref{ed,,smtplib} also supports SMTP
authentication.  (Contributed by Gerhard Häring.)

@item 
The @ref{97,,imaplib} module, maintained by Piers Lauder, has support for several
new extensions: the NAMESPACE extension defined in 
@geindex RFC; RFC 2342
RFC 2342@footnote{https://tools.ietf.org/html/rfc2342.html}, SORT, GETACL and
SETACL.  (Contributed by Anthony Baxter and Michel Pelletier.)

@item 
The @code{rfc822} module's parsing of email addresses is now compliant with
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html}, an update to 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html}.  (The module's name is @emph{not} going to be
changed to @code{rfc2822}.)  A new package, @ref{67,,email}, has also been added for
parsing and generating e-mail messages.  (Contributed by Barry Warsaw, and
arising out of his work on Mailman.)

@item 
The @ref{36,,difflib} module now contains a new @code{Differ} class for
producing human-readable lists of changes (a "delta") between two sequences of
lines of text.  There are also two generator functions, @code{ndiff()} and
@code{restore()}, which respectively return a delta from two sequences, or one of
the original sequences from a delta. (Grunt work contributed by David Goodger,
from ndiff.py code by Tim Peters who then did the generatorization.)

@item 
New constants @code{ascii_letters}, @code{ascii_lowercase}, and
@code{ascii_uppercase} were added to the @ref{f6,,string} module.  There were
several modules in the standard library that used @code{string.letters} to
mean the ranges A-Za-z, but that assumption is incorrect when locales are in
use, because @code{string.letters} varies depending on the set of legal
characters defined by the current locale.  The buggy modules have all been fixed
to use @code{ascii_letters} instead. (Reported by an unknown person; fixed by
Fred L. Drake, Jr.)

@item 
The @ref{b2,,mimetypes} module now makes it easier to use alternative MIME-type
databases by the addition of a @code{MimeTypes} class, which takes a list of
filenames to be parsed.  (Contributed by Fred L. Drake, Jr.)

@item 
A @code{Timer} class was added to the @ref{10b,,threading} module that allows
scheduling an activity to happen at some future time.  (Contributed by Itamar
Shtull-Trauring.)
@end itemize

@c ======================================================================

@node 解释器的改变和修正,其他的改变和修正<3>,新增和改进的模块<3>,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 interpreter-changes-and-fixes}@anchor{f04}
@subsection 解释器的改变和修正


Some of the changes only affect people who deal with the Python interpreter at
the C level because they're writing Python extension modules, embedding the
interpreter, or just hacking on the interpreter itself. If you only write Python
code, none of the changes described here will affect you very much.


@itemize *

@item 
Profiling and tracing functions can now be implemented in C, which can operate
at much higher speeds than Python-based functions and should reduce the overhead
of profiling and tracing.  This  will be of interest to authors of development
environments for Python.  Two new C functions were added to Python's API,
@ref{f05,,PyEval_SetProfile()} and @ref{f06,,PyEval_SetTrace()}. The existing
@ref{f07,,sys.setprofile()} and @ref{f08,,sys.settrace()} functions still exist, and have
simply been changed to use the new C-level interface.  (Contributed by Fred L.
Drake, Jr.)

@item 
Another low-level API, primarily of interest to implementors of Python
debuggers and development tools, was added. @ref{f09,,PyInterpreterState_Head()} and
@ref{f0a,,PyInterpreterState_Next()} let a caller walk through all the existing
interpreter objects; @ref{f0b,,PyInterpreterState_ThreadHead()} and
@ref{f0c,,PyThreadState_Next()} allow looping over all the thread states for a given
interpreter.  (Contributed by David Beazley.)

@item 
The C-level interface to the garbage collector has been changed to make it
easier to write extension types that support garbage collection and to debug
misuses of the functions. Various functions have slightly different semantics,
so a bunch of functions had to be renamed.  Extensions that use the old API will
still compile but will @emph{not} participate in garbage collection, so updating them
for 2.2 should be considered fairly high priority.

要将一个扩展模块升级至新 API，请执行下列步骤:

@item 
将 @code{Py_TPFLAGS_GC()} 重命名为 @code{PyTPFLAGS_HAVE_GC()}。

@item 

@table @asis

@item 使用 @ref{3fc,,PyObject_GC_New()} 或 @ref{3fd,,PyObject_GC_NewVar()} 来分配

对象，并使用 @ref{f0d,,PyObject_GC_Del()} 来释放它们。
@end table

@item 

@table @asis

@item 将 @code{PyObject_GC_Init()} 重命名为 @ref{f0e,,PyObject_GC_Track()} 并

将 @code{PyObject_GC_Fini()} 重命名为 @ref{f0f,,PyObject_GC_UnTrack()}。
@end table

@item 
将 @code{PyGC_HEAD_SIZE()} 从对象大小计算中移除。

@item 
移除对 @code{PyObject_AS_GC()} 和 @code{PyObject_FROM_GC()} 的调用。

@item 
A new @code{et} format sequence was added to @ref{39b,,PyArg_ParseTuple()}; @code{et}
takes both a parameter and an encoding name, and converts the parameter to the
given encoding if the parameter turns out to be a Unicode string, or leaves it
alone if it's an 8-bit string, assuming it to already be in the desired
encoding.  This differs from the @code{es} format character, which assumes that
8-bit strings are in Python's default ASCII encoding and converts them to the
specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS
support on Windows described in the following section.)

@item 
A different argument parsing function, @ref{f10,,PyArg_UnpackTuple()}, has been
added that's simpler and presumably faster.  Instead of specifying a format
string, the caller simply gives the minimum and maximum number of arguments
expected, and a set of pointers to @ref{5bd,,PyObject*} variables that will be
filled in with argument values.

@item 
Two new flags @ref{ee2,,METH_NOARGS} and @ref{f11,,METH_O} are available in method
definition tables to simplify implementation of methods with no arguments or a
single untyped argument. Calling such methods is more efficient than calling a
corresponding method that uses @ref{f12,,METH_VARARGS}.  Also, the old
@code{METH_OLDARGS} style of writing C methods is  now officially deprecated.

@item 
Two new wrapper functions, @ref{f13,,PyOS_snprintf()} and @ref{f14,,PyOS_vsnprintf()}
were added to provide  cross-platform implementations for the relatively new
@code{snprintf()} and @code{vsnprintf()} C lib APIs. In contrast to the standard
@code{sprintf()} and @code{vsprintf()} functions, the Python versions check the
bounds of the buffer used to protect against buffer overruns. (Contributed by
M.-A. Lemburg.)

@item 
The @ref{f15,,_PyTuple_Resize()} function has lost an unused parameter, so now it
takes 2 parameters instead of 3.  The third argument was never used, and can
simply be discarded when porting code from earlier versions to Python 2.2.
@end itemize

@c ======================================================================

@node 其他的改变和修正<3>,致谢<6>,解释器的改变和修正,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 other-changes-and-fixes}@anchor{f16}
@subsection 其他的改变和修正


As usual there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1
applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches and fixed 82
bugs.  These figures are likely to be underestimates.

一些较为重要的改变:


@itemize *

@item 
The code for the MacOS port for Python, maintained by Jack Jansen, is now kept
in the main Python CVS tree, and many changes have been made to support MacOS X.

The most significant change is the ability to build Python as a framework,
enabled by supplying the @code{--enable-framework} option to the configure
script when compiling Python.  According to Jack Jansen, "This installs a
self-contained Python installation plus the OS X framework "glue" into
@code{/Library/Frameworks/Python.framework} (or another location of choice).
For now there is little immediate added benefit to this (actually, there is the
disadvantage that you have to change your PATH to be able to find Python), but
it is the basis for creating a full-blown Python application, porting the
MacPython IDE, possibly using Python as a standard OSA scripting language and
much more."

Most of the MacPython toolbox modules, which interface to MacOS APIs such as
windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been
left commented out in @code{setup.py}.  People who want to experiment with
these modules can uncomment them manually.

@c Jack's original comments:
@c The main change is the possibility to build Python as a
@c framework. This installs a self-contained Python installation plus the
@c OSX framework "glue" into /Library/Frameworks/Python.framework (or
@c another location of choice). For now there is little immediate added
@c benefit to this (actually, there is the disadvantage that you have to
@c change your PATH to be able to find Python), but it is the basis for
@c creating a fullblown Python application, porting the MacPython IDE,
@c possibly using Python as a standard OSA scripting language and much
@c more. You enable this with "configure --enable-framework".
@c The other change is that most MacPython toolbox modules, which
@c interface to all the MacOS APIs such as windowing, quicktime,
@c scripting, etc. have been ported. Again, most of these are not of
@c immediate use, as they need a full application to be really useful, so
@c they have been commented out in setup.py. People wanting to experiment
@c can uncomment them. Gestalt and Internet Config modules are enabled by
@c default.

@item 
Keyword arguments passed to built-in functions that don't take them now cause a
@ref{1ff,,TypeError} exception to be raised, with the message "@emph{function} takes no
keyword arguments".

@item 
Weak references, added in Python 2.1 as an extension module, are now part of
the core because they're used in the implementation of new-style classes.  The
@ref{f17,,ReferenceError} exception has therefore moved from the @ref{131,,weakref}
module to become a built-in exception.

@item 
A new script, @code{Tools/scripts/cleanfuture.py} by Tim Peters,
automatically removes obsolete @code{__future__} statements from Python source
code.

@item 
An additional @emph{flags} argument has been added to the built-in function
@ref{2ee,,compile()}, so the behaviour of @code{__future__} statements can now be
correctly observed in simulated shells, such as those presented by IDLE and
other development environments.  This is described in 
@geindex Python 提高建议; PEP 264
PEP 264@footnote{https://www.python.org/dev/peps/pep-0264}. (Contributed
by Michael Hudson.)

@item 
The new license introduced with Python 1.6 wasn't GPL-compatible.  This is
fixed by some minor textual changes to the 2.2 license, so it's now legal to
embed Python inside a GPLed program again.  Note that Python itself is not
GPLed, but instead is under a license that's essentially equivalent to the BSD
license, same as it always was.  The license changes were also applied to the
Python 2.0.1 and 2.1.1 releases.

@item 
When presented with a Unicode filename on Windows, Python will now convert it
to an MBCS encoded string, as used by the Microsoft file APIs.  As MBCS is
explicitly used by the file APIs, Python's choice of ASCII as the default
encoding turns out to be an annoyance.  On Unix, the locale's character set is
used if @code{locale.nl_langinfo(CODESET)} is available.  (Windows support was
contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix
support was added by Martin von Löwis.)

@item 
大文件支持目前已在 Windows 上启用。 （由 Tim Peters 贡献。）

@item 
@code{Tools/scripts/ftpmirror.py} 脚本现在会解析 @code{.netrc} 文件，如果存在的话。 （由 Mike Romberg 贡献。）

@item 
Some features of the object returned by the @code{xrange()} function are now
deprecated, and trigger warnings when they're accessed; they'll disappear in
Python 2.3. @code{xrange} objects tried to pretend they were full sequence
types by supporting slicing, sequence multiplication, and the @ref{179,,in}
operator, but these features were rarely used and therefore buggy.  The
@code{tolist()} method and the @code{start}, @code{stop}, and @code{step}
attributes are also being deprecated.  At the C level, the fourth argument to
the @code{PyRange_New()} function, @code{repeat}, has also been deprecated.

@item 
There were a bunch of patches to the dictionary implementation, mostly to fix
potential core dumps if a dictionary contains objects that sneakily changed
their hash value, or mutated the dictionary they were contained in. For a while
python-dev fell into a gentle rhythm of Michael Hudson finding a case that
dumped core, Tim Peters fixing the bug, Michael finding another case, and round
and round it went.

@item 
On Windows, Python can now be compiled with Borland C thanks to a number of
patches contributed by Stephen Hansen, though the result isn't fully functional
yet.  (But this @emph{is} progress...)

@item 
Another Windows enhancement: Wise Solutions generously offered PythonLabs use
of their InstallerMaster 8.1 system.  Earlier PythonLabs Windows installers used
Wise 5.0a, which was beginning to show its age.  (Packaged up by Tim Peters.)

@item 
Files ending in @code{.pyw} can now be imported on Windows. @code{.pyw} is a
Windows-only thing, used to indicate that a script needs to be run using
PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS console from popping
up to display the output.  This patch makes it possible to import such scripts,
in case they're also usable as modules.  (Implemented by David Bolen.)

@item 
On platforms where Python uses the C @code{dlopen()} function  to load
extension modules, it's now possible to set the flags used  by @code{dlopen()}
using the @ref{f18,,sys.getdlopenflags()} and @ref{b4a,,sys.setdlopenflags()} functions.
(Contributed by Bram Stolk.)

@item 
The @ref{2d6,,pow()} built-in function no longer supports 3 arguments when
floating-point numbers are supplied. @code{pow(x, y, z)} returns @code{(x**y) % z},
but this is never useful for floating point numbers, and the final result varies
unpredictably depending on the platform.  A call such as @code{pow(2.0, 8.0, 7.0)}
will now raise a @ref{1ff,,TypeError} exception.
@end itemize

@c ======================================================================

@node 致谢<6>,,其他的改变和修正<3>,Python 2 2 有什么新变化
@anchor{whatsnew/2 2 acknowledgements}@anchor{f19}
@subsection 致谢


作者感谢以下人员为本文的各种草案提供建议，更正和帮助： Fred Bremmer, Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger, Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen, Marc-André Lemburg, Martin von Löwis, Fredrik Lundh, Michael McLay, Nick Mathewson, Paul Moore, Gustavo Niemeyer, Don O'Donnell, Joonas Paalasma, Tim Peters, Jens Quade, Tom Reinhardt, Neil Schemenauer, Guido van Rossum, Greg Ward, Edward Welbourne.

@node Python 2 1 有什么新变化,Python 2 0 有什么新变化,Python 2 2 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 1 doc}@anchor{f1a}@anchor{whatsnew/2 1 what-s-new-in-python-2-1}@anchor{f1b}
@section Python 2.1 有什么新变化


@*作者: 
A.M. Kuchling


@c $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $

@menu
* 概述: 概述<2>. 
* PEP 227; 嵌套的作用域: PEP 227 嵌套的作用域<2>. 
* PEP 236; __future__ 指令: PEP 236 __future__ 指令. 
* PEP 207; 富比较: PEP 207 富比较. 
* PEP 230; 警告框架: PEP 230 警告框架. 
* PEP 229; 新的构建系统: PEP 229 新的构建系统. 
* PEP 205; 弱引用: PEP 205 弱引用. 
* PEP 232; 函数属性: PEP 232 函数属性. 
* PEP 235; 在大小写不敏感的平台上导入模块: PEP 235 在大小写不敏感的平台上导入模块. 
* PEP 217; Interactive Display Hook: PEP 217 Interactive Display Hook. 
* PEP 208; New Coercion Model: PEP 208 New Coercion Model. 
* PEP 241; Metadata in Python Packages: PEP 241 Metadata in Python Packages. 
* 新增和改进的模块: 新增和改进的模块<4>. 
* 其他的改变和修正: 其他的改变和修正<4>. 
* 致谢: 致谢<7>. 

@end menu

@node 概述<2>,PEP 227 嵌套的作用域<2>,,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 introduction}@anchor{f1c}
@subsection 概述


This article explains the new features in Python 2.1.  While there aren't as
many changes in 2.1 as there were in Python 2.0, there are still some pleasant
surprises in store.  2.1 is the first release to be steered through the use of
Python Enhancement Proposals, or PEPs, so most of the sizable changes have
accompanying PEPs that provide more complete documentation and a design
rationale for the change.  This article doesn't attempt to document the new
features completely, but simply provides an overview of the new features for
Python programmers. Refer to the Python 2.1 documentation, or to the specific
PEP, for more details about any new feature that particularly interests you.

One recent goal of the Python development team has been to accelerate the pace
of new releases, with a new release coming every 6 to 9 months. 2.1 is the first
release to come out at this faster pace, with the first alpha appearing in
January, 3 months after the final version of 2.0 was released.

Python 2.1 的最终版本于2001年4月17日发布。

@c ======================================================================

@node PEP 227 嵌套的作用域<2>,PEP 236 __future__ 指令,概述<2>,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-227-nested-scopes}@anchor{f1d}
@subsection PEP 227: 嵌套的作用域


The largest change in Python 2.1 is to Python's scoping rules.  In Python 2.0,
at any given time there are at most three namespaces used to look up variable
names: local, module-level, and the built-in namespace.  This often surprised
people because it didn't match their intuitive expectations.  For example, a
nested recursive function definition doesn't work:

@example
def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...
@end example

The function @code{g()} will always raise a @ref{e48,,NameError} exception, because
the binding of the name @code{g} isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the @ref{d01,,lambda} expression clumsier, and this was a problem in practice.
In code which uses @ref{d01,,lambda} you can often find local variables being
copied by passing them as the default values of arguments.

@example
def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L
@end example

The readability of Python code written in a strongly functional style suffers
greatly as a result.

The most significant change to Python 2.1 is that static scoping has been added
to the language to fix this problem.  As a first effect, the @code{name=name}
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the @ref{e8b,,def}, @ref{d3a,,class}, or @ref{cef,,import} statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.

One side effect of the change is that the @code{from module import *} and
@code{exec} statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that @code{from
module import *} is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  @code{from
module import *} and @code{exec} make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or @ref{d01,,lambda} expressions with free variables, the compiler
will flag this by raising a @ref{562,,SyntaxError} exception.

为了使前面的解释更清楚，下面是一个例子:

@example
x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x
@end example

Line 4 containing the @code{exec} statement is a syntax error, since
@code{exec} would define a new local variable named @code{x} whose value should
be accessed by @code{g()}.

This shouldn't be much of a limitation, since @code{exec} is rarely used in
most Python code (and when it is used, it's often a sign of a poor design
anyway).

Compatibility concerns have led to nested scopes being introduced gradually; in
Python 2.1, they aren't enabled by default, but can be turned on within a module
by using a future statement as described in 
@geindex Python 提高建议; PEP 236
PEP 236@footnote{https://www.python.org/dev/peps/pep-0236}.  (See the following section
for further discussion of 
@geindex Python 提高建议; PEP 236
PEP 236@footnote{https://www.python.org/dev/peps/pep-0236}.)  In Python 2.2, nested scopes will become
the default and there will be no way to turn them off, but users will have had
all of 2.1's lifetime to fix any breakage resulting from their introduction.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 227

@item PEP 227@footnote{https://www.python.org/dev/peps/pep-0227} - 静态嵌套作用域

由 Jeremy Hylton 撰写并实现。
@end table


@c ======================================================================

@node PEP 236 __future__ 指令,PEP 207 富比较,PEP 227 嵌套的作用域<2>,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-236-future-directives}@anchor{f1e}
@subsection PEP 236: __future__ 指令


The reaction to nested scopes was widespread concern about the dangers of
breaking code with the 2.1 release, and it was strong enough to make the
Pythoneers take a more conservative approach.  This approach consists of
introducing a convention for enabling optional functionality in release N that
will become compulsory in release N+1.

The syntax uses a @code{from...import} statement using the reserved module name
@ref{0,,__future__}.  Nested scopes can be enabled by the following statement:

@example
from __future__ import nested_scopes
@end example

While it looks like a normal @ref{cef,,import} statement, it's not; there are
strict rules on where such a future statement can be put. They can only be at
the top of a module, and must precede any Python code or regular
@code{import} statements.  This is because such statements can affect how
the Python bytecode compiler parses code and generates bytecode, so they must
precede any statement that will result in bytecodes being produced.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 236

@item PEP 236@footnote{https://www.python.org/dev/peps/pep-0236} - 回到 @ref{0,,__future__}

由 Tim Peters 撰写，主要由 Jeremy Hylton 实现。
@end table


@c ======================================================================

@node PEP 207 富比较,PEP 230 警告框架,PEP 236 __future__ 指令,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-207-rich-comparisons}@anchor{f1f}
@subsection PEP 207: 富比较


In earlier versions, Python's support for implementing comparisons on user-defined
classes and extension types was quite simple. Classes could implement a
@code{__cmp__()} method that was given two instances of a class, and could only
return 0 if they were equal or +1 or -1 if they weren't; the method couldn't
raise an exception or return anything other than a Boolean value.  Users of
Numeric Python often found this model too weak and restrictive, because in the
number-crunching programs that numeric Python is used for, it would be more
useful to be able to perform elementwise comparisons of two matrices, returning
a matrix containing the results of a given comparison for each element.  If the
two matrices are of different sizes, then the compare has to be able to raise an
exception to signal the error.

In Python 2.1, rich comparisons were added in order to support this need.
Python classes can now individually overload each of the @code{<}, @code{<=}, @code{>},
@code{>=}, @code{==}, and @code{!=} operations.  The new magic method names are:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

方法名称

@item

@code{<}

@tab

@ref{d06,,__lt__()}

@item

@code{<=}

@tab

@ref{d70,,__le__()}

@item

@code{>}

@tab

@ref{d71,,__gt__()}

@item

@code{>=}

@tab

@ref{d72,,__ge__()}

@item

@code{==}

@tab

@ref{454,,__eq__()}

@item

@code{!=}

@tab

@ref{f20,,__ne__()}

@end multitable


(The magic methods are named after the corresponding Fortran operators @code{.LT.}.
@code{.LE.}, &c.  Numeric programmers are almost certainly quite familiar with
these names and will find them easy to remember.)

Each of these magic methods is of the form @code{method(self, other)}, where
@code{self} will be the object on the left-hand side of the operator, while
@code{other} will be the object on the right-hand side.  For example, the
expression @code{A < B} will cause @code{A.__lt__(B)} to be called.

Each of these magic methods can return anything at all: a Boolean, a matrix, a
list, or any other Python object.  Alternatively they can raise an exception if
the comparison is impossible, inconsistent, or otherwise meaningless.

The built-in @code{cmp(A,B)} function can use the rich comparison machinery,
and now accepts an optional argument specifying which comparison operation to
use; this is given as one of the strings @code{"<"}, @code{"<="}, @code{">"}, @code{">="},
@code{"=="}, or @code{"!="}.  If called without the optional third argument,
@code{cmp()} will only return -1, 0, or +1 as in previous versions of Python;
otherwise it will call the appropriate method and can return any Python object.

There are also corresponding changes of interest to C programmers; there's a new
slot @code{tp_richcmp} in type objects and an API for performing a given rich
comparison.  I won't cover the C API here, but will refer you to 
@geindex Python 提高建议; PEP 207
PEP 207@footnote{https://www.python.org/dev/peps/pep-0207}, or to
2.1's C API documentation, for the full list of related functions.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 207

@item PEP 207@footnote{https://www.python.org/dev/peps/pep-0207} - 富比较

由 Guido van Rossum 编写，大量参考 David Ascher 的先期工作，并由 Guido van Rossum 实现。
@end table


@c ======================================================================

@node PEP 230 警告框架,PEP 229 新的构建系统,PEP 207 富比较,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-230-warning-framework}@anchor{f21}
@subsection PEP 230: 警告框架


Over its 10 years of existence, Python has accumulated a certain number of
obsolete modules and features along the way.  It's difficult to know when a
feature is safe to remove, since there's no way of knowing how much code uses it
--- perhaps no programs depend on the feature, or perhaps many do.  To enable
removing old features in a more structured way, a warning framework was added.
When the Python developers want to get rid of a feature, it will first trigger a
warning in the next version of Python.  The following Python version can then
drop the feature, and users will have had a full release cycle to remove uses of
the old feature.

Python 2.1 adds the warning framework to be used in this scheme.  It adds a
@ref{12f,,warnings} module that provide functions to issue warnings, and to filter
out warnings that you don't want to be displayed. Third-party modules can also
use this framework to deprecate old features that they no longer wish to
support.

For example, in Python 2.1 the @code{regex} module is deprecated, so importing
it causes a warning to be printed:

@example
>>> import regex
__main__:1: DeprecationWarning: the regex module
         is deprecated; please use the re module
>>>
@end example

警告可以通过调用 @ref{f22,,warnings.warn()} 函数来发出:

@example
warnings.warn("feature X no longer supported")
@end example

The first parameter is the warning message; an additional optional parameters
can be used to specify a particular warning category.

Filters can be added to disable certain warnings; a regular expression pattern
can be applied to the message or to the module name in order to suppress a
warning.  For example, you may have a program that uses the @code{regex} module
and not want to spare the time to convert it to use the @ref{dd,,re} module right
now.  The warning can be suppressed by calling

@example
import warnings
warnings.filterwarnings(action = 'ignore',
                        message='.*regex module is deprecated',
                        category=DeprecationWarning,
                        module = '__main__')
@end example

This adds a filter that will apply only to warnings of the class
@ref{15a,,DeprecationWarning} triggered in the @ref{1,,__main__} module, and applies
a regular expression to only match the message about the @code{regex} module
being deprecated, and will cause such warnings to be ignored.  Warnings can also
be printed only once, printed every time the offending code is executed, or
turned into exceptions that will cause the program to stop (unless the
exceptions are caught in the usual way, of course).

Functions were also added to Python's C API for issuing warnings; refer to PEP
230 or to Python's API documentation for the details.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 5

@item PEP 5@footnote{https://www.python.org/dev/peps/pep-0005} - 语言演化的准则

Written by Paul Prescod, to specify procedures to be followed when removing old
features from Python.  The policy described in this PEP hasn't been officially
adopted, but the eventual policy probably won't be too different from Prescod's
proposal.

@geindex Python 提高建议; PEP 230

@item PEP 230@footnote{https://www.python.org/dev/peps/pep-0230} - 警告框架

由 Guido van Rossum 撰写并实现。
@end table


@c ======================================================================

@node PEP 229 新的构建系统,PEP 205 弱引用,PEP 230 警告框架,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-229-new-build-system}@anchor{f23}
@subsection PEP 229: 新的构建系统


When compiling Python, the user had to go in and edit the @code{Modules/Setup}
file in order to enable various additional modules; the default set is
relatively small and limited to modules that compile on most Unix platforms.
This means that on Unix platforms with many more features, most notably Linux,
Python installations often don't contain all useful modules they could.

Python 2.0 added the Distutils, a set of modules for distributing and installing
extensions.  In Python 2.1, the Distutils are used to compile much of the
standard library of extension modules, autodetecting which ones are supported on
the current machine.  It's hoped that this will make Python installations easier
and more featureful.

Instead of having to edit the @code{Modules/Setup} file in order to enable
modules, a @code{setup.py} script in the top directory of the Python source
distribution is run at build time, and attempts to discover which modules can be
enabled by examining the modules and header files on the system.  If a module is
configured in @code{Modules/Setup}, the @code{setup.py} script won't attempt
to compile that module and will defer to the @code{Modules/Setup} file's
contents.  This provides a way to specific any strange command-line flags or
libraries that are required for a specific platform.

In another far-reaching change to the build mechanism, Neil Schemenauer
restructured things so Python now uses a single makefile that isn't recursive,
instead of makefiles in the top directory and in each of the @code{Python/},
@code{Parser/}, @code{Objects/}, and @code{Modules/} subdirectories.  This
makes building Python faster and also makes hacking the Makefiles clearer and
simpler.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 229

@item PEP 229@footnote{https://www.python.org/dev/peps/pep-0229} - 使用 Distutils 来构建 Python

由 A.M. Kuchling 撰写并实现。
@end table


@c ======================================================================

@node PEP 205 弱引用,PEP 232 函数属性,PEP 229 新的构建系统,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-205-weak-references}@anchor{f24}
@subsection PEP 205: 弱引用


Weak references, available through the @ref{131,,weakref} module, are a minor but
useful new data type in the Python programmer's toolbox.

Storing a reference to an object (say, in a dictionary or a list) has the side
effect of keeping that object alive forever.  There are a few specific cases
where this behaviour is undesirable, object caches being the most common one,
and another being circular references in data structures such as trees.

For example, consider a memoizing function that caches the results of another
function @code{f(x)} by storing the function's argument and its result in a
dictionary:

@example
_cache = @{@}
def memoize(x):
    if _cache.has_key(x):
        return _cache[x]

    retval = f(x)

    # Cache the returned object
    _cache[x] = retval

    return retval
@end example

This version works for simple things such as integers, but it has a side effect;
the @code{_cache} dictionary holds a reference to the return values, so they'll
never be deallocated until the Python process exits and cleans up. This isn't
very noticeable for integers, but if @code{f()} returns an object, or a data
structure that takes up a lot of memory, this can be a problem.

Weak references provide a way to implement a cache that won't keep objects alive
beyond their time.  If an object is only accessible through weak references, the
object will be deallocated and the weak references will now indicate that the
object it referred to no longer exists.  A weak reference to an object @emph{obj} is
created by calling @code{wr = weakref.ref(obj)}.  The object being referred to is
returned by calling the weak reference as if it were a function: @code{wr()}.  It
will return the referenced object, or @code{None} if the object no longer exists.

This makes it possible to write a @code{memoize()} function whose cache doesn't
keep objects alive, by storing weak references in the cache.

@example
_cache = @{@}
def memoize(x):
    if _cache.has_key(x):
        obj = _cache[x]()
        # If weak reference object still exists,
        # return it
        if obj is not None: return obj

    retval = f(x)

    # Cache a weak reference
    _cache[x] = weakref.ref(retval)

    return retval
@end example

The @ref{131,,weakref} module also allows creating proxy objects which behave like
weak references --- an object referenced only by proxy objects is deallocated --
but instead of requiring an explicit call to retrieve the object, the proxy
transparently forwards all operations to the object as long as the object still
exists.  If the object is deallocated, attempting to use a proxy will cause a
@code{weakref.ReferenceError} exception to be raised.

@example
proxy = weakref.proxy(obj)
proxy.attr   # Equivalent to obj.attr
proxy.meth() # Equivalent to obj.meth()
del obj
proxy.attr   # raises weakref.ReferenceError
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 205

@item PEP 205@footnote{https://www.python.org/dev/peps/pep-0205} - 弱引用

由 Fred L. Drake, Jr 撰写并实现。
@end table


@c ======================================================================

@node PEP 232 函数属性,PEP 235 在大小写不敏感的平台上导入模块,PEP 205 弱引用,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-232-function-attributes}@anchor{f25}
@subsection PEP 232: 函数属性


In Python 2.1, functions can now have arbitrary information attached to them.
People were often using docstrings to hold information about functions and
methods, because the @code{__doc__} attribute was the only way of attaching any
information to a function.  For example, in the Zope Web application server,
functions are marked as safe for public access by having a docstring, and in
John Aycock's SPARK parsing framework, docstrings hold parts of the BNF grammar
to be parsed.  This overloading is unfortunate, since docstrings are really
intended to hold a function's documentation; for example, it means you can't
properly document functions intended for private use in Zope.

Arbitrary attributes can now be set and retrieved on functions using the regular
Python syntax:

@example
def f(): pass

f.publish = 1
f.secure = 1
f.grammar = "A ::= B (C D)*"
@end example

The dictionary containing attributes can be accessed as the function's
@ref{5fe,,__dict__}. Unlike the @ref{5fe,,__dict__} attribute of class instances, in
functions you can actually assign a new dictionary to @ref{5fe,,__dict__}, though
the new value is restricted to a regular Python dictionary; you @emph{can't} be
tricky and set it to a @code{UserDict} instance, or any other random object
that behaves like a mapping.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 232

@item PEP 232@footnote{https://www.python.org/dev/peps/pep-0232} - 函数属性

由 Barry Warsaw 撰写并实现
@end table


@c ======================================================================

@node PEP 235 在大小写不敏感的平台上导入模块,PEP 217 Interactive Display Hook,PEP 232 函数属性,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-235-importing-modules-on-case-insensitive-platforms}@anchor{f26}
@subsection PEP 235: 在大小写不敏感的平台上导入模块


Some operating systems have filesystems that are case-insensitive, MacOS and
Windows being the primary examples; on these systems, it's impossible to
distinguish the filenames @code{FILE.PY} and @code{file.py}, even though they do store
the file's name  in its original case (they're case-preserving, too).

In Python 2.1, the @ref{cef,,import} statement will work to simulate case-sensitivity
on case-insensitive platforms.  Python will now search for the first
case-sensitive match by default, raising an @ref{16c,,ImportError} if no such file
is found, so @code{import file} will not import a module named @code{FILE.PY}.
Case-insensitive matching can be requested by setting the 
@geindex PYTHONCASEOK
@geindex 环境变量; PYTHONCASEOK
@ref{233,,PYTHONCASEOK}
environment variable before starting the Python interpreter.

@c ======================================================================

@node PEP 217 Interactive Display Hook,PEP 208 New Coercion Model,PEP 235 在大小写不敏感的平台上导入模块,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-217-interactive-display-hook}@anchor{f27}
@subsection PEP 217: Interactive Display Hook


When using the Python interpreter interactively, the output of commands is
displayed using the built-in @ref{8c3,,repr()} function. In Python 2.1, the variable
@ref{f28,,sys.displayhook()} can be set to a callable object which will be called
instead of @ref{8c3,,repr()}. For example, you can set it to a special
pretty-printing function:

@example
>>> # Create a recursive data structure
... L = [1,2,3]
>>> L.append(L)
>>> L # Show Python's default output
[1, 2, 3, [...]]
>>> # Use pprint.pprint() as the display function
... import sys, pprint
>>> sys.displayhook = pprint.pprint
>>> L
[1, 2, 3,  <Recursion on list with id=135143996>]
>>>
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 217

@item PEP 217@footnote{https://www.python.org/dev/peps/pep-0217} - Display Hook for Interactive Use

由 Moshe Zadka 撰写并实现
@end table


@c ======================================================================

@node PEP 208 New Coercion Model,PEP 241 Metadata in Python Packages,PEP 217 Interactive Display Hook,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-208-new-coercion-model}@anchor{f29}
@subsection PEP 208: New Coercion Model


How numeric coercion is done at the C level was significantly modified.  This
will only affect the authors of C extensions to Python, allowing them more
flexibility in writing extension types that support numeric operations.

Extension types can now set the type flag @code{Py_TPFLAGS_CHECKTYPES} in their
@code{PyTypeObject} structure to indicate that they support the new coercion model.
In such extension types, the numeric slot functions can no longer assume that
they'll be passed two arguments of the same type; instead they may be passed two
arguments of differing types, and can then perform their own internal coercion.
If the slot function is passed a type it can't handle, it can indicate the
failure by returning a reference to the @code{Py_NotImplemented} singleton value.
The numeric functions of the other type will then be tried, and perhaps they can
handle the operation; if the other type also returns @code{Py_NotImplemented}, then
a @ref{1ff,,TypeError} will be raised.  Numeric methods written in Python can also
return @code{Py_NotImplemented}, causing the interpreter to act as if the method
did not exist (perhaps raising a @ref{1ff,,TypeError}, perhaps trying another
object's numeric methods).


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 208

@item PEP 208@footnote{https://www.python.org/dev/peps/pep-0208} - Reworking the Coercion Model

Written and implemented by Neil Schemenauer, heavily based upon earlier work by
Marc-André Lemburg.  Read this to understand the fine points of how numeric
operations will now be processed at the C level.
@end table


@c ======================================================================

@node PEP 241 Metadata in Python Packages,新增和改进的模块<4>,PEP 208 New Coercion Model,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 pep-241-metadata-in-python-packages}@anchor{f2a}
@subsection PEP 241: Metadata in Python Packages


A common complaint from Python users is that there's no single catalog of all
the Python modules in existence.  T. Middleton's Vaults of Parnassus at
@indicateurl{http://www.vex.net/parnassus/} are the largest catalog of Python modules, but
registering software at the Vaults is optional, and many people don't bother.

As a first small step toward fixing the problem, Python software packaged using
the Distutils @code{sdist} command will include a file named
@code{PKG-INFO} containing information about the package such as its name,
version, and author (metadata, in cataloguing terminology).  
@geindex Python 提高建议; PEP 241
PEP 241@footnote{https://www.python.org/dev/peps/pep-0241} contains
the full list of fields that can be present in the @code{PKG-INFO} file.  As
people began to package their software using Python 2.1, more and more packages
will include metadata, making it possible to build automated cataloguing systems
and experiment with them.  With the result experience, perhaps it'll be possible
to design a really good catalog and then build support for it into Python 2.2.
For example, the Distutils @code{sdist} and @code{bdist_*} commands
could support an @code{upload} option that would automatically upload your
package to a catalog server.

You can start creating packages containing @code{PKG-INFO} even if you're not
using Python 2.1, since a new release of the Distutils will be made for users of
earlier Python versions.  Version 1.0.2 of the Distutils includes the changes
described in 
@geindex Python 提高建议; PEP 241
PEP 241@footnote{https://www.python.org/dev/peps/pep-0241}, as well as various bugfixes and enhancements.  It will be
available from the Distutils SIG at @indicateurl{https://www.python.org/community/sigs/current/distutils-sig/}.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 241

@item PEP 241@footnote{https://www.python.org/dev/peps/pep-0241} - Metadata for Python Software Packages

由 A.M. Kuchling 撰写并实现。

@geindex Python 提高建议; PEP 243

@item PEP 243@footnote{https://www.python.org/dev/peps/pep-0243} - Module Repository Upload Mechanism

Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for
uploading  Python packages to a central server.
@end table


@c ======================================================================

@node 新增和改进的模块<4>,其他的改变和修正<4>,PEP 241 Metadata in Python Packages,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 new-and-improved-modules}@anchor{f2b}
@subsection 新增和改进的模块



@itemize *

@item 
Ka-Ping Yee contributed two new modules: @code{inspect.py}, a module for
getting information about live Python code, and @code{pydoc.py}, a module for
interactively converting docstrings to HTML or text.  As a bonus,
@code{Tools/scripts/pydoc}, which is now automatically installed, uses
@code{pydoc.py} to display documentation given a Python module, package, or
class name.  For example, @code{pydoc xml.dom} displays the following:

@example
Python Library Documentation: package xml.dom in xml

NAME
    xml.dom - W3C Document Object Model implementation for Python.

FILE
    /usr/local/lib/python2.1/xml/dom/__init__.pyc

DESCRIPTION
    The Python mapping of the Document Object Model is documented in the
    Python Library Reference in the section on the xml.dom package.

    This package contains the following modules:
      ...
@end example

@code{pydoc} also includes a Tk-based interactive help browser.   @code{pydoc}
quickly becomes addictive; try it out!

@item 
Two different modules for unit testing were added to the standard library.
The @ref{66,,doctest} module, contributed by Tim Peters, provides a testing
framework based on running embedded examples in docstrings and comparing the
results against the expected output.  PyUnit, contributed by Steve Purcell, is a
unit testing framework inspired by JUnit, which was in turn an adaptation of
Kent Beck's Smalltalk testing framework.  See @indicateurl{http://pyunit.sourceforge.net/} for
more information about PyUnit.

@item 
The @ref{36,,difflib} module contains a class, @code{SequenceMatcher}, which
compares two sequences and computes the changes required to transform one
sequence into the other.  For example, this module can be used to write a tool
similar to the Unix @code{diff} program, and in fact the sample program
@code{Tools/scripts/ndiff.py} demonstrates how to write such a script.

@item 
@ref{2d,,curses.panel}, a wrapper for the panel library, part of ncurses and of
SYSV curses, was contributed by Thomas Gellekum.  The panel library provides
windows with the additional feature of depth. Windows can be moved higher or
lower in the depth ordering, and the panel library figures out where panels
overlap and which sections are visible.

@item 
The PyXML package has gone through a few releases since Python 2.0, and Python
2.1 includes an updated version of the @ref{13c,,xml} package.  Some of the
noteworthy changes include support for Expat 1.2 and later versions, the ability
for Expat parsers to handle files in any encoding supported by Python, and
various bugfixes for SAX, DOM, and the @code{minidom} module.

@item 
Ping also contributed another hook for handling uncaught exceptions.
@ref{1ae,,sys.excepthook()} can be set to a callable object.  When an exception isn't
caught by any @ref{e3f,,try}...@ref{c19,,except} blocks, the exception will be
passed to @ref{1ae,,sys.excepthook()}, which can then do whatever it likes.  At the
Ninth Python Conference, Ping demonstrated an application for this hook:
printing an extended traceback that not only lists the stack frames, but also
lists the function arguments and the local variables for each frame.

@item 
Various functions in the @ref{10c,,time} module, such as @code{asctime()} and
@code{localtime()}, require a floating point argument containing the time in
seconds since the epoch.  The most common use of these functions is to work with
the current time, so the floating point argument has been made optional; when a
value isn't provided, the current time will be used.  For example, log file
entries usually need a string containing the current time; in Python 2.1,
@code{time.asctime()} can be used, instead of the lengthier
@code{time.asctime(time.localtime(time.time()))} that was previously required.

This change was proposed and implemented by Thomas Wouters.

@item 
The @ref{82,,ftplib} module now defaults to retrieving files in passive mode,
because passive mode is more likely to work from behind a firewall.  This
request came from the Debian bug tracking system, since other Debian packages
use @ref{82,,ftplib} to retrieve files and then don't work from behind a firewall.
It's deemed unlikely that this will cause problems for anyone, because Netscape
defaults to passive mode and few people complain, but if passive mode is
unsuitable for your application or network setup, call @code{set_pasv(0)} on
FTP objects to disable passive mode.

@item 
Support for raw socket access has been added to the @ref{ef,,socket} module,
contributed by Grant Edwards.

@item 
The @ref{d4,,pstats} module now contains a simple interactive statistics browser
for displaying timing profiles for Python programs, invoked when the module is
run as a script.  Contributed by  Eric S. Raymond.

@item 
A new implementation-dependent function, @code{sys._getframe([depth])}, has
been added to return a given frame object from the current call stack.
@ref{f2c,,sys._getframe()} returns the frame at the top of the call stack;  if the
optional integer argument @emph{depth} is supplied, the function returns the frame
that is @emph{depth} calls below the top of the stack.  For example,
@code{sys._getframe(1)} returns the caller's frame object.

This function is only present in CPython, not in Jython or the .NET
implementation.  Use it for debugging, and resist the temptation to put it into
production code.
@end itemize

@c ======================================================================

@node 其他的改变和修正<4>,致谢<7>,新增和改进的模块<4>,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 other-changes-and-fixes}@anchor{f2d}
@subsection 其他的改变和修正


There were relatively few smaller changes made in Python 2.1 due to the shorter
release cycle.  A search through the CVS change logs turns up 117 patches
applied, and 136 bugs fixed; both figures are likely to be underestimates.  Some
of the more notable changes are:


@itemize *

@item 
A specialized object allocator is now optionally available, that should be
faster than the system @code{malloc()} and have less memory overhead.  The
allocator uses C's @code{malloc()} function to get large pools of memory, and
then fulfills smaller memory requests from these pools.  It can be enabled by
providing the @code{--with-pymalloc} option to the @code{configure}
script; see @code{Objects/obmalloc.c} for the implementation details.

Authors of C extension modules should test their code with the object allocator
enabled, because some incorrect code may break, causing core dumps at runtime.
There are a bunch of memory allocation functions in Python's C API that have
previously been just aliases for the C library's @code{malloc()} and
@code{free()}, meaning that if you accidentally called mismatched functions, the
error wouldn't be noticeable.  When the object allocator is enabled, these
functions aren't aliases of @code{malloc()} and @code{free()} any more, and
calling the wrong function to free memory will get you a core dump.  For
example, if memory was allocated using @code{PyMem_New()}, it has to be freed
using @code{PyMem_Del()}, not @code{free()}.  A few modules included with Python
fell afoul of this and had to be fixed; doubtless there are more third-party
modules that will have the same problem.

The object allocator was contributed by Vladimir Marangozov.

@item 
The speed of line-oriented file I/O has been improved because people often
complain about its lack of speed, and because it's often been used as a naïve
benchmark.  The @ref{de,,readline()} method of file objects has therefore been
rewritten to be much faster.  The exact amount of the speedup will vary from
platform to platform depending on how slow the C library's @code{getc()} was, but
is around 66%, and potentially much faster on some particular operating systems.
Tim Peters did much of the benchmarking and coding for this change, motivated by
a discussion in comp.lang.python.

A new module and method for file objects was also added, contributed by Jeff
Epler. The new method, @code{xreadlines()}, is similar to the existing
@code{xrange()} built-in.  @code{xreadlines()} returns an opaque sequence object
that only supports being iterated over, reading a line on every iteration but
not reading the entire file into memory as the existing @code{readlines()} method
does. You'd use it like this:

@example
for line in sys.stdin.xreadlines():
    # ... do something for each line ...
    ...
@end example

For a fuller discussion of the line I/O changes, see the python-dev summary for
January 1--15, 2001 at @indicateurl{https://mail.python.org/pipermail/python-dev/2001-January/}.

@item 
A new method, @code{popitem()}, was added to dictionaries to enable
destructively iterating through the contents of a dictionary; this can be faster
for large dictionaries because there's no need to construct a list containing
all the keys or values. @code{D.popitem()} removes a random @code{(key, value)} pair
from the dictionary @code{D} and returns it as a 2-tuple.  This was implemented
mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary
patch by Moshe Zadka.

@item 
Modules can now control which names are imported when @code{from module import *}
is used, by defining an @code{__all__} attribute containing a list of names that
will be imported.  One common complaint is that if the module imports other
modules such as @ref{fd,,sys} or @ref{f6,,string}, @code{from module import *} will add
them to the importing module's namespace.  To fix this, simply list the public
names in @code{__all__}:

@example
# List public names
__all__ = ['Database', 'open']
@end example

A stricter version of this patch was first suggested and implemented by Ben
Wolfson, but after some python-dev discussion, a weaker final version was
checked in.

@item 
Applying @ref{8c3,,repr()} to strings previously used octal escapes for
non-printable characters; for example, a newline was @code{'\012'}.  This was a
vestigial trace of Python's C ancestry, but today octal is of very little
practical use.  Ka-Ping Yee suggested using hex escapes instead of octal ones,
and using the @code{\n}, @code{\t}, @code{\r} escapes for the appropriate characters,
and implemented this new formatting.

@item 
Syntax errors detected at compile-time can now raise exceptions containing the
filename and line number of the error, a pleasant side effect of the compiler
reorganization done by Jeremy Hylton.

@item 
C extensions which import other modules have been changed to use
@code{PyImport_ImportModule()}, which means that they will use any import hooks
that have been installed.  This is also encouraged for third-party extensions
that need to import some other module from C code.

@item 
The size of the Unicode character database was shrunk by another 340K thanks
to Fredrik Lundh.

@item 
Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by
Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7  (by Billy G.
Allie).
@end itemize

And there's the usual list of minor bugfixes, minor memory leaks, docstring
edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for
the full details if you want them.

@c ======================================================================

@node 致谢<7>,,其他的改变和修正<4>,Python 2 1 有什么新变化
@anchor{whatsnew/2 1 acknowledgements}@anchor{f2e}
@subsection 致谢


作者感谢以下人员对本文的各种草案提出建议： Graeme Cross, David Goodger, Jay Graves, Michael Hudson, Marc-André Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.

@node Python 2 0 有什么新变化,更新日志,Python 2 1 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/2 0 doc}@anchor{f2f}@anchor{whatsnew/2 0 what-s-new-in-python-2-0}@anchor{f30}
@section Python 2.0 有什么新变化


@*作者: 
A.M. Kuchling 和 Moshe Zadka


@c $Id: whatsnew20.tex 50964 2006-07-30 03:03:43Z fred.drake $

@menu
* 概述: 概述<3>. 
* What About Python 1.6?: What About Python 1 6?. 
* 新开发流程:: 
* Unicode: Unicode<2>. 
* 列表推导式:: 
* Augmented Assignment:: 
* 字符串的方法:: 
* Garbage Collection of Cycles:: 
* 其他核心变化:: 
* 移植 Python 2.0: 移植 Python 2 0. 
* 扩展/嵌入更改:: 
* Distutils：使模块易于安装:: 
* XML 模块:: 
* 模块更改:: 
* 新增模块: 新增模块<8>. 
* IDLE 改进:: 
* 删除和弃用的模块:: 
* 致谢: 致谢<8>. 

@end menu

@node 概述<3>,What About Python 1 6?,,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 introduction}@anchor{f31}
@subsection 概述


A new release of Python, version 2.0, was released on October 16, 2000. This
article covers the exciting new features in 2.0, highlights some other useful
changes, and points out a few incompatible changes that may require rewriting
code.

Python's development never completely stops between releases, and a steady flow
of bug fixes and improvements are always being submitted. A host of minor fixes,
a few optimizations, additional docstrings, and better error messages went into
2.0; to list them all would be impossible, but they're certainly significant.
Consult the publicly-available CVS logs if you want to see the full list.  This
progress is due to the five developers working for  PythonLabs are now getting
paid to spend their days fixing bugs, and also due to the improved communication
resulting  from moving to SourceForge.

@c ======================================================================

@node What About Python 1 6?,新开发流程,概述<3>,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 what-about-python-1-6}@anchor{f32}
@subsection What About Python 1.6?


Python 1.6 can be thought of as the Contractual Obligations Python release.
After the core development team left CNRI in May 2000, CNRI requested that a 1.6
release be created, containing all the work on Python that had been performed at
CNRI.  Python 1.6 therefore represents the state of the CVS tree as of May 2000,
with the most significant new feature being Unicode support.  Development
continued after May, of course, so the 1.6 tree received a few fixes to ensure
that it's forward-compatible with Python 2.0.  1.6 is therefore part of Python's
evolution, and not a side branch.

So, should you take much interest in Python 1.6?  Probably not.  The 1.6final
and 2.0beta1 releases were made on the same day (September 5, 2000), the plan
being to finalize Python 2.0 within a month or so.  If you have applications to
maintain, there seems little point in breaking things by moving to 1.6, fixing
them, and then having another round of breakage within a month by moving to 2.0;
you're better off just going straight to 2.0.  Most of the really interesting
features described in this document are only in 2.0, because a lot of work was
done between May and September.

@c ======================================================================

@node 新开发流程,Unicode<2>,What About Python 1 6?,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 new-development-process}@anchor{f33}
@subsection 新开发流程


The most important change in Python 2.0 may not be to the code at all, but to
how Python is developed: in May 2000 the Python developers began using the tools
made available by SourceForge for storing  source code, tracking bug reports,
and managing the queue of patch submissions.  To report bugs or submit patches
for Python 2.0, use the bug tracking and patch manager tools available from
Python's project page, located at @indicateurl{https://sourceforge.net/projects/python/}.

The most important of the services now hosted at SourceForge is the Python CVS
tree, the version-controlled repository containing the source code for Python.
Previously, there were roughly 7 or so people who had write access to the CVS
tree, and all patches had to be inspected and checked in by one of the people on
this short list. Obviously, this wasn't very scalable.  By moving the CVS tree
to SourceForge, it became possible to grant write access to more people; as of
September 2000 there were 27 people able to check in changes, a fourfold
increase.  This makes possible large-scale changes that wouldn't be attempted if
they'd have to be filtered through the small group of core developers.  For
example, one day Peter Schneider-Kamp took it into his head to drop K&R C
compatibility and convert the C source for Python to ANSI C. After getting
approval on the python-dev mailing list, he launched into a flurry of checkins
that lasted about a week, other developers joined in to help, and the job was
done.  If there were only 5 people with write access, probably that task would
have been viewed as "nice, but not worth the time and effort needed" and it
would never have gotten done.

The shift to using SourceForge's services has resulted in a remarkable increase
in the speed of development.  Patches now get submitted, commented on, revised
by people other than the original submitter, and bounced back and forth between
people until the patch is deemed worth checking in.  Bugs are tracked in one
central location and can be assigned to a specific person for fixing, and we can
count the number of open bugs to measure progress.  This didn't come without a
cost: developers now have more e-mail to deal with, more mailing lists to
follow, and special tools had to be written for the new environment. For
example, SourceForge sends default patch and bug notification e-mail messages
that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that
sends more useful messages.

The ease of adding code caused a few initial growing pains, such as code was
checked in before it was ready or without getting clear agreement from the
developer group.  The approval process that has emerged is somewhat similar to
that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch;
+1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is
mostly indifferent to the change, though with a slight positive or negative
slant.  The most significant change from the Apache model is that the voting is
essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For
Life status, know what the general opinion is. He can still ignore the result of
a vote, and approve or reject a change even if the community disagrees with him.

Producing an actual patch is the last step in adding a new feature, and is
usually easy compared to the earlier task of coming up with a good design.
Discussions of new features can often explode into lengthy mailing list threads,
making the discussion hard to follow, and no one can read every posting to
python-dev.  Therefore, a relatively formal process has been set up to write
Python Enhancement Proposals (PEPs), modelled on the Internet RFC process.  PEPs
are draft documents that describe a proposed new feature, and are continually
revised until the community reaches a consensus, either accepting or rejecting
the proposal.  Quoting from the introduction to 
@geindex Python 提高建议; PEP 1
PEP 1@footnote{https://www.python.org/dev/peps/pep-0001}, "PEP Purpose and
Guidelines":

@quotation

PEP stands for Python Enhancement Proposal.  A PEP is a design document
providing information to the Python community, or describing a new feature for
Python.  The PEP should provide a concise technical specification of the feature
and a rationale for the feature.

We intend PEPs to be the primary mechanisms for proposing new features, for
collecting community input on an issue, and for documenting the design decisions
that have gone into Python.  The PEP author is responsible for building
consensus within the community and documenting dissenting opinions.
@end quotation

Read the rest of 
@geindex Python 提高建议; PEP 1
PEP 1@footnote{https://www.python.org/dev/peps/pep-0001} for the details of the PEP editorial process, style, and
format.  PEPs are kept in the Python CVS tree on SourceForge, though they're not
part of the Python 2.0 distribution, and are also available in HTML form from
@indicateurl{https://www.python.org/dev/peps/}.  As of September 2000, there are 25 PEPS, ranging
from 
@geindex Python 提高建议; PEP 201
PEP 201@footnote{https://www.python.org/dev/peps/pep-0201}, "Lockstep Iteration", to PEP 225, "Elementwise/Objectwise
Operators".

@c ======================================================================

@node Unicode<2>,列表推导式,新开发流程,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 unicode}@anchor{f34}
@subsection Unicode


The largest new feature in Python 2.0 is a new fundamental data type: Unicode
strings.  Unicode uses 16-bit numbers to represent characters instead of the
8-bit number used by ASCII, meaning that 65,536 distinct characters can be
supported.

The final interface for Unicode support was arrived at through countless
often-stormy discussions on the python-dev mailing list, and mostly implemented by
Marc-André Lemburg, based on a Unicode string type implementation by Fredrik
Lundh.  A detailed explanation of the interface was written up as 
@geindex Python 提高建议; PEP 100
PEP 100@footnote{https://www.python.org/dev/peps/pep-0100},
"Python Unicode Integration". This article will simply cover the most
significant points about the Unicode interfaces.

In Python source code, Unicode strings are written as @code{u"string"}.  Arbitrary
Unicode characters can be written using a new escape sequence, @code{\uHHHH}, where
@emph{HHHH} is a 4-digit hexadecimal number from 0000 to FFFF.  The existing
@code{\xHHHH} escape sequence can also be used, and octal escapes can be used for
characters up to U+01FF, which is represented by @code{\777}.

Unicode strings, just like regular strings, are an immutable sequence type.
They can be indexed and sliced, but not modified in place. Unicode strings have
an @code{encode( [encoding] )} method that returns an 8-bit string in the desired
encoding.  Encodings are named by strings, such as @code{'ascii'}, @code{'utf-8'},
@code{'iso-8859-1'}, or whatever.  A codec API is defined for implementing and
registering new encodings that are then available throughout a Python program.
If an encoding isn't specified, the default encoding is usually 7-bit ASCII,
though it can be changed for your Python installation by calling the
@code{sys.setdefaultencoding(encoding)} function in a customized version of
@code{site.py}.

Combining 8-bit and Unicode strings always coerces to Unicode, using the default
ASCII encoding; the result of @code{'a' + u'bc'} is @code{u'abc'}.

New built-in functions have been added, and existing built-ins modified to
support Unicode:


@itemize *

@item 
@code{unichr(ch)} returns a Unicode string 1 character long, containing the
character @emph{ch}.

@item 
@code{ord(u)}, where @emph{u} is a 1-character regular or Unicode string, returns the
number of the character as an integer.

@item 
@code{unicode(string [, encoding]  [, errors] )} creates a Unicode string
from an 8-bit string.  @code{encoding} is a string naming the encoding to use. The
@code{errors} parameter specifies the treatment of characters that are invalid for
the current encoding; passing @code{'strict'} as the value causes an exception to
be raised on any encoding error, while @code{'ignore'} causes errors to be silently
ignored and @code{'replace'} uses U+FFFD, the official replacement character, in
case of any problems.

@item 
The @code{exec} statement, and various built-ins such as @code{eval()},
@code{getattr()}, and @code{setattr()} will also accept Unicode strings as well as
regular strings.  (It's possible that the process of fixing this missed some
built-ins; if you find a built-in function that accepts strings but doesn't
accept Unicode strings at all, please report it as a bug.)
@end itemize

A new module, @ref{123,,unicodedata}, provides an interface to Unicode character
properties.  For example, @code{unicodedata.category(u'A')} returns the 2-character
string 'Lu', the 'L' denoting it's a letter, and 'u' meaning that it's
uppercase. @code{unicodedata.bidirectional(u'\u0660')} returns 'AN', meaning that
U+0660 is an Arabic number.

The @ref{1b,,codecs} module contains functions to look up existing encodings and
register new ones.  Unless you want to implement a new encoding, you'll most
often use the @code{codecs.lookup(encoding)} function, which returns a
4-element tuple: @code{(encode_func, decode_func, stream_reader, stream_writer)}.


@itemize *

@item 
@emph{encode_func} is a function that takes a Unicode string, and returns a 2-tuple
@code{(string, length)}.  @emph{string} is an 8-bit string containing a portion (perhaps
all) of the Unicode string converted into the given encoding, and @emph{length} tells
you how much of the Unicode string was converted.

@item 
@emph{decode_func} is the opposite of @emph{encode_func}, taking an 8-bit string and
returning a 2-tuple @code{(ustring, length)}, consisting of the resulting Unicode
string @emph{ustring} and the integer @emph{length} telling how much of the 8-bit string
was consumed.

@item 
@emph{stream_reader} is a class that supports decoding input from a stream.
@emph{stream_reader(file_obj)} returns an object that supports the @code{read()},
@ref{de,,readline()}, and @code{readlines()} methods.  These methods will all
translate from the given encoding and return Unicode strings.

@item 
@emph{stream_writer}, similarly, is a class that supports encoding output to a
stream.  @emph{stream_writer(file_obj)} returns an object that supports the
@code{write()} and @code{writelines()} methods.  These methods expect Unicode
strings, translating them to the given encoding on output.
@end itemize

For example, the following code writes a Unicode string into a file,  encoding
it as UTF-8:

@example
import codecs

unistr = u'\u0660\u2000ab ...'

(UTF8_encode, UTF8_decode,
 UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')

output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
output.write( unistr )
output.close()
@end example

The following code would then read UTF-8 input from the file:

@example
input = UTF8_streamreader( open( '/tmp/output', 'rb') )
print repr(input.read())
input.close()
@end example

Unicode-aware regular expressions are available through the @ref{dd,,re} module,
which has a new underlying implementation called SRE written by Fredrik Lundh of
Secret Labs AB.

A @code{-U} command line option was added which causes the Python compiler to
interpret all string literals as Unicode string literals. This is intended to be
used in testing and future-proofing your Python code, since some future version
of Python may drop support for 8-bit strings and provide only Unicode strings.

@c ======================================================================

@node 列表推导式,Augmented Assignment,Unicode<2>,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 list-comprehensions}@anchor{f35}
@subsection 列表推导式


Lists are a workhorse data type in Python, and many programs manipulate a list
at some point.  Two common operations on lists are to loop over them, and either
pick out the elements that meet a certain criterion, or apply some function to
each element.  For example, given a list of strings, you might want to pull out
all the strings containing a given substring, or strip off trailing whitespace
from each line.

The existing @ref{cff,,map()} and @ref{d00,,filter()} functions can be used for this
purpose, but they require a function as one of their arguments.  This is fine if
there's an existing built-in function that can be passed directly, but if there
isn't, you have to create a little function to do the required work, and
Python's scoping rules make the result ugly if the little function needs
additional information.  Take the first example in the previous paragraph,
finding all the strings in the list containing a given substring.  You could
write the following to do it:

@example
# Given the list L, make a list of all strings
# containing the substring S.
sublist = filter( lambda s, substring=S:
                     string.find(s, substring) != -1,
                  L)
@end example

Because of Python's scoping rules, a default argument is used so that the
anonymous function created by the @ref{d01,,lambda} expression knows what
substring is being searched for.  List comprehensions make this cleaner:

@example
sublist = [ s for s in L if string.find(s, S) != -1 ]
@end example

List comprehensions have the form:

@example
[ expression for expr in sequence1
             for expr2 in sequence2 ...
             for exprN in sequenceN
             if condition ]
@end example

The @code{for}...@code{in} clauses contain the sequences to be
iterated over.  The sequences do not have to be the same length, because they
are @emph{not} iterated over in parallel, but from left to right; this is explained
more clearly in the following paragraphs.  The elements of the generated list
will be the successive values of @emph{expression}.  The final @code{if} clause
is optional; if present, @emph{expression} is only evaluated and added to the result
if @emph{condition} is true.

To make the semantics very clear, a list comprehension is equivalent to the
following Python code:

@example
for expr1 in sequence1:
    for expr2 in sequence2:
    ...
        for exprN in sequenceN:
             if (condition):
                  # Append the value of
                  # the expression to the
                  # resulting list.
@end example

This means that when there are multiple @code{for}...@code{in}
clauses, the resulting list will be equal to the product of the lengths of all
the sequences.  If you have two lists of length 3, the output list is 9 elements
long:

@example
seq1 = 'abc'
seq2 = (1,2,3)
>>> [ (x,y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
('c', 2), ('c', 3)]
@end example

To avoid introducing an ambiguity into Python's grammar, if @emph{expression} is
creating a tuple, it must be surrounded with parentheses.  The first list
comprehension below is a syntax error, while the second one is correct:

@example
# Syntax error
[ x,y for x in seq1 for y in seq2]
# Correct
[ (x,y) for x in seq1 for y in seq2]
@end example

The idea of list comprehensions originally comes from the functional programming
language Haskell (@indicateurl{https://www.haskell.org}).  Greg Ewing argued most effectively
for adding them to Python and wrote the initial list comprehension patch, which
was then discussed for a seemingly endless time on the python-dev mailing list
and kept up-to-date by Skip Montanaro.

@c ======================================================================

@node Augmented Assignment,字符串的方法,列表推导式,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 augmented-assignment}@anchor{f36}
@subsection Augmented Assignment


Augmented assignment operators, another long-requested feature, have been added
to Python 2.0.  Augmented assignment operators include @code{+=}, @code{-=}, @code{*=},
and so forth.  For example, the statement @code{a += 2} increments the value of the
variable  @code{a} by 2, equivalent to the slightly lengthier @code{a = a + 2}.

The full list of supported assignment operators is @code{+=}, @code{-=}, @code{*=},
@code{/=}, @code{%=}, @code{**=}, @code{&=}, @code{|=}, @code{^=}, @code{>>=}, and @code{<<=}.  Python
classes can override the augmented assignment operators by defining methods
named @ref{f37,,__iadd__()}, @ref{f38,,__isub__()}, etc.  For example, the following
@code{Number} class stores a number and supports using += to create a new
instance with an incremented value.

@c The empty groups below prevent conversion to guillemets.

@example
class Number:
    def __init__(self, value):
        self.value = value
    def __iadd__(self, increment):
        return Number( self.value + increment)

n = Number(5)
n += 3
print n.value
@end example

The @ref{f37,,__iadd__()} special method is called with the value of the increment,
and should return a new instance with an appropriately modified value; this
return value is bound as the new value of the variable on the left-hand side.

Augmented assignment operators were first introduced in the C programming
language, and most C-derived languages, such as @code{awk}, C++, Java, Perl,
and PHP also support them.  The augmented assignment patch was implemented by
Thomas Wouters.

@c ======================================================================

@node 字符串的方法,Garbage Collection of Cycles,Augmented Assignment,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 string-methods}@anchor{f39}
@subsection 字符串的方法


Until now string-manipulation functionality was in the @ref{f6,,string} module,
which was usually a front-end for the @code{strop} module written in C.  The
addition of Unicode posed a difficulty for the @code{strop} module, because the
functions would all need to be rewritten in order to accept either 8-bit or
Unicode strings.  For functions such as @code{string.replace()}, which takes 3
string arguments, that means eight possible permutations, and correspondingly
complicated code.

Instead, Python 2.0 pushes the problem onto the string type, making string
manipulation functionality available through methods on both 8-bit strings and
Unicode strings.

@example
>>> 'andrew'.capitalize()
'Andrew'
>>> 'hostname'.replace('os', 'linux')
'hlinuxtname'
>>> 'moshe'.find('sh')
2
@end example

One thing that hasn't changed, a noteworthy April Fools' joke notwithstanding,
is that Python strings are immutable. Thus, the string methods return new
strings, and do not modify the string on which they operate.

The old @ref{f6,,string} module is still around for backwards compatibility, but it
mostly acts as a front-end to the new string methods.

Two methods which have no parallel in pre-2.0 versions, although they did exist
in JPython for quite some time, are @code{startswith()} and @code{endswith()}.
@code{s.startswith(t)} is equivalent to @code{s[:len(t)] == t}, while
@code{s.endswith(t)} is equivalent to @code{s[-len(t):] == t}.

One other method which deserves special mention is @code{join()}.  The
@code{join()} method of a string receives one parameter, a sequence of strings,
and is equivalent to the @code{string.join()} function from the old @ref{f6,,string}
module, with the arguments reversed. In other words, @code{s.join(seq)} is
equivalent to the old @code{string.join(seq, s)}.

@c ======================================================================

@node Garbage Collection of Cycles,其他核心变化,字符串的方法,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 garbage-collection-of-cycles}@anchor{f3a}
@subsection Garbage Collection of Cycles


The C implementation of Python uses reference counting to implement garbage
collection.  Every Python object maintains a count of the number of references
pointing to itself, and adjusts the count as references are created or
destroyed.  Once the reference count reaches zero, the object is no longer
accessible, since you need to have a reference to an object to access it, and if
the count is zero, no references exist any longer.

Reference counting has some pleasant properties: it's easy to understand and
implement, and the resulting implementation is portable, fairly fast, and reacts
well with other libraries that implement their own memory handling schemes.  The
major problem with reference counting is that it sometimes doesn't realise that
objects are no longer accessible, resulting in a memory leak.  This happens when
there are cycles of references.

Consider the simplest possible cycle,  a class instance which has a reference to
itself:

@example
instance = SomeClass()
instance.myself = instance
@end example

After the above two lines of code have been executed, the reference count of
@code{instance} is 2; one reference is from the variable named @code{'instance'}, and
the other is from the @code{myself} attribute of the instance.

If the next line of code is @code{del instance}, what happens?  The reference count
of @code{instance} is decreased by 1, so it has a reference count of 1; the
reference in the @code{myself} attribute still exists.  Yet the instance is no
longer accessible through Python code, and it could be deleted.  Several objects
can participate in a cycle if they have references to each other, causing all of
the objects to be leaked.

Python 2.0 fixes this problem by periodically executing a cycle detection
algorithm which looks for inaccessible cycles and deletes the objects involved.
A new @ref{84,,gc} module provides functions to perform a garbage collection,
obtain debugging statistics, and tuning the collector's parameters.

Running the cycle detection algorithm takes some time, and therefore will result
in some additional overhead.  It is hoped that after we've gotten experience
with the cycle collection from using 2.0, Python 2.1 will be able to minimize
the overhead with careful tuning.  It's not yet obvious how much performance is
lost, because benchmarking this is tricky and depends crucially on how often the
program creates and destroys objects.  The detection of cycles can be disabled
when Python is compiled, if you can't afford even a tiny speed penalty or
suspect that the cycle collection is buggy, by specifying the
@code{--without-cycle-gc} switch when running the @code{configure}
script.

Several people tackled this problem and contributed to a solution.  An early
implementation of the cycle detection approach was written by Toby Kelsey.  The
current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and
Guido van Rossum and Neil Schemenauer wrote two different implementations, which
were later integrated by Neil.  Lots of other people offered suggestions along
the way; the March 2000 archives of the python-dev mailing list contain most of
the relevant discussion, especially in the threads titled "Reference cycle
collection for Python" and "Finalization again".

@c ======================================================================

@node 其他核心变化,移植 Python 2 0,Garbage Collection of Cycles,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 other-core-changes}@anchor{f3b}
@subsection 其他核心变化


Various minor changes have been made to Python's syntax and built-in functions.
None of the changes are very far-reaching, but they're handy conveniences.

@menu
* 细微的语言特性修改:: 
* 对于内置函数的修改:: 

@end menu

@node 细微的语言特性修改,对于内置函数的修改,,其他核心变化
@anchor{whatsnew/2 0 minor-language-changes}@anchor{f3c}
@subsubsection 细微的语言特性修改


A new syntax makes it more convenient to call a given function with a tuple of
arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
you'd use the @code{apply()} built-in function: @code{apply(f, args, kw)} calls the
function @code{f()} with the argument tuple @emph{args} and the keyword arguments in
the dictionary @emph{kw}.  @code{apply()}  is the same in 2.0, but thanks to a patch
from Greg Ewing, @code{f(*args, **kw)} is a shorter and clearer way to achieve the
same effect.  This syntax is symmetrical with the syntax for defining
functions:

@example
def f(*args, **kw):
    # args is a tuple of positional args,
    # kw is a dictionary of keyword args
    ...
@end example

The @code{print} statement can now have its output directed to a file-like
object by following the @code{print} with  @code{>> file}, similar to the
redirection operator in Unix shells. Previously you'd either have to use the
@code{write()} method of the file-like object, which lacks the convenience and
simplicity of @code{print}, or you could assign a new value to
@code{sys.stdout} and then restore the old value.  For sending output to standard
error, it's much easier to write this:

@example
print >> sys.stderr, "Warning: action field not supplied"
@end example

Modules can now be renamed on importing them, using the syntax @code{import module
as name} or @code{from module import name as othername}.  The patch was submitted
by Thomas Wouters.

A new format style is available when using the @code{%} operator; '%r' will insert
the @ref{8c3,,repr()} of its argument.  This was also added from symmetry
considerations, this time for symmetry with the existing '%s' format style,
which inserts the @ref{206,,str()} of its argument.  For example, @code{'%r %s' % ('abc',
'abc')} returns a string containing @code{'abc' abc}.

Previously there was no way to implement a class that overrode Python's built-in
@ref{179,,in} operator and implemented a custom version.  @code{obj in seq} returns
true if @emph{obj} is present in the sequence @emph{seq}; Python computes this by simply
trying every index of the sequence until either @emph{obj} is found or an
@ref{f3d,,IndexError} is encountered.  Moshe Zadka contributed a patch which adds a
@ref{df6,,__contains__()} magic method for providing a custom implementation for
@code{in}. Additionally, new built-in objects written in C can define what
@code{in} means for them via a new slot in the sequence protocol.

Earlier versions of Python used a recursive algorithm for deleting objects.
Deeply nested data structures could cause the interpreter to fill up the C stack
and crash; Christian Tismer rewrote the deletion logic to fix this problem.  On
a related note, comparing recursive objects recursed infinitely and crashed;
Jeremy Hylton rewrote the code to no longer crash, producing a useful result
instead.  For example, after this code:

@example
a = []
b = []
a.append(a)
b.append(b)
@end example

The comparison @code{a==b} returns true, because the two recursive data structures
are isomorphic. See the thread "trashcan and PR#7" in the April 2000 archives of
the python-dev mailing list for the discussion leading up to this
implementation, and some useful relevant links.    Note that comparisons can now
also raise exceptions. In earlier versions of Python, a comparison operation
such as @code{cmp(a,b)} would always produce an answer, even if a user-defined
@code{__cmp__()} method encountered an error, since the resulting exception would
simply be silently swallowed.

@c Starting URL:

@c https://www.python.org/pipermail/python-dev/2000-April/004834.html

Work has been done on porting Python to 64-bit Windows on the Itanium processor,
mostly by Trent Mick of ActiveState.  (Confusingly, @code{sys.platform} is still
@code{'win32'} on Win64 because it seems that for ease of porting, MS Visual C++
treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the
Python CE page at @indicateurl{http://pythonce.sourceforge.net/} for more information.

Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0.
Dynamic loading works, if you specify "configure --with-dyld --with-suffix=.x".
Consult the README in the Python source distribution for more instructions.

An attempt has been made to alleviate one of Python's warts, the often-confusing
@ref{e48,,NameError} exception when code refers to a local variable before the
variable has been assigned a value.  For example, the following code raises an
exception on the @code{print} statement in both 1.5.2 and 2.0; in 1.5.2 a
@ref{e48,,NameError} exception is raised, while 2.0 raises a new
@ref{f3e,,UnboundLocalError} exception. @ref{f3e,,UnboundLocalError} is a subclass of
@ref{e48,,NameError}, so any existing code that expects @ref{e48,,NameError} to be
raised should still work.

@example
def f():
    print "i=",i
    i = i + 1
f()
@end example

Two new exceptions, @ref{f3f,,TabError} and @ref{f40,,IndentationError}, have been
introduced.  They're both subclasses of @ref{562,,SyntaxError}, and are raised when
Python code is found to be improperly indented.

@node 对于内置函数的修改,,细微的语言特性修改,其他核心变化
@anchor{whatsnew/2 0 changes-to-built-in-functions}@anchor{f41}
@subsubsection 对于内置函数的修改


A new built-in, @code{zip(seq1, seq2, ...)}, has been added.  @ref{d04,,zip()}
returns a list of tuples where each tuple contains the i-th element from each of
the argument sequences.  The difference between @ref{d04,,zip()} and @code{map(None,
seq1, seq2)} is that @ref{cff,,map()} pads the sequences with @code{None} if the
sequences aren't all of the same length, while @ref{d04,,zip()} truncates the
returned list to the length of the shortest argument sequence.

The @ref{205,,int()} and @code{long()} functions now accept an optional "base"
parameter when the first argument is a string. @code{int('123', 10)} returns 123,
while @code{int('123', 16)} returns 291.  @code{int(123, 16)} raises a
@ref{1ff,,TypeError} exception with the message "can't convert non-string with
explicit base".

A new variable holding more detailed version information has been added to the
@ref{fd,,sys} module.  @code{sys.version_info} is a tuple @code{(major, minor, micro,
level, serial)} For example, in a hypothetical 2.0.1beta1, @code{sys.version_info}
would be @code{(2, 0, 1, 'beta', 1)}. @emph{level} is a string such as @code{"alpha"},
@code{"beta"}, or @code{"final"} for a final release.

Dictionaries have an odd new method, @code{setdefault(key, default)}, which
behaves similarly to the existing @code{get()} method.  However, if the key is
missing, @code{setdefault()} both returns the value of @emph{default} as @code{get()}
would do, and also inserts it into the dictionary as the value for @emph{key}.  Thus,
the following lines of code:

@example
if dict.has_key( key ): return dict[key]
else:
    dict[key] = []
    return dict[key]
@end example

can be reduced to a single @code{return dict.setdefault(key, [])} statement.

The interpreter sets a maximum recursion depth in order to catch runaway
recursion before filling the C stack and causing a core dump or GPF..
Previously this limit was fixed when you compiled Python, but in 2.0 the maximum
recursion depth can be read and modified using @ref{f42,,sys.getrecursionlimit()} and
@ref{f43,,sys.setrecursionlimit()}. The default value is 1000, and a rough maximum
value for a given platform can be found by running a new script,
@code{Misc/find_recursionlimit.py}.

@c ======================================================================

@node 移植 Python 2 0,扩展/嵌入更改,其他核心变化,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 porting-to-2-0}@anchor{f44}
@subsection 移植 Python 2.0


New Python releases try hard to be compatible with previous releases, and the
record has been pretty good.  However, some changes are considered useful
enough, usually because they fix initial design decisions that turned out to be
actively mistaken, that breaking backward compatibility can't always be avoided.
This section lists the changes in Python 2.0 that may cause old Python code to
break.

The change which will probably break the most code is tightening up the
arguments accepted by some methods.  Some methods would take multiple arguments
and treat them as a tuple, particularly various list methods such as
@code{append()} and @code{insert()}. In earlier versions of Python, if @code{L} is
a list, @code{L.append( 1,2 )} appends the tuple @code{(1,2)} to the list.  In Python
2.0 this causes a @ref{1ff,,TypeError} exception to be raised, with the message:
'append requires exactly 1 argument; 2 given'.  The fix is to simply add an
extra set of parentheses to pass both values as a tuple:  @code{L.append( (1,2) )}.

The earlier versions of these methods were more forgiving because they used an
old function in Python's C interface to parse their arguments; 2.0 modernizes
them to use @code{PyArg_ParseTuple()}, the current argument parsing function,
which provides more helpful error messages and treats multi-argument calls as
errors.  If you absolutely must use 2.0 but can't fix your code, you can edit
@code{Objects/listobject.c} and define the preprocessor symbol
@code{NO_STRICT_LIST_APPEND} to preserve the old behaviour; this isn't recommended.

Some of the functions in the @ref{ef,,socket} module are still forgiving in this
way.  For example, @code{socket.connect( ('hostname', 25) )()} is the correct
form, passing a tuple representing an IP address, but @code{socket.connect(
'hostname', 25 )()} also works. @code{socket.connect_ex()} and @code{socket.bind()}
are similarly easy-going.  2.0alpha1 tightened these functions up, but because
the documentation actually used the erroneous multiple argument form, many
people wrote code which would break with the stricter checking.  GvR backed out
the changes in the face of public reaction, so for the @ref{ef,,socket} module, the
documentation was fixed and the multiple argument form is simply marked as
deprecated; it @emph{will} be tightened up again in a future Python version.

The @code{\x} escape in string literals now takes exactly 2 hex digits.  Previously
it would consume all the hex digits following the 'x' and take the lowest 8 bits
of the result, so @code{\x123456} was equivalent to @code{\x56}.

The @ref{4aa,,AttributeError} and @ref{e48,,NameError} exceptions have a more friendly
error message, whose text will be something like @code{'Spam' instance has no
attribute 'eggs'} or @code{name 'eggs' is not defined}.  Previously the error
message was just the missing attribute name @code{eggs}, and code written to take
advantage of this fact will break in 2.0.

Some work has been done to make integers and long integers a bit more
interchangeable.  In 1.5.2, large-file support was added for Solaris, to allow
reading files larger than 2 GiB; this made the @code{tell()} method of file
objects return a long integer instead of a regular integer.  Some code would
subtract two file offsets and attempt to use the result to multiply a sequence
or slice a string, but this raised a @ref{1ff,,TypeError}.  In 2.0, long integers
can be used to multiply or slice a sequence, and it'll behave as you'd
intuitively expect it to; @code{3L * 'abc'} produces 'abcabcabc', and
@code{(0,1,2,3)[2L:4L]} produces (2,3). Long integers can also be used in various
contexts where previously only integers were accepted, such as in the
@code{seek()} method of file objects, and in the formats supported by the @code{%}
operator (@code{%d}, @code{%i}, @code{%x}, etc.).  For example, @code{"%d" % 2L**64} will
produce the string @code{18446744073709551616}.

The subtlest long integer change of all is that the @ref{206,,str()} of a long
integer no longer has a trailing 'L' character, though @ref{8c3,,repr()} still
includes it.  The 'L' annoyed many people who wanted to print long integers that
looked just like regular integers, since they had to go out of their way to chop
off the character.  This is no longer a problem in 2.0, but code which does
@code{str(longval)[:-1]} and assumes the 'L' is there, will now lose the final
digit.

Taking the @ref{8c3,,repr()} of a float now uses a different formatting precision
than @ref{206,,str()}.  @ref{8c3,,repr()} uses @code{%.17g} format string for C's
@code{sprintf()}, while @ref{206,,str()} uses @code{%.12g} as before.  The effect is that
@ref{8c3,,repr()} may occasionally show more decimal places than  @ref{206,,str()}, for
certain numbers.  For example, the number 8.1 can't be represented exactly in
binary, so @code{repr(8.1)} is @code{'8.0999999999999996'}, while str(8.1) is
@code{'8.1'}.

The @code{-X} command-line option, which turned all standard exceptions into
strings instead of classes, has been removed; the standard exceptions will now
always be classes.  The @code{exceptions} module containing the standard
exceptions was translated from Python to a built-in C module, written by Barry
Warsaw and Fredrik Lundh.

@c Commented out for now -- I don't think anyone will care.
@c The pattern and match objects provided by SRE are C types, not Python
@c class instances as in 1.5.  This means you can no longer inherit from
@c \class{RegexObject} or \class{MatchObject}, but that shouldn't be much
@c of a problem since no one should have been doing that in the first
@c place.

@c ======================================================================

@node 扩展/嵌入更改,Distutils：使模块易于安装,移植 Python 2 0,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 extending-embedding-changes}@anchor{f45}
@subsection 扩展/嵌入更改


Some of the changes are under the covers, and will only be apparent to people
writing C extension modules or embedding a Python interpreter in a larger
application.  If you aren't dealing with Python's C API, you can safely skip
this section.

The version number of the Python C API was incremented, so C extensions compiled
for 1.5.2 must be recompiled in order to work with 2.0.  On Windows, it's not
possible for Python 2.0 to import a third party extension built for Python 1.5.x
due to how Windows DLLs work, so Python will raise an exception and the import
will fail.

Users of Jim Fulton's ExtensionClass module will be pleased to find out that
hooks have been added so that ExtensionClasses are now supported by
@ref{55a,,isinstance()} and @ref{55b,,issubclass()}. This means you no longer have to
remember to write code such as @code{if type(obj) == myExtensionClass}, but can use
the more natural @code{if isinstance(obj, myExtensionClass)}.

The @code{Python/importdl.c} file, which was a mass of #ifdefs to support
dynamic loading on many different platforms, was cleaned up and reorganised by
Greg Stein.  @code{importdl.c} is now quite small, and platform-specific code
has been moved into a bunch of @code{Python/dynload_*.c} files.  Another
cleanup: there were also a number of @code{my*.h} files in the Include/
directory that held various portability hacks; they've been merged into a single
file, @code{Include/pyport.h}.

Vladimir Marangozov's long-awaited malloc restructuring was completed, to make
it easy to have the Python interpreter use a custom allocator instead of C's
standard @code{malloc()}.  For documentation, read the comments in
@code{Include/pymem.h} and @code{Include/objimpl.h}.  For the lengthy
discussions during which the interface was hammered out, see the Web archives of
the 'patches' and 'python-dev' lists at python.org.

Recent versions of the GUSI development environment for MacOS support POSIX
threads.  Therefore, Python's POSIX threading support now works on the
Macintosh.  Threading support using the user-space GNU @code{pth} library was also
contributed.

Threading support on Windows was enhanced, too.  Windows supports thread locks
that use kernel objects only in case of contention; in the common case when
there's no contention, they use simpler functions which are an order of
magnitude faster.  A threaded version of Python 1.5.2 on NT is twice as slow as
an unthreaded version; with the 2.0 changes, the difference is only 10%.  These
improvements were contributed by Yakov Markovitch.

Python 2.0's source now uses only ANSI C prototypes, so compiling Python now
requires an ANSI C compiler, and can no longer be done using a compiler that
only supports K&R C.

Previously the Python virtual machine used 16-bit numbers in its bytecode,
limiting the size of source files.  In particular, this affected the maximum
size of literal lists and dictionaries in Python source; occasionally people who
are generating Python code would run into this limit.  A patch by Charles G.
Waldman raises the limit from @code{2**16} to @code{2**32}.

Three new convenience functions intended for adding constants to a module's
dictionary at module initialization time were added: @code{PyModule_AddObject()},
@code{PyModule_AddIntConstant()}, and @code{PyModule_AddStringConstant()}.  Each
of these functions takes a module object, a null-terminated C string containing
the name to be added, and a third argument for the value to be assigned to the
name.  This third argument is, respectively, a Python object, a C long, or a C
string.

A wrapper API was added for Unix-style signal handlers. @code{PyOS_getsig()} gets
a signal handler and @code{PyOS_setsig()} will set a new handler.

@c ======================================================================

@node Distutils：使模块易于安装,XML 模块,扩展/嵌入更改,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 distutils-making-modules-easy-to-install}@anchor{f46}
@subsection Distutils：使模块易于安装


Before Python 2.0, installing modules was a tedious affair -- there was no way
to figure out automatically where Python is installed, or what compiler options
to use for extension modules.  Software authors had to go through an arduous
ritual of editing Makefiles and configuration files, which only really work on
Unix and leave Windows and MacOS unsupported.  Python users faced wildly
differing installation instructions which varied between different extension
packages, which made administering a Python installation something of  a chore.

The SIG for distribution utilities, shepherded by Greg Ward, has created the
Distutils, a system to make package installation much easier.  They form the
@ref{38,,distutils} package, a new part of Python's standard library. In the best
case, installing a Python module from source will require the same steps: first
you simply mean unpack the tarball or zip archive, and the run "@code{python
setup.py install}".  The platform will be automatically detected, the compiler
will be recognized, C extension modules will be compiled, and the distribution
installed into the proper directory.  Optional command-line arguments provide
more control over the installation process, the distutils package offers many
places to override defaults -- separating the build from the install, building
or installing in non-default directories, and more.

In order to use the Distutils, you need to write a @code{setup.py} script.  For
the simple case, when the software contains only .py files, a minimal
@code{setup.py} can be just a few lines long:

@example
from distutils.core import setup
setup (name = "foo", version = "1.0",
       py_modules = ["module1", "module2"])
@end example

The @code{setup.py} file isn't much more complicated if the software consists
of a few packages:

@example
from distutils.core import setup
setup (name = "foo", version = "1.0",
       packages = ["package", "package.subpackage"])
@end example

A C extension can be the most complicated case; here's an example taken from
the PyXML package:

@example
from distutils.core import setup, Extension

expat_extension = Extension('xml.parsers.pyexpat',
     define_macros = [('XML_NS', None)],
     include_dirs = [ 'extensions/expat/xmltok',
                      'extensions/expat/xmlparse' ],
     sources = [ 'extensions/pyexpat.c',
                 'extensions/expat/xmltok/xmltok.c',
                 'extensions/expat/xmltok/xmlrole.c', ]
       )
setup (name = "PyXML", version = "0.5.4",
       ext_modules =[ expat_extension ] )
@end example

The Distutils can also take care of creating source and binary distributions.
The "sdist" command, run by "@code{python setup.py sdist}', builds a source
distribution such as @code{foo-1.0.tar.gz}. Adding new commands isn't
difficult, "bdist_rpm" and "bdist_wininst" commands have already been
contributed to create an RPM distribution and a Windows installer for the
software, respectively.  Commands to create other distribution formats such as
Debian packages and Solaris @code{.pkg} files are in various stages of
development.

All this is documented in a new manual, @emph{Distributing Python Modules}, that
joins the basic set of Python documentation.

@c ======================================================================

@node XML 模块,模块更改,Distutils：使模块易于安装,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 xml-modules}@anchor{f47}
@subsection XML 模块


Python 1.5.2 included a simple XML parser in the form of the @code{xmllib}
module, contributed by Sjoerd Mullender.  Since 1.5.2's release, two different
interfaces for processing XML have become common: SAX2 (version 2 of the Simple
API for XML) provides an event-driven interface with some similarities to
@code{xmllib}, and the DOM (Document Object Model) provides a tree-based
interface, transforming an XML document into a tree of nodes that can be
traversed and modified.  Python 2.0 includes a SAX2 interface and a stripped-down
DOM interface as part of the @ref{13c,,xml} package. Here we will give a brief
overview of these new interfaces; consult the Python documentation or the source
code for complete details. The Python XML SIG is also working on improved
documentation.

@menu
* SAX2 Support:: 
* DOM Support:: 
* Relationship to PyXML:: 

@end menu

@node SAX2 Support,DOM Support,,XML 模块
@anchor{whatsnew/2 0 sax2-support}@anchor{f48}
@subsubsection SAX2 Support


SAX defines an event-driven interface for parsing XML.  To use SAX, you must
write a SAX handler class.  Handler classes inherit from various classes
provided by SAX, and override various methods that will then be called by the
XML parser.  For example, the @code{startElement()} and @code{endElement()}
methods are called for every starting and end tag encountered by the parser, the
@code{characters()} method is called for every chunk of character data, and so
forth.

The advantage of the event-driven approach is that the whole document doesn't
have to be resident in memory at any one time, which matters if you are
processing really huge documents.  However, writing the SAX handler class can
get very complicated if you're trying to modify the document structure in some
elaborate way.

For example, this little example program defines a handler that prints a message
for every starting and ending tag, and then parses the file @code{hamlet.xml}
using it:

@example
from xml import sax

class SimpleHandler(sax.ContentHandler):
    def startElement(self, name, attrs):
        print 'Start of element:', name, attrs.keys()

    def endElement(self, name):
        print 'End of element:', name

# Create a parser object
parser = sax.make_parser()

# Tell it what handler to use
handler = SimpleHandler()
parser.setContentHandler( handler )

# Parse a file!
parser.parse( 'hamlet.xml' )
@end example

For more information, consult the Python documentation, or the XML HOWTO at
@indicateurl{http://pyxml.sourceforge.net/topics/howto/xml-howto.html}.

@node DOM Support,Relationship to PyXML,SAX2 Support,XML 模块
@anchor{whatsnew/2 0 dom-support}@anchor{f49}
@subsubsection DOM Support


The Document Object Model is a tree-based representation for an XML document.  A
top-level @code{Document} instance is the root of the tree, and has a single
child which is the top-level @code{Element} instance. This @code{Element}
has children nodes representing character data and any sub-elements, which may
have further children of their own, and so forth.  Using the DOM you can
traverse the resulting tree any way you like, access element and attribute
values, insert and delete nodes, and convert the tree back into XML.

The DOM is useful for modifying XML documents, because you can create a DOM
tree, modify it by adding new nodes or rearranging subtrees, and then produce a
new XML document as output.  You can also construct a DOM tree manually and
convert it to XML, which can be a more flexible way of producing XML output than
simply writing @code{<tag1>}...@code{</tag1>} to a file.

The DOM implementation included with Python lives in the @ref{13e,,xml.dom.minidom}
module.  It's a lightweight implementation of the Level 1 DOM with support for
XML namespaces.  The  @code{parse()} and @code{parseString()} convenience
functions are provided for generating a DOM tree:

@example
from xml.dom import minidom
doc = minidom.parse('hamlet.xml')
@end example

@code{doc} is a @code{Document} instance.  @code{Document}, like all the other
DOM classes such as @code{Element} and @code{Text}, is a subclass of the
@code{Node} base class.  All the nodes in a DOM tree therefore support certain
common methods, such as @code{toxml()} which returns a string containing the XML
representation of the node and its children.  Each class also has special
methods of its own; for example, @code{Element} and @code{Document}
instances have a method to find all child elements with a given tag name.
Continuing from the previous 2-line example:

@example
perslist = doc.getElementsByTagName( 'PERSONA' )
print perslist[0].toxml()
print perslist[1].toxml()
@end example

For the @emph{Hamlet} XML file, the above few lines output:

@example
<PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
<PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>
@end example

The root element of the document is available as @code{doc.documentElement}, and
its children can be easily modified by deleting, adding, or removing nodes:

@example
root = doc.documentElement

# Remove the first child
root.removeChild( root.childNodes[0] )

# Move the new first child to the end
root.appendChild( root.childNodes[0] )

# Insert the new first child (originally,
# the third child) before the 20th child.
root.insertBefore( root.childNodes[0], root.childNodes[20] )
@end example

Again, I will refer you to the Python documentation for a complete listing of
the different @code{Node} classes and their various methods.

@node Relationship to PyXML,,DOM Support,XML 模块
@anchor{whatsnew/2 0 relationship-to-pyxml}@anchor{f4a}
@subsubsection Relationship to PyXML


The XML Special Interest Group has been working on XML-related Python code for a
while.  Its code distribution, called PyXML, is available from the SIG's Web
pages at @indicateurl{https://www.python.org/community/sigs/current/xml-sig}. The PyXML distribution also used
the package name @code{xml}.  If you've written programs that used PyXML, you're
probably wondering about its compatibility with the 2.0 @ref{13c,,xml} package.

The answer is that Python 2.0's @ref{13c,,xml} package isn't compatible with PyXML,
but can be made compatible by installing a recent version PyXML.  Many
applications can get by with the XML support that is included with Python 2.0,
but more complicated applications will require that the full PyXML package will
be installed.  When installed, PyXML versions 0.6.0 or greater will replace the
@ref{13c,,xml} package shipped with Python, and will be a strict superset of the
standard package, adding a bunch of additional features.  Some of the additional
features in PyXML include:


@itemize *

@item 
4DOM, a full DOM implementation from FourThought, Inc.

@item 
The xmlproc validating parser, written by Lars Marius Garshol.

@item 
The @code{sgmlop} parser accelerator module, written by Fredrik Lundh.
@end itemize

@c ======================================================================

@node 模块更改,新增模块<8>,XML 模块,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 module-changes}@anchor{f4b}
@subsection 模块更改


Lots of improvements and bugfixes were made to Python's extensive standard
library; some of the affected modules include @ref{de,,readline},
@code{ConfigParser}, @ref{15,,cgi}, @ref{14,,calendar}, @ref{d1,,posix}, @ref{de,,readline},
@code{xmllib}, @ref{4,,aifc}, @code{chunk, wave}, @ref{dc,,random}, @ref{e7,,shelve},
and @ref{c0,,nntplib}.  Consult the CVS logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the @ref{ef,,socket} module.  OpenSSL
is an implementation of the Secure Socket Layer, which encrypts the data being
sent over a socket.  When compiling Python, you can edit @code{Modules/Setup}
to include SSL support, which adds an additional function to the @ref{ef,,socket}
module: @code{socket.ssl(socket, keyfile, certfile)}, which takes a socket
object and returns an SSL socket.  The @code{httplib} and @ref{126,,urllib} modules
were also changed to support @code{https://} URLs, though no one has implemented
FTP or SMTP over SSL.

The @code{httplib} module has been rewritten by Greg Stein to support HTTP/1.1.
Backward compatibility with the 1.5 version of @code{httplib} is provided,
though using HTTP/1.1 features such as pipelining will require rewriting code to
use a different set of interfaces.

The @code{Tkinter} module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
support for the older 7.x versions has been dropped.  The Tkinter module now
supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh
contributed an optimization which makes operations like @code{create_line} and
@code{create_polygon} much faster, especially when using lots of coordinates.

The @ref{2b,,curses} module has been greatly extended, starting from Oliver
Andrich's enhanced version, to provide many additional functions from ncurses
and SYSV curses, such as colour, alternative character set support, pads, and
mouse support.  This means the module is no longer compatible with operating
systems that only have BSD curses, but there don't seem to be any currently
maintained OSes that fall into this category.

As mentioned in the earlier discussion of 2.0's Unicode support, the underlying
implementation of the regular expressions provided by the @ref{dd,,re} module has
been changed.  SRE, a new regular expression engine written by Fredrik Lundh and
partially funded by Hewlett Packard, supports matching against both 8-bit
strings and Unicode strings.

@c ======================================================================

@node 新增模块<8>,IDLE 改进,模块更改,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 new-modules}@anchor{f4c}
@subsection 新增模块


A number of new modules were added.  We'll simply list them with brief
descriptions; consult the 2.0 documentation for the details of a particular
module.


@itemize *

@item 
@ref{b,,atexit}:  For registering functions to be called before the Python
interpreter exits. Code that currently sets @code{sys.exitfunc} directly should be
changed to  use the @ref{b,,atexit} module instead, importing @ref{b,,atexit} and
calling @ref{f4d,,atexit.register()} with  the function to be called on exit.
(Contributed by Skip Montanaro.)

@item 
@ref{1b,,codecs}, @code{encodings}, @ref{123,,unicodedata}:  Added as part of the new
Unicode support.

@item 
@ref{7d,,filecmp}: Supersedes the old @code{cmp}, @code{cmpcache} and
@code{dircmp} modules, which have now become deprecated. (Contributed by Gordon
MacMillan and Moshe Zadka.)

@item 
@ref{87,,gettext}: This module provides internationalization (I18N) and
localization (L10N) support for Python programs by providing an interface to the
GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate
contributions by Martin  von Löwis, Peter Funk, and James Henstridge.)

@item 
@code{linuxaudiodev}: Support for the @code{/dev/audio} device on Linux, a
twin to the existing @code{sunaudiodev} module. (Contributed by Peter Bosch,
with fixes by Jeremy Hylton.)

@item 
@ref{b3,,mmap}: An interface to memory-mapped files on both Windows and Unix.  A
file's contents can be mapped directly into memory, at which point it behaves
like a mutable string, so its contents can be read and modified.  They can even
be passed to functions that expect ordinary strings, such as the @ref{dd,,re}
module. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)

@item 
@code{pyexpat}: An interface to the Expat XML parser. (Contributed by Paul
Prescod.)

@item 
@code{robotparser}: Parse a @code{robots.txt} file, which is used for writing
Web spiders that politely avoid certain areas of a Web site.  The parser accepts
the contents of a @code{robots.txt} file, builds a set of rules from it, and
can then answer questions about the fetchability of a given URL.  (Contributed
by Skip Montanaro.)

@item 
@ref{100,,tabnanny}: A module/script to  check Python source code for ambiguous
indentation. (Contributed by Tim Peters.)

@item 
@code{UserString}: A base class useful for deriving objects that behave like
strings.

@item 
@ref{132,,webbrowser}: A module that provides a platform independent way to launch
a web browser on a specific URL. For each platform, various browsers are tried
in a specific order. The user can alter which browser is launched by setting the
@emph{BROWSER} environment variable.  (Originally inspired by Eric S. Raymond's patch
to @ref{126,,urllib} which added similar functionality, but the final module comes
from code originally  implemented by Fred Drake as
@code{Tools/idle/BrowserControl.py}, and adapted for the standard library by
Fred.)

@item 
@code{_winreg}: An interface to the Windows registry.  @code{_winreg} is an
adaptation of functions that have been part of PythonWin since 1995, but has now
been added to the core  distribution, and enhanced to support Unicode.
@code{_winreg} was written by Bill Tutt and Mark Hammond.

@item 
@ref{14b,,zipfile}: A module for reading and writing ZIP-format archives.  These
are archives produced by @code{PKZIP} on DOS/Windows or @code{zip} on
Unix, not to be confused with @code{gzip}-format files (which are
supported by the @ref{8b,,gzip} module) (Contributed by James C. Ahlstrom.)

@item 
@code{imputil}: A module that provides a simpler way for writing customized
import hooks, in comparison to the existing @code{ihooks} module.  (Implemented
by Greg Stein, with much discussion on python-dev along the way.)
@end itemize

@c ======================================================================

@node IDLE 改进,删除和弃用的模块,新增模块<8>,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 idle-improvements}@anchor{f4e}
@subsection IDLE 改进


IDLE is the official Python cross-platform IDE, written using Tkinter. Python
2.0 includes IDLE 0.6, which adds a number of new features and improvements.  A
partial list:


@itemize *

@item 
UI improvements and optimizations, especially in the area of syntax
highlighting and auto-indentation.

@item 
The class browser now shows more information, such as the top level functions
in a module.

@item 
Tab width is now a user settable option. When opening an existing Python file,
IDLE automatically detects the indentation conventions, and adapts.

@item 
There is now support for calling browsers on various platforms, used to open
the Python documentation in a browser.

@item 
IDLE now has a command line, which is largely similar to  the vanilla Python
interpreter.

@item 
Call tips were added in many places.

@item 
IDLE 现在可以作为一个包被安装。

@item 
In the editor window, there is now a line/column bar at the bottom.

@item 
Three new keystroke commands: Check module (@code{Alt-F5}), Import module (@code{F5}) and
Run script (@code{Ctrl-F5}).
@end itemize

@c ======================================================================

@node 删除和弃用的模块,致谢<8>,IDLE 改进,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 deleted-and-deprecated-modules}@anchor{f4f}
@subsection 删除和弃用的模块


A few modules have been dropped because they're obsolete, or because there are
now better ways to do the same thing.  The @code{stdwin} module is gone; it was
for a platform-independent windowing toolkit that's no longer developed.

A number of modules have been moved to the @code{lib-old} subdirectory:
@code{cmp}, @code{cmpcache}, @code{dircmp}, @code{dump},  @code{find},
@code{grep}, @code{packmail},  @code{poly}, @code{util}, @code{whatsound},
@code{zmod}.  If you have code which relies on a module  that's been moved to
@code{lib-old}, you can simply add that directory to @code{sys.path}   to get them
back, but you're encouraged to update any code that uses these modules.

@node 致谢<8>,,删除和弃用的模块,Python 2 0 有什么新变化
@anchor{whatsnew/2 0 acknowledgements}@anchor{f50}
@subsection 致谢


作者感谢以下人士对本文的各种草稿提出建议： David Bolen, Mark Hammond, Gregg Hauser, Jeremy Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.

这个“更新日志”是 Misc/NEWS.d@footnote{https://github.com/python/cpython/tree/3.9/Misc/NEWS.d} 目录下文件 构建@footnote{https://pypi.org/project/blurb} 的 HTML 版本，它包含了对当前 Python 版本进行的 @emph{所有} 重要的更改。

@node 更新日志,,Python 2 0 有什么新变化,Python 有什么新变化？
@anchor{whatsnew/changelog doc}@anchor{f51}@anchor{whatsnew/changelog changelog}@anchor{156}@anchor{whatsnew/changelog id1}@anchor{f52}
@section 更新日志


@menu
* Python 3.9.17 final: Python 3 9 17 final. 
* Python 3.9.16 final: Python 3 9 16 final. 
* Python 3.9.15 final: Python 3 9 15 final. 
* Python 3.9.14 final: Python 3 9 14 final. 
* Python 3.9.13 final: Python 3 9 13 final. 
* Python 3.9.12 final: Python 3 9 12 final. 
* Python 3.9.11 final: Python 3 9 11 final. 
* Python 3.9.10 final: Python 3 9 10 final. 
* Python 3.9.9 final: Python 3 9 9 final. 
* Python 3.9.8 final: Python 3 9 8 final. 
* Python 3.9.7 final: Python 3 9 7 final. 
* Python 3.9.6 final: Python 3 9 6 final. 
* Python 3.9.5 final: Python 3 9 5 final. 
* Python 3.9.4 final: Python 3 9 4 final. 
* Python 3.9.3 final: Python 3 9 3 final. 
* Python 3.9.2 final: Python 3 9 2 final. 
* Python 3.9.2 release candidate 1: Python 3 9 2 release candidate 1. 
* Python 3.9.1 final: Python 3 9 1 final. 
* Python 3.9.1 release candidate 1: Python 3 9 1 release candidate 1. 
* Python 3.9.0 final: Python 3 9 0 final. 
* Python 3.9.0 release candidate 2: Python 3 9 0 release candidate 2. 
* Python 3.9.0 release candidate 1: Python 3 9 0 release candidate 1. 
* Python 3.9.0 beta 5: Python 3 9 0 beta 5. 
* Python 3.9.0 beta 4: Python 3 9 0 beta 4. 
* Python 3.9.0 beta 3: Python 3 9 0 beta 3. 
* Python 3.9.0 beta 2: Python 3 9 0 beta 2. 
* Python 3.9.0 beta 1: Python 3 9 0 beta 1. 
* Python 3.9.0 alpha 6: Python 3 9 0 alpha 6. 
* Python 3.9.0 alpha 5: Python 3 9 0 alpha 5. 
* Python 3.9.0 alpha 4: Python 3 9 0 alpha 4. 
* Python 3.9.0 alpha 3: Python 3 9 0 alpha 3. 
* Python 3.9.0 alpha 2: Python 3 9 0 alpha 2. 
* Python 3.9.0 alpha 1: Python 3 9 0 alpha 1. 
* Python 3.8.0 beta 1: Python 3 8 0 beta 1. 
* Python 3.8.0 alpha 4: Python 3 8 0 alpha 4. 
* Python 3.8.0 alpha 3: Python 3 8 0 alpha 3. 
* Python 3.8.0 alpha 2: Python 3 8 0 alpha 2. 
* Python 3.8.0 alpha 1: Python 3 8 0 alpha 1. 
* Python 3.7.0 final: Python 3 7 0 final. 
* Python 3.7.0 release candidate 1: Python 3 7 0 release candidate 1. 
* Python 3.7.0 beta 5: Python 3 7 0 beta 5. 
* Python 3.7.0 beta 4: Python 3 7 0 beta 4. 
* Python 3.7.0 beta 3: Python 3 7 0 beta 3. 
* Python 3.7.0 beta 2: Python 3 7 0 beta 2. 
* Python 3.7.0 beta 1: Python 3 7 0 beta 1. 
* Python 3.7.0 alpha 4: Python 3 7 0 alpha 4. 
* Python 3.7.0 alpha 3: Python 3 7 0 alpha 3. 
* Python 3.7.0 alpha 2: Python 3 7 0 alpha 2. 
* Python 3.7.0 alpha 1: Python 3 7 0 alpha 1. 
* Python 3.6.6 final: Python 3 6 6 final. 
* Python 3.6.6 release candidate 1: Python 3 6 6 release candidate 1. 
* Python 3.6.5 final: Python 3 6 5 final. 
* Python 3.6.5 release candidate 1: Python 3 6 5 release candidate 1. 
* Python 3.6.4 final: Python 3 6 4 final. 
* Python 3.6.4 release candidate 1: Python 3 6 4 release candidate 1. 
* Python 3.6.3 final: Python 3 6 3 final. 
* Python 3.6.3 release candidate 1: Python 3 6 3 release candidate 1. 
* Python 3.6.2 final: Python 3 6 2 final. 
* Python 3.6.2 release candidate 2: Python 3 6 2 release candidate 2. 
* Python 3.6.2 release candidate 1: Python 3 6 2 release candidate 1. 
* Python 3.6.1 final: Python 3 6 1 final. 
* Python 3.6.1 release candidate 1: Python 3 6 1 release candidate 1. 
* Python 3.6.0 final: Python 3 6 0 final. 
* Python 3.6.0 release candidate 2: Python 3 6 0 release candidate 2. 
* Python 3.6.0 release candidate 1: Python 3 6 0 release candidate 1. 
* Python 3.6.0 beta 4: Python 3 6 0 beta 4. 
* Python 3.6.0 beta 3: Python 3 6 0 beta 3. 
* Python 3.6.0 beta 2: Python 3 6 0 beta 2. 
* Python 3.6.0 beta 1: Python 3 6 0 beta 1. 
* Python 3.6.0 alpha 4: Python 3 6 0 alpha 4. 
* Python 3.6.0 alpha 3: Python 3 6 0 alpha 3. 
* Python 3.6.0 alpha 2: Python 3 6 0 alpha 2. 
* Python 3.6.0 alpha 1: Python 3 6 0 alpha 1. 
* Python 3.5.5 final: Python 3 5 5 final. 
* Python 3.5.5 release candidate 1: Python 3 5 5 release candidate 1. 
* Python 3.5.4 final: Python 3 5 4 final. 
* Python 3.5.4 release candidate 1: Python 3 5 4 release candidate 1. 
* Python 3.5.3 final: Python 3 5 3 final. 
* Python 3.5.3 release candidate 1: Python 3 5 3 release candidate 1. 
* Python 3.5.2 final: Python 3 5 2 final. 
* Python 3.5.2 release candidate 1: Python 3 5 2 release candidate 1. 
* Python 3.5.1 final: Python 3 5 1 final. 
* Python 3.5.1 release candidate 1: Python 3 5 1 release candidate 1. 
* Python 3.5.0 final: Python 3 5 0 final. 
* Python 3.5.0 release candidate 4: Python 3 5 0 release candidate 4. 
* Python 3.5.0 release candidate 3: Python 3 5 0 release candidate 3. 
* Python 3.5.0 release candidate 2: Python 3 5 0 release candidate 2. 
* Python 3.5.0 release candidate 1: Python 3 5 0 release candidate 1. 
* Python 3.5.0 beta 4: Python 3 5 0 beta 4. 
* Python 3.5.0 beta 3: Python 3 5 0 beta 3. 
* Python 3.5.0 beta 2: Python 3 5 0 beta 2. 
* Python 3.5.0 beta 1: Python 3 5 0 beta 1. 
* Python 3.5.0 alpha 4: Python 3 5 0 alpha 4. 
* Python 3.5.0 alpha 3: Python 3 5 0 alpha 3. 
* Python 3.5.0 alpha 2: Python 3 5 0 alpha 2. 
* Python 3.5.0 alpha 1: Python 3 5 0 alpha 1. 

@end menu

@node Python 3 9 17 final,Python 3 9 16 final,,更新日志
@anchor{whatsnew/changelog python-3-9-17-final}@anchor{f53}
@subsection Python 3.9.17 final


@emph{Release date: 2023-06-06}

@menu
* Security:: 
* Core and Builtins:: 
* Library:: 
* Windows:: 
* macOS:: 

@end menu

@node Security,Core and Builtins,,Python 3 9 17 final
@anchor{whatsnew/changelog security}@anchor{f54}
@subsubsection Security



@itemize -

@item 
gh-103142@footnote{https://github.com/python/cpython/issues/103142}: The version of OpenSSL used in our binary builds has been
upgraded to 1.1.1u to address several CVEs.

@item 
gh-99889@footnote{https://github.com/python/cpython/issues/99889}: Fixed a security in flaw in @ref{f55,,uu.decode()} that could
allow for directory traversal based on the input if no @code{out_file} was
specified.

@item 
gh-104049@footnote{https://github.com/python/cpython/issues/104049}: Do not expose the local on-disk location in directory
indexes produced by @code{http.client.SimpleHTTPRequestHandler}.

@item 
gh-102153@footnote{https://github.com/python/cpython/issues/102153}: @ref{6fa,,urllib.parse.urlsplit()} now strips leading C0
control and space characters following the specification for URLs defined
by WHATWG in response to CVE-2023-24329. Patch by Illia Volochii.

@item 
gh-101727@footnote{https://github.com/python/cpython/issues/101727}: Updated the OpenSSL version used in Windows and macOS
binary release builds to 1.1.1t to address CVE-2023-0286, CVE-2022-4303,
and CVE-2022-4303 per the OpenSSL 2023-02-07 security advisory@footnote{https://www.openssl.org/news/secadv/20230207.txt}.

@item 
gh-101283@footnote{https://github.com/python/cpython/issues/101283}: @ref{3e3,,subprocess.Popen} now uses a safer approach to
find @code{cmd.exe} when launching with @code{shell=True}. Patch by Eryk Sun,
based on a patch by Oleg Iarygin.
@end itemize

@node Core and Builtins,Library,Security,Python 3 9 17 final
@anchor{whatsnew/changelog core-and-builtins}@anchor{f56}
@subsubsection Core and Builtins



@itemize -

@item 
gh-102126@footnote{https://github.com/python/cpython/issues/102126}: Fix deadlock at shutdown when clearing thread states if
any finalizer tries to acquire the runtime head lock. Patch by Kumar
Aditya.

@item 
gh-100892@footnote{https://github.com/python/cpython/issues/100892}: Fix race while iterating over thread states in clearing
@ref{f57,,threading.local}. Patch by Kumar Aditya.
@end itemize

@node Library,Windows,Core and Builtins,Python 3 9 17 final
@anchor{whatsnew/changelog library}@anchor{f58}
@subsubsection Library



@itemize -

@item 
gh-103935@footnote{https://github.com/python/cpython/issues/103935}: Use @ref{f59,,io.open_code()} for files to be executed instead
of raw @ref{16f,,open()}

@item 
gh-102953@footnote{https://github.com/python/cpython/issues/102953}: The extraction methods in @ref{101,,tarfile}, and
@ref{28b,,shutil.unpack_archive()}, have a new a @emph{filter} argument that allows
limiting tar features than may be surprising or dangerous, such as
creating files outside the destination directory. See
@ref{28c,,Extraction filters} for details.

@item 
gh-101997@footnote{https://github.com/python/cpython/issues/101997}: Upgrade pip wheel bundled with ensurepip (pip 23.0.1)
@end itemize

@node Windows,macOS,Library,Python 3 9 17 final
@anchor{whatsnew/changelog windows}@anchor{f5a}
@subsubsection Windows



@itemize -

@item 
gh-100180@footnote{https://github.com/python/cpython/issues/100180}: Update Windows installer to OpenSSL 1.1.1s
@end itemize

@node macOS,,Windows,Python 3 9 17 final
@anchor{whatsnew/changelog macos}@anchor{f5b}
@subsubsection macOS



@itemize -

@item 
gh-103142@footnote{https://github.com/python/cpython/issues/103142}: Update macOS installer to use OpenSSL 1.1.1u.
@end itemize

@node Python 3 9 16 final,Python 3 9 15 final,Python 3 9 17 final,更新日志
@anchor{whatsnew/changelog python-3-9-16-final}@anchor{f5c}
@subsection Python 3.9.16 final


@emph{Release date: 2022-12-06}

@menu
* Security: Security<2>. 

@end menu

@node Security<2>,,,Python 3 9 16 final
@anchor{whatsnew/changelog id2}@anchor{f5d}
@subsubsection Security



@itemize -

@item 
gh-100001@footnote{https://github.com/python/cpython/issues/100001}: @code{python -m http.server} no longer allows terminal
control characters sent within a garbage request to be printed to the
stderr server log.

This is done by changing the @ref{96,,http.server}
@code{BaseHTTPRequestHandler} @code{.log_message} method to replace control
characters with a @code{\xHH} hex escape before printing.

@item 
gh-87604@footnote{https://github.com/python/cpython/issues/87604}: Avoid publishing list of active per-interpreter audit
hooks via the @ref{84,,gc} module

@item 
gh-98433@footnote{https://github.com/python/cpython/issues/98433}: The IDNA codec decoder used on DNS hostnames by
@ref{ef,,socket} or @ref{9,,asyncio} related name resolution functions no
longer involves a quadratic algorithm. This prevents a potential CPU
denial of service if an out-of-spec excessive length hostname involving
bidirectional characters were decoded. Some protocols such as
@ref{126,,urllib} http @code{3xx} redirects potentially allow for an attacker to
supply such a name.

@item 
gh-98739@footnote{https://github.com/python/cpython/issues/98739}: Update bundled libexpat to 2.5.0

@item 
gh-98517@footnote{https://github.com/python/cpython/issues/98517}: Port XKCP's fix for the buffer overflows in SHA-3
(CVE-2022-37454).

@item 
gh-97514@footnote{https://github.com/python/cpython/issues/97514}: On Linux the @ref{b7,,multiprocessing} module returns to
using filesystem backed unix domain sockets for communication with the
@emph{forkserver} process instead of the Linux abstract socket namespace.  Only
code that chooses to use the @ref{96a,,"forkserver" start method} is affected.

Abstract sockets have no permissions and could allow any user on the
system in the same network namespace@footnote{https://man7.org/linux/man-pages/man7/network_namespaces.7.html} (often
the whole system) to inject code into the multiprocessing @emph{forkserver}
process. This was a potential privilege escalation. Filesystem based
socket permissions restrict this to the @emph{forkserver} process user as was
the default in Python 3.8 and earlier.

This prevents Linux CVE-2022-42919@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-42919}.

@item 
gh-68966@footnote{https://github.com/python/cpython/issues/68966}: The deprecated mailcap module now refuses to inject unsafe
text (filenames, MIME types, parameters) into shell commands. Instead of
using such text, it will warn and act as if a match was not found (or for
test commands, as if the test failed).
@end itemize

@node Python 3 9 15 final,Python 3 9 14 final,Python 3 9 16 final,更新日志
@anchor{whatsnew/changelog python-3-9-15-final}@anchor{f5e}
@subsection Python 3.9.15 final


@emph{Release date: 2022-10-11}

@menu
* Security: Security<3>. 
* Core and Builtins: Core and Builtins<2>. 
* Library: Library<2>. 
* Windows: Windows<2>. 
* macOS: macOS<2>. 

@end menu

@node Security<3>,Core and Builtins<2>,,Python 3 9 15 final
@anchor{whatsnew/changelog id3}@anchor{f5f}
@subsubsection Security



@itemize -

@item 
gh-97616@footnote{https://github.com/python/cpython/issues/97616}: Fix multiplying a list by an integer (@code{list *= int}):
detect the integer overflow when the new allocated length is close to the
maximum size. Issue reported by Jordan Limor.  Patch by Victor Stinner.

@item 
gh-97612@footnote{https://github.com/python/cpython/issues/97612}: Fix a shell code injection vulnerability in the
@code{get-remote-certificate.py} example script. The script no longer uses a
shell to run @code{openssl} commands. Issue reported and initial fix by Caleb
Shortt. Patch by Victor Stinner.
@end itemize

@node Core and Builtins<2>,Library<2>,Security<3>,Python 3 9 15 final
@anchor{whatsnew/changelog id4}@anchor{f60}
@subsubsection Core and Builtins



@itemize -

@item 
gh-96848@footnote{https://github.com/python/cpython/issues/96848}: Fix command line parsing: reject @ref{297,,-X int_max_str_digits} option with no value (invalid) when the
@geindex PYTHONINTMAXSTRDIGITS
@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@ref{f61,,PYTHONINTMAXSTRDIGITS} environment variable is set to a valid
limit. Patch by Victor Stinner.

@item 
gh-95778@footnote{https://github.com/python/cpython/issues/95778}: When @ref{16d,,ValueError} is raised if an integer is larger
than the limit, mention the @ref{f62,,sys.set_int_max_str_digits()} function in
the error message. Patch by Victor Stinner.
@end itemize

@node Library<2>,Windows<2>,Core and Builtins<2>,Python 3 9 15 final
@anchor{whatsnew/changelog id5}@anchor{f63}
@subsubsection Library



@itemize -

@item 
gh-97005@footnote{https://github.com/python/cpython/issues/97005}: Update bundled libexpat to 2.4.9
@end itemize

@node Windows<2>,macOS<2>,Library<2>,Python 3 9 15 final
@anchor{whatsnew/changelog id6}@anchor{f64}
@subsubsection Windows



@itemize -

@item 
gh-96577@footnote{https://github.com/python/cpython/issues/96577}: Fixes a potential buffer overrun in @ref{b5,,msilib}.
@end itemize

@node macOS<2>,,Windows<2>,Python 3 9 15 final
@anchor{whatsnew/changelog id7}@anchor{f65}
@subsubsection macOS



@itemize -

@item 
gh-97897@footnote{https://github.com/python/cpython/issues/97897}: The macOS 13 SDK includes support for the @code{mkfifoat} and
@code{mknodat} system calls. Using the @code{dir_fd} option with either
@ref{760,,os.mkfifo()} or @ref{761,,os.mknod()} could result in a segfault if
cpython is built with the macOS 13 SDK but run on an earlier version of
macOS. Prevent this by adding runtime support for detection of these
system calls ("weaklinking") as is done for other newer syscalls on macOS.
@end itemize

@node Python 3 9 14 final,Python 3 9 13 final,Python 3 9 15 final,更新日志
@anchor{whatsnew/changelog python-3-9-14-final}@anchor{f66}
@subsection Python 3.9.14 final


@emph{Release date: 2022-09-06}

@menu
* Security: Security<4>. 
* Core and Builtins: Core and Builtins<3>. 
* Library: Library<3>. 
* Tests:: 

@end menu

@node Security<4>,Core and Builtins<3>,,Python 3 9 14 final
@anchor{whatsnew/changelog id8}@anchor{f67}
@subsubsection Security



@itemize -

@item 
gh-95778@footnote{https://github.com/python/cpython/issues/95778}: Converting between @ref{205,,int} and @ref{206,,str} in bases
other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base
10 (decimal) now raises a @ref{16d,,ValueError} if the number of digits in
string form is above a limit to avoid potential denial of service attacks
due to the algorithmic complexity. This is a mitigation for
CVE-2020-10735@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735}.

This new limit can be configured or disabled by environment variable,
command line flag, or @ref{fd,,sys} APIs. See the @ref{288,,integer string conversion length limitation} documentation.  The
default limit is 4300 digits in string form.

Patch by Gregory P. Smith [Google] and Christian Heimes [Red Hat] with
feedback from Victor Stinner, Thomas Wouters, Steve Dower, Ned Deily, and
Mark Dickinson.

@item 
gh-87389@footnote{https://github.com/python/cpython/issues/87389}: @ref{96,,http.server}: Fix an open redirection vulnerability
in the HTTP server when an URI path starts with @code{//}.  Vulnerability
discovered, and initial fix proposed, by Hamza Avvan.
@end itemize

@node Core and Builtins<3>,Library<3>,Security<4>,Python 3 9 14 final
@anchor{whatsnew/changelog id9}@anchor{f68}
@subsubsection Core and Builtins



@itemize -

@item 
gh-93065@footnote{https://github.com/python/cpython/issues/93065}: Fix contextvars HAMT implementation to handle iteration
over deep trees.

The bug was discovered and fixed by Eli Libman. See
MagicStack/immutables#84@footnote{https://github.com/MagicStack/immutables/issues/84} for more details.
@end itemize

@node Library<3>,Tests,Core and Builtins<3>,Python 3 9 14 final
@anchor{whatsnew/changelog id10}@anchor{f69}
@subsubsection Library



@itemize -

@item 
gh-94821@footnote{https://github.com/python/cpython/issues/94821}: Fix binding of unix socket to empty address on Linux to
use an available address from the abstract namespace, instead of "0".

@item 
gh-91810@footnote{https://github.com/python/cpython/issues/91810}: Suppress writing an XML declaration in open files in
@code{ElementTree.write()} with @code{encoding='unicode'} and
@code{xml_declaration=None}.

@item 
bpo-45393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45393}: Fix the formatting for @code{await x} and @code{not x} in the
operator precedence table when using the @ref{175,,help()} system.

@item 
bpo-46197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46197}: Fix @ref{78,,ensurepip} environment isolation for subprocess
running @code{pip}.
@end itemize

@node Tests,,Library<3>,Python 3 9 14 final
@anchor{whatsnew/changelog tests}@anchor{f6a}
@subsubsection Tests



@itemize -

@item 
gh-95280@footnote{https://github.com/python/cpython/issues/95280}: Fix problem with @code{test_ssl} @code{test_get_ciphers} on
systems that require perfect forward secrecy (PFS) ciphers.

@item 
gh-94208@footnote{https://github.com/python/cpython/issues/94208}: @code{test_ssl} is now checking for supported TLS version and
protocols in more tests.

@item 
bpo-47016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47016}: Create a GitHub Actions workflow for verifying bundled pip and
setuptools. Patch by Illia Volochii and Adam Turner.
@end itemize

@node Python 3 9 13 final,Python 3 9 12 final,Python 3 9 14 final,更新日志
@anchor{whatsnew/changelog python-3-9-13-final}@anchor{f6b}
@subsection Python 3.9.13 final


@emph{Release date: 2022-05-17}

@menu
* Core and Builtins: Core and Builtins<4>. 
* Library: Library<4>. 
* Documentation:: 
* Tests: Tests<2>. 
* Build:: 
* Windows: Windows<3>. 
* Tools/Demos:: 

@end menu

@node Core and Builtins<4>,Library<4>,,Python 3 9 13 final
@anchor{whatsnew/changelog id11}@anchor{f6c}
@subsubsection Core and Builtins



@itemize -

@item 
gh-92311@footnote{https://github.com/python/cpython/issues/92311}: Fixed a bug where setting @code{frame.f_lineno} to jump over
a list comprehension could misbehave or crash.

@item 
gh-92112@footnote{https://github.com/python/cpython/issues/92112}: Fix crash triggered by an evil custom @code{mro()} on a
metaclass.

@item 
gh-92036@footnote{https://github.com/python/cpython/issues/92036}: Fix a crash in subinterpreters related to the garbage
collector. When a subinterpreter is deleted, untrack all objects tracked
by its GC. To prevent a crash in deallocator functions expecting objects
to be tracked by the GC, leak a strong reference to these objects on
purpose, so they are never deleted and their deallocator functions are not
called. Patch by Victor Stinner.

@item 
gh-91421@footnote{https://github.com/python/cpython/issues/91421}: Fix a potential integer overflow in _Py_DecodeUTF8Ex.

@item 
bpo-46775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46775}: Some Windows system error codes(>= 10000) are now mapped into
the correct errno and may now raise a subclass of @ref{30b,,OSError}. Patch by
Dong-hee Na.

@item 
bpo-46962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46962}: Classes and functions that unconditionally declared their
docstrings ignoring the @code{--without-doc-strings} compilation flag no longer
do so.

The classes affected are @ref{f6d,,pickle.PickleBuffer},
@code{testcapi.RecursingInfinitelyError}, and
@ref{27d,,types.GenericAlias}.

The functions affected are 24 methods in @ref{2a,,ctypes}.

Patch by Oleg Iarygin.

@item 
bpo-36819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36819}: Fix crashes in built-in encoders with error handlers that
return position less or equal than the starting position of non-encodable
characters.
@end itemize

@node Library<4>,Documentation,Core and Builtins<4>,Python 3 9 13 final
@anchor{whatsnew/changelog id12}@anchor{f6e}
@subsubsection Library



@itemize -

@item 
gh-91581@footnote{https://github.com/python/cpython/issues/91581}: @ref{f6f,,utcfromtimestamp()} no longer
attempts to resolve @code{fold} in the pure Python implementation, since the
fold is never 1 in UTC. In addition to being slightly faster in the common
case, this also prevents some errors when the timestamp is close to
@ref{f70,,datetime.min}.  Patch by Paul Ganssle.

@item 
gh-92530@footnote{https://github.com/python/cpython/issues/92530}: Fix an issue that occurred after interrupting
@ref{f71,,threading.Condition.notify()}.

@item 
gh-92049@footnote{https://github.com/python/cpython/issues/92049}: Forbid pickling constants @code{re._constants.SUCCESS} etc.
Previously, pickling did not fail, but the result could not be unpickled.

@item 
bpo-47029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47029}: Always close the read end of the pipe used by
@ref{f72,,multiprocessing.Queue} @emph{after} the last write of buffered data to
the write end of the pipe to avoid @ref{a87,,BrokenPipeError} at garbage
collection and at @ref{f73,,multiprocessing.Queue.close()} calls. Patch by Géry
Ogam.

@item 
gh-91910@footnote{https://github.com/python/cpython/issues/91910}: Add missing f prefix to f-strings in error messages from
the @ref{b7,,multiprocessing} and @ref{9,,asyncio} modules.

@item 
gh-91810@footnote{https://github.com/python/cpython/issues/91810}: @ref{21d,,ElementTree} method
@ref{a06,,write()} and function
@ref{a04,,tostring()} now use the text file's encoding
("UTF-8" if not available) instead of locale encoding in XML declaration
when @code{encoding="unicode"} is specified.

@item 
gh-91832@footnote{https://github.com/python/cpython/issues/91832}: Add @code{required} attribute to @ref{f74,,argparse.Action}
repr output.

@item 
gh-91734@footnote{https://github.com/python/cpython/issues/91734}: Fix OSS audio support on Solaris.

@item 
gh-91700@footnote{https://github.com/python/cpython/issues/91700}: Compilation of regular expression containing a conditional
expression @code{(?(group)...)} now raises an appropriate @ref{82e,,re.error} if
the group number refers to not defined group. Previously an internal
RuntimeError was raised.

@item 
gh-91676@footnote{https://github.com/python/cpython/issues/91676}: Fix @ref{37e,,unittest.IsolatedAsyncioTestCase} to shutdown
the per test event loop executor before returning from its @code{run} method
so that a not yet stopped or garbage collected executor state does not
persist beyond the test.

@item 
gh-90568@footnote{https://github.com/python/cpython/issues/90568}: Parsing @code{\N} escapes of Unicode Named Character
Sequences in a @ref{dd,,regular expression} raises now @ref{82e,,re.error}
instead of @code{TypeError}.

@item 
gh-91595@footnote{https://github.com/python/cpython/issues/91595}: Fix the comparison of character and integer inside
@code{Tools.gdb.libpython.write_repr()}. Patch by Yu Liu.

@item 
gh-90622@footnote{https://github.com/python/cpython/issues/90622}: Worker processes for
@ref{196,,concurrent.futures.ProcessPoolExecutor} are no longer spawned on
demand (a feature added in 3.9) when the multiprocessing context start
method is @code{"fork"} as that can lead to deadlocks in the child processes
due to a fork happening while threads are running.

@item 
gh-91575@footnote{https://github.com/python/cpython/issues/91575}: Update case-insensitive matching in the @ref{dd,,re} module
to the latest Unicode version.

@item 
gh-91581@footnote{https://github.com/python/cpython/issues/91581}: Remove an unhandled error case in the C implementation of
calls to @ref{f75,,datetime.fromtimestamp}
with no time zone (i.e. getting a local time from an epoch timestamp).
This should have no user-facing effect other than giving a possibly more
accurate error message when called with timestamps that fall on
10000-01-01 in the local time. Patch by Paul Ganssle.

@item 
bpo-34480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34480}: Fix a bug where @code{_markupbase} raised an
@ref{f3e,,UnboundLocalError} when an invalid keyword was found in marked
section. Patch by Marek Suscak.

@item 
bpo-27929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27929}: Fix @ref{79e,,asyncio.loop.sock_connect()} to only resolve names for
@ref{f76,,socket.AF_INET} or @ref{f77,,socket.AF_INET6} families. Resolution
may not make sense for other families, like @code{socket.AF_BLUETOOTH}
and @ref{f78,,socket.AF_UNIX}.

@item 
bpo-43323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43323}: Fix errors in the @ref{67,,email} module if the charset itself
contains undecodable/unencodable characters.

@item 
bpo-46787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46787}: Fix @ref{196,,concurrent.futures.ProcessPoolExecutor} exception
memory leak

@item 
bpo-46415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46415}: Fix ipaddress.ip_@{address,interface,network@} raising TypeError
instead of ValueError if given invalid tuple as address parameter.

@item 
bpo-44911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44911}: @ref{37e,,IsolatedAsyncioTestCase} will no longer throw
an exception while cancelling leaked tasks. Patch by Bar Harel.

@item 
bpo-44493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44493}: Add missing terminated NUL in sockaddr_un's length

This was potentially observable when using non-abstract AF_UNIX datagram
sockets to processes written in another programming language.

@item 
bpo-42627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42627}: Fix incorrect parsing of Windows registry proxy settings

@item 
bpo-36073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36073}: Raise @ref{f79,,ProgrammingError} instead of segfaulting
on recursive usage of cursors in @ref{f2,,sqlite3} converters. Patch by
Sergey Fedoseev.
@end itemize

@node Documentation,Tests<2>,Library<4>,Python 3 9 13 final
@anchor{whatsnew/changelog documentation}@anchor{f7a}
@subsubsection Documentation



@itemize -

@item 
gh-91888@footnote{https://github.com/python/cpython/issues/91888}: Add a new @code{gh} role to the documentation to link to
GitHub issues.

@item 
gh-91783@footnote{https://github.com/python/cpython/issues/91783}: Document security issues concerning the use of the
function @ref{28b,,shutil.unpack_archive()}

@item 
gh-91547@footnote{https://github.com/python/cpython/issues/91547}: Remove "Undocumented modules" page.

@item 
bpo-44347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44347}: Clarify the meaning of @emph{dirs_exist_ok}, a kwarg of
@ref{34e,,shutil.copytree()}.

@item 
bpo-38668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38668}: Update the introduction to documentation for @ref{c5,,os.path} to
remove warnings that became irrelevant after the implementations of
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383} and 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529}.

@item 
bpo-47138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47138}: Pin Jinja to a version compatible with Sphinx version 2.4.4.

@item 
bpo-46962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46962}: All docstrings in code snippets are now wrapped into
@code{PyDoc_STR()} to follow the guideline of PEP 7's Documentation Strings paragraph@footnote{https://www.python.org/dev/peps/pep-0007/#documentation-strings}. Patch
by Oleg Iarygin.

@item 
bpo-26792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26792}: Improve the docstrings of @ref{f7b,,runpy.run_module()} and
@ref{d81,,runpy.run_path()}. Original patch by Andrew Brezovsky.

@item 
bpo-45790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45790}: Adjust inaccurate phrasing in
@ref{f7c,,自定义扩展类型：教程} about the @code{ob_base} field and the
macros used to access its contents.

@item 
bpo-42340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42340}: Document that in some circumstances @ref{2d3,,KeyboardInterrupt}
may cause the code to enter an inconsistent state. Provided a sample
workaround to avoid it if needed.

@item 
bpo-41233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41233}: Link the errnos referenced in @code{Doc/library/exceptions.rst} to
their respective section in @code{Doc/library/errno.rst}, and vice versa.
Previously this was only done for EINTR and InterruptedError. Patch by Yan
"yyyyyyyan" Orestes.

@item 
bpo-38056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38056}: Overhaul the @ref{f7d,,错误处理方案} documentation in
@ref{1b,,codecs}.

@item 
bpo-13553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13553}: Document tkinter.Tk args.
@end itemize

@node Tests<2>,Build,Documentation,Python 3 9 13 final
@anchor{whatsnew/changelog id13}@anchor{f7e}
@subsubsection Tests



@itemize -

@item 
gh-91607@footnote{https://github.com/python/cpython/issues/91607}: Fix @code{test_concurrent_futures} to test the correct
multiprocessing start method context in several cases where the test logic
mixed this up.

@item 
bpo-47205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47205}: Skip test for @ref{b35,,sched_getaffinity()} and
@ref{b39,,sched_setaffinity()} error case on FreeBSD.

@item 
bpo-29890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29890}: Add tests for @ref{f7f,,ipaddress.IPv4Interface} and
@ref{f80,,ipaddress.IPv6Interface} construction with tuple arguments.
Original patch and tests by louisom.
@end itemize

@node Build,Windows<3>,Tests<2>,Python 3 9 13 final
@anchor{whatsnew/changelog build}@anchor{f81}
@subsubsection Build



@itemize -

@item 
bpo-47103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47103}: Windows @code{PGInstrument} builds now copy a required DLL into
the output directory, making it easier to run the profile stage of a PGO
build.
@end itemize

@node Windows<3>,Tools/Demos,Build,Python 3 9 13 final
@anchor{whatsnew/changelog id14}@anchor{f82}
@subsubsection Windows



@itemize -

@item 
bpo-47194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47194}: Update @code{zlib} to v1.2.12 to resolve CVE-2018-25032.

@item 
bpo-46785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46785}: Fix race condition between @ref{328,,os.stat()} and unlinking a file
on Windows, by using errors codes returned by @code{FindFirstFileW()} when
appropriate in @code{win32_xstat_impl}.

@item 
bpo-40859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40859}: Update Windows build to use xz-5.2.5
@end itemize

@node Tools/Demos,,Windows<3>,Python 3 9 13 final
@anchor{whatsnew/changelog tools-demos}@anchor{f83}
@subsubsection Tools/Demos



@itemize -

@item 
gh-91583@footnote{https://github.com/python/cpython/issues/91583}: Fix regression in the code generated by Argument Clinic
for functions with the @code{defining_class} parameter.
@end itemize

@node Python 3 9 12 final,Python 3 9 11 final,Python 3 9 13 final,更新日志
@anchor{whatsnew/changelog python-3-9-12-final}@anchor{f84}
@subsection Python 3.9.12 final


@emph{Release date: 2022-03-23}

@menu
* Core and Builtins: Core and Builtins<5>. 
* Library: Library<5>. 

@end menu

@node Core and Builtins<5>,Library<5>,,Python 3 9 12 final
@anchor{whatsnew/changelog id15}@anchor{f85}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46968}: Check for the existence of the "sys/auxv.h" header in
@ref{7b,,faulthandler} to avoid compilation problems in systems where this
header doesn't exist. Patch by Pablo Galindo
@end itemize

@node Library<5>,,Core and Builtins<5>,Python 3 9 12 final
@anchor{whatsnew/changelog id16}@anchor{f86}
@subsubsection Library



@itemize -

@item 
bpo-47101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47101}: @ref{dcb,,hashlib.algorithms_available} now lists only algorithms
that are provided by activated crypto providers on OpenSSL 3.0. Legacy
algorithms are not listed unless the legacy provider has been loaded into
the default OSSL context.

@item 
bpo-23691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23691}: Protect the @ref{f87,,re.finditer()} iterator from re-entering.

@item 
bpo-42369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42369}: Fix thread safety of @code{zipfile._SharedFile.tell()} to avoid
a "zipfile.BadZipFile: Bad CRC-32 for file" exception when reading a
@code{ZipFile} from multiple threads.

@item 
bpo-38256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38256}: Fix @ref{f88,,binascii.crc32()} when it is compiled to use zlib'c
crc32 to work properly on inputs 4+GiB in length instead of returning the
wrong result. The workaround prior to this was to always feed the function
data in increments smaller than 4GiB or to just call the zlib module
function.

@item 
bpo-39394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39394}: A warning about inline flags not at the start of the regular
expression now contains the position of the flag.

@item 
bpo-47061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47061}: Deprecate the various modules listed by 
@geindex Python 提高建议; PEP 594
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594}:

aifc, asynchat, asyncore, audioop, cgi, cgitb, chunk, crypt, imghdr,
msilib, nntplib, nis, ossaudiodev, pipes, smtpd, sndhdr, spwd, sunau,
telnetlib, uu, xdrlib

@item 
bpo-2604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2604}: Fix bug where doctests using globals would fail when run
multiple times.

@item 
bpo-45997@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45997}: Fix @ref{3b9,,asyncio.Semaphore} re-aquiring FIFO order.

@item 
bpo-47022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47022}: The @ref{8,,asynchat}, @ref{a,,asyncore} and  @ref{ec,,smtpd} modules
have been deprecated since at least Python 3.6. Their documentation has
now been updated to note they will removed in Python 3.12 (
@geindex Python 提高建议; PEP 594
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594}).

@item 
bpo-46421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46421}: Fix a unittest issue where if the command was invoked as
@code{python -m unittest} and the filename(s) began with a dot (.), a
@code{ValueError} is returned.

@item 
bpo-40296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40296}: Fix supporting generic aliases in @ref{d9,,pydoc}.

@item 
bpo-14156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14156}: argparse.FileType now supports an argument of '-' in binary
mode, returning the .buffer attribute of sys.stdin/sys.stdout as
appropriate. Modes including 'x' and 'a' are treated equivalently to 'w'
when argument is '-'. Patch contributed by Josh Rosenberg
@end itemize

@node Python 3 9 11 final,Python 3 9 10 final,Python 3 9 12 final,更新日志
@anchor{whatsnew/changelog python-3-9-11-final}@anchor{f89}
@subsection Python 3.9.11 final


@emph{Release date: 2022-03-16}

@menu
* Core and Builtins: Core and Builtins<6>. 
* Library: Library<6>. 
* Documentation: Documentation<2>. 
* Tests: Tests<3>. 
* Build: Build<2>. 
* Windows: Windows<4>. 
* macOS: macOS<3>. 
* IDLE: IDLE<3>. 

@end menu

@node Core and Builtins<6>,Library<6>,,Python 3 9 11 final
@anchor{whatsnew/changelog id17}@anchor{f8a}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46852}: Rename the private undocumented @code{float.__set_format__()}
method to @code{float.__setformat__()} to fix a typo introduced in Python
3.7. The method is only used by test_float. Patch by Victor Stinner.

@item 
bpo-46794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46794}: Bump up the libexpat version into 2.4.6

@item 
bpo-46762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46762}: Fix an assert failure in debug builds when a '<', '>', or '='
is the last character in an f-string that's missing a closing right brace.

@item 
bpo-46732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46732}: Correct the docstring for the @ref{d38,,__bool__()} method. Patch by
Jelle Zijlstra.

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Add a missing call to @code{va_end()} in
@code{Modules/_hashopenssl.c}.

@item 
bpo-46615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46615}: When iterating over sets internally in @code{setobject.c}, acquire
strong references to the resulting items from the set.  This prevents
crashes in corner-cases of various set operations where the set gets
mutated.

@item 
bpo-43721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43721}: Fix docstrings of @code{getter},
@code{setter}, and @code{deleter} to clarify that
they create a new copy of the property.

@item 
bpo-46503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46503}: Fix an assert when parsing some invalid N escape sequences in
f-strings.

@item 
bpo-46417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46417}: Fix a race condition on setting a type @code{__bases__} attribute:
the internal function @code{add_subclass()} now gets the
@code{PyTypeObject.tp_subclasses} member after calling
@ref{f8b,,PyWeakref_NewRef()} which can trigger a garbage collection which
can indirectly modify @code{PyTypeObject.tp_subclasses}. Patch by Victor
Stinner.

@item 
bpo-46383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46383}: Fix invalid signature of @code{_zoneinfo}'s @code{module_free}
function to resolve a crash on wasm32-emscripten platform.
@end itemize

@node Library<6>,Documentation<2>,Core and Builtins<6>,Python 3 9 11 final
@anchor{whatsnew/changelog id18}@anchor{f8c}
@subsubsection Library



@itemize -

@item 
bpo-43253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43253}: Fix a crash when closing transports where the underlying socket
handle is already invalid on the Proactor event loop.

@item 
bpo-47004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47004}: Apply bugfixes from importlib_metadata 4.11.3, including bugfix
for EntryPoint.extras, which was returning match objects and not the
extras strings.

@item 
bpo-46985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46985}: Upgrade pip wheel bundled with ensurepip (pip 22.0.4)

@item 
bpo-46968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46968}: @ref{7b,,faulthandler}: On Linux 5.14 and newer, dynamically
determine size of signal handler stack size CPython allocates using
@code{getauxval(AT_MINSIGSTKSZ)}. This changes allows for Python extension's
request to Linux kernel to use AMX_TILE instruction set on Sapphire Rapids
Xeon processor to succeed, unblocking use of the ISA in frameworks.

@item 
bpo-46955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46955}: Expose @code{asyncio.base_events.Server} as
@ref{46d,,asyncio.Server}. Patch by Stefan Zabka.

@item 
bpo-46932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46932}: Update bundled libexpat to 2.4.7

@item 
bpo-25707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25707}: Fixed a file leak in @ref{a32,,xml.etree.ElementTree.iterparse()}
when the iterator is not exhausted. Patch by Jacob Walls.

@item 
bpo-44886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44886}: Inherit asyncio proactor datagram transport from
@ref{f8d,,asyncio.DatagramTransport}.

@item 
bpo-46827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46827}: Support UDP sockets in  @ref{79e,,asyncio.loop.sock_connect()} for
selector-based event loops.  Patch by Thomas Grainger.

@item 
bpo-46811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46811}: Make test suite support Expat >=2.4.5

@item 
bpo-46252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46252}: Raise @ref{1ff,,TypeError} if @ref{192,,ssl.SSLSocket} is passed to
transport-based APIs.

@item 
bpo-46784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46784}: Fix libexpat symbols collisions with user dynamically loaded or
statically linked libexpat in embedded Python.

@item 
bpo-39327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39327}: @ref{350,,shutil.rmtree()} can now work with VirtualBox shared
folders when running from the guest operating-system.

@item 
bpo-46756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46756}: Fix a bug in
@ref{f8e,,urllib.request.HTTPPasswordMgr.find_user_password()} and
@ref{f8f,,urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated()} which
allowed to bypass authorization. For example, access to URI
@code{example.org/foobar} was allowed if the user was authorized for URI
@code{example.org/foo}.

@item 
bpo-45863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45863}: When the @ref{101,,tarfile} module creates a pax format archive, it
will put an integer representation of timestamps in the ustar header (if
possible) for the benefit of older unarchivers, in addition to the
existing full-precision timestamps in the pax extended header.

@item 
bpo-46672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46672}: Fix @code{NameError} in @ref{3b3,,asyncio.gather()} when initial type
check fails.

@item 
bpo-45948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45948}: Fixed a discrepancy in the C implementation of the
@ref{140,,xml.etree.ElementTree} module. Now, instantiating an
@ref{383,,xml.etree.ElementTree.XMLParser} with a @code{target=None} keyword
provides a default @ref{384,,xml.etree.ElementTree.TreeBuilder} target as
the Python implementation does.

@item 
bpo-46591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46591}: Make the IDLE doc URL on the About IDLE dialog clickable.

@item 
bpo-46400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46400}: expat: Update libexpat from 2.4.1 to 2.4.4

@item 
bpo-46487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46487}: Add the @code{get_write_buffer_limits} method to
@code{asyncio.transports.WriteTransport} and to the SSL transport.

@item 
bpo-46539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46539}: In @ref{1f0,,typing.get_type_hints()}, support evaluating
stringified @code{ClassVar} and @code{Final} annotations inside @code{Annotated}.
Patch by Gregory Beauregard.

@item 
bpo-46491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46491}: Allow @ref{1ef,,typing.Annotated} to wrap @ref{36f,,typing.Final} and
@ref{6a4,,typing.ClassVar}. Patch by Gregory Beauregard.

@item 
bpo-46436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46436}: Fix command-line option @code{-d}/@code{--directory} in module
@ref{96,,http.server} which is ignored when combined with command-line option
@code{--cgi}. Patch by Géry Ogam.

@item 
bpo-41403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41403}: Make @code{mock.patch()} raise a @ref{1ff,,TypeError} with a
relevant error message on invalid arg. Previously it allowed a cryptic
@ref{4aa,,AttributeError} to escape.

@item 
bpo-46474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46474}: In @code{importlib.metadata.EntryPoint.pattern}, avoid potential
REDoS by limiting ambiguity in consecutive whitespace.

@item 
bpo-46469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46469}: @ref{9,,asyncio} generic classes now return
@ref{27d,,types.GenericAlias} in @code{__class_getitem__} instead of the same
class.

@item 
bpo-46434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46434}: @ref{c9,,pdb} now gracefully handles @code{help} when @code{__doc__}
is missing, for example when run with pregenerated optimized @code{.pyc}
files.

@item 
bpo-46333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46333}: The @ref{454,,__eq__()} and @ref{455,,__hash__()} methods of
@ref{f90,,typing.ForwardRef} now honor the @code{module} parameter of
@ref{f90,,typing.ForwardRef}. Forward references from different modules are
now differentiated.

@item 
bpo-43118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43118}: Fix a bug in @ref{65e,,inspect.signature()} that was causing it to
fail on some subclasses of classes with a @code{__text_signature__}
referencing module globals. Patch by Weipeng Hong.

@item 
bpo-21987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21987}: Fix an issue with @ref{f91,,tarfile.TarFile.getmember()} getting a
directory name with a trailing slash.

@item 
bpo-20392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20392}: Fix inconsistency with uppercase file extensions in
@code{MimeTypes.guess_type()}. Patch by Kumar Aditya.

@item 
bpo-46080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46080}: Fix exception in argparse help text generation if a
@code{argparse.BooleanOptionalAction} argument's default is
@code{argparse.SUPPRESS} and it has @code{help} specified.  Patch by Felix
Fontein.

@item 
bpo-44439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44439}: Fix @code{.write()} method of a member file in @code{ZipFile}, when
the input data is an object that supports the buffer protocol, the file
length may be wrong.

@item 
bpo-45703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45703}: When a namespace package is imported before another module from
the same namespace is created/installed in a different @ref{262,,sys.path}
location while the program is running, calling the
@ref{59f,,importlib.invalidate_caches()} function will now also guarantee the
new module is noticed.

@item 
bpo-24959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24959}: Fix bug where @ref{124,,unittest} sometimes drops frames from
tracebacks of exceptions raised in tests.
@end itemize

@node Documentation<2>,Tests<3>,Library<6>,Python 3 9 11 final
@anchor{whatsnew/changelog id19}@anchor{f92}
@subsubsection Documentation



@itemize -

@item 
bpo-46463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46463}: Fixes @code{escape4chm.py} script used when building the CHM
documentation file
@end itemize

@node Tests<3>,Build<2>,Documentation<2>,Python 3 9 11 final
@anchor{whatsnew/changelog id20}@anchor{f93}
@subsubsection Tests



@itemize -

@item 
bpo-46913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46913}: Fix test_faulthandler.test_sigfpe() if Python is built with
undefined behavior sanitizer (UBSAN): disable UBSAN on the
faulthandler_sigfpe() function. Patch by Victor Stinner.

@item 
bpo-46708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46708}: Prevent default asyncio event loop policy modification warning
after @code{test_asyncio} execution.

@item 
bpo-46616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46616}: Ensures @code{test_importlib.test_windows} cleans up registry keys
after completion.

@item 
bpo-44359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44359}: test_ftplib now silently ignores socket errors to prevent
logging unhandled threading exceptions. Patch by Victor Stinner.

@item 
bpo-46542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46542}: Fix a Python crash in test_lib2to3 when using Python built in
debug mode: limit the recursion limit. Patch by Victor Stinner.

@item 
bpo-46576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46576}: test_peg_generator now disables compiler optimization when
testing compilation of its own C extensions to significantly speed up the
testing on non-debug builds of CPython.

@item 
bpo-46542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46542}: Fix @code{test_json} tests checking for @ref{731,,RecursionError}:
modify these tests to use @code{support.infinite_recursion()}. Patch by
Victor Stinner.

@item 
bpo-13886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13886}: Skip test_builtin PTY tests on non-ASCII characters if the
readline module is loaded. The readline module changes input() behavior,
but test_builtin is not intented to test the readline module. Patch by
Victor Stinner.
@end itemize

@node Build<2>,Windows<4>,Tests<3>,Python 3 9 11 final
@anchor{whatsnew/changelog id21}@anchor{f94}
@subsubsection Build



@itemize -

@item 
bpo-47024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47024}: Update OpenSSL to 1.1.1n for macOS installers and all Windows
builds.

@item 
bpo-38472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38472}: Fix GCC detection in setup.py when cross-compiling. The C
compiler is now run with LC_ALL=C. Previously, the detection failed with a
German locale.

@item 
bpo-46513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46513}: @code{configure} no longer uses @code{AC_C_CHAR_UNSIGNED}
macro and @code{pyconfig.h} no longer defines reserved symbol
@code{__CHAR_UNSIGNED__}.

@item 
bpo-45925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45925}: Update Windows installer to use SQLite 3.37.2.

@item 
bpo-47032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=47032}: Ensure Windows install builds fail correctly with a non-zero
exit code when part of the build fails.
@end itemize

@node Windows<4>,macOS<3>,Build<2>,Python 3 9 11 final
@anchor{whatsnew/changelog id22}@anchor{f95}
@subsubsection Windows



@itemize -

@item 
bpo-44549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44549}: Update bzip2 to 1.0.8 in Windows builds to mitigate
CVE-2016-3189 and CVE-2019-12900

@item 
bpo-46948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46948}: Prevent CVE-2022-26488 by ensuring the Add to PATH option in
the Windows installer uses the correct path when being repaired.

@item 
bpo-46638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46638}: Ensures registry virtualization is consistently disabled. For
3.10 and earlier, it remains enabled (some registry writes are protected),
while for 3.11 and later it is disabled (registry modifications affect all
applications).
@end itemize

@node macOS<3>,IDLE<3>,Windows<4>,Python 3 9 11 final
@anchor{whatsnew/changelog id23}@anchor{f96}
@subsubsection macOS



@itemize -

@item 
bpo-45925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45925}: Update macOS installer to SQLite 3.37.2.
@end itemize

@node IDLE<3>,,macOS<3>,Python 3 9 11 final
@anchor{whatsnew/changelog idle}@anchor{f97}
@subsubsection IDLE



@itemize -

@item 
bpo-46630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46630}: Make query dialogs on Windows start with a cursor in the entry
box.

@item 
bpo-45296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45296}: Clarify close, quit, and exit in IDLE.  In the File menu,
'Close' and 'Exit' are now 'Close Window' (the current one) and 'Exit' is
now 'Exit IDLE' (by closing all windows).  In Shell, 'quit()' and 'exit()'
mean 'close Shell'. If there are no other windows, this also exits IDLE.

@item 
bpo-45447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45447}: Apply IDLE syntax highlighting to @code{pyi} files. Patch by Alex
Waygood and Terry Jan Reedy.
@end itemize

@node Python 3 9 10 final,Python 3 9 9 final,Python 3 9 11 final,更新日志
@anchor{whatsnew/changelog python-3-9-10-final}@anchor{f98}
@subsection Python 3.9.10 final


@emph{Release date: 2022-01-13}

@menu
* Core and Builtins: Core and Builtins<7>. 
* Library: Library<7>. 
* Documentation: Documentation<3>. 
* Tests: Tests<4>. 
* Build: Build<3>. 
* Windows: Windows<5>. 
* macOS: macOS<4>. 
* Tools/Demos: Tools/Demos<2>. 
* C API:: 

@end menu

@node Core and Builtins<7>,Library<7>,,Python 3 9 10 final
@anchor{whatsnew/changelog id24}@anchor{f99}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-46070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46070}: @ref{f9a,,Py_EndInterpreter()} now explicitly untracks all objects
currently tracked by the GC. Previously, if an object was used later by
another interpreter, calling @ref{f0f,,PyObject_GC_UnTrack()} on the object
crashed if the previous or the next object of the @code{PyGC_Head}
structure became a dangling pointer. Patch by Victor Stinner.

@item 
bpo-46085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46085}: Fix iterator cache mechanism of @code{OrderedDict}.

@item 
bpo-46110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46110}: Add a maximum recursion check to the PEG parser to avoid stack
overflow. Patch by Pablo Galindo

@item 
bpo-46000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46000}: Improve compatibility of the @ref{2b,,curses} module with NetBSD
curses.

@item 
bpo-45614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45614}: Fix @ref{11c,,traceback} display for exceptions with invalid module
name.

@item 
bpo-45806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45806}: Re-introduced fix that allows recovery from stack overflow
without crashing the interpreter.  The original fix as part of
bpo-42500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42500} was reverted (see release notes for Python 3.9.4) since it
introduced an ABI change in a bugfix release which is not allowed.  The
new fix doesn't introduce any ABI changes.  Patch by Mark Shannon.

@item 
bpo-45822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45822}: Fixed a bug in the parser that was causing it to not respect
@geindex Python 提高建议; PEP 263
PEP 263@footnote{https://www.python.org/dev/peps/pep-0263} coding cookies when no flags are provided. Patch by Pablo
Galindo

@item 
bpo-45820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45820}: Fix a segfault when the parser fails without reading any input.
Patch by Pablo Galindo

@item 
bpo-42540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42540}: Fix crash when @ref{a4b,,os.fork()} is called with an active
non-default memory allocator.
@end itemize

@node Library<7>,Documentation<3>,Core and Builtins<7>,Python 3 9 10 final
@anchor{whatsnew/changelog id25}@anchor{f9b}
@subsubsection Library



@itemize -

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Fix @ref{8c,,hashlib} @emph{usedforsecurity} option to work correctly
with OpenSSL 3.0.0 in FIPS mode.

@item 
bpo-46070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46070}: Fix possible segfault when importing the @ref{9,,asyncio} module
from different sub-interpreters in parallel. Patch by Erlend E. Aasland.

@item 
bpo-46278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46278}: Reflect @code{context} argument in @code{AbstractEventLoop.call_*()}
methods. Loop implementations already support it.

@item 
bpo-46239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46239}: Improve error message when importing
@code{asyncio.windows_events} on non-Windows.

@item 
bpo-20369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20369}: @ref{f9c,,concurrent.futures.wait()} no longer blocks forever when
given duplicate Futures. Patch by Kumar Aditya.

@item 
bpo-46105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46105}: Honor spec when generating requirement specs with urls and
extras (importlib_metadata 4.8.3).

@item 
bpo-26952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26952}: @ref{5,,argparse} raises @ref{16d,,ValueError} with clear message
when trying to render usage for an empty mutually-exclusive group.
Previously it raised a cryptic @ref{f3d,,IndexError}.

@item 
bpo-27718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27718}: Fix help for the @ref{ea,,signal} module. Some functions (e.g.
@code{signal()} and @code{getsignal()}) were omitted.

@item 
bpo-46032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46032}: The @code{registry()} method of @ref{499,,functools.singledispatch()}
functions checks now the first argument or the first parameter annotation
and raises a TypeError if it is not supported. Previously unsupported
"types" were ignored (e.g. @code{typing.List[int]}) or caused an error at
calling time (e.g. @code{list[int]}).

@item 
bpo-46018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46018}: Ensure that @ref{c43,,math.expm1()} does not raise on underflow.

@item 
bpo-27946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27946}: Fix possible crash when getting an attribute of
class:@ref{21e,,xml.etree.ElementTree.Element} simultaneously with replacing the
@code{attrib} dict.

@item 
bpo-13236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13236}: @ref{f9d,,unittest.TextTestResult} and
@ref{f9e,,unittest.TextTestRunner} flush now the output stream more often.

@item 
bpo-37658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37658}: Fix issue when on certain conditions @code{asyncio.wait_for()} may
allow a coroutine to complete successfully, but fail to return the result,
potentially causing memory leaks or other issues.

@item 
bpo-45831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45831}: @ref{7b,,faulthandler} can now write ASCII-only strings (like
filenames and function names) with a single write() syscall when dumping a
traceback. It reduces the risk of getting an unreadable dump when two
threads or two processes dump a traceback to the same file (like stderr)
at the same time. Patch by Victor Stinner.

@item 
bpo-41735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41735}: Fix thread lock in @code{zlib.Decompress.flush()} method before
@code{PyObject_GetBuffer}.

@item 
bpo-45664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45664}: Fix @ref{513,,types.resolve_bases()} and @ref{b98,,types.new_class()} for
@ref{27d,,types.GenericAlias} instance as a base.

@item 
bpo-45663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45663}: Fix @ref{f9f,,dataclasses.is_dataclass()} for dataclasses which are
subclasses of @ref{27d,,types.GenericAlias}.

@item 
bpo-45662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45662}: Fix the repr of @code{dataclasses.InitVar} with a type alias
to the built-in class, e.g. @code{InitVar[list[int]]}.

@item 
bpo-43498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43498}: Avoid a possible @emph{"RuntimeError: dictionary changed size during
iteration"} when adjusting the process count of
@code{ProcessPoolExecutor}.

@item 
bpo-29620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29620}: @ref{b9d,,assertWarns()} no longer raises a
@code{RuntimeException} when accessing a module's @code{__warningregistry__}
causes importation of a new module, or when a new module is imported in
another thread. Patch by Kernc.
@end itemize

@node Documentation<3>,Tests<4>,Library<7>,Python 3 9 10 final
@anchor{whatsnew/changelog id26}@anchor{fa0}
@subsubsection Documentation



@itemize -

@item 
bpo-19737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19737}: Update the documentation for the @ref{fa1,,globals()} function.

@item 
bpo-45840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45840}: Improve cross-references in the documentation for the data
model.

@item 
bpo-45788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45788}: Link doc for sys.prefix to sysconfig doc on installation paths.

@item 
bpo-25381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25381}: In the extending chapter of the extending doc, update a
paragraph about the global variables containing exception information.

@item 
bpo-43905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43905}: Expanded @ref{fa2,,astuple()} and
@ref{fa3,,asdict()} docs, warning about deepcopy being applied and
providing a workaround.

@item 
bpo-41028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41028}: Language and version switchers, previously maintained in every
cpython branches, are now handled by docsbuild-script.
@end itemize

@node Tests<4>,Build<3>,Documentation<3>,Python 3 9 10 final
@anchor{whatsnew/changelog id27}@anchor{fa4}
@subsubsection Tests



@itemize -

@item 
bpo-46205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46205}: Fix hang in runtest_mp due to race condition

@item 
bpo-46263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46263}: Fix test_capi on FreeBSD 14-dev: instruct jemalloc to not fill
freed memory with junk byte.

@item 
bpo-46150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46150}: Now @code{fakename} in
@code{test_pathlib.PosixPathTest.test_expanduser} is checked to be
non-existent.

@item 
bpo-46129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46129}: Rewrite @code{asyncio.locks} tests with
@ref{37e,,unittest.IsolatedAsyncioTestCase} usage.

@item 
bpo-23819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23819}: Fixed @ref{9,,asyncio} tests in python optimized mode. Patch by
Kumar Aditya.

@item 
bpo-46114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46114}: Fix test case for OpenSSL 3.0.1 version. OpenSSL 3.0 uses
@code{0xMNN00PP0L}.

@item 
bpo-19460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19460}: Add new Test for
@ref{fa5,,email.mime.nonmultipart.MIMENonMultipart}.

@item 
bpo-45835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45835}: Fix race condition in test_queue tests with multiple "feeder"
threads.
@end itemize

@node Build<3>,Windows<5>,Tests<4>,Python 3 9 10 final
@anchor{whatsnew/changelog id28}@anchor{fa6}
@subsubsection Build



@itemize -

@item 
bpo-46263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46263}: @code{configure} no longer sets @code{MULTIARCH} on FreeBSD
platforms.

@item 
bpo-46106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=46106}: Updated OpenSSL to 1.1.1m in Windows builds, macOS installer
builds, and CI. Patch by Kumar Aditya.

@item 
bpo-44035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44035}: CI now verifies that autoconf files have been regenerated with
a current and unpatched autoconf package.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update @code{config.guess} to 2021-06-03 and @code{config.sub} to
2021-08-14. @code{Makefile} now has an @code{update-config} target to make
updating more convenient.

@item 
bpo-45866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45866}: @code{make regen-all} now produces the same output when run from a
directory other than the source tree: when building Python out of the
source tree. pegen now strips directory of the "generated by pygen from
<FILENAME>" header Patch by Victor Stinner.

@item 
bpo-41498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41498}: Python now compiles on platforms without @code{sigset_t}. Several
functions in @ref{ea,,signal} are not available when @code{sigset_t} is missing.

Based on patch by Roman Yurchak for pyodide.

@item 
bpo-45881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45881}: @code{setup.py} now uses @code{CC} from environment first to discover
multiarch and cross compile paths.
@end itemize

@node Windows<5>,macOS<4>,Build<3>,Python 3 9 10 final
@anchor{whatsnew/changelog id29}@anchor{fa7}
@subsubsection Windows



@itemize -

@item 
bpo-45901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45901}: When installed through the Microsoft Store and set as the
default app for @code{*.py} files, command line arguments will now be
passed to Python when invoking a script without explicitly launching
Python (that is, @code{script.py args} rather than @code{python script.py
args}).
@end itemize

@node macOS<4>,Tools/Demos<2>,Windows<5>,Python 3 9 10 final
@anchor{whatsnew/changelog id30}@anchor{fa8}
@subsubsection macOS



@itemize -

@item 
bpo-40477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40477}: The Python Launcher app for macOS now properly launches scripts
and, if necessary, the Terminal app when running on recent macOS releases.

@item 
bpo-45732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45732}: Update python.org macOS installer to use Tcl/Tk 8.6.12.
@end itemize

@node Tools/Demos<2>,C API,macOS<4>,Python 3 9 10 final
@anchor{whatsnew/changelog id31}@anchor{fa9}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-45838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45838}: Fix line number calculation when debugging Python with GDB.
@end itemize

@node C API,,Tools/Demos<2>,Python 3 9 10 final
@anchor{whatsnew/changelog c-api}@anchor{faa}
@subsubsection C API



@itemize -

@item 
bpo-39026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39026}: Fix Python.h to build C extensions with Xcode: remove a
relative include from @code{Include/cpython/pystate.h}.
@end itemize

@node Python 3 9 9 final,Python 3 9 8 final,Python 3 9 10 final,更新日志
@anchor{whatsnew/changelog python-3-9-9-final}@anchor{fab}
@subsection Python 3.9.9 final


@emph{Release date: 2021-11-15}

@menu
* Core and Builtins: Core and Builtins<8>. 
* Library: Library<8>. 
* Documentation: Documentation<4>. 
* Windows: Windows<6>. 

@end menu

@node Core and Builtins<8>,Library<8>,,Python 3 9 9 final
@anchor{whatsnew/changelog id32}@anchor{fac}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45738}: Fix computation of error location for invalid continuation
characters in the parser. Patch by Pablo Galindo.
@end itemize

@node Library<8>,Documentation<4>,Core and Builtins<8>,Python 3 9 9 final
@anchor{whatsnew/changelog id33}@anchor{fad}
@subsubsection Library



@itemize -

@item 
bpo-45235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45235}: Reverted an argparse bugfix that caused regression in the
handling of default arguments for subparsers.  This prevented leaf level
arguments from taking precedence over root level arguments.

@item 
bpo-45765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45765}: In importlib.metadata, fix distribution discovery for an empty
path.

@item 
bpo-45644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45644}: In-place JSON file formatting using @code{python3 -m json.tool
infile infile} now works correctly, previously it left the file empty.
Patch by Chris Wesseling.
@end itemize

@node Documentation<4>,Windows<6>,Library<8>,Python 3 9 9 final
@anchor{whatsnew/changelog id34}@anchor{fae}
@subsubsection Documentation



@itemize -

@item 
bpo-45772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45772}: @code{socket.socket} documentation is corrected to a class from a
function.

@item 
bpo-45392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45392}: Update the docstring of the @ref{709,,type} built-in to remove a
redundant line and to mention keyword arguments for the constructor.
@end itemize

@node Windows<6>,,Documentation<4>,Python 3 9 9 final
@anchor{whatsnew/changelog id35}@anchor{faf}
@subsubsection Windows



@itemize -

@item 
bpo-45732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45732}: Updates bundled Tcl/Tk to 8.6.12.

@item 
bpo-45720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45720}: Internal reference to @code{shlwapi.dll} was dropped to help
improve startup time. This DLL will no longer be loaded at the start of
every Python process.
@end itemize

@node Python 3 9 8 final,Python 3 9 7 final,Python 3 9 9 final,更新日志
@anchor{whatsnew/changelog python-3-9-8-final}@anchor{fb0}
@subsection Python 3.9.8 final


@emph{Release date: 2021-11-05}

@menu
* Core and Builtins: Core and Builtins<9>. 
* Library: Library<9>. 
* Documentation: Documentation<5>. 
* Tests: Tests<5>. 
* Build: Build<4>. 
* Windows: Windows<7>. 
* macOS: macOS<5>. 
* IDLE: IDLE<4>. 
* C API: C API<2>. 

@end menu

@node Core and Builtins<9>,Library<9>,,Python 3 9 8 final
@anchor{whatsnew/changelog id36}@anchor{fb1}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-30570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30570}: Fixed a crash in @code{issubclass()} from infinite recursion when
searching pathological @code{__bases__} tuples.

@item 
bpo-45494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45494}: Fix parser crash when reporting errors involving invalid
continuation characters. Patch by Pablo Galindo.

@item 
bpo-45385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45385}: Fix reference leak from descr_check. Patch by Dong-hee Na.

@item 
bpo-45167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45167}: Fix deepcopying of @ref{27d,,types.GenericAlias} objects.

@item 
bpo-44219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44219}: Release the GIL while performing @code{isatty} system calls on
arbitrary file descriptors. In particular, this affects @ref{fb2,,os.isatty()},
@ref{fb3,,os.device_encoding()} and @ref{6f4,,io.TextIOWrapper}. By extension,
@ref{757,,io.open()} in text mode is also affected. This change solves a
deadlock in @ref{fb2,,os.isatty()}. Patch by Vincent Michel in bpo-44219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44219}.

@item 
bpo-44959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44959}: Added fallback to extension modules with '.sl' suffix on HP-UX

@item 
bpo-44050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44050}: Extensions that indicate they use global state (by setting
@code{m_size} to -1) can again be used in multiple interpreters. This reverts
to behavior of Python 3.8.

@item 
bpo-45121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45121}: Fix issue where @code{Protocol.__init__} raises @code{RecursionError}
when it's called directly or via @code{super()}. Patch provided by Yurii
Karabas.

@item 
bpo-45083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45083}: When the interpreter renders an exception, its name now has a
complete qualname. Previously only the class name was concatenated to the
module name, which sometimes resulted in an incorrect full name being
displayed.

(This issue impacted only the C code exception rendering, the
@ref{11c,,traceback} module was using qualname already).
@end itemize

@node Library<9>,Documentation<5>,Core and Builtins<9>,Python 3 9 8 final
@anchor{whatsnew/changelog id37}@anchor{fb4}
@subsubsection Library



@itemize -

@item 
bpo-45678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45678}: Fix bug in Python 3.9 that meant
@code{functools.singledispatchmethod} failed to properly wrap the attributes
of the target method. Patch by Alex Waygood.

@item 
bpo-45679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45679}: Fix caching of multi-value @ref{276,,typing.Literal}.
@code{Literal[True, 2]} is no longer equal to @code{Literal[1, 2]}.

@item 
bpo-45438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45438}: Fix typing.Signature string representation for generic builtin
types.

@item 
bpo-45581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45581}: @ref{4e9,,sqlite3.connect()} now correctly raises @ref{fb5,,MemoryError}
if the underlying SQLite API signals memory error. Patch by Erlend E.
Aasland.

@item 
bpo-39679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39679}: Fix bug in @ref{301,,functools.singledispatchmethod} that caused
it to fail when attempting to register a @ref{310,,classmethod()} or
@ref{311,,staticmethod()} using type annotations. Patch contributed by Alex
Waygood.

@item 
bpo-45515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45515}: Add references to @ref{14e,,zoneinfo} in the @ref{30,,datetime}
documentation, mostly replacing outdated references to @code{dateutil.tz}.
Change by Paul Ganssle.

@item 
bpo-45467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45467}: Fix incremental decoder and stream reader in the
"raw-unicode-escape" codec. Previously they failed if the escape sequence
was split.

@item 
bpo-45461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45461}: Fix incremental decoder and stream reader in the
"unicode-escape" codec. Previously they failed if the escape sequence was
split.

@item 
bpo-45239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45239}: Fixed @ref{fb6,,email.utils.parsedate_tz()} crashing with
@ref{f3e,,UnboundLocalError} on certain invalid input instead of returning
@code{None}. Patch by Ben Hoyt.

@item 
bpo-44904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44904}: Fix bug in the @ref{66,,doctest} module that caused it to fail if
a docstring included an example with a @code{classmethod} @code{property}. Patch
by Alex Waygood.

@item 
bpo-45406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45406}: Make @ref{fb7,,inspect.getmodule()} catch @code{FileNotFoundError}
raised by :'func:@code{inspect.getabsfile}, and return @code{None} to indicate
that the module could not be determined.

@item 
bpo-45262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45262}: Prevent use-after-free in asyncio. Make sure the cached running
loop holder gets cleared on dealloc to prevent use-after-free in
get_running_loop

@item 
bpo-45386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45386}: Make @ref{148,,xmlrpc.client} more robust to C runtimes where the
underlying C @code{strftime} function results in a @code{ValueError} when
testing for year formatting options.

@item 
bpo-45371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45371}: Fix clang rpath issue in @ref{38,,distutils}. The UnixCCompiler
now uses correct clang option to add a runtime library directory (rpath)
to a shared library.

@item 
bpo-20028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20028}: Improve error message of @ref{fb8,,csv.Dialect} when
initializing. Patch by Vajrasky Kok and Dong-hee Na.

@item 
bpo-45343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45343}: Update bundled pip to 21.2.4 and setuptools to 58.1.0

@item 
bpo-41710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41710}: On Unix, if the @code{sem_clockwait()} function is available in
the C library (glibc 2.30 and newer), the @ref{865,,threading.Lock.acquire()}
method now uses the monotonic clock (@ref{504,,time.CLOCK_MONOTONIC}) for the
timeout, rather than using the system clock (@ref{fb9,,time.CLOCK_REALTIME}),
to not be affected by system clock changes. Patch by Victor Stinner.

@item 
bpo-45328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45328}: Fixed @ref{4a1,,http.client.HTTPConnection} to work properly in
OSs that don't support the @code{TCP_NODELAY} socket option.

@item 
bpo-1596321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1596321}: Fix the @code{threading._shutdown()} function when the
@ref{10b,,threading} module was imported first from a thread different than
the main thread: no longer log an error at Python exit.

@item 
bpo-45274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45274}: Fix a race condition in the @ref{c3b,,Thread.join()} method of the @ref{10b,,threading} module. If the
function is interrupted by a signal and the signal handler raises an
exception, make sure that the thread remains in a consistent state to
prevent a deadlock. Patch by Victor Stinner.

@item 
bpo-45238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45238}: Fix @code{unittest.IsolatedAsyncioTestCase.debug()}: it runs now
asynchronous methods and callbacks.

@item 
bpo-36674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36674}: @ref{fba,,unittest.TestCase.debug()} raises now a
@ref{9f2,,unittest.SkipTest} if the class or the test method are decorated
with the skipping decorator.

@item 
bpo-45235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45235}: Fix an issue where argparse would not preserve values in a
provided namespace when using a subparser with defaults.

@item 
bpo-45234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45234}: Fixed a regression in @ref{389,,copyfile()},
@ref{38a,,copy()}, @ref{38b,,copy2()} raising
@ref{8b7,,FileNotFoundError} when source is a directory, which should raise
@ref{a83,,IsADirectoryError}

@item 
bpo-45228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45228}: Fix stack buffer overflow in parsing J1939 network address.

@item 
bpo-45192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45192}: Fix the @code{tempfile._infer_return_type} function so that the
@code{dir} argument of the @ref{103,,tempfile} functions accepts an object
implementing the @code{os.PathLike} protocol.

Patch by Kyungmin Lee.

@item 
bpo-45160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45160}: When tracing a tkinter variable used by a ttk OptionMenu,
callbacks are no longer made twice.

@item 
bpo-35474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35474}: Calling @ref{fbb,,mimetypes.guess_all_extensions()} with
@code{strict=False} no longer affects the result of the following call with
@code{strict=True}. Also, mutating the returned list no longer affects the
global state.

@item 
bpo-45166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45166}: @ref{1f0,,typing.get_type_hints()} now works with
@ref{36f,,Final} wrapped in @ref{f90,,ForwardRef}.

@item 
bpo-45097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45097}: Remove deprecation warnings about the loop argument in
@ref{9,,asyncio} incorrectly emitted in cases when the user does not pass
the loop argument.

@item 
bpo-45081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45081}: Fix issue when dataclasses that inherit from
@code{typing.Protocol} subclasses have wrong @code{__init__}. Patch provided by
Yurii Karabas.

@item 
bpo-24444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24444}: Fixed an error raised in @ref{5,,argparse} help display when help
for an option is set to 1+ blank spaces or when @emph{choices} arg is an empty
container.

@item 
bpo-45021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45021}: Fix a potential deadlock at shutdown of forked children when
using @ref{21,,concurrent.futures} module

@item 
bpo-45030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45030}: Fix integer overflow in pickling and copying the range
iterator.

@item 
bpo-39039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39039}: tarfile.open raises @ref{fbc,,ReadError} when a zlib error
occurs during file extraction.

@item 
bpo-44594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44594}: Fix an edge case of @code{ExitStack} and
@code{AsyncExitStack} exception chaining.  They will now match @code{with}
block behavior when @code{__context__} is explicitly set to @code{None} when the
exception is in flight.
@end itemize

@node Documentation<5>,Tests<5>,Library<9>,Python 3 9 8 final
@anchor{whatsnew/changelog id38}@anchor{fbd}
@subsubsection Documentation



@itemize -

@item 
bpo-45726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45726}: Improve documentation for @ref{499,,functools.singledispatch()} and
@ref{301,,functools.singledispatchmethod}.

@item 
bpo-45680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45680}: Amend the docs on @code{GenericAlias} objects to clarify that
non-container classes can also implement @code{__class_getitem__}. Patch
contributed by Alex Waygood.

@item 
bpo-45655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45655}: Add a new "relevant PEPs" section to the top of the
documentation for the @code{typing} module. Patch by Alex Waygood.

@item 
bpo-45604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45604}: Add @code{level} argument to @code{multiprocessing.log_to_stderr}
function docs.

@item 
bpo-45464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45464}: Mention in the documentation of @ref{fbe,,Built-in Exceptions} that inheriting from multiple exception types in a
single subclass is not recommended due to possible memory layout
incompatibility.

@item 
bpo-45449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45449}: Add note about 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} in @ref{1e,,collections.abc}.

@item 
bpo-45516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45516}: Add protocol description to the
@ref{fbf,,importlib.abc.Traversable} documentation.

@item 
bpo-20692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20692}: Add Programming FAQ entry explaining that int literal attribute
access requires either a space after or parentheses around the literal.

@item 
bpo-45216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45216}: Remove extra documentation listing methods in @code{difflib}. It
was rendering twice in pydoc and was outdated in some places.
@end itemize

@node Tests<5>,Build<4>,Documentation<5>,Python 3 9 8 final
@anchor{whatsnew/changelog id39}@anchor{fc0}
@subsubsection Tests



@itemize -

@item 
bpo-45578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45578}: Add tests for @ref{92a,,dis.distb()}

@item 
bpo-45577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45577}: Add subtests for all @code{pickle} protocols in @code{test_zoneinfo}.

@item 
bpo-43592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43592}: @code{test.libregrtest} now raises the soft resource limit for
the maximum number of file descriptors when the default is too low for our
test suite as was often the case on macOS.

@item 
bpo-40173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40173}: Fix @code{test.support.import_helper.import_fresh_module()}.

@item 
bpo-45280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45280}: Add a test case for empty @ref{228,,typing.NamedTuple}.

@item 
bpo-45269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45269}: Cover case when invalid @code{markers} type is supplied to
@code{c_make_encoder}.

@item 
bpo-45209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45209}: Fix @code{UserWarning: resource_tracker} warning in
@code{_test_multiprocessing._TestSharedMemory.test_shared_memory_cleaned_after_process_termination}

@item 
bpo-45195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45195}: Fix test_readline.test_nonascii(): sometimes, the newline
character is not written at the end, so don't expect it in the output.
Patch by Victor Stinner.

@item 
bpo-45156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45156}: Fixes infinite loop on @ref{518,,unittest.mock.seal()} of mocks
created by @code{create_autospec()}.

@item 
bpo-45042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45042}: Fixes that test classes decorated with
@code{@@hashlib_helper.requires_hashdigest} were skipped all the time.
@end itemize

@node Build<4>,Windows<7>,Tests<5>,Python 3 9 8 final
@anchor{whatsnew/changelog id40}@anchor{fc1}
@subsubsection Build



@itemize -

@item 
bpo-43158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43158}: @code{setup.py} now uses values from configure script to build the
@code{_uuid} extension module. Configure now detects util-linux's
@code{libuuid}, too.

@item 
bpo-45571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45571}: @code{Modules/Setup} now use @code{PY_CFLAGS_NODIST} instead of
@code{PY_CFLAGS} to compile shared modules.

@item 
bpo-45532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45532}: Update @ref{6d4,,sys.version} to use @code{main} as fallback
information. Patch by Jeong YunWon.

@item 
bpo-45405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45405}: Prevent @code{internal configure error} when running @code{configure}
with recent versions of non-Apple clang.  Patch by David Bohman.

@item 
bpo-45220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45220}: Avoid building with the Windows 11 SDK previews automatically.
This may be overridden by setting the @code{DefaultWindowsSDKVersion}
environment variable before building.
@end itemize

@node Windows<7>,macOS<5>,Build<4>,Python 3 9 8 final
@anchor{whatsnew/changelog id41}@anchor{fc2}
@subsubsection Windows



@itemize -

@item 
bpo-45337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45337}: venv now warns when the created environment may need to be
accessed at a different path, due to redirections, links or junctions. It
also now correctly installs or upgrades components when the alternate path
is required.
@end itemize

@node macOS<5>,IDLE<4>,Windows<7>,Python 3 9 8 final
@anchor{whatsnew/changelog id42}@anchor{fc3}
@subsubsection macOS



@itemize -

@item 
bpo-44828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44828}: Avoid tkinter file dialog failure on macOS 12 Monterey when
using the Tk 8.6.11 provided by python.org macOS installers. Patch by Marc
Culler of the Tk project.
@end itemize

@node IDLE<4>,C API<2>,macOS<5>,Python 3 9 8 final
@anchor{whatsnew/changelog id43}@anchor{fc4}
@subsubsection IDLE



@itemize -

@item 
bpo-45296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45296}: On Windows, change exit/quit message to suggest Ctrl-D, which
works, instead of <Ctrl-Z Return>, which does not work in IDLE.
@end itemize

@node C API<2>,,IDLE<4>,Python 3 9 8 final
@anchor{whatsnew/changelog id44}@anchor{fc5}
@subsubsection C API



@itemize -

@item 
bpo-44687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44687}: @code{BufferedReader.peek()} no longer raises @ref{16d,,ValueError}
when the entire file has already been buffered.

@item 
bpo-44751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44751}: Remove @code{crypt.h} include from the public @code{Python.h} header.
@end itemize

@node Python 3 9 7 final,Python 3 9 6 final,Python 3 9 8 final,更新日志
@anchor{whatsnew/changelog python-3-9-7-final}@anchor{fc6}
@subsection Python 3.9.7 final


@emph{Release date: 2021-08-30}

@menu
* Security: Security<5>. 
* Core and Builtins: Core and Builtins<10>. 
* Library: Library<10>. 
* Documentation: Documentation<6>. 
* Tests: Tests<6>. 
* Build: Build<5>. 
* Windows: Windows<8>. 
* macOS: macOS<6>. 

@end menu

@node Security<5>,Core and Builtins<10>,,Python 3 9 7 final
@anchor{whatsnew/changelog id45}@anchor{fc7}
@subsubsection Security



@itemize -

@item 
bpo-42278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42278}: Replaced usage of @ref{fc8,,tempfile.mktemp()} with
@ref{c9e,,TemporaryDirectory} to avoid a potential race condition.

@item 
bpo-41180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41180}: Add auditing events to the @ref{b0,,marshal} module, and stop
raising @code{code.__init__} events for every unmarshalled code object.
Directly instantiated code objects will continue to raise an event, and
audit event handlers should inspect or collect the raw marshal data. This
reduces a significant performance overhead when loading from @code{.pyc}
files.

@item 
bpo-44394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44394}: Update the vendored copy of libexpat to 2.4.1 (from 2.2.8) to
get the fix for the CVE-2013-0340 "Billion Laughs" vulnerability. This
copy is most used on Windows and macOS.

@item 
bpo-43124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43124}: Made the internal @code{putcmd} function in @ref{ed,,smtplib}
sanitize input for presence of @code{\r} and @code{\n} characters to avoid
(unlikely) command injection.
@end itemize

@node Core and Builtins<10>,Library<10>,Security<5>,Python 3 9 7 final
@anchor{whatsnew/changelog id46}@anchor{fc9}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-45018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45018}: Fixed pickling of range iterators that iterated for over 2**32
times.

@item 
bpo-44962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44962}: Fix a race in WeakKeyDictionary, WeakValueDictionary and
WeakSet when two threads attempt to commit the last pending removal. This
fixes asyncio.create_task and fixes a data loss in asyncio.run where
shutdown_asyncgens is not run

@item 
bpo-44954@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44954}: Fixed a corner case bug where the result of
@code{float.fromhex('0x.8p-1074')} was rounded the wrong way.

@item 
bpo-44947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44947}: Refine the syntax error for trailing commas in import
statements. Patch by Pablo Galindo.

@item 
bpo-44698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44698}: Restore behaviour of complex exponentiation with integer-valued
exponent of type @ref{1fe,,float} or @ref{2c8,,complex}.

@item 
bpo-44885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44885}: Correct the ast locations of f-strings with format specs and
repeated expressions. Patch by Pablo Galindo

@item 
bpo-44872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44872}: Use new trashcan macros (Py_TRASHCAN_BEGIN/END) in
frameobject.c instead of the old ones (Py_TRASHCAN_SAFE_BEGIN/END).

@item 
bpo-33930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33930}: Fix segmentation fault with deep recursion when cleaning method
objects. Patch by Augusto Goulart and Pablo Galindo.

@item 
bpo-25782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25782}: Fix bug where @code{PyErr_SetObject} hangs when the current
exception has a cycle in its context chain.

@item 
bpo-44856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44856}: Fix reference leaks in the error paths of @code{update_bases()}
and @code{__build_class__}. Patch by Pablo Galindo.

@item 
bpo-44698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44698}: Fix undefined behaviour in complex object exponentiation.

@item 
bpo-44562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44562}: Remove uses of @ref{f0d,,PyObject_GC_Del()} in error path when
initializing @ref{27d,,types.GenericAlias}.

@item 
bpo-44523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44523}: Remove the pass-through for @ref{aac,,hash()} of
@ref{381,,weakref.proxy} objects to prevent unintended consequences when the
original referred object dies while the proxy is part of a hashable
object. Patch by Pablo Galindo.

@item 
bpo-44472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44472}: Fix ltrace functionality when exceptions are raised. Patch by
Pablo Galindo

@item 
bpo-44184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44184}: Fix a crash at Python exit when a deallocator function removes
the last strong reference to a heap type. Patch by Victor Stinner.

@item 
bpo-39091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39091}: Fix crash when using passing a non-exception to a generator's
@code{throw()} method. Patch by Noah Oxer
@end itemize

@node Library<10>,Documentation<6>,Core and Builtins<10>,Python 3 9 7 final
@anchor{whatsnew/changelog id47}@anchor{fca}
@subsubsection Library



@itemize -

@item 
bpo-41620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41620}: @ref{b9f,,run()} now always return a
@ref{ba0,,TestResult} instance. Previously it returned @code{None} if
the test class or method was decorated with a skipping decorator.

@item 
bpo-43913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43913}: Fix bugs in cleaning up classes and modules in @ref{124,,unittest}:


@itemize *

@item 
Functions registered with @ref{37b,,addModuleCleanup()} were not called unless the user defines @code{tearDownModule()} in their test module.

@item 
Functions registered with @ref{37c,,addClassCleanup()} were not called if @code{tearDownClass} is set to @code{None}.

@item 
Buffering in @ref{ba0,,TestResult} did not work with functions registered with @code{addClassCleanup()} and @code{addModuleCleanup()}.

@item 
Errors in functions registered with @code{addClassCleanup()} and @code{addModuleCleanup()} were not handled correctly in buffered and debug modes.

@item 
Errors in @code{setUpModule()} and functions registered with @code{addModuleCleanup()} were reported in wrong order.

@item 
And several lesser bugs.
@end itemize

@item 
bpo-45001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45001}: Made email date parsing more robust against malformed input,
namely a whitespace-only @code{Date:} header. Patch by Wouter Bolsterlee.

@item 
bpo-44449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44449}: Fix a crash in the signal handler of the @ref{7b,,faulthandler}
module: no longer modify the reference count of frame objects. Patch by
Victor Stinner.

@item 
bpo-44955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44955}: Method @ref{db4,,stopTestRun()} is now always
called in pair with method @ref{db3,,startTestRun()} for
@ref{ba0,,TestResult} objects implicitly created in
@ref{b9f,,run()}. Previously it was not called for test
methods and classes decorated with a skipping decorator.

@item 
bpo-38956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38956}: @code{argparse.BooleanOptionalAction}'s default value is no
longer printed twice when used with
@ref{fcb,,argparse.ArgumentDefaultsHelpFormatter}.

@item 
bpo-44581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44581}: Upgrade bundled pip to 21.2.3 and setuptools to 57.4.0

@item 
bpo-44849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44849}: Fix the @ref{8f3,,os.set_inheritable()} function on FreeBSD 14 for
file descriptor opened with the @ref{977,,O_PATH} flag: ignore the
@ref{230,,EBADF} error on @code{ioctl()}, fallback on the @code{fcntl()}
implementation. Patch by Victor Stinner.

@item 
bpo-44605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44605}: The @@functools.total_ordering() decorator now works with
metaclasses.

@item 
bpo-44822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44822}: @ref{f2,,sqlite3} user-defined functions and aggregators returning
@ref{206,,strings} with embedded NUL characters are no longer
truncated. Patch by Erlend E. Aasland.

@item 
bpo-44815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44815}: Always show @code{loop=} arg deprecations in
@ref{3b3,,asyncio.gather()} and @ref{3b2,,asyncio.sleep()}

@item 
bpo-44806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44806}: Non-protocol subclasses of @ref{371,,typing.Protocol} ignore now
the @code{__init__} method inherited from protocol base classes.

@item 
bpo-44667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44667}: The @ref{d2b,,tokenize.tokenize()} doesn't incorrectly generate a
@code{NEWLINE} token if the source doesn't end with a new line character but
the last line is a comment, as the function is already generating a @code{NL}
token. Patch by Pablo Galindo

@item 
bpo-42853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42853}: Fix @code{http.client.HTTPSConnection} fails to download >2GiB
data.

@item 
bpo-44752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44752}: @code{rcompleter} does not call @ref{554,,getattr()} on
@ref{30f,,property} objects to avoid the side-effect of  evaluating the
corresponding method.

@item 
bpo-44720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44720}: @code{weakref.proxy} objects referencing non-iterators now raise
@code{TypeError} rather than dereferencing the null @code{tp_iternext} slot and
crashing.

@item 
bpo-44704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44704}: The implementation of @code{collections.abc.Set._hash()} now
matches that of @code{frozenset.__hash__()}.

@item 
bpo-44666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44666}: Fixed issue in @ref{7b8,,compileall.compile_file()} when
@code{sys.stdout} is redirected. Patch by Stefan Hölzl.

@item 
bpo-40897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40897}: Give priority to using the current class constructor in
@ref{65e,,inspect.signature()}. Patch by Weipeng Hong.

@item 
bpo-44608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44608}: Fix memory leak in @code{_tkinter._flatten()} if it is called
with a sequence or set, but not list or tuple.

@item 
bpo-41928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41928}: Update @ref{389,,shutil.copyfile()} to raise
@ref{8b7,,FileNotFoundError} instead of confusing @ref{a83,,IsADirectoryError}
when a path ending with a @code{os.path.sep} does not exist;
@ref{38a,,shutil.copy()} and @ref{38b,,shutil.copy2()} are also affected.

@item 
bpo-44566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44566}: handle StopIteration subclass raised from
@@contextlib.contextmanager generator

@item 
bpo-44558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44558}: Make the implementation consistency of
@ref{17b,,indexOf()} between C and Python versions. Patch by Dong-hee
Na.

@item 
bpo-41249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41249}: Fixes @code{TypedDict} to work with @code{typing.get_type_hints()}
and postponed evaluation of annotations across modules.

@item 
bpo-44461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44461}: Fix bug with @ref{c9,,pdb}'s handling of import error due to a
package which does not have a @code{__main__} module

@item 
bpo-42892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42892}: Fixed an exception thrown while parsing a malformed multipart
email by @ref{645,,email.message.EmailMessage}.

@item 
bpo-27827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27827}: @code{pathlib.PureWindowsPath.is_reserved()} now identifies a
greater range of reserved filenames, including those with trailing spaces
or colons.

@item 
bpo-34266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34266}: Handle exceptions from parsing the arg of @ref{c9,,pdb}'s
run/restart command.

@item 
bpo-27334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27334}: The @ref{f2,,sqlite3} context manager now performs a rollback
(thus releasing the database lock) if commit failed.  Patch by Luca Citi
and Erlend E. Aasland.

@item 
bpo-43853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43853}: Improved string handling for @ref{f2,,sqlite3} user-defined
functions and aggregates:


@itemize *

@item 
It is now possible to pass strings with embedded null characters to UDFs

@item 
Conversion failures now correctly raise @ref{fb5,,MemoryError}
@end itemize

Patch by Erlend E. Aasland.

@item 
bpo-43048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43048}: Handle @ref{731,,RecursionError} in
@ref{86f,,TracebackException}'s constructor, so that long
exceptions chains are truncated instead of causing traceback formatting to
fail.

@item 
bpo-41402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41402}: Fix @ref{fcc,,email.message.EmailMessage.set_content()} when called
with binary data and @code{7bit} content transfer encoding.

@item 
bpo-32695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32695}: The @emph{compresslevel} and @emph{preset} keyword arguments of
@ref{85f,,tarfile.open()} are now both documented and tested.

@item 
bpo-34990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34990}: Fixed a Y2k38 bug in the compileall module where it would fail
to compile files with a modification time after the year 2038.

@item 
bpo-38840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38840}: Fix @code{test___all__} on platforms lacking a shared memory
implementation.

@item 
bpo-30256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30256}: Pass multiprocessing BaseProxy argument @code{manager_owned}
through AutoProxy.

@item 
bpo-27513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27513}: @ref{fcd,,email.utils.getaddresses()} now accepts
@ref{fce,,email.header.Header} objects along with string values. Patch by
Zackery Spytz.

@item 
bpo-33349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33349}: lib2to3 now recognizes async generators everywhere.

@item 
bpo-29298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29298}: Fix @code{TypeError} when required subparsers without @code{dest} do
not receive arguments. Patch by Anthony Sottile.
@end itemize

@node Documentation<6>,Tests<6>,Library<10>,Python 3 9 7 final
@anchor{whatsnew/changelog id48}@anchor{fcf}
@subsubsection Documentation



@itemize -

@item 
bpo-44903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44903}: Removed the othergui.rst file, any references to it, and the
list of GUI frameworks in the FAQ. In their place I've added links to the
Python Wiki @code{page on GUI frameworks}.

@item 
bpo-44693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44693}: Update the definition of __future__ in the glossary by
replacing the confusing word "pseudo-module" with a more accurate
description.

@item 
bpo-35183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35183}: Add typical examples to os.path.splitext docs

@item 
bpo-30511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30511}: Clarify that @ref{34f,,shutil.make_archive()} is not thread-safe due
to reliance on changing the current working directory.

@item 
bpo-44561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44561}: Update of three expired hyperlinks in
Doc/distributing/index.rst: "Project structure", "Building and packaging
the project", and "Uploading the project to the Python Packaging Index".

@item 
bpo-42958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42958}: Updated the docstring and docs of @ref{fd0,,filecmp.cmp()} to be
more accurate and less confusing especially in respect to @emph{shallow} arg.

@item 
bpo-44558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44558}: Match the docstring and python implementation of
@ref{17c,,countOf()} to the behavior of its c implementation.

@item 
bpo-44544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44544}: List all kwargs for @ref{fd1,,textwrap.wrap()},
@ref{fd2,,textwrap.fill()}, and @ref{9dc,,textwrap.shorten()}. Now, there are nav
links to attributes of @code{TextWrap}, which makes navigation much
easier while minimizing duplication in the documentation.

@item 
bpo-38062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38062}: Clarify that atexit uses equality comparisons internally.

@item 
bpo-43066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43066}: Added a warning to @ref{14b,,zipfile} docs: filename arg with a
leading slash may cause archive to be un-openable on Windows systems.

@item 
bpo-27752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27752}: Documentation of csv.Dialect is more descriptive.

@item 
bpo-44453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44453}: Fix documentation for the return type of
@ref{d8e,,sysconfig.get_path()}.

@item 
bpo-39498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39498}: Add a "Security Considerations" index which links to standard
library modules that have explicitly documented security considerations.

@item 
bpo-33479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33479}: Remove the unqualified claim that tkinter is threadsafe. It has
not been true for several years and likely never was. An explanation of
what is true may be added later, after more discussion, and possibly after
patching _tkinter.c,
@end itemize

@node Tests<6>,Build<5>,Documentation<6>,Python 3 9 7 final
@anchor{whatsnew/changelog id49}@anchor{fd3}
@subsubsection Tests



@itemize -

@item 
bpo-25130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25130}: Add calls of @ref{362,,gc.collect()} in tests to support PyPy.

@item 
bpo-45011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45011}: Made tests relying on the @code{_asyncio} C extension module
optional to allow running on alternative Python implementations. Patch by
Serhiy Storchaka.

@item 
bpo-44949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44949}: Fix auto history tests of test_readline: sometimes, the newline
character is not written at the end, so don't expect it in the output.

@item 
bpo-44852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44852}: Add ability to wholesale silence DeprecationWarnings while
running the regression test suite.

@item 
bpo-40928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40928}: Notify users running test_decimal regression tests on macOS of
potential harmless "malloc can't allocate region" messages spewed by
test_decimal.

@item 
bpo-44734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44734}: Fixed floating point precision issue in turtle tests.

@item 
bpo-44708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44708}: Regression tests, when run with -w, are now re-running only the
affected test methods instead of re-running the entire test file.

@item 
bpo-30256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30256}: Add test for nested queues when using @code{multiprocessing}
shared objects @code{AutoProxy[Queue]} inside @code{ListProxy} and @code{DictProxy}
@end itemize

@node Build<5>,Windows<8>,Tests<6>,Python 3 9 7 final
@anchor{whatsnew/changelog id50}@anchor{fd4}
@subsubsection Build



@itemize -

@item 
bpo-44535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44535}: Enable building using a Visual Studio 2022 install on Windows.

@item 
bpo-43298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43298}: Improved error message when building without a Windows SDK
installed.
@end itemize

@node Windows<8>,macOS<6>,Build<5>,Python 3 9 7 final
@anchor{whatsnew/changelog id51}@anchor{fd5}
@subsubsection Windows



@itemize -

@item 
bpo-45007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45007}: Update to OpenSSL 1.1.1l in Windows build

@item 
bpo-44572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44572}: Avoid consuming standard input in the @ref{ce,,platform} module

@item 
bpo-40263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40263}: This is a follow-on bug from
@indicateurl{https://bugs.python.org/issue26903}. Once that is applied we run into an
off-by-one assertion problem. The assert was not correct.
@end itemize

@node macOS<6>,,Windows<8>,Python 3 9 7 final
@anchor{whatsnew/changelog id52}@anchor{fd6}
@subsubsection macOS



@itemize -

@item 
bpo-45007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=45007}: Update macOS installer builds to use OpenSSL 1.1.1l.

@item 
bpo-44689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44689}: @ref{70b,,ctypes.util.find_library()} now works correctly on macOS
11 Big Sur even if Python is built on an older version of macOS.
Previously, when built on older macOS systems, @code{find_library} was not
able to find  macOS system libraries when running on Big Sur due to
changes in  how system libraries are stored.
@end itemize

@node Python 3 9 6 final,Python 3 9 5 final,Python 3 9 7 final,更新日志
@anchor{whatsnew/changelog python-3-9-6-final}@anchor{fd7}
@subsection Python 3.9.6 final


@emph{Release date: 2021-06-28}

@menu
* Security: Security<6>. 
* Core and Builtins: Core and Builtins<11>. 
* Library: Library<11>. 
* Documentation: Documentation<7>. 
* Tests: Tests<7>. 
* Build: Build<6>. 
* Windows: Windows<9>. 
* macOS: macOS<7>. 
* IDLE: IDLE<5>. 
* Tools/Demos: Tools/Demos<3>. 
* C API: C API<3>. 

@end menu

@node Security<6>,Core and Builtins<11>,,Python 3 9 6 final
@anchor{whatsnew/changelog id53}@anchor{fd8}
@subsubsection Security



@itemize -

@item 
bpo-44022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44022}: mod:@ref{93,,http.client} now avoids infinitely reading potential HTTP
headers after a @code{100 Continue} status response from the server.
@end itemize

@node Core and Builtins<11>,Library<11>,Security<6>,Python 3 9 6 final
@anchor{whatsnew/changelog id54}@anchor{fd9}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-44409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44409}: Fix error location information for tokenizer errors raised on
initialization of the tokenizer. Patch by Pablo Galindo.

@item 
bpo-43667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43667}: Improve Unicode support in non-UTF locales on Oracle Solaris.
This issue does not affect other Solaris systems.

@item 
bpo-44168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44168}: Fix error message in the parser involving keyword arguments
with invalid expressions. Patch by Pablo Galindo

@item 
bpo-44114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44114}: Fix incorrect dictkeys_reversed and dictitems_reversed function
signatures in C code, which broke webassembly builds.

@item 
bpo-44070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44070}: No longer eagerly makes import filenames absolute, except for
extension modules, which was introduced in 3.9.5.

@item 
bpo-28146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28146}: Fix a confusing error message in @ref{5dd,,str.format()}.

@item 
bpo-11105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11105}: When compiling @ref{187,,ast.AST} objects with recursive
references through @ref{2ee,,compile()}, the interpreter doesn't crash anymore
instead it raises a @ref{731,,RecursionError}.
@end itemize

@node Library<11>,Documentation<7>,Core and Builtins<11>,Python 3 9 6 final
@anchor{whatsnew/changelog id55}@anchor{fda}
@subsubsection Library



@itemize -

@item 
bpo-44516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44516}: Update vendored pip to 21.1.3

@item 
bpo-44482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44482}: Fix very unlikely resource leak in @ref{88,,glob} in alternate
Python implementations.

@item 
bpo-44439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44439}: Fix in @code{bz2.BZ2File.write()} / @code{lzma.LZMAFile.write()}
methods, when the input data is an object that supports the buffer
protocol, the file length may be wrong.

@item 
bpo-44434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44434}: _thread.start_new_thread() no longer calls
PyThread_exit_thread() explicitly at the thread exit, the call was
redundant. On Linux with the glibc, pthread_exit() aborts the whole
process if dlopen() fails to open libgcc_s.so file (ex: EMFILE error).
Patch by Victor Stinner.

@item 
bpo-44422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44422}: The @ref{fdb,,threading.enumerate()} function now uses a reentrant
lock to prevent a hang on reentrant call. Patch by Victor Stinner.

@item 
bpo-44395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44395}: Fix @code{as_string()} to pass unixfrom
properly. Patch by Dong-hee Na.

@item 
bpo-44342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44342}: [Enum] Be more robust in searching for pickle support before
making an enum class unpicklable.

@item 
bpo-44356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44356}: [Enum] Allow multiple data-type mixins if they are all the
same.

@item 
bpo-44254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44254}: On Mac, give turtledemo button text a color that works on both
light or dark background.  Programmers cannot control the latter.

@item 
bpo-44145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44145}: @ref{8e,,hmac} computations were not releasing the GIL while
calling the OpenSSL @code{HMAC_Update} C API (a new feature in 3.9).  This
unintentionally prevented parallel computation as other @ref{8c,,hashlib}
algorithms support.

@item 
bpo-37788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37788}: Fix a reference leak when a Thread object is never joined.

@item 
bpo-44061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44061}: Fix regression in previous release when calling
@ref{70c,,pkgutil.iter_modules()} with a list of @ref{336,,pathlib.Path} objects

@item 
bpo-36515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36515}: The @ref{8c,,hashlib} module no longer does unaligned memory
accesses when compiled for ARM platforms.

@item 
bpo-44018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44018}: random.seed() no longer mutates bytearray inputs.

@item 
bpo-38352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38352}: Add @code{IO}, @code{BinaryIO}, @code{TextIO}, @code{Match}, and
@code{Pattern} to @code{typing.__all__}. Patch by Jelle Zijlstra.

@item 
bpo-43972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43972}: When @ref{4a4,,http.server.SimpleHTTPRequestHandler} sends a
@code{301 (Moved Permanently)} for a directory path not ending with @code{/}, add
a @code{Content-Length: 0} header. This improves the behavior for certain
clients.

@item 
bpo-28528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28528}: Fix a bug in @ref{c9,,pdb} where @code{checkline()} raises
@ref{4aa,,AttributeError} if it is called after @code{reset()}.

@item 
bpo-43776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43776}: When @ref{3e3,,subprocess.Popen} args are provided as a string or
as @ref{336,,pathlib.Path}, the Popen instance repr now shows the right
thing.

@item 
bpo-43666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43666}: AIX: @code{Lib/_aix_support.get_platform()} may fail in an AIX WPAR.
The fileset bos.rte appears to have a builddate in both LPAR and WPAR so
this fileset is queried rather than bos.mp64. To prevent a similiar
situation (no builddate in ODM) a value (9988) sufficient for completing a
build is provided. Patch by M Felt.

@item 
bpo-43650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43650}: Fix @ref{fb5,,MemoryError} in @ref{28b,,shutil.unpack_archive()} which
fails inside @code{shutil._unpack_zipfile()} on large files. Patch by Igor
Bolshakov.

@item 
bpo-43318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43318}: Fix a bug where @ref{c9,,pdb} does not always echo cleared
breakpoints.

@item 
bpo-43295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43295}: @ref{fdc,,datetime.datetime.strptime()} now raises @code{ValueError}
instead of @code{IndexError} when matching @code{'z'} with the @code{%z} format
specifier.

@item 
bpo-37022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37022}: @ref{c9,,pdb} now displays exceptions from @code{repr()} with its
@code{p} and @code{pp} commands.
@end itemize

@node Documentation<7>,Tests<7>,Library<11>,Python 3 9 6 final
@anchor{whatsnew/changelog id56}@anchor{fdd}
@subsubsection Documentation



@itemize -

@item 
bpo-40620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40620}: Convert examples in tutorial controlflow.rst section 4.3 to be
interpreter-demo style.

@item 
bpo-13814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13814}: In the Design FAQ, answer "Why don't generators support the
with statement?"

@item 
bpo-44392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44392}: Added a new section in the C API documentation for types used
in type hinting.  Documented @code{Py_GenericAlias} and
@code{Py_GenericAliasType}.

@item 
bpo-38291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38291}: Mark @code{typing.io} and @code{typing.re} as deprecated since Python
3.8 in the documentation. They were never properly supported by type
checkers.

@item 
bpo-44322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44322}: Document that SyntaxError args have a details tuple and that
details are adjusted for errors in f-string field replacement expressions.

@item 
bpo-44195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44195}: Corrected references to @code{TraversableResources} in docs. There
is no @code{TraversableReader}.

@item 
bpo-41963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41963}: Document that @code{ConfigParser} strips off comments when reading
configuration files.

@item 
bpo-44072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44072}: Correct where in the numeric ABC hierarchy @code{**} support is
added, i.e., in numbers.Complex, not numbers.Integral.

@item 
bpo-43558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43558}: Add the remark to @ref{2f,,dataclasses} documentation that the
@ref{e2b,,__init__()} of any base class has to be called in
@code{__post_init__()}, along with a code example.

@item 
bpo-41621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41621}: Document that @ref{c15,,collections.defaultdict} parameter
@code{default_factory} defaults to None and is positional-only.
@end itemize

@node Tests<7>,Build<6>,Documentation<7>,Python 3 9 6 final
@anchor{whatsnew/changelog id57}@anchor{fde}
@subsubsection Tests



@itemize -

@item 
bpo-44287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44287}: Fix asyncio test_popen() of test_windows_utils by using a
longer timeout. Use military grade battle-tested
@ref{fdf,,test.support.SHORT_TIMEOUT} timeout rather than a hardcoded timeout
of 10 seconds: it's 30 seconds by default, but it is made longer on slow
buildbots. Patch by Victor Stinner.

@item 
bpo-44363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44363}: Account for address sanitizer in test_capi. test_capi now
passes when run GCC address sanitizer.
@end itemize

@node Build<6>,Windows<9>,Tests<7>,Python 3 9 6 final
@anchor{whatsnew/changelog id58}@anchor{fe0}
@subsubsection Build



@itemize -

@item 
bpo-44381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44381}: The Windows build now accepts 
@geindex EnableControlFlowGuard
@geindex 环境变量; EnableControlFlowGuard
@code{EnableControlFlowGuard}
set to @code{guard} to enable CFG.
@end itemize

@node Windows<9>,macOS<7>,Build<6>,Python 3 9 6 final
@anchor{whatsnew/changelog id59}@anchor{fe1}
@subsubsection Windows



@itemize -

@item 
bpo-41299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41299}: Fix 16ms jitter when using timeouts in @ref{10b,,threading}, such
as with @ref{865,,threading.Lock.acquire()} or
@ref{fe2,,threading.Condition.wait()}.
@end itemize

@node macOS<7>,IDLE<5>,Windows<9>,Python 3 9 6 final
@anchor{whatsnew/changelog id60}@anchor{fe3}
@subsubsection macOS



@itemize -

@item 
bpo-43568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43568}: Relax unnecessarily restrictive MACOSX_DEPLOYMENT_TARGET check
when building extension modules for macOS. Patch by Joshua Root.

@item 
bpo-43109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43109}: Allow --with-lto configure option to work with Apple-supplied
Xcode or Command Line Tools.
@end itemize

@node IDLE<5>,Tools/Demos<3>,macOS<7>,Python 3 9 6 final
@anchor{whatsnew/changelog id61}@anchor{fe4}
@subsubsection IDLE



@itemize -

@item 
bpo-40128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40128}: Mostly fix completions on macOS when not using tcl/tk 8.6.11
(as with 3.9). The added update_idletask call should be harmless and
possibly helpful otherwise.

@item 
bpo-33962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33962}: Move the indent space setting from the Font tab to the new
Windows tab. Patch by Mark Roseman and Terry Jan Reedy.

@item 
bpo-40468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40468}: Split the settings dialog General tab into Windows and Shell/ED
tabs. Move help sources, which extend the Help menu, to the Extensions
tab. Make space for new options and shorten the dialog. The latter makes
the dialog better fit small screens.

@item 
bpo-41611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41611}: Avoid uncaught exceptions in
@code{AutoCompleteWindow.winconfig_event()}.

@item 
bpo-41611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41611}: Fix IDLE sometimes freezing upon tab-completion on macOS.
@end itemize

@node Tools/Demos<3>,C API<3>,IDLE<5>,Python 3 9 6 final
@anchor{whatsnew/changelog id62}@anchor{fe5}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-44074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44074}: Make patchcheck automatically detect the correct base branch
name (previously it was hardcoded to 'master')
@end itemize

@node C API<3>,,Tools/Demos<3>,Python 3 9 6 final
@anchor{whatsnew/changelog id63}@anchor{fe6}
@subsubsection C API



@itemize -

@item 
bpo-44441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44441}: @ref{2bc,,Py_RunMain()} now resets @code{PyImport_Inittab} to
its initial value at exit. It must be possible to call
@ref{fe7,,PyImport_AppendInittab()} or @ref{fe8,,PyImport_ExtendInittab()} at
each Python initialization. Patch by Victor Stinner.

@item 
bpo-42083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42083}: Fix crash in @ref{fe9,,PyStructSequence_NewType()} when passed
@code{NULL} in the documentation string slot.
@end itemize

@node Python 3 9 5 final,Python 3 9 4 final,Python 3 9 6 final,更新日志
@anchor{whatsnew/changelog python-3-9-5-final}@anchor{fea}
@subsection Python 3.9.5 final


@emph{Release date: 2021-05-03}

@menu
* Security: Security<7>. 
* Core and Builtins: Core and Builtins<12>. 
* Library: Library<12>. 
* Documentation: Documentation<8>. 
* Tests: Tests<8>. 
* Windows: Windows<10>. 
* macOS: macOS<8>. 
* IDLE: IDLE<6>. 

@end menu

@node Security<7>,Core and Builtins<12>,,Python 3 9 5 final
@anchor{whatsnew/changelog id64}@anchor{feb}
@subsubsection Security



@itemize -

@item 
bpo-43434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43434}: Creating a @ref{4e7,,sqlite3.Connection} object now also produces
a @code{sqlite3.connect} @ref{fec,,auditing event}. Previously this
event was only produced by @ref{4e9,,sqlite3.connect()} calls. Patch by Erlend
E. Aasland.

@item 
bpo-43882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43882}: The presence of newline or tab characters in parts of a URL
could allow some forms of attacks.

Following the controlling specification for URLs defined by WHATWG
@ref{128,,urllib.parse()} now removes ASCII newlines and tabs from URLs,
preventing such attacks.

@item 
bpo-43472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43472}: Ensures interpreter-level audit hooks receive the
@code{cpython.PyInterpreterState_New} event when called through the
@code{_xxsubinterpreters} module.

@item 
bpo-36384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36384}: @ref{a2,,ipaddress} module no longer accepts any leading zeros in
IPv4 address strings. Leading zeros are ambiguous and interpreted as octal
notation by some libraries. For example the legacy function
@ref{237,,socket.inet_aton()} treats leading zeros as octal notatation. glibc
implementation of modern @ref{238,,inet_pton()} does not accept any
leading zeros. For a while the @ref{a2,,ipaddress} module used to accept
ambiguous leading zeros.

@item 
bpo-43075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43075}: Fix Regular Expression Denial of Service (ReDoS) vulnerability
in @ref{fed,,urllib.request.AbstractBasicAuthHandler}.  The ReDoS-vulnerable
regex has quadratic worst-case complexity and it allows cause a denial of
service when identifying crafted invalid RFCs. This ReDoS issue is on the
client side and needs remote attackers to control the HTTP server.

@item 
bpo-42800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42800}: Audit hooks are now fired for frame.f_code, traceback.tb_frame,
and generator code/frame attribute access.
@end itemize

@node Core and Builtins<12>,Library<12>,Security<7>,Python 3 9 5 final
@anchor{whatsnew/changelog id65}@anchor{fee}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43105}: Importlib now resolves relative paths when creating module spec
objects from file locations.

@item 
bpo-42924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42924}: Fix @code{bytearray} repetition incorrectly copying data from the
start of the buffer, even if the data is offset within the buffer (e.g.
after reassigning a slice at the start of the @code{bytearray} to a shorter
byte string).
@end itemize

@node Library<12>,Documentation<8>,Core and Builtins<12>,Python 3 9 5 final
@anchor{whatsnew/changelog id66}@anchor{fef}
@subsubsection Library



@itemize -

@item 
bpo-43993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43993}: Update bundled pip to 21.1.1.

@item 
bpo-43937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43937}: Fixed the @ref{11f,,turtle} module working with non-default root
window.

@item 
bpo-43930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43930}: Update bundled pip to 21.1 and setuptools to 56.0.0

@item 
bpo-43920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43920}: OpenSSL 3.0.0: @ref{8e2,,load_verify_locations()}
now returns a consistent error message when cadata contains no valid
certificate.

@item 
bpo-43607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43607}: @ref{126,,urllib} can now convert Windows paths with @code{\\?\}
prefixes into URL paths.

@item 
bpo-43284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43284}: platform.win32_ver derives the windows version from
sys.getwindowsversion().platform_version which in turn derives the version
from kernel32.dll (which can be of a different version than Windows
itself). Therefore change the platform.win32_ver to determine the version
using the platform module's _syscmd_ver private function to return an
accurate version.

@item 
bpo-42248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42248}: [Enum] ensure exceptions raised in @code{_missing_} are released.

@item 
bpo-43799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43799}: OpenSSL 3.0.0: define @code{OPENSSL_API_COMPAT} 1.1.1 to suppress
deprecation warnings. Python requires OpenSSL 1.1.1 APIs.

@item 
bpo-43794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43794}: Add @ref{ff0,,ssl.OP_IGNORE_UNEXPECTED_EOF} constants (OpenSSL
3.0.0)

@item 
bpo-43789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43789}: OpenSSL 3.0.0: Don't call the password callback function a
second time when first call has signaled an error condition.

@item 
bpo-43788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43788}: The header files for @ref{f3,,ssl} error codes are now OpenSSL
version-specific. Exceptions will now show correct reason and library
codes. The @code{make_ssl_data.py} script has been rewritten to use OpenSSL's
text file with error codes.

@item 
bpo-43655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43655}: @ref{10e,,tkinter} dialog windows are now recognized as dialogs by
window managers on macOS and X Window.

@item 
bpo-43534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43534}: @ref{ff1,,turtle.textinput()} and @ref{ff2,,turtle.numinput()} create now
a transient window working on behalf of the canvas window.

@item 
bpo-43522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43522}: Fix problem with
@ref{4ed,,hostname_checks_common_name}. OpenSSL does not copy
hostflags from @emph{struct SSL_CTX} to @emph{struct SSL}.

@item 
bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}: Allow @ref{172,,bytes} @code{separator} argument in
@code{urllib.parse.parse_qs} and @code{urllib.parse.parse_qsl} when parsing
@ref{206,,str} query strings. Previously, this raised a @code{TypeError}.

@item 
bpo-43176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43176}: Fixed processing of a dataclass that inherits from a frozen
dataclass with no fields.  It is now correctly detected as an error.

@item 
bpo-41735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41735}: Fix thread locks in zlib module may go wrong in rare case.
Patch by Ma Lin.

@item 
bpo-36470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36470}: Fix dataclasses with @code{InitVar}s and
@ref{ff3,,replace()}. Patch by Claudiu Popa.

@item 
bpo-32745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32745}: Fix a regression in the handling of ctypes'
@ref{ff4,,ctypes.c_wchar_p} type: embedded null characters would cause a
@ref{16d,,ValueError} to be raised. Patch by Zackery Spytz.
@end itemize

@node Documentation<8>,Tests<8>,Library<12>,Python 3 9 5 final
@anchor{whatsnew/changelog id67}@anchor{ff5}
@subsubsection Documentation



@itemize -

@item 
bpo-43959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43959}: The documentation on the PyContextVar C-API was clarified.

@item 
bpo-43938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43938}: Update dataclasses documentation to express that
FrozenInstanceError is derived from AttributeError.

@item 
bpo-43755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43755}: Update documentation to reflect that unparenthesized lambda
expressions can no longer be the expression part in an @code{if} clause in
comprehensions and generator expressions since Python 3.9.

@item 
bpo-43739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43739}: Fixing the example code in Doc/extending/extending.rst to
declare and initialize the pmodule variable to be of the right type.
@end itemize

@node Tests<8>,Windows<10>,Documentation<8>,Python 3 9 5 final
@anchor{whatsnew/changelog id68}@anchor{ff6}
@subsubsection Tests



@itemize -

@item 
bpo-43961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43961}: Fix test_logging.test_namer_rotator_inheritance() on Windows:
use @ref{b1e,,os.replace()} rather than @ref{b1d,,os.rename()}. Patch by Victor
Stinner.

@item 
bpo-43842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43842}: Fix a race condition in the SMTP test of test_logging. Don't
close a file descriptor (socket) from a different thread while
asyncore.loop() is polling the file descriptor. Patch by Victor Stinner.

@item 
bpo-43811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43811}: Tests multiple OpenSSL versions on GitHub Actions. Use ccache
to speed up testing.

@item 
bpo-43791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43791}: OpenSSL 3.0.0: Disable testing of legacy protocols TLS 1.0 and
1.1. Tests are failing with TLSV1_ALERT_INTERNAL_ERROR.
@end itemize

@node Windows<10>,macOS<8>,Tests<8>,Python 3 9 5 final
@anchor{whatsnew/changelog id69}@anchor{ff7}
@subsubsection Windows



@itemize -

@item 
bpo-35306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35306}: Avoid raising errors from @ref{337,,pathlib.Path.exists()} when
passed an invalid filename.

@item 
bpo-38822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38822}: Fixed @ref{328,,os.stat()} failing on inaccessible directories with
a trailing slash, rather than falling back to the parent directory's
metadata. This implicitly affected @ref{32c,,os.path.exists()} and
@ref{32e,,os.path.isdir()}.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: Fixed decoding of host names in @ref{ff8,,socket.gethostbyaddr()}
and @ref{ff9,,socket.gethostbyname_ex()}.

@item 
bpo-40432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40432}: Updated pegen regeneration script on Windows to find and use
Python 3.8 or higher.  Prior to this, pegen regeneration already required
3.8 or higher, but the script may have used lower versions of Python.

@item 
bpo-43745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43745}: Actually updates Windows release to OpenSSL 1.1.1k. Earlier
releases were mislabelled and actually included 1.1.1i again.

@item 
bpo-43492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43492}: Upgrade Windows installer to use SQLite 3.35.5.
@end itemize

@node macOS<8>,IDLE<6>,Windows<10>,Python 3 9 5 final
@anchor{whatsnew/changelog id70}@anchor{ffa}
@subsubsection macOS



@itemize -

@item 
bpo-42119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42119}: Fix check for macOS SDK paths when building Python. Narrow
search to match contents of SDKs, namely only files in
@code{/System/Library}, @code{/System/IOSSupport}, and @code{/usr} other than
@code{/usr/local}. Previously, anything under @code{/System} was assumed to be
in an SDK which causes problems with the new file system layout in 10.15+
where user file systems may appear to be mounted under @code{/System}.  Paths
in @code{/Library} were also incorrectly treated as SDK locations.

@item 
bpo-44009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=44009}: Provide "python3.x-intel64" executable to allow reliably
forcing macOS universal2 framework builds to run under Rosetta 2 Intel-64
emulation on Apple Silicon Macs.  This can be useful for testing or when
universal2 wheels are not yet available.

@item 
bpo-43492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43492}: Update macOS installer to use SQLite 3.35.4.
@end itemize

@node IDLE<6>,,macOS<8>,Python 3 9 5 final
@anchor{whatsnew/changelog id71}@anchor{ffb}
@subsubsection IDLE



@itemize -

@item 
bpo-43655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43655}: IDLE dialog windows are now recognized as dialogs by window
managers on macOS and X Window.
@end itemize

@node Python 3 9 4 final,Python 3 9 3 final,Python 3 9 5 final,更新日志
@anchor{whatsnew/changelog python-3-9-4-final}@anchor{ffc}
@subsection Python 3.9.4 final


@emph{Release date: 2021-04-04}

@menu
* Core and Builtins: Core and Builtins<13>. 
* Library: Library<13>. 

@end menu

@node Core and Builtins<13>,Library<13>,,Python 3 9 4 final
@anchor{whatsnew/changelog id72}@anchor{ffd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43710}: Reverted the fix for @indicateurl{https://bugs.python.org/issue42500} as it
changed the PyThreadState struct size and broke the 3.9.x ABI in the 3.9.3
release (visible on 32-bit platforms using binaries compiled using an
earlier version of Python 3.9.x headers).
@end itemize

@node Library<13>,,Core and Builtins<13>,Python 3 9 4 final
@anchor{whatsnew/changelog id73}@anchor{ffe}
@subsubsection Library



@itemize -

@item 
bpo-26053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26053}: Fixed bug where the @ref{c9,,pdb} interactive run command echoed
the args from the shell command line, even if those have been overridden
at the pdb prompt.
@end itemize

@node Python 3 9 3 final,Python 3 9 2 final,Python 3 9 4 final,更新日志
@anchor{whatsnew/changelog python-3-9-3-final}@anchor{fff}
@subsection Python 3.9.3 final


@emph{Release date: 2021-04-02}

@menu
* Security: Security<8>. 
* Core and Builtins: Core and Builtins<14>. 
* Library: Library<14>. 
* Documentation: Documentation<9>. 
* Tests: Tests<9>. 
* Build: Build<7>. 
* macOS: macOS<9>. 
* IDLE: IDLE<7>. 

@end menu

@node Security<8>,Core and Builtins<14>,,Python 3 9 3 final
@anchor{whatsnew/changelog id74}@anchor{1000}
@subsubsection Security



@itemize -

@item 
bpo-42988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42988}: CVE-2021-3426: Remove the @code{getfile} feature of the
@ref{d9,,pydoc} module which could be abused to read arbitrary files on the
disk (directory traversal vulnerability). Moreover, even source code of
Python modules can contain sensitive data like passwords. Vulnerability
reported by David Schwörer.

@item 
bpo-43285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43285}: @ref{82,,ftplib} no longer trusts the IP address value returned
from the server in response to the PASV command by default.  This prevents
a malicious FTP server from using the response to probe IPv4 address and
port combinations on the client network.

Code that requires the former vulnerable behavior may set a
@code{trust_server_pasv_ipv4_address} attribute on their @ref{1a6,,ftplib.FTP}
instances to @code{True} to re-enable it.

@item 
bpo-43439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43439}: Add audit hooks for @ref{305,,gc.get_objects()},
@ref{1001,,gc.get_referrers()} and @ref{1002,,gc.get_referents()}. Patch by Pablo
Galindo.
@end itemize

@node Core and Builtins<14>,Library<14>,Security<8>,Python 3 9 3 final
@anchor{whatsnew/changelog id75}@anchor{1003}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-43660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43660}: Fix crash that happens when replacing @code{sys.stderr} with a
callable that can remove the object while an exception is being printed.
Patch by Pablo Galindo.

@item 
bpo-43555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43555}: Report the column offset for @ref{562,,SyntaxError} for invalid
line continuation characters. Patch by Pablo Galindo.

@item 
bpo-43517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43517}: Fix misdetection of circular imports when using @code{from pkg.mod
import attr}, which caused false positives in non-trivial multi-threaded
code.

@item 
bpo-35883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35883}: Python no longer fails at startup with a fatal error if a
command line argument contains an invalid Unicode character. The
@ref{547,,Py_DecodeLocale()} function now escapes byte sequences which would
be decoded as Unicode characters outside the [U+0000; U+10ffff] range.

@item 
bpo-43406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43406}: Fix a possible race condition where @code{PyErr_CheckSignals}
tries to execute a non-Python signal handler.

@item 
bpo-42500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42500}: Improve handling of exceptions near recursion limit. Converts a
number of Fatal Errors in RecursionErrors.
@end itemize

@node Library<14>,Documentation<9>,Core and Builtins<14>,Python 3 9 3 final
@anchor{whatsnew/changelog id76}@anchor{1004}
@subsubsection Library



@itemize -

@item 
bpo-43433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43433}: @ref{386,,xmlrpc.client.ServerProxy} no longer ignores query and
fragment in the URL of the server.

@item 
bpo-35930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35930}: Raising an exception raised in a "future" instance will create
reference cycles.

@item 
bpo-43577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43577}: Fix deadlock when using @ref{4f2,,ssl.SSLContext} debug callback
with @ref{1005,,ssl.SSLContext.sni_callback()}.

@item 
bpo-43521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43521}: @code{ast.unparse} can now render NaNs and empty sets.

@item 
bpo-43423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43423}: @code{subprocess.communicate()} no longer raises an IndexError
when there is an empty stdout or stderr IO buffer during a timeout on
Windows.

@item 
bpo-27820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27820}: Fixed long-standing bug of smtplib.SMTP where doing AUTH LOGIN
with initial_response_ok=False will fail.

The cause is that SMTP.auth_login _always_ returns a password if provided
with a challenge string, thus non-compliant with the standard for AUTH
LOGIN.

Also fixes bug with the test for smtpd.

@item 
bpo-43332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43332}: Improves the networking efficiency of @ref{93,,http.client} when
using a proxy via @code{set_tunnel()}.  Fewer small send
calls are made during connection setup.

@item 
bpo-43399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43399}: Fix @code{ElementTree.extend} not working on iterators when using
the Python implementation

@item 
bpo-43316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43316}: The @code{python -m gzip} command line application now properly
fails when detecting an unsupported extension. It exits with a non-zero
exit code and prints an error message to stderr.

@item 
bpo-43260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43260}: Fix TextIOWrapper can not flush internal buffer forever after
very large text is written.

@item 
bpo-42782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42782}: Fail fast in @ref{38c,,shutil.move()} to avoid creating
destination directories on failure.

@item 
bpo-37193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37193}: Fixed memory leak in @code{socketserver.ThreadingMixIn} introduced
in Python 3.7.
@end itemize

@node Documentation<9>,Tests<9>,Library<14>,Python 3 9 3 final
@anchor{whatsnew/changelog id77}@anchor{1006}
@subsubsection Documentation



@itemize -

@item 
bpo-43199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43199}: Answer "Why is there no goto?" in the Design and History FAQ.

@item 
bpo-43407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43407}: Clarified that a result from @ref{868,,time.monotonic()},
@ref{3d4,,time.perf_counter()}, @ref{3d5,,time.process_time()}, or
@ref{1e8,,time.thread_time()} can be compared with the result from any
following call to the same function - not just the next immediate call.

@item 
bpo-27646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27646}: Clarify that 'yield from <expr>' works with any iterable, not
just iterators.

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: Update some deprecated unicode APIs which are documented as
"will be removed in 4.0" to "3.12". See 
@geindex Python 提高建议; PEP 623
PEP 623@footnote{https://www.python.org/dev/peps/pep-0623} for detail.
@end itemize

@node Tests<9>,Build<7>,Documentation<9>,Python 3 9 3 final
@anchor{whatsnew/changelog id78}@anchor{1007}
@subsubsection Tests



@itemize -

@item 
bpo-37945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37945}: Fix test_getsetlocale_issue1813() of test_locale: skip the test
if @code{setlocale()} fails. Patch by Victor Stinner.

@item 
bpo-41561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41561}: Add workaround for Ubuntu's custom OpenSSL security level
policy.

@item 
bpo-43288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43288}: Fix test_importlib to correctly skip Unicode file tests if the
fileystem does not support them.
@end itemize

@node Build<7>,macOS<9>,Tests<9>,Python 3 9 3 final
@anchor{whatsnew/changelog id79}@anchor{1008}
@subsubsection Build



@itemize -

@item 
bpo-43631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43631}: Update macOS, Windows, and CI to OpenSSL 1.1.1k.

@item 
bpo-43617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43617}: Improve configure.ac: Check for presence of autoconf-archive
package and remove our copies of M4 macros.
@end itemize

@node macOS<9>,IDLE<7>,Build<7>,Python 3 9 3 final
@anchor{whatsnew/changelog id80}@anchor{1009}
@subsubsection macOS



@itemize -

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Update macOS installer build to use OpenSSL 1.1.1j.
@end itemize

@node IDLE<7>,,macOS<9>,Python 3 9 3 final
@anchor{whatsnew/changelog id81}@anchor{100a}
@subsubsection IDLE



@itemize -

@item 
bpo-42225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42225}: Document that IDLE can fail on Unix either from misconfigured
IP masquerage rules or failure displaying complex colored (non-ascii)
characters.

@item 
bpo-43283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43283}: Document why printing to IDLE's Shell is often slower than
printing to a system terminal and that it can be made faster by
pre-formatting a single string before printing.
@end itemize

@node Python 3 9 2 final,Python 3 9 2 release candidate 1,Python 3 9 3 final,更新日志
@anchor{whatsnew/changelog python-3-9-2-final}@anchor{100b}
@subsection Python 3.9.2 final


@emph{Release date: 2021-02-19}

@menu
* Windows: Windows<11>. 

@end menu

@node Windows<11>,,,Python 3 9 2 final
@anchor{whatsnew/changelog id82}@anchor{100c}
@subsubsection Windows



@itemize -

@item 
bpo-43155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43155}: @code{PyCMethod_New()} is now present in @code{python3.lib}.
@end itemize

@node Python 3 9 2 release candidate 1,Python 3 9 1 final,Python 3 9 2 final,更新日志
@anchor{whatsnew/changelog python-3-9-2-release-candidate-1}@anchor{100d}
@subsection Python 3.9.2 release candidate 1


@emph{Release date: 2021-02-16}

@menu
* Security: Security<9>. 
* Core and Builtins: Core and Builtins<15>. 
* Library: Library<15>. 
* Documentation: Documentation<10>. 
* Tests: Tests<10>. 
* Build: Build<8>. 
* Windows: Windows<12>. 
* macOS: macOS<10>. 
* IDLE: IDLE<8>. 
* Tools/Demos: Tools/Demos<4>. 
* C API: C API<4>. 

@end menu

@node Security<9>,Core and Builtins<15>,,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id83}@anchor{100e}
@subsubsection Security



@itemize -

@item 
bpo-42967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42967}: Fix web cache poisoning vulnerability by defaulting the query
args separator to @code{&}, and allowing the user to choose a custom
separator.

@item 
bpo-42938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42938}: Avoid static buffers when computing the repr of
@ref{100f,,ctypes.c_double} and @ref{1010,,ctypes.c_longdouble} values.
@end itemize

@node Core and Builtins<15>,Library<15>,Security<9>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id84}@anchor{1011}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42819}: @ref{de,,readline}: Explicitly disable bracketed paste in the
interactive interpreter, even if it's set in the inputrc, is enabled by
default (eg GNU Readline 8.1), or a user calls
@code{readline.read_init_file()}. The Python REPL has not implemented
bracketed paste support. Also, bracketed mode writes the @code{"\x1b[?2004h"}
escape sequence into stdout which causes test failures in applications
that don't support it. It can still be explicitly enabled by calling
@code{readline.parse_and_bind("set enable-bracketed-paste on")}. Patch by
Dustin Rodrigues.

@item 
bpo-42806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42806}: Fix the column offsets for f-strings @ref{7,,ast} nodes
surrounded by parentheses and for nodes that spawn multiple lines. Patch
by Pablo Galindo.

@item 
bpo-40631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40631}: Fix regression where a single parenthesized starred expression
was a valid assignment target.

@item 
bpo-32381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32381}: Fix encoding name when running a @code{.pyc} file on Windows:
@ref{1012,,PyRun_SimpleFileExFlags()} now uses the correct encoding to
decode the filename.

@item 
bpo-42536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42536}: Several built-in and standard library types now ensure that
their internal result tuples are always tracked by the @ref{1013,,garbage collector}:


@itemize -

@item 
@ref{2f1,,collections.OrderedDict.items()}

@item 
@ref{cfd,,dict.items()}

@item 
@ref{eaf,,enumerate()}

@item 
@ref{d3f,,functools.reduce()}

@item 
@ref{d76,,itertools.combinations()}

@item 
@ref{ceb,,itertools.combinations_with_replacement()}

@item 
@ref{1014,,itertools.permutations()}

@item 
@ref{d77,,itertools.product()}

@item 
@ref{d03,,itertools.zip_longest()}

@item 
@ref{d04,,zip()}
@end itemize

Previously, they could have become untracked by a prior garbage
collection. Patch by Brandt Bucher.

@item 
bpo-42195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42195}: The @code{__args__} of the parameterized generics for
@ref{27c,,typing.Callable} and @ref{27b,,collections.abc.Callable} are now
consistent.  The @code{__args__} for @ref{27b,,collections.abc.Callable} are
now flattened while @ref{27c,,typing.Callable}'s have not changed.  To allow
this change, @ref{27d,,types.GenericAlias} can now be subclassed and
@code{collections.abc.Callable}'s @code{__class_getitem__} will now return a
subclass of @code{types.GenericAlias}.  Tests for typing were also updated to
not subclass things like @code{Callable[..., T]} as that is not a valid base
class.  Finally, both types no longer validate their @code{argtypes}, in
@code{Callable[[argtypes], resulttype]} to prepare for 
@geindex Python 提高建议; PEP 612
PEP 612@footnote{https://www.python.org/dev/peps/pep-0612}.  Patch by
Ken Jin.
@end itemize

@node Library<15>,Documentation<10>,Core and Builtins<15>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id85}@anchor{1015}
@subsubsection Library



@itemize -

@item 
bpo-43102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43102}: The namedtuple __new__ method had its __builtins__ set to None
instead of an actual dictionary.  This created problems for introspection
tools.

@item 
bpo-43108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43108}: Fixed a reference leak in the @ref{2b,,curses} module. Patch by
Pablo Galindo

@item 
bpo-42944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42944}: Fix @code{random.Random.sample} when @code{counts} argument is not
@code{None}.

@item 
bpo-42931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42931}: Add @code{randbytes()} to @code{random.__all__}.

@item 
bpo-42780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42780}: Fix os.set_inheritable() for O_PATH file descriptors on Linux.

@item 
bpo-42851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42851}: remove __init_subclass__ support for Enum members

@item 
bpo-41748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41748}: Fix HTMLParser parsing rules for element attributes containing
commas with spaces. Patch by Karl Dubost.

@item 
bpo-42759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42759}: Fixed equality comparison of @code{tkinter.Variable} and
@ref{1016,,tkinter.font.Font}. Objects which belong to different Tcl
interpreters are now always different, even if they have the same name.

@item 
bpo-42756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42756}: Configure LMTP Unix-domain socket to use socket global default
timeout when a timeout is not explicitly provided.

@item 
bpo-23328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23328}: Allow / character in username, password fields on _PROXY
envars.

@item 
bpo-42655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42655}: @ref{f9,,subprocess} @emph{extra_groups} is now correctly passed into
setgroups() system call.

@item 
bpo-42727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42727}: @code{EnumMeta.__prepare__} now accepts @code{**kwds} to properly
support @code{__init_subclass__}

@item 
bpo-42681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42681}: Fixed range checks for color and pair numbers in @ref{2b,,curses}.

@item 
bpo-37961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37961}: Fix crash in @code{tracemalloc.Traceback.__repr__()} (regressed
in Python 3.9).

@item 
bpo-42630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42630}: @ref{10e,,tkinter} functions and constructors which need a default
root window raise now @ref{3e4,,RuntimeError} with descriptive message instead
of obscure @ref{4aa,,AttributeError} or @ref{e48,,NameError} if it is not created
yet or cannot be created automatically.

@item 
bpo-42644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42644}: @ref{1017,,logging.disable} will now validate the types and value of its
parameter. It also now accepts strings representing the levels (as does
@code{loging.setLevel}) instead of only the numerical values.

@item 
bpo-36541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36541}: Fixed lib2to3.pgen2 to be able to parse PEP-570 positional only
argument syntax.

@item 
bpo-42517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42517}: Enum: private names will raise a DeprecationWarning; in 3.10
they will become normal attributes

@item 
bpo-42678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42678}: @code{Enum}: call @code{__init_subclass__} after members have been added

@item 
bpo-42532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42532}: Remove unexpected call of @code{__bool__} when passing a
@code{spec_arg} argument to a Mock.

@item 
bpo-42388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42388}: Fix subprocess.check_output(..., input=None) behavior when
text=True to be consistent with that of the documentation and
universal_newlines=True.

@item 
bpo-34463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34463}: Fixed discrepancy between @ref{11c,,traceback} and the interpreter
in formatting of SyntaxError with lineno not set (@ref{11c,,traceback} was
changed to match interpreter).

@item 
bpo-42375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42375}: subprocess module update for DragonFlyBSD support.

@item 
bpo-42384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42384}: Make pdb populate sys.path[0] exactly the same as regular
python execution.

@item 
bpo-42383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42383}: Fix pdb: previously pdb would fail to restart the debugging
target if it was specified using a relative path and the current directory
changed.

@item 
bpo-42318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42318}: Fixed support of non-BMP characters in @ref{10e,,tkinter} on macOS.

@item 
bpo-42163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42163}: Restore compatibility for @code{uname_result} around deepcopy and
_replace.

@item 
bpo-39825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39825}: Windows: Change @code{sysconfig.get_config_var('EXT_SUFFIX')} to
the expected full @code{platform_tag.extension} format. Previously it was
hard-coded to @code{.pyd}, now it is compatible with @code{distutils.sysconfig}
and will result in something like @code{.cp38-win_amd64.pyd}. This brings
windows into conformance with the other platforms.

@item 
bpo-42059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42059}: @ref{36e,,typing.TypedDict} types created using the alternative
call-style syntax now correctly respect the @code{total} keyword argument
when setting their @code{__required_keys__} and @code{__optional_keys__} class
attributes.

@item 
bpo-39101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39101}: Fixed tests using IsolatedAsyncioTestCase from hanging on
BaseExceptions.

@item 
bpo-42005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42005}: Fix CLI of @ref{27,,cProfile} and @ref{d3,,profile} to catch
@ref{a87,,BrokenPipeError}.

@item 
bpo-41907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41907}: fix @ref{5de,,format()} behavior for @code{IntFlag}

@item 
bpo-41889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41889}: Enum: fix regression involving inheriting a multiply-inherited
enum

@item 
bpo-41891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41891}: Ensure asyncio.wait_for waits for task completion

@item 
bpo-41604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41604}: Don't decrement the reference count of the previous user_ptr
when set_panel_userptr fails.

@item 
bpo-40219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40219}: Lowered @code{tkinter.ttk.LabeledScale} dummy widget to
prevent hiding part of the content label.

@item 
bpo-40084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40084}: Fix @code{Enum.__dir__}: dir(Enum.member) now includes attributes
as well as methods.

@item 
bpo-39068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39068}: Fix initialization race condition in @code{a85encode()} and
@code{b85encode()} in @ref{d,,base64}. Patch by Brandon Stansbury.

@item 
bpo-33289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33289}: Correct call to @ref{10f,,tkinter.colorchooser} to return RGB
triplet of ints instead of floats.  Patch by Cheryl Sabella.
@end itemize

@node Documentation<10>,Tests<10>,Library<15>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id86}@anchor{1018}
@subsubsection Documentation



@itemize -

@item 
bpo-40304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40304}: Fix doc for type(name, bases, dict).  Patch by Boris
Verkhovskiy and Éric Araujo.

@item 
bpo-42811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42811}: Updated importlib.utils.resolve_name() doc to use
__spec__.parent instead of __package__. (Thanks Yair Frid.)

@item 
bpo-17140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17140}: Add documentation for the
@ref{1019,,multiprocessing.pool.ThreadPool} class.
@end itemize

@node Tests<10>,Build<8>,Documentation<10>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id87}@anchor{101a}
@subsubsection Tests



@itemize -

@item 
bpo-42794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42794}: Update test_nntplib to use offical group name of news.aioe.org
for testing. Patch by Dong-hee Na.

@item 
bpo-40810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40810}: In @ref{f2,,sqlite3}, fix @code{CheckTraceCallbackContent} for SQLite
pre 3.7.15.
@end itemize

@node Build<8>,Windows<12>,Tests<10>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id88}@anchor{101b}
@subsubsection Build



@itemize -

@item 
bpo-43174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43174}: Windows build now uses @code{/utf-8} compiler option.

@item 
bpo-42692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42692}: Fix __builtin_available check on older compilers. Patch by
Joshua Root.

@item 
bpo-42604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42604}: Now all platforms use a value for the "EXT_SUFFIX" build
variable derived from SOABI (for instance in freeBSD, "EXT_SUFFIX" is now
".cpython-310d.so" instead of ".so"). Previosuly only Linux, Mac and
VxWorks were using a value for "EXT_SUFFIX" that included "SOABI".

@item 
bpo-42598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42598}: Fix implicit function declarations in configure which could
have resulted in incorrect configuration checks.  Patch contributed by
Joshua Root.

@item 
bpo-29076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29076}: Add fish shell support to macOS installer.
@end itemize

@node Windows<12>,macOS<10>,Build<8>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id89}@anchor{101c}
@subsubsection Windows



@itemize -

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Updated Windows installer to include OpenSSL 1.1.1i

@item 
bpo-42584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42584}: Upgrade Windows installer to use SQLite 3.34.0.
@end itemize

@node macOS<10>,IDLE<8>,Windows<12>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id90}@anchor{101d}
@subsubsection macOS



@itemize -

@item 
bpo-42504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42504}: Ensure that the value of
sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') is always a string,
even in when the value is parsable as an integer.

@item 
bpo-42361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42361}: Update macOS installer build to use Tcl/Tk 8.6.11 (rc2,
expected to be final release).

@item 
bpo-41837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41837}: Update macOS installer build to use OpenSSL 1.1.1i.

@item 
bpo-42584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42584}: Update macOS installer to use SQLite 3.34.0.
@end itemize

@node IDLE<8>,Tools/Demos<4>,macOS<10>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id91}@anchor{101e}
@subsubsection IDLE



@itemize -

@item 
bpo-43008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43008}: Make IDLE invoke @ref{1ae,,sys.excepthook()} in normal, 2-process
mode. Patch by Ken Hilton.

@item 
bpo-33065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33065}: Fix problem debugging user classes with __repr__ method.

@item 
bpo-23544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23544}: Disable Debug=>Stack Viewer when user code is running or
Debugger is active, to prevent hang or crash.  Patch by Zackery Spytz.

@item 
bpo-32631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32631}: Finish zzdummy example extension module: make menu entries
work; add docstrings and tests with 100% coverage.
@end itemize

@node Tools/Demos<4>,C API<4>,IDLE<8>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id92}@anchor{101f}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-42726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42726}: Fixed Python 3 compatibility issue with gdb/libpython.py
handling of attribute dictionaries.

@item 
bpo-42613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42613}: Fix @code{freeze.py} tool to use the prope config and library
directories. Patch by Victor Stinner.
@end itemize

@node C API<4>,,Tools/Demos<4>,Python 3 9 2 release candidate 1
@anchor{whatsnew/changelog id93}@anchor{1020}
@subsubsection C API



@itemize -

@item 
bpo-43030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=43030}: Fixed a compiler warning in @ref{1021,,Py_UNICODE_ISSPACE()} on
platforms with signed @code{wchar_t}.

@item 
bpo-42591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42591}: Export the @code{Py_FrozenMain()} function: fix a Python 3.9.0
regression. Python 3.9 uses @code{-fvisibility=hidden} and the function was
not exported explicitly and so not exported.

@item 
bpo-40052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40052}: Fix an alignment build warning/error in function
@code{PyVectorcall_Function()}. Patch by Andreas Schneider, Antoine Pitrou
and Petr Viktorin.
@end itemize

@node Python 3 9 1 final,Python 3 9 1 release candidate 1,Python 3 9 2 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-9-1-final}@anchor{1022}
@subsection Python 3.9.1 final


@emph{Release date: 2020-12-07}

@menu
* Core and Builtins: Core and Builtins<16>. 
* Library: Library<16>. 
* Tests: Tests<11>. 
* macOS: macOS<11>. 
* IDLE: IDLE<9>. 

@end menu

@node Core and Builtins<16>,Library<16>,,Python 3 9 1 final
@anchor{whatsnew/changelog id94}@anchor{1023}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-42576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42576}: @code{types.GenericAlias} will now raise a @code{TypeError} when
attempting to initialize with a keyword argument.  Previously, this would
cause the interpreter to crash if the interpreter was compiled with debug
symbols. This does not affect interpreters compiled for release.  Patch by
Ken Jin.
@end itemize

@node Library<16>,Tests<11>,Core and Builtins<16>,Python 3 9 1 final
@anchor{whatsnew/changelog id95}@anchor{1024}
@subsubsection Library



@itemize -

@item 
bpo-5054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5054}: CGIHTTPRequestHandler.run_cgi() HTTP_ACCEPT improperly parsed.
Replace the special purpose getallmatchingheaders with generic get_all
method and add relevant tests.

Original Patch by Martin Panter. Modified by Senthil Kumaran.

@item 
bpo-17735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17735}: @code{inspect.findsource()} now raises @ref{30b,,OSError} instead of
@ref{f3d,,IndexError} when @code{co_lineno} of a code object is greater than
the file length. This can happen, for example, when a file is edited after
it was imported.  PR by Irit Katriel.

@item 
bpo-42116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42116}: Fix handling of trailing comments by @ref{1025,,inspect.getsource()}.

@item 
bpo-42487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42487}: ChainMap.__iter__ no longer calls __getitem__ on underlying
maps

@item 
bpo-42482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42482}: @ref{86f,,TracebackException} no longer holds a
reference to the exception's traceback object. Consequently, instances of
TracebackException for equivalent but non-equal exceptions now compare as
equal.

@item 
bpo-42406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42406}: We fixed an issue in @code{pickle.whichmodule} in which importing
@ref{b7,,multiprocessing} could change the how pickle identifies which module an
object belongs to, potentially breaking the unpickling of those objects.

@item 
bpo-34215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34215}: Clarify the error message for
@ref{1026,,asyncio.IncompleteReadError} when @code{expected} is @code{None}.

@item 
bpo-12800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12800}: Extracting a symlink from a tarball should succeed and
overwrite the symlink if it already exists. The fix is to remove the
existing file or symlink before extraction. Based on patch by Chris AtLee,
Jeffrey Kintscher, and Senthil Kumaran.
@end itemize

@node Tests<11>,macOS<11>,Library<16>,Python 3 9 1 final
@anchor{whatsnew/changelog id96}@anchor{1027}
@subsubsection Tests



@itemize -

@item 
bpo-41473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41473}: Reenable test_gdb on gdb 9.2 and newer:
@indicateurl{https://bugzilla.redhat.com/show_bug.cgi?id=1866884} bug is fixed in gdb
10.1.

@item 
bpo-42553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42553}: Fix @code{test_asyncio.test_call_later()} race condition: don't
measure asyncio performance in the @code{call_later()} unit test. The test
failed randomly on the CI.
@end itemize

@node macOS<11>,IDLE<9>,Tests<11>,Python 3 9 1 final
@anchor{whatsnew/changelog id97}@anchor{1028}
@subsubsection macOS



@itemize -

@item 
bpo-41116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41116}: If no explicit macOS SDK was specified, setup.py should check
for Tcl and TK frameworks in /Library/Frameworks; the previous commit
inadvertently broke that test.

@item 
bpo-42504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42504}: Fix build on macOS Big Sur when MACOSX_DEPLOYMENT_TARGET=11
@end itemize

@node IDLE<9>,,macOS<11>,Python 3 9 1 final
@anchor{whatsnew/changelog id98}@anchor{1029}
@subsubsection IDLE



@itemize -

@item 
bpo-42508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42508}: Keep IDLE running on macOS.  Remove obsolete workaround that
prevented running files with shortcuts when using new universal2
installers built on macOS 11.
@end itemize

@node Python 3 9 1 release candidate 1,Python 3 9 0 final,Python 3 9 1 final,更新日志
@anchor{whatsnew/changelog python-3-9-1-release-candidate-1}@anchor{102a}
@subsection Python 3.9.1 release candidate 1


@emph{Release date: 2020-11-24}

@menu
* Security: Security<10>. 
* Core and Builtins: Core and Builtins<17>. 
* Library: Library<17>. 
* Documentation: Documentation<11>. 
* Tests: Tests<12>. 
* Build: Build<9>. 
* Windows: Windows<13>. 
* macOS: macOS<12>. 
* IDLE: IDLE<10>. 
* C API: C API<5>. 

@end menu

@node Security<10>,Core and Builtins<17>,,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id99}@anchor{102b}
@subsubsection Security



@itemize -

@item 
bpo-42103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42103}: Prevented potential DoS attack via CPU and RAM exhaustion when
processing malformed Apple Property List files in binary format.

@item 
bpo-42051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42051}: The @ref{cf,,plistlib} module no longer accepts entity
declarations in XML plist files to avoid XML vulnerabilities. This should
not affect users as entity declarations are not used in regular plist
files.

@item 
bpo-40791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40791}: Add @code{volatile} to the accumulator variable in
@code{hmac.compare_digest}, making constant-time-defeating optimizations less
likely.
@end itemize

@node Core and Builtins<17>,Library<17>,Security<10>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id100}@anchor{102c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41686}: On Windows, the @code{SIGINT} event, @code{_PyOS_SigintEvent()}, is
now created even if Python is configured to not install signal handlers
(if @ref{102d,,PyConfig.install_signal_handlers} equals to 0, or
@code{Py_InitializeEx(0)}).

@item 
bpo-42381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42381}: Allow assignment expressions in set literals and set
comprehensions as per PEP 572. Patch by Pablo Galindo.

@item 
bpo-42374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42374}: Fix a regression introduced by the new parser, where an
unparenthesized walrus operator was not allowed within generator
expressions.

@item 
bpo-42296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42296}: On Windows, fix a regression in signal handling which prevented
to interrupt a program using CTRL+C. The signal handler can be run in a
thread different than the Python thread, in which case the test deciding
if the thread can handle signals is wrong.

@item 
bpo-42332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42332}: @ref{27d,,types.GenericAlias} objects can now be the targets of
weakrefs.

@item 
bpo-42218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42218}: Fixed a bug in the PEG parser that was causing crashes in debug
mode. Now errors are checked in left-recursive rules to avoid cases where
such errors do not get handled in time and appear as long-distance crashes
in other places.

@item 
bpo-42214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42214}: Fixed a possible crash in the PEG parser when checking for the
'!=' token in the @code{barry_as_flufl} rule. Patch by Pablo Galindo.

@item 
bpo-42143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42143}: Fix handling of errors during creation of @code{PyFunctionObject},
which resulted in operations on uninitialized memory. Patch by Yonatan
Goldschmidt.

@item 
bpo-41659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41659}: Fix a bug in the parser, where a curly brace following a
@code{primary} didn't fail immediately. This led to invalid expressions like @code{a
@{b@}} to throw a @ref{562,,SyntaxError} with a wrong offset, or invalid
expressions ending with a curly brace like @code{a @{} to not fail immediately
in the REPL.

@item 
bpo-42150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42150}: Fix possible buffer overflow in the new parser when checking
for continuation lines. Patch by Pablo Galindo.

@item 
bpo-42123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42123}: Run the parser two times. On the first run, disable all the
rules that only generate better error messages to gain performance. If
there's a parse failure, run the parser a second time with those enabled.

@item 
bpo-42057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42057}: Fix peephole optimizer misoptimize conditional jump +
JUMP_IF_NOT_EXC_MATCH pair.

@item 
bpo-41984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41984}: The garbage collector now tracks all user-defined classes.
Patch by Brandt Bucher.

@item 
bpo-41993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41993}: Fixed potential issues with removing not completely initialized
module from @code{sys.modules} when import fails.

@item 
bpo-41979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41979}: Star-unpacking is now allowed for with item's targets in the
PEG parser.

@item 
bpo-41909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41909}: Fixed stack overflow in @ref{55b,,issubclass()} and
@ref{55a,,isinstance()} when getting the @code{__bases__} attribute leads to
infinite recursion.

@item 
bpo-41894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41894}: When loading a native module and a load failure occurs, prevent
a possible UnicodeDecodeError when not running in a UTF-8 locale by
decoding the load error message using the current locale's encoding.

@item 
bpo-39934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39934}: Correctly count control blocks in 'except' in compiler. Ensures
that a syntax error, rather a fatal error, occurs for deeply nested, named
exception handlers.
@end itemize

@node Library<17>,Documentation<11>,Core and Builtins<17>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id101}@anchor{102e}
@subsubsection Library



@itemize -

@item 
bpo-42328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42328}: Fixed @ref{102f,,tkinter.ttk.Style.map()}. The function accepts now
the representation of the default state as empty sequence (as returned by
@code{Style.map()}). The structure of the result is now the same on all
platform and does not depend on the value of @code{wantobjects}.

@item 
bpo-42345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42345}: Fix various issues with @code{typing.Literal} parameter handling
(flatten, deduplicate, use type to cache key). Patch provided by Yurii
Karabas.

@item 
bpo-42350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42350}: Fix the @ref{21b,,threading.Thread} class at fork: do nothing if
the thread is already stopped (ex: fork called at Python exit).
Previously, an error was logged in the child process.

@item 
bpo-42014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42014}: The @code{onerror} callback from @code{shutil.rmtree} now receives
correct function when @code{os.open} fails.

@item 
bpo-42237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42237}: Fix @ref{46a,,os.sendfile()} on illumos.

@item 
bpo-42249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42249}: Fixed writing binary Plist files larger than 4 GiB.

@item 
bpo-35455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35455}: On Solaris, @ref{1e8,,thread_time()} is now implemented with
@code{gethrvtime()} because @code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)} is not
always available. Patch by Jakub Kulik.

@item 
bpo-42233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42233}: The @ref{8c3,,repr()} of @ref{122,,typing} types containing
@ref{1030,,Generic Alias Types} previously did not show
the parameterized types in the @code{GenericAlias}.  They have now been
changed to do so.

@item 
bpo-41754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41754}: webbrowser: Ignore @emph{NotADirectoryError} when calling
@code{xdg-settings}.

@item 
bpo-29566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29566}: @code{binhex.binhex()} consistently writes macOS 9 line endings.

@item 
bpo-42183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42183}: Fix a stack overflow error for asyncio Task or Future repr().

The overflow occurs under some circumstances when a Task or Future
recursively returns itself.

@item 
bpo-42146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42146}: Fix memory leak in @ref{3e3,,subprocess.Popen()} in case an uid
(gid) specified in @code{user} (@code{group}, @code{extra_groups}) overflows @code{uid_t}
(@code{gid_t}).

@item 
bpo-42140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42140}: Improve asyncio.wait function to create the futures set just
one time.

@item 
bpo-42103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42103}: @code{InvalidFileException} and @ref{731,,RecursionError}
are now the only errors caused by loading malformed binary Plist file
(previously ValueError and TypeError could be raised in some specific
cases).

@item 
bpo-41052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41052}: Pickling heap types implemented in C with protocols 0 and 1
raises now an error instead of producing incorrect data.

@item 
bpo-41491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41491}: plistlib: fix parsing XML plists with hexadecimal integer
values

@item 
bpo-42065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42065}: Fix an incorrectly formatted error from
@code{_codecs.charmap_decode()} when called with a mapped value outside the
range of valid Unicode code points. PR by Max Bernstein.

@item 
bpo-41966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41966}: Fix pickling pure Python @ref{5f5,,datetime.time} subclasses.
Patch by Dean Inwood.

@item 
bpo-41976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41976}: Fixed a bug that was causing @ref{70b,,ctypes.util.find_library()}
to return @code{None} when triying to locate a library in an environment when
gcc>=9 is available and @code{ldconfig} is not. Patch by Pablo Galindo

@item 
bpo-41900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41900}: C14N 2.0 serialisation in xml.etree.ElementTree failed for
unprefixed attributes when a default namespace was defined.

@item 
bpo-41840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41840}: Fix a bug in the @ref{fc,,symtable} module that was causing
module-scope global variables to not be reported as both local and global.
Patch by Pablo Galindo.

@item 
bpo-41831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41831}: @code{str()} for the @code{type} attribute of the @code{tkinter.Event}
object always returns now the numeric code returned by Tk instead of the
name of the event type.

@item 
bpo-41817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41817}: fix @code{tkinter.EventType} Enum so all members are strings, and
none are tuples

@item 
bpo-41815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41815}: Fix SQLite3 segfault when backing up closed database. Patch
contributed by Peter David McCormick.

@item 
bpo-41316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41316}: Fix the @ref{101,,tarfile} module to write only basename of TAR
file to GZIP compression header.

@item 
bpo-16396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16396}: Allow @code{ctypes.wintypes} to be imported on non-Windows
systems.

@item 
bpo-40592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40592}: @ref{1031,,shutil.which()} now ignores empty entries in
@geindex PATHEXT
@geindex 环境变量; PATHEXT
@code{PATHEXT} instead of treating them as a match.

@item 
bpo-40550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40550}: Fix time-of-check/time-of-action issue in
subprocess.Popen.send_signal.

@item 
bpo-40492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40492}: Fix @code{--outfile} for @ref{27,,cProfile} / @ref{d3,,profile} not
writing the output file in the original directory when the program being
profiled changes the working directory.  PR by Anthony Sottile.

@item 
bpo-40105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40105}: ZipFile truncates files to avoid corruption when a shorter
comment is provided in append ("a") mode. Patch by Jan Mazur.

@item 
bpo-27321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27321}: Fixed KeyError exception when flattening an email to a string
attempts to replace a non-existent Content-Transfer-Encoding header.
@end itemize

@node Documentation<11>,Tests<12>,Library<17>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id102}@anchor{1032}
@subsubsection Documentation



@itemize -

@item 
bpo-42153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42153}: Fix the URL for the IMAP protocol documents.

@item 
bpo-42061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42061}: Document __format__ functionality for IP addresses.

@item 
bpo-41910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41910}: Document the default implementation of @ref{454,,object.__eq__}.

@item 
bpo-42010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42010}: Clarify that subscription expressions are also valid for
certain @ref{1033,,classes} and @ref{1034,,types} in the standard
library, and for user-defined classes and types if the classmethod
@ref{440,,__class_getitem__()} is provided.

@item 
bpo-41805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41805}: Documented @ref{1030,,generic alias type} and
@ref{27d,,types.GenericAlias}. Also added an entry in glossary for
@ref{1035,,generic types}.

@item 
bpo-41774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41774}: In Programming FAQ "Sequences (Tuples/Lists)" section, add "How
do you remove multiple items from a list".

@item 
bpo-35293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35293}: Fix RemovedInSphinx40Warning when building the documentation.
Patch by Dong-hee Na.

@item 
bpo-41726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41726}: Update the refcounts info of @code{PyType_FromModuleAndSpec}.

@item 
bpo-39693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39693}: Fix tarfile's extractfile documentation

@item 
bpo-39416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39416}: Document some restrictions on the default string
representations of numeric classes.
@end itemize

@node Tests<12>,Build<9>,Documentation<11>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id103}@anchor{1036}
@subsubsection Tests



@itemize -

@item 
bpo-40754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40754}: Include @code{_testinternalcapi} module in Windows installer for
test suite

@item 
bpo-41739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41739}: Fix test_logging.test_race_between_set_target_and_flush(): the
test now waits until all threads complete to avoid leaking running
threads.

@item 
bpo-41970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41970}: Avoid a test failure in @code{test_lib2to3} if the module has
already imported at the time the test executes. Patch by Pablo Galindo.

@item 
bpo-41944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41944}: Tests for CJK codecs no longer call @code{eval()} on content
received via HTTP.

@item 
bpo-41939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41939}: Fix test_site.test_license_exists_at_url(): call
@code{urllib.request.urlcleanup()} to reset the global
@code{urllib.request._opener}. Patch by Victor Stinner.

@item 
bpo-41561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41561}: test_ssl: skip test_min_max_version_mismatch when TLS 1.0 is
not available

@item 
bpo-41602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41602}: Add tests for SIGINT handling in the runpy module.

@item 
bpo-41306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41306}: Fixed a failure in @code{test_tk.test_widgets.ScaleTest} happening
when executing the test with Tk 8.6.10.
@end itemize

@node Build<9>,Windows<13>,Tests<12>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id104}@anchor{1037}
@subsubsection Build



@itemize -

@item 
bpo-42398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42398}: Fix a race condition in "make regen-all" when make -jN option
is used to run jobs in parallel. The clinic.py script now only use atomic
write to write files. Moveover, generated files are now left unchanged if
the content does not change, to not change the file modification time.

@item 
bpo-41617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41617}: Fix building @code{pycore_bitutils.h} internal header on old clang
version without @code{__builtin_bswap16()} (ex: Xcode 4.6.3 on Mac OS X
10.7). Patch by Joshua Root and Victor Stinner.

@item 
bpo-38249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38249}: Update @ref{52f,,Py_UNREACHABLE} to use __builtin_unreachable()
if only the compiler is able to use it. Patch by Dong-hee Na.

@item 
bpo-40998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40998}: Addressed three compiler warnings found by undefined behavior
sanitizer (ubsan).
@end itemize

@node Windows<13>,macOS<12>,Build<9>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id105}@anchor{1038}
@subsubsection Windows



@itemize -

@item 
bpo-42120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42120}: Remove macro definition of @code{copysign} (to @code{_copysign}) in
headers.

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Updates the icons for IDLE in the Windows Store package.

@item 
bpo-41744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41744}: Fixes automatic import of props file when using the Nuget
package.

@item 
bpo-41557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41557}: Update Windows installer to use SQLite 3.33.0.

@item 
bpo-38324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38324}: Avoid Unicode errors when accessing certain locale data on
Windows.
@end itemize

@node macOS<12>,IDLE<10>,Windows<13>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id106}@anchor{1039}
@subsubsection macOS



@itemize -

@item 
bpo-41116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41116}: Ensure distutils.unixxcompiler.find_library_file can find
system provided libraries on macOS 11.

@item 
bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100}: Add support for macOS 11 and Apple Silicon systems.

It is now possible to build "Universal 2" binaries using
"--enable-universalsdk --with-universal-archs=universal2".

Binaries build on later macOS versions can be deployed back to older
versions (tested up to macOS 10.9), when using the correct deployment
target. This is tested using Xcode 11 and later.

@item 
bpo-38443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38443}: The @code{--enable-universalsdk} and @code{--with-universal-archs}
options for the configure script now check that the specified
architectures can be used.

@item 
bpo-41471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41471}: Ignore invalid prefix lengths in system proxy excludes.

@item 
bpo-41557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41557}: Update macOS installer to use SQLite 3.33.0.
@end itemize

@node IDLE<10>,C API<5>,macOS<12>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id107}@anchor{103a}
@subsubsection IDLE



@itemize -

@item 
bpo-42426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42426}: Fix reporting offset of the RE error in searchengine.

@item 
bpo-42415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42415}: Get docstrings for IDLE calltips more often by using
inspect.getdoc.

@item 
bpo-33987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33987}: Mostly finish using ttk widgets, mainly for editor, settings,
and searches. Some patches by Mark Roseman.

@item 
bpo-41775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41775}: Use 'IDLE Shell' as shell title

@item 
bpo-35764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35764}: Rewrite the Calltips doc section.

@item 
bpo-40181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40181}: In calltips, stop reminding that '/' marks the end of
positional-only arguments.

@item 
bpo-40511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40511}: Typing opening and closing parentheses inside the parentheses
of a function call will no longer cause unnecessary "flashing" off and on
of an existing open call-tip, e.g. when typed in a string literal.

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Add a 256×256 pixel IDLE icon to the Windows .ico file. Created
by Andrew Clover. Remove the low-color gif variations from the .ico file.
@end itemize

@node C API<5>,,IDLE<10>,Python 3 9 1 release candidate 1
@anchor{whatsnew/changelog id108}@anchor{103b}
@subsubsection C API



@itemize -

@item 
bpo-42015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=42015}: Fix potential crash in deallocating method objects when
dynamically allocated @code{PyMethodDef}'s lifetime is managed through the
@code{self} argument of a @code{PyCFunction}.

@item 
bpo-41986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41986}: @code{Py_FileSystemDefaultEncodeErrors} and
@code{Py_UTF8Mode} are available again in limited API.
@end itemize

@node Python 3 9 0 final,Python 3 9 0 release candidate 2,Python 3 9 1 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-9-0-final}@anchor{103c}
@subsection Python 3.9.0 final


@emph{Release date: 2020-10-04}

@menu
* Library: Library<18>. 
* Tests: Tests<13>. 
* Build: Build<10>. 

@end menu

@node Library<18>,Tests<13>,,Python 3 9 0 final
@anchor{whatsnew/changelog id109}@anchor{103d}
@subsubsection Library



@itemize -

@item 
bpo-41815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41815}: Fix SQLite3 segfault when backing up closed database. Patch
contributed by Peter David McCormick.

@item 
bpo-41662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41662}: No longer override exceptions raised in @code{__len__()} of a
sequence of parameters in @ref{f2,,sqlite3} with
@ref{f79,,ProgrammingError}.

@item 
bpo-41662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41662}: Fixed crash when mutate list of parameters during iteration in
@ref{f2,,sqlite3}.

@item 
bpo-39728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39728}: fix default @code{_missing_} so a duplicate @ref{16d,,ValueError} is not set
as the @code{__context__} of the original @ref{16d,,ValueError}
@end itemize

@node Tests<13>,Build<10>,Library<18>,Python 3 9 0 final
@anchor{whatsnew/changelog id110}@anchor{103e}
@subsubsection Tests



@itemize -

@item 
bpo-41602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41602}: Add tests for SIGINT handling in the runpy module.
@end itemize

@node Build<10>,,Tests<13>,Python 3 9 0 final
@anchor{whatsnew/changelog id111}@anchor{103f}
@subsubsection Build



@itemize -

@item 
bpo-38249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38249}: Update @ref{52f,,Py_UNREACHABLE} to use __builtin_unreachable()
if only the compiler is able to use it. Patch by Dong-hee Na.
@end itemize

@node Python 3 9 0 release candidate 2,Python 3 9 0 release candidate 1,Python 3 9 0 final,更新日志
@anchor{whatsnew/changelog python-3-9-0-release-candidate-2}@anchor{1040}
@subsection Python 3.9.0 release candidate 2


@emph{Release date: 2020-09-16}

@menu
* Core and Builtins: Core and Builtins<18>. 
* Library: Library<19>. 
* Documentation: Documentation<12>. 
* Tests: Tests<14>. 
* Build: Build<11>. 
* Windows: Windows<14>. 
* C API: C API<6>. 

@end menu

@node Core and Builtins<18>,Library<19>,,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id112}@anchor{1041}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41780}: Fix @ref{434,,__dir__()} of @ref{27d,,types.GenericAlias}. Patch by
Batuhan Taskaya.

@item 
bpo-41690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41690}: Fix a possible stack overflow in the parser when parsing
functions and classes with a huge ammount of arguments. Patch by Pablo
Galindo.

@item 
bpo-41681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41681}: Fixes the wrong error description in the error raised by using
2 @code{,} in format string in f-string and @ref{5dd,,str.format()}.

@item 
bpo-41654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41654}: Fix a crash that occurred when destroying subclasses of
@ref{fb5,,MemoryError}. Patch by Pablo Galindo.

@item 
bpo-41631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41631}: The @code{_ast} module uses again a global state. Using a module
state per module instance is causing subtle practical problems. For
example, the Mercurial project replaces the @code{__import__()} function to
implement lazy import, whereas Python expected that @code{import _ast} always
return a fully initialized @code{_ast} module.

@item 
bpo-41533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41533}: Free the stack allocated in @code{va_build_stack} if
@code{do_mkstack} fails and the stack is not a @code{small_stack}.

@item 
bpo-41531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41531}: Fix a bug that was dropping keys when compiling dict literals
with more than 0xFFFF elements. Patch by Pablo Galindo.

@item 
bpo-41525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41525}: The output of @code{python --help} contains now only ASCII
characters.

@item 
bpo-29590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29590}: Make the stack trace correct after calling
@ref{1042,,generator.throw()} on a generator that has yielded from a @code{yield
from}.
@end itemize

@node Library<19>,Documentation<12>,Core and Builtins<18>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id113}@anchor{1043}
@subsubsection Library



@itemize -

@item 
bpo-41517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41517}: fix bug allowing Enums to be extended via multiple inheritance

@item 
bpo-39587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39587}: use the correct mix-in data type when constructing Enums

@item 
bpo-41789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41789}: Honor @ref{3da,,object} overrides in @code{Enum} class creation
(specifically, @code{__str__}, @code{__repr__}, @code{__format__}, and @code{__reduce_ex__}).

@item 
bpo-39651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39651}: Fix a race condition in the @code{call_soon_threadsafe()} method
of @code{asyncio.ProactorEventLoop}: do nothing if the self-pipe socket has
been closed.

@item 
bpo-41720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41720}: Fixed @code{turtle.Vec2D.__rmul__()} for arguments which are not
int or float.

@item 
bpo-41696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41696}: Fix handling of debug mode in @ref{18d,,asyncio.run()}. This allows
setting @code{PYTHONASYNCIODEBUG} or @code{-X dev} to enable asyncio debug mode
when using @ref{18d,,asyncio.run()}.

@item 
bpo-41687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41687}: Fix implementation of sendfile to be compatible with Solaris.

@item 
bpo-39010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39010}: Restarting a @code{ProactorEventLoop} on Windows no longer logs
spurious @code{ConnectionResetErrors}.

@item 
bpo-41609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41609}: The pdb whatis command correctly reports instance methods as
'Method' rather than 'Function'.

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{191,,asyncio.wait_for()} will now wait until the cancellation is complete
also in the case when @emph{timeout} is <= 0, like it does with positive
timeouts.

@item 
bpo-37658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37658}: @ref{191,,asyncio.wait_for()} now properly handles races between
cancellation of itself and the completion of the wrapped awaitable.

@item 
bpo-40782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40782}: Change the method asyncio.AbstractEventLoop.run_in_executor to
not be a coroutine.

@item 
bpo-41520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41520}: Fix @ref{1c,,codeop} regression that prevented turning compile
warnings into errors.

@item 
bpo-41503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41503}: Fixed a race between setTarget and flush in
logging.handlers.MemoryHandler.

@item 
bpo-41344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41344}: Prevent creating @code{shared_memory.SharedMemory} objects
with @code{size=0}.

@item 
bpo-41025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41025}: Fixed an issue preventing the C implementation of
@ref{17f,,zoneinfo.ZoneInfo} from being subclassed.

@item 
bpo-31122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31122}: ssl.wrap_socket() now raises ssl.SSLEOFError rather than
OSError when peer closes connection during TLS negotiation

@item 
bpo-33660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33660}: Fix pathlib.PosixPath to resolve a relative path located on the
root directory properly.
@end itemize

@node Documentation<12>,Tests<14>,Library<19>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id114}@anchor{1044}
@subsubsection Documentation



@itemize -

@item 
bpo-37149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37149}: Change Shipman tkinter doc link from archive.org to TkDocs.
(The doc has been removed from the NMT server.)  The new link responds
much faster and includes a short explanatory note.

@item 
bpo-41624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41624}: Fix the signature of @ref{1045,,typing.Coroutine}.

@item 
bpo-40204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40204}: Enable Sphinx 3.2 @code{c_allow_pre_v3} option and disable
@code{c_warn_on_allowed_pre_v3} option to make the documentation compatible
with Sphinx 2 and Sphinx 3.

@item 
bpo-40979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40979}: Refactored typing.rst, arranging more than 70 classes,
functions, and decorators into new sub-sections.

@item 
bpo-39883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39883}: Make code, examples, and recipes in the Python documentation be
licensed under the more permissive BSD0 license in addition to the
existing Python 2.0 license.
@end itemize

@node Tests<14>,Build<11>,Documentation<12>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id115}@anchor{1046}
@subsubsection Tests



@itemize -

@item 
bpo-41731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41731}: Make test_cmd_line_script pass with option '-vv'.
@end itemize

@node Build<11>,Windows<14>,Tests<14>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id116}@anchor{1047}
@subsubsection Build



@itemize -

@item 
bpo-41617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41617}: Fix @code{pycore_byteswap.h} header file to support old clang
versions: @code{__builtin_bswap16()} is not available in LLVM clang 3.0.
@end itemize

@node Windows<14>,C API<6>,Build<11>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id117}@anchor{1048}
@subsubsection Windows



@itemize -

@item 
bpo-41526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41526}: Fixed layout of final page of the installer by removing the
special thanks to Mark Hammond (with his permission).
@end itemize

@node C API<6>,,Windows<14>,Python 3 9 0 release candidate 2
@anchor{whatsnew/changelog id118}@anchor{1049}
@subsubsection C API



@itemize -

@item 
bpo-41524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41524}: Fix bug in PyOS_mystrnicmp and PyOS_mystricmp that incremented
pointers beyond the end of a string.
@end itemize

@node Python 3 9 0 release candidate 1,Python 3 9 0 beta 5,Python 3 9 0 release candidate 2,更新日志
@anchor{whatsnew/changelog python-3-9-0-release-candidate-1}@anchor{104a}
@subsection Python 3.9.0 release candidate 1


@emph{Release date: 2020-08-11}

@menu
* Core and Builtins: Core and Builtins<19>. 
* Library: Library<20>. 
* Documentation: Documentation<13>. 
* Windows: Windows<15>. 
* IDLE: IDLE<11>. 

@end menu

@node Core and Builtins<19>,Library<20>,,Python 3 9 0 release candidate 1
@anchor{whatsnew/changelog id119}@anchor{104b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-38156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38156}: Handle interrupts that come after EOF correctly in
@code{PyOS_StdioReadline}.
@end itemize

@node Library<20>,Documentation<13>,Core and Builtins<19>,Python 3 9 0 release candidate 1
@anchor{whatsnew/changelog id120}@anchor{104c}
@subsubsection Library



@itemize -

@item 
bpo-41497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41497}: Fix potential UnicodeDecodeError in dis module.

@item 
bpo-41490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41490}: Update @ref{78,,ensurepip} to install pip 20.2.1 and setuptools
49.2.1.

@item 
bpo-41467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41467}: On Windows, fix asyncio @code{recv_into()} return value when the
socket/pipe is closed (@ref{a87,,BrokenPipeError}): return @code{0} rather than
an empty byte string (@code{b'@w{'}}).

@item 
bpo-41425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41425}: Make tkinter doc example runnable.

@item 
bpo-41384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41384}: Raise TclError instead of TypeError when an unknown option is
passed to tkinter.OptionMenu.

@item 
bpo-38731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38731}: Fix @ref{e48,,NameError} in command-line interface of
@ref{d7,,py_compile}.

@item 
bpo-41317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41317}: Use add_done_callback() in asyncio.loop.sock_accept() to
unsubscribe reader early on cancellation.

@item 
bpo-41364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41364}: Reduce import overhead of @ref{12d,,uuid}.

@item 
bpo-41341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41341}: Recursive evaluation of @ref{f90,,typing.ForwardRef} in
@code{get_type_hints}.

@item 
bpo-41182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41182}: selector: use DefaultSelector based upon implementation

@item 
bpo-40726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40726}: Handle cases where the @code{end_lineno} is @code{None} on
@ref{104d,,ast.increment_lineno()}.
@end itemize

@node Documentation<13>,Windows<15>,Library<20>,Python 3 9 0 release candidate 1
@anchor{whatsnew/changelog id121}@anchor{104e}
@subsubsection Documentation



@itemize -

@item 
bpo-41045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41045}: Add documentation for debug feature of f-strings.

@item 
bpo-41314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41314}: Changed the release when @code{from __future__ import annotations}
becomes the default from @code{4.0} to @code{3.10} (following a change in PEP
563).
@end itemize

@node Windows<15>,IDLE<11>,Documentation<13>,Python 3 9 0 release candidate 1
@anchor{whatsnew/changelog id122}@anchor{104f}
@subsubsection Windows



@itemize -

@item 
bpo-41492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41492}: Fixes the description that appears in UAC prompts.

@item 
bpo-40948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40948}: Improve post-install message to direct people to the "py"
command.

@item 
bpo-41412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41412}: The installer will now fail to install on Windows 7 and Windows
8. Further, the UCRT dependency is now always downloaded on demand.

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update Windows release to include SQLite 3.32.3.
@end itemize

@node IDLE<11>,,Windows<15>,Python 3 9 0 release candidate 1
@anchor{whatsnew/changelog id123}@anchor{1050}
@subsubsection IDLE



@itemize -

@item 
bpo-41468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41468}: Improve IDLE run crash error message (which users should never
see).

@item 
bpo-41373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41373}: Save files loaded with no line ending, as when blank, or
different line endings, by setting its line ending to the system default.
Fix regression in 3.8.4 and 3.9.0b4.
@end itemize

@node Python 3 9 0 beta 5,Python 3 9 0 beta 4,Python 3 9 0 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-9-0-beta-5}@anchor{1051}
@subsection Python 3.9.0 beta 5


@emph{Release date: 2020-07-20}

@menu
* Security: Security<11>. 
* Core and Builtins: Core and Builtins<20>. 
* Library: Library<21>. 
* Documentation: Documentation<14>. 
* macOS: macOS<13>. 
* IDLE: IDLE<12>. 
* C API: C API<7>. 

@end menu

@node Security<11>,Core and Builtins<20>,,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id124}@anchor{1052}
@subsubsection Security



@itemize -

@item 
bpo-41304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41304}: Fixes @code{python3x._pth} being ignored on Windows, caused by the
fix for bpo-29778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29778} (CVE-2020-15801).

@item 
bpo-41162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41162}: Audit hooks are now cleared later during finalization to avoid
missing events.

@item 
bpo-29778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29778}: Ensure @code{python3.dll} is loaded from correct locations
when Python is embedded (CVE-2020-15523).

@item 
bpo-39603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39603}: Prevent http header injection by rejecting control characters
in http.client.putrequest(...).
@end itemize

@node Core and Builtins<20>,Library<21>,Security<11>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id125}@anchor{1053}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41295}: Resolve a regression in CPython 3.8.4 where defining
"__setattr__" in a multi-inheritance setup and calling up the hierarchy
chain could fail if builtins/extension types were involved in the base
types.

@item 
bpo-41247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41247}: Always cache the running loop holder when running
@code{asyncio.set_running_loop}.

@item 
bpo-41252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41252}: Fix incorrect refcounting in _ssl.c's
@code{_servername_callback()}.

@item 
bpo-41215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41215}: Use non-NULL default values in the PEG parser keyword list to
overcome a bug that was preventing Python from being properly compiled
when using the XLC compiler. Patch by Pablo Galindo.

@item 
bpo-41218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41218}: Python 3.8.3 had a regression where compiling with
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT would aggressively mark list comprehension
with CO_COROUTINE. Now only list comprehension making use of async/await
will tagged as so.

@item 
bpo-41175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41175}: Guard against a NULL pointer dereference within bytearrayobject
triggered by the @code{bytearray() + bytearray()} operation.

@item 
bpo-39960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39960}: The "hackcheck" that prevents sneaking around a type's
__setattr__() by calling the superclass method was rewritten to allow C
implemented heap types.
@end itemize

@node Library<21>,Documentation<14>,Core and Builtins<20>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id126}@anchor{1054}
@subsubsection Library



@itemize -

@item 
bpo-41288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41288}: Unpickling invalid NEWOBJ_EX opcode with the C implementation
raises now UnpicklingError instead of crashing.

@item 
bpo-39017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39017}: Avoid infinite loop when reading specially crafted TAR files
using the tarfile module (CVE-2019-20907).

@item 
bpo-41235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41235}: Fix the error handling in
@ref{b73,,ssl.SSLContext.load_dh_params()}.

@item 
bpo-41207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41207}: In distutils.spawn, restore expectation that DistutilsExecError
is raised when the command is not found.

@item 
bpo-39168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39168}: Remove the @code{__new__} method of @ref{1055,,typing.Generic}.

@item 
bpo-41194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41194}: Fix a crash in the @code{_ast} module: it can no longer be loaded
more than once. It now uses a global state rather than a module state.

@item 
bpo-39384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39384}: Fixed email.contentmanager to allow set_content() to set a null
string.
@end itemize

@node Documentation<14>,macOS<13>,Library<21>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id127}@anchor{1056}
@subsubsection Documentation



@itemize -

@item 
bpo-37703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37703}: Updated Documentation to comprehensively elaborate on the
behaviour of gather.cancel()
@end itemize

@node macOS<13>,IDLE<12>,Documentation<14>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id128}@anchor{1057}
@subsubsection macOS



@itemize -

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update macOS installer to use SQLite 3.32.3.
@end itemize

@node IDLE<12>,C API<7>,macOS<13>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id129}@anchor{1058}
@subsubsection IDLE



@itemize -

@item 
bpo-41300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41300}: Save files with non-ascii chars. Fix regression released in
3.9.0b4 and 3.8.4.

@item 
bpo-37765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37765}: Add keywords to module name completion list.  Rewrite
Completions section of IDLE doc.
@end itemize

@node C API<7>,,IDLE<12>,Python 3 9 0 beta 5
@anchor{whatsnew/changelog id130}@anchor{1059}
@subsubsection C API



@itemize -

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Revert @ref{105a,,PyType_HasFeature()} change: it reads again
directly the @ref{105b,,PyTypeObject.tp_flags} member when the limited C
API is not used, rather than always calling @ref{105c,,PyType_GetFlags()}
which hides implementation details.
@end itemize

@node Python 3 9 0 beta 4,Python 3 9 0 beta 3,Python 3 9 0 beta 5,更新日志
@anchor{whatsnew/changelog python-3-9-0-beta-4}@anchor{105d}
@subsection Python 3.9.0 beta 4


@emph{Release date: 2020-07-02}

@menu
* Security: Security<12>. 
* Core and Builtins: Core and Builtins<21>. 
* Library: Library<22>. 
* Tests: Tests<15>. 
* Build: Build<12>. 
* Windows: Windows<16>. 
* macOS: macOS<14>. 
* IDLE: IDLE<13>. 
* C API: C API<8>. 

@end menu

@node Security<12>,Core and Builtins<21>,,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id131}@anchor{105e}
@subsubsection Security



@itemize -

@item 
bpo-41004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41004}: The __hash__() methods of  ipaddress.IPv4Interface and
ipaddress.IPv6Interface incorrectly generated constant hash values of 32
and 128 respectively. This resulted in always causing hash collisions. The
fix uses hash() to generate hash values for the tuple of (address, mask
length, network address).
@end itemize

@node Core and Builtins<21>,Library<22>,Security<12>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id132}@anchor{105f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-41094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41094}: Fix decoding errors with audit when open files with non-ASCII
names on non-UTF-8 locale.

@item 
bpo-41084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41084}: Prefix the error message with 'f-string: ', when parsing an
f-string expression which throws a @ref{562,,SyntaxError}.

@item 
bpo-41076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41076}: Pre-feed the parser with the location of the f-string
expression, not the f-string itself, which allows us to skip the shifting
of the AST node locations after the parsing is completed.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Deprecate @code{PyNode_Compile()}.

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fixes a reference to deallocated stack space during startup
when constructing sys.path involving a relative symlink when code was
supplied via -c.  (discovered via Coverity)

@item 
bpo-41061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41061}: Fix incorrect expressions and asserts in hashtable code and
tests.

@item 
bpo-41052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41052}: Opt out serialization/deserialization for _random.Random

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Deprecate @ref{200,,PyParser_SimpleParseStringFlags()},
@ref{201,,PyParser_SimpleParseStringFlagsFilename()} and
@ref{202,,PyParser_SimpleParseFileFlags()}.

@item 
bpo-35975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35975}: Stefan Behnel reported that cf_feature_version is used even
when PyCF_ONLY_AST is not set. This is against the intention and against
the documented behavior, so it's been fixed.

@item 
bpo-40985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40985}: Fix a bug that caused the @ref{562,,SyntaxError} text to be empty
when a file ends with a line ending in a line continuation character (i.e.
backslash). The error text should contain the text of the last line.

@item 
bpo-40958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40958}: Fix a possible buffer overflow in the PEG parser when gathering
information for emitting syntax errors. Patch by Pablo Galindo.

@item 
bpo-40957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40957}: Fix refleak in _Py_fopen_obj() when PySys_Audit() fails

@item 
bpo-40947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40947}: The Python @ref{1060,,Path Configuration} now
takes @ref{1061,,PyConfig.platlibdir} in account.

@item 
bpo-40847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40847}: Fix a bug where a line with only a line continuation character
is not considered a blank line at tokenizer level. In such cases, more
than a single @code{NEWLINE} token was emitted. The old parser was working
around the issue, but the new parser threw a @ref{562,,SyntaxError} for valid
input due to this. For example, an empty line following a line
continuation character was interpreted as a @ref{562,,SyntaxError}.

@item 
bpo-40824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40824}: Unexpected errors in calling the @code{__iter__} method are no
longer masked by @code{TypeError} in the @ref{179,,in} operator and functions
@ref{17a,,contains()}, @ref{17b,,indexOf()} and
@ref{17c,,countOf()} of the @ref{c2,,operator} module.

@item 
bpo-19569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19569}: Add the private macros @code{_Py_COMP_DIAG_PUSH},
@code{_Py_COMP_DIAG_IGNORE_DEPR_DECLS}, and @code{_Py_COMP_DIAG_POP}.
@end itemize

@node Library<22>,Tests<15>,Core and Builtins<21>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id133}@anchor{1062}
@subsubsection Library



@itemize -

@item 
bpo-41193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41193}: The @code{write_history()} atexit function of the readline
completer now ignores any @ref{30b,,OSError} to ignore error if the filesystem
is read-only, instead of only ignoring @ref{8b7,,FileNotFoundError} and
@ref{700,,PermissionError}.

@item 
bpo-41161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41161}: The decimal module now requires libmpdec-2.5.0. Users of
--with-system-libmpdec should update their system library.

@item 
bpo-40874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40874}: The decimal module now requires libmpdec-2.5.0.

@item 
bpo-41138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41138}: Fixed the @ref{11b,,trace} module CLI for Python source files with
non-UTF-8 encoding.

@item 
bpo-31938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31938}: Fix default-value signatures of several functions in the
@ref{e5,,select} module - by Anthony Sottile.

@item 
bpo-41068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41068}: Fixed reading files with non-ASCII names from ZIP archive
directly after writing them.

@item 
bpo-41058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41058}: @code{pdb.find_function()} now correctly determines the source
file encoding.

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fix a NULL pointer dereference within the ssl module during a
MemoryError in the keylog callback. (discovered by Coverity)

@item 
bpo-41056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41056}: Fixed an instance where a MemoryError within the zoneinfo
module might not be reported or not reported at its source. (found by
Coverity)

@item 
bpo-41048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41048}: @ref{1063,,mimetypes.read_mime_types()} function reads the rule file
using UTF-8 encoding, not the locale encoding. Patch by Srinivas Reddy
Thatiparthy.

@item 
bpo-41043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41043}: Fixed the use of @ref{6c7,,glob()} in the stdlib: literal part
of the path is now always correctly escaped.

@item 
bpo-40448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40448}: @ref{78,,ensurepip} now disables the use of @code{pip} cache when
installing the bundled versions of @code{pip} and @code{setuptools}.  Patch by
Krzysztof Konopko.

@item 
bpo-40967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40967}: Removed @code{asyncio.Task.current_task()} and
@code{asyncio.Task.all_tasks()}. Patch contributed by Rémi Lapeyre.

@item 
bpo-40955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40955}: Fix a minor memory leak in @ref{f9,,subprocess} module when
extra_groups was specified.

@item 
bpo-40855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40855}: The standard deviation and variance functions in the statistics
module were ignoring their mu and xbar arguments.

@item 
bpo-40924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40924}: Removed support for loaders implementing .files and supplying
TraversableResources.

@item 
bpo-40939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40939}: Use the new PEG parser when generating the stdlib
@ref{a6,,keyword} module.

@item 
bpo-40834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40834}: Fix truncate when sending str object
with_xxsubinterpreters.channel_send.

@item 
bpo-26407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26407}: Unexpected errors in calling the @code{__iter__} method are no
longer masked by @code{TypeError} in @ref{1064,,csv.reader()},
@code{csv.writer.writerow()} and @code{csv.writer.writerows()}.

@item 
bpo-38488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38488}: Update ensurepip to install pip 20.1.1 and setuptools 47.1.0.

@item 
bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543}: Restored the deprecated @code{xml.etree.cElementTree} module.

@item 
bpo-34226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34226}: Fix @ref{283,,cgi.parse_multipart} without content_length. Patch by
Roger Duran
@end itemize

@node Tests<15>,Build<12>,Library<22>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id134}@anchor{1065}
@subsubsection Tests



@itemize -

@item 
bpo-41085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41085}: Fix integer overflow in the @ref{1066,,array.array.index()} method on
64-bit Windows for index larger than @code{2**31}.

@item 
bpo-41069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41069}: @ref{1067,,test.support.TESTFN} and the current directory for tests
when run via @code{test.regrtest} contain now non-ascii characters if
possible.

@item 
bpo-38377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38377}: On Linux, skip tests using multiprocessing if the current user
cannot create a file in @code{/dev/shm/} directory. Add the
@code{skip_if_broken_multiprocessing_synchronize()} function
to the @ref{106,,test.support} module.

@item 
bpo-41009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41009}: Fix use of @code{support.require_@{linux|mac|freebsd@}_version()}
decorators as class decorator.

@item 
bpo-41003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41003}: Fix @code{test_copyreg} when @code{numpy} is installed:
@code{test.pickletester} now saves/restores warnings filters when importing
@code{numpy}, to ignore filters installed by @code{numpy}.

@item 
bpo-40964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40964}: Disable remote @ref{97,,imaplib} tests, host cyrus.andrew.cmu.edu
is blocking incoming connections.

@item 
bpo-40927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40927}: Fix test_binhex when run twice: it now uses
import_fresh_module() to ensure that it raises DeprecationWarning each
time.

@item 
bpo-34401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34401}: Make test_gdb properly run on HP-UX. Patch by Michael Osipov.
@end itemize

@node Build<12>,Windows<16>,Tests<15>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id135}@anchor{1068}
@subsubsection Build



@itemize -

@item 
bpo-40204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40204}: Pin Sphinx version to 2.3.1 in @code{Doc/Makefile}.
@end itemize

@node Windows<16>,macOS<14>,Build<12>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id136}@anchor{1069}
@subsubsection Windows



@itemize -

@item 
bpo-41074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41074}: Fixed support of non-ASCII names in functions
@ref{106a,,msilib.OpenDatabase()} and @ref{106b,,msilib.init_database()} and non-ASCII
SQL in method @ref{106c,,msilib.Database.OpenView()}.

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Updates Windows OpenSSL to 1.1.1g

@item 
bpo-37556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37556}: Extend py.exe help to mention overrides via venv, shebang,
environmental variables & ini files.
@end itemize

@node macOS<14>,IDLE<13>,Windows<16>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id137}@anchor{106d}
@subsubsection macOS



@itemize -

@item 
bpo-39580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39580}: Avoid opening Finder window if running installer from the
command line. Patch contributed by Rick Heil.

@item 
bpo-41100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41100}: Fix configure error when building on macOS 11. Note that the
current Python release was released shortly after the first developer
preview of macOS 11 (Big Sur); there are other known issues with building
and running on the developer preview. Big Sur is expected to be fully
supported in a future bugfix release of Python 3.8.x and with 3.9.0.

@item 
bpo-41005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41005}: fixed an XDG settings issue not allowing macos to open browser
in webbrowser.py
@end itemize

@node IDLE<13>,C API<8>,macOS<14>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id138}@anchor{106e}
@subsubsection IDLE



@itemize -

@item 
bpo-41152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41152}: The encoding of @code{stdin}, @code{stdout} and @code{stderr} in IDLE is
now always UTF-8.

@item 
bpo-41144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=41144}: Make Open Module open a special module such as os.path.
@end itemize

@node C API<8>,,IDLE<13>,Python 3 9 0 beta 4
@anchor{whatsnew/changelog id139}@anchor{106f}
@subsubsection C API



@itemize -

@item 
bpo-36346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36346}: Mark @code{Py_UNICODE_COPY}, @code{Py_UNICODE_FILL},
@code{PyUnicode_WSTR_LENGTH}, @code{PyUnicode_FromUnicode},
@code{PyUnicode_AsUnicode}, @code{_PyUnicode_AsUnicode}, and
@code{PyUnicode_AsUnicodeAndSize} as deprecated in C. Remove
@code{Py_UNICODE_MATCH} which was deprecated and broken since Python 3.3.

@item 
bpo-36020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36020}: On Windows, @code{#include "pyerrors.h"} no longer defines
@code{snprintf} and @code{vsnprintf} macros.

@item 
bpo-40703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40703}: The PyType_FromSpec*() functions no longer overwrite the type's
"__module__" attribute if it is set via "Py_tp_members" or "Py_tp_getset".
@end itemize

@node Python 3 9 0 beta 3,Python 3 9 0 beta 2,Python 3 9 0 beta 4,更新日志
@anchor{whatsnew/changelog python-3-9-0-beta-3}@anchor{1070}
@subsection Python 3.9.0 beta 3


@emph{Release date: 2020-06-09}

@menu
* Library: Library<23>. 
* Build: Build<13>. 

@end menu

@node Library<23>,Build<13>,,Python 3 9 0 beta 3
@anchor{whatsnew/changelog id140}@anchor{1071}
@subsubsection Library



@itemize -

@item 
bpo-40924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40924}: @ref{9e,,importlib.resources}: Reverted @code{TraversableResources}
implementations from the built-in loaders (SourceFileLoader and
ZipImporter) as it was an incompatible change introduced in 3.9.0 beta 2
causing through a chain of events for root TLS certificates to be missing.
@end itemize

@node Build<13>,,Library<23>,Python 3 9 0 beta 3
@anchor{whatsnew/changelog id141}@anchor{1072}
@subsubsection Build



@itemize -

@item 
bpo-40684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40684}: @code{make install} now uses the @code{PLATLIBDIR} variable for the
destination @code{lib-dynload/} directory when @code{./configure
--with-platlibdir} is used.
@end itemize

@node Python 3 9 0 beta 2,Python 3 9 0 beta 1,Python 3 9 0 beta 3,更新日志
@anchor{whatsnew/changelog python-3-9-0-beta-2}@anchor{1073}
@subsection Python 3.9.0 beta 2


@emph{Release date: 2020-06-08}

@menu
* Core and Builtins: Core and Builtins<22>. 
* Library: Library<24>. 
* Tests: Tests<16>. 
* Build: Build<14>. 
* Windows: Windows<17>. 
* macOS: macOS<15>. 
* IDLE: IDLE<14>. 
* C API: C API<9>. 

@end menu

@node Core and Builtins<22>,Library<24>,,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id142}@anchor{1074}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40904}: Fix possible segfault in the new PEG parser when parsing
f-string containing yield statements with no value (@code{f"@{yield@}"}).
Patch by Pablo Galindo

@item 
bpo-40903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40903}: Fixed a possible segfault in the new PEG parser when producing
error messages for invalid assignments of the form @code{p=p=}. Patch by
Pablo Galindo

@item 
bpo-40880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40880}: Fix invalid memory read in the new parser when checking
newlines in string literals. Patch by Pablo Galindo.

@item 
bpo-40883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40883}: Fix memory leak in when parsing f-strings in the new parser.
Patch by Pablo Galindo

@item 
bpo-40870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40870}: Raise @ref{16d,,ValueError} when validating custom AST's where the
constants @code{True}, @code{False} and @code{None} are used within a
@ref{1075,,ast.Name} node.

@item 
bpo-40854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40854}: Allow overriding @ref{1ea,,sys.platlibdir} via a new
@geindex PYTHONPLATLIBDIR
@geindex 环境变量; PYTHONPLATLIBDIR
@ref{1076,,PYTHONPLATLIBDIR} environment variable.

@item 
bpo-40826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40826}: Fix GIL usage in @code{PyOS_Readline()}: lock the GIL to set
an exception and pass the Python thread state when checking if there is a
pending signal.

@item 
bpo-40780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40780}: Fix a corner case where g-style string formatting of a float
failed to remove trailing zeros.

@item 
bpo-38964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38964}: When there's a @ref{562,,SyntaxError} in the expression part of an
fstring, the filename attribute of the @ref{562,,SyntaxError} gets correctly
set to the name of the file the fstring resides in.

@item 
bpo-40750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40750}: Support the "-d" debug flag in the new PEG parser. Patch by
Pablo Galindo

@item 
bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217}: Instances of types created with
@ref{1077,,PyType_FromSpecWithBases()} will no longer automatically visit
their class object when traversing references in the garbage collector.
The user is expected to manually visit the object's class. Patch by Pablo
Galindo.

@item 
bpo-40696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40696}: Fix a hang that can arise after @ref{1042,,generator.throw()} due to
a cycle in the exception context chain.
@end itemize

@node Library<24>,Tests<16>,Core and Builtins<22>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id143}@anchor{1078}
@subsubsection Library



@itemize -

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Refresh importlib.metadata from importlib_metadata 1.6.1.

@item 
bpo-40807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40807}: Stop codeop._maybe_compile, used by code.InteractiveInterpreter
(and IDLE). from from emitting each warning three times.

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Built-in loaders (SourceFileLoader and ZipImporter) now supply
@code{TraversableResources} implementations for @code{ResourceReader}, and the
fallback function has been removed.

@item 
bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005}: The topological sort functionality that was introduced
initially in the @ref{83,,functools} module has been moved to a new
@ref{89,,graphlib} module to better accommodate the new tools and keep the
original scope of the @ref{83,,functools} module. Patch by Pablo Galindo

@item 
bpo-40777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40777}: Initialize PyDateTime_IsoCalendarDateType.tp_base at run-time
to avoid errors on some compilers.

@item 
bpo-40767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40767}: @ref{132,,webbrowser} now properly finds the default browser in
pure Wayland systems by checking the WAYLAND_DISPLAY environment variable.
Patch contributed by Jérémy Attali.

@item 
bpo-40791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40791}: @code{hashlib.compare_digest()} uses OpenSSL's
@code{CRYPTO_memcmp()} function when OpenSSL is available.

@item 
bpo-40795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40795}: @ref{2a,,ctypes} module: If ctypes fails to convert the result of
a callback or if a ctypes callback function raises an exception,
sys.unraisablehook is now called with an exception set. Previously, the
error was logged into stderr by @ref{1079,,PyErr_Print()}.

@item 
bpo-30008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30008}: Fix @ref{f3,,ssl} code to be compatible with OpenSSL 1.1.x builds
that use @code{no-deprecated} and @code{--api=1.1.0}.

@item 
bpo-30064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30064}: Fix asyncio @code{loop.sock_*} race condition issue

@item 
bpo-40759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40759}: Deprecate the @ref{fb,,symbol} module.

@item 
bpo-40737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40737}: Fix possible reference leak for @ref{f2,,sqlite3} initialization.

@item 
bpo-40698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40698}: @ref{38,,distutils} upload creates SHA2-256 and Blake2b-256
digests. MD5 digests is skipped if platform blocks MD5.

@item 
bpo-40695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40695}: @ref{8c,,hashlib} no longer falls back to builtin hash
implementations when OpenSSL provides a hash digest and the algorithm is
blocked by security policy.

@item 
bpo-9216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9216}: func:@ref{107a,,hashlib.new} passed @code{usedforsecurity} to OpenSSL EVP
constructor @code{_hashlib.new()}. test_hashlib and test_smtplib handle
strict security policy better.

@item 
bpo-40614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40614}: @ref{2dd,,ast.parse()} will not parse self documenting expressions
in f-strings when passed @code{feature_version} is less than @code{(3, 8)}.

@item 
bpo-40671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40671}: Prepare @code{_hashlib} for 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} and use
@ref{254,,PyModule_AddType()}.

@item 
bpo-32309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32309}: Added a new @ref{18a,,coroutine} @ref{18f,,asyncio.to_thread()}. It is
mainly used for running IO-bound functions in a separate thread to avoid
blocking the event loop, and essentially works as a high-level version of
@ref{190,,run_in_executor()} that can directly take keyword
arguments.

@item 
bpo-40630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40630}: Added @ref{1ed,,tracemalloc.reset_peak()} to set the peak size of
traced memory blocks to the current size, to measure the peak of specific
pieces of code.

@item 
bpo-13097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13097}: @code{ctypes} now raises an @code{ArgumentError} when a callback is
invoked with more than 1024 arguments.

@item 
bpo-23082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23082}: Updated the error message and docs of PurePath.relative_to() to
better reflect the function behaviour.

@item 
bpo-39244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39244}: Fixed @code{multiprocessing.context.get_all_start_methods} to
properly return the default method first on macOS.

@item 
bpo-39040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39040}: Fix parsing of invalid mime headers parameters by collapsing
whitespace between encoded words in a bare-quote-string.

@item 
bpo-35714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35714}: @ref{d84,,struct.error} is now raised if there is a null character
in a @ref{f8,,struct} format string.

@item 
bpo-36290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36290}: AST nodes are now raising @ref{1ff,,TypeError} on conflicting
keyword arguments. Patch contributed by Rémi Lapeyre.
@end itemize

@node Tests<16>,Build<14>,Library<24>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id144}@anchor{107b}
@subsubsection Tests



@itemize -

@item 
bpo-17258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17258}: Skip some @ref{b7,,multiprocessing} tests when MD5 hash digest is
blocked.
@end itemize

@node Build<14>,Windows<17>,Tests<16>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id145}@anchor{107c}
@subsubsection Build



@itemize -

@item 
bpo-40514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40514}: Remove @code{--with-experimental-isolated-subinterpreters}
configure option in Python 3.9: the experiment continues in the master
branch, but it's no longer needed in 3.9.

@item 
bpo-40683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40683}: Fixed an issue where the @ref{14e,,zoneinfo} module and its tests
were not included when Python is installed with @code{make}.
@end itemize

@node Windows<17>,macOS<15>,Build<14>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id146}@anchor{107d}
@subsubsection Windows



@itemize -

@item 
bpo-39631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39631}: Changes the registered MIME type for @code{.py} files on Windows
to @code{text/x-python} instead of @code{text/plain}.

@item 
bpo-40677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40677}: Manually define IO_REPARSE_TAG_APPEXECLINK in case some old
Windows SDK doesn't have it.
@end itemize

@node macOS<15>,IDLE<14>,Windows<17>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id147}@anchor{107e}
@subsubsection macOS



@itemize -

@item 
bpo-40741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40741}: Update macOS installer to use SQLite 3.32.2.
@end itemize

@node IDLE<14>,C API<9>,macOS<15>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id148}@anchor{107f}
@subsubsection IDLE



@itemize -

@item 
bpo-39885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39885}: Make context menu Cut and Copy work again when right-clicking
within a selection.

@item 
bpo-40723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40723}: Make test_idle pass when run after import.
@end itemize

@node C API<9>,,IDLE<14>,Python 3 9 0 beta 2
@anchor{whatsnew/changelog id149}@anchor{1080}
@subsubsection C API



@itemize -

@item 
bpo-40910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40910}: Export explicitly the @ref{1081,,Py_GetArgcArgv()} function to the
C API and document the function. Previously, it was exported implicitly
which no longer works since Python is built with @code{-fvisibility=hidden}.

@item 
bpo-40724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40724}: Allow defining buffer slots in type specs.

@item 
bpo-40826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40826}: @code{PyOS_InterruptOccurred()} now fails with a fatal error
if it is called with the GIL released.
@end itemize

@node Python 3 9 0 beta 1,Python 3 9 0 alpha 6,Python 3 9 0 beta 2,更新日志
@anchor{whatsnew/changelog python-3-9-0-beta-1}@anchor{1082}
@subsection Python 3.9.0 beta 1


@emph{Release date: 2020-05-19}

@menu
* Security: Security<13>. 
* Core and Builtins: Core and Builtins<23>. 
* Library: Library<25>. 
* Documentation: Documentation<15>. 
* Tests: Tests<17>. 
* Build: Build<15>. 
* Windows: Windows<18>. 
* macOS: macOS<16>. 
* Tools/Demos: Tools/Demos<5>. 
* C API: C API<10>. 

@end menu

@node Security<13>,Core and Builtins<23>,,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id150}@anchor{1083}
@subsubsection Security



@itemize -

@item 
bpo-40501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40501}: @ref{12d,,uuid} no longer uses @ref{2a,,ctypes} to load
@code{libuuid} or @code{rpcrt4.dll} at runtime.
@end itemize

@node Core and Builtins<23>,Library<25>,Security<13>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id151}@anchor{1084}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40663}: Correctly generate annotations where parentheses are omitted
but required (e.g: @code{Type[(str, int, *other))]}.

@item 
bpo-40596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40596}: Fixed @ref{1085,,str.isidentifier()} for non-canonicalized strings
containing non-BMP characters on Windows.

@item 
bpo-40593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40593}: Improved syntax errors for invalid characters in source code.

@item 
bpo-40585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40585}: Fixed a bug when using @ref{1086,,codeop.compile_command()} that was
causing exceptions to be swallowed with the new parser. Patch by Pablo
Galindo

@item 
bpo-40566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40566}: Apply 
@geindex Python 提高建议; PEP 573
PEP 573@footnote{https://www.python.org/dev/peps/pep-0573} to @ref{3,,abc}.

@item 
bpo-40502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40502}: Initialize @code{n->n_col_offset}. (Patch by Joannah Nanjekye)

@item 
bpo-40527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40527}: Fix command line argument parsing: no longer write errors
multiple times into stderr.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{7a,,errno} to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-40523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40523}: Add pass-throughs for @ref{aac,,hash()} and @ref{2cd,,reversed()} to
@ref{381,,weakref.proxy} objects. Patch by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{ff,,syslog} to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}: Reporting a specialised error message for invalid string
prefixes, which was introduced in bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}, is being reverted due to
backwards compatibility concerns for strings that immediately follow a
reserved keyword without whitespace between them. Constructs like
@code{bg="#d00" if clear else"#fca"} were failing to parse, which is not an
acceptable breakage on such short notice.

@item 
bpo-40417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40417}: Fix imp module deprecation warning when PyImport_ReloadModule
is called. Patch by Robert Rouhani.

@item 
bpo-40408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40408}: Fixed support of nested type variables in GenericAlias (e.g.
@code{list[list[T]]}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _stat module to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-29587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29587}: Enable implicit exception chaining when calling
@ref{1042,,generator.throw()}.

@item 
bpo-40328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40328}: Add tools for generating mappings headers for CJKCodecs.

@item 
bpo-40228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40228}: Setting frame.f_lineno is now robust w.r.t. changes in the
source-to-bytecode compiler

@item 
bpo-38880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38880}: Added the ability to list interpreters associated with channel
ends in the internal subinterpreters module.

@item 
bpo-37986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37986}: Improve performance of @ref{1f5,,PyLong_FromDouble()} for values
that fit into @code{long}.
@end itemize

@node Library<25>,Documentation<15>,Core and Builtins<23>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id152}@anchor{1087}
@subsubsection Library



@itemize -

@item 
bpo-40662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40662}: Fixed @ref{2dc,,ast.get_source_segment()} for ast nodes that have
incomplete location information. Patch by Irit Katriel.

@item 
bpo-40665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40665}: Convert @ref{11,,bisect} to use Argument Clinic.

@item 
bpo-40536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40536}: Added the @ref{1088,,available_timezones()} function to the
@ref{14e,,zoneinfo} module. Patch by Paul Ganssle.

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: The @code{hmac.HMAC} exposes internal implementation details.
The attributes @code{digest_cons}, @code{inner}, and @code{outer} are deprecated
and will be removed in the future.

@item 
bpo-40645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40645}: The internal module @code{_hashlib} wraps and exposes OpenSSL's
HMAC API. The new code will be used in Python 3.10 after the internal
implementation details of the pure Python HMAC module are no longer part
of the public API.

@item 
bpo-40637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40637}: Builtin hash modules can now be disabled or selectively enabled
with @code{configure --with-builtin-hashlib-hashes=sha3,blake1} or
@code{--without-builtin-hashlib-hashes}.

@item 
bpo-37630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37630}: The @ref{8c,,hashlib} module can now use SHA3 hashes and SHAKE XOF
from OpenSSL when available.

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: The @ref{8c,,hashlib} now compiles with OpenSSL 3.0.0-alpha2.

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: Revert changes to @ref{30e,,inspect.getdoc()}.

@item 
bpo-40607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40607}: When cancelling a task due to timeout, @ref{191,,asyncio.wait_for()}
will now propagate the exception if an error happens during cancellation.
Patch by Roman Skurikhin.

@item 
bpo-40612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40612}: Fix edge cases in SyntaxError formatting. If the offset is <=
0, no caret is printed. If the offset is > line length, the caret is
printed pointing just after the last character.

@item 
bpo-40597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40597}: If text content lines are longer than policy.max_line_length,
always use a content-encoding to make sure they are wrapped.

@item 
bpo-40571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40571}: Added functools.cache() as a simpler, more discoverable way to
access the unbounded cache variant of lru_cache(maxsize=None).

@item 
bpo-40503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40503}: 
@geindex Python 提高建议; PEP 615
PEP 615@footnote{https://www.python.org/dev/peps/pep-0615}, the @ref{14e,,zoneinfo} module. Adds support for the
IANA time zone database.

@item 
bpo-40397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40397}: Removed attributes @code{__args__} and @code{__parameters__} from
special generic aliases like @code{typing.List} (not subscripted).

@item 
bpo-40549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40549}: Convert posixmodule.c ("posix" or "nt" module) to the
multiphase initialization (PEP 489).

@item 
bpo-31033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31033}: Add a @code{msg} argument to @code{Future.cancel()} and
@code{Task.cancel()}.

@item 
bpo-40541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40541}: Added an optional @emph{counts} parameter to random.sample().

@item 
bpo-40515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40515}: The @ref{f3,,ssl} and @ref{8c,,hashlib} modules now actively check
that OpenSSL is build with thread support. Python 3.7.0 made thread
support mandatory and no longer works safely with a no-thread builds.

@item 
bpo-31033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31033}: When a @ref{2e7,,asyncio.Task} is cancelled, the exception
traceback now chains all the way back to where the task was first
interrupted.

@item 
bpo-40504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40504}: @ref{2ff,,functools.lru_cache()} objects can now be the targets of
weakrefs.

@item 
bpo-40559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40559}: Fix possible memory leak in the C implementation of
@ref{2e7,,asyncio.Task}.

@item 
bpo-40480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40480}: @code{fnmatch.fnmatch()} could take exponential time in the
presence of multiple @code{*} pattern characters.  This was repaired by
generating more elaborate regular expressions to avoid futile
backtracking.

@item 
bpo-40495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40495}: @ref{20,,compileall} is now able to use hardlinks to prevent
duplicates in a case when @code{.pyc} files for different optimization levels
have the same content.

@item 
bpo-40457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40457}: The ssl module now support OpenSSL builds without TLS 1.0 and
1.1 methods.

@item 
bpo-40355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40355}: Improve error reporting in @ref{5a8,,ast.literal_eval()} in the
presence of malformed @ref{1089,,ast.Dict} nodes instead of silently ignoring
any non-conforming elements. Patch by Curtis Bucher.

@item 
bpo-40465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40465}: Deprecated the optional @emph{random} argument to
@emph{random.shuffle()}.

@item 
bpo-40459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40459}: @ref{108a,,platform.win32_ver()} now produces correct @emph{ptype} strings
instead of empty strings.

@item 
bpo-39435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39435}: The first argument of @ref{6c4,,pickle.loads()} is now
positional-only.

@item 
bpo-39305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39305}: Update @ref{c0,,nntplib} to merge @ref{1c7,,nntplib.NNTP} and
@code{nntplib._NNTPBase}. Patch by Dong-hee Na.

@item 
bpo-32494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32494}: Update @ref{33,,dbm.gnu} to use gdbm_count if possible when
calling @ref{292,,len()}. Patch by Dong-hee Na.

@item 
bpo-40453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40453}: Add @code{isolated=True} keyword-only parameter to
@code{_xxsubinterpreters.create()}. An isolated subinterpreter cannot spawn
threads, spawn a child process or call @code{os.fork()}.

@item 
bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286}: Remove @code{_random.Random.randbytes()}: the C implementation of
@code{randbytes()}. Implement the method in Python to ease subclassing:
@code{randbytes()} now directly reuses @code{getrandbits()}.

@item 
bpo-40394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40394}: Added default arguments to
@ref{108b,,difflib.SequenceMatcher.find_longest_match()}.

@item 
bpo-39995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39995}: Fix a race condition in concurrent.futures._ThreadWakeup:
access to _ThreadWakeup is now protected with the shutdown lock.

@item 
bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966}: @code{Process.shutdown(wait=True)} of @ref{21,,concurrent.futures}
now closes explicitly the result queue.

@item 
bpo-30966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30966}: Add a new @ref{1c5,,close()} method to
the @ref{1c4,,SimpleQueue} class to explicitly close the
queue.

@item 
bpo-39966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39966}: Revert bpo-25597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25597}. @ref{87e,,unittest.mock.MagicMock} with wraps'
set uses default return values for magic methods.

@item 
bpo-39791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39791}: Added @code{files()} function to importlib.resources with support
for subdirectories in package data, matching backport in
importlib_resources 1.5.

@item 
bpo-40375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40375}: @ref{1b4,,imaplib.IMAP4.unselect()} is added. Patch by Dong-hee Na.

@item 
bpo-40389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40389}: @code{repr()} now returns @code{typing.Optional[T]} when called for
@code{typing.Union} of two types, one of which is @code{NoneType}.

@item 
bpo-40291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40291}: Add support for CAN_J1939 sockets (available on Linux 5.4+)

@item 
bpo-40273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40273}: @ref{b97,,types.MappingProxyType} is now reversible.

@item 
bpo-39075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39075}: The repr for @ref{1d9,,types.SimpleNamespace} is now insertion
ordered rather than alphabetical.

@item 
bpo-40192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40192}: On AIX, @ref{1e8,,thread_time()} is now implemented with
@code{thread_cputime()} which has nanosecond resolution, rather than
@code{clock_gettime(CLOCK_THREAD_CPUTIME_ID)} which has a resolution of 10
ms. Patch by Batuhan Taskaya.

@item 
bpo-40025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40025}: Raise TypeError when _generate_next_value_ is defined after
members. Patch by Ethan Onstott.

@item 
bpo-39058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39058}: In the argparse module, the repr for Namespace() and other
argument holders now displayed in the order attributes were added.
Formerly, it displayed in alphabetical order even though argument order is
preserved the user visible parts of the module.

@item 
bpo-24416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24416}: The @code{isocalendar()} methods of @ref{19d,,datetime.date} and
@ref{19f,,datetime.datetime} now return a @ref{b84,,named tuple} instead of a
@ref{1a2,,tuple}.
@end itemize

@node Documentation<15>,Tests<17>,Library<25>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id153}@anchor{108c}
@subsubsection Documentation



@itemize -

@item 
bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}: Add version of removal for explicit passing of coros to
@ref{208,,asyncio.wait()}'s documentation

@item 
bpo-40561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40561}: Provide docstrings for webbrowser open functions.

@item 
bpo-40499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40499}: Mention that @ref{208,,asyncio.wait()} requires a non-empty set of
awaitables.

@item 
bpo-39705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39705}: Tutorial example for sorted() in the Loop Techniques section is
given a better explanation. Also a new example is included to explain
sorted()'s basic behavior.

@item 
bpo-39435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39435}: Fix an incorrect signature for @ref{6c4,,pickle.loads()} in the docs
@end itemize

@node Tests<17>,Build<15>,Documentation<15>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id154}@anchor{108d}
@subsubsection Tests



@itemize -

@item 
bpo-40055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40055}: distutils.tests now saves/restores warnings filters to leave
them unchanged. Importing tests imports docutils which imports
pkg_resources which adds a warnings filter.

@item 
bpo-40436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40436}: test_gdb and test.pythoninfo now check gdb command exit code.
@end itemize

@node Build<15>,Windows<18>,Tests<17>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id155}@anchor{108e}
@subsubsection Build



@itemize -

@item 
bpo-40653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40653}: Move _dirnameW out of HAVE_SYMLINK to fix a potential compiling
issue.

@item 
bpo-40514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40514}: Add @code{--with-experimental-isolated-subinterpreters} build
option to @code{configure}: better isolate subinterpreters, experimental
build mode.
@end itemize

@node Windows<18>,macOS<16>,Build<15>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id156}@anchor{108f}
@subsubsection Windows



@itemize -

@item 
bpo-40650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40650}: Include winsock2.h in pytime.c for timeval.

@item 
bpo-40458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40458}: Increase reserved stack space to prevent overflow crash on
Windows.

@item 
bpo-39148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39148}: Add IPv6 support to @ref{9,,asyncio} datagram endpoints in
ProactorEventLoop. Change the raised exception for unknown address
families to ValueError as it's not coming from Windows API.
@end itemize

@node macOS<16>,Tools/Demos<5>,Windows<18>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id157}@anchor{1090}
@subsubsection macOS



@itemize -

@item 
bpo-34956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34956}: When building Python on macOS from source, @code{_tkinter} now
links with non-system Tcl and Tk frameworks if they are installed in
@code{/Library/Frameworks}, as had been the case on older releases of macOS.
If a macOS SDK is explicitly configured, by using
@code{--enable-universalsdk=} or @code{-isysroot}, only the SDK itself is
searched. The default behavior can still be overridden with
@code{--with-tcltk-includes} and @code{--with-tcltk-libs}.

@item 
bpo-35569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35569}: Expose RFC 3542 IPv6 socket options.
@end itemize

@node Tools/Demos<5>,C API<10>,macOS<16>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id158}@anchor{1091}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-40479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40479}: Update multissltest helper to test with latest OpenSSL 1.0.2,
1.1.0, 1.1.1, and 3.0.0-alpha.

@item 
bpo-40431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40431}: Fix a syntax typo in @code{turtledemo} that now raises a
@code{SyntaxError}.

@item 
bpo-40163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40163}: Fix multissltest tool. OpenSSL has changed download URL for old
releases. The multissltest tool now tries to download from current and old
download URLs.
@end itemize

@node C API<10>,,Tools/Demos<5>,Python 3 9 0 beta 1
@anchor{whatsnew/changelog id159}@anchor{1092}
@subsubsection C API



@itemize -

@item 
bpo-39465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39465}: Remove the @code{_PyUnicode_ClearStaticStrings()} function from
the C API.

@item 
bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787}: Add PyCFunction_CheckExact() macro for exact type checks now
that we allow subtypes of PyCFunction, as well as PyCMethod_CheckExact()
and PyCMethod_Check() for the new PyCMethod subtype.

@item 
bpo-40545@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40545}: Declare @code{_PyErr_GetTopmostException()} with @code{PyAPI_FUNC()}
to properly export the function in the C API. The function remains private
(@code{_Py}) prefix.

@item 
bpo-40412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40412}: Nullify inittab_copy during finalization, preventing future
interpreter initializations in an embedded situation from crashing. Patch
by Gregory Szorc.

@item 
bpo-40429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40429}: The @ref{24f,,PyThreadState_GetFrame()} function now returns a
strong reference to the frame.

@item 
bpo-40428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40428}: Remove the following functions from the C API. Call
@code{PyGC_Collect()} explicitly to free all free lists.


@itemize *

@item 
@code{PyAsyncGen_ClearFreeLists()}

@item 
@code{PyContext_ClearFreeList()}

@item 
@code{PyDict_ClearFreeList()}

@item 
@code{PyFloat_ClearFreeList()}

@item 
@code{PyFrame_ClearFreeList()}

@item 
@code{PyList_ClearFreeList()}

@item 
@code{PySet_ClearFreeList()}

@item 
@code{PyTuple_ClearFreeList()}
@end itemize

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: New @ref{24b,,PyFrame_GetBack()} function: get the frame next
outer frame.

@item 
bpo-40421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40421}: New @ref{24a,,PyFrame_GetCode()} function: return a borrowed
reference to the frame code.

@item 
bpo-40217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40217}: Ensure that instances of types created with
@ref{1077,,PyType_FromSpecWithBases()} will visit its class object when
traversing references in the garbage collector (implemented as an
extension of the provided @ref{23c,,tp_traverse}). Patch by
Pablo Galindo.

@item 
bpo-38787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38787}: Module C state is now accessible from C-defined heap type
methods (
@geindex Python 提高建议; PEP 573
PEP 573@footnote{https://www.python.org/dev/peps/pep-0573}). Patch by Marcel Plch and Petr Viktorin.
@end itemize

@node Python 3 9 0 alpha 6,Python 3 9 0 alpha 5,Python 3 9 0 beta 1,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-6}@anchor{1093}
@subsection Python 3.9.0 alpha 6


@emph{Release date: 2020-04-27}

@menu
* Security: Security<14>. 
* Core and Builtins: Core and Builtins<24>. 
* Library: Library<26>. 
* Documentation: Documentation<16>. 
* Tests: Tests<18>. 
* Build: Build<16>. 
* Windows: Windows<19>. 
* macOS: macOS<17>. 
* IDLE: IDLE<15>. 
* Tools/Demos: Tools/Demos<6>. 
* C API: C API<11>. 

@end menu

@node Security<14>,Core and Builtins<24>,,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id160}@anchor{1094}
@subsubsection Security



@itemize -

@item 
bpo-40121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40121}: Fixes audit events raised on creating a new socket.

@item 
bpo-39073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39073}: Disallow CR or LF in email.headerregistry.Address arguments to
guard against header injection attacks.

@item 
bpo-39503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39503}: CVE-2020-8492: The
@ref{fed,,AbstractBasicAuthHandler} class of the
@ref{129,,urllib.request} module uses an inefficient regular expression which
can be exploited by an attacker to cause a denial of service. Fix the
regex to prevent the catastrophic backtracking. Vulnerability reported by
Ben Caller and Matt Schwager.
@end itemize

@node Core and Builtins<24>,Library<26>,Security<14>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id161}@anchor{1095}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40313}: Improve the performance of bytes.hex().

@item 
bpo-40334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40334}: Switch to a new parser, based on PEG.  For more details see PEP
617. To temporarily switch back to the old parser, use @code{-X oldparser} or
@code{PYTHONOLDPARSER=1}.  In Python 3.10 we will remove the old parser
completely, including the @code{parser} module (already deprecated) and
anything that depends on it.

@item 
bpo-40267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40267}: Fix the tokenizer to display the correct error message, when
there is a SyntaxError on the last input character and no newline follows.
It used to be @code{unexpected EOF while parsing}, while it should be @code{invalid
syntax}.

@item 
bpo-39522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39522}: Correctly unparse explicit @code{u} prefix for strings when
postponed evaluation for annotations activated. Patch by Batuhan Taskaya.

@item 
bpo-40246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40246}: Report a specialized error message, @code{invalid string prefix},
when the tokenizer encounters a string with an invalid prefix.

@item 
bpo-40082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40082}: Fix the signal handler: it now always uses the main
interpreter, rather than trying to get the current Python thread state.

@item 
bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388}: str.encode() and str.decode() no longer check the encoding and
errors in development mode or in debug mode during Python finalization.
The codecs machinery can no longer work on very late calls to str.encode()
and str.decode().

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Fix possible refleaks in @code{_json}, memo of PyScannerObject
should be traversed.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{dict()} by using the 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}
@code{vectorcall} calling convention.

@item 
bpo-40141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40141}: Add column and line information to @code{ast.keyword} nodes. Patch
by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{e0,,resource} to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port @ref{b1,,math} to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _uuid module to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-40077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40077}: Convert json module to use @ref{23b,,PyType_FromSpec()}.

@item 
bpo-40067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40067}: Improve the error message for multiple star expressions in an
assignment. Patch by Furkan Onder

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _functools module to multiphase initialization (PEP
489). Patch by Paulo Henrique Silva.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port operator module to multiphase initialization (PEP 489).
Patch by Paulo Henrique Silva.

@item 
bpo-20526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20526}: Fix @ref{1096,,PyThreadState_Clear()}. @code{PyThreadState.frame} is
a borrowed reference, not a strong reference: @code{PyThreadState_Clear()}
must not call @code{Py_CLEAR(tstate->frame)}.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port time module to multiphase initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).
Patch by Paulo Henrique Silva.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _weakref extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-40020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40020}: Fix a leak and subsequent crash in parsetok.c caused by realloc
misuse on a rare codepath.

@item 
bpo-39939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39939}: Added str.removeprefix and str.removesuffix methods and
corresponding bytes, bytearray, and collections.UserString methods to
remove affixes from a string if present. See 
@geindex Python 提高建议; PEP 616
PEP 616@footnote{https://www.python.org/dev/peps/pep-0616} for a full
description. Patch by Dennis Sweeney.

@item 
bpo-39481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39481}: Implement PEP 585. This supports list[int], tuple[str, ...]
etc.

@item 
bpo-32894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32894}: Support unparsing of infinity numbers in postponed annotations.
Patch by Batuhan Taşkaya.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{list()} by using the 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}
@code{vectorcall} calling convention. Patch by Mark Shannon.
@end itemize

@node Library<26>,Documentation<16>,Core and Builtins<24>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id162}@anchor{1097}
@subsubsection Library



@itemize -

@item 
bpo-40398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40398}: @ref{27e,,typing.get_args()} now always returns an empty tuple for
special generic aliases.

@item 
bpo-40396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40396}: Functions @ref{375,,typing.get_origin()}, @ref{27e,,typing.get_args()}
and @ref{1f0,,typing.get_type_hints()} support now generic aliases like
@code{list[int]}.

@item 
bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061}: Optimize the @ref{f9,,subprocess} module on FreeBSD using
@code{closefrom()}. A single @code{close(fd)} syscall is cheap, but when
@code{sysconf(_SC_OPEN_MAX)} is high, the loop calling @code{close(fd)} on each
file descriptor can take several milliseconds.

The workaround on FreeBSD to improve performance was to load and mount the
fdescfs kernel module, but this is not enabled by default.

Initial patch by Ed Maste (emaste), Conrad Meyer (cem), Kyle Evans
(kevans) and Kubilay Kocak (koobs):
@indicateurl{https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274}

@item 
bpo-38061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38061}: On FreeBSD, @code{os.closerange(fd_low, fd_high)} now calls
@code{closefrom(fd_low)} if @emph{fd_high} is greater than or equal to
@code{sysconf(_SC_OPEN_MAX)}.

Initial patch by Ed Maste (emaste), Conrad Meyer (cem), Kyle Evans
(kevans) and Kubilay Kocak (koobs):
@indicateurl{https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274}

@item 
bpo-40360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40360}: The @ref{a7,,lib2to3} module is pending deprecation due to
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617}.

@item 
bpo-40138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40138}: Fix the Windows implementation of @ref{76a,,os.waitpid()} for exit
code larger than @code{INT_MAX >> 8}. The exit status is now interpreted as
an unsigned number.

@item 
bpo-39942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39942}: Set "__main__" as the default module name when "__name__" is
missing in @ref{1098,,typing.TypeVar}. Patch by Weipeng Hong.

@item 
bpo-40275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40275}: The @ref{aa,,logging} package is now imported lazily in
@ref{124,,unittest} only when the @ref{9f4,,assertLogs()}
assertion is used.

@item 
bpo-40275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40275}: The @ref{9,,asyncio} package is now imported lazily in
@ref{124,,unittest} only when the @ref{37e,,IsolatedAsyncioTestCase}
class is used.

@item 
bpo-40330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40330}: In @code{ShareableList.__setitem__()}, check the size of a new
string item after encoding it to utf-8, not before.

@item 
bpo-40148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40148}: Added @code{pathlib.Path.with_stem()} to create a new Path
with the stem replaced.

@item 
bpo-40325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40325}: Deprecated support for set objects in random.sample().

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: Improved help for the @ref{122,,typing} module. Docstrings are now
shown for all special forms and special generic aliases (like @code{Union}
and @code{List}). Using @code{help()} with generic alias like @code{List[int]} will
show the help for the correspondent concrete type (@code{list} in this case).

@item 
bpo-40257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40257}: func:@ref{30e,,inspect.getdoc} no longer returns docstring inherited
from the type of the object or from parent class if it is a class if it is
not defined in the object itself. In @ref{d9,,pydoc} the documentation string
is now shown not only for class, function, method etc, but for any object
that has its own @code{__doc__} attribute.

@item 
bpo-40287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40287}: Fixed @code{SpooledTemporaryFile.seek()} to return the position.

@item 
bpo-40290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40290}: Added zscore() to statistics.NormalDist().

@item 
bpo-40282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40282}: Allow @code{random.getrandbits(0)} to succeed and to return 0.

@item 
bpo-40286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40286}: Add @ref{1099,,random.randbytes()} function and
@code{random.Random.randbytes()} method to generate random bytes.

@item 
bpo-40277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40277}: @ref{1a1,,collections.namedtuple()} now provides a human-readable
repr for its field accessors.

@item 
bpo-40270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40270}: The included copy of sqlite3 on Windows is now compiled with
the json extension. This allows the use of functions such as
@code{json_object}.

@item 
bpo-29255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29255}: Wait in @code{KqueueSelector.select} when no fds are registered

@item 
bpo-40260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40260}: Ensure @ref{b4,,modulefinder} uses @ref{f59,,io.open_code()} and
respects coding comments.

@item 
bpo-40234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40234}: Allow again to spawn daemon threads in subinterpreters (revert
change which denied them).

@item 
bpo-39207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39207}: Workers in @ref{196,,ProcessPoolExecutor} are
now spawned on demand, only when there are no available idle workers to
reuse. This optimizes startup overhead and reduces the amount of lost CPU
time to idle workers. Patch by Kyle Stanley.

@item 
bpo-40091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40091}: Fix a hang at fork in the logging module: the new private
_at_fork_reinit() method is now used to reinitialize locks at fork in the
child process.

@item 
bpo-40149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40149}: Implement traverse and clear slots in _abc._abc_data type.

@item 
bpo-40208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40208}: Remove deprecated @code{symtable.SymbolTable.has_exec()}.

@item 
bpo-40196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40196}: Fix a bug in the @ref{fc,,symtable} module that was causing
incorrectly report global variables as local. Patch by Pablo Galindo.

@item 
bpo-40190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40190}: Add support for @code{_SC_AIX_REALMEM} to @code{posix.sysconf()}.

@item 
bpo-40182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40182}: Removed the @code{_field_types} attribute of the
@ref{228,,typing.NamedTuple} class.

@item 
bpo-36517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36517}: Multiple inheritance with @ref{228,,typing.NamedTuple} now raises
an error instead of silently ignoring other types.

@item 
bpo-40126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40126}: Fixed reverting multiple patches in unittest.mock. Patcher's
@code{__exit__()} is now never called if its @code{__enter__()} is failed.
Returning true from @code{__exit__()} silences now the exception.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: CGIHTTPRequestHandler of http.server now logs the CGI script
exit code, rather than the CGI script exit status of os.waitpid(). For
example, if the script is killed by signal 11, it now logs: "CGI script
exit code -11."

@item 
bpo-40108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40108}: Improve the error message when triying to import a module using
@ref{e2,,runpy} and incorrently use the ".py" extension at the end of the
module name. Patch by Pablo Galindo.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Add @ref{1cf,,os.waitstatus_to_exitcode()} function: convert a wait
status to an exit code.

@item 
bpo-40089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40089}: Fix threading._after_fork(): if fork was not called by a thread
spawned by threading.Thread, threading._after_fork() now creates a
_MainThread instance for _main_thread, instead of a _DummyThread instance.

@item 
bpo-40089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40089}: Add a private @code{_at_fork_reinit()} method to
@code{_thread.Lock}, @code{_thread.RLock}, @ref{cc2,,threading.RLock}
and @ref{b8b,,threading.Condition} classes: reinitialize the lock at fork in
the child process, reset the lock to the unlocked state. Rename also the
private @code{_reset_internal_locks()} method of @ref{b8e,,threading.Event} to
@code{_at_fork_reinit()}.

@item 
bpo-25780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25780}: Expose @ref{1e3,,CAN_RAW_JOIN_FILTERS} in the
@ref{ef,,socket} module.

@item 
bpo-39503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39503}: @ref{fed,,AbstractBasicAuthHandler} of
@ref{129,,urllib.request} now parses all WWW-Authenticate HTTP headers and
accepts multiple challenges per header: use the realm of the first Basic
challenge.

@item 
bpo-39812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39812}: Removed daemon threads from @ref{21,,concurrent.futures} by adding
an internal @code{threading._register_atexit()}, which calls registered
functions prior to joining all non-daemon threads. This allows for
compatibility with subinterpreters, which don't support daemon threads.

@item 
bpo-40050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40050}: Fix @code{importlib._bootstrap_external}: avoid creating a new
@code{winreg} builtin module if it's already available in
@ref{109a,,sys.modules}, and remove redundant imports.

@item 
bpo-40014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40014}: Fix @code{os.getgrouplist()}: if @code{getgrouplist()} function fails
because the group list is too small, retry with a larger group list. On
failure, the glibc implementation of @code{getgrouplist()} sets @code{ngroups}
to the total number of groups. For other implementations, double the group
list size.

@item 
bpo-40017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40017}: Add @ref{109b,,time.CLOCK_TAI} constant if the operating system
support it.

@item 
bpo-40016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40016}: In re docstring, clarify the relationship between inline and
argument compile flags.

@item 
bpo-39953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39953}: Update internal table of OpenSSL error codes in the @code{ssl}
module.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} operators to
@ref{109c,,weakref.WeakValueDictionary}.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} operators to
@ref{109d,,weakref.WeakKeyDictionary}.

@item 
bpo-38891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38891}: Fix linear runtime behaviour of the @code{__getitem__} and
@code{__setitem__} methods in
@ref{109e,,multiprocessing.shared_memory.ShareableList}. This avoids
quadratic performance when iterating a @code{ShareableList}. Patch by Thomas
Krennwallner.

@item 
bpo-39682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39682}: Remove undocumented support for @emph{closing} a @ref{336,,pathlib.Path}
object via its context manager. The context manager magic methods remain,
but they are now a no-op, making @code{Path} objects immutable.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Added 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} operators (@code{|} and @code{|=}) to
@ref{5ac,,collections.ChainMap}.

@item 
bpo-39011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39011}: Normalization of line endings in ElementTree attributes was
removed, as line endings which were replaced by entity numbers should be
preserved in original form.

@item 
bpo-38410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38410}: Properly handle @ref{109f,,sys.audit()} failures in
@ref{10a0,,sys.set_asyncgen_hooks()}.

@item 
bpo-36541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36541}: lib2to3 now recognizes named assignment expressions (the walrus
operator, @code{:=})

@item 
bpo-35967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35967}: In platform, delay the invocation of 'uname -p' until the
processor attribute is requested.

@item 
bpo-35113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35113}: @ref{1025,,inspect.getsource()} now returns correct source code for
inner class with same name as module level class. Decorators are also
returned as part of source of the class. Patch by Karthikeyan
Singaravelan.

@item 
bpo-33262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33262}: Deprecate passing None as an argument for
@ref{211,,shlex.split()}'s @code{s} parameter.  Patch by Zackery Spytz.

@item 
bpo-31758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31758}: Prevent crashes when using an uninitialized
@code{_elementtree.XMLParser} object. Patch by Oren Milman.
@end itemize

@node Documentation<16>,Tests<18>,Library<26>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id163}@anchor{10a1}
@subsubsection Documentation



@itemize -

@item 
bpo-27635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27635}: The pickle documentation incorrectly claimed that @code{__new__}
isn't called by default when unpickling.

@item 
bpo-39879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39879}: Updated @ref{10a2,,数据模型} docs to include @ref{164,,dict()} insertion
order preservation. Patch by Furkan Onder and Samy Lahfa.

@item 
bpo-38387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38387}: Document @ref{10a3,,PyDoc_STRVAR} macro in the C-API reference.

@item 
bpo-13743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13743}: Some methods within xml.dom.minidom.Element class are now
better documented.
@end itemize

@node Tests<18>,Build<16>,Documentation<16>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id164}@anchor{10a4}
@subsubsection Tests



@itemize -

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Set expected default encoding in test_c_locale_coercion.py for
VxWorks RTOS.

@item 
bpo-40162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40162}: Update Travis CI configuration to OpenSSL 1.1.1f.

@item 
bpo-40146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40146}: Update OpenSSL to 1.1.1f in Azure Pipelines.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Add @ref{10a5,,test.support.wait_process()} function.

@item 
bpo-40003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40003}: @code{test.bisect_cmd} now copies Python command line options like
@code{-O} or @code{-W}. Moreover, emit a warning if @code{test.bisect_cmd} is used
with @code{-w}/@code{--verbose2} option.

@item 
bpo-39380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39380}: Add the encoding in @ref{1a6,,ftplib.FTP} and
@ref{1a7,,ftplib.FTP_TLS} to the constructor as keyword-only and change the
default from @code{latin-1} to @code{utf-8} to follow 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://tools.ietf.org/html/rfc2640.html}.

@item 
bpo-39793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39793}: Use the same domain when testing @code{make_msgid}. Patch by
Batuhan Taskaya.

@item 
bpo-1812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1812}: Fix newline handling in doctest.testfile when loading from a
package whose loader has a get_data method. Patch by Peter Donis.
@end itemize

@node Build<16>,Windows<19>,Tests<18>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id165}@anchor{10a6}
@subsubsection Build



@itemize -

@item 
bpo-38360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38360}: Support single-argument form of macOS -isysroot flag.

@item 
bpo-40158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40158}: Fix CPython MSBuild Properties in NuGet Package
(build/native/python.props)

@item 
bpo-38527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38527}: Fix configure check on Solaris for "float word ordering":
sometimes, the correct "grep" command was not being used. Patch by Arnon
Yaari.
@end itemize

@node Windows<19>,macOS<17>,Build<16>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id166}@anchor{10a7}
@subsubsection Windows



@itemize -

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Updates Windows to OpenSSL 1.1.1f

@item 
bpo-8901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8901}: Ignore the Windows registry when the @code{-E} option is used.
@end itemize

@node macOS<17>,IDLE<15>,Windows<19>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id167}@anchor{10a8}
@subsubsection macOS



@itemize -

@item 
bpo-38329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38329}: python.org macOS installers now update the Current version
symlink of /Library/Frameworks/Python.framework/Versions for 3.9 installs.
Previously, Current was only updated for Python 2.x installs. This should
make it easier to embed Python 3 into other macOS applications.

@item 
bpo-40164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40164}: Update macOS installer builds to use OpenSSL 1.1.1g.
@end itemize

@node IDLE<15>,Tools/Demos<6>,macOS<17>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id168}@anchor{10a9}
@subsubsection IDLE



@itemize -

@item 
bpo-38439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38439}: Add a 256×256 pixel IDLE icon to support more modern
environments. Created by Andrew Clover. Delete the unused macOS idle.icns
icon file.

@item 
bpo-38689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38689}: IDLE will no longer freeze when inspect.signature fails when
fetching a calltip.
@end itemize

@node Tools/Demos<6>,C API<11>,IDLE<15>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id169}@anchor{10aa}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-40385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40385}: Removed the checkpyc.py tool. Please see compileall without
force mode as a potential alternative.

@item 
bpo-40179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40179}: Fixed translation of @code{#elif} in Argument Clinic.

@item 
bpo-40094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40094}: Fix @code{which.py} script exit code: it now uses
@ref{1cf,,os.waitstatus_to_exitcode()} to convert @ref{e8e,,os.system()} exit status
into an exit code.
@end itemize

@node C API<11>,,Tools/Demos<6>,Python 3 9 0 alpha 6
@anchor{whatsnew/changelog id170}@anchor{10ab}
@subsubsection C API



@itemize -

@item 
bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}: Move the @code{PyGC_Head} structure to the internal C API.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert @ref{268,,PyObject_IS_GC()} macro to a function to hide
implementation details.

@item 
bpo-40241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40241}: Add the functions @ref{255,,PyObject_GC_IsTracked()} and
@ref{256,,PyObject_GC_IsFinalized()} to the public API to allow to query if
Python objects are being currently tracked or have been already finalized
by the garbage collector respectively. Patch by Pablo Galindo.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: The @code{PyObject_NEW()} macro becomes an alias to the
@ref{269,,PyObject_New()} macro, and the @code{PyObject_NEW_VAR()} macro
becomes an alias to the @ref{26a,,PyObject_NewVar()} macro, to hide
implementation details. They no longer access directly the
@ref{26b,,PyTypeObject.tp_basicsize} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: @ref{105a,,PyType_HasFeature()} now always calls
@ref{105c,,PyType_GetFlags()} to hide implementation details. Previously, it
accessed directly the @ref{105b,,PyTypeObject.tp_flags} member when the
limited C API was not used.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert the @code{PyObject_GET_WEAKREFS_LISTPTR()} macro to a
function to hide implementation details: the macro accessed directly to
the @ref{26c,,PyTypeObject.tp_weaklistoffset} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Convert @ref{26d,,PyObject_CheckBuffer()} macro to a function to
hide implementation details: the macro accessed directly the
@ref{26e,,PyTypeObject.tp_as_buffer} member.

@item 
bpo-40170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40170}: Always declare @ref{26f,,PyIndex_Check()} as an opaque function to
hide implementation details: remove @code{PyIndex_Check()} macro. The macro
accessed directly the @ref{270,,PyTypeObject.tp_as_number} member.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{250,,PyThreadState_GetID()} function: get the unique
identifier of a Python thread state.
@end itemize

@node Python 3 9 0 alpha 5,Python 3 9 0 alpha 4,Python 3 9 0 alpha 6,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-5}@anchor{10ac}
@subsection Python 3.9.0 alpha 5


@emph{Release date: 2020-03-23}

@menu
* Security: Security<15>. 
* Core and Builtins: Core and Builtins<25>. 
* Library: Library<27>. 
* Documentation: Documentation<17>. 
* Tests: Tests<19>. 
* Build: Build<17>. 
* Windows: Windows<20>. 
* macOS: macOS<18>. 
* IDLE: IDLE<16>. 
* Tools/Demos: Tools/Demos<7>. 
* C API: C API<12>. 

@end menu

@node Security<15>,Core and Builtins<25>,,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id171}@anchor{10ad}
@subsubsection Security



@itemize -

@item 
bpo-38576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38576}: Disallow control characters in hostnames in http.client,
addressing CVE-2019-18348. Such potentially malicious header injection
URLs now cause a InvalidURL to be raised.
@end itemize

@node Core and Builtins<25>,Library<27>,Security<15>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id172}@anchor{10ae}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010}: Optimize pending calls in multithreaded applications. If a
thread different than the main thread schedules a pending call
(@ref{260,,Py_AddPendingCall()}), the bytecode evaluation loop is no longer
interrupted at each bytecode instruction to check for pending calls which
cannot be executed. Only the main thread can execute pending calls.

Previously, the bytecode evaluation loop was interrupted at each
instruction until the main thread executes pending calls.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _weakref extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _collections module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-40010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40010}: Optimize signal handling in multithreaded applications. If a
thread different than the main thread gets a signal, the bytecode
evaluation loop is no longer interrupted at each bytecode instruction to
check for pending signals which cannot be handled. Only the main thread of
the main interpreter can handle signals.

Previously, the bytecode evaluation loop was interrupted at each
instruction until the main thread handles signals.

@item 
bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984}: If @ref{260,,Py_AddPendingCall()} is called in a subinterpreter,
the function is now scheduled to be called from the subinterpreter, rather
than being called from the main interpreter. Each subinterpreter now has
its own list of scheduled calls.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _heapq module to multiphase initialization.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port itertools module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{frozenset()} by using the 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}
@code{vectorcall} calling convention. Patch by Dong-hee Na.

@item 
bpo-39984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39984}: subinterpreters: Move
@code{_PyRuntimeState.ceval.tracing_possible} to
@code{PyInterpreterState.ceval.tracing_possible}: each interpreter now has
its own variable.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{set()} by using the 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}
@code{vectorcall} calling convention. Patch by Dong-hee Na.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _statistics module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39968}: Use inline function to replace extension modules'
get_module_state macros.

@item 
bpo-39965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39965}: Correctly raise @code{SyntaxError} if @emph{await} is used inside
non-async functions and @code{PyCF_ALLOW_TOP_LEVEL_AWAIT} is set (like in the
asyncio REPL). Patch by Pablo Galindo.

@item 
bpo-39562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39562}: Allow executing asynchronous comprehensions on the top level
when the @code{PyCF_ALLOW_TOP_LEVEL_AWAIT} flag is given. Patch by Batuhan
Taskaya.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{tuple()} by using the 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}
@code{vectorcall} calling convention. Patch by Dong-hee Na.

@item 
bpo-38373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38373}: Changed list overallocation strategy. It no longer
overallocates if the new size is closer to overalocated size than to the
old size and adds padding.

@item 
bpo-39926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39926}: Update Unicode database to Unicode version 13.0.0.

@item 
bpo-19466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19466}: Clear the frames of daemon threads earlier during the Python
shutdown to call objects destructors. So "unclosed file" resource warnings
are now emitted for daemon threads in a more reliable way.

@item 
bpo-38894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38894}: Fix a bug that was causing incomplete results when calling
@code{pathlib.Path.glob} in the presence of symlinks that point to files
where the user does not have read access. Patch by Pablo Galindo and Matt
Wozniski.

@item 
bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877}: Fix @ref{3de,,PyEval_RestoreThread()} random crash at exit with
daemon threads. It now accesses the @code{_PyRuntime} variable directly
instead of using @code{tstate->interp->runtime}, since @code{tstate} can be a
dangling pointer after @ref{dbb,,Py_Finalize()} has been called. Moreover,
the daemon thread now exits before trying to take the GIL.

@item 
bpo-39871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39871}: Fix a possible @ref{6fc,,SystemError} in
@code{math.@{atan2,copysign,remainder@}()} when the first argument cannot be
converted to a @ref{1fe,,float}. Patch by Zackery Spytz.

@item 
bpo-39776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39776}: Fix race condition where threads created by PyGILState_Ensure()
could get a duplicate id.

This affects consumers of tstate->id like the contextvar caching
machinery, which could return invalid cached objects under heavy thread
load (observed in embedded scenarios).

@item 
bpo-39778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39778}: Fixed a crash due to incorrect handling of weak references in
@code{collections.OrderedDict} classes. Patch by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port audioop extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39702}: Relax @ref{174,,decorator} grammar restrictions to allow any valid
expression (
@geindex Python 提高建议; PEP 614
PEP 614@footnote{https://www.python.org/dev/peps/pep-0614}).

@item 
bpo-38091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38091}: Tweak import deadlock detection code to not deadlock itself.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _locale extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39087}: Optimize @ref{537,,PyUnicode_AsUTF8()} and
@ref{536,,PyUnicode_AsUTF8AndSize()} slightly when they need to create
internal UTF-8 cache.

@item 
bpo-39520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39520}: Fix unparsing of ext slices with no items (@code{foo[:,]}). Patch
by Batuhan Taskaya.

@item 
bpo-39220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39220}: Do not optimize annotations if 'from __future__ import
annotations' is used. Patch by Pablo Galindo.

@item 
bpo-35712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35712}: Using @ref{203,,NotImplemented} in a boolean context has been
deprecated. Patch contributed by Josh Rosenberg.

@item 
bpo-22490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22490}: Don't leak environment variable @code{__PYVENV_LAUNCHER__} into
the interpreter session on macOS.
@end itemize

@node Library<27>,Documentation<17>,Core and Builtins<25>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id173}@anchor{10af}
@subsubsection Library



@itemize -

@item 
bpo-39830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39830}: Add @ref{10b0,,zipfile.Path} to @code{__all__} in the @ref{14b,,zipfile}
module.

@item 
bpo-40000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40000}: Improved error messages for validation of @code{ast.Constant}
nodes. Patch by Batuhan Taskaya.

@item 
bpo-39999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39999}: @code{__module__} of the AST node classes is now set to "ast"
instead of "_ast". Added docstrings for dummy AST node classes and
deprecated attributes.

@item 
bpo-39991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39991}: @ref{51f,,uuid.getnode()} now skips IPv6 addresses with the same
string length than a MAC address (17 characters): only use MAC addresses.

@item 
bpo-39988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39988}: Deprecated @code{ast.AugLoad} and @code{ast.AugStore} node classes
because they are no longer used.

@item 
bpo-39656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39656}: Ensure @code{bin/python3.#} is always present in virtual
environments on POSIX platforms - by Anthony Sottile.

@item 
bpo-39969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39969}: Deprecated @code{ast.Param} node class because it's no longer
used. Patch by Batuhan Taskaya.

@item 
bpo-39360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39360}: Ensure all workers exit when finalizing a
@code{multiprocessing.Pool} implicitly via the module finalization
handlers of multiprocessing. This fixes a deadlock situation that can be
experienced when the Pool is not properly finalized via the context
manager or a call to @code{multiprocessing.Pool.terminate}. Patch by Batuhan
Taskaya and Pablo Galindo.

@item 
bpo-35370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35370}: sys.settrace(), sys.setprofile() and _lsprof.Profiler.enable()
now properly report @ref{10b1,,PySys_Audit()} error if "sys.setprofile" or
"sys.settrace" audit event is denied.

@item 
bpo-39936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39936}: AIX: Fix _aix_support module when the subprocess is not
available, when building Python from scratch. It now uses new private
_bootsubprocess module, rather than having two implementations depending
if subprocess is available or not. So _aix_support.aix_platform() result
is now the same if subprocess is available or not.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{2f1,,collections.OrderedDict} now implements @code{|} and
@code{|=} (
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}).

@item 
bpo-39652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39652}: The column name found in @code{sqlite3.Cursor.description} is now
truncated on the first '[' only if the PARSE_COLNAMES option is set.

@item 
bpo-39915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39915}: Ensure @ref{10b2,,unittest.mock.AsyncMock.await_args_list} has call
objects in the order of awaited arguments instead of using
@ref{10b3,,unittest.mock.Mock.call_args} which has the last value of the call.
Patch by Karthikeyan Singaravelan.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: Updated @ref{c12,,os.environ} and @ref{c6e,,os.environb} to support
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}'s merge (@code{|}) and update (@code{|=}) operators.

@item 
bpo-38662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38662}: The @code{ensurepip} module now invokes @code{pip} via the @code{runpy}
module. Hence it is no longer tightly coupled with the internal API of the
bundled @code{pip} version, allowing easier updates to a newer @code{pip}
version both internally and for distributors.

@item 
bpo-38075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38075}: Fix the @code{random.Random.seed()} method when a @ref{2c4,,bool}
is passed as the seed.

@item 
bpo-39916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39916}: More reliable use of @code{os.scandir()} in @code{Path.glob()}. It no
longer emits a ResourceWarning when interrupted.

@item 
bpo-39850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39850}: @ref{b7,,multiprocessing} now supports abstract socket addresses
(if abstract sockets are supported in the running platform). When creating
arbitrary addresses (like when default-constructing
@ref{10b4,,multiprocessing.connection.Listener} objects) abstract sockets are
preferred to avoid the case when the temporary-file-generated address is
too large for an AF_UNIX socket address. Patch by Pablo Galindo.

@item 
bpo-36287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36287}: @ref{185,,ast.dump()} no longer outputs optional fields and
attributes with default values. The default values for optional fields and
attributes of AST nodes are now set as class attributes (e.g.
@code{Constant.kind} is set to @code{None}).

@item 
bpo-39889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39889}: Fixed @ref{186,,ast.unparse()} for extended slices containing a
single element (e.g. @code{a[i:j,]}). Remove redundant tuples when index with
a tuple (e.g. @code{a[i, j]}).

@item 
bpo-39828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39828}: Fix @ref{a5,,json.tool} to catch @ref{a87,,BrokenPipeError}. Patch by
Dong-hee Na.

@item 
bpo-13487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13487}: Avoid a possible @emph{"RuntimeError: dictionary changed size during
iteration"} from @ref{fb7,,inspect.getmodule()} when it tried to loop through
@ref{109a,,sys.modules}.

@item 
bpo-39674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39674}: Revert "bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}: open() no longer accept 'U' in file mode".
The "U" mode of open() is kept in Python 3.9 to ease transition from
Python 2.7, but will be removed in Python 3.10.

@item 
bpo-28577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28577}: The hosts method on 32-bit prefix length IPv4Networks and
128-bit prefix IPv6Networks now returns a list containing the single
Address instead of an empty list.

@item 
bpo-39826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39826}: Add getConnection method to logging HTTPHandler to enable
custom connections.

@item 
bpo-39763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39763}: Reimplement @code{distutils.spawn.spawn()} function with the
@ref{f9,,subprocess} module.

@item 
bpo-39794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39794}: Add --without-decimal-contextvar build option.  This enables a
thread-local rather than a coroutine local context.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{c15,,collections.defaultdict} now implements @code{|}
(
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}).

@item 
bpo-39517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39517}: Fix runpy.run_path() when using pathlike objects

@item 
bpo-39775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39775}: Change @code{inspect.Signature.parameters} back to
@code{collections.OrderedDict}. This was changed to @code{dict} in Python
3.9.0a4.

@item 
bpo-39678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39678}: Refactor queue_manager in
@ref{196,,concurrent.futures.ProcessPoolExecutor} to make it easier to
maintain.

@item 
bpo-39764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39764}: Fix AttributeError when calling get_stack on a PyAsyncGenObject
Task

@item 
bpo-39769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39769}: The @ref{483,,compileall.compile_dir()} function's @emph{ddir} parameter
and the compileall command line flag @code{-d} no longer write the wrong
pathname to the generated pyc file for submodules beneath the root of the
directory tree being compiled.  This fixes a regression introduced with
Python 3.5.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{b97,,types.MappingProxyType} objects now support the merge
(@code{|}) operator from 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}.

@item 
bpo-38691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38691}: The @ref{9a,,importlib} module now ignores the
@geindex PYTHONCASEOK
@geindex 环境变量; PYTHONCASEOK
@ref{233,,PYTHONCASEOK} environment variable when the @ref{231,,-E} or
@ref{232,,-I} command line options are being used.

@item 
bpo-39719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39719}: Remove @code{tempfile.SpooledTemporaryFile.softspace()} as files
no longer have the @code{softspace} attribute in Python 3. Patch by Shantanu.

@item 
bpo-39667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39667}: Improve pathlib.Path compatibility on zipfile.Path and correct
performance degradation as found in zipp 3.0.

@item 
bpo-39638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39638}: Keep ASDL signatures in the docstrings for @code{AST} nodes. Patch
by Batuhan Taskaya

@item 
bpo-39639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39639}: Deprecated @code{ast.Suite} node class because it's no longer
used. Patch by Batuhan Taskaya.

@item 
bpo-39609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39609}: Add thread_name_prefix to default asyncio executor

@item 
bpo-39548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39548}: Fix handling of header in
@ref{10b5,,urllib.request.AbstractDigestAuthHandler} when the optional
@code{qop} parameter is not present.

@item 
bpo-39509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39509}: HTTP status codes @code{103 EARLY_HINTS} and @code{425 TOO_EARLY} are
added to @ref{1ac,,http.HTTPStatus}. Patch by Dong-hee Na.

@item 
bpo-39507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39507}: Adding HTTP status 418 "I'm a Teapot" to HTTPStatus in http
library. Patch by Ross Rhodes.

@item 
bpo-39495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39495}: Remove default value from @emph{attrs} parameter of
@ref{10b6,,xml.etree.ElementTree.TreeBuilder.start()} for consistency between
Python and C implementations.

@item 
bpo-38971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38971}: Open issue in the BPO indicated a desire to make the
implementation of codecs.open() at parity with io.open(), which implements
a try/except to assure file stream gets closed before an exception is
raised.

@item 
bpo-38641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38641}: Added starred expressions support to @code{return} and @code{yield}
statements for @code{lib2to3}. Patch by Vlad Emelianov.

@item 
bpo-37534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37534}: When using minidom module to generate XML documents the ability
to add Standalone Document Declaration is added. All the changes are made
to generate a document in compliance with Extensible Markup Language (XML)
1.0 (Fifth Edition) W3C Recommendation (available here:
@indicateurl{https://www.w3.org/TR/xml/#sec-prolog-dtd}).

@item 
bpo-34788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34788}: Add support for scoped IPv6 addresses to @ref{a2,,ipaddress}.
Patch by Oleksandr Pavliuk.

@item 
bpo-34822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34822}: Simplified AST for subscription. Simple indices are now
represented by their value, extended slices are represented as tuples.
@ref{7,,ast} classes @code{Index} and @code{ExtSlice} are considered deprecated
and will be removed in future Python versions. In the meantime,
@code{Index(value)} now returns a @code{value} itself, @code{ExtSlice(slices)}
returns @code{Tuple(slices, Load())}.
@end itemize

@node Documentation<17>,Tests<19>,Library<27>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id174}@anchor{10b7}
@subsubsection Documentation



@itemize -

@item 
bpo-39868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39868}: Updated the Language Reference for 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572}.

@item 
bpo-13790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13790}: Change 'string' to 'specification' in format doc.

@item 
bpo-17422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17422}: The language reference no longer restricts default class
namespaces to dicts only.

@item 
bpo-39530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39530}: Fix misleading documentation about mixed-type numeric
comparisons.

@item 
bpo-39718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39718}: Update @ref{119,,token} documentation to reflect additions in
Python 3.8

@item 
bpo-39677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39677}: Changed operand name of @strong{MAKE_FUNCTION} from @emph{argc} to
@emph{flags} for module @ref{37,,dis}
@end itemize

@node Tests<19>,Build<17>,Documentation<17>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id175}@anchor{10b8}
@subsubsection Tests



@itemize -

@item 
bpo-40019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40019}: test_gdb now skips tests if it detects that gdb failed to read
debug information because the Python binary is optimized.

@item 
bpo-27807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27807}: @code{test_site.test_startup_imports()} is now skipped if a path
of @ref{262,,sys.path} contains a @code{.pth} file.

@item 
bpo-26067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26067}: Do not fail test_shutil test_chown test when uid or gid of user
cannot be resolved to a name.

@item 
bpo-39855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39855}: test_subprocess.test_user() now skips the test on an user name
if the user name doesn't exist. For example, skip the test if the user
"nobody" doesn't exist on Linux.
@end itemize

@node Build<17>,Windows<20>,Tests<19>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id176}@anchor{10b9}
@subsubsection Build



@itemize -

@item 
bpo-39761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39761}: Fix build with DTrace but without additional DFLAGS.

@item 
bpo-39763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39763}: setup.py now uses a basic implementation of the
@ref{f9,,subprocess} module if the @ref{f9,,subprocess} module is not available:
before required C extension modules are built.

@item 
bpo-1294959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1294959}: Add @code{--with-platlibdir} option to the configure script:
name of the platform-specific library directory, stored in the new
@ref{1ea,,sys.platlibdir} attribute. It is used to build the path of
platform-specific extension modules and the path of the standard library.
It is equal to @code{"lib"} on most platforms. On Fedora and SuSE, it is
equal to @code{"lib64"} on 64-bit platforms. Patch by Jan Matějek, Matěj
Cepl, Charalampos Stratakis and Victor Stinner.
@end itemize

@node Windows<20>,macOS<18>,Build<17>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id177}@anchor{10ba}
@subsubsection Windows



@itemize -

@item 
bpo-39930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39930}: Ensures the required @code{vcruntime140.dll} is included in
install packages.

@item 
bpo-39847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39847}: Avoid hang when computer is hibernated whilst waiting for a
mutex (for lock-related objects from @ref{10b,,threading}) around 49-day
uptime.

@item 
bpo-38597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38597}: @ref{38,,distutils} will no longer statically link
@code{vcruntime140.dll} when a redistributable version is unavailable.
All future releases of CPython will include a copy of this DLL to ensure
distributed extensions can continue to load.

@item 
bpo-38380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38380}: Update Windows builds to use SQLite 3.31.1

@item 
bpo-39789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39789}: Update Windows release build machines to Visual Studio 2019
(MSVC 14.2).

@item 
bpo-34803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34803}: Package for nuget.org now includes repository reference and
bundled icon image.
@end itemize

@node macOS<18>,IDLE<16>,Windows<20>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id178}@anchor{10bb}
@subsubsection macOS



@itemize -

@item 
bpo-38380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38380}: Update macOS builds to use SQLite 3.31.1
@end itemize

@node IDLE<16>,Tools/Demos<7>,macOS<18>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id179}@anchor{10bc}
@subsubsection IDLE



@itemize -

@item 
bpo-27115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27115}: For 'Go to Line', use a Query box subclass with IDLE standard
behavior and improved error checking.

@item 
bpo-39885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39885}: Since clicking to get an IDLE context menu moves the cursor,
any text selection should be and now is cleared.

@item 
bpo-39852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39852}: Edit "Go to line" now clears any selection, preventing
accidental deletion. It also updates Ln and Col on the status bar.

@item 
bpo-39781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39781}: Selecting code context lines no longer causes a jump.
@end itemize

@node Tools/Demos<7>,C API<12>,IDLE<16>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id180}@anchor{10bd}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-36184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36184}: Port python-gdb.py to FreeBSD. python-gdb.py now checks for
"take_gil" function name to check if a frame tries to acquire the GIL,
instead of checking for "pthread_cond_timedwait" which is specific to
Linux and can be a different condition than the GIL.

@item 
bpo-38080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38080}: Added support to fix @code{getproxies} in the
@code{lib2to3.fixes.fix_urllib} module. Patch by José Roberto Meza
Cabrera.
@end itemize

@node C API<12>,,Tools/Demos<7>,Python 3 9 0 alpha 5
@anchor{whatsnew/changelog id181}@anchor{10be}
@subsubsection C API



@itemize -

@item 
bpo-40024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=40024}: Add @ref{254,,PyModule_AddType()} helper function: add a type to a
module. Patch by Dong-hee Na.

@item 
bpo-39946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39946}: Remove @code{_PyRuntime.getframe} hook and remove
@code{_PyThreadState_GetFrame} macro which was an alias to
@code{_PyRuntime.getframe}. They were only exposed by the internal C API.
Remove also @code{PyThreadFrameGetter} type.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{24f,,PyThreadState_GetFrame()} function: get the current
frame of a Python thread state.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Add _PyArg_NoKwnames helper function. Patch by Dong-hee Na.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{24d,,PyThreadState_GetInterpreter()}: get the interpreter
of a Python thread state.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Add @ref{24e,,PyInterpreterState_Get()} function to the limited C
API.

@item 
bpo-35370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35370}: If @ref{10b1,,PySys_Audit()} fails in @ref{f05,,PyEval_SetProfile()}
or @ref{f06,,PyEval_SetTrace()}, log the error as an unraisable exception.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Move the static inline function flavor of
Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() to the internal C API:
they access PyThreadState attributes. The limited C API provides regular
functions which hide implementation details.

@item 
bpo-39947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39947}: Py_TRASHCAN_BEGIN_CONDITION and Py_TRASHCAN_END macro no longer
access PyThreadState attributes, but call new private _PyTrash_begin() and
_PyTrash_end() functions which hide implementation details.

@item 
bpo-39884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39884}: @ref{10bf,,PyDescr_NewMethod()} and @code{PyCFunction_NewEx()} now
include the method name in the SystemError "bad call flags" error message
to ease debug.

@item 
bpo-39877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39877}: Deprecated @ref{20d,,PyEval_InitThreads()} and
@ref{20e,,PyEval_ThreadsInitialized()}. Calling @ref{20d,,PyEval_InitThreads()}
now does nothing.

@item 
bpo-38249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38249}: @ref{52f,,Py_UNREACHABLE} is now implemented with
@code{__builtin_unreachable()} and analogs in release mode.

@item 
bpo-38643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38643}: @ref{10c0,,PyNumber_ToBase()} now raises a @ref{6fc,,SystemError}
instead of crashing when called with invalid base.

@item 
bpo-39882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39882}: The @ref{267,,Py_FatalError()} function is replaced with a macro
which logs automatically the name of the current function, unless the
@code{Py_LIMITED_API} macro is defined.

@item 
bpo-39824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39824}: Extension modules: @ref{25a,,m_traverse},
@ref{25b,,m_clear} and @ref{25c,,m_free}
functions of @ref{259,,PyModuleDef} are no longer called if the module
state was requested but is not allocated yet. This is the case immediately
after the module is created and before the module is executed
(@ref{25d,,Py_mod_exec} function). More precisely, these functions are not
called if @ref{25e,,m_size} is greater than 0 and the module
state (as returned by @ref{25f,,PyModule_GetState()}) is @code{NULL}.

Extension modules without module state (@code{m_size <= 0}) are not affected.

@item 
bpo-38913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38913}: Fixed segfault in @code{Py_BuildValue()} called with a format
containing "#" and undefined PY_SSIZE_T_CLEAN whwn an exception is set.

@item 
bpo-38500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38500}: Add a private API to get and set the frame evaluation function:
add @ref{10c1,,_PyInterpreterState_GetEvalFrameFunc()} and
@ref{10c2,,_PyInterpreterState_SetEvalFrameFunc()} C functions. The
@ref{10c3,,_PyFrameEvalFunction} function type now takes a @emph{tstate}
parameter.
@end itemize

@node Python 3 9 0 alpha 4,Python 3 9 0 alpha 3,Python 3 9 0 alpha 5,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-4}@anchor{10c4}
@subsection Python 3.9.0 alpha 4


@emph{Release date: 2020-02-25}

@menu
* Security: Security<16>. 
* Core and Builtins: Core and Builtins<26>. 
* Library: Library<28>. 
* Documentation: Documentation<18>. 
* Tests: Tests<20>. 
* Build: Build<18>. 
* Windows: Windows<21>. 
* IDLE: IDLE<17>. 
* C API: C API<13>. 

@end menu

@node Security<16>,Core and Builtins<26>,,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id182}@anchor{10c5}
@subsubsection Security



@itemize -

@item 
bpo-39184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39184}: Add audit events to functions in @ref{7c,,fcntl}, @ref{b6,,msvcrt}, @ref{c4,,os},
@ref{e0,,resource}, @ref{e9,,shutil}, @ref{ea,,signal} and @ref{ff,,syslog}.

@item 
bpo-39401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39401}: Avoid unsafe DLL load at startup on Windows 7 and earlier.

@item 
bpo-39184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39184}: Add audit events to command execution functions in os and pty
modules.
@end itemize

@node Core and Builtins<26>,Library<28>,Security<16>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id183}@anchor{10c6}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39382}: Fix a use-after-free in the single inheritance path of
@code{issubclass()}, when the @code{__bases__} of an object has a single
reference, and so does its first item. Patch by Yonatan Goldschmidt.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Update clinic tool to use @ref{10c7,,Py_IS_TYPE()}. Patch by
Dong-hee Na.

@item 
bpo-39619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39619}: Enable use of @ref{10c8,,os.chroot()} on HP-UX systems.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{10c7,,Py_IS_TYPE()} static inline function to check
whether the object @emph{o} type is @emph{type}.

@item 
bpo-39606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39606}: Fix regression caused by fix for bpo-39386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39386}, that prevented
calling @code{aclose} on an async generator that had already been closed or
exhausted.

@item 
bpo-39579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39579}: Change the ending column offset of @code{Attribute} nodes
constructed in @code{ast_for_dotted_name} to point at the end of the current
node and not at the end of the last @code{NAME} node.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _crypt extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _contextvars extension module to multiphase
initialization (
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39510}: Fix segfault in @code{readinto()} method on closed BufferedReader.

@item 
bpo-39502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39502}: Fix @ref{10c9,,time.localtime()} on 64-bit AIX  to support years
before 1902 and after 2038. Patch by M Felt.

@item 
bpo-39492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39492}: Fix a reference cycle in the C Pickler that was preventing the
garbage collection of deleted, pickled objects.

@item 
bpo-39453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39453}: Fixed a possible crash in @code{list.__contains__()} when a list
is changed during comparing items. Patch by Dong-hee Na.

@item 
bpo-39434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39434}: @ref{1fa,,floor division} of float operation now has a better
performance. Also the message of @ref{1fb,,ZeroDivisionError} for this
operation is updated. Patch by Dong-hee Na.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _codecs extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _bz2 extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _abc extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39320}: Replace two complex bytecodes for building dicts with two
simpler ones. The new bytecodes @code{DICT_MERGE} and @code{DICT_UPDATE} have
been added The old bytecodes @code{BUILD_MAP_UNPACK} and
@code{BUILD_MAP_UNPACK_WITH_CALL} have been removed.

@item 
bpo-39219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39219}: Syntax errors raised in the tokenizer now always set correct
"text" and "offset" attributes.

@item 
bpo-36051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36051}: Drop the GIL during large @code{bytes.join} operations. Patch by
Bruce Merry.

@item 
bpo-38960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38960}: Fix DTrace build issues on FreeBSD. Patch by David Carlier.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: Speed up calls to @code{range()} by about 30%, by using the PEP
590 @code{vectorcall} calling convention. Patch by Mark Shannon.

@item 
bpo-36144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36144}: @ref{164,,dict} (and @ref{10ca,,collections.UserDict}) objects now
support PEP 584's merge (@code{|}) and update (@code{|=}) operators. Patch by
Brandt Bucher.

@item 
bpo-32856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32856}: Optimized the idiom for assignment a temporary variable in
comprehensions. Now @code{for y in [expr]} in comprehensions is as fast as a
simple assignment @code{y = expr}.
@end itemize

@node Library<28>,Documentation<18>,Core and Builtins<26>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id184}@anchor{10cb}
@subsubsection Library



@itemize -

@item 
bpo-30566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30566}: Fix @ref{f3d,,IndexError} when trying to decode an invalid string
with punycode codec.

@item 
bpo-39649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39649}: Remove obsolete check for @code{__args__} in
bdb.Bdb.format_stack_entry.

@item 
bpo-39648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39648}: Expanded @ref{1bf,,math.gcd()} and @ref{1c0,,math.lcm()} to handle
multiple arguments.

@item 
bpo-39681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39681}: Fix a regression where the C pickle module wouldn't allow
unpickling from a file-like object that doesn't expose a readinto()
method.

@item 
bpo-35950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35950}: Raise @ref{10cc,,io.UnsupportedOperation} in
@code{io.BufferedReader.truncate()} when it is called on a read-only
@ref{c64,,io.BufferedReader} instance.

@item 
bpo-39479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39479}: Add @ref{1c0,,math.lcm()} function: least common multiple.

@item 
bpo-39674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39674}: Revert "Do not expose abstract collection classes in the
collections module" change (bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}). Aliases to ABC like
collections.Mapping are kept in Python 3.9 to ease transition from Python
2.7, but will be removed in Python 3.10.

@item 
bpo-39104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39104}: Fix hanging ProcessPoolExcutor on @code{shutdown(wait=False)} when
a task has failed pickling.

@item 
bpo-39627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39627}: Fixed TypedDict totality check for inherited keys.

@item 
bpo-39474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39474}: Fixed starting position of AST for expressions like @code{(a)(b)},
@code{(a)[b]} and @code{(a).b}.

@item 
bpo-21016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21016}: The @ref{d9,,pydoc} and @ref{11b,,trace} modules now use the
@ref{fe,,sysconfig} module to get the path to the Python standard library, to
support uncommon installation path like @code{/usr/lib64/python3.9/} on
Fedora. Patch by Jan Matějek.

@item 
bpo-39590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39590}: Collections.deque now holds strong references during
deque.__contains__ and deque.count, fixing crashes.

@item 
bpo-39586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39586}: The distutils @code{bdist_msi} command is deprecated in Python
3.9, use @code{bdist_wheel} (wheel packages) instead.

@item 
bpo-39595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39595}: Improved performance of zipfile.Path for files with a large
number of entries. Also improved performance and fixed minor issue as
published with importlib_metadata 1.5@footnote{https://importlib-metadata.readthedocs.io/en/latest/changelog%20(links).html#v1-5-0}.

@item 
bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350}: Fix regression in @ref{2c5,,fractions.Fraction} if the numerator
and/or the denominator is an @ref{205,,int} subclass. The @ref{1bf,,math.gcd()}
function is now used to normalize the @emph{numerator} and @emph{denominator}.
@ref{1bf,,math.gcd()} always return a @ref{205,,int} type. Previously, the GCD
type depended on @emph{numerator} and @emph{denominator}.

@item 
bpo-39567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39567}: Added audit for @ref{751,,os.walk()}, @ref{4c3,,os.fwalk()},
@ref{10cd,,pathlib.Path.glob()} and @ref{10ce,,pathlib.Path.rglob()}.

@item 
bpo-39559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39559}: Remove unused, undocumented argument @code{getters} from
@ref{51f,,uuid.getnode()}

@item 
bpo-38149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38149}: @ref{109f,,sys.audit()} is now called only once per call of
@ref{6c7,,glob.glob()} and @ref{6c8,,glob.iglob()}.

@item 
bpo-39546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39546}: Fix a regression in @ref{792,,ArgumentParser} where
@code{allow_abbrev=False} was ignored for long options that used a prefix
character other than "-".

@item 
bpo-39450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39450}: Striped whitespace from docstring before returning it from
@code{unittest.case.shortDescription()}.

@item 
bpo-12915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12915}: A new function @code{resolve_name} has been added to the
@code{pkgutil} module. This resolves a string of the form @code{'a.b.c.d'} or
@code{'a.b:c.d'} to an object. In the example, @code{a.b} is a package/module
and @code{c.d} is an object within that package/module reached via recursive
attribute access.

@item 
bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353}: The @ref{10cf,,binascii.crc_hqx()} function is no longer deprecated.

@item 
bpo-39493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39493}: Mark @code{typing.IO.closed} as a property

@item 
bpo-39491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39491}: Add @ref{1ef,,typing.Annotated} and @code{include_extras} parameter
to @ref{1f0,,typing.get_type_hints()} as part of 
@geindex Python 提高建议; PEP 593
PEP 593@footnote{https://www.python.org/dev/peps/pep-0593}. Patch by Till
Varoquaux, documentation by Till Varoquaux and Konstantin Kashin.

@item 
bpo-39485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39485}: Fix a bug in @ref{10d0,,unittest.mock.create_autospec()} that would
complain about the wrong number of arguments for custom descriptors
defined in an extension module returning functions.

@item 
bpo-38932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38932}: Mock fully resets child objects on reset_mock(). Patch by
Vegard Stikbakke

@item 
bpo-39082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39082}: Allow AsyncMock to correctly patch static/class methods

@item 
bpo-39432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39432}: Implement PEP-489 algorithm for non-ascii "PyInit_..." symbol
names in distutils to make it export the correct init symbol also on
Windows.

@item 
bpo-18819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18819}: Omit @code{devmajor} and @code{devminor} fields for non-device files
in @ref{101,,tarfile} archives, enabling bit-for-bit compatibility with GNU
@code{tar(1)}.

@item 
bpo-39349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39349}: Added a new @emph{cancel_futures} parameter to
@ref{195,,concurrent.futures.Executor.shutdown()} that cancels all pending
futures which have not started running, instead of waiting for them to
complete before shutting down the executor.

@item 
bpo-39274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39274}: @code{bool(fraction.Fraction)} now returns a boolean even if
(numerator != 0) does not return a boolean (ex: numpy number).

@item 
bpo-34793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34793}: Remove support for @code{with (await asyncio.lock):} and @code{with
(yield from asyncio.lock):}.  The same is correct for
@code{asyncio.Condition} and @code{asyncio.Semaphore}.

@item 
bpo-25597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25597}: Ensure, if @code{wraps} is supplied to
@ref{87e,,unittest.mock.MagicMock}, it is used to calculate return values
for the magic methods instead of using the default return values. Patch by
Karthikeyan Singaravelan.

@item 
bpo-36350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36350}: @ref{10d1,,inspect.Signature.parameters} and
@ref{1ba,,inspect.BoundArguments.arguments} are now dicts instead of OrderedDicts.
Patch contributed by Rémi Lapeyre.

@item 
bpo-35727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35727}: Fix sys.exit() and sys.exit(None) exit code propagation when
used in multiprocessing.Process.

@item 
bpo-32173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32173}: * Add @code{lazycache} function to @code{__all__}. * Use @ref{10d2,,dict.clear} to
clear the cache. * Refactoring @code{getline} function and @code{checkcache}
function.
@end itemize

@node Documentation<18>,Tests<20>,Library<28>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id185}@anchor{10d3}
@subsubsection Documentation



@itemize -

@item 
bpo-17422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17422}: The language reference now specifies restrictions on class
namespaces. Adapted from a patch by Ethan Furman.

@item 
bpo-39572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39572}: Updated documentation of @code{total} flag of @code{TypedDict}.

@item 
bpo-39654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39654}: In pyclbr doc, update 'class' to 'module' where appropriate and
add readmodule comment. Patch by Hakan Çelik.

@item 
bpo-39153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39153}: Clarify refcounting semantics for the following functions: -
PyObject_SetItem - PyMapping_SetItemString - PyDict_SetItem -
PyDict_SetItemString

@item 
bpo-39392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39392}: Explain that when filling with turtle, overlap regions may be
left unfilled.

@item 
bpo-39369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39369}: Update mmap readline method description. The fact that the
readline method does update the file position should not be ignored since
this might give the impression for the programmer that it doesn't update
it.

@item 
bpo-9056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9056}: Include subsection in TOC for PDF version of docs.
@end itemize

@node Tests<20>,Build<18>,Documentation<18>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id186}@anchor{10d4}
@subsubsection Tests



@itemize -

@item 
bpo-38325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38325}: Skip tests on non-BMP characters of test_winconsoleio.

@item 
bpo-39502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39502}: Skip test_zipfile.test_add_file_after_2107() if
@ref{10c9,,time.localtime()} fails with @ref{a4a,,OverflowError}. It is the case on
AIX 6.1 for example.
@end itemize

@node Build<18>,Windows<21>,Tests<20>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id187}@anchor{10d5}
@subsubsection Build



@itemize -

@item 
bpo-39489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39489}: Remove @code{COUNT_ALLOCS} special build.
@end itemize

@node Windows<21>,IDLE<17>,Build<18>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id188}@anchor{10d6}
@subsubsection Windows



@itemize -

@item 
bpo-39553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39553}: Delete unused code related to SxS manifests.

@item 
bpo-39439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39439}: Honor the Python path when a virtualenv is active on Windows.

@item 
bpo-39393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39393}: Improve the error message when attempting to load a DLL with
unresolved dependencies.

@item 
bpo-38883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38883}: @ref{824,,home()} and
@ref{823,,expanduser()} on Windows now prefer
@geindex USERPROFILE
@geindex 环境变量; USERPROFILE
@code{USERPROFILE} and no longer use 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME}, which is not
normally set for regular user accounts. This makes them again behave like
@ref{333,,os.path.expanduser()}, which was changed to ignore 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} in
3.8, see bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}.

@item 
bpo-39185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39185}: The build.bat script has additional options for very-quiet
output (-q) and very-verbose output (-vv)
@end itemize

@node IDLE<17>,C API<13>,Windows<21>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id189}@anchor{10d7}
@subsubsection IDLE



@itemize -

@item 
bpo-39663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39663}: Add tests for pyparse find_good_parse_start().

@item 
bpo-39600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39600}: In the font configuration window, remove duplicated font names.

@item 
bpo-30780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30780}: Add remaining configdialog tests for buttons and highlights and
keys tabs.

@item 
bpo-39388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39388}: IDLE Settings Cancel button now cancels pending changes

@item 
bpo-38792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38792}: Close an IDLE shell calltip if a @ref{2d3,,KeyboardInterrupt} or
shell restart occurs.  Patch by Zackery Spytz.
@end itemize

@node C API<13>,,IDLE<17>,Python 3 9 0 alpha 4
@anchor{whatsnew/changelog id190}@anchor{10d8}
@subsubsection C API



@itemize -

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Move the @code{bytes_methods.h} header file to the internal C API
as @code{pycore_bytes_methods.h}: it only contains private symbols (prefixed
by @code{_Py}), except of the @code{PyDoc_STRVAR_shared()} macro.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Move the @code{dtoa.h} header file to the internal C API as
@code{pycore_dtoa.h}: it only contains private functions (prefixed by
@code{_Py}). The @ref{b1,,math} and @ref{18,,cmath} modules must now be compiled
with the @code{Py_BUILD_CORE} macro defined.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{10d9,,Py_SET_SIZE()} function to set the size of an
object.

@item 
bpo-39500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39500}: @ref{10da,,PyUnicode_IsIdentifier()} does not call
@ref{267,,Py_FatalError()} anymore if the string is not ready.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add @ref{10db,,Py_SET_TYPE()} function to set the type of an
object.

@item 
bpo-39573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39573}: Add a @ref{10dc,,Py_SET_REFCNT()} function to set the reference
counter of an object.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: Convert @ref{105a,,PyType_HasFeature()}, @ref{10dd,,PyType_Check()} and
@ref{10de,,PyType_CheckExact()} macros to static inline functions.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: In the limited C API, @code{PyObject_INIT()} and
@code{PyObject_INIT_VAR()} are now defined as aliases to
@ref{3a0,,PyObject_Init()} and @ref{10df,,PyObject_InitVar()} to make their
implementation opaque. It avoids to leak implementation details in the
limited C API. Exclude the following functions from the limited C API:
@code{_Py_NewReference()}, @code{_Py_ForgetReference()},
@code{_PyTraceMalloc_NewReference()} and @code{_Py_GetRefTotal()}.

@item 
bpo-39542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39542}: Exclude trashcan mechanism from the limited C API: it requires
access to PyTypeObject and PyThreadState structure fields, whereas these
structures are opaque in the limited C API.

@item 
bpo-39511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39511}: The @ref{1096,,PyThreadState_Clear()} function now calls the
@code{PyThreadState.on_delete} callback. Previously, that happened in
@ref{10e0,,PyThreadState_Delete()}.

@item 
bpo-38076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38076}: Fix to clear the interpreter state only after clearing module
globals to guarantee module state access from C Extensions during runtime
destruction

@item 
bpo-39245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39245}: The Vectorcall API (PEP 590) was made public, adding the
functions @code{PyObject_Vectorcall}, @code{PyObject_VectorcallMethod},
@code{PyVectorcall_Function}, @code{PyObject_CallOneArg},
@code{PyObject_CallMethodNoArgs}, @code{PyObject_CallMethodOneArg},
@code{PyObject_FastCallDict}, and the flag @code{Py_TPFLAGS_HAVE_VECTORCALL}.
@end itemize

@node Python 3 9 0 alpha 3,Python 3 9 0 alpha 2,Python 3 9 0 alpha 4,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-3}@anchor{10e1}
@subsection Python 3.9.0 alpha 3


@emph{Release date: 2020-01-24}

@menu
* Core and Builtins: Core and Builtins<27>. 
* Library: Library<29>. 
* Documentation: Documentation<19>. 
* Build: Build<19>. 
* IDLE: IDLE<18>. 
* C API: C API<14>. 

@end menu

@node Core and Builtins<27>,Library<29>,,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id191}@anchor{10e2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39427}: Document all possibilities for the @code{-X} options in the
command line help section. Patch by Pablo Galindo.

@item 
bpo-39421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39421}: Fix possible crashes when operating with the functions in the
@ref{8d,,heapq} module and custom comparison operators.

@item 
bpo-39386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39386}: Prevent double awaiting of async iterator.

@item 
bpo-17005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17005}: Add @code{functools.TopologicalSorter} to the
@ref{83,,functools} module to offers functionality to perform topological
sorting of graphs. Patch by Pablo Galindo, Tim Peters and Larry Hastings.

@item 
bpo-39320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39320}: Replace four complex bytecodes for building sequences with
three simpler ones.

The following four bytecodes have been removed:


@itemize *

@item 
BUILD_LIST_UNPACK

@item 
BUILD_TUPLE_UNPACK

@item 
BUILD_SET_UNPACK

@item 
BUILD_TUPLE_UNPACK_WITH_CALL
@end itemize

The following three bytecodes have been added:


@itemize *

@item 
LIST_TO_TUPLE

@item 
LIST_EXTEND

@item 
SET_UPDATE
@end itemize

@item 
bpo-39336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39336}: Import loaders which publish immutable module objects can now
publish immutable packages in addition to individual modules.

@item 
bpo-39322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39322}: Added a new function @ref{1a9,,gc.is_finalized()} to check if an
object has been finalized by the garbage collector. Patch by Pablo
Galindo.

@item 
bpo-39048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39048}: Improve the displayed error message when incorrect types are
passed to @code{async with} statements by looking up the @ref{10e3,,__aenter__()}
special method before the @ref{10e4,,__aexit__()} special method when entering
an asynchronous context manager. Patch by Géry Ogam.

@item 
bpo-39235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39235}: Fix AST end location for lone generator expression in function
call, e.g. f(i for i in a).

@item 
bpo-39209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39209}: Correctly handle multi-line tokens in interactive mode. Patch
by Pablo Galindo.

@item 
bpo-1635741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1635741}: Port _json extension module to multiphase initialization
(
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}).

@item 
bpo-39216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39216}: Fix constant folding optimization for positional only arguments
- by Anthony Sottile.

@item 
bpo-39215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39215}: Fix @code{SystemError} when nested function has annotation on
positional-only argument - by Anthony Sottile.

@item 
bpo-39200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39200}: Correct the error message when calling the @ref{900,,min()} or
@ref{901,,max()} with no arguments. Patch by Dong-hee Na.

@item 
bpo-39200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39200}: Correct the error message when trying to construct
@ref{1f6,,range} objects with no arguments. Patch by Pablo Galindo.

@item 
bpo-39166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39166}: Fix incorrect line execution reporting in trace functions when
tracing the last iteration of asynchronous for loops. Patch by Pablo
Galindo.

@item 
bpo-39114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39114}: Fix incorrect line execution reporting in trace functions when
tracing exception handlers with name binding. Patch by Pablo Galindo.

@item 
bpo-39156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39156}: Split the COMPARE_OP bytecode instruction into four distinct
instructions.


@itemize *

@item 
COMPARE_OP for rich comparisons

@item 
IS_OP for 'is' and 'is not' tests

@item 
CONTAINS_OP for 'in' and 'is not' tests

@item 
JUMP_IF_NOT_EXC_MATCH for checking exceptions in 'try-except' statements.
@end itemize

This improves the clarity of the interpreter and should provide a modest
speedup.

@item 
bpo-38588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38588}: Fix possible crashes in dict and list when calling
@ref{10e5,,PyObject_RichCompareBool()}.

@item 
bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601}: By default, @code{sys.stderr} is line-buffered now, even if
@code{stderr} is redirected to a file. You can still make @code{sys.stderr}
unbuffered by passing the @ref{10e6,,-u} command-line option or setting the
@geindex PYTHONUNBUFFERED
@geindex 环境变量; PYTHONUNBUFFERED
@ref{10e7,,PYTHONUNBUFFERED} environment variable.

(Contributed by Jendrik Seipp in bpo-13601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13601}.)

@item 
bpo-38610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38610}: Fix possible crashes in several list methods by holding strong
references to list elements when calling
@ref{10e5,,PyObject_RichCompareBool()}.

@item 
bpo-32021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32021}: Include brotli .br encoding in mimetypes encodings_map
@end itemize

@node Library<29>,Documentation<19>,Core and Builtins<27>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id192}@anchor{10e8}
@subsubsection Library



@itemize -

@item 
bpo-39430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39430}: Fixed race condition in lazy imports in @ref{101,,tarfile}.

@item 
bpo-39413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39413}: The @ref{1cd,,os.unsetenv()} function is now also available on
Windows.

@item 
bpo-39390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39390}: Fixed a regression with the @code{ignore} callback of
@ref{34e,,shutil.copytree()}. The argument types are now str and List[str]
again.

@item 
bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395}: The @ref{1ce,,os.putenv()} and @ref{1cd,,os.unsetenv()} functions are now
always available.

@item 
bpo-39406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39406}: If @code{setenv()} C function is available, @ref{1ce,,os.putenv()} is
now implemented with @code{setenv()} instead of @code{putenv()}, so Python
doesn't have to handle the environment variable memory.

@item 
bpo-39396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39396}: Fix @code{math.nextafter(-0.0, +0.0)} on AIX 7.1.

@item 
bpo-29435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29435}: Allow @ref{10e9,,tarfile.is_tarfile()} to be used with file and
file-like objects, like @ref{d8a,,zipfile.is_zipfile()}. Patch by William
Woodruff.

@item 
bpo-39377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39377}: Removed @code{encoding} option from @ref{226,,json.loads()}.  It has
been deprecated since Python 3.1.

@item 
bpo-39389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39389}: Write accurate compression level metadata in @ref{8b,,gzip}
archives, rather than always signaling maximum compression.

@item 
bpo-39366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39366}: The previously deprecated @code{xpath()} and @code{xgtitle()} methods
of @ref{1c7,,nntplib.NNTP} have been removed.

@item 
bpo-39357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39357}: Remove the @emph{buffering} parameter of @ref{225,,bz2.BZ2File}. Since
Python 3.0, it was ignored and using it was emitting
@ref{15a,,DeprecationWarning}. Pass an open file object, to control how the
file is opened. The @emph{compresslevel} parameter becomes keyword-only.

@item 
bpo-39353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39353}: Deprecate binhex4 and hexbin4 standards. Deprecate the
@ref{10,,binhex} module and the following @ref{f,,binascii} functions:
@ref{209,,b2a_hqx()}, @ref{20a,,a2b_hqx()},
@ref{20b,,rlecode_hqx()}, @ref{20c,,rledecode_hqx()},
@ref{10cf,,crc_hqx()}.

@item 
bpo-39351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39351}: Remove @code{base64.encodestring()} and @code{base64.decodestring()},
aliases deprecated since Python 3.1: use @ref{223,,base64.encodebytes()} and
@ref{224,,base64.decodebytes()} instead.

@item 
bpo-39350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39350}: Remove @code{fractions.gcd()} function, deprecated since Python
3.5 (bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}): use @ref{1bf,,math.gcd()} instead.

@item 
bpo-39329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39329}: @ref{1e1,,LMTP} constructor now has an optional
@emph{timeout} parameter. Patch by Dong-hee Na.

@item 
bpo-39313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39313}: Add a new @code{exec_function} option (@emph{--exec-function} in the
CLI) to @code{RefactoringTool} for making @code{exec} a function. Patch by
Batuhan Taskaya.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{1a7,,FTP_TLS} and @ref{1a7,,FTP_TLS} now raise
a @ref{16d,,ValueError} if the given timeout for their constructor is zero
to prevent the creation of a non-blocking socket. Patch by Dong-hee Na.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{1df,,SMTP} and @ref{1e0,,SMTP_SSL} now raise
a @ref{16d,,ValueError} if the given timeout for their constructor is zero
to prevent the creation of a non-blocking socket. Patch by Dong-hee Na.

@item 
bpo-39310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39310}: Add @ref{1c2,,math.ulp()}: return the value of the least significant
bit of a float.

@item 
bpo-39297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39297}: Improved performance of importlib.metadata distribution
discovery and resilients to inaccessible sys.path entries
(importlib_metadata v1.4.0).

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{1c7,,NNTP} and @ref{1c8,,NNTP_SSL} now raise
a @ref{16d,,ValueError} if the given timeout for their constructor is zero
to prevent the creation of a non-blocking socket. Patch by Dong-hee Na.

@item 
bpo-38901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38901}: When you specify prompt='.' or equivalently python -m venv
--prompt . ... the basename of the current directory is used to set the
created venv's prompt when it's activated.

@item 
bpo-39288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39288}: Add @ref{1c1,,math.nextafter()}: return the next floating-point
value after @emph{x} towards @emph{y}.

@item 
bpo-39259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39259}: @ref{1d6,,POP3} and @ref{1d7,,POP3_SSL} now raise a
@ref{16d,,ValueError} if the given timeout for their constructor is zero to
prevent the creation of a non-blocking socket. Patch by Dong-hee Na.

@item 
bpo-39242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39242}: Updated the Gmane domain from news.gmane.org to news.gmane.io
which is used for examples of @ref{1c7,,NNTP} news reader server
and nntplib tests.

@item 
bpo-35292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35292}: Proxy the @code{SimpleHTTPRequestHandler.guess_type} to
@ref{10ea,,mimetypes.guess_type} so the @ref{10eb,,mimetypes.init} is called lazily to avoid
unnecessary costs when @ref{96,,http.server} module is imported.

@item 
bpo-39239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39239}: The @ref{22f,,select.epoll.unregister()} method no longer ignores
the @ref{230,,EBADF} error.

@item 
bpo-38907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38907}: In http.server script, restore binding to IPv4 on Windows.

@item 
bpo-39152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39152}: Fix ttk.Scale.configure([name]) to return configuration tuple
for name or all options.  Giovanni Lombardo contributed part of the patch.

@item 
bpo-39198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39198}: If an exception were to be thrown in @code{Logger.isEnabledFor}
(say, by asyncio timeouts or stopit) , the @ref{aa,,logging} global lock may not
be released appropriately, resulting in deadlock.  This change wraps that
block of code with @code{try...finally} to ensure the lock is released.

@item 
bpo-39191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39191}: Perform a check for running loop before starting a new task in
@code{loop.run_until_complete()} to fail fast; it prevents the side effect of
new task spawning before exception raising.

@item 
bpo-38871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38871}: Correctly parenthesize filter-based statements that contain
lambda expressions in mod:@ref{a7,,lib2to3}. Patch by Dong-hee Na.

@item 
bpo-39142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39142}: A change was made to logging.config.dictConfig to avoid
converting instances of named tuples to ConvertingTuple. It's assumed that
named tuples are too specialised to be treated like ordinary tuples; if a
user of named tuples requires ConvertingTuple functionality, they will
have to implement that themselves in their named tuple class.

@item 
bpo-39158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39158}: ast.literal_eval() now supports empty sets.

@item 
bpo-39129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39129}: Fix import path for @code{asyncio.TimeoutError}

@item 
bpo-39057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39057}: @code{urllib.request.proxy_bypass_environment()} now ignores
leading dots and no longer ignores a trailing newline.

@item 
bpo-39056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39056}: Fixed handling invalid warning category in the -W option.  No
longer import the re module if it is not needed.

@item 
bpo-39055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39055}: @ref{10ec,,base64.b64decode()} with @code{validate=True} raises now a
binascii.Error if the input ends with a single @code{\n}.

@item 
bpo-21600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21600}: Fix @code{mock.patch.stopall()} to stop active patches that were
created with @code{mock.patch.dict()}.

@item 
bpo-39019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39019}: Implement dummy @code{__class_getitem__} for
@ref{b87,,tempfile.SpooledTemporaryFile}.

@item 
bpo-39019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39019}: Implement dummy @code{__class_getitem__} for @code{subprocess.Popen},
@code{subprocess.CompletedProcess}

@item 
bpo-38914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38914}: Adjusted the wording of the warning issued by distutils'
@code{check} command when the @code{author} and @code{maintainer} fields are
supplied but no corresponding e-mail field (@code{author_email} or
@code{maintainer_email}) is found. The wording now reflects the fact that
these fields are suggested, but not required. Patch by Juergen Gmach.

@item 
bpo-38878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38878}: Fixed __subclasshook__ of @ref{5ee,,os.PathLike} to return a
correct result upon inheritance. Patch by Bar Harel.

@item 
bpo-38615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38615}: @ref{1b0,,IMAP4} and @ref{1b1,,IMAP4_SSL} now
have an optional @emph{timeout} parameter for their constructors. Also, the
@ref{1b2,,open()} method now has an optional @emph{timeout} parameter
with this change. The overridden methods of @ref{1b1,,IMAP4_SSL}
and @ref{1b3,,IMAP4_stream} were applied to this change. Patch by
Dong-hee Na.

@item 
bpo-35182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35182}: Fixed @code{Popen.communicate()} subsequent call crash when the
child process has already closed any piped standard stream, but still
continues to be running. Patch by Andriy Maletsky.

@item 
bpo-38630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38630}: On Unix, @ref{10ed,,subprocess.Popen.send_signal()} now polls the
process status. Polling reduces the risk of sending a signal to the wrong
process if the process completed, the @ref{10ee,,subprocess.Popen.returncode}
attribute is still @code{None}, and the pid has been reassigned (recycled) to
a new different process.

@item 
bpo-38536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38536}: Removes trailing space in formatted currency with
@code{international=True} and a locale with symbol following value. E.g.
@code{locale.currency(12.34, international=True)} returned @code{'12,34 EUR '}
instead of @code{'12,34 EUR'}.

@item 
bpo-38473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38473}: Use signature from inner mock for autospecced methods attached
with @code{unittest.mock.attach_mock()}. Patch by Karthikeyan Singaravelan.

@item 
bpo-38361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38361}: Fixed an issue where @code{ident} could include a leading path
separator when @ref{10ef,,syslog.openlog()} was called without arguments.

@item 
bpo-38293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38293}: Add @ref{4da,,copy.copy()} and @ref{4db,,copy.deepcopy()} support to
@ref{30f,,property()} objects.

@item 
bpo-37958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37958}: Added the pstats.Stats.get_profile_dict() method to return the
profile data as a StatsProfile instance.

@item 
bpo-28367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28367}: Termios magic constants for the following baud rates:   -
B500000   - B576000   - B921600   - B1000000   - B1152000   - B1500000   -
B2000000   - B2500000   - B3000000   - B3500000   - B4000000 Patch by
Andrey Smirnov
@end itemize

@node Documentation<19>,Build<19>,Library<29>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id193}@anchor{10f0}
@subsubsection Documentation



@itemize -

@item 
bpo-39381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39381}: Mention in docs that @ref{466,,asyncio.get_event_loop()} implicitly
creates new event loop only if called from the main thread.

@item 
bpo-38918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38918}: Add an entry for @code{__module__} in the "function" & "method"
sections of the inspect docs types and members table@footnote{https://docs.python.org/3/library/inspect.html#types-and-members}

@item 
bpo-3530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3530}: In the @ref{7,,ast} module documentation, fix a misleading
@code{NodeTransformer} example and add advice on when to use the
@code{fix_missing_locations} function.
@end itemize

@node Build<19>,IDLE<18>,Documentation<19>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id194}@anchor{10f1}
@subsubsection Build



@itemize -

@item 
bpo-39395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39395}: On non-Windows platforms, the @code{setenv()} and
@code{unsetenv()} functions are now required to build Python.

@item 
bpo-39160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39160}: Updated the documentation in @code{/configure --help} to show
default values, reference documentation where required and add additional
explanation where needed.

@item 
bpo-39144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39144}: The ctags and etags build targets both include Modules/_ctypes
and Python standard library source files.
@end itemize

@node IDLE<18>,C API<14>,Build<19>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id195}@anchor{10f2}
@subsubsection IDLE



@itemize -

@item 
bpo-39050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39050}: Make IDLE Settings dialog Help button work again.

@item 
bpo-34118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34118}: Tag memoryview, range, and tuple as classes, the same as list,
etcetera, in the library manual built-in functions list.

@item 
bpo-32989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32989}: Add tests for editor newline_and_indent_event method. Remove
dead code from pyparse find_good_parse_start method.
@end itemize

@node C API<14>,,IDLE<18>,Python 3 9 0 alpha 3
@anchor{whatsnew/changelog id196}@anchor{10f3}
@subsubsection C API



@itemize -

@item 
bpo-39372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39372}: Clean header files of interfaces defined but with no
implementation. The public API symbols being removed are:
@code{_PyBytes_InsertThousandsGroupingLocale},
@code{_PyBytes_InsertThousandsGrouping}, @code{_Py_InitializeFromArgs},
@code{_Py_InitializeFromWideArgs}, @code{_PyFloat_Repr}, @code{_PyFloat_Digits},
@code{_PyFloat_DigitsInit}, @code{PyFrame_ExtendStack},
@code{_PyAIterWrapper_Type}, @code{PyNullImporter_Type}, @code{PyCmpWrapper_Type},
@code{PySortWrapper_Type}, @code{PyNoArgsFunction}.

@item 
bpo-39164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39164}: Add a private @code{_PyErr_GetExcInfo()} function to retrieve
exception information of the specified Python thread state.
@end itemize

@node Python 3 9 0 alpha 2,Python 3 9 0 alpha 1,Python 3 9 0 alpha 3,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-2}@anchor{10f4}
@subsection Python 3.9.0 alpha 2


@emph{Release date: 2019-12-18}

@menu
* Security: Security<17>. 
* Core and Builtins: Core and Builtins<28>. 
* Library: Library<30>. 
* Documentation: Documentation<20>. 
* Tests: Tests<21>. 
* Build: Build<20>. 
* Windows: Windows<22>. 
* macOS: macOS<19>. 
* IDLE: IDLE<19>. 
* C API: C API<15>. 

@end menu

@node Security<17>,Core and Builtins<28>,,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id197}@anchor{10f5}
@subsubsection Security



@itemize -

@item 
bpo-38945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38945}: Newline characters have been escaped when performing uu
encoding to prevent them from overflowing into to content section of the
encoded file. This prevents malicious or accidental modification of data
during the decoding process.

@item 
bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228}: Due to significant security concerns, the @emph{reuse_address}
parameter of @ref{189,,asyncio.loop.create_datagram_endpoint()} is no longer
supported. This is because of the behavior of @code{SO_REUSEADDR} in UDP. For
more details, see the documentation for
@code{loop.create_datagram_endpoint()}. (Contributed by Kyle Stanley, Antoine
Pitrou, and Yury Selivanov in bpo-37228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37228}.)

@item 
bpo-38804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38804}: Fixes a ReDoS vulnerability in @ref{94,,http.cookiejar}. Patch by
Ben Caller.
@end itemize

@node Core and Builtins<28>,Library<30>,Security<17>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id198}@anchor{10f6}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-39028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39028}: Slightly improve the speed of keyword argument parsing with
many kwargs by strengthening the assumption that kwargs are interned
strings.

@item 
bpo-39080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39080}: Fix the value of @emph{end_col_offset} for Starred Expression AST
nodes when they are among the elements in the @emph{args} attribute of Call AST
nodes.

@item 
bpo-39031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39031}: When parsing an "elif" node, lineno and col_offset of the node
now point to the "elif" keyword and not to its condition, making it
consistent with the "if" node. Patch by Lysandros Nikolaou.

@item 
bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443}: In Python 3.9.0a1, sys.argv[0] was made an absolute path if a
filename was specified on the command line. Revert this change, since most
users expect sys.argv to be unmodified.

@item 
bpo-39008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39008}: @ref{10b1,,PySys_Audit()} now requires @code{Py_ssize_t} to be used
for size arguments in the format string, regardless of whether
@code{PY_SSIZE_T_CLEAN} was defined at include time.

@item 
bpo-38673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38673}: In REPL mode, don't switch to PS2 if the line starts with
comment or whitespace. Based on work by Batuhan Taşkaya.

@item 
bpo-38922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38922}: Calling @code{replace} on a code object now raises the
@code{code.__new__} audit event.

@item 
bpo-38920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38920}: Add audit hooks for when @ref{1ae,,sys.excepthook()} and
@ref{361,,sys.unraisablehook()} are invoked.

@item 
bpo-38892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38892}: Improve documentation for audit events table and functions.

@item 
bpo-38852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38852}: Set the thread stack size to 8 Mb for debug builds on android
platforms.

@item 
bpo-38858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38858}: Each Python subinterpreter now has its own "small integer
singletons": numbers in [-5; 257] range. It is no longer possible to
change the number of small integers at build time by overriding
@code{NSMALLNEGINTS} and @code{NSMALLPOSINTS} macros: macros should now be
modified manually in @code{pycore_pystate.h} header file.

@item 
bpo-36854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36854}: The garbage collector state becomes per interpreter
(@code{PyInterpreterState.gc}), rather than being global
(@code{_PyRuntimeState.gc}).

@item 
bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835}: The @code{PyFPE_START_PROTECT()} and @code{PyFPE_END_PROTECT()}
macros are empty: they have been doing nothing for the last year, so stop
using them.

@item 
bpo-38328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38328}: Sped up the creation time of constant @ref{1f9,,list} and
@ref{1f7,,set} displays. Patch by Brandt Bucher.

@item 
bpo-38707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38707}: @code{MainThread.native_id} is now correctly reset in child
processes spawned using @ref{4c1,,multiprocessing.Process}, instead of
retaining the parent's value.

@item 
bpo-38629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38629}: Added @code{__floor__} and @code{__ceil__} methods to float object.
Patch by Batuhan Taşkaya.

@item 
bpo-27145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27145}: int + int and int - int operators can now return small integer
singletons. Patch by hongweipeng.

@item 
bpo-38021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38021}: Provide a platform tag for AIX that is sufficient for PEP425
binary distribution identification. Patch by Michael Felt.

@item 
bpo-35409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35409}: Ignore GeneratorExit exceptions when throwing an exception into
the aclose coroutine of an asynchronous generator.

@item 
bpo-33387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33387}: Removed WITH_CLEANUP_START, WITH_CLEANUP_FINISH, BEGIN_FINALLY,
END_FINALLY, CALL_FINALLY and POP_FINALLY bytecodes. Replaced with RERAISE
and WITH_EXCEPT_START bytecodes. The compiler now generates different code
for exceptional and non-exceptional branches for 'with' and 'try-except'
statements. For 'try-finally' statements the 'finally' block is replicated
for each exit from the 'try' body.
@end itemize

@node Library<30>,Documentation<20>,Core and Builtins<28>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id199}@anchor{10f7}
@subsubsection Library



@itemize -

@item 
bpo-39033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39033}: Fix @ref{e48,,NameError} in @ref{14c,,zipimport}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-39022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39022}: Update importlib.metadata to include improvements from
importlib_metadata 1.3 including better serialization of EntryPoints and
improved documentation for custom finders.

@item 
bpo-39006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39006}: Fix asyncio when the ssl module is missing: only check for
ssl.SSLSocket instance if the ssl module is available.

@item 
bpo-38708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38708}: Fix a potential IndexError in email parser when parsing an
empty msg-id.

@item 
bpo-38698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38698}: Add a new @code{InvalidMessageID} token to email parser to
represent invalid Message-ID headers.  Also, add defects when there is
remaining value after parsing the header.

@item 
bpo-38994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38994}: Implement @code{__class_getitem__} for @code{os.PathLike},
@code{pathlib.Path}.

@item 
bpo-38979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38979}: Return class from @code{ContextVar.__class_getitem__} to simplify
subclassing.

@item 
bpo-38978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38978}: Implement @code{__class_getitem__} on asyncio objects (Future,
Task, Queue). Patch by Batuhan Taskaya.

@item 
bpo-38916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38916}: @ref{217,,array.array}: Remove @code{tostring()} and
@code{fromstring()} methods. They were aliases to @code{tobytes()} and
@code{frombytes()}, deprecated since Python 3.2.

@item 
bpo-38986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38986}: Make repr of C accelerated TaskWakeupMethWrapper the same as of
pure Python version.

@item 
bpo-38982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38982}: Fix asyncio @code{PidfdChildWatcher}: handle @code{waitpid()} error.
If @code{waitpid()} is called elsewhere, @code{waitpid()} call fails with
@ref{a82,,ChildProcessError}: use return code 255 in this case, and log a
warning. It ensures that the pidfd file descriptor is closed if this error
occurs.

@item 
bpo-38529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38529}: Drop too noisy asyncio warning about deletion of a stream
without explicit @code{.close()} call.

@item 
bpo-27413@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27413}: Added ability to pass through @code{ensure_ascii} options to
json.dumps in the @code{json.tool} command-line interface.

@item 
bpo-38634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38634}: The @ref{de,,readline} module now detects if Python is linked to
libedit at runtime on all platforms.  Previously, the check was only done
on macOS.

@item 
bpo-33684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33684}: Fix @code{json.tool} failed to read a JSON file with non-ASCII
characters when locale encoding is not UTF-8.

@item 
bpo-38698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38698}: Prevent UnboundLocalError to pop up in parse_message_id.

parse_message_id() was improperly using a token defined inside an
exception handler, which was raising @ref{f3e,,UnboundLocalError} on parsing an
invalid value. Patch by Claudiu Popa.

@item 
bpo-38927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38927}: Use @code{python -m pip} instead of @code{pip} to upgrade
dependencies in venv.

@item 
bpo-26730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26730}: Fix @code{SpooledTemporaryFile.rollover()} might corrupt the file
when it is in text mode. Patch by Serhiy Storchaka.

@item 
bpo-38881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38881}: random.choices() now raises a ValueError when all the weights
are zero.

@item 
bpo-38876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38876}: Raise pickle.UnpicklingError when loading an item from memo for
invalid input.

The previous code was raising a @ref{3f1,,KeyError} for both the Python and C
implementation. This was caused by the specified index of an invalid input
which did not exist in the memo structure, where the pickle stores what
objects it has seen. The malformed input would have caused either a
@code{BINGET} or @code{LONG_BINGET} load from the memo, leading to a @ref{3f1,,KeyError} as
the determined index was bogus. Patch by Claudiu Popa

@item 
bpo-38688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38688}: Calling func:@ref{34e,,shutil.copytree} to copy a directory tree from
one directory to another subdirectory resulted in an endless loop and a
RecursionError. A fix was added to consume an iterator and create the list
of the entries to be copied, avoiding the recursion for newly created
directories. Patch by Bruno P. Kinoshita.

@item 
bpo-38863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38863}: Improve @code{is_cgi()} function in @ref{96,,http.server}, which
enables processing the case that cgi directory is a child of another
directory other than root.

@item 
bpo-37838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37838}: @ref{1f0,,typing.get_type_hints()} properly handles functions
decorated with @ref{95e,,functools.wraps()}.

@item 
bpo-38870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38870}: Expose @ref{186,,ast.unparse()} as a function of the @ref{7,,ast}
module that can be used to unparse an @ref{187,,ast.AST} object and produce
a string with code that would produce an equivalent @ref{187,,ast.AST}
object when parsed. Patch by Pablo Galindo and Batuhan Taskaya.

@item 
bpo-38859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38859}: AsyncMock now returns StopAsyncIteration on the exhaustion of a
side_effects iterable. Since PEP-479 its Impossible to raise a
StopIteration exception from a coroutine.

@item 
bpo-38857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38857}: AsyncMock fix for return values that are awaitable types.  This
also covers side_effect iterable values that happened to be awaitable, and
wraps callables that return an awaitable type. Before these awaitables
were being awaited instead of being returned as is.

@item 
bpo-38834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38834}: @ref{36e,,typing.TypedDict} subclasses now track which keys are
optional using the @code{__required_keys__} and @code{__optional_keys__}
attributes, to enable runtime validation by downstream projects.  Patch by
Zac Hatfield-Dodds.

@item 
bpo-38821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38821}: Fix unhandled exceptions in @ref{5,,argparse} when
internationalizing error messages for arguments with @code{nargs} set to
special (non-integer) values. Patch by Federico Bond.

@item 
bpo-38820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38820}: Make Python compatible with OpenSSL 3.0.0.
@ref{9c0,,ssl.SSLSocket.getpeercert()} no longer returns IPv6 addresses with a
trailing new line.

@item 
bpo-38811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38811}: Fix an unhandled exception in @ref{c8,,pathlib} when
@ref{b1a,,os.link()} is missing. Patch by Toke Høiland-Jørgensen.

@item 
bpo-38686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38686}: Added support for multiple @code{qop} values in
@ref{10b5,,urllib.request.AbstractDigestAuthHandler}.

@item 
bpo-38712@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38712}: Add the Linux-specific @ref{1dd,,signal.pidfd_send_signal()}
function, which allows sending a signal to a process identified by a file
descriptor rather than a pid.

@item 
bpo-38348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38348}: Add @code{-i} and @code{--indent} (indentation level), and
@code{--no-type-comments} (type comments) command line options to ast parsing
tool.

@item 
bpo-37523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37523}: Change @code{zipfile.ZipExtFile} to raise @code{ValueError} when
trying to access the underlying file object after it has been closed. This
new behavior is consistent with how accessing closed files is handled in
other parts of Python.

@item 
bpo-38045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38045}: Improve the performance of @code{enum._decompose()} in
@ref{79,,enum}. Patch by hongweipeng.

@item 
bpo-36820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36820}: Break cycle generated when saving an exception in socket.py,
codeop.py and dyld.py as they keep alive not only the exception but user
objects through the @code{__traceback__} attribute. Patch by Mario Corchero.

@item 
bpo-36406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36406}: Handle namespace packages in @ref{66,,doctest}. Patch by
Karthikeyan Singaravelan.

@item 
bpo-34776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34776}: Fix dataclasses to support forward references in type
annotations

@item 
bpo-20928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20928}: ElementTree supports recursive XInclude processing.  Patch by
Stefan Behnel.

@item 
bpo-29636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29636}: Add whitespace options for formatting JSON with the
@code{json.tool} CLI. The following mutually exclusive options are now
supported: @code{--indent} for setting the indent level in spaces; @code{--tab}
for indenting with tabs; @code{--no-indent} for suppressing newlines; and
@code{--compact} for suppressing all whitespace. The default behavior remains
the same as @code{--indent=4}.
@end itemize

@node Documentation<20>,Tests<21>,Library<30>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id200}@anchor{10f8}
@subsubsection Documentation



@itemize -

@item 
bpo-38928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38928}: Correct when venv's @code{upgrade_dependencies()} and
@code{--upgrade-deps} are added.

@item 
bpo-38899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38899}: Update documentation to state that to activate virtual
environments under fish one should use @code{source}, not @code{} as documented at
@indicateurl{https://fishshell.com/docs/current/commands.html#source}.

@item 
bpo-22377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22377}: Improves documentation of the values that
@ref{fdc,,datetime.datetime.strptime()} accepts for @code{%Z}. Patch by Karl
Dubost.
@end itemize

@node Tests<21>,Build<20>,Documentation<20>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id201}@anchor{10f9}
@subsubsection Tests



@itemize -

@item 
bpo-38546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38546}: Fix test_ressources_gced_in_workers() of
test_concurrent_futures: explicitly stop the manager to prevent leaking a
child process running in the background after the test completes.

@item 
bpo-38546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38546}: Multiprocessing and concurrent.futures tests now stop the
resource tracker process when tests complete.

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Replace hardcoded timeout constants in tests with new
@ref{106,,test.support} constants: @ref{10fa,,LOOPBACK_TIMEOUT},
@ref{10fb,,INTERNET_TIMEOUT},
@ref{fdf,,SHORT_TIMEOUT} and
@ref{10fc,,LONG_TIMEOUT}. It becomes easier to adjust these four
timeout constants for all tests at once, rather than having to adjust
every single test file.

@item 
bpo-38547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38547}: Fix test_pty: if the process is the session leader, closing the
master file descriptor raises a SIGHUP signal: simply ignore SIGHUP when
running the tests.

@item 
bpo-38992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38992}: Fix a test for @ref{e0c,,math.fsum()} that was failing due to
constant folding.

@item 
bpo-38991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38991}: @ref{106,,test.support}:
@code{run_python_until_end()},
@code{assert_python_ok()} and
@code{assert_python_failure()} functions no longer strip
whitespaces from stderr. Remove @code{test.support.strip_python_stderr()}
function.

@item 
bpo-38965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38965}: Fix test_faulthandler on GCC 10. Use the "volatile" keyword in
@code{faulthandler._stack_overflow()} to prevent tail call optimization on
any compiler, rather than relying on compiler specific pragma.

@item 
bpo-38875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38875}: test_capi: trashcan tests now require the test "cpu" resource.

@item 
bpo-38841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38841}: Skip asyncio test_create_datagram_endpoint_existing_sock_unix
on platforms lacking a functional bind() for named unix domain sockets.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Skip the test_posix.test_pidfd_open() test if
@code{os.pidfd_open()} fails with a @ref{700,,PermissionError}. This situation
can happen in a Linux sandbox using a syscall whitelist which doesn't
allow the @code{pidfd_open()} syscall yet.

@item 
bpo-38839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38839}: Fix some unused functions in tests. Patch by Adam Johnson.

@item 
bpo-38669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38669}: Raise @ref{1ff,,TypeError} when passing target as a string with
@ref{10fd,,unittest.mock.patch.object()}.

@item 
bpo-37957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37957}: test.regrtest now can receive a list of test patterns to ignore
(using the -i/--ignore argument) or a file with a list of patterns to
ignore (using the --ignore-file argument). Patch by Pablo Galindo.
@end itemize

@node Build<20>,Windows<22>,Tests<21>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id202}@anchor{10fe}
@subsubsection Build



@itemize -

@item 
bpo-37404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37404}: @ref{9,,asyncio} now raises @code{TyperError} when calling
incompatible methods with an @ref{192,,ssl.SSLSocket} socket.  Patch by Ido
Michael.

@item 
bpo-36500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36500}: Added an optional "regen" project to the Visual Studio solution
that will regenerate all grammar, tokens, and opcodes.
@end itemize

@node Windows<22>,macOS<19>,Build<20>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id203}@anchor{10ff}
@subsubsection Windows



@itemize -

@item 
bpo-39007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=39007}: Add auditing events to functions in @ref{133,,winreg}.

@item 
bpo-33125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33125}: Add support for building and releasing Windows ARM64 packages.
@end itemize

@node macOS<19>,IDLE<19>,Windows<22>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id204}@anchor{1100}
@subsubsection macOS



@itemize -

@item 
bpo-37931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37931}: Fixed a crash on OSX dynamic builds that occurred when
re-initializing the posix module after a Py_Finalize if the environment
had changed since the previous @code{import posix}. Patch by Benoît Hudson.
@end itemize

@node IDLE<19>,C API<15>,macOS<19>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id205}@anchor{1101}
@subsubsection IDLE



@itemize -

@item 
bpo-38944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38944}: Escape key now closes IDLE completion windows.  Patch by Johnny
Najera.

@item 
bpo-38943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38943}: Fix IDLE autocomplete windows not always appearing on some
systems. Patch by Johnny Najera.

@item 
bpo-38862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38862}: 'Strip Trailing Whitespace' on the Format menu removes extra
newlines at the end of non-shell files.

@item 
bpo-38636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38636}: Fix IDLE Format menu tab toggle and file indent width. These
functions (default shortcuts Alt-T and Alt-U) were mistakenly disabled in
3.7.5 and 3.8.0.
@end itemize

@node C API<15>,,IDLE<19>,Python 3 9 0 alpha 2
@anchor{whatsnew/changelog id206}@anchor{1102}
@subsubsection C API



@itemize -

@item 
bpo-38896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38896}: Remove @code{PyUnicode_ClearFreeList()} function: the Unicode free
list has been removed in Python 3.3.

@item 
bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340}: Remove @code{PyMethod_ClearFreeList()} and
@code{PyCFunction_ClearFreeList()} functions: the free lists of bound method
objects have been removed.

@item 
bpo-38835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38835}: Exclude @code{PyFPE_START_PROTECT()} and @code{PyFPE_END_PROTECT()}
macros of @code{pyfpe.h} from @code{Py_LIMITED_API} (stable API).
@end itemize

@node Python 3 9 0 alpha 1,Python 3 8 0 beta 1,Python 3 9 0 alpha 2,更新日志
@anchor{whatsnew/changelog python-3-9-0-alpha-1}@anchor{1103}
@subsection Python 3.9.0 alpha 1


@emph{Release date: 2019-11-19}

@menu
* Security: Security<18>. 
* Core and Builtins: Core and Builtins<29>. 
* Library: Library<31>. 
* Documentation: Documentation<21>. 
* Tests: Tests<22>. 
* Build: Build<21>. 
* Windows: Windows<23>. 
* macOS: macOS<20>. 
* IDLE: IDLE<20>. 
* Tools/Demos: Tools/Demos<8>. 
* C API: C API<16>. 

@end menu

@node Security<18>,Core and Builtins<29>,,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id207}@anchor{1104}
@subsubsection Security



@itemize -

@item 
bpo-38722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38722}: @ref{e2,,runpy} now uses @ref{f59,,io.open_code()} to open code files.
Patch by Jason Killen.

@item 
bpo-38622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38622}: Add additional audit events for the @ref{2a,,ctypes} module.

@item 
bpo-38418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38418}: Fixes audit event for @ref{e8e,,os.system()} to be named
@code{os.system}.

@item 
bpo-38243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38243}: Escape the server title of
@ref{1105,,xmlrpc.server.DocXMLRPCServer} when rendering the document page as
HTML. (Contributed by Dong-hee Na in bpo-38243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38243}.)

@item 
bpo-38174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38174}: Update vendorized expat library version to 2.2.8, which
resolves CVE-2019-15903.

@item 
bpo-37764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37764}: Fixes email._header_value_parser.get_unstructured going into an
infinite loop for a specific case in which the email header does not have
trailing whitespace, and the case in which it contains an invalid encoded
word. Patch by Ashwin Ramaswami.

@item 
bpo-37461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37461}: Fix an infinite loop when parsing specially crafted email
headers. Patch by Abhilash Raj.

@item 
bpo-37363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37363}: Adds audit events for the range of supported run commands (see
@ref{1106,,命令行与环境}).

@item 
bpo-37463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37463}: ssl.match_hostname() no longer accepts IPv4 addresses with
additional text after the address and only quad-dotted notation without
trailing whitespaces. Some inet_aton() implementations ignore whitespace
and all data after whitespace, e.g. '127.0.0.1 whatever'.

@item 
bpo-37363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37363}: Adds audit events for @ref{78,,ensurepip}, @ref{82,,ftplib},
@ref{88,,glob}, @ref{97,,imaplib}, @ref{c0,,nntplib}, @ref{c9,,pdb}, @ref{d0,,poplib},
@ref{e9,,shutil}, @ref{ed,,smtplib}, @ref{f2,,sqlite3}, @ref{f9,,subprocess},
@ref{102,,telnetlib}, @ref{103,,tempfile} and @ref{132,,webbrowser}, as well as
@ref{b25,,os.listdir()}, @ref{390,,os.scandir()} and @ref{414,,breakpoint()}.

@item 
bpo-37364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37364}: @ref{f59,,io.open_code()} is now used when reading @code{.pth}
files.

@item 
bpo-34631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34631}: Updated OpenSSL to 1.1.1c in Windows installer

@item 
bpo-34155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34155}: Fix parsing of invalid email addresses with more than one @code{@@}
(e.g. a@@b@@c.com.) to not return the part before 2nd @code{@@} as valid email
address. Patch by maxking & jpic.
@end itemize

@node Core and Builtins<29>,Library<31>,Security<18>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id208}@anchor{1107}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-38631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38631}: Replace @code{Py_FatalError()} call with a regular
@ref{3e4,,RuntimeError} exception in @code{float.__getformat__()}.

@item 
bpo-38639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38639}: Optimized @ref{dfa,,math.floor()}, @ref{dfb,,math.ceil()} and
@ref{dfc,,math.trunc()} for floats.

@item 
bpo-38640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38640}: Fixed a bug in the compiler that was causing to raise in the
presence of break statements and continue statements inside always false
while loops. Patch by Pablo Galindo.

@item 
bpo-38613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38613}: Optimized some set operations (e.g. @code{|}, @code{^}, and @code{-}) of
@code{dict_keys}. @code{d.keys() | other} was slower than @code{set(d) | other} but
they are almost same performance for now.

@item 
bpo-28029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28029}: @code{"".replace("", s, n)} now returns @code{s} instead of an empty
string for all non-zero @code{n}.  There are similar changes for
@ref{172,,bytes} and @ref{173,,bytearray} objects.

@item 
bpo-38535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38535}: Fixed line numbers and column offsets for AST nodes for calls
without arguments in decorators.

@item 
bpo-38525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38525}: Fix a segmentation fault when using reverse iterators of empty
@code{dict} objects. Patch by Dong-hee Na and Inada Naoki.

@item 
bpo-38465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38465}: @ref{173,,bytearray}, @ref{217,,array} and
@ref{323,,mmap} objects allow now to export more than @code{2**31}
buffers at a time.

@item 
bpo-38469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38469}: Fixed a bug where the scope of named expressions was not being
resolved correctly in the presence of the @emph{global} keyword. Patch by Pablo
Galindo.

@item 
bpo-38437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38437}: Activate the @code{GC_DEBUG} macro for debug builds of the
interpreter (when @code{Py_DEBUG} is set). Patch by Pablo Galindo.

@item 
bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379}: When the garbage collector makes a collection in which some
objects resurrect (they are reachable from outside the isolated cycles
after the finalizers have been executed), do not block the collection of
all objects that are still unreachable. Patch by Pablo Galindo and Tim
Peters.

@item 
bpo-38379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38379}: When cyclic garbage collection (gc) runs finalizers that
resurrect unreachable objects, the current gc run ends, without collecting
any cyclic trash.  However, the statistics reported by @code{collect()} and
@code{get_stats()} claimed that all cyclic trash found was collected, and
that the resurrected objects were collected.   Changed the stats to report
that none were collected.

@item 
bpo-38392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38392}: In debug mode, @ref{f0e,,PyObject_GC_Track()} now calls
@code{tp_traverse()} of the object type to ensure that the object is valid:
test that objects visited by @code{tp_traverse()} are valid.

@item 
bpo-38210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38210}: Remove unnecessary intersection and update set operation in
dictview with empty set. (Contributed by Dong-hee Na in bpo-38210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38210}.)

@item 
bpo-38402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38402}: Check the error from the system's underlying @code{crypt} or
@code{crypt_r}.

@item 
bpo-37474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37474}: On FreeBSD, Python no longer calls @code{fedisableexcept()} at
startup to control the floating point control mode. The call became
useless since FreeBSD 6: it became the default mode.

@item 
bpo-38006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38006}: Fix a bug due to the interaction of weakrefs and the cyclic
garbage collector. We must clear any weakrefs in garbage in order to
prevent their callbacks from executing and causing a crash.

@item 
bpo-38317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38317}: Fix warnings options priority: @code{PyConfig.warnoptions} has the
highest priority, as stated in the 
@geindex Python 提高建议; PEP 587
PEP 587@footnote{https://www.python.org/dev/peps/pep-0587}.

@item 
bpo-38310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38310}: Predict @code{BUILD_MAP_UNPACK_WITH_CALL} -> @code{CALL_FUNCTION_EX}
opcode pairs in the main interpreter loop. Patch by Brandt Bucher.

@item 
bpo-36871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36871}: Improve error handling for the assert_has_calls and
assert_has_awaits methods of mocks. Fixed a bug where any errors
encountered while binding the expected calls to the mock's spec were
silently swallowed, leading to misleading error output.

@item 
bpo-11410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11410}: Better control over symbol visibility is provided through use
of the visibility attributes available in gcc >= 4.0, provided in a
uniform way across POSIX and Windows. The POSIX build files have been
updated to compile with -fvisibility=hidden, minimising exported symbols.

@item 
bpo-38219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38219}: Optimized the @ref{164,,dict} constructor and the
@ref{e96,,update()} method for the case when the argument is a dict.

@item 
bpo-38236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38236}: Python now dumps path configuration if it fails to import the
Python codecs of the filesystem and stdio encodings.

@item 
bpo-38013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38013}: Allow to call @code{async_generator_athrow().throw(...)} even for
non-started async generator helper. It fixes annoying warning at the end
of @ref{18d,,asyncio.run()} call.

@item 
bpo-38124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38124}: Fix an off-by-one error in PyState_AddModule that could cause
out-of-bounds memory access.

@item 
bpo-38116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38116}: The select module is now PEP-384 compliant and no longer has
static state

@item 
bpo-38113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38113}: ast module updated to PEP-384 and all statics removed

@item 
bpo-38076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38076}: The struct module is now PEP-384 compatible

@item 
bpo-38075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38075}: The random module is now PEP-384 compatible

@item 
bpo-38074@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38074}: zlib module made PEP-384 compatible

@item 
bpo-38073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38073}: Make pwd extension module PEP-384 compatible

@item 
bpo-38072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38072}: grp module made PEP-384 compatible

@item 
bpo-38069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38069}: Make _posixsubprocess PEP-384 compatible

@item 
bpo-38071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38071}: Make termios extension module PEP-384 compatible

@item 
bpo-38005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38005}: Fixed comparing and creating of InterpreterID and ChannelID.

@item 
bpo-36946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36946}: Fix possible signed integer overflow when handling slices.
Patch by hongweipeng.

@item 
bpo-37994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37994}: Fixed silencing arbitrary errors if an attribute lookup fails
in several sites. Only AttributeError should be silenced.

@item 
bpo-8425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8425}: Optimize set difference_update for the case when the other set
is much larger than the base set.  (Suggested by Evgeny Kapun with code
contributed by Michele Orrù).

@item 
bpo-37966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37966}: The implementation of @ref{377,,is_normalized()} has
been greatly sped up on strings that aren't normalized, by implementing
the full normalization-quick-check algorithm from the Unicode standard.

@item 
bpo-37947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37947}: Adjust correctly the recursion level in the symtable generation
for named expressions. Patch by Pablo Galindo.

@item 
bpo-37812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37812}: The @code{CHECK_SMALL_INT} macro used inside
@code{Object/longobject.c} has been replaced with an explicit @code{return}
at each call site.

@item 
bpo-37751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37751}: Fix @ref{239,,codecs.lookup()} to normalize the encoding name the
same way than @code{encodings.normalize_encoding()}, except that
@ref{239,,codecs.lookup()} also converts the name to lower case.

@item 
bpo-37830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37830}: Fixed compilation of @ref{403,,break} and @ref{2c2,,continue}
in the @ref{2c3,,finally} block when the corresponding @ref{e3f,,try}
block contains @ref{2cf,,return} with a non-constant value.

@item 
bpo-20490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20490}: Improve import error message for partially initialized module
on circular @code{from} imports - by Anthony Sottile.

@item 
bpo-37840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37840}: Fix handling of negative indices in
@ref{1108,,sq_item} of @ref{173,,bytearray}. Patch by
Sergey Fedoseev.

@item 
bpo-37802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37802}: Slightly improve performance of
@ref{1109,,PyLong_FromUnsignedLong()}, @ref{110a,,PyLong_FromUnsignedLongLong()}
and @ref{110b,,PyLong_FromSize_t()}. Patch by Sergey Fedoseev.

@item 
bpo-37409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37409}: Ensure explicit relative imports from interactive sessions and
scripts (having no parent package) always raise ImportError, rather than
treating the current module as the package. Patch by Ben Lewis.

@item 
bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: Reverted bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: emitting @ref{2d0,,SyntaxWarning} instead
of @ref{15a,,DeprecationWarning} for invalid escape sequences in string and
bytes literals.

@item 
bpo-37757@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37757}: 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572}: As described in the PEP, assignment expressions now
raise @ref{562,,SyntaxError} when their interaction with comprehension scoping
results in an ambiguous target scope.

The @code{TargetScopeError} subclass originally proposed by the PEP has been
removed in favour of just raising regular syntax errors for the disallowed
cases.

@item 
bpo-36279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36279}: Fix potential use of uninitialized memory in @ref{766,,os.wait3()}.

@item 
bpo-36311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36311}: Decoding bytes objects larger than 2GiB is faster and no longer
fails when a multibyte characters spans a chunk boundary.

@item 
bpo-34880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34880}: The @ref{240,,assert} statement now works properly if the
@ref{241,,AssertionError} exception is being shadowed. Patch by Zackery Spytz.

@item 
bpo-37340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37340}: Removed object cache (@code{free_list}) for bound method objects.
Temporary bound method objects are less used than before thanks to the
@code{LOAD_METHOD} opcode and the @code{_PyObject_VectorcallMethod} C API.

@item 
bpo-37648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37648}: Fixed minor inconsistency in @code{list.__contains__()},
@code{tuple.__contains__()} and a few other places. The collection's item
is now always at the left and the needle is on the right of @code{==}.

@item 
bpo-37444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37444}: Update differing exception between @code{builtins.__import__()}
and @ref{a97,,importlib.__import__()}.

@item 
bpo-37619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37619}: When adding a wrapper descriptor from one class to a different
class (for example, setting @code{__add__ = str.__add__} on an @code{int}
subclass), an exception is correctly raised when the operator is called.

@item 
bpo-37593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37593}: Swap the positions of the @emph{posonlyargs} and @emph{args} parameters
in the constructor of @code{ast.parameters} nodes.

@item 
bpo-37543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37543}: Optimized pymalloc for non PGO build.

@item 
bpo-37537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37537}: Compute allocated pymalloc blocks inside
_Py_GetAllocatedBlocks().  This slows down _Py_GetAllocatedBlocks() but
gives a small speedup to _PyObject_Malloc() and _PyObject_Free().

@item 
bpo-37467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37467}: Fix @ref{1ae,,sys.excepthook()} and @code{PyErr_Display()} if a
filename is a bytes string. For example, for a SyntaxError exception where
the filename attribute is a bytes string.

@item 
bpo-37433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37433}: Fix @code{SyntaxError} indicator printing too many spaces for
multi-line strings - by Anthony Sottile.

@item 
bpo-37417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37417}: @code{bytearray.extend()} now correctly handles errors that
arise during iteration. Patch by Brandt Bucher.

@item 
bpo-37414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37414}: The undocumented @code{sys.callstats()} function has been removed.
Since Python 3.7, it was deprecated and always returned @code{None}. It
required a special build option @code{CALL_PROFILE} which was already removed
in Python 3.7.

@item 
bpo-37392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37392}: Remove @code{sys.getcheckinterval()} and
@code{sys.setcheckinterval()} functions. They were deprecated since Python
3.2. Use @ref{218,,sys.getswitchinterval()} and @ref{219,,sys.setswitchinterval()}
instead. Remove also @code{check_interval} field of the
@code{PyInterpreterState} structure.

@item 
bpo-37388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37388}: In development mode and in debug build, @emph{encoding} and @emph{errors}
arguments are now checked on string encoding and decoding operations.
Examples: @ref{16f,,open()}, @ref{170,,str.encode()} and @ref{171,,bytes.decode()}.

By default, for best performances, the @emph{errors} argument is only checked
at the first encoding/decoding error, and the @emph{encoding} argument is
sometimes ignored for empty strings.

@item 
bpo-37348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37348}: Optimized decoding short ASCII string with UTF-8 and ascii
codecs. @code{b"foo".decode()} is about 15% faster.  Patch by Inada Naoki.

@item 
bpo-24214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24214}: Improved support of the surrogatepass error handler in the
UTF-8 and UTF-16 incremental decoders.

@item 
bpo-37330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37330}: @ref{16f,,open()}, @ref{757,,io.open()}, @ref{110c,,codecs.open()} and
@ref{3ac,,fileinput.FileInput} no longer accept @code{'U'} ("universal
newline") in the file mode. This flag was deprecated since Python 3.3.

@item 
bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224}: Reverse evaluation order of key: value in dict comprehensions
as proposed in PEP 572. I.e. in @code{@{k: v for ...@}}, @code{k} will be
evaluated before @code{v}.

@item 
bpo-37316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37316}: Fix the @ref{10b1,,PySys_Audit()} call in @ref{323,,mmap.mmap}.

@item 
bpo-37300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37300}: Remove an unnecessary Py_XINCREF in classobject.c.

@item 
bpo-37269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37269}: Fix a bug in the peephole optimizer that was not treating
correctly constant conditions with binary operators. Patch by Pablo
Galindo.

@item 
bpo-20443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20443}: Python now gets the absolute path of the script filename
specified on the command line (ex: "python3 script.py"): the __file__
attribute of the __main__ module and sys.path[0] become an absolute path,
rather than a relative path.

@item 
bpo-37257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37257}: Python's small object allocator (@code{obmalloc.c}) now allows (no
more than) one empty arena to remain available for immediate reuse,
without returning it to the OS.  This prevents thrashing in simple loops
where an arena could be created and destroyed anew on each iteration.

@item 
bpo-37231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37231}: The dispatching of type slots to special methods (for example
calling @code{__mul__} when doing @code{x * y}) has been made faster.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: Implemented separate vectorcall functions for every calling
convention of builtin functions and methods. This improves performance for
calls.

@item 
bpo-37213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37213}: Handle correctly negative line offsets in the peephole
optimizer. Patch by Pablo Galindo.

@item 
bpo-37219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37219}: Remove erroneous optimization for empty set differences.

@item 
bpo-15913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15913}: Implement @ref{110d,,PyBuffer_SizeFromFormat()} function
(previously documented but not implemented): call @ref{110e,,struct.calcsize()}.
Patch by Joannah Nanjekye.

@item 
bpo-36922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36922}: Slot functions optimize any callable with
@code{Py_TPFLAGS_METHOD_DESCRIPTOR} instead of only instances of
@code{function}.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: The slot @code{tp_vectorcall_offset} is inherited unconditionally
to support @code{super().__call__()} when the base class uses vectorcall.

@item 
bpo-37160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37160}: @ref{367,,threading.get_native_id()} now also supports NetBSD.

@item 
bpo-37077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37077}: Add @ref{367,,threading.get_native_id()} support for AIX. Patch by
M. Felt

@item 
bpo-36781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36781}: @ref{31d,,sum()} has been optimized for boolean values.

@item 
bpo-34556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34556}: Add @code{--upgrade-deps} to venv module. Patch by Cooper Ry Lees

@item 
bpo-20523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20523}: @code{pdb.Pdb} supports ~/.pdbrc in Windows 7. Patch by Tim Hopper
and Dan Lidral-Porter.

@item 
bpo-35551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35551}: Updated encodings: - Removed the "tis260" encoding, which was
an alias for the nonexistent "tactis" codec. - Added "mac_centeuro" as an
alias for the mac_latin2 encoding.

@item 
bpo-19072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19072}: The @ref{310,,classmethod} decorator can now wrap other
descriptors such as property objects.  Adapted from a patch written by
Graham Dumpleton.

@item 
bpo-27575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27575}: Improve speed of dictview intersection by directly using set
intersection logic. Patch by David Su.

@item 
bpo-30773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30773}: Prohibit parallel running of aclose() / asend() / athrow(). Fix
ag_running to reflect the actual running status of the AG.
@end itemize

@node Library<31>,Documentation<21>,Core and Builtins<29>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id209}@anchor{110f}
@subsubsection Library



@itemize -

@item 
bpo-36589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36589}: The @ref{7c3,,curses.update_lines_cols()} function now returns
@code{None} instead of @code{1} on success.

@item 
bpo-38807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38807}: Update @ref{1ff,,TypeError} messages for @ref{1110,,os.path.join()} to
include @ref{5ee,,os.PathLike} objects as acceptable input types.

@item 
bpo-38724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38724}: Add a repr for @code{subprocess.Popen} objects. Patch by Andrey
Doroschenko.

@item 
bpo-38786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38786}: pydoc now recognizes and parses HTTPS URLs. Patch by python273.

@item 
bpo-38785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38785}: Prevent asyncio from crashing if parent @code{__init__} is not
called from a constructor of object derived from @code{asyncio.Future}.

@item 
bpo-38723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38723}: @ref{c9,,pdb} now uses @ref{f59,,io.open_code()} to trigger auditing
events.

@item 
bpo-27805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27805}: Allow opening pipes and other non-seekable files in append mode
with @ref{16f,,open()}.

@item 
bpo-38438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38438}: Simplify the @ref{5,,argparse} usage message for @code{nargs="*"}.

@item 
bpo-38761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38761}: WeakSet is now registered as a collections.abc.MutableSet.

@item 
bpo-38716@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38716}: logging: change RotatingHandler namer and rotator to
class-level attributes. This stops __init__ from setting them to None in
the case where a subclass defines them with eponymous methods.

@item 
bpo-38713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38713}: Add @ref{1cc,,os.P_PIDFD} constant, which may be passed to
@ref{769,,os.waitid()} to wait on a Linux process file descriptor.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Add @ref{18e,,asyncio.PidfdChildWatcher}, a Linux-specific child
watcher implementation that polls process file descriptors.

@item 
bpo-38692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38692}: Expose the Linux @code{pidfd_open} syscall as
@ref{158,,os.pidfd_open()}.

@item 
bpo-38602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38602}: Added constants @code{F_OFD_GETLK},
@code{F_OFD_SETLK} and @code{F_OFD_SETLKW} to the
@ref{7c,,fcntl} module. Patch by Dong-hee Na.

@item 
bpo-38334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38334}: Fixed seeking backward on an encrypted
@code{zipfile.ZipExtFile}.

@item 
bpo-38312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38312}: Add @ref{198,,curses.get_escdelay()}, @ref{199,,curses.set_escdelay()},
@ref{19a,,curses.get_tabsize()}, and @ref{19b,,curses.set_tabsize()} functions - by
Anthony Sottile.

@item 
bpo-38586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38586}: Now @ref{4b8,,fileConfig()} correctly sets the .name
of handlers loaded.

@item 
bpo-38565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38565}: Add new cache_parameters() method for functools.lru_cache() to
better support pickling.

@item 
bpo-34679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34679}: asynci.ProactorEventLoop.close() now only calls
signal.set_wakeup_fd() in the main thread.

@item 
bpo-31202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31202}: The case the result of @code{pathlib.WindowsPath.glob()} matches
now the case of the pattern for literal parts.

@item 
bpo-36321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36321}: Remove misspelled attribute.  The 3.8 changelog noted that this
would be removed in 3.9.

@item 
bpo-38521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38521}: Fixed erroneous equality comparison in statistics.NormalDist().

@item 
bpo-38493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38493}: Added @ref{1ca,,CLD_KILLED} and @ref{1cb,,CLD_STOPPED} for
@code{si_code}. Patch by Dong-hee Na.

@item 
bpo-38478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38478}: Fixed a bug in @code{inspect.signature.bind()} that was causing
it to fail when handling a keyword argument with same name as
positional-only parameter. Patch by Pablo Galindo.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Fixed @ref{3f5,,hmac.new} and @code{hmac.HMAC} to raise TypeError instead of
ValueError when the digestmod parameter, now required in 3.8, is omitted.
Also clarified the hmac module documentation and docstrings.

@item 
bpo-38378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38378}: Parameters @emph{out} and @emph{in} of @ref{46a,,os.sendfile()} was renamed to
@emph{out_fd} and @emph{in_fd}.

@item 
bpo-38417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38417}: Added support for setting the umask in the child process to the
subprocess module on POSIX systems.

@item 
bpo-38449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38449}: Revert PR 15522, which introduces a regression in
@ref{10ea,,mimetypes.guess_type()} due to improper handling of filenames as
urls.

@item 
bpo-38431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38431}: Fix @code{__repr__} method for @code{dataclasses.InitVar} to
support typing objects, patch by Samuel Colvin.

@item 
bpo-38109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38109}: Add missing @ref{9c3,,stat.S_IFDOOR}, @ref{9c4,,stat.S_IFPORT},
@ref{9c5,,stat.S_IFWHT}, @ref{1111,,stat.S_ISDOOR()}, @ref{1112,,stat.S_ISPORT()}, and
@ref{1113,,stat.S_ISWHT()} values to the Python implementation of @ref{f4,,stat}.

@item 
bpo-38422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38422}: Clarify docstrings of pathlib suffix(es)

@item 
bpo-38405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38405}: Nested subclasses of @ref{228,,typing.NamedTuple} are now
pickleable.

@item 
bpo-38332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38332}: Prevent @ref{3f1,,KeyError} thrown by @code{_encoded_words.decode()}
when given an encoded-word with invalid content-type encoding from
propagating all the way to @code{email.message.get()}.

@item 
bpo-38371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38371}: Deprecated the @code{split()} method in
@code{_tkinter.TkappType} in favour of the @code{splitlist()} method which
has more consistent and predicable behavior.

@item 
bpo-38341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38341}: Add @ref{1114,,smtplib.SMTPNotSupportedError} to the @ref{ed,,smtplib}
exported names.

@item 
bpo-38319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38319}: sendfile() used in socket and shutil modules was raising
OverflowError for files >= 2GiB on 32-bit architectures.  (patch by
Giampaolo Rodola)

@item 
bpo-38242@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38242}: Revert the new asyncio Streams API

@item 
bpo-13153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13153}: OS native encoding is now used for converting between Python
strings and Tcl objects.  This allows to display, copy and paste to
clipboard emoji and other non-BMP characters.  Converting strings from Tcl
to Python and back now never fails (except MemoryError).

@item 
bpo-38019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38019}: Correctly handle pause/resume reading of closed asyncio unix
pipe.

@item 
bpo-38163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38163}: Child mocks will now detect their type as either synchronous or
asynchronous, asynchronous child mocks will be AsyncMocks and synchronous
child mocks will be either MagicMock or Mock (depending on their parent
type).

@item 
bpo-38161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38161}: Removes _AwaitEvent from AsyncMock.

@item 
bpo-38216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38216}: Allow the rare code that wants to send invalid http requests
from the @ref{93,,http.client} library a way to do so.  The fixes for bpo-30458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30458}
led to breakage for some projects that were relying on this ability to
test their own behavior in the face of bad requests.

@item 
bpo-28286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28286}: Deprecate opening @ref{207,,GzipFile} for writing
implicitly.  Always specify the @emph{mode} argument for writing.

@item 
bpo-38108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38108}: Any synchronous magic methods on an AsyncMock now return a
MagicMock. Any asynchronous magic methods on a MagicMock now return an
AsyncMock.

@item 
bpo-38265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38265}: Update the @emph{length} parameter of @ref{4c8,,os.pread()} to accept
@ref{391,,Py_ssize_t} instead of @code{int}.

@item 
bpo-38112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38112}: @ref{20,,compileall} has a higher default recursion limit and new
command-line arguments for path manipulation, symlinks handling, and
multiple optimization levels.

@item 
bpo-38248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38248}: asyncio: Fix inconsistent immediate Task cancellation

@item 
bpo-38237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38237}: The arguments for the builtin pow function are more
descriptive. They can now also be passed in as keywords.

@item 
bpo-34002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34002}: Improve efficiency in parts of email package by changing
while-pop to a for loop, using isdisjoint instead of set intersections.

@item 
bpo-38191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38191}: Constructors of @ref{228,,NamedTuple} and
@ref{36e,,TypedDict} types now accept arbitrary keyword argument
names, including "cls", "self", "typename", "_typename", "fields" and
"_fields".

@item 
bpo-38155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38155}: Add @code{__all__} to  @ref{30,,datetime}. Patch by Tahia Khan.

@item 
bpo-38185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38185}: Fixed case-insensitive string comparison in
@ref{857,,sqlite3.Row} indexing.

@item 
bpo-38136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38136}: Changes AsyncMock call count and await count to be two
different counters. Now await count only counts when a coroutine has been
awaited, not when it has been called, and vice-versa. Update the
documentation around this.

@item 
bpo-37828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37828}: Fix default mock name in
@ref{6a9,,unittest.mock.Mock.assert_called()} exceptions. Patch by Abraham
Toriz Cruz.

@item 
bpo-38175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38175}: Fix a memory leak in comparison of @ref{857,,sqlite3.Row}
objects.

@item 
bpo-33936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33936}: _hashlib no longer calls obsolete OpenSSL initialization
function with OpenSSL 1.1.0+.

@item 
bpo-34706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34706}: Preserve subclassing in inspect.Signature.from_callable.

@item 
bpo-38153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38153}: Names of hashing algorithms from OpenSSL are now normalized to
follow Python's naming conventions. For example OpenSSL uses sha3-512
instead of sha3_512 or blake2b512 instead of blake2b.

@item 
bpo-38115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38115}: Fix a bug in dis.findlinestarts() where it would return invalid
bytecode offsets. Document that a code object's co_lnotab can contain
invalid bytecode offsets.

@item 
bpo-38148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38148}: Add slots to @ref{9,,asyncio} transport classes, which can reduce
memory usage.

@item 
bpo-38142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38142}: The _hashlib OpenSSL wrapper extension module is now PEP-384
compliant.

@item 
bpo-9216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9216}: hashlib constructors now support usedforsecurity flag to signal
that a hashing algorithm is not used in a security context.

@item 
bpo-36991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36991}: Fixes a potential incorrect AttributeError exception escaping
ZipFile.extract() in some unsupported input error situations.

@item 
bpo-38134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38134}: Remove obsolete copy of PBKDF2_HMAC_fast. All supported OpenSSL
versions contain a fast implementation.

@item 
bpo-38132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38132}: The OpenSSL hashlib wrapper uses a simpler implementation.
Several Macros and pointless caches are gone. The hash name now comes from
OpenSSL's EVP. The algorithm name stays the same, except it is now always
lower case.

@item 
bpo-38008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38008}: Fix parent class check in protocols to correctly identify the
module that provides a builtin protocol, instead of assuming they all come
from the @ref{1e,,collections.abc} module

@item 
bpo-34037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34037}: For @ref{9,,asyncio}, add a new coroutine
@code{loop.shutdown_default_executor()}. The new coroutine provides an API
to schedule an executor shutdown that waits on the threadpool to finish
closing. Also, @ref{18d,,asyncio.run()} has been updated to utilize the new
coroutine. Patch by Kyle Stanley.

@item 
bpo-37405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37405}: Fixed regression bug for socket.getsockname() for non-CAN_ISOTP
AF_CAN address family sockets by returning a 1-tuple instead of string.

@item 
bpo-38121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38121}: Update parameter names on functions in importlib.metadata
matching the changes in the 0.22 release of importlib_metadata.

@item 
bpo-38110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38110}: The os.closewalk() implementation now uses the libc fdwalk()
API on platforms where it is available.

@item 
bpo-38093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38093}: Fixes AsyncMock so it doesn't crash when used with
AsyncContextManagers or AsyncIterators.

@item 
bpo-37488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37488}: Add warning to @code{datetime.utctimetuple()},
@code{datetime.utcnow()} and @code{datetime.utcfromtimestamp()} .

@item 
bpo-35640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35640}: Allow passing a @ref{47b,,path-like object} as @code{directory}
argument to the @ref{4a4,,http.server.SimpleHTTPRequestHandler} class. Patch
by Géry Ogam.

@item 
bpo-38086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38086}: Update importlib.metadata with changes from importlib_metadata 0.21@footnote{https://gitlab.com/python-devs/importlib_metadata/blob/0.21/importlib_metadata/docs/changelog.rst}.

@item 
bpo-37251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37251}: Remove @code{__code__} check in AsyncMock that incorrectly evaluated
function specs as async objects but failed to evaluate classes with
@code{__await__} but no @code{__code__} attribute defined as async objects.

@item 
bpo-38037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38037}: Fix reference counters in the @ref{ea,,signal} module.

@item 
bpo-38066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38066}: Hide internal asyncio.Stream methods: feed_eof(), feed_data(),
set_exception() and set_transport().

@item 
bpo-38059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38059}: inspect.py now uses sys.exit() instead of exit()

@item 
bpo-38049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38049}: Added command-line interface for the @ref{7,,ast} module.

@item 
bpo-37953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37953}: In @ref{122,,typing}, improved the @code{__hash__} and @code{__eq__}
methods for @code{ForwardReferences}.

@item 
bpo-38026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38026}: Fixed @ref{ca1,,inspect.getattr_static()} used @code{isinstance} while
it should avoid dynamic lookup.

@item 
bpo-35923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35923}: Update @ref{658,,importlib.machinery.BuiltinImporter} to use
@code{loader._ORIGIN} instead of a hardcoded value. Patch by Dong-hee Na.

@item 
bpo-38010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38010}: In @code{importlib.metadata} sync with @code{importlib_metadata}
0.20, clarifying behavior of @code{files()} and fixing issue where only one
requirement was returned for @code{requires()} on @code{dist-info} packages.

@item 
bpo-38006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38006}: weakref.WeakValueDictionary defines a local remove() function
used as callback for weak references. This function was created with a
closure. Modify the implementation to avoid the closure.

@item 
bpo-37995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37995}: Added the @emph{indent} option to @ref{185,,ast.dump()} which allows it
to produce a multiline indented output.

@item 
bpo-34410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34410}: Fixed a crash in the @code{tee()} iterator when re-enter it.
RuntimeError is now raised in this case.

@item 
bpo-37140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37140}: Fix a ctypes regression of Python 3.8. When a ctypes.Structure
is passed by copy to a function, ctypes internals created a temporary
object which had the side effect of calling the structure finalizer
(__del__) twice. The Python semantics requires a finalizer to be called
exactly once. Fix ctypes internals to no longer call the finalizer twice.

@item 
bpo-37587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37587}: @code{_json.scanstring} is now up to 3x faster when there are many
backslash escaped characters in the JSON string.

@item 
bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}: Prevent shutil.rmtree exception when built on non-Windows
system without fd system call support, like older versions of macOS.

@item 
bpo-10978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10978}: Semaphores and BoundedSemaphores can now release more than one
waiting thread at a time.

@item 
bpo-37972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37972}: Subscripts to the @ref{1115,,unittest.mock.call} objects now receive the
same chaining mechanism as any other custom attributes, so that the
following usage no longer raises a @ref{1ff,,TypeError}:

call().foo().__getitem__('bar')

Patch by blhsing

@item 
bpo-37965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37965}: Fix C compiler warning caused by
distutils.ccompiler.CCompiler.has_function.

@item 
bpo-37964@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37964}: Add @code{F_GETPATH} command to @ref{7c,,fcntl}.

@item 
bpo-37960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37960}: @code{repr()} of buffered and text streams now silences only
expected exceptions when get the value of "name" and "mode" attributes.

@item 
bpo-37961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37961}: Add a @code{total_nframe} field to the traces collected by the
tracemalloc module. This field indicates the original number of frames
before it was truncated.

@item 
bpo-37951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37951}: Most features of the subprocess module now work again in
subinterpreters. Only @emph{preexec_fn} is restricted in subinterpreters.

@item 
bpo-36205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36205}: Fix the rusage implementation of time.process_time() to
correctly report the sum of the system and user CPU time.

@item 
bpo-37950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37950}: Fix @ref{185,,ast.dump()} when call with incompletely initialized
node.

@item 
bpo-34679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34679}: Restores instantiation of Windows IOCP event loops from the
non-main thread.

@item 
bpo-36917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36917}: Add default implementation of the
@code{ast.NodeVisitor.visit_Constant()} method which emits a deprecation
warning and calls corresponding methody @code{visit_Num()}, @code{visit_Str()},
etc.

@item 
bpo-37798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37798}: Update test_statistics.py to verify that the statistics module
works well for both C and Python implementations. Patch by Dong-hee Na

@item 
bpo-26589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26589}: Added a new status code to the http module: 451
UNAVAILABLE_FOR_LEGAL_REASONS

@item 
bpo-37915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37915}: Fix a segmentation fault that appeared when comparing instances
of @code{datetime.timezone} and @code{datetime.tzinfo} objects. Patch by Pablo
Galindo.

@item 
bpo-32554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32554}: Deprecate having random.seed() call hash on arbitrary types.

@item 
bpo-9938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9938}: Add optional keyword argument @code{exit_on_error} for
@code{ArgumentParser}.

@item 
bpo-37851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37851}: The @ref{7b,,faulthandler} module no longer allocates its
alternative stack at Python startup. Now the stack is only allocated at
the first faulthandler usage.

@item 
bpo-32793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32793}: Fix a duplicated debug message when
@ref{1116,,smtplib.SMTP.connect()} is called.

@item 
bpo-37885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37885}: venv: Don't generate unset variable warning on deactivate.

@item 
bpo-37868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37868}: Fix dataclasses.is_dataclass when given an instance that never
raises AttributeError in __getattr__.  That is, an object that returns
something for __dataclass_fields__ even if it's not a dataclass.

@item 
bpo-37811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37811}: Fix @code{socket} module's @code{socket.connect(address)} function
being unable to establish connection in case of interrupted system call.
The problem was observed on all OSes which @code{poll(2)} system call can
take only non-negative integers and -1 as a timeout value.

@item 
bpo-37863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37863}: Optimizations for Fraction.__hash__ suggested by Tim Peters.

@item 
bpo-21131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21131}: Fix @code{faulthandler.register(chain=True)} stack. faulthandler
now allocates a dedicated stack of @code{SIGSTKSZ*2} bytes, instead of just
@code{SIGSTKSZ} bytes. Calling the previous signal handler in faulthandler
signal handler uses more than @code{SIGSTKSZ} bytes of stack memory on some
platforms.

@item 
bpo-37798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37798}: Add C fastpath for statistics.NormalDist.inv_cdf() Patch by
Dong-hee Na

@item 
bpo-37804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37804}: Remove the deprecated method @code{threading.Thread.isAlive()}.
Patch by Dong-hee Na.

@item 
bpo-37819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37819}: Add Fraction.as_integer_ratio() to match the corresponding
methods in bool, int, float, and decimal.

@item 
bpo-14465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14465}: Add an xml.etree.ElementTree.indent() function for
pretty-printing XML trees. Contributed by Stefan Behnel.

@item 
bpo-37810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37810}: Fix @ref{36,,difflib} @code{?} hint in diff output when dealing with
tabs.  Patch by Anthony Sottile.

@item 
bpo-37772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37772}: In @code{zipfile.Path}, when adding implicit dirs, ensure that
ancestral directories are added and that duplicates are excluded.

@item 
bpo-18578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18578}: Renamed and documented @code{test.bytecode_helper} as
@ref{107,,test.support.bytecode_helper}. Patch by Joannah Nanjekye.

@item 
bpo-37785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37785}: Fix xgettext warnings in @ref{5,,argparse}.

@item 
bpo-34488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34488}: @code{writelines()} method of @ref{894,,io.BytesIO} is now
slightly faster when many small lines are passed. Patch by Sergey
Fedoseev.

@item 
bpo-37449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37449}: @ref{78,,ensurepip} now uses @ref{1117,,importlib.resources.read_binary()} to
read data instead of @ref{1118,,pkgutil.get_data()}. Patch by Joannah Nanjekye.

@item 
bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292}: Mark calendar.py helper functions as being private.  The
follows PEP 8 guidance to maintain the style conventions in the module and
it addresses a known case of user confusion.

@item 
bpo-18049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18049}: Add definition of THREAD_STACK_SIZE for AIX in
Python/thread_pthread.h The default thread stacksize caused crashes with
the default recursion limit Patch by M Felt

@item 
bpo-37742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37742}: The logging.getLogger() API now returns the root logger when
passed the name 'root', whereas previously it returned a non-root logger
named 'root'. This could affect cases where user code explicitly wants a
non-root logger named 'root', or instantiates a logger using
logging.getLogger(__name__) in some top-level module called 'root.py'.

@item 
bpo-37738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37738}: Fix the implementation of curses @code{addch(str, color_pair)}:
pass the color pair to @code{setcchar()}, instead of always passing 0 as the
color pair.

@item 
bpo-37723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37723}: Fix performance regression on regular expression parsing with
huge character sets. Patch by Yann Vaginay.

@item 
bpo-35943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35943}: The function @ref{52d,,PyImport_GetModule()} now ensures any
module it returns is fully initialized. Patch by Joannah Nanjekye.

@item 
bpo-32178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32178}: Fix IndexError in @ref{67,,email} package when trying to parse
invalid address fields starting with @code{:}.

@item 
bpo-37268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37268}: The @ref{c7,,parser} module is deprecated and will be removed in
future versions of Python.

@item 
bpo-11953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11953}: Completing WSA* error codes in @ref{ef,,socket}.

@item 
bpo-37685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37685}: Fixed comparisons of @ref{2d1,,datetime.timedelta} and
@ref{ae9,,datetime.timezone}.

@item 
bpo-37697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37697}: Synchronize @code{importlib.metadata} with importlib_metadata 0.19@footnote{https://gitlab.com/python-devs/importlib_metadata/-/milestones/20},
improving handling of EGG-INFO files and fixing a crash when entry point
names contained colons.

@item 
bpo-37695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37695}: Correct @ref{ac8,,curses.unget_wch()} error message.  Patch by
Anthony Sottile.

@item 
bpo-37689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37689}: Add @code{is_relative_to()} in @code{PurePath} to determine
whether or not one path is relative to another.

@item 
bpo-29553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29553}: Fixed @ref{1119,,argparse.ArgumentParser.format_usage()} for mutually
exclusive groups. Patch by Andrew Nester.

@item 
bpo-37691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37691}: Let math.dist() accept coordinates as sequences (or iterables)
rather than just tuples.

@item 
bpo-37685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37685}: Fixed @code{__eq__}, @code{__lt__} etc implementations in some
classes. They now return @ref{203,,NotImplemented} for unsupported type of
the other operand. This allows the other operand to play role (for example
the equality comparison with @ref{111a,,ANY} will return
@code{True}).

@item 
bpo-37354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37354}: Make Activate.ps1 Powershell script static to allow for signing
it.

@item 
bpo-37664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37664}: Update wheels bundled with ensurepip (pip 19.2.3 and setuptools
41.2.0)

@item 
bpo-37663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37663}: Bring consistency to venv shell activation scripts by always
using __VENV_PROMPT__.

@item 
bpo-37642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37642}: Allowed the pure Python implementation of
@ref{ae9,,datetime.timezone} to represent sub-minute offsets close to
minimum and maximum boundaries, specifically in the ranges (23:59, 24:00)
and (-23:59, 24:00). Patch by Ngalim Siregar

@item 
bpo-36161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36161}: In @ref{d1,,posix}, use @code{ttyname_r} instead of @code{ttyname} for
thread safety.

@item 
bpo-36324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36324}: Make internal attributes for statistics.NormalDist() private.

@item 
bpo-37555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37555}: Fix @code{NonCallableMock._call_matcher} returning tuple instead of
@code{_Call} object when @code{self._spec_signature} exists. Patch by Elizabeth
Uselton

@item 
bpo-29446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29446}: Make @code{from tkinter import *} import only the expected objects.

@item 
bpo-16970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16970}: Adding a value error when an invalid value in passed to nargs
Patch by Robert Leenders

@item 
bpo-34443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34443}: Exceptions from @ref{79,,enum} now use the @code{__qualname} of the
enum class in the exception message instead of the @code{__name__}.

@item 
bpo-37491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37491}: Fix @code{IndexError} when parsing email headers with unexpectedly
ending bare-quoted string value. Patch by Abhilash Raj.

@item 
bpo-37587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37587}: Make json.loads faster for long strings. (Patch by Marco
Paolini)

@item 
bpo-18378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18378}: Recognize "UTF-8" as a valid value for LC_CTYPE in
locale._parse_localename.

@item 
bpo-37579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37579}: Return @ref{203,,NotImplemented} in Python implementation of
@code{__eq__} for @ref{2d1,,timedelta} and @ref{5f5,,time}
when the other object being compared is not of the same type to match C
implementation. Patch by Karthikeyan Singaravelan.

@item 
bpo-21478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21478}: Record calls to parent when autospecced object is attached to a
mock using @code{unittest.mock.attach_mock()}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: "python3 -m test -jN --timeout=TIMEOUT" now kills a worker
process if it runs longer than @emph{TIMEOUT} seconds.

@item 
bpo-37482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37482}: Fix serialization of display name in originator or destination
address fields with both encoded words and special chars.

@item 
bpo-36993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36993}: Improve error reporting for corrupt zip files with bad zip64
extra data. Patch by Daniel Hillier.

@item 
bpo-37502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37502}: pickle.loads() no longer raises TypeError when the buffers
argument is set to None

@item 
bpo-37520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37520}: Correct behavior for zipfile.Path.parent when the path object
identifies a subdirectory.

@item 
bpo-18374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18374}: Fix the @code{.col_offset} attribute of nested @ref{111b,,ast.BinOp}
instances which had a too large value in some situations.

@item 
bpo-37424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37424}: Fixes a possible hang when using a timeout on
@ref{4fb,,subprocess.run()} while capturing output.  If the child process spawned
its own children or otherwise connected its stdout or stderr handles with
another process, we could hang after the timeout was reached and our child
was killed when attempting to read final output from the pipes.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: Fix @code{multiprocessing.util.get_temp_dir()} finalizer: clear
also the 'tempdir' configuration of the current process, so next call to
@code{get_temp_dir()} will create a new temporary directory, rather than
reusing the removed temporary directory.

@item 
bpo-37481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37481}: The distutils @code{bdist_wininst} command is deprecated in Python
3.8, use @code{bdist_wheel} (wheel packages) instead.

@item 
bpo-37479@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37479}: When @code{Enum.__str__} is overridden in a derived class, the
override will be used by @code{Enum.__format__} regardless of whether mixin
classes are present.

@item 
bpo-37440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37440}: http.client now enables TLS 1.3 post-handshake authentication
for default context or if a cert_file is passed to HTTPSConnection.

@item 
bpo-37437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37437}: Update vendorized expat version to 2.2.7.

@item 
bpo-37428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37428}: SSLContext.post_handshake_auth = True no longer sets
SSL_VERIFY_POST_HANDSHAKE verify flag for client connections. Although the
option is documented as ignored for clients, OpenSSL implicitly enables
cert chain validation when the flag is set.

@item 
bpo-37420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37420}: @ref{b39,,os.sched_setaffinity()} now correctly handles errors that
arise during iteration over its @code{mask} argument. Patch by Brandt Bucher.

@item 
bpo-37412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37412}: The @ref{3e2,,os.getcwdb()} function now uses the UTF-8 encoding on
Windows, rather than the ANSI code page: see 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} for the rationale.
The function is no longer deprecated on Windows.

@item 
bpo-37406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37406}: The sqlite3 module now raises TypeError, rather than
ValueError, if operation argument type is not str: execute(),
executemany() and calling a connection.

@item 
bpo-29412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29412}: Fix IndexError in parsing a header value ending unexpectedly.
Patch by Abhilash Raj.

@item 
bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546}: The @emph{dist} argument for statistics.quantiles() is now
positional only. The current name doesn't reflect that the argument can be
either a dataset or a distribution.  Marking the parameter as positional
avoids confusion and makes it possible to change the name later.

@item 
bpo-37394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37394}: Fix a bug that was causing the @ref{da,,queue} module to fail if
the accelerator module was not available. Patch by Pablo Galindo.

@item 
bpo-37376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37376}: @ref{d2,,pprint} now has support for
@ref{1d9,,types.SimpleNamespace}. Patch by Carl Bordum Hansen.

@item 
bpo-26967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26967}: An @ref{792,,ArgumentParser} with
@code{allow_abbrev=False} no longer disables grouping of short flags, such as
@code{-vv}, but only disables abbreviation of long flags as documented. Patch
by Zac Hatfield-Dodds.

@item 
bpo-37212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37212}: @ref{1115,,unittest.mock.call()} now preserves the order of keyword
arguments in repr output. Patch by Karthikeyan Singaravelan.

@item 
bpo-37372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37372}: Fix error unpickling datetime.time objects from Python 2 with
seconds>=24. Patch by Justin Blanchard.

@item 
bpo-37345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37345}: Add formal support for UDPLITE sockets. Support was present
before, but it is now easier to detect support with @code{hasattr(socket,
'IPPROTO_UDPLITE')} and there are constants defined for each of the
values needed: @code{socket.IPPROTO_UDPLITE},
@code{UDPLITE_SEND_CSCOV}, and @code{UDPLITE_RECV_CSCOV}. Patch by
Gabe Appleton.

@item 
bpo-37358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37358}: Optimized @code{functools.partial} by using vectorcall.

@item 
bpo-37347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37347}: @ref{111c,,sqlite3.Connection.create_aggregate()},
@ref{111d,,sqlite3.Connection.create_function()},
@ref{111e,,sqlite3.Connection.set_authorizer()},
@ref{111f,,sqlite3.Connection.set_progress_handler()}
@ref{b6e,,sqlite3.Connection.set_trace_callback()} methods lead to segfaults if
some of these methods are called twice with an equal object but not the
same. Now callbacks are stored more carefully. Patch by Aleksandr Balezin.

@item 
bpo-37163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37163}: The @emph{obj} argument of @ref{ff3,,dataclasses.replace()} is
positional-only now.

@item 
bpo-37085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37085}: Add the optional Linux SocketCAN Broadcast Manager constants,
used as flags to configure the BCM behaviour, in the socket module.  Patch
by Karl Ding.

@item 
bpo-37328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37328}: @code{HTMLParser.unescape} is removed.  It was undocumented and
deprecated since Python 3.4.

@item 
bpo-37305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37305}: Add .webmanifest -> application/manifest+json to list of
recognized file types and content type headers

@item 
bpo-37320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37320}: @code{aifc.openfp()} alias to @code{aifc.open()}, @code{sunau.openfp()}
alias to @code{sunau.open()}, and @code{wave.openfp()} alias to @code{wave.open()}
have been removed. They were deprecated since Python 3.7.

@item 
bpo-37315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37315}: Deprecated accepting floats with integral value (like @code{5.0})
in @ref{1fd,,math.factorial()}.

@item 
bpo-37312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37312}: @code{_dummy_thread} and @code{dummy_threading} modules have been
removed. These modules were deprecated since Python 3.7 which requires
threading support.

@item 
bpo-33972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33972}: Email with single part but content-type set to @code{multipart/*}
doesn't raise AttributeError anymore.

@item 
bpo-37280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37280}: Use threadpool for reading from file for sendfile fallback
mode.

@item 
bpo-37279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37279}: Fix asyncio sendfile support when sendfile sends extra data in
fallback mode.

@item 
bpo-19865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19865}: @ref{1120,,ctypes.create_unicode_buffer()} now also supports
non-BMP characters on platforms with 16-bit @code{wchar_t} (for
example, Windows and AIX).

@item 
bpo-37266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37266}: In a subinterpreter, spawning a daemon thread now raises an
exception. Daemon threads were never supported in subinterpreters.
Previously, the subinterpreter finalization crashed with a Python fatal
error if a daemon thread was still running.

@item 
bpo-37210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37210}: Allow pure Python implementation of @ref{ca,,pickle} to work even
when the C @code{_pickle} module is unavailable.

@item 
bpo-21872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21872}: Fix @ref{ad,,lzma}: module decompresses data incompletely. When
decompressing a FORMAT_ALONE format file, and it doesn't have the end
marker, sometimes the last one to dozens bytes can't be output. Patch by
Ma Lin.

@item 
bpo-35922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35922}: Fix @code{RobotFileParser.crawl_delay()} and
@code{RobotFileParser.request_rate()} to return @code{None} rather than raise
@ref{4aa,,AttributeError} when no relevant rule is defined in the robots.txt
file.  Patch by Rémi Lapeyre.

@item 
bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766}: Change the format of feature_version to be a (major, minor)
tuple.

@item 
bpo-36607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36607}: Eliminate @ref{3e4,,RuntimeError} raised by
@ref{22a,,asyncio.all_tasks()} if internal tasks weak set is changed by
another thread during iteration.

@item 
bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}: @code{_pyio.IOBase} destructor now does nothing if getting
the @code{closed} attribute fails to better mimic @code{_io.IOBase}
finalizer.

@item 
bpo-36402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36402}: Fix a race condition at Python shutdown when waiting for
threads. Wait until the Python thread state of all non-daemon threads get
deleted (join all non-daemon threads), rather than just wait until
non-daemon Python threads complete.

@item 
bpo-37206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37206}: Default values which cannot be represented as Python objects no
longer improperly represented as @code{None} in function signatures.

@item 
bpo-37111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37111}: Added @code{encoding} and @code{errors} keyword parameters to
@code{logging.basicConfig}.

@item 
bpo-12144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12144}: Ensure cookies with @code{expires} attribute are handled in
@code{CookieJar.make_cookies()}.

@item 
bpo-34886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34886}: Fix an unintended ValueError from @ref{4fb,,subprocess.run()} when
checking for conflicting @ref{d3b,,input} and @code{stdin} or @code{capture_output} and
@code{stdout} or @code{stderr} args when they were explicitly provided but with
@ref{204,,None} values within a passed in @code{**kwargs} dict rather than as passed
directly by name. Patch contributed by Rémi Lapeyre.

@item 
bpo-37173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37173}: The exception message for @code{inspect.getfile()} now correctly
reports the passed class rather than the builtins module.

@item 
bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178}: Give math.perm() a one argument form that means the same as
math.factorial().

@item 
bpo-37178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37178}: For math.perm(n, k), let k default to n, giving the same result
as factorial.

@item 
bpo-37165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37165}: Converted _collections._count_elements to use the Argument
Clinic.

@item 
bpo-34767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34767}: Do not always create a @ref{633,,collections.deque} in
@ref{3b6,,asyncio.Lock}.

@item 
bpo-37158@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37158}: Speed-up statistics.fmean() by switching from a function to a
generator.

@item 
bpo-34282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34282}: Remove @code{Enum._convert} method, deprecated in 3.8.

@item 
bpo-37150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37150}: @code{argparse._ActionsContainer.add_argument} now throws error, if
someone accidentally pass FileType class object instead of instance of
FileType as @ref{709,,type} argument

@item 
bpo-28724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28724}: The socket module now has the @ref{1e5,,socket.send_fds()} and
@code{socket.recv.fds()} methods. Contributed by Joannah Nanjekye, Shinya
Okano and Victor Stinner.

@item 
bpo-35621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35621}: Support running asyncio subprocesses when execution event loop
in a thread on UNIX.

@item 
bpo-36520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36520}: Lengthy email headers with UTF-8 characters are now properly
encoded when they are folded. Patch by Jeffrey Kintscher.

@item 
bpo-30835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30835}: Fixed a bug in email parsing where a message with invalid bytes
in content-transfer-encoding of a multipart message can cause an
AttributeError. Patch by Andrew Donnellan.

@item 
bpo-31163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31163}: pathlib.Path instance's rename and replace methods now return
the new Path instance.

@item 
bpo-25068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25068}: @ref{1121,,urllib.request.ProxyHandler} now lowercases the keys of
the passed dictionary.

@item 
bpo-26185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26185}: Fix @ref{8c3,,repr()} on empty @code{ZipInfo} object. Patch by
Mickaël Schoentgen.

@item 
bpo-21315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21315}: Email headers containing RFC2047 encoded words are parsed
despite the missing whitespace, and a defect registered. Also missing
trailing whitespace after encoded words is now registered as a defect.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Port test_datetime to VxWorks: skip zoneinfo tests on VxWorks

@item 
bpo-35805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35805}: Add parser for Message-ID header and add it to default
HeaderRegistry. This should prevent folding of Message-ID using RFC 2048
encoded words.

@item 
bpo-36871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36871}: Ensure method signature is used instead of constructor
signature of a class while asserting mock object against method calls.
Patch by Karthikeyan Singaravelan.

@item 
bpo-35070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35070}: posix.getgrouplist() now works correctly when the user belongs
to NGROUPS_MAX supplemental groups. Patch by Jeffrey Kintscher.

@item 
bpo-31783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31783}: Fix race condition in ThreadPoolExecutor when worker threads
are created during interpreter shutdown.

@item 
bpo-36582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36582}: Fix @code{UserString.encode()} to correctly return @code{bytes}
rather than a @code{UserString} instance.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Deprecate xml.etree.ElementTree.Element.copy() in favor of
copy.copy().

Patch by Gordon P. Hemsley

@item 
bpo-36564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36564}: Fix infinite loop in email header folding logic that would be
triggered when an email policy's max_line_length is not long enough to
include the required markup and any values in the message. Patch by Paul
Ganssle

@item 
bpo-36543@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36543}: Removed methods Element.getchildren(), Element.getiterator()
and ElementTree.getiterator() and the xml.etree.cElementTree module.

@item 
bpo-36409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36409}: Remove the old plistlib API deprecated in Python 3.4

@item 
bpo-36302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36302}: distutils sorts source file lists so that Extension .so files
build more reproducibly by default

@item 
bpo-36250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36250}: Ignore @code{ValueError} from @code{signal} with @code{interaction} in
non-main thread.

@item 
bpo-36046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36046}: Added @code{user}, @code{group} and @code{extra_groups} parameters to
the subprocess.Popen constructor. Patch by Patrick McLean.

@item 
bpo-32627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32627}: Fix compile error when @code{_uuid} headers conflicting included.

@item 
bpo-35800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35800}: Deprecate @code{smtpd.MailmanProxy} ready for future removal.

@item 
bpo-35168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35168}: @ref{1122,,shlex.shlex.punctuation_chars} is now a read-only
property.

@item 
bpo-8538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8538}: Add support for boolean actions like @code{--foo} and @code{--no-foo}
to argparse. Patch contributed by Rémi Lapeyre.

@item 
bpo-20504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20504}: Fixes a bug in @ref{15,,cgi} module when a multipart/form-data
request has no @code{Content-Length} header.

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: The abstract base classes in @ref{1e,,collections.abc} no longer
are exposed in the regular @ref{1d,,collections} module.

@item 
bpo-11122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11122}: Distutils won't check for rpmbuild in specified paths only.

@item 
bpo-34775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34775}: Division handling of PurePath now returns NotImplemented
instead of raising a TypeError when passed something other than an
instance of str or PurePath. Patch by Roger Aiudi.

@item 
bpo-34749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34749}: @ref{1123,,binascii.a2b_base64()} is now up to 2 times faster. Patch
by Sergey Fedoseev.

@item 
bpo-34519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34519}: Add additional aliases for HP Roman 8. Patch by Michael Osipov.

@item 
bpo-28009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28009}: Fix uuid.getnode() on platforms with '.' as MAC Addr delimiter
as well fix for MAC Addr format that omits a leading 0 in MAC Addr values.
Currently, AIX is the only know platform with these settings. Patch by
Michael Felt.

@item 
bpo-30618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30618}: Add @ref{1d1,,readlink()}. Patch by Girts Folkmanis.

@item 
bpo-32498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32498}: Made @ref{1124,,urllib.parse.unquote()} accept bytes in addition to
strings. Patch by Stein Karlsen.

@item 
bpo-33348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33348}: lib2to3 now recognizes expressions after @code{*} and @code{**} like in
@code{f(*[] or [])}.

@item 
bpo-32689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32689}: Update @ref{38c,,shutil.move()} function to allow for Path objects
to be used as source argument. Patch by Emily Morehouse and Maxwell
"5.13b" McKinnon.

@item 
bpo-32820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32820}: Added __format__ to IPv4 and IPv6 classes.  Always outputs a
fully zero- padded string. Supports b/x/n modifiers (bin/hex/native
format).  Native format for IPv4 is bin, native format for IPv6 is hex.
Also supports '#' and '_' modifiers.

@item 
bpo-27657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27657}: Fix urllib.parse.urlparse() with numeric paths. A string like
"path:80" is no longer parsed as a path but as a scheme ("path") and a
path ("80").

@item 
bpo-4963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4963}: Fixed non-deterministic behavior related to mimetypes extension
mapping and module reinitialization.
@end itemize

@node Documentation<21>,Tests<22>,Library<31>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id210}@anchor{1125}
@subsubsection Documentation



@itemize -

@item 
bpo-21767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21767}: Explicitly mention abc support in functools.singledispatch

@item 
bpo-38816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38816}: Provides more details about the interaction between
@code{fork()} and CPython's runtime, focusing just on the C-API.  This
includes cautions about where @code{fork()} should and shouldn't be
called.

@item 
bpo-38351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38351}: Modernize @ref{67,,email} examples from %-formatting to f-strings.

@item 
bpo-38778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38778}: Document the fact that @ref{3e4,,RuntimeError} is raised if
@ref{a4b,,os.fork()} is called in a subinterpreter.

@item 
bpo-38592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38592}: Add Brazilian Portuguese to the language switcher at Python
Documentation website.

@item 
bpo-38294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38294}: Add list of no-longer-escaped chars to re.escape documentation

@item 
bpo-38053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38053}: Modernized the plistlib documentation

@item 
bpo-26868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26868}: Fix example usage of @ref{1126,,PyModule_AddObject()} to properly
handle errors.

@item 
bpo-36797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36797}: Fix a dead link in the distutils API Reference.

@item 
bpo-37977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37977}: Warn more strongly and clearly about pickle insecurity

@item 
bpo-37979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37979}: Added a link to dateutil.parser.isoparse in the
datetime.fromisoformat documentation. Patch by Paul Ganssle

@item 
bpo-12707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12707}: Deprecate info(), geturl(), getcode() methods in favor of the
headers, url, and status properties, respectively, for HTTPResponse and
addinfourl. Also deprecate the code attribute of addinfourl in favor of
the status attribute. Patch by Ashwin Ramaswami

@item 
bpo-37937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37937}: Mention @code{frame.f_trace} in @ref{f08,,sys.settrace()} docs.

@item 
bpo-37878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37878}: Make @ref{1127,,PyThreadState_DeleteCurrent()} Internal.

@item 
bpo-37759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37759}: Beginning edits to Whatsnew 3.8

@item 
bpo-37726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37726}: Stop recommending getopt in the tutorial for command line
argument parsing and promote argparse.

@item 
bpo-32910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32910}: Remove implementation-specific behaviour of how venv's
Deactivate works.

@item 
bpo-37256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37256}: Fix wording of arguments for @code{Request} in
@ref{129,,urllib.request}

@item 
bpo-37284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37284}: Add a brief note to indicate that any new
@code{sys.implementation} required attributes must go through the PEP
process.

@item 
bpo-30088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30088}: Documented that @ref{d78,,mailbox.Maildir} constructor doesn't
attempt to verify the maildir folder layout correctness. Patch by
Sviatoslav Sydorenko.

@item 
bpo-37521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37521}: Fix @ref{9a,,importlib} examples to insert any newly created modules
via importlib.util.module_from_spec() immediately into sys.modules instead
of after calling loader.exec_module().

Thanks to Benjamin Mintz for finding the bug.

@item 
bpo-37456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37456}: Slash ('/') is now part of syntax.

@item 
bpo-37487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37487}: Fix PyList_GetItem index description to include 0.

@item 
bpo-37149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37149}: Replace the dead link to the Tkinter 8.5 reference by John
Shipman, New Mexico Tech, with a link to the archive.org copy.

@item 
bpo-37478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37478}: Added possible exceptions to the description of os.chdir().

@item 
bpo-34903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34903}: Documented that in @ref{fdc,,datetime.datetime.strptime()}, the
leading zero in some two-digit formats is optional. Patch by Mike Gleen.

@item 
bpo-36260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36260}: Add decompression pitfalls to zipfile module documentation.

@item 
bpo-37004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37004}: In the documentation for difflib, a note was added explicitly
warning that the results of SequenceMatcher's ratio method may depend on
the order of the input strings.

@item 
bpo-36960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36960}: Restructured the @ref{30,,datetime} docs in the interest of making
them more user-friendly and improving readability. Patch by Brad Solomon.

@item 
bpo-36487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36487}: Make C-API docs clear about what the "main" interpreter is.

@item 
bpo-23460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23460}: The documentation for decimal string formatting using the @code{:g}
specifier has been updated to reflect the correct exponential notation
cutoff point. Original patch contributed by Tuomas Suutari.

@item 
bpo-35803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35803}: Document and test that @code{tempfile} functions may accept a
@ref{47b,,path-like object} for the @code{dir} argument.  Patch by Anthony
Sottile.

@item 
bpo-33944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33944}: Added a note about the intended use of code in .pth files.

@item 
bpo-34293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34293}: Fix the Doc/Makefile regarding PAPER environment variable and
PDF builds

@item 
bpo-25237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25237}: Add documentation for tkinter modules
@end itemize

@node Tests<22>,Build<21>,Documentation<21>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id211}@anchor{1128}
@subsubsection Tests



@itemize -

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Fix test_communicate() of test_asyncio.test_subprocess: use
@code{support.LONG_TIMEOUT} (5 minutes), instead of just 1 minute.

@item 
bpo-38614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38614}: Add timeout constants to @ref{106,,test.support}:
@ref{10fa,,LOOPBACK_TIMEOUT},
@ref{10fb,,INTERNET_TIMEOUT},
@ref{fdf,,SHORT_TIMEOUT} and
@ref{10fc,,LONG_TIMEOUT}.

@item 
bpo-38502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38502}: test.regrtest now uses process groups in the multiprocessing
mode (-jN command line option) if process groups are available: if
@ref{1129,,os.setsid()} and @ref{112a,,os.killpg()} functions are available.

@item 
bpo-35998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35998}: Fix a race condition in test_asyncio.test_start_tls_server_1().
Previously, there was a race condition between the test main() function
which replaces the protocol and the test ServerProto protocol which sends
ANSWER once it gets HELLO. Now, only the test main() function is
responsible to send data, ServerProto no longer sends data.

@item 
bpo-38470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38470}: Fix @code{test_compileall.test_compile_dir_maxlevels()} on Windows
without long path support: only create 3 subdirectories instead of between
20 and 100 subdirectories.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: On timeout, regrtest no longer attempts to call
@code{popen.communicate()} again: it can hang until all child processes using
stdout and stderr pipes completes. Kill the worker process and ignores its
output. Change also the faulthandler timeout of the main process from 1
minute to 5 minutes, for Python slowest buildbots.

@item 
bpo-38239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38239}: Fix test_gdb for Link Time Optimization (LTO) builds.

@item 
bpo-38275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38275}: test_ssl now handles disabled TLS/SSL versions better.
OpenSSL's crypto policy and run-time settings are recognized and tests for
disabled versions are skipped. Tests also accept more TLS minimum_versions
for platforms that override OpenSSL's default with strict settings.

@item 
bpo-38271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38271}: The private keys for test_ssl were encrypted with 3DES in
traditional PKCS#5 format. 3DES and the digest algorithm of PKCS#5 are
blocked by some strict crypto policies. Use PKCS#8 format with AES256
encryption instead.

@item 
bpo-38270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38270}: test.support now has a helper function to check for
availability of a hash digest function. Several tests are refactored avoid
MD5 and use SHA256 instead. Other tests are marked to use MD5 and skipped
when MD5 is disabled.

@item 
bpo-37123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37123}: Multiprocessing test test_mymanager() now also expects
-SIGTERM, not only exitcode 0. BaseManager._finalize_manager() sends
SIGTERM to the manager process if it takes longer than 1 second to stop,
which happens on slow buildbots.

@item 
bpo-38212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38212}: Multiprocessing tests: increase
test_queue_feeder_donot_stop_onexc() timeout from 1 to 60 seconds.

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Test with OpenSSL 1.1.1d

@item 
bpo-38018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38018}: Increase code coverage for multiprocessing.shared_memory.

@item 
bpo-37805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37805}: Add tests for json.dump(..., skipkeys=True). Patch by Dong-hee
Na.

@item 
bpo-37531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37531}: Enhance regrtest multiprocess timeout: write a message when
killing a worker process, catch popen.kill() and popen.wait() exceptions,
put a timeout on the second call to popen.communicate().

@item 
bpo-37876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37876}: Add tests for ROT-13 codec.

@item 
bpo-36833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36833}: Added tests for PyDateTime_xxx_GET_xxx() macros of the C API of
the @ref{30,,datetime} module. Patch by Joannah Nanjekye.

@item 
bpo-37558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37558}: Fix test_shared_memory_cleaned_after_process_termination name
handling

@item 
bpo-37526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37526}: Add @ref{112b,,test.support.catch_threading_exception()}: context
manager catching @ref{21b,,threading.Thread} exception using
@ref{365,,threading.excepthook()}.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_concurrent_futures now explicitly stops the ForkServer
instance if it's running.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: multiprocessing tests now stop the ForkServer instance if it's
running: close the "alive" file descriptor to ask the server to stop and
then remove its UNIX address.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_distutils.test_build_ext() is now able to remove the
temporary directory on Windows: don't import the newly built C extension
("xx") in the current process, but test it in a separated process.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_concurrent_futures now cleans up multiprocessing to remove
immediately temporary directories created by
multiprocessing.util.get_temp_dir().

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: test_winconsoleio doesn't leak a temporary file anymore: use
tempfile.TemporaryFile() to remove it when the test completes.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: multiprocessing tests now explicitly call @code{_run_finalizers()}
to immediately remove temporary directories created by tests.

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: urllib.request tests now call
@ref{112c,,urlcleanup()} to remove temporary files created by
@code{urlretrieve()} tests and to clear the @code{_opener} global variable set
by @code{urlopen()} and functions calling indirectly @code{urlopen()}.

@item 
bpo-37472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37472}: Remove @code{Lib/test/outstanding_bugs.py}.

@item 
bpo-37199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37199}: Fix test failures when IPv6 is unavailable or disabled.

@item 
bpo-19696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19696}: Replace deprecated method "random.choose" with "random.choice"
in "test_pkg_import.py".

@item 
bpo-37335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37335}: Remove no longer necessary code from c locale coercion tests

@item 
bpo-37421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37421}: Fix test_shutil to no longer leak temporary files.

@item 
bpo-37411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37411}: Fix test_wsgiref.testEnviron() to no longer depend on the
environment variables (don't fail if "X" variable is set).

@item 
bpo-37400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37400}: Fix test_os.test_chown(): use os.getgroups() rather than
grp.getgrall() to get groups. Rename also the test to test_chown_gid().

@item 
bpo-37359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37359}: Add --cleanup option to python3 -m test to remove
@code{test_python_*} directories of previous failed jobs. Add "make
cleantest" to run @code{python3 -m test --cleanup}.

@item 
bpo-37362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37362}: test_gdb no longer fails if it gets an "unexpected" message on
stderr: it now ignores stderr. The purpose of test_gdb is to test that
python-gdb.py commands work as expected, not to test gdb.

@item 
bpo-35998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35998}: Avoid TimeoutError in test_asyncio: test_start_tls_server_1()

@item 
bpo-37278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37278}: Fix test_asyncio ProactorLoopCtrlC: join the thread to prevent
leaking a running thread and leaking a reference.

@item 
bpo-37261@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37261}: Fix @ref{112d,,test.support.catch_unraisable_exception()}: its
__exit__() method now ignores unraisable exception raised when clearing
its @code{unraisable} attribute.

@item 
bpo-37069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37069}: regrtest now uses @ref{361,,sys.unraisablehook()} to mark a test as
"environment altered" (ENV_CHANGED) if it emits an "unraisable exception".
Moreover, regrtest logs a warning in this case.

Use @code{python3 -m test --fail-env-changed} to catch unraisable exceptions
in tests.

@item 
bpo-37252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37252}: Fix assertions in @code{test_close} and
@code{test_events_mask_overflow} devpoll tests.

@item 
bpo-37169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37169}: Rewrite @code{_PyObject_IsFreed()} unit tests.

@item 
bpo-37153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37153}: @code{test_venv.test_multiprocessing()} now explicitly calls
@code{pool.terminate()} to wait until the pool completes.

@item 
bpo-34001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34001}: Make test_ssl pass with LibreSSL. LibreSSL handles minimum and
maximum TLS version differently than OpenSSL.

@item 
bpo-36919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36919}: Make @code{test_source_encoding.test_issue2301} implementation
independent. The test will work now for both CPython and IronPython.

@item 
bpo-30202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30202}: Update @code{test.test_importlib.test_abc} to test
@code{find_spec()}.

@item 
bpo-28009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28009}: Modify the test_uuid logic to test when a program is available
AND can be used to obtain a MACADDR as basis for an UUID. Patch by M. Felt

@item 
bpo-34596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34596}: Fallback to a default reason when @ref{112e,,unittest.skip()} is
uncalled. Patch by Naitree Zhu.
@end itemize

@node Build<21>,Windows<23>,Tests<22>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id212}@anchor{112f}
@subsubsection Build



@itemize -

@item 
bpo-38809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38809}: On Windows, build scripts will now recognize and use python.exe
from an active virtual env.

@item 
bpo-38684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38684}: Fix _hashlib build when Blake2 is disabled, but OpenSSL
supports it.

@item 
bpo-38468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38468}: Misc/python-config.in now uses @code{getvar()} for all still
existing @ref{a4e,,sysconfig.get_config_var()} calls. Patch by Joannah Nanjekye.

@item 
bpo-37415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37415}: Fix stdatomic.h header check for ICC compiler: the ICC
implementation lacks atomic_uintptr_t type which is needed by Python.

@item 
bpo-38301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38301}: In Solaris family, we must be sure to use @code{-D_REENTRANT}.
Patch by Jesús Cea Avión.

@item 
bpo-36002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36002}: Locate @code{llvm-profdata} and @code{llvm-ar} binaries using
@code{AC_PATH_TOOL} rather than @code{AC_PATH_TARGET_TOOL}.

@item 
bpo-37936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37936}: The @code{.gitignore} file systematically keeps "rooted", with
a non-trailing slash, all the rules that are meant to apply to files in a
specific place in the repo.  Previously, when the intended file to ignore
happened to be at the root of the repo, we'd most often accidentally also
ignore files and directories with the same name anywhere in the tree.

@item 
bpo-37760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37760}: The @code{Tools/unicode/makeunicodedata.py} script, which is
used for converting information from the Unicode Character Database into
generated code and data used by the methods of @ref{206,,str} and by the
@ref{123,,unicodedata} module, now handles each character's data as a
@code{dataclass} with named attributes, rather than a length-18 list of
different fields.

@item 
bpo-37936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37936}: The @code{.gitignore} file no longer applies to any files that
are in fact tracked in the Git repository.  Patch by Greg Price.

@item 
bpo-37725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37725}: Change "clean" makefile target to also clean the program guided
optimization (PGO) data.  Previously you would have to use "make clean"
and "make profile-removal", or "make clobber".

@item 
bpo-37707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37707}: Mark some individual tests to skip when --pgo is used.  The
tests marked increase the PGO task time significantly and likely don't
help improve optimization of the final executable.

@item 
bpo-36044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36044}: Reduce the number of unit tests run for the PGO generation
task.  This speeds up the task by a factor of about 15x.  Running the full
unit test suite is slow.  This change may result in a slightly less
optimized build since not as many code branches will be executed.  If you
are willing to wait for the much slower build, the old behavior can be
restored using './configure [..] PROFILE_TASK="-m test --pgo-extended"'.
We make no guarantees as to which PGO task set produces a faster build.
Users who care should run their own relevant benchmarks as results can
depend on the environment, workload, and compiler tool chain.

@item 
bpo-37468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37468}: @code{make install} no longer installs @code{wininst-*.exe} files
used by distutils bdist_wininst: bdist_wininst only works on Windows.

@item 
bpo-37189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37189}: Many @code{PyRun_XXX()} functions like @ref{1130,,PyRun_String()} were
no longer exported in @code{libpython38.dll} by mistake. Export them again to
fix the ABI compatibility.

@item 
bpo-25361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25361}: Enables use of SSE2 instructions in Windows 32-bit build.

@item 
bpo-36210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36210}: Update optional extension module detection for AIX. ossaudiodev
and spwd are not applicable for AIX, and are no longer reported as
missing. 3rd-party packaging of ncurses (with ASIS support) conflicts with
officially supported AIX curses library, so configure AIX to use
libcurses.a. However, skip trying to build _curses_panel.

patch by M Felt
@end itemize

@node Windows<23>,macOS<20>,Build<21>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id213}@anchor{1131}
@subsubsection Windows



@itemize -

@item 
bpo-38589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38589}: Fixes HTML Help shortcut when Windows is not installed to C
drive

@item 
bpo-38453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38453}: Ensure ntpath.realpath() correctly resolves relative paths.

@item 
bpo-38519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38519}: Restores the internal C headers that were missing from the
nuget.org and Microsoft Store packages.

@item 
bpo-38492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38492}: Remove @code{pythonw.exe} dependency on the Microsoft C++ runtime.

@item 
bpo-38344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38344}: Fix error message in activate.bat

@item 
bpo-38359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38359}: Ensures @code{pyw.exe} launcher reads correct registry key.

@item 
bpo-38355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38355}: Fixes @code{ntpath.realpath} failing on @code{sys.executable}.

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Update bundled OpenSSL to 1.1.1d

@item 
bpo-38092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38092}: Reduce overhead when using multiprocessing in a Windows virtual
environment.

@item 
bpo-38133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38133}: Allow py.exe launcher to locate installations from the
Microsoft Store and improve display of active virtual environments.

@item 
bpo-38114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38114}: The @code{pip.ini} is no longer included in the Nuget package.

@item 
bpo-32592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32592}: Set Windows 8 as the minimum required version for API support

@item 
bpo-36634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36634}: @ref{973,,os.cpu_count()} now returns active processors rather than
maximum processors.

@item 
bpo-36634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36634}: venv activate.bat now works when the existing variables contain
double quote characters.

@item 
bpo-38081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38081}: Prevent error calling @ref{334,,os.path.realpath()} on @code{'NUL'}.

@item 
bpo-38087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38087}: Fix case sensitivity in test_pathlib and test_ntpath.

@item 
bpo-38088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38088}: Fixes distutils not finding vcruntime140.dll with only the v142
toolset installed.

@item 
bpo-37283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37283}: Ensure command-line and unattend.xml setting override
previously detected states in Windows installer.

@item 
bpo-38030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38030}: Fixes @ref{328,,os.stat()} failing for block devices on Windows

@item 
bpo-38020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38020}: Fixes potential crash when calling @ref{1d2,,os.readlink()} (or
indirectly through @ref{334,,realpath()}) on a file that is not a
supported link.

@item 
bpo-37705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37705}: Improve the implementation of @code{winerror_to_errno()}.

@item 
bpo-37549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37549}: @ref{1132,,os.dup()} no longer fails for standard streams on Windows
7.

@item 
bpo-1311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1311}: The @code{nul} file on Windows now returns True from
@ref{32c,,exists()} and a valid result from @ref{328,,os.stat()} with
@code{S_IFCHR} set.

@item 
bpo-9949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9949}: Enable support for following symlinks in @code{os.realpath()}.

@item 
bpo-37834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37834}: Treat all name surrogate reparse points on Windows in
@ref{329,,os.lstat()} and other reparse points as regular files in
@ref{328,,os.stat()}.

@item 
bpo-36266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36266}: Add the module name in the formatted error message when DLL
load fail happens during module import in
@code{_PyImport_FindSharedFuncptrWindows()}. Patch by Srinivas Nyayapati.

@item 
bpo-25172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25172}: Trying to import the @ref{28,,crypt} module on Windows will result
in an @ref{16c,,ImportError} with a message explaining that the module isn't
supported on Windows. On other platforms, if the underlying @code{_crypt}
module is not available, the ImportError will include a message explaining
the problem.

@item 
bpo-37778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37778}: Fixes the icons used for file associations to the Microsoft
Store package.

@item 
bpo-37734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37734}: Fix use of registry values to launch Python from Microsoft
Store app.

@item 
bpo-37702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37702}: Fix memory leak on Windows in creating an SSLContext object or
running urllib.request.urlopen('@indicateurl{https://}...').

@item 
bpo-37672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37672}: Switch Windows Store package's pip to use bundled
@code{pip.ini} instead of 
@geindex PIP_USER
@geindex 环境变量; PIP_USER
@code{PIP_USER} variable.

@item 
bpo-10945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10945}: Officially drop support for creating bdist_wininst installers
on non-Windows systems.

@item 
bpo-37445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37445}: Include the @code{FORMAT_MESSAGE_IGNORE_INSERTS} flag in
@code{FormatMessageW()} calls.

@item 
bpo-37369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37369}: Fixes path for @ref{3a5,,sys.executable} when running from the
Microsoft Store.

@item 
bpo-37380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37380}: Don't collect unfinished processes with @code{subprocess._active}
on Windows to cleanup later. Patch by Ruslan Kuprieiev.

@item 
bpo-37351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37351}: Removes libpython38.a from standard Windows distribution.

@item 
bpo-35360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35360}: Update Windows builds to use SQLite 3.28.0.

@item 
bpo-37267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37267}: On Windows, @ref{1132,,os.dup()} no longer creates an inheritable fd
when handling a character file.

@item 
bpo-36779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36779}: Ensure @code{time.tzname} is correct on Windows when the active
code page is set to CP_UTF7 or CP_UTF8.

@item 
bpo-32587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32587}: Make @ref{1133,,winreg.REG_MULTI_SZ} support zero-length strings.

@item 
bpo-28269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28269}: Replace use of @code{strcasecmp()} for the system function
@code{_stricmp()}. Patch by Minmin Gong.

@item 
bpo-36590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36590}: Add native Bluetooth RFCOMM support to socket module.
@end itemize

@node macOS<20>,IDLE<20>,Windows<23>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id214}@anchor{1134}
@subsubsection macOS



@itemize -

@item 
bpo-38117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38117}: Updated OpenSSL to 1.1.1d in macOS installer.

@item 
bpo-38089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38089}: Move Azure Pipelines to latest VM versions and make macOS tests
optional

@item 
bpo-18049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18049}: Increase the default stack size of threads from 5MB to 16MB on
macOS, to match the stack size of the main thread. This avoids crashes on
deep recursion in threads.

@item 
bpo-34602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34602}: Avoid test suite failures on macOS by no longer calling
resource.setrlimit to increase the process stack size limit at runtime.
The runtime change is no longer needed since the interpreter is being
built with a larger default stack size.

@item 
bpo-35360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35360}: Update macOS installer to use SQLite 3.28.0.

@item 
bpo-34631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34631}: Updated OpenSSL to 1.1.1c in macOS installer.
@end itemize

@node IDLE<20>,Tools/Demos<8>,macOS<20>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id215}@anchor{1135}
@subsubsection IDLE



@itemize -

@item 
bpo-26353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26353}: Stop adding newline when saving an IDLE shell window.

@item 
bpo-4630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4630}: Add an option to toggle IDLE's cursor blink for shell, editor,
and output windows.  See Settings, General, Window Preferences, Cursor
Blink. Patch by Zackery Spytz.

@item 
bpo-38598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38598}: Do not try to compile IDLE shell or output windows

@item 
bpo-36698@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36698}: IDLE no longer fails when write non-encodable characters to
stderr.  It now escapes them with a backslash, as the regular Python
interpreter. Added the @code{errors} field to the standard streams.

@item 
bpo-35379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35379}: When exiting IDLE, catch any AttributeError.  One happens when
EditorWindow.close is called twice.  Printing a traceback, when IDLE is
run from a terminal, is useless and annoying.

@item 
bpo-38183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38183}: To avoid problems, test_idle ignores the user config directory.
It no longer tries to create or access .idlerc or any files within. Users
must run IDLE to discover problems with saving settings.

@item 
bpo-38077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38077}: IDLE no longer adds 'argv' to the user namespace when
initializing it.  This bug only affected 3.7.4 and 3.8.0b2 to 3.8.0b4.

@item 
bpo-38041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38041}: Shell restart lines now fill the window width, always start
with '=', and avoid wrapping unnecessarily. The line will still wrap if
the included file name is long relative to the width.

@item 
bpo-35771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35771}: To avoid occasional spurious test_idle failures on slower
machines, increase the @code{hover_delay} in test_tooltip.

@item 
bpo-37824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37824}: Properly handle user input warnings in IDLE shell. Cease
turning SyntaxWarnings into SyntaxErrors.

@item 
bpo-37929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37929}: IDLE Settings dialog now closes properly when there is no shell
window.

@item 
bpo-37902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37902}: Add mousewheel scrolling for IDLE module, path, and stack
browsers. Patch by George Zhang.

@item 
bpo-37849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37849}: Fixed completions list appearing too high or low when shown
above the current line.

@item 
bpo-36419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36419}: Refactor IDLE autocomplete and improve testing.

@item 
bpo-37748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37748}: Reorder the Run menu.  Put the most common choice, Run Module,
at the top.

@item 
bpo-37692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37692}: Improve highlight config sample with example shell interaction
and better labels for shell elements.

@item 
bpo-37628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37628}: Settings dialog no longer expands with font size.

@item 
bpo-37627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37627}: Initialize the Customize Run dialog with the command line
arguments most recently entered before.  The user can optionally edit
before submitting them.

@item 
bpo-33610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33610}: Fix code context not showing the correct context when first
toggled on.

@item 
bpo-37530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37530}: Optimize code context to reduce unneeded background activity.
Font and highlight changes now occur along with text changes instead of
after a random delay.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: Cleanup @code{config.py} by inlining @code{RemoveFile} and
simplifying the handling of @code{file} in @code{CreateConfigHandlers}.

@item 
bpo-37325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37325}: Fix tab focus traversal order for help source and custom run
dialogs.

@item 
bpo-37321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37321}: Both subprocess connection error messages now refer to the
'Startup failure' section of the IDLE doc.

@item 
bpo-17535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17535}: Add optional line numbers for IDLE editor windows.  Windows
open without line numbers unless set otherwise in the General tab of the
configuration dialog.

@item 
bpo-26806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26806}: To compensate for stack frames added by IDLE and avoid possible
problems with low recursion limits, add 30 to limits in the user code
execution process.  Subtract 30 when reporting recursion limits to make
this addition mostly transparent.

@item 
bpo-37177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37177}: Properly 'attach' search dialogs to their main window so that
they behave like other dialogs and do not get hidden behind their main
window.

@item 
bpo-37039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37039}: Adjust "Zoom Height" to individual screens by momentarily
maximizing the window on first use with a particular screen.  Changing
screen settings may invalidate the saved height.  While a window is
maximized, "Zoom Height" has no effect.

@item 
bpo-35763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35763}: Make calltip reminder about '/' meaning positional-only less
obtrusive by only adding it when there is room on the first line.

@item 
bpo-5680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5680}: Add 'Run... Customized' to the Run menu to run a module with
customized settings.  Any 'command line arguments' entered are added to
sys.argv. One can suppress the normal Shell main module restart.

@item 
bpo-36390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36390}: Gather Format menu functions into format.py.  Combine
paragraph.py, rstrip.py, and format methods from editor.py.
@end itemize

@node Tools/Demos<8>,C API<16>,IDLE<20>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id216}@anchor{1136}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-38118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38118}: Update Valgrind suppression file to ignore a false alarm in
@ref{1137,,PyUnicode_Decode()} when using GCC builtin strcmp().

@item 
bpo-38347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38347}: pathfix.py: Assume all files that end on '.py' are Python
scripts when working recursively.

@item 
bpo-37803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37803}: pdb's @code{--help} and @code{--version} long options now work.

@item 
bpo-37942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37942}: Improve ArgumentClinic converter for floats.

@item 
bpo-37704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37704}: Remove @code{Tools/scripts/h2py.py}: use cffi to access a C API in
Python.

@item 
bpo-37675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37675}: 2to3 now works when run from a zipped standard library.

@item 
bpo-37034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37034}: Argument Clinic now uses the argument name on errors with
keyword-only argument instead of their position. Patch contributed by Rémi
Lapeyre.

@item 
bpo-37064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37064}: Add option -k to pathscript.py script: preserve shebang flags.
Add option -a to pathscript.py script: add flags.
@end itemize

@node C API<16>,,Tools/Demos<8>,Python 3 9 0 alpha 1
@anchor{whatsnew/changelog id217}@anchor{1138}
@subsubsection C API



@itemize -

@item 
bpo-37633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37633}: Re-export some function compatibility wrappers for macros in
@code{pythonrun.h}.

@item 
bpo-38644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38644}: Provide @ref{252,,Py_EnterRecursiveCall()} and
@ref{253,,Py_LeaveRecursiveCall()} as regular functions for the limited API.
Previously, there were defined as macros, but these macros didn't work
with the limited API which cannot access @code{PyThreadState.recursion_depth}
field. Remove @code{_Py_CheckRecursionLimit} from the stable ABI.

@item 
bpo-38650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38650}: The global variable @ref{263,,PyStructSequence_UnnamedField} is
now a constant and refers to a constant string.

@item 
bpo-38540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38540}: Fixed possible leak in @ref{1139,,PyArg_Parse()} and similar
functions for format units @code{"es#"} and @code{"et#"} when the macro
@code{PY_SSIZE_T_CLEAN} is not defined.

@item 
bpo-38395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38395}: Fix a crash in @ref{381,,weakref.proxy} objects due to incorrect
lifetime management when calling some associated methods that may delete
the last reference to object being referenced by the proxy. Patch by Pablo
Galindo.

@item 
bpo-36389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36389}: The @code{_PyObject_CheckConsistency()} function is now also
available in release mode. For example, it can be used to debug a crash in
the @code{visit_decref()} function of the GC.

@item 
bpo-38266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38266}: Revert the removal of PyThreadState_DeleteCurrent() with
documentation.

@item 
bpo-38303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38303}: Update audioop extension module to use the stable ABI
(PEP-384). Patch by Tyler Kieft.

@item 
bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234}: @ref{3a4,,Py_SetPath()} now sets @ref{3a5,,sys.executable} to the
program full path (@ref{3a6,,Py_GetProgramFullPath()}) rather than to the
program name (@ref{3a7,,Py_GetProgramName()}).

@item 
bpo-38234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38234}: Python ignored arguments passed to @ref{3a4,,Py_SetPath()},
@ref{113a,,Py_SetPythonHome()} and @ref{113b,,Py_SetProgramName()}: fix Python
initialization to use specified arguments.

@item 
bpo-38205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38205}: The @ref{52f,,Py_UNREACHABLE()} macro now calls
@ref{267,,Py_FatalError()}.

@item 
bpo-38140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=38140}: Make dict and weakref offsets opaque for C heap types by
passing the offsets through PyMemberDef

@item 
bpo-15088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15088}: The C function @code{PyGen_NeedsFinalizing} has been removed. It
was not documented, tested or used anywhere within CPython after the
implementation of 
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442}. Patch by Joannah Nanjekye. (Patch by Joannah
Nanjekye)

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Options added by @code{PySys_AddXOption()} are now handled the
same way than @code{PyConfig.xoptions} and command line @code{-X} options.

@item 
bpo-37926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37926}: Fix a crash in @code{PySys_SetArgvEx(0, NULL, 0)}.

@item 
bpo-37879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37879}: Fix subtype_dealloc to suppress the type decref when the base
type is a C heap type

@item 
bpo-37645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37645}: Add @code{_PyObject_FunctionStr()} to get a user-friendly
string representation of a function-like object. Patch by Jeroen Demeyer.

@item 
bpo-29548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29548}: The functions @code{PyEval_CallObject}, @code{PyEval_CallFunction},
@code{PyEval_CallMethod} and @code{PyEval_CallObjectWithKeywords} are
deprecated. Use @ref{23d,,PyObject_Call()} and its variants instead.

@item 
bpo-37151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37151}: @code{PyCFunction_Call} is now a deprecated alias of
@ref{23d,,PyObject_Call()}.

@item 
bpo-37540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37540}: The vectorcall protocol now requires that the caller passes
only strings as keyword names.

@item 
bpo-37207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37207}: The vectorcall protocol is now enabled for @code{type} objects:
set @code{tp_vectorcall} to a vectorcall function to be used instead of
@code{tp_new} and @code{tp_init} when calling the class itself.

@item 
bpo-21120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21120}: Exclude Python-ast.h, ast.h and asdl.h from the limited API.

@item 
bpo-37483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37483}: Add new function @code{_PyObject_CallOneArg} for calling an object
with one positional argument.

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Add @code{PyConfig_SetWideStringList()} function.

@item 
bpo-37337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37337}: Add fast functions for calling methods:
@code{_PyObject_VectorcallMethod()}, @code{_PyObject_CallMethodNoArgs()}
and @code{_PyObject_CallMethodOneArg()}.

@item 
bpo-28805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28805}: The @ref{113c,,METH_FASTCALL} calling convention has been
documented.

@item 
bpo-37221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37221}: The new function @ref{3a2,,PyCode_NewWithPosOnlyArgs()} allows to
create code objects like @ref{3a3,,PyCode_New()}, but with an extra
@emph{posonlyargcount} parameter for indicating the number of positonal-only
arguments.

@item 
bpo-37215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37215}: Fix dtrace issue introduce by bpo-36842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36842}

@item 
bpo-37194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37194}: Add a new public @ref{251,,PyObject_CallNoArgs()} function to the
C API: call a callable Python object without any arguments. It is the most
efficient way to call a callback without any argument. On x86-64, for
example, @code{PyObject_CallFunctionObjArgs(func, NULL)} allocates 960 bytes
on the stack per call, whereas @code{PyObject_CallNoArgs(func)} only
allocates 624 bytes per call.

@item 
bpo-37170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37170}: Fix the cast on error in
@ref{113d,,PyLong_AsUnsignedLongLongMask()}.

@item 
bpo-35381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35381}: Convert posixmodule.c statically allocated types
@code{DirEntryType} and @code{ScandirIteratorType} to heap-allocated types.

@item 
bpo-34331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34331}: Use singular/plural noun in error message when instantiating an
abstract class with non-overriden abstract method(s).
@end itemize

@node Python 3 8 0 beta 1,Python 3 8 0 alpha 4,Python 3 9 0 alpha 1,更新日志
@anchor{whatsnew/changelog python-3-8-0-beta-1}@anchor{113e}
@subsection Python 3.8.0 beta 1


@emph{Release date: 2019-06-04}

@menu
* Security: Security<19>. 
* Core and Builtins: Core and Builtins<30>. 
* Library: Library<32>. 
* Documentation: Documentation<22>. 
* Tests: Tests<23>. 
* Build: Build<22>. 
* Windows: Windows<24>. 
* macOS: macOS<21>. 
* IDLE: IDLE<21>. 
* Tools/Demos: Tools/Demos<9>. 
* C API: C API<17>. 

@end menu

@node Security<19>,Core and Builtins<30>,,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id218}@anchor{113f}
@subsubsection Security



@itemize -

@item 
bpo-35907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35907}: CVE-2019-9948: Avoid file reading by disallowing
@code{local-file://} and @code{local_file://} URL schemes in
@code{URLopener().open()} and @code{URLopener().retrieve()} of
@ref{129,,urllib.request}.

@item 
bpo-33529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33529}: Prevent fold function used in email header encoding from
entering infinite loop when there are too many non-ASCII characters in a
header.

@item 
bpo-33164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33164}: Updated blake2 implementation which uses secure memset
implementation provided by platform.
@end itemize

@node Core and Builtins<30>,Library<32>,Security<19>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id219}@anchor{1140}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-35814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35814}: Allow unpacking in the right hand side of annotated
assignments. In particular, @code{t: Tuple[int, ...] = x, y, *z} is now
allowed.

@item 
bpo-37126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37126}: All structseq objects are now tracked by the garbage collector.
Patch by Pablo Galindo.

@item 
bpo-37122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37122}: Make the @emph{co_argcount} attribute of code objects represent the
total number of positional arguments (including positional-only
arguments). The value of @emph{co_posonlyargcount} can be used to distinguish
which arguments are positional only, and the difference (@emph{co_argcount} -
@emph{co_posonlyargcount}) is the number of positional-or-keyword arguments.
Patch by Pablo Galindo.

@item 
bpo-20092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20092}: Constructors of @ref{205,,int}, @ref{1fe,,float} and
@ref{2c8,,complex} will now use the @ref{2c9,,__index__()} special
method, if available and the corresponding method @ref{2ca,,__int__()},
@ref{2cb,,__float__()} or @ref{2cc,,__complex__()} is not available.

@item 
bpo-37087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37087}: Add native thread ID (TID) support to OpenBSD.

@item 
bpo-26219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26219}: Implemented per opcode cache mechanism and @code{LOAD_GLOBAL}
instruction use it. @code{LOAD_GLOBAL} is now about 40% faster. Contributed
by Yury Selivanov, and Inada Naoki.

@item 
bpo-37072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37072}: Fix crash in PyAST_FromNodeObject() when flags is NULL.

@item 
bpo-37029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37029}: Freeing a great many small objects could take time quadratic in
the number of arenas, due to using linear search to keep @code{obmalloc.c}'s
list of usable arenas sorted by order of number of free memory pools.
This is accomplished without search now, leaving the worst-case time
linear in the number of arenas.  For programs where this quite visibly
matters (typically with more than 100 thousand small objects alive
simultaneously), this can greatly reduce the time needed to release their
memory.

@item 
bpo-26423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26423}: Fix possible overflow in @code{wrap_lenfunc()} when @code{sizeof(long)
< sizeof(Py_ssize_t)} (e.g., 64-bit Windows).

@item 
bpo-37050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37050}: Improve the AST for "debug" f-strings, which use '=' to print
out the source of the expression being evaluated.  Delete expr_text from
the FormattedValue node, and instead use a Constant string node (possibly
merged with adjacent constant expressions inside the f-string).

@item 
bpo-22385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22385}: The @ref{72e,,bytes.hex}, @ref{72f,,bytearray.hex}, and @ref{730,,memoryview.hex} methods
as well as the @ref{1141,,binascii.hexlify} and @code{b2a_hex} functions now have the
ability to include an optional separator between hex bytes.  This
functionality was inspired by MicroPython's hexlify implementation.

@item 
bpo-26836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26836}: Add @ref{327,,os.memfd_create()}.

@item 
bpo-37032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37032}: Added new @code{replace()} method to the code type
(@ref{2d4,,types.CodeType}).

@item 
bpo-37007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37007}: Implement @ref{354,,socket.if_nameindex()},
@ref{355,,socket.if_nametoindex()}, and @ref{356,,socket.if_indextoname()} on
Windows.

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: @ref{1142,,PyErr_WriteUnraisable()} now creates a traceback object
if there is no current traceback. Moreover, call
@ref{1143,,PyErr_NormalizeException()} and @ref{1144,,PyException_SetTraceback()}
to normalize the exception value. Ignore any error.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: Only accept text after @code{# type: ignore} if the first character
is ASCII. This is to disallow things like @code{# type: ignoreé}.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: Store text appearing after a @code{# type: ignore} comment in the
AST. For example a type ignore like @code{# type: ignore[E1000]} will have the
string @code{"[E1000]"} stored in its AST node.

@item 
bpo-2180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2180}: Treat line continuation at EOF as a @code{SyntaxError} by Anthony
Sottile.

@item 
bpo-36907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36907}: Fix a crash when calling a C function with a keyword dict
(@code{f(**kwargs)}) and changing the dict @code{kwargs} while that function is
running.

@item 
bpo-36946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36946}: Fix possible signed integer overflow when handling slices.

@item 
bpo-36826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36826}: Add NamedExpression kind support to ast_unparse.c

@item 
bpo-1875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1875}: A @ref{562,,SyntaxError} is now raised if a code blocks that will be
optimized away (e.g. if conditions that are always false) contains syntax
errors. Patch by Pablo Galindo.

@item 
bpo-36027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36027}: Allow computation of modular inverses via three-argument
@code{pow}: the second argument is now permitted to be negative in the case
where the first and third arguments are relatively prime.

@item 
bpo-36861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36861}: Update the Unicode database to version 12.1.0.

@item 
bpo-28866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28866}: Avoid caching attributes of classes which type defines mro() to
avoid a hard cache invalidation problem.

@item 
bpo-36851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36851}: The @code{FrameType} stack is now correctly cleaned up if the
execution ends with a return and the stack is not empty.

@item 
bpo-34616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34616}: The @code{compile()} builtin functions now support the
@code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} flag,  which allow to compile sources
that  contains top-level @code{await}, @code{async with} or @code{async for}. This
is useful to evaluate async-code from with an already async functions; for
example in a custom REPL.

@item 
bpo-36842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36842}: Implement PEP 578, adding sys.audit, io.open_code and related
APIs.

@item 
bpo-27639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27639}: Correct return type for UserList slicing operations. Patch by
Michael Blahay, Erick Cervantes, and vaultah

@item 
bpo-36737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36737}: Move PyRuntimeState.warnings into per-interpreter state (via
"module state").

@item 
bpo-36793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36793}: Removed @code{__str__} implementations from builtin types
@ref{2c4,,bool}, @ref{205,,int}, @ref{1fe,,float}, @ref{2c8,,complex} and few
classes from the standard library. They now inherit @code{__str__()} from
@ref{3da,,object}.

@item 
bpo-36817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36817}: Add a @code{=} feature f-strings for debugging. This can precede
@code{!s}, @code{!r}, or @code{!a}. It produces the text of the expression,
followed by an equal sign, followed by the repr of the value of the
expression. So @code{f'@{3*9+15=@}'} would be equal to the string
@code{'3*9+15=42'}.  If @code{=} is specified, the default conversion is set to
@code{!r}, unless a format spec is given, in which case the formatting
behavior is unchanged, and __format__ will be used.

@item 
bpo-24048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24048}: Save the live exception during import.c's @code{remove_module()}.

@item 
bpo-27987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27987}: pymalloc returns memory blocks aligned by 16 bytes, instead of
8 bytes, on 64-bit platforms to conform x86-64 ABI. Recent compilers
assume this alignment more often. Patch by Inada Naoki.

@item 
bpo-36601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36601}: A long-since-meaningless check for @code{getpid() == main_pid} was
removed from Python's internal C signal handler.

@item 
bpo-36594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36594}: Fix incorrect use of @code{%p} in format strings. Patch by Zackery
Spytz.

@item 
bpo-36045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36045}: builtins.help() now prefixes @code{async} for async functions

@item 
bpo-36084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36084}: Add native thread ID (TID) to threading.Thread objects
(supported platforms: Windows, FreeBSD, Linux, macOS)

@item 
bpo-36035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36035}: Added fix for broken symlinks in combination with pathlib

@item 
bpo-35983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35983}: Added new trashcan macros to deal with a double deallocation
that could occur when the @code{tp_dealloc} of a subclass calls the
@code{tp_dealloc} of a base class and that base class uses the trashcan
mechanism. Patch by Jeroen Demeyer.

@item 
bpo-20602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20602}: Do not clear @ref{c17,,sys.flags} and @ref{1145,,sys.float_info}
during shutdown. Patch by Zackery Spytz.

@item 
bpo-26826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26826}: Expose @code{copy_file_range()} as a low level API in the
@ref{c4,,os} module.

@item 
bpo-32388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32388}: Remove cross-version binary compatibility requirement in
tp_flags.

@item 
bpo-31862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31862}: Port binascii to PEP 489 multiphase initialization. Patch by
Marcel Plch.
@end itemize

@node Library<32>,Documentation<22>,Core and Builtins<30>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id220}@anchor{1146}
@subsubsection Library



@itemize -

@item 
bpo-37128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37128}: Added @ref{31e,,math.perm()}.

@item 
bpo-37120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37120}: Add SSLContext.num_tickets to control the number of TLSv1.3
session tickets.

@item 
bpo-12202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12202}: Fix the error handling in
@ref{1147,,msilib.SummaryInformation.GetProperty()}. Patch by Zackery Spytz.

@item 
bpo-26835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26835}: The fcntl module now contains file sealing constants for
sealing of memfds.

@item 
bpo-29262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29262}: Add @code{get_origin()} and @code{get_args()} introspection helpers
to @code{typing} module.

@item 
bpo-12639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12639}: @ref{1148,,msilib.Directory.start_component()} no longer fails if
@emph{keyfile} is not @code{None}.

@item 
bpo-36999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36999}: Add the @code{asyncio.Task.get_coro()} method to publicly expose
the tasks's coroutine object.

@item 
bpo-35246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35246}: Make @ref{3bc,,asyncio.create_subprocess_exec()} accept path-like
arguments.

@item 
bpo-35279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35279}: Change default @emph{max_workers} of @code{ThreadPoolExecutor} from
@code{cpu_count() * 5} to @code{min(32, cpu_count() + 4)}.  Previous value was
unreasonably large on many cores machines.

@item 
bpo-37076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37076}: @ref{1149,,_thread.start_new_thread()} now logs uncaught exception
raised by the function using @ref{361,,sys.unraisablehook()}, rather than
@ref{1ae,,sys.excepthook()}, so the hook gets access to the function which
raised the exception.

@item 
bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}: On macOS, the @ref{b7,,multiprocessing} module now uses @emph{spawn}
start method by default.

@item 
bpo-37054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37054}: Fix destructor @code{_pyio.BytesIO} and
@code{_pyio.TextIOWrapper}: initialize their @code{_buffer} attribute as
soon as possible (in the class body), because it's used by @code{__del__()}
which calls @code{close()}.

@item 
bpo-37058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37058}: PEP 544: Add @code{Protocol} and @code{@@runtime_checkable} to the
@code{typing} module.

@item 
bpo-36933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36933}: The functions @code{sys.set_coroutine_wrapper} and
@code{sys.get_coroutine_wrapper} that were deprecated and marked for removal
in 3.8 have been removed.

@item 
bpo-37047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37047}: Handle late binding and attribute access in
@ref{379,,unittest.mock.AsyncMock} setup for autospeccing. Document newly
implemented async methods in @ref{87e,,unittest.mock.MagicMock}.

@item 
bpo-37049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37049}: PEP 589: Add @code{TypedDict} to the @code{typing} module.

@item 
bpo-37046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37046}: PEP 586: Add @code{Literal} to the @code{typing} module.

@item 
bpo-37045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37045}: PEP 591: Add @code{Final} qualifier and @code{@@final} decorator to
the @code{typing} module.

@item 
bpo-37035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37035}: Don't log OSError based exceptions if a fatal error has
occurred in asyncio transport. Peer can generate almost any OSError, user
cannot avoid these exceptions by fixing own code. Errors are still
propagated to user code, it's just logging them is pointless and pollute
asyncio logs.

@item 
bpo-37001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37001}: @ref{114a,,symtable.symtable()} now accepts the same input types for
source code as the built-in @ref{2ee,,compile()} function. Patch by Dino
Viehland.

@item 
bpo-37028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37028}: Implement asyncio REPL

@item 
bpo-37027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37027}: Return safe to use proxy socket object from
transport.get_extra_info('socket')

@item 
bpo-32528@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32528}: Make asyncio.CancelledError a BaseException.

This will address the common mistake many asyncio users make: an "except
Exception" clause breaking Tasks cancellation.

In addition to this change, we stop inheriting asyncio.TimeoutError and
asyncio.InvalidStateError from their concurrent.futures.* counterparts.
There's no point for these exceptions to share the inheritance chain.

@item 
bpo-1230540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1230540}: Add a new @ref{365,,threading.excepthook()} function which handles
uncaught @ref{366,,threading.Thread.run()} exception. It can be overridden to
control how uncaught @ref{366,,threading.Thread.run()} exceptions are handled.

@item 
bpo-36996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36996}: Handle @ref{881,,unittest.mock.patch()} used as a decorator on async
functions.

@item 
bpo-37008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37008}: Add support for calling @ref{77f,,next()} with the mock resulting
from @ref{114b,,unittest.mock.mock_open()}

@item 
bpo-27737@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27737}: Allow whitespace only header encoding in @code{email.header} - by
Batuhan Taskaya

@item 
bpo-36969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36969}: PDB command @code{args} now  display positional only arguments.
Patch contributed by Rémi Lapeyre.

@item 
bpo-36969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36969}: PDB command @code{args} now  display keyword only arguments. Patch
contributed by Rémi Lapeyre.

@item 
bpo-36983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36983}: Add missing names to @code{typing.__all__}: @code{ChainMap},
@code{ForwardRef}, @code{OrderedDict} - by Anthony Sottile.

@item 
bpo-36972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36972}: Add SupportsIndex protocol to the typing module to allow type
checking to detect classes that can be passed to @ref{d36,,hex()}, @ref{d35,,oct()} and
@ref{d10,,bin()}.

@item 
bpo-32972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32972}: Implement @code{unittest.IsolatedAsyncioTestCase} to help testing
asyncio-based code.

@item 
bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952}: @ref{3d7,,fileinput.input()} and @ref{3ac,,fileinput.FileInput}
@strong{bufsize} argument has been removed (was deprecated and ignored since
Python 3.6), and as a result the @strong{mode} and @strong{openhook} arguments have
been made keyword-only.

@item 
bpo-36952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36952}: Starting with Python 3.3, importing ABCs from
@ref{1d,,collections} is deprecated, and import should be done from
@ref{1e,,collections.abc}. Still being able to import from @ref{1d,,collections}
was marked for removal in 3.8, but has been delayed to 3.9; documentation
and @code{DeprecationWarning} clarified.

@item 
bpo-36949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36949}: Implement __repr__ for WeakSet objects.

@item 
bpo-36948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36948}: Fix @ref{e48,,NameError} in
@ref{114c,,urllib.request.URLopener.retrieve()}. Patch by Karthikeyan
Singaravelan.

@item 
bpo-33524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33524}: Fix the folding of email header when the max_line_length is 0
or None and the header contains non-ascii characters.  Contributed by
Licht Takeuchi (@@Licht-T).

@item 
bpo-24564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24564}: @ref{b5b,,shutil.copystat()} now ignores @ref{114d,,errno.EINVAL} on
@ref{b32,,os.setxattr()} which may occur when copying files on filesystems
without extended attributes support.

Original patch by Giampaolo Rodola, updated by Ying Wang.

@item 
bpo-36888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36888}: Python child processes can now access the status of their
parent process using multiprocessing.process.parent_process

@item 
bpo-36921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36921}: Deprecate @code{@@coroutine} for sake of @code{async def}.

@item 
bpo-25652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25652}: Fix bug in @code{__rmod__} of @code{UserString} - by Batuhan Taskaya.

@item 
bpo-36916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36916}: Remove a message about an unhandled exception in a task when
writer.write() is used without await and writer.drain() fails with an
exception.

@item 
bpo-36889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36889}: Introduce @code{asyncio.Stream} class that merges
@ref{114e,,asyncio.StreamReader} and @ref{114f,,asyncio.StreamWriter}
functionality. @code{asyncio.Stream} can work in readonly, writeonly and
readwrite modes. Provide @code{asyncio.connect()},
@code{asyncio.connect_unix()}, @code{asyncio.connect_read_pipe()} and
@code{asyncio.connect_write_pipe()} factories to open
@code{asyncio.Stream} connections. Provide @code{asyncio.StreamServer}
and @code{UnixStreamServer} to serve servers with asyncio.Stream API.
Modify @ref{3bd,,asyncio.create_subprocess_shell()} and
@ref{3bc,,asyncio.create_subprocess_exec()} to use @code{asyncio.Stream}
instead of deprecated @code{StreamReader} and @code{StreamWriter}.
Deprecate @ref{114e,,asyncio.StreamReader} and @ref{114f,,asyncio.StreamWriter}.
Deprecate usage of private classes, e.g.
@code{asyncio.FlowControlMixing} and
@code{asyncio.StreamReaderProtocol} outside of asyncio package.

@item 
bpo-36845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36845}: Added validation of integer prefixes to the construction of IP
networks and interfaces in the ipaddress module.

@item 
bpo-23378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23378}: Add an extend action to argparser.

@item 
bpo-36867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36867}: Fix a bug making a SharedMemoryManager instance and its parent
process use two separate resource_tracker processes.

@item 
bpo-23896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23896}: Adds a grammar to lib2to3.pygram that contains exec as a
function not as statement.

@item 
bpo-36895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36895}: The function @code{time.clock()} was deprecated in 3.3 in favor of
@code{time.perf_counter()} and marked for removal in 3.8, it has removed.

@item 
bpo-35545@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35545}: Fix asyncio discarding IPv6 scopes when ensuring hostname
resolutions internally

@item 
bpo-36887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36887}: Add new function @ref{320,,math.isqrt()} to compute integer square
roots.

@item 
bpo-34632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34632}: Introduce the @code{importlib.metadata} module with (provisional)
support for reading metadata from third-party packages.

@item 
bpo-36878@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36878}: When using @code{type_comments=True} in @ref{2dd,,ast.parse}, treat @code{# type:
ignore} followed by a non-alphanumeric character and then arbitrary text
as a type ignore, instead of requiring nothing but whitespace or another
comment. This is to permit formations such as @code{# type: ignore[E1000]}.

@item 
bpo-36778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36778}: @code{cp65001} encoding (Windows code page 65001) becomes an alias
to @code{utf_8} encoding.

@item 
bpo-36867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36867}: The multiprocessing.resource_tracker replaces the
multiprocessing.semaphore_tracker module. Other than semaphores,
resource_tracker also tracks shared_memory segments.

@item 
bpo-30262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30262}: The @code{Cache} and @code{Statement} objects of the @ref{f2,,sqlite3}
module are not exposed to the user.  Patch by Aviv Palivoda.

@item 
bpo-24538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24538}: In @ref{b5b,,shutil.copystat()}, first copy extended file attributes and
then file permissions, since extended attributes can only be set on the
destination while it is still writeable.

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: Add new @ref{361,,sys.unraisablehook()} function which can be
overridden to control how "unraisable exceptions" are handled. It is
called when an exception has occurred but there is no way for Python to
handle it. For example, when a destructor raises an exception or during
garbage collection (@ref{362,,gc.collect()}).

@item 
bpo-36832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36832}: Introducing @code{zipfile.Path}, a pathlib-compatible wrapper for
traversing zip files.

@item 
bpo-36814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36814}: Fix an issue where os.posix_spawnp() would incorrectly raise a
TypeError when file_actions is None.

@item 
bpo-33110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33110}: Handle exceptions raised by functions added by
concurrent.futures add_done_callback correctly when the Future has already
completed.

@item 
bpo-26903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26903}: Limit @code{max_workers} in @code{ProcessPoolExecutor} to 61 to work
around a WaitForMultipleObjects limitation.

@item 
bpo-36813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36813}: Fix @ref{80d,,QueueListener} to call
@code{queue.task_done()} upon stopping. Patch by Bar Harel.

@item 
bpo-36806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36806}: Forbid creation of asyncio stream objects like StreamReader,
StreamWriter, Process, and their protocols outside of asyncio package.

@item 
bpo-36802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36802}: Provide both sync and async calls for StreamWriter.write() and
StreamWriter.close()

@item 
bpo-36801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36801}: Properly handle SSL connection closing in asyncio
StreamWriter.drain() call.

@item 
bpo-36785@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36785}: Implement PEP 574 (pickle protocol 5 with out-of-band buffers).

@item 
bpo-36772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36772}: functools.lru_cache() can now be used as a straight decorator
in addition to its existing usage as a function that returns a decorator.

@item 
bpo-6584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6584}: Add a @ref{30a,,BadGzipFile} exception to the @ref{8b,,gzip}
module.

@item 
bpo-36748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36748}: Optimized write buffering in C implementation of
@code{TextIOWrapper}. Writing ASCII string to @code{TextIOWrapper} with ascii,
latin1, or utf-8 encoding is about 20% faster.  Patch by Inada Naoki.

@item 
bpo-8138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8138}: Don't mark @code{wsgiref.simple_server.SimpleServer} as
multi-threaded since @code{wsgiref.simple_server.WSGIServer} is
single-threaded.

@item 
bpo-22640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22640}: @ref{34a,,py_compile.compile()} now supports silent mode. Patch by
Joannah Nanjekye

@item 
bpo-29183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29183}: Fix double exceptions in @ref{1150,,wsgiref.handlers.BaseHandler}
by calling its @code{close()} method only
when no exception is raised.

@item 
bpo-36548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36548}: Improved the repr of regular expression flags.

@item 
bpo-36542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36542}: The signature of Python functions can now be overridden by
specifying the @code{__text_signature__} attribute.

@item 
bpo-36533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36533}: Reinitialize logging.Handler locks in forked child processes
instead of attempting to acquire them all in the parent before forking
only to be released in the child process.  The acquire/release pattern was
leading to deadlocks in code that has implemented any form of chained
logging handlers that depend upon one another as the lock acquisition
order cannot be guaranteed.

@item 
bpo-35252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35252}: Throw a TypeError instead of an AssertionError when using an
invalid type annotation with singledispatch.

@item 
bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}: Allow reduction methods to return a 6-item tuple where the 6th
item specifies a custom state-setting method that's called instead of the
regular @code{__setstate__} method.

@item 
bpo-35900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35900}: enable custom reduction callback registration for functions and
classes in _pickle.c, using the new Pickler's attribute
@code{reducer_override}

@item 
bpo-36368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36368}: Fix a bug crashing SharedMemoryManager instances in interactive
sessions after a ctrl-c (KeyboardInterrupt) was sent

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix mmap fail for VxWorks

@item 
bpo-27497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27497}: @ref{c55,,csv.DictWriter.writeheader()} now returns the return value
of the underlying @code{csv.Writer.writerow()} method. Patch contributed by
Ashish Nitin Patil.

@item 
bpo-36239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36239}: Parsing .mo files now ignores comments starting and ending with
#-#-#-#-#.

@item 
bpo-26707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26707}: Enable plistlib to read and write binary plist files that were
created as a KeyedArchive file. Specifically, this allows the plistlib to
process 0x80 tokens as UID objects.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add posix module support for VxWorks.

@item 
bpo-35125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35125}: Asyncio: Remove inner callback on outer cancellation in shield

@item 
bpo-35721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35721}: Fix @code{asyncio.SelectorEventLoop.subprocess_exec()} leaks
file descriptors if @code{Popen} fails and called with
@code{stdin=subprocess.PIPE}. Patch by Niklas Fiekas.

@item 
bpo-31855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31855}: @ref{114b,,unittest.mock.mock_open()} results now respects the
argument of read([size]). Patch contributed by Rémi Lapeyre.

@item 
bpo-35431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35431}: Implement @ref{31f,,math.comb()} that returns binomial coefficient,
that computes the number of ways to choose k items from n items without
repetition and without order. Patch by Yash Aggarwal and Keller Fuchs.

@item 
bpo-26660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26660}: Fixed permission errors in
@ref{c9e,,TemporaryDirectory} clean up. Previously
@code{TemporaryDirectory.cleanup()} failed when non-writeable or
non-searchable files or directories were created inside a temporary
directory.

@item 
bpo-34271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34271}: Add debugging helpers to ssl module. It's now possible to dump
key material and to trace TLS protocol. The default and stdlib contexts
also support SSLKEYLOGFILE env var.

@item 
bpo-26467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26467}: Added AsyncMock to support using unittest to mock asyncio
coroutines. Patch by Lisa Roach.

@item 
bpo-33569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33569}: dataclasses.InitVar: Exposes the type used to create the init
var.

@item 
bpo-34424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34424}: Fix serialization of messages containing encoded strings when
the policy.linesep is set to a multi-character string. Patch by Jens
Troeger.

@item 
bpo-34303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34303}: Performance of @ref{d3f,,functools.reduce()} is slightly improved.
Patch by Sergey Fedoseev.

@item 
bpo-33361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33361}: Fix a bug in @ref{1151,,codecs.StreamRecoder} where seeking might
leave old data in a buffer and break subsequent read calls. Patch by Ammar
Askar.

@item 
bpo-22454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22454}: The @ref{e8,,shlex} module now exposes @ref{34c,,shlex.join()}, the
inverse of @ref{211,,shlex.split()}. Patch by Bo Bayles.

@item 
bpo-31922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31922}: @code{asyncio.AbstractEventLoop.create_datagram_endpoint()}: Do
not connect UDP socket when broadcast is allowed. This allows to receive
replies after a UDP broadcast.

@item 
bpo-24882@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24882}: Change ThreadPoolExecutor to use existing idle threads before
spinning up new ones.

@item 
bpo-31961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31961}: Added support for bytes and path-like objects in
@ref{3e3,,subprocess.Popen()} on Windows.  The @emph{args} parameter now accepts a
@ref{47b,,path-like object} if @emph{shell} is @code{False} and a sequence containing
bytes and path-like objects. The @emph{executable} parameter now accepts a
bytes and @ref{47b,,path-like object}. The @emph{cwd} parameter now accepts a
bytes object. Based on patch by Anders Lorentsen.

@item 
bpo-33123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33123}: @ref{1152,,pathlib.Path.unlink} now accepts a @emph{missing_ok}
parameter to avoid a @ref{8b7,,FileNotFoundError} from being raised. Patch by
Robert Buchholz.

@item 
bpo-32941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32941}: Allow @ref{323,,mmap.mmap} objects to access the madvise() system
call (through @ref{324,,mmap.mmap.madvise()}).

@item 
bpo-22102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22102}: Added support for ZIP files with disks set to 0. Such files are
commonly created by builtin tools on Windows when use ZIP64 extension.
Patch by Francisco Facioni.

@item 
bpo-32515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32515}: trace.py can now run modules via python3 -m trace -t --module
module_name

@item 
bpo-32299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32299}: Changed @ref{1153,,unittest.mock.patch.dict()} to return the patched
dictionary when used as context manager. Patch by Vadim Tsander.

@item 
bpo-27141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27141}: Added a @code{__copy__()} to @code{collections.UserList} and
@code{collections.UserDict} in order to correctly implement shallow copying
of the objects. Patch by Bar Harel.

@item 
bpo-31829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31829}: @code{\r}, @code{\0} and @code{\x1a} (end-of-file on Windows) are now
escaped in protocol 0 pickles of Unicode strings. This allows to load them
without loss from files open in text mode in Python 2.

@item 
bpo-23395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23395}: @code{_thread.interrupt_main()} now avoids setting the Python
error status if the @code{SIGINT} signal is ignored or not handled by Python.
@end itemize

@node Documentation<22>,Tests<23>,Library<32>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id221}@anchor{1154}
@subsubsection Documentation



@itemize -

@item 
bpo-36896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36896}: Clarify that some types have unstable constructor signature
between Python versions.

@item 
bpo-36686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36686}: Improve documentation of the stdin, stdout, and stderr
arguments of the @code{asyncio.subprocess_exec} function to specify which
values are supported. Also mention that decoding as text is not supported.

Add a few tests to verify that the various values passed to the std*
arguments actually work.

@item 
bpo-36984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36984}: Improve version added references in @code{typing} module - by
Anthony Sottile.

@item 
bpo-36868@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36868}: What's new now mentions SSLContext.hostname_checks_common_name
instead of SSLContext.host_flags.

@item 
bpo-35924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35924}: Add a note to the @code{curses.addstr()} documentation to warn
that multiline strings can cause segfaults because of an ncurses bug.

@item 
bpo-36783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36783}: Added C API Documentation for Time_FromTimeAndFold and
PyDateTime_FromDateAndTimeAndFold as per PEP 495. Patch by Edison
Abahurire.

@item 
bpo-36797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36797}: More of the legacy distutils documentation has been either
pruned, or else more clearly marked as being retained solely until the
setuptools documentation covers it independently.

@item 
bpo-22865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22865}: Add detail to the documentation on the @ref{988,,pty.spawn} function.

@item 
bpo-35397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35397}: Remove deprecation and document urllib.parse.unwrap(). Patch
contributed by Rémi Lapeyre.

@item 
bpo-32995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32995}: Added the context variable in glossary.

@item 
bpo-33519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33519}: Clarify that @ref{25,,copy()} is not part of the @code{MutableSequence} ABC.

@item 
bpo-33482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33482}: Make @code{codecs.StreamRecoder.writelines} take a list of bytes.

@item 
bpo-25735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25735}: Added documentation for func factorial to indicate that returns
integer values

@item 
bpo-20285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20285}: Expand object.__doc__ (docstring) to make it clearer. Modify
pydoc.py so that help(object) lists object methods (for other classes,
help omits methods of the object base class.)
@end itemize

@node Tests<23>,Build<22>,Documentation<22>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id222}@anchor{1155}
@subsubsection Tests



@itemize -

@item 
bpo-37069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37069}: Modify test_coroutines, test_cprofile, test_generators,
test_raise, test_ssl and test_yield_from to use
@ref{112d,,test.support.catch_unraisable_exception()} rather than
@ref{1156,,test.support.captured_stderr()}.

@item 
bpo-37098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37098}: Fix test_memfd_create on older Linux Kernels.

@item 
bpo-37081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37081}: Test with OpenSSL 1.1.1c

@item 
bpo-36829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36829}: Add @ref{112d,,test.support.catch_unraisable_exception()}: context
manager catching unraisable exception using @ref{361,,sys.unraisablehook()}.

@item 
bpo-36915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36915}: The main regrtest process now always removes all temporary
directories of worker processes even if they crash or if they are killed
on KeyboardInterrupt (CTRL+c).

@item 
bpo-36719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36719}: "python3 -m test -jN ..." now continues the execution of next
tests when a worker process crash (CHILD_ERROR state). Previously, the
test suite stopped immediately. Use --failfast to stop at the first error.

@item 
bpo-36816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36816}: Update Lib/test/selfsigned_pythontestdotnet.pem to match
self-signed.pythontest.net's new TLS certificate.

@item 
bpo-35925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35925}: Skip httplib and nntplib networking tests when they would
otherwise fail due to a modern OS or distro with a default OpenSSL policy
of rejecting connections to servers with weak certificates.

@item 
bpo-36782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36782}: Add tests for several C API functions in the @ref{30,,datetime}
module. Patch by Edison Abahurire.

@item 
bpo-36342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36342}: Fix test_multiprocessing in test_venv if platform lacks
functioning sem_open.
@end itemize

@node Build<22>,Windows<24>,Tests<23>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id223}@anchor{1157}
@subsubsection Build



@itemize -

@item 
bpo-36721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36721}: To embed Python into an application, a new @code{--embed} option
must be passed to @code{python3-config --libs --embed} to get @code{-lpython3.8}
(link the application to libpython). To support both 3.8 and older, try
@code{python3-config --libs --embed} first and fallback to @code{python3-config
--libs} (without @code{--embed}) if the previous command fails.

Add a pkg-config @code{python-3.8-embed} module to embed Python into an
application: @code{pkg-config python-3.8-embed --libs} includes
@code{-lpython3.8}. To support both 3.8 and older, try @code{pkg-config
python-X.Y-embed --libs} first and fallback to @code{pkg-config python-X.Y
--libs} (without @code{--embed}) if the previous command fails (replace
@code{X.Y} with the Python version).

On the other hand, @code{pkg-config python3.8 --libs} no longer contains
@code{-lpython3.8}. C extensions must not be linked to libpython (except on
Android, case handled by the script); this change is backward incompatible
on purpose.

@item 
bpo-36786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36786}: "make install" now runs compileall in parallel.
@end itemize

@node Windows<24>,macOS<21>,Build<22>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id224}@anchor{1158}
@subsubsection Windows



@itemize -

@item 
bpo-36965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36965}: include of STATUS_CONTROL_C_EXIT without depending on MSC
compiler

@item 
bpo-35926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35926}: Update to OpenSSL 1.1.1b for Windows.

@item 
bpo-29883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29883}: Add Windows support for UDP transports for the Proactor Event
Loop. Patch by Adam Meily.

@item 
bpo-33407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33407}: The @code{Py_DEPRECATED()} macro has been implemented for
MSVC.
@end itemize

@node macOS<21>,IDLE<21>,Windows<24>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id225}@anchor{1159}
@subsubsection macOS



@itemize -

@item 
bpo-36231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36231}: Support building Python on macOS without /usr/include
installed. As of macOS 10.14, system header files are only available
within an SDK provided by either the Command Line Tools or the Xcode app.
@end itemize

@node IDLE<21>,Tools/Demos<9>,macOS<21>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id226}@anchor{115a}
@subsubsection IDLE



@itemize -

@item 
bpo-35610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35610}: Replace now redundant .context_use_ps1 with .prompt_last_line.
This finishes change started in bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}.

@item 
bpo-37038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37038}: Make idlelib.run runnable; add test clause.

@item 
bpo-36958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36958}: Print any argument other than None or int passed to SystemExit
or sys.exit().

@item 
bpo-36807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36807}: When saving a file, call os.fsync() so bits are flushed to e.g.
USB drive.

@item 
bpo-32411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32411}: In browser.py, remove extraneous sorting by line number since
dictionary was created in line number order.
@end itemize

@node Tools/Demos<9>,C API<17>,IDLE<21>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id227}@anchor{115b}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-37053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37053}: Handle strings like u"bar" correctly in
Tools/parser/unparse.py. Patch by Chih-Hsuan Yen.
@end itemize

@node C API<17>,,Tools/Demos<9>,Python 3 8 0 beta 1
@anchor{whatsnew/changelog id228}@anchor{115c}
@subsubsection C API



@itemize -

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Implement the 
@geindex Python 提高建议; PEP 587
PEP 587@footnote{https://www.python.org/dev/peps/pep-0587} "Python Initialization Configuration".

@item 
bpo-36379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36379}: Fix crashes when attempting to use the @emph{modulo} parameter when
@code{__ipow__} is implemented in C.

@item 
bpo-37107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=37107}: Update @ref{115d,,PyObject_CallMethodObjArgs()} and
@code{_PyObject_CallMethodIdObjArgs} to use @code{_PyObject_GetMethod} to avoid
creating a bound method object in many cases. Patch by Michael J.
Sullivan.

@item 
bpo-36974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36974}: Implement 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590}: Vectorcall: a fast calling protocol for
CPython. This is a new protocol to optimize calls of custom callable
objects.

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: @code{Py_Main()} now returns the exitcode rather than calling
@code{Py_Exit(exitcode)} when calling @code{PyErr_Print()} if the current
exception type is @code{SystemExit}.

@item 
bpo-36922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36922}: Add new type flag @code{Py_TPFLAGS_METHOD_DESCRIPTOR} for objects
behaving like unbound methods. These are objects supporting the
optimization given by the @code{LOAD_METHOD}/@code{CALL_METHOD} opcodes. See PEP
590.

@item 
bpo-36728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36728}: The @code{PyEval_ReInitThreads()} function has been removed
from the C API. It should not be called explicitly: use
@ref{3f8,,PyOS_AfterFork_Child()} instead.
@end itemize

@node Python 3 8 0 alpha 4,Python 3 8 0 alpha 3,Python 3 8 0 beta 1,更新日志
@anchor{whatsnew/changelog python-3-8-0-alpha-4}@anchor{115e}
@subsection Python 3.8.0 alpha 4


@emph{Release date: 2019-05-06}

@menu
* Security: Security<20>. 
* Core and Builtins: Core and Builtins<31>. 
* Library: Library<33>. 
* Documentation: Documentation<23>. 
* Tests: Tests<24>. 
* Build: Build<23>. 
* Windows: Windows<25>. 
* macOS: macOS<22>. 
* IDLE: IDLE<22>. 
* Tools/Demos: Tools/Demos<10>. 
* C API: C API<18>. 

@end menu

@node Security<20>,Core and Builtins<31>,,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id229}@anchor{115f}
@subsubsection Security



@itemize -

@item 
bpo-36742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36742}: Fixes mishandling of pre-normalization characters in
urlsplit().

@item 
bpo-30458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30458}: Address CVE-2019-9740 by disallowing URL paths with embedded
whitespace or control characters through into the underlying http client
request.  Such potentially malicious header injection URLs now cause an
http.client.InvalidURL exception to be raised.

@item 
bpo-35755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35755}: @ref{1031,,shutil.which()} now uses @code{os.confstr("CS_PATH")} if
available and if the 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} environment variable is not set.
Remove also the current directory from @code{posixpath.defpath}. On Unix,
@ref{1031,,shutil.which()} and the @ref{f9,,subprocess} module no longer search the
executable in the current directory if the 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} environment
variable is not set.
@end itemize

@node Core and Builtins<31>,Library<33>,Security<20>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id230}@anchor{1160}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36722}: In debug build, import now also looks for C extensions compiled
in release mode and for C extensions compiled in the stable ABI.

@item 
bpo-32849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32849}: Fix Python Initialization code on FreeBSD to detect properly
when stdin file descriptor (fd 0) is invalid.

@item 
bpo-36623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36623}: Remove parser headers and related function declarations that
lack implementations after the removal of pgen.

@item 
bpo-20180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20180}: @code{dict.pop()} is now up to 33% faster thanks to Argument
Clinic. Patch by Inada Naoki.

@item 
bpo-36611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36611}: Debug memory allocators: disable serialno field by default from
debug hooks on Python memory allocators to reduce the memory footprint by
5%. Enable @ref{11d,,tracemalloc} to get the traceback where a memory block
has been allocated when a fatal memory error is logged to decide where to
put a breakpoint. Compile Python with @code{PYMEM_DEBUG_SERIALNO} defined to
get back the field.

@item 
bpo-36588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36588}: On AIX, @ref{3db,,sys.platform} doesn't contain the major version
anymore. Always return @code{'aix'}, instead of @code{'aix3'} .. @code{'aix7'}.
Since older Python versions include the version number, it is recommended
to always use @code{sys.platform.startswith('aix')}. Contributed by M. Felt.

@item 
bpo-36549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36549}: Change str.capitalize to use titlecase for the first character
instead of uppercase.

@item 
bpo-36540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36540}: Implement 
@geindex Python 提高建议; PEP 570
PEP 570@footnote{https://www.python.org/dev/peps/pep-0570} (Python positional-only parameters). Patch
by Pablo Galindo.

@item 
bpo-36475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36475}: @ref{3dc,,PyEval_AcquireLock()} and @ref{3dd,,PyEval_AcquireThread()}
now terminate the current thread if called while the interpreter is
finalizing, making them consistent with @ref{3de,,PyEval_RestoreThread()},
@ref{3df,,Py_END_ALLOW_THREADS()}, and @ref{3e0,,PyGILState_Ensure()}.

@item 
bpo-36504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36504}: Fix signed integer overflow in _ctypes.c's
@code{PyCArrayType_new()}.

@item 
bpo-20844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20844}: Fix running script with encoding cookie and LF line ending may
fail on Windows.

@item 
bpo-24214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24214}: Fixed support of the surrogatepass error handler in the UTF-8
incremental decoder.

@item 
bpo-36452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36452}: Changing @code{dict} keys during iteration of the dict itself,
@code{keys()}, @code{values()}, or @code{items()} will now be detected in certain
corner cases where keys are deleted/added so that the number of keys isn't
changed. A @ref{3e4,,RuntimeError} will be raised after @code{len(dict)} iterations.
Contributed by Thomas Perl.

@item 
bpo-36459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36459}: Fix a possible double @code{PyMem_FREE()} due to tokenizer.c's
@code{tok_nextc()}.

@item 
bpo-36433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36433}: Fixed TypeError message in classmethoddescr_call.

@item 
bpo-36430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36430}: Fix a possible reference leak in @ref{ced,,itertools.count()}.

@item 
bpo-36440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36440}: Include node names in @code{ParserError} messages, instead of
numeric IDs. Patch by A. Skrobov.

@item 
bpo-36143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36143}: Regenerate @ref{a6,,keyword} from the Grammar and Tokens file
using pgen. Patch by Pablo Galindo.

@item 
bpo-18372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18372}: Add missing @ref{f0e,,PyObject_GC_Track()} calls in the
@ref{ca,,pickle} module. Patch by Zackery Spytz.
@end itemize

@node Library<33>,Documentation<23>,Core and Builtins<31>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id231}@anchor{1161}
@subsubsection Library



@itemize -

@item 
bpo-35952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35952}: Fix pythoninfo when the compiler is missing.

@item 
bpo-28238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28238}: The @code{.find*()} methods of xml.etree.ElementTree can now
search for wildcards like @code{@{*@}tag} and @code{@{ns@}*} that match a tag in any
namespace or all tags in a namespace.  Patch by Stefan Behnel.

@item 
bpo-26978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26978}: @code{pathlib.path.link_to()} is now implemented. It creates a hard
link pointing to a path.

@item 
bpo-1613500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1613500}: @ref{3ac,,fileinput.FileInput} now uses the input file mode to
correctly set the output file mode (previously it was hardcoded to
@code{'w'})  when @code{inplace=True} is passed to its constructor.

@item 
bpo-36734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36734}: Fix compilation of @code{faulthandler.c} on HP-UX. Initialize
@code{stack_t current_stack} to zero using @code{memset()}.

@item 
bpo-13611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13611}: The xml.etree.ElementTree packages gained support for C14N 2.0
serialisation. Patch by Stefan Behnel.

@item 
bpo-36669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36669}: Add missing matrix multiplication operator support to
weakref.proxy.

@item 
bpo-36676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36676}: The XMLParser() in xml.etree.ElementTree provides namespace
prefix context to the parser target if it defines the callback methods
"start_ns()" and/or "end_ns()". Patch by Stefan Behnel.

@item 
bpo-36673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36673}: The TreeBuilder and XMLPullParser in xml.etree.ElementTree
gained support for parsing comments and processing instructions. Patch by
Stefan Behnel.

@item 
bpo-36650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36650}: The C version of functools.lru_cache() was treating calls with
an empty @code{**kwargs} dictionary as being distinct from calls with no
keywords at all. This did not result in an incorrect answer, but it did
trigger an unexpected cache miss.

@item 
bpo-28552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28552}: Fix @ref{61,,distutils.sysconfig} if @ref{3a5,,sys.executable} is
@code{None} or an empty string: use @ref{1162,,os.getcwd()} to initialize
@code{project_base}.  Fix also the distutils build command: don't use
@ref{3a5,,sys.executable} if it is @code{None} or an empty string.

@item 
bpo-35755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35755}: @ref{1031,,shutil.which()} and
@code{distutils.spawn.find_executable()} now use @code{os.confstr("CS_PATH")}
if available instead of @ref{1163,,os.defpath}, if the @code{PATH} environment
variable is not set. Moreover, don't use @code{os.confstr("CS_PATH")} nor
@ref{1163,,os.defpath} if the @code{PATH} environment variable is set to an empty
string.

@item 
bpo-25430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25430}: improve performance of @code{IPNetwork.__contains__()}

@item 
bpo-30485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30485}: Path expressions in xml.etree.ElementTree can now avoid
explicit namespace prefixes for tags (or the "@{namespace@}tag" notation) by
passing a default namespace with an empty string prefix.

@item 
bpo-36613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36613}: Fix @ref{9,,asyncio} wait() not removing callback if exception

@item 
bpo-36598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36598}: Fix @code{isinstance} check for Mock objects with spec when the
code is executed under tracing. Patch by Karthikeyan Singaravelan.

@item 
bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748}: In development mode (@ref{297,,-X} @code{dev}) and in debug build,
the @ref{313,,io.IOBase} destructor now logs @code{close()} exceptions. These
exceptions are silent by default in release mode.

@item 
bpo-36575@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36575}: The @code{_lsprof} module now uses internal timer same to
@code{time.perf_counter()} by default. @code{gettimeofday(2)} was used on Unix.
New timer has better resolution on most Unix platforms and timings are no
longer impacted by system clock updates since @code{perf_counter()} is
monotonic. Patch by Inada Naoki.

@item 
bpo-33461@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33461}: @code{json.loads} now emits @code{DeprecationWarning} when
@code{encoding} option is specified.  Patch by Matthias Bussonnier.

@item 
bpo-36559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36559}: The random module now prefers the lean internal _sha512 module
over hashlib for seed(version=2) to optimize import time.

@item 
bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561}: Set backlog=None as the default for socket.create_server.

@item 
bpo-34373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34373}: Fix @ref{c3f,,time.mktime()} error handling on AIX for year before
1970.

@item 
bpo-36232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36232}: Improve error message when trying to open existing DBM database
that actually doesn't exist. Patch by Marco Rougeth.

@item 
bpo-36546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36546}: Add statistics.quantiles()

@item 
bpo-36050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36050}: Optimized @code{http.client.HTTPResponse.read()} for large
response. Patch by Inada Naoki.

@item 
bpo-36522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36522}: If @emph{debuglevel} is set to >0 in @ref{93,,http.client}, print all
values for headers with multiple values for the same header name. Patch by
Matt Houglum.

@item 
bpo-36492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36492}: Deprecated passing required arguments like @emph{func} as keyword
arguments in functions which should accept arbitrary keyword arguments and
pass them to other function. Arbitrary keyword arguments (even with names
"self" and "func") can now be passed to these functions if the required
arguments are passed as positional arguments.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: Add statistics.geometric_mean().

@item 
bpo-30427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30427}: @code{os.path.normcase()} relies on @code{os.fspath()} to check the
type of its argument. Redundant checks have been removed from its
@code{posixpath.normcase()} and @code{ntpath.normcase()} implementations. Patch
by Wolfgang Maier.

@item 
bpo-36385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36385}: Stop rejecting IPv4 octets for being ambiguously octal. Leading
zeros are ignored, and no longer are assumed to specify octal octets.
Octets are always decimal numbers. Octets must still be no more than three
digits, including leading zeroes.

@item 
bpo-36434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36434}: Errors during writing to a ZIP file no longer prevent to
properly close it.

@item 
bpo-36407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36407}: Fixed wrong indentation writing for CDATA section in
xml.dom.minidom. Patch by Vladimir Surjaninov.

@item 
bpo-36326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36326}: inspect.getdoc() can now find docstrings for member objects
when __slots__ is a dictionary.

@item 
bpo-36366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36366}: Calling @code{stop()} on an unstarted or stopped
@ref{881,,unittest.mock.patch()} object will now return @ref{204,,None} instead of
raising @ref{3e4,,RuntimeError}, making the method idempotent. Patch by
Karthikeyan Singaravelan.

@item 
bpo-36348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36348}: The @code{imap.IMAP4.logout()} method no longer ignores silently
arbitrary exceptions.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add time module support and fix test_time faiures for VxWorks.

@item 
bpo-36227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36227}: Added support for keyword arguments @code{default_namespace} and
@code{xml_declaration} in functions ElementTree.tostring() and
ElementTree.tostringlist().

@item 
bpo-36004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36004}: Added new alternate constructors
@ref{2fc,,datetime.date.fromisocalendar()} and
@ref{2fd,,datetime.datetime.fromisocalendar()}, which construct date objects
from ISO year, week number and weekday; these are the inverse of each
class's @code{isocalendar} method. Patch by Paul Ganssle.

@item 
bpo-35936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35936}: @ref{b4,,modulefinder} no longer depends on the deprecated
@ref{99,,imp} module, and the initializer for
@ref{1164,,modulefinder.ModuleFinder} now has immutable default arguments.
Patch by Brandt Bucher.

@item 
bpo-35376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35376}: @ref{b4,,modulefinder} correctly handles modules that have the
same name as a bad package. Patch by Brandt Bucher.

@item 
bpo-17396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17396}: @ref{b4,,modulefinder} no longer crashes when encountering syntax
errors in followed imports. Patch by Brandt Bucher.

@item 
bpo-35934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35934}: Added @ref{352,,create_server()} and
@ref{353,,has_dualstack_ipv6()} convenience functions to automate the
necessary tasks usually involved when creating a server socket, including
accepting both IPv4 and IPv6 connections on the same socket.  (Contributed
by Giampaolo Rodola in bpo-17561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17561}.)

@item 
bpo-23078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23078}: Add support for @ref{310,,classmethod()} and @ref{311,,staticmethod()} to
@ref{10d0,,unittest.mock.create_autospec()}.  Initial patch by Felipe Ochoa.

@item 
bpo-35416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35416}: Fix potential resource warnings in distutils. Patch by Mickaël
Schoentgen.

@item 
bpo-25451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25451}: Add transparency methods to @code{tkinter.PhotoImage}.  Patch
by Zackery Spytz.

@item 
bpo-35082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35082}: Don't return deleted attributes when calling dir on a
@ref{37a,,unittest.mock.Mock}.

@item 
bpo-34547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34547}: @ref{1150,,wsgiref.handlers.BaseHandler} now handles abrupt client
connection terminations gracefully. Patch by Petter Strandmark.

@item 
bpo-31658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31658}: @ref{1165,,xml.sax.parse()} now supports @ref{47b,,path-like}. Patch by Mickaël Schoentgen.

@item 
bpo-34139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34139}: Remove stale unix datagram socket before binding

@item 
bpo-33530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33530}: Implemented Happy Eyeballs in @code{asyncio.create_connection()}.
Added two new arguments, @emph{happy_eyeballs_delay} and @emph{interleave}, to
specify Happy Eyeballs behavior.

@item 
bpo-33291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33291}: Do not raise AttributeError when calling the inspect functions
isgeneratorfunction, iscoroutinefunction, isasyncgenfunction on a method
created from an arbitrary callable. Instead, return False.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: Fix the multiprocessing.semaphore_tracker so it is reused by
child processes

@item 
bpo-31292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31292}: Fix @code{setup.py check --restructuredtext} for files containing
@code{include} directives.
@end itemize

@node Documentation<23>,Tests<24>,Library<33>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id232}@anchor{1166}
@subsubsection Documentation



@itemize -

@item 
bpo-36625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36625}: Remove obsolete comments from docstrings in fractions.Fraction

@item 
bpo-30840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30840}: Document relative imports

@item 
bpo-36523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36523}: Add docstring for io.IOBase.writelines().

@item 
bpo-36425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36425}: New documentation translation: Simplified Chinese@footnote{https://docs.python.org/zh-cn/}.

@item 
bpo-36345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36345}: Avoid the duplication of code from @code{Tools/scripts/serve.py}
in using the @code{literalinclude} directive for the basic
wsgiref-based web server in the documentation of @ref{135,,wsgiref}.
Contributed by Stéphane Wirtel.

@item 
bpo-36345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36345}: Using the code of the @code{Tools/scripts/serve.py} script as an
example in the @ref{135,,wsgiref} documentation.  Contributed by Stéphane
Wirtel.

@item 
bpo-36157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36157}: Added Documention for  PyInterpreterState_Main().

@item 
bpo-33043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33043}: Updates the docs.python.org page with the addition of a
'Contributing to Docs' link at the end of the page (between 'Reporting
Bugs' and 'About Documentation'). Updates the 'Found a Bug' page with
additional links and information in the Documentation Bugs section.

@item 
bpo-35581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35581}: @@typing.type_check_only now allows type stubs to mark functions
and classes not available during runtime.

@item 
bpo-33832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33832}: Add glossary entry for 'magic method'.

@item 
bpo-32913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32913}: Added re.Match.groupdict example to regex HOWTO.
@end itemize

@node Tests<24>,Build<23>,Documentation<23>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id233}@anchor{1167}
@subsubsection Tests



@itemize -

@item 
bpo-36719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36719}: regrtest now always detects uncollectable objects. Previously,
the check was only enabled by @code{--findleaks}. The check now also works
with @code{-jN/--multiprocess N}. @code{--findleaks} becomes a deprecated alias
to @code{--fail-env-changed}.

@item 
bpo-36725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36725}: When using multiprocessing mode (-jN), regrtest now better
reports errors if a worker process fails, and it exits immediately on a
worker thread failure or when interrupted.

@item 
bpo-36454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36454}: Change test_time.test_monotonic() to test only the lower bound
of elapsed time after a sleep command rather than the upper bound. This
prevents unnecessary test failures on slow buildbots. Patch by Victor
Stinner.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Improve test coverage for xml.etree.ElementTree. Patch by
Gordon P. Hemsley.

@item 
bpo-32424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32424}: Fix typo in test_cyclic_gc() test for xml.etree.ElementTree.
Patch by Gordon P. Hemsley.

@item 
bpo-36635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36635}: Add a new @code{_testinternalcapi} module to test the internal
C API.

@item 
bpo-36629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36629}: Fix @code{test_imap4_host_default_value()} of @code{test_imaplib}:
catch also @ref{1168,,errno.ENETUNREACH} error.

@item 
bpo-36611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36611}: Fix @code{test_sys.test_getallocatedblocks()} when
@ref{11d,,tracemalloc} is enabled.

@item 
bpo-36560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36560}: Fix reference leak hunting in regrtest: compute also deltas (of
reference count, allocated memory blocks, file descriptor count) during
warmup, to ensure that everything is initialized before starting to hunt
reference leaks.

@item 
bpo-36565@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36565}: Fix reference hunting (@code{python3 -m test -R 3:3}) when Python
has no built-in abc module.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Port test_resource to VxWorks: skip tests cases setting
RLIMIT_FSIZE and RLIMIT_CPU.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_tabnanny on VxWorks: adjust ENOENT error message.

@item 
bpo-36436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36436}: Fix @code{_testcapi.pymem_buffer_overflow()}: handle memory
allocation failure.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Fix test_utf8_mode on VxWorks: Python always use UTF-8 on
VxWorks.

@item 
bpo-36341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36341}: Fix tests that may fail with PermissionError upon calling
bind() on AF_UNIX sockets.
@end itemize

@node Build<23>,Windows<25>,Tests<24>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id234}@anchor{1169}
@subsubsection Build



@itemize -

@item 
bpo-36747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36747}: Remove the stale scriptsinstall Makefile target.

@item 
bpo-21536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21536}: On Unix, C extensions are no longer linked to libpython except
on Android and Cygwin.

It is now possible for a statically linked Python to load a C extension
built using a shared library Python.

When Python is embedded, @code{libpython} must not be loaded with
@code{RTLD_LOCAL}, but @code{RTLD_GLOBAL} instead. Previously, using
@code{RTLD_LOCAL}, it was already not possible to load C extensions which
were not linked to @code{libpython}, such as C extensions of the standard
library built by the @code{*shared*} section of @code{Modules/Setup}.

distutils, python-config and python-config.py have been modified.

@item 
bpo-36707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36707}: @code{./configure --with-pymalloc} no longer adds the @code{m} flag
to SOABI (sys.implementation.cache_tag). Enabling or disabling pymalloc
has no impact on the ABI.

@item 
bpo-36635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36635}: Change @code{PyAPI_FUNC(type)}, @code{PyAPI_DATA(type)} and
@code{PyMODINIT_FUNC} macros of @code{pyport.h} when @code{Py_BUILD_CORE_MODULE} is
defined. The @code{Py_BUILD_CORE_MODULE} define must be now be used to build
a C extension as a dynamic library accessing Python internals: export the
PyInit_xxx() function in DLL exports on Windows.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Don't build the @code{_crypt} extension on VxWorks.

@item 
bpo-36618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36618}: Add @code{-fmax-type-align=8} to CFLAGS when clang compiler is
detected. The pymalloc memory allocator aligns memory on 8 bytes. On
x86-64, clang expects alignment on 16 bytes by default and so uses MOVAPS
instruction which can lead to segmentation fault. Instruct clang that
Python is limited to alignment on 8 bytes to use MOVUPS instruction
instead: slower but don't trigger a SIGSEGV if the memory is not aligned
on 16 bytes. Sadly, the flag must be added to @code{CFLAGS} and not just
@code{CFLAGS_NODIST}, since third party C extensions can have the same issue.

@item 
bpo-36605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36605}: @code{make tags} and @code{make TAGS} now also parse
@code{Modules/_io/*.c} and @code{Modules/_io/*.h}.

@item 
bpo-36465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36465}: Release builds and debug builds are now ABI compatible:
defining the @code{Py_DEBUG} macro no longer implies the @code{Py_TRACE_REFS}
macro, which introduces the only ABI incompatibility. The
@code{Py_TRACE_REFS} macro, which adds the @code{sys.getobjects()} function
and the 
@geindex PYTHONDUMPREFS
@geindex 环境变量; PYTHONDUMPREFS
@ref{29a,,PYTHONDUMPREFS} environment variable, can be set using
the new @code{./configure --with-trace-refs} build option.

@item 
bpo-36577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36577}: setup.py now correctly reports missing OpenSSL headers and
libraries again.

@item 
bpo-36544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36544}: Fix regression introduced in bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146} refactoring setup.py

@item 
bpo-36508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36508}: @code{python-config --ldflags} no longer includes flags of the
@code{LINKFORSHARED} variable. The @code{LINKFORSHARED} variable must only be
used to build executables.

@item 
bpo-36503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36503}: Remove references to "aix3" and "aix4". Patch by M. Felt.
@end itemize

@node Windows<25>,macOS<22>,Build<23>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id235}@anchor{116a}
@subsubsection Windows



@itemize -

@item 
bpo-35920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35920}: Added platform.win32_edition() and platform.win32_is_iot().
Added support for cross-compiling packages for Windows ARM32. Skip tests
that are not expected to work on Windows IoT Core ARM32.

@item 
bpo-36649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36649}: Remove trailing spaces for registry keys when installed via the
Store.

@item 
bpo-34144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34144}: Fixed activate.bat to correctly update codepage when chcp.com
returns dots in output. Patch by Lorenz Mende.

@item 
bpo-36509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36509}: Added preset-iot layout for Windows IoT ARM containers. This
layout doesn't contain UI components like tkinter or IDLE. It also doesn't
contain files to support on-target builds since Windows ARM32 builds must
be cross-compiled when using MSVC.

@item 
bpo-35941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35941}: enum_certificates function of the ssl module now returns
certificates from all available certificate stores inside windows in a
query instead of returning only certificates from the system wide
certificate store. This includes certificates from these certificate
stores: local machine, local machine enterprise, local machine group
policy, current user, current user group policy, services, users.
ssl.enum_crls() function is changed in the same way to return all
certificate revocation lists inside the windows certificate revocation
list stores.

@item 
bpo-36441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36441}: Fixes creating a venv when debug binaries are installed.

@item 
bpo-36085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36085}: Enable better DLL resolution on Windows by using safe DLL
search paths and adding @ref{2fa,,os.add_dll_directory()}.

@item 
bpo-36010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36010}: Add the venv standard library module to the nuget distribution
for Windows.

@item 
bpo-29515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29515}: Add the following socket module constants on Windows:
IPPROTO_AH IPPROTO_CBT IPPROTO_DSTOPTS IPPROTO_EGP IPPROTO_ESP
IPPROTO_FRAGMENT IPPROTO_GGP IPPROTO_HOPOPTS IPPROTO_ICLFXBM
IPPROTO_ICMPV6 IPPROTO_IDP IPPROTO_IGMP IPPROTO_IGP IPPROTO_IPV4
IPPROTO_IPV6 IPPROTO_L2TP IPPROTO_MAX IPPROTO_ND IPPROTO_NONE IPPROTO_PGM
IPPROTO_PIM IPPROTO_PUP IPPROTO_RDP IPPROTO_ROUTING IPPROTO_SCTP
IPPROTO_ST

@item 
bpo-35947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35947}: Added current version of libffi to cpython-source-deps. Change
_ctypes to use current version of libffi on Windows.

@item 
bpo-34060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34060}: Report system load when running test suite on Windows. Patch by
Ammar Askar. Based on prior work by Jeremy Kloth.

@item 
bpo-31512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31512}: With the Windows 10 Creators Update, non-elevated users can now
create symlinks as long as the computer has Developer Mode enabled.
@end itemize

@node macOS<22>,IDLE<22>,Windows<25>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id236}@anchor{116b}
@subsubsection macOS



@itemize -

@item 
bpo-34602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34602}: Avoid failures setting macOS stack resource limit with
resource.setrlimit. This reverts an earlier fix for bpo-18075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18075} which forced
a non-default stack size when building the interpreter executable on
macOS.
@end itemize

@node IDLE<22>,Tools/Demos<10>,macOS<22>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id237}@anchor{116c}
@subsubsection IDLE



@itemize -

@item 
bpo-36429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36429}: Fix starting IDLE with pyshell. Add idlelib.pyshell alias at
top; remove pyshell alias at bottom. Remove obsolete __name__=='__main__'
command.
@end itemize

@node Tools/Demos<10>,C API<18>,IDLE<22>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id238}@anchor{116d}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-14546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14546}: Fix the argument handling in Tools/scripts/lll.py.
@end itemize

@node C API<18>,,Tools/Demos<10>,Python 3 8 0 alpha 4
@anchor{whatsnew/changelog id239}@anchor{116e}
@subsubsection C API



@itemize -

@item 
bpo-36763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36763}: Fix memory leak in @ref{a13,,Py_SetStandardStreamEncoding()}:
release memory if the function is called twice.

@item 
bpo-36641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36641}: @code{PyDoc_VAR(name)} and
@code{PyDoc_STRVAR(name,str)} now create @code{static const char name[]}
instead of @code{static char name[]}.  Patch by Inada Naoki.

@item 
bpo-36389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36389}: Change the value of @code{CLEANBYTE}, @code{DEADDYTE} and
@code{FORBIDDENBYTE} internal constants used by debug hooks on Python memory
allocators (@ref{60c,,PyMem_SetupDebugHooks()} function). Byte patterns
@code{0xCB}, @code{0xDB} and @code{0xFB} have been replaced with @code{0xCD}, @code{0xDD}
and @code{0xFD} to use the same values than Windows CRT debug @code{malloc()}
and @code{free()}.

@item 
bpo-36443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36443}: Since Python 3.7.0, calling @ref{547,,Py_DecodeLocale()} before
@ref{210,,Py_Initialize()} produces mojibake if the @code{LC_CTYPE} locale is
coerced and/or if the UTF-8 Mode is enabled by the user configuration. The
LC_CTYPE coercion and UTF-8 Mode are now disabled by default to fix the
mojibake issue. They must now be enabled explicitly (opt-in) using the new
@code{_Py_PreInitialize()} API with @code{_PyPreConfig}.

@item 
bpo-36025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36025}: Fixed an accidental change to the datetime C API where the
arguments to the @ref{116f,,PyDate_FromTimestamp()} function were incorrectly
interpreted as a single timestamp rather than an arguments tuple, which
causes existing code to start raising @ref{1ff,,TypeError}. The
backwards-incompatible change was only present in alpha releases of Python
3.8. Patch by Paul Ganssle.

@item 
bpo-35810@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35810}: Modify @code{PyObject_Init} to correctly increase the refcount of
heap- allocated Type objects. Also fix the refcounts of the heap-allocated
types that were either doing this manually or not decreasing the type's
refcount in tp_dealloc
@end itemize

@node Python 3 8 0 alpha 3,Python 3 8 0 alpha 2,Python 3 8 0 alpha 4,更新日志
@anchor{whatsnew/changelog python-3-8-0-alpha-3}@anchor{1170}
@subsection Python 3.8.0 alpha 3


@emph{Release date: 2019-03-25}

@menu
* Security: Security<21>. 
* Core and Builtins: Core and Builtins<32>. 
* Library: Library<34>. 
* Documentation: Documentation<24>. 
* Tests: Tests<25>. 
* Build: Build<24>. 
* Windows: Windows<26>. 
* IDLE: IDLE<23>. 
* Tools/Demos: Tools/Demos<11>. 
* C API: C API<19>. 

@end menu

@node Security<21>,Core and Builtins<32>,,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id240}@anchor{1171}
@subsubsection Security



@itemize -

@item 
bpo-36216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36216}: Changes urlsplit() to raise ValueError when the URL contains
characters that decompose under IDNA encoding (NFKC-normalization) into
characters that affect how the URL is parsed.

@item 
bpo-35121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35121}: Don't send cookies of domain A without Domain attribute to
domain B when domain A is a suffix match of domain B while using a
cookiejar with @ref{1172,,http.cookiejar.DefaultCookiePolicy} policy. Patch
by Karthikeyan Singaravelan.
@end itemize

@node Core and Builtins<32>,Library<34>,Security<21>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id241}@anchor{1173}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36421}: Fix a possible double decref in _ctypes.c's
@code{PyCArrayType_new()}.

@item 
bpo-36412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36412}: Fix a possible crash when creating a new dictionary.

@item 
bpo-36398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36398}: Fix a possible crash in @code{structseq_repr()}.

@item 
bpo-36256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36256}: Fix bug in parsermodule when parsing a state in a DFA that has
two or more arcs with labels of the same type. Patch by Pablo Galindo.

@item 
bpo-36365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36365}: repr(structseq) is no longer limited to 512 bytes.

@item 
bpo-36374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36374}: Fix a possible null pointer dereference in
@code{merge_consts_recursive()}. Patch by Zackery Spytz.

@item 
bpo-36236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36236}: At Python initialization, the current directory is no longer
prepended to @ref{262,,sys.path} if it has been removed.

@item 
bpo-36352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36352}: Python initialization now fails with an error, rather than
silently truncating paths, if a path is too long.

@item 
bpo-36301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36301}: Python initialization now fails if decoding @code{pybuilddir.txt}
configuration file fails at startup.

@item 
bpo-36333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36333}: Fix leak in _PyRuntimeState_Fini. Contributed by Stéphane
Wirtel.

@item 
bpo-36332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36332}: The builtin @ref{2ee,,compile()} can now handle AST objects that
contain assignment expressions. Patch by Pablo Galindo.

@item 
bpo-36282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36282}: Improved error message for too much positional arguments in
some builtin functions.

@item 
bpo-30040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30040}: New empty dict uses fewer memory for now.  It used more memory
than empty dict created by @code{dict.clear()}.  And empty dict creation and
deletion is about 2x faster.  Patch by Inada Naoki.

@item 
bpo-36262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36262}: Fix an unlikely memory leak on conversion from string to float
in the function @code{_Py_dg_strtod()} used by @code{float(str)},
@code{complex(str)}, @ref{6c3,,pickle.load()}, @ref{1174,,marshal.load()}, etc.

@item 
bpo-36252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36252}: Update Unicode databases to version 12.0.0.

@item 
bpo-36218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36218}: Fix a segfault occurring when sorting a list of heterogeneous
values. Patch contributed by Rémi Lapeyre and Elliot Gorokhovsky.

@item 
bpo-36188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36188}: Cleaned up left-over vestiges of Python 2 unbound method
handling in method objects and documentation. Patch by Martijn Pieters

@item 
bpo-36124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36124}: Add a new interpreter-specific dict and expose it in the C-API
via PyInterpreterState_GetDict().  This parallels PyThreadState_GetDict().
However, extension modules should continue using PyModule_GetState() for
their own internal per-interpreter state.

@item 
bpo-35975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35975}: Add a @code{feature_version} flag to @code{ast.parse()} (documented)
and @code{compile()} (hidden) that allows tweaking the parser to support
older versions of the grammar. In particular, if @code{feature_version} is 5
or 6, the hacks for the @code{async} and @code{await} keyword from PEP 492 are
reinstated. (For 7 or higher, these are unconditionally treated as
keywords, but they are still special tokens rather than @code{NAME} tokens
that the parser driver recognizes.)

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Use UTF-8 as the system encoding on VxWorks.

@item 
bpo-36048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36048}: The @ref{2c9,,__index__()} special method will be used
instead of @ref{2ca,,__int__()} for implicit conversion of Python
numbers to C integers.  Using the @code{__int__()} method in implicit
conversions has been deprecated.

@item 
bpo-35808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35808}: Retire pgen and use a modified version of pgen2 to generate the
parser. Patch by Pablo Galindo.
@end itemize

@node Library<34>,Documentation<24>,Core and Builtins<32>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id242}@anchor{1175}
@subsubsection Library



@itemize -

@item 
bpo-36401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36401}: The class documentation created by pydoc now has a separate
section for readonly properties.

@item 
bpo-36320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36320}: The typing.NamedTuple() class has deprecated the _field_types
attribute in favor of the __annotations__ attribute which carried the same
information. Also, both attributes were converted from OrderedDict to a
regular dict.

@item 
bpo-34745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34745}: Fix @ref{9,,asyncio} ssl memory issues caused by circular
references

@item 
bpo-36324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36324}: Add method to statistics.NormalDist for computing the inverse
cumulative normal distribution.

@item 
bpo-36321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36321}: collections.namedtuple() misspelled the name of an attribute.
To be consistent with typing.NamedTuple, the attribute name should have
been "_field_defaults" instead of "_fields_defaults".  For backwards
compatibility, both spellings are now created.  The misspelled version may
be removed in the future.

@item 
bpo-36297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36297}: "unicode_internal" codec is removed.  It was deprecated since
Python 3.3. Patch by Inada Naoki.

@item 
bpo-36298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36298}: Raise ModuleNotFoundError in pyclbr when a module can't be
found. Thanks to 'mental' for the bug report.

@item 
bpo-36268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36268}: Switch the default format used for writing tars with
mod:@ref{101,,tarfile} to the modern POSIX.1-2001 pax standard, from the
vendor-specific GNU. Contributed by C.A.M. Gerlach.

@item 
bpo-36285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36285}: Fix integer overflows in the array module. Patch by Stephan
Hohe.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Add _signal module support for VxWorks.

@item 
bpo-36272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36272}: @ref{aa,,logging} does not silently ignore RecursionError anymore.
Patch contributed by Rémi Lapeyre.

@item 
bpo-36280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36280}: Add a kind field to ast.Constant. It is 'u' if the literal has
a 'u' prefix (i.e. a Python 2 style unicode literal), else None.

@item 
bpo-35931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35931}: The @ref{c9,,pdb} @code{debug} command now gracefully handles all
exceptions.

@item 
bpo-36251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36251}: Fix format strings used for stderrprinter and re.Match reprs.
Patch by Stephan Hohe.

@item 
bpo-36235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36235}: Fix @code{CFLAGS} in @code{customize_compiler()} of
@code{distutils.sysconfig}: when the @code{CFLAGS} environment variable is
defined, don't override @code{CFLAGS} variable with the @code{OPT} variable
anymore. Initial patch written by David Malcolm.

@item 
bpo-35807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35807}: Update ensurepip to install pip 19.0.3 and setuptools 40.8.0.

@item 
bpo-36139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36139}: Release GIL when closing @ref{323,,mmap} objects.

@item 
bpo-36179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36179}: Fix two unlikely reference leaks in _hashopenssl. The leaks
only occur in out-of-memory cases.

@item 
bpo-36169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36169}: Add overlap() method to statistics.NormalDist.  Computes the
overlapping coefficient for two normal distributions.

@item 
bpo-36103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36103}: Default buffer size used by @code{shutil.copyfileobj()} is changed
from 16 KiB to 64 KiB on non-Windows platform to reduce system call
overhead. Contributed by Inada Naoki.

@item 
bpo-36130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36130}: Fix @code{pdb} with @code{skip=...} when stepping into a frame
without a @code{__name__} global.  Patch by Anthony Sottile.

@item 
bpo-35652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35652}: shutil.copytree(copy_function=...) erroneously pass DirEntry
instead of a path string.

@item 
bpo-35178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35178}: Ensure custom @ref{1176,,warnings.formatwarning()} function can
receive @code{line} as positional argument. Based on patch by Tashrif Billah.

@item 
bpo-36106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36106}: Resolve potential name clash with libm's sinpi(). Patch by
Dmitrii Pasechnik.

@item 
bpo-36091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36091}: Clean up reference to async generator in Lib/types. Patch by
Henry Chen.

@item 
bpo-36043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36043}: @code{FileCookieJar} supports @ref{47b,,path-like object}.
Contributed by Stéphane Wirtel

@item 
bpo-35899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35899}: Enum has been fixed to correctly handle empty strings and
strings with non-Latin characters (ie. 'α', 'א') without crashing.
Original patch contributed by Maxwell. Assisted by Stéphane Wirtel.

@item 
bpo-21269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21269}: Add @code{args} and @code{kwargs} properties to mock call objects.
Contributed by Kumar Akshay.

@item 
bpo-30670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30670}: @ref{347,,pprint.pp} has been added to pretty-print objects with
dictionary keys being sorted with their insertion order by default.
Parameter @emph{sort_dicts} has been added to @ref{348,,pprint.pprint}, @ref{986,,pprint.pformat}
and @ref{985,,pprint.PrettyPrinter}. Contributed by Rémi Lapeyre.

@item 
bpo-35843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35843}: Implement @code{__getitem__} for @code{_NamespacePath}.  Patch by
Anthony Sottile.

@item 
bpo-35802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35802}: Clean up code which checked presence of @code{os.stat} /
@code{os.lstat} / @code{os.chmod} which are always present.  Patch by Anthony
Sottile.

@item 
bpo-35715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35715}: Librates the return value of a ProcessPoolExecutor
_process_worker after it's no longer needed to free memory

@item 
bpo-35493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35493}: Use @ref{b0a,,multiprocessing.connection.wait()} instead of polling
each 0.2 seconds for worker updates in @code{multiprocessing.Pool}.
Patch by Pablo Galindo.

@item 
bpo-35661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35661}: Store the venv prompt in pyvenv.cfg.

@item 
bpo-35121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35121}: Don't set cookie for a request when the request path is a
prefix match of the cookie's path attribute but doesn't end with "/".
Patch by Karthikeyan Singaravelan.

@item 
bpo-21478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21478}: Calls to a child function created with
@ref{10d0,,unittest.mock.create_autospec()} should propagate to the parent.
Patch by Karthikeyan Singaravelan.

@item 
bpo-35198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35198}: Fix C++ extension compilation on AIX
@end itemize

@node Documentation<24>,Tests<25>,Library<34>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id243}@anchor{1177}
@subsubsection Documentation



@itemize -

@item 
bpo-36329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36329}: Declare the path of the Python binary for the usage of
@code{Tools/scripts/serve.py} when executing @code{make -C Doc/ serve}.
Contributed by Stéphane Wirtel

@item 
bpo-36138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36138}: Improve documentation about converting datetime.timedelta to
scalars.

@item 
bpo-21314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21314}: A new entry was added to the Core Language Section of the
Programming FAQ, which explaines the usage of slash(/) in the signature of
a function. Patch by Lysandros Nikolaou
@end itemize

@node Tests<25>,Build<24>,Documentation<24>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id244}@anchor{1178}
@subsubsection Tests



@itemize -

@item 
bpo-36234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36234}: test_posix.PosixUidGidTests: add tests for invalid uid/gid type
(str). Initial patch written by David Malcolm.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: Fix @code{test_re.test_locale_flag()}:  use
@code{locale.getpreferredencoding()} rather than @code{locale.getlocale()} to
get the locale encoding. With some locales, @code{locale.getlocale()} returns
the wrong encoding.

@item 
bpo-36123@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36123}: Fix race condition in test_socket.
@end itemize

@node Build<24>,Windows<26>,Tests<25>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id245}@anchor{1179}
@subsubsection Build



@itemize -

@item 
bpo-36356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36356}: Fix leaks that led to build failure when configured with
address sanitizer.

@item 
bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146}: Add @code{TEST_EXTENSIONS} constant to @code{setup.py} to allow to
not build test extensions like @code{_testcapi}.

@item 
bpo-36146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36146}: Fix setup.py on macOS: only add @code{/usr/include/ffi} to include
directories of _ctypes, not for all extensions.

@item 
bpo-31904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31904}: Enable build system to cross-build for VxWorks RTOS.
@end itemize

@node Windows<26>,IDLE<23>,Build<24>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id246}@anchor{117a}
@subsubsection Windows



@itemize -

@item 
bpo-36312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36312}: Fixed decoders for the following code pages: 50220, 50221,
50222, 50225, 50227, 50229, 57002 through 57011, 65000 and 42.

@item 
bpo-36264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36264}: Don't honor POSIX @code{HOME} in @code{os.path.expanduser} on
windows.  Patch by Anthony Sottile.

@item 
bpo-24643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24643}: Fix name collisions due to @code{#define timezone _timezone} in
PC/pyconfig.h.
@end itemize

@node IDLE<23>,Tools/Demos<11>,Windows<26>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id247}@anchor{117b}
@subsubsection IDLE



@itemize -

@item 
bpo-36405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36405}: Use dict unpacking in idlelib.

@item 
bpo-36396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36396}: Remove fgBg param of idlelib.config.GetHighlight(). This param
was only used twice and changed the return type.

@item 
bpo-36176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36176}: Fix IDLE autocomplete & calltip popup colors. Prevent conflicts
with Linux dark themes (and slightly darken calltip background).

@item 
bpo-23205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23205}: For the grep module, add tests for findfiles, refactor
findfiles to be a module-level function, and refactor findfiles to use
os.walk.

@item 
bpo-23216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23216}: Add docstrings to IDLE search modules.

@item 
bpo-36152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36152}: Remove colorizer.ColorDelegator.close_when_done and the
corresponding argument of .close().  In IDLE, both have always been None
or False since 2007.

@item 
bpo-32129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32129}: Avoid blurry IDLE application icon on macOS with Tk 8.6. Patch
by Kevin Walzer.

@item 
bpo-36096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36096}: Refactor class variables to instance variables in colorizer.

@item 
bpo-30348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30348}: Increase test coverage of idlelib.autocomplete by 30%. Patch by
Louie Lu
@end itemize

@node Tools/Demos<11>,C API<19>,IDLE<23>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id248}@anchor{117c}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-35132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35132}: Fix py-list and py-bt commands of python-gdb.py on gdb7.

@item 
bpo-32217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32217}: Fix freeze script on Windows.
@end itemize

@node C API<19>,,Tools/Demos<11>,Python 3 8 0 alpha 3
@anchor{whatsnew/changelog id249}@anchor{117d}
@subsubsection C API



@itemize -

@item 
bpo-36381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36381}: Raise @code{DeprecationWarning} when '#' formats are used for
building or parsing values without @code{PY_SSIZE_T_CLEAN}.

@item 
bpo-36142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36142}: The whole coreconfig.h header is now excluded from
Py_LIMITED_API. Move functions definitions into a new internal
pycore_coreconfig.h header.
@end itemize

@node Python 3 8 0 alpha 2,Python 3 8 0 alpha 1,Python 3 8 0 alpha 3,更新日志
@anchor{whatsnew/changelog python-3-8-0-alpha-2}@anchor{117e}
@subsection Python 3.8.0 alpha 2


@emph{Release date: 2019-02-25}

@menu
* Core and Builtins: Core and Builtins<33>. 
* Library: Library<35>. 
* Documentation: Documentation<25>. 
* Tests: Tests<26>. 
* Windows: Windows<27>. 
* IDLE: IDLE<24>. 

@end menu

@node Core and Builtins<33>,Library<35>,,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id250}@anchor{117f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-36052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36052}: Raise a @ref{562,,SyntaxError} when assigning a value to
@ref{1180,,__debug__} with the Assignment Operator. Contributed by Stéphane Wirtel
and Pablo Galindo.

@item 
bpo-36012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36012}: Doubled the speed of class variable writes.  When a non-dunder
attribute was updated, there was an unnecessary call to update slots.

@item 
bpo-35942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35942}: The error message emitted when returning invalid types from
@code{__fspath__} in interfaces that allow passing @ref{5ee,,PathLike}
objects has been improved and now it does explain the origin of the error.

@item 
bpo-36016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36016}: @code{gc.get_objects} can now receive an optional parameter
indicating a generation to get objects from. Patch by Pablo Galindo.

@item 
bpo-1054041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1054041}: When the main interpreter exits due to an uncaught
KeyboardInterrupt, the process now exits in the appropriate manner for its
parent process to detect that a SIGINT or ^C terminated the process.  This
allows shells and batch scripts to understand that the user has asked them
to stop.

@item 
bpo-35992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35992}: Fix @code{__class_getitem__()} not being called on a class with a
custom non-subscriptable metaclass.

@item 
bpo-35993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35993}: Fix a crash on fork when using subinterpreters. Contributed by
Stéphane Wirtel

@item 
bpo-35991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35991}: Fix a potential double free in Modules/_randommodule.c.

@item 
bpo-35961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35961}: Fix a crash in slice_richcompare(): use strong references
rather than stolen references for the two temporary internal tuples.

@item 
bpo-35911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35911}: Enable the creation of cell objects by adding a
@code{cell.__new__} method, and expose the type @code{cell} in @code{Lib/types.py}
under the name CellType. Patch by Pierre Glaser.

@item 
bpo-12822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12822}: Use monotonic clock for @code{pthread_cond_timedwait} when
@code{pthread_condattr_setclock} and @code{CLOCK_MONOTONIC} are available.

@item 
bpo-15248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15248}: The compiler emits now syntax warnings in the case when a comma
is likely missed before tuple or list.

@item 
bpo-35886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35886}: The implementation of PyInterpreterState has been moved into
the internal header files (guarded by Py_BUILD_CORE).

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Clarify the errors reported when @code{object.__new__} and
@code{object.__init__} receive more than one argument. Contributed by Sanyam
Khurana.

@item 
bpo-35724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35724}: Signal-handling is now guaranteed to happen relative to the
main interpreter.

@item 
bpo-33608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33608}: We added a new internal _Py_AddPendingCall() that operates
relative to the provided interpreter.  This allows us to use the existing
implementation to ask another interpreter to do work that cannot be done
in the current interpreter, like decref an object the other interpreter
owns.  The existing Py_AddPendingCall() only operates relative to the main
interpreter.

@item 
bpo-33989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33989}: Fix a possible crash in @ref{550,,list.sort()} when sorting objects
with @code{ob_type->tp_richcompare == NULL}.  Patch by Zackery Spytz.
@end itemize

@node Library<35>,Documentation<25>,Core and Builtins<33>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id251}@anchor{1181}
@subsubsection Library



@itemize -

@item 
bpo-35512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35512}: @ref{1153,,unittest.mock.patch.dict()} used as a decorator with
string target resolves the target during function call instead of during
decorator construction. Patch by Karthikeyan Singaravelan.

@item 
bpo-36018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36018}: Add statistics.NormalDist, a tool for creating and manipulating
normal distributions of random variable.  Features a composite class that
treats the mean and standard deviation of measurement data as single
entity.

@item 
bpo-35904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35904}: Added statistics.fmean() as a faster, floating point variant of
the existing mean() function.

@item 
bpo-35918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35918}: Removed broken @code{has_key} method from
multiprocessing.managers.SyncManager.dict. Contributed by Rémi Lapeyre.

@item 
bpo-18283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18283}: Add support for bytes to @ref{1031,,shutil.which()}.

@item 
bpo-35960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35960}: Fix @ref{1182,,dataclasses.field()} throwing away empty mapping
objects passed as metadata.

@item 
bpo-35500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35500}: Write expected and actual call parameters on separate lines in
@ref{1183,,unittest.mock.Mock.assert_called_with()} assertion errors.
Contributed by Susan Su.

@item 
bpo-35931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35931}: The @ref{c9,,pdb} @code{debug} command now gracefully handles syntax
errors.

@item 
bpo-24209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24209}: In http.server script, rely on getaddrinfo to bind to preferred
address based on the bind parameter. Now default bind or binding to a name
may bind to IPv6 or dual-stack, depending on the environment.

@item 
bpo-35321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35321}: Set @code{__spec__.origin} of  @code{_frozen_importlib} to frozen so
that it matches the behavior of @code{_frozen_importlib_external}.  Patch by
Nina Zakharenko.

@item 
bpo-35378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35378}: Fix a reference issue inside @code{multiprocessing.Pool} that
caused the pool to remain alive if it was deleted without being closed or
terminated explicitly. A new strong reference is added to the pool
iterators to link the lifetime of the pool to the lifetime of its
iterators so the pool does not get destroyed if a pool iterator is still
alive.

@item 
bpo-34294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34294}: re module, fix wrong capturing groups in rare cases.
@ref{c8a,,re.search()}, @ref{a4d,,re.findall()}, @ref{582,,re.sub()} and other functions
that scan through string looking for a match, should reset capturing
groups between two match attempts. Patch by Ma Lin.

@item 
bpo-35615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35615}: @ref{131,,weakref}: Fix a RuntimeError when copying a
WeakKeyDictionary or a WeakValueDictionary, due to some keys or values
disappearing while iterating.

@item 
bpo-35606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35606}: Implement @ref{31c,,math.prod()} as analogous function to
@ref{31d,,sum()} that returns the product of a 'start' value (default: 1) times
an iterable of numbers. Patch by Pablo Galindo.

@item 
bpo-32417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32417}: Performing arithmetic between @ref{19f,,datetime.datetime}
subclasses and @ref{2d1,,datetime.timedelta} now returns an object of the
same type as the @ref{19f,,datetime.datetime} subclass. As a result,
@ref{2d2,,datetime.datetime.astimezone()} and alternate constructors like
@ref{1184,,datetime.datetime.now()} and @code{datetime.fromtimestamp()} called
with a @code{tz} argument now @emph{also} retain their subclass.

@item 
bpo-35153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35153}: Add @emph{headers} optional keyword-only parameter to
@ref{386,,xmlrpc.client.ServerProxy}, @code{xmlrpc.client.Transport} and
@code{xmlrpc.client.SafeTransport}.  Patch by Cédric Krier.

@item 
bpo-34572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34572}: Fix C implementation of pickle.loads to use importlib's locking
mechanisms, and thereby avoid using partially-loaded modules. Patch by Tim
Burgess.
@end itemize

@node Documentation<25>,Tests<26>,Library<35>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id252}@anchor{1185}
@subsubsection Documentation



@itemize -

@item 
bpo-36083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36083}: Fix formatting of --check-hash-based-pycs options in the
manpage Synopsis.

@item 
bpo-36007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36007}: Bump minimum sphinx version to 1.8.  Patch by Anthony Sottile.

@item 
bpo-22062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22062}: Update documentation and docstrings for pathlib. Original patch
by Mike Short.
@end itemize

@node Tests<26>,Windows<27>,Documentation<25>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id253}@anchor{1186}
@subsubsection Tests



@itemize -

@item 
bpo-27313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27313}: Avoid test_ttk_guionly ComboboxTest failure with macOS Cocoa
Tk.

@item 
bpo-36019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36019}: Add test.support.TEST_HTTP_URL and replace references of
@indicateurl{http://www.example.com} by this new constant. Contributed by Stéphane
Wirtel.

@item 
bpo-36037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=36037}: Fix test_ssl for strict OpenSSL configuration like RHEL8 strict
crypto policy. Use older TLS version for minimum TLS version of the server
SSL context if needed, to test TLS version older than default minimum TLS
version.

@item 
bpo-35798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35798}: Added @ref{1187,,test.support.check_syntax_warning()}.

@item 
bpo-35505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35505}: Make test_imap4_host_default_value independent on whether the
local IMAP server is running.

@item 
bpo-35917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35917}: multiprocessing: provide unit tests for SyncManager and
SharedMemoryManager classes + all the shareable types which are supposed
to be supported by them.  (patch by Giampaolo Rodola)

@item 
bpo-35704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35704}: Skip @code{test_shutil.test_unpack_archive_xztar} to prevent a
MemoryError on 32-bit AIX when MAXDATA setting is less than 0x20000000.

Patch by Michael Felt (aixtools)

@item 
bpo-34720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34720}: Assert m_state != NULL to mimic GC traversal functions that do
not correctly handle module creation when the module state has not been
created.
@end itemize

@node Windows<27>,IDLE<24>,Tests<26>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id254}@anchor{1188}
@subsubsection Windows



@itemize -

@item 
bpo-35976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35976}: Added ARM build support to Windows build files in PCBuild.

@item 
bpo-35692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35692}: @code{pathlib} no longer raises when checking file and directory
existence on drives that are not ready

@item 
bpo-35872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35872}: Uses the base Python executable when invoking venv in a virtual
environment

@item 
bpo-35873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35873}: Prevents venv paths being inherited by child processes

@item 
bpo-35299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35299}: Fix sysconfig detection of the source directory and distutils
handling of pyconfig.h during PGO profiling
@end itemize

@node IDLE<24>,,Windows<27>,Python 3 8 0 alpha 2
@anchor{whatsnew/changelog id255}@anchor{1189}
@subsubsection IDLE



@itemize -

@item 
bpo-24310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24310}: IDLE -- Document settings dialog font tab sample.

@item 
bpo-35833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35833}: Revise IDLE doc for control codes sent to Shell. Add a code
example block.

@item 
bpo-35689@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35689}: Add docstrings and unittests for colorizer.py.
@end itemize

@node Python 3 8 0 alpha 1,Python 3 7 0 final,Python 3 8 0 alpha 2,更新日志
@anchor{whatsnew/changelog python-3-8-0-alpha-1}@anchor{118a}
@subsection Python 3.8.0 alpha 1


@emph{Release date: 2019-02-03}

@menu
* Security: Security<22>. 
* Core and Builtins: Core and Builtins<34>. 
* Library: Library<36>. 
* Documentation: Documentation<26>. 
* Tests: Tests<27>. 
* Build: Build<25>. 
* Windows: Windows<28>. 
* macOS: macOS<23>. 
* IDLE: IDLE<25>. 
* Tools/Demos: Tools/Demos<12>. 
* C API: C API<20>. 

@end menu

@node Security<22>,Core and Builtins<34>,,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id256}@anchor{118b}
@subsubsection Security



@itemize -

@item 
bpo-35746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35746}: [CVE-2019-5010] Fix a NULL pointer deref in ssl module. The
cert parser did not handle CRL distribution points with empty DP or URI
correctly. A malicious or buggy certificate can result into segfault.
Vulnerability (TALOS-2018-0758) reported by Colin Read and Nicolas Edet of
Cisco.

@item 
bpo-34812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34812}: The @ref{232,,-I} command line option (run Python in isolated
mode) is now also copied by the @ref{b7,,multiprocessing} and
@ref{38,,distutils} modules when spawning child processes. Previously, only
@ref{231,,-E} and @ref{de3,,-s} options (enabled by @ref{232,,-I}) were
copied.

@item 
bpo-34791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34791}: The xml.sax and xml.dom.domreg no longer use environment
variables to override parser implementations when
sys.flags.ignore_environment is set by -E or -I arguments.

@item 
bpo-17239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17239}: The xml.sax and xml.dom.minidom parsers no longer processes
external entities by default. External DTD and ENTITY declarations no
longer load files or create network connections.

@item 
bpo-34623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34623}: CVE-2018-14647: The C accelerated _elementtree module now
initializes hash randomization salt from _Py_HashSecret instead of
libexpat's default CSPRNG.

@item 
bpo-34405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34405}: Updated to OpenSSL 1.1.0i for Windows builds.

@item 
bpo-33871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33871}: Fixed sending the part of the file in @ref{46a,,os.sendfile()} on
macOS.  Using the @emph{trailers} argument could cause sending more bytes from
the input file than was specified.

@item 
bpo-32533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32533}: Fixed thread-safety of error handling in _ssl.

@item 
bpo-33136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33136}: Harden ssl module against LibreSSL CVE-2018-8970.
X509_VERIFY_PARAM_set1_host() is called with an explicit namelen. A new
test ensures that NULL bytes are not allowed.

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch
by Jamie Davis.

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: The ssl module now allows users to perform their own IDN
en/decoding when using SNI.
@end itemize

@node Core and Builtins<34>,Library<36>,Security<22>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id257}@anchor{118c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-35877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35877}: Make parenthesis optional for named expressions in while
statement. Patch by Karthikeyan Singaravelan.

@item 
bpo-35814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35814}: Allow same right hand side expressions in annotated assignments
as in normal ones. In particular, @code{x: Tuple[int, int] = 1, 2} (without
parentheses on the right) is now allowed.

@item 
bpo-35766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35766}: Add the option to parse PEP 484 type comments in the ast
module. (Off by default.) This is merging the key functionality of the
third party fork thereof,
[typed_ast](@indicateurl{https://github.com/python/typed_ast}).

@item 
bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713}: Reorganize Python initialization to get working exceptions and
sys.stderr earlier.

@item 
bpo-33416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33416}: Add end line and end column position information to the Python
AST nodes. This is a C-level backwards incompatible change.

@item 
bpo-35720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35720}: Fixed a minor memory leak in pymain_parse_cmdline_impl function
in Modules/main.c

@item 
bpo-35634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35634}: @code{func(**kwargs)} will now raise an error when @code{kwargs} is a
mapping containing multiple entries with the same key. An error was
already raised when other keyword arguments are passed before @code{**kwargs}
since Python 3.6.

@item 
bpo-35623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35623}: Fix a crash when sorting very long lists. Patch by Stephan
Hohe.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: clang Memory Sanitizer build instrumentation was added to work
around false positives from posix, socket, time, test_io, and
test_faulthandler.

@item 
bpo-35560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35560}: Fix an assertion error in @ref{5de,,format()} in debug build for
floating point formatting with "n" format, zero padding and small width.
Release build is not impacted. Patch by Karthikeyan Singaravelan.

@item 
bpo-35552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35552}: Format characters @code{%s} and @code{%V} in
@ref{8c2,,PyUnicode_FromFormat()} and @code{%s} in @ref{118d,,PyBytes_FromFormat()}
no longer read memory past the limit if @emph{precision} is specified.

@item 
bpo-35504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35504}: Fix segfaults and @ref{6fc,,SystemError}s when deleting certain
attributes. Patch by Zackery Spytz.

@item 
bpo-35504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35504}: Fixed a SystemError when delete the characters_written
attribute of an OSError.

@item 
bpo-35494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35494}: Improved syntax error messages for unbalanced parentheses in
f-string.

@item 
bpo-35444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35444}: Fixed error handling in pickling methods when fail to look up
builtin "getattr". Sped up pickling iterators.

@item 
bpo-35436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35436}: Fix various issues with memory allocation error handling.
Patch by Zackery Spytz.

@item 
bpo-35423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35423}: Separate the signal handling trigger in the eval loop from the
"pending calls" machinery. There is no semantic change and the difference
in performance is insignificant.

@item 
bpo-35357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35357}: Internal attributes' names of unittest.mock._Call and
unittest.mock.MagicProxy (name, parent & from_kall) are now prefixed with
_mock_ in order to prevent clashes with widely used object attributes.
Fixed minor typo in test function name.

@item 
bpo-35372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35372}: Fixed the code page decoder for input longer than 2 GiB
containing undecodable bytes.

@item 
bpo-35336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35336}: Fix PYTHONCOERCECLOCALE=1 environment variable: only coerce the
C locale if the LC_CTYPE locale is "C".

@item 
bpo-31241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31241}: The @emph{lineno} and @emph{col_offset} attributes of AST nodes for list
comprehensions, generator expressions and tuples are now point to the
opening parenthesis or square brace. For tuples without parenthesis they
point to the position of the first item.

@item 
bpo-33954@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33954}: For @ref{5dd,,str.format()}, @code{float.__format__()} and
@code{complex.__format__()} methods for non-ASCII decimal point when using
the "n" formatter.

@item 
bpo-35269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35269}: Fix a possible segfault involving a newly-created coroutine.
Patch by Zackery Spytz.

@item 
bpo-35224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35224}: Implement 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} (assignment expressions). Patch by Emily
Morehouse.

@item 
bpo-32492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32492}: Speed up @code{namedtuple} attribute access by 1.6x using a C
fast-path for the name descriptors. Patch by Pablo Galindo.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: Fixed an out of bounds memory access when parsing a truncated
unicode escape sequence at the end of a string such as @code{'\N'}.  It would
read one byte beyond the end of the memory allocation.

@item 
bpo-35214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35214}: The interpreter and extension modules have had annotations
added so that they work properly under clang's Memory Sanitizer.  A new
configure flag --with-memory-sanitizer has been added to make test builds
of this nature easier to perform.

@item 
bpo-35193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35193}: Fix an off by one error in the bytecode peephole optimizer
where it could read bytes beyond the end of bounds of an array when
removing unreachable code. This bug was present in every release of Python
3.6 and 3.7 until now.

@item 
bpo-35169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35169}: Improved error messages for forbidden assignments.

@item 
bpo-34022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34022}: Fix handling of hash-based bytecode files in @ref{14c,,zipimport}.
Patch by Elvis Pranskevichus.

@item 
bpo-28401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28401}: Debug builds will no longer to attempt to import extension
modules built for the ABI as they were never compatible to begin with.
Patch by Stefano Rivera.

@item 
bpo-29341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29341}: Clarify in the docstrings of @ref{c4,,os} methods that path-like
objects are also accepted as input parameters.

@item 
bpo-35050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35050}: @ref{ef,,socket}: Fix off-by-one bug in length check for
@code{AF_ALG} name and type.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Raise @ref{16d,,ValueError} instead of @ref{a4a,,OverflowError} in case
of a negative @code{_length_} in a @ref{118e,,ctypes.Array} subclass.  Also
raise @ref{1ff,,TypeError} instead of @ref{4aa,,AttributeError} for non-integer
@code{_length_}. Original patch by Oren Milman.

@item 
bpo-16806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16806}: Fix @code{lineno} and @code{col_offset} for multi-line string tokens.

@item 
bpo-35029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35029}: @ref{2d0,,SyntaxWarning} raised as an exception at code generation
time will be now replaced with a @ref{562,,SyntaxError} for better error
reporting.

@item 
bpo-34983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34983}: Expose @ref{118f,,symtable.Symbol.is_nonlocal()} in the symtable
module. Patch by Pablo Galindo.

@item 
bpo-34974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34974}: @ref{172,,bytes} and @ref{173,,bytearray} constructors no longer
convert unexpected exceptions (e.g. @ref{fb5,,MemoryError} and
@ref{2d3,,KeyboardInterrupt}) to @ref{1ff,,TypeError}.

@item 
bpo-34939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34939}: Allow annotated names in module namespace that are declared
global before the annotation happens. Patch by Pablo Galindo.

@item 
bpo-34973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34973}: Fixed crash in @ref{172,,bytes()} when the @ref{1f9,,list} argument is
mutated while it is iterated.

@item 
bpo-34876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34876}: The @emph{lineno} and @emph{col_offset} attributes of the AST for
decorated function and class refer now to the position of the
corresponding @code{def}, @code{async def} and @code{class} instead of the position
of the first decorator. This leads to more correct line reporting in
tracing. This is the only case when the position of child AST nodes can
precede the position of the parent AST node.

@item 
bpo-34879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34879}: Fix a possible null pointer dereference in bytesobject.c.
Patch by Zackery Spytz.

@item 
bpo-34784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34784}: Fix the implementation of PyStructSequence_NewType in order to
create heap allocated StructSequences.

@item 
bpo-32912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32912}: A @ref{2d0,,SyntaxWarning} is now emitted instead of a
@ref{15a,,DeprecationWarning} for invalid escape sequences in string and bytes
literals.

@item 
bpo-34854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34854}: Fixed a crash in compiling string annotations containing a
lambda with a keyword-only argument that doesn't have a default value.

@item 
bpo-34850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34850}: The compiler now produces a @ref{2d0,,SyntaxWarning} when identity
checks (@code{is} and @code{is not}) are used with certain types of literals
(e.g. strings, ints).  These can often work by accident in CPython, but
are not guaranteed by the language spec.  The warning advises users to use
equality tests (@code{==} and @code{!=}) instead.

@item 
bpo-34824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34824}: Fix a possible null pointer dereference in Modules/_ssl.c.
Patch by Zackery Spytz.

@item 
bpo-30156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30156}: The C function @code{property_descr_get()} uses a "cached" tuple
to optimize function calls. But this tuple can be discovered in debug mode
with @code{sys.getobjects()}. Remove the optimization, it's not really
worth it and it causes 3 different crashes last years.

@item 
bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762}: Fix contextvars C API to use PyObject* pointer types.

@item 
bpo-34751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34751}: The hash function for tuples is now based on xxHash which gives
better collision results on (formerly) pathological cases. Additionally,
on 64-bit systems it improves tuple hashes in general. Patch by Jeroen
Demeyer with substantial contributions by Tim Peters.

@item 
bpo-34735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34735}: Fix a memory leak in Modules/timemodule.c.  Patch by Zackery
Spytz.

@item 
bpo-34683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34683}: Fixed a bug where some SyntaxError error pointed to locations
that were off-by-one.

@item 
bpo-34651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34651}: Only allow the main interpreter to fork.  The avoids the
possibility of affecting the main interpreter, which is critical to
operation of the runtime.

@item 
bpo-34653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34653}: Remove unused function PyParser_SimpleParseStringFilename.

@item 
bpo-32236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32236}: Warn that line buffering is not supported if @ref{16f,,open()} is
called with binary mode and @code{buffering=1}.

@item 
bpo-34641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34641}: Further restrict the syntax of the left-hand side of keyword
arguments in function calls. In particular, @code{f((keyword)=arg)} is now
disallowed.

@item 
bpo-34637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34637}: Make the @emph{start} argument to @emph{sum()} visible as a keyword
argument.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Do not assume signed integer overflow behavior (C undefined
behavior) when performing set hash table resizing.

@item 
bpo-34588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34588}: Fix an off-by-one in the recursive call pruning feature of
traceback formatting.

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: On Windows, the LC_CTYPE is now set to the user preferred
locale at startup. Previously, the LC_CTYPE locale was "C" at startup, but
changed when calling setlocale(LC_CTYPE, "") or setlocale(LC_ALL, "").

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Standard streams like sys.stdout now use the "surrogateescape"
error handler, instead of "strict", on the POSIX locale (when the C locale
is not coerced and the UTF-8 Mode is disabled).

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Fix the error handler of standard streams like sys.stdout:
PYTHONIOENCODING=":" is now ignored instead of setting the error handler
to "strict".

@item 
bpo-34485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34485}: Python now gets the locale encoding with C code to initialize
the encoding of standard streams like sys.stdout. Moreover, the encoding
is now initialized to the Python codec name to get a normalized encoding
name and to ensure that the codec is loaded. The change avoids importing
_bootlocale and _locale modules at startup by default.

@item 
bpo-34527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34527}: On FreeBSD, Py_DecodeLocale() and Py_EncodeLocale() now also
forces the ASCII encoding if the LC_CTYPE locale is "POSIX", not only if
the LC_CTYPE locale is "C".

@item 
bpo-34527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34527}: The UTF-8 Mode is now also enabled by the "POSIX" locale, not
only by the "C" locale.

@item 
bpo-34403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34403}: On HP-UX with C or POSIX locale, sys.getfilesystemencoding()
now returns "ascii" instead of "roman8" (when the UTF-8 Mode is disabled
and the C locale is not coerced).

@item 
bpo-34523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34523}: The Python filesystem encoding is now read earlier during the
Python initialization.

@item 
bpo-12458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12458}: Tracebacks show now correct line number for subexpressions in
multiline expressions. Tracebacks show now the line number of the first
line for multiline expressions instead of the line number of the last
subexpression.

@item 
bpo-34408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34408}: Prevent a null pointer dereference and resource leakage in
@code{PyInterpreterState_New()}.

@item 
bpo-34400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34400}: Fix undefined behavior in parsetok.c.  Patch by Zackery Spytz.

@item 
bpo-33073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33073}: Added as_integer_ratio to ints to make them more interoperable
with floats.

@item 
bpo-34377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34377}: Update valgrind suppression list to use
@code{_PyObject_Free}/@code{_PyObject_Realloc} instead of
@code{PyObject_Free}/@code{PyObject_Realloc}.

@item 
bpo-34353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34353}: Added the "socket" option in the @ref{b7e,,stat.filemode()} Python
implementation to match the C implementation.

@item 
bpo-34320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34320}: Fix @code{dict(od)} didn't copy iteration order of OrderedDict.

@item 
bpo-34113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34113}: Fixed crash on debug builds when opcode stack was adjusted with
negative numbers. Patch by Constantin Petrisor.

@item 
bpo-34100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34100}: Compiler now merges constants in tuples and frozensets
recursively. Code attributes like @code{co_names} are merged too.

@item 
bpo-34151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34151}: Performance of list concatenation, repetition and slicing
operations is slightly improved. Patch by Sergey Fedoseev.

@item 
bpo-34170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34170}: -X dev: it is now possible to override the memory allocator
using PYTHONMALLOC even if the developer mode is enabled.

@item 
bpo-33237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33237}: Improved @ref{4aa,,AttributeError} message for partially
initialized module.

@item 
bpo-34149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34149}: Fix min and max functions to get default behavior when key is
None.

@item 
bpo-34125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34125}: Profiling of unbound built-in methods now works when
@code{**kwargs} is given.

@item 
bpo-34141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34141}: Optimized pickling atomic types (None, bool, int, float, bytes,
str).

@item 
bpo-34126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34126}: Fix crashes when profiling certain invalid calls of unbound
methods. Patch by Jeroen Demeyer.

@item 
bpo-24618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24618}: Fixed reading invalid memory when create the code object with
too small varnames tuple or too large argument counts.

@item 
bpo-34068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34068}: In @ref{1190,,io.IOBase.close()}, ensure that the
@ref{1191,,closed} attribute is not set with a live exception.
Patch by Zackery Spytz and Serhiy Storchaka.

@item 
bpo-34087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34087}: Fix buffer overflow while converting unicode to numeric values.

@item 
bpo-34080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34080}: Fixed a memory leak in the compiler when it raised some
uncommon errors during tokenizing.

@item 
bpo-34066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34066}: Disabled interruption by Ctrl-C between calling @code{open()} and
entering a @strong{with} block in @code{with open()}.

@item 
bpo-34042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34042}: Fix dict.copy() to maintain correct total refcount (as reported
by sys.gettotalrefcount()).

@item 
bpo-33418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33418}: Fix potential memory leak in function object when it creates
reference cycle.

@item 
bpo-33985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33985}: Implement contextvars.ContextVar.name attribute.

@item 
bpo-33956@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33956}: Update vendored Expat library copy to version 2.2.5.

@item 
bpo-24596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24596}: Decref the module object in @ref{1012,,PyRun_SimpleFileExFlags()}
before calling @ref{1079,,PyErr_Print()}.  Patch by Zackery Spytz.

@item 
bpo-33451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33451}: Close directly executed pyc files before calling
@code{PyEval_EvalCode()}.

@item 
bpo-1617161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1617161}: The hash of @code{BuiltinMethodType} instances (methods of
built-in classes) now depends on the hash of the identity of @emph{__self__}
instead of its value. The hash and equality of @code{ModuleType} and
@code{MethodWrapperType} instances (methods of user-defined classes and
some methods of built-in classes like @code{str.__add__}) now depend on the
hash and equality of the identity of @emph{__self__} instead of its value.
@code{MethodWrapperType} instances no longer support ordering.

@item 
bpo-33824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33824}: Fix "LC_ALL=C python3.7 -V": reset properly the command line
parser when the encoding changes after reading the Python configuration.

@item 
bpo-33803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33803}: Fix a crash in hamt.c caused by enabling GC tracking for an
object that hadn't all of its fields set to NULL.

@item 
bpo-33738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33738}: Seven macro incompatibilities with the Limited API were fixed,
and the macros @ref{1192,,PyIter_Check()}, @ref{26f,,PyIndex_Check()} and
@code{PyExceptionClass_Name()} were added as functions. A script for
automatic macro checks was added.

@item 
bpo-33786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33786}: Fix asynchronous generators to handle GeneratorExit in athrow()
correctly

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: @code{PyRun_SimpleFileExFlags} removes @code{__cached__} from module
in addition to @code{__file__}.

@item 
bpo-33706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33706}: Fix a crash in Python initialization when parsing the command
line options. Thanks Christoph Gohlke for the bug report and the fix!

@item 
bpo-33597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33597}: Reduce @code{PyGC_Head} size from 3 words to 2 words.

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{c1b,,gc.garbage} list. @code{PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-33462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33462}: Make dict and dict views reversible. Patch by Rémi Lapeyre.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: A @ref{3e4,,RuntimeError} is now raised when the custom metaclass
doesn't provide the @code{__classcell__} entry in the namespace passed to
@code{type.__new__}.  A @ref{15a,,DeprecationWarning} was emitted in Python
3.6--3.7.

@item 
bpo-33499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33499}: Add 
@geindex PYTHONPYCACHEPREFIX
@geindex 环境变量; PYTHONPYCACHEPREFIX
@ref{296,,PYTHONPYCACHEPREFIX} environment variable and
@ref{297,,-X} @code{pycache_prefix} command-line option to set an alternate
root directory for writing module bytecode cache files.

@item 
bpo-25711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25711}: The @ref{14c,,zipimport} module has been rewritten in pure Python.

@item 
bpo-33509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33509}: Fix module_globals parameter of warnings.warn_explicit(): don't
crash if module_globals is not a dict.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.

@item 
bpo-33475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33475}: Fixed miscellaneous bugs in converting annotations to strings
and optimized parentheses in the string representation.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Added support for the @code{setpgroup}, @code{resetids}, @code{setsigmask},
@code{setsigdef} and @code{scheduler} parameters of @code{posix_spawn}. Patch by Pablo
Galindo.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-33363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33363}: Raise a SyntaxError for @code{async with} and @code{async for}
statements outside of async functions.

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-33128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33128}: Fix a bug that causes PathFinder to appear twice on
sys.meta_path. Patch by Pablo Galindo Salgado.

@item 
bpo-33331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33331}: Modules imported last are now cleared first at interpreter
shutdown.

@item 
bpo-33312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33312}: Fixed clang ubsan (undefined behavior sanitizer) warnings in
dictobject.c by adjusting how the internal struct _dictkeysobject shared
keys structure is declared.

@item 
bpo-33305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33305}: Improved syntax error messages for invalid numerical literals.

@item 
bpo-33306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33306}: Improved syntax error messages for unbalanced parentheses.

@item 
bpo-33234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33234}: The list constructor will pre-size and not over-allocate when
the input length is known.

@item 
bpo-33270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33270}: Intern the names for all anonymous code objects.  Patch by
Zackery Spytz.

@item 
bpo-30455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30455}: The C and Python code and the documentation related to tokens
are now generated from a single source file @code{Grammar/Tokens}.

@item 
bpo-33176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33176}: Add a @code{toreadonly()} method to memoryviews.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-33205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33205}: Change dict growth function from
@code{round_up_to_power_2(used*2+hashtable_size/2)} to
@code{round_up_to_power_2(used*3)}.  Previously, dict is shrinked only when
@code{used == 0}. Now dict has more chance to be shrinked.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.

@item 
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}: When using the -m switch, sys.path[0] is now explicitly
expanded as the @emph{starting} working directory, rather than being left as
the empty path (which allows imports from the current working directory at
the time of the import)

@item 
bpo-33138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33138}: Changed standard error message for non-pickleable and
non-copyable types. It now says "cannot pickle" instead of "can't pickle"
or "cannot serialize".

@item 
bpo-33018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33018}: Improve consistency of errors raised by @code{issubclass()} when
called with a non-class and an abstract base class as the first and second
arguments, respectively. Patch by Josh Bronson.

@item 
bpo-33083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33083}: @code{math.factorial} no longer accepts arguments that are not
int-like. Patch by Pablo Galindo.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Added new opcode @ref{405,,END_ASYNC_FOR} and fixes the
following issues:


@itemize *

@item 
Setting global @ref{1193,,StopAsyncIteration} no longer breaks @code{async for}
loops.

@item 
Jumping into an @code{async for} loop is now disabled.

@item 
Jumping out of an @code{async for} loop no longer corrupts the stack.
@end itemize

@item 
bpo-25750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25750}: Fix rare Python crash due to bad refcounting in
@code{type_getattro()} if a descriptor deletes itself from the class. Patch
by Jeroen Demeyer.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed bytecode generation for "async for" with a complex
target. A StopAsyncIteration raised on assigning or unpacking will be now
propagated instead of stopping the iteration.

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-33005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33005}: Fix a crash on fork when using a custom memory allocator (ex:
using PYTHONMALLOC env var). _PyGILState_Reinit() and
_PyInterpreterState_Enable() now use the default RAW memory allocator to
allocate a new interpreters mutex on fork.

@item 
bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}: Due to unexpected compatibility issues discovered during
downstream beta testing, reverted bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}. @code{docstring} field is
removed from Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes
which was added in 3.7a1.  Docstring expression is restored as a first
statement in their body. Based on patch by Inada Naoki.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32946}: Importing names from already imported module with "from ...
import ..." is now 30% faster if the module is not a package.

@item 
bpo-32932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32932}: Make error message more revealing when there are non-str
objects in @code{__all__}.

@item 
bpo-32925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32925}: Optimized iterating and containing test for literal lists
consisting of non-constants: @code{x in [a, b]} and @code{for x in [a, b]}. The
case of all constant elements already was optimized.

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-32836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32836}: Don't use temporary variables in cases of list/dict/set
comprehensions

@item 
bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356}: Remove the new API added in bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356} (gc.ensure_disabled()
context manager).

@item 
bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}: For namespace packages, ensure that both @code{__file__} and
@code{__spec__.origin} are set to None.

@item 
bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}: Make sure @code{__spec__.loader} matches @code{__loader__} for
namespace packages.

@item 
bpo-32711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32711}: Fix the warning messages for Python/ast_unparse.c. Patch by
Stéphane Wirtel

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.

@item 
bpo-32489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32489}: A @ref{2c2,,continue} statement is now allowed in the
@ref{2c3,,finally} clause.

@item 
bpo-17611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17611}: Simplified the interpreter loop by moving the logic of
unrolling the stack of blocks into the compiler. The compiler emits now
explicit instructions for adjusting the stack of values and calling the
cleaning up code for @ref{403,,break}, @ref{2c2,,continue} and
@ref{2cf,,return}.

Removed opcodes @code{BREAK_LOOP}, @code{CONTINUE_LOOP},
@code{SETUP_LOOP} and @code{SETUP_EXCEPT}. Added new opcodes
@ref{404,,ROT_FOUR}, @code{BEGIN_FINALLY} and @code{CALL_FINALLY} and
@code{POP_FINALLY}. Changed the behavior of @code{END_FINALLY} and
@code{WITH_CLEANUP_START}.

@item 
bpo-32285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32285}: New function unicodedata.is_normalized, which can check whether
a string is in a specific normal form.

@item 
bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}: Yield expressions are now disallowed in comprehensions and
generator expressions except the expression for the outermost iterable.

@item 
bpo-32117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32117}: Iterable unpacking is now allowed without parentheses in yield
and return statements, e.g. @code{yield 1, 2, 3, *rest}. Thanks to David
Cuthbert for the change and Jordan Chapman for added tests.

@item 
bpo-31902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31902}: Fix the @code{col_offset} attribute for ast nodes
@code{ast.AsyncFor}, @code{ast.AsyncFunctionDef}, and @code{ast.AsyncWith}.
Previously, @code{col_offset} pointed to the keyword after @code{async}.

@item 
bpo-25862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25862}: Fix assertion failures in the @code{tell()} method of
@code{io.TextIOWrapper}. Patch by Zackery Spytz.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @ref{1194,,ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.

@item 
bpo-31577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31577}: Fix a crash in @ref{b22,,os.utime()} in case of a bad ns argument. Patch
by Oren Milman.

@item 
bpo-29832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29832}: Remove references to 'getsockaddrarg' from various socket error
messages. Patch by Oren Milman.
@end itemize

@node Library<36>,Documentation<26>,Core and Builtins<34>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id258}@anchor{1195}
@subsubsection Library



@itemize -

@item 
bpo-35845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35845}: Add 'order' parameter to memoryview.tobytes().

@item 
bpo-35864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35864}: The _asdict() method for collections.namedtuple now returns a
regular dict instead of an OrderedDict.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: An ExitStack is now used internally within subprocess.POpen to
clean up pipe file handles. No behavior change in normal operation. But if
closing one handle were ever to cause an exception, the others will now be
closed instead of leaked.  (patch by Giampaolo Rodola)

@item 
bpo-35847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35847}: RISC-V needed the CTYPES_PASS_BY_REF_HACK.  Fixes ctypes
Structure test_pass_by_value.

@item 
bpo-35813@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35813}: Shared memory submodule added to multiprocessing to avoid need
for serialization between processes

@item 
bpo-35780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35780}: Fix lru_cache() errors arising in recursive, reentrant, or
multi-threaded code. These errors could result in orphan links and in the
cache being trapped in a state with fewer than the specified maximum
number of links. Fix handling of negative maxsize which should have been
treated as zero. Fix errors in toggling the "full" status flag. Fix
misordering of links when errors are encountered.  Sync-up the C code and
pure Python code for the space saving path in functions with a single
positional argument. In this common case, the space overhead of an lru
cache entry is reduced by almost half.  Fix counting of cache misses. In
error cases, the miss count was out of sync with the actual number of
times the underlying user function was called.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: @ref{388,,os.posix_spawn()} and @ref{1196,,os.posix_spawnp()} now have a
@emph{setsid} parameter.

@item 
bpo-23846@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23846}: @ref{2e5,,asyncio.ProactorEventLoop} now catches and logs send
errors when the self-pipe is full.

@item 
bpo-34323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34323}: @ref{9,,asyncio}: Enhance @code{IocpProactor.close()} log: wait 1
second before the first log, then log every second. Log also the number of
seconds since @code{close()} was called.

@item 
bpo-35674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35674}: Add a new @ref{1196,,os.posix_spawnp()} function. Patch by Joannah
Nanjekye.

@item 
bpo-35733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35733}: @code{ast.Constant(boolean)} no longer an instance of
@code{ast.Num}.  Patch by Anthony Sottile.

@item 
bpo-35726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35726}: QueueHandler.prepare() now makes a copy of the record before
modifying and enqueueing it, to avoid affecting other handlers in the
chain.

@item 
bpo-35719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35719}: Sped up multi-argument @ref{b1,,math} functions atan2(),
copysign(), remainder() and hypot() by 1.3--2.5 times.

@item 
bpo-35717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35717}: Fix KeyError exception raised when using enums and compile.
Patch contributed by Rémi Lapeyre.

@item 
bpo-35699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35699}: Fixed detection of Visual Studio Build Tools 2017 in distutils

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: Fix memory leaks in asyncio ProactorEventLoop on overlapped
operation failure.

@item 
bpo-35702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35702}: The @ref{36c,,time.CLOCK_UPTIME_RAW} constant is now available for
macOS 10.12.

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: Fix a memory leak in asyncio in the ProactorEventLoop when
@code{ReadFile()} or @code{WSASend()} overlapped operation fail immediately:
release the internal buffer.

@item 
bpo-35682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35682}: Fix @code{asyncio.ProactorEventLoop.sendfile()}: don't attempt to
set the result of an internal future if it's already done.

@item 
bpo-35283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35283}: Add a deprecated warning for the
@code{threading.Thread.isAlive()} method. Patch by Dong-hee Na.

@item 
bpo-35664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35664}: Improve operator.itemgetter() performance by 33% with optimized
argument handling and with adding a fast path for the common case of a
single non-negative integer index into a tuple (which is the typical use
case in the standard library).

@item 
bpo-35643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35643}: Fixed a SyntaxWarning: invalid escape sequence in
Modules/_sha3/cleanup.py. Patch by Mickaël Schoentgen.

@item 
bpo-35619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35619}: Improved support of custom data descriptors in @ref{175,,help()} and
@ref{d9,,pydoc}.

@item 
bpo-28503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28503}: The @ref{28,,crypt} module now internally uses the @code{crypt_r()} library
function instead of @ref{28,,crypt()} when available.

@item 
bpo-35614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35614}: Fixed help() on metaclasses. Patch by Sanyam Khurana.

@item 
bpo-35568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35568}: Expose @code{raise(signum)} as @code{raise_signal}

@item 
bpo-35588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35588}: The floor division and modulo operations and the @ref{294,,divmod()}
function on @ref{2c5,,fractions.Fraction} types are 2--4x faster. Patch by
Stefan Behnel.

@item 
bpo-35585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35585}: Speed-up building enums by value, e.g. http.HTTPStatus(200).

@item 
bpo-30561@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30561}: random.gammavariate(1.0, beta) now computes the same result as
random.expovariate(1.0 / beta).  This synchronizes the two algorithms and
eliminates some idiosyncrasies in the old implementation.  It does however
produce a difference stream of random variables than it used to.

@item 
bpo-35537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35537}: The @ref{f9,,subprocess} module can now use the
@ref{388,,os.posix_spawn()} function in some cases for better performance.

@item 
bpo-35526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35526}: Delaying the 'joke' of barry_as_FLUFL.mandatory to Python
version 4.0

@item 
bpo-35523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35523}: Remove @ref{2a,,ctypes} callback workaround: no longer create a
callback at startup. Avoid SELinux alert on @code{import ctypes} and @code{import
uuid}.

@item 
bpo-31784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31784}: @ref{520,,uuid.uuid1()} now calls @ref{43c,,time.time_ns()} rather than
@code{int(time.time() * 1e9)}.

@item 
bpo-35513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35513}: @code{TextTestRunner} of
@code{unittest.runner} now uses @ref{3d4,,time.perf_counter()} rather than
@ref{436,,time.time()} to measure the execution time of a test:
@ref{436,,time.time()} can go backwards, whereas @ref{3d4,,time.perf_counter()} is
monotonic.

@item 
bpo-35502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35502}: Fixed reference leaks in
@ref{384,,xml.etree.ElementTree.TreeBuilder} in case of unfinished building
of the tree (in particular when an error was raised during parsing XML).

@item 
bpo-35348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35348}: Make @ref{1197,,platform.architecture()} parsing of @code{file} command
output more reliable: add the @code{-b} option to the @code{file} command to
omit the filename, force the usage of the C locale, and search also the
"shared object" pattern.

@item 
bpo-35491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35491}: @ref{b7,,multiprocessing}: Add @code{Pool.__repr__()} and enhance
@code{BaseProcess.__repr__()} (add pid and parent pid) to ease debugging.
Pool state constant values are now strings instead of integers, for
example @code{RUN} value becomes @code{'RUN'} instead of @code{0}.

@item 
bpo-35477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35477}: @code{multiprocessing.Pool.__enter__()} now fails if the pool is
not running: @code{with pool:} fails if used more than once.

@item 
bpo-31446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31446}: Copy command line that was passed to CreateProcessW since this
function can change the content of the input buffer.

@item 
bpo-35471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35471}: Python 2.4 dropped MacOS 9 support. The macpath module was
deprecated in Python 3.7. The module is now removed.

@item 
bpo-23057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23057}: Unblock Proactor event loop when keyboard interrupt is received
on Windows

@item 
bpo-35052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35052}: Fix xml.dom.minidom cloneNode() on a document with an entity:
pass the correct arguments to the user data handler of an entity.

@item 
bpo-20239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20239}: Allow repeated assignment deletion of
@ref{37a,,unittest.mock.Mock} attributes. Patch by Pablo Galindo.

@item 
bpo-17185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17185}: Set @code{__signature__} on mock for @ref{a0,,inspect} to get
signature. Patch by Karthikeyan Singaravelan.

@item 
bpo-35445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35445}: Memory errors during creating posix.environ no longer ignored.

@item 
bpo-35415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35415}: Validate fileno= argument to socket.socket().

@item 
bpo-35424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35424}: @code{multiprocessing.Pool} destructor now emits
@ref{5d3,,ResourceWarning} if the pool is still running.

@item 
bpo-35330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35330}: When a @code{Mock} instance was used to wrap an object, if
@code{side_effect} is used in one of the mocks of it methods, don't call the
original implementation and return the result of using the side effect the
same way that it is done with return_value.

@item 
bpo-35346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35346}: Drop Mac OS 9 and Rhapsody support from the @ref{ce,,platform}
module. Rhapsody last release was in 2000. Mac OS 9 last release was in
2001.

@item 
bpo-10496@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10496}: @code{check_environ()} of
@code{distutils.utils} now catches @ref{3f1,,KeyError} on calling
@ref{1198,,pwd.getpwuid()}: don't create the @code{HOME} environment variable in
this case.

@item 
bpo-10496@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10496}: @code{posixpath.expanduser()} now returns the input @emph{path}
unchanged if the @code{HOME} environment variable is not set and the current
user has no home directory (if the current user identifier doesn't exist
in the password database). This change fix the @ref{eb,,site} module if the
current user doesn't exist in the password database (if the user has no
home directory).

@item 
bpo-35389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35389}: @ref{1199,,platform.libc_ver()} now uses
@code{os.confstr('CS_GNU_LIBC_VERSION')} if available and the @emph{executable}
parameter is not set.

@item 
bpo-35394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35394}: Add empty slots to asyncio abstract protocols.

@item 
bpo-35310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35310}: Fix a bug in @ref{770,,select.select()} where, in some cases, the
file descriptor sequences were returned unmodified after a signal
interruption, even though the file descriptors might not be ready yet.
@ref{770,,select.select()} will now always return empty lists if a timeout has
occurred.  Patch by Oran Avraham.

@item 
bpo-35380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35380}: Enable TCP_NODELAY on Windows for proactor asyncio event loop.

@item 
bpo-35341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35341}: Add generic version of @code{collections.OrderedDict} to the
@code{typing} module. Patch by Ismo Toijala.

@item 
bpo-35371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35371}: Fixed possible crash in @code{os.utime()} on Windows when pass
incorrect arguments.

@item 
bpo-35346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35346}: @ref{119a,,platform.uname()} now redirects @code{stderr} to
@ref{119b,,os.devnull} when running external programs like @code{cmd /c ver}.

@item 
bpo-35066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35066}: Previously, calling the strftime() method on a datetime object
with a trailing '%' in the format string would result in an exception.
However, this only occurred when the datetime C module was being used; the
python implementation did not match this behavior. Datetime is now PEP-399
compliant, and will not throw an exception on a trailing '%'.

@item 
bpo-35345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35345}: The function @code{platform.popen} has been removed, it was
deprecated since Python 3.3: use @ref{3d3,,os.popen()} instead.

@item 
bpo-35344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35344}: On macOS, @ref{119c,,platform.platform()} now uses
@ref{119d,,platform.mac_ver()}, if it returns a non-empty release string, to get
the macOS version rather than the darwin version.

@item 
bpo-35312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35312}: Make @code{lib2to3.pgen2.parse.ParseError} round-trip pickle-able.
Patch by Anthony Sottile.

@item 
bpo-35308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35308}: Fix regression in @code{webbrowser} where default browsers may be
preferred over browsers in the @code{BROWSER} environment variable.

@item 
bpo-24746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24746}: Avoid stripping trailing whitespace in doctest fancy diff.
Original patch by R. David Murray & Jairo Trad. Enhanced by Sanyam
Khurana.

@item 
bpo-28604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28604}: @ref{58d,,locale.localeconv()} now sets temporarily the @code{LC_CTYPE}
locale to the @code{LC_MONETARY} locale if the two locales are different and
monetary strings are non-ASCII. This temporary change affects other
threads.

@item 
bpo-35277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35277}: Update ensurepip to install pip 18.1 and setuptools 40.6.2.

@item 
bpo-24209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24209}: Adds IPv6 support when invoking http.server directly.

@item 
bpo-35226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35226}: Recursively check arguments when testing for equality of
@ref{1115,,unittest.mock.call} objects and add note that tracking of
parameters used to create ancestors of mocks in @code{mock_calls} is not
possible.

@item 
bpo-29564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29564}: The warnings module now suggests to enable tracemalloc if the
source is specified, the tracemalloc module is available, but tracemalloc
is not tracing memory allocations.

@item 
bpo-35189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35189}: Modify the following fnctl function to retry if interrupted by
a signal (EINTR): flock, lockf, fnctl

@item 
bpo-30064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30064}: Use add_done_callback() in sock_* asyncio API to unsubscribe
reader/writer early on calcellation.

@item 
bpo-35186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35186}: Removed the "built with" comment added when @code{setup.py upload}
is used with either @code{bdist_rpm} or @code{bdist_dumb}.

@item 
bpo-35152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35152}: Allow sending more than 2 GB at once on a multiprocessing
connection on non-Windows systems.

@item 
bpo-35062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35062}: Fix incorrect parsing of
@code{_io.IncrementalNewlineDecoder}'s @emph{translate} argument.

@item 
bpo-35065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35065}: Remove @code{StreamReaderProtocol._untrack_reader}. The call to
@code{_untrack_reader} is currently performed too soon, causing the protocol to
forget about the reader before @code{connection_lost} can run and feed the EOF
to the reader.

@item 
bpo-34160@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34160}: ElementTree and minidom now preserve the attribute order
specified by the user.

@item 
bpo-35079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35079}: Improve difflib.SequenceManager.get_matching_blocks doc by
adding 'non-overlapping' and changing '!=' to '<'.

@item 
bpo-33710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33710}: Deprecated @code{l*gettext()} functions and methods in the
@ref{87,,gettext} module. They return encoded bytes instead of Unicode
strings and are artifacts from Python 2 times. Also deprecated functions
and methods related to setting the charset for @code{l*gettext()} functions
and methods.

@item 
bpo-35017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35017}: @ref{b6c,,socketserver.BaseServer.serve_forever()} now exits
immediately if it's @ref{119e,,shutdown()} method is
called while it is polling for new events.

@item 
bpo-35024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35024}: @ref{9a,,importlib} no longer logs @code{wrote} redundantly
after @code{(created|could not create)} is already logged.
Patch by Quentin Agren.

@item 
bpo-35047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35047}: @code{unittest.mock} now includes mock calls in exception messages
if @code{assert_not_called}, @code{assert_called_once}, or
@code{assert_called_once_with} fails. Patch by Petter Strandmark.

@item 
bpo-31047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31047}: Fix @code{ntpath.abspath} regression where it didn't remove a
trailing separator on Windows. Patch by Tim Graham.

@item 
bpo-35053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35053}: tracemalloc now tries to update the traceback when an object is
reused from a "free list" (optimization for faster object creation, used
by the builtin list type for example).

@item 
bpo-31553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31553}: Add the --json-lines option to json.tool. Patch by hongweipeng.

@item 
bpo-34794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34794}: Fixed a leak in Tkinter when pass the Python wrapper around
Tcl_Obj back to Tcl/Tk.

@item 
bpo-34909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34909}: Enum: fix grandchildren subclassing when parent mixed with
concrete data types.

@item 
bpo-35022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35022}: @ref{87e,,unittest.mock.MagicMock} now supports the
@code{__fspath__} method (from @ref{5ee,,os.PathLike}).

@item 
bpo-35008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35008}: Fixed references leaks when call the @code{__setstate__()} method
of @ref{21e,,xml.etree.ElementTree.Element} in the C implementation for
already initialized element.

@item 
bpo-23420@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23420}: Verify the value for the parameter '-s' of the cProfile CLI.
Patch by Robert Kuska

@item 
bpo-33947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33947}: dataclasses now handle recursive reprs without raising
RecursionError.

@item 
bpo-34890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34890}: Make @ref{7f3,,inspect.iscoroutinefunction()},
@ref{119f,,inspect.isgeneratorfunction()} and @ref{11a0,,inspect.isasyncgenfunction()}
work with @ref{8bf,,functools.partial()}. Patch by Pablo Galindo.

@item 
bpo-34521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34521}: Use @ref{11a1,,socket.CMSG_SPACE()} to calculate ancillary data size
instead of @ref{11a2,,socket.CMSG_LEN()} in
@code{multiprocessing.reduction.recvfds()} as 
@geindex RFC; RFC 3542
RFC 3542@footnote{https://tools.ietf.org/html/rfc3542.html} requires the use
of the former for portable applications.

@item 
bpo-31522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31522}: The @code{mailbox.mbox.get_string} function @emph{from_} parameter can
now successfully be set to a non-default value.

@item 
bpo-34970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34970}: Protect tasks weak set manipulation in @code{asyncio.all_tasks()}

@item 
bpo-34969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34969}: gzip: Add --fast, --best on the gzip CLI, these parameters will
be used for the fast compression method (quick) or the best method
compress (slower, but smaller file). Also, change the default compression
level to 6 (tradeoff).

@item 
bpo-16965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16965}: The @ref{11a3,,2to3} @ref{11a4,,execfile} fixer now opens the file
with mode @code{'rb'}.  Patch by Zackery Spytz.

@item 
bpo-34966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34966}: @ref{d9,,pydoc} now supports aliases not only to methods defined
in the end class, but also to inherited methods.  The docstring is not
duplicated for aliases.

@item 
bpo-34926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34926}: @ref{11a5,,mimetypes.MimeTypes.guess_type()} now accepts
@ref{47b,,path-like object} in addition to url strings. Patch by Mayank
Asthana.

@item 
bpo-23831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23831}: Add @code{moveto()} method to the @code{tkinter.Canvas} widget. Patch
by Juliette Monsel.

@item 
bpo-34941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34941}: Methods @code{find()}, @code{findtext()} and @code{findall()} of the
@code{Element} class in the @ref{140,,xml.etree.ElementTree} module are now able
to find children which are instances of @code{Element} subclasses.

@item 
bpo-32680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32680}: @ref{1df,,smtplib.SMTP} objects now always have a @code{sock}
attribute present

@item 
bpo-34769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34769}: Fix for async generators not finalizing when event loop is in
debug mode and garbage collector runs in another thread.

@item 
bpo-34936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34936}: Fix @code{TclError} in @code{tkinter.Spinbox.selection_element()}.
Patch by Juliette Monsel.

@item 
bpo-34829@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34829}: Add methods @code{selection_from}, @code{selection_range},
@code{selection_present} and @code{selection_to} to the @code{tkinter.Spinbox} for
consistency with the @code{tkinter.Entry} widget. Patch by Juliette Monsel.

@item 
bpo-34911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34911}: Added @emph{secure_protocols} argument to
@emph{http.cookiejar.DefaultCookiePolicy} to allow for tweaking of protocols
and also to add support by default for @emph{wss}, the secure websocket
protocol.

@item 
bpo-34922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34922}: Fixed integer overflow in the @ref{11a6,,digest()}
and @ref{11a7,,hexdigest()} methods for the SHAKE algorithm in
the @ref{8c,,hashlib} module.

@item 
bpo-34925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34925}: 25% speedup in argument parsing for the functions in the bisect
module.

@item 
bpo-34900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34900}: Fixed @ref{fba,,unittest.TestCase.debug()} when used to call test
methods with subtests.  Patch by Bruno Oliveira.

@item 
bpo-34844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34844}: logging.Formatter enhancement - Ensure styles and fmt matches
in logging.Formatter - Added validate method in each format style class:
StrFormatStyle, PercentStyle, StringTemplateStyle. - This method is called
in the constructor of logging.Formatter class - Also re-raise the KeyError
in the format method of each style class, so it would a bit clear that
it's an error with the invalid format fields.

@item 
bpo-34897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34897}: Adjust test.support.missing_compiler_executable check so that a
nominal command name of "" is ignored. Patch by Michael Felt.

@item 
bpo-34871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34871}: Fix inspect module polluted @code{sys.modules} when parsing
@code{__text_signature__} of callable.

@item 
bpo-34898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34898}: Add @code{mtime} argument to @ref{309,,gzip.compress} for reproducible
output. Patch by Guo Ci Teo.

@item 
bpo-28441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28441}: On Cygwin and MinGW, ensure that @code{sys.executable} always
includes the full filename in the path, including the @code{.exe} suffix
(unless it is a symbolic link).

@item 
bpo-34866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34866}: Adding @code{max_num_fields} to @code{cgi.FieldStorage} to make DOS
attacks harder by limiting the number of @code{MiniFieldStorage} objects
created by @code{FieldStorage}.

@item 
bpo-34711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34711}: http.server ensures it reports HTTPStatus.NOT_FOUND when the
local path ends with "/" and is not a directory, even if the underlying OS
(e.g. AIX) accepts such paths as a valid file reference. Patch by Michael
Felt.

@item 
bpo-34872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34872}: Fix self-cancellation in C implementation of asyncio.Task

@item 
bpo-34849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34849}: Don't log waiting for @code{selector.select} in asyncio loop
iteration. The waiting is pretty normal for any asyncio program, logging
its time just adds a noise to logs without any useful information
provided.

@item 
bpo-34022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34022}: The 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable no longer
overrides the value of the @emph{invalidation_mode} argument to
@ref{34a,,py_compile.compile()}, and determines its default value instead.

@item 
bpo-34819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34819}: Use a monotonic clock to compute timeouts in
@code{Executor.map()} and @code{as_completed()}, in order to prevent
timeouts from deviating when the system clock is adjusted.

@item 
bpo-34758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34758}: Add .wasm -> application/wasm to list of recognized file types
and content type headers

@item 
bpo-34789@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34789}: @ref{11a8,,xml.sax.make_parser()} now accepts any iterable as its
@emph{parser_list} argument.  Patch by Andrés Delfino.

@item 
bpo-34334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34334}: In @code{QueueHandler}, clear @code{exc_text} from
@code{LogRecord} to prevent traceback from being written twice.

@item 
bpo-34687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34687}: On Windows, asyncio now uses ProactorEventLoop, instead of
SelectorEventLoop, by default.

@item 
bpo-5950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5950}: Support reading zip files with archive comments in
@ref{14c,,zipimport}.

@item 
bpo-32892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32892}: The parser now represents all constants as
@ref{3ae,,ast.Constant} instead of using specific constant AST types
(@code{Num}, @code{Str}, @code{Bytes}, @code{NameConstant} and @code{Ellipsis}). These
classes are considered deprecated and will be removed in future Python
versions.

@item 
bpo-34728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34728}: Add deprecation warning when @code{loop} is used in methods:
@ref{3b2,,asyncio.sleep}, @ref{208,,asyncio.wait} and @ref{191,,asyncio.wait_for}.

@item 
bpo-34738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34738}: ZIP files created by @ref{38,,distutils} will now include entries
for directories.

@item 
bpo-34659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34659}: Add an optional @emph{initial} argument to itertools.accumulate().

@item 
bpo-29577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29577}: Support multiple mixin classes when creating Enums.

@item 
bpo-34670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34670}: Add SSLContext.post_handshake_auth and
SSLSocket.verify_client_post_handshake for TLS 1.3's post handshake
authentication feature.

@item 
bpo-32718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32718}: The Activate.ps1 script from venv works with PowerShell Core
6.1 and is now available under all operating systems.

@item 
bpo-31177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31177}: Fix bug that prevented using @ref{6ab,,reset_mock} on mock instances with deleted attributes

@item 
bpo-34672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34672}: Add a workaround, so the @code{'Z'} @ref{c40,,time.strftime()}
specifier on the musl C library can work in some cases.

@item 
bpo-34666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34666}: Implement @code{asyncio.StreamWriter.awrite} and
@code{asyncio.StreamWriter.aclose()} coroutines.  Methods are needed for
providing a consistent stream API with control flow switched on by
default.

@item 
bpo-6721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6721}: Acquire the logging module's commonly used internal locks while
fork()ing to avoid deadlocks in the child process.

@item 
bpo-34658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34658}: Fix a rare interpreter unhandled exception state SystemError
only seen when using subprocess with a preexec_fn while an after_parent
handler has been registered with os.register_at_fork and the fork system
call fails.

@item 
bpo-34652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34652}: Ensure @ref{11a9,,os.lchmod()} is never defined on Linux.

@item 
bpo-34638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34638}: Store a weak reference to stream reader to break strong
references loop between reader and protocol.  It allows to detect and
close the socket if the stream is deleted (garbage collected) without
@code{close()} call.

@item 
bpo-34536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34536}: @code{Enum._missing_}:  raise @ref{16d,,ValueError} if None returned and
@ref{1ff,,TypeError} if non-member is returned.

@item 
bpo-34636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34636}: Speed up re scanning of many non-matching characters for s w
and d within bytes objects. (microoptimization)

@item 
bpo-24412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24412}: Add @ref{37b,,addModuleCleanup()} and
@ref{37c,,addClassCleanup()} to unittest to support
cleanups for @code{setUpModule()} and
@ref{37d,,setUpClass()}. Patch by Lisa Roach.

@item 
bpo-34630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34630}: Don't log SSL certificate errors in asyncio code (connection
error logging is skipped already).

@item 
bpo-32490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32490}: Prevent filename duplication in @ref{f9,,subprocess} exception
messages.  Patch by Zackery Spytz.

@item 
bpo-34363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34363}: dataclasses.asdict() and .astuple() now handle namedtuples
correctly.

@item 
bpo-34625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34625}: Update vendorized expat library version to 2.2.6.

@item 
bpo-32270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32270}: The subprocess module no longer mistakenly closes redirected
fds even when they were in pass_fds when outside of the default @{0, 1, 2@}
set.

@item 
bpo-34622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34622}: Create a dedicated @code{asyncio.CancelledError},
@code{asyncio.InvalidStateError} and @code{asyncio.TimeoutError} exception
classes.  Inherit them from corresponding exceptions from
@code{concurrent.futures} package. Extract @code{asyncio} exceptions into a
separate file.

@item 
bpo-34610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34610}: Fixed iterator of @code{multiprocessing.managers.DictProxy}.

@item 
bpo-34421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34421}: Fix distutils logging for non-ASCII strings.  This caused
installation issues on Windows.

@item 
bpo-34604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34604}: Fix possible mojibake in the error message of @ref{11aa,,pwd.getpwnam}
and @ref{11ab,,grp.getgrnam} using string representation because of invisible
characters or trailing whitespaces. Patch by William Grzybowski.

@item 
bpo-30977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30977}: Make uuid.UUID use @code{__slots__} to reduce its memory
footprint. Based on original patch by Wouter Bolsterlee.

@item 
bpo-34574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34574}: OrderedDict iterators are not exhausted during pickling
anymore. Patch by Sergey Fedoseev.

@item 
bpo-8110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8110}: Refactored @ref{f9,,subprocess} to check for Windows-specific
modules rather than @code{sys.platform == 'win32'}.

@item 
bpo-34530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34530}: @code{distutils.spawn.find_executable()} now falls back on
@ref{1163,,os.defpath} if the @code{PATH} environment variable is not set.

@item 
bpo-34563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34563}: On Windows, fix multiprocessing.Connection for very large read:
fix _winapi.PeekNamedPipe() and _winapi.ReadFile() for read larger than
INT_MAX (usually @code{2**31-1}).

@item 
bpo-34558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34558}: Correct typo in Lib/ctypes/_aix.py

@item 
bpo-34282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34282}: Move @code{Enum._convert} to @code{EnumMeta._convert_} and fix enum
members getting shadowed by parent attributes.

@item 
bpo-22872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22872}: When the queue is closed, @ref{16d,,ValueError} is now raised by
@ref{11ac,,multiprocessing.Queue.put()} and @ref{11ad,,multiprocessing.Queue.get()}
instead of @ref{241,,AssertionError} and @ref{30b,,OSError}, respectively. Patch
by Zackery Spytz.

@item 
bpo-34515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34515}: Fix parsing non-ASCII identifiers in
@code{lib2to3.pgen2.tokenize} (PEP 3131).

@item 
bpo-13312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13312}: Avoids a possible integer underflow (undefined behavior) in the
time module's year handling code when passed a very low negative year
value.

@item 
bpo-34472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34472}: Improved compatibility for streamed files in @ref{14b,,zipfile}.
Previously an optional signature was not being written and certain ZIP
applications were not supported. Patch by Silas Sewell.

@item 
bpo-34454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34454}: Fix the .fromisoformat() methods of datetime types crashing
when given unicode with non-UTF-8-encodable code points.  Specifically,
datetime.fromisoformat() now accepts surrogate unicode code points used as
the separator. Report and tests by Alexey Izbyshev, patch by Paul Ganssle.

@item 
bpo-6700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6700}: Fix inspect.getsourcelines for module level frames/tracebacks.
Patch by Vladimir Matveev.

@item 
bpo-34171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34171}: Running the @ref{11b,,trace} module no longer creates the
@code{trace.cover} file.

@item 
bpo-34441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34441}: Fix crash when an @code{ABC}-derived class with invalid
@code{__subclasses__} is passed as the second argument to
@ref{55b,,issubclass()}. Patch by Alexey Izbyshev.

@item 
bpo-34427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34427}: Fix infinite loop in @code{a.extend(a)} for @code{MutableSequence}
subclasses.

@item 
bpo-34412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34412}: Make @ref{11ae,,signal.strsignal()} work on HP-UX. Patch by Michael
Osipov.

@item 
bpo-20849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20849}: shutil.copytree now accepts a new @code{dirs_exist_ok} keyword
argument. Patch by Josh Bronson.

@item 
bpo-31715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31715}: Associate @code{.mjs} file extension with
@code{application/javascript} MIME Type.

@item 
bpo-34384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34384}: @ref{1d2,,os.readlink()} now accepts @ref{47b,,path-like} and @ref{172,,bytes} objects on Windows.

@item 
bpo-22602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22602}: The UTF-7 decoder now raises @ref{332,,UnicodeDecodeError} for
ill-formed sequences starting with "+" (as specified in RFC 2152).  Patch
by Zackery Spytz.

@item 
bpo-2122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2122}: The @ref{3ed,,mmap.flush()} method now returns
@code{None} on success, raises an exception on error under all platforms.

@item 
bpo-34341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34341}: Appending to the ZIP archive with the ZIP64 extension no longer
grows the size of extra fields of existing entries.

@item 
bpo-34333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34333}: Fix %-formatting in @ref{11af,,pathlib.PurePath.with_suffix()} when
formatting an error message.

@item 
bpo-18540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18540}: The @ref{1b0,,imaplib.IMAP4} and @ref{1b1,,imaplib.IMAP4_SSL}
classes now resolve to the local host IP correctly when the default value
of @emph{host} parameter (@code{'@w{'}}) is used.

@item 
bpo-26502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26502}: Implement @code{traceback.FrameSummary.__len__()} method to
preserve compatibility with the old tuple API.

@item 
bpo-34318@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34318}: @ref{b9b,,assertRaises()},
@ref{b9c,,assertRaisesRegex()},
@ref{b9d,,assertWarns()} and
@ref{b9e,,assertWarnsRegex()} no longer success if the
passed callable is None. They no longer ignore unknown keyword arguments
in the context manager mode. A DeprecationWarning was raised in these
cases since Python 3.5.

@item 
bpo-9372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9372}: Deprecate @ref{3ad,,__getitem__()} methods of
@ref{3aa,,xml.dom.pulldom.DOMEventStream}, @ref{3ab,,wsgiref.util.FileWrapper}
and @ref{3ac,,fileinput.FileInput}.

@item 
bpo-33613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33613}: Fix a race condition in @code{multiprocessing.semaphore_tracker}
when the tracker receives SIGINT before it can register signal handlers
for ignoring it.

@item 
bpo-34248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34248}: Report filename in the exception raised when the database file
cannot be opened by @ref{11b0,,dbm.gnu.open()} and @ref{11b1,,dbm.ndbm.open()} due to
OS-related error. Patch by Zsolt Cserna.

@item 
bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089}: Add math.dist() to compute the Euclidean distance between two
points.

@item 
bpo-34246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34246}: @ref{83e,,smtplib.SMTP.send_message()} no longer modifies the
content of the @emph{mail_options} argument. Patch by Pablo S. Blum de Aguiar.

@item 
bpo-31047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31047}: Fix @code{ntpath.abspath} for invalid paths on windows. Patch by
Franz Woellert.

@item 
bpo-32321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32321}: Add pure Python fallback for functools.reduce. Patch by Robert
Wright.

@item 
bpo-34270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34270}: The default asyncio task class now always has a name which can
be get or set using two new methods (@ref{2eb,,get_name()} and
@ref{2ea,,set_name()}) and is visible in the @ref{8c3,,repr()} output.
An initial name can also be set using the new @code{name} keyword argument to
@ref{2e8,,asyncio.create_task()} or the
@code{create_task()} method of the event loop.
If no initial name is set, the default Task implementation generates a
name like @code{Task-1} using a monotonic counter.

@item 
bpo-34263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34263}: asyncio's event loop will not pass timeouts longer than one day
to epoll/select etc.

@item 
bpo-34035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34035}: Fix several AttributeError in zipfile seek() methods. Patch by
Mickaël Schoentgen.

@item 
bpo-32215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32215}: Fix performance regression in @ref{f2,,sqlite3} when a DML
statement appeared in a different line than the rest of the SQL query.

@item 
bpo-34075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34075}: Deprecate passing non-ThreadPoolExecutor instances to
@code{AbstractEventLoop.set_default_executor()}.

@item 
bpo-34251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34251}: Restore @code{msilib.Win64} to preserve backwards compatibility
since it's already used by @ref{38,,distutils}' @code{bdist_msi} command.

@item 
bpo-19891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19891}: Ignore errors caused by missing / non-writable homedir while
writing history during exit of an interactive session.  Patch by Anthony
Sottile.

@item 
bpo-33089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33089}: Enhanced math.hypot() to support more than two dimensions.

@item 
bpo-34228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34228}: tracemalloc: PYTHONTRACEMALLOC=0 environment variable and -X
tracemalloc=0 command line option are now allowed to disable explicitly
tracemalloc at startup.

@item 
bpo-13041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13041}: Use @ref{b2e,,shutil.get_terminal_size()} to calculate the terminal
width correctly in the @code{argparse.HelpFormatter} class.  Initial patch by
Zbyszek Jędrzejewski-Szmek.

@item 
bpo-34213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34213}: Allow frozen dataclasses to have a field named "object".
Previously this conflicted with an internal use of "object".

@item 
bpo-34052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34052}: @ref{111c,,sqlite3.Connection.create_aggregate()},
@ref{111d,,sqlite3.Connection.create_function()},
@ref{111e,,sqlite3.Connection.set_authorizer()},
@ref{111f,,sqlite3.Connection.set_progress_handler()} methods raises TypeError
when unhashable objects are passed as callable. These methods now don't
pass such objects to SQLite API. Previous behavior could lead to
segfaults. Patch by Sergey Fedoseev.

@item 
bpo-34197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34197}: Attributes @emph{skipinitialspace}, @emph{doublequote} and @emph{strict} of
the @emph{dialect} attribute of the @ref{29,,csv} reader are now @ref{2c4,,bool}
instances instead of integers 0 or 1.

@item 
bpo-32788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32788}: Errors other than @ref{1ff,,TypeError} raised in methods
@code{__adapt__()} and @code{__conform__()} in the @ref{f2,,sqlite3} module are now
propagated to the user.

@item 
bpo-21446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21446}: The @ref{11b2,,reload} fixer now uses @ref{4a8,,importlib.reload()}
instead of deprecated @ref{d40,,imp.reload()}.

@item 
bpo-940286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=940286}: pydoc's @code{Helper.showtopic()} method now prints the cross
references of a topic correctly.

@item 
bpo-34164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34164}: @ref{a47,,base64.b32decode()} could raise UnboundLocalError or
OverflowError for incorrect padding.  Now it always raises
@code{base64.Error} in these cases.

@item 
bpo-33729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33729}: Fixed issues with arguments parsing in @ref{8c,,hashlib}.

@item 
bpo-34097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34097}: ZipFile can zip files older than 1980-01-01 and newer than
2107-12-31 using a new @code{strict_timestamps} parameter at the cost of
setting the timestamp to the limit.

@item 
bpo-34108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34108}: Remove extraneous CR in 2to3 refactor.

@item 
bpo-34070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34070}: Make sure to only check if the handle is a tty, when opening a
file with @code{buffering=-1}.

@item 
bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}: Reverted bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}. 2to3 rejects now a trailing comma in
generator expressions.

@item 
bpo-33967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33967}: functools.singledispatch now raises TypeError instead of
IndexError when no positional arguments are passed.

@item 
bpo-34041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34041}: Add the parameter @emph{deterministic} to the
@ref{111d,,sqlite3.Connection.create_function()} method. Patch by Sergey
Fedoseev.

@item 
bpo-34056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34056}: Ensure the loader shim created by @code{imp.load_module} always
returns bytes from its @code{get_data()} function. This fixes using
@code{imp.load_module} with 
@geindex Python 提高建议; PEP 552
PEP 552@footnote{https://www.python.org/dev/peps/pep-0552} hash-based pycs.

@item 
bpo-34054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34054}: The multiprocessing module now uses the monotonic clock
@ref{868,,time.monotonic()} instead of the system clock @ref{436,,time.time()} to
implement timeout.

@item 
bpo-34043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34043}: Optimize tarfile uncompress performance about 15% when gzip is
used.

@item 
bpo-34044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34044}: @code{subprocess.Popen} now copies the @emph{startupinfo} argument to
leave it unchanged: it will modify the copy, so that the same
@code{STARTUPINFO} object can be used multiple times.

@item 
bpo-34010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34010}: Fixed a performance regression for reading streams with
tarfile. The buffered read should use a list, instead of appending to a
bytes object.

@item 
bpo-34019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34019}: webbrowser: Correct the arguments passed to Opera Browser when
opening a new URL using the @code{webbrowser} module. Patch by Bumsik Kim.

@item 
bpo-34003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34003}: csv.DictReader now creates dicts instead of OrderedDicts. Patch
by Michael Selik.

@item 
bpo-33978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33978}: Closed existing logging handlers before reconfiguration via
fileConfig and dictConfig. Patch by Karthikeyan Singaravelan.

@item 
bpo-14117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14117}: Make minor tweaks to turtledemo. The 'wikipedia' example is now
'rosette', describing what it draws.  The 'penrose' print output is
reduced. The'1024' output of 'tree' is eliminated.

@item 
bpo-33974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33974}: Fixed passing lists and tuples of strings containing special
characters @code{"}, @code{\}, @code{@{}, @code{@}} and @code{\n} as options to
@ref{118,,ttk} widgets.

@item 
bpo-27500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27500}: Fix getaddrinfo to resolve IPv6 addresses correctly.

@item 
bpo-24567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24567}: Improve random.choices() to handle subnormal input weights that
could occasionally trigger an IndexError.

@item 
bpo-33871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33871}: Fixed integer overflow in @ref{4c7,,os.readv()}, @ref{4ca,,os.writev()},
@ref{4c6,,os.preadv()} and @ref{4c9,,os.pwritev()} and in @ref{46a,,os.sendfile()} with
@emph{headers} or @emph{trailers} arguments (on BSD-based OSes and macOS).

@item 
bpo-25007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25007}: Add @ref{4da,,copy.copy()} and @ref{4db,,copy.deepcopy()} support to zlib
compressors and decompressors.  Patch by Zackery Spytz.

@item 
bpo-33929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33929}: multiprocessing: Fix a race condition in Popen of
multiprocessing.popen_spawn_win32. The child process now duplicates the
read end of pipe instead of "stealing" it. Previously, the read end of
pipe was "stolen" by the child process, but it leaked a handle if the
child process had been terminated before it could steal the handle from
the parent process.

@item 
bpo-33899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33899}: Tokenize module now implicitly emits a NEWLINE when provided
with input that does not have a trailing new line.  This behavior now
matches what the C tokenizer does internally.  Contributed by Ammar Askar.

@item 
bpo-33897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33897}: Added a 'force' keyword argument to logging.basicConfig().

@item 
bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695}: @ref{34e,,shutil.copytree()} uses @ref{390,,os.scandir()} function and
all copy functions depending from it use cached @ref{328,,os.stat()} values.
The speedup for copying a directory with 8000 files is around +9% on
Linux, +20% on Windows and + 30% on a Windows SMB share. Also the number
of @ref{328,,os.stat()} syscalls is reduced by 38% making
@ref{34e,,shutil.copytree()} especially faster on network filesystems.
(Contributed by Giampaolo Rodola' in bpo-33695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33695}.)

@item 
bpo-33916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33916}: bz2 and lzma: When Decompressor.__init__() is called twice,
free the old lock to not leak memory.

@item 
bpo-32568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32568}: Make select.epoll() and its documentation consistent regarding
@emph{sizehint} and @emph{flags}.

@item 
bpo-33833@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33833}: Fixed bug in asyncio where ProactorSocketTransport logs
AssertionError if force closed during write.

@item 
bpo-33663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33663}: Convert content length to string before putting to header.

@item 
bpo-33721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33721}: @ref{c5,,os.path} functions that return a boolean result like
@ref{32c,,exists()}, @ref{32d,,lexists()}, @ref{32e,,isdir()},
@ref{32f,,isfile()}, @ref{32a,,islink()}, and
@ref{330,,ismount()}, and @ref{336,,pathlib.Path} methods that return a
boolean result like @ref{337,,exists()},
@ref{338,,is_dir()}, @ref{339,,is_file()},
@ref{33a,,is_mount()}, @ref{33b,,is_symlink()},
@ref{33c,,is_block_device()},
@ref{33d,,is_char_device()}, @ref{33e,,is_fifo()},
@ref{33f,,is_socket()} now return @code{False} instead of raising
@ref{16d,,ValueError} or its subclasses @ref{331,,UnicodeEncodeError} and
@ref{332,,UnicodeDecodeError} for paths that contain characters or bytes
unrepresentable at the OS level.

@item 
bpo-26544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26544}: Fixed implementation of @ref{1199,,platform.libc_ver()}. It almost
always returned version '2.9' for glibc.

@item 
bpo-33843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33843}: Remove deprecated @code{cgi.escape}, @code{cgi.parse_qs} and
@code{cgi.parse_qsl}.

@item 
bpo-33842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33842}: Remove @code{tarfile.filemode} which is deprecated since Python
3.3.

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33805}: Improve error message of dataclasses.replace() when an InitVar
is not specified

@item 
bpo-33687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33687}: Fix the call to @code{os.chmod()} for @code{uu.decode()} if a mode is
given or decoded. Patch by Timo Furrer.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-32108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32108}: In configparser, don't clear section when it is assigned to
itself.

@item 
bpo-27397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27397}: Make email module properly handle invalid-length base64
strings.

@item 
bpo-33578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33578}: Implement multibyte encoder/decoder state methods

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33476}: Fix _header_value_parser.py when address group is missing final
';'. Contributed by Enrique Perez-Terron

@item 
bpo-33694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33694}: asyncio: Fix a race condition causing data loss on
pause_reading()/resume_reading() when using the ProactorEventLoop.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Correct test for @code{uuid_enc_be} availability in
@code{configure.ac}. Patch by Michael Felt.

@item 
bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792}: Add asyncio.WindowsSelectorEventLoopPolicy and
asyncio.WindowsProactorEventLoopPolicy.

@item 
bpo-33274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33274}: W3C DOM Level 1 specifies return value of
Element.removeAttributeNode() as "The Attr node that was removed."
xml.dom.minidom now complies with this requirement.

@item 
bpo-33778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33778}: Update @code{unicodedata}'s database to Unicode version 11.0.0.

@item 
bpo-33165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33165}: Added a stacklevel parameter to logging calls to allow use of
wrapper/helper functions for logging APIs.

@item 
bpo-33770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33770}: improve base64 exception message for encoded inputs of invalid
length

@item 
bpo-33769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33769}: asyncio/start_tls: Fix error message; cancel callbacks in case
of an unhandled error; mark SSLTransport as closed if it is aborted.

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{1ff,,TypeError} instead of @ref{6fc,,SystemError} when
performed on @ref{323,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-33734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33734}: asyncio/ssl: Fix AttributeError, increase default handshake
timeout

@item 
bpo-31014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31014}: Fixed creating a controller for @ref{132,,webbrowser} when a user
specifies a path to an entry in the BROWSER environment variable.  Based
on patch by John Still.

@item 
bpo-2504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2504}: Add gettext.pgettext() and variants.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Add description property for _ParameterKind

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{191,,asyncio.wait_for()} will now wait until the cancellation is complete.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Support protocol type switching in SSLTransport.set_protocol().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Pause the transport as early as possible to further reduce the
risk of data_received() being called before connection_made().

@item 
bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671}: @ref{389,,shutil.copyfile()}, @ref{38a,,shutil.copy()},
@ref{38b,,shutil.copy2()}, @ref{34e,,shutil.copytree()} and @ref{38c,,shutil.move()} use
platform-specific fast-copy syscalls on Linux and macOS in order to copy
the file more efficiently. On Windows @ref{389,,shutil.copyfile()} uses a
bigger default buffer size (1 MiB instead of 16 KiB) and a
@ref{38d,,memoryview()}-based variant of @ref{38e,,shutil.copyfileobj()} is used.
The speedup for copying a 512MiB file is about +26% on Linux, +50% on
macOS and +40% on Windows. Also, much less CPU cycles are consumed.
(Contributed by Giampaolo Rodola' in bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427}.)

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-32610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32610}: Make asyncio.all_tasks() return only pending tasks.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Avoid blocking on file IO in sendfile fallback code

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Fix transport.set_protocol() to support switching between
asyncio.Protocol and asyncio.BufferedProtocol.  Fix loop.start_tls() to
work with asyncio.BufferedProtocols.

@item 
bpo-33652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33652}: Pickles of type variables and subscripted generics are now
future-proof and compatible with older Python versions.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Fixed @ref{520,,uuid.uuid1()} on FreeBSD.

@item 
bpo-33238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33238}: Add @code{InvalidStateError} to @ref{21,,concurrent.futures}.
@code{Future.set_result} and @code{Future.set_exception} now raise
@code{InvalidStateError} if the futures are not pending or running. Patch by
Jason Haydaman.

@item 
bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618}: Finalize and document preliminary and experimental TLS 1.3
support with OpenSSL 1.1.1

@item 
bpo-33625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33625}: Release GIL on @ref{11ab,,grp.getgrnam}, @ref{6e0,,grp.getgrgid}, @ref{11aa,,pwd.getpwnam}
and @ref{1198,,pwd.getpwuid} if reentrant variants of these functions are available.
Patch by William Grzybowski.

@item 
bpo-33623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33623}: Fix possible SIGSGV when asyncio.Future is created in __del__

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Remove HMAC default to md5 marked for removal in 3.8 (removal
originally planned in 3.6, bump to 3.8 in PR 7062).

@item 
bpo-33582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33582}: Emit a deprecation warning for inspect.formatargspec

@item 
bpo-21145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21145}: Add @code{functools.cached_property} decorator, for computed
properties cached for the life of the instance.

@item 
bpo-33570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33570}: Change TLS 1.3 cipher suite settings for compatibility with
OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 ciphers
enabled by default.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Do not simplify arguments to @ref{11b3,,typing.Union}. Now
@code{Union[Manager, Employee]} is not simplified to @code{Employee} at runtime.
Such simplification previously caused several bugs and limited
possibilities for introspection.

@item 
bpo-12486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12486}: @ref{11b4,,tokenize.generate_tokens()} is now documented as a public
API to tokenize unicode strings. It was previously present but
undocumented.

@item 
bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}: Add a new @code{block_on_close} class attribute to
@code{ForkingMixIn} and @code{ThreadingMixIn} classes of @ref{f0,,socketserver}.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33109}: argparse subparsers are once again not required by default,
reverting the change in behavior introduced by bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510} in 3.7.0a2.

@item 
bpo-33541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33541}: Remove unused private method @code{_strptime.LocaleTime.__pad}
(a.k.a. @code{_LocaleTime__pad}).

@item 
bpo-33536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33536}: dataclasses.make_dataclass now checks for invalid field names
and duplicate fields. Also, added a check for invalid field
specifications.

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
Fix failure in @ref{1f0,,typing.get_type_hints()} when ClassVar was provided as a
string forward reference.

@item 
bpo-33516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33516}: @ref{87e,,unittest.mock.MagicMock} now supports the @code{__round__}
magic method.

@item 
bpo-28612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28612}: Added support for Site Maps to urllib's @code{RobotFileParser} as
@ref{11b5,,RobotFileParser.site_maps()}. Patch by Lady Red, based
on patch by Peter Wirtz.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: Remove platform.linux_distribution, which was deprecated since
3.5.

@item 
bpo-33504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33504}: Switch the default dictionary implementation for
@ref{22,,configparser} from @ref{2f1,,collections.OrderedDict} to the standard
@ref{164,,dict} type.

@item 
bpo-33505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33505}: Optimize asyncio.ensure_future() by reordering if checks: 1.17x
faster.

@item 
bpo-33497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33497}: Add errors param to cgi.parse_multipart and make an encoding in
FieldStorage use the given errors (needed for Twisted).  Patch by Amber
Brown.

@item 
bpo-29235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29235}: The @code{cProfile.Profile} class can now be used as a
context manager. Patch by Scott Sanderson.

@item 
bpo-33495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33495}: Change dataclasses.Fields repr to use the repr of each of its
members, instead of str.  This makes it more clear what each field
actually represents.  This is especially true for the 'type' member.

@item 
bpo-26103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26103}: Correct @code{inspect.isdatadescriptor} to look for @code{__set__} or
@code{__delete__}.  Patch by Aaron Hall.

@item 
bpo-29209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29209}: Removed the @code{doctype()} method and the @emph{html} parameter of
the constructor of @ref{383,,XMLParser}.  The
@code{doctype()} method defined in a subclass will no longer be called.
Deprecated methods @code{getchildren()} and @code{getiterator()} in the
@ref{140,,ElementTree} module emit now a @ref{15a,,DeprecationWarning}
instead of @ref{15c,,PendingDeprecationWarning}.

@item 
bpo-33453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33453}: Fix dataclasses to work if using literal string type
annotations or if using PEP 563 "Postponed Evaluation of Annotations".
Only specific string prefixes are detected for both ClassVar ("ClassVar"
and "typing.ClassVar") and InitVar ("InitVar" and "dataclasses.InitVar").

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-33365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33365}: Print the header values besides the header keys instead just
the header keys if @emph{debuglevel} is set to >0 in @ref{93,,http.client}. Patch
by Marco Strigl.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: The function @code{platform.linux_distribution} and
@code{platform.dist} now trigger a @code{DeprecationWarning} and have been
marked for removal in Python 3.8

@item 
bpo-33281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33281}: Fix ctypes.util.find_library regression on macOS.

@item 
bpo-33311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33311}: Text and html output generated by cgitb does not display
parentheses if the current call is done directly in the module. Patch by
Stéphane Blondon.

@item 
bpo-27300@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27300}: The file classes in @emph{tempfile} now accept an @emph{errors} parameter
that complements the already existing @emph{encoding}.  Patch by Stephan Hohe.

@item 
bpo-32933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32933}: @ref{114b,,unittest.mock.mock_open()} now supports iteration over the
file contents. Patch by Tony Flury.

@item 
bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}: Raise @ref{1ff,,TypeError} when looking up non-Enum objects in Enum
classes and Enum members.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Dong-hee Na.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{34,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33375}: The warnings module now finds the Python file associated with a
warning from the code object, rather than the frame's global namespace.
This is consistent with how tracebacks and pdb find filenames, and should
work better for dynamically executed code.

@item 
bpo-33336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33336}: @code{imaplib} now allows @code{MOVE} command in @code{IMAP4.uid()} (RFC
6851: IMAP MOVE Extension) and potentially as a name of supported method
of @code{IMAP4} object.

@item 
bpo-32455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32455}: Added @emph{jump} parameter to @ref{931,,dis.stack_effect()}.

@item 
bpo-27485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27485}: Rename and deprecate undocumented functions in
@ref{128,,urllib.parse()}.

@item 
bpo-33332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33332}: Add @code{signal.valid_signals()} to expose the POSIX sigfillset()
functionality.

@item 
bpo-33251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33251}: @code{ConfigParser.items()} was fixed so that key-value pairs passed
in via @ref{11b6,,vars} are not included in the resulting output.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-33334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33334}: @ref{931,,dis.stack_effect()} now supports all defined opcodes
including NOP and EXTENDED_ARG.

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{11b7,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @ref{c7,,parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-23403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23403}: lib2to3 now uses pickle protocol 4 for pre-computed grammars.

@item 
bpo-33266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33266}: lib2to3 now recognizes @code{rf'...'} strings.

@item 
bpo-11594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11594}: Ensure line-endings are respected when using lib2to3.

@item 
bpo-33254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33254}: Have @ref{11b8,,importlib.resources.contents()} and
@ref{11b9,,importlib.abc.ResourceReader.contents()} return an @ref{c84,,iterable}
instead of an @ref{11ba,,iterator}.

@item 
bpo-33265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33265}: @code{contextlib.ExitStack} and @code{contextlib.AsyncExitStack} now
use a method instead of a wrapper function for exit callbacks.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33144}: @code{random.Random()} and its subclassing mechanism got optimized
to check only once at class/subclass instantiation time whether its
@code{getrandbits()} method can be relied on by other methods, including
@code{randrange()}, for the generation of arbitrarily large random integers.
Patch by Wolfgang Maier.

@item 
bpo-33185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33185}: Fixed regression when running pydoc with the @ref{44c,,-m}
switch. (The regression was introduced in 3.7.0b3 by the resolution of
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053})

This fix also changed pydoc to add @code{os.getcwd()} to @ref{262,,sys.path}
when necessary, rather than adding @code{"."}.

@item 
bpo-29613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29613}: Added support for the @code{SameSite} cookie flag to the
@code{http.cookies} module.

@item 
bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169}: Delete entries of @code{None} in @ref{5a0,,sys.path_importer_cache}
when @code{importlib.machinery.invalidate_caches()} is called.

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{11bb,,pickle.Pickler.dump()}.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Also removes extra newlines that were being appended to the end of the
string. Patch by Michael Lazar.

@item 
bpo-23403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23403}: @code{DEFAULT_PROTOCOL} in @ref{ca,,pickle} was bumped to 4. Protocol
4 is described in 
@geindex Python 提高建议; PEP 3154
PEP 3154@footnote{https://www.python.org/dev/peps/pep-3154} and available since Python 3.4. It offers
better performance and smaller size compared to protocol 3 introduced in
Python 3.0.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Improved error handling and fixed a reference leak in
@ref{388,,os.posix_spawn()}.

@item 
bpo-33106@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33106}: Deleting a key from a read-only dbm database raises module
specific error instead of KeyError.

@item 
bpo-33175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33175}: In dataclasses, Field.__set_name__ now looks up the
__set_name__ special method on the class, not the instance, of the default
value.

@item 
bpo-32380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32380}: Create functools.singledispatchmethod to support generic single
dispatch on descriptors and methods.

@item 
bpo-33141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33141}: Have Field objects pass through __set_name__ to their default
values, if they have their own __set_name__.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-32873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32873}: Treat type variables and special typing forms as immutable by
copy and pickle.  This fixes several minor issues and inconsistencies, and
improves backwards compatibility with Python 3.6.

@item 
bpo-33134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33134}: When computing dataclass's __hash__, use the lookup table to
contain the function which returns the __hash__ value.  This is an
improvement over looking up a string, and then testing that string to see
what to do.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-32505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32505}: Raise TypeError if a member variable of a dataclass is of type
Field, but doesn't have a type annotation.

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the failure on OSX caused by the tests relying on
sem_getvalue

@item 
bpo-33116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33116}: Add 'Field' to dataclasses.__all__.

@item 
bpo-32896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32896}: Fix an error where subclassing a dataclass with a field that
uses a default_factory would generate an incorrect class.

@item 
bpo-33100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33100}: Dataclasses: If a field has a default value that's a
MemberDescriptorType, then it's from that field being in __slots__, not an
actual default value.

@item 
bpo-32953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32953}: If a non-dataclass inherits from a frozen dataclass, allow
attributes to be added to the derived class.  Only attributes from the
frozen dataclass cannot be assigned to.  Require all dataclasses in a
hierarchy to be either all frozen or all non-frozen.

@item 
bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097}: Raise RuntimeError when @code{executor.submit} is called during
interpreter shutdown.

@item 
bpo-32968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32968}: Modulo and floor division involving Fraction and float should
return float.

@item 
bpo-33061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33061}: Add missing @code{NoReturn} to @code{__all__} in typing.py

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the size handling in multiprocessing.Queue when a pickling
error occurs.

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-33056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33056}: FIX properly close leaking fds in
concurrent.futures.ProcessPoolExecutor.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33034}: Providing an explicit error message when casting the port
property to anything that is not an integer value using @code{urlparse()} and
@code{urlsplit()}. Patch by Matt Eaton.

@item 
bpo-30249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30249}: Improve struct.unpack_from() exception messages for problems
with the buffer size and offset.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{a2,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-22674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22674}: Add the strsignal() function in the signal module that returns
the system description of the given signal, as returned by strsignal(3).

@item 
bpo-32999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32999}: Fix C implementation of @code{ABC.__subclasscheck__(cls,
subclass)} crashed when @code{subclass} is not a type object.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32056}: Improved exceptions raised for invalid number of channels and
sample width when read an audio file in modules @ref{4,,aifc}, @ref{130,,wave}
and @ref{fa,,sunau}.

@item 
bpo-32970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32970}: Improved disassembly of the MAKE_FUNCTION instruction.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-32960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32960}: For dataclasses, disallow inheriting frozen from non-frozen
classes, and also disallow inheriting non-frozen from frozen classes. This
restriction will be relaxed at a future date.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-32257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32257}: The ssl module now contains OP_NO_RENEGOTIATION constant,
available with OpenSSL 1.1.0h or 1.1.1.

@item 
bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951}: Direct instantiation of SSLSocket and SSLObject objects is now
prohibited. The constructors were never documented, tested, or designed as
public constructors. Users were suppose to use ssl.wrap_socket() or
SSLContext.

@item 
bpo-32929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32929}: Remove the tri-state parameter "hash", and add the boolean
"unsafe_hash". If unsafe_hash is True, add a __hash__ function, but if a
__hash__ exists, raise TypeError.  If unsafe_hash is False, add a __hash__
based on the values of eq= and frozen=.  The unsafe_hash=False behavior is
the same as the old hash=None behavior.  unsafe_hash=False is the default,
just as hash=None used to be.

@item 
bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3
for future compatibility with OpenSSL 1.1.1.

@item 
bpo-32146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32146}: Document the interaction between frozen executables and the
spawn and forkserver start methods in multiprocessing.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32759}: Free unused arenas in multiprocessing.heap.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-32556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32556}: nt._getfinalpathname, nt._getvolumepathname and
nt._getdiskusage now correctly convert from bytes.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{10e,,tkinter}, @code{after_cancel(None)} now raises a
@ref{16d,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333}: @code{_abc} module is added.  It is a speedup module with C
implementations for various functions and methods in @code{abc}.  Creating an
ABC subclass and calling @code{isinstance} or @code{issubclass} with an ABC
subclass are up to 1.5x faster. In addition, this makes Python start-up up
to 10% faster.

Note that the new implementation hides internal registry and caches,
previously accessible via private attributes @code{_abc_registry},
@code{_abc_cache}, and @code{_abc_negative_cache}.  There are three debugging
helper methods that can be used instead @code{_dump_registry},
@code{_abc_registry_clear}, and @code{_abc_caches_clear}.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @ref{3b8,,asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-32819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32819}: ssl.match_hostname() has been simplified and no longer depends
on re and ipaddress module for wildcard and IP addresses. Error reporting
for invalid wildcards has been improved.

@item 
bpo-19675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19675}: @code{multiprocessing.Pool} no longer leaks processes if its
initialization fails.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove
TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older version
Windows during run-time.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-30688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30688}: Added support of @code{\N@{name@}} escapes in regular expressions.
Based on patch by Jonathan Eunice.

@item 
bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792}: collections.ChainMap() preserves the order of the underlying
mappings.

@item 
bpo-32775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32775}: @ref{11bc,,fnmatch.translate()} no longer produces patterns which
contain set operations. Sets starting with '[' or containing '--', '&&',
'~~' or '||' will be interpreted differently in regular expressions in
future versions. Currently they emit warnings. fnmatch.translate() now
avoids producing patterns containing such sets by accident.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Implement native fast sendfile for Windows proactor event loop.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32749}: A @ref{32,,dbm.dumb} database opened with flags 'r' is now
read-only. @ref{3e9,,dbm.dumb.open()} with flags 'r' and 'w' no longer creates
a database if it does not exist.

@item 
bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741}: Implement @code{asyncio.TimerHandle.when()} method.

@item 
bpo-32691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32691}: Use mod_spec.parent when running modules with pdb

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-31453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31453}: Add TLSVersion constants and SSLContext.maximum_version /
minimum_version attributes. The new API wraps OpenSSL 1.1
@indicateurl{https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html}
feature.

@item 
bpo-24334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24334}: Internal implementation details of ssl module were cleaned up.
The SSLSocket has one less layer of indirection. Owner and session
information are now handled by the SSLSocket and SSLObject constructor.
Channel binding implementation has been simplified.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585}: Add Ttk spinbox widget to @ref{118,,tkinter.ttk}.  Patch by Alan D
Moore.

@item 
bpo-32512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32512}: @ref{d3,,profile} CLI accepts @code{-m module_name} as an alternative
to script path.

@item 
bpo-8525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8525}: help() on a type now displays builtin subclasses. This is
intended primarily to help with notification of more specific exception
subclasses.

Patch by Sanyam Khurana.

@item 
bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639}: http.server now exposes a ThreadingHTTPServer class and uses it
when the module is run with @code{-m} to cope with web browsers pre-opening
sockets.

@item 
bpo-29877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29877}: compileall: import ProcessPoolExecutor only when needed,
preventing hangs on low resource platforms

@item 
bpo-32221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32221}: Various functions returning tuple containing IPv6 addresses now
omit @code{%scope} part since the same information is already encoded in
@emph{scopeid} tuple item. Especially this speeds up @code{socket.recvfrom()}
when it receives multicast packet since useless resolving of network
interface name is omitted.

@item 
bpo-32147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32147}: @ref{11bd,,binascii.unhexlify()} is now up to 2 times faster. Patch
by Sergey Fedoseev.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The TarFile class now recurses directories in a reproducible
way.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The ZipFile class now recurses directories in a reproducible
way.

@item 
bpo-31680@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31680}: Added @ref{2f7,,curses.ncurses_version}.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.

@item 
bpo-31608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31608}: Raise a @code{TypeError} instead of crashing if a
@code{collections.deque} subclass returns a non-deque from @code{__new__}. Patch
by Oren Milman.

@item 
bpo-31425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31425}: Add support for sockets of the AF_QIPCRTR address family,
supported by the Linux kernel. This is used to communicate with services,
such as GPS or radio, running on Qualcomm devices. Patch by Bjorn
Andersson.

@item 
bpo-22005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22005}: Implemented unpickling instances of
@ref{19f,,datetime}, @ref{19d,,date} and
@ref{5f5,,time} pickled by Python 2. @code{encoding='latin1'} should
be used for successful decoding.

@item 
bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645}: @ref{4e7,,sqlite3.Connection} now exposes a
@ref{4e8,,backup} method, if the underlying SQLite
library is at version 3.6.11 or higher.  Patch by Lele Gaifax.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2a,,ctypes}.  Patch by Segev Finer.

@item 
bpo-31508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31508}: Removed support of arguments in
@ref{3e7,,tkinter.ttk.Treeview.selection}. It was deprecated in 3.6.  Use
specialized methods like @code{selection_set} for changing the selection.

@item 
bpo-29456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29456}: Fix bugs in hangul normalization: u1176, u11a7 and u11c3
@end itemize

@node Documentation<26>,Tests<27>,Library<36>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id259}@anchor{11be}
@subsubsection Documentation



@itemize -

@item 
bpo-21257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21257}: Document @ref{11bf,,http.client.parse_headers()}.

@item 
bpo-34764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34764}: Improve example of iter() with 2nd sentinel argument.

@item 
bpo-35564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35564}: Explicitly set master_doc variable in conf.py for compliance
with Sphinx 2.0

@item 
bpo-35511@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35511}: Specified that profile.Profile class doesn't not support enable
or disable methods. Also, elaborated that Profile object as a context
manager is only supported in cProfile module.

@item 
bpo-10536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10536}: Enhance the gettext docs. Patch by Éric Araujo

@item 
bpo-35089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35089}: Remove mention of @code{typing.io} and @code{typing.re}. Their types
should be imported from @code{typing} directly.

@item 
bpo-35038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35038}: Fix the documentation about an unexisting @code{f_restricted}
attribute in the frame object. Patch by Stéphane Wirtel

@item 
bpo-35042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35042}: Replace PEP XYZ by the pep role and allow to use the direct
links to the PEPs.

@item 
bpo-35044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35044}: Fix the documentation with the role @code{exc} for the
appropriated exception. Patch by Stéphane Wirtel

@item 
bpo-35035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35035}: Rename documentation for @ref{74,,email.utils} to
@code{email.utils.rst}.

@item 
bpo-34967@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34967}: Use app.add_object_type() instead of the deprecated Sphinx
function app.description_unit()

@item 
bpo-34913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34913}: Add documentation about the new command line interface of the
gzip module.

@item 
bpo-32174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32174}: chm document displays non-ASCII charaters properly on some MBCS
Windows systems.

@item 
bpo-11233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11233}: Create availability directive for documentation.  Original
patch by Georg Brandl.

@item 
bpo-34790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34790}: Document how passing coroutines to asyncio.wait() can be
confusing.

@item 
bpo-34552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34552}: Make clear that @code{==} operator sometimes is equivalent to
@code{is}. The @code{<}, @code{<=}, @code{>} and @code{>=} operators are only defined where
they make sense.

@item 
bpo-28617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28617}: Fixed info in the stdtypes docs concerning the types that
support membership tests.

@item 
bpo-20177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20177}: Migrate datetime.date.fromtimestamp to Argument Clinic. Patch
by Tim Hoffmann.

@item 
bpo-34065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34065}: Fix wrongly written basicConfig documentation markup syntax

@item 
bpo-33460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33460}: replaced ellipsis with correct error codes in tutorial chapter
3.

@item 
bpo-33847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33847}: Add '@@' operator entry to index.

@item 
bpo-33409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33409}: Clarified the relationship between 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538}'s
PYTHONCOERCECLOCALE and PEP 540's PYTHONUTF8 mode.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Add versionadded tag to the documentation of
ParameterKind.description

@item 
bpo-17045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17045}: Improve the C-API doc for PyTypeObject.  This includes adding
several quick-reference tables and a lot of missing slot/typedef entries.
The existing entries were also cleaned up with a slightly more consistent
format.

@item 
bpo-33736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33736}: Improve the documentation of @ref{474,,asyncio.open_connection()},
@ref{475,,asyncio.start_server()} and their UNIX socket counterparts.

@item 
bpo-23859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23859}: Document that @ref{208,,asyncio.wait()} does not cancel its futures on
timeout.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Document 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} changes to asyncio.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Update HMAC md5 default to a DeprecationWarning, bump removal
to 3.8.

@item 
bpo-33594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33594}: Document @code{getargspec}, @code{from_function} and @code{from_builtin}
as deprecated in their respective docstring, and include version since
deprecation in DeprecationWarning message.

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.

@item 
bpo-33487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33487}: BZ2file now emit a DeprecationWarning when buffering=None is
passed, the deprecation message and documentation also now explicitly
state it is deprecated since 3.0.

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{14a,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)

@item 
bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124}: The ssl module function ssl.wrap_socket() has been
de-emphasized and deprecated in favor of the more secure and efficient
SSLContext.wrap_socket() method.

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Add documentation for the contextvars module (PEP 567).

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-11015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11015}: Update @ref{106,,test.support} documentation.

@item 
bpo-32613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32613}: Update the faq/windows.html to use the py command from PEP 397
instead of python.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @ref{433,,__getattr__()} behavior when property @code{get()}
method raises @ref{4aa,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{15a,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-20709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20709}: Remove the paragraph where we explain that os.utime() does not
support a directory as path under Windows. Patch by Jan-Philip Gehrcke

@item 
bpo-32722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32722}: Remove the bad example in the tutorial of the Generator
Expression. Patch by Stéphane Wirtel

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @ref{236,,pathlib.PurePath} subclasses.

@item 
bpo-30607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30607}: Use the externalized @code{python-docs-theme} package when
building the documentation.

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-32337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32337}: Update documentation related with @code{dict} order.

@item 
bpo-25041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25041}: Document @code{AF_PACKET} in the @ref{ef,,socket} module.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node Tests<27>,Build<25>,Documentation<26>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id260}@anchor{11c0}
@subsubsection Tests



@itemize -

@item 
bpo-35772@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35772}: Fix sparse file tests of test_tarfile on ppc64 with the tmpfs
filesystem. Fix the function testing if the filesystem supports sparse
files: create a file which contains data and "holes", instead of creating
a file which contains no data. tmpfs effective block size is a page size
(tmpfs lives in the page cache). RHEL uses 64 KiB pages on aarch64, ppc64,
ppc64le, only s390x and x86_64 use 4 KiB pages, whereas the test punch
holes of 4 KiB.

@item 
bpo-35045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35045}: Make ssl tests less strict and also accept TLSv1 as system
default. The changes unbreaks test_min_max_version on Fedora 29.

@item 
bpo-32710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32710}: @code{test_asyncio/test_sendfile.py} now resets the event loop
policy using @code{tearDownModule()} as done in other tests, to prevent a
warning when running tests on Windows.

@item 
bpo-33717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33717}: test.pythoninfo now logs information of all clocks, not only
time.time() and time.perf_counter().

@item 
bpo-35488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35488}: Add a test to pathlib's Path.match() to verify it does not
support glob-style ** recursive pattern matching.

@item 
bpo-31731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31731}: Fix a race condition in @code{check_interrupted_write()} of
test_io: create directly the thread with SIGALRM signal blocked, rather
than blocking the signal later from the thread. Previously, it was
possible that the thread gets the signal before the signal is blocked.

@item 
bpo-35424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35424}: Fix test_multiprocessing_main_handling: use
@code{multiprocessing.Pool} with a context manager and then explicitly
join the pool.

@item 
bpo-35519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35519}: Rename @code{test.bisect} module to @code{test.bisect_cmd} to
avoid conflict with @ref{11,,bisect} module when running directly a test like
@code{./python Lib/test/test_xmlrpc.py}.

@item 
bpo-35513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35513}: Replace @ref{436,,time.time()} with @ref{868,,time.monotonic()} in tests
to measure time delta.

@item 
bpo-34279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34279}: @ref{11c1,,test.support.run_unittest()} no longer raise
@code{TestDidNotRun} if the test result contains skipped tests. The
exception is now only raised if no test have been run and no test have
been skipped.

@item 
bpo-35412@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35412}: Add testcase to @code{test_future4}: check unicode literal.

@item 
bpo-26704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26704}: Added test demonstrating double-patching of an instance method.
Patch by Anthony Sottile.

@item 
bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725}: test_multiprocessing_fork may crash on recent versions of
macOS.  Until the issue is resolved, skip the test on macOS.

@item 
bpo-35352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35352}: Modify test_asyncio to use the certificate set from the test
directory.

@item 
bpo-35317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35317}: Fix @code{mktime()} overflow error in @code{test_email}: run
@code{test_localtime_daylight_true_dst_true()} and
@code{test_localtime_daylight_false_dst_true()} with a specific timezone.

@item 
bpo-21263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21263}: After several reports that test_gdb does not work properly on
macOS and since gdb is not shipped by default anymore, test_gdb is now
skipped on macOS when LLVM Clang has been used to compile Python. Patch by
Lysandros Nikolaou

@item 
bpo-34279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34279}: regrtest issue a warning when no tests have been executed in a
particular test file. Also, a new final result state is issued if no test
have been executed across all test files. Patch by Pablo Galindo.

@item 
bpo-34962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34962}: make docstest in Doc now passes., and is enforced in CI

@item 
bpo-23596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23596}: Use argparse for the command line of the gzip module. Patch by
Antony Lee

@item 
bpo-34537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34537}: Fix @code{test_gdb.test_strings()} when @code{LC_ALL=C} and GDB was
compiled with Python 3.6 or earlier.

@item 
bpo-34587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34587}: test_socket: Remove RDSTest.testCongestion(). The test tries to
fill the receiver's socket buffer and expects an error. But the RDS
protocol doesn't require that. Moreover, the Linux implementation of RDS
expects that the producer of the messages reduces its rate, it's not the
role of the receiver to trigger an error. The test fails on Fedora 28 by
design, so just remove it.

@item 
bpo-34661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34661}: Fix test_shutil if unzip doesn't support -t.

@item 
bpo-34200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34200}: Fixed non-deterministic flakiness of test_pkg by not using the
scary test.support.module_cleanup() logic to save and restore sys.modules
contents between test cases.

@item 
bpo-34569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34569}: The experimental PEP 554 data channels now correctly pass
negative PyLong objects between subinterpreters on 32-bit systems. Patch
by Michael Felt.

@item 
bpo-34594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34594}: Fix usage of hardcoded @code{errno} values in the tests.

@item 
bpo-34579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34579}: Fix test_embed for AIX Patch by Michael Felt

@item 
bpo-34542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34542}: Use 3072 RSA keys and SHA-256 signature for test certs and
keys.

@item 
bpo-11193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11193}: Remove special condition for AIX in
@code{test_subprocess.test_undecodable_env}

@item 
bpo-34347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34347}: Fix @code{test_utf8_mode.test_cmd_line} for AIX

@item 
bpo-34490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34490}: On AIX with AF_UNIX family sockets getsockname() does not
provide 'sockname', so skip calls to transport.get_extra_info('sockname')

@item 
bpo-34391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34391}: Fix ftplib test for TLS 1.3 by reading from data socket.

@item 
bpo-11192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11192}: Fix @code{test_socket} on AIX 6.1 and later IPv6 zone id supports
only supported by inet_pton6_zone() Switch to runtime-based
platform.system() to establish current platform  rather than build-time
based sys.platform()

@item 
bpo-34399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34399}: Update all RSA keys and DH params to use at least 2048 bits.

@item 
bpo-34373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34373}: Fix @code{test_mktime} and @code{test_pthread_getcpuclickid} tests
for AIX Add range checking for @code{_PyTime_localtime} for AIX Patch by
Michael Felt

@item 
bpo-11191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11191}: Skip the distutils test 'test_search_cpp' when using XLC as
compiler patch by aixtools (Michael Felt)

@item 
Improved an error message when mock assert_has_calls fails.

@item 
bpo-33746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33746}: Fix test_unittest when run in verbose mode.

@item 
bpo-33901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33901}: Fix test_dbm_gnu on macOS with gdbm 1.15: add a larger value to
make sure that the file size changes.

@item 
bpo-33873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33873}: Fix a bug in @code{regrtest} that caused an extra test to run if
--huntrleaks/-R was used. Exit with error in case that invalid parameters
are specified to --huntrleaks/-R (at least one warmup run and one
repetition must be used).

@item 
bpo-33562@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33562}: Check that a global asyncio event loop policy is not left
behind by any tests.

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: Fixed test_gdb when Python is compiled with flags -mcet
-fcf-protection -O0.

@item 
bpo-33358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33358}: Fix @code{test_embed.test_pre_initialization_sys_options()} when
the interpreter is built with @code{--enable-shared}.

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-32663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32663}: Making sure the @code{SMTPUTF8SimTests} class of tests gets run in
test_smtplib.py.

@item 
bpo-27643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27643}: Test_C test case needs "signed short" bitfields, but the IBM
XLC compiler (on AIX) does not support this Skip the code and test when
AIX and XLC are used

Applicable to Python2-2.7 and later

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.

@item 
bpo-31809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31809}: Add tests to verify connection with secp ECDH curves.
@end itemize

@node Build<25>,Windows<28>,Tests<27>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id261}@anchor{11c2}
@subsubsection Build



@itemize -

@item 
bpo-34691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34691}: The _contextvars module is now built into the core Python
library on Windows.

@item 
bpo-35683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35683}: Improved Azure Pipelines build steps and now verifying layouts
correctly

@item 
bpo-35642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35642}: Remove asynciomodule.c from pythoncore.vcxproj

@item 
bpo-35550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35550}: Fix incorrect Solaris #ifdef checks to look for __sun && __SVR4
instead of sun when compiling.

@item 
bpo-35499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35499}: @code{make profile-opt} no longer replaces @code{CFLAGS_NODIST} with
@code{CFLAGS}. It now adds profile-guided optimization (PGO) flags to
@code{CFLAGS_NODIST}: existing @code{CFLAGS_NODIST} flags are kept.

@item 
bpo-35257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35257}: Avoid leaking the linker flags from Link Time Optimizations
(LTO) into distutils when compiling C extensions.

@item 
bpo-35351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35351}: When building Python with clang and LTO, LTO flags are no
longer passed into CFLAGS to build third-party C extensions through
distutils.

@item 
bpo-35139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35139}: Fix a compiler error when statically linking @code{pyexpat} in
@code{Modules/Setup}.

@item 
bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059}: PCbuild: Set InlineFunctionExpansion to OnlyExplicitInline
("/Ob1" option) in pyproject.props in Debug mode to expand functions
marked as inline. This change should make Python compiled in Debug mode a
little bit faster on Windows.

@item 
bpo-35011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35011}: Restores the use of pyexpatns.h to isolate our embedded copy of
the expat C library so that its symbols do not conflict at link or dynamic
loading time with an embedding application or other extension modules with
their own version of libexpat.

@item 
bpo-28015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28015}: Have --with-lto works correctly with clang.

@item 
bpo-34765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34765}: Update the outdated install-sh file to the latest revision from
automake v1.16.1

@item 
bpo-34585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34585}: Check for floating-point byte order in configure.ac using
compilation tests instead of executing code, so that these checks work in
cross-compiled builds.

@item 
bpo-34710@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34710}: Fixed SSL module build with OpenSSL & pedantic CFLAGS.

@item 
bpo-34582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34582}: Add JUnit XML output for regression tests and update Azure
DevOps builds.

@item 
bpo-34081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34081}: Make Sphinx warnings as errors in the Docs Makefile.

@item 
bpo-34555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34555}: Fix for case where it was not possible to have both
@code{HAVE_LINUX_VM_SOCKETS_H} and @code{HAVE_SOCKADDR_ALG} be undefined.

@item 
bpo-33015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33015}: Fix an undefined behaviour in the pthread implementation of
@code{PyThread_start_new_thread()}: add a function wrapper to always
return @code{NULL}.

@item 
bpo-34245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34245}: The Python shared library is now installed with write
permission (mode 0755), which is the standard way of installing such
libraries.

@item 
bpo-34121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34121}: Fix detection of C11 atomic support on clang.

@item 
bpo-32430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32430}: Rename Modules/Setup.dist to Modules/Setup, and remove the
necessity to copy the former manually to the latter when updating the
local source tree.

@item 
bpo-30345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30345}: Add -g to LDFLAGS when compiling with LTO to get debug symbols.

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33648}: The --with-c-locale-warning configuration flag has been
removed. It has had no effect for about a year.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33512}: configure's check for "long double" has been simplified

@item 
bpo-33483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33483}: C compiler is now correctly detected from the standard
environment variables. --without-gcc and --with-icc options have been
removed.

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update config.guess and config.sub files.

@item 
bpo-33377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33377}: Add new triplets for mips r6 and riscv variants (used in
extension suffixes).

@item 
bpo-32232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32232}: By default, modules configured in @code{Modules/Setup} are no longer
built with @code{-DPy_BUILD_CORE}. Instead, modules that specifically need that
preprocessor definition include it in their individual entries.

@item 
bpo-33182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33182}: The embedding tests can once again be built with clang 6.0

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: gcc 8 has added a new warning heuristic to detect invalid
function casts and a stock python build seems to hit that warning quite
often.  The most common is the cast of a METH_NOARGS function (that uses
just one argument) to a PyCFunction. Fix this by adding a dummy argument
to all functions that implement METH_NOARGS.

@item 
bpo-32898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32898}: Fix the python debug build when using COUNT_ALLOCS.

@item 
bpo-29442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29442}: Replace optparse with argparse in setup.py
@end itemize

@node Windows<28>,macOS<23>,Build<25>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id262}@anchor{11c3}
@subsubsection Windows



@itemize -

@item 
bpo-35890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35890}: Fix API calling consistency of GetVersionEx and wcstok.

@item 
bpo-32560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32560}: The @code{py} launcher now forwards its @code{STARTUPINFO} structure
to child processes.

@item 
bpo-35854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35854}: Fix EnvBuilder and --symlinks in venv on Windows

@item 
bpo-35811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35811}: Avoid propagating venv settings when launching via py.exe

@item 
bpo-35797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35797}: Fix default executable used by the multiprocessing module

@item 
bpo-35758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35758}: Allow building on ARM with MSVC.

@item 
bpo-29734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29734}: Fix handle leaks in os.stat on Windows.

@item 
bpo-35596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35596}: Use unchecked PYCs for the embeddable distro to avoid zipimport
restrictions.

@item 
bpo-35596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35596}: Fix vcruntime140.dll being added to embeddable distro multiple
times.

@item 
bpo-35402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35402}: Update Windows build to use Tcl and Tk 8.6.9

@item 
bpo-35401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35401}: Updates Windows build to OpenSSL 1.1.0j

@item 
bpo-34977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34977}: venv on Windows will now use a python.exe redirector rather
than copying the actual binaries from the base environment.

@item 
bpo-34977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34977}: Adds support for building a Windows App Store package

@item 
bpo-35067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35067}: Remove _distutils_findvs module and use vswhere.exe instead.

@item 
bpo-32557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32557}: Allow shutil.disk_usage to take a file path on Windows

@item 
bpo-34770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34770}: Fix a possible null pointer dereference in pyshellext.cpp.

@item 
bpo-34603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34603}: Fix returning structs from functions produced by MSVC

@item 
bpo-34581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34581}: Guard MSVC-specific code in socketmodule.c with @code{#ifdef
_MSC_VER}.

@item 
bpo-34532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34532}: Fixes exit code of list version arguments for py.exe.

@item 
bpo-34062@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34062}: Fixed the '--list' and '--list-paths' arguments for the py.exe
launcher

@item 
bpo-34225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34225}: Ensure INCLUDE and LIB directories do not end with a backslash.

@item 
bpo-34011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34011}: A suite of code has been changed which copied across DLLs and
init.tcl from the running Python location into a venv being created. These
copies are needed only when running from a Python source build, and the
copying code is now only run when that is the case, rather than whenever a
venv is created.

@item 
bpo-34006@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34006}: Revert line length limit for Windows help docs. The line-length
limit is not needed because the pages appear in a separate app rather than
on a browser tab.  It can also interact badly with the DPI setting.

@item 
bpo-31546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31546}: Restore running PyOS_InputHook while waiting for user input at
the prompt. The restores integration of interactive GUI windows (such as
Matplotlib figures) with the prompt on Windows.

@item 
bpo-30237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30237}: Output error when ReadConsole is canceled by
CancelSynchronousIo instead of crashing.

@item 
bpo-33895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33895}: GIL is released while calling functions that acquire Windows
loader lock.

@item 
bpo-33720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33720}: Reduces maximum marshal recursion depth on release builds.

@item 
bpo-29097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29097}: Fix bug where @code{datetime.fromtimestamp()} erroneously throws
an @ref{30b,,OSError} on Windows for values between 0 and 86400. Patch by
Ammar Askar.

@item 
bpo-33316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33316}: PyThread_release_lock always fails

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to use OpenSSL 1.1.0h.

@item 
bpo-32890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32890}: Fix usage of GetLastError() instead of errno in os.execve() and
os.truncate().

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update Tcl and Tk versions to 8.6.8

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{1d2,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

@item 
bpo-1104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1104}: Correctly handle string length in
@code{msilib.SummaryInfo.GetProperty()} to prevent it from truncating the
last character.
@end itemize

@node macOS<23>,IDLE<25>,Windows<28>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id263}@anchor{11c4}
@subsubsection macOS



@itemize -

@item 
bpo-35401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35401}: Update macOS installer to use OpenSSL 1.1.0j.

@item 
bpo-35025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35025}: Properly guard the use of the @code{CLOCK_GETTIME} et al. macros
in @code{timemodule} on macOS.

@item 
bpo-24658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24658}: On macOS, fix reading from and writing into a file with a size
larger than 2 GiB.

@item 
bpo-34405@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34405}: Update to OpenSSL 1.1.0i for macOS installer builds.

@item 
bpo-33635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33635}: In macOS stat on some file descriptors (/dev/fd/3 f.e) will
result in bad file descriptor OSError. Guard against this exception was
added in is_dir, is_file and similar methods. DirEntry.is_dir can also
throw this exception so _RecursiveWildcardSelector._iterate_directories
was also extended with the same error ignoring pattern.

@item 
bpo-13631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13631}: The .editrc file in user's home directory is now processed
correctly during the readline initialization through editline emulation on
macOS.

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.1.0h.

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Build and link with private copy of Tcl/Tk 8.6 for the macOS
10.6+ installer. The 10.9+ installer variant already does this.  This
means that the Python 3.7 provided by the python.org macOS installers no
longer need or use any external versions of Tcl/Tk, either system-provided
or user-installed, such as ActiveTcl.

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

@item 
bpo-31903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31903}: In @code{_scproxy}, drop the GIL when calling into
@code{SystemConfiguration} to avoid deadlocks.
@end itemize

@node IDLE<25>,Tools/Demos<12>,macOS<23>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id264}@anchor{11c5}
@subsubsection IDLE



@itemize -

@item 
bpo-35770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35770}: IDLE macosx deletes Options => Configure IDLE. It previously
deleted Window => Zoom Height by mistake. (Zoom Height is now on the
Options menu).  On Mac, the settings dialog is accessed via Preferences on
the IDLE menu.

@item 
bpo-35769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35769}: Change IDLE's new file name from 'Untitled' to 'untitled'

@item 
bpo-35660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35660}: Fix imports in idlelib.window.

@item 
bpo-35641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35641}: Proper format @code{calltip} when the function has no docstring.

@item 
bpo-33987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33987}: Use ttk Frame for ttk widgets.

@item 
bpo-34055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34055}: Fix erroneous 'smart' indents and newlines in IDLE Shell.

@item 
bpo-35591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35591}: Find Selection now works when selection not found.

@item 
bpo-35196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35196}: Speed up squeezer line counting.

@item 
bpo-35598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35598}: Update config_key: use PEP 8 names and ttk widgets, make some
objects global, and add tests.

@item 
bpo-28097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28097}: Add Previous/Next History entries to Shell menu.

@item 
bpo-35208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35208}: Squeezer now properly counts wrapped lines before newlines.

@item 
bpo-35555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35555}: Gray out Code Context menu entry when it's not applicable.

@item 
bpo-35521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35521}: Document the IDLE editor code context feature. Add some
internal references within the IDLE doc.

@item 
bpo-22703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22703}: The Code Context menu label now toggles between Show/Hide Code
Context. The Zoom Height menu now toggles between Zoom/Restore Height.
Zoom Height has moved from the Window menu to the Options menu.

@item 
bpo-35213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35213}: Where appropriate, use 'macOS' in idlelib.

@item 
bpo-34864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34864}: On macOS, warn if the system preference "Prefer tabs when
opening documents" is set to "Always".

@item 
bpo-34864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34864}: Document two IDLE on MacOS issues. The System Preferences Dock
"prefer tabs always" setting disables some IDLE features.  Menus are a bit
different than as described for Windows and Linux.

@item 
bpo-35202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35202}: Remove unused imports from lib/idlelib

@item 
bpo-33000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33000}: Document that IDLE's shell has no line limit. A program that
runs indefinitely can overfill memory.

@item 
bpo-23220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23220}: Explain how IDLE's Shell displays output.

@item 
bpo-35099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35099}: Improve the doc about IDLE running user code.   The section is
renamed from "IDLE -- console differences" is renamed "Running user code".
It mostly covers the implications of using custom sys.stdxxx objects.

@item 
bpo-35097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35097}: Add IDLE doc subsection explaining editor windows. Topics
include opening, title and status bar, .py* extension, and running.

@item 
bpo-35093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35093}: Document the IDLE document viewer in the IDLE doc. Add a
paragraph in "Help and preferences", "Help sources" subsection.

@item 
bpo-35088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35088}: Update idlelib.help.copy_string docstring. We now use git and
backporting instead of hg and forward merging.

@item 
bpo-35087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35087}: Update idlelib help files for the current doc build. The main
change is the elimination of chapter-section numbers.

@item 
bpo-34548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34548}: Use configured color theme for read-only text views.

@item 
bpo-1529353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1529353}: Enable "squeezing" of long outputs in the shell, to avoid
performance degradation and to clean up the history without losing it.
Squeezed outputs may be copied, viewed in a separate window, and
"unsqueezed".

@item 
bpo-34047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34047}: Fixed mousewheel scrolling direction on macOS.

@item 
bpo-34275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34275}: Make IDLE calltips always visible on Mac. Some MacOS-tk
combinations need .update_idletasks(). Patch by Kevin Walzer.

@item 
bpo-34120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34120}: Fix unresponsiveness after closing certain windows and dialogs.

@item 
bpo-33975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33975}: Avoid small type when running htests. Since part of the purpose
of human-viewed tests is to determine that widgets look right, it is
important that they look the same for testing as when running IDLE.

@item 
bpo-33905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33905}: Add test for idlelib.stackview.StackBrowser.

@item 
bpo-33924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33924}: Change mainmenu.menudefs key 'windows' to 'window'. Every other
menudef key is lowercase version of main menu entry.

@item 
bpo-33906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33906}: Rename idlelib.windows as window Match Window on the main menu
and remove last plural module name.

@item 
bpo-33917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33917}: Fix and document idlelib/idle_test/template.py. The revised
file compiles, runs, and tests OK.  idle_test/README.txt explains how to
use it to create new IDLE test files.

@item 
bpo-33904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33904}: IDLE: In rstrip, rename class RstripExtension as Rstrip

@item 
bpo-33907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33907}: For consistency and clarity, rename an IDLE module and classes.
Module calltips and its class CallTips are now calltip and Calltip. In
module calltip_w, class CallTip is now CalltipWindow.

@item 
bpo-33856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33856}: Add "help" in the welcome message of IDLE

@item 
bpo-33839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33839}: IDLE: refactor ToolTip and CallTip and add documentation and
tests

@item 
bpo-33855@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33855}: Minimally test all IDLE modules. Add missing files, import
module, instantiate classes, and check coverage. Check existing files.

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 环境变量; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<12>,C API<20>,IDLE<25>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id265}@anchor{11c6}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-35884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35884}: Add a benchmark script for timing various ways to access
variables: @code{Tools/scripts/var_access_benchmark.py}.

@item 
bpo-34989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34989}: python-gdb.py now handles errors on computing the line number
of a Python frame.

@item 
bpo-20260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20260}: Argument Clinic now has non-bitwise unsigned int converters.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: python-gdb now catches @code{UnicodeDecodeError} exceptions when
calling @code{string()}.

@item 
bpo-32962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32962}: python-gdb now catches ValueError on read_var(): when Python
has no debug symbols for example.

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-25427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25427}: Remove the pyvenv script in favor of @code{python3 -m venv} in
order to lower confusion as to what Python interpreter a virtual
environment will be created for.

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node C API<20>,,Tools/Demos<12>,Python 3 8 0 alpha 1
@anchor{whatsnew/changelog id266}@anchor{11c7}
@subsubsection C API



@itemize -

@item 
bpo-35713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35713}: The @code{PyByteArray_Init()} and @code{PyByteArray_Fini()}
functions have been removed. They did nothing since Python 2.7.4 and
Python 3.2.0, were excluded from the limited API (stable ABI), and were
not documented.

@item 
bpo-33817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33817}: Fixed @ref{11c8,,_PyBytes_Resize()} for empty bytes objects.

@item 
bpo-35322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35322}: Fix memory leak in @ref{54a,,PyUnicode_EncodeLocale()} and
@ref{11c9,,PyUnicode_EncodeFSDefault()} on error handling.

@item 
bpo-35059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35059}: The following C macros have been converted to static inline
functions: @ref{396,,Py_INCREF()}, @ref{397,,Py_DECREF()}, @ref{398,,Py_XINCREF()},
@ref{399,,Py_XDECREF()}, @code{PyObject_INIT()},
@code{PyObject_INIT_VAR()}.

@item 
bpo-35296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35296}: @code{make install} now also installs the internal API:
@code{Include/internal/*.h} header files.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: Internal APIs surrounded by @code{#ifdef Py_BUILD_CORE} have been
moved from @code{Include/*.h} headers to new header files
@code{Include/internal/pycore_*.h}.

@item 
bpo-35259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35259}: Conditionally declare @ref{6ca,,Py_FinalizeEx()} (new in 3.6)
based on Py_LIMITED_API. Patch by Arthur Neufeld.

@item 
bpo-35081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35081}: The @code{_PyObject_GC_TRACK()} and
@code{_PyObject_GC_UNTRACK()} macros have been removed from the public C
API.

@item 
bpo-35134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=35134}: Creation of a new @code{Include/cpython/} subdirectory.

@item 
bpo-34725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34725}: Adds _Py_SetProgramFullPath so embedders may override
sys.executable

@item 
bpo-34910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34910}: Ensure that @ref{11ca,,PyObject_Print()} always returns @code{-1} on
error.  Patch by Zackery Spytz.

@item 
bpo-34523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34523}: Py_DecodeLocale() and Py_EncodeLocale() now use the UTF-8
encoding on Windows if Py_LegacyWindowsFSEncodingFlag is zero.

@item 
bpo-34193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34193}: Fix pluralization in TypeError messages in getargs.c and
typeobject.c: '1 argument' instead of '1 arguments' and '1 element'
instead of '1 elements'.

@item 
bpo-34127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34127}: Return grammatically correct error message based on argument
count. Patch by Karthikeyan Singaravelan.

@item 
bpo-23927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23927}: Fixed @ref{6fc,,SystemError} in
@ref{6cb,,PyArg_ParseTupleAndKeywords()} when the @code{w*} format unit is used
for optional parameter.

@item 
bpo-32455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32455}: Added @code{PyCompile_OpcodeStackEffectWithJump()}.

@item 
bpo-34008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34008}: Py_Main() can again be called after Py_Initialize(), as in
Python 3.6.

@item 
bpo-32500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32500}: Fixed error messages for @ref{11cb,,PySequence_Size()},
@ref{11cc,,PySequence_GetItem()}, @ref{11cd,,PySequence_SetItem()} and
@ref{11ce,,PySequence_DelItem()} called with a mapping and
@ref{11cf,,PyMapping_Size()} called with a sequence.

@item 
bpo-33818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33818}: @code{PyExceptionClass_Name()} will now return @code{const char
*} instead of @code{char *}.

@item 
bpo-33042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33042}: Embedding applications may once again call
PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption prior to
calling Py_Initialize.

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check

@item 
bpo-30863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30863}: @ref{11d0,,PyUnicode_AsWideChar()} and
@ref{544,,PyUnicode_AsWideCharString()} no longer cache the @code{wchar_t*}
representation of string objects.
@end itemize

@node Python 3 7 0 final,Python 3 7 0 release candidate 1,Python 3 8 0 alpha 1,更新日志
@anchor{whatsnew/changelog python-3-7-0-final}@anchor{11d1}
@subsection Python 3.7.0 final


@emph{Release date: 2018-06-27}

@menu
* Library: Library<37>. 
* C API: C API<21>. 

@end menu

@node Library<37>,C API<21>,,Python 3 7 0 final
@anchor{whatsnew/changelog id267}@anchor{11d2}
@subsubsection Library



@itemize -

@item 
bpo-33851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33851}: Fix @ref{11d3,,ast.get_docstring()} for a node that lacks a
docstring.
@end itemize

@node C API<21>,,Library<37>,Python 3 7 0 final
@anchor{whatsnew/changelog id268}@anchor{11d4}
@subsubsection C API



@itemize -

@item 
bpo-33932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33932}: Calling Py_Initialize() twice does nothing, instead of failing
with a fatal error: restore the Python 3.6 behaviour.
@end itemize

@node Python 3 7 0 release candidate 1,Python 3 7 0 beta 5,Python 3 7 0 final,更新日志
@anchor{whatsnew/changelog python-3-7-0-release-candidate-1}@anchor{11d5}
@subsection Python 3.7.0 release candidate 1


@emph{Release date: 2018-06-12}

@menu
* Core and Builtins: Core and Builtins<35>. 
* Library: Library<38>. 
* Documentation: Documentation<27>. 
* Build: Build<26>. 
* Windows: Windows<29>. 
* IDLE: IDLE<26>. 

@end menu

@node Core and Builtins<35>,Library<38>,,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id269}@anchor{11d6}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33803}: Fix a crash in hamt.c caused by enabling GC tracking for an
object that hadn't all of its fields set to NULL.

@item 
bpo-33706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33706}: Fix a crash in Python initialization when parsing the command
line options. Thanks Christoph Gohlke for the bug report and the fix!

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.
@end itemize

@node Library<38>,Documentation<27>,Core and Builtins<35>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id270}@anchor{11d7}
@subsubsection Library



@itemize -

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33694}: asyncio: Fix a race condition causing data loss on
pause_reading()/resume_reading() when using the ProactorEventLoop.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Correct test for @code{uuid_enc_be} availability in
@code{configure.ac}. Patch by Michael Felt.

@item 
bpo-33792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33792}: Add asyncio.WindowsSelectorEventLoopPolicy and
asyncio.WindowsProactorEventLoopPolicy.

@item 
bpo-33778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33778}: Update @code{unicodedata}'s database to Unicode version 11.0.0.

@item 
bpo-33770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33770}: improve base64 exception message for encoded inputs of invalid
length

@item 
bpo-33769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33769}: asyncio/start_tls: Fix error message; cancel callbacks in case
of an unhandled error; mark SSLTransport as closed if it is aborted.

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{1ff,,TypeError} instead of @ref{6fc,,SystemError} when
performed on @ref{323,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-33734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33734}: asyncio/ssl: Fix AttributeError, increase default handshake
timeout

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-33582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33582}: Emit a deprecation warning for inspect.formatargspec
@end itemize

@node Documentation<27>,Build<26>,Library<38>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id271}@anchor{11d8}
@subsubsection Documentation



@itemize -

@item 
bpo-33409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33409}: Clarified the relationship between 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538}'s
PYTHONCOERCECLOCALE and PEP 540's PYTHONUTF8 mode.

@item 
bpo-33736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33736}: Improve the documentation of @ref{474,,asyncio.open_connection()},
@ref{475,,asyncio.start_server()} and their UNIX socket counterparts.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node Build<26>,Windows<29>,Documentation<27>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id272}@anchor{11d9}
@subsubsection Build



@itemize -

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.
@end itemize

@node Windows<29>,IDLE<26>,Build<26>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id273}@anchor{11da}
@subsubsection Windows



@itemize -

@item 
bpo-33720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33720}: Reduces maximum marshal recursion depth on release builds.
@end itemize

@node IDLE<26>,,Windows<29>,Python 3 7 0 release candidate 1
@anchor{whatsnew/changelog id274}@anchor{11db}
@subsubsection IDLE



@itemize -

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.
@end itemize

@node Python 3 7 0 beta 5,Python 3 7 0 beta 4,Python 3 7 0 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-7-0-beta-5}@anchor{11dc}
@subsection Python 3.7.0 beta 5


@emph{Release date: 2018-05-30}

@menu
* Core and Builtins: Core and Builtins<36>. 
* Library: Library<39>. 
* Documentation: Documentation<28>. 
* Tests: Tests<28>. 
* Build: Build<27>. 
* macOS: macOS<24>. 
* IDLE: IDLE<27>. 

@end menu

@node Core and Builtins<36>,Library<39>,,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id275}@anchor{11dd}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{c1b,,gc.garbage} list. @code{PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-33509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33509}: Fix module_globals parameter of warnings.warn_explicit(): don't
crash if module_globals is not a dict.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: The new @ref{388,,os.posix_spawn} added in 3.7.0b1 was removed as we are
still working on what the API should look like.  Expect this in 3.8
instead.

@item 
bpo-33475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33475}: Fixed miscellaneous bugs in converting annotations to strings
and optimized parentheses in the string representation.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}: Due to unexpected compatibility issues discovered during
downstream beta testing, reverted bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}. @code{docstring} field is
removed from Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes
which was added in 3.7a1.  Docstring expression is restored as a first
statement in their body. Based on patch by Inada Naoki.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @ref{1194,,ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.
@end itemize

@node Library<39>,Documentation<28>,Core and Builtins<36>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id276}@anchor{11de}
@subsubsection Library



@itemize -

@item 
bpo-32751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32751}: When cancelling the task due to a timeout,
@ref{191,,asyncio.wait_for()} will now wait until the cancellation is complete.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Support protocol type switching in SSLTransport.set_protocol().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Pause the transport as early as possible to further reduce the
risk of data_received() being called before connection_made().

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-32610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32610}: Make asyncio.all_tasks() return only pending tasks.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Avoid blocking on file IO in sendfile fallback code

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33654}: Fix transport.set_protocol() to support switching between
asyncio.Protocol and asyncio.BufferedProtocol.  Fix loop.start_tls() to
work with asyncio.BufferedProtocols.

@item 
bpo-33652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33652}: Pickles of type variables and subscripted generics are now
future-proof and compatible with older Python versions.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: Fixed @ref{520,,uuid.uuid1()} on FreeBSD.

@item 
bpo-33618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33618}: Finalize and document preliminary and experimental TLS 1.3
support with OpenSSL 1.1.1

@item 
bpo-33623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33623}: Fix possible SIGSGV when asyncio.Future is created in __del__

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33570}: Change TLS 1.3 cipher suite settings for compatibility with
OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 ciphers
enabled by default.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Do not simplify arguments to @ref{11b3,,typing.Union}. Now
@code{Union[Manager, Employee]} is not simplified to @code{Employee} at runtime.
Such simplification previously caused several bugs and limited
possibilities for introspection.

@item 
bpo-33540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33540}: Add a new @code{block_on_close} class attribute to
@code{ForkingMixIn} and @code{ThreadingMixIn} classes of @ref{f0,,socketserver}.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33109}: argparse subparsers are once again not required by default,
reverting the change in behavior introduced by bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510} in 3.7.0a2.

@item 
bpo-33536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33536}: dataclasses.make_dataclass now checks for invalid field names
and duplicate fields. Also, added a check for invalid field
specifications.

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
Fix failure in @ref{1f0,,typing.get_type_hints()} when ClassVar was provided as a
string forward reference.

@item 
bpo-33505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33505}: Optimize asyncio.ensure_future() by reordering if checks: 1.17x
faster.

@item 
bpo-33497@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33497}: Add errors param to cgi.parse_multipart and make an encoding in
FieldStorage use the given errors (needed for Twisted).  Patch by Amber
Brown.

@item 
bpo-33495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33495}: Change dataclasses.Fields repr to use the repr of each of its
members, instead of str.  This makes it more clear what each field
actually represents.  This is especially true for the 'type' member.

@item 
bpo-33453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33453}: Fix dataclasses to work if using literal string type
annotations or if using PEP 563 "Postponed Evaluation of Annotations".
Only specific string prefixes are detected for both ClassVar ("ClassVar"
and "typing.ClassVar") and InitVar ("InitVar" and "dataclasses.InitVar").

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-28167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28167}: The function @code{platform.linux_distribution} and
@code{platform.dist} now trigger a @code{DeprecationWarning} and have been
marked for removal in Python 3.8

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Dong-hee Na.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Patch by Michael Lazar.

@item 
bpo-32257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32257}: The ssl module now contains OP_NO_RENEGOTIATION constant,
available with OpenSSL 1.1.0h or 1.1.1.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2a,,ctypes}.  Patch by Segev Finer.
@end itemize

@node Documentation<28>,Tests<28>,Library<39>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id277}@anchor{11df}
@subsubsection Documentation



@itemize -

@item 
bpo-23859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23859}: Document that @ref{208,,asyncio.wait()} does not cancel its futures on
timeout.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Document 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} changes to asyncio.

@item 
bpo-33604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33604}: Update HMAC md5 default to a DeprecationWarning, bump removal
to 3.8.

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.
@end itemize

@node Tests<28>,Build<27>,Documentation<28>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id278}@anchor{11e0}
@subsubsection Tests



@itemize -

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-32604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32604}: Remove the _xxsubinterpreters module (meant for testing) and
associated helpers.  This module was originally added recently in 3.7b1.
@end itemize

@node Build<27>,macOS<24>,Tests<28>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id279}@anchor{11e1}
@subsubsection Build



@itemize -

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: Add @code{-Wno-cast-function-type} for gcc 8 for silencing
warnings about function casts like casting to PyCFunction in method
definition lists.
@end itemize

@node macOS<24>,IDLE<27>,Build<27>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id280}@anchor{11e2}
@subsubsection macOS



@itemize -

@item 
bpo-13631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13631}: The .editrc file in user's home directory is now processed
correctly during the readline initialization through editline emulation on
macOS.
@end itemize

@node IDLE<27>,,macOS<24>,Python 3 7 0 beta 5
@anchor{whatsnew/changelog id281}@anchor{11e3}
@subsubsection IDLE



@itemize -

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.
@end itemize

@node Python 3 7 0 beta 4,Python 3 7 0 beta 3,Python 3 7 0 beta 5,更新日志
@anchor{whatsnew/changelog python-3-7-0-beta-4}@anchor{11e4}
@subsection Python 3.7.0 beta 4


@emph{Release date: 2018-05-02}

@menu
* Core and Builtins: Core and Builtins<37>. 
* Library: Library<40>. 
* Documentation: Documentation<29>. 
* Tests: Tests<29>. 
* Build: Build<28>. 
* Windows: Windows<30>. 
* macOS: macOS<25>. 
* IDLE: IDLE<28>. 
* Tools/Demos: Tools/Demos<13>. 

@end menu

@node Core and Builtins<37>,Library<40>,,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id282}@anchor{11e5}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33363}: Raise a SyntaxError for @code{async with} and @code{async for}
statements outside of async functions.

@item 
bpo-33128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33128}: Fix a bug that causes PathFinder to appear twice on
sys.meta_path. Patch by Pablo Galindo Salgado.

@item 
bpo-33312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33312}: Fixed clang ubsan (undefined behavior sanitizer) warnings in
dictobject.c by adjusting how the internal struct _dictkeysobject shared
keys structure is declared.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-33205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33205}: Change dict growth function from
@code{round_up_to_power_2(used*2+hashtable_size/2)} to
@code{round_up_to_power_2(used*3)}.  Previously, dict is shrinked only when
@code{used == 0}. Now dict has more chance to be shrinked.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.
@end itemize

@node Library<40>,Documentation<29>,Core and Builtins<37>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id283}@anchor{11e6}
@subsubsection Library



@itemize -

@item 
bpo-33281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33281}: Fix ctypes.util.find_library regression on macOS.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{34,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{11b7,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @ref{c7,,parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-33266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33266}: lib2to3 now recognizes @code{rf'...'} strings.

@item 
bpo-11594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11594}: Ensure line-endings are respected when using lib2to3.

@item 
bpo-33254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33254}: Have @ref{11b8,,importlib.resources.contents()} and
@ref{11b9,,importlib.abc.ResourceReader.contents()} return an @ref{c84,,iterable}
instead of an @ref{11ba,,iterator}.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33185}: Fixed regression when running pydoc with the @ref{44c,,-m}
switch. (The regression was introduced in 3.7.0b3 by the resolution of
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}) This fix also changed pydoc to add @code{os.getcwd()} to
@ref{262,,sys.path} when necessary, rather than adding @code{"."}.

@item 
bpo-33169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33169}: Delete entries of @code{None} in @ref{5a0,,sys.path_importer_cache}
when @code{importlib.machinery.invalidate_caches()} is called.

@item 
bpo-33217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33217}: Deprecate looking up non-Enum objects in Enum classes and Enum
members (will raise @ref{1ff,,TypeError} in 3.8+).

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{11bb,,pickle.Pickler.dump()}.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Improved error handling and fixed a reference leak in
@ref{388,,os.posix_spawn()}.

@item 
bpo-33175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33175}: In dataclasses, Field.__set_name__ now looks up the
__set_name__ special method on the class, not the instance, of the default
value.

@item 
bpo-33097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33097}: Raise RuntimeError when @code{executor.submit} is called during
interpreter shutdown.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.
@end itemize

@node Documentation<29>,Tests<29>,Library<40>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id284}@anchor{11e7}
@subsubsection Documentation



@itemize -

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-32337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32337}: Update documentation related with @code{dict} order.
@end itemize

@node Tests<29>,Build<28>,Documentation<29>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id285}@anchor{11e8}
@subsubsection Tests



@itemize -

@item 
bpo-33358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33358}: Fix @code{test_embed.test_pre_initialization_sys_options()} when
the interpreter is built with @code{--enable-shared}.
@end itemize

@node Build<28>,Windows<30>,Tests<29>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id286}@anchor{11e9}
@subsubsection Build



@itemize -

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.

@item 
bpo-33393@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33393}: Update config.guess and config.sub files.

@item 
bpo-33377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33377}: Add new triplets for mips r6 and riscv variants (used in
extension suffixes).

@item 
bpo-32232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32232}: By default, modules configured in @code{Modules/Setup} are no longer
built with @code{-DPy_BUILD_CORE}. Instead, modules that specifically need that
preprocessor definition include it in their individual entries.

@item 
bpo-33182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33182}: The embedding tests can once again be built with clang 6.0
@end itemize

@node Windows<30>,macOS<25>,Build<28>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id287}@anchor{11ea}
@subsubsection Windows



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to use OpenSSL 1.1.0h.
@end itemize

@node macOS<25>,IDLE<28>,Windows<30>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id288}@anchor{11eb}
@subsubsection macOS



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.1.0h.
@end itemize

@node IDLE<28>,Tools/Demos<13>,macOS<25>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id289}@anchor{11ec}
@subsubsection IDLE



@itemize -

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.
@end itemize

@node Tools/Demos<13>,,IDLE<28>,Python 3 7 0 beta 4
@anchor{whatsnew/changelog id290}@anchor{11ed}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node Python 3 7 0 beta 3,Python 3 7 0 beta 2,Python 3 7 0 beta 4,更新日志
@anchor{whatsnew/changelog python-3-7-0-beta-3}@anchor{11ee}
@subsection Python 3.7.0 beta 3


@emph{Release date: 2018-03-29}

@menu
* Security: Security<23>. 
* Core and Builtins: Core and Builtins<38>. 
* Library: Library<41>. 
* Documentation: Documentation<30>. 
* Tests: Tests<30>. 
* Build: Build<29>. 
* Windows: Windows<31>. 
* macOS: macOS<26>. 
* IDLE: IDLE<29>. 
* Tools/Demos: Tools/Demos<14>. 
* C API: C API<22>. 

@end menu

@node Security<23>,Core and Builtins<38>,,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id291}@anchor{11ef}
@subsubsection Security



@itemize -

@item 
bpo-33136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33136}: Harden ssl module against LibreSSL CVE-2018-8970.
X509_VERIFY_PARAM_set1_host() is called with an explicit namelen. A new
test ensures that NULL bytes are not allowed.

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch
by Jamie Davis.
@end itemize

@node Core and Builtins<38>,Library<41>,Security<23>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id292}@anchor{11f0}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33053}: When using the -m switch, sys.path[0] is now explicitly
expanded as the @emph{starting} working directory, rather than being left as
the empty path (which allows imports from the current working directory at
the time of the import)

@item 
bpo-33018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33018}: Improve consistency of errors raised by @code{issubclass()} when
called with a non-class and an abstract base class as the first and second
arguments, respectively. Patch by Josh Bronson.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed jumping when the function contains an @code{async for} loop.

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-33005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33005}: Fix a crash on fork when using a custom memory allocator (ex:
using PYTHONMALLOC env var). _PyGILState_Reinit() and
_PyInterpreterState_Enable() now use the default RAW memory allocator to
allocate a new interpreters mutex on fork.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32836}: Don't use temporary variables in cases of list/dict/set
comprehensions
@end itemize

@node Library<41>,Documentation<30>,Core and Builtins<38>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id293}@anchor{11f1}
@subsubsection Library



@itemize -

@item 
bpo-33141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33141}: Have Field objects pass through __set_name__ to their default
values, if they have their own __set_name__.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-32873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32873}: Treat type variables and special typing forms as immutable by
copy and pickle.  This fixes several minor issues and inconsistencies, and
improves backwards compatibility with Python 3.6.

@item 
bpo-33134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33134}: When computing dataclass's __hash__, use the lookup table to
contain the function which returns the __hash__ value.  This is an
improvement over looking up a string, and then testing that string to see
what to do.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-32505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32505}: Raise TypeError if a member variable of a dataclass is of type
Field, but doesn't have a type annotation.

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the failure on OSX caused by the tests relying on
sem_getvalue

@item 
bpo-33116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33116}: Add 'Field' to dataclasses.__all__.

@item 
bpo-32896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32896}: Fix an error where subclassing a dataclass with a field that
uses a default_factory would generate an incorrect class.

@item 
bpo-33100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33100}: Dataclasses: If a field has a default value that's a
MemberDescriptorType, then it's from that field being in __slots__, not an
actual default value.

@item 
bpo-32953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32953}: If a non-dataclass inherits from a frozen dataclass, allow
attributes to be added to the derived class.  Only attributes from the
frozen dataclass cannot be assigned to.  Require all dataclasses in a
hierarchy to be either all frozen or all non-frozen.

@item 
bpo-33061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33061}: Add missing @code{NoReturn} to @code{__all__} in typing.py

@item 
bpo-33078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33078}: Fix the size handling in multiprocessing.Queue when a pickling
error occurs.

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-33056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33056}: FIX properly close leaking fds in
concurrent.futures.ProcessPoolExecutor.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{a2,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-32999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32999}: Fix C implementation of @code{ABC.__subclasscheck__(cls,
subclass)} crashed when @code{subclass} is not a type object.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32056}: Improved exceptions raised for invalid number of channels and
sample width when read an audio file in modules @ref{4,,aifc}, @ref{130,,wave}
and @ref{fa,,sunau}.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{10e,,tkinter}, @code{after_cancel(None)} now raises a
@ref{16d,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-31639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31639}: http.server now exposes a ThreadedHTTPServer class and uses it
when the module is run with @code{-m} to cope with web browsers pre-opening
sockets.

@item 
bpo-27645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27645}: @ref{4e7,,sqlite3.Connection} now exposes a
@ref{4e8,,backup} method, if the underlying SQLite
library is at version 3.6.11 or higher.  Patch by Lele Gaifax.
@end itemize

@node Documentation<30>,Tests<30>,Library<41>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id294}@anchor{11f2}
@subsubsection Documentation



@itemize -

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{14a,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)
@end itemize

@node Tests<30>,Build<29>,Documentation<30>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id295}@anchor{11f3}
@subsubsection Tests



@itemize -

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.
@end itemize

@node Build<29>,Windows<31>,Tests<30>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id296}@anchor{11f4}
@subsubsection Build



@itemize -

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.
@end itemize

@node Windows<31>,macOS<26>,Build<29>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id297}@anchor{11f5}
@subsubsection Windows



@itemize -

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.
@end itemize

@node macOS<26>,IDLE<29>,Windows<31>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id298}@anchor{11f6}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Build and link with private copy of Tcl/Tk 8.6 for the macOS
10.6+ installer. The 10.9+ installer variant already does this.  This
means that the Python 3.7 provided by the python.org macOS installers no
longer need or use any external versions of Tcl/Tk, either system-provided
or user-installed, such as ActiveTcl.
@end itemize

@node IDLE<29>,Tools/Demos<14>,macOS<26>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id299}@anchor{11f7}
@subsubsection IDLE



@itemize -

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 环境变量; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.
@end itemize

@node Tools/Demos<14>,C API<22>,IDLE<29>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id300}@anchor{11f8}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).
@end itemize

@node C API<22>,,Tools/Demos<14>,Python 3 7 0 beta 3
@anchor{whatsnew/changelog id301}@anchor{11f9}
@subsubsection C API



@itemize -

@item 
bpo-33042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33042}: Embedding applications may once again call
PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption prior to
calling Py_Initialize.

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check
@end itemize

@node Python 3 7 0 beta 2,Python 3 7 0 beta 1,Python 3 7 0 beta 3,更新日志
@anchor{whatsnew/changelog python-3-7-0-beta-2}@anchor{11fa}
@subsection Python 3.7.0 beta 2


@emph{Release date: 2018-02-27}

@menu
* Security: Security<24>. 
* Core and Builtins: Core and Builtins<39>. 
* Library: Library<42>. 
* Documentation: Documentation<31>. 
* Tests: Tests<31>. 
* Build: Build<30>. 
* Windows: Windows<32>. 
* macOS: macOS<27>. 
* IDLE: IDLE<30>. 
* Tools/Demos: Tools/Demos<15>. 

@end menu

@node Security<24>,Core and Builtins<39>,,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id302}@anchor{11fb}
@subsubsection Security



@itemize -

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: The ssl module now allows users to perform their own IDN
en/decoding when using SNI.
@end itemize

@node Core and Builtins<39>,Library<42>,Security<24>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id303}@anchor{11fc}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356}: Remove the new API added in bpo-31356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31356} (gc.ensure_disabled()
context manager).

@item 
bpo-32305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32305}: For namespace packages, ensure that both @code{__file__} and
@code{__spec__.origin} are set to None.

@item 
bpo-32303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32303}: Make sure @code{__spec__.loader} matches @code{__loader__} for
namespace packages.

@item 
bpo-32711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32711}: Fix the warning messages for Python/ast_unparse.c. Patch by
Stéphane Wirtel

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.
@end itemize

@node Library<42>,Documentation<31>,Core and Builtins<39>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id304}@anchor{11fd}
@subsubsection Library



@itemize -

@item 
bpo-32960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32960}: For dataclasses, disallow inheriting frozen from non-frozen
classes, and also disallow inheriting non-frozen from frozen classes. This
restriction will be relaxed at a future date.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-32951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32951}: Direct instantiation of SSLSocket and SSLObject objects is now
prohibited. The constructors were never documented, tested, or designed as
public constructors. Users were suppose to use ssl.wrap_socket() or
SSLContext.

@item 
bpo-32929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32929}: Remove the tri-state parameter "hash", and add the boolean
"unsafe_hash". If unsafe_hash is True, add a __hash__ function, but if a
__hash__ exists, raise TypeError.  If unsafe_hash is False, add a __hash__
based on the values of eq= and frozen=.  The unsafe_hash=False behavior is
the same as the old hash=None behavior.  unsafe_hash=False is the default,
just as hash=None used to be.

@item 
bpo-32947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32947}: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3
for future compatibility with OpenSSL 1.1.1.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-32556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32556}: nt._getfinalpathname, nt._getvolumepathname and
nt._getdiskusage now correctly convert from bytes.

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: Emit a @ref{15a,,DeprecationWarning} when using or importing an ABC
directly from @ref{1d,,collections} rather than from @ref{1e,,collections.abc}.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-31333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31333}: @code{_abc} module is added.  It is a speedup module with C
implementations for various functions and methods in @code{abc}.  Creating an
ABC subclass and calling @code{isinstance} or @code{issubclass} with an ABC
subclass are up to 1.5x faster. In addition, this makes Python start-up up
to 10% faster. Note that the new implementation hides internal registry
and caches, previously accessible via private attributes
@code{_abc_registry}, @code{_abc_cache}, and @code{_abc_negative_cache}.  There are
three debugging helper methods that can be used instead
@code{_dump_registry}, @code{_abc_registry_clear}, and @code{_abc_caches_clear}.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @ref{3b8,,asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-32819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32819}: ssl.match_hostname() has been simplified and no longer depends
on re and ipaddress module for wildcard and IP addresses. Error reporting
for invalid wildcards has been improved.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove
TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older version
Windows during run-time.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-32792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32792}: collections.ChainMap() preserves the order of the underlying
mappings.

@item 
bpo-32775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32775}: @ref{11bc,,fnmatch.translate()} no longer produces patterns which
contain set operations. Sets starting with '[' or containing '--', '&&',
'~~' or '||' will be interpreted differently in regular expressions in
future versions. Currently they emit warnings. fnmatch.translate() now
avoids producing patterns containing such sets by accident.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Implement native fast sendfile for Windows proactor event loop.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32741}: Implement @code{asyncio.TimerHandle.when()} method.

@item 
bpo-32691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32691}: Use mod_spec.parent when running modules with pdb

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-31453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31453}: Add TLSVersion constants and SSLContext.maximum_version /
minimum_version attributes. The new API wraps OpenSSL 1.1
@indicateurl{https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html}
feature.

@item 
bpo-24334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24334}: Internal implementation details of ssl module were cleaned up.
The SSLSocket has one less layer of indirection. Owner and session
information are now handled by the SSLSocket and SSLObject constructor.
Channel binding implementation has been simplified.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32585}: Add Ttk spinbox widget to @ref{118,,tkinter.ttk}.  Patch by Alan D
Moore.

@item 
bpo-32221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32221}: Various functions returning tuple containing IPv6 addresses now
omit @code{%scope} part since the same information is already encoded in
@emph{scopeid} tuple item. Especially this speeds up @code{socket.recvfrom()}
when it receives multicast packet since useless resolving of network
interface name is omitted.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The TarFile class now recurses directories in a reproducible
way.

@item 
bpo-30693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30693}: The ZipFile class now recurses directories in a reproducible
way.
@end itemize

@node Documentation<31>,Tests<31>,Library<42>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id305}@anchor{11fe}
@subsubsection Documentation



@itemize -

@item 
bpo-28124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28124}: The ssl module function ssl.wrap_socket() has been
de-emphasized and deprecated in favor of the more secure and efficient
SSLContext.wrap_socket() method.

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Add documentation for the contextvars module (PEP 567).

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-11015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11015}: Update @ref{106,,test.support} documentation.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @ref{433,,__getattr__()} behavior when property @code{get()}
method raises @ref{4aa,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{15a,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @ref{236,,pathlib.PurePath} subclasses.
@end itemize

@node Tests<31>,Build<30>,Documentation<31>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id306}@anchor{11ff}
@subsubsection Tests



@itemize -

@item 
bpo-31809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31809}: Add tests to verify connection with secp ECDH curves.
@end itemize

@node Build<30>,Windows<32>,Tests<31>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id307}@anchor{1200}
@subsubsection Build



@itemize -

@item 
bpo-32898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32898}: Fix the python debug build when using COUNT_ALLOCS.
@end itemize

@node Windows<32>,macOS<27>,Build<30>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id308}@anchor{1201}
@subsubsection Windows



@itemize -

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update Tcl and Tk versions to 8.6.8

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{1d2,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.
@end itemize

@node macOS<27>,IDLE<30>,Windows<32>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id309}@anchor{1202}
@subsubsection macOS



@itemize -

@item 
bpo-32901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32901}: Update macOS 10.9+ installer to Tcl/Tk 8.6.8.
@end itemize

@node IDLE<30>,Tools/Demos<15>,macOS<27>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id310}@anchor{1203}
@subsubsection IDLE



@itemize -

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<15>,,IDLE<30>,Python 3 7 0 beta 2
@anchor{whatsnew/changelog id311}@anchor{1204}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.
@end itemize

@node Python 3 7 0 beta 1,Python 3 7 0 alpha 4,Python 3 7 0 beta 2,更新日志
@anchor{whatsnew/changelog python-3-7-0-beta-1}@anchor{1205}
@subsection Python 3.7.0 beta 1


@emph{Release date: 2018-01-30}

@menu
* Core and Builtins: Core and Builtins<40>. 
* Library: Library<43>. 
* Documentation: Documentation<32>. 
* Tests: Tests<32>. 
* Build: Build<31>. 
* Windows: Windows<33>. 
* macOS: macOS<28>. 
* C API: C API<23>. 

@end menu

@node Core and Builtins<40>,Library<43>,,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id312}@anchor{1206}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32703}: Fix coroutine's ResourceWarning when there's an active error
set when it's being finalized.

@item 
bpo-32650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32650}: Pdb and other debuggers dependent on bdb.py will correctly step
over (next command) native coroutines. Patch by Pablo Galindo.

@item 
bpo-28685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28685}: Optimize list.sort() and sorted() by using type specialized
comparisons when possible.

@item 
bpo-32685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32685}: Improve suggestion when the Python 2 form of print statement is
either present on the same line as the header of a compound statement or
else terminated by a semi-colon instead of a newline. Patch by Nitish
Chandra.

@item 
bpo-32697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32697}: Python now explicitly preserves the definition order of
keyword-only parameters.  It's always preserved their order, but this
behavior was never guaranteed before; this behavior is now guaranteed and
tested.

@item 
bpo-32690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32690}: The locals() dictionary now displays in the lexical order that
variables were defined.  Previously, the order was reversed.

@item 
bpo-32677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32677}: Add @code{.isascii()} method to @code{str}, @code{bytes} and
@code{bytearray}. It can be used to test that string contains only ASCII
characters.

@item 
bpo-32670@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32670}: Enforce 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} for all code. This means that manually
raising a StopIteration exception from a generator is prohibited for all
code, regardless of whether 'from __future__ import generator_stop' was
used or not.

@item 
bpo-32591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32591}: Added built-in support for tracking the origin of coroutine
objects; see sys.set_coroutine_origin_tracking_depth and
CoroutineType.cr_origin. This replaces the asyncio debug mode's use of
coroutine wrapping for native coroutine objects.

@item 
bpo-31368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31368}: Expose preadv and pwritev system calls in the os module. Patch
by Pablo Galindo

@item 
bpo-32544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32544}: @code{hasattr(obj, name)} and @code{getattr(obj, name, default)} are
about 4 times faster than before when @code{name} is not found and @code{obj}
doesn't override @code{__getattr__} or @code{__getattribute__}.

@item 
bpo-26163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26163}: Improved frozenset() hash to create more distinct hash values
when faced with datasets containing many similar values.

@item 
bpo-32550@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32550}: Remove the STORE_ANNOTATION bytecode.

@item 
bpo-20104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20104}: Expose posix_spawn as a low level API in the os module.
(removed before 3.7.0rc1)

@item 
bpo-24340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24340}: Fixed estimation of the code stack size.

@item 
bpo-32436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32436}: Implement 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} Context Variables.

@item 
bpo-18533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18533}: @code{repr()} on a dict containing its own @code{values()} or
@code{items()} no longer raises @code{RecursionError}; OrderedDict similarly.
Instead, use @code{...}, as for other recursive structures.  Patch by Ben
North.

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Py_Initialize() now creates the GIL. The GIL is no longer
created "on demand" to fix a race condition when PyGILState_Ensure() is
called in a non-Python thread.

@item 
bpo-32028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32028}: Leading whitespace is now correctly ignored when generating
suggestions for converting Py2 print statements to Py3 builtin print
function calls. Patch by Sanyam Khurana.

@item 
bpo-31179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31179}: Make dict.copy() up to 5.5 times faster.

@item 
bpo-31113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31113}: Get rid of recursion in the compiler for normal control flow.
@end itemize

@node Library<43>,Documentation<32>,Core and Builtins<40>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id313}@anchor{1207}
@subsubsection Library



@itemize -

@item 
bpo-25988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25988}: Deprecate exposing the contents of collections.abc in the
regular collections module.

@item 
bpo-31429@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31429}: The default cipher suite selection of the ssl module now uses a
blacklist approach rather than a hard-coded whitelist. Python no longer
re-enables ciphers that have been blocked by OpenSSL security update.
Default cipher suite selection can be configured on compile time.

@item 
bpo-30306@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30306}: contextlib.contextmanager now releases the arguments passed to
the underlying generator as soon as the context manager is entered.
Previously it would keep them alive for as long as the context manager was
alive, even when not being used as a function decorator. Patch by Martin
Teichmann.

@item 
bpo-21417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21417}: Added support for setting the compression level for
zipfile.ZipFile.

@item 
bpo-32251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32251}: Implement asyncio.BufferedProtocol (provisional API).

@item 
bpo-32513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32513}: In dataclasses, allow easier overriding of dunder methods
without specifying decorator parameters.

@item 
bpo-32660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32660}: @ref{104,,termios} makes available @code{FIONREAD}, @code{FIONCLEX},
@code{FIOCLEX}, @code{FIOASYNC} and @code{FIONBIO} also under Solaris/derivatives.

@item 
bpo-27931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27931}: Fix email address header parsing error when the username is an
empty quoted string. Patch by Xiang Zhang.

@item 
bpo-32659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32659}: Under Solaris and derivatives, @ref{1208,,os.stat_result} provides
a st_fstype attribute.

@item 
bpo-32662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32662}: Implement Server.start_serving(), Server.serve_forever(), and
Server.is_serving() methods.  Add 'start_serving' keyword parameter to
loop.create_server() and loop.create_unix_server().

@item 
bpo-32391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32391}: Implement @ref{467,,asyncio.StreamWriter.wait_closed()} and
@ref{468,,asyncio.StreamWriter.is_closing()} methods

@item 
bpo-32643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32643}: Make Task._step, Task._wakeup and Future._schedule_callbacks
methods private.

@item 
bpo-32630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32630}: Refactor decimal module to use contextvars to store decimal
context.

@item 
bpo-32622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32622}: Add @code{asyncio.AbstractEventLoop.sendfile()} method.

@item 
bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304}: distutils' upload command no longer corrupts tar files ending
with a CR byte, and no longer tries to convert CR to CRLF in any of the
upload text fields.

@item 
bpo-32502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32502}: uuid.uuid1 no longer raises an exception if a 64-bit hardware
address is encountered.

@item 
bpo-32596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32596}: @code{concurrent.futures} imports @code{ThreadPoolExecutor} and
@code{ProcessPoolExecutor} lazily (using 
@geindex Python 提高建议; PEP 562
PEP 562@footnote{https://www.python.org/dev/peps/pep-0562}). It makes @code{import
asyncio} about 15% faster because asyncio uses only
@code{ThreadPoolExecutor} by default.

@item 
bpo-31801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31801}: Add @code{_ignore_} to @code{Enum} so temporary variables can be used
during class construction without being turned into members.

@item 
bpo-32576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32576}: Use queue.SimpleQueue() in places where it can be invoked from
a weakref callback.

@item 
bpo-32574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32574}: Fix memory leak in asyncio.Queue, when the queue has limited
size and it is full, the cancelation of queue.put() can cause a memory
leak. Patch by: José Melero.

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: The nis module is now compatible with new libnsl and headers
location.

@item 
bpo-32467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32467}: collections.abc.ValuesView now inherits from
collections.abc.Collection.

@item 
bpo-32473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32473}: Improve ABCMeta._dump_registry() output readability

@item 
bpo-32102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32102}: New argument @code{capture_output} for subprocess.run

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: glibc has removed Sun RPC. Use replacement libtirpc headers and
library in nis module.

@item 
bpo-32493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32493}: UUID module fixes build for FreeBSD/OpenBSD

@item 
bpo-32503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32503}: Pickling with protocol 4 no longer creates too small frames.

@item 
bpo-29237@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29237}: Create enum for pstats sorting options

@item 
bpo-32454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32454}: Add close(fd) function to the socket module.

@item 
bpo-25942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25942}: The subprocess module is now more graceful when handling a
Ctrl-C KeyboardInterrupt during subprocess.call, subprocess.run, or a
Popen context manager.  It now waits a short amount of time for the child
(presumed to have also gotten the SIGINT) to exit, before continuing the
KeyboardInterrupt exception handling.  This still includes a SIGKILL in
the call() and run() APIs, but at least the child had a chance first.

@item 
bpo-32433@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32433}: The hmac module now has hmac.digest(), which provides an
optimized HMAC digest.

@item 
bpo-28134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28134}: Sockets now auto-detect family, type and protocol from file
descriptor by default.

@item 
bpo-32404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32404}: Fix bug where @ref{f75,,datetime.datetime.fromtimestamp()} did not
call __new__ in @ref{19f,,datetime.datetime} subclasses.

@item 
bpo-32403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32403}: Improved speed of @ref{19d,,datetime.date} and
@ref{19f,,datetime.datetime} alternate constructors.

@item 
bpo-32228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32228}: Ensure that @code{truncate()} preserves the file position (as
reported by @code{tell()}) after writes longer than the buffer size.

@item 
bpo-32410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32410}: Implement @code{loop.sock_sendfile} for asyncio event loop.

@item 
bpo-22908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22908}: Added seek and tell to the ZipExtFile class. This only works if
the file object used to open the zipfile is seekable.

@item 
bpo-32373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32373}: Add socket.getblocking() method.

@item 
bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}: Add @ref{9e,,importlib.resources} and
@ref{457,,importlib.abc.ResourceReader} as the unified API for reading
resources contained within packages.  Loaders wishing to support resource
reading must implement the @code{get_resource_reader()} method.
File-based and zipimport-based loaders both implement these APIs.
@ref{570,,importlib.abc.ResourceLoader} is deprecated in favor of these new
APIs.

@item 
bpo-32320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32320}: collections.namedtuple() now supports default values.

@item 
bpo-29302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29302}: Add contextlib.AsyncExitStack. Patch by Alexander Mohr and Ilya
Kulakov.

@item 
bpo-31961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31961}: @emph{Removed in Python 3.7.0b2.} The @emph{args} argument of
subprocess.Popen can now be a @ref{47b,,path-like object}. If @emph{args} is given
as a sequence, it's first element can now be a @ref{47b,,path-like object} as
well.

@item 
bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}: The @ref{58d,,locale.localeconv()} function now sets temporarily the
@code{LC_CTYPE} locale to the @code{LC_NUMERIC} locale to decode
@code{decimal_point} and @code{thousands_sep} byte strings if they are non-ASCII
or longer than 1 byte, and the @code{LC_NUMERIC} locale is different than the
@code{LC_CTYPE} locale. This temporary change affects other threads. Same
change for the @ref{5dd,,str.format()} method when formatting a number
(@ref{205,,int}, @ref{1fe,,float}, @ref{1fe,,float} and subclasses) with the
@code{n} type (ex: @code{'@{:n@}'.format(1234)}).

@item 
bpo-31853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31853}: Use super().method instead of socket.method in SSLSocket.  They
were there most likely for legacy reasons.

@item 
bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399}: The ssl module now uses OpenSSL's X509_VERIFY_PARAM_set1_host()
and X509_VERIFY_PARAM_set1_ip() API to verify hostname and IP addresses.
Subject common name fallback can be disabled with
SSLContext.hostname_checks_common_name.

@item 
bpo-14976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14976}: Add a queue.SimpleQueue class, an unbounded FIFO queue with a
reentrant C implementation of put().
@end itemize

@node Documentation<32>,Tests<32>,Library<43>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id314}@anchor{1209}
@subsubsection Documentation



@itemize -

@item 
bpo-32724@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32724}: Add references to some commands in the documentation of Pdb.
Patch by Stéphane Wirtel

@item 
bpo-32649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32649}: Complete the C API documentation, profiling and tracing part
with the newly added per-opcode events.

@item 
bpo-17799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17799}: Explain real behaviour of sys.settrace and sys.setprofile and
their C-API counterparts regarding which type of events are received in
each function. Patch by Pablo Galindo Salgado.
@end itemize

@node Tests<32>,Build<31>,Documentation<32>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id315}@anchor{120a}
@subsubsection Tests



@itemize -

@item 
bpo-32721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32721}: Fix test_hashlib to not fail if the _md5 module is not built.

@item 
bpo-28414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28414}: Add test cases for IDNA 2003 and 2008 host names. IDNA 2003
internationalized host names are working since bpo-31399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31399} has landed. IDNA
2008 are still broken.

@item 
bpo-32604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32604}: Add a new "_xxsubinterpreters" extension module that exposes
the existing subinterpreter C-API and a new cross-interpreter data sharing
mechanism. The module is primarily intended for more thorough testing of
the existing subinterpreter support. Note that the _xxsubinterpreters
module has been removed in 3.7.0rc1.

@item 
bpo-32602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32602}: Add test certs and test for ECDSA cert and EC/RSA dual mode.

@item 
bpo-32549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32549}: On Travis CI, Python now Compiles and uses a local copy of
OpenSSL 1.1.0g for testing.
@end itemize

@node Build<31>,Windows<33>,Tests<32>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id316}@anchor{120b}
@subsubsection Build



@itemize -

@item 
bpo-32635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32635}: Fix segfault of the crypt module when libxcrypt is provided
instead of libcrypt at the system.

@item 
bpo-32598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32598}: Use autoconf to detect OpenSSL libs, headers and supported
features. The ax_check_openssl M4 macro uses pkg-config to locate OpenSSL
and falls back to manual search.

@item 
bpo-32593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32593}: Drop support of FreeBSD 9 and older.

@item 
bpo-29708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29708}: If the 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} environment variable is set,
@ref{d7,,py_compile} will always create hash-based @code{.pyc} files.
@end itemize

@node Windows<33>,macOS<28>,Build<31>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id317}@anchor{120c}
@subsubsection Windows



@itemize -

@item 
bpo-32588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32588}: Create standalone _distutils_findvs module and add missing
_queue module to installer.

@item 
bpo-29911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29911}: Ensure separate Modify and Uninstall buttons are displayed.

@item 
bpo-32507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32507}: Use app-local UCRT install rather than the proper update for
old versions of Windows.
@end itemize

@node macOS<28>,C API<23>,Windows<33>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id318}@anchor{120d}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Provide an additional, more modern macOS installer variant that
supports macOS 10.9+ systems in 64-bit mode only.  Upgrade the supplied
third-party libraries to OpenSSL 1.1.0g and to SQLite 3.22.0.  The 10.9+
installer now links with and supplies its own copy of Tcl/Tk 8.6.

@item 
bpo-28440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28440}: No longer add /Library/Python/3.x/site-packages to sys.path for
macOS framework builds to avoid future conflicts.
@end itemize

@node C API<23>,,macOS<28>,Python 3 7 0 beta 1
@anchor{whatsnew/changelog id319}@anchor{120e}
@subsubsection C API



@itemize -

@item 
bpo-32681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32681}: Fix uninitialized variable 'res' in the C implementation of
os.dup2. Patch by Stéphane Wirtel

@item 
bpo-10381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10381}: Add C API access to the @code{datetime.timezone} constructor and
@code{datetime.timzone.UTC} singleton.
@end itemize

@node Python 3 7 0 alpha 4,Python 3 7 0 alpha 3,Python 3 7 0 beta 1,更新日志
@anchor{whatsnew/changelog python-3-7-0-alpha-4}@anchor{120f}
@subsection Python 3.7.0 alpha 4


@emph{Release date: 2018-01-08}

@menu
* Core and Builtins: Core and Builtins<41>. 
* Library: Library<44>. 
* Documentation: Documentation<33>. 
* Tests: Tests<33>. 
* Windows: Windows<34>. 
* Tools/Demos: Tools/Demos<16>. 
* C API: C API<24>. 

@end menu

@node Core and Builtins<41>,Library<44>,,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id320}@anchor{1210}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31975}: The default warning filter list now starts with a
"default::DeprecationWarning:__main__" entry, so deprecation warnings are
once again shown by default in single-file scripts and at the interactive
prompt.

@item 
bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226}: @code{__class_getitem__} is now an automatic class method.

@item 
bpo-32399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32399}: Add AIX uuid library support for RFC4122 using uuid_create() in
libc.a

@item 
bpo-32390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32390}: Fix the compilation failure on AIX after the f_fsid field has
been added to the object returned by os.statvfs() (bpo-32143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32143}). Original
patch by Michael Felt.

@item 
bpo-32379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32379}: Make MRO computation faster when a class inherits from a single
base.

@item 
bpo-32259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32259}: The error message of a TypeError raised when unpack
non-iterable is now more specific.

@item 
bpo-27169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27169}: The @code{__debug__} constant is now optimized out at compile
time. This fixes also bpo-22091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22091}.

@item 
bpo-32329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32329}: The @ref{1211,,-R} option now turns on hash randomization when
the 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} environment variable is set to @code{0}.
Previously, the option was ignored. Moreover,
@code{sys.flags.hash_randomization} is now properly set to 0 when hash
randomization is turned off by @code{PYTHONHASHSEED=0}.

@item 
bpo-30416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30416}: The optimizer is now protected from spending much time doing
complex calculations and consuming much memory for creating large
constants in constant folding. Increased limits for constants that can be
produced in constant folding.

@item 
bpo-32282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32282}: Fix an unnecessary ifdef in the include of VersionHelpers.h in
socketmodule on Windows.

@item 
bpo-30579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30579}: Implement TracebackType.__new__ to allow Python-level creation
of traceback objects, and make TracebackType.tb_next mutable.

@item 
bpo-32260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32260}: Don't byte swap the input keys to the SipHash algorithm on
big-endian platforms. This should ensure siphash gives consistent results
across platforms.

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Improve the error message logic for object.__new__ and
object.__init__. Patch by Sanyam Khurana.

@item 
bpo-20361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20361}: @code{-b} and @code{-bb} now inject @code{'default::BytesWarning'} and
@code{error::BytesWarning} entries into @code{sys.warnoptions}, ensuring that
they take precedence over any other warning filters configured via the
@code{-W} option or the @code{PYTHONWARNINGS} environment variable.

@item 
bpo-32230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32230}: @code{-X dev} now injects a @code{'default'} entry into
sys.warnoptions, ensuring that it behaves identically to actually passing
@code{-Wdefault} at the command line.

@item 
bpo-29240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29240}: Add a new UTF-8 mode: implementation of the 
@geindex Python 提高建议; PEP 540
PEP 540@footnote{https://www.python.org/dev/peps/pep-0540}.

@item 
bpo-32226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32226}: 
@geindex Python 提高建议; PEP 560
PEP 560@footnote{https://www.python.org/dev/peps/pep-0560}: Add support for @code{__mro_entries__} and
@code{__class_getitem__}. Implemented by Ivan Levkivskyi.

@item 
bpo-32225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32225}: 
@geindex Python 提高建议; PEP 562
PEP 562@footnote{https://www.python.org/dev/peps/pep-0562}: Add support for module @code{__getattr__} and
@code{__dir__}. Implemented by Ivan Levkivskyi.

@item 
bpo-31901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31901}: The @ref{b,,atexit} module now has its callback stored per
interpreter.

@item 
bpo-31650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31650}: Implement 
@geindex Python 提高建议; PEP 552
PEP 552@footnote{https://www.python.org/dev/peps/pep-0552} (Deterministic pycs). Python now supports
invalidating bytecode cache files bashed on a source content hash rather
than source last-modified time.

@item 
bpo-29469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29469}: Move constant folding from bytecode layer to AST layer.
Original patch by Eugene Toder.
@end itemize

@node Library<44>,Documentation<33>,Core and Builtins<41>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id321}@anchor{1212}
@subsubsection Library



@itemize -

@item 
bpo-32506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32506}: Now that dict is defined as keeping insertion order, drop
OrderedDict and just use plain dict.

@item 
bpo-32279@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32279}: Add params to dataclasses.make_dataclasses(): init, repr, eq,
order, hash, and frozen.  Pass them through to dataclass().

@item 
bpo-32278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32278}: Make type information optional on dataclasses.make_dataclass().
If omitted, the string 'typing.Any' is used.

@item 
bpo-32499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32499}: Add dataclasses.is_dataclass(obj), which returns True if obj is
a dataclass or an instance of one.

@item 
bpo-32468@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32468}: Improve frame repr() to mention filename, code name and current
line number.

@item 
bpo-23749@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23749}: asyncio: Implement loop.start_tls()

@item 
bpo-32441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32441}: Return the new file descriptor (i.e., the second argument) from
@code{os.dup2}. Previously, @code{None} was always returned.

@item 
bpo-32422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32422}: @code{functools.lru_cache} uses less memory (3 words for each
cached key) and takes about 1/3 time for cyclic GC.

@item 
bpo-31721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31721}: Prevent Python crash from happening when Future._log_traceback
is set to True manually.  Now it can only be set to False, or a ValueError
is raised.

@item 
bpo-32415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32415}: asyncio: Add Task.get_loop() and Future.get_loop()

@item 
bpo-26133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26133}: Don't unsubscribe signals in asyncio UNIX event loop on
interpreter shutdown.

@item 
bpo-32363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32363}: Make asyncio.Task.set_exception() and set_result() raise
NotImplementedError. Task._step() and Future.__await__() raise proper
exceptions when they are in an invalid state, instead of raising an
AssertionError.

@item 
bpo-32357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32357}: Optimize asyncio.iscoroutine() and loop.create_task() for
non-native coroutines (e.g. async/await compiled with Cython).
'loop.create_task(python_coroutine)' used to be 20% faster than
'loop.create_task(cython_coroutine)'.  Now, the latter is as fast.

@item 
bpo-32356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32356}: asyncio.transport.resume_reading() and pause_reading() are now
idempotent. New transport.is_reading() method is added.

@item 
bpo-32355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32355}: Optimize asyncio.gather(); now up to 15% faster.

@item 
bpo-32351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32351}: Use fastpath in asyncio.sleep if delay<0 (2x boost)

@item 
bpo-32348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32348}: Optimize asyncio.Future schedule/add/remove callback.  The
optimization shows 3-6% performance improvements of async/await code.

@item 
bpo-32331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32331}: Fix socket.settimeout() and socket.setblocking() to keep
socket.type as is. Fix socket.socket() constructor to reset any bit flags
applied to socket's type.  This change only affects OSes that have
SOCK_NONBLOCK and/or SOCK_CLOEXEC.

@item 
bpo-32248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32248}: Add @ref{457,,importlib.abc.ResourceReader} as an ABC for loaders
to provide a unified API for reading resources contained within packages.
Also add @ref{9e,,importlib.resources} as the port of
@code{importlib_resources}.

@item 
bpo-32311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32311}: Implement asyncio.create_task(coro) shortcut

@item 
bpo-32327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32327}: Convert asyncio functions that were documented as coroutines to
coroutines. Affected functions: loop.sock_sendall, loop.sock_recv,
loop.sock_accept, loop.getaddrinfo, loop.getnameinfo.

@item 
bpo-32323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32323}: @ref{6fa,,urllib.parse.urlsplit()} does not convert zone-id
(scope) to lower case for scoped IPv6 addresses in hostnames now.

@item 
bpo-32302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32302}: Fix bdist_wininst of distutils for CRT v142: it binary
compatible with CRT v140.

@item 
bpo-29711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29711}: Fix @code{stop_serving} in asyncio proactor loop kill all
listening servers

@item 
bpo-32308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32308}: @ref{582,,re.sub()} now replaces empty matches adjacent to a
previous non-empty match.

@item 
bpo-29970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29970}: Abort asyncio SSLProtocol connection if handshake not complete
within 10s

@item 
bpo-32314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32314}: Implement asyncio.run().

@item 
bpo-17852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17852}: Revert incorrect fix based on misunderstanding of
_Py_PyAtExit() semantics.

@item 
bpo-32296@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32296}: Implement asyncio._get_running_loop() and get_event_loop() in
C. This makes them 4x faster.

@item 
bpo-32250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32250}: Implement @code{asyncio.current_task()} and
@code{asyncio.all_tasks()}. Add helpers intended to be used by alternative
task implementations: @code{asyncio._register_task}, @code{asyncio._enter_task},
@code{asyncio._leave_task} and @code{asyncio._unregister_task}. Deprecate
@code{asyncio.Task.current_task()} and @code{asyncio.Task.all_tasks()}.

@item 
bpo-32255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32255}: A single empty field is now always quoted when written into a
CSV file. This allows to distinguish an empty row from a row consisting of
a single empty field. Patch by Licht Takeuchi.

@item 
bpo-32277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32277}: Raise @code{NotImplementedError} instead of @code{SystemError} on
platforms where @code{chmod(..., follow_symlinks=False)} is not supported.
Patch by Anthony Sottile.

@item 
bpo-30050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30050}: New argument warn_on_full_buffer to signal.set_wakeup_fd lets
you control whether Python prints a warning on stderr when the wakeup fd
buffer overflows.

@item 
bpo-29137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29137}: The @code{fpectl} library has been removed. It was never enabled
by default, never worked correctly on x86-64, and it changed the Python
ABI in ways that caused unexpected breakage of C extensions.

@item 
bpo-32273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32273}: Move asyncio.test_utils to test.test_asyncio.

@item 
bpo-32272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32272}: Remove asyncio.async() function.

@item 
bpo-32269@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32269}: Add asyncio.get_running_loop() function.

@item 
bpo-32265@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32265}: All class and static methods of builtin types now are correctly
classified by inspect.classify_class_attrs() and grouped in pydoc ouput.
Added types.ClassMethodDescriptorType for unbound class methods of builtin
types.

@item 
bpo-32253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32253}: Deprecate @code{yield from lock}, @code{await lock}, @code{with (yield
from lock)} and @code{with await lock} for asyncio synchronization
primitives.

@item 
bpo-22589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22589}: Changed MIME type of .bmp from 'image/x-ms-bmp' to 'image/bmp'

@item 
bpo-32193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32193}: Convert asyncio to use @emph{async/await} syntax. Old styled @code{yield
from} is still supported too.

@item 
bpo-32206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32206}: Add support to run modules with pdb

@item 
bpo-32227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32227}: @code{functools.singledispatch} now supports registering
implementations using type annotations.

@item 
bpo-15873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15873}: Added new alternate constructors
@ref{48f,,datetime.datetime.fromisoformat()},
@ref{1213,,datetime.time.fromisoformat()} and
@ref{1214,,datetime.date.fromisoformat()} as the inverse operation of each
classes's respective @code{isoformat} methods.

@item 
bpo-32199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32199}: The getnode() ip getter now uses 'ip link' instead of 'ip link
list'.

@item 
bpo-32143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32143}: os.statvfs() includes the f_fsid field from statvfs(2)

@item 
bpo-26439@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26439}: Fix ctypes.util.find_library() for AIX by implementing
ctypes._aix.find_library() Patch by: Michael Felt

@item 
bpo-31993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31993}: The pickler now uses less memory when serializing large bytes
and str objects into a file.  Pickles created with protocol 4 will require
less memory for unpickling large bytes and str objects.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

@item 
bpo-31778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31778}: ast.literal_eval() is now more strict. Addition and subtraction
of arbitrary numbers no longer allowed.

@item 
bpo-31802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31802}: Importing native path module (@code{posixpath}, @code{ntpath}) now
works even if the @code{os} module still is not imported.

@item 
bpo-30241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30241}: Add contextlib.AbstractAsyncContextManager. Patch by Jelle
Zijlstra.

@item 
bpo-31699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31699}: Fix deadlocks in
@ref{196,,concurrent.futures.ProcessPoolExecutor} when task arguments or
results cause pickling or unpickling errors. This should make sure that
calls to the @code{ProcessPoolExecutor} API always eventually return.

@item 
bpo-15216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15216}: @code{TextIOWrapper.reconfigure()} supports changing @emph{encoding},
@emph{errors}, and @emph{newline}.
@end itemize

@node Documentation<33>,Tests<33>,Library<44>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id322}@anchor{1215}
@subsubsection Documentation



@itemize -

@item 
bpo-32418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32418}: Add get_loop() method to Server and AbstractServer classes.
@end itemize

@node Tests<33>,Windows<34>,Documentation<33>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id323}@anchor{1216}
@subsubsection Tests



@itemize -

@item 
bpo-32252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32252}: Fix faulthandler_suppress_crash_report() used to prevent core
dump files when testing crashes. getrlimit() returns zero on success.

@item 
bpo-32002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32002}: Adjust C locale coercion testing for the empty locale and POSIX
locale cases to more readily adjust to platform dependent behaviour.
@end itemize

@node Windows<34>,Tools/Demos<16>,Tests<33>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id324}@anchor{1217}
@subsubsection Windows



@itemize -

@item 
bpo-19764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19764}: Implement support for @code{subprocess.Popen(close_fds=True)} on
Windows. Patch by Segev Finer.
@end itemize

@node Tools/Demos<16>,C API<24>,Windows<34>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id325}@anchor{1218}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24960}: 2to3 and lib2to3 can now read pickled grammar files using
pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and
lib2to3 work when run from a zipfile.
@end itemize

@node C API<24>,,Tools/Demos<16>,Python 3 7 0 alpha 4
@anchor{whatsnew/changelog id326}@anchor{1219}
@subsubsection C API



@itemize -

@item 
bpo-32030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32030}: Py_Initialize() doesn't reset the memory allocators to default
if the @code{PYTHONMALLOC} environment variable is not set.

@item 
bpo-29084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29084}: Undocumented C API for OrderedDict has been excluded from the
limited C API. It was added by mistake and actually never worked in the
limited C API.

@item 
bpo-32264@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32264}: Moved the pygetopt.h header into internal/, since it has no
public APIs.

@item 
bpo-32241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32241}: @ref{113b,,Py_SetProgramName()} and @ref{113a,,Py_SetPythonHome()} now
take the @code{const wchar *} arguments instead of @code{wchar *}.
@end itemize

@node Python 3 7 0 alpha 3,Python 3 7 0 alpha 2,Python 3 7 0 alpha 4,更新日志
@anchor{whatsnew/changelog python-3-7-0-alpha-3}@anchor{121a}
@subsection Python 3.7.0 alpha 3


@emph{Release date: 2017-12-05}

@menu
* Core and Builtins: Core and Builtins<42>. 
* Library: Library<45>. 
* Documentation: Documentation<34>. 
* Tests: Tests<34>. 
* Build: Build<32>. 
* Windows: Windows<35>. 
* macOS: macOS<29>. 
* IDLE: IDLE<31>. 
* Tools/Demos: Tools/Demos<17>. 
* C API: C API<25>. 

@end menu

@node Core and Builtins<42>,Library<45>,,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id327}@anchor{121b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32176}: co_flags.CO_NOFREE is now always set correctly by the code
object constructor based on freevars and cellvars, rather than needing to
be set correctly by the caller. This ensures it will be cleared
automatically when additional cell references are injected into a modified
code object and function.

@item 
bpo-10544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10544}: Yield expressions are now deprecated in comprehensions and
generator expressions. They are still permitted in the definition of the
outermost iterable, as that is evaluated directly in the enclosing scope.

@item 
bpo-32137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32137}: The repr of deeply nested dict now raises a RecursionError
instead of crashing due to a stack overflow.

@item 
bpo-32096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32096}: Revert memory allocator changes in the C API: move structures
back from _PyRuntime to Objects/obmalloc.c. The memory allocators are once
again initialized statically, and so PyMem_RawMalloc() and
Py_DecodeLocale() can be called before _PyRuntime_Initialize().

@item 
bpo-32043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32043}: Add a new "developer mode": new "-X dev" command line option to
enable debug checks at runtime.

@item 
bpo-32023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32023}: SyntaxError is now correctly raised when a generator expression
without parenthesis is used instead of an inheritance list in a class
definition. The duplication of the parentheses can be omitted only on
calls.

@item 
bpo-32012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32012}: SyntaxError is now correctly raised when a generator expression
without parenthesis is passed as an argument, but followed by a trailing
comma. A generator expression always needs to be directly inside a set of
parentheses and cannot have a comma on either side.

@item 
bpo-28180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28180}: A new internal @code{_Py_SetLocaleFromEnv(category)} helper
function has been added in order to improve the consistency of behaviour
across different @code{libc} implementations (e.g. Android doesn't support
setting the locale from the environment by default).

@item 
bpo-31949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31949}: Fixed several issues in printing tracebacks
(PyTraceBack_Print()). Setting sys.tracebacklimit to 0 or less now
suppresses printing tracebacks. Setting sys.tracebacklimit to None now
causes using the default limit. Setting sys.tracebacklimit to an integer
larger than LONG_MAX now means using the limit LONG_MAX rather than the
default limit. Fixed integer overflows in the case of more than @code{2**31}
traceback items on Windows. Fixed output errors handling.

@item 
bpo-30696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30696}: Fix the interactive interpreter looping endlessly when no
memory.

@item 
bpo-20047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20047}: Bytearray methods partition() and rpartition() now accept only
bytes-like objects as separator, as documented.  In particular they now
raise TypeError rather of returning a bogus result when an integer is
passed as a separator.

@item 
bpo-21720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21720}: BytesWarning no longer emitted when the @emph{fromlist} argument of
@code{__import__()} or the @code{__all__} attribute of the module contain bytes
instances.

@item 
bpo-31845@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31845}: Environment variables are once more read correctly at
interpreter startup.

@item 
bpo-28936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28936}: Ensure that lexically first syntax error involving a parameter
and @code{global} or @code{nonlocal} is detected first at a given scope. Patch
by Ivan Levkivskyi.

@item 
bpo-31825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31825}: Fixed OverflowError in the 'unicode-escape' codec and in
codecs.escape_decode() when decode an escaped non-ascii byte.

@item 
bpo-31618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31618}: The per-frame tracing logic added in 3.7a1 has been altered so
that @code{frame->f_lineno} is updated before either @code{"line"} or
@code{"opcode"} events are emitted. Previously, opcode events were emitted
first, and therefore would occasionally see stale line numbers on the
frame. The behavior of this feature has changed slightly as a result: when
both @code{f_trace_lines} and @code{f_trace_opcodes} are enabled, line events
now occur first.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Print the full context/cause chain of exceptions on interpreter
exit, even if an exception in the chain is unhashable or compares equal to
later ones. Patch by Zane Bitter.

@item 
bpo-31786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31786}: Fix timeout rounding in the select module to round correctly
negative timeouts between -1.0 and 0.0. The functions now block waiting
for events as expected. Previously, the call was incorrectly non-blocking.
Patch by Pablo Galindo.

@item 
bpo-31781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31781}: Prevent crashes when calling methods of an uninitialized
@code{zipimport.zipimporter} object. Patch by Oren Milman.

@item 
bpo-30399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30399}: Standard repr() of BaseException with a single argument no
longer contains redundant trailing comma.

@item 
bpo-31626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31626}: Fixed a bug in debug memory allocator.  There was a write to
freed memory after shrinking a memory block.

@item 
bpo-30817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30817}: @code{PyErr_PrintEx()} clears now the ignored exception that may be
raised by @code{_PySys_SetObjectId()}, for example when no memory.
@end itemize

@node Library<45>,Documentation<34>,Core and Builtins<42>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id328}@anchor{121c}
@subsubsection Library



@itemize -

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Two minor fixes for @code{typing} module: allow shallow copying
instances of generic classes, improve interaction of @code{__init_subclass__}
with generics. Original PRs by Ivan Levkivskyi.

@item 
bpo-32214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32214}: PEP 557, Data Classes. Provides a decorator which adds
boilerplate methods to classes which use type annotations so specify
fields.

@item 
bpo-27240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27240}: The header folding algorithm for the new email policies has
been rewritten, which also fixes bpo-30788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30788}, bpo-31831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31831}, and bpo-32182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32182}.  In
particular, RFC2231 folding is now done correctly.

@item 
bpo-32186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32186}: io.FileIO.readall() and io.FileIO.read() now release the GIL
when getting the file size. Fixed hang of all threads with inaccessible
NFS server. Patch by Nir Soffer.

@item 
bpo-32101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32101}: Add @code{sys.flags.dev_mode} flag

@item 
bpo-32154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32154}: The @code{asyncio.windows_utils.socketpair()} function has been
removed: use directly @ref{585,,socket.socketpair()} which is available on all
platforms since Python 3.5 (before, it wasn't available on Windows).
@code{asyncio.windows_utils.socketpair()} was just an alias to
@code{socket.socketpair} on Python 3.5 and newer.

@item 
bpo-32089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32089}: warnings: In development (-X dev) and debug mode (pydebug
build), use the "default" action for ResourceWarning, rather than the
"always" action, in the default warnings filters.

@item 
bpo-32107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32107}: @code{uuid.getnode()} now preferentially returns universally
administered MAC addresses if available, over locally administered MAC
addresses.  This makes a better guarantee for global uniqueness of UUIDs
returned from @code{uuid.uuid1()}.  If only locally administered MAC
addresses are available, the first such one found is returned.

@item 
bpo-23033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23033}: Wildcard is now supported in hostname when it is one and only
character in the left most segment of hostname in second argument of
@ref{4eb,,ssl.match_hostname()}.  Patch by Mandeep Singh.

@item 
bpo-12239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12239}: Make @ref{1147,,msilib.SummaryInformation.GetProperty()} return
@code{None} when the value of property is @code{VT_EMPTY}.  Initial patch by
Mark Mc Mahon.

@item 
bpo-28334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28334}: Use @ref{333,,os.path.expanduser()} to find the @code{~/.netrc} file in
@ref{121d,,netrc.netrc}.  If it does not exist, @ref{8b7,,FileNotFoundError} is
raised.  Patch by Dimitri Merejkowsky.

@item 
bpo-32121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32121}: Made @code{tracemalloc.Traceback} behave more like the traceback
module, sorting the frames from oldest to most recent.
@code{Traceback.format()} now accepts negative @emph{limit}, truncating the result
to the @code{abs(limit)} oldest frames. To get the old behaviour, one can use
the new @emph{most_recent_first} argument to @code{Traceback.format()}. (Patch by
Jesse Bakker.)

@item 
bpo-31325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31325}: Fix wrong usage of @ref{1a1,,collections.namedtuple()} in the
@ref{121e,,RobotFileParser.parse()}
method. Initial patch by Robin Wellner.

@item 
bpo-12382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12382}: @ref{106a,,msilib.OpenDatabase()} now raises a better exception
message when it couldn't open or create an MSI file.  Initial patch by
William Tisäter.

@item 
bpo-19610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19610}: @code{setup()} now warns about invalid types for some fields. The
@code{distutils.dist.Distribution} class now warns when @code{classifiers},
@code{keywords} and @code{platforms} fields are not specified as a list or a
string.

@item 
bpo-32071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32071}: Added the @code{-k} command-line option to @code{python -m unittest}
to run only tests that match the given pattern(s).

@item 
bpo-10049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10049}: Added @emph{nullcontext} no-op context manager to contextlib. This
provides a simpler and faster alternative to ExitStack() when handling
optional context managers.

@item 
bpo-28684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28684}: The new test.support.skip_unless_bind_unix_socket() decorator
is used here to skip asyncio tests that fail because the platform lacks a
functional bind() function for unix domain sockets (as it is the case for
non root users on the recent Android versions that run now SELinux in
enforcing mode).

@item 
bpo-32110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32110}: @code{codecs.StreamReader.read(n)} now returns not more than @emph{n}
characters/bytes for non-negative @emph{n}. This makes it compatible with
@code{read()} methods of other file-like objects.

@item 
bpo-27535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27535}: The warnings module doesn't leak memory anymore in the hidden
warnings registry for the "ignore" action of warnings filters.
warn_explicit() function doesn't add the warning key to the registry
anymore for the "ignore" action.

@item 
bpo-32088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32088}: warnings:  When Python is build is debug mode (@code{Py_DEBUG}),
@ref{15a,,DeprecationWarning}, @ref{15c,,PendingDeprecationWarning} and
@ref{6d9,,ImportWarning} warnings are now displayed by default.

@item 
bpo-1647489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1647489}: Fixed searching regular expression patterns that could match
an empty string. Non-empty string can now be correctly found after
matching an empty string.

@item 
bpo-25054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25054}: Added support of splitting on a pattern that could match an
empty string.

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-32069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32069}: Drop legacy SSL transport from asyncio, ssl.MemoryBIO is always
used anyway.

@item 
bpo-32066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32066}: asyncio: Support pathlib.Path in create_unix_connection; sock
arg should be optional

@item 
bpo-32046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32046}: Updates 2to3 to convert from operator.isCallable(obj) to
callable(obj). Patch by Dong-hee Na.

@item 
bpo-32018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32018}: inspect.signature should follow 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008}, if the parameter has
an annotation and a default value. Patch by Dong-hee Na.

@item 
bpo-32025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32025}: Add time.thread_time() and time.thread_time_ns()

@item 
bpo-32037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32037}: Integers that fit in a signed 32-bit integer will be now
pickled with protocol 0 using the INT opcode.  This will decrease the size
of a pickle, speed up pickling and unpickling, and make these integers be
unpickled as int instances in Python 2.

@item 
bpo-32034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32034}: Make asyncio.IncompleteReadError and LimitOverrunError
pickleable.

@item 
bpo-32015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32015}: Fixed the looping of asyncio in the case of reconnection the
socket during waiting async read/write from/to the socket.

@item 
bpo-32011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32011}: Restored support of loading marshal files with the TYPE_INT64
code. These files can be produced in Python 2.7.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Enhance add_reader/writer check that socket is not used by some
transport. Before, only cases when add_reader/writer were called with an
int FD were supported.  Now the check is implemented correctly for all
file-like objects.

@item 
bpo-31976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31976}: Fix race condition when flushing a file is slow, which can
cause a segfault if closing the file from another thread.

@item 
bpo-31985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31985}: Formally deprecated aifc.openfp, sunau.openfp, and wave.openfp.
Since change 7bc817d5ba917528e8bd07ec461c635291e7b06a in 1993, openfp in
each of the three modules had been pointing to that module's open function
as a matter of backwards compatibility, though it had been both untested
and undocumented.

@item 
bpo-21862@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21862}: cProfile command line now accepts @code{-m module_name} as an
alternative to script path. Patch by Sanyam Khurana.

@item 
bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970}: Reduce performance overhead of asyncio debug mode.

@item 
bpo-31843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31843}: @emph{database} argument of sqlite3.connect() now accepts a
@ref{47b,,path-like object}, instead of just a string.

@item 
bpo-31945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31945}: Add Configurable @emph{blocksize} to @code{HTTPConnection} and
@code{HTTPSConnection} for improved upload throughput.  Patch by Nir Soffer.

@item 
bpo-31943@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31943}: Add a @code{cancelled()} method to @ref{121f,,asyncio.Handle}.  Patch
by Marat Sharafutdinov.

@item 
bpo-9678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9678}: Fixed determining the MAC address in the uuid module: Using
ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD, NetBSD and
OpenBSD. Based on patch by Takayuki Shimizukawa.

@item 
bpo-30057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30057}: Fix potential missed signal in signal.signal().

@item 
bpo-31933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31933}: Fix Blake2 params leaf_size and node_offset on big endian
platforms. Patch by Jack O'Connor.

@item 
bpo-21423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21423}: Add an initializer argument to @{Process,Thread@}PoolExecutor

@item 
bpo-31927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31927}: Fixed compilation of the socket module on NetBSD 8.  Fixed
assertion failure or reading arbitrary data when parse a AF_BLUETOOTH
address on NetBSD and DragonFly BSD.

@item 
bpo-27666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27666}: Fixed stack corruption in curses.box() and curses.ungetmouse()
when the size of types chtype or mmask_t is less than the size of C long.
curses.box() now accepts characters as arguments.  Based on patch by Steve
Fink.

@item 
bpo-31917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31917}: Add 3 new clock identifiers: @ref{503,,time.CLOCK_BOOTTIME},
@ref{505,,time.CLOCK_PROF} and @ref{506,,time.CLOCK_UPTIME}.

@item 
bpo-31897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31897}: plistlib now catches more errors when read binary plists and
raises InvalidFileException instead of unexpected exceptions.

@item 
bpo-25720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25720}: Fix the method for checking pad state of curses WINDOW. Patch
by Masayuki Yamamoto.

@item 
bpo-31893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31893}: Fixed the layout of the kqueue_event structure on OpenBSD and
NetBSD. Fixed the comparison of the kqueue_event objects.

@item 
bpo-31891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31891}: Fixed building the curses module on NetBSD.

@item 
bpo-31884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31884}: added required constants to subprocess module for setting
priority on windows

@item 
bpo-28281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28281}: Remove year (1-9999) limits on the Calendar.weekday() function.
Patch by Mark Gollahon.

@item 
bpo-31702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31702}: crypt.mksalt() now allows to specify the number of rounds for
SHA-256 and SHA-512 hashing.

@item 
bpo-30639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30639}: @ref{1220,,inspect.getfile()} no longer computes the repr of unknown
objects to display in an error message, to protect against badly behaved
custom reprs.

@item 
bpo-30768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30768}: Fix the pthread+semaphore implementation of
PyThread_acquire_lock_timed() when called with timeout > 0 and
intr_flag=0: recompute the timeout if sem_timedwait() is interrupted by a
signal (EINTR). See also the 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}.

@item 
bpo-31854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31854}: Add @code{mmap.ACCESS_DEFAULT} constant.

@item 
bpo-31834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31834}: Use optimized code for BLAKE2 only with SSSE3+. The pure SSE2
implementation is slower than the pure C reference implementation.

@item 
bpo-28292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28292}: Calendar.itermonthdates() will now consistently raise an
exception when a date falls outside of the 0001-01-01 through 9999-12-31
range.  To support applications that cannot tolerate such exceptions, the
new methods itermonthdays3() and itermonthdays4() are added.  The new
methods return tuples and are not restricted by the range supported by
datetime.date.

@item 
bpo-28564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28564}: The shutil.rmtree() function has been sped up to 20--40%. This
was done using the os.scandir() function.

@item 
bpo-28416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28416}: Instances of pickle.Pickler subclass with the persistent_id()
method and pickle.Unpickler subclass with the persistent_load() method no
longer create reference cycles.

@item 
bpo-31653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31653}: Don't release the GIL if we can acquire a multiprocessing
semaphore immediately.

@item 
bpo-28326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28326}: Fix multiprocessing.Process when stdout and/or stderr is closed
or None.

@item 
bpo-20825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20825}: Add @code{subnet_of} and @code{superset_of} containment tests to
@ref{4ae,,ipaddress.IPv6Network} and @ref{4af,,ipaddress.IPv4Network}. Patch
by Michel Albert and Cheryl Sabella.

@item 
bpo-31827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31827}: Remove the os.stat_float_times() function. It was introduced in
Python 2.3 for backward compatibility with Python 2.2, and was deprecated
since Python 3.1.

@item 
bpo-31756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31756}: Add a @code{subprocess.Popen(text=False)} keyword argument to
@ref{f9,,subprocess} functions to be more explicit about when the library should
attempt to decode outputs into text. Patch by Andrew Clegg.

@item 
bpo-31819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31819}: Add AbstractEventLoop.sock_recv_into().

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: The @code{manager} property on LoggerAdapter objects is now
properly settable.

@item 
bpo-31806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31806}: Fix timeout rounding in time.sleep(), threading.Lock.acquire()
and socket.socket.settimeout() to round correctly negative timeouts
between -1.0 and 0.0. The functions now block waiting for events as
expected. Previously, the call was incorrectly non-blocking. Patch by
Pablo Galindo.

@item 
bpo-31803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31803}: time.clock() and time.get_clock_info('clock') now emit a
DeprecationWarning warning.

@item 
bpo-31800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31800}: Extended support for parsing UTC offsets. strptime '%z' can now
parse the output generated by datetime.isoformat, including seconds and
microseconds.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: traceback: Fix a TypeError that occurred during printing of
exception tracebacks when either the current exception or an exception in
its context/cause chain is unhashable. Patch by Zane Bitter.

@item 
bpo-30541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30541}: Add new function to seal a mock and prevent the automatically
creation of child mocks. Patch by Mario Corchero.

@item 
bpo-31784@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31784}: Implement the 
@geindex Python 提高建议; PEP 564
PEP 564@footnote{https://www.python.org/dev/peps/pep-0564}, add new 6 new functions with
nanosecond resolution to the @ref{10c,,time} module:
@ref{437,,clock_gettime_ns()}, @ref{438,,clock_settime_ns()},
@ref{439,,monotonic_ns()}, @ref{43a,,perf_counter_ns()},
@ref{43b,,process_time_ns()}, @ref{43c,,time_ns()}.

@item 
bpo-30143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30143}: 2to3 now generates a code that uses abstract collection classes
from collections.abc rather than collections.

@item 
bpo-31770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31770}: Prevent a crash when calling the @code{__init__()} method of a
@code{sqlite3.Cursor} object more than once. Patch by Oren Milman.

@item 
bpo-31764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31764}: Prevent a crash in @code{sqlite3.Cursor.close()} in case the
@code{Cursor} object is uninitialized. Patch by Oren Milman.

@item 
bpo-31752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31752}: Fix possible crash in timedelta constructor called with custom
integers.

@item 
bpo-31620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31620}: an empty asyncio.Queue now doesn't leak memory when queue.get
pollers timeout

@item 
bpo-31690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31690}: Allow the flags re.ASCII, re.LOCALE, and re.UNICODE to be used
as group flags for regular expressions.

@item 
bpo-30349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30349}: FutureWarning is now emitted if a regular expression contains
character set constructs that will change semantically in the future
(nested sets and set operations).

@item 
bpo-31664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31664}: Added support for the Blowfish hashing in the crypt module.

@item 
bpo-31632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31632}: Fix method set_protocol() of class _SSLProtocolTransport in
asyncio module. This method was previously modifying a wrong reference to
the protocol.

@item 
bpo-15037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15037}: Added a workaround for getkey() in curses for ncurses 5.7 and
earlier.

@item 
bpo-31307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31307}: Allow use of bytes objects for arguments to
@ref{1221,,configparser.ConfigParser.read()}. Patch by Vincent Michel.

@item 
bpo-31334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31334}: Fix @code{poll.poll([timeout])} in the @code{select} module for
arbitrary negative timeouts on all OSes where it can only be a
non-negative integer or -1. Patch by Riccardo Coccioli.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: multiprocessing's semaphore tracker should be launched again if
crashed.

@item 
bpo-31308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31308}: Make multiprocessing's forkserver process immune to Ctrl-C and
other user interruptions. If it crashes, restart it when necessary.

@item 
bpo-31245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31245}: Added support for AF_UNIX socket in asyncio
@code{create_datagram_endpoint}.

@item 
bpo-30553@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30553}: Add HTTP/2 status code 421 (Misdirected Request) to
@ref{1ac,,http.HTTPStatus}. Patch by Vitor Pereira.
@end itemize

@node Documentation<34>,Tests<34>,Library<45>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id329}@anchor{1222}
@subsubsection Documentation



@itemize -

@item 
bpo-32105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32105}: Added asyncio.BaseEventLoop.connect_accepted_socket
versionadded marker.
@end itemize

@node Tests<34>,Build<32>,Documentation<34>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id330}@anchor{1223}
@subsubsection Tests



@itemize -

@item 
bpo-31380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31380}: Skip test_httpservers test_undecodable_file on macOS: fails on
APFS.

@item 
bpo-31705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31705}: Skip test_socket.test_sha256() on Linux kernel older than 4.5.
The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged
into the kernel 4.5.

@item 
bpo-32138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32138}: Skip on Android test_faulthandler tests that raise SIGSEGV and
remove the test.support.requires_android_level decorator.

@item 
bpo-32136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32136}: The runtime embedding tests have been split out from
@code{Lib/test/test_capi.py} into a new @code{Lib/test/test_embed.py} file.

@item 
bpo-28668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28668}: test.support.requires_multiprocessing_queue is removed. Skip
tests with test.support.import_module('multiprocessing.synchronize')
instead when the semaphore implementation is broken or missing.

@item 
bpo-32126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32126}: Skip test_get_event_loop_new_process in
test.test_asyncio.test_events when sem_open() is not functional.

@item 
bpo-31174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31174}: Fix test_tools.test_unparse: DirectoryTestCase now stores the
names sample to always test the same files. It prevents false alarms when
hunting reference leaks.
@end itemize

@node Build<32>,Windows<35>,Tests<34>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id331}@anchor{1224}
@subsubsection Build



@itemize -

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Revert the previous changes, the if_nameindex structure is
defined by Unified Headers.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: Revert the last commit, the F_LOCK macro is defined by Android
Unified Headers.

@item 
bpo-29040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29040}: Support building Android with Unified Headers. The first NDK
release to support Unified Headers is android-ndk-r14.

@item 
bpo-32059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32059}: @code{detect_modules()} in @code{setup.py} now also searches the
sysroot paths when cross-compiling.

@item 
bpo-31957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31957}: Fixes Windows SDK version detection when building for Windows.

@item 
bpo-31609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31609}: Fixes quotes in PCbuild/clean.bat

@item 
bpo-31934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31934}: Abort the build when building out of a not clean source tree.

@item 
bpo-31926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31926}: Fixed Argument Clinic sometimes causing compilation errors when
there was more than one function and/or method in a .c file with the same
name.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update Windows builds to use SQLite 3.21.0.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update OS X installer to use SQLite 3.21.0.

@item 
bpo-28643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28643}: Record profile-opt build progress with stamp files.

@item 
bpo-31866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31866}: Finish removing support for AtheOS.
@end itemize

@node Windows<35>,macOS<29>,Build<32>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id332}@anchor{1225}
@subsubsection Windows



@itemize -

@item 
bpo-1102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1102}: Return @code{None} when @code{View.Fetch()} returns
@code{ERROR_NO_MORE_ITEMS} instead of raising @code{MSIError}. Initial patch by
Anthony Tuininga.

@item 
bpo-31944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31944}: Fixes Modify button in Apps and Features dialog.

@item 
bpo-20486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20486}: Implement the @code{Database.Close()} method to help closing MSI
database objects.

@item 
bpo-31857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31857}: Make the behavior of USE_STACKCHECK deterministic in a
multi-threaded environment.
@end itemize

@node macOS<29>,IDLE<31>,Windows<35>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id333}@anchor{1226}
@subsubsection macOS



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update macOS installer to use OpenSSL 1.0.2m
@end itemize

@node IDLE<31>,Tools/Demos<17>,macOS<29>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id334}@anchor{1227}
@subsubsection IDLE



@itemize -

@item 
bpo-32207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32207}: Improve tk event exception tracebacks in IDLE. When tk event
handling is driven by IDLE's run loop, a confusing and distracting
queue.EMPTY traceback context is no longer added to tk event exception
tracebacks.  The traceback is now the same as when event handling is
driven by user code.  Patch based on a suggestion by Serhiy Storchaka.

@item 
bpo-32164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32164}: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet
in configdialog was replaced by ttk.Notebook.

@item 
bpo-32100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32100}: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch
mostly by Cheryl Sabella.

@item 
bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}: IDLE -- Restrict shell prompt manipulation to the shell. Editor
and output windows only see an empty last prompt line.  This simplifies
the code and fixes a minor bug when newline is inserted. Sys.ps1, if
present, is read on Shell start-up, but is not set or changed.

@item 
bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}: The font sample in the IDLE configuration dialog is now
editable. Changes persist while IDLE remains open

@item 
bpo-31836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31836}: Test_code_module now passes if run after test_idle, which sets
ps1. The code module uses sys.ps1 if present or sets it to '>>> ' if not.
Test_code_module now properly tests both behaviors.  Ditto for ps2.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Fix a TypeError that caused a shell restart when printing a
traceback that includes an exception that is unhashable. Patch by Zane
Bitter.

@item 
bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}: Use non-Latin characters in the IDLE's Font settings sample.
Even if one selects a font that defines a limited subset of the unicode
Basic Multilingual Plane, tcl/tk will use other fonts that define a
character. The expanded example give users of non-Latin characters a
better idea of what they might see in IDLE's shell and editors. To make
room for the expanded sample, frames on the Font tab are re-arranged.  The
Font/Tabs help explains a bit about the additions.
@end itemize

@node Tools/Demos<17>,C API<25>,IDLE<31>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id335}@anchor{1228}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-32159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32159}: Remove CVS and Subversion tools: remove svneol.py and
treesync.py scripts. CPython migrated from CVS to Subversion, to
Mercurial, and then to Git. CVS and Subversion are no longer used to
develop CPython.

@item 
bpo-30722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30722}: Make redemo work with Python 3.6 and newer versions. Also,
remove the @code{LOCALE} option since it doesn't work with string patterns in
Python 3. Patch by Christoph Sarnowski.
@end itemize

@node C API<25>,,Tools/Demos<17>,Python 3 7 0 alpha 3
@anchor{whatsnew/changelog id336}@anchor{1229}
@subsubsection C API



@itemize -

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in
a non-Python thread before PyEval_InitThreads(), only call
PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

@item 
bpo-32125@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32125}: The @code{Py_UseClassExceptionsFlag} flag has been removed. It was
deprecated and wasn't used anymore since Python 2.0.

@item 
bpo-25612@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25612}: Move the current exception state from the frame object to the
co-routine. This simplifies the interpreter and fixes a couple of obscure
bugs caused by having swap exception state when entering or exiting a
generator.

@item 
bpo-23699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23699}: Add Py_RETURN_RICHCOMPARE macro to reduce boilerplate code in
rich comparison functions.

@item 
bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}: The @code{PyExc_RecursionErrorInst} singleton is removed and
@code{PyErr_NormalizeException()} does not use it anymore. This singleton is
persistent and its members being never cleared may cause a segfault during
finalization of the interpreter. See also bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898}.
@end itemize

@node Python 3 7 0 alpha 2,Python 3 7 0 alpha 1,Python 3 7 0 alpha 3,更新日志
@anchor{whatsnew/changelog python-3-7-0-alpha-2}@anchor{122a}
@subsection Python 3.7.0 alpha 2


@emph{Release date: 2017-10-16}

@menu
* Core and Builtins: Core and Builtins<43>. 
* Library: Library<46>. 
* Documentation: Documentation<35>. 
* Build: Build<33>. 
* IDLE: IDLE<32>. 
* C API: C API<26>. 

@end menu

@node Core and Builtins<43>,Library<46>,,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id337}@anchor{122b}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31558}: @code{gc.freeze()} is a new API that allows for moving all objects
currently tracked by the garbage collector to a permanent generation,
effectively removing them from future collection events. This can be used
to protect those objects from having their PyGC_Head mutated. In effect,
this enables great copy-on-write stability at fork().

@item 
bpo-31642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31642}: Restored blocking "from package import module" by setting
sys.modules["package.module"] to None.

@item 
bpo-31708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31708}: Allow use of asynchronous generator expressions in synchronous
functions.

@item 
bpo-31709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31709}: Drop support of asynchronous __aiter__.

@item 
bpo-30404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30404}: The -u option now makes the stdout and stderr streams
unbuffered rather than line-buffered.

@item 
bpo-31619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31619}: Fixed a ValueError when convert a string with large number of
underscores to integer with binary base.

@item 
bpo-31602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31602}: Fix an assertion failure in @code{zipimporter.get_source()} in case
of a bad @ref{6c0,,zlib.decompress()}. Patch by Oren Milman.

@item 
bpo-31592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31592}: Fixed an assertion failure in Python parser in case of a bad
@ref{122c,,unicodedata.normalize()}. Patch by Oren Milman.

@item 
bpo-31588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31588}: Raise a @ref{1ff,,TypeError} with a helpful error message when class
creation fails due to a metaclass with a bad @code{__prepare__()} method.
Patch by Oren Milman.

@item 
bpo-31574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31574}: Importlib was instrumented with two dtrace probes to profile
import timing.

@item 
bpo-31566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31566}: Fix an assertion failure in @code{_warnings.warn()} in case of a bad
@code{__name__} global. Patch by Oren Milman.

@item 
bpo-31506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31506}: Improved the error message logic for object.__new__ and
object.__init__.

@item 
bpo-31505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31505}: Fix an assertion failure in @ref{a4,,json}, in case
@code{_json.make_encoder()} received a bad @code{encoder()} argument. Patch by Oren
Milman.

@item 
bpo-31492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31492}: Fix assertion failures in case of failing to import from a
module with a bad @code{__name__} attribute, and in case of failing to access
an attribute of such a module. Patch by Oren Milman.

@item 
bpo-31478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31478}: Fix an assertion failure in @code{_random.Random.seed()} in case the
argument has a bad @code{__abs__()} method. Patch by Oren Milman.

@item 
bpo-31336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31336}: Speed up class creation by 10-20% by reducing the overhead in
the necessary special method lookups.  Patch by Stefan Behnel.

@item 
bpo-31415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31415}: Add @code{-X importtime} option to show how long each import
takes. It can be used to optimize application's startup time.  Support the
@geindex PYTHONPROFILEIMPORTTIME
@geindex 环境变量; PYTHONPROFILEIMPORTTIME
@ref{44d,,PYTHONPROFILEIMPORTTIME} as an equivalent way to enable this.

@item 
bpo-31410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31410}: Optimized calling wrapper and classmethod descriptors.

@item 
bpo-31353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31353}: 
@geindex Python 提高建议; PEP 553
PEP 553@footnote{https://www.python.org/dev/peps/pep-0553} - Add a new built-in called @code{breakpoint()} which
calls @code{sys.breakpointhook()}.  By default this imports @code{pdb} and calls
@code{pdb.set_trace()}, but users may override @code{sys.breakpointhook()} to
call whatever debugger they want.  The original value of the hook is saved
in @code{sys.__breakpointhook__}.

@item 
bpo-17852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17852}: Maintain a list of open buffered files, flush them before
exiting the interpreter.  Based on a patch from Armin Rigo.

@item 
bpo-31315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31315}: Fix an assertion failure in imp.create_dynamic(), when
spec.name is not a string. Patch by Oren Milman.

@item 
bpo-31311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31311}: Fix a crash in the @code{__setstate__()} method of
@ref{122d,,ctypes._CData}, in case of a bad @code{__dict__}. Patch by Oren Milman.

@item 
bpo-31293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31293}: Fix crashes in true division and multiplication of a timedelta
object by a float with a bad as_integer_ratio() method. Patch by Oren
Milman.

@item 
bpo-31285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31285}: Fix an assertion failure in @ref{6b1,,warnings.warn_explicit}, when the
return value of the received loader's get_source() has a bad splitlines()
method. Patch by Oren Milman.

@item 
bpo-30406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30406}: Make @code{async} and @code{await} proper keywords, as specified in
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492}.
@end itemize

@node Library<46>,Documentation<35>,Core and Builtins<43>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id338}@anchor{122e}
@subsubsection Library



@itemize -

@item 
bpo-30058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30058}: Fixed buffer overflow in select.kqueue.control().

@item 
bpo-31672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31672}: @code{idpattern} in @code{string.Template} matched some non-ASCII
characters. Now it uses @code{-i} regular expression local flag to avoid
non-ASCII characters.

@item 
bpo-31701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31701}: On Windows, faulthandler.enable() now ignores MSC and COM
exceptions.

@item 
bpo-31728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31728}: Prevent crashes in @code{_elementtree} due to unsafe cleanup of
@code{Element.text} and @code{Element.tail}. Patch by Oren Milman.

@item 
bpo-31671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31671}: Now @code{re.compile()} converts passed RegexFlag to normal int
object before compiling. bm_regex_compile benchmark shows 14% performance
improvements.

@item 
bpo-30397@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30397}: The types of compiled regular objects and match objects are now
exposed as @code{re.Pattern} and @code{re.Match}.  This adds information in pydoc
output for the re module.

@item 
bpo-31675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31675}: Fixed memory leaks in Tkinter's methods splitlist() and split()
when pass a string larger than 2 GiB.

@item 
bpo-31673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31673}: Fixed typo in the name of Tkinter's method adderrorinfo().

@item 
bpo-31648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31648}: Improvements to path predicates in ElementTree: Allow
whitespace around predicate parts, i.e. "[a = 'text']" instead of
requiring the less readable "[a='text']". Add support for text comparison
of the current node, like "[.='text']". Patch by Stefan Behnel.

@item 
bpo-30806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30806}: Fix the string representation of a netrc object.

@item 
bpo-31638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31638}: Add optional argument @code{compressed} to
@code{zipapp.create_archive}, and add option @code{--compress} to the command
line interface of @code{zipapp}.

@item 
bpo-25351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25351}: Avoid venv activate failures with undefined variables

@item 
bpo-20519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20519}: Avoid ctypes use (if possible) and improve import time for
uuid.

@item 
bpo-28293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28293}: The regular expression cache is no longer completely dumped
when it is full.

@item 
bpo-31596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31596}: Added pthread_getcpuclockid() to the time module

@item 
bpo-27494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27494}: Make 2to3 accept a trailing comma in generator expressions. For
example, @code{set(x for x in [],)} is now allowed.

@item 
bpo-30347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30347}: Stop crashes when concurrently iterate over itertools.groupby()
iterators.

@item 
bpo-30346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30346}: An iterator produced by itertools.groupby() iterator now
becomes exhausted after advancing the groupby iterator.

@item 
bpo-31556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31556}: Cancel asyncio.wait_for future faster if timeout <= 0

@item 
bpo-31540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31540}: Allow passing a context object in
@ref{196,,concurrent.futures.ProcessPoolExecutor} constructor. Also, free
job resources in @ref{196,,concurrent.futures.ProcessPoolExecutor} earlier
to improve memory usage when a worker waits for new jobs.

@item 
bpo-31516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31516}: @code{threading.current_thread()} should not return a dummy thread
at shutdown.

@item 
bpo-31525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31525}: In the sqlite module, require the sqlite3_prepare_v2 API. Thus,
the sqlite module now requires sqlite version at least 3.3.9.

@item 
bpo-26510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26510}: argparse subparsers are now required by default.  This matches
behaviour in Python 2. For optional subparsers, use the new parameter
@code{add_subparsers(required=False)}. Patch by Anthony Sottile. (As of
3.7.0rc1, the default was changed to not required as had been the case
since Python 3.3.)

@item 
bpo-27541@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27541}: Reprs of subclasses of some collection and iterator classes
(@ref{173,,bytearray}, @ref{217,,array.array}, @ref{633,,collections.deque},
@ref{c15,,collections.defaultdict}, @ref{ced,,itertools.count}, @ref{122f,,itertools.repeat}) now
contain actual type name insteads of hardcoded name of the base class.

@item 
bpo-31351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31351}: python -m ensurepip now exits with non-zero exit code if pip
bootstrapping has failed.

@item 
bpo-31389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31389}: @code{pdb.set_trace()} now takes an optional keyword-only argument
@code{header}. If given, this is printed to the console just before debugging
begins.
@end itemize

@node Documentation<35>,Build<33>,Library<46>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id339}@anchor{1230}
@subsubsection Documentation



@itemize -

@item 
bpo-31537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31537}: Fix incorrect usage of @code{get_history_length} in readline
documentation example code. Patch by Brad Smith.

@item 
bpo-30085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30085}: The operator functions without double underscores are preferred
for clarity. The one with underscores are only kept for
back-compatibility.
@end itemize

@node Build<33>,IDLE<32>,Documentation<35>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id340}@anchor{1231}
@subsubsection Build



@itemize -

@item 
bpo-31696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31696}: Improve compiler version information in @ref{6d4,,sys.version}
when Python is built with Clang.

@item 
bpo-31625@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31625}: Stop using ranlib on static libraries. Instead, we assume ar
supports the 's' flag.

@item 
bpo-31624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31624}: Remove support for BSD/OS.

@item 
bpo-22140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22140}: Prevent double substitution of prefix in python-config.sh.

@item 
bpo-31569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31569}: Correct PCBuild/ case to PCbuild/ in build scripts and
documentation.

@item 
bpo-31536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31536}: Avoid wholesale rebuild after @code{make regen-all} if nothing
changed.
@end itemize

@node IDLE<32>,C API<26>,Build<33>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id341}@anchor{1232}
@subsubsection IDLE



@itemize -

@item 
bpo-31460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31460}: Simplify the API of IDLE's Module Browser. Passing a widget
instead of an flist with a root widget opens the option of creating a
browser frame that is only part of a window.  Passing a full file name
instead of pieces assumed to come from a .py file opens the possibility of
browsing python files that do not end in .py.

@item 
bpo-31649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31649}: IDLE - Make _htest, _utest parameters keyword only.

@item 
bpo-31559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31559}: Remove test order dependence in idle_test.test_browser.

@item 
bpo-31459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31459}: Rename IDLE's module browser from Class Browser to Module
Browser. The original module-level class and method browser became a
module browser, with the addition of module-level functions, years ago.
Nested classes and functions were added yesterday.  For
back-compatibility, the virtual event <<open-class-browser>>, which
appears on the Keys tab of the Settings dialog, is not changed. Patch by
Cheryl Sabella.

@item 
bpo-31500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31500}: Default fonts now are scaled on HiDPI displays.

@item 
bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}: IDLE module browser now shows nested classes and functions.
Original patches for code and tests by Guilherme Polo and Cheryl Sabella,
respectively.
@end itemize

@node C API<26>,,IDLE<32>,Python 3 7 0 alpha 2
@anchor{whatsnew/changelog id342}@anchor{1233}
@subsubsection C API



@itemize -

@item 
bpo-28280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28280}: Make @code{PyMapping_Keys()}, @code{PyMapping_Values()} and
@code{PyMapping_Items()} always return a @ref{1f9,,list} (rather than a @ref{1f9,,list} or a
@ref{1a2,,tuple}). Patch by Oren Milman.

@item 
bpo-31532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31532}: Fix memory corruption due to allocator mix in getpath.c between
Py_GetPath() and Py_SetPath()

@item 
bpo-25658@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25658}: Implement 
@geindex Python 提高建议; PEP 539
PEP 539@footnote{https://www.python.org/dev/peps/pep-0539} for Thread Specific Storage (TSS) API: it
is a new Thread Local Storage (TLS) API to CPython which would supersede
use of the existing TLS API within the CPython interpreter, while
deprecating the existing API. PEP written by Erik M. Bray, patch by
Masayuki Yamamoto.
@end itemize

@node Python 3 7 0 alpha 1,Python 3 6 6 final,Python 3 7 0 alpha 2,更新日志
@anchor{whatsnew/changelog python-3-7-0-alpha-1}@anchor{1234}
@subsection Python 3.7.0 alpha 1


@emph{Release date: 2017-09-19}

@menu
* Security: Security<25>. 
* Core and Builtins: Core and Builtins<44>. 
* Library: Library<47>. 
* Documentation: Documentation<36>. 
* Tests: Tests<35>. 
* Build: Build<34>. 
* Windows: Windows<36>. 
* IDLE: IDLE<33>. 
* Tools/Demos: Tools/Demos<18>. 
* C API: C API<27>. 

@end menu

@node Security<25>,Core and Builtins<44>,,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id343}@anchor{1235}
@subsubsection Security



@itemize -

@item 
bpo-29781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29781}: SSLObject.version() now correctly returns None when handshake
over BIO has not been performed yet.

@item 
bpo-29505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29505}: Add fuzz tests for float(str), int(str), unicode(str); for
oss-fuzz.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: CVE-2017-9233 (External entity
infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix),
CVE-2016-0718 (Fix regression bugs from 2.2.0's fix to CVE-2016-0718) and
CVE-2012-0876 (Counter hash flooding with SipHash). Note: the
CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn't
impact Python, since Python already gets entropy from the OS to set the
expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
CVE-2016-0718 and CVE-2016-4472. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<44>,Library<47>,Security<25>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id344}@anchor{1236}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31490}: Fix an assertion failure in @ref{2a,,ctypes} class definition, in case
the class has an attribute whose name is specified in @code{_anonymous_} but
not in @code{_fields_}. Patch by Oren Milman.

@item 
bpo-31471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31471}: Fix an assertion failure in @ref{3e3,,subprocess.Popen()} on Windows, in
case the env argument has a bad keys() method. Patch by Oren Milman.

@item 
bpo-31418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31418}: Fix an assertion failure in @code{PyErr_WriteUnraisable()} in case
of an exception with a bad @code{__module__} attribute. Patch by Oren Milman.

@item 
bpo-31416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31416}: Fix assertion failures in case of a bad warnings.filters or
warnings.defaultaction. Patch by Oren Milman.

@item 
bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411}: Change direct usage of PyInterpreterState.modules to
PyImport_GetModuleDict(). Also introduce more uniformity in other code
that deals with sys.modules. This helps reduce complications when working
on sys.modules.

@item 
bpo-28411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28411}: Switch to the abstract API when dealing with
@code{PyInterpreterState.modules}. This allows later support for all dict
subclasses and other Mapping implementations.  Also add a
@code{PyImport_GetModule()} function to reduce a bunch of duplicated code.

@item 
bpo-31411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31411}: Raise a TypeError instead of SystemError in case
warnings.onceregistry is not a dictionary. Patch by Oren Milman.

@item 
bpo-31344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31344}: For finer control of tracing behaviour when testing the
interpreter, two new frame attributes have been added to control the
emission of particular trace events: @code{f_trace_lines} (@code{True} by
default) to turn off per-line trace events; and @code{f_trace_opcodes}
(@code{False} by default) to turn on per-opcode trace events.

@item 
bpo-31373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31373}: Fix several possible instances of undefined behavior due to
floating-point demotions.

@item 
bpo-30465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30465}: Location information (@code{lineno} and @code{col_offset}) in
f-strings is now (mostly) correct.  This fixes tools like flake8 from
showing warnings on the wrong line (typically the first line of the file).

@item 
bpo-30860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30860}: Consolidate CPython's global runtime state under a single
struct.  This improves discoverability of the runtime state.

@item 
bpo-31347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31347}: Fix possible undefined behavior in _PyObject_FastCall_Prepend.

@item 
bpo-31343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31343}: Include sys/sysmacros.h for major(), minor(), and makedev().
GNU C libray plans to remove the functions from sys/types.h.

@item 
bpo-31291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31291}: Fix an assertion failure in @ref{1237,,zipimport.zipimporter.get_data} on
Windows, when the return value of @code{pathname.replace('/','\\')} isn't a
string. Patch by Oren Milman.

@item 
bpo-31271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31271}: Fix an assertion failure in the write() method of
@ref{6f4,,io.TextIOWrapper}, when the encoder doesn't return a bytes object. Patch
by Oren Milman.

@item 
bpo-31243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31243}: Fix a crash in some methods of @ref{6f4,,io.TextIOWrapper}, when the
decoder's state is invalid. Patch by Oren Milman.

@item 
bpo-30721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30721}: @code{print} now shows correct usage hint for using Python 2
redirection syntax.  Patch by Sanyam Khurana.

@item 
bpo-31070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31070}: Fix a race condition in importlib _get_module_lock().

@item 
bpo-30747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30747}: Add a non-dummy implementation of _Py_atomic_store and
_Py_atomic_load on MSVC.

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.

@item 
bpo-31071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31071}: Avoid masking original TypeError in call with * unpacking when
other arguments are passed.

@item 
bpo-30978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30978}: str.format_map() now passes key lookup exceptions through.
Previously any exception was replaced with a KeyError exception.

@item 
bpo-30808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30808}: Use _Py_atomic API for concurrency-sensitive signal state.

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30703}: Improve signal delivery. Avoid using Py_AddPendingCall from
signal handler, to avoid calling signal-unsafe functions. The tests I'm
adding here fail without the rest of the patch, on Linux and OS X. This
means our signal delivery logic had defects (some signals could be lost).

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-31161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31161}: Make sure the 'Missing parentheses' syntax error message is
only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

@item 
bpo-30814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30814}: Fixed a race condition when import a submodule from a package.

@item 
bpo-30736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30736}: The internal unicodedata database has been upgraded to Unicode
10.0.

@item 
bpo-30604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30604}: Move co_extra_freefuncs from per-thread to per-interpreter to
avoid crashes.

@item 
bpo-30597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30597}: @code{print} now shows expected input in custom error message when
used as a Python 2 statement. Patch by Sanyam Khurana.

@item 
bpo-30682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30682}: Removed a too-strict assertion that failed for certain
f-strings, such as eval("f'\n'") and eval("f'\r'").

@item 
bpo-30501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30501}: The compiler now produces more optimal code for complex
condition expressions in the "if", "while" and "assert" statement, the
"if" expression, and generator expressions and comprehensions.

@item 
bpo-28180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28180}: Implement 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} (legacy C locale coercion). This means
that when a suitable coercion target locale is available, both the core
interpreter and locale-aware C extensions will assume the use of UTF-8 as
the default text encoding, rather than ASCII.

@item 
bpo-30486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30486}: Allows setting cell values for __closure__. Patch by Lisa
Roach.

@item 
bpo-30537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30537}: itertools.islice now accepts integer-like objects (having an
__index__ method) as start, stop, and slice arguments

@item 
bpo-25324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25324}: Tokens needed for parsing in Python moved to C. @code{COMMENT},
@code{NL} and @code{ENCODING}. This way the tokens and tok_names in the token
module don't get changed when you import the tokenize module.

@item 
bpo-29104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29104}: Fixed parsing backslashes in f-strings.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-30039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30039}: If a KeyboardInterrupt happens when the interpreter is in the
middle of resuming a chain of nested 'yield from' or 'await' calls, it's
now correctly delivered to the innermost frame.

@item 
bpo-28974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28974}: @code{object.__format__(x, '@w{'})} is now equivalent to @code{str(x)}
rather than @code{format(str(self), '@w{'})}.

@item 
bpo-30024@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30024}: Circular imports involving absolute imports with binding a
submodule to a name are now supported.

@item 
bpo-12414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12414}: sys.getsizeof() on a code object now returns the sizes which
includes the code struct and sizes of objects which it references. Patch
by Dong-hee Na.

@item 
bpo-29839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29839}: len() now raises ValueError rather than OverflowError if
__len__() returned a large negative integer.

@item 
bpo-11913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11913}: README.rst is now included in the list of distutils standard
READMEs and therefore included in source distributions.

@item 
bpo-29914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29914}: Fixed default implementations of __reduce__ and
__reduce_ex__(). object.__reduce__() no longer takes arguments,
object.__reduce_ex__() now requires one argument.

@item 
bpo-29949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29949}: Fix memory usage regression of set and frozenset object.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-29816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29816}: Shift operation now has less opportunity to raise
OverflowError. ValueError always is raised rather than OverflowError for
negative counts. Shifting zero with non-negative count always returns
zero.

@item 
bpo-24821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24821}: Fixed the slowing down to 25 times in the searching of some
unlucky Unicode characters.

@item 
bpo-29102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29102}: Add a unique ID to PyInterpreterState.  This makes it easier to
identify each subinterpreter.

@item 
bpo-29894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29894}: The deprecation warning is emitted if __complex__ returns an
instance of a strict subclass of complex.  In a future versions of Python
this can be an error.

@item 
bpo-29859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29859}: Show correct error messages when any of the pthread_* calls in
thread_pthread.h fails.

@item 
bpo-29849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29849}: Fix a memory leak when an ImportError is raised during from
import.

@item 
bpo-28856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28856}: Fix an oversight that %b format for bytes should support
objects follow the buffer protocol.

@item 
bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. The interpreter now consistently avoids ever adding the import
location's parent directory to @code{sys.path}, and ensures no other
@code{sys.path} entries are inadvertently modified when inserting the import
location named on the command line.

@item 
bpo-29568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29568}: Escaped percent "%%" in the format string for classic string
formatting no longer allows any characters between two percents.

@item 
bpo-29714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29714}: Fix a regression that bytes format may fail when containing
zero bytes inside.

@item 
bpo-29695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29695}: bool(), float(), list() and tuple() no longer take keyword
arguments. The first argument of int() can now be passes only as
positional argument.

@item 
bpo-28893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28893}: Set correct __cause__ for errors about invalid awaitables
returned from __aiter__ and __anext__.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a4a,,OverflowError}.

@item 
bpo-29683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29683}: Fixes to memory allocation in _PyCode_SetExtra.  Patch by Brian
Coleman.

@item 
bpo-29684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29684}: Fix minor regression of PyEval_CallObjectWithKeywords. It
should raise TypeError when kwargs is not a dict.  But it might cause segv
when args=NULL and kwargs is not a dict.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29607}: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by
Matthieu Dartiailh.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29463}: Add @code{docstring} field to Module, ClassDef, FunctionDef, and
AsyncFunctionDef ast nodes.  docstring is not first stmt in their body
anymore.  It affects @code{co_firstlineno} and @code{co_lnotab} of code object
for module and class. (Reverted in bpo-32911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32911}.)

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546}: Set the 'path' and 'name' attribute on ImportError for @code{from
... import ...}.

@item 
bpo-29546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29546}: Improve from-import error message with location

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29327}: Fixed a crash when pass the iterable keyword argument to
sorted().

@item 
bpo-29034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29034}: Fix memory leak and use-after-free in os module
(path_converter).

@item 
bpo-29159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29159}: Fix regression in bytes(x) when x.__index__() raises Exception.

@item 
bpo-29049@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29049}: Call _PyObject_GC_TRACK() lazily when calling Python function.
Calling function is up to 5% faster.

@item 
bpo-28927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28927}: bytes.fromhex() and bytearray.fromhex() now ignore all ASCII
whitespace, not only spaces.  Patch by Robert Xiao.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-18896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18896}: Python function can now have more than 255 parameters.
collections.namedtuple() now supports tuples with more than 255 elements.

@item 
bpo-28596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28596}: The preferred encoding is UTF-8 on Android. Patch written by
Chi Hsuan Yen.

@item 
bpo-22257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22257}: Clean up interpreter startup (see 
@geindex Python 提高建议; PEP 432
PEP 432@footnote{https://www.python.org/dev/peps/pep-0432}).

@item 
bpo-26919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26919}: On Android, operating system data is now always encoded/decoded
to/from UTF-8, instead of the locale encoding to avoid inconsistencies
with os.fsencode() and os.fsdecode() which are already using UTF-8.

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug triggerable by a monkey-patched len() function.

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table. Patch written by INADA Naoki.

@item 
bpo-28739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28739}: f-string expressions are no longer accepted as docstrings and
by ast.literal_eval() even if they do not include expressions.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28918}: Fix the cross compilation of xxlimited when Python has been
built with Py_DEBUG defined.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: Rather than silently producing a class that doesn't support
zero-argument @code{super()} in methods, failing to pass the new
@code{__classcell__} namespace entry up to @code{type.__new__} now results in a
@code{DeprecationWarning} and a class that supports zero-argument
@code{super()}.

@item 
bpo-28797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28797}: Modifying the class __dict__ inside the __set_name__ method of
a descriptor that is used inside that class no longer prevents calling the
__set_name__ method of other descriptors.

@item 
bpo-28799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28799}: Remove the @code{PyEval_GetCallStats()} function and deprecate the
untested and undocumented @code{sys.callstats()} function. Remove the
@code{CALL_PROFILE} special build: use the @ref{f07,,sys.setprofile()} function,
@ref{27,,cProfile} or @ref{d3,,profile} to profile function calls.

@item 
bpo-12844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12844}: More than 255 arguments can now be passed to a function.

@item 
bpo-28782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28782}: Fix a bug in the implementation @code{yield from} when checking if
the next instruction is YIELD_FROM. Regression introduced by WORDCODE
(bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}).

@item 
bpo-28774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28774}: Fix error position of the unicode error in ASCII and Latin1
encoders when a string returned by the error handler contains multiple
non-encodable characters (non-ASCII for the ASCII codec, characters out of
the U+0000-U+00FF range for Latin1).

@item 
bpo-28731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28731}: Optimize _PyDict_NewPresized() to create correct size dict.
Improve speed of dict literal with constant keys up to 30%.

@item 
bpo-28532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28532}: Show sys.version when -V option is supplied twice.

@item 
bpo-27100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27100}: The with-statement now checks for __enter__ before it checks
for __exit__. This gives less confusing error messages when both methods
are missing. Patch by Jonathan Ellington.

@item 
bpo-28746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28746}: Fix the set_inheritable() file descriptor method on platforms
that do not have the ioctl FIOCLEX and FIONCLEX commands.

@item 
bpo-26920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26920}: Fix not getting the locale's charset upon initializing the
interpreter, on platforms that do not have langinfo.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-28665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28665}: Improve speed of the STORE_DEREF opcode by 40%.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28621}: Sped up converting int to float by reusing faster bits counting
implementation.  Patch by Adrian Wielgosik.

@item 
bpo-28580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28580}: Optimize iterating split table values. Patch by Xiang Zhang.

@item 
bpo-28583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28583}: PyDict_SetDefault didn't combine split table when needed. Patch
by Xiang Zhang.

@item 
bpo-28128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28128}: Deprecation warning for invalid str and byte escape sequences
now prints better information about where the error occurs. Patch by
Serhiy Storchaka and Eric Smith.

@item 
bpo-28509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28509}: dict.update() no longer allocate unnecessary large memory.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-28517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28517}: Fixed of-by-one error in the peephole optimizer that caused
keeping unreachable code.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Improved exception reporting for problematic __set_name__
attributes.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28183}: Optimize and cleanup dict iteration.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Added C implementation of asyncio.Future. Original patch by
Yury Selivanov.

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: Creating instances of range_iterator by calling range_iterator
type now is disallowed.  Calling iter() on range instance is the only way.
Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28201}: Dict reduces possibility of 2nd conflict in hash table when
hashes have same lower bits.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-28289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28289}: ImportError.__init__ now resets not specified attributes.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in complex(1.0, @{2:3@}) error message. Patch
by Soumya Sharma.

@item 
bpo-28086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28086}: Single var-positional argument of tuple subtype was passed
unscathed to the C-defined function.  Now it is converted to exact tuple.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Now __set_name__ is looked up on the class instead of the
instance.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28192}: Don't import readline in isolated mode.

@item 
bpo-27441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27441}: Remove some redundant assignments to ob_size in longobject.c.
Thanks Oren Milman.

@item 
bpo-27222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27222}: Clean up redundant code in long_rshift function. Thanks Oren
Milman.

@item 
Upgrade internal unicode databases to Unicode version 9.0.0.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-28126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28126}: Replace Py_MEMCPY with memcpy(). Visual Studio can properly
optimize memcpy().

@item 
bpo-28120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28120}: Fix dict.pop() for splitted dictionary when trying to remove a
"pending key" (Not yet inserted in split-table). Patch by Xiang Zhang.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Raise DeprecationWarning when async and await keywords are used
as variable/attribute/class/function name.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Fix a refleak in code that raises DeprecationWarning.

@item 
bpo-28721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28721}: Fix asynchronous generators aclose() and athrow() to handle
StopAsyncIteration propagation properly.

@item 
bpo-26110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26110}: Speed-up method calls: add LOAD_METHOD and CALL_METHOD opcodes.
@end itemize

@node Library<47>,Documentation<36>,Core and Builtins<44>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id345}@anchor{1238}
@subsubsection Library



@itemize -

@item 
bpo-31499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31499}: xml.etree: Fix a crash when a parser is part of a reference
cycle.

@item 
bpo-31482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31482}: @code{random.seed()} now works with bytes in version=1

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: typing.get_type_hints now finds the right globalns for classes
and modules by default (when no @code{globalns} was specified by the caller).

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Speed improvements to the @code{typing} module.  Original PRs by
Ivan Levkivskyi and Mitar.

@item 
bpo-31544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31544}: The C accelerator module of ElementTree ignored exceptions
raised when looking up TreeBuilder target methods in XMLParser().

@item 
bpo-31234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31234}: socket.create_connection() now fixes manually a reference
cycle: clear the variable storing the last exception on success.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: LoggerAdapter objects can now be nested.

@item 
bpo-31431@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31431}: SSLContext.check_hostname now automatically sets
SSLContext.verify_mode to ssl.CERT_REQUIRED instead of failing with a
ValueError.

@item 
bpo-31233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31233}: socketserver.ThreadingMixIn now keeps a list of non-daemonic
threads to wait until all these threads complete in server_close().

@item 
bpo-28638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28638}: Changed the implementation strategy for
collections.namedtuple() to substantially reduce the use of exec() in
favor of precomputed methods. As a result, the @emph{verbose} parameter and
@emph{_source} attribute are no longer supported.  The benefits include 1)
having a smaller memory footprint for applications using multiple named
tuples, 2) faster creation of the named tuple class (approx 4x to 6x
depending on how it is measured), and 3) minor speed-ups for instance
creation using __new__, _make, and _replace.  (The primary patch
contributor is Jelle Zijlstra with further improvements by INADA Naoki,
Serhiy Storchaka, and Raymond Hettinger.)

@item 
bpo-31400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31400}: Improves SSL error handling to avoid losing error numbers.

@item 
bpo-27629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27629}: Make return types of SSLContext.wrap_bio() and
SSLContext.wrap_socket() customizable.

@item 
bpo-28958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28958}: ssl.SSLContext() now uses OpenSSL error information when a
context cannot be instantiated.

@item 
bpo-28182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28182}: The SSL module now raises SSLCertVerificationError when OpenSSL
fails to verify the peer's certificate. The exception contains more
information about the error.

@item 
bpo-27340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27340}: SSLSocket.sendall() now uses memoryview to create slices of
data. This fixes support for all bytes-like object. It is also more
efficient and avoids costly copies.

@item 
bpo-14191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14191}: A new function
@code{argparse.ArgumentParser.parse_intermixed_args} provides the ability to
parse command lines where there user intermixes options and positional
arguments.

@item 
bpo-31178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31178}: Fix string concatenation bug in rare error path in the
subprocess module

@item 
bpo-31350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31350}: Micro-optimize @code{asyncio._get_running_loop()} to become up
to 10% faster.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}

@item 
bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

@item 
bpo-1198569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1198569}: @code{string.Template} subclasses can optionally define
@code{braceidpattern} if they want to specify different placeholder patterns
inside and outside the braces.  If None (the default) it falls back to
@code{idpattern}.

@item 
bpo-31326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31326}: concurrent.futures.ProcessPoolExecutor.shutdown() now
explicitly closes the call queue. Moreover, shutdown(wait=True) now also
join the call queue thread, to prevent leaking a dangling thread.

@item 
bpo-27144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27144}: The @code{map()} and @code{as_completed()} iterators in
@code{concurrent.futures} now avoid keeping a reference to yielded objects.

@item 
bpo-31281@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31281}: Fix @code{fileinput.FileInput(files, inplace=True)} when @code{files}
contain @code{pathlib.Path} objects.

@item 
bpo-10746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10746}: Fix ctypes producing wrong 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} type codes for integer
types.

@item 
bpo-27584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27584}: @code{AF_VSOCK} has been added to the socket interface which
allows communication between virtual machines and their host.

@item 
bpo-22536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22536}: The subprocess module now sets the filename when
FileNotFoundError is raised on POSIX systems due to the executable or cwd
not being found.

@item 
bpo-29741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29741}: Update some methods in the _pyio module to also accept integer
types. Patch by Oren Milman.

@item 
bpo-31249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31249}: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor
now breaks a reference cycle between an exception object and the WorkItem
object.

@item 
bpo-31247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31247}: xmlrpc.server now explicitly breaks reference cycles when using
sys.exc_info() in code handling exceptions.

@item 
bpo-23835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23835}: configparser: reading defaults in the @code{ConfigParser()}
constructor is now using @code{read_dict()}, making its behavior consistent
with the rest of the parser.  Non-string keys and values in the defaults
dictionary are now being implicitly converted to strings.  Patch by James
Tocknell.

@item 
bpo-31238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31238}: pydoc: the stop() method of the private ServerThread class now
waits until DocServer.serve_until_quit() completes and then explicitly
sets its docserver attribute to None to break a reference cycle.

@item 
bpo-5001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5001}: Many asserts in @ref{b7,,multiprocessing} are now more informative, and
some error types have been changed to more specific ones.

@item 
bpo-31109@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31109}: Convert zipimport to use Argument Clinic.

@item 
bpo-30102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30102}: The ssl and hashlib modules now call
OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function
detects CPU features and enables optimizations on some CPU architectures
such as POWER8. Patch is based on research from Gustavo Serra Scalet.

@item 
bpo-18966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18966}: Non-daemonic threads created by a multiprocessing.Process are
now joined on child exit.

@item 
bpo-31183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31183}: @ref{37,,dis} now works with asynchronous generator and coroutine
objects. Patch by George Collins based on diagnosis by Luciano Ramalho.

@item 
bpo-5001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5001}: There are a number of uninformative asserts in the
@ref{b7,,multiprocessing} module, as noted in issue 5001. This change fixes two of
the most potentially problematic ones, since they are in error-reporting
code, in the @code{multiprocessing.managers.convert_to_error} function. (It
also makes more informative a ValueError message.) The only potentially
problematic change is that the AssertionError is now a TypeError; however,
this should also help distinguish it from an AssertionError being
@emph{reported} by the function/its caller (such as in issue 31169). - Patch by
Allen W. Smith (drallensmith on github).

@item 
bpo-31185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31185}: Fixed miscellaneous errors in asyncio speedup module.

@item 
bpo-31151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31151}: socketserver.ForkingMixIn.server_close() now waits until all
child processes completed to prevent leaking zombie processes.

@item 
bpo-31072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31072}: Add an @code{include_file} parameter to
@code{zipapp.create_archive()}

@item 
bpo-24700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24700}: Optimize array.array comparison. It is now from 10x up to 70x
faster when comparing arrays holding values of the same integer type.

@item 
bpo-31135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31135}: ttk: fix the destroy() method of LabeledScale and OptionMenu
classes. Call the parent destroy() method even if the used attribute
doesn't exist. The LabeledScale.destroy() method now also explicitly
clears label and scale attributes to help the garbage collector to destroy
all widgets.

@item 
bpo-31107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31107}: Fix @code{copyreg._slotnames()} mangled attribute calculation for
classes whose name begins with an underscore. Patch by Shane Harvey.

@item 
bpo-31080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31080}: Allow @ref{4b8,,logging.config.fileConfig} to accept kwargs and/or args.

@item 
bpo-30897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30897}: @code{pathlib.Path} objects now include an @code{is_mount()} method
(only implemented on POSIX).  This is similar to @code{os.path.ismount(p)}.
Patch by Cooper Ry Lees.

@item 
bpo-31061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31061}: Fixed a crash when using asyncio and threads.

@item 
bpo-30987@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30987}: Added support for CAN ISO-TP protocol in the socket module.

@item 
bpo-30522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30522}: Added a @code{setStream} method to @code{logging.StreamHandler} to
allow the stream to be set after creation.

@item 
bpo-30502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30502}: Fix handling of long oids in ssl.  Based on patch by Christian
Heimes.

@item 
bpo-5288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5288}: Support tzinfo objects with sub-minute offsets.

@item 
bpo-30919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30919}: Fix shared memory performance regression in multiprocessing in
3.x. Shared memory used anonymous memory mappings in 2.x, while 3.x mmaps
actual files. Try to be careful to do as little disk I/O as possible.

@item 
bpo-26732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26732}: Fix too many fds in processes started with the "forkserver"
method. A child process would inherit as many fds as the number of
still-running children.

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-19896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19896}: Fix multiprocessing.sharedctypes to recognize typecodes @code{'q'}
and @code{'Q'}.

@item 
bpo-30946@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30946}: Remove obsolete code in readline module for platforms where GNU
readline is older than 2.1 or where select() is not available.

@item 
bpo-25684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25684}: Change @code{ttk.OptionMenu} radiobuttons to be unique across
instances of @code{OptionMenu}.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30794}: Added multiprocessing.Process.kill method to terminate using
the SIGKILL signal on Unix.

@item 
bpo-30319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30319}: socket.close() now ignores ECONNRESET error.

@item 
bpo-30828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30828}: Fix out of bounds write in
@code{asyncio.CFuture.remove_done_callback()}.

@item 
bpo-30302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30302}: Use keywords in the @code{repr} of @code{datetime.timedelta}.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-29585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29585}: Avoid importing @code{sysconfig} from @code{site} to improve startup
speed. Python startup is about 5% faster on Linux and 30% faster on macOS.

@item 
bpo-29293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29293}: Add missing parameter "n" on
multiprocessing.Condition.notify(). The doc claims
multiprocessing.Condition behaves like threading.Condition, but its
notify() method lacked the optional "n" argument (to specify the number of
sleepers to wake up) that threading.Condition.notify() accepts.

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-30596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30596}: Add a @code{close()} method to @code{multiprocessing.Process}.

@item 
bpo-9146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9146}: Fix a segmentation fault in _hashopenssl when standard hash
functions such as md5 are not available in the linked OpenSSL library.  As
in some special FIPS-140 build environments.

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Dong-hee Na.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-30664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30664}: The description of a unittest subtest now preserves the order
of keyword arguments of TestCase.subTest().

@item 
bpo-21071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21071}: struct.Struct.format type is now @ref{206,,str} instead of
@ref{172,,bytes}.

@item 
bpo-29212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29212}: Fix concurrent.futures.thread.ThreadPoolExecutor threads to
have a non repr() based thread name by default when no thread_name_prefix
is supplied. They will now identify themselves as
"ThreadPoolExecutor-y_n".

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.

@item 
bpo-30616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30616}: Functional API of enum allows to create empty enums. Patched by
Dong-hee Na

@item 
bpo-30038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30038}: Fix race condition between signal delivery and wakeup file
descriptor. Patch by Nathaniel Smith.

@item 
bpo-23894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23894}: lib2to3 now recognizes @code{rb'...'} and @code{f'...'} strings.

@item 
bpo-24744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24744}: pkgutil.walk_packages function now raises ValueError if @emph{path}
is a string. Patch by Sanyam Khurana.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup.

@item 
bpo-30589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30589}: Fix multiprocessing.Process.exitcode to return the opposite of
the signal number when the process is killed by a signal (instead of 255)
when using the "forkserver" method.

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in @code{imp.load_package()}, fixing it for
cases when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-11822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11822}: The dis.dis() function now is able to disassemble nested code
objects.

@item 
bpo-30624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30624}: selectors does not take KeyboardInterrupt and SystemExit into
account, leaving a fd in a bad state in case of error. Patch by Giampaolo
Rodola'.

@item 
bpo-30595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30595}: multiprocessing.Queue.get() with a timeout now polls its reader
in non-blocking mode if it succeeded to acquire the lock but the acquire
took longer than the timeout.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-30605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30605}: re.compile() no longer raises a BytesWarning when compiling a
bytes instance with misplaced inline modifier.  Patch by Roy Williams.

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30014}: modify() method of poll(), epoll() and devpoll() based classes
of selectors module is around 10% faster.  Patch by Giampaolo Rodola'.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-30463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30463}: Addded empty __slots__ to abc.ABC.  This allows subclassers to
deny __dict__ and __weakref__ creation.  Patch by Aaron Hall.

@item 
bpo-30520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30520}: Loggers are now pickleable.

@item 
bpo-30557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30557}: faulthandler now correctly filters and displays exception codes
on Windows

@item 
bpo-30526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30526}: Add TextIOWrapper.reconfigure() and a
TextIOWrapper.write_through attribute.

@item 
bpo-30245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30245}: Fix possible overflow when organize struct.pack_into error
message.  Patch by Yuan Liu.

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}: Allow registering at-fork handlers.

@item 
bpo-30470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30470}: Deprecate invalid ctypes call protection on Windows.  Patch by
Mariatta Wijaya.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Dong-hee
Na.

@item 
bpo-30436@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30436}: importlib.find_spec() raises ModuleNotFoundError instead of
AttributeError if the specified parent module is not a package (i.e. lacks
a __path__ attribute).

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under @emph{spawn}
and @emph{forkserver} start methods.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-29196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29196}: Removed previously deprecated in Python 2.4 classes Plist, Dict
and _InternalDict in the plistlib module.  Dict values in the result of
functions readPlist() and readPlistFromBytes() are now normal dicts.  You
no longer can use attribute access to access items of these dictionaries.

@item 
bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850}: The @code{macpath} is now deprecated and will be removed in
Python 3.8.

@item 
bpo-30299@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30299}: Compiling regular expression in debug mode on CPython now
displays the compiled bytecode in human readable form.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-30266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30266}: contextlib.AbstractContextManager now supports
anti-registration by setting __enter__ = None or __exit__ = None,
following the pattern introduced in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}. Patch by Jelle Zijlstra.

@item 
bpo-30340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30340}: Enhanced regular expressions optimization. This increased the
performance of matching some patterns up to 25 times.

@item 
bpo-30298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30298}: Weaken the condition of deprecation warnings for inline
modifiers. Now allowed several subsequential inline modifiers at the start
of the pattern (e.g. @code{'(?i)(?s)...'}).  In verbose mode whitespaces and
comments now are allowed before and between inline modifiers (e.g. @code{'(?x)
(?i) (?s)...'}).

@item 
bpo-30285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30285}: Optimized case-insensitive matching and searching of regular
expressions.

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-29979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29979}: rewrite cgi.parse_multipart, reusing the FieldStorage class and
making its results consistent with those of FieldStorage for
multipart/form-data requests. Patch by Pierre Quentel.

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30215}: Compiled regular expression objects with the re.LOCALE flag no
longer depend on the locale at compile time.  Only the locale at matching
time affects the result of matching.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-30103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30103}: binascii.b2a_uu() and uu.encode() now support using @code{'`'} as
zero instead of space.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30228}: The seek() and tell() methods of io.FileIO now set the internal
seekable attribute to avoid one syscall on open() (in buffered or text
mode).

@item 
bpo-30190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30190}: unittest's assertAlmostEqual and assertNotAlmostEqual provide a
better message in case of failure which includes the difference between
left and right arguments.  (patch by Giampaolo Rodola')

@item 
bpo-30101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30101}: Add support for curses.A_ITALIC.

@item 
bpo-29822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29822}: inspect.isabstract() now works during __init_subclass__.  Patch
by Nate Soares.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-22352@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22352}: Column widths in the output of dis.dis() are now adjusted for
large line numbers and instruction offsets.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30218}: Fix PathLike support for shutil.unpack_archive. Patch by Jelle
Zijlstra.

@item 
bpo-10076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10076}: Compiled regular expression and match objects in the re module
now support copy.copy() and copy.deepcopy() (they are considered atomic).

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-26187@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26187}: Test that sqlite3 trace callback is not called multiple times
when schema is changing.  Indirectly fixed by switching to use
sqlite3_prepare_v2() in bpo-9303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9303}.  Patch by Aviv Palivoda.

@item 
bpo-30017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30017}: Allowed calling the close() method of the zip entry writer
object multiple times.  Writing to a closed writer now always produces a
ValueError.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29995}: re.escape() now escapes only regex special characters.

@item 
bpo-29962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29962}: Add math.remainder operation, implementing remainder as
specified in IEEE 754.

@item 
bpo-29649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29649}: Improve struct.pack_into() exception messages for problems with
the buffer size and offset.  Patch by Andrew Nester.

@item 
bpo-29654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29654}: Support If-Modified-Since HTTP header (browser cache).  Patch
by Pierre Quentel.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-29953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29953}: Fixed memory leaks in the replace() method of datetime and time
objects when pass out of bound fold argument.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-10030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10030}: Sped up reading encrypted ZIP files by 2 times.

@item 
bpo-29204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29204}: Element.getiterator() and the html parameter of XMLParser()
were deprecated only in the documentation (since Python 3.2 and 3.4
correspondingly). Now using them emits a deprecation warning.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-25996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25996}: Added support of file descriptors in os.scandir() on Unix.
os.fwalk() is sped up by 2 times by using os.scandir().

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-29901@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29901}: The zipapp module now supports general path-like objects, not
just pathlib.Path.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-19930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19930}: The mode argument of os.makedirs() no longer affects the file
permission bits of newly-created intermediate-level directories.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28692}: Using non-integer value for selecting a plural form in gettext
is now deprecated.

@item 
bpo-26121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26121}: Use C library implementation for math functions erf() and
erfc().

@item 
bpo-29619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29619}: os.stat() and os.DirEntry.inode() now convert inode (st_ino)
using unsigned integers.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.

@item 
bpo-29645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29645}: Speed up importing the webbrowser module.
webbrowser.register() is now thread-safe.

@item 
bpo-28231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28231}: The zipfile module now accepts path-like objects for external
paths.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: index() and count() methods of collections.abc.Sequence now
check identity before checking equality when do comparisons.

@item 
bpo-28682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28682}: Added support for bytes paths in os.fwalk().

@item 
bpo-29728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29728}: Add new @code{socket.TCP_NOTSENT_LOWAT} (Linux 3.12) constant.
Patch by Nathaniel J. Smith.

@item 
bpo-29623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29623}: Allow use of path-like object as a single argument in
ConfigParser.read(). Patch by David Ellis.

@item 
bpo-9303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9303}: Migrate sqlite3 module to _v2 API.  Patch by Aviv Palivoda.

@item 
bpo-28963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28963}: Fix out of bound iteration in
asyncio.Future.remove_done_callback implemented in C.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29271}: Fix Task.current_task and Task.all_tasks implemented in C to
accept None argument as their pure Python implementation.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-7769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7769}: Method register_function() of
xmlrpc.server.SimpleXMLRPCDispatcher and its subclasses can now be used as
a decorator.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-28624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28624}: Add a test that checks that cwd parameter of Popen() accepts
PathLike objects.  Patch by Sayan Chowdhury.

@item 
bpo-28518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28518}: Start a transaction implicitly before a DML statement. Patch by
Aviv Palivoda.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-16285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16285}: urllib.parse.quote is now based on RFC 3986 and hence includes
'~' in the set of characters that is not quoted by default. Patch by
Christian Theune and Ratnadeep Debnath.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-22807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22807}: Add uuid.SafeUUID and uuid.UUID.is_safe to relay information
from the platform about whether generated UUIDs are generated with a
multiprocessing safe method.

@item 
bpo-29576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29576}: Improve some deprecations in importlib. Some deprecated methods
now emit DeprecationWarnings and have better descriptive messages.

@item 
bpo-29534@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29534}: Fixed different behaviour of Decimal.from_float() for _decimal
and _pydecimal. Thanks Andrew Nester.

@item 
bpo-10379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10379}: locale.format_string now supports the 'monetary' keyword
argument, and locale.format is deprecated.

@item 
bpo-29851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29851}: importlib.reload() now raises ModuleNotFoundError if the module
lacks a spec.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29377}: Add WrapperDescriptorType, MethodWrapperType, and
MethodDescriptorType built-in types to types module. Original patch by
Manuel Krebber.

@item 
bpo-29218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29218}: Unused install_misc command is now removed.  It has been
documented as unused since 2000.  Patch by Eric N. Vander Weele.

@item 
bpo-29368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29368}: The extend() method is now called instead of the append()
method when unpickle collections.deque and other list-like objects. This
can speed up unpickling to 2 times.

@item 
bpo-29338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29338}: The help of a builtin or extension class now includes the
constructor signature if __text_signature__ is provided for the class.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29197}: Removed deprecated function ntpath.splitunc().

@item 
bpo-29210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29210}: Removed support of deprecated argument "exclude" in
tarfile.TarFile.add().

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-29192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29192}: Removed deprecated features in the http.cookies module.

@item 
bpo-29193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29193}: A format string argument for string.Formatter.format() is now
positional-only.

@item 
bpo-29195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29195}: Removed support of deprecated undocumented keyword arguments in
methods of regular expression objects.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-20804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20804}: The unittest.mock.sentinel attributes now preserve their
identity when they are copied or pickled.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-28985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28985}: Update authorizer constants in sqlite3 module. Patch by
Dingyuan Wang.

@item 
bpo-29079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29079}: Prevent infinite loop in pathlib.resolve() on Windows

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when passing a sequence
that doesn't own its elements as limits.

@item 
bpo-16255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16255}: subprocess.Popen uses /system/bin/sh on Android as the shell,
instead of /bin/sh.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-26937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26937}: The chown() method of the tarfile.TarFile class does not fail
now when the grp module cannot be imported, as for example on Android
platforms.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.  A deprecation warning is
now emitted if the index file is missed and recreated in the 'r' and 'w'
modes (will be an error in future Python releases).

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes consisting of @code{'\'} and an ASCII letter in
re.sub() replacement templates regular expressions now are errors.

@item 
bpo-28835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28835}: Fix a regression introduced in warnings.catch_warnings(): call
warnings.showwarning() if it was overridden inside the context manager.

@item 
bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172}: To assist with upgrades from 2.7, the previously documented
deprecation of @code{inspect.getfullargspec()} has been reversed. This
decision may be revisited again after the Python 2.7 branch is no longer
officially supported.

@item 
bpo-28740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28740}: Add sys.getandroidapilevel(): return the build time API version
of Android as an integer. Function only available on Android.

@item 
bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273}: Add new @code{socket.TCP_CONGESTION} (Linux 2.6.13) and
@code{socket.TCP_USER_TIMEOUT} (Linux 2.6.37) constants. Patch written by
Omar Sandoval.

@item 
bpo-28752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28752}: Restored the __reduce__() methods of datetime objects.

@item 
bpo-28727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28727}: Regular expression patterns, _sre.SRE_Pattern objects created
by re.compile(), become comparable (only x==y and x!=y operators). This
change should fix the bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: don't duplicate warning filters when
the warnings module is reloaded (thing usually only done in unit tests).

@item 
bpo-20572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20572}: Remove the subprocess.Popen.wait endtime parameter.  It was
deprecated in 3.4 and undocumented prior to that.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-28548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28548}: In the "http.server" module, parse the protocol version if
possible, to avoid using HTTP 0.9 in some error responses.

@item 
bpo-19717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19717}: Makes Path.resolve() succeed on paths that do not exist. Patch
by Vajrasky Kok

@item 
bpo-28563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28563}: Fixed possible DoS and arbitrary code execution when handle
plural form selections in the gettext module.  The expression parser now
supports exact syntax supported by GNU gettext.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-24241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24241}: The webbrowser in an X environment now prefers using the
default browser directly. Also, the webbrowser register() function now has
a documented 'preferred' argument, to specify browsers to be returned by
get() with no arguments. Patch by David Steele

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar.prweek() no longer prints a space after a
weeks's calendar.  calendar.TextCalendar.pryear() no longer prints
redundant newline after a year's calendar.  Based on patch by Xiang Zhang.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar.prmonth() no longer prints a space at the
start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-28430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28430}: Fix iterator of C implemented asyncio.Future doesn't accept
non-None value is passed to it.send(val).

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets now start by the "!" prefix
for readability.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer adds entry "./" to ZIP archive.

@item 
bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}: re.sub() now raises an error for invalid numerical group
reference in replacement template even if the pattern is not found in the
string.  Error message for invalid group reference now includes the group
index and the position of the reference. Based on patch by SilentGhost.

@item 
bpo-28469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28469}: timeit now uses the sequence 1, 2, 5, 10, 20, 50,... instead of
1, 10, 100,... for autoranging.

@item 
bpo-28115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28115}: Command-line interface of the zipfile module now uses argparse.
Added support of long options.

@item 
bpo-18219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18219}: Optimize csv.DictWriter for large number of columns. Patch by
Mariatta Wijaya.

@item 
bpo-28448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28448}: Fix C implemented asyncio.Future didn't work on Windows.

@item 
bpo-23214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23214}: In the "io" module, the argument to BufferedReader and
BytesIO's read1() methods is now optional and can be -1, matching the
BufferedIOBase specification.

@item 
bpo-28480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28480}: Fix error building socket module when multithreading is
disabled.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit: remove @code{-c/--clock} and @code{-t/--time} command line
options which were deprecated since Python 3.3.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit now repeats the benchmarks 5 times instead of only 3 to
make benchmarks more reliable.

@item 
bpo-28240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28240}: timeit autorange now uses a single loop iteration if the
benchmark takes less than 10 seconds, instead of 10 iterations. "python3
-m timeit -s 'import time' 'time.sleep(1)'" now takes 4 seconds instead of
40 seconds.

@item 
Distutils.sdist now looks for README and setup.py files with case
sensitivity. This behavior matches that found in Setuptools 6.0 and later.
See setuptools 100@footnote{https://github.com/pypa/setuptools/issues/100} for
rationale.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X. Patch by Ned
Batchelder.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-27998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27998}: Fixed bytes path support in os.scandir() on Windows. Patch by
Eryk Sun.

@item 
bpo-28317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28317}: The disassembler now decodes FORMAT_VALUE argument.

@item 
bpo-28380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28380}: unittest.mock Mock autospec functions now properly support
assert_called, assert_not_called, and assert_called_once.

@item 
bpo-28229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28229}: lzma module now supports pathlib.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28225}: bz2 module now supports pathlib.  Initial patch by Ethan
Furman.

@item 
bpo-28227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28227}: gzip now supports pathlib.  Patch by Ethan Furman.

@item 
bpo-28332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28332}: Deprecated silent truncations in socket.htons and socket.ntohs.
Original patch by Oren Milman.

@item 
bpo-27358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27358}: Optimized merging var-keyword arguments and improved error
message when passing a non-mapping as a var-keyword argument.

@item 
bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}: Improved error message when passing a non-iterable as a
var-positional argument.  Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
bpo-28228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28228}: imghdr now supports pathlib.

@item 
bpo-28226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28226}: compileall now supports pathlib.

@item 
bpo-28314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28314}: Fix function declaration (C flags) for the getiterator() method
of xml.etree.ElementTree.Element.

@item 
bpo-28148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28148}: Stop using localtime() and gmtime() in the time module.
Introduced platform independent _PyTime_localtime API that is similar to
POSIX localtime_r, but available on all platforms.  Patch by Ed Schouten.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: random.choices() now has k as a keyword-only argument to
improve the readability of common cases and come into line with the
signature used in other languages.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.
Added the master parameter in the DisplayStyle constructor.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow falsy values to be used for msg parameter of subTest().

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Fix a memory leak in os.getrandom() when the getrandom() is
interrupted by a signal and a signal handler raises a Python exception.

@item 
bpo-28200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28200}: Fix memory leak on Windows in the os module (fix
path_converter() function).

@item 
bpo-25400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25400}: RobotFileParser now correctly returns default values for
crawl_delay and request_rate.  Initial patch by Peter Wirtz.

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Warning message emitted by using inline flags in the middle of
regular expression now contains a (truncated) regex pattern. Patch by Tim
Graham.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-28114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28114}: Fix a crash in parse_envlist() when env contains byte strings.
Patch by Eryk Sun.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28325}: Remove vestigial MacOS 9 macurl2path module and its tests.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left configparser in an invalid
state. Original patch by Florian Höch.

@item 
bpo-29581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29581}: ABCMeta.__new__ now accepts @code{**kwargs}, allowing abstract
base classes to use keyword parameters in __init_subclass__. Patch by Nate
Soares.

@item 
bpo-25532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25532}: inspect.unwrap() will now only try to unwrap an object
sys.getrecursionlimit() times, to protect against objects which create a
new object on every attribute access.

@item 
bpo-30177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30177}: path.resolve(strict=False) no longer cuts the path after the
first element not present in the filesystem.  Patch by Antoine Pietri.
@end itemize

@node Documentation<36>,Tests<35>,Library<47>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id346}@anchor{1239}
@subsubsection Documentation



@itemize -

@item 
bpo-31294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31294}: Fix incomplete code snippet in the ZeroMQSocketListener and
ZeroMQSocketHandler examples and adapt them to Python 3.

@item 
bpo-21649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21649}: Add RFC 7525 and Mozilla server side TLS links to SSL
documentation.

@item 
bpo-31128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31128}: Allow the pydoc server to bind to arbitrary hostnames.

@item 
bpo-30803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30803}: Clarify doc on truth value testing. Original patch by Peter
Thomassen.

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-30052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30052}: the link targets for @ref{172,,bytes()} and @ref{173,,bytearray()} are
now their respective type definitions, rather than the corresponding
builtin function entries. Use @ref{123a,,bytes} and
@ref{123b,,bytearray} to reference the latter. In order to
ensure this and future cross-reference updates are applied automatically,
the daily documentation builds now disable the default output caching
features in Sphinx.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.

@item 
bpo-19824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19824}: Improve the documentation for, and links to, template strings
by emphasizing their utility for internationalization, and by clarifying
some usage constraints. (See also: bpo-20314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20314}, bpo-12518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12518})

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The data model reference and the porting section in the 3.6
What's New guide now cover the additional @code{__classcell__} handling
needed for custom metaclasses to fully support 
@geindex Python 提高建议; PEP 487
PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} and
zero-argument @code{super()}.

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node Tests<35>,Build<34>,Documentation<36>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id347}@anchor{123c}
@subsubsection Tests



@itemize -

@item 
bpo-29639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29639}: test.support.HOST is now "localhost", a new HOSTv4 constant has
been added for your @code{127.0.0.1} needs, similar to the existing HOSTv6
constant.

@item 
bpo-31320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31320}: Silence traceback in test_ssl

@item 
bpo-31346@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31346}: Prefer PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER protocols
for SSLContext.

@item 
bpo-25674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25674}: Remove sha256.tbs-internet.com ssl test

@item 
bpo-30715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30715}: Address ALPN callback changes for OpenSSL 1.1.0f. The latest
version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: regrtest: Exclude tzdata from regrtest --all. When running the
test suite using --use=all / -u all, exclude tzdata since it makes
test_datetime too slow (15-20 min on some buildbots) which then times out
on some buildbots. Fix also regrtest command line parser to allow passing
-u extralargefile to run test_zipfile64.

@item 
bpo-30695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30695}: Add the @code{set_nomemory(start, stop)} and @code{remove_mem_hooks()}
functions to the _testcapi module.

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.

@item 
bpo-24932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24932}: Use proper command line parsing in _testembed

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l in regrtest command line
arguments.

@item 
bpo-28683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28683}: Fix the tests that bind() a unix socket and raise
PermissionError on Android for a non-root user.

@item 
bpo-26936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26936}: Fix the test_socket failures on Android - getservbyname(),
getservbyport() and getaddrinfo() are broken on some Android API levels.

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.

@item 
bpo-26944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26944}: Fix test_posix for Android where 'id -G' is entirely wrong or
missing the effective gid.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.

@item 
bpo-28217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28217}: Adds _testconsole module to test console input.

@item 
bpo-26939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26939}: Add the support.setswitchinterval() function to fix
test_functools hanging on the Android armv7 qemu emulator.
@end itemize

@node Build<34>,Windows<36>,Tests<35>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id348}@anchor{123d}
@subsubsection Build



@itemize -

@item 
bpo-31354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31354}: Allow --with-lto to be used on all builds, not just @code{make
profile-opt}.

@item 
bpo-31370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31370}: Remove support for building --without-threads. This option is
not really useful anymore in the 21st century. Removing lots of
conditional paths allows us to simplify the code base, including in
difficult to maintain low-level internal code.

@item 
bpo-31341@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31341}: Per 
@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011}, support for the IRIX operating system was
removed.

@item 
bpo-30854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30854}: Fix compile error when compiling --without-threads. Patch by
Masayuki Yamamoto.

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-20210@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20210}: Support the @emph{disabled} marker in Setup files. Extension modules
listed after this marker are not built at all, neither by the Makefile nor
by setup.py.

@item 
bpo-29941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29941}: Add @code{--with-assertions} configure flag to explicitly enable C
@code{assert()} checks. Defaults to off. @code{--with-pydebug} implies
@code{--with-assertions}.

@item 
bpo-28787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28787}: Fix out-of-tree builds of Python when configured with
@code{--with--dtrace}.

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: sys.version and the platform module python_build(),
python_branch(), and python_revision() functions now use git information
rather than hg when building from a repo.

@item 
bpo-29572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29572}: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

@item 
bpo-27659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27659}: Prohibit implicit C function declarations: use
@code{-Werror=implicit-function-declaration} when possible (GCC and Clang,
but it depends on the compiler version). Patch written by Chi Hsuan Yen.

@item 
bpo-29384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29384}: Remove old Be OS helper scripts.

@item 
bpo-26851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26851}: Set Android compilation and link flags.

@item 
bpo-28768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28768}: Fix implicit declaration of function _setmode. Patch by
Masayuki Yamamoto

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: lockf() is available on Android API level 24, but the F_LOCK
macro is not defined in android-ndk-r13.

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Fix the compilation error that occurs because if_nameindex() is
available on Android API level 24, but the if_nameindex structure is not
defined.

@item 
bpo-20211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20211}: Do not add the directory for installing C header files and the
directory for installing object code libraries to the cross compilation
search paths. Original patch by Thomas Petazzoni.

@item 
bpo-28849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28849}: Do not define sys.implementation._multiarch on Android.

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28208}: Update Windows build and OS X installers to use SQLite 3.14.2.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

@item 
bpo-21124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21124}: Fix building the _struct module on Cygwin by passing @code{NULL}
instead of @code{&PyType_Type} to PyVarObject_HEAD_INIT.  Patch by Masayuki
Yamamoto.

@item 
bpo-13756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13756}: Fix building extensions modules on Cygwin.  Patch by Roumen
Petrov, based on original patch by Jason Tishler.

@item 
bpo-21085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21085}: Add configure check for siginfo_t.si_band, which Cygwin does
not provide. Patch by Masayuki Yamamoto with review and rebase by Erik
Bray.

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-27979@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27979}: A full copy of libffi is no longer bundled for use when
building _ctypes on non-OSX UNIX platforms.  An installed copy of libffi
is now required when building _ctypes on such platforms.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Windows<36>,IDLE<33>,Build<34>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id349}@anchor{123e}
@subsubsection Windows



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update Windows build to use OpenSSL 1.1.0f

@item 
bpo-30389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30389}: Adds detection of Visual Studio 2017 to distutils on Windows.

@item 
bpo-31358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31358}: zlib is no longer bundled in the CPython source, instead it is
downloaded on demand just like bz2, lzma, OpenSSL, Tcl/Tk, and SQLite.

@item 
bpo-31340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31340}: Change to building with MSVC v141 (included with Visual Studio
2017)

@item 
bpo-30581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30581}: os.cpu_count() now returns the correct number of processors on
Windows when the number of logical processors is greater than 64.

@item 
bpo-30916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30916}: Pre-build OpenSSL, Tcl and Tk and include the binaries in the
build.

@item 
bpo-30731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30731}: Add a missing xmlns to python.manifest so that it matches the
schema.

@item 
bpo-30291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30291}: Allow requiring 64-bit interpreters from py.exe using -64
suffix. Contributed by Steve (Gadget) Barnes.

@item 
bpo-30362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30362}: Adds list options (-0, -0p) to py.exe launcher. Contributed by
Steve Barnes.

@item 
bpo-23451@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23451}: Fix socket deprecation warnings in socketmodule.c. Patch by
Segev Finer.

@item 
bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450}: The build process on Windows no longer depends on Subversion,
instead pulling external code from GitHub via a Python script.  If Python
3.6 is not found on the system (via @code{py -3.6}), NuGet is used to
download a copy of 32-bit Python.

@item 
bpo-29579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29579}: Removes readme.txt from the installer.

@item 
bpo-25778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25778}: winreg does not truncate string correctly (Patch by Eryk Sun)

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder and disable it by default

@item 
bpo-28522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28522}: Fixes mishandled buffer reallocation in getpathp.c

@item 
bpo-28402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28402}: Adds signed catalog files for stdlib on Windows.

@item 
bpo-28333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28333}: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk
Sun)

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-28161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28161}: Opening CON for write access fails

@item 
bpo-28162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28162}: WindowsConsoleIO readall() fails if first line starts with
Ctrl+Z

@item 
bpo-28163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28163}: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: _PyIO_get_console_type fails for various paths

@item 
bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137}: Renames Windows path file to ._pth

@item 
bpo-28138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28138}: Windows ._pth file should allow import site
@end itemize

@node IDLE<33>,Tools/Demos<18>,Windows<36>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id350}@anchor{123f}
@subsubsection IDLE



@itemize -

@item 
bpo-31493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31493}: IDLE code context -- fix code update and font update timers.
Canceling timers prevents a warning message when test_idle completes.

@item 
bpo-31488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31488}: IDLE - Update non-key options in former extension classes. When
applying configdialog changes, call .reload for each feature class. Change
ParenMatch so updated options affect existing instances attached to
existing editor windows.

@item 
bpo-31477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31477}: IDLE - Improve rstrip entry in doc. Strip trailing whitespace
strips more than blank spaces.  Multiline string literals are not skipped.

@item 
bpo-31480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31480}: IDLE - make tests pass with zzdummy extension disabled by
default.

@item 
bpo-31421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31421}: Document how IDLE runs tkinter programs. IDLE calls tcl/tk
update in the background in order to make live interaction and
experimentation with tkinter applications much easier.

@item 
bpo-31414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31414}: IDLE -- fix tk entry box tests by deleting first. Adding to an
int entry is not the same as deleting and inserting because int('@w{'}) will
fail.

@item 
bpo-31051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31051}: Rearrange IDLE configdialog GenPage into Window, Editor, and
Help sections.

@item 
bpo-30617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30617}: IDLE - Add docstrings and tests for outwin subclass of editor.
Move some data and functions from the class to module level. Patch by
Cheryl Sabella.

@item 
bpo-31287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31287}: IDLE - Do not modify tkinter.message in test_configdialog.

@item 
bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}: Convert IDLE's built-in 'extensions' to regular features. About
10 IDLE features were implemented as supposedly optional extensions. Their
different behavior could be confusing or worse for users and not good for
maintenance. Hence the conversion. The main difference for users is that
user configurable key bindings for builtin features are now handled
uniformly. Now, editing a binding in a keyset only affects its value in
the keyset. All bindings are defined together in the system-specific
default keysets in config-extensions.def. All custom keysets are saved as
a whole in config-extension.cfg.  All take effect as soon as one clicks
Apply or Ok. The affected events are '<<force-open-completions>>',
'<<expand-word>>', '<<force-open-calltip>>', '<<flash-paren>>',
'<<format-paragraph>>', '<<run-module>>', '<<check-module>>', and
'<<zoom-height>>'.  Any (global) customizations made before 3.6.3 will not
affect their keyset-specific customization after 3.6.3. and vice versa.
Initial patch by Charles Wohlganger.

@item 
bpo-31206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31206}: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by
Cheryl Sabella.

@item 
bpo-31001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31001}: Add tests for configdialog highlight tab.  Patch by Cheryl
Sabella.

@item 
bpo-31205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31205}: IDLE: Factor KeysPage(Frame) class from ConfigDialog.  The
slightly modified tests continue to pass.  Patch by Cheryl Sabella.

@item 
bpo-31130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31130}: IDLE -- stop leaks in test_configdialog. Initial patch by
Victor Stinner.

@item 
bpo-31002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31002}: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

@item 
bpo-19903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19903}: IDLE: Calltips use @ref{65e,,inspect.signature} instead of
@ref{660,,inspect.getfullargspec}. This improves calltips for builtins converted to
use Argument Clinic. Patch by Louie Lu.

@item 
bpo-31083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31083}: IDLE - Add an outline of a TabPage class in configdialog.
Update existing classes to match outline. Initial patch by Cheryl Sabella.

@item 
bpo-31050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31050}: Factor GenPage(Frame) class from ConfigDialog. The slightly
modified tests continue to pass. Patch by Cheryl Sabella.

@item 
bpo-31004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31004}: IDLE - Factor FontPage(Frame) class from ConfigDialog. Slightly
modified tests continue to pass. Fix General tests. Patch mostly by Cheryl
Sabella.

@item 
bpo-30781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30781}: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan
Reedy and Cheryl Sabella.

@item 
bpo-31060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31060}: IDLE - Finish rearranging methods of ConfigDialog Grouping
methods pertaining to each tab and the buttons will aid writing tests and
improving the tabs and will enable splitting the groups into classes.

@item 
bpo-30853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30853}: IDLE -- Factor a VarTrace class out of ConfigDialog. Instance
tracers manages pairs consisting of a tk variable and a callback function.
When tracing is turned on, setting the variable calls the function.  Test
coverage for the new class is 100%.

@item 
bpo-31003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31003}: IDLE: Add more tests for General tab.

@item 
bpo-30993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30993}: IDLE - Improve configdialog font page and tests. In
configdialog: Document causal pathways in create_font_tab docstring.
Simplify some attribute names. Move set_samples calls to var_changed_font
(idea from Cheryl Sabella).  Move related functions to positions after the
create widgets function. In test_configdialog: Fix test_font_set so not
order dependent.  Fix renamed test_indent_scale so it tests the widget.
Adjust tests for movement of set_samples call.  Add tests for load
functions.  Put all font tests in one class and tab indent tests in
another.  Except for two lines, these tests completely cover the related
functions.

@item 
bpo-30981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30981}: IDLE -- Add more configdialog font page tests.

@item 
bpo-28523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28523}: IDLE: replace 'colour' with 'color' in configdialog.

@item 
bpo-30917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30917}: Add tests for idlelib.config.IdleConf. Increase coverage from
46% to 96%. Patch by Louie Lu.

@item 
bpo-30934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30934}: Document coverage details for idlelib tests. Add section to
idlelib/idle-test/README.txt. Include check that branches are taken both
ways. Exclude IDLE-specific code that does not run during unit tests.

@item 
bpo-30913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30913}: IDLE: Document ConfigDialog tk Vars, methods, and widgets in
docstrings This will facilitate improving the dialog and splitting up the
class. Original patch by Cheryl Sabella.

@item 
bpo-30899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30899}: IDLE: Add tests for ConfigParser subclasses in config. Patch by
Louie Lu.

@item 
bpo-30881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30881}: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

@item 
bpo-30851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30851}: IDLE: Remove unused variables in configdialog.  One is a
duplicate, one is set but cannot be altered by users. Patch by Cheryl
Sabella.

@item 
bpo-30870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30870}: IDLE: In Settings dialog, select font with Up, Down keys as
well as mouse. Initial patch by Louie Lu.

@item 
bpo-8231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8231}: IDLE: call config.IdleConf.GetUserCfgDir only once.

@item 
bpo-30779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30779}: IDLE: Factor ConfigChanges class from configdialog, put in
config; test. * In config, put dump test code in a function; run it and
unittest in   'if __name__ == '__main__'. * Add class config.ConfigChanges
based on changes_class_v4.py on bpo issue. * Add class
test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise
configdialog to use ConfigChanges; see tracker msg297804. * Revise
test_configdialog to match configdialog changes. * Remove configdialog
functions unused or moved to ConfigChanges. Cheryl Sabella contributed
parts of the patch.

@item 
bpo-30777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30777}: IDLE: configdialog - Add docstrings and fix comments. Patch by
Cheryl Sabella.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: IDLE: Improve textview with docstrings, PEP8 names, and more
tests. Patch by Cheryl Sabella.

@item 
bpo-30723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30723}: IDLE: Make several improvements to parenmatch. Add 'parens'
style to highlight both opener and closer. Make 'default' style, which is
not default, a synonym for 'opener'. Make time-delay work the same with
all styles. Add help for config dialog extensions tab, including help for
parenmatch. Add new tests.  Original patch by Charles Wohlganger.

@item 
bpo-30674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30674}: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

@item 
bpo-21519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21519}: IDLE's basic custom key entry dialog now detects duplicates
properly. Original patch by Saimadhav Heblikar.

@item 
bpo-29910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29910}: IDLE no longer deletes a character after commenting out a
region by a key shortcut.  Add @code{return 'break'} for this and other
potential conflicts between IDLE and default key bindings.

@item 
bpo-30728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30728}: Review and change idlelib.configdialog names. Lowercase method
and attribute names. Replace 'colour' with 'color', expand overly cryptic
names, delete unneeded underscores. Replace @code{import *} with specific
imports. Patches by Cheryl Sabella.

@item 
bpo-6739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6739}: IDLE: Verify user-entered key sequences by trying to bind them
with tk. Add tests for all 3 validation functions. Original patch by G
Polo.  Tests added by Cheryl Sabella.

@item 
bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}: Fix several problems with IDLE's autocompletion box. The
following should now work: clicking on selection box items; using the
scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no
longer happen. Patch by Louie Lu.

@item 
bpo-25514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25514}: Add doc subsubsection about IDLE failure to start. Popup
no-connection message directs users to this section.

@item 
bpo-30642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30642}: Fix reference leaks in IDLE tests. Patches by Louie Lu and
Terry Jan Reedy.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: Add docstrings for textview.py and use PEP8 names. Patches by
Cheryl Sabella and Terry Jan Reedy.

@item 
bpo-30290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30290}: Help-about: use pep8 names and add tests. Increase coverage to
100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

@item 
bpo-30303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30303}: Add _utest option to textview; add new tests. Increase coverage
to 100%. Patches by Louie Lu and Terry Jan Reedy.

@item 
bpo-29071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29071}: IDLE colors f-string prefixes (but not invalid ur prefixes).

@item 
bpo-28572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28572}: Add 10% to coverage of IDLE's test_configdialog. Update and
augment description of the configuration system.
@end itemize

@node Tools/Demos<18>,C API<27>,IDLE<33>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id351}@anchor{1240}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30983}: gdb integration commands (py-bt, etc.) work on optimized shared
builds now, too.  
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} introduced _PyEval_EvalFrameDefault which
inlines PyEval_EvalFrameEx on non-debug shared builds.  This broke the
ability to use py-bt, py-up, and a few other Python-specific gdb
integrations. The problem is fixed by only looking for
_PyEval_EvalFrameDefault frames in python-gdb.py.  Original patch by Bruno
"Polaco" Penteado.

@item 
bpo-29748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29748}: Added the slice index converter in Argument Clinic.

@item 
bpo-24037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24037}: Argument Clinic now uses the converter @code{bool(accept=@{int@})}
rather than @ref{205,,int} for semantical booleans.  This avoids repeating the
default value for Python and C and will help in converting to @ref{2c4,,bool} in
future.

@item 
bpo-29367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29367}: python-gdb.py now supports also @code{method-wrapper}
(@code{wrapperobject}) objects.

@item 
bpo-28023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28023}: Fix python-gdb.py didn't support new dict implementation.

@item 
bpo-15369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15369}: The pybench and pystone microbenchmark have been removed from
Tools. Please use the new Python benchmark suite
@indicateurl{https://github.com/python/performance} which is more reliable and includes
a portable version of pybench working on Python 2 and Python 3.

@item 
bpo-28102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28102}: The zipfile module CLI now prints usage to stderr. Patch by
Stephen J. Turnbull.
@end itemize

@node C API<27>,,Tools/Demos<18>,Python 3 7 0 alpha 1
@anchor{whatsnew/changelog id352}@anchor{1241}
@subsubsection C API



@itemize -

@item 
bpo-31338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31338}: Added the @code{Py_UNREACHABLE()} macro for code paths which are
never expected to be reached.  This and a few other useful macros are now
documented in the C API manual.

@item 
bpo-30832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30832}: Remove own implementation for thread-local storage. CPython has
provided the own implementation for thread-local storage (TLS) on
Python/thread.c, it's used in the case which a platform has not supplied
native TLS.  However, currently all supported platforms (Windows and
pthreads) have provided native TLS and defined the Py_HAVE_NATIVE_TLS
macro with unconditional in any case.

@item 
bpo-30708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30708}: PyUnicode_AsWideCharString() now raises a ValueError if the
second argument is NULL and the wchar_t* string contains null characters.

@item 
bpo-16500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16500}: Deprecate PyOS_AfterFork() and add PyOS_BeforeFork(),
PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

@item 
bpo-6532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6532}: The type of results of PyThread_start_new_thread() and
PyThread_get_thread_ident(), and the id parameter of
PyThreadState_SetAsyncExc() changed from "long" to "unsigned long".

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is deprecated and replaced with
a macro if Py_LIMITED_API is not set or set to the value between
0x03050400 and 0x03060000 (not including) or 0x03060100 or higher.  Added
functions PySlice_Unpack() and PySlice_AdjustIndices().

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.

@item 
bpo-28769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28769}: The result of PyUnicode_AsUTF8AndSize() and PyUnicode_AsUTF8()
is now of type @code{const char *} rather of @code{char *}.

@item 
bpo-29058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29058}: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.

@item 
bpo-28822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28822}: The index parameters @emph{start} and @emph{end} of PyUnicode_FindChar()
are now adjusted to behave like @code{str[start:end]}.

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.

@item 
bpo-28761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28761}: The fields name and doc of structures PyMemberDef, PyGetSetDef,
PyStructSequence_Field, PyStructSequence_Desc, and wrapperbase are now of
type @code{const char *} rather of @code{char *}.

@item 
bpo-28748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28748}: Private variable _Py_PackageContext is now of type @code{const char
*} rather of @code{char *}.

@item 
bpo-19569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19569}: Compiler warnings are now emitted if use most of deprecated
functions.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Deprecated undocumented functions PyUnicode_AsEncodedObject(),
PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and
PyUnicode_AsEncodedUnicode().
@end itemize

@node Python 3 6 6 final,Python 3 6 6 release candidate 1,Python 3 7 0 alpha 1,更新日志
@anchor{whatsnew/changelog python-3-6-6-final}@anchor{1242}
@subsection Python 3.6.6 final


@emph{Release date: 2018-06-27}

There were no new changes in version 3.6.6.

@node Python 3 6 6 release candidate 1,Python 3 6 5 final,Python 3 6 6 final,更新日志
@anchor{whatsnew/changelog python-3-6-6-release-candidate-1}@anchor{1243}
@subsection Python 3.6.6 release candidate 1


@emph{Release date: 2018-06-11}

@menu
* Core and Builtins: Core and Builtins<45>. 
* Library: Library<48>. 
* Documentation: Documentation<37>. 
* Tests: Tests<36>. 
* Build: Build<35>. 
* Windows: Windows<37>. 
* macOS: macOS<30>. 
* IDLE: IDLE<34>. 
* Tools/Demos: Tools/Demos<19>. 
* C API: C API<28>. 

@end menu

@node Core and Builtins<45>,Library<48>,,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id353}@anchor{1244}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33786}: Fix asynchronous generators to handle GeneratorExit in athrow()
correctly

@item 
bpo-30654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30654}: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
shutdown even when there was a custom handler set previously. Patch by
Philipp Kerling.

@item 
bpo-33622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33622}: Fixed a leak when the garbage collector fails to add an object
with the @code{__del__} method or referenced by it into the
@ref{c1b,,gc.garbage} list. @code{PyGC_Collect()} can now be called when an
exception is set and preserves it.

@item 
bpo-31849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31849}: Fix signed/unsigned comparison warning in pyhash.c.

@item 
bpo-33391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33391}: Fix a leak in set_symmetric_difference().

@item 
bpo-28055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28055}: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

@item 
bpo-33231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33231}: Fix potential memory leak in @code{normalizestring()}.

@item 
bpo-29922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29922}: Improved error messages in 'async with' when @code{__aenter__()}
or @code{__aexit__()} return non-awaitable object.

@item 
bpo-33199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33199}: Fix @code{ma_version_tag} in dict implementation is uninitialized
when copying from key-sharing dict.

@item 
bpo-33041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33041}: Fixed jumping when the function contains an @code{async for} loop.

@item 
bpo-32282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32282}: Fix an unnecessary ifdef in the include of VersionHelpers.h in
socketmodule on Windows.

@item 
bpo-21983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21983}: Fix a crash in @ref{1194,,ctypes.cast()} in case the type argument is a
ctypes structured data type. Patch by Eryk Sun and Oren Milman.
@end itemize

@node Library<48>,Documentation<37>,Core and Builtins<45>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id354}@anchor{1245}
@subsubsection Library



@itemize -

@item 
bpo-30167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30167}: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by
Steve Weber.

@item 
bpo-33812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33812}: Datetime instance d with non-None tzinfo, but with
d.tzinfo.utcoffset(d) returning None is now treated as naive by the
astimezone() method.

@item 
bpo-30805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30805}: Avoid race condition with debug logging

@item 
bpo-33767@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33767}: The concatenation (@code{+}) and repetition (@code{*}) sequence
operations now raise @ref{1ff,,TypeError} instead of @ref{6fc,,SystemError} when
performed on @ref{323,,mmap.mmap} objects.  Patch by Zackery Spytz.

@item 
bpo-32684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32684}: Fix gather to propagate cancellation of itself even with
return_exceptions.

@item 
bpo-33674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33674}: Fix a race condition in SSLProtocol.connection_made() of
asyncio.sslproto: start immediately the handshake instead of using
call_soon(). Previously, data_received() could be called before the
handshake started, causing the handshake to hang or fail.

@item 
bpo-31647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31647}: Fixed bug where calling write_eof() on a
_SelectorSocketTransport after it's already closed raises AttributeError.

@item 
bpo-33672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33672}: Fix Task.__repr__ crash with Cython's bogus coroutines

@item 
bpo-33469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33469}: Fix RuntimeError after closing loop that used run_in_executor

@item 
bpo-11874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11874}: Use a better regex when breaking usage into wrappable parts.
Avoids bogus assertion errors from custom metavar strings.

@item 
bpo-30877@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30877}: Fixed a bug in the Python implementation of the JSON decoder
that prevented the cache of parsed strings from clearing after finishing
the decoding. Based on patch by c-fos.

@item 
bpo-33548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33548}: tempfile._candidate_tempdir_list should consider common TEMP
locations

@item 
bpo-33542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33542}: Prevent @code{uuid.get_node} from using a DUID instead of a MAC on
Windows. Patch by Zvi Effron

@item 
bpo-26819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26819}: Fix race condition with @code{ReadTransport.resume_reading} in
Windows proactor event loop.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Minor fixes in typing module: add annotations to
@code{NamedTuple.__new__}, pass @code{*args} and @code{**kwds} in
@code{Generic.__new__}.  Original PRs by Paulius Šarka and Chad Dombrova.

@item 
bpo-20087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20087}: Updated alias mapping with glibc 2.27 supported locales.

@item 
bpo-33422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33422}: Fix trailing quotation marks getting deleted when looking up
byte/string literals on pydoc. Patch by Andrés Delfino.

@item 
bpo-33197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33197}: Update error message when constructing invalid
inspect.Parameters Patch by Dong-hee Na.

@item 
bpo-33383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33383}: Fixed crash in the get() method of the @ref{34,,dbm.ndbm} database
object when it is called with a single argument.

@item 
bpo-33329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33329}: Fix multiprocessing regression on newer glibcs

@item 
bpo-991266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=991266}: Fix quoting of the @code{Comment} attribute of
@ref{11b7,,http.cookies.SimpleCookie}.

@item 
bpo-33131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33131}: Upgrade bundled version of pip to 10.0.1.

@item 
bpo-33308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33308}: Fixed a crash in the @ref{c7,,parser} module when converting an ST
object to a tree of tuples or lists with @code{line_info=False} and
@code{col_info=True}.

@item 
bpo-33263@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33263}: Fix FD leak in @code{_SelectorSocketTransport}  Patch by Vlad
Starostin.

@item 
bpo-33256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33256}: Fix display of @code{<module>} call in the html produced by
@code{cgitb.html()}. Patch by Stéphane Blondon.

@item 
bpo-33203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33203}: @code{random.Random.choice()} now raises @code{IndexError} for empty
sequences consistently even when called from subclasses without a
@code{getrandbits()} implementation.

@item 
bpo-33224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33224}: Update difflib.mdiff() for 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}.  Convert an uncaught
StopIteration in a generator into a return-statement.

@item 
bpo-33209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33209}: End framing at the end of C implementation of
@ref{11bb,,pickle.Pickler.dump()}.

@item 
bpo-32861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32861}: The urllib.robotparser's @code{__str__} representation now
includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
Patch by Michael Lazar.

@item 
bpo-33096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33096}: Allow ttk.Treeview.insert to insert iid that has a false
boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
Khatri.

@item 
bpo-33127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33127}: The ssl module now compiles with LibreSSL 2.7.1.

@item 
bpo-33021@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33021}: Release the GIL during fstat() calls, avoiding hang of all
threads when calling mmap.mmap(), os.urandom(), and random.seed().  Patch
by Nir Soffer.

@item 
bpo-27683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27683}: Fix a regression in @ref{a2,,ipaddress} that result of
@code{hosts()} is empty when the network is constructed by a tuple
containing an integer mask and only 1 bit left for addresses.

@item 
bpo-32844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32844}: Fix wrong redirection of a low descriptor (0 or 1) to stderr in
subprocess if another low descriptor is closed.

@item 
bpo-31908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31908}: Fix output of cover files for @code{trace} module command-line
tool. Previously emitted cover files only when @code{--missing} option was
used. Patch by Michael Selik.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-16865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16865}: Support arrays >=2GiB in @ref{2a,,ctypes}.  Patch by Segev Finer.

@item 
bpo-31238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31238}: pydoc: the stop() method of the private ServerThread class now
waits until DocServer.serve_until_quit() completes and then explicitly
sets its docserver attribute to None to break a reference cycle.
@end itemize

@node Documentation<37>,Tests<36>,Library<48>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id355}@anchor{1246}
@subsubsection Documentation



@itemize -

@item 
bpo-33503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33503}: Fix broken pypi link

@item 
bpo-33421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33421}: Add missing documentation for @code{typing.AsyncContextManager}.

@item 
bpo-33378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33378}: Add Korean language switcher for @indicateurl{https://docs.python.org/3/}

@item 
bpo-33276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33276}: Clarify that the @code{__path__} attribute on modules cannot be
just any value.

@item 
bpo-33201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33201}: Modernize documentation for writing C extension types.

@item 
bpo-33195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33195}: Deprecate @code{Py_UNICODE} usage in @code{c-api/arg} document.
@code{Py_UNICODE} related APIs are deprecated since Python 3.3, but it is
missed in the document.

@item 
bpo-33126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33126}: Document PyBuffer_ToContiguous().

@item 
bpo-27212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27212}: Modify documentation for the @code{islice()} recipe to consume
initial values up to the start index.

@item 
bpo-28247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28247}: Update @ref{14a,,zipapp} documentation to describe how to make
standalone applications.

@item 
bpo-18802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18802}: Documentation changes for ipaddress.  Patch by Jon Foster and
Berker Peksag.

@item 
bpo-27428@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27428}: Update documentation to clarify that @code{WindowsRegistryFinder}
implements @code{MetaPathFinder}. (Patch by Himanshu Lakhara)

@item 
bpo-8243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8243}: Add a note about curses.addch and curses.addstr exception
behavior when writing outside a window, or pad.

@item 
bpo-31432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31432}: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED
flags for ssl.SSLContext.verify_mode.
@end itemize

@node Tests<36>,Build<35>,Documentation<37>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id356}@anchor{1247}
@subsubsection Tests



@itemize -

@item 
bpo-33655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33655}: Ignore test_posix_fallocate failures on BSD platforms that
might be due to running on ZFS.

@item 
bpo-19417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19417}: Add test_bdb.py.
@end itemize

@node Build<35>,Windows<37>,Tests<36>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id357}@anchor{1248}
@subsubsection Build



@itemize -

@item 
bpo-5755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5755}: Move @code{-Wstrict-prototypes} option to @code{CFLAGS_NODIST} from
@code{OPT}. This option emitted annoying warnings when building extension
modules written in C++.

@item 
bpo-33614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33614}: Ensures module definition files for the stable ABI on Windows
are correctly regenerated.

@item 
bpo-33522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33522}: Enable CI builds on Visual Studio Team Services at
@indicateurl{https://python.visualstudio.com/cpython}

@item 
bpo-33012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33012}: Add @code{-Wno-cast-function-type} for gcc 8 for silencing
warnings about function casts like casting to PyCFunction in method
definition lists.

@item 
bpo-33394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33394}: Enable the verbose build for extension modules, when GNU make
is passed macros on the command line.
@end itemize

@node Windows<37>,macOS<30>,Build<35>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id358}@anchor{1249}
@subsubsection Windows



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update Windows installer to OpenSSL 1.0.2o.
@end itemize

@node macOS<30>,IDLE<34>,Windows<37>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id359}@anchor{124a}
@subsubsection macOS



@itemize -

@item 
bpo-33184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33184}: Update macOS installer build to use OpenSSL 1.0.2o.
@end itemize

@node IDLE<34>,Tools/Demos<19>,macOS<30>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id360}@anchor{124b}
@subsubsection IDLE



@itemize -

@item 
bpo-33656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33656}: On Windows, add API call saying that tk scales for DPI. On
Windows 8.1+ or 10, with DPI compatibility properties of the Python binary
unchanged, and a monitor resolution greater than 96 DPI, this should make
text and lines sharper.  It should otherwise have no effect.

@item 
bpo-33768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33768}: Clicking on a context line moves that line to the top of the
editor window.

@item 
bpo-33763@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33763}: IDLE: Use read-only text widget for code context instead of
label widget.

@item 
bpo-33664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33664}: Scroll IDLE editor text by lines. Previously, the mouse wheel
and scrollbar slider moved text by a fixed number of pixels, resulting in
partial lines at the top of the editor box.  The change also applies to
the shell and grep output windows, but not to read-only text views.

@item 
bpo-33679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33679}: Enable theme-specific color configuration for Code Context. Use
the Highlights tab to see the setting for built-in themes or add settings
to custom themes.

@item 
bpo-33642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33642}: Display up to maxlines non-blank lines for Code Context. If
there is no current context, show a single blank line.

@item 
bpo-33628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33628}: IDLE: Cleanup codecontext.py and its test.

@item 
bpo-33564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33564}: IDLE's code context now recognizes async as a block opener.

@item 
bpo-29706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29706}: IDLE now colors async and await as keywords in 3.6. They become
full keywords in 3.7.

@item 
bpo-21474@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21474}: Update word/identifier definition from ascii to unicode. In
text and entry boxes, this affects selection by double-click, movement
left/right by control-left/right, and deletion left/right by
control-BACKSPACE/DEL.

@item 
bpo-33204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33204}: IDLE: consistently color invalid string prefixes. A 'u' string
prefix cannot be paired with either 'r' or 'f'. Consistently color as much
of the prefix, starting at the right, as is valid. Revise and extend
colorizer test.

@item 
bpo-32831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32831}: Add docstrings and tests for codecontext.
@end itemize

@node Tools/Demos<19>,C API<28>,IDLE<34>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id361}@anchor{124c}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-33189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33189}: @code{pygettext.py} now recognizes only literal strings as
docstrings and translatable strings, and rejects bytes literals and
f-string expressions.

@item 
bpo-31920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31920}: Fixed handling directories as arguments in the @code{pygettext}
script. Based on patch by Oleg Krasnikov.

@item 
bpo-29673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29673}: Fix pystackv and pystack gdbinit macros.

@item 
bpo-32885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32885}: Add an @code{-n} flag for @code{Tools/scripts/pathfix.py} to disable
automatic backup creation (files with @code{~} suffix).

@item 
bpo-31583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31583}: Fix 2to3 for using with --add-suffix option but without
--output-dir option for relative path to files in current directory.
@end itemize

@node C API<28>,,Tools/Demos<19>,Python 3 6 6 release candidate 1
@anchor{whatsnew/changelog id362}@anchor{124d}
@subsubsection C API



@itemize -

@item 
bpo-32374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32374}: Document that m_traverse for multi-phase initialized modules
can be called with m_state=NULL, and add a sanity check
@end itemize

@node Python 3 6 5 final,Python 3 6 5 release candidate 1,Python 3 6 6 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-5-final}@anchor{124e}
@subsection Python 3.6.5 final


@emph{Release date: 2018-03-28}

@menu
* Tests: Tests<37>. 
* Build: Build<36>. 

@end menu

@node Tests<37>,Build<36>,,Python 3 6 5 final
@anchor{whatsnew/changelog id363}@anchor{124f}
@subsubsection Tests



@itemize -

@item 
bpo-32872@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32872}: Avoid regrtest compatibility issue with namespace packages.
@end itemize

@node Build<36>,,Tests<37>,Python 3 6 5 final
@anchor{whatsnew/changelog id364}@anchor{1250}
@subsubsection Build



@itemize -

@item 
bpo-33163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33163}: Upgrade pip to 9.0.3 and setuptools to v39.0.1.
@end itemize

@node Python 3 6 5 release candidate 1,Python 3 6 4 final,Python 3 6 5 final,更新日志
@anchor{whatsnew/changelog python-3-6-5-release-candidate-1}@anchor{1251}
@subsection Python 3.6.5 release candidate 1


@emph{Release date: 2018-03-13}

@menu
* Security: Security<26>. 
* Core and Builtins: Core and Builtins<46>. 
* Library: Library<49>. 
* Documentation: Documentation<38>. 
* Tests: Tests<38>. 
* Build: Build<37>. 
* Windows: Windows<38>. 
* macOS: macOS<31>. 
* IDLE: IDLE<35>. 
* Tools/Demos: Tools/Demos<20>. 
* C API: C API<29>. 

@end menu

@node Security<26>,Core and Builtins<46>,,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id365}@anchor{1252}
@subsubsection Security



@itemize -

@item 
bpo-33001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33001}: Minimal fix to prevent buffer overrun in os.symlink on Windows

@item 
bpo-32981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32981}: Regexes in difflib and poplib were vulnerable to catastrophic
backtracking. These regexes formed potential DOS vectors (REDOS). They
have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch
by Jamie Davis.
@end itemize

@node Core and Builtins<46>,Library<49>,Security<26>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id366}@anchor{1253}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-33026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33026}: Fixed jumping out of "with" block by setting f_lineno.

@item 
bpo-17288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17288}: Prevent jumps from 'return' and 'exception' trace events.

@item 
bpo-32889@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32889}: Update Valgrind suppression list to account for the rename of
@code{Py_ADDRESS_IN_RANG} to @code{address_in_range}.

@item 
bpo-32650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32650}: Pdb and other debuggers dependent on bdb.py will correctly step
over (next command) native coroutines. Patch by Pablo Galindo.

@item 
bpo-32685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32685}: Improve suggestion when the Python 2 form of print statement is
either present on the same line as the header of a compound statement or
else terminated by a semi-colon instead of a newline. Patch by Nitish
Chandra.

@item 
bpo-32583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32583}: Fix possible crashing in builtin Unicode decoders caused by
write out-of-bound errors when using customized decode error handlers.

@item 
bpo-26163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26163}: Improved frozenset() hash to create more distinct hash values
when faced with datasets containing many similar values.

@item 
bpo-27169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27169}: The @code{__debug__} constant is now optimized out at compile
time. This fixes also bpo-22091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22091}.

@item 
bpo-32329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32329}: @code{sys.flags.hash_randomization} is now properly set to 0 when
hash randomization is turned off by @code{PYTHONHASHSEED=0}.

@item 
bpo-30416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30416}: The optimizer is now protected from spending much time doing
complex calculations and consuming much memory for creating large
constants in constant folding.

@item 
bpo-18533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18533}: @code{repr()} on a dict containing its own @code{values()} or
@code{items()} no longer raises @code{RecursionError}; OrderedDict similarly.
Instead, use @code{...}, as for other recursive structures.  Patch by Ben
North.

@item 
bpo-32028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32028}: Leading whitespace is now correctly ignored when generating
suggestions for converting Py2 print statements to Py3 builtin print
function calls. Patch by Sanyam Khurana.

@item 
bpo-32137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32137}: The repr of deeply nested dict now raises a RecursionError
instead of crashing due to a stack overflow.
@end itemize

@node Library<49>,Documentation<38>,Core and Builtins<46>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id367}@anchor{1254}
@subsubsection Library



@itemize -

@item 
bpo-33064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33064}: lib2to3 now properly supports trailing commas after @code{*args}
and @code{**kwargs} in function signatures.

@item 
bpo-31804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31804}: Avoid failing in multiprocessing.Process if the standard
streams are closed or None at exit.

@item 
bpo-33037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33037}: Skip sending/receiving data after SSL transport closing.

@item 
bpo-30353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30353}: Fix ctypes pass-by-value for structs on 64-bit Cygwin/MinGW.

@item 
bpo-33009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33009}: Fix inspect.signature() for single-parameter partialmethods.

@item 
bpo-32969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32969}: Expose several missing constants in zlib and fix corresponding
documentation.

@item 
bpo-32713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32713}: Fixed tarfile.itn handling of out-of-bounds float values. Patch
by Joffrey Fuhrer.

@item 
bpo-30622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30622}: The ssl module now detects missing NPN support in LibreSSL.

@item 
bpo-32922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32922}: dbm.open() now encodes filename with the filesystem encoding
rather than default encoding.

@item 
bpo-32859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32859}: In @code{os.dup2}, don't check every call whether the @code{dup3}
syscall exists or not.

@item 
bpo-21060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21060}: Rewrite confusing message from setup.py upload from "No dist
file created in earlier command" to the more helpful "Must create and
upload files in one command".

@item 
bpo-32857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32857}: In @ref{10e,,tkinter}, @code{after_cancel(None)} now raises a
@ref{16d,,ValueError} instead of canceling the first scheduled function.
Patch by Cheryl Sabella.

@item 
bpo-32852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32852}: Make sure sys.argv remains as a list when running trace.

@item 
bpo-32841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32841}: Fixed @ref{3b8,,asyncio.Condition} issue which silently ignored
cancellation after notifying and cancelling a conditional lock. Patch by
Bar Harel.

@item 
bpo-31787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31787}: Fixed refleaks of @code{__init__()} methods in various modules.
(Contributed by Oren Milman)

@item 
bpo-30157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30157}: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
only the last field is quoted.  Patch by Jake Davis.

@item 
bpo-32394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32394}: socket: Remove TCP_FASTOPEN, TCP_KEEPCNT flags on older version
Windows during run-time.

@item 
bpo-32777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32777}: Fix a rare but potential pre-exec child process deadlock in
subprocess on POSIX systems when marking file descriptors inheritable on
exec in the child process.  This bug appears to have been introduced in
3.4.

@item 
bpo-32647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32647}: The ctypes module used to depend on indirect linking for
dlopen. The shared extension is now explicitly linked against libdl on
platforms with dl.

@item 
bpo-32734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32734}: Fixed @code{asyncio.Lock()} safety issue which allowed acquiring
and locking the same lock multiple times, without it being free. Patch by
Bar Harel.

@item 
bpo-32727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32727}: Do not include name field in SMTP envelope from address. Patch
by Stéphane Wirtel

@item 
bpo-27931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27931}: Fix email address header parsing error when the username is an
empty quoted string. Patch by Xiang Zhang.

@item 
bpo-32304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32304}: distutils' upload command no longer corrupts tar files ending
with a CR byte, and no longer tries to convert CR to CRLF in any of the
upload text fields.

@item 
bpo-32502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32502}: uuid.uuid1 no longer raises an exception if a 64-bit hardware
address is encountered.

@item 
bpo-31848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31848}: Fix the error handling in Aifc_read.initfp() when the SSND
chunk is not found. Patch by Zackery Spytz.

@item 
bpo-32555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32555}: On FreeBSD and Solaris, os.strerror() now always decode the
byte string from the current locale encoding, rather than using
ASCII/surrogateescape in some cases.

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: The nis module is now compatible with new libnsl and headers
location.

@item 
bpo-32473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32473}: Improve ABCMeta._dump_registry() output readability

@item 
bpo-32521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32521}: glibc has removed Sun RPC. Use replacement libtirpc headers and
library in nis module.

@item 
bpo-32228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32228}: Ensure that @code{truncate()} preserves the file position (as
reported by @code{tell()}) after writes longer than the buffer size.

@item 
bpo-26133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26133}: Don't unsubscribe signals in asyncio UNIX event loop on
interpreter shutdown.

@item 
bpo-32185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32185}: The SSL module no longer sends IP addresses in SNI TLS
extension on platforms with OpenSSL 1.0.2+ or inet_pton.

@item 
bpo-32323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32323}: @ref{6fa,,urllib.parse.urlsplit()} does not convert zone-id
(scope) to lower case for scoped IPv6 addresses in hostnames now.

@item 
bpo-32302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32302}: Fix bdist_wininst of distutils for CRT v142: it binary
compatible with CRT v140.

@item 
bpo-32255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32255}: A single empty field is now always quoted when written into a
CSV file. This allows to distinguish an empty row from a row consisting of
a single empty field. Patch by Licht Takeuchi.

@item 
bpo-32277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32277}: Raise @code{NotImplementedError} instead of @code{SystemError} on
platforms where @code{chmod(..., follow_symlinks=False)} is not supported.
Patch by Anthony Sottile.

@item 
bpo-32199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32199}: The getnode() ip getter now uses 'ip link' instead of 'ip link
list'.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

@item 
bpo-31900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31900}: The @ref{58d,,locale.localeconv()} function now sets temporarily the
@code{LC_CTYPE} locale to the @code{LC_NUMERIC} locale to decode
@code{decimal_point} and @code{thousands_sep} byte strings if they are non-ASCII
or longer than 1 byte, and the @code{LC_NUMERIC} locale is different than the
@code{LC_CTYPE} locale. This temporary change affects other threads. Same
change for the @ref{5dd,,str.format()} method when formatting a number
(@ref{205,,int}, @ref{1fe,,float}, @ref{1fe,,float} and subclasses) with the
@code{n} type (ex: @code{'@{:n@}'.format(1234)}).

@item 
bpo-31802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31802}: Importing native path module (@code{posixpath}, @code{ntpath}) now
works even if the @code{os} module still is not imported.
@end itemize

@node Documentation<38>,Tests<38>,Library<49>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id368}@anchor{1255}
@subsubsection Documentation



@itemize -

@item 
bpo-17232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17232}: Clarify docs for -O and -OO.  Patch by Terry Reedy.

@item 
bpo-32800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32800}: Update link to w3c doc for xml default namespaces.

@item 
bpo-8722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8722}: Document @ref{433,,__getattr__()} behavior when property @code{get()}
method raises @ref{4aa,,AttributeError}.

@item 
bpo-32614@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32614}: Modify RE examples in documentation to use raw strings to
prevent @ref{15a,,DeprecationWarning} and add text to REGEX HOWTO to highlight
the deprecation.

@item 
bpo-31972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31972}: Improve docstrings for @ref{236,,pathlib.PurePath} subclasses.

@item 
bpo-17799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17799}: Explain real behaviour of sys.settrace and sys.setprofile and
their C-API counterparts regarding which type of events are received in
each function. Patch by Pablo Galindo Salgado.
@end itemize

@node Tests<38>,Build<37>,Documentation<38>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id369}@anchor{1256}
@subsubsection Tests



@itemize -

@item 
bpo-32517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32517}: Fix failing @code{test_asyncio} on macOS 10.12.2+ due to transport
of @code{KqueueSelector} loop was not being closed.

@item 
bpo-32721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32721}: Fix test_hashlib to not fail if the _md5 module is not built.

@item 
bpo-32252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32252}: Fix faulthandler_suppress_crash_report() used to prevent core
dump files when testing crashes. getrlimit() returns zero on success.

@item 
bpo-31518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31518}: Debian Unstable has disabled TLS 1.0 and 1.1 for
SSLv23_METHOD(). Change TLS/SSL protocol of some tests to PROTOCOL_TLS or
PROTOCOL_TLSv1_2 to make them pass on Debian.
@end itemize

@node Build<37>,Windows<38>,Tests<38>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id370}@anchor{1257}
@subsubsection Build



@itemize -

@item 
bpo-32635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32635}: Fix segfault of the crypt module when libxcrypt is provided
instead of libcrypt at the system.
@end itemize

@node Windows<38>,macOS<31>,Build<37>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id371}@anchor{1258}
@subsubsection Windows



@itemize -

@item 
bpo-33016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33016}: Fix potential use of uninitialized memory in
nt._getfinalpathname

@item 
bpo-32903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32903}: Fix a memory leak in os.chdir() on Windows if the current
directory is set to a UNC path.

@item 
bpo-31966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31966}: Fixed WindowsConsoleIO.write() for writing empty data.

@item 
bpo-32409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32409}: Ensures activate.bat can handle Unicode contents.

@item 
bpo-32457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32457}: Improves handling of denormalized executable path when
launching Python.

@item 
bpo-32370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32370}: Use the correct encoding for ipconfig output in the uuid
module. Patch by Segev Finer.

@item 
bpo-29248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29248}: Fix @ref{1d2,,os.readlink()} on Windows, which was mistakenly
treating the @code{PrintNameOffset} field of the reparse data buffer as a
number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

@item 
bpo-32588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32588}: Create standalone _distutils_findvs module.
@end itemize

@node macOS<31>,IDLE<35>,Windows<38>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id372}@anchor{1259}
@subsubsection macOS



@itemize -

@item 
bpo-32726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32726}: Provide an additional, more modern macOS installer variant that
supports macOS 10.9+ systems in 64-bit mode only. Upgrade the supplied
third-party libraries to OpenSSL 1.0.2n, XZ 5.2.3, and SQLite 3.22.0. The
10.9+ installer now links with and supplies its own copy of Tcl/Tk 8.6.8.
@end itemize

@node IDLE<35>,Tools/Demos<20>,macOS<31>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id373}@anchor{125a}
@subsubsection IDLE



@itemize -

@item 
bpo-32984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32984}: Set @code{__file__} while running a startup file.  Like Python,
IDLE optionally runs one startup file in the Shell window before
presenting the first interactive input prompt.  For IDLE, @code{-s} runs a
file named in environmental variable  
@geindex IDLESTARTUP
@geindex 环境变量; IDLESTARTUP
@code{IDLESTARTUP} or
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP}; @code{-r file} runs @code{file}.  Python sets
@code{__file__} to the startup file name before running the file and unsets
it before the first prompt.  IDLE now does the same when run normally,
without the @code{-n} option.

@item 
bpo-32940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32940}: Simplify and rename StringTranslatePseudoMapping in pyparse.

@item 
bpo-32916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32916}: Change @code{str} to @code{code} in pyparse.

@item 
bpo-32905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32905}: Remove unused code in pyparse module.

@item 
bpo-32874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32874}: Add tests for pyparse.

@item 
bpo-32837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32837}: Using the system and place-dependent default encoding for
open() is a bad idea for IDLE's system and location-independent files.

@item 
bpo-32826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32826}: Add "encoding=utf-8" to open() in IDLE's test_help_about. GUI
test test_file_buttons() only looks at initial ascii-only lines, but
failed on systems where open() defaults to 'ascii' because readline()
internally reads and decodes far enough ahead to encounter a non-ascii
character in CREDITS.txt.

@item 
bpo-32765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32765}: Update configdialog General tab docstring to add new widgets to
the widget list.
@end itemize

@node Tools/Demos<20>,C API<29>,IDLE<35>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id374}@anchor{125b}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24960}: 2to3 and lib2to3 can now read pickled grammar files using
pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and
lib2to3 work when run from a zipfile.

@item 
bpo-32222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32222}: Fix pygettext not extracting docstrings for functions with type
annotated arguments. Patch by Toby Harradine.
@end itemize

@node C API<29>,,Tools/Demos<20>,Python 3 6 5 release candidate 1
@anchor{whatsnew/changelog id375}@anchor{125c}
@subsubsection C API



@itemize -

@item 
bpo-29084@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29084}: Undocumented C API for OrderedDict has been excluded from the
limited C API. It was added by mistake and actually never worked in the
limited C API.
@end itemize

@node Python 3 6 4 final,Python 3 6 4 release candidate 1,Python 3 6 5 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-4-final}@anchor{125d}
@subsection Python 3.6.4 final


@emph{Release date: 2017-12-18}

There were no new code changes in version 3.6.4 since v3.6.4rc1.

@node Python 3 6 4 release candidate 1,Python 3 6 3 final,Python 3 6 4 final,更新日志
@anchor{whatsnew/changelog python-3-6-4-release-candidate-1}@anchor{125e}
@subsection Python 3.6.4 release candidate 1


@emph{Release date: 2017-12-05}

@menu
* Core and Builtins: Core and Builtins<47>. 
* Library: Library<50>. 
* Documentation: Documentation<39>. 
* Tests: Tests<39>. 
* Build: Build<38>. 
* Windows: Windows<39>. 
* macOS: macOS<32>. 
* IDLE: IDLE<36>. 
* Tools/Demos: Tools/Demos<21>. 
* C API: C API<30>. 

@end menu

@node Core and Builtins<47>,Library<50>,,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id376}@anchor{125f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-32176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32176}: co_flags.CO_NOFREE is now always set correctly by the code
object constructor based on freevars and cellvars, rather than needing to
be set correctly by the caller. This ensures it will be cleared
automatically when additional cell references are injected into a modified
code object and function.

@item 
bpo-31949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31949}: Fixed several issues in printing tracebacks
(PyTraceBack_Print()). Setting sys.tracebacklimit to 0 or less now
suppresses printing tracebacks. Setting sys.tracebacklimit to None now
causes using the default limit. Setting sys.tracebacklimit to an integer
larger than LONG_MAX now means using the limit LONG_MAX rather than the
default limit. Fixed integer overflows in the case of more than @code{2**31}
traceback items on Windows. Fixed output errors handling.

@item 
bpo-30696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30696}: Fix the interactive interpreter looping endlessly when no
memory.

@item 
bpo-20047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20047}: Bytearray methods partition() and rpartition() now accept only
bytes-like objects as separator, as documented.  In particular they now
raise TypeError rather of returning a bogus result when an integer is
passed as a separator.

@item 
bpo-31852@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31852}: Fix a segmentation fault caused by a combination of the async
soft keyword and continuation lines.

@item 
bpo-21720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21720}: BytesWarning no longer emitted when the @emph{fromlist} argument of
@code{__import__()} or the @code{__all__} attribute of the module contain bytes
instances.

@item 
bpo-31825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31825}: Fixed OverflowError in the 'unicode-escape' codec and in
codecs.escape_decode() when decode an escaped non-ascii byte.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Print the full context/cause chain of exceptions on interpreter
exit, even if an exception in the chain is unhashable or compares equal to
later ones. Patch by Zane Bitter.

@item 
bpo-31786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31786}: Fix timeout rounding in the select module to round correctly
negative timeouts between -1.0 and 0.0. The functions now block waiting
for events as expected. Previously, the call was incorrectly non-blocking.
Patch by Pablo Galindo.

@item 
bpo-31642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31642}: Restored blocking "from package import module" by setting
sys.modules["package.module"] to None.

@item 
bpo-31626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31626}: Fixed a bug in debug memory allocator.  There was a write to
freed memory after shrinking a memory block.

@item 
bpo-31619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31619}: Fixed a ValueError when convert a string with large number of
underscores to integer with binary base.

@item 
bpo-31592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31592}: Fixed an assertion failure in Python parser in case of a bad
@ref{122c,,unicodedata.normalize()}. Patch by Oren Milman.

@item 
bpo-31588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31588}: Raise a @ref{1ff,,TypeError} with a helpful error message when class
creation fails due to a metaclass with a bad @code{__prepare__()} method.
Patch by Oren Milman.

@item 
bpo-31566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31566}: Fix an assertion failure in @code{_warnings.warn()} in case of a bad
@code{__name__} global. Patch by Oren Milman.

@item 
bpo-31505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31505}: Fix an assertion failure in @ref{a4,,json}, in case
@code{_json.make_encoder()} received a bad @code{encoder()} argument. Patch by Oren
Milman.

@item 
bpo-31492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31492}: Fix assertion failures in case of failing to import from a
module with a bad @code{__name__} attribute, and in case of failing to access
an attribute of such a module. Patch by Oren Milman.

@item 
bpo-31490@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31490}: Fix an assertion failure in @ref{2a,,ctypes} class definition, in case
the class has an attribute whose name is specified in @code{_anonymous_} but
not in @code{_fields_}. Patch by Oren Milman.

@item 
bpo-31478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31478}: Fix an assertion failure in @code{_random.Random.seed()} in case the
argument has a bad @code{__abs__()} method. Patch by Oren Milman.

@item 
bpo-31315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31315}: Fix an assertion failure in imp.create_dynamic(), when
spec.name is not a string. Patch by Oren Milman.

@item 
bpo-31311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31311}: Fix a crash in the @code{__setstate__()} method of
@ref{122d,,ctypes._CData}, in case of a bad @code{__dict__}. Patch by Oren Milman.

@item 
bpo-31293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31293}: Fix crashes in true division and multiplication of a timedelta
object by a float with a bad as_integer_ratio() method. Patch by Oren
Milman.

@item 
bpo-31285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31285}: Fix an assertion failure in @ref{6b1,,warnings.warn_explicit}, when the
return value of the received loader's get_source() has a bad splitlines()
method. Patch by Oren Milman.

@item 
bpo-30817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30817}: @code{PyErr_PrintEx()} clears now the ignored exception that may be
raised by @code{_PySys_SetObjectId()}, for example when no memory.
@end itemize

@node Library<50>,Documentation<39>,Core and Builtins<47>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id377}@anchor{1260}
@subsubsection Library



@itemize -

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Two minor fixes for @code{typing} module: allow shallow copying
instances of generic classes, improve interaction of @code{__init_subclass__}
with generics. Original PRs by Ivan Levkivskyi.

@item 
bpo-27240@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27240}: The header folding algorithm for the new email policies has
been rewritten, which also fixes bpo-30788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30788}, bpo-31831@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31831}, and bpo-32182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32182}.  In
particular, RFC2231 folding is now done correctly.

@item 
bpo-32186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32186}: io.FileIO.readall() and io.FileIO.read() now release the GIL
when getting the file size. Fixed hang of all threads with inaccessible
NFS server. Patch by Nir Soffer.

@item 
bpo-12239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12239}: Make @ref{1147,,msilib.SummaryInformation.GetProperty()} return
@code{None} when the value of property is @code{VT_EMPTY}.  Initial patch by
Mark Mc Mahon.

@item 
bpo-31325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31325}: Fix wrong usage of @ref{1a1,,collections.namedtuple()} in the
@ref{121e,,RobotFileParser.parse()}
method. Initial patch by Robin Wellner.

@item 
bpo-12382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12382}: @ref{106a,,msilib.OpenDatabase()} now raises a better exception
message when it couldn't open or create an MSI file.  Initial patch by
William Tisäter.

@item 
bpo-32110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32110}: @code{codecs.StreamReader.read(n)} now returns not more than @emph{n}
characters/bytes for non-negative @emph{n}. This makes it compatible with
@code{read()} methods of other file-like objects.

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-32034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32034}: Make asyncio.IncompleteReadError and LimitOverrunError
pickleable.

@item 
bpo-32015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32015}: Fixed the looping of asyncio in the case of reconnection the
socket during waiting async read/write from/to the socket.

@item 
bpo-32011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32011}: Restored support of loading marshal files with the TYPE_INT64
code. These files can be produced in Python 2.7.

@item 
bpo-31970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31970}: Reduce performance overhead of asyncio debug mode.

@item 
bpo-9678@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9678}: Fixed determining the MAC address in the uuid module: Using
ifconfig on NetBSD and OpenBSD. Using arp on Linux, FreeBSD, NetBSD and
OpenBSD. Based on patch by Takayuki Shimizukawa.

@item 
bpo-30057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30057}: Fix potential missed signal in signal.signal().

@item 
bpo-31933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31933}: Fix Blake2 params leaf_size and node_offset on big endian
platforms. Patch by Jack O'Connor.

@item 
bpo-31927@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31927}: Fixed compilation of the socket module on NetBSD 8.  Fixed
assertion failure or reading arbitrary data when parse a AF_BLUETOOTH
address on NetBSD and DragonFly BSD.

@item 
bpo-27666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27666}: Fixed stack corruption in curses.box() and curses.ungetmouse()
when the size of types chtype or mmask_t is less than the size of C long.
curses.box() now accepts characters as arguments.  Based on patch by Steve
Fink.

@item 
bpo-31897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31897}: plistlib now catches more errors when read binary plists and
raises InvalidFileException instead of unexpected exceptions.

@item 
bpo-25720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25720}: Fix the method for checking pad state of curses WINDOW. Patch
by Masayuki Yamamoto.

@item 
bpo-31893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31893}: Fixed the layout of the kqueue_event structure on OpenBSD and
NetBSD. Fixed the comparison of the kqueue_event objects.

@item 
bpo-31891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31891}: Fixed building the curses module on NetBSD.

@item 
bpo-28416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28416}: Instances of pickle.Pickler subclass with the persistent_id()
method and pickle.Unpickler subclass with the persistent_load() method no
longer create reference cycles.

@item 
bpo-28326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28326}: Fix multiprocessing.Process when stdout and/or stderr is closed
or None.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: If nested log adapters are used, the inner @code{process()}
methods are no longer omitted.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: The @code{manager} property on LoggerAdapter objects is now
properly settable.

@item 
bpo-31806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31806}: Fix timeout rounding in time.sleep(), threading.Lock.acquire()
and socket.socket.settimeout() to round correctly negative timeouts
between -1.0 and 0.0. The functions now block waiting for events as
expected. Previously, the call was incorrectly non-blocking. Patch by
Pablo Galindo.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: traceback: Fix a TypeError that occurred during printing of
exception tracebacks when either the current exception or an exception in
its context/cause chain is unhashable. Patch by Zane Bitter.

@item 
bpo-30058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30058}: Fixed buffer overflow in select.kqueue.control().

@item 
bpo-31770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31770}: Prevent a crash when calling the @code{__init__()} method of a
@code{sqlite3.Cursor} object more than once. Patch by Oren Milman.

@item 
bpo-31672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31672}: @code{idpattern} in @code{string.Template} matched some non-ASCII
characters. Now it uses @code{-i} regular expression local flag to avoid
non-ASCII characters.

@item 
bpo-31764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31764}: Prevent a crash in @code{sqlite3.Cursor.close()} in case the
@code{Cursor} object is uninitialized. Patch by Oren Milman.

@item 
bpo-31752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31752}: Fix possible crash in timedelta constructor called with custom
integers.

@item 
bpo-31701@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31701}: On Windows, faulthandler.enable() now ignores MSC and COM
exceptions.

@item 
bpo-31728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31728}: Prevent crashes in @code{_elementtree} due to unsafe cleanup of
@code{Element.text} and @code{Element.tail}. Patch by Oren Milman.

@item 
bpo-31620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31620}: an empty asyncio.Queue now doesn't leak memory when queue.get
pollers timeout

@item 
bpo-31632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31632}: Fix method set_protocol() of class _SSLProtocolTransport in
asyncio module. This method was previously modifying a wrong reference to
the protocol.

@item 
bpo-31675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31675}: Fixed memory leaks in Tkinter's methods splitlist() and split()
when pass a string larger than 2 GiB.

@item 
bpo-31673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31673}: Fixed typo in the name of Tkinter's method adderrorinfo().

@item 
bpo-30806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30806}: Fix the string representation of a netrc object.

@item 
bpo-15037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15037}: Added a workaround for getkey() in curses for ncurses 5.7 and
earlier.

@item 
bpo-25351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25351}: Avoid venv activate failures with undefined variables

@item 
bpo-25532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25532}: inspect.unwrap() will now only try to unwrap an object
sys.getrecursionlimit() times, to protect against objects which create a
new object on every attribute access.

@item 
bpo-30347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30347}: Stop crashes when concurrently iterate over itertools.groupby()
iterators.

@item 
bpo-31516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31516}: @code{threading.current_thread()} should not return a dummy thread
at shutdown.

@item 
bpo-31351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31351}: python -m ensurepip now exits with non-zero exit code if pip
bootstrapping has failed.

@item 
bpo-31482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31482}: @code{random.seed()} now works with bytes in version=1

@item 
bpo-31334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31334}: Fix @code{poll.poll([timeout])} in the @code{select} module for
arbitrary negative timeouts on all OSes where it can only be a
non-negative integer or -1. Patch by Riccardo Coccioli.

@item 
bpo-31310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31310}: multiprocessing's semaphore tracker should be launched again if
crashed.

@item 
bpo-31308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31308}: Make multiprocessing's forkserver process immune to Ctrl-C and
other user interruptions. If it crashes, restart it when necessary.
@end itemize

@node Documentation<39>,Tests<39>,Library<50>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id378}@anchor{1261}
@subsubsection Documentation



@itemize -

@item 
bpo-32105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32105}: Added asyncio.BaseEventLoop.connect_accepted_socket
versionadded marker.

@item 
bpo-31537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31537}: Fix incorrect usage of @code{get_history_length} in readline
documentation example code. Patch by Brad Smith.

@item 
bpo-30085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30085}: The operator functions without double underscores are preferred
for clarity. The one with underscores are only kept for
back-compatibility.
@end itemize

@node Tests<39>,Build<38>,Documentation<39>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id379}@anchor{1262}
@subsubsection Tests



@itemize -

@item 
bpo-31380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31380}: Skip test_httpservers test_undecodable_file on macOS: fails on
APFS.

@item 
bpo-31705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31705}: Skip test_socket.test_sha256() on Linux kernel older than 4.5.
The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged
into the kernel 4.5.

@item 
bpo-31174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31174}: Fix test_tools.test_unparse: DirectoryTestCase now stores the
names sample to always test the same files. It prevents false alarms when
hunting reference leaks.

@item 
bpo-30695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30695}: Add the @code{set_nomemory(start, stop)} and @code{remove_mem_hooks()}
functions to the _testcapi module.
@end itemize

@node Build<38>,Windows<39>,Tests<39>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id380}@anchor{1263}
@subsubsection Build



@itemize -

@item 
bpo-32059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32059}: @code{detect_modules()} in @code{setup.py} now also searches the
sysroot paths when cross-compiling.

@item 
bpo-31957@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31957}: Fixes Windows SDK version detection when building for Windows.

@item 
bpo-31609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31609}: Fixes quotes in PCbuild/clean.bat

@item 
bpo-31934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31934}: Abort the build when building out of a not clean source tree.

@item 
bpo-31926@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31926}: Fixed Argument Clinic sometimes causing compilation errors when
there was more than one function and/or method in a .c file with the same
name.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update Windows builds to use SQLite 3.21.0.

@item 
bpo-28791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28791}: Update OS X installer to use SQLite 3.21.0.

@item 
bpo-22140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22140}: Prevent double substitution of prefix in python-config.sh.

@item 
bpo-31536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31536}: Avoid wholesale rebuild after @code{make regen-all} if nothing
changed.
@end itemize

@node Windows<39>,macOS<32>,Build<38>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id381}@anchor{1264}
@subsubsection Windows



@itemize -

@item 
bpo-1102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1102}: Return @code{None} when @code{View.Fetch()} returns
@code{ERROR_NO_MORE_ITEMS} instead of raising @code{MSIError}. Initial patch by
Anthony Tuininga.

@item 
bpo-31944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31944}: Fixes Modify button in Apps and Features dialog.
@end itemize

@node macOS<32>,IDLE<36>,Windows<39>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id382}@anchor{1265}
@subsubsection macOS



@itemize -

@item 
bpo-31392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31392}: Update macOS installer to use OpenSSL 1.0.2m
@end itemize

@node IDLE<36>,Tools/Demos<21>,macOS<32>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id383}@anchor{1266}
@subsubsection IDLE



@itemize -

@item 
bpo-32207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32207}: Improve tk event exception tracebacks in IDLE. When tk event
handling is driven by IDLE's run loop, a confusing and distracting
queue.EMPTY traceback context is no longer added to tk event exception
tracebacks.  The traceback is now the same as when event handling is
driven by user code.  Patch based on a suggestion by Serhiy Storchaka.

@item 
bpo-32164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32164}: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet
in configdialog was replaced by ttk.Notebook.

@item 
bpo-32100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32100}: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch
mostly by Cheryl Sabella.

@item 
bpo-31858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31858}: IDLE -- Restrict shell prompt manipulation to the shell. Editor
and output windows only see an empty last prompt line.  This simplifies
the code and fixes a minor bug when newline is inserted. Sys.ps1, if
present, is read on Shell start-up, but is not set or changed.

@item 
bpo-31860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31860}: The font sample in the IDLE configuration dialog is now
editable. Changes persist while IDLE remains open

@item 
bpo-31836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31836}: Test_code_module now passes if run after test_idle, which sets
ps1. The code module uses sys.ps1 if present or sets it to '>>> ' if not.
Test_code_module now properly tests both behaviors.  Ditto for ps2.

@item 
bpo-28603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28603}: Fix a TypeError that caused a shell restart when printing a
traceback that includes an exception that is unhashable. Patch by Zane
Bitter.

@item 
bpo-13802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13802}: Use non-Latin characters in the IDLE's Font settings sample.
Even if one selects a font that defines a limited subset of the unicode
Basic Multilingual Plane, tcl/tk will use other fonts that define a
character. The expanded example give users of non-Latin characters a
better idea of what they might see in IDLE's shell and editors. To make
room for the expanded sample, frames on the Font tab are re-arranged. The
Font/Tabs help explains a bit about the additions.

@item 
bpo-31460@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31460}: Simplify the API of IDLE's Module Browser. Passing a widget
instead of an flist with a root widget opens the option of creating a
browser frame that is only part of a window.  Passing a full file name
instead of pieces assumed to come from a .py file opens the possibility of
browsing python files that do not end in .py.

@item 
bpo-31649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31649}: IDLE - Make _htest, _utest parameters keyword only.

@item 
bpo-31559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31559}: Remove test order dependence in idle_test.test_browser.

@item 
bpo-31459@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31459}: Rename IDLE's module browser from Class Browser to Module
Browser. The original module-level class and method browser became a
module browser, with the addition of module-level functions, years ago.
Nested classes and functions were added yesterday.  For
back-compatibility, the virtual event <<open-class-browser>>, which
appears on the Keys tab of the Settings dialog, is not changed. Patch by
Cheryl Sabella.

@item 
bpo-31500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31500}: Default fonts now are scaled on HiDPI displays.

@item 
bpo-1612262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1612262}: IDLE module browser now shows nested classes and functions.
Original patches for code and tests by Guilherme Polo and Cheryl Sabella,
respectively.
@end itemize

@node Tools/Demos<21>,C API<30>,IDLE<36>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id384}@anchor{1267}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30722}: Make redemo work with Python 3.6 and newer versions. Also,
remove the @code{LOCALE} option since it doesn't work with string patterns in
Python 3. Patch by Christoph Sarnowski.
@end itemize

@node C API<30>,,Tools/Demos<21>,Python 3 6 4 release candidate 1
@anchor{whatsnew/changelog id385}@anchor{1268}
@subsubsection C API



@itemize -

@item 
bpo-20891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20891}: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in
a non-Python thread before PyEval_InitThreads(), only call
PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

@item 
bpo-31532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31532}: Fix memory corruption due to allocator mix in getpath.c between
Py_GetPath() and Py_SetPath()

@item 
bpo-30697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30697}: The @code{PyExc_RecursionErrorInst} singleton is removed and
@code{PyErr_NormalizeException()} does not use it anymore. This singleton is
persistent and its members being never cleared may cause a segfault during
finalization of the interpreter. See also bpo-22898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22898}.
@end itemize

@node Python 3 6 3 final,Python 3 6 3 release candidate 1,Python 3 6 4 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-3-final}@anchor{1269}
@subsection Python 3.6.3 final


@emph{Release date: 2017-10-03}

@menu
* Library: Library<51>. 
* Build: Build<39>. 

@end menu

@node Library<51>,Build<39>,,Python 3 6 3 final
@anchor{whatsnew/changelog id386}@anchor{126a}
@subsubsection Library



@itemize -

@item 
bpo-31641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31641}: Re-allow arbitrary iterables in
@ref{126b,,concurrent.futures.as_completed()}. Fixes regression in 3.6.3rc1.
@end itemize

@node Build<39>,,Library<51>,Python 3 6 3 final
@anchor{whatsnew/changelog id387}@anchor{126c}
@subsubsection Build



@itemize -

@item 
bpo-31662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31662}: Fix typos in Windows @code{uploadrelease.bat} script. Fix Windows
Doc build issues in @code{Doc/make.bat}.

@item 
bpo-31423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31423}: Fix building the PDF documentation with newer versions of
Sphinx.
@end itemize

@node Python 3 6 3 release candidate 1,Python 3 6 2 final,Python 3 6 3 final,更新日志
@anchor{whatsnew/changelog python-3-6-3-release-candidate-1}@anchor{126d}
@subsection Python 3.6.3 release candidate 1


@emph{Release date: 2017-09-18}

@menu
* Security: Security<27>. 
* Core and Builtins: Core and Builtins<48>. 
* Library: Library<52>. 
* Documentation: Documentation<40>. 
* Tests: Tests<40>. 
* Build: Build<40>. 
* Windows: Windows<40>. 
* IDLE: IDLE<37>. 
* Tools/Demos: Tools/Demos<22>. 

@end menu

@node Security<27>,Core and Builtins<48>,,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id388}@anchor{126e}
@subsubsection Security



@itemize -

@item 
bpo-29781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29781}: SSLObject.version() now correctly returns None when handshake
over BIO has not been performed yet.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.
@end itemize

@node Core and Builtins<48>,Library<52>,Security<27>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id389}@anchor{126f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31471}: Fix an assertion failure in @ref{3e3,,subprocess.Popen()} on Windows, in
case the env argument has a bad keys() method. Patch by Oren Milman.

@item 
bpo-31418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31418}: Fix an assertion failure in @code{PyErr_WriteUnraisable()} in case
of an exception with a bad @code{__module__} attribute. Patch by Oren Milman.

@item 
bpo-31416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31416}: Fix assertion failures in case of a bad warnings.filters or
warnings.defaultaction. Patch by Oren Milman.

@item 
bpo-31411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31411}: Raise a TypeError instead of SystemError in case
warnings.onceregistry is not a dictionary. Patch by Oren Milman.

@item 
bpo-31373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31373}: Fix several possible instances of undefined behavior due to
floating-point demotions.

@item 
bpo-30465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30465}: Location information (@code{lineno} and @code{col_offset}) in
f-strings is now (mostly) correct.  This fixes tools like flake8 from
showing warnings on the wrong line (typically the first line of the file).

@item 
bpo-31343@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31343}: Include sys/sysmacros.h for major(), minor(), and makedev().
GNU C libray plans to remove the functions from sys/types.h.

@item 
bpo-31291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31291}: Fix an assertion failure in @ref{1237,,zipimport.zipimporter.get_data} on
Windows, when the return value of @code{pathname.replace('/','\\')} isn't a
string. Patch by Oren Milman.

@item 
bpo-31271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31271}: Fix an assertion failure in the write() method of
@ref{6f4,,io.TextIOWrapper}, when the encoder doesn't return a bytes object. Patch
by Oren Milman.

@item 
bpo-31243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31243}: Fix a crash in some methods of @ref{6f4,,io.TextIOWrapper}, when the
decoder's state is invalid. Patch by Oren Milman.

@item 
bpo-30721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30721}: @code{print} now shows correct usage hint for using Python 2
redirection syntax.  Patch by Sanyam Khurana.

@item 
bpo-31070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31070}: Fix a race condition in importlib _get_module_lock().

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.

@item 
bpo-31071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31071}: Avoid masking original TypeError in call with * unpacking when
other arguments are passed.

@item 
bpo-30978@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30978}: str.format_map() now passes key lookup exceptions through.
Previously any exception was replaced with a KeyError exception.

@item 
bpo-30808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30808}: Use _Py_atomic API for concurrency-sensitive signal state.

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30703}: Improve signal delivery. Avoid using Py_AddPendingCall from
signal handler, to avoid calling signal-unsafe functions. The tests I'm
adding here fail without the rest of the patch, on Linux and OS X. This
means our signal delivery logic had defects (some signals could be lost).

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-31161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31161}: Make sure the 'Missing parentheses' syntax error message is
only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

@item 
bpo-30814@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30814}: Fixed a race condition when import a submodule from a package.

@item 
bpo-30597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30597}: @code{print} now shows expected input in custom error message when
used as a Python 2 statement. Patch by Sanyam Khurana.
@end itemize

@node Library<52>,Documentation<40>,Core and Builtins<48>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id390}@anchor{1270}
@subsubsection Library



@itemize -

@item 
bpo-31499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31499}: xml.etree: Fix a crash when a parser is part of a reference
cycle.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: typing.get_type_hints now finds the right globalns for classes
and modules by default (when no @code{globalns} was specified by the caller).

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Speed improvements to the @code{typing} module.  Original PRs by
Ivan Levkivskyi and Mitar.

@item 
bpo-31544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31544}: The C accelerator module of ElementTree ignored exceptions
raised when looking up TreeBuilder target methods in XMLParser().

@item 
bpo-31234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31234}: socket.create_connection() now fixes manually a reference
cycle: clear the variable storing the last exception on success.

@item 
bpo-31457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31457}: LoggerAdapter objects can now be nested.

@item 
bpo-31400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31400}: Improves SSL error handling to avoid losing error numbers.

@item 
bpo-28958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28958}: ssl.SSLContext() now uses OpenSSL error information when a
context cannot be instantiated.

@item 
bpo-27340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27340}: SSLSocket.sendall() now uses memoryview to create slices of
data. This fixes support for all bytes-like object. It is also more
efficient and avoids costly copies.

@item 
bpo-31178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31178}: Fix string concatenation bug in rare error path in the
subprocess module

@item 
bpo-31350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31350}: Micro-optimize @code{asyncio._get_running_loop()} to become up
to 10% faster.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}

@item 
bpo-29136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29136}: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

@item 
bpo-29212@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29212}: Fix concurrent.futures.thread.ThreadPoolExecutor threads to
have a non repr() based thread name by default when no thread_name_prefix
is supplied. They will now identify themselves as
"ThreadPoolExecutor-y_n".

@item 
bpo-9146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9146}: Fix a segmentation fault in _hashopenssl when standard hash
functions such as md5 are not available in the linked OpenSSL library.  As
in some special FIPS-140 build environments.

@item 
bpo-27144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27144}: The @code{map()} and @code{as_completed()} iterators in
@code{concurrent.futures} now avoid keeping a reference to yielded objects.

@item 
bpo-10746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10746}: Fix ctypes producing wrong 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} type codes for integer
types.

@item 
bpo-22536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22536}: The subprocess module now sets the filename when
FileNotFoundError is raised on POSIX systems due to the executable or cwd
not being found.

@item 
bpo-31249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31249}: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor
now breaks a reference cycle between an exception object and the WorkItem
object.

@item 
bpo-31247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31247}: xmlrpc.server now explicitly breaks reference cycles when using
sys.exc_info() in code handling exceptions.

@item 
bpo-30102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30102}: The ssl and hashlib modules now call
OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function
detects CPU features and enables optimizations on some CPU architectures
such as POWER8. Patch is based on research from Gustavo Serra Scalet.

@item 
bpo-31185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31185}: Fixed miscellaneous errors in asyncio speedup module.

@item 
bpo-31135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31135}: ttk: fix the destroy() method of LabeledScale and OptionMenu
classes. Call the parent destroy() method even if the used attribute
doesn't exist. The LabeledScale.destroy() method now also explicitly
clears label and scale attributes to help the garbage collector to destroy
all widgets.

@item 
bpo-31107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31107}: Fix @code{copyreg._slotnames()} mangled attribute calculation for
classes whose name begins with an underscore. Patch by Shane Harvey.

@item 
bpo-31061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31061}: Fixed a crash when using asyncio and threads.

@item 
bpo-30502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30502}: Fix handling of long oids in ssl.  Based on patch by Christian
Heimes.

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Dong-hee Na.

@item 
bpo-30595@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30595}: multiprocessing.Queue.get() with a timeout now polls its reader
in non-blocking mode if it succeeded to acquire the lock but the acquire
took longer than the timeout.

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-25684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25684}: Change @code{ttk.OptionMenu} radiobuttons to be unique across
instances of @code{OptionMenu}.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30319}: socket.close() now ignores ECONNRESET error.

@item 
bpo-30828@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30828}: Fix out of bounds write in
@code{asyncio.CFuture.remove_done_callback()}.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.
@end itemize

@node Documentation<40>,Tests<40>,Library<52>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id391}@anchor{1271}
@subsubsection Documentation



@itemize -

@item 
bpo-31294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31294}: Fix incomplete code snippet in the ZeroMQSocketListener and
ZeroMQSocketHandler examples and adapt them to Python 3.

@item 
bpo-21649@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21649}: Add RFC 7525 and Mozilla server side TLS links to SSL
documentation.

@item 
bpo-30803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30803}: Clarify doc on truth value testing. Original patch by Peter
Thomassen.
@end itemize

@node Tests<40>,Build<40>,Documentation<40>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id392}@anchor{1272}
@subsubsection Tests



@itemize -

@item 
bpo-31320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31320}: Silence traceback in test_ssl

@item 
bpo-25674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25674}: Remove sha256.tbs-internet.com ssl test

@item 
bpo-30715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30715}: Address ALPN callback changes for OpenSSL 1.1.0f. The latest
version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: regrtest: Exclude tzdata from regrtest --all. When running the
test suite using --use=all / -u all, exclude tzdata since it makes
test_datetime too slow (15-20 min on some buildbots) which then times out
on some buildbots. Fix also regrtest command line parser to allow passing
-u extralargefile to run test_zipfile64.
@end itemize

@node Build<40>,Windows<40>,Tests<40>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id393}@anchor{1273}
@subsubsection Build



@itemize -

@item 
bpo-30854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30854}: Fix compile error when compiling --without-threads. Patch by
Masayuki Yamamoto.
@end itemize

@node Windows<40>,IDLE<37>,Build<40>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id394}@anchor{1274}
@subsubsection Windows



@itemize -

@item 
bpo-30389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30389}: Adds detection of Visual Studio 2017 to distutils on Windows.

@item 
bpo-31340@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31340}: Change to building with MSVC v141 (included with Visual Studio
2017)

@item 
bpo-30581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30581}: os.cpu_count() now returns the correct number of processors on
Windows when the number of logical processors is greater than 64.

@item 
bpo-30731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30731}: Add a missing xmlns to python.manifest so that it matches the
schema.
@end itemize

@node IDLE<37>,Tools/Demos<22>,Windows<40>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id395}@anchor{1275}
@subsubsection IDLE



@itemize -

@item 
bpo-31493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31493}: IDLE code context -- fix code update and font update timers.
Canceling timers prevents a warning message when test_idle completes.

@item 
bpo-31488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31488}: IDLE - Update non-key options in former extension classes. When
applying configdialog changes, call .reload for each feature class. Change
ParenMatch so updated options affect existing instances attached to
existing editor windows.

@item 
bpo-31477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31477}: IDLE - Improve rstrip entry in doc. Strip trailing whitespace
strips more than blank spaces.  Multiline string literals are not skipped.

@item 
bpo-31480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31480}: IDLE - make tests pass with zzdummy extension disabled by
default.

@item 
bpo-31421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31421}: Document how IDLE runs tkinter programs. IDLE calls tcl/tk
update in the background in order to make live interaction and
experimentation with tkinter applications much easier.

@item 
bpo-31414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31414}: IDLE -- fix tk entry box tests by deleting first. Adding to an
int entry is not the same as deleting and inserting because int('@w{'}) will
fail.

@item 
bpo-31051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31051}: Rearrange IDLE configdialog GenPage into Window, Editor, and
Help sections.

@item 
bpo-30617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30617}: IDLE - Add docstrings and tests for outwin subclass of editor.
Move some data and functions from the class to module level. Patch by
Cheryl Sabella.

@item 
bpo-31287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31287}: IDLE - Do not modify tkinter.message in test_configdialog.

@item 
bpo-27099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27099}: Convert IDLE's built-in 'extensions' to regular features. About
10 IDLE features were implemented as supposedly optional extensions. Their
different behavior could be confusing or worse for users and not good for
maintenance. Hence the conversion. The main difference for users is that
user configurable key bindings for builtin features are now handled
uniformly. Now, editing a binding in a keyset only affects its value in
the keyset. All bindings are defined together in the system-specific
default keysets in config-extensions.def. All custom keysets are saved as
a whole in config-extension.cfg.  All take effect as soon as one clicks
Apply or Ok. The affected events are '<<force-open-completions>>',
'<<expand-word>>', '<<force-open-calltip>>', '<<flash-paren>>',
'<<format-paragraph>>', '<<run-module>>', '<<check-module>>', and
'<<zoom-height>>'.  Any (global) customizations made before 3.6.3 will not
affect their keyset-specific customization after 3.6.3. and vice versa.
Initial patch by Charles Wohlganger.

@item 
bpo-31206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31206}: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by
Cheryl Sabella.

@item 
bpo-31001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31001}: Add tests for configdialog highlight tab.  Patch by Cheryl
Sabella.

@item 
bpo-31205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31205}: IDLE: Factor KeysPage(Frame) class from ConfigDialog.  The
slightly modified tests continue to pass.  Patch by Cheryl Sabella.

@item 
bpo-31130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31130}: IDLE -- stop leaks in test_configdialog. Initial patch by
Victor Stinner.

@item 
bpo-31002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31002}: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

@item 
bpo-19903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19903}: IDLE: Calltips use @ref{65e,,inspect.signature} instead of
@ref{660,,inspect.getfullargspec}. This improves calltips for builtins converted to
use Argument Clinic. Patch by Louie Lu.

@item 
bpo-31083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31083}: IDLE - Add an outline of a TabPage class in configdialog.
Update existing classes to match outline. Initial patch by Cheryl Sabella.

@item 
bpo-31050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31050}: Factor GenPage(Frame) class from ConfigDialog. The slightly
modified tests continue to pass. Patch by Cheryl Sabella.

@item 
bpo-31004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31004}: IDLE - Factor FontPage(Frame) class from ConfigDialog. Slightly
modified tests continue to pass. Fix General tests. Patch mostly by Cheryl
Sabella.

@item 
bpo-30781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30781}: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan
Reedy and Cheryl Sabella.

@item 
bpo-31060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31060}: IDLE - Finish rearranging methods of ConfigDialog Grouping
methods pertaining to each tab and the buttons will aid writing tests and
improving the tabs and will enable splitting the groups into classes.

@item 
bpo-30853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30853}: IDLE -- Factor a VarTrace class out of ConfigDialog. Instance
tracers manages pairs consisting of a tk variable and a callback function.
When tracing is turned on, setting the variable calls the function.  Test
coverage for the new class is 100%.

@item 
bpo-31003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31003}: IDLE: Add more tests for General tab.

@item 
bpo-30993@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30993}: IDLE - Improve configdialog font page and tests. In
configdialog: Document causal pathways in create_font_tab docstring.
Simplify some attribute names. Move set_samples calls to var_changed_font
(idea from Cheryl Sabella).  Move related functions to positions after the
create widgets function. In test_configdialog: Fix test_font_set so not
order dependent.  Fix renamed test_indent_scale so it tests the widget.
Adjust tests for movement of set_samples call.  Add tests for load
functions.  Put all font tests in one class and tab indent tests in
another.  Except for two lines, these tests completely cover the related
functions.

@item 
bpo-30981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30981}: IDLE -- Add more configdialog font page tests.

@item 
bpo-28523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28523}: IDLE: replace 'colour' with 'color' in configdialog.

@item 
bpo-30917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30917}: Add tests for idlelib.config.IdleConf. Increase coverage from
46% to 96%. Patch by Louie Lu.

@item 
bpo-30934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30934}: Document coverage details for idlelib tests. Add section to
idlelib/idle-test/README.txt. Include check that branches are taken both
ways. Exclude IDLE-specific code that does not run during unit tests.

@item 
bpo-30913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30913}: IDLE: Document ConfigDialog tk Vars, methods, and widgets in
docstrings This will facilitate improving the dialog and splitting up the
class. Original patch by Cheryl Sabella.

@item 
bpo-30899@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30899}: IDLE: Add tests for ConfigParser subclasses in config. Patch by
Louie Lu.

@item 
bpo-30881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30881}: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

@item 
bpo-30851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30851}: IDLE: Remove unused variables in configdialog.  One is a
duplicate, one is set but cannot be altered by users. Patch by Cheryl
Sabella.

@item 
bpo-30870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30870}: IDLE: In Settings dialog, select font with Up, Down keys as
well as mouse. Initial patch by Louie Lu.

@item 
bpo-8231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8231}: IDLE: call config.IdleConf.GetUserCfgDir only once.

@item 
bpo-30779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30779}: IDLE: Factor ConfigChanges class from configdialog, put in
config; test. * In config, put dump test code in a function; run it and
unittest in   'if __name__ == '__main__'. * Add class config.ConfigChanges
based on changes_class_v4.py on bpo issue. * Add class
test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise
configdialog to use ConfigChanges; see tracker msg297804. * Revise
test_configdialog to match configdialog changes. * Remove configdialog
functions unused or moved to ConfigChanges. Cheryl Sabella contributed
parts of the patch.

@item 
bpo-30777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30777}: IDLE: configdialog - Add docstrings and fix comments. Patch by
Cheryl Sabella.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: IDLE: Improve textview with docstrings, PEP8 names, and more
tests. Patch by Cheryl Sabella.

@item 
bpo-30723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30723}: IDLE: Make several improvements to parenmatch. Add 'parens'
style to highlight both opener and closer. Make 'default' style, which is
not default, a synonym for 'opener'. Make time-delay work the same with
all styles. Add help for config dialog extensions tab, including help for
parenmatch. Add new tests.  Original patch by Charles Wohlganger.

@item 
bpo-30674@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30674}: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

@item 
bpo-21519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21519}: IDLE's basic custom key entry dialog now detects duplicates
properly. Original patch by Saimadhav Heblikar.

@item 
bpo-29910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29910}: IDLE no longer deletes a character after commenting out a
region by a key shortcut.  Add @code{return 'break'} for this and other
potential conflicts between IDLE and default key bindings.

@item 
bpo-30728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30728}: Review and change idlelib.configdialog names. Lowercase method
and attribute names. Replace 'colour' with 'color', expand overly cryptic
names, delete unneeded underscores. Replace @code{import *} with specific
imports. Patches by Cheryl Sabella.

@item 
bpo-6739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6739}: IDLE: Verify user-entered key sequences by trying to bind them
with tk. Add tests for all 3 validation functions. Original patch by G
Polo.  Tests added by Cheryl Sabella.
@end itemize

@node Tools/Demos<22>,,IDLE<37>,Python 3 6 3 release candidate 1
@anchor{whatsnew/changelog id396}@anchor{1276}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-30983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30983}: gdb integration commands (py-bt, etc.) work on optimized shared
builds now, too.  
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} introduced _PyEval_EvalFrameDefault which
inlines PyEval_EvalFrameEx on non-debug shared builds.  This broke the
ability to use py-bt, py-up, and a few other Python-specific gdb
integrations. The problem is fixed by only looking for
_PyEval_EvalFrameDefault frames in python-gdb.py.  Original patch by Bruno
"Polaco" Penteado.
@end itemize

@node Python 3 6 2 final,Python 3 6 2 release candidate 2,Python 3 6 3 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-2-final}@anchor{1277}
@subsection Python 3.6.2 final


@emph{Release date: 2017-07-17}

No changes since release candidate 2

@node Python 3 6 2 release candidate 2,Python 3 6 2 release candidate 1,Python 3 6 2 final,更新日志
@anchor{whatsnew/changelog python-3-6-2-release-candidate-2}@anchor{1278}
@subsection Python 3.6.2 release candidate 2


@emph{Release date: 2017-07-07}

@menu
* Security: Security<28>. 

@end menu

@node Security<28>,,,Python 3 6 2 release candidate 2
@anchor{whatsnew/changelog id397}@anchor{1279}
@subsubsection Security



@itemize -

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: CVE-2017-9233 (External entity
infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix),
CVE-2016-0718 (Fix regression bugs from 2.2.0's fix to CVE-2016-0718) and
CVE-2012-0876 (Counter hash flooding with SipHash). Note: the
CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn't
impact Python, since Python already gets entropy from the OS to set the
expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).
@end itemize

@node Python 3 6 2 release candidate 1,Python 3 6 1 final,Python 3 6 2 release candidate 2,更新日志
@anchor{whatsnew/changelog python-3-6-2-release-candidate-1}@anchor{127a}
@subsection Python 3.6.2 release candidate 1


@emph{Release date: 2017-06-17}

@menu
* Security: Security<29>. 
* Core and Builtins: Core and Builtins<49>. 
* Library: Library<53>. 
* IDLE: IDLE<38>. 
* C API: C API<31>. 
* Build: Build<41>. 
* Documentation: Documentation<41>. 
* Tools/Demos: Tools/Demos<23>. 
* Tests: Tests<41>. 
* Windows: Windows<41>. 

@end menu

@node Security<29>,Core and Builtins<49>,,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id398}@anchor{127b}
@subsubsection Security



@itemize -

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
CVE-2016-0718 and CVE-2016-4472. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<49>,Library<53>,Security<29>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id399}@anchor{127c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-30682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30682}: Removed a too-strict assertion that failed for certain
f-strings, such as eval("f'\n'") and eval("f'\r'").

@item 
bpo-30604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30604}: Move co_extra_freefuncs to not be per-thread to avoid crashes

@item 
bpo-29104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29104}: Fixed parsing backslashes in f-strings.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-30039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30039}: If a KeyboardInterrupt happens when the interpreter is in the
middle of resuming a chain of nested 'yield from' or 'await' calls, it's
now correctly delivered to the innermost frame.

@item 
bpo-12414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12414}: sys.getsizeof() on a code object now returns the sizes which
includes the code struct and sizes of objects which it references. Patch
by Dong-hee Na.

@item 
bpo-29949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29949}: Fix memory usage regression of set and frozenset object.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-29859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29859}: Show correct error messages when any of the pthread_* calls in
thread_pthread.h fails.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a4a,,OverflowError}.

@item 
bpo-29600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29600}: Fix wrapping coroutine return values in StopIteration.

@item 
bpo-28856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28856}: Fix an oversight that %b format for bytes should support
objects follow the buffer protocol.

@item 
bpo-29714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29714}: Fix a regression that bytes format may fail when containing
zero bytes inside.

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.
@end itemize

@node Library<53>,IDLE<38>,Core and Builtins<49>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id400}@anchor{127d}
@subsubsection Library



@itemize -

@item 
bpo-30616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30616}: Functional API of enum allows to create empty enums. Patched by
Dong-hee Na

@item 
bpo-30038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30038}: Fix race condition between signal delivery and wakeup file
descriptor. Patch by Nathaniel Smith.

@item 
bpo-23894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23894}: lib2to3 now recognizes @code{rb'...'} and @code{f'...'} strings.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Dong-hee
Na.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in imp.load_package(), fixing it for cases
when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-30605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30605}: re.compile() no longer raises a BytesWarning when compiling a
bytes instance with misplaced inline modifier.  Patch by Roy Williams.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup (#2159)

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-29822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29822}: inspect.isabstract() now works during __init_subclass__.  Patch
by Nate Soares.

@item 
bpo-29581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29581}: ABCMeta.__new__ now accepts @code{**kwargs}, allowing abstract
base classes to use keyword parameters in __init_subclass__. Patch by Nate
Soares.

@item 
bpo-30557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30557}: faulthandler now correctly filters and displays exception codes
on Windows

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under @emph{spawn}
and @emph{forkserver} start methods.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-30266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30266}: contextlib.AbstractContextManager now supports
anti-registration by setting __enter__ = None or __exit__ = None,
following the pattern introduced in bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}. Patch by Jelle Zijlstra.

@item 
bpo-30298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30298}: Weaken the condition of deprecation warnings for inline
modifiers. Now allowed several subsequential inline modifiers at the start
of the pattern (e.g. @code{'(?i)(?s)...'}).  In verbose mode whitespaces and
comments now are allowed before and between inline modifiers (e.g. @code{'(?x)
(?i) (?s)...'}).

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Change resulted because of zipfile breakage. (See also:
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094})

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30017}: Allowed calling the close() method of the zip entry writer
object multiple times.  Writing to a closed writer now always produces a
ValueError.

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29953}: Fixed memory leaks in the replace() method of datetime and time
objects when pass out of bound fold argument.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.  Patch by Oren
Milman.

@item 
bpo-28231@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28231}: The zipfile module now accepts path-like objects for external
paths.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: index() and count() methods of collections.abc.Sequence now
check identity before checking equality when do comparisons.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-30177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30177}: path.resolve(strict=False) no longer cuts the path after the
first element not present in the filesystem.  Patch by Antoine Pietri.
@end itemize

@node IDLE<38>,C API<31>,Library<53>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id401}@anchor{127e}
@subsubsection IDLE



@itemize -

@item 
bpo-15786@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15786}: Fix several problems with IDLE's autocompletion box. The
following should now work: clicking on selection box items; using the
scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no
longer happen. Patch by Louie Lu.

@item 
bpo-25514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25514}: Add doc subsubsection about IDLE failure to start. Popup
no-connection message directs users to this section.

@item 
bpo-30642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30642}: Fix reference leaks in IDLE tests. Patches by Louie Lu and
Terry Jan Reedy.

@item 
bpo-30495@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30495}: Add docstrings for textview.py and use PEP8 names. Patches by
Cheryl Sabella and Terry Jan Reedy.

@item 
bpo-30290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30290}: Help-about: use pep8 names and add tests. Increase coverage to
100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

@item 
bpo-30303@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30303}: Add _utest option to textview; add new tests. Increase coverage
to 100%. Patches by Louie Lu and Terry Jan Reedy.
@end itemize

@node C API<31>,Build<41>,IDLE<38>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id402}@anchor{127f}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() no longer replaced with a macro
if Py_LIMITED_API is not set.
@end itemize

@node Build<41>,Documentation<41>,C API<31>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id403}@anchor{1280}
@subsubsection Build



@itemize -

@item 
bpo-29941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29941}: Add @code{--with-assertions} configure flag to explicitly enable C
@code{assert()} checks. Defaults to off. @code{--with-pydebug} implies
@code{--with-assertions}.

@item 
bpo-28787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28787}: Fix out-of-tree builds of Python when configured with
@code{--with--dtrace}.

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.
@end itemize

@node Documentation<41>,Tools/Demos<23>,Build<41>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id404}@anchor{1281}
@subsubsection Documentation



@itemize -

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-30052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30052}: the link targets for @ref{172,,bytes()} and @ref{173,,bytearray()} are
now their respective type definitions, rather than the corresponding
builtin function entries. Use @ref{123a,,bytes} and
@ref{123b,,bytearray} to reference the latter. In order to
ensure this and future cross-reference updates are applied automatically,
the daily documentation builds now disable the default output caching
features in Sphinx.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.
@end itemize

@node Tools/Demos<23>,Tests<41>,Documentation<41>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id405}@anchor{1282}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-29367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29367}: python-gdb.py now supports also @code{method-wrapper}
(@code{wrapperobject}) objects.
@end itemize

@node Tests<41>,Windows<41>,Tools/Demos<23>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id406}@anchor{1283}
@subsubsection Tests



@itemize -

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.
@end itemize

@node Windows<41>,,Tests<41>,Python 3 6 2 release candidate 1
@anchor{whatsnew/changelog id407}@anchor{1284}
@subsubsection Windows



@itemize -

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-30450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30450}: The build process on Windows no longer depends on Subversion,
instead pulling external code from GitHub via a Python script.  If Python
3.6 is not found on the system (via @code{py -3.6}), NuGet is used to
download a copy of 32-bit Python.
@end itemize

@node Python 3 6 1 final,Python 3 6 1 release candidate 1,Python 3 6 2 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-1-final}@anchor{1285}
@subsection Python 3.6.1 final


@emph{Release date: 2017-03-21}

@menu
* Core and Builtins: Core and Builtins<50>. 
* Build: Build<42>. 

@end menu

@node Core and Builtins<50>,Build<42>,,Python 3 6 1 final
@anchor{whatsnew/changelog id408}@anchor{1286}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. The interpreter now consistently avoids ever adding the import
location's parent directory to @code{sys.path}, and ensures no other
@code{sys.path} entries are inadvertently modified when inserting the import
location named on the command line.
@end itemize

@node Build<42>,,Core and Builtins<50>,Python 3 6 1 final
@anchor{whatsnew/changelog id409}@anchor{1287}
@subsubsection Build



@itemize -

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: fix format of git information used in sys.version

@item 
Fix incompatible comment in python.h
@end itemize

@node Python 3 6 1 release candidate 1,Python 3 6 0 final,Python 3 6 1 final,更新日志
@anchor{whatsnew/changelog python-3-6-1-release-candidate-1}@anchor{1288}
@subsection Python 3.6.1 release candidate 1


@emph{Release date: 2017-03-04}

@menu
* Core and Builtins: Core and Builtins<51>. 
* Library: Library<54>. 
* IDLE: IDLE<39>. 
* Windows: Windows<42>. 
* C API: C API<32>. 
* Documentation: Documentation<42>. 
* Tests: Tests<42>. 
* Build: Build<43>. 

@end menu

@node Core and Builtins<51>,Library<54>,,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id410}@anchor{1289}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28893}: Set correct __cause__ for errors about invalid awaitables
returned from __aiter__ and __anext__.

@item 
bpo-29683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29683}: Fixes to memory allocation in _PyCode_SetExtra.  Patch by Brian
Coleman.

@item 
bpo-29684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29684}: Fix minor regression of PyEval_CallObjectWithKeywords. It
should raise TypeError when kwargs is not a dict.  But it might cause segv
when args=NULL and kwargs is not a dict.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29607@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29607}: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by
Matthieu Dartiailh.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29327@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29327}: Fixed a crash when pass the iterable keyword argument to
sorted().

@item 
bpo-29034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29034}: Fix memory leak and use-after-free in os module
(path_converter).

@item 
bpo-29159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29159}: Fix regression in bytes(x) when x.__index__() raises Exception.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-26919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26919}: On Android, operating system data is now always encoded/decoded
to/from UTF-8, instead of the locale encoding to avoid inconsistencies
with os.fsencode() and os.fsdecode() which are already using UTF-8.

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug triggerable by a monkey-patched len() function.

@item 
bpo-28739@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28739}: f-string expressions are no longer accepted as docstrings and
by ast.literal_eval() even if they do not include expressions.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28918}: Fix the cross compilation of xxlimited when Python has been
built with Py_DEBUG defined.

@item 
bpo-28731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28731}: Optimize _PyDict_NewPresized() to create correct size dict.
Improve speed of dict literal with constant keys up to 30%.
@end itemize

@node Library<54>,IDLE<39>,Core and Builtins<51>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id411}@anchor{128a}
@subsubsection Library



@itemize -

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-29623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29623}: Allow use of path-like object as a single argument in
ConfigParser.read(). Patch by David Ellis.

@item 
bpo-28963@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28963}: Fix out of bound iteration in
asyncio.Future.remove_done_callback implemented in C.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29271}: Fix Task.current_task and Task.all_tasks implemented in C to
accept None argument as their pure Python implementation.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-28624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28624}: Add a test that checks that cwd parameter of Popen() accepts
PathLike objects.  Patch by Sayan Chowdhury.

@item 
bpo-28518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28518}: Start a transaction implicitly before a DML statement. Patch by
Aviv Palivoda.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29519}: Fix weakref spewing exceptions during interpreter shutdown when
used with a rare combination of multiprocessing and custom codecs.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29316}: Restore the provisional status of typing module, add
corresponding note to documentation. Patch by Ivan L.

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-29011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29011}: Fix an important omission by adding Deque to the typing module.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-29203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29203}: functools.lru_cache() now respects 
@geindex Python 提高建议; PEP 468
PEP 468@footnote{https://www.python.org/dev/peps/pep-0468} and preserves the
order of keyword arguments.  f(a=1, b=2) is now cached separately from
f(b=2, a=1) since both calls could potentially give different results.

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094}: Offsets in a ZIP file created with extern file object and modes
"w" and "x" now are relative to the start of the file.

@item 
bpo-29085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29085}: Allow random.Random.seed() to use high quality OS randomness
rather than the pid and time.

@item 
bpo-29061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29061}: Fixed bug in secrets.randbelow() which would hang when given a
negative input.  Patch by Brendan Donegan.

@item 
bpo-29079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29079}: Prevent infinite loop in pathlib.resolve() on Windows

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-29119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29119}: Fix weakrefs in the pure python version of
collections.OrderedDict move_to_end() method. Contributed by Andra
Bogildea.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-29055@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29055}: Neaten-up empty population error on random.choice() by
suppressing the upstream exception.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when passing a sequence
that doesn't own its elements as limits.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.

@item 
bpo-26937@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26937}: The chown() method of the tarfile.TarFile class does not fail
now when the grp module cannot be imported, as for example on Android
platforms.
@end itemize

@node IDLE<39>,Windows<42>,Library<54>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id412}@anchor{128b}
@subsubsection IDLE



@itemize -

@item 
bpo-29071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29071}: IDLE colors f-string prefixes (but not invalid ur prefixes).

@item 
bpo-28572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28572}: Add 10% to coverage of IDLE's test_configdialog. Update and
augment description of the configuration system.
@end itemize

@node Windows<42>,C API<32>,IDLE<39>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id413}@anchor{128c}
@subsubsection Windows



@itemize -

@item 
bpo-29579@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29579}: Removes readme.txt from the installer

@item 
bpo-29326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29326}: Ignores blank lines in ._pth files (Patch by Alexey Izbyshev)

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: Correctly handle special console filenames (patch by Eryk Sun)

@item 
bpo-29409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29409}: Implement 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} for io.FileIO (Patch by Eryk Sun)

@item 
bpo-29392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29392}: Prevent crash when passing invalid arguments into msvcrt
module.

@item 
bpo-25778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25778}: winreg does not truncate string correctly (Patch by Eryk Sun)

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder and disable it by default.
@end itemize

@node C API<32>,Documentation<42>,Windows<42>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id414}@anchor{128d}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is replaced with a macro if
Py_LIMITED_API is not set or set to the value between 0x03050400 and
0x03060000 (not including) or 0x03060100 or higher.

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.

@item 
bpo-29058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29058}: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.
@end itemize

@node Documentation<42>,Tests<42>,C API<32>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id415}@anchor{128e}
@subsubsection Documentation



@itemize -

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.
@end itemize

@node Tests<42>,Build<43>,Documentation<42>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id416}@anchor{128f}
@subsubsection Tests



@itemize -

@item 
bpo-28087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28087}: Skip test_asyncore and test_eintr poll failures on macOS. Skip
some tests of select.poll when running on macOS due to unresolved issues
with the underlying system poll function on some macOS versions.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: to match the behaviour of the @code{re.LOCALE} flag,
test_re.test_locale_flag now uses @code{locale.getpreferredencoding(False)}
to determine the candidate encoding for the test regex (allowing it to
correctly skip the test when the default locale encoding is a multi-byte
encoding)

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l in regrtest command line
arguments.

@item 
bpo-28683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28683}: Fix the tests that bind() a unix socket and raise
PermissionError on Android for a non-root user.

@item 
bpo-26939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26939}: Add the support.setswitchinterval() function to fix
test_functools hanging on the Android armv7 qemu emulator.
@end itemize

@node Build<43>,,Tests<42>,Python 3 6 1 release candidate 1
@anchor{whatsnew/changelog id417}@anchor{1290}
@subsubsection Build



@itemize -

@item 
bpo-27593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27593}: sys.version and the platform module python_build(),
python_branch(), and python_revision() functions now use git information
rather than hg when building from a repo.

@item 
bpo-29572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29572}: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

@item 
bpo-26851@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26851}: Set Android compilation and link flags.

@item 
bpo-28768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28768}: Fix implicit declaration of function _setmode. Patch by
Masayuki Yamamoto

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-28762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28762}: lockf() is available on Android API level 24, but the F_LOCK
macro is not defined in android-ndk-r13.

@item 
bpo-28538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28538}: Fix the compilation error that occurs because if_nameindex() is
available on Android API level 24, but the if_nameindex structure is not
defined.

@item 
bpo-20211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20211}: Do not add the directory for installing C header files and the
directory for installing object code libraries to the cross compilation
search paths. Original patch by Thomas Petazzoni.

@item 
bpo-28849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28849}: Do not define sys.implementation._multiarch on Android.
@end itemize

@node Python 3 6 0 final,Python 3 6 0 release candidate 2,Python 3 6 1 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-0-final}@anchor{1291}
@subsection Python 3.6.0 final


@emph{Release date: 2016-12-23}

No changes since release candidate 2

@node Python 3 6 0 release candidate 2,Python 3 6 0 release candidate 1,Python 3 6 0 final,更新日志
@anchor{whatsnew/changelog python-3-6-0-release-candidate-2}@anchor{1292}
@subsection Python 3.6.0 release candidate 2


@emph{Release date: 2016-12-16}

@menu
* Core and Builtins: Core and Builtins<52>. 
* Tools/Demos: Tools/Demos<24>. 
* Windows: Windows<43>. 
* Build: Build<44>. 

@end menu

@node Core and Builtins<52>,Tools/Demos<24>,,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id418}@anchor{1293}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table. Patch written by INADA Naoki.

@item 
bpo-28990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28990}: Fix asyncio SSL hanging if connection is closed before
handshake is completed. (Patch by HoHo-Ho)
@end itemize

@node Tools/Demos<24>,Windows<43>,Core and Builtins<52>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id419}@anchor{1294}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-28770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28770}: Fix python-gdb.py for fastcalls.
@end itemize

@node Windows<43>,Build<44>,Tools/Demos<24>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id420}@anchor{1295}
@subsubsection Windows



@itemize -

@item 
bpo-28896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28896}: Deprecate WindowsRegistryFinder.
@end itemize

@node Build<44>,,Windows<43>,Python 3 6 0 release candidate 2
@anchor{whatsnew/changelog id421}@anchor{1296}
@subsubsection Build



@itemize -

@item 
bpo-28898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28898}: Prevent gdb build errors due to HAVE_LONG_LONG redefinition.
@end itemize

@node Python 3 6 0 release candidate 1,Python 3 6 0 beta 4,Python 3 6 0 release candidate 2,更新日志
@anchor{whatsnew/changelog python-3-6-0-release-candidate-1}@anchor{1297}
@subsection Python 3.6.0 release candidate 1


@emph{Release date: 2016-12-06}

@menu
* Core and Builtins: Core and Builtins<53>. 
* Library: Library<55>. 
* C API: C API<33>. 
* Documentation: Documentation<43>. 
* Tools/Demos: Tools/Demos<25>. 

@end menu

@node Core and Builtins<53>,Library<55>,,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id422}@anchor{1298}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: Rather than silently producing a class that doesn't support
zero-argument @code{super()} in methods, failing to pass the new
@code{__classcell__} namespace entry up to @code{type.__new__} now results in a
@code{DeprecationWarning} and a class that supports zero-argument
@code{super()}.

@item 
bpo-28797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28797}: Modifying the class __dict__ inside the __set_name__ method of
a descriptor that is used inside that class no longer prevents calling the
__set_name__ method of other descriptors.

@item 
bpo-28782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28782}: Fix a bug in the implementation @code{yield from} when checking if
the next instruction is YIELD_FROM. Regression introduced by WORDCODE
(bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}).
@end itemize

@node Library<55>,C API<33>,Core and Builtins<53>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id423}@anchor{1299}
@subsubsection Library



@itemize -

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes in re.sub() replacement template are allowed
again.  But they still are deprecated and will be disabled in 3.7.

@item 
bpo-28835@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28835}: Fix a regression introduced in warnings.catch_warnings(): call
warnings.showwarning() if it was overridden inside the context manager.

@item 
bpo-27172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27172}: To assist with upgrades from 2.7, the previously documented
deprecation of @code{inspect.getfullargspec()} has been reversed. This
decision may be revisited again after the Python 2.7 branch is no longer
officially supported.

@item 
bpo-26273@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26273}: Add new @code{socket.TCP_CONGESTION} (Linux 2.6.13) and
@code{socket.TCP_USER_TIMEOUT} (Linux 2.6.37) constants. Patch written by
Omar Sandoval.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left configparser in an invalid
state. Original patch by Florian Höch.

@item 
bpo-28843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28843}: Fix asyncio C Task to handle exceptions __traceback__.
@end itemize

@node C API<33>,Documentation<43>,Library<55>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id424}@anchor{129a}
@subsubsection C API



@itemize -

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.
@end itemize

@node Documentation<43>,Tools/Demos<25>,C API<33>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id425}@anchor{129b}
@subsubsection Documentation



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The data model reference and the porting section in the What's
New guide now cover the additional @code{__classcell__} handling needed for
custom metaclasses to fully support 
@geindex Python 提高建议; PEP 487
PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} and zero-argument
@code{super()}.
@end itemize

@node Tools/Demos<25>,,Documentation<43>,Python 3 6 0 release candidate 1
@anchor{whatsnew/changelog id426}@anchor{129c}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-28023@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28023}: Fix python-gdb.py didn't support new dict implementation.
@end itemize

@node Python 3 6 0 beta 4,Python 3 6 0 beta 3,Python 3 6 0 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-6-0-beta-4}@anchor{129d}
@subsection Python 3.6.0 beta 4


@emph{Release date: 2016-11-21}

@menu
* Core and Builtins: Core and Builtins<54>. 
* Library: Library<56>. 
* Documentation: Documentation<44>. 
* Tests: Tests<43>. 
* Build: Build<45>. 

@end menu

@node Core and Builtins<54>,Library<56>,,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id427}@anchor{129e}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28532}: Show sys.version when -V option is supplied twice.

@item 
bpo-27100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27100}: The with-statement now checks for __enter__ before it checks
for __exit__. This gives less confusing error messages when both methods
are missing. Patch by Jonathan Ellington.

@item 
bpo-28746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28746}: Fix the set_inheritable() file descriptor method on platforms
that do not have the ioctl FIOCLEX and FIONCLEX commands.

@item 
bpo-26920@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26920}: Fix not getting the locale's charset upon initializing the
interpreter, on platforms that do not have langinfo.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28665}: Improve speed of the STORE_DEREF opcode by 40%.

@item 
bpo-28583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28583}: PyDict_SetDefault didn't combine split table when needed. Patch
by Xiang Zhang.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Change PendingDeprecationWarning -> DeprecationWarning. As it
was agreed in the issue, __aiter__ returning an awaitable should result in
PendingDeprecationWarning in 3.5 and in DeprecationWarning in 3.6.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Fix a refleak in code that raises DeprecationWarning.

@item 
bpo-28721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28721}: Fix asynchronous generators aclose() and athrow() to handle
StopAsyncIteration propagation properly.
@end itemize

@node Library<56>,Documentation<44>,Core and Builtins<54>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id428}@anchor{129f}
@subsubsection Library



@itemize -

@item 
bpo-28752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28752}: Restored the __reduce__() methods of datetime objects.

@item 
bpo-28727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28727}: Regular expression patterns, _sre.SRE_Pattern objects created
by re.compile(), become comparable (only x==y and x!=y operators). This
change should fix the bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: don't duplicate warning filters when
the warnings module is reloaded (thing usually only done in unit tests).

@item 
bpo-20572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20572}: The subprocess.Popen.wait method's undocumented endtime
parameter now raises a DeprecationWarning.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-19717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19717}: Makes Path.resolve() succeed on paths that do not exist. Patch
by Vajrasky Kok

@item 
bpo-28563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28563}: Fixed possible DoS and arbitrary code execution when handle
plural form selections in the gettext module.  The expression parser now
supports exact syntax supported by GNU gettext.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-28600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28600}: Optimize loop.call_soon.

@item 
bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}: Fix get_event_loop() return the current loop if called from
coroutines/callbacks.

@item 
bpo-28634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28634}: Fix asyncio.isfuture() to support unittest.Mock.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Fix refleak in _asyncio.Future.__iter__().throw.

@item 
bpo-28639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28639}: Fix inspect.isawaitable to always return bool Patch by Justin
Mayfield.

@item 
bpo-28652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28652}: Make loop methods reject socket kinds they do not support.

@item 
bpo-28653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28653}: Fix a refleak in functools.lru_cache.

@item 
bpo-28703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28703}: Fix asyncio.iscoroutinefunction to handle Mock objects.

@item 
bpo-28704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28704}: Fix create_unix_server to support Path-like objects (PEP 519).

@item 
bpo-28720@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28720}: Add collections.abc.AsyncGenerator.
@end itemize

@node Documentation<44>,Tests<43>,Library<56>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id429}@anchor{12a0}
@subsubsection Documentation



@itemize -

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node Tests<43>,Build<45>,Documentation<44>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id430}@anchor{12a1}
@subsubsection Tests



@itemize -

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.
@end itemize

@node Build<45>,,Tests<43>,Python 3 6 0 beta 4
@anchor{whatsnew/changelog id431}@anchor{12a2}
@subsubsection Build



@itemize -

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Python 3 6 0 beta 3,Python 3 6 0 beta 2,Python 3 6 0 beta 4,更新日志
@anchor{whatsnew/changelog python-3-6-0-beta-3}@anchor{12a3}
@subsection Python 3.6.0 beta 3


@emph{Release date: 2016-10-31}

@menu
* Core and Builtins: Core and Builtins<55>. 
* Library: Library<57>. 
* Windows: Windows<44>. 
* Build: Build<46>. 
* Tests: Tests<44>. 

@end menu

@node Core and Builtins<55>,Library<57>,,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id432}@anchor{12a4}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28128}: Deprecation warning for invalid str and byte escape sequences
now prints better information about where the error occurs. Patch by
Serhiy Storchaka and Eric Smith.

@item 
bpo-28509@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28509}: dict.update() no longer allocate unnecessary large memory.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-28517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28517}: Fixed of-by-one error in the peephole optimizer that caused
keeping unreachable code.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Improved exception reporting for problematic __set_name__
attributes.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28471}: Fix "Python memory allocator called without holding the GIL"
crash in socket.setblocking.
@end itemize

@node Library<57>,Windows<44>,Core and Builtins<55>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id433}@anchor{12a5}
@subsubsection Library



@itemize -

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: The various ways of specifying weights for random.choices() now
produce the same result sequences.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar().prmonth() no longer prints a space at
the start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-28430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28430}: Fix iterator of C implemented asyncio.Future doesn't accept
non-None value is passed to it.send(val).

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets now start by the "!" prefix
for readability.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer adds entry "./" to ZIP archive.

@item 
bpo-25953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25953}: re.sub() now raises an error for invalid numerical group
reference in replacement template even if the pattern is not found in the
string.  Error message for invalid group reference now includes the group
index and the position of the reference. Based on patch by SilentGhost.

@item 
bpo-18219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18219}: Optimize csv.DictWriter for large number of columns. Patch by
Mariatta Wijaya.

@item 
bpo-28448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28448}: Fix C implemented asyncio.Future didn't work on Windows.

@item 
bpo-28480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28480}: Fix error building socket module when multithreading is
disabled.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-28492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28492}: Fix how StopIteration exception is raised in _asyncio.Future.

@item 
bpo-28500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28500}: Fix asyncio to handle async gens GC from another thread.

@item 
bpo-26923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26923}: Fix asyncio.Gather to refuse being cancelled once all children
are done. Patch by Johannes Ebke.

@item 
bpo-26796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26796}: Don't configure the number of workers for default threadpool
executor. Initial patch by Hans Lawrenz.

@item 
bpo-28544@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28544}: Implement asyncio.Task in C.
@end itemize

@node Windows<44>,Build<46>,Library<57>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id434}@anchor{12a6}
@subsubsection Windows



@itemize -

@item 
bpo-28522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28522}: Fixes mishandled buffer reallocation in getpathp.c
@end itemize

@node Build<46>,Tests<44>,Windows<44>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id435}@anchor{12a7}
@subsubsection Build



@itemize -

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28208@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28208}: Update Windows build and OS X installers to use SQLite 3.14.2.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.
@end itemize

@node Tests<44>,,Build<46>,Python 3 6 0 beta 3
@anchor{whatsnew/changelog id436}@anchor{12a8}
@subsubsection Tests



@itemize -

@item 
bpo-26944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26944}: Fix test_posix for Android where 'id -G' is entirely wrong or
missing the effective gid.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.
@end itemize

@node Python 3 6 0 beta 2,Python 3 6 0 beta 1,Python 3 6 0 beta 3,更新日志
@anchor{whatsnew/changelog python-3-6-0-beta-2}@anchor{12a9}
@subsection Python 3.6.0 beta 2


@emph{Release date: 2016-10-10}

@menu
* Core and Builtins: Core and Builtins<56>. 
* Library: Library<58>. 
* Windows: Windows<45>. 
* C API: C API<34>. 
* Build: Build<47>. 
* Tests: Tests<45>. 

@end menu

@node Core and Builtins<56>,Library<58>,,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id437}@anchor{12aa}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-28183@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28183}: Optimize and cleanup dict iteration.

@item 
bpo-26081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26081}: Added C implementation of asyncio.Future. Original patch by
Yury Selivanov.

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: Creating instances of range_iterator by calling range_iterator
type now is deprecated.  Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The constructor of range_iterator now checks that step is not
0. Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28201}: Dict reduces possibility of 2nd conflict in hash table when
hashes have same lower bits.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in complex(1.0, @{2:3@}) error message. Patch
by Soumya Sharma.

@item 
bpo-28086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28086}: Single var-positional argument of tuple subtype was passed
unscathed to the C-defined function.  Now it is converted to exact tuple.

@item 
bpo-28214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28214}: Now __set_name__ is looked up on the class instead of the
instance.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28192}: Don't import readline in isolated mode.

@item 
Upgrade internal unicode databases to Unicode version 9.0.0.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-28126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28126}: Replace Py_MEMCPY with memcpy(). Visual Studio can properly
optimize memcpy().

@item 
bpo-28120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28120}: Fix dict.pop() for splitted dictionary when trying to remove a
"pending key" (Not yet inserted in split-table). Patch by Xiang Zhang.

@item 
bpo-26182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26182}: Raise DeprecationWarning when async and await keywords are used
as variable/attribute/class/function name.
@end itemize

@node Library<58>,Windows<45>,Core and Builtins<56>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id438}@anchor{12ab}
@subsubsection Library



@itemize -

@item 
bpo-27998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27998}: Fixed bytes path support in os.scandir() on Windows. Patch by
Eryk Sun.

@item 
bpo-28317@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28317}: The disassembler now decodes FORMAT_VALUE argument.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Fixed writing ZIP files that starts not from the start of the
file.  Offsets in ZIP file now are relative to the start of the archive in
conforming to the specification.

@item 
bpo-28380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28380}: unittest.mock Mock autospec functions now properly support
assert_called, assert_not_called, and assert_called_once.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: remove statistics.geometric_mean and defer until 3.7.

@item 
bpo-28229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28229}: lzma module now supports pathlib.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28225}: bz2 module now supports pathlib.  Initial patch by Ethan
Furman.

@item 
bpo-28227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28227}: gzip now supports pathlib.  Patch by Ethan Furman.

@item 
bpo-27358@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27358}: Optimized merging var-keyword arguments and improved error
message when passing a non-mapping as a var-keyword argument.

@item 
bpo-28257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28257}: Improved error message when passing a non-iterable as a
var-positional argument.  Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
bpo-28228@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28228}: imghdr now supports pathlib.

@item 
bpo-28226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28226}: compileall now supports pathlib.

@item 
bpo-28314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28314}: Fix function declaration (C flags) for the getiterator() method
of xml.etree.ElementTree.Element.

@item 
bpo-28148@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28148}: Stop using localtime() and gmtime() in the time module.
Introduced platform independent _PyTime_localtime API that is similar to
POSIX localtime_r, but available on all platforms.  Patch by Ed Schouten.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: random.choices() now has k as a keyword-only argument to
improve the readability of common cases and come into line with the
signature used in other languages.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.
Added the master parameter in the DisplayStyle constructor.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow falsy values to be used for msg parameter of subTest().

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Fix a memory leak in os.getrandom() when the getrandom() is
interrupted by a signal and a signal handler raises a Python exception.

@item 
bpo-28200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28200}: Fix memory leak on Windows in the os module (fix
path_converter() function).

@item 
bpo-25400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25400}: RobotFileParser now correctly returns default values for
crawl_delay and request_rate.  Initial patch by Peter Wirtz.

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Warning message emitted by using inline flags in the middle of
regular expression now contains a (truncated) regex pattern. Patch by Tim
Graham.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-28114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28114}: Fix a crash in parse_envlist() when env contains byte strings.
Patch by Eryk Sun.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.
@end itemize

@node Windows<45>,C API<34>,Library<58>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id439}@anchor{12ac}
@subsubsection Windows



@itemize -

@item 
bpo-28402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28402}: Adds signed catalog files for stdlib on Windows.

@item 
bpo-28333@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28333}: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk
Sun)

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-28161@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28161}: Opening CON for write access fails

@item 
bpo-28162@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28162}: WindowsConsoleIO readall() fails if first line starts with
Ctrl+Z

@item 
bpo-28163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28163}: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

@item 
bpo-28164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28164}: _PyIO_get_console_type fails for various paths

@item 
bpo-28137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28137}: Renames Windows path file to ._pth

@item 
bpo-28138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28138}: Windows ._pth file should allow import site
@end itemize

@node C API<34>,Build<47>,Windows<45>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id440}@anchor{12ad}
@subsubsection C API



@itemize -

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Deprecated undocumented functions PyUnicode_AsEncodedObject(),
PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and
PyUnicode_AsEncodedUnicode().
@end itemize

@node Build<47>,Tests<45>,C API<34>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id441}@anchor{12ae}
@subsubsection Build



@itemize -

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.
@end itemize

@node Tests<45>,,Build<47>,Python 3 6 0 beta 2
@anchor{whatsnew/changelog id442}@anchor{12af}
@subsubsection Tests



@itemize -

@item 
bpo-28217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28217}: Adds _testconsole module to test console input.
@end itemize

@node Python 3 6 0 beta 1,Python 3 6 0 alpha 4,Python 3 6 0 beta 2,更新日志
@anchor{whatsnew/changelog python-3-6-0-beta-1}@anchor{12b0}
@subsection Python 3.6.0 beta 1


@emph{Release date: 2016-09-12}

@menu
* Core and Builtins: Core and Builtins<57>. 
* Library: Library<59>. 
* IDLE: IDLE<40>. 
* C API: C API<35>. 
* Tests: Tests<46>. 
* Build: Build<48>. 
* Tools/Demos: Tools/Demos<26>. 
* Windows: Windows<46>. 

@end menu

@node Core and Builtins<57>,Library<59>,,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id443}@anchor{12b1}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23722}: The __class__ cell used by zero-argument super() is now
initialized from type.__new__ rather than __build_class__, so class
methods relying on that will now work correctly when called from metaclass
methods during class creation. Patch by Martin Teichmann.

@item 
bpo-25221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25221}: Fix corrupted result from PyLong_FromLong(0) when Python is
compiled with NSMALLPOSINTS = 0.

@item 
bpo-27080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27080}: Implement formatting support for 
@geindex Python 提高建议; PEP 515
PEP 515@footnote{https://www.python.org/dev/peps/pep-0515}.  Initial patch by
Chris Angelico.

@item 
bpo-27199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27199}: In tarfile, expose copyfileobj bufsize to improve throughput.
Patch by Jason Fried.

@item 
bpo-27948@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27948}: In f-strings, only allow backslashes inside the braces (where
the expressions are).  This is a breaking change from the 3.6 alpha
releases, where backslashes are allowed anywhere in an f-string.  Also,
require that expressions inside f-strings be enclosed within literal
braces, and not escapes like @code{f'\x7b"hi"\x7d'}.

@item 
bpo-28046@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28046}: Remove platform-specific directories from sys.path.

@item 
bpo-28071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28071}: Add early-out for differencing from an empty set.

@item 
bpo-25758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25758}: Prevents zipimport from unnecessarily encoding a filename
(patch by Eryk Sun)

@item 
bpo-25856@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25856}: The __module__ attribute of extension classes and functions now
is interned. This leads to more compact pickle data with protocol 4.

@item 
bpo-27213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27213}: Rework CALL_FUNCTION* opcodes to produce shorter and more
efficient bytecode. Patch by Demur Rumed, design by Serhiy Storchaka,
reviewed by Serhiy Storchaka and Victor Stinner.

@item 
bpo-26331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26331}: Implement tokenizing support for 
@geindex Python 提高建议; PEP 515
PEP 515@footnote{https://www.python.org/dev/peps/pep-0515}. Patch by Georg
Brandl.

@item 
bpo-27999@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27999}: Make "global after use" a SyntaxError, and ditto for nonlocal.
Patch by Ivan Levkivskyi.

@item 
bpo-28003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28003}: Implement 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525} -- Asynchronous Generators.

@item 
bpo-27985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27985}: Implement 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} -- Syntax for Variable Annotations. Patch
by Ivan Levkivskyi.

@item 
bpo-26058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26058}: Add a new private version to the builtin dict type, incremented
at each dictionary creation and at each dictionary change. Implementation
of the PEP 509.

@item 
bpo-27364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27364}: A backslash-character pair that is not a valid escape sequence
now generates a DeprecationWarning.  Patch by Emanuel Barry.

@item 
bpo-27350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27350}: @ref{164,,dict} implementation is changed like PyPy. It is more compact
and preserves insertion order. (Concept developed by Raymond Hettinger and
patch by Inada Naoki.)

@item 
bpo-27911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27911}: Remove unnecessary error checks in
@code{exec_builtin_or_dynamic()}.

@item 
bpo-27078@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27078}: Added BUILD_STRING opcode.  Optimized f-strings evaluation.

@item 
bpo-17884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17884}: Python now requires systems with inttypes.h and stdint.h

@item 
bpo-27961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27961}: Require platforms to support @code{long long}. Python hasn't
compiled without @code{long long} for years, so this is basically a
formality.

@item 
bpo-27355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27355}: Removed support for Windows CE.  It was never finished, and
Windows CE is no longer a relevant platform for Python.

@item 
Implement 
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523}.

@item 
bpo-27870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27870}: A left shift of zero by a large integer no longer attempts to
allocate large amounts of memory.

@item 
bpo-25402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25402}: In int-to-decimal-string conversion, improve the estimate of
the intermediate memory required, and remove an unnecessarily strict
overflow check. Patch by Serhiy Storchaka.

@item 
bpo-27214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27214}: In long_invert, be more careful about modifying object returned
by long_add, and remove an unnecessary check for small longs. Thanks Oren
Milman for analysis and patch.

@item 
bpo-27506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27506}: Support passing the bytes/bytearray.translate() "delete"
argument by keyword.

@item 
bpo-27812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27812}: Properly clear out a generator's frame's backreference to the
generator to prevent crashes in frame.clear().

@item 
bpo-27811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27811}: Fix a crash when a coroutine that has not been awaited is
finalized with warnings-as-errors enabled.

@item 
bpo-27587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27587}: Fix another issue found by PVS-Studio: Null pointer check after
use of 'def' in _PyState_AddModule(). Initial patch by Christian Heimes.

@item 
bpo-27792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27792}: The modulo operation applied to @code{bool} and other @code{int}
subclasses now always returns an @code{int}. Previously the return type
depended on the input values. Patch by Xiang Zhang.

@item 
bpo-26984@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26984}: int() now always returns an instance of exact int.

@item 
bpo-25604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25604}: Fix a minor bug in integer true division; this bug could
potentially have caused off-by-one-ulp results on platforms with
unreliable ldexp implementations.

@item 
bpo-24254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24254}: Make class definition namespace ordered by default.

@item 
bpo-27662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27662}: Fix an overflow check in @code{List_New}: the original code was
checking against @code{Py_SIZE_MAX} instead of the correct upper bound of
@code{Py_SSIZE_T_MAX}. Patch by Xiang Zhang.

@item 
bpo-27782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27782}: Multi-phase extension module import now correctly allows the
@code{m_methods} field to be used to add module level functions to instances
of non-module types returned from @code{Py_create_mod}. Patch by Xiang Zhang.

@item 
bpo-27936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27936}: The round() function accepted a second None argument for some
types but not for others.  Fixed the inconsistency by accepting None for
all numeric types.

@item 
bpo-27487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27487}: Warn if a submodule argument to "python -m" or
runpy.run_module() is found in sys.modules after parent packages are
imported, but before the submodule is executed.

@item 
bpo-27157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27157}: Make only type() itself accept the one-argument form. Patch by
Eryk Sun and Emanuel Barry.

@item 
bpo-27558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27558}: Fix a SystemError in the implementation of "raise" statement.
In a brand new thread, raise a RuntimeError since there is no active
exception to reraise. Patch written by Xiang Zhang.

@item 
bpo-28008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28008}: Implement 
@geindex Python 提高建议; PEP 530
PEP 530@footnote{https://www.python.org/dev/peps/pep-0530} -- asynchronous comprehensions.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: Fix memory leak in codeobject.c
@end itemize

@node Library<59>,IDLE<40>,Core and Builtins<57>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id444}@anchor{12b2}
@subsubsection Library



@itemize -

@item 
bpo-28732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28732}: Fix crash in os.spawnv() with no elements in args

@item 
bpo-28485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28485}: Always raise ValueError for negative
compileall.compile_dir(workers=...) parameter, even when multithreading is
unavailable.

@item 
bpo-28037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28037}: Use sqlite3_get_autocommit() instead of setting
Connection->inTransaction manually.

@item 
bpo-25283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25283}: Attributes tm_gmtoff and tm_zone are now available on all
platforms in the return values of time.localtime() and time.gmtime().

@item 
bpo-24454@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24454}: Regular expression match object groups are now accessible using
__getitem__. "mo[x]" is equivalent to "mo.group(x)".

@item 
bpo-10740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10740}: sqlite3 no longer implicitly commit an open transaction before
DDL statements.

@item 
bpo-17941@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17941}: Add a @emph{module} parameter to collections.namedtuple().

@item 
bpo-22493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22493}: Inline flags now should be used only at the start of the
regular expression. Deprecation warning is emitted if uses them in the
middle of the regular expression.

@item 
bpo-26885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26885}: xmlrpc now supports unmarshalling additional data types used by
Apache XML-RPC implementation for numerics and None.

@item 
bpo-28070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28070}: Fixed parsing inline verbose flag in regular expressions.

@item 
bpo-19500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19500}: Add client-side SSL session resumption to the ssl module.

@item 
bpo-28022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28022}: Deprecate ssl-related arguments in favor of SSLContext. The
deprecation include manual creation of SSLSocket and certfile/keyfile (or
similar) in ftplib, httplib, imaplib, smtplib, poplib and urllib.

@item 
bpo-28043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28043}: SSLContext has improved default settings: OP_NO_SSLv2,
OP_NO_SSLv3, OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE,
OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE and HIGH ciphers without MD5.

@item 
bpo-24693@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24693}: Changed some RuntimeError's in the zipfile module to more
appropriate types. Improved some error messages and debugging output.

@item 
bpo-17909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17909}: @code{json.load} and @code{json.loads} now support binary input
encoded as UTF-8, UTF-16 or UTF-32. Patch by Serhiy Storchaka.

@item 
bpo-27137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27137}: the pure Python fallback implementation of
@code{functools.partial} now matches the behaviour of its accelerated C
counterpart for subclassing, pickling and text representation purposes.
Patch by Emanuel Barry and Serhiy Storchaka.

@item 
Fix possible integer overflows and crashes in the mmap module with unusual
usage patterns.

@item 
bpo-1703178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1703178}: Fix the ability to pass the --link-objects option to the
distutils build_ext command.

@item 
bpo-28019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28019}: itertools.count() no longer rounds non-integer step in range
between 1.0 and 2.0 to 1.

@item 
bpo-18401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18401}: Pdb now supports the 'readrc' keyword argument to control
whether .pdbrc files should be read.  Patch by Martin Matusiak and Sam
Kimbrel.

@item 
bpo-25969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25969}: Update the lib2to3 grammar to handle the unpacking
generalizations added in 3.5.

@item 
bpo-14977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14977}: mailcap now respects the order of the lines in the mailcap
files ("first match"), as required by RFC 1542.  Patch by Michael Lazar.

@item 
bpo-28082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28082}: Convert re flag constants to IntFlag.

@item 
bpo-28025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28025}: Convert all ssl module constants to IntEnum and IntFlags.
SSLContext properties now return flags and enums.

@item 
bpo-23591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23591}: Add Flag, IntFlag, and auto() to enum module.

@item 
bpo-433028@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=433028}: Added support of modifier spans in regular expressions.

@item 
bpo-24594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24594}: Validates persist parameter when opening MSI database

@item 
bpo-17582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17582}: xml.etree.ElementTree nows preserves whitespaces in attributes
(Patch by Duane Griffin.  Reviewed and approved by Stefan Behnel.)

@item 
bpo-28047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28047}: Fixed calculation of line length used for the base64 CTE in the
new email policies.

@item 
bpo-27576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27576}: Fix call order in OrderedDict.__init__().

@item 
email.generator.DecodedGenerator now supports the policy keyword.

@item 
bpo-28027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28027}: Remove undocumented modules from @code{Lib/plat-*}: IN, CDROM,
DLFCN, TYPES, CDIO, and STROPTS.

@item 
bpo-27445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27445}: Don't pass str(_charset) to MIMEText.set_payload(). Patch by
Claude Paroz.

@item 
bpo-24277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24277}: The new email API is no longer provisional, and the docs have
been reorganized and rewritten to emphasize the new API.

@item 
bpo-22450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22450}: urllib now includes an @code{Accept: */*} header among the default
headers. This makes the results of REST API requests more consistent and
predictable especially when proxy servers are involved.

@item 
lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
between runs given the same Grammar.txt input regardless of the hash
randomization setting.

@item 
bpo-28005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28005}: Allow ImportErrors in encoding implementation to propagate.

@item 
bpo-26667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26667}: Support path-like objects in importlib.util.

@item 
bpo-27570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27570}: Avoid zero-length memcpy() etc calls with null source pointers
in the "ctypes" and "array" modules.

@item 
bpo-22233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22233}: Break email header lines @emph{only} on the RFC specified CR and LF
characters, not on arbitrary unicode line breaks.  This also fixes a bug
in HTTP header parsing.

@item 
bpo-27331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27331}: The email.mime classes now all accept an optional policy
keyword.

@item 
bpo-27988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27988}: Fix email iter_attachments incorrect mutation of payload list.

@item 
bpo-16113@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16113}: Add SHA-3 and SHAKE support to hashlib module.

@item 
Eliminate a tautological-pointer-compare warning in _scproxy.c.

@item 
bpo-27776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27776}: The @ref{5d4,,os.urandom()} function does now block on Linux 3.17
and newer until the system urandom entropy pool is initialized to increase
the security. This change is part of the 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524}.

@item 
bpo-27778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27778}: Expose the Linux @code{getrandom()} syscall as a new
@ref{66c,,os.getrandom()} function. This change is part of the 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524}.

@item 
bpo-27691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27691}: Fix ssl module's parsing of GEN_RID subject alternative name
fields in X.509 certs.

@item 
bpo-18844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18844}: Add random.choices().

@item 
bpo-25761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25761}: Improved error reporting about truncated pickle data in C
implementation of unpickler.  UnpicklingError is now raised instead of
AttributeError and ValueError in some cases.

@item 
bpo-26798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26798}: Add BLAKE2 (blake2b and blake2s) to hashlib.

@item 
bpo-26032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26032}: Optimized globbing in pathlib by using os.scandir(); it is now
about 1.5--4 times faster.

@item 
bpo-25596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25596}: Optimized glob() and iglob() functions in the glob module; they
are now about 3--6 times faster.

@item 
bpo-27928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27928}: Add scrypt (password-based key derivation function) to hashlib
module (requires OpenSSL 1.1.0).

@item 
bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850}: Remove 3DES from ssl module's default cipher list to counter
measure sweet32 attack (CVE-2016-2183).

@item 
bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}: Add ChaCha20 Poly1305 to ssl module's default cipher list.
(Required OpenSSL 1.1.0 or LibreSSL).

@item 
bpo-25387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25387}: Check return value of winsound.MessageBeep.

@item 
bpo-27866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27866}: Add SSLContext.get_ciphers() method to get a list of all
enabled ciphers.

@item 
bpo-27744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27744}: Add AF_ALG (Linux Kernel crypto) to socket module.

@item 
bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}: Port ssl and hashlib module to OpenSSL 1.1.0.

@item 
bpo-11620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11620}: Fix support for SND_MEMORY in winsound.PlaySound.  Based on a
patch by Tim Lesher.

@item 
bpo-11734@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11734}: Add support for IEEE 754 half-precision floats to the struct
module. Based on a patch by Eli Stevens.

@item 
bpo-27919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27919}: Deprecated @code{extra_path} distribution option in distutils
packaging.

@item 
bpo-23229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23229}: Add new @code{cmath} constants: @code{cmath.inf} and @code{cmath.nan} to
match @code{math.inf} and @code{math.nan}, and also @code{cmath.infj} and
@code{cmath.nanj} to match the format used by complex repr.

@item 
bpo-27842@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27842}: The csv.DictReader now returns rows of type OrderedDict.
(Contributed by Steve Holden.)

@item 
Remove support for passing a file descriptor to os.access. It never worked
but previously didn't raise.

@item 
bpo-12885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12885}: Fix error when distutils encounters symlink.

@item 
bpo-27881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27881}: Fixed possible bugs when setting
sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

@item 
bpo-27861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27861}: Fixed a crash in sqlite3.Connection.cursor() when a factory
creates not a cursor.  Patch by Xiang Zhang.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: Avoid spurious output on OS X with Gnu Readline.

@item 
bpo-27706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27706}: Restore deterministic behavior of random.Random().seed() for
string seeds using seeding version 1.  Allows sequences of calls to
random() to exactly match those obtained in Python 2. Patch by Nofar
Schnider.

@item 
bpo-10513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10513}: Fix a regression in Connection.commit().  Statements should not
be reset after a commit.

@item 
bpo-12319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12319}: Chunked transfer encoding support added to
http.client.HTTPConnection requests.  The
urllib.request.AbstractHTTPHandler class does not enforce a Content-Length
header any more.  If a HTTP request has a file or iterable body, but no
Content-Length header, the library now falls back to use chunked
transfer-encoding.

@item 
A new version of typing.py from @indicateurl{https://github.com/python/typing}: -
Collection (only for 3.6) (bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}) - Add FrozenSet to __all__
(upstream #261) - fix crash in _get_type_vars() (upstream #259) - Remove
the dict constraint in ForwardRef._eval_type (upstream #252)

@item 
bpo-27832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27832}: Make @code{_normalize} parameter to @code{Fraction} constructor
keyword-only, so that @code{Fraction(2, 3, 4)} now raises @code{TypeError}.

@item 
bpo-27539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27539}: Fix unnormalised @code{Fraction.__pow__} result in the case of
negative exponent and negative base.

@item 
bpo-21718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21718}: cursor.description is now available for queries using CTEs.

@item 
bpo-27819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27819}: In distutils sdists, simply produce the "gztar" (gzipped tar
format) distributions on all platforms unless "formats" is supplied.

@item 
bpo-2466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2466}: posixpath.ismount now correctly recognizes mount points which
the user does not have permission to access.

@item 
bpo-9998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9998}: On Linux, ctypes.util.find_library now looks in LD_LIBRARY_PATH
for shared libraries.

@item 
bpo-27573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27573}: exit message for code.interact is now configurable.

@item 
bpo-27930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27930}: Improved behaviour of logging.handlers.QueueListener. Thanks to
Paulo Andrade and Petr Viktorin for the analysis and patch.

@item 
bpo-6766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6766}: Distributed reference counting added to multiprocessing to
support nesting of shared values / proxy objects.

@item 
bpo-21201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21201}: Improves readability of multiprocessing error message.  Thanks
to Wojciech Walczak for patch.

@item 
asyncio: Add set_protocol / get_protocol to Transports.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: asyncio: Set TCP_NODELAY by default.
@end itemize

@node IDLE<40>,C API<35>,Library<59>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id445}@anchor{12b3}
@subsubsection IDLE



@itemize -

@item 
bpo-15308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15308}: Add 'interrupt execution' (^C) to Shell menu. Patch by Roger
Serwy, updated by Bayard Randel.

@item 
bpo-27922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27922}: Stop IDLE tests from 'flashing' gui widgets on the screen.

@item 
bpo-27891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27891}: Consistently group and sort imports within idlelib modules.

@item 
bpo-17642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17642}: add larger font sizes for classroom projection.

@item 
Add version to title of IDLE help window.

@item 
bpo-25564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25564}: In section on IDLE -- console differences, mention that using
exec means that __builtins__ is defined for each statement.

@item 
bpo-27821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27821}: Fix 3.6.0a3 regression that prevented custom key sets from
being selected when no custom theme was defined.
@end itemize

@node C API<35>,Tests<46>,IDLE<40>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id446}@anchor{12b4}
@subsubsection C API



@itemize -

@item 
bpo-26900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26900}: Excluded underscored names and other private API from limited
API.

@item 
bpo-26027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26027}: Add support for path-like objects in PyUnicode_FSConverter() &
PyUnicode_FSDecoder().
@end itemize

@node Tests<46>,Build<48>,C API<35>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id447}@anchor{12b5}
@subsubsection Tests



@itemize -

@item 
bpo-27427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27427}: Additional tests for the math module. Patch by Francisco Couzo.

@item 
bpo-27953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27953}: Skip math and cmath tests that fail on OS X 10.4 due to a poor
libm implementation of tan.

@item 
bpo-26040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26040}: Improve test_math and test_cmath coverage and rigour. Patch by
Jeff Allen.

@item 
bpo-27787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27787}: Call gc.collect() before checking each test for "dangling
threads", since the dangling threads are weak references.
@end itemize

@node Build<48>,Tools/Demos<26>,Tests<46>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id448}@anchor{12b6}
@subsubsection Build



@itemize -

@item 
bpo-27566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27566}: Fix clean target in freeze makefile (patch by Lisa Roach)

@item 
bpo-27705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27705}: Update message in validate_ucrtbase.py

@item 
bpo-27976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27976}: Deprecate building _ctypes with the bundled copy of libffi on
non-OSX UNIX platforms.

@item 
bpo-27983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27983}: Cause lack of llvm-profdata tool when using clang as required
for PGO linking to be a configure time error rather than make time when
@code{--with-optimizations} is enabled.  Also improve our ability to find the
llvm-profdata tool on MacOS and some Linuxes.

@item 
bpo-21590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21590}: Support for DTrace and SystemTap probes.

@item 
bpo-26307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26307}: The profile-opt build now applies PGO to the built-in modules.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Add the --with-optimizations flag to turn on LTO and PGO build
support when available.

@item 
bpo-27917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27917}: Set platform triplets for Android builds.

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Update references to the $(LIBPL) installation path on AIX.
This path was changed in 3.2a4.

@item 
Update OS X installer to use SQLite 3.14.1 and XZ 5.2.2.

@item 
bpo-21122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21122}: Fix LTO builds on OS X.

@item 
bpo-17128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17128}: Build OS X installer with a private copy of OpenSSL. Also
provide a sample Install Certificates command script to install a set of
root certificates from the third-party certifi module.
@end itemize

@node Tools/Demos<26>,Windows<46>,Build<48>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id449}@anchor{12b7}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27952}: Get Tools/scripts/fixcid.py working with Python 3 and the
current "re" module, avoid invalid Python backslash escapes, and fix a bug
parsing escaped C quote signs.
@end itemize

@node Windows<46>,,Tools/Demos<26>,Python 3 6 0 beta 1
@anchor{whatsnew/changelog id450}@anchor{12b8}
@subsubsection Windows



@itemize -

@item 
bpo-28065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28065}: Update xz dependency to 5.2.2 and build it from source.

@item 
bpo-25144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25144}: Ensures TargetDir is set before continuing with custom install.

@item 
bpo-1602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1602}: Windows console doesn't input or print Unicode (PEP 528)

@item 
bpo-27781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27781}: Change file system encoding on Windows to UTF-8 (PEP 529)

@item 
bpo-27731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27731}: Opt-out of MAX_PATH on Windows 10

@item 
bpo-6135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6135}: Adds encoding and errors parameters to subprocess.

@item 
bpo-27959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27959}: Adds oem encoding, alias ansi to mbcs, move aliasmbcs to codec
lookup.

@item 
bpo-27982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27982}: The functions of the winsound module now accept keyword
arguments.

@item 
bpo-20366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20366}: Build full text search support into SQLite on Windows.

@item 
bpo-27756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27756}: Adds new icons for Python files and processes on Windows.
Designs by Cherry Wang.

@item 
bpo-27883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27883}: Update sqlite to 3.14.1.0 on Windows.
@end itemize

@node Python 3 6 0 alpha 4,Python 3 6 0 alpha 3,Python 3 6 0 beta 1,更新日志
@anchor{whatsnew/changelog python-3-6-0-alpha-4}@anchor{12b9}
@subsection Python 3.6.0 alpha 4


@emph{Release date: 2016-08-15}

@menu
* Core and Builtins: Core and Builtins<58>. 
* Library: Library<60>. 
* IDLE: IDLE<41>. 
* Tests: Tests<47>. 
* Windows: Windows<47>. 
* Build: Build<49>. 

@end menu

@node Core and Builtins<58>,Library<60>,,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id451}@anchor{12ba}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27704}: Optimized creating bytes and bytearray from byte-like objects
and iterables. Speed up to 3 times for short objects.  Original patch by
Naoki Inada.

@item 
bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}: Large sections of repeated lines in tracebacks are now
abbreviated as "[Previous line repeated @{count@} more times]" by the
builtin traceback rendering. Patch by Emanuel Barry.

@item 
bpo-27574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27574}: Decreased an overhead of parsing keyword arguments in functions
implemented with using Argument Clinic.

@item 
bpo-22557@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22557}: Now importing already imported modules is up to 2.5 times
faster.

@item 
bpo-17596@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17596}: Include <wincrypt.h> to help with Min GW building.

@item 
bpo-17599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17599}: On Windows, rename the privately defined REPARSE_DATA_BUFFER
structure to avoid conflicting with the definition from Min GW.

@item 
bpo-27507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27507}: Add integer overflow check in bytearray.extend().  Patch by
Xiang Zhang.

@item 
bpo-27581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27581}: Don't rely on wrapping for overflow check in
PySequence_Tuple().  Patch by Xiang Zhang.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Avoid signed integer overflow in list and tuple operations.
Patch by Xiang Zhang.

@item 
bpo-27419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27419}: Standard __import__() no longer look up "__import__" in globals
or builtins for importing submodules or "from import".  Fixed a crash if
raise a warning about unabling to resolve package from __spec__ or
__package__.

@item 
bpo-27083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27083}: Respect the PYTHONCASEOK environment variable under Windows.

@item 
bpo-27514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27514}: Make having too many statically nested blocks a SyntaxError
instead of SystemError.

@item 
bpo-27366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27366}: Implemented 
@geindex Python 提高建议; PEP 487
PEP 487@footnote{https://www.python.org/dev/peps/pep-0487} (Simpler customization of class
creation). Upon subclassing, the __init_subclass__ classmethod is called
on the base class. Descriptors are initialized with __set_name__ after
class creation.
@end itemize

@node Library<60>,IDLE<41>,Core and Builtins<58>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id452}@anchor{12bb}
@subsubsection Library



@itemize -

@item 
bpo-26027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26027}: Add 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}/__fspath__() support to the os and os.path
modules. Includes code from Jelle Zijlstra. (See also: bpo-27524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27524})

@item 
bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}: Add Collections to collections.abc. Patch by Ivan Levkivskyi,
docs by Neil Girdhar.

@item 
bpo-25958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25958}: Support "anti-registration" of special methods from various
ABCs, like __hash__, __iter__ or __len__.  All these (and several more)
can be set to None in an implementation class and the behavior will be as
if the method is not defined at all. (Previously, this mechanism existed
only for __hash__, to make mutable classes unhashable.)  Code contributed
by Andrew Barnert and Ivan Levkivskyi.

@item 
bpo-16764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16764}: Support keyword arguments to zlib.decompress().  Patch by Xiang
Zhang.

@item 
bpo-27736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27736}: Prevent segfault after interpreter re-initialization due to ref
count problem introduced in code for bpo-27038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27038} in 3.6.0a3. Patch by
Xiang Zhang.

@item 
bpo-25628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25628}: The @emph{verbose} and @emph{rename} parameters for
collections.namedtuple are now keyword-only.

@item 
bpo-12345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12345}: Add mathematical constant tau to math and cmath. See also
@geindex Python 提高建议; PEP 628
PEP 628@footnote{https://www.python.org/dev/peps/pep-0628}.

@item 
bpo-26823@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26823}: traceback.StackSummary.format now abbreviates large sections of
repeated lines as "[Previous line repeated @{count@} more times]" (this
change then further affects other traceback display operations in the
module). Patch by Emanuel Barry.

@item 
bpo-27664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27664}: Add to concurrent.futures.thread.ThreadPoolExecutor() the
ability to specify a thread name prefix.

@item 
bpo-27181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27181}: Add geometric_mean and harmonic_mean to statistics module.

@item 
bpo-27573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27573}: code.interact now prints an message when exiting.

@item 
bpo-6422@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6422}: Add autorange method to timeit.Timer objects.

@item 
bpo-27773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27773}: Correct some memory management errors server_hostname in
_ssl.wrap_socket().

@item 
bpo-26750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26750}: unittest.mock.create_autospec() now works properly for
subclasses of property() and other data descriptors.  Removes the never
publicly used, never documented unittest.mock.DescriptorTypes tuple.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Undocumented support of general bytes-like objects as path in
compile() and similar functions is now deprecated.

@item 
bpo-26800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26800}: Undocumented support of general bytes-like objects as paths in
os functions is now deprecated.

@item 
bpo-26981@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26981}: Add _order_ compatibility shim to enum.Enum for Python 2/3 code
bases.

@item 
bpo-27661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27661}: Added tzinfo keyword argument to datetime.combine.

@item 
In the curses module, raise an error if window.getstr() or window.instr()
is passed a negative value.

@item 
bpo-27783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27783}: Fix possible usage of uninitialized memory in
operator.methodcaller.

@item 
bpo-27774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27774}: Fix possible Py_DECREF on unowned object in _sre.

@item 
bpo-27760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27760}: Fix possible integer overflow in binascii.b2a_qp.

@item 
bpo-27758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27758}: Fix possible integer overflow in the _csv module for large
record lengths.

@item 
bpo-27568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27568}: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the
HTTP_PROXY variable when REQUEST_METHOD environment is set, which
indicates that the script is in CGI mode.

@item 
bpo-7063@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7063}: Remove dead code from the "array" module's slice handling. Patch
by Chuck.

@item 
bpo-27656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27656}: Do not assume sched.h defines any SCHED_* constants.

@item 
bpo-27130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27130}: In the "zlib" module, fix handling of large buffers (typically
4 GiB) when compressing and decompressing.  Previously, inputs were
limited to 4 GiB, and compression and decompression operations did not
properly handle results of 4 GiB.

@item 
bpo-24773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24773}: Implemented 
@geindex Python 提高建议; PEP 495
PEP 495@footnote{https://www.python.org/dev/peps/pep-0495} (Local Time Disambiguation).

@item 
Expose the EPOLLEXCLUSIVE constant (when it is defined) in the select
module.

@item 
bpo-27567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27567}: Expose the EPOLLRDHUP and POLLRDHUP constants in the select
module.

@item 
bpo-1621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1621}: Avoid signed int negation overflow in the "audioop" module.

@item 
bpo-27533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27533}: Release GIL in nt._isdir

@item 
bpo-17711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17711}: Fixed unpickling by the persistent ID with protocol 0. Original
patch by Alexandre Vassalotti.

@item 
bpo-27522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27522}: Avoid an unintentional reference cycle in email.feedparser.

@item 
bpo-27512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27512}: Fix a segfault when os.fspath() called an __fspath__() method
that raised an exception. Patch by Xiang Zhang.
@end itemize

@node IDLE<41>,Tests<47>,Library<60>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id453}@anchor{12bc}
@subsubsection IDLE



@itemize -

@item 
bpo-27714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27714}: text_textview and test_autocomplete now pass when re-run in the
same process.  This occurs when test_idle fails when run with the -w
option but without -jn.  Fix warning from test_config.

@item 
bpo-27621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27621}: Put query response validation error messages in the query box
itself instead of in a separate messagebox.  Redo tests to match. Add Mac
OSX refinements. Original patch by Mark Roseman.

@item 
bpo-27620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27620}: Escape key now closes Query box as cancelled.

@item 
bpo-27609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27609}: IDLE: tab after initial whitespace should tab, not
autocomplete. This fixes problem with writing docstrings at least twice
indented.

@item 
bpo-27609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27609}: Explicitly return None when there are also non-None returns. In
a few cases, reverse a condition and eliminate a return.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.

@item 
bpo-27173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27173}: Add 'IDLE Modern Unix' to the built-in key sets. Make the
default key set depend on the platform. Add tests for the changes to the
config module.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.
@end itemize

@node Tests<47>,Windows<47>,IDLE<41>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id454}@anchor{12bd}
@subsubsection Tests



@itemize -

@item 
bpo-25805@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25805}: Skip a test in test_pkgutil as needed that doesn't work when
@code{__name__ == __main__}. Patch by SilentGhost.

@item 
bpo-27472@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27472}: Add test.support.unix_shell as the path to the default shell.

@item 
bpo-27369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27369}: In test_pyexpat, avoid testing an error message detail that
changed in Expat 2.2.0.

@item 
bpo-27594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27594}: Prevent assertion error when running test_ast with coverage
enabled: ensure code object has a valid first line number. Patch suggested
by Ivan Levkivskyi.
@end itemize

@node Windows<47>,Build<49>,Tests<47>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id455}@anchor{12be}
@subsubsection Windows



@itemize -

@item 
bpo-27647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27647}: Update bundled Tcl/Tk to 8.6.6.

@item 
bpo-27610@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27610}: Adds 
@geindex Python 提高建议; PEP 514
PEP 514@footnote{https://www.python.org/dev/peps/pep-0514} metadata to Windows installer

@item 
bpo-27469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27469}: Adds a shell extension to the launcher so that drag and drop
works correctly.

@item 
bpo-27309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27309}: Enables proper Windows styles in python[w].exe manifest.
@end itemize

@node Build<49>,,Windows<47>,Python 3 6 0 alpha 4
@anchor{whatsnew/changelog id456}@anchor{12bf}
@subsubsection Build



@itemize -

@item 
bpo-27713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27713}: Suppress spurious build warnings when updating importlib's
bootstrap files. Patch by Xiang Zhang

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Correct the references to Modules/python.exp, which is required
on AIX.  The references were accidentally changed in 3.5.0a1.

@item 
bpo-27453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27453}: CPP invocation in configure must use CPPFLAGS. Patch by Chi
Hsuan Yen.

@item 
bpo-27641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27641}: The configure script now inserts comments into the makefile to
prevent the pgen and _freeze_importlib executables from being
cross-compiled.

@item 
bpo-26662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26662}: Set PYTHON_FOR_GEN in configure as the Python program to be
used for file generation during the build.

@item 
bpo-10910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10910}: Avoid C++ compilation errors on FreeBSD and OS X. Also update
FreedBSD version checks for the original ctype UTF-8 workaround.
@end itemize

@node Python 3 6 0 alpha 3,Python 3 6 0 alpha 2,Python 3 6 0 alpha 4,更新日志
@anchor{whatsnew/changelog python-3-6-0-alpha-3}@anchor{12c0}
@subsection Python 3.6.0 alpha 3


@emph{Release date: 2016-07-11}

@menu
* Security: Security<30>. 
* Core and Builtins: Core and Builtins<59>. 
* Library: Library<61>. 
* IDLE: IDLE<42>. 
* C API: C API<36>. 
* Build: Build<50>. 
* Tools/Demos: Tools/Demos<27>. 
* Documentation: Documentation<45>. 
* Tests: Tests<48>. 

@end menu

@node Security<30>,Core and Builtins<59>,,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id457}@anchor{12c1}
@subsubsection Security



@itemize -

@item 
bpo-27278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27278}: Fix os.urandom() implementation using getrandom() on Linux.
Truncate size to INT_MAX and loop until we collected enough random bytes,
instead of casting a directly Py_ssize_t to int.

@item 
bpo-22636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22636}: Avoid shell injection problems with ctypes.util.find_library().
@end itemize

@node Core and Builtins<59>,Library<61>,Security<30>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id458}@anchor{12c2}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27473}: Fixed possible integer overflow in bytes and bytearray
concatenations. Patch by Xiang Zhang.

@item 
bpo-23034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23034}: The output of a special Python build with defined COUNT_ALLOCS,
SHOW_ALLOC_COUNT or SHOW_TRACK_COUNT macros is now off by  default.  It
can be re-enabled using the "-X showalloccount" option.  It now outputs to
stderr instead of stdout.

@item 
bpo-27443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27443}: __length_hint__() of bytearray iterators no longer return a
negative integer for a resized bytearray.

@item 
bpo-27007@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27007}: The fromhex() class methods of bytes and bytearray subclasses
now return an instance of corresponding subclass.
@end itemize

@node Library<61>,IDLE<42>,Core and Builtins<59>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id459}@anchor{12c3}
@subsubsection Library



@itemize -

@item 
bpo-26844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26844}: Fix error message for imp.find_module() to refer to 'path'
instead of 'name'. Patch by Lev Maximov.

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL zero-length recv() calls to not block and not raise an
error about unclean EOF.

@item 
bpo-27466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27466}: Change time format returned by http.cookie.time2netscape,
confirming the netscape cookie format and making it consistent with
documentation.

@item 
bpo-21708@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21708}: Deprecated dbm.dumb behavior that differs from common dbm
behavior: creating a database in 'r' and 'w' modes and modifying a
database in 'r' mode.

@item 
bpo-26721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26721}: Change the socketserver.StreamRequestHandler.wfile attribute to
implement BufferedIOBase. In particular, the write() method no longer does
partial writes.

@item 
bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}: Added methods trace_add, trace_remove and trace_info in the
tkinter.Variable class.  They replace old methods trace_variable, trace,
trace_vdelete and trace_vinfo that use obsolete Tcl commands and might not
work in future versions of Tcl.  Fixed old tracing methods:
trace_vdelete() with wrong mode no longer break tracing, trace_vinfo() now
always returns a list of pairs of strings, tracing in the "u" mode now
works.

@item 
bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243}: Only the level argument to zlib.compress() is keyword argument
now.  The first argument is positional-only.

@item 
bpo-27038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27038}: Expose the DirEntry type as os.DirEntry. Code patch by Jelle
Zijlstra.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Update os.fspath()/PyOS_FSPath() to check the return value of
__fspath__() to be either str or bytes.

@item 
bpo-18726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18726}: All optional parameters of the dump(), dumps(), load() and
loads() functions and JSONEncoder and JSONDecoder class constructors in
the json module are now keyword-only.

@item 
bpo-27319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27319}: Methods selection_set(), selection_add(), selection_remove()
and selection_toggle() of ttk.TreeView now allow passing multiple items as
multiple arguments instead of passing them as a tuple.  Deprecated
undocumented ability of calling the selection() method with arguments.

@item 
bpo-27079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27079}: Fixed curses.ascii functions isblank(), iscntrl() and
ispunct().

@item 
bpo-27294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27294}: Numerical state in the repr for Tkinter event objects is now
represented as a combination of known flags.

@item 
bpo-27177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27177}: Match objects in the re module now support index-like objects
as group indices.  Based on patches by Jeroen Demeyer and Xiang Zhang.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Some functions (compile() etc) accepted a filename argument
encoded as an iterable of integers. Now only strings and byte-like objects
are accepted.

@item 
bpo-26536@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26536}: socket.ioctl now supports SIO_LOOPBACK_FAST_PATH. Patch by
Daniel Stokes.

@item 
bpo-27048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27048}: Prevents distutils failing on Windows when environment
variables contain non-ASCII characters

@item 
bpo-27330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27330}: Fixed possible leaks in the ctypes module.

@item 
bpo-27238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27238}: Got rid of bare excepts in the turtle module.  Original patch
by Jelle Zijlstra.

@item 
bpo-27122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27122}: When an exception is raised within the context being managed by
a contextlib.ExitStack() and one of the exit stack generators catches and
raises it in a chain, do not re-raise the original exception when exiting,
let the new chained one through.  This avoids the 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} bug described
in issue25782.

@item 
bpo-16864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16864}: sqlite3.Cursor.lastrowid now supports REPLACE statement.
Initial patch by Alex LordThorsen.

@item 
bpo-26386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26386}: Fixed ttk.TreeView selection operations with item id's
containing spaces.

@item 
bpo-8637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8637}: Honor a pager set by the env var MANPAGER (in preference to one
set by the env var PAGER).

@item 
bpo-16182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16182}: Fix various functions in the "readline" module to use the
locale encoding, and fix get_begidx() and get_endidx() to return code
point indexes.

@item 
bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}: Add loop.connect_accepted_socket(). Patch by Jim Fulton.
@end itemize

@node IDLE<42>,C API<36>,Library<61>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id460}@anchor{12c4}
@subsubsection IDLE



@itemize -

@item 
bpo-27477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27477}: IDLE search dialogs now use ttk widgets.

@item 
bpo-27173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27173}: Add 'IDLE Modern Unix' to the built-in key sets. Make the
default key set depend on the platform. Add tests for the changes to the
config module.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: make command line "idle-test> python test_help.py" work.
__file__ is relative when python is started in the file's directory.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.

@item 
bpo-27380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27380}: IDLE: add query.py with base Query dialog and ttk widgets.
Module had subclasses SectionName, ModuleName, and HelpSource, which are
used to get information from users by configdialog and file =>Load Module.
Each subclass has itw own validity checks.  Using ModuleName allows users
to edit bad module names instead of starting over. Add tests and delete
the two files combined into the new one.

@item 
bpo-27372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27372}: Test_idle no longer changes the locale.

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

@item 
bpo-27245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27245}: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.

@item 
bpo-24137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24137}: Run IDLE, test_idle, and htest with tkinter default root
disabled.  Fix code and tests that fail with this restriction.  Fix htests
to not create a second and redundant root and mainloop.

@item 
bpo-27310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27310}: Fix IDLE.app failure to launch on OS X due to vestigial import.
@end itemize

@node C API<36>,Build<50>,IDLE<42>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id461}@anchor{12c5}
@subsubsection C API



@itemize -

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: PyUnicode_FSDecoder() accepted a filename argument encoded as
an iterable of integers. Now only strings and byte-like objects are
accepted.
@end itemize

@node Build<50>,Tools/Demos<27>,C API<36>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id462}@anchor{12c6}
@subsubsection Build



@itemize -

@item 
bpo-28066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28066}: Fix the logic that searches build directories for generated
include files when building outside the source tree.

@item 
bpo-27442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27442}: Expose the Android API level that python was built against, in
sysconfig.get_config_vars() as 'ANDROID_API_LEVEL'.

@item 
bpo-27434@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27434}: The interpreter that runs the cross-build, found in PATH, must
now be of the same feature version (e.g. 3.6) as the source being built.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update Windows builds to use OpenSSL 1.0.2h.

@item 
bpo-23968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23968}: Rename the platform directory from plat-$(MACHDEP) to
plat-$(PLATFORM_TRIPLET). Rename the config directory (LIBPL) from
config-$(LDVERSION) to config-$(LDVERSION)-$(PLATFORM_TRIPLET). Install
the platform specific _sysconfigdata module into the platform directory
and rename it to include the ABIFLAGS.

@item 
Don't use largefile support for GNU/Hurd.
@end itemize

@node Tools/Demos<27>,Documentation<45>,Build<50>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id463}@anchor{12c7}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27332}: Fixed the type of the first argument of module-level functions
generated by Argument Clinic.  Patch by Petr Viktorin.

@item 
bpo-27418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27418}: Fixed Tools/importbench/importbench.py.
@end itemize

@node Documentation<45>,Tests<48>,Tools/Demos<27>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id464}@anchor{12c8}
@subsubsection Documentation



@itemize -

@item 
bpo-19489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19489}: Moved the search box from the sidebar to the header and footer
of each page. Patch by Ammar Askar.

@item 
bpo-27285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27285}: Update documentation to reflect the deprecation of @code{pyvenv}
and normalize on the term "virtual environment". Patch by Steve Piercy.
@end itemize

@node Tests<48>,,Documentation<45>,Python 3 6 0 alpha 3
@anchor{whatsnew/changelog id465}@anchor{12c9}
@subsubsection Tests



@itemize -

@item 
bpo-27027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27027}: Added test.support.is_android that is True when this is an
Android build.
@end itemize

@node Python 3 6 0 alpha 2,Python 3 6 0 alpha 1,Python 3 6 0 alpha 3,更新日志
@anchor{whatsnew/changelog python-3-6-0-alpha-2}@anchor{12ca}
@subsection Python 3.6.0 alpha 2


@emph{Release date: 2016-06-13}

@menu
* Security: Security<31>. 
* Core and Builtins: Core and Builtins<60>. 
* Library: Library<62>. 
* IDLE: IDLE<43>. 
* Documentation: Documentation<46>. 
* Tests: Tests<49>. 
* Windows: Windows<48>. 
* Build: Build<51>. 
* C API: C API<37>. 
* Tools/Demos: Tools/Demos<28>. 

@end menu

@node Security<31>,Core and Builtins<60>,,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id466}@anchor{12cb}
@subsubsection Security



@itemize -

@item 
bpo-26556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26556}: Update expat to 2.1.1, fixes CVE-2015-1283.

@item 
Fix TLS stripping vulnerability in smtplib, CVE-2016-0772. Reported by
Team Oststrom.

@item 
bpo-26839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26839}: On Linux, @ref{5d4,,os.urandom()} now calls @code{getrandom()} with
@code{GRND_NONBLOCK} to fall back on reading @code{/dev/urandom} if the urandom
entropy pool is not initialized yet. Patch written by Colm Buckley.
@end itemize

@node Core and Builtins<60>,Library<62>,Security<31>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id467}@anchor{12cc}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27095}: Simplified MAKE_FUNCTION and removed MAKE_CLOSURE opcodes.
Patch by Demur Rumed.

@item 
bpo-27190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27190}: Raise NotSupportedError if sqlite3 is older than 3.3.1. Patch
by Dave Sawyer.

@item 
bpo-27286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27286}: Fixed compiling BUILD_MAP_UNPACK_WITH_CALL opcode.  Calling
function with generalized unpacking (PEP 448) and conflicting keyword
names could cause undefined behavior.

@item 
bpo-27140@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27140}: Added BUILD_CONST_KEY_MAP opcode.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add support for os.PathLike objects to open() (part of
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}).

@item 
bpo-27066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27066}: Fixed SystemError if a custom opener (for open()) returns a
negative number without setting an exception.

@item 
bpo-26983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26983}: float() now always return an instance of exact float. The
deprecation warning is emitted if __float__ returns an instance of a
strict subclass of float.  In a future versions of Python this can be an
error.

@item 
bpo-27097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27097}: Python interpreter is now about 7% faster due to optimized
instruction decoding.  Based on patch by Demur Rumed.

@item 
bpo-26647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26647}: Python interpreter now uses 16-bit wordcode instead of
bytecode. Patch by Demur Rumed.

@item 
bpo-23275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23275}: Allow assigning to an empty target list in round brackets: () =
iterable.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Update the __aiter__ protocol: instead of returning an
awaitable that resolves to an asynchronous iterator, the asynchronous
iterator should be returned directly.  Doing the former will trigger a
PendingDeprecationWarning.
@end itemize

@node Library<62>,IDLE<43>,Core and Builtins<60>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id468}@anchor{12cd}
@subsubsection Library



@itemize -

@item 
Comment out socket (SO_REUSEPORT) and posix (O_SHLOCK, O_EXLOCK) constants
exposed on the API which are not implemented on GNU/Hurd. They would not
work at runtime anyway.

@item 
bpo-27025@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27025}: Generated names for Tkinter widgets are now more meaningful and
recognizable.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive ElementTree.Element and
functools.partial objects.

@item 
bpo-27294@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27294}: Improved repr for Tkinter event objects.

@item 
bpo-20508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20508}: Improve exception message of IPv@{4,6@}Network.__getitem__. Patch
by Gareth Rees.

@item 
bpo-21386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21386}: Implement missing IPv4Address.is_global property.  It was
documented since 07a5610bae9d.  Initial patch by Roger Luethi.

@item 
bpo-27029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27029}: Removed deprecated support of universal newlines mode from
ZipFile.open().

@item 
bpo-27030@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27030}: Unknown escapes consisting of @code{'\'} and an ASCII letter in
regular expressions now are errors.  The re.LOCALE flag now can be used
only with bytes patterns.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add os.PathLike support to DirEntry (part of 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}).
Initial patch by Jelle Zijlstra.

@item 
bpo-20900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20900}: distutils register command now decodes HTTP responses
correctly.  Initial patch by ingrid.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add os.PathLike support to pathlib, removing its provisional
status (part of PEP 519). Initial patch by Dusty Phillips.

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add support for os.PathLike objects to os.fsencode() and
os.fsdecode() (part of 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}).

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Introduce os.PathLike and os.fspath() (part of 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}).

@item 
A new version of typing.py provides several new classes and features:
@@overload outside stubs, Reversible, DefaultDict, Text, ContextManager,
Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some
of the new features are not yet implemented in mypy or other static
analyzers). Also classes for 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} (Awaitable, AsyncIterable,
AsyncIterator) have been added (in fact they made it into 3.5.1 but were
never mentioned).

@item 
bpo-25738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25738}: Stop http.server.BaseHTTPRequestHandler.send_error() from
sending a message body for 205 Reset Content.  Also, don't send Content
header fields in responses that don't have a body.  Patch by Susumu
Koshiba.

@item 
bpo-21313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21313}: Fix the "platform" module to tolerate when sys.version contains
truncated build information.

@item 
bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}: Added missing APIs to __all__ to match the documented APIs for
the following modules: cgi, mailbox, mimetypes, plistlib and smtpd.
Patches by Jacek Kołodziej.

@item 
bpo-27164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27164}: In the zlib module, allow decompressing raw Deflate streams
with a predefined zdict.  Based on patch by Xiang Zhang.

@item 
bpo-24291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24291}: Fix wsgiref.simple_server.WSGIRequestHandler to completely
write data to the client.  Previously it could do partial writes and
truncate data.  Also, wsgiref.handler.ServerHandler can now handle stdout
doing partial writes, but this is deprecated.

@item 
bpo-21272@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21272}: Use _sysconfigdata.py to initialize distutils.sysconfig.

@item 
bpo-19611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19611}: @ref{a0,,inspect} now reports the implicit @code{.0} parameters
generated by the compiler for comprehension and generator expression
scopes as if they were positional-only parameters called @code{implicit0}.
Patch by Jelle Zijlstra.

@item 
bpo-26809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26809}: Add @code{__all__} to @ref{f6,,string}.  Patch by Emanuel Barry.

@item 
bpo-26373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26373}: subprocess.Popen.communicate now correctly ignores
BrokenPipeError when the child process dies before .communicate() is
called in more/all circumstances.

@item 
signal, socket, and ssl module IntEnum constant name lookups now return a
consistent name for values having multiple names.  Ex: signal.Signals(6)
now refers to itself as signal.SIGALRM rather than flipping between that
and signal.SIGIOT based on the interpreter's hash randomization seed.

@item 
bpo-27167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27167}: Clarify the subprocess.CalledProcessError error message text
when the child process died due to a signal.

@item 
bpo-25931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25931}: Don't define socketserver.Forking* names on platforms such as
Windows that do not support os.fork().

@item 
bpo-21776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21776}: distutils.upload now correctly handles HTTPError. Initial patch
by Claudiu Popa.

@item 
bpo-26526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26526}: Replace custom parse tree validation in the parser module with
a simple DFA validator.

@item 
bpo-27114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27114}: Fix SSLContext._load_windows_store_certs fails with
PermissionError

@item 
bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: Avoid creating duplicate filters when using filterwarnings and
simplefilter. Based on patch by Alex Shkop.

@item 
bpo-23026@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23026}: winreg.QueryValueEx() now return an integer for REG_QWORD type.

@item 
bpo-26741@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26741}: subprocess.Popen destructor now emits a ResourceWarning warning
if the child process is still running.

@item 
bpo-27056@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27056}: Optimize pickle.load() and pickle.loads(), up to 10% faster to
deserialize a lot of small objects.

@item 
bpo-21271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21271}: New keyword only parameters in reset_mock call.
@end itemize

@node IDLE<43>,Documentation<46>,Library<62>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id469}@anchor{12ce}
@subsubsection IDLE



@itemize -

@item 
bpo-5124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5124}: Paste with text selected now replaces the selection on X11. This
matches how paste works on Windows, Mac, most modern Linux apps, and ttk
widgets. Original patch by Serhiy Storchaka.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Switch all scrollbars in IDLE to ttk versions. Where needed,
minimal tests are added to cover changes.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: IDLE requires tk 8.5 and availability ttk widgets. Delete now
unneeded tk version tests and code for older versions. Add test for IDLE
syntax colorizer.

@item 
bpo-27239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27239}: idlelib.macosx.isXyzTk functions initialize as needed.

@item 
bpo-27262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27262}: move Aqua unbinding code, which enable context menus, to
macosx.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: Make clear in idlelib.idle_test.__init__ that the directory is
a private implementation of test.test_idle and tool for maintainers.

@item 
bpo-27196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27196}: Stop 'ThemeChanged' warnings when running IDLE tests. These
persisted after other warnings were suppressed in #20567. Apply Serhiy
Storchaka's update_idletasks solution to four test files. Record this
additional advice in idle_test/README.txt

@item 
bpo-20567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20567}: Revise idle_test/README.txt with advice about avoiding tk
warning messages from tests.  Apply advice to several IDLE tests.

@item 
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}: Update idlelib/README.txt with new file names and event
handlers.

@item 
bpo-27156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27156}: Remove obsolete code not used by IDLE.

@item 
bpo-27117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27117}: Make colorizer htest and turtledemo work with dark themes. Move
code for configuring text widget colors to a new function.

@item 
bpo-24225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24225}: Rename many @code{idlelib/*.py} and @code{idle_test/test_*.py} files.
Edit files to replace old names with new names when the old name referred
to the module rather than the class it contained. See the issue and IDLE
section in What's New in 3.6 for more.

@item 
bpo-26673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26673}: When tk reports font size as 0, change to size 10. Such fonts
on Linux prevented the configuration dialog from opening.

@item 
bpo-21939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21939}: Add test for IDLE's percolator. Original patch by Saimadhav
Heblikar.

@item 
bpo-21676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21676}: Add test for IDLE's replace dialog. Original patch by Saimadhav
Heblikar.

@item 
bpo-18410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18410}: Add test for IDLE's search dialog. Original patch by Westley
Martínez.

@item 
bpo-21703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21703}: Add test for undo delegator.  Patch mostly by Saimadhav
Heblikar .

@item 
bpo-27044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27044}: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

@item 
bpo-23977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23977}: Add more asserts to test_delegator.
@end itemize

@node Documentation<46>,Tests<49>,IDLE<43>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id470}@anchor{12cf}
@subsubsection Documentation



@itemize -

@item 
bpo-16484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16484}: Change the default PYTHONDOCS URL to "https:", and fix the
resulting links to use lowercase.  Patch by Sean Rodman, test by Kaushik
Nadikuditi.

@item 
bpo-24136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24136}: Document the new 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} unpacking syntax of 3.5.

@item 
bpo-22558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22558}: Add remaining doc links to source code for Python-coded
modules. Patch by Yoni Lavi.
@end itemize

@node Tests<49>,Windows<48>,Documentation<46>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id471}@anchor{12d0}
@subsubsection Tests



@itemize -

@item 
bpo-25285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25285}: regrtest now uses subprocesses when the -j1 command line option
is used: each test file runs in a fresh child process. Before, the -j1
option was ignored.

@item 
bpo-25285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25285}: Tools/buildbot/test.bat script now uses -j1 by default to run
each test file in fresh child process.
@end itemize

@node Windows<48>,Build<51>,Tests<49>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id472}@anchor{12d1}
@subsubsection Windows



@itemize -

@item 
bpo-27064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27064}: The py.exe launcher now defaults to Python 3. The Windows
launcher @code{py.exe} no longer prefers an installed Python 2 version over
Python 3 by default when used interactively.

@item 
bpo-17500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17500}: Remove unused and outdated icons. (See also:
@indicateurl{https://github.com/python/pythondotorg/issues/945})
@end itemize

@node Build<51>,C API<37>,Windows<48>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id473}@anchor{12d2}
@subsubsection Build



@itemize -

@item 
bpo-27229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27229}: Fix the cross-compiling pgen rule for in-tree builds.  Patch by
Xavier de Gaye.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2h.
@end itemize

@node C API<37>,Tools/Demos<28>,Build<51>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id474}@anchor{12d3}
@subsubsection C API



@itemize -

@item 
bpo-27186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27186}: Add the PyOS_FSPath() function (part of 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519}).

@item 
bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}: PyArg_ParseTupleAndKeywords() now supports positional-only
parameters.
@end itemize

@node Tools/Demos<28>,,C API<37>,Python 3 6 0 alpha 2
@anchor{whatsnew/changelog id475}@anchor{12d4}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26282@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26282}: Argument Clinic now supports positional-only and keyword
parameters in the same function.
@end itemize

@node Python 3 6 0 alpha 1,Python 3 5 5 final,Python 3 6 0 alpha 2,更新日志
@anchor{whatsnew/changelog python-3-6-0-alpha-1}@anchor{12d5}
@subsection Python 3.6.0 alpha 1


@emph{Release date: 2016-05-16}

@menu
* Security: Security<32>. 
* Core and Builtins: Core and Builtins<61>. 
* Library: Library<63>. 
* IDLE: IDLE<44>. 
* Documentation: Documentation<47>. 
* Tests: Tests<50>. 
* Build: Build<52>. 
* Windows: Windows<49>. 
* Tools/Demos: Tools/Demos<29>. 
* C API: C API<38>. 

@end menu

@node Security<32>,Core and Builtins<61>,,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id476}@anchor{12d6}
@subsubsection Security



@itemize -

@item 
bpo-26657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26657}: Fix directory traversal vulnerability with http.server on
Windows.  This fixes a regression that was introduced in 3.3.4rc1 and
3.4.0rc1.  Based on patch by Philipp Hagemeister.

@item 
bpo-26313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26313}: ssl.py _load_windows_store_certs fails if windows cert store is
empty. Patch by Baji.

@item 
bpo-25939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25939}: On Windows open the cert store readonly in
ssl.enum_certificates.
@end itemize

@node Core and Builtins<61>,Library<63>,Security<32>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id477}@anchor{12d7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-20041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20041}: Fixed TypeError when frame.f_trace is set to None. Patch by
Xavier de Gaye.

@item 
bpo-26168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26168}: Fixed possible refleaks in failing Py_BuildValue() with the "N"
format unit.

@item 
bpo-26991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26991}: Fix possible refleak when creating a function with annotations.

@item 
bpo-27039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27039}: Fixed bytearray.remove() for values greater than 127.  Based on
patch by Joe Jevnik.

@item 
bpo-23640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23640}: int.from_bytes() no longer bypasses constructors for
subclasses.

@item 
bpo-27005@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27005}: Optimized the float.fromhex() class method for exact float. It
is now 2 times faster.

@item 
bpo-18531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18531}: Single var-keyword argument of dict subtype was passed
unscathed to the C-defined function.  Now it is converted to exact dict.

@item 
bpo-26811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26811}: gc.get_objects() no longer contains a broken tuple with NULL
pointer.

@item 
bpo-20120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20120}: Use RawConfigParser for .pypirc parsing, removing support for
interpolation unintentionally added with move to Python 3. Behavior no
longer does any interpolation in .pypirc files, matching behavior in
Python 2.7 and Setuptools 19.0.

@item 
bpo-26249@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26249}: Memory functions of the @ref{607,,PyMem_Malloc()} domain
(@ref{60a,,PYMEM_DOMAIN_MEM}) now use the @ref{6c2,,pymalloc allocator} rather than system @code{malloc()}. Applications calling
@ref{607,,PyMem_Malloc()} without holding the GIL can now crash: use
@code{PYTHONMALLOC=debug} environment variable to validate the usage of
memory allocators in your application.

@item 
bpo-26802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26802}: Optimize function calls only using unpacking like
@code{func(*tuple)} (no other positional argument, no keyword): avoid copying
the tuple. Patch written by Joe Jevnik.

@item 
bpo-26659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26659}: Make the builtin slice type support cycle collection.

@item 
bpo-26718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26718}: super.__init__ no longer leaks memory if called multiple times.
NOTE: A direct call of super.__init__ is not endorsed!

@item 
bpo-27138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27138}: Fix the doc comment for FileFinder.find_spec().

@item 
bpo-27147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27147}: Mention 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} in the importlib docs.

@item 
bpo-25339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25339}: PYTHONIOENCODING now has priority over locale in setting the
error handler for stdin and stdout.

@item 
bpo-26494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26494}: Fixed crash on iterating exhausting iterators. Affected classes
are generic sequence iterators, iterators of str, bytes, bytearray, list,
tuple, set, frozenset, dict, OrderedDict, corresponding views and
os.scandir() iterator.

@item 
bpo-26574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26574}: Optimize @code{bytes.replace(b'@w{'}, b'.')} and
@code{bytearray.replace(b'@w{'}, b'.')}. Patch written by Josh Snider.

@item 
bpo-26581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26581}: If coding cookie is specified multiple times on a line in
Python source code file, only the first one is taken to account.

@item 
bpo-19711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19711}: Add tests for reloading namespace packages.

@item 
bpo-21099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21099}: Switch applicable importlib tests to use 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} API.

@item 
bpo-26563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26563}: Debug hooks on Python memory allocators now raise a fatal error
if functions of the @ref{607,,PyMem_Malloc()} family are called without
holding the GIL.

@item 
bpo-26564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26564}: On error, the debug hooks on Python memory allocators now use
the @ref{11d,,tracemalloc} module to get the traceback where a memory block
was allocated.

@item 
bpo-26558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26558}: The debug hooks on Python memory allocator
@ref{609,,PyObject_Malloc()} now detect when functions are called without
holding the GIL.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: Add 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} environment variable to set the
Python memory allocators and/or install debug hooks.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: The @ref{60c,,PyMem_SetupDebugHooks()} function can now also be
used on Python compiled in release mode.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: The 
@geindex PYTHONMALLOCSTATS
@geindex 环境变量; PYTHONMALLOCSTATS
@ref{12d8,,PYTHONMALLOCSTATS} environment variable can now
also be used on Python compiled in release mode. It now has no effect if
set to an empty string.

@item 
bpo-26516@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26516}: In debug mode, debug hooks are now also installed on Python
memory allocators when Python is configured without pymalloc.

@item 
bpo-26464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26464}: Fix str.translate() when string is ASCII and first replacements
removes character, but next replacement uses a non-ASCII character or a
string longer than 1 character. Regression introduced in Python 3.5.0.

@item 
bpo-22836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22836}: Ensure exception reports from PyErr_Display() and
PyErr_WriteUnraisable() are sensible even when formatting them produces
secondary errors.  This affects the reports produced by
sys.__excepthook__() and when __del__() raises an exception.

@item 
bpo-26302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26302}: Correct behavior to reject comma as a legal character for
cookie names.

@item 
bpo-26136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26136}: Upgrade the warning when a generator raises StopIteration from
PendingDeprecationWarning to DeprecationWarning.  Patch by Anish Shah.

@item 
bpo-26204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26204}: The compiler now ignores all constant statements: bytes, str,
int, float, complex, name constants (None, False, True), Ellipsis and
ast.Constant; not only str and int. For example, @code{1.0} is now ignored in
@code{def f(): 1.0}.

@item 
bpo-4806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4806}: Avoid masking the original TypeError exception when using star
(@code{*}) unpacking in function calls.  Based on patch by Hagen Fürstenau
and Daniel Urban.

@item 
bpo-26146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26146}: Add a new kind of AST node: @code{ast.Constant}. It can be used by
external AST optimizers, but the compiler does not emit directly such
node.

@item 
bpo-23601@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23601}: Sped-up allocation of dict key objects by using Python's small
object allocator.  (Contributed by Julian Taylor.)

@item 
bpo-18018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18018}: Import raises ImportError instead of SystemError if a relative
import is attempted without a known parent package.

@item 
bpo-25843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25843}: When compiling code, don't merge constants if they are equal
but have a different types. For example, @code{f1, f2 = lambda: 1, lambda:
1.0} is now correctly compiled to two different functions: @code{f1()}
returns @code{1} (@code{int}) and @code{f2()} returns @code{1.0} (@code{float}), even if
@code{1} and @code{1.0} are equal.

@item 
bpo-26107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26107}: The format of the @code{co_lnotab} attribute of code objects
changes to support negative line number delta.

@item 
bpo-26154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26154}: Add a new private _PyThreadState_UncheckedGet() function to get
the current Python thread state, but don't issue a fatal error if it is
NULL. This new function must be used instead of accessing directly the
_PyThreadState_Current variable.  The variable is no more exposed since
Python 3.5.1 to hide the exact implementation of atomic C types, to avoid
compiler issues.

@item 
bpo-25791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25791}: If __package__ != __spec__.parent or if neither __package__ or
__spec__ are defined then ImportWarning is raised.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: [UPDATE] Comment out the one of the pickleability tests in
_PyObject_GetState() due to regressions observed in Cython-based projects.

@item 
bpo-25961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25961}: Disallowed null characters in the type name.

@item 
bpo-25973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25973}: Fix segfault when an invalid nonlocal statement binds a name
starting with two underscores.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Instances of extension types with a state that aren't
subclasses of list or dict and haven't implemented any pickle-related
methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or
__getstate__), can no longer be pickled.  Including memoryview.

@item 
bpo-20440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20440}: Massive replacing unsafe attribute setting code with special
macro Py_SETREF.

@item 
bpo-25766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25766}: Special method __bytes__() now works in str subclasses.

@item 
bpo-25421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25421}: __sizeof__ methods of builtin types now use dynamic basic size.
This allows sys.getsize() to work correctly with their subclasses with
__slots__ defined.

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.

@item 
bpo-5319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5319}: New Py_FinalizeEx() API allowing Python to set an exit status of
120 on failure to flush buffered streams.

@item 
bpo-25485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25485}: telnetlib.Telnet is now a context manager.

@item 
bpo-24097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24097}: Fixed crash in object.__reduce__() if slot name is freed inside
__getattr__.

@item 
bpo-24731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24731}: Fixed crash on converting objects with special methods
__bytes__, __trunc__, and __float__ returning instances of subclasses of
bytes, int, and float to subclasses of bytes, int, and float
correspondingly.

@item 
bpo-25630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25630}: Fix a possible segfault during argument parsing in functions
that accept filesystem paths.

@item 
bpo-23564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23564}: Fixed a partially broken sanity check in the _posixsubprocess
internals regarding how fds_to_pass were passed to the child.  The bug had
no actual impact as subprocess.py already avoided it.

@item 
bpo-25388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25388}: Fixed tokenizer crash when processing undecodable source code
with a null byte.

@item 
bpo-25462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25462}: The hash of the key now is calculated only once in most
operations in C implementation of OrderedDict.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Default implementation of __reduce__ and __reduce_ex__ now
rejects builtin types with not defined __new__.

@item 
bpo-24802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24802}: Avoid buffer overreads when int(), float(), compile(), exec()
and eval() are passed bytes-like objects.  These objects are not
necessarily terminated by a null byte, but the functions assumed they
were.

@item 
bpo-25555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25555}: Fix parser and AST: fill lineno and col_offset of "arg" node
when compiling AST from Python objects.

@item 
bpo-24726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24726}: Fixed a crash and leaking NULL in repr() of OrderedDict that
was mutated by direct calls of dict methods.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Iterating OrderedDict with keys with unstable hash now raises
KeyError in C implementations as well as in Python implementation.

@item 
bpo-25395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25395}: Fixed crash when highly nested OrderedDict structures were
garbage collected.

@item 
bpo-25401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25401}: Optimize bytes.fromhex() and bytearray.fromhex(): they are now
between 2x and 3.5x faster.

@item 
bpo-25399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25399}: Optimize bytearray % args using the new private _PyBytesWriter
API. Formatting is now between 2.5 and 5 times faster.

@item 
bpo-25274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25274}: sys.setrecursionlimit() now raises a RecursionError if the new
recursion limit is too low depending at the current recursion depth.
Modify also the "lower-water mark" formula to make it monotonic. This mark
is used to decide when the overflowed flag of the thread state is reset.

@item 
bpo-24402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24402}: Fix input() to prompt to the redirected stdout when
sys.stdout.fileno() fails.

@item 
bpo-25349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25349}: Optimize bytes % args using the new private _PyBytesWriter API.
Formatting is now up to 2 times faster.

@item 
bpo-24806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24806}: Prevent builtin types that are not allowed to be subclassed
from being subclassed through multiple inheritance.

@item 
bpo-25301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25301}: The UTF-8 decoder is now up to 15 times as fast for error
handlers: @code{ignore}, @code{replace} and @code{surrogateescape}.

@item 
bpo-24848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24848}: Fixed a number of bugs in UTF-7 decoding of misformed data.

@item 
bpo-25267@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25267}: The UTF-8 encoder is now up to 75 times as fast for error
handlers: @code{ignore}, @code{replace}, @code{surrogateescape}, @code{surrogatepass}.
Patch co-written with Serhiy Storchaka.

@item 
bpo-25280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25280}: Import trace messages emitted in verbose (-v) mode are no
longer formatted twice.

@item 
bpo-25227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25227}: Optimize ASCII and latin1 encoders with the @code{surrogateescape}
error handler: the encoders are now up to 3 times as fast. Initial patch
written by Serhiy Storchaka.

@item 
bpo-25003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25003}: On Solaris 11.3 or newer, os.urandom() now uses the getrandom()
function instead of the getentropy() function. The getentropy() function
is blocking to generate very good quality entropy, os.urandom() doesn't
need such high-quality entropy.

@item 
bpo-9232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9232}: Modify Python's grammar to allow trailing commas in the argument
list of a function declaration.  For example, "def f(*, a = 3,): pass" is
now legal. Patch from Mark Dickinson.

@item 
bpo-24965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24965}: Implement 
@geindex Python 提高建议; PEP 498
PEP 498@footnote{https://www.python.org/dev/peps/pep-0498} "Literal String Interpolation". This
allows you to embed expressions inside f-strings, which are converted to
normal strings at run time. Given x=3, then f'value=@{x@}' == 'value=3'.
Patch by Eric V. Smith.

@item 
bpo-26478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26478}: Fix semantic bugs when using binary operators with dictionary
views and tuples.

@item 
bpo-26171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26171}: Fix possible integer overflow and heap corruption in
zipimporter.get_data().

@item 
bpo-25660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25660}: Fix TAB key behaviour in REPL with readline.

@item 
bpo-26288@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26288}: Optimize PyLong_AsDouble.

@item 
bpo-26289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26289}: Optimize floor and modulo division for single-digit longs.
Microbenchmarks show 2-2.5x improvement.  Built-in 'divmod' function is
now also ~10% faster. (See also: bpo-26315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26315})

@item 
bpo-25887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25887}: Raise a RuntimeError when a coroutine object is awaited more
than once.
@end itemize

@node Library<63>,IDLE<44>,Core and Builtins<61>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id478}@anchor{12d9}
@subsubsection Library



@itemize -

@item 
bpo-27057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27057}: Fix os.set_inheritable() on Android, ioctl() is blocked by
SELinux and fails with EACCESS. The function now falls back to fcntl().
Patch written by Michał Bednarski.

@item 
bpo-27014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27014}: Fix infinite recursion using typing.py.  Thanks to Kalle Tuure!

@item 
bpo-27031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27031}: Removed dummy methods in Tkinter widget classes: tk_menuBar()
and tk_bindForTraversal().

@item 
bpo-14132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14132}: Fix urllib.request redirect handling when the target only has a
query string.  Original fix by Ján Janech.

@item 
bpo-17214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17214}: The "urllib.request" module now percent-encodes non-ASCII bytes
found in redirect target URLs.  Some servers send Location header fields
with non-ASCII bytes, but "http.client" requires the request target to be
ASCII-encodable, otherwise a UnicodeEncodeError is raised.  Based on patch
by Christian Heimes.

@item 
bpo-27033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27033}: The default value of the decode_data parameter for
smtpd.SMTPChannel and smtpd.SMTPServer constructors is changed to False.

@item 
bpo-27034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27034}: Removed deprecated class asynchat.fifo.

@item 
bpo-26870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26870}: Added readline.set_auto_history(), which can stop entries being
automatically added to the history list.  Based on patch by Tyler
Crompton.

@item 
bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}: zipfile.ZipFile.open() can now be used to write data into a ZIP
file, as well as for extracting data.  Patch by Thomas Kluyver.

@item 
bpo-26892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26892}: Honor debuglevel flag in urllib.request.HTTPHandler. Patch
contributed by Chi Hsuan Yen.

@item 
bpo-22274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22274}: In the subprocess module, allow stderr to be redirected to
stdout even when stdout is not redirected.  Patch by Akira Li.

@item 
bpo-26807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26807}: mock_open 'files' no longer error on readline at end of file.
Patch from Yolanda Robla.

@item 
bpo-25745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25745}: Fixed leaking a userptr in curses panel destructor.

@item 
bpo-26977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26977}: Removed unnecessary, and ignored, call to sum of squares helper
in statistics.pvariance.

@item 
bpo-26002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26002}: Use bisect in statistics.median instead of a linear search.
Patch by Upendra Kuma.

@item 
bpo-25974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25974}: Make use of new Decimal.as_integer_ratio() method in statistics
module. Patch by Stefan Krah.

@item 
bpo-26996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26996}: Add secrets module as described in 
@geindex Python 提高建议; PEP 506
PEP 506@footnote{https://www.python.org/dev/peps/pep-0506}.

@item 
bpo-26881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26881}: The modulefinder module now supports extended opcode arguments.

@item 
bpo-23815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23815}: Fixed crashes related to directly created instances of types in
_tkinter and curses.panel modules.

@item 
bpo-17765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17765}: weakref.ref() no longer silently ignores keyword arguments.
Patch by Georg Brandl.

@item 
bpo-26873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26873}: xmlrpc now raises ResponseError on unsupported type tags
instead of silently return incorrect result.

@item 
bpo-26915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26915}: The __contains__ methods in the collections ABCs now check for
identity before checking equality.  This better matches the behavior of
the concrete classes, allows sensible handling of NaNs, and makes it
easier to reason about container invariants.

@item 
bpo-26711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26711}: Fixed the comparison of plistlib.Data with other types.

@item 
bpo-24114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24114}: Fix an uninitialized variable in @code{ctypes.util}. The bug only
occurs on SunOS when the ctypes implementation searches for the @code{crle}
program.  Patch by Xiang Zhang.  Tested on SunOS by Kees Bos.

@item 
bpo-26864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26864}: In urllib.request, change the proxy bypass host checking
against no_proxy to be case-insensitive, and to not match unrelated host
names that happen to have a bypassed hostname as a suffix.  Patch by Xiang
Zhang.

@item 
bpo-24902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24902}: Print server URL on http.server startup.  Initial patch by
Felix Kaiser.

@item 
bpo-25788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25788}: fileinput.hook_encoded() now supports an "errors" argument for
passing to open.  Original patch by Joseph Hackman.

@item 
bpo-26634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26634}: recursive_repr() now sets __qualname__ of wrapper.  Patch by
Xiang Zhang.

@item 
bpo-26804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26804}: urllib.request will prefer lower_case proxy environment
variables over UPPER_CASE or Mixed_Case ones. Patch contributed by
Hans-Peter Jansen.

@item 
bpo-26837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26837}: assertSequenceEqual() now correctly outputs non-stringified
differing items (like bytes in the -b mode).  This affects
assertListEqual() and assertTupleEqual().

@item 
bpo-26041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26041}: Remove "will be removed in Python 3.7" from deprecation
messages of platform.dist() and platform.linux_distribution(). Patch by
Kumaripaba Miyurusara Athukorala.

@item 
bpo-26822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26822}: itemgetter, attrgetter and methodcaller objects no longer
silently ignore keyword arguments.

@item 
bpo-26733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26733}: Disassembling a class now disassembles class and static
methods. Patch by Xiang Zhang.

@item 
bpo-26801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26801}: Fix error handling in @ref{b2e,,shutil.get_terminal_size()}, catch
@ref{4aa,,AttributeError} instead of @ref{e48,,NameError}. Patch written by
Emanuel Barry.

@item 
bpo-24838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24838}: tarfile's ustar and gnu formats now correctly calculate name
and link field limits for multibyte character encodings like utf-8.

@item 
bpo-26717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26717}: Stop encoding Latin-1-ized WSGI paths with UTF-8.  Patch by
Anthony Sottile.

@item 
bpo-26782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26782}: Add STARTUPINFO to subprocess.__all__ on Windows.

@item 
bpo-26404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26404}: Add context manager to socketserver.  Patch by Aviv Palivoda.

@item 
bpo-26735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26735}: Fix @ref{5d4,,os.urandom()} on Solaris 11.3 and newer when reading
more than 1,024 bytes: call @code{getrandom()} multiple times with a limit of
1024 bytes per call.

@item 
bpo-26585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26585}: Eliminate http.server._quote_html() and use
html.escape(quote=False).  Patch by Xiang Zhang.

@item 
bpo-26685@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26685}: Raise OSError if closing a socket fails.

@item 
bpo-16329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16329}: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.

@item 
bpo-13952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13952}: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.

@item 
bpo-26587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26587}: the site module now allows .pth files to specify files to be
added to sys.path (e.g. zip files).

@item 
bpo-25609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25609}: Introduce contextlib.AbstractContextManager and
typing.ContextManager.

@item 
bpo-26709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26709}: Fixed Y2038 problem in loading binary PLists.

@item 
bpo-23735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23735}: Handle terminal resizing with Readline 6.3+ by installing our
own SIGWINCH handler.  Patch by Eric Price.

@item 
bpo-25951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25951}: Change SSLSocket.sendall() to return None, as explicitly
documented for plain socket objects.  Patch by Aviv Palivoda.

@item 
bpo-26586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26586}: In http.server, respond with "413 Request header fields too
large" if there are too many header fields to parse, rather than killing
the connection and raising an unhandled exception.  Patch by Xiang Zhang.

@item 
bpo-26676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26676}: Added missing XMLPullParser to ElementTree.__all__.

@item 
bpo-22854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22854}: Change BufferedReader.writable() and BufferedWriter.readable()
to always return False.

@item 
bpo-26492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26492}: Exhausted iterator of array.array now conforms with the
behavior of iterators of other mutable sequences: it lefts exhausted even
if iterated array is extended.

@item 
bpo-26641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26641}: doctest.DocFileTest and doctest.testfile() now support packages
(module splitted into multiple directories) for the package parameter.

@item 
bpo-25195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25195}: Fix a regression in mock.MagicMock. _Call is a subclass of
tuple (changeset 3603bae63c13 only works for classes) so we need to
implement __ne__ ourselves.  Patch by Andrew Plummer.

@item 
bpo-26644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26644}: Raise ValueError rather than SystemError when a negative length
is passed to SSLSocket.recv() or read().

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL recv(0) and read(0) methods to return zero bytes
instead of up to 1024.

@item 
bpo-26616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26616}: Fixed a bug in datetime.astimezone() method.

@item 
bpo-26637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26637}: The @ref{9a,,importlib} module now emits an @ref{16c,,ImportError}
rather than a @ref{1ff,,TypeError} if @ref{16b,,__import__()} is tried during the
Python shutdown process but @ref{262,,sys.path} is already cleared (set to
@code{None}).

@item 
bpo-21925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21925}: @ref{1176,,warnings.formatwarning()} now catches exceptions when
calling @ref{804,,linecache.getline()} and
@ref{12da,,tracemalloc.get_object_traceback()} to be able to log
@ref{5d3,,ResourceWarning} emitted late during the Python shutdown process.

@item 
bpo-23848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23848}: On Windows, faulthandler.enable() now also installs an
exception handler to dump the traceback of all Python threads on any
Windows exception, not only on UNIX signals (SIGSEGV, SIGFPE, SIGABRT).

@item 
bpo-26530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26530}: Add C functions @code{_PyTraceMalloc_Track()} and
@code{_PyTraceMalloc_Untrack()} to track memory blocks using the
@ref{11d,,tracemalloc} module. Add @code{_PyTraceMalloc_GetTraceback()} to
get the traceback of an object.

@item 
bpo-26588@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26588}: The _tracemalloc now supports tracing memory allocations of
multiple address spaces (domains).

@item 
bpo-24266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24266}: Ctrl+C during Readline history search now cancels the search
mode when compiled with Readline 7.

@item 
bpo-26590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26590}: Implement a safe finalizer for the _socket.socket type. It now
releases the GIL to close the socket.

@item 
bpo-18787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18787}: spwd.getspnam() now raises a PermissionError if the user
doesn't have privileges.

@item 
bpo-26560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26560}: Avoid potential ValueError in BaseHandler.start_response.
Initial patch by Peter Inglesby.

@item 
bpo-26567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26567}: Add a new function @ref{6cd,,PyErr_ResourceWarning()} function to
pass the destroyed object. Add a @emph{source} attribute to
@code{warnings.WarningMessage}. Add warnings._showwarnmsg() which uses
tracemalloc to get the traceback where source object was allocated.

@item 
bpo-26569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26569}: Fix @ref{12db,,pyclbr.readmodule()} and @ref{12dc,,pyclbr.readmodule_ex()}
to support importing packages.

@item 
bpo-26499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26499}: Account for remaining Content-Length in HTTPResponse.readline()
and read1(). Based on patch by Silent Ghost. Also document that
HTTPResponse now supports these methods.

@item 
bpo-25320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25320}: Handle sockets in directories unittest discovery is scanning.
Patch from Victor van den Elzen.

@item 
bpo-16181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16181}: cookiejar.http2time() now returns None if year is higher than
datetime.MAXYEAR.

@item 
bpo-26513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26513}: Fixes platform module detection of Windows Server

@item 
bpo-23718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23718}: Fixed parsing time in week 0 before Jan 1.  Original patch by
Tamás Bence Gedai.

@item 
bpo-26323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26323}: Add Mock.assert_called() and Mock.assert_called_once() methods
to unittest.mock. Patch written by Amit Saha.

@item 
bpo-20589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20589}: Invoking Path.owner() and Path.group() on Windows now raise
NotImplementedError instead of ImportError.

@item 
bpo-26177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26177}: Fixed the keys() method for Canvas and Scrollbar widgets.

@item 
bpo-15068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15068}: Got rid of excessive buffering in fileinput. The bufsize
parameter is now deprecated and ignored.

@item 
bpo-19475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19475}: Added an optional argument timespec to the datetime isoformat()
method to choose the precision of the time component.

@item 
bpo-2202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2202}: Fix UnboundLocalError in
AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu
Dupuy.

@item 
bpo-26167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26167}: Minimized overhead in copy.copy() and copy.deepcopy().
Optimized copying and deepcopying bytearrays, NotImplemented, slices,
short lists, tuples, dicts, sets.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed pickling and copying the accumulate() iterator with total
is None.

@item 
bpo-26475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26475}: Fixed debugging output for regular expressions with the (?x)
flag.

@item 
bpo-26482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26482}: Allowed pickling recursive dequeues.

@item 
bpo-26335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26335}: Make mmap.write() return the number of bytes written like other
write methods.  Patch by Jakub Stasiak.

@item 
bpo-26457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26457}: Fixed the subnets() methods in IP network classes for the case
when resulting prefix length is equal to maximal prefix length. Based on
patch by Xiang Zhang.

@item 
bpo-26385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26385}: Remove the file if the internal open() call in
NamedTemporaryFile() fails. Patch by Silent Ghost.

@item 
bpo-26402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26402}: Fix XML-RPC client to retry when the server shuts down a
persistent connection.  This was a regression related to the new
http.client.RemoteDisconnected exception in 3.5.0a4.

@item 
bpo-25913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25913}: Leading @code{<~} is optional now in base64.a85decode() with
adobe=True.  Patch by Swati Jaiswal.

@item 
bpo-26186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26186}: Remove an invalid type check in importlib.util.LazyLoader.

@item 
bpo-26367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26367}: importlib.__import__() raises ImportError like
builtins.__import__() when @code{level} is specified but without an
accompanying package specified.

@item 
bpo-26309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26309}: In the "socketserver" module, shut down the request (closing
the connected socket) when verify_request() returns false.  Patch by Aviv
Palivoda.

@item 
bpo-23430@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23430}: Change the socketserver module to only catch exceptions raised
from a request handler that are derived from Exception (instead of
BaseException). Therefore SystemExit and KeyboardInterrupt no longer
trigger the handle_error() method, and will now to stop a single-threaded
server.

@item 
bpo-25995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25995}: os.walk() no longer uses FDs proportional to the tree depth.

@item 
bpo-25994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25994}: Added the close() method and the support of the context manager
protocol for the os.scandir() iterator.

@item 
bpo-23992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23992}: multiprocessing: make MapResult not fail-fast upon exception.

@item 
bpo-26243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26243}: Support keyword arguments to zlib.compress().  Patch by Aviv
Palivoda.

@item 
bpo-26117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26117}: The os.scandir() iterator now closes file descriptor not only
when the iteration is finished, but when it was failed with error.

@item 
bpo-25949@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25949}: __dict__ for an OrderedDict instance is now created only when
needed.

@item 
bpo-25911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25911}: Restored support of bytes paths in os.walk() on Windows.

@item 
bpo-26045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26045}: Add UTF-8 suggestion to error message when posting a
non-Latin-1 string with http.client.

@item 
bpo-26039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26039}: Added zipfile.ZipInfo.from_file() and zipinfo.ZipInfo.is_dir().
Patch by Thomas Kluyver.

@item 
bpo-12923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12923}: Reset FancyURLopener's redirect counter even if there is an
exception. Based on patches by Brian Brazil and Daniel Rocco.

@item 
bpo-25945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25945}: Fixed a crash when unpickle the functools.partial object with
wrong state. Fixed a leak in failed functools.partial constructor. "args"
and "keywords" attributes of functools.partial have now always types tuple
and dict correspondingly.

@item 
bpo-26202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26202}: copy.deepcopy() now correctly copies range() objects with
non-atomic attributes.

@item 
bpo-23076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23076}: Path.glob() now raises a ValueError if it's called with an
invalid pattern. Patch by Thomas Nyberg.

@item 
bpo-19883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19883}: Fixed possible integer overflows in zipimport.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: On Windows, getnameinfo(), gethostbyaddr() and
gethostbyname_ex() functions of the socket module now decode the hostname
from the ANSI code page rather than UTF-8.

@item 
bpo-26099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26099}: The site module now writes an error into stderr if
sitecustomize module can be imported but executing the module raise an
ImportError. Same change for usercustomize.

@item 
bpo-26147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26147}: xmlrpc now works with strings not encodable with used non-UTF-8
encoding.

@item 
bpo-25935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25935}: Garbage collector now breaks reference loops with OrderedDict.

@item 
bpo-16620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16620}: Fixed AttributeError in msilib.Directory.glob().

@item 
bpo-26013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26013}: Added compatibility with broken protocol 2 pickles created in
old Python 3 versions (3.4.3 and lower).

@item 
bpo-26129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26129}: Deprecated accepting non-integers in grp.getgrgid().

@item 
bpo-25850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25850}: Use cross-compilation by default for 64-bit Windows.

@item 
bpo-25822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25822}: Add docstrings to the fields of urllib.parse results. Patch
contributed by Swati Jaiswal.

@item 
bpo-22642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22642}: Convert trace module option parsing mechanism to argparse.
Patch contributed by SilentGhost.

@item 
bpo-24705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24705}: Fix sysconfig._parse_makefile not expanding $@{@} vars appearing
before $() vars.

@item 
bpo-26069@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26069}: Remove the deprecated apis in the trace module.

@item 
bpo-22138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22138}: Fix mock.patch behavior when patching descriptors. Restore
original values after patching. Patch contributed by Sean McCully.

@item 
bpo-25672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25672}: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode
option if it is safe to do so.

@item 
bpo-26012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26012}: Don't traverse into symlinks for @code{**} pattern in
pathlib.Path.[r]glob().

@item 
bpo-24120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24120}: Ignore PermissionError when traversing a tree with
pathlib.Path.[r]glob(). Patch by Ulrich Petri.

@item 
bpo-21815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21815}: Accept ] characters in the data portion of imap responses, in
order to handle the flags with square brackets accepted and produced by
servers such as gmail.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: fileinput now uses sys.stdin as-is if it does not have a buffer
attribute (restores backward compatibility).

@item 
bpo-25971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25971}: Optimized creating Fractions from floats by 2 times and from
Decimals by 3 times.

@item 
bpo-25802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25802}: Document as deprecated the remaining implementations of
importlib.abc.Loader.load_module().

@item 
bpo-25928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25928}: Add Decimal.as_integer_ratio().

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: Copying the lru_cache() wrapper object now always works,
independently from the type of the wrapped object (by returning the
original object unchanged).

@item 
bpo-25768@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25768}: Have the functions in compileall return booleans instead of
ints and add proper documentation and tests for the return values.

@item 
bpo-24103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24103}: Fixed possible use after free in ElementTree.XMLPullParser.

@item 
bpo-25860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25860}: os.fwalk() no longer skips remaining directories when error
occurs. Original patch by Samson Lee.

@item 
bpo-25914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25914}: Fixed and simplified OrderedDict.__sizeof__.

@item 
bpo-25869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25869}: Optimized deepcopying ElementTree; it is now 20 times faster.

@item 
bpo-25873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25873}: Optimized iterating ElementTree.  Iterating elements
Element.iter() is now 40% faster, iterating text Element.itertext() is now
up to 2.5 times faster.

@item 
bpo-25902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25902}: Fixed various refcount issues in ElementTree iteration.

@item 
bpo-22227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22227}: The TarFile iterator is reimplemented using generator. This
implementation is simpler that using class.

@item 
bpo-25638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25638}: Optimized ElementTree.iterparse(); it is now 2x faster.
Optimized ElementTree parsing; it is now 10% faster.

@item 
bpo-25761@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25761}: Improved detecting errors in broken pickle data.

@item 
bpo-25717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25717}: Restore the previous behaviour of tolerating most fstat()
errors when opening files.  This was a regression in 3.5a1, and stopped
anonymous temporary files from working in special cases.

@item 
bpo-24903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24903}: Fix regression in number of arguments compileall accepts when
'-d' is specified.  The check on the number of arguments has been dropped
completely as it never worked correctly anyway.

@item 
bpo-25764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25764}: In the subprocess module, preserve any exception caused by
fork() failure when preexec_fn is used.

@item 
bpo-25771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25771}: Tweak the exception message for importlib.util.resolve_name()
when 'package' isn't specified but necessary.

@item 
bpo-6478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6478}: _strptime's regexp cache now is reset after changing timezone
with time.tzset().

@item 
bpo-14285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14285}: When executing a package with the "python -m package" option,
and package initialization fails, a proper traceback is now reported.  The
"runpy" module now lets exceptions from package initialization pass back
to the caller, rather than raising ImportError.

@item 
bpo-19771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19771}: Also in runpy and the "-m" option, omit the irrelevant message
". . . is a package and cannot be directly executed" if the package could
not even be initialized (e.g. due to a bad @code{*.pyc} file).

@item 
bpo-25177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25177}: Fixed problem with the mean of very small and very large
numbers. As a side effect, statistics.mean and statistics.variance should
be significantly faster.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed copying object with state with boolean value is false.

@item 
bpo-10131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10131}: Fixed deep copying of minidom documents.  Based on patch by
Marian Ganisin.

@item 
bpo-7990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7990}: dir() on ElementTree.Element now lists properties: "tag",
"text", "tail" and "attrib".  Original patch by Santoso Wijaya.

@item 
bpo-25725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25725}: Fixed a reference leak in pickle.loads() when unpickling
invalid data including tuple instructions.

@item 
bpo-25663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25663}: In the Readline completer, avoid listing duplicate global
names, and search the global namespace before searching builtins.

@item 
bpo-25688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25688}: Fixed file leak in ElementTree.iterparse() raising an error.

@item 
bpo-23914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23914}: Fixed SystemError raised by unpickler on broken pickle data.

@item 
bpo-25691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25691}: Fixed crash on deleting ElementTree.Element attributes.

@item 
bpo-25624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25624}: ZipFile now always writes a ZIP_STORED header for directory
entries.  Patch by Dingyuan Wang.

@item 
bpo-25626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25626}: Change three zlib functions to accept sizes that fit in
Py_ssize_t, but internally cap those sizes to UINT_MAX.  This resolves a
regression in 3.5 where GzipFile.read() failed to read chunks larger than
2 or 4 GiB.  The change affects the zlib.Decompress.decompress()
max_length parameter, the zlib.decompress() bufsize parameter, and the
zlib.Decompress.flush() length parameter.

@item 
bpo-25583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25583}: Avoid incorrect errors raised by os.makedirs(exist_ok=True)
when the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}: Change semantics of EventLoop.stop() in asyncio.

@item 
bpo-6973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6973}: When we know a subprocess.Popen process has died, do not allow
the send_signal(), terminate(), or kill() methods to do anything as they
could potentially signal a different process.

@item 
bpo-23883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23883}: Added missing APIs to __all__ to match the documented APIs for
the following modules: calendar, csv, enum, fileinput, ftplib, logging,
optparse, tarfile, threading and wave.  Also added a
test.support.check__all__() helper. Patches by Jacek Kołodziej, Mauro S.
M. Rodrigues and Joel Taddei.

@item 
bpo-25590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25590}: In the Readline completer, only call getattr() once per
attribute.  Also complete names of attributes such as properties and slots
which are listed by dir() but not yet created on an instance.

@item 
bpo-25498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25498}: Fix a crash when garbage-collecting ctypes objects created by
wrapping a memoryview.  This was a regression made in 3.5a1.  Based on
patch by Eryksun.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Added "escape" to the __all__ list in the glob module.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Fixed recursive glob() with patterns starting with @code{**}.

@item 
bpo-25446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25446}: Fix regression in smtplib's AUTH LOGIN support.

@item 
bpo-18010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18010}: Fix the pydoc web server's module search function to handle
exceptions from importing packages.

@item 
bpo-25554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25554}: Got rid of circular references in regular expression parsing.

@item 
bpo-18973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18973}: Command-line interface of the calendar module now uses argparse
instead of optparse.

@item 
bpo-25510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25510}: fileinput.FileInput.readline() now returns b'@w{'} instead of '@w{'} at
the end if the FileInput was opened with binary mode. Patch by Ryosuke
Ito.

@item 
bpo-25503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25503}: Fixed inspect.getdoc() for inherited docstrings of properties.
Original patch by John Mark Vandenberg.

@item 
bpo-25515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25515}: Always use os.urandom as a source of randomness in uuid.uuid4.

@item 
bpo-21827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21827}: Fixed textwrap.dedent() for the case when largest common
whitespace is a substring of smallest leading whitespace. Based on patch
by Robert Li.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: The lru_cache() wrapper objects now can be copied and pickled
(by returning the original object unchanged).

@item 
bpo-25390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25390}: typing: Don't crash on Union[str, Pattern].

@item 
bpo-25441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25441}: asyncio: Raise error from drain() when socket is closed.

@item 
bpo-25410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25410}: Cleaned up and fixed minor bugs in C implementation of
OrderedDict.

@item 
bpo-25411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25411}: Improved Unicode support in SMTPHandler through better use of
the email package. Thanks to user simon04 for the patch.

@item 
Move the imp module from a PendingDeprecationWarning to
DeprecationWarning.

@item 
bpo-25407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25407}: Remove mentions of the formatter module being removed in Python
3.6.

@item 
bpo-25406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25406}: Fixed a bug in C implementation of OrderedDict.move_to_end()
that caused segmentation fault or hang in iterating after moving several
items to the start of ordered dict.

@item 
bpo-25382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25382}: pickletools.dis() now outputs implicit memo index for the
MEMOIZE opcode.

@item 
bpo-25357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25357}: Add an optional newline parameter to binascii.b2a_base64().
base64.b64encode() uses it to avoid a memory copy.

@item 
bpo-24164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24164}: Objects that need calling @code{__new__} with keyword arguments,
can now be pickled using pickle protocols older than protocol version 4.

@item 
bpo-25364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25364}: zipfile now works in threads disabled builds.

@item 
bpo-25328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25328}: smtpd's SMTPChannel now correctly raises a ValueError if both
decode_data and enable_SMTPUTF8 are set to true.

@item 
bpo-16099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16099}: RobotFileParser now supports Crawl-delay and Request-rate
extensions.  Patch by Nikolay Bogoychev.

@item 
bpo-25316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25316}: distutils raises OSError instead of DistutilsPlatformError when
MSVC is not installed.

@item 
bpo-25380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25380}: Fixed protocol for the STACK_GLOBAL opcode in
pickletools.opcodes.

@item 
bpo-23972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23972}: Updates asyncio datagram create method allowing reuseport and
reuseaddr socket options to be set prior to binding the socket. Mirroring
the existing asyncio create_server method the reuseaddr option for
datagram sockets defaults to True if the O/S is 'posix' (except if the
platform is Cygwin). Patch by Chris Laws.

@item 
bpo-25304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25304}: Add asyncio.run_coroutine_threadsafe().  This lets you submit a
coroutine to a loop from another thread, returning a
concurrent.futures.Future.  By Vincent Michel.

@item 
bpo-25232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25232}: Fix CGIRequestHandler to split the query from the URL at the
first question mark (?) rather than the last. Patch from Xiang Zhang.

@item 
bpo-24657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24657}: Prevent CGIRequestHandler from collapsing slashes in the query
part of the URL as if it were a path. Patch from Xiang Zhang.

@item 
bpo-25287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25287}: Don't add crypt.METHOD_CRYPT to crypt.methods if it's not
supported. Check if it is supported, it may not be supported on OpenBSD
for example.

@item 
bpo-23600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23600}: Default implementation of tzinfo.fromutc() was returning wrong
results in some cases.

@item 
bpo-25203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25203}: Failed readline.set_completer_delims() no longer left the
module in inconsistent state.

@item 
bpo-25011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25011}: rlcompleter now omits private and special attribute names
unless the prefix starts with underscores.

@item 
bpo-25209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25209}: rlcompleter now can add a space or a colon after completed
keyword.

@item 
bpo-22241@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22241}: timezone.utc name is now plain 'UTC', not 'UTC-00:00'.

@item 
bpo-23517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23517}: fromtimestamp() and utcfromtimestamp() methods of
datetime.datetime now round microseconds to nearest with ties going to
nearest even integer (ROUND_HALF_EVEN), as round(float), instead of
rounding towards -Infinity (ROUND_FLOOR).

@item 
bpo-23552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23552}: Timeit now warns when there is substantial (4x) variance
between best and worst times. Patch from Serhiy Storchaka.

@item 
bpo-24633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24633}: site-packages/README -> README.txt.

@item 
bpo-24879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24879}: help() and pydoc can now list named tuple fields in the order
they were defined rather than alphabetically.  The ordering is determined
by the _fields attribute if present.

@item 
bpo-24874@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24874}: Improve speed of itertools.cycle() and make its pickle more
compact.

@item 
Fix crash in itertools.cycle.__setstate__() when the first argument wasn't
a list.

@item 
bpo-20059@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20059}: urllib.parse raises ValueError on all invalid ports. Patch by
Martin Panter.

@item 
bpo-24360@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24360}: Improve __repr__ of argparse.Namespace() for invalid
identifiers.  Patch by Matthias Bussonnier.

@item 
bpo-23426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23426}: run_setup was broken in distutils. Patch from Alexander
Belopolsky.

@item 
bpo-13938@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13938}: 2to3 converts StringTypes to a tuple. Patch from Mark Hammond.

@item 
bpo-2091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2091}: open() accepted a 'U' mode string containing '+', but 'U' can
only be used with 'r'. Patch from Jeff Balogh and John O'Connor.

@item 
bpo-8585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8585}: improved tests for zipimporter2. Patch from Mark Lawrence.

@item 
bpo-18622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18622}: unittest.mock.mock_open().reset_mock would recurse infinitely.
Patch from Nicola Palumbo and Laurent De Buyst.

@item 
bpo-24426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24426}: Fast searching optimization in regular expressions now works
for patterns that starts with capturing groups.  Fast searching
optimization now can't be disabled at compile time.

@item 
bpo-23661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23661}: unittest.mock side_effects can now be exceptions again. This
was a regression vs Python 3.4. Patch from Ignacio Rossi

@item 
bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}: Remove deprecated inspect.getmoduleinfo function.

@item 
bpo-25578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25578}: Fix (another) memory leak in SSLSocket.getpeercer().

@item 
bpo-25530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25530}: Disable the vulnerable SSLv3 protocol by default when creating
ssl.SSLContext.

@item 
bpo-25569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25569}: Fix memory leak in SSLSocket.getpeercert().

@item 
bpo-25471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25471}: Sockets returned from accept() shouldn't appear to be
nonblocking.

@item 
bpo-25319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25319}: When threading.Event is reinitialized, the underlying condition
should use a regular lock rather than a recursive lock.

@item 
Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu
Davis.

@item 
bpo-26050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26050}: Add asyncio.StreamReader.readuntil() method. Patch by Марк
Коренберг.

@item 
bpo-25924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25924}: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X
versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.

@item 
bpo-26406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26406}: Avoid unnecessary serialization of getaddrinfo(3) calls on
current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.

@item 
bpo-26848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26848}: Fix asyncio/subprocess.communicate() to handle empty input.
Patch by Jack O'Connor.

@item 
bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}: Add loop.get_exception_handler method

@item 
bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}: asyncio: Add loop.create_future method
@end itemize

@node IDLE<44>,Documentation<47>,Library<63>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id479}@anchor{12dd}
@subsubsection IDLE



@itemize -

@item 
bpo-20640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20640}: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav
Heblikar.

@item 
In the 'IDLE-console differences' section of the IDLE doc, clarify how
running with IDLE affects sys.modules and the standard streams.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: fix incorrect change in IOBinding that prevented printing.
Augment IOBinding htest to include all major IOBinding functions.

@item 
bpo-25905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25905}: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
MARK in README.txt and open this and NEWS.txt with 'ascii'. Re-encode
CREDITS.txt to utf-8 and open it with 'utf-8'.

@item 
bpo-15348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15348}: Stop the debugger engine (normally in a user process) before
closing the debugger window (running in the IDLE process). This prevents
the RuntimeErrors that were being caught and ignored.

@item 
bpo-24455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24455}: Prevent IDLE from hanging when a) closing the shell while the
debugger is active (15347); b) closing the debugger with the [X] button
(15348); and c) activating the debugger when already active (24455). The
patch by Mark Roseman does this by making two changes. 1. Suspend and
resume the gui.interaction method with the tcl vwait mechanism intended
for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow
any existing interaction to terminate first.

@item 
Change 'The program' to 'Your program' in an IDLE 'kill program?' message
to make it clearer that the program referred to is the currently running
user program, not IDLE itself.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Improve the appearance of the IDLE editor window status bar.
Patch by Mark Roseman.

@item 
bpo-25313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25313}: Change the handling of new built-in text color themes to better
address the compatibility problem introduced by the addition of IDLE Dark.
Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

@item 
bpo-24782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24782}: Extension configuration is now a tab in the IDLE Preferences
dialog rather than a separate dialog.  The former tabs are now a sorted
list.  Patch by Mark Roseman.

@item 
bpo-22726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22726}: Re-activate the config dialog help button with some content
about the other buttons and the new IDLE Dark theme.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: IDLE now has an 'IDLE Dark' built-in text color theme. It is
more or less IDLE Classic inverted, with a cobalt blue background.
Strings, comments, keywords, ... are still green, red, orange, ... . To
use it with IDLEs released before November 2015, hit the 'Save as New
Custom Theme' button and enter a new name, such as 'Custom Dark'.  The
custom theme will work with any IDLE release, and can be modified.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: README.txt is now an idlelib index for IDLE developers and
curious users. The previous user content is now in the IDLE doc chapter.
'IDLE' now means 'Integrated Development and Learning Environment'.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: Users can now set breakpoint colors in Settings -> Custom
Highlighting. Original patch by Mark Roseman.

@item 
bpo-24972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24972}: Inactive selection background now matches active selection
background, as configured by users, on all systems.  Found items are now
always highlighted on Windows.  Initial patch by Mark Roseman.

@item 
bpo-24570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24570}: Idle: make calltip and completion boxes appear on Macs affected
by a tk regression.  Initial patch by Mark Roseman.

@item 
bpo-24988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24988}: Idle ScrolledList context menus (used in debugger) now work on
Mac Aqua. Patch by Mark Roseman.

@item 
bpo-24801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24801}: Make right-click for context menu work on Mac Aqua. Patch by
Mark Roseman.

@item 
bpo-25173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25173}: Associate tkinter messageboxes with a specific widget. For Mac
OSX, make them a 'sheet'.  Patch by Mark Roseman.

@item 
bpo-25198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25198}: Enhance the initial html viewer now used for Idle Help.
Properly indent fixed-pitch text (patch by Mark Roseman). Give code
snippet a very Sphinx-like light blueish-gray background. Re-use initial
width and height set by users for shell and editor. When the Table of
Contents (TOC) menu is used, put the section header at the top of the
screen.

@item 
bpo-25225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25225}: Condense and rewrite Idle doc section on text colors.

@item 
bpo-21995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21995}: Explain some differences between IDLE and console Python.

@item 
bpo-22820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22820}: Explain need for @emph{print} when running file from Idle editor.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: Doc: augment Idle feature list and no-subprocess section.

@item 
bpo-25219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25219}: Update doc for Idle command line options. Some were missing and
notes were not correct.

@item 
bpo-24861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24861}: Most of idlelib is private and subject to change. Use
idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

@item 
bpo-25199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25199}: Idle: add synchronization comments for future maintainers.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Replace help.txt with help.html for Idle doc display. The new
idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks
better than help.txt and will better document Idle as released. The
tkinter html viewer that works for this file was written by Rose Roseman.
The now unused EditorWindow.HelpDialog class and helt.txt file are
deprecated.

@item 
bpo-24199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24199}: Deprecate unused idlelib.idlever with possible removal in 3.6.

@item 
bpo-24790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24790}: Remove extraneous code (which also create 2 & 3 conflicts).
@end itemize

@node Documentation<47>,Tests<50>,IDLE<44>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id480}@anchor{12de}
@subsubsection Documentation



@itemize -

@item 
bpo-26736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26736}: Used HTTPS for external links in the documentation if possible.

@item 
bpo-6953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6953}: Rework the Readline module documentation to group related
functions together, and add more details such as what underlying Readline
functions and variables are accessed.

@item 
bpo-23606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23606}: Adds note to ctypes documentation regarding cdll.msvcrt.

@item 
bpo-24952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24952}: Clarify the default size argument of stack_size() in the
"threading" and "_thread" modules. Patch from Mattip.

@item 
bpo-26014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26014}: Update 3.x packaging documentation: * "See also" links to the
new docs are now provided in the legacy pages * links to setuptools
documentation have been updated
@end itemize

@node Tests<50>,Build<52>,Documentation<47>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id481}@anchor{12df}
@subsubsection Tests



@itemize -

@item 
bpo-21916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21916}: Added tests for the turtle module.  Patch by ingrid, Gregory
Loyse and Jelle Zijlstra.

@item 
bpo-26295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26295}: When using "python3 -m test --testdir=TESTDIR", regrtest
doesn't add "test." prefix to test module names.

@item 
bpo-26523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26523}: The multiprocessing thread pool (multiprocessing.dummy.Pool)
was untested.

@item 
bpo-26015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26015}: Added new tests for pickling iterators of mutable sequences.

@item 
bpo-26325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26325}: Added test.support.check_no_resource_warning() to check that no
ResourceWarning is emitted.

@item 
bpo-25940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25940}: Changed test_ssl to use its internal local server more.  This
avoids relying on svn.python.org, which recently changed root certificate.

@item 
bpo-25616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25616}: Tests for OrderedDict are extracted from test_collections into
separate file test_ordered_dict.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Added tests for OrderedDict subclasses.

@item 
bpo-25188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25188}: Add -P/--pgo to test.regrtest to suppress error output when
running the test suite for the purposes of a PGO build. Initial patch by
Alecsandru Patrascu.

@item 
bpo-22806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22806}: Add @code{python -m test --list-tests} command to list tests.

@item 
bpo-18174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18174}: @code{python -m test --huntrleaks ...} now also checks for leak of
file descriptors. Patch written by Richard Oudkerk.

@item 
bpo-25260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25260}: Fix @code{python -m test --coverage} on Windows. Remove the list
of ignored directories.

@item 
@code{PCbuild\rt.bat} now accepts an unlimited number of arguments to pass
along to regrtest.py.  Previously there was a limit of 9.

@item 
bpo-26583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26583}: Skip test_timestamp_overflow in test_import if bytecode files
cannot be written.
@end itemize

@node Build<52>,Windows<49>,Tests<50>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id482}@anchor{12e0}
@subsubsection Build



@itemize -

@item 
bpo-21277@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21277}: Don't try to link _ctypes with a ffi_convenience library.

@item 
bpo-26884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26884}: Fix linking extension modules for cross builds. Patch by Xavier
de Gaye.

@item 
bpo-26932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26932}: Fixed support of RTLD_* constants defined as enum values, not
via macros (in particular on Android).  Patch by Chi Hsuan Yen.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Disable the rules for running _freeze_importlib and pgen when
cross-compiling.  The output of these programs is normally saved with the
source code anyway, and is still regenerated when doing a native build.
Patch by Xavier de Gaye.

@item 
bpo-21668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21668}: Link audioop, _datetime, _ctypes_test modules to libm, except
on Mac OS X. Patch written by Chi Hsuan Yen.

@item 
bpo-25702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25702}: A --with-lto configure option has been added that will enable
link time optimizations at build time during a make profile-opt. Some
compilers and toolchains are known to not produce stable code when using
LTO, be sure to test things thoroughly before relying on it. It can
provide a few % speed up over profile-opt alone.

@item 
bpo-26624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26624}: Adds validation of ucrtbase[d].dll version with warning for old
versions.

@item 
bpo-17603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17603}: Avoid error about nonexistent fileblocks.o file by using a
lower-level check for st_blocks in struct stat.

@item 
bpo-26079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26079}: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern
Thiel.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update Windows builds to use OpenSSL 1.0.2g.

@item 
bpo-25348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25348}: Added @code{--pgo} and @code{--pgo-job} arguments to
@code{PCbuild\build.bat} for building with Profile-Guided Optimization.  The
old @code{PCbuild\build_pgo.bat} script is removed.

@item 
bpo-25827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25827}: Add support for building with ICC to @code{configure}, including a
new @code{--with-icc} flag.

@item 
bpo-25696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25696}: Fix installation of Python on UNIX with make -j9.

@item 
bpo-24986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24986}: It is now possible to build Python on Windows without errors
when external libraries are not available.

@item 
bpo-24421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24421}: Compile Modules/_math.c once, before building extensions.
Previously it could fail to compile properly if the math and cmath builds
were concurrent.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2g.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update Windows builds to use OpenSSL 1.0.2f.

@item 
bpo-25136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25136}: Support Apple Xcode 7's new textual SDK stub libraries.

@item 
bpo-24324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24324}: Do not enable unreachable code warnings when using gcc as the
option does not work correctly in older versions of gcc and has been
silently removed as of gcc-4.5.
@end itemize

@node Windows<49>,Tools/Demos<29>,Build<52>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id483}@anchor{12e1}
@subsubsection Windows



@itemize -

@item 
bpo-27053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27053}: Updates make_zip.py to correctly generate library ZIP file.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update the prepare_ssl.py script to handle OpenSSL releases
that don't include the contents of the include directory (that is, 1.0.2e
and later).

@item 
bpo-26071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26071}: bdist_wininst created binaries fail to start and find 32bit
Python

@item 
bpo-26073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26073}: Update the list of magic numbers in launcher

@item 
bpo-26065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26065}: Excludes venv from library when generating embeddable distro.

@item 
bpo-25022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25022}: Removed very outdated PC/example_nt/ directory.
@end itemize

@node Tools/Demos<29>,C API<38>,Windows<49>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id484}@anchor{12e2}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26799}: Fix python-gdb.py: don't get C types once when the Python code
is loaded, but get C types on demand. The C types can change if
python-gdb.py is loaded before the Python executable. Patch written by
Thomas Ilsche.

@item 
bpo-26271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26271}: Fix the Freeze tool to properly use flags passed through
configure. Patch by Daniel Shaulov.

@item 
bpo-26489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26489}: Add dictionary unpacking support to Tools/parser/unparse.py.
Patch by Guo Ci Teo.

@item 
bpo-26316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26316}: Fix variable name typo in Argument Clinic.

@item 
bpo-25440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25440}: Fix output of python-config --extension-suffix.

@item 
bpo-25154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25154}: The pyvenv script has been deprecated in favour of @code{python3 -m
venv}.
@end itemize

@node C API<38>,,Tools/Demos<29>,Python 3 6 0 alpha 1
@anchor{whatsnew/changelog id485}@anchor{12e3}
@subsubsection C API



@itemize -

@item 
bpo-26312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26312}: SystemError is now raised in all programming bugs with using
PyArg_ParseTupleAndKeywords().  RuntimeError did raised before in some
programming bugs.

@item 
bpo-26198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26198}: ValueError is now raised instead of TypeError on buffer
overflow in parsing "es#" and "et#" format units.  SystemError is now
raised instead of TypeError on programmatical error in parsing format
string.
@end itemize

@node Python 3 5 5 final,Python 3 5 5 release candidate 1,Python 3 6 0 alpha 1,更新日志
@anchor{whatsnew/changelog python-3-5-5-final}@anchor{12e4}
@subsection Python 3.5.5 final


@emph{Release date: 2018-02-04}

There were no new changes in version 3.5.5.

@node Python 3 5 5 release candidate 1,Python 3 5 4 final,Python 3 5 5 final,更新日志
@anchor{whatsnew/changelog python-3-5-5-release-candidate-1}@anchor{12e5}
@subsection Python 3.5.5 release candidate 1


@emph{Release date: 2018-01-23}

@menu
* Security: Security<33>. 
* Core and Builtins: Core and Builtins<62>. 
* Library: Library<64>. 

@end menu

@node Security<33>,Core and Builtins<62>,,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id486}@anchor{12e6}
@subsubsection Security



@itemize -

@item 
bpo-32551@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32551}: The @code{sys.path[0]} initialization change for bpo-29139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29139} caused
a regression by revealing an inconsistency in how sys.path is initialized
when executing @code{__main__} from a zipfile, directory, or other import
location. This is considered a potential security issue, as it may lead to
privileged processes unexpectedly loading code from user controlled
directories in situations where that was not previously the case. The
interpreter now consistently avoids ever adding the import location's
parent directory to @code{sys.path}, and ensures no other @code{sys.path}
entries are inadvertently modified when inserting the import location
named on the command line. (Originally reported as bpo-29723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29723} against
Python 3.6rc1, but it was missed at the time that the then upcoming Python
3.5.4 release would also be affected)

@item 
bpo-30657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30657}: Fixed possible integer overflow in PyBytes_DecodeEscape,
CVE-2017-1000158. Original patch by Jay Bosamiya; rebased to Python 3 by
Miro Hrončok.

@item 
bpo-30947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30947}: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
get security fixes.
@end itemize

@node Core and Builtins<62>,Library<64>,Security<33>,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id487}@anchor{12e7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-31095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31095}: Fix potential crash during GC caused by @code{tp_dealloc} which
doesn't call @code{PyObject_GC_UnTrack()}.
@end itemize

@node Library<64>,,Core and Builtins<62>,Python 3 5 5 release candidate 1
@anchor{whatsnew/changelog id488}@anchor{12e8}
@subsubsection Library



@itemize -

@item 
bpo-32072@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=32072}: Fixed issues with binary plists: Fixed saving bytearrays.
Identical objects will be saved only once. Equal references will be load
as identical objects. Added support for saving and loading recursive data
structures.

@item 
bpo-31170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=31170}: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
partial characters for UTF-8 input (libexpat bug 115):
@indicateurl{https://github.com/libexpat/libexpat/issues/115}
@end itemize

@node Python 3 5 4 final,Python 3 5 4 release candidate 1,Python 3 5 5 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-4-final}@anchor{12e9}
@subsection Python 3.5.4 final


@emph{Release date: 2017-08-07}

@menu
* Library: Library<65>. 

@end menu

@node Library<65>,,,Python 3 5 4 final
@anchor{whatsnew/changelog id489}@anchor{12ea}
@subsubsection Library



@itemize -

@item 
bpo-30119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30119}: ftplib.FTP.putline() now throws ValueError on commands that
contains CR or LF. Patch by Dong-hee Na.
@end itemize

@node Python 3 5 4 release candidate 1,Python 3 5 3 final,Python 3 5 4 final,更新日志
@anchor{whatsnew/changelog python-3-5-4-release-candidate-1}@anchor{12eb}
@subsection Python 3.5.4 release candidate 1


@emph{Release date: 2017-07-23}

@menu
* Security: Security<34>. 
* Core and Builtins: Core and Builtins<63>. 
* Library: Library<66>. 
* Documentation: Documentation<48>. 
* Tests: Tests<51>. 
* Build: Build<53>. 
* Windows: Windows<50>. 
* C API: C API<39>. 

@end menu

@node Security<34>,Core and Builtins<63>,,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id490}@anchor{12ec}
@subsubsection Security



@itemize -

@item 
bpo-30730@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30730}: Prevent environment variables injection in subprocess on
Windows.  Prevent passing other environment variables and command
arguments.

@item 
bpo-30694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30694}: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
security vulnerabilities including: CVE-2017-9233 (External entity
infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix),
CVE-2016-0718 (Fix regression bugs from 2.2.0's fix to CVE-2016-0718) and
CVE-2012-0876 (Counter hash flooding with SipHash). Note: the
CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn't
impact Python, since Python already gets entropy from the OS to set the
expat secret using @code{XML_SetHashSalt()}.

@item 
bpo-30500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30500}: Fix urllib.parse.splithost() to correctly parse fragments. For
example, @code{splithost('//127.0.0.1#@@evil.com/')} now correctly returns the
@code{127.0.0.1} host, instead of treating @code{@@evil.com} as the host in an
authentication (@code{login@@host}).

@item 
bpo-29591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29591}: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
CVE-2016-0718 and CVE-2016-4472. See
@indicateurl{https://sourceforge.net/p/expat/bugs/537/} for more information.
@end itemize

@node Core and Builtins<63>,Library<66>,Security<34>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id491}@anchor{12ed}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-30876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30876}: Relative import from unloaded package now reimports the package
instead of failing with SystemError.  Relative import from non-package now
fails with ImportError rather than SystemError.

@item 
bpo-30765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30765}: Avoid blocking in pthread_mutex_lock() when
PyThread_acquire_lock() is asked not to block.

@item 
bpo-27945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27945}: Fixed various segfaults with dict when input collections are
mutated during searching, inserting or comparing.  Based on patches by
Duane Griffin and Tim Mitchell.

@item 
bpo-25794@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25794}: Fixed type.__setattr__() and type.__delattr__() for
non-interned attribute names.  Based on patch by Eryk Sun.

@item 
bpo-29935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29935}: Fixed error messages in the index() method of tuple, list and
deque when pass indices of wrong type.

@item 
bpo-28876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28876}: @code{bool(range)} works even if @code{len(range)} raises
@ref{a4a,,OverflowError}.

@item 
bpo-29600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29600}: Fix wrapping coroutine return values in StopIteration.

@item 
bpo-29537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29537}: Restore runtime compatibility with bytecode files generated by
CPython 3.5.0 to 3.5.2, and adjust the eval loop to avoid the problems
that could be caused by the malformed variant of the
BUILD_MAP_UNPACK_WITH_CALL opcode that they may contain. Patch by Petr
Viktorin, Serhiy Storchaka, and Nick Coghlan.

@item 
bpo-28598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28598}: Support __rmod__ for subclasses of str being called before
str.__mod__. Patch by Martijn Pieters.

@item 
bpo-29602@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29602}: Fix incorrect handling of signed zeros in complex constructor
for complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka.

@item 
bpo-29347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29347}: Fixed possibly dereferencing undefined pointers when creating
weakref objects.

@item 
bpo-29438@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29438}: Fixed use-after-free problem in key sharing dict.

@item 
bpo-29319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29319}: Prevent RunMainFromImporter overwriting sys.path[0].

@item 
bpo-29337@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29337}: Fixed possible BytesWarning when compare the code objects.
Warnings could be emitted at compile time.

@item 
bpo-29478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29478}: If max_line_length=None is specified while using the Compat32
policy, it is no longer ignored.  Patch by Mircea Cosbuc.
@end itemize

@node Library<66>,Documentation<48>,Core and Builtins<63>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id492}@anchor{12ee}
@subsubsection Library



@itemize -

@item 
bpo-29403@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29403}: Fix @code{unittest.mock}'s autospec to not fail on method-bound
builtin functions.  Patch by Aaron Gallagher.

@item 
bpo-30961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30961}: Fix decrementing a borrowed reference in tracemalloc.

@item 
bpo-30886@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30886}: Fix multiprocessing.Queue.join_thread(): it now waits until the
thread completes, even if the thread was started by the same process which
created the queue.

@item 
bpo-29854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29854}: Fix segfault in readline when using readline's history-size
option.  Patch by Nir Soffer.

@item 
bpo-30807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30807}: signal.setitimer() may disable the timer when passed a tiny
value. Tiny values (such as 1e-6) are valid non-zero values for
setitimer(), which is specified as taking microsecond-resolution
intervals. However, on some platform, our conversion routine could convert
1e-6 into a zero interval, therefore disabling the timer instead of
(re-)scheduling it.

@item 
bpo-30441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30441}: Fix bug when modifying os.environ while iterating over it

@item 
bpo-30532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30532}: Fix email header value parser dropping folding white space in
certain cases.

@item 
bpo-29169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29169}: Update zlib to 1.2.11.

@item 
bpo-30879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30879}: os.listdir() and os.scandir() now emit bytes names when called
with bytes-like argument.

@item 
bpo-30746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30746}: Prohibited the '=' character in environment variable names in
@code{os.putenv()} and @code{os.spawn*()}.

@item 
bpo-29755@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29755}: Fixed the lgettext() family of functions in the gettext module.
They now always return bytes.

@item 
bpo-30645@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30645}: Fix path calculation in imp.load_package(), fixing it for cases
when a package is only shipped with bytecodes. Patch by Alexandru
Ardelean.

@item 
bpo-23890@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23890}: unittest.TestCase.assertRaises() now manually breaks a
reference cycle to not keep objects alive longer than expected.

@item 
bpo-30149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30149}: inspect.signature() now supports callables with
variable-argument parameters wrapped with partialmethod. Patch by Dong-hee
Na.

@item 
bpo-29931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29931}: Fixed comparison check for ipaddress.ip_interface objects.
Patch by Sanjay Sundaresan.

@item 
bpo-24484@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24484}: Avoid race condition in multiprocessing cleanup.

@item 
bpo-28994@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28994}: The traceback no longer displayed for SystemExit raised in a
callback registered by atexit.

@item 
bpo-30508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30508}: Don't log exceptions if Task/Future "cancel()" method was
called.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Updates to typing module: Add generic AsyncContextManager, add
support for ContextManager on all versions. Original PRs by Jelle Zijlstra
and Ivan Levkivskyi

@item 
bpo-29870@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29870}: Fix ssl sockets leaks when connection is aborted in asyncio/ssl
implementation. Patch by Michaël Sghaïer.

@item 
bpo-29743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29743}: Closing transport during handshake process leaks open socket.
Patch by Nikolay Kim

@item 
bpo-27585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27585}: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu
Sornay.

@item 
bpo-30418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30418}: On Windows, subprocess.Popen.communicate() now also ignore
EINVAL on stdin.write() if the child process is still running but closed
the pipe.

@item 
bpo-30378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30378}: Fix the problem that logging.handlers.SysLogHandler cannot
handle IPv6 addresses.

@item 
bpo-29960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29960}: Preserve generator state when _random.Random.setstate() raises
an exception. Patch by Bryan Olson.

@item 
bpo-30414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30414}: multiprocessing.Queue._feed background running thread do not
break from main loop on exception.

@item 
bpo-30003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30003}: Fix handling escape characters in HZ codec.  Based on patch by
Ma Lin.

@item 
bpo-30301@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30301}: Fix AttributeError when using SimpleQueue.empty() under @emph{spawn}
and @emph{forkserver} start methods.

@item 
bpo-30329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30329}: imaplib and poplib now catch the Windows socket WSAEINVAL error
(code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted.
This error occurs sometimes on SSL connections.

@item 
bpo-30375@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30375}: Warnings emitted when compile a regular expression now always
point to the line in the user code.  Previously they could point into
inners of the re module if emitted from inside of groups or conditionals.

@item 
bpo-30048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30048}: Fixed @code{Task.cancel()} can be ignored when the task is running
coroutine and the coroutine returned without any more @code{await}.

@item 
bpo-29990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29990}: Fix range checking in GB18030 decoder.  Original patch by Ma
Lin.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Change resulted because of zipfile breakage. (See also:
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094})

@item 
bpo-30243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30243}: Removed the __init__ methods of _json's scanner and encoder.
Misusing them could cause memory leaks or crashes.  Now scanner and
encoder objects are completely initialized in the __new__ methods.

@item 
bpo-30185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30185}: Avoid KeyboardInterrupt tracebacks in forkserver helper process
when Ctrl-C is received.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: add typing.NoReturn type, use
WrapperDescriptorType, minor bug-fixes.  Original PRs by Jim
Fasarakis-Hilliard and Ivan Levkivskyi.

@item 
bpo-30205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30205}: Fix getsockname() for unbound AF_UNIX sockets on Linux.

@item 
bpo-30070@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30070}: Fixed leaks and crashes in errors handling in the parser
module.

@item 
bpo-30061@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30061}: Fixed crashes in IOBase methods __next__() and readlines() when
readline() or __next__() respectively return non-sizeable object. Fixed
possible other errors caused by not checking results of PyObject_Size(),
PySequence_Size(), or PyMapping_Size().

@item 
bpo-30068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30068}: _io._IOBase.readlines will check if it's closed first when hint
is present.

@item 
bpo-29694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29694}: Fixed race condition in pathlib mkdir with flags parents=True.
Patch by Armin Rigo.

@item 
bpo-29692@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29692}: Fixed arbitrary unchaining of RuntimeError exceptions in
contextlib.contextmanager.  Patch by Siddharth Velankar.

@item 
bpo-29998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29998}: Pickling and copying ImportError now preserves name and path
attributes.

@item 
bpo-29942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29942}: Fix a crash in itertools.chain.from_iterable when encountering
long runs of empty iterables.

@item 
bpo-27863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27863}: Fixed multiple crashes in ElementTree caused by race conditions
and wrong types.

@item 
bpo-28699@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28699}: Fixed a bug in pools in multiprocessing.pool that raising an
exception at the very first of an iterable may swallow the exception or
make the program hang. Patch by Davin Potts and Xiang Zhang.

@item 
bpo-25803@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25803}: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when
the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-29861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29861}: Release references to tasks, their arguments and their results
as soon as they are finished in multiprocessing.Pool.

@item 
bpo-29884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29884}: faulthandler: Restore the old sigaltstack during teardown.
Patch by Christophe Zeitouny.

@item 
bpo-25455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25455}: Fixed crashes in repr of recursive buffered file-like objects.

@item 
bpo-29800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29800}: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings.  Patch by Michael Seifert.

@item 
bpo-29742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29742}: get_extra_info() raises exception if get called on closed ssl
transport. Patch by Nikolay Kim.

@item 
bpo-8256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8256}: Fixed possible failing or crashing input() if attributes
"encoding" or "errors" of sys.stdin or sys.stdout are not set or are not
strings.

@item 
bpo-28298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28298}: Fix a bug that prevented array 'Q', 'L' and 'I' from accepting
big intables (objects that have __int__) as elements.  Patch by Oren
Milman.

@item 
bpo-29615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29615}: SimpleXMLRPCDispatcher no longer chains KeyError (or any other
exception) to exception(s) raised in the dispatched methods. Patch by Petr
Motejlek.

@item 
bpo-29704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29704}: asyncio.subprocess.SubprocessStreamProtocol no longer closes
before all pipes are closed.

@item 
bpo-29703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29703}: Fix asyncio to support instantiation of new event loops in
child processes.

@item 
bpo-29376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29376}: Fix assertion error in threading._DummyThread.is_alive().

@item 
bpo-29110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29110}: Fix file object leak in aifc.open() when file is given as a
filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

@item 
bpo-28961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28961}: Fix unittest.mock._Call helper: don't ignore the name parameter
anymore. Patch written by Jiajun Huang.

@item 
bpo-29532@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29532}: Altering a kwarg dictionary passed to functools.partial() no
longer affects a partial object after creation.

@item 
bpo-28556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28556}: Various updates to typing module: typing.Counter,
typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle
Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

@item 
bpo-29100@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29100}: Fix datetime.fromtimestamp() regression introduced in Python
3.6.0: check minimum and maximum years.

@item 
bpo-29519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29519}: Fix weakref spewing exceptions during interpreter shutdown when
used with a rare combination of multiprocessing and custom codecs.

@item 
bpo-29416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29416}: Prevent infinite loop in pathlib.Path.mkdir

@item 
bpo-29444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29444}: Fixed out-of-bounds buffer access in the group() method of the
match object. Based on patch by WGH.

@item 
bpo-29335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29335}: Fix subprocess.Popen.wait() when the child process has exited
to a stopped instead of terminated state (ex: when under ptrace).

@item 
bpo-29290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29290}: Fix a regression in argparse that help messages would wrap at
non-breaking spaces.

@item 
bpo-28735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28735}: Fixed the comparison of mock.MagickMock with mock.ANY.

@item 
bpo-29011@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29011}: Fix an important omission by adding Deque to the typing module.

@item 
bpo-29219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29219}: Fixed infinite recursion in the repr of uninitialized
ctypes.CDLL instances.

@item 
bpo-28969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28969}: Fixed race condition in C implementation of
functools.lru_cache. KeyError could be raised when cached function with
full cache was simultaneously called from different threads with the same
uncached arguments.

@item 
bpo-29142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29142}: In urllib.request, suffixes in no_proxy environment variable
with leading dots could match related hostnames again (e.g. .b.c matches
a.b.c). Patch by Milan Oberkirch.
@end itemize

@node Documentation<48>,Tests<51>,Library<66>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id493}@anchor{12ef}
@subsubsection Documentation



@itemize -

@item 
bpo-30176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30176}: Add missing attribute related constants in curses
documentation.

@item 
bpo-26985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26985}: Add missing info of code object in inspect documentation.

@item 
bpo-28929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28929}: Link the documentation to its source file on GitHub.

@item 
bpo-25008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25008}: Document smtpd.py as effectively deprecated and add a pointer
to aiosmtpd, a third-party asyncio-based replacement.

@item 
bpo-26355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26355}: Add canonical header link on each page to corresponding major
version of the documentation. Patch by Matthias Bussonnier.

@item 
bpo-29349@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29349}: Fix Python 2 syntax in code for building the documentation.
@end itemize

@node Tests<51>,Build<53>,Documentation<48>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id494}@anchor{12f0}
@subsubsection Tests



@itemize -

@item 
bpo-30822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30822}: Fix regrtest command line parser to allow passing -u
extralargefile to run test_zipfile64.

@item 
bpo-30383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30383}: regrtest: Enhance regrtest and backport features from the
master branch. Add options: --coverage, --testdir, --list-tests (list test
files, don't run them), --list-cases (list test identifiers, don't run
them, bpo-30523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30523}), --matchfile (load a list of test filters from a
text file, bpo-30540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30540}), --slowest (alias to --slow). Enhance output:
add timestamp, test result, currently running tests, "Tests result: xxx"
summary with total duration, etc. Fix reference leak hunting in regrtest,
--huntrleaks: regrtest now warms up caches, create explicitly all internal
singletons which are created on demand to prevent false positives when
checking for reference leaks. (bpo-30675@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30675}).

@item 
bpo-30357@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30357}: test_thread: setUp() now uses support.threading_setup() and
support.threading_cleanup() to wait until threads complete to avoid random
side effects on following tests. Initial patch written by Grzegorz
Grzywacz.

@item 
bpo-28087@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28087}: Skip test_asyncore and test_eintr poll failures on macOS. Skip
some tests of select.poll when running on macOS due to unresolved issues
with the underlying system poll function on some macOS versions.

@item 
bpo-30197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30197}: Enhanced functions swap_attr() and swap_item() in the
test.support module. They now work when delete replaced attribute or item
inside the with statement.  The old value of the attribute or item (or
None if it doesn't exist) now will be assigned to the target of the "as"
clause, if there is one.

@item 
bpo-29571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29571}: to match the behaviour of the @code{re.LOCALE} flag,
test_re.test_locale_flag now uses @code{locale.getpreferredencoding(False)}
to determine the candidate encoding for the test regex (allowing it to
correctly skip the test when the default locale encoding is a multi-byte
encoding)
@end itemize

@node Build<53>,Windows<50>,Tests<51>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id495}@anchor{12f1}
@subsubsection Build



@itemize -

@item 
bpo-29243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29243}: Prevent unnecessary rebuilding of Python during @code{make test},
@code{make install} and some other make targets when configured with
@code{--enable-optimizations}.

@item 
bpo-23404@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23404}: Don't regenerate generated files based on file modification
time anymore: the action is now explicit. Replace @code{make touch} with
@code{make regen-all}.

@item 
bpo-29643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29643}: Fix @code{--enable-optimization} didn't work.
@end itemize

@node Windows<50>,C API<39>,Build<53>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id496}@anchor{12f2}
@subsubsection Windows



@itemize -

@item 
bpo-30687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=30687}: Locate msbuild.exe on Windows when building rather than
vcvarsall.bat

@item 
bpo-29392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29392}: Prevent crash when passing invalid arguments into msvcrt
module.
@end itemize

@node C API<39>,,Windows<50>,Python 3 5 4 release candidate 1
@anchor{whatsnew/changelog id497}@anchor{12f3}
@subsubsection C API



@itemize -

@item 
bpo-27867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27867}: Function PySlice_GetIndicesEx() is replaced with a macro if
Py_LIMITED_API is set to the value between 0x03050400 and 0x03060000 (not
including) or 0x03060100 or higher.

@item 
bpo-29083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29083}: Fixed the declaration of some public API functions.
PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in
limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and
Py_BuildValue() were not available in limited API of version < 3.3 when
PY_SSIZE_T_CLEAN is defined.
@end itemize

@node Python 3 5 3 final,Python 3 5 3 release candidate 1,Python 3 5 4 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-3-final}@anchor{12f4}
@subsection Python 3.5.3 final


@emph{Release date: 2017-01-17}

There were no code changes between 3.5.3rc1 and 3.5.3 final.

@node Python 3 5 3 release candidate 1,Python 3 5 2 final,Python 3 5 3 final,更新日志
@anchor{whatsnew/changelog python-3-5-3-release-candidate-1}@anchor{12f5}
@subsection Python 3.5.3 release candidate 1


@emph{Release date: 2017-01-02}

@menu
* Security: Security<35>. 
* Core and Builtins: Core and Builtins<64>. 
* Library: Library<67>. 
* IDLE: IDLE<45>. 
* C API: C API<40>. 
* Documentation: Documentation<49>. 
* Tests: Tests<52>. 
* Tools/Demos: Tools/Demos<30>. 
* Windows: Windows<51>. 
* Build: Build<54>. 

@end menu

@node Security<35>,Core and Builtins<64>,,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id498}@anchor{12f6}
@subsubsection Security



@itemize -

@item 
bpo-27278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27278}: Fix os.urandom() implementation using getrandom() on Linux.
Truncate size to INT_MAX and loop until we collected enough random bytes,
instead of casting a directly Py_ssize_t to int.

@item 
bpo-22636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22636}: Avoid shell injection problems with ctypes.util.find_library().
@end itemize

@node Core and Builtins<64>,Library<67>,Security<35>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id499}@anchor{12f7}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-29073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29073}: bytearray formatting no longer truncates on first null byte.

@item 
bpo-28932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28932}: Do not include <sys/random.h> if it does not exist.

@item 
bpo-28147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28147}: Fix a memory leak in split-table dictionaries: setattr() must
not convert combined table into split table.

@item 
bpo-25677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25677}: Correct the positioning of the syntax error caret for indented
blocks. Based on patch by Michael Layzell.

@item 
bpo-29000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29000}: Fixed bytes formatting of octals with zero padding in alternate
form.

@item 
bpo-28512@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28512}: Fixed setting the offset attribute of SyntaxError by
PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

@item 
bpo-28991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28991}: functools.lru_cache() was susceptible to an obscure reentrancy
bug caused by a monkey-patched len() function.

@item 
bpo-28648@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28648}: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
when decode astral characters.  Patch by Xiang Zhang.

@item 
bpo-19398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19398}: Extra slash no longer added to sys.path components in case of
empty compile-time PYTHONPATH components.

@item 
bpo-28426@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28426}: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
build.

@item 
bpo-23782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23782}: Fixed possible memory leak in _PyTraceback_Add() and exception
loss in PyTraceBack_Here().

@item 
bpo-28379@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28379}: Added sanity checks and tests for PyUnicode_CopyCharacters().
Patch by Xiang Zhang.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The type of long range iterator is now registered as Iterator.
Patch by Oren Milman.

@item 
bpo-28376@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28376}: The constructor of range_iterator now checks that step is not
0. Patch by Oren Milman.

@item 
bpo-26906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26906}: Resolving special methods of uninitialized type now causes
implicit initialization of the type instead of a fail.

@item 
bpo-18287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18287}: PyType_Ready() now checks that tp_name is not NULL. Original
patch by Niklas Koep.

@item 
bpo-24098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24098}: Fixed possible crash when AST is changed in process of
compiling it.

@item 
bpo-28350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28350}: String constants with null character no longer interned.

@item 
bpo-26617@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26617}: Fix crash when GC runs during weakref callbacks.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: String constants now interned recursively in tuples and
frozensets.

@item 
bpo-21578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21578}: Fixed misleading error message when ImportError called with
invalid keyword args.

@item 
bpo-28203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28203}: Fix incorrect type in error message from @code{complex(1.0,
@{2:3@})}. Patch by Soumya Sharma.

@item 
bpo-27955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27955}: Fallback on reading /dev/urandom device when the getrandom()
syscall fails with EPERM, for example when blocked by SECCOMP.

@item 
bpo-28131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28131}: Fix a regression in zipimport's compile_source().  zipimport
should use the same optimization level as the interpreter.

@item 
bpo-25221@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25221}: Fix corrupted result from PyLong_FromLong(0) when Python is
compiled with NSMALLPOSINTS = 0.

@item 
bpo-25758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25758}: Prevents zipimport from unnecessarily encoding a filename
(patch by Eryk Sun)

@item 
bpo-28189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28189}: dictitems_contains no longer swallows compare errors. (Patch by
Xiang Zhang)

@item 
bpo-27812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27812}: Properly clear out a generator's frame's backreference to the
generator to prevent crashes in frame.clear().

@item 
bpo-27811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27811}: Fix a crash when a coroutine that has not been awaited is
finalized with warnings-as-errors enabled.

@item 
bpo-27587@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27587}: Fix another issue found by PVS-Studio: Null pointer check after
use of 'def' in _PyState_AddModule(). Initial patch by Christian Heimes.

@item 
bpo-26020@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26020}: set literal evaluation order did not match documented
behaviour.

@item 
bpo-27782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27782}: Multi-phase extension module import now correctly allows the
@code{m_methods} field to be used to add module level functions to instances
of non-module types returned from @code{Py_create_mod}. Patch by Xiang Zhang.

@item 
bpo-27936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27936}: The round() function accepted a second None argument for some
types but not for others.  Fixed the inconsistency by accepting None for
all numeric types.

@item 
bpo-27487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27487}: Warn if a submodule argument to "python -m" or
runpy.run_module() is found in sys.modules after parent packages are
imported, but before the submodule is executed.

@item 
bpo-27558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27558}: Fix a SystemError in the implementation of "raise" statement.
In a brand new thread, raise a RuntimeError since there is no active
exception to reraise. Patch written by Xiang Zhang.

@item 
bpo-27419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27419}: Standard __import__() no longer look up "__import__" in globals
or builtins for importing submodules or "from import".  Fixed handling an
error of non-string package name.

@item 
bpo-27083@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27083}: Respect the PYTHONCASEOK environment variable under Windows.

@item 
bpo-27514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27514}: Make having too many statically nested blocks a SyntaxError
instead of SystemError.

@item 
bpo-27473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27473}: Fixed possible integer overflow in bytes and bytearray
concatenations. Patch by Xiang Zhang.

@item 
bpo-27507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27507}: Add integer overflow check in bytearray.extend().  Patch by
Xiang Zhang.

@item 
bpo-27581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27581}: Don't rely on wrapping for overflow check in
PySequence_Tuple().  Patch by Xiang Zhang.

@item 
bpo-27443@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27443}: __length_hint__() of bytearray iterators no longer return a
negative integer for a resized bytearray.

@item 
bpo-27942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27942}: Fix memory leak in codeobject.c
@end itemize

@node Library<67>,IDLE<45>,Core and Builtins<64>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id500}@anchor{12f8}
@subsubsection Library



@itemize -

@item 
bpo-15812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15812}: inspect.getframeinfo() now correctly shows the first line of a
context. Patch by Sam Breese.

@item 
bpo-29094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29094}: Offsets in a ZIP file created with extern file object and modes
"w" and "x" now are relative to the start of the file.

@item 
bpo-13051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13051}: Fixed recursion errors in large or resized
curses.textpad.Textbox.  Based on patch by Tycho Andersen.

@item 
bpo-29119@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29119}: Fix weakrefs in the pure python version of
collections.OrderedDict move_to_end() method. Contributed by Andra
Bogildea.

@item 
bpo-9770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9770}: curses.ascii predicates now work correctly with negative
integers.

@item 
bpo-28427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28427}: old keys should not remove new values from WeakValueDictionary
when collecting from another thread.

@item 
bpo-28923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28923}: Remove editor artifacts from Tix.py.

@item 
bpo-28871@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28871}: Fixed a crash when deallocate deep ElementTree.

@item 
bpo-19542@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19542}: Fix bugs in WeakValueDictionary.setdefault() and
WeakValueDictionary.pop() when a GC collection happens in another thread.

@item 
bpo-20191@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20191}: Fixed a crash in resource.prlimit() when pass a sequence that
doesn't own its elements as limits.

@item 
bpo-28779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28779}: multiprocessing.set_forkserver_preload() would crash the
forkserver process if a preloaded module instantiated some multiprocessing
objects such as locks.

@item 
bpo-28847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28847}: dbm.dumb now supports reading read-only files and no longer
writes the index file when it is not changed.

@item 
bpo-25659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25659}: In ctypes, prevent a crash calling the from_buffer() and
from_buffer_copy() methods on abstract classes like Array.

@item 
bpo-28732@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28732}: Fix crash in os.spawnv() with no elements in args

@item 
bpo-28485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28485}: Always raise ValueError for negative
compileall.compile_dir(workers=...) parameter, even when multithreading is
unavailable.

@item 
bpo-28387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28387}: Fixed possible crash in _io.TextIOWrapper deallocator when the
garbage collector is invoked in other thread.  Based on patch by Sebastian
Cufre.

@item 
bpo-27517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27517}: LZMA compressor and decompressor no longer raise exceptions if
given empty data twice.  Patch by Benjamin Fogle.

@item 
bpo-28549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28549}: Fixed segfault in curses's addch() with ncurses6.

@item 
bpo-28449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28449}: tarfile.open() with mode "r" or "r:" now tries to open a tar
file with compression before trying to open it without compression.
Otherwise it had 50% chance failed with ignore_zeros=True.

@item 
bpo-23262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23262}: The webbrowser module now supports Firefox 36+ and derived
browsers.  Based on patch by Oleg Broytman.

@item 
bpo-27939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27939}: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
by representing the scale as float value internally in Tk.  tkinter.IntVar
now works if float value is set to underlying Tk variable.

@item 
bpo-28255@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28255}: calendar.TextCalendar().prmonth() no longer prints a space at
the start of new line after printing a month's calendar.  Patch by Xiang
Zhang.

@item 
bpo-20491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20491}: The textwrap.TextWrapper class now honors non-breaking spaces.
Based on patch by Kaarle Ritvanen.

@item 
bpo-28353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28353}: os.fwalk() no longer fails on broken links.

@item 
bpo-25464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25464}: Fixed HList.header_exists() in tkinter.tix module by addin a
workaround to Tix library bug.

@item 
bpo-28488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28488}: shutil.make_archive() no longer add entry "./" to ZIP archive.

@item 
bpo-24452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24452}: Make webbrowser support Chrome on Mac OS X.

@item 
bpo-20766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20766}: Fix references leaked by pdb in the handling of SIGINT
handlers.

@item 
bpo-26293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26293}: Fixed writing ZIP files that starts not from the start of the
file.  Offsets in ZIP file now are relative to the start of the archive in
conforming to the specification.

@item 
bpo-28321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28321}: Fixed writing non-BMP characters with binary format in
plistlib.

@item 
bpo-28322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28322}: Fixed possible crashes when unpickle itertools objects from
incorrect pickle data.  Based on patch by John Leitch.

@item 
Fix possible integer overflows and crashes in the mmap module with unusual
usage patterns.

@item 
bpo-1703178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1703178}: Fix the ability to pass the --link-objects option to the
distutils build_ext command.

@item 
bpo-28253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28253}: Fixed calendar functions for extreme months: 0001-01 and
9999-12. Methods itermonthdays() and itermonthdays2() are reimplemented so
that they don't call itermonthdates() which can cause datetime.date
under/overflow.

@item 
bpo-28275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28275}: Fixed possible use after free in the decompress() methods of
the LZMADecompressor and BZ2Decompressor classes. Original patch by John
Leitch.

@item 
bpo-27897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27897}: Fixed possible crash in sqlite3.Connection.create_collation()
if pass invalid string-like object as a name.  Patch by Xiang Zhang.

@item 
bpo-18893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18893}: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
Patch by Madison May.

@item 
bpo-27611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27611}: Fixed support of default root window in the tkinter.tix module.

@item 
bpo-27348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27348}: In the traceback module, restore the formatting of exception
messages like "Exception: None".  This fixes a regression introduced in
3.5a2.

@item 
bpo-25651@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25651}: Allow falsy values to be used for msg parameter of subTest().

@item 
bpo-27932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27932}: Prevent memory leak in win32_ver().

@item 
Fix UnboundLocalError in socket._sendfile_use_sendfile.

@item 
bpo-28075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28075}: Check for ERROR_ACCESS_DENIED in Windows implementation of
os.stat().  Patch by Eryk Sun.

@item 
bpo-25270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25270}: Prevent codecs.escape_encode() from raising SystemError when an
empty bytestring is passed.

@item 
bpo-28181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28181}: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

@item 
bpo-25895@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25895}: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by
Gergely Imreh and Markus Holtermann.

@item 
bpo-27599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27599}: Fixed buffer overrun in binascii.b2a_qp() and
binascii.a2b_qp().

@item 
bpo-19003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19003}: m email.generator now replaces only @code{\r} and/or @code{\n} line
endings, per the RFC, instead of all unicode line endings.

@item 
bpo-28019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28019}: itertools.count() no longer rounds non-integer step in range
between 1.0 and 2.0 to 1.

@item 
bpo-25969@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25969}: Update the lib2to3 grammar to handle the unpacking
generalizations added in 3.5.

@item 
bpo-14977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14977}: mailcap now respects the order of the lines in the mailcap
files ("first match"), as required by RFC 1542.  Patch by Michael Lazar.

@item 
bpo-24594@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24594}: Validates persist parameter when opening MSI database

@item 
bpo-17582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17582}: xml.etree.ElementTree nows preserves whitespaces in attributes
(Patch by Duane Griffin.  Reviewed and approved by Stefan Behnel.)

@item 
bpo-28047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28047}: Fixed calculation of line length used for the base64 CTE in the
new email policies.

@item 
bpo-27445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27445}: Don't pass str(_charset) to MIMEText.set_payload(). Patch by
Claude Paroz.

@item 
bpo-22450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22450}: urllib now includes an @code{Accept: */*} header among the default
headers. This makes the results of REST API requests more consistent and
predictable especially when proxy servers are involved.

@item 
lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
between runs given the same Grammar.txt input regardless of the hash
randomization setting.

@item 
bpo-27570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27570}: Avoid zero-length memcpy() etc calls with null source pointers
in the "ctypes" and "array" modules.

@item 
bpo-22233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22233}: Break email header lines @emph{only} on the RFC specified CR and LF
characters, not on arbitrary unicode line breaks.  This also fixes a bug
in HTTP header parsing.

@item 
bpo-27988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27988}: Fix email iter_attachments incorrect mutation of payload list.

@item 
bpo-27691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27691}: Fix ssl module's parsing of GEN_RID subject alternative name
fields in X.509 certs.

@item 
bpo-27850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27850}: Remove 3DES from ssl module's default cipher list to counter
measure sweet32 attack (CVE-2016-2183).

@item 
bpo-27766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27766}: Add ChaCha20 Poly1305 to ssl module's default cipher list.
(Required OpenSSL 1.1.0 or LibreSSL).

@item 
bpo-26470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26470}: Port ssl and hashlib module to OpenSSL 1.1.0.

@item 
Remove support for passing a file descriptor to os.access. It never worked
but previously didn't raise.

@item 
bpo-12885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12885}: Fix error when distutils encounters symlink.

@item 
bpo-27881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27881}: Fixed possible bugs when setting
sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

@item 
bpo-27861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27861}: Fixed a crash in sqlite3.Connection.cursor() when a factory
creates not a cursor.  Patch by Xiang Zhang.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: Avoid spurious output on OS X with Gnu Readline.

@item 
bpo-27706@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27706}: Restore deterministic behavior of random.Random().seed() for
string seeds using seeding version 1.  Allows sequences of calls to
random() to exactly match those obtained in Python 2. Patch by Nofar
Schnider.

@item 
bpo-10513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10513}: Fix a regression in Connection.commit().  Statements should not
be reset after a commit.

@item 
A new version of typing.py from @indicateurl{https://github.com/python/typing}:
Collection (only for 3.6) (bpo-27598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27598}). Add FrozenSet to __all__
(upstream #261). Fix crash in _get_type_vars() (upstream #259). Remove the
dict constraint in ForwardRef._eval_type (upstream #252).

@item 
bpo-27539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27539}: Fix unnormalised @code{Fraction.__pow__} result in the case of
negative exponent and negative base.

@item 
bpo-21718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21718}: cursor.description is now available for queries using CTEs.

@item 
bpo-2466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2466}: posixpath.ismount now correctly recognizes mount points which
the user does not have permission to access.

@item 
bpo-27773@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27773}: Correct some memory management errors server_hostname in
_ssl.wrap_socket().

@item 
bpo-26750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26750}: unittest.mock.create_autospec() now works properly for
subclasses of property() and other data descriptors.

@item 
In the curses module, raise an error if window.getstr() or window.instr()
is passed a negative value.

@item 
bpo-27783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27783}: Fix possible usage of uninitialized memory in
operator.methodcaller.

@item 
bpo-27774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27774}: Fix possible Py_DECREF on unowned object in _sre.

@item 
bpo-27760@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27760}: Fix possible integer overflow in binascii.b2a_qp.

@item 
bpo-27758@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27758}: Fix possible integer overflow in the _csv module for large
record lengths.

@item 
bpo-27568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27568}: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the
HTTP_PROXY variable when REQUEST_METHOD environment is set, which
indicates that the script is in CGI mode.

@item 
bpo-27656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27656}: Do not assume sched.h defines any SCHED_* constants.

@item 
bpo-27130@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27130}: In the "zlib" module, fix handling of large buffers (typically
4 GiB) when compressing and decompressing.  Previously, inputs were
limited to 4 GiB, and compression and decompression operations did not
properly handle results of 4 GiB.

@item 
bpo-27533@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27533}: Release GIL in nt._isdir

@item 
bpo-17711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17711}: Fixed unpickling by the persistent ID with protocol 0. Original
patch by Alexandre Vassalotti.

@item 
bpo-27522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27522}: Avoid an unintentional reference cycle in email.feedparser.

@item 
bpo-26844@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26844}: Fix error message for imp.find_module() to refer to 'path'
instead of 'name'. Patch by Lev Maximov.

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL zero-length recv() calls to not block and not raise an
error about unclean EOF.

@item 
bpo-27466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27466}: Change time format returned by http.cookie.time2netscape,
confirming the netscape cookie format and making it consistent with
documentation.

@item 
bpo-26664@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26664}: Fix activate.fish by removing mis-use of @code{$}.

@item 
bpo-22115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22115}: Fixed tracing Tkinter variables: trace_vdelete() with wrong
mode no longer break tracing, trace_vinfo() now always returns a list of
pairs of strings, tracing in the "u" mode now works.

@item 
Fix a scoping issue in importlib.util.LazyLoader which triggered an
UnboundLocalError when lazy-loading a module that was already put into
sys.modules.

@item 
bpo-27079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27079}: Fixed curses.ascii functions isblank(), iscntrl() and
ispunct().

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: Some functions (compile() etc) accepted a filename argument
encoded as an iterable of integers. Now only strings and byte-like objects
are accepted.

@item 
bpo-27048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27048}: Prevents distutils failing on Windows when environment
variables contain non-ASCII characters

@item 
bpo-27330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27330}: Fixed possible leaks in the ctypes module.

@item 
bpo-27238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27238}: Got rid of bare excepts in the turtle module.  Original patch
by Jelle Zijlstra.

@item 
bpo-27122@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27122}: When an exception is raised within the context being managed by
a contextlib.ExitStack() and one of the exit stack generators catches and
raises it in a chain, do not re-raise the original exception when exiting,
let the new chained one through.  This avoids the 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479} bug described
in issue25782.

@item 
bpo-26386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26386}: Fixed ttk.TreeView selection operations with item id's
containing spaces.

@item 
bpo-16182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16182}: Fix various functions in the "readline" module to use the
locale encoding, and fix get_begidx() and get_endidx() to return code
point indexes.

@item 
bpo-27392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27392}: Add loop.connect_accepted_socket(). Patch by Jim Fulton.

@item 
bpo-27930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27930}: Improved behaviour of logging.handlers.QueueListener. Thanks to
Paulo Andrade and Petr Viktorin for the analysis and patch.

@item 
bpo-21201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21201}: Improves readability of multiprocessing error message.  Thanks
to Wojciech Walczak for patch.

@item 
bpo-27456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27456}: asyncio: Set TCP_NODELAY by default.

@item 
bpo-27906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27906}: Fix socket accept exhaustion during high TCP traffic. Patch by
Kevin Conway.

@item 
bpo-28174@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28174}: Handle when SO_REUSEPORT isn't properly supported. Patch by
Seth Michael Larson.

@item 
bpo-26654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26654}: Inspect functools.partial in asyncio.Handle.__repr__. Patch by
iceboy.

@item 
bpo-26909@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26909}: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

@item 
bpo-28176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28176}: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

@item 
bpo-27759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27759}: Fix selectors incorrectly retain invalid file descriptors.
Patch by Mark Williams.

@item 
bpo-28368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28368}: Refuse monitoring processes if the child watcher has no loop
attached. Patch by Vincent Michel.

@item 
bpo-28369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28369}: Raise RuntimeError when transport's FD is used with add_reader,
add_writer, etc.

@item 
bpo-28370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28370}: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг
Марк.

@item 
bpo-28371@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28371}: Deprecate passing asyncio.Handles to run_in_executor.

@item 
bpo-28372@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28372}: Fix asyncio to support formatting of non-python coroutines.

@item 
bpo-28399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28399}: Remove UNIX socket from FS before binding. Patch by Коренберг
Марк.

@item 
bpo-27972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27972}: Prohibit Tasks to await on themselves.

@item 
bpo-26923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26923}: Fix asyncio.Gather to refuse being cancelled once all children
are done. Patch by Johannes Ebke.

@item 
bpo-26796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26796}: Don't configure the number of workers for default threadpool
executor. Initial patch by Hans Lawrenz.

@item 
bpo-28600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28600}: Optimize loop.call_soon().

@item 
bpo-28613@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28613}: Fix get_event_loop() return the current loop if called from
coroutines/callbacks.

@item 
bpo-28639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28639}: Fix inspect.isawaitable to always return bool Patch by Justin
Mayfield.

@item 
bpo-28652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28652}: Make loop methods reject socket kinds they do not support.

@item 
bpo-28653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28653}: Fix a refleak in functools.lru_cache.

@item 
bpo-28703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28703}: Fix asyncio.iscoroutinefunction to handle Mock objects.

@item 
bpo-24142@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24142}: Reading a corrupt config file left the parser in an invalid
state.  Original patch by Florian Höch.

@item 
bpo-28990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28990}: Fix SSL hanging if connection is closed before handshake
completed. (Patch by HoHo-Ho)
@end itemize

@node IDLE<45>,C API<40>,Library<67>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id501}@anchor{12f9}
@subsubsection IDLE



@itemize -

@item 
bpo-15308@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15308}: Add 'interrupt execution' (^C) to Shell menu. Patch by Roger
Serwy, updated by Bayard Randel.

@item 
bpo-27922@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27922}: Stop IDLE tests from 'flashing' gui widgets on the screen.

@item 
Add version to title of IDLE help window.

@item 
bpo-25564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25564}: In section on IDLE -- console differences, mention that using
exec means that __builtins__ is defined for each statement.

@item 
bpo-27714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27714}: text_textview and test_autocomplete now pass when re-run in the
same process.  This occurs when test_idle fails when run with the -w
option but without -jn.  Fix warning from test_config.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: IDLE no longer runs buggy code because of its tkinter imports.
Users must include the same imports required to run directly in Python.

@item 
bpo-27452@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27452}: add line counter and crc to IDLE configHandler test dump.

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

@item 
bpo-27245@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27245}: IDLE: Cleanly delete custom themes and key bindings.
Previously, when IDLE was started from a console or by import, a cascade
of warnings was emitted. Patch by Serhiy Storchaka.
@end itemize

@node C API<40>,Documentation<49>,IDLE<45>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id502}@anchor{12fa}
@subsubsection C API



@itemize -

@item 
bpo-28808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28808}: PyUnicode_CompareWithASCIIString() now never raises exceptions.

@item 
bpo-26754@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26754}: PyUnicode_FSDecoder() accepted a filename argument encoded as
an iterable of integers. Now only strings and bytes-like objects are
accepted.
@end itemize

@node Documentation<49>,Tests<52>,C API<40>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id503}@anchor{12fb}
@subsubsection Documentation



@itemize -

@item 
bpo-28513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28513}: Documented command-line interface of zipfile.
@end itemize

@node Tests<52>,Tools/Demos<30>,Documentation<49>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id504}@anchor{12fc}
@subsubsection Tests



@itemize -

@item 
bpo-28950@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28950}: Disallow -j0 to be combined with -T/-l/-M in regrtest command
line arguments.

@item 
bpo-28666@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28666}: Now test.support.rmtree is able to remove unwritable or
unreadable directories.

@item 
bpo-23839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23839}: Various caches now are cleared before running every test file.

@item 
bpo-28409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28409}: regrtest: fix the parser of command line arguments.

@item 
bpo-27787@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27787}: Call gc.collect() before checking each test for "dangling
threads", since the dangling threads are weak references.

@item 
bpo-27369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27369}: In test_pyexpat, avoid testing an error message detail that
changed in Expat 2.2.0.
@end itemize

@node Tools/Demos<30>,Windows<51>,Tests<52>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id505}@anchor{12fd}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-27952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27952}: Get Tools/scripts/fixcid.py working with Python 3 and the
current "re" module, avoid invalid Python backslash escapes, and fix a bug
parsing escaped C quote signs.

@item 
bpo-27332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27332}: Fixed the type of the first argument of module-level functions
generated by Argument Clinic.  Patch by Petr Viktorin.

@item 
bpo-27418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27418}: Fixed Tools/importbench/importbench.py.
@end itemize

@node Windows<51>,Build<54>,Tools/Demos<30>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id506}@anchor{12fe}
@subsubsection Windows



@itemize -

@item 
bpo-28251@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28251}: Improvements to help manuals on Windows.

@item 
bpo-28110@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28110}: launcher.msi has different product codes between 32-bit and
64-bit

@item 
bpo-25144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25144}: Ensures TargetDir is set before continuing with custom install.

@item 
bpo-27469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27469}: Adds a shell extension to the launcher so that drag and drop
works correctly.

@item 
bpo-27309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27309}: Enabled proper Windows styles in python[w].exe manifest.
@end itemize

@node Build<54>,,Windows<51>,Python 3 5 3 release candidate 1
@anchor{whatsnew/changelog id507}@anchor{12ff}
@subsubsection Build



@itemize -

@item 
bpo-29080@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=29080}: Removes hard dependency on hg.exe from PCBuild/build.bat

@item 
bpo-23903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23903}: Added missed names to PC/python3.def.

@item 
bpo-10656@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10656}: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
Michael Haubenwallner.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Rename --with-optimiations to --enable-optimizations.

@item 
bpo-28444@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28444}: Fix missing extensions modules when cross compiling.

@item 
bpo-28248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28248}: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

@item 
bpo-28258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28258}: Fixed build with Estonian locale (python-config and distclean
targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-26661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26661}: setup.py now detects system libffi with multiarch wrapper.

@item 
bpo-28066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28066}: Fix the logic that searches build directories for generated
include files when building outside the source tree.

@item 
bpo-15819@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15819}: Remove redundant include search directory option for building
outside the source tree.

@item 
bpo-27566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27566}: Fix clean target in freeze makefile (patch by Lisa Roach)

@item 
bpo-27705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27705}: Update message in validate_ucrtbase.py

@item 
bpo-27983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27983}: Cause lack of llvm-profdata tool when using clang as required
for PGO linking to be a configure time error rather than make time when
--with-optimizations is enabled.  Also improve our ability to find the
llvm-profdata tool on MacOS and some Linuxes.

@item 
bpo-26307@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26307}: The profile-opt build now applies PGO to the built-in modules.

@item 
bpo-26359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26359}: Add the --with-optimizations configure flag.

@item 
bpo-27713@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27713}: Suppress spurious build warnings when updating importlib's
bootstrap files. Patch by Xiang Zhang

@item 
bpo-25825@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25825}: Correct the references to Modules/python.exp and ld_so_aix,
which are required on AIX.  This updates references to an installation
path that was changed in 3.2a4, and undoes changed references to the build
tree that were made in 3.5.0a1.

@item 
bpo-27453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27453}: CPP invocation in configure must use CPPFLAGS. Patch by Chi
Hsuan Yen.

@item 
bpo-27641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27641}: The configure script now inserts comments into the makefile to
prevent the pgen and _freeze_importlib executables from being
cross-compiled.

@item 
bpo-26662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26662}: Set PYTHON_FOR_GEN in configure as the Python program to be
used for file generation during the build.

@item 
bpo-10910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10910}: Avoid C++ compilation errors on FreeBSD and OS X. Also update
FreedBSD version checks for the original ctype UTF-8 workaround.

@item 
bpo-28676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28676}: Prevent missing 'getentropy' declaration warning on macOS.
Patch by Gareth Rees.
@end itemize

@node Python 3 5 2 final,Python 3 5 2 release candidate 1,Python 3 5 3 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-2-final}@anchor{1300}
@subsection Python 3.5.2 final


@emph{Release date: 2016-06-26}

@menu
* Core and Builtins: Core and Builtins<65>. 
* Tests: Tests<53>. 
* IDLE: IDLE<46>. 

@end menu

@node Core and Builtins<65>,Tests<53>,,Python 3 5 2 final
@anchor{whatsnew/changelog id508}@anchor{1301}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update Windows builds to use OpenSSL 1.0.2h.
@end itemize

@node Tests<53>,IDLE<46>,Core and Builtins<65>,Python 3 5 2 final
@anchor{whatsnew/changelog id509}@anchor{1302}
@subsubsection Tests



@itemize -

@item 
bpo-26867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26867}: Ubuntu's openssl OP_NO_SSLv3 is forced on by default; fix test.
@end itemize

@node IDLE<46>,,Tests<53>,Python 3 5 2 final
@anchor{whatsnew/changelog id510}@anchor{1303}
@subsubsection IDLE



@itemize -

@item 
bpo-27365@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27365}: Allow non-ascii in idlelib/NEWS.txt - minimal part for 3.5.2.
@end itemize

@node Python 3 5 2 release candidate 1,Python 3 5 1 final,Python 3 5 2 final,更新日志
@anchor{whatsnew/changelog python-3-5-2-release-candidate-1}@anchor{1304}
@subsection Python 3.5.2 release candidate 1


@emph{Release date: 2016-06-12}

@menu
* Security: Security<36>. 
* Core and Builtins: Core and Builtins<66>. 
* Library: Library<68>. 
* IDLE: IDLE<47>. 
* Documentation: Documentation<50>. 
* Tests: Tests<54>. 
* Build: Build<55>. 
* Windows: Windows<52>. 
* Tools/Demos: Tools/Demos<31>. 

@end menu

@node Security<36>,Core and Builtins<66>,,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id511}@anchor{1305}
@subsubsection Security



@itemize -

@item 
bpo-26556@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26556}: Update expat to 2.1.1, fixes CVE-2015-1283.

@item 
Fix TLS stripping vulnerability in smtplib, CVE-2016-0772. Reported by
Team Oststrom

@item 
bpo-26839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26839}: On Linux, @ref{5d4,,os.urandom()} now calls @code{getrandom()} with
@code{GRND_NONBLOCK} to fall back on reading @code{/dev/urandom} if the urandom
entropy pool is not initialized yet. Patch written by Colm Buckley.

@item 
bpo-26657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26657}: Fix directory traversal vulnerability with http.server on
Windows.  This fixes a regression that was introduced in 3.3.4rc1 and
3.4.0rc1.  Based on patch by Philipp Hagemeister.

@item 
bpo-26313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26313}: ssl.py _load_windows_store_certs fails if windows cert store is
empty. Patch by Baji.

@item 
bpo-25939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25939}: On Windows open the cert store readonly in
ssl.enum_certificates.
@end itemize

@node Core and Builtins<66>,Library<68>,Security<36>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id512}@anchor{1306}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-27066@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27066}: Fixed SystemError if a custom opener (for open()) returns a
negative number without setting an exception.

@item 
bpo-20041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20041}: Fixed TypeError when frame.f_trace is set to None. Patch by
Xavier de Gaye.

@item 
bpo-26168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26168}: Fixed possible refleaks in failing Py_BuildValue() with the "N"
format unit.

@item 
bpo-26991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26991}: Fix possible refleak when creating a function with annotations.

@item 
bpo-27039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27039}: Fixed bytearray.remove() for values greater than 127.  Patch by
Joe Jevnik.

@item 
bpo-23640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23640}: int.from_bytes() no longer bypasses constructors for
subclasses.

@item 
bpo-26811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26811}: gc.get_objects() no longer contains a broken tuple with NULL
pointer.

@item 
bpo-20120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20120}: Use RawConfigParser for .pypirc parsing, removing support for
interpolation unintentionally added with move to Python 3. Behavior no
longer does any interpolation in .pypirc files, matching behavior in
Python 2.7 and Setuptools 19.0.

@item 
bpo-26659@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26659}: Make the builtin slice type support cycle collection.

@item 
bpo-26718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26718}: super.__init__ no longer leaks memory if called multiple times.
NOTE: A direct call of super.__init__ is not endorsed!

@item 
bpo-25339@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25339}: PYTHONIOENCODING now has priority over locale in setting the
error handler for stdin and stdout.

@item 
bpo-26494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26494}: Fixed crash on iterating exhausting iterators. Affected classes
are generic sequence iterators, iterators of str, bytes, bytearray, list,
tuple, set, frozenset, dict, OrderedDict, corresponding views and
os.scandir() iterator.

@item 
bpo-26581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26581}: If coding cookie is specified multiple times on a line in
Python source code file, only the first one is taken to account.

@item 
bpo-26464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26464}: Fix str.translate() when string is ASCII and first replacements
removes character, but next replacement uses a non-ASCII character or a
string longer than 1 character. Regression introduced in Python 3.5.0.

@item 
bpo-22836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22836}: Ensure exception reports from PyErr_Display() and
PyErr_WriteUnraisable() are sensible even when formatting them produces
secondary errors.  This affects the reports produced by
sys.__excepthook__() and when __del__() raises an exception.

@item 
bpo-26302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26302}: Correct behavior to reject comma as a legal character for
cookie names.

@item 
bpo-4806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4806}: Avoid masking the original TypeError exception when using star
(@code{*}) unpacking in function calls.  Based on patch by Hagen Fürstenau
and Daniel Urban.

@item 
bpo-27138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27138}: Fix the doc comment for FileFinder.find_spec().

@item 
bpo-26154@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26154}: Add a new private _PyThreadState_UncheckedGet() function to get
the current Python thread state, but don't issue a fatal error if it is
NULL. This new function must be used instead of accessing directly the
_PyThreadState_Current variable.  The variable is no more exposed since
Python 3.5.1 to hide the exact implementation of atomic C types, to avoid
compiler issues.

@item 
bpo-26194@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26194}: Deque.insert() gave odd results for bounded deques that had
reached their maximum size.  Now an IndexError will be raised when
attempting to insert into a full deque.

@item 
bpo-25843@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25843}: When compiling code, don't merge constants if they are equal
but have a different types. For example, @code{f1, f2 = lambda: 1, lambda:
1.0} is now correctly compiled to two different functions: @code{f1()}
returns @code{1} (@code{int}) and @code{f2()} returns @code{1.0} (@code{int}), even if
@code{1} and @code{1.0} are equal.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: [UPDATE] Comment out the one of the pickleability tests in
_PyObject_GetState() due to regressions observed in Cython-based projects.

@item 
bpo-25961@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25961}: Disallowed null characters in the type name.

@item 
bpo-25973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25973}: Fix segfault when an invalid nonlocal statement binds a name
starting with two underscores.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Instances of extension types with a state that aren't
subclasses of list or dict and haven't implemented any pickle-related
methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or
__getstate__), can no longer be pickled.  Including memoryview.

@item 
bpo-20440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20440}: Massive replacing unsafe attribute setting code with special
macro Py_SETREF.

@item 
bpo-25766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25766}: Special method __bytes__() now works in str subclasses.

@item 
bpo-25421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25421}: __sizeof__ methods of builtin types now use dynamic basic size.
This allows sys.getsize() to work correctly with their subclasses with
__slots__ defined.

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.

@item 
bpo-27147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27147}: Mention 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} in the importlib docs.

@item 
bpo-24097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24097}: Fixed crash in object.__reduce__() if slot name is freed inside
__getattr__.

@item 
bpo-24731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24731}: Fixed crash on converting objects with special methods
__bytes__, __trunc__, and __float__ returning instances of subclasses of
bytes, int, and float to subclasses of bytes, int, and float
correspondingly.

@item 
bpo-26478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26478}: Fix semantic bugs when using binary operators with dictionary
views and tuples.

@item 
bpo-26171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26171}: Fix possible integer overflow and heap corruption in
zipimporter.get_data().

@item 
bpo-25660@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25660}: Fix TAB key behaviour in REPL with readline.

@item 
bpo-25887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25887}: Raise a RuntimeError when a coroutine object is awaited more
than once.

@item 
bpo-27243@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27243}: Update the __aiter__ protocol: instead of returning an
awaitable that resolves to an asynchronous iterator, the asynchronous
iterator should be returned directly.  Doing the former will trigger a
PendingDeprecationWarning.
@end itemize

@node Library<68>,IDLE<47>,Core and Builtins<66>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id513}@anchor{1307}
@subsubsection Library



@itemize -

@item 
bpo-21386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21386}: Implement missing IPv4Address.is_global property.  It was
documented since 07a5610bae9d.  Initial patch by Roger Luethi.

@item 
bpo-20900@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20900}: distutils register command now decodes HTTP responses
correctly.  Initial patch by ingrid.

@item 
A new version of typing.py provides several new classes and features:
@@overload outside stubs, Reversible, DefaultDict, Text, ContextManager,
Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some
of the new features are not yet implemented in mypy or other static
analyzers). Also classes for 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} (Awaitable, AsyncIterable,
AsyncIterator) have been added (in fact they made it into 3.5.1 but were
never mentioned).

@item 
bpo-25738@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25738}: Stop http.server.BaseHTTPRequestHandler.send_error() from
sending a message body for 205 Reset Content.  Also, don't send Content
header fields in responses that don't have a body.  Patch by Susumu
Koshiba.

@item 
bpo-21313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21313}: Fix the "platform" module to tolerate when sys.version contains
truncated build information.

@item 
bpo-27164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27164}: In the zlib module, allow decompressing raw Deflate streams
with a predefined zdict.  Based on patch by Xiang Zhang.

@item 
bpo-24291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24291}: Fix wsgiref.simple_server.WSGIRequestHandler to completely
write data to the client.  Previously it could do partial writes and
truncate data.  Also, wsgiref.handler.ServerHandler can now handle stdout
doing partial writes, but this is deprecated.

@item 
bpo-26809@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26809}: Add @code{__all__} to @ref{f6,,string}.  Patch by Emanuel Barry.

@item 
bpo-26373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26373}: subprocess.Popen.communicate now correctly ignores
BrokenPipeError when the child process dies before .communicate() is
called in more/all circumstances.

@item 
bpo-21776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21776}: distutils.upload now correctly handles HTTPError. Initial patch
by Claudiu Popa.

@item 
bpo-27114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27114}: Fix SSLContext._load_windows_store_certs fails with
PermissionError

@item 
bpo-18383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18383}: Avoid creating duplicate filters when using filterwarnings and
simplefilter. Based on patch by Alex Shkop.

@item 
bpo-27057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27057}: Fix os.set_inheritable() on Android, ioctl() is blocked by
SELinux and fails with EACCESS. The function now falls back to fcntl().
Patch written by Michał Bednarski.

@item 
bpo-27014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27014}: Fix infinite recursion using typing.py.  Thanks to Kalle Tuure!

@item 
bpo-14132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14132}: Fix urllib.request redirect handling when the target only has a
query string.  Original fix by Ján Janech.

@item 
bpo-17214@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17214}: The "urllib.request" module now percent-encodes non-ASCII bytes
found in redirect target URLs.  Some servers send Location header fields
with non-ASCII bytes, but "http.client" requires the request target to be
ASCII-encodable, otherwise a UnicodeEncodeError is raised.  Based on patch
by Christian Heimes.

@item 
bpo-26892@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26892}: Honor debuglevel flag in urllib.request.HTTPHandler. Patch
contributed by Chi Hsuan Yen.

@item 
bpo-22274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22274}: In the subprocess module, allow stderr to be redirected to
stdout even when stdout is not redirected.  Patch by Akira Li.

@item 
bpo-26807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26807}: mock_open 'files' no longer error on readline at end of file.
Patch from Yolanda Robla.

@item 
bpo-25745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25745}: Fixed leaking a userptr in curses panel destructor.

@item 
bpo-26977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26977}: Removed unnecessary, and ignored, call to sum of squares helper
in statistics.pvariance.

@item 
bpo-26881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26881}: The modulefinder module now supports extended opcode arguments.

@item 
bpo-23815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23815}: Fixed crashes related to directly created instances of types in
_tkinter and curses.panel modules.

@item 
bpo-17765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17765}: weakref.ref() no longer silently ignores keyword arguments.
Patch by Georg Brandl.

@item 
bpo-26873@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26873}: xmlrpc now raises ResponseError on unsupported type tags
instead of silently return incorrect result.

@item 
bpo-26711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26711}: Fixed the comparison of plistlib.Data with other types.

@item 
bpo-24114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24114}: Fix an uninitialized variable in @code{ctypes.util}. The bug only
occurs on SunOS when the ctypes implementation searches for the @code{crle}
program.  Patch by Xiang Zhang.  Tested on SunOS by Kees Bos.

@item 
bpo-26864@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26864}: In urllib.request, change the proxy bypass host checking
against no_proxy to be case-insensitive, and to not match unrelated host
names that happen to have a bypassed hostname as a suffix.  Patch by Xiang
Zhang.

@item 
bpo-26634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26634}: recursive_repr() now sets __qualname__ of wrapper.  Patch by
Xiang Zhang.

@item 
bpo-26804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26804}: urllib.request will prefer lower_case proxy environment
variables over UPPER_CASE or Mixed_Case ones. Patch contributed by
Hans-Peter Jansen.

@item 
bpo-26837@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26837}: assertSequenceEqual() now correctly outputs non-stringified
differing items (like bytes in the -b mode).  This affects
assertListEqual() and assertTupleEqual().

@item 
bpo-26041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26041}: Remove "will be removed in Python 3.7" from deprecation
messages of platform.dist() and platform.linux_distribution(). Patch by
Kumaripaba Miyurusara Athukorala.

@item 
bpo-26822@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26822}: itemgetter, attrgetter and methodcaller objects no longer
silently ignore keyword arguments.

@item 
bpo-26733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26733}: Disassembling a class now disassembles class and static
methods. Patch by Xiang Zhang.

@item 
bpo-26801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26801}: Fix error handling in @ref{b2e,,shutil.get_terminal_size()}, catch
@ref{4aa,,AttributeError} instead of @ref{e48,,NameError}. Patch written by
Emanuel Barry.

@item 
bpo-24838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24838}: tarfile's ustar and gnu formats now correctly calculate name
and link field limits for multibyte character encodings like utf-8.

@item 
bpo-26717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26717}: Stop encoding Latin-1-ized WSGI paths with UTF-8.  Patch by
Anthony Sottile.

@item 
bpo-26735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26735}: Fix @ref{5d4,,os.urandom()} on Solaris 11.3 and newer when reading
more than 1,024 bytes: call @code{getrandom()} multiple times with a limit of
1024 bytes per call.

@item 
bpo-16329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16329}: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.

@item 
bpo-13952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13952}: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.

@item 
bpo-26709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26709}: Fixed Y2038 problem in loading binary PLists.

@item 
bpo-23735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23735}: Handle terminal resizing with Readline 6.3+ by installing our
own SIGWINCH handler.  Patch by Eric Price.

@item 
bpo-26586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26586}: In http.server, respond with "413 Request header fields too
large" if there are too many header fields to parse, rather than killing
the connection and raising an unhandled exception.  Patch by Xiang Zhang.

@item 
bpo-22854@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22854}: Change BufferedReader.writable() and BufferedWriter.readable()
to always return False.

@item 
bpo-25195@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25195}: Fix a regression in mock.MagicMock. _Call is a subclass of
tuple (changeset 3603bae63c13 only works for classes) so we need to
implement __ne__ ourselves.  Patch by Andrew Plummer.

@item 
bpo-26644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26644}: Raise ValueError rather than SystemError when a negative length
is passed to SSLSocket.recv() or read().

@item 
bpo-23804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23804}: Fix SSL recv(0) and read(0) methods to return zero bytes
instead of up to 1024.

@item 
bpo-26616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26616}: Fixed a bug in datetime.astimezone() method.

@item 
bpo-21925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21925}: @ref{1176,,warnings.formatwarning()} now catches exceptions on
@code{linecache.getline(...)} to be able to log @ref{5d3,,ResourceWarning}
emitted late during the Python shutdown process.

@item 
bpo-24266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24266}: Ctrl+C during Readline history search now cancels the search
mode when compiled with Readline 7.

@item 
bpo-26560@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26560}: Avoid potential ValueError in BaseHandler.start_response.
Initial patch by Peter Inglesby.

@item 
bpo-26569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26569}: Fix @ref{12db,,pyclbr.readmodule()} and @ref{12dc,,pyclbr.readmodule_ex()}
to support importing packages.

@item 
bpo-26499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26499}: Account for remaining Content-Length in HTTPResponse.readline()
and read1(). Based on patch by Silent Ghost. Also document that
HTTPResponse now supports these methods.

@item 
bpo-25320@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25320}: Handle sockets in directories unittest discovery is scanning.
Patch from Victor van den Elzen.

@item 
bpo-16181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16181}: cookiejar.http2time() now returns None if year is higher than
datetime.MAXYEAR.

@item 
bpo-26513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26513}: Fixes platform module detection of Windows Server

@item 
bpo-23718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23718}: Fixed parsing time in week 0 before Jan 1.  Original patch by
Tamás Bence Gedai.

@item 
bpo-20589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20589}: Invoking Path.owner() and Path.group() on Windows now raise
NotImplementedError instead of ImportError.

@item 
bpo-26177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26177}: Fixed the keys() method for Canvas and Scrollbar widgets.

@item 
bpo-15068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15068}: Got rid of excessive buffering in the fileinput module. The
bufsize parameter is no longer used.

@item 
bpo-2202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2202}: Fix UnboundLocalError in
AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu
Dupuy.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed pickling and copying the accumulate() iterator with total
is None.

@item 
bpo-26475@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26475}: Fixed debugging output for regular expressions with the (?x)
flag.

@item 
bpo-26457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26457}: Fixed the subnets() methods in IP network classes for the case
when resulting prefix length is equal to maximal prefix length. Based on
patch by Xiang Zhang.

@item 
bpo-26385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26385}: Remove the file if the internal open() call in
NamedTemporaryFile() fails. Patch by Silent Ghost.

@item 
bpo-26402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26402}: Fix XML-RPC client to retry when the server shuts down a
persistent connection.  This was a regression related to the new
http.client.RemoteDisconnected exception in 3.5.0a4.

@item 
bpo-25913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25913}: Leading @code{<~} is optional now in base64.a85decode() with
adobe=True.  Patch by Swati Jaiswal.

@item 
bpo-26186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26186}: Remove an invalid type check in importlib.util.LazyLoader.

@item 
bpo-26367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26367}: importlib.__import__() raises SystemError like
builtins.__import__() when @code{level} is specified but without an
accompanying package specified.

@item 
bpo-26309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26309}: In the "socketserver" module, shut down the request (closing
the connected socket) when verify_request() returns false.  Patch by Aviv
Palivoda.

@item 
bpo-25995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25995}: os.walk() no longer uses FDs proportional to the tree depth.

@item 
bpo-26117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26117}: The os.scandir() iterator now closes file descriptor not only
when the iteration is finished, but when it was failed with error.

@item 
bpo-25911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25911}: Restored support of bytes paths in os.walk() on Windows.

@item 
bpo-26045@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26045}: Add UTF-8 suggestion to error message when posting a
non-Latin-1 string with http.client.

@item 
bpo-12923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12923}: Reset FancyURLopener's redirect counter even if there is an
exception. Based on patches by Brian Brazil and Daniel Rocco.

@item 
bpo-25945@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25945}: Fixed a crash when unpickle the functools.partial object with
wrong state. Fixed a leak in failed functools.partial constructor. "args"
and "keywords" attributes of functools.partial have now always types tuple
and dict correspondingly.

@item 
bpo-26202@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26202}: copy.deepcopy() now correctly copies range() objects with
non-atomic attributes.

@item 
bpo-23076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23076}: Path.glob() now raises a ValueError if it's called with an
invalid pattern. Patch by Thomas Nyberg.

@item 
bpo-19883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19883}: Fixed possible integer overflows in zipimport.

@item 
bpo-26227@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26227}: On Windows, getnameinfo(), gethostbyaddr() and
gethostbyname_ex() functions of the socket module now decode the hostname
from the ANSI code page rather than UTF-8.

@item 
bpo-26147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26147}: xmlrpc now works with strings not encodable with used non-UTF-8
encoding.

@item 
bpo-25935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25935}: Garbage collector now breaks reference loops with OrderedDict.

@item 
bpo-16620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16620}: Fixed AttributeError in msilib.Directory.glob().

@item 
bpo-26013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26013}: Added compatibility with broken protocol 2 pickles created in
old Python 3 versions (3.4.3 and lower).

@item 
bpo-25850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25850}: Use cross-compilation by default for 64-bit Windows.

@item 
bpo-17633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17633}: Improve zipimport's support for namespace packages.

@item 
bpo-24705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24705}: Fix sysconfig._parse_makefile not expanding $@{@} vars appearing
before $() vars.

@item 
bpo-22138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22138}: Fix mock.patch behavior when patching descriptors. Restore
original values after patching. Patch contributed by Sean McCully.

@item 
bpo-25672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25672}: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode
option if it is safe to do so.

@item 
bpo-26012@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26012}: Don't traverse into symlinks for @code{**} pattern in
pathlib.Path.[r]glob().

@item 
bpo-24120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24120}: Ignore PermissionError when traversing a tree with
pathlib.Path.[r]glob(). Patch by Ulrich Petri.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: fileinput now uses sys.stdin as-is if it does not have a buffer
attribute (restores backward compatibility).

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: Copying the lru_cache() wrapper object now always works,
independently from the type of the wrapped object (by returning the
original object unchanged).

@item 
bpo-24103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24103}: Fixed possible use after free in ElementTree.XMLPullParser.

@item 
bpo-25860@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25860}: os.fwalk() no longer skips remaining directories when error
occurs. Original patch by Samson Lee.

@item 
bpo-25914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25914}: Fixed and simplified OrderedDict.__sizeof__.

@item 
bpo-25902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25902}: Fixed various refcount issues in ElementTree iteration.

@item 
bpo-25717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25717}: Restore the previous behaviour of tolerating most fstat()
errors when opening files.  This was a regression in 3.5a1, and stopped
anonymous temporary files from working in special cases.

@item 
bpo-24903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24903}: Fix regression in number of arguments compileall accepts when
'-d' is specified.  The check on the number of arguments has been dropped
completely as it never worked correctly anyway.

@item 
bpo-25764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25764}: In the subprocess module, preserve any exception caused by
fork() failure when preexec_fn is used.

@item 
bpo-6478@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6478}: _strptime's regexp cache now is reset after changing timezone
with time.tzset().

@item 
bpo-14285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14285}: When executing a package with the "python -m package" option,
and package initialization fails, a proper traceback is now reported.  The
"runpy" module now lets exceptions from package initialization pass back
to the caller, rather than raising ImportError.

@item 
bpo-19771@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19771}: Also in runpy and the "-m" option, omit the irrelevant message
". . . is a package and cannot be directly executed" if the package could
not even be initialized (e.g. due to a bad @code{*.pyc} file).

@item 
bpo-25177@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25177}: Fixed problem with the mean of very small and very large
numbers. As a side effect, statistics.mean and statistics.variance should
be significantly faster.

@item 
bpo-25718@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25718}: Fixed copying object with state with boolean value is false.

@item 
bpo-10131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10131}: Fixed deep copying of minidom documents.  Based on patch by
Marian Ganisin.

@item 
bpo-25725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25725}: Fixed a reference leak in pickle.loads() when unpickling
invalid data including tuple instructions.

@item 
bpo-25663@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25663}: In the Readline completer, avoid listing duplicate global
names, and search the global namespace before searching builtins.

@item 
bpo-25688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25688}: Fixed file leak in ElementTree.iterparse() raising an error.

@item 
bpo-23914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23914}: Fixed SystemError raised by unpickler on broken pickle data.

@item 
bpo-25691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25691}: Fixed crash on deleting ElementTree.Element attributes.

@item 
bpo-25624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25624}: ZipFile now always writes a ZIP_STORED header for directory
entries.  Patch by Dingyuan Wang.

@item 
Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu
Davis.

@item 
bpo-26050@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26050}: Add asyncio.StreamReader.readuntil() method. Patch by Марк
Коренберг.

@item 
bpo-25924@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25924}: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X
versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.

@item 
bpo-26406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26406}: Avoid unnecessary serialization of getaddrinfo(3) calls on
current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.

@item 
bpo-26848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26848}: Fix asyncio/subprocess.communicate() to handle empty input.
Patch by Jack O'Connor.

@item 
bpo-27040@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27040}: Add loop.get_exception_handler method

@item 
bpo-27041@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27041}: asyncio: Add loop.create_future method

@item 
bpo-27223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27223}: asyncio: Fix _read_ready and _write_ready to respect
_conn_lost. Patch by Łukasz Langa.

@item 
bpo-22970@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22970}: asyncio: Fix inconsistency cancelling Condition.wait. Patch by
David Coles.
@end itemize

@node IDLE<47>,Documentation<50>,Library<68>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id514}@anchor{1308}
@subsubsection IDLE



@itemize -

@item 
bpo-5124@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5124}: Paste with text selected now replaces the selection on X11. This
matches how paste works on Windows, Mac, most modern Linux apps, and ttk
widgets. Original patch by Serhiy Storchaka.

@item 
bpo-24759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24759}: Make clear in idlelib.idle_test.__init__ that the directory is
a private implementation of test.test_idle and tool for maintainers.

@item 
bpo-27196@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27196}: Stop 'ThemeChanged' warnings when running IDLE tests. These
persisted after other warnings were suppressed in #20567. Apply Serhiy
Storchaka's update_idletasks solution to four test files. Record this
additional advice in idle_test/README.txt

@item 
bpo-20567@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20567}: Revise idle_test/README.txt with advice about avoiding tk
warning messages from tests.  Apply advice to several IDLE tests.

@item 
bpo-27117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27117}: Make colorizer htest and turtledemo work with dark themes. Move
code for configuring text widget colors to a new function.

@item 
bpo-26673@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26673}: When tk reports font size as 0, change to size 10. Such fonts
on Linux prevented the configuration dialog from opening.

@item 
bpo-21939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21939}: Add test for IDLE's percolator. Original patch by Saimadhav
Heblikar.

@item 
bpo-21676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21676}: Add test for IDLE's replace dialog. Original patch by Saimadhav
Heblikar.

@item 
bpo-18410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18410}: Add test for IDLE's search dialog. Original patch by Westley
Martínez.

@item 
bpo-21703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21703}: Add test for IDLE's undo delegator. Original patch by Saimadhav
Heblikar .

@item 
bpo-27044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27044}: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

@item 
bpo-23977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23977}: Add more asserts to test_delegator.

@item 
bpo-20640@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20640}: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav
Heblikar.

@item 
In the 'IDLE-console differences' section of the IDLE doc, clarify how
running with IDLE affects sys.modules and the standard streams.

@item 
bpo-25507@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25507}: fix incorrect change in IOBinding that prevented printing.
Augment IOBinding htest to include all major IOBinding functions.

@item 
bpo-25905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25905}: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
MARK in README.txt and open this and NEWS.txt with 'ascii'. Re-encode
CREDITS.txt to utf-8 and open it with 'utf-8'.
@end itemize

@node Documentation<50>,Tests<54>,IDLE<47>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id515}@anchor{1309}
@subsubsection Documentation



@itemize -

@item 
bpo-19489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19489}: Moved the search box from the sidebar to the header and footer
of each page. Patch by Ammar Askar.

@item 
bpo-24136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24136}: Document the new 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} unpacking syntax of 3.5.

@item 
bpo-26736@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26736}: Used HTTPS for external links in the documentation if possible.

@item 
bpo-6953@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6953}: Rework the Readline module documentation to group related
functions together, and add more details such as what underlying Readline
functions and variables are accessed.

@item 
bpo-23606@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23606}: Adds note to ctypes documentation regarding cdll.msvcrt.

@item 
bpo-25500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25500}: Fix documentation to not claim that __import__ is searched for
in the global scope.

@item 
bpo-26014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26014}: Update 3.x packaging documentation: * "See also" links to the
new docs are now provided in the legacy pages * links to setuptools
documentation have been updated
@end itemize

@node Tests<54>,Build<55>,Documentation<50>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id516}@anchor{130a}
@subsubsection Tests



@itemize -

@item 
bpo-21916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21916}: Added tests for the turtle module.  Patch by ingrid, Gregory
Loyse and Jelle Zijlstra.

@item 
bpo-26523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26523}: The multiprocessing thread pool (multiprocessing.dummy.Pool)
was untested.

@item 
bpo-26015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26015}: Added new tests for pickling iterators of mutable sequences.

@item 
bpo-26325@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26325}: Added test.support.check_no_resource_warning() to check that no
ResourceWarning is emitted.

@item 
bpo-25940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25940}: Changed test_ssl to use self-signed.pythontest.net.  This
avoids relying on svn.python.org, which recently changed root certificate.

@item 
bpo-25616@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25616}: Tests for OrderedDict are extracted from test_collections into
separate file test_ordered_dict.

@item 
bpo-26583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26583}: Skip test_timestamp_overflow in test_import if bytecode files
cannot be written.
@end itemize

@node Build<55>,Windows<52>,Tests<54>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id517}@anchor{130b}
@subsubsection Build



@itemize -

@item 
bpo-26884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26884}: Fix linking extension modules for cross builds. Patch by Xavier
de Gaye.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Disable the rules for running _freeze_importlib and pgen when
cross-compiling.  The output of these programs is normally saved with the
source code anyway, and is still regenerated when doing a native build.
Patch by Xavier de Gaye.

@item 
bpo-27229@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27229}: Fix the cross-compiling pgen rule for in-tree builds.  Patch by
Xavier de Gaye.

@item 
bpo-21668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21668}: Link audioop, _datetime, _ctypes_test modules to libm, except
on Mac OS X. Patch written by Xavier de Gaye.

@item 
bpo-25702@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25702}: A --with-lto configure option has been added that will enable
link time optimizations at build time during a make profile-opt. Some
compilers and toolchains are known to not produce stable code when using
LTO, be sure to test things thoroughly before relying on it. It can
provide a few % speed up over profile-opt alone.

@item 
bpo-26624@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26624}: Adds validation of ucrtbase[d].dll version with warning for old
versions.

@item 
bpo-17603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17603}: Avoid error about nonexistent fileblocks.o file by using a
lower-level check for st_blocks in struct stat.

@item 
bpo-26079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26079}: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern
Thiel.

@item 
bpo-26465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26465}: Update Windows builds to use OpenSSL 1.0.2g.

@item 
bpo-24421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24421}: Compile Modules/_math.c once, before building extensions.
Previously it could fail to compile properly if the math and cmath builds
were concurrent.

@item 
bpo-25348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25348}: Added @code{--pgo} and @code{--pgo-job} arguments to
@code{PCbuild\build.bat} for building with Profile-Guided Optimization.  The
old @code{PCbuild\build_pgo.bat} script is now deprecated, and simply calls
@code{PCbuild\build.bat --pgo %*}.

@item 
bpo-25827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25827}: Add support for building with ICC to @code{configure}, including a
new @code{--with-icc} flag.

@item 
bpo-25696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25696}: Fix installation of Python on UNIX with make -j9.

@item 
bpo-26930@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26930}: Update OS X 10.5+ 32-bit-only installer to build and link with
OpenSSL 1.0.2h.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update Windows builds to use OpenSSL 1.0.2f.

@item 
bpo-25136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25136}: Support Apple Xcode 7's new textual SDK stub libraries.

@item 
bpo-24324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24324}: Do not enable unreachable code warnings when using gcc as the
option does not work correctly in older versions of gcc and has been
silently removed as of gcc-4.5.
@end itemize

@node Windows<52>,Tools/Demos<31>,Build<55>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id518}@anchor{130c}
@subsubsection Windows



@itemize -

@item 
bpo-27053@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=27053}: Updates make_zip.py to correctly generate library ZIP file.

@item 
bpo-26268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26268}: Update the prepare_ssl.py script to handle OpenSSL releases
that don't include the contents of the include directory (that is, 1.0.2e
and later).

@item 
bpo-26071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26071}: bdist_wininst created binaries fail to start and find 32bit
Python

@item 
bpo-26073@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26073}: Update the list of magic numbers in launcher

@item 
bpo-26065@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26065}: Excludes venv from library when generating embeddable distro.

@item 
bpo-17500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17500}: Remove unused and outdated icons. (See also:
@indicateurl{https://github.com/python/pythondotorg/issues/945})
@end itemize

@node Tools/Demos<31>,,Windows<52>,Python 3 5 2 release candidate 1
@anchor{whatsnew/changelog id519}@anchor{130d}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-26799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26799}: Fix python-gdb.py: don't get C types once when the Python code
is loaded, but get C types on demand. The C types can change if
python-gdb.py is loaded before the Python executable. Patch written by
Thomas Ilsche.

@item 
bpo-26271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26271}: Fix the Freeze tool to properly use flags passed through
configure. Patch by Daniel Shaulov.

@item 
bpo-26489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26489}: Add dictionary unpacking support to Tools/parser/unparse.py.
Patch by Guo Ci Teo.

@item 
bpo-26316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=26316}: Fix variable name typo in Argument Clinic.
@end itemize

@node Python 3 5 1 final,Python 3 5 1 release candidate 1,Python 3 5 2 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-1-final}@anchor{130e}
@subsection Python 3.5.1 final


@emph{Release date: 2015-12-06}

@menu
* Core and Builtins: Core and Builtins<67>. 
* Windows: Windows<53>. 

@end menu

@node Core and Builtins<67>,Windows<53>,,Python 3 5 1 final
@anchor{whatsnew/changelog id520}@anchor{130f}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-25709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25709}: Fixed problem with in-place string concatenation and utf-8
cache.
@end itemize

@node Windows<53>,,Core and Builtins<67>,Python 3 5 1 final
@anchor{whatsnew/changelog id521}@anchor{1310}
@subsubsection Windows



@itemize -

@item 
bpo-25715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25715}: Python 3.5.1 installer shows wrong upgrade path and incorrect
logic for launcher detection.
@end itemize

@node Python 3 5 1 release candidate 1,Python 3 5 0 final,Python 3 5 1 final,更新日志
@anchor{whatsnew/changelog python-3-5-1-release-candidate-1}@anchor{1311}
@subsection Python 3.5.1 release candidate 1


@emph{Release date: 2015-11-22}

@menu
* Core and Builtins: Core and Builtins<68>. 
* Library: Library<69>. 
* IDLE: IDLE<48>. 
* Documentation: Documentation<51>. 
* Tests: Tests<55>. 
* Build: Build<56>. 
* Windows: Windows<54>. 
* Tools/Demos: Tools/Demos<32>. 

@end menu

@node Core and Builtins<68>,Library<69>,,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id522}@anchor{1312}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-25630@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25630}: Fix a possible segfault during argument parsing in functions
that accept filesystem paths.

@item 
bpo-23564@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23564}: Fixed a partially broken sanity check in the _posixsubprocess
internals regarding how fds_to_pass were passed to the child.  The bug had
no actual impact as subprocess.py already avoided it.

@item 
bpo-25388@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25388}: Fixed tokenizer crash when processing undecodable source code
with a null byte.

@item 
bpo-25462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25462}: The hash of the key now is calculated only once in most
operations in C implementation of OrderedDict.

@item 
bpo-22995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22995}: Default implementation of __reduce__ and __reduce_ex__ now
rejects builtin types with not defined __new__.

@item 
bpo-25555@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25555}: Fix parser and AST: fill lineno and col_offset of "arg" node
when compiling AST from Python objects.

@item 
bpo-24802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24802}: Avoid buffer overreads when int(), float(), compile(), exec()
and eval() are passed bytes-like objects.  These objects are not
necessarily terminated by a null byte, but the functions assumed they
were.

@item 
bpo-24726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24726}: Fixed a crash and leaking NULL in repr() of OrderedDict that
was mutated by direct calls of dict methods.

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Iterating OrderedDict with keys with unstable hash now raises
KeyError in C implementations as well as in Python implementation.

@item 
bpo-25395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25395}: Fixed crash when highly nested OrderedDict structures were
garbage collected.

@item 
bpo-25274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25274}: sys.setrecursionlimit() now raises a RecursionError if the new
recursion limit is too low depending at the current recursion depth.
Modify also the "lower-water mark" formula to make it monotonic. This mark
is used to decide when the overflowed flag of the thread state is reset.

@item 
bpo-24402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24402}: Fix input() to prompt to the redirected stdout when
sys.stdout.fileno() fails.

@item 
bpo-24806@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24806}: Prevent builtin types that are not allowed to be subclassed
from being subclassed through multiple inheritance.

@item 
bpo-24848@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24848}: Fixed a number of bugs in UTF-7 decoding of misformed data.

@item 
bpo-25280@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25280}: Import trace messages emitted in verbose (-v) mode are no
longer formatted twice.

@item 
bpo-25003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25003}: On Solaris 11.3 or newer, os.urandom() now uses the getrandom()
function instead of the getentropy() function. The getentropy() function
is blocking to generate very good quality entropy, os.urandom() doesn't
need such high-quality entropy.

@item 
bpo-25182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25182}: The stdprinter (used as sys.stderr before the io module is
imported at startup) now uses the backslashreplace error handler.

@item 
bpo-25131@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25131}: Make the line number and column offset of set/dict literals and
comprehensions correspond to the opening brace.

@item 
bpo-25150@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25150}: Hide the private _Py_atomic_xxx symbols from the public
Python.h header to fix a compilation error with OpenMP.
PyThreadState_GET() becomes an alias to PyThreadState_Get() to avoid ABI
incompatibilities.
@end itemize

@node Library<69>,IDLE<48>,Core and Builtins<68>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id523}@anchor{1313}
@subsubsection Library



@itemize -

@item 
bpo-25626@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25626}: Change three zlib functions to accept sizes that fit in
Py_ssize_t, but internally cap those sizes to UINT_MAX.  This resolves a
regression in 3.5 where GzipFile.read() failed to read chunks larger than
2 or 4 GiB.  The change affects the zlib.Decompress.decompress()
max_length parameter, the zlib.decompress() bufsize parameter, and the
zlib.Decompress.flush() length parameter.

@item 
bpo-25583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25583}: Avoid incorrect errors raised by os.makedirs(exist_ok=True)
when the OS gives priority to errors such as EACCES over EEXIST.

@item 
bpo-25593@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25593}: Change semantics of EventLoop.stop() in asyncio.

@item 
bpo-6973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6973}: When we know a subprocess.Popen process has died, do not allow
the send_signal(), terminate(), or kill() methods to do anything as they
could potentially signal a different process.

@item 
bpo-25590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25590}: In the Readline completer, only call getattr() once per
attribute.

@item 
bpo-25498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25498}: Fix a crash when garbage-collecting ctypes objects created by
wrapping a memoryview.  This was a regression made in 3.5a1.  Based on
patch by Eryksun.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Added "escape" to the __all__ list in the glob module.

@item 
bpo-25584@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25584}: Fixed recursive glob() with patterns starting with @code{**}.

@item 
bpo-25446@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25446}: Fix regression in smtplib's AUTH LOGIN support.

@item 
bpo-18010@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18010}: Fix the pydoc web server's module search function to handle
exceptions from importing packages.

@item 
bpo-25554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25554}: Got rid of circular references in regular expression parsing.

@item 
bpo-25510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25510}: fileinput.FileInput.readline() now returns b'@w{'} instead of '@w{'} at
the end if the FileInput was opened with binary mode. Patch by Ryosuke
Ito.

@item 
bpo-25503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25503}: Fixed inspect.getdoc() for inherited docstrings of properties.
Original patch by John Mark Vandenberg.

@item 
bpo-25515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25515}: Always use os.urandom as a source of randomness in uuid.uuid4.

@item 
bpo-21827@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21827}: Fixed textwrap.dedent() for the case when largest common
whitespace is a substring of smallest leading whitespace. Based on patch
by Robert Li.

@item 
bpo-25447@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25447}: The lru_cache() wrapper objects now can be copied and pickled
(by returning the original object unchanged).

@item 
bpo-25390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25390}: typing: Don't crash on Union[str, Pattern].

@item 
bpo-25441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25441}: asyncio: Raise error from drain() when socket is closed.

@item 
bpo-25410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25410}: Cleaned up and fixed minor bugs in C implementation of
OrderedDict.

@item 
bpo-25411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25411}: Improved Unicode support in SMTPHandler through better use of
the email package. Thanks to user simon04 for the patch.

@item 
bpo-25407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25407}: Remove mentions of the formatter module being removed in Python
3.6.

@item 
bpo-25406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25406}: Fixed a bug in C implementation of OrderedDict.move_to_end()
that caused segmentation fault or hang in iterating after moving several
items to the start of ordered dict.

@item 
bpo-25364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25364}: zipfile now works in threads disabled builds.

@item 
bpo-25328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25328}: smtpd's SMTPChannel now correctly raises a ValueError if both
decode_data and enable_SMTPUTF8 are set to true.

@item 
bpo-25316@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25316}: distutils raises OSError instead of DistutilsPlatformError when
MSVC is not installed.

@item 
bpo-25380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25380}: Fixed protocol for the STACK_GLOBAL opcode in
pickletools.opcodes.

@item 
bpo-23972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23972}: Updates asyncio datagram create method allowing reuseport and
reuseaddr socket options to be set prior to binding the socket. Mirroring
the existing asyncio create_server method the reuseaddr option for
datagram sockets defaults to True if the O/S is 'posix' (except if the
platform is Cygwin). Patch by Chris Laws.

@item 
bpo-25304@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25304}: Add asyncio.run_coroutine_threadsafe().  This lets you submit a
coroutine to a loop from another thread, returning a
concurrent.futures.Future.  By Vincent Michel.

@item 
bpo-25232@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25232}: Fix CGIRequestHandler to split the query from the URL at the
first question mark (?) rather than the last. Patch from Xiang Zhang.

@item 
bpo-24657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24657}: Prevent CGIRequestHandler from collapsing slashes in the query
part of the URL as if it were a path. Patch from Xiang Zhang.

@item 
bpo-24483@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24483}: C implementation of functools.lru_cache() now calculates key's
hash only once.

@item 
bpo-22958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22958}: Constructor and update method of weakref.WeakValueDictionary
now accept the self and the dict keyword arguments.

@item 
bpo-22609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22609}: Constructor of collections.UserDict now accepts the self
keyword argument.

@item 
bpo-25111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25111}: Fixed comparison of traceback.FrameSummary.

@item 
bpo-25262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25262}: Added support for BINBYTES8 opcode in Python implementation of
unpickler. Highest 32 bits of 64-bit size for BINUNICODE8 and BINBYTES8
opcodes no longer silently ignored on 32-bit platforms in C
implementation.

@item 
bpo-25034@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25034}: Fix string.Formatter problem with auto-numbering and nested
format_specs. Patch by Anthon van der Neut.

@item 
bpo-25233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25233}: Rewrite the guts of asyncio.Queue and asyncio.Semaphore to be
more understandable and correct.

@item 
bpo-25203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25203}: Failed readline.set_completer_delims() no longer left the
module in inconsistent state.

@item 
bpo-23600@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23600}: Default implementation of tzinfo.fromutc() was returning wrong
results in some cases.

@item 
bpo-23329@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23329}: Allow the ssl module to be built with older versions of
LibreSSL.

@item 
Prevent overflow in _Unpickler_Read.

@item 
bpo-25047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25047}: The XML encoding declaration written by Element Tree now
respects the letter case given by the user. This restores the ability to
write encoding names in uppercase like "UTF-8", which worked in Python 2.

@item 
bpo-25135@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25135}: Make deque_clear() safer by emptying the deque before clearing.
This helps avoid possible reentrancy issues.

@item 
bpo-19143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19143}: platform module now reads Windows version from kernel32.dll to
avoid compatibility shims.

@item 
bpo-25092@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25092}: Fix datetime.strftime() failure when errno was already set to
EINVAL.

@item 
bpo-23517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23517}: Fix rounding in fromtimestamp() and utcfromtimestamp() methods
of datetime.datetime: microseconds are now rounded to nearest with ties
going to nearest even integer (ROUND_HALF_EVEN), instead of being rounding
towards minus infinity (ROUND_FLOOR). It's important that these methods
use the same rounding mode than datetime.timedelta to keep the property:
(datetime(1970,1,1) + timedelta(seconds=t)) ==
datetime.utcfromtimestamp(t). It also the rounding mode used by
round(float) for example.

@item 
bpo-25155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25155}: Fix datetime.datetime.now() and datetime.datetime.utcnow() on
Windows to support date after year 2038. It was a regression introduced in
Python 3.5.0.

@item 
bpo-25108@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25108}: Omitted internal frames in traceback functions print_stack(),
format_stack(), and extract_stack() called without arguments.

@item 
bpo-25118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25118}: Fix a regression of Python 3.5.0 in os.waitpid() on Windows.

@item 
bpo-24684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24684}: socket.socket.getaddrinfo() now calls
PyUnicode_AsEncodedString() instead of calling the encode() method of the
host, to handle correctly custom string with an encode() method which
doesn't return a byte string. The encoder of the IDNA codec is now called
directly instead of calling the encode() method of the string.

@item 
bpo-25060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25060}: Correctly compute stack usage of the BUILD_MAP opcode.

@item 
bpo-24857@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24857}: Comparing call_args to a long sequence now correctly returns a
boolean result instead of raising an exception.  Patch by A Kaptur.

@item 
bpo-23144@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23144}: Make sure that HTMLParser.feed() returns all the data, even
when convert_charrefs is True.

@item 
bpo-24982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24982}: shutil.make_archive() with the "zip" format now adds entries
for directories (including empty directories) in ZIP file.

@item 
bpo-25019@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25019}: Fixed a crash caused by setting non-string key of expat parser.
Based on patch by John Leitch.

@item 
bpo-16180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16180}: Exit pdb if file has syntax error, instead of trapping user in
an infinite loop.  Patch by Xavier de Gaye.

@item 
bpo-24891@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24891}: Fix a race condition at Python startup if the file descriptor
of stdin (0), stdout (1) or stderr (2) is closed while Python is creating
sys.stdin, sys.stdout and sys.stderr objects. These attributes are now set
to None if the creation of the object failed, instead of raising an
OSError exception. Initial patch written by Marco Paolini.

@item 
bpo-24992@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24992}: Fix error handling and a race condition (related to garbage
collection) in collections.OrderedDict constructor.

@item 
bpo-24881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24881}: Fixed setting binary mode in Python implementation of FileIO on
Windows and Cygwin.  Patch from Akira Li.

@item 
bpo-25578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25578}: Fix (another) memory leak in SSLSocket.getpeercer().

@item 
bpo-25530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25530}: Disable the vulnerable SSLv3 protocol by default when creating
ssl.SSLContext.

@item 
bpo-25569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25569}: Fix memory leak in SSLSocket.getpeercert().

@item 
bpo-25471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25471}: Sockets returned from accept() shouldn't appear to be
nonblocking.

@item 
bpo-25319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25319}: When threading.Event is reinitialized, the underlying condition
should use a regular lock rather than a recursive lock.

@item 
bpo-21112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21112}: Fix regression in unittest.expectedFailure on subclasses. Patch
from Berker Peksag.

@item 
bpo-24764@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24764}: cgi.FieldStorage.read_multi() now ignores the Content-Length
header in part headers. Patch written by Peter Landry and reviewed by
Pierre Quentel.

@item 
bpo-24913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24913}: Fix overrun error in deque.index(). Found by John Leitch and
Bryce Darling.

@item 
bpo-24774@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24774}: Fix docstring in http.server.test. Patch from Chiu-Hsiang Hsu.

@item 
bpo-21159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21159}: Improve message in
configparser.InterpolationMissingOptionError. Patch from Łukasz Langa.

@item 
bpo-20362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20362}: Honour TestCase.longMessage correctly in assertRegex. Patch
from Ilia Kurenkov.

@item 
bpo-23572@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23572}: Fixed functools.singledispatch on classes with falsy
metaclasses.  Patch by Ethan Furman.

@item 
asyncio: ensure_future() now accepts awaitable objects.
@end itemize

@node IDLE<48>,Documentation<51>,Library<69>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id524}@anchor{1314}
@subsubsection IDLE



@itemize -

@item 
bpo-15348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15348}: Stop the debugger engine (normally in a user process) before
closing the debugger window (running in the IDLE process). This prevents
the RuntimeErrors that were being caught and ignored.

@item 
bpo-24455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24455}: Prevent IDLE from hanging when a) closing the shell while the
debugger is active (15347); b) closing the debugger with the [X] button
(15348); and c) activating the debugger when already active (24455). The
patch by Mark Roseman does this by making two changes. 1. Suspend and
resume the gui.interaction method with the tcl vwait mechanism intended
for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow
any existing interaction to terminate first.

@item 
Change 'The program' to 'Your program' in an IDLE 'kill program?' message
to make it clearer that the program referred to is the currently running
user program, not IDLE itself.

@item 
bpo-24750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24750}: Improve the appearance of the IDLE editor window status bar.
Patch by Mark Roseman.

@item 
bpo-25313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25313}: Change the handling of new built-in text color themes to better
address the compatibility problem introduced by the addition of IDLE Dark.
Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

@item 
bpo-24782@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24782}: Extension configuration is now a tab in the IDLE Preferences
dialog rather than a separate dialog.  The former tabs are now a sorted
list.  Patch by Mark Roseman.

@item 
bpo-22726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22726}: Re-activate the config dialog help button with some content
about the other buttons and the new IDLE Dark theme.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: IDLE now has an 'IDLE Dark' built-in text color theme. It is
more or less IDLE Classic inverted, with a cobalt blue background.
Strings, comments, keywords, ... are still green, red, orange, ... . To
use it with IDLEs released before November 2015, hit the 'Save as New
Custom Theme' button and enter a new name, such as 'Custom Dark'.  The
custom theme will work with any IDLE release, and can be modified.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: README.txt is now an idlelib index for IDLE developers and
curious users. The previous user content is now in the IDLE doc chapter.
'IDLE' now means 'Integrated Development and Learning Environment'.

@item 
bpo-24820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24820}: Users can now set breakpoint colors in Settings -> Custom
Highlighting. Original patch by Mark Roseman.

@item 
bpo-24972@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24972}: Inactive selection background now matches active selection
background, as configured by users, on all systems.  Found items are now
always highlighted on Windows.  Initial patch by Mark Roseman.

@item 
bpo-24570@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24570}: Idle: make calltip and completion boxes appear on Macs affected
by a tk regression.  Initial patch by Mark Roseman.

@item 
bpo-24988@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24988}: Idle ScrolledList context menus (used in debugger) now work on
Mac Aqua. Patch by Mark Roseman.

@item 
bpo-24801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24801}: Make right-click for context menu work on Mac Aqua. Patch by
Mark Roseman.

@item 
bpo-25173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25173}: Associate tkinter messageboxes with a specific widget. For Mac
OSX, make them a 'sheet'.  Patch by Mark Roseman.

@item 
bpo-25198@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25198}: Enhance the initial html viewer now used for Idle Help.
Properly indent fixed-pitch text (patch by Mark Roseman). Give code
snippet a very Sphinx-like light blueish-gray background. Re-use initial
width and height set by users for shell and editor. When the Table of
Contents (TOC) menu is used, put the section header at the top of the
screen.

@item 
bpo-25225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25225}: Condense and rewrite Idle doc section on text colors.

@item 
bpo-21995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21995}: Explain some differences between IDLE and console Python.

@item 
bpo-22820@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22820}: Explain need for @emph{print} when running file from Idle editor.

@item 
bpo-25224@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25224}: Doc: augment Idle feature list and no-subprocess section.

@item 
bpo-25219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25219}: Update doc for Idle command line options. Some were missing and
notes were not correct.

@item 
bpo-24861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24861}: Most of idlelib is private and subject to change. Use
idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

@item 
bpo-25199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25199}: Idle: add synchronization comments for future maintainers.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Replace help.txt with help.html for Idle doc display. The new
idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks
better than help.txt and will better document Idle as released. The
tkinter html viewer that works for this file was written by Mark Roseman.
The now unused EditorWindow.HelpDialog class and helt.txt file are
deprecated.

@item 
bpo-24199@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24199}: Deprecate unused idlelib.idlever with possible removal in 3.6.

@item 
bpo-24790@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24790}: Remove extraneous code (which also create 2 & 3 conflicts).
@end itemize

@node Documentation<51>,Tests<55>,IDLE<48>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id525}@anchor{1315}
@subsubsection Documentation



@itemize -

@item 
bpo-22558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22558}: Add remaining doc links to source code for Python-coded
modules. Patch by Yoni Lavi.

@item 
bpo-12067@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12067}: Rewrite Comparisons section in the Expressions chapter of the
language reference. Some of the details of comparing mixed types were
incorrect or ambiguous. NotImplemented is only relevant at a lower level
than the Expressions chapter. Added details of comparing range() objects,
and default behaviour and consistency suggestions for user-defined
classes. Patch from Andy Maier.

@item 
bpo-24952@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24952}: Clarify the default size argument of stack_size() in the
"threading" and "_thread" modules. Patch from Mattip.

@item 
bpo-23725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23725}: Overhaul tempfile docs. Note deprecated status of mktemp. Patch
from Zbigniew Jędrzejewski-Szmek.

@item 
bpo-24808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24808}: Update the types of some PyTypeObject fields.  Patch by Joseph
Weston.

@item 
bpo-22812@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22812}: Fix unittest discovery examples. Patch from Pam McA'Nulty.
@end itemize

@node Tests<55>,Build<56>,Documentation<51>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id526}@anchor{1316}
@subsubsection Tests



@itemize -

@item 
bpo-25449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25449}: Added tests for OrderedDict subclasses.

@item 
bpo-25099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25099}: Make test_compileall not fail when an entry on sys.path cannot
be written to (commonly seen in administrative installs on Windows).

@item 
bpo-23919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23919}: Prevents assert dialogs appearing in the test suite.

@item 
@code{PCbuild\rt.bat} now accepts an unlimited number of arguments to pass
along to regrtest.py.  Previously there was a limit of 9.
@end itemize

@node Build<56>,Windows<54>,Tests<55>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id527}@anchor{1317}
@subsubsection Build



@itemize -

@item 
bpo-24915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24915}: Add LLVM support for PGO builds and use the test suite to
generate the profile data. Initial patch by Alecsandru Patrascu of Intel.

@item 
bpo-24910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24910}: Windows MSIs now have unique display names.

@item 
bpo-24986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24986}: It is now possible to build Python on Windows without errors
when external libraries are not available.
@end itemize

@node Windows<54>,Tools/Demos<32>,Build<56>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id528}@anchor{1318}
@subsubsection Windows



@itemize -

@item 
bpo-25450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25450}: Updates shortcuts to start Python in installation directory.

@item 
bpo-25164@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25164}: Changes default all-users install directory to match per-user
directory.

@item 
bpo-25143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25143}: Improves installer error messages for unsupported platforms.

@item 
bpo-25163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25163}: Display correct directory in installer when using non-default
settings.

@item 
bpo-25361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25361}: Disables use of SSE2 instructions in Windows 32-bit build

@item 
bpo-25089@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25089}: Adds logging to installer for case where launcher is not
selected on upgrade.

@item 
bpo-25165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25165}: Windows uninstallation should not remove launcher if other
versions remain

@item 
bpo-25112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25112}: py.exe launcher is missing icons

@item 
bpo-25102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25102}: Windows installer does not precompile for -O or -OO.

@item 
bpo-25081@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25081}: Makes Back button in installer go back to upgrade page when
upgrading.

@item 
bpo-25091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25091}: Increases font size of the installer.

@item 
bpo-25126@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25126}: Clarifies that the non-web installer will download some
components.

@item 
bpo-25213@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25213}: Restores requestedExecutionLevel to manifest to disable UAC
virtualization.

@item 
bpo-25022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25022}: Removed very outdated PC/example_nt/ directory.
@end itemize

@node Tools/Demos<32>,,Windows<54>,Python 3 5 1 release candidate 1
@anchor{whatsnew/changelog id529}@anchor{1319}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-25440@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25440}: Fix output of python-config --extension-suffix.
@end itemize

@node Python 3 5 0 final,Python 3 5 0 release candidate 4,Python 3 5 1 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-0-final}@anchor{131a}
@subsection Python 3.5.0 final


@emph{Release date: 2015-09-13}

@menu
* Build: Build<57>. 

@end menu

@node Build<57>,,,Python 3 5 0 final
@anchor{whatsnew/changelog id530}@anchor{131b}
@subsubsection Build



@itemize -

@item 
bpo-25071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25071}: Windows installer should not require TargetDir parameter when
installing quietly.
@end itemize

@node Python 3 5 0 release candidate 4,Python 3 5 0 release candidate 3,Python 3 5 0 final,更新日志
@anchor{whatsnew/changelog python-3-5-0-release-candidate-4}@anchor{131c}
@subsection Python 3.5.0 release candidate 4


@emph{Release date: 2015-09-09}

@menu
* Library: Library<70>. 
* Build: Build<58>. 

@end menu

@node Library<70>,Build<58>,,Python 3 5 0 release candidate 4
@anchor{whatsnew/changelog id531}@anchor{131d}
@subsubsection Library



@itemize -

@item 
bpo-25029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25029}: Fixes MemoryError in test_strptime.
@end itemize

@node Build<58>,,Library<70>,Python 3 5 0 release candidate 4
@anchor{whatsnew/changelog id532}@anchor{131e}
@subsubsection Build



@itemize -

@item 
bpo-25027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=25027}: Reverts partial-static build options and adds vcruntime140.dll
to Windows installation.
@end itemize

@node Python 3 5 0 release candidate 3,Python 3 5 0 release candidate 2,Python 3 5 0 release candidate 4,更新日志
@anchor{whatsnew/changelog python-3-5-0-release-candidate-3}@anchor{131f}
@subsection Python 3.5.0 release candidate 3


@emph{Release date: 2015-09-07}

@menu
* Core and Builtins: Core and Builtins<69>. 
* Library: Library<71>. 

@end menu

@node Core and Builtins<69>,Library<71>,,Python 3 5 0 release candidate 3
@anchor{whatsnew/changelog id533}@anchor{1320}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24305@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24305}: Prevent import subsystem stack frames from being counted by the
warnings.warn(stacklevel=) parameter.

@item 
bpo-24912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24912}: Prevent __class__ assignment to immutable built-in objects.

@item 
bpo-24975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24975}: Fix AST compilation for 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} syntax.
@end itemize

@node Library<71>,,Core and Builtins<69>,Python 3 5 0 release candidate 3
@anchor{whatsnew/changelog id534}@anchor{1321}
@subsubsection Library



@itemize -

@item 
bpo-24917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24917}: time_strftime() buffer over-read.

@item 
bpo-24748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24748}: To resolve a compatibility problem found with py2exe and
pywin32, imp.load_dynamic() once again ignores previously loaded modules
to support Python modules replacing themselves with extension modules.
Patch by Petr Viktorin.

@item 
bpo-24635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24635}: Fixed a bug in typing.py where isinstance([], typing.Iterable)
would return True once, then False on subsequent calls.

@item 
bpo-24989@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24989}: Fixed buffer overread in BytesIO.readline() if a position is
set beyond size.  Based on patch by John Leitch.

@item 
bpo-24913@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24913}: Fix overrun error in deque.index(). Found by John Leitch and
Bryce Darling.
@end itemize

@node Python 3 5 0 release candidate 2,Python 3 5 0 release candidate 1,Python 3 5 0 release candidate 3,更新日志
@anchor{whatsnew/changelog python-3-5-0-release-candidate-2}@anchor{1322}
@subsection Python 3.5.0 release candidate 2


@emph{Release date: 2015-08-25}

@menu
* Core and Builtins: Core and Builtins<70>. 
* Library: Library<72>. 

@end menu

@node Core and Builtins<70>,Library<72>,,Python 3 5 0 release candidate 2
@anchor{whatsnew/changelog id535}@anchor{1323}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24769}: Interpreter now starts properly when dynamic loading is
disabled.  Patch by Petr Viktorin.

@item 
bpo-21167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21167}: NAN operations are now handled correctly when python is
compiled with ICC even if -fp-model strict is not specified.

@item 
bpo-24492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24492}: A "package" lacking a __name__ attribute when trying to perform
a @code{from .. import ...} statement will trigger an ImportError instead of
an AttributeError.
@end itemize

@node Library<72>,,Core and Builtins<70>,Python 3 5 0 release candidate 2
@anchor{whatsnew/changelog id536}@anchor{1324}
@subsubsection Library



@itemize -

@item 
bpo-24847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24847}: Removes vcruntime140.dll dependency from Tcl/Tk.

@item 
bpo-24839@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24839}: platform._syscmd_ver raises DeprecationWarning

@item 
bpo-24867@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24867}: Fix Task.get_stack() for 'async def' coroutines
@end itemize

@node Python 3 5 0 release candidate 1,Python 3 5 0 beta 4,Python 3 5 0 release candidate 2,更新日志
@anchor{whatsnew/changelog python-3-5-0-release-candidate-1}@anchor{1325}
@subsection Python 3.5.0 release candidate 1


@emph{Release date: 2015-08-09}

@menu
* Core and Builtins: Core and Builtins<71>. 
* Library: Library<73>. 
* IDLE: IDLE<49>. 
* Documentation: Documentation<52>. 
* Tests: Tests<56>. 

@end menu

@node Core and Builtins<71>,Library<73>,,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id537}@anchor{1326}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24667@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24667}: Resize odict in all cases that the underlying dict resizes.
@end itemize

@node Library<73>,IDLE<49>,Core and Builtins<71>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id538}@anchor{1327}
@subsubsection Library



@itemize -

@item 
bpo-24824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24824}: Signatures of codecs.encode() and codecs.decode() now are
compatible with pydoc.

@item 
bpo-24634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24634}: Importing uuid should not try to load libc on Windows

@item 
bpo-24798@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24798}: _msvccompiler.py doesn't properly support manifests

@item 
bpo-4395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4395}: Better testing and documentation of binary operators. Patch by
Martin Panter.

@item 
bpo-23973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23973}: Update typing.py from GitHub repo.

@item 
bpo-23004@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23004}: mock_open() now reads binary data correctly when the type of
read_data is bytes.  Initial patch by Aaron Hill.

@item 
bpo-23888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23888}: Handle fractional time in cookie expiry. Patch by ssh.

@item 
bpo-23652@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23652}: Make it possible to compile the select module against the libc
headers from the Linux Standard Base, which do not include some EPOLL
macros.  Patch by Matt Frank.

@item 
bpo-22932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22932}: Fix timezones in email.utils.formatdate. Patch from Dmitry
Shachnev.

@item 
bpo-23779@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23779}: imaplib raises TypeError if authenticator tries to abort. Patch
from Craig Holmquist.

@item 
bpo-23319@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23319}: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
written by Matthieu Gautier.

@item 
bpo-23254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23254}: Document how to close the TCPServer listening socket. Patch
from Martin Panter.

@item 
bpo-19450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19450}: Update Windows and OS X installer builds to use SQLite 3.8.11.

@item 
bpo-17527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17527}: Add PATCH to wsgiref.validator. Patch from Luca Sbardella.

@item 
bpo-24791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24791}: Fix grammar regression for call syntax: 'g(*a or b)'.
@end itemize

@node IDLE<49>,Documentation<52>,Library<73>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id539}@anchor{1328}
@subsubsection IDLE



@itemize -

@item 
bpo-23672@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23672}: Allow Idle to edit and run files with astral chars in name.
Patch by Mohd Sanad Zaki Rizvi.

@item 
bpo-24745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24745}: Idle editor default font. Switch from Courier to
platform-sensitive TkFixedFont.  This should not affect current customized
font selections.  If there is a problem, edit
$HOME/.idlerc/config-main.cfg and remove 'fontxxx' entries from [Editor
Window].  Patch by Mark Roseman.

@item 
bpo-21192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21192}: Idle editor. When a file is run, put its name in the restart
bar. Do not print false prompts. Original patch by Adnan Umer.

@item 
bpo-13884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13884}: Idle menus. Remove tearoff lines. Patch by Roger Serwy.
@end itemize

@node Documentation<52>,Tests<56>,IDLE<49>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id540}@anchor{1329}
@subsubsection Documentation



@itemize -

@item 
bpo-24129@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24129}: Clarify the reference documentation for name resolution. This
includes removing the assumption that readers will be familiar with the
name resolution scheme Python used prior to the introduction of lexical
scoping for function namespaces. Patch by Ivan Levkivskyi.

@item 
bpo-20769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20769}: Improve reload() docs. Patch by Dorian Pula.

@item 
bpo-23589@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23589}: Remove duplicate sentence from the FAQ.  Patch by Yongzhi Pan.

@item 
bpo-24729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24729}: Correct IO tutorial to match implementation regarding encoding
parameter to open function.
@end itemize

@node Tests<56>,,Documentation<52>,Python 3 5 0 release candidate 1
@anchor{whatsnew/changelog id541}@anchor{132a}
@subsubsection Tests



@itemize -

@item 
bpo-24751@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24751}: When running regrtest with the @code{-w} command line option, a
test run is no longer marked as a failure if all tests succeed when
re-run.
@end itemize

@node Python 3 5 0 beta 4,Python 3 5 0 beta 3,Python 3 5 0 release candidate 1,更新日志
@anchor{whatsnew/changelog python-3-5-0-beta-4}@anchor{132b}
@subsection Python 3.5.0 beta 4


@emph{Release date: 2015-07-26}

@menu
* Core and Builtins: Core and Builtins<72>. 
* Library: Library<74>. 
* Build: Build<59>. 

@end menu

@node Core and Builtins<72>,Library<74>,,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id542}@anchor{132c}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}: Restored optimization of bytes.rfind() and bytearray.rfind()
for single-byte argument on Linux.

@item 
bpo-24569@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24569}: Make 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} dictionary evaluation more consistent.

@item 
bpo-24583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24583}: Fix crash when set is mutated while being updated.

@item 
bpo-24407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24407}: Fix crash when dict is mutated while being updated.

@item 
bpo-24619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24619}: New approach for tokenizing async/await. As a consequence, it
is now possible to have one-line 'async def foo(): await ..' functions.

@item 
bpo-24687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24687}: Plug refleak on SyntaxError in function parameters annotations.

@item 
bpo-15944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15944}: memoryview: Allow arbitrary formats when casting to bytes.
Patch by Martin Panter.
@end itemize

@node Library<74>,Build<59>,Core and Builtins<72>,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id543}@anchor{132d}
@subsubsection Library



@itemize -

@item 
bpo-23441@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23441}: rcompleter now prints a tab character instead of displaying
possible completions for an empty word.  Initial patch by Martin Sekera.

@item 
bpo-24683@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24683}: Fixed crashes in _json functions called with arguments of
inappropriate type.

@item 
bpo-21697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21697}: shutil.copytree() now correctly handles symbolic links that
point to directories.  Patch by Eduardo Seabra and Thomas Kluyver.

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: Fixed segmentation fault when gc.collect() is called during
constructing lru_cache (C implementation).

@item 
bpo-24695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24695}: Fix a regression in traceback.print_exception().  If
exc_traceback is None we shouldn't print a traceback header like described
in the documentation.

@item 
bpo-24620@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24620}: Random.setstate() now validates the value of state last
element.

@item 
bpo-22485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22485}: Fixed an issue that caused @ref{1025,,inspect.getsource} to return
incorrect results on nested functions.

@item 
bpo-22153@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22153}: Improve unittest docs. Patch from Martin Panter and evilzero.

@item 
bpo-24580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24580}: Symbolic group references to open group in re patterns now are
explicitly forbidden as well as numeric group references.

@item 
bpo-24206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24206}: Fixed __eq__ and __ne__ methods of inspect classes.

@item 
bpo-24631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24631}: Fixed regression in the timeit module with multiline setup.

@item 
bpo-18622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18622}: unittest.mock.mock_open().reset_mock would recurse infinitely.
Patch from Nicola Palumbo and Laurent De Buyst.

@item 
bpo-23661@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23661}: unittest.mock side_effects can now be exceptions again. This
was a regression vs Python 3.4. Patch from Ignacio Rossi

@item 
bpo-24608@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24608}: chunk.Chunk.read() now always returns bytes, not str.

@item 
bpo-18684@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18684}: Fixed reading out of the buffer in the re module.

@item 
bpo-24259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24259}: tarfile now raises a ReadError if an archive is truncated
inside a data segment.

@item 
bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}: SMTP.auth() and SMTP.login() now support RFC 4954's optional
initial-response argument to the SMTP AUTH command.

@item 
bpo-24669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24669}: Fix inspect.getsource() for 'async def' functions. Patch by Kai
Groner.

@item 
bpo-24688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24688}: ast.get_docstring() for 'async def' functions.
@end itemize

@node Build<59>,,Library<74>,Python 3 5 0 beta 4
@anchor{whatsnew/changelog id544}@anchor{132e}
@subsubsection Build



@itemize -

@item 
bpo-24603@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24603}: Update Windows builds and OS X 10.5 installer to use OpenSSL
1.0.2d.
@end itemize

@node Python 3 5 0 beta 3,Python 3 5 0 beta 2,Python 3 5 0 beta 4,更新日志
@anchor{whatsnew/changelog python-3-5-0-beta-3}@anchor{132f}
@subsection Python 3.5.0 beta 3


@emph{Release date: 2015-07-05}

@menu
* Core and Builtins: Core and Builtins<73>. 
* Library: Library<75>. 
* Tests: Tests<57>. 
* Documentation: Documentation<53>. 
* Build: Build<60>. 

@end menu

@node Core and Builtins<73>,Library<75>,,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id545}@anchor{1330}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24467@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24467}: Fixed possible buffer over-read in bytearray. The bytearray
object now always allocates place for trailing null byte and it's buffer
now is always null-terminated.

@item 
Upgrade to Unicode 8.0.0.

@item 
bpo-24345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24345}: Add Py_tp_finalize slot for the stable ABI.

@item 
bpo-24400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24400}: Introduce a distinct type for 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} coroutines; add
types.CoroutineType, inspect.getcoroutinestate,
inspect.getcoroutinelocals; coroutines no longer use CO_GENERATOR flag;
sys.set_coroutine_wrapper works only for 'async def' coroutines;
inspect.iscoroutine no longer uses collections.abc.Coroutine, it's
intended to test for pure 'async def' coroutines only; add new opcode:
GET_YIELD_FROM_ITER; fix generators wrapper used in types.coroutine to be
instance of collections.abc.Generator; collections.abc.Awaitable and
collections.abc.Coroutine can no longer be used to detect generator-based
coroutines--use inspect.isawaitable instead.

@item 
bpo-24450@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24450}: Add gi_yieldfrom to generators and cr_await to coroutines.
Contributed by Benno Leslie and Yury Selivanov.

@item 
bpo-19235@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19235}: Add new RecursionError exception. Patch by Georg Brandl.
@end itemize

@node Library<75>,Tests<57>,Core and Builtins<73>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id546}@anchor{1331}
@subsubsection Library



@itemize -

@item 
bpo-21750@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21750}: mock_open.read_data can now be read from each instance, as it
could in Python 3.3.

@item 
bpo-24552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24552}: Fix use after free in an error case of the _pickle module.

@item 
bpo-24514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24514}: tarfile now tolerates number fields consisting of only
whitespace.

@item 
bpo-19176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19176}: Fixed doctype() related bugs in C implementation of
ElementTree. A deprecation warning no longer issued by XMLParser subclass
with default doctype() method.  Direct call of doctype() now issues a
warning.  Parser's doctype() now is not called if target's doctype() is
called.  Based on patch by Martin Panter.

@item 
bpo-20387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20387}: Restore semantic round-trip correctness in tokenize/untokenize
for tab-indented blocks.

@item 
bpo-24456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24456}: Fixed possible buffer over-read in adpcm2lin() and lin2adpcm()
functions of the audioop module.

@item 
bpo-24336@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24336}: The contextmanager decorator now works with functions with
keyword arguments called "func" and "self".  Patch by Martin Panter.

@item 
bpo-24522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24522}: Fix possible integer overflow in json accelerator module.

@item 
bpo-24489@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24489}: ensure a previously set C errno doesn't disturb cmath.polar().

@item 
bpo-24408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24408}: Fixed AttributeError in measure() and metrics() methods of
tkinter.Font.

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: C implementation of functools.lru_cache() now can be used with
methods.

@item 
bpo-24347@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24347}: Set KeyError if PyDict_GetItemWithError returns NULL.

@item 
bpo-24348@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24348}: Drop superfluous incref/decref.

@item 
bpo-24359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24359}: Check for changed OrderedDict size during iteration.

@item 
bpo-24368@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24368}: Support keyword arguments in OrderedDict methods.

@item 
bpo-24362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24362}: Simplify the C OrderedDict fast nodes resize logic.

@item 
bpo-24377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24377}: Fix a ref leak in OrderedDict.__repr__.

@item 
bpo-24369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24369}: Defend against key-changes during iteration.
@end itemize

@node Tests<57>,Documentation<53>,Library<75>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id547}@anchor{1332}
@subsubsection Tests



@itemize -

@item 
bpo-24373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24373}: _testmultiphase and xxlimited now use tp_traverse and
tp_finalize to avoid reference leaks encountered when combining tp_dealloc
with PyType_FromSpec (see bpo-16690@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16690} for details)
@end itemize

@node Documentation<53>,Build<60>,Tests<57>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id548}@anchor{1333}
@subsubsection Documentation



@itemize -

@item 
bpo-24458@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24458}: Update documentation to cover multi-phase initialization for
extension modules (PEP 489). Patch by Petr Viktorin.

@item 
bpo-24351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24351}: Clarify what is meant by "identifier" in the context of
string.Template instances.
@end itemize

@node Build<60>,,Documentation<53>,Python 3 5 0 beta 3
@anchor{whatsnew/changelog id549}@anchor{1334}
@subsubsection Build



@itemize -

@item 
bpo-24432@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24432}: Update Windows builds and OS X 10.5 installer to use OpenSSL
1.0.2c.
@end itemize

@node Python 3 5 0 beta 2,Python 3 5 0 beta 1,Python 3 5 0 beta 3,更新日志
@anchor{whatsnew/changelog python-3-5-0-beta-2}@anchor{1335}
@subsection Python 3.5.0 beta 2


@emph{Release date: 2015-05-31}

@menu
* Core and Builtins: Core and Builtins<74>. 
* Library: Library<76>. 

@end menu

@node Core and Builtins<74>,Library<76>,,Python 3 5 0 beta 2
@anchor{whatsnew/changelog id550}@anchor{1336}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24284}: The startswith and endswith methods of the str class no longer
return True when finding the empty string and the indexes are completely
out of range.

@item 
bpo-24115@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24115}: Update uses of PyObject_IsTrue(), PyObject_Not(),
PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains()
to check for and handle errors correctly.

@item 
bpo-24328@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24328}: Fix importing one character extension modules.

@item 
bpo-11205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11205}: In dictionary displays, evaluate the key before the value.

@item 
bpo-24285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24285}: Fixed regression that prevented importing extension modules
from inside packages. Patch by Petr Viktorin.
@end itemize

@node Library<76>,,Core and Builtins<74>,Python 3 5 0 beta 2
@anchor{whatsnew/changelog id551}@anchor{1337}
@subsubsection Library



@itemize -

@item 
bpo-23247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23247}: Fix a crash in the StreamWriter.reset() of CJK codecs.

@item 
bpo-24270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24270}: Add math.isclose() and cmath.isclose() functions as per
@geindex Python 提高建议; PEP 485
PEP 485@footnote{https://www.python.org/dev/peps/pep-0485}. Contributed by Chris Barker and Tal Einat.

@item 
bpo-5633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5633}: Fixed timeit when the statement is a string and the setup is
not.

@item 
bpo-24326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24326}: Fixed audioop.ratecv() with non-default weightB argument.
Original patch by David Moore.

@item 
bpo-16991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16991}: Add a C implementation of OrderedDict.

@item 
bpo-23934@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23934}: Fix inspect.signature to fail correctly for builtin types
lacking signature information.  Initial patch by James Powell.
@end itemize

@node Python 3 5 0 beta 1,Python 3 5 0 alpha 4,Python 3 5 0 beta 2,更新日志
@anchor{whatsnew/changelog python-3-5-0-beta-1}@anchor{1338}
@subsection Python 3.5.0 beta 1


@emph{Release date: 2015-05-24}

@menu
* Core and Builtins: Core and Builtins<75>. 
* Library: Library<77>. 
* IDLE: IDLE<50>. 
* Tests: Tests<58>. 
* Documentation: Documentation<54>. 
* Tools/Demos: Tools/Demos<33>. 

@end menu

@node Core and Builtins<75>,Library<77>,,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id552}@anchor{1339}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-24276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24276}: Fixed optimization of property descriptor getter.

@item 
bpo-24268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24268}: PEP 489: Multi-phase extension module initialization. Patch by
Petr Viktorin.

@item 
bpo-23955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23955}: Add pyvenv.cfg option to suppress registry/environment lookup
for generating sys.path on Windows.

@item 
bpo-24257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24257}: Fixed system error in the comparison of faked
types.SimpleNamespace.

@item 
bpo-22939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22939}: Fixed integer overflow in iterator object.  Patch by Clement
Rouault.

@item 
bpo-23985@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23985}: Fix a possible buffer overrun when deleting a slice from the
front of a bytearray and then appending some other bytes data.

@item 
bpo-24102@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24102}: Fixed exception type checking in standard error handlers.

@item 
bpo-15027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15027}: The UTF-32 encoder is now 3x to 7x faster.

@item 
bpo-23290@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23290}: Optimize set_merge() for cases where the target is empty.
(Contributed by Serhiy Storchaka.)

@item 
bpo-2292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2292}: PEP 448: Additional Unpacking Generalizations.

@item 
bpo-24096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24096}: Make warnings.warn_explicit more robust against mutation of the
warnings.filters list.

@item 
bpo-23996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23996}: Avoid a crash when a delegated generator raises an unnormalized
StopIteration exception.  Patch by Stefan Behnel.

@item 
bpo-23910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23910}: Optimize property() getter calls.  Patch by Joe Jevnik.

@item 
bpo-23911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23911}: Move path-based importlib bootstrap code to a separate frozen
module.

@item 
bpo-24192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24192}: Fix namespace package imports.

@item 
bpo-24022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24022}: Fix tokenizer crash when processing undecodable source code.

@item 
bpo-9951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9951}: Added a hex() method to bytes, bytearray, and memoryview.

@item 
bpo-22906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22906}: PEP 479: Change StopIteration handling inside generators.

@item 
bpo-24017@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24017}: PEP 492: Coroutines with async and await syntax.
@end itemize

@node Library<77>,IDLE<50>,Core and Builtins<75>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id553}@anchor{133a}
@subsubsection Library



@itemize -

@item 
bpo-14373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14373}: Added C implementation of functools.lru_cache().  Based on
patches by Matt Joiner and Alexey Kachayev.

@item 
bpo-24230@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24230}: The tempfile module now accepts bytes for prefix, suffix and
dir parameters and returns bytes in such situations (matching the os
module APIs).

@item 
bpo-22189@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22189}: collections.UserString now supports __getnewargs__(),
__rmod__(), casefold(), format_map(), isprintable(), and maketrans().
Patch by Joe Jevnik.

@item 
bpo-24244@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24244}: Prevents termination when an invalid format string is
encountered on Windows in strftime.

@item 
bpo-23973@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23973}: PEP 484: Add the typing module.

@item 
bpo-23086@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23086}: The collections.abc.Sequence() abstract base class added
@emph{start} and @emph{stop} parameters to the index() mixin. Patch by Devin
Jeanpierre.

@item 
bpo-20035@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20035}: Replaced the @code{tkinter._fix} module used for setting up the
Tcl/Tk environment on Windows with a private function in the @code{_tkinter}
module that makes no permanent changes to the environment.

@item 
bpo-24257@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24257}: Fixed segmentation fault in sqlite3.Row constructor with faked
cursor type.

@item 
bpo-15836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15836}: assertRaises(), assertRaisesRegex(), assertWarns() and
assertWarnsRegex() assertments now check the type of the first argument to
prevent possible user error.  Based on patch by Daniel Wagner-Hall.

@item 
bpo-9858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9858}: Add missing method stubs to _io.RawIOBase.  Patch by Laura
Rupprecht.

@item 
bpo-22955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22955}: attrgetter, itemgetter and methodcaller objects in the operator
module now support pickling.  Added readable and evaluable repr for these
objects. Based on patch by Josh Rosenberg.

@item 
bpo-22107@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22107}: tempfile.gettempdir() and tempfile.mkdtemp() now try again when
a directory with the chosen name already exists on Windows as well as on
Unix. tempfile.mkstemp() now fails early if parent directory is not valid
(not exists or is a file) on Windows.

@item 
bpo-23780@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23780}: Improved error message in os.path.join() with single argument.

@item 
bpo-6598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6598}: Increased time precision and random number range in
email.utils.make_msgid() to strengthen the uniqueness of the message ID.

@item 
bpo-24091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24091}: Fixed various crashes in corner cases in C implementation of
ElementTree.

@item 
bpo-21931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21931}: msilib.FCICreate() now raises TypeError in the case of a bad
argument instead of a ValueError with a bogus FCI error number. Patch by
Jeffrey Armstrong.

@item 
bpo-13866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13866}: @emph{quote_via} argument added to urllib.parse.urlencode.

@item 
bpo-20098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20098}: New mangle_from policy option for email, default True for
compat32, but False for all other policies.

@item 
bpo-24211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24211}: The email library now supports RFC 6532: it can generate
headers using utf-8 instead of encoded words.

@item 
bpo-16314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16314}: Added support for the LZMA compression in distutils.

@item 
bpo-21804@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21804}: poplib now supports RFC 6856 (UTF8).

@item 
bpo-18682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18682}: Optimized pprint functions for builtin scalar types.

@item 
bpo-22027@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22027}: smtplib now supports RFC 6531 (SMTPUTF8).

@item 
bpo-23488@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23488}: Random generator objects now consume 2x less memory on 64-bit.

@item 
bpo-1322@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1322}: platform.dist() and platform.linux_distribution() functions are
now deprecated.  Initial patch by Vajrasky Kok.

@item 
bpo-22486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22486}: Added the math.gcd() function.  The fractions.gcd() function
now is deprecated.  Based on patch by Mark Dickinson.

@item 
bpo-24064@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24064}: Property() docstrings are now writeable. (Patch by Berker
Peksag.)

@item 
bpo-22681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22681}: Added support for the koi8_t encoding.

@item 
bpo-22682@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22682}: Added support for the kz1048 encoding.

@item 
bpo-23796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23796}: peek and read1 methods of BufferedReader now raise ValueError
if they called on a closed object. Patch by John Hergenroeder.

@item 
bpo-21795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21795}: smtpd now supports the 8BITMIME extension whenever the new
@emph{decode_data} constructor argument is set to False.

@item 
bpo-24155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24155}: optimize heapq.heapify() for better cache performance when
heapifying large lists.

@item 
bpo-21800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21800}: imaplib now supports RFC 5161 (enable), RFC 6855
(utf8/internationalized email) and automatically encodes non-ASCII
usernames and passwords to UTF8.

@item 
bpo-20274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20274}: When calling a _sqlite.Connection, it now complains if passed
any keyword arguments.  Previously it silently ignored them.

@item 
bpo-20274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20274}: Remove ignored and erroneous "kwargs" parameters from three
METH_VARARGS methods on _sqlite.Connection.

@item 
bpo-24134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24134}: assertRaises(), assertRaisesRegex(), assertWarns() and
assertWarnsRegex() checks now emits a deprecation warning when callable is
None or keyword arguments except msg is passed in the context manager
mode.

@item 
bpo-24018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24018}: Add a collections.abc.Generator abstract base class.
Contributed by Stefan Behnel.

@item 
bpo-23880@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23880}: Tkinter's getint() and getdouble() now support Tcl_Obj.
Tkinter's getdouble() now supports any numbers (in particular int).

@item 
bpo-22619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22619}: Added negative limit support in the traceback module. Based on
patch by Dmitry Kazakov.

@item 
bpo-24094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24094}: Fix possible crash in json.encode with poorly behaved dict
subclasses.

@item 
bpo-9246@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9246}: On POSIX, os.getcwd() now supports paths longer than 1025 bytes.
Patch written by William Orr.

@item 
bpo-17445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17445}: add difflib.diff_bytes() to support comparison of byte strings
(fixes a regression from Python 2).

@item 
bpo-23917@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23917}: Fall back to sequential compilation when ProcessPoolExecutor
doesn't exist. Patch by Claudiu Popa.

@item 
bpo-23008@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23008}: Fixed resolving attributes with boolean value is False in
pydoc.

@item 
Fix asyncio issue 235: LifoQueue and PriorityQueue's put didn't increment
unfinished tasks (this bug was introduced when JoinableQueue was merged
with Queue).

@item 
bpo-23908@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23908}: os functions now reject paths with embedded null character on
Windows instead of silently truncating them.

@item 
bpo-23728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23728}: binascii.crc_hqx() could return an integer outside of the range
0-0xffff for empty data.

@item 
bpo-23887@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23887}: urllib.error.HTTPError now has a proper repr() representation.
Patch by Berker Peksag.

@item 
asyncio: New event loop APIs: set_task_factory() and get_task_factory().

@item 
asyncio: async() function is deprecated in favour of ensure_future().

@item 
bpo-24178@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24178}: asyncio.Lock, Condition, Semaphore, and BoundedSemaphore
support new 'async with' syntax.  Contributed by Yury Selivanov.

@item 
bpo-24179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24179}: Support 'async for' for asyncio.StreamReader. Contributed by
Yury Selivanov.

@item 
bpo-24184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24184}: Add AsyncIterator and AsyncIterable ABCs to collections.abc.
Contributed by Yury Selivanov.

@item 
bpo-22547@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22547}: Implement informative __repr__ for inspect.BoundArguments.
Contributed by Yury Selivanov.

@item 
bpo-24190@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24190}: Implement inspect.BoundArgument.apply_defaults() method.
Contributed by Yury Selivanov.

@item 
bpo-20691@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20691}: Add 'follow_wrapped' argument to
inspect.Signature.from_callable() and inspect.signature(). Contributed by
Yury Selivanov.

@item 
bpo-24248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24248}: Deprecate inspect.Signature.from_function() and
inspect.Signature.from_builtin().

@item 
bpo-23898@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23898}: Fix inspect.classify_class_attrs() to support attributes with
overloaded __eq__ and __bool__.  Patch by Mike Bayer.

@item 
bpo-24298@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24298}: Fix inspect.signature() to correctly unwrap wrappers around
bound methods.
@end itemize

@node IDLE<50>,Tests<58>,Library<77>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id554}@anchor{133b}
@subsubsection IDLE



@itemize -

@item 
bpo-23184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23184}: remove unused names and imports in idlelib. Initial patch by Al
Sweigart.
@end itemize

@node Tests<58>,Documentation<54>,IDLE<50>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id555}@anchor{133c}
@subsubsection Tests



@itemize -

@item 
bpo-21520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21520}: test_zipfile no longer fails if the word 'bad' appears anywhere
in the name of the current directory.

@item 
bpo-9517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9517}: Move script_helper into the support package. Patch by Christie
Wilson.
@end itemize

@node Documentation<54>,Tools/Demos<33>,Tests<58>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id556}@anchor{133d}
@subsubsection Documentation



@itemize -

@item 
bpo-22155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22155}: Add File Handlers subsection with createfilehandler to tkinter
doc.  Remove obsolete example from FAQ.  Patch by Martin Panter.

@item 
bpo-24029@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24029}: Document the name binding behavior for submodule imports.

@item 
bpo-24077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24077}: Fix typo in man page for -I command option: -s, not -S
@end itemize

@node Tools/Demos<33>,,Documentation<54>,Python 3 5 0 beta 1
@anchor{whatsnew/changelog id557}@anchor{133e}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-24000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24000}: Improved Argument Clinic's mapping of converters to legacy
"format units". Updated the documentation to match.

@item 
bpo-24001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24001}: Argument Clinic converters now use accept=@{type@} instead of
types=@{'type'@} to specify the types the converter accepts.

@item 
bpo-23330@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23330}: h2py now supports arbitrary filenames in #include.

@item 
bpo-24031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24031}: make patchcheck now supports git checkouts, too.
@end itemize

@node Python 3 5 0 alpha 4,Python 3 5 0 alpha 3,Python 3 5 0 beta 1,更新日志
@anchor{whatsnew/changelog python-3-5-0-alpha-4}@anchor{133f}
@subsection Python 3.5.0 alpha 4


@emph{Release date: 2015-04-19}

@menu
* Core and Builtins: Core and Builtins<76>. 
* Library: Library<78>. 
* Build: Build<61>. 
* Tests: Tests<59>. 
* Tools/Demos: Tools/Demos<34>. 
* C API: C API<41>. 

@end menu

@node Core and Builtins<76>,Library<78>,,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id558}@anchor{1340}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-22980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22980}: Under Linux, GNU/KFreeBSD and the Hurd, C extensions now
include the architecture triplet in the extension name, to make it easy to
test builds for different ABIs in the same working tree.  Under OS X, the
extension name now includes 
@geindex Python 提高建议; PEP 3149
PEP 3149@footnote{https://www.python.org/dev/peps/pep-3149}-style information.

@item 
bpo-22631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22631}: Added Linux-specific socket constant CAN_RAW_FD_FRAMES. Patch
courtesy of Joe Jevnik.

@item 
bpo-23731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23731}: Implement 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488}: removal of .pyo files.

@item 
bpo-23726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23726}: Don't enable GC for user subclasses of non-GC types that don't
add any new fields.  Patch by Eugene Toder.

@item 
bpo-23309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23309}: Avoid a deadlock at shutdown if a daemon thread is aborted
while it is holding a lock to a buffered I/O object, and the main thread
tries to use the same I/O object (typically stdout or stderr).  A fatal
error is emitted instead.

@item 
bpo-22977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22977}: Fixed formatting Windows error messages on Wine. Patch by
Martin Panter.

@item 
bpo-23466@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23466}: %c, %o, %x, and %X in bytes formatting now raise TypeError on
non-integer input.

@item 
bpo-24044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24044}: Fix possible null pointer dereference in list.sort in out of
memory conditions.

@item 
bpo-21354@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21354}: PyCFunction_New function is exposed by python DLL again.
@end itemize

@node Library<78>,Build<61>,Core and Builtins<76>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id559}@anchor{1341}
@subsubsection Library



@itemize -

@item 
bpo-23840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23840}: tokenize.open() now closes the temporary binary file on error
to fix a resource warning.

@item 
bpo-16914@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16914}: new debuglevel 2 in smtplib adds timestamps to debug output.

@item 
bpo-7159@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7159}: urllib.request now supports sending auth credentials
automatically after the first 401.  This enhancement is a superset of the
enhancement from bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494} and supersedes that change.

@item 
bpo-23703@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23703}: Fix a regression in urljoin() introduced in 901e4e52b20a. Patch
by Demian Brecht.

@item 
bpo-4254@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4254}: Adds _curses.update_lines_cols().  Patch by Arnon Yaari

@item 
bpo-19933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19933}: Provide default argument for ndigits in round. Patch by
Vajrasky Kok.

@item 
bpo-23193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23193}: Add a numeric_owner parameter to tarfile.TarFile.extract and
tarfile.TarFile.extractall. Patch by Michael Vogt and Eric Smith.

@item 
bpo-23342@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23342}: Add a subprocess.run() function than returns a CalledProcess
instance for a more consistent API than the existing call* functions.

@item 
bpo-21217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21217}: inspect.getsourcelines() now tries to compute the start and end
lines from the code object, fixing an issue when a lambda function is used
as decorator argument. Patch by Thomas Ballinger and Allison Kaptur.

@item 
bpo-24521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=24521}: Fix possible integer overflows in the pickle module.

@item 
bpo-22931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22931}: Allow '[' and ']' in cookie values.

@item 
The keywords attribute of functools.partial is now always a dictionary.

@item 
bpo-23811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23811}: Add missing newline to the PyCompileError error message. Patch
by Alex Shkop.

@item 
bpo-21116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21116}: Avoid blowing memory when allocating a multiprocessing shared
array that's larger than 50% of the available RAM.  Patch by Médéric
Boquien.

@item 
bpo-22982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22982}: Improve BOM handling when seeking to multiple positions of a
writable text file.

@item 
bpo-23464@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23464}: Removed deprecated asyncio JoinableQueue.

@item 
bpo-23529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23529}: Limit the size of decompressed data when reading from GzipFile,
BZ2File or LZMAFile.  This defeats denial of service attacks using
compressed bombs (i.e. compressed payloads which decompress to a huge
size).  Patch by Martin Panter and Nikolaus Rath.

@item 
bpo-21859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21859}: Added Python implementation of io.FileIO.

@item 
bpo-23865@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23865}: close() methods in multiple modules now are idempotent and more
robust at shutdown. If they need to release multiple resources, all are
released even if errors occur.

@item 
bpo-23400@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23400}: Raise same exception on both Python 2 and 3 if sem_open is not
available. Patch by Davin Potts.

@item 
bpo-10838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10838}: The subprocess now module includes SubprocessError and
TimeoutError in its list of exported names for the users wild enough to
use @code{from subprocess import *}.

@item 
bpo-23411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23411}: Added DefragResult, ParseResult, SplitResult,
DefragResultBytes, ParseResultBytes, and SplitResultBytes to
urllib.parse.__all__. Patch by Martin Panter.

@item 
bpo-23881@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23881}: urllib.request.ftpwrapper constructor now closes the socket if
the FTP connection failed to fix a ResourceWarning.

@item 
bpo-23853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23853}: @ref{778,,socket.socket.sendall()} does no more reset the socket
timeout each time data is sent successfully. The socket timeout is now the
maximum total duration to send all data.

@item 
bpo-22721@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22721}: An order of multiline pprint output of set or dict containing
orderable and non-orderable elements no longer depends on iteration order
of set or dict.

@item 
bpo-15133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15133}: _tkinter.tkapp.getboolean() now supports Tcl_Obj and always
returns bool. tkinter.BooleanVar now validates input values (accepted
bool, int, str, and Tcl_Obj).  tkinter.BooleanVar.get() now always returns
bool.

@item 
bpo-10590@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10590}: xml.sax.parseString() now supports string argument.

@item 
bpo-23338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23338}: Fixed formatting ctypes error messages on Cygwin. Patch by
Makoto Kato.

@item 
bpo-15582@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15582}: inspect.getdoc() now follows inheritance chains.

@item 
bpo-2175@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2175}: SAX parsers now support a character stream of InputSource
object.

@item 
bpo-16840@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16840}: Tkinter now supports 64-bit integers added in Tcl 8.4 and
arbitrary precision integers added in Tcl 8.5.

@item 
bpo-23834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23834}: Fix socket.sendto(), use the C Py_ssize_t type to store the
result of sendto() instead of the C int type.

@item 
bpo-23618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23618}: @ref{773,,socket.socket.connect()} now waits until the connection
completes instead of raising @ref{756,,InterruptedError} if the connection is
interrupted by signals, signal handlers don't raise an exception and the
socket is blocking or has a timeout. @ref{773,,socket.socket.connect()} still
raise @ref{756,,InterruptedError} for non-blocking sockets.

@item 
bpo-21526@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21526}: Tkinter now supports new boolean type in Tcl 8.5.

@item 
bpo-23836@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23836}: Fix the faulthandler module to handle reentrant calls to its
signal handlers.

@item 
bpo-23838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23838}: linecache now clears the cache and returns an empty result on
MemoryError.

@item 
bpo-10395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10395}: Added os.path.commonpath(). Implemented in posixpath and
ntpath. Based on patch by Rafik Draoui.

@item 
bpo-23611@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23611}: Serializing more "lookupable" objects (such as unbound methods
or nested classes) now are supported with pickle protocols < 4.

@item 
bpo-13583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13583}: sqlite3.Row now supports slice indexing.

@item 
bpo-18473@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18473}: Fixed 2to3 and 3to2 compatible pickle mappings.  Fixed
ambiguous reverse mappings.  Added many new mappings.  Import mapping is
no longer applied to modules already mapped with full name mapping.

@item 
bpo-23485@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23485}: select.select() is now retried automatically with the
recomputed timeout when interrupted by a signal, except if the signal
handler raises an exception. This change is part of the 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}.

@item 
bpo-23752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23752}: When built from an existing file descriptor, io.FileIO() now
only calls fstat() once. Before fstat() was called twice, which was not
necessary.

@item 
bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}: collections.deque() objects now support __add__, __mul__, and
__imul__().

@item 
bpo-23171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23171}: csv.Writer.writerow() now supports arbitrary iterables.

@item 
bpo-23745@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23745}: The new email header parser now handles duplicate MIME
parameter names without error, similar to how get_param behaves.

@item 
bpo-22117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22117}: Fix os.utime(), it now rounds the timestamp towards minus
infinity (-inf) instead of rounding towards zero.

@item 
bpo-23310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23310}: Fix MagicMock's initializer to work with __methods__, just like
configure_mock().  Patch by Kasia Jachim.
@end itemize

@node Build<61>,Tests<59>,Library<78>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id560}@anchor{1342}
@subsubsection Build



@itemize -

@item 
bpo-23817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23817}: FreeBSD now uses "1.0" in the SOVERSION as other operating
systems, instead of just "1".

@item 
bpo-23501@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23501}: Argument Clinic now generates code into separate files by
default.
@end itemize

@node Tests<59>,Tools/Demos<34>,Build<61>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id561}@anchor{1343}
@subsubsection Tests



@itemize -

@item 
bpo-23799@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23799}: Added test.support.start_threads() for running and cleaning up
multiple threads.

@item 
bpo-22390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22390}: test.regrtest now emits a warning if temporary files or
directories are left after running a test.
@end itemize

@node Tools/Demos<34>,C API<41>,Tests<59>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id562}@anchor{1344}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-18128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18128}: pygettext now uses standard +NNNN format in the
POT-Creation-Date header.

@item 
bpo-23935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23935}: Argument Clinic's understanding of format units accepting
bytes, bytearrays, and buffers is now consistent with both the
documentation and the implementation.

@item 
bpo-23944@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23944}: Argument Clinic now wraps long impl prototypes at column 78.

@item 
bpo-20586@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20586}: Argument Clinic now ensures that functions without docstrings
have signatures.

@item 
bpo-23492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23492}: Argument Clinic now generates argument parsing code with
PyArg_Parse instead of PyArg_ParseTuple if possible.

@item 
bpo-23500@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23500}: Argument Clinic is now smarter about generating the "#ifndef"
(empty) definition of the methoddef macro: it's only generated once, even
if Argument Clinic processes the same symbol multiple times, and it's
emitted at the end of all processing rather than immediately after the
first use.
@end itemize

@node C API<41>,,Tools/Demos<34>,Python 3 5 0 alpha 4
@anchor{whatsnew/changelog id563}@anchor{1345}
@subsubsection C API



@itemize -

@item 
bpo-23998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23998}: PyImport_ReInitLock() now checks for lock allocation error
@end itemize

@node Python 3 5 0 alpha 3,Python 3 5 0 alpha 2,Python 3 5 0 alpha 4,更新日志
@anchor{whatsnew/changelog python-3-5-0-alpha-3}@anchor{1346}
@subsection Python 3.5.0 alpha 3


@emph{Release date: 2015-03-28}

@menu
* Core and Builtins: Core and Builtins<77>. 
* Library: Library<79>. 
* Build: Build<62>. 
* Tests: Tests<60>. 
* Tools/Demos: Tools/Demos<35>. 

@end menu

@node Core and Builtins<77>,Library<79>,,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id564}@anchor{1347}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23573}: Increased performance of string search operations (str.find,
str.index, str.count, the in operator, str.split, str.partition) with
arguments of different kinds (UCS1, UCS2, UCS4).

@item 
bpo-23753@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23753}: Python doesn't support anymore platforms without stat() or
fstat(), these functions are always required.

@item 
bpo-23681@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23681}: The -b option now affects comparisons of bytes with int.

@item 
bpo-23632@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23632}: Memoryviews now allow tuple indexing (including for
multi-dimensional memoryviews).

@item 
bpo-23192@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23192}: Fixed generator lambdas.  Patch by Bruno Cauet.

@item 
bpo-23629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23629}: Fix the default __sizeof__ implementation for variable-sized
objects.
@end itemize

@node Library<79>,Build<62>,Core and Builtins<77>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id565}@anchor{1348}
@subsubsection Library



@itemize -

@item 
bpo-14260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14260}: The groupindex attribute of regular expression pattern object
now is non-modifiable mapping.

@item 
bpo-23792@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23792}: Ignore KeyboardInterrupt when the pydoc pager is active. This
mimics the behavior of the standard unix pagers, and prevents pipepager
from shutting down while the pager itself is still running.

@item 
bpo-23775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23775}: pprint() of OrderedDict now outputs the same representation as
repr().

@item 
bpo-23765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23765}: Removed IsBadStringPtr calls in ctypes

@item 
bpo-22364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22364}: Improved some re error messages using regex for hints.

@item 
bpo-23742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23742}: ntpath.expandvars() no longer loses unbalanced single quotes.

@item 
bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}: The zipfile.ZipFile.open function now supports 'x' (exclusive
creation) mode.

@item 
bpo-21802@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21802}: The reader in BufferedRWPair now is closed even when closing
writer failed in BufferedRWPair.close().

@item 
bpo-23622@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23622}: Unknown escapes in regular expressions that consist of @code{'\'}
and ASCII letter now raise a deprecation warning and will be forbidden in
Python 3.6.

@item 
bpo-23671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23671}: string.Template now allows specifying the "self" parameter as a
keyword argument.  string.Formatter now allows specifying the "self" and
the "format_string" parameters as keyword arguments.

@item 
bpo-23502@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23502}: The pprint module now supports mapping proxies.

@item 
bpo-17530@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17530}: pprint now wraps long bytes objects and bytearrays.

@item 
bpo-22687@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22687}: Fixed some corner cases in breaking words in tetxtwrap. Got rid
of quadratic complexity in breaking long words.

@item 
bpo-4727@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4727}: The copy module now uses pickle protocol 4 (PEP 3154) and
supports copying of instances of classes whose __new__ method takes
keyword-only arguments.

@item 
bpo-23491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23491}: Added a zipapp module to support creating executable zip file
archives of Python code. Registered ".pyz" and ".pyzw" extensions on
Windows for these archives (PEP 441).

@item 
bpo-23657@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23657}: Avoid explicit checks for str in zipapp, adding support for
pathlib.Path objects as arguments.

@item 
bpo-23688@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23688}: Added support of arbitrary bytes-like objects and avoided
unnecessary copying of memoryview in gzip.GzipFile.write(). Original patch
by Wolfgang Maier.

@item 
bpo-23252@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23252}: Added support for writing ZIP files to unseekable streams.

@item 
bpo-23647@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23647}: Increase imaplib's MAXLINE to accommodate modern mailbox sizes.

@item 
bpo-23539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23539}: If body is None, http.client.HTTPConnection.request now sets
Content-Length to 0 for PUT, POST, and PATCH headers to avoid 411 errors
from some web servers.

@item 
bpo-22351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22351}: The nntplib.NNTP constructor no longer leaves the connection
and socket open until the garbage collector cleans them up.  Patch by
Martin Panter.

@item 
bpo-23704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23704}: collections.deque() objects now support methods for index(),
insert(), and copy().  This allows deques to be registered as a
MutableSequence and it improves their substitutability for lists.

@item 
bpo-23715@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23715}: @ref{77c,,signal.sigwaitinfo()} and @ref{77b,,signal.sigtimedwait()} are
now retried when interrupted by a signal not in the @emph{sigset} parameter, if
the signal handler does not raise an exception. signal.sigtimedwait()
recomputes the timeout with a monotonic clock when it is retried.

@item 
bpo-23001@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23001}: Few functions in modules mmap, ossaudiodev, socket, ssl, and
codecs, that accepted only read-only bytes-like object now accept writable
bytes-like object too.

@item 
bpo-23646@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23646}: If time.sleep() is interrupted by a signal, the sleep is now
retried with the recomputed delay, except if the signal handler raises an
exception (PEP 475).

@item 
bpo-23136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23136}: _strptime now uniformly handles all days in week 0, including
Dec 30 of previous year.  Based on patch by Jim Carroll.

@item 
bpo-23700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23700}: Iterator of NamedTemporaryFile now keeps a reference to
NamedTemporaryFile instance.  Patch by Bohuslav Kabrda.

@item 
bpo-22903@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22903}: The fake test case created by unittest.loader when it fails
importing a test module is now picklable.

@item 
bpo-22181@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22181}: On Linux, os.urandom() now uses the new getrandom() syscall if
available, syscall introduced in the Linux kernel 3.17. It is more
reliable and more secure, because it avoids the need of a file descriptor
and waits until the kernel has enough entropy.

@item 
bpo-2211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2211}: Updated the implementation of the http.cookies.Morsel class.
Setting attributes key, value and coded_value directly now is deprecated.
update() and setdefault() now transform and check keys.  Comparing for
equality now takes into account attributes key, value and coded_value.
copy() now returns a Morsel, not a dict.  repr() now contains all
attributes. Optimized checking keys and quoting values.  Added new tests.
Original patch by Demian Brecht.

@item 
bpo-18983@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18983}: Allow selection of output units in timeit. Patch by Julian
Gindi.

@item 
bpo-23631@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23631}: Fix traceback.format_list when a traceback has been mutated.

@item 
bpo-23568@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23568}: Add rdivmod support to MagicMock() objects. Patch by Håkan
Lövdahl.

@item 
bpo-2052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2052}: Add charset parameter to HtmlDiff.make_file().

@item 
bpo-23668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23668}: Support os.truncate and os.ftruncate on Windows.

@item 
bpo-23138@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23138}: Fixed parsing cookies with absent keys or values in cookiejar.
Patch by Demian Brecht.

@item 
bpo-23051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23051}: multiprocessing.Pool methods imap() and imap_unordered() now
handle exceptions raised by an iterator.  Patch by Alon Diamant and Davin
Potts.

@item 
bpo-23581@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23581}: Add matmul support to MagicMock. Patch by Håkan Lövdahl.

@item 
bpo-23566@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23566}: enable(), register(), dump_traceback() and
dump_traceback_later() functions of faulthandler now accept file
descriptors. Patch by Wei Wu.

@item 
bpo-22928@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22928}: Disabled HTTP header injections in http.client. Original patch
by Demian Brecht.

@item 
bpo-23615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23615}: Modules bz2, tarfile and tokenize now can be reloaded with
imp.reload(). Patch by Thomas Kluyver.

@item 
bpo-23605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23605}: os.walk() now calls os.scandir() instead of os.listdir(). The
usage of os.scandir() reduces the number of calls to os.stat(). Initial
patch written by Ben Hoyt.
@end itemize

@node Build<62>,Tests<60>,Library<79>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id566}@anchor{1349}
@subsubsection Build



@itemize -

@item 
bpo-23585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23585}: make patchcheck will ensure the interpreter is built.
@end itemize

@node Tests<60>,Tools/Demos<35>,Build<62>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id567}@anchor{134a}
@subsubsection Tests



@itemize -

@item 
bpo-23583@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23583}: Added tests for standard IO streams in IDLE.

@item 
bpo-22289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22289}: Prevent test_urllib2net failures due to ftp connection timeout.
@end itemize

@node Tools/Demos<35>,,Tests<60>,Python 3 5 0 alpha 3
@anchor{whatsnew/changelog id568}@anchor{134b}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-22826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22826}: The result of open() in Tools/freeze/bkfile.py is now better
compatible with regular files (in particular it now supports the context
management protocol).
@end itemize

@node Python 3 5 0 alpha 2,Python 3 5 0 alpha 1,Python 3 5 0 alpha 3,更新日志
@anchor{whatsnew/changelog python-3-5-0-alpha-2}@anchor{134c}
@subsection Python 3.5.0 alpha 2


@emph{Release date: 2015-03-09}

@menu
* Core and Builtins: Core and Builtins<78>. 
* Library: Library<80>. 
* Build: Build<63>. 
* C API: C API<42>. 
* Windows: Windows<55>. 

@end menu

@node Core and Builtins<78>,Library<80>,,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id569}@anchor{134d}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23571}: PyObject_Call() and PyCFunction_Call() now raise a SystemError
if a function returns a result and raises an exception. The SystemError is
chained to the previous exception.
@end itemize

@node Library<80>,Build<63>,Core and Builtins<78>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id570}@anchor{134e}
@subsubsection Library



@itemize -

@item 
bpo-22524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22524}: New os.scandir() function, part of the 
@geindex Python 提高建议; PEP 471
PEP 471@footnote{https://www.python.org/dev/peps/pep-0471}:
"os.scandir() function -- a better and faster directory iterator". Patch
written by Ben Hoyt.

@item 
bpo-23103@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23103}: Reduced the memory consumption of IPv4Address and IPv6Address.

@item 
bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}: BaseHTTPRequestHandler again logs response code as numeric, not
as stringified enum.  Patch by Demian Brecht.

@item 
bpo-23476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23476}: In the ssl module, enable OpenSSL's X509_V_FLAG_TRUSTED_FIRST
flag on certificate stores when it is available.

@item 
bpo-23576@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23576}: Avoid stalling in SSL reads when EOF has been reached in the
SSL layer but the underlying connection hasn't been closed.

@item 
bpo-23504@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23504}: Added an __all__ to the types module.

@item 
bpo-23563@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23563}: Optimized utility functions in urllib.parse.

@item 
bpo-7830@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7830}: Flatten nested functools.partial.

@item 
bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}: Added the __module__ attribute to _tkinter classes.

@item 
bpo-19980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19980}: Improved help() for non-recognized strings.  help('@w{'}) now shows
the help on str.  help('help') now shows the help on help(). Original
patch by Mark Lawrence.

@item 
bpo-23521@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23521}: Corrected pure python implementation of timedelta division.
Eliminated OverflowError from @code{timedelta * float} for some floats;
Corrected rounding in timedelta true division.

@item 
bpo-21619@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21619}: Popen objects no longer leave a zombie after exit in the with
statement if the pipe was broken.  Patch by Martin Panter.

@item 
bpo-22936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22936}: Make it possible to show local variables in tracebacks for both
the traceback module and unittest.

@item 
bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}: Add an option to limit the output size in bz2.decompress().
Patch by Nikolaus Rath.

@item 
bpo-6639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6639}: Module-level turtle functions no longer raise TclError after
closing the window.

@item 
bpo-814253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=814253}: Group references and conditional group references now work in
lookbehind assertions in regular expressions. (See also: bpo-9179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9179})

@item 
bpo-23215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23215}: Multibyte codecs with custom error handlers that ignores errors
consumed too much memory and raised SystemError or MemoryError. Original
patch by Aleksi Torhamo.

@item 
bpo-5700@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5700}: io.FileIO() called flush() after closing the file. flush() was
not called in close() if closefd=False.

@item 
bpo-23374@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23374}: Fixed pydoc failure with non-ASCII files when stdout encoding
differs from file system encoding (e.g. on Mac OS).

@item 
bpo-23481@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23481}: Remove RC4 from the SSL module's default cipher list.

@item 
bpo-21548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21548}: Fix pydoc.synopsis() and pydoc.apropos() on modules with empty
docstrings.

@item 
bpo-22885@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22885}: Fixed arbitrary code execution vulnerability in the dbm.dumb
module. Original patch by Claudiu Popa.

@item 
bpo-23239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23239}: ssl.match_hostname() now supports matching of IP addresses.

@item 
bpo-23146@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23146}: Fix mishandling of absolute Windows paths with forward slashes
in pathlib.

@item 
bpo-23096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23096}: Pickle representation of floats with protocol 0 now is the same
for both Python and C implementations.

@item 
bpo-19105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19105}: pprint now more efficiently uses free space at the right.

@item 
bpo-14910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14910}: Add allow_abbrev parameter to argparse.ArgumentParser. Patch by
Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson.

@item 
bpo-21717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21717}: tarfile.open() now supports 'x' (exclusive creation) mode.

@item 
bpo-23344@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23344}: marshal.dumps() is now 20-25% faster on average.

@item 
bpo-20416@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20416}: marshal.dumps() with protocols 3 and 4 is now 40-50% faster on
average.

@item 
bpo-23421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23421}: Fixed compression in tarfile CLI.  Patch by wdv4758h.

@item 
bpo-23367@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23367}: Fix possible overflows in the unicodedata module.

@item 
bpo-23361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23361}: Fix possible overflow in Windows subprocess creation code.

@item 
logging.handlers.QueueListener now takes a respect_handler_level keyword
argument which, if set to True, will pass messages to handlers taking
handler levels into account.

@item 
bpo-19705@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19705}: turtledemo now has a visual sorting algorithm demo.  Original
patch from Jason Yeo.

@item 
bpo-23801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23801}: Fix issue where cgi.FieldStorage did not always ignore the
entire preamble to a multipart body.
@end itemize

@node Build<63>,C API<42>,Library<80>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id571}@anchor{134f}
@subsubsection Build



@itemize -

@item 
bpo-23445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23445}: pydebug builds now use "gcc -Og" where possible, to make the
resulting executable faster.

@item 
bpo-23686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23686}: Update OS X 10.5 installer build to use OpenSSL 1.0.2a.
@end itemize

@node C API<42>,Windows<55>,Build<63>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id572}@anchor{1350}
@subsubsection C API



@itemize -

@item 
bpo-20204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20204}: Deprecation warning is now raised for builtin types without the
__module__ attribute.
@end itemize

@node Windows<55>,,C API<42>,Python 3 5 0 alpha 2
@anchor{whatsnew/changelog id573}@anchor{1351}
@subsubsection Windows



@itemize -

@item 
bpo-23465@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23465}: Implement 
@geindex Python 提高建议; PEP 486
PEP 486@footnote{https://www.python.org/dev/peps/pep-0486} - Make the Python Launcher aware of
virtual environments. Patch by Paul Moore.

@item 
bpo-23437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23437}: Make user scripts directory versioned on Windows. Patch by Paul
Moore.
@end itemize

@node Python 3 5 0 alpha 1,,Python 3 5 0 alpha 2,更新日志
@anchor{whatsnew/changelog python-3-5-0-alpha-1}@anchor{1352}
@subsection Python 3.5.0 alpha 1


@emph{Release date: 2015-02-08}

@menu
* Core and Builtins: Core and Builtins<79>. 
* Library: Library<81>. 
* IDLE: IDLE<51>. 
* Build: Build<64>. 
* C API: C API<43>. 
* Documentation: Documentation<55>. 
* Tests: Tests<61>. 
* Tools/Demos: Tools/Demos<36>. 
* Windows: Windows<56>. 

@end menu

@node Core and Builtins<79>,Library<81>,,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id574}@anchor{1353}
@subsubsection Core and Builtins



@itemize -

@item 
bpo-23285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23285}: PEP 475 - EINTR handling.

@item 
bpo-22735@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22735}: Fix many edge cases (including crashes) involving custom mro()
implementations.

@item 
bpo-22896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22896}: Avoid using PyObject_AsCharBuffer(), PyObject_AsReadBuffer()
and PyObject_AsWriteBuffer().

@item 
bpo-21295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21295}: Revert some changes (bpo-16795@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16795}) to AST line numbers and
column offsets that constituted a regression.

@item 
bpo-22986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22986}: Allow changing an object's __class__ between a dynamic type and
static type in some cases.

@item 
bpo-15859@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15859}: PyUnicode_EncodeFSDefault(), PyUnicode_EncodeMBCS() and
PyUnicode_EncodeCodePage() now raise an exception if the object is not a
Unicode object. For PyUnicode_EncodeFSDefault(), it was already the case
on platforms other than Windows. Patch written by Campbell Barton.

@item 
bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408}: The default __ne__() now returns NotImplemented if __eq__()
returned NotImplemented.  Original patch by Martin Panter.

@item 
bpo-23321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23321}: Fixed a crash in str.decode() when error handler returned
replacement string longer than malformed input data.

@item 
bpo-22286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22286}: The "backslashreplace" error handlers now works with decoding
and translating.

@item 
bpo-23253@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23253}: Delay-load ShellExecute[AW] in os.startfile for reduced startup
overhead on Windows.

@item 
bpo-22038@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22038}: pyatomic.h now uses stdatomic.h or GCC built-in functions for
atomic memory access if available. Patch written by Vitor de Lima and
Gustavo Temple.

@item 
bpo-20284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20284}: %-interpolation (aka printf) formatting added for bytes and
bytearray.

@item 
bpo-23048@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23048}: Fix jumping out of an infinite while loop in the pdb.

@item 
bpo-20335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20335}: bytes constructor now raises TypeError when encoding or errors
is specified with non-string argument.  Based on patch by Renaud Blanch.

@item 
bpo-22834@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22834}: If the current working directory ends up being set to a
non-existent directory then import will no longer raise FileNotFoundError.

@item 
bpo-22869@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22869}: Move the interpreter startup & shutdown code to a new dedicated
pylifecycle.c module

@item 
bpo-22847@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22847}: Improve method cache efficiency.

@item 
bpo-22335@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22335}: Fix crash when trying to enlarge a bytearray to 0x7fffffff
bytes on a 32-bit platform.

@item 
bpo-22653@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22653}: Fix an assertion failure in debug mode when doing a reentrant
dict insertion in debug mode.

@item 
bpo-22643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22643}: Fix integer overflow in Unicode case operations (upper, lower,
title, swapcase, casefold).

@item 
bpo-17636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17636}: Circular imports involving relative imports are now supported.

@item 
bpo-22604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22604}: Fix assertion error in debug mode when dividing a complex
number by (nan+0j).

@item 
bpo-21052@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21052}: Do not raise ImportWarning when sys.path_hooks or sys.meta_path
are set to None.

@item 
bpo-16518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16518}: Use 'bytes-like object required' in error messages that
previously used the far more cryptic "'x' does not support the buffer
protocol.

@item 
bpo-22470@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22470}: Fixed integer overflow issues in "backslashreplace",
"xmlcharrefreplace", and "surrogatepass" error handlers.

@item 
bpo-22540@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22540}: speed up @code{PyObject_IsInstance} and @code{PyObject_IsSubclass} in the
common case that the second argument has metaclass @ref{709,,type}.

@item 
bpo-18711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18711}: Add a new @code{PyErr_FormatV} function, similar to @code{PyErr_Format}
but accepting a @code{va_list} argument.

@item 
bpo-22520@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22520}: Fix overflow checking when generating the repr of a unicode
object.

@item 
bpo-22519@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22519}: Fix overflow checking in PyBytes_Repr.

@item 
bpo-22518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22518}: Fix integer overflow issues in latin-1 encoding.

@item 
bpo-16324@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16324}: _charset parameter of MIMEText now also accepts
email.charset.Charset instances. Initial patch by Claude Paroz.

@item 
bpo-1764286@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1764286}: Fix inspect.getsource() to support decorated functions. Patch
by Claudiu Popa.

@item 
bpo-18554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18554}: os.__all__ includes posix functions.

@item 
bpo-21391@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21391}: Use os.path.abspath in the shutil module.

@item 
bpo-11471@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11471}: avoid generating a JUMP_FORWARD instruction at the end of an
if-block if there is no else-clause.  Original patch by Eugene Toder.

@item 
bpo-22215@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22215}: Now ValueError is raised instead of TypeError when str or bytes
argument contains not permitted null character or byte.

@item 
bpo-22258@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22258}: Fix the internal function set_inheritable() on Illumos. This
platform exposes the function @code{ioctl(FIOCLEX)}, but calling it fails
with errno is ENOTTY: "Inappropriate ioctl for device". set_inheritable()
now falls back to the slower @code{fcntl()} (@code{F_GETFD} and then
@code{F_SETFD}).

@item 
bpo-21389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21389}: Displaying the __qualname__ of the underlying function in the
repr of a bound method.

@item 
bpo-22206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22206}: Using pthread, PyThread_create_key() now sets errno to ENOMEM
and returns -1 (error) on integer overflow.

@item 
bpo-20184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20184}: Argument Clinic based signature introspection added for 30 of
the builtin functions.

@item 
bpo-22116@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22116}: C functions and methods (of the 'builtin_function_or_method'
type) can now be weakref'ed.  Patch by Wei Wu.

@item 
bpo-22077@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22077}: Improve index error messages for bytearrays, bytes, lists, and
tuples by adding 'or slices'. Added ', not <typename>' for bytearrays.
Original patch by Claudiu Popa.

@item 
bpo-20179@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20179}: Apply Argument Clinic to bytes and bytearray. Patch by Tal
Einat.

@item 
bpo-22082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22082}: Clear interned strings in slotdefs.

@item 
Upgrade Unicode database to Unicode 7.0.0.

@item 
bpo-21897@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21897}: Fix a crash with the f_locals attribute with closure variables
when frame.clear() has been called.

@item 
bpo-21205@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21205}: Add a new @code{__qualname__} attribute to generator, the
qualified name, and use it in the representation of a generator
(@code{repr(gen)}). The default name of the generator (@code{__name__}
attribute) is now get from the function instead of the code. Use
@code{gen.gi_code.co_name} to get the name of the code.

@item 
bpo-21669@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21669}: With the aid of heuristics in SyntaxError.__init__, the parser
now attempts to generate more meaningful (or at least more search engine
friendly) error messages when "exec" and "print" are used as statements.

@item 
bpo-21642@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21642}: In the conditional if-else expression, allow an integer written
with no space between itself and the @code{else} keyword (e.g. @code{True if
42else False}) to be valid syntax.

@item 
bpo-21523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21523}: Fix over-pessimistic computation of the stack effect of some
opcodes in the compiler.  This also fixes a quadratic compilation time
issue noticeable when compiling code with a large number of "and" and "or"
operators.

@item 
bpo-21418@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21418}: Fix a crash in the builtin function super() when called without
argument and without current frame (ex: embedded Python).

@item 
bpo-21425@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21425}: Fix flushing of standard streams in the interactive
interpreter.

@item 
bpo-21435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21435}: In rare cases, when running finalizers on objects in cyclic
trash a bad pointer dereference could occur due to a subtle flaw in
internal iteration logic.

@item 
bpo-21377@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21377}: PyBytes_Concat() now tries to concatenate in-place when the
first argument has a reference count of 1.  Patch by Nikolaus Rath.

@item 
bpo-20355@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20355}: -W command line options now have higher priority than the
PYTHONWARNINGS environment variable.  Patch by Arfrever.

@item 
bpo-21274@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21274}: Define PATH_MAX for GNU/Hurd in Python/pythonrun.c.

@item 
bpo-20904@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20904}: Support setting FPU precision on m68k.

@item 
bpo-21209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21209}: Fix sending tuples to custom generator objects with the yield
from syntax.

@item 
bpo-21193@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21193}: pow(a, b, c) now raises ValueError rather than TypeError when b
is negative. Patch by Josh Rosenberg.

@item 
bpo-21176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21176}: PEP 465: Add the '@@' operator for matrix multiplication.

@item 
bpo-21134@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21134}: Fix segfault when str is called on an uninitialized
UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError object.

@item 
bpo-19537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19537}: Fix PyUnicode_DATA() alignment under m68k.  Patch by Andreas
Schwab.

@item 
bpo-20929@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20929}: Add a type cast to avoid shifting a negative number.

@item 
bpo-20731@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20731}: Properly position in source code files even if they are opened
in text mode. Patch by Serhiy Storchaka.

@item 
bpo-20637@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20637}: Key-sharing now also works for instance dictionaries of
subclasses.  Patch by Peter Ingebretson.

@item 
bpo-8297@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8297}: Attributes missing from modules now include the module name in
the error text.  Original patch by ysj.ray.

@item 
bpo-19995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19995}: %c, %o, %x, and %X now raise TypeError on non-integer input.

@item 
bpo-19655@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19655}: The ASDL parser - used by the build process to generate code
for managing the Python AST in C - was rewritten. The new parser is self
contained and does not require to carry long the spark.py parser-generator
library; spark.py was removed from the source base.

@item 
bpo-12546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12546}: Allow @code{\x00} to be used as a fill character when using str,
int, float, and complex __format__ methods.

@item 
bpo-20480@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20480}: Add ipaddress.reverse_pointer. Patch by Leon Weber.

@item 
bpo-13598@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13598}: Modify string.Formatter to support auto-numbering of
replacement fields. It now matches the behavior of str.format() in this
regard. Patches by Phil Elson and Ramchandra Apte.

@item 
bpo-8931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8931}: Make alternate formatting ('#') for type 'c' raise an exception.
In versions prior to 3.5, '#' with 'c' had no effect. Now specifying it is
an error. Patch by Torsten Landschoff.

@item 
bpo-23165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23165}: Perform overflow checks before allocating memory in the
_Py_char2wchar function.
@end itemize

@node Library<81>,IDLE<51>,Core and Builtins<79>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id575}@anchor{1354}
@subsubsection Library



@itemize -

@item 
bpo-23399@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23399}: pyvenv creates relative symlinks where possible.

@item 
bpo-20289@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20289}: cgi.FieldStorage() now supports the context management
protocol.

@item 
bpo-13128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13128}: Print response headers for CONNECT requests when debuglevel >
0. Patch by Demian Brecht.

@item 
bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381}: Optimized io.BytesIO to make less allocations and copyings.

@item 
bpo-22818@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22818}: Splitting on a pattern that could match an empty string now
raises a warning.  Patterns that can only match empty strings are now
rejected.

@item 
bpo-23099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23099}: Closing io.BytesIO with exported buffer is rejected now to
prevent corrupting exported buffer.

@item 
bpo-23326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23326}: Removed __ne__ implementations.  Since fixing default __ne__
implementation in bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408} they are redundant.

@item 
bpo-23363@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23363}: Fix possible overflow in itertools.permutations.

@item 
bpo-23364@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23364}: Fix possible overflow in itertools.product.

@item 
bpo-23366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23366}: Fixed possible integer overflow in itertools.combinations.

@item 
bpo-23369@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23369}: Fixed possible integer overflow in
_json.encode_basestring_ascii.

@item 
bpo-23353@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23353}: Fix the exception handling of generators in
PyEval_EvalFrameEx(). At entry, save or swap the exception state even if
PyEval_EvalFrameEx() is called with throwflag=0. At exit, the exception
state is now always restored or swapped, not only if why is WHY_YIELD or
WHY_RETURN. Patch co-written with Antoine Pitrou.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: Restored support of writing ZIP files to tellable but
non-seekable streams.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: Writing to ZipFile and reading multiple ZipExtFiles is
threadsafe now.

@item 
bpo-19361@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19361}: JSON decoder now raises JSONDecodeError instead of ValueError.

@item 
bpo-18518@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18518}: timeit now rejects statements which can't be compiled outside a
function or a loop (e.g. "return" or "break").

@item 
bpo-23094@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23094}: Fixed readline with frames in Python implementation of pickle.

@item 
bpo-23268@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23268}: Fixed bugs in the comparison of ipaddress classes.

@item 
bpo-21408@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21408}: Removed incorrect implementations of __ne__() which didn't
returned NotImplemented if __eq__() returned NotImplemented.  The default
__ne__() now works correctly.

@item 
bpo-19996@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19996}: @code{email.feedparser.FeedParser} now handles (malformed)
headers with no key rather than assuming the body has started.

@item 
bpo-20188@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20188}: Support Application-Layer Protocol Negotiation (ALPN) in the
ssl module.

@item 
bpo-23133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23133}: Pickling of ipaddress objects now produces more compact and
portable representation.

@item 
bpo-23248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23248}: Update ssl error codes from latest OpenSSL git master.

@item 
bpo-23266@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23266}: Much faster implementation of ipaddress.collapse_addresses()
when there are many non-consecutive addresses.

@item 
bpo-23098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23098}: 64-bit dev_t is now supported in the os module.

@item 
bpo-21817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21817}: When an exception is raised in a task submitted to a
ProcessPoolExecutor, the remote traceback is now displayed in the parent
process.  Patch by Claudiu Popa.

@item 
bpo-15955@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15955}: Add an option to limit output size when decompressing LZMA
data.  Patch by Nikolaus Rath and Martin Panter.

@item 
bpo-23250@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23250}: In the http.cookies module, capitalize "HttpOnly" and "Secure"
as they are written in the standard.

@item 
bpo-23063@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23063}: In the distutils' check command, fix parsing of reST with code
or code-block directives.

@item 
bpo-23209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23209}: selectors.BaseSelector.get_key() now raises a RuntimeError if
the selector is closed. And selectors.BaseSelector.close() now clears its
internal reference to the selector mapping to break a reference cycle.
Initial patch written by Martin Richard. (See also: bpo-23225@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23225})

@item 
bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}: Provide a way to seed the linecache for a PEP-302 module
without actually loading the code.

@item 
bpo-17911@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17911}: Provide a new object API for traceback, including the ability
to not lookup lines at all until the traceback is actually rendered,
without any trace of the original objects being kept alive.

@item 
bpo-19777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19777}: Provide a home() classmethod on Path objects.  Contributed by
Victor Salgado and Mayank Tripathi.

@item 
bpo-23206@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23206}: Make @code{json.dumps(..., ensure_ascii=False)} as fast as the
default case of @code{ensure_ascii=True}.  Patch by Naoki Inada.

@item 
bpo-23185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23185}: Add math.inf and math.nan constants.

@item 
bpo-23186@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23186}: Add ssl.SSLObject.shared_ciphers() and
ssl.SSLSocket.shared_ciphers() to fetch the client's list ciphers sent at
handshake.

@item 
bpo-23143@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23143}: Remove compatibility with OpenSSLs older than 0.9.8.

@item 
bpo-23132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23132}: Improve performance and introspection support of comparison
methods created by functool.total_ordering.

@item 
bpo-19776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19776}: Add an expanduser() method on Path objects.

@item 
bpo-23112@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23112}: Fix SimpleHTTPServer to correctly carry the query string and
fragment when it redirects to add a trailing slash.

@item 
bpo-21793@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21793}: Added http.HTTPStatus enums (i.e. HTTPStatus.OK,
HTTPStatus.NOT_FOUND). Patch by Demian Brecht.

@item 
bpo-23093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23093}: In the io, module allow more operations to work on detached
streams.

@item 
bpo-23111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23111}: In the ftplib, make ssl.PROTOCOL_SSLv23 the default protocol
version.

@item 
bpo-22585@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22585}: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(),
instead of reading /dev/urandom, to get pseudo-random bytes.

@item 
bpo-19104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19104}: pprint now produces evaluable output for wrapped strings.

@item 
bpo-23071@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23071}: Added missing names to codecs.__all__.  Patch by Martin Panter.

@item 
bpo-22783@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22783}: Pickling now uses the NEWOBJ opcode instead of the NEWOBJ_EX
opcode if possible.

@item 
bpo-15513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15513}: Added a __sizeof__ implementation for pickle classes.

@item 
bpo-19858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19858}: pickletools.optimize() now aware of the MEMOIZE opcode, can
produce more compact result and no longer produces invalid output if input
data contains MEMOIZE opcodes together with PUT or BINPUT opcodes.

@item 
bpo-22095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22095}: Fixed HTTPConnection.set_tunnel with default port.  The port
value in the host header was set to "None".  Patch by Demian Brecht.

@item 
bpo-23016@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23016}: A warning no longer produces an AttributeError when the program
is run with pythonw.exe.

@item 
bpo-21775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21775}: shutil.copytree(): fix crash when copying to VFAT. An exception
handler assumed that OSError objects always have a 'winerror' attribute.
That is not the case, so the exception handler itself raised
AttributeError when run on Linux (and, presumably, any other non-Windows
OS). Patch by Greg Ward.

@item 
bpo-1218234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1218234}: Fix inspect.getsource() to load updated source of reloaded
module. Initial patch by Berker Peksag.

@item 
bpo-21740@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21740}: Support wrapped callables in doctest. Patch by Claudiu Popa.

@item 
bpo-23009@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23009}: Make sure selectors.EpollSelector.select() works when no FD is
registered.

@item 
bpo-22959@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22959}: In the constructor of http.client.HTTPSConnection, prefer the
context's check_hostname attribute over the @emph{check_hostname} parameter.

@item 
bpo-22696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22696}: Add function @ref{85b,,sys.is_finalizing()} to know about
interpreter shutdown.

@item 
bpo-16043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16043}: Add a default limit for the amount of data
xmlrpclib.gzip_decode will return. This resolves CVE-2013-1753.

@item 
bpo-14099@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14099}: ZipFile.open() no longer reopen the underlying file.  Objects
returned by ZipFile.open() can now operate independently of the ZipFile
even if the ZipFile was created by passing in a file-like object as the
first argument to the constructor.

@item 
bpo-22966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22966}: Fix __pycache__ pyc file name clobber when pyc_compile is asked
to compile a source file containing multiple dots in the source file name.

@item 
bpo-21971@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21971}: Update turtledemo doc and add module to the index.

@item 
bpo-21032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21032}: Fixed socket leak if HTTPConnection.getresponse() fails.
Original patch by Martin Panter.

@item 
bpo-22407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22407}: Deprecated the use of re.LOCALE flag with str patterns or
re.ASCII. It was newer worked.

@item 
bpo-22902@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22902}: The "ip" command is now used on Linux to determine MAC address
in uuid.getnode().  Pach by Bruno Cauet.

@item 
bpo-22960@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22960}: Add a context argument to xmlrpclib.ServerProxy constructor.

@item 
bpo-22389@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22389}: Add contextlib.redirect_stderr().

@item 
bpo-21356@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21356}: Make ssl.RAND_egd() optional to support LibreSSL. The
availability of the function is checked during the compilation. Patch
written by Bernard Spil.

@item 
bpo-22915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22915}: SAX parser now supports files opened with file descriptor or
bytes path.

@item 
bpo-22609@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22609}: Constructors and update methods of mapping classes in the
collections module now accept the self keyword argument.

@item 
bpo-22940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22940}: Add readline.append_history_file.

@item 
bpo-19676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19676}: Added the "namereplace" error handler.

@item 
bpo-22788@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22788}: Add @emph{context} parameter to logging.handlers.HTTPHandler.

@item 
bpo-22921@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22921}: Allow SSLContext to take the @emph{hostname} parameter even if
OpenSSL doesn't support SNI.

@item 
bpo-22894@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22894}: TestCase.subTest() would cause the test suite to be stopped
when in failfast mode, even in the absence of failures.

@item 
bpo-22796@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22796}: HTTP cookie parsing is now stricter, in order to protect
against potential injection attacks.

@item 
bpo-22370@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22370}: Windows detection in pathlib is now more robust.

@item 
bpo-22841@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22841}: Reject coroutines in asyncio add_signal_handler(). Patch by
Ludovic.Gasc.

@item 
bpo-19494@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19494}: Added urllib.request.HTTPBasicPriorAuthHandler. Patch by Matej
Cepl.

@item 
bpo-22578@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22578}: Added attributes to the re.error class.

@item 
bpo-22849@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22849}: Fix possible double free in the io.TextIOWrapper constructor.

@item 
bpo-12728@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12728}: Different Unicode characters having the same uppercase but
different lowercase are now matched in case-insensitive regular
expressions.

@item 
bpo-22821@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22821}: Fixed fcntl() with integer argument on 64-bit big-endian
platforms.

@item 
bpo-21650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21650}: Add an @code{--sort-keys} option to json.tool CLI.

@item 
bpo-22824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22824}: Updated reprlib output format for sets to use set literals.
Patch contributed by Berker Peksag.

@item 
bpo-22824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22824}: Updated reprlib output format for arrays to display empty
arrays without an unnecessary empty list.  Suggested by Serhiy Storchaka.

@item 
bpo-22406@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22406}: Fixed the uu_codec codec incorrectly ported to 3.x. Based on
patch by Martin Panter.

@item 
bpo-17293@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17293}: uuid.getnode() now determines MAC address on AIX using netstat.
Based on patch by Aivars Kalvāns.

@item 
bpo-22769@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22769}: Fixed ttk.Treeview.tag_has() when called without arguments.

@item 
bpo-22417@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22417}: Verify certificates by default in httplib (PEP 476).

@item 
bpo-22775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22775}: Fixed unpickling of http.cookies.SimpleCookie with protocol 2
and above. Patch by Tim Graham.

@item 
bpo-22776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22776}: Brought excluded code into the scope of a try block in
SysLogHandler.emit().

@item 
bpo-22665@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22665}: Add missing get_terminal_size and SameFileError to
shutil.__all__.

@item 
bpo-6623@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6623}: Remove deprecated Netrc class in the ftplib module. Patch by
Matt Chaput.

@item 
bpo-17381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17381}: Fixed handling of case-insensitive ranges in regular
expressions.

@item 
bpo-22410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22410}: Module level functions in the re module now cache compiled
locale-dependent regular expressions taking into account the locale.

@item 
bpo-22759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22759}: Query methods on pathlib.Path() (exists(), is_dir(), etc.) now
return False when the underlying stat call raises NotADirectoryError.

@item 
bpo-8876@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8876}: distutils now falls back to copying files when hard linking
doesn't work. This allows use with special filesystems such as VirtualBox
shared folders.

@item 
bpo-22217@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22217}: Implemented reprs of classes in the zipfile module.

@item 
bpo-22457@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22457}: Honour load_tests in the start_dir of discovery.

@item 
bpo-18216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18216}: gettext now raises an error when a .mo file has an unsupported
major version number.  Patch by Aaron Hill.

@item 
bpo-13918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13918}: Provide a locale.delocalize() function which can remove
locale-specific number formatting from a string representing a number,
without then converting it to a specific type.  Patch by Cédric Krier.

@item 
bpo-22676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22676}: Make the pickling of global objects which don't have a
__module__ attribute less slow.

@item 
bpo-18853@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18853}: Fixed ResourceWarning in shlex.__nain__.

@item 
bpo-9351@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9351}: Defaults set with set_defaults on an argparse subparser are no
longer ignored when also set on the parent parser.

@item 
bpo-7559@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7559}: unittest test loading ImportErrors are reported as import errors
with their import exception rather than as attribute errors after the
import has already failed.

@item 
bpo-19746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19746}: Make it possible to examine the errors from unittest discovery
without executing the test suite. The new @code{errors} attribute on TestLoader
exposes these non-fatal errors encountered during discovery.

@item 
bpo-21991@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21991}: Make email.headerregistry's header 'params' attributes be
read-only (MappingProxyType).  Previously the dictionary was modifiable
but a new one was created on each access of the attribute.

@item 
bpo-22638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22638}: SSLv3 is now disabled throughout the standard library. It can
still be enabled by instantiating a SSLContext manually.

@item 
bpo-22641@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22641}: In asyncio, the default SSL context for client connections is
now created using ssl.create_default_context(), for stronger security.

@item 
bpo-17401@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17401}: Include closefd in io.FileIO repr.

@item 
bpo-21338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21338}: Add silent mode for compileall. quiet parameters of
compile_@{dir, file, path@} functions now have a multilevel value. Also, -q
option of the CLI now have a multilevel value. Patch by Thomas Kluyver.

@item 
bpo-20152@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20152}: Convert the array and cmath modules to Argument Clinic.

@item 
bpo-18643@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18643}: Add socket.socketpair() on Windows.

@item 
bpo-22435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22435}: Fix a file descriptor leak when socketserver bind fails.

@item 
bpo-13096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13096}: Fixed segfault in CTypes POINTER handling of large values.

@item 
bpo-11694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11694}: Raise ConversionError in xdrlib as documented.  Patch by Filip
Gruszczyński and Claudiu Popa.

@item 
bpo-19380@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19380}: Optimized parsing of regular expressions.

@item 
bpo-1519638@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=1519638}: Now unmatched groups are replaced with empty strings in
re.sub() and re.subn().

@item 
bpo-18615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18615}: sndhdr.what/whathdr now return a namedtuple.

@item 
bpo-22462@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22462}: Fix pyexpat's creation of a dummy frame to make it appear in
exception tracebacks.

@item 
bpo-21965@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21965}: Add support for in-memory SSL to the ssl module.  Patch by
Geert Jansen.

@item 
bpo-21173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21173}: Fix len() on a WeakKeyDictionary when .clear() was called with
an iterator alive.

@item 
bpo-11866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11866}: Eliminated race condition in the computation of names for new
threads.

@item 
bpo-21905@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21905}: Avoid RuntimeError in pickle.whichmodule() when sys.modules is
mutated while iterating.  Patch by Olivier Grisel.

@item 
bpo-11271@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11271}: concurrent.futures.Executor.map() now takes a @emph{chunksize}
argument to allow batching of tasks in child processes and improve
performance of ProcessPoolExecutor.  Patch by Dan O'Reilly.

@item 
bpo-21883@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21883}: os.path.join() and os.path.relpath() now raise a TypeError with
more helpful error message for unsupported or mismatched types of
arguments.

@item 
bpo-22219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22219}: The zipfile module CLI now adds entries for directories
(including empty directories) in ZIP file.

@item 
bpo-22449@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22449}: In the ssl.SSLContext.load_default_certs, consult the
environmental variables SSL_CERT_DIR and SSL_CERT_FILE on Windows.

@item 
bpo-22508@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22508}: The email.__version__ variable has been removed; the email code
is no longer shipped separately from the stdlib, and __version__ hasn't
been updated in several releases.

@item 
bpo-20076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20076}: Added non derived UTF-8 aliases to locale aliases table.

@item 
bpo-20079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20079}: Added locales supported in glibc 2.18 to locale alias table.

@item 
bpo-20218@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20218}: Added convenience methods read_text/write_text and read_bytes/
write_bytes to pathlib.Path objects.

@item 
bpo-22396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22396}: On 32-bit AIX platform, don't expose os.posix_fadvise() nor
os.posix_fallocate() because their prototypes in system headers are wrong.

@item 
bpo-22517@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22517}: When an io.BufferedRWPair object is deallocated, clear its
weakrefs.

@item 
bpo-22437@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22437}: Number of capturing groups in regular expression is no longer
limited by 100.

@item 
bpo-17442@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17442}: InteractiveInterpreter now displays the full chained traceback
in its showtraceback method, to match the built in interactive
interpreter.

@item 
bpo-23392@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23392}: Added tests for marshal C API that works with FILE*.

@item 
bpo-10510@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10510}: distutils register and upload methods now use HTML standards
compliant CRLF line endings.

@item 
bpo-9850@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9850}: Fixed macpath.join() for empty first component.  Patch by Oleg
Oshmyan.

@item 
bpo-5309@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5309}: distutils' build and build_ext commands now accept a @code{-j}
option to enable parallel building of extension modules.

@item 
bpo-22448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22448}: Improve canceled timer handles cleanup to prevent unbound
memory usage. Patch by Joshua Moore-Oliva.

@item 
bpo-22427@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22427}: TemporaryDirectory no longer attempts to clean up twice when
used in the with statement in generator.

@item 
bpo-22362@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22362}: Forbidden ambiguous octal escapes out of range 0-0o377 in
regular expressions.

@item 
bpo-20912@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20912}: Now directories added to ZIP file have correct Unix and MS-DOS
directory attributes.

@item 
bpo-21866@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21866}: ZipFile.close() no longer writes ZIP64 central directory
records if allowZip64 is false.

@item 
bpo-22278@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22278}: Fix urljoin problem with relative urls, a regression observed
after changes to issue22118 were submitted.

@item 
bpo-22415@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22415}: Fixed debugging output of the GROUPREF_EXISTS opcode in the re
module. Removed trailing spaces in debugging output.

@item 
bpo-22423@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22423}: Unhandled exception in thread no longer causes unhandled
AttributeError when sys.stderr is None.

@item 
bpo-21332@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21332}: Ensure that @code{bufsize=1} in subprocess.Popen() selects line
buffering, rather than block buffering.  Patch by Akira Li.

@item 
bpo-21091@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21091}: Fix API bug: email.message.EmailMessage.is_attachment is now a
method.

@item 
bpo-21079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21079}: Fix email.message.EmailMessage.is_attachment to return the
correct result when the header has parameters as well as a value.

@item 
bpo-22247@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22247}: Add NNTPError to nntplib.__all__.

@item 
bpo-22366@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22366}: urllib.request.urlopen will accept a context object
(SSLContext) as an argument which will then be used for HTTPS connection.
Patch by Alex Gaynor.

@item 
bpo-4180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4180}: The warnings registries are now reset when the filters are
modified.

@item 
bpo-22419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22419}: Limit the length of incoming HTTP request in wsgiref server to
65536 bytes and send a 414 error code for higher lengths. Patch
contributed by Devin Cook.

@item 
Lax cookie parsing in http.cookies could be a security issue when combined
with non-standard cookie handling in some Web browsers.  Reported by
Sergey Bobrov.

@item 
bpo-20537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20537}: logging methods now accept an exception instance as well as a
Boolean value or exception tuple. Thanks to Yury Selivanov for the patch.

@item 
bpo-22384@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22384}: An exception in Tkinter callback no longer crashes the program
when it is run with pythonw.exe.

@item 
bpo-22168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22168}: Prevent turtle AttributeError with non-default Canvas on OS X.

@item 
bpo-21147@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21147}: sqlite3 now raises an exception if the request contains a null
character instead of truncating it.  Based on patch by Victor Stinner.

@item 
bpo-13968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13968}: The glob module now supports recursive search in subdirectories
using the @code{**} pattern.

@item 
bpo-21951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21951}: Fixed a crash in Tkinter on AIX when called Tcl command with
empty string or tuple argument.

@item 
bpo-21951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21951}: Tkinter now most likely raises MemoryError instead of crash if
the memory allocation fails.

@item 
bpo-22338@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22338}: Fix a crash in the json module on memory allocation failure.

@item 
bpo-12410@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12410}: imaplib.IMAP4 now supports the context management protocol.
Original patch by Tarek Ziadé.

@item 
bpo-21270@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21270}: We now override tuple methods in mock.call objects so that they
can be used as normal call attributes.

@item 
bpo-16662@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16662}: load_tests() is now unconditionally run when it is present in a
package's __init__.py.  TestLoader.loadTestsFromModule() still accepts
use_load_tests, but it is deprecated and ignored.  A new keyword-only
attribute @code{pattern} is added and documented.  Patch given by Robert
Collins, tweaked by Barry Warsaw.

@item 
bpo-22226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22226}: First letter no longer is stripped from the "status" key in the
result of Treeview.heading().

@item 
bpo-19524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19524}: Fixed resource leak in the HTTP connection when an invalid
response is received.  Patch by Martin Panter.

@item 
bpo-20421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20421}: Add a .version() method to SSL sockets exposing the actual
protocol version in use.

@item 
bpo-19546@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19546}: configparser exceptions no longer expose implementation
details. Chained KeyErrors are removed, which leads to cleaner tracebacks.
Patch by Claudiu Popa.

@item 
bpo-22051@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22051}: turtledemo no longer reloads examples to re-run them.
Initialization of variables and gui setup should be done in main(), which
is called each time a demo is run, but not on import.

@item 
bpo-21933@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21933}: Turtledemo users can change the code font size with a menu
selection or control(command) '-' or '+' or control-mousewheel. Original
patch by Lita Cho.

@item 
bpo-21597@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21597}: The separator between the turtledemo text pane and the drawing
canvas can now be grabbed and dragged with a mouse.  The code text pane
can be widened to easily view or copy the full width of the text.  The
canvas can be widened on small screens.  Original patches by Jan Kanis and
Lita Cho.

@item 
bpo-18132@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18132}: Turtledemo buttons no longer disappear when the window is
shrunk.  Original patches by Jan Kanis and Lita Cho.

@item 
bpo-22043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22043}: time.monotonic() is now always available.
@code{threading.Lock.acquire()}, @code{threading.RLock.acquire()} and socket
operations now use a monotonic clock, instead of the system clock, when a
timeout is used.

@item 
bpo-21527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21527}: Add a default number of workers to ThreadPoolExecutor equal to
5 times the number of CPUs.  Patch by Claudiu Popa.

@item 
bpo-22216@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22216}: smtplib now resets its state more completely after a quit.  The
most obvious consequence of the previous behavior was a STARTTLS failure
during a connect/starttls/quit/connect/starttls sequence.

@item 
bpo-22098@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22098}: ctypes' BigEndianStructure and LittleEndianStructure now define
an empty __slots__ so that subclasses don't always get an instance dict.
Patch by Claudiu Popa.

@item 
bpo-22185@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22185}: Fix an occasional RuntimeError in threading.Condition.wait()
caused by mutation of the waiters queue without holding the lock.  Patch
by Doug Zongker.

@item 
bpo-22287@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22287}: On UNIX, _PyTime_gettimeofday() now uses
clock_gettime(CLOCK_REALTIME) if available. As a side effect, Python now
depends on the librt library on Solaris and on Linux (only with glibc
older than 2.17).

@item 
bpo-22182@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22182}: Use e.args to unpack exceptions correctly in
distutils.file_util.move_file. Patch by Claudiu Popa.

@item 
The webbrowser module now uses subprocess's start_new_session=True rather
than a potentially risky preexec_fn=os.setsid call.

@item 
bpo-22042@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22042}: signal.set_wakeup_fd(fd) now raises an exception if the file
descriptor is in blocking mode.

@item 
bpo-16808@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16808}: inspect.stack() now returns a named tuple instead of a tuple.
Patch by Daniel Shahaf.

@item 
bpo-22236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22236}: Fixed Tkinter images copying operations in NoDefaultRoot mode.

@item 
bpo-2527@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=2527}: Add a @emph{globals} argument to timeit functions, in order to
override the globals namespace in which the timed code is executed. Patch
by Ben Roberts.

@item 
bpo-22118@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22118}: Switch urllib.parse to use RFC 3986 semantics for the
resolution of relative URLs, rather than RFCs 1808 and 2396. Patch by
Demian Brecht.

@item 
bpo-21549@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21549}: Added the "members" parameter to TarFile.list().

@item 
bpo-19628@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19628}: Allow compileall recursion depth to be specified with a -r
option.

@item 
bpo-15696@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15696}: Add a __sizeof__ implementation for mmap objects on Windows.

@item 
bpo-22068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22068}: Avoided reference loops with Variables and Fonts in Tkinter.

@item 
bpo-22165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22165}: SimpleHTTPRequestHandler now supports undecodable file names.

@item 
bpo-15381@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15381}: Optimized line reading in io.BytesIO.

@item 
bpo-8797@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=8797}: Raise HTTPError on failed Basic Authentication immediately.
Initial patch by Sam Bull.

@item 
bpo-20729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20729}: Restored the use of lazy iterkeys()/itervalues()/iteritems() in
the mailbox module.

@item 
bpo-21448@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21448}: Changed FeedParser feed() to avoid O(N@w{^2}) behavior when
parsing long line. Original patch by Raymond Hettinger.

@item 
bpo-22184@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22184}: The functools LRU Cache decorator factory now gives an earlier
and clearer error message when the user forgets the required parameters.

@item 
bpo-17923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17923}: glob() patterns ending with a slash no longer match non-dirs on
AIX.  Based on patch by Delhallt.

@item 
bpo-21725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21725}: Added support for RFC 6531 (SMTPUTF8) in smtpd.

@item 
bpo-22176@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22176}: Update the ctypes module's libffi to v3.1.  This release adds
support for the Linux AArch64 and POWERPC ELF ABIv2 little endian
architectures.

@item 
bpo-5411@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5411}: Added support for the "xztar" format in the shutil module.

@item 
bpo-21121@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21121}: Don't force 3rd party C extensions to be built with
-Werror=declaration-after-statement.

@item 
bpo-21975@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21975}: Fixed crash when using uninitialized sqlite3.Row (in particular
when unpickling pickled sqlite3.Row).  sqlite3.Row is now initialized in
the __new__() method.

@item 
bpo-20170@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20170}: Convert posixmodule to use Argument Clinic.

@item 
bpo-21539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21539}: Add an @emph{exists_ok} argument to @code{Pathlib.mkdir()} to mimic
@code{mkdir -p} and @ref{4cc,,os.makedirs()} functionality.  When true, ignore
FileExistsErrors.  Patch by Berker Peksag.

@item 
bpo-22127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22127}: Bypass IDNA for pure-ASCII host names in the socket module (in
particular for numeric IPs).

@item 
bpo-21047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21047}: set the default value for the @emph{convert_charrefs} argument of
HTMLParser to True.  Patch by Berker Peksag.

@item 
Add an __all__ to html.entities.

@item 
bpo-15114@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15114}: the strict mode and argument of HTMLParser, HTMLParser.error,
and the HTMLParserError exception have been removed.

@item 
bpo-22085@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22085}: Dropped support of Tk 8.3 in Tkinter.

@item 
bpo-21580@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21580}: Now Tkinter correctly handles bytes arguments passed to Tk. In
particular this allows initializing images from binary data.

@item 
bpo-22003@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22003}: When initialized from a bytes object, io.BytesIO() now defers
making a copy until it is mutated, improving performance and memory use on
some use cases. Patch by David Wilson.

@item 
bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}: On Windows, signal.set_wakeup_fd() now also supports sockets. A
side effect is that Python depends to the WinSock library.

@item 
bpo-22054@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22054}: Add os.get_blocking() and os.set_blocking() functions to get
and set the blocking mode of a file descriptor (False if the O_NONBLOCK
flag is set, True otherwise). These functions are not available on
Windows.

@item 
bpo-17172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17172}: Make turtledemo start as active on OS X even when run with
subprocess. Patch by Lita Cho.

@item 
bpo-21704@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21704}: Fix build error for _multiprocessing when semaphores are not
available. Patch by Arfrever Frehtes Taifersar Arahesis.

@item 
bpo-20173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20173}: Convert sha1, sha256, sha512 and md5 to ArgumentClinic. Patch
by Vajrasky Kok.

@item 
Fix repr(_socket.socket) on Windows 64-bit: don't fail with OverflowError
on closed socket. repr(socket.socket) already works fine.

@item 
bpo-22033@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22033}: Reprs of most Python implemented classes now contain actual
class name instead of hardcoded one.

@item 
bpo-21947@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21947}: The dis module can now disassemble generator-iterator objects
based on their gi_code attribute. Patch by Clement Rouault.

@item 
bpo-16133@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16133}: The asynchat.async_chat.handle_read() method now ignores
BlockingIOError exceptions.

@item 
bpo-22044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22044}: Fixed premature DECREF in call_tzinfo_method. Patch by Tom
Flanagan.

@item 
bpo-19884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19884}: readline: Disable the meta modifier key if stdout is not a
terminal to not write the ANSI sequence @code{"\033[1034h"} into stdout. This
sequence is used on some terminal (ex: TERM=xterm-256color") to enable
support of 8 bit characters.

@item 
bpo-4350@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4350}: Removed a number of out-of-dated and non-working for a long time
Tkinter methods.

@item 
bpo-6167@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6167}: Scrollbar.activate() now returns the name of active element if
the argument is not specified.  Scrollbar.set() now always accepts only 2
arguments.

@item 
bpo-15275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15275}: Clean up and speed up the ntpath module.

@item 
bpo-21888@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21888}: plistlib's load() and loads() now work if the fmt parameter is
specified.

@item 
bpo-22032@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22032}: __qualname__ instead of __name__ is now always used to format
fully qualified class names of Python implemented classes.

@item 
bpo-22031@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22031}: Reprs now always use hexadecimal format with the "0x" prefix
when contain an id in form " at 0x...".

@item 
bpo-22018@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22018}: signal.set_wakeup_fd() now raises an OSError instead of a
ValueError on @code{fstat()} failure.

@item 
bpo-21044@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21044}: tarfile.open() now handles fileobj with an integer 'name'
attribute.  Based on patch by Antoine Pietri.

@item 
bpo-21966@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21966}: Respect -q command-line option when code module is ran.

@item 
bpo-19076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19076}: Don't pass the redundant 'file' argument to self.error().

@item 
bpo-16382@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16382}: Improve exception message of warnings.warn() for bad category.
Initial patch by Phil Elson.

@item 
bpo-21932@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21932}: os.read() now uses a @ref{391,,Py_ssize_t()} type instead of
@code{int} for the size to support reading more than 2 GB at once. On
Windows, the size is truncated to INT_MAX. As any call to os.read(), the
OS may read less bytes than the number of requested bytes.

@item 
bpo-21942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21942}: Fixed source file viewing in pydoc's server mode on Windows.

@item 
bpo-11259@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11259}: asynchat.async_chat().set_terminator() now raises a ValueError
if the number of received bytes is negative.

@item 
bpo-12523@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12523}: asynchat.async_chat.push() now raises a TypeError if it doesn't
get a bytes string

@item 
bpo-21707@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21707}: Add missing kwonlyargcount argument to
ModuleFinder.replace_paths_in_code().

@item 
bpo-20639@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20639}: calling Path.with_suffix('@w{'}) allows removing the suffix again.
Patch by July Tikhonov.

@item 
bpo-21714@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21714}: Disallow the construction of invalid paths using
Path.with_name().  Original patch by Antony Lee.

@item 
bpo-15014@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15014}: Added 'auth' method to smtplib to make implementing auth
mechanisms simpler, and used it internally in the login method.

@item 
bpo-21151@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21151}: Fixed a segfault in the winreg module when @code{None} is passed
as a @code{REG_BINARY} value to SetValueEx.  Patch by John Ehresman.

@item 
bpo-21090@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21090}: io.FileIO.readall() does not ignore I/O errors anymore. Before,
it ignored I/O errors if at least the first C call read() succeed.

@item 
bpo-5800@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5800}: headers parameter of wsgiref.headers.Headers is now optional.
Initial patch by Pablo Torres Navarrete and SilentGhost.

@item 
bpo-21781@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21781}: ssl.RAND_add() now supports strings longer than 2 GB.

@item 
bpo-21679@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21679}: Prevent extraneous fstat() calls during open().  Patch by
Bohuslav Kabrda.

@item 
bpo-21863@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21863}: cProfile now displays the module name of C extension functions,
in addition to their own name.

@item 
bpo-11453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11453}: asyncore: emit a ResourceWarning when an unclosed file_wrapper
object is destroyed. The destructor now closes the file if needed. The
close() method can now be called twice: the second call does nothing.

@item 
bpo-21858@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21858}: Better handling of Python exceptions in the sqlite3 module.

@item 
bpo-21476@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21476}: Make sure the email.parser.BytesParser TextIOWrapper is
discarded after parsing, so the input file isn't unexpectedly closed.

@item 
bpo-20295@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20295}: imghdr now recognizes OpenEXR format images.

@item 
bpo-21729@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21729}: Used the "with" statement in the dbm.dumb module to ensure
files closing. Patch by Claudiu Popa.

@item 
bpo-21491@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21491}: socketserver: Fix a race condition in child processes reaping.

@item 
bpo-21719@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21719}: Added the @code{st_file_attributes} field to os.stat_result on
Windows.

@item 
bpo-21832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21832}: Require named tuple inputs to be exact strings.

@item 
bpo-21722@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21722}: The distutils "upload" command now exits with a non-zero return
code when uploading fails.  Patch by Martin Dengler.

@item 
bpo-21723@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21723}: asyncio.Queue: support any type of number (ex: float) for the
maximum size. Patch written by Vajrasky Kok.

@item 
bpo-21711@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21711}: support for "site-python" directories has now been removed from
the site module (it was deprecated in 3.4).

@item 
bpo-17552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17552}: new socket.sendfile() method allowing a file to be sent over a
socket by using high-performance os.sendfile() on UNIX. Patch by Giampaolo
Rodola'.

@item 
bpo-18039@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18039}: dbm.dump.open() now always creates a new database when the flag
has the value 'n'.  Patch by Claudiu Popa.

@item 
bpo-21326@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21326}: Add a new is_closed() method to asyncio.BaseEventLoop.
run_forever() and run_until_complete() methods of asyncio.BaseEventLoop
now raise an exception if the event loop was closed.

@item 
bpo-21766@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21766}: Prevent a security hole in CGIHTTPServer by URL unquoting paths
before checking for a CGI script at that path.

@item 
bpo-21310@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21310}: Fixed possible resource leak in failed open().

@item 
bpo-21256@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21256}: Printout of keyword args should be in deterministic order in a
mock function call. This will help to write better doctests.

@item 
bpo-21677@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21677}: Fixed chaining nonnormalized exceptions in io close() methods.

@item 
bpo-11709@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11709}: Fix the pydoc.help function to not fail when sys.stdin is not a
valid file.

@item 
bpo-21515@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21515}: tempfile.TemporaryFile now uses os.O_TMPFILE flag is available.

@item 
bpo-13223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13223}: Fix pydoc.writedoc so that the HTML documentation for methods
that use 'self' in the example code is generated correctly.

@item 
bpo-21463@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21463}: In urllib.request, fix pruning of the FTP cache.

@item 
bpo-21618@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21618}: The subprocess module could fail to close open fds that were
inherited by the calling process and already higher than POSIX resource
limits would otherwise allow.  On systems with a functioning /proc/self/fd
or /dev/fd interface the max is now ignored and all fds are closed.

@item 
bpo-20383@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20383}: Introduce importlib.util.module_from_spec() as the preferred
way to create a new module.

@item 
bpo-21552@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21552}: Fixed possible integer overflow of too long string lengths in
the tkinter module on 64-bit platforms.

@item 
bpo-14315@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14315}: The zipfile module now ignores extra fields in the central
directory that are too short to be parsed instead of letting a
struct.unpack error bubble up as this "bad data" appears in many real
world zip files in the wild and is ignored by other zip tools.

@item 
bpo-13742@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13742}: Added "key" and "reverse" parameters to heapq.merge(). (First
draft of patch contributed by Simon Sapin.)

@item 
bpo-21402@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21402}: tkinter.ttk now works when default root window is not set.

@item 
bpo-3015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3015}: _tkinter.create() now creates tkapp object with wantobject=1 by
default.

@item 
bpo-10203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10203}: sqlite3.Row now truly supports sequence protocol.  In
particular it supports reverse() and negative indices.  Original patch by
Claudiu Popa.

@item 
bpo-18807@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18807}: If copying (no symlinks) specified for a venv, then the python
interpreter aliases (python, python3) are now created by copying rather
than symlinking.

@item 
bpo-20197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20197}: Added support for the WebP image type in the imghdr module.
Patch by Fabrice Aneche and Claudiu Popa.

@item 
bpo-21513@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21513}: Speedup some properties of IP addresses (IPv4Address,
IPv6Address) such as .is_private or .is_multicast.

@item 
bpo-21137@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21137}: Improve the repr for threading.Lock() and its variants by
showing the "locked" or "unlocked" status.  Patch by Berker Peksag.

@item 
bpo-21538@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21538}: The plistlib module now supports loading of binary plist files
when reference or offset size is not a power of two.

@item 
bpo-21455@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21455}: Add a default backlog to socket.listen().

@item 
bpo-21525@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21525}: Most Tkinter methods which accepted tuples now accept lists
too.

@item 
bpo-22166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22166}: With the assistance of a new internal _codecs._forget_codec
helping function, test_codecs now clears the encoding caches to avoid the
appearance of a reference leak

@item 
bpo-22236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22236}: Tkinter tests now don't reuse default root window.  New root
window is created for every test class.

@item 
bpo-10744@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10744}: Fix 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} format strings on ctypes objects with a
nontrivial shape.

@item 
bpo-20826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20826}: Optimize ipaddress.collapse_addresses().

@item 
bpo-21487@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21487}: Optimize ipaddress.summarize_address_range() and
ipaddress.@{IPv4Network,IPv6Network@}.subnets().

@item 
bpo-21486@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21486}: Optimize parsing of netmasks in ipaddress.IPv4Network and
ipaddress.IPv6Network.

@item 
bpo-13916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13916}: Disallowed the surrogatepass error handler for non UTF-*
encodings.

@item 
bpo-20998@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20998}: Fixed re.fullmatch() of repeated single character pattern with
ignore case. Original patch by Matthew Barnett.

@item 
bpo-21075@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21075}: fileinput.FileInput now reads bytes from standard stream if
binary mode is specified.  Patch by Sam Kimbrel.

@item 
bpo-19775@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19775}: Add a samefile() method to pathlib Path objects.  Initial patch
by Vajrasky Kok.

@item 
bpo-21226@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21226}: Set up modules properly in PyImport_ExecCodeModuleObject (and
friends).

@item 
bpo-21398@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21398}: Fix a unicode error in the pydoc pager when the documentation
contains characters not encodable to the stdout encoding.

@item 
bpo-16531@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16531}: ipaddress.IPv4Network and ipaddress.IPv6Network now accept an
(address, netmask) tuple argument, so as to easily construct network
objects from existing addresses.

@item 
bpo-21156@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21156}: importlib.abc.InspectLoader.source_to_code() is now a
staticmethod.

@item 
bpo-21424@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21424}: Simplified and optimized heaqp.nlargest() and nmsmallest() to
make fewer tuple comparisons.

@item 
bpo-21396@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21396}: Fix TextIOWrapper(..., write_through=True) to not force a
flush() on the underlying binary stream.  Patch by akira.

@item 
bpo-18314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18314}: Unlink now removes junctions on Windows. Patch by Kim Gräsman

@item 
bpo-21088@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21088}: Bugfix for curses.window.addch() regression in 3.4.0. In
porting to Argument Clinic, the first two arguments were reversed.

@item 
bpo-21407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21407}: _decimal: The module now supports function signatures.

@item 
bpo-10650@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10650}: Remove the non-standard 'watchexp' parameter from the
Decimal.quantize() method in the Python version.  It had never been
present in the C version.

@item 
bpo-21469@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21469}: Reduced the risk of false positives in robotparser by checking
to make sure that robots.txt has been read or does not exist prior to
returning True in can_fetch().

@item 
bpo-19414@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19414}: Have the OrderedDict mark deleted links as unusable. This gives
an early failure if the link is deleted during iteration.

@item 
bpo-21421@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21421}: Add __slots__ to the MappingViews ABC. Patch by Josh Rosenberg.

@item 
bpo-21101@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21101}: Eliminate double hashing in the C speed-up code for
collections.Counter().

@item 
bpo-21321@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21321}: itertools.islice() now releases the reference to the source
iterator when the slice is exhausted.  Patch by Anton Afanasyev.

@item 
bpo-21057@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21057}: TextIOWrapper now allows the underlying binary stream's read()
or read1() method to return an arbitrary bytes-like object (such as a
memoryview). Patch by Nikolaus Rath.

@item 
bpo-20951@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20951}: SSLSocket.send() now raises either SSLWantReadError or
SSLWantWriteError on a non-blocking socket if the operation would block.
Previously, it would return 0.  Patch by Nikolaus Rath.

@item 
bpo-13248@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13248}: removed previously deprecated asyncore.dispatcher __getattr__
cheap inheritance hack.

@item 
bpo-9815@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9815}: assertRaises now tries to clear references to local variables in
the exception's traceback.

@item 
bpo-19940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19940}: ssl.cert_time_to_seconds() now interprets the given time string
in the UTC timezone (as specified in RFC 5280), not the local timezone.

@item 
bpo-13204@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13204}: Calling sys.flags.__new__ would crash the interpreter, now it
raises a TypeError.

@item 
bpo-19385@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19385}: Make operations on a closed dbm.dumb database always raise the
same exception.

@item 
bpo-21207@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21207}: Detect when the os.urandom cached fd has been closed or
replaced, and open it anew.

@item 
bpo-21291@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21291}: subprocess's Popen.wait() is now thread safe so that multiple
threads may be calling wait() or poll() on a Popen instance at the same
time without losing the Popen.returncode value.

@item 
bpo-21127@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21127}: Path objects can now be instantiated from str subclass
instances (such as @code{numpy.str_}).

@item 
bpo-15002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15002}: urllib.response object to use _TemporaryFileWrapper (and
_TemporaryFileCloser) facility. Provides a better way to handle file
descriptor close. Patch contributed by Christian Theune.

@item 
bpo-12220@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12220}: mindom now raises a custom ValueError indicating it doesn't
support spaces in URIs instead of letting a 'split' ValueError bubble up.

@item 
bpo-21068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21068}: The ssl.PROTOCOL* constants are now enum members.

@item 
bpo-21276@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21276}: posixmodule: Don't define USE_XATTRS on KFreeBSD and the Hurd.

@item 
bpo-21262@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21262}: New method assert_not_called for Mock. It raises AssertionError
if the mock has been called.

@item 
bpo-21238@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21238}: New keyword argument @code{unsafe} to Mock. It raises
@ref{4aa,,AttributeError} incase of an attribute startswith assert or assret.

@item 
bpo-20896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20896}: ssl.get_server_certificate() now uses PROTOCOL_SSLv23, not
PROTOCOL_SSLv3, for maximum compatibility.

@item 
bpo-21239@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21239}: patch.stopall() didn't work deterministically when the same
name was patched more than once.

@item 
bpo-21203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21203}: Updated fileConfig and dictConfig to remove inconsistencies.
Thanks to Jure Koren for the patch.

@item 
bpo-21222@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21222}: Passing name keyword argument to mock.create_autospec now
works.

@item 
bpo-21197@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21197}: Add lib64 -> lib symlink in venvs on 64-bit non-OS X POSIX.

@item 
bpo-17498@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17498}: Some SMTP servers disconnect after certain errors, violating
strict RFC conformance.  Instead of losing the error code when we issue
the subsequent RSET, smtplib now returns the error code and defers raising
the SMTPServerDisconnected error until the next command is issued.

@item 
bpo-17826@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17826}: setting an iterable side_effect on a mock function created by
create_autospec now works. Patch by Kushal Das.

@item 
bpo-7776@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=7776}: Fix @code{Host:} header and reconnection when using
http.client.HTTPConnection.set_tunnel(). Patch by Nikolaus Rath.

@item 
bpo-20968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20968}: unittest.mock.MagicMock now supports division. Patch by
Johannes Baiter.

@item 
bpo-21529@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21529}: Fix arbitrary memory access in JSONDecoder.raw_decode with a
negative second parameter. Bug reported by Guido Vranken. (See also:
CVE-2014-4616)

@item 
bpo-21169@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21169}: getpass now handles non-ascii characters that the input stream
encoding cannot encode by re-encoding using the replace error handler.

@item 
bpo-21171@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21171}: Fixed undocumented filter API of the rot13 codec. Patch by
Berker Peksag.

@item 
bpo-20539@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20539}: Improved math.factorial error message for large positive inputs
and changed exception type (OverflowError -> ValueError) for large
negative inputs.

@item 
bpo-21172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21172}: isinstance check relaxed from dict to collections.Mapping.

@item 
bpo-21155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21155}: asyncio.EventLoop.create_unix_server() now raises a ValueError
if path and sock are specified at the same time.

@item 
bpo-21136@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21136}: Avoid unnecessary normalization of Fractions resulting from
power and other operations.  Patch by Raymond Hettinger.

@item 
bpo-17621@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17621}: Introduce importlib.util.LazyLoader.

@item 
bpo-21076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21076}: signal module constants were turned into enums. Patch by
Giampaolo Rodola'.

@item 
bpo-20636@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20636}: Improved the repr of Tkinter widgets.

@item 
bpo-19505@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19505}: The items, keys, and values views of OrderedDict now support
reverse iteration using reversed().

@item 
bpo-21149@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21149}: Improved thread-safety in logging cleanup during interpreter
shutdown. Thanks to Devin Jeanpierre for the patch.

@item 
bpo-21058@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21058}: Fix a leak of file descriptor in
@ref{e16,,tempfile.NamedTemporaryFile()}, close the file descriptor if
@ref{757,,io.open()} fails

@item 
bpo-21200@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21200}: Return None from pkgutil.get_loader() when __spec__ is missing.

@item 
bpo-21013@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21013}: Enhance ssl.create_default_context() when used for server side
sockets to provide better security by default.

@item 
bpo-20145@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20145}: @code{assertRaisesRegex} and @code{assertWarnsRegex} now raise a
TypeError if the second argument is not a string or compiled regex.

@item 
bpo-20633@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20633}: Replace relative import by absolute import.

@item 
bpo-20980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20980}: Stop wrapping exception when using ThreadPool.

@item 
bpo-21082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21082}: In os.makedirs, do not set the process-wide umask. Note this
changes behavior of makedirs when exist_ok=True.

@item 
bpo-20990@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20990}: Fix issues found by pyflakes for multiprocessing.

@item 
bpo-21015@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21015}: SSL contexts will now automatically select an elliptic curve
for ECDH key exchange on OpenSSL 1.0.2 and later, and otherwise default to
"prime256v1".

@item 
bpo-21000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21000}: Improve the command-line interface of json.tool.

@item 
bpo-20995@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20995}: Enhance default ciphers used by the ssl module to enable better
security and prioritize perfect forward secrecy.

@item 
bpo-20884@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20884}: Don't assume that __file__ is defined on importlib.__init__.

@item 
bpo-21499@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21499}: Ignore __builtins__ in several test_importlib.test_api tests.

@item 
bpo-20627@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20627}: xmlrpc.client.ServerProxy is now a context manager.

@item 
bpo-19165@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19165}: The formatter module now raises DeprecationWarning instead of
PendingDeprecationWarning.

@item 
bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936}: Remove the ability of datetime.time instances to be considered
false in boolean contexts.

@item 
bpo-18931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18931}: selectors module now supports /dev/poll on Solaris. Patch by
Giampaolo Rodola'.

@item 
bpo-19977@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19977}: When the @code{LC_TYPE} locale is the POSIX locale (@code{C} locale),
@ref{427,,sys.stdin} and @ref{428,,sys.stdout} are now using the
@code{surrogateescape} error handler, instead of the @code{strict} error
handler.

@item 
bpo-20574@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20574}: Implement incremental decoder for cp65001 code (Windows code
page 65001, Microsoft UTF-8).

@item 
bpo-20879@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20879}: Delay the initialization of encoding and decoding tables for
base32, ascii85 and base85 codecs in the base64 module, and delay the
initialization of the unquote_to_bytes() table of the urllib.parse module,
to not waste memory if these modules are not used.

@item 
bpo-19157@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19157}: Include the broadcast address in the usuable hosts for IPv6 in
ipaddress.

@item 
bpo-11599@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11599}: When an external command (e.g. compiler) fails, distutils now
prints out the whole command line (instead of just the command name) if
the environment variable DISTUTILS_DEBUG is set.

@item 
bpo-4931@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4931}: distutils should not produce unhelpful "error: None" messages
anymore. distutils.util.grok_environment_error is kept but doc-deprecated.

@item 
bpo-20875@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20875}: Prevent possible gzip "'read' is not defined" NameError. Patch
by Claudiu Popa.

@item 
bpo-11558@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11558}: @code{email.message.Message.attach} now returns a more useful
error message if @code{attach} is called on a message for which
@code{is_multipart} is False.

@item 
bpo-20283@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20283}: RE pattern methods now accept the string keyword parameters as
documented. The pattern and source keyword parameters are left as
deprecated aliases.

@item 
bpo-20778@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20778}: Fix modulefinder to work with bytecode-only modules.

@item 
bpo-20791@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20791}: copy.copy() now doesn't make a copy when the input is a bytes
object. Initial patch by Peter Otten.

@item 
bpo-19748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19748}: On AIX, time.mktime() now raises an OverflowError for year
outsize range [1902; 2037].

@item 
bpo-19573@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19573}: inspect.signature: Use enum for parameter kind constants.

@item 
bpo-20726@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20726}: inspect.signature: Make Signature and Parameter picklable.

@item 
bpo-17373@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17373}: Add inspect.Signature.from_callable method.

@item 
bpo-20378@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20378}: Improve repr of inspect.Signature and inspect.Parameter.

@item 
bpo-20816@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20816}: Fix inspect.getcallargs() to raise correct TypeError for
missing keyword-only arguments. Patch by Jeremiah Lowin.

@item 
bpo-20817@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20817}: Fix inspect.getcallargs() to fail correctly if more than 3
arguments are missing. Patch by Jeremiah Lowin.

@item 
bpo-6676@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6676}: Ensure a meaningful exception is raised when attempting to parse
more than one XML document per pyexpat xmlparser instance. (Original
patches by Hirokazu Yamamoto and Amaury Forgeot d'Arc, with suggested
wording by David Gutteridge)

@item 
bpo-21117@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21117}: Fix inspect.signature to better support functools.partial. Due
to the specifics of functools.partial implementation,
positional-or-keyword arguments passed as keyword arguments become
keyword-only.

@item 
bpo-20334@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20334}: inspect.Signature and inspect.Parameter are now hashable.
Thanks to Antony Lee for bug reports and suggestions.

@item 
bpo-15916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15916}: doctest.DocTestSuite returns an empty unittest.TestSuite
instead of raising ValueError if it finds no tests

@item 
bpo-21209@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21209}: Fix asyncio.tasks.CoroWrapper to workaround a bug in yield-from
implementation in CPythons prior to 3.4.1.

@item 
asyncio: Add gi_@{frame,running,code@} properties to CoroWrapper (upstream
bpo-163@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=163}).

@item 
bpo-21311@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21311}: Avoid exception in _osx_support with non-standard compiler
configurations. Patch by John Szakmeister.

@item 
bpo-11571@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11571}: Ensure that the turtle window becomes the topmost window when
launched on OS X.

@item 
bpo-21801@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21801}: Validate that __signature__ is None or an instance of
Signature.

@item 
bpo-21923@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21923}: Prevent AttributeError in
distutils.sysconfig.customize_compiler due to possible uninitialized
_config_vars.

@item 
bpo-21323@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21323}: Fix http.server to again handle scripts in CGI subdirectories,
broken by the fix for security bpo-19435@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19435}.  Patch by Zach Byrne.

@item 
bpo-22733@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22733}: Fix ffi_prep_args not zero-extending argument values correctly
on 64-bit Windows.

@item 
bpo-23302@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23302}: Default to TCP_NODELAY=1 upon establishing an HTTPConnection.
Removed use of hard-coded MSS as it's an optimization that's no longer
needed with Nagle disabled.
@end itemize

@node IDLE<51>,Build<64>,Library<81>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id576}@anchor{1355}
@subsubsection IDLE



@itemize -

@item 
bpo-20577@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20577}: Configuration of the max line length for the FormatParagraph
extension has been moved from the General tab of the Idle preferences
dialog to the FormatParagraph tab of the Config Extensions dialog. Patch
by Tal Einat.

@item 
bpo-16893@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16893}: Update Idle doc chapter to match current Idle and add new
information.

@item 
bpo-3068@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3068}: Add Idle extension configuration dialog to Options menu. Changes
are written to HOME/.idlerc/config-extensions.cfg. Original patch by Tal
Einat.

@item 
bpo-16233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16233}: A module browser (File : Class Browser, Alt+C) requires an
editor window with a filename.  When Class Browser is requested otherwise,
from a shell, output window, or 'Untitled' editor, Idle no longer displays
an error box. It now pops up an Open Module box (Alt+M). If a valid name
is entered and a module is opened, a corresponding browser is also opened.

@item 
bpo-4832@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=4832}: Save As to type Python files automatically adds .py to the name
you enter (even if your system does not display it).  Some systems
automatically add .txt when type is Text files.

@item 
bpo-21986@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21986}: Code objects are not normally pickled by the pickle module. To
match this, they are no longer pickled when running under Idle.

@item 
bpo-17390@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17390}: Adjust Editor window title; remove 'Python', move version to
end.

@item 
bpo-14105@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14105}: Idle debugger breakpoints no longer disappear when inserting or
deleting lines.

@item 
bpo-17172@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17172}: Turtledemo can now be run from Idle. Currently, the entry is on
the Help menu, but it may move to Run. Patch by Ramchandra Apt and Lita
Cho.

@item 
bpo-21765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21765}: Add support for non-ascii identifiers to HyperParser.

@item 
bpo-21940@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21940}: Add unittest for WidgetRedirector. Initial patch by Saimadhav
Heblikar.

@item 
bpo-18592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18592}: Add unittest for SearchDialogBase. Patch by Phil Webster.

@item 
bpo-21694@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21694}: Add unittest for ParenMatch. Patch by Saimadhav Heblikar.

@item 
bpo-21686@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21686}: add unittest for HyperParser. Original patch by Saimadhav
Heblikar.

@item 
bpo-12387@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12387}: Add missing upper(lower)case versions of default Windows key
bindings for Idle so Caps Lock does not disable them. Patch by Roger
Serwy.

@item 
bpo-21695@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21695}: Closing a Find-in-files output window while the search is still
in progress no longer closes Idle.

@item 
bpo-18910@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18910}: Add unittest for textView. Patch by Phil Webster.

@item 
bpo-18292@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18292}: Add unittest for AutoExpand. Patch by Saihadhav Heblikar.

@item 
bpo-18409@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18409}: Add unittest for AutoComplete. Patch by Phil Webster.

@item 
bpo-21477@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21477}: htest.py - Improve framework, complete set of tests. Patches by
Saimadhav Heblikar

@item 
bpo-18104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18104}: Add idlelib/idle_test/htest.py with a few sample tests to begin
consolidating and improving human-validated tests of Idle. Change other
files as needed to work with htest.  Running the module as __main__ runs
all tests.

@item 
bpo-21139@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21139}: Change default paragraph width to 72, the 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008}
recommendation.

@item 
bpo-21284@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21284}: Paragraph reformat test passes after user changes reformat
width.

@item 
bpo-17654@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17654}: Ensure IDLE menus are customized properly on OS X for
non-framework builds and for all variants of Tk.

@item 
bpo-23180@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23180}: Rename IDLE "Windows" menu item to "Window". Patch by Al
Sweigart.
@end itemize

@node Build<64>,C API<43>,IDLE<51>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id577}@anchor{1356}
@subsubsection Build



@itemize -

@item 
bpo-15506@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15506}: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the
configure script.

@item 
bpo-22935@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22935}: Allow the ssl module to be compiled if openssl doesn't support
SSL 3.

@item 
bpo-22592@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22592}: Drop support of the Borland C compiler to build Python. The
distutils module still supports it to build extensions.

@item 
bpo-22591@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22591}: Drop support of MS-DOS, especially of the DJGPP compiler
(MS-DOS port of GCC).

@item 
bpo-16537@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16537}: Check whether self.extensions is empty in setup.py. Patch by
Jonathan Hosmer.

@item 
bpo-22359@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22359}: Remove incorrect uses of recursive make.  Patch by Jonas
Wagner.

@item 
bpo-21958@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21958}: Define HAVE_ROUND when building with Visual Studio 2013 and
above.  Patch by Zachary Turner.

@item 
bpo-18093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18093}: the programs that embed the CPython runtime are now in a
separate "Programs" directory, rather than being kept in the Modules
directory.

@item 
bpo-15759@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15759}: "make suspicious", "make linkcheck" and "make doctest" in Doc/
now display special message when and only when there are failures.

@item 
bpo-21141@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21141}: The Windows build process no longer attempts to find Perl,
instead relying on OpenSSL source being configured and ready to build.
The @code{PCbuild\build_ssl.py} script has been re-written and re-named to
@code{PCbuild\prepare_ssl.py}, and takes care of configuring OpenSSL source
for both 32 and 64 bit platforms.  OpenSSL sources obtained from
svn.python.org will always be pre-configured and ready to build.

@item 
bpo-21037@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21037}: Add a build option to enable AddressSanitizer support.

@item 
bpo-19962@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19962}: The Windows build process now creates "python.bat" in the root
of the source tree, which passes all arguments through to the most
recently built interpreter.

@item 
bpo-21285@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21285}: Refactor and fix curses configure check to always search in a
ncursesw directory.

@item 
bpo-15234@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15234}: For BerkeleyDB and Sqlite, only add the found library and
include directories if they aren't already being searched. This avoids an
explicit runtime library dependency.

@item 
bpo-17861@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17861}: Tools/scripts/generate_opcode_h.py automatically regenerates
Include/opcode.h from Lib/opcode.py if the latter gets any change.

@item 
bpo-20644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20644}: OS X installer build support for documentation build changes in
3.4.1: assume externally supplied sphinx-build is available in /usr/bin.

@item 
bpo-20022@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20022}: Eliminate use of deprecated bundlebuilder in OS X builds.

@item 
bpo-15968@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=15968}: Incorporated Tcl, Tk, and Tix builds into the Windows build
solution.

@item 
bpo-17095@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17095}: Fix Modules/Setup @emph{shared} support.

@item 
bpo-21811@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21811}: Anticipated fixes to support OS X versions > 10.9.

@item 
bpo-21166@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21166}: Prevent possible segfaults and other random failures of python
--generate-posix-vars in pybuilddir.txt build target.

@item 
bpo-18096@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18096}: Fix library order returned by python-config.

@item 
bpo-17219@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17219}: Add library build dir for Python extension cross-builds.

@item 
bpo-22919@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22919}: Windows build updated to support VC 14.0 (Visual Studio 2015),
which will be used for the official release.

@item 
bpo-21236@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21236}: Build _msi.pyd with cabinet.lib instead of fci.lib

@item 
bpo-17128@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17128}: Use private version of OpenSSL for OS X 10.5+ installer.
@end itemize

@node C API<43>,Documentation<55>,Build<64>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id578}@anchor{1357}
@subsubsection C API



@itemize -

@item 
bpo-14203@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=14203}: Remove obsolete support for view==NULL in PyBuffer_FillInfo(),
bytearray_getbuffer(), bytesiobuf_getbuffer() and array_buffer_getbuf().
All functions now raise BufferError in that case.

@item 
bpo-22445@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22445}: PyBuffer_IsContiguous() now implements precise contiguity
tests, compatible with NumPy's NPY_RELAXED_STRIDES_CHECKING compilation
flag.  Previously the function reported false negatives for corner cases.

@item 
bpo-22079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22079}: PyType_Ready() now checks that statically allocated type has no
dynamically allocated bases.

@item 
bpo-22453@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22453}: Removed non-documented macro PyObject_REPR().

@item 
bpo-18395@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18395}: Rename @code{_Py_char2wchar()} to @ref{547,,Py_DecodeLocale()},
rename @code{_Py_wchar2char()} to @ref{548,,Py_EncodeLocale()}, and document
these functions.

@item 
bpo-21233@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21233}: Add new C functions: PyMem_RawCalloc(), PyMem_Calloc(),
PyObject_Calloc(), _PyObject_GC_Calloc(). bytes(int) is now using
@code{calloc()} instead of @code{malloc()} for large objects which is faster and
use less memory.

@item 
bpo-20942@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20942}: PyImport_ImportFrozenModuleObject() no longer sets __file__ to
match what importlib does; this affects _frozen_importlib as well as any
module loaded using imp.init_frozen().
@end itemize

@node Documentation<55>,Tests<61>,C API<43>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id579}@anchor{1358}
@subsubsection Documentation



@itemize -

@item 
bpo-19548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19548}: Update the codecs module documentation to better cover the
distinction between text encodings and other codecs, together with other
clarifications. Patch by Martin Panter.

@item 
bpo-22394@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22394}: Doc/Makefile now supports @code{make venv PYTHON=../python} to
create a venv for generating the documentation, e.g., @code{make html
PYTHON=venv/bin/python3}.

@item 
bpo-21514@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21514}: The documentation of the json module now refers to new JSON RFC
7159 instead of obsoleted RFC 4627.

@item 
bpo-21777@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21777}: The binary sequence methods on bytes and bytearray are now
documented explicitly, rather than assuming users will be able to derive
the expected behaviour from the behaviour of the corresponding str
methods.

@item 
bpo-6916@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=6916}: undocument deprecated asynchat.fifo class.

@item 
bpo-17386@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17386}: Expanded functionality of the @code{Doc/make.bat} script to make
it much more comparable to @code{Doc/Makefile}.

@item 
bpo-21312@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21312}: Update the thread_foobar.h template file to include newer
threading APIs. Patch by Jack McCracken.

@item 
bpo-21043@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21043}: Remove the recommendation for specific CA organizations and to
mention the ability to load the OS certificates.

@item 
bpo-20765@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20765}: Add missing documentation for PurePath.with_name() and
PurePath.with_suffix().

@item 
bpo-19407@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19407}: New package installation and distribution guides based on the
Python Packaging Authority tools. Existing guides have been retained as
legacy links from the distutils docs, as they still contain some required
reference material for tool developers that isn't recorded anywhere else.

@item 
bpo-19697@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19697}: Document cases where __main__.__spec__ is None.
@end itemize

@node Tests<61>,Tools/Demos<36>,Documentation<55>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id580}@anchor{1359}
@subsubsection Tests



@itemize -

@item 
bpo-18982@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18982}: Add tests for CLI of the calendar module.

@item 
bpo-19548@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19548}: Added some additional checks to test_codecs to ensure that
statements in the updated documentation remain accurate. Patch by Martin
Panter.

@item 
bpo-22838@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22838}: All test_re tests now work with unittest test discovery.

@item 
bpo-22173@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22173}: Update lib2to3 tests to use unittest test discovery.

@item 
bpo-16000@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16000}: Convert test_curses to use unittest.

@item 
bpo-21456@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21456}: Skip two tests in test_urllib2net.py if _ssl module not
present. Patch by Remi Pointel.

@item 
bpo-20746@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20746}: Fix test_pdb to run in refleak mode (-R).  Patch by Xavier de
Gaye.

@item 
bpo-22060@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22060}: test_ctypes has been somewhat cleaned up and simplified; it now
uses unittest test discovery to find its tests.

@item 
bpo-22104@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22104}: regrtest.py no longer holds a reference to the suite of tests
loaded from test modules that don't define test_main().

@item 
bpo-22111@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22111}: Assorted cleanups in test_imaplib.  Patch by Milan Oberkirch.

@item 
bpo-22002@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22002}: Added @code{load_package_tests} function to test.support and used
it to implement/augment test discovery in test_asyncio, test_email,
test_importlib, test_json, and test_tools.

@item 
bpo-21976@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21976}: Fix test_ssl to accept LibreSSL version strings.  Thanks to
William Orr.

@item 
bpo-21918@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21918}: Converted test_tools from a module to a package containing
separate test files for each tested script.

@item 
bpo-9554@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=9554}: Use modern unittest features in test_argparse. Initial patch by
Denver Coneybeare and Radu Voicilas.

@item 
bpo-20155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20155}: Changed HTTP method names in failing tests in test_httpservers
so that packet filtering software (specifically Windows Base Filtering
Engine) does not interfere with the transaction semantics expected by the
tests.

@item 
bpo-19493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19493}: Refactored the ctypes test package to skip tests explicitly
rather than silently.

@item 
bpo-18492@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18492}: All resources are now allowed when tests are not run by
regrtest.py.

@item 
bpo-21634@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21634}: Fix pystone micro-benchmark: use floor division instead of true
division to benchmark integers instead of floating point numbers. Set
pystone version to 1.2. Patch written by Lennart Regebro.

@item 
bpo-21605@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21605}: Added tests for Tkinter images.

@item 
bpo-21493@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21493}: Added test for ntpath.expanduser().  Original patch by Claudiu
Popa.

@item 
bpo-19925@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=19925}: Added tests for the spwd module. Original patch by Vajrasky
Kok.

@item 
bpo-21522@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21522}: Added Tkinter tests for Listbox.itemconfigure(),
PanedWindow.paneconfigure(), and Menu.entryconfigure().

@item 
bpo-17756@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17756}: Fix test_code test when run from the installed location.

@item 
bpo-17752@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17752}: Fix distutils tests when run from the installed location.

@item 
bpo-18604@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18604}: Consolidated checks for GUI availability.  All platforms now at
least check whether Tk can be instantiated when the GUI resource is
requested.

@item 
bpo-21275@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21275}: Fix a socket test on KFreeBSD.

@item 
bpo-21223@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21223}: Pass test_site/test_startup_imports when some of the extensions
are built as builtins.

@item 
bpo-20635@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20635}: Added tests for Tk geometry managers.

@item 
Add test case for freeze.

@item 
bpo-20743@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20743}: Fix a reference leak in test_tcl.

@item 
bpo-21097@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21097}: Move test_namespace_pkgs into test_importlib.

@item 
bpo-21503@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21503}: Use test_both() consistently in test_importlib.

@item 
bpo-20939@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20939}: Avoid various network test failures due to new redirect of
@indicateurl{http://www.python.org/} to @indicateurl{https://www.python.org}: use
@indicateurl{http://www.example.com} instead.

@item 
bpo-20668@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20668}: asyncio tests no longer rely on tests.txt file. (Patch by
Vajrasky Kok)

@item 
bpo-21093@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21093}: Prevent failures of ctypes test_macholib on OS X if a copy of
libz exists in $HOME/lib or /usr/local/lib.

@item 
bpo-22770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22770}: Prevent some Tk segfaults on OS X when running gui tests.

@item 
bpo-23211@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23211}: Workaround test_logging failure on some OS X 10.6 systems.

@item 
bpo-23345@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23345}: Prevent test_ssl failures with large OpenSSL patch level values
(like 0.9.8zc).
@end itemize

@node Tools/Demos<36>,Windows<56>,Tests<61>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id581}@anchor{135a}
@subsubsection Tools/Demos



@itemize -

@item 
bpo-22314@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22314}: pydoc now works when the LINES environment variable is set.

@item 
bpo-22615@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22615}: Argument Clinic now supports the "type" argument for the int
converter. This permits using the int converter with enums and typedefs.

@item 
bpo-20076@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20076}: The makelocalealias.py script no longer ignores UTF-8 mapping.

@item 
bpo-20079@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20079}: The makelocalealias.py script now can parse the SUPPORTED file
from glibc sources and supports command line options for source paths.

@item 
bpo-22201@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22201}: Command-line interface of the zipfile module now correctly
extracts ZIP files with directory entries.  Patch by Ryan Wilson.

@item 
bpo-22120@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22120}: For functions using an unsigned integer return converter,
Argument Clinic now generates a cast to that type for the comparison to -1
in the generated code.  (This suppresses a compilation warning.)

@item 
bpo-18974@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18974}: Tools/scripts/diff.py now uses argparse instead of optparse.

@item 
bpo-21906@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21906}: Make Tools/scripts/md5sum.py work in Python 3. Patch by Zachary
Ware.

@item 
bpo-21629@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21629}: Fix Argument Clinic's "--converters" feature.

@item 
Add support for @code{yield from} to 2to3.

@item 
Add support for the 
@geindex Python 提高建议; PEP 465
PEP 465@footnote{https://www.python.org/dev/peps/pep-0465} matrix multiplication operator to 2to3.

@item 
bpo-16047@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=16047}: Fix module exception list and __file__ handling in freeze.
Patch by Meador Inge.

@item 
bpo-11824@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=11824}: Consider ABI tags in freeze. Patch by Meador Inge.

@item 
bpo-20535@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=20535}: PYTHONWARNING no longer affects the run_tests.py script. Patch
by Arfrever Frehtes Taifersar Arahesis.
@end itemize

@node Windows<56>,,Tools/Demos<36>,Python 3 5 0 alpha 1
@anchor{whatsnew/changelog id582}@anchor{135b}
@subsubsection Windows



@itemize -

@item 
bpo-23260@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=23260}: Update Windows installer

@item 
The bundled version of Tcl/Tk has been updated to 8.6.3.  The most visible
result of this change is the addition of new native file dialogs when
running on Windows Vista or newer.  See Tcl/Tk's TIP 432 for more
information.  Also, this version of Tcl/Tk includes support for Windows
10.

@item 
bpo-17896@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17896}: The Windows build scripts now expect external library sources
to be in @code{PCbuild\..\externals} rather than @code{PCbuild\..\..}.

@item 
bpo-17717@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17717}: The Windows build scripts now use a copy of NASM pulled from
svn.python.org to build OpenSSL.

@item 
bpo-21907@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21907}: Improved the batch scripts provided for building Python.

@item 
bpo-22644@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22644}: The bundled version of OpenSSL has been updated to 1.0.1j.

@item 
bpo-10747@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=10747}: Use versioned labels in the Windows start menu. Patch by Olive
Kilburn.

@item 
bpo-22980@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=22980}: .pyd files with a version and platform tag (for example,
".cp35-win32.pyd") will now be loaded in preference to those without tags.
@end itemize

@strong{(For information about older versions, consult the HISTORY file.)}

@node Python 教程,安装和使用 Python,Python 有什么新变化？,Top
@anchor{tutorial/index doc}@anchor{135c}@anchor{tutorial/index the-python-tutorial}@anchor{135d}@anchor{tutorial/index tutorial-index}@anchor{135e}
@chapter Python 教程


Python 是一种易于学习又功能强大的编程语言。它提供了高效的高级数据结构，还能简单有效地面向对象编程。Python 优雅的语法和动态类型，以及解释型语言的本质，使它成为多数平台上写脚本和快速开发应用的理想语言。

Python 解释器及丰富的标准库，提供了适用于各个主要系统平台的源码或机器码，这些可以到 Python 官网 @indicateurl{https://www.python.org/} 免费获取，并可自由地分发。许多免费的第三方 Python 模块、程序、工具和它们的文档，也能在这个网站上找到对应内容或链接。

Python 解释器易于扩展，可以使用 C 或 C++（或者其他可以通过 C 调用的语言）扩展新的功能和数据类型。Python 也可用于可定制化软件中的扩展程序语言。

这个教程非正式地介绍了 Python 语言和系统的基本概念和功能。最好在阅读的时候准备一个 Python 解释器进行练习。所有的例子都是相互独立的，所以这个教程也可以离线阅读。

有关标准的对象和模块，请参阅 @ref{135f,,Python 标准库}。@ref{1360,,Python 语言参考手册} 提供了更正式的语言定义。想要编写 C 或者 C++ 扩展可以参考 @ref{1361,,扩展和嵌入 Python 解释器} 和 @ref{1362,,Python/C API 参考手册}。另外还有不少书籍深入讲解 Python。

这个教程并没有完整地介绍每一个功能，甚至可能没有涉及全部的常用功能。这个教程只介绍 Python 中最值得注意的功能，也会让你体会到这个语言的风格特色。学习完这个教程，你将可以阅读和编写 Python 模块和程序，也可以开始学习 @ref{135f,,Python 标准库}。

@ref{1363,,术语对照表} 也很值得一读。

@menu
* 课前甜点:: 
* Python 解释器:: 
* Python 速览:: 
* 其他流程控制工具:: 
* 数据结构:: 
* 模块:: 
* 输入与输出:: 
* 错误和异常:: 
* 类:: 
* 标准库简介:: 
* 标准库简介 —— 第二部分:: 
* 虚拟环境和包:: 
* 接下来？:: 
* 交互式编辑和编辑历史:: 
* 浮点算术：争议和限制:: 
* 附录:: 

@end menu

@node 课前甜点,Python 解释器,,Python 教程
@anchor{tutorial/appetite doc}@anchor{1364}@anchor{tutorial/appetite tut-intro}@anchor{1365}@anchor{tutorial/appetite whetting-your-appetite}@anchor{1366}
@section 课前甜点


如果您的工作主要是用电脑完成的，总有一天您会想能不能自动执行一些任务。比如，对大量文本文件执行查找、替换操作；利用复杂的规则重命名、重排序一堆照片文件；也可能您想编写一个小型数据库、或开发专用的图形界面应用，甚至是开发一个简单的游戏。

专业软件开发人员可能要处理 C/C++/Java 库，但编码、编译、测试、再编译这些开发流程太慢了；也许您正在给这些库开发测试套件，但总觉得这项工作真是枯燥乏味。又或许，您开发了个使用扩展语言的软件，却不想为这个软件专门设计一种新语言。

那么，Python 正好能满足您的需要。

你可以针对这些任务编写 Unix shell 脚本或 Windows 批处理文件，但 shell 脚本擅长的是移动文件和改变文本数据，而不适合编写 GUI 应用或游戏。 你可以编写 C/C++/Java 程序，但即使只完成一个初始版程序也需要耗费很长的开发时间。 Python 则更为简单易用，同时支持 Windows, macOS 和 Unix 操作系统，并能帮助你更快速地完成工作。

Python 虽然简单易用，但它可是真正的编程语言，提供了大量的数据结构，也支持开发大型程序，远超 shell 脚本或批处理文件；Python 提供的错误检查比 C 还多；作为一种“非常高级的语言”，它内置了灵活的数组与字典等高级数据类型。正因为配备了更通用的数据类型，Python 比 Awk，甚至 Perl 能解决更多问题，而且，很多时候，Python 比这些语言更简单。

Python 支持把程序分割为模块，以便在其他 Python 程序中复用。它还内置了大量标准模块，作为开发程序的基础 —— 您还可以把这些模块当作学习 Python 编程的实例。这些模块包括 I/O、系统调用、套接字，甚至还包括 Tk 图形用户界面工作套件。

Python 是一种解释型语言，不需要编译和链接，可以节省大量开发时间。它的解释器实现了交互式操作，轻而易举地就能试用各种语言功能，编写临时程序，或在自底向上的程序开发中测试功能。同时，它还是一个超好用的计算器。

Python 程序简洁、易读，通常比实现同种功能的 C、C++、Java 代码短很多，原因如下：


@itemize *

@item 
高级数据类型允许在单一语句中表述复杂操作；

@item 
使用缩进，而不是括号实现代码块分组；

@item 
无需预声明变量或参数。
@end itemize

Python “可以扩展”：会开发 C 语言程序，就能快速上手为解释器增加新的内置函数或模块，不论是让核心程序以最高速度运行，还是把 Python 程序链接到只提供预编译程序的库（比如，硬件图形库）。只要下点功夫，就能把 Python 解释器和用 C 开发的应用链接在一起，用它来扩展和控制该应用。

顺便提一句，本语言的命名源自 BBC 的 “Monty Python 飞行马戏团”，与爬行动物无关（Python 原义为“蟒蛇”）。欢迎大家在文档中引用 Monty Python 小品短篇集，多多益善！

现在，您已经对 Python 跃跃欲试，想深入了解一些细节了吧。要知道，学习语言的最佳方式是上手实践，建议您边阅读本教程，边在 Python 解释器中练习。

下一章介绍解释器的用法。这部分内容有些单调乏味，但对上手实践后面的例子来说却至关重要。

本教程的其他部分将利用各种示例，介绍 Python 语言、系统的功能，开始只是简单的表达式、语句和数据类型，然后是函数、模块，最后，介绍一些高级概念，如，异常、用户定义的类等功能。

@node Python 解释器,Python 速览,课前甜点,Python 教程
@anchor{tutorial/interpreter doc}@anchor{1367}@anchor{tutorial/interpreter tut-using}@anchor{1368}@anchor{tutorial/interpreter using-the-python-interpreter}@anchor{1369}
@section Python 解释器


@menu
* 调用解释器:: 
* 解释器的运行环境:: 

@end menu

@node 调用解释器,解释器的运行环境,,Python 解释器
@anchor{tutorial/interpreter invoking-the-interpreter}@anchor{136a}@anchor{tutorial/interpreter tut-invoking}@anchor{136b}
@subsection 调用解释器


Python 解释器一般安装在 @code{/usr/local/bin/python3.9} 路径下；将 @code{/usr/local/bin} 加入 Unix 终端的搜索路径，键入以下命令就可以启动 Python：

@example
python3.9
@end example

这样，就可以在 shell 中运行 Python 了 @footnote{@w{(1)} 
Unix 系统中，为了不与同时安装的 Python 2.x 冲突，Python 3.x 解释器默认安装的执行文件名不是 @code{python}。
} 。因为可以选择安装目录，解释器也有可能安装在别的位置；如果还不明白，就去问问身边的 Python 大神或系统管理员。（例如，常见备选路径还有 @code{/usr/local/python}。）

Windows 系统中，从 @ref{136c,,Microsoft Store} 安装 Python 后，就可以使用 @code{python3.9} 命令了。 如果安装了 @ref{a79,,py.exe 启动器}，则可以使用 @code{py} 命令。 请参阅 @ref{136d,,附录：设置环境变量}，了解其他启动 Python 的方式。

在主提示符中，输入文件结束符（Unix 里是 @code{Control-D}，Windows 里是 @code{Control-Z}），就会退出解释器，退出状态码为 0。如果不能退出，还可以输入这个命令：@code{quit()}。

在支持 GNU Readline@footnote{https://tiswww.case.edu/php/chet/readline/rltop.html} 库的系统中，解释器的行编辑功能包括交互式编辑、历史替换、代码补全等。检测是否支持命令行编辑最快速的方式是，在首次出现 Python 提示符时，输入 @code{Control-P}。听到“哔”提示音，说明支持行编辑；请参阅附录 @ref{136e,,交互式编辑和编辑历史}，了解功能键。如果没有反应，或回显了 @code{^P}，则说明不支持行编辑；只能用退格键删除当前行的字符。

解释器的操作方式类似 Unix Shell：用与 tty 设备关联的标准输入调用时，可以交互式地读取和执行命令；以文件名参数，或标准输入文件调用时，则读取并执行文件中的 @emph{脚本}。

启动解释器的另一种方式是 @code{python -c command [arg] ...}，这与 shell 的 @ref{136f,,-c} 选项类似，其中，@emph{command} 需换成要执行的语句。由于 Python 语句经常包含空格等被 shell 特殊对待的字符，一般情况下，建议用单引号标注整个 @emph{command}。

Python 模块也可以当作脚本使用。输入：@code{python -m module [arg] ...}，会执行 @emph{module} 的源文件，这跟在命令行把路径写全了一样。

在交互模式下运行脚本文件，只要在脚本名称参数前，加上选项 @ref{ee9,,-i} 就可以了。

命令行的所有选项详见 @ref{1106,,命令行与环境}。

@menu
* 传入参数:: 
* 交互模式:: 

@end menu

@node 传入参数,交互模式,,调用解释器
@anchor{tutorial/interpreter argument-passing}@anchor{1370}@anchor{tutorial/interpreter tut-argpassing}@anchor{1371}
@subsubsection 传入参数


解释器读取命令行参数，把脚本名与其他参数转化为字符串列表存到 @code{sys} 模块的 @code{argv} 变量里。执行 @code{import sys}，可以导入这个模块，并访问该列表。该列表最少有一个元素；未给定输入参数时，@code{sys.argv[0]} 是空字符串。给定脚本名是 @code{'-'} （标准输入）时，@code{sys.argv[0]} 是 @code{'-'}。使用 @ref{136f,,-c} @emph{command} 时，@code{sys.argv[0]} 是 @code{'-c'}。如果使用选项 @ref{44c,,-m} @emph{module}，@code{sys.argv[0]} 就是包含目录的模块全名。解释器不处理 @ref{136f,,-c} @emph{command} 或 @ref{44c,,-m} @emph{module} 之后的选项，而是直接留在 @code{sys.argv} 中由命令或模块来处理。

@node 交互模式,,传入参数,调用解释器
@anchor{tutorial/interpreter interactive-mode}@anchor{1372}@anchor{tutorial/interpreter tut-interactive}@anchor{9d2}
@subsubsection 交互模式


在终端（tty）输入并执行指令时，解释器在 @emph{交互模式（interactive mode）} 中运行。在这种模式中，会显示 @emph{主提示符}，提示输入下一条指令，主提示符通常用三个大于号（@code{>>>}）表示；输入连续行时，显示 @emph{次要提示符}，默认是三个点（@code{...}）。进入解释器时，首先显示欢迎信息、版本信息、版权声明，然后才是提示符：

@example
$ python3.9
Python 3.9 (default, June 4 2019, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
@end example

@c XXX update for new releases

输入多行架构的语句时，要用连续行。以 @ref{eb3,,if} 为例：

@example
>>> the_world_is_flat = True
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
...
Be careful not to fall off!
@end example

交互模式的内容详见 @ref{1373,,交互模式}。

@node 解释器的运行环境,,调用解释器,Python 解释器
@anchor{tutorial/interpreter the-interpreter-and-its-environment}@anchor{1374}@anchor{tutorial/interpreter tut-interp}@anchor{1375}
@subsection 解释器的运行环境


@menu
* 源文件的字符编码:: 

@end menu

@node 源文件的字符编码,,,解释器的运行环境
@anchor{tutorial/interpreter source-code-encoding}@anchor{1376}@anchor{tutorial/interpreter tut-source-encoding}@anchor{1377}
@subsubsection 源文件的字符编码


默认情况下，Python 源码文件的编码是 UTF-8。这种编码支持世界上大多数语言的字符，可以用于字符串字面值、变量、函数名及注释 —— 尽管标准库只用常规的 ASCII 字符作为变量名或函数名，可移植代码都应遵守此约定。要正确显示这些字符，编辑器必须能识别 UTF-8 编码，而且必须使用支持文件中所有字符的字体。

如果不使用默认编码，则要声明文件的编码，文件的 @emph{第一} 行要写成特殊注释。句法如下：

@example
# -*- coding: encoding -*-
@end example

其中，@emph{encoding} 可以是 Python 支持的任意一种 @ref{1b,,codecs}。

比如，声明使用 Windows-1252 编码，源码文件要写成：

@example
# -*- coding: cp1252 -*-
@end example

@emph{第一行} 的规则也有一种例外情况，源码以 @ref{1378,,UNIX "shebang" 行} 开头。此时，编码声明要写在文件的第二行。例如：

@example
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
@end example

@node Python 速览,其他流程控制工具,Python 解释器,Python 教程
@anchor{tutorial/introduction doc}@anchor{1379}@anchor{tutorial/introduction an-informal-introduction-to-python}@anchor{137a}@anchor{tutorial/introduction tut-informal}@anchor{137b}
@section Python 速览


下面的例子以是否显示提示符（@ref{137c,,>>>} 与 @ref{137d,,...}）区分输入与输出：输入例子中的代码时，要键入以提示符开头的行中提示符后的所有内容；未以提示符开头的行是解释器的输出。注意，例子中的某行出现的第二个提示符是用来结束多行命令的，此时，要键入一个空白行。


@geindex # (hash); comment

本手册中的许多例子，甚至交互式命令都包含注释。Python 注释以 @code{#} 开头，直到该物理行结束。注释可以在行开头，或空白符与代码之后，但不能在字符串里面。字符串中的 # 号就是 # 号。注释用于阐明代码，Python 不解释注释，键入例子时，可以不输入注释。

几个例子：

@example
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
@end example

@menu
* Python 用作计算器:: 
* 走向编程的第一步:: 

@end menu

@node Python 用作计算器,走向编程的第一步,,Python 速览
@anchor{tutorial/introduction tut-calculator}@anchor{137e}@anchor{tutorial/introduction using-python-as-a-calculator}@anchor{137f}
@subsection Python 用作计算器


现在，尝试一些简单的 Python 命令。启动解释器，等待主提示符（@code{>>>} ）出现。

@menu
* 数字:: 
* 字符串:: 
* 列表:: 

@end menu

@node 数字,字符串,,Python 用作计算器
@anchor{tutorial/introduction numbers}@anchor{1380}@anchor{tutorial/introduction tut-numbers}@anchor{1381}
@subsubsection 数字


解释器像一个简单的计算器：输入表达式，就会给出答案。表达式的语法很直接：运算符 @code{+}、@code{-}、@code{*}、@code{/} 的用法和其他大部分语言一样（比如，Pascal 或 C）；括号 (@code{()}) 用来分组。例如：

@example
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
@end example

整数（如，@code{2}、@code{4}、@code{20} ）的类型是 @ref{205,,int}，带小数（如，@code{5.0}、@code{1.6} ）的类型是 @ref{1fe,,float}。本教程后半部分将介绍更多数字类型。

除法运算（@code{/}）返回浮点数。用 @code{//} 运算符执行 @ref{1fa,,floor division} 的结果是整数（忽略小数）；计算余数用 @code{%}：

@example
>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
@end example

Python 用 @code{**} 运算符计算乘方 @footnote{@w{(1)} 
@code{**} 比 @code{-} 的优先级更高, 所以 @code{-3**2} 会被解释成 @code{-(3**2)} ，因此，结果是 @code{-9}。要避免这个问题，并且得到 @code{9}, 可以用 @code{(-3)**2}。
}：

@example
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
@end example

等号（@code{=}）用于给变量赋值。赋值后，下一个交互提示符的位置不显示任何结果：

@example
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
@end example

如果变量未定义（即，未赋值），使用该变量会提示错误：

@example
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
@end example

Python 全面支持浮点数；混合类型运算数的运算会把整数转换为浮点数：

@example
>>> 4 * 3.75 - 1
14.0
@end example

交互模式下，上次输出的表达式会赋给变量 @code{_}。把 Python 当作计算器时，用该变量实现下一步计算更简单，例如：

@example
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
@end example

最好把该变量当作只读类型。不要为它显式赋值，否则会创建一个同名独立局部变量，该变量会用它的魔法行为屏蔽内置变量。

除了 @ref{205,,int} 和 @ref{1fe,,float}，Python 还支持其他数字类型，例如 @ref{2c7,,Decimal} 或 @ref{2c5,,Fraction}。Python 还内置支持 @ref{1382,,复数}，后缀 @code{j} 或 @code{J} 用于表示虚数（例如 @code{3+5j} ）。

@node 字符串,列表,数字,Python 用作计算器
@anchor{tutorial/introduction strings}@anchor{1383}@anchor{tutorial/introduction tut-strings}@anchor{1384}
@subsubsection 字符串


除了数字，Python 还可以操作字符串。字符串有多种表现形式，用单引号（@code{'……'}）或双引号（@code{"……"}）标注的结果相同 @footnote{@w{(2)} 
和其他语言不一样，特殊字符如 @code{\n} 在单引号（@code{'...'}）和双引号（@code{"..."}）里的意义一样。这两种引号唯一的区别是，不需要在单引号里转义双引号 @code{"}，但必须把单引号转义成 @code{\'}，反之亦然。
}。反斜杠 @code{\} 用于转义：

@example
>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
@end example

交互式解释器会为输出的字符串加注引号，特殊字符使用反斜杠转义。虽然，有时输出的字符串看起来与输入的字符串不一样（外加的引号可能会改变），但两个字符串是相同的。如果字符串中有单引号而没有双引号，该字符串外将加注双引号，反之，则加注单引号。@ref{97a,,print()} 函数输出的内容更简洁易读，它会省略两边的引号，并输出转义后的特殊字符：

@example
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.
@end example

如果不希望前置 @code{\} 的字符转义成特殊字符，可以使用 @emph{原始字符串}，在引号前添加 @code{r} 即可：

@example
>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name
@end example

字符串字面值可以包含多行。 一种实现方式是使用三重引号：@code{"""..."""} 或 @code{'@w{'}'...'@w{'}'}。 字符串中将自动包括行结束符，但也可以在换行的地方添加一个 @code{\} 来避免此情况。 参见以下示例：

@example
print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
@end example

输出如下（请注意开始的换行符没有被包括在内）：

@example
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
@end example

字符串可以用 @code{+} 合并（粘到一起），也可以用 @code{*} 重复：

@example
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
@end example

相邻的两个或多个 @emph{字符串字面值} （引号标注的字符）会自动合并：

@example
>>> 'Py' 'thon'
'Python'
@end example

拼接分隔开的长字符串时，这个功能特别实用：

@example
>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
@end example

这项功能只能用于两个字面值，不能用于变量或表达式：

@example
>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
                ^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
                   ^
SyntaxError: invalid syntax
@end example

合并多个变量，或合并变量与字面值，要用 @code{+}：

@example
>>> prefix + 'thon'
'Python'
@end example

字符串支持 @emph{索引} （下标访问），第一个字符的索引是 0。单字符没有专用的类型，就是长度为一的字符串：

@example
>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'
@end example

索引还支持负数，用负数索引时，从右边开始计数：

@example
>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'
@end example

注意，-0 和 0 一样，因此，负数索引从 -1 开始。

除了索引，字符串还支持 @emph{切片}。索引可以提取单个字符，@emph{切片} 则提取子字符串：

@example
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
@end example

切片索引的默认值很有用；省略开始索引时，默认值为 0，省略结束索引时，默认为到字符串的结尾：

@example
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'
@end example

注意，输出结果包含切片开始，但不包含切片结束。因此，@code{s[:i] + s[i:]} 总是等于 @code{s}：

@example
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
@end example

还可以这样理解切片，索引指向的是字符 @emph{之间} ，第一个字符的左侧标为 0，最后一个字符的右侧标为 @emph{n} ，@emph{n} 是字符串长度。例如：

@example
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
@end example

第一行数字是字符串中索引 0...6 的位置，第二行数字是对应的负数索引位置。@emph{i} 到 @emph{j} 的切片由 @emph{i} 和 @emph{j} 之间所有对应的字符组成。

对于使用非负索引的切片，如果两个索引都不越界，切片长度就是起止索引之差。例如， @code{word[1:3]} 的长度是 2。

索引越界会报错：

@example
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
@end example

但是，切片会自动处理越界索引：

@example
>>> word[4:42]
'on'
>>> word[42:]
'@w{'}
@end example

Python 字符串不能修改，是  @ref{1385,,immutable} 的。因此，为字符串中某个索引位置赋值会报错：

@example
>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
@end example

要生成不同的字符串，应新建一个字符串：

@example
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
@end example

内置函数 @ref{292,,len()} 返回字符串的长度：

@example
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
@end example


@subsubheading 参见



@table @asis

@item @ref{1386,,文本序列类型 --- str}

字符串是 @emph{序列类型} ，支持序列类型的各种操作。

@item @ref{1387,,字符串的方法}

字符串支持很多变形与查找方法。

@item @ref{29d,,格式字符串字面值}

内嵌表达式的字符串字面值。

@item @ref{de8,,格式字符串语法}

使用 @ref{5dd,,str.format()} 格式化字符串。

@item @ref{1388,,printf 风格的字符串格式化}

这里详述了用 @code{%} 运算符格式化字符串的操作。
@end table


@node 列表,,字符串,Python 用作计算器
@anchor{tutorial/introduction lists}@anchor{1389}@anchor{tutorial/introduction tut-lists}@anchor{138a}
@subsubsection 列表


Python 支持多种 @emph{复合} 数据类型，可将不同值组合在一起。最常用的 @emph{列表} ，是用方括号标注，逗号分隔的一组值。@emph{列表} 可以包含不同类型的元素，但一般情况下，各个元素的类型相同：

@example
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
@end example

和字符串（及其他内置 @ref{138b,,sequence} 类型）一样，列表也支持索引和切片：

@example
>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]
@end example

切片操作返回包含请求元素的新列表。以下切片操作会返回列表的 @ref{138c,,浅拷贝}：

@example
>>> squares[:]
[1, 4, 9, 16, 25]
@end example

列表还支持合并操作：

@example
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
@end example

与 @ref{1385,,immutable} 字符串不同, 列表是 @ref{138d,,mutable} 类型，其内容可以改变：

@example
>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
@end example

@code{append()} @emph{方法} 可以在列表结尾添加新元素（详见后文）:

@example
>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
@end example

为切片赋值可以改变列表大小，甚至清空整个列表：

@example
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
@end example

内置函数 @ref{292,,len()} 也支持列表：

@example
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
@end example

还可以嵌套列表（创建包含其他列表的列表），例如：

@example
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
@end example

@node 走向编程的第一步,,Python 用作计算器,Python 速览
@anchor{tutorial/introduction first-steps-towards-programming}@anchor{138e}@anchor{tutorial/introduction tut-firststeps}@anchor{138f}
@subsection 走向编程的第一步


当然，Python 还可以完成比二加二更复杂的任务。 例如，可以编写 斐波那契数列@footnote{https://en.wikipedia.org/wiki/Fibonacci_number} 的初始子序列，如下所示：

@example
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8
@end example

本例引入了几个新功能。


@itemize *

@item 
第一行中的 @emph{多重赋值}：变量 @code{a} 和 @code{b} 同时获得新值 0 和 1。最后一行又用了一次多重赋值，这体现在右表达式在赋值前就已经求值了。右表达式求值顺序为从左到右。

@item 
@ref{1390,,while} 循环只要条件（这里指：@code{a < 10}）保持为真就会一直执行。Python 和 C 一样，任何非零整数都为真，零为假。这个条件也可以是字符串或列表的值，事实上，任何序列都可以；长度非零就为真，空序列则为假。示例中的判断只是最简单的比较。比较操作符的标准写法和 C 语言一样： @code{<} （小于）、 @code{>} （大于）、 @code{==} （等于）、 @code{<=} （小于等于)、 @code{>=} （大于等于）及 @code{!=} （不等于）。

@item 
@emph{循环体} 是 @emph{缩进的} ：缩进是 Python 组织语句的方式。在交互式命令行里，得为每个缩输入制表符或空格。使用文本编辑器可以实现更复杂的输入方式；所有像样的文本编辑器都支持自动缩进。交互式输入复合语句时, 要在最后输入空白行表示结束（因为解析器不知道哪一行代码是最后一行）。注意，同一块语句的每一行的缩进相同。

@item 
@ref{97a,,print()} 函数输出给定参数的值。与表达式不同（比如，之前计算器的例子），它能处理多个参数，包括浮点数与字符串。它输出的字符串不带引号，且各参数项之间会插入一个空格，这样可以实现更好的格式化操作：

@example
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
@end example

关键字参数 @emph{end} 可以取消输出后面的换行, 或用另一个字符串结尾：

@example
>>> a, b = 0, 1
>>> while a < 1000:
...     print(a, end=',')
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
@end example
@end itemize

@node 其他流程控制工具,数据结构,Python 速览,Python 教程
@anchor{tutorial/controlflow doc}@anchor{1391}@anchor{tutorial/controlflow more-control-flow-tools}@anchor{1392}@anchor{tutorial/controlflow tut-morecontrol}@anchor{1393}
@section 其他流程控制工具


除了上一章介绍的 @ref{1390,,while} 语句，Python 还支持其他语言中常见的流程控制语句，只是稍有不同。

@menu
* if 语句:: 
* for 语句:: 
* range() 函数: range 函数. 
* 循环中的 break、continue 语句及 else 子句:: 
* pass 语句:: 
* 定义函数:: 
* 函数定义详解:: 
* 小插曲：编码风格:: 

@end menu

@node if 语句,for 语句,,其他流程控制工具
@anchor{tutorial/controlflow if-statements}@anchor{1394}@anchor{tutorial/controlflow tut-if}@anchor{1395}
@subsection @code{if} 语句


最让人耳熟能详的应该是 @ref{eb3,,if} 语句。例如：

@example
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More
@end example

if 语句包含零个或多个 @ref{1396,,elif} 子句，及可选的 @ref{1397,,else} 子句。关键字 '@code{elif}' 是 'else if' 的缩写，适用于避免过多的缩进。可以把 @code{if} ... @code{elif} ... @code{elif} ... 序列看作是其他语言中 @code{switch} 或 @code{case} 语句的替代品。

@node for 语句,range 函数,if 语句,其他流程控制工具
@anchor{tutorial/controlflow for-statements}@anchor{1398}@anchor{tutorial/controlflow tut-for}@anchor{1399}
@subsection @code{for} 语句


@geindex 语句; for

Python 的 @ref{d02,,for} 语句与 C 或 Pascal 中的不同。Python 的 @code{for} 语句不迭代算术递增数值（如 Pascal），或是给予用户定义迭代步骤和暂停条件的能力（如 C），而是迭代列表或字符串等任意序列，元素的迭代顺序与在序列中出现的顺序一致。 例如：

@c One suggestion was to give a real C example here, but that may only serve to
@c confuse non-C programmers.

@example
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
@end example

遍历某个集合的同时修改该集合的内容，很难获取想要的结果。要在遍历时修改集合的内容，应该遍历该集合的副本或创建新的集合：

@example
# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = @{@}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
@end example

@node range 函数,循环中的 break、continue 语句及 else 子句,for 语句,其他流程控制工具
@anchor{tutorial/controlflow the-range-function}@anchor{139a}@anchor{tutorial/controlflow tut-range}@anchor{139b}
@subsection @code{range()} 函数


内置函数 @ref{1f6,,range()} 常用于遍历数字序列，该函数可以生成算术级数：

@example
>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
@end example

生成的序列不包含给定的终止数值；@code{range(10)} 生成 10 个值，这是一个长度为 10 的序列，其中的元素索引都是合法的。range 可以不从 0 开始，还可以按指定幅度递增（递增幅度称为 '步进'，支持负数）：

@example
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
@end example

@ref{1f6,,range()} 和 @ref{292,,len()} 组合在一起，可以按索引迭代序列：

@example
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
@end example

不过，大多数情况下，@ref{eaf,,enumerate()} 函数更便捷，详见 @ref{139c,,循环的技巧} 。

如果只输出 range，会出现意想不到的结果：

@example
>>> range(10)
range(0, 10)
@end example

@ref{1f6,,range()} 返回对象的操作和列表很像，但其实这两种对象不是一回事。迭代时，该对象基于所需序列返回连续项，并没有生成真正的列表，从而节省了空间。

这种对象称为可迭代对象 @ref{c84,,iterable}，函数或程序结构可通过该对象获取连续项，直到所有元素全部迭代完毕。@ref{d02,,for} 语句就是这样的架构，@ref{31d,,sum()} 是一种把可迭代对象作为参数的函数：

@example
>>> sum(range(4))  # 0 + 1 + 2 + 3
6
@end example

下文将介绍更多返回可迭代对象或把可迭代对象当作参数的函数。 在 @ref{139d,,数据结构} 这一章节中，我们将讨论有关 @ref{1f9,,list()} 的更多细节。

@node 循环中的 break、continue 语句及 else 子句,pass 语句,range 函数,其他流程控制工具
@anchor{tutorial/controlflow break-and-continue-statements-and-else-clauses-on-loops}@anchor{139e}@anchor{tutorial/controlflow tut-break}@anchor{139f}
@subsection 循环中的 @code{break}、@code{continue} 语句及 @code{else} 子句


@ref{403,,break} 语句和 C 中的类似，用于跳出最近的 @ref{d02,,for} 或 @ref{1390,,while} 循环。

循环语句支持 @code{else} 子句；@ref{d02,,for} 循环中，可迭代对象中的元素全部循环完毕时，或 @ref{1390,,while} 循环的条件为假时，执行该子句；@ref{403,,break} 语句终止循环时，不执行该子句。 请看下面这个查找素数的循环示例：

@example
>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
@end example

（没错，这段代码就是这么写。仔细看：@code{else} 子句属于 @ref{d02,,for} 循环，@strong{不属于} @ref{eb3,,if} 语句。）

与 @ref{eb3,,if} 语句相比，循环的 @code{else} 子句更像 @ref{e3f,,try} 的 @code{else} 子句： @ref{e3f,,try} 的 @code{else} 子句在未触发异常时执行，循环的 @code{else} 子句则在未运行 @code{break} 时执行。@code{try} 语句和异常详见 @ref{13a0,,处理异常}。

@ref{2c2,,continue} 语句也借鉴自 C 语言，表示继续执行循环的下一次迭代：

@example
>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
@end example

@node pass 语句,定义函数,循环中的 break、continue 语句及 else 子句,其他流程控制工具
@anchor{tutorial/controlflow pass-statements}@anchor{13a1}@anchor{tutorial/controlflow tut-pass}@anchor{13a2}
@subsection @code{pass} 语句


@ref{13a3,,pass} 语句不执行任何操作。语法上需要一个语句，但程序不实际执行任何动作时，可以使用该语句。例如：

@example
>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...
@end example

下面这段代码创建了一个最小的类：

@example
>>> class MyEmptyClass:
...     pass
...
@end example

@ref{13a3,,pass} 还可以用作函数或条件子句的占位符，让开发者聚焦更抽象的层次。此时，程序直接忽略 @code{pass}：

@example
>>> def initlog(*args):
...     pass   # Remember to implement this!
...
@end example

@node 定义函数,函数定义详解,pass 语句,其他流程控制工具
@anchor{tutorial/controlflow defining-functions}@anchor{13a4}@anchor{tutorial/controlflow tut-functions}@anchor{13a5}
@subsection 定义函数


下列代码创建一个可以输出限定数值内的斐波那契数列函数：

@example
>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
@end example

@geindex documentation strings
@geindex docstrings
@geindex strings@comma{} documentation

@emph{定义} 函数使用关键字 @ref{e8b,,def}，后跟函数名与括号内的形参列表。函数语句从下一行开始，并且必须缩进。

函数内的第一条语句是字符串时，该字符串就是文档字符串，也称为 @emph{docstring}，详见 @ref{13a6,,文档字符串}。利用文档字符串可以自动生成在线文档或打印版文档，还可以让开发者在浏览代码时直接查阅文档；Python 开发者最好养成在代码中加入文档字符串的好习惯。

函数在 @emph{执行} 时使用函数局部变量符号表，所有函数变量赋值都存在局部符号表中；引用变量时，首先，在局部符号表里查找变量，然后，是外层函数局部符号表，再是全局符号表，最后是内置名称符号表。因此，尽管可以引用全局变量和外层函数的变量，但最好不要在函数内直接赋值（除非是 @ref{13a7,,global} 语句定义的全局变量，或 @ref{d0f,,nonlocal} 语句定义的外层函数变量）。

在调用函数时会将实际参数（实参）引入到被调用函数的局部符号表中；因此，实参是使用 @emph{按值调用} 来传递的（其中的 @emph{值} 始终是对象的 @emph{引用} 而不是对象的值）。 @footnote{@w{(1)} 
实际上，@emph{对象引用调用} 这种说法更好，因为，传递的是可变对象时，调用者能发现被调者做出的任何更改（插入列表的元素）。
} 当一个函数调用另外一个函数时，会为该调用创建一个新的局部符号表。

函数定义在当前符号表中把函数名与函数对象关联在一起。解释器把函数名指向的对象作为用户自定义函数。还可以使用其他名称指向同一个函数对象，并访问访该函数：

@example
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
@end example

@code{fib} 不返回值，因此，其他语言不把它当作函数，而是当作过程。事实上，没有 @ref{2cf,,return} 语句的函数也返回值，尽管它是一个相当无聊的值。这个值叫 @code{None} （它是一个内置名称）。一般来说，解释器不会输出单独的返回值 @code{None} ，如需查看该值，可以使用 @ref{97a,,print()}：

@example
>>> fib(0)
>>> print(fib(0))
None
@end example

编写不直接输出斐波那契数列运算结果，而是返回运算结果列表的函数也非常简单：

@example
>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
@end example

本例也新引入了一些 Python 功能：


@itemize *

@item 
@ref{2cf,,return} 语句返回函数的值。@code{return} 语句不带表达式参数时，返回 @code{None}。函数执行完毕退出也返回 @code{None}。

@item 
@code{result.append(a)} 语句调用了列表对象 @code{result} 的 @emph{方法} 。方法是“从属于”对象的函数，命名为 @code{obj.methodname}，@code{obj} 是对象（也可以是表达式），@code{methodname} 是对象类型定义的方法名。不同类型定义不同的方法，不同类型的方法名可以相同，且不会引起歧义。（用 @emph{类} 可以自定义对象类型和方法，详见 @ref{13a8,,类} ）示例中的方法 @code{append()} 是为列表对象定义的，用于在列表末尾添加新元素。本例中，该方法相当于 @code{result = result + [a]} ，但更有效。
@end itemize

@node 函数定义详解,小插曲：编码风格,定义函数,其他流程控制工具
@anchor{tutorial/controlflow more-on-defining-functions}@anchor{13a9}@anchor{tutorial/controlflow tut-defining}@anchor{13aa}
@subsection 函数定义详解


函数定义支持可变数量的参数。这里列出三种可以组合使用的形式。

@menu
* 默认值参数:: 
* 关键字参数:: 
* 特殊参数:: 
* 任意实参列表:: 
* 解包实参列表:: 
* Lambda 表达式:: 
* 文档字符串:: 
* 函数注解:: 

@end menu

@node 默认值参数,关键字参数,,函数定义详解
@anchor{tutorial/controlflow default-argument-values}@anchor{13ab}@anchor{tutorial/controlflow tut-defaultargs}@anchor{13ac}
@subsubsection 默认值参数


为参数指定默认值是非常有用的方式。调用函数时，可以使用比定义时更少的参数，例如：

@example
def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)
@end example

该函数可以用以下方式调用：


@itemize *

@item 
只给出必选实参：@code{ask_ok('Do you really want to quit?')}

@item 
给出一个可选实参：@code{ask_ok('OK to overwrite the file?', 2)}

@item 
给出所有实参：@code{ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')}
@end itemize

本例还使用了关键字 @ref{179,,in} ，用于确认序列中是否包含某个值。

默认值在 @emph{定义} 作用域里的函数定义中求值，所以：

@example
i = 5

def f(arg=i):
    print(arg)

i = 6
f()
@end example

上例输出的是 @code{5}。

@strong{重要警告：} 默认值只计算一次。默认值为列表、字典或类实例等可变对象时，会产生与该规则不同的结果。例如，下面的函数会累积后续调用时传递的参数：

@example
def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
@end example

输出结果如下：

@example
[1]
[1, 2]
[1, 2, 3]
@end example

不想在后续调用之间共享默认值时，应以如下方式编写函数：

@example
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
@end example

@node 关键字参数,特殊参数,默认值参数,函数定义详解
@anchor{tutorial/controlflow keyword-arguments}@anchor{13ad}@anchor{tutorial/controlflow tut-keywordargs}@anchor{13ae}
@subsubsection 关键字参数


@code{kwarg=value} 形式的 @ref{6c5,,关键字参数} 也可以用于调用函数。函数示例如下：

@example
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
@end example

该函数接受一个必选参数（@code{voltage}）和三个可选参数（@code{state}, @code{action} 和 @code{type}）。该函数可用下列方式调用：

@example
parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword
@end example

以下调用函数的方式都无效：

@example
parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument
@end example

函数调用时，关键字参数必须跟在位置参数后面。所有传递的关键字参数都必须匹配一个函数接受的参数（比如，@code{actor} 不是函数 @code{parrot} 的有效参数），关键字参数的顺序并不重要。这也包括必选参数，（比如，@code{parrot(voltage=1000)} 也有效）。不能对同一个参数多次赋值，下面就是一个因此限制而失败的例子：

@example
>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'
@end example

最后一个形参为 @code{**name}  形式时，接收一个字典（详见 @ref{417,,映射类型 --- dict}），该字典包含与函数中已定义形参对应之外的所有关键字参数。@code{**name} 形参可以与 @code{*name} 形参（下一小节介绍）组合使用（@code{*name} 必须在 @code{**name} 前面）， @code{*name} 形参接收一个 @ref{13af,,元组}，该元组包含形参列表之外的位置参数。例如，可以定义下面这样的函数：

@example
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])
@end example

该函数可以用如下方式调用：

@example
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
@end example

输出结果如下：

@example
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
@end example

注意，关键字参数在输出结果中的顺序与调用函数时的顺序一致。

@node 特殊参数,任意实参列表,关键字参数,函数定义详解
@anchor{tutorial/controlflow special-parameters}@anchor{13b0}
@subsubsection 特殊参数


默认情况下，参数可以按位置或显式关键字传递给 Python 函数。为了让代码易读、高效，最好限制参数的传递方式，这样，开发者只需查看函数定义，即可确定参数项是仅按位置、按位置或关键字，还是仅按关键字传递。

函数定义如下：

@example
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only
@end example

@code{/} 和 @code{*} 是可选的。这些符号表明形参如何把参数值传递给函数：位置、位置或关键字、关键字。关键字形参也叫作命名形参。

@menu
* 位置或关键字参数:: 
* 仅位置参数:: 
* 仅限关键字参数:: 
* 函数示例:: 
* 小结:: 

@end menu

@node 位置或关键字参数,仅位置参数,,特殊参数
@anchor{tutorial/controlflow positional-or-keyword-arguments}@anchor{13b1}
@subsubsection 位置或关键字参数


函数定义中未使用 @code{/} 和 @code{*} 时，参数可以按位置或关键字传递给函数。

@node 仅位置参数,仅限关键字参数,位置或关键字参数,特殊参数
@anchor{tutorial/controlflow positional-only-parameters}@anchor{13b2}
@subsubsection 仅位置参数


此处再介绍一些细节，特定形参可以标记为 @emph{仅限位置}。@emph{仅限位置} 时，形参的顺序很重要，且这些形参不能用关键字传递。仅限位置形参应放在 @code{/}  （正斜杠）前。@code{/} 用于在逻辑上分割仅限位置形参与其它形参。如果函数定义中没有 @code{/}，则表示没有仅限位置形参。

@code{/} 后可以是 @emph{位置或关键字} 或 @emph{仅限关键字} 形参。

@node 仅限关键字参数,函数示例,仅位置参数,特殊参数
@anchor{tutorial/controlflow keyword-only-arguments}@anchor{13b3}
@subsubsection 仅限关键字参数


把形参标记为 @emph{仅限关键字}，表明必须以关键字参数形式传递该形参，应在参数列表中第一个 @emph{仅限关键字} 形参前添加 @code{*}。

@node 函数示例,小结,仅限关键字参数,特殊参数
@anchor{tutorial/controlflow function-examples}@anchor{13b4}
@subsubsection 函数示例


请看下面的函数定义示例，注意 @code{/} 和 @code{*} 标记：

@example
>>> def standard_arg(arg):
...     print(arg)
...
>>> def pos_only_arg(arg, /):
...     print(arg)
...
>>> def kwd_only_arg(*, arg):
...     print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
...     print(pos_only, standard, kwd_only)
@end example

第一个函数定义 @code{standard_arg} 是最常见的形式，对调用方式没有任何限制，可以按位置也可以按关键字传递参数：

@example
>>> standard_arg(2)
2

>>> standard_arg(arg=2)
2
@end example

第二个函数 @code{pos_only_arg} 的函数定义中有 @code{/}，仅限使用位置形参：

@example
>>> pos_only_arg(1)
1

>>> pos_only_arg(arg=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'
@end example

第三个函数 @code{kwd_only_args} 的函数定义通过 @code{*} 表明仅限关键字参数：

@example
>>> kwd_only_arg(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given

>>> kwd_only_arg(arg=3)
3
@end example

最后一个函数在同一个函数定义中，使用了全部三种调用惯例：

@example
>>> combined_example(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given

>>> combined_example(1, 2, kwd_only=3)
1 2 3

>>> combined_example(1, standard=2, kwd_only=3)
1 2 3

>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'
@end example

下面的函数定义中，@code{kwds} 把 @code{name} 当作键，因此，可能与位置参数 @code{name} 产生潜在冲突：

@example
def foo(name, **kwds):
    return 'name' in kwds
@end example

调用该函数不可能返回 @code{True}，因为关键字 @code{'name'} 总与第一个形参绑定。例如：

@example
>>> foo(1, **@{'name': 2@})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>
@end example

加上 @code{/} （仅限位置参数）后，就可以了。此时，函数定义把 @code{name} 当作位置参数，@code{'name'} 也可以作为关键字参数的键：

@example
def foo(name, /, **kwds):
    return 'name' in kwds
>>> foo(1, **@{'name': 2@})
True
@end example

换句话说，仅限位置形参的名称可以在 @code{**kwds} 中使用，而不产生歧义。

@node 小结,,函数示例,特殊参数
@anchor{tutorial/controlflow recap}@anchor{13b5}
@subsubsection 小结


以下用例决定哪些形参可以用于函数定义：

@example
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
@end example

说明：


@itemize *

@item 
使用仅限位置形参，可以让用户无法使用形参名。形参名没有实际意义时，强制调用函数的实参顺序时，或同时接收位置形参和关键字时，这种方式很有用。

@item 
当形参名有实际意义，且显式名称可以让函数定义更易理解时，阻止用户依赖传递实参的位置时，才使用关键字。

@item 
对于 API，使用仅限位置形参，可以防止未来修改形参名时造成破坏性的 API 变动。
@end itemize

@node 任意实参列表,解包实参列表,特殊参数,函数定义详解
@anchor{tutorial/controlflow arbitrary-argument-lists}@anchor{13b6}@anchor{tutorial/controlflow tut-arbitraryargs}@anchor{13b7}
@subsubsection 任意实参列表


@geindex * (asterisk); in function calls

调用函数时，使用任意数量的实参是最少见的选项。这些实参包含在元组中（详见 @ref{13af,,元组和序列} ）。在可变数量的实参之前，可能有若干个普通参数：

@example
def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))
@end example

@emph{variadic} 参数用于采集传递给函数的所有剩余参数，因此，它们通常在形参列表的末尾。@code{*args} 形参后的任何形式参数只能是仅限关键字参数，即只能用作关键字参数，不能用作位置参数：

@example
>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
@end example

@node 解包实参列表,Lambda 表达式,任意实参列表,函数定义详解
@anchor{tutorial/controlflow tut-unpacking-arguments}@anchor{13b8}@anchor{tutorial/controlflow unpacking-argument-lists}@anchor{13b9}
@subsubsection 解包实参列表


函数调用要求独立的位置参数，但实参在列表或元组里时，要执行相反的操作。例如，内置的 @ref{1f6,,range()} 函数要求独立的 @emph{start} 和 @emph{stop} 实参。如果这些参数不是独立的，则要在调用函数时，用 @code{*} 操作符把实参从列表或元组解包出来：

@example
>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
@end example

@geindex **; in function calls

同样，字典可以用 @code{**} 操作符传递关键字参数：

@example
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = @{"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"@}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
@end example

@node Lambda 表达式,文档字符串,解包实参列表,函数定义详解
@anchor{tutorial/controlflow lambda-expressions}@anchor{13ba}@anchor{tutorial/controlflow tut-lambda}@anchor{13bb}
@subsubsection Lambda 表达式


@ref{d01,,lambda} 关键字用于创建小巧的匿名函数。@code{lambda a, b: a+b} 函数返回两个参数的和。Lambda 函数可用于任何需要函数对象的地方。在语法上，匿名函数只能是单个表达式。在语义上，它只是常规函数定义的语法糖。与嵌套函数定义一样，lambda 函数可以引用包含作用域中的变量：

@example
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
@end example

上例用 lambda 表达式返回函数。还可以把匿名函数用作传递的实参：

@example
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
@end example

@node 文档字符串,函数注解,Lambda 表达式,函数定义详解
@anchor{tutorial/controlflow documentation-strings}@anchor{13bc}@anchor{tutorial/controlflow tut-docstrings}@anchor{13a6}
@subsubsection 文档字符串


@geindex docstrings
@geindex documentation strings
@geindex strings@comma{} documentation

以下是文档字符串内容和格式的约定。

第一行应为对象用途的简短摘要。为保持简洁，不要在这里显式说明对象名或类型，因为可通过其他方式获取这些信息（除非该名称碰巧是描述函数操作的动词）。这一行应以大写字母开头，以句点结尾。

文档字符串为多行时，第二行应为空白行，在视觉上将摘要与其余描述分开。后面的行可包含若干段落，描述对象的调用约定、副作用等。

Python 解析器不会删除 Python 中多行字符串字面值的缩进，因此，文档处理工具应在必要时删除缩进。这项操作遵循以下约定：文档字符串第一行 @emph{之后} 的第一个非空行决定了整个文档字符串的缩进量（第一行通常与字符串开头的引号相邻，其缩进在字符串中并不明显，因此，不能用第一行的缩进），然后，删除字符串中所有行开头处与此缩进“等价”的空白符。不能有比此缩进更少的行，但如果出现了缩进更少的行，应删除这些行的所有前导空白符。转化制表符后（通常为 8 个空格），应测试空白符的等效性。

下面是多行文档字符串的一个例子：

@example
>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.

    No, really, it doesn't do anything.
@end example

@node 函数注解,,文档字符串,函数定义详解
@anchor{tutorial/controlflow function-annotations}@anchor{13bd}@anchor{tutorial/controlflow tut-annotations}@anchor{13be}
@subsubsection 函数注解


@geindex function; annotations
@geindex ->; function annotations
@geindex ; (colon); function annotations

@ref{13bf,,函数注解} 是可选的用户自定义函数类型的元数据完整信息（详见 
@geindex Python 提高建议; PEP 3107
PEP 3107@footnote{https://www.python.org/dev/peps/pep-3107} 和 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} ）。

@ref{13c0,,标注} 以字典的形式存放在函数的 @code{__annotations__} 属性中，并且不会影响函数的任何其他部分。 形参标注的定义方式是在形参名后加冒号，后面跟一个表达式，该表达式会被求值为标注的值。 返回值标注的定义方式是加组合符号 @code{->}，后面跟一个表达式，该标注位于形参列表和表示 @ref{e8b,,def} 语句结束的冒号之间。  下面的示例有一个必须的参数，一个可选的关键字参数以及返回值都带有相应的标注:

@example
>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: @{'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>@}
Arguments: spam eggs
'spam and eggs'
@end example

@node 小插曲：编码风格,,函数定义详解,其他流程控制工具
@anchor{tutorial/controlflow intermezzo-coding-style}@anchor{13c1}@anchor{tutorial/controlflow tut-codingstyle}@anchor{13c2}
@subsection 小插曲：编码风格


@geindex coding; style

现在你将要写更长，更复杂的 Python 代码，是时候讨论一下 @emph{代码风格} 了。 大多数语言都能以不同的风格被编写（或更准确地说，被格式化）；有些比其他的更具有可读性。 能让其他人轻松阅读你的代码总是一个好主意，采用一种好的编码风格对此有很大帮助。

Python 项目大多都遵循 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 的风格指南；它推行的编码风格易于阅读、赏心悦目。Python 开发者均应抽时间悉心研读；以下是该提案中的核心要点：


@itemize *

@item 
缩进，用 4 个空格，不要用制表符。

4 个空格是小缩进（更深嵌套）和大缩进（更易阅读）之间的折中方案。制表符会引起混乱，最好别用。

@item 
换行，一行不超过 79 个字符。

这样换行的小屏阅读体验更好，还便于在大屏显示器上并排阅读多个代码文件。

@item 
用空行分隔函数和类，及函数内较大的代码块。

@item 
最好把注释放到单独一行。

@item 
使用文档字符串。

@item 
运算符前后、逗号后要用空格，但不要直接在括号内使用： @code{a = f(1, 2) + g(3, 4)}。

@item 
类和函数的命名要一致；按惯例，命名类用 @code{UpperCamelCase}，命名函数与方法用 @code{lowercase_with_underscores}。命名方法中第一个参数总是用 @code{self} (类和方法详见 @ref{13c3,,初探类})。

@item 
编写用于国际多语环境的代码时，不要用生僻的编码。Python 默认的 UTF-8 或纯 ASCII 可以胜任各种情况。

@item 
同理，就算多语阅读、维护代码的可能再小，也不要在标识符中使用非 ASCII 字符。
@end itemize

@node 数据结构,模块,其他流程控制工具,Python 教程
@anchor{tutorial/datastructures doc}@anchor{13c4}@anchor{tutorial/datastructures data-structures}@anchor{13c5}@anchor{tutorial/datastructures tut-structures}@anchor{139d}
@section 数据结构


本章深入讲解之前学过的一些内容，同时，还增加了新的知识点。

@menu
* 列表详解:: 
* del 语句:: 
* 元组和序列:: 
* 集合:: 
* 字典:: 
* 循环的技巧:: 
* 深入条件控制:: 
* 序列和其他类型的比较:: 

@end menu

@node 列表详解,del 语句,,数据结构
@anchor{tutorial/datastructures more-on-lists}@anchor{13c6}@anchor{tutorial/datastructures tut-morelists}@anchor{13c7}
@subsection 列表详解


列表数据类型支持很多方法，列表对象的所有方法所示如下：


@deffn {方法} list.append (x)

在列表末尾添加一个元素，相当于 @code{a[len(a):] = [x]} 。
@end deffn


@deffn {方法} list.extend (iterable)

用可迭代对象的元素扩展列表。相当于  @code{a[len(a):] = iterable} 。
@end deffn


@deffn {方法} list.insert (i, x)

在指定位置插入元素。第一个参数是插入元素的索引，因此，@code{a.insert(0, x)} 在列表开头插入元素， @code{a.insert(len(a), x)} 等同于 @code{a.append(x)} 。
@end deffn


@deffn {方法} list.remove (x)

从列表中删除第一个值为 @emph{x} 的元素。未找到指定元素时，触发 @ref{16d,,ValueError} 异常。
@end deffn


@deffn {方法} list.pop ([i])

删除列表中指定位置的元素，并返回被删除的元素。未指定位置时，@code{a.pop()} 删除并返回列表的最后一个元素。（方法签名中 @emph{i} 两边的方括号表示该参数是可选的，不是要求输入方括号。这种表示法常见于 Python 参考库）。
@end deffn


@deffn {方法} list.clear ()

删除列表里的所有元素，相当于 @code{del a[:]} 。
@end deffn


@deffn {方法} list.index (x[, start[, end]])

返回列表中第一个值为 @emph{x} 的元素的零基索引。未找到指定元素时，触发 @ref{16d,,ValueError} 异常。

可选参数 @emph{start} 和 @emph{end} 是切片符号，用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的，而不是 @emph{start} 参数。
@end deffn


@deffn {方法} list.count (x)

返回列表中元素 @emph{x} 出现的次数。
@end deffn


@deffn {方法} list.sort (*, key=None, reverse=False)

就地排序列表中的元素（要了解自定义排序参数，详见 @ref{54f,,sorted()}）。
@end deffn


@deffn {方法} list.reverse ()

反转列表中的元素。
@end deffn


@deffn {方法} list.copy ()

返回列表的浅拷贝。相当于 @code{a[:]}  。
@end deffn

列表方法示例：

@example
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
@end example

@code{insert}、@code{remove}、@code{sort} 等方法只修改列表，不输出返回值——返回的默认值为 @code{None} 。@footnote{@w{(1)} 
别的语言可能会返回可变对象，允许方法连续执行，例如，@code{d->insert("a")->remove("b")->sort();}。
} 这是所有 Python 可变数据结构的设计原则。

还有，不是所有数据都可以排序或比较。例如，@code{[None, 'hello', 10]} 就不可排序，因为整数不能与字符串对比，而 @emph{None} 不能与其他类型对比。有些类型根本就没有定义顺序关系，例如，@code{3+4j < 5+7j} 这种对比操作就是无效的。

@menu
* 用列表实现堆栈:: 
* 用列表实现队列:: 
* 列表推导式: 列表推导式<2>. 
* 嵌套的列表推导式:: 

@end menu

@node 用列表实现堆栈,用列表实现队列,,列表详解
@anchor{tutorial/datastructures tut-lists-as-stacks}@anchor{13c8}@anchor{tutorial/datastructures using-lists-as-stacks}@anchor{13c9}
@subsubsection 用列表实现堆栈


使用列表方法实现堆栈非常容易，最后插入的最先取出（“后进先出”）。把元素添加到堆栈的顶端，使用 @code{append()} 。从堆栈顶部取出元素，使用 @code{pop()} ，不用指定索引。例如：

@example
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
@end example

@node 用列表实现队列,列表推导式<2>,用列表实现堆栈,列表详解
@anchor{tutorial/datastructures tut-lists-as-queues}@anchor{13ca}@anchor{tutorial/datastructures using-lists-as-queues}@anchor{13cb}
@subsubsection 用列表实现队列


列表也可以用作队列，最先加入的元素，最先取出（“先进先出”）；然而，列表作为队列的效率很低。因为，在列表末尾添加和删除元素非常快，但在列表开头插入或移除元素却很慢（因为所有其他元素都必须移动一位）。

实现队列最好用 @ref{633,,collections.deque}，可以快速从两端添加或删除元素。例如：

@example
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
@end example

@node 列表推导式<2>,嵌套的列表推导式,用列表实现队列,列表详解
@anchor{tutorial/datastructures list-comprehensions}@anchor{13cc}@anchor{tutorial/datastructures tut-listcomps}@anchor{13cd}
@subsubsection 列表推导式


列表推导式创建列表的方式更简洁。常见的用法为，对序列或可迭代对象中的每个元素应用某种操作，用生成的结果创建新的列表；或用满足特定条件的元素创建子序列。

例如，创建平方值的列表：

@example
>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@end example

注意，这段代码创建（或覆盖）变量 @code{x}，该变量在循环结束后仍然存在。下述方法可以无副作用地计算平方列表：

@example
squares = list(map(lambda x: x**2, range(10)))
@end example

或等价于：

@example
squares = [x**2 for x in range(10)]
@end example

上面这种写法更简洁、易读。

列表推导式的方括号内包含以下内容：一个表达式，后面为一个 @code{for} 子句，然后，是零个或多个 @code{for} 或 @code{if} 子句。结果是由表达式依据 @code{for} 和 @code{if} 子句求值计算而得出一个新列表。 举例来说，以下列表推导式将两个列表中不相等的元素组合起来：

@example
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
@end example

等价于：

@example
>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
@end example

注意，上面两段代码中，@ref{d02,,for} 和 @ref{eb3,,if} 的顺序相同。

表达式是元组（例如上例的 @code{(x, y)}）时，必须加上括号：

@example
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in <module>
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

列表推导式可以使用复杂的表达式和嵌套函数：

@example
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
@end example

@node 嵌套的列表推导式,,列表推导式<2>,列表详解
@anchor{tutorial/datastructures nested-list-comprehensions}@anchor{13ce}
@subsubsection 嵌套的列表推导式


列表推导式中的初始表达式可以是任何表达式，甚至可以是另一个列表推导式。

下面这个 3x4 矩阵，由 3 个长度为 4 的列表组成：

@example
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
@end example

下面的列表推导式可以转置行列：

@example
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

如上节所示，嵌套的列表推导式基于其后的 @ref{d02,,for} 求值，所以这个例子等价于：

@example
>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

反过来说，也等价于：

@example
>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
@end example

实际应用中，最好用内置函数替代复杂的流程语句。此时，@ref{d04,,zip()} 函数更好用：

@example
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
@end example

关于本行中星号的详细说明，参见 @ref{13b8,,解包实参列表}。

@node del 语句,元组和序列,列表详解,数据结构
@anchor{tutorial/datastructures the-del-statement}@anchor{13cf}@anchor{tutorial/datastructures tut-del}@anchor{13d0}
@subsection @code{del} 语句


@ref{13d1,,del} 语句按索引，而不是值从列表中移除元素。与返回值的 @code{pop()} 方法不同， @code{del} 语句也可以从列表中移除切片，或清空整个列表（之前是将空列表赋值给切片）。 例如：

@example
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
@end example

@ref{13d1,,del} 也可以用来删除整个变量：

@example
>>> del a
@end example

此后，再引用 @code{a} 就会报错（直到为它赋与另一个值）。后文会介绍 @ref{13d1,,del} 的其他用法。

@node 元组和序列,集合,del 语句,数据结构
@anchor{tutorial/datastructures tuples-and-sequences}@anchor{13d2}@anchor{tutorial/datastructures tut-tuples}@anchor{13af}
@subsection 元组和序列


列表和字符串有很多共性，例如，索引和切片操作。这两种数据类型是 @emph{序列} （参见 @ref{13d3,,序列类型 --- list@comma{} tuple@comma{} range}）。随着 Python 语言的发展，其他的序列类型也被加入其中。本节介绍另一种标准序列类型：@emph{元组}。

元组由多个用逗号隔开的值组成，例如：

@example
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
@end example

输出时，元组都要由圆括号标注，这样才能正确地解释嵌套元组。输入时，圆括号可有可无，不过经常是必须的（如果元组是更大的表达式的一部分）。不允许为元组中的单个元素赋值，当然，可以创建含列表等可变对象的元组。

虽然，元组与列表很像，但使用场景不同，用途也不同。元组是 @ref{1385,,immutable} （不可变的），一般可包含异质元素序列，通过解包（见本节下文）或索引访问（如果是 @ref{1a1,,namedtuples}，可以属性访问）。列表是 @ref{138d,,mutable} （可变的），列表元素一般为同质类型，可迭代访问。

构造 0 个或 1 个元素的元组比较特殊：为了适应这种情况，对句法有一些额外的改变。用一对空圆括号就可以创建空元组；只有一个元素的元组可以通过在这个元素后添加逗号来构建（圆括号里只有一个值的话不够明确）。丑陋，但是有效。例如：

@example
>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
@end example

语句 @code{t = 12345, 54321, 'hello!'} 是 @emph{元组打包} 的例子：值 @code{12345}, @code{54321} 和 @code{'hello!'} 一起被打包进元组。逆操作也可以：

@example
>>> x, y, z = t
@end example

称之为 @emph{序列解包}  也是妥妥的，适用于右侧的任何序列。序列解包时，左侧变量与右侧序列元素的数量应相等。注意，多重赋值其实只是元组打包和序列解包的组合。

@node 集合,字典,元组和序列,数据结构
@anchor{tutorial/datastructures sets}@anchor{13d4}@anchor{tutorial/datastructures tut-sets}@anchor{13d5}
@subsection 集合


Python 还支持 @emph{集合} 这种数据类型。集合是由不重复元素组成的无序容器。基本用法包括成员检测、消除重复元素。集合对象支持合集、交集、差集、对称差分等数学运算。

创建集合用花括号或 @ref{1f7,,set()} 函数。注意，创建空集合只能用 @code{set()}，不能用 @code{@{@}}，@code{@{@}} 创建的是空字典，下一小节介绍数据结构：字典。

以下是一些简单的示例：

@example
>>> basket = @{'apple', 'orange', 'apple', 'pear', 'orange', 'banana'@}
>>> print(basket)                      # show that duplicates have been removed
@{'orange', 'banana', 'pear', 'apple'@}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
@{'a', 'r', 'b', 'c', 'd'@}
>>> a - b                              # letters in a but not in b
@{'r', 'd', 'b'@}
>>> a | b                              # letters in a or b or both
@{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'@}
>>> a & b                              # letters in both a and b
@{'a', 'c'@}
>>> a ^ b                              # letters in a or b but not both
@{'r', 'd', 'b', 'm', 'z', 'l'@}
@end example

与 @ref{13cd,,列表推导式} 类似，集合也支持推导式：

@example
>>> a = @{x for x in 'abracadabra' if x not in 'abc'@}
>>> a
@{'r', 'd'@}
@end example

@node 字典,循环的技巧,集合,数据结构
@anchor{tutorial/datastructures dictionaries}@anchor{13d6}@anchor{tutorial/datastructures tut-dictionaries}@anchor{13d7}
@subsection 字典


@emph{字典} （参见 @ref{417,,映射类型 --- dict}） 也是一种常用的 Python 內置数据类型。其他语言可能把字典称为 @emph{联合内存} 或 @emph{联合数组}。与以连续整数为索引的序列不同，字典以 @emph{关键字} 为索引，关键字通常是字符串或数字，也可以是其他任意不可变类型。只包含字符串、数字、元组的元组，也可以用作关键字。但如果元组直接或间接地包含了可变对象，就不能用作关键字。列表不能当关键字，因为列表可以用索引、切片、@code{append()} 、@code{extend()} 等方法修改。

可以把字典理解为 @emph{键值对} 的集合，但字典的键必须是唯一的。花括号 @code{@{@}} 用于创建空字典。另一种初始化字典的方式是，在花括号里输入逗号分隔的键值对，这也是字典的输出方式。

字典的主要用途是通过关键字存储、提取值。用 @code{del} 可以删除键值对。用已存在的关键字存储值，与该关键字关联的旧值会被取代。通过不存在的键提取值，则会报错。

对字典执行 @code{list(d)} 操作，返回该字典中所有键的列表，按插入次序排列（如需排序，请使用 @code{sorted(d)}）。检查字典里是否存在某个键，使用关键字 @ref{179,,in}。

以下是一些字典的简单示例：

@example
>>> tel = @{'jack': 4098, 'sape': 4139@}
>>> tel['guido'] = 4127
>>> tel
@{'jack': 4098, 'sape': 4139, 'guido': 4127@}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
@{'jack': 4098, 'guido': 4127, 'irv': 4127@}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
@end example

@ref{164,,dict()} 构造函数可以直接用键值对序列创建字典：

@example
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
@{'sape': 4139, 'guido': 4127, 'jack': 4098@}
@end example

字典推导式可以用任意键值表达式创建字典：

@example
>>> @{x: x**2 for x in (2, 4, 6)@}
@{2: 4, 4: 16, 6: 36@}
@end example

关键字是比较简单的字符串时，直接用关键字参数指定键值对更便捷：

@example
>>> dict(sape=4139, guido=4127, jack=4098)
@{'sape': 4139, 'guido': 4127, 'jack': 4098@}
@end example

@node 循环的技巧,深入条件控制,字典,数据结构
@anchor{tutorial/datastructures looping-techniques}@anchor{13d8}@anchor{tutorial/datastructures tut-loopidioms}@anchor{139c}
@subsection 循环的技巧


在字典中循环时，用 @code{items()} 方法可同时取出键和对应的值：

@example
>>> knights = @{'gallahad': 'the pure', 'robin': 'the brave'@}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
@end example

在序列中循环时，用 @ref{eaf,,enumerate()} 函数可以同时取出位置索引和对应的值：

@example
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe
@end example

同时循环两个或多个序列时，用 @ref{d04,,zip()} 函数可以将其内的元素一一匹配：

@example
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your @{0@}?  It is @{1@}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
@end example

逆向循环序列时，先正向定位序列，然后调用 @ref{2cd,,reversed()} 函数：

@example
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1
@end example

按指定顺序循环序列，可以用 @ref{54f,,sorted()} 函数，在不改动原序列的基础上，返回一个重新的序列：

@example
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
...     print(i)
...
apple
apple
banana
orange
orange
pear
@end example

使用 @ref{1f7,,set()} 去除序列中的重复元素。使用 @ref{54f,,sorted()} 加 @ref{1f7,,set()} 则按排序后的顺序，循环遍历序列中的唯一元素：

@example
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
@end example

一般来说，在循环中修改列表的内容时，创建新列表比较简单，且安全：

@example
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
@end example

@node 深入条件控制,序列和其他类型的比较,循环的技巧,数据结构
@anchor{tutorial/datastructures more-on-conditions}@anchor{13d9}@anchor{tutorial/datastructures tut-conditions}@anchor{13da}
@subsection 深入条件控制


@code{while} 和 @code{if} 条件句不只可以进行比较，还可以使用任意运算符。

比较运算符 @code{in} 和 @code{not in} 校验序列里是否存在某个值。运算符 @code{is} 和 @code{is not} 比较两个对象是否为同一个对象。所有比较运算符的优先级都一样，且低于数值运算符。

比较操作支持链式操作。例如，@code{a < b == c} 校验 @code{a} 是否小于 @code{b}，且 @code{b} 是否等于 @code{c}。

比较操作可以用布尔运算符 @code{and} 和 @code{or} 组合，并且，比较操作（或其他布尔运算）的结果都可以用 @code{not} 取反。这些操作符的优先级低于比较操作符；@code{not} 的优先级最高， @code{or} 的优先级最低，因此，@code{A and not B or C} 等价于 @code{(A and (not B)) or C}。与其他运算符操作一样，此处也可以用圆括号表示想要的组合。

布尔运算符 @code{and} 和 @code{or} 也称为 @emph{短路} 运算符：其参数从左至右解析，一旦可以确定结果，解析就会停止。例如，如果 @code{A} 和 @code{C} 为真，@code{B} 为假，那么 @code{A and B and C} 不会解析 @code{C}。用作普通值而不是布尔值时，短路操作符返回的值通常是最后一个变量。

还可以把比较操作或逻辑表达式的结果赋值给变量，例如：

@example
>>> string1, string2, string3 = '@w{'}, 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
@end example

注意，Python 与 C 不同，在表达式内部赋值必须显式使用 @ref{13db,,海象运算符} @code{:=}。 这避免了 C 程序中常见的问题：要在表达式中写 @code{==} 时，却写成了 @code{=}。

@node 序列和其他类型的比较,,深入条件控制,数据结构
@anchor{tutorial/datastructures comparing-sequences-and-other-types}@anchor{13dc}@anchor{tutorial/datastructures tut-comparing}@anchor{13dd}
@subsection 序列和其他类型的比较


序列对象可以与相同序列类型的其他对象比较。这种比较使用 @emph{字典式} 顺序：首先，比较前两个对应元素，如果不相等，则可确定比较结果；如果相等，则比较之后的两个元素，以此类推，直到其中一个序列结束。如果要比较的两个元素本身是相同类型的序列，则递归地执行字典式顺序比较。如果两个序列中所有的对应元素都相等，则两个序列相等。如果一个序列是另一个的初始子序列，则较短的序列可被视为较小（较少）的序列。 对于字符串来说，字典式顺序使用 Unicode 码位序号排序单个字符。下面列出了一些比较相同类型序列的例子：

@example
(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
@end example

注意，对不同类型的对象来说，只要待比较的对象提供了合适的比较方法，就可以使用 @code{<} 和 @code{>} 进行比较。例如，混合数值类型通过数值进行比较，所以，0 等于 0.0，等等。否则，解释器不会随便给出一个对比结果，而是触发 @ref{1ff,,TypeError} 异常。

@node 模块,输入与输出,数据结构,Python 教程
@anchor{tutorial/modules doc}@anchor{13de}@anchor{tutorial/modules modules}@anchor{13df}@anchor{tutorial/modules tut-modules}@anchor{13e0}
@section 模块


退出 Python 解释器后，再次进入时，之前在 Python 解释器中定义的函数和变量就丢失了。因此，编写较长程序时，建议用文本编辑器代替解释器，执行文件中的输入内容，这就是编写 @emph{脚本} 。随着程序越来越长，为了方便维护，最好把脚本拆分成多个文件。编写脚本还一个好处，不同程序调用同一个函数时，不用每次把函数复制到各个程序。

为实现这些需求，Python 把各种定义存入一个文件，在脚本或解释器的交互式实例中使用。这个文件就是 @emph{模块} ；模块中的定义可以 @emph{导入} 到其他模块或 @emph{主} 模块（在顶层和计算器模式下，执行脚本中可访问的变量集）。

模块是包含 Python 定义和语句的文件。其文件名是模块名加后缀名 @code{.py} 。在模块内部，通过全局变量 @code{__name__} 可以获取模块名（即字符串）。例如，用文本编辑器在当前目录下创建 @code{fibo.py} 文件，输入以下内容：

@example
# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result
@end example

现在，进入 Python 解释器，用以下命令导入该模块：

@example
>>> import fibo
@end example

这项操作不直接把 @code{fibo} 函数定义的名称导入到当前符号表，只导入模块名 @code{fibo} 。要使用模块名访问函数：

@example
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
@end example

如果经常使用某个函数，可以把它赋值给局部变量：

@example
>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

@menu
* 模块详解:: 
* 标准模块:: 
* dir() 函数: dir 函数. 
* 包:: 

@end menu

@node 模块详解,标准模块,,模块
@anchor{tutorial/modules more-on-modules}@anchor{13e1}@anchor{tutorial/modules tut-moremodules}@anchor{13e2}
@subsection 模块详解


模块包含可执行语句及函数定义。这些语句用于初始化模块，且仅在 import 语句 @emph{第一次} 遇到模块名时执行。@footnote{@w{(1)} 
实际上，函数定义也是“可执行”的“语句”；执行模块级函数定义时，函数名将被导入到模块的全局符号表。
} (文件作为脚本运行时，也会执行这些语句。)

模块有自己的私有符号表，用作模块中所有函数的全局符号表。因此，在模块内使用全局变量时，不用担心与用户定义的全局变量发生冲突。另一方面，可以用与访问模块函数一样的标记法，访问模块的全局变量，@code{modname.itemname}。

可以把其他模块导入模块。 按惯例，所有 @ref{cef,,import} 语句都放在模块（或脚本）开头，但这不是必须的。 被导入的模块名存在导入方模块的全局符号表里。

@ref{cef,,import} 语句有一个变体，可以直接把模块里的名称导入到另一个模块的符号表。例如：

@example
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

这段代码不会把模块名导入到局部符号表里（因此，本例没有定义 @code{fibo}）。

还有一种变体可以导入模块内定义的所有名称：

@example
>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

这种方式会导入所有不以下划线（@code{_}）开头的名称。大多数情况下，不要用这个功能，这种方式向解释器导入了一批未知的名称，可能会覆盖已经定义的名称。

注意，一般情况下，不建议从模块或包内导入 @code{*}， 因为，这项操作经常让代码变得难以理解。不过，为了在交互式编译器中少打几个字，这么用也没问题。

模块名后使用 @code{as} 时，直接把 @code{as} 后的名称与导入模块绑定。

@example
>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

与 @code{import fibo} 一样，这种方式也可以有效地导入模块，唯一的区别是，导入的名称是 @code{fib}。

@ref{d15,,from} 中也可以使用这种方式，效果类似：

@example
>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
@end example

@cartouche
@quotation 注解 
为了保证运行效率，每次解释器会话只导入一次模块。如果更改了模块内容，必须重启解释器；仅交互测试一个模块时，也可以使用 @ref{4a8,,importlib.reload()}，例如 @code{import importlib; importlib.reload(modulename)}。
@end quotation
@end cartouche

@menu
* 以脚本方式执行模块:: 
* 模块搜索路径:: 
* “已编译的” Python 文件:: 

@end menu

@node 以脚本方式执行模块,模块搜索路径,,模块详解
@anchor{tutorial/modules executing-modules-as-scripts}@anchor{13e3}@anchor{tutorial/modules tut-modulesasscripts}@anchor{13e4}
@subsubsection 以脚本方式执行模块


可以用以下方式运行 Python 模块：

@example
python fibo.py <arguments>
@end example

这项操作将执行模块里的代码，和导入模块一样，但会把 @code{__name__} 赋值为 @code{"__main__"}。 也就是把下列代码添加到模块末尾：

@example
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
@end example

既可以把这个文件当脚本使用，也可以用作导入的模块， 因为，解析命令行的代码只有在模块以 “main” 文件执行时才会运行：

@example
$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
@end example

导入模块时，不运行这些代码：

@example
>>> import fibo
>>>
@end example

这种操作常用于为模块提供便捷用户接口，或用于测试（把模块当作执行测试套件的脚本运行）。

@node 模块搜索路径,“已编译的” Python 文件,以脚本方式执行模块,模块详解
@anchor{tutorial/modules the-module-search-path}@anchor{13e5}@anchor{tutorial/modules tut-searchpath}@anchor{13e6}
@subsubsection 模块搜索路径


@geindex module; search; path

当一个名为 @code{spam} 的模块被导入时，解释器首先搜索具有该名称的内置模块。这些模块的名字被列在 @ref{13e7,,sys.builtin_module_names} 中。如果没有找到，它就在变量 @ref{262,,sys.path} 给出的目录列表中搜索一个名为 @code{spam.py} 的文件， @ref{262,,sys.path} 从这些位置初始化:


@itemize *

@item 
输入脚本的目录（或未指定文件时的当前目录）。

@item 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} （目录列表，与 shell 变量 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 的语法一样）。

@item 
依赖于安装的默认值（按照惯例包括一个 @code{site-packages} 目录，由 @ref{eb,,site} 模块处理）。
@end itemize

@cartouche
@quotation 注解 
在支持 symlink 的文件系统中，输入脚本目录是在追加 symlink 后计算出来的。换句话说，包含 symlink 的目录并 @strong{没有} 添加至模块搜索路径。
@end quotation
@end cartouche

初始化后，Python 程序可以更改 @ref{262,,sys.path}。运行脚本的目录在标准库路径之前，置于搜索路径的开头。即，加载的是该目录里的脚本，而不是标准库的同名模块。 除非刻意替换，否则会报错。详见 @ref{13e8,,标准模块}。

@c %
@c Do we need stuff on zip files etc. ? DUBOIS

@node “已编译的” Python 文件,,模块搜索路径,模块详解
@anchor{tutorial/modules compiled-python-files}@anchor{13e9}
@subsubsection “已编译的” Python 文件


为了快速加载模块，Python 把模块的编译版缓存在 @code{__pycache__} 目录中，文件名为 @code{module.@emph{version}.pyc}，version 对编译文件格式进行编码，一般是 Python 的版本号。例如，CPython 的 3.3 发行版中，spam.py 的编译版本缓存为 @code{__pycache__/spam.cpython-33.pyc}。使用这种命名惯例，可以让不同 Python 发行版及不同版本的已编译模块共存。

Python 对比编译版本与源码的修改日期，查看它是否已过期，是否要重新编译，此过程完全自动化。此外，编译模块与平台无关，因此，可在不同架构系统之间共享相同的支持库。

Python 在两种情况下不检查缓存。其一，从命令行直接载入模块，只重新编译，不存储编译结果；其二，没有源模块，就不会检查缓存。为了支持无源文件（仅编译）发行版本， 编译模块必须在源目录下，并且绝不能有源模块。

给专业人士的一些小建议：


@itemize *

@item 
在 Python 命令中使用 @ref{788,,-O} 或 @ref{789,,-OO} 开关，可以减小编译模块的大小。@code{-O} 去除断言语句，@code{-OO} 去除断言语句和 __doc__ 字符串。有些程序可能依赖于这些内容，因此，没有十足的把握，不要使用这两个选项。“优化过的”模块带有 @code{opt-} 标签，并且文件通常会一小些。将来的发行版或许会改进优化的效果。

@item 
从 @code{.pyc} 文件读取的程序不比从 @code{.py} 读取的执行速度快，@code{.pyc} 文件只是加载速度更快。

@item 
@ref{20,,compileall} 模块可以为一个目录下的所有模块创建 .pyc 文件。

@item 
本过程的细节及决策流程图，详见 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}。
@end itemize

@node 标准模块,dir 函数,模块详解,模块
@anchor{tutorial/modules standard-modules}@anchor{13ea}@anchor{tutorial/modules tut-standardmodules}@anchor{13e8}
@subsection 标准模块


@geindex 模块; sys

Python 附带了标准模块库，详见 Python 标准库参考手册（以下简称为“库参考”）。解释器中内置了一些模块，用于访问不属于语言核心的内置操作，其目的主要是为了提高运行效率，或访问系统调用等操作系统原语。这些模块的集合是依赖于底层平台的配置选项。例如，@ref{133,,winreg} 模块仅供 Windows 使用。特别要注意内嵌到 Python 解释器中的模块 @ref{fd,,sys}。变量 @code{sys.ps1} 和 @code{sys.ps2} 则用来定义主次提示的字符串：

@example
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>
@end example

只有解释器用于交互模式时，才定义这两个变量。

变量 @code{sys.path} 是字符串列表，用于确定解释器的模块搜索路径。该变量以环境变量 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 提取的默认路径进行初始化，如未设置 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH}，则使用内置的默认路径。可以用标准列表操作修改该变量：

@example
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
@end example

@node dir 函数,包,标准模块,模块
@anchor{tutorial/modules the-dir-function}@anchor{13eb}@anchor{tutorial/modules tut-dir}@anchor{13ec}
@subsection @code{dir()} 函数


内置函数 @ref{e01,,dir()} 用于查找模块定义的名称。返回结果是经过排序的字符串列表：

@example
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)  
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
 '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
 '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
 '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
 'warnoptions']
@end example

没有参数时，@ref{e01,,dir()} 列出当前定义的名称：

@example
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
@end example

注意，该函数列出所有类型的名称：变量、模块、函数等。

@geindex 模块; builtins

@ref{e01,,dir()} 不会列出内置函数和变量的名称。这些内容的定义在标准模块 @ref{12,,builtins} 里：

@example
>>> import builtins
>>> dir(builtins)  
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
 '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
 'zip']
@end example

@node 包,,dir 函数,模块
@anchor{tutorial/modules packages}@anchor{13ed}@anchor{tutorial/modules tut-packages}@anchor{13ee}
@subsection 包


包是一种用“点式模块名”构造 Python 模块命名空间的方法。例如，模块名 @code{A.B} 表示包 @code{A} 中名为 @code{B} 的子模块。正如模块可以区分不同模块之间的全局变量名称一样，点式模块名可以区分 NumPy 或 Pillow 等不同多模块包之间的模块名称。

假设要为统一处理声音文件与声音数据设计一个模块集（“包”）。声音文件的格式很多（通常以扩展名来识别，例如：@code{.wav}， @code{.aiff}， @code{.au}），因此，为了不同文件格式之间的转换，需要创建和维护一个不断增长的模块集合。为了实现对声音数据的不同处理（例如，混声、添加回声、均衡器功能、创造人工立体声效果），还要编写无穷无尽的模块流。下面这个分级文件树展示了这个包的架构：

@example
sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...
@end example

导入包时，Python 搜索 @code{sys.path} 里的目录，查找包的子目录。

Python 只把含 @code{__init__.py} 文件的目录当成包。这样可以防止以 @code{string} 等通用名称命名的目录，无意中屏蔽出现在后方模块搜索路径中的有效模块。 最简情况下，@code{__init__.py} 只是一个空文件，但该文件也可以执行包的初始化代码，或设置 @code{__all__} 变量，详见下文。

还可以从包中导入单个模块，例如：

@example
import sound.effects.echo
@end example

这段代码加载子模块 @code{sound.effects.echo} ，但引用时必须使用子模块的全名：

@example
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
@end example

另一种导入子模块的方法是 ：

@example
from sound.effects import echo
@end example

这段代码还可以加载子模块 @code{echo} ，不加包前缀也可以使用。因此，可以按如下方式使用：

@example
echo.echofilter(input, output, delay=0.7, atten=4)
@end example

Import 语句的另一种变体是直接导入所需的函数或变量：

@example
from sound.effects.echo import echofilter
@end example

同样，这样也会加载子模块 @code{echo}，但可以直接使用函数 @code{echofilter()}：

@example
echofilter(input, output, delay=0.7, atten=4)
@end example

注意，使用 @code{from package import item} 时，item 可以是包的子模块（或子包），也可以是包中定义的函数、类或变量等其他名称。@code{import} 语句首先测试包中是否定义了 item；如果未在包中定义，则假定 item 是模块，并尝试加载。如果找不到 item，则触发 @ref{16c,,ImportError} 异常。

相反，使用 @code{import item.subitem.subsubitem} 句法时，除最后一项外，每个 item 都必须是包；最后一项可以是模块或包，但不能是上一项中定义的类、函数或变量。

@menu
* 从包中导入 *:: 
* 子包参考:: 
* 多目录中的包:: 

@end menu

@node 从包中导入 *,子包参考,,包
@anchor{tutorial/modules importing-from-a-package}@anchor{13ef}@anchor{tutorial/modules tut-pkg-import-star}@anchor{13f0}
@subsubsection 从包中导入 *


@geindex __all__

使用 @code{from sound.effects import *} 时会发生什么？理想情况下，该语句在文件系统查找并导入包的所有子模块。这项操作花费的时间较长，并且导入子模块可能会产生不必要的副作用，这种副作用只有在显式导入子模块时才会发生。

唯一的解决方案是提供包的显式索引。@ref{cef,,import} 语句使用如下惯例：如果包的 @code{__init__.py} 代码定义了列表 @code{__all__}，运行 @code{from package import *} 时，它就是用于导入的模块名列表。发布包的新版本时，包的作者应更新此列表。如果包的作者认为没有必要在包中执行导入 * 操作，也可以不提供此列表。例如，@code{sound/effects/__init__.py} 文件包含以下代码：

@example
__all__ = ["echo", "surround", "reverse"]
@end example

这将意味着将 @code{from sound.effects import *} 导入 @code{sound.effects} 包的三个命名的子模块。

如果没有定义 @code{__all__}，@code{from sound.effects import *} 语句 @emph{不会} 把包 @code{sound.effects} 中所有子模块都导入到当前命名空间；该语句只确保导入包 @code{sound.effects} （可能还会运行 @code{__init__.py} 中的初始化代码），然后，再导入包中定义的名称。这些名称包括 @code{__init__.py} 中定义的任何名称（以及显式加载的子模块），还包括之前 @ref{cef,,import} 语句显式加载的包里的子模块。请看以下代码：

@example
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
@end example

本例中，执行 @code{from...import} 语句时，将把 @code{echo} 和 @code{surround} 模块导入至当前命名空间，因为，它们是在 @code{sound.effects} 包里定义的。（该导入操作在定义了 @code{__all__} 时也有效。）

虽然，可以把模块设计为用 @code{import *} 时只导出遵循指定模式的名称，但仍不提倡在生产代码中使用这种做法。

记住，使用 @code{from package import specific_submodule} 没有任何问题！ 实际上，除了导入模块使用不同包的同名子模块之外，这种方式是推荐用法。

@node 子包参考,多目录中的包,从包中导入 *,包
@anchor{tutorial/modules intra-package-references}@anchor{13f1}
@subsubsection 子包参考


包中含有多个子包时（与示例中的 @code{sound} 包一样），可以使用绝对导入引用兄弟包中的子模块。例如，要在模块 @code{sound.filters.vocoder} 中使用 @code{sound.effects} 包的 @code{echo} 模块时，可以用 @code{from sound.effects import echo} 导入。

还可以用 import 语句的 @code{from module import name} 形式执行相对导入。这些导入语句使用前导句点表示相对导入中的当前包和父包。例如，相对于 @code{surround} 模块，可以使用：

@example
from . import echo
from .. import formats
from ..filters import equalizer
@end example

注意，相对导入基于当前模块名。因为主模块名是 @code{"__main__"} ，所以 Python 程序的主模块必须始终使用绝对导入。

@node 多目录中的包,,子包参考,包
@anchor{tutorial/modules packages-in-multiple-directories}@anchor{13f2}
@subsubsection 多目录中的包


包还支持特殊属性 @ref{13f3,,__path__}。该属性初始化为在包的 @code{__init__.py} 文件中的代码执行前所在的目录名列表。这个变量可以修改，但这样做会影响将来搜索包中模块和子包的操作。

这个功能虽然不常用，但可用于扩展包中的模块集。

@node 输入与输出,错误和异常,模块,Python 教程
@anchor{tutorial/inputoutput doc}@anchor{13f4}@anchor{tutorial/inputoutput input-and-output}@anchor{13f5}@anchor{tutorial/inputoutput tut-io}@anchor{13f6}
@section 输入与输出


程序输出有几种显示方式；数据既可以输出供人阅读的形式，也可以写入文件备用。本章探讨一些可用的方式。

@menu
* 更复杂的输出格式:: 
* 读写文件:: 

@end menu

@node 更复杂的输出格式,读写文件,,输入与输出
@anchor{tutorial/inputoutput fancier-output-formatting}@anchor{13f7}@anchor{tutorial/inputoutput tut-formatting}@anchor{13f8}
@subsection 更复杂的输出格式


至此，我们已学习了两种写入值的方法：@emph{表达式语句} 和 @ref{97a,,print()} 函数。第三种方法是使用文件对象的 @code{write()} 方法；标准输出文件称为 @code{sys.stdout}。详见标准库参考。

对输出格式的控制不只是打印空格分隔的值，还需要更多方式。格式化输出包括以下几种方法。


@itemize *

@item 
使用 @ref{13f9,,格式化字符串字面值} ，要在字符串开头的引号/三引号前添加 @code{f} 或 @code{F} 。在这种字符串中，可以在 @code{@{} 和 @code{@}} 字符之间输入引用的变量，或字面值的 Python 表达式。

@example
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the @{year@} @{event@}'
'Results of the 2016 Referendum'
@end example

@item 
字符串的 @ref{5dd,,str.format()} 方法需要更多手动操作。该方法也用 @code{@{} 和 @code{@}} 标记替换变量的位置，虽然这种方法支持详细的格式化指令，但需要提供格式化信息。

@example
>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '@{:-9@} YES votes  @{:2.2%@}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'
@end example

@item 
最后，还可以用字符串切片和合并操作完成字符串处理操作，创建任何排版布局。字符串类型还支持将字符串按给定列宽进行填充，这些方法也很有用。
@end itemize

如果不需要花哨的输出，只想快速显示变量进行调试，可以用 @ref{8c3,,repr()} 或 @ref{206,,str()} 函数把值转化为字符串。

@ref{206,,str()} 函数返回供人阅读的值，@ref{8c3,,repr()} 则生成适于解释器读取的值（如果没有等效的语法，则强制执行 @ref{562,,SyntaxError}）。对于没有支持供人阅读展示结果的对象， @ref{206,,str()} 返回与 @ref{8c3,,repr()} 相同的值。一般情况下，数字、列表或字典等结构的值，使用这两个函数输出的表现形式是一样的。字符串有两种不同的表现形式。

示例如下：

@example
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
@end example

@ref{f6,,string} 模块包含 @ref{4f9,,Template} 类，提供了将值替换为字符串的另一种方法。该类使用 @code{$x} 占位符，并用字典的值进行替换，但对格式控制的支持比较有限。

@menu
* 格式化字符串字面值:: 
* 字符串 format() 方法: 字符串 format 方法. 
* 手动格式化字符串:: 
* 旧式字符串格式化方法:: 

@end menu

@node 格式化字符串字面值,字符串 format 方法,,更复杂的输出格式
@anchor{tutorial/inputoutput formatted-string-literals}@anchor{13fa}@anchor{tutorial/inputoutput tut-f-strings}@anchor{13f9}
@subsubsection 格式化字符串字面值


@ref{29d,,格式化字符串字面值} （简称为 f-字符串）在字符串前加前缀 @code{f} 或 @code{F}，通过 @code{@{expression@}} 表达式，把 Python 表达式的值添加到字符串内。

格式说明符是可选的，写在表达式后面，可以更好地控制格式化值的方式。下例将 pi 舍入到小数点后三位：

@example
>>> import math
>>> print(f'The value of pi is approximately @{math.pi:.3f@}.')
The value of pi is approximately 3.142.
@end example

在 @code{':'} 后传递整数，为该字段设置最小字符宽度，常用于列对齐：

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678@}
>>> for name, phone in table.items():
...     print(f'@{name:10@} ==> @{phone:10d@}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678
@end example

还有一些修饰符可以在格式化前转换值。 @code{'!a'} 应用 @ref{e19,,ascii()} ，@code{'!s'} 应用 @ref{206,,str()}，@code{'!r'} 应用 @ref{8c3,,repr()}：

@example
>>> animals = 'eels'
>>> print(f'My hovercraft is full of @{animals@}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of @{animals!r@}.')
My hovercraft is full of 'eels'.
@end example

格式规范参考详见参考指南 @ref{5e1,,格式规格迷你语言}。

@node 字符串 format 方法,手动格式化字符串,格式化字符串字面值,更复杂的输出格式
@anchor{tutorial/inputoutput the-string-format-method}@anchor{13fb}@anchor{tutorial/inputoutput tut-string-format}@anchor{13fc}
@subsubsection 字符串 format() 方法


@ref{5dd,,str.format()} 方法的基本用法如下所示：

@example
>>> print('We are the @{@} who say "@{@}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
@end example

花括号及之内的字符（称为格式字段）被替换为传递给 @ref{5dd,,str.format()} 方法的对象。花括号中的数字表示传递给 @ref{5dd,,str.format()} 方法的对象所在的位置。

@example
>>> print('@{0@} and @{1@}'.format('spam', 'eggs'))
spam and eggs
>>> print('@{1@} and @{0@}'.format('spam', 'eggs'))
eggs and spam
@end example

@ref{5dd,,str.format()} 方法中使用关键字参数名引用值。

@example
>>> print('This @{food@} is @{adjective@}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
@end example

位置参数和关键字参数可以任意组合：

@example
>>> print('The story of @{0@}, @{1@}, and @{other@}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.
@end example

如果不想分拆较长的格式字符串，最好按名称引用变量进行格式化，不要按位置。这项操作可以通过传递字典，并用方括号 @code{'[]'} 访问键来完成。

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678@}
>>> print('Jack: @{0[Jack]:d@}; Sjoerd: @{0[Sjoerd]:d@}; '
...       'Dcab: @{0[Dcab]:d@}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
@end example

也可以用 '**' 符号，把 table 当作传递的关键字参数。

@example
>>> table = @{'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678@}
>>> print('Jack: @{Jack:d@}; Sjoerd: @{Sjoerd:d@}; Dcab: @{Dcab:d@}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
@end example

与内置函数 @ref{11b6,,vars()} 结合使用时，这种方式非常实用，可以返回包含所有局部变量的字典。

例如，下面的代码生成一组整齐的列，包含给定整数及其平方与立方：

@example
>>> for x in range(1, 11):
...     print('@{0:2d@} @{1:3d@} @{2:4d@}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
@end example

@ref{5dd,,str.format()} 进行字符串格式化的完整概述详见 @ref{de8,,格式字符串语法} 。

@node 手动格式化字符串,旧式字符串格式化方法,字符串 format 方法,更复杂的输出格式
@anchor{tutorial/inputoutput manual-string-formatting}@anchor{13fd}
@subsubsection 手动格式化字符串


下面是使用手动格式化方式实现的同一个平方和立方的表：

@example
>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
@end example

（注意，每列之间的空格是通过使用 @ref{97a,,print()} 添加的：它总在其参数间添加空格。）

字符串对象的 @ref{13fe,,str.rjust()} 方法通过在左侧填充空格，对给定宽度字段中的字符串进行右对齐。同类方法还有 @ref{13ff,,str.ljust()} 和 @ref{1400,,str.center()} 。这些方法不写入任何内容，只返回一个新字符串，如果输入的字符串太长，它们不会截断字符串，而是原样返回；虽然这种方式会弄乱列布局，但也比另一种方法好，后者在显示值时可能不准确（如果真的想截断字符串，可以使用 @code{x.ljust(n)[:n]} 这样的切片操作 。）

另一种方法是 @ref{1401,,str.zfill()} ，该方法在数字字符串左边填充零，且能识别正负号：

@example
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
@end example

@node 旧式字符串格式化方法,,手动格式化字符串,更复杂的输出格式
@anchor{tutorial/inputoutput old-string-formatting}@anchor{1402}
@subsubsection 旧式字符串格式化方法


% 运算符（求余符）也可用于字符串格式化。给定 @code{'string' % values}，则 @code{string} 中的 @code{%} 实例会以零个或多个 @code{values} 元素替换。此操作被称为字符串插值。例如：

@example
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
@end example

@ref{1388,,printf 风格的字符串格式化} 小节介绍更多相关内容。

@node 读写文件,,更复杂的输出格式,输入与输出
@anchor{tutorial/inputoutput reading-and-writing-files}@anchor{1403}@anchor{tutorial/inputoutput tut-files}@anchor{1404}
@subsection 读写文件


@geindex 內置函数; open
@geindex 对象; file

@ref{16f,,open()} 返回一个 @ref{c1d,,file object} ，最常使用的是两个位置参数和一个关键字参数：@code{open(filename, mode, encoding=None)}

@example
>>> f = open('workfile', 'w', encoding="utf-8")
@end example

@c XXX str(f) is <io.TextIOWrapper object at 0x82e8dc4>
@c 
@c >>> print(f)
@c <open file 'workfile', mode 'w' at 80a0960>

第一个实参是文件名字符串。第二个实参是包含描述文件使用方式字符的字符串。@emph{mode} 的值包括 @code{'r'} ，表示文件只能读取；@code{'w'} 表示只能写入（现有同名文件会被覆盖）；@code{'a'} 表示打开文件并追加内容，任何写入的数据会自动添加到文件末尾。@code{'r+'} 表示打开文件进行读写。@emph{mode} 实参是可选的，省略时的默认值为 @code{'r'}。

通常情况下，文件是以 @emph{text mode} 打开的，也就是说，你从文件中读写字符串，这些字符串是以特定的 @emph{encoding} 编码的。如果没有指定 @emph{encoding} ，默认的是与平台有关的（见 @ref{16f,,open()} ）。因为 UTF-8 是现代事实上的标准，除非你知道你需要使用一个不同的编码，否则建议使用 @code{encoding="utf-8"} 。在模式后面加上一个 @code{'b'} ，可以用 @emph{binary mode} 打开文件。二进制模式的数据是以 @ref{172,,bytes} 对象的形式读写的。在二进制模式下打开文件时，你不能指定 @emph{encoding} 。

在文本模式下读取文件时，默认把平台特定的行结束符（Unix 上为 @code{\n}, Windows 上为 @code{\r\n}）转换为 @code{\n}。在文本模式下写入数据时，默认把 @code{\n} 转换回平台特定结束符。这种操作方式在后台修改文件数据对文本文件来说没有问题，但会破坏 @code{JPEG} 或 @code{EXE} 等二进制文件中的数据。注意，在读写此类文件时，一定要使用二进制模式。

在处理文件对象时，最好使用 @ref{7e4,,with} 关键字。优点是，子句体结束后，文件会正确关闭，即便触发异常也可以。而且，使用 @code{with} 相比等效的 @ref{e3f,,try}-@ref{2c3,,finally} 代码块要简短得多：

@example
>>> with open('workfile', encoding="utf-8") as f:
...     read_data = f.read()

>>> # We can check that the file has been automatically closed.
>>> f.closed
True
@end example

如果没有使用 @ref{7e4,,with} 关键字，则应调用 @code{f.close()} 关闭文件，即可释放文件占用的系统资源。

@cartouche
@quotation 警告 
调用 @code{f.write()} 时，未使用 @code{with} 关键字，或未调用 @code{f.close()}，即使程序正常退出，也**可能** 导致 @code{f.write()} 的参数没有完全写入磁盘。
@end quotation
@end cartouche

@c See also https://bugs.python.org/issue17852

通过 @ref{7e4,,with} 语句，或调用 @code{f.close()} 关闭文件对象后，再次使用该文件对象将会失败。

@example
>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
@end example

@menu
* 文件对象的方法:: 
* 使用 json 保存结构化数据:: 

@end menu

@node 文件对象的方法,使用 json 保存结构化数据,,读写文件
@anchor{tutorial/inputoutput methods-of-file-objects}@anchor{1405}@anchor{tutorial/inputoutput tut-filemethods}@anchor{1406}
@subsubsection 文件对象的方法


本节下文中的例子假定已创建 @code{f} 文件对象。

@code{f.read(size)} 可用于读取文件内容，它会读取一些数据，并返回字符串（文本模式），或字节串对象（在二进制模式下）。 @emph{size} 是可选的数值参数。省略 @emph{size} 或 @emph{size} 为负数时，读取并返回整个文件的内容；文件大小是内存的两倍时，会出现问题。@emph{size} 取其他值时，读取并返回最多 @emph{size} 个字符（文本模式）或 @emph{size} 个字节（二进制模式）。如已到达文件末尾，@code{f.read()} 返回空字符串（@code{'@w{'}}）。

@example
>>> f.read()
'This is the entire file.\n'
>>> f.read()
'@w{'}
@end example

@code{f.readline()} 从文件中读取单行数据；字符串末尾保留换行符（@code{\n}），只有在文件不以换行符结尾时，文件的最后一行才会省略换行符。这种方式让返回值清晰明确；只要 @code{f.readline()} 返回空字符串，就表示已经到达了文件末尾，空行使用 @code{'\n'} 表示，该字符串只包含一个换行符。

@example
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
'@w{'}
@end example

从文件中读取多行时，可以用循环遍历整个文件对象。这种操作能高效利用内存，快速，且代码简单：

@example
>>> for line in f:
...     print(line, end='@w{'})
...
This is the first line of the file.
Second line of the file
@end example

如需以列表形式读取文件中的所有行，可以用 @code{list(f)} 或 @code{f.readlines()}。

@code{f.write(string)} 把 @emph{string} 的内容写入文件，并返回写入的字符数。

@example
>>> f.write('This is a test\n')
15
@end example

写入其他类型的对象前，要先把它们转化为字符串（文本模式）或字节对象（二进制模式）：

@example
>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18
@end example

@code{f.tell()} 返回整数，给出文件对象在文件中的当前位置，表示为二进制模式下时从文件开始的字节数，以及文本模式下的意义不明的数字。

@code{f.seek(offset, whence)} 可以改变文件对象的位置。通过向参考点添加 @emph{offset} 计算位置；参考点由 @emph{whence} 参数指定。 @emph{whence} 值为 0 时，表示从文件开头计算，1 表示使用当前文件位置，2 表示使用文件末尾作为参考点。省略 @emph{whence} 时，其默认值为 0，即使用文件开头作为参考点。

@example
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'
@end example

在文本文件（模式字符串未使用 @code{b} 时打开的文件）中，只允许相对于文件开头搜索（使用 @code{seek(0, 2)} 搜索到文件末尾是个例外），唯一有效的 @emph{offset} 值是能从 @code{f.tell()} 中返回的，或 0。其他 @emph{offset} 值都会产生未定义的行为。

文件对象还支持 @code{isatty()} 和 @code{truncate()}  等方法，但不常用；文件对象的完整指南详见库参考。

@node 使用 json 保存结构化数据,,文件对象的方法,读写文件
@anchor{tutorial/inputoutput saving-structured-data-with-json}@anchor{1407}@anchor{tutorial/inputoutput tut-json}@anchor{1408}
@subsubsection 使用 @code{json} 保存结构化数据


@geindex 模块; json

从文件写入或读取字符串很简单，数字则稍显麻烦，因为 @code{read()} 方法只返回字符串，这些字符串必须传递给 @ref{205,,int()} 这样的函数，接受 @code{'123'} 这样的字符串，并返回数字值 123。保存嵌套列表、字典等复杂数据类型时，手动解析和序列化的操作非常复杂。

Python 支持 JSON (JavaScript Object Notation)@footnote{http://json.org} 这种流行数据交换格式，用户无需没完没了地编写、调试代码，才能把复杂的数据类型保存到文件。@ref{a4,,json} 标准模块采用 Python 数据层次结构，并将之转换为字符串表示形式；这个过程称为 @emph{serializing} （序列化）。从字符串表示中重建数据称为 @emph{deserializing} （解序化）。在序列化和解序化之间，表示对象的字符串可能已经存储在文件或数据中，或通过网络连接发送到远方 的机器。

@cartouche
@quotation 注解 
JSON 格式通常用于现代应用程序的数据交换。程序员早已对它耳熟能详，可谓是交互操作的不二之选。
@end quotation
@end cartouche

只需一行简单的代码即可查看某个对象的 JSON 字符串表现形式：

@example
>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
@end example

@ref{706,,dumps()} 函数还有一个变体， @ref{705,,dump()} ，它只将对象序列化为 @ref{1409,,text file} 。因此，如果 @code{f} 是 @ref{1409,,text file} 对象，可以这样做：

@example
json.dump(x, f)
@end example

要再次解码对象，如果 @code{f} 是已打开、供读取的 @ref{140a,,binary file} 或 @ref{1409,,text file} 对象：

@example
x = json.load(f)
@end example

@cartouche
@quotation 注解 
JSON文件必须以UTF-8编码。当打开JSON文件作为一个 @ref{1409,,text file} 用于读写时，使用 @code{encoding="utf-8"} 。
@end quotation
@end cartouche

这种简单的序列化技术可以处理列表和字典，但在 JSON 中序列化任意类的实例，则需要付出额外努力。@ref{a4,,json} 模块的参考包含对此的解释。


@subsubheading 参见


@ref{ca,,pickle} - 封存模块

与 @ref{1408,,JSON} 不同，@emph{pickle} 是一种允许对复杂 Python 对象进行序列化的协议。因此，它为 Python 所特有，不能用于与其他语言编写的应用程序通信。默认情况下它也是不安全的：如果解序化的数据是由手段高明的攻击者精心设计的，这种不受信任来源的 pickle 数据可以执行任意代码。


@node 错误和异常,类,输入与输出,Python 教程
@anchor{tutorial/errors doc}@anchor{140b}@anchor{tutorial/errors errors-and-exceptions}@anchor{140c}@anchor{tutorial/errors tut-errors}@anchor{140d}
@section 错误和异常


至此，本教程还未深入介绍错误信息，但如果您输入过本教程前文中的例子，应该已经看到过一些错误信息。目前，（至少）有两种不同错误：@emph{句法错误} 和 @emph{异常}。

@menu
* 句法错误:: 
* 异常:: 
* 处理异常:: 
* 触发异常:: 
* 异常链:: 
* 用户自定义异常:: 
* 定义清理操作:: 
* 预定义的清理操作:: 

@end menu

@node 句法错误,异常,,错误和异常
@anchor{tutorial/errors syntax-errors}@anchor{140e}@anchor{tutorial/errors tut-syntaxerrors}@anchor{140f}
@subsection 句法错误


句法错误又称解析错误，是学习 Python 时最常见的错误：

@example
>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
@end example

解析器会复现出现句法错误的代码行，并用小“箭头”指向行里检测到的第一个错误。错误是由箭头 @emph{上方} 的 token 触发的（至少是在这里检测出的）：本例中，在 @ref{97a,,print()} 函数中检测到错误，因为，在它前面缺少冒号（@code{':'}） 。错误信息还输出文件名与行号，在使用脚本文件时，就可以知道去哪里查错。

@node 异常,处理异常,句法错误,错误和异常
@anchor{tutorial/errors exceptions}@anchor{1410}@anchor{tutorial/errors tut-exceptions}@anchor{1411}
@subsection 异常


即使语句或表达式使用了正确的语法，执行时仍可能触发错误。执行时检测到的错误称为 @emph{异常}，异常不一定导致严重的后果：很快我们就能学会如何处理 Python 的异常。大多数异常不会被程序处理，而是显示下列错误信息：

@example
>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
@end example

错误信息的最后一行说明程序遇到了什么类型的错误。异常有不同的类型，而类型名称会作为错误信息的一部分中打印出来：上述示例中的异常类型依次是：@ref{1fb,,ZeroDivisionError}， @ref{e48,,NameError} 和 @ref{1ff,,TypeError}。作为异常类型打印的字符串是发生的内置异常的名称。对于所有内置异常都是如此，但对于用户定义的异常则不一定如此（虽然这种规范很有用）。标准的异常类型是内置的标识符（不是保留关键字）。

此行其余部分根据异常类型，结合出错原因，说明错误细节。

错误信息开头用堆栈回溯形式展示发生异常的语境。一般会列出源代码行的堆栈回溯；但不会显示从标准输入读取的行。

@ref{fbe,,内置异常} 列出了内置异常及其含义。

@node 处理异常,触发异常,异常,错误和异常
@anchor{tutorial/errors handling-exceptions}@anchor{1412}@anchor{tutorial/errors tut-handling}@anchor{13a0}
@subsection 处理异常


可以编写程序处理选定的异常。下例会要求用户一直输入内容，直到输入有效的整数，但允许用户中断程序（使用 @code{Control-C} 或操作系统支持的其他操作）；注意，用户中断程序会触发 @ref{2d3,,KeyboardInterrupt} 异常。

@example
>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...
@end example

@ref{e3f,,try} 语句的工作原理如下：


@itemize *

@item 
首先，执行 @emph{try 子句} （@ref{e3f,,try} 和 @ref{c19,,except} 关键字之间的（多行）语句）。

@item 
如果没有触发异常，则跳过 @emph{except 子句}，@ref{e3f,,try} 语句执行完毕。

@item 
如果执行 try 子句时发生了异常，则跳过该子句中剩下的部分。如果异常的类型与 @ref{c19,,except} 关键字后面的异常匹配，则执行 except 子句，然后，继续执行 @ref{e3f,,try} 语句之后的代码。

@item 
如果发生的异常不是 except 子句中列示的异常，则将其传递到外部的 @ref{e3f,,try} 语句中；如果没有找到处理程序，则它是一个 @emph{未处理异常}，语句执行将终止，并显示如上所示的消息。
@end itemize

@ref{e3f,,try} 语句可以有多个 except 子句，可为不同异常指定相应的处理程序。但最多只会执行一个处理程序。处理程序只处理对应的 try 子句中发生的异常，而不处理同一 @code{try} 语句内其他处理程序中的异常。except 子句可以用元组命名多个异常，例如：

@example
... except (RuntimeError, TypeError, NameError):
...     pass
@end example

发生的异常与 @ref{c19,,except} 子句中的类是同一个类或是它的基类时，异常与 except 子句中的类兼容（反之则不成立 --- 列出派生类的 except 子句与基类不兼容）。例如，下面的代码依次输出 B, C, D：

@example
class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")
@end example

注意，如果颠倒 except 子句的顺序（把 @code{except B} 放到第一个），则输出 B，B，B --- 即触发第一个匹配的 except 子句。

最后的 except 子句可以省略异常名，以用作通配符。但应谨慎使用，这种方式很容易掩盖真正的编程错误！它还可用于输出错误消息，然后重新触发异常（同样允许调用者处理异常）：

@example
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: @{0@}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
@end example

@ref{e3f,,try} ... @ref{c19,,except} 语句支持可选的 @emph{else 子句}，该子句必须放在所有 except 子句之后。如果 try 子句没有触发异常，但又必须执行一些代码时，这个子句很有用。例如：

@example
for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
@end example

使用 @code{else} 子句比向 @ref{e3f,,try} 子句添加额外的代码要好，可以避免意外捕获非 @code{try} ... @code{except} 语句保护的代码触发的异常。

发生异常时，它可能具有关联值，即异常 @emph{参数} 。是否需要参数，以及参数的类型取决于异常的类型。

except 子句可以在异常名称后面指定一个变量。这个变量和一个异常实例绑定，它的参数存储在 @code{instance.args} 中。为了方便起见，异常实例定义了 @ref{f01,,__str__()} ，因此可以直接打印参数而无需引用 @code{.args} 。也可以在抛出之前首先实例化异常，并根据需要向其添加任何属性。:

@example
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
@end example

如果异常有参数，则它们将作为未处理异常的消息的最后一部分（'详细信息'）打印。

异常处理程序不仅处理 try 子句中遇到的异常，还处理 try 子句中调用（即使是间接地）的函数内部发生的异常。例如:

@example
>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as err:
...     print('Handling run-time error:', err)
...
Handling run-time error: division by zero
@end example

@node 触发异常,异常链,处理异常,错误和异常
@anchor{tutorial/errors raising-exceptions}@anchor{1413}@anchor{tutorial/errors tut-raising}@anchor{1414}
@subsection 触发异常


@ref{d12,,raise} 语句支持强制触发指定的异常。例如：

@example
>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere
@end example

@ref{d12,,raise} 唯一的参数就是要触发的异常。这个参数必须是异常实例或异常类（派生自 @ref{2e3,,Exception} 类）。如果传递的是异常类，将通过调用没有参数的构造函数来隐式实例化：

@example
raise ValueError  # shorthand for 'raise ValueError()'
@end example

如果只想判断是否触发了异常，但并不打算处理该异常，则可以使用更简单的 @ref{d12,,raise} 语句重新触发异常：

@example
>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('An exception flew by!')
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: HiThere
@end example

@node 异常链,用户自定义异常,触发异常,错误和异常
@anchor{tutorial/errors exception-chaining}@anchor{1415}@anchor{tutorial/errors tut-exception-chaining}@anchor{1416}
@subsection 异常链


@ref{d12,,raise} 语句支持可选的 @ref{d12,,from} 子句，该子句用于启用链式异常。 例如：

@example
# exc must be exception instance or None.
raise RuntimeError from exc
@end example

转换异常时，这种方式很有用。例如：

@example
>>> def func():
...     raise IOError
...
>>> try:
...     func()
... except IOError as exc:
...     raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in func
OSError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database
@end example

异常链在 @ref{c19,,except} 或 @ref{2c3,,finally} 子句触发异常时自动生成。禁用异常链可使用 @code{from None} 习语：

@example
>>> try:
...     open('database.sqlite')
... except OSError:
...     raise RuntimeError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError
@end example

异常链机制详见 @ref{fbe,,内置异常}。

@node 用户自定义异常,定义清理操作,异常链,错误和异常
@anchor{tutorial/errors tut-userexceptions}@anchor{1417}@anchor{tutorial/errors user-defined-exceptions}@anchor{1418}
@subsection 用户自定义异常


程序可以通过创建新的异常类命名自己的异常（Python 类的内容详见 @ref{13a8,,类}）。不论是以直接还是间接的方式，异常都应从 @ref{2e3,,Exception} 类派生。

异常类可以被定义成能做其他类所能做的任何事，但通常应当保持简单，它往往只提供一些属性，允许相应的异常处理程序提取有关错误的信息。

大多数异常命名都以 “Error” 结尾，类似标准异常的命名。

许多标准模块都需要自定义异常，以报告由其定义的函数中出现的错误。有关类的说明，详见 @ref{13a8,,类}。

@node 定义清理操作,预定义的清理操作,用户自定义异常,错误和异常
@anchor{tutorial/errors defining-clean-up-actions}@anchor{1419}@anchor{tutorial/errors tut-cleanup}@anchor{141a}
@subsection 定义清理操作


@ref{e3f,,try} 语句还有一个可选子句，用于定义在所有情况下都必须要执行的清理操作。例如：

@example
>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt
@end example

如果存在 @ref{2c3,,finally} 子句，则 @code{finally} 子句是 @ref{e3f,,try} 语句结束前执行的最后一项任务。不论 @code{try} 语句是否触发异常，都会执行 @code{finally} 子句。以下内容介绍了几种比较复杂的触发异常情景：


@itemize *

@item 
如果执行 @code{try} 子句期间触发了某个异常，则某个 @ref{c19,,except} 子句应处理该异常。如果该异常没有 @code{except} 子句处理，在 @code{finally} 子句执行后会被重新触发。

@item 
@code{except} 或 @code{else} 子句执行期间也会触发异常。 同样，该异常会在 @code{finally} 子句执行之后被重新触发。

@item 
如果 @code{finally} 子句中包含 @ref{403,,break}、@ref{2c2,,continue} 或 @ref{2cf,,return} 等语句，异常将不会被重新引发。

@item 
如果执行 @code{try} 语句时遇到 @ref{403,,break},、@ref{2c2,,continue} 或 @ref{2cf,,return} 语句，则 @code{finally} 子句在执行 @code{break}、@code{continue} 或 @code{return} 语句之前执行。

@item 
如果 @code{finally} 子句中包含 @code{return} 语句，则返回值来自 @code{finally} 子句的某个 @code{return} 语句的返回值，而不是来自 @code{try} 子句的 @code{return} 语句的返回值。
@end itemize

例如：

@example
>>> def bool_return():
...     try:
...         return True
...     finally:
...         return False
...
>>> bool_return()
False
@end example

这是一个比较复杂的例子：

@example
>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
@end example

如上所示，任何情况下都会执行 @ref{2c3,,finally} 子句。@ref{c19,,except} 子句不处理两个字符串相除触发的 @ref{1ff,,TypeError}，因此会在 @code{finally} 子句执行后被重新触发。

在实际应用程序中，@ref{2c3,,finally} 子句对于释放外部资源（例如文件或者网络连接）非常有用，无论是否成功使用资源。

@node 预定义的清理操作,,定义清理操作,错误和异常
@anchor{tutorial/errors predefined-clean-up-actions}@anchor{141b}@anchor{tutorial/errors tut-cleanup-with}@anchor{141c}
@subsection 预定义的清理操作


某些对象定义了不需要该对象时要执行的标准清理操作。无论使用该对象的操作是否成功，都会执行清理操作。比如，下例要打开一个文件，并输出文件内容：

@example
for line in open("myfile.txt"):
    print(line, end="")
@end example

这个代码的问题在于，执行完代码后，文件在一段不确定的时间内处于打开状态。在简单脚本中这没有问题，但对于较大的应用程序来说可能会出问题。@ref{7e4,,with} 语句支持以及时、正确的清理的方式使用文件对象：

@example
with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
@end example

语句执行完毕后，即使在处理行时遇到问题，都会关闭文件 @emph{f}。和文件一样，支持预定义清理操作的对象会在文档中指出这一点。

@node 类,标准库简介,错误和异常,Python 教程
@anchor{tutorial/classes doc}@anchor{141d}@anchor{tutorial/classes classes}@anchor{141e}@anchor{tutorial/classes tut-classes}@anchor{13a8}
@section 类


类把数据与功能绑定在一起。创建新类就是创建新的对象 @emph{类型}，从而创建该类型的新 @emph{实例} 。类实例具有多种保持自身状态的属性。类实例还支持（由类定义的）修改自身状态的方法。

和其他编程语言相比，Python 只用了很少的新语法和语义就加入了类。Python 的类是 C++ 和 Modula-3 中类机制的结合体，而且支持所有面向对象编程（OOP）的标准特性：类继承机制支持多个基类，派生类可以覆盖基类的任何方法，类的方法可以调用基类中相同名称的方法。对象可以包含任意数量和类型的数据。和模块一样，类也拥有 Python 天然的动态特性：在运行时创建，创建后也可以修改。

如果用 C++ 术语来描述的话，类成员（包括数据成员）通常为 @emph{public} （例外的情况见下文 @ref{141f,,私有变量}），所有成员函数都是 @emph{virtual}。与在 Modula-3 中一样，没有用于从对象的方法中引用对象成员的简写形式：方法函数在声明时，有一个显式的参数代表本对象，该参数由调用隐式提供。 与在 Smalltalk 中一样，Python 的类也是对象，这为导入和重命名提供了语义支持。与 C++ 和 Modula-3 不同，Python 的内置类型可以用作基类，供用户扩展。 此外，与 C++ 一样，算术运算符、下标等具有特殊语法的内置运算符都可以为类实例而重新定义。

（由于缺乏关于类的公认术语，我会偶尔使用 Smalltalk、C++ 的术语，我还会使用 Modula-3 的术语，因为它的面向对象语义比 C++ 更接近 Python，但估计没几个读者听说过这门语言。）

@menu
* 名称和对象:: 
* Python 作用域和命名空间:: 
* 初探类:: 
* 补充说明:: 
* 继承:: 
* 私有变量:: 
* 杂项说明:: 
* 迭代器:: 
* 生成器:: 
* 生成器表达式:: 

@end menu

@node 名称和对象,Python 作用域和命名空间,,类
@anchor{tutorial/classes a-word-about-names-and-objects}@anchor{1420}@anchor{tutorial/classes tut-object}@anchor{1421}
@subsection 名称和对象


对象之间相互独立，多个名称（在多个作用域内）可以绑定到同一个对象。 其他语言称之为别名。Python 初学者通常不容易理解这个概念，处理数字、字符串、元组等不可变基本类型时，可以不必理会。 但是，对涉及可变对象，如列表、字典等大多数其他类型的 Python 代码的语义，别名可能会产生意料之外的效果。这样做，通常是为了让程序受益，因为别名在某些方面就像指针。例如，传递对象的代价很小，因为实现只传递一个指针；如果函数修改了作为参数传递的对象，调用者就可以看到更改 --- 无需 Pascal 用两个不同参数的传递机制。

@node Python 作用域和命名空间,初探类,名称和对象,类
@anchor{tutorial/classes python-scopes-and-namespaces}@anchor{1422}@anchor{tutorial/classes tut-scopes}@anchor{1423}
@subsection Python 作用域和命名空间


在介绍类之前，我首先要告诉你一些 Python 的作用域规则。类定义对命名空间有一些巧妙的技巧，你需要知道作用域和命名空间如何工作才能完全理解正在发生的事情。顺便说一下，关于这个主题的知识对任何高级 Python 程序员都很有用。

让我们从一些定义开始。

@emph{namespace} （命名空间）是一个从名字到对象的映射。 当前大部分命名空间都由 Python 字典实现，但一般情况下基本不会去关注它们（除了要面对性能问题时），而且也有可能在将来更改。 下面是几个命名空间的例子：存放内置函数的集合（包含 @ref{1424,,abs()} 这样的函数，和内建的异常等）；模块中的全局名称；函数调用中的局部名称。 从某种意义上说，对象的属性集合也是一种命名空间的形式。 关于命名空间的重要一点是，不同命名空间中的名称之间绝对没有关系；例如，两个不同的模块都可以定义一个 @code{maximize} 函数而不会产生混淆 --- 模块的用户必须在其前面加上模块名称。

顺便说明一下，我把任何跟在一个点号之后的名称都称为 @emph{属性} --- 例如，在表达式 @code{z.real} 中，@code{real} 是对象 @code{z} 的一个属性。按严格的说法，对模块中名称的引用属于属性引用：在表达式 @code{modname.funcname} 中，@code{modname} 是一个模块对象而 @code{funcname} 是它的一个属性。在此情况下在模块的属性和模块中定义的全局名称之间正好存在一个直观的映射：它们共享相同的命名空间！ @footnote{@w{(1)} 
存在一个例外。 模块对象有一个秘密的只读属性 @ref{5fe,,__dict__}，它返回用于实现模块命名空间的字典；@ref{5fe,,__dict__} 是属性但不是全局名称。 显然，使用这个将违反命名空间实现的抽象，应当仅被用于事后调试器之类的场合。
}

属性可以是只读或者可写的。如果为后者，那么对属性的赋值是可行的。模块属性是可写的，你可以写 @code{modname.the_answer = 42} 。可写的属性同样可以用 @ref{13d1,,del} 语句删除。例如， @code{del modname.the_answer} 将会从名为 @code{modname} 的对象中移除 @code{the_answer} 属性。

命名空间在不同时刻被创建，拥有不同的生存期。包含内置名称的命名空间是在 Python 解释器启动时创建的，永远不会被删除。模块的全局命名空间在模块定义被读入时创建；通常，模块命名空间也会持续到解释器退出。被解释器的顶层调用执行的语句，从一个脚本文件读取或交互式地读取，被认为是 @ref{1,,__main__} 模块调用的一部分，因此它们拥有自己的全局命名空间。（内置名称实际上也存在于一个模块中；这个模块被称作 @ref{12,,builtins} 。）

函数的本地命名空间在调用该函数时创建，并在函数返回或抛出不在函数内部处理的错误时被删除。 （实际上，用“遗忘”来描述实际发生的情况会更好一些。） 当然，每次递归调用都会有自己的本地命名空间。

一个 @emph{作用域} 是一个命名空间可直接访问的 Python 程序的文本区域。 这里的 “可直接访问” 意味着对名称的非限定引用会尝试在命名空间中查找名称。

虽然作用域是静态地确定的，但它们会被动态地使用。 在执行期间的任何时刻，会有 3 或 4 个命名空间可被直接访问的嵌套作用域:


@itemize *

@item 
最先搜索的最内部作用域包含局部名称

@item 
从最近的封闭作用域开始搜索的任何封闭函数的作用域包含非局部名称，也包括非全局名称

@item 
倒数第二个作用域包含当前模块的全局名称

@item 
最外面的作用域（最后搜索）是包含内置名称的命名空间
@end itemize

如果一个名称被声明为全局变量，则所有引用和赋值将直接指向包含该模块的全局名称的中间作用域。 要重新绑定在最内层作用域以外找到的变量，可以使用 @ref{d0f,,nonlocal} 语句声明为非本地变量。 如果没有被声明为非本地变量，这些变量将是只读的（尝试写入这样的变量只会在最内层作用域中创建一个 @emph{新的} 局部变量，而同名的外部变量保持不变）。

通常，当前局部作用域将（按字面文本）引用当前函数的局部名称。 在函数以外，局部作用域将引用与全局作用域相一致的命名空间：模块的命名空间。 类定义将在局部命名空间内再放置另一个命名空间。

重要的是应该意识到作用域是按字面文本来确定的：在一个模块内定义的函数的全局作用域就是该模块的命名空间，无论该函数从什么地方或以什么别名被调用。  另一方面，实际的名称搜索是在运行时动态完成的 --- 但是，Python 正在朝着“编译时静态名称解析”的方向发展，因此不要过于依赖动态名称解析！ （事实上，局部变量已经是被静态确定了。）

Python 的一个特殊规定是这样的 -- 如果不存在生效的 @ref{13a7,,global} 或 @ref{d0f,,nonlocal} 语句 -- 则对名称的赋值总是会进入最内层作用域。 赋值不会复制数据 --- 它们只是将名称绑定到对象。 删除也是如此：语句 @code{del x} 会从局部作用域所引用的命名空间中移除对 @code{x} 的绑定。 事实上，所有引入新名称的操作都是使用局部作用域：特别地，@ref{cef,,import} 语句和函数定义会在局部作用域中绑定模块或函数名称。

@ref{13a7,,global} 语句可被用来表明特定变量生存于全局作用域并且应当在其中被重新绑定；@ref{d0f,,nonlocal} 语句表明特定变量生存于外层作用域中并且应当在其中被重新绑定。

@menu
* 作用域和命名空间示例:: 

@end menu

@node 作用域和命名空间示例,,,Python 作用域和命名空间
@anchor{tutorial/classes scopes-and-namespaces-example}@anchor{1425}@anchor{tutorial/classes tut-scopeexample}@anchor{1426}
@subsubsection 作用域和命名空间示例


这个例子演示了如何引用不同作用域和名称空间，以及 @ref{13a7,,global} 和 @ref{d0f,,nonlocal} 会如何影响变量绑定:

@example
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
@end example

示例代码的输出是：

@example
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
@end example

请注意 @emph{局部} 赋值（这是默认状态）不会改变 @emph{scope_test} 对 @emph{spam} 的绑定。 @ref{d0f,,nonlocal} 赋值会改变 @emph{scope_test} 对 @emph{spam} 的绑定，而 @ref{13a7,,global} 赋值会改变模块层级的绑定。

您还可以发现在 @ref{13a7,,global} 赋值之前没有 @emph{spam} 的绑定。

@node 初探类,补充说明,Python 作用域和命名空间,类
@anchor{tutorial/classes a-first-look-at-classes}@anchor{1427}@anchor{tutorial/classes tut-firstclasses}@anchor{13c3}
@subsection 初探类


类引入了一些新语法，三种新对象类型和一些新语义。

@menu
* 类定义语法:: 
* 类对象:: 
* 实例对象:: 
* 方法对象:: 
* 类和实例变量:: 

@end menu

@node 类定义语法,类对象,,初探类
@anchor{tutorial/classes class-definition-syntax}@anchor{1428}@anchor{tutorial/classes tut-classdefinition}@anchor{1429}
@subsubsection 类定义语法


最简单的类定义看起来像这样:

@example
class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

类定义与函数定义 (@ref{e8b,,def} 语句) 一样必须被执行才会起作用。 （你可以尝试将类定义放在 @ref{eb3,,if} 语句的一个分支或是函数的内部。）

在实践中，类定义内的语句通常都是函数定义，但也允许有其他语句，有时还很有用 --- 我们会稍后再回来说明这个问题。 在类内部的函数定义通常具有一种特别形式的参数列表，这是方法调用的约定规范所指明的 --- 这个问题也将在稍后再说明。

当进入类定义时，将创建一个新的命名空间，并将其用作局部作用域 --- 因此，所有对局部变量的赋值都是在这个新命名空间之内。 特别的，函数定义会绑定到这里的新函数名称。

当（从结尾处）正常离开类定义时，将创建一个 @emph{类对象}。 这基本上是一个包围在类定义所创建命名空间内容周围的包装器；我们将在下一节了解有关类对象的更多信息。 原始的（在进入类定义之前起作用的）局部作用域将重新生效，类对象将在这里被绑定到类定义头所给出的类名称 (在这个示例中为 @code{ClassName})。

@node 类对象,实例对象,类定义语法,初探类
@anchor{tutorial/classes class-objects}@anchor{142a}@anchor{tutorial/classes tut-classobjects}@anchor{142b}
@subsubsection 类对象


类对象支持两种操作：属性引用和实例化。

@emph{属性引用} 使用 Python 中所有属性引用所使用的标准语法: @code{obj.name}。 有效的属性名称是类对象被创建时存在于类命名空间中的所有名称。 因此，如果类定义是这样的:

@example
class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
@end example

那么 @code{MyClass.i} 和 @code{MyClass.f} 就是有效的属性引用，将分别返回一个整数和一个函数对象。 类属性也可以被赋值，因此可以通过赋值来更改 @code{MyClass.i} 的值。 @code{__doc__} 也是一个有效的属性，将返回所属类的文档字符串: @code{"A simple example class"}。

类的 @emph{实例化} 使用函数表示法。 可以把类对象视为是返回该类的一个新实例的不带参数的函数。 举例来说（假设使用上述的类）:

@example
x = MyClass()
@end example

创建类的新 @emph{实例} 并将此对象分配给局部变量 @code{x}。

实例化操作（“调用”类对象）会创建一个空对象。 许多类喜欢创建带有特定初始状态的自定义实例。 为此类定义可能包含一个名为 @ref{e2b,,__init__()} 的特殊方法，就像这样:

@example
def __init__(self):
    self.data = []
@end example

当一个类定义了 @ref{e2b,,__init__()} 方法时，类的实例化操作会自动为新创建的类实例发起调用 @ref{e2b,,__init__()}。 因此在这个示例中，可以通过以下语句获得一个经初始化的新实例:

@example
x = MyClass()
@end example

当然，@ref{e2b,,__init__()} 方法还可以有额外参数以实现更高灵活性。 在这种情况下，提供给类实例化运算符的参数将被传递给 @ref{e2b,,__init__()}。 例如，:

@example
>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
@end example

@node 实例对象,方法对象,类对象,初探类
@anchor{tutorial/classes instance-objects}@anchor{142c}@anchor{tutorial/classes tut-instanceobjects}@anchor{142d}
@subsubsection 实例对象


现在我们能用实例对象做什么？ 实例对象所能理解的唯一操作是属性引用。 有两种有效的属性名称：数据属性和方法。

@emph{数据属性} 对应于 Smalltalk 中的“实例变量”，以及 C++ 中的“数据成员”。 数据属性不需要声明；像局部变量一样，它们将在第一次被赋值时产生。 例如，如果 @code{x} 是上面创建的 @code{MyClass} 的实例，则以下代码段将打印数值 @code{16}，且不保留任何追踪信息:

@example
x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter
@end example

另一类实例属性引用称为 @emph{方法}。 方法是“从属于”对象的函数。 （在 Python 中，方法这个术语并不是类实例所特有的：其他对象也可以有方法。 例如，列表对象具有 append, insert, remove, sort 等方法。 然而，在以下讨论中，我们使用方法一词将专指类实例对象的方法，除非另外显式地说明。）

@geindex 对象; method

实例对象的有效方法名称依赖于其所属的类。 根据定义，一个类中所有是函数对象的属性都是定义了其实例的相应方法。 因此在我们的示例中，@code{x.f} 是有效的方法引用，因为 @code{MyClass.f} 是一个函数，而 @code{x.i} 不是方法，因为 @code{MyClass.i} 不是函数。 但是 @code{x.f} 与 @code{MyClass.f} 并不是一回事 --- 它是一个 @emph{方法对象}，不是函数对象。

@node 方法对象,类和实例变量,实例对象,初探类
@anchor{tutorial/classes method-objects}@anchor{142e}@anchor{tutorial/classes tut-methodobjects}@anchor{142f}
@subsubsection 方法对象


通常，方法在绑定后立即被调用:

@example
x.f()
@end example

在 @code{MyClass} 示例中，这将返回字符串 @code{'hello world'}。 但是，立即调用一个方法并不是必须的: @code{x.f} 是一个方法对象，它可以被保存起来以后再调用。 例如:

@example
xf = x.f
while True:
    print(xf())
@end example

将持续打印 @code{hello world}，直到结束。

当一个方法被调用时到底发生了什么？ 你可能已经注意到上面调用 @code{x.f()} 时并没有带参数，虽然 @code{f()} 的函数定义指定了一个参数。 这个参数发生了什么事？ 当不带参数地调用一个需要参数的函数时 Python 肯定会引发异常 --- 即使参数实际未被使用...

实际上，你可能已经猜到了答案：方法的特殊之处就在于实例对象会作为函数的第一个参数被传入。 在我们的示例中，调用 @code{x.f()} 其实就相当于 @code{MyClass.f(x)}。 总之，调用一个具有 @emph{n} 个参数的方法就相当于调用再多一个参数的对应函数，这个参数值为方法所属实例对象，位置在其他参数之前。

如果你仍然无法理解方法的运作原理，那么查看实现细节可能会弄清楚问题。 当一个实例的非数据属性被引用时，将搜索实例所属的类。 如果被引用的属性名称表示一个有效的类属性中的函数对象，会通过打包（指向）查找到的实例对象和函数对象到一个抽象对象的方式来创建方法对象：这个抽象对象就是方法对象。 当附带参数列表调用方法对象时，将基于实例对象和参数列表构建一个新的参数列表，并使用这个新参数列表调用相应的函数对象。

@node 类和实例变量,,方法对象,初探类
@anchor{tutorial/classes class-and-instance-variables}@anchor{1430}@anchor{tutorial/classes tut-class-and-instance-variables}@anchor{1431}
@subsubsection 类和实例变量


一般来说，实例变量用于每个实例的唯一数据，而类变量用于类的所有实例共享的属性和方法:

@example
class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'
@end example

正如 @ref{1421,,名称和对象} 中已讨论过的，共享数据可能在涉及 @ref{138d,,mutable} 对象例如列表和字典的时候导致令人惊讶的结果。 例如以下代码中的 @emph{tricks} 列表不应该被用作类变量，因为所有的 @emph{Dog} 实例将只共享一个单独的列表:

@example
class Dog:

    tricks = []             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']
@end example

正确的类设计应该使用实例变量:

@example
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
@end example

@node 补充说明,继承,初探类,类
@anchor{tutorial/classes random-remarks}@anchor{1432}@anchor{tutorial/classes tut-remarks}@anchor{1433}
@subsection 补充说明


@c These should perhaps be placed more carefully...

如果同样的属性名称同时出现在实例和类中，则属性查找会优先选择实例:

@example
>>> class Warehouse:
        purpose = 'storage'
        region = 'west'

>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east
@end example

数据属性可以被方法以及一个对象的普通用户（“客户端”）所引用。 换句话说，类不能用于实现纯抽象数据类型。 实际上，在 Python 中没有任何东西能强制隐藏数据 --- 它是完全基于约定的。 （而在另一方面，用 C 语言编写的 Python 实现则可以完全隐藏实现细节，并在必要时控制对象的访问；此特性可以通过用 C 编写 Python 扩展来使用。）

客户端应当谨慎地使用数据属性 --- 客户端可能通过直接操作数据属性的方式破坏由方法所维护的固定变量。 请注意客户端可以向一个实例对象添加他们自己的数据属性而不会影响方法的可用性，只要保证避免名称冲突 --- 再次提醒，在此使用命名约定可以省去许多令人头痛的麻烦。

在方法内部引用数据属性（或其他方法！）并没有简便方式。 我发现这实际上提升了方法的可读性：当浏览一个方法代码时，不会存在混淆局部变量和实例变量的机会。

方法的第一个参数常常被命名为 @code{self}。 这也不过就是一个约定: @code{self} 这一名称在 Python 中绝对没有特殊含义。 但是要注意，不遵循此约定会使得你的代码对其他 Python 程序员来说缺乏可读性，而且也可以想像一个 @emph{类浏览器} 程序的编写可能会依赖于这样的约定。

任何一个作为类属性的函数都为该类的实例定义了一个相应方法。 函数定义的文本并非必须包含于类定义之内：将一个函数对象赋值给一个局部变量也是可以的。 例如:

@example
# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1

    def g(self):
        return 'hello world'

    h = g
@end example

现在 @code{f}, @code{g} 和 @code{h} 都是 @code{C} 类的引用函数对象的属性，因而它们就都是 @code{C} 的实例的方法 --- 其中 @code{h} 完全等同于 @code{g}。 但请注意，本示例的做法通常只会令程序的阅读者感到迷惑。

方法可以通过使用 @code{self} 参数的方法属性调用其他方法:

@example
class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)
@end example

方法可以通过与普通函数相同的方式引用全局名称。 与方法相关联的全局作用域就是包含其定义的模块。 （类永远不会被作为全局作用域。） 虽然我们很少会有充分的理由在方法中使用全局作用域，但全局作用域存在许多合理的使用场景：举个例子，导入到全局作用域的函数和模块可以被方法所使用，在其中定义的函数和类也一样。 通常，包含该方法的类本身是在全局作用域中定义的，而在下一节中我们将会发现为何方法需要引用其所属类的很好的理由。

每个值都是一个对象，因此具有 @emph{类} （也称为 @emph{类型}），并存储为 @code{object.__class__} 。

@node 继承,私有变量,补充说明,类
@anchor{tutorial/classes inheritance}@anchor{1434}@anchor{tutorial/classes tut-inheritance}@anchor{1435}
@subsection 继承


当然，如果不支持继承，语言特性就不值得称为“类”。派生类定义的语法如下所示:

@example
class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

名称 @code{BaseClassName} 必须定义于包含派生类定义的作用域中。 也允许用其他任意表达式代替基类名称所在的位置。 这有时也可能会用得上，例如，当基类定义在另一个模块中的时候:

@example
class DerivedClassName(modname.BaseClassName):
@end example

派生类定义的执行过程与基类相同。 当构造类对象时，基类会被记住。 此信息将被用来解析属性引用：如果请求的属性在类中找不到，搜索将转往基类中进行查找。 如果基类本身也派生自其他某个类，则此规则将被递归地应用。

派生类的实例化没有任何特殊之处: @code{DerivedClassName()} 会创建该类的一个新实例。 方法引用将按以下方式解析：搜索相应的类属性，如有必要将按基类继承链逐步向下查找，如果产生了一个函数对象则方法引用就生效。

派生类可能会重写其基类的方法。 因为方法在调用同一对象的其他方法时没有特殊权限，所以调用同一基类中定义的另一方法的基类方法最终可能会调用覆盖它的派生类的方法。 （对 C++ 程序员的提示：Python 中所有的方法实际上都是 @code{virtual} 方法。）

在派生类中的重载方法实际上可能想要扩展而非简单地替换同名的基类方法。 有一种方式可以简单地直接调用基类方法：即调用 @code{BaseClassName.methodname(self, arguments)}。 有时这对客户端来说也是有用的。 （请注意仅当此基类可在全局作用域中以 @code{BaseClassName} 的名称被访问时方可使用此方式。）

Python有两个内置函数可被用于继承机制：


@itemize *

@item 
使用 @ref{55a,,isinstance()} 来检查一个实例的类型: @code{isinstance(obj, int)} 仅会在 @code{obj.__class__} 为 @ref{205,,int} 或某个派生自 @ref{205,,int} 的类时为 @code{True}。

@item 
使用 @ref{55b,,issubclass()} 来检查类的继承关系: @code{issubclass(bool, int)} 为 @code{True}，因为 @ref{2c4,,bool} 是 @ref{205,,int} 的子类。 但是，@code{issubclass(float, int)} 为 @code{False}，因为 @ref{1fe,,float} 不是 @ref{205,,int} 的子类。
@end itemize

@menu
* 多重继承:: 

@end menu

@node 多重继承,,,继承
@anchor{tutorial/classes multiple-inheritance}@anchor{1436}@anchor{tutorial/classes tut-multiple}@anchor{1437}
@subsubsection 多重继承


Python 也支持一种多重继承。 带有多个基类的类定义语句如下所示:

@example
class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
@end example

对于多数应用来说，在最简单的情况下，你可以认为搜索从父类所继承属性的操作是深度优先、从左至右的，当层次结构中存在重叠时不会在同一个类中搜索两次。 因此，如果某一属性在 @code{DerivedClassName} 中未找到，则会到 @code{Base1} 中搜索它，然后（递归地）到 @code{Base1} 的基类中搜索，如果在那里未找到，再到 @code{Base2} 中搜索，依此类推。

真实情况比这个更复杂一些；方法解析顺序会动态改变以支持对 @ref{5e6,,super()} 的协同调用。 这种方式在某些其他多重继承型语言中被称为后续方法调用，它比单继承型语言中的 super 调用更强大。

动态改变顺序是有必要的，因为所有多重继承的情况都会显示出一个或更多的菱形关联（即至少有一个父类可通过多条路径被最底层类所访问）。 例如，所有类都是继承自 @ref{3da,,object}，因此任何多重继承的情况都提供了一条以上的路径可以通向 @ref{3da,,object}。 为了确保基类不会被访问一次以上，动态算法会用一种特殊方式将搜索顺序线性化， 保留每个类所指定的从左至右的顺序，只调用每个父类一次，并且保持单调（即一个类可以被子类化而不影响其父类的优先顺序）。 总而言之，这些特性使得设计具有多重继承的可靠且可扩展的类成为可能。 要了解更多细节，请参阅 @indicateurl{https://www.python.org/download/releases/2.3/mro/}。

@node 私有变量,杂项说明,继承,类
@anchor{tutorial/classes private-variables}@anchor{1438}@anchor{tutorial/classes tut-private}@anchor{141f}
@subsection 私有变量


那种仅限从一个对象内部访问的“私有”实例变量在 Python 中并不存在。 但是，大多数 Python 代码都遵循这样一个约定：带有一个下划线的名称 (例如 @code{_spam}) 应该被当作是 API 的非公有部分 (无论它是函数、方法或是数据成员)。 这应当被视为一个实现细节，可能不经通知即加以改变。

@geindex name; mangling

由于存在对于类私有成员的有效使用场景（例如避免名称与子类所定义的名称相冲突），因此存在对此种机制的有限支持，称为 @emph{名称改写}。 任何形式为 @code{__spam} 的标识符（至少带有两个前缀下划线，至多一个后缀下划线）的文本将被替换为 @code{_classname__spam}，其中 @code{classname} 为去除了前缀下划线的当前类名称。 这种改写不考虑标识符的句法位置，只要它出现在类定义内部就会进行。

名称改写有助于让子类重载方法而不破坏类内方法调用。例如:

@example
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)
@end example

上面的示例即使在 @code{MappingSubclass} 引入了一个 @code{__update} 标识符的情况下也不会出错，因为它会在 @code{Mapping} 类中被替换为 @code{_Mapping__update} 而在 @code{MappingSubclass} 类中被替换为 @code{_MappingSubclass__update}。

请注意，改写规则的设计主要是为了避免意外冲突；访问或修改被视为私有的变量仍然是可能的。这在特殊情况下甚至会很有用，例如在调试器中。

请注意传递给 @code{exec()} 或 @code{eval()} 的代码不会将发起调用类的类名视作当前类；这类似于 @code{global} 语句的效果，因此这种效果仅限于同时经过字节码编译的代码。 同样的限制也适用于 @code{getattr()}, @code{setattr()} 和 @code{delattr()}，以及对于 @code{__dict__} 的直接引用。

@node 杂项说明,迭代器,私有变量,类
@anchor{tutorial/classes odds-and-ends}@anchor{1439}@anchor{tutorial/classes tut-odds}@anchor{143a}
@subsection 杂项说明


有时会需要使用类似于 Pascal 的“record”或 C 的“struct”这样的数据类型，将一些命名数据项捆绑在一起。 这种情况适合定义一个空类:

@example
class Employee:
    pass

john = Employee()  # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
@end example

一段需要特定抽象数据类型的 Python 代码往往可以被传入一个模拟了该数据类型的方法的类作为替代。 例如，如果你有一个基于文件对象来格式化某些数据的函数，你可以定义一个带有 @code{read()} 和 @code{readline()} 方法从字符串缓存获取数据的类，并将其作为参数传入。

@c (Unfortunately, this technique has its limitations: a class can't define
@c operations that are accessed by special syntax such as sequence subscripting
@c or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
@c not cause the interpreter to read further input from it.)

实例方法对象也具有属性: @code{m.__self__} 就是带有 @code{m()} 方法的实例对象，而 @code{m.__func__} 则是该方法所对应的函数对象。

@node 迭代器,生成器,杂项说明,类
@anchor{tutorial/classes iterators}@anchor{143b}@anchor{tutorial/classes tut-iterators}@anchor{143c}
@subsection 迭代器


到目前为止，您可能已经注意到大多数容器对象都可以使用 @ref{d02,,for} 语句:

@example
for element in [1, 2, 3]:
    print(element)
for element in (1, 2, 3):
    print(element)
for key in @{'one':1, 'two':2@}:
    print(key)
for char in "123":
    print(char)
for line in open("myfile.txt"):
    print(line, end='@w{'})
@end example

这种访问风格清晰、简洁又方便。 迭代器的使用非常普遍并使得 Python 成为一个统一的整体。 在幕后，@ref{d02,,for} 语句会在容器对象上调用 @ref{df5,,iter()}。 该函数返回一个定义了 @ref{d34,,__next__()} 方法的迭代器对象，此方法将逐一访问容器中的元素。 当元素用尽时，@ref{d34,,__next__()} 将引发 @ref{58a,,StopIteration} 异常来通知终止 @code{for} 循环。 你可以使用 @ref{77f,,next()} 内置函数来调用 @ref{d34,,__next__()} 方法；这个例子显示了它的运作方式:

@example
>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x10c90e650>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    next(it)
StopIteration
@end example

看过迭代器协议的幕后机制，给你的类添加迭代器行为就很容易了。 定义一个 @ref{611,,__iter__()} 方法来返回一个带有 @ref{d34,,__next__()} 方法的对象。 如果类已定义了 @code{__next__()}，则 @ref{611,,__iter__()} 可以简单地返回 @code{self}:

@example
class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
@end example

@example
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print(char)
...
m
a
p
s
@end example

@node 生成器,生成器表达式,迭代器,类
@anchor{tutorial/classes generators}@anchor{143d}@anchor{tutorial/classes tut-generators}@anchor{143e}
@subsection 生成器


@ref{a8c,,生成器} 是一个用于创建迭代器的简单而强大的工具。 它们的写法类似于标准的函数，但当它们要返回数据时会使用 @ref{2ce,,yield} 语句。 每次在生成器上调用 @ref{77f,,next()} 时，它会从上次离开的位置恢复执行（它会记住上次执行语句时的所有数据值）。 一个显示如何非常容易地创建生成器的示例如下:

@example
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]
@end example

@example
>>> for char in reverse('golf'):
...     print(char)
...
f
l
o
g
@end example

可以用生成器来完成的操作同样可以用前一节所描述的基于类的迭代器来完成。 但生成器的写法更为紧凑，因为它会自动创建 @ref{611,,__iter__()} 和 @ref{143f,,__next__()} 方法。

另一个关键特性在于局部变量和执行状态会在每次调用之间自动保存。 这使得该函数相比使用 @code{self.index} 和 @code{self.data} 这种实例变量的方式更易编写且更为清晰。

除了会自动创建方法和保存程序状态，当生成器终结时，它们还会自动引发 @ref{58a,,StopIteration}。 这些特性结合在一起，使得创建迭代器能与编写常规函数一样容易。

@node 生成器表达式,,生成器,类
@anchor{tutorial/classes generator-expressions}@anchor{1440}@anchor{tutorial/classes tut-genexps}@anchor{1441}
@subsection 生成器表达式


某些简单的生成器可以写成简洁的表达式代码，所用语法类似列表推导式，但外层为圆括号而非方括号。 这种表达式被设计用于生成器将立即被外层函数所使用的情况。 生成器表达式相比完整的生成器更紧凑但较不灵活，相比等效的列表推导式则更为节省内存。

例如:

@example
>>> sum(i*i for i in range(10))                 # sum of squares
285

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))         # dot product
260

>>> unique_words = set(word for line in page  for word in line.split())

>>> valedictorian = max((student.gpa, student.name) for student in graduates)

>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']
@end example

@node 标准库简介,标准库简介 —— 第二部分,类,Python 教程
@anchor{tutorial/stdlib doc}@anchor{1442}@anchor{tutorial/stdlib brief-tour-of-the-standard-library}@anchor{1443}@anchor{tutorial/stdlib tut-brieftour}@anchor{1444}
@section 标准库简介


@menu
* 操作系统接口:: 
* 文件通配符:: 
* 命令行参数:: 
* 错误输出重定向和程序终止:: 
* 字符串模式匹配:: 
* 数学:: 
* 互联网访问:: 
* 日期和时间:: 
* 数据压缩:: 
* 性能测量:: 
* 质量控制:: 
* 自带电池:: 

@end menu

@node 操作系统接口,文件通配符,,标准库简介
@anchor{tutorial/stdlib operating-system-interface}@anchor{1445}@anchor{tutorial/stdlib tut-os-interface}@anchor{1446}
@subsection 操作系统接口


@ref{c4,,os} 模块提供了许多与操作系统交互的函数:

@example
>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python39'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0
@end example

一定要使用 @code{import os} 而不是 @code{from os import *} 。这将避免内建的 @ref{16f,,open()} 函数被 @ref{762,,os.open()} 隐式替换掉，因为它们的使用方式大不相同。

@geindex 內置函数; help

内置的 @ref{e01,,dir()} 和 @ref{175,,help()} 函数可用作交互式辅助工具，用于处理大型模块，如 @ref{c4,,os}:

@example
>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>
@end example

对于日常文件和目录管理任务， @ref{e9,,shutil} 模块提供了更易于使用的更高级别的接口:

@example
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
@end example

@node 文件通配符,命令行参数,操作系统接口,标准库简介
@anchor{tutorial/stdlib file-wildcards}@anchor{1447}@anchor{tutorial/stdlib tut-file-wildcards}@anchor{1448}
@subsection 文件通配符


@ref{88,,glob} 模块提供了一个在目录中使用通配符搜索创建文件列表的函数:

@example
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
@end example

@node 命令行参数,错误输出重定向和程序终止,文件通配符,标准库简介
@anchor{tutorial/stdlib command-line-arguments}@anchor{1449}@anchor{tutorial/stdlib tut-command-line-arguments}@anchor{144a}
@subsection 命令行参数


通用实用程序脚本通常需要处理命令行参数。这些参数作为列表存储在 @ref{fd,,sys} 模块的 @emph{argv} 属性中。例如，以下输出来自在命令行运行 @code{python demo.py one two three}

@example
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
@end example

@ref{5,,argparse} 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本可提取一个或多个文件名，并可选择要显示的行数:

@example
import argparse

parser = argparse.ArgumentParser(
    prog='top',
    description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
@end example

当在通过 @code{python top.py --lines=5 alpha.txt beta.txt} 在命令行运行时，该脚本会将 @code{args.lines} 设为 @code{5} 并将 @code{args.filenames} 设为 @code{['alpha.txt', 'beta.txt']}。

@node 错误输出重定向和程序终止,字符串模式匹配,命令行参数,标准库简介
@anchor{tutorial/stdlib error-output-redirection-and-program-termination}@anchor{144b}@anchor{tutorial/stdlib tut-stderr}@anchor{144c}
@subsection 错误输出重定向和程序终止


@ref{fd,,sys} 模块还具有 @emph{stdin} ， @emph{stdout} 和 @emph{stderr} 的属性。后者对于发出警告和错误消息非常有用，即使在 @emph{stdout} 被重定向后也可以看到它们:

@example
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
@end example

终止脚本的最直接方法是使用 @code{sys.exit()} 。

@node 字符串模式匹配,数学,错误输出重定向和程序终止,标准库简介
@anchor{tutorial/stdlib string-pattern-matching}@anchor{144d}@anchor{tutorial/stdlib tut-string-pattern-matching}@anchor{144e}
@subsection 字符串模式匹配


@ref{dd,,re} 模块为高级字符串处理提供正则表达式工具。对于复杂的匹配和操作，正则表达式提供简洁，优化的解决方案:

@example
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
@end example

当只需要简单的功能时，首选字符串方法因为它们更容易阅读和调试:

@example
>>> 'tea for too'.replace('too', 'two')
'tea for two'
@end example

@node 数学,互联网访问,字符串模式匹配,标准库简介
@anchor{tutorial/stdlib mathematics}@anchor{144f}@anchor{tutorial/stdlib tut-mathematics}@anchor{1450}
@subsection 数学


@ref{b1,,math} 模块提供对浮点数学的底层C库函数的访问:

@example
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
@end example

@ref{dc,,random} 模块提供了进行随机选择的工具:

@example
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4
@end example

@ref{f5,,statistics} 模块计算数值数据的基本统计属性（均值，中位数，方差等）:

@example
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095
@end example

SciPy项目 <@indicateurl{https://scipy.org}> 有许多其他模块用于数值计算。

@node 互联网访问,日期和时间,数学,标准库简介
@anchor{tutorial/stdlib internet-access}@anchor{1451}@anchor{tutorial/stdlib tut-internet-access}@anchor{1452}
@subsection 互联网访问


有许多模块可用于访问互联网和处理互联网协议。其中两个最简单的 @ref{129,,urllib.request} 用于从URL检索数据，以及 @ref{ed,,smtplib} 用于发送邮件:

@example
>>> from urllib.request import urlopen
>>> with urlopen('http://worldtimeapi.org/api/timezone/etc/UTC.txt') as response:
...     for line in response:
...         line = line.decode()             # Convert bytes to a str
...         if line.startswith('datetime'):
...             print(line.rstrip())         # Remove trailing newline
...
datetime: 2022-01-01T01:36:47.689215+00:00

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@@example.org', 'jcaesar@@example.org',
... """To: jcaesar@@example.org
... From: soothsayer@@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
@end example

（请注意，第二个示例需要在localhost上运行的邮件服务器。）

@node 日期和时间,数据压缩,互联网访问,标准库简介
@anchor{tutorial/stdlib dates-and-times}@anchor{1453}@anchor{tutorial/stdlib tut-dates-and-times}@anchor{1454}
@subsection 日期和时间


@ref{30,,datetime} 模块提供了以简单和复杂的方式操作日期和时间的类。虽然支持日期和时间算法，但实现的重点是有效的成员提取以进行输出格式化和操作。该模块还支持可感知时区的对象。

@example
>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
@end example

@node 数据压缩,性能测量,日期和时间,标准库简介
@anchor{tutorial/stdlib data-compression}@anchor{1455}@anchor{tutorial/stdlib tut-data-compression}@anchor{1456}
@subsection 数据压缩


常见的数据存档和压缩格式由模块直接支持，包括：@ref{14d,,zlib}, @ref{8b,,gzip}, @ref{13,,bz2}, @ref{ad,,lzma}, @ref{14b,,zipfile} 和 @ref{101,,tarfile}。:

@example
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
@end example

@node 性能测量,质量控制,数据压缩,标准库简介
@anchor{tutorial/stdlib performance-measurement}@anchor{1457}@anchor{tutorial/stdlib tut-performance-measurement}@anchor{1458}
@subsection 性能测量


一些Python用户对了解同一问题的不同方法的相对性能产生了浓厚的兴趣。 Python提供了一种可以立即回答这些问题的测量工具。

例如，元组封包和拆包功能相比传统的交换参数可能更具吸引力。@ref{10d,,timeit} 模块可以快速演示在运行效率方面一定的优势:

@example
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
@end example

与 @ref{10d,,timeit} 的精细粒度级别相反， @ref{d3,,profile} 和 @ref{d4,,pstats} 模块提供了用于在较大的代码块中识别时间关键部分的工具。

@node 质量控制,自带电池,性能测量,标准库简介
@anchor{tutorial/stdlib quality-control}@anchor{1459}@anchor{tutorial/stdlib tut-quality-control}@anchor{145a}
@subsection 质量控制


开发高质量软件的一种方法是在开发过程中为每个函数编写测试，并在开发过程中经常运行这些测试。

@ref{66,,doctest} 模块提供了一个工具，用于扫描模块并验证程序文档字符串中嵌入的测试。测试构造就像将典型调用及其结果剪切并粘贴到文档字符串一样简单。这通过向用户提供示例来改进文档，并且它允许doctest模块确保代码保持对文档的真实:

@example
def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests
@end example

@ref{124,,unittest} 模块不像 @ref{66,,doctest} 模块那样易于使用，但它允许在一个单独的文件中维护更全面的测试集:

@example
import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests
@end example

@node 自带电池,,质量控制,标准库简介
@anchor{tutorial/stdlib batteries-included}@anchor{145b}@anchor{tutorial/stdlib tut-batteries-included}@anchor{145c}
@subsection 自带电池


Python有“自带电池”的理念。通过其包的复杂和强大功能可以最好地看到这一点。例如:


@itemize *

@item 
@ref{148,,xmlrpc.client} 和 @ref{149,,xmlrpc.server} 模块使得实现远程过程调用变成了小菜一碟。 尽管存在于模块名称中，但用户不需要直接了解或处理 XML。

@item 
@ref{67,,email} 包是一个用于管理电子邮件的库，包括MIME和其他：基于 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的邮件文档。与 @ref{ed,,smtplib} 和 @ref{d0,,poplib} 实际上发送和接收消息不同，电子邮件包具有完整的工具集，用于构建或解码复杂的消息结构（包括附件）以及实现互联网编码和标头协议。

@item 
 @ref{a4,,json} 包为解析这种流行的数据交换格式提供了强大的支持。 @ref{29,,csv} 模块支持以逗号分隔值格式直接读取和写入文件，这些格式通常由数据库和电子表格支持。 XML处理由 @ref{140,,xml.etree.ElementTree} ， @ref{13d,,xml.dom} 和 @ref{144,,xml.sax} 包支持。这些模块和软件包共同大大简化了Python应用程序和其他工具之间的数据交换。

@item 
@ref{f2,,sqlite3} 模块是SQLite数据库库的包装器，提供了一个可以使用稍微非标准的SQL语法更新和访问的持久数据库。

@item 
国际化由许多模块支持，包括 @ref{87,,gettext} ， @ref{a9,,locale} ，以及 @ref{1b,,codecs} 包。
@end itemize

@node 标准库简介 —— 第二部分,虚拟环境和包,标准库简介,Python 教程
@anchor{tutorial/stdlib2 doc}@anchor{145d}@anchor{tutorial/stdlib2 brief-tour-of-the-standard-library-part-ii}@anchor{145e}@anchor{tutorial/stdlib2 tut-brieftourtwo}@anchor{145f}
@section 标准库简介 —— 第二部分


第二部分涵盖了专业编程所需要的更高级的模块。这些模块很少用在小脚本中。

@menu
* 格式化输出:: 
* 模板:: 
* 使用二进制数据记录格式:: 
* 多线程: 多线程<2>. 
* 日志:: 
* 弱引用:: 
* 用于操作列表的工具:: 
* 十进制浮点运算:: 

@end menu

@node 格式化输出,模板,,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 output-formatting}@anchor{1460}@anchor{tutorial/stdlib2 tut-output-formatting}@anchor{1461}
@subsection 格式化输出


@ref{df,,reprlib} 模块提供了一个定制化版本的 @ref{8c3,,repr()} 函数，用于缩略显示大型或深层嵌套的容器对象:

@example
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"@{'a', 'c', 'd', 'e', 'f', 'g', ...@}"
@end example

@ref{d2,,pprint} 模块提供了更加复杂的打印控制，其输出的内置对象和用户自定义对象能够被解释器直接读取。当输出结果过长而需要折行时，“美化输出机制”会添加换行符和缩进，以更清楚地展示数据结构:

@example
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
   'white',
   ['green', 'red']],
  [['magenta', 'yellow'],
   'blue']]]
@end example

@ref{10a,,textwrap} 模块能够格式化文本段落，以适应给定的屏幕宽度:

@example
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
@end example

@ref{a9,,locale} 模块处理与特定地域文化相关的数据格式。locale 模块的 format 函数包含一个 grouping 属性，可直接将数字格式化为带有组分隔符的样式:

@example
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()          # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
...                      conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
@end example

@node 模板,使用二进制数据记录格式,格式化输出,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 templating}@anchor{1462}@anchor{tutorial/stdlib2 tut-templating}@anchor{1463}
@subsection 模板


@ref{f6,,string} 模块包含一个通用的 @ref{4f9,,Template} 类，具有适用于最终用户的简化语法。它允许用户在不更改应用逻辑的情况下定制自己的应用。

上述格式化操作是通过占位符实现的，占位符由 @code{$} 加上合法的 Python 标识符（只能包含字母、数字和下划线）构成。一旦使用花括号将占位符括起来，就可以在后面直接跟上更多的字母和数字而无需空格分割。@code{$$} 将被转义成单个字符 @code{$}:

@example
>>> from string import Template
>>> t = Template('$@{village@}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
@end example

如果在字典或关键字参数中未提供某个占位符的值，那么 @ref{1464,,substitute()} 方法将抛出 @ref{3f1,,KeyError}。对于邮件合并类型的应用，用户提供的数据有可能是不完整的，此时使用 @ref{1465,,safe_substitute()} 方法更加合适 —— 如果数据缺失，它会直接将占位符原样保留。

@example
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
  ...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
@end example

Template 的子类可以自定义分隔符。例如，以下是某个照片浏览器的批量重命名功能，采用了百分号作为日期、照片序号和照片格式的占位符:

@example
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
...     delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print('@{0@} --> @{1@}'.format(filename, newname))

img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
@end example

模板的另一个应用是将程序逻辑与多样的格式化输出细节分离开来。这使得对 XML 文件、纯文本报表和 HTML 网络报表使用自定义模板成为可能。

@node 使用二进制数据记录格式,多线程<2>,模板,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 tut-binary-formats}@anchor{1466}@anchor{tutorial/stdlib2 working-with-binary-data-record-layouts}@anchor{1467}
@subsection 使用二进制数据记录格式


@ref{f8,,struct} 模块提供了 @ref{cde,,pack()} 和 @ref{1468,,unpack()} 函数，用于处理不定长度的二进制记录格式。下面的例子展示了在不使用 @ref{14b,,zipfile} 模块的情况下，如何循环遍历一个 ZIP 文件的所有头信息。Pack 代码 @code{"H"} 和 @code{"I"} 分别代表两字节和四字节无符号整数。@code{"<"} 代表它们是标准尺寸的小端字节序:

@example
import struct

with open('myfile.zip', 'rb') as f:
    data = f.read()

start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('<IIIHH', data[start:start+16])
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16
    filename = data[start:start+filenamesize]
    start += filenamesize
    extra = data[start:start+extra_size]
    print(filename, hex(crc32), comp_size, uncomp_size)

    start += extra_size + comp_size     # skip to the next header
@end example

@node 多线程<2>,日志,使用二进制数据记录格式,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 multi-threading}@anchor{1469}@anchor{tutorial/stdlib2 tut-multi-threading}@anchor{146a}
@subsection 多线程


线程是一种对于非顺序依赖的多个任务进行解耦的技术。多线程可以提高应用的响应效率，当接收用户输入的同时，保持其他任务在后台运行。一个有关的应用场景是，将 I/O 和计算运行在两个并行的线程中。

以下代码展示了高阶的 @ref{10b,,threading} 模块如何在后台运行任务，且不影响主程序的继续运行:

@example
import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')
@end example

多线程应用面临的主要挑战是，相互协调的多个线程之间需要共享数据或其他资源。为此，threading 模块提供了多个同步操作原语，包括线程锁、事件、条件变量和信号量。

尽管这些工具非常强大，但微小的设计错误却可以导致一些难以复现的问题。因此，实现多任务协作的首选方法是将所有对资源的请求集中到一个线程中，然后使用 @ref{da,,queue} 模块向该线程供应来自其他线程的请求。 应用程序使用 @ref{de6,,Queue} 对象进行线程间通信和协调，更易于设计，更易读，更可靠。

@node 日志,弱引用,多线程<2>,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 logging}@anchor{146b}@anchor{tutorial/stdlib2 tut-logging}@anchor{146c}
@subsection 日志


@ref{aa,,logging} 模块提供功能齐全且灵活的日志记录系统。在最简单的情况下，日志消息被发送到文件或 @code{sys.stderr}

@example
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
@end example

这会产生以下输出:

@example
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
@end example

默认情况下，informational 和 debugging 消息被压制，输出会发送到标准错误流。其他输出选项包括将消息转发到电子邮件，数据报，套接字或 HTTP 服务器。新的过滤器可以根据消息优先级选择不同的路由方式：@code{DEBUG}，@code{INFO}，@code{WARNING}，@code{ERROR}，和 @code{CRITICAL}。

日志系统可以直接从 Python 配置，也可以从用户配置文件加载，以便自定义日志记录而无需更改应用程序。

@node 弱引用,用于操作列表的工具,日志,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 tut-weak-references}@anchor{146d}@anchor{tutorial/stdlib2 weak-references}@anchor{146e}
@subsection 弱引用


Python 会自动进行内存管理（对大多数对象进行引用计数并使用 @ref{1013,,garbage collection} 来清除循环引用）。 当某个对象的最后一个引用被移除后不久就会释放其所占用的内存。

此方式对大多数应用来说都适用，但偶尔也必须在对象持续被其他对象所使用时跟踪它们。 不幸的是，跟踪它们将创建一个会令其永久化的引用。 @ref{131,,weakref} 模块提供的工具可以不必创建引用就能跟踪对象。 当对象不再需要时，它将自动从一个弱引用表中被移除，并为弱引用对象触发一个回调。 典型应用包括对创建开销较大的对象进行缓存:

@example
>>> import weakref, gc
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...
>>> a = A(10)                   # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a            # does not create a reference
>>> d['primary']                # fetch the object if it is still alive
10
>>> del a                       # remove the one reference
>>> gc.collect()                # run garbage collection right away
0
>>> d['primary']                # entry was automatically removed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d['primary']                # entry was automatically removed
  File "C:/python39/lib/weakref.py", line 46, in __getitem__
    o = self.data[key]()
KeyError: 'primary'
@end example

@node 用于操作列表的工具,十进制浮点运算,弱引用,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 tools-for-working-with-lists}@anchor{146f}@anchor{tutorial/stdlib2 tut-list-tools}@anchor{1470}
@subsection 用于操作列表的工具


许多对于数据结构的需求可以通过内置列表类型来满足。 但是，有时也会需要具有不同效费比的替代实现。

@ref{6,,array} 模块提供了一种 @ref{217,,array()} 对象，它类似于列表，但只能存储类型一致的数据且存储密集更高。 下面的例子演示了一个以两个字节为存储单元的无符号二进制数值的数组 (类型码为 @code{"H"})，而对于普通列表来说，每个条目存储为标准 Python 的 int 对象通常要占用16 个字节:

@example
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
@end example

@ref{1d,,collections} 模块提供了一种 @ref{633,,deque()} 对象，它类似于列表，但从左端添加和弹出的速度较快，而在中间查找的速度较慢。 此种对象适用于实现队列和广度优先树搜索:

@example
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
@end example

@example
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
    node = unsearched.popleft()
    for m in gen_moves(node):
        if is_goal(m):
            return m
        unsearched.append(m)
@end example

在替代的列表实现以外，标准库也提供了其他工具，例如 @ref{11,,bisect} 模块具有用于操作有序列表的函数:

@example
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
@end example

@ref{8d,,heapq} 模块提供了基于常规列表来实现堆的函数。 最小值的条目总是保持在位置零。 这对于需要重复访问最小元素而不希望运行完整列表排序的应用来说非常有用:

@example
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # rearrange the list into heap order
>>> heappush(data, -5)                 # add a new entry
>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
[-5, 0, 1]
@end example

@node 十进制浮点运算,,用于操作列表的工具,标准库简介 —— 第二部分
@anchor{tutorial/stdlib2 decimal-floating-point-arithmetic}@anchor{1471}@anchor{tutorial/stdlib2 tut-decimal-fp}@anchor{1472}
@subsection 十进制浮点运算


@ref{35,,decimal} 模块提供了一种 @ref{2c7,,Decimal} 数据类型用于十进制浮点运算。 相比内置的 @ref{1fe,,float} 二进制浮点实现，该类特别适用于


@itemize *

@item 
财务应用和其他需要精确十进制表示的用途，

@item 
控制精度，

@item 
控制四舍五入以满足法律或监管要求，

@item 
跟踪有效小数位，或

@item 
用户期望结果与手工完成的计算相匹配的应用程序。
@end itemize

例如，使用十进制浮点和二进制浮点数计算70美分手机和5％税的总费用，会产生的不同结果。如果结果四舍五入到最接近的分数差异会更大:

@example
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
@end example

@ref{2c7,,Decimal} 表示的结果会保留尾部的零，并根据具有两个有效位的被乘数自动推出四个有效位。 Decimal 可以模拟手工运算来避免当二进制浮点数无法精确表示十进制数时会导致的问题。

精确表示特性使得 @ref{2c7,,Decimal} 类能够执行对于二进制浮点数来说不适用的模运算和相等性检测:

@example
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False
@end example

@ref{35,,decimal} 模块提供了运算所需要的足够精度:

@example
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')
@end example

@node 虚拟环境和包,接下来？,标准库简介 —— 第二部分,Python 教程
@anchor{tutorial/venv doc}@anchor{1473}@anchor{tutorial/venv tut-venv}@anchor{1474}@anchor{tutorial/venv virtual-environments-and-packages}@anchor{1475}
@section 虚拟环境和包


@menu
* 概述: 概述<4>. 
* 创建虚拟环境:: 
* 使用pip管理包:: 

@end menu

@node 概述<4>,创建虚拟环境,,虚拟环境和包
@anchor{tutorial/venv introduction}@anchor{1476}
@subsection 概述


Python应用程序通常会使用不在标准库内的软件包和模块。应用程序有时需要特定版本的库，因为应用程序可能需要修复特定的错误，或者可以使用库的过时版本的接口编写应用程序。

这意味着一个Python安装可能无法满足每个应用程序的要求。如果应用程序A需要特定模块的1.0版本但应用程序B需要2.0版本，则需求存在冲突，安装版本1.0或2.0将导致某一个应用程序无法运行。

这个问题的解决方案是创建一个 @ref{1477,,virtual environment}，一个目录树，其中安装有特定Python版本，以及许多其他包。

然后，不同的应用将可以使用不同的虚拟环境。 要解决先前需求相冲突的例子，应用程序 A 可以拥有自己的 安装了 1.0 版本的虚拟环境，而应用程序 B 则拥有安装了 2.0 版本的另一个虚拟环境。 如果应用程序 B 要求将某个库升级到 3.0 版本，也不会影响应用程序 A 的环境。

@node 创建虚拟环境,使用pip管理包,概述<4>,虚拟环境和包
@anchor{tutorial/venv creating-virtual-environments}@anchor{1478}
@subsection 创建虚拟环境


用于创建和管理虚拟环境的模块称为 @ref{12e,,venv}。@ref{12e,,venv} 通常会安装你可用的最新版本的 Python。如果您的系统上有多个版本的 Python，您可以通过运行 @code{python3} 或您想要的任何版本来选择特定的Python版本。

要创建虚拟环境，请确定要放置它的目录，并将 @ref{12e,,venv} 模块作为脚本运行目录路径:

@example
python3 -m venv tutorial-env
@end example

如果 @code{tutorial-env} 目录不存在，它将为你创建一个，并在其中创建包含Python解释器，标准库和各种支持文件的副本的目录。

虚拟环境的常用目录位置是 @code{.venv}。 这个名称通常会令该目录在你的终端中保持隐藏，从而避免需要对所在目录进行额外解释的一般名称。 它还能防止与某些工具所支持的 @code{.env} 环境变量定义文件发生冲突。

创建虚拟环境后，您可以激活它。

在Windows上，运行:

@example
tutorial-env\Scripts\activate.bat
@end example

在Unix或MacOS上，运行:

@example
source tutorial-env/bin/activate
@end example

（这个脚本是为bash shell编写的。如果你使用 @code{csh} 或 @code{fish} shell，你应该改用 @code{activate.csh} 或 @code{activate.fish} 脚本。）

激活虚拟环境将改变你所用终端的提示符，以显示你正在使用的虚拟环境，并修改环境以使 @code{python} 命令所运行的将是已安装的特定 Python 版本。 例如：

@example
$ source ~/envs/tutorial-env/bin/activate
(tutorial-env) $ python
Python 3.5.1 (default, May  6 2016, 10:59:36)
  ...
>>> import sys
>>> sys.path
['@w{'}, '/usr/local/lib/python35.zip', ...,
'~/envs/tutorial-env/lib/python3.5/site-packages']
>>>
@end example

@node 使用pip管理包,,创建虚拟环境,虚拟环境和包
@anchor{tutorial/venv managing-packages-with-pip}@anchor{1479}
@subsection 使用pip管理包


你可以使用一个名为 @code{pip} 的程序来安装、升级和移除软件包。 默认情况下 @code{pip} 将从 Python Package Index <@indicateurl{https://pypi.org}> 安装软件包。 你可以在你的 web 浏览器中查看 Python Package Index。

@code{pip} 有许多子命令: "install", "uninstall", "freeze" 等等。 （请在 @ref{8ec,,安装 Python 模块} 指南页查看完整的 @code{pip} 文档。）

您可以通过指定包的名称来安装最新版本的包：

@example
(tutorial-env) $ python -m pip install novas
Collecting novas
  Downloading novas-3.1.1.3.tar.gz (136kB)
Installing collected packages: novas
  Running setup.py install for novas
Successfully installed novas-3.1.1.3
@end example

您还可以通过提供包名称后跟 @code{==} 和版本号来安装特定版本的包：

@example
(tutorial-env) $ python -m pip install requests==2.6.0
Collecting requests==2.6.0
  Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.6.0
@end example

如果你重新运行这个命令，@code{pip} 会注意到已经安装了所请求的版本并且什么都不做。您可以提供不同的版本号来获取该版本，或者您可以运行 @code{pip install --upgrade} 将软件包升级到最新版本：

@example
(tutorial-env) $ python -m pip install --upgrade requests
Collecting requests
Installing collected packages: requests
  Found existing installation: requests 2.6.0
    Uninstalling requests-2.6.0:
      Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0
@end example

@code{pip uninstall} 后跟一个或多个包名称将从虚拟环境中删除包。

@code{pip show} 将显示有关特定包的信息：

@example
(tutorial-env) $ pip show requests
---
Metadata-Version: 2.0
Name: requests
Version: 2.7.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@@kennethreitz.com
License: Apache 2.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:
@end example

@code{pip list} 将显示虚拟环境中安装的所有软件包：

@example
(tutorial-env) $ pip list
novas (3.1.1.3)
numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (16.0)
@end example

@cite{pip freeze`} 将生成一个类似的已安装包列表，但输出使用 @code{pip install} 期望的格式。一个常见的约定是将此列表放在 @code{requirements.txt} 文件中：

@example
(tutorial-env) $ pip freeze > requirements.txt
(tutorial-env) $ cat requirements.txt
novas==3.1.1.3
numpy==1.9.2
requests==2.7.0
@end example

然后可以将 @code{requirements.txt} 提交给版本控制并作为应用程序的一部分提供。然后用户可以使用 @code{install -r} 安装所有必需的包：

@example
(tutorial-env) $ python -m pip install -r requirements.txt
Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
  ...
Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
  ...
Collecting requests==2.7.0 (from -r requirements.txt (line 3))
  ...
Installing collected packages: novas, numpy, requests
  Running setup.py install for novas
Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0
@end example

@code{pip} 有更多选择。有关 @code{pip} 的完整文档，请参阅 @ref{8ec,,安装 Python 模块} 指南。当您编写一个包并希望在 Python 包索引中使它可用时，请参考 @ref{8ed,,分发 Python 模块} 指南。

@node 接下来？,交互式编辑和编辑历史,虚拟环境和包,Python 教程
@anchor{tutorial/whatnow doc}@anchor{147a}@anchor{tutorial/whatnow tut-whatnow}@anchor{147b}@anchor{tutorial/whatnow what-now}@anchor{147c}
@section 接下来？


阅读本教程可能会增强您对使用Python的兴趣 - 您应该热衷于应用Python来解决您的实际问题。你应该去哪里了解更多？

本教程是Python文档集的一部分。其他文档：


@itemize *

@item 
@ref{135f,,Python 标准库}:

您应该浏览本手册，该手册提供了有关标准库中的类型，功能和模块的完整（尽管简洁）参考资料。标准的Python发行版包含 @emph{很多} 的附加代码。有些模块可以读取Unix邮箱，通过HTTP检索文档，生成随机数，解析命令行选项，编写CGI程序，压缩数据以及许多其他任务。浏览标准库参考可以了解更多可用的内容。

@item 
@ref{8ec,,安装 Python 模块} 解释了怎么安装由其他Python开发者编写的模块。

@item 
@ref{1360,,Python 语言参考手册}: Python的语法和语义的详细解释。尽管阅读完非常繁重，但作为语言本身的完整指南是有用的。
@end itemize

更多Python资源：


@itemize *

@item 
@indicateurl{https://www.python.org} ：主要的Python网站。它包含代码，文档以及指向Web上与Python相关的页面的链接。该网站世界很多地区都有镜像，如欧洲，日本和澳大利亚；镜像可能比主站点更快，具体取决于您的地理位置。

@item 
@indicateurl{https://docs.python.org} ：快速访问Python的文档。

@item 
@indicateurl{https://pypi.org}: The Python Package Index，以前也被昵称为 Cheese Shop @footnote{@w{(1)} 
“Cheese Shop”是 Monty Python 的一个短剧：一位顾客来到一家奶酪商店，但无论他要哪种奶酪，店员都说没有货。
}，是可下载用户自制 Python 模块的索引。 当你要开始发布代码时，你可以在此处进行注册以便其他人能找到它。

@item 
@indicateurl{https://code.activestate.com/recipes/langs/python/} ：Python Cookbook是一个相当大的代码示例集，更多的模块和有用的脚本。特别值得注意的贡献收集在一本名为Python Cookbook（O'Reilly＆Associates，ISBN 0-596-00797-3）的书中。

@item 
@indicateurl{http://www.pyvideo.org} 从会议和用户组会议中收集与Python相关的视频的链接。

@item 
@indicateurl{https://scipy.org} ：Ecientific Python项目包括用于快速阵列计算和操作的模块，以及用于诸如线性代数，傅里叶变换，非线性求解器，随机数分布，统计分析等的一系列包。
@end itemize

对于与Python相关的问题和问题报告，您可以发布到新闻组 @code{comp.lang.python} ，或者将它们发送到邮件列表python-@email{list@@python.org}。新闻组和邮件列表是互通的，因此发布到一个地方将自动转发给另一个。每天有数百个帖子，询问（和回答）问题，建议新功能，以及宣布新模块。邮件列表档案可在 @indicateurl{https://mail.python.org/pipermail/} 上找到。

在发问之前，请务必查看以下列表 @ref{147d,,常见问题} （或简写为 FAQ）。常见问题包含了很多一次又一次问到的问题及答案，并且可能已经包含了您的问题的解决方案。

@subsubheading 备注


@node 交互式编辑和编辑历史,浮点算术：争议和限制,接下来？,Python 教程
@anchor{tutorial/interactive doc}@anchor{147e}@anchor{tutorial/interactive interactive-input-editing-and-history-substitution}@anchor{147f}@anchor{tutorial/interactive tut-interacting}@anchor{136e}
@section 交互式编辑和编辑历史


某些版本的 Python 解释器支持编辑当前输入行和编辑历史记录，类似 Korn shell 和 GNU Bash shell 的功能 。这个功能使用了 GNU Readline@footnote{https://tiswww.case.edu/php/chet/readline/rltop.html} 来实现，一个支持多种编辑方式的库。这个库有它自己的文档，在这里我们就不重复说明了。

@menu
* Tab 补全和编辑历史:: 
* 默认交互式解释器的替代品:: 

@end menu

@node Tab 补全和编辑历史,默认交互式解释器的替代品,,交互式编辑和编辑历史
@anchor{tutorial/interactive tab-completion-and-history-editing}@anchor{1480}@anchor{tutorial/interactive tut-keybindings}@anchor{1481}
@subsection Tab 补全和编辑历史


在解释器启动的时候，补全变量和模块名的功能将 @ref{9d5,,自动打开}，以便在按下 @code{Tab} 键的时候调用补全函数。它会查看 Python 语句名称，当前局部变量和可用的模块名称。处理像 @code{string.a} 的表达式，它会求值在最后一个 @code{'.'} 之前的表达式，接着根据求值结果对象的属性给出补全建议。如果拥有 @ref{433,,__getattr__()} 方法的对象是表达式的一部分，注意这可能会执行程序定义的代码。默认配置下会把编辑历史记录保存在用户目录下名为 @code{.python_history} 的文件。在下一次 Python 解释器会话期间，编辑历史记录仍旧可用。

@node 默认交互式解释器的替代品,,Tab 补全和编辑历史,交互式编辑和编辑历史
@anchor{tutorial/interactive alternatives-to-the-interactive-interpreter}@anchor{1482}@anchor{tutorial/interactive tut-commentary}@anchor{1483}
@subsection 默认交互式解释器的替代品


Python 解释器与早期版本的相比，向前迈进了一大步；无论怎样，还有些希望的功能：如果能在编辑连续行时建议缩进（解析器知道接下来是否需要缩进符号），那将很棒。补全机制可以使用解释器的符号表。有命令去检查（甚至建议）括号，引号以及其他符号是否匹配。

一个可选的增强型交互式解释器是 IPython@footnote{https://ipython.org/}，它已经存在了有一段时间，它具有 tab 补全，探索对象和高级历史记录管理功能。它还可以彻底定制并嵌入到其他应用程序中。另一个相似的增强型交互式环境是 bpython@footnote{https://www.bpython-interpreter.org/}。

@c import math

@node 浮点算术：争议和限制,附录,交互式编辑和编辑历史,Python 教程
@anchor{tutorial/floatingpoint doc}@anchor{1484}@anchor{tutorial/floatingpoint bpython}@anchor{1485}@anchor{tutorial/floatingpoint floating-point-arithmetic-issues-and-limitations}@anchor{1486}@anchor{tutorial/floatingpoint tut-fp-issues}@anchor{1487}
@section 浮点算术：争议和限制


浮点数在计算机硬件中表示为以 2 为基数（二进制）的小数。举例而言，十进制的小数

@example
0.125
@end example

等于 1/10 + 2/100 + 5/1000 ，同理，二进制的小数

@example
0.001
@end example

等于0/2 + 0/4 + 1/8。这两个小数具有相同的值，唯一真正的区别是第一个是以 10 为基数的小数表示法，第二个则是 2 为基数。

不幸的是，大多数的十进制小数都不能精确地表示为二进制小数。这导致在大多数情况下，你输入的十进制浮点数都只能近似地以二进制浮点数形式储存在计算机中。

用十进制来理解这个问题显得更加容易一些。考虑分数 1/3 。我们可以得到它在十进制下的一个近似值

@example
0.3
@end example

或者，更近似的，:

@example
0.33
@end example

或者，更近似的，:

@example
0.333
@end example

以此类推。结果是无论你写下多少的数字，它都永远不会等于 1/3 ，只是更加更加地接近 1/3 。

同样的道理，无论你使用多少位以 2 为基数的数码，十进制的 0.1 都无法精确地表示为一个以 2 为基数的小数。 在以 2 为基数的情况下， 1/10 是一个无限循环小数

@example
0.0001100110011001100110011001100110011001100110011...
@end example

在任何一个位置停下，你都只能得到一个近似值。因此，在今天的大部分架构上，浮点数都只能近似地使用二进制小数表示，对应分数的分子使用每 8 字节的前 53 位表示，分母则表示为 2 的幂次。在 1/10 这个例子中，相应的二进制分数是 @code{3602879701896397 / 2 ** 55} ，它很接近 1/10 ，但并不是 1/10 。

大部分用户都不会意识到这个差异的存在，因为 Python 只会打印计算机中存储的二进制值的十进制近似值。在大部分计算机中，如果 Python 想把 0.1 的二进制对应的精确十进制打印出来，将会变成这样

@example
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
@end example

这比大多数人认为有用的数字更多，因此Python通过显示舍入值来保持可管理的位数

@example
>>> 1 / 10
0.1
@end example

牢记，即使输出的结果看起来好像就是 1/10 的精确值，实际储存的值只是最接近 1/10 的计算机可表示的二进制分数。

有趣的是，有许多不同的十进制数共享相同的最接近的近似二进制小数。例如， @code{0.1} 、 @code{0.10000000000000001} 、 @code{0.1000000000000000055511151231257827021181583404541015625} 全都近似于 @code{3602879701896397 / 2 ** 55} 。由于所有这些十进制值都具有相同的近似值，因此可以显示其中任何一个，同时仍然保留不变的 @code{eval(repr(x)) == x} 。

在历史上，Python 提示符和内置的 @ref{8c3,,repr()} 函数会选择具有 17 位有效数字的来显示，即 @code{0.10000000000000001}。 从 Python 3.1 开始，Python（在大多数系统上）现在能够选择这些表示中最短的并简单地显示 @code{0.1} 。

请注意这种情况是二进制浮点数的本质特性：它不是 Python 的错误，也不是你代码中的错误。 你会在所有支持你的硬件中的浮点运算的语言中发现同样的情况（虽然某些语言在默认状态或所有输出模块下都不会 @emph{显示} 这种差异）。

想要更美观的输出，你可能会希望使用字符串格式化来产生限定长度的有效位数:

@example
>>> format(math.pi, '.12g')  # give 12 significant digits
'3.14159265359'

>>> format(math.pi, '.2f')   # give 2 digits after the point
'3.14'

>>> repr(math.pi)
'3.141592653589793'
@end example

必须重点了解的是，这在实际上只是一个假象：你只是将真正的机器码值进行了舍入操作再 @emph{显示} 而已。

一个假象还可能导致另一个假象。 例如，由于这个 0.1 并非真正的 1/10，将三个 0.1 的值相加也不一定能恰好得到 0.3:

@example
>>> .1 + .1 + .1 == .3
False
@end example

而且，由于这个 0.1 无法精确表示 1/10 的值而这个 0.3 也无法精确表示 3/10 的值，使用 @ref{d3d,,round()} 函数进行预先舍入也是没用的:

@example
>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False
@end example

虽然这些小数无法精确表示其所要代表的实际值，@ref{d3d,,round()} 函数还是可以用来“事后舍入”，使得实际的结果值可以做相互比较:

@example
>>> round(.1 + .1 + .1, 10) == round(.3, 10)
True
@end example

二进制浮点运算会造成许多这样的意外。 有关 "0.1" 的问题会在下面的 "表示性错误" 一节中更精确详细地描述。 请参阅 浮点数的危险性@footnote{https://www.lahey.com/float.htm} 了解有关其他常见意外现象的更完整介绍。

正如那篇文章的结尾所言，“对此问题并无简单的答案。” 但是也不必过于担心浮点数的问题！ Python 浮点运算中的错误是从浮点运算硬件继承而来，而在大多数机器上每次浮点运算得到的 2**53 数码位都会被作为 1 个整体来处理。 这对大多数任务来说都已足够，但你确实需要记住它并非十进制算术，且每次浮点运算都可能会导致新的舍入错误。

虽然病态的情况确实存在，但对于大多数正常的浮点运算使用来说，你只需简单地将最终显示的结果舍入为你期望的十进制数值即可得到你期望的结果。 @ref{206,,str()} 通常已足够，对于更精度的控制可参看 @ref{de8,,格式字符串语法} 中 @ref{5dd,,str.format()} 方法的格式描述符。

对于需要精确十进制表示的使用场景，请尝试使用 @ref{35,,decimal} 模块，该模块实现了适合会计应用和高精度应用的十进制运算。

另一种形式的精确运算由 @ref{81,,fractions} 模块提供支持，该模块实现了基于有理数的算术运算（因此可以精确表示像 1/3 这样的数值）。

如果你是浮点运算的重度用户则你应当了解一下 NumPy 包以及由 SciPy 项目所提供的许多其他数字和统计运算包。 参见 <@indicateurl{https://scipy.org}>。

Python 也提供了一些工具，可以在你真的 @emph{想要} 知道一个浮点数精确值的少数情况下提供帮助。 例如 @ref{1488,,float.as_integer_ratio()} 方法会将浮点数表示为一个分数:

@example
>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)
@end example

由于这是一个精确的比值，它可以被用来无损地重建原始值:

@example
>>> x == 3537115888337719 / 1125899906842624
True
@end example

@ref{1489,,float.hex()} 方法会以十六进制（以 16 为基数）来表示浮点数，同样能给出保存在你的计算机中的精确值:

@example
>>> x.hex()
'0x1.921f9f01b866ep+1'
@end example

这种精确的十六进制表示法可被用来精确地重建浮点值:

@example
>>> x == float.fromhex('0x1.921f9f01b866ep+1')
True
@end example

由于这种表示法是精确的，它适用于跨越不同版本（平台无关）的 Python 移植数值，以及与支持相同格式的其他语言（例如 Java 和 C99）交换数据.

另一个有用的工具是 @ref{e0c,,math.fsum()} 函数，它有助于减少求和过程中的精度损失。 它会在数值被添加到总计值的时候跟踪“丢失的位”。 这可以很好地保持总计值的精确度， 使得错误不会积累到能影响结果总数的程度:

@example
>>> sum([0.1] * 10) == 1.0
False
>>> math.fsum([0.1] * 10) == 1.0
True
@end example

@menu
* 表示性错误:: 

@end menu

@node 表示性错误,,,浮点算术：争议和限制
@anchor{tutorial/floatingpoint representation-error}@anchor{148a}@anchor{tutorial/floatingpoint tut-fp-error}@anchor{148b}
@subsection 表示性错误


本小节将详细解释 "0.1" 的例子，并说明你可以怎样亲自对此类情况进行精确分析。 假定前提是已基本熟悉二进制浮点表示法。

@emph{表示性错误} 是指某些（其实是大多数）十进制小数无法以二进制（以 2 为基数的计数制）精确表示这一事实造成的错误。 这就是为什么 Python（或者 Perl、C、C++、Java、Fortran 以及许多其他语言）经常不会显示你所期待的精确十进制数值的主要原因。

为什么会这样？ 1/10 是无法用二进制小数精确表示的。 目前（2000年11月）几乎所有使用 IEEE-754 浮点运算标准的机器以及几乎所有系统平台都会将 Python 浮点数映射为 IEEE-754 “双精度类型”。 754 双精度类型包含 53 位精度，因此在输入时，计算会尽量将 0.1 转换为以 @emph{J}/2**@emph{N} 形式所能表示的最接近分数，其中 @emph{J} 为恰好包含 53 个二进制位的整数。 重新将

@example
1 / 10 ~= J / (2**N)
@end example

写为

@example
J ~= 2**N / 10
@end example

并且由于 @emph{J} 恰好有 53 位 (即 @code{>= 2**52} 但 @code{< 2**53})，@emph{N} 的最佳值为 56:

@example
>>> 2**52 <=  2**56 // 10  < 2**53
True
@end example

也就是说，56 是唯一的 @emph{N} 值能令 @emph{J} 恰好有 53 位。 这样 @emph{J} 的最佳可能值就是经过舍入的商:

@example
>>> q, r = divmod(2**56, 10)
>>> r
6
@end example

由于余数超过 10 的一半，最佳近似值可通过四舍五入获得:

@example
>>> q+1
7205759403792794
@end example

这样在 754 双精度下 1/10 的最佳近似值为:

@example
7205759403792794 / 2 ** 56
@end example

分子和分母都除以二则结果小数为:

@example
3602879701896397 / 2 ** 55
@end example

请注意由于我们做了向上舍入，这个结果实际上略大于 1/10；如果我们没有向上舍入，则商将会略小于 1/10。 但无论如何它都不会是 @emph{精确的} 1/10！

因此计算永远不会“看到”1/10：它实际看到的就是上面所给出的小数，它所能达到的最佳 754 双精度近似值:

@example
>>> 0.1 * 2 ** 55
3602879701896397.0
@end example

如果我们将该小数乘以 10**55，我们可以看到该值输出为 55 位的十进制数:

@example
>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625
@end example

这意味着存储在计算机中的确切数值等于十进制数值 0.1000000000000000055511151231257827021181583404541015625。 许多语言（包括较旧版本的 Python）都不会显示这个完整的十进制数值，而是将结果舍入为 17 位有效数字:

@example
>>> format(0.1, '.17f')
'0.10000000000000001'
@end example

@ref{81,,fractions} 和 @ref{35,,decimal} 模块可令进行此类计算更加容易:

@example
>>> from decimal import Decimal
>>> from fractions import Fraction

>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

>>> format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'
@end example

@node 附录,,浮点算术：争议和限制,Python 教程
@anchor{tutorial/appendix doc}@anchor{148c}@anchor{tutorial/appendix appendix}@anchor{148d}@anchor{tutorial/appendix tut-appendix}@anchor{148e}
@section 附录


@menu
* 交互模式: 交互模式<2>. 

@end menu

@node 交互模式<2>,,,附录
@anchor{tutorial/appendix interactive-mode}@anchor{148f}@anchor{tutorial/appendix tut-interac}@anchor{1373}
@subsection 交互模式


@menu
* 错误处理:: 
* 可执行的Python脚本:: 
* 交互式启动文件:: 
* 定制模块:: 

@end menu

@node 错误处理,可执行的Python脚本,,交互模式<2>
@anchor{tutorial/appendix error-handling}@anchor{1490}@anchor{tutorial/appendix tut-error}@anchor{1491}
@subsubsection 错误处理


当发生错误时，解释器会打印错误信息和错误堆栈。在交互模式下，将返回到主命令提示符；如果输入内容来自文件，在打印错误堆栈之后，程序会以非零状态退出。（这里所说的错误不包括 @ref{e3f,,try} 语句中由 @ref{c19,,except} 所捕获的异常。）有些错误是无条件致命的，会导致程序以非零状态退出；比如内部逻辑矛盾或内存耗尽。所有错误信息都会被写入标准错误流；而命令的正常输出则被写入标准输出流。

将中断字符（通常为 @code{Control-C} 或 @code{Delete} ）键入主要或辅助提示会取消输入并返回主提示符。 @footnote{@w{(1)} 
GNU Readline 包的问题可能会阻止这种情况。
} 在执行命令时键入中断引发的 @ref{2d3,,KeyboardInterrupt} 异常，可以由 @ref{e3f,,try} 语句处理。

@node 可执行的Python脚本,交互式启动文件,错误处理,交互模式<2>
@anchor{tutorial/appendix executable-python-scripts}@anchor{1492}@anchor{tutorial/appendix tut-scripts}@anchor{1378}
@subsubsection 可执行的Python脚本


在BSD等类Unix系统上，Python脚本可以直接执行，就像shell脚本一样，第一行添加:

@example
#!/usr/bin/env python3.5
@end example

（假设解释器位于用户的 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} ）脚本的开头，并将文件设置为可执行。 @code{#!} 必须是文件的前两个字符。在某些平台上，第一行必须以Unix样式的行结尾（@code{'\n'}）结束，而不是以Windows（@code{'\r\n'}）行结尾。请注意，散列或磅字符 @code{'#'} 在Python中代表注释开始。

可以使用 @code{chmod} 命令为脚本提供可执行模式或权限。

@example
$ chmod +x myscript.py
@end example

在Windows系统上，没有“可执行模式”的概念。 Python安装程序自动将 @code{.py} 文件与 @code{python.exe} 相关联，这样双击Python文件就会将其作为脚本运行。扩展也可以是 @code{.pyw} ，在这种情况下，会隐藏通常出现的控制台窗口。

@node 交互式启动文件,定制模块,可执行的Python脚本,交互模式<2>
@anchor{tutorial/appendix the-interactive-startup-file}@anchor{1493}@anchor{tutorial/appendix tut-startup}@anchor{1494}
@subsubsection 交互式启动文件


当您以交互方式使用Python时，每次启动解释器时都会执行一些标准命令，这通常很方便。您可以通过将名为 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 的环境变量设置为包含启动命令的文件名来实现。这类似于Unix shell的 @code{.profile} 功能。

此文件只会在交互式会话时读取，而非在 Python 从脚本读取指令或是在给定 @code{/dev/tty} 为指令的明确来源时（后者反而表现得像是一个交互式会话）。 该文件执行时所在的命名空间与交互式指令相同，所以它定义或导入的对象可以在交互式会话中直接使用。 你也可以在该文件中更改提示符 @code{sys.ps1} 和 @code{sys.ps2}。

如果你想从当前目录中读取一个额外的启动文件，你可以使用像 @code{if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())} 这样的代码在全局启动文件中对它进行编程。如果要在脚本中使用启动文件，则必须在脚本中显式执行此操作:

@example
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)
@end example

@node 定制模块,,交互式启动文件,交互模式<2>
@anchor{tutorial/appendix the-customization-modules}@anchor{1495}@anchor{tutorial/appendix tut-customize}@anchor{1496}
@subsubsection 定制模块


Python提供了两个钩子来让你自定义它：@code{sitecustomize} 和 @code{usercustomize}。要查看其工作原理，首先需要找到用户site-packages目录的位置。启动Python并运行此代码:

@example
>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.5/site-packages'
@end example

现在，您可以在该目录中创建一个名为 @code{usercustomize.py} 的文件，并将所需内容放入其中。它会影响Python的每次启动，除非它以 @ref{de3,,-s} 选项启动，以禁用自动导入。

@code{sitecustomize} 以相同的方式工作，但通常由计算机管理员在全局 site-packages 目录中创建，并在 @code{usercustomize} 之前被导入。有关详情请参阅 @ref{eb,,site} 模块的文档。

@node 安装和使用 Python,Python 语言参考手册,Python 教程,Top
@anchor{using/index doc}@anchor{1497}@anchor{using/index python-setup-and-usage}@anchor{1498}@anchor{using/index using-index}@anchor{1499}
@chapter 安装和使用 Python


这一部分文档专门介绍在不同平台上配置Python环境的一般方法，解释器的调用以及方便使用Python的技巧。

@c ATTENTION: You probably should update Misc/python.man, too, if you modify
@c this file.

@menu
* 命令行与环境:: 
* 在Unix平台中使用Python:: 
* 在Windows上使用 Python:: 
* 在 Mac 上使用 Python:: 
* 编辑器和集成开发环境:: 

@end menu

@node 命令行与环境,在Unix平台中使用Python,,安装和使用 Python
@anchor{using/cmdline doc}@anchor{149a}@anchor{using/cmdline command-line-and-environment}@anchor{149b}@anchor{using/cmdline using-on-general}@anchor{1106}
@section 命令行与环境


为获取各种设置信息，CPython 解析器会扫描命令行与环境。

@strong{CPython implementation detail:} 其他实现的命令行方案可能会有所不同。 详见 @ref{149c,,其他实现}。

@menu
* 命令行:: 
* 环境变量:: 

@end menu

@node 命令行,环境变量,,命令行与环境
@anchor{using/cmdline command-line}@anchor{149d}@anchor{using/cmdline using-on-cmdline}@anchor{a19}
@subsection 命令行


调用 Python 时，可以指定下列任意选项：

@example
python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
@end example

最常见的用例是启动时执行脚本：

@example
python myscript.py
@end example

@menu
* 接口选项:: 
* 通用选项:: 
* 其他选项:: 
* 不应当使用的选项:: 

@end menu

@node 接口选项,通用选项,,命令行
@anchor{using/cmdline interface-options}@anchor{149e}@anchor{using/cmdline using-on-interface-options}@anchor{149f}
@subsubsection 接口选项


解释器接口类似于 UNIX shell，但提供了额外的调用方法:


@itemize *

@item 
用连接到 tty 设备的标准输入调用时，会提示输入并执行命令，输入 EOF （文件结束符，UNIX 中按 @code{Ctrl-D}，Windows 中按 @code{Ctrl-Z, Enter}）时终止。

@item 
用文件名参数或以标准输入文件调用时，读取，并执行该脚本文件。

@item 
用目录名参数调用时，从该目录读取、执行适当名称的脚本。

@item 
用 @code{-c command} 调用时，执行 @emph{command} 表示的 Python 语句。@emph{command} 可以包含用换行符分隔的多条语句。注意，前导空白字符在 Python 语句中非常重要！

@item 
用 @code{-m module-name} 调用时，在 Python 模块路径中查找指定的模块，并将其作为脚本执行。
@end itemize

非交互模式下，先解析全部输入，再执行。

接口选项会终结解释器读入的选项列表，所有后续参数都在 @ref{cce,,sys.argv} 里 -- 注意，首个元素，即下标为零的元素（@code{sys.argv[0]}）是表示程序来源的字符串。

@geindex command line option; -c <command>
@anchor{using/cmdline cmdoption-c}@anchor{136f}
@deffn {程序选项} @w{-}c <command>

执行 @emph{command} 中的 Python 代码。@emph{command} 可以是一条语句，也可以是用换行符分隔的多条语句，其中，前导空白字符与普通模块代码中的作用一样。

使用此选项时，@ref{cce,,sys.argv} 的首个元素为 @code{"-c"}，并会把当前目录加入至 @ref{262,,sys.path} 开头（让该目录中的模块作为顶层模块导入）。

使用 @code{command} 参数会引发 @ref{fec,,审计事件} @code{cpython.run_command} 。
@end deffn

@geindex command line option; -m <module-name>
@anchor{using/cmdline cmdoption-m}@anchor{44c}
@deffn {程序选项} @w{-}m <module@w{-}name>

在 @ref{262,,sys.path} 中搜索指定模块，并以 @ref{1,,__main__} 模块执行其内容。

该参数是 @emph{模块名}，请勿输入文件扩展名（@code{.py}）。模块名应为有效的绝对 Python 模块名，但本实现对此不作强制要求（例如，允许使用含连字符 @code{-} 的名称）。

包名称（包括命名空间包）也允许使用。使用包名称而不是普通模块名时，解释器把 @code{<pkg>.__main__} 作为主模块执行。此行为特意被设计为与作为脚本参数传递给解释器的目录和 zip 文件的处理方式类似。

@cartouche
@quotation 注解 
此选项不适用于内置模块和以 C 编写的扩展模块，因为它们并没有对应的 Python 模块文件。 但是它仍然适用于预编译的模块，即使没有可用的初始源文件。
@end quotation
@end cartouche

如果给出此选项，@ref{cce,,sys.argv} 的首个元素将为模块文件的完整路径 (在定位模块文件期间，首个元素将设为 @code{"-m"})。 与 @ref{136f,,-c} 选项一样，当前目录将被加入 @ref{262,,sys.path} 的开头。

@ref{232,,-I} 选项可用来在隔离模式下运行脚本，此模式中 @ref{262,,sys.path} 既不包含当前目录也不包含用户的 site-packages 目录。 所有 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} 环境变量也会被忽略。

许多标准库模块都包含在执行时，以脚本方式调用的代码。例如 @ref{10d,,timeit} 模块：

@example
python -m timeit -s 'setup here' 'benchmarked code here'
python -m timeit -h # for details
@end example

使用 @code{module-name} 参数会引发 @ref{fec,,审计事件} @code{cpython.run_module} 。


@subsubheading 参见



@table @asis

@item @ref{f7b,,runpy.run_module()}

Python 代码可以直接使用的等效功能
@end table

@geindex Python 提高建议; PEP 338
PEP 338@footnote{https://www.python.org/dev/peps/pep-0338} -- 将模块作为脚本执行



在 3.1 版更改: 提供包名称来运行 @code{__main__} 子模块。



在 3.4 版更改: 同样支持命名空间包

@end deffn
@anchor{using/cmdline cmdarg-dash}@anchor{14a0}

@deffn {Describe} @w{-}

从标准输入 (@ref{427,,sys.stdin}) 读取命令。标准输入为终端时，使用 @ref{ee9,,-i}。

使用此选项时，@ref{cce,,sys.argv} 的第一个元素是 @code{"-"}， 同时，把当前目录加入 @ref{262,,sys.path} 开头。

没有参数时，会触发  @ref{fec,,审计事件} @code{cpython.run_stdin} 。
@end deffn
@anchor{using/cmdline cmdarg-script}@anchor{14a1}

@deffn {Describe} <script>

执行 @emph{script} 中的 Python 代码，该参数应为（绝对或相对）文件系统路径，指向 Python 文件、包含 @code{__main__.py} 文件的目录，或包含 @code{__main__.py} 文件的 zip 文件。

给出此选项时，@ref{cce,,sys.argv} 的第一个元素就是在命令行中指定的脚本名称。

如果脚本名称直接指向 Python 文件，则把该文件所在目录加入 @ref{262,,sys.path} 的开头，并且把该文件当作 @ref{1,,__main__} 模块来执行。

如果脚本名称指向目录或 zip 文件，则把脚本名加入 @ref{262,,sys.path} 的开头，并把该位置中的 @code{__main__.py} 文件当作 @ref{1,,__main__} 模块来执行。

@ref{232,,-I} 选项以隔离模式运行脚本，此模式中，@ref{262,,sys.path} 既不包含脚本目录，也不包含用户的 site-packages 目录，还会忽略所有 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} 环境变量。

使用 @code{filename} 参数会引发  @ref{fec,,审计事件} @code{cpython.run_file} 。


@subsubheading 参见



@table @asis

@item @ref{d81,,runpy.run_path()}

Python 代码可以直接使用的等效功能
@end table

@end deffn

未给出接口选项时，使用 @ref{ee9,,-i}，@code{sys.argv[0]} 为空字符串 (@code{""})，并把当前目录加至 @ref{262,,sys.path} 的开头。 此外，如果系统支持，还能自动启用 tab 补全和历史编辑（参见 @ref{9d5,,Readline 配置}）。


@subsubheading 参见


@ref{136b,,调用解释器}



在 3.4 版更改: 自动启用 tab 补全和历史编辑。


@node 通用选项,其他选项,接口选项,命令行
@anchor{using/cmdline generic-options}@anchor{14a2}
@subsubsection 通用选项


@geindex command line option; -?
@geindex command line option; -h
@geindex command line option; --help
@anchor{using/cmdline cmdoption}@anchor{e59}
@deffn {程序选项} @w{-}?
@anchor{using/cmdline cmdoption-h}@anchor{14a3}
@deffnx {程序选项} @w{-}h
@anchor{using/cmdline cmdoption-help}@anchor{e58}
@deffnx {程序选项} @w{-}@w{-}help

输出所有命令行选项的简介。
@end deffn

@geindex command line option; -V
@geindex command line option; --version
@anchor{using/cmdline cmdoption-v}@anchor{6d3}
@deffn {程序选项} @w{-}V
@anchor{using/cmdline cmdoption-version}@anchor{6d2}
@deffnx {程序选项} @w{-}@w{-}version

输出 Python 版本号并退出。示例如下：

@example
Python 3.8.0b2+
@end example

输入两次 @code{V} 选项时，输出更多构建信息，例如：

@example
Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
[GCC 6.2.0 20161005]
@end example


3.6 新版功能: @code{-VV} 选项。

@end deffn

@node 其他选项,不应当使用的选项,通用选项,命令行
@anchor{using/cmdline miscellaneous-options}@anchor{14a4}@anchor{using/cmdline using-on-misc-options}@anchor{a1a}
@subsubsection 其他选项


@geindex command line option; -b
@anchor{using/cmdline cmdoption-b}@anchor{522}
@deffn {程序选项} @w{-}b

用 @ref{206,,str} 与 @ref{172,,bytes} 或 @ref{173,,bytearray} 对比， 或对比 @ref{172,,bytes} 与 @ref{205,,int} 时，会发出警告。重复给出该选项（@code{-bb}）时会报错。


在 3.5 版更改: 影响 @ref{172,,bytes} 与 @ref{205,,int} 的比较。

@end deffn

@geindex command line option; -B
@anchor{using/cmdline id1}@anchor{e06}
@deffn {程序选项} @w{-}B

给出此选项时，Python 不在导入源模块时写入 @code{.pyc} 文件。另请参阅 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE}。
@end deffn

@geindex command line option; --check-hash-based-pycs default|always|never
@anchor{using/cmdline cmdoption-check-hash-based-pycs}@anchor{14a5}
@deffn {程序选项} @w{-}@w{-}check@w{-}hash@w{-}based@w{-}pycs default|always|never

控制基于哈希值的 @code{.pyc} 文件的验证行为。 参见 @ref{442,,已缓存字节码的失效}。 当设为 @code{default} 时，已选定和未选定的基于哈希值的字节码缓存文件将根据其默认语义进行验证。 当设为 @code{always} 时，所有基于哈希值的 @code{.pyc} 文件，不论是已选定还是未选定的都将根据其对应的源文件进行验证。 当设为 @code{never} 时，基于哈希值的 @code{.pyc} 文件将不会根据其对应的源文件进行验证。

基于时间戳的 @code{.pyc} 文件的语义不会受此选项影响。
@end deffn

@geindex command line option; -d
@anchor{using/cmdline cmdoption-d}@anchor{14a6}
@deffn {程序选项} @w{-}d

开启解析器调试输出（限专家使用，依赖于编译选项）。 另请参阅 
@geindex PYTHONDEBUG
@geindex 环境变量; PYTHONDEBUG
@ref{14a7,,PYTHONDEBUG}。
@end deffn

@geindex command line option; -E
@anchor{using/cmdline cmdoption-e}@anchor{231}
@deffn {程序选项} @w{-}E

忽略所有 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} 环境变量，例如，已设置的 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 和 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME}。
@end deffn

@geindex command line option; -i
@anchor{using/cmdline cmdoption-i}@anchor{ee9}
@deffn {程序选项} @w{-}i

脚本是第一个参数，或使用 @ref{136f,,-c} 时，即便 @ref{427,,sys.stdin} 不是终端，执行脚本或命令后，也会进入交互模式。不读取 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 文件。

本选项用于，脚本触发异常时，检查全局变量或堆栈回溯。 详见 
@geindex PYTHONINSPECT
@geindex 环境变量; PYTHONINSPECT
@ref{ee8,,PYTHONINSPECT}。
@end deffn

@geindex command line option; -I
@anchor{using/cmdline id2}@anchor{232}
@deffn {程序选项} @w{-}I

在隔离模式下运行 Python。 这将同时应用 -E 和 -s。 在隔离模式下 @ref{262,,sys.path} 既不包含脚本所在目录也不包含用户的 site-packages 目录。 所有 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} 环境变量也会被忽略。 还可以施加更进一步的限制以防止用户注入恶意代码。


3.4 新版功能.

@end deffn

@geindex command line option; -O
@anchor{using/cmdline cmdoption-o}@anchor{788}
@deffn {程序选项} @w{-}O

移除 assert 语句以及任何以 @ref{1180,,__debug__} 的值作为条件的代码。 通过在 @code{.pyc} 扩展名之前添加 @code{.opt-1} 来扩充已编译文件 (@ref{713,,bytecode}) 的文件名  (参见 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488})。 另请参阅 
@geindex PYTHONOPTIMIZE
@geindex 环境变量; PYTHONOPTIMIZE
@ref{14a8,,PYTHONOPTIMIZE}。


在 3.5 版更改: 依据 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} 修改 @code{.pyc} 文件名。

@end deffn

@geindex command line option; -OO
@anchor{using/cmdline cmdoption-oo}@anchor{789}
@deffn {程序选项} @w{-}OO

在启用 @ref{788,,-O} 的同时丢弃文档字符串。 通过在 @code{.pyc} 扩展名之前添加 @code{.opt-2} 来扩展已编译文件 (@ref{713,,bytecode}) 的文件名 (参见 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488})。


在 3.5 版更改: 依据 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} 修改 @code{.pyc} 文件名。

@end deffn

@geindex command line option; -q
@anchor{using/cmdline cmdoption-q}@anchor{14a9}
@deffn {程序选项} @w{-}q

即使在交互模式下也不显示版权和版本信息。


3.2 新版功能.

@end deffn

@geindex command line option; -R
@anchor{using/cmdline cmdoption-r}@anchor{1211}
@deffn {程序选项} @w{-}R

开启哈希随机化。 此选项权 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} 环境变量设置为 @code{0} 时起作用，因为哈希随机化是默认启用的。

在Python的早期版本中，此选项启用哈希随机化，将 str 和 bytes 的对象 @ref{455,,__hash__()} 的值 "加盐" 为不可预测的随机值。虽然它们在单个Python进程中保持不变，但是在重复调用的Python进程之间它们是不可预测的。

哈希随机化旨在针对由精心选择的输入引起的拒绝服务攻击提供防护，这种输入利用了构造 dict 在最坏情况下的性能即 O(n@w{^2}) 复杂度。 请参阅 @indicateurl{http://www.ocert.org/advisories/ocert-2011-003.html} 了解详情。

@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} 允许你为哈希种子密码设置一个固定值。


在 3.7 版更改: 此选项不会再被忽略。



3.2.3 新版功能.

@end deffn

@geindex command line option; -s
@anchor{using/cmdline cmdoption-s}@anchor{de3}
@deffn {程序选项} @w{-}s

不要将 @ref{14aa,,用户 site-packages 目录} 添加到 @ref{262,,sys.path}。


@subsubheading 参见


@geindex Python 提高建议; PEP 370
PEP 370@footnote{https://www.python.org/dev/peps/pep-0370} -- 分用户的 site-packages 目录

@end deffn

@geindex command line option; -S
@anchor{using/cmdline id3}@anchor{c00}
@deffn {程序选项} @w{-}S

禁用 @ref{eb,,site} 的导入及其所附带的基于站点对 @ref{262,,sys.path} 的操作。 如果 @ref{eb,,site} 会在稍后被显式地导入也会禁用这些操作 (如果你希望触发它们则应调用 @ref{14ab,,site.main()})。
@end deffn

@geindex command line option; -u
@anchor{using/cmdline cmdoption-u}@anchor{10e6}
@deffn {程序选项} @w{-}u

强制 stdout 和 stderr 流不使用缓冲。 此选项对 stdin 流无影响。

另请参阅 
@geindex PYTHONUNBUFFERED
@geindex 环境变量; PYTHONUNBUFFERED
@ref{10e7,,PYTHONUNBUFFERED}。


在 3.7 版更改: stdout 和 stderr 流在文本层现在不使用缓冲。

@end deffn

@geindex command line option; -v
@anchor{using/cmdline id4}@anchor{e55}
@deffn {程序选项} @w{-}v

每当一个模块被初始化时打印一条信息，显示其加载位置（文件名或内置模块）。 当重复给出时 (@code{-vv})，为搜索模块时所检查的每个文件都打印一条消息。 此外还提供退出时有关模块清理的信息A。 另请参阅 
@geindex PYTHONVERBOSE
@geindex 环境变量; PYTHONVERBOSE
@ref{14ac,,PYTHONVERBOSE}。
@end deffn
@anchor{using/cmdline using-on-warnings}@anchor{14ad}
@geindex command line option; -W arg
@anchor{using/cmdline cmdoption-w}@anchor{15b}
@deffn {程序选项} @w{-}W arg

警告控制。 Python 的警告机制在默认情况下会向 @ref{1eb,,sys.stderr} 打印警告消息。 典型的警告消息具有如下形式：

@example
file:line: category: message
@end example

默认情况下，每个警告都对于其发生所在的每个源行都会打印一次。 此选项可控制警告打印的频繁程度。

可以给出多个 @ref{15b,,-W} 选项；当某个警告能与多个选项匹配时，将执行最后一个匹配选项的操作。 无效的 @ref{15b,,-W} 选项将被忽略（但是，在发出第一个警告时会打印有关无效选项的警告消息）。

警告也可以使用 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS} 环境变量以及使用 @ref{12f,,warnings} 模块在 Python 程序内部进行控制。

最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使是在默认情况下会忽略的那些警告):

@example
-Wdefault  # Warn once per call location
-Werror    # Convert to exceptions
-Walways   # Warn every time
-Wmodule   # Warn once per calling module
-Wonce     # Warn once per Python process
-Wignore   # Never warn
@end example

操作名称可以根据需要进行缩写 (例如 @code{-Wi}, @code{-Wd}, @code{-Wa}, @code{-We})，解释器将会把它们解析为适当的操作名称。

请参阅 @ref{15d,,警告过滤器} 和 @ref{14ae,,警告过滤器的介绍} 了解更多细节。
@end deffn

@geindex command line option; -x
@anchor{using/cmdline cmdoption-x}@anchor{14af}
@deffn {程序选项} @w{-}x

跳过源中第一行，以允许使用非 Unix 形式的 @code{#!cmd}。 这适用于 DOS 专属的破解操作。
@end deffn

@geindex command line option; -X
@anchor{using/cmdline id5}@anchor{297}
@deffn {程序选项} @w{-}X

保留用于各种具体实现专属的选项。 CPython 目前定义了下列可用的值：


@itemize *

@item 
@code{-X faulthandler} 启用 @ref{7b,,faulthandler}；

@item 
@code{-X oldparser}: 启用传统的 LL(1) 解析器。 另请参阅 
@geindex PYTHONOLDPARSER
@geindex 环境变量; PYTHONOLDPARSER
@ref{14b0,,PYTHONOLDPARSER} 和 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617}。

@item 
@code{-X showrefcount} 当程序结束或在交互解释器中的每条语句之后输出总引用计数和已使用内存块计数。 此选项仅在调试版本中有效。

@item 
@code{-X tracemalloc} 使用 @ref{11d,,tracemalloc} 模块启动对 Python 内存分配的跟踪。 默认情况下，只有最近的帧会保存在跟踪的回溯信息中。 使用 @code{-X tracemalloc=NFRAME} 以启动限定回溯 @emph{NFRAME} 帧的跟踪。 请参阅 @ref{14b1,,tracemalloc.start()} 了解详情。

@item 
@code{-X int_max_str_digits} configures the @ref{288,,integer string conversion length limitation}.  See also
@geindex PYTHONINTMAXSTRDIGITS
@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@ref{f61,,PYTHONINTMAXSTRDIGITS}.

@item 
@code{-X importtime} 显示每次导入耗费的时间。 它会显示模块名称，累计时间（包括嵌套的导入）和自身时间（排除嵌套的导入）。 请注意它的输出在多线程应用程序中可能会出错。 典型用法如 @code{python3 -X importtime -c 'import asyncio'}。 另请参阅 
@geindex PYTHONPROFILEIMPORTTIME
@geindex 环境变量; PYTHONPROFILEIMPORTTIME
@ref{44d,,PYTHONPROFILEIMPORTTIME}。

@item 
@code{-X dev}: 启用 @ref{160,,Python 开发模式}，引入在默认情况下启用会导致开销过大的运行时检查。

@item 
@code{-X utf8} 为操作系统接口启用 UTF-8 模式，覆盖默认的区域感知模式。 @code{-X utf8=0} 显式地禁用 UTF-8 模式（即使在它应当被自动激活的时候）。 请参阅 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} 了解详情。

@item 
@code{-X pycache_prefix=PATH} 允许将 @code{.pyc} 文件写入以给定目录为根的并行树，而不是代码树。另见 
@geindex PYTHONPYCACHEPREFIX
@geindex 环境变量; PYTHONPYCACHEPREFIX
@ref{296,,PYTHONPYCACHEPREFIX} 。
@end itemize

它还允许传入任意值并通过 @ref{14b2,,sys._xoptions} 字典来提取这些值。


在 3.2 版更改: 增加了 @ref{297,,-X} 选项。



3.3 新版功能: @code{-X faulthandler} 选项。



3.4 新版功能: @code{-X showrefcount} 与 @code{-X tracemalloc} 选项。



3.6 新版功能: @code{-X showalloccount} 选项。



3.7 新版功能: @code{-X importtime}, @code{-X dev} 与 @code{-X utf8} 选项。



3.8 新版功能: @code{-X pycache_prefix} 选项。 @code{-X dev} 选项现在在 @ref{313,,io.IOBase} 析构函数中记录 @code{close()} 异常。



在 3.9 版更改: 使用 @code{-X dev} 选项，在字符串编码和解码操作时检查 @emph{encoding} 和 @emph{errors} 参数。

The @code{-X showalloccount} 选项已被移除。



3.9.14 新版功能: The @code{-X int_max_str_digits} option.



Deprecated since version 3.9, will be removed in version 3.10: The @code{-X oldparser} 选项。

@end deffn

@node 不应当使用的选项,,其他选项,命令行
@anchor{using/cmdline options-you-shouldn-t-use}@anchor{14b3}
@subsubsection 不应当使用的选项


@geindex command line option; -J
@anchor{using/cmdline cmdoption-j}@anchor{e05}
@deffn {程序选项} @w{-}J

保留给 Jython@footnote{http://www.jython.org/} 使用。
@end deffn

@node 环境变量,,命令行,命令行与环境
@anchor{using/cmdline environment-variables}@anchor{14b4}@anchor{using/cmdline using-on-envvars}@anchor{14b5}
@subsection 环境变量


这些环境变量会影响 Python 的行为，它们是在命令行开关之前被处理的，但 -E 或 -I 除外。 根据约定，当存在冲突时命令行开关会覆盖环境变量的设置。

@geindex 环境变量; PYTHONHOME
@anchor{using/cmdline envvar-PYTHONHOME}@anchor{5d9}
@deffn {环境变量} PYTHONHOME

更改标准 Python 库的位置。 默认情况下库是在 @code{@emph{prefix}/lib/python@emph{version}} 和 @code{@emph{exec_prefix}/lib/python@emph{version}} 中搜索，其中 @code{@emph{prefix}} 和 @code{@emph{exec_prefix}} 是由安装位置确定的目录，默认都位于 @code{/usr/local}。

当 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 被设为单个目录时，它的值会同时替代 @code{@emph{prefix}} 和 @code{@emph{exec_prefix}}。 要为两者指定不同的值，请将 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 设为 @code{@emph{prefix}:@emph{exec_prefix}}。
@end deffn

@geindex 环境变量; PYTHONPATH
@anchor{using/cmdline envvar-PYTHONPATH}@anchor{a3d}
@deffn {环境变量} PYTHONPATH

增加模块文件默认搜索路径。 所用格式与终端的 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 相同：一个或多个由 @ref{14b6,,os.pathsep} 分隔的目录路径名称（例如 Unix 上用冒号而在 Windows 上用分号）。 默认忽略不存在的目录。

除了普通目录之外，单个 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 条目可以引用包含纯Python模块的zip文件（源代码或编译形式）。无法从zip文件导入扩展模块。

默认索引路径依赖于安装路径，但通常都是以 @code{@emph{prefix}/lib/python@emph{version}} 开始 (参见上文中的 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME})。 它 @emph{总是} 会被添加到 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH}。

有一个附加目录将被插入到索引路径的 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 之前，正如上文中 @ref{149f,,接口选项} 所描述的。 搜索路径可以在 Python 程序内作为变量 @ref{262,,sys.path} 来进行操作。
@end deffn

@geindex 环境变量; PYTHONPLATLIBDIR
@anchor{using/cmdline envvar-PYTHONPLATLIBDIR}@anchor{1076}
@deffn {环境变量} PYTHONPLATLIBDIR

如果它被设为非空字符串，则会覆盖 @ref{1ea,,sys.platlibdir} 值。


3.9 新版功能.

@end deffn

@geindex 环境变量; PYTHONSTARTUP
@anchor{using/cmdline envvar-PYTHONSTARTUP}@anchor{9d4}
@deffn {环境变量} PYTHONSTARTUP

这如果是一个可读文件的名称，该文件中的 Python 命令会在交互模式的首个提示符显示之前被执行。 该文件会在与交互式命令执行所在的同一命名空间中被执行，因此其中所定义或导入的对象可以在交互式会话中无限制地使用。 你还可以在这个文件中修改提示符 @ref{14b7,,sys.ps1} 和 @ref{14b8,,sys.ps2} 以及钩子 @ref{9d3,,sys.__interactivehook__}。

使用 @code{filename} 参数会引发 @ref{fec,,审计事件} @code{cpython.run_startup} 。
@end deffn

@geindex 环境变量; PYTHONOPTIMIZE
@anchor{using/cmdline envvar-PYTHONOPTIMIZE}@anchor{14a8}
@deffn {环境变量} PYTHONOPTIMIZE

这如果被设为一个非空字符串，它就相当于指定 @ref{788,,-O} 选项。 如果设为一个整数，则它就相当于多次指定 @ref{788,,-O}。
@end deffn

@geindex 环境变量; PYTHONBREAKPOINT
@anchor{using/cmdline envvar-PYTHONBREAKPOINT}@anchor{42d}
@deffn {环境变量} PYTHONBREAKPOINT

此变量如果被设定，它会使用加点号的路径标记一个可调用对象。 包含该可调用对象的模块将被导入，随后该可调用对象将由 @ref{42c,,sys.breakpointhook()} 的默认实现来运行，后者自身将由内置的 @ref{414,,breakpoint()} 来调用。 如果未设定，或设定为空字符串，则它相当于值 "pdb.set_trace"。 将此变量设为字符串 "0" 会导致 @ref{42c,,sys.breakpointhook()} 的默认实现不做任何事而直接返回。


3.7 新版功能.

@end deffn

@geindex 环境变量; PYTHONDEBUG
@anchor{using/cmdline envvar-PYTHONDEBUG}@anchor{14a7}
@deffn {环境变量} PYTHONDEBUG

此变量如果被设为一个非空字符串，它就相当于指定 @ref{14a6,,-d} 选项。 如果设为一个整数，则它就相当于多次指定 @ref{14a6,,-d}。
@end deffn

@geindex 环境变量; PYTHONOLDPARSER
@anchor{using/cmdline envvar-PYTHONOLDPARSER}@anchor{14b0}
@deffn {环境变量} PYTHONOLDPARSER

如果将该选项设为非空字符串，则启用传统的 LL(1) 解析器。

另请参阅 @ref{297,,-X} @code{oldparser} 选项和 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617}。


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex 环境变量; PYTHONINSPECT
@anchor{using/cmdline envvar-PYTHONINSPECT}@anchor{ee8}
@deffn {环境变量} PYTHONINSPECT

此变量如果被设为一个非空字符串，它就相当于指定 @ref{ee9,,-i} 选项。

此变量也可由 Python 代码使用 @ref{c12,,os.environ} 来修改以在程序终结时强制检查模式。
@end deffn

@geindex 环境变量; PYTHONUNBUFFERED
@anchor{using/cmdline envvar-PYTHONUNBUFFERED}@anchor{10e7}
@deffn {环境变量} PYTHONUNBUFFERED

此变量如果被设为一个非空字符串，它就相当于指定 @ref{10e6,,-u} 选项。
@end deffn

@geindex 环境变量; PYTHONVERBOSE
@anchor{using/cmdline envvar-PYTHONVERBOSE}@anchor{14ac}
@deffn {环境变量} PYTHONVERBOSE

此变量如果被设为一个非空字符串，它就相当于指定 @ref{e55,,-v} 选项。 如果设为一个整数，则它就相当于多次指定 @ref{e55,,-v}。
@end deffn

@geindex 环境变量; PYTHONCASEOK
@anchor{using/cmdline envvar-PYTHONCASEOK}@anchor{233}
@deffn {环境变量} PYTHONCASEOK

如果设置了此变量，Python 将忽略 @ref{cef,,import} 语句中的大小写。 这仅在 Windows 和 macOS 上有效。
@end deffn

@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@anchor{using/cmdline envvar-PYTHONDONTWRITEBYTECODE}@anchor{e07}
@deffn {环境变量} PYTHONDONTWRITEBYTECODE

此变量如果被设为一个非空字符串，Python 将不会尝试在导入源模块时写入 @code{.pyc} 文件。 这相当于指定 @ref{e06,,-B} 选项。
@end deffn

@geindex 环境变量; PYTHONPYCACHEPREFIX
@anchor{using/cmdline envvar-PYTHONPYCACHEPREFIX}@anchor{296}
@deffn {环境变量} PYTHONPYCACHEPREFIX

如果设置了此选项，Python将在镜像目录树中的此路径中写入 @code{.pyc} 文件，而不是源树中的 @code{__pycache__} 目录中。这相当于指定 @ref{297,,-X} @code{pycache_prefix=PATH} 选项。


3.8 新版功能.

@end deffn

@geindex 环境变量; PYTHONHASHSEED
@anchor{using/cmdline envvar-PYTHONHASHSEED}@anchor{aad}
@deffn {环境变量} PYTHONHASHSEED

如果此变量未设置或设为 @code{random}，将使用一个随机值作为 str 和 bytes 对象哈希运算的种子。

如果 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} 被设为一个整数值，它将被作为固定的种子数用来生成哈希随机化所涵盖的类型的 hash() 结果。

它的目的是允许可复现的哈希运算，例如用于解释器本身的自我检测，或允许一组 python 进程共享哈希值。

该整数必须为一个 [0,4294967295] 范围内的十进制数。 指定数值 0 将禁用哈希随机化。


3.2.3 新版功能.

@end deffn

@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@anchor{using/cmdline envvar-PYTHONINTMAXSTRDIGITS}@anchor{f61}
@deffn {环境变量} PYTHONINTMAXSTRDIGITS

If this variable is set to an integer, it is used to configure the
interpreter's global @ref{288,,integer string conversion length limitation}.


3.9.14 新版功能.

@end deffn

@geindex 环境变量; PYTHONIOENCODING
@anchor{using/cmdline envvar-PYTHONIOENCODING}@anchor{a1d}
@deffn {环境变量} PYTHONIOENCODING

如果此变量在运行解释器之前被设置，它会覆盖通过 @code{encodingname:errorhandler} 语法设置的 stdin/stdout/stderr 所用编码。 @code{encodingname} 和 @code{:errorhandler} 部分都是可选项，与在 @ref{170,,str.encode()} 中的含义相同。

对于 stderr，@code{:errorhandler} 部分会被忽略；处理程序将总是为 @code{'backslashreplace'}。


在 3.4 版更改: “encodingname” 部分现在是可选的。



在 3.6 版更改: 在 Windows 上，对于交互式控制台缓冲区会忽略此变量所指定的编码，除非还指定了 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 环境变量; PYTHONLEGACYWINDOWSSTDIO
@ref{5fc,,PYTHONLEGACYWINDOWSSTDIO}。 通过标准流重定向的文件和管道则不受其影响。

@end deffn

@geindex 环境变量; PYTHONNOUSERSITE
@anchor{using/cmdline envvar-PYTHONNOUSERSITE}@anchor{de4}
@deffn {环境变量} PYTHONNOUSERSITE

如果设置了此变量，Python 将不会把 @ref{14aa,,用户 site-packages 目录} 添加到 @ref{262,,sys.path}。


@subsubheading 参见


@geindex Python 提高建议; PEP 370
PEP 370@footnote{https://www.python.org/dev/peps/pep-0370} -- 分用户的 site-packages 目录

@end deffn

@geindex 环境变量; PYTHONUSERBASE
@anchor{using/cmdline envvar-PYTHONUSERBASE}@anchor{de2}
@deffn {环境变量} PYTHONUSERBASE

定义 @ref{14b9,,用户基准目录}，它会在执行 @code{python setup.py install --user} 时被用来计算 @ref{14aa,,用户 site-packages 目录} 的路径以及 @ref{14ba,,Distutils 安装路径}。


@subsubheading 参见


@geindex Python 提高建议; PEP 370
PEP 370@footnote{https://www.python.org/dev/peps/pep-0370} -- 分用户的 site-packages 目录

@end deffn

@geindex 环境变量; PYTHONEXECUTABLE
@anchor{using/cmdline envvar-PYTHONEXECUTABLE}@anchor{14bb}
@deffn {环境变量} PYTHONEXECUTABLE

如果设置了此环境变量，则 @code{sys.argv[0]} 将被设为此变量的值而不是通过 C 运行时所获得的值。 这仅在 macOS 上起作用。
@end deffn

@geindex 环境变量; PYTHONWARNINGS
@anchor{using/cmdline envvar-PYTHONWARNINGS}@anchor{524}
@deffn {环境变量} PYTHONWARNINGS

此变量等价于 @ref{15b,,-W} 选项。 如果被设为一个以逗号分隔的字符串，它就相当于多次指定 @ref{15b,,-W}，列表中后出现的过滤器优先级会高于列表中先出现的。

最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使是在默认情况下会忽略的那些警告):

@example
PYTHONWARNINGS=default  # Warn once per call location
PYTHONWARNINGS=error    # Convert to exceptions
PYTHONWARNINGS=always   # Warn every time
PYTHONWARNINGS=module   # Warn once per calling module
PYTHONWARNINGS=once     # Warn once per Python process
PYTHONWARNINGS=ignore   # Never warn
@end example

请参阅 @ref{15d,,警告过滤器} 和 @ref{14ae,,警告过滤器的介绍} 了解更多细节。
@end deffn

@geindex 环境变量; PYTHONFAULTHANDLER
@anchor{using/cmdline envvar-PYTHONFAULTHANDLER}@anchor{ab0}
@deffn {环境变量} PYTHONFAULTHANDLER

如果此环境变量被设为一个非空字符串，@ref{64b,,faulthandler.enable()} 会在启动时被调用：为 @code{SIGSEGV}, @code{SIGFPE}, @code{SIGABRT}, @code{SIGBUS} 和 @code{SIGILL} 等信号安装一个处理句柄以转储 Python 回溯信息。 此变量等价于 @ref{297,,-X} @code{faulthandler} 选项。


3.3 新版功能.

@end deffn

@geindex 环境变量; PYTHONTRACEMALLOC
@anchor{using/cmdline envvar-PYTHONTRACEMALLOC}@anchor{14bc}
@deffn {环境变量} PYTHONTRACEMALLOC

如果此环境变量被设为一个非空字符串，则会使用 @ref{11d,,tracemalloc} 模块启动对 Python 内存分配的跟踪。 该变量的值是保存于跟踪的回溯信息中的最大帧数。 例如，@code{PYTHONTRACEMALLOC=1} 只保存最近的帧。 请参阅 @ref{14b1,,tracemalloc.start()} 了解详情。


3.4 新版功能.

@end deffn

@geindex 环境变量; PYTHONPROFILEIMPORTTIME
@anchor{using/cmdline envvar-PYTHONPROFILEIMPORTTIME}@anchor{44d}
@deffn {环境变量} PYTHONPROFILEIMPORTTIME

如果此变量被设为一个非空字符串，Python 将显示每次导入花费了多长时间。 此变量完全等价于在命令行为设置 @code{-X importtime}。


3.7 新版功能.

@end deffn

@geindex 环境变量; PYTHONASYNCIODEBUG
@anchor{using/cmdline envvar-PYTHONASYNCIODEBUG}@anchor{14bd}
@deffn {环境变量} PYTHONASYNCIODEBUG

如果此变量被设为一个非空字符串，则会启用 @ref{9,,asyncio} 模块的 @ref{14be,,调试模式}。


3.4 新版功能.

@end deffn

@geindex 环境变量; PYTHONMALLOC
@anchor{using/cmdline envvar-PYTHONMALLOC}@anchor{605}
@deffn {环境变量} PYTHONMALLOC

设置 Python 内存分配器和/或安装调试钩子。

设置 Python 所使用的内存分配器族群：


@itemize *

@item 
@code{default}: 使用 @ref{14bf,,默认内存分配器}。

@item 
@code{malloc}: 对所有域 (@ref{14c0,,PYMEM_DOMAIN_RAW}, @ref{60a,,PYMEM_DOMAIN_MEM}, @ref{608,,PYMEM_DOMAIN_OBJ}) 使用 C 库的 @code{malloc()} 函数。

@item 
@code{pymalloc}: 对 @ref{60a,,PYMEM_DOMAIN_MEM} 和 @ref{608,,PYMEM_DOMAIN_OBJ} 域使用 @ref{6c2,,pymalloc 分配器} 而对 @ref{14c0,,PYMEM_DOMAIN_RAW} 域使用 @code{malloc()} 函数。
@end itemize

安装调试钩子：


@itemize *

@item 
@code{debug}: 在 @ref{14bf,,默认内存分配器} 之上安装调试钩子。

@item 
@code{malloc_debug}: 与 @code{malloc} 相同但还会安装调试钩子。

@item 
@code{pymalloc_debug}: 与 @code{pymalloc} 相同但还会安装调试钩子。
@end itemize

请参阅 @ref{14bf,,默认内存分配器} 以及 @ref{60c,,PyMem_SetupDebugHooks()} 函数（在 Python 内存分配器之上安装调试钩子）。


在 3.7 版更改: 增加了 @code{"default"} 分配器。



3.6 新版功能.

@end deffn

@geindex 环境变量; PYTHONMALLOCSTATS
@anchor{using/cmdline envvar-PYTHONMALLOCSTATS}@anchor{12d8}
@deffn {环境变量} PYTHONMALLOCSTATS

如果设为一个非空字符串，Python 将在每次创建新的 pymalloc 对象区域以及在关闭时打印 @ref{6c2,,pymalloc 内存分配器} 的统计信息。

如果 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 环境变量被用来强制开启 C 库的 @code{malloc()} 分配器，或者如果 Python 的配置不支持 @code{pymalloc}，则此变量将被忽略。


在 3.6 版更改: 此变量现在也可以被用于在发布模式下编译的 Python。 如果它被设置为一个空字符串则将没有任何效果。

@end deffn

@geindex 环境变量; PYTHONLEGACYWINDOWSFSENCODING
@anchor{using/cmdline envvar-PYTHONLEGACYWINDOWSFSENCODING}@anchor{5f9}
@deffn {环境变量} PYTHONLEGACYWINDOWSFSENCODING

如果设为一个非空字符串，则默认的文件系统编码和错误模式将分别恢复为它们在 3.6 版之前的值 'mbcs' 和 'replace'。 否则会使用新的默认值 'utf-8' 和 'surrogatepass'。

这也可以在运行时通过 @ref{5fa,,sys._enablelegacywindowsfsencoding()} 来启用。

@ref{14c1,,可用性}: Windows。


3.6 新版功能: 有关更多详细信息，请参阅 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529}。

@end deffn

@geindex 环境变量; PYTHONLEGACYWINDOWSSTDIO
@anchor{using/cmdline envvar-PYTHONLEGACYWINDOWSSTDIO}@anchor{5fc}
@deffn {环境变量} PYTHONLEGACYWINDOWSSTDIO

如果设为一个非空字符串，则不使用新的控制台读取器和写入器。 这意味着 Unicode 字符将根据活动控制台的代码页进行编码，而不是使用 utf-8。

如果标准流被重定向（到文件或管道）而不是指向控制台缓冲区则该变量会被忽略。

@ref{14c1,,可用性}: Windows。


3.6 新版功能.

@end deffn

@geindex 环境变量; PYTHONCOERCECLOCALE
@anchor{using/cmdline envvar-PYTHONCOERCECLOCALE}@anchor{426}
@deffn {环境变量} PYTHONCOERCECLOCALE

如果值设为 @code{0}，将导致主 Python 命令行应用跳过将传统的基于 ASCII 的 C 与 POSIX 区域设置强制转换为更强大的基于 UTF-8 的替代方案。

如果此变量 @emph{未被} 设置（或被设为 @code{0} 以外的值），则覆盖环境变量的 @code{LC_ALL} 区域选项也不会被设置，并且报告给 @code{LC_CTYPE} 类别的当前区域选项或者为默认的 @code{C} 区域，或者为显式指明的基于 ASCII 的 @code{POSIX} 区域，然后 Python CLI 将在加载解释器运行时之前尝试为 @code{LC_CTYPE} 类别按指定的顺序配置下列区域选项：


@itemize *

@item 
@code{C.UTF-8}

@item 
@code{C.utf8}

@item 
@code{UTF-8}
@end itemize

如果成功设置了以上区域类别中的一个，则初始化 Python 运行时之前也将在当前进程环境中相应地设置 @code{LC_CTYPE} 环境变量。 这会确保除了解释器本身和运行于同一进程中的其他可感知区域选项的组件 (例如 GNU @code{readline} 库) 之外，还能在子进程 (无论这些进程是否在运行 Python 解释器) 以及在查询环境而非当前 C 区域的操作 (例如 Python 自己的 @ref{14c2,,locale.getdefaultlocale()}) 中看到更新的设置。

(显式地或通过上述的隐式区域强制转换) 配置其中一个区域选项将自动为 @ref{427,,sys.stdin} 和 @ref{428,,sys.stdout} 启用 @code{surrogateescape} @ref{f7d,,错误处理句柄} (@ref{1eb,,sys.stderr} 会继续使用 @code{backslashreplace} 如同在任何其他区域选项中一样)。 这种流处理行为可以按通常方式使用 
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} 来覆盖。

出于调试目的，如果激活了区域强制转换，或者如果当 Python 运行时被初始化时某个 @emph{应该} 触发强制转换的区域选项仍处于激活状态则设置 @code{PYTHONCOERCECLOCALE=warn} 将导致 Python 在 @code{stderr} 上发出警告消息。

还要注意，即使在区域转换转换被禁用，或者在其无法找到合适的目标区域时，默认 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} 仍将在传统的基于 ASCII 的区域中被激活。 必须同时禁用这两项特性以强制解释器使用 @code{ASCII} 而不是 @code{UTF-8} 作为系统接口。

@ref{14c1,,可用性}: *nix。


3.7 新版功能: 请参阅 
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538} 了解详情。

@end deffn

@geindex 环境变量; PYTHONDEVMODE
@anchor{using/cmdline envvar-PYTHONDEVMODE}@anchor{445}
@deffn {环境变量} PYTHONDEVMODE

如果将此环境变量设为非空字符串，则启用 @ref{160,,Python 开发模式}，引入在默认情况下启用会导致开销过大的运行时检查。


3.7 新版功能.

@end deffn

@geindex 环境变量; PYTHONUTF8
@anchor{using/cmdline envvar-PYTHONUTF8}@anchor{42a}
@deffn {环境变量} PYTHONUTF8

如果设为 @code{1}，则会启用解释器的 UTF-8 模式，将 @code{UTF-8} 用作系统接口的文本编码，无论当前区域选项如何设置。

这意味着：

@quotation


@itemize *

@item 
@ref{5f8,,sys.getfilesystemencoding()} 将返回 @code{'UTF-8'} (本地编码会被忽略)。

@item 
@ref{4b4,,locale.getpreferredencoding()} 将返回 @code{'UTF-8'} (本地编码会被忽略，并且该函数的 @code{do_setlocale} 参数不起作用)。

@item 
@ref{427,,sys.stdin}, @ref{428,,sys.stdout} 和 @ref{1eb,,sys.stderr} 都将 UTF-8 用作它们的文本编码，并且为 @ref{427,,sys.stdin} 和 @ref{428,,sys.stdout} 启用 @code{surrogateescape} @ref{f7d,,错误处理句柄} (@ref{1eb,,sys.stderr} 会继续使用 @code{backslashreplace} 如同在默认的局部感知模式下一样)
@end itemize
@end quotation

作为低层级 API 发生改变的结果，其他高层级 API 也会表现出不同的默认行为：

@quotation


@itemize *

@item 
命令行参数，环境变量和文件名会使用 UTF-8 编码来解码为文本。

@item 
@ref{5f1,,os.fsdecode()} 和 @ref{5f2,,os.fsencode()} 会使用 UTF-8 编码。

@item 
@ref{16f,,open()}, @ref{757,,io.open()} 和 @ref{110c,,codecs.open()} 默认会使用 UTF-8 编码。 但是，它们默认仍将使用严格错误处理句柄，因此试图在文本模式下打开二进制文件将可能引发异常，而不是生成无意义的数据。
@end itemize
@end quotation

请注意 UTF-8 模式下的标准流设置可以被 
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} 所覆盖（在默认的区域感知模式下也同样如此）。

如果设置为“0”，则解释器以其默认的区域识别模式运行。

设置任何其他非空字符串会在解释器初始化期间导致错误。

如果根本未设置此环境变量，则解释器默认使用当前区域设置，@emph{除非} 当前区域被标识为基于 ASCII 的旧式区域设置（如 
@geindex PYTHONCOERCECLOCALE
@geindex 环境变量; PYTHONCOERCECLOCALE
@ref{426,,PYTHONCOERCECLOCALE} 所述），并且区域强制转换被禁用或失败。 在此类旧式区域设置中，解释器将默认启用 UTF-8 模式，除非显式地指定不这样做。

也可以使用 @ref{297,,-X} @code{utf8} 选项。


3.7 新版功能: 有关更多详细信息，请参阅 
@geindex Python 提高建议; PEP 540
PEP 540@footnote{https://www.python.org/dev/peps/pep-0540} 。

@end deffn

@menu
* 调试模式变量:: 

@end menu

@node 调试模式变量,,,环境变量
@anchor{using/cmdline debug-mode-variables}@anchor{14c3}
@subsubsection 调试模式变量


设置这些变量只会在Python的调试版本中产生影响。

@geindex 环境变量; PYTHONTHREADDEBUG
@anchor{using/cmdline envvar-PYTHONTHREADDEBUG}@anchor{14c4}
@deffn {环境变量} PYTHONTHREADDEBUG

如果设置，Python将打印线程调试信息。

需要使用 @code{--with-pydebug} 构建选项配置Python。
@end deffn

@geindex 环境变量; PYTHONDUMPREFS
@anchor{using/cmdline envvar-PYTHONDUMPREFS}@anchor{29a}
@deffn {环境变量} PYTHONDUMPREFS

如果设置，Python在关闭解释器，及转储对象和引用计数后仍将保持活动。

需要使用 @code{--with-trace-refs} 构建选项配置Python。
@end deffn

@node 在Unix平台中使用Python,在Windows上使用 Python,命令行与环境,安装和使用 Python
@anchor{using/unix doc}@anchor{14c5}@anchor{using/unix using-on-unix}@anchor{14c6}@anchor{using/unix using-python-on-unix-platforms}@anchor{14c7}
@section 在Unix平台中使用Python


@menu
* 获取最新版本的Python:: 
* 构建Python:: 
* 与Python相关的路径和文件:: 
* 杂项:: 

@end menu

@node 获取最新版本的Python,构建Python,,在Unix平台中使用Python
@anchor{using/unix getting-and-installing-the-latest-version-of-python}@anchor{14c8}
@subsection 获取最新版本的Python


@menu
* 在Linux中:: 
* 在FreeBSD和OpenBSD上:: 
* 在OpenSolaris系统上:: 

@end menu

@node 在Linux中,在FreeBSD和OpenBSD上,,获取最新版本的Python
@anchor{using/unix on-linux}@anchor{14c9}
@subsubsection 在Linux中


Python预装在大多数Linux发行版上，并作为一个包提供给所有其他用户。 但是，您可能想要使用的某些功能在发行版提供的软件包中不可用。这时您可以从源代码轻松编译最新版本的Python。

如果Python没有预先安装并且不在发行版提供的库中，您可以轻松地为自己使用的发行版创建包。 参阅以下链接：


@subsubheading 参见



@table @asis

@item @indicateurl{https://www.debian.org/doc/manuals/maint-guide/first.en.html}

对于Debian用户

@item @indicateurl{https://en.opensuse.org/Portal:Packaging}

对于OpenSuse用户

@item @indicateurl{https://docs-old.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html}

对于Fedora用户

@item @indicateurl{http://www.slackbook.org/html/package-management-making-packages.html}

对于Slackware用户
@end table


@node 在FreeBSD和OpenBSD上,在OpenSolaris系统上,在Linux中,获取最新版本的Python
@anchor{using/unix on-freebsd-and-openbsd}@anchor{14ca}
@subsubsection 在FreeBSD和OpenBSD上



@itemize *

@item 
FreeBSD用户，使用以下命令添加包:

@example
pkg install python3
@end example

@item 
OpenBSD用户，使用以下命令添加包:

@example
pkg_add -r python

pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz
@end example

例如：i386用户获取Python 2.5.1的可用版本:

@example
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
@end example
@end itemize

@node 在OpenSolaris系统上,,在FreeBSD和OpenBSD上,获取最新版本的Python
@anchor{using/unix on-opensolaris}@anchor{14cb}
@subsubsection 在OpenSolaris系统上


你可以从 OpenCSW@footnote{https://www.opencsw.org/} 获取、安装及使用各种版本的Python。比如 @code{pkgutil -i python27} 。

@node 构建Python,与Python相关的路径和文件,获取最新版本的Python,在Unix平台中使用Python
@anchor{using/unix building-python}@anchor{14cc}@anchor{using/unix building-python-on-unix}@anchor{8ea}
@subsection 构建Python


如果你想自己编译CPython，首先要做的是获取 source@footnote{https://www.python.org/downloads/source/} 。您可以下载最新版本的源代码，也可以直接提取最新的 clone@footnote{https://devguide.python.org/setup/#getting-the-source-code} 。 （如果你想要制作补丁，则需要克隆代码。）

构建过程由常用命令组成：

@example
./configure
make
make install
@end example

特定Unix平台的配置选项和注意事项通常记录在Python源代码的根目录下的 README.rst@footnote{https://github.com/python/cpython/tree/3.9/README.rst} 文件中。

@cartouche
@quotation 警告 
@code{make install} 可以覆盖或伪装 @code{python3} 二进制文件。因此，建议使用 @code{make altinstall} 而不是 @code{make install} ，因为后者只安装了 @code{@emph{exec_prefix}/bin/python@emph{version}} 。
@end quotation
@end cartouche

@node 与Python相关的路径和文件,杂项,构建Python,在Unix平台中使用Python
@anchor{using/unix python-related-paths-and-files}@anchor{14cd}
@subsection 与Python相关的路径和文件


这取决于本地安装惯例； 
@geindex prefix
@geindex 环境变量; prefix
@code{prefix} （ @code{$@{prefix@}} ）和 
@geindex exec_prefix
@geindex 环境变量; exec_prefix
@code{exec_prefix} （ @code{$@{exec_prefix@}} ）  取决于安装，应解释为GNU软件；它们可能相同。

例如，在大多数Linux系统上，两者的默认值是 @code{/usr} 。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件/目录

@tab

含义

@item

@code{@emph{exec_prefix}/bin/python3}

@tab

解释器的推荐位置

@item

@code{@emph{prefix}/lib/python@emph{version}},
@code{@emph{exec_prefix}/lib/python@emph{version}}

@tab

包含标准模块的目录的推荐位置

@item

@code{@emph{prefix}/include/python@emph{version}},
@code{@emph{exec_prefix}/include/python@emph{version}}

@tab

包含开发Python扩展和嵌入解释器所需的include文件的目录的推荐位置

@end multitable


@node 杂项,,与Python相关的路径和文件,在Unix平台中使用Python
@anchor{using/unix miscellaneous}@anchor{14ce}
@subsection 杂项


要在Unix上使用Python脚本，需要添加可执行权限，例如：

@example
$ chmod +x script
@end example

并在脚本的顶部放置一个合适的Shebang线。一个很好的选择通常是:

@example
#!/usr/bin/env python3
@end example

将在整个 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 中搜索Python解释器。但是，某些Unix系统可能没有 @code{env} 命令，因此可能需要将 @code{/usr/bin/python3} 硬编码为解释器路径。

要在Python脚本中使用shell命令，请查看 @ref{f9,,subprocess} 模块。

@node 在Windows上使用 Python,在 Mac 上使用 Python,在Unix平台中使用Python,安装和使用 Python
@anchor{using/windows doc}@anchor{14cf}@anchor{using/windows using-on-windows}@anchor{401}@anchor{using/windows using-python-on-windows}@anchor{14d0}
@section 在Windows上使用 Python


本文档旨在概述在 Microsoft Windows 上使用 Python 时应了解的特定于 Windows 的行为。

与大多数UNIX系统和服务不同，Windows系统没有预安装Python。多年来CPython 团队已经编译了每一个 发行版@footnote{https://www.python.org/download/releases/} 的Windows安装程序（MSI 包），已便Windows 用户下载和安装。这些安装程序主要用于每个用户单独安装Python时，添加核心解释器和库。安装程序还可以为一台机器的所有用户安装，并且可以为应用程序本地分发提供单独的zip文件。

如 
@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011} 所述，Python 发布版对某个 Windows 平台的支持仅限于被 Microsoft 视为处于延长支持周期内的版本。 这意味着 Python 3.9 支持 Windows 8.1 及其后的版本。 如果你需要 Windows 7 支持，请安装 Python 3.8。

Windows提供了许多不同的安装程序，每个安装程序都有一定的优点和缺点。

@ref{14d1,,完整安装程序} 内含所有组件，对于使用Python 进行任何类型项目的开发人员而言，它是最佳选择。

@ref{136c,,Microsoft Store包} 是一个简单的Python 安装，适用于运行脚本和包，以及使用IDLE或其他开发环境。 它需要Windows 10，但可以安全地安装而不会破坏其他程序。 它还提供了许多方便的命令来启动Python及其工具。

@ref{14d2,,nuget.org 安装包} 是用于持续集成系统的轻量级安装。它可用于构建Python包或运行脚本，但不可更新且没有用户界面工具。

@ref{14d3,,可嵌入的包} 是Python的最小安装包，适合嵌入到更大的应用程序中。

@menu
* 完整安装程序:: 
* Microsoft Store包:: 
* nuget.org 安装包: nuget org 安装包. 
* 可嵌入的包:: 
* 替代捆绑包:: 
* 配置Python:: 
* UTF-8 模式:: 
* 适用于Windows的Python启动器:: 
* 查找模块:: 
* 附加模块:: 
* 在Windows上编译Python:: 
* 其他平台:: 

@end menu

@node 完整安装程序,Microsoft Store包,,在Windows上使用 Python
@anchor{using/windows the-full-installer}@anchor{14d4}@anchor{using/windows windows-full}@anchor{14d1}
@subsection 完整安装程序


@menu
* 安装步骤:: 
* 删除 MAX_PATH 限制:: 
* 无UI 安装:: 
* 免下载安装:: 
* 修改安装:: 

@end menu

@node 安装步骤,删除 MAX_PATH 限制,,完整安装程序
@anchor{using/windows installation-steps}@anchor{14d5}
@subsubsection 安装步骤


四个 Python 3.9 安装程序可供下载 - 32位和64位版本的各有两个。 @emph{web installer} （网络安装包）是一个小的初始化工具，它将在安装过程中，根据需要自动下载所需的组件。 @emph{offline installer} （离线安装包）内含默认安装所需的组件，可选择功能仍需要Internet连接下载。请参阅 @ref{14d6,,免下载安装} 以了解在安装过程中避免下载的其他方法。

启动安装程序后，可以选择以下两个选项之一：

@image{python-figures/win_installer,,,,png}

如果选择“Install Now（立即安装）”：


@itemize *

@item 
您 @emph{不} 需要成为管理员（除非需要对C运行库进行系统更新，或者为所有用户安装 @ref{a79,,适用于Windows的Python启动器} ）

@item 
Python将安装到您的用户目录中

@item 
@ref{a79,,适用于Windows的Python启动器} 将根据第一页底部的选项安装

@item 
将安装标准库，测试套件，启动器和pip

@item 
如果选择将安装目录将添加到 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}

@item 
快捷方式仅对当前用户可见
@end itemize

选择“自定义安装”将允许您选择：要安装的功能、安装位置、其他选项或安装后的操作。如果要安装调试符号或二进制文件，您需要使用此选项。

如要为全部用户安装，应选择“自定义安装”。在这种情况下:


@itemize *

@item 
您可能需要提供管理凭据或批准

@item 
Python 将安装到Program Files目录中

@item 
@ref{a79,,适用于Windows的Python启动器} 将安装到Windows目录中

@item 
安装期间可以选择可选功能

@item 
标准库可以预编译为字节码

@item 
如果选中，安装目录将添加到系统 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}

@item 
快捷方式所有用户可用
@end itemize

@node 删除 MAX_PATH 限制,无UI 安装,安装步骤,完整安装程序
@anchor{using/windows max-path}@anchor{5d8}@anchor{using/windows removing-the-max-path-limitation}@anchor{14d7}
@subsubsection 删除 MAX_PATH 限制


历史上Windows的路径长度限制为260个字符。这意味着长于此的路径将无法解决并导致错误。

在最新版本的 Windows 中，此限制可被扩展到大约 32,000 个字符。 但需要让管理员激活“启用 Win32 长路径”组策略，或在注册表键 @code{HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem} 中设置 @code{LongPathsEnabled} 为 @code{1}。

这允许 @ref{16f,,open()} 函数，@ref{c4,,os} 模块和大多数其他路径功能接受并返回长度超过 260 个字符的路径。

更改上述选项后，无需进一步配置。


在 3.6 版更改: Python中启用了对长路径的支持。


@node 无UI 安装,免下载安装,删除 MAX_PATH 限制,完整安装程序
@anchor{using/windows install-quiet-option}@anchor{14d8}@anchor{using/windows installing-without-ui}@anchor{14d9}
@subsubsection 无UI 安装


安装程序UI中的所有选项也可以从命令行指定，允许脚本安装程序在许多机器上复制安装，而无需用户交互。还可以在不禁用UI的情况下设置这些选项，以更改一些默认值。

要完全隐藏安装程序UI并静默安装Python，请使用 @code{/quiet} 选项。要跳过用户交互但仍然显示进度和错误，请使用 @code{/passive} 选项。可以通过 @code{/uninstall} 选项立即开始删除Python  - -   不会显示任何确认提示。

所有其他选项都传递为 @code{name=value} ，其中值通常是 @code{0} 来禁用某个特性， @code{1} 来启用某个特性或路径。可用选项的完整列表如下所示。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名称

@tab

描述

@tab

默认值

@item

InstallAllUsers

@tab

为所有用户安装。

@tab

0

@item

TargetDir

@tab

安装目录

@tab

基于InstallAllUsers选择

@item

DefaultAllUsersTargetDir

@tab

为所有用户安装时的默认安装路径

@tab

@code{%ProgramFiles%\Python X.Y} 或 @code{%ProgramFiles(x86)%\Python X.Y}

@item

DefaultJustForMeTargetDir

@tab

仅为当前用户安装时的默认安装路径

@tab

@code{%LocalAppData%\Programs\PythonXY} 或 @code{%LocalAppData%\Programs\PythonXY-32} 或 @code{%LocalAppData%\Programs\PythonXY-64}

@item

DefaultCustomTargetDir

@tab

UI中显示的默认自定义安装目录

@tab

（空）

@item

AssociateFiles

@tab

如果还安装了启动器，则创建文件关联。

@tab

1

@item

CompileAll

@tab

将所有 @code{.py} 文件编译为 @code{.pyc} 。

@tab

0

@item

PrependPath

@tab

将install和Scripts目录添加到 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 以及将 @code{.PY} 添加到 
@geindex PATHEXT
@geindex 环境变量; PATHEXT
@code{PATHEXT}

@tab

0

@item

Shortcuts

@tab

如果已安装，为解释器，文档和IDLE创建快捷方式

@tab

1

@item

Include_doc

@tab

安装Python手册

@tab

1

@item

Include_debug

@tab

安装调试二进制文件

@tab

0

@item

Include_dev

@tab

安装开发人员头文件和库

@tab

1

@item

Include_exe

@tab

安装 @code{python.exe} 及相关文件

@tab

1

@item

Include_launcher

@tab

安装 @ref{a79,,适用于Windows的Python启动器} .

@tab

1

@item

InstallLauncherAllUsers

@tab

为所有用户安装 @ref{a79,,适用于Windows的Python启动器} 。

@tab

1

@item

Include_lib

@tab

安装标准库和扩展模块

@tab

1

@item

Include_pip

@tab

安装捆绑的pip和setuptools

@tab

1

@item

Include_symbols

@tab

安装调试符号(@cite{*}.pdb)

@tab

0

@item

Include_tcltk

@tab

安装Tcl/Tk 支持和IDLE

@tab

1

@item

Include_test

@tab

安装标准库测试套件

@tab

1

@item

Include_tools

@tab

安装实用程序脚本

@tab

1

@item

LauncherOnly

@tab

仅安装启动器。这将覆盖大多数其他选项。

@tab

0

@item

SimpleInstall

@tab

禁用大多数安装UI

@tab

0

@item

SimpleInstallDescription

@tab

使用简化安装UI时显示的自定义消息。

@tab

（空）

@end multitable


例如，要以静默方式全局安装默认的Python，您可以（在命令提示符>）使用以下命令:

@example
python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
@end example

要允许用户在没有测试套件的情况下轻松安装Python的个人副本，可以使用以下命令提供快捷方式。这将显示一个简化的初始页面，不允许自定义:

@example
python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
    SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."
@end example

（请注意，省略启动器也会省略文件关联，并且仅在全局安装包含启动器时才建议用于每用户安装。）

上面列出的选项也可以在一个名为 @code{unattend.xml} 的文件中与可执行文件一起提供。此文件指定选项和值的列表。作为属性提供的值，（如果可能）它将转换为数字。作为文本提供的值，始终保留为字符串。此示例文件设置与上一示例采用相同的选项：

@example
<Options>
    <Option Name="InstallAllUsers" Value="no" />
    <Option Name="Include_launcher" Value="0" />
    <Option Name="Include_test" Value="no" />
    <Option Name="SimpleInstall" Value="yes" />
    <Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
</Options>
@end example

@node 免下载安装,修改安装,无UI 安装,完整安装程序
@anchor{using/windows install-layout-option}@anchor{14d6}@anchor{using/windows installing-without-downloading}@anchor{14da}
@subsubsection 免下载安装


由于下载的初始安装包中未包含Python的某些可选功能，如果选择安装这些功能可能需要Internet连接。为了避免这种需要，可以按需下载所有可能的组件，以创建一个完整的布局，该布局将不再需要internet连接，而不管所选择的特性是什么。请注意，此下载可能比要求的要大，但是如果要执行大量安装，则拥有本地缓存​​的副本非常有用。

从命令提示符执行以下命令以下载所有可能的必需文件。 请记得要将 @code{python-3.9.0.exe} 替换为安装程序的实际名称，并在单独的目录中创建子目录以避免同名文件间的冲突。

@example
python-3.9.0.exe /layout [optional target directory]
@end example

您也可以指定 @code{/quiet} 选项来隐藏进度显示。

@node 修改安装,,免下载安装,完整安装程序
@anchor{using/windows modifying-an-install}@anchor{14db}
@subsubsection 修改安装


安装Python后，您可以通过Windows中的“程序和功能”工具添加或删除功能。选择Python条目并选择“卸载/更改”以在维护模式下打开安装程序。

“修改” 允许您通过修改复选框来添加或删除功能 - 未更改的复选框将不会安装或删除任何内容。在此模式下无法更改某些选项，例如安装目录；要修改这些，您需要完全删除然后重新安装Python。

“修复” 将使用当前设置验证应安装的所有文件，并替换已删除或修改的任何文件

“卸载” 将完全删除Python，但 @ref{a79,,适用于Windows的Python启动器} 除外，它在“程序和功能”中有自己的条目。

@node Microsoft Store包,nuget org 安装包,完整安装程序,在Windows上使用 Python
@anchor{using/windows the-microsoft-store-package}@anchor{14dc}@anchor{using/windows windows-store}@anchor{136c}
@subsection Microsoft Store包



3.7.2 新版功能.


Microsoft Store 包是一个易于安装的 Python 解释器，主要针对在交互模式下使用，例如用于教学。

要安装软件包，请确保您拥有最新的Windows 10更新，并在Microsoft Store应用程序中搜索 "Python 3.9" 。确保您选择的应用程序由 Python Software Foundation 发布并安装。

@cartouche
@quotation 警告 
Python将始终在Microsoft Store上免费提供。如果要求您付款，则表示您没有选择正确的包。
@end quotation
@end cartouche

安装完成后，可以在开始菜单中找到它来启动 Python。或者可以在命令提示符或 PowerShell 会话中输入 @code{python} 来启动。此外可以输入 @code{pip} 或 @code{idle} 来使用 pip 和 IDLE。IDLE 也在开始菜单中。

所有这三个命令也可以使用版本号后缀，例如， @code{python3.exe} 和 @code{python3.x.exe} 以及 @code{python.exe} （其中 @code{3.x} 是您要启动的特定版本，例如 3.9 ）。在 @code{设置-->主页-->应用和功能} 页面中，点选 @code{管理可选功能} ，选择与每个命令关联的python版本。建议确保 @code{pip} 和 @code{idle} 与选择的 @code{python} 版本一致。

可以使用 @code{python -m venv} 创建虚拟环境并激活并正常使用。

如果你已经安装了另一个版本的Python并将它添加到你的 @code{PATH} 变量中，那么它将作为 @code{python.exe} 而不是来自Microsoft Store的那个。要访问新安装，请使用 @code{python3.exe} 或 @code{python3.x.exe} 。

@code{py.exe} 启动器将检测此 Python 安装版，但会优先使用来自传统安装器的安装版。

要删除Python，请打开“设置”并使用“应用程序和功能”，或者在“开始”中找到Python，然后右键单击以选择“卸载”。卸载将删除该已安装Python程序中的所有软件包，但不会删除任何虚拟环境

@menu
* 已知的问题:: 

@end menu

@node 已知的问题,,,Microsoft Store包
@anchor{using/windows known-issues}@anchor{14dd}
@subsubsection 已知的问题


由于Microsoft Store应用程序的限制，Python脚本可能无法对共享位置（如 @code{TEMP} ）和注册表进行完全写入访问。相反，它将写入私人副本。如果脚本必须修改共享位置，则需要安装完整安装程序。

有关此限制的技术原理的更多细节，请查询 Microsoft 已打包完全可信应用的文档，当前位于 docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes@footnote{https://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes}

@node nuget org 安装包,可嵌入的包,Microsoft Store包,在Windows上使用 Python
@anchor{using/windows the-nuget-org-packages}@anchor{14de}@anchor{using/windows windows-nuget}@anchor{14d2}
@subsection nuget.org 安装包



3.5.2 新版功能.


nuget.org是一个精简的Python环境，用于在没有全局安装Python的系统的持续集成和构建。虽然Nuget是“.NET的包管理器”，但是对于包含构建时工具的包来说，它也可以很好地工作。

访问 nuget.org@footnote{https://www.nuget.org/}  获取有关使用nuget的最新信息。下面的摘要对Python开发人员来说已经足够了。

 @code{nuget.exe} 命令行工具可以直接从 @code{https://aka.ms/nugetclidl} 下载，例如，使用curl或PowerShell。使用该工具安装64位或32位最新版本的Python:

@example
nuget.exe install python -ExcludeVersion -OutputDirectory .
nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .
@end example

要选择特定版本，请添加 @code{-Version 3.x.y} 。输出目录可以从 @code{.} 更改，包将安装到子目录中。默认情况下，子目录的名称与包的名称相同，如果没有 @code{-ExcludeVersion} 选项，则此名称将包含已安装的特定版本。子目录里面是一个包含Python安装的 @code{tools} 目录：

@example
# Without -ExcludeVersion
> .\python.3.5.2\tools\python.exe -V
Python 3.5.2

# With -ExcludeVersion
> .\python\tools\python.exe -V
Python 3.5.2
@end example

通常，nuget包不可升级，应该平行安装较新版本并使用完整路径引用。或者，手动删除程序包目录并再次安装。如果在构建之间不保留文件，许多CI系统将自动执行此操作。

除了 @code{tools} 目录外，还有一个 @code{build\native} 目录。它包含一个MSBuild属性文件 @code{python.props} ，可以在C++项目中使用该文件来引用Python安装。包含这些设置将自动在生成中使用标头和导入库。

nuget.org上的包信息页是 www.nuget.org/packages/python@footnote{https://www.nuget.org/packages/python}        对于64位版本和 www.nuget.org/packages/pythonx86@footnote{https://www.nuget.org/packages/pythonx86} 表示32位版本。

@node 可嵌入的包,替代捆绑包,nuget org 安装包,在Windows上使用 Python
@anchor{using/windows the-embeddable-package}@anchor{14df}@anchor{using/windows windows-embeddable}@anchor{14d3}
@subsection 可嵌入的包



3.5 新版功能.


嵌入式发行版是一个包含最小Python环境的ZIP文件。它旨在作为另一个应用程序的一部分，而不是由最终用户直接访问。

解压缩后，嵌入式发行版（几乎）与用户系统完全隔离，包括环境变量、系统注册表设置和已安装的软件包。标准库作为预先编译和优化的 @code{.pyc} 文件包含在ZIP中，并提供了 @code{python3.dll} ， @code{python37.dll} ， @code{python.exe} 和 @code{pythonw.exe} 文件。不包括Tcl/tk（包括所有依赖项，如Idle），pip和Python文档。

@cartouche
@quotation 注解 
嵌入式发行版不包括 Microsoft C Runtime@footnote{https://docs.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist#visual-studio-2015-2017-2019-and-2022} ，应用程序安装程序负责提供此功能。运行时可能已经预先安装在用户的系统上或通过Windows Update自动安装，并且可以通过在系统目录中找到 @code{ucrtbase.dll} 来检测
@end quotation
@end cartouche

第三方软件包应该由应用程序与嵌入式发行版一起安装。这个发行版不支持像常规Python安装那样使用pip来管理依赖关系，不过可以小心地将pip包含进来并使用它进行自动更新。通常，第三方包应该作为应用程序的一部分(“打包”)处理，以便开发人员在向用户提供更新之前能够确保与新版本兼容。

下面描述了这个发行版的两个推荐用例。

@menu
* Python应用程序:: 
* 嵌入Python:: 

@end menu

@node Python应用程序,嵌入Python,,可嵌入的包
@anchor{using/windows python-application}@anchor{14e0}
@subsubsection Python应用程序


用Python编写的应用程序并不一定要求用户了解这一事实。在这种情况下，可以使用嵌入式发行版在安装包中包含Python的私有版本。根据它应该有多透明(或者相反，它应该看起来有多专业)，有两个选项。

使用专门的可执行文件作为启动程序需要一些编码，但为用户提供了最透明的体验。使用定制的启动器，没有明显的迹象表明程序是在Python上运行的：图标可以定制，公司和版本信息可以指定，文件关联可以正常运行。在大多数情况下，自定义启动程序应该只需使用硬编码的命令行就能调用 @code{Py_Main}

更简单的方法是提供批处理文件或生成的快捷方式，使用所需的命令行参数直接调用 @code{python.exe} 或 @code{pythonw.exe} 。在这种情况下，应用程序将显示为Python而不是其实际名称，并且用户可能无法将其与其他正在运行的Python进程或文件关联区分开来。

对于后一种方法，包应该与Python可执行文件一起作为目录安装，以确保它们在路径上可用。使用专用的启动器，包可以位于其他位置，因为在启动应用程序之前有机会指定搜索路径。

@node 嵌入Python,,Python应用程序,可嵌入的包
@anchor{using/windows embedding-python}@anchor{14e1}
@subsubsection 嵌入Python


用本地代码编写的应用程序通常需要某种形式的脚本语言，嵌入式Python发行版可以用于此目的。通常，应用程序的大部分都是本机代码，某些部分将调用 @code{python.exe} 或直接使用 @code{python3.dll} 。无论是哪种情况，将嵌入的发行版解压缩到应用程序安装的子目录中就足以提供可加载的Python解释器。

与应用程序使用一样，包可以安装到任何位置，因为在初始化解释器之前有机会指定搜索路径。否则，使用嵌入式发行版和常规安装之间没有根本区别。

@node 替代捆绑包,配置Python,可嵌入的包,在Windows上使用 Python
@anchor{using/windows alternative-bundles}@anchor{14e2}
@subsection 替代捆绑包


除了标准的CPython发行版之外，还有一些包含附加功能的修改包。以下是热门版本及其主要功能的列表：


@table @asis

@item ActivePython@footnote{https://www.activestate.com/activepython/}

具有多平台兼容性的安装程序，文档，PyWin32

@item Anaconda@footnote{https://www.anaconda.com/download/}

流行的科学模块（如numpy，scipy和pandas）和 @code{conda} 包管理器。

@item Canopy@footnote{https://www.enthought.com/product/canopy/}

具有编辑器和其他开发工具的“全面的Python分析环境”。

@item WinPython@footnote{https://winpython.github.io/}

特定于Windows的发行版，包含用于构建包的预构建科学包和工具。
@end table

请注意，这些软件包可能不包含最新版本的Python或其他库，并且不由核心Python团队维护或支持。

@node 配置Python,UTF-8 模式,替代捆绑包,在Windows上使用 Python
@anchor{using/windows configuring-python}@anchor{14e3}
@subsection 配置Python


要从命令提示符方便地运行Python，您可以考虑在Windows中更改一些默认环境变量。虽然安装程序提供了为您配置PATH和PATHEXT变量的选项，但这仅适用于单版本、全局安装。如果您经常使用多个版本的Python，请考虑使用 @ref{a79,,适用于Windows的Python启动器} 。

@menu
* 附录：设置环境变量:: 
* 查找Python可执行文件:: 

@end menu

@node 附录：设置环境变量,查找Python可执行文件,,配置Python
@anchor{using/windows excursus-setting-environment-variables}@anchor{14e4}@anchor{using/windows setting-envvars}@anchor{136d}
@subsubsection 附录：设置环境变量


Windows允许在用户级别和系统级别永久配置环境变量，或临时在命令提示符中配置环境变量。

要临时设置环境变量，请打开命令提示符并使用 @code{set} 命令：

@example
C:\>set PATH=C:\Program Files\Python 3.9;%PATH%
C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
C:\>python
@end example

这些环境变量的更改将应用​​于在该控制台中执行的任何其他命令，并且，由该控制台启动的任何应用程序都继承设这些设置。

在百分号中包含的变量名将被现有值替换，允许在开始或结束时添加新值。通过将包含 @code{python.exe} 的目录添加到开头来修改 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}  是确保启动正确版本的Python的常用方法。

要永久修改默认环境变量，请单击“开始”并搜索“编辑环境变量”，或打开系统属性的 高级系统设置 ，然后单击 环境变量 按钮。在此对话框中，您可以添加或修改用户和系统变量。要更改系统变量，您需要对计算机进行无限制访问（即管理员权限）。

@cartouche
@quotation 注解 
Windows会将用户变量串联在系统变量 @emph{之后} ，这可能会在修改 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 时导致意外结果。

@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 变量被 Python 的所有版本使用，因此除非它列出的路径只包含与所有已安装的 Python 版本兼容的代码，否则不要永久配置此变量。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item @indicateurl{https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables}

Windows 中的环境变量概述

@item @indicateurl{https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/set_1}

用于临时修改环境变量的 @code{set} 命令

@item @indicateurl{https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/setx}

用于永久修改环境变量的 @code{setx} 命令
@end table


@node 查找Python可执行文件,,附录：设置环境变量,配置Python
@anchor{using/windows finding-the-python-executable}@anchor{14e5}@anchor{using/windows windows-path-mod}@anchor{a7a}
@subsubsection 查找Python可执行文件



在 3.5 版更改.


除了使用自动创建的Python解释器的开始菜单项之外，您可能还想在命令提示符下启动Python。安装程序有一个选项可以为您设置。

在安装程序的第一页上，可以选择标记为“将Python添加到环境变量”的选项，以使安装程序将安装位置添加到 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 。还添加了 @code{Scripts\} 文件夹的位置。这允许你输入 @code{python} 来运行解释器，并且 @code{pip} 用于包安装程序。因此，您还可以使用命令行选项执行脚本，请参阅 @ref{a19,,命令行} 文档。

如果在安装时未启用此选项，则始终可以重新运行安装程序，选择“修改”并启用它。或者，您可以使用 @ref{136d,,附录：设置环境变量} 的方法手动修改 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 。您需要将Python安装目录添加到 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量中，该内容与其他条目用分号分隔。示例变量可能如下所示（假设前两个条目已经存在）:

@example
C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.9
@end example

@node UTF-8 模式,适用于Windows的Python启动器,配置Python,在Windows上使用 Python
@anchor{using/windows utf-8-mode}@anchor{14e6}@anchor{using/windows win-utf8-mode}@anchor{14e7}
@subsection UTF-8 模式



3.7 新版功能.


Windows 仍然使用传统编码格式作为系统的编码格式（ANSI 代码页）。 Python 使用它作为文本文件默认的编码格式 (即 @ref{4b4,,locale.getpreferredencoding()})。

这可能会造成问题，因为因特网和大多数 Unix 系统包括 WSL (Windows Subsystem for Linux) 广泛使用 UTF-8。

你可以使用 UTF-8 模式将默认的文本编码格式改为 UTF-8。 要启用 UTF-8 模式可以通过 @code{-X utf8} 命令行选项，或者 @code{PYTHONUTF8=1} 环境变量。 请参见 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} 了解如何启用 UTF-8 模式，并参见 @ref{136d,,附录：设置环境变量} 了解如何修改环境变量。

当 UTF-8 模式被启用时：


@itemize *

@item 
@ref{4b4,,locale.getpreferredencoding()} 将返回 @code{'UTF-8'} 而不是系统的编码格式。 此函数可用来在许多场合下获取默认的文本编码格式，包括 @ref{16f,,open()}, @code{Popen}, @code{Path.read_text()} 等等。

@item 
@ref{427,,sys.stdin}, @ref{428,,sys.stdout} 和 @ref{1eb,,sys.stderr} 都将使用 UTF-8 作为其文本编码格式。

@item 
你仍然可以通过 "mbcs" 编解码器来使用系统的编码格式。
@end itemize

请注意添加 @code{PYTHONUTF8=1} 到默认环境变量将会影响你的系统中的所有 Python 3.7+ 应用。 如果你有任何 Python 3.7+ 应用仍然依赖于传统的系统编码格式，则推荐设置临时环境变量或使用 @code{-X utf8} 命令行选项。

@cartouche
@quotation 注解 
即使在不启用 UTF-8 模式时，Windows 版的 Python 也会在以下情况中默认使用 UTF-8：


@itemize *

@item 
控制台 I/O 包括标准 I/O (详情见 
@geindex Python 提高建议; PEP 528
PEP 528@footnote{https://www.python.org/dev/peps/pep-0528})。

@item 
文件系统编码格式 (详情见 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529})。
@end itemize
@end quotation
@end cartouche

@node 适用于Windows的Python启动器,查找模块,UTF-8 模式,在Windows上使用 Python
@anchor{using/windows launcher}@anchor{a79}@anchor{using/windows python-launcher-for-windows}@anchor{14e8}
@subsection 适用于Windows的Python启动器



3.3 新版功能.


用于Windows的Python启动器是一个实用程序，可帮助定位和执行不同的Python版本。它允许脚本（或命令行）指示特定Python版本的首选项，并将定位并执行该版本。

与 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 变量不同，启动器将正确选择最合适的Python版本。它更倾向于按用户安装而不是系统安装，并按语言版本排序，而不是使用最新安装的版本。

启动器最初是在 
@geindex Python 提高建议; PEP 397
PEP 397@footnote{https://www.python.org/dev/peps/pep-0397} 中指定的。

@menu
* 入门:: 
* Shebang Lines:: 
* shebang lines 的参数:: 
* 自定义:: 
* 诊断:: 

@end menu

@node 入门,Shebang Lines,,适用于Windows的Python启动器
@anchor{using/windows getting-started}@anchor{14e9}
@subsubsection 入门


@menu
* 从命令行:: 
* 从虚拟环境:: 
* 从脚本:: 
* 从文件关联:: 

@end menu

@node 从命令行,从虚拟环境,,入门
@anchor{using/windows from-the-command-line}@anchor{14ea}
@subsubsection 从命令行



在 3.6 版更改.


全局安装Python 3.3及更高版本将把启动器放在你的 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 上。启动程序与所有可用的Python版本兼容，因此安装哪个版本无关紧要。要检查启动程序是否可用，请在命令提示符中执行以下命令：

@example
py
@end example

您应该会发现已安装的最新版本的Python已启动 - 它可以正常退出，并且将指定的任何其他命令行参数直接发送到Python。

如果您安装了多个版本的Python（例如，3.7和 3.9 ），您会注意到Python 3.9 启动 - 如果要启动 Python 3.7，尝试命令：

@example
py -3.7
@end example

如果您想使用已安装的 Python 2 的最新版本，请尝试以下命令：

@example
py -2
@end example

你会发现 Python 3.x 的最新版本已启动。

如果您看到以下错误，则表明您没有安装启动器：

@example
'py' is not recognized as an internal or external command,
operable program or batch file.
@end example

除非在安装时选择了该选项，单个用户安装的Python不会将启动程序添加到 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 。

Tix 命令：

@example
py --list
@end example

显示当前已安装的Python版本。

@node 从虚拟环境,从脚本,从命令行,入门
@anchor{using/windows virtual-environments}@anchor{14eb}
@subsubsection 从虚拟环境



3.5 新版功能.


如果启动程序运行时没有明确的Python版本，并且虚拟环境（使用标准库创建 @ref{12e,,venv} 模块或外部 @code{virtualenv} 工具）处于活动状态，则启动程序将运行虚拟环境的解释器而不是全局的。要运行全局解释器，请停用虚拟环境，或显式指定全局Python版本。

@node 从脚本,从文件关联,从虚拟环境,入门
@anchor{using/windows from-a-script}@anchor{14ec}
@subsubsection 从脚本


让我们创建一个测试Python脚本 - 创建一个名为`@w{`}hello.py`@w{`}的文件，其中包含以下内容

@example
#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
@end example

从hello.py所在的目录中，执行以下命令：

@example
py hello.py
@end example

您应该注意到最新的Python 2.x安装的版本号已打印出来。现在尝试将第一行更改为：

@example
#! python3
@end example

现在，重新执行该命令应该打印最新的Python 3.x信息。与上面的命令行示例一样，你可以更明确的指定版本限定符。假设您安装了 Python 3.7，请尝试将第一行更改为 @code{#! python3.7} ，你会发现打印的3.7版本信息。

请注意，与交互式使用不同，裸“python”将使用您已安装的Python 2.x的最新版本。这是为了向后兼容及兼容Unix，其中命令 @code{python} 通常是指Python 2。

@node 从文件关联,,从脚本,入门
@anchor{using/windows from-file-associations}@anchor{14ed}
@subsubsection 从文件关联


安装时应该将启动器与Python文件（即 @code{.py}, @code{.pyw}, @code{.pyc} 文件）相关联。这意味着当您从Windows资源管理器中双击其中一个文件时，将使用启动程序，因此您可以使用上述相同的工具让脚本指定应使用的版本。

这样做的主要好处是，单个启动程序可以同时支持多个Python版本，具体取决于第一行的内容。

@node Shebang Lines,shebang lines 的参数,入门,适用于Windows的Python启动器
@anchor{using/windows shebang-lines}@anchor{14ee}
@subsubsection Shebang Lines


如果脚本文件的第一行以 @code{#!} 开头，则称为 "shebang" 行。Linux和其他类Unix操作系统都有对这些行的本机支持，它们通常在此类系统上用来指示应该如何执行脚本。这个启动器允许在Windows上对Python脚本使用相同的工具，上面的示例演示了它们的使用。

为了允许Python脚本中的shebang行在Unix和Windows之间移植，该启动器支持许多“虚拟”命令来指定要使用的解释器。支持的虚拟命令是：


@itemize *

@item 
@code{/usr/bin/env python}

@item 
@code{/usr/bin/python}

@item 
@code{/usr/local/bin/python}

@item 
@code{python}
@end itemize

例如，如果脚本开始的第一行

@example
#! /usr/bin/python
@end example

将找到并使用默认的Python。因为在Unix上编写的许多Python脚本已经有了这一行，你应该发现这些脚本可以由启动器使用而无需修改。如果您在Windows上编写一个新脚本，希望在Unix上有用，那么您应该使用以 @code{/usr} 开头的一个shebang行。

任何上述虚拟命令都可以显式指定版本（可以仅为主要版本，也可以为主要版本加次要版本）作为后缀。 此外，可以通过在次要版本之后添加 “-32” 来请求 32 位版本。 例如 @code{/usr/bin/python3.7-32} 将请求使用 32 位 python 3.7。


3.7 新版功能: 从python启动程序3.7开始，可以通过“-64”后缀调用64位版本。此外，可以指定没有次要的主要和架构（即 @code{/usr/bin/python3-64} ）。


shebang line的 @code{/usr/bin/env} 形式还有一个特殊属性。在寻找已安装的Python解释器之前，此表单将搜索可执行文件 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 以获取Python可执行文件。这对应于Unix中 @code{env} 程序的行为，该程序将在 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 执行搜索。

@node shebang lines 的参数,自定义,Shebang Lines,适用于Windows的Python启动器
@anchor{using/windows arguments-in-shebang-lines}@anchor{14ef}
@subsubsection shebang lines 的参数


shebang lines 还可以指定要传递给Python解释器的其他选项。例如，如果你有一个shebang lines ：

@example
#! /usr/bin/python -v
@end example

然后Python将以 @code{-v} 选项启动

@node 自定义,诊断,shebang lines 的参数,适用于Windows的Python启动器
@anchor{using/windows customization}@anchor{14f0}
@subsubsection 自定义


@menu
* 通过INI文件自定义:: 
* 自定义默认的Python版本:: 

@end menu

@node 通过INI文件自定义,自定义默认的Python版本,,自定义
@anchor{using/windows customization-via-ini-files}@anchor{14f1}
@subsubsection 通过INI文件自定义


启动程序将搜索两个.ini文件 - 在当前用户的 "application data" 目录中搜索 @code{py.ini} （即通过使用 @code{CSIDL_LOCAL_APPDATA} 调用Windows函数 @code{SHGetFolderPath} 返回的目录）以及与启动器位于同一目录中的 @code{py.ini} 。相同的.ini文件既用于启动器的“控制台”版本（即 py.exe），也用于“windows”版本（即pyw.exe）

“应用程序目录”中指定的自定义优先于可执行文件旁边.ini文件的自定义，因此对启动程序旁边的.ini文件不具有写访问权限的用户可以覆盖该全局.ini文件中的命令。

@node 自定义默认的Python版本,,通过INI文件自定义,自定义
@anchor{using/windows customizing-default-python-versions}@anchor{14f2}
@subsubsection 自定义默认的Python版本


在某些情况下，可以在命令中包含版本限定符，以指定命令将使用哪个Python版本。版本限定符以主版本号开头，可以选择后跟 ('.') 和次版本说明符。此外，可以通过添加 "-32" 或 “-64” 来指定是请求32位还是64位实现。

例如，一个shebang line 的 @code{#!python} 行没有版本限定符，而 @code{#!python3} 有一个版本限定符，它只指定一个主要版本。

如果在命令中找不到版本限定符，则可以设置环境变量 
@geindex PY_PYTHON
@geindex 环境变量; PY_PYTHON
@code{PY_PYTHON} 以指定默认版本限定符。 如果未设置，则默认为 "3"。 该变量可以指定能通过命令行传递的任何值，比如 "3", "3.7", "3.7-32" 或 "3.7-64"。 （请注意 "-64" 选项仅适用于 Python 3.7 或更高版本中包含的启动器。）

如果没有找到次要版本限定符，则可以设置环境变量 @code{PY_PYTHON@{major@}} （其中 @code{@{major@}} 是上面确定的当前主要版本限定符）以指定完整版本。如果没有找到这样的选项，启动器将枚举已安装的Python版本并使用为主要版本找到的最新次要版本，尽管不能保证，但该版本可能是该系列中最新安装的版本。

在安装了相同（major.minor）Python版本的32位和64位的64位Windows上，64位版本将始终是首选。对于启动程序的32位和64位实现都是如此 -- 这对于启动程序32位和64位都是正确的 -- 如果可用，32位启动程序将倾向于执行指定版本的64位Python安装。这样就可以预测启动器的行为，只知道PC上安装了哪些版本，而不考虑它们的安装顺序（即，不知道32位或64位版本的Python和相应的启动器是否是最后安装）。如上所述，可以在版本说明符上使用可选的“-32”或“-64”后缀来更改此行为。

示例：


@itemize *

@item 
如果没有设置相关选项，命令 @code{python} 和 @code{python2} 将使用安装的最新Python 2.x版本，命令 @code{python3} 将使用最新安装的Python 3.x.

@item 
命令 @code{python3.7} 根本不会查阅任何选项，因为版本已完全指定。

@item 
如果 @code{PY_PYTHON=3} ，命令`@w{`}python`@w{`} 和 @code{python3} 都将使用最新安装的Python 3版本。

@item 
如果 @code{PY_PYTHON=3.7-32} ，命令 @code{python} 将使用3.7的32位实现，而命令 @code{python3} 将使用最新安装的Python（PY_PYTHON根本没有被视为指定了主要版本。）

@item 
如果 @code{PY_PYTHON=3} 且 @code{PY_PYTHON3=3.7} ，命令 @code{python} 和 @code{python3} 都将特别使用3.7
@end itemize

除环境变量外，还可以在启动程序使用的.INI文件中配置相同的设置。 INI文件中的部分称为 @code{[defaults]} ，键名称将与没有前导 @code{PY_} 前缀的环境变量相同（并注意INI文件中的键名不区分大小写） 。）环境变量的内容将覆盖INI文件中指定的内容。

例如:


@itemize *

@item 
设置 @code{PY_PYTHON=3.7} 等同于包含以下内容的INI文件：
@end itemize

@example
[defaults]
python=3.7
@end example


@itemize *

@item 
设置 @code{PY_PYTHON=3} 和 @code{PY_PYTHON3=3.7} 相当于包含以下内容的INI文件：
@end itemize

@example
[defaults]
python=3
python3=3.7
@end example

@node 诊断,,自定义,适用于Windows的Python启动器
@anchor{using/windows diagnostics}@anchor{14f3}
@subsubsection 诊断


如果设置了环境变量 @code{PYLAUNCH_DEBUG} （任何值），启动器将诊断信息打印到stderr（即：控制台）。虽然这些信息同时具有冗长 @emph{和} 简洁性，但它应该允许您查看Python的版本、选择特定版本的原因以及用于执行目标Python的确切命令行。

@node 查找模块,附加模块,适用于Windows的Python启动器,在Windows上使用 Python
@anchor{using/windows finding-modules}@anchor{5b3}@anchor{using/windows id1}@anchor{14f4}
@subsection 查找模块


Python通常将其库（以及您的site-packages文件夹）存储在安装目录中。因此，如果您已将Python安装到 @code{C:\Python\} ，则默认库将驻留在 @code{C:\Python\Lib\} 中，第三方模块存储在 @code{C:\Python\Lib\site-packages\} 。

若要完全覆盖 @ref{262,,sys.path} ，请创建与DLL(@code{python37._pth})或可执行文件(“python._pth`”)同名的 @code{._pth} 文件，并为要添加的每个路径指定一行 @ref{262,,sys.path} 。基于DLL名称的文件覆盖基于可执行文件的文件，如果需要，可以为加载运行时的任何程序限制路径。

当文件存在时，将忽略所有注册表和环境变量，启用隔离模式，并且：除非文件中的一行指定 @code{import site} ，否则不会导入 @ref{eb,,site} 。以 @code{＃} 开头的空白路径和行将被忽略。每个路径可以是绝对的或相对于文件的位置。不允许使用除 @code{site} 以外的导入语句，并且不能指定任意代码。

请注意，当指定 @code{import site} 时， @code{.pth} 文件（没有前导下划线）将由 @ref{eb,,site} 模块正常处理。

当找不到 @code{._pth} 文件时， @ref{262,,sys.path} 是如何在Windows上填充的：


@itemize *

@item 
在开始时，添加一个空条目，该条目对应于当前目录。

@item 
如果环境变量 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 存在，如 @ref{14b5,,环境变量} 中所述，则接下来添加其条目。请注意，在Windows上，此变量中的路径必须用分号分隔，以区别于驱动器标识符中使用的冒号（ @code{C:\}  等）。

@item 
额外的 "应用程序路径" 可以作为子键被同时添加到注册表 @code{HKEY_CURRENT_USER} 和 @code{HKEY_LOCAL_MACHINE} 分支下的 @code{\SOFTWARE\Python\PythonCore@{version@}\PythonPath} 中。 以分号分隔的路径字符串作为默认值的子键将导致每个路径都被添加到 @ref{262,,sys.path} 中。 （请注意所有已知的安装程序都只使用 HKLM，因此 HKCU 通常为空。）

@item 
如果设置了环境变量 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME}  ，则将其假定为 “Python 主目录” 。否则，主Python可执行文件的路径用于定位 “landmark 文件” （ @code{Lib\os.py} 或 @code{pythonXY.zip} ）以推断 ”Python 主目录“ 。如果找到了Python主目录，则基于该文件夹将相关的子目录添加到 @ref{262,,sys.path} （@code{Lib} , @code{plat-win} 等）。否则，核心Python路径是从存储在注册表中的PythonPath构造的。

@item 
如果找不到Python Home，也没有指定 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 环境变量，并且找不到注册表项，则使用具有相对条目的默认路径（例如 @code{.\Lib; .\plat-win} 等等）。
@end itemize

如果在主可执行文件旁边或在可执行文件上一级的目录中找到 @code{pyvenv.cfg} 文件，则以下变体适用：


@itemize *

@item 
如果 @code{home} 是一个绝对路径，并且 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 未设置，则在推断起始位置时使用此路径而不是主可执行文件的路径。
@end itemize

这一切的最终结果是：


@itemize *

@item 
运行 @code{python.exe} ，或主Python目录中的任何其他.exe（安装版本，或直接来自PCbuild目录）时，推导出核心路径，并忽略注册表中的核心路径。始终读取注册表中的其他“应用程序路径”。

@item 
当Python托管在另一个.exe（不同的目录，通过COM嵌入等）时，将不会推断出“Python Home”，因此使用了来自注册表的核心路径。始终读取注册表中的其他“应用程序路径”。

@item 
如果Python找不到它的主目录并且没有注册表值（冻结的.exe，一些非常奇怪的安装设置），那么你会得到一条带有一些默认但相对的路径的路径。
@end itemize

对于那些想要将Python捆绑到其应用程序或发行版中的人，以下建议将防止与其他安装冲突：


@itemize *

@item 
在您的可执行文件中包含一个 @code{._pth} 文件，其中包含目录。这将忽略注册表和环境变量中列出的路径，并忽略 @ref{eb,,site} ，除非列出 @code{import site} 。

@item 
如果你在自己的可执行文件中加载 @code{python3.dll} 或 @code{python37.dll} ，在 @ref{210,,Py_Initialize()} 之前，要显式调用 @ref{3a4,,Py_SetPath()}  或（至少） @ref{113b,,Py_SetProgramName()}

@item 
清除 和/或 覆盖 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 并在启动来自应用程序的 @code{python.exe} 之前设置 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 。

@item 
如果您不能使用前面的建议（例如，您是一个允许人们直接运行 @code{python.exe} 的分发版），请确保安装目录中存在 landmark 文件 (@code{Lib\os.py})。 （请注意，在 ZIP 文件中不会检测到该文件，但会检测到正确命名的 ZIP 文件。）
@end itemize

这些将确保系统范围安装中的文件不会优先于与应用程序捆绑在一起的标准库的副本。否则，用户可能会在使用您的应用程序时遇到问题请注意，第一个建议是最好的，因为其他建议可能仍然容易受到注册表和用户站点包中的非标准路径的影响。


@quotation
在 3.6 版更改: 

@itemize *

@item 
添加 @code{._pth} 文件支持并从 @code{pyvenv.cfg} 中删除 @code{applocal} 选项

@item 
当直接与可执行文件相邻时，添加 @code{pythonXX.zip} 作为潜在的 landmark 。
@end itemize
@end quotation



@quotation
3.6 版后已移除: 
在 @code{Modules} （不是 @code{PythonPath} ）下的注册表中指定的模块可以通过以下方式导入 @ref{6e6,,importlib.machinery.WindowsRegistryFinder} 。在Windows上，此查找程序在3.6.0及更早版本的可用，但可能需要在将来显式添加到 @ref{6e7,,sys.meta_path}
@end quotation


@node 附加模块,在Windows上编译Python,查找模块,在Windows上使用 Python
@anchor{using/windows additional-modules}@anchor{14f5}
@subsection 附加模块


尽管Python的目标是在所有平台中都可移植，但是Windows有一些独特的特性。在标准库和外部都有一些模块和代码片段在使用这些特性。

特定于Windows的标准模块记录在 @ref{14f6,,Windows系统相关模块} 中。

@menu
* PyWin32:: 
* cx_Freeze:: 

@end menu

@node PyWin32,cx_Freeze,,附加模块
@anchor{using/windows pywin32}@anchor{14f7}
@subsubsection PyWin32


Mark Hammond 的 PyWin32@footnote{https://pypi.org/project/pywin32}  模块是一组用于高级Windows特定支持的模块。这包括以下实用程序：


@itemize *

@item 
组件对象模型@footnote{https://docs.microsoft.com/en-us/windows/win32/com/component-object-model--com--portal} (COM)

@item 
Win32 API 调用

@item 
注册

@item 
事件日志

@item 
Microsoft Foundation Classes@footnote{https://docs.microsoft.com/en-us/cpp/mfc/mfc-desktop-applications} (MFC) 用户界面
@end itemize

PythonWin@footnote{https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/} 是PyWin32附带的一个示例MFC应用程序。它是一个内置调试器的可嵌入IDE。


@subsubheading 参见



@table @asis

@item Win32 How Do I...?@footnote{http://timgolden.me.uk/python/win32_how_do_i.html}

Tim Golden 著

@item Python and COM@footnote{https://www.boddie.org.uk/python/COM.html}

David 和 Paul Boddie 著
@end table


@node cx_Freeze,,PyWin32,附加模块
@anchor{using/windows cx-freeze}@anchor{14f8}
@subsubsection cx_Freeze


cx_Freeze@footnote{https://cx-freeze.readthedocs.io/en/latest/} 是一个 @ref{38,,distutils} 的扩展 (参见 @ref{14f9,,扩展 Distutils})，它将 Python 脚本包装成可执行的 Windows 程序 (@code{@emph{*}.exe} 文件)。 完成此操作后，你就可以分发你的应用程序而无需用户安装 Python。

@node 在Windows上编译Python,其他平台,附加模块,在Windows上使用 Python
@anchor{using/windows compiling-python-on-windows}@anchor{14fa}
@subsection 在Windows上编译Python


如果你想自己编译CPython，首先要做的是获取 source@footnote{https://www.python.org/downloads/source/}. 。您可以下载最新版本的源代码，也可以重新签出 checkout@footnote{https://devguide.python.org/setup/#getting-the-source-code}. 。

源代码树包含Microsoft Visual Studio的构建解决方案和项目文件，它是用于构建官方Python版本的编译器。这些文件位于 @code{PCbuild} 目录中。

检查 @code{PCbuild/readme.txt} 以获取有关构建过程的一般信息。

有关扩展模块，请参阅 @ref{14fb,,在 Windows 上构建 C 和 C++ 扩展} 。

@node 其他平台,,在Windows上编译Python,在Windows上使用 Python
@anchor{using/windows other-platforms}@anchor{14fc}
@subsection 其他平台


随着Python的不断发展，不再支持以前曾经支持的一些平台（由于缺少用户或开发人员）。检查 
@geindex Python 提高建议; PEP 11
PEP 11@footnote{https://www.python.org/dev/peps/pep-0011} 了解所有不支持的平台的详细信息。


@itemize *

@item 
Windows CE@footnote{http://pythonce.sourceforge.net/} 从Python 3开始 不再支持@footnote{https://github.com/python/cpython/issues/71542} （如果曾经支持的话）。

@item 
Cygwin <@indicateurl{https://cygwin.com/}>`_安装程序也提供了安装 Python 解释器@footnote{https://cygwin.com/packages/summary/python3.html} 的功能。
@end itemize

有关具有预编译安装程序平台的详细信息，请参阅 Python for Windows@footnote{https://www.python.org/downloads/windows/}

@node 在 Mac 上使用 Python,编辑器和集成开发环境,在Windows上使用 Python,安装和使用 Python
@anchor{using/mac doc}@anchor{14fd}@anchor{using/mac using-on-mac}@anchor{14fe}@anchor{using/mac using-python-on-a-mac}@anchor{14ff}
@section 在 Mac 上使用 Python


@*作者: 
Bob Savage <@email{bobsavage@@mac.com}>


在运行 macOS 的 Mac 上的 Python 原则上与在其他 Unix 平台上的 Python 非常相似，但有一些额外的特性，如 IDE 和包管理器，值得指出。

@menu
* 获取和安装 MacPython:: 
* IDE:: 
* 安装额外的 Python 包:: 
* Mac 上的图形界面编程:: 
* 在 Mac 上分发 Python 应用程序:: 
* 其他资源:: 

@end menu

@node 获取和安装 MacPython,IDE,,在 Mac 上使用 Python
@anchor{using/mac getting-and-installing-macpython}@anchor{1500}@anchor{using/mac getting-osx}@anchor{1501}
@subsection 获取和安装 MacPython


macOS 从 10.8 版开始就由苹果预装了 Python 2.7 。如果你希望，你可以从 Python 网站 (@indicateurl{https://www.python.org}) 安装最新的 Python 3 版本。 那里有当前的Python的 "通用二进制" 版本，它可以在Mac的新 Intel 和传统的PPC CPU 上运行。

你安装后得到的东西有：


@itemize *

@item 
会有一个 @code{Python 3.9} 文件夹在你的 @code{Applications} 文件夹中。 在这里你可以找到 IDLE，它是作为官方 Python 发行版标准组成部分的开发环境；以及 PythonLauncher，它负责处理在 Finder 中双击 Python 脚本的操作。

@item 
框架 @code{/Library/Frameworks/Python.framework} ，包括 Python 可执行文件和库。安装程序将此位置添加到 shell 路径。 要卸载 MacPython ，你可以简单地移除这三个项目。 Python 可执行文件的符号链接放在 /usr/local/bin/ 中。
@end itemize

Apple 提供的 Python 版本分别安装在 @code{/System/Library/Frameworks/Python.framework} 和 @code{/usr/bin/python} 中。 你永远不应修改或删除这些内容，因为它们由 Apple 控制并由 Apple 或第三方软件使用。 请记住，如果你选择从 python.org 安装较新的 Python 版本，那么你的计算机上将安装两个不同但都有用的 Python ，因此你的路径和用法与你想要执行的操作一致非常重要。

IDLE 包含一个帮助菜单，允许你访问 Python 文档。 如果您是 Python 的新手，你应该开始阅读该文档中的教程介绍。

如果你熟悉其他 Unix 平台上的 Python ，那么你应该阅读有关从 Unix shell 运行 Python 脚本的部分。

@menu
* 如何运行 Python 脚本:: 
* 运行有图形界面的脚本:: 
* 配置:: 

@end menu

@node 如何运行 Python 脚本,运行有图形界面的脚本,,获取和安装 MacPython
@anchor{using/mac how-to-run-a-python-script}@anchor{1502}
@subsubsection 如何运行 Python 脚本


你在 macOS 上开始使用 Python 的最好方法是通过 IDLE 集成开发环境，参见章节 @ref{1503,,IDE} 以及在IDE运行时使用帮助菜单。

如果你想从终端窗口的命令行或 Finder 中运行 Python 脚本，你首先需要一个编辑器来创建你的脚本。macOS 自带了一些标准的 Unix 命令行编辑器， @code{vim} 和 @code{emacs} 就是其中之二。如果你想要一个更 Mac 的编辑器，来自 Bare Bones Software 的 @code{BBEdit} 或 @code{TextWrangler} （见 @indicateurl{http://www.barebones.com/products/bbedit/index.html} ）是不错的选择，还有 @code{TextMate} （见 @indicateurl{https://macromates.com/} ）。其他编辑器包括 @code{Gvim} （ @indicateurl{http://macvim-dev.github.io/macvim/} ）和 @code{Aquamacs} （ @indicateurl{http://aquamacs.org/} ）。

要从终端窗口运行脚本，必须确保:file:@cite{/usr/local/bin} 位于 shell 搜索路径中。

要从 Finder 运行你的脚本，你有两个选择：


@itemize *

@item 
把脚本拖拽到 @code{PythonLauncher}

@item 
选择 @code{PythonLauncher} 作为通过 finder Info 窗口打开脚本（或任何 .py 脚本）的默认应用程序，然后双击脚本。 @code{PythonLauncher} 有各种首选项来控制脚本的启动方式。 拖拽方式允许你为一次调用更改这些选项，或使用其“首选项”菜单全局更改内容。
@end itemize

@node 运行有图形界面的脚本,配置,如何运行 Python 脚本,获取和安装 MacPython
@anchor{using/mac osx-gui-scripts}@anchor{1504}@anchor{using/mac running-scripts-with-a-gui}@anchor{1505}
@subsubsection 运行有图形界面的脚本


对于旧版本的 Python ，有一个需要注意的 macOS 特殊问题：与 Aqua 窗口管理器通信的程序（换句话说，任何有 GUI 的程序）需要以特殊的方式运行。使用 @code{pythonw} 而不是 @code{python} 来启动此类脚本。

对于 Python 3.9，你可以使用 @code{python} 或者 @code{pythonw}。

@node 配置,,运行有图形界面的脚本,获取和安装 MacPython
@anchor{using/mac configuration}@anchor{1506}
@subsubsection 配置


macOS 上的 Python 遵循所有标准的 Unix 环境变量，例如 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} ，但是为从 Finder 启动的程序设置这些变量是不标准的，因为 Finder 在启动时不会读取你的 @code{.profile} 或 @code{.cshrc} 。你需要创建一个文件 @code{~/.MacOSX/environment.plist} 。详情请看苹果的技术文件QA1067。

更多关于在 MacPython 中安装 Python 包的信息，参阅 @ref{1507,,安装额外的 Python 包} 部分。

@node IDE,安装额外的 Python 包,获取和安装 MacPython,在 Mac 上使用 Python
@anchor{using/mac ide}@anchor{1503}@anchor{using/mac the-ide}@anchor{1508}
@subsection IDE


MacPython 附带标准的 IDLE 开发环境。 有关使用 IDLE 的详细介绍，请访问 @indicateurl{http://www.hashcollision.org/hkn/python/idle_intro/index.html} 。

@node 安装额外的 Python 包,Mac 上的图形界面编程,IDE,在 Mac 上使用 Python
@anchor{using/mac installing-additional-python-packages}@anchor{1509}@anchor{using/mac mac-package-manager}@anchor{1507}
@subsection 安装额外的 Python 包


有几个方法可以安装额外的 Python 包：


@itemize *

@item 
可以通过标准的 Python distutils 模式（ @code{python setup.py install} ）安装软件包。

@item 
许多包也可以通过 @code{setuptools} 扩展或 @code{pip} 包装器安装，请参阅 @indicateurl{https://pip.pypa.io/} 。
@end itemize

@node Mac 上的图形界面编程,在 Mac 上分发 Python 应用程序,安装额外的 Python 包,在 Mac 上使用 Python
@anchor{using/mac gui-programming-on-the-mac}@anchor{150a}
@subsection Mac 上的图形界面编程


使用 Python 在 Mac 上构建 GUI 应用程序有多种选择。

@emph{PyObjC} 是一个 Python 到 Apple 的 Objective-C/Cocoa 框架的绑定，这是大多数现代 Mac 开发的基础。 有关 PyObjC 的信息，请访问 @indicateurl{https://pypi.org/project/pyobjc/}。

标准的 Python GUI 工具包是 @ref{10e,,tkinter} ，基于跨平台的 Tk 工具包（ @indicateurl{https://www.tcl.tk} ）。 Apple 的 OS X 捆绑了 Aqua 原生版本的 Tk ，最新版本可以从 @indicateurl{https://www.activestate.com} 下载和安装；它也可以从源代码构建。

@emph{wxPython} 是另一个流行的跨平台 GUI 工具包，可以在 macOS 上原生运行。软件包和文档可从 @indicateurl{https://www.wxpython.org} 获取。

@emph{PyQt} 是另一个流行的跨平台 GUI 工具包，可以在 MacOS 上原生运行。更多信息可以在 @indicateurl{https://riverbankcomputing.com/software/pyqt/intro} 找到。

@node 在 Mac 上分发 Python 应用程序,其他资源,Mac 上的图形界面编程,在 Mac 上使用 Python
@anchor{using/mac distributing-python-applications-on-the-mac}@anchor{150b}
@subsection 在 Mac 上分发 Python 应用程序


在 Mac 上部署独立 Python 应用程序的标准工具是 @code{py2app} 。关于安装和使用 py2app 的更多信息可以在 @indicateurl{https://pypi.org/project/py2app/} 找到。

@node 其他资源,,在 Mac 上分发 Python 应用程序,在 Mac 上使用 Python
@anchor{using/mac other-resources}@anchor{150c}
@subsection 其他资源


MacPython 邮件列表是 Mac 上 Python 用户和开发人员的优秀支持资源：

@indicateurl{https://www.python.org/community/sigs/current/pythonmac-sig/}

另一个有用的资源是 MacPython wiki ：

@indicateurl{https://wiki.python.org/moin/MacPython}

@node 编辑器和集成开发环境,,在 Mac 上使用 Python,安装和使用 Python
@anchor{using/editors doc}@anchor{150d}@anchor{using/editors editors}@anchor{150e}@anchor{using/editors editors-and-ides}@anchor{150f}
@section 编辑器和集成开发环境


有很多支持Python编程语言的集成开发环境。大多数编辑器和集成开发环境支持语法高亮，调试工具和 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 检查。

请访问 Python Editors@footnote{https://wiki.python.org/moin/PythonEditors} 和 Integrated Development Environments@footnote{https://wiki.python.org/moin/IntegratedDevelopmentEnvironments} 以获取完整列表。

@node Python 语言参考手册,Python 标准库,安装和使用 Python,Top
@anchor{reference/index doc}@anchor{1510}@anchor{reference/index reference-index}@anchor{1360}@anchor{reference/index the-python-language-reference}@anchor{1511}
@chapter Python 语言参考手册


本参考手册介绍了 Python 句法与“核心语义”。在力求简明扼要的同时，我们也尽量做到准确、完整。有关内置对象类型、内置函数、模块的语义在 @ref{135f,,Python 标准库} 中介绍。有关本语言的非正式介绍，请参阅 @ref{135e,,Python 教程} 。对于 C 或 C++ 程序员，我们还提供了两个手册：@ref{1361,,扩展和嵌入 Python 解释器} 介绍了如何编写 Python 扩展模块，@ref{1362,,Python/C API 参考手册} 则详细介绍了 C/C++ 的可用接口。

@menu
* 概述: 概述<5>. 
* 词法分析:: 
* 数据模型:: 
* 执行模型:: 
* 导入系统:: 
* 表达式:: 
* 简单语句:: 
* 复合语句:: 
* 顶级组件:: 
* 完整的语法规范:: 

@end menu

@node 概述<5>,词法分析,,Python 语言参考手册
@anchor{reference/introduction doc}@anchor{1512}@anchor{reference/introduction id1}@anchor{1513}@anchor{reference/introduction introduction}@anchor{1514}
@section 概述


本手册仅描述 Python 编程语言，不宜当作教程。

我希望尽可能地保证内容精确无误，但还是选择使用自然词句进行描述，正式的规格定义仅用于句法和词法解析。这样应该能使文档对于普通人来说更易理解，但也可能导致一些歧义。因此，如果你是来自火星并且想凭借这份文档把 Python 重新实现一遍，也许有时需要自行猜测，实际上最终大概会得到一个十分不同的语言。而在另一方面，如果你正在使用 Python 并且想了解有关该语言特定领域的精确规则，你应该能够在这里找到它们。如果你希望查看对该语言更正式的定义，也许你可以花些时间自己写上一份 --- 或者发明一台克隆机器 :-)

在语言参考文档里加入过多的实现细节是很危险的 --- 具体实现可能发生改变，对同一语言的其他实现可能使用不同的方式。而在另一方面，CPython 是得到广泛使用的 Python 实现 (然而其他一些实现的拥护者也在增加)，其中的特殊细节有时也值得一提，特别是当其实现方式导致额外的限制时。因此，你会发现在正文里不时会跳出来一些简短的 "实现注释"。

每种 Python 实现都带有一些内置和标准的模块。相关的文档可参见 @ref{135f,,Python 标准库} 索引。少数内置模块也会在此提及，如果它们同语言描述存在明显的关联。

@menu
* 其他实现:: 
* 标注:: 

@end menu

@node 其他实现,标注,,概述<5>
@anchor{reference/introduction alternate-implementations}@anchor{1515}@anchor{reference/introduction implementations}@anchor{149c}
@subsection 其他实现


虽然官方 Python 实现差不多得到最广泛的欢迎，但也有一些其他实现对特定领域的用户来说更具吸引力。

知名的实现包括:


@table @asis

@item CPython

这是最早出现并持续维护的 Python 实现，以 C 语言编写。新的语言特性通常在此率先添加。

@item Jython

以 Java 语言编写的 Python 实现。此实现可以作为 Java 应用的一个脚本语言，或者可以用来创建需要 Java 类库支持的应用。想了解更多信息可访问 Jython 网站@footnote{http://www.jython.org/}。

@item Python for .NET

此实现实际上使用了 CPython 实现，但是属于 .NET 托管应用并且可以引入 .NET 类库。它的创造者是 Brian Lloyd。想了解详情可访问 Python for .NET 主页@footnote{https://pythonnet.github.io/}。

@item IronPython

另一个 .NET 的 Python 实现，与 Python.NET 不同点在于它是生成 IL 的完全 Python 实现，并且将 Python 代码直接编译为 .NET 程序集。它的创造者就是当初创造 Jython 的 Jim Hugunin。想了解详情可访问 IronPython 网站@footnote{http://ironpython.net/}。

@item PyPy

完全使用 Python 语言编写的 Python 实现。它支持多个其他实现所没有的高级特性，例如非栈式支持和 JIT 编译器等。此项目的目标之一是通过允许方便地修改解释器 (因为它是用 Python 编写的)，鼓励该对语言本身进行试验。想了解详情可访问 PyPy 项目主页@footnote{http://pypy.org/}。
@end table

以上这些实现都可能在某些方面与此参考文档手册的描述有所差异，或是引入了超出标准 Python 文档范围的特定信息。请参考它们各自的专门文档，以确定你正在使用的这个实现有哪些你需要了解的东西。

@node 标注,,其他实现,概述<5>
@anchor{reference/introduction id2}@anchor{1516}@anchor{reference/introduction notation}@anchor{1517}
@subsection 标注


@geindex BNF
@geindex grammar
@geindex syntax
@geindex notation

句法和词法解析的描述采用经过改进的 BNF 语法标注。这包含以下定义样式:

@example
@anchor{reference/introduction grammar-token-name}@anchor{1518}name      ::= lc_letter (lc_letter | "_")*
@anchor{reference/introduction grammar-token-lc-letter}@anchor{1519}lc_letter ::= "a"..."z"
@end example

第一行表示 @code{name} 是 @code{lc_letter} 之后跟零个或多个 @code{lc_letter} 和下划线。而 @code{lc_letter} 则是任意单个 @code{'a'} 至 @code{'z'} 字符。(实际上在本文档中始终采用此规则来定义词法和语法规则的名称。)

每条规则的开头是一个名称 (即该规则所定义的名称) 加上 @code{::=}。 竖线 (@code{|}) 被用来分隔可选项，它是此标注中绑定程度最低的操作符。 星号 (@code{*}) 表示前一项的零次或多次重复，类似地，加号 (@code{+}) 表示一次或多次重复，而由方括号括起的内容 (@code{[ ]}) 表示出现零次或一次 (或者说，这部分内容是可选的)。 @code{*} 和 @code{+} 操作符的绑定是最紧密的，圆括号用于分组。 字符串字面值包含在引号内。 空格的作用仅限于分隔形符。 每条规则通常为一行，有许多个可选项的规则可能会以竖线为界分为多行。

@geindex lexical definitions
@geindex ASCII

在词法定义中 (如上述示例)，还额外使用了两个约定: 由三个点号分隔的两个字符字面值表示在指定 (闭) 区间范围内的任意单个 ASCII 字符。由尖括号 (@code{<...>}) 括起来的内容是对于所定义符号的非正式描述；即可以在必要时用来说明 '控制字符' 的意图。

虽然所用的标注方式几乎相同，但是词法定义和句法定义是存在很大区别的: 词法定义作用于输入源中单独的字符，而句法定义则作用于由词法分析所生成的形符流。在下一章节 ("词法分析") 中使用的 BNF 全部都是词法定义；在之后的章节中使用的则是句法定义。

@node 词法分析,数据模型,概述<5>,Python 语言参考手册
@anchor{reference/lexical_analysis doc}@anchor{151a}@anchor{reference/lexical_analysis lexical}@anchor{151b}@anchor{reference/lexical_analysis lexical-analysis}@anchor{151c}
@section 词法分析


@geindex lexical analysis
@geindex parser
@geindex token

Python 程序由 @emph{解析器} 读取，输入解析器的是 @emph{词法分析器} 生成的 @emph{形符} 流。本章介绍词法分析器怎样把文件拆成形符。

Python 将读取的程序文本转为 Unicode 代码点；编码声明用于指定源文件的编码，默认为 UTF-8，详见 
@geindex Python 提高建议; PEP 3120
PEP 3120@footnote{https://www.python.org/dev/peps/pep-3120}。源文件不能解码时，触发 @ref{562,,SyntaxError}。

@menu
* 行结构:: 
* 其他形符:: 
* 标识符和关键字:: 
* 字面值:: 
* 运算符:: 
* 分隔符:: 

@end menu

@node 行结构,其他形符,,词法分析
@anchor{reference/lexical_analysis id1}@anchor{151d}@anchor{reference/lexical_analysis line-structure}@anchor{151e}
@subsection 行结构


@geindex line structure

Python 程序可以拆分为多个 @emph{逻辑行}。

@menu
* 逻辑行:: 
* 物理行:: 
* 注释:: 
* 编码声明:: 
* 显式拼接行:: 
* 隐式拼接行:: 
* 空白行:: 
* 缩进:: 
* 形符间的空白字符:: 

@end menu

@node 逻辑行,物理行,,行结构
@anchor{reference/lexical_analysis id2}@anchor{151f}@anchor{reference/lexical_analysis logical-lines}@anchor{1520}
@subsubsection 逻辑行


@geindex logical line
@geindex physical line
@geindex line joining
@geindex NEWLINE token

NEWLINE 形符表示结束逻辑行。语句不能超出逻辑行的边界，除非句法支持 NEWLINE （例如，复合语句中的多行子语句）。根据显式或隐式 @emph{行拼接} 规则，一个或多个 @emph{物理行} 可组成逻辑行。

@node 物理行,注释,逻辑行,行结构
@anchor{reference/lexical_analysis id3}@anchor{1521}@anchor{reference/lexical_analysis physical-lines}@anchor{1522}
@subsubsection 物理行


物理行是一序列字符，由行尾序列终止。源文件和字符串可使用任意标准平台行终止序列 - Unix ASCII 字符 LF （换行）、 Windows ASCII 字符序列 CR LF （回车换行）、或老式 Macintosh ASCII 字符 CR （回车）。不管在哪个平台，这些形式均可等价使用。输入结束也可以用作最终物理行的隐式终止符。

嵌入 Python 时，传入 Python API 的源码字符串应使用 C 标准惯例换行符（@code{\n}，代表 ASCII 字符 LF， 行终止符）。

@node 注释,编码声明,物理行,行结构
@anchor{reference/lexical_analysis comments}@anchor{1523}@anchor{reference/lexical_analysis id4}@anchor{1524}
@subsubsection 注释


@geindex comment
@geindex hash character
@geindex # (hash); comment

注释以井号 （@code{#}） 开头，在物理行末尾截止。注意，井号不是字符串字面值。除非应用隐式行拼接规则，否则，注释代表逻辑行结束。句法不解析注释。

@node 编码声明,显式拼接行,注释,行结构
@anchor{reference/lexical_analysis encoding-declarations}@anchor{1525}@anchor{reference/lexical_analysis encodings}@anchor{1526}
@subsubsection 编码声明


@geindex source character set
@geindex encoding declarations (source file)
@geindex # (hash); source encoding declaration

Python 脚本第一或第二行的注释匹配正则表达式 @code{coding[=:]\s*([-\w.]+)} 时，该注释会被当作编码声明；这个表达式的第一组指定了源码文件的编码。编码声明必须独占一行，在第二行时，则第一行必须也是注释。编码表达式的形式如下：

@example
# -*- coding: <encoding-name> -*-
@end example

这也是 GNU Emacs 认可的形式，此外，还支持如下形式：

@example
# vim:fileencoding=<encoding-name>
@end example

这是 Bram Moolenaar 的 VIM 认可的形式。

没有编码声明时，默认编码为 UTF-8。此外，如果文件的首字节为 UTF-8 字节顺序标志（@code{b'\xef\xbb\xbf'}），文件编码也声明为 UTF-8（这是 Microsoft 的 @code{notepad} 等软件支持的形式）。

如果声明了编码格式，该编码格式的名称必须是 Python 可识别的 (参见 @ref{78c,,标准编码})。 编码格式会被用于所有的词法分析，包括字符串字面值、注释和标识符等。

@node 显式拼接行,隐式拼接行,编码声明,行结构
@anchor{reference/lexical_analysis explicit-joining}@anchor{1527}@anchor{reference/lexical_analysis explicit-line-joining}@anchor{1528}
@subsubsection 显式拼接行


@geindex physical line
@geindex line joining
@geindex line continuation
@geindex backslash character

两个及两个以上的物理行可用反斜杠（@code{\}）拼接为一个逻辑行，规则如下：以不在字符串或注释内的反斜杠结尾时，物理行将与下一行拼接成一个逻辑行，并删除反斜杠及其后的换行符。例如：

@example
if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1
@end example

以反斜杠结尾的行，不能加注释；反斜杠也不能拼接注释。除字符串字面值外，反斜杠不能拼接形符（如，除字符串字面值外，不能用反斜杠把形符切分至两个物理行）。反斜杠只能在代码的字符串字面值里，在其他任何位置都是非法的。

@node 隐式拼接行,空白行,显式拼接行,行结构
@anchor{reference/lexical_analysis implicit-joining}@anchor{1529}@anchor{reference/lexical_analysis implicit-line-joining}@anchor{152a}
@subsubsection 隐式拼接行


圆括号、方括号、花括号内的表达式可以分成多个物理行，不必使用反斜杠。例如：

@example
month_names = ['Januari', 'Februari', 'Maart',      # These are the
               'April',   'Mei',      'Juni',       # Dutch names
               'Juli',    'Augustus', 'September',  # for the months
               'Oktober', 'November', 'December']   # of the year
@end example

隐式行拼接可含注释；后续行的缩进并不重要；还支持空的后续行。隐式拼接行之间没有 NEWLINE 形符。三引号字符串支持隐式拼接行（见下文），但不支持注释。

@node 空白行,缩进,隐式拼接行,行结构
@anchor{reference/lexical_analysis blank-lines}@anchor{152b}@anchor{reference/lexical_analysis id5}@anchor{152c}
@subsubsection 空白行


@geindex blank line

只包含空格符、制表符、换页符、注释的逻辑行会被忽略（即不生成 NEWLINE 形符）。交互模式输入语句时，空白行的处理方式可能因读取 - 求值 - 打印循环（REPL）的具体实现方式而不同。标准交互模式解释器中，完全空白的逻辑行（即连空格或注释都没有）将结束多行复合语句。

@node 缩进,形符间的空白字符,空白行,行结构
@anchor{reference/lexical_analysis id6}@anchor{152d}@anchor{reference/lexical_analysis indentation}@anchor{152e}
@subsubsection 缩进


@geindex indentation
@geindex leading whitespace
@geindex space
@geindex tab
@geindex grouping
@geindex statement grouping

逻辑行开头的空白符（空格符和制表符）用于计算该行的缩进层级，决定语句组块。

制表符（从左至右）被替换为一至八个空格，缩进空格的总数是八的倍数（与 Unix 的规则保持一致）。首个非空字符前的空格数决定了该行的缩进层次。缩进不能用反斜杠进行多行拼接；首个反斜杠之前的空白符决定了缩进的层次。

源文件混用制表符和空格符缩进时，因空格数量与制表符相关，由此产生的不一致将导致不能正常识别缩进层次，从而触发 @ref{f3f,,TabError}。

@strong{跨平台兼容性说明：} 鉴于非 UNIX 平台文本编辑器本身的特性，请勿在源文件中混用制表符和空格符。另外也请注意，不同平台有可能会显式限制最大缩进层级。

行首含换页符时，缩进计算将忽略该换页符。换页符在行首空白符内其他位置的效果未定义（例如，可能导致空格计数重置为零）。

@geindex INDENT token
@geindex DEDENT token

连续行的缩进层级以堆栈形式生成 INDENT 和 DEDENT 形符，说明如下。

读取文件第一行前，先向栈推入一个零值，该零值不会被移除。推入栈的层级值从底至顶持续增加。每个逻辑行开头的行缩进层级将与栈顶行比较。如果相等，则不做处理。如果新行层级较高，则会被推入栈顶，并生成一个 INDENT 形符。如果新行层级较低，则 @emph{应当} 是栈中的层级数值之一；栈中高于该层级的所有数值都将被移除，每移除一级数值生成一个 DEDENT 形符。文件末尾，栈中剩余的每个大于零的数值生成一个 DEDENT 形符。

下面的 Python 代码缩进示例虽然正确，但含混不清：

@example
def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r
@end example

下例展示了多种缩进错误：

@example
 def perm(l):                       # error: first line indented
for i in range(len(l)):             # error: not indented
    s = l[:i] + l[i+1:]
        p = perm(l[:i] + l[i+1:])   # error: unexpected indent
        for x in p:
                r.append(l[i:i+1] + x)
            return r                # error: inconsistent dedent
@end example

（实际上，解析器可以识别前三个错误；只有最后一个错误由词法分析器识别  --- @code{return r} 的缩进无法匹配从栈里移除的缩进层级。）

@node 形符间的空白字符,,缩进,行结构
@anchor{reference/lexical_analysis whitespace}@anchor{152f}@anchor{reference/lexical_analysis whitespace-between-tokens}@anchor{1530}
@subsubsection 形符间的空白字符


除非在逻辑行开头或字符串内，空格符、制表符、换页符等空白符都可以分隔形符。要把两个相连形符解读为不同形符，需要用空白符分隔（例如，ab 是一个形符，a b 则是两个形符）。

@node 其他形符,标识符和关键字,行结构,词法分析
@anchor{reference/lexical_analysis id7}@anchor{1531}@anchor{reference/lexical_analysis other-tokens}@anchor{1532}
@subsection 其他形符


除 NEWLINE、INDENT、DEDENT 外，还有 @emph{标识符}、@emph{关键字}、@emph{字面值}、@emph{运算符} 、@emph{分隔符} 等形符。 空白符（前述的行终止符除外）不是形符，可用于分隔形符。存在二义性时，将从左至右，读取尽量长的字符串组成合法形符。

@node 标识符和关键字,字面值,其他形符,词法分析
@anchor{reference/lexical_analysis identifiers}@anchor{1533}@anchor{reference/lexical_analysis identifiers-and-keywords}@anchor{1534}
@subsection 标识符和关键字


@geindex identifier
@geindex name

标识符（也称为 @emph{名称}）的词法定义说明如下。

Python 标识符的句法基于 Unicode 标准附件 UAX-31，并加入了下文定义的细化与修改；详见 
@geindex Python 提高建议; PEP 3131
PEP 3131@footnote{https://www.python.org/dev/peps/pep-3131} 。

与 Python 2.x 一样，在 ASCII 范围内（U+0001..U+007F），有效标识符字符为： 大小写字母 @code{A} 至 @code{Z}、下划线 @code{_} 、数字 @code{0} 至 @code{9}，但不能以数字开头。

Python 3.0 引入了 ASCII 之外的更多字符（请参阅 
@geindex Python 提高建议; PEP 3131
PEP 3131@footnote{https://www.python.org/dev/peps/pep-3131}）。这些字符的分类使用 @ref{123,,unicodedata} 模块中的 Unicode 字符数据库版本。

标识符的长度没有限制，但区分大小写。

@example
@anchor{reference/lexical_analysis grammar-token-identifier}@anchor{1535}identifier   ::= xid_start xid_continue*
@anchor{reference/lexical_analysis grammar-token-id-start}@anchor{1536}id_start     ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
@anchor{reference/lexical_analysis grammar-token-id-continue}@anchor{1537}id_continue  ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
@anchor{reference/lexical_analysis grammar-token-xid-start}@anchor{1538}xid_start    ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
@anchor{reference/lexical_analysis grammar-token-xid-continue}@anchor{1539}xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">
@end example

上述 Unicode 类别码的含义:


@itemize *

@item 
@emph{Lu} - 大写字母

@item 
@emph{Ll} - 小写字母

@item 
@emph{Lt} - 词首大写字母

@item 
@emph{Lm} - 修饰符字母

@item 
@emph{Lo} - 其他字母

@item 
@emph{Nl} - 字母数字

@item 
@emph{Mn} - 非空白标识

@item 
@emph{Mc} - 含空白标识

@item 
@emph{Nd} - 十进制数字

@item 
@emph{Pc} - 连接标点

@item 
@emph{Other_ID_Start} - 由 PropList.txt@footnote{https://www.unicode.org/Public/13.0.0/ucd/PropList.txt} 定义的显式字符列表，用于支持向后兼容

@item 
@emph{Other_ID_Continue} - 同上
@end itemize

在解析时，所有标识符都会被转换为规范形式 NFKC；标识符的比较都是基于 NFKC。

Unicode 4.1 中所有可用的标识符字符详见此 HTML 文件 @indicateurl{https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt}

@menu
* 关键字:: 
* 保留的标识符类:: 

@end menu

@node 关键字,保留的标识符类,,标识符和关键字
@anchor{reference/lexical_analysis id8}@anchor{153a}@anchor{reference/lexical_analysis keywords}@anchor{153b}
@subsubsection 关键字


@geindex keyword
@geindex reserved word

以下标识符为保留字，或称 @emph{关键字}，不可用于普通标识符。关键字的拼写必须与这里列出的完全一致：

@example
False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield
@end example

@geindex _@comma{} identifiers
@geindex __@comma{} identifiers

@node 保留的标识符类,,关键字,标识符和关键字
@anchor{reference/lexical_analysis id-classes}@anchor{153c}@anchor{reference/lexical_analysis reserved-classes-of-identifiers}@anchor{153d}
@subsubsection 保留的标识符类


某些标识符类（除了关键字）具有特殊含义。这些类的命名模式以下划线字符开头，并以下划线结尾：


@table @asis

@item @code{_*}

@code{from module import *} 时，不会导入。交互式解释器中，特殊标识符 @code{_} 用于存储最近一次求值的结果；该标识符保存在 @ref{12,,builtins} 模块里。不处于交互模式时，@code{_} 没有特殊含义，也没有预定义。详见 @ref{cef,,import 语句}。

@cartouche
@quotation 注解 
@code{_} 常用于连接国际化文本；详见 @ref{87,,gettext} 模块文档。
@end quotation
@end cartouche

@item @code{__*__}

系统定义的名称，通常简称为 "dunder" 。这些名称由解释器及其实现（包括标准库）定义。现有系统定义名称相关的论述详见 @ref{610,,特殊方法名称} 等章节。Python 未来版本中还将定义更多此类名称。任何情况下，@emph{任何} 不显式遵从 @code{__*__} 名称的文档用法，都可能导致无警告提示的错误。

@item @code{__*}

类的私有名称。类定义时，此类名称以一种混合形式重写，以避免基类及派生类的 "私有" 属性之间产生名称冲突。详见 @ref{153e,,标识符（名称）}。
@end table

@node 字面值,运算符,标识符和关键字,词法分析
@anchor{reference/lexical_analysis id9}@anchor{153f}@anchor{reference/lexical_analysis literals}@anchor{1540}
@subsection 字面值


@geindex literal
@geindex constant

字面值是内置类型常量值的表示法。

@geindex string literal
@geindex bytes literal
@geindex ASCII
@geindex ' (single quote); string literal
@geindex " (double quote); string literal
@geindex u'; string literal
@geindex u"; string literal

@menu
* 字符串与字节串字面值:: 
* 字符串字面值合并:: 
* 格式字符串字面值:: 
* 数值字面值:: 
* 整数字面值:: 
* 浮点数字面值:: 
* 虚数字面值:: 

@end menu

@node 字符串与字节串字面值,字符串字面值合并,,字面值
@anchor{reference/lexical_analysis string-and-bytes-literals}@anchor{1541}@anchor{reference/lexical_analysis strings}@anchor{1542}
@subsubsection 字符串与字节串字面值


字符串字面值的词法定义如下：

@example
@anchor{reference/lexical_analysis grammar-token-stringliteral}@anchor{1543}stringliteral   ::= [stringprefix](shortstring | longstring)
@anchor{reference/lexical_analysis grammar-token-stringprefix}@anchor{1544}stringprefix    ::= "r" | "u" | "R" | "U" | "f" | "F"
                    | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
@anchor{reference/lexical_analysis grammar-token-shortstring}@anchor{1545}shortstring     ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
@anchor{reference/lexical_analysis grammar-token-longstring}@anchor{1546}longstring      ::= "'@w{'}'" longstringitem* "'@w{'}'" | '"""' longstringitem* '"""'
@anchor{reference/lexical_analysis grammar-token-shortstringitem}@anchor{1547}shortstringitem ::= shortstringchar | stringescapeseq
@anchor{reference/lexical_analysis grammar-token-longstringitem}@anchor{1548}longstringitem  ::= longstringchar | stringescapeseq
@anchor{reference/lexical_analysis grammar-token-shortstringchar}@anchor{1549}shortstringchar ::= <any source character except "\" or newline or the quote>
@anchor{reference/lexical_analysis grammar-token-longstringchar}@anchor{154a}longstringchar  ::= <any source character except "\">
@anchor{reference/lexical_analysis grammar-token-stringescapeseq}@anchor{154b}stringescapeseq ::= "\" <any source character>
@end example

@example
@anchor{reference/lexical_analysis grammar-token-bytesliteral}@anchor{154c}bytesliteral   ::= bytesprefix(shortbytes | longbytes)
@anchor{reference/lexical_analysis grammar-token-bytesprefix}@anchor{154d}bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
@anchor{reference/lexical_analysis grammar-token-shortbytes}@anchor{154e}shortbytes     ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
@anchor{reference/lexical_analysis grammar-token-longbytes}@anchor{154f}longbytes      ::= "'@w{'}'" longbytesitem* "'@w{'}'" | '"""' longbytesitem* '"""'
@anchor{reference/lexical_analysis grammar-token-shortbytesitem}@anchor{1550}shortbytesitem ::= shortbyteschar | bytesescapeseq
@anchor{reference/lexical_analysis grammar-token-longbytesitem}@anchor{1551}longbytesitem  ::= longbyteschar | bytesescapeseq
@anchor{reference/lexical_analysis grammar-token-shortbyteschar}@anchor{1552}shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
@anchor{reference/lexical_analysis grammar-token-longbyteschar}@anchor{1553}longbyteschar  ::= <any ASCII character except "\">
@anchor{reference/lexical_analysis grammar-token-bytesescapeseq}@anchor{1554}bytesescapeseq ::= "\" <any ASCII character>
@end example

上述产生式没有说明以下句法限制，@ref{1544,,stringprefix} 或 @ref{154d,,bytesprefix} 与其他字面值之间不允许有空白符。源字符集由编码声明定义；源文件没有编码声明时，默认为 UTF-8；详见 @ref{1526,,编码声明}。

@geindex triple-quoted string
@geindex Unicode Consortium
@geindex raw string
@geindex """; string literal
@geindex '@w{'}'; string literal

直白的说明：两种类型的字面值都可用成对的单引号 (@code{'}) 或双引号 (@code{"}) 括起来。 它们还可以用成对的连续三个单引号或双引号括起来 (这通常被称为 @emph{三重引号字符串})。 反斜杠 (@code{\}) 字符被用来给予普通的字符特殊含义例如 @code{n}，当用斜杠转义时 (@code{\n}) 表示 '换行'。 它还可以被用来对具有特殊含义的字符进行转义，例如换行符、反斜杠本身或者引号等。 请参阅下面的 @ref{1555,,转义序列} 查看示例。

@geindex b'; bytes literal
@geindex b"; bytes literal

字节串字面值要加前缀 @code{'b'} 或 @code{'B'}；生成的是类型 @ref{172,,bytes} 的实例，不是类型 @ref{206,,str} 的实例；字节串只能包含 ASCII 字符；字节串数值大于等于 128 时，必须用转义表示。

@geindex r'; raw string literal
@geindex r"; raw string literal

字符串和字节串都可以加前缀 @code{'r'} 或 @code{'R'}，称为 @emph{原始字符串}，原始字符串把反斜杠当作原义字符，不执行转义操作。因此，原始字符串不转义 @code{'\U'} 和 @code{'\u'}。与 Python 2.x 的原始 unicode 字面值操作不同，Python 3.x 现已不支持 @code{'ur'} 句法。


3.3 新版功能: 新增原始字节串 @code{'rb'} 前缀，是 @code{'br'} 的同义词。



3.3 新版功能: 支持 unicode 字面值（@code{u'value'}）遗留代码，简化 Python 2.x 和 3.x 并行代码库的维护工作。详见 
@geindex Python 提高建议; PEP 414
PEP 414@footnote{https://www.python.org/dev/peps/pep-0414}。


@geindex f'; formatted string literal
@geindex f"; formatted string literal

前缀为 @code{'f'} 或 @code{'F'} 的字符串称为 @emph{格式字符串}；详见 @ref{29d,,格式字符串字面值}。@code{'f'} 可与 @code{'r'} 连用，但不能与 @code{'b'} 或 @code{'u'} 连用，因此，可以使用原始格式字符串，但不能使用格式字节串字面值。

三引号字面值可以包含未转义的换行和引号（原样保留），除了连在一起的，用于终止字面值的，未经转义的三个引号。（"引号" 是启用字面值的字符，可以是 @code{'}，也可以是 @code{"}。）

@geindex physical line
@geindex escape sequence
@geindex Standard C
@geindex C
@geindex \ (backslash); escape sequence
@geindex \\; escape sequence
@geindex \a; escape sequence
@geindex \b; escape sequence
@geindex \f; escape sequence
@geindex \n; escape sequence
@geindex \r; escape sequence
@geindex \t; escape sequence
@geindex \v; escape sequence
@geindex \x; escape sequence
@geindex \N; escape sequence
@geindex \u; escape sequence
@geindex \U; escape sequence
@anchor{reference/lexical_analysis escape-sequences}@anchor{1555}
如未标注 @code{'r'} 或 @code{'R'} 前缀，字符串和字节串字面值中，转义序列以类似 C 标准的规则进行解释。可用的转义序列如下：


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

转义序列

@tab

意义

@tab

备注

@item

@code{\newline}

@tab

忽略反斜杠与换行符

@tab

@item

@code{\\}

@tab

反斜杠（@code{\}）

@tab

@item

@code{\'}

@tab

单引号（@code{'}）

@tab

@item

@code{\"}

@tab

双引号（@code{"}）

@tab

@item

@code{\a}

@tab

ASCII 响铃（BEL）

@tab

@item

@code{\b}

@tab

ASCII 退格符（BS）

@tab

@item

@code{\f}

@tab

ASCII 换页符（FF）

@tab

@item

@code{\n}

@tab

ASCII 换行符（LF）

@tab

@item

@code{\r}

@tab

ASCII 回车符（CR）

@tab

@item

@code{\t}

@tab

ASCII 水平制表符（TAB）

@tab

@item

@code{\v}

@tab

ASCII 垂直制表符（VT）

@tab

@item

@code{\ooo}

@tab

八进制数 @emph{ooo} 字符

@tab

(1,3)

@item

@code{\xhh}

@tab

十六进制数 @emph{hh} 字符

@tab

(2,3)

@end multitable


字符串字面值专用的转义序列：


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

转义序列

@tab

意义

@tab

备注

@item

@code{\N@{name@}}

@tab

Unicode 数据库中名为 @emph{name} 的字符

@tab

(4)

@item

@code{\uxxxx}

@tab

16 位十六进制数 @emph{xxxx} 码位的字符

@tab

(5)

@item

@code{\Uxxxxxxxx}

@tab

32 位 16 进制数 @emph{xxxxxxxx} 码位的字符

@tab

(6)

@end multitable


注释：


@enumerate 

@item 
与 C 标准一致，接受最多三个八进制数字。

@item 
与 C 标准不同，必须为两个十六进制数字。

@item 
@emph{字节串} 字面值中，十六进制数和八进制数的转义码以相应数值代表每个字节。@emph{字符串} 字面值中，这些转义码以相应数值代表每个 Unicode 字符。

@item 

在 3.3 版更改: 加入了对别名 @footnote{@w{(1)} 
@indicateurl{https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt}
} 的支持。


@item 
必须为 4 个十六进制数码。

@item 
表示任意 Unicode 字符。必须为 8 个十六进制数码。
@end enumerate

@geindex unrecognized escape sequence

与 C 标准不同，无法识别的转义序列在字符串里原样保留，即，@emph{输出结果保留反斜杠}。（调试时，这种方式很有用：输错转义序列时，更容易在输出结果中识别错误。）注意，在字节串字面值内，字符串字面值专用的转义序列属于无法识别的转义序列。

@quotation


在 3.6 版更改: 无法识别的转义序列触发 @ref{15a,,DeprecationWarning}。未来的 Python 发行版将改为触发 @ref{2d0,,SyntaxWarning}，最终会改为触发 @ref{562,,SyntaxError}。

@end quotation

即使在原始字面值中，引号也可以用反斜杠转义，但反斜杠会保留在输出结果里；例如 @code{r"\""} 是由两个字符组成的有效字符串字面值：反斜杠和双引号；@code{r"\"} 则不是有效字符串字面值（原始字符串也不能以奇数个反斜杠结尾）。尤其是，@emph{原始字面值不能以单个反斜杠结尾} （反斜杠会转义其后的引号)。还要注意，反斜杠加换行在字面值中被解释为两个字符，而 @emph{不是} 连续行。

@node 字符串字面值合并,格式字符串字面值,字符串与字节串字面值,字面值
@anchor{reference/lexical_analysis string-concatenation}@anchor{1556}@anchor{reference/lexical_analysis string-literal-concatenation}@anchor{1557}
@subsubsection 字符串字面值合并


以空白符分隔的多个相邻字符串或字节串字面值，可用不同引号标注，等同于合并操作。因此，@code{"hello" 'world'} 等价于 @code{"helloworld"}。此功能不需要反斜杠，即可将长字符串分为多个物理行，还可以为不同部分的字符串添加注释，例如：

@example
re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
          )
@end example

注意，此功能在句法层面定义，在编译时实现。在运行时，合并字符串表达式必须使用 '+' 运算符。还要注意，字面值合并可以为每个部分应用不同的引号风格（甚至混用原始字符串和三引号字符串)，格式字符串字面值也可以与纯字符串字面值合并。

@geindex formatted string literal
@geindex interpolated string literal
@geindex string; formatted literal
@geindex string; interpolated literal
@geindex f-string
@geindex fstring
@geindex @{@} (curly brackets); in formatted string literal
@geindex ! (exclamation); in formatted string literal
@geindex ; (colon); in formatted string literal
@geindex = (equals); for help in debugging using string literals

@node 格式字符串字面值,数值字面值,字符串字面值合并,字面值
@anchor{reference/lexical_analysis f-strings}@anchor{29d}@anchor{reference/lexical_analysis formatted-string-literals}@anchor{1558}
@subsubsection 格式字符串字面值



3.6 新版功能.


@emph{格式字符串字面值} 或称 @emph{f-string} 是标注了 @code{'f'} 或 @code{'F'} 前缀的字符串字面值。这种字符串可包含替换字段，即以 @code{@{@}} 标注的表达式。其他字符串字面值只是常量，格式字符串字面值则是可在运行时求值的表达式。

除非字面值标记为原始字符串，否则，与在普通字符串字面值中一样，转义序列也会被解码。解码后，用于字符串内容的语法如下：

@example
@anchor{reference/lexical_analysis grammar-token-f-string}@anchor{1559}f_string          ::= (literal_char | "@{@{" | "@}@}" | replacement_field)*
@anchor{reference/lexical_analysis grammar-token-replacement-field}@anchor{155a}replacement_field ::= "@{" f_expression ["="] ["!" conversion] [":" format_spec] "@}"
@anchor{reference/lexical_analysis grammar-token-f-expression}@anchor{155b}f_expression      ::= (conditional_expression | "*" or_expr)
                        ("," conditional_expression | "," "*" or_expr)* [","]
                      | yield_expression
@anchor{reference/lexical_analysis grammar-token-conversion}@anchor{155c}conversion        ::= "s" | "r" | "a"
@anchor{reference/lexical_analysis grammar-token-format-spec}@anchor{155d}format_spec       ::= (literal_char | NULL | replacement_field)*
@anchor{reference/lexical_analysis grammar-token-literal-char}@anchor{155e}literal_char      ::= <any code point except "@{", "@}" or NULL>
@end example

双花括号 @code{'@{@{'} 或 @code{'@}@}'} 被替换为单花括号，花括号外的字符串仍按字面值处理。单左花括号 @code{'@{'} 标记以 Python 表达式开头的替换字段。在表达式后加等于号 @code{'='}，可在求值后，同时显示表达式文本及其结果（用于调试）。 随后是用叹号 @code{'!'} 标记的转换字段。还可以在冒号 @code{':'}  后附加格式说明符。替换字段以右花括号 @code{'@}'} 为结尾。

格式字符串字面值中，表达式的处理与圆括号中的常规 Python 表达式基本一样，但也有一些不同的地方。不允许使用空表达式；@ref{d01,,lambda} 和赋值表达式 @code{:=} 必须显式用圆括号标注；替换表达式可以包含换行（例如，三引号字符串中），但不能包含注释；在格式字符串字面值语境内，按从左至右的顺序，为每个表达式求值。


在 3.7 版更改: Python 3.7 以前， 因为实现的问题，不允许在格式字符串字面值表达式中使用 @ref{2df,,await} 表达式与包含 @ref{406,,async for} 子句的推导式。


表达式里含等号 @code{'='} 时，输出内容包括表达式文本、@code{'='} 、求值结果。输出内容可以保留表达式中左花括号 @code{'@{'} 后，及 @code{'='} 后的空格。没有指定格式时，@code{'='} 默认调用表达式的 @ref{8c3,,repr()}。指定了格式时，默认调用表达式的 @ref{206,,str()}，除非声明了转换字段 @code{'!r'}。


3.8 新版功能: 等号 @code{'='}。


指定了转换符时，表达式求值的结果会先转换，再格式化。转换符 @code{'!s'} 调用 @ref{206,,str()} 转换求值结果，@code{'!r'} 调用 @ref{8c3,,repr()}，@code{'!a'} 调用 @ref{e19,,ascii()}。

输出结果的格式化使用 @ref{5de,,format()} 协议。格式说明符传入表达式或转换结果的 @ref{a38,,__format__()} 方法。省略格式说明符，则传入空字符串。然后，格式化结果包含在整个字符串的最终值里。

顶层格式说明符可以包含嵌套替换字段。嵌套字段也可以包含自己的转换字段和 @ref{5e1,,格式说明符}，但不可再包含更深层嵌套的替换字段。@ref{5e1,,格式说明符微语言} 与 @ref{5dd,,str.format()} 方法使用的微语言相同。

格式化字符串字面值可以拼接，但是一个替换字段不能拆分到多个字面值。

格式字符串字面值示例如下：

@example
>>> name = "Fred"
>>> f"He said his name is @{name!r@}."
"He said his name is 'Fred'."
>>> f"He said his name is @{repr(name)@}."  # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: @{value:@{width@}.@{precision@}@}"  # nested fields
'result:      12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"@{today:%B %d, %Y@}"  # using date format specifier
'January 27, 2017'
>>> f"@{today=:%B %d, %Y@}" # using date format specifier and debugging
'today=January 27, 2017'
>>> number = 1024
>>> f"@{number:#0x@}"  # using integer format specifier
'0x400'
>>> foo = "bar"
>>> f"@{ foo = @}" # preserves whitespace
" foo = 'bar'"
>>> line = "The mill's closed"
>>> f"@{line = @}"
'line = "The mill\'s closed"'
>>> f"@{line = :20@}"
"line = The mill's closed   "
>>> f"@{line = !r:20@}"
'line = "The mill\'s closed" '
@end example

与常规字符串字面值的语法一样，替换字段中的字符不能与外层格式字符串字面值的引号冲突：

@example
f"abc @{a["x"]@} def"    # error: outer string literal ended prematurely
f"abc @{a['x']@} def"    # workaround: use different quoting
@end example

格式表达式中不能有反斜杠，否则会报错：

@example
f"newline: @{ord('\n')@}"  # raises SyntaxError
@end example

要使用反斜杠转义的值，则需创建临时变量。

@example
>>> newline = ord('\n')
>>> f"newline: @{newline@}"
'newline: 10'
@end example

即便未包含表达式，格式字符串字面值也不能用作文档字符串。

@example
>>> def foo():
...     f"Not a docstring"
...
>>> foo.__doc__ is None
True
@end example

参阅 
@geindex Python 提高建议; PEP 498
PEP 498@footnote{https://www.python.org/dev/peps/pep-0498}，了解格式字符串字面值的提案，以及与格式字符串机制相关的 @ref{5dd,,str.format()}。

@node 数值字面值,整数字面值,格式字符串字面值,字面值
@anchor{reference/lexical_analysis numbers}@anchor{155f}@anchor{reference/lexical_analysis numeric-literals}@anchor{1560}
@subsubsection 数值字面值


@geindex number
@geindex numeric literal
@geindex integer literal
@geindex floating point literal
@geindex hexadecimal literal
@geindex octal literal
@geindex binary literal
@geindex decimal literal
@geindex imaginary literal
@geindex complex literal

数值字面值有三种类型：整数、浮点数、虚数。没有复数字面值（复数由实数加虚数构成）。

注意，数值字面值不含正负号；实际上，@code{-1} 等负数是由一元运算符 '@code{-}' 和字面值 @code{1} 合成的。

@geindex 0b; integer literal
@geindex 0o; integer literal
@geindex 0x; integer literal
@geindex _ (underscore); in numeric literal

@node 整数字面值,浮点数字面值,数值字面值,字面值
@anchor{reference/lexical_analysis integer-literals}@anchor{1561}@anchor{reference/lexical_analysis integers}@anchor{1562}
@subsubsection 整数字面值


整数字面值词法定义如下：

@example
@anchor{reference/lexical_analysis grammar-token-integer}@anchor{1563}integer      ::= decinteger | bininteger | octinteger | hexinteger
@anchor{reference/lexical_analysis grammar-token-decinteger}@anchor{1564}decinteger   ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
@anchor{reference/lexical_analysis grammar-token-bininteger}@anchor{1565}bininteger   ::= "0" ("b" | "B") (["_"] bindigit)+
@anchor{reference/lexical_analysis grammar-token-octinteger}@anchor{1566}octinteger   ::= "0" ("o" | "O") (["_"] octdigit)+
@anchor{reference/lexical_analysis grammar-token-hexinteger}@anchor{1567}hexinteger   ::= "0" ("x" | "X") (["_"] hexdigit)+
@anchor{reference/lexical_analysis grammar-token-nonzerodigit}@anchor{1568}nonzerodigit ::= "1"..."9"
@anchor{reference/lexical_analysis grammar-token-digit}@anchor{1569}digit        ::= "0"..."9"
@anchor{reference/lexical_analysis grammar-token-bindigit}@anchor{156a}bindigit     ::= "0" | "1"
@anchor{reference/lexical_analysis grammar-token-octdigit}@anchor{156b}octdigit     ::= "0"..."7"
@anchor{reference/lexical_analysis grammar-token-hexdigit}@anchor{156c}hexdigit     ::= digit | "a"..."f" | "A"..."F"
@end example

整数字面值的长度没有限制，能一直大到占满可用内存。

确定数值时，会忽略字面值中的下划线。下划线只是为了分组数字，让数字更易读。下划线可在数字之间，也可在 @code{0x} 等基数说明符后。

注意，除了 0 以外，十进制数字的开头不允许有零。以免与 Python 3.0 版之前使用的 C 样式八进制字面值混淆。

整数字面值示例如下：

@example
7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101
@end example


在 3.6 版更改: 现已支持在字面值中，用下划线分组数字。


@geindex . (dot); in numeric literal
@geindex e; in numeric literal
@geindex _ (underscore); in numeric literal

@node 浮点数字面值,虚数字面值,整数字面值,字面值
@anchor{reference/lexical_analysis floating}@anchor{156d}@anchor{reference/lexical_analysis floating-point-literals}@anchor{156e}
@subsubsection 浮点数字面值


浮点数字面值词法定义如下：

@example
@anchor{reference/lexical_analysis grammar-token-floatnumber}@anchor{156f}floatnumber   ::= pointfloat | exponentfloat
@anchor{reference/lexical_analysis grammar-token-pointfloat}@anchor{1570}pointfloat    ::= [digitpart] fraction | digitpart "."
@anchor{reference/lexical_analysis grammar-token-exponentfloat}@anchor{1571}exponentfloat ::= (digitpart | pointfloat) exponent
@anchor{reference/lexical_analysis grammar-token-digitpart}@anchor{1572}digitpart     ::= digit (["_"] digit)*
@anchor{reference/lexical_analysis grammar-token-fraction}@anchor{1573}fraction      ::= "." digitpart
@anchor{reference/lexical_analysis grammar-token-exponent}@anchor{1574}exponent      ::= ("e" | "E") ["+" | "-"] digitpart
@end example

注意，解析时，整数和指数部分总以 10 为基数。例如，@code{077e010} 是合法的，表示的数值与 @code{77e10} 相同。浮点数字面值的支持范围取决于具体实现。整数字面值支持用下划线分组数字。

浮点数字面值示例如下：

@example
3.14    10.    .001    1e100    3.14e-10    0e0    3.14_15_93
@end example


在 3.6 版更改: 现已支持在字面值中，用下划线分组数字。


@geindex j; in numeric literal

@node 虚数字面值,,浮点数字面值,字面值
@anchor{reference/lexical_analysis imaginary}@anchor{1575}@anchor{reference/lexical_analysis imaginary-literals}@anchor{1576}
@subsubsection 虚数字面值


虚数字面值词法定义如下：

@example
@anchor{reference/lexical_analysis grammar-token-imagnumber}@anchor{1577}imagnumber ::= (floatnumber | digitpart) ("j" | "J")
@end example

虚数字面值生成实部为 0.0 的复数。复数由一对浮点数表示，它们的取值范围相同。创建实部不为零的复数，则需添加浮点数，例如 @code{(3+4j)}。虚数字面值示例如下：

@example
3.14j   10.j    10j     .001j   1e100j   3.14e-10j   3.14_15_93j
@end example

@node 运算符,分隔符,字面值,词法分析
@anchor{reference/lexical_analysis id11}@anchor{1578}@anchor{reference/lexical_analysis operators}@anchor{1579}
@subsection 运算符


@geindex operators

运算符如下所示：

@example
+       -       *       **      /       //      %      @@
<<      >>      &       |       ^       ~       :=
<       >       <=      >=      ==      !=
@end example

@node 分隔符,,运算符,词法分析
@anchor{reference/lexical_analysis delimiters}@anchor{157a}@anchor{reference/lexical_analysis id12}@anchor{157b}
@subsection 分隔符


@geindex delimiters

以下形符在语法中为分隔符：

@example
(       )       [       ]       @{       @}
,       :       .       ;       @@       =       ->
+=      -=      *=      /=      //=     %=      @@=
&=      |=      ^=      >>=     <<=     **=
@end example

句点也可以用于浮点数和虚数字面值。三个连续句点表示省略符。列表后半部分是增强赋值操作符，用作词法分隔符，但也可以执行运算。

以下 ASCII 字符具有特殊含义，对词法分析器有重要意义：

@example
'       "       #       \
@end example

以下 ASCII 字符不用于 Python。在字符串字面值或注释外使用时，将直接报错：

@example
$       ?       `
@end example

@node 数据模型,执行模型,词法分析,Python 语言参考手册
@anchor{reference/datamodel doc}@anchor{157c}@anchor{reference/datamodel data-model}@anchor{157d}@anchor{reference/datamodel datamodel}@anchor{10a2}
@section 数据模型


@menu
* 对象、值与类型:: 
* 标准类型层级结构:: 
* 特殊方法名称:: 
* 协程:: 

@end menu

@node 对象、值与类型,标准类型层级结构,,数据模型
@anchor{reference/datamodel objects}@anchor{157e}@anchor{reference/datamodel objects-values-and-types}@anchor{157f}
@subsection 对象、值与类型


@geindex object
@geindex data

@emph{对象} 是 Python 中对数据的抽象。 Python 程序中的所有数据都是由对象或对象间关系来表示的。 （从某种意义上说，按照冯·诺依曼的“存储程序计算机”模型，代码本身也是由对象来表示的。）

@geindex 內置函数; id
@geindex 內置函数; type
@geindex identity of an object
@geindex value of an object
@geindex type of an object
@geindex mutable object
@geindex immutable object

@c XXX it *is* now possible in some cases to change an object's
@c type, under certain controlled conditions

每个对象都有各自的标识号、类型和值。一个对象被创建后，它的 @emph{标识号} 就绝不会改变；你可以将其理解为该对象在内存中的地址。 '@ref{1580,,is}' 运算符可以比较两个对象的标识号是否相同；@ref{e53,,id()} 函数能返回一个代表其标识号的整数。

@strong{CPython implementation detail:} 在 CPython 中，@code{id(x)} 就是存放 @code{x} 的内存的地址。

对象的类型决定该对象所支持的操作 (例如 "对象是否有长度属性？") 并且定义了该类型的对象可能的取值。@ref{709,,type()} 函数能返回一个对象的类型 (类型本身也是对象)。与编号一样，一个对象的 @emph{类型} 也是不可改变的。@footnote{@w{(1)} 
在某些情况下 @emph{有可能} 基于可控的条件改变一个对象的类型。 但这通常不是个好主意，因为如果处理不当会导致一些非常怪异的行为。
}

有些对象的 @emph{值} 可以改变。值可以改变的对象被称为 @emph{可变对象}；值不可以改变的对象就被称为 @emph{不可变对象}。(一个不可变容器对象如果包含对可变对象的引用，当后者的值改变时，前者的值也会改变；但是该容器仍属于不可变对象，因为它所包含的对象集是不会改变的。因此，不可变并不严格等同于值不能改变，实际含义要更微妙。) 一个对象的可变性是由其类型决定的；例如，数字、字符串和元组是不可变的，而字典和列表是可变的。

@geindex garbage collection
@geindex reference counting
@geindex unreachable object

对象绝不会被显式地销毁；然而，当无法访问时它们可能会被作为垃圾回收。允许具体的实现推迟垃圾回收或完全省略此机制 --- 如何实现垃圾回收是实现的质量问题，只要可访问的对象不会被回收即可。

@strong{CPython implementation detail:} CPython 目前使用带有 (可选) 延迟检测循环链接垃圾的引用计数方案，会在对象不可访问时立即回收其中的大部分，但不保证回收包含循环引用的垃圾。请查看 @ref{84,,gc} 模块的文档了解如何控制循环垃圾的收集相关信息。其他实现会有不同的行为方式，CPython 现有方式也可能改变。不要依赖不可访问对象的立即终结机制 (所以你应当总是显式地关闭文件)。

注意：使用实现的跟踪或调试功能可能令正常情况下会被回收的对象继续存活。还要注意通过 '@ref{e3f,,try}...@ref{c19,,except}' 语句捕捉异常也可能令对象保持存活。

有些对象包含对 "外部" 资源的引用，例如打开文件或窗口。当对象被作为垃圾回收时这些资源也应该会被释放，但由于垃圾回收并不确保发生，这些对象还提供了明确地释放外部资源的操作，通常为一个 @code{close()} 方法。强烈推荐在程序中显式关闭此类对象。'@ref{e3f,,try}...@ref{2c3,,finally}' 语句和 '@ref{7e4,,with}' 语句提供了进行此种操作的更便捷方式。

@geindex container

有些对象包含对其他对象的引用；它们被称为 @emph{容器}。容器的例子有元组、列表和字典等。这些引用是容器对象值的组成部分。在多数情况下，当谈论一个容器的值时，我们是指所包含对象的值而不是其编号；但是，当我们谈论一个容器的可变性时，则仅指其直接包含的对象的编号。因此，如果一个不可变容器 (例如元组) 包含对一个可变对象的引用，则当该可变对象被改变时容器的值也会改变。

类型会影响对象行为的几乎所有方面。甚至对象编号的重要性也在某种程度上受到影响: 对于不可变类型，会得出新值的运算实际上会返回对相同类型和取值的任一现有对象的引用，而对于可变类型来说这是不允许的。例如在 @code{a = 1; b = 1} 之后，@code{a} 和 @code{b} 可能会也可能不会指向同一个值为一的对象，这取决于具体实现，但是在 @code{c = []; d = []} 之后，@code{c} 和 @code{d} 保证会指向两个不同、单独的新建空列表。(请注意 @code{c = d = []} 则是将同一个对象赋值给 @code{c} 和 @code{d}。)

@node 标准类型层级结构,特殊方法名称,对象、值与类型,数据模型
@anchor{reference/datamodel the-standard-type-hierarchy}@anchor{1581}@anchor{reference/datamodel types}@anchor{1582}
@subsection 标准类型层级结构


@geindex type
@geindex data; type
@geindex type; hierarchy
@geindex extension; module
@geindex C; language

以下是 Python 内置类型的列表。扩展模块 (具体实现会以 C, Java 或其他语言编写) 可以定义更多的类型。未来版本的 Python 可能会加入更多的类型 (例如有理数、高效存储的整型数组等等)，不过新增类型往往都是通过标准库来提供的。

@geindex attribute
@geindex special; attribute
@geindex generic; special; attribute

以下部分类型的描述中包含有 '特殊属性列表' 段落。这些属性提供对具体实现的访问而非通常使用。它们的定义在未来可能会改变。


@table @asis

@item None

@geindex 对象; None

此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称 @code{None} 访问。在许多情况下它被用来表示空值，例如未显式指明返回值的函数将返回 None。它的逻辑值为假。

@item NotImplemented

@geindex 对象; NotImplemented

此类型只有一种取值。 是一个具有该值的单独对象。 此对象通过内置名称 @code{NotImplemented} 访问。 数值方法和丰富比较方法如未实现指定运算符表示的运算则应返回该值。 （解释器会根据具体运算符继续尝试反向运算或其他回退操作。） 它不应被解读为布尔值。

详情参见 @ref{1583,,实现算术运算}。


在 3.9 版更改: 作为布尔值来解读 @code{NotImplemented} 已被弃用。 虽然它目前会被解读为真值，但将同时发出 @ref{15a,,DeprecationWarning}。 它将在未来的 Python 版本中引发 @ref{1ff,,TypeError}。


@item Ellipsis

@geindex 对象; Ellipsis
@geindex ...; ellipsis literal

此类型只有一种取值。是一个具有此值的单独对象。此对象通过字面值 @code{...} 或内置名称 @code{Ellipsis} 访问。它的逻辑值为真。

@item @ref{1584,,numbers.Number}

@geindex 对象; numeric

此类对象由数字字面值创建，并会被作为算术运算符和算术内置函数的返回结果。数字对象是不可变的；一旦创建其值就不再改变。Python 中的数字当然非常类似数学中的数字，但也受限于计算机中的数字表示方法。

数字类的字符串表示形式，由 @ref{453,,__repr__()} 和 @ref{f01,,__str__()} 算出，具有以下特征属性:


@itemize *

@item 
它们是有效的数字字面值，当被传给它们的类构造器时，将会产生具有原数字值的对象。

@item 
表示形式会在可能的情况下采用 10 进制。

@item 
开头的零，除小数点前可能存在的单个零之外，将不会被显示。

@item 
末尾的零，除小数点后可能存在的单个零之外，将不会被显示。

@item 
正负号仅在当数字为负值时会被显示。
@end itemize

Python 区分整型数、浮点型数和复数:


@table @asis

@item @ref{1585,,numbers.Integral}

@geindex 对象; integer

此类对象表示数学中整数集合的成员 (包括正数和负数)。

整型数可细分为两种类型:


@table @asis

@item 整型 (@ref{205,,int})

此类对象表示任意大小的数字，仅受限于可用的内存 (包括虚拟内存)。在变换和掩码运算中会以二进制表示，负数会以 2 的补码表示，看起来像是符号位向左延伸补满空位。

@item 布尔型 (@ref{2c4,,bool})

@geindex 对象; Boolean
@geindex False
@geindex True

此类对象表示逻辑值 False 和 True。代表 @code{False} 和 @code{True} 值的两个对象是唯二的布尔对象。布尔类型是整型的子类型，两个布尔值在各种场合的行为分别类似于数值 0 和 1，例外情况只有在转换为字符串时分别返回字符串 @code{"False"} 或 @code{"True"}。
@end table

@geindex integer; representation

整型数表示规则的目的是在涉及负整型数的变换和掩码运算时提供最为合理的解释。

@item @ref{1586,,numbers.Real} (@ref{1fe,,float})

@geindex 对象; floating point
@geindex floating point; number
@geindex C; language
@geindex Java; language

此类对象表示机器级的双精度浮点数。其所接受的取值范围和溢出处理将受制于底层的机器架构 (以及 C 或 Java 实现)。Python 不支持单精度浮点数；支持后者通常的理由是节省处理器和内存消耗，但这点节省相对于在 Python 中使用对象的开销来说太过微不足道，因此没有理由包含两种浮点数而令该语言变得复杂。

@item @ref{1587,,numbers.Complex} (@ref{2c8,,complex})

@geindex 对象; complex
@geindex complex; number

此类对象以一对机器级的双精度浮点数来表示复数值。有关浮点数的附带规则对其同样有效。一个复数值 @code{z} 的实部和虚部可通过只读属性 @code{z.real} 和 @code{z.imag} 来获取。
@end table

@item 序列

@geindex 內置函数; len
@geindex 对象; sequence
@geindex index operation
@geindex item selection
@geindex subscription

此类对象表示以非负整数作为索引的有限有序集。内置函数 @ref{292,,len()} 可返回一个序列的条目数量。当一个序列的长度为 @emph{n} 时，索引集包含数字 0, 1, ..., @emph{n}-1。序列 @emph{a} 的条目 @emph{i} 可通过 @code{a[i]} 选择。

@geindex slicing

序列还支持切片: @code{a[i:j]} 选择索引号为 @emph{k} 的所有条目，@emph{i} @code{<=} @emph{k} @code{<} @emph{j}。当用作表达式时，序列的切片就是一个与序列类型相同的新序列。新序列的索引还是从 0 开始。

有些序列还支持带有第三个 "step" 形参的 "扩展切片": @code{a[i:j:k]} 选择 @emph{a} 中索引号为 @emph{x} 的所有条目，@code{x = i + n*k}, @emph{n} @code{>=} @code{0} 且 @emph{i} @code{<=} @emph{x} @code{<} @emph{j}。

序列可根据其可变性来加以区分:


@table @asis

@item 不可变序列

@geindex 对象; immutable sequence
@geindex 对象; immutable

不可变序列类型的对象一旦创建就不能再改变。(如果对象包含对其他对象的引用，其中的可变对象就是可以改变的；但是，一个不可变对象所直接引用的对象集是不能改变的。)

以下类型属于不可变对象:

@geindex string; immutable sequences


@table @asis

@item 字符串

@geindex 內置函数; chr
@geindex 內置函数; ord
@geindex character
@geindex integer
@geindex Unicode

字符串是由 Unicode 码位值组成的序列。范围在 @code{U+0000 - U+10FFFF} 之内的所有码位值都可在字符串中使用。Python 没有 @code{char} 类型；而是将字符串中的每个码位表示为一个长度为 @code{1} 的字符串对象。内置函数 @ref{1588,,ord()} 可将一个码位由字符串形式转换成一个范围在 @code{0 - 10FFFF} 之内的整型数；@ref{1589,,chr()} 可将一个范围在 @code{0 - 10FFFF} 之内的整型数转换为长度为 @code{1} 的对应字符串对象。@ref{170,,str.encode()} 可以使用指定的文本编码将 @ref{206,,str} 转换为 @ref{172,,bytes}，而 @ref{171,,bytes.decode()} 则可以实现反向的解码。

@item 元组

@geindex 对象; tuple
@geindex singleton; tuple
@geindex empty; tuple

一个元组中的条目可以是任意 Python 对象。包含两个或以上条目的元组由逗号分隔的表达式构成。只有一个条目的元组 ('单项元组') 可通过在表达式后加一个逗号来构成 (一个表达式本身不能创建为元组，因为圆括号要用来设置表达式分组)。一个空元组可通过一对内容为空的圆括号创建。

@item 字节串

@geindex bytes
@geindex byte

字节串对象是不可变的数组。其中每个条目都是一个 8 位字节，以取值范围 0 <= x < 256 的整型数表示。字节串字面值 (例如 @code{b'abc'}) 和内置的 @ref{172,,bytes()} 构造器可被用来创建字节串对象。字节串对象还可以通过 @ref{171,,decode()} 方法解码为字符串。
@end table

@item 可变序列

@geindex 对象; mutable sequence
@geindex 对象; mutable
@geindex assignment; statement
@geindex subscription
@geindex slicing

可变序列在被创建后仍可被改变。下标和切片标注可被用作赋值和 @ref{13d1,,del} (删除) 语句的目标。

目前有两种内生可变序列类型:


@table @asis

@item 列表

@geindex 对象; list

列表中的条目可以是任意 Python 对象。列表由用方括号括起并由逗号分隔的多个表达式构成。(注意创建长度为 0 或 1 的列表无需使用特殊规则。)

@item 字节数组

@geindex bytearray

字节数组对象属于可变数组。可以通过内置的 @ref{173,,bytearray()} 构造器来创建。除了是可变的 (因而也是不可哈希的)，在其他方面字节数组提供的接口和功能都与不可变的 @ref{172,,bytes} 对象一致。
@end table

@geindex 模块; array

扩展模块 @ref{6,,array} 提供了一个额外的可变序列类型示例，@ref{1d,,collections} 模块也是如此。
@end table

@item 集合类型

@geindex 內置函数; len
@geindex 对象; set type

此类对象表示由不重复且不可变对象组成的无序且有限的集合。因此它们不能通过下标来索引。但是它们可被迭代，也可用内置函数 @ref{292,,len()} 返回集合中的条目数。集合常见的用处是快速成员检测，去除序列中的重复项，以及进行交、并、差和对称差等数学运算。

对于集合元素所采用的不可变规则与字典的键相同。注意数字类型遵循正常的数字比较规则: 如果两个数字相等 (例如 @code{1} 和 @code{1.0})，则同一集合中只能包含其中一个。

目前有两种内生集合类型:


@table @asis

@item 集合

@geindex 对象; set

此类对象表示可变集合。它们可通过内置的 @ref{1f7,,set()} 构造器创建，并且创建之后可以通过方法进行修改，例如 @code{add()}。

@item 冻结集合

@geindex 对象; frozenset

此类对象表示不可变集合。它们可通过内置的 @ref{1f8,,frozenset()} 构造器创建。由于 frozenset 对象不可变且 @ref{277,,hashable}，它可以被用作另一个集合的元素或是字典的键。
@end table

@item 映射

@geindex 內置函数; len
@geindex subscription
@geindex 对象; mapping

此类对象表示由任意索引集合所索引的对象的集合。通过下标 @code{a[k]} 可在映射 @code{a} 中选择索引为 @code{k} 的条目；这可以在表达式中使用，也可作为赋值或 @ref{13d1,,del} 语句的目标。内置函数 @ref{292,,len()} 可返回一个映射中的条目数。

目前只有一种内生映射类型:


@table @asis

@item 字典

@geindex 对象; dictionary

此类对象表示由几乎任意值作为索引的有限个对象的集合。不可作为键的值类型只有包含列表或字典或其他可变类型，通过值而非对象编号进行比较的值，其原因在于高效的字典实现需要使用键的哈希值以保持一致性。用作键的数字类型遵循正常的数字比较规则: 如果两个数字相等 (例如 @code{1} 和 @code{1.0}) 则它们均可来用来索引同一个字典条目。

字典会保留插入顺序，这意味着键将以它们被添加的顺序在字典中依次产生。 替换某个现有的键不会改变其顺序，但是移除某个键再重新插入则会将其添加到末尾而不会保留其原有位置。

字典是可变的；它们可通过 @code{@{...@}} 标注来创建 (参见 @ref{74b,,字典显示} 小节)。

@geindex 模块; dbm.ndbm
@geindex 模块; dbm.gnu

扩展模块 @ref{34,,dbm.ndbm} 和 @ref{33,,dbm.gnu} 提供了额外的映射类型示例，@ref{1d,,collections} 模块也是如此。


在 3.7 版更改: 在 Python 3.6 版之前字典不会保留插入顺序。 在 CPython 3.6 中插入顺序会被保留，但这在当时被当作是一个实现细节而非确定的语言特性。

@end table

@item 可调用类型

@geindex 对象; callable
@geindex function; call
@geindex invocation
@geindex function; argument

此类型可以被应用于函数调用操作 (参见 @ref{749,,调用} 小节):


@table @asis

@item 用户定义函数

@geindex user-defined; function
@geindex 对象; function
@geindex 对象; user-defined function

用户定义函数对象可通过函数定义来创建 (参见 @ref{13bf,,函数定义} 小节)。它被调用时应附带一个参数列表，其中包含的条目应与函数所定义的形参列表一致。

特殊属性:

@geindex __doc__ (function attribute)
@geindex __name__ (function attribute)
@geindex __module__ (function attribute)
@geindex __dict__ (function attribute)
@geindex __defaults__ (function attribute)
@geindex __closure__ (function attribute)
@geindex __code__ (function attribute)
@geindex __globals__ (function attribute)
@geindex __annotations__ (function attribute)
@geindex __kwdefaults__ (function attribute)
@geindex global; namespace


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

属性

@tab

意义

@tab

@item

@code{__doc__}

@tab

该函数的文档字符串，没有则为 @code{None}；不会被子类继承。

@tab

可写

@item

@ref{d37,,__name__}

@tab

该函数的名称。

@tab

可写

@item

@ref{158a,,__qualname__}

@tab

该函数的 @ref{158b,,qualified name}。


3.3 新版功能.


@tab

可写

@item

@code{__module__}

@tab

该函数所属模块的名称，没有则为 @code{None}。

@tab

可写

@item

@code{__defaults__}

@tab

由具有默认值的参数的默认参数值组成的元组，如无任何参数具有默认值则为 @code{None}。

@tab

可写

@item

@code{__code__}

@tab

表示编译后的函数体的代码对象。

@tab

可写

@item

@code{__globals__}

@tab

对存放该函数中全局变量的字典的引用 --- 函数所属模块的全局命名空间。

@tab

只读

@item

@ref{5fe,,__dict__}

@tab

命名空间支持的函数属性。

@tab

可写

@item

@code{__closure__}

@tab

@code{None} 或包含该函数可用变量的绑定的单元的元组。有关 @code{cell_contents} 属性的详情见下。

@tab

只读

@item

@code{__annotations__}

@tab

包含参数标注的字典。字典的键是参数名，如存在返回标注则为 @code{'return'}。

@tab

可写

@item

@code{__kwdefaults__}

@tab

仅包含关键字参数默认值的字典。

@tab

可写

@end multitable


大部分标有 "Writable" 的属性均会检查赋值的类型。

函数对象也支持获取和设置任意属性，例如这可以被用来给函数附加元数据。使用正规的属性点号标注获取和设置此类属性。@emph{注意当前实现仅支持用户定义函数属性。未来可能会增加支持内置函数属性。}

单元对象具有 @code{cell_contents} 属性。这可被用来获取以及设置单元的值。

有关函数定义的额外信息可以从其代码对象中提取；参见下文对内部类型的描述。 @ref{158c,,cell} 类型可以在 @ref{121,,types} 模块中访问。

@item 实例方法

@geindex 对象; method
@geindex 对象; user-defined method
@geindex user-defined; method

实例方法用于结合类、类实例和任何可调用对象 (通常为用户定义函数)。

@geindex __func__ (method attribute)
@geindex __self__ (method attribute)
@geindex __doc__ (method attribute)
@geindex __name__ (method attribute)
@geindex __module__ (method attribute)

特殊的只读属性: @code{__self__} 为类实例对象本身，@code{__func__} 为函数对象；@code{__doc__} 为方法的文档 (与 @code{__func__.__doc__} 作用相同)；@ref{d37,,__name__} 为方法名称 (与 @code{__func__.__name__} 作用相同)；@code{__module__} 为方法所属模块的名称，没有则为 @code{None}。

方法还支持获取 (但不能设置) 下层函数对象的任意函数属性。

用户定义方法对象可在获取一个类的属性时被创建 (也可能通过该类的一个实例)，如果该属性为用户定义函数对象或类方法对象。

当通过从类实例获取一个用户定义函数对象的方式创建一个实例方法对象时，类实例对象的 @code{__self__} 属性即为该实例，并会绑定方法对象。该新建方法的 @code{__func__} 属性就是原来的函数对象。

当通过从类或实例获取一个类方法对象的方式创建一个实例对象时，实例对象的 @code{__self__} 属性为该类本身，其 @code{__func__} 属性为类方法对应的下层函数对象。

当一个实例方法对象被调用时，会调用对应的下层函数 (@code{__func__})，并将类实例 (@code{__self__}) 插入参数列表的开头。例如，当 @code{C} 是一个包含了 @code{f()} 函数定义的类，而 @code{x} 是 @code{C} 的一个实例，则调用 @code{x.f(1)} 就等同于调用 @code{C.f(x, 1)}。

当一个实例方法对象是衍生自一个类方法对象时，保存在 @code{__self__} 中的 "类实例" 实际上会是该类本身，因此无论是调用 @code{x.f(1)} 还是 @code{C.f(1)} 都等同于调用 @code{f(C,1)}，其中 @code{f} 为对应的下层函数。

请注意从函数对象到实例方法对象的变换会在每一次从实例获取属性时发生。在某些情况下，一种高效的优化方式是将属性赋值给一个本地变量并调用该本地变量。还要注意这样的变换只发生于用户定义函数；其他可调用对象 (以及所有不可调用对象) 在被获取时都不会发生变换。还有一个需要关注的要点是作为一个类实例属性的用户定义函数不会被转换为绑定方法；这样的变换 @emph{仅当} 函数是类属性时才会发生。

@item 生成器函数

@geindex generator; function
@geindex generator; iterator

一个使用 @ref{2ce,,yield} 语句 （见 @ref{2ce,,yield 语句} 章节）的函数或方法被称作一个 @emph{生成器函数}。 这样的函数在被调用时，总是返回一个可以执行函数体的迭代器对象：调用该迭代器的 @ref{d34,,iterator.__next__()} 方法将会导致这个函数一直运行直到它使用 @code{yield} 语句提供了一个值为止。 当这个函数执行 @ref{2cf,,return} 语句或者执行到末尾时，将引发 @ref{58a,,StopIteration} 异常并且这个迭代器将到达所返回的值集合的末尾。

@item 协程函数

@geindex coroutine; function

使用 @ref{3b1,,async def} 来定义的函数或方法就被称为 @emph{协程函数}。这样的函数在被调用时会返回一个 @ref{18a,,coroutine} 对象。它可能包含 @ref{2df,,await} 表达式以及 @ref{740,,async with} 和 @ref{406,,async for} 语句。详情可参见 @ref{158d,,协程对象} 一节。

@item 异步生成器函数

@geindex asynchronous generator; function
@geindex asynchronous generator; asynchronous iterator

使用 @ref{3b1,,async def} 来定义并包含 @ref{2ce,,yield} 语句的函数或方法就被称为 @emph{异步生成器函数}。这样的函数在被调用时会返回一个异步迭代器对象，该对象可在 @ref{406,,async for} 语句中用来执行函数体。

调用异步迭代器的 @ref{158e,,aiterator.__anext__} 方法将返回一个 @ref{61b,,awaitable}，此对象会在被等待时执行直到使用 @ref{2ce,,yield} 产生一个值。 当函数执行到空的 @ref{2cf,,return} 语句或函数末尾时，将会引发 @ref{1193,,StopAsyncIteration} 异常并且异步迭代器也将到达要产生的值集合的末尾。

@item 内置函数

@geindex 对象; built-in function
@geindex 对象; function
@geindex C; language

内置函数对象是对于 C 函数的外部封装。内置函数的例子包括 @ref{292,,len()} 和 @ref{ed9,,math.sin()}  (@ref{b1,,math} 是一个标准内置模块)。内置函数参数的数量和类型由 C 函数决定。特殊的只读属性: @code{__doc__} 是函数的文档字符串，如果没有则为 @code{None}; @ref{d37,,__name__} 是函数的名称; @code{__self__} 设定为 @code{None} (参见下一条目); @code{__module__} 是函数所属模块的名称，如果没有则为 @code{None}。

@item 内置方法

@geindex 对象; built-in method
@geindex 对象; method
@geindex built-in; method

此类型实际上是内置函数的另一种形式，只不过还包含了一个传入 C 函数的对象作为隐式的额外参数。内置方法的一个例子是 @code{alist.append()}，其中 @emph{alist} 为一个列表对象。在此示例中，特殊的只读属性 @code{__self__} 会被设为 @emph{alist} 所标记的对象。

@item 类

类是可调用对象。 这些对象通常是用作创建自身实例的“工厂”，但类也可以有重载 @ref{97d,,__new__()} 的变体类型。 调用的参数会传递给 @ref{97d,,__new__()}，并且在通常情况下，也会传递给 @ref{e2b,,__init__()} 来初始化新的实例。to initialize the new instance.

@item 类实例

任意类的实例可以通过在其所属类中定义 @ref{158f,,__call__()} 方法变成可调用对象。
@end table

@item 模块

@geindex 语句; import
@geindex 对象; module

模块是 Python 代码的基本组织单元，由 @ref{1590,,导入系统} 创建，由 @ref{cef,,import} 语句发起调用，或者通过 @ref{bef,,importlib.import_module()} 和内置的 @ref{16b,,__import__()} 等函数发起调用。 模块对象具有由字典对象实现的命名空间（这是被模块中定义的函数的 @code{__globals__} 属性引用的字典）。 属性引用被转换为该字典中的查找，例如 @code{m.x} 相当于 @code{m.__dict__["x"]}。 模块对象不包含用于初始化模块的代码对象（因为初始化完成后不需要它）。

属性赋值会更新模块的命名空间字典，例如 @code{m.x = 1} 等同于 @code{m.__dict__["x"] = 1}。

@geindex __name__ (module attribute)
@geindex __doc__ (module attribute)
@geindex __file__ (module attribute)
@geindex __annotations__ (module attribute)
@geindex module; namespace

预定义的 (可写) 属性: @ref{de0,,__name__} 为模块的名称; @code{__doc__} 为模块的文档字符串，如果没有则为 @code{None}; @code{__annotations__} (可选) 为一个包含 @ref{71c,,变量标注} 的字典，它是在模块体执行时获取的; @ref{1591,,__file__} 是模块对应的被加载文件的路径名，如果它是加载自一个文件的话。某些类型的模块可能没有 @ref{1591,,__file__} 属性，例如 C 模块是静态链接到解释器内部的; 对于从一个共享库动态加载的扩展模块来说该属性为该共享库文件的路径名。

@geindex __dict__ (module attribute)

特殊的只读属性: @ref{5fe,,__dict__} 为以字典对象表示的模块命名空间。

@strong{CPython implementation detail:} 由于 CPython 清理模块字典的设定，当模块离开作用域时模块字典将会被清理，即使该字典还有活动的引用。想避免此问题，可复制该字典或保持模块状态以直接使用其字典。

@item 自定义类

自定义类这种类型一般通过类定义来创建 (参见 @ref{d3a,,类定义} 一节)。每个类都有通过一个字典对象实现的独立命名空间。类属性引用会被转化为在此字典中查找，例如 @code{C.x} 会被转化为 @code{C.__dict__["x"]} (不过也存在一些钩子对象以允许其他定位属性的方式)。当未在其中发现某个属性名称时，会继续在基类中查找。这种基类查找使用 C3 方法解析顺序，即使存在 '钻石形' 继承结构即有多条继承路径连到一个共同祖先也能保持正确的行为。有关 Python 使用的 C3 MRO 的详情可查看配合 2.3 版发布的文档 @indicateurl{https://www.python.org/download/releases/2.3/mro/}.

@c XXX: Could we add that MRO doc as an appendix to the language ref?

@geindex 对象; class
@geindex 对象; class instance
@geindex 对象; instance
@geindex class object; call
@geindex container
@geindex 对象; dictionary
@geindex class; attribute

当一个类属性引用 (假设类名为 @code{C}) 会产生一个类方法对象时，它将转化为一个 @code{__self__} 属性为 @code{C} 的实例方法对象。当其会产生一个静态方法对象时，它将转化为该静态方法对象所封装的对象。从类的 @ref{5fe,,__dict__} 所包含内容以外获取属性的其他方式请参看 @ref{5ec,,实现描述器} 一节。

@geindex class; attribute; assignment

类属性赋值会更新类的字典，但不会更新基类的字典。

@geindex class object; call

类对象可被调用 (见上文) 以产生一个类实例 (见下文)。

@geindex __name__ (class attribute)
@geindex __module__ (class attribute)
@geindex __dict__ (class attribute)
@geindex __bases__ (class attribute)
@geindex __doc__ (class attribute)
@geindex __annotations__ (class attribute)

特殊属性: @ref{d37,,__name__} 为类的名称; @code{__module__} 为类所在模块的名称; @ref{5fe,,__dict__} 为包含类命名空间的字典; @ref{ed3,,__bases__} 为包含基类的元组，按其在基类列表中的出现顺序排列; @code{__doc__} 为类的文档字符串，如果没有则为 @code{None}; @code{__annotations__} (可选) 为一个包含 @ref{71c,,变量标注} 的字典，它是在类体执行时获取的。

@item 类实例

@geindex 对象; class instance
@geindex 对象; instance
@geindex class; instance
@geindex class instance; attribute

类实例可通过调用类对象来创建（见上文）。 每个类实例都有通过一个字典对象实现的独立命名空间，属性引用会首先在此字典中查找。 当未在其中发现某个属性，而实例对应的类中有该属性时，会继续在类属性中查找。 如果找到的类属性为一个用户自定义函数对象，它会被转化为实例方法对象，其 @code{__self__} 属性即该实例。 静态方法和类方法对象也会被转化；参见上文的“类”小节。 要了解其他通过类实例来获取相应类属性的方式请参阅 @ref{5ec,,实现描述器} 小节，这样得到的属性可能与实际存放在类的 @ref{5fe,,__dict__} 中的对象不同。 如果未找到类属性，而对象所属的类具有 @ref{433,,__getattr__()} 方法，则会调用该方法来满足查找要求。

@geindex class instance; attribute; assignment

属性赋值和删除会更新实例的字典，但绝不会更新类的字典。 如果类具有 @ref{ef6,,__setattr__()} 或 @ref{1592,,__delattr__()} 方法，则将调用该方法而不再直接更新实例的字典。

@geindex 对象; numeric
@geindex 对象; sequence
@geindex 对象; mapping

如果类实例具有某些特殊名称的方法，就可以伪装为数字、序列或映射。参见 @ref{610,,特殊方法名称} 一节。

@geindex __dict__ (instance attribute)
@geindex __class__ (instance attribute)

特殊属性: @ref{5fe,,__dict__} 为属性字典; @ref{ed4,,__class__} 为实例对应的类。

@item I/O 对象 (或称文件对象)

@geindex 內置函数; open
@geindex 模块; io
@geindex popen() (in module os)
@geindex makefile() (socket method)
@geindex sys.stdin
@geindex sys.stdout
@geindex sys.stderr
@geindex stdio
@geindex stdin (in module sys)
@geindex stdout (in module sys)
@geindex stderr (in module sys)

@ref{c1d,,file object} 表示一个打开的文件。有多种快捷方式可用来创建文件对象: @ref{16f,,open()} 内置函数，以及 @ref{3d3,,os.popen()}, @ref{1593,,os.fdopen()} 和 socket 对象的 @ref{bf5,,makefile()} 方法 (还可能使用某些扩展模块所提供的其他函数或方法)。

@code{sys.stdin}, @code{sys.stdout} 和 @code{sys.stderr} 会初始化为对应于解释器标准输入、输出和错误流的文件对象；它们都会以文本模式打开，因此都遵循 @ref{d09,,io.TextIOBase} 抽象类所定义的接口。

@item 内部类型

@geindex internal type
@geindex types@comma{} internal

某些由解释器内部使用的类型也被暴露给用户。它们的定义可能随未来解释器版本的更新而变化，为内容完整起见在此处一并介绍。

@geindex bytecode
@geindex object; code
@geindex code object


@table @asis

@item 代码对象

代码对象表示 @emph{编译为字节的} 可执行 Python 代码，或称 @ref{713,,bytecode}。代码对象和函数对象的区别在于函数对象包含对函数全局对象 (函数所属的模块) 的显式引用，而代码对象不包含上下文；而且默认参数值会存放于函数对象而不是代码对象内 (因为它们表示在运行时算出的值)。与函数对象不同，代码对象不可变，也不包含对可变对象的引用 (不论是直接还是间接)。

@geindex co_argcount (code object attribute)
@geindex co_posonlyargcount (code object attribute)
@geindex co_kwonlyargcount (code object attribute)
@geindex co_code (code object attribute)
@geindex co_consts (code object attribute)
@geindex co_filename (code object attribute)
@geindex co_firstlineno (code object attribute)
@geindex co_flags (code object attribute)
@geindex co_lnotab (code object attribute)
@geindex co_name (code object attribute)
@geindex co_names (code object attribute)
@geindex co_nlocals (code object attribute)
@geindex co_stacksize (code object attribute)
@geindex co_varnames (code object attribute)
@geindex co_cellvars (code object attribute)
@geindex co_freevars (code object attribute)

特殊的只读属性: @code{co_name} 给出了函数名; @code{co_argcount} 为位置参数的总数量 (包括仅限位置参数和带有默认值的参数); @code{co_posonlyargcount} 为仅限位置参数的数量 (包括带有默认值的参数); @code{co_kwonlyargcount} 为仅限关键字参数的数量 (包括带有默认值的参数); @code{co_nlocals} 为函数使用的局部变量的数量 (包括参数); @code{co_varnames} 为一个包含局部变量名称的元组 (参数名排在最前面); @code{co_cellvars} 为一个包含被嵌套函数所引用的局部变量名称的元组; @code{co_freevars} 为一个包含自由变量名称的元组; @code{co_code} 为一个表示字节码指令序列的字符口中; @code{co_consts} 为一个包含字节码所使用的字面值的元组; @code{co_names} 为一个包含字节码所使用的名称的元组; @code{co_filename} 为被编码代码所在的文件名; @code{co_firstlineno} 为函数首行的行号; @code{co_lnotab} 为一个字符串，其中编码了从字节码偏移量到行号的映射 (详情参见解释器的源代码); @code{co_stacksize} 为要求的栈大小; @code{co_flags} 为一个整数，其中编码了解释器所用的多个旗标。

@geindex 对象; generator

以下是可用于 @code{co_flags} 的标志位定义：如果函数使用 @code{*arguments} 语法来接受任意数量的位置参数，则 @code{0x04} 位被设置；如果函数使用 @code{**keywords} 语法来接受任意数量的关键字参数，则 @code{0x08} 位被设置；如果函数是一个生成器，则 @code{0x20} 位被设置。

未来特性声明 (@code{from __future__ import division}) 也使用 @code{co_flags} 中的标志位来指明代码对象的编译是否启用特定的特性: 如果函数编译时启用未来除法特性则设置 @code{0x2000} 位; 在更早的 Python 版本中则使用 @code{0x10} 和 @code{0x1000} 位。

@code{co_flags} 中的其他位被保留为内部使用。

@geindex documentation string

如果代码对象表示一个函数，@code{co_consts} 中的第一项将是函数的文档字符串，如果未定义则为 @code{None}。
@end table
@anchor{reference/datamodel frame-objects}@anchor{1594}

@table @asis

@item 帧对象

@geindex 对象; frame

帧对象表示执行帧。它们可能出现在回溯对象中 (见下文)，还会被传递给注册跟踪函数。

@geindex f_back (frame attribute)
@geindex f_code (frame attribute)
@geindex f_globals (frame attribute)
@geindex f_locals (frame attribute)
@geindex f_lasti (frame attribute)
@geindex f_builtins (frame attribute)

特殊的只读属性: @code{f_back} 为前一堆栈帧 (指向调用者)，如是最底层堆栈帧则为 @code{None}; @code{f_code} 为此帧中所执行的代码对象; @code{f_locals} 为用于查找本地变量的字典; @code{f_globals} 则用于查找全局变量; @code{f_builtins} 用于查找内置 (固有) 名称; @code{f_lasti} 给出精确指令 (这是代码对象的字节码字符串的一个索引)。

访问 @code{f_code} 会引发一个 @ref{fec,,审计事件} @code{object.__getattr__}，附带参数 @code{obj} 和 @code{"f_code"}。

@geindex f_trace (frame attribute)
@geindex f_trace_lines (frame attribute)
@geindex f_trace_opcodes (frame attribute)
@geindex f_lineno (frame attribute)

特殊的可写属性: @code{f_trace}，如果不为 @code{None}，则是在代码执行期间调用各类事件的函数 (由调试器使用)。通常每个新源码行会触发一个事件 - 这可以通过将 @code{f_trace_lines} 设为 @ref{497,,False} 来禁用。

具体的实现 @emph{可能} 会通过将 @code{f_trace_opcodes} 设为 @ref{59c,,True} 来允许按操作码请求事件。请注意如果跟踪函数引发的异常逃逸到被跟踪的函数中，这可能会导致未定义的解释器行为。

@code{f_lineno} 为帧的当前行号 --- 在这里写入从一个跟踪函数内部跳转的指定行 (仅用于最底层的帧)。调试器可以通过写入 f_lineno 实现一个 Jump 命令 (即设置下一语句)。

帧对象支持一个方法:

@geindex clear() (frame 方法)
@anchor{reference/datamodel frame clear}@anchor{902}
@deffn {方法} frame.clear ()

此方法清除该帧持有的全部对本地变量的引用。而且如果该帧属于一个生成器，生成器会被完成。这有助于打破包含帧对象的循环引用 (例如当捕获一个异常并保存其回溯在之后使用)。

如果该帧当前正在执行则会引发 @ref{3e4,,RuntimeError}。


3.4 新版功能.

@end deffn
@end table
@anchor{reference/datamodel traceback-objects}@anchor{44b}

@table @asis

@item 回溯对象

@geindex 对象; traceback
@geindex stack; trace
@geindex exception; handler
@geindex execution; stack
@geindex exc_info (in module sys)
@geindex last_traceback (in module sys)
@geindex sys.exc_info
@geindex sys.last_traceback

回溯对象表示一个异常的栈跟踪记录。当异常发生时会隐式地创建一个回溯对象，也可能通过调用 @ref{44a,,types.TracebackType} 显式地创建。

对于隐式地创建的回溯对象，当查找异常句柄使得执行栈展开时，会在每个展开层级的当前回溯之前插入一个回溯对象。当进入一个异常句柄时，栈跟踪将对程序启用。(参见 @ref{e3f,,try 语句} 一节。) 它可作为 @code{sys.exc_info()} 所返回的元组的第三项，以及所捕获异常的 @code{__traceback__} 属性被获取。

当程序不包含可用的句柄时，栈跟踪会 (以良好的格式) 写入标准错误流；如果解释器处于交互模式，它也可作为 @code{sys.last_traceback} 对用户启用。

对于显式创建的回溯对象，则由回溯对象的创建者来决定应该如何链接 @code{tb_next} 属性来构成完整的栈跟踪。

@geindex tb_frame (traceback attribute)
@geindex tb_lineno (traceback attribute)
@geindex tb_lasti (traceback attribute)
@geindex 语句; try

特殊的只读属性: @code{tb_frame} 指向当前层级的执行帧; @code{tb_lineno} 给出发生异常所在的行号; @code{tb_lasti} 标示具体指令。如果异常发生于没有匹配的 except 子句或有 finally 子句的 @ref{e3f,,try} 语句中，回溯对象中的行号和最后指令可能与相应帧对象中行号不同。

访问 @code{tb_frame} 会引发一个 @ref{fec,,审计事件} @code{object.__getattr__}，附带参数 @code{obj} 和 @code{"tb_frame"}。

@geindex tb_next (traceback attribute)

特殊的可写属性: @code{tb_next} 为栈跟踪中的下一层级 (通往发生异常的帧)，如果没有下一层级则为 @code{None}。


在 3.7 版更改: 回溯对象现在可以使用 Python 代码显式地实例化，现有实例的 @code{tb_next} 属性可以被更新。


@item 切片对象

@geindex 內置函数; slice

切片对象被用来表示 @ref{3ad,,__getitem__()} 方法所使用的切片。 该对象也可使用内置的 @ref{ed0,,slice()} 函数来创建。

@geindex start (slice object attribute)
@geindex stop (slice object attribute)
@geindex step (slice object attribute)

特殊的只读属性: @code{start} 为下界; @code{stop} 为上界; @code{step} 为步长值; 各值如省略则为 @code{None}。这些属性可具有任意类型。

切片对象支持一个方法:

@geindex indices() (slice 方法)
@anchor{reference/datamodel slice indices}@anchor{a49}
@deffn {方法} slice.indices (self, length)

此方法接受一个整型参数 @emph{length} 并计算在切片对象被应用到 @emph{length} 指定长度的条目序列时切片的相关信息应如何描述。 其返回值为三个整型数组成的元组；这些数分别为切片的 @emph{start} 和 @emph{stop} 索引号以及 @emph{step} 步长值。索引号缺失或越界则按照与正规切片相一致的方式处理。
@end deffn

@item 静态方法对象

静态方法对象提供了一种避免上文所述将函数对象转换为方法对象的方式。静态方法对象为对任意其他对象的封装，通常用来封装用户定义方法对象。当从类或类实例获取一个静态方法对象时，实际返回的对象是封装的对象，它不会被进一步转换。静态方法对象自身不是可调用的，但它们所封装的对象通常都是可调用的。静态方法对象可通过内置的 @ref{311,,staticmethod()} 构造器来创建。

@item 类方法对象

类方法对象和静态方法一样是对其他对象的封装，会改变从类或类实例获取该对象的方式。类方法对象在此类获取操作中的行为已在上文  "用户定义方法" 一节中描述。类方法对象可通过内置的 @ref{310,,classmethod()} 构造器来创建。
@end table
@end table

@node 特殊方法名称,协程,标准类型层级结构,数据模型
@anchor{reference/datamodel special-method-names}@anchor{1595}@anchor{reference/datamodel specialnames}@anchor{610}
@subsection 特殊方法名称


@geindex operator; overloading
@geindex __getitem__() (mapping object method)

一个类可以通过定义具有特殊名称的方法来实现由特殊语法来发起调用的特定操作（例如算术运算或抽取与切片）。 这是 Python 实现 @emph{运算符重载} 的方式，允许每个类自行定义基于该语言运算符的特定行为。 举例来说，如果一个类定义了名为 @ref{3ad,,__getitem__()} 的方法，并且 @code{x} 是该类的一个实例，则 @code{x[i]} 基本就等价于 @code{type(x).__getitem__(x, i)}。 除非有说明例外情况，在没有定义适当方法的时候尝试执行某种操作将引发一个异常 (通常为 @ref{4aa,,AttributeError} 或 @ref{1ff,,TypeError})。

将一个特殊方法设为 @code{None} 表示对应的操作不可用。 例如，如果一个类将 @ref{611,,__iter__()} 设为 @code{None}，则该类就是不可迭代的，因此对其实例调用 @ref{df5,,iter()} 将引发一个 @ref{1ff,,TypeError} (而不会回退至 @ref{3ad,,__getitem__()})。 @footnote{@w{(2)} 
@ref{455,,__hash__()}, @ref{611,,__iter__()}, @ref{631,,__reversed__()} 以及 @ref{df6,,__contains__()} 方法对此有特殊处理；其他方法仍会引发 @ref{1ff,,TypeError}，但可能依赖 @code{None} 属于不可调用对象的行为来做到这一点。
}

在实现模拟任何内置类型的类时，很重要的一点是模拟的实现程度对于被模拟对象来说应当是有意义的。例如，提取单个元素的操作对于某些序列来说是适宜的，但提取切片可能就没有意义。(这种情况的一个实例是 W3C 的文档对象模型中的 @code{NodeList} 接口。)

@menu
* 基本定制:: 
* 自定义属性访问:: 
* 自定义类创建:: 
* 自定义实例及子类检查:: 
* 模拟泛型类型:: 
* 模拟可调用对象:: 
* 模拟容器类型:: 
* 模拟数字类型:: 
* with 语句上下文管理器:: 
* 特殊方法查找:: 

@end menu

@node 基本定制,自定义属性访问,,特殊方法名称
@anchor{reference/datamodel basic-customization}@anchor{1596}@anchor{reference/datamodel customization}@anchor{1597}
@subsubsection 基本定制


@geindex __new__() (object 方法)
@anchor{reference/datamodel object __new__}@anchor{97d}
@deffn {方法} object.__new__ (cls[, ...])

@geindex subclassing; immutable types

调用以创建一个 @emph{cls} 类的新实例。@ref{97d,,__new__()} 是一个静态方法 (因为是特例所以你不需要显式地声明)，它会将所请求实例所属的类作为第一个参数。其余的参数会被传递给对象构造器表达式 (对类的调用)。@ref{97d,,__new__()} 的返回值应为新对象实例 (通常是 @emph{cls} 的实例)。

典型的实现会附带适宜的参数使用 @code{super().__new__(cls[, ...])}，通过超类的 @ref{97d,,__new__()} 方法来创建一个类的新实例，然后根据需要修改新创建的实例再将其返回。

如果 @ref{97d,,__new__()} 在构造对象期间被发起调用并且它返回了一个 @emph{cls} 的实例，则新实例的 @ref{e2b,,__init__()} 方法将以 @code{__init__(self[, ...])} 的形式被发起调用，其中 @emph{self} 为新实例而其余的参数与被传给对象构造器的参数相同。

如果 @ref{97d,,__new__()} 未返回一个 @emph{cls} 的实例，则新实例的 @ref{e2b,,__init__()} 方法就不会被执行。

@ref{97d,,__new__()} 的目的主要是允许不可变类型的子类 (例如 int, str 或 tuple) 定制实例创建过程。它也常会在自定义元类中被重载以便定制类创建过程。
@end deffn

@geindex __init__() (object 方法)
@anchor{reference/datamodel object __init__}@anchor{e2b}
@deffn {方法} object.__init__ (self[, ...])

@geindex class; constructor

在实例 (通过 @ref{97d,,__new__()}) 被创建之后，返回调用者之前调用。其参数与传递给类构造器表达式的参数相同。一个基类如果有 @ref{e2b,,__init__()} 方法，则其所派生的类如果也有 @ref{e2b,,__init__()} 方法，就必须显式地调用它以确保实例基类部分的正确初始化；例如: @code{super().__init__([args...])}.

因为对象是由 @ref{97d,,__new__()} 和 @ref{e2b,,__init__()} 协作构造完成的 (由 @ref{97d,,__new__()} 创建，并由 @ref{e2b,,__init__()} 定制)，所以 @ref{e2b,,__init__()} 返回的值只能是 @code{None}，否则会在运行时引发 @ref{1ff,,TypeError}。
@end deffn

@geindex __del__() (object 方法)
@anchor{reference/datamodel object __del__}@anchor{a0d}
@deffn {方法} object.__del__ (self)

@geindex destructor
@geindex finalizer
@geindex 语句; del

在实例将被销毁时调用。 这还被称为终结器或析构器（不适当）。 如果一个基类具有 @ref{a0d,,__del__()} 方法，则其所派生的类如果也有 @ref{a0d,,__del__()} 方法，就必须显式地调用它以确保实例基类部分的正确清除。

@ref{a0d,,__del__()} 方法可以 (但不推荐!) 通过创建一个该实例的新引用来推迟其销毁。这被称为对象 @emph{重生}。@ref{a0d,,__del__()} 是否会在重生的对象将被销毁时再次被调用是由具体实现决定的 ；当前的 @ref{1598,,CPython} 实现只会调用一次。

当解释器退出时不会确保为仍然存在的对象调用 @ref{a0d,,__del__()} 方法。

@cartouche
@quotation 注解 
@code{del x} 并不直接调用 @code{x.__del__()} --- 前者会将 @code{x} 的引用计数减一，而后者仅会在 @code{x} 的引用计数变为零时被调用。
@end quotation
@end cartouche

@strong{CPython implementation detail:} It is possible for a reference cycle to prevent the reference count
of an object from going to zero.  In this case, the cycle will be
later detected and deleted by the @ref{1013,,cyclic garbage collector}.  A common cause of reference cycles is when
an exception has been caught in a local variable.  The frame's
locals then reference the exception, which references its own
traceback, which references the locals of all frames caught in the
traceback.


@subsubheading 参见


@ref{84,,gc} 模块的文档。


@cartouche
@quotation 警告 
由于调用 @ref{a0d,,__del__()} 方法时周边状况已不确定，在其执行期间发生的异常将被忽略，改为打印一个警告到 @code{sys.stderr}。特别地：


@itemize *

@item 
@ref{a0d,,__del__()} 可在任意代码被执行时启用，包括来自任意线程的代码。如果 @ref{a0d,,__del__()} 需要接受锁或启用其他阻塞资源，可能会发生死锁，例如该资源已被为执行 @ref{a0d,,__del__()} 而中断的代码所获取。

@item 
@ref{a0d,,__del__()} 可以在解释器关闭阶段被执行。因此，它需要访问的全局变量（包含其他模块）可能已被删除或设为 @code{None}。Python 会保证先删除模块中名称以单个下划线打头的全局变量再删除其他全局变量；如果已不存在其他对此类全局变量的引用，这有助于确保导入的模块在 @ref{a0d,,__del__()} 方法被调用时仍然可用。
@end itemize
@end quotation
@end cartouche

@geindex repr() (built-in function); __repr__() (object method)
@end deffn

@geindex __repr__() (object 方法)
@anchor{reference/datamodel object __repr__}@anchor{453}
@deffn {方法} object.__repr__ (self)

由 @ref{8c3,,repr()} 内置函数调用以输出一个对象的“官方”字符串表示。如果可能，这应类似一个有效的 Python 表达式，能被用来重建具有相同取值的对象（只要有适当的环境）。如果这不可能，则应返回形式如 @code{<...some useful description...>} 的字符串。返回值必须是一个字符串对象。如果一个类定义了 @ref{453,,__repr__()} 但未定义 @ref{f01,,__str__()}，则在需要该类的实例的“非正式”字符串表示时也会使用 @ref{453,,__repr__()}。

此方法通常被用于调试，因此确保其表示的内容包含丰富信息且无歧义是很重要的。

@geindex string; __str__() (object method)
@geindex format() (built-in function); __str__() (object method)
@geindex print() (built-in function); __str__() (object method)
@end deffn

@geindex __str__() (object 方法)
@anchor{reference/datamodel object __str__}@anchor{f01}
@deffn {方法} object.__str__ (self)

通过 @ref{206,,str(object)} 以及内置函数 @ref{5de,,format()} 和 @ref{97a,,print()} 调用以生成一个对象的“非正式”或格式良好的字符串表示。返回值必须为一个 @ref{1386,,字符串} 对象。

此方法与 @ref{453,,object.__repr__()} 的不同点在于 @ref{f01,,__str__()} 并不预期返回一个有效的 Python 表达式：可以使用更方便或更准确的描述信息。

内置类型 @ref{3da,,object} 所定义的默认实现会调用 @ref{453,,object.__repr__()}。

@c XXX what about subclasses of string?
@end deffn

@geindex __bytes__() (object 方法)
@anchor{reference/datamodel object __bytes__}@anchor{1599}
@deffn {方法} object.__bytes__ (self)

@geindex 內置函数; bytes

通过 @ref{123a,,bytes} 调用以生成一个对象的字节串表示。这应该返回一个 @ref{172,,bytes} 对象。

@geindex string; __format__() (object method)
@geindex string; conversion
@geindex 內置函数; print
@end deffn

@geindex __format__() (object 方法)
@anchor{reference/datamodel object __format__}@anchor{a38}
@deffn {方法} object.__format__ (self, format_spec)

通过 @ref{5de,,format()} 内置函数、扩展、@ref{29d,,格式化字符串字面值} 的求值以及 @ref{5dd,,str.format()} 方法调用以生成一个对象的“格式化”字符串表示。 @emph{format_spec} 参数为包含所需格式选项描述的字符串。 @emph{format_spec} 参数的解读是由实现 @ref{a38,,__format__()} 的类型决定的，不过大多数类或是将格式化委托给某个内置类型，或是使用相似的格式化选项语法。

请参看 @ref{5e1,,格式规格迷你语言} 了解标准格式化语法的描述。

返回值必须为一个字符串对象。


在 3.4 版更改: @code{object} 本身的 __format__ 方法如果被传入任何非空字符，将会引发一个 @ref{1ff,,TypeError}。



在 3.7 版更改: @code{object.__format__(x, '@w{'})} 现在等同于 @code{str(x)} 而不再是 @code{format(str(x), '@w{'})}。

@end deffn
@anchor{reference/datamodel richcmpfuncs}@anchor{159a}
@geindex __lt__() (object 方法)
@geindex __le__() (object 方法)
@geindex __eq__() (object 方法)
@geindex __ne__() (object 方法)
@geindex __gt__() (object 方法)
@geindex __ge__() (object 方法)
@anchor{reference/datamodel object __lt__}@anchor{d06}
@deffn {方法} object.__lt__ (self, other)
@anchor{reference/datamodel object __le__}@anchor{d70}
@deffnx {方法} object.__le__ (self, other)
@anchor{reference/datamodel object __eq__}@anchor{454}
@deffnx {方法} object.__eq__ (self, other)
@anchor{reference/datamodel object __ne__}@anchor{f20}
@deffnx {方法} object.__ne__ (self, other)
@anchor{reference/datamodel object __gt__}@anchor{d71}
@deffnx {方法} object.__gt__ (self, other)
@anchor{reference/datamodel object __ge__}@anchor{d72}
@deffnx {方法} object.__ge__ (self, other)

@geindex comparisons

以上这些被称为“富比较”方法。运算符号与方法名称的对应关系如下：@code{x<y} 调用 @code{x.__lt__(y)}、@code{x<=y} 调用 @code{x.__le__(y)}、@code{x==y} 调用 @code{x.__eq__(y)}、@code{x!=y} 调用 @code{x.__ne__(y)}、@code{x>y} 调用 @code{x.__gt__(y)}、@code{x>=y} 调用 @code{x.__ge__(y)}。

如果指定的参数对没有相应的实现，富比较方法可能会返回单例对象 @code{NotImplemented}。按照惯例，成功的比较会返回 @code{False} 或 @code{True}。不过实际上这些方法可以返回任意值，因此如果比较运算符是要用于布尔值判断（例如作为 @code{if} 语句的条件），Python 会对返回值调用 @ref{2c4,,bool()} 以确定结果为真还是假。

在默认情况下，@code{object} 通过使用 @code{is} 来实现 @ref{454,,__eq__()}，并在比较结果为假值时返回 @code{NotImplemented}: @code{True if x is y else NotImplemented}。 对于 @ref{f20,,__ne__()}，默认会委托给 @ref{454,,__eq__()} 并对结果取反，除非结果为 @code{NotImplemented}。 比较运算符之间没有其他隐含关系或默认实现；例如，@code{(x<y or x==y)} 为真并不意味着 @code{x<=y}。 要根据单根运算自动生成排序操作，请参看 @ref{942,,functools.total_ordering()}。

请查看 @ref{455,,__hash__()} 的相关段落，了解创建可支持自定义比较运算并可用作字典键的 @ref{277,,hashable} 对象时要注意的一些事项。

这些方法并没有对调参数版本（在左边参数不支持该操作但右边参数支持时使用）；而是 @ref{d06,,__lt__()} 和 @ref{d71,,__gt__()} 互为对方的反射， @ref{d70,,__le__()} 和 @ref{d72,,__ge__()} 互为对方的反射，而 @ref{454,,__eq__()} 和 @ref{f20,,__ne__()} 则是它们自己的反射。如果两个操作数的类型不同，且右操作数类型是左操作数类型的直接或间接子类，则优先选择右操作数的反射方法，否则优先选择左操作数的方法。虚拟子类不会被考虑。
@end deffn

@geindex __hash__() (object 方法)
@anchor{reference/datamodel object __hash__}@anchor{455}
@deffn {方法} object.__hash__ (self)

@geindex 对象; dictionary
@geindex 內置函数; hash

通过内置函数 @ref{aac,,hash()} 调用以对哈希集的成员进行操作，属于哈希集的类型包括 @ref{1f7,,set}、@ref{1f8,,frozenset} 以及 @ref{164,,dict}。@code{__hash__()} 应该返回一个整数。对象比较结果相同所需的唯一特征属性是其具有相同的哈希值；建议的做法是把参与比较的对象全部组件的哈希值混在一起，即将它们打包为一个元组并对该元组做哈希运算。例如:

@example
def __hash__(self):
    return hash((self.name, self.nick, self.color))
@end example

@cartouche
@quotation 注解 
@ref{aac,,hash()} 会从一个对象自定义的 @ref{455,,__hash__()} 方法返回值中截断为 @ref{391,,Py_ssize_t} 的大小。通常对 64 位构建为 8 字节，对 32 位构建为 4 字节。如果一个对象的   @ref{455,,__hash__()} 必须在不同位大小的构建上进行互操作，请确保检查全部所支持构建的宽度。做到这一点的简单方法是使用 @code{python -c "import sys; print(sys.hash_info.width)"}。
@end quotation
@end cartouche

如果一个类没有定义 @ref{454,,__eq__()} 方法，那么也不应该定义 @ref{455,,__hash__()} 操作；如果它定义了 @ref{454,,__eq__()} 但没有定义 @ref{455,,__hash__()}，则其实例将不可被用作可哈希集的项。如果一个类定义了可变对象并实现了 @ref{454,,__eq__()} 方法，则不应该实现 @ref{455,,__hash__()}，因为可哈希集的实现要求键的哈希集是不可变的（如果对象的哈希值发生改变，它将处于错误的哈希桶中）。

用户定义的类默认带有 @ref{454,,__eq__()} 和 @ref{455,,__hash__()} 方法；使用它们与任何对象（自己除外）比较必定不相等，并且 @code{x.__hash__()} 会返回一个恰当的值以确保 @code{x == y} 同时意味着 @code{x is y} 且 @code{hash(x) == hash(y)}。

一个类如果重载了 @ref{454,,__eq__()} 且没有定义 @ref{455,,__hash__()} 则会将其 @ref{455,,__hash__()} 隐式地设为 @code{None}。当一个类的 @ref{455,,__hash__()} 方法为 @code{None} 时，该类的实例将在一个程序尝试获取其哈希值时正确地引发 @ref{1ff,,TypeError}，并会在检测 @code{isinstance(obj, collections.abc.Hashable)} 时被正确地识别为不可哈希对象。

如果一个重载了 @ref{454,,__eq__()} 的类需要保留来自父类的 @ref{455,,__hash__()} 实现，则必须通过设置 @code{__hash__ = <ParentClass>.__hash__} 来显式地告知解释器。

如果一个没有重载 @ref{454,,__eq__()} 的类需要去掉哈希支持，则应该在类定义中包含 @code{__hash__ = None}。一个自定义了 @ref{455,,__hash__()} 以显式地引发 @ref{1ff,,TypeError} 的类会被 @code{isinstance(obj, collections.abc.Hashable)} 调用错误地识别为可哈希对象。

@cartouche
@quotation 注解 
在默认情况下，str 和 bytes 对象的 @ref{455,,__hash__()} 值会使用一个不可预知的随机值“加盐”。 虽然它们在一个单独 Python 进程中会保持不变，但它们的值在重复运行的 Python 间是不可预测的。

这是为了防护通过精心选择输入来利用字典插入操作在最坏情况下的执行效率即 O(n@w{^2}) 复杂度制造的拒绝服务攻击。 请参阅 @indicateurl{http://www.ocert.org/advisories/ocert-2011-003.html} 了解详情。

改变哈希值会影响集合的迭代次序。Python 也从不保证这个次序不会被改变（通常它在 32 位和 64 位构建上是不一致的）。

另见 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED}.
@end quotation
@end cartouche


在 3.3 版更改: 默认启用哈希随机化。

@end deffn

@geindex __bool__() (object 方法)
@anchor{reference/datamodel object __bool__}@anchor{d38}
@deffn {方法} object.__bool__ (self)

@geindex __len__() (mapping object method)

调用此方法以实现真值检测以及内置的 @code{bool()} 操作；应该返回 @code{False} 或 @code{True}。如果未定义此方法，则会查找并调用 @ref{e98,,__len__()} 并在其返回非零值时视对象的逻辑值为真。如果一个类既未定义 @ref{e98,,__len__()} 也未定义 @ref{d38,,__bool__()} 则视其所有实例的逻辑值为真。
@end deffn

@node 自定义属性访问,自定义类创建,基本定制,特殊方法名称
@anchor{reference/datamodel attribute-access}@anchor{159b}@anchor{reference/datamodel customizing-attribute-access}@anchor{159c}
@subsubsection 自定义属性访问


可以定义下列方法来自定义对类实例属性访问（@code{x.name} 的使用、赋值或删除）的具体含义.

@c XXX explain how descriptors interfere here!

@geindex __getattr__() (object 方法)
@anchor{reference/datamodel object __getattr__}@anchor{433}
@deffn {方法} object.__getattr__ (self, name)

当默认属性访问因引发 @ref{4aa,,AttributeError} 而失败时被调用 (可能是调用 @ref{552,,__getattribute__()} 时由于 @emph{name} 不是一个实例属性或 @code{self} 的类关系树中的属性而引发了 @ref{4aa,,AttributeError}；或者是对 @emph{name} 特性属性调用 @ref{159d,,__get__()} 时引发了 @ref{4aa,,AttributeError})。此方法应当返回（找到的）属性值或是引发一个 @ref{4aa,,AttributeError} 异常。

请注意如果属性是通过正常机制找到的，@ref{433,,__getattr__()} 就不会被调用。（这是在 @ref{433,,__getattr__()} 和 @ref{ef6,,__setattr__()} 之间故意设置的不对称性。）这既是出于效率理由也是因为不这样设置的话 @ref{433,,__getattr__()} 将无法访问实例的其他属性。要注意至少对于实例变量来说，你不必在实例属性字典中插入任何值（而是通过插入到其他对象）就可以模拟对它的完全控制。请参阅下面的 @ref{552,,__getattribute__()} 方法了解真正获取对属性访问的完全控制权的办法。
@end deffn

@geindex __getattribute__() (object 方法)
@anchor{reference/datamodel object __getattribute__}@anchor{552}
@deffn {方法} object.__getattribute__ (self, name)

此方法会无条件地被调用以实现对类实例属性的访问。如果类还定义了 @ref{433,,__getattr__()}，则后者不会被调用，除非 @ref{552,,__getattribute__()} 显式地调用它或是引发了 @ref{4aa,,AttributeError}。此方法应当返回（找到的）属性值或是引发一个 @ref{4aa,,AttributeError} 异常。为了避免此方法中的无限递归，其实现应该总是调用具有相同名称的基类方法来访问它所需要的任何属性，例如 @code{object.__getattribute__(self, name)}。

@cartouche
@quotation 注解 
此方法在作为通过特定语法或内置函数隐式地调用的结果的情况下查找特殊方法时仍可能会被跳过。参见 @ref{159e,,特殊方法查找}。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{object.__getattr__}，附带参数 @code{obj}, @code{name}。
@end deffn

@geindex __setattr__() (object 方法)
@anchor{reference/datamodel object __setattr__}@anchor{ef6}
@deffn {方法} object.__setattr__ (self, name, value)

此方法在一个属性被尝试赋值时被调用。这个调用会取代正常机制（即将值保存到实例字典）。 @emph{name} 为属性名称， @emph{value} 为要赋给属性的值。

如果 @ref{ef6,,__setattr__()} 想要赋值给一个实例属性，它应该调用同名的基类方法，例如 @code{object.__setattr__(self, name, value)}。

引发一个 @ref{fec,,审计事件} @code{object.__setattr__}，附带参数 @code{obj}, @code{name}, @code{value}。
@end deffn

@geindex __delattr__() (object 方法)
@anchor{reference/datamodel object __delattr__}@anchor{1592}
@deffn {方法} object.__delattr__ (self, name)

类似于 @ref{ef6,,__setattr__()} 但其作用为删除而非赋值。此方法应该仅在 @code{del obj.name} 对于该对象有意义时才被实现。

引发一个 @ref{fec,,审计事件} @code{object.__delattr__}，附带参数 @code{obj}, @code{name}。
@end deffn

@geindex __dir__() (object 方法)
@anchor{reference/datamodel object __dir__}@anchor{434}
@deffn {方法} object.__dir__ (self)

此方法会在对相应对象调用 @ref{e01,,dir()} 时被调用。返回值必须为一个序列。 @ref{e01,,dir()} 会把返回的序列转换为列表并对其排序。
@end deffn

@menu
* 自定义模块属性访问:: 
* 实现描述器:: 
* 发起调用描述器:: 
* __slots__:: 

@end menu

@node 自定义模块属性访问,实现描述器,,自定义属性访问
@anchor{reference/datamodel customizing-module-attribute-access}@anchor{159f}
@subsubsection 自定义模块属性访问


@geindex __getattr__ (module attribute)
@geindex __dir__ (module attribute)
@geindex __class__ (module attribute)

特殊名称 @code{__getattr__} 和 @code{__dir__} 还可被用来自定义对模块属性的访问。模块层级的 @code{__getattr__} 函数应当接受一个参数，其名称为一个属性名，并返回计算结果值或引发一个 @ref{4aa,,AttributeError}。如果通过正常查找即 @ref{552,,object.__getattribute__()} 未在模块对象中找到某个属性，则 @code{__getattr__} 会在模块的 @code{__dict__} 中查找，未找到时会引发一个 @ref{4aa,,AttributeError}。如果找到，它会以属性名被调用并返回结果值。

@code{__dir__} 函数应当不接受任何参数，并且返回一个表示模块中可访问名称的字符串序列。 此函数如果存在，将会重载一个模块中的标准 @ref{e01,,dir()} 查找。

想要更细致地自定义模块的行为（设置属性和特性属性等待），可以将模块对象的 @code{__class__} 属性设置为一个 @ref{7ec,,types.ModuleType} 的子类。例如:

@example
import sys
from types import ModuleType

class VerboseModule(ModuleType):
    def __repr__(self):
        return f'Verbose @{self.__name__@}'

    def __setattr__(self, attr, value):
        print(f'Setting @{attr@}...')
        super().__setattr__(attr, value)

sys.modules[__name__].__class__ = VerboseModule
@end example

@cartouche
@quotation 注解 
定义模块的 @code{__getattr__} 和设置模块的 @code{__class__} 只会影响使用属性访问语法进行的查找 -- 直接访问模块全局变量（不论是通过模块内的代码还是通过对模块全局字典的引用）是不受影响的。
@end quotation
@end cartouche


在 3.5 版更改: @code{__class__} 模块属性改为可写。



3.7 新版功能: @code{__getattr__} 和 @code{__dir__} 模块属性。



@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 562

@item PEP 562@footnote{https://www.python.org/dev/peps/pep-0562} - 模块 __getattr__ 和 __dir__

描述用于模块的 @code{__getattr__} 和 @code{__dir__} 函数。
@end table


@node 实现描述器,发起调用描述器,自定义模块属性访问,自定义属性访问
@anchor{reference/datamodel descriptors}@anchor{5ec}@anchor{reference/datamodel implementing-descriptors}@anchor{15a0}
@subsubsection 实现描述器


以下方法仅当一个包含该方法的类（称为 @emph{描述器} 类）的实例出现于一个 @emph{所有者} 类中的时候才会起作用（该描述器必须在所有者类或其某个上级类的字典中）。在以下示例中，“属性”指的是名称为所有者类 @ref{5fe,,__dict__} 中的特征属性的键名的属性。

@geindex __get__() (object 方法)
@anchor{reference/datamodel object __get__}@anchor{159d}
@deffn {方法} object.__get__ (self, instance, owner=None)

调用此方法以获取所有者类的属性（类属性访问）或该类的实例的属性（实例属性访问）。 可选的 @emph{owner} 参数是所有者类而 @emph{instance} 是被用来访问属性的实例，如果通过 @emph{owner} 来访问属性则返回 @code{None}。

此方法应当返回计算得到的属性值或是引发 @ref{4aa,,AttributeError} 异常。

@geindex Python 提高建议; PEP 252
PEP 252@footnote{https://www.python.org/dev/peps/pep-0252} 指明 @ref{159d,,__get__()} 为带有一至二个参数的可调用对象。 Python 自身内置的描述器支持此规格定义；但是，某些第三方工具可能要求必须带两个参数。 Python 自身的 @ref{552,,__getattribute__()} 实现总是会传入两个参数，无论它们是否被要求提供。
@end deffn

@geindex __set__() (object 方法)
@anchor{reference/datamodel object __set__}@anchor{15a1}
@deffn {方法} object.__set__ (self, instance, value)

调用此方法以设置 @emph{instance} 指定的所有者类的实例的属性为新值 @emph{value}。

请注意，添加 @ref{15a1,,__set__()} 或 @ref{15a2,,__delete__()} 会将描述器变成“数据描述器”。 更多细节请参阅 @ref{15a3,,发起调用描述器}。
@end deffn

@geindex __delete__() (object 方法)
@anchor{reference/datamodel object __delete__}@anchor{15a2}
@deffn {方法} object.__delete__ (self, instance)

调用此方法以删除 @emph{instance} 指定的所有者类的实例的属性。
@end deffn

@geindex __set_name__() (object 方法)
@anchor{reference/datamodel object __set_name__}@anchor{5eb}
@deffn {方法} object.__set_name__ (self, owner, name)

在所有者类 @emph{owner} 创建时被调用。描述器会被赋值给 @emph{name}。

@cartouche
@quotation 注解 
@ref{5eb,,__set_name__()} 只是作为 @ref{709,,type} 构造器的一部分被隐式地调用，因此在某个类被初次创建之后又额外添加一个描述器时，那就需要显式地调用它并且附带适当的形参:

@example
class A:
   pass
descr = custom_descriptor()
A.attr = descr
descr.__set_name__(A, 'attr')
@end example

详情参见 @ref{5e7,,创建类对象}。
@end quotation
@end cartouche


3.6 新版功能.

@end deffn

属性 @code{__objclass__} 会被 @ref{a0,,inspect} 模块解读为指定此对象定义所在的类（正确设置此属性有助于动态类属性的运行时内省）。对于可调用对象来说，它可以指明预期或要求提供一个特定类型（或子类）的实例作为第一个位置参数（例如，CPython 会为实现于 C 中的未绑定方法设置此属性）。

@node 发起调用描述器,__slots__,实现描述器,自定义属性访问
@anchor{reference/datamodel descriptor-invocation}@anchor{15a3}@anchor{reference/datamodel invoking-descriptors}@anchor{15a4}
@subsubsection 发起调用描述器


总的说来，描述器就是具有“绑定行为”的对象属性，其属性访问已被描述器协议中的方法所重载:  @ref{159d,,__get__()}, @ref{15a1,,__set__()} 和 @ref{15a2,,__delete__()}。 如果一个对象定义了以上方法中的任意一个，它就被称为描述器。

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。例如，@code{a.x} 的查找顺序会从 @code{a.__dict__['x']} 开始，然后是 @code{type(a).__dict__['x']}，接下来依次查找 @code{type(a)} 的上级基类，不包括元类。

但是，如果找到的值是定义了某个描述器方法的对象，则 Python 可能会重载默认行为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定义的描述器方法及其被调用的方式来决定。

描述器发起调用的开始点是一个绑定 @code{a.x}。参数的组合方式依 @code{a} 而定:


@table @asis

@item 直接调用

最简单但最不常见的调用方式是用户代码直接发起调用一个描述器方法:    @code{x.__get__(a)}。

@item 实例绑定

如果绑定到一个对象实例，@code{a.x} 会被转换为调用: @code{type(a).__dict__['x'].__get__(a, type(a))}。

@item 类绑定

如果绑定到一个类，@code{A.x} 会被转换为调用: @code{A.__dict__['x'].__get__(None, A)}。

@item 超绑定

如果 @code{a} 是 @ref{5e6,,super} 的一个实例，则绑定 @code{super(B, obj).m()} 会在 @code{obj.__class__.__mro__} 中搜索 @code{B} 的直接上级基类 @code{A} 然后通过以下调用来发起调用描述器: @code{A.__dict__['m'].__get__(obj, obj.__class__)}。
@end table

对于实例绑定，发起描述器调用的优先级取决于定义了哪些描述器方法。 一个描述器可以定义 @ref{159d,,__get__()}, @ref{15a1,,__set__()} 和 @ref{15a2,,__delete__()} 的任意组合。 如果它没有定义 @ref{159d,,__get__()}，则访问属性将返回描述器对象自身，除非对象的实例字典中有相应的属性值。 如果描述器定义了 @ref{15a1,,__set__()} 和/或 @ref{15a2,,__delete__()}，则它是一个数据描述器；如果以上两个都未定义，则它是一个非数据描述器。 通常，数据描述器会同时定义 @ref{159d,,__get__()} 和 @ref{15a1,,__set__()}，而非数据描述器则只有 @ref{159d,,__get__()} 方法。 定义了 @ref{159d,,__get__()} 和 @ref{15a1,,__set__()} (和/或 @ref{15a2,,__delete__()}) 的数据描述器总是会重载实例字典中的定义。 与之相对地，非数据描述器则可被实例所重载。

Python 方法（包括用 @ref{311,,@@staticmethod} 和 @ref{310,,@@classmethod} 装饰的方法）都是作为非数据描述器来实现的。 因而，实例可以重定义和重载方法。 这允许单个实例获得与相同类的其他实例不一样的行为。

@ref{30f,,property()} 函数是作为数据描述器来实现的。因此实例不能重载特性属性的行为。

@node __slots__,,发起调用描述器,自定义属性访问
@anchor{reference/datamodel id3}@anchor{15a5}@anchor{reference/datamodel slots}@anchor{15a6}
@subsubsection __slots__


@emph{__slots__} 允许我们显式地声明数据成员（如特征属性）并禁止创建 @ref{5fe,,__dict__} 和 @emph{__weakref__} (除非是在 @emph{__slots__} 中显式地声明或是在父类中可用。)

相比使用 @ref{5fe,,__dict__} 可以显著节省空间。 属性查找速度也可得到显著的提升。

@geindex object.__slots__ (內置变量)
@anchor{reference/datamodel object __slots__}@anchor{ef7}
@deffn {数据} object.__slots__

这个类变量可赋值为字符串、可迭代对象或由实例使用的变量名组成的字符串序列。 @emph{__slots__} 会为已声明的变量保留空间并阻止自动为每个实例创建 @ref{5fe,,__dict__} 和 @emph{__weakref__}。
@end deffn

@menu
* 使用 __slots__ 的注意事项:: 

@end menu

@node 使用 __slots__ 的注意事项,,,__slots__
@anchor{reference/datamodel notes-on-using-slots}@anchor{15a7}
@subsubsection 使用 @emph{__slots__} 的注意事项



@itemize *

@item 
当继承自一个没有 @emph{__slots__} 的类时，实例的 @ref{5fe,,__dict__} 和 @emph{__weakref__} 属性将总是可访问的。

@item 
没有 @ref{5fe,,__dict__} 变量，实例就不能给未在 @emph{__slots__} 定义中列出的新变量赋值。 尝试给一个未列出的变量名赋值将引发 @ref{4aa,,AttributeError}。 如果需要动态地给新变量赋值，则要将 @code{'__dict__'} 加入到在 @emph{__slots__} 中声明的字符串序列中。

@item 
如果未给每个实例设置 @emph{__weakref__} 变量，则定义了 @emph{__slots__} 的类就不支持对其实例的 @ref{131,,弱引用}。 如果需要支持弱引用，则要将 @code{'__weakref__'} 加入到在 @emph{__slots__} 中声明的字符串序列中。

@item 
@emph{__slots__} 是通过为每个变量名创建 @ref{5ec,,描述器} 在类层级上实现的。 因此，类属性不能被用来为通过 @emph{__slots__} 定义的实例变量设置默认值；否则，类属性将会覆盖描述器赋值。

@item 
@emph{__slots__} 声明的作用不只限于定义它的类。 在父类中声明的 @emph{__slots__} 在其子类中同样可用。 不过，子类将会获得 @ref{5fe,,__dict__} 和 @emph{__weakref__} 除非它们也定义了 @emph{__slots__} (其中应当仅包含任何 @emph{附加} 槽位的名称)。

@item 
如果一个类定义的位置在某个基类中也有定义，则由基类位置定义的实例变量将不可访问（除非通过直接从基类获取其描述器的方式）。这会使得程序的含义变成未定义。未来可能会添加一个防止此情况的检查。

@item 
非空的 @emph{__slots__} 不适用于派生自“可变长度”内置类型例如 @ref{205,,int}、@ref{172,,bytes} 和 @ref{1a2,,tuple} 的派生类。

@item 
任何非字符串的 @ref{c84,,iterable} 都可以被赋值给 @emph{__slots__}。

@item 
如果是使用一个 @ref{164,,字典} 来给 @emph{__slots__} 赋值，则该字典的键将被用作槽位名称。 字典的值可被用来为每个属性提供将被 @ref{30e,,inspect.getdoc()} 识别并在and displayed in the output of @ref{175,,help()} 的输出中显示的文档字符串。

@item 
@ref{ed4,,__class__} 赋值仅在两个类具有同样的 @emph{__slots__} 时会起作用。

@item 
带有多槽位父类的 @ref{1437,,多重继承} 也是可用的，但仅允许一个父类具有由槽位创建的属性（其他基类必须具有空的槽位布局） —— 违反此规则将引发 @ref{1ff,,TypeError}。

@item 
如果将 @ref{11ba,,iterator} 用于 @emph{__slots__} 则会为该迭代器的每个值创建一个 @ref{15a8,,descriptor}。 但是，@emph{__slots__} 属性将为一个空迭代器。
@end itemize

@node 自定义类创建,自定义实例及子类检查,自定义属性访问,特殊方法名称
@anchor{reference/datamodel class-customization}@anchor{5e8}@anchor{reference/datamodel customizing-class-creation}@anchor{15a9}
@subsubsection 自定义类创建


当一个类继承另一个类时，会在这个父类上调用 @ref{5e5,,__init_subclass__()}。 这样，就使得编写改变子类行为的类成为可能。 这与类装饰器有很密切的关联，但类装饰器只能影响它们所应用的特定类，而 @code{__init_subclass__} 则只作用于定义了该方法的类在未来的子类。

@geindex __init_subclass__() (object 类方法)
@anchor{reference/datamodel object __init_subclass__}@anchor{5e5}
@deffn {方法} classmethod object.__init_subclass__ (cls)

当所在类派生子类时此方法就会被调用。@emph{cls} 将指向新的子类。如果定义为一个普通实例方法，此方法将被隐式地转换为类方法。

传入一个新类的关键字参数会被传给父类的 @code{__init_subclass__}。为了与其他使用 @code{__init_subclass__} 的类兼容，应当根据需要去掉部分关键字参数再将其余的传给基类，例如:

@example
class Philosopher:
    def __init_subclass__(cls, /, default_name, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.default_name = default_name

class AustralianPhilosopher(Philosopher, default_name="Bruce"):
    pass
@end example

@code{object.__init_subclass__} 的默认实现什么都不做，只在带任意参数调用时引发一个错误。

@cartouche
@quotation 注解 
元类提示 @code{metaclass} 将被其它类型机制消耗掉，并不会被传给 @code{__init_subclass__} 的实现。实际的元类（而非显式的提示）可通过 @code{type(cls)} 访问。
@end quotation
@end cartouche


3.6 新版功能.

@end deffn

@menu
* 元类:: 
* 解析 MRO 条目:: 
* 确定适当的元类:: 
* 准备类命名空间:: 
* 执行类主体:: 
* 创建类对象:: 
* 元类的作用:: 

@end menu

@node 元类,解析 MRO 条目,,自定义类创建
@anchor{reference/datamodel id4}@anchor{15aa}@anchor{reference/datamodel metaclasses}@anchor{15ab}
@subsubsection 元类


@geindex metaclass
@geindex 內置函数; type
@geindex = (equals); class definition

默认情况下，类是使用 @ref{709,,type()} 来构建的。类体会在一个新的命名空间内执行，类名会被局部绑定到 @code{type(name, bases, namespace)} 的结果。

类创建过程可通过在定义行传入 @code{metaclass} 关键字参数，或是通过继承一个包含此参数的现有类来进行定制。在以下示例中，@code{MyClass} 和 @code{MySubclass} 都是 @code{Meta} 的实例:

@example
class Meta(type):
    pass

class MyClass(metaclass=Meta):
    pass

class MySubclass(MyClass):
    pass
@end example

在类定义内指定的任何其他关键字参数都会在下面所描述的所有元类操作中进行传递。

当一个类定义被执行时，将发生以下步骤:


@itemize *

@item 
解析 MRO 条目；

@item 
确定适当的元类；

@item 
准备类命名空间；

@item 
执行类主体；

@item 
创建类对象。
@end itemize

@node 解析 MRO 条目,确定适当的元类,元类,自定义类创建
@anchor{reference/datamodel resolving-mro-entries}@anchor{15ac}
@subsubsection 解析 MRO 条目


如果在类定义中出现的基类不是 @ref{709,,type} 的实例，则使用 @code{__mro_entries__} 方法对其进行搜索，当找到结果时，它会以原始基类元组做参数进行调用。此方法必须返回类的元组以替代此基类被使用。元组可以为空，在此情况下原始基类将被忽略。


@subsubheading 参见


@geindex Python 提高建议; PEP 560
PEP 560@footnote{https://www.python.org/dev/peps/pep-0560} - 对 typing 模块和泛型类型的核心支持


@node 确定适当的元类,准备类命名空间,解析 MRO 条目,自定义类创建
@anchor{reference/datamodel determining-the-appropriate-metaclass}@anchor{15ad}
@subsubsection 确定适当的元类


@geindex metaclass hint

为一个类定义确定适当的元类是根据以下规则:


@itemize *

@item 
如果没有基类且没有显式指定元类，则使用 @ref{709,,type()}；

@item 
如果给出一个显式元类而且 @emph{不是} @ref{709,,type()} 的实例，则其会被直接用作元类；

@item 
如果给出一个 @ref{709,,type()} 的实例作为显式元类，或是定义了基类，则使用最近派生的元类。
@end itemize

最近派生的元类会从显式指定的元类（如果有）以及所有指定的基类的元类（即 @code{type(cls)}）中选取。最近派生的元类应为 @emph{所有} 这些候选元类的一个子类型。如果没有一个候选元类符合该条件，则类定义将失败并抛出 @code{TypeError}。

@node 准备类命名空间,执行类主体,确定适当的元类,自定义类创建
@anchor{reference/datamodel prepare}@anchor{5ff}@anchor{reference/datamodel preparing-the-class-namespace}@anchor{15ae}
@subsubsection 准备类命名空间


@geindex __prepare__ (metaclass method)

一旦确定了适当的元类，就将准备好类的命名空间。 如果元类具有 @code{__prepare__} 属性，它将以 @code{namespace = metaclass.__prepare__(name, bases, **kwds)} 的形式被调用（其中如果存在任何额外关键字参数，则应来自类定义）。 @code{__prepare__} 方法应当被实现为 @ref{310,,类方法}。 @code{__prepare__} 所返回的命名空间会被传入 @code{__new__}，但是当最终的类对象被创建时该命名空间会被拷贝到一个新的 @code{dict} 中。

如果元类没有 @code{__prepare__} 属性，则类命名空间将初始化为一个空的有序映射。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3115

@item PEP 3115@footnote{https://www.python.org/dev/peps/pep-3115} - Python 3000 中的元类

引入 @code{__prepare__} 命名空间钩子
@end table


@node 执行类主体,创建类对象,准备类命名空间,自定义类创建
@anchor{reference/datamodel executing-the-class-body}@anchor{15af}
@subsubsection 执行类主体


@geindex class; body

类主体会以（类似于） @code{exec(body, globals(), namespace)} 的形式被执行。普通调用与 @ref{d14,,exec()} 的关键区别在于当类定义发生于函数内部时，词法作用域允许类主体（包括任何方法）引用来自当前和外部作用域的名称。

但是，即使当类定义发生于函数内部时，在类内部定义的方法仍然无法看到在类作用域层次上定义的名称。类变量必须通过实例的第一个形参或类方法来访问，或者是通过下一节中描述的隐式词法作用域的 @code{__class__} 引用。

@node 创建类对象,元类的作用,执行类主体,自定义类创建
@anchor{reference/datamodel class-object-creation}@anchor{5e7}@anchor{reference/datamodel creating-the-class-object}@anchor{15b0}
@subsubsection 创建类对象


@geindex __class__ (method cell)
@geindex __classcell__ (class namespace entry)

一旦执行类主体完成填充类命名空间，将通过调用 @code{metaclass(name, bases, namespace, **kwds)} 创建类对象（此处的附加关键字参数与传入 @code{__prepare__} 的相同）。

如果类主体中有任何方法引用了 @code{__class__} 或 @code{super}，这个类对象会通过零参数形式的 @ref{5e6,,super()}. @code{__class__} 所引用，这是由编译器所创建的隐式闭包引用。这使用零参数形式的 @ref{5e6,,super()} 能够正确标识正在基于词法作用域来定义的类，而被用于进行当前调用的类或实例则是基于传递给方法的第一个参数来标识的。

@strong{CPython implementation detail:} 在 CPython 3.6 及之后的版本中，@code{__class__} 单元会作为类命名空间中的 @code{__classcell__} 条目被传给元类。 如果存在，它必须被向上传播给 @code{type.__new__} 调用，以便能正确地初始化该类。 如果不这样做，在 Python 3.8 中将引发 @ref{3e4,,RuntimeError}。

当使用默认的元类 @ref{709,,type} 或者任何最终会调用 @code{type.__new__} 的元类时，以下额外的自定义步骤将在创建类对象之后被发起调用:


@itemize *

@item 
首先，@code{type.__new__} 将收集类命名空间中所有定义了 @ref{5eb,,__set_name__()} 方法的描述器；

@item 
接下来，所有这些 @code{__set_name__} 方法将使用所定义的类和特定描述器所赋的名称进行调用；

@item 
最后，将在新类根据方法解析顺序所确定的直接父类上调用 @ref{5e5,,__init_subclass__()} 钩子。
@end itemize

在类对象创建之后，它会被传给包含在类定义中的类装饰器（如果有的话），得到的对象将作为已定义的类绑定到局部命名空间。

当通过 @code{type.__new__} 创建一个新类时，提供以作为命名空间形参的对象会被复制到一个新的有序映射并丢弃原对象。这个新副本包装于一个只读代理中，后者则成为类对象的 @ref{5fe,,__dict__} 属性。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3135

@item PEP 3135@footnote{https://www.python.org/dev/peps/pep-3135} - 新的超类型

描述隐式的 @code{__class__} 闭包引用
@end table


@node 元类的作用,,创建类对象,自定义类创建
@anchor{reference/datamodel uses-for-metaclasses}@anchor{15b1}
@subsubsection 元类的作用


元类的潜在作用非常广泛。已经过尝试的设想包括枚举、日志、接口检查、自动委托、自动特征属性创建、代理、框架以及自动资源锁定/同步等等。

@node 自定义实例及子类检查,模拟泛型类型,自定义类创建,特殊方法名称
@anchor{reference/datamodel customizing-instance-and-subclass-checks}@anchor{15b2}
@subsubsection 自定义实例及子类检查


以下方法被用来重载 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 内置函数的默认行为。

特别地，元类 @ref{910,,abc.ABCMeta} 实现了这些方法以便允许将抽象基类（ABC）作为“虚拟基类”添加到任何类或类型（包括内置类型），包括其他 ABC 之中。

@geindex __instancecheck__() (class 方法)
@anchor{reference/datamodel class __instancecheck__}@anchor{15b3}
@deffn {方法} class.__instancecheck__ (self, instance)

如果 @emph{instance} 应被视为 @emph{class} 的一个（直接或间接）实例则返回真值。如果定义了此方法，则会被调用以实现 @code{isinstance(instance, class)}。
@end deffn

@geindex __subclasscheck__() (class 方法)
@anchor{reference/datamodel class __subclasscheck__}@anchor{15b4}
@deffn {方法} class.__subclasscheck__ (self, subclass)

Return true 如果 @emph{subclass} 应被视为 @emph{class} 的一个（直接或间接）子类则返回真值。如果定义了此方法，则会被调用以实现 @code{issubclass(subclass, class)}。
@end deffn

请注意这些方法的查找是基于类的类型（元类）。它们不能作为类方法在实际的类中被定义。这与基于实例被调用的特殊方法的查找是一致的，只有在此情况下实例本身被当作是类。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3119

@item PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119} - 引入抽象基类

新增功能描述，通过 @ref{15b3,,__instancecheck__()} 和 @ref{15b4,,__subclasscheck__()} 来定制 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 行为，加入此功能的动机是出于向该语言添加抽象基类的内容（参见 @ref{3,,abc} 模块）。
@end table


@node 模拟泛型类型,模拟可调用对象,自定义实例及子类检查,特殊方法名称
@anchor{reference/datamodel emulating-generic-types}@anchor{15b5}
@subsubsection 模拟泛型类型


当使用 @ref{15b6,,类型标注} 时，使用 Python 的方括号标记来 @emph{形参化} 一个 @ref{1035,,generic type} 往往会很有用处。 例如，@code{list[int]} 这样的标注可以被用来表示一个 @ref{1f9,,list} 中的所有元素均为 @ref{205,,int} 类型。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 484

@item PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} —— 类型注解

介绍 Python 中用于类型标注的框架

@item @ref{1030,,泛用别名类型}

代表形参化泛用类的对象的文档

@item @ref{15b7,,泛型（Generic）}, @ref{15b8,,用户自定义泛型} 和 @ref{1055,,typing.Generic}

有关如何实现可在运行时被形参化并能被静态类型检查器所识别的泛用类的文档。
@end table


一个类 @emph{通常} 只有在定义了特殊的类方法 @code{__class_getitem__()} 时才能被形参化。

@geindex __class_getitem__() (object 类方法)
@anchor{reference/datamodel object __class_getitem__}@anchor{440}
@deffn {方法} classmethod object.__class_getitem__ (cls, key)

按照 @emph{key} 参数指定的类型返回一个表示泛型类的专门化对象。

当在类上定义时，@code{__class_getitem__()} 会自动成为类方法。 因此，当它被定义时没有必要使用 @ref{310,,@@classmethod} 来装饰。
@end deffn

@menu
* __class_getitem__ 的目的:: 
* __class_getitem__ 与 __getitem__:: 

@end menu

@node __class_getitem__ 的目的,__class_getitem__ 与 __getitem__,,模拟泛型类型
@anchor{reference/datamodel the-purpose-of-class-getitem}@anchor{15b9}
@subsubsection @emph{__class_getitem__} 的目的


@ref{440,,__class_getitem__()} 的目的是允许标准库泛型类的运行时形参化以更方便地对这些类应用 @ref{15ba,,类型提示}。

要实现可以在运行时被形参化并可被静态类型检查所理解的自定义泛型类，用户应当从已经实现了 @ref{440,,__class_getitem__()} 的标准库类继承，或是从 @ref{1055,,typing.Generic} 继承，这个类拥有自己的 @code{__class_getitem__()} 实现。

标准库以外的类上的 @ref{440,,__class_getitem__()} 自定义实现可能无法被第三方类型检查器如 mypy 所理解。 不建议在任何类上出于类型提示以外的目的使用 @code{__class_getitem__()}。

@node __class_getitem__ 与 __getitem__,,__class_getitem__ 的目的,模拟泛型类型
@anchor{reference/datamodel class-getitem-versus-getitem}@anchor{15bb}@anchor{reference/datamodel classgetitem-versus-getitem}@anchor{15bc}
@subsubsection @emph{__class_getitem__} 与 @emph{__getitem__}


通常，使用方括号语法 @ref{15bd,,抽取} 一个对象将会调用在该对象的类上定义的 @ref{3ad,,__getitem__()} 实例方法。 不过，如果被拟抽取的对象本身是一个类，则可能会调用 @ref{440,,__class_getitem__()} 类方法。 @code{__class_getitem__()} 如果被正确地定义，则应当返回一个 @ref{1030,,GenericAlias} 对象。

使用 @ref{15be,,expression} @code{obj[x]} 来呈现，Python 解释器会遵循下面这样的过程来确定应当调用 @ref{3ad,,__getitem__()} 还是 @ref{440,,__class_getitem__()}:

@example
from inspect import isclass

def subscribe(obj, x):
    """Return the result of the expression `obj[x]`"""

    class_of_obj = type(obj)

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__(obj, x)
    if hasattr(class_of_obj, '__getitem__'):
        return class_of_obj.__getitem__(obj, x)

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__(x)
    elif isclass(obj) and hasattr(obj, '__class_getitem__'):
        return obj.__class_getitem__(x)

    # Else, raise an exception
    else:
        raise TypeError(
            f"'@{class_of_obj.__name__@}' object is not subscriptable"
        )
@end example

在 Python 中，所有的类自身也是其他类的实例。 一个类所属的类被称为该类的 @ref{15bf,,metaclass}，并且大多数类都将 @ref{709,,type} 类作为它们的元类。 @ref{709,,type} 没有定义 @ref{3ad,,__getitem__()}，这意味着 @code{list[int]}, @code{dict[str, float]} 和 @code{tuple[str, bytes]} 这样的表达式都将导致 @ref{440,,__class_getitem__()} 被调用:

@example
>>> # list has class "type" as its metaclass, like most classes:
>>> type(list)
<class 'type'>
>>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
True
>>> # "list[int]" calls "list.__class_getitem__(int)"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type(list[int])
<class 'types.GenericAlias'>
@end example

然而，如果一个类属于定义了 @ref{3ad,,__getitem__()} 的自定义元类，则抽取该类可能导致不同的行为。 这方面的一个例子可以在 @ref{79,,enum} 模块中找到:

@example
>>> from enum import Enum
>>> class Menu(Enum):
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type(Menu)
<class 'enum.EnumMeta'>
>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']
<Menu.SPAM: 'spam'>
>>> type(Menu['SPAM'])
<enum 'Menu'>
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 560

@item PEP 560@footnote{https://www.python.org/dev/peps/pep-0560} - 对 typing 模块和泛型的核心支持

介绍 @ref{440,,__class_getitem__()}，并指明 @ref{15bd,,抽取} 在何时会导致 @code{__class_getitem__()} 而不是 @ref{3ad,,__getitem__()} 被调用
@end table


@node 模拟可调用对象,模拟容器类型,模拟泛型类型,特殊方法名称
@anchor{reference/datamodel callable-types}@anchor{15c0}@anchor{reference/datamodel emulating-callable-objects}@anchor{15c1}
@subsubsection 模拟可调用对象


@geindex __call__() (object 方法)
@anchor{reference/datamodel object __call__}@anchor{158f}
@deffn {方法} object.__call__ (self[, args...])

@geindex call; instance

此方法会在实例作为一个函数被“调用”时被调用；如果定义了此方法，则 @code{x(arg1, arg2, ...)} 就大致可以被改写为 @code{type(x).__call__(x, arg1, ...)}。
@end deffn

@node 模拟容器类型,模拟数字类型,模拟可调用对象,特殊方法名称
@anchor{reference/datamodel emulating-container-types}@anchor{15c2}@anchor{reference/datamodel sequence-types}@anchor{15c3}
@subsubsection 模拟容器类型


可以定义下列方法来实现容器对象。 窗口通常属于 @ref{138b,,序列} (如 @ref{1f9,,列表} 或 @ref{1a2,,元组}) 或者 @ref{c14,,映射} (如 @ref{164,,字典})，但也有表现为其他形式的容器。 前几个方法被用来模拟序列或是模拟映射；两者的不同之处在于序列允许的键应为整数 @emph{k} 并且 @code{0 <= k < N} 其中 @emph{N} 是序列或 @ref{ed0,,slice} 对象的长度，它们定义了条目的范围。 此外还建议让映射提供 @code{keys()}, @code{values()}, @code{items()}, @code{get()}, @code{clear()}, @code{setdefault()}, @code{pop()}, @code{popitem()}, @code{copy()} 以及 @code{update()} 等方法，它们的行为应与 Python 的标准 @ref{164,,字典} 对象类似。 此外 @ref{1e,,collections.abc} 模块提供了一个 @ref{ad7,,MutableMapping} @ref{c0e,,abstract base class} 以便根据由 @ref{3ad,,__getitem__()}, @ref{d32,,__setitem__()}, @ref{d33,,__delitem__()} 和 @code{keys()} 组成的基本集来创建所需的方法。 可变序列还应提供 @code{append()}, @code{count()}, @code{index()}, @code{extend()}, @code{insert()}, @code{pop()}, @code{remove()}, @code{reverse()} 和 @code{sort()} 等方法，就像 Python 的标准 @ref{1f9,,list} 对象那样。 最后，序列类型还应通过定义下文描述的 @ref{15c4,,__add__()}, @ref{15c5,,__radd__()}, @ref{f37,,__iadd__()}, @ref{15c6,,__mul__()}, @ref{15c7,,__rmul__()} 和 @ref{15c8,,__imul__()} 等方法来实现加法（指拼接）和乘法（指重复）；它们不应定义其他数值运算符。 此外还建议映射和序列都实现 @ref{df6,,__contains__()} 方法以允许高效地使用 @code{in} 运算符；对于映射，@code{in} 应当搜索映射的键；对于序列，则应当搜索其中的值。 另外还建议映射和序列都实现 @ref{611,,__iter__()} 方法以允许高效地迭代容器中的条目；对于映射，@ref{611,,__iter__()} 应当迭代对象的键；对于序列，则应当迭代其中的值。

@geindex __len__() (object 方法)
@anchor{reference/datamodel object __len__}@anchor{e98}
@deffn {方法} object.__len__ (self)

@geindex 內置函数; len
@geindex __bool__() (object method)

调用此方法以实现内置函数 @ref{292,,len()}。应该返回对象的长度，以一个 @code{>=} 0 的整数表示。此外，如果一个对象未定义 @ref{d38,,__bool__()} 方法而其 @ref{e98,,__len__()} 方法返回值为零，则在布尔运算中会被视为假值。

@strong{CPython implementation detail:} 在 CPython 中，要求长度最大为 @ref{c1e,,sys.maxsize}。如果长度大于 @code{sys.maxsize} 则某些特性 (例如 @ref{292,,len()}) 可能会引发 @ref{a4a,,OverflowError}。要通过真值检测来防止引发 @code{OverflowError}，对象必须定义 @ref{d38,,__bool__()} 方法。
@end deffn

@geindex __length_hint__() (object 方法)
@anchor{reference/datamodel object __length_hint__}@anchor{903}
@deffn {方法} object.__length_hint__ (self)

调用此方法以实现 @ref{971,,operator.length_hint()}。 应该返回对象长度的估计值（可能大于或小于实际长度）。 此长度应为一个 @code{>=} 0 的整数。 返回值也可以为 @ref{203,,NotImplemented}，这会被视作与 @code{__length_hint__} 方法完全不存在时一样处理。 此方法纯粹是为了优化性能，并不要求正确无误。


3.4 新版功能.

@end deffn

@geindex 对象; slice

@cartouche
@quotation 注解 
切片是通过下述三个专门方法完成的。以下形式的调用

@example
a[1:2] = b
@end example

会为转写为

@example
a[slice(1, 2, None)] = b
@end example

其他形式以此类推。略去的切片项总是以 @code{None} 补全。
@end quotation
@end cartouche

@geindex __getitem__() (object 方法)
@anchor{reference/datamodel object __getitem__}@anchor{3ad}
@deffn {方法} object.__getitem__ (self, key)

调用此方法以实现 @code{self[key]} 的未付。 对于 @ref{138b,,sequence} 类型，接受的键应为整数和切片对象。 请注意负数索引（如果类想要模拟 @ref{138b,,sequence} 类型）的特殊解读是依赖于 @ref{3ad,,__getitem__()} 方法。 如果 @emph{key} 的类型不正确，则会引发 @ref{1ff,,TypeError}；如果为序列索引集范围以外的值（在进行任何负数索引的特殊解读之后），则应当引发 @ref{f3d,,IndexError}。 对于 @ref{c14,,mapping} 类型，如果 @emph{key} 找不到（不在容器中），则应当引发 @ref{3f1,,KeyError}。

@cartouche
@quotation 注解 
@ref{d02,,for} 循环在有不合法索引时会期待捕获 @ref{f3d,,IndexError} 以便正确地检测到序列的结束。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
当 @ref{15bd,,抽取} 一个 @emph{class} 时，可能会调用特殊类方法 @ref{440,,__class_getitem__()} 而不是 @code{__getitem__()}。 请参阅 @ref{15bc,,__class_getitem__ 与 __getitem__} 了解详情。
@end quotation
@end cartouche
@end deffn

@geindex __setitem__() (object 方法)
@anchor{reference/datamodel object __setitem__}@anchor{d32}
@deffn {方法} object.__setitem__ (self, key, value)

调用此方法以实现向 @code{self[key]} 赋值。注意事项与 @ref{3ad,,__getitem__()} 相同。为对象实现此方法应该仅限于需要映射允许基于键修改值或添加键，或是序列允许元素被替换时。不正确的 @emph{key} 值所引发的异常应与 @ref{3ad,,__getitem__()} 方法的情况相同。
@end deffn

@geindex __delitem__() (object 方法)
@anchor{reference/datamodel object __delitem__}@anchor{d33}
@deffn {方法} object.__delitem__ (self, key)

调用此方法以实现 @code{self[key]} 的删除。注意事项与 @ref{3ad,,__getitem__()} 相同。为对象实现此方法应该权限于需要映射允许移除键，或是序列允许移除元素时。不正确的 @emph{key} 值所引发的异常应与 @ref{3ad,,__getitem__()} 方法的情况相同。
@end deffn

@geindex __missing__() (object 方法)
@anchor{reference/datamodel object __missing__}@anchor{c16}
@deffn {方法} object.__missing__ (self, key)

此方法由 @ref{164,,dict}.@ref{3ad,,__getitem__()} 在找不到字典中的键时调用以实现 dict 子类的 @code{self[key]}。
@end deffn

@geindex __iter__() (object 方法)
@anchor{reference/datamodel object __iter__}@anchor{611}
@deffn {方法} object.__iter__ (self)

此方法在需要为容器创建迭代器时被调用。此方法应该返回一个新的迭代器对象，它能够逐个迭代容器中的所有对象。对于映射，它应该逐个迭代容器中的键。

迭代器对象也需要实现此方法；它们需要返回对象自身。有关迭代器对象的详情请参看 @ref{15c9,,迭代器类型} 一节。
@end deffn

@geindex __reversed__() (object 方法)
@anchor{reference/datamodel object __reversed__}@anchor{631}
@deffn {方法} object.__reversed__ (self)

此方法（如果存在）会被 @ref{2cd,,reversed()} 内置函数调用以实现逆向迭代。它应当返回一个新的以逆序逐个迭代容器内所有对象的迭代器对象。

如果未提供 @ref{631,,__reversed__()} 方法，则 @ref{2cd,,reversed()} 内置函数将回退到使用序列协议 (@ref{e98,,__len__()} 和 @ref{3ad,,__getitem__()})。支持序列协议的对象应当仅在能够提供比 @ref{2cd,,reversed()} 所提供的实现更高效的实现时才提供 @ref{631,,__reversed__()} 方法。
@end deffn

成员检测运算符 (@ref{179,,in} 和 @ref{15ca,,not in}) 通常以对容器进行逐个迭代的方式来实现。 不过，容器对象可以提供以下特殊方法并采用更有效率的实现，这样也不要求对象必须为可迭代对象。

@geindex __contains__() (object 方法)
@anchor{reference/datamodel object __contains__}@anchor{df6}
@deffn {方法} object.__contains__ (self, item)

调用此方法以实现成员检测运算符。如果 @emph{item} 是 @emph{self} 的成员则应返回真，否则返回假。对于映射类型，此检测应基于映射的键而不是值或者键值对。

对于未定义 @ref{df6,,__contains__()} 的对象，成员检测将首先尝试通过 @ref{611,,__iter__()} 进行迭代，然后再使用 @ref{3ad,,__getitem__()} 的旧式序列迭代协议，参看 @ref{15cb,,语言参考中的相应部分}。
@end deffn

@node 模拟数字类型,with 语句上下文管理器,模拟容器类型,特殊方法名称
@anchor{reference/datamodel emulating-numeric-types}@anchor{15cc}@anchor{reference/datamodel numeric-types}@anchor{15cd}
@subsubsection 模拟数字类型


定义以下方法即可模拟数字类型。特定种类的数字不支持的运算（例如非整数不能进行位运算）所对应的方法应当保持未定义状态。

@geindex __add__() (object 方法)
@geindex __sub__() (object 方法)
@geindex __mul__() (object 方法)
@geindex __matmul__() (object 方法)
@geindex __truediv__() (object 方法)
@geindex __floordiv__() (object 方法)
@geindex __mod__() (object 方法)
@geindex __divmod__() (object 方法)
@geindex __pow__() (object 方法)
@geindex __lshift__() (object 方法)
@geindex __rshift__() (object 方法)
@geindex __and__() (object 方法)
@geindex __xor__() (object 方法)
@geindex __or__() (object 方法)
@anchor{reference/datamodel object __add__}@anchor{15c4}
@deffn {方法} object.__add__ (self, other)
@anchor{reference/datamodel object __sub__}@anchor{15ce}
@deffnx {方法} object.__sub__ (self, other)
@anchor{reference/datamodel object __mul__}@anchor{15c6}
@deffnx {方法} object.__mul__ (self, other)
@anchor{reference/datamodel object __matmul__}@anchor{745}
@deffnx {方法} object.__matmul__ (self, other)
@anchor{reference/datamodel object __truediv__}@anchor{87f}
@deffnx {方法} object.__truediv__ (self, other)
@anchor{reference/datamodel object __floordiv__}@anchor{eff}
@deffnx {方法} object.__floordiv__ (self, other)
@anchor{reference/datamodel object __mod__}@anchor{15cf}
@deffnx {方法} object.__mod__ (self, other)
@anchor{reference/datamodel object __divmod__}@anchor{880}
@deffnx {方法} object.__divmod__ (self, other)
@anchor{reference/datamodel object __pow__}@anchor{15d0}
@deffnx {方法} object.__pow__ (self, other[, modulo])
@anchor{reference/datamodel object __lshift__}@anchor{15d1}
@deffnx {方法} object.__lshift__ (self, other)
@anchor{reference/datamodel object __rshift__}@anchor{15d2}
@deffnx {方法} object.__rshift__ (self, other)
@anchor{reference/datamodel object __and__}@anchor{15d3}
@deffnx {方法} object.__and__ (self, other)
@anchor{reference/datamodel object __xor__}@anchor{15d4}
@deffnx {方法} object.__xor__ (self, other)
@anchor{reference/datamodel object __or__}@anchor{15d5}
@deffnx {方法} object.__or__ (self, other)

@geindex 內置函数; divmod
@geindex 內置函数; pow
@geindex 內置函数; pow

调用这些方法来实现二进制算术运算 (@code{+}, @code{-}, @code{*}, @code{@@}, @code{/}, @code{//}, @code{%}, @ref{294,,divmod()}, @ref{2d6,,pow()}, @code{**}, @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|})。例如，求表达式 @code{x + y} 的值，其中 @emph{x} 是具有 @ref{15c4,,__add__()} 方法的类的一个实例，则会调用 @code{x.__add__(y)}。@ref{880,,__divmod__()} 方法应该等价于使用 @ref{eff,,__floordiv__()} 和 @ref{15cf,,__mod__()}，它不应该被关联到 @ref{87f,,__truediv__()}。请注意如果要支持三元版本的内置 @ref{2d6,,pow()} 函数，则 @ref{15d0,,__pow__()} 的定义应该接受可选的第三个参数。

如果这些方法中的某一个不支持与所提供参数进行运算，它应该返回 @code{NotImplemented}。
@end deffn

@geindex __radd__() (object 方法)
@geindex __rsub__() (object 方法)
@geindex __rmul__() (object 方法)
@geindex __rmatmul__() (object 方法)
@geindex __rtruediv__() (object 方法)
@geindex __rfloordiv__() (object 方法)
@geindex __rmod__() (object 方法)
@geindex __rdivmod__() (object 方法)
@geindex __rpow__() (object 方法)
@geindex __rlshift__() (object 方法)
@geindex __rrshift__() (object 方法)
@geindex __rand__() (object 方法)
@geindex __rxor__() (object 方法)
@geindex __ror__() (object 方法)
@anchor{reference/datamodel object __radd__}@anchor{15c5}
@deffn {方法} object.__radd__ (self, other)
@anchor{reference/datamodel object __rsub__}@anchor{15d6}
@deffnx {方法} object.__rsub__ (self, other)
@anchor{reference/datamodel object __rmul__}@anchor{15c7}
@deffnx {方法} object.__rmul__ (self, other)
@anchor{reference/datamodel object __rmatmul__}@anchor{746}
@deffnx {方法} object.__rmatmul__ (self, other)
@anchor{reference/datamodel object __rtruediv__}@anchor{15d7}
@deffnx {方法} object.__rtruediv__ (self, other)
@anchor{reference/datamodel object __rfloordiv__}@anchor{15d8}
@deffnx {方法} object.__rfloordiv__ (self, other)
@anchor{reference/datamodel object __rmod__}@anchor{7ac}
@deffnx {方法} object.__rmod__ (self, other)
@anchor{reference/datamodel object __rdivmod__}@anchor{15d9}
@deffnx {方法} object.__rdivmod__ (self, other)
@anchor{reference/datamodel object __rpow__}@anchor{15da}
@deffnx {方法} object.__rpow__ (self, other[, modulo])
@anchor{reference/datamodel object __rlshift__}@anchor{15db}
@deffnx {方法} object.__rlshift__ (self, other)
@anchor{reference/datamodel object __rrshift__}@anchor{15dc}
@deffnx {方法} object.__rrshift__ (self, other)
@anchor{reference/datamodel object __rand__}@anchor{15dd}
@deffnx {方法} object.__rand__ (self, other)
@anchor{reference/datamodel object __rxor__}@anchor{15de}
@deffnx {方法} object.__rxor__ (self, other)
@anchor{reference/datamodel object __ror__}@anchor{15df}
@deffnx {方法} object.__ror__ (self, other)

@geindex 內置函数; divmod
@geindex 內置函数; pow

调用这些方法来实现具有反射（交换）操作数的二进制算术运算 (@code{+}, @code{-}, @code{*}, @code{@@}, @code{/}, @code{//}, @code{%}, @ref{294,,divmod()}, @ref{2d6,,pow()}, @code{**}, @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|})。这些成员函数仅会在左操作数不支持相应运算 @footnote{@w{(3)} 
这里的“不支持”是指该类无此方法，或方法返回 @code{NotImplemented}。 如果你想强制回退到右操作数的反射方法，请不要设置方法为 @code{None} — 那会造成显式地 @emph{阻塞} 此种回退的相反效果。
} 且两个操作数类型不同时被调用。@footnote{@w{(4)} 
对于相同类型的操作数，如果非返回方法 -- 例如 @ref{15c4,,__add__()} -- 失败则会认为整个运算都不被支持，这就是反射方法不会被调用的原因。
} 例如，求表达式 @code{x - y} 的值，其中 @emph{y} 是具有 @ref{15d6,,__rsub__()} 方法的类的一个实例，则当 @code{x.__sub__(y)} 返回 @emph{NotImplemented} 时会调用 @code{y.__rsub__(x)}。

@geindex 內置函数; pow

请注意三元版的 @ref{2d6,,pow()} 并不会尝试调用 @ref{15da,,__rpow__()} (因为强制转换规则会太过复杂)。

@cartouche
@quotation 注解 
如果右操作数类型为左操作数类型的一个子类，且该子类提供了指定运算的反射方法，则此方法将先于左操作数的非反射方法被调用。 此行为可允许子类重载其祖先类的运算符。
@end quotation
@end cartouche
@end deffn

@geindex __iadd__() (object 方法)
@geindex __isub__() (object 方法)
@geindex __imul__() (object 方法)
@geindex __imatmul__() (object 方法)
@geindex __itruediv__() (object 方法)
@geindex __ifloordiv__() (object 方法)
@geindex __imod__() (object 方法)
@geindex __ipow__() (object 方法)
@geindex __ilshift__() (object 方法)
@geindex __irshift__() (object 方法)
@geindex __iand__() (object 方法)
@geindex __ixor__() (object 方法)
@geindex __ior__() (object 方法)
@anchor{reference/datamodel object __iadd__}@anchor{f37}
@deffn {方法} object.__iadd__ (self, other)
@anchor{reference/datamodel object __isub__}@anchor{f38}
@deffnx {方法} object.__isub__ (self, other)
@anchor{reference/datamodel object __imul__}@anchor{15c8}
@deffnx {方法} object.__imul__ (self, other)
@anchor{reference/datamodel object __imatmul__}@anchor{747}
@deffnx {方法} object.__imatmul__ (self, other)
@anchor{reference/datamodel object __itruediv__}@anchor{15e0}
@deffnx {方法} object.__itruediv__ (self, other)
@anchor{reference/datamodel object __ifloordiv__}@anchor{15e1}
@deffnx {方法} object.__ifloordiv__ (self, other)
@anchor{reference/datamodel object __imod__}@anchor{15e2}
@deffnx {方法} object.__imod__ (self, other)
@anchor{reference/datamodel object __ipow__}@anchor{15e3}
@deffnx {方法} object.__ipow__ (self, other[, modulo])
@anchor{reference/datamodel object __ilshift__}@anchor{15e4}
@deffnx {方法} object.__ilshift__ (self, other)
@anchor{reference/datamodel object __irshift__}@anchor{15e5}
@deffnx {方法} object.__irshift__ (self, other)
@anchor{reference/datamodel object __iand__}@anchor{15e6}
@deffnx {方法} object.__iand__ (self, other)
@anchor{reference/datamodel object __ixor__}@anchor{15e7}
@deffnx {方法} object.__ixor__ (self, other)
@anchor{reference/datamodel object __ior__}@anchor{15e8}
@deffnx {方法} object.__ior__ (self, other)

调用这些方法来实现扩展算术赋值 (@code{+=}, @code{-=}, @code{*=}, @code{@@=}, @code{/=}, @code{//=}, @code{%=}, @code{**=}, @code{<<=}, @code{>>=}, @code{&=}, @code{^=}, @code{|=})。这些方法应该尝试进行自身操作 (修改 @emph{self}) 并返回结果 (结果应该但并非必须为 @emph{self})。如果某个方法未被定义，相应的扩展算术赋值将回退到普通方法。例如，如果 @emph{x} 是具有 @ref{f37,,__iadd__()} 方法的类的一个实例，则 @code{x += y} 就等价于 @code{x = x.__iadd__(y)}。否则就如 @code{x + y} 的求值一样选择 @code{x.__add__(y)} 和 @code{y.__radd__(x)}。在某些情况下，扩展赋值可导致未预期的错误 (参见 @ref{15e9,,为什么 a_tuple[i] += ['item'] 会引发异常？})，但此行为实际上是数据模型的一个组成部分。

@cartouche
@quotation 注解 
由于 @code{**=} 的分配机制存在一个错误，定义了 @ref{15e3,,__ipow__()} 但是返回 @code{NotImplemented} 的类将无法回退到 @code{x.__pow__(y)} 和 @code{y.__rpow__(x)}。 此错误在 Python 3.10 中被修正。
@end quotation
@end cartouche
@end deffn

@geindex __neg__() (object 方法)
@geindex __pos__() (object 方法)
@geindex __abs__() (object 方法)
@geindex __invert__() (object 方法)
@anchor{reference/datamodel object __neg__}@anchor{15ea}
@deffn {方法} object.__neg__ (self)
@anchor{reference/datamodel object __pos__}@anchor{15eb}
@deffnx {方法} object.__pos__ (self)
@anchor{reference/datamodel object __abs__}@anchor{15ec}
@deffnx {方法} object.__abs__ (self)
@anchor{reference/datamodel object __invert__}@anchor{15ed}
@deffnx {方法} object.__invert__ (self)

@geindex 內置函数; abs

调用此方法以实现一元算术运算 (@code{-}, @code{+}, @ref{1424,,abs()} 和 @code{~})。
@end deffn

@geindex __complex__() (object 方法)
@geindex __int__() (object 方法)
@geindex __float__() (object 方法)
@anchor{reference/datamodel object __complex__}@anchor{2cc}
@deffn {方法} object.__complex__ (self)
@anchor{reference/datamodel object __int__}@anchor{2ca}
@deffnx {方法} object.__int__ (self)
@anchor{reference/datamodel object __float__}@anchor{2cb}
@deffnx {方法} object.__float__ (self)

@geindex 內置函数; complex
@geindex 內置函数; int
@geindex 內置函数; float

调用这些方法以实现内置函数 @ref{2c8,,complex()}, @ref{205,,int()} 和 @ref{1fe,,float()}。应当返回一个相应类型的值。
@end deffn

@geindex __index__() (object 方法)
@anchor{reference/datamodel object __index__}@anchor{2c9}
@deffn {方法} object.__index__ (self)

调用此方法以实现 @ref{15ee,,operator.index()} 以及 Python 需要无损地将数字对象转换为整数对象的场合（例如切片或是内置的 @ref{d10,,bin()}, @ref{d36,,hex()} 和 @ref{d35,,oct()} 函数)。 存在此方法表明数字对象属于整数类型。 必须返回一个整数。

如果未定义 @ref{2ca,,__int__()}, @ref{2cb,,__float__()} 和 @ref{2cc,,__complex__()} 则相应的内置函数 @ref{205,,int()}, @ref{1fe,,float()} 和 @ref{2c8,,complex()} 将回退为 @ref{2c9,,__index__()}。
@end deffn

@geindex __round__() (object 方法)
@geindex __trunc__() (object 方法)
@geindex __floor__() (object 方法)
@geindex __ceil__() (object 方法)
@anchor{reference/datamodel object __round__}@anchor{15ef}
@deffn {方法} object.__round__ (self[, ndigits])
@anchor{reference/datamodel object __trunc__}@anchor{15f0}
@deffnx {方法} object.__trunc__ (self)
@anchor{reference/datamodel object __floor__}@anchor{15f1}
@deffnx {方法} object.__floor__ (self)
@anchor{reference/datamodel object __ceil__}@anchor{15f2}
@deffnx {方法} object.__ceil__ (self)

@geindex 內置函数; round

调用这些方法以实现内置函数 @ref{d3d,,round()} 以及 @ref{b1,,math} 函数 @ref{dfc,,trunc()}, @ref{dfa,,floor()} 和 @ref{dfb,,ceil()}。 除了将 @emph{ndigits} 传给 @code{__round__()} 的情况之外这些方法的返回值都应当是原对象截断为 @ref{1585,,Integral} (通常为 @ref{205,,int})。

如果 @ref{2ca,,__int__()} 或 @ref{2c9,,__index__()} 均未被定义则内置函数 @ref{205,,int()} 会回退至 @ref{15f0,,__trunc__()}。
@end deffn

@node with 语句上下文管理器,特殊方法查找,模拟数字类型,特殊方法名称
@anchor{reference/datamodel context-managers}@anchor{15f3}@anchor{reference/datamodel with-statement-context-managers}@anchor{15f4}
@subsubsection with 语句上下文管理器


@emph{上下文管理器} 是一个对象，它定义了在执行 @ref{7e4,,with} 语句时要建立的运行时上下文。 上下文管理器处理进入和退出所需运行时上下文以执行代码块。 通常使用 @code{with} 语句（在 @ref{7e4,,with 语句} 中描述），但是也可以通过直接调用它们的方法来使用。

@geindex 语句; with
@geindex context manager

上下文管理器的典型用法包括保存和恢复各种全局状态，锁定和解锁资源，关闭打开的文件等等。

要了解上下文管理器的更多信息，请参阅 @ref{15f5,,上下文管理器类型}。

@geindex __enter__() (object 方法)
@anchor{reference/datamodel object __enter__}@anchor{d65}
@deffn {方法} object.__enter__ (self)

进入与此对象相关的运行时上下文。 @ref{7e4,,with} 语句将会绑定这个方法的返回值到 @code{as} 子句中指定的目标，如果有的话。
@end deffn

@geindex __exit__() (object 方法)
@anchor{reference/datamodel object __exit__}@anchor{d66}
@deffn {方法} object.__exit__ (self, exc_type, exc_value, traceback)

退出关联到此对象的运行时上下文。 各个参数描述了导致上下文退出的异常。 如果上下文是无异常地退出的，三个参数都将为 @ref{204,,None}。

如果提供了异常，并且希望方法屏蔽此异常（即避免其被传播），则应当返回真值。 否则的话，异常将在退出此方法时按正常流程处理。

请注意 @ref{d66,,__exit__()} 方法不应该重新引发被传入的异常，这是调用者的责任。
@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 343

@item PEP 343@footnote{https://www.python.org/dev/peps/pep-0343} - "with" 语句

Python @ref{7e4,,with} 语句的规范描述、背景和示例。
@end table


@node 特殊方法查找,,with 语句上下文管理器,特殊方法名称
@anchor{reference/datamodel special-lookup}@anchor{159e}@anchor{reference/datamodel special-method-lookup}@anchor{15f6}
@subsubsection 特殊方法查找


对于自定义类来说，特殊方法的隐式发起调用仅保证在其定义于对象类型中时能正确地发挥作用，而不能定义在对象实例字典中。 该行为就是以下代码会引发异常的原因。:

@example
>>> class C:
...     pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()
@end example

此行为背后的原理在于包括类型对象在内的所有对象都会实现的几个特殊方法如 @ref{455,,__hash__()} 和 @ref{453,,__repr__()}。 如果这些方法的隐式查找使用了传统的查找过程，则当它们在对类型对象自身发起调用时将会失败:

@example
>>> 1 .__hash__() == hash(1)
True
>>> int.__hash__() == hash(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor '__hash__' of 'int' object needs an argument
@end example

以这种方式不正确地尝试发起调用一个类的未绑定方法有时被称为‘元类混淆’，可以通过在查找特殊方法时绕过实例的方式来避免:

@example
>>> type(1).__hash__(1) == hash(1)
True
>>> type(int).__hash__(int) == hash(int)
True
@end example

除了出于正确性考虑而会绕过任何实例属性，隐式特殊方法查找通常还会绕过 @ref{552,,__getattribute__()} 方法，甚至包括对象的元类:

@example
>>> class Meta(type):
...     def __getattribute__(*args):
...         print("Metaclass getattribute invoked")
...         return type.__getattribute__(*args)
...
>>> class C(object, metaclass=Meta):
...     def __len__(self):
...         return 10
...     def __getattribute__(*args):
...         print("Class getattribute invoked")
...         return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__()                 # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c)          # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c)                      # Implicit lookup
10
@end example

以这种方式绕过 @ref{552,,__getattribute__()} 机制为解释器内部的速度优化提供了显著的空间，其代价则是牺牲了一些处理特殊方法时的灵活性（特殊方法 @emph{must} 必须设置在类对象自身上以便始终一致地由解释器发起调用）。

@geindex coroutine

@node 协程,,特殊方法名称,数据模型
@anchor{reference/datamodel coroutines}@anchor{15f7}
@subsection 协程


@menu
* 可等待对象:: 
* 协程对象:: 
* 异步迭代器:: 
* 异步上下文管理器:: 

@end menu

@node 可等待对象,协程对象,,协程
@anchor{reference/datamodel awaitable-objects}@anchor{15f8}
@subsubsection 可等待对象


@ref{61b,,awaitable} 对象主要实现了 @ref{73f,,__await__()} 方法。 从 @ref{3b1,,async def} 函数返回的 @ref{18a,,协程对象} 即为可等待对象。

@cartouche
@quotation 注解 
从带有 @ref{875,,types.coroutine()} 或 @ref{3b0,,asyncio.coroutine()} 装饰器的生成器返回的 @ref{561,,generator iterator} 对象也属于可等待对象，但它们并未实现 @ref{73f,,__await__()}。
@end quotation
@end cartouche

@geindex __await__() (object 方法)
@anchor{reference/datamodel object __await__}@anchor{73f}
@deffn {方法} object.__await__ (self)

必须返回一个 @ref{11ba,,iterator}。 应当被用来实现 @ref{61b,,awaitable} 对象。 例如，@ref{54e,,asyncio.Future} 实现了此方法以与 @ref{2df,,await} 表达式相兼容。
@end deffn


3.5 新版功能.



@subsubheading 参见


@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 了解有关可等待对象的详细信息。


@node 协程对象,异步迭代器,可等待对象,协程
@anchor{reference/datamodel coroutine-objects}@anchor{158d}@anchor{reference/datamodel id7}@anchor{15f9}
@subsubsection 协程对象


@ref{18a,,协程对象} 属于 @ref{61b,,awaitable} 对象。 协程的执行可以通过调用 @ref{73f,,__await__()} 并迭代其结果来控制。 当协程结束执行并返回时，迭代器会引发 @ref{58a,,StopIteration}，而该异常的 @code{value} 属性将存放返回值。 如果协程引发了异常，它会被迭代器传播出去。 协程不应当直接引发未被处理的 @ref{58a,,StopIteration} 异常。

协程也具有下面列出的方法，它们类似于生成器的对应方法 (参见 @ref{15fa,,生成器-迭代器的方法})。 但是，与生成器不同，协程并不直接支持迭代。


在 3.5.2 版更改: 等待一个协程超过一次将引发 @ref{3e4,,RuntimeError}。


@geindex send() (coroutine 方法)
@anchor{reference/datamodel coroutine send}@anchor{15fb}
@deffn {方法} coroutine.send (value)

开始或恢复协程的执行。 如果 @emph{value} 为 @code{None}，那么这就相当于前往 @ref{73f,,__await__()} 所返回迭代器的下一项。 如果 @emph{value} 不为 @code{None}，此方法将委托给导致协程挂起的迭代器的 @ref{15fc,,send()} 方法。 其结果（返回值，@ref{58a,,StopIteration} 或是其他异常）将与上述对 @ref{73f,,__await__()} 返回值进行迭代的结果相同。
@end deffn

@geindex throw() (coroutine 方法)
@anchor{reference/datamodel coroutine throw}@anchor{15fd}
@deffn {方法} coroutine.throw (value)

@deffnx {方法} coroutine.throw (type[, value[, traceback]])

在协程内引发指定的异常。 此方法将委托给导致该协程挂起的迭代器的 @ref{1042,,throw()} 方法，如果存在此方法的话。 否则，该异常将在挂起点被引发。 其结果（返回值，@ref{58a,,StopIteration} 或是其他异常）将与上述对 @ref{73f,,__await__()} 返回值进行迭代的结果相同。 如果该异常未在协程内被捕获，则将回传给调用方。
@end deffn

@geindex close() (coroutine 方法)
@anchor{reference/datamodel coroutine close}@anchor{15fe}
@deffn {方法} coroutine.close ()

此方法会使得协程清理自身并退出。 如果协程被挂起，此方法会先委托给导致协程挂起的迭代器的 @ref{15ff,,close()} 方法，如果存在该方法。 然后它会在挂起点引发 @ref{e00,,GeneratorExit}，使得协程立即清理自身。 最后，协程会被标记为已结束执行，即使它根本未被启动。

当协程对象将要被销毁时，会使用以上处理过程来自动关闭。
@end deffn

@node 异步迭代器,异步上下文管理器,协程对象,协程
@anchor{reference/datamodel async-iterators}@anchor{743}@anchor{reference/datamodel asynchronous-iterators}@anchor{1600}
@subsubsection 异步迭代器


@emph{异步迭代器} 可以在其 @code{__anext__} 方法中调用异步代码。

异步迭代器可在 @ref{406,,async for} 语句中使用。

@geindex __aiter__() (object 方法)
@anchor{reference/datamodel object __aiter__}@anchor{58b}
@deffn {方法} object.__aiter__ (self)

必须返回一个 @emph{异步迭代器} 对象。
@end deffn

@geindex __anext__() (object 方法)
@anchor{reference/datamodel object __anext__}@anchor{158e}
@deffn {方法} object.__anext__ (self)

必须返回一个 @emph{可迭代对象} 输出迭代器的下一结果值。 当迭代结束时应该引发 @ref{1193,,StopAsyncIteration} 错误。
@end deffn

异步可迭代对象的一个示例:

@example
class Reader:
    async def readline(self):
        ...

    def __aiter__(self):
        return self

    async def __anext__(self):
        val = await self.readline()
        if val == b'@w{'}:
            raise StopAsyncIteration
        return val
@end example


3.5 新版功能.



在 3.7 版更改: 在 Python 3.7 之前，@ref{58b,,__aiter__()} 可以返回一个 @emph{可等待对象} 并将被解析为 @ref{742,,异步迭代器}。

从 Python 3.7 开始，@ref{58b,,__aiter__()} 必须返回一个异步迭代器对象。 返回任何其他对象都将导致 @ref{1ff,,TypeError} 错误。


@node 异步上下文管理器,,异步迭代器,协程
@anchor{reference/datamodel async-context-managers}@anchor{1601}@anchor{reference/datamodel asynchronous-context-managers}@anchor{1602}
@subsubsection 异步上下文管理器


@emph{异步上下文管理器} 是 @emph{上下文管理器} 的一种，它能够在其 @code{__aenter__} 和 @code{__aexit__} 方法中暂停执行。

异步上下文管理器可在 @ref{740,,async with} 语句中使用。

@geindex __aenter__() (object 方法)
@anchor{reference/datamodel object __aenter__}@anchor{10e3}
@deffn {方法} object.__aenter__ (self)

在语义上类似于 @ref{d65,,__enter__()}，仅有的区别是它必须返回一个 @emph{可等待对象}。
@end deffn

@geindex __aexit__() (object 方法)
@anchor{reference/datamodel object __aexit__}@anchor{10e4}
@deffn {方法} object.__aexit__ (self, exc_type, exc_value, traceback)

在语义上类似于 @ref{d66,,__exit__()}，仅有的区别是它必须返回一个 @emph{可等待对象}。
@end deffn

异步上下文管理器类的一个示例:

@example
class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')
@end example


3.5 新版功能.


@node 执行模型,导入系统,数据模型,Python 语言参考手册
@anchor{reference/executionmodel doc}@anchor{1603}@anchor{reference/executionmodel execmodel}@anchor{1604}@anchor{reference/executionmodel execution-model}@anchor{1605}
@section 执行模型


@geindex execution model
@geindex code; block

@menu
* 程序的结构:: 
* 命名与绑定:: 
* 异常: 异常<2>. 

@end menu

@node 程序的结构,命名与绑定,,执行模型
@anchor{reference/executionmodel prog-structure}@anchor{1606}@anchor{reference/executionmodel structure-of-a-program}@anchor{1607}
@subsection 程序的结构


@geindex block

Python 程序是由代码块构成的。 @emph{代码块} 是被作为一个单元来执行的一段 Python 程序文本。 以下几个都属于代码块：模块、函数体和类定义。 交互式输入的每条命令都是代码块。 一个脚本文件（作为标准输入发送给解释器或是作为命令行参数发送给解释器的文件）也是代码块。 一条脚本命令（通过 @ref{136f,,-c} 选项在解释器命令行中指定的命令）也是代码块。 通过在命令行中使用 @ref{44c,,-m} 参数作为最高层级脚本（即 @code{__main__} 模块）运行的模块也是代码块。 传递给内置函数 @ref{c6a,,eval()} 和 @ref{d14,,exec()} 的字符串参数也是代码块。

@geindex execution; frame

代码块在 @emph{执行帧} 中被执行。 一个帧会包含某些管理信息（用于调试）并决定代码块执行完成后应前往何处以及如何继续执行。

@node 命名与绑定,异常<2>,程序的结构,执行模型
@anchor{reference/executionmodel naming}@anchor{1608}@anchor{reference/executionmodel naming-and-binding}@anchor{1609}
@subsection 命名与绑定


@geindex namespace
@geindex scope

@menu
* 名称的绑定:: 
* 名称的解析:: 
* 内置命名空间和受限的执行:: 
* 与动态特性的交互:: 

@end menu

@node 名称的绑定,名称的解析,,命名与绑定
@anchor{reference/executionmodel bind-names}@anchor{160a}@anchor{reference/executionmodel binding-of-names}@anchor{160b}
@subsubsection 名称的绑定


@geindex name
@geindex binding; name

@emph{名称} 用于指代对象。 名称是通过名称绑定操作来引入的。

@geindex from; import statement

以下构造会绑定名称：传给函数的正式形参，@ref{cef,,import} 语句，类与函数定义（这会在定义的代码块中绑定类或函数名称）以及发生以标识符为目标的赋值，@ref{d02,,for} 循环的开头，或 @ref{7e4,,with} 语句和 @ref{c19,,except} 子句的 @code{as} 之后。 @code{import} 语句的 @code{from ... import *} 形式会绑定在被导入模块中定义的所有名称，那些以下划线开头的除外。 这种形式仅在模块层级上被使用。

@ref{13d1,,del} 语句的目标也被视作一种绑定（虽然其实际语义为解除名称绑定）。

每条赋值或导入语句均发生于类或函数内部定义的代码块中，或是发生于模块层级（即最高层级的代码块）。

@geindex free; variable

如果名称绑定在一个代码块中，则为该代码块的局部变量，除非声明为 @ref{d0f,,nonlocal} 或 @ref{13a7,,global}。 如果名称绑定在模块层级，则为全局变量。 (模块代码块的变量既为局部变量又为全局变量。) 如果变量在一个代码块中被使用但不是在其中定义，则为 @emph{自由变量}。

每个在程序文本中出现的名称是指由以下名称解析规则所建立的对该名称的 @emph{绑定}。

@node 名称的解析,内置命名空间和受限的执行,名称的绑定,命名与绑定
@anchor{reference/executionmodel resolution-of-names}@anchor{160c}@anchor{reference/executionmodel resolve-names}@anchor{160d}
@subsubsection 名称的解析


@geindex scope

@emph{作用域} 定义了一个代码块中名称的可见性。 如果代码块中定义了一个局部变量，则其作用域包含该代码块。 如果定义发生于函数代码块中，则其作用域会扩展到该函数所包含的任何代码块，除非有某个被包含代码块引入了对该名称的不同绑定。

@geindex environment

当一个名称在代码块中被使用时，会由包含它的最近作用域来解析。 对一个代码块可见的所有这种作用域的集合称为该代码块的 @emph{环境}。

@geindex NameError (built-in exception)
@geindex UnboundLocalError

当一个名称完全找不到时，将会引发 @ref{e48,,NameError} 异常。 如果当前作用域为函数作用域，且该名称指向一个局部变量，而此变量在该名称被使用的时候尚未绑定到特定值，将会引发 @ref{f3e,,UnboundLocalError} 异常。 @ref{f3e,,UnboundLocalError} 为 @ref{e48,,NameError} 的一个子类。

如果一个代码块内的任何位置发生名称绑定操作，则代码块内所有对该名称的使用会被认为是对当前代码块的引用。 当一个名称在其被绑定前就在代码块内被使用时则会导致错误。 这个一个很微妙的规则。 Python 缺少声明语法，并允许名称绑定操作发生于代码块内的任何位置。 一个代码块的局部变量可通过在整个代码块文本中扫描名称绑定操作来确定。

如果 @ref{13a7,,global} 语句出现在一个代码块中，则所有对该语句所指定名称的使用都是在最高层级命名空间内对该名称绑定的引用。 名称在最高层级命名内的解析是通过全局命名空间，也就是包含该代码块的模块的命名空间，以及内置命名空间即 @ref{12,,builtins} 模块的命名空间。 全局命名空间会先被搜索。 如果未在其中找到指定名称，再搜索内置命名空间。  @code{global} 语句必须位于所有对其所列出名称的使用之前。

@ref{13a7,,global} 语句与同一代码块中名称绑定具有相同的作用域。 如果一个自由变量的最近包含作用域中有一条 global 语句，则该自由变量也会被当作是全局变量。

@c XXX say more about "nonlocal" semantics here

@ref{d0f,,nonlocal} 语句会使得相应的名称指向之前在最近包含函数作用域中绑定的变量。 如果指定名称不存在于任何包含函数作用域中则将在编译时引发 @ref{562,,SyntaxError}。

@geindex 模块; __main__

模块的作用域会在模块第一次被导入时自动创建。 一个脚本的主模块总是被命名为 @ref{1,,__main__}。

类定义代码块以及传给 @ref{d14,,exec()} 和 @ref{c6a,,eval()} 的参数是名称解析上下文中的特殊情况。 类定义是可能使用并定义名称的可执行语句。 这些引用遵循正常的名称解析规则，例外之处在于未绑定的局部变量将会在全局命名空间中查找。 类定义的命名空间会成为该类的属性字典。 在类代码块中定义的名称的作用域会被限制在类代码块中；它不会扩展到方法的代码块中 -- 这也包括推导式和生成器表达式，因为它们都是使用函数作用域实现的。 这意味着以下代码将会失败:

@example
class A:
    a = 42
    b = list(a + i for i in range(10))
@end example

@node 内置命名空间和受限的执行,与动态特性的交互,名称的解析,命名与绑定
@anchor{reference/executionmodel builtins-and-restricted-execution}@anchor{160e}@anchor{reference/executionmodel restrict-exec}@anchor{160f}
@subsubsection 内置命名空间和受限的执行


@geindex restricted; execution

@strong{CPython implementation detail:} 用户不应该接触 @code{__builtins__}，严格说来它属于实现细节。 用户如果要重载内置命名空间中的值则应该 @ref{cef,,import} @ref{12,,builtins} 并相应地修改该模块中的属性。

与一个代码块的执行相关联的内置命名空间实际上是通过在其全局命名空间中搜索名称 @code{__builtins__} 来找到的；这应该是一个字典或一个模块（在后一种情况下会使用该模块的字典）。 默认情况下，当在 @ref{1,,__main__} 模块中时，@code{__builtins__} 就是内置模块 @ref{12,,builtins}；当在任何其他模块中时，@code{__builtins__} 则是 @ref{12,,builtins} 模块自身的字典的一个别名。

@node 与动态特性的交互,,内置命名空间和受限的执行,命名与绑定
@anchor{reference/executionmodel dynamic-features}@anchor{1610}@anchor{reference/executionmodel interaction-with-dynamic-features}@anchor{1611}
@subsubsection 与动态特性的交互


自由变量的名称解析发生于运行时而不是编译时。 这意味着以下代码将打印出 42:

@example
i = 10
def f():
    print(i)
i = 42
f()
@end example

@c XXX from * also invalid with relative imports (at least currently)

@ref{c6a,,eval()} 和 @ref{d14,,exec()} 函数没有对完整环境的访问权限来解析名称。 名称可以在调用者的局部和全局命名空间中被解析。 自由变量的解析不是在最近包含命名空间中，而是在全局命名空间中。 @footnote{@w{(1)} 
出现这样的限制是由于通过这些操作执行的代码在模块被编译的时候并不可用。
} @ref{d14,,exec()} 和 @ref{c6a,,eval()} 函数有可选参数用来重载全局和局部命名空间。 如果只指定一个命名空间，则它会同时作用于两者。

@node 异常<2>,,命名与绑定,执行模型
@anchor{reference/executionmodel exceptions}@anchor{1612}@anchor{reference/executionmodel id2}@anchor{1613}
@subsection 异常


@geindex exception

@geindex raise an exception
@geindex handle an exception
@geindex exception handler
@geindex errors
@geindex error handling

异常是中断代码块的正常控制流程以便处理错误或其他异常条件的一种方式。 异常会在错误被检测到的位置 @emph{引发}，它可以被当前包围代码块或是任何直接或间接发起调用发生错误的代码块的其他代码块所 @emph{处理}。

Python 解析器会在检测到运行时错误（例如零作为被除数）的时候引发异常。 Python 程序也可以通过 @ref{d12,,raise} 语句显式地引发异常。 异常处理是通过 @ref{e3f,,try} ... @ref{c19,,except} 语句来指定的。 该语句的 @ref{2c3,,finally} 子句可被用来指定清理代码，它并不处理异常，而是无论之前的代码是否发生异常都会被执行。

@geindex termination model

Python 的错误处理采用的是“终止”模型：异常处理器可以找出发生了什么问题，并在外层继续执行，但它不能修复错误的根源并重试失败的操作（除非通过从顶层重新进入出错的代码片段）。

@geindex SystemExit (built-in exception)

当一个异常完全未被处理时，解释器会终止程序的执行，或者返回交互模式的主循环。 无论是哪种情况，它都会打印栈回溯信息，除非是当异常为 @ref{6fd,,SystemExit} 的时候。

异常是通过类实例来标识的。 @ref{c19,,except} 子句会依据实例的类来选择：它必须引用实例的类或是其所属的 @ref{c0e,,非虚基类} 。 实例可通过处理器被接收，并可携带有关异常条件的附加信息。

@cartouche
@quotation 注解 
异常消息不是 Python API 的组成部分。 其内容可能在 Python 升级到新版本时不经警告地发生改变，不应该被需要在多版本解释器中运行的代码所依赖。
@end quotation
@end cartouche

另请参看  @ref{e3f,,try 语句} 小节中对 @ref{e3f,,try} 语句的描述以及 @ref{d12,,raise 语句} 小节中对 @ref{d12,,raise} 语句的描述。

@node 导入系统,表达式,执行模型,Python 语言参考手册
@anchor{reference/import doc}@anchor{1614}@anchor{reference/import importsystem}@anchor{1590}@anchor{reference/import the-import-system}@anchor{1615}
@section 导入系统


@geindex import machinery

一个 @ref{1616,,module} 内的 Python 代码通过 @ref{1617,,importing} 操作就能够访问另一个模块内的代码。 @ref{cef,,import} 语句是发起调用导入机制的最常用方式，但不是唯一的方式。 @ref{bef,,importlib.import_module()} 以及内置的 @ref{16b,,__import__()} 等函数也可以被用来发起调用导入机制。

@ref{cef,,import} 语句结合了两个操作；它先搜索指定名称的模块，然后将搜索结果绑定到当前作用域中的名称。 @code{import} 语句的搜索操作定义为对 @ref{16b,,__import__()} 函数的调用并带有适当的参数。 @ref{16b,,__import__()} 的返回值会被用于执行 @code{import} 语句的名称绑定操作。 请参阅 @code{import} 语句了解名称绑定操作的更多细节。

对 @ref{16b,,__import__()} 的直接调用将仅执行模块搜索以及在找到时的模块创建操作。 不过也可能产生某些副作用，例如导入父包和更新各种缓存 (包括 @ref{109a,,sys.modules})，只有 @ref{cef,,import} 语句会执行名称绑定操作。

当 @ref{cef,,import} 语句被执行时，标准的内置 @ref{16b,,__import__()} 函数会被调用。 其他发起调用导入系统的机制 (例如 @ref{bef,,importlib.import_module()}) 可能会选择绕过 @ref{16b,,__import__()} 并使用它们自己的解决方案来实现导入机制。

当一个模块首次被导入时，Python 会搜索该模块，如果找到就创建一个 module 对象 @footnote{@w{(1)} 
参见 @ref{7ec,,types.ModuleType}。
} 并初始化它。 如果指定名称的模块未找到，则会引发 @ref{4a9,,ModuleNotFoundError}。 当发起调用导入机制时，Python 会实现多种策略来搜索指定名称的模块。 这些策略可以通过使用使用下文所描述的多种钩子来加以修改和扩展。


在 3.3 版更改: 导入系统已被更新以完全实现 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 中的第二阶段要求。 不会再有任何隐式的导入机制 —— 整个导入系统都通过 @ref{6e7,,sys.meta_path} 暴露出来。 此外，对原生命名空间包的支持也已被实现 (参见 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420})。


@menu
* importlib: importlib<8>. 
* 包: 包<2>. 
* 搜索:: 
* 加载:: 
* 基于路径的查找器:: 
* 替换标准导入系统:: 
* 包相对导入:: 
* 有关 __main__ 的特殊事项:: 
* 开放问题项:: 
* 参考文献:: 

@end menu

@node importlib<8>,包<2>,,导入系统
@anchor{reference/import importlib}@anchor{1618}
@subsection @code{importlib}


@ref{9a,,importlib} 模块提供了一个丰富的 API 用来与导入系统进行交互。 例如 @ref{bef,,importlib.import_module()} 提供了相比内置的 @ref{16b,,__import__()} 更推荐、更简单的 API 用来发起调用导入机制。 更多细节请参看 @ref{9a,,importlib} 库文档。

@node 包<2>,搜索,importlib<8>,导入系统
@anchor{reference/import packages}@anchor{1619}
@subsection 包


@geindex package

Python 只有一种模块对象类型，所有模块都属于该类型，无论模块是用 Python、C 还是别的语言实现。 为了帮助组织模块并提供名称层次结构，Python 还引入了 @ref{161a,,包} 的概念。

你可以把包看成是文件系统中的目录，并把模块看成是目录中的文件，但请不要对这个类似做过于字面的理解，因为包和模块不是必须来自于文件系统。 为了方便理解本文档，我们将继续使用这种目录和文件的类比。 与文件系统一样，包通过层次结构进行组织，在包之内除了一般的模块，还可以有子包。

要注意的一个重点概念是所有包都是模块，但并非所有模块都是包。 或者换句话说，包只是一种特殊的模块。 特别地，任何具有 @code{__path__} 属性的模块都会被当作是包。

所有模块都有自己的名字。 子包名与其父包名会以点号分隔，与 Python 的标准属性访问语法一致。 因此你可能会有一个名为 @ref{67,,email} 的包，这个包中又有一个名为 @ref{71,,email.mime} 的子包以及该子包中的名为 @code{email.mime.text} 的子包。

@menu
* 常规包:: 
* 命名空间包:: 

@end menu

@node 常规包,命名空间包,,包<2>
@anchor{reference/import regular-packages}@anchor{161b}
@subsubsection 常规包


@geindex package; regular

Python 定义了两种类型的包，@ref{161c,,常规包} 和 @ref{161d,,命名空间包}。 常规包是传统的包类型，它们在 Python 3.2 及之前就已存在。 常规包通常以一个包含 @code{__init__.py} 文件的目录形式实现。 当一个常规包被导入时，这个 @code{__init__.py} 文件会隐式地被执行，它所定义的对象会被绑定到该包命名空间中的名称。@code{__init__.py} 文件可以包含与任何其他模块中所包含的 Python 代码相似的代码，Python 将在模块被导入时为其添加额外的属性。

例如，以下文件系统布局定义了一个最高层级的 @code{parent} 包和三个子包:

@example
parent/
    __init__.py
    one/
        __init__.py
    two/
        __init__.py
    three/
        __init__.py
@end example

导入 @code{parent.one} 将隐式地执行 @code{parent/__init__.py} 和 @code{parent/one/__init__.py}。 后续导入 @code{parent.two} 或 @code{parent.three} 则将分别执行 @code{parent/two/__init__.py} 和 @code{parent/three/__init__.py}。

@node 命名空间包,,常规包,包<2>
@anchor{reference/import namespace-packages}@anchor{161e}
@subsubsection 命名空间包


@geindex package; namespace
@geindex package; portion

命名空间包是由多个 @ref{161f,,部分} 构成的，每个部分为父包增加一个子包。 各个部分可能处于文件系统的不同位置。 部分也可能处于 zip 文件中、网络上，或者 Python 在导入期间可以搜索的其他地方。 命名空间包并不一定会直接对应到文件系统中的对象；它们有可能是无实体表示的虚拟模块。

命名空间包的 @code{__path__} 属性不使用普通的列表。 而是使用定制的可迭代类型，如果其父包的路径 (或者最高层级包的 @ref{262,,sys.path}) 发生改变，这种对象会在该包内的下一次导入尝试时自动执行新的对包部分的搜索。

命名空间包没有 @code{parent/__init__.py} 文件。 实际上，在导入搜索期间可能找到多个 @code{parent} 目录，每个都由不同的部分所提供。 因此 @code{parent/one} 的物理位置不一定与 @code{parent/two} 相邻。 在这种情况下，Python 将为顶级的 @code{parent} 包创建一个命名空间包，无论是它本身还是它的某个子包被导入。

另请参阅 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 了解对命名空间包的规格描述。

@node 搜索,加载,包<2>,导入系统
@anchor{reference/import searching}@anchor{1620}
@subsection 搜索


为了开始搜索，Python 需要被导入模块（或者包，对于当前讨论来说两者没有差别）的完整 @ref{158b,,限定名称}。 此名称可以来自 @ref{cef,,import} 语句所带的各种参数，或者来自传给 @ref{bef,,importlib.import_module()} 或 @ref{16b,,__import__()} 函数的形参。

此名称会在导入搜索的各个阶段被使用，它也可以是指向一个子模块的带点号路径，例如 @code{foo.bar.baz}。 在这种情况下，Python 会先尝试导入 @code{foo}，然后是 @code{foo.bar}，最后是 @code{foo.bar.baz}。 如果这些导入中的任何一个失败，都会引发 @ref{4a9,,ModuleNotFoundError}。

@menu
* 模块缓存:: 
* 查找器和加载器:: 
* 导入钩子:: 
* 元路径:: 

@end menu

@node 模块缓存,查找器和加载器,,搜索
@anchor{reference/import the-module-cache}@anchor{1621}
@subsubsection 模块缓存


@geindex sys.modules

在导入搜索期间首先会被检查的地方是 @ref{109a,,sys.modules}。 这个映射起到缓存之前导入的所有模块的作用（包括其中间路径）。 因此如果之前导入过 @code{foo.bar.baz}，则 @ref{109a,,sys.modules} 将包含 @code{foo}, @code{foo.bar} 和 @code{foo.bar.baz} 条目。 每个键的值就是相应的模块对象。

在导入期间，会在 @ref{109a,,sys.modules} 查找模块名称，如存在则其关联的值就是需要导入的模块，导入过程完成。 然而，如果值为 @code{None}，则会引发 @ref{4a9,,ModuleNotFoundError}。 如果找不到指定模块名称，Python 将继续搜索该模块。

@ref{109a,,sys.modules} 是可写的。删除键可能不会破坏关联的模块（因为其他模块可能会保留对它的引用），但它会使命名模块的缓存条目无效，导致 Python 在下次导入时重新搜索命名模块。键也可以赋值为 @code{None} ，强制下一次导入模块导致 @ref{4a9,,ModuleNotFoundError} 。

但是要小心，因为如果你还保有对某个模块对象的引用，同时停用其在 @ref{109a,,sys.modules} 中的缓存条目，然后又再次导入该名称的模块，则前后两个模块对象将 @emph{不是} 同一个。 相反地，@ref{4a8,,importlib.reload()} 将重用 @emph{同一个} 模块对象，并简单地通过重新运行模块的代码来重新初始化模块内容。

@node 查找器和加载器,导入钩子,模块缓存,搜索
@anchor{reference/import finders-and-loaders}@anchor{1622}@anchor{reference/import id2}@anchor{1623}
@subsubsection 查找器和加载器


@geindex finder
@geindex loader
@geindex module spec

如果指定名称的模块在 @ref{109a,,sys.modules} 找不到，则将发起调用 Python 的导入协议以查找和加载该模块。 此协议由两个概念性模块构成，即 @ref{1624,,查找器} 和 @ref{1625,,加载器}。 查找器的任务是确定是否能使用其所知的策略找到该名称的模块。 同时实现这两种接口的对象称为 @ref{1626,,导入器} —— 它们在确定能加载所需的模块时会返回其自身。

Python 包含了多个默认查找器和导入器。 第一个知道如何定位内置模块，第二个知道如何定位冻结模块。 第三个默认查找器会在 @ref{1627,,import path} 中搜索模块。 @ref{1627,,import path} 是一个由文件系统路径或 zip 文件组成的位置列表。 它还可以扩展为搜索任意可定位资源，例如由 URL 指定的资源。

导入机制是可扩展的，因此可以加入新的查找器以扩展模块搜索的范围和作用域。

查找器并不真正加载模块。 如果它们能找到指定名称的模块，会返回一个 @emph{模块规格说明}，这是对模块导入相关信息的封装，供后续导入机制用于在加载模块时使用。

以下各节描述了有关查找器和加载器协议的更多细节，包括你应该如何创建并注册新的此类对象来扩展导入机制。


在 3.4 版更改: 在之前的 Python 版本中，查找器会直接返回 @ref{1625,,加载器}，现在它们则返回模块规格说明，其中 @emph{包含} 加载器。 加载器仍然在导入期间被使用，但负担的任务有所减少。


@node 导入钩子,元路径,查找器和加载器,搜索
@anchor{reference/import import-hooks}@anchor{1628}
@subsubsection 导入钩子


@geindex import hooks
@geindex meta hooks
@geindex path hooks
@geindex hooks; import
@geindex hooks; meta
@geindex hooks; path

导入机制被设计为可扩展；其中的基本机制是 @emph{导入钩子}。 导入钩子有两种类型: @emph{元钩子} 和 @emph{导入路径钩子}。

元钩子在导入过程开始时被调用，此时任何其他导入过程尚未发生，但 @ref{109a,,sys.modules} 缓存查找除外。 这允许元钩子重载 @ref{262,,sys.path} 过程、冻结模块甚至内置模块。 元钩子的注册是通过向 @ref{6e7,,sys.meta_path} 添加新的查找器对象，具体如下所述。

导入路径钩子是作为 @ref{262,,sys.path} (或 @code{package.__path__}) 过程的一部分，在遇到它们所关联的路径项的时候被调用。 导入路径钩子的注册是通过向 @ref{a46,,sys.path_hooks} 添加新的可调用对象，具体如下所述。

@node 元路径,,导入钩子,搜索
@anchor{reference/import the-meta-path}@anchor{1629}
@subsubsection 元路径


@geindex sys.meta_path
@geindex finder; find_spec

当指定名称的模块在 @ref{109a,,sys.modules} 中找不到时，Python 会接着搜索 @ref{6e7,,sys.meta_path}，其中包含元路径查找器对象列表。 这些查找器按顺序被查询以确定它们是否知道如何处理该名称的模块。 元路径查找器必须实现名为 @ref{56d,,find_spec()} 的方法，该方法接受三个参数：名称、导入路径和目标模块（可选）。 元路径查找器可使用任何策略来确定它是否能处理指定名称的模块。

如果元路径查找器知道如何处理指定名称的模块，它将返回一个说明对象。 如果它不能处理该名称的模块，则会返回 @code{None}。 如果 @ref{6e7,,sys.meta_path} 处理过程到达列表末尾仍未返回说明对象，则将引发 @ref{4a9,,ModuleNotFoundError}。 任何其他被引发异常将直接向上传播，并放弃导入过程。

元路径查找器的 @ref{56d,,find_spec()} 方法调用带有两到三个参数。 第一个是被导入模块的完整限定名称，例如 @code{foo.bar.baz}。 第二个参数是供模块搜索使用的路径条目。 对于最高层级模块，第二个参数为 @code{None}，但对于子模块或子包，第二个参数为父包 @code{__path__} 属性的值。 如果相应的 @code{__path__} 属性无法访问，将引发 @ref{4a9,,ModuleNotFoundError}。 第三个参数是一个将被作为稍后加载目标的现有模块对象。 导入系统仅会在重加载期间传入一个目标模块。

对于单个导入请求可以多次遍历元路径。 例如，假设所涉及的模块都尚未被缓存，则导入 @code{foo.bar.baz} 将首先执行顶级的导入，在每个元路径查找器 (@code{mpf}) 上调用 @code{mpf.find_spec("foo", None, None)}。 在导入 @code{foo} 之后，@code{foo.bar} 将通过第二次遍历元路径来导入，调用 @code{mpf.find_spec("foo.bar", foo.__path__, None)}。 一旦 @code{foo.bar} 完成导入，最后一次遍历将调用 @code{mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)}。

有些元路径查找器只支持顶级导入。 当把 @code{None} 以外的对象作为第三个参数传入时，这些导入器将总是返回 @code{None}。

Python 的默认 @ref{6e7,,sys.meta_path} 具有三种元路径查找器，一种知道如何导入内置模块，一种知道如何导入冻结模块，还有一种知道如何导入来自 @ref{1627,,import path} 的模块 (即 @ref{162a,,path based finder})。


在 3.4 版更改: 元路径查找器的 @ref{56d,,find_spec()} 方法替代了 @ref{56c,,find_module()}，后者现已弃用，它将继续可用但不会再做改变，导入机制仅会在查找器未实现 @code{find_spec()} 时尝试使用它。


@node 加载,基于路径的查找器,搜索,导入系统
@anchor{reference/import loading}@anchor{162b}
@subsection 加载


当一个模块说明被找到时，导入机制将在加载该模块时使用它（及其所包含的加载器）。 下面是导入的加载部分所发生过程的简要说明:

@example
module = None
if spec.loader is not None and hasattr(spec.loader, 'create_module'):
    # It is assumed 'exec_module' will also be defined on the loader.
    module = spec.loader.create_module(spec)
if module is None:
    module = ModuleType(spec.name)
# The import-related module attributes get set here:
_init_module_attrs(spec, module)

if spec.loader is None:
    # unsupported
    raise ImportError
if spec.origin is None and spec.submodule_search_locations is not None:
    # namespace package
    sys.modules[spec.name] = module
elif not hasattr(spec.loader, 'exec_module'):
    module = spec.loader.load_module(spec.name)
    # Set __loader__ and __package__ if missing.
else:
    sys.modules[spec.name] = module
    try:
        spec.loader.exec_module(module)
    except BaseException:
        try:
            del sys.modules[spec.name]
        except KeyError:
            pass
        raise
return sys.modules[spec.name]
@end example

请注意以下细节:

@quotation


@itemize *

@item 
如果在 @ref{109a,,sys.modules} 中存在指定名称的模块对象，导入操作会已经将其返回。

@item 
在加载器执行模块代码之前，该模块将存在于 @ref{109a,,sys.modules} 中。 这一点很关键，因为该模块代码可能（直接或间接地）导入其自身；预先将其添加到 @ref{109a,,sys.modules} 可防止在最坏情况下的无限递归和最好情况下的多次加载。

@item 
如果加载失败，则该模块 -- 只限加载失败的模块 -- 将从 @ref{109a,,sys.modules} 中移除。 任何已存在于 @ref{109a,,sys.modules} 缓存的模块，以及任何作为附带影响被成功加载的模块仍会保留在缓存中。 这与重新加载不同，后者会把即使加载失败的模块也保留在 @ref{109a,,sys.modules} 中。

@item 
在模块创建完成但还未执行之前，导入机制会设置导入相关模块属性（在上面的示例伪代码中为 “_init_module_attrs”），详情参见 @ref{162c,,后续部分}。

@item 
模块执行是加载的关键时刻，在此期间将填充模块的命名空间。 执行会完全委托给加载器，由加载器决定要填充的内容和方式。

@item 
在加载过程中创建并传递给 exec_module() 的模块并不一定就是在导入结束时返回的模块 @footnote{@w{(2)} 
importlib 实现避免直接使用返回值。 而是通过在 @ref{109a,,sys.modules} 中查找模块名称来获取模块对象。 这种方式的间接影响是被导入的模块可能在 @ref{109a,,sys.modules} 中替换其自身。 这属于具体实现的特定行为，不保证能在其他 Python 实现中起作用。
}。
@end itemize
@end quotation


在 3.4 版更改: 导入系统已经接管了加载器建立样板的责任。 这些在以前是由 @ref{6e4,,importlib.abc.Loader.load_module()} 方法来执行的。


@menu
* 加载器:: 
* 子模块:: 
* 模块规格说明:: 
* 导入相关的模块属性:: 
* module.__path__: module __path__. 
* 模块的 repr:: 
* 已缓存字节码的失效:: 

@end menu

@node 加载器,子模块,,加载
@anchor{reference/import loaders}@anchor{162d}
@subsubsection 加载器


模块加载器提供关键的加载功能：模块执行。 导入机制调用 @ref{6e5,,importlib.abc.Loader.exec_module()} 方法并传入一个参数来执行模块对象。 从 @ref{6e5,,exec_module()} 返回的任何值都将被忽略。

加载器必须满足下列要求:

@quotation


@itemize *

@item 
如果模块是一个 Python 模块（而非内置模块或动态加载的扩展），加载器应该在模块的全局命名空间 (@code{module.__dict__}) 中执行模块的代码。

@item 
如果加载器无法执行指定模块，它应该引发 @ref{16c,,ImportError}，不过在 @ref{6e5,,exec_module()} 期间引发的任何其他异常也会被传播。
@end itemize
@end quotation

在许多情况下，查找器和加载器可以是同一对象；在此情况下 @ref{56d,,find_spec()} 方法将返回一个规格说明，其中加载器会被设为 @code{self}。

模块加载器可以选择通过实现 @ref{657,,create_module()} 方法在加载期间创建模块对象。 它接受一个参数，即模块规格说明，并返回新的模块对象供加载期间使用。 @code{create_module()} 不需要在模块对象上设置任何属性。 如果模块返回 @code{None}，导入机制将自行创建新模块。


3.4 新版功能: 加载器的 @ref{657,,create_module()} 方法。



在 3.4 版更改: @ref{6e4,,load_module()} 方法被 @ref{6e5,,exec_module()} 所替代，导入机制会对加载的所有样板责任作出假定。

为了与现有的加载器兼容，导入机制会使用导入器的 @code{load_module()} 方法，如果它存在且导入器也未实现 @code{exec_module()}。 但是，@code{load_module()} 现已弃用，加载器应该转而实现 @code{exec_module()}。

除了执行模块之外，@code{load_module()} 方法必须实现上文描述的所有样板加载功能。 所有相同的限制仍然适用，并带有一些附加规定:

@quotation


@itemize *

@item 
如果 @ref{109a,,sys.modules} 中存在指定名称的模块对象，加载器必须使用已存在的模块。 （否则 @ref{4a8,,importlib.reload()} 将无法正确工作。） 如果该名称模块不存在于 @ref{109a,,sys.modules} 中，加载器必须创建一个新的模块对象并将其加入 @ref{109a,,sys.modules}。

@item 
在加载器执行模块代码之前，模块 @emph{必须} 存在于 @ref{109a,,sys.modules} 之中，以防止无限递归或多次加载。

@item 
如果加载失败，加载器必须移除任何它已加入到 @ref{109a,,sys.modules} 中的模块，但它必须 @strong{仅限} 移除加载失败的模块，且所移除的模块应为加载器自身显式加载的。
@end itemize
@end quotation



在 3.5 版更改: 当 @code{exec_module()} 已定义但 @code{create_module()} 未定义时将引发 @ref{15a,,DeprecationWarning}。



在 3.6 版更改: 当 @code{exec_module()} 已定义但 @code{create_module()} 未定义时将引发 @ref{16c,,ImportError}。


@node 子模块,模块规格说明,加载器,加载
@anchor{reference/import submodules}@anchor{162e}
@subsubsection 子模块


当使用任意机制 (例如 @code{importlib} API, @code{import} 及 @code{import-from} 语句或者内置的 @code{__import__()}) 加载一个子模块时，父模块的命名空间中会添加一个对子模块对象的绑定。 例如，如果包 @code{spam} 有一个子模块 @code{foo}，则在导入 @code{spam.foo} 之后，@code{spam} 将具有一个 绑定到相应子模块的 @code{foo} 属性。 假如现在有如下的目录结构:

@example
spam/
    __init__.py
    foo.py
@end example

并且 @code{spam/__init__.py} 中有如下几行内容:

@example
from .foo import Foo
@end example

那么执行如下代码将把 @code{foo} 和 @code{Foo} 的名称绑定添加到 @code{spam} 模块中:

@example
>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
>>> spam.Foo
<class 'spam.foo.Foo'>
@end example

按照通常的 Python 名称绑定规则，这看起来可能会令人惊讶，但它实际上是导入系统的一个基本特性。 保持不变的一点是如果你有 @code{sys.modules['spam']} 和 @code{sys.modules['spam.foo']} (例如在上述导入之后就是如此)，则后者必须显示为前者的 @code{foo} 属性。

@node 模块规格说明,导入相关的模块属性,子模块,加载
@anchor{reference/import module-spec}@anchor{162f}
@subsubsection 模块规格说明


导入机制在导入期间会使用有关每个模块的多种信息，特别是加载之前。 大多数信息都是所有模块通用的。 模块规格说明的目的是基于每个模块来封装这些导入相关信息。

在导入期间使用规格说明可允许状态在导入系统各组件之间传递，例如在创建模块规格说明的查找器和执行模块的加载器之间。 最重要的一点是，它允许导入机制执行加载的样板操作，在没有模块规格说明的情况下这是加载器的责任。

模块的规格说明会作为模块对象的 @code{__spec__} 属性对外公开。 有关模块规格的详细内容请参阅 @ref{1630,,ModuleSpec}。


3.4 新版功能.


@node 导入相关的模块属性,module __path__,模块规格说明,加载
@anchor{reference/import import-mod-attrs}@anchor{162c}@anchor{reference/import import-related-module-attributes}@anchor{1631}
@subsubsection 导入相关的模块属性


导入机制会在加载期间会根据模块的规格说明填充每个模块对象的这些属性，并在加载器执行模块之前完成。

@geindex __name__
@anchor{reference/import __name__}@anchor{de0}
@deffn {属性} __name__

@code{__name__} 属性必须被设为模块的完整限定名称。 此名称被用来在导入系统中唯一地标识模块。
@end deffn

@geindex __loader__
@anchor{reference/import __loader__}@anchor{a40}
@deffn {属性} __loader__

@code{__loader__} 属性必须被设为导入系统在加载模块时使用的加载器对象。 这主要是用于内省，但也可用于额外的加载器专用功能，例如获取关联到加载器的数据。
@end deffn

@geindex __package__
@anchor{reference/import __package__}@anchor{a3f}
@deffn {属性} __package__

模块的 @code{__package__} 属性必须设定。 其取值必须为一个字符串，但可以与 @code{__name__} 取相同的值。 当模块是包时，其 @code{__package__} 值应该设为其 @code{__name__} 值。 当模块不是包时，对于最高层级模块 @code{__package__} 应该设为空字符串，对于子模块则应该设为其父包名。 更多详情可参阅 
@geindex Python 提高建议; PEP 366
PEP 366@footnote{https://www.python.org/dev/peps/pep-0366}。

该属性取代 @code{__name__} 被用来为主模块计算显式相对导入，相关定义见 
@geindex Python 提高建议; PEP 366
PEP 366@footnote{https://www.python.org/dev/peps/pep-0366}。 预期它与 @code{__spec__.parent} 具有相同的值。


在 3.6 版更改: @code{__package__} 预期与 @code{__spec__.parent} 具有相同的值。

@end deffn

@geindex __spec__
@anchor{reference/import __spec__}@anchor{1632}
@deffn {属性} __spec__

@code{__spec__} 属性必须设为在导入模块时要使用的模块规格说明。 对 @code{__spec__} 的正确设定将同时作用于 @ref{1633,,解释器启动期间初始化的模块}。 唯一的例外是 @code{__main__}，其中的 @code{__spec__} 会 @ref{1634,,在某些情况下设为 None}.

当 @code{__package__} 未定义时， @code{__spec__.parent} 会被用作回退项。


3.4 新版功能.



在 3.6 版更改: 当 @code{__package__} 未定义时，@code{__spec__.parent} 会被用作回退项。

@end deffn

@geindex __path__
@anchor{reference/import __path__}@anchor{13f3}
@deffn {属性} __path__

如果模块为包（不论是正规包还是命名空间包），则必须设置模块对象的 @code{__path__} 属性。 属性值必须为可迭代对象，但如果 @code{__path__} 没有进一步的用处则可以为空。 如果 @code{__path__} 不为空，则在迭代时它应该产生字符串。 有关 @code{__path__} 语义的更多细节将在 @ref{1635,,下文} 中给出。

不是包的模块不应该具有 @code{__path__} 属性。
@end deffn

@geindex __file__
@anchor{reference/import __file__}@anchor{1591}
@deffn {属性} __file__
@end deffn

@geindex __cached__
@anchor{reference/import __cached__}@anchor{c0d}
@deffn {属性} __cached__

@code{__file__} 是可选项。 如果设置，此属性的值必须为字符串。 导入系统可以选择在其没有语法意义时不设置 @code{__file__} (例如从数据库加载的模块)。

如果设置了 @code{__file__}，则也可以再设置 @code{__cached__} 属性，后者取值为编译版本代码（例如字节码文件）所在的路径。 设置此属性不要求文件已存在；该路径可以简单地指向应该存放编译文件的位置 (参见 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147})。

当未设置 @code{__file__} 时也可以设置 @code{__cached__}。 但是，那样的场景很不典型。 最终，加载器会使用 @code{__file__} 和/或 @code{__cached__}。 因此如果一个加载器可以从缓存加载模块但是不能从文件加载，那种非典型场景就是适当的。
@end deffn

@node module __path__,模块的 repr,导入相关的模块属性,加载
@anchor{reference/import module-path}@anchor{1636}@anchor{reference/import package-path-rules}@anchor{1635}
@subsubsection module.__path__


根据定义，如果一个模块具有 @code{__path__} 属性，它就是包。

包的 @code{__path__} 属性会在导入其子包期间被使用。 在导入机制内部，它的功能与 @ref{262,,sys.path} 基本相同，即在导入期间提供一个模块搜索位置列表。 但是，@code{__path__} 通常会比 @ref{262,,sys.path} 受到更多限制。

@code{__path__} 必须是由字符串组成的可迭代对象，但它也可以为空。 作用于 @ref{262,,sys.path} 的规则同样适用于包的 @code{__path__}，并且 @ref{a46,,sys.path_hooks} (见下文) 会在遍历包的 @code{__path__} 时被查询。

包的 @code{__init__.py} 文件可以设置或更改包的 @code{__path__} 属性，而且这是在 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 之前实现命名空间包的典型方式。 随着 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 的引入，命名空间包不再需要提供仅包含 @code{__path__} 操控代码的 @code{__init__.py} 文件；导入机制会自动为命名空间包正确地设置 @code{__path__}。

@node 模块的 repr,已缓存字节码的失效,module __path__,加载
@anchor{reference/import module-reprs}@anchor{1637}
@subsubsection 模块的 repr


默认情况下，全部模块都具有一个可用的 repr，但是你可以依据上述的属性设置，在模块的规格说明中更为显式地控制模块对象的 repr。

如果模块具有 spec (@code{__spec__})，导入机制将尝试用它来生成一个 repr。 如果生成失败或找不到 spec，导入系统将使用模块中的各种可用信息来制作一个默认 repr。 它将尝试使用 @code{module.__name__}, @code{module.__file__} 以及 @code{module.__loader__} 作为 repr 的输入，并将任何丢失的信息赋为默认值。

以下是所使用的确切规则:

@quotation


@itemize *

@item 
如果模块具有 @code{__spec__} 属性，其中的规格信息会被用来生成 repr。 被查询的属性有 "name", "loader", "origin" 和 "has_location" 等等。

@item 
如果模块具有 @code{__file__} 属性，这会被用作模块 repr 的一部分。

@item 
如果模块没有 @code{__file__} 但是有 @code{__loader__} 且取值不为 @code{None}，则加载器的 repr 会被用作模块 repr 的一部分。

@item 
对于其他情况，仅在 repr 中使用模块的 @code{__name__}。
@end itemize
@end quotation


在 3.4 版更改: @ref{a2e,,loader.module_repr()} 已弃用，导入机制现在使用模块规格说明来生成模块 repr。

为了向后兼容 Python 3.3，如果加载器定义了 @ref{a2e,,module_repr()} 方法，则会在尝试上述两种方式之前先调用该方法来生成模块 repr。 但请注意此方法已弃用。


@node 已缓存字节码的失效,,模块的 repr,加载
@anchor{reference/import cached-bytecode-invalidation}@anchor{1638}@anchor{reference/import pyc-invalidation}@anchor{442}
@subsubsection 已缓存字节码的失效


在 Python 从 @code{.pyc} 文件加载已缓存字节码之前，它会检查缓存是否由最新的 @code{.py} 源文件所生成。 默认情况下，Python 通过在所写入缓存文件中保存源文件的最新修改时间戳和大小来实现这一点。 在运行时，导入系统会通过比对缓存文件中保存的元数据和源文件的元数据确定该缓存的有效性。

Python 也支持“基于哈希的”缓存文件，即保存源文件内容的哈希值而不是其元数据。 存在两种基于哈希的 @code{.pyc} 文件：检查型和非检查型。 对于检查型基于哈希的 @code{.pyc} 文件，Python 会通过求哈希源文件并将结果哈希值与缓存文件中的哈希值比对来确定缓存有效性。 如果检查型基于哈希的缓存文件被确定为失效，Python 会重新生成并写入一个新的检查型基于哈希的缓存文件。 对于非检查型 @code{.pyc} 文件，只要其存在 Python 就会直接认定缓存文件有效。 确定基于哈希的 @code{.pyc} 文件有效性的行为可通过 @ref{14a5,,--check-hash-based-pycs} 旗标来重载。


在 3.7 版更改: 增加了基于哈希的 @code{.pyc} 文件。在此之前，Python 只支持基于时间戳来确定字节码缓存的有效性。


@node 基于路径的查找器,替换标准导入系统,加载,导入系统
@anchor{reference/import the-path-based-finder}@anchor{1639}
@subsection 基于路径的查找器


@geindex path based finder

在之前已经提及，Python 带有几种默认的元路径查找器。 其中之一是 @ref{162a,,path based finder} (@ref{a45,,PathFinder})，它会搜索包含一个 @ref{163a,,路径条目} 列表的 @ref{1627,,import path}。 每个路径条目指定一个用于搜索模块的位置。

基于路径的查找器自身并不知道如何进行导入。 它只是遍历单独的路径条目，将它们各自关联到某个知道如何处理特定类型路径的路径条目查找器。

默认的路径条目查找器集合实现了在文件系统中查找模块的所有语义，可处理多种特殊文件类型例如 Python 源码 (@code{.py} 文件)，Python 字节码 (@code{.pyc} 文件) 以及共享库 (例如 @code{.so} 文件)。 在标准库中 @ref{14c,,zipimport} 模块的支持下，默认路径条目查找器还能处理所有来自 zip 文件的上述文件类型。

路径条目不必仅限于文件系统位置。 它们可以指向 URL、数据库查询或可以用字符串指定的任何其他位置。

基于路径的查找器还提供了额外的钩子和协议以便能扩展和定制可搜索路径条目的类型。 例如，如果你想要支持网络 URL 形式的路径条目，你可以编写一个实现 HTTP 语义在网络上查找模块的钩子。 这个钩子（可调用对象）应当返回一个支持下述协议的 @ref{a9b,,path entry finder}，以被用来获取一个专门针对来自网络的模块的加载器。

预先的警告：本节和上节都使用了 @emph{查找器} 这一术语，并通过 @ref{a9a,,meta path finder} 和 @ref{a9b,,path entry finder} 两个术语来明确区分它们。 这两种类型的查找器非常相似，支持相似的协议，且在导入过程中以相似的方式运作，但关键的一点是要记住它们是有微妙差异的。 特别地，元路径查找器作用于导入过程的开始，主要是启动 @ref{6e7,,sys.meta_path} 遍历。

相比之下，路径条目查找器在某种意义上说是基于路径的查找器的实现细节，实际上，如果需要从 @ref{6e7,,sys.meta_path} 移除基于路径的查找器，并不会有任何路径条目查找器被发起调用。

@menu
* 路径条目查找器:: 
* 路径条目查找器协议:: 

@end menu

@node 路径条目查找器,路径条目查找器协议,,基于路径的查找器
@anchor{reference/import path-entry-finders}@anchor{163b}
@subsubsection 路径条目查找器


@geindex sys.path
@geindex sys.path_hooks
@geindex sys.path_importer_cache
@geindex PYTHONPATH

@ref{162a,,path based finder} 会负责查找和加载通过 @ref{163a,,path entry} 字符串来指定位置的 Python 模块和包。 多数路径条目所指定的是文件系统中的位置，但它们并不必受限于此。

作为一种元路径查找器，@ref{162a,,path based finder} 实现了上文描述的 @ref{56d,,find_spec()} 协议，但是它还对外公开了一些附加钩子，可被用来定制模块如何从 @ref{1627,,import path} 查找和加载。

有三个变量由 @ref{162a,,path based finder}, @ref{262,,sys.path}, @ref{a46,,sys.path_hooks} 和 @ref{5a0,,sys.path_importer_cache} 所使用。 包对象的 @code{__path__} 属性也会被使用。 它们提供了可用于定制导入机制的额外方式。

@ref{262,,sys.path} 包含一个提供模块和包搜索位置的字符串列表。 它初始化自 @code{PYTHONPATH} 环境变量以及多种其他特定安装和实现的默认设置。 @ref{262,,sys.path} 条目可指定的名称有文件系统中的目录、zip 文件和其他可用于搜索模块的潜在“位置”（参见 @ref{eb,,site} 模块），例如 URL 或数据库查询等。 在 @ref{262,,sys.path} 中只能出现字符串和字节串；所有其他数据类型都会被忽略。 字节串条目使用的编码由单独的 @ref{a9b,,路径条目查找器} 来确定。

@ref{162a,,path based finder} 是一种  @ref{a9a,,meta path finder}，因此导入机制会通过调用上文描述的基于路径的查找器的 @ref{a27,,find_spec()} 方法来启动 @ref{1627,,import path} 搜索。 当要向 @ref{a27,,find_spec()} 传入 @code{path} 参数时，它将是一个可遍历的字符串列表 —— 通常为用来在其内部进行导入的包的 @code{__path__} 属性。 如果 @code{path} 参数为 @code{None}，这表示最高层级的导入，将会使用 @ref{262,,sys.path}。

基于路径的查找器会迭代搜索路径中的每个条目，并且每次都查找与路径条目对应的 @ref{a9b,,path entry finder} (@ref{a9d,,PathEntryFinder})。 因为这种操作可能很耗费资源（例如搜索会有 @cite{stat()} 调用的开销），基于路径的查找器会维持一个缓存来将路径条目映射到路径条目查找器。 这个缓存放于 @ref{5a0,,sys.path_importer_cache} (尽管如此命名，但这个缓存实际存放的是查找器对象而非仅限于 @ref{1626,,importer} 对象)。 通过这种方式，对特定 @ref{163a,,path entry} 位置的 @ref{a9b,,path entry finder} 的高耗费搜索只需进行一次。 用户代码可以自由地从 @ref{5a0,,sys.path_importer_cache} 移除缓存条目，以强制基于路径的查找器再次执行路径条目搜索 @footnote{@w{(3)} 
在遗留代码中，有可能在 @ref{5a0,,sys.path_importer_cache} 中找到 @ref{aa4,,imp.NullImporter} 的实例。 建议将这些代码修改为使用 @code{None} 代替。 详情参见 @ref{bee,,Porting Python code}。
}。

如果路径条目不存在于缓存中，基于路径的查找器会迭代 @ref{a46,,sys.path_hooks} 中的每个可调用对象。 对此列表中的每个 @ref{163c,,路径条目钩子} 的调用会带有一个参数，即要搜索的路径条目。 每个可调用对象或是返回可处理路径条目的 @ref{a9b,,path entry finder}，或是引发 @ref{16c,,ImportError}。 基于路径的查找器使用 @ref{16c,,ImportError} 来表示钩子无法找到与 @ref{163a,,path entry} 相对应的 @ref{a9b,,path entry finder}。 该异常会被忽略并继续进行 @ref{1627,,import path} 的迭代。 每个钩子应该期待接收一个字符串或字节串对象；字节串对象的编码由钩子决定（例如可以是文件系统使用的编码  UTF-8 或其它编码），如果钩子无法解码参数，它应该引发 @ref{16c,,ImportError}。

如果 @ref{a46,,sys.path_hooks} 迭代结束时没有返回 @ref{a9b,,path entry finder}，则基于路径的查找器 @ref{a27,,find_spec()} 方法将在 @ref{5a0,,sys.path_importer_cache} 中存入 @code{None} (表示此路径条目没有对应的查找器) 并返回 @code{None}，表示此 @ref{a9a,,meta path finder} 无法找到该模块。

如果 @ref{a46,,sys.path_hooks} 中的某个 @ref{163c,,path entry hook} 可调用对象的返回值 @emph{是} 一个 @ref{a9b,,path entry finder}，则以下协议会被用来向查找器请求一个模块的规格说明，并在加载该模块时被使用。

当前工作目录 -- 由一个空字符串表示 -- 的处理方式与 @ref{262,,sys.path} 中的其他条目略有不同。 首先，如果发现当前工作目录不存在，则 @ref{5a0,,sys.path_importer_cache} 中不会存放任何值。 其次，每个模块查找会对当前工作目录的值进行全新查找。 第三，由 @ref{5a0,,sys.path_importer_cache} 所使用并由 @ref{a27,,importlib.machinery.PathFinder.find_spec()} 所返回的路径将是实际的当前工作目录而非空字符串。

@node 路径条目查找器协议,,路径条目查找器,基于路径的查找器
@anchor{reference/import path-entry-finder-protocol}@anchor{163d}
@subsubsection 路径条目查找器协议


为了支持模块和已初始化包的导入，也为了给命名空间包提供组成部分，路径条目查找器必须实现 @ref{56f,,find_spec()} 方法。

@ref{56f,,find_spec()} 接受两个参数，即要导入模块的完整限定名称，以及（可选的）目标模块。 @code{find_spec()} 返回模块的完全填充好的规格说明。 这个规格说明总是包含“加载器”集合（但有一个例外）。

为了向导入机制提示该规格说明代表一个命名空间 @ref{161f,,portion}，路径条目查找器会将 "submodule_search_locations" 设为一个包含该部分的列表。


在 3.4 版更改: @ref{56f,,find_spec()} 替代了 @ref{56e,,find_loader()} 和 @ref{a28,,find_module()}，后两者现在都已弃用，但会在 @code{find_spec()} 未定义时被使用。

较旧的路径条目查找器可能会实现这两个已弃用的方法中的一个而没有实现 @code{find_spec()}。 为保持向后兼容，这两个方法仍会被接受。 但是，如果在路径条目查找器上实现了 @code{find_spec()}，这两个遗留方法就会被忽略。

@ref{56e,,find_loader()} 接受一个参数，即要导入模块的完整限定名称。 @code{find_loader()} 返回一个 2 元组，其中第一项是加载器而第二项是命名空间 @ref{161f,,portion}。

为了向后兼容其他导入协议的实现，许多路径条目查找器也同样支持元路径查找器所支持的传统 @code{find_module()} 方法。 但是路径条目查找器 @code{find_module()} 方法的调用绝不会带有 @code{path} 参数（它们被期望记录来自对路径钩子初始调用的恰当路径信息）。

路径条目查找器的 @code{find_module()} 方法已弃用，因为它不允许路径条目查找器为命名空间包提供部分。 如果 @code{find_loader()} 和 @code{find_module()} 同时存在于一个路径条目查找器中，导入系统将总是调用 @code{find_loader()} 而不选择 @code{find_module()}。


@node 替换标准导入系统,包相对导入,基于路径的查找器,导入系统
@anchor{reference/import replacing-the-standard-import-system}@anchor{163e}
@subsection 替换标准导入系统


替换整个导入系统的最可靠机制是移除 @ref{6e7,,sys.meta_path} 的默认内容，,将其完全替换为自定义的元路径钩子。

一个可行的方式是仅改变导入语句的行为而不影响访问导入系统的其他 API，那么替换内置的 @ref{16b,,__import__()} 函数可能就够了。 这种技巧也可以在模块层级上运用，即只在某个模块内部改变导入语句的行为。

想要选择性地预先防止在元路径上从一个钩子导入某些模块（而不是完全禁用标准导入系统），只需直接从 @ref{56d,,find_spec()} 引发 @ref{4a9,,ModuleNotFoundError} 而非返回 @code{None} 就足够了。 返回后者表示元路径搜索应当继续，而引发异常则会立即终止搜索。

@node 包相对导入,有关 __main__ 的特殊事项,替换标准导入系统,导入系统
@anchor{reference/import package-relative-imports}@anchor{163f}@anchor{reference/import relativeimports}@anchor{1640}
@subsection 包相对导入


相对导入使用前缀点号。 一个前缀点号表示相对导入从当前包开始。 两个或更多前缀点号表示对当前包的上级包的相对导入，第一个点号之后的每个点号代表一级。 例如，给定以下的包布局结构:

@example
package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py
@end example

不论是在 @code{subpackage1/moduleX.py} 还是 @code{subpackage1/__init__.py} 中，以下导入都是有效的:

@example
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
@end example

绝对导入可以使用 @code{import <>} 或 @code{from <> import <>} 语法，但相对导入只能使用第二种形式；其中的原因在于:

@example
import XXX.YYY.ZZZ
@end example

应当提供 @code{XXX.YYY.ZZZ} 作为可用表达式，但 .moduleY 不是一个有效的表达式。

@node 有关 __main__ 的特殊事项,开放问题项,包相对导入,导入系统
@anchor{reference/import special-considerations-for-main}@anchor{1641}
@subsection 有关 __main__ 的特殊事项


对于 Python 的导入系统来说 @ref{1,,__main__} 模块是一个特殊情况。 正如在 @ref{1633,,另一节} 中所述，@code{__main__} 模块是在解释器启动时直接初始化的，与 @ref{fd,,sys} 和 @ref{12,,builtins} 很类似。 但是，与那两者不同，它并不被严格归类为内置模块。 这是因为 @code{__main__} 被初始化的方式依赖于发起调用解释器所附带的旗标和其他选项。

@menu
* __main__.__spec__: __main__ __spec__. 

@end menu

@node __main__ __spec__,,,有关 __main__ 的特殊事项
@anchor{reference/import id5}@anchor{1642}@anchor{reference/import main-spec}@anchor{1634}
@subsubsection __main__.__spec__


根据 @ref{1,,__main__} 被初始化的方式，@code{__main__.__spec__} 会被设置相应值或是 @code{None}。

当 Python 附加 @ref{44c,,-m} 选项启动时，@code{__spec__} 会被设为相应模块或包的模块规格说明。 @code{__spec__} 也会在 @code{__main__} 模块作为执行某个目录，zip 文件或其它 @ref{262,,sys.path} 条目的一部分加载时被填充。

在 @ref{149f,,其余的情况} 下 @code{__main__.__spec__} 会被设为 @code{None}，因为用于填充 @ref{1,,__main__} 的代码不直接与可导入的模块相对应:


@itemize -

@item 
交互型提示

@item 
@ref{136f,,-c} 选项

@item 
从 stdin 运行

@item 
直接从源码或字节码文件运行
@end itemize

请注意在最后一种情况中 @code{__main__.__spec__} 总是为 @code{None}，@emph{即使} 文件从技术上说可以作为一个模块被导入。 如果想要让 @ref{1,,__main__} 中的元数据生效，请使用 @ref{44c,,-m} 开关。

还要注意即使是在 @code{__main__} 对应于一个可导入模块且 @code{__main__.__spec__} 被相应地设定时，它们仍会被视为 @emph{不同的} 模块。 这是由于以下事实：使用 @code{if __name__ == "__main__":}  检测来保护的代码块仅会在模块被用来填充 @code{__main__} 命名空间时而非普通的导入时被执行。

@node 开放问题项,参考文献,有关 __main__ 的特殊事项,导入系统
@anchor{reference/import open-issues}@anchor{1643}
@subsection 开放问题项


XXX 最好是能增加一个图表。

XXX * (import_machinery.rst) 是否要专门增加一节来说明模块和包的属性，也许可以扩展或移植数据模型参考页中的相关条目？

XXX 库手册中的 runpy 和 pkgutil 等等应该都在页面顶端增加指向新的导入系统章节的“另请参阅”链接。

XXX 是否要增加关于初始化 @code{__main__} 的不同方式的更多解释？

XXX 增加更多有关 @code{__main__} 怪异/坑人特性的信息 (例如直接从 
@geindex Python 提高建议; PEP 395
PEP 395@footnote{https://www.python.org/dev/peps/pep-0395} 复制)。

@node 参考文献,,开放问题项,导入系统
@anchor{reference/import references}@anchor{1644}
@subsection 参考文献


导入机制自 Python 诞生之初至今已发生了很大的变化。 原始的 包规格说明@footnote{https://www.python.org/doc/essays/packages/} 仍然可以查阅，但在撰写该文档之后许多相关细节已被修改。

原始的 @ref{6e7,,sys.meta_path} 规格说明见 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}，后续的扩展说明见 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420}。

@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 为 Python 3.3 引入了 @ref{161d,,命名空间包}。 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 还引入了 @code{find_loader()} 协议作为 @code{find_module()} 的替代。

@geindex Python 提高建议; PEP 366
PEP 366@footnote{https://www.python.org/dev/peps/pep-0366} 描述了新增的 @code{__package__} 属性，用于在模块中的显式相对导入。

@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328} 引入了绝对和显式相对导入，并初次提出了 @code{__name__} 语义，最终由 
@geindex Python 提高建议; PEP 366
PEP 366@footnote{https://www.python.org/dev/peps/pep-0366} 为 @code{__package__} 加入规范描述。

@geindex Python 提高建议; PEP 338
PEP 338@footnote{https://www.python.org/dev/peps/pep-0338} 定义了将模块作为脚本执行。

@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} 在 spec 对象中增加了对每个模块导入状态的封装。 它还将加载器的大部分样板责任移交回导入机制中。 这些改变允许弃用导入系统中的一些 API 并为查找器和加载器增加一些新的方法。

@node 表达式,简单语句,导入系统,Python 语言参考手册
@anchor{reference/expressions doc}@anchor{1645}@anchor{reference/expressions expressions}@anchor{1646}@anchor{reference/expressions id1}@anchor{1647}
@section 表达式


@geindex expression
@geindex BNF

本章将解释 Python 中组成表达式的各种元素的的含义。

@strong{语法注释:} 在本章和后续章节中，会使用扩展 BNF 标注来描述语法而不是词法分析。 当（某种替代的）语法规则具有如下形式

@example
@anchor{reference/expressions grammar-token-name}@anchor{1648}name ::= othername
@end example

并且没有给出语义，则这种形式的 @code{name} 在语法上与 @code{othername} 相同。

@menu
* 算术转换:: 
* 原子:: 
* 原型:: 
* await 表达式:: 
* 幂运算符:: 
* 一元算术和位运算:: 
* 二元算术运算符:: 
* 移位运算:: 
* 二元位运算:: 
* 比较运算:: 
* 布尔运算:: 
* 赋值表达式: 赋值表达式<2>. 
* 条件表达式:: 
* lambda 表达式:: 
* 表达式列表:: 
* 求值顺序:: 
* 运算符优先级:: 

@end menu

@node 算术转换,原子,,表达式
@anchor{reference/expressions arithmetic-conversions}@anchor{1649}@anchor{reference/expressions conversions}@anchor{164a}
@subsection 算术转换


@geindex arithmetic; conversion

当对下述某个算术运算符的描述中使用了“数值参数被转换为普通类型”这样的说法，这意味着内置类型的运算符实现采用了如下运作方式:


@itemize *

@item 
如果任一参数为复数，另一参数会被转换为复数；

@item 
否则，如果任一参数为浮点数，另一参数会被转换为浮点数；

@item 
否则，两者应该都为整数，不需要进行转换。
@end itemize

某些附加规则会作用于特定运算符（例如，字符串作为 '%' 运算符的左运算参数）。 扩展必须定义它们自己的转换行为。

@node 原子,原型,算术转换,表达式
@anchor{reference/expressions atoms}@anchor{164b}@anchor{reference/expressions id2}@anchor{164c}
@subsection 原子


@geindex atom

“原子”指表达式的最基本构成元素。 最简单的原子是标识符和字面值。 以圆括号、方括号或花括号包括的形式在语法上也被归类为原子。 原子的句法为:

@example
@anchor{reference/expressions grammar-token-atom}@anchor{164d}atom      ::= identifier | literal | enclosure
@anchor{reference/expressions grammar-token-enclosure}@anchor{164e}enclosure ::= parenth_form | list_display | dict_display | set_display
              | generator_expression | yield_atom
@end example

@menu
* 标识符（名称）:: 
* 字面值: 字面值<2>. 
* 带圆括号的形式:: 
* 列表、集合与字典的显示:: 
* 列表显示:: 
* 集合显示:: 
* 字典显示:: 
* 生成器表达式: 生成器表达式<2>. 
* yield 表达式:: 

@end menu

@node 标识符（名称）,字面值<2>,,原子
@anchor{reference/expressions atom-identifiers}@anchor{153e}@anchor{reference/expressions identifiers-names}@anchor{164f}
@subsubsection 标识符（名称）


@geindex name
@geindex identifier

作为原子出现的标识符叫做名称。 请参看 @ref{1533,,标识符和关键字} 一节了解其词法定义，以及 @ref{1608,,命名与绑定} 获取有关命名与绑定的文档。

@geindex 例外; NameError

当名称被绑定到一个对象时，对该原子求值将返回相应对象。 当名称未被绑定时，尝试对其求值将引发 @ref{e48,,NameError} 异常。
@anchor{reference/expressions private-name-mangling}@anchor{1650}
@geindex name; mangling
@geindex private; names

@strong{私有名称转换:} 当以文本形式出现在类定义中的一个标识符以两个或更多下划线开头并且不以两个或更多下划线结尾，它会被视为该类的 @emph{私有名称}。 私有名称会在为其生成代码之前被转换为一种更长的形式。 转换时会插入类名，移除打头的下划线再在名称前增加一个下划线。 例如，出现在一个名为 @code{Ham} 的类中的标识符 @code{__spam} 会被转换为 @code{_Ham__spam}。 这种转换独立于标识符所使用的相关句法。 如果转换后的名称太长（超过 255 个字符），可能发生由具体实现定义的截断。 如果类名仅由下划线组成，则不会进行转换。

@node 字面值<2>,带圆括号的形式,标识符（名称）,原子
@anchor{reference/expressions atom-literals}@anchor{1651}@anchor{reference/expressions literals}@anchor{1652}
@subsubsection 字面值


@geindex literal

Python 支持字符串和字节串字面值，以及几种数字字面值:

@example
@anchor{reference/expressions grammar-token-literal}@anchor{1653}literal ::= stringliteral | bytesliteral
            | integer | floatnumber | imagnumber
@end example

对字面值求值将返回一个该值所对应类型的对象（字符串、字节串、整数、浮点数、复数）。 对于浮点数和虚数（复数）的情况，该值可能为近似值。 详情参见 @ref{1540,,字面值}。

@geindex immutable; data; type
@geindex immutable; object

所有字面值都对应于不可变数据类型，因此对象标识的重要性不如其实际值。 多次对具有相同值的字面值求值（不论是发生在程序文本的相同位置还是不同位置）可能得到相同对象或是具有相同值的不同对象。

@node 带圆括号的形式,列表、集合与字典的显示,字面值<2>,原子
@anchor{reference/expressions parenthesized}@anchor{1654}@anchor{reference/expressions parenthesized-forms}@anchor{1655}
@subsubsection 带圆括号的形式


@geindex parenthesized form
@geindex () (parentheses); tuple display

带圆括号的形式是包含在圆括号中的可选表达式列表。

@example
@anchor{reference/expressions grammar-token-parenth-form}@anchor{1656}parenth_form ::= "(" [starred_expression] ")"
@end example

带圆括号的表达式列表将返回该表达式列表所产生的任何东西：如果该列表包含至少一个逗号，它会产生一个元组；否则，它会产生该表达式列表所对应的单一表达式。

@geindex empty; tuple

一对内容为空的圆括号将产生一个空的元组对象。 由于元组是不可变对象，因此适用与字面值相同的规则（即两次出现的空元组产生的对象可能相同也可能不同）。

@geindex comma
@geindex @comma{} (comma)

请注意元组并不是由圆括号构建，实际起作用的是逗号操作符。 例外情况是空元组，这时圆括号 @emph{才是} 必须的 --- 允许在表达式中使用不带圆括号的 "空" 会导致歧义，并会造成常见输入错误无法被捕获。

@node 列表、集合与字典的显示,列表显示,带圆括号的形式,原子
@anchor{reference/expressions comprehensions}@anchor{1657}@anchor{reference/expressions displays-for-lists-sets-and-dictionaries}@anchor{1658}
@subsubsection 列表、集合与字典的显示


@geindex comprehensions

为了构建列表、集合或字典，Python 提供了名为“显示”的特殊句法，每个类型各有两种形式:


@itemize *

@item 
第一种是显式地列出容器内容

@item 
第二种是通过一组循环和筛选指令计算出来，称为 @emph{推导式}。
@end itemize

@geindex for; in comprehensions
@geindex if; in comprehensions
@geindex async for; in comprehensions

推导式的常用句法元素为:

@example
@anchor{reference/expressions grammar-token-comprehension}@anchor{1659}comprehension ::= assignment_expression comp_for
@anchor{reference/expressions grammar-token-comp-for}@anchor{165a}comp_for      ::= ["async"] "for" target_list "in" or_test [comp_iter]
@anchor{reference/expressions grammar-token-comp-iter}@anchor{165b}comp_iter     ::= comp_for | comp_if
@anchor{reference/expressions grammar-token-comp-if}@anchor{165c}comp_if       ::= "if" or_test [comp_iter]
@end example

推导式的结构是一个单独表达式后面加至少一个 @code{for} 子句以及零个或更多个 @code{for} 或 @code{if} 子句。 在这种情况下，新容器的元素产生方式是将每个 @code{for} 或 @code{if} 子句视为一个代码块，按从左至右的顺序嵌套，然后每次到达最内层代码块时就对表达式进行求值以产生一个元素。

不过，除了最左边 @code{for} 子句中的可迭代表达式，推导式是在另一个隐式嵌套的作用域内执行的。 这能确保赋给目标列表的名称不会“泄露”到外层的作用域。

最左边的 @code{for} 子句中的可迭代对象表达式会直接在外层作用域中被求值，然后作为一个参数被传给隐式嵌套的作用域。 后续的 @code{for} 子句以及最左侧 @code{for} 子句中的任何筛选条件不能在外层作用域中被求值，因为它们可能依赖于从最左侧可迭代对象中获得的值。 例如: @code{[x*y for x in range(10) for y in range(x, x+10)]}。

为了确保推导式得出的结果总是一个类型正确的容器，在隐式嵌套作用域内禁止使用 @code{yield} 和 @code{yield from} 表达式。

@geindex await; in comprehensions

从 Python 3.6 开始，在 @ref{3b1,,async def} 函数中可以使用 @code{async for} 子句来迭代 @ref{742,,asynchronous iterator}。 在 @code{async def} 函数中构建推导式可以通过在打头的表达式后加上 @code{for} 或 @code{async for} 子句，也可能包含额外的 @code{for} 或 @code{async for} 子句，还可能使用 @ref{2df,,await} 表达式。 如果一个推导式包含 @code{async for} 子句或者 @code{await} 表达式，则被称为 @emph{异步推导式}。 异步推导式可以暂停执行它所在的协程函数。 另请参阅 
@geindex Python 提高建议; PEP 530
PEP 530@footnote{https://www.python.org/dev/peps/pep-0530}。


3.6 新版功能: 引入了异步推导式。



在 3.8 版更改: @code{yield} 和 @code{yield from} 在隐式嵌套的作用域中已被禁用。


@node 列表显示,集合显示,列表、集合与字典的显示,原子
@anchor{reference/expressions list-displays}@anchor{165d}@anchor{reference/expressions lists}@anchor{165e}
@subsubsection 列表显示


@geindex list; display
@geindex list; comprehensions
@geindex empty; list
@geindex 对象; list
@geindex [] (square brackets); list expression
@geindex @comma{} (comma); expression list

列表显示是一个用方括号括起来的可能为空的表达式系列:

@example
@anchor{reference/expressions grammar-token-list-display}@anchor{165f}list_display ::= "[" [starred_list | comprehension] "]"
@end example

列表显示会产生一个新的列表对象，其内容通过一系列表达式或一个推导式来指定。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并按此顺序放入列表对象。 当提供一个推导式时，列表会根据推导式所产生的结果元素进行构建。

@node 集合显示,字典显示,列表显示,原子
@anchor{reference/expressions set}@anchor{1660}@anchor{reference/expressions set-displays}@anchor{1661}
@subsubsection 集合显示


@geindex set; display
@geindex set; comprehensions
@geindex 对象; set
@geindex @{@} (curly brackets); set expression
@geindex @comma{} (comma); expression list

集合显示是用花括号标明的，与字典显示的区别在于没有冒号分隔的键和值:

@example
@anchor{reference/expressions grammar-token-set-display}@anchor{1662}set_display ::= "@{" (starred_list | comprehension) "@}"
@end example

集合显示会产生一个新的可变集合对象，其内容通过一系列表达式或一个推导式来指定。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并加入到集合对象。 当提供一个推导式时，集合会根据推导式所产生的结果元素进行构建。

空集合不能用 @code{@{@}} 来构建；该字面值所构建的是一个空字典。

@node 字典显示,生成器表达式<2>,集合显示,原子
@anchor{reference/expressions dict}@anchor{74b}@anchor{reference/expressions dictionary-displays}@anchor{1663}
@subsubsection 字典显示


@geindex dictionary; display
@geindex dictionary; comprehensions
@geindex key
@geindex datum
@geindex key/datum pair
@geindex 对象; dictionary
@geindex @{@} (curly brackets); dictionary expression
@geindex ; (colon); in dictionary expressions
@geindex @comma{} (comma); in dictionary displays

字典显示是一个用花括号括起来的可能为空的键/数据对系列:

@example
@anchor{reference/expressions grammar-token-dict-display}@anchor{1664}dict_display       ::= "@{" [key_datum_list | dict_comprehension] "@}"
@anchor{reference/expressions grammar-token-key-datum-list}@anchor{1665}key_datum_list     ::= key_datum ("," key_datum)* [","]
@anchor{reference/expressions grammar-token-key-datum}@anchor{1666}key_datum          ::= expression ":" expression | "**" or_expr
@anchor{reference/expressions grammar-token-dict-comprehension}@anchor{1667}dict_comprehension ::= expression ":" expression comp_for
@end example

字典显示会产生一个新的字典对象。

如果给出一个由逗号分隔的键/数据对序列，它们会从左至右被求值以定义字典的条目：每个键对象会被用作在字典中存放相应数据的键。 这意味着你可以在键/数据对序列中多次指定相同的键，最终字典的值将由最后一次给出的键决定。

@geindex unpacking; dictionary
@geindex **; in dictionary displays

双星号 @code{**} 表示 @emph{字典拆包}。 它的操作数必须是一个 @ref{c14,,mapping}。 每个映射项被会加入新的字典。 后续的值会替代先前的键/数据对和先前的字典拆包所设置的值。


3.5 新版功能: 拆包到字典显示，最初由 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} 提出。


字典推导式与列表和集合推导式有所不同，它需要以冒号分隔的两个表达式，后面带上标准的 "for" 和 "if" 子句。 当推导式被执行时，作为结果的键和值元素会按它们的产生顺序被加入新的字典。

@geindex immutable; object
@geindex hashable

对键取值类型的限制已列在之前的 @ref{1582,,标准类型层级结构} 一节中。 (总的说来，键的类型应该为 @ref{277,,hashable}，这就把所有可变对象都排除在外。) 重复键之间的冲突不会被检测；指定键所保存的最后一个数据 (即在显示中排最右边的文本) 为最终有效数据。


在 3.8 版更改: 在 Python 3.8 之前的字典推导式中，并没有定义好键和值的求值顺序。 在 CPython 中，值会先于键被求值。 根据 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} 的提议，从 3.8 开始，键会先于值被求值。


@node 生成器表达式<2>,yield 表达式,字典显示,原子
@anchor{reference/expressions generator-expressions}@anchor{1668}@anchor{reference/expressions genexpr}@anchor{1669}
@subsubsection 生成器表达式


@geindex generator; expression
@geindex 对象; generator
@geindex () (parentheses); generator expression

生成器表达式是用圆括号括起来的紧凑形式生成器标注。

@example
@anchor{reference/expressions grammar-token-generator-expression}@anchor{166a}generator_expression ::= "(" expression comp_for ")"
@end example

生成器表达式会产生一个新的生成器对象。 其句法与推导式相同，区别在于它是用圆括号而不是用方括号或花括号括起来的。

在生成器表达式中使用的变量会在为生成器对象调用 @ref{143f,,__next__()} 方法的时候以惰性方式被求值（即与普通生成器相同的方式）。 但是，最左侧 @code{for} 子句内的可迭代对象是会被立即求值的，因此它所造成的错误会在生成器表达式被定义时被检测到，而不是在获取第一个值时才出错。 后续的 @code{for} 子句以及最左侧 @code{for} 子句内的任何筛选条件无法在外层作用域内被求值，因为它们可能会依赖于从最左侧可迭代对象获取的值。 例如: @code{(x*y for x in range(10) for y in range(x, x+10))}.

圆括号在只附带一个参数的调用中可以被省略。 详情参见 @ref{749,,调用} 一节。

为了避免干扰到生成器表达式本身的预期操作，禁止在隐式定义的生成器中使用 @code{yield} 和 @code{yield from} 表达式。

如果生成器表达式包含 @code{async for} 子句或 @ref{2df,,await} 表达式，则称为 @emph{异步生成器表达式}。 异步生成器表达式会返回一个新的异步生成器对象，此对象属于异步迭代器 (参见 @ref{743,,异步迭代器})。


3.6 新版功能: 引入了异步生成器表达式。



在 3.7 版更改: 在 Python 3.7 之前，异步生成器表达式只能在 @ref{3b1,,async def} 协和中出现。 从 3.7 开始，任何函数都可以使用异步生成器表达式。



在 3.8 版更改: @code{yield} 和 @code{yield from} 在隐式嵌套的作用域中已被禁用。


@node yield 表达式,,生成器表达式<2>,原子
@anchor{reference/expressions yield-expressions}@anchor{166b}@anchor{reference/expressions yieldexpr}@anchor{166c}
@subsubsection yield 表达式


@geindex 关键字; yield
@geindex 关键字; from
@geindex yield; expression
@geindex generator; function

@example
@anchor{reference/expressions grammar-token-yield-atom}@anchor{166d}yield_atom       ::= "(" yield_expression ")"
@anchor{reference/expressions grammar-token-yield-expression}@anchor{166e}yield_expression ::= "yield" [expression_list | "from" expression]
@end example

yield 表达式在定义 @ref{a8c,,generator} 函数或 @ref{166f,,asynchronous generator} 函数时才会用到因此只能在函数定义的内部使用。 在一个函数体内使用 yield 表达式会使这个函数变成一个生成器函数，而在一个 @ref{3b1,,async def} 函数的内部使用它则会让这个协程函数变成一个异步生成器函数。 例如:

@example
def gen():  # defines a generator function
    yield 123

async def agen(): # defines an asynchronous generator function
    yield 123
@end example

由于它们会对外层作用域造成附带影响，@code{yield} 表达式不被允许作为用于实现推导式和生成器表达式的隐式定义作用域的一部分。


在 3.8 版更改: 禁止在实现推导式和生成器表达式的隐式嵌套作用域中使用 yield 表达式。


下面是对生成器函数的描述，异步生成器函数会在 @ref{1670,,异步生成器函数} 一节中单独介绍。

当一个生成器函数被调用的时候，它返回一个迭代器，称为生成器。然后这个生成器来控制生成器函数的执行。当这个生成器的某一个方法被调用的时候，生成器函数开始执行。这时会一直执行到第一个 yield 表达式，在此执行再次被挂起，给生成器的调用者返回  @ref{1671,,expression_list} 的值。挂起后，我们说所有局部状态都被保留下来，包括局部变量的当前绑定，指令指针，内部求值栈和任何异常处理的状态。通过调用生成器的某一个方法，生成器函数继续执行。此时函数的运行就和 yield 表达式只是一个外部函数调用的情况完全一致。恢复后 yield 表达式的值取决于调用的哪个方法来恢复执行。 如果用的是 @ref{143f,,__next__()} (通常通过语言内置的 @ref{d02,,for} 或是 @ref{77f,,next()} 来调用) 那么结果就是 @ref{204,,None}.  否则，如果用 @ref{15fc,,send()}, 那么结果就是传递给send方法的值。

@geindex coroutine

所有这些使生成器函数与协程非常相似；它们 yield 多次，它们具有多个入口点，并且它们的执行可以被挂起。唯一的区别是生成器函数不能控制在它在 yield 后交给哪里继续执行；控制权总是转移到生成器的调用者。

在 @ref{e3f,,try} 结构中的任何位置都允许yield表达式。如果生成器在(因为引用计数到零或是因为被垃圾回收)销毁之前没有恢复执行，将调用生成器-迭代器的 @ref{15ff,,close()} 方法. close 方法允许任何挂起的 @ref{2c3,,finally} 子句执行。

@geindex from; yield from expression

当使用 @code{yield from <expr>} 时，所提供的表达式必须是一个可迭代对象。 迭代该可迭代对象所产生的值会被直接传递给当前生成器方法的调用者。 任何通过 @ref{15fc,,send()} 传入的值以及任何通过 @ref{1042,,throw()} 传入的异常如果有适当的方法则会被传给下层迭代器。 如果不是这种情况，那么 @ref{15fc,,send()} 将引发 @ref{4aa,,AttributeError} 或 @ref{1ff,,TypeError}，而 @ref{1042,,throw()} 将立即引发所转入的异常。

当下层迭代器完成时，被引发的 @ref{58a,,StopIteration} 实例的 @code{value} 属性会成为 yield 表达式的值。 它可以在引发 @ref{58a,,StopIteration} 时被显式地设置，也可以在子迭代器是一个生成器时自动地设置（通过从子生成器返回一个值）。

@quotation


在 3.3 版更改: 添加 @code{yield from <expr>} 以委托控制流给一个子迭代器。

@end quotation

当yield表达式是赋值语句右侧的唯一表达式时，括号可以省略。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 255

@item PEP 255@footnote{https://www.python.org/dev/peps/pep-0255} - 简单生成器

在 Python 中加入生成器和 @ref{2ce,,yield} 语句的提议。

@geindex Python 提高建议; PEP 342

@item PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} - 通过增强型生成器实现协程

增强生成器 API 和语法的提议，使其可以被用作简单的协程。

@geindex Python 提高建议; PEP 380

@item PEP 380@footnote{https://www.python.org/dev/peps/pep-0380} - 委托给子生成器的语法

引入 @code{yield_from} 语法以方便地委托给子生成器的提议。

@geindex Python 提高建议; PEP 525

@item PEP 525@footnote{https://www.python.org/dev/peps/pep-0525} - 异步生成器

通过给协程函数加入生成器功能对 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 进行扩展的提议。
@end table


@geindex 对象; generator

@menu
* 生成器-迭代器的方法:: 
* 示例:: 
* 异步生成器函数:: 
* 异步生成器-迭代器方法:: 

@end menu

@node 生成器-迭代器的方法,示例,,yield 表达式
@anchor{reference/expressions generator-iterator-methods}@anchor{1672}@anchor{reference/expressions generator-methods}@anchor{15fa}
@subsubsection 生成器-迭代器的方法


这个子小节描述了生成器迭代器的方法。 它们可被用于控制生成器函数的执行。

请注意在生成器已经在执行时调用以下任何方法都会引发 @ref{16d,,ValueError} 异常。

@geindex 例外; StopIteration

@geindex __next__() (generator 方法)
@anchor{reference/expressions generator __next__}@anchor{143f}
@deffn {方法} generator.__next__ ()

开始一个生成器函数的执行或是从上次执行的 yield 表达式位置恢复执行。 当一个生成器函数通过 @ref{143f,,__next__()} 方法恢复执行时，当前的 yield 表达式总是取值为 @ref{204,,None}。 随后会继续执行到下一个 yield 表达式，其 @ref{1671,,expression_list} 的值会返回给 @ref{143f,,__next__()} 的调用者。 如果生成器没有产生下一个值就退出，则将引发 @ref{58a,,StopIteration} 异常。

此方法通常是隐式地调用，例如通过 @ref{d02,,for} 循环或是内置的 @ref{77f,,next()} 函数。
@end deffn

@geindex send() (generator 方法)
@anchor{reference/expressions generator send}@anchor{15fc}
@deffn {方法} generator.send (value)

恢复执行并向生成器函数“发送”一个值。 @emph{value} 参数将成为当前 yield 表达式的结果。 @ref{15fc,,send()} 方法会返回生成器所产生的下一个值，或者如果生成器没有产生下一个值就退出则会引发 @ref{58a,,StopIteration}。 当调用 @ref{15fc,,send()} 来启动生成器时，它必须以 @ref{204,,None} 作为调用参数，因为这时没有可以接收值的 yield 表达式。
@end deffn

@geindex throw() (generator 方法)
@anchor{reference/expressions generator throw}@anchor{1042}
@deffn {方法} generator.throw (value)

@deffnx {方法} generator.throw (type[, value[, traceback]])

在生成器暂停的位置引发一个异常，并返回该生成器函数所产生的下一个值。 如果生成器没有产生下一个值就退出，则将引发 @ref{58a,,StopIteration} 异常。 如果生成器函数没有捕获传入的异常，或是引发了另一个异常，则该异常会被传播给调用方。

在典型的使用场景下，其调用将附带单个异常实例，类似于使用 @ref{d12,,raise} 关键字的方式。

但是为了向下兼容性，也支持第二种签名，遵循来自旧版本 Python 的惯例。 @emph{type} 参数应为一个异常类，而 @emph{value} 应为一个异常实例。 如果未提供 @emph{value}，则将调用 @emph{type} 构造器来获取一个实例。 如果提供了 @emph{traceback}，它将被设置到异常上，否则任何存储在 @emph{value} 中的现有 @code{__traceback__} 属性都会被清空。
@end deffn

@geindex 例外; GeneratorExit

@geindex close() (generator 方法)
@anchor{reference/expressions generator close}@anchor{15ff}
@deffn {方法} generator.close ()

在生成器函数暂停的位置引发 @ref{e00,,GeneratorExit}。 如果之后生成器函数正常退出、关闭或引发 @ref{e00,,GeneratorExit} (由于未捕获该异常) 则关闭并返回其调用者。 如果生成器产生了一个值，关闭会引发 @ref{3e4,,RuntimeError}。 如果生成器引发任何其他异常，它会被传播给调用者。 如果生成器已经由于异常或正常退出则 @ref{15ff,,close()} 不会做任何事。
@end deffn

@geindex yield; examples

@node 示例,异步生成器函数,生成器-迭代器的方法,yield 表达式
@anchor{reference/expressions examples}@anchor{1673}
@subsubsection 示例


这里是一个简单的例子，演示了生成器和生成器函数的行为:

@example
>>> def echo(value=None):
...     print("Execution starts when 'next()' is called for the first time.")
...     try:
...         while True:
...             try:
...                 value = (yield value)
...             except Exception as e:
...                 value = e
...     finally:
...         print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
@end example

对于 @code{yield from} 的例子, 参见“Python 有什么新变化”中的 @ref{a62,,PEP 380; 委托给子生成器的语法}。

@node 异步生成器函数,异步生成器-迭代器方法,示例,yield 表达式
@anchor{reference/expressions asynchronous-generator-functions}@anchor{1670}@anchor{reference/expressions id3}@anchor{1674}
@subsubsection 异步生成器函数


在一个使用 @ref{3b1,,async def} 定义的函数或方法中出现的 yield 表达式会进一步将该函数定义为一个 @ref{166f,,asynchronous generator} 函数。

当一个异步生成器函数被调用时，它会返回一个名为异步生成器对象的异步迭代器。 此对象将在之后控制该生成器函数的执行。 异步生成器对象通常被用在协程函数的 @ref{406,,async for} 语句中，类似于在 @ref{d02,,for} 语句中使用生成器对象。

调用异步生成器的方法之一将返回 @ref{61b,,awaitable} 对象，执行会在此对象被等待时启动。 到那时，执行将前往第一个 yield 表达式，在那里它会再次暂停，将 @ref{1671,,expression_list} 的值返回给等待中的协程。 与生成器一样，挂起意味着局部的所有状态会被保留，包括局部变量的当前绑定、指令的指针、内部求值的堆栈以及任何异常处理的状态。 当执行在等待异步生成器的方法返回下一个对象后恢复时，该函数可以从原状态继续进行，就仿佛 yield 表达式只是另一个外部调用。 恢复执行之后 yield 表达式的值取决于恢复执行所用的方法。 如果使用 @ref{1675,,__anext__()} 则结果为 @ref{204,,None}。 否则的话，如果使用 @ref{177,,asend()} 则结果将是传递给该方法的值。

在异步生成器函数中，yield 表达式允许出现在 @ref{e3f,,try} 结构的任何位置。 但是，如果一个异步生成器在其被终结（由于引用计数达到零或被作为垃圾回收）之前未被恢复，则then a yield expression within a @code{try} 结构中的 yield 表达式可能导致挂起的 @ref{2c3,,finally} 子句执行失败。 在此情况下，应由运行该异步生成器的事件循环或任务调度器来负责调用异步生成器-迭代器的 @ref{176,,aclose()} 方法并运行所返回的协程对象，从而允许任何挂起的 @code{finally} 子句得以执行。

为了能处理最终化，事件循环应该定义一个 @emph{终结器} 函数，它接受一个异步生成器-迭代器且可能调用 @ref{176,,aclose()} 并执行协程。 这个  @emph{终结器} 可能通过调用 @ref{10a0,,sys.set_asyncgen_hooks()} 来注册。 当首次迭代时，异步生成器-迭代器将保存已注册的 @emph{终结器} 以便在最终化时调用。 有关For a reference example of a @emph{终结器} 方法的参考示例请查看 Lib/asyncio/base_events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py} 中实现的 @code{asyncio.Loop.shutdown_asyncgens}。

@code{yield from <expr>} 表达式如果在异步生成器函数中使用会引发语法错误。

@geindex 对象; asynchronous-generator

@node 异步生成器-迭代器方法,,异步生成器函数,yield 表达式
@anchor{reference/expressions asynchronous-generator-iterator-methods}@anchor{1676}@anchor{reference/expressions asynchronous-generator-methods}@anchor{1677}
@subsubsection 异步生成器-迭代器方法


这个子小节描述了异步生成器迭代器的方法，它们可被用于控制生成器函数的执行。

@geindex 例外; StopAsyncIteration

@geindex __anext__() (agen 方法)
@anchor{reference/expressions agen __anext__}@anchor{1675}
@deffn {方法} coroutine agen.__anext__ ()

返回一个可等待对象，它在运行时会开始执行该异步生成器或是从上次执行的 yield 表达式位置恢复执行。 当一个异步生成器函数通过 @ref{1675,,__anext__()} 方法恢复执行时，当前的 yield 表达式所返回的可等待对象总是取值为 @ref{204,,None}，它在运行时将继续执行到下一个 yield 表达式。 该 yield 表达式的 @ref{1671,,expression_list} 的值会是完成的协程所引发的 @ref{58a,,StopIteration} 异常的值。 如果异步生成器没有产生下一个值就退出，则该可等待对象将引发 @ref{1193,,StopAsyncIteration} 异常，提示该异步迭代操作已完成。

此方法通常是通过 @ref{406,,async for} 循环隐式地调用。
@end deffn

@geindex asend() (agen 方法)
@anchor{reference/expressions agen asend}@anchor{177}
@deffn {方法} coroutine agen.asend (value)

返回一个可等待对象，它在运行时会恢复该异步生成器的执行。 与生成器的 @ref{15fc,,send()} 方法一样，此方法会“发送”一个值给异步生成器函数，其 @emph{value} 参数会成为当前 yield 表达式的结果值。 @ref{177,,asend()} 方法所返回的可等待对象将返回生成器产生的下一个值，其值为所引发的 @ref{58a,,StopIteration}，或者如果异步生成器没有产生下一个值就退出则引发 @ref{1193,,StopAsyncIteration}。 当调用 @ref{177,,asend()} 来启动异步生成器时，它必须以 @ref{204,,None} 作为调用参数，因为这时没有可以接收值的 yield 表达式。
@end deffn

@geindex athrow() (agen 方法)
@anchor{reference/expressions agen athrow}@anchor{178}
@deffn {方法} coroutine agen.athrow (type[, value[, traceback]])

返回一个可等待对象，它会在异步生成器暂停的位置引发 @code{type} 类型的异常，并返回该生成器函数所产生的下一个值，其值为所引发的 @ref{58a,,StopIteration} 异常。 如果异步生成器没有产生下一个值就退出，则将由该可等待对象引发 @ref{1193,,StopAsyncIteration} 异步。 如果生成器函数没有捕获传入的异常，或引发了另一个异常，则当可等待对象运行时该异常会被传播给可等待对象的调用者。
@end deffn

@geindex 例外; GeneratorExit

@geindex aclose() (agen 方法)
@anchor{reference/expressions agen aclose}@anchor{176}
@deffn {方法} coroutine agen.aclose ()

返回一个可等待对象，它会在运行时向异步生成器函数暂停的位置抛入一个 @ref{e00,,GeneratorExit}。 如果该异步生成器函数正常退出、关闭或引发 @ref{e00,,GeneratorExit} (由于未捕获该异常) 则返回的可等待对象将引发 @ref{58a,,StopIteration} 异常。 后续调用异步生成器所返回的任何其他可等待对象将引发 @ref{1193,,StopAsyncIteration} 异常。 如果异步生成器产生了一个值，该可等待对象会引发 @ref{3e4,,RuntimeError}。 如果异步生成器引发任何其他异常，它会被传播给可等待对象的调用者。 如果异步生成器已经由于异常或正常退出则后续调用 @ref{176,,aclose()} 将返回一个不会做任何事的可等待对象。
@end deffn

@node 原型,await 表达式,原子,表达式
@anchor{reference/expressions id4}@anchor{1678}@anchor{reference/expressions primaries}@anchor{1679}
@subsection 原型


@geindex primary

原型代表编程语言中最紧密绑定的操作。 它们的句法如下:

@example
@anchor{reference/expressions grammar-token-primary}@anchor{167a}primary ::= atom | attributeref | subscription | slicing | call
@end example

@menu
* 属性引用:: 
* 抽取:: 
* 切片:: 
* 调用:: 

@end menu

@node 属性引用,抽取,,原型
@anchor{reference/expressions attribute-references}@anchor{167b}@anchor{reference/expressions id5}@anchor{167c}
@subsubsection 属性引用


@geindex attribute; reference
@geindex . (dot); attribute reference

属性引用是后面带有一个句点加一个名称的原型:

@example
@anchor{reference/expressions grammar-token-attributeref}@anchor{167d}attributeref ::= primary "." identifier
@end example

@geindex 例外; AttributeError
@geindex 对象; module
@geindex 对象; list

此原型必须求值为一个支持属性引用的类型的对象，多数对象都支持属性引用。 随后该对象会被要求产生以指定标识符为名称的属性。 这个产生过程可通过重载 @ref{433,,__getattr__()} 方法来自定义。 如果这个属性不可用，则将引发 @ref{4aa,,AttributeError} 异常。 否则的话，所产生对象的类型和值会根据该对象来确定。 对同一属性引用的多次求值可能产生不同的对象。

@node 抽取,切片,属性引用,原型
@anchor{reference/expressions id6}@anchor{167e}@anchor{reference/expressions subscriptions}@anchor{15bd}
@subsubsection 抽取


@geindex subscription
@geindex [] (square brackets); subscription

@geindex 对象; sequence
@geindex 对象; mapping
@geindex 对象; string
@geindex 对象; tuple
@geindex 对象; list
@geindex 对象; dictionary
@geindex sequence; item

对一个 @ref{15c3,,容器类} 的实例执行抽取操作通常将会从该容器中选取一个元素。 而对一个 @ref{1035,,泛型类} 执行抽取操作通常将会返回一个 @ref{1030,,GenericAlias} 对象。

@example
@anchor{reference/expressions grammar-token-subscription}@anchor{167f}subscription ::= primary "[" expression_list "]"
@end example

当一个对象被抽取时，解释器将对原型和表达式列表进行求值。

原型必须可被求值为一个支持抽取操作的对象。 一个对象可通过同时定义 @ref{3ad,,__getitem__()} 和 @ref{440,,__class_getitem__()} 或其中之一来支持抽取操作。 当原型被抽取时，表达式列表的求值结果将被传给以上方法中的一个。 对于在何时会调用 @code{__class_getitem__} 而不是 @code{__getitem__} 的更多细节，请参阅 @ref{15bc,,__class_getitem__ 与 __getitem__}。

如果表达式列表包含至少一个逗号，它将被求值为包含该表达式列表中所有条目的 @ref{1a2,,tuple}。 在其他情况下，表达式列表将被求值为列表中唯一成员的值。

对于内置对象，有两种类型的对象支持通过 @ref{3ad,,__getitem__()} 执行抽取操作:


@enumerate 

@item 
映射。 如果原型是一个 @ref{c14,,mapping}，则表达式列表必须求值为一个以该映射的某个键为值的对象，而抽取操作会在映射中选取该键所对应的值。 内置映射类的一个例子是 @ref{164,,dict} 类。

@item 
序列。 如果原型是一个 @ref{138b,,sequence}，则表达式列表必须求值为一个 @ref{205,,int} 或一个 @ref{ed0,,slice} (如下面的小节所讨论的)。 内置序列类的例子包括 @ref{206,,str}, @ref{1f9,,list} 和 @ref{1a2,,tuple} 等类。
@end enumerate

正式语法规则并未在 @ref{138b,,序列} 中设置负索引号的特殊保留条款。 不过，内置序列都提供了通过给索引号加上序列长度来解读负索引号的 @ref{3ad,,__getitem__()} 方法，因此举例来说，@code{x[-1]} 将选取 @code{x} 的最后一项。 结果值必须为一个小于序列中条目数的非负整数，抽取操作会选取索引号为该值的条目（从零开始计数）。 由于对负索引号和切片的支持位于对象的 @ref{3ad,,__getitem__()} 方法中，因而重载此方法的子类将需要显式地添加这种支持。

@geindex character
@geindex string; item

@ref{206,,字符串} 是一种特殊的序列，其中的项是 @emph{字符}。 字符并不是一种单独的数据类型而是长度恰好为一个字符的字符串。

@node 切片,调用,抽取,原型
@anchor{reference/expressions id7}@anchor{1680}@anchor{reference/expressions slicings}@anchor{1681}
@subsubsection 切片


@geindex slicing
@geindex slice
@geindex ; (colon); slicing
@geindex @comma{} (comma); slicing

@geindex 对象; sequence
@geindex 对象; string
@geindex 对象; tuple
@geindex 对象; list

切片就是在序列对象（字符串、元组或列表）中选择某个范围内的项。 切片可被用作表达式以及赋值或 @ref{13d1,,del} 语句的目标。 切片的句法如下:

@example
@anchor{reference/expressions grammar-token-slicing}@anchor{1682}slicing      ::= primary "[" slice_list "]"
@anchor{reference/expressions grammar-token-slice-list}@anchor{1683}slice_list   ::= slice_item ("," slice_item)* [","]
@anchor{reference/expressions grammar-token-slice-item}@anchor{1684}slice_item   ::= expression | proper_slice
@anchor{reference/expressions grammar-token-proper-slice}@anchor{1685}proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
@anchor{reference/expressions grammar-token-lower-bound}@anchor{1686}lower_bound  ::= expression
@anchor{reference/expressions grammar-token-upper-bound}@anchor{1687}upper_bound  ::= expression
@anchor{reference/expressions grammar-token-stride}@anchor{1688}stride       ::= expression
@end example

此处的正式句法中存在一点歧义：任何形似表达式列表的东西同样也会形似切片列表，因此任何抽取操作也可以被解析为切片。 为了不使句法更加复杂，于是通过定义将此情况解析为抽取优先于解析为切片来消除这种歧义（切片列表未包含正确的切片就属于此情况）。

@geindex start (slice object attribute)
@geindex stop (slice object attribute)
@geindex step (slice object attribute)

切片的语义如下所述。 元型通过一个根据下面的切片列表来构造的键进行索引（与普通抽取一样使用 @ref{3ad,,__getitem__()} 方法）。 如果切片列表包含至少一个逗号，则键将是一个包含切片项转换的元组；否则的话，键将是单个切片项的转换。 切片项如为一个表达式，则其转换就是该表达式。 一个正确切片的转换就是一个切片对象（参见 @ref{1582,,标准类型层级结构} 一节），该对象的 @code{start}, @code{stop} 和 @code{step} 属性将分别为表达式所给出的下界、上界和步长值，省略的表达式将用 @code{None} 来替换。

@geindex 对象; callable
@geindex call
@geindex argument; call semantics
@geindex () (parentheses); call
@geindex @comma{} (comma); argument list
@geindex = (equals); in function calls

@node 调用,,切片,原型
@anchor{reference/expressions calls}@anchor{749}@anchor{reference/expressions id8}@anchor{1689}
@subsubsection 调用


所谓调用就是附带可能为空的一系列 @ref{168a,,参数} 来执行一个可调用对象 (例如 @ref{168b,,function}):

@example
@anchor{reference/expressions grammar-token-call}@anchor{168c}call                 ::= primary "(" [argument_list [","] | comprehension] ")"
@anchor{reference/expressions grammar-token-argument-list}@anchor{168d}argument_list        ::= positional_arguments ["," starred_and_keywords]
                           ["," keywords_arguments]
                         | starred_and_keywords ["," keywords_arguments]
                         | keywords_arguments
@anchor{reference/expressions grammar-token-positional-arguments}@anchor{168e}positional_arguments ::= positional_item ("," positional_item)*
@anchor{reference/expressions grammar-token-positional-item}@anchor{168f}positional_item      ::= assignment_expression | "*" expression
@anchor{reference/expressions grammar-token-starred-and-keywords}@anchor{1690}starred_and_keywords ::= ("*" expression | keyword_item)
                         ("," "*" expression | "," keyword_item)*
@anchor{reference/expressions grammar-token-keywords-arguments}@anchor{1691}keywords_arguments   ::= (keyword_item | "**" expression)
                         ("," keyword_item | "," "**" expression)*
@anchor{reference/expressions grammar-token-keyword-item}@anchor{1692}keyword_item         ::= identifier "=" expression
@end example

一个可选项为在位置和关键字参数后加上逗号而不影响语义。

@geindex parameter; call semantics

此原型必须求值为一个可调用对象（用户定义的函数，内置函数，内置对象的方法，类对象，类实例的方法以及任何具有 @ref{158f,,__call__()} 方法的对象都是可调用对象）。 所有参数表达式将在尝试调用前被求值。 请参阅 @ref{13bf,,函数定义} 一节了解正式的 @ref{1693,,parameter} 列表句法。

@c XXX update with kwonly args PEP

如果存在关键字参数，它们会先通过以下操作被转换为位置参数。 首先，为正式参数创建一个未填充空位的列表. 如果有 N 个位置参数，则将它们放入前 N 个空位。 然后，对于每个关键字参数，使用标识符来确定其对应的空位（如果标识符与第一个正式参数名相同则使用第一个个空位，依此类推）。 如果空位已被填充，则会引发 @ref{1ff,,TypeError} 异常。 否则，将参数值放入空位进行填充（即使表达式为 @code{None} 也会填充空位）。 当所有参数处理完毕时，尚未填充的空位将用来自函数定义的相应默认值来填充。 （函数一旦定义其参数默认值就会被计算；因此，当列表或字典这类可变对象被用作默认值时，将会被所有未指定相应空位参数值的调用所共享；这种情况通常应当避免。） 如果任何一个未填充空位没有指定默认值，则会引发 @ref{1ff,,TypeError} 异常。 否则的话，已填充空位的列表会被作为调用的参数列表。

@strong{CPython implementation detail:} 某些实现可能提供位置参数没有名称的内置函数，即使它们在文档说明的场合下有“命名”，因此不能以关键字形式提供参数。 在 CPython 中，以 C 编写并使用 @ref{39b,,PyArg_ParseTuple()} 来解析其参数的函数实现就属于这种情况。

如果存在比正式参数空位多的位置参数，将会引发 @ref{1ff,,TypeError} 异常，除非有一个正式参数使用了 @code{*identifier} 句法；在此情况下，该正式参数将接受一个包含了多余位置参数的元组（如果没有多余位置参数则为一个空元组）。

如果任何关键字参数没有与之对应的正式参数名称，将会引发 @ref{1ff,,TypeError} 异常，除非有一个正式参数使用了 @code{**identifier} 句法，该正式参数将接受一个包含了多余关键字参数的字典（使用关键字作为键而参数值作为与键对应的值），如果没有多余关键字参数则为一个（新的）空字典。

@geindex * (asterisk); in function calls
@geindex unpacking; in function calls

如果函数调用中出现了 @code{*expression} 句法，@code{expression} 必须求值为一个 @ref{c84,,iterable}。 来自该可迭代对象的元素会被当作是额外的位置参数。 对于 @code{f(x1, x2, *y, x3, x4)} 调用，如果 @emph{y} 求值为一个序列 @emph{y1}, ..., @emph{yM}，则它就等价于一个带有 M+4 个位置参数 @emph{x1}, @emph{x2}, @emph{y1}, ..., @emph{yM}, @emph{x3}, @emph{x4} 的调用。

这样做的一个后果是虽然 @code{*expression} 句法可能出现于显式的关键字参数 @emph{之后}，但它会在关键字参数（以及任何 @code{**expression} 参数 -- 见下文） @emph{之前} 被处理。 因此:

@example
>>> def f(a, b):
...     print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
@end example

在同一个调用中同时使用关键字参数和 @code{*expression} 句法并不常见，因此实际上这样的混淆不会发生。

@geindex **; in function calls

如果函数调用中出现了 @code{**expression} 句法，@code{expression} 必须求值为一个 @ref{c14,,mapping}，其内容会被当作是额外的关键字参数。 如果一个关键字已存在（作为显式关键字参数，或来自另一个拆包），则将引发 @ref{1ff,,TypeError} 异常。

使用 @code{*identifier} 或 @code{**identifier} 句法的正式参数不能被用作位置参数空位或关键字参数名称。


在 3.5 版更改: 函数调用接受任意数量的 @code{*} 和 @code{**} 拆包，位置参数可能跟在可迭代对象拆包 (@code{*}) 之后，而关键字参数可能跟在字典拆包 (@code{**}) 之后。 由 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} 发起最初提议。


除非引发了异常，调用总是会有返回值，返回值也可能为 @code{None}。 返回值的计算方式取决于可调用对象的类型。

如果类型为---


@table @asis

@item 用户自定义函数:

@geindex function; call
@geindex user-defined; function; call
@geindex 对象; user-defined function
@geindex 对象; function

函数的代码块会被执行，并向其传入参数列表。 代码块所做的第一件事是将正式形参绑定到对应参数；相关描述参见 @ref{13bf,,函数定义} 一节。 当代码块执行 @ref{2cf,,return} 语句时，由其指定函数调用的返回值。

@item 内置函数或方法:

@geindex function; call
@geindex built-in function; call
@geindex method; call
@geindex built-in method; call
@geindex 对象; built-in method
@geindex 对象; built-in function
@geindex 对象; method
@geindex 对象; function

具体结果依赖于解释器；有关内置函数和方法的描述参见 @ref{cc6,,内置函数}。

@item 类对象:

@geindex 对象; class
@geindex class object; call

返回该类的一个新实例。

@item 类实例方法:

@geindex 对象; class instance
@geindex 对象; instance
@geindex class instance; call

调用相应的用户自定义函数，向其传入的参数列表会比调用的参数列表多一项：该实例将成为第一个参数。

@item 类实例:

@geindex instance; call
@geindex __call__() (object method)

该类必须定义有 @ref{158f,,__call__()} 方法；作用效果将等价于调用该方法。
@end table

@geindex 关键字; await

@node await 表达式,幂运算符,原型,表达式
@anchor{reference/expressions await}@anchor{2df}@anchor{reference/expressions await-expression}@anchor{1694}
@subsection await 表达式


挂起 @ref{18a,,coroutine} 的执行以等待一个 @ref{61b,,awaitable} 对象。 只能在 @ref{73c,,coroutine function} 内部使用。

@example
@anchor{reference/expressions grammar-token-await-expr}@anchor{1695}await_expr ::= "await" primary
@end example


3.5 新版功能.


@node 幂运算符,一元算术和位运算,await 表达式,表达式
@anchor{reference/expressions power}@anchor{1696}@anchor{reference/expressions the-power-operator}@anchor{1697}
@subsection 幂运算符


@geindex power; operation
@geindex 运算符; **

幂运算符的绑定比在其左侧的一元运算符更紧密；但绑定紧密程度不及在其右侧的一元运算符。 句法如下:

@example
@anchor{reference/expressions grammar-token-power}@anchor{1698}power ::= (await_expr | primary) ["**" u_expr]
@end example

因此，在一个未加圆括号的幂运算符和单目运算符序列中，运算符将从右向左求值（这不会限制操作数的求值顺序）: @code{-1**2} 结果将为 @code{-1}。

幂运算符与附带两个参数调用内置 @ref{2d6,,pow()} 函数具有相同的语义：结果为对其左参数进行其右参数所指定幂次的乘方运算。 数值参数会先转换为相同类型，结果也为转换后的类型。

对于 int 类型的操作数，结果将具有与操作数相同的类型，除非第二个参数为负数；在那种情况下，所有参数会被转换为 float 类型并输出 float 类型的结果。 例如，@code{10**2} 返回 @code{100}，而 @code{10**-2} 返回 @code{0.01}。

对 @code{0.0} 进行负数幂次运算将导致 @ref{1fb,,ZeroDivisionError}。 对负数进行分数幂次运算将返回 @ref{2c8,,complex} 数值。 （在早期版本中这将引发 @ref{16d,,ValueError}。）

此运算符可使用特殊的 @ref{15d0,,__pow__()} 方法来自定义。

@node 一元算术和位运算,二元算术运算符,幂运算符,表达式
@anchor{reference/expressions unary}@anchor{1699}@anchor{reference/expressions unary-arithmetic-and-bitwise-operations}@anchor{169a}
@subsection 一元算术和位运算


@geindex unary; arithmetic; operation
@geindex unary; bitwise; operation

所有算术和位运算具有相同的优先级:

@example
@anchor{reference/expressions grammar-token-u-expr}@anchor{169b}u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
@end example

@geindex negation
@geindex minus
@geindex operator; - (minus)
@geindex - (minus); unary operator

单目的 @code{-} (负值) 运算符会产生其数字参数的负值；该运算可通过 @ref{15ea,,__neg__()} 特殊方法来重载。

@geindex plus
@geindex operator; + (plus)
@geindex + (plus); unary operator

单目的 @code{+} (正值) 运算符会原样输出其数字参数；该运算可通过 @ref{15eb,,__pos__()} 特殊方法来重载。

@geindex inversion
@geindex 运算符; ~ (tilde)

单目的 @code{~} (取反) 运算符会对其整数参数按位取反。 @code{x} 的按位取反被定义为 @code{-(x+1)}。 它只作用于整数或是重载了 @ref{15ed,,__invert__()} 特殊方法的自定义对象。

@geindex 例外; TypeError

在所有三种情况下，如果参数的类型不正确，将引发 @ref{1ff,,TypeError} 异常。

@node 二元算术运算符,移位运算,一元算术和位运算,表达式
@anchor{reference/expressions binary}@anchor{169c}@anchor{reference/expressions binary-arithmetic-operations}@anchor{169d}
@subsection 二元算术运算符


@geindex binary; arithmetic; operation

二元算术运算符遵循传统的优先级。 请注意某些此类运算符也作用于特定的非数字类型。 除幂运算符以外只有两个优先级别，一个作用于乘法型运算符，另一个作用于加法型运算符:

@example
@anchor{reference/expressions grammar-token-m-expr}@anchor{169e}m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@@" m_expr |
           m_expr "//" u_expr | m_expr "/" u_expr |
           m_expr "%" u_expr
@anchor{reference/expressions grammar-token-a-expr}@anchor{169f}a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr
@end example

@geindex multiplication
@geindex 运算符; * (asterisk)

运算符 @code{*} (乘) 将输出其参数的乘积。 两个参数或者必须都为数字，或者一个参数必须为整数而另一个参数必须为序列。 在前一种情况下，两个数字将被转换为相同类型然后相乘。 在后一种情况下，将执行序列的重复；重复因子为负数将输出空序列。

此运算可使用特殊的 @ref{15c6,,__mul__()} 和 @ref{15c7,,__rmul__()} 方法来自定义。

@geindex matrix multiplication
@geindex 运算符; @@ (at)

运算符 @code{@@} (at) 的目标是用于矩阵乘法。 没有内置 Python 类型实现此运算符。


3.5 新版功能.


@geindex 例外; ZeroDivisionError
@geindex division
@geindex 运算符; / (slash)
@geindex 运算符; //

运算符 @code{/} (除) 和 @code{//} (整除) 将输出其参数的商。 两个数字参数将先被转换为相同类型。 整数相除会输出一个 float 值，整数相整除的结果仍是整数；整除的结果就是使用 'floor' 函数进行算术除法的结果。 除以零的运算将引发 @ref{1fb,,ZeroDivisionError} 异常。

此运行可使用特殊的 @ref{87f,,__truediv__()} 和 @ref{eff,,__floordiv__()} 方法来自定义。

@geindex modulo
@geindex 运算符; % (percent)

运算符 @code{%} (模) 将输出第一个参数除以第二个参数的余数。 两个数字参数将先被转换为相同类型。 右参数为零将引发 @ref{1fb,,ZeroDivisionError} 异常。 参数可以为浮点数，例如 @code{3.14%0.7} 等于 @code{0.34} (因为 @code{3.14} 等于 @code{4*0.7 + 0.34})。 模运算符的结果的正负总是与第二个操作数一致（或是为零）；结果的绝对值一定小于第二个操作数的绝对值 @footnote{@w{(1)} 
虽然 @code{abs(x%y) < abs(y)} 在数学中必为真，但对于浮点数而言，由于舍入的存在，其在数值上未必为真。 例如，假设在某个平台上的 Python 浮点数为一个 IEEE 754 双精度数值，为了使 @code{-1e-100 % 1e100} 具有与 @code{1e100} 相同的正负性，计算结果将是 @code{-1e-100 + 1e100}，这在数值上正好等于 @code{1e100}。 函数 @ref{16a0,,math.fmod()} 返回的结果则会具有与第一个参数相同的正负性，因此在这种情况下将返回 @code{-1e-100}。 何种方式更适宜取决于具体的应用。
}。

整除与模运算符的联系可通过以下等式说明: @code{x == (x//y)*y + (x%y)}。 此外整除与模也可通过内置函数 @ref{294,,divmod()} 来同时进行: @code{divmod(x, y) == (x//y, x%y)}。 @footnote{@w{(2)} 
如果 x 恰好非常接近于 y 的整数倍，则由于舍入的存在 @code{x//y} 可能会比 @code{(x-x%y)//y} 大。 在这种情况下，Python 会返回后一个结果，以便保持令 @code{divmod(x,y)[0] * y + x % y} 尽量接近 @code{x}.
}。

除了对数字执行模运算，运算符 @code{%} 还被字符串对象重载用于执行旧式的字符串格式化（又称插值）。 字符串格式化句法的描述参见 Python 库参考的 @ref{1388,,printf 风格的字符串格式化} 一节。

@emph{取余} 运算可使用特殊的 @ref{15cf,,__mod__()} 方法来自定义。

整除运算符，模运算符和 @ref{294,,divmod()} 函数未被定义用于复数。 如果有必要可以使用 @ref{1424,,abs()} 函数将其转换为浮点数。

@geindex addition
@geindex operator; + (plus)
@geindex + (plus); binary operator

运算符 @code{+} (addition) 将输出其参数的和。 两个参数或者必须都为数字，或者都为相同类型的序列。 在前一种情况下，两个数字将被转换为相同类型然后相加。 在后一种情况下，将执行序列拼接操作。

此运算可使用特殊的 @ref{15c4,,__add__()} 和 @ref{15c5,,__radd__()} 方法来自定义。

@geindex subtraction
@geindex operator; - (minus)
@geindex - (minus); binary operator

运算符 @code{-} (减) 将输出其参数的差。 两个数字参数将先被转换为相同类型。

此运算可使用特殊的 @ref{15ce,,__sub__()} 方法来自定义。

@node 移位运算,二元位运算,二元算术运算符,表达式
@anchor{reference/expressions shifting}@anchor{16a1}@anchor{reference/expressions shifting-operations}@anchor{16a2}
@subsection 移位运算


@geindex shifting; operation
@geindex 运算符; <<
@geindex 运算符; >>

移位运算的优先级低于算术运算:

@example
@anchor{reference/expressions grammar-token-shift-expr}@anchor{16a3}shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr
@end example

这些运算符接受整数参数。 它们会将第一个参数左移或右移第二个参数所指定的比特位数。

此运算可使用特殊的 @ref{15d1,,__lshift__()} 和 @ref{15d2,,__rshift__()} 方法来自定义。

@geindex 例外; ValueError

右移 @emph{n} 位被定义为被 @code{pow(2,n)} 整除。 左移 @emph{n} 位被定义为乘以 @code{pow(2,n)}。

@node 二元位运算,比较运算,移位运算,表达式
@anchor{reference/expressions binary-bitwise-operations}@anchor{16a4}@anchor{reference/expressions bitwise}@anchor{16a5}
@subsection 二元位运算


@geindex binary; bitwise; operation

三种位运算具有各不相同的优先级:

@example
@anchor{reference/expressions grammar-token-and-expr}@anchor{16a6}and_expr ::= shift_expr | and_expr "&" shift_expr
@anchor{reference/expressions grammar-token-xor-expr}@anchor{16a7}xor_expr ::= and_expr | xor_expr "^" and_expr
@anchor{reference/expressions grammar-token-or-expr}@anchor{16a8}or_expr  ::= xor_expr | or_expr "|" xor_expr
@end example

@geindex bitwise; and
@geindex 运算符; & (ampersand)

@code{&} 运算符会对其参数执行按位 AND，参数必须都为整数或者其中之一必须为重载了 @ref{15d3,,__and__()} 或 @ref{15dd,,__rand__()} 特殊方法的自定义对象。

@geindex bitwise; xor
@geindex exclusive; or
@geindex 运算符; ^ (caret)

@code{^} 运算符会对其参数执行按位 XOR (异 OR)，参数必须都为整数或者其中之一必须为重载了 @ref{15d4,,__xor__()} 或 @ref{15de,,__rxor__()} 特殊方法的自定义对象。

@geindex bitwise; or
@geindex inclusive; or
@geindex 运算符; | (vertical bar)

@code{|} 运算符会对其参数执行按位 (合并) OR，参数必须都为整数或者其中之一必须为重载了 @ref{15d5,,__or__()} 或 @ref{15df,,__ror__()} 特殊方法的自定义对象。

@node 比较运算,布尔运算,二元位运算,表达式
@anchor{reference/expressions comparisons}@anchor{16a9}@anchor{reference/expressions id11}@anchor{16aa}
@subsection 比较运算


@geindex comparison
@geindex C; language
@geindex 运算符; < (less)
@geindex 运算符; > (greater)
@geindex 运算符; <=
@geindex 运算符; >=
@geindex 运算符; ==
@geindex 运算符; !=

与 C 不同，Python 中所有比较运算的优先级相同，低于任何算术、移位或位运算。 另一个与 C 不同之处在于 @code{a < b < c} 这样的表达式会按传统算术法则来解读:

@example
@anchor{reference/expressions grammar-token-comparison}@anchor{16ab}comparison    ::= or_expr (comp_operator or_expr)*
@anchor{reference/expressions grammar-token-comp-operator}@anchor{16ac}comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
                  | "is" ["not"] | ["not"] "in"
@end example

比较运算会产生布尔值: @code{True} 或 @code{False}。 自定义的 @emph{富比较方法} 可能返回非布尔值。 在此情况下 Python 将在布尔运算上下文中对该值调用 @ref{2c4,,bool()}。

@geindex chaining; comparisons

比较运算可以任意串连，例如 @code{x < y <= z} 等价于 @code{x < y and y <= z}，除了 @code{y} 只被求值一次（但在两种写法下当 @code{x < y} 值为假时 @code{z} 都不会被求值）。

正式的说法是这样：如果 @emph{a}, @emph{b}, @emph{c}, ..., @emph{y}, @emph{z} 为表达式而 @emph{op1}, @emph{op2}, ..., @emph{opN} 为比较运算符，则 @code{a op1 b op2 c ... y opN z} 就等价于 @code{a op1 b and b op2 c and ... y opN z}，不同点在于每个表达式最多只被求值一次。

请注意 @code{a op1 b op2 c} 不意味着在 @emph{a} 和 @emph{c} 之间进行任何比较，因此，如 @code{x < y > z} 这样的写法是完全合法的（虽然也许不太好看）。

@menu
* 值比较:: 
* 成员检测运算:: 
* 标识号比较:: 

@end menu

@node 值比较,成员检测运算,,比较运算
@anchor{reference/expressions value-comparisons}@anchor{16ad}
@subsubsection 值比较


运算符 @code{<}, @code{>}, @code{==}, @code{>=}, @code{<=} 和 @code{!=} 将比较两个对象的值。 两个对象不要求为相同类型。

@ref{157e,,对象、值与类型} 一章已说明对象都有相应的值（还有类型和标识号）。 对象值在 Python 中是一个相当抽象的概念：例如，对象值并没有一个规范的访问方法。 而且，对象值并不要求具有特定的构建方式，例如由其全部数据属性组成等。 比较运算符实现了一个特定的对象值概念。 人们可以认为这是通过实现对象比较间接地定义了对象值。

由于所有类型都是 @ref{3da,,object} 的（直接或间接）子类型，它们都从 @ref{3da,,object} 继承了默认的比较行为。 类型可以通过实现 @emph{丰富比较方法} 例如 @ref{d06,,__lt__()} 来定义自己的比较行为，详情参见 @ref{1597,,基本定制}。

默认的一致性比较 (@code{==} 和 @code{!=}) 是基于对象的标识号。 因此，具有相同标识号的实例一致性比较结果为相等，具有不同标识号的实例一致性比较结果为不等。 规定这种默认行为的动机是希望所有对象都应该是自反射的 (即 @code{x is y} 就意味着 @code{x == y})。

次序比较 (@code{<}, @code{>}, @code{<=} 和 @code{>=}) 默认没有提供；如果尝试比较会引发 @ref{1ff,,TypeError}。 规定这种默认行为的原因是缺少与一致性比较类似的固定值。

按照默认的一致性比较行为，具有不同标识号的实例总是不相等，这可能不适合某些对象值需要有合理定义并有基于值的一致性的类型。 这样的类型需要定制自己的比较行为，实际上，许多内置类型都是这样做的。

以下列表描述了最主要内置类型的比较行为。


@itemize *

@item 
内置数值类型 (@ref{1382,,数字类型 --- int@comma{} float@comma{} complex}) 以及标准库类型 @ref{2c5,,fractions.Fraction} 和 @ref{2c7,,decimal.Decimal} 可进行类型内部和跨类型的比较，例外限制是复数不支持次序比较。 在类型相关的限制以内，它们会按数学（算法）规则正确进行比较且不会有精度损失。

非数字值 @code{float('NaN')} 和 @code{decimal.Decimal('NaN')} 属于特例。 任何数字与非数字值的排序比较均返回假值。 还有一个反直觉的结果是非数字值不等于其自身。 举例来说，如果 @code{x = float('NaN')} 则 @code{3 < x}, @code{x < 3} 和 @code{x == x} 均为假值，而 @code{x != x} 则为真值。 此行为是遵循 IEEE 754 标准的。

@item 
@code{None} 和 @code{NotImplemented} 都是单例对象。 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 建议单例对象的比较应当总是通过 @code{is} 或 @code{is not} 而不是等于运算符来进行。

@item 
二进制码序列 (@ref{172,,bytes} 或 @ref{173,,bytearray} 的实例) 可进行类型内部和跨类型的比较。 它们使用其元素的数字值按字典顺序进行比较。

@item 
字符串 (@ref{206,,str} 的实例) 使用其字符的 Unicode 码位数字值 (内置函数 @ref{1588,,ord()} 的结果) 按字典顺序进行比较。 @footnote{@w{(3)} 
Unicode 标准明确区分 @emph{码位} (例如 U+0041) 和 @emph{抽象字符} (例如 "大写拉丁字母 A")。 虽然 Unicode 中的大多数抽象字符都只用一个码位来代表，但也存在一些抽象字符可使用由多个码位组成的序列来表示。 例如，抽象字符 "带有下加符的大写拉丁字母 C" 可以用 U+00C7 码位上的单个 @emph{预设字符} 来表示，也可以用一个 U+0043 码位上的 @emph{基础字符} (大写拉丁字母 C) 加上一个 U+0327 码位上的 @emph{组合字符} (组合下加符) 组成的序列来表示。

对于字符串，比较运算符会按 Unicode 码位级别进行比较。 这可能会违反人类的直觉。 例如，@code{"\u00C7" == "\u0043\u0327"} 为 @code{False}，虽然两个字符串都代表同一个抽象字符 "带有下加符的大写拉丁字母 C"。

要按抽象字符级别（即对人类来说更直观的方式）对字符串进行比较，应使用 @ref{122c,,unicodedata.normalize()}。
}

字符串和二进制码序列不能直接比较。

@item 
序列 (@ref{1a2,,tuple}, @ref{1f9,,list} 或 @ref{1f6,,range} 的实例) 只可进行类型内部的比较，range 还有一个限制是不支持次序比较。 以上对象的跨类型一致性比较结果将是不相等，跨类型次序比较将引发 @ref{1ff,,TypeError}。

序列比较是按字典序对相应元素进行逐个比较。 内置容器通常设定同一对象与其自身是相等的。 这使得它们能跳过同一对象的相等性检测以提升运行效率并保持它们的内部不变性。

内置多项集间的字典序比较规则如下:


@itemize -

@item 
两个多项集若要相等，它们必须为相同类型、相同长度，并且每对相应的元素都必须相等（例如，@code{[1,2] == (1,2)} 为假值，因为类型不同）。

@item 
对于支持次序比较的多项集，排序与其第一个不相等元素的排序相同（例如 @code{[1,2,x] <= [1,2,y]} 的值与`@w{`}x <= y`@w{`} 相同）。 如果对应元素不存在，较短的多项集排序在前（例如 @code{[1,2] < [1,2,3]} 为真值）。
@end itemize

@item 
两个映射 (@ref{164,,dict} 的实例) 若要相等，必须当且仅当它们具有相同的 @cite{(键@comma{} 值)} 对。 键和值的一致性比较强制规定自反射性。

次序比较 (@code{<}, @code{>}, @code{<=} 和 @code{>=}) 将引发 @ref{1ff,,TypeError}。

@item 
集合 (@ref{1f7,,set} 或 @ref{1f8,,frozenset} 的实例) 可进行类型内部和跨类型的比较。

它们将比较运算符定义为子集和超集检测。 这类关系没有定义完全排序（例如 @code{@{1,2@}} 和 @code{@{2,3@}} 两个集合不相等，即不为彼此的子集，也不为彼此的超集。 相应地，集合不适宜作为依赖于完全排序的函数的参数（例如如果给出一个集合列表作为 @ref{900,,min()}, @ref{901,,max()} 和 @ref{54f,,sorted()} 的输入将产生未定义的结果）。

集合的比较强制规定其元素的自反射性。

@item 
大多数其他内置类型没有实现比较方法，因此它们会继承默认的比较行为。
@end itemize

在可能的情况下，用户定义类在定制其比较行为时应当遵循一些一致性规则:


@itemize *

@item 
相等比较应该是自反射的。 换句话说，相同的对象比较时应该相等:

@quotation

@code{x is y} 意味着 @code{x == y}
@end quotation

@item 
比较应该是对称的。 换句话说，下列表达式应该有相同的结果:

@quotation

@code{x == y} 和 @code{y == x}

@code{x != y} 和 @code{y != x}

@code{x < y} 和 @code{y > x}

@code{x <= y} 和 @code{y >= x}
@end quotation

@item 
比较应该是可传递的。 下列（简要的）例子显示了这一点:

@quotation

@code{x > y and y > z} 意味着 @code{x > z}

@code{x < y and y <= z} 意味着 @code{x < z}
@end quotation

@item 
反向比较应该导致布尔值取反。 换句话说，下列表达式应该有相同的结果:

@quotation

@code{x == y} 和 @code{not x != y}

@code{x < y} 和 @code{not x >= y} (对于完全排序)

@code{x > y} 和 @code{not x <= y} (对于完全排序)
@end quotation

最后两个表达式适用于完全排序的多项集（即序列而非集合或映射）。 另请参阅 @ref{942,,total_ordering()} 装饰器。

@item 
@ref{aac,,hash()} 的结果应该与是否相等一致。 相等的对象应该或者具有相同的哈希值，或者标记为不可哈希。
@end itemize

Python 并不强制要求这些一致性规则。 实际上，非数字值就是一个不遵循这些规则的例子。
@anchor{reference/expressions in}@anchor{179}@anchor{reference/expressions not-in}@anchor{15ca}
@node 成员检测运算,标识号比较,值比较,比较运算
@anchor{reference/expressions membership-test-details}@anchor{15cb}@anchor{reference/expressions membership-test-operations}@anchor{16ae}
@subsubsection 成员检测运算


运算符 @ref{179,,in} 和 @ref{15ca,,not in} 用于成员检测。 如果 @emph{x} 是 @emph{s} 的成员则 @code{x in s} 求值为 @code{True}，否则为 @code{False}。 @code{x not in s} 返回 @code{x in s} 取反后的值。 所有内置序列和集合类型以及字典都支持此运算，对于字典来说 @code{in} 检测其是否有给定的键。 对于 list, tuple, set, frozenset, dict 或 collections.deque 这样的容器类型，表达式 @code{x in y} 等价于 @code{any(x is e or x == e for e in y)}。

对于字符串和字节串类型来说，当且仅当 @emph{x} 是 @emph{y} 的子串时 @code{x in y} 为 @code{True}。 一个等价的检测是 @code{y.find(x) != -1}。 空字符串总是被视为任何其他字符串的子串，因此 @code{"" in "abc"} 将返回 @code{True}。

对于定义了 @ref{df6,,__contains__()} 方法的用户自定义类来说，如果 @code{y.__contains__(x)} 返回真值则 @code{x in y} 返回 @code{True}，否则返回 @code{False}。

对于未定义 @ref{df6,,__contains__()} 但定义了 @ref{611,,__iter__()} 的用户自定义类来说，如果在对 @code{y} 进行迭代时产生了值 @code{z} 使得表达式 @code{x is z or x == z} 为真，则 @code{x in y} 为 @code{True}。 如果在迭代期间引发了异常，则等同于 @ref{179,,in} 引发了该异常。

最后将会尝试旧式的迭代协议：如果一个类定义了 @ref{3ad,,__getitem__()}，则当且仅当存在非负整数索引号 @emph{i} 使得 @code{x is y[i] or x == y[i]} 并且没有更小的索引号引发 @ref{f3d,,IndexError} 异常时 @code{x in y} 为 @code{True}。 （如果引发了任何其他异常，则等同于 @ref{179,,in} 引发了该异常）。

@geindex 运算符; in
@geindex 运算符; not in
@geindex membership; test
@geindex 对象; sequence

运算符 @ref{15ca,,not in} 被定义为具有与 @ref{179,,in} 相反的逻辑值。

@geindex 运算符; is
@geindex 运算符; is not
@geindex identity; test
@anchor{reference/expressions is}@anchor{1580}
@node 标识号比较,,成员检测运算,比较运算
@anchor{reference/expressions identity-comparisons}@anchor{16af}@anchor{reference/expressions is-not}@anchor{16b0}
@subsubsection 标识号比较


运算符 @ref{1580,,is} 和 @ref{16b0,,is not} 用于检测对象的标识号：当且仅当 @emph{x} 和 @emph{y} 是同一对象时 @code{x is y} 为真。 一个对象的标识号可使用 @ref{e53,,id()} 函数来确定。 @code{x is not y} 会产生相反的逻辑值。 @footnote{@w{(4)} 
由于存在自动垃圾收集、空闲列表以及描述器的动态特性，你可能会注意到在特定情况下使用 @ref{1580,,is} 运算符会出现看似不正常的行为，例如涉及到实例方法或常量之间的比较时就是如此。 更多信息请查看有关它们的文档。
}
@anchor{reference/expressions booleans}@anchor{16b1}@anchor{reference/expressions and}@anchor{16b2}@anchor{reference/expressions or}@anchor{16b3}
@node 布尔运算,赋值表达式<2>,比较运算,表达式
@anchor{reference/expressions boolean-operations}@anchor{16b4}@anchor{reference/expressions not}@anchor{16b5}
@subsection 布尔运算


@geindex Conditional; expression
@geindex Boolean; operation

@example
@anchor{reference/expressions grammar-token-or-test}@anchor{16b6}or_test  ::= and_test | or_test "or" and_test
@anchor{reference/expressions grammar-token-and-test}@anchor{16b7}and_test ::= not_test | and_test "and" not_test
@anchor{reference/expressions grammar-token-not-test}@anchor{16b8}not_test ::= comparison | "not" not_test
@end example

在执行布尔运算的情况下，或是当表达式被用于流程控制语句时，以下值会被解析为假值: @code{False}, @code{None}, 所有类型的数字零，以及空字符串和空容器（包括字符串、元组、列表、字典、集合与冻结集合）。 所有其他值都会被解析为真值。 用户自定义对象可通过提供 @ref{d38,,__bool__()} 方法来定制其逻辑值。

@geindex 运算符; not

运算符 @ref{16b5,,not} 将在其参数为假值时产生 @code{True}，否则产生 @code{False}。

@geindex 运算符; and

表达式 @code{x and y} 首先对 @emph{x} 求值；如果 @emph{x} 为假则返回该值；否则对 @emph{y} 求值并返回其结果值。

@geindex 运算符; or

表达式 @code{x or y} 首先对 @emph{x} 求值；如果 @emph{x} 为真则返回该值；否则对 @emph{y} 求值并返回其结果值。

请注意 @ref{16b2,,and} 和 @ref{16b3,,or} 都不限制其返回的值和类型必须为 @code{False} 和 @code{True}，而是返回最后被求值的操作数。 此行为是有必要的，例如假设 @code{s} 为一个当其为空时应被替换为某个默认值的字符串，表达式 @code{s or 'foo'} 将产生希望的值。 由于 @ref{16b5,,not} 必须创建一个新值，不论其参数为何种类型它都会返回一个布尔值（例如，@code{not 'foo'} 结果为 @code{False} 而非 @code{'@w{'}}。）

@node 赋值表达式<2>,条件表达式,布尔运算,表达式
@anchor{reference/expressions assignment-expressions}@anchor{16b9}
@subsection 赋值表达式


@example
@anchor{reference/expressions grammar-token-assignment-expression}@anchor{16ba}assignment_expression ::= [identifier ":="] expression
@end example

赋值表达式（有时又被叫做“命名表达式”或“海象表达式”）将一个 @ref{16bb,,expression} 赋值给一个 @ref{1535,,identifier}，同时还返回 @ref{16bb,,expression} 的值。

一个常见用例是在处理匹配的正则表达式的时候:

@example
if matching := pattern.search(data):
    do_something(matching)
@end example

或者是在处理分块的文件流的时候:

@example
while chunk := file.read(9000):
    process(chunk)
@end example


3.8 新版功能: 请参阅 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} 了解有关赋值表达式的详情。


@node 条件表达式,lambda 表达式,赋值表达式<2>,表达式
@anchor{reference/expressions conditional-expressions}@anchor{16bc}@anchor{reference/expressions if-expr}@anchor{16bd}
@subsection 条件表达式


@geindex conditional; expression
@geindex ternary; operator
@geindex if; conditional expression
@geindex else; conditional expression

@example
@anchor{reference/expressions grammar-token-conditional-expression}@anchor{16be}conditional_expression ::= or_test ["if" or_test "else" expression]
@anchor{reference/expressions grammar-token-expression}@anchor{16bb}expression             ::= conditional_expression | lambda_expr
@end example

条件表达式（有时称为“三元运算符”）在所有 Python 运算中具有最低的优先级。

表达式 @code{x if C else y} 首先是对条件 @emph{C} 而非 @emph{x} 求值。 如果 @emph{C} 为真，@emph{x} 将被求值并返回其值；否则将对 @emph{y} 求值并返回其值。

请参阅 
@geindex Python 提高建议; PEP 308
PEP 308@footnote{https://www.python.org/dev/peps/pep-0308} 了解有关条件表达式的详情。
@anchor{reference/expressions lambdas}@anchor{16bf}
@node lambda 表达式,表达式列表,条件表达式,表达式
@anchor{reference/expressions id14}@anchor{16c0}@anchor{reference/expressions lambda}@anchor{d01}
@subsection lambda 表达式


@geindex lambda; expression
@geindex lambda; form
@geindex anonymous; function
@geindex ; (colon); lambda expression

@example
@anchor{reference/expressions grammar-token-lambda-expr}@anchor{16c1}lambda_expr ::= "lambda" [parameter_list] ":" expression
@end example

lambda 表达式（有时称为 lambda 构型）被用于创建匿名函数。 表达式 @code{lambda parameters: expression} 会产生一个函数对象 。 该未命名对象的行为类似于用以下方式定义的函数:

@example
def <lambda>(parameters):
    return expression
@end example

请参阅 @ref{13bf,,函数定义} 了解有关参数列表的句法。 请注意通过 lambda 表达式创建的函数不能包含语句或标注。

@node 表达式列表,求值顺序,lambda 表达式,表达式
@anchor{reference/expressions expression-lists}@anchor{16c2}@anchor{reference/expressions exprlists}@anchor{74a}
@subsection 表达式列表


@geindex expression; list
@geindex @comma{} (comma); expression list

@example
@anchor{reference/expressions grammar-token-expression-list}@anchor{1671}expression_list    ::= expression ("," expression)* [","]
@anchor{reference/expressions grammar-token-starred-list}@anchor{16c3}starred_list       ::= starred_item ("," starred_item)* [","]
@anchor{reference/expressions grammar-token-starred-expression}@anchor{16c4}starred_expression ::= expression | (starred_item ",")* [starred_item]
@anchor{reference/expressions grammar-token-starred-item}@anchor{16c5}starred_item       ::= assignment_expression | "*" or_expr
@end example

@geindex 对象; tuple

除了作为列表或集合显示的一部分，包含至少一个逗号的表达式列表将生成一个元组。 元组的长度就是列表中表达式的数量。 表达式将从左至右被求值。

@geindex iterable; unpacking
@geindex * (asterisk); in expression lists

一个星号 @code{*} 表示 @emph{可迭代拆包}。 其操作数必须为一个 @ref{c84,,iterable}。 该可迭代对象将被拆解为迭代项的序列，并被包含于在拆包位置上新建的元组、列表或集合之中。


3.5 新版功能: 表达式列表中的可迭代对象拆包，最初由 
@geindex Python 提高建议; PEP 448
PEP 448@footnote{https://www.python.org/dev/peps/pep-0448} 提出。


@geindex trailing; comma

末尾的逗号仅在创建单独元组 (或称 @emph{单例}) 时需要；在所有其他情况下都是可选项。 没有末尾逗号的单独表达式不会创建一个元组，而是产生该表达式的值。 （要创建一个空元组，应使用一对内容为空的圆括号: @code{()}。）

@node 求值顺序,运算符优先级,表达式列表,表达式
@anchor{reference/expressions evalorder}@anchor{16c6}@anchor{reference/expressions evaluation-order}@anchor{16c7}
@subsection 求值顺序


@geindex evaluation; order

Python 按从左至右的顺序对表达式求值。 但注意在对赋值操作求值时，右侧会先于左侧被求值。

在以下几行中，表达式将按其后缀的算术优先顺序被求值。:

@example
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
@{expr1: expr2, expr3: expr4@}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
@end example

@node 运算符优先级,,求值顺序,表达式
@anchor{reference/expressions operator-precedence}@anchor{16c8}@anchor{reference/expressions operator-summary}@anchor{16c9}
@subsection 运算符优先级


@geindex operator; precedence

下表对 Python 中运算符的优先顺序进行了总结，从最高优先级（最先绑定）到最低优先级（最后绑定）。 相同单元格内的运算符具有相同优先级。 除非句法显式地给出，否则运算符均指二元运算。 相同单元格内的运算符从左至右分组（除了幂运算是从右至左分组）。

请注意比较、成员检测和标识号检测均为相同优先级，并具有如 @ref{16a9,,比较运算} 一节所描述的从左至右串连特性。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算符

@tab

描述

@item

@code{(expressions...)},

@code{[expressions...]},
@code{@{key: value...@}},
@code{@{expressions...@}}

@tab

绑定或加圆括号的表达式，列表显示，字典显示，集合显示

@item

@code{x[index]}, @code{x[index:index]},
@code{x(arguments...)}, @code{x.attribute}

@tab

抽取，切片，调用，属性引用

@item

@ref{2df,,await x}

@tab

await 表达式

@item

@code{**}

@tab

乘方 @footnote{@w{(5)} 
幂运算符 @code{**} 绑定的紧密程度低于在其右侧的算术或按位一元运算符，也就是说 @code{2**-1} 为 @code{0.5}。
}

@item

@code{+x}, @code{-x}, @code{~x}

@tab

正，负，按位非 NOT

@item

@code{*}, @code{@@}, @code{/}, @code{//}, @code{%}

@tab

乘，矩阵乘，除，整除，取余 @footnote{@w{(6)} 
@code{%} 运算符也被用于字符串格式化；在此场合下会使用同样的优先级。
}

@item

@code{+}, @code{-}

@tab

加和减

@item

@code{<<}, @code{>>}

@tab

移位

@item

@code{&}

@tab

按位与 AND

@item

@code{^}

@tab

按位异或 XOR

@item

@code{|}

@tab

按位或 OR

@item

@ref{179,,in}, @ref{15ca,,not in},
@ref{1580,,is}, @ref{16b0,,is not}, @code{<},
@code{<=}, @code{>}, @code{>=}, @code{!=}, @code{==}

@tab

比较运算，包括成员检测和标识号检测

@item

@ref{16b5,,not x}

@tab

布尔逻辑非 NOT

@item

@ref{16b2,,and}

@tab

布尔逻辑与 AND

@item

@ref{16b3,,or}

@tab

布尔逻辑或 OR

@item

@ref{16bd,,if} -- @code{else}

@tab

条件表达式

@item

@ref{d01,,lambda}

@tab

lambda 表达式

@item

@code{:=}

@tab

赋值表达式

@end multitable


@node 简单语句,复合语句,表达式,Python 语言参考手册
@anchor{reference/simple_stmts doc}@anchor{16ca}@anchor{reference/simple_stmts simple}@anchor{16cb}@anchor{reference/simple_stmts simple-statements}@anchor{16cc}
@section 简单语句


@geindex simple; statement

简单语句由一个单独的逻辑行构成。 多条简单语句可以存在于同一行内并以分号分隔。 简单语句的句法为:

@example
@anchor{reference/simple_stmts grammar-token-simple-stmt}@anchor{16cd}simple_stmt ::= expression_stmt
                | assert_stmt
                | assignment_stmt
                | augmented_assignment_stmt
                | annotated_assignment_stmt
                | pass_stmt
                | del_stmt
                | return_stmt
                | yield_stmt
                | raise_stmt
                | break_stmt
                | continue_stmt
                | import_stmt
                | future_stmt
                | global_stmt
                | nonlocal_stmt
@end example

@menu
* 表达式语句:: 
* 赋值语句:: 
* assert 语句:: 
* pass 语句: pass 语句<2>. 
* del 语句: del 语句<2>. 
* return 语句:: 
* yield 语句:: 
* raise 语句:: 
* break 语句:: 
* continue 语句:: 
* import 语句:: 
* global 语句:: 
* nonlocal 语句:: 

@end menu

@node 表达式语句,赋值语句,,简单语句
@anchor{reference/simple_stmts expression-statements}@anchor{16ce}@anchor{reference/simple_stmts exprstmts}@anchor{16cf}
@subsection 表达式语句


@geindex expression; statement
@geindex expression; list

@geindex expression; list

表达式语句用于计算和写入值（大多是在交互模式下），或者（通常情况）调用一个过程 (过程就是不返回有意义结果的函数；在 Python 中，过程的返回值为 @code{None})。 表达式语句的其他使用方式也是允许且有特定用处的。 表达式语句的句法为:

@example
@anchor{reference/simple_stmts grammar-token-expression-stmt}@anchor{16d0}expression_stmt ::= starred_expression
@end example

表达式语句会对指定的表达式列表（也可能为单一表达式）进行求值。

@geindex 內置函数; repr
@geindex 对象; None
@geindex string; conversion
@geindex output
@geindex standard; output
@geindex writing; values
@geindex procedure; call

在交互模式下，如果结果值不为 @code{None}，它会通过内置的 @ref{8c3,,repr()} 函数转换为一个字符串，该结果字符串将以单独一行的形式写入标准输出（例外情况是如果结果为 @code{None}，则该过程调用不产生任何输出。）

@node 赋值语句,assert 语句,表达式语句,简单语句
@anchor{reference/simple_stmts assignment}@anchor{16d1}@anchor{reference/simple_stmts assignment-statements}@anchor{16d2}
@subsection 赋值语句


@geindex = (equals); assignment statement
@geindex assignment; statement
@geindex binding; name
@geindex rebinding; name
@geindex 对象; mutable
@geindex attribute; assignment

赋值语句用于将名称（重）绑定到特定值，以及修改属性或可变对象的成员项:

@example
@anchor{reference/simple_stmts grammar-token-assignment-stmt}@anchor{16d3}assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
@anchor{reference/simple_stmts grammar-token-target-list}@anchor{16d4}target_list     ::= target ("," target)* [","]
@anchor{reference/simple_stmts grammar-token-target}@anchor{16d5}target          ::= identifier
                    | "(" [target_list] ")"
                    | "[" [target_list] "]"
                    | attributeref
                    | subscription
                    | slicing
                    | "*" target
@end example

(请参阅 @ref{1679,,原型} 一节了解 @emph{属性引用}, @emph{抽取} 和 @emph{切片} 的句法定义。)

赋值语句会对指定的表达式列表进行求值（注意这可能为单一表达式或是由逗号分隔的列表，后者将产生一个元组）并将单一结果对象从左至右逐个赋值给目标列表。

@geindex target
@geindex target; list

赋值是根据目标（列表）的格式递归地定义的。 当目标为一个可变对象（属性引用、抽取或切片）的组成部分时，该可变对象必须最终执行赋值并决定其有效性，如果赋值操作不可接受也可能引发异常。 各种类型可用的规则和引发的异常通过对象类型的定义给出（参见 @ref{1582,,标准类型层级结构} 一节）。

@geindex target; list; assignment
@geindex @comma{} (comma); in target list
@geindex * (asterisk); in assignment target list
@geindex [] (square brackets); in assignment target list
@geindex () (parentheses); in assignment target list

对象赋值的目标对象可以包含于圆括号或方括号内，具体操作按以下方式递归地定义。


@itemize *

@item 
如果目标列表为后面不带逗号、可以包含于圆括号内的单一目标，则将对象赋值给该目标。

@item 
否则:


@itemize *

@item 
如果目标列表包含一个带有星号前缀的目标，这称为“加星”目标：则该对象至少必须为与目标列表项数减一相同项数的可迭代对象。 该可迭代对象前面的项将按从左至右的顺序被赋值给加星目标之前的目标。 该可迭代对象末尾的项将被赋值给加星目标之后的目标。 然后该可迭代对象中剩余项的列表将被赋值给加星目标（该列表可以为空）。

@item 
否则：该对象必须为具有与目标列表相同项数的可迭代对象，这些项将按从左至右的顺序被赋值给对应的目标。
@end itemize
@end itemize

对象赋值给单个目标的操作按以下方式递归地定义。


@itemize *

@item 
如果目标为标识符（名称）:


@itemize *

@item 
如果该名称未出现于当前代码块的 @ref{13a7,,global} 或 @ref{d0f,,nonlocal} 语句中：该名称将被绑定到当前局部命名空间的对象。

@item 
否则：该名称将被分别绑定到全局命名空间或由 @ref{d0f,,nonlocal} 所确定的外层命名空间的对象。
@end itemize

@geindex destructor

如果该名称已经被绑定则将被重新绑定。 这可能导致之前被绑定到该名称的对象的引用计数变为零，造成该对象进入释放过程并调用其析构器（如果存在）。

@geindex attribute; assignment

@item 
如果该对象为属性引用：引用中的原型表达式会被求值。 它应该产生一个具有可赋值属性的对象；否则将引发 @ref{1ff,,TypeError}。 该对象会被要求将可赋值对象赋值给指定的属性；如果它无法执行赋值，则会引发异常 (通常应为 @ref{4aa,,AttributeError} 但并不强制要求)。
@anchor{reference/simple_stmts attr-target-note}@anchor{16d6}
注意：如果该对象为类实例并且属性引用在赋值运算符的两侧都出现，则右侧表达式 @code{a.x} 可以访问实例属性或（如果实例属性不存在）类属性。 左侧目标 @code{a.x} 将总是设定为实例属性，并在必要时创建该实例属性。 因此 @code{a.x} 的两次出现不一定指向相同的属性：如果右侧表达式指向一个类属性，则左侧会创建一个新的实例属性作为赋值的目标:

@example
class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3
@end example

此描述不一定作用于描述器属性，例如通过 @ref{30f,,property()} 创建的特征属性。

@geindex subscription; assignment
@geindex 对象; mutable

@item 
如果目标为一个抽取项：引用中的原型表达式会被求值。 它应当产生一个可变序列对象（例如列表）或一个映射对象（例如字典）。 接下来，该抽取表达式会被求值。

@geindex 对象; sequence
@geindex 对象; list

如果原型为一个可变序列对象（例如列表），抽取应产生一个整数。 如其为负值，则再加上序列长度。 结果值必须为一个小于序列长度的非负整数，序列将把被赋值对象赋值给该整数指定索引号的项。 如果索引超出范围，将会引发 @ref{f3d,,IndexError} (给被抽取序列赋值不能向列表添加新项)。

@geindex 对象; mapping
@geindex 对象; dictionary

如果原型为一个映射对象（例如字典），抽取必须具有与该映射的键类型相兼容的类型，然后映射中会创建一个将抽取映射到被赋值对象的键/值对。 这可以是替换一个现有键/值对并保持相同键值，也可以是插入一个新键/值对（如果具有相同值的键不存在）。

对于用户定义对象，会调用 @ref{d32,,__setitem__()} 方法并附带适当的参数。

@geindex slicing; assignment

@item 
如果目标为一个切片：引用中的原型表达式会被求值。 它应当产生一个可变序列对象（例如列表）。 被赋值对象应当是一个相同类型的序列对象。 接下来，下界与上界表达式如果存在的话将被求值；默认值分别为零和序列长度。 上下边界值应当为整数。 如果某一边界为负值，则会加上序列长度。 求出的边界会被裁剪至介于零和序列长度的开区间中。 最后，将要求序列对象以被赋值序列的项替换该切片。 切片的长度可能与被赋值序列的长度不同，这会在目标序列允许的情况下改变目标序列的长度。
@end itemize

@strong{CPython implementation detail:} 在当前实现中，目标的句法被当作与表达式的句法相同，无效的句法会在代码生成阶段被拒绝，导致不太详细的错误信息。

虽然赋值的定义意味着左手边与右手边的重叠是“同时”进行的（例如 @code{a, b = b, a} 会交换两个变量的值），但在赋值给变量的多项集 @emph{之内} 的重叠是从左至右进行的，这有时会令人混淆。 例如，以下程序将会打印出 @code{[0, 2]}:

@example
x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)
@end example


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3132

@item PEP 3132@footnote{https://www.python.org/dev/peps/pep-3132} - 扩展的可迭代对象拆包

对 @code{*target} 特性的规范说明。
@end table


@menu
* 增强赋值语句:: 
* 带标注的赋值语句:: 

@end menu

@node 增强赋值语句,带标注的赋值语句,,赋值语句
@anchor{reference/simple_stmts augassign}@anchor{16d7}@anchor{reference/simple_stmts augmented-assignment-statements}@anchor{16d8}
@subsubsection 增强赋值语句


@geindex augmented; assignment
@geindex statement; assignment@comma{} augmented
@geindex +=; augmented assignment
@geindex -=; augmented assignment
@geindex *=; augmented assignment
@geindex /=; augmented assignment
@geindex %=; augmented assignment
@geindex &=; augmented assignment
@geindex ^=; augmented assignment
@geindex |=; augmented assignment
@geindex **=; augmented assignment
@geindex //=; augmented assignment
@geindex >>=; augmented assignment
@geindex <<=; augmented assignment

增强赋值语句就是在单个语句中将二元运算和赋值语句合为一体:

@example
@anchor{reference/simple_stmts grammar-token-augmented-assignment-stmt}@anchor{16d9}augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
@anchor{reference/simple_stmts grammar-token-augtarget}@anchor{16da}augtarget                 ::= identifier | attributeref | subscription | slicing
@anchor{reference/simple_stmts grammar-token-augop}@anchor{16db}augop                     ::= "+=" | "-=" | "*=" | "@@=" | "/=" | "//=" | "%=" | "**="
                              | ">>=" | "<<=" | "&=" | "^=" | "|="
@end example

（请参阅 @ref{1679,,原型} 一节了解最后三种符号的句法定义。）

增强赋值语句将对目标和表达式列表求值（与普通赋值语句不同的是，前者不能为可迭代对象拆包），对两个操作数相应类型的赋值执行指定的二元运算，并将结果赋值给原始目标。 目标仅会被求值一次。

增强赋值语句例如 @code{x += 1} 可以改写为 @code{x = x + 1} 获得类似但并非完全等价的效果。 在增强赋值的版本中，@code{x} 仅会被求值一次。 而且，在可能的情况下，实际的运算是 @emph{原地} 执行的，也就是说并不是创建一个新对象并将其赋值给目标，而是直接修改原对象。

不同于普通赋值，增强赋值会在对右手边求值 @emph{之前} 对左手边求值。 例如，@code{a[i] += f(x)} 首先查找 @code{a[i]}，然后对 @code{f(x)} 求值并执行加法操作，最后将结果写回到 @code{a[i]}。

除了在单个语句中赋值给元组和多个目标的例外情况，增强赋值语句的赋值操作处理方式与普通赋值相同。 类似地，除了可能存在 @emph{原地} 操作行为的例外情况，增强赋值语句执行的二元运算也与普通二元运算相同。

对于属性引用类目标，针对常规赋值的 @ref{16d6,,关于类和实例属性的警告} 也同样适用。

@node 带标注的赋值语句,,增强赋值语句,赋值语句
@anchor{reference/simple_stmts annassign}@anchor{16dc}@anchor{reference/simple_stmts annotated-assignment-statements}@anchor{16dd}
@subsubsection 带标注的赋值语句


@geindex annotated; assignment
@geindex statement; assignment@comma{} annotated
@geindex ; (colon); annotated variable

@ref{71c,,标注} 赋值就是在单个语句中将变量或属性标注和可选的赋值语句合为一体:

@example
@anchor{reference/simple_stmts grammar-token-annotated-assignment-stmt}@anchor{16de}annotated_assignment_stmt ::= augtarget ":" expression
                              ["=" (starred_expression | yield_expression)]
@end example

与普通 @ref{16d1,,赋值语句} 的差别在于仅允许单个目标。

对于将简单名称作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值并存入一个特殊的类或模块属性 @code{__annotations__} 中，这是一个将变量名称（如为私有会被移除）映射到被求值标注的字典。 此属性为可写并且在类或模块体开始执行时如果静态地发现标注就会自动创建。

对于将表达式作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值，但不会保存。

如果一个名称在函数作用域内被标注，则该名称为该作用域的局部变量。 标注绝不会在函数作用域内被求值和保存。

如果存在右手边，带标注的赋值会在对标注求值之前（如果适用）执行实际的赋值。 如果用作表达式目标的右手边不存在，则解释器会对目标求值，但最后的 @ref{d32,,__setitem__()} 或 @ref{ef6,,__setattr__()} 调用除外。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 526

@item PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} - 变量标注的语法

该提议增加了标注变量（也包括类变量和实例变量）类型的语法，而不再是通过注释来进行表达。

@geindex Python 提高建议; PEP 484

@item PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} - 类型提示

该提议增加了 @ref{122,,typing} 模块以便为类型标注提供标准句法，可被静态分析工具和 IDE 所使用。
@end table



在 3.8 版更改: 现在带有标注的赋值允许在右边以同样的表达式作为常规赋值。 之前，某些表达式（例如未加圆括号的元组表达式）会导致语法错误。


@node assert 语句,pass 语句<2>,赋值语句,简单语句
@anchor{reference/simple_stmts assert}@anchor{240}@anchor{reference/simple_stmts the-assert-statement}@anchor{16df}
@subsection @code{assert} 语句


@geindex 语句; assert
@geindex debugging; assertions
@geindex @comma{} (comma); expression list

assert 语句是在程序中插入调试性断言的简便方式:

@example
@anchor{reference/simple_stmts grammar-token-assert-stmt}@anchor{16e0}assert_stmt ::= "assert" expression ["," expression]
@end example

简单形式 @code{assert expression} 等价于

@example
if __debug__:
    if not expression: raise AssertionError
@end example

扩展形式 @code{assert expression1, expression2} 等价于

@example
if __debug__:
    if not expression1: raise AssertionError(expression2)
@end example

@geindex __debug__
@geindex 例外; AssertionError

以上等价形式假定 @ref{1180,,__debug__} 和 @ref{241,,AssertionError} 指向具有指定名称的内置变量。 在当前实现中，内置变量 @ref{1180,,__debug__} 在正常情况下为 @code{True}，在请求优化时为 @code{False} (对应命令行选项为 @ref{788,,-O})。 如果在编译时请求优化，当前代码生成器不会为 assert 语句发出任何代码。 请注意不必在错误信息中包含失败表达式的源代码；它会被作为栈追踪的一部分被显示。

赋值给 @ref{1180,,__debug__} 是非法的。 该内置变量的值会在解释器启动时确定。

@node pass 语句<2>,del 语句<2>,assert 语句,简单语句
@anchor{reference/simple_stmts pass}@anchor{13a3}@anchor{reference/simple_stmts the-pass-statement}@anchor{16e1}
@subsection @code{pass} 语句


@geindex 语句; pass
@geindex null; operation
@geindex null; operation

@example
@anchor{reference/simple_stmts grammar-token-pass-stmt}@anchor{16e2}pass_stmt ::= "pass"
@end example

@ref{13a3,,pass} 是一个空操作 --- 当它被执行时，什么都不发生。 它适合当语法上需要一条语句但并不需要执行任何代码时用来临时占位，例如:

@example
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
@end example

@node del 语句<2>,return 语句,pass 语句<2>,简单语句
@anchor{reference/simple_stmts del}@anchor{13d1}@anchor{reference/simple_stmts the-del-statement}@anchor{16e3}
@subsection @code{del} 语句


@geindex 语句; del
@geindex deletion; target
@geindex deletion; target; list

@example
@anchor{reference/simple_stmts grammar-token-del-stmt}@anchor{16e4}del_stmt ::= "del" target_list
@end example

删除是递归定义的，与赋值的定义方式非常类似。 此处不再详细说明，只给出一些提示。

目标列表的删除将从左至右递归地删除每一个目标。

@geindex 语句; global
@geindex unbinding; name

名称的删除将从局部或全局命名空间中移除该名称的绑定，具体作用域的确定是看该名称是否有在同一代码块的 @ref{13a7,,global} 语句中出现。 如果该名称未被绑定，将会引发 @ref{e48,,NameError}。

@geindex attribute; deletion

属性引用、抽取和切片的删除会被传递给相应的原型对象；删除一个切片基本等价于赋值为一个右侧类型的空切片（但即便这一点也是由切片对象决定的）。


在 3.2 版更改: 在之前版本中，如果一个名称作为被嵌套代码块中的自由变量出现，则将其从局部命名空间中删除是非法的。


@node return 语句,yield 语句,del 语句<2>,简单语句
@anchor{reference/simple_stmts return}@anchor{2cf}@anchor{reference/simple_stmts the-return-statement}@anchor{16e5}
@subsection @code{return} 语句


@geindex 语句; return
@geindex function; definition
@geindex class; definition

@example
@anchor{reference/simple_stmts grammar-token-return-stmt}@anchor{16e6}return_stmt ::= "return" [expression_list]
@end example

@ref{2cf,,return} 在语法上只会出现于函数定义所嵌套的代码，不会出现于类定义所嵌套的代码。

如果提供了表达式列表，它将被求值，否则以 @code{None} 替代。

@ref{2cf,,return} 会离开当前函数调用，并以表达式列表 (或 @code{None}) 作为返回值。

@geindex 关键字; finally

当 @ref{2cf,,return} 将控制流传出一个带有 @ref{2c3,,finally} 子句的 @ref{e3f,,try} 语句时，该 @code{finally} 子句会先被执行然后再真正离开该函数。

在一个生成器函数中，@ref{2cf,,return} 语句表示生成器已完成并将导致 @ref{58a,,StopIteration} 被引发。 返回值（如果有的话）会被当作一个参数用来构建 @ref{58a,,StopIteration} 并成为 @code{StopIteration.value} 属性。

在一个异步生成器函数中，一个空的 @ref{2cf,,return} 语句表示异步生成器已完成并将导致 @ref{1193,,StopAsyncIteration} 被引发。 一个非空的 @code{return} 语句在异步生成器函数中会导致语法错误。

@node yield 语句,raise 语句,return 语句,简单语句
@anchor{reference/simple_stmts the-yield-statement}@anchor{16e7}@anchor{reference/simple_stmts yield}@anchor{2ce}
@subsection @code{yield} 语句


@geindex 语句; yield
@geindex generator; function
@geindex generator; iterator
@geindex function; generator
@geindex 例外; StopIteration

@example
@anchor{reference/simple_stmts grammar-token-yield-stmt}@anchor{16e8}yield_stmt ::= yield_expression
@end example

@ref{2ce,,yield} 语句在语义上等同于 @ref{166c,,yield 表达式}。 yield 语句可用来省略在使用等效的 yield 表达式语句时所必须的圆括号。 例如，以下 yield 语句

@example
yield <expr>
yield from <expr>
@end example

等同于以下 yield 表达式语句

@example
(yield <expr>)
(yield from <expr>)
@end example

yield 表达式和语句仅在定义 @ref{a8c,,generator} 函数时使用，并且仅被用于生成器函数的函数体内部。 在函数定义中使用 yield 就足以使得该定义创建的是生成器函数而非普通函数。

有关 @ref{2ce,,yield} 语义的完整细节请参看 @ref{166c,,yield 表达式} 一节。

@node raise 语句,break 语句,yield 语句,简单语句
@anchor{reference/simple_stmts raise}@anchor{d12}@anchor{reference/simple_stmts the-raise-statement}@anchor{16e9}
@subsection @code{raise} 语句


@geindex 语句; raise
@geindex exception
@geindex raising; exception
@geindex __traceback__ (exception attribute)

@example
@anchor{reference/simple_stmts grammar-token-raise-stmt}@anchor{16ea}raise_stmt ::= "raise" [expression ["from" expression]]
@end example

如果没有提供表达式，则 @ref{d12,,raise} 会重新引发当前正在处理的异常，它也被称为 @emph{活动的异常}。 如果当前没有活动的异常，则会引发 @ref{3e4,,RuntimeError} 来提示发生了错误。

否则的话，@ref{d12,,raise} 会将第一个表达式求值为异常对象。 它必须为 @ref{2e2,,BaseException} 的子类或实例。 如果它是一个类，当需要时会通过不带参数地实例化该类来获得异常的实例。

异常的 @emph{类型} 为异常实例的类，@emph{值} 为实例本身。

@geindex 对象; traceback

当有异常被引发时通常会自动创建一个回溯对象并将其关联到它的 @code{__traceback__} 属性，该属性是可写的。 你可以创建一个异常并使用 @ref{16eb,,with_traceback()} 异常方法（该方法将返回同一异常实例，并将回溯对象设为其参数）直接设置自己的回溯对象，就像这样like so:

@example
raise Exception("foo occurred").with_traceback(tracebackobj)
@end example

@geindex exception; chaining
@geindex __cause__ (exception attribute)
@geindex __context__ (exception attribute)

@code{from} 子句用于异常串连：如果有该子句，则第二个 @emph{表达式} 必须为另一个异常类或实例。 如果第二个表达式是一个异常实例，它将作为可写的 @code{__cause__} 属性被关联到所引发的异常。 如果该表达式是一个异常类，这个类将被实例化且所生成的异常实例将作为 @code{__cause__} 属性被关联到所引发的异常。 如果所引发的异常未被处理，则两个异常都将被打印出来:

@example
>>> try:
...     print(1 / 0)
... except Exception as exc:
...     raise RuntimeError("Something bad happened") from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
@end example

当已经有一个异常在处理时如果有新的异常被引发则类似的机制会隐式地起作用。 异常可以通过使用 @ref{c19,,except} 或 @ref{2c3,,finally} 子句或是 @ref{7e4,,with} 语句来处理。 之前的异常将被关联至新异常的 @code{__context__} 属性:

@example
>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
@end example

异常串连可通过在 @code{from} 子句中指定 @ref{204,,None} 来显式地加以抑制:

@example
>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
@end example

有关异常的更多信息可在 @ref{1612,,异常} 一节查看，有关处理异常的信息可在 @ref{e3f,,try 语句} 一节查看。


在 3.3 版更改: @ref{204,,None} 现在允许被用作 @code{raise X from Y} 中的 @code{Y}。



3.3 新版功能: 使用 @code{__suppress_context__} 属性来抑制异常上下文的自动显示。


@node break 语句,continue 语句,raise 语句,简单语句
@anchor{reference/simple_stmts break}@anchor{403}@anchor{reference/simple_stmts the-break-statement}@anchor{16ec}
@subsection @code{break} 语句


@geindex 语句; break
@geindex 语句; for
@geindex 语句; while
@geindex loop; statement

@example
@anchor{reference/simple_stmts grammar-token-break-stmt}@anchor{16ed}break_stmt ::= "break"
@end example

@ref{403,,break} 在语法上只会出现于 @ref{d02,,for} 或 @ref{1390,,while} 循环所嵌套的代码，但不会出现于该循环内部的函数或类定义所嵌套的代码。

@geindex 关键字; else
@geindex loop control; target

它会终结最近的外层循环，如果循环有可选的 @code{else} 子句，也会跳过该子句。

如果一个 @ref{d02,,for} 循环被 @ref{403,,break} 所终结，该循环的控制目标会保持其当前值。

@geindex 关键字; finally

当 @ref{403,,break} 将控制流传出一个带有 @ref{2c3,,finally} 子句的 @ref{e3f,,try} 语句时，该 @code{finally} 子句会先被执行然后再真正离开该循环。

@node continue 语句,import 语句,break 语句,简单语句
@anchor{reference/simple_stmts continue}@anchor{2c2}@anchor{reference/simple_stmts the-continue-statement}@anchor{16ee}
@subsection @code{continue} 语句


@geindex 语句; continue
@geindex 语句; for
@geindex 语句; while
@geindex loop; statement
@geindex 关键字; finally

@example
@anchor{reference/simple_stmts grammar-token-continue-stmt}@anchor{16ef}continue_stmt ::= "continue"
@end example

@ref{2c2,,continue} 在语法上只会出现于 @ref{d02,,for} 或 @ref{1390,,while} 循环所嵌套的代码中，但不会出现于该循环内部的函数或类定义中。 它会继续执行最近的外层循环的下一个轮次。

当 @ref{2c2,,continue} 将控制流传出一个带有 @ref{2c3,,finally} 子句的 @ref{e3f,,try} 语句时，该 @code{finally} 子句会先被执行然后再真正开始循环的下一个轮次。
@anchor{reference/simple_stmts import}@anchor{cef}
@node import 语句,global 语句,continue 语句,简单语句
@anchor{reference/simple_stmts from}@anchor{d15}@anchor{reference/simple_stmts the-import-statement}@anchor{16f0}
@subsection @code{import} 语句


@geindex 语句; import
@geindex module; importing
@geindex name; binding
@geindex 关键字; from
@geindex 关键字; as
@geindex 例外; ImportError
@geindex @comma{} (comma); import statement

@example
@anchor{reference/simple_stmts grammar-token-import-stmt}@anchor{16f1}import_stmt     ::= "import" module ["as" identifier] ("," module ["as" identifier])*
                    | "from" relative_module "import" identifier ["as" identifier]
                    ("," identifier ["as" identifier])*
                    | "from" relative_module "import" "(" identifier ["as" identifier]
                    ("," identifier ["as" identifier])* [","] ")"
                    | "from" relative_module "import" "*"
@anchor{reference/simple_stmts grammar-token-module}@anchor{16f2}module          ::= (identifier ".")* identifier
@anchor{reference/simple_stmts grammar-token-relative-module}@anchor{16f3}relative_module ::= "."* module | "."+
@end example

基本的 import 语句（不带 @ref{d15,,from} 子句）会分两步执行:


@enumerate 

@item 
查找一个模块，如果有必要还会加载并初始化模块。

@item 
在局部命名空间中为 @ref{cef,,import} 语句发生位置所处的作用域定义一个或多个名称。
@end enumerate

当语句包含多个子句（由逗号分隔）时这两个步骤将对每个子句分别执行，如同这些子句被分成独立的 import 语句一样。

第一个步骤即查找和加载模块的详情 @ref{1590,,导入系统} 一节中有更详细的描述，其中也描述了可被导入的多种类型的包和模块，以及可用于定制导入系统的所有钩子对象。 请注意这一步如果失败，则可能说明模块无法找到，@emph{或者} 是在初始化模块，包括执行模块代码期间发生了错误。

如果成功获取到请求的模块，则可以通过以下三种方式一之在局部命名空间中使用它:

@geindex as; import statement


@itemize *

@item 
如果模块名称之后带有 @code{as}，则跟在 @code{as} 之后的名称将直接绑定到所导入的模块。

@item 
如果没有指定其他名称，且被导入的模块为最高层级模块，则模块的名称将被绑定到局部命名空间作为对所导入模块的引用。

@item 
如果被导入的模块 @emph{不是} 最高层级模块，则包含该模块的最高层级包的名称将被绑定到局部命名空间作为对该最高层级包的引用。 所导入的模块必须使用其完整限定名称来访问而不能直接访问。
@end itemize

@geindex name; binding
@geindex from; import statement

@ref{d15,,from} 形式使用的过程略微繁复一些:


@enumerate 

@item 
查找 @ref{d15,,from} 子句中指定的模块，如有必要还会加载并初始化模块；

@item 
对于 @ref{cef,,import} 子句中指定的每个标识符：


@enumerate 

@item 
检查被导入模块是否有该名称的属性

@item 
如果没有，尝试导入具有该名称的子模块，然后再次检查被导入模块是否有该属性

@item 
如果未找到该属性，则引发 @ref{16c,,ImportError}。

@item 
否则的话，将对该值的引用存入局部命名空间，如果有 @code{as} 子句则使用其指定的名称，否则使用该属性的名称
@end enumerate
@end enumerate

例如:

@example
import foo                 # foo imported and bound locally
import foo.bar.baz         # foo, foo.bar, and foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb  # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
from foo.bar import baz    # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
from foo import attr       # foo imported and foo.attr bound as attr
@end example

@geindex * (asterisk); import statement

如果标识符列表改为一个星号 (@code{'*'})，则在模块中定义的全部公有名称都将按 @ref{cef,,import} 语句所在的作用域被绑定到局部命名空间。

@geindex __all__ (optional module attribute)

一个模块所定义的 @emph{公有名称} 是由在模块的命名空间中检测一个名为 @code{__all__} 的变量来确定的；如果有定义，它必须是一个字符串列表，其中的项为该模块所定义或导入的名称。 在 @code{__all__} 中所给出的名称都会被视为公有并且应当存在。 如果 @code{__all__} 没有被定义，则公有名称的集合将包含在模块的命名空间中找到的所有不以下划线字符 (@code{'_'}) 打头的名称。 @code{__all__} 应当包括整个公有 API。 它的目标是避免意外地导出不属于 API 的一部分的项（例如在模块内部被导入和使用的库模块）。

通配符形式的导入 --- @code{from module import *} --- 仅在模块层级上被允许。 尝试在类或函数定义中使用它将引发 @ref{562,,SyntaxError}。

@geindex relative; import

当指定要导入哪个模块时，你不必指定模块的绝对名称。 当一个模块或包被包含在另一个包之中时，可以在同一个最高层级包中进行相对导入，而不必提及包名称。 通过在 @ref{d15,,from} 之后指定的模块或包中使用前缀点号，你可以在不指定确切名称的情况下指明在当前包层级结构中要上溯多少级。 一个前缀点号表示是执行导入的模块所在的当前包，两个点号表示上溯一个包层级。 三个点号表示上溯两级，依此类推。 因此如果你执行 @code{from . import mod} 时所处位置为 @code{pkg} 包内的一个模块，则最终你将导入 @code{pkg.mod}。 如果你执行 @code{from ..subpkg2 import mod} 时所处位置为 @code{pkg.subpkg1} 则你将导入 @code{pkg.subpkg2.mod}。 有关相对导入的规范说明包含在 @ref{1640,,包相对导入} 一节中。

@ref{bef,,importlib.import_module()} 被提供用来为动态地确定要导入模块的应用提供支持。

引发一个 @ref{fec,,审计事件} @code{import} 附带参数 @code{module}, @code{filename}, @code{sys.path}, @code{sys.meta_path}, @code{sys.path_hooks}。

@menu
* future 语句:: 

@end menu

@node future 语句,,,import 语句
@anchor{reference/simple_stmts future}@anchor{16f4}@anchor{reference/simple_stmts future-statements}@anchor{16f5}
@subsubsection future 语句


@geindex future; statement
@geindex __future__; future statement

@emph{future 语句} 是一种针对编译器的指令，指明某个特定模块应当使用在特定的未来某个 Python 发行版中成为标准特性的语法或语义。

future 语句的目的是使得向在语言中引入了不兼容改变的 Python 未来版本的迁移更为容易。 它允许基于每个模块在某种新特性成为标准之前的发行版中使用该特性。

@example
@anchor{reference/simple_stmts grammar-token-future-stmt}@anchor{16f6}future_stmt ::= "from" "__future__" "import" feature ["as" identifier]
                ("," feature ["as" identifier])*
                | "from" "__future__" "import" "(" feature ["as" identifier]
                ("," feature ["as" identifier])* [","] ")"
@anchor{reference/simple_stmts grammar-token-feature}@anchor{16f7}feature     ::= identifier
@end example

future 语句必须在靠近模块开头的位置出现。 可以出现在 future 语句之前行只有:


@itemize *

@item 
模块的文档字符串（如果存在），

@item 
注释，

@item 
空行，以及

@item 
其他 future 语句。
@end itemize

唯一需要使用 future 语句的特性是 @code{标注} (参见 
@geindex Python 提高建议; PEP 563
PEP 563@footnote{https://www.python.org/dev/peps/pep-0563})。

future 语句所启用的所有历史特性仍然为 Python 3 所认可。  其中包括 @code{absolute_import}, @code{division}, @code{generators}, @code{generator_stop}, @code{unicode_literals}, @code{print_function}, @code{nested_scopes} 和 @code{with_statement}。 它们都已成为冗余项，因为它们总是为已启用状态，保留它们只是为了向后兼容。

future 语句在编译时会被识别并做特殊对待：对核心构造语义的改变常常是通过生成不同的代码来实现。 新的特性甚至可能会引入新的不兼容语法（例如新的保留字），在这种情况下编译器可能需要以不同的方式来解析模块。 这样的决定不能推迟到运行时方才作出。

对于任何给定的发布版本，编译器要知道哪些特性名称已被定义，如果某个 future 语句包含未知的特性则会引发编译时错误。

直接运行时的语义与任何 import 语句相同：存在一个后文将详细说明的标准模块 @ref{0,,__future__}，它会在执行 future 语句时以通常的方式被导入。

相应的运行时语义取决于 future 语句所启用的指定特性。

请注意以下语句没有任何特别之处:

@example
import __future__ [as name]
@end example

这并非 future 语句；它只是一条没有特殊语义或语法限制的普通 import 语句。

在默认情况下，通过对Code compiled by calls to the 内置函数 @ref{d14,,exec()} 和 @ref{2ee,,compile()} 的调用所编译的代码如果出现于一个包含有 future 语句的模块 @code{M} 之中，就会使用 future 语句所关联的语法和语义。 此行为可以通过 @ref{2ee,,compile()} 的可选参数加以控制 --- 请参阅该函数的文档以了解详情。

在交互式解释器提示符中键入的 future 语句将在解释器会话此后的交互中有效。 如果一个解释器的启动使用了 @ref{ee9,,-i} 选项启动，并传入了一个脚本名称来执行，且该脚本包含 future 语句，它将在交互式会话开始执行脚本之后保持有效。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 236

@item PEP 236@footnote{https://www.python.org/dev/peps/pep-0236} - 回到 __future__

有关 __future__ 机制的最初提议。
@end table


@node global 语句,nonlocal 语句,import 语句,简单语句
@anchor{reference/simple_stmts global}@anchor{13a7}@anchor{reference/simple_stmts the-global-statement}@anchor{16f8}
@subsection @code{global} 语句


@geindex 语句; global
@geindex global; name; binding
@geindex @comma{} (comma); identifier list

@example
@anchor{reference/simple_stmts grammar-token-global-stmt}@anchor{16f9}global_stmt ::= "global" identifier ("," identifier)*
@end example

@ref{13a7,,global} 语句是作用于整个当前代码块的声明。 它意味着所列出的标识符将被解读为全局变量。 要给全局变量赋值不可能不用到 @code{global} 关键字，不过自由变量也可以指向全局变量而不必声明为全局变量。

在 @ref{13a7,,global} 语句中列出的名称不得在同一代码块内该 @code{global} 语句之前的位置中使用。

在 @ref{13a7,,global} 语句中列出的名称不能被定义为形式参数，也不能在 @ref{d02,,for} 循环的控制目标、@ref{d3a,,class} 定义、函数定义、@ref{cef,,import} 语句或变量标注中定义。

@strong{CPython implementation detail:} 当前的实现并未强制要求所有的上述限制，但程序不应当滥用这样的自由，因为未来的实现可能会改为强制要求，并静默地改变程序的含义。

@geindex 內置函数; exec
@geindex 內置函数; eval
@geindex 內置函数; compile

@strong{程序员注意事项:} @ref{13a7,,global} 是对解析器的指令。 它仅对与 @code{global} 语句同时被解析的代码起作用。 特别地，包含在提供给内置 @ref{d14,,exec()} 函数字符串或代码对象中的 @code{global} 语句并不会影响 @emph{包含} 该函数调用的代码块，而包含在这种字符串中的代码也不会受到包含该函数调用的代码中的 @code{global} 语句影响。 这同样适用于 @ref{c6a,,eval()} 和 @ref{2ee,,compile()} 函数。

@node nonlocal 语句,,global 语句,简单语句
@anchor{reference/simple_stmts nonlocal}@anchor{d0f}@anchor{reference/simple_stmts the-nonlocal-statement}@anchor{16fa}
@subsection @code{nonlocal} 语句


@geindex 语句; nonlocal
@geindex @comma{} (comma); identifier list

@example
@anchor{reference/simple_stmts grammar-token-nonlocal-stmt}@anchor{16fb}nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
@end example

@c XXX add when implemented
@c : ["=" (`target_list` "=")+ starred_expression]
@c : | "nonlocal" identifier augop expression_list

@ref{d0f,,nonlocal} 语句会使得所列出的名称指向之前在最近的包含作用域中绑定的除全局变量以外的变量。 这种功能很重要，因为绑定的默认行为是先搜索局部命名空间。 这个语句允许被封装的代码重新绑定局部作用域以外且非全局（模块）作用域当中的变量。

@c XXX not implemented
@c The :keyword:`nonlocal` statement may prepend an assignment or augmented
@c assignment, but not an expression.

与 @ref{13a7,,global} 语句中列出的名称不同，@ref{d0f,,nonlocal} 语句中列出的名称必须指向之前存在于包含作用域之中的绑定（在这个应当用来创建新绑定的作用域不能被无歧义地确定）。

@ref{d0f,,nonlocal} 语句中列出的名称不得与之前存在于局部作用域中的绑定相冲突。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3104

@item PEP 3104@footnote{https://www.python.org/dev/peps/pep-3104} - 访问外层作用域中的名称

有关 @ref{d0f,,nonlocal} 语句的规范说明。
@end table


@node 复合语句,顶级组件,简单语句,Python 语言参考手册
@anchor{reference/compound_stmts doc}@anchor{16fc}@anchor{reference/compound_stmts compound}@anchor{16fd}@anchor{reference/compound_stmts compound-statements}@anchor{16fe}
@section 复合语句


@geindex compound; statement

复合语句是包含其它语句（语句组）的语句；它们会以某种方式影响或控制所包含其它语句的执行。 通常，复合语句会跨越多行，虽然在某些简单形式下整个复合语句也可能包含于一行之内。

@ref{eb3,,if}, @ref{1390,,while} 和 @ref{d02,,for} 语句用来实现传统的控制流程构造。 @ref{e3f,,try} 语句为一组语句指定异常处理和/和清理代码，而 @ref{7e4,,with} 语句允许在一个代码块周围执行初始化和终结化代码。 函数和类定义在语法上也属于复合语句。

@geindex clause
@geindex suite
@geindex ; (semicolon)

一条复合语句由一个或多个‘子句’组成。 一个子句则包含一个句头和一个‘句体’。 特定复合语句的子句头都处于相同的缩进层级。 每个子句头以一个作为唯一标识的关键字开始并以一个冒号结束。 子句体是由一个子句控制的一组语句。 子句体可以是在子句头的冒号之后与其同处一行的一条或由分号分隔的多条简单语句，或者也可以是在其之后缩进的一行或多行语句。 只有后一种形式的子句体才能包含嵌套的复合语句；以下形式是不合法的，这主要是因为无法分清某个后续的 @ref{1397,,else} 子句应该属于哪个 @ref{eb3,,if} 子句:

@example
if test1: if test2: print(x)
@end example

还要注意的是在这种情形下分号的绑定比冒号更紧密，因此在以下示例中，所有 @ref{97a,,print()} 调用或者都不执行，或者都执行:

@example
if x < y < z: print(x); print(y); print(z)
@end example

总结:

@example
@anchor{reference/compound_stmts grammar-token-compound-stmt}@anchor{16ff}compound_stmt ::= if_stmt
                  | while_stmt
                  | for_stmt
                  | try_stmt
                  | with_stmt
                  | funcdef
                  | classdef
                  | async_with_stmt
                  | async_for_stmt
                  | async_funcdef
@anchor{reference/compound_stmts grammar-token-suite}@anchor{1700}suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
@anchor{reference/compound_stmts grammar-token-statement}@anchor{1701}statement     ::= stmt_list NEWLINE | compound_stmt
@anchor{reference/compound_stmts grammar-token-stmt-list}@anchor{1702}stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]
@end example

@geindex NEWLINE token
@geindex DEDENT token
@geindex dangling; else

请注意语句总是以 @code{NEWLINE} 结束，之后可能跟随一个 @code{DEDENT}。 还要注意可选的后续子句总是以一个不能作为语句开头的关键字作为开头，因此不会产生歧义（‘悬空的 @ref{1397,,else}’问题在 Python 中是通过要求嵌套的 @ref{eb3,,if} 语句必须缩进来解决的)。

为了保证清晰，以下各节中语法规则采用将每个子句都放在单独行中的格式。
@anchor{reference/compound_stmts if}@anchor{eb3}@anchor{reference/compound_stmts elif}@anchor{1396}
@menu
* if 语句: if 语句<2>. 
* while 语句:: 
* for 语句: for 语句<2>. 
* try 语句:: 
* with 语句:: 
* 函数定义:: 
* 类定义:: 
* 协程: 协程<2>. 

@end menu

@node if 语句<2>,while 语句,,复合语句
@anchor{reference/compound_stmts else}@anchor{1397}@anchor{reference/compound_stmts the-if-statement}@anchor{1703}
@subsection @code{if} 语句


@geindex 语句; if
@geindex 关键字; elif
@geindex 关键字; else
@geindex ; (colon); compound statement

@ref{eb3,,if} 语句用于有条件的执行:

@example
@anchor{reference/compound_stmts grammar-token-if-stmt}@anchor{1704}if_stmt ::= "if" assignment_expression ":" suite
            ("elif" assignment_expression ":" suite)*
            ["else" ":" suite]
@end example

它通过对表达式逐个求值直至找到一个真值（请参阅 @ref{16b1,,布尔运算} 了解真值与假值的定义）在子句体中选择唯一匹配的一个；然后执行该子句体（而且 @ref{eb3,,if} 语句的其他部分不会被执行或求值）。 如果所有表达式均为假值，则如果 @ref{1397,,else} 子句体如果存在就会被执行。

@node while 语句,for 语句<2>,if 语句<2>,复合语句
@anchor{reference/compound_stmts the-while-statement}@anchor{1705}@anchor{reference/compound_stmts while}@anchor{1390}
@subsection @code{while} 语句


@geindex 语句; while
@geindex 关键字; else
@geindex loop; statement
@geindex ; (colon); compound statement

@ref{1390,,while} 语句用于在表达式保持为真的情况下重复地执行:

@example
@anchor{reference/compound_stmts grammar-token-while-stmt}@anchor{1706}while_stmt ::= "while" assignment_expression ":" suite
               ["else" ":" suite]
@end example

这将重复地检验表达式，并且如果其值为真就执行第一个子句体；如果表达式值为假（这可能在第一次检验时就发生）则如果 @code{else} 子句体存在就会被执行并终止循环。

@geindex 语句; break
@geindex 语句; continue

第一个子句体中的 @ref{403,,break} 语句在执行时将终止循环且不执行 @code{else} 子句体。 第一个子句体中的 @ref{2c2,,continue} 语句在执行时将跳过子句体中的剩余部分并返回检验表达式。

@node for 语句<2>,try 语句,while 语句,复合语句
@anchor{reference/compound_stmts for}@anchor{d02}@anchor{reference/compound_stmts the-for-statement}@anchor{1707}
@subsection @code{for} 语句


@geindex 语句; for
@geindex 关键字; in
@geindex 关键字; else
@geindex target; list
@geindex loop; statement
@geindex 对象; sequence
@geindex ; (colon); compound statement

@ref{d02,,for} 语句用于对序列（例如字符串、元组或列表）或其他可迭代对象中的元素进行迭代:

@example
@anchor{reference/compound_stmts grammar-token-for-stmt}@anchor{1708}for_stmt ::= "for" target_list "in" expression_list ":" suite
             ["else" ":" suite]
@end example

表达式列表会被求值一次；它应该产生一个可迭代对象。 系统将为 @code{expression_list} 的结果创建一个迭代器，然后将为迭代器所提供的每一项执行一次子句体，具体次序与迭代器的返回顺序一致。 每一项会按标准赋值规则 (参见 @ref{16d1,,赋值语句}) 被依次赋值给目标列表，然后子句体将被执行。 当所有项被耗尽时 (这会在序列为空或迭代器引发 @ref{58a,,StopIteration} 异常时立刻发生)，@code{else} 子句的子句体如果存在将会被执行，并终止循环。

@geindex 语句; break
@geindex 语句; continue

第一个子句体中的 @ref{403,,break} 语句在执行时将终止循环且不执行 @code{else} 子句体。 第一个子句体中的 @ref{2c2,,continue} 语句在执行时将跳过子句体中的剩余部分并转往下一项继续执行，或者在没有下一项时转往 @code{else} 子句执行。

for 循环会对目标列表中的变量进行赋值。 这将覆盖之前对这些变量的所有赋值，包括在 for 循环体中的赋值:

@example
for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range
@end example

@geindex 內置函数; range

目标列表中的名称在循环结束时不会被删除，但如果序列为空，则它们根本不会被循环所赋值。 提示：内置函数 @ref{1f6,,range()} 会返回一个可迭代的整数序列，适用于模拟 Pascal 中的 @code{for i := a to b do} 这种效果；例如 @code{list(range(3))} 会返回列表 @code{[0, 1, 2]}。

@cartouche
@quotation 注解 
@geindex loop; over mutable sequence
@geindex mutable sequence; loop over

当序列在循环中被修改时会有一个微妙的问题（这只可能发生于可变序列例如列表中）。 会有一个内部计数器被用来跟踪下一个要使用的项，每次迭代都会使计数器递增。 当计数器值达到序列长度时循环就会终止。 这意味着如果语句体从序列中删除了当前（或之前）的一项，下一项就会被跳过（因为其标号将变成已被处理的当前项的标号）。 类似地，如果语句体在序列当前项的前面插入一个新项，当前项会在循环的下一轮中再次被处理。 这会导致麻烦的程序错误，避免此问题的办法是对整个序列使用切片来创建一个临时副本，例如

@example
for x in a[:]:
    if x < 0: a.remove(x)
@end example
@end quotation
@end cartouche
@anchor{reference/compound_stmts try}@anchor{e3f}@anchor{reference/compound_stmts except}@anchor{c19}
@node try 语句,with 语句,for 语句<2>,复合语句
@anchor{reference/compound_stmts finally}@anchor{2c3}@anchor{reference/compound_stmts the-try-statement}@anchor{1709}
@subsection @code{try} 语句


@geindex 语句; try
@geindex 关键字; except
@geindex 关键字; finally
@geindex 关键字; else
@geindex 关键字; as
@geindex ; (colon); compound statement

@ref{e3f,,try} 语句可为一组语句指定异常处理器和/或清理代码:

@example
@anchor{reference/compound_stmts grammar-token-try-stmt}@anchor{170a}try_stmt  ::= try1_stmt | try2_stmt
@anchor{reference/compound_stmts grammar-token-try1-stmt}@anchor{170b}try1_stmt ::= "try" ":" suite
              ("except" [expression ["as" identifier]] ":" suite)+
              ["else" ":" suite]
              ["finally" ":" suite]
@anchor{reference/compound_stmts grammar-token-try2-stmt}@anchor{170c}try2_stmt ::= "try" ":" suite
              "finally" ":" suite
@end example

@ref{c19,,except} 子句指定一个或多个异常处理程序。 当 @ref{e3f,,try} 子句中无异常发生时，也不会有任何异常处理程序被执行。 当 @code{try} 子句中发生异常时，将启动对异常处理程序的搜索。 此搜索会逐一检查 except 子句直至找到与该异常相匹配的子句。 如果存在无表达式的 except 子句，它必须是最后一个；它将匹配任何异常。 对于带有表达式的 except 子句，该表达式会被未付，如果结果对象与发生的异常“兼容”，则该子句将匹配当前异常。 如果一个对象是异常对象所属的类或是其 @ref{c0e,,非虚基类}，或者是包含异常对象的类的非虚基类的元组，则此对象与异常是兼容的。

如果没有 except 子句与异常相匹配，则会在周边代码和发起调用栈上继续搜索异常处理器。 @footnote{@w{(1)} 
异常会被传播给发起调用栈，除非存在一个 @ref{2c3,,finally} 子句正好引发了另一个异常。 新引发的异常将导致旧异常的丢失。
}

如果在对 except 子句头中的表达式求值时引发了异常，则原来对处理器的搜索会被取消，并在周边代码和调用栈上启动对新异常的搜索（它会被视作是整个 @ref{e3f,,try} 语句所引发的异常）。

@geindex as; except clause

当找到一个匹配的 except 子句时，该异常将被赋值给该 except 子句在 @code{as} 关键字之后指定的目标，如果存在此关键字的话，并且该 except 子句体将被执行。 所有 except 子句都必须有可执行的子句体。 当到达子句体的末尾时，通常会转向整个 try 语句之后继续执行。 （这意味着如果对于同一异常存在有嵌套的两个处理器，而异常发生于内层处理器的 try 子句中，则外层处理器将不会处理该异常。）

当使用 @code{as} 将目标赋值为一个异常时，它将在 except 子句结束时被清除。 这就相当于

@example
except E as N:
    foo
@end example

被转写为

@example
except E as N:
    try:
        foo
    finally:
        del N
@end example

这意味着异常必须赋值给一个不同的名称才能在 except 子句之后引用它。 异常会被清除是因为在附加了回溯信息的情况下，它们会形成堆栈帧的循环引用，使得所有局部变量保持存活直到发生下一次垃圾回收。

@geindex 模块; sys
@geindex 对象; traceback

在一个 except 子句体被执行之前，有关异常的详细信息存放在 @ref{fd,,sys} 模块中，可通过 @ref{d2f,,sys.exc_info()} 来访问。 @ref{d2f,,sys.exc_info()} 返回一个 3 元组，由异常类、异常实例和回溯对象组成（参见 @ref{1582,,标准类型层级结构} 一节），用于在程序中标识异常发生点。 当从处理异常的函数返回时 @ref{d2f,,sys.exc_info()} 的值会恢复为（调用前的）原值。

@geindex 关键字; else
@geindex 语句; return
@geindex 语句; break
@geindex 语句; continue

如果控制流离开 @ref{e3f,,try} 子句体时没有引发异常，并且没有执行 @ref{2cf,,return}, @ref{2c2,,continue} 或 @ref{403,,break} 语句，可选的 @code{else} 子句将被执行。  @code{else} 语句中的异常不会由之前的 @ref{c19,,except} 子句处理。

@geindex 关键字; finally

如果存在 @ref{2c3,,finally}，它将指定一个‘清理’处理程序。 @ref{e3f,,try} 子句会被执行，包括任何 @ref{c19,,except} 和 @code{else} 子句。 如果在这些子句中发生任何未处理的异常，该异常会被临时保存。 @code{finally} 子句将被执行。 如果存在被保存的异常，它会在 @code{finally} 子句的末尾被重新引发。 如果 @code{finally} 子句引发了另一个异常，被保存的异常会被设为新异常的上下文。 如果 @code{finally} 子句执行了 @ref{2cf,,return}, @ref{403,,break} 或 @ref{2c2,,continue} 语句，则被保存的异常会被丢弃:

@example
>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42
@end example

在 @ref{2c3,,finally} 子句执行期间，程序不能获取异常信息。

@geindex 语句; return
@geindex 语句; break
@geindex 语句; continue

当 @ref{2cf,,return}, @ref{403,,break} 或 @ref{2c2,,continue} 语句在一个 @code{try}...@code{finally} 语句的 @ref{e3f,,try} 子语句体中被执行时，@ref{2c3,,finally} 子语句也会‘在离开时’被执行。

函数的返回值是由最后被执行的 @ref{2cf,,return} 语句所决定的。 由于 @ref{2c3,,finally} 子句总是被执行，因此在 @code{finally} 子句中被执行的 @code{return} 语句总是最后被执行的:

@example
>>> def foo():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> foo()
'finally'
@end example

有关异常的更多信息可以在 @ref{1612,,异常} 一节找到，有关使用 @ref{d12,,raise} 语句生成异常的信息可以在 @ref{d12,,raise 语句} 一节找到。


在 3.8 版更改: 在 Python 3.8 之前，@ref{2c2,,continue} 语句不允许在 @ref{2c3,,finally} 子句中使用，这是因为具体实现存在一个问题。

@anchor{reference/compound_stmts with}@anchor{7e4}
@node with 语句,函数定义,try 语句,复合语句
@anchor{reference/compound_stmts as}@anchor{170d}@anchor{reference/compound_stmts the-with-statement}@anchor{170e}
@subsection @code{with} 语句


@geindex 语句; with
@geindex 关键字; as
@geindex as; with statement
@geindex @comma{} (comma); with statement
@geindex ; (colon); compound statement

@ref{7e4,,with} 语句用于包装带有使用上下文管理器 (参见 @ref{15f3,,with 语句上下文管理器} 一节) 定义的方法的代码块的执行。 这允许对普通的 @ref{e3f,,try}...@ref{c19,,except}...@ref{2c3,,finally} 使用模式进行封装以方便地重用。

@example
@anchor{reference/compound_stmts grammar-token-with-stmt}@anchor{170f}with_stmt ::= "with" with_item ("," with_item)* ":" suite
@anchor{reference/compound_stmts grammar-token-with-item}@anchor{1710}with_item ::= expression ["as" target]
@end example

带有一个“项目”的 @ref{7e4,,with} 语句的执行过程如下:


@enumerate 

@item 
对上下文表达式 (在 @ref{1710,,with_item} 中给出的表达式) 求值以获得一个上下文管理器。

@item 
载入上下文管理器的 @ref{d65,,__enter__()} 以便后续使用。

@item 
载入上下文管理器的 @ref{d66,,__exit__()} 以便后续使用。

@item 
发起调用上下文管理器的 @ref{d65,,__enter__()} 方法。

@item 
如果 @ref{7e4,,with} 语句中包含一个目标，来自 @ref{d65,,__enter__()} 的返回值将被赋值给它。

@cartouche
@quotation 注解 
@ref{7e4,,with} 语句会保证如果 @ref{d65,,__enter__()} 方法返回时未发生错误，则 @ref{d66,,__exit__()} 将总是被调用。 因此，如果在对目标列表赋值期间发生错误，则会将其视为在语句体内部发生的错误。 参见下面的第 6 步。
@end quotation
@end cartouche

@item 
执行语句体。

@item 
发起调用上下文管理器的 @ref{d66,,__exit__()} 方法。 如果语句体的退出是由异常导致的，则其类型、值和回溯信息将被作为参数传递给 @ref{d66,,__exit__()}。 否则的话，将提供三个 @ref{204,,None} 参数。

如果语句体的退出是由异常导致的，并且来自 @ref{d66,,__exit__()} 方法的返回值为假，则该异常会被重新引发。 如果返回值为真，则该异常会被抑制，并会继续执行 @ref{7e4,,with} 语句之后的语句。

如果语句体由于异常以外的任何原因退出，则来自 @ref{d66,,__exit__()} 的返回值会被忽略，并会在该类退出正常的发生位置继续执行。
@end enumerate

以下代码:

@example
with EXPRESSION as TARGET:
    SUITE
@end example

在语义上等价于:

@example
manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(manager, None, None, None)
@end example

如果有多个项目，则会视作存在多个 @ref{7e4,,with} 语句嵌套来处理多个上下文管理器:

@example
with A() as a, B() as b:
    SUITE
@end example

在语义上等价于:

@example
with A() as a:
    with B() as b:
        SUITE
@end example


在 3.1 版更改: 支持多个上下文表达式。



@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 343

@item PEP 343@footnote{https://www.python.org/dev/peps/pep-0343} - "with" 语句

Python @ref{7e4,,with} 语句的规范描述、背景和示例。
@end table


@geindex parameter; function definition
@anchor{reference/compound_stmts function}@anchor{13bf}
@node 函数定义,类定义,with 语句,复合语句
@anchor{reference/compound_stmts def}@anchor{e8b}@anchor{reference/compound_stmts function-definitions}@anchor{1711}
@subsection 函数定义


@geindex 语句; def
@geindex function; definition
@geindex function; name
@geindex name; binding
@geindex 对象; user-defined function
@geindex 对象; function
@geindex function; name
@geindex name; binding
@geindex () (parentheses); function definition
@geindex @comma{} (comma); parameter list
@geindex ; (colon); compound statement

函数定义就是对用户自定义函数的定义（参见 @ref{1582,,标准类型层级结构} 一节）:

@example
@anchor{reference/compound_stmts grammar-token-funcdef}@anchor{1712}funcdef                   ::= [decorators] "def" funcname "(" [parameter_list] ")"
                              ["->" expression] ":" suite
@anchor{reference/compound_stmts grammar-token-decorators}@anchor{1713}decorators                ::= decorator+
@anchor{reference/compound_stmts grammar-token-decorator}@anchor{1714}decorator                 ::= "@@" assignment_expression NEWLINE
@anchor{reference/compound_stmts grammar-token-parameter-list}@anchor{1715}parameter_list            ::= defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
                                | parameter_list_no_posonly
@anchor{reference/compound_stmts grammar-token-parameter-list-no-posonly}@anchor{1716}parameter_list_no_posonly ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                              | parameter_list_starargs
@anchor{reference/compound_stmts grammar-token-parameter-list-starargs}@anchor{1717}parameter_list_starargs   ::= "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                              | "**" parameter [","]
@anchor{reference/compound_stmts grammar-token-parameter}@anchor{1718}parameter                 ::= identifier [":" expression]
@anchor{reference/compound_stmts grammar-token-defparameter}@anchor{1719}defparameter              ::= parameter ["=" expression]
@anchor{reference/compound_stmts grammar-token-funcname}@anchor{171a}funcname                  ::= identifier
@end example

函数定义是一条可执行语句。 它执行时会在当前局部命名空间中将函数名称绑定到一个函数对象（函数可执行代码的包装器）。 这个函数对象包含对当前全局命名空间的引用，作为函数被调用时所使用的全局命名空间。

函数定义并不会执行函数体；只有当函数被调用时才会执行此操作。 @footnote{@w{(2)} 
作为函数体的第一条语句出现的字符串字面值会被转换为函数的 @code{__doc__} 属性，也就是该函数的 @ref{171b,,docstring}。
}

@geindex @@ (at); function definition

一个函数定义可以被一个或多个 @ref{174,,decorator} 表达式所包装。 当函数被定义时将在包含该函数定义的作用域中对装饰器表达式求值。 求值结果必须是一个可调用对象，它会以该函数对象作为唯一参数被发起调用。 其返回值将被绑定到函数名称而非函数对象。 多个装饰器会以嵌套方式被应用。 例如以下代码

@example
@@f1(arg)
@@f2
def func(): pass
@end example

大致等价于

@example
def func(): pass
func = f1(arg)(f2(func))
@end example

不同之处在于原始函数并不会被临时绑定到名称 @code{func}。


在 3.9 版更改: 函数可使用任何有效的 @ref{16ba,,assignment_expression} 来装饰。 在之前版本中，此语法则更为受限，详情参见 
@geindex Python 提高建议; PEP 614
PEP 614@footnote{https://www.python.org/dev/peps/pep-0614}。


@geindex default; parameter; value
@geindex argument; function definition
@geindex = (equals); function definition

当一个或多个 @ref{1693,,形参} 具有 @emph{形参} @code{=} @emph{表达式} 这样的形式时，该函数就被称为具有“默认形参值”。 对于一个具有默认值的形参，其对应的 @ref{168a,,argument} 可以在调用中被省略，在此情况下会用形参的默认值来替代。 如果一个形参具有默认值，后续所有在 "@code{*}" 之前的形参也必须具有默认值 --- 这个句法限制并未在语法中明确表达。

@strong{默认形参值会在执行函数定义时按从左至右的顺序被求值。} 这意味着当函数被定义时将对表达式求值一次，相同的“预计算”值将在每次调用时被使用。 这一点在默认形参为可变对象，例如列表或字典的时候尤其需要重点理解：如果函数修改了该对象（例如向列表添加了一项），则实际上默认值也会被修改。 这通常不是人们所预期的。 绕过此问题的一个方法是使用 @code{None} 作为默认值，并在函数体中显式地对其进行测试，例如:

@example
def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin
@end example

@geindex / (slash); function definition
@geindex * (asterisk); function definition
@geindex **; function definition

函数调用的语义在 @ref{749,,调用} 一节中有更详细的描述。 函数调用总是会给形参列表中列出的所有形参赋值，或是用位置参数，或是用关键字参数，或是用默认值。 如果存在 "@code{*identifier}" 这样的形式，它会被初始化为一个元组来接收任何额外的位置参数，默认为一个空元组。 如果存在 "@code{**identifier}" 这样的形式，它会被初始化为一个新的有序映射来接收任何额外的关键字参数，默认为一个相同类型的空映射。 在 "@code{*}" 或 "@code{*identifier}" 之后的形参都是仅限关键字形参因而只能通过关键字参数传入。 在 "@code{/}" 之前的形参都是仅限位置形参因而只能通过位置参数传入。


在 3.8 版更改: 可以使用 @code{/} 函数形参语法来标示仅限位置形参。 请参阅 
@geindex Python 提高建议; PEP 570
PEP 570@footnote{https://www.python.org/dev/peps/pep-0570} 了解详情。


@geindex function; annotations
@geindex ->; function annotations
@geindex ; (colon); function annotations

形参可以带有 @ref{13c0,,标注}，其形式为在形参名称后加上 "@code{: expression}"。 任何形参都可以带有标注，甚至 @code{*identifier} 或 @code{**identifier} 这样的形参也可以。 函数可以带有“返回”标注，其形式为在形参列表后加上 "@code{-> expression}"。 这些标注可以是任何有效的 Python 表达式。 标注的存在不会改变函数的语义。 标注值可以作为函数对象的 @code{__annotations__} 属性中以对应形参名称为键的字典值被访问。 如果使用了 @code{annotations} import from @ref{0,,__future__} 的方式，则标注会在运行时保存为字符串以启用延迟求值特性。 否则，它们会在执行函数定义时被求值。 在这种情况下，标注的求值顺序可能与它们在源代码中出现的顺序不同。

@geindex lambda; expression

创建匿名函数（未绑定到一个名称的函数）以便立即在表达式中使用也是可能的。 这需要使用 lambda 表达式，具体描述见 @ref{d01,,lambda 表达式} 一节。 请注意 lambda 只是简单函数定义的一种简化写法；在 "@ref{e8b,,def}" 语句中定义的函数也可以像用 lambda 表达式定义的函数一样被传递或赋值给其他名称。 "@code{def}" 形式实际上更为强大，因为它允许执行多条语句和使用标注。

@strong{程序员注意事项:} 函数属于一类对象。 在一个函数内部执行的 "@code{def}" 语句会定义一个局部函数并可被返回或传递。 在嵌套函数中使用的自由变量可以访问包含该 def 语句的函数的局部变量。 详情参见 @ref{1608,,命名与绑定} 一节。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3107

@item PEP 3107@footnote{https://www.python.org/dev/peps/pep-3107} - 函数标注

最初的函数标注规范说明。

@geindex Python 提高建议; PEP 484

@item PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} - 类型提示

标注的标准含意定义：类型提示。

@geindex Python 提高建议; PEP 526

@item PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} - 变量标注的语法

变量声明的类型提示功能，包括类变量和实例变量

@geindex Python 提高建议; PEP 563

@item PEP 563@footnote{https://www.python.org/dev/peps/pep-0563} - 延迟的标注求值

支持在运行时通过以字符串形式保存标注而非不是即求值来实现标注内部的向前引用。
@end table


@node 类定义,协程<2>,函数定义,复合语句
@anchor{reference/compound_stmts class}@anchor{d3a}@anchor{reference/compound_stmts class-definitions}@anchor{171c}
@subsection 类定义


@geindex 对象; class
@geindex 语句; class
@geindex class; definition
@geindex class; name
@geindex name; binding
@geindex execution; frame
@geindex inheritance
@geindex docstring
@geindex () (parentheses); class definition
@geindex @comma{} (comma); expression list
@geindex ; (colon); compound statement

类定义就是对类对象的定义 (参见 @ref{1582,,标准类型层级结构} 一节):

@example
@anchor{reference/compound_stmts grammar-token-classdef}@anchor{171d}classdef    ::= [decorators] "class" classname [inheritance] ":" suite
@anchor{reference/compound_stmts grammar-token-inheritance}@anchor{171e}inheritance ::= "(" [argument_list] ")"
@anchor{reference/compound_stmts grammar-token-classname}@anchor{171f}classname   ::= identifier
@end example

类定义是一条可执行语句。 其中继承列表通常给出基类的列表 (进阶用法请参见 @ref{15ab,,元类})，列表中的每一项都应当被求值为一个允许子类的类对象。 没有继承列表的类默认继承自基类 @ref{3da,,object}；因此，:

@example
class Foo:
    pass
@end example

等价于

@example
class Foo(object):
    pass
@end example

随后类体将在一个新的执行帧 (参见 @ref{1608,,命名与绑定}) 中被执行，使用新创建的局部命名空间和原有的全局命名空间。 （通常，类体主要包含函数定义。） 当类体结束执行时，其执行帧将被丢弃而其局部命名空间会被保存。 @footnote{@w{(3)} 
作为类体的第一条语句出现的字符串字面值会被转换为命名空间的 @code{__doc__} 条目，也就是该类的 @ref{171b,,docstring}。
} 一个类对象随后会被创建，其基类使用给定的继承列表，属性字典使用保存的局部命名空间。 类名称将在原有的全局命名空间中绑定到该类对象。

在类体内定义的属性的顺序保存在新类的 @code{__dict__} 中。 请注意此顺序的可靠性只限于类刚被创建时，并且只适用于使用定义语法所定义的类。

类的创建可使用 @ref{15ab,,元类} 进行重度定制。

@geindex @@ (at); class definition

类也可以被装饰：就像装饰函数一样，:

@example
@@f1(arg)
@@f2
class Foo: pass
@end example

大致等价于

@example
class Foo: pass
Foo = f1(arg)(f2(Foo))
@end example

装饰器表达式的求值规则与函数装饰器相同。 结果随后会被绑定到类名称。


在 3.9 版更改: 类可使用任何有效的 @ref{16ba,,assignment_expression} 来装饰。 在之前版本中，此语法则更为受限，详情参见 
@geindex Python 提高建议; PEP 614
PEP 614@footnote{https://www.python.org/dev/peps/pep-0614}。


@strong{程序员注意事项:} 在类定义内定义的变量是类属性；它们将被类实例所共享。 实例属性可通过 @code{self.name = value} 在方法中设定。 类和实例属性均可通过 "@code{self.name}" 表示法来访问，当通过此方式访问时实例属性会隐藏同名的类属性。 类属性可被用作实例属性的默认值，但在此场景下使用可变值可能导致未预期的结果。 可以使用 @ref{5ec,,描述器} 来创建具有不同实现细节的实例变量。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3115

@item PEP 3115@footnote{https://www.python.org/dev/peps/pep-3115} - Python 3000 中的元类

将元类声明修改为当前语法的提议，以及关于如何构建带有元类的类的语义描述。

@geindex Python 提高建议; PEP 3129

@item PEP 3129@footnote{https://www.python.org/dev/peps/pep-3129} - 类装饰器

增加类装饰器的提议。 函数和方法装饰器是在 
@geindex Python 提高建议; PEP 318
PEP 318@footnote{https://www.python.org/dev/peps/pep-0318} 中被引入的。
@end table


@node 协程<2>,,类定义,复合语句
@anchor{reference/compound_stmts async}@anchor{2de}@anchor{reference/compound_stmts coroutines}@anchor{1720}
@subsection 协程



3.5 新版功能.


@geindex 语句; async def

@menu
* 协程函数定义:: 
* async for 语句:: 
* async with 语句:: 

@end menu

@node 协程函数定义,async for 语句,,协程<2>
@anchor{reference/compound_stmts async-def}@anchor{3b1}@anchor{reference/compound_stmts coroutine-function-definition}@anchor{1721}
@subsubsection 协程函数定义


@example
@anchor{reference/compound_stmts grammar-token-async-funcdef}@anchor{1722}async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
                  ["->" expression] ":" suite
@end example

@geindex 关键字; async
@geindex 关键字; await

Python 协程可以在多个位置上挂起和恢复执行 (参见 @ref{18a,,coroutine})。 在协程函数体内部，@code{await} 和 @code{async} 标识符已成为保留关键字；@ref{2df,,await} 表达式，@ref{406,,async for} 以及 @ref{740,,async with} 只能在协程函数体中使用。

使用 @code{async def} 语法定义的函数总是为协程函数，即使它们不包含 @code{await} 或 @code{async} 关键字。

在协程函数体中使用 @code{yield from} 表达式将引发 @ref{562,,SyntaxError}。

协程函数的例子:

@example
async def func(param1, param2):
    do_stuff()
    await some_coroutine()
@end example

@geindex 语句; async for

@node async for 语句,async with 语句,协程函数定义,协程<2>
@anchor{reference/compound_stmts async-for}@anchor{406}@anchor{reference/compound_stmts the-async-for-statement}@anchor{1723}
@subsubsection @code{async for} 语句


@example
@anchor{reference/compound_stmts grammar-token-async-for-stmt}@anchor{1724}async_for_stmt ::= "async" for_stmt
@end example

@ref{73d,,asynchronous iterable} 提供了 @code{__aiter__} 方法，该方法会直接返回 @ref{742,,asynchronous iterator}，它可以在其 @code{__anext__} 方法中调用异步代码。

@code{async for} 语句允许方便地对异步可迭代对象进行迭代。

以下代码:

@example
async for TARGET in ITER:
    SUITE
else:
    SUITE2
@end example

在语义上等价于:

@example
iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True

while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
        SUITE
else:
    SUITE2
@end example

另请参阅 @ref{58b,,__aiter__()} 和 @ref{158e,,__anext__()} 了解详情。

在协程函数体之外使用 @code{async for} 语句将引发 @ref{562,,SyntaxError}。

@geindex 语句; async with

@node async with 语句,,async for 语句,协程<2>
@anchor{reference/compound_stmts async-with}@anchor{740}@anchor{reference/compound_stmts the-async-with-statement}@anchor{1725}
@subsubsection @code{async with} 语句


@example
@anchor{reference/compound_stmts grammar-token-async-with-stmt}@anchor{1726}async_with_stmt ::= "async" with_stmt
@end example

@ref{73e,,asynchronous context manager} 是一种 @ref{66b,,context manager}，能够在其 @emph{enter} 和 @emph{exit} 方法中暂停执行。

以下代码:

@example
async with EXPRESSION as TARGET:
    SUITE
@end example

在语义上等价于:

@example
manager = (EXPRESSION)
aenter = type(manager).__aenter__
aexit = type(manager).__aexit__
value = await aenter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not await aexit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        await aexit(manager, None, None, None)
@end example

另请参阅 @ref{10e3,,__aenter__()} 和 @ref{10e4,,__aexit__()} 了解详情。

在协程函数体之外使用 @code{async with} 语句将引发 @ref{562,,SyntaxError}。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 492

@item PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} - 使用 async 和 await 语法实现协程

将协程作为 Python 中的一个正式的单独概念，并增加相应的支持语法。
@end table


@node 顶级组件,完整的语法规范,复合语句,Python 语言参考手册
@anchor{reference/toplevel_components doc}@anchor{1727}@anchor{reference/toplevel_components top-level}@anchor{1728}@anchor{reference/toplevel_components top-level-components}@anchor{1729}
@section 顶级组件


@geindex interpreter

Python 解释器可以从多种源获得输入：作为标准输入或程序参数传入的脚本，以交互方式键入的语句，导入的模块源文件等等。 这一章将给出在这些情况下所用的语法。

@menu
* 完整的 Python 程序:: 
* 文件输入:: 
* 交互式输入:: 
* 表达式输入:: 

@end menu

@node 完整的 Python 程序,文件输入,,顶级组件
@anchor{reference/toplevel_components complete-python-programs}@anchor{172a}@anchor{reference/toplevel_components programs}@anchor{1633}
@subsection 完整的 Python 程序


@geindex program

@geindex 模块; sys
@geindex 模块; __main__
@geindex 模块; builtins

虽然语言规范描述不必规定如何发起调用语言解释器，但对完整的 Python 程序加以说明还是很有用的。 一个完整的 Python 程序会在最小初始化环境中被执行：所有内置和标准模块均为可用，但均处于未初始化状态，只有 @ref{fd,,sys} (各种系统服务), @ref{12,,builtins} (内置函数、异常以及 @code{None}) 和 @ref{1,,__main__} 除外。 最后一个模块用于为完整程序的执行提供局部和全局命名空间。

适用于一个完整 Python 程序的语法即下节所描述的文件输入。

@geindex interactive mode
@geindex 模块; __main__

解释器也可以通过交互模式被发起调用；在此情况下，它并不读取和执行一个完整程序，而是每次读取和执行一条语句（可能为复合语句）。 此时的初始环境与一个完整程序的相同；每条语句会在 @ref{1,,__main__} 的命名空间中被执行。

@geindex UNIX
@geindex Windows
@geindex command line
@geindex standard input

一个完整程序可通过三种形式被传递给解释器：使用 @ref{136f,,-c} @emph{字符串} 命令行选项，使用一个文件作为第一个命令行参数，或者使用标准输入。 如果文件或标准输入是一个 tty 设置，解释器会进入交互模式；否则的话，它会将文件当作一个完整程序来执行。

@node 文件输入,交互式输入,完整的 Python 程序,顶级组件
@anchor{reference/toplevel_components file-input}@anchor{172b}@anchor{reference/toplevel_components id1}@anchor{172c}
@subsection 文件输入


所有从非交互式文件读取的输入都具有相同的形式:

@example
@anchor{reference/toplevel_components grammar-token-file-input}@anchor{172d}file_input ::= (NEWLINE | statement)*
@end example

此语法用于下列几种情况:


@itemize *

@item 
解析一个完整 Python 程序时（从文件或字符串）；

@item 
解析一个模块时；

@item 
解析一个传递给 @ref{d14,,exec()} 函数的字符串时；
@end itemize

@node 交互式输入,表达式输入,文件输入,顶级组件
@anchor{reference/toplevel_components interactive}@anchor{172e}@anchor{reference/toplevel_components interactive-input}@anchor{172f}
@subsection 交互式输入


交互模式下的输入使用以下语法进行解析:

@example
@anchor{reference/toplevel_components grammar-token-interactive-input}@anchor{1730}interactive_input ::= [stmt_list] NEWLINE | compound_stmt NEWLINE
@end example

请注意在交互模式下一条（最高层级）复合语句必须带有一个空行；这对于帮助解析器确定输入的结束是必须的。

@node 表达式输入,,交互式输入,顶级组件
@anchor{reference/toplevel_components expression-input}@anchor{1731}@anchor{reference/toplevel_components id2}@anchor{1732}
@subsection 表达式输入


@geindex input

@geindex 內置函数; eval

@ref{c6a,,eval()} 被用于表达式输入。 它会忽略开头的空白。 传递给 @ref{c6a,,eval()} 的字符串参数必须具有以下形式:

@example
@anchor{reference/toplevel_components grammar-token-eval-input}@anchor{1733}eval_input ::= expression_list NEWLINE*
@end example

@node 完整的语法规范,,顶级组件,Python 语言参考手册
@anchor{reference/grammar doc}@anchor{1734}@anchor{reference/grammar full-grammar-specification}@anchor{1735}
@section 完整的语法规范


这是完整的 Python 语法规范，直接提取自用于生成 CPython 解析器的语法 (参见 Grammar/python.gram@footnote{https://github.com/python/cpython/tree/3.9/Grammar/python.gram})。 这里显示的版本省略了有关代码生成和错误恢复的细节。

所用的标记法是 EBNF@footnote{https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form} 和 PEG@footnote{https://en.wikipedia.org/wiki/Parsing_expression_grammar} 的混合体。 特别地，@code{&} 后跟一个符号、形符或带括号的分组来表示正向前视（即要求执行匹配但不会被消耗掉），而 @code{!} 表示负向前视（即要求 _不_ 执行匹配）。 我们使用 @code{|} 分隔符来表示 PEG 的“有序选择” (在传统 PEG 语法中则写为 @code{/})。

@example
# PEG grammar for Python

@@trailer '@w{'}'
void *
_PyPegen_parse(Parser *p)
@{
    // Initialize keywords
    p->keywords = reserved_keywords;
    p->n_keyword_lists = n_keyword_lists;

    // Run parser
    void *result = NULL;
    if (p->start_rule == Py_file_input) @{
        result = file_rule(p);
    @} else if (p->start_rule == Py_single_input) @{
        result = interactive_rule(p);
    @} else if (p->start_rule == Py_eval_input) @{
        result = eval_rule(p);
    @} else if (p->start_rule == Py_func_type_input) @{
        result = func_type_rule(p);
    @} else if (p->start_rule == Py_fstring_input) @{
        result = fstring_rule(p);
    @}

    return result;
@}

// The end
'@w{'}'
file[mod_ty]: a=[statements] ENDMARKER @{ _PyPegen_make_module(p, a) @}
interactive[mod_ty]: a=statement_newline @{ Interactive(a, p->arena) @}
eval[mod_ty]: a=expressions NEWLINE* ENDMARKER @{ Expression(a, p->arena) @}
func_type[mod_ty]: '(' a=[type_expressions] ')' '->' b=expression NEWLINE* ENDMARKER @{ FunctionType(a, b, p->arena) @}
fstring[expr_ty]: star_expressions

# type_expressions allow */** but ignore them
type_expressions[asdl_seq*]:
    | a=','.expression+ ',' '*' b=expression ',' '**' c=expression @{
        _PyPegen_seq_append_to_end(p, CHECK(_PyPegen_seq_append_to_end(p, a, b)), c) @}
    | a=','.expression+ ',' '*' b=expression @{ _PyPegen_seq_append_to_end(p, a, b) @}
    | a=','.expression+ ',' '**' b=expression @{ _PyPegen_seq_append_to_end(p, a, b) @}
    | '*' a=expression ',' '**' b=expression @{
        _PyPegen_seq_append_to_end(p, CHECK(_PyPegen_singleton_seq(p, a)), b) @}
    | '*' a=expression @{ _PyPegen_singleton_seq(p, a) @}
    | '**' a=expression @{ _PyPegen_singleton_seq(p, a) @}
    | ','.expression+

statements[asdl_seq*]: a=statement+ @{ _PyPegen_seq_flatten(p, a) @}
statement[asdl_seq*]: a=compound_stmt @{ _PyPegen_singleton_seq(p, a) @} | simple_stmt
statement_newline[asdl_seq*]:
    | a=compound_stmt NEWLINE @{ _PyPegen_singleton_seq(p, a) @}
    | simple_stmt
    | NEWLINE @{ _PyPegen_singleton_seq(p, CHECK(_Py_Pass(EXTRA))) @}
    | ENDMARKER @{ _PyPegen_interactive_exit(p) @}
simple_stmt[asdl_seq*]:
    | a=small_stmt !';' NEWLINE @{ _PyPegen_singleton_seq(p, a) @} # Not needed, there for speedup
    | a=';'.small_stmt+ [';'] NEWLINE @{ a @}
# NOTE: assignment MUST precede expression, else parsing a simple assignment
# will throw a SyntaxError.
small_stmt[stmt_ty] (memo):
    | assignment
    | e=star_expressions @{ _Py_Expr(e, EXTRA) @}
    | &'return' return_stmt
    | &('import' | 'from') import_stmt
    | &'raise' raise_stmt
    | 'pass' @{ _Py_Pass(EXTRA) @}
    | &'del' del_stmt
    | &'yield' yield_stmt
    | &'assert' assert_stmt
    | 'break' @{ _Py_Break(EXTRA) @}
    | 'continue' @{ _Py_Continue(EXTRA) @}
    | &'global' global_stmt
    | &'nonlocal' nonlocal_stmt
compound_stmt[stmt_ty]:
    | &('def' | '@@' | ASYNC) function_def
    | &'if' if_stmt
    | &('class' | '@@') class_def
    | &('with' | ASYNC) with_stmt
    | &('for' | ASYNC) for_stmt
    | &'try' try_stmt
    | &'while' while_stmt

# NOTE: annotated_rhs may start with 'yield'; yield_expr must start with 'yield'
assignment[stmt_ty]:
    | a=NAME ':' b=expression c=['=' d=annotated_rhs @{ d @}] @{
        CHECK_VERSION(
            6,
            "Variable annotation syntax is",
            _Py_AnnAssign(CHECK(_PyPegen_set_expr_context(p, a, Store)), b, c, 1, EXTRA)
        ) @}
    | a=('(' b=single_target ')' @{ b @}
         | single_subscript_attribute_target) ':' b=expression c=['=' d=annotated_rhs @{ d @}] @{
        CHECK_VERSION(6, "Variable annotations syntax is", _Py_AnnAssign(a, b, c, 0, EXTRA)) @}
    | a=(z=star_targets '=' @{ z @})+ b=(yield_expr | star_expressions) !'=' tc=[TYPE_COMMENT] @{
         _Py_Assign(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | a=single_target b=augassign ~ c=(yield_expr | star_expressions) @{
         _Py_AugAssign(a, b->kind, c, EXTRA) @}
    | invalid_assignment

augassign[AugOperator*]:
    | '+=' @{ _PyPegen_augoperator(p, Add) @}
    | '-=' @{ _PyPegen_augoperator(p, Sub) @}
    | '*=' @{ _PyPegen_augoperator(p, Mult) @}
    | '@@=' @{ CHECK_VERSION(5, "The '@@' operator is", _PyPegen_augoperator(p, MatMult)) @}
    | '/=' @{ _PyPegen_augoperator(p, Div) @}
    | '%=' @{ _PyPegen_augoperator(p, Mod) @}
    | '&=' @{ _PyPegen_augoperator(p, BitAnd) @}
    | '|=' @{ _PyPegen_augoperator(p, BitOr) @}
    | '^=' @{ _PyPegen_augoperator(p, BitXor) @}
    | '<<=' @{ _PyPegen_augoperator(p, LShift) @}
    | '>>=' @{ _PyPegen_augoperator(p, RShift) @}
    | '**=' @{ _PyPegen_augoperator(p, Pow) @}
    | '//=' @{ _PyPegen_augoperator(p, FloorDiv) @}

global_stmt[stmt_ty]: 'global' a=','.NAME+ @{
    _Py_Global(CHECK(_PyPegen_map_names_to_ids(p, a)), EXTRA) @}
nonlocal_stmt[stmt_ty]: 'nonlocal' a=','.NAME+ @{
    _Py_Nonlocal(CHECK(_PyPegen_map_names_to_ids(p, a)), EXTRA) @}

yield_stmt[stmt_ty]: y=yield_expr @{ _Py_Expr(y, EXTRA) @}

assert_stmt[stmt_ty]: 'assert' a=expression b=[',' z=expression @{ z @}] @{ _Py_Assert(a, b, EXTRA) @}

del_stmt[stmt_ty]:
    | 'del' a=del_targets &(';' | NEWLINE) @{ _Py_Delete(a, EXTRA) @}
    | invalid_del_stmt

import_stmt[stmt_ty]: import_name | import_from
import_name[stmt_ty]: 'import' a=dotted_as_names @{ _Py_Import(a, EXTRA) @}
# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
import_from[stmt_ty]:
    | 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets @{
        _Py_ImportFrom(b->v.Name.id, c, _PyPegen_seq_count_dots(a), EXTRA) @}
    | 'from' a=('.' | '...')+ 'import' b=import_from_targets @{
        _Py_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) @}
import_from_targets[asdl_seq*]:
    | '(' a=import_from_as_names [','] ')' @{ a @}
    | import_from_as_names !','
    | '*' @{ _PyPegen_singleton_seq(p, CHECK(_PyPegen_alias_for_star(p))) @}
    | invalid_import_from_targets
import_from_as_names[asdl_seq*]:
    | a=','.import_from_as_name+ @{ a @}
import_from_as_name[alias_ty]:
    | a=NAME b=['as' z=NAME @{ z @}] @{ _Py_alias(a->v.Name.id,
                                               (b) ? ((expr_ty) b)->v.Name.id : NULL,
                                               p->arena) @}
dotted_as_names[asdl_seq*]:
    | a=','.dotted_as_name+ @{ a @}
dotted_as_name[alias_ty]:
    | a=dotted_name b=['as' z=NAME @{ z @}] @{ _Py_alias(a->v.Name.id,
                                                      (b) ? ((expr_ty) b)->v.Name.id : NULL,
                                                      p->arena) @}
dotted_name[expr_ty]:
    | a=dotted_name '.' b=NAME @{ _PyPegen_join_names_with_dot(p, a, b) @}
    | NAME

if_stmt[stmt_ty]:
    | 'if' a=named_expression ':' b=block c=elif_stmt @{ _Py_If(a, b, CHECK(_PyPegen_singleton_seq(p, c)), EXTRA) @}
    | 'if' a=named_expression ':' b=block c=[else_block] @{ _Py_If(a, b, c, EXTRA) @}
elif_stmt[stmt_ty]:
    | 'elif' a=named_expression ':' b=block c=elif_stmt @{ _Py_If(a, b, CHECK(_PyPegen_singleton_seq(p, c)), EXTRA) @}
    | 'elif' a=named_expression ':' b=block c=[else_block] @{ _Py_If(a, b, c, EXTRA) @}
else_block[asdl_seq*]: 'else' ':' b=block @{ b @}

while_stmt[stmt_ty]:
    | 'while' a=named_expression ':' b=block c=[else_block] @{ _Py_While(a, b, c, EXTRA) @}

for_stmt[stmt_ty]:
    | 'for' t=star_targets 'in' ~ ex=star_expressions ':' tc=[TYPE_COMMENT] b=block el=[else_block] @{
        _Py_For(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | ASYNC 'for' t=star_targets 'in' ~ ex=star_expressions ':' tc=[TYPE_COMMENT] b=block el=[else_block] @{
        CHECK_VERSION(5, "Async for loops are", _Py_AsyncFor(t, ex, b, el, NEW_TYPE_COMMENT(p, tc), EXTRA)) @}
    | invalid_for_target

with_stmt[stmt_ty]:
    | 'with' '(' a=','.with_item+ ','? ')' ':' b=block @{
        _Py_With(a, b, NULL, EXTRA) @}
    | 'with' a=','.with_item+ ':' tc=[TYPE_COMMENT] b=block @{
        _Py_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | ASYNC 'with' '(' a=','.with_item+ ','? ')' ':' b=block @{
       CHECK_VERSION(5, "Async with statements are", _Py_AsyncWith(a, b, NULL, EXTRA)) @}
    | ASYNC 'with' a=','.with_item+ ':' tc=[TYPE_COMMENT] b=block @{
       CHECK_VERSION(5, "Async with statements are", _Py_AsyncWith(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA)) @}
with_item[withitem_ty]:
    | e=expression 'as' t=star_target &(',' | ')' | ':') @{ _Py_withitem(e, t, p->arena) @}
    | invalid_with_item
    | e=expression @{ _Py_withitem(e, NULL, p->arena) @}

try_stmt[stmt_ty]:
    | 'try' ':' b=block f=finally_block @{ _Py_Try(b, NULL, NULL, f, EXTRA) @}
    | 'try' ':' b=block ex=except_block+ el=[else_block] f=[finally_block] @{ _Py_Try(b, ex, el, f, EXTRA) @}
except_block[excepthandler_ty]:
    | 'except' e=expression t=['as' z=NAME @{ z @}] ':' b=block @{
        _Py_ExceptHandler(e, (t) ? ((expr_ty) t)->v.Name.id : NULL, b, EXTRA) @}
    | 'except' ':' b=block @{ _Py_ExceptHandler(NULL, NULL, b, EXTRA) @}
finally_block[asdl_seq*]: 'finally' ':' a=block @{ a @}

return_stmt[stmt_ty]:
    | 'return' a=[star_expressions] @{ _Py_Return(a, EXTRA) @}

raise_stmt[stmt_ty]:
    | 'raise' a=expression b=['from' z=expression @{ z @}] @{ _Py_Raise(a, b, EXTRA) @}
    | 'raise' @{ _Py_Raise(NULL, NULL, EXTRA) @}

function_def[stmt_ty]:
    | d=decorators f=function_def_raw @{ _PyPegen_function_def_decorators(p, d, f) @}
    | function_def_raw

function_def_raw[stmt_ty]:
    | 'def' n=NAME '(' params=[params] ')' a=['->' z=expression @{ z @}] ':' tc=[func_type_comment] b=block @{
        _Py_FunctionDef(n->v.Name.id,
                        (params) ? params : CHECK(_PyPegen_empty_arguments(p)),
                        b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA) @}
    | ASYNC 'def' n=NAME '(' params=[params] ')' a=['->' z=expression @{ z @}] ':' tc=[func_type_comment] b=block @{
        CHECK_VERSION(
            5,
            "Async functions are",
            _Py_AsyncFunctionDef(n->v.Name.id,
                            (params) ? params : CHECK(_PyPegen_empty_arguments(p)),
                            b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA)
        ) @}
func_type_comment[Token*]:
    | NEWLINE t=TYPE_COMMENT &(NEWLINE INDENT) @{ t @}  # Must be followed by indented block
    | invalid_double_type_comments
    | TYPE_COMMENT

params[arguments_ty]:
    | invalid_parameters
    | parameters

parameters[arguments_ty]:
    | a=slash_no_default b=param_no_default* c=param_with_default* d=[star_etc] @{
        _PyPegen_make_arguments(p, a, NULL, b, c, d) @}
    | a=slash_with_default b=param_with_default* c=[star_etc] @{
        _PyPegen_make_arguments(p, NULL, a, NULL, b, c) @}
    | a=param_no_default+ b=param_with_default* c=[star_etc] @{
        _PyPegen_make_arguments(p, NULL, NULL, a, b, c) @}
    | a=param_with_default+ b=[star_etc] @{ _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)@}
    | a=star_etc @{ _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) @}

# Some duplication here because we can't write (',' | &')'),
# which is because we don't support empty alternatives (yet).
#
slash_no_default[asdl_seq*]:
    | a=param_no_default+ '/' ',' @{ a @}
    | a=param_no_default+ '/' &')' @{ a @}
slash_with_default[SlashWithDefault*]:
    | a=param_no_default* b=param_with_default+ '/' ',' @{ _PyPegen_slash_with_default(p, a, b) @}
    | a=param_no_default* b=param_with_default+ '/' &')' @{ _PyPegen_slash_with_default(p, a, b) @}

star_etc[StarEtc*]:
    | '*' a=param_no_default b=param_maybe_default* c=[kwds] @{
        _PyPegen_star_etc(p, a, b, c) @}
    | '*' ',' b=param_maybe_default+ c=[kwds] @{
        _PyPegen_star_etc(p, NULL, b, c) @}
    | a=kwds @{ _PyPegen_star_etc(p, NULL, NULL, a) @}
    | invalid_star_etc

kwds[arg_ty]: '**' a=param_no_default @{ a @}

# One parameter.  This *includes* a following comma and type comment.
#
# There are three styles:
# - No default
# - With default
# - Maybe with default
#
# There are two alternative forms of each, to deal with type comments:
# - Ends in a comma followed by an optional type comment
# - No comma, optional type comment, must be followed by close paren
# The latter form is for a final parameter without trailing comma.
#
param_no_default[arg_ty]:
    | a=param ',' tc=TYPE_COMMENT? @{ _PyPegen_add_type_comment_to_arg(p, a, tc) @}
    | a=param tc=TYPE_COMMENT? &')' @{ _PyPegen_add_type_comment_to_arg(p, a, tc) @}
param_with_default[NameDefaultPair*]:
    | a=param c=default ',' tc=TYPE_COMMENT? @{ _PyPegen_name_default_pair(p, a, c, tc) @}
    | a=param c=default tc=TYPE_COMMENT? &')' @{ _PyPegen_name_default_pair(p, a, c, tc) @}
param_maybe_default[NameDefaultPair*]:
    | a=param c=default? ',' tc=TYPE_COMMENT? @{ _PyPegen_name_default_pair(p, a, c, tc) @}
    | a=param c=default? tc=TYPE_COMMENT? &')' @{ _PyPegen_name_default_pair(p, a, c, tc) @}
param[arg_ty]: a=NAME b=annotation? @{ _Py_arg(a->v.Name.id, b, NULL, EXTRA) @}

annotation[expr_ty]: ':' a=expression @{ a @}
default[expr_ty]: '=' a=expression @{ a @}

decorators[asdl_seq*]: a=('@@' f=named_expression NEWLINE @{ f @})+ @{ a @}

class_def[stmt_ty]:
    | a=decorators b=class_def_raw @{ _PyPegen_class_def_decorators(p, a, b) @}
    | class_def_raw
class_def_raw[stmt_ty]:
    | 'class' a=NAME b=['(' z=[arguments] ')' @{ z @}] ':' c=block @{
        _Py_ClassDef(a->v.Name.id,
                     (b) ? ((expr_ty) b)->v.Call.args : NULL,
                     (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
                     c, NULL, EXTRA) @}

block[asdl_seq*] (memo):
    | NEWLINE INDENT a=statements DEDENT @{ a @}
    | simple_stmt
    | invalid_block

star_expressions[expr_ty]:
    | a=star_expression b=(',' c=star_expression @{ c @})+ [','] @{
        _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) @}
    | a=star_expression ',' @{ _Py_Tuple(CHECK(_PyPegen_singleton_seq(p, a)), Load, EXTRA) @}
    | star_expression
star_expression[expr_ty] (memo):
    | '*' a=bitwise_or @{ _Py_Starred(a, Load, EXTRA) @}
    | expression

star_named_expressions[asdl_seq*]: a=','.star_named_expression+ [','] @{ a @}
star_named_expression[expr_ty]:
    | '*' a=bitwise_or @{ _Py_Starred(a, Load, EXTRA) @}
    | named_expression
named_expression[expr_ty]:
    | a=NAME ':=' ~ b=expression @{ _Py_NamedExpr(CHECK(_PyPegen_set_expr_context(p, a, Store)), b, EXTRA) @}
    | expression !':='
    | invalid_named_expression

annotated_rhs[expr_ty]: yield_expr | star_expressions

expressions[expr_ty]:
    | a=expression b=(',' c=expression @{ c @})+ [','] @{
        _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Load, EXTRA) @}
    | a=expression ',' @{ _Py_Tuple(CHECK(_PyPegen_singleton_seq(p, a)), Load, EXTRA) @}
    | expression
expression[expr_ty] (memo):
    | a=disjunction 'if' b=disjunction 'else' c=expression @{ _Py_IfExp(b, a, c, EXTRA) @}
    | disjunction
    | lambdef

lambdef[expr_ty]:
    | 'lambda' a=[lambda_params] ':' b=expression @{ _Py_Lambda((a) ? a : CHECK(_PyPegen_empty_arguments(p)), b, EXTRA) @}

lambda_params[arguments_ty]:
    | invalid_lambda_parameters
    | lambda_parameters

# lambda_parameters etc. duplicates parameters but without annotations
# or type comments, and if there's no comma after a parameter, we expect
# a colon, not a close parenthesis.  (For more, see parameters above.)
#
lambda_parameters[arguments_ty]:
    | a=lambda_slash_no_default b=lambda_param_no_default* c=lambda_param_with_default* d=[lambda_star_etc] @{
        _PyPegen_make_arguments(p, a, NULL, b, c, d) @}
    | a=lambda_slash_with_default b=lambda_param_with_default* c=[lambda_star_etc] @{
        _PyPegen_make_arguments(p, NULL, a, NULL, b, c) @}
    | a=lambda_param_no_default+ b=lambda_param_with_default* c=[lambda_star_etc] @{
        _PyPegen_make_arguments(p, NULL, NULL, a, b, c) @}
    | a=lambda_param_with_default+ b=[lambda_star_etc] @{ _PyPegen_make_arguments(p, NULL, NULL, NULL, a, b)@}
    | a=lambda_star_etc @{ _PyPegen_make_arguments(p, NULL, NULL, NULL, NULL, a) @}

lambda_slash_no_default[asdl_seq*]:
    | a=lambda_param_no_default+ '/' ',' @{ a @}
    | a=lambda_param_no_default+ '/' &':' @{ a @}
lambda_slash_with_default[SlashWithDefault*]:
    | a=lambda_param_no_default* b=lambda_param_with_default+ '/' ',' @{ _PyPegen_slash_with_default(p, a, b) @}
    | a=lambda_param_no_default* b=lambda_param_with_default+ '/' &':' @{ _PyPegen_slash_with_default(p, a, b) @}

lambda_star_etc[StarEtc*]:
    | '*' a=lambda_param_no_default b=lambda_param_maybe_default* c=[lambda_kwds] @{
        _PyPegen_star_etc(p, a, b, c) @}
    | '*' ',' b=lambda_param_maybe_default+ c=[lambda_kwds] @{
        _PyPegen_star_etc(p, NULL, b, c) @}
    | a=lambda_kwds @{ _PyPegen_star_etc(p, NULL, NULL, a) @}
    | invalid_lambda_star_etc

lambda_kwds[arg_ty]: '**' a=lambda_param_no_default @{ a @}

lambda_param_no_default[arg_ty]:
    | a=lambda_param ',' @{ a @}
    | a=lambda_param &':' @{ a @}
lambda_param_with_default[NameDefaultPair*]:
    | a=lambda_param c=default ',' @{ _PyPegen_name_default_pair(p, a, c, NULL) @}
    | a=lambda_param c=default &':' @{ _PyPegen_name_default_pair(p, a, c, NULL) @}
lambda_param_maybe_default[NameDefaultPair*]:
    | a=lambda_param c=default? ',' @{ _PyPegen_name_default_pair(p, a, c, NULL) @}
    | a=lambda_param c=default? &':' @{ _PyPegen_name_default_pair(p, a, c, NULL) @}
lambda_param[arg_ty]: a=NAME @{ _Py_arg(a->v.Name.id, NULL, NULL, EXTRA) @}

disjunction[expr_ty] (memo):
    | a=conjunction b=('or' c=conjunction @{ c @})+ @{ _Py_BoolOp(
        Or,
        CHECK(_PyPegen_seq_insert_in_front(p, a, b)),
        EXTRA) @}
    | conjunction
conjunction[expr_ty] (memo):
    | a=inversion b=('and' c=inversion @{ c @})+ @{ _Py_BoolOp(
        And,
        CHECK(_PyPegen_seq_insert_in_front(p, a, b)),
        EXTRA) @}
    | inversion
inversion[expr_ty] (memo):
    | 'not' a=inversion @{ _Py_UnaryOp(Not, a, EXTRA) @}
    | comparison
comparison[expr_ty]:
    | a=bitwise_or b=compare_op_bitwise_or_pair+ @{
        _Py_Compare(a, CHECK(_PyPegen_get_cmpops(p, b)), CHECK(_PyPegen_get_exprs(p, b)), EXTRA) @}
    | bitwise_or
compare_op_bitwise_or_pair[CmpopExprPair*]:
    | eq_bitwise_or
    | noteq_bitwise_or
    | lte_bitwise_or
    | lt_bitwise_or
    | gte_bitwise_or
    | gt_bitwise_or
    | notin_bitwise_or
    | in_bitwise_or
    | isnot_bitwise_or
    | is_bitwise_or
eq_bitwise_or[CmpopExprPair*]: '==' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, Eq, a) @}
noteq_bitwise_or[CmpopExprPair*]:
    | (tok='!=' @{ _PyPegen_check_barry_as_flufl(p, tok) ? NULL : tok@}) a=bitwise_or @{_PyPegen_cmpop_expr_pair(p, NotEq, a) @}
lte_bitwise_or[CmpopExprPair*]: '<=' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, LtE, a) @}
lt_bitwise_or[CmpopExprPair*]: '<' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, Lt, a) @}
gte_bitwise_or[CmpopExprPair*]: '>=' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, GtE, a) @}
gt_bitwise_or[CmpopExprPair*]: '>' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, Gt, a) @}
notin_bitwise_or[CmpopExprPair*]: 'not' 'in' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, NotIn, a) @}
in_bitwise_or[CmpopExprPair*]: 'in' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, In, a) @}
isnot_bitwise_or[CmpopExprPair*]: 'is' 'not' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, IsNot, a) @}
is_bitwise_or[CmpopExprPair*]: 'is' a=bitwise_or @{ _PyPegen_cmpop_expr_pair(p, Is, a) @}

bitwise_or[expr_ty]:
    | a=bitwise_or '|' b=bitwise_xor @{ _Py_BinOp(a, BitOr, b, EXTRA) @}
    | bitwise_xor
bitwise_xor[expr_ty]:
    | a=bitwise_xor '^' b=bitwise_and @{ _Py_BinOp(a, BitXor, b, EXTRA) @}
    | bitwise_and
bitwise_and[expr_ty]:
    | a=bitwise_and '&' b=shift_expr @{ _Py_BinOp(a, BitAnd, b, EXTRA) @}
    | shift_expr
shift_expr[expr_ty]:
    | a=shift_expr '<<' b=sum @{ _Py_BinOp(a, LShift, b, EXTRA) @}
    | a=shift_expr '>>' b=sum @{ _Py_BinOp(a, RShift, b, EXTRA) @}
    | sum

sum[expr_ty]:
    | a=sum '+' b=term @{ _Py_BinOp(a, Add, b, EXTRA) @}
    | a=sum '-' b=term @{ _Py_BinOp(a, Sub, b, EXTRA) @}
    | term
term[expr_ty]:
    | a=term '*' b=factor @{ _Py_BinOp(a, Mult, b, EXTRA) @}
    | a=term '/' b=factor @{ _Py_BinOp(a, Div, b, EXTRA) @}
    | a=term '//' b=factor @{ _Py_BinOp(a, FloorDiv, b, EXTRA) @}
    | a=term '%' b=factor @{ _Py_BinOp(a, Mod, b, EXTRA) @}
    | a=term '@@' b=factor @{ CHECK_VERSION(5, "The '@@' operator is", _Py_BinOp(a, MatMult, b, EXTRA)) @}
    | factor
factor[expr_ty] (memo):
    | '+' a=factor @{ _Py_UnaryOp(UAdd, a, EXTRA) @}
    | '-' a=factor @{ _Py_UnaryOp(USub, a, EXTRA) @}
    | '~' a=factor @{ _Py_UnaryOp(Invert, a, EXTRA) @}
    | power
power[expr_ty]:
    | a=await_primary '**' b=factor @{ _Py_BinOp(a, Pow, b, EXTRA) @}
    | await_primary
await_primary[expr_ty] (memo):
    | AWAIT a=primary @{ CHECK_VERSION(5, "Await expressions are", _Py_Await(a, EXTRA)) @}
    | primary
primary[expr_ty]:
    | invalid_primary  # must be before 'primay genexp' because of invalid_genexp
    | a=primary '.' b=NAME @{ _Py_Attribute(a, b->v.Name.id, Load, EXTRA) @}
    | a=primary b=genexp @{ _Py_Call(a, CHECK(_PyPegen_singleton_seq(p, b)), NULL, EXTRA) @}
    | a=primary '(' b=[arguments] ')' @{
        _Py_Call(a,
                 (b) ? ((expr_ty) b)->v.Call.args : NULL,
                 (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
                 EXTRA) @}
    | a=primary '[' b=slices ']' @{ _Py_Subscript(a, b, Load, EXTRA) @}
    | atom

slices[expr_ty]:
    | a=slice !',' @{ a @}
    | a=','.slice+ [','] @{ _Py_Tuple(a, Load, EXTRA) @}
slice[expr_ty]:
    | a=[expression] ':' b=[expression] c=[':' d=[expression] @{ d @}] @{ _Py_Slice(a, b, c, EXTRA) @}
    | a=expression @{ a @}
atom[expr_ty]:
    | NAME
    | 'True' @{ _Py_Constant(Py_True, NULL, EXTRA) @}
    | 'False' @{ _Py_Constant(Py_False, NULL, EXTRA) @}
    | 'None' @{ _Py_Constant(Py_None, NULL, EXTRA) @}
    | '__peg_parser__' @{ RAISE_SYNTAX_ERROR("You found it!") @}
    | &STRING strings
    | NUMBER
    | &'(' (tuple | group | genexp)
    | &'[' (list | listcomp)
    | &'@{' (dict | set | dictcomp | setcomp)
    | '...' @{ _Py_Constant(Py_Ellipsis, NULL, EXTRA) @}

strings[expr_ty] (memo): a=STRING+ @{ _PyPegen_concatenate_strings(p, a) @}
list[expr_ty]:
    | '[' a=[star_named_expressions] ']' @{ _Py_List(a, Load, EXTRA) @}
listcomp[expr_ty]:
    | '[' a=named_expression ~ b=for_if_clauses ']' @{ _Py_ListComp(a, b, EXTRA) @}
    | invalid_comprehension
tuple[expr_ty]:
    | '(' a=[y=star_named_expression ',' z=[star_named_expressions] @{ _PyPegen_seq_insert_in_front(p, y, z) @} ] ')' @{
        _Py_Tuple(a, Load, EXTRA) @}
group[expr_ty]:
    | '(' a=(yield_expr | named_expression) ')' @{ a @}
    | invalid_group
genexp[expr_ty]:
    | '(' a=named_expression ~ b=for_if_clauses ')' @{ _Py_GeneratorExp(a, b, EXTRA) @}
    | invalid_comprehension
set[expr_ty]: '@{' a=star_named_expressions '@}' @{ _Py_Set(a, EXTRA) @}
setcomp[expr_ty]:
    | '@{' a=named_expression ~ b=for_if_clauses '@}' @{ _Py_SetComp(a, b, EXTRA) @}
    | invalid_comprehension
dict[expr_ty]:
    | '@{' a=[double_starred_kvpairs] '@}' @{
        _Py_Dict(CHECK(_PyPegen_get_keys(p, a)), CHECK(_PyPegen_get_values(p, a)), EXTRA) @}
dictcomp[expr_ty]:
    | '@{' a=kvpair b=for_if_clauses '@}' @{ _Py_DictComp(a->key, a->value, b, EXTRA) @}
    | invalid_dict_comprehension
double_starred_kvpairs[asdl_seq*]: a=','.double_starred_kvpair+ [','] @{ a @}
double_starred_kvpair[KeyValuePair*]:
    | '**' a=bitwise_or @{ _PyPegen_key_value_pair(p, NULL, a) @}
    | kvpair
kvpair[KeyValuePair*]: a=expression ':' b=expression @{ _PyPegen_key_value_pair(p, a, b) @}
for_if_clauses[asdl_seq*]:
    | for_if_clause+
for_if_clause[comprehension_ty]:
    | ASYNC 'for' a=star_targets 'in' ~ b=disjunction c=('if' z=disjunction @{ z @})* @{
        CHECK_VERSION(6, "Async comprehensions are", _Py_comprehension(a, b, c, 1, p->arena)) @}
    | 'for' a=star_targets 'in' ~ b=disjunction c=('if' z=disjunction @{ z @})* @{
        _Py_comprehension(a, b, c, 0, p->arena) @}
    | invalid_for_target

yield_expr[expr_ty]:
    | 'yield' 'from' a=expression @{ _Py_YieldFrom(a, EXTRA) @}
    | 'yield' a=[star_expressions] @{ _Py_Yield(a, EXTRA) @}

arguments[expr_ty] (memo):
    | a=args [','] &')' @{ a @}
    | invalid_arguments
args[expr_ty]:
    | a=','.(starred_expression | named_expression !'=')+ b=[',' k=kwargs @{k@}] @{ _PyPegen_collect_call_seqs(p, a, b, EXTRA) @}
    | a=kwargs @{ _Py_Call(_PyPegen_dummy_name(p),
                          CHECK_NULL_ALLOWED(_PyPegen_seq_extract_starred_exprs(p, a)),
                          CHECK_NULL_ALLOWED(_PyPegen_seq_delete_starred_exprs(p, a)),
                          EXTRA) @}
kwargs[asdl_seq*]:
    | a=','.kwarg_or_starred+ ',' b=','.kwarg_or_double_starred+ @{ _PyPegen_join_sequences(p, a, b) @}
    | ','.kwarg_or_starred+
    | ','.kwarg_or_double_starred+
starred_expression[expr_ty]:
    | '*' a=expression @{ _Py_Starred(a, Load, EXTRA) @}
kwarg_or_starred[KeywordOrStarred*]:
    | a=NAME '=' b=expression @{
        _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(a->v.Name.id, b, EXTRA)), 1) @}
    | a=starred_expression @{ _PyPegen_keyword_or_starred(p, a, 0) @}
    | invalid_kwarg
kwarg_or_double_starred[KeywordOrStarred*]:
    | a=NAME '=' b=expression @{
        _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(a->v.Name.id, b, EXTRA)), 1) @}
    | '**' a=expression @{ _PyPegen_keyword_or_starred(p, CHECK(_Py_keyword(NULL, a, EXTRA)), 1) @}
    | invalid_kwarg

# NOTE: star_targets may contain *bitwise_or, targets may not.
star_targets[expr_ty]:
    | a=star_target !',' @{ a @}
    | a=star_target b=(',' c=star_target @{ c @})* [','] @{
        _Py_Tuple(CHECK(_PyPegen_seq_insert_in_front(p, a, b)), Store, EXTRA) @}
star_targets_list_seq[asdl_seq*]: a=','.star_target+ [','] @{ a @}
star_targets_tuple_seq[asdl_seq*]:
    | a=star_target b=(',' c=star_target @{ c @})+ [','] @{ _PyPegen_seq_insert_in_front(p, a, b) @}
    | a=star_target ',' @{ _PyPegen_singleton_seq(p, a) @}
star_target[expr_ty] (memo):
    | '*' a=(!'*' star_target) @{
        _Py_Starred(CHECK(_PyPegen_set_expr_context(p, a, Store)), Store, EXTRA) @}
    | target_with_star_atom
target_with_star_atom[expr_ty] (memo):
    | a=t_primary '.' b=NAME !t_lookahead @{ _Py_Attribute(a, b->v.Name.id, Store, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _Py_Subscript(a, b, Store, EXTRA) @}
    | star_atom
star_atom[expr_ty]:
    | a=NAME @{ _PyPegen_set_expr_context(p, a, Store) @}
    | '(' a=target_with_star_atom ')' @{ _PyPegen_set_expr_context(p, a, Store) @}
    | '(' a=[star_targets_tuple_seq] ')' @{ _Py_Tuple(a, Store, EXTRA) @}
    | '[' a=[star_targets_list_seq] ']' @{ _Py_List(a, Store, EXTRA) @}

single_target[expr_ty]:
    | single_subscript_attribute_target
    | a=NAME @{ _PyPegen_set_expr_context(p, a, Store) @}
    | '(' a=single_target ')' @{ a @}
single_subscript_attribute_target[expr_ty]:
    | a=t_primary '.' b=NAME !t_lookahead @{ _Py_Attribute(a, b->v.Name.id, Store, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _Py_Subscript(a, b, Store, EXTRA) @}

del_targets[asdl_seq*]: a=','.del_target+ [','] @{ a @}
del_target[expr_ty] (memo):
    | a=t_primary '.' b=NAME !t_lookahead @{ _Py_Attribute(a, b->v.Name.id, Del, EXTRA) @}
    | a=t_primary '[' b=slices ']' !t_lookahead @{ _Py_Subscript(a, b, Del, EXTRA) @}
    | del_t_atom
del_t_atom[expr_ty]:
    | a=NAME @{ _PyPegen_set_expr_context(p, a, Del) @}
    | '(' a=del_target ')' @{ _PyPegen_set_expr_context(p, a, Del) @}
    | '(' a=[del_targets] ')' @{ _Py_Tuple(a, Del, EXTRA) @}
    | '[' a=[del_targets] ']' @{ _Py_List(a, Del, EXTRA) @}

t_primary[expr_ty]:
    | a=t_primary '.' b=NAME &t_lookahead @{ _Py_Attribute(a, b->v.Name.id, Load, EXTRA) @}
    | a=t_primary '[' b=slices ']' &t_lookahead @{ _Py_Subscript(a, b, Load, EXTRA) @}
    | a=t_primary b=genexp &t_lookahead @{ _Py_Call(a, CHECK(_PyPegen_singleton_seq(p, b)), NULL, EXTRA) @}
    | a=t_primary '(' b=[arguments] ')' &t_lookahead @{
        _Py_Call(a,
                 (b) ? ((expr_ty) b)->v.Call.args : NULL,
                 (b) ? ((expr_ty) b)->v.Call.keywords : NULL,
                 EXTRA) @}
    | a=atom &t_lookahead @{ a @}
t_lookahead: '(' | '[' | '.'

# From here on, there are rules for invalid syntax with specialised error messages
invalid_arguments:
    | args ',' '*' @{ RAISE_SYNTAX_ERROR("iterable argument unpacking follows keyword argument unpacking") @}
    | a=expression for_if_clauses ',' [args | expression for_if_clauses] @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "Generator expression must be parenthesized") @}
    | a=args for_if_clauses @{ _PyPegen_nonparen_genexp_in_call(p, a) @}
    | args ',' a=expression for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "Generator expression must be parenthesized") @}
    | a=args ',' args @{ _PyPegen_arguments_parsing_error(p, a) @}
invalid_kwarg:
    | !(NAME '=') a=expression b='=' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "expression cannot contain assignment, perhaps you meant \"==\"?") @}
invalid_named_expression:
    | a=expression ':=' expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) @}
invalid_assignment:
    | a=invalid_ann_assign_target ':' expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
            a,
            "only single target (not %s) can be annotated",
            _PyPegen_get_expr_name(a)
        )@}
    | a=star_named_expression ',' star_named_expressions* ':' expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "only single target (not tuple) can be annotated") @}
    | a=expression ':' expression @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "illegal target for annotation") @}
    | (star_targets '=')* a=star_expressions '=' @{
        RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) @}
    | (star_targets '=')* a=yield_expr '=' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "assignment to yield expression not possible") @}
    | a=star_expressions augassign (yield_expr | star_expressions) @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION( 
            a,
            "'%s' is an illegal expression for augmented assignment",
            _PyPegen_get_expr_name(a)
        )@}
invalid_ann_assign_target[expr_ty]:
    | list
    | tuple
    | '(' a=invalid_ann_assign_target ')' @{ a @}
invalid_del_stmt:
    | 'del' a=star_expressions @{
        RAISE_SYNTAX_ERROR_INVALID_TARGET(DEL_TARGETS, a) @}
invalid_block:
    | NEWLINE !INDENT @{ RAISE_INDENTATION_ERROR("expected an indented block") @}
invalid_primary:
    | primary a='@{' @{ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "invalid syntax") @}
invalid_comprehension:
    | ('[' | '(' | '@{') a=starred_expression for_if_clauses @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "iterable unpacking cannot be used in comprehension") @}
invalid_dict_comprehension:
    | '@{' a='**' bitwise_or for_if_clauses '@}' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "dict unpacking cannot be used in dict comprehension") @}
invalid_parameters:
    | param_no_default* (slash_with_default | param_with_default+) param_no_default @{
        RAISE_SYNTAX_ERROR("non-default argument follows default argument") @}
invalid_lambda_parameters:
    | lambda_param_no_default* (lambda_slash_with_default | lambda_param_with_default+) lambda_param_no_default @{
        RAISE_SYNTAX_ERROR("non-default argument follows default argument") @}
invalid_star_etc:
    | '*' (')' | ',' (')' | '**')) @{ RAISE_SYNTAX_ERROR("named arguments must follow bare *") @}
    | '*' ',' TYPE_COMMENT @{ RAISE_SYNTAX_ERROR("bare * has associated type comment") @}
invalid_lambda_star_etc:
    | '*' (':' | ',' (':' | '**')) @{ RAISE_SYNTAX_ERROR("named arguments must follow bare *") @}
invalid_double_type_comments:
    | TYPE_COMMENT NEWLINE TYPE_COMMENT NEWLINE INDENT @{
        RAISE_SYNTAX_ERROR("Cannot have two type comments on def") @}
invalid_with_item:
    | expression 'as' a=expression @{
        RAISE_SYNTAX_ERROR_INVALID_TARGET(STAR_TARGETS, a) @}

invalid_for_target:
    | ASYNC? 'for' a=star_expressions @{
        RAISE_SYNTAX_ERROR_INVALID_TARGET(FOR_TARGETS, a) @}

invalid_group:
    | '(' a=starred_expression ')' @{
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "can't use starred expression here") @}
invalid_import_from_targets:
    | import_from_as_names ',' NEWLINE @{
        RAISE_SYNTAX_ERROR("trailing comma not allowed without surrounding parentheses") @}
@end example

@node Python 标准库,扩展和嵌入 Python 解释器,Python 语言参考手册,Top
@anchor{library/index doc}@anchor{1736}@anchor{library/index library-index}@anchor{135f}@anchor{library/index the-python-standard-library}@anchor{1737}
@chapter Python 标准库


@ref{1360,,Python 语言参考手册} 描述了 Python 语言的具体语法和语义，这份库参考则介绍了与 Python 一同发行的标准库。它还描述了通常包含在 Python 发行版中的一些可选组件。

Python 标准库非常庞大，所提供的组件涉及范围十分广泛，正如以下内容目录所显示的。这个库包含了多个内置模块 (以 C 编写)，Python 程序员必须依靠它们来实现系统级功能，例如文件 I/O，此外还有大量以 Python 编写的模块，提供了日常编程中许多问题的标准解决方案。其中有些模块经过专门设计，通过将特定平台功能抽象化为平台中立的 API 来鼓励和加强 Python 程序的可移植性。

Windows 版本的 Python 安装程序通常包含整个标准库，往往还包含许多额外组件。对于类 Unix 操作系统，Python 通常会分成一系列的软件包，因此可能需要使用操作系统所提供的包管理工具来获取部分或全部可选组件。

在这个标准库以外还存在成千上万并且不断增加的其他组件 (从单独的程序、模块、软件包直到完整的应用开发框架)，访问 Python 包索引@footnote{https://pypi.org} 即可获取这些第三方包。

@c We don't use :numbered: option for the TOC below as it enforces
@c numbered sections for the entire stdlib docs.  If desired,
@c :numbered: can be enabled on a per-module basis.

@menu
* 概述: 概述<6>. 
* 内置函数:: 
* 内置常量:: 
* 内置类型:: 
* 内置异常:: 
* 文本处理服务:: 
* 二进制数据服务:: 
* 数据类型:: 
* 数字和数学模块:: 
* 函数式编程模块:: 
* 文件和目录访问:: 
* 数据持久化:: 
* 数据压缩和存档:: 
* 文件格式:: 
* 加密服务:: 
* 通用操作系统服务:: 
* 并发执行:: 
* 网络和进程间通信:: 
* 互联网数据处理:: 
* 结构化标记处理工具:: 
* 互联网协议和支持:: 
* 多媒体服务:: 
* 国际化:: 
* 程序框架:: 
* Tk图形用户界面(GUI): Tk图形用户界面 GUI. 
* 开发工具:: 
* 调试和分析:: 
* 软件打包和分发:: 
* Python运行时服务:: 
* 自定义 Python 解释器:: 
* 导入模块:: 
* Python 语言服务:: 
* 杂项服务:: 
* Windows系统相关模块:: 
* Unix 专有服务:: 
* 被取代的模块:: 
* Security Considerations:: 

@end menu

@node 概述<6>,内置函数,,Python 标准库
@anchor{library/intro doc}@anchor{1738}@anchor{library/intro introduction}@anchor{1739}@anchor{library/intro library-intro}@anchor{173a}
@section 概述


"Python 库"中包含了几种不同的组件。

它包含通常被视为语言“核心”中的一部分的数据类型，例如数字和列表。对于这些类型，Python语言核心定义了文字的形式，并对它们的语义设置了一些约束，但没有完全定义语义。（另一方面，语言核心确实定义了语法属性，如操作符的拼写和优先级。）

这个库也包含了内置函数和异常 --- 不需要 @ref{cef,,import} 语句就可以在所有Python代码中使用的对象。有一些是由语言核心定义的，但是许多对于核心语义不是必需的，并且仅在这里描述。

不过这个库主要是由一系列的模块组成。这些模块集可以不同方式分类。有些模块是用 C 编写并内置于 Python 解释器中；另一些模块则是用 Python 编写并以源码形式导入。有些模块提供专用于 Python 的接口，例如打印栈追踪信息；有些模块提供专用于特定操作系统的接口，例如操作特定的硬件；另一些模块则提供针对特定应用领域的接口，例如万维网。有些模块在所有更新和移植版本的 Python 中可用；另一些模块仅在底层系统支持或要求时可用；还有些模块则仅当编译和安装 Python 时选择了特定配置选项时才可用。

本手册以 "从内到外" 的顺序组织：首先描述内置函数、数据类型和异常，最后是根据相关性进行分组的各种模块。

这意味着如果你从头开始阅读本手册，并在感到厌烦时跳到下一章，你仍能对 Python 库的可用模块和所支持的应用领域有个大致了解。当然，你并非 @emph{必须} 如同读小说一样从头读到尾 --- 你也可以先浏览内容目录 (在手册开头)，或在索引 (在手册末尾) 中查找某个特定函数、模块或条目。最后，如果你喜欢随意学习某个主题，你可以选择一个随机页码 (参见 @ref{dc,,random} 模块) 并读上一两小节。无论你想以怎样的顺序阅读本手册，还是建议先从 @ref{cc6,,内置函数} 这一章开始，因为本手册的其余内容都需要你熟悉其中的基本概念。

让我们开始吧！

@menu
* 可用性注释:: 

@end menu

@node 可用性注释,,,概述<6>
@anchor{library/intro availability}@anchor{14c1}@anchor{library/intro notes-on-availability}@anchor{173b}
@subsection 可用性注释



@itemize *

@item 
如果出现“可用性：Unix”注释，意味着相应函数通常存在于 Unix 系统中。 但这并不保证其存在于某个特定的操作系统中。

@item 
如果没有单独说明，所有注明 "可用性: Unix" 的函数都在 macOS 上受到支持，因为此系统是基于 Unix 内核的。
@end itemize

@c XXX document all delegations to __special__ methods

@node 内置函数,内置常量,概述<6>,Python 标准库
@anchor{library/functions doc}@anchor{173c}@anchor{library/functions built-in-funcs}@anchor{cc6}@anchor{library/functions built-in-functions}@anchor{173d}
@section 内置函数


Python 解释器内置了很多函数和类型，您可以在任何时候使用它们。以下按字母表顺序列出它们。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem


@tab


@tab

内置函数

@tab


@tab


@item

@ref{1424,,abs()}

@tab

@ref{173e,,delattr()}

@tab

@ref{aac,,hash()}

@tab

@ref{173f,,memoryview()}

@tab

@ref{1740,,set()}

@item

@ref{e52,,all()}

@tab

@ref{1741,,dict()}

@tab

@ref{175,,help()}

@tab

@ref{900,,min()}

@tab

@ref{1742,,setattr()}

@item

@ref{e51,,any()}

@tab

@ref{e01,,dir()}

@tab

@ref{d36,,hex()}

@tab

@ref{77f,,next()}

@tab

@ref{ed0,,slice()}

@item

@ref{e19,,ascii()}

@tab

@ref{294,,divmod()}

@tab

@ref{e53,,id()}

@tab

@ref{3da,,object()}

@tab

@ref{54f,,sorted()}

@item

@ref{d10,,bin()}

@tab

@ref{eaf,,enumerate()}

@tab

@ref{d3b,,input()}

@tab

@ref{d35,,oct()}

@tab

@ref{311,,staticmethod()}

@item

@ref{2c4,,bool()}

@tab

@ref{c6a,,eval()}

@tab

@ref{205,,int()}

@tab

@ref{16f,,open()}

@tab

@ref{1743,,str()}

@item

@ref{414,,breakpoint()}

@tab

@ref{d14,,exec()}

@tab

@ref{55a,,isinstance()}

@tab

@ref{1588,,ord()}

@tab

@ref{31d,,sum()}

@item

@ref{123b,,bytearray()}

@tab

@ref{d00,,filter()}

@tab

@ref{55b,,issubclass()}

@tab

@ref{2d6,,pow()}

@tab

@ref{5e6,,super()}

@item

@ref{123a,,bytes()}

@tab

@ref{1fe,,float()}

@tab

@ref{df5,,iter()}

@tab

@ref{97a,,print()}

@tab

@ref{1744,,tuple()}

@item

@ref{c1f,,callable()}

@tab

@ref{5de,,format()}

@tab

@ref{292,,len()}

@tab

@ref{30f,,property()}

@tab

@ref{709,,type()}

@item

@ref{1589,,chr()}

@tab

@ref{1745,,frozenset()}

@tab

@ref{1746,,list()}

@tab

@ref{1747,,range()}

@tab

@ref{11b6,,vars()}

@item

@ref{310,,classmethod()}

@tab

@ref{554,,getattr()}

@tab

@ref{55f,,locals()}

@tab

@ref{8c3,,repr()}

@tab

@ref{d04,,zip()}

@item

@ref{2ee,,compile()}

@tab

@ref{fa1,,globals()}

@tab

@ref{cff,,map()}

@tab

@ref{2cd,,reversed()}

@tab

@ref{16b,,__import__()}

@item

@ref{2c8,,complex()}

@tab

@ref{553,,hasattr()}

@tab

@ref{901,,max()}

@tab

@ref{d3d,,round()}

@tab

@end multitable


@c using :func:`dict` would create a link to another page, so local targets are
@c used, with replacement texts to make the output in the table consistent

@geindex abs() (內置函数)
@anchor{library/functions abs}@anchor{1424}
@deffn {函数} abs (x)

返回一个数的绝对值。 参数可以是整数、浮点数或任何实现了 @ref{15ec,,__abs__()} 的对象。 如果参数是一个复数，则返回它的模。
@end deffn

@geindex all() (內置函数)
@anchor{library/functions all}@anchor{e52}
@deffn {函数} all (iterable)

如果 @emph{iterable} 的所有元素均为真值（或可迭代对象为空）则返回 @code{True} 。 等价于:

@example
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
@end example
@end deffn

@geindex any() (內置函数)
@anchor{library/functions any}@anchor{e51}
@deffn {函数} any (iterable)

如果 @emph{iterable} 的任一元素为真值则返回 @code{True}。 如果可迭代对象为空，返回 @code{False}。 等价于:

@example
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
@end example
@end deffn

@geindex ascii() (內置函数)
@anchor{library/functions ascii}@anchor{e19}
@deffn {函数} ascii (object)

与 @ref{8c3,,repr()} 类似，返回一个包含对象的可打印表示形式的字符串，但是使用 @code{\x}、@code{\u} 和 @code{\U} 对 @ref{8c3,,repr()} 返回的字符串中非 ASCII 编码的字符进行转义。 生成的字符串和 Python 2 的 @ref{8c3,,repr()} 返回的结果相似。
@end deffn

@geindex bin() (內置函数)
@anchor{library/functions bin}@anchor{d10}
@deffn {函数} bin (x)

将一个整数转变为一个前缀为“0b”的二进制字符串。结果是一个合法的 Python 表达式。如果 @emph{x} 不是 Python 的 @ref{205,,int} 对象，那它需要定义 @ref{2c9,,__index__()}  方法返回一个整数。一些例子：

@example
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
@end example

如果不一定需要前缀“0b”，还可以使用如下的方法。

@example
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'@{14:#b@}', f'@{14:b@}'
('0b1110', '1110')
@end example

另见 @ref{5de,,format()} 获取更多信息。
@end deffn

@geindex bool (內置类)
@anchor{library/functions bool}@anchor{2c4}
@deffn {类} bool ([x])

返回一个布尔值，@code{True} 或者 @code{False}。 @emph{x} 使用标准的 @ref{1748,,真值测试过程} 来转换。 如果 @emph{x} 是假值或者被省略，返回 @code{False}；其他情况返回 @code{True}。 @ref{2c4,,bool} 类是 @ref{205,,int} 的子类（参见 @ref{1382,,数字类型 --- int@comma{} float@comma{} complex} ）。其他类不能继承自它。它只有 @code{False} 和 @code{True} 两个实例（参见 @ref{1749,,布尔值} ）。

@geindex Boolean; type


在 3.7 版更改: @emph{x} 现在只能作为位置参数。

@end deffn

@geindex breakpoint() (內置函数)
@anchor{library/functions breakpoint}@anchor{414}
@deffn {函数} breakpoint (*args, **kws)

此函数会在调用时将你陷入调试器中。具体来说，它调用 @ref{42c,,sys.breakpointhook()} ，直接传递 @code{args} 和 @code{kws} 。默认情况下， @code{sys.breakpointhook()} 调用 @ref{4d1,,pdb.set_trace()} 且没有参数。在这种情况下，它纯粹是一个便利函数，因此您不必显式导入 @ref{c9,,pdb} 且键入尽可能少的代码即可进入调试器。但是， @ref{42c,,sys.breakpointhook()} 可以设置为其他一些函数并被 @ref{414,,breakpoint()} 自动调用，以允许进入你想用的调试器。

引发一个 @ref{fec,,审计事件} @code{builtins.breakpoint} 并附带参数 @code{breakpointhook}。


3.7 新版功能.

@end deffn
@anchor{library/functions func-bytearray}@anchor{123b}

@deffn {类} bytearray ([source[, encoding[, errors]]])

返回一个新的 bytes 数组。 @ref{173,,bytearray} 类是一个可变序列，包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法，见 @ref{174a,,可变序列类型} 的描述；同时有 @ref{172,,bytes} 类型的大部分方法，参见 @ref{174b,,bytes 和 bytearray 操作}。

可选形参 @emph{source} 可以用不同的方式来初始化数组：


@itemize *

@item 
如果是一个 @emph{string}，您必须提供 @emph{encoding} 参数（@emph{errors} 参数仍是可选的）；@ref{173,,bytearray()} 会使用 @ref{170,,str.encode()} 方法来将 string 转变成 bytes。

@item 
如果是一个 @emph{integer}，会初始化大小为该数字的数组，并使用 null 字节填充。

@item 
如果是一个遵循 @ref{174c,,缓冲区接口} 的对象，该对象的只读缓冲区将被用来初始化字节数组。

@item 
如果是一个 @emph{iterable} 可迭代对象，它的元素的范围必须是 @code{0 <= x < 256} 的整数，它会被用作数组的初始内容。
@end itemize

如果没有实参，则创建大小为 0 的数组。

另见 @ref{174d,,二进制序列类型 --- bytes@comma{} bytearray@comma{} memoryview} 和 @ref{174e,,bytearray 对象}。
@end deffn
@anchor{library/functions func-bytes}@anchor{123a}

@deffn {类} bytes ([source[, encoding[, errors]]])

返回一个新的“bytes”对象， 是一个不可变序列，包含范围为 @code{0 <= x < 256} 的整数。@ref{172,,bytes} 是 @ref{173,,bytearray} 的不可变版本 - 它有其中不改变序列的方法和相同的索引、切片操作。

因此，构造函数的实参和 @ref{173,,bytearray()} 相同。

字节对象还可以用字面值创建，参见 @ref{1542,,字符串与字节串字面值}。

另见 @ref{174d,,二进制序列类型 --- bytes@comma{} bytearray@comma{} memoryview}，@ref{174f,,bytes 对象} 和 @ref{174b,,bytes 和 bytearray 操作}。
@end deffn

@geindex callable() (內置函数)
@anchor{library/functions callable}@anchor{c1f}
@deffn {函数} callable (object)

如果参数 @emph{object} 是可调用的就返回 @ref{59c,,True}，否则返回 @ref{497,,False}。 如果返回 @code{True}，调用仍可能失败，但如果返回 @code{False}，则调用 @emph{object} 将肯定不会成功。 请注意类是可调用的（调用类将返回一个新的实例）；如果实例所属的类有 @ref{158f,,__call__()} 则它就是可调用的。


3.2 新版功能: 这个函数一开始在 Python 3.0 被移除了，但在 Python 3.2 被重新加入。

@end deffn

@geindex chr() (內置函数)
@anchor{library/functions chr}@anchor{1589}
@deffn {函数} chr (i)

返回 Unicode 码位为整数 @emph{i} 的字符的字符串格式。例如，@code{chr(97)} 返回字符串 @code{'a'}，@code{chr(8364)} 返回字符串 @code{'€'}。这是 @ref{1588,,ord()} 的逆函数。

实参的合法范围是 0 到 1,114,111（16 进制表示是 0x10FFFF）。如果 @emph{i} 超过这个范围，会触发 @ref{16d,,ValueError} 异常。
@end deffn

@geindex classmethod() (內置函数)
@anchor{library/functions classmethod}@anchor{310}
@deffn {函数} @@classmethod

把一个方法封装成类方法。

一个类方法把类自己作为第一个实参，就像一个实例方法把实例自己作为第一个实参。请用以下习惯来声明类方法:

@example
class C:
    @@classmethod
    def f(cls, arg1, arg2): ...
@end example

@code{@@classmethod} 这样的形式称为函数的 @ref{174,,decorator} -- 详情参阅 @ref{13bf,,函数定义}。

类方法的调用可以在类上进行 (例如 @code{C.f()}) 也可以在实例上进行 (例如 @code{C().f()})。 其所属类以外的类实例会被忽略。 如果类方法在其所属类的派生类上调用，则该派生类对象会被作为隐含的第一个参数被传入。

类方法与 C++ 或 Java 中的静态方法不同。 如果你需要后者，请参阅本节中的 @ref{311,,staticmethod()}。 有关类方法的更多信息，请参阅 @ref{1582,,标准类型层级结构}。


在 3.9 版更改: 类方法现在可以包装其他 @ref{15a8,,描述器} 例如 @ref{30f,,property()}。

@end deffn

@geindex compile() (內置函数)
@anchor{library/functions compile}@anchor{2ee}
@deffn {函数} compile (source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

将 @emph{source} 编译成代码或 AST 对象。代码对象可以被 @ref{d14,,exec()} 或 @ref{c6a,,eval()} 执行。@emph{source} 可以是常规的字符串、字节字符串，或者 AST 对象。参见 @ref{7,,ast} 模块的文档了解如何使用 AST 对象。

@emph{filename} 实参需要是代码读取的文件名；如果代码不需要从文件中读取，可以传入一些可辨识的值（经常会使用 @code{'<string>'}）。

@emph{mode} 实参指定了编译代码必须用的模式。如果 @emph{source} 是语句序列，可以是 @code{'exec'}；如果是单一表达式，可以是 @code{'eval'}；如果是单个交互式语句，可以是 @code{'single'}。（在最后一种情况下，如果表达式执行结果不是 @code{None} 将会被打印出来。）

可选参数 @emph{flags} 和 @emph{dont_inherit} 控制应当激活哪个 @ref{1750,,编译器选项} 以及应当允许哪个 @ref{16f4,,future 特性}。 如果两者都未提供 (或都为零) 则代码会应用与调用 @ref{2ee,,compile()} 的代码相同的旗标来编译。 如果给出了 @emph{flags} 参数而未给出 @emph{dont_inherit} (或者为零) 则会在无论如何都将被使用的旗标之外还会额外使用 @emph{flags} 参数所指定的编译器选项和 future 语句。 如果 @emph{dont_inherit} 为非零整数，则只使用 @emph{flags} 参数 -- 外围代码中的旗标 (future 特性和编译器选项) 会被忽略。

编译器选项和 future 语句是由比特位来指明的。 比特位可以通过一起按位 OR 来指明多个选项。 指明特定 future 特性所需的比特位可以在 @ref{0,,__future__} 模块的 @code{_Feature} 实例的 @code{compiler_flag} 属性中找到。 @ref{1750,,编译器旗标} 可以在 @ref{7,,ast} 模块中查找带有 @code{PyCF_} 前缀的名称。

@emph{optimize} 实参指定编译器的优化级别；默认值 @code{-1}  选择与解释器的 @ref{788,,-O} 选项相同的优化级别。显式级别为 @code{0} （没有优化；@code{__debug__}  为真）、@code{1} （断言被删除， @code{__debug__} 为假）或 @code{2} （文档字符串也被删除）。

如果编译的源码不合法，此函数会触发 @ref{562,,SyntaxError} 异常；如果源码包含 null 字节，则会触发 @ref{16d,,ValueError} 异常。

如果您想分析 Python 代码的 AST 表示，请参阅 @ref{2dd,,ast.parse()}。

引发一个 @ref{fec,,审计事件} @code{compile} 附带参数 @code{source}, @code{filename}。

@cartouche
@quotation 注解 
在 @code{'single'}  或 @code{'eval'} 模式编译多行代码字符串时，输入必须以至少一个换行符结尾。 这使 @ref{1a,,code} 模块更容易检测语句的完整性。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
在将足够大或者足够复杂的字符串编译成 AST 对象时，Python 解释器有可能因为 Python AST 编译器的栈深度限制而崩溃。
@end quotation
@end cartouche


在 3.2 版更改: 允许使用 Windows 和 Mac 的换行符。在 @code{'exec'} 模式不再需要以换行符结尾。增加了  @emph{optimize} 形参。



在 3.5 版更改: 之前 @emph{source} 中包含 null 字节的话会触发 @ref{1ff,,TypeError} 异常。



3.8 新版功能: @code{ast.PyCF_ALLOW_TOP_LEVEL_AWAIT} 现在可在旗标中传入以启用对最高层级 @code{await}, @code{async for} 和 @code{async with} 的支持。

@end deffn

@geindex complex (內置类)
@anchor{library/functions complex}@anchor{2c8}
@deffn {类} complex ([real[, imag]])

返回值为 @emph{real} + @emph{imag}*1j 的复数，或将字符串或数字转换为复数。如果第一个形参是字符串，则它被解释为一个复数，并且函数调用时必须没有第二个形参。第二个形参不能是字符串。每个实参都可以是任意的数值类型（包括复数）。如果省略了 @emph{imag}，则默认值为零，构造函数会像 @ref{205,,int} 和 @ref{1fe,,float} 一样进行数值转换。如果两个实参都省略，则返回 @code{0j}。

对于一个普通 Python 对象 @code{x}，@code{complex(x)} 会委托给 @code{x.__complex__()}。  如果 @code{__complex__()} 未定义则将回退至 @ref{2cb,,__float__()}。 如果 @code{__float__()} 未定义则将回退至 @ref{2c9,,__index__()}。

@cartouche
@quotation 注解 
当从字符串转换时，字符串在 @code{+} 或 @code{-} 的周围必须不能有空格。例如 @code{complex('1+2j')} 是合法的，但 @code{complex('1 + 2j')} 会触发 @ref{16d,,ValueError} 异常。
@end quotation
@end cartouche

@ref{1382,,数字类型 --- int@comma{} float@comma{} complex} 描述了复数类型。


在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。



在 3.8 版更改: 如果 @ref{2cc,,__complex__()} 和 @ref{2cb,,__float__()} 未定义则回退至 @ref{2c9,,__index__()}。

@end deffn

@geindex delattr() (內置函数)
@anchor{library/functions delattr}@anchor{173e}
@deffn {函数} delattr (object, name)

@ref{1742,,setattr()} 相关的函数。实参是一个对象和一个字符串。该字符串必须是对象的某个属性。如果对象允许，该函数将删除指定的属性。例如 @code{delattr(x, 'foobar')}  等价于 @code{del x.foobar} 。
@end deffn
@anchor{library/functions func-dict}@anchor{1741}

@deffn {类} dict (**kwarg)

@deffnx {类} dict (mapping, **kwarg)

@deffnx {类} dict (iterable, **kwarg)

创建一个新的字典。@ref{164,,dict} 对象是一个字典类。参见 @ref{164,,dict} 和 @ref{417,,映射类型 --- dict} 了解这个类。

其他容器类型，请参见内置的 @ref{1f9,,list}、@ref{1f7,,set} 和 @ref{1a2,,tuple} 类，以及 @ref{1d,,collections} 模块。
@end deffn

@geindex dir() (內置函数)
@anchor{library/functions dir}@anchor{e01}
@deffn {函数} dir ([object])

如果没有实参，则返回当前本地作用域中的名称列表。如果有实参，它会尝试返回该对象的有效属性列表。

如果对象有一个名为 @ref{434,,__dir__()} 的方法，那么该方法将被调用，并且必须返回一个属性列表。这允许实现自定义 @ref{433,,__getattr__()} 或 @ref{552,,__getattribute__()} 函数的对象能够自定义 @ref{e01,,dir()} 来报告它们的属性。

如果对象不提供 @ref{434,,__dir__()}，这个函数会尝试从对象已定义的 @ref{5fe,,__dict__} 属性和类型对象收集信息。结果列表并不总是完整的，如果对象有自定义 @ref{433,,__getattr__()}，那结果可能不准确。

默认的 @ref{e01,,dir()} 机制对不同类型的对象行为不同，它会试图返回最相关而不是最全的信息：


@itemize *

@item 
如果对象是模块对象，则列表包含模块的属性名称。

@item 
如果对象是类型或类对象，则列表包含它们的属性名称，并且递归查找所有基类的属性。

@item 
否则，列表包含对象的属性名称，它的类属性名称，并且递归查找它的类的所有基类的属性。
@end itemize

返回的列表按字母表排序。例如：

@example
>>> import struct
>>> dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
@end example

@cartouche
@quotation 注解 
因为 @ref{e01,,dir()} 主要是为了便于在交互式时使用，所以它会试图返回人们感兴趣的名字集合，而不是试图保证结果的严格性或一致性，它具体的行为也可能在不同版本之间改变。例如，当实参是一个类时，metaclass 的属性不包含在结果列表中。
@end quotation
@end cartouche
@end deffn

@geindex divmod() (內置函数)
@anchor{library/functions divmod}@anchor{294}
@deffn {函数} divmod (a, b)

它将两个（非复数）数字作为实参，并在执行整数除法时返回一对商和余数。对于混合操作数类型，适用双目算术运算符的规则。对于整数，结果和 @code{(a // b, a % b)} 一致。对于浮点数，结果是 @code{(q, a % b)} ，@emph{q} 通常是 @code{math.floor(a / b)} 但可能会比 1 小。在任何情况下， @code{q * b + a % b} 和  @emph{a} 基本相等；如果 @code{a % b} 非零，它的符号和 @emph{b} 一样，并且 @code{0 <= abs(a % b) < abs(b)} 。
@end deffn

@geindex enumerate() (內置函数)
@anchor{library/functions enumerate}@anchor{eaf}
@deffn {函数} enumerate (iterable, start=0)

返回一个枚举对象。@emph{iterable} 必须是一个序列，或 @ref{11ba,,iterator}，或其他支持迭代的对象。 @ref{eaf,,enumerate()} 返回的迭代器的 @ref{d34,,__next__()} 方法返回一个元组，里面包含一个计数值（从 @emph{start} 开始，默认为 0）和通过迭代 @emph{iterable} 获得的值。

@example
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
@end example

等价于:

@example
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
@end example
@end deffn

@geindex eval() (內置函数)
@anchor{library/functions eval}@anchor{c6a}
@deffn {函数} eval (expression[, globals[, locals]])

实参是一个字符串，以及可选的 globals 和 locals。@emph{globals} 实参必须是一个字典。@emph{locals} 可以是任何映射对象。

@emph{expression} 参数会作为一个 Python 表达式（从技术上说是一个条件列表）被解析并求值，并使用 @emph{globals} 和 @emph{locals} 字典作为全局和局部命名空间。 如果 @emph{globals} 字典存在且不包含以 @code{__builtins__} 为键的值，则会在解析 @emph{expression} 之前插入以此为键的对内置模块 @ref{12,,builtins} 的引用。 这意味着 @emph{expression} 通常具有对标准 @ref{12,,builtins} 模块的完全访问权限且受限的环境会被传播。 如果省略 @emph{locals} 字典则其默认值为 @emph{globals} 字典。 如果两个字典同时省略，则表达式执行时会使用 @ref{c6a,,eval()} 被调用的环境中的 @emph{globals} 和 @emph{locals}。 请注意，@emph{eval()} 并没有对外围环境下的 (非局部) @ref{1751,,嵌套作用域} 的访问权限。

返回值就是表达式的求值结果。 语法错误将作为异常被报告。 例如：

@example
>>> x = 1
>>> eval('x+1')
2
@end example

这个函数也可以用来执行任何代码对象（如 @ref{2ee,,compile()}  创建的）。这种情况下，参数是代码对象，而不是字符串。如果编译该对象时的 @emph{mode} 实参是 @code{'exec'} 那么 @ref{c6a,,eval()} 返回值为 @code{None} 。

提示： @ref{d14,,exec()} 函数支持动态执行语句。 @ref{fa1,,globals()} 和 @ref{55f,,locals()} 函数各自返回当前的全局和本地字典，因此您可以将它们传递给 @ref{c6a,,eval()} 或 @ref{d14,,exec()} 来使用。

另外可以参阅 @ref{5a8,,ast.literal_eval()}，该函数可以安全执行仅包含文字的表达式字符串。

引发一个 @ref{fec,,审计事件} @code{exec} 附带参数 @code{code_object}。
@end deffn

@geindex 內置函数; exec

@geindex exec() (內置函数)
@anchor{library/functions exec}@anchor{d14}
@deffn {函数} exec (object[, globals[, locals]])

这个函数支持动态执行 Python 代码。 @emph{object} 必须是字符串或者代码对象。 如果是字符串，那么该字符串将被解析为一系列 Python 语句并执行（除非发生语法错误）。 @footnote{@w{(1)} 
解析器只接受 Unix 风格的行结束符。如果您从文件中读取代码，请确保用换行符转换模式转换 Windows 或 Mac 风格的换行符。
} 如果是代码对象，它将被直接执行。 在任何情况下，被执行的代码都应当是有效的文件输入（见参考手册中的 @ref{172b,,文件输入}  一节）。 请注意即使在传递给 @ref{d14,,exec()} 函数的代码的上下文中，@ref{d0f,,nonlocal}, @ref{2ce,,yield} 和 @ref{2cf,,return} 语句也不能在函数定义以外使用。 该函数的返回值是 @code{None}。

无论哪种情况，如果省略了可选项，代码将在当前作用域内执行。 如果只提供了 @emph{globals}，则它必须是一个字典（不能是字典的子类），该字典将同时被用于全局和局部变量。 如果同时提供了 @emph{globals} 和 @emph{locals}，它们会分别被用于全局和局部变量。 如果提供了 @emph{locals}，则它可以是任何映射对象。 请记住在模块层级上，globals 和 locals 是同一个字典。 如果 exec 得到两个单独对象作为 @emph{globals} 和 @emph{locals}，则代码将如同嵌入类定义的情况一样执行。

如果 @emph{globals} 字典不包含 @code{__builtins__} 键值，则将为该键插入对内建 @ref{12,,builtins} 模块字典的引用。因此，在将执行的代码传递给 @ref{d14,,exec()} 之前，可以通过将自己的 @code{__builtins__} 字典插入到 @emph{globals} 中来控制可以使用哪些内置代码。

引发一个 @ref{fec,,审计事件} @code{exec} 附带参数 @code{code_object}。

@cartouche
@quotation 注解 
内置 @ref{fa1,,globals()} 和 @ref{55f,,locals()} 函数各自返回当前的全局和本地字典，因此可以将它们传递给 @ref{d14,,exec()} 的第二个和第三个实参。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
默认情况下，@emph{locals} 的行为如下面 @ref{55f,,locals()} 函数描述的一样：不要试图改变默认的 @emph{locals} 字典。如果您想在 @ref{d14,,exec()} 函数返回时知道代码对 @emph{locals} 的变动，请明确地传递 @emph{locals} 字典。
@end quotation
@end cartouche
@end deffn

@geindex filter() (內置函数)
@anchor{library/functions filter}@anchor{d00}
@deffn {函数} filter (function, iterable)

用 @emph{iterable}  中函数 @emph{function} 返回真的那些元素，构建一个新的迭代器。@emph{iterable} 可以是一个序列，一个支持迭代的容器，或一个迭代器。如果 @emph{function} 是 @code{None} ，则会假设它是一个身份函数，即 @emph{iterable} 中所有返回假的元素会被移除。

请注意， @code{filter(function, iterable)} 相当于一个生成器表达式，当 function 不是 @code{None} 的时候为 @code{(item for item in iterable if function(item))}；function 是 @code{None} 的时候为 @code{(item for item in iterable if item)} 。

请参阅 @ref{1752,,itertools.filterfalse()} 了解，只有 @emph{function} 返回 false 时才选取 @emph{iterable} 中元素的补充函数。
@end deffn

@geindex float (內置类)
@anchor{library/functions float}@anchor{1fe}
@deffn {类} float ([x])

@geindex NaN
@geindex Infinity

返回从数字或字符串 @emph{x} 生成的浮点数。

如果实参是字符串，则它必须是包含十进制数字的字符串，字符串前面可以有符号，之前也可以有空格。可选的符号有 @code{'+'} 和 @code{'-'} ； @code{'+'} 对创建的值没有影响。实参也可以是 NaN（非数字）、正负无穷大的字符串。确切地说，除去首尾的空格后，输入必须遵循以下语法：

@example
@anchor{library/functions grammar-token-sign}@anchor{1753}sign           ::= "+" | "-"
@anchor{library/functions grammar-token-infinity}@anchor{1754}infinity       ::= "Infinity" | "inf"
@anchor{library/functions grammar-token-nan}@anchor{1755}nan            ::= "nan"
@anchor{library/functions grammar-token-numeric-value}@anchor{1756}numeric_value  ::= floatnumber | infinity | nan
@anchor{library/functions grammar-token-numeric-string}@anchor{1757}numeric_string ::= [sign] numeric_value
@end example

这里， @code{floatnumber} 是 Python 浮点数的字符串形式，详见 @ref{156d,,浮点数字面值}。字母大小写都可以，例如，“inf”、“Inf”、“INFINITY”、“iNfINity” 都可以表示正无穷大。

另一方面，如果实参是整数或浮点数，则返回具有相同值（在 Python 浮点精度范围内）的浮点数。如果实参在 Python 浮点精度范围外，则会触发 @ref{a4a,,OverflowError}。

对于一个普通 Python 对象 @code{x}，@code{float(x)} 会委托给 @code{x.__float__()}。 如果 @code{__float__()} 未定义则将回退至 @ref{2c9,,__index__()}。

如果没有实参，则返回 @code{0.0} 。

例如:

@example
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
@end example

@ref{1382,,数字类型 --- int@comma{} float@comma{} complex} 描述了浮点类型。


在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。



在 3.7 版更改: @emph{x} 现在只能作为位置参数。



在 3.8 版更改: 如果 @ref{2cb,,__float__()} 未定义则回退至 @ref{2c9,,__index__()}。

@end deffn

@geindex __format__
@geindex string; format() (built-in function)

@geindex format() (內置函数)
@anchor{library/functions format}@anchor{5de}
@deffn {函数} format (value[, format_spec])

将 @emph{value} 转换为 @emph{format_spec} 控制的“格式化”表示。@emph{format_spec} 的解释取决于 @emph{value} 实参的类型，但是大多数内置类型使用标准格式化语法：@ref{5e1,,格式规格迷你语言}。

默认的 @emph{format_spec} 是一个空字符串，它通常给出与调用 @ref{206,,str(value)} 相同的结果。

调用 @code{format(value, format_spec)} 会转换成  @code{type(value).__format__(value, format_spec)} ，所以实例字典中的 @ref{a38,,__format__()} 方法将不会调用。如果方法搜索回退到 @ref{3da,,object} 类但  @emph{format_spec} 不为空，或者如果 @emph{format_spec} 或返回值不是字符串，则会触发 @ref{1ff,,TypeError} 异常。


在 3.4 版更改: 当 @emph{format_spec} 不是空字符串时， @code{object().__format__(format_spec)} 会触发  @ref{1ff,,TypeError}。

@end deffn
@anchor{library/functions func-frozenset}@anchor{1745}

@deffn {类} frozenset ([iterable])

返回一个新的 @ref{1f8,,frozenset} 对象，它包含可选参数 @emph{iterable} 中的元素。 @code{frozenset} 是一个内置的类。有关此类的文档，请参阅 @ref{1f8,,frozenset} 和 @ref{1758,,集合类型 --- set@comma{} frozenset}。

请参阅内建的 @ref{1f7,,set}、@ref{1f9,,list}、@ref{1a2,,tuple} 和 @ref{164,,dict} 类，以及 @ref{1d,,collections} 模块来了解其它的容器。
@end deffn

@geindex getattr() (內置函数)
@anchor{library/functions getattr}@anchor{554}
@deffn {函数} getattr (object, name[, default])

返回对象命名属性的值。@emph{name} 必须是字符串。如果该字符串是对象的属性之一，则返回该属性的值。例如， @code{getattr(x, 'foobar')} 等同于 @code{x.foobar}。如果指定的属性不存在，且提供了 @emph{default} 值，则返回它，否则触发 @ref{4aa,,AttributeError}。

@cartouche
@quotation 注解 
由于 @ref{1650,,私有名称混合} 发生在编译时，因此必须 手动混合私有属性（以两个下划线打头的属性）名称以使使用 @ref{554,,getattr()} 来提取它。
@end quotation
@end cartouche
@end deffn

@geindex globals() (內置函数)
@anchor{library/functions globals}@anchor{fa1}
@deffn {函数} globals ()

返回实现当前模块命名空间的字典。对于函数内的代码，这是在定义函数时设置的，无论函数在哪里被调用都保持不变。
@end deffn

@geindex hasattr() (內置函数)
@anchor{library/functions hasattr}@anchor{553}
@deffn {函数} hasattr (object, name)

该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称，则返回 @code{True}，否则返回 @code{False}。（此功能是通过调用 @code{getattr(object, name)} 看是否有 @ref{4aa,,AttributeError} 异常来实现的。）
@end deffn

@geindex hash() (內置函数)
@anchor{library/functions hash}@anchor{aac}
@deffn {函数} hash (object)

返回该对象的哈希值（如果它有的话）。哈希值是整数。它们在字典查找元素时用来快速比较字典的键。相同大小的数字变量有相同的哈希值（即使它们类型不同，如 1 和 1.0）。

@cartouche
@quotation 注解 
如果对象实现了自己的 @ref{455,,__hash__()} 方法，请注意，@ref{aac,,hash()} 根据机器的字长来截断返回值。另请参阅 @ref{455,,__hash__()}。
@end quotation
@end cartouche
@end deffn

@geindex help() (內置函数)
@anchor{library/functions help}@anchor{175}
@deffn {函数} help ([object])

启动内置的帮助系统（此函数主要在交互式中使用）。如果没有实参，解释器控制台里会启动交互式帮助系统。如果实参是一个字符串，则在模块、函数、类、方法、关键字或文档主题中搜索该字符串，并在控制台上打印帮助信息。如果实参是其他任意对象，则会生成该对象的帮助页。

请注意如果在函数的形参列表中出现了斜杠 (/)，则它在发起调用 @ref{175,,help()} 的时候意味着斜杠之前的均为仅限位置形参。 更多相关信息，请参阅 @ref{1759,,有关仅限位置形参的 FAQ 条目}。

该函数通过 @ref{eb,,site} 模块加入到内置命名空间。


在 3.4 版更改: @ref{d9,,pydoc} 和 @ref{a0,,inspect} 的变更使得可调用对象的签名信息更加全面和一致。

@end deffn

@geindex hex() (內置函数)
@anchor{library/functions hex}@anchor{d36}
@deffn {函数} hex (x)

将整数转换为以“0x”为前缀的小写十六进制字符串。如果 @emph{x} 不是 Python @ref{205,,int} 对象，则必须定义返回整数的 @ref{2c9,,__index__()} 方法。一些例子：

@example
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
@end example

如果要将整数转换为大写或小写的十六进制字符串，并可选择有无“0x”前缀，则可以使用如下方法：

@example
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'@{255:#x@}', f'@{255:x@}', f'@{255:X@}'
('0xff', 'ff', 'FF')
@end example

另见 @ref{5de,,format()} 获取更多信息。

另请参阅 @ref{205,,int()} 将十六进制字符串转换为以 16 为基数的整数。

@cartouche
@quotation 注解 
如果要获取浮点数的十六进制字符串形式，请使用 @ref{1489,,float.hex()} 方法。
@end quotation
@end cartouche
@end deffn

@geindex id() (內置函数)
@anchor{library/functions id}@anchor{e53}
@deffn {函数} id (object)

返回对象的“标识值”。该值是一个整数，在此对象的生命周期中保证是唯一且恒定的。两个生命期不重叠的对象可能具有相同的 @ref{e53,,id()} 值。

@strong{CPython implementation detail:} This is the address of the object in memory.

引发一个 @ref{fec,,审计事件} @code{builtins.id}，附带参数 @code{id}。
@end deffn

@geindex input() (內置函数)
@anchor{library/functions input}@anchor{d3b}
@deffn {函数} input ([prompt])

如果存在 @emph{prompt} 实参，则将其写入标准输出，末尾不带换行符。接下来，该函数从输入中读取一行，将其转换为字符串（除了末尾的换行符）并返回。当读取到 EOF 时，则触发 @ref{d3c,,EOFError}。例如:

@example
>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"
@end example

如果加载了 @ref{de,,readline} 模块，@ref{d3b,,input()} 将使用它来提供复杂的行编辑和历史记录功能。

引发一个 @ref{fec,,审计事件} @code{builtins.input} 附带参数 @code{prompt}。


在成功读取输入之后引发一个审计事件 @code{builtins.input/result} 附带结果。

@end deffn

@geindex int (內置类)
@anchor{library/functions int}@anchor{205}
@deffn {类} int ([x])

@deffnx {类} int (x, base=10)

返回一个基于数字或字符串 @emph{x} 构造的整数对象，或者在未给出参数时返回 @code{0}。 如果 @emph{x} 定义了 @ref{2ca,,__int__()}，@code{int(x)} 将返回 @code{x.__int__()}。 如果 @emph{x} 定义了 @ref{2c9,,__index__()}，它将返回 @code{x.__index__()}。 如果 @emph{x} 定义了 @ref{15f0,,__trunc__()}，它将返回 @code{x.__trunc__()}。 对于浮点数，它将向零舍入。

如果 @emph{x} 不是数字，或者有 @emph{base} 参数，@emph{x} 必须是字符串、@ref{172,,bytes}、表示进制为 @emph{base} 的 @ref{1562,,整数字面值} 的 @ref{173,,bytearray} 实例。该文字前可以有 @code{+} 或 @code{-} （中间不能有空格），前后可以有空格。一个进制为 n 的数字包含 0 到 n-1 的数，其中 @code{a} 到 @code{z} （或 @code{A} 到 @code{Z} ）表示 10 到 35。默认的 @emph{base} 为 10 ，允许的进制有 0、2-36。2、8、16 进制的数字可以在代码中用 @code{0b}/@code{0B} 、 @code{0o}/@code{0O} 、 @code{0x}/@code{0X} 前缀来表示。进制为 0 将安照代码的字面量来精确解释，最后的结果会是 2、8、10、16 进制中的一个。所以 @code{int('010', 0)} 是非法的，但 @code{int('010')} 和 @code{int('010', 8)} 是合法的。

整数类型定义请参阅 @ref{1382,,数字类型 --- int@comma{} float@comma{} complex} 。


在 3.4 版更改: 如果 @emph{base} 不是 @ref{205,,int} 的实例，但 @emph{base} 对象有 @ref{2c9,,base.__index__} 方法，则会调用该方法来获取进制数。以前的版本使用 @ref{2ca,,base.__int__} 而不是 @ref{2c9,,base.__index__}。



在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。



在 3.7 版更改: @emph{x} 现在只能作为位置参数。



在 3.8 版更改: 如果 @ref{2ca,,__int__()} 未定义则回退至 @ref{2c9,,__index__()}。



在 3.9.14 版更改: @ref{205,,int} string inputs and string representations can be limited to
help avoid denial of service attacks. A @ref{16d,,ValueError} is raised when
the limit is exceeded while converting a string @emph{x} to an @ref{205,,int} or
when converting an @ref{205,,int} into a string would exceed the limit.
See the @ref{288,,integer string conversion length limitation} documentation.

@end deffn

@geindex isinstance() (內置函数)
@anchor{library/functions isinstance}@anchor{55a}
@deffn {函数} isinstance (object, classinfo)

如果参数 @emph{object} 是参数 @emph{classinfo} 的实例或者是其 (直接、间接或 @ref{c0e,,虚拟}) 子类则返回 @code{True}。 如果 @emph{object} 不是给定类型的对象，函数将总是返回 @code{False}。 如果 @emph{classinfo} 是类型对象元组（或由其他此类元组递归组成的元组），那么如果 @emph{object} 是其中任何一个类型的实例就返回 @code{True}。 如果 @emph{classinfo} 既不是类型，也不是类型元组或类型元组的元组，则将引发 @ref{1ff,,TypeError} 异常。
@end deffn

@geindex issubclass() (內置函数)
@anchor{library/functions issubclass}@anchor{55b}
@deffn {函数} issubclass (class, classinfo)

Return @code{True} if @emph{class} is a subclass (direct, indirect or @ref{c0e,,virtual}) of @emph{classinfo}.  A
class is considered a subclass of itself. @emph{classinfo} may be a tuple of class
objects (or recursively, other such tuples),
in which case return @code{True} if @emph{class} is a subclass of any entry
in @emph{classinfo}.  In any other case, a @ref{1ff,,TypeError} exception is raised.
@end deffn

@geindex iter() (內置函数)
@anchor{library/functions iter}@anchor{df5}
@deffn {函数} iter (object[, sentinel])

返回一个 @ref{11ba,,iterator} 对象。根据是否存在第二个实参，第一个实参的解释是非常不同的。如果没有第二个实参，@emph{object} 必须是支持迭代协议（有 @ref{611,,__iter__()} 方法）的集合对象，或必须支持序列协议（有 @ref{3ad,,__getitem__()} 方法，且数字参数从 @code{0} 开始）。如果它不支持这些协议，会触发 @ref{1ff,,TypeError}。如果有第二个实参 @emph{sentinel}，那么 @emph{object} 必须是可调用的对象。这种情况下生成的迭代器，每次迭代调用它的 @ref{d34,,__next__()} 方法时都会不带实参地调用 @emph{object}；如果返回的结果是 @emph{sentinel} 则触发 @ref{58a,,StopIteration}，否则返回调用结果。

另请参阅 @ref{15c9,,迭代器类型}。

适合 @ref{df5,,iter()} 的第二种形式的应用之一是构建块读取器。 例如，从二进制数据库文件中读取固定宽度的块，直至到达文件的末尾:

@example
from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b'@w{'}):
        process_block(block)
@end example
@end deffn

@geindex len() (內置函数)
@anchor{library/functions len}@anchor{292}
@deffn {函数} len (s)

返回对象的长度（元素个数）。实参可以是序列（如 string、bytes、tuple、list 或 range 等）或集合（如 dictionary、set 或 frozen set 等）。

@strong{CPython implementation detail:} @code{len} 对于大于 @ref{c1e,,sys.maxsize} 的长度如 @ref{1f6,,range(2 ** 100)} 会引发 @ref{a4a,,OverflowError}。
@end deffn
@anchor{library/functions func-list}@anchor{1746}

@deffn {类} list ([iterable])

虽然被称为函数，@ref{1f9,,list} 实际上是一种可变序列类型，详情请参阅 @ref{175a,,列表} 和 @ref{13d3,,序列类型 --- list@comma{} tuple@comma{} range}。
@end deffn

@geindex locals() (內置函数)
@anchor{library/functions locals}@anchor{55f}
@deffn {函数} locals ()

更新并返回表示当前本地符号表的字典。 在函数代码块但不是类代码块中调用 @ref{55f,,locals()} 时将返回自由变量。 请注意在模块层级上，@ref{55f,,locals()} 和 @ref{fa1,,globals()} 是同一个字典。

@cartouche
@quotation 注解 
不要更改此字典的内容；更改不会影响解释器使用的局部变量或自由变量的值。
@end quotation
@end cartouche
@end deffn

@geindex map() (內置函数)
@anchor{library/functions map}@anchor{cff}
@deffn {函数} map (function, iterable, ...)

返回一个将 @emph{function} 应用于 @emph{iterable} 中每一项并输出其结果的迭代器。 如果传入了额外的 @emph{iterable} 参数，@emph{function} 必须接受相同个数的实参并被应用于从所有可迭代对象中并行获取的项。 当有多个可迭代对象时，最短的可迭代对象耗尽则整个迭代就将结束。 对于函数的输入已经是参数元组的情况，请参阅 @ref{b0e,,itertools.starmap()}。
@end deffn

@geindex max() (內置函数)
@anchor{library/functions max}@anchor{901}
@deffn {函数} max (iterable, *[, key, default])

@deffnx {函数} max (arg1, arg2, *args[, key])

返回可迭代对象中最大的元素，或者返回两个及以上实参中最大的。

如果只提供了一个位置参数，它必须是非空 @ref{c84,,iterable}，返回可迭代对象中最大的元素；如果提供了两个及以上的位置参数，则返回最大的位置参数。

有两个可选只能用关键字的实参。@emph{key} 实参指定排序函数用的参数，如传给 @ref{550,,list.sort()} 的。@emph{default} 实参是当可迭代对象为空时返回的值。如果可迭代对象为空，并且没有给 @emph{default} ，则会触发 @ref{16d,,ValueError}。

如果有多个最大元素，则此函数将返回第一个找到的。这和其他稳定排序工具如 @code{sorted(iterable, key=keyfunc, reverse=True)[0]} 和 @code{heapq.nlargest(1, iterable, key=keyfunc)} 保持一致。


3.4 新版功能: keyword-only 实参 @emph{default} 。



在 3.8 版更改: @emph{key} 可以为 @code{None}。

@end deffn
@anchor{library/functions func-memoryview}@anchor{173f}

@deffn {类} memoryview (object)

返回由给定实参创建的“内存视图”对象。有关详细信息，请参阅 @ref{175b,,内存视图}。
@end deffn

@geindex min() (內置函数)
@anchor{library/functions min}@anchor{900}
@deffn {函数} min (iterable, *[, key, default])

@deffnx {函数} min (arg1, arg2, *args[, key])

返回可迭代对象中最小的元素，或者返回两个及以上实参中最小的。

如果只提供了一个位置参数，它必须是 @ref{c84,,iterable}，返回可迭代对象中最小的元素；如果提供了两个及以上的位置参数，则返回最小的位置参数。

有两个可选只能用关键字的实参。@emph{key} 实参指定排序函数用的参数，如传给 @ref{550,,list.sort()} 的。@emph{default} 实参是当可迭代对象为空时返回的值。如果可迭代对象为空，并且没有给 @emph{default} ，则会触发 @ref{16d,,ValueError}。

如果有多个最小元素，则此函数将返回第一个找到的。这和其他稳定排序工具如 @code{sorted(iterable, key=keyfunc)[0]} 和 @code{heapq.nsmallest(1, iterable, key=keyfunc)} 保持一致。


3.4 新版功能: keyword-only 实参 @emph{default} 。



在 3.8 版更改: @emph{key} 可以为 @code{None}。

@end deffn

@geindex next() (內置函数)
@anchor{library/functions next}@anchor{77f}
@deffn {函数} next (iterator[, default])

通过调用 @emph{iterator} 的 @ref{d34,,__next__()} 方法获取下一个元素。如果迭代器耗尽，则返回给定的 @emph{default}，如果没有默认值则触发 @ref{58a,,StopIteration}。
@end deffn

@geindex object (內置类)
@anchor{library/functions object}@anchor{3da}
@deffn {类} object

返回一个没有特征的新对象。@ref{3da,,object} 是所有类的基类。它具有所有 Python 类实例的通用方法。这个函数不接受任何实参。

@cartouche
@quotation 注解 
由于 @ref{3da,,object} 没有 @ref{5fe,,__dict__}，因此无法将任意属性赋给 @ref{3da,,object} 的实例。
@end quotation
@end cartouche
@end deffn

@geindex oct() (內置函数)
@anchor{library/functions oct}@anchor{d35}
@deffn {函数} oct (x)

将一个整数转变为一个前缀为“0o”的八进制字符串。结果是一个合法的 Python 表达式。如果 @emph{x} 不是 Python 的 @ref{205,,int} 对象，那它需要定义 @ref{2c9,,__index__()}  方法返回一个整数。一些例子：

@example
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
@end example

如果要将整数转换为八进制字符串，并可选择有无“0o”前缀，则可以使用如下方法：

@example
>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'@{10:#o@}', f'@{10:o@}'
('0o12', '12')
@end example

另见 @ref{5de,,format()} 获取更多信息。

@quotation

@geindex file object; open() built-in function
@end quotation
@end deffn

@geindex open() (內置函数)
@anchor{library/functions open}@anchor{16f}
@deffn {函数} open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

打开 @emph{file} 并返回对应的 @ref{c1d,,file object}。 如果该文件不能被打开，则引发 @ref{30b,,OSError}。 请参阅 @ref{1404,,读写文件} 获取此函数的更多用法示例。

@emph{file} 是一个 @ref{47b,,path-like object}，表示将要打开的文件的路径（绝对路径或者当前工作目录的相对路径），也可以是要被封装的整数类型文件描述符。（如果是文件描述符，它会随着返回的 I/O 对象关闭而关闭，除非 @emph{closefd} 被设为 @code{False} 。）

@emph{mode} 是一个可选字符串，用于指定打开文件的模式。默认值是 @code{'r'}  ，这意味着它以文本模式打开并读取。其他常见模式有：写入 @code{'w'} （截断已经存在的文件）；排它性创建 @code{'x'} ；追加写 @code{'a'} （在 @emph{一些}  Unix 系统上，无论当前的文件指针在什么位置，@emph{所有} 写入都会追加到文件末尾）。在文本模式，如果 @emph{encoding} 没有指定，则根据平台来决定使用的编码：使用 @code{locale.getpreferredencoding(False)} 来获取本地编码。（要读取和写入原始字节，请使用二进制模式并不要指定 @emph{encoding}。）可用的模式有：
@anchor{library/functions filemodes}@anchor{175c}
@geindex file; modes


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

字符

@tab

意义

@item

@code{'r'}

@tab

读取（默认）

@item

@code{'w'}

@tab

写入，并先截断文件

@item

@code{'x'}

@tab

排它性创建，如果文件已存在则失败

@item

@code{'a'}

@tab

写入，如果文件存在则在末尾追加

@item

@code{'b'}

@tab

二进制模式

@item

@code{'t'}

@tab

文本模式（默认）

@item

@code{'+'}

@tab

打开用于更新（读取与写入）

@end multitable


默认模式为 @code{'r'} (打开用于读取文本，与 @code{'rt'} 同义)。 模式 @code{'w+'} 与 @code{'w+b'} 将打开文件并清空内容。 模式 @code{'r+'} 与 @code{'r+b'} 将打开文件并不清空内容。

正如在 @ref{175d,,概述} 中提到的，Python区分二进制和文本I/O。以二进制模式打开的文件（包括 @emph{mode} 参数中的 @code{'b'} ）返回的内容为 @ref{172,,bytes} 对象，不进行任何解码。在文本模式下（默认情况下，或者在 @emph{mode} 参数中包含 @code{'t'} ）时，文件内容返回为 @ref{206,,str} ，首先使用指定的 @emph{encoding} （如果给定）或者使用平台默认的的字节编码解码。

此外还允许使用一个模式字符 @code{'U'}，该字符已不再具有任何效果，并被视为已弃用。 之前它会在文本模式中启用 @ref{6f5,,universal newlines}，这在 Python 3.0 中成为默认行为。 请参阅 @ref{175e,,newline} 形参的文档了解更多细节。

@cartouche
@quotation 注解 
Python不依赖于底层操作系统的文本文件概念;所有处理都由Python本身完成，因此与平台无关。
@end quotation
@end cartouche

@emph{buffering} 是一个可选的整数，用于设置缓冲策略。 传入 0 来关闭缓冲（只允许在二进制模式下），传入 1 来选择行缓冲（只在文本模式下可用），传入一个整数 > 1 来表示固定大小的块缓冲区的字节大小。注意，这样指定缓冲区的大小适用于二进制缓冲的 I/O ，但 @code{TextIOWrapper} （即用 @code{mode='r+'} 打开的文件）会有另一种缓冲。要禁用在 @code{TextIOWrapper} 缓冲，考虑使用 @ref{4ac,,io.TextIOWrapper.reconfigure()} 的 @code{write_through} 标志来。当没有给出 @emph{buffering} 参数时，默认的缓冲策略工作如下。


@itemize *

@item 
二进制文件以固定大小的块进行缓冲；使用启发式方法选择缓冲区的大小，尝试确定底层设备的“块大小”或使用 @ref{175f,,io.DEFAULT_BUFFER_SIZE}。在许多系统上，缓冲区的长度通常为4096或8192字节。

@item 
“交互式”文本文件（ @ref{1760,,isatty()} 返回 @code{True} 的文件）使用行缓冲。其他文本文件使用上述策略用于二进制文件。
@end itemize

@emph{encoding} 是用于解码或编码文件的编码的名称。这应该只在文本模式下使用。默认编码是依赖于平台的（不 管 @ref{4b4,,locale.getpreferredencoding()} 返回何值），但可以使用任何Python支持的 @ref{1761,,text encoding} 。有关支持的编码列表，请参阅 @ref{1b,,codecs} 模块。

@emph{errors} 是一个可选的字符串参数，用于指定如何处理编码和解码错误 - 这不能在二进制模式下使用。可以使用各种标准错误处理程序（列在 @ref{f7d,,错误处理方案} ），但是使用 @ref{ec1,,codecs.register_error()} 注册的任何错误处理名称也是有效的。标准名称包括:


@itemize *

@item 
如果存在编码错误，@code{'strict'} 会引发 @ref{16d,,ValueError} 异常。 默认值 @code{None} 具有相同的效果。

@item 
@code{'ignore'} 忽略错误。请注意，忽略编码错误可能会导致数据丢失。

@item 
@code{'replace'} 会将替换标记（例如 @code{'?'} ）插入有错误数据的地方。

@item 
@code{'surrogateescape'} 将把任何不正确的字节表示为 U+DC80 至 U+DCFF 范围内的下方替代码位。 当在写入数据时使用 @code{surrogateescape} 错误处理句柄时这些替代码位会被转回到相同的字节。 这适用于处理具有未知编码格式的文件。

@item 
只有在写入文件时才支持 @code{'xmlcharrefreplace'}。编码不支持的字符将替换为相应的XML字符引用 @code{&#nnn;}。

@item 
@code{'backslashreplace'} 用Python的反向转义序列替换格式错误的数据。

@item 
@code{'namereplace'} （也只在编写时支持）用 @code{\N@{...@}} 转义序列替换不支持的字符。
@end itemize

@geindex universal newlines; open() built-in function
@anchor{library/functions open-newline-parameter}@anchor{175e}
@emph{newline} 控制 @ref{6f5,,universal newlines} 模式如何生效（它仅适用于文本模式）。它可以是 @code{None}，@code{'@w{'}}，@code{'\n'}，@code{'\r'} 和 @code{'\r\n'}。它的工作原理:


@itemize *

@item 
从流中读取输入时，如果 @emph{newline} 为 @code{None}，则启用通用换行模式。输入中的行可以以 @code{'\n'}，@code{'\r'} 或 @code{'\r\n'} 结尾，这些行被翻译成 @code{'\n'} 在返回呼叫者之前。如果它是 @code{'@w{'}}，则启用通用换行模式，但行结尾将返回给调用者未翻译。如果它具有任何其他合法值，则输入行仅由给定字符串终止，并且行结尾将返回给未调用的调用者。

@item 
将输出写入流时，如果 @emph{newline} 为 @code{None}，则写入的任何 @code{'\n'} 字符都将转换为系统默认行分隔符 @ref{1762,,os.linesep}。如果 @emph{newline} 是 @code{'@w{'}} 或 @code{'\n'}，则不进行翻译。如果 @emph{newline} 是任何其他合法值，则写入的任何 @code{'\n'} 字符将被转换为给定的字符串。
@end itemize

如果 @emph{closefd} 是 @code{False} 并且给出了文件描述符而不是文件名，那么当文件关闭时，底层文件描述符将保持打开状态。如果给出文件名则 @emph{closefd} 必须为 @code{True} （默认值），否则将引发错误。

可以通过传递可调用的 @emph{opener} 来使用自定义开启器。然后通过使用参数（ @emph{file}，@emph{flags} ）调用 @emph{opener} 获得文件对象的基础文件描述符。 @emph{opener} 必须返回一个打开的文件描述符（使用 @ref{762,,os.open} as @emph{opener} 时与传递 @code{None} 的效果相同）。

新创建的文件是 @ref{8f1,,不可继承的}。

下面的示例使用 @ref{762,,os.open()} 函数的 @ref{b14,,dir_fd} 的形参，从给定的目录中用相对路径打开文件:

@example
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor
@end example

@ref{16f,,open()} 函数所返回的 @ref{c1d,,file object} 类型取决于所用模式。 当使用 @ref{16f,,open()} 以文本模式 (@code{'w'}, @code{'r'}, @code{'wt'}, @code{'rt'} 等) 打开文件时，它将返回 @ref{d09,,io.TextIOBase} (特别是 @ref{6f4,,io.TextIOWrapper}) 的一个子类。 当使用缓冲以二进制模式打开文件时，返回的类是 @ref{689,,io.BufferedIOBase} 的一个子类。 具体的类会有多种：在只读的二进制模式下，它将返回 @ref{c64,,io.BufferedReader}；在写入二进制和追加二进制模式下，它将返回 @ref{1763,,io.BufferedWriter}，而在读/写模式下，它将返回 @ref{1764,,io.BufferedRandom}。 当禁用缓冲时，则会返回原始流，即 @ref{afa,,io.RawIOBase} 的一个子类 @ref{d74,,io.FileIO}。

@geindex line-buffered I/O
@geindex unbuffered I/O
@geindex buffer size@comma{} I/O
@geindex I/O control; buffering
@geindex binary mode
@geindex text mode
@geindex 模块; sys

另请参阅文件操作模块，例如 @ref{7e,,fileinput}、@ref{a1,,io} （声明了 @ref{16f,,open()}）、@ref{c4,,os}、@ref{c5,,os.path}、@ref{103,,tempfile} 和 @ref{e9,,shutil}。

引发一个 @ref{fec,,审计事件} @code{open} 附带参数 @code{file}, @code{mode}, @code{flags}。

@code{mode} 与 @code{flags} 参数可以在原始调用的基础上被修改或传递。


@quotation
在 3.3 版更改: 

@itemize *

@item 
增加了 @emph{opener} 形参。

@item 
增加了 @code{'x'} 模式。

@item 
过去触发的 @ref{a7c,,IOError}，现在是 @ref{30b,,OSError} 的别名。

@item 
如果文件已存在但使用了排它性创建模式（ @code{'x'} ），现在会触发 @ref{a42,,FileExistsError}。
@end itemize
@end quotation



@quotation
在 3.4 版更改: 

@itemize *

@item 
文件现在禁止继承。
@end itemize
@end quotation



Deprecated since version 3.4, will be removed in version 3.10: @code{'U'} 模式。



@quotation
在 3.5 版更改: 

@itemize *

@item 
如果系统调用被中断，但信号处理程序没有触发异常，此函数现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常（原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@item 
增加了 @code{'namereplace'} 错误处理接口。
@end itemize
@end quotation



@quotation
在 3.6 版更改: 

@itemize *

@item 
增加对实现了 @ref{5ee,,os.PathLike} 对象的支持。

@item 
在 Windows 上，打开一个控制台缓冲区将返回 @ref{afa,,io.RawIOBase} 的子类，而不是 @ref{d74,,io.FileIO}。
@end itemize
@end quotation

@end deffn

@geindex ord() (內置函数)
@anchor{library/functions ord}@anchor{1588}
@deffn {函数} ord (c)

对表示单个 Unicode 字符的字符串，返回代表它 Unicode 码点的整数。例如 @code{ord('a')} 返回整数 @code{97}， @code{ord('€')} （欧元符号）返回 @code{8364} 。这是 @ref{1589,,chr()} 的逆函数。
@end deffn

@geindex pow() (內置函数)
@anchor{library/functions pow}@anchor{2d6}
@deffn {函数} pow (base, exp[, mod])

返回 @emph{base} 的 @emph{exp} 次幂；如果 @emph{mod} 存在，则返回 @emph{base} 的 @emph{exp} 次幂对 @emph{mod} 取余（比 @code{pow(base, exp) % mod} 更高效）。 两参数形式 @code{pow(base, exp)} 等价于乘方运算符: @code{base**exp}。

参数必须为数值类型。 对于混用的操作数类型，则适用二元算术运算符的类型强制转换规则。 对于 @ref{205,,int} 操作数，结果具有与操作数相同的类型（转换后），除非第二个参数为负值；在这种情况下，所有参数将被转换为浮点数并输出浮点数结果。 例如，@code{pow(10, 2)} 返回 @code{100}，但 @code{pow(10, -2)} 返回 @code{0.01}。 对于 @ref{205,,int} 或 @ref{1fe,,float} 类型的负基和一个非整数的指数，会产生一个复杂的结果。 例如， @code{pow(-9, 0.5)} 返回一个接近于 @code{3j} 的值。

对于 @ref{205,,int} 操作数 @emph{base} 和 @emph{exp}，如果给出 @emph{mod}，则 @emph{mod} 必须为整数类型并且 @emph{mod} 必须不为零。 如果给出 @emph{mod} 并且 @emph{exp} 为负值，则 @emph{base} 必须相对于 @emph{mod} 不可整除。 在这种情况下，将会返回 @code{pow(inv_base, -exp, mod)}，其中 @emph{inv_base} 为 @emph{base} 的倒数对 @emph{mod} 取余。

下面的例子是 @code{38} 的倒数对 @code{97} 取余:

@example
>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True
@end example


在 3.8 版更改: 对于 @ref{205,,int} 操作数，三参数形式的 @code{pow} 现在允许第二个参数为负值，即可以计算倒数的余数。



在 3.8 版更改: 允许关键字参数。 之前只支持位置参数。

@end deffn

@geindex print() (內置函数)
@anchor{library/functions print}@anchor{97a}
@deffn {函数} print (*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

将 @emph{objects} 打印到 @emph{file} 指定的文本流，以 @emph{sep} 分隔并在末尾加上 @emph{end}。 @emph{sep}, @emph{end}, @emph{file} 和 @emph{flush} 如果存在，它们必须以关键字参数的形式给出。

所有非关键字参数都会被转换为字符串，就像是执行了 @ref{206,,str()} 一样，并会被写入到流，以 @emph{sep} 且在末尾加上 @emph{end}。 @emph{sep} 和 @emph{end} 都必须为字符串；它们也可以为 @code{None}，这意味着使用默认值。 如果没有给出 @emph{objects}，则 @ref{97a,,print()} 将只写入 @emph{end}。

@emph{file} 参数必须是一个具有 @code{write(string)} 方法的对象；如果参数不存在或为 @code{None}，则将使用 @ref{428,,sys.stdout}。 由于要打印的参数会被转换为文本字符串，因此 @ref{97a,,print()} 不能用于二进制模式的文件对象。 对于这些对象，应改用 @code{file.write(...)}。

输出是否被缓存通常决定于 @emph{file}，但如果 @emph{flush} 关键字参数为真值，流会被强制刷新。


在 3.3 版更改: 增加了 @emph{flush} 关键字参数。

@end deffn

@geindex property (內置类)
@anchor{library/functions property}@anchor{30f}
@deffn {类} property (fget=None, fset=None, fdel=None, doc=None)

返回 property 属性。

@emph{fget} 是获取属性值的函数。 @emph{fset} 是用于设置属性值的函数。 @emph{fdel} 是用于删除属性值的函数。并且 @emph{doc} 为属性对象创建文档字符串。

一个典型的用法是定义一个托管属性 @code{x}:

@example
class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")
@end example

如果 @emph{c} 是 @emph{C} 的实例，@code{c.x} 将调用getter，@code{c.x = value} 将调用setter， @code{del c.x} 将调用deleter。

如果给出，@emph{doc} 将成为该 property 属性的文档字符串。 否则该 property 将拷贝 @emph{fget} 的文档字符串（如果存在）。 这令使用 @ref{30f,,property()} 作为 @ref{174,,decorator} 来创建只读的特征属性可以很容易地实现:

@example
class Parrot:
    def __init__(self):
        self._voltage = 100000

    @@property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage
@end example

以上 @code{@@property} 装饰器会将 @code{voltage()} 方法转化为一个具有相同名称的只读属性的 "getter"，并将 @emph{voltage} 的文档字符串设置为 "Get the current voltage."

特征属性对象具有 @code{getter}, @code{setter} 以及 @code{deleter} 方法，它们可用作装饰器来创建该特征属性的副本，并将相应的访问函数设为所装饰的函数。  这最好是用一个例子来解释:

@example
class C:
    def __init__(self):
        self._x = None

    @@property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @@x.setter
    def x(self, value):
        self._x = value

    @@x.deleter
    def x(self):
        del self._x
@end example

上述代码与第一个例子完全等价。 注意一定要给附加函数与原始的特征属性相同的名称 (在本例中为 @code{x}。)

返回的特征属性对象同样具有与构造器参数相对应的属性 @code{fget}, @code{fset} 和 @code{fdel}。


在 3.5 版更改: 特征属性对象的文档字符串现在是可写的。

@end deffn
@anchor{library/functions func-range}@anchor{1747}

@deffn {类} range (stop)

@deffnx {类} range (start, stop[, step])

虽然被称为函数，但 @ref{1f6,,range} 实际上是一个不可变的序列类型，参见在 @ref{1765,,range 对象} 与 @ref{13d3,,序列类型 --- list@comma{} tuple@comma{} range} 中的文档说明。
@end deffn

@geindex repr() (內置函数)
@anchor{library/functions repr}@anchor{8c3}
@deffn {函数} repr (object)

返回包含一个对象的可打印表示形式的字符串。 对于许多类型来说，该函数会尝试返回的字符串将会与该对象被传递给 @ref{c6a,,eval()} 时所生成的对象具有相同的值，在其他情况下表示形式会是一个括在尖括号中的字符串，其中包含对象类型的名称与通常包括对象名称和地址的附加信息。 类可以通过定义 @ref{453,,__repr__()} 方法来控制此函数为它的实例所返回的内容。
@end deffn

@geindex reversed() (內置函数)
@anchor{library/functions reversed}@anchor{2cd}
@deffn {函数} reversed (seq)

返回一个反向的 @ref{11ba,,iterator}。 @emph{seq} 必须是一个具有 @ref{631,,__reversed__()} 方法的对象或者是支持该序列协议（具有从 @code{0} 开始的整数类型参数的 @ref{e98,,__len__()} 方法和 @ref{3ad,,__getitem__()} 方法）。
@end deffn

@geindex round() (內置函数)
@anchor{library/functions round}@anchor{d3d}
@deffn {函数} round (number[, ndigits])

返回 @emph{number} 舍入到小数点后 @emph{ndigits} 位精度的值。 如果 @emph{ndigits} 被省略或为 @code{None}，则返回最接近输入值的整数。

对于支持 @ref{d3d,,round()} 的内置类型，值会被舍入到最接近的 10 的负 @emph{ndigits} 次幂的倍数；如果与两个倍数的距离相等，则选择偶数 (因此，@code{round(0.5)} 和 @code{round(-0.5)} 均为 @code{0} 而 @code{round(1.5)} 为 @code{2})。 任何整数值都可作为有效的 @emph{ndigits} (正数、零或负数)。 如果 @emph{ndigits} 被省略或为 @code{None} 则返回值将为整数。 否则返回值与 @emph{number} 的类型相同。

对于一般的 Python 对象 @code{number}, @code{round} 将委托给 @code{number.__round__}。

@cartouche
@quotation 注解 
对浮点数执行 @ref{d3d,,round()} 的行为可能会令人惊讶：例如，@code{round(2.675, 2)} 将给出 @code{2.67} 而不是期望的 @code{2.68}。 这不算是程序错误：这一结果是由于大多数十进制小数实际上都不能以浮点数精确地表示。 请参阅 @ref{1487,,浮点算术：争议和限制} 了解更多信息。
@end quotation
@end cartouche
@end deffn
@anchor{library/functions func-set}@anchor{1740}

@deffn {类} set ([iterable])

返回一个新的 @ref{1f7,,set} 对象，可以选择带有从 @emph{iterable} 获取的元素。 @code{set} 是一个内置类型。 请查看 @ref{1f7,,set} 和 @ref{1758,,集合类型 --- set@comma{} frozenset} 获取关于这个类的文档。

有关其他容器请参看内置的 @ref{1f8,,frozenset}, @ref{1f9,,list}, @ref{1a2,,tuple} 和 @ref{164,,dict} 类，以及 @ref{1d,,collections} 模块。
@end deffn

@geindex setattr() (內置函数)
@anchor{library/functions setattr}@anchor{1742}
@deffn {函数} setattr (object, name, value)

此函数与 @ref{554,,getattr()} 两相对应。 其参数为一个对象、一个字符串和一个任意值。 字符串指定一个现有属性或者新增属性。 函数会将值赋给该属性，只要对象允许这种操作。 例如，@code{setattr(x, 'foobar', 123)} 等价于 @code{x.foobar = 123}。

@cartouche
@quotation 注解 
由于 @ref{1650,,私有名称混合} 发生在编译时，因此必须手动混合私有属性（以两个下划线打头的属性）名称以便使用 @ref{1742,,setattr()} 来设置它。
@end quotation
@end cartouche
@end deffn

@geindex slice (內置类)
@anchor{library/functions slice}@anchor{ed0}
@deffn {类} slice (stop)

@deffnx {类} slice (start, stop[, step])

Return a @ref{1766,,slice} object representing the set of indices specified by
@code{range(start, stop, step)}.  The @emph{start} and @emph{step} arguments default to
@code{None}.  Slice objects have read-only data attributes @code{start},
@code{stop} and @code{step} which merely return the argument
values (or their default).  They have no other explicit functionality;
however they are used by NumPy and other third party packages.
Slice objects are also generated when extended indexing syntax is used.  For
example: @code{a[start:stop:step]} or @code{a[start:stop, i]}.  See
@ref{4b1,,itertools.islice()} for an alternate version that returns an iterator.
@end deffn

@geindex sorted() (內置函数)
@anchor{library/functions sorted}@anchor{54f}
@deffn {函数} sorted (iterable, /, *, key=None, reverse=False)

根据 @emph{iterable} 中的项返回一个新的已排序列表。

具有两个可选参数，它们都必须指定为关键字参数。

@emph{key} 指定带有单个参数的函数，用于从 @emph{iterable} 的每个元素中提取用于比较的键 (例如 @code{key=str.lower})。 默认值为 @code{None} (直接比较元素)。

@emph{reverse} 为一个布尔值。 如果设为 @code{True}，则每个列表元素将按反向顺序比较进行排序。

使用 @ref{c31,,functools.cmp_to_key()} 可将老式的 @emph{cmp} 函数转换为 @emph{key} 函数。

内置的 @ref{54f,,sorted()} 确保是稳定的。 如果一个排序确保不会改变比较结果相等的元素的相对顺序就称其为稳定的 --- 这有利于进行多重排序（例如先按部门、再按薪级排序）。

排序算法只使用 @code{<} 在项目之间比较。 虽然定义一个 @ref{d06,,__lt__()} 方法就足以进行排序，但 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 建议实现所有六个 @ref{16a9,,富比较} 。 这将有助于避免在与其他排序工具（如 @ref{901,,max()} ）使用相同的数据时出现错误，这些工具依赖于不同的底层方法。实现所有六个比较也有助于避免混合类型比较的混乱，因为混合类型比较可以调用反射到 @ref{d71,,__gt__()} 的方法。

有关排序示例和简要排序教程，请参阅 @ref{1767,,排序指南} 。
@end deffn

@geindex staticmethod() (內置函数)
@anchor{library/functions staticmethod}@anchor{311}
@deffn {函数} @@staticmethod

将方法转换为静态方法。

静态方法不会接收隐式的第一个参数。要声明一个静态方法，请使用此语法

@example
class C:
    @@staticmethod
    def f(arg1, arg2, ...): ...
@end example

@code{@@staticmethod} 这样的形式称为函数的 @ref{174,,decorator} -- 详情参阅 @ref{13bf,,函数定义}。

静态方法的调用可以在类上进行 (例如 @code{C.f()}) 也可以在实例上进行 (例如 @code{C().f()})。

Python中的静态方法与Java或C ++中的静态方法类似。另请参阅 @ref{310,,classmethod()} ，用于创建备用类构造函数的变体。

像所有装饰器一样，也可以像常规函数一样调用 @code{staticmethod} ，并对其结果执行某些操作。比如某些情况下需要从类主体引用函数并且您希望避免自动转换为实例方法。对于这些情况，请使用此语法:

@example
class C:
    builtin_open = staticmethod(open)
@end example

想了解更多有关静态方法的信息，请参阅 @ref{1582,,标准类型层级结构} 。
@end deffn

@geindex string; str() (built-in function)
@anchor{library/functions func-str}@anchor{1743}

@deffn {类} str (object='@w{'})

@deffnx {类} str (object=b'@w{'}, encoding='utf-8', errors='strict')

返回一个 @ref{206,,str} 版本的 @emph{object} 。有关详细信息，请参阅 @ref{206,,str()} 。

@code{str} 是内置字符串 @ref{1033,,class} 。更多关于字符串的信息查看 @ref{1386,,文本序列类型 --- str}。
@end deffn

@geindex sum() (內置函数)
@anchor{library/functions sum}@anchor{31d}
@deffn {函数} sum (iterable, /, start=0)

从 @emph{start} 开始自左向右对 @emph{iterable} 的项求和并返回总计值。 @emph{iterable} 的项通常为数字，而 start 值则不允许为字符串。

对某些用例来说，存在 @ref{31d,,sum()} 的更好替代。 拼接字符串序列的更好更快方式是调用 @code{'@w{'}.join(sequence)}。 要以扩展精度对浮点值求和，请参阅 @ref{e0c,,math.fsum()}。 要拼接一系列可迭代对象，请考虑使用 @ref{1768,,itertools.chain()}。


在 3.8 版更改: @emph{start} 形参可用关键字参数形式来指定。

@end deffn

@geindex super() (內置函数)
@anchor{library/functions super}@anchor{5e6}
@deffn {函数} super ([type[, object-or-type]])

返回一个代理对象，它会将方法调用委托给 @emph{type} 的父类或兄弟类。 这对于访问已在类中被重载的继承方法很有用。

@emph{object-or-type} 确定用于搜索的 @ref{1769,,method resolution order}。 搜索会从 @emph{type} 之后的类开始。

举例来说，如果 @emph{object-or-type} 的 @ref{176a,,__mro__} 为 @code{D -> B -> C -> A -> object} 并且 @emph{type} 的值为 @code{B}，则 @ref{5e6,,super()} 将会搜索 @code{C -> A -> object}。

@emph{object-or-type} 的 @ref{176a,,__mro__} 属性列出了 @ref{554,,getattr()} 和 @ref{5e6,,super()} 所共同使用的方法解析搜索顺序。 该属性是动态的，可以在任何继承层级结构发生更新的时候被改变。

如果省略第二个参数，则返回的超类对象是未绑定的。 如果第二个参数为一个对象，则 @code{isinstance(obj, type)} 必须为真值。 如果第二个参数为一个类型，则 @code{issubclass(type2, type)} 必须为真值（这适用于类方法）。

@emph{super} 有两个典型用例。 在具有单继承的类层级结构中，@emph{super} 可用来引用父类而不必显式地指定它们的名称，从而令代码更易维护。 这种用法与其他编程语言中 @emph{super} 的用法非常相似。

第二个用例是在动态执行环境中支持协作多重继承。 此用例为 Python 所独有而不存在于静态编码语言或仅支持单继承的语言当中。 这使用实现“菱形图”成为可能，即有多个基类实现相同的方法。 好的设计强制要求这样的方法在每个情况下都具有相同的调用签名（因为调用顺序是在运行时确定的，也因为这个顺序要适应类层级结构的更改，还因为这个顺序可能包括在运行时之前未知的兄弟类）。

对于以上两个用例，典型的超类调用看起来是这样的:

@example
class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)
@end example

除了方法查找之外，@ref{5e6,,super()} 也可用于属性查找。 一个可能的应用场合是在上级或同级类中调用 @ref{15a8,,描述器}。

请注意 @ref{5e6,,super()} 是作为显式加点属性查找的绑定过程的一部分来实现的，例如 @code{super().__getitem__(name)}。 它做到这一点是通过实现自己的 @ref{552,,__getattribute__()} 方法，这样就能以可预测的顺序搜索类，并且支持协作多重继承。 对应地，@ref{5e6,,super()} 在像 @code{super()[name]} 这样使用语句或操作符进行隐式查找时则未被定义。

还要注意的是，除了零个参数的形式以外，@ref{5e6,,super()} 并不限于在方法内部使用。 两个参数的形式明确指定参数并进行相应的引用。 零个参数的形式仅适用于类定义内部，因为编译器需要填入必要的细节以正确地检索到被定义的类，还需要让普通方法访问当前实例。

对于有关如何使用 @ref{5e6,,super()} 来如何设计协作类的实用建议，请参阅 使用 super() 的指南@footnote{https://rhettinger.wordpress.com/2011/05/26/super-considered-super/}。
@end deffn
@anchor{library/functions func-tuple}@anchor{1744}

@deffn {类} tuple ([iterable])

虽然被称为函数，但 @ref{1a2,,tuple} 实际上是一个不可变的序列类型，参见在 @ref{176b,,元组} 与 @ref{13d3,,序列类型 --- list@comma{} tuple@comma{} range} 中的文档说明。
@end deffn

@geindex type (內置类)
@anchor{library/functions type}@anchor{709}
@deffn {类} type (object)

@deffnx {类} type (name, bases, dict, **kwds)

@geindex 对象; type

传入一个参数时，返回 @emph{object} 的类型。 返回值是一个 type 对象，通常与 @ref{ed4,,object.__class__} 所返回的对象相同。

推荐使用 @ref{55a,,isinstance()} 内置函数来检测对象的类型，因为它会考虑子类的情况。

传入三个参数时，返回一个新的 type 对象。 这在本质上是 @ref{d3a,,class} 语句的一种动态形式，@emph{name} 字符串即类名并会成为 @ref{d37,,__name__} 属性；@emph{bases} 元组包含基类并会成为 @ref{ed3,,__bases__} 属性；如果为空则会添加所有类的终极基类 @ref{3da,,object}。 @emph{dict} 字典包含类主体的属性和方法定义；它在成为 @ref{5fe,,__dict__} 属性之前可能会被拷贝或包装。 下面两条语句会创建相同的 @ref{709,,type} 对象:

@example
>>> class X:
...     a = 1
...
>>> X = type('X', (), dict(a=1))
@end example

另请参阅 @ref{176c,,类型对象}。

提供给三参数形式的关键字参数会被传递给适当的元类机制 (通常为 @ref{5e5,,__init_subclass__()})，相当于类定义中关键字 (除了 @emph{metaclass}) 的行为方式。

另请参阅 @ref{5e8,,自定义类创建}。


在 3.6 版更改: @ref{709,,type} 的子类如果未重载 @code{type.__new__}，将不再能使用一个参数的形式来获取对象的类型。

@end deffn

@geindex vars() (內置函数)
@anchor{library/functions vars}@anchor{11b6}
@deffn {函数} vars ([object])

返回模块、类、实例或任何其它具有 @ref{5fe,,__dict__} 属性的对象的 @ref{5fe,,__dict__} 属性。

模块和实例这样的对象具有可更新的 @ref{5fe,,__dict__} 属性；但是，其它对象的 @ref{5fe,,__dict__} 属性可能会设为限制写入（例如，类会使用 @ref{b97,,types.MappingProxyType} 来防止直接更新字典）。

不带参数时，@ref{11b6,,vars()} 的行为类似 @ref{55f,,locals()}。 请注意，locals 字典仅对于读取起作用，因为对 locals 字典的更新会被忽略。

如果指定了一个对象但它没有 @ref{5fe,,__dict__} 属性（例如，当它所属的类定义了 @ref{ef7,,__slots__} 属性时）则会引发 @ref{1ff,,TypeError} 异常。
@end deffn

@geindex zip() (內置函数)
@anchor{library/functions zip}@anchor{d04}
@deffn {函数} zip (*iterables)

创建一个聚合了来自每个可迭代对象中的元素的迭代器。

返回一个元组的迭代器，其中的第 @emph{i} 个元组包含来自每个参数序列或可迭代对象的第 @emph{i} 个元素。 当所输入可迭代对象中最短的一个被耗尽时，迭代器将停止迭代。 当只有一个可迭代对象参数时，它将返回一个单元组的迭代器。 不带参数时，它将返回一个空迭代器。 相当于:

@example
def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)
@end example

函数会保证可迭代对象按从左至右的顺序被求值。 使得可以通过 @code{zip(*[iter(s)]*n)} 这样的惯用形式将一系列数据聚类为长度为 n 的分组。 这将重复 @emph{同样的} 迭代器 @code{n} 次，以便每个输出的元组具有第 @code{n} 次调用该迭代器的结果。 它的作用效果就是将输入拆分为长度为 n 的数据块。

当你不用关心较长可迭代对象末尾不匹配的值时，则 @ref{d04,,zip()} 只须使用长度不相等的输入即可。 如果那些值很重要，则应改用 @ref{d03,,itertools.zip_longest()}。

@ref{d04,,zip()} 与 @code{*} 运算符相结合可以用来拆解一个列表:

@example
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
@end example
@end deffn

@geindex __import__() (內置函数)
@anchor{library/functions __import__}@anchor{16b}
@deffn {函数} __import__ (name, globals=None, locals=None, fromlist=(), level=0)

@geindex 语句; import
@geindex 模块; imp

@cartouche
@quotation 注解 
与 @ref{bef,,importlib.import_module()} 不同，这是一个日常 Python 编程中不需要用到的高级函数。
@end quotation
@end cartouche

此函数会由 @ref{cef,,import} 语句发起调用。 它可以被替换 (通过导入 @ref{12,,builtins} 模块并赋值给 @code{builtins.__import__}) 以便修改 @code{import} 语句的语义，但是 @strong{强烈} 不建议这样做，因为使用导入钩子 (参见 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}) 通常更容易实现同样的目标，并且不会导致代码问题，因为许多代码都会假定所用的是默认实现。 同样也不建议直接使用 @ref{16b,,__import__()} 而应该用 @ref{bef,,importlib.import_module()}。

该函数会导入 @emph{name} 模块，有可能使用给定的 @emph{globals} 和 @emph{locals} 来确定如何在包的上下文中解读名称。 @emph{fromlist} 给出了应该从由 @emph{name} 指定的模块导入对象或子模块的名称。 标准实现完全不使用其 @emph{locals} 参数，而仅使用 @emph{globals} 参数来确定 @ref{cef,,import} 语句的包上下文。

@emph{level} 指定是使用绝对还是相对导入。 @code{0} (默认值) 意味着仅执行绝对导入。 @emph{level} 为正数值表示相对于模块调用 @ref{16b,,__import__()} 的目录，将要搜索的父目录层数 (详情参见 
@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328})。

当 @emph{name} 变量的形式为 @code{package.module} 时，通常将会返回最高层级的包（第一个点号之前的名称），而 @emph{不是} 以 @emph{name} 命名的模块。 但是，当给出了非空的 @emph{fromlist} 参数时，则将返回以 @emph{name} 命名的模块。

例如，语句 @code{import spam} 的结果将为与以下代码作用相同的字节码:

@example
spam = __import__('spam', globals(), locals(), [], 0)
@end example

语句 @code{import spam.ham} 的结果将为以下调用:

@example
spam = __import__('spam.ham', globals(), locals(), [], 0)
@end example

请注意在这里 @ref{16b,,__import__()} 是如何返回顶层模块的，因为这是通过 @ref{cef,,import} 语句被绑定到特定名称的对象。

另一方面，语句 @code{from spam.ham import eggs, sausage as saus} 的结果将为

@example
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
@end example

在这里， @code{spam.ham} 模块会由 @ref{16b,,__import__()} 返回。 要导入的对象将从此对象中提取并赋值给它们对应的名称。

如果您只想按名称导入模块（可能在包中），请使用 @ref{bef,,importlib.import_module()}


在 3.3 版更改: @emph{level} 的值不再支持负数（默认值也修改为0）。



在 3.9 版更改: 当使用了命令行参数 @ref{231,,-E} 或 @ref{232,,-I} 时，环境变量 
@geindex PYTHONCASEOK
@geindex 环境变量; PYTHONCASEOK
@ref{233,,PYTHONCASEOK} 现在将被忽略。

@end deffn

@node 内置常量,内置类型,内置函数,Python 标准库
@anchor{library/constants doc}@anchor{176d}@anchor{library/constants built-in-constants}@anchor{176e}@anchor{library/constants built-in-consts}@anchor{176f}
@section 内置常量


有少数的常量存在于内置命名空间中。 它们是：

@geindex False (內置变量)
@anchor{library/constants False}@anchor{497}
@deffn {数据} False

@ref{2c4,,bool} 类型的假值。 给 @code{False} 赋值是非法的并会引发 @ref{562,,SyntaxError}。
@end deffn

@geindex True (內置变量)
@anchor{library/constants True}@anchor{59c}
@deffn {数据} True

@ref{2c4,,bool} 类型的真值。 给 @code{True} 赋值是非法的并会引发 @ref{562,,SyntaxError}。
@end deffn

@geindex None (內置变量)
@anchor{library/constants None}@anchor{204}
@deffn {数据} None

@code{NoneType} 类型的唯一值。 @code{None} 经常用于表示缺少值，当因为默认参数未传递给函数时。 给 @code{None} 赋值是非法的并会引发 @ref{562,,SyntaxError}。
@end deffn

@geindex NotImplemented (內置变量)
@anchor{library/constants NotImplemented}@anchor{203}
@deffn {数据} NotImplemented

双目运算特殊方法（如 @ref{454,,__eq__()}, @ref{d06,,__lt__()}, @ref{15c4,,__add__()}, @ref{15d6,,__rsub__()} 等）应返回的特殊值，用于表示运算没有针对其他类型的实现；也可由原地双目运算特殊方法（如 @ref{15c8,,__imul__()}, @ref{15e6,,__iand__()} 等）出于同样的目的而返回。 它不应被作为布尔值来解读。

@cartouche
@quotation 注解 
当二进制（或就地）方法返回 @code{NotImplemented} 时，解释器将尝试对另一种类型（或其他一些回滚操作，取决于运算符）的反射操作。 如果所有尝试都返回 @code{NotImplemented}，则解释器将引发适当的异常。 错误返回的 @code{NotImplemented} 将导致误导性错误消息或返回到 Python 代码中的 @code{NotImplemented} 值。

参见 @ref{1583,,实现算术运算} 为例。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
@code{NotImplementedError} 和 @code{NotImplemented} 不可互换，即使它们有相似的名称和用途。 有关何时使用它的详细信息，请参阅 @ref{70e,,NotImplementedError}。
@end quotation
@end cartouche


在 3.9 版更改: 作为布尔值来解读 @code{NotImplemented} 已被弃用。 虽然它目前会被解读为真值，但将同时发出 @ref{15a,,DeprecationWarning}。 它将在未来的 Python 版本中引发 @ref{1ff,,TypeError}。

@end deffn

@geindex ...; ellipsis literal

@geindex Ellipsis (內置变量)
@anchor{library/constants Ellipsis}@anchor{1770}
@deffn {数据} Ellipsis

与省略号文字字面 “@code{...}” 相同。 特殊值主要与用户定义的容器数据类型的扩展切片语法结合使用。
@end deffn

@geindex __debug__ (內置变量)
@anchor{library/constants __debug__}@anchor{1180}
@deffn {数据} __debug__

如果 Python 没有以 @ref{788,,-O} 选项启动，则此常量为真值。 另请参见 @ref{240,,assert} 语句。
@end deffn

@cartouche
@quotation 注解 
变量名 @ref{204,,None}，@ref{497,,False}，@ref{59c,,True} 和 @ref{1180,,__debug__} 无法重新赋值（赋值给它们，即使是属性名，将引发 @ref{562,,SyntaxError} ），所以它们可以被认为是“真正的”常数。
@end quotation
@end cartouche

@menu
* 由 site 模块添加的常量:: 

@end menu

@node 由 site 模块添加的常量,,,内置常量
@anchor{library/constants constants-added-by-the-site-module}@anchor{1771}
@subsection 由 @code{site} 模块添加的常量


@ref{eb,,site} 模块（在启动期间自动导入，除非给出 @ref{c00,,-S} 命令行选项）将几个常量添加到内置命名空间。 它们对交互式解释器 shell 很有用，并且不应在程序中使用。

@geindex quit (內置变量)
@geindex exit (內置变量)
@anchor{library/constants quit}@anchor{1772}
@deffn {数据} quit (code=None)
@anchor{library/constants exit}@anchor{1773}
@deffnx {数据} exit (code=None)

当打印此对象时，会打印出一条消息，例如“Use quit() or Ctrl-D (i.e. EOF) to exit”，当调用此对象时，将使用指定的退出代码来引发 @ref{6fd,,SystemExit}。
@end deffn

@geindex copyright (內置变量)
@geindex credits (內置变量)
@anchor{library/constants copyright}@anchor{1774}
@deffn {数据} copyright
@anchor{library/constants credits}@anchor{1775}
@deffnx {数据} credits

打印或调用的对象分别打印版权或作者的文本。
@end deffn

@geindex license (內置变量)
@anchor{library/constants license}@anchor{1776}
@deffn {数据} license

当打印此对象时，会打印出一条消息“Type license() to see the full license text”，当调用此对象时，将以分页形式显示完整的许可证文本（每次显示一屏）。
@end deffn

@c XXX: reference/datamodel and this have quite a few overlaps!

@node 内置类型,内置异常,内置常量,Python 标准库
@anchor{library/stdtypes doc}@anchor{1777}@anchor{library/stdtypes bltin-types}@anchor{1778}@anchor{library/stdtypes built-in-types}@anchor{1779}
@section 内置类型


以下部分描述了解释器中内置的标准类型。

@geindex built-in; types

主要内置类型有数字、序列、映射、类、实例和异常。

有些多项集类是可变的。 它们用于添加、移除或重排其成员的方法将原地执行，并不返回特定的项，绝对不会返回多项集实例自身而是返回 @code{None}。

有些操作受多种对象类型的支持；特别地，实际上所有对象都可以比较是否相等、检测逻辑值，以及转换为字符串（使用 @ref{8c3,,repr()} 函数或略有差异的 @ref{206,,str()} 函数）。 后一个函数是在对象由 @ref{97a,,print()} 函数输出时被隐式地调用的。

@menu
* 逻辑值检测:: 
* 布尔运算: 布尔运算 --- and or not. and, or, not
* 比较:: 
* 数字类型: 数字类型 --- int float complex. int, float, complex
* 迭代器类型:: 
* 序列类型: 序列类型 --- list tuple range. list, tuple, range
* 文本序列类型: 文本序列类型 --- str. str
* 二进制序列类型: 二进制序列类型 --- bytes bytearray memoryview. bytes, bytearray, memoryview
* 集合类型: 集合类型 --- set frozenset. set, frozenset
* 映射类型: 映射类型 --- dict. dict
* 上下文管理器类型:: 
* GenericAlias 类型:: 
* 其他内置类型:: 
* 特殊属性:: 
* Integer string conversion length limitation:: 

@end menu

@node 逻辑值检测,布尔运算 --- and or not,,内置类型
@anchor{library/stdtypes truth}@anchor{1748}@anchor{library/stdtypes truth-value-testing}@anchor{177a}
@subsection 逻辑值检测


@geindex 语句; if
@geindex 语句; while
@geindex truth; value
@geindex Boolean; operations
@geindex false

任何对象都可以进行逻辑值的检测，以便在 @ref{eb3,,if} 或 @ref{1390,,while} 作为条件或是作为下文所述布尔运算的操作数来使用。

@geindex true

一个对象在默认情况下均被视为真值，除非当该对象被调用时其所属类定义了 @ref{d38,,__bool__()} 方法且返回 @code{False} 或是定义了 @ref{e98,,__len__()} 方法且返回零。 @footnote{@w{(1)} 
有关这些特殊方法的额外信息可参看 Python 参考指南 (@ref{1597,,基本定制})。
}  下面基本完整地列出了会被视为假值的内置对象:

@quotation

@geindex None (Built-in object)
@geindex False (Built-in object)
@end quotation


@itemize *

@item 
被定义为假值的常量: @code{None} 和 @code{False}。

@item 
任何数值类型的零: @code{0}, @code{0.0}, @code{0j}, @code{Decimal(0)}, @code{Fraction(0, 1)}

@item 
空的序列和多项集: @code{'@w{'}}, @code{()}, @code{[]}, @code{@{@}}, @code{set()}, @code{range(0)}
@end itemize

@geindex 运算符; or
@geindex 运算符; and
@geindex False
@geindex True

产生布尔值结果的运算和内置函数总是返回 @code{0} 或 @code{False} 作为假值，@code{1} 或 @code{True} 作为真值，除非另行说明。 （重要例外：布尔运算 @code{or} 和 @code{and} 总是返回其中一个操作数。）

@node 布尔运算 --- and or not,比较,逻辑值检测,内置类型
@anchor{library/stdtypes boolean}@anchor{177b}@anchor{library/stdtypes boolean-operations-and-or-not}@anchor{177c}
@subsection 布尔运算 --- @code{and}, @code{or}, @code{not}


@geindex Boolean; operations

这些属于布尔运算，按优先级升序排列:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

运算

@tab

结果

@tab

注释

@item

@code{x or y}

@tab

if @emph{x} is false, then @emph{y}, else
@emph{x}

@tab

(1)

@item

@code{x and y}

@tab

if @emph{x} is false, then @emph{x}, else
@emph{y}

@tab

(2)

@item

@code{not x}

@tab

if @emph{x} is false, then @code{True},
else @code{False}

@tab

(3)

@end multitable


@geindex 运算符; and
@geindex 运算符; or
@geindex 运算符; not

注释:


@enumerate 

@item 
这是个短路运算符，因此只有在第一个参数为假值时才会对第二个参数求值。

@item 
这是个短路运算符，因此只有在第一个参数为真值时才会对第二个参数求值。

@item 
@code{not} 的优先级比非布尔运算符低，因此 @code{not a == b} 会被解读为 @code{not (a == b)} 而 @code{a == not b} 会引发语法错误。
@end enumerate

@node 比较,数字类型 --- int float complex,布尔运算 --- and or not,内置类型
@anchor{library/stdtypes comparisons}@anchor{177d}@anchor{library/stdtypes stdcomparisons}@anchor{177e}
@subsection 比较


@geindex chaining; comparisons
@geindex operator; comparison
@geindex 运算符; ==
@geindex 运算符; < (less)
@geindex 运算符; <=
@geindex 运算符; > (greater)
@geindex 运算符; >=
@geindex 运算符; !=
@geindex 运算符; is
@geindex 运算符; is not

在 Python 中有八种比较运算符。 它们的优先级相同（比布尔运算的优先级高）。 比较运算可以任意串连；例如，@code{x < y <= z} 等价于 @code{x < y and y <= z}，前者的不同之处在于 @emph{y} 只被求值一次（但在两种情况下当 @code{x < y} 结果为假值时 @emph{z} 都不会被求值）。

此表格汇总了比较运算:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

含义

@item

@code{<}

@tab

严格小于

@item

@code{<=}

@tab

小于或等于

@item

@code{>}

@tab

严格大于

@item

@code{>=}

@tab

大于或等于

@item

@code{==}

@tab

等于

@item

@code{!=}

@tab

不等于

@item

@code{is}

@tab

对象标识

@item

@code{is not}

@tab

否定的对象标识

@end multitable


@geindex object; numeric
@geindex objects; comparing

除不同的数字类型外，不同类型的对象不能进行相等比较。@code{==} 运算符总有定义，但对于某些对象类型（例如，类对象），它等于 @ref{1580,,is} 。其他 @code{<}、@code{<=}、@code{>} 和 @code{>=} 运算符仅在有意义的地方定义。例如，当参与比较的参数之一为复数时，它们会抛出 @ref{1ff,,TypeError} 异常。

@geindex __eq__() (instance method)
@geindex __ne__() (instance method)
@geindex __lt__() (instance method)
@geindex __le__() (instance method)
@geindex __gt__() (instance method)
@geindex __ge__() (instance method)

具有不同标识的类的实例比较结果通常为不相等，除非类定义了 @ref{454,,__eq__()} 方法。

一个类的实例不能与相同类的其他实例或其他类型的对象进行排序，除非定义该类定义了足够多的方法，包括 @ref{d06,,__lt__()}, @ref{d70,,__le__()}, @ref{d71,,__gt__()} 以及 @ref{d72,,__ge__()} (而如果你想实现常规意义上的比较操作，通常只要有 @ref{d06,,__lt__()} 和 @ref{454,,__eq__()} 就可以了)。

@ref{1580,,is} 和 @ref{16b0,,is not} 运算符无法自定义；并且它们可以被应用于任意两个对象而不会引发异常。

@geindex 运算符; in
@geindex 运算符; not in

还有两种具有相同语法优先级的运算 @ref{179,,in} 和 @ref{15ca,,not in}，它们被 @ref{c84,,iterable} 或实现了 @ref{df6,,__contains__()} 方法的类型所支持。

@node 数字类型 --- int float complex,迭代器类型,比较,内置类型
@anchor{library/stdtypes numeric-types-int-float-complex}@anchor{177f}@anchor{library/stdtypes typesnumeric}@anchor{1382}
@subsection 数字类型 --- @code{int}, @code{float}, @code{complex}


@geindex 对象; numeric
@geindex 对象; Boolean
@geindex 对象; integer
@geindex 对象; floating point
@geindex 对象; complex number
@geindex C; language

存在三种不同的数字类型: @emph{整数}, @emph{浮点数} 和 @emph{复数}。 此外，布尔值属于整数的子类型。 整数具有无限的精度。 浮点数通常使用 C 中的 @code{double} 来实现；有关你的程序运行所在机器上浮点数的精度和内部表示法可在 @ref{1145,,sys.float_info} 中查看。 复数包含实部和虚部，分别以一个浮点数表示。 要从一个复数 @emph{z} 中提取这两个部分，可使用 @code{z.real} 和 @code{z.imag}。 （标准库包含附加的数字类型，如表示有理数的 @ref{2c5,,fractions.Fraction} 以及以用户定制精度表示浮点数的 @ref{2c7,,decimal.Decimal}。）

@geindex numeric; literals
@geindex integer; literals
@geindex floating point; literals
@geindex complex number; literals
@geindex hexadecimal; literals
@geindex octal; literals
@geindex binary; literals

数字是由数字字面值或内置函数与运算符的结果来创建的。 不带修饰的整数字面值（包括十六进制、八进制和二进制数）会生成整数。 包含小数点或幂运算符的数字字面值会生成浮点数。 在数字字面值末尾加上 @code{'j'} 或 @code{'J'} 会生成虚数（实部为零的复数），你可以将其与整数或浮点数相加来得到具有实部和虚部的复数。

@geindex arithmetic
@geindex 內置函数; int
@geindex 內置函数; float
@geindex 內置函数; complex
@geindex operator; + (plus)
@geindex + (plus); unary operator
@geindex + (plus); binary operator
@geindex operator; - (minus)
@geindex - (minus); unary operator
@geindex - (minus); binary operator
@geindex 运算符; * (asterisk)
@geindex 运算符; / (slash)
@geindex 运算符; //
@geindex 运算符; % (percent)
@geindex 运算符; **

Python 完全支持混合运算：当一个二元算术运算符的操作数有不同数值类型时，"较窄"类型的操作数会拓宽到另一个操作数的类型，其中整数比浮点数窄，浮点数比复数窄。不同类型的数字之间的比较，同比较这些数字的精确值一样。@footnote{@w{(2)} 
作为结果，列表 @code{[1, 2]} 与 @code{[1.0, 2.0]} 是相等的，元组的情况也类似。
}

构造函数 @ref{205,,int()}、 @ref{1fe,,float()} 和 @ref{2c8,,complex()} 可以用来构造特定类型的数字。

所有数字类型（复数除外）都支持下列运算（有关运算优先级，请参阅：@ref{16c9,,运算符优先级}）:


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@tab

注释

@tab

完整文档

@item

@code{x + y}

@tab

@emph{x} 和 @emph{y} 的和

@tab

@tab

@item

@code{x - y}

@tab

@emph{x} 和 @emph{y} 的差

@tab

@tab

@item

@code{x * y}

@tab

@emph{x} 和 @emph{y} 的乘积

@tab

@tab

@item

@code{x / y}

@tab

@emph{x} 和 @emph{y} 的商

@tab

@tab

@item

@code{x // y}

@tab

@emph{x} 和 @emph{y} 的商数

@tab

(1)

@tab

@item

@code{x % y}

@tab

@code{x / y} 的余数

@tab

(2)

@tab

@item

@code{-x}

@tab

@emph{x} 取反

@tab

@tab

@item

@code{+x}

@tab

@emph{x} 不变

@tab

@tab

@item

@code{abs(x)}

@tab

@emph{x} 的绝对值或大小

@tab

@tab

@ref{1424,,abs()}

@item

@code{int(x)}

@tab

将 @emph{x} 转换为整数

@tab

(3)(6)

@tab

@ref{205,,int()}

@item

@code{float(x)}

@tab

将 @emph{x} 转换为浮点数

@tab

(4)(6)

@tab

@ref{1fe,,float()}

@item

@code{complex(re, im)}

@tab

一个带有实部 @emph{re} 和虚部 @emph{im} 的复数。@emph{im} 默认为0。

@tab

(6)

@tab

@ref{2c8,,complex()}

@item

@code{c.conjugate()}

@tab

复数 @emph{c} 的共轭

@tab

@tab

@item

@code{divmod(x, y)}

@tab

@code{(x // y, x % y)}

@tab

(2)

@tab

@ref{294,,divmod()}

@item

@code{pow(x, y)}

@tab

@emph{x} 的 @emph{y} 次幂

@tab

(5)

@tab

@ref{2d6,,pow()}

@item

@code{x ** y}

@tab

@emph{x} 的 @emph{y} 次幂

@tab

(5)

@tab

@end multitable


@geindex operations on; numeric; types
@geindex conjugate() (complex number method)

注释:


@enumerate 

@item 
也称为整数除法。 结果值是一个整数，但结果的类型不一定是 int。 运算结果总是向负无穷的方向舍入: @code{1//2} 为 @code{0}, @code{(-1)//2} 为 @code{-1}, @code{1//(-2)} 为 @code{-1} 而 @code{(-1)//(-2)} 为 @code{0}。

@item 
不可用于复数。 而应在适当条件下使用 @ref{1424,,abs()} 转换为浮点数。

@item 
@geindex 模块; math
@geindex floor() (in module math)
@geindex ceil() (in module math)
@geindex trunc() (in module math)
@geindex numeric; conversions
@geindex C; language

从浮点数转换为整数会被舍入或是像在 C 语言中一样被截断；请参阅 @ref{dfa,,math.floor()} 和 @ref{dfb,,math.ceil()} 函数查看转换的完整定义。

@item 
float 也接受字符串 "nan" 和附带可选前缀 "+" 或 "-" 的 "inf" 分别表示非数字 (NaN) 以及正或负无穷。

@item 
Python 将 @code{pow(0, 0)} 和 @code{0 ** 0} 定义为 @code{1}，这是编程语言的普遍做法。

@item 
接受的数字字面值包括数码 @code{0} 到 @code{9} 或任何等效的 Unicode 字符（具有 @code{Nd} 特征属性的代码点）。

请参阅 @indicateurl{https://www.unicode.org/Public/13.0.0/ucd/extracted/DerivedNumericType.txt} 查看具有 @code{Nd} 特征属性的代码点的完整列表。
@end enumerate

所有 @ref{1586,,numbers.Real} 类型 (@ref{205,,int} 和 @ref{1fe,,float}) 还包括下列运算:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@item

@ref{dfc,,math.trunc(x)}

@tab

@emph{x} 截断为 @ref{1585,,Integral}

@item

@ref{d3d,,round(x[@comma{} n])}

@tab

@emph{x} 舍入到 @emph{n} 位小数，半数值会舍入到偶数。 如果省略 @emph{n}，则默认为 0。

@item

@ref{dfa,,math.floor(x)}

@tab

<= @emph{x} 的最大 @ref{1585,,Integral}

@item

@ref{dfb,,math.ceil(x)}

@tab

>= @emph{x} 的最小 @ref{1585,,Integral}

@end multitable


有关更多的数字运算请参阅 @ref{b1,,math} 和 @ref{18,,cmath} 模块。

@c XXXJH exceptions: overflow (when? what operations?) zerodivision

@menu
* 整数类型的按位运算:: 
* 整数类型的附加方法:: 
* 浮点类型的附加方法:: 
* 数字类型的哈希运算:: 

@end menu

@node 整数类型的按位运算,整数类型的附加方法,,数字类型 --- int float complex
@anchor{library/stdtypes bitstring-ops}@anchor{1780}@anchor{library/stdtypes bitwise-operations-on-integer-types}@anchor{1781}
@subsubsection 整数类型的按位运算


@geindex operations on; integer; types
@geindex bitwise; operations
@geindex shifting; operations
@geindex masking; operations
@geindex 运算符; | (vertical bar)
@geindex 运算符; ^ (caret)
@geindex 运算符; & (ampersand)
@geindex 运算符; <<
@geindex 运算符; >>
@geindex 运算符; ~ (tilde)

按位运算只对整数有意义。 计算按位运算的结果，就相当于使用无穷多个二进制符号位对二的补码执行操作。

二进制按位运算的优先级全都低于数字运算，但又高于比较运算；一元运算 @code{~} 具有与其他一元算术运算 (@code{+} and @code{-}) 相同的优先级。

此表格是以优先级升序排序的按位运算列表:


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@tab

注释

@item

@code{x | y}

@tab

@emph{x} 和 @emph{y} 按位 @emph{或}

@tab

(4)

@item

@code{x ^ y}

@tab

@emph{x} 和 @emph{y} 按位 @emph{异或}

@tab

(4)

@item

@code{x & y}

@tab

@emph{x} 和 @emph{y} 按位 @emph{与}

@tab

(4)

@item

@code{x << n}

@tab

@emph{x} 左移 @emph{n} 位

@tab

(1)(2)

@item

@code{x >> n}

@tab

@emph{x} 右移 @emph{n} 位

@tab

(1)(3)

@item

@code{~x}

@tab

@emph{x} 逐位取反

@tab

@end multitable


注释:


@enumerate 

@item 
负的移位数是非法的，会导致引发 @ref{16d,,ValueError}。

@item 
左移 @emph{n} 位等价于乘以 @code{pow(2, n)} 。

@item 
右移 @emph{n} 位等价于除以 @code{pow(2, n)} ，作向下取整除法。

@item 
使用带有至少一个额外符号扩展位的有限个二进制补码表示（有效位宽度为 @code{1 + max(x.bit_length(), y.bit_length())} 或以上）执行这些计算就足以获得相当于有无数个符号位时的同样结果。
@end enumerate

@node 整数类型的附加方法,浮点类型的附加方法,整数类型的按位运算,数字类型 --- int float complex
@anchor{library/stdtypes additional-methods-on-integer-types}@anchor{1782}
@subsubsection 整数类型的附加方法


int 类型实现了 @ref{1585,,numbers.Integral} @ref{c0e,,abstract base class}。 此外，它还提供了其他几个方法:

@geindex bit_length() (int 方法)
@anchor{library/stdtypes int bit_length}@anchor{1783}
@deffn {方法} int.bit_length ()

返回以二进制表示一个整数所需要的位数，不包括符号位和前面的零:

@example
>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6
@end example

更准确地说，如果 @code{x} 非零，则 @code{x.bit_length()} 是使得 @code{2**(k-1) <= abs(x) < 2**k} 的唯一正整数 @code{k}。 同样地，当 @code{abs(x)} 小到足以具有正确的舍入对数时，则 @code{k = 1 + int(log(abs(x), 2))}。 如果 @code{x} 为零，则 @code{x.bit_length()} 返回 @code{0}。

等价于:

@example
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
@end example


3.1 新版功能.

@end deffn

@geindex to_bytes() (int 方法)
@anchor{library/stdtypes int to_bytes}@anchor{1784}
@deffn {方法} int.to_bytes (length, byteorder, *, signed=False)

返回表示一个整数的字节数组。

@example
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
@end example

整数会使用 @emph{length} 个字节来表示。 如果整数不能用给定的字节数来表示则会引发 @ref{a4a,,OverflowError}。

@emph{byteorder} 参数确定用于表示整数的字节顺序。 如果 @emph{byteorder} 为 @code{"big"}，则最高位字节放在字节数组的开头。 如果 @emph{byteorder} 为 @code{"little"}，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生字节顺序，请使用 @ref{1785,,sys.byteorder} 作为字节顺序值。

@emph{signed} 参数确定是否使用二的补码来表示整数。 如果 @emph{signed} 为 @code{False} 并且给出的是负整数，则会引发 @ref{a4a,,OverflowError}。 @emph{signed} 的默认值为 @code{False}。


3.2 新版功能.

@end deffn

@geindex from_bytes() (int 类方法)
@anchor{library/stdtypes int from_bytes}@anchor{1786}
@deffn {方法} classmethod int.from_bytes (bytes, byteorder, *, signed=False)

返回由给定字节数组所表示的整数。

@example
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
@end example

@emph{bytes} 参数必须为一个 @ref{6e9,,bytes-like object} 或是生成字节的可迭代对象。

@emph{byteorder} 参数确定用于表示整数的字节顺序。 如果 @emph{byteorder} 为 @code{"big"}，则最高位字节放在字节数组的开头。 如果 @emph{byteorder} 为 @code{"little"}，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生字节顺序，请使用 @ref{1785,,sys.byteorder} 作为字节顺序值。

@emph{signed} 参数指明是否使用二的补码来表示整数。


3.2 新版功能.

@end deffn

@geindex as_integer_ratio() (int 方法)
@anchor{library/stdtypes int as_integer_ratio}@anchor{2c6}
@deffn {方法} int.as_integer_ratio ()

返回一对整数，其比率正好等于原整数并且分母为正数。 整数的比率总是用这个整数本身作为分子，@code{1} 作为分母。


3.8 新版功能.

@end deffn

@node 浮点类型的附加方法,数字类型的哈希运算,整数类型的附加方法,数字类型 --- int float complex
@anchor{library/stdtypes additional-methods-on-float}@anchor{1787}
@subsubsection 浮点类型的附加方法


float 类型实现了 @ref{1586,,numbers.Real} @ref{c0e,,abstract base class}。 float 还具有以下附加方法。

@geindex as_integer_ratio() (float 方法)
@anchor{library/stdtypes float as_integer_ratio}@anchor{1488}
@deffn {方法} float.as_integer_ratio ()

返回一对整数，其比率正好等于原浮点数并且分母为正数。 无穷大会引发 @ref{a4a,,OverflowError} 而 NaN 则会引发 @ref{16d,,ValueError}。
@end deffn

@geindex is_integer() (float 方法)
@anchor{library/stdtypes float is_integer}@anchor{1788}
@deffn {方法} float.is_integer ()

如果 float 实例可用有限位整数表示则返回 @code{True}，否则返回 @code{False}:

@example
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
@end example
@end deffn

两个方法均支持与十六进制数字符串之间的转换。 由于 Python 浮点数在内部存储为二进制数，因此浮点数与 @emph{十进制数} 字符串之间的转换往往会导致微小的舍入错误。 而十六进制数字符串却允许精确地表示和描述浮点数。 这在进行调试和数值工作时非常有用。

@geindex hex() (float 方法)
@anchor{library/stdtypes float hex}@anchor{1489}
@deffn {方法} float.hex ()

以十六进制字符串的形式返回一个浮点数表示。 对于有限浮点数，这种表示法将总是包含前导的 @code{0x} 和尾随的 @code{p} 加指数。
@end deffn

@geindex fromhex() (float 类方法)
@anchor{library/stdtypes float fromhex}@anchor{1789}
@deffn {方法} classmethod float.fromhex (s)

返回以十六进制字符串 @emph{s} 表示的浮点数的类方法。 字符串 @emph{s} 可以带有前导和尾随的空格。
@end deffn

请注意 @ref{1489,,float.hex()} 是实例方法，而 @ref{1789,,float.fromhex()} 是类方法。

十六进制字符串采用的形式为:

@example
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
@end example

可选的 @code{sign} 可以是 @code{+} 或 @code{-}，@code{integer} 和 @code{fraction} 是十六进制数码组成的字符串，@code{exponent} 是带有可选前导符的十进制整数。 大小写没有影响，在 integer 或 fraction 中必须至少有一个十六进制数码。 此语法类似于 C99 标准的 6.4.4.2 小节中所描述的语法，也是 Java 1.5 以上所使用的语法。 特别地，@ref{1489,,float.hex()} 的输出可以用作 C 或 Java 代码中的十六进制浮点数字面值，而由 C 的 @code{%a} 格式字符或 Java 的 @code{Double.toHexString} 所生成的十六进制数字符串由为 @ref{1789,,float.fromhex()} 所接受。

请注意 exponent 是十进制数而非十六进制数，它给出要与系数相乘的 2 的幂次。 例如，十六进制数字符串 @code{0x3.a7p10} 表示浮点数 @code{(3 + 10./16 + 7./16**2) * 2.0**10} 即 @code{3740.0}:

@example
>>> float.fromhex('0x3.a7p10')
3740.0
@end example

对 @code{3740.0} 应用反向转换会得到另一个代表相同数值的十六进制数字符串:

@example
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
@end example

@node 数字类型的哈希运算,,浮点类型的附加方法,数字类型 --- int float complex
@anchor{library/stdtypes hashing-of-numeric-types}@anchor{178a}@anchor{library/stdtypes numeric-hash}@anchor{178b}
@subsubsection 数字类型的哈希运算


对于可能为不同类型的数字 @code{x} 和 @code{y}，要求 @code{x == y} 时必定 @code{hash(x) == hash(y)} (详情参见 @ref{455,,__hash__()} 方法的文档)。 为了便于在各种数字类型 (包括 @ref{205,,int}, @ref{1fe,,float}, @ref{2c7,,decimal.Decimal} 和 @ref{2c5,,fractions.Fraction}) 上实现并保证效率，Python 对数字类型的哈希运算是基于为任意有理数定义统一的数学函数，因此该运算对 @ref{205,,int} 和 @ref{2c5,,fractions.Fraction} 的全部实例，以及 @ref{1fe,,float} 和 @ref{2c7,,decimal.Decimal} 的全部有限实例均可用。 从本质上说，此函数是通过以一个固定质数 @code{P} 进行 @code{P} 降模给出的。 @code{P} 的值在 Python 中可以 @ref{a0f,,sys.hash_info} 的 @code{modulus} 属性的形式被访问。

@strong{CPython implementation detail:} 目前所用的质数设定，在 C long 为 32 位的机器上 @code{P = 2**31 - 1} 而在 C long 为 64 位的机器上 @code{P = 2**61 - 1}。

详细规则如下所述:


@itemize -

@item 
如果 @code{x = m / n} 是一个非负的有理数且 @code{n} 不可被 @code{P} 整除，则定义 @code{hash(x)} 为 @code{m * invmod(n, P) % P}，其中 @code{invmod(n, P)} 是对 @code{n} 模 @code{P} 取反。

@item 
如果 @code{x = m / n} 是一个非负的有理数且 @code{n} 可被 @code{P} 整除（但 @code{m} 不能）则 @code{n} 不能对 @code{P} 降模，以上规则不适用；在此情况下则定义 @code{hash(x)} 为常数值 @code{sys.hash_info.inf}。

@item 
如果 @code{x = m / n} 是一个负的有理数则定义 @code{hash(x)} 为 @code{-hash(-x)}。 如果结果哈希值为 @code{-1} 则将其替换为 @code{-2}。

@item 
特定值 @code{sys.hash_info.inf}, @code{-sys.hash_info.inf} 和 @code{sys.hash_info.nan} 被用作正无穷、负无穷和空值（所分别对应的）哈希值。 （所有可哈希的空值都具有相同的哈希值。）

@item 
对于一个 @ref{2c8,,complex} 值 @code{z}，会通过计算 @code{hash(z.real) + sys.hash_info.imag * hash(z.imag)} 将实部和虚部的哈希值结合起来，并进行降模 @code{2**sys.hash_info.width} 以使其处于 @code{range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))} 范围之内。 同样地，如果结果为 @code{-1} 则将其替换为 @code{-2}。
@end itemize

为了阐明上述规则，这里有一些等价于内置哈希算法的 Python 代码示例，可用于计算有理数、@ref{1fe,,float} 或 @ref{2c8,,complex} 的哈希值:

@example
import sys, math

def hash_fraction(m, n):
    """Compute the hash of a rational number m / n.

    Assumes m and n are integers, with n positive.
    Equivalent to hash(fractions.Fraction(m, n)).

    """
    P = sys.hash_info.modulus
    # Remove common factors of P.  (Unnecessary if m and n already coprime.)
    while m % P == n % P == 0:
        m, n = m // P, n // P

    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
        # pow(n, P-2, P) gives the inverse of n modulo P.
        hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

def hash_float(x):
    """Compute the hash of a float x."""

    if math.isnan(x):
        return sys.hash_info.nan
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

def hash_complex(z):
    """Compute the hash of a complex number z."""

    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    # do a signed reduction modulo 2**sys.hash_info.width
    M = 2**(sys.hash_info.width - 1)
    hash_value = (hash_value & (M - 1)) - (hash_value & M)
    if hash_value == -1:
        hash_value = -2
    return hash_value
@end example

@node 迭代器类型,序列类型 --- list tuple range,数字类型 --- int float complex,内置类型
@anchor{library/stdtypes iterator-types}@anchor{178c}@anchor{library/stdtypes typeiter}@anchor{15c9}
@subsection 迭代器类型


@geindex iterator protocol
@geindex protocol; iterator
@geindex sequence; iteration
@geindex container; iteration over

Python 支持在容器中进行迭代的概念。 这是通过使用两个单独方法来实现的；它们被用于允许用户自定义类对迭代的支持。 将在下文中详细描述的序列总是支持迭代方法。

容器对象要提供迭代支持，必须定义一个方法:

@c XXX duplicated in reference/datamodel!

@geindex __iter__() (container 方法)
@anchor{library/stdtypes container __iter__}@anchor{178d}
@deffn {方法} container.__iter__ ()

返回一个迭代器对象。 该对象需要支持下文所述的迭代器协议。 如果容器支持不同的迭代类型，则可以提供额外的方法来专门地请求不同迭代类型的迭代器。 （支持多种迭代形式的对象的例子有同时支持广度优先和深度优先遍历的树结构。） 此方法对应于 Python/C API 中 Python 对象类型结构体的 @ref{efa,,tp_iter} 槽位。
@end deffn

迭代器对象自身需要支持以下两个方法，它们共同组成了 @emph{迭代器协议}:

@geindex __iter__() (iterator 方法)
@anchor{library/stdtypes iterator __iter__}@anchor{178e}
@deffn {方法} iterator.__iter__ ()

返回迭代器对象本身。 这是同时允许容器和迭代器配合 @ref{d02,,for} 和 @ref{179,,in} 语句使用所必须的。 此方法对应于 Python/C API 中 Python 对象类型结构体的 @ref{efa,,tp_iter} 槽位。
@end deffn

@geindex __next__() (iterator 方法)
@anchor{library/stdtypes iterator __next__}@anchor{d34}
@deffn {方法} iterator.__next__ ()

从容器中返回下一项。 如果已经没有项可返回，则会引发 @ref{58a,,StopIteration} 异常。 此方法对应于 Python/C API 中 Python 对象类型结构体的 @ref{efb,,tp_iternext} 槽位。
@end deffn

Python 定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别的形式进行迭代。 除了迭代器协议的实现，特定类型的其他性质对迭代操作来说都不重要。

一旦迭代器的 @ref{d34,,__next__()} 方法引发了 @ref{58a,,StopIteration}，它必须一直对后续调用引发同样的异常。 不遵循此行为特性的实现将无法正常使用。

@menu
* 生成器类型:: 

@end menu

@node 生成器类型,,,迭代器类型
@anchor{library/stdtypes generator-types}@anchor{178f}@anchor{library/stdtypes id3}@anchor{1790}
@subsubsection 生成器类型


Python 的 @ref{a8c,,generator} 提供了一种实现迭代器协议的便捷方式。 如果容器对象 @ref{611,,__iter__()} 方法被实现为一个生成器，它将自动返回一个迭代器对象（从技术上说是一个生成器对象），该对象提供 @ref{611,,__iter__()} 和 @ref{143f,,__next__()} 方法。 有关生成器的更多信息可以参阅 @ref{166c,,yield 表达式的文档}。

@node 序列类型 --- list tuple range,文本序列类型 --- str,迭代器类型,内置类型
@anchor{library/stdtypes sequence-types-list-tuple-range}@anchor{1791}@anchor{library/stdtypes typesseq}@anchor{13d3}
@subsection 序列类型 --- @code{list}, @code{tuple}, @code{range}


有三种基本序列类型：list, tuple 和 range 对象。 为处理 @ref{174d,,二进制数据} 和 @ref{1386,,文本字符串} 而特别定制的附加序列类型会在专门的小节中描述。

@menu
* 通用序列操作:: 
* 不可变序列类型:: 
* 可变序列类型:: 
* 列表: 列表<2>. 
* 元组:: 
* range 对象:: 

@end menu

@node 通用序列操作,不可变序列类型,,序列类型 --- list tuple range
@anchor{library/stdtypes common-sequence-operations}@anchor{1792}@anchor{library/stdtypes typesseq-common}@anchor{1793}
@subsubsection 通用序列操作


@geindex 对象; sequence

大多数序列类型，包括可变类型和不可变类型都支持下表中的操作。 @ref{1794,,collections.abc.Sequence} ABC 被提供用来更容易地在自定义序列类型上正确地实现这些操作。

此表按优先级升序列出了序列操作。 在表格中，@emph{s} 和 @emph{t} 是具有相同类型的序列，@emph{n}, @emph{i}, @emph{j} 和 @emph{k} 是整数而 @emph{x} 是任何满足 @emph{s} 所规定的类型和值限制的任意对象。

@code{in} 和 @code{not in} 操作具有与比较操作相同的优先级。 @code{+} (拼接) 和 @code{*} (重复) 操作具有与对应数值运算相同的优先级。 @footnote{@w{(3)} 
它们必须如此，因为解析器无法区分这些操作数的类型。
}

@geindex operations on; sequence; types
@geindex 內置函数; len
@geindex 內置函数; min
@geindex 內置函数; max
@geindex concatenation; operation
@geindex repetition; operation
@geindex subscript; operation
@geindex slice; operation
@geindex 运算符; in
@geindex 运算符; not in
@geindex count() (sequence method)
@geindex index() (sequence method)


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@tab

注释

@item

@code{x in s}

@tab

如果 @emph{s} 中的某项等于 @emph{x} 则结果为 @code{True}，否则为 @code{False}

@tab

(1)

@item

@code{x not in s}

@tab

如果 @emph{s} 中的某项等于 @emph{x} 则结果为 @code{False}，否则为 @code{True}

@tab

(1)

@item

@code{s + t}

@tab

@emph{s} 与 @emph{t} 相拼接

@tab

(6)(7)

@item

@code{s * n} 或 @code{n * s}

@tab

相当于 @emph{s} 与自身进行 @emph{n} 次拼接

@tab

(2)(7)

@item

@code{s[i]}

@tab

@emph{s} 的第 @emph{i} 项，起始为 0

@tab

(3)

@item

@code{s[i:j]}

@tab

@emph{s} 从 @emph{i} 到 @emph{j} 的切片

@tab

(3)(4)

@item

@code{s[i:j:k]}

@tab

@emph{s} 从 @emph{i} 到 @emph{j} 步长为 @emph{k} 的切片

@tab

(3)(5)

@item

@code{len(s)}

@tab

@emph{s} 的长度

@tab

@item

@code{min(s)}

@tab

@emph{s} 的最小项

@tab

@item

@code{max(s)}

@tab

@emph{s} 的最大项

@tab

@item

@code{s.index(x[, i[, j]])}

@tab

@emph{x} 在 @emph{s} 中首次出现项的索引号（索引号在 @emph{i} 或其后且在 @emph{j} 之前）

@tab

(8)

@item

@code{s.count(x)}

@tab

@emph{x} 在 @emph{s} 中出现的总次数

@tab

@end multitable


相同类型的序列也支持比较。 特别地，tuple 和 list 的比较是通过比较对应元素的字典顺序。 这意味着想要比较结果相等，则每个元素比较结果都必须相等，并且两个序列长度必须相同。 （完整细节请参阅语言参考的 @ref{16a9,,比较运算} 部分。）

注释:


@enumerate 

@item 
虽然 @code{in} 和 @code{not in} 操作在通常情况下仅被用于简单的成员检测，某些专门化序列 (例如 @ref{206,,str}, @ref{172,,bytes} 和 @ref{173,,bytearray}) 也使用它们进行子序列检测:

@example
>>> "gg" in "eggs"
True
@end example

@item 
小于 @code{0} 的 @emph{n} 值会被当作 @code{0} 来处理 (生成一个与 @emph{s} 同类型的空序列)。 请注意序列 @emph{s} 中的项并不会被拷贝；它们会被多次引用。 这一点经常会令 Python 编程新手感到困扰；例如:

@example
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
@end example

具体的原因在于 @code{[[]]} 是一个包含了一个空列表的单元素列表，所以 @code{[[]] * 3} 结果中的三个元素都是对这一个空列表的引用。 修改 @code{lists} 中的任何一个元素实际上都是对这一个空列表的修改。 你可以用以下方式创建以不同列表为元素的列表:

@example
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
@end example

进一步的解释可以在 FAQ 条目 @ref{1795,,如何创建多维列表？} 中查看。

@item 
如果 @emph{i} 或 @emph{j} 为负值，则索引顺序是相对于序列 @emph{s} 的末尾: 索引号会被替换为 @code{len(s) + i} 或 @code{len(s) + j}。 但要注意 @code{-0} 仍然为 @code{0}。

@item 
@emph{s} 从 @emph{i} 到 @emph{j} 的切片被定义为所有满足 @code{i <= k < j} 的索引号 @emph{k} 的项组成的序列。 如果 @emph{i} 或 @emph{j} 大于 @code{len(s)}，则使用 @code{len(s)}。 如果 @emph{i} 被省略或为 @code{None}，则使用 @code{0}。 如果 @emph{j} 被省略或为 @code{None}，则使用 @code{len(s)}。 如果 @emph{i} 大于等于 @emph{j}，则切片为空。

@item 
@emph{s} 从 @emph{i} 到 @emph{j} 步长为 @emph{k} 的切片被定义为所有满足 @code{0 <= n < (j-i)/k} 的索引号  @code{x = i + n*k} 的项组成的序列。 换句话说，索引号为 @code{i}, @code{i+k}, @code{i+2*k}, @code{i+3*k}，以此类推，当达到 @emph{j} 时停止 (但一定不包括 @emph{j})。 当 @emph{k} 为正值时，@emph{i} 和 @emph{j} 会被减至不大于 @code{len(s)}。 当 @emph{k} 为负值时，@emph{i} 和 @emph{j} 会被减至不大于 @code{len(s) - 1}。 如果 @emph{i} 或 @emph{j} 被省略或为 @code{None}，它们会成为“终止”值 (是哪一端的终止值则取决于 @emph{k} 的符号)。 请注意，@emph{k} 不可为零。 如果 @emph{k} 为 @code{None}，则当作 @code{1} 处理。

@item 
拼接不可变序列总是会生成新的对象。 这意味着通过重复拼接来构建序列的运行时开销将会基于序列总长度的乘方。 想要获得线性的运行时开销，你必须改用下列替代方案之一：


@itemize *

@item 
如果拼接 @ref{206,,str} 对象，你可以构建一个列表并在最后使用 @ref{1796,,str.join()} 或是写入一个 @ref{924,,io.StringIO} 实例并在结束时获取它的值

@item 
如果拼接 @ref{172,,bytes} 对象，你可以类似地使用 @ref{1797,,bytes.join()} 或 @ref{894,,io.BytesIO}，或者你也可以使用 @ref{173,,bytearray} 对象进行原地拼接。 @ref{173,,bytearray} 对象是可变的，并且具有高效的重分配机制

@item 
如果拼接 @ref{1a2,,tuple} 对象，请改为扩展 @ref{1f9,,list} 类

@item 
对于其它类型，请查看相应的文档
@end itemize

@item 
某些序列类型 (例如 @ref{1f6,,range}) 仅支持遵循特定模式的项序列，因此并不支持序列拼接或重复。

@item 
当 @emph{x} 在 @emph{s} 中找不到时 @code{index} 会引发 @ref{16d,,ValueError}。 不是所有实现都支持传入额外参数 @emph{i} 和 @emph{j}。 这两个参数允许高效地搜索序列的子序列。 传入这两个额外参数大致相当于使用 @code{s[i:j].index(x)}，但是不会复制任何数据，并且返回的索引是相对于序列的开头而非切片的开头。
@end enumerate

@node 不可变序列类型,可变序列类型,通用序列操作,序列类型 --- list tuple range
@anchor{library/stdtypes immutable-sequence-types}@anchor{1798}@anchor{library/stdtypes typesseq-immutable}@anchor{1799}
@subsubsection 不可变序列类型


@geindex immutable; sequence; types
@geindex 对象; tuple
@geindex 內置函数; hash

不可变序列类型普遍实现而可变序列类型未实现的唯一操作就是对 @ref{aac,,hash()} 内置函数的支持。

这种支持允许不可变类型，例如 @ref{1a2,,tuple} 实例被用作 @ref{164,,dict} 键，以及存储在 @ref{1f7,,set} 和 @ref{1f8,,frozenset} 实例中。

尝试对包含有不可哈希值的不可变序列进行哈希运算将会导致 @ref{1ff,,TypeError}。

@node 可变序列类型,列表<2>,不可变序列类型,序列类型 --- list tuple range
@anchor{library/stdtypes mutable-sequence-types}@anchor{179a}@anchor{library/stdtypes typesseq-mutable}@anchor{174a}
@subsubsection 可变序列类型


@geindex mutable; sequence; types
@geindex 对象; list
@geindex 对象; bytearray

以下表格中的操作是在可变序列类型上定义的。 @ref{7a9,,collections.abc.MutableSequence} ABC 被提供用来更容易地在自定义序列类型上正确实现这些操作。

表格中的 @emph{s} 是可变序列类型的实例，@emph{t} 是任意可迭代对象，而 @emph{x} 是符合对 @emph{s} 所规定类型与值限制的任何对象 (例如，@ref{173,,bytearray} 仅接受满足 @code{0 <= x <= 255} 值限制的整数)。

@geindex operations on; sequence; types
@geindex operations on; list; type
@geindex subscript; assignment
@geindex slice; assignment
@geindex 语句; del
@geindex append() (sequence method)
@geindex clear() (sequence method)
@geindex copy() (sequence method)
@geindex extend() (sequence method)
@geindex insert() (sequence method)
@geindex pop() (sequence method)
@geindex remove() (sequence method)
@geindex reverse() (sequence method)


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@tab

注释

@item

@code{s[i] = x}

@tab

将 @emph{s} 的第 @emph{i} 项替换为 @emph{x}

@tab

@item

@code{s[i:j] = t}

@tab

将 @emph{s} 从 @emph{i} 到 @emph{j} 的切片替换为可迭代对象 @emph{t} 的内容

@tab

@item

@code{del s[i:j]}

@tab

等同于 @code{s[i:j] = []}

@tab

@item

@code{s[i:j:k] = t}

@tab

将 @code{s[i:j:k]} 的元素替换为 @emph{t} 的元素

@tab

(1)

@item

@code{del s[i:j:k]}

@tab

从列表中移除 @code{s[i:j:k]} 的元素

@tab

@item

@code{s.append(x)}

@tab

将 @emph{x} 添加到序列的末尾 (等同于 @code{s[len(s):len(s)] = [x]})

@tab

@item

@code{s.clear()}

@tab

从 @emph{s} 中移除所有项 (等同于 @code{del s[:]})

@tab

(5)

@item

@code{s.copy()}

@tab

创建 @emph{s} 的浅拷贝 (等同于 @code{s[:]})

@tab

(5)

@item

@code{s.extend(t)} 或 @code{s += t}

@tab

用 @emph{t} 的内容扩展 @emph{s} (基本上等同于 @code{s[len(s):len(s)] = t})

@tab

@item

@code{s *= n}

@tab

使用 @emph{s} 的内容重复 @emph{n} 次来对其进行更新

@tab

(6)

@item

@code{s.insert(i, x)}

@tab

在由 @emph{i} 给出的索引位置将 @emph{x} 插入 @emph{s} (等同于 @code{s[i:i] = [x]})

@tab

@item

@code{s.pop()} 或 @code{s.pop(i)}

@tab

提取在 @emph{i} 位置上的项，并将其从 @emph{s} 中移除

@tab

(2)

@item

@code{s.remove(x)}

@tab

删除 @emph{s} 中第一个 @code{s[i]} 等于 @emph{x} 的项目。

@tab

(3)

@item

@code{s.reverse()}

@tab

就地将列表中的元素逆序。

@tab

(4)

@end multitable


注释:


@enumerate 

@item 
@emph{t} 必须与它所替换的切片具有相同的长度。

@item 
可选参数 @emph{i} 默认为 @code{-1}，因此在默认情况下会移除并返回最后一项。

@item 
当在 @emph{s} 中找不到 @emph{x} 时 @code{remove()} 操作会引发 @ref{16d,,ValueError}。

@item 
当反转大尺寸序列时 @code{reverse()} 方法会原地修改该序列以保证空间经济性。 为提醒用户此操作是通过间接影响进行的，它并不会返回反转后的序列。

@item 
包括 @code{clear()} 和 @code{copy()} 是为了与不支持切片操作的可变容器 (例如 @ref{164,,dict} 和 @ref{1f7,,set}) 的接口保持一致。 @code{copy()} 不是 @ref{7a9,,collections.abc.MutableSequence} ABC 的一部分，但大多数具体的可变序列类都提供了它。


3.3 新版功能: @code{clear()} 和 @code{copy()} 方法。


@item 
@emph{n} 值为一个整数，或是一个实现了 @ref{2c9,,__index__()} 的对象。 @emph{n} 值为零或负数将清空序列。 序列中的项不会被拷贝；它们会被多次引用，正如 @ref{1793,,通用序列操作} 中有关 @code{s * n} 的说明。
@end enumerate

@node 列表<2>,元组,可变序列类型,序列类型 --- list tuple range
@anchor{library/stdtypes lists}@anchor{179b}@anchor{library/stdtypes typesseq-list}@anchor{175a}
@subsubsection 列表


@geindex 对象; list

列表是可变序列，通常用于存放同类项目的集合（其中精确的相似程度将根据应用而变化）。

@geindex list (內置类)
@anchor{library/stdtypes list}@anchor{1f9}
@deffn {类} list ([iterable])

可以用多种方式构建列表：


@itemize *

@item 
使用一对方括号来表示空列表: @code{[]}

@item 
使用方括号，其中的项以逗号分隔: @code{[a]}, @code{[a, b, c]}

@item 
使用列表推导式: @code{[x for x in iterable]}

@item 
使用类型的构造器: @code{list()} 或 @code{list(iterable)}
@end itemize

构造器将构造一个列表，其中的项与 @emph{iterable} 中的项具有相同的的值与顺序。 @emph{iterable} 可以是序列、支持迭代的容器或其它可迭代对象。 如果 @emph{iterable} 已经是一个列表，将创建并返回其副本，类似于 @code{iterable[:]}。 例如，@code{list('abc')} 返回 @code{['a', 'b', 'c']} 而 @code{list( (1, 2, 3) )} 返回 @code{[1, 2, 3]}。 如果没有给出参数，构造器将创建一个空列表 @code{[]}。

其它许多操作也会产生列表，包括 @ref{54f,,sorted()} 内置函数。

列表实现了所有 @ref{1793,,一般} 和 @ref{174a,,可变} 序列的操作。 列表还额外提供了以下方法：

@geindex sort() (list 方法)
@anchor{library/stdtypes list sort}@anchor{550}
@deffn {方法} sort (*, key=None, reverse=False)

此方法会对列表进行原地排序，只使用 @code{<} 来进行各项间比较。 异常不会被屏蔽 —— 如果有任何比较操作失败，整个排序操作将失败（而列表可能会处于被部分修改的状态）。

@ref{550,,sort()} 接受两个仅限以关键字形式传入的参数 (@ref{3d6,,仅限关键字参数}):

@emph{key} 指定带有一个参数的函数，用于从每个列表元素中提取比较键 (例如 @code{key=str.lower})。 对应于列表中每一项的键会被计算一次，然后在整个排序过程中使用。 默认值 @code{None} 表示直接对列表项排序而不计算一个单独的键值。

可以使用 @ref{c31,,functools.cmp_to_key()} 将 2.x 风格的 @emph{cmp} 函数转换为 @emph{key} 函数。

@emph{reverse} 为一个布尔值。 如果设为 @code{True}，则每个列表元素将按反向顺序比较进行排序。

当顺序大尺寸序列时此方法会原地修改该序列以保证空间经济性。 为提醒用户此操作是通过间接影响进行的，它并不会返回排序后的序列（请使用 @ref{54f,,sorted()} 显示地请求一个新的已排序列表实例）。

@ref{550,,sort()} 方法确保是稳定的。 如果一个排序确保不会改变比较结果相等的元素的相对顺序就称其为稳定的 --- 这有利于进行多重排序（例如先按部门、再接薪级排序）。

有关排序示例和简要排序教程，请参阅 @ref{1767,,排序指南} 。

@strong{CPython implementation detail:} 在一个列表被排序期间，尝试改变甚至进行检测也会造成未定义的影响。 Python 的 C 实现会在排序期间将列表显示为空，如果发现列表在排序期间被改变将会引发 @ref{16d,,ValueError}。
@end deffn
@end deffn

@node 元组,range 对象,列表<2>,序列类型 --- list tuple range
@anchor{library/stdtypes tuples}@anchor{179c}@anchor{library/stdtypes typesseq-tuple}@anchor{176b}
@subsubsection 元组


@geindex 对象; tuple

元组是不可变序列，通常用于储存异构数据的多项集（例如由 @ref{eaf,,enumerate()} 内置函数所产生的二元组）。 元组也被用于需要同构数据的不可变序列的情况（例如允许存储到 @ref{1f7,,set} 或 @ref{164,,dict} 的实例）。

@geindex tuple (內置类)
@anchor{library/stdtypes tuple}@anchor{1a2}
@deffn {类} tuple ([iterable])

可以用多种方式构建元组：


@itemize *

@item 
使用一对圆括号来表示空元组: @code{()}

@item 
使用一个后缀的逗号来表示单元组: @code{a,} 或 @code{(a,)}

@item 
使用以逗号分隔的多个项: @code{a, b, c} or @code{(a, b, c)}

@item 
使用内置的 @ref{1a2,,tuple()}: @code{tuple()} 或 @code{tuple(iterable)}
@end itemize

构造器将构造一个元组，其中的项与 @emph{iterable} 中的项具有相同的值与顺序。 @emph{iterable} 可以是序列、支持迭代的容器或其他可迭代对象。 如果 @emph{iterable} 已经是一个元组，会不加改变地将其返回。 例如，@code{tuple('abc')} 返回 @code{('a', 'b', 'c')} 而 @code{tuple( [1, 2, 3] )} 返回 @code{(1, 2, 3)}。 如果没有给出参数，构造器将创建一个空元组 @code{()}。

请注意决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的，生成空元组或需要避免语法歧义的情况除外。 例如，@code{f(a, b, c)} 是在调用函数时附带三个参数，而 @code{f((a, b, c))} 则是在调用函数时附带一个三元组。

元组实现了所有 @ref{1793,,一般} 序列的操作。
@end deffn

对于通过名称访问相比通过索引访问更清晰的异构数据多项集，@ref{1a1,,collections.namedtuple()} 可能是比简单元组对象更为合适的选择。

@node range 对象,,元组,序列类型 --- list tuple range
@anchor{library/stdtypes ranges}@anchor{179d}@anchor{library/stdtypes typesseq-range}@anchor{1765}
@subsubsection range 对象


@geindex 对象; range

@ref{1f6,,range} 类型表示不可变的数字序列，通常用于在 @ref{d02,,for} 循环中循环指定的次数。

@geindex range (內置类)
@anchor{library/stdtypes range}@anchor{1f6}
@deffn {类} range (stop)

@deffnx {类} range (start, stop[, step])

range 构造器的参数必须为整数（可以是内置的 @ref{205,,int} 或任何实现了 @ref{2c9,,__index__()} 特殊方法的对象）。 如果省略 @emph{step} 参数，则默认为 @code{1}。 如果省略 @emph{start} 参数，则默认为 @code{0}。 如果 @emph{step} 为零，则会引发 @ref{16d,,ValueError}。

如果 @emph{step} 为正值，确定 range @code{r} 内容的公式为 @code{r[i] = start + step*i} 其中 @code{i >= 0} 且 @code{r[i] < stop}。

如果 @emph{step} 为负值，确定 range 内容的公式仍然为 @code{r[i] = start + step*i}，但限制条件改为 @code{i >= 0} 且 @code{r[i] > stop}.

如果 @code{r[0]} 不符合值的限制条件，则该 range 对象为空。 range 对象确实支持负索引，但是会将其解读为从正索引所确定的序列的末尾开始索引。

元素绝对值大于 @ref{c1e,,sys.maxsize} 的 range 对象是被允许的，但某些特性 (例如 @ref{292,,len()}) 可能引发 @ref{a4a,,OverflowError}。

一些 range 对象的例子:

@example
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
@end example

range 对象实现了 @ref{1793,,一般} 序列的所有操作，但拼接和重复除外（这是由于 range 对象只能表示符合严格模式的序列，而重复和拼接通常都会违反这样的模式）。

@geindex start (range 属性)
@anchor{library/stdtypes range start}@anchor{179e}
@deffn {属性} start

@emph{start} 形参的值 (如果该形参未提供则为 @code{0})
@end deffn

@geindex stop (range 属性)
@anchor{library/stdtypes range stop}@anchor{179f}
@deffn {属性} stop

@emph{stop} 形参的值
@end deffn

@geindex step (range 属性)
@anchor{library/stdtypes range step}@anchor{17a0}
@deffn {属性} step

@emph{step} 形参的值 (如果该形参未提供则为 @code{1})
@end deffn
@end deffn

@ref{1f6,,range} 类型相比常规 @ref{1f9,,list} 或 @ref{1a2,,tuple} 的优势在于一个 @ref{1f6,,range} 对象总是占用固定数量的（较小）内存，不论其所表示的范围有多大（因为它只保存了 @code{start}, @code{stop} 和 @code{step} 值，并会根据需要计算具体单项或子范围的值）。

range 对象实现了 @ref{1794,,collections.abc.Sequence} ABC，提供如包含检测、元素索引查找、切片等特性，并支持负索引 (参见 @ref{13d3,,序列类型 --- list@comma{} tuple@comma{} range}):

@example
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18
@end example

使用 @code{==} 和 @code{!=} 检测 range 对象是否相等是将其作为序列来比较。 也就是说，如果两个 range 对象表示相同的值序列就认为它们是相等的。 （请注意比较结果相等的两个 range 对象可能会具有不同的 @ref{179e,,start}, @ref{179f,,stop} 和 @ref{17a0,,step} 属性，例如 @code{range(0) == range(2, 1, 3)} 而 @code{range(0, 3, 2) == range(0, 4, 2)}。）


在 3.2 版更改: 实现 Sequence ABC。 支持切片和负数索引。 使用 @ref{205,,int} 对象在固定时间内进行成员检测，而不是逐一迭代所有项。



在 3.3 版更改: 定义 '==' 和 '!=' 以根据 range 对象所定义的值序列来进行比较（而不是根据对象的标识）。



3.3 新版功能: @ref{179e,,start}, @ref{179f,,stop} 和 @ref{17a0,,step} 属性。



@subsubheading 参见



@itemize *

@item 
linspace recipe@footnote{http://code.activestate.com/recipes/579000/} 演示了如何实现一个延迟求值版本的适合浮点数应用的 range 对象。
@end itemize


@geindex string; text sequence type
@geindex str (built-in class); (see also string)
@geindex 对象; string

@node 文本序列类型 --- str,二进制序列类型 --- bytes bytearray memoryview,序列类型 --- list tuple range,内置类型
@anchor{library/stdtypes text-sequence-type-str}@anchor{17a1}@anchor{library/stdtypes textseq}@anchor{1386}
@subsection 文本序列类型 --- @code{str}


在 Python 中处理文本数据是使用 @ref{206,,str} 对象，也称为 @emph{字符串}。 字符串是由 Unicode 码位构成的不可变 @ref{13d3,,序列}。 字符串字面值有多种不同的写法：


@itemize *

@item 
单引号: @code{'允许包含有 "双" 引号'}

@item 
双引号: @code{"允许嵌入 '单' 引号"}

@item 
三重引号: @code{'@w{'}'三重单引号'@w{'}'}, @code{"""三重双引号"""}
@end itemize

使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串字面值中。

作为单一表达式组成部分，之间只由空格分隔的多个字符串字面值会被隐式地转换为单个字符串字面值。 也就是说，@code{("spam " "eggs") == "spam eggs"}。

请参阅 @ref{1542,,字符串与字节串字面值} 了解有关不同字符串字面值的更多信息，包括所支持的转义序列，以及使用 @code{r} ("raw") 前缀来禁用大多数转义序列的处理。

字符串也可以通过使用 @ref{206,,str} 构造器从其他对象创建。

由于不存在单独的“字符”类型，对字符串做索引操作将产生一个长度为 1 的字符串。 也就是说，对于一个非空字符串 @emph{s}, @code{s[0] == s[0:1]}。

@geindex 对象; io.StringIO

不存在可变的字符串类型，但是 @ref{1796,,str.join()} 或 @ref{924,,io.StringIO} 可以被被用来根据多个片段高效率地构建字符串。


在 3.3 版更改: 为了与 Python 2 系列的向下兼容，再次允许字符串字面值使用 @code{u} 前缀。 它对字符串字面值的含义没有影响，并且不能与 @code{r} 前缀同时出现。


@geindex string; str (built-in class)

@geindex str (內置类)
@anchor{library/stdtypes str}@anchor{206}
@deffn {类} str (object='@w{'})

@deffnx {类} str (object=b'@w{'}, encoding='utf-8', errors='strict')

返回 @emph{object} 的 @ref{1386,,字符串} 版本。 如果未提供 @emph{object} 则返回空字符串。 在其他情况下 @code{str()} 的行为取决于 @emph{encoding} 或 @emph{errors} 是否有给出，具体见下。

如果 @emph{encoding} 或 @emph{errors} 均未给出，则 @code{str(object)} 返回 @ref{f01,,type(object).__str__(object)}，这是 @emph{object} 的 "非正式" 或格式良好的字符串表示形式。 对于字符串对象，这是该字符串本身。 如果 @emph{object} 没有 @ref{f01,,__str__()} 方法，则 @ref{206,,str()} 将回退为返回 @ref{8c3,,repr(object)}。

@geindex buffer protocol; str (built-in class)
@geindex bytes; str (built-in class)

如果 @emph{encoding} 或 @emph{errors} 至少给出其中之一，则 @emph{object} 应该是一个 @ref{6e9,,bytes-like object} (例如 @ref{172,,bytes} 或 @ref{173,,bytearray})。 在此情况下，如果 @emph{object} 是一个 @ref{172,,bytes} (或 @ref{173,,bytearray}) 对象，则 @code{str(bytes, encoding, errors)} 等价于 @ref{171,,bytes.decode(encoding@comma{} errors)}。 否则的话，会在调用 @ref{171,,bytes.decode()} 之前获取缓冲区对象下层的 bytes 对象。 请参阅 @ref{174d,,二进制序列类型 --- bytes@comma{} bytearray@comma{} memoryview} 与 @ref{174c,,缓冲协议} 了解有关缓冲区对象的信息。

将一个 @ref{172,,bytes} 对象传入 @ref{206,,str()} 而不给出 @emph{encoding} 或 @emph{errors} 参数的操作属于第一种情况， 将返回非正式的字符串表示（另请参阅 Python 的 @ref{522,,-b} 命令行选项）。 例如:

@example
>>> str(b'Zoot!')
"b'Zoot!'"
@end example

有关 @code{str} 类及其方法的更多信息，请参阅下面的 @ref{1386,,文本序列类型 --- str} 和 @ref{1387,,字符串的方法} 小节。 要输出格式化字符串，请参阅 @ref{29d,,格式字符串字面值} 和 @ref{de8,,格式字符串语法} 小节。 此外还可以参阅 @ref{17a2,,文本处理服务} 小节。
@end deffn

@geindex string; methods

@menu
* 字符串的方法: 字符串的方法<2>. 
* printf 风格的字符串格式化:: 

@end menu

@node 字符串的方法<2>,printf 风格的字符串格式化,,文本序列类型 --- str
@anchor{library/stdtypes id5}@anchor{17a3}@anchor{library/stdtypes string-methods}@anchor{1387}
@subsubsection 字符串的方法


@geindex 模块; re

字符串实现了所有 @ref{1793,,一般} 序列的操作，还额外提供了以下列出的一些附加方法。

字符串还支持两种字符串格式化样式，一种提供了很大程度的灵活性和可定制性 (参阅 @ref{5dd,,str.format()}, @ref{de8,,格式字符串语法} 和 @ref{17a4,,自定义字符串格式化}) 而另一种是基于 C @code{printf} 样式的格式化，它可处理的类型范围较窄，并且更难以正确使用，但对于它可处理的情况往往会更为快速 (@ref{1388,,printf 风格的字符串格式化})。

标准库的 @ref{17a5,,文本处理服务} 部分涵盖了许多其他模块，提供各种文本相关工具（例如包含于 @ref{dd,,re} 模块中的正则表达式支持）。

@geindex capitalize() (str 方法)
@anchor{library/stdtypes str capitalize}@anchor{17a6}
@deffn {方法} str.capitalize ()

返回原字符串的副本，其首个字符大写，其余为小写。


在 3.8 版更改: 第一个字符现在被放入了 titlecase 而不是 uppercase。 这意味着复合字母类字符将只有首个字母改为大写，而再不是全部字符大写。

@end deffn

@geindex casefold() (str 方法)
@anchor{library/stdtypes str casefold}@anchor{7ad}
@deffn {方法} str.casefold ()

返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的匹配。

消除大小写类似于转为小写，但是更加彻底一些，因为它会移除字符串中的所有大小写变化形式。 例如，德语小写字母 @code{'ß'} 相当于 @code{"ss"}。 由于它已经是小写了，@ref{17a7,,lower()} 不会对 @code{'ß'} 做任何改变；而 @ref{7ad,,casefold()} 则会将其转换为 @code{"ss"}。

消除大小写算法的描述请参见 Unicode 标准的 3.13 节。


3.3 新版功能.

@end deffn

@geindex center() (str 方法)
@anchor{library/stdtypes str center}@anchor{1400}
@deffn {方法} str.center (width[, fillchar])

返回长度为 @emph{width} 的字符串，原字符串在其正中。 使用指定的 @emph{fillchar} 填充两边的空位（默认使用 ASCII 空格符）。 如果 @emph{width} 小于等于 @code{len(s)} 则返回原字符串的副本。
@end deffn

@geindex count() (str 方法)
@anchor{library/stdtypes str count}@anchor{17a8}
@deffn {方法} str.count (sub[, start[, end]])

返回子字符串 @emph{sub} 在 [@emph{start}, @emph{end}] 范围内非重叠出现的次数。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。
@end deffn

@geindex encode() (str 方法)
@anchor{library/stdtypes str encode}@anchor{170}
@deffn {方法} str.encode (encoding="utf-8", errors="strict")

返回原字符串编码为字节串对象的版本。 默认编码为 @code{'utf-8'}。 可以给出 @emph{errors} 来设置不同的错误处理方案。 @emph{errors} 的默认值为 @code{'strict'}，表示编码错误会引发 @ref{d0b,,UnicodeError}。 其他可用的值为 @code{'ignore'}, @code{'replace'}, @code{'xmlcharrefreplace'}, @code{'backslashreplace'} 以及任何其他通过 @ref{ec1,,codecs.register_error()} 注册的值，请参阅 @ref{f7d,,错误处理方案} 小节。 要查看可用的编码列表，请参阅 @ref{78c,,标准编码} 小节。

@emph{errors} 参数默认不会被检查，以获得最佳性能，而只在第一次编码错误时使用。启用 @ref{160,,Python 开发模式} ，或者使用调试构建来检查 @emph{errors} 。


在 3.1 版更改: 加入了对关键字参数的支持。



在 3.9 版更改: @emph{errors} 现在在开发模式和调试模式下都会被检查。

@end deffn

@geindex endswith() (str 方法)
@anchor{library/stdtypes str endswith}@anchor{8be}
@deffn {方法} str.endswith (suffix[, start[, end]])

如果字符串以指定的 @emph{suffix} 结束返回 @code{True}，否则返回 @code{False}。 @emph{suffix} 也可以为由多个供查找的后缀构成的元组。 如果有可选项 @emph{start}，将从所指定位置开始检查。 如果有可选项 @emph{end}，将在所指定位置停止比较。
@end deffn

@geindex expandtabs() (str 方法)
@anchor{library/stdtypes str expandtabs}@anchor{17a9}
@deffn {方法} str.expandtabs (tabsize=8)

返回字符串的副本，其中所有的制表符会由一个或多个空格替换，具体取决于当前列位置和给定的制表符宽度。 每 @emph{tabsize} 个字符设为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开字符串，当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符 (@code{\t})，则会在结果中插入一个或多个空格符，直到当前列等于下一个制表位。 （制表符本身不会被复制。） 如果字符为换行符 (@code{\n}) 或回车符 (@code{\r})，它会被复制并将当前列重设为零。 任何其他字符会被不加修改地复制并将当前列加一，不论该字符在被打印时会如何显示。

@example
>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
@end example
@end deffn

@geindex find() (str 方法)
@anchor{library/stdtypes str find}@anchor{898}
@deffn {方法} str.find (sub[, start[, end]])

返回子字符串 @emph{sub} 在 @code{s[start:end]} 切片内被找到的最小索引。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。 如果 @emph{sub} 未被找到则返回 @code{-1}。

@cartouche
@quotation 注解 
@ref{898,,find()} 方法应该只在你需要知道 @emph{sub} 所在位置时使用。 要检查 @emph{sub} 是否为子字符串，请使用 @ref{179,,in} 操作符:

@example
>>> 'Py' in 'Python'
True
@end example
@end quotation
@end cartouche
@end deffn

@geindex format() (str 方法)
@anchor{library/stdtypes str format}@anchor{5dd}
@deffn {方法} str.format (*args, **kwargs)

执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以花括号 @code{@{@}} 括起来的替换域。 每个替换域可以包含一个位置参数的数字索引，或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替换为对应参数的字符串值。

@example
>>> "The sum of 1 + 2 is @{0@}".format(1+2)
'The sum of 1 + 2 is 3'
@end example

请参阅 @ref{de8,,格式字符串语法} 了解有关可以在格式字符串中指定的各种格式选项的说明。

@cartouche
@quotation 注解 
当使用 @code{n} 类型 (例如: @code{'@{:n@}'.format(1234)}) 来格式化数字 (@ref{205,,int}, @ref{1fe,,float}, @ref{2c8,,complex}, @ref{2c7,,decimal.Decimal} 及其子类) 的时候，该函数会临时性地将 @code{LC_CTYPE} 区域设置为 @code{LC_NUMERIC} 区域以解码  @code{localeconv()} 的 @code{decimal_point} 和 @code{thousands_sep} 字段，如果它们是非 ASCII 字符或长度超过 1 字节的话，并且 @code{LC_NUMERIC} 区域会与 @code{LC_CTYPE} 区域不一致。 这个临时更改会影响其他线程。
@end quotation
@end cartouche


在 3.7 版更改: 当使用 @code{n} 类型格式化数字时，该函数在某些情况下会临时性地将 @code{LC_CTYPE} 区域设置为 @code{LC_NUMERIC} 区域。

@end deffn

@geindex format_map() (str 方法)
@anchor{library/stdtypes str format_map}@anchor{7ae}
@deffn {方法} str.format_map (mapping)

类似于 @code{str.format(**mapping)}，不同之处在于 @code{mapping} 会被直接使用而不是复制到一个 @ref{164,,dict}。 适宜使用此方法的一个例子是当 @code{mapping} 为 dict 的子类的情况：

@example
>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '@{name@} was born in @{country@}'.format_map(Default(name='Guido'))
'Guido was born in country'
@end example


3.2 新版功能.

@end deffn

@geindex index() (str 方法)
@anchor{library/stdtypes str index}@anchor{17aa}
@deffn {方法} str.index (sub[, start[, end]])

类似于 @ref{898,,find()}，但在找不到子类时会引发 @ref{16d,,ValueError}。
@end deffn

@geindex isalnum() (str 方法)
@anchor{library/stdtypes str isalnum}@anchor{17ab}
@deffn {方法} str.isalnum ()

如果字符串中的所有字符都是字母或数字且至少有一个字符，则返回 @code{True} ， 否则返回 @code{False} 。 如果 @code{c.isalpha()} ， @code{c.isdecimal()} ， @code{c.isdigit()} ，或 @code{c.isnumeric()} 之中有一个返回 @code{True} ，则字符`@w{`}c`@w{`}是字母或数字。
@end deffn

@geindex isalpha() (str 方法)
@anchor{library/stdtypes str isalpha}@anchor{17ac}
@deffn {方法} str.isalpha ()

如果字符串中的所有字符都是字母，并且至少有一个字符，返回 @code{True} ，否则返回 @code{False} 。字母字符是指那些在 Unicode 字符数据库中定义为 "Letter" 的字符，即那些具有 "Lm"、"Lt"、"Lu"、"Ll" 或 "Lo" 之一的通用类别属性的字符。 注意，这与 Unicode 标准中定义的"字母"属性不同。
@end deffn

@geindex isascii() (str 方法)
@anchor{library/stdtypes str isascii}@anchor{449}
@deffn {方法} str.isascii ()

如果字符串为空或字符串中的所有字符都是 ASCII ，返回 @code{True} ，否则返回 @code{False} 。ASCII 字符的码点范围是 U+0000-U+007F 。


3.7 新版功能.

@end deffn

@geindex isdecimal() (str 方法)
@anchor{library/stdtypes str isdecimal}@anchor{17ad}
@deffn {方法} str.isdecimal ()

如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符，则返回 @code{True} ， 否则返回 @code{False} 。十进制字符指那些可以用来组成10进制数字的字符，例如 U+0660 ，即阿拉伯字母数字0 。 严格地讲，十进制字符是 Unicode 通用类别 "Nd" 中的一个字符。
@end deffn

@geindex isdigit() (str 方法)
@anchor{library/stdtypes str isdigit}@anchor{17ae}
@deffn {方法} str.isdigit ()

如果字符串中的所有字符都是数字，并且至少有一个字符，返回 @code{True} ，否则返回 @code{False} 。 数字包括十进制字符和需要特殊处理的数字，如兼容性上标数字。这包括了不能用来组成 10 进制数的数字，如 Kharosthi 数。 严格地讲，数字是指属性值为 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符。
@end deffn

@geindex isidentifier() (str 方法)
@anchor{library/stdtypes str isidentifier}@anchor{1085}
@deffn {方法} str.isidentifier ()

如果字符串是有效的标识符，返回 @code{True} ，依据语言定义， @ref{1533,,标识符和关键字} 节。

调用 @ref{17af,,keyword.iskeyword()} 来检测字符串 @code{s} 是否为保留标识符，例如 @ref{e8b,,def} 和 @ref{d3a,,class}。

示例：

@example
>>> from keyword import iskeyword

>>> 'hello'.isidentifier(), iskeyword('hello')
(True, False)
>>> 'def'.isidentifier(), iskeyword('def')
(True, True)
@end example
@end deffn

@geindex islower() (str 方法)
@anchor{library/stdtypes str islower}@anchor{17b0}
@deffn {方法} str.islower ()

如果字符串中至少有一个区分大小写的字符 @footnote{@w{(4)} 
区分大小写的字符是指所属一般类别属性为 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的字符。
} 且此类字符均为小写则返回 @code{True} ，否则返回 @code{False} 。
@end deffn

@geindex isnumeric() (str 方法)
@anchor{library/stdtypes str isnumeric}@anchor{17b1}
@deffn {方法} str.isnumeric ()

如果字符串中至少有一个字符且所有字符均为数值字符则返回 @code{True} ，否则返回 @code{False} 。 数值字符包括数字字符，以及所有在 Unicode 中设置了数值特性属性的字符，例如 U+2155, VULGAR FRACTION ONE FIFTH。 正式的定义为：数值字符就是具有特征属性值 Numeric_Type=Digit, Numeric_Type=Decimal 或 Numeric_Type=Numeric 的字符。
@end deffn

@geindex isprintable() (str 方法)
@anchor{library/stdtypes str isprintable}@anchor{7af}
@deffn {方法} str.isprintable ()

如果字符串中所有字符均为可打印字符或字符串为空则返回 @code{True} ，否则返回 @code{False} 。 不可打印字符是在 Unicode 字符数据库中被定义为 "Other" 或 "Separator" 的字符，例外情况是 ASCII 空格字符 (0x20) 被视作可打印字符。 （请注意在此语境下可打印字符是指当对一个字符串发起调用 @ref{8c3,,repr()} 时不必被转义的字符。 它们与字符串写入 @ref{428,,sys.stdout} 或 @ref{1eb,,sys.stderr} 时所需的处理无关。）
@end deffn

@geindex isspace() (str 方法)
@anchor{library/stdtypes str isspace}@anchor{17b2}
@deffn {方法} str.isspace ()

如果字符串中只有空白字符且至少有一个字符则返回 @code{True} ，否则返回 @code{False} 。

@emph{空白} 字符是指在 Unicode 字符数据库 (参见 @ref{123,,unicodedata}) 中主要类别为 @code{Zs} ("Separator, space") 或所属双向类为 @code{WS}, @code{B} 或 @code{S} 的字符。
@end deffn

@geindex istitle() (str 方法)
@anchor{library/stdtypes str istitle}@anchor{17b3}
@deffn {方法} str.istitle ()

如果字符串中至少有一个字符且为标题字符串则返回 @code{True} ，例如大写字符之后只能带非大写字符而小写字符必须有大写字符打头。 否则返回 @code{False} 。
@end deffn

@geindex isupper() (str 方法)
@anchor{library/stdtypes str isupper}@anchor{17b4}
@deffn {方法} str.isupper ()

如果字符串中至少有一个区分大小写的字符 @footnote{@w{(4)} 
区分大小写的字符是指所属一般类别属性为 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的字符。
} 且此类字符均为大写则返回 @code{True} ，否则返回 @code{False} 。

@example
>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
@end example
@end deffn

@geindex join() (str 方法)
@anchor{library/stdtypes str join}@anchor{1796}
@deffn {方法} str.join (iterable)

返回一个由 @emph{iterable} 中的字符串拼接而成的字符串。 如果 @emph{iterable} 中存在任何非字符串值包括 @ref{172,,bytes} 对象则会引发 @ref{1ff,,TypeError}。 调用该方法的字符串将作为元素之间的分隔。
@end deffn

@geindex ljust() (str 方法)
@anchor{library/stdtypes str ljust}@anchor{13ff}
@deffn {方法} str.ljust (width[, fillchar])

返回长度为 @emph{width} 的字符串，原字符串在其中靠左对齐。 使用指定的 @emph{fillchar} 填充空位 (默认使用 ASCII 空格符)。 如果 @emph{width} 小于等于 @code{len(s)} 则返回原字符串的副本。
@end deffn

@geindex lower() (str 方法)
@anchor{library/stdtypes str lower}@anchor{17a7}
@deffn {方法} str.lower ()

返回原字符串的副本，其所有区分大小写的字符 @footnote{@w{(4)} 
区分大小写的字符是指所属一般类别属性为 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的字符。
} 均转换为小写。

所用转换小写算法的描述请参见 Unicode 标准的 3.13 节。
@end deffn

@geindex lstrip() (str 方法)
@anchor{library/stdtypes str lstrip}@anchor{17b5}
@deffn {方法} str.lstrip ([chars])

返回原字符串的副本，移除其中的前导字符。 @emph{chars} 参数为指定要移除字符的字符串。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除空白符。 实际上 @emph{chars} 参数并非指定单个前缀；而是会移除参数值的所有组合:

@example
>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
@end example

参见 @ref{166,,str.removeprefix()} ，该方法将删除单个前缀字符串，而不是全部给定集合中的字符。 例如:

@example
>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'
@end example
@end deffn

@geindex maketrans() (str 静态方法)
@anchor{library/stdtypes str maketrans}@anchor{7b0}
@deffn {方法} static str.maketrans (x[, y[, z]])

此静态方法返回一个可供 @ref{17b6,,str.translate()} 使用的转换对照表。

如果只有一个参数，则它必须是一个将 Unicode 码位序号（整数）或字符（长度为 1 的字符串）映射到 Unicode 码位序号、（任意长度的）字符串或 @code{None} 的字典。 字符键将会被转换为码位序号。

如果有两个参数，则它们必须是两个长度相等的字符串，并且在结果字典中，x 中每个字符将被映射到 y 中相同位置的字符。 如果有第三个参数，它必须是一个字符串，其中的字符将在结果中被映射到 @code{None}。
@end deffn

@geindex partition() (str 方法)
@anchor{library/stdtypes str partition}@anchor{89b}
@deffn {方法} str.partition (sep)

在 @emph{sep} 首次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含字符本身以及两个空字符串。
@end deffn

@geindex removeprefix() (str 方法)
@anchor{library/stdtypes str removeprefix}@anchor{166}
@deffn {方法} str.removeprefix (prefix, /)

如果字符串以 @emph{prefix} 字符串开头，返回 @code{string[len(prefix):]}。 否则，返回原始字符串的副本：

@example
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
@end example


3.9 新版功能.

@end deffn

@geindex removesuffix() (str 方法)
@anchor{library/stdtypes str removesuffix}@anchor{167}
@deffn {方法} str.removesuffix (suffix, /)

如果字符串以 @emph{suffix} 字符串结尾，并且 @emph{suffix} 非空，返回 @code{string[:-len(suffix)]}。 否则，返回原始字符串的副本:

@example
>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
@end example


3.9 新版功能.

@end deffn

@geindex replace() (str 方法)
@anchor{library/stdtypes str replace}@anchor{17b7}
@deffn {方法} str.replace (old, new[, count])

返回字符串的副本，其中出现的所有子字符串 @emph{old} 都将被替换为 @emph{new}。 如果给出了可选参数 @emph{count}，则只替换前 @emph{count} 次出现。
@end deffn

@geindex rfind() (str 方法)
@anchor{library/stdtypes str rfind}@anchor{899}
@deffn {方法} str.rfind (sub[, start[, end]])

返回子字符串 @emph{sub} 在字符串内被找到的最大（最右）索引，这样 @emph{sub} 将包含在 @code{s[start:end]} 当中。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。 如果未找到则返回 @code{-1}。
@end deffn

@geindex rindex() (str 方法)
@anchor{library/stdtypes str rindex}@anchor{17b8}
@deffn {方法} str.rindex (sub[, start[, end]])

类似于 @ref{899,,rfind()}，但在子字符串 @emph{sub} 未找到时会引发 @ref{16d,,ValueError}。
@end deffn

@geindex rjust() (str 方法)
@anchor{library/stdtypes str rjust}@anchor{13fe}
@deffn {方法} str.rjust (width[, fillchar])

返回长度为 @emph{width} 的字符串，原字符串在其中靠右对齐。 使用指定的 @emph{fillchar} 填充空位 (默认使用 ASCII 空格符)。 如果 @emph{width} 小于等于 @code{len(s)} 则返回原字符串的副本。
@end deffn

@geindex rpartition() (str 方法)
@anchor{library/stdtypes str rpartition}@anchor{17b9}
@deffn {方法} str.rpartition (sep)

在 @emph{sep} 最后一次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含两个空字符串以及字符串本身。
@end deffn

@geindex rsplit() (str 方法)
@anchor{library/stdtypes str rsplit}@anchor{17ba}
@deffn {方法} str.rsplit (sep=None, maxsplit=-1)

返回一个由字符串内单词组成的列表，使用 @emph{sep} 作为分隔字符串。 如果给出了 @emph{maxsplit}，则最多进行 @emph{maxsplit} 次拆分，从 @emph{最右边} 开始。 如果 @emph{sep} 未指定或为 @code{None}，任何空白字符串都会被作为分隔符。 除了从右边开始拆分，@ref{17ba,,rsplit()} 的其他行为都类似于下文所述的 @ref{89a,,split()}。
@end deffn

@geindex rstrip() (str 方法)
@anchor{library/stdtypes str rstrip}@anchor{17bb}
@deffn {方法} str.rstrip ([chars])

返回原字符串的副本，移除其中的末尾字符。 @emph{chars} 参数为指定要移除字符的字符串。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除空白符。 实际上 @emph{chars} 参数并非指定单个后缀；而是会移除参数值的所有组合:

@example
>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
@end example

要删除单个后缀字符串，而不是全部给定集合中的字符，请参见 @ref{167,,str.removesuffix()} 方法。 例如:

@example
>>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'
@end example
@end deffn

@geindex split() (str 方法)
@anchor{library/stdtypes str split}@anchor{89a}
@deffn {方法} str.split (sep=None, maxsplit=-1)

返回一个由字符串内单词组成的列表，使用 @emph{sep} 作为分隔字符串。 如果给出了 @emph{maxsplit}，则最多进行 @emph{maxsplit} 次拆分（因此，列表最多会有 @code{maxsplit+1} 个元素）。 如果 @emph{maxsplit} 未指定或为 @code{-1}，则不限制拆分次数（进行所有可能的拆分）。

如果给出了 @emph{sep}，则连续的分隔符不会被组合在一起而是被视为分隔空字符串 (例如 @code{'1,,2'.split(',')} 将返回 @code{['1', '@w{'}, '2']})。 @emph{sep} 参数可能由多个字符组成 (例如 @code{'1<>2<>3'.split('<>')} 将返回 @code{['1', '2', '3']})。 使用指定的分隔符拆分空字符串将返回 @code{['@w{'}]}。

例如:

@example
>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '@w{'}, '3', '@w{'}]
@end example

如果 @emph{sep} 未指定或为 @code{None}，则会应用另一种拆分算法：连续的空格会被视为单个分隔符，其结果将不包含开头或末尾的空字符串，如果字符串包含前缀或后缀空格的话。 因此，使用 @code{None} 拆分空字符串或仅包含空格的字符串将返回 @code{[]}。

例如:

@example
>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
@end example
@end deffn

@geindex universal newlines; str.splitlines method

@geindex splitlines() (str 方法)
@anchor{library/stdtypes str splitlines}@anchor{17bc}
@deffn {方法} str.splitlines (keepends=False)

返回由原字符串中各行组成的列表，在行边界的位置拆分。 结果列表中不包含行边界，除非给出了 @emph{keepends} 且为真值。

此方法会以下列行边界进行拆分。 特别地，行边界是 @ref{6f5,,universal newlines} 的一个超集。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

表示符

@tab

描述

@item

@code{\n}

@tab

换行

@item

@code{\r}

@tab

回车

@item

@code{\r\n}

@tab

回车 + 换行

@item

@code{\v} 或 @code{\x0b}

@tab

行制表符

@item

@code{\f} 或 @code{\x0c}

@tab

换表单

@item

@code{\x1c}

@tab

文件分隔符

@item

@code{\x1d}

@tab

组分隔符

@item

@code{\x1e}

@tab

记录分隔符

@item

@code{\x85}

@tab

下一行 (C1 控制码)

@item

@code{\u2028}

@tab

行分隔符

@item

@code{\u2029}

@tab

段分隔符

@end multitable



在 3.2 版更改: @code{\v} 和 @code{\f} 被添加到行边界列表


例如:

@example
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '@w{'}, 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
@end example

不同于 @ref{89a,,split()}，当给出了分隔字符串 @emph{sep} 时，对于空字符串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

@example
>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']
@end example

作为比较，@code{split('\n')} 的结果为:

@example
>>> '@w{'}.split('\n')
['@w{'}]
>>> 'Two lines\n'.split('\n')
['Two lines', '@w{'}]
@end example
@end deffn

@geindex startswith() (str 方法)
@anchor{library/stdtypes str startswith}@anchor{8bd}
@deffn {方法} str.startswith (prefix[, start[, end]])

如果字符串以指定的 @emph{prefix} 开始则返回 @code{True}，否则返回 @code{False}。 @emph{prefix} 也可以为由多个供查找的前缀构成的元组。 如果有可选项 @emph{start}，将从所指定位置开始检查。 如果有可选项 @emph{end}，将在所指定位置停止比较。
@end deffn

@geindex strip() (str 方法)
@anchor{library/stdtypes str strip}@anchor{17bd}
@deffn {方法} str.strip ([chars])

返回原字符串的副本，移除其中的前导和末尾字符。 @emph{chars} 参数为指定要移除字符的字符串。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除空白符。 实际上 @emph{chars} 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:

@example
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
@end example

最外侧的前导和末尾 @emph{chars} 参数值将从字符串中移除。 开头端的字符的移除将在遇到一个未包含于 @emph{chars} 所指定字符集的字符时停止。 类似的操作也将在结尾端发生。 例如:

@example
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
@end example
@end deffn

@geindex swapcase() (str 方法)
@anchor{library/stdtypes str swapcase}@anchor{17be}
@deffn {方法} str.swapcase ()

返回原字符串的副本，其中大写字符转换为小写，反之亦然。 请注意 @code{s.swapcase().swapcase() == s} 并不一定为真值。
@end deffn

@geindex title() (str 方法)
@anchor{library/stdtypes str title}@anchor{17bf}
@deffn {方法} str.title ()

返回原字符串的标题版本，其中每个单词第一个字母为大写，其余字母为小写。

例如:

@example
>>> 'Hello world'.title()
'Hello World'
@end example

该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也会成为单词边界，这可能导致不希望的结果:

@example
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
@end example

@ref{17c0,,string.capwords()} 函数没有此问题，因为它只用空格来拆分单词。

作为替代，可以使用正则表达式来构造针对撇号的变通处理:

@example
>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0).capitalize(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
@end example
@end deffn

@geindex translate() (str 方法)
@anchor{library/stdtypes str translate}@anchor{17b6}
@deffn {方法} str.translate (table)

返回原字符串的副本，其中每个字符按给定的转换表进行映射。 转换表必须是一个使用 @ref{3ad,,__getitem__()} 来实现索引操作的对象，通常为 @ref{c14,,mapping} 或 @ref{138b,,sequence}。 当以 Unicode 码位序号（整数）为索引时，转换表对象可以做以下任何一种操作：返回 Unicode 序号或字符串，将字符映射为一个或多个字符；返回 @code{None}，将字符从结果字符串中删除；或引发 @ref{17c1,,LookupError} 异常，将字符映射为其自身。

你可以使用 @ref{7b0,,str.maketrans()} 基于不同格式的字符到字符映射来创建一个转换映射表。

另请参阅 @ref{1b,,codecs} 模块以了解定制字符映射的更灵活方式。
@end deffn

@geindex upper() (str 方法)
@anchor{library/stdtypes str upper}@anchor{17c2}
@deffn {方法} str.upper ()

返回原字符串的副本，其中所有区分大小写的字符 @footnote{@w{(4)} 
区分大小写的字符是指所属一般类别属性为 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的字符。
} 均转换为大写。 请注意如果 @code{s} 包含不区分大小写的字符或者如果结果字符的 Unicode 类别不是 "Lu" (Letter, uppercase) 而是 "Lt" (Letter, titlecase) 则 @code{s.upper().isupper()} 有可能为 @code{False}。

所用转换大写算法的描述请参见 Unicode 标准的 3.13 节。
@end deffn

@geindex zfill() (str 方法)
@anchor{library/stdtypes str zfill}@anchor{1401}
@deffn {方法} str.zfill (width)

返回原字符串的副本，在左边填充 ASCII @code{'0'} 数码使其长度变为 @emph{width}。 正负值前缀 (@code{'+'}/@code{'-'}) 的处理方式是在正负符号 @emph{之后} 填充而非在之前。 如果 @emph{width} 小于等于 @code{len(s)} 则返回原字符串的副本。

例如:

@example
>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
@end example
@end deffn

@node printf 风格的字符串格式化,,字符串的方法<2>,文本序列类型 --- str
@anchor{library/stdtypes old-string-formatting}@anchor{1388}@anchor{library/stdtypes printf-style-string-formatting}@anchor{17c3}
@subsubsection @code{printf} 风格的字符串格式化


@geindex formatting@comma{} string (%)
@geindex interpolation@comma{} string (%)
@geindex string; formatting@comma{} printf
@geindex string; interpolation@comma{} printf
@geindex printf-style formatting
@geindex sprintf-style formatting
@geindex % (percent); printf-style formatting

@cartouche
@quotation 注解 
此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（例如无法正确显示元组和字典）。 使用较新的 @ref{29d,,格式化字符串字面值}，@ref{5dd,,str.format()} 接口或 @ref{17c4,,模板字符串} 有助于避免这样的错误。 这些替代方案中的每一种都更好地权衡并提供了简单、灵活以及可扩展性优势。
@end quotation
@end cartouche

字符串具有一种特殊的内置操作：使用 @code{%} (取模) 运算符。 这也被称为字符串的 @emph{格式化} 或 @emph{插值} 运算符。 对于 @code{format % values} (其中 @emph{format} 为一个字符串)，在 @emph{format} 中的 @code{%} 转换标记符将被替换为零个或多个 @emph{values} 条目。 其效果类似于在 C 语言中使用 @code{sprintf()}。

如果 @emph{format} 要求一个单独参数，则 @emph{values} 可以为一个非元组对象。 @footnote{@w{(5)} 
要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元素就是要被格式化的元组。
}  否则的话，@emph{values} 必须或者是一个包含项数与格式字符串中指定的转换符项数相同的元组，或者是一个单独映射对象（例如字典）。

@geindex () (parentheses); in printf-style formatting
@geindex * (asterisk); in printf-style formatting
@geindex . (dot); in printf-style formatting

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：


@enumerate 

@item 
@code{'%'} 字符，用于标记转换符的起始。

@item 
映射键（可选），由加圆括号的字符序列组成 (例如 @code{(somename)})。

@item 
转换旗标（可选），用于影响某些转换类型的结果。

@item 
最小字段宽度（可选）。 如果指定为 @code{'*'} (星号)，则实际宽度会从 @emph{values} 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的精度之后的元素。

@item 
精度（可选），以在 @code{'.'} (点号) 之后加精度值的形式给出。 如果指定为 @code{'*'} (星号)，则实际精度会从 @emph{values} 元组的下一元素中读取，要转换的对象则为精度之后的元素。

@item 
长度修饰符（可选）。

@item 
转换类型。
@end enumerate

当右边的参数为一个字典（或其他映射类型）时，字符串中的格式 @emph{必须} 包含加圆括号的映射键，对应 @code{'%'} 字符之后字典中的每一项。 映射键将从映射中选取要格式化的值。 例如：

@example
>>> print('%(language)s has %(number)03d quote types.' %
...       @{'language': "Python", "number": 2@})
Python has 002 quote types.
@end example

在此情况下格式中不能出现 @code{*} 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

@geindex # (hash); in printf-style formatting
@geindex - (minus); in printf-style formatting
@geindex + (plus); in printf-style formatting
@geindex space; in printf-style formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标志

@tab

含义

@item

@code{'#'}

@tab

值的转换将使用“替代形式”（具体定义见下文）。

@item

@code{'0'}

@tab

转换将为数字值填充零字符。

@item

@code{'-'}

@tab

转换值将靠左对齐（如果同时给出 @code{'0'} 转换，则会覆盖后者）。

@item

@code{' '}

@tab

(空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。

@item

@code{'+'}

@tab

符号字符 (@code{'+'} 或 @code{'-'}) 将显示于转换结果的开头（会覆盖 "空格" 旗标）。

@end multitable


可以给出长度修饰符 (@code{h}, @code{l} 或 @code{L})，但会被忽略，因为对 Python 来说没有必要 -- 所以 @code{%ld} 等价于 @code{%d}。

转换类型为：


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

转换符

@tab

含义

@tab

注释

@item

@code{'d'}

@tab

有符号十进制整数。

@tab

@item

@code{'i'}

@tab

有符号十进制整数。

@tab

@item

@code{'o'}

@tab

有符号八进制数。

@tab

(1)

@item

@code{'u'}

@tab

过时类型 -- 等价于 @code{'d'}。

@tab

(6)

@item

@code{'x'}

@tab

有符号十六进制数（小写）。

@tab

(2)

@item

@code{'X'}

@tab

有符号十六进制数（大写）。

@tab

(2)

@item

@code{'e'}

@tab

浮点指数格式（小写）。

@tab

(3)

@item

@code{'E'}

@tab

浮点指数格式（大写）。

@tab

(3)

@item

@code{'f'}

@tab

浮点十进制格式。

@tab

(3)

@item

@code{'F'}

@tab

浮点十进制格式。

@tab

(3)

@item

@code{'g'}

@tab

浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格式，否则使用十进制格式。

@tab

(4)

@item

@code{'G'}

@tab

浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格式，否则使用十进制格式。

@tab

(4)

@item

@code{'c'}

@tab

单个字符（接受整数或单个字符的字符串）。

@tab

@item

@code{'r'}

@tab

字符串（使用 @ref{8c3,,repr()} 转换任何 Python 对象）。

@tab

(5)

@item

@code{'s'}

@tab

字符串（使用 @ref{206,,str()} 转换任何 Python 对象）。

@tab

(5)

@item

@code{'a'}

@tab

字符串（使用 @ref{e19,,ascii()} 转换任何 Python 对象）。

@tab

(5)

@item

@code{'%'}

@tab

不转换参数，在结果中输出一个 @code{'%'} 字符。

@tab

@end multitable


注释:


@enumerate 

@item 
此替代形式会在第一个数码之前插入标示八进制数的前缀 (@code{'0o'})。

@item 
此替代形式会在第一个数码之前插入 @code{'0x'} 或 @code{'0X'} 前缀（取决于是使用 @code{'x'} 还是 @code{'X'} 格式）。

@item 
此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

小数点后的数码位数由精度决定，默认为 6。

@item 
此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况下那样被移除。

小数点前后的有效数码位数由精度决定，默认为 6。

@item 
如果精度为 @code{N}，输出将截短为 @code{N} 个字符。

@item 
参见 
@geindex Python 提高建议; PEP 237
PEP 237@footnote{https://www.python.org/dev/peps/pep-0237}。
@end enumerate

由于 Python 字符串显式指明长度，@code{%s} 转换不会将 @code{'\0'} 视为字符串的结束。

@c XXX Examples?


在 3.1 版更改: 绝对值超过 1e50 的 @code{%f} 转换不会再被替换为 @code{%g} 转换。


@geindex buffer protocol; binary sequence types

@node 二进制序列类型 --- bytes bytearray memoryview,集合类型 --- set frozenset,文本序列类型 --- str,内置类型
@anchor{library/stdtypes binary-sequence-types-bytes-bytearray-memoryview}@anchor{17c5}@anchor{library/stdtypes binaryseq}@anchor{174d}
@subsection 二进制序列类型 --- @code{bytes}, @code{bytearray}, @code{memoryview}


@geindex 对象; bytes
@geindex 对象; bytearray
@geindex 对象; memoryview
@geindex 模块; array

操作二进制数据的核心内置类型是 @ref{172,,bytes} 和 @ref{173,,bytearray}。 它们由 @ref{38d,,memoryview} 提供支持，该对象使用 @ref{174c,,缓冲区协议} 来访问其他二进制对象所在内存，不需要创建对象的副本。

@ref{6,,array} 模块支持高效地存储基本数据类型，例如 32 位整数和 IEEE754 双精度浮点值。

@menu
* bytes 对象:: 
* bytearray 对象:: 
* bytes 和 bytearray 操作:: 
* printf 风格的字节串格式化:: 
* 内存视图:: 

@end menu

@node bytes 对象,bytearray 对象,,二进制序列类型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-objects}@anchor{17c6}@anchor{library/stdtypes typebytes}@anchor{174f}
@subsubsection bytes 对象


@geindex 对象; bytes

bytes 对象是由单个字节构成的不可变序列。 由于许多主要二进制协议都基于 ASCII 文本编码，因此 bytes 对象提供了一些仅在处理 ASCII 兼容数据时可用，并且在许多特性上与字符串对象紧密相关的方法。

@geindex bytes (內置类)
@anchor{library/stdtypes bytes}@anchor{172}
@deffn {类} bytes ([source[, encoding[, errors]]])

首先，表示 bytes 字面值的语法与字符串字面值的大致相同，只是添加了一个 @code{b} 前缀：


@itemize *

@item 
单引号: @code{b'同样允许嵌入 "双" 引号'}。

@item 
双引号: @code{b"仍然允许嵌入 '单' 引号"}

@item 
三重引号: @code{b'@w{'}'三重单引号'@w{'}'}, @code{b"""三重双引号"""}
@end itemize

bytes 字面值中只允许 ASCII 字符（无论源代码声明的编码为何）。 任何超出 127 的二进制值必须使用相应的转义序列形式加入 bytes 字面值。

像字符串字面值一样，bytes 字面值也可以使用 @code{r} 前缀来禁用转义序列处理。 请参阅 @ref{1542,,字符串与字节串字面值} 了解有关各种 bytes 字面值形式的详情，包括所支持的转义序列。

虽然 bytes 字面值和表示法是基于 ASCII 文本的，但 bytes 对象的行为实际上更像是不可变的整数序列，序列中的每个值的大小被限制为 @code{0 <= x < 256} (如果违反此限制将引发 @ref{16d,,ValueError})。 这种限制是有意设计用以强调以下事实，虽然许多二进制格式都包含基于 ASCII 的元素，可以通过某些面向文本的算法进行有用的操作，但情况对于任意二进制数据来说通常却并非如此（盲目地将文本处理算法应用于不兼容 ASCII 的二进制数据格式往往将导致数据损坏）。

除了字面值形式，bytes 对象还可以通过其他几种方式来创建：


@itemize *

@item 
指定长度的以零值填充的 bytes 对象: @code{bytes(10)}

@item 
通过由整数组成的可迭代对象: @code{bytes(range(20))}

@item 
通过缓冲区协议复制现有的二进制数据:  @code{bytes(obj)}
@end itemize

另请参阅 @ref{123a,,bytes} 内置类型。

由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数据的常用格式。 相应地，bytes 类型具有从此种格式读取数据的附加类方法：

@geindex fromhex() (bytes 类方法)
@anchor{library/stdtypes bytes fromhex}@anchor{447}
@deffn {方法} classmethod fromhex (string)

此 @ref{172,,bytes} 类方法返回一个解码给定字符串的 bytes 对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的 ASCII 空白符会被忽略。

@example
>>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'
@end example


在 3.7 版更改: @ref{447,,bytes.fromhex()} 现在会忽略所有 ASCII 空白符而不只是空格符。

@end deffn

存在一个反向转换函数，可以将 bytes 对象转换为对应的十六进制表示。

@geindex hex() (bytes 方法)
@anchor{library/stdtypes bytes hex}@anchor{72e}
@deffn {方法} hex ([sep[, bytes_per_sep]])

返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字。

@example
>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
@end example

如果你希望令十六进制数字符串更易读，你可以指定单个字符分隔符作为 @emph{sep} 形参包含于输出中。 默认会放在每个字节之间。 第二个可选的 @emph{bytes_per_sep} 形参控制间距。 正值会从右开始计算分隔符的位置，负值则是从左开始。

@example
>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
@end example


3.5 新版功能.



在 3.8 版更改: @ref{72e,,bytes.hex()} 现在支持可选的 @emph{sep} 和 @emph{bytes_per_sep} 形参以在十六进制输出的字节之间插入分隔符。

@end deffn
@end deffn

由于 bytes 对象是由整数构成的序列（类似于元组），因此对于一个 bytes 对象 @emph{b}，@code{b[0]} 将为一个整数，而 @code{b[0:1]} 将为一个长度为 1 的 bytes 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。

bytes 对象的表示使用字面值格式 (@code{b'...'})，因为它通常都要比像 @code{bytes([46, 46, 46])} 这样的格式更好用。 你总是可以使用 @code{list(b)} 将 bytes 对象转换为一个由整数构成的列表。

@node bytearray 对象,bytes 和 bytearray 操作,bytes 对象,二进制序列类型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytearray-objects}@anchor{17c7}@anchor{library/stdtypes typebytearray}@anchor{174e}
@subsubsection bytearray 对象


@geindex 对象; bytearray

@ref{173,,bytearray} 对象是 @ref{172,,bytes} 对象的可变对应物。

@geindex bytearray (內置类)
@anchor{library/stdtypes bytearray}@anchor{173}
@deffn {类} bytearray ([source[, encoding[, errors]]])

bytearray 对象没有专属的字面值语法，它们总是通过调用构造器来创建：


@itemize *

@item 
创建一个空实例: @code{bytearray()}

@item 
创建一个指定长度的以零值填充的实例: @code{bytearray(10)}

@item 
通过由整数组成的可迭代对象: @code{bytearray(range(20))}

@item 
通过缓冲区协议复制现有的二进制数据:  @code{bytearray(b'Hi!')}
@end itemize

由于 bytearray 对象是可变的，该对象除了 @ref{174b,,bytes 和 bytearray 操作} 中所描述的 bytes 和 bytearray 共有操作之外，还支持 @ref{174a,,可变} 序列操作。

另请参见 @ref{123b,,bytearray} 内置类型。

由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数据的常用格式。 相应地，bytearray 类型具有从此种格式读取数据的附加类方法：

@geindex fromhex() (bytearray 类方法)
@anchor{library/stdtypes bytearray fromhex}@anchor{448}
@deffn {方法} classmethod fromhex (string)

@ref{173,,bytearray} 类方法返回一个解码给定字符串的 bytearray 对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的 ASCII 空白符会被忽略。

@example
>>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')
@end example


在 3.7 版更改: @ref{448,,bytearray.fromhex()} 现在会忽略所有 ASCII 空白符而不只是空格符。

@end deffn

存在一个反向转换函数，可以将 bytearray 对象转换为对应的十六进制表示。

@geindex hex() (bytearray 方法)
@anchor{library/stdtypes bytearray hex}@anchor{72f}
@deffn {方法} hex ([sep[, bytes_per_sep]])

返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字。

@example
>>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'
@end example


3.5 新版功能.



在 3.8 版更改: 与 @ref{72e,,bytes.hex()} 相似， @ref{72f,,bytearray.hex()} 现在支持可选的 @emph{sep} 和 @emph{bytes_per_sep} 参数以在十六进制输出的字节之间插入分隔符。

@end deffn
@end deffn

由于 bytearray 对象是由整数构成的序列（类似于列表），因此对于一个 bytearray 对象 @emph{b}，@code{b[0]} 将为一个整数，而 @code{b[0:1]} 将为一个长度为 1 的 bytearray 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。

bytearray 对象的表示使用 bytes 对象字面值格式 (@code{bytearray(b'...')})，因为它通常都要比 @code{bytearray([46, 46, 46])} 这样的格式更好用。 你总是可以使用 @code{list(b)} 将 bytearray 对象转换为一个由整数构成的列表。

@node bytes 和 bytearray 操作,printf 风格的字节串格式化,bytearray 对象,二进制序列类型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-and-bytearray-operations}@anchor{17c8}@anchor{library/stdtypes bytes-methods}@anchor{174b}
@subsubsection bytes 和 bytearray 操作


@geindex bytes; methods
@geindex bytearray; methods

bytes 和 bytearray 对象都支持 @ref{1793,,通用} 序列操作。 它们不仅能与相同类型的操作数，也能与任何 @ref{6e9,,bytes-like object} 进行互操作。 由于这样的灵活性，它们可以在操作中自由地混合而不会导致错误。 但是，操作结果的返回值类型可能取决于操作数的顺序。

@cartouche
@quotation 注解 
bytes 和 bytearray 对象的方法不接受字符串作为其参数，就像字符串的方法不接受 bytes 对象作为其参数一样。 例如，你必须使用以下写法:

@example
a = "abc"
b = a.replace("a", "f")
@end example

和:

@example
a = b"abc"
b = a.replace(b"a", b"f")
@end example
@end quotation
@end cartouche

某些 bytes 和 bytearray 操作假定使用兼容 ASCII 的二进制格式，因此在处理任意二进数数据时应当避免使用。 这些限制会在下文中说明。

@cartouche
@quotation 注解 
使用这些基于 ASCII 的操作来处理未以基于 ASCII 的格式存储的二进制数据可能会导致数据损坏。
@end quotation
@end cartouche

bytes 和 bytearray 对象的下列方法可以用于任意二进制数据。

@geindex count() (bytes 方法)
@geindex count() (bytearray 方法)
@anchor{library/stdtypes bytes count}@anchor{17c9}
@deffn {方法} bytes.count (sub[, start[, end]])
@anchor{library/stdtypes bytearray count}@anchor{17ca}
@deffnx {方法} bytearray.count (sub[, start[, end]])

返回子序列 @emph{sub} 在 [@emph{start}, @emph{end}] 范围内非重叠出现的次数。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。

要搜索的子序列可以是任意 @ref{6e9,,bytes-like object} 或是 0 至 255 范围内的整数。


在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

@end deffn

@geindex removeprefix() (bytes 方法)
@geindex removeprefix() (bytearray 方法)
@anchor{library/stdtypes bytes removeprefix}@anchor{17cb}
@deffn {方法} bytes.removeprefix (prefix, /)
@anchor{library/stdtypes bytearray removeprefix}@anchor{17cc}
@deffnx {方法} bytearray.removeprefix (prefix, /)

如果二进制数据以 @emph{prefix} 字符串开头，返回 @code{bytes[len(prefix):]}。 否则，返回原始二进制数据的副本：

@example
>>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
@end example

@emph{prefix} 可以是任意 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche


3.9 新版功能.

@end deffn

@geindex removesuffix() (bytes 方法)
@geindex removesuffix() (bytearray 方法)
@anchor{library/stdtypes bytes removesuffix}@anchor{17cd}
@deffn {方法} bytes.removesuffix (suffix, /)
@anchor{library/stdtypes bytearray removesuffix}@anchor{17ce}
@deffnx {方法} bytearray.removesuffix (suffix, /)

如果二进制数据以 @emph{suffix} 字符串结尾，并且 @emph{suffix} 非空，返回 @code{bytes[:-len(suffix)]}。 否则，返回原始二进制数据的副本:

@example
>>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
@end example

@emph{suffix} 可以是任意 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche


3.9 新版功能.

@end deffn

@geindex decode() (bytes 方法)
@geindex decode() (bytearray 方法)
@anchor{library/stdtypes bytes decode}@anchor{171}
@deffn {方法} bytes.decode (encoding="utf-8", errors="strict")
@anchor{library/stdtypes bytearray decode}@anchor{17cf}
@deffnx {方法} bytearray.decode (encoding="utf-8", errors="strict")

返回从给定 bytes 解码出来的字符串。 默认编码为 @code{'utf-8'}。 可以给出 @emph{errors} 来设置不同的错误处理方案。 @emph{errors} 的默认值为 @code{'strict'}，表示编码错误会引发 @ref{d0b,,UnicodeError}。 其他可用的值为 @code{'ignore'}, @code{'replace'} 以及任何其他通过 @ref{ec1,,codecs.register_error()} 注册的名称，请参阅 @ref{f7d,,错误处理方案} 小节。 要查看可用的编码列表，请参阅 @ref{78c,,标准编码} 小节。

@emph{errors} 参数默认不会被检查，以获得最佳性能，而只在第一次解码错误时使用。启用 @ref{160,,Python 开发模式} ，或者使用调试构建来检查 @emph{errors} 。

@cartouche
@quotation 注解 
将 @emph{encoding} 参数传给 @ref{206,,str} 允许直接解码任何 @ref{6e9,,bytes-like object}，无须创建临时的 bytes 或 bytearray 对象。
@end quotation
@end cartouche


在 3.1 版更改: 加入了对关键字参数的支持。



在 3.9 版更改: @emph{errors} 现在在开发模式和调试模式下都会被检查。

@end deffn

@geindex endswith() (bytes 方法)
@geindex endswith() (bytearray 方法)
@anchor{library/stdtypes bytes endswith}@anchor{17d0}
@deffn {方法} bytes.endswith (suffix[, start[, end]])
@anchor{library/stdtypes bytearray endswith}@anchor{17d1}
@deffnx {方法} bytearray.endswith (suffix[, start[, end]])

如果二进制数据以指定的 @emph{suffix} 结束则返回 @code{True}，否则返回 @code{False}。 @emph{suffix} 也可以为由多个供查找的后缀构成的元组。 如果有可选项 @emph{start}，将从所指定位置开始检查。 如果有可选项 @emph{end}，将在所指定位置停止比较。

要搜索的后缀可以是任意 @ref{6e9,,bytes-like object}。
@end deffn

@geindex find() (bytes 方法)
@geindex find() (bytearray 方法)
@anchor{library/stdtypes bytes find}@anchor{17d2}
@deffn {方法} bytes.find (sub[, start[, end]])
@anchor{library/stdtypes bytearray find}@anchor{17d3}
@deffnx {方法} bytearray.find (sub[, start[, end]])

返回子序列 @emph{sub} 在数据中被找到的最小索引，@emph{sub} 包含于切片 @code{s[start:end]} 之内。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。 如果 @emph{sub} 未被找到则返回 @code{-1}。

要搜索的子序列可以是任意 @ref{6e9,,bytes-like object} 或是 0 至 255 范围内的整数。

@cartouche
@quotation 注解 
@ref{17d2,,find()} 方法应该只在你需要知道 @emph{sub} 所在位置时使用。 要检查 @emph{sub} 是否为子串，请使用 @ref{179,,in} 操作符:

@example
>>> b'Py' in b'Python'
True
@end example
@end quotation
@end cartouche


在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

@end deffn

@geindex index() (bytes 方法)
@geindex index() (bytearray 方法)
@anchor{library/stdtypes bytes index}@anchor{17d4}
@deffn {方法} bytes.index (sub[, start[, end]])
@anchor{library/stdtypes bytearray index}@anchor{17d5}
@deffnx {方法} bytearray.index (sub[, start[, end]])

类似于 @ref{17d2,,find()}，但在找不到子序列时会引发 @ref{16d,,ValueError}。

要搜索的子序列可以是任意 @ref{6e9,,bytes-like object} 或是 0 至 255 范围内的整数。


在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

@end deffn

@geindex join() (bytes 方法)
@geindex join() (bytearray 方法)
@anchor{library/stdtypes bytes join}@anchor{1797}
@deffn {方法} bytes.join (iterable)
@anchor{library/stdtypes bytearray join}@anchor{17d6}
@deffnx {方法} bytearray.join (iterable)

返回一个由 @emph{iterable} 中的二进制数据序列拼接而成的 bytes 或 bytearray 对象。 如果 @emph{iterable} 中存在任何非 @ref{6e9,,字节类对象} 包括存在 @ref{206,,str} 对象值则会引发 @ref{1ff,,TypeError}。 提供该方法的 bytes 或 bytearray 对象的内容将作为元素之间的分隔。
@end deffn

@geindex maketrans() (bytes 静态方法)
@geindex maketrans() (bytearray 静态方法)
@anchor{library/stdtypes bytes maketrans}@anchor{cdc}
@deffn {方法} static bytes.maketrans (from, to)
@anchor{library/stdtypes bytearray maketrans}@anchor{cdd}
@deffnx {方法} static bytearray.maketrans (from, to)

此静态方法返回一个可用于 @ref{17d7,,bytes.translate()} 的转换对照表，它将把 @emph{from} 中的每个字符映射为 @emph{to} 中相同位置上的字符；@emph{from} 与 @emph{to} 必须都是 @ref{6e9,,字节类对象} 并且具有相同的长度。


3.1 新版功能.

@end deffn

@geindex partition() (bytes 方法)
@geindex partition() (bytearray 方法)
@anchor{library/stdtypes bytes partition}@anchor{17d8}
@deffn {方法} bytes.partition (sep)
@anchor{library/stdtypes bytearray partition}@anchor{17d9}
@deffnx {方法} bytearray.partition (sep)

在 @emph{sep} 首次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之前的部分、分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含原序列以及两个空的 bytes 或 bytearray 对象。

要搜索的分隔符可以是任意 @ref{6e9,,bytes-like object}。
@end deffn

@geindex replace() (bytes 方法)
@geindex replace() (bytearray 方法)
@anchor{library/stdtypes bytes replace}@anchor{17da}
@deffn {方法} bytes.replace (old, new[, count])
@anchor{library/stdtypes bytearray replace}@anchor{17db}
@deffnx {方法} bytearray.replace (old, new[, count])

返回序列的副本，其中出现的所有子序列 @emph{old} 都将被替换为 @emph{new}。 如果给出了可选参数 @emph{count}，则只替换前 @emph{count} 次出现。

要搜索的子序列及其替换序列可以是任意 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex rfind() (bytes 方法)
@geindex rfind() (bytearray 方法)
@anchor{library/stdtypes bytes rfind}@anchor{17dc}
@deffn {方法} bytes.rfind (sub[, start[, end]])
@anchor{library/stdtypes bytearray rfind}@anchor{17dd}
@deffnx {方法} bytearray.rfind (sub[, start[, end]])

返回子序列 @emph{sub} 在序列内被找到的最大（最右）索引，这样 @emph{sub} 将包含在 @code{s[start:end]} 当中。 可选参数 @emph{start} 与 @emph{end} 会被解读为切片表示法。 如果未找到则返回 @code{-1}。

要搜索的子序列可以是任意 @ref{6e9,,bytes-like object} 或是 0 至 255 范围内的整数。


在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

@end deffn

@geindex rindex() (bytes 方法)
@geindex rindex() (bytearray 方法)
@anchor{library/stdtypes bytes rindex}@anchor{17de}
@deffn {方法} bytes.rindex (sub[, start[, end]])
@anchor{library/stdtypes bytearray rindex}@anchor{17df}
@deffnx {方法} bytearray.rindex (sub[, start[, end]])

类似于 @ref{17dc,,rfind()}，但在子序列 @emph{sub} 未找到时会引发 @ref{16d,,ValueError}。

要搜索的子序列可以是任意 @ref{6e9,,bytes-like object} 或是 0 至 255 范围内的整数。


在 3.3 版更改: 也接受 0 至 255 范围内的整数作为子序列。

@end deffn

@geindex rpartition() (bytes 方法)
@geindex rpartition() (bytearray 方法)
@anchor{library/stdtypes bytes rpartition}@anchor{17e0}
@deffn {方法} bytes.rpartition (sep)
@anchor{library/stdtypes bytearray rpartition}@anchor{17e1}
@deffnx {方法} bytearray.rpartition (sep)

在 @emph{sep} 最后一次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之前的部分，分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如果分隔符未找到，则返回的 3 元组中包含两个空的 bytes 或 bytearray 对象以及原序列的副本。

要搜索的分隔符可以是任意 @ref{6e9,,bytes-like object}。
@end deffn

@geindex startswith() (bytes 方法)
@geindex startswith() (bytearray 方法)
@anchor{library/stdtypes bytes startswith}@anchor{17e2}
@deffn {方法} bytes.startswith (prefix[, start[, end]])
@anchor{library/stdtypes bytearray startswith}@anchor{17e3}
@deffnx {方法} bytearray.startswith (prefix[, start[, end]])

如果二进制数据以指定的 @emph{prefix} 开头则返回 @code{True}，否则返回 @code{False}。 @emph{prefix} 也可以为由多个供查找的前缀构成的元组。 如果有可选项 @emph{start}，将从所指定位置开始检查。 如果有可选项 @emph{end}，将在所指定位置停止比较。

要搜索的前缀可以是任意 @ref{6e9,,bytes-like object}。
@end deffn

@geindex translate() (bytes 方法)
@geindex translate() (bytearray 方法)
@anchor{library/stdtypes bytes translate}@anchor{17d7}
@deffn {方法} bytes.translate (table, /, delete=b'@w{'})
@anchor{library/stdtypes bytearray translate}@anchor{d61}
@deffnx {方法} bytearray.translate (table, /, delete=b'@w{'})

返回原 bytes 或 bytearray 对象的副本，移除其中所有在可选参数 @emph{delete} 中出现的 bytes，其余 bytes 将通过给定的转换表进行映射，该转换表必须是长度为 256 的 bytes 对象。

你可以使用 @ref{cdc,,bytes.maketrans()} 方法来创建转换表。

对于仅需移除字符的转换，请将 @emph{table} 参数设为 @code{None}:

@example
>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
@end example


在 3.6 版更改: 现在支持将 @emph{delete} 作为关键字参数。

@end deffn

以下 bytes 和 bytearray 对象的方法的默认行为会假定使用兼容 ASCII 的二进制格式，但通过传入适当的参数仍然可用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 @emph{不是} 原地执行操作，而是会产生新的对象。

@geindex center() (bytes 方法)
@geindex center() (bytearray 方法)
@anchor{library/stdtypes bytes center}@anchor{17e4}
@deffn {方法} bytes.center (width[, fillbyte])
@anchor{library/stdtypes bytearray center}@anchor{17e5}
@deffnx {方法} bytearray.center (width[, fillbyte])

返回原对象的副本，在长度为 @emph{width} 的序列内居中，使用指定的 @emph{fillbyte} 填充两边的空位（默认使用 ASCII 空格符）。 对于 @ref{172,,bytes} 对象，如果 @emph{width} 小于等于 @code{len(s)} 则返回原序列的副本。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex ljust() (bytes 方法)
@geindex ljust() (bytearray 方法)
@anchor{library/stdtypes bytes ljust}@anchor{17e6}
@deffn {方法} bytes.ljust (width[, fillbyte])
@anchor{library/stdtypes bytearray ljust}@anchor{17e7}
@deffnx {方法} bytearray.ljust (width[, fillbyte])

返回原对象的副本，在长度为 @emph{width} 的序列中靠左对齐。 使用指定的 @emph{fillbyte} 填充空位（默认使用 ASCII 空格符）。 对于 @ref{172,,bytes} 对象，如果 @emph{width} 小于等于 @code{len(s)} 则返回原序列的副本。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex lstrip() (bytes 方法)
@geindex lstrip() (bytearray 方法)
@anchor{library/stdtypes bytes lstrip}@anchor{17e8}
@deffn {方法} bytes.lstrip ([chars])
@anchor{library/stdtypes bytearray lstrip}@anchor{17e9}
@deffnx {方法} bytearray.lstrip ([chars])

返回原序列的副本，移除指定的前导字节。 @emph{chars} 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除 ASCII 空白符。 @emph{chars} 参数并非指定单个前缀；而是会移除参数值的所有组合:

@example
>>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
@end example

要移除的二进制序列可以是任意 @ref{6e9,,bytes-like object} 。 要删除单个前缀字符串，而不是全部给定集合中的字符，请参见 @ref{166,,str.removeprefix()} 方法。 例如:

@example
>>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
@end example

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex rjust() (bytes 方法)
@geindex rjust() (bytearray 方法)
@anchor{library/stdtypes bytes rjust}@anchor{17ea}
@deffn {方法} bytes.rjust (width[, fillbyte])
@anchor{library/stdtypes bytearray rjust}@anchor{17eb}
@deffnx {方法} bytearray.rjust (width[, fillbyte])

返回原对象的副本，在长度为 @emph{width} 的序列中靠右对齐。 使用指定的 @emph{fillbyte} 填充空位（默认使用 ASCII 空格符）。 对于 @ref{172,,bytes} 对象，如果 @emph{width} 小于等于 @code{len(s)} 则返回原序列的副本。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex rsplit() (bytes 方法)
@geindex rsplit() (bytearray 方法)
@anchor{library/stdtypes bytes rsplit}@anchor{17ec}
@deffn {方法} bytes.rsplit (sep=None, maxsplit=-1)
@anchor{library/stdtypes bytearray rsplit}@anchor{17ed}
@deffnx {方法} bytearray.rsplit (sep=None, maxsplit=-1)

将二进制序列拆分为相同类型的子序列，使用 @emph{sep} 作为分隔符。 如果给出了 @emph{maxsplit}，则最多进行 @emph{maxsplit} 次拆分，从 @emph{最右边} 开始。 如果 @emph{sep} 未指定或为 @code{None}，任何只包含 ASCII 空白符的子序列都会被作为分隔符。 除了从右边开始拆分，@ref{17ed,,rsplit()} 的其他行为都类似于下文所述的 @ref{17ee,,split()}。
@end deffn

@geindex rstrip() (bytes 方法)
@geindex rstrip() (bytearray 方法)
@anchor{library/stdtypes bytes rstrip}@anchor{17ef}
@deffn {方法} bytes.rstrip ([chars])
@anchor{library/stdtypes bytearray rstrip}@anchor{17f0}
@deffnx {方法} bytearray.rstrip ([chars])

返回原序列的副本，移除指定的末尾字节。 @emph{chars} 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除 ASCII 空白符。 @emph{chars} 参数并非指定单个后缀；而是会移除参数值的所有组合:

@example
>>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
@end example

要移除的二进制序列可以是任意 @ref{6e9,,bytes-like object} 。 要删除单个后缀字符串，而不是全部给定集合中的字符，请参见 @ref{167,,str.removesuffix()} 方法。 例如:

@example
>>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
@end example

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex split() (bytes 方法)
@geindex split() (bytearray 方法)
@anchor{library/stdtypes bytes split}@anchor{17f1}
@deffn {方法} bytes.split (sep=None, maxsplit=-1)
@anchor{library/stdtypes bytearray split}@anchor{17ee}
@deffnx {方法} bytearray.split (sep=None, maxsplit=-1)

将二进制序列拆分为相同类型的子序列，使用 @emph{sep} 作为分隔符。 如果给出了 @emph{maxsplit} 且非负值，则最多进行 @emph{maxsplit} 次拆分（因此，列表最多会有 @code{maxsplit+1} 个元素）。 如果 @emph{maxsplit} 未指定或为 @code{-1}，则不限制拆分次数（进行所有可能的拆分）。

如果给出了 @emph{sep}，则连续的分隔符不会被组合在一起而是被视为分隔空子序列 (例如 @code{b'1,,2'.split(b',')} 将返回 @code{[b'1', b'@w{'}, b'2']})。 @emph{sep} 参数可能为一个多字节序列 (例如 @code{b'1<>2<>3'.split(b'<>')} 将返回 @code{[b'1', b'2', b'3']})。 使用指定的分隔符拆分空序列将返回 @code{[b'@w{'}]} 或 @code{[bytearray(b'@w{'})]}，具体取决于被拆分对象的类型。 @emph{sep} 参数可以是任意 @ref{6e9,,bytes-like object}。

例如:

@example
>>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'@w{'}, b'3', b'@w{'}]
@end example

如果 @emph{sep} 未指定或为 @code{None}，则会应用另一种拆分算法：连续的 ASCII 空白符会被视为单个分隔符，其结果将不包含序列开头或末尾的空白符。 因此，在不指定分隔符的情况下对空序列或仅包含 ASCII 空白符的序列进行拆分将返回 @code{[]}。

例如:

@example
>>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']
@end example
@end deffn

@geindex strip() (bytes 方法)
@geindex strip() (bytearray 方法)
@anchor{library/stdtypes bytes strip}@anchor{17f2}
@deffn {方法} bytes.strip ([chars])
@anchor{library/stdtypes bytearray strip}@anchor{17f3}
@deffnx {方法} bytearray.strip ([chars])

返回原序列的副本，移除指定的开头和末尾字节。 @emph{chars} 参数为指定要移除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如果省略或为 @code{None}，则 @emph{chars} 参数默认移除 ASCII 空白符。 @emph{chars} 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:

@example
>>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
@end example

要移除的字节值二进制序列可以是任意 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

以下 bytes 和 bytearray 对象的方法会假定使用兼容 ASCII 的二进制格式，不应当被应用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 @emph{不是} 原地执行操作，而是会产生新的对象。

@geindex capitalize() (bytes 方法)
@geindex capitalize() (bytearray 方法)
@anchor{library/stdtypes bytes capitalize}@anchor{17f4}
@deffn {方法} bytes.capitalize ()
@anchor{library/stdtypes bytearray capitalize}@anchor{17f5}
@deffnx {方法} bytearray.capitalize ()

返回原序列的副本，其中每个字节将都将被解读为一个 ASCII 字符，并且第一个字节的字符大写而其余的小写。 非 ASCII 字节值将保持原样不变。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex expandtabs() (bytes 方法)
@geindex expandtabs() (bytearray 方法)
@anchor{library/stdtypes bytes expandtabs}@anchor{17f6}
@deffn {方法} bytes.expandtabs (tabsize=8)
@anchor{library/stdtypes bytearray expandtabs}@anchor{17f7}
@deffnx {方法} bytearray.expandtabs (tabsize=8)

返回序列的副本，其中所有的 ASCII 制表符会由一个或多个 ASCII 空格替换，具体取决于当前列位置和给定的制表符宽度。 每 @emph{tabsize} 个字节设为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开序列，当前列位置将被设为零并逐一检查序列中的每个字节。 如果字节为 ASCII 制表符 (@code{b'\t'})，则并在结果中插入一个或多个空格符，直到当前列等于下一个制表位。 （制表符本身不会被复制。） 如果当前字节为 ASCII 换行符 (@code{b'\n'}) 或回车符 (@code{b'\r'})，它会被复制并将当前列重设为零。 任何其他字节会被不加修改地复制并将当前列加一，不论该字节值在被打印时会如何显示:

@example
>>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'
@end example

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex isalnum() (bytes 方法)
@geindex isalnum() (bytearray 方法)
@anchor{library/stdtypes bytes isalnum}@anchor{17f8}
@deffn {方法} bytes.isalnum ()
@anchor{library/stdtypes bytearray isalnum}@anchor{17f9}
@deffnx {方法} bytearray.isalnum ()

如果序列中所有字节都是字母类 ASCII 字符或 ASCII 十进制数码并且序列非空则返回 @code{True} ，否则返回 @code{False} 。 字母类 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。 ASCII 十进制数码就是字节值包含在序列 @code{b'0123456789'} 中的字符。

例如:

@example
>>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False
@end example
@end deffn

@geindex isalpha() (bytes 方法)
@geindex isalpha() (bytearray 方法)
@anchor{library/stdtypes bytes isalpha}@anchor{17fa}
@deffn {方法} bytes.isalpha ()
@anchor{library/stdtypes bytearray isalpha}@anchor{17fb}
@deffnx {方法} bytearray.isalpha ()

如果序列中所有字节都是字母类 ASCII 字符并且序列不非空则返回 @code{True} ，否则返回 @code{False} 。 字母类 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。

例如:

@example
>>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False
@end example
@end deffn

@geindex isascii() (bytes 方法)
@geindex isascii() (bytearray 方法)
@anchor{library/stdtypes bytes isascii}@anchor{17fc}
@deffn {方法} bytes.isascii ()
@anchor{library/stdtypes bytearray isascii}@anchor{17fd}
@deffnx {方法} bytearray.isascii ()

如果序列为空或序列中所有字节都是 ASCII 字节则返回 @code{True} ，否则返回 @code{False} 。 ASCII 字节的取值范围是 0-0x7F。


3.7 新版功能.

@end deffn

@geindex isdigit() (bytes 方法)
@geindex isdigit() (bytearray 方法)
@anchor{library/stdtypes bytes isdigit}@anchor{17fe}
@deffn {方法} bytes.isdigit ()
@anchor{library/stdtypes bytearray isdigit}@anchor{17ff}
@deffnx {方法} bytearray.isdigit ()

如果序列中所有字节都是 ASCII 十进制数码并且序列非空则返回 @code{True} ，否则返回 @code{False} 。 ASCII 十进制数码就是字节值包含在序列 @code{b'0123456789'} 中的字符。

例如:

@example
>>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False
@end example
@end deffn

@geindex islower() (bytes 方法)
@geindex islower() (bytearray 方法)
@anchor{library/stdtypes bytes islower}@anchor{1800}
@deffn {方法} bytes.islower ()
@anchor{library/stdtypes bytearray islower}@anchor{1801}
@deffnx {方法} bytearray.islower ()

如果序列中至少有一个小写的 ASCII 字符并且没有大写的 ASCII 字符则返回 @code{True} ，否则返回 @code{False} 。

例如:

@example
>>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。
@end deffn

@geindex isspace() (bytes 方法)
@geindex isspace() (bytearray 方法)
@anchor{library/stdtypes bytes isspace}@anchor{1802}
@deffn {方法} bytes.isspace ()
@anchor{library/stdtypes bytearray isspace}@anchor{1803}
@deffnx {方法} bytearray.isspace ()

如果序列中所有字节都是 ASCII 空白符并且序列非空则返回 @code{True} ，否则返回 @code{False} 。 ASCII 空白符就是字节值包含在序列 @code{b' \t\n\r\x0b\f'} (空格, 制表, 换行, 回车, 垂直制表, 进纸) 中的字符。
@end deffn

@geindex istitle() (bytes 方法)
@geindex istitle() (bytearray 方法)
@anchor{library/stdtypes bytes istitle}@anchor{1804}
@deffn {方法} bytes.istitle ()
@anchor{library/stdtypes bytearray istitle}@anchor{1805}
@deffnx {方法} bytearray.istitle ()

如果序列为 ASCII 标题大小写形式并且序列非空则返回 @code{True} ，否则返回 @code{False} 。 请参阅 @ref{1806,,bytes.title()} 了解有关“标题大小写”的详细定义。

例如:

@example
>>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False
@end example
@end deffn

@geindex isupper() (bytes 方法)
@geindex isupper() (bytearray 方法)
@anchor{library/stdtypes bytes isupper}@anchor{1807}
@deffn {方法} bytes.isupper ()
@anchor{library/stdtypes bytearray isupper}@anchor{1808}
@deffnx {方法} bytearray.isupper ()

如果序列中至少有一个大写字母 ASCII 字符并且没有小写 ASCII 字符则返回 @code{True} ，否则返回 @code{False} 。

例如:

@example
>>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。
@end deffn

@geindex lower() (bytes 方法)
@geindex lower() (bytearray 方法)
@anchor{library/stdtypes bytes lower}@anchor{1809}
@deffn {方法} bytes.lower ()
@anchor{library/stdtypes bytearray lower}@anchor{180a}
@deffnx {方法} bytearray.lower ()

返回原序列的副本，其所有大写 ASCII 字符均转换为对应的小写形式。

例如:

@example
>>> b'Hello World'.lower()
b'hello world'
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex universal newlines; bytes.splitlines method
@geindex universal newlines; bytearray.splitlines method

@geindex splitlines() (bytes 方法)
@geindex splitlines() (bytearray 方法)
@anchor{library/stdtypes bytes splitlines}@anchor{180b}
@deffn {方法} bytes.splitlines (keepends=False)
@anchor{library/stdtypes bytearray splitlines}@anchor{180c}
@deffnx {方法} bytearray.splitlines (keepends=False)

返回由原二进制序列中各行组成的列表，在 ASCII 行边界符的位置拆分。 此方法使用 @ref{6f5,,universal newlines} 方式来分行。 结果列表中不包含换行符，除非给出了 @emph{keepends} 且为真值。

例如:

@example
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'@w{'}, b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
@end example

不同于 @ref{17f1,,split()}，当给出了分隔符 @emph{sep} 时，对于空字符串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

@example
>>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b'@w{'}], [b'Two lines', b'@w{'}])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])
@end example
@end deffn

@geindex swapcase() (bytes 方法)
@geindex swapcase() (bytearray 方法)
@anchor{library/stdtypes bytes swapcase}@anchor{180d}
@deffn {方法} bytes.swapcase ()
@anchor{library/stdtypes bytearray swapcase}@anchor{180e}
@deffnx {方法} bytearray.swapcase ()

返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式，反之亦反。

例如:

@example
>>> b'Hello World'.swapcase()
b'hELLO wORLD'
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。

不同于 @ref{17be,,str.swapcase()}，在些二进制版本下 @code{bin.swapcase().swapcase() == bin} 总是成立。 大小写转换在 ASCII 中是对称的，即使其对于任意 Unicode 码位来说并不总是成立。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex title() (bytes 方法)
@geindex title() (bytearray 方法)
@anchor{library/stdtypes bytes title}@anchor{1806}
@deffn {方法} bytes.title ()
@anchor{library/stdtypes bytearray title}@anchor{180f}
@deffnx {方法} bytearray.title ()

返回原二进制序列的标题版本，其中每个单词以一个大写 ASCII 字符为开头，其余字母为小写。 不区别大小写的字节值将保持原样不变。

例如:

@example
>>> b'Hello world'.title()
b'Hello World'
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。 所有其他字节值都不区分大小写。

该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也会成为单词边界，这可能导致不希望的结果:

@example
>>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
@end example

可以使用正则表达式来构建针对撇号的特别处理:

@example
>>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
@end example

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex upper() (bytes 方法)
@geindex upper() (bytearray 方法)
@anchor{library/stdtypes bytes upper}@anchor{1810}
@deffn {方法} bytes.upper ()
@anchor{library/stdtypes bytearray upper}@anchor{1811}
@deffnx {方法} bytearray.upper ()

返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式。

例如:

@example
>>> b'Hello World'.upper()
b'HELLO WORLD'
@end example

小写 ASCII 字符就是字节值包含在序列 @code{b'abcdefghijklmnopqrstuvwxyz'} 中的字符。 大写 ASCII 字符就是字节值包含在序列 @code{b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'} 中的字符。

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@geindex zfill() (bytes 方法)
@geindex zfill() (bytearray 方法)
@anchor{library/stdtypes bytes zfill}@anchor{1812}
@deffn {方法} bytes.zfill (width)
@anchor{library/stdtypes bytearray zfill}@anchor{1813}
@deffnx {方法} bytearray.zfill (width)

返回原序列的副本，在左边填充 @code{b'0'} 数码使序列长度为 @emph{width}。 正负值前缀 (@code{b'+'}/ @code{b'-'}) 的处理方式是在正负符号 @emph{之后} 填充而非在之前。 对于 @ref{172,,bytes} 对象，如果 @emph{width} 小于等于 @code{len(seq)} 则返回原序列。

例如:

@example
>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
@end example

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche
@end deffn

@node printf 风格的字节串格式化,内存视图,bytes 和 bytearray 操作,二进制序列类型 --- bytes bytearray memoryview
@anchor{library/stdtypes bytes-formatting}@anchor{74d}@anchor{library/stdtypes printf-style-bytes-formatting}@anchor{1814}
@subsubsection @code{printf} 风格的字节串格式化


@geindex formatting; bytes (%)
@geindex formatting; bytearray (%)
@geindex interpolation; bytes (%)
@geindex interpolation; bytearray (%)
@geindex bytes; formatting
@geindex bytearray; formatting
@geindex bytes; interpolation
@geindex bytearray; interpolation
@geindex printf-style formatting
@geindex sprintf-style formatting
@geindex % (percent); printf-style formatting

@cartouche
@quotation 注解 
此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（例如无法正确显示元组和字典）。 如果要打印的值可能为元组或字典，请将其放入一个元组中。
@end quotation
@end cartouche

字节串对象 (@code{bytes}/@code{bytearray}) 具有一种特殊的内置操作：使用 @code{%} (取模) 运算符。 这也被称为字节串的 @emph{格式化} 或 @emph{插值} 运算符。 对于 @code{format % values} (其中 @emph{format} 为一个字节串对象)，在 @emph{format} 中的 @code{%} 转换标记符将被替换为零个或多个 @emph{values} 条目。 其效果类似于在 C 语言中使用 @code{sprintf()}。

如果 @emph{format} 要求一个单独参数，则 @emph{values} 可以为一个非元组对象。 @footnote{@w{(5)} 
要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元素就是要被格式化的元组。
}  否则的话，@emph{values} 必须或是是一个包含项数与格式字节串对象中指定的转换符项数相同的元组，或者是一个单独的映射对象（例如元组）。

@geindex () (parentheses); in printf-style formatting
@geindex * (asterisk); in printf-style formatting
@geindex . (dot); in printf-style formatting

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：


@enumerate 

@item 
@code{'%'} 字符，用于标记转换符的起始。

@item 
映射键（可选），由加圆括号的字符序列组成 (例如 @code{(somename)})。

@item 
转换旗标（可选），用于影响某些转换类型的结果。

@item 
最小字段宽度（可选）。 如果指定为 @code{'*'} (星号)，则实际宽度会从 @emph{values} 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的精度之后的元素。

@item 
精度（可选），以在 @code{'.'} (点号) 之后加精度值的形式给出。 如果指定为 @code{'*'} (星号)，则实际精度会从 @emph{values} 元组的下一元素中读取，要转换的对象则为精度之后的元素。

@item 
长度修饰符（可选）。

@item 
转换类型。
@end enumerate

当右边的参数为一个字典（或其他映射类型）时，字节串对象中的格式 @emph{必须} 包含加圆括号的映射键，对应 @code{'%'} 字符之后字典中的每一项。 映射键将从映射中选取要格式化的值。 例如：

@example
>>> print(b'%(language)s has %(number)03d quote types.' %
...       @{b'language': b"Python", b"number": 2@})
b'Python has 002 quote types.'
@end example

在此情况下格式中不能出现 @code{*} 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

@geindex # (hash); in printf-style formatting
@geindex - (minus); in printf-style formatting
@geindex + (plus); in printf-style formatting
@geindex space; in printf-style formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标志

@tab

含义

@item

@code{'#'}

@tab

值的转换将使用“替代形式”（具体定义见下文）。

@item

@code{'0'}

@tab

转换将为数字值填充零字符。

@item

@code{'-'}

@tab

转换值将靠左对齐（如果同时给出 @code{'0'} 转换，则会覆盖后者）。

@item

@code{' '}

@tab

(空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。

@item

@code{'+'}

@tab

符号字符 (@code{'+'} 或 @code{'-'}) 将显示于转换结果的开头（会覆盖 "空格" 旗标）。

@end multitable


可以给出长度修饰符 (@code{h}, @code{l} 或 @code{L})，但会被忽略，因为对 Python 来说没有必要 -- 所以 @code{%ld} 等价于 @code{%d}。

转换类型为：


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

转换符

@tab

含义

@tab

注释

@item

@code{'d'}

@tab

有符号十进制整数。

@tab

@item

@code{'i'}

@tab

有符号十进制整数。

@tab

@item

@code{'o'}

@tab

有符号八进制数。

@tab

(1)

@item

@code{'u'}

@tab

过时类型 -- 等价于 @code{'d'}。

@tab

(8)

@item

@code{'x'}

@tab

有符号十六进制数（小写）。

@tab

(2)

@item

@code{'X'}

@tab

有符号十六进制数（大写）。

@tab

(2)

@item

@code{'e'}

@tab

浮点指数格式（小写）。

@tab

(3)

@item

@code{'E'}

@tab

浮点指数格式（大写）。

@tab

(3)

@item

@code{'f'}

@tab

浮点十进制格式。

@tab

(3)

@item

@code{'F'}

@tab

浮点十进制格式。

@tab

(3)

@item

@code{'g'}

@tab

浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格式，否则使用十进制格式。

@tab

(4)

@item

@code{'G'}

@tab

浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格式，否则使用十进制格式。

@tab

(4)

@item

@code{'c'}

@tab

单个字节（接受整数或单个字节对象）。

@tab

@item

@code{'b'}

@tab

字节串（任何遵循 @ref{174c,,缓冲区协议} 或是具有 @ref{1599,,__bytes__()} 的对象）。

@tab

(5)

@item

@code{'s'}

@tab

@code{'s'} 是 @code{'b'} 的一个别名，只应当在基于 Python2/3 的代码中使用。

@tab

(6)

@item

@code{'a'}

@tab

字节串（使用 @code{repr(obj).encode('ascii', 'backslashreplace')} 来转换任意 Python 对象）。

@tab

(5)

@item

@code{'r'}

@tab

@code{'r'} 是 @code{'a'} 的一个别名，只应当在基于 Python2/3 的代码中使用。

@tab

(7)

@item

@code{'%'}

@tab

不转换参数，在结果中输出一个 @code{'%'} 字符。

@tab

@end multitable


注释:


@enumerate 

@item 
此替代形式会在第一个数码之前插入标示八进制数的前缀 (@code{'0o'})。

@item 
此替代形式会在第一个数码之前插入 @code{'0x'} 或 @code{'0X'} 前缀（取决于是使用 @code{'x'} 还是 @code{'X'} 格式）。

@item 
此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

小数点后的数码位数由精度决定，默认为 6。

@item 
此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况下那样被移除。

小数点前后的有效数码位数由精度决定，默认为 6。

@item 
如果精度为 @code{N}，输出将截短为 @code{N} 个字符。

@item 
@code{b'%s'} 已弃用，但在 3.x 系列中将不会被移除。

@item 
@code{b'%r'} 已弃用，但在 3.x 系列中将不会被移除。

@item 
参见 
@geindex Python 提高建议; PEP 237
PEP 237@footnote{https://www.python.org/dev/peps/pep-0237}。
@end enumerate

@cartouche
@quotation 注解 
此方法的 bytearray 版本 @emph{并非} 原地操作 —— 它总是产生一个新对象，即便没有做任何改变。
@end quotation
@end cartouche


@subsubheading 参见


@geindex Python 提高建议; PEP 461
PEP 461@footnote{https://www.python.org/dev/peps/pep-0461} - 为 bytes 和 bytearray 添加 % 格式化



3.5 新版功能.


@node 内存视图,,printf 风格的字节串格式化,二进制序列类型 --- bytes bytearray memoryview
@anchor{library/stdtypes memory-views}@anchor{1815}@anchor{library/stdtypes typememoryview}@anchor{175b}
@subsubsection 内存视图


@ref{38d,,memoryview} 对象允许 Python 代码访问一个对象的内部数据，只要该对象支持 @ref{174c,,缓冲区协议} 而无需进行拷贝。

@geindex memoryview (內置类)
@anchor{library/stdtypes memoryview}@anchor{38d}
@deffn {类} memoryview (object)

创建一个引用 @emph{object} 的 @ref{38d,,memoryview} 。 @emph{object} 必须支持缓冲区协议。支持缓冲区协议的内置对象有 @ref{172,,bytes} 和 @ref{173,,bytearray} 。

@ref{38d,,memoryview} 有 @strong{元素} 的概念， @strong{元素} 指由原始 @emph{object} 处理的原子内存单元。对于许多简单的类型，如 @ref{172,,bytes} 和 @ref{173,,bytearray} ，一个元素是一个字节，但其他类型，如 @ref{217,,array.array} 可能有更大的元素。

@code{len(view)} 与 @ref{1816,,tolist} 的长度相等。 如果 @code{view.ndim = 0}，则其长度为 1。 如果 @code{view.ndim = 1}，则其长度等于 view 中元素的数量。 对于更高的维度，其长度等于表示 view 的嵌套列表的长度。 @ref{1817,,itemsize} 属性可向你给出单个元素所占的字节数。

@ref{38d,,memoryview} 支持通过切片和索引访问其元素。 一维切片的结果将是一个子视图:

@example
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'
@end example

如果 @ref{1818,,format} 是一个来自于 @ref{f8,,struct} 模块的原生格式说明符，则也支持使用整数或由整数构成的元组进行索引，并返回具有正确类型的单个 @emph{元素}。 一维内存视图可以使用一个整数或由一个整数构成的元组进行索引。 多维内存视图可以使用由恰好 @emph{ndim} 个整数构成的元素进行索引，@emph{ndim} 即其维度。 零维内存视图可以使用空元组进行索引。

这里是一个使用非字节格式的例子:

@example
>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]
@end example

如果下层对象是可写的，则内存视图支持一维切片赋值。 改变大小则不被允许:

@example
>>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')
@end example

由带有格式符号 'B', 'b' 或 'c' 的可哈希（只读）类型构成的一维内存视图同样是可哈希的。 哈希定义为 @code{hash(m) == hash(m.tobytes())}:

@example
>>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True
@end example


在 3.3 版更改: 一维内存视图现在可以被切片。 带有格式符号 'B', 'b' 或 'c' 的一维内存视图现在是可哈希的。



在 3.4 版更改: 内存视图现在会自动注册为 @ref{1794,,collections.abc.Sequence}



在 3.5 版更改: 内存视图现在可使用整数元组进行索引。


@ref{38d,,memoryview} 具有以下一些方法：

@geindex __eq__() (memoryview 方法)
@anchor{library/stdtypes memoryview __eq__}@anchor{1819}
@deffn {方法} __eq__ (exporter)

memoryview 与 
@geindex Python 提高建议; PEP 3118
PEP 3118@footnote{https://www.python.org/dev/peps/pep-3118} 中的导出器这两者如果形状相同，并且如果当使用 @ref{f8,,struct} 语法解读操作数的相应格式代码时所有对应值都相同，则它们就是等价的。

对于 @ref{1816,,tolist()} 当前所支持的 @ref{f8,,struct} 格式字符串子集，如果 @code{v.tolist() == w.tolist()} 则 @code{v} 和 @code{w} 相等:

@example
>>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True
@end example

如果两边的格式字符串都不被 @ref{f8,,struct} 模块所支持，则两对象比较结果总是不相等（即使格式字符串和缓冲区内容相同）:

@example
>>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
...     _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False
@end example

请注意，与浮点数的情况一样，对于内存视图对象来说，@code{v is w} 也 @emph{并不} 意味着 @code{v == w}。


在 3.3 版更改: 之前的版本比较原始内存时会忽略条目的格式与逻辑数组结构。

@end deffn

@geindex tobytes() (memoryview 方法)
@anchor{library/stdtypes memoryview tobytes}@anchor{181a}
@deffn {方法} tobytes (order=None)

将缓冲区中的数据作为字节串返回。 这相当于在内存视图上调用 @ref{172,,bytes} 构造器。

@example
>>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'
@end example

对于非连续数组，结果等于平面化表示的列表，其中所有元素都转换为字节串。 @ref{181a,,tobytes()} 支持所有格式字符串，不符合 @ref{f8,,struct} 模块语法的那些也包括在内。


3.8 新版功能: @emph{order} 可以为 @{'C', 'F', 'A'@}。 当 @emph{order} 为 'C' 或 'F' 时，原始数组的数据会被转换至 C 或 Fortran 顺序。 对于连续视图，'A' 会返回物理内存的精确副本。 特别地，内存中的 Fortran 顺序会被保留。对于非连续视图，数据会先被转换为 C 形式。 @emph{order=None} 与 @emph{order='C'} 是相同的。

@end deffn

@geindex hex() (memoryview 方法)
@anchor{library/stdtypes memoryview hex}@anchor{730}
@deffn {方法} hex ([sep[, bytes_per_sep]])

返回一个字符串对象，其中分别以两个十六进制数码表示缓冲区里的每个字节。

@example
>>> m = memoryview(b"abc")
>>> m.hex()
'616263'
@end example


3.5 新版功能.



在 3.8 版更改: 与 @ref{72e,,bytes.hex()} 相似， @ref{730,,memoryview.hex()} 现在支持可选的 @emph{sep} 和 @emph{bytes_per_sep} 参数以在十六进制输出的字节之间插入分隔符。

@end deffn

@geindex tolist() (memoryview 方法)
@anchor{library/stdtypes memoryview tolist}@anchor{1816}
@deffn {方法} tolist ()

将缓冲区内的数据以一个元素列表的形式返回。

@example
>>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]
@end example


在 3.3 版更改: @ref{1816,,tolist()} 现在支持 @ref{f8,,struct} 模块语法中的所有单字符原生格式以及多维表示形式。

@end deffn

@geindex toreadonly() (memoryview 方法)
@anchor{library/stdtypes memoryview toreadonly}@anchor{181b}
@deffn {方法} toreadonly ()

返回 memoryview 对象的只读版本。 原始的 memoryview 对象不会被改变。

@example
>>> m = memoryview(bytearray(b'abc'))
>>> mm = m.toreadonly()
>>> mm.tolist()
[89, 98, 99]
>>> mm[0] = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> m[0] = 43
>>> mm.tolist()
[43, 98, 99]
@end example


3.8 新版功能.

@end deffn

@geindex release() (memoryview 方法)
@anchor{library/stdtypes memoryview release}@anchor{c18}
@deffn {方法} release ()

释放由内存视图对象所公开的底层缓冲区。 许多对象在被视图所获取时都会采取特殊动作（例如，@ref{173,,bytearray} 将会暂时禁止调整大小）；因此，调用 release() 可以方便地尽早去除这些限制（并释放任何多余的资源）。

在此方法被调用后，任何对视图的进一步操作将引发 @ref{16d,,ValueError} (@ref{c18,,release()} 本身除外，它可以被多次调用):

@example
>>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
@end example

使用 @code{with} 语句，可以通过上下文管理协议达到类似的效果:

@example
>>> with memoryview(b'abc') as m:
...     m[0]
...
97
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object
@end example


3.2 新版功能.

@end deffn

@geindex cast() (memoryview 方法)
@anchor{library/stdtypes memoryview cast}@anchor{181c}
@deffn {方法} cast (format[, shape])

将内存视图转化为新的格式或形状。 @emph{shape} 默认为 @code{[byte_length//new_itemsize]}，这意味着结果视图将是一维的。 返回值是一个新的内存视图，但缓冲区本身不会被复制。 支持的转化有 1D -> C-@ref{181d,,contiguous} 和 C-contiguous -> 1D。

目标格式仅限于 @ref{f8,,struct} 语法中的单一元素原生格式。 其中一种格式必须为字节格式 ('B', 'b' 或 'c')。 结果的字节长度必须与原始长度相同。

将 1D/long 转换为 1D/unsigned bytes:

@example
>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24
@end example

将 1D/unsigned bytes 转换为 1D/char:

@example
>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview: invalid value for format "B"
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')
@end example

将 1D/bytes 转换为 3D/ints 再转换为 1D/signed char:

@example
>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48
@end example

将 1D/unsigned long 转换为 2D/unsigned long:

@example
>>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]
@end example


3.3 新版功能.



在 3.5 版更改: 当转换为字节视图时，源格式将不再受限。

@end deffn

还存在一些可用的只读属性：

@geindex obj (memoryview 属性)
@anchor{library/stdtypes memoryview obj}@anchor{181e}
@deffn {属性} obj

内存视图的下层对象:

@example
>>> b  = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True
@end example


3.3 新版功能.

@end deffn

@geindex nbytes (memoryview 属性)
@anchor{library/stdtypes memoryview nbytes}@anchor{181f}
@deffn {属性} nbytes

@code{nbytes == product(shape) * itemsize == len(m.tobytes())}。 这是数组在连续表示时将会占用的空间总字节数。 它不一定等于 @code{len(m)}:

@example
>>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12
@end example

多维数组:

@example
>>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96
@end example


3.3 新版功能.

@end deffn

@geindex readonly (memoryview 属性)
@anchor{library/stdtypes memoryview readonly}@anchor{1820}
@deffn {属性} readonly

一个表明内存是否只读的布尔值。
@end deffn

@geindex format (memoryview 属性)
@anchor{library/stdtypes memoryview format}@anchor{1818}
@deffn {属性} format

一个字符串，包含视图中每个元素的格式（表示为 @ref{f8,,struct} 模块样式）。 内存视图可以从具有任意格式字符串的导出器创建，但某些方法 (例如 @ref{1816,,tolist()}) 仅限于原生的单元素格式。


在 3.3 版更改: 格式 @code{'B'} 现在会按照 struct 模块语法来处理。 这意味着 @code{memoryview(b'abc')[0] == b'abc'[0] == 97}。

@end deffn

@geindex itemsize (memoryview 属性)
@anchor{library/stdtypes memoryview itemsize}@anchor{1817}
@deffn {属性} itemsize

memoryview 中每个元素以字节表示的大小:

@example
>>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True
@end example
@end deffn

@geindex ndim (memoryview 属性)
@anchor{library/stdtypes memoryview ndim}@anchor{1821}
@deffn {属性} ndim

一个整数，表示内存所代表的多维数组具有多少个维度。
@end deffn

@geindex shape (memoryview 属性)
@anchor{library/stdtypes memoryview shape}@anchor{1822}
@deffn {属性} shape

一个整数元组，通过 @ref{1821,,ndim} 的长度值给出内存所代表的 N 维数组的形状。


在 3.3 版更改: 当 ndim = 0 时值为空元组而不再为 @code{None}。

@end deffn

@geindex strides (memoryview 属性)
@anchor{library/stdtypes memoryview strides}@anchor{1823}
@deffn {属性} strides

一个整数元组，通过 @ref{1821,,ndim} 的长度给出以字节表示的大小，以便访问数组中每个维度上的每个元素。


在 3.3 版更改: 当 ndim = 0 时值为空元组而不再为 @code{None}。

@end deffn

@geindex suboffsets (memoryview 属性)
@anchor{library/stdtypes memoryview suboffsets}@anchor{1824}
@deffn {属性} suboffsets

供 PIL 风格的数组内部使用。 该值仅作为参考信息。
@end deffn

@geindex c_contiguous (memoryview 属性)
@anchor{library/stdtypes memoryview c_contiguous}@anchor{1825}
@deffn {属性} c_contiguous

一个表明内存是否为 C-@ref{181d,,contiguous} 的布尔值。


3.3 新版功能.

@end deffn

@geindex f_contiguous (memoryview 属性)
@anchor{library/stdtypes memoryview f_contiguous}@anchor{1826}
@deffn {属性} f_contiguous

一个表明内存是否为 Fortran @ref{181d,,contiguous} 的布尔值。


3.3 新版功能.

@end deffn

@geindex contiguous (memoryview 属性)
@anchor{library/stdtypes memoryview contiguous}@anchor{1827}
@deffn {属性} contiguous

一个表明内存是否为 @ref{181d,,contiguous} 的布尔值。


3.3 新版功能.

@end deffn
@end deffn

@node 集合类型 --- set frozenset,映射类型 --- dict,二进制序列类型 --- bytes bytearray memoryview,内置类型
@anchor{library/stdtypes set-types-set-frozenset}@anchor{1828}@anchor{library/stdtypes types-set}@anchor{1758}
@subsection 集合类型 --- @code{set}, @code{frozenset}


@geindex 对象; set

@emph{set} 对象是由具有唯一性的 @ref{277,,hashable} 对象所组成的无序多项集。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算，例如交集、并集、差集与对称差集等等。 （关于其他容器对象请参看 @ref{164,,dict}, @ref{1f9,,list} 与 @ref{1a2,,tuple} 等内置类，以及 @ref{1d,,collections} 模块。）

与其他多项集一样，集合也支持 @code{x in set}, @code{len(set)} 和 @code{for x in set}。 作为一种无序的多项集，集合并不记录元素位置或插入顺序。 相应地，集合不支持索引、切片或其他序列类的操作。

目前有两种内置集合类型，@ref{1f7,,set} 和 @ref{1f8,,frozenset}。 @ref{1f7,,set} 类型是可变的 --- 其内容可以使用 @code{add()} 和 @code{remove()} 这样的方法来改变。 由于是可变类型，它没有哈希值，且不能被用作字典的键或其他集合的元素。 @ref{1f8,,frozenset} 类型是不可变并且为 @ref{277,,hashable} --- 其内容在被创建后不能再改变；因此它可以被用作字典的键或其他集合的元素。

除了可以使用 @ref{1f7,,set} 构造器，非空的 set (不是 frozenset) 还可以通过将以逗号分隔的元素列表包含于花括号之内来创建，例如: @code{@{'jack', 'sjoerd'@}}。

两个类的构造器具有相同的作用方式：

@geindex set (內置类)
@geindex frozenset (內置类)
@anchor{library/stdtypes set}@anchor{1f7}
@deffn {类} set ([iterable])
@anchor{library/stdtypes frozenset}@anchor{1f8}
@deffnx {类} frozenset ([iterable])

返回一个新的 set 或 frozenset 对象，其元素来自于 @emph{iterable}。 集合的元素必须为 @ref{277,,hashable}。 要表示由集合对象构成的集合，所有的内层集合必须为 @ref{1f8,,frozenset} 对象。 如果未指定 @emph{iterable}，则将返回一个新的空集合。

集合可用多种方式来创建:


@itemize *

@item 
使用花括号内以逗号分隔元素的方式: @code{@{'jack', 'sjoerd'@}}

@item 
使用集合推导式: @code{@{c for c in 'abracadabra' if c not in 'abc'@}}

@item 
使用类型构造器: @code{set()}, @code{set('foobar')}, @code{set(['a', 'b', 'foo'])}
@end itemize

@ref{1f7,,set} 和 @ref{1f8,,frozenset} 的实例提供以下操作：


@deffn {Describe} len(s)

返回集合 @emph{s} 中的元素数量（即 @emph{s} 的基数）。
@end deffn


@deffn {Describe} x in s

检测 @emph{x} 是否为 @emph{s} 中的成员。
@end deffn


@deffn {Describe} x not in s

检测 @emph{x} 是否非 @emph{s} 中的成员。
@end deffn

@geindex isdisjoint() (frozenset 方法)
@anchor{library/stdtypes frozenset isdisjoint}@anchor{1829}
@deffn {方法} isdisjoint (other)

如果集合中没有与 @emph{other} 共有的元素则返回 @code{True}。 当且仅当两个集合的交集为空集合时，两者为不相交集合。
@end deffn

@geindex issubset() (frozenset 方法)
@anchor{library/stdtypes frozenset issubset}@anchor{182a}
@deffn {方法} issubset (other)

@deffnx {方法} set <= other

检测是否集合中的每个元素都在 @emph{other} 之中。
@end deffn


@deffn {方法} set < other

检测集合是否为 @emph{other} 的真子集，即 @code{set <= other and set != other}。
@end deffn

@geindex issuperset() (frozenset 方法)
@anchor{library/stdtypes frozenset issuperset}@anchor{182b}
@deffn {方法} issuperset (other)

@deffnx {方法} set >= other

检测是否 @emph{other} 中的每个元素都在集合之中。
@end deffn


@deffn {方法} set > other

检测集合是否为 @emph{other} 的真超集，即 @code{set >= other and set != other}。
@end deffn

@geindex union() (frozenset 方法)
@anchor{library/stdtypes frozenset union}@anchor{182c}
@deffn {方法} union (*others)

@deffnx {方法} set | other | ...

返回一个新集合，其中包含来自原集合以及 others 指定的所有集合中的元素。
@end deffn

@geindex intersection() (frozenset 方法)
@anchor{library/stdtypes frozenset intersection}@anchor{182d}
@deffn {方法} intersection (*others)

@deffnx {方法} set & other & ...

返回一个新集合，其中包含原集合以及 others 指定的所有集合中共有的元素。
@end deffn

@geindex difference() (frozenset 方法)
@anchor{library/stdtypes frozenset difference}@anchor{182e}
@deffn {方法} difference (*others)

@deffnx {方法} set @w{-} other @w{-} ...

返回一个新集合，其中包含原集合中在 others 指定的其他集合中不存在的元素。
@end deffn

@geindex symmetric_difference() (frozenset 方法)
@anchor{library/stdtypes frozenset symmetric_difference}@anchor{182f}
@deffn {方法} symmetric_difference (other)

@deffnx {方法} set ^ other

返回一个新集合，其中的元素或属于原集合或属于 @emph{other} 指定的其他集合，但不能同时属于两者。
@end deffn

@geindex copy() (frozenset 方法)
@anchor{library/stdtypes frozenset copy}@anchor{1830}
@deffn {方法} copy ()

返回原集合的浅拷贝。
@end deffn

请注意，非运算符版本的 @ref{182c,,union()}, @ref{182d,,intersection()}, @ref{182e,,difference()}，以及 @ref{182f,,symmetric_difference()}, @ref{182a,,issubset()} 和 @ref{182b,,issuperset()} 方法会接受任意可迭代对象作为参数。 相比之下，它们所对应的运算符版本则要求其参数为集合。 这就排除了容易出错的构造形式例如 @code{set('abc') & 'cbs'}，而推荐可读性更强的 @code{set('abc').intersection('cbs')}。

@ref{1f7,,set} 和 @ref{1f8,,frozenset} 均支持集合与集合的比较。 两个集合当且仅当每个集合中的每个元素均包含于另一个集合之内（即各为对方的子集）时则相等。 一个集合当且仅当其为另一个集合的真子集（即为后者的子集但两者不相等）时则小于另一个集合。 一个集合当且仅当其为另一个集合的真超集（即为后者的超集但两者不相等）时则大于另一个集合。

@ref{1f7,,set} 的实例与 @ref{1f8,,frozenset} 的实例之间基于它们的成员进行比较。 例如 @code{set('abc') == frozenset('abc')} 返回 @code{True}，@code{set('abc') in set([frozenset('abc')])} 也一样。

子集与相等比较并不能推广为完全排序函数。 例如，任意两个非空且不相交的集合不相等且互不为对方的子集，因此以下 @emph{所有} 比较均返回 @code{False}: @code{a<b}, @code{a==b}, or @code{a>b}。

由于集合仅定义了部分排序（子集关系），因此由集合构成的列表 @ref{550,,list.sort()} 方法的输出并无定义。

集合的元素，与字典的键类似，必须为 @ref{277,,hashable}。

混合了 @ref{1f7,,set} 实例与 @ref{1f8,,frozenset} 的二进制位运算将返回与第一个操作数相同的类型。例如: @code{frozenset('ab') | set('bc')} 将返回 @ref{1f8,,frozenset} 的实例。

下表列出了可用于 @ref{1f7,,set} 而不能用于不可变的 @ref{1f8,,frozenset} 实例的操作：

@geindex update() (frozenset 方法)
@anchor{library/stdtypes frozenset update}@anchor{1831}
@deffn {方法} update (*others)

@deffnx {方法} set |= other | ...

更新集合，添加来自 others 中的所有元素。
@end deffn

@geindex intersection_update() (frozenset 方法)
@anchor{library/stdtypes frozenset intersection_update}@anchor{1832}
@deffn {方法} intersection_update (*others)

@deffnx {方法} set &= other & ...

更新集合，只保留其中在所有 others 中也存在的元素。
@end deffn

@geindex difference_update() (frozenset 方法)
@anchor{library/stdtypes frozenset difference_update}@anchor{1833}
@deffn {方法} difference_update (*others)

@deffnx {方法} set @w{-}= other | ...

更新集合，移除其中也存在于 others 中的元素。
@end deffn

@geindex symmetric_difference_update() (frozenset 方法)
@anchor{library/stdtypes frozenset symmetric_difference_update}@anchor{1834}
@deffn {方法} symmetric_difference_update (other)

@deffnx {方法} set ^= other

更新集合，只保留存在于集合的一方而非共同存在的元素。
@end deffn

@geindex add() (frozenset 方法)
@anchor{library/stdtypes frozenset add}@anchor{1835}
@deffn {方法} add (elem)

将元素 @emph{elem} 添加到集合中。
@end deffn

@geindex remove() (frozenset 方法)
@anchor{library/stdtypes frozenset remove}@anchor{1836}
@deffn {方法} remove (elem)

从集合中移除元素 @emph{elem}。 如果 @emph{elem} 不存在于集合中则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex discard() (frozenset 方法)
@anchor{library/stdtypes frozenset discard}@anchor{1837}
@deffn {方法} discard (elem)

如果元素 @emph{elem} 存在于集合中则将其移除。
@end deffn

@geindex pop() (frozenset 方法)
@anchor{library/stdtypes frozenset pop}@anchor{1838}
@deffn {方法} pop ()

从集合中移除并返回任意一个元素。 如果集合为空则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex clear() (frozenset 方法)
@anchor{library/stdtypes frozenset clear}@anchor{1839}
@deffn {方法} clear ()

从集合中移除所有元素。
@end deffn

请注意，非运算符版本的 @ref{1831,,update()}, @ref{1832,,intersection_update()}, @ref{1833,,difference_update()} 和 @ref{1834,,symmetric_difference_update()} 方法将接受任意可迭代对象作为参数。

请注意，@ref{df6,,__contains__()}, @ref{1836,,remove()} 和 @ref{1837,,discard()} 方法的 @emph{elem} 参数可能是一个 set。 为支持对一个等价的 frozenset 进行搜索，会根据 @emph{elem} 临时创建一个该类型对象。
@end deffn

@node 映射类型 --- dict,上下文管理器类型,集合类型 --- set frozenset,内置类型
@anchor{library/stdtypes mapping-types-dict}@anchor{183a}@anchor{library/stdtypes typesmapping}@anchor{417}
@subsection 映射类型 --- @code{dict}


@geindex 对象; mapping
@geindex 对象; dictionary
@geindex operations on; mapping; types
@geindex operations on; dictionary; type
@geindex 语句; del
@geindex 內置函数; len

@ref{c14,,mapping} 对象会将 @ref{277,,hashable} 值映射到任意对象。 映射属于可变对象。 目前仅有一种标准映射类型 @emph{字典}。 （关于其他容器对象请参看 @ref{1f9,,list}, @ref{1f7,,set} 与 @ref{1a2,,tuple} 等内置类，以及 @ref{1d,,collections} 模块。）

字典的键 @emph{几乎} 可以是任何值。 非 @ref{277,,hashable} 的值，即包含列表、字典或其他可变类型的值（此类对象基于值而非对象标识进行比较）不可用作键。 数字类型用作键时遵循数字比较的一般规则：如果两个数值相等 (例如 @code{1} 和 @code{1.0}) 则两者可以被用来索引同一字典条目。 （但是请注意，由于计算机对于浮点数存储的只是近似值，因此将其用作字典键是不明智的。）

@geindex dict (內置类)
@anchor{library/stdtypes dict}@anchor{164}
@deffn {类} dict (**kwargs)

@deffnx {类} dict (mapping, **kwargs)

@deffnx {类} dict (iterable, **kwargs)

返回一个新的字典，基于可选的位置参数和可能为空的关键字参数集来初始化。

字典可用多种方式来创建:


@itemize *

@item 
使用花括号内以逗号分隔 @code{键: 值} 对的方式: @code{@{'jack': 4098, 'sjoerd': 4127@}} or @code{@{4098: 'jack', 4127: 'sjoerd'@}}

@item 
使用字典推导式: @code{@{@}}, @code{@{x: x ** 2 for x in range(10)@}}

@item 
使用类型构造器: @code{dict()}, @code{dict([('foo', 100), ('bar', 200)])}, @code{dict(foo=100, bar=200)}
@end itemize

如果没有给出位置参数，将创建一个空字典。 如果给出一个位置参数并且其属于映射对象，将创建一个具有与映射对象相同键值对的字典。 否则的话，位置参数必须为一个 @ref{c84,,iterable} 对象。 该可迭代对象中的每一项本身必须为一个刚好包含两个元素的可迭代对象。 每一项中的第一个对象将成为新字典的一个键，第二个对象将成为其对应的值。 如果一个键出现一次以上，该键的最后一个值将成为其在新字典中对应的值。

如果给出了关键字参数，则关键字参数及其值会被加入到基于位置参数创建的字典。 如果要加入的键已存在，来自关键字参数的值将替代来自位置参数的值。

作为演示，以下示例返回的字典均等于 @code{@{"one": 1, "two": 2, "three": 3@}}:

@example
>>> a = dict(one=1, two=2, three=3)
>>> b = @{'one': 1, 'two': 2, 'three': 3@}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict(@{'three': 3, 'one': 1, 'two': 2@})
>>> f = dict(@{'one': 1, 'three': 3@}, two=2)
>>> a == b == c == d == e == f
True
@end example

像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作为键。 其他方式则可使用任何有效的键。

这些是字典所支持的操作（因而自定义的映射类型也应当支持）：


@deffn {Describe} list(d)

返回字典 @emph{d} 中使用的所有键的列表。
@end deffn


@deffn {Describe} len(d)

返回字典 @emph{d} 中的项数。
@end deffn


@deffn {Describe} d[key]

返回 @emph{d} 中以 @emph{key} 为键的项。 如果映射中不存在 @emph{key} 则会引发 @ref{3f1,,KeyError}。

@geindex __missing__()

如果字典的子类定义了方法 @ref{c16,,__missing__()} 并且 @emph{key} 不存在，则 @code{d[key]} 操作将调用该方法并附带键 @emph{key} 作为参数。 @code{d[key]} 随后将返回或引发 @code{__missing__(key)} 调用所返回或引发的任何对象或异常。 没有其他操作或方法会发起调用 @ref{c16,,__missing__()}。 如果未定义 @ref{c16,,__missing__()}，则会引发 @ref{3f1,,KeyError}。 @ref{c16,,__missing__()} 必须是一个方法；它不能是一个实例变量:

@example
>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1
@end example

上面的例子显示了 @ref{ac2,,collections.Counter} 实现的部分代码。 还有另一个不同的 @code{__missing__} 方法是由 @ref{c15,,collections.defaultdict} 所使用的。
@end deffn


@deffn {Describe} d[key] = value

将 @code{d[key]} 设为 @emph{value}。
@end deffn


@deffn {Describe} del d[key]

将 @code{d[key]} 从 @emph{d} 中移除。 如果映射中不存在 @emph{key} 则会引发 @ref{3f1,,KeyError}。
@end deffn


@deffn {Describe} key in d

如果 @emph{d} 中存在键 @emph{key} 则返回 @code{True}，否则返回 @code{False}。
@end deffn


@deffn {Describe} key not in d

等价于 @code{not key in d}。
@end deffn


@deffn {Describe} iter(d)

返回以字典的键为元素的迭代器。 这是 @code{iter(d.keys())} 的快捷方式。
@end deffn

@geindex clear() (dict 方法)
@anchor{library/stdtypes dict clear}@anchor{10d2}
@deffn {方法} clear ()

移除字典中的所有元素。
@end deffn

@geindex copy() (dict 方法)
@anchor{library/stdtypes dict copy}@anchor{551}
@deffn {方法} copy ()

返回原字典的浅拷贝。
@end deffn

@geindex fromkeys() (dict 类方法)
@anchor{library/stdtypes dict fromkeys}@anchor{183b}
@deffn {方法} classmethod fromkeys (iterable[, value])

使用来自 @emph{iterable} 的键创建一个新字典，并将键值设为 @emph{value}。

@ref{183b,,fromkeys()} 是一个返回新字典的类方法。 @emph{value} 默认为 @code{None}。 所有值都只引用一个单独的实例，因此让 @emph{value} 成为一个可变对象例如空列表通常是没有意义的。 要获取不同的值，请改用 @ref{74b,,字典推导式}。
@end deffn

@geindex get() (dict 方法)
@anchor{library/stdtypes dict get}@anchor{183c}
@deffn {方法} get (key[, default])

如果 @emph{key} 存在于字典中则返回 @emph{key} 的值，否则返回 @emph{default}。 如果 @emph{default} 未给出则默认为 @code{None}，因而此方法绝不会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex items() (dict 方法)
@anchor{library/stdtypes dict items}@anchor{cfd}
@deffn {方法} items ()

返回由字典项 (@code{(键, 值)} 对) 组成的一个新视图。 参见 @ref{183d,,视图对象文档}。
@end deffn

@geindex keys() (dict 方法)
@anchor{library/stdtypes dict keys}@anchor{cfc}
@deffn {方法} keys ()

返回由字典键组成的一个新视图。 参见 @ref{183d,,视图对象文档}。
@end deffn

@geindex pop() (dict 方法)
@anchor{library/stdtypes dict pop}@anchor{183e}
@deffn {方法} pop (key[, default])

如果 @emph{key} 存在于字典中则将其移除并返回其值，否则返回 @emph{default}。 如果 @emph{default} 未给出且 @emph{key} 不存在于字典中，则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex popitem() (dict 方法)
@anchor{library/stdtypes dict popitem}@anchor{183f}
@deffn {方法} popitem ()

从字典中移除并返回一个 @code{(键, 值)} 对。 键值对会按 @abbr{LIFO,后进先出} 的顺序被返回。

@ref{183f,,popitem()} 适用于对字典进行消耗性的迭代，这在集合算法中经常被使用。 如果字典为空，调用 @ref{183f,,popitem()} 将引发 @ref{3f1,,KeyError}。


在 3.7 版更改: 现在会确保采用 LIFO 顺序。 在之前的版本中，@ref{183f,,popitem()} 会返回一个任意的键/值对。

@end deffn


@deffn {Describe} reversed(d)

返回一个逆序获取字典键的迭代器。 这是 @code{reversed(d.keys())} 的快捷方式。


3.8 新版功能.

@end deffn

@geindex setdefault() (dict 方法)
@anchor{library/stdtypes dict setdefault}@anchor{aa7}
@deffn {方法} setdefault (key[, default])

如果字典存在键 @emph{key} ，返回它的值。如果不存在，插入值为 @emph{default} 的键 @emph{key} ，并返回 @emph{default} 。 @emph{default} 默认为 @code{None}。
@end deffn

@geindex update() (dict 方法)
@anchor{library/stdtypes dict update}@anchor{e96}
@deffn {方法} update ([other])

使用来自 @emph{other} 的键/值对更新字典，覆盖原有的键。 返回 @code{None}。

@ref{e96,,update()} 接受另一个字典对象，或者一个包含键/值对（以长度为二的元组或其他可迭代对象表示）的可迭代对象。 如果给出了关键字参数，则会以其所指定的键/值对更新字典: @code{d.update(red=1, blue=2)}。
@end deffn

@geindex values() (dict 方法)
@anchor{library/stdtypes dict values}@anchor{cfe}
@deffn {方法} values ()

返回由字典值组成的一个新视图。 参见 @ref{183d,,视图对象文档}。

两个 @code{dict.values()} 视图之间的相等性比较将总是返回 @code{False}。 这在 @code{dict.values()} 与其自身比较时也同样适用:

@example
>>> d = @{'a': 1@}
>>> d.values() == d.values()
False
@end example
@end deffn


@deffn {Describe} d | other

合并 @emph{d} 和 @emph{other} 中的键和值来创建一个新的字典，两者必须都是字典。当 @emph{d} 和 @emph{other} 有相同键时， @emph{other} 的值优先。


3.9 新版功能.

@end deffn


@deffn {Describe} d |= other

用 @emph{other} 的键和值更新字典 @emph{d} ，@emph{other} 可以是 @ref{c14,,mapping} 或 @ref{c84,,iterable} 的键值对。当 @emph{d} 和 @emph{other} 有相同键时， @emph{other} 的值优先。


3.9 新版功能.

@end deffn

两个字典的比较当且仅当它们具有相同的 @code{(键, 值)} 对时才会相等（不考虑顺序）。 排序比较 ('<', '<=', '>=', '>') 会引发 @ref{1ff,,TypeError}。

字典会保留插入时的顺序。 请注意对键的更新不会影响顺序。 删除并再次添加的键将被插入到末尾。

@example
>>> d = @{"one": 1, "two": 2, "three": 3, "four": 4@}
>>> d
@{'one': 1, 'two': 2, 'three': 3, 'four': 4@}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
@{'one': 42, 'two': 2, 'three': 3, 'four': 4@}
>>> del d["two"]
>>> d["two"] = None
>>> d
@{'one': 42, 'three': 3, 'four': 4, 'two': None@}
@end example


在 3.7 版更改: 字典顺序会确保为插入顺序。 此行为是自 3.6 版开始的 CPython 实现细节。


字典和字典视图都是可逆的。

@example
>>> d = @{"one": 1, "two": 2, "three": 3, "four": 4@}
>>> d
@{'one': 1, 'two': 2, 'three': 3, 'four': 4@}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
@end example


在 3.8 版更改: 字典现在是可逆的。

@end deffn


@subsubheading 参见


@ref{b97,,types.MappingProxyType} 可被用来创建一个 @ref{164,,dict} 的只读视图。


@menu
* 字典视图对象:: 

@end menu

@node 字典视图对象,,,映射类型 --- dict
@anchor{library/stdtypes dict-views}@anchor{183d}@anchor{library/stdtypes dictionary-view-objects}@anchor{1840}
@subsubsection 字典视图对象


由 @ref{cfc,,dict.keys()}, @ref{cfe,,dict.values()} 和 @ref{cfd,,dict.items()} 所返回的对象是 @emph{视图对象}。 该对象提供字典条目的一个动态视图，这意味着当字典改变时，视图也会相应改变。

字典视图可以被迭代以产生与其对应的数据，并支持成员检测：


@deffn {Describe} len(dictview)

返回字典中的条目数。
@end deffn


@deffn {Describe} iter(dictview)

返回字典中的键、值或项（以 @code{(键, 值)} 为元素的元组表示）的迭代器。

键和值是按插入时的顺序进行迭代的。 这样就允许使用 @ref{d04,,zip()} 来创建 @code{(值, 键)} 对: @code{pairs = zip(d.values(), d.keys())}。 另一个创建相同列表的方式是 @code{pairs = [(v, k) for (k, v) in d.items()]}.

在添加或删除字典中的条目期间对视图进行迭代可能引发 @ref{3e4,,RuntimeError} 或者无法完全迭代所有条目。


在 3.7 版更改: 字典顺序会确保为插入顺序。

@end deffn


@deffn {Describe} x in dictview

如果 @emph{x} 是对应字典中存在的键、值或项（在最后一种情况下 @emph{x} 应为一个 @code{(键, 值)} 元组） 则返回 @code{True}。
@end deffn


@deffn {Describe} reversed(dictview)

返回一个逆序获取字典键、值或项的迭代器。 视图将按与插入时相反的顺序进行迭代。


在 3.8 版更改: 字典视图现在是可逆的。

@end deffn

键视图类似于集合，因为其条目不重复且可哈希。 如果所有值都是可哈希的，即 @code{(键, 值)} 对也是不重复且可哈希的，那么条目视图也会类似于集合。 （值视图则不被视为类似于集合，因其条目通常都是有重复的。） 对于类似于集合的视图，为抽象基类 @ref{1841,,collections.abc.Set} 所定义的全部操作都是有效的 (例如 @code{==}, @code{<} 或 @code{^})。

一个使用字典视图的示例:

@example
>>> dishes = @{'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500@}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & @{'eggs', 'bacon', 'salad'@}
@{'bacon'@}
>>> keys ^ @{'sausage', 'juice'@}
@{'juice', 'sausage', 'bacon', 'spam'@}
@end example

@node 上下文管理器类型,GenericAlias 类型,映射类型 --- dict,内置类型
@anchor{library/stdtypes context-manager-types}@anchor{1842}@anchor{library/stdtypes typecontextmanager}@anchor{15f5}
@subsection 上下文管理器类型


@geindex context manager
@geindex context management protocol
@geindex protocol; context management

Python 的 @ref{7e4,,with} 语句支持通过上下文管理器所定义的运行时上下文这一概念。 此对象的实现使用了一对专门方法，允许用户自定义类来定义运行时上下文，在语句体被执行前进入该上下文，并在语句执行完毕时退出该上下文：

@geindex __enter__() (contextmanager 方法)
@anchor{library/stdtypes contextmanager __enter__}@anchor{1843}
@deffn {方法} contextmanager.__enter__ ()

进入运行时上下文并返回此对象或关联到该运行时上下文的其他对象。 此方法的返回值会绑定到使用此上下文管理器的 @ref{7e4,,with} 语句的 @code{as} 子句中的标识符。

一个返回其自身的上下文管理器的例子是 @ref{c1d,,file object}。 文件对象会从 __enter__() 返回其自身，以允许 @ref{16f,,open()} 被用作 @ref{7e4,,with} 语句中的上下文表达式。

一个返回关联对象的上下文管理器的例子是 @ref{1844,,decimal.localcontext()} 所返回的对象。 此种管理器会将活动的 decimal 上下文设为原始 decimal 上下文的一个副本并返回该副本。 这允许对 @ref{7e4,,with} 语句的语句体中的当前 decimal 上下文进行更改，而不会影响 @code{with} 语句以外的代码。
@end deffn

@geindex __exit__() (contextmanager 方法)
@anchor{library/stdtypes contextmanager __exit__}@anchor{1845}
@deffn {方法} contextmanager.__exit__ (exc_type, exc_val, exc_tb)

退出运行时上下文并返回一个布尔值旗标来表明所发生的任何异常是否应当被屏蔽。 如果在执行 @ref{7e4,,with} 语句的语句体期间发生了异常，则参数会包含异常的类型、值以及回溯信息。 在其他情况下三个参数均为 @code{None}。

自此方法返回一个真值将导致 @ref{7e4,,with} 语句屏蔽异常并继续执行紧随在 @code{with} 语句之后的语句。 否则异常将在此方法结束执行后继续传播。 在此方法执行期间发生的异常将会取代 @code{with} 语句的语句体中发生的任何异常。

传入的异常绝对不应当被显式地重新引发 —— 相反地，此方法应当返回一个假值以表明方法已成功完成并且不希望屏蔽被引发的异常。 这允许上下文管理代码方便地检测 @ref{1845,,__exit__()} 方法是否确实已失败。
@end deffn

Python 定义了一些上下文管理器来支持简易的线程同步、文件或其他对象的快速关闭，以及更方便地操作活动的十进制算术上下文。 除了实现上下文管理协议以外，不同类型不会被特殊处理。 请参阅 @ref{23,,contextlib} 模块查看相关的示例。

Python 的 @ref{a8c,,generator} 和 @ref{c58,,contextlib.contextmanager} 装饰器提供了实现这些协议的便捷方式。 如果使用 @ref{c58,,contextlib.contextmanager} 装饰器来装饰一个生成器函数，它将返回一个实现了必要的 @ref{1843,,__enter__()} 和 @ref{1845,,__exit__()} 方法的上下文管理器，而不再是由未经装饰的生成器所产生的迭代器。

请注意，Python/C API 中 Python 对象的类型结构中并没有针对这些方法的专门槽位。 想要定义这些方法的扩展类型必须将它们作为普通的 Python 可访问方法来提供。 与设置运行时上下文的开销相比，单个类字典查找的开销可以忽略不计。

@node GenericAlias 类型,其他内置类型,上下文管理器类型,内置类型
@anchor{library/stdtypes generic-alias-type}@anchor{1846}@anchor{library/stdtypes types-genericalias}@anchor{1030}
@subsection GenericAlias 类型


@geindex 对象; GenericAlias
@geindex Generic; Alias

@code{GenericAlias} 对象通常是通过 @ref{15bd,,抽取} 一个类来创建的。 它们最常被用于 @ref{15c3,,容器类}，如 @ref{1f9,,list} 或 @ref{164,,dict}。 举例来说，@code{list[int]} 这个 @code{GenericAlias} 对象是通过附带 @ref{205,,int} 参数抽取 @code{list} 类来创建的。 @code{GenericAlias} 对象的主要目的是用于 @ref{15b6,,类型标注}。

@cartouche
@quotation 注解 
通常一个类只有在实现了特殊方法 @ref{440,,__class_getitem__()} 时才支持抽取操作。
@end quotation
@end cartouche

@code{GenericAlias} 对象可作为 @ref{1035,,generic type} 的代理，实现了 @emph{形参化泛型}。

对于一个容器类，提供给类的 @ref{15bd,,抽取} 操作的参数可以指明对象所包含的元素类型。 例如，@code{set[bytes]} 可在类型标注中用来表示一个 @ref{1f7,,set} 中的所有元素均为 @ref{172,,bytes} 类型。

对于一个定义了 @ref{440,,__class_getitem__()} 但不属于容器的类，提供给类的抽取操作的参数往往会指明在对象上定义的一个或多个方法的返回值类型。 例如，@ref{dd,,正则表达式} 可以被用在 @ref{206,,str} 数据类型和 @ref{172,,bytes} 数据类型上:


@itemize *

@item 
如果 @code{x = re.search('foo', 'foo')}，则 @code{x} 将为一个 @ref{98d,,re.Match} 对象而 @code{x.group(0)} 和 @code{x[0]} 的返回值将均为 @ref{206,,str} 类型。 我们可以在类型标注中使用 @code{GenericAlias} @code{re.Match[str]} 来代表这种对象。

@item 
如果 @code{y = re.search(b'bar', b'bar')}，(注意 @code{b} 表示 @ref{172,,bytes})，则 @code{y} 也将为一个 @code{re.Match} 的实例，但 @code{y.group(0)} 和 @code{y[0]} 的返回值将均为 @ref{172,,bytes} 类型。 在类型标注中，我们将使用 @code{re.Match[bytes]} 来代表这种形式的 @ref{98d,,re.Match} 对象。
@end itemize

@code{GenericAlias} 对象是 @ref{27d,,types.GenericAlias} 类的实例，该类也可被用来直接创建 @code{GenericAlias} 对象。


@deffn {Describe} T[X, Y, ...]

创建一个代表由类型 @emph{X}, @emph{Y} 来参数化的类型 @code{T} 的 @code{GenericAlias}，此类型会更依赖于所使用的 @code{T}。 例如，一个接受包含 @ref{1fe,,float} 元素的 @ref{1f9,,list} 的函数:

@example
def average(values: list[float]) -> float:
    return sum(values) / len(values)
@end example

另一个例子是关于 @ref{c14,,mapping} 对象的，用到了 @ref{164,,dict}，泛型的两个类型参数分别代表了键类型和值类型。本例中的函数需要一个 @code{dict}，其键的类型为 @ref{206,,str}，值的类型为 @ref{205,,int}:。

@example
def send_post_request(url: str, body: dict[str, int]) -> None:
    ...
@end example
@end deffn

内置函数 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 不接受第二个参数为`@w{`}GenericAlias`@w{`} 类型：

@example
>>> isinstance([1, 2], list[str])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic
@end example

Python 运行时不会强制执行 @ref{15b6,,类型标注}。 这种行为扩展到了泛型及其类型形参。 当由 @code{GenericAlias} 创建容器对象时，并不会检查容器中为元素指定的类型。 例如，以下代码虽然不被鼓励，但运行时并不会报错:

@example
>>> t = list[str]
>>> t([1, 2, 3])
[1, 2, 3]
@end example

不仅如此，在创建对象的过程中，参数化的泛型还会抹除类型参数：

@example
>>> t = list[str]
>>> type(t)
<class 'types.GenericAlias'>

>>> l = t()
>>> type(l)
<class 'list'>
@end example

在泛型上调用 @ref{8c3,,repr()} 或 @ref{206,,str()} 会显示应用参数之后的类型：

@example
>>> repr(list[int])
'list[int]'

>>> str(list[int])
'list[int]'
@end example

调用泛型容器的 @ref{3ad,,__getitem__()} 方法将引发异常以防出现 @code{dict[str][str]} 之类的错误:

@example
>>> dict[str][str]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: There are no type variables left in dict[str]
@end example

不过，当使用了 @ref{15b7,,类型变量} 时这种表达式是无效的。 索引必须有与 @code{GenericAlias} 对象的 @ref{1847,,__args__} 中的类型变量条目数量相当的元素。

@example
>>> from typing import TypeVar
>>> Y = TypeVar('Y')
>>> dict[str, Y][int]
dict[str, int]
@end example

@menu
* 标准泛型类:: 
* GenericAlias 对象的特殊属性:: 

@end menu

@node 标准泛型类,GenericAlias 对象的特殊属性,,GenericAlias 类型
@anchor{library/stdtypes standard-generic-classes}@anchor{1848}
@subsubsection 标准泛型类


下列标准库类支持形参化的泛型。 此列表并不是详尽无遗的。


@itemize *

@item 
@ref{1a2,,tuple}

@item 
@ref{1f9,,list}

@item 
@ref{164,,dict}

@item 
@ref{1f7,,set}

@item 
@ref{1f8,,frozenset}

@item 
@ref{709,,type}

@item 
@ref{633,,collections.deque}

@item 
@ref{c15,,collections.defaultdict}

@item 
@ref{2f1,,collections.OrderedDict}

@item 
@ref{ac2,,collections.Counter}

@item 
@ref{5ac,,collections.ChainMap}

@item 
@ref{7b3,,collections.abc.Awaitable}

@item 
@ref{7b4,,collections.abc.Coroutine}

@item 
@ref{7b6,,collections.abc.AsyncIterable}

@item 
@ref{7b6,,collections.abc.AsyncIterable}

@item 
@ref{632,,collections.abc.AsyncGenerator}

@item 
@ref{1849,,collections.abc.Iterable}

@item 
@ref{184a,,collections.abc.Iterator}

@item 
@ref{7b2,,collections.abc.Generator}

@item 
@ref{630,,collections.abc.Reversible}

@item 
@ref{184b,,collections.abc.Container}

@item 
@ref{62f,,collections.abc.Collection}

@item 
@ref{27b,,collections.abc.Callable}

@item 
@ref{1841,,collections.abc.Set}

@item 
@ref{184c,,collections.abc.MutableSet}

@item 
@ref{15f,,collections.abc.Mapping}

@item 
@ref{ad7,,collections.abc.MutableMapping}

@item 
@ref{1794,,collections.abc.Sequence}

@item 
@ref{7a9,,collections.abc.MutableSequence}

@item 
@ref{184d,,collections.abc.ByteString}

@item 
@ref{184e,,collections.abc.MappingView}

@item 
@ref{184f,,collections.abc.KeysView}

@item 
@ref{1850,,collections.abc.ItemsView}

@item 
@ref{1851,,collections.abc.ValuesView}

@item 
@ref{636,,contextlib.AbstractContextManager}

@item 
@ref{489,,contextlib.AbstractAsyncContextManager}

@item 
@ref{1852,,dataclasses.Field}

@item 
@ref{300,,functools.cached_property}

@item 
@ref{3c7,,functools.partialmethod}

@item 
@ref{5ee,,os.PathLike}

@item 
@ref{1853,,queue.LifoQueue}

@item 
@ref{de6,,queue.Queue}

@item 
@ref{1854,,queue.PriorityQueue}

@item 
@ref{4d5,,queue.SimpleQueue}

@item 
@ref{98c,,re.Pattern}

@item 
@ref{98d,,re.Match}

@item 
@ref{1855,,shelve.BsdDbShelf}

@item 
@ref{1856,,shelve.DbfilenameShelf}

@item 
@ref{9a0,,shelve.Shelf}

@item 
@ref{b97,,types.MappingProxyType}

@item 
@ref{109d,,weakref.WeakKeyDictionary}

@item 
@ref{9fe,,weakref.WeakMethod}

@item 
@ref{d88,,weakref.WeakSet}

@item 
@ref{109c,,weakref.WeakValueDictionary}
@end itemize

@node GenericAlias 对象的特殊属性,,标准泛型类,GenericAlias 类型
@anchor{library/stdtypes special-attributes-of-genericalias-objects}@anchor{1857}
@subsubsection @code{GenericAlias} 对象的特殊属性


应用参数后的泛型都实现了一些特殊的只读属性：

@geindex __origin__ (genericalias 属性)
@anchor{library/stdtypes genericalias __origin__}@anchor{1858}
@deffn {属性} genericalias.__origin__

本属性指向未应用参数之前的泛型类：

@example
>>> list[int].__origin__
<class 'list'>
@end example
@end deffn

@geindex __args__ (genericalias 属性)
@anchor{library/stdtypes genericalias __args__}@anchor{1847}
@deffn {属性} genericalias.__args__

该属性是传给泛型类的原始 @ref{440,,__class_getitem__()} 的泛型所组成的 @ref{1a2,,tuple} (长度可能为 1):

@example
>>> dict[str, list[int]].__args__
(<class 'str'>, list[int])
@end example
@end deffn

@geindex __parameters__ (genericalias 属性)
@anchor{library/stdtypes genericalias __parameters__}@anchor{1859}
@deffn {属性} genericalias.__parameters__

该属性是延迟计算出来的一个元组（可能为空），包含了  @code{__args__} 中的唯一类型变量。

@example
>>> from typing import TypeVar

>>> T = TypeVar('T')
>>> list[T].__parameters__
(~T,)
@end example
@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 484

@item PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} —— 类型注解

介绍 Python 中用于类型标注的框架。

@geindex Python 提高建议; PEP 585

@item PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} - 标准多项集中的类型提示泛型

介绍了对标准库类进行原生形参化的能力，只要它们实现了特殊的类方法 @ref{440,,__class_getitem__()}。

@item @ref{15b7,,泛型（Generic）}, @ref{15b8,,用户自定义泛型} 和 @ref{1055,,typing.Generic}

有关如何实现可在运行时被形参化并能被静态类型检查器所识别的泛用类的文档。
@end table



3.9 新版功能.


@node 其他内置类型,特殊属性,GenericAlias 类型,内置类型
@anchor{library/stdtypes other-built-in-types}@anchor{185a}@anchor{library/stdtypes typesother}@anchor{185b}
@subsection 其他内置类型


解释器支持一些其他种类的对象。 这些对象大都仅支持一两种操作。

@menu
* 模块: 模块<2>. 
* 类与类实例:: 
* 函数:: 
* 方法:: 
* 代码对象:: 
* 类型对象:: 
* 空对象:: 
* 省略符对象:: 
* 未实现对象:: 
* 布尔值:: 
* 内部对象:: 

@end menu

@node 模块<2>,类与类实例,,其他内置类型
@anchor{library/stdtypes modules}@anchor{185c}@anchor{library/stdtypes typesmodules}@anchor{185d}
@subsubsection 模块


模块唯一的特殊操作是属性访问: @code{m.name}，这里 @emph{m} 为一个模块而 @emph{name} 访问定义在 @emph{m} 的符号表中的一个名称。 模块属性可以被赋值。 （请注意 @ref{cef,,import} 语句严格来说也是对模块对象的一种操作；@code{import foo} 不要求存在一个名为 @emph{foo} 的模块对象，而是要求存在一个对于名为 @emph{foo} 的模块的 (永久性) @emph{定义}。）

每个模块都有一个特殊属性 @ref{5fe,,__dict__}。 这是包含模块的符号表的字典。 修改此字典将实际改变模块的符号表，但是无法直接对 @ref{5fe,,__dict__} 赋值 (你可以写 @code{m.__dict__['a'] = 1}，这会将 @code{m.a} 定义为 @code{1}，但是你不能写 @code{m.__dict__ = @{@}})。 不建议直接修改 @ref{5fe,,__dict__}。

内置于解释器中的模块会写成这样: @code{<module 'sys' (built-in)>}。 如果是从一个文件加载，则会写成 @code{<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>}。

@node 类与类实例,函数,模块<2>,其他内置类型
@anchor{library/stdtypes classes-and-class-instances}@anchor{185e}@anchor{library/stdtypes typesobjects}@anchor{185f}
@subsubsection 类与类实例


关于这些类型请参阅 @ref{157e,,对象、值与类型} 和 @ref{d3a,,类定义}。

@node 函数,方法,类与类实例,其他内置类型
@anchor{library/stdtypes functions}@anchor{1860}@anchor{library/stdtypes typesfunctions}@anchor{1861}
@subsubsection 函数


函数对象是通过函数定义创建的。 对函数对象的唯一操作是调用它: @code{func(argument-list)}。

实际上存在两种不同的函数对象：内置函数和用户自定义函数。 两者支持同样的操作（调用函数），但实现方式不同，因此对象类型也不同。

更多信息请参阅 @ref{13bf,,函数定义}。

@node 方法,代码对象,函数,其他内置类型
@anchor{library/stdtypes methods}@anchor{1862}@anchor{library/stdtypes typesmethods}@anchor{1863}
@subsubsection 方法


@geindex 对象; method

方法是使用属性表示法来调用的函数。 存在两种形式：内置方法（例如列表的 @code{append()} 方法）和类实例方法。 内置方法由支持它们的类型来描述。

如果你通过一个实例来访问方法（即定义在类命名空间内的函数），你会得到一个特殊对象: @emph{绑定方法} (或称 @emph{实例方法}) 对象。 当被调用时，它会将 @code{self} 参数添加到参数列表。 绑定方法具有两个特殊的只读属性: @code{m.__self__} 操作该方法的对象，而 @code{m.__func__} 是实现该方法的函数。 调用 @code{m(arg-1, arg-2, ..., arg-n)} 完全等价于调用 @code{m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)}。

与函数对象类似，绑定方法对象也支持获取任意属性。 但是，由于方法属性实际上保存于下层的函数对象中 (@code{meth.__func__})，因此不允许设置绑定方法的方法属性。 尝试设置方法的属性将会导致引发 @ref{4aa,,AttributeError}。 想要设置方法属性，你必须在下层的函数对象中显式地对其进行设置:

@example
>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # can't set on the method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'
@end example

更多信息请参阅 @ref{1582,,标准类型层级结构}。

@geindex object; code
@geindex code object

@node 代码对象,类型对象,方法,其他内置类型
@anchor{library/stdtypes bltin-code-objects}@anchor{1864}@anchor{library/stdtypes code-objects}@anchor{1865}
@subsubsection 代码对象


@geindex 內置函数; compile
@geindex __code__ (function object attribute)

代码对象被具体实现用来表示“伪编译”的可执行 Python 代码，例如一个函数体。 它们不同于函数对象，因为它们不包含对其全局执行环境的引用。 代码对象由内置的 @ref{2ee,,compile()} 函数返回，并可通过从函数对象的 @code{__code__} 属性从中提取。 另请参阅 @ref{1a,,code} 模块。

访问 @code{__code__} 会触发 @ref{fec,,审计事件} @code{object.__getattr__}，参数为 @code{obj} 和 @code{"__code__"}。

@geindex 內置函数; exec
@geindex 內置函数; eval

可以通过将代码对象（而非源码字符串）传给 @ref{d14,,exec()} 或 @ref{c6a,,eval()} 内置函数来执行或求值。

更多信息请参阅 @ref{1582,,标准类型层级结构}。

@node 类型对象,空对象,代码对象,其他内置类型
@anchor{library/stdtypes bltin-type-objects}@anchor{176c}@anchor{library/stdtypes type-objects}@anchor{1866}
@subsubsection 类型对象


@geindex 內置函数; type
@geindex 模块; types

类型对象表示各种对象类型。 对象的类型可通过内置函数 @ref{709,,type()} 来获取。 类型没有特殊的操作。 标准库模块 @ref{121,,types} 定义了所有标准内置类型的名称。

类型以这样的写法来表示: @code{<class 'int'>}。

@node 空对象,省略符对象,类型对象,其他内置类型
@anchor{library/stdtypes bltin-null-object}@anchor{1867}@anchor{library/stdtypes the-null-object}@anchor{1868}
@subsubsection 空对象


此对象会由不显式地返回值的函数所返回。 它不支持任何特殊的操作。 空对象只有一种值 @code{None} (这是个内置名称)。 @code{type(None)()} 会生成同一个单例。

该对象的写法为 @code{None}。

@geindex ...; ellipsis literal

@node 省略符对象,未实现对象,空对象,其他内置类型
@anchor{library/stdtypes bltin-ellipsis-object}@anchor{1869}@anchor{library/stdtypes the-ellipsis-object}@anchor{186a}
@subsubsection 省略符对象


此对象常被用于切片 (参见 @ref{1681,,切片})。 它不支持任何特殊的操作。 省略符对象只有一种值 @ref{1770,,Ellipsis} (这是个内置名称)。 @code{type(Ellipsis)()} 会生成 @ref{1770,,Ellipsis} 单例。

该对象的写法为 @code{Ellipsis} 或 @code{...}。

@node 未实现对象,布尔值,省略符对象,其他内置类型
@anchor{library/stdtypes bltin-notimplemented-object}@anchor{186b}@anchor{library/stdtypes the-notimplemented-object}@anchor{186c}
@subsubsection 未实现对象


此对象会被作为比较和二元运算被应用于它们所不支持的类型时的返回值。 请参阅 @ref{16a9,,比较运算} 了解更多信息。 未实现对象只有一种值 @code{NotImplemented}。 @code{type(NotImplemented)()} 会生成这个单例。

该对象的写法为 @code{NotImplemented}。

@node 布尔值,内部对象,未实现对象,其他内置类型
@anchor{library/stdtypes bltin-boolean-values}@anchor{1749}@anchor{library/stdtypes boolean-values}@anchor{186d}
@subsubsection 布尔值


布尔值是两个常量对象 @code{False} 和 @code{True}。 它们被用来表示逻辑上的真假（不过其他值也可被当作真值或假值）。 在数字类的上下文中（例如被用作算术运算符的参数时），它们的行为分别类似于整数 0 和 1。 内置函数 @ref{2c4,,bool()} 可被用来将任意值转换为布尔值，只要该值可被解析为一个逻辑值（参见之前的 @ref{1748,,逻辑值检测} 部分）。

@geindex False
@geindex True
@geindex Boolean; values

该对象的写法分别为 @code{False} 和 @code{True}。

@node 内部对象,,布尔值,其他内置类型
@anchor{library/stdtypes internal-objects}@anchor{186e}@anchor{library/stdtypes typesinternal}@anchor{186f}
@subsubsection 内部对象


有关此对象的信息请参阅 @ref{1582,,标准类型层级结构}。 其中描述了栈帧对象、回溯对象以及切片对象等等。

@node 特殊属性,Integer string conversion length limitation,其他内置类型,内置类型
@anchor{library/stdtypes special-attributes}@anchor{1870}@anchor{library/stdtypes specialattrs}@anchor{1871}
@subsection 特殊属性


语言实现为部分对象类型添加了一些特殊的只读属性，它们具有各自的作用。 其中一些并不会被 @ref{e01,,dir()} 内置函数所列出。

@geindex __dict__ (object 属性)
@anchor{library/stdtypes object __dict__}@anchor{5fe}
@deffn {属性} object.__dict__

一个字典或其他类型的映射对象，用于存储对象的（可写）属性。
@end deffn

@geindex __class__ (instance 属性)
@anchor{library/stdtypes instance __class__}@anchor{ed4}
@deffn {属性} instance.__class__

类实例所属的类。
@end deffn

@geindex __bases__ (class 属性)
@anchor{library/stdtypes class __bases__}@anchor{ed3}
@deffn {属性} class.__bases__

由类对象的基类所组成的元组。
@end deffn

@geindex __name__ (definition 属性)
@anchor{library/stdtypes definition __name__}@anchor{d37}
@deffn {属性} definition.__name__

类、函数、方法、描述器或生成器实例的名称。
@end deffn

@geindex __qualname__ (definition 属性)
@anchor{library/stdtypes definition __qualname__}@anchor{158a}
@deffn {属性} definition.__qualname__

类、函数、方法、描述器或生成器实例的 @ref{158b,,qualified name}。


3.3 新版功能.

@end deffn

@geindex __mro__ (class 属性)
@anchor{library/stdtypes class __mro__}@anchor{176a}
@deffn {属性} class.__mro__

此属性是由类组成的元组，在方法解析期间会基于它来查找基类。
@end deffn

@geindex mro() (class 方法)
@anchor{library/stdtypes class mro}@anchor{1872}
@deffn {方法} class.mro ()

此方法可被一个元类来重载，以为其实例定制方法解析顺序。 它会在类实例化时被调用，其结果存储于 @ref{176a,,__mro__} 之中。
@end deffn

@geindex __subclasses__() (class 方法)
@anchor{library/stdtypes class __subclasses__}@anchor{1873}
@deffn {方法} class.__subclasses__ ()

每个类都存有对直接子类的弱引用列表。本方法返回所有存活引用的列表。列表的顺序按照子类定义的排列。例如：

@example
>>> int.__subclasses__()
[<class 'bool'>]
@end example
@end deffn

@node Integer string conversion length limitation,,特殊属性,内置类型
@anchor{library/stdtypes int-max-str-digits}@anchor{288}@anchor{library/stdtypes integer-string-conversion-length-limitation}@anchor{1874}
@subsection Integer string conversion length limitation


CPython has a global limit for converting between @ref{205,,int} and @ref{206,,str}
to mitigate denial of service attacks. This limit @emph{only} applies to decimal or
other non-power-of-two number bases. Hexadecimal, octal, and binary conversions
are unlimited. The limit can be configured.

The @ref{205,,int} type in CPython is an arbitrary length number stored in binary
form (commonly known as a "bignum"). There exists no algorithm that can convert
a string to a binary integer or a binary integer to a string in linear time,
@emph{unless} the base is a power of 2. Even the best known algorithms for base 10
have sub-quadratic complexity. Converting a large value such as @code{int('1' *
500_000)} can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoid CVE-2020-10735@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735}.

The limit is applied to the number of digit characters in the input or output
string when a non-linear conversion algorithm would be involved.  Underscores
and the sign are not counted towards the limit.

When an operation would exceed the limit, a @ref{16d,,ValueError} is raised:

@example
>>> import sys
>>> sys.set_int_max_str_digits(4300)  # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 8599 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i  # Hexadecimal is unlimited.
@end example

The default limit is 4300 digits as provided in
@ref{cf3,,sys.int_info.default_max_str_digits}.
The lowest limit that can be configured is 640 digits as provided in
@ref{cf3,,sys.int_info.str_digits_check_threshold}.

Verification:

@example
>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
...           '9252925514383915483333812743580549779436104706260696366600'
...           '571186405732').to_bytes(53, 'big')
...
@end example


3.9.14 新版功能.


@menu
* Affected APIs:: 
* Configuring the limit:: 
* Recommended configuration:: 

@end menu

@node Affected APIs,Configuring the limit,,Integer string conversion length limitation
@anchor{library/stdtypes affected-apis}@anchor{1875}
@subsubsection Affected APIs


The limitation only applies to potentially slow conversions between @ref{205,,int}
and @ref{206,,str} or @ref{172,,bytes}:


@itemize *

@item 
@code{int(string)} with default base 10.

@item 
@code{int(string, base)} for all bases that are not a power of 2.

@item 
@code{str(integer)}.

@item 
@code{repr(integer)}.

@item 
any other string conversion to base 10, for example @code{f"@{integer@}"},
@code{"@{@}".format(integer)}, or @code{b"%d" % integer}.
@end itemize

The limitations do not apply to functions with a linear algorithm:


@itemize *

@item 
@code{int(string, base)} with base 2, 4, 8, 16, or 32.

@item 
@ref{1786,,int.from_bytes()} and @ref{1784,,int.to_bytes()}.

@item 
@ref{d36,,hex()}, @ref{d35,,oct()}, @ref{d10,,bin()}.

@item 
@ref{5e1,,格式规格迷你语言} for hex, octal, and binary numbers.

@item 
@ref{206,,str} to @ref{1fe,,float}.

@item 
@ref{206,,str} to @ref{2c7,,decimal.Decimal}.
@end itemize

@node Configuring the limit,Recommended configuration,Affected APIs,Integer string conversion length limitation
@anchor{library/stdtypes configuring-the-limit}@anchor{1876}
@subsubsection Configuring the limit


Before Python starts up you can use an environment variable or an interpreter
command line flag to configure the limit:


@itemize *

@item 
@geindex PYTHONINTMAXSTRDIGITS
@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@ref{f61,,PYTHONINTMAXSTRDIGITS}, e.g.
@code{PYTHONINTMAXSTRDIGITS=640 python3} to set the limit to 640 or
@code{PYTHONINTMAXSTRDIGITS=0 python3} to disable the limitation.

@item 
@ref{297,,-X int_max_str_digits}, e.g.
@code{python3 -X int_max_str_digits=640}

@item 
@code{sys.flags.int_max_str_digits} contains the value of
@geindex PYTHONINTMAXSTRDIGITS
@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@ref{f61,,PYTHONINTMAXSTRDIGITS} or @ref{297,,-X int_max_str_digits}.
If both the env var and the @code{-X} option are set, the @code{-X} option takes
precedence. A value of @emph{-1} indicates that both were unset, thus a value of
@code{sys.int_info.default_max_str_digits} was used during initialization.
@end itemize

From code, you can inspect the current limit and set a new one using these
@ref{fd,,sys} APIs:


@itemize *

@item 
@ref{1877,,sys.get_int_max_str_digits()} and @ref{f62,,sys.set_int_max_str_digits()} are
a getter and setter for the interpreter-wide limit. Subinterpreters have
their own limit.
@end itemize

Information about the default and minimum can be found in @ref{cf3,,sys.int_info}:


@itemize *

@item 
@ref{cf3,,sys.int_info.default_max_str_digits} is the compiled-in
default limit.

@item 
@ref{cf3,,sys.int_info.str_digits_check_threshold} is the lowest
accepted value for the limit (other than 0 which disables it).
@end itemize


3.9.14 新版功能.


@cartouche
@quotation 警告 
Setting a low limit @emph{can} lead to problems. While rare, code exists that
contains integer constants in decimal in their source that exceed the
minimum threshold. A consequence of setting the limit is that Python source
code containing decimal integer literals longer than the limit will
encounter an error during parsing, usually at startup time or import time or
even at installation time - anytime an up to date @code{.pyc} does not already
exist for the code. A workaround for source that contains such large
constants is to convert them to @code{0x} hexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests
run with the limit set early via the environment or flag so that it applies
during startup and even during any installation step that may invoke Python
to precompile @code{.py} sources to @code{.pyc} files.
@end quotation
@end cartouche

@node Recommended configuration,,Configuring the limit,Integer string conversion length limitation
@anchor{library/stdtypes recommended-configuration}@anchor{1878}
@subsubsection Recommended configuration


The default @code{sys.int_info.default_max_str_digits} is expected to be
reasonable for most applications. If your application requires a different
limit, set it from your main entry point using Python version agnostic code as
these APIs were added in security patch releases in versions before 3.11.

示例：

@example
>>> import sys
>>> if hasattr(sys, "set_int_max_str_digits"):
...     upper_bound = 68000
...     lower_bound = 4004
...     current_limit = sys.get_int_max_str_digits()
...     if current_limit == 0 or current_limit > upper_bound:
...         sys.set_int_max_str_digits(upper_bound)
...     elif current_limit < lower_bound:
...         sys.set_int_max_str_digits(lower_bound)
@end example

If you need to disable it entirely, set it to @code{0}.

@node 内置异常,文本处理服务,内置类型,Python 标准库
@anchor{library/exceptions doc}@anchor{1879}@anchor{library/exceptions bltin-exceptions}@anchor{fbe}@anchor{library/exceptions built-in-exceptions}@anchor{187a}
@section 内置异常


@geindex 语句; try
@geindex 语句; except

在 Python 中，所有异常必须为一个派生自 @ref{2e2,,BaseException} 的类的实例。 在带有提及一个特定类的 @ref{c19,,except} 子句的 @ref{e3f,,try} 语句中，该子句也会处理任何派生自该类的异常类（但不处理 @emph{它} 所派生出的异常类）。 通过子类化创建的两个不相关异常类永远是不等效的，既使它们具有相同的名称。

@geindex 语句; raise

下面列出的内置异常可通过解释器或内置函数来生成。除非另有说明，它们都会具有一个提示导致错误详细原因的“关联值”。 这可以是一个字符串或由多个信息项（例如一个错误码和一个解释错误的字符串）组成的元组。 关联值通常会作为参数被传递给异常类的构造器。

用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件，“就像” 在解释器引发了相同异常的情况时一样；但是请注意，没有任何机制能防止用户代码引发不适当的错误。

内置异常类可以被子类化以定义新的异常；鼓励程序员从 @ref{2e3,,Exception} 类或它的某个子类而不是从 @ref{2e2,,BaseException} 来派生新的异常。 关于定义异常的更多信息可以在 Python 教程的 @ref{1417,,用户自定义异常} 部分查看。

@menu
* 异常上下文:: 
* 从内置异常继承:: 
* 基类:: 
* 具体异常:: 
* 警告:: 
* 异常层次结构:: 

@end menu

@node 异常上下文,从内置异常继承,,内置异常
@anchor{library/exceptions exception-context}@anchor{187b}
@subsection 异常上下文


当有其他异常已经被处理的情况下又引发一个新异常的时候，新异常的 @code{__context__} 属性会被自动设为已经被处理的异常。 异常可以在使用了 @ref{c19,,except} 或 @ref{2c3,,finally} 子句，或者 @ref{7e4,,with} 语句的时候被处理。

这个隐式异常上下文可以通过使用 @code{from} 配合 @ref{d12,,raise} 来补充一个显式的原因:

@example
raise new_exc from original_exc
@end example

跟在 @ref{d12,,from} 之后一表达式必须为一个异常或 @code{None}。 它将在所引发的异常上被设置为 @code{__cause__}。 设置 @code{__cause__} 还会隐式地将 @code{__suppress_context__} 属性设为 @code{True}，这样使用 @code{raise new_exc from None} 可以有效地将旧异常替换为新异常来显示其目的 (例如将 @ref{3f1,,KeyError} 转换为 @ref{4aa,,AttributeError})，同时让旧异常在 @code{__context__} 中保持可用状态以便在调试时进行内省。

除了异常本身的回溯以外，默认的回溯还会显示这些串连的异常。 @code{__cause__} 中的显式串连异常如果存在将总是显示。 @code{__context__} 中的隐式串连异常仅在 @code{__cause__} 为 @ref{204,,None} 并且 @code{__suppress_context__} 为假值时显示。

不论在哪种情况下，异常本身总会在任何串连异常之后显示，以便回溯的最后一行总是显示所引发的最后一个异常。

@node 从内置异常继承,基类,异常上下文,内置异常
@anchor{library/exceptions inheriting-from-built-in-exceptions}@anchor{187c}
@subsection 从内置异常继承


用户代码可以创建继承自某个异常类型的子类。 建议每次仅子类化一个异常类型以避免多个基类处理 @code{args} 属性的不同方式，以及内存布局不兼容可能导致的冲突。

@strong{CPython implementation detail:} 大多数内置异常都用 C 实现以保证运行效率，参见: Objects/exceptions.c@footnote{https://github.com/python/cpython/tree/3.9/Objects/exceptions.c}。 其中一些具有自定义内存布局，这使得创建继承自多个异常类型的子类成为不可能。 一个类型的内存布局属于实现细节并可能随着 Python 版本升级而改变，导致在未来可能产生新的冲突。 因此，建议完全避免子类化多个异常类型。

@node 基类,具体异常,从内置异常继承,内置异常
@anchor{library/exceptions base-classes}@anchor{187d}
@subsection 基类


下列异常主要被用作其他异常的基类。

@geindex BaseException
@anchor{library/exceptions BaseException}@anchor{2e2}
@deffn {例外} BaseException

所有内置异常的基类。 它不应该被用户自定义类直接继承 (这种情况请使用 @ref{2e3,,Exception})。 如果在此类的实例上调用 @ref{206,,str()}，则会返回实例的参数表示，或者当没有参数时返回空字符串。

@geindex args (BaseException 属性)
@anchor{library/exceptions BaseException args}@anchor{187e}
@deffn {属性} args

传给异常构造器的参数元组。 某些内置异常 (例如 @ref{30b,,OSError}) 接受特定数量的参数并赋予此元组中的元素特殊的含义，而其他异常通常只接受一个给出错误信息的单独字符串。
@end deffn

@geindex with_traceback() (BaseException 方法)
@anchor{library/exceptions BaseException with_traceback}@anchor{16eb}
@deffn {方法} with_traceback (tb)

此方法将 @emph{tb} 设为异常的新回溯信息并返回该异常对象。 它通常以如下的形式在异常处理程序中使用:

@example
try:
    ...
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)
@end example
@end deffn
@end deffn

@geindex Exception
@anchor{library/exceptions Exception}@anchor{2e3}
@deffn {例外} Exception

所有内置的非系统退出类异常都派生自此类。 所有用户自定义异常也应当派生自此类。
@end deffn

@geindex ArithmeticError
@anchor{library/exceptions ArithmeticError}@anchor{187f}
@deffn {例外} ArithmeticError

此基类用于派生针对各种算术类错误而引发的内置异常: @ref{a4a,,OverflowError}, @ref{1fb,,ZeroDivisionError}, @ref{1880,,FloatingPointError}。
@end deffn

@geindex BufferError
@anchor{library/exceptions BufferError}@anchor{1881}
@deffn {例外} BufferError

当与 @ref{174c,,缓冲区} 相关的操作无法执行时将被引发。
@end deffn

@geindex LookupError
@anchor{library/exceptions LookupError}@anchor{17c1}
@deffn {例外} LookupError

此基类用于派生当映射或序列所使用的键或索引无效时引发的异常: @ref{f3d,,IndexError}, @ref{3f1,,KeyError}。 这可以通过 @ref{239,,codecs.lookup()} 来直接引发。
@end deffn

@node 具体异常,警告,基类,内置异常
@anchor{library/exceptions concrete-exceptions}@anchor{1882}
@subsection 具体异常


以下异常属于经常被引发的异常。

@geindex AssertionError
@anchor{library/exceptions AssertionError}@anchor{241}
@deffn {例外} AssertionError

@geindex 语句; assert

当 @ref{240,,assert} 语句失败时将被引发。
@end deffn

@geindex AttributeError
@anchor{library/exceptions AttributeError}@anchor{4aa}
@deffn {例外} AttributeError

当属性引用 (参见 @ref{167b,,属性引用}) 或赋值失败时将被引发。 （当一个对象根本不支持属性引用或属性赋值时则将引发 @ref{1ff,,TypeError}。）
@end deffn

@geindex EOFError
@anchor{library/exceptions EOFError}@anchor{d3c}
@deffn {例外} EOFError

当 @ref{d3b,,input()} 函数未读取任何数据即达到文件结束条件 (EOF) 时将被引发。 （另外，@code{io.IOBase.read()} 和 @ref{1883,,io.IOBase.readline()} 方法在遇到 EOF 则将返回一个空字符串。）
@end deffn

@geindex FloatingPointError
@anchor{library/exceptions FloatingPointError}@anchor{1880}
@deffn {例外} FloatingPointError

目前未被使用。
@end deffn

@geindex GeneratorExit
@anchor{library/exceptions GeneratorExit}@anchor{e00}
@deffn {例外} GeneratorExit

当一个 @ref{a8c,,generator} 或 @ref{18a,,coroutine} 被关闭时将被引发；参见 @ref{15ff,,generator.close()} 和 @ref{15fe,,coroutine.close()}。 它直接继承自 @ref{2e2,,BaseException} 而不是 @ref{2e3,,Exception}，因为从技术上来说它并不是一个错误。
@end deffn

@geindex ImportError
@anchor{library/exceptions ImportError}@anchor{16c}
@deffn {例外} ImportError

当 @ref{cef,,import} 语句尝试加载模块遇到麻烦时将被引发。 并且当 @code{from ... import} 中的 "from list" 存在无法找到的名称时也会被引发。

@code{name} 与 @code{path} 属性可通过对构造器使用仅关键字参数来设定。 设定后它们将分别表示被尝试导入的模块名称与触发异常的任意文件所在路径。


在 3.3 版更改: 添加了 @code{name} 与 @code{path} 属性。

@end deffn

@geindex ModuleNotFoundError
@anchor{library/exceptions ModuleNotFoundError}@anchor{4a9}
@deffn {例外} ModuleNotFoundError

@ref{16c,,ImportError} 的子类，当一个模块无法被定位时将由 @ref{cef,,import} 引发。 当在 @ref{109a,,sys.modules} 中找到 @code{None} 时也会被引发。


3.6 新版功能.

@end deffn

@geindex IndexError
@anchor{library/exceptions IndexError}@anchor{f3d}
@deffn {例外} IndexError

当序列抽取超出范围时将被引发。 （切片索引会被静默截短到允许的范围；如果指定索引不是整数则 @ref{1ff,,TypeError} 会被引发。）

@c XXX xref to sequences
@end deffn

@geindex KeyError
@anchor{library/exceptions KeyError}@anchor{3f1}
@deffn {例外} KeyError

当在现有键集合中找不到指定的映射（字典）键时将被引发。

@c XXX xref to mapping objects?
@end deffn

@geindex KeyboardInterrupt
@anchor{library/exceptions KeyboardInterrupt}@anchor{2d3}
@deffn {例外} KeyboardInterrupt

当用户按下中断键 (通常为 @code{Control-C} 或 @code{Delete}) 时将被引发。 在执行期间，会定期检测中断信号。 该异常继承自 @ref{2e2,,BaseException} 以确保不会被处理 @ref{2e3,,Exception} 的代码意外捕获，这样可以避免退出解释器。

@cartouche
@quotation 注解 
捕获 @ref{2d3,,KeyboardInterrupt} 需要特别考虑。 因为它可能会在不可预知的点位被引发，在某些情况下，它可能使运行中的程序陷入不一致的状态。 通常最好是让 @ref{2d3,,KeyboardInterrupt} 尽快结束程序或者完全避免引发它。 (参见 @ref{1884,,有关信号处理句柄和异常的注释}。)
@end quotation
@end cartouche
@end deffn

@geindex MemoryError
@anchor{library/exceptions MemoryError}@anchor{fb5}
@deffn {例外} MemoryError

当一个操作耗尽内存但情况仍可（通过删除一些对象）进行挽救时将被引发。 关联的值是一个字符串，指明是哪种（内部）操作耗尽了内存。 请注意由于底层的内存管理架构（C 的 @code{malloc()} 函数），解释器也许并不总是能够从这种情况下完全恢复；但它毕竟可以引发一个异常，这样就能打印出栈回溯信息，以便找出导致问题的失控程序。
@end deffn

@geindex NameError
@anchor{library/exceptions NameError}@anchor{e48}
@deffn {例外} NameError

当某个局部或全局名称未找到时将被引发。 此异常仅用于非限定名称。 关联的值是一条错误信息，其中包含未找到的名称。
@end deffn

@geindex NotImplementedError
@anchor{library/exceptions NotImplementedError}@anchor{70e}
@deffn {例外} NotImplementedError

此异常派生自 @ref{3e4,,RuntimeError}。 在用户自定义的基类中，抽象方法应当在其要求所派生类重载该方法，或是在其要求所开发的类提示具体实现尚待添加时引发此异常。

@cartouche
@quotation 注解 
它不应当用来表示一个运算符或方法根本不能被支持 -- 在此情况下应当让特定运算符 / 方法保持未定义，或者在子类中将其设为 @ref{204,,None}。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
@code{NotImplementedError} 和 @code{NotImplemented} 不可互换，即使它们有相似的名称和用途。 请参阅 @ref{203,,NotImplemented} 了解有关何时使用它们的详细说明。
@end quotation
@end cartouche
@end deffn

@geindex OSError
@anchor{library/exceptions OSError}@anchor{30b}
@deffn {例外} OSError ([arg])

@deffnx {例外} OSError (errno, strerror[, filename[, winerror[, filename2]]])

@geindex 模块; errno

此异常在一个系统函数返回系统相关的错误时将被引发，此类错误包括 I/O 操作失败例如 "文件未找到" 或 "磁盘已满" 等（不包括非法参数类型或其他偶然性错误）。

构造器的第二种形式可设置如下所述的相应属性。 如果未指定这些属性则默认为 @ref{204,,None}。 为了能向下兼容，如果传入了三个参数，则 @ref{187e,,args} 属性将仅包含由前两个构造器参数组成的 2 元组。

构造器实际返回的往往是 @ref{30b,,OSError} 的某个子类，如下文 @ref{1885,,OS exceptions} 中所描述的。 具体的子类取决于最终的 @ref{1886,,errno} 值。 此行为仅在直接或通过别名来构造 @ref{30b,,OSError} 时发生，并且在子类化时不会被继承。

@geindex errno (OSError 属性)
@anchor{library/exceptions OSError errno}@anchor{1886}
@deffn {属性} errno

来自于 C 变量 @code{errno} 的数字错误码。
@end deffn

@geindex winerror (OSError 属性)
@anchor{library/exceptions OSError winerror}@anchor{1887}
@deffn {属性} winerror

在 Windows 下，此参数将给出原生的 Windows 错误码。 而 @ref{1886,,errno} 属性将是该原生错误码在 POSIX 平台下的近似转换形式。

在 Windows 下，如果 @emph{winerror} 构造器参数是一个整数，则 @ref{1886,,errno} 属性会根据 Windows 错误码来确定，而 @emph{errno} 参数会被忽略。 在其他平台上，@emph{winerror} 参数会被忽略，并且 @ref{1887,,winerror} 属性将不存在。
@end deffn

@geindex strerror (OSError 属性)
@anchor{library/exceptions OSError strerror}@anchor{1888}
@deffn {属性} strerror

操作系统所提供的相应错误信息。 它在 POSIX 平台中由 C 函数 @code{perror()} 来格式化，在 Windows 中则是由 @code{FormatMessage()}。
@end deffn

@geindex filename (OSError 属性)
@geindex filename2 (OSError 属性)
@anchor{library/exceptions OSError filename}@anchor{1889}
@deffn {属性} filename
@anchor{library/exceptions OSError filename2}@anchor{188a}
@deffnx {属性} filename2

对于与文件系统路径有关 (例如 @ref{16f,,open()} 或 @ref{b21,,os.unlink()}) 的异常，@ref{1889,,filename} 是传给函数的文件名。 对于涉及两个文件系统路径的函数 (例如 @ref{b1d,,os.rename()})，@ref{188a,,filename2} 将是传给函数的第二个文件名。
@end deffn


在 3.3 版更改: @ref{a7d,,EnvironmentError}, @ref{a7c,,IOError}, @ref{a7e,,WindowsError}, @ref{a7f,,socket.error}, @ref{a80,,select.error} 与 @code{mmap.error} 已被合并到 @ref{30b,,OSError}，构造器可能返回其中一个子类。



在 3.4 版更改: @ref{1889,,filename} 属性现在将是传给函数的原始文件名，而不是经过编码或基于文件系统编码进行解码之后的名称。 此外还添加了 @emph{filename2} 构造器参数和属性。

@end deffn

@geindex OverflowError
@anchor{library/exceptions OverflowError}@anchor{a4a}
@deffn {例外} OverflowError

当算术运算的结果大到无法表示时将被引发。 这对整数来说不可能发生（宁可引发 @ref{fb5,,MemoryError} 也不会放弃尝试）。 但是出于历史原因，有时也会在整数超出要求范围的情况下引发 OverflowError。 因为在 C 中缺少对浮点异常处理的标准化，大多数浮点运算都不会做检查。
@end deffn

@geindex RecursionError
@anchor{library/exceptions RecursionError}@anchor{731}
@deffn {例外} RecursionError

此异常派生自 @ref{3e4,,RuntimeError}。 它会在解释器检测发现超过最大递归深度 (参见 @ref{f42,,sys.getrecursionlimit()}) 时被引发。


3.5 新版功能: 在此之前将只引发 @ref{3e4,,RuntimeError}。

@end deffn

@geindex ReferenceError
@anchor{library/exceptions ReferenceError}@anchor{f17}
@deffn {例外} ReferenceError

此异常将在使用 @ref{381,,weakref.proxy()} 函数所创建的弱引用来访问该引用的某个已被作为垃圾回收的属性时被引发。 有关弱引用的更多信息请参阅 @ref{131,,weakref} 模块。
@end deffn

@geindex RuntimeError
@anchor{library/exceptions RuntimeError}@anchor{3e4}
@deffn {例外} RuntimeError

当检测到一个不归属于任何其他类别的错误时将被引发。 关联的值是一个指明究竟发生了什么问题的字符串。
@end deffn

@geindex StopIteration
@anchor{library/exceptions StopIteration}@anchor{58a}
@deffn {例外} StopIteration

由内置函数 @ref{77f,,next()} 和 @ref{11ba,,iterator} 的 @ref{d34,,__next__()} 方法所引发，用来表示该迭代器不能产生下一项。

该异常对象只有一个属性 @code{value}，它在构造该异常时作为参数给出，默认值为 @ref{204,,None}。

当一个 @ref{a8c,,generator} 或 @ref{18a,,coroutine} 函数返回时，将引发一个新的 @ref{58a,,StopIteration} 实例，函数返回的值将被用作异常构造器的 @code{value} 形参。

如果某个生成器代码直接或间接地引发了 @ref{58a,,StopIteration}，它会被转换为 @ref{3e4,,RuntimeError} (并将 @ref{58a,,StopIteration} 保留为导致新异常的原因)。


在 3.3 版更改: 添加了 @code{value} 属性及其被生成器函数用作返回值的功能。



在 3.5 版更改: 引入了通过 @code{from __future__ import generator_stop} 来实现 RuntimeError 转换，参见 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}。



在 3.7 版更改: 默认对所有代码启用 
@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}: 在生成器中引发的 @ref{58a,,StopIteration} 错误将被转换为 @ref{3e4,,RuntimeError}。

@end deffn

@geindex StopAsyncIteration
@anchor{library/exceptions StopAsyncIteration}@anchor{1193}
@deffn {例外} StopAsyncIteration

必须由一个 @ref{742,,asynchronous iterator} 对象的 @ref{158e,,__anext__()} 方法来引发以停止迭代操作。


3.5 新版功能.

@end deffn

@geindex SyntaxError
@anchor{library/exceptions SyntaxError}@anchor{562}
@deffn {例外} SyntaxError (message, details)

当解析器遇到语法错误时引发。 这可以发生在 @ref{cef,,import} 语句，对内置函数 @ref{2ee,,compile()}, @ref{d14,,exec()} 或 @ref{c6a,,eval()} 的调用，或是读取原始脚本或标准输入（也包括交互模式）的时候。

异常实例的 @ref{206,,str()} 只返回错误消息。 错误详情为一个元组，其成员也可在单独的属性中分别获取。

@geindex filename (SyntaxError 属性)
@anchor{library/exceptions SyntaxError filename}@anchor{188b}
@deffn {属性} filename

发生语法错误所在文件的名称。
@end deffn

@geindex lineno (SyntaxError 属性)
@anchor{library/exceptions SyntaxError lineno}@anchor{188c}
@deffn {属性} lineno

发生错误所在文件中的行号。  行号索引从 1 开始：文件中首行的 @code{lineno} 为 1。
@end deffn

@geindex offset (SyntaxError 属性)
@anchor{library/exceptions SyntaxError offset}@anchor{188d}
@deffn {属性} offset

发生错误所在文件中的列号。 列号索引从 1 开始：行中首个字符的 @code{offset} 为 1。
@end deffn

@geindex text (SyntaxError 属性)
@anchor{library/exceptions SyntaxError text}@anchor{188e}
@deffn {属性} text

错误所涉及的源代码文本。
@end deffn

对于 f-字符串字段中的错误，消息会带有 "f-string: " 前缀并且其位置是基于替换表达式构建的文本中的位置。 例如，编译 f'Bad @{a b@} field' 将产生以下 args 属性: ('f-string: ...', ('@w{'}, 1, 4, '(a b)n'))。
@end deffn

@geindex IndentationError
@anchor{library/exceptions IndentationError}@anchor{f40}
@deffn {例外} IndentationError

与不正确的缩进相关的语法错误的基类。 这是 @ref{562,,SyntaxError} 的一个子类。
@end deffn

@geindex TabError
@anchor{library/exceptions TabError}@anchor{f3f}
@deffn {例外} TabError

当缩进包含对制表符和空格符不一致的使用时将被引发。 这是 @ref{f40,,IndentationError} 的一个子类。
@end deffn

@geindex SystemError
@anchor{library/exceptions SystemError}@anchor{6fc}
@deffn {例外} SystemError

当解释器发现内部错误，但情况看起来尚未严重到要放弃所有希望时将被引发。 关联的值是一个指明发生了什么问题的字符串（表示为低层级的符号）。

你应当将此问题报告给你所用 Python 解释器的作者或维护人员。 请确认报告 Python 解释器的版本号 (@code{sys.version}; 它也会在交互式 Python 会话开始时被打印出来)，具体的错误消息（异常所关联的值）以及可能触发该错误的程序源码。
@end deffn

@geindex SystemExit
@anchor{library/exceptions SystemExit}@anchor{6fd}
@deffn {例外} SystemExit

此异常由 @ref{db2,,sys.exit()} 函数引发。 它继承自 @ref{2e2,,BaseException} 而不是 @ref{2e3,,Exception} 以确保不会被处理 @ref{2e3,,Exception} 的代码意外捕获。 这允许此异常正确地向上传播并导致解释器退出。 如果它未被处理，则 Python 解释器就将退出；不会打印任何栈回溯信息。 构造器接受的可选参数与传递给 @ref{db2,,sys.exit()} 的相同。 如果该值为一个整数，则它指明系统退出状态码（会传递给 C 的 @code{exit()} 函数）；如果该值为 @code{None}，则退出状态码为零；如果该值为其他类型（例如字符串），则会打印对象的值并将退出状态码设为一。

对 @ref{db2,,sys.exit()} 的调用会被转换为一个异常以便能执行清理处理程序 (@ref{e3f,,try} 语句的 @ref{2c3,,finally} 子句)，并且使得调试器可以执行一段脚本而不必冒失去控制的风险。 如果绝对确实地需要立即退出（例如在调用 @ref{a4b,,os.fork()} 之后的子进程中）则可使用 @ref{188f,,os._exit()}.

@geindex code (SystemExit 属性)
@anchor{library/exceptions SystemExit code}@anchor{1890}
@deffn {属性} code

传给构造器的退出状态码或错误信息（默认为 @code{None}。）
@end deffn
@end deffn

@geindex TypeError
@anchor{library/exceptions TypeError}@anchor{1ff}
@deffn {例外} TypeError

当一个操作或函数被应用于类型不适当的对象时将被引发。 关联的值是一个字符串，给出有关类型不匹配的详情。

此异常可以由用户代码引发，以表明尝试对某个对象进行的操作不受支持也不应当受支持。 如果某个对象应当支持给定的操作但尚未提供相应的实现，所要引发的适当异常应为 @ref{70e,,NotImplementedError}。

传入参数的类型错误 (例如在要求 @ref{205,,int} 时却传入了 @ref{1f9,,list}) 应当导致 @ref{1ff,,TypeError}，但传入参数的值错误 (例如传入要求范围之外的数值) 则应当导致 @ref{16d,,ValueError}。
@end deffn

@geindex UnboundLocalError
@anchor{library/exceptions UnboundLocalError}@anchor{f3e}
@deffn {例外} UnboundLocalError

当在函数或方法中对某个局部变量进行引用，但该变量并未绑定任何值时将被引发。 此异常是 @ref{e48,,NameError} 的一个子类。
@end deffn

@geindex UnicodeError
@anchor{library/exceptions UnicodeError}@anchor{d0b}
@deffn {例外} UnicodeError

当发生与 Unicode 相关的编码或解码错误时将被引发。 此异常是 @ref{16d,,ValueError} 的一个子类。

@ref{d0b,,UnicodeError} 具有一些描述编码或解码错误的属性。 例如 @code{err.object[err.start:err.end]} 会给出导致编解码器失败的特定无效输入。

@geindex encoding (UnicodeError 属性)
@anchor{library/exceptions UnicodeError encoding}@anchor{1891}
@deffn {属性} encoding

引发错误的编码名称。
@end deffn

@geindex reason (UnicodeError 属性)
@anchor{library/exceptions UnicodeError reason}@anchor{1892}
@deffn {属性} reason

描述特定编解码器错误的字符串。
@end deffn

@geindex object (UnicodeError 属性)
@anchor{library/exceptions UnicodeError object}@anchor{1893}
@deffn {属性} object

编解码器试图要编码或解码的对象。
@end deffn

@geindex start (UnicodeError 属性)
@anchor{library/exceptions UnicodeError start}@anchor{1894}
@deffn {属性} start

@ref{3da,,object} 中无效数据的开始位置索引。
@end deffn

@geindex end (UnicodeError 属性)
@anchor{library/exceptions UnicodeError end}@anchor{1895}
@deffn {属性} end

@ref{3da,,object} 中无效数据的末尾位置索引（不含）。
@end deffn
@end deffn

@geindex UnicodeEncodeError
@anchor{library/exceptions UnicodeEncodeError}@anchor{331}
@deffn {例外} UnicodeEncodeError

当在编码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 @ref{d0b,,UnicodeError} 的一个子类。
@end deffn

@geindex UnicodeDecodeError
@anchor{library/exceptions UnicodeDecodeError}@anchor{332}
@deffn {例外} UnicodeDecodeError

当在解码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 @ref{d0b,,UnicodeError} 的一个子类。
@end deffn

@geindex UnicodeTranslateError
@anchor{library/exceptions UnicodeTranslateError}@anchor{1896}
@deffn {例外} UnicodeTranslateError

在转写过程中发生与 Unicode 相关的错误时将被引发。 此异常是 @ref{d0b,,UnicodeError} 的一个子类。
@end deffn

@geindex ValueError
@anchor{library/exceptions ValueError}@anchor{16d}
@deffn {例外} ValueError

当操作或函数接收到具有正确类型但值不适合的参数，并且情况不能用更精确的异常例如 @ref{f3d,,IndexError} 来描述时将被引发。
@end deffn

@geindex ZeroDivisionError
@anchor{library/exceptions ZeroDivisionError}@anchor{1fb}
@deffn {例外} ZeroDivisionError

当除法或取余运算的第二个参数为零时将被引发。 关联的值是一个字符串，指明操作数和运算的类型。
@end deffn

下列异常被保留以与之前的版本相兼容；从 Python 3.3 开始，它们都是 @ref{30b,,OSError} 的别名。

@geindex EnvironmentError
@anchor{library/exceptions EnvironmentError}@anchor{a7d}
@deffn {例外} EnvironmentError
@end deffn

@geindex IOError
@anchor{library/exceptions IOError}@anchor{a7c}
@deffn {例外} IOError
@end deffn

@geindex WindowsError
@anchor{library/exceptions WindowsError}@anchor{a7e}
@deffn {例外} WindowsError

限在 Windows 中可用。
@end deffn

@menu
* OS 异常:: 

@end menu

@node OS 异常,,,具体异常
@anchor{library/exceptions os-exceptions}@anchor{1885}
@subsubsection OS 异常


下列异常均为 @ref{30b,,OSError} 的子类，它们将根据系统错误代码被引发。

@geindex BlockingIOError
@anchor{library/exceptions BlockingIOError}@anchor{a81}
@deffn {例外} BlockingIOError

当一个操作将会在设置为非阻塞操作的对象（例如套接字）上发生阻塞时将被引发。 对应于 @code{errno} @ref{1897,,EAGAIN}, @ref{1898,,EALREADY}, @ref{1899,,EWOULDBLOCK} 和 @ref{189a,,EINPROGRESS}。

除了 @ref{30b,,OSError} 已有的属性，@ref{a81,,BlockingIOError} 还有一个额外属性：

@geindex characters_written (BlockingIOError 属性)
@anchor{library/exceptions BlockingIOError characters_written}@anchor{189b}
@deffn {属性} characters_written

一个整数，表示在被阻塞前已写入到流的字符数。 当使用来自 @ref{a1,,io} 模块的带缓冲 I/O 类时此属性可用。
@end deffn
@end deffn

@geindex ChildProcessError
@anchor{library/exceptions ChildProcessError}@anchor{a82}
@deffn {例外} ChildProcessError

当一个子进程上的操作失败时将被引发。 对应于 @code{errno} @ref{189c,,ECHILD}。
@end deffn

@geindex ConnectionError
@anchor{library/exceptions ConnectionError}@anchor{7e1}
@deffn {例外} ConnectionError

与连接相关问题的基类。

其子类有 @ref{a87,,BrokenPipeError}, @ref{a88,,ConnectionAbortedError}, @ref{a89,,ConnectionRefusedError} 和 @ref{a8a,,ConnectionResetError}。
@end deffn

@geindex BrokenPipeError
@anchor{library/exceptions BrokenPipeError}@anchor{a87}
@deffn {例外} BrokenPipeError

@ref{7e1,,ConnectionError} 的子类，当试图写入一个管道而该管道的另一端已关闭，或者试图写入一个套接字而该套接字已关闭写入时将被引发。 对应于 @code{errno} @ref{189d,,EPIPE} 和 @ref{189e,,ESHUTDOWN}。
@end deffn

@geindex ConnectionAbortedError
@anchor{library/exceptions ConnectionAbortedError}@anchor{a88}
@deffn {例外} ConnectionAbortedError

@ref{7e1,,ConnectionError} 的子类，当一个连接尝试被对端中止时将被引发。 对应于 @code{errno} @ref{189f,,ECONNABORTED}。
@end deffn

@geindex ConnectionRefusedError
@anchor{library/exceptions ConnectionRefusedError}@anchor{a89}
@deffn {例外} ConnectionRefusedError

@ref{7e1,,ConnectionError} 的子类，当一个连接尝试被对端拒绝时将被引发。 对应于 @code{errno} @ref{18a0,,ECONNREFUSED}。
@end deffn

@geindex ConnectionResetError
@anchor{library/exceptions ConnectionResetError}@anchor{a8a}
@deffn {例外} ConnectionResetError

@ref{7e1,,ConnectionError} 的子类，当一个连接尝试被对端重置时将被引发。 对应于 @code{errno} @ref{18a1,,ECONNRESET}。
@end deffn

@geindex FileExistsError
@anchor{library/exceptions FileExistsError}@anchor{a42}
@deffn {例外} FileExistsError

当试图创建一个已存在的文件或目录时将被引发。 对应于 @code{errno} @ref{18a2,,EEXIST}。
@end deffn

@geindex FileNotFoundError
@anchor{library/exceptions FileNotFoundError}@anchor{8b7}
@deffn {例外} FileNotFoundError

将所请求的文件或目录不存在时将被引发。 对应于 @code{errno} @ref{18a3,,ENOENT}。
@end deffn

@geindex InterruptedError
@anchor{library/exceptions InterruptedError}@anchor{756}
@deffn {例外} InterruptedError

当系统调用被输入信号中断时将被引发。 对应于 @code{errno} @ref{755,,EINTR}。


在 3.5 版更改: 当系统调用被某个信号中断时，Python 现在会重试系统调用，除非该信号的处理程序引发了其它异常 (原理参见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}) 而不是引发 @ref{756,,InterruptedError}。

@end deffn

@geindex IsADirectoryError
@anchor{library/exceptions IsADirectoryError}@anchor{a83}
@deffn {例外} IsADirectoryError

当请求对一个目录执行文件操作 (例如 @ref{b1c,,os.remove()}) 时将被引发。 对应于 @code{errno} @ref{18a4,,EISDIR}。
@end deffn

@geindex NotADirectoryError
@anchor{library/exceptions NotADirectoryError}@anchor{a84}
@deffn {例外} NotADirectoryError

当请求对一个非目录执行目录操作 (例如 @ref{b25,,os.listdir()}) 时将被引发。 在大多数 POSIX 平台上，它还可能在某个操作试图将一个非目录作为目录打开或遍历时被引发。 对应于 @code{errno} @ref{18a5,,ENOTDIR}。
@end deffn

@geindex PermissionError
@anchor{library/exceptions PermissionError}@anchor{700}
@deffn {例外} PermissionError

当在没有足够访问权限的情况下试图执行某个操作时将被引发 —— 例如文件系统权限。 对应于 @code{errno} @ref{18a6,,EACCES} 和 @ref{18a7,,EPERM}。
@end deffn

@geindex ProcessLookupError
@anchor{library/exceptions ProcessLookupError}@anchor{a85}
@deffn {例外} ProcessLookupError

当给定的进程不存在时将被引发。 对应于 @code{errno} @ref{18a8,,ESRCH}。
@end deffn

@geindex TimeoutError
@anchor{library/exceptions TimeoutError}@anchor{a86}
@deffn {例外} TimeoutError

当一个系统函数在系统层级发生超时的情况下将被引发。 对应于 @code{errno} @ref{18a9,,ETIMEDOUT}。
@end deffn


3.3 新版功能: 添加了以上所有 @ref{30b,,OSError} 的子类。



@subsubheading 参见


@geindex Python 提高建议; PEP 3151
PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151} - 重写 OS 和 IO 异常的层次结构


@node 警告,异常层次结构,具体异常,内置异常
@anchor{library/exceptions warning-categories-as-exceptions}@anchor{18aa}@anchor{library/exceptions warnings}@anchor{18ab}
@subsection 警告


下列异常被用作警告类别；请参阅 @ref{18ac,,警告类别} 文档了解详情。

@geindex Warning
@anchor{library/exceptions Warning}@anchor{18ad}
@deffn {例外} Warning

警告类别的基类。
@end deffn

@geindex UserWarning
@anchor{library/exceptions UserWarning}@anchor{18ae}
@deffn {例外} UserWarning

用户代码所产生警告的基类。
@end deffn

@geindex DeprecationWarning
@anchor{library/exceptions DeprecationWarning}@anchor{15a}
@deffn {例外} DeprecationWarning

如果所发出的警告是针对其他 Python 开发者的，则以此作为与已弃用特性相关警告的基类。

会被默认警告过滤器忽略，在 @code{__main__} 模块中的情况除外 (
@geindex Python 提高建议; PEP 565
PEP 565@footnote{https://www.python.org/dev/peps/pep-0565})。 启用 @ref{160,,Python 开发模式} 时会显示此警告。

这个弃用政策是在 
@geindex Python 提高建议; PEP 387
PEP 387@footnote{https://www.python.org/dev/peps/pep-0387} 中描述的。
@end deffn

@geindex PendingDeprecationWarning
@anchor{library/exceptions PendingDeprecationWarning}@anchor{15c}
@deffn {例外} PendingDeprecationWarning

对于已过时并预计在未来弃用，但目前尚未弃用的特性相关警告的基类。

这个类很少被使用，因为针对未来可能的弃用发出警告的做法并不常见，而针对当前已有的弃用则推荐使用 @ref{15a,,DeprecationWarning}。

会被默认警告过滤器忽略。 启用 @ref{160,,Python 开发模式} 时会显示此警告。

这个弃用政策是在 
@geindex Python 提高建议; PEP 387
PEP 387@footnote{https://www.python.org/dev/peps/pep-0387} 中描述的。
@end deffn

@geindex SyntaxWarning
@anchor{library/exceptions SyntaxWarning}@anchor{2d0}
@deffn {例外} SyntaxWarning

与模糊的语法相关的警告的基类。
@end deffn

@geindex RuntimeWarning
@anchor{library/exceptions RuntimeWarning}@anchor{3ea}
@deffn {例外} RuntimeWarning

与模糊的运行时行为相关的警告的基类。
@end deffn

@geindex FutureWarning
@anchor{library/exceptions FutureWarning}@anchor{43e}
@deffn {例外} FutureWarning

如果所发出的警告是针对以 Python 所编写应用的最终用户的，则以此作为与已弃用特性相关警告的基类。
@end deffn

@geindex ImportWarning
@anchor{library/exceptions ImportWarning}@anchor{6d9}
@deffn {例外} ImportWarning

与在模块导入中可能的错误相关的警告的基类。

会被默认警告过滤器忽略。 启用 @ref{160,,Python 开发模式} 时会显示此警告。
@end deffn

@geindex UnicodeWarning
@anchor{library/exceptions UnicodeWarning}@anchor{e54}
@deffn {例外} UnicodeWarning

与 Unicode 相关的警告的基类。
@end deffn

@geindex BytesWarning
@anchor{library/exceptions BytesWarning}@anchor{5b8}
@deffn {例外} BytesWarning

与 @ref{172,,bytes} 和 @ref{173,,bytearray} 相关的警告的基类。
@end deffn

@geindex ResourceWarning
@anchor{library/exceptions ResourceWarning}@anchor{5d3}
@deffn {例外} ResourceWarning

资源使用相关警告的基类。

会被默认警告过滤器忽略。 启用 @ref{160,,Python 开发模式} 时会显示此警告。


3.2 新版功能.

@end deffn

@node 异常层次结构,,警告,内置异常
@anchor{library/exceptions exception-hierarchy}@anchor{18af}
@subsection 异常层次结构


内置异常的类层级结构如下：

@example
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
@end example
@anchor{library/text stringservices}@anchor{17a2}
@node 文本处理服务,二进制数据服务,内置异常,Python 标准库
@anchor{library/text doc}@anchor{18b0}@anchor{library/text text-processing-services}@anchor{18b1}@anchor{library/text textservices}@anchor{17a5}
@section 文本处理服务


本章介绍的模块提供了广泛的字符串操作和其他文本处理服务。

在 @ref{18b2,,二进制数据服务} 之下描述的  @ref{1b,,codecs} 模块也与文本处理高度相关。 此外也请参阅 Python 内置字符串类型的文档 @ref{1386,,文本序列类型 --- str}。

@menu
* string: string --- 常见的字符串操作. 常见的字符串操作
* re: re --- 正则表达式操作. 正则表达式操作
* difflib: difflib --- 计算差异的辅助工具. 计算差异的辅助工具
* textwrap: textwrap --- 文本自动换行与填充. 文本自动换行与填充
* unicodedata: unicodedata --- Unicode 数据库. Unicode 数据库
* stringprep: stringprep --- 因特网字符串预备. 因特网字符串预备
* readline: readline --- GNU readline 接口. GNU readline 接口
* rlcompleter: rlcompleter --- GNU readline 的补全函数. GNU readline 的补全函数

@end menu

@node string --- 常见的字符串操作,re --- 正则表达式操作,,文本处理服务
@anchor{library/string doc}@anchor{18b3}@anchor{library/string module-string}@anchor{f6}@anchor{library/string string-common-string-operations}@anchor{18b4}
@subsection @code{string} --- 常见的字符串操作


@geindex string (模块)

@strong{源代码：} Lib/string.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/string.py}


__________________________________________________________________



@subsubheading 参见


@ref{1386,,文本序列类型 --- str}

@ref{1387,,字符串的方法}


@menu
* 字符串常量:: 
* 自定义字符串格式化:: 
* 格式字符串语法:: 
* 模板字符串:: 
* 辅助函数:: 

@end menu

@node 字符串常量,自定义字符串格式化,,string --- 常见的字符串操作
@anchor{library/string string-constants}@anchor{18b5}
@subsubsection 字符串常量


此模块中定义的常量为：

@geindex ascii_letters() (在 string 模块中)
@anchor{library/string string ascii_letters}@anchor{d2c}
@deffn {数据} string.ascii_letters

下文所述 @ref{18b6,,ascii_lowercase} 和 @ref{18b7,,ascii_uppercase} 常量的拼连。 该值不依赖于语言区域。
@end deffn

@geindex ascii_lowercase() (在 string 模块中)
@anchor{library/string string ascii_lowercase}@anchor{18b6}
@deffn {数据} string.ascii_lowercase

小写字母 @code{'abcdefghijklmnopqrstuvwxyz'}。 该值不依赖于语言区域，不会发生改变。
@end deffn

@geindex ascii_uppercase() (在 string 模块中)
@anchor{library/string string ascii_uppercase}@anchor{18b7}
@deffn {数据} string.ascii_uppercase

大写字母 @code{'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}。 该值不依赖于语言区域，不会发生改变。
@end deffn

@geindex digits() (在 string 模块中)
@anchor{library/string string digits}@anchor{18b8}
@deffn {数据} string.digits

字符串 @code{'0123456789'}。
@end deffn

@geindex hexdigits() (在 string 模块中)
@anchor{library/string string hexdigits}@anchor{18b9}
@deffn {数据} string.hexdigits

字符串 @code{'0123456789abcdefABCDEF'}。
@end deffn

@geindex octdigits() (在 string 模块中)
@anchor{library/string string octdigits}@anchor{18ba}
@deffn {数据} string.octdigits

字符串 @code{'01234567'}。
@end deffn

@geindex punctuation() (在 string 模块中)
@anchor{library/string string punctuation}@anchor{18bb}
@deffn {数据} string.punctuation

由在 @code{C} 区域设置中被视为标点符号的 ASCII 字符所组成的字符串: @code{!"#$%&'()*+,-./:;<=>?@@[\]^_`@{|@}~}.
@end deffn

@geindex printable() (在 string 模块中)
@anchor{library/string string printable}@anchor{18bc}
@deffn {数据} string.printable

由被视为可打印符号的 ASCII 字符组成的字符串。 这是 @ref{18b8,,digits}, @ref{d2c,,ascii_letters}, @ref{18bb,,punctuation} 和 @ref{18bd,,whitespace} 的总和。
@end deffn

@geindex whitespace() (在 string 模块中)
@anchor{library/string string whitespace}@anchor{18bd}
@deffn {数据} string.whitespace

由被视为空白符号的 ASCII 字符组成的字符串。 其中包括空格、制表、换行、回车、进纸和纵向制表符。
@end deffn

@node 自定义字符串格式化,格式字符串语法,字符串常量,string --- 常见的字符串操作
@anchor{library/string custom-string-formatting}@anchor{18be}@anchor{library/string string-formatting}@anchor{17a4}
@subsubsection 自定义字符串格式化


内置的字符串类提供了通过使用 
@geindex Python 提高建议; PEP 3101
PEP 3101@footnote{https://www.python.org/dev/peps/pep-3101} 所描述的 @ref{5dd,,format()} 方法进行复杂变量替换和值格式化的能力。 @ref{f6,,string} 模块中的 @ref{8ad,,Formatter} 类允许你使用与内置 @ref{5dd,,format()} 方法相同的实现来创建并定制你自己的字符串格式化行为。

@geindex Formatter (string 中的类)
@anchor{library/string string Formatter}@anchor{8ad}
@deffn {类} string.Formatter

@ref{8ad,,Formatter} 类包含下列公有方法：

@geindex format() (string.Formatter 方法)
@anchor{library/string string Formatter format}@anchor{58f}
@deffn {方法} format (format_string, /, *args, **kwargs)

首要的 API 方法。 它接受一个格式字符串和任意一组位置和关键字参数。 它只是一个调用 @ref{18bf,,vformat()} 的包装器。


在 3.7 版更改: 格式字符串参数现在是 @ref{3d1,,仅限位置参数}。

@end deffn

@geindex vformat() (string.Formatter 方法)
@anchor{library/string string Formatter vformat}@anchor{18bf}
@deffn {方法} vformat (format_string, args, kwargs)

此函数执行实际的格式化操作。 它被公开为一个单独的函数，用于需要传入一个预定义字母作为参数，而不是使用 @code{*args} 和 @code{**kwargs} 语法将字典解包为多个单独参数并重打包的情况。 @ref{18bf,,vformat()} 完成将格式字符串分解为字符数据和替换字段的工作。 它会调用下文所述的几种不同方法。
@end deffn

此外，@ref{8ad,,Formatter} 还定义了一些旨在被子类替换的方法：

@geindex parse() (string.Formatter 方法)
@anchor{library/string string Formatter parse}@anchor{18c0}
@deffn {方法} parse (format_string)

循环遍历 format_string 并返回一个由可迭代对象组成的元组 (@emph{literal_text}, @emph{field_name}, @emph{format_spec}, @emph{conversion})。 它会被 @ref{18bf,,vformat()} 用来将字符串分解为文本字面值或替换字段。

元组中的值在概念上表示一段字面文本加上一个替换字段。 如果没有字面文本（如果连续出现两个替换字段就会发生这种情况），则 @emph{literal_text} 将是一个长度为零的字符串。 如果没有替换字段，则 @emph{field_name}, @emph{format_spec} 和 @emph{conversion} 的值将为 @code{None}。
@end deffn

@geindex get_field() (string.Formatter 方法)
@anchor{library/string string Formatter get_field}@anchor{18c1}
@deffn {方法} get_field (field_name, args, kwargs)

给定 @emph{field_name} 作为 @ref{18c0,,parse()} (见上文) 的返回值，将其转换为要格式化的对象。 返回一个元组 (obj, used_key)。 默认版本接受在 
@geindex Python 提高建议; PEP 3101
PEP 3101@footnote{https://www.python.org/dev/peps/pep-3101} 所定义形式的字符串，例如 "0[name]" 或 "label.title"。 @emph{args} 和 @emph{kwargs} 与传给 @ref{18bf,,vformat()} 的一样。 返回值 @emph{used_key} 与 @ref{18c2,,get_value()} 的 @emph{key} 形参具有相同的含义。
@end deffn

@geindex get_value() (string.Formatter 方法)
@anchor{library/string string Formatter get_value}@anchor{18c2}
@deffn {方法} get_value (key, args, kwargs)

提取给定的字段值。 @emph{key} 参数将为整数或字符串。 如果是整数，它表示 @emph{args} 中位置参数的索引；如果是字符串，它表示 @emph{kwargs} 中的关键字参数名。

@emph{args} 形参会被设为 @ref{18bf,,vformat()} 的位置参数列表，而 @emph{kwargs} 形参会被设为由关键字参数组成的字典。

对于复合字段名称，仅会为字段名称的第一个组件调用这些函数；后续组件会通过普通属性和索引操作来进行处理。

因此举例来说，字段表达式 '0.name' 将导致调用 @ref{18c2,,get_value()} 时附带 @emph{key} 参数值 0。 在 @ref{18c2,,get_value()} 通过调用内置的 @ref{554,,getattr()} 函数返回后将会查找 @code{name} 属性。

如果索引或关键字引用了一个不存在的项，则将引发 @ref{f3d,,IndexError} 或 @ref{3f1,,KeyError}。
@end deffn

@geindex check_unused_args() (string.Formatter 方法)
@anchor{library/string string Formatter check_unused_args}@anchor{18c3}
@deffn {方法} check_unused_args (used_args, args, kwargs)

在必要时实现对未使用参数进行检测。 此函数的参数是是格式字符串中实际引用的所有参数键的集合（整数表示位置参数，字符串表示名称参数），以及被传给 vformat 的 @emph{args} 和 @emph{kwargs} 的引用。 未使用参数的集合可以根据这些形参计算出来。 如果检测失败则 @ref{18c3,,check_unused_args()} 应会引发一个异常。
@end deffn

@geindex format_field() (string.Formatter 方法)
@anchor{library/string string Formatter format_field}@anchor{18c4}
@deffn {方法} format_field (value, format_spec)

@ref{18c4,,format_field()} 会简单地调用内置全局函数 @ref{5de,,format()}。 提供该方法是为了让子类能够重载它。
@end deffn

@geindex convert_field() (string.Formatter 方法)
@anchor{library/string string Formatter convert_field}@anchor{18c5}
@deffn {方法} convert_field (value, conversion)

使用给定的转换类型（来自 @ref{18c0,,parse()} 方法所返回的元组）来转换（由 @ref{18c1,,get_field()} 所返回的）值。 默认版本支持 's' (str), 'r' (repr) 和 'a' (ascii) 等转换类型。
@end deffn
@end deffn

@node 格式字符串语法,模板字符串,自定义字符串格式化,string --- 常见的字符串操作
@anchor{library/string format-string-syntax}@anchor{18c6}@anchor{library/string formatstrings}@anchor{de8}
@subsubsection 格式字符串语法


@ref{5dd,,str.format()} 方法和 @ref{8ad,,Formatter} 类共享相同的格式字符串语法（虽然对于 @ref{8ad,,Formatter} 来说，其子类可以定义它们自己的格式字符串语法）。 具体语法与 @ref{29d,,格式化字符串字面值} 相似，但较为简单一些，并且关键的一点是不支持任意表达式。

@geindex @{@} (curly brackets); in string formatting
@geindex . (dot); in string formatting
@geindex [] (square brackets); in string formatting
@geindex ! (exclamation); in string formatting
@geindex ; (colon); in string formatting

格式字符串包含有以花括号 @code{@{@}} 括起来的“替换字段”。 不在花括号之内的内容被视为字面文本，会不加修改地复制到输出中。 如果你需要在字面文本中包含花括号字符，可以通过重复来转义: @code{@{@{} and @code{@}@}}。

替换字段的语法如下：

@quotation

@example
@anchor{library/string grammar-token-replacement-field}@anchor{18c7}replacement_field ::= "@{" [field_name] ["!" conversion] [":" format_spec] "@}"
@anchor{library/string grammar-token-field-name}@anchor{18c8}field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*
@anchor{library/string grammar-token-arg-name}@anchor{18c9}arg_name          ::= [identifier | digit+]
@anchor{library/string grammar-token-attribute-name}@anchor{18ca}attribute_name    ::= identifier
@anchor{library/string grammar-token-element-index}@anchor{18cb}element_index     ::= digit+ | index_string
@anchor{library/string grammar-token-index-string}@anchor{18cc}index_string      ::= <any source character except "]"> +
@anchor{library/string grammar-token-conversion}@anchor{18cd}conversion        ::= "r" | "s" | "a"
@anchor{library/string grammar-token-format-spec}@anchor{18ce}format_spec       ::= <described in the next section>
@end example
@end quotation

用不太正式的术语来描述，替换字段开头可以用一个 @emph{field_name} 指定要对值进行格式化并取代替换字符被插入到输出结果的对象。 @emph{field_name} 之后有可选的  @emph{conversion} 字段，它是一个感叹号 @code{'!'} 加一个 @emph{format_spec}，并以一个冒号 @code{':'} 打头。 这些指明了替换值的非默认格式。

另请参阅 @ref{5e1,,格式规格迷你语言} 一节。

@emph{field_name} 本身以一个数字或关键字 @emph{arg_name} 打头。 如果为数字，则它指向一个位置参数，而如果为关键字，则它指向一个命名关键字参数。 如果格式字符串中的数字 arg_names 为 0, 1, 2, ... 的序列，它们可以全部省略（而非部分省略），数字 0, 1, 2, ... 将会按顺序自动插入。 由于 @emph{arg_name} 不使用引号分隔，因此无法在格式字符串中指定任意的字典键 (例如字符串 @code{'10'} 或 @code{':-]'})。 @emph{arg_name} 之后可以带上任意数量的索引或属性表达式。 @code{'.name'} 形式的表达式会使用 @ref{554,,getattr()} 选择命名属性，而 @code{'[index]'} 形式的表达式会使用 @ref{3ad,,__getitem__()} 执行索引查找。


在 3.1 版更改: 位置参数说明符对于 @ref{5dd,,str.format()} 可以省略，因此 @code{'@{@} @{@}'.format(a, b)} 等价于 @code{'@{0@} @{1@}'.format(a, b)}。



在 3.4 版更改: 位置参数说明符对于 @ref{8ad,,Formatter} 可以省略。


一些简单的格式字符串示例

@example
"First, thou shalt count to @{0@}"  # References first positional argument
"Bring me a @{@}"                   # Implicitly references the first positional argument
"From @{@} to @{@}"                   # Same as "From @{0@} to @{1@}"
"My quest is @{name@}"              # References keyword argument 'name'
"Weight in tons @{0.weight@}"       # 'weight' attribute of first positional arg
"Units destroyed: @{players[0]@}"   # First element of keyword argument 'players'.
@end example

使用 @emph{conversion} 字段在格式化之前进行类型强制转换。 通常，格式化值的工作由值本身的 @ref{a38,,__format__()} 方法来完成。 但是，在某些情况下最好强制将类型格式化为一个字符串，覆盖其本身的格式化定义。 通过在调用 @ref{a38,,__format__()} 之前将值转换为字符串，可以绕过正常的格式化逻辑。

目前支持的转换旗标有三种: @code{'!s'} 会对值调用 @ref{206,,str()}，@code{'!r'} 调用 @ref{8c3,,repr()} 而 @code{'!a'} 则调用 @ref{e19,,ascii()}。

几个例子：

@example
"Harold's a clever @{0!s@}"        # Calls str() on the argument first
"Bring out the holy @{name!r@}"    # Calls repr() on the argument first
"More @{!a@}"                      # Calls ascii() on the argument first
@end example

@emph{format_spec} 字段包含值应如何呈现的规格描述，例如字段宽度、对齐、填充、小数精度等细节信息。 每种值类型可以定义自己的“格式化迷你语言”或对 @emph{format_spec} 的解读方式。

大多数内置类型都支持同样的格式化迷你语言，具体描述见下一节。

@emph{format_spec} 字段还可以在其内部包含嵌套的替换字段。 这些嵌套的替换字段可能包括字段名称、转换旗标和格式规格描述，但是不再允许更深层的嵌套。 format_spec 内部的替换字段会在解读 @emph{format_spec} 字符串之前先被解读。 这将允许动态地指定特定值的格式。

请参阅 @ref{18cf,,格式示例} 一节查看相关示例。

@menu
* 格式规格迷你语言:: 
* 格式示例:: 

@end menu

@node 格式规格迷你语言,格式示例,,格式字符串语法
@anchor{library/string format-specification-mini-language}@anchor{18d0}@anchor{library/string formatspec}@anchor{5e1}
@subsubsection 格式规格迷你语言


“格式规格”在格式字符串所包含的替换字段内部使用，用于定义单个值应如何呈现 (参见 @ref{de8,,格式字符串语法} 和 @ref{29d,,格式字符串字面值})。 它们也可以被直接传给内置的 @ref{5de,,format()} 函数。 每种可格式化的类型都可以自行定义如何对格式规格进行解读。

大多数内置类型都为格式规格实现了下列选项，不过某些格式化选项只被数值类型所支持。

一般约定空的格式描述将产生与在值上调用 @ref{206,,str()} 相同的结果。 非空格式描述通常会修改此结果。

@emph{标准格式说明符} 的一般形式如下：

@example
@anchor{library/string id1}@anchor{18d1}format_spec     ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
@anchor{library/string grammar-token-fill}@anchor{18d2}fill            ::= <any character>
@anchor{library/string grammar-token-align}@anchor{18d3}align           ::= "<" | ">" | "=" | "^"
@anchor{library/string grammar-token-sign}@anchor{18d4}sign            ::= "+" | "-" | " "
@anchor{library/string grammar-token-width}@anchor{18d5}width           ::= digit+
@anchor{library/string grammar-token-grouping-option}@anchor{18d6}grouping_option ::= "_" | ","
@anchor{library/string grammar-token-precision}@anchor{18d7}precision       ::= digit+
@anchor{library/string grammar-token-type}@anchor{18d8}type            ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
@end example

如果指定了一个有效的 @emph{align} 值，则可以在该值前面加一个 @emph{fill} 字符，它可以为任意字符，如果省略则默认为空格符。 在 @ref{29d,,格式化字符串字面值} 或在使用 @ref{5dd,,str.format()} 方法时是无法使用花括号字面值 ("@code{@{}" or "@code{@}}") 作为 @emph{fill} 字符的。 但是，通过嵌套替换字段插入花括号则是可以的。 这个限制不会影响 @ref{5de,,format()} 函数。

各种对齐选项的含义如下：

@quotation

@geindex < (less); in string formatting
@geindex > (greater); in string formatting
@geindex = (equals); in string formatting
@geindex ^ (caret); in string formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

意义

@item

@code{'<'}

@tab

强制字段在可用空间内左对齐（这是大多数对象的默认值）。

@item

@code{'>'}

@tab

强制字段在可用空间内右对齐（这是数字的默认值）。

@item

@code{'='}

@tab

强制将填充放置在符号（如果有）之后但在数字之前。这用于以“+000000120”形式打印字段。此对齐选项仅对数字类型有效。当'0'紧接在字段宽度之前时，它成为默认值。

@item

@code{'^'}

@tab

强制字段在可用空间内居中。

@end multitable

@end quotation

请注意，除非定义了最小字段宽度，否则字段宽度将始终与填充它的数据大小相同，因此在这种情况下，对齐选项没有意义。

@emph{sign} 选项仅对数字类型有效，可以是以下之一：

@quotation

@geindex + (plus); in string formatting
@geindex - (minus); in string formatting
@geindex space; in string formatting


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

意义

@item

@code{'+'}

@tab

表示标志应该用于正数和负数。

@item

@code{'-'}

@tab

表示标志应仅用于负数（这是默认行为）。

@item

space

@tab

表示应在正数上使用前导空格，在负数上使用减号。

@end multitable

@end quotation

@geindex # (hash); in string formatting

@code{'#'} 选项可让“替代形式”被用于执行转换。 替代形式会针对不同的类型分别定义。  此选项仅适用于整数、浮点数和复数类型。 对于整数类型，当使用二进制、八进制或十六进制输出时，此选项会为输出值分别添加相应的 @code{'0b'}, @code{'0o'}, @code{'0x'} 或 @code{'0X'} 前缀。 对于浮点数和复数类型，替代形式会使得转换结果总是包含小数点符号，即使其不带小数部分。 通常只有在带有小数部分的情况下，此类转换的结果中才会出现小数点符号。 此外，对于 @code{'g'} 和 @code{'G'} 转换，末尾的零不会从结果中被移除。

@geindex @comma{} (comma); in string formatting

@code{','} 选项表示使用逗号作为千位分隔符。 对于感应区域设置的分隔符，请改用 @code{'n'} 整数表示类型。


在 3.1 版更改: 添加了 @code{','} 选项 (另请参阅 
@geindex Python 提高建议; PEP 378
PEP 378@footnote{https://www.python.org/dev/peps/pep-0378})。


@geindex _ (underscore); in string formatting

@code{'_'} 选项表示对浮点表示类型和整数表示类型 @code{'d'} 使用下划线作为千位分隔符。 对于整数表示类型 @code{'b'}, @code{'o'}, @code{'x'} 和 @code{'X'}，将为每 4 个数位插入一个下划线。 对于其他表示类型指定此选项则将导致错误。


在 3.6 版更改: 添加了 @code{'_'} 选项 (另请参阅 
@geindex Python 提高建议; PEP 515
PEP 515@footnote{https://www.python.org/dev/peps/pep-0515})。


@emph{width} 是一个定义最小总字段宽度的十进制整数，包括任何前缀、分隔符和其他格式化字符。 如果未指定，则字段宽度将由内容确定。

当未显式给出对齐方式时，在 @emph{width} 字段前加一个零 (@code{'0'}) 字段将为数字类型启用感知正负号的零填充。 这相当于设置 @emph{fill} 字符为 @code{'0'} 且 @emph{alignment} 类型为 @code{'='}。

@emph{precision} 是一个十进制整数，它表示对于以表示类型 @code{'f'} 和 @code{'F'} 格式化的数值应当在小数点后显示多少个数位，或者对于以表示类型 @code{'g'} 或 @code{'G'} 格式化的数值应当在小数点前后显示多少个数位。 对于字符串表示类型，该字段表示最大的字段大小 ——换句话说，就是要使用多少个来自字段内容的字符。 @emph{precision} 对于整数表示类型是不允许使用的。

最后，@emph{type} 确定了数据应如何呈现。

可用的字符串表示类型是：

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类型

@tab

意义

@item

@code{'s'}

@tab

字符串格式。这是字符串的默认类型，可以省略。

@item

None

@tab

和 @code{'s'} 一样。

@end multitable

@end quotation

可用的整数表示类型是：

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类型

@tab

意义

@item

@code{'b'}

@tab

二进制格式。 输出以 2 为基数的数字。

@item

@code{'c'}

@tab

字符。在打印之前将整数转换为相应的unicode字符。

@item

@code{'d'}

@tab

十进制整数。 输出以 10 为基数的数字。

@item

@code{'o'}

@tab

八进制格式。 输出以 8 为基数的数字。

@item

@code{'x'}

@tab

十六进制格式。 输出以 16 为基数的数字，使用小写字母表示 9 以上的数码。

@item

@code{'X'}

@tab

十六进制格式。 输出以 16 为基数的数字，使用大写字母表示 9 以上的数码。 在指定 @code{'#'} 的情况下，前缀 @code{'0x'} 也将被转为大写形式 @code{'0X'}。

@item

@code{'n'}

@tab

数字。 这与 @code{'d'} 相似，不同之处在于它会使用当前区域设置来插入适当的数字分隔字符。

@item

None

@tab

和 @code{'d'} 相同。

@end multitable

@end quotation

在上述的表示类型之外，整数还可以通过下列的浮点表示类型来格式化 (除了 @code{'n'} 和 @code{None})。 当这样做时，会在格式化之前使用 @ref{1fe,,float()} 将整数转换为浮点数。

@ref{1fe,,float} 和 @ref{2c7,,Decimal} 值的可用表示类型有:

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类型

@tab

意义

@item

@code{'e'}

@tab

科学计数法。 对于一个给定的精度 @code{p}，将数字格式化为以字母 'e' 分隔系数和指数的科学计数法形式。 系数在小数点之前有一位，之后有 @code{p} 位，总计 @code{p + 1} 个有效数位。 如未指定精度，则会对 @ref{1fe,,float} 采用小数点之后 @code{6} 位精度，而对 @ref{2c7,,Decimal} 则显示所有系数位。 如果小数点之后没有数位，则小数点也会被略去，除非使用了 @code{#} 选项。

@item

@code{'E'}

@tab

科学计数法。 与 @code{'e'} 相似，不同之处在于它使用大写字母 'E' 作为分隔字符。

@item

@code{'f'}

@tab

定点表示法。 对于一个给定的精度 @code{p}，将数字格式化为在小数点之后恰好有 @code{p} 位的小数形式。 如未指定精度，则会对 @ref{1fe,,float} 采用小数点之后 @code{6} 位精度，而对 @ref{2c7,,Decimal} 则使用大到足够显示所有系数位的精度。 如果小数点之后没有数位，则小数点也会被略去，除非使用了 @code{#} 选项。

@item

@code{'F'}

@tab

定点表示。 与 @code{'f'} 相似，但会将 @code{nan} 转为  @code{NAN} 并将 @code{inf} 转为 @code{INF}。

@item

@code{'g'}

@tab

常规格式。 对于给定精度 @code{p >= 1}，这会将数值舍入到 @code{p} 个有效数位，再将结果以定点表示法或科学计数法进行格式化，具体取决于其值的大小。 精度 @code{0} 会被视为等价于精度 @code{1}。

准确的规则如下：假设使用表示类型 @code{'e'} 和精度 @code{p-1} 进行格式化的结果具有指数值 @code{exp}。 那么如果 @code{m <= exp < p}，其中 @code{m} 以 -4 表示浮点值而以 -6 表示 @ref{2c7,,Decimal} 值，该数字将使用类型 @code{'f'} 和精度 @code{p-1-exp} 进行格式化。 否则的话，该数字将使用表示类型 @code{'e'} 和精度 @code{p-1} 进行格式化。 在两种情况下，都会从有效数字中移除无意义的末尾零，如果小数点之后没有余下数字则小数点也会被移除，除非使用了 @code{'#'} 选项。

如未指定精度，会对 @ref{1fe,,float} 采用 @code{6} 个有效数位的精度。 对于 @ref{2c7,,Decimal}，结果的系数会沿用原值的系数数位；对于绝对值小于 @code{1e-6} 的值以及最小有效数位的位值大于 1 的数值将会使用科学计数法，在其他情况下则会使用定点表示法。

正负无穷，正负零和 nan 会分别被格式化为 @code{inf}, @code{-inf}, @code{0}, @code{-0} 和 @code{nan}，无论精度如何设定。

@item

@code{'G'}

@tab

常规格式。 类似于 @code{'g'}，不同之处在于当数值非常大时会切换为 @code{'E'}。 无穷与 NaN 也会表示为大写形式。

@item

@code{'n'}

@tab

数字。 这与 @code{'g'} 相似，不同之处在于它会使用当前区域设置来插入适当的数字分隔字符。

@item

@code{'%'}

@tab

百分比。 将数字乘以 100 并显示为定点 (@code{'f'}) 格式，后面带一个百分号。

@item

None

@tab

对于 @ref{1fe,,float} 来说这类似于 @code{'g'}，不同之处在于当使用定点表示法时，小数点之后将至少显示一位。 所用的精度会大到足以精确表示给定的值。

对于 @ref{2c7,,Decimal} 来说这相当于 @code{'g'} 或 @code{'G'}，具体取决于当前 decimal 上下文的 @code{context.capitals} 值。

总体效果是将 @ref{206,,str()} 的输出匹配为其他格式化因子所调整出的样子。

@end multitable

@end quotation

@node 格式示例,,格式规格迷你语言,格式字符串语法
@anchor{library/string format-examples}@anchor{18d9}@anchor{library/string formatexamples}@anchor{18cf}
@subsubsection 格式示例


本节包含 @ref{5dd,,str.format()} 语法的示例以及与旧式 @code{%} 格式化的比较。

该语法在大多数情况下与旧式的 @code{%} 格式化类似，只是增加了 @code{@{@}} 和 @code{:} 来取代 @code{%}。 例如，，@code{'%03.2f'} 可以被改写为 @code{'@{:03.2f@}'}。

新的格式语法还支持新增的不同选项，将在以下示例中说明。

按位置访问参数:

@example
>>> '@{0@}, @{1@}, @{2@}'.format('a', 'b', 'c')
'a, b, c'
>>> '@{@}, @{@}, @{@}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '@{2@}, @{1@}, @{0@}'.format('a', 'b', 'c')
'c, b, a'
>>> '@{2@}, @{1@}, @{0@}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '@{0@}@{1@}@{0@}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'
@end example

按名称访问参数:

@example
>>> 'Coordinates: @{latitude@}, @{longitude@}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = @{'latitude': '37.24N', 'longitude': '-115.81W'@}
>>> 'Coordinates: @{latitude@}, @{longitude@}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
@end example

访问参数的属性:

@example
>>> c = 3-5j
>>> ('The complex number @{0@} is formed from the real part @{0.real@} '
...  'and the imaginary part @{0.imag@}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point(@{self.x@}, @{self.y@})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
@end example

访问参数的项:

@example
>>> coord = (3, 5)
>>> 'X: @{0[0]@};  Y: @{0[1]@}'.format(coord)
'X: 3;  Y: 5'
@end example

替代 @code{%s} 和 @code{%r}:

@example
>>> "repr() shows quotes: @{!r@}; str() doesn't: @{!s@}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
@end example

对齐文本以及指定宽度:

@example
>>> '@{:<30@}'.format('left aligned')
'left aligned                  '
>>> '@{:>30@}'.format('right aligned')
'                 right aligned'
>>> '@{:^30@}'.format('centered')
'           centered           '
>>> '@{:*^30@}'.format('centered')  # use '*' as a fill char
'***********centered***********'
@end example

替代 @code{%+f}, @code{%-f} 和 @code{% f} 以及指定正负号:

@example
>>> '@{:+f@}; @{:+f@}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '@{: f@}; @{: f@}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '@{:-f@}; @{:-f@}'.format(3.14, -3.14)  # show only the minus -- same as '@{:f@}; @{:f@}'
'3.140000; -3.140000'
@end example

替代 @code{%x} 和 @code{%o} 以及转换基于不同进位制的值:

@example
>>> # format also supports binary numbers
>>> "int: @{0:d@};  hex: @{0:x@};  oct: @{0:o@};  bin: @{0:b@}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: @{0:d@};  hex: @{0:#x@};  oct: @{0:#o@};  bin: @{0:#b@}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
@end example

使用逗号作为千位分隔符:

@example
>>> '@{:,@}'.format(1234567890)
'1,234,567,890'
@end example

表示为百分数:

@example
>>> points = 19
>>> total = 22
>>> 'Correct answers: @{:.2%@}'.format(points/total)
'Correct answers: 86.36%'
@end example

使用特定类型的专属格式化:

@example
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '@{:%Y-%m-%d %H:%M:%S@}'.format(d)
'2010-07-04 12:15:58'
@end example

嵌套参数以及更复杂的示例:

@example
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '@{0:@{fill@}@{align@}16@}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '@{:02X@}@{:02X@}@{:02X@}@{:02X@}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12): 
...     for base in 'dXob':
...         print('@{0:@{width@}@{base@}@}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011
@end example

@node 模板字符串,辅助函数,格式字符串语法,string --- 常见的字符串操作
@anchor{library/string id2}@anchor{18da}@anchor{library/string template-strings}@anchor{17c4}
@subsubsection 模板字符串


模板字符串提供了由 
@geindex Python 提高建议; PEP 292
PEP 292@footnote{https://www.python.org/dev/peps/pep-0292} 所描述的更简便的字符串替换方式。 模板字符串的一个主要用例是文本国际化 (i18n)，因为在此场景下，更简单的语法和功能使得文本翻译过程比使用 Python 的其他内置字符串格式化工具更为方便。 作为基于模板字符串构建以实现 i18n 的库的一个示例，请参看 flufl.i18n@footnote{http://flufli18n.readthedocs.io/en/latest/} 包。

@geindex $ (dollar); in template strings

模板字符串支持基于 @code{$} 的替换，使用以下规则：


@itemize *

@item 
@code{$$} 为转义符号；它会被替换为单个的 @code{$}。

@item 
@code{$identifier} 为替换占位符，它会匹配一个名为 @code{"identifier"} 的映射键。 在默认情况下，@code{"identifier"} 限制为任意 ASCII 字母数字（包括下划线）组成的字符串，不区分大小写，以下划线或 ASCII 字母开头。 在 @code{$} 字符之后的第一个非标识符字符将表明占位符的终结。

@item 
@code{$@{identifier@}} 等价于 @code{$identifier}。 当占位符之后紧跟着有效的但又不是占位符一部分的标识符字符时需要使用，例如 @code{"$@{noun@}ification"}。
@end itemize

在字符串的其他位置出现 @code{$} 将导致引发 @ref{16d,,ValueError}。

@ref{f6,,string} 模块提供了实现这些规则的 @ref{4f9,,Template} 类。 @ref{4f9,,Template} 有下列方法：

@geindex Template (string 中的类)
@anchor{library/string string Template}@anchor{4f9}
@deffn {类} string.Template (template)

该构造器接受一个参数作为模板字符串。

@geindex substitute() (string.Template 方法)
@anchor{library/string string Template substitute}@anchor{1464}
@deffn {方法} substitute (mapping=@{@}, /, **kwds)

执行模板替换，返回一个新字符串。 @emph{mapping} 为任意字典类对象，其中的键将匹配模板中的占位符。 或者你也可以提供一组关键字参数，其中的关键字即对应占位符。 当同时给出 @emph{mapping} 和 @emph{kwds} 并且存在重复时，则以 @emph{kwds} 中的占位符为优先。
@end deffn

@geindex safe_substitute() (string.Template 方法)
@anchor{library/string string Template safe_substitute}@anchor{1465}
@deffn {方法} safe_substitute (mapping=@{@}, /, **kwds)

类似于 @ref{1464,,substitute()}，不同之处是如果有占位符未在 @emph{mapping} 和 @emph{kwds} 中找到，不是引发 @ref{3f1,,KeyError} 异常，而是将原始占位符不加修改地显示在结果字符串中。 另一个与 @ref{1464,,substitute()} 的差异是任何在其他情况下出现的 @code{$} 将简单地返回 @code{$} 而不是引发 @ref{16d,,ValueError}。

此方法被认为“安全”，因为虽然仍有可能发生其他异常，但它总是尝试返回可用的字符串而不是引发一个异常。 从另一方面来说，@ref{1465,,safe_substitute()} 也可能根本算不上安全，因为它将静默地忽略错误格式的模板，例如包含多余的分隔符、不成对的花括号或不是合法 Python 标识符的占位符等等。
@end deffn

@ref{4f9,,Template} 的实例还提供一个公有数据属性：

@geindex template (string.Template 属性)
@anchor{library/string string Template template}@anchor{18db}
@deffn {属性} template

这是作为构造器的 @emph{template} 参数被传入的对象。 一般来说，你不应该修改它，但并不强制要求只读访问。
@end deffn
@end deffn

以下是一个如何使用模版的示例：

@example
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
@end example

进阶用法：你可以派生 @ref{4f9,,Template} 的子类来自定义占位符语法、分隔符，或用于解析模板字符串的整个正则表达式。 为此目的，你可以重载这些类属性：


@itemize *

@item 
@emph{delimiter} -- 这是用来表示占位符的起始的分隔符的字符串字面值。 默认值为 @code{$}。 请注意此参数 @emph{不能} 为正则表达式，因为其实现将在必要时对此字符串调用 @ref{598,,re.escape()}。 还要注意你不能在创建类之后改变此分隔符（例如在子类的类命名空间中必须设置不同的分隔符）。

@item 
@emph{idpattern} -- 这是用来描述不带花括号的占位符的模式的正则表达式。 默认值为正则表达式 @code{(?a:[_a-z][_a-z0-9]*)}。 如果给出了此属性并且 @emph{braceidpattern} 为 @code{None} 则此模式也将作用于带花括号的占位符。

@cartouche
@quotation 注解 
由于默认的 @emph{flags} 为 @code{re.IGNORECASE}，模式 @code{[a-z]} 可以匹配某些非 ASCII 字符。 因此我们在这里使用了局部旗标 @code{a}。
@end quotation
@end cartouche


在 3.7 版更改: @emph{braceidpattern} 可被用来定义对花括号内部和外部进行区分的模式。


@item 
@emph{braceidpattern} -- 此属性类似于 @emph{idpattern} 但是用来描述带花括号的占位符的模式。 默认值 @code{None} 意味着回退到 @emph{idpattern} (即在花括号内部和外部使用相同的模式)。 如果给出此属性，这将允许你为带花括号和不带花括号的占位符定义不同的模式。


3.7 新版功能.


@item 
@emph{flags} -- 将在编译用于识别替换内容的正则表达式被应用的正则表达式旗标。 默认值为 @code{re.IGNORECASE}。 请注意 @code{re.VERBOSE} 总是会被加为旗标，因此自定义的 @emph{idpattern} 必须遵循详细正则表达式的约定。


3.2 新版功能.

@end itemize

作为另一种选项，你可以通过重载类属性 @emph{pattern} 来提供整个正则表达式模式。 如果你这样做，该值必须为一个具有四个命名捕获组的正则表达式对象。 这些捕获组对应于上面已经给出的规则，以及无效占位符的规则：


@itemize *

@item 
@emph{escaped} -- 这个组匹配转义序列，在默认模式中即 @code{$$}。

@item 
@emph{named} -- 这个组匹配不带花括号的占位符名称；它不应当包含捕获组中的分隔符。

@item 
@emph{braced} -- 这个组匹配带有花括号的占位符名称；它不应当包含捕获组中的分隔符或者花括号。

@item 
@emph{invalid} -- 这个组匹配任何其他分隔符模式（通常为单个分隔符），并且它应当出现在正则表达式的末尾。
@end itemize

@node 辅助函数,,模板字符串,string --- 常见的字符串操作
@anchor{library/string helper-functions}@anchor{18dc}
@subsubsection 辅助函数


@geindex capwords() (在 string 模块中)
@anchor{library/string string capwords}@anchor{17c0}
@deffn {函数} string.capwords (s, sep=None)

使用 @ref{89a,,str.split()} 将参数拆分为单词，使用 @ref{17a6,,str.capitalize()} 将单词转为大写形式，使用 @ref{1796,,str.join()} 将大写的单词进行拼接。 如果可选的第二个参数 @emph{sep} 被省略或为 @code{None}，则连续的空白字符会被替换为单个空格符并且开头和末尾的空白字符会被移除，否则 @emph{sep} 会被用来拆分和拼接单词。
@end deffn

@node re --- 正则表达式操作,difflib --- 计算差异的辅助工具,string --- 常见的字符串操作,文本处理服务
@anchor{library/re doc}@anchor{18dd}@anchor{library/re module-re}@anchor{dd}@anchor{library/re re-regular-expression-operations}@anchor{18de}
@subsection @code{re} --- 正则表达式操作


@geindex re (模块)

@strong{源代码:} Lib/re.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/re.py}


__________________________________________________________________


本模块提供了与 Perl 语言类似的正则表达式匹配操作。

模式和被搜索的字符串既可以是 Unicode 字符串 (@ref{206,,str}) ，也可以是8位字节串 (@ref{172,,bytes})。 但是，Unicode 字符串与 8 位字节串不能混用：也就是说，不能用字节串模式匹配 Unicode 字符串，反之亦然；同理，替换操作时，替换字符串的类型也必须与所用的模式和搜索字符串的类型一致。

正则表达式用反斜杠字符 (@code{'\'}) 表示特殊形式，或是允许在使用特殊字符时，不引发它们的特殊含义。 这与 Python 的字符串字面值中对相同字符出于相同目的的用法产生冲突；例如，要匹配一个反斜杠字面值，用户可能必须写成 @code{'\\\\'} 来作为模式字符串，因为正则表达式必须为 @code{\\}，而每个反斜杠在普通 Python 字符串字面值中又必须表示为 @code{\\}。 而且还要注意，在 Python 的字符串字面值中使用的反斜杠如果有任何无效的转义序列，现在会触发 @ref{15a,,DeprecationWarning}，但以后会改为 @ref{562,,SyntaxError}。 此行为即使对于正则表达式来说有效的转义字符同样会发生。

解决办法是对于正则表达式样式使用 Python 的原始字符串表示法；在带有 @code{'r'} 前缀的字符串字面值中，反斜杠不必做任何特殊处理。 因此 @code{r"\n"} 表示包含 @code{'\'} 和 @code{'n'} 两个字符的字符串，而 @code{"\n"} 则表示只包含一个换行符的字符串。 样式在 Python 代码中通常都使用原始字符串表示法。

绝大多数正则表达式操作都提供为模块函数和方法，在 @ref{98c,,编译正则表达式}.  这些函数是一个捷径，不需要先编译正则对象，但是损失了一些优化参数。


@subsubheading 参见


第三方模块 regex@footnote{https://pypi.org/project/regex/} , 提供了与标准库 @ref{dd,,re} 模块兼容的 API 接口，同时，还提供了更多功能和更全面的 Unicode 支持。


@menu
* 正则表达式语法:: 
* 模块内容:: 
* 正则表达式对象 （正则对象）:: 
* 匹配对象:: 
* 正则表达式例子:: 

@end menu

@node 正则表达式语法,模块内容,,re --- 正则表达式操作
@anchor{library/re re-syntax}@anchor{18df}@anchor{library/re regular-expression-syntax}@anchor{18e0}
@subsubsection 正则表达式语法


正则表达式（或 RE）指定了一组与之匹配的字符串；模块内的函数可以检查某个字符串是否与给定的正则表达式匹配（或者正则表达式是否匹配到字符串，这两种说法含义相同）。

正则表达式可以拼接；如果 @emph{A} 和 @emph{B} 都是正则表达式，则 @emph{AB} 也是正则表达式。通常，如果字符串 @emph{p} 匹配 @emph{A}，并且另一个字符串 @emph{q} 匹配 @emph{B}，那么 @emph{pq} 可以匹配 AB。除非 @emph{A} 或者 @emph{B} 包含低优先级操作，@emph{A} 和 @emph{B} 存在边界条件；或者命名组引用。所以，复杂表达式可以很容易的从这里描述的简单源语表达式构建。更多正则表达式理论和实现，详见 the Friedl book @ref{18e1,,[Frie09]} ，或者其他构建编译器的书籍。

以下是正则表达式格式的简要说明。更详细的信息和演示，参考  @ref{18e2,,正则表达式HOWTO}。

正则表达式可以包含普通或者特殊字符。绝大部分普通字符，比如 @code{'A'}, @code{'a'}, 或者 @code{'0'}，都是最简单的正则表达式。它们就匹配自身。你可以拼接普通字符，所以 @code{last} 匹配字符串 @code{'last'}.  （在这一节的其他部分，我们将用 @code{this special style} 这种方式表示正则表达式，通常不带引号，要匹配的字符串用 @code{'in single quotes'} ，单引号形式。）

有些字符，比如 @code{'|'} 或者 @code{'('}，属于特殊字符。 特殊字符既可以表示它的普通含义， 也可以影响它旁边的正则表达式的解释。

重复修饰符 (@code{*}, @code{+}, @code{?}, @code{@{m,n@}}, 等) 不能直接嵌套。这样避免了非贪婪后缀 @code{?} 修饰符，和其他实现中的修饰符产生的多义性。要应用一个内层重复嵌套，可以使用括号。 比如，表达式 @code{(?:a@{6@})*} 匹配6个 @code{'a'} 字符重复任意次数。

特殊字符有：

@geindex . (dot); in regular expressions


@table @asis

@item @code{.}

(点) 在默认模式，匹配除了换行的任意字符。如果指定了标签 @ref{18e3,,DOTALL} ，它将匹配包括换行符的任意字符。
@end table

@geindex ^ (caret); in regular expressions


@table @asis

@item @code{^}

(插入符号)  匹配字符串的开头， 并且在 @ref{18e4,,MULTILINE} 模式也匹配换行后的首个符号。
@end table

@geindex $ (dollar); in regular expressions


@table @asis

@item @code{$}

匹配字符串尾或者在字符串尾的换行符的前一个字符，在 @ref{18e4,,MULTILINE} 模式下也会匹配换行符之前的文本。 @code{foo} 匹配 'foo' 和 'foobar'，但正则表达式 @code{foo$} 只匹配 'foo'。 更有趣的是，在 @code{'foo1\nfoo2\n'} 中搜索 @code{foo.$}，通常匹配  'foo2'，但在 @ref{18e4,,MULTILINE} 模式下可以匹配到 'foo1'；在 @code{'foo\n'} 中搜索 @code{$} 会找到两个（空的）匹配：一个在换行符之前，一个在字符串的末尾。
@end table

@geindex * (asterisk); in regular expressions


@table @asis

@item @code{*}

对它前面的正则式匹配0到任意次重复， 尽量多的匹配字符串。  @code{ab*} 会匹配 @code{'a'}，@code{'ab'}，或者 @code{'a'} 后面跟随任意个 @code{'b'}。
@end table

@geindex + (plus); in regular expressions


@table @asis

@item @code{+}

对它前面的正则式匹配1到任意次重复。 @code{ab+} 会匹配 @code{'a'} 后面跟随1个以上到任意个 @code{'b'}，它不会匹配 @code{'a'}。
@end table

@geindex ? (question mark); in regular expressions


@table @asis

@item @code{?}

对它前面的正则式匹配0到1次重复。 @code{ab?} 会匹配 @code{'a'} 或者 @code{'ab'}。
@end table

@geindex *?; in regular expressions
@geindex +?; in regular expressions
@geindex ??; in regular expressions


@table @asis

@item @code{*?}, @code{+?}, @code{??}

@code{'*'}, @code{'+'}，和 @code{'?'} 修饰符都是 @emph{贪婪的}；它们在字符串进行尽可能多的匹配。有时候并不需要这种行为。如果正则式 @code{<.*>} 希望找到 @code{'<a> b <c>'}，它将会匹配整个字符串，而不仅是 @code{'<a>'}。在修饰符之后添加 @code{?} 将使样式以 @emph{非贪婪`方式或者 :dfn:`最小} 方式进行匹配； 尽量 @emph{少} 的字符将会被匹配。 使用正则式 @code{<.*?>} 将会仅仅匹配 @code{'<a>'}。
@end table

@geindex @{@} (curly brackets); in regular expressions


@table @asis

@item @code{@{m@}}

对其之前的正则式指定匹配 @emph{m} 个重复；少于 @emph{m} 的话就会导致匹配失败。比如， @code{a@{6@}} 将匹配6个 @code{'a'} , 但是不能是5个。

@item @code{@{m,n@}}

对正则式进行 @emph{m} 到 @emph{n} 次匹配，在 @emph{m} 和 @emph{n} 之间取尽量多。 比如，@code{a@{3,5@}} 将匹配 3 到 5个 @code{'a'}。忽略 @emph{m} 意为指定下界为0，忽略 @emph{n} 指定上界为无限次。 比如 @code{a@{4,@}b} 将匹配 @code{'aaaab'} 或者1000个 @code{'a'} 尾随一个 @code{'b'}，但不能匹配 @code{'aaab'}。逗号不能省略，否则无法辨别修饰符应该忽略哪个边界。

@item @code{@{m,n@}?}

前一个修饰符的非贪婪模式，只匹配尽量少的字符次数。比如，对于 @code{'aaaaaa'}， @code{a@{3,5@}} 匹配 5个 @code{'a'} ，而 @code{a@{3,5@}?} 只匹配3个 @code{'a'}。
@end table

@geindex \ (backslash); in regular expressions


@table @asis

@item @code{\}

转义特殊字符（允许你匹配 @code{'*'}, @code{'?'}, 或者此类其他），或者表示一个特殊序列；特殊序列之后进行讨论。

如果你没有使用原始字符串（ @code{r'raw'} ）来表达样式，要牢记Python也使用反斜杠作为转义序列；如果转义序列不被Python的分析器识别，反斜杠和字符才能出现在字符串中。如果Python可以识别这个序列，那么反斜杠就应该重复两次。这将导致理解障碍，所以高度推荐，就算是最简单的表达式，也要使用原始字符串。
@end table

@geindex [] (square brackets); in regular expressions


@table @asis

@item @code{[]}

用于表示一个字符集合。在一个集合中：


@itemize *

@item 
字符可以单独列出，比如 @code{[amk]} 匹配 @code{'a'}， @code{'m'}， 或者 @code{'k'}。
@end itemize

@geindex - (minus); in regular expressions


@itemize *

@item 
可以表示字符范围，通过用 @code{'-'} 将两个字符连起来。比如 @code{[a-z]} 将匹配任何小写ASCII字符， @code{[0-5][0-9]} 将匹配从 @code{00} 到 @code{59} 的两位数字， @code{[0-9A-Fa-f]} 将匹配任何十六进制数位。 如果 @code{-} 进行了转义 （比如 @code{[a\-z]}）或者它的位置在首位或者末尾（如 @code{[-a]} 或 @code{[a-]}），它就只表示普通字符 @code{'-'}。

@item 
特殊字符在集合中，失去它的特殊含义。比如 @code{[(+*)]} 只会匹配这几个文法字符 @code{'('}, @code{'+'}, @code{'*'}, or @code{')'}。
@end itemize

@geindex \ (backslash); in regular expressions


@itemize *

@item 
字符类如 @code{\w} 或者 @code{\S} (如下定义) 在集合内可以接受，它们可以匹配的字符由 @ref{4d7,,ASCII} 或者 @ref{4d8,,LOCALE} 模式决定。
@end itemize

@geindex ^ (caret); in regular expressions


@itemize *

@item 
不在集合范围内的字符可以通过 @emph{取反} 来进行匹配。如果集合首字符是 @code{'^'} ，所有 @emph{不} 在集合内的字符将会被匹配，比如 @code{[^5]} 将匹配所有字符，除了 @code{'5'}， @code{[^^]} 将匹配所有字符，除了 @code{'^'}.  @code{^} 如果不在集合首位，就没有特殊含义。

@item 
在集合内要匹配一个字符 @code{']'}，有两种方法，要么就在它之前加上反斜杠，要么就把它放到集合首位。比如， @code{[()[\]@{@}]} 和 @code{[]()[@{@}]} 都可以匹配括号。
@end itemize

@c .. index:: single: --; in regular expressions

@c .. index:: single: &&; in regular expressions

@c .. index:: single: ~~; in regular expressions

@c .. index:: single: ||; in regular expressions


@itemize *

@item 
Unicode Technical Standard #18@footnote{https://unicode.org/reports/tr18/} 里的嵌套集合和集合操作支持可能在未来添加。这将会改变语法，所以为了帮助这个改变，一个 @ref{43e,,FutureWarning} 将会在有多义的情况里被 @code{raise}，包含以下几种情况，集合由 @code{'['} 开始，或者包含下列字符序列  @code{'--'}, @code{'&&'}, @code{'~~'}, 和 @code{'||'}。为了避免警告，需要将它们用反斜杠转义。
@end itemize


在 3.7 版更改: 如果一个字符串构建的语义在未来会改变的话，一个 @ref{43e,,FutureWarning} 会 @code{raise} 。

@end table

@geindex | (vertical bar); in regular expressions


@table @asis

@item @code{|}

@code{A|B}， @emph{A} 和 @emph{B} 可以是任意正则表达式，创建一个正则表达式，匹配 @emph{A} 或者 @emph{B}.  任意个正则表达式可以用 @code{'|'} 连接。它也可以在组合（见下列）内使用。扫描目标字符串时， @code{'|'} 分隔开的正则样式从左到右进行匹配。当一个样式完全匹配时，这个分支就被接受。意思就是，一旦 @emph{A} 匹配成功， @emph{B} 就不再进行匹配，即便它能产生一个更好的匹配。或者说，@code{'|'} 操作符绝不贪婪。  如果要匹配 @code{'|'} 字符，使用 @code{\|}， 或者把它包含在字符集里，比如 @code{[|]}.
@end table

@geindex () (parentheses); in regular expressions


@table @asis

@item @code{(...)}

（组合），匹配括号内的任意正则表达式，并标识出组合的开始和结尾。匹配完成后，组合的内容可以被获取，并可以在之后用  @code{\number} 转义序列进行再次匹配，之后进行详细说明。要匹配字符 @code{'('} 或者 @code{')'}, 用 @code{\(} 或 @code{\)}, 或者把它们包含在字符集合里: @code{[(]}, @code{[)]}.
@end table

@geindex (?; in regular expressions


@table @asis

@item @code{(?…)}

这是个扩展标记法 （一个 @code{'?'} 跟随 @code{'('} 并无含义）。  @code{'?'} 后面的第一个字符决定了这个构建采用什么样的语法。这种扩展通常并不创建新的组合； @code{(?P<name>...)} 是唯一的例外。 以下是目前支持的扩展。

@item @code{(?aiLmsux)}

( @code{'a'}, @code{'i'}, @code{'L'}, @code{'m'}, @code{'s'}, @code{'u'}, @code{'x'} 中的一个或多个) 这个组合匹配一个空字符串；这些字符对正则表达式设置以下标记 @ref{18e5,,re.A} (只匹配ASCII字符), @ref{18e6,,re.I} (忽略大小写), @ref{18e7,,re.L} (语言依赖), @ref{18e8,,re.M} (多行模式), @ref{18e9,,re.S} (点dot匹配全部字符), @code{re.U} (Unicode匹配), and @ref{18ea,,re.X} (冗长模式)。 (这些标记在 @ref{18eb,,模块内容} 中描述) 如果你想将这些标记包含在正则表达式中，这个方法就很有用，免去了在 @ref{555,,re.compile()} 中传递 @emph{flag} 参数。标记应该在表达式字符串首位表示。
@end table

@geindex (?;; in regular expressions


@table @asis

@item @code{(?:…)}

正则括号的非捕获版本。 匹配在括号内的任何正则表达式，但该分组所匹配的子字符串 @emph{不能} 在执行匹配后被获取或是之后在模式中被引用。

@item @code{(?aiLmsux-imsx:…)}

(@code{'a'}, @code{'i'}, @code{'L'}, @code{'m'}, @code{'s'}, @code{'u'}, @code{'x'} 中的0或者多个， 之后可选跟随 @code{'-'} 在后面跟随 @code{'i'} , @code{'m'} , @code{'s'} , @code{'x'} 中的一到多个 .) 这些字符为表达式的其中一部分 @emph{设置} 或者 @emph{去除} 相应标记 @ref{18e5,,re.A} (只匹配ASCII), @ref{18e6,,re.I} (忽略大小写), @ref{18e7,,re.L} (语言依赖), @ref{18e8,,re.M} (多行), @ref{18e9,,re.S} (点匹配所有字符), @code{re.U} (Unicode匹配), and @ref{18ea,,re.X} (冗长模式)。(标记描述在 @ref{18eb,,模块内容} .)

@code{'a'}, @code{'L'} and @code{'u'} 作为内联标记是相互排斥的， 所以它们不能结合在一起，或者跟随 @code{'-'} 。 当他们中的某个出现在内联组中，它就覆盖了括号组内的匹配模式。在Unicode样式中， @code{(?a:...)} 切换为 只匹配ASCII， @code{(?u:...)} 切换为Unicode匹配 (默认).  在byte样式中 @code{(?L:...)} 切换为语言依赖模式， @code{(?a:...)} 切换为 只匹配ASCII (默认)。这种方式只覆盖组合内匹配，括号外的匹配模式不受影响。


3.6 新版功能.



在 3.7 版更改: 符号 @code{'a'}, @code{'L'} 和 @code{'u'} 同样可以用在一个组合内。

@end table

@geindex (?P<; in regular expressions


@table @asis

@item @code{(?P<name>…)}

（命名组合）类似正则组合，但是匹配到的子串组在外部是通过定义的 @emph{name} 来获取的。组合名必须是有效的Python标识符，并且每个组合名只能用一个正则表达式定义，只能定义一次。一个符号组合同样是一个数字组合，就像这个组合没有被命名一样。

命名组合可以在三种上下文中引用。如果样式是 @code{(?P<quote>['"]).*?(?P=quote)} （也就是说，匹配单引号或者双引号括起来的字符串)：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

引用组合 "quote" 的上下文

@tab

引用方法

@item

在正则式自身内

@tab


@itemize *

@item 
@code{(?P=quote)} (如示)

@item 
@code{\1}
@end itemize

@item

处理匹配对象 @emph{m}

@tab


@itemize *

@item 
@code{m.group('quote')}

@item 
@code{m.end('quote')} (等)
@end itemize

@item

传递到 @code{re.sub()} 里的 @emph{repl} 参数中

@tab


@itemize *

@item 
@code{\g<quote>}

@item 
@code{\g<1>}

@item 
@code{\1}
@end itemize

@end multitable

@end table

@geindex (?P=; in regular expressions


@table @asis

@item @code{(?P=name)}

反向引用一个命名组合；它匹配前面那个叫 @emph{name} 的命名组中匹配到的串同样的字串。
@end table

@geindex (?#; in regular expressions


@table @asis

@item @code{(?#…)}

注释；里面的内容会被忽略。
@end table

@geindex (?=; in regular expressions


@table @asis

@item @code{(?=…)}

匹配 @code{…} 的内容，但是并不消费样式的内容。这个叫做 @emph{lookahead assertion}。比如， @code{Isaac (?=Asimov)} 匹配 @code{'Isaac '} 只有在后面是  @code{'Asimov'} 的时候。
@end table

@geindex (?!; in regular expressions


@table @asis

@item @code{(?!…)}

匹配 @code{…} 不符合的情况。这个叫 @emph{negative lookahead assertion} （前视取反）。比如说， @code{Isaac (?!Asimov)} 只有后面 @emph{不} 是 @code{'Asimov'} 的时候才匹配 @code{'Isaac '} 。
@end table

@geindex (?<=; in regular expressions


@table @asis

@item @code{(?<=…)}

匹配字符串的当前位置，它的前面匹配 @code{...} 的内容到当前位置。这叫 @emph{positive lookbehind assertion} （正向后视断定）。 @code{(?<=abc)def} 会在 @code{'abcdef'} 中找到一个匹配，因为后视会往后看3个字符并检查是否包含匹配的样式。包含的匹配样式必须是定长的，意思就是 @code{abc} 或 @code{a|b} 是允许的，但是 @code{a*} 和 @code{a@{3,4@}} 不可以。注意以 positive lookbehind assertions 开始的样式，如 @code{(?<=abc)def} ，并不是从 a 开始搜索，而是从 d 往回看的。你可能更加愿意使用 @ref{c8a,,search()} 函数，而不是 @ref{c8b,,match()} 函数：

@example
>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
@end example

这个例子搜索一个跟随在连字符后的单词：

@example
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
@end example


在 3.5 版更改: 添加定长组合引用的支持。

@end table

@geindex (?<!; in regular expressions


@table @asis

@item @code{(?<!…)}

匹配当前位置之前不是 @code{...} 的样式。这个叫 @emph{negative lookbehind assertion} （后视断定取非）。类似正向后视断定，包含的样式匹配必须是定长的。由 negative lookbehind assertion 开始的样式可以从字符串搜索开始的位置进行匹配。

@item @code{(?(id/name)yes-pattern|no-pattern)}

如果给定的  @emph{id} 或 @emph{name} 存在，将会尝试匹配 @code{yes-pattern} ，否则就尝试匹配 @code{no-pattern}，@code{no-pattern} 可选，也可以被忽略。比如， @code{(<)?(\w+@@\w+(?:\.\w+)+)(?(1)>|$)} 是一个email样式匹配，将匹配 @code{'<user@@host.com>'} 或 @code{'user@@host.com'} ，但不会匹配 @code{'<user@@host.com'} ，也不会匹配 @code{'user@@host.com>'}。
@end table

由 @code{'\'} 和一个字符组成的特殊序列在以下列出。 如果普通字符不是ASCII数位或者ASCII字母，那么正则样式将匹配第二个字符。比如，@code{\$} 匹配字符 @code{'$'}.

@geindex \ (backslash); in regular expressions


@table @asis

@item @code{\number}

匹配数字代表的组合。每个括号是一个组合，组合从1开始编号。比如 @code{(.+) \1} 匹配 @code{'the the'} 或者 @code{'55 55'}, 但不会匹配 @code{'thethe'} (注意组合后面的空格)。这个特殊序列只能用于匹配前面99个组合。如果  @emph{number} 的第一个数位是0， 或者 @emph{number} 是三个八进制数，它将不会被看作是一个组合，而是八进制的数字值。在 @code{'['} 和 @code{']'} 字符集合内，任何数字转义都被看作是字符。
@end table

@geindex \A; in regular expressions


@table @asis

@item @code{\A}

只匹配字符串开始。
@end table

@geindex \b; in regular expressions


@table @asis

@item @code{\b}

匹配空字符串，但只在单词开始或结尾的位置。一个单词被定义为一个单词字符的序列。注意，通常 @code{\b} 定义为 @code{\w} 和 @code{\W} 字符之间，或者 @code{\w} 和字符串开始/结尾的边界， 意思就是 @code{r'\bfoo\b'} 匹配 @code{'foo'}, @code{'foo.'}, @code{'(foo)'}, @code{'bar foo baz'} 但不匹配 @code{'foobar'} 或者 @code{'foo3'}。

默认情况下，Unicode字母和数字是在Unicode样式中使用的，但是可以用  @ref{4d7,,ASCII} 标记来更改。如果 @ref{4d8,,LOCALE} 标记被设置的话，词的边界是由当前语言区域设置决定的，@code{\b} 表示退格字符，以便与Python字符串文本兼容。
@end table

@geindex \B; in regular expressions


@table @asis

@item @code{\B}

匹配空字符串，但 @emph{不} 能在词的开头或者结尾。意思就是 @code{r'py\B'} 匹配 @code{'python'}, @code{'py3'}, @code{'py2'}, 但不匹配 @code{'py'}, @code{'py.'}, 或者 @code{'py!'}. @code{\B} 是 @code{\b} 的取非，所以Unicode样式的词语是由Unicode字母，数字或下划线构成的，虽然可以用 @ref{4d7,,ASCII} 标志来改变。如果使用了 @ref{4d8,,LOCALE} 标志，则词的边界由当前语言区域设置。
@end table

@geindex \d; in regular expressions


@table @asis

@item @code{\d}


@table @asis

@item 对于 Unicode (str) 样式：

匹配任何Unicode十进制数（就是在Unicode字符目录[Nd]里的字符）。这包括了 @code{[0-9]} ，和很多其他的数字字符。如果设置了 @ref{4d7,,ASCII} 标志，就只匹配 @code{[0-9]} 。

@item 对于8位(bytes)样式：

匹配任何十进制数，就是 @code{[0-9]}。
@end table
@end table

@geindex \D; in regular expressions


@table @asis

@item @code{\D}

匹配任何非十进制数字的字符。就是 @code{\d} 取非。 如果设置了 @ref{4d7,,ASCII} 标志，就相当于 @code{[^0-9]} 。
@end table

@geindex \s; in regular expressions


@table @asis

@item @code{\s}


@table @asis

@item 对于 Unicode (str) 样式：

匹配任何Unicode空白字符（包括 @code{[ \t\n\r\f\v]} ，还有很多其他字符，比如不同语言排版规则约定的不换行空格）。如果 @ref{4d7,,ASCII} 被设置，就只匹配 @code{[ \t\n\r\f\v]} 。

@item 对于8位(bytes)样式：

匹配ASCII中的空白字符，就是 @code{[ \t\n\r\f\v]} 。
@end table
@end table

@geindex \S; in regular expressions


@table @asis

@item @code{\S}

匹配任何非空白字符。就是 @code{\s} 取非。如果设置了 @ref{4d7,,ASCII} 标志，就相当于 @code{[^ \t\n\r\f\v]} 。
@end table

@geindex \w; in regular expressions


@table @asis

@item @code{\w}


@table @asis

@item 对于 Unicode (str) 样式：

匹配Unicode词语的字符，包含了可以构成词语的绝大部分字符，也包括数字和下划线。如果设置了 @ref{4d7,,ASCII} 标志，就只匹配 @code{[a-zA-Z0-9_]} 。

@item 对于8位(bytes)样式：

匹配ASCII字符中的数字和字母和下划线，就是 @code{[a-zA-Z0-9_]} 。如果设置了 @ref{4d8,,LOCALE} 标记，就匹配当前语言区域的数字和字母和下划线。
@end table
@end table

@geindex \W; in regular expressions


@table @asis

@item @code{\W}

匹配非单词字符的字符。这与 @code{\w} 正相反。如果使用了 @ref{4d7,,ASCII} 旗标，这就等价于 @code{[^a-zA-Z0-9_]}。如果使用了 @ref{4d8,,LOCALE} 旗标，则会匹配当前区域中既非字母数字也非下划线的字符。
@end table

@geindex \Z; in regular expressions


@table @asis

@item @code{\Z}

只匹配字符串尾。
@end table

@geindex \a; in regular expressions
@geindex \b; in regular expressions
@geindex \f; in regular expressions
@geindex \n; in regular expressions
@geindex \N; in regular expressions
@geindex \r; in regular expressions
@geindex \t; in regular expressions
@geindex \u; in regular expressions
@geindex \U; in regular expressions
@geindex \v; in regular expressions
@geindex \x; in regular expressions
@geindex \\; in regular expressions

绝大部分Python的标准转义字符也被正则表达式分析器支持。:

@example
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
@end example

（注意 @code{\b} 被用于表示词语的边界，它只在字符集合内表示退格，比如 @code{[\b]} 。）

@code{'\u'}, @code{'\U'} 和 @code{'\N'} 转义序列只在 Unicode 模式中可被识别。 在 bytes 模式中它们会导致错误。 未知的 ASCII 字母转义序列保留在未来使用，会被当作错误来处理。

八进制转义包含为一个有限形式。如果首位数字是 0， 或者有三个八进制数位，那么就认为它是八进制转义。其他的情况，就看作是组引用。对于字符串文本，八进制转义最多有三个数位长。


在 3.3 版更改: 增加了 @code{'\u'} 和 @code{'\U'} 转义序列。



在 3.6 版更改: 由 @code{'\'} 和一个ASCII字符组成的未知转义会被看成错误。



在 3.8 版更改: 添加了 @code{'\N@{name@}'} 转义序列。 与在字符串字面值中一样，它扩展了命名 Unicode 字符 (例如 @code{'\N@{EM DASH@}'})。


@node 模块内容,正则表达式对象 （正则对象）,正则表达式语法,re --- 正则表达式操作
@anchor{library/re contents-of-module-re}@anchor{18eb}@anchor{library/re module-contents}@anchor{18ec}
@subsubsection 模块内容


模块定义了几个函数、常量，和一个异常。有些函数是编译后的正则表达式方法的简化版本（少了一些特性）。重要的应用程序大多会在使用前先编译正则表达式。


在 3.6 版更改: 标志常量现在是 @code{RegexFlag} 类的实例，这个类是 @ref{18ed,,enum.IntFlag} 的子类。


@geindex compile() (在 re 模块中)
@anchor{library/re re compile}@anchor{555}
@deffn {函数} re.compile (pattern, flags=0)

将正则表达式的样式编译为一个 @ref{98c,,正则表达式对象}  （正则对象），可以用于匹配，通过这个对象的方法  @ref{18ee,,match()}, @ref{18ef,,search()} 以及其他如下描述。

这个表达式的行为可以通过指定 @emph{标记} 的值来改变。值可以是以下任意变量，可以通过位的OR操作来结合（ @code{|} 操作符）。

序列

@example
prog = re.compile(pattern)
result = prog.match(string)
@end example

等价于

@example
result = re.match(pattern, string)
@end example

如果需要多次使用这个正则表达式的话，使用 @ref{555,,re.compile()} 和保存这个正则对象以便复用，可以让程序更加高效。

@cartouche
@quotation 注解 
通过 @ref{555,,re.compile()} 编译后的样式，和模块级的函数会被缓存， 所以少数的正则表达式使用无需考虑编译的问题。
@end quotation
@end cartouche
@end deffn

@geindex A() (在 re 模块中)
@geindex ASCII() (在 re 模块中)
@anchor{library/re re A}@anchor{18e5}
@deffn {数据} re.A
@anchor{library/re re ASCII}@anchor{4d7}
@deffnx {数据} re.ASCII

让 @code{\w}, @code{\W}, @code{\b}, @code{\B}, @code{\d}, @code{\D}, @code{\s} 和 @code{\S} 只匹配ASCII，而不是Unicode。这只对Unicode样式有效，会被byte样式忽略。相当于前面语法中的内联标志 @code{(?a)} 。

注意，为了保持向后兼容， @code{re.U} 标记依然存在（还有他的同义  @code{re.UNICODE} 和嵌入形式 @code{(?u)} ) ， 但是这些在 Python 3 是冗余的，因为默认字符串已经是Unicode了（并且Unicode匹配不允许byte出现)。
@end deffn

@geindex DEBUG() (在 re 模块中)
@anchor{library/re re DEBUG}@anchor{18f0}
@deffn {数据} re.DEBUG

显示编译时的debug信息，没有内联标记。
@end deffn

@geindex I() (在 re 模块中)
@geindex IGNORECASE() (在 re 模块中)
@anchor{library/re re I}@anchor{18e6}
@deffn {数据} re.I
@anchor{library/re re IGNORECASE}@anchor{18f1}
@deffnx {数据} re.IGNORECASE

进行忽略大小写匹配；表达式如 @code{[A-Z]} 也会匹配小写字符。Unicode匹配（比如 @code{Ü} 匹配 @code{ü}）同样有用，除非设置了 @ref{4d7,,re.ASCII} 标记来禁用非ASCII匹配。当前语言区域不会改变这个标记，除非设置了 @ref{4d8,,re.LOCALE} 标记。这个相当于内联标记 @code{(?i)} 。

注意，当设置了 @ref{18f1,,IGNORECASE} 标记，搜索Unicode样式 @code{[a-z]} 或 @code{[A-Z]} 的结合时，它将会匹配52个ASCII字符和4个额外的非ASCII字符： 'İ' (U+0130, 拉丁大写的 I 带个点在上面), 'ı' (U+0131, 拉丁小写没有点的 I ), 'ſ' (U+017F, 拉丁小写长 s) and 'K' (U+212A, 开尔文符号).如果使用 @ref{4d7,,ASCII} 标记，就只匹配 'a' 到 'z' 和 'A' 到 'Z' 。
@end deffn

@geindex L() (在 re 模块中)
@geindex LOCALE() (在 re 模块中)
@anchor{library/re re L}@anchor{18e7}
@deffn {数据} re.L
@anchor{library/re re LOCALE}@anchor{4d8}
@deffnx {数据} re.LOCALE

由当前语言区域决定 @code{\w}, @code{\W}, @code{\b}, @code{\B} 和大小写敏感匹配。这个标记只能对byte样式有效。这个标记不推荐使用，因为语言区域机制很不可靠，它一次只能处理一个 "习惯”，而且只对8位字节有效。Unicode匹配在Python 3 里默认启用，并可以处理不同语言。 这个对应内联标记 @code{(?L)} 。


在 3.6 版更改: @ref{4d8,,re.LOCALE} 只能用于byte样式，而且不能和 @ref{4d7,,re.ASCII} 一起用。



在 3.7 版更改: 设置了 @ref{4d8,,re.LOCALE} 标记的编译正则对象不再在编译时依赖语言区域设置。语言区域设置只在匹配的时候影响其结果。

@end deffn

@geindex M() (在 re 模块中)
@geindex MULTILINE() (在 re 模块中)
@anchor{library/re re M}@anchor{18e8}
@deffn {数据} re.M
@anchor{library/re re MULTILINE}@anchor{18e4}
@deffnx {数据} re.MULTILINE

设置以后，样式字符 @code{'^'} 匹配字符串的开始，和每一行的开始（换行符后面紧跟的符号）；样式字符 @code{'$'} 匹配字符串尾，和每一行的结尾（换行符前面那个符号）。默认情况下，@code{’^’} 匹配字符串头，@code{'$'} 匹配字符串尾。对应内联标记 @code{(?m)} 。
@end deffn

@geindex S() (在 re 模块中)
@geindex DOTALL() (在 re 模块中)
@anchor{library/re re S}@anchor{18e9}
@deffn {数据} re.S
@anchor{library/re re DOTALL}@anchor{18e3}
@deffnx {数据} re.DOTALL

让 @code{'.'} 特殊字符匹配任何字符，包括换行符；如果没有这个标记，@code{'.'} 就匹配 @emph{除了} 换行符的其他任意字符。对应内联标记 @code{(?s)} 。
@end deffn

@geindex X() (在 re 模块中)
@geindex VERBOSE() (在 re 模块中)
@anchor{library/re re X}@anchor{18ea}
@deffn {数据} re.X
@anchor{library/re re VERBOSE}@anchor{18f2}
@deffnx {数据} re.VERBOSE

@geindex # (hash); in regular expressions

这个标记允许你编写更具可读性更友好的正则表达式。通过分段和添加注释。空白符号会被忽略，除非在一个字符集合当中或者由反斜杠转义，或者在 @code{*?}, @code{(?:} or @code{(?P<…>} 分组之内。当一个行内有 @code{#} 不在字符集和转义序列，那么它之后的所有字符都是注释。

意思就是下面两个正则表达式等价地匹配一个十进制数字：

@example
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
@end example

对应内联标记 @code{(?x)} 。
@end deffn

@geindex search() (在 re 模块中)
@anchor{library/re re search}@anchor{c8a}
@deffn {函数} re.search (pattern, string, flags=0)

扫描整个 @emph{字符串} 找到匹配样式的第一个位置，并返回一个相应的 @ref{98d,,匹配对象}。如果没有匹配，就返回一个 @code{None} ； 注意这和找到一个零长度匹配是不同的。
@end deffn

@geindex match() (在 re 模块中)
@anchor{library/re re match}@anchor{c8b}
@deffn {函数} re.match (pattern, string, flags=0)

如果 @emph{string} 开始的0或者多个字符匹配到了正则表达式样式，就返回一个相应的 @ref{98d,,匹配对象} 。 如果没有匹配，就返回 @code{None} ；注意它跟零长度匹配是不同的。

注意即便是 @ref{18e4,,MULTILINE} 多行模式， @ref{c8b,,re.match()} 也只匹配字符串的开始位置，而不匹配每行开始。

如果你想定位 @emph{string} 的任何位置，使用 @ref{c8a,,search()} 来替代（也可参考 @ref{18f3,,search() vs. match()} ）
@end deffn

@geindex fullmatch() (在 re 模块中)
@anchor{library/re re fullmatch}@anchor{98b}
@deffn {函数} re.fullmatch (pattern, string, flags=0)

如果整个 @emph{string} 匹配到正则表达式样式，就返回一个相应的 @ref{98d,,匹配对象} 。 否则就返回一个 @code{None} ；注意这跟零长度匹配是不同的。


3.4 新版功能.

@end deffn

@geindex split() (在 re 模块中)
@anchor{library/re re split}@anchor{4d9}
@deffn {函数} re.split (pattern, string, maxsplit=0, flags=0)

用 @emph{pattern} 分开  @emph{string} 。 如果在 @emph{pattern} 中捕获到括号，那么所有的组里的文字也会包含在列表里。如果 @emph{maxsplit} 非零， 最多进行 @emph{maxsplit} 次分隔， 剩下的字符全部返回到列表的最后一个元素。

@example
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '@w{'}]
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '@w{'}]
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
@end example

如果分隔符里有捕获组合，并且匹配到字符串的开始，那么结果将会以一个空字符串开始。对于结尾也是一样

@example
>>> re.split(r'(\W+)', '...words, words...')
['@w{'}, '...', 'words', ', ', 'words', '...', '@w{'}]
@end example

这样的话，分隔组将会出现在结果列表中同样的位置。

样式的空匹配仅在与前一个空匹配不相邻时才会拆分字符串。

@example
>>> re.split(r'\b', 'Words, words, words.')
['@w{'}, 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['@w{'}, '@w{'}, 'w', 'o', 'r', 'd', 's', '@w{'}, '@w{'}]
>>> re.split(r'(\W*)', '...words...')
['@w{'}, '...', '@w{'}, '@w{'}, 'w', '@w{'}, 'o', '@w{'}, 'r', '@w{'}, 'd', '@w{'}, 's', '...', '@w{'}, '@w{'}, '@w{'}]
@end example


在 3.1 版更改: 增加了可选标记参数。



在 3.7 版更改: 增加了空字符串的样式分隔。

@end deffn

@geindex findall() (在 re 模块中)
@anchor{library/re re findall}@anchor{a4d}
@deffn {函数} re.findall (pattern, string, flags=0)

返回 @emph{pattern} 在 @emph{string} 中的所有非重叠匹配，以字符串列表或字符串元组列表的形式。对 @emph{string} 的扫描从左至右，匹配结果按照找到的顺序返回。 空匹配也包括在结果中。

返回结果取决于模式中捕获组的数量。如果没有组，返回与整个模式匹配的字符串列表。如果有且仅有一个组，返回与该组匹配的字符串列表。如果有多个组，返回与这些组匹配的字符串元组列表。非捕获组不影响结果。

@example
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10')
[('width', '20'), ('height', '10')]
@end example


在 3.7 版更改: 非空匹配现在可以在前一个空匹配之后出现了。

@end deffn

@geindex finditer() (在 re 模块中)
@anchor{library/re re finditer}@anchor{f87}
@deffn {函数} re.finditer (pattern, string, flags=0)

@emph{pattern} 在 @emph{string} 里所有的非重复匹配，返回为一个迭代器  @ref{11ba,,iterator} 保存了  @ref{98d,,匹配对象} 。 @emph{string} 从左到右扫描，匹配按顺序排列。空匹配也包含在结果里。


在 3.7 版更改: 非空匹配现在可以在前一个空匹配之后出现了。

@end deffn

@geindex sub() (在 re 模块中)
@anchor{library/re re sub}@anchor{582}
@deffn {函数} re.sub (pattern, repl, string, count=0, flags=0)

返回通过使用 @emph{repl} 替换在 @emph{string} 最左边非重叠出现的 @emph{pattern} 而获得的字符串。 如果样式没有找到，则不加改变地返回 @emph{string}。 @emph{repl} 可以是字符串或函数；如为字符串，则其中任何反斜杠转义序列都会被处理。 也就是说，@code{\n} 会被转换为一个换行符，@code{\r} 会被转换为一个回车符，依此类推。 未知的 ASCII 字符转义序列保留在未来使用，会被当作错误来处理。 其他未知转义序列例如 @code{\&} 会保持原样。 向后引用像是 @code{\6} 会用样式中第 6 组所匹配到的子字符串来替换。 例如:

@example
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n@{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n@{'
@end example

如果 @emph{repl} 是一个函数，那它会对每个非重复的 @emph{pattern} 的情况调用。这个函数只能有一个 @ref{98d,,匹配对象} 参数，并返回一个替换后的字符串。比如

@example
>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
>>> re.sub('-@{1,2@}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
@end example

样式可以是一个字符串或者一个 @ref{98c,,样式对象} 。

可选参数 @emph{count} 是要替换的最大次数；@emph{count} 必须是非负整数。如果省略这个参数或设为 0，所有的匹配都会被替换。 样式的空匹配仅在与前一个空匹配不相邻时才会被替换，所以  @code{sub('x*', '-', 'abxd')} 返回 @code{'-a-b--d-'} 。

@geindex \g; in regular expressions

在字符串类型的 @emph{repl} 参数里，如上所述的转义和向后引用中，@code{\g<name>} 会使用命名组合 @code{name}，（在  @code{(?P<name>…)} 语法中定义） @code{\g<number>} 会使用数字组；@code{\g<2>} 就是 @code{\2}，但它避免了二义性，如 @code{\g<2>0}。 @code{\20} 就会被解释为组20，而不是组2后面跟随一个字符 @code{'0'}。向后引用 @code{\g<0>} 把 @emph{pattern} 作为一整个组进行引用。


在 3.1 版更改: 增加了可选标记参数。



在 3.5 版更改: 不匹配的组合替换为空字符串。



在 3.6 版更改: @emph{pattern} 中的未知转义（由 @code{'\'} 和一个 ASCII 字符组成）被视为错误。



在 3.7 版更改: @emph{repl} 中的未知转义（由 @code{'\'} 和一个 ASCII 字符组成）被视为错误。



在 3.7 版更改: 样式中的空匹配相邻接时会被替换。

@end deffn

@geindex subn() (在 re 模块中)
@anchor{library/re re subn}@anchor{82d}
@deffn {函数} re.subn (pattern, repl, string, count=0, flags=0)

行为与 @ref{582,,sub()} 相同，但是返回一个元组 @code{(字符串, 替换次数)}.


在 3.1 版更改: 增加了可选标记参数。



在 3.5 版更改: 不匹配的组合替换为空字符串。

@end deffn

@geindex escape() (在 re 模块中)
@anchor{library/re re escape}@anchor{598}
@deffn {函数} re.escape (pattern)

转义 @emph{pattern} 中的特殊字符。如果你想对任意可能包含正则表达式元字符的文本字符串进行匹配，它就是有用的。比如

@example
>>> print(re.escape('https://www.python.org'))
https://www\.python\.org

>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
>>> print('[%s]+' % re.escape(legal_chars))
[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+

>>> operators = ['+', '-', '*', '/', '**']
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
/|\-|\+|\*\*|\*
@end example

这个函数不能被用于 @ref{582,,sub()} 和 @ref{82d,,subn()} 的替换字符串，只有反斜杠应该被转义。 例如:

@example
>>> digits_re = r'\d+'
>>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings'
>>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample))
/usr/sbin/sendmail - \d+ errors, \d+ warnings
@end example


在 3.3 版更改: @code{'_'} 不再被转义。



在 3.7 版更改: 只有在正则表达式中具有特殊含义的字符才会被转义。 因此， @code{'!'}, @code{'"'}, @code{'%'}, @code{"'"}, @code{','}, @code{'/'}, @code{':'}, @code{';'}, @code{'<'}, @code{'='}, @code{'>'}, @code{'@@'} 和 @code{"`"} 将不再会被转义。

@end deffn

@geindex purge() (在 re 模块中)
@anchor{library/re re purge}@anchor{18f4}
@deffn {函数} re.purge ()

清除正则表达式的缓存。
@end deffn

@geindex error
@anchor{library/re re error}@anchor{82e}
@deffn {例外} re.error (msg, pattern=None, pos=None)

当传递给函数的正则表达式不合法（比如括号不匹配），或者在编译或匹配过程中出现其他错误时，会引发异常。所给字符串不匹配所给模式不会引发异常。异常实例有以下附加属性：

@geindex msg (re.error 属性)
@anchor{library/re re error msg}@anchor{82f}
@deffn {属性} msg

未格式化的错误消息。
@end deffn

@geindex pattern (re.error 属性)
@anchor{library/re re error pattern}@anchor{830}
@deffn {属性} pattern

正则表达式的模式串。
@end deffn

@geindex pos (re.error 属性)
@anchor{library/re re error pos}@anchor{831}
@deffn {属性} pos

编译失败的 @emph{pattern} 的位置索引（可以是 @code{None} ）。
@end deffn

@geindex lineno (re.error 属性)
@anchor{library/re re error lineno}@anchor{832}
@deffn {属性} lineno

对应 @emph{pos} (可以是 @code{None}) 的行号。
@end deffn

@geindex colno (re.error 属性)
@anchor{library/re re error colno}@anchor{833}
@deffn {属性} colno

对应 @emph{pos} (可以是 @code{None}) 的列号。
@end deffn


在 3.5 版更改: 增加了额外的属性。

@end deffn

@node 正则表达式对象 （正则对象）,匹配对象,模块内容,re --- 正则表达式操作
@anchor{library/re re-objects}@anchor{98c}@anchor{library/re regular-expression-objects}@anchor{18f5}
@subsubsection 正则表达式对象 （正则对象）


编译后的正则表达式对象支持以下方法和属性：

@geindex search() (re.Pattern 方法)
@anchor{library/re re Pattern search}@anchor{18ef}
@deffn {方法} Pattern.search (string[, pos[, endpos]])

扫描整个 @emph{string} 寻找第一个匹配的位置， 并返回一个相应的 @ref{98d,,匹配对象}。如果没有匹配，就返回 @code{None} ；注意它和零长度匹配是不同的。

可选的第二个参数 @emph{pos} 给出了字符串中开始搜索的位置索引；默认为 @code{0}，它不完全等价于字符串切片； @code{'^'} 样式字符匹配字符串真正的开头，和换行符后面的第一个字符，但不会匹配索引规定开始的位置。

可选参数 @emph{endpos} 限定了字符串搜索的结束；它假定字符串长度到 @emph{endpos} ， 所以只有从 @code{pos} 到 @code{endpos - 1} 的字符会被匹配。如果 @emph{endpos} 小于 @emph{pos}，就不会有匹配产生；另外，如果 @emph{rx} 是一个编译后的正则对象， @code{rx.search(string, 0, 50)} 等价于 @code{rx.search(string[:50], 0)}。

@example
>>> pattern = re.compile("d")
>>> pattern.search("dog")     # Match at index 0
<re.Match object; span=(0, 1), match='d'>
>>> pattern.search("dog", 1)  # No match; search doesn't include the "d"
@end example
@end deffn

@geindex match() (re.Pattern 方法)
@anchor{library/re re Pattern match}@anchor{18ee}
@deffn {方法} Pattern.match (string[, pos[, endpos]])

如果 @emph{string} 的 @emph{开始位置} 能够找到这个正则样式的任意个匹配，就返回一个相应的 @ref{98d,,匹配对象}。如果不匹配，就返回 @code{None} ；注意它与零长度匹配是不同的。

可选参数 @emph{pos} 和 @emph{endpos} 与 @ref{18ef,,search()} 含义相同。

@example
>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>
@end example

如果你想定位匹配在 @emph{string} 中的位置，使用 @ref{18ef,,search()} 来替代（另参考  @ref{18f3,,search() vs. match()}）。
@end deffn

@geindex fullmatch() (re.Pattern 方法)
@anchor{library/re re Pattern fullmatch}@anchor{18f6}
@deffn {方法} Pattern.fullmatch (string[, pos[, endpos]])

如果整个 @emph{string} 匹配这个正则表达式，就返回一个相应的 @ref{98d,,匹配对象} 。 否则就返回 @code{None} ； 注意跟零长度匹配是不同的。

可选参数 @emph{pos} 和 @emph{endpos} 与 @ref{18ef,,search()} 含义相同。

@example
>>> pattern = re.compile("o[gh]")
>>> pattern.fullmatch("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.fullmatch("ogre")     # No match as not the full string matches.
>>> pattern.fullmatch("doggie", 1, 3)   # Matches within given limits.
<re.Match object; span=(1, 3), match='og'>
@end example


3.4 新版功能.

@end deffn

@geindex split() (re.Pattern 方法)
@anchor{library/re re Pattern split}@anchor{18f7}
@deffn {方法} Pattern.split (string, maxsplit=0)

等价于 @ref{4d9,,split()} 函数，使用了编译后的样式。
@end deffn

@geindex findall() (re.Pattern 方法)
@anchor{library/re re Pattern findall}@anchor{18f8}
@deffn {方法} Pattern.findall (string[, pos[, endpos]])

类似函数 @ref{a4d,,findall()} ， 使用了编译后样式，但也可以接收可选参数 @emph{pos} 和 @emph{endpos} ，限制搜索范围，就像 @ref{c8a,,search()}。
@end deffn

@geindex finditer() (re.Pattern 方法)
@anchor{library/re re Pattern finditer}@anchor{18f9}
@deffn {方法} Pattern.finditer (string[, pos[, endpos]])

类似函数 @ref{f87,,finditer()} ， 使用了编译后样式，但也可以接收可选参数 @emph{pos} 和 @emph{endpos} ，限制搜索范围，就像 @ref{c8a,,search()}。
@end deffn

@geindex sub() (re.Pattern 方法)
@anchor{library/re re Pattern sub}@anchor{18fa}
@deffn {方法} Pattern.sub (repl, string, count=0)

等价于 @ref{582,,sub()} 函数，使用了编译后的样式。
@end deffn

@geindex subn() (re.Pattern 方法)
@anchor{library/re re Pattern subn}@anchor{18fb}
@deffn {方法} Pattern.subn (repl, string, count=0)

等价于 @ref{82d,,subn()} 函数，使用了编译后的样式。
@end deffn

@geindex flags (re.Pattern 属性)
@anchor{library/re re Pattern flags}@anchor{18fc}
@deffn {属性} Pattern.flags

正则匹配标记。这是可以传递给 @ref{555,,compile()} 的参数，任何 @code{(?…)} 内联标记，隐性标记比如 @code{UNICODE} 的结合。
@end deffn

@geindex groups (re.Pattern 属性)
@anchor{library/re re Pattern groups}@anchor{18fd}
@deffn {属性} Pattern.groups

捕获到的模式串中组的数量。
@end deffn

@geindex groupindex (re.Pattern 属性)
@anchor{library/re re Pattern groupindex}@anchor{18fe}
@deffn {属性} Pattern.groupindex

映射由 @code{(?P<id>)} 定义的命名符号组合和数字组合的字典。如果没有符号组，那字典就是空的。
@end deffn

@geindex pattern (re.Pattern 属性)
@anchor{library/re re Pattern pattern}@anchor{18ff}
@deffn {属性} Pattern.pattern

编译对象的原始样式字符串。
@end deffn


在 3.7 版更改: 添加 @ref{4da,,copy.copy()} 和 @ref{4db,,copy.deepcopy()} 函数的支持。编译后的正则表达式对象被认为是原子性的。


@node 匹配对象,正则表达式例子,正则表达式对象 （正则对象）,re --- 正则表达式操作
@anchor{library/re id2}@anchor{1900}@anchor{library/re match-objects}@anchor{98d}
@subsubsection 匹配对象


匹配对象总是有一个布尔值 @code{True}。如果没有匹配的话 @ref{18ee,,match()} 和 @ref{18ef,,search()} 返回 @code{None} 所以你可以简单的用 @code{if} 语句来判断是否匹配

@example
match = re.search(pattern, string)
if match:
    process(match)
@end example

匹配对象支持以下方法和属性：

@geindex expand() (re.Match 方法)
@anchor{library/re re Match expand}@anchor{1901}
@deffn {方法} Match.expand (template)

对 @emph{template} 进行反斜杠转义替换并且返回，就像 @ref{18fa,,sub()} 方法中一样。转义如同 @code{\n} 被转换成合适的字符，数字引用(@code{\1}, @code{\2})和命名组合(@code{\g<1>}, @code{\g<name>}) 替换为相应组合的内容。


在 3.5 版更改: 不匹配的组合替换为空字符串。

@end deffn

@geindex group() (re.Match 方法)
@anchor{library/re re Match group}@anchor{1902}
@deffn {方法} Match.group ([group1, ...])

返回一个或者多个匹配的子组。如果只有一个参数，结果就是一个字符串，如果有多个参数，结果就是一个元组（每个参数对应一个项），如果没有参数，组1默认到0（整个匹配都被返回）。 如果一个组N 参数值为 0，相应的返回值就是整个匹配字符串；如果它是一个范围 [1..99]，结果就是相应的括号组字符串。如果一个组号是负数，或者大于样式中定义的组数，就引发一个 @ref{f3d,,IndexError} 异常。如果一个组包含在样式的一部分，并被匹配多次，就返回最后一个匹配。:

@example
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')
@end example

如果正则表达式使用了 @code{(?P<name>...)} 语法， @emph{groupN} 参数就也可能是命名组合的名字。如果一个字符串参数在样式中未定义为组合名，就引发一个 @ref{f3d,,IndexError} 异常。

一个相对复杂的例子

@example
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'
@end example

命名组合同样可以通过索引值引用

@example
>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'
@end example

如果一个组匹配成功多次，就只返回最后一个匹配

@example
>>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
>>> m.group(1)                        # Returns only the last match.
'c3'
@end example
@end deffn

@geindex __getitem__() (re.Match 方法)
@anchor{library/re re Match __getitem__}@anchor{1903}
@deffn {方法} Match.__getitem__ (g)

这个等价于 @code{m.group(g)}。这允许更方便的引用一个匹配

@example
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m[0]       # The entire match
'Isaac Newton'
>>> m[1]       # The first parenthesized subgroup.
'Isaac'
>>> m[2]       # The second parenthesized subgroup.
'Newton'
@end example


3.6 新版功能.

@end deffn

@geindex groups() (re.Match 方法)
@anchor{library/re re Match groups}@anchor{1904}
@deffn {方法} Match.groups (default=None)

返回一个元组，包含所有匹配的子组，在样式中出现的从1到任意多的组合。 @emph{default} 参数用于不参与匹配的情况，默认为 @code{None}。

例如

@example
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')
@end example

如果我们使小数点可选，那么不是所有的组都会参与到匹配当中。这些组合默认会返回一个 @code{None} ，除非指定了 @emph{default} 参数。

@example
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # Second group defaults to None.
('24', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('24', '0')
@end example
@end deffn

@geindex groupdict() (re.Match 方法)
@anchor{library/re re Match groupdict}@anchor{1905}
@deffn {方法} Match.groupdict (default=None)

返回一个字典，包含了所有的 @emph{命名} 子组。key就是组名。 @emph{default} 参数用于不参与匹配的组合；默认为 @code{None}。 例如

@example
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict()
@{'first_name': 'Malcolm', 'last_name': 'Reynolds'@}
@end example
@end deffn

@geindex start() (re.Match 方法)
@geindex end() (re.Match 方法)
@anchor{library/re re Match start}@anchor{1906}
@deffn {方法} Match.start ([group])
@anchor{library/re re Match end}@anchor{1907}
@deffnx {方法} Match.end ([group])

返回 @emph{group} 匹配到的字串的开始和结束标号。@emph{group} 默认为0（意思是整个匹配的子串）。如果  @emph{group} 存在，但未产生匹配，就返回 @code{-1} 。对于一个匹配对象 @emph{m}， 和一个未参与匹配的组 @emph{g} ，组 @emph{g} (等价于 @code{m.group(g)})产生的匹配是

@example
m.string[m.start(g):m.end(g)]
@end example

注意 @code{m.start(group)} 将会等于 @code{m.end(group)} ，如果 @emph{group} 匹配一个空字符串的话。比如，在 @code{m = re.search('b(c?)', 'cba')} 之后，@code{m.start(0)} 为 1, @code{m.end(0)} 为 2, @code{m.start(1)} 和 @code{m.end(1)} 都是 2, @code{m.start(2)} 引发一个 @ref{f3d,,IndexError} 异常。

这个例子会从email地址中移除掉 @emph{remove_this}

@example
>>> email = "tony@@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@@tiger.net'
@end example
@end deffn

@geindex span() (re.Match 方法)
@anchor{library/re re Match span}@anchor{1908}
@deffn {方法} Match.span ([group])

对于一个匹配 @emph{m} ， 返回一个二元组 @code{(m.start(group), m.end(group))} 。 注意如果 @emph{group} 没有在这个匹配中，就返回 @code{(-1, -1)} 。@emph{group} 默认为0，就是整个匹配。
@end deffn

@geindex pos (re.Match 属性)
@anchor{library/re re Match pos}@anchor{1909}
@deffn {属性} Match.pos

@emph{pos} 的值，会传递给 @ref{18ef,,search()} 或 @ref{18ee,,match()} 的方法 a @ref{98c,,正则对象} 。这个是正则引擎开始在字符串搜索一个匹配的索引位置。
@end deffn

@geindex endpos (re.Match 属性)
@anchor{library/re re Match endpos}@anchor{190a}
@deffn {属性} Match.endpos

@emph{endpos} 的值，会传递给 @ref{18ef,,search()} 或 @ref{18ee,,match()} 的方法 a @ref{98c,,正则对象} 。这个是正则引擎停止在字符串搜索一个匹配的索引位置。
@end deffn

@geindex lastindex (re.Match 属性)
@anchor{library/re re Match lastindex}@anchor{190b}
@deffn {属性} Match.lastindex

捕获组的最后一个匹配的整数索引值，或者 @code{None} 如果没有匹配产生的话。比如，对于字符串 @code{'ab'}，表达式 @code{(a)b}, @code{((a)(b))}, 和 @code{((ab))} 将得到 @code{lastindex == 1} ， 而 @code{(a)(b)} 会得到 @code{lastindex == 2} 。
@end deffn

@geindex lastgroup (re.Match 属性)
@anchor{library/re re Match lastgroup}@anchor{190c}
@deffn {属性} Match.lastgroup

最后一个匹配的命名组名字，或者 @code{None} 如果没有产生匹配的话。
@end deffn

@geindex re (re.Match 属性)
@anchor{library/re re Match re}@anchor{190d}
@deffn {属性} Match.re

返回产生这个实例的 @ref{98c,,正则对象} ， 这个实例是由 正则对象的 @ref{18ee,,match()} 或 @ref{18ef,,search()} 方法产生的。
@end deffn

@geindex string (re.Match 属性)
@anchor{library/re re Match string}@anchor{190e}
@deffn {属性} Match.string

传递到 @ref{18ee,,match()} 或 @ref{18ef,,search()} 的字符串。
@end deffn


在 3.7 版更改: 添加了对 @ref{4da,,copy.copy()} 和 @ref{4db,,copy.deepcopy()} 的支持。匹配对象被看作是原子性的。


@node 正则表达式例子,,匹配对象,re --- 正则表达式操作
@anchor{library/re re-examples}@anchor{cc7}@anchor{library/re regular-expression-examples}@anchor{190f}
@subsubsection 正则表达式例子


@menu
* 检查对子:: 
* 模拟 scanf(): 模拟 scanf. 
* search() vs. match(): search vs match. 
* 制作一个电话本:: 
* 文字整理:: 
* 查找所有副词:: 
* 查找所有的副词及其位置:: 
* 原始字符串标记:: 
* 写一个词法分析器:: 

@end menu

@node 检查对子,模拟 scanf,,正则表达式例子
@anchor{library/re checking-for-a-pair}@anchor{1910}
@subsubsection 检查对子


在这个例子里，我们使用以下辅助函数来更好地显示匹配对象:

@example
def displaymatch(match):
    if match is None:
        return None
    return '<Match: %r, groups=%r>' % (match.group(), match.groups())
@end example

假设你在写一个扑克程序，一个玩家的一手牌为五个字符的串，每个字符表示一张牌，"a" 就是 A, "k"  K， "q"  Q, "j" J, "t" 为 10, "2" 到 "9" 表示2 到 9。

要看给定的字符串是否有效，我们可以按照以下步骤

@example
>>> valid = re.compile(r"^[a2-9tjqk]@{5@}$")
>>> displaymatch(valid.match("akt5q"))  # Valid.
"<Match: 'akt5q', groups=()>"
>>> displaymatch(valid.match("akt5e"))  # Invalid.
>>> displaymatch(valid.match("akt"))    # Invalid.
>>> displaymatch(valid.match("727ak"))  # Valid.
"<Match: '727ak', groups=()>"
@end example

最后一手牌，@code{"727ak"} ，包含了一个对子，或者两张同样数值的牌。要用正则表达式匹配它，应该使用向后引用如下

@example
>>> pair = re.compile(r".*(.).*\1")
>>> displaymatch(pair.match("717ak"))     # Pair of 7s.
"<Match: '717', groups=('7',)>"
>>> displaymatch(pair.match("718ak"))     # No pairs.
>>> displaymatch(pair.match("354aa"))     # Pair of aces.
"<Match: '354aa', groups=('a',)>"
@end example

要找出对子由什么牌组成，开发者可以按照下面的方式来使用匹配对象的 @ref{1902,,group()} 方法:

@example
>>> pair = re.compile(r".*(.).*\1")
>>> pair.match("717ak").group(1)
'7'

# Error because re.match() returns None, which doesn't have a group() method:
>>> pair.match("718ak").group(1)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    re.match(r".*(.).*\1", "718ak").group(1)
AttributeError: 'NoneType' object has no attribute 'group'

>>> pair.match("354aa").group(1)
'a'
@end example

@node 模拟 scanf,search vs match,检查对子,正则表达式例子
@anchor{library/re simulating-scanf}@anchor{1911}
@subsubsection 模拟 scanf()


@geindex scanf()

Python 目前没有一个类似c函数 @code{scanf()} 的替代品。正则表达式通常比 @code{scanf()} 格式字符串要更强大一些，但也带来更多复杂性。下面的表格提供了 @code{scanf()} 格式符和正则表达式大致相同的映射。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@code{scanf()} 格式符

@tab

正则表达式

@item

@code{%c}

@tab

@code{.}

@item

@code{%5c}

@tab

@code{.@{5@}}

@item

@code{%d}

@tab

@code{[-+]?\d+}

@item

@code{%e}, @code{%E}, @code{%f}, @code{%g}

@tab

@code{[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?}

@item

@code{%i}

@tab

@code{[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)}

@item

@code{%o}

@tab

@code{[-+]?[0-7]+}

@item

@code{%s}

@tab

@code{\S+}

@item

@code{%u}

@tab

@code{\d+}

@item

@code{%x}, @code{%X}

@tab

@code{[-+]?(0[xX])?[\dA-Fa-f]+}

@end multitable


从文件名和数字提取字符串

@example
/usr/sbin/sendmail - 0 errors, 4 warnings
@end example

你可以使用 @code{scanf()} 格式化

@example
%s - %d errors, %d warnings
@end example

等价的正则表达式是：

@example
(\S+) - (\d+) errors, (\d+) warnings
@end example

@node search vs match,制作一个电话本,模拟 scanf,正则表达式例子
@anchor{library/re id3}@anchor{1912}@anchor{library/re search-vs-match}@anchor{18f3}
@subsubsection search() vs. match()


Python 提供了两种不同的操作：基于 @ref{c8b,,re.match()} 检查字符串开头，或者 @ref{c8a,,re.search()} 检查字符串的任意位置（默认Perl中的行为）。

例如

@example
>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match
<re.Match object; span=(2, 3), match='c'>
@end example

在 @ref{c8a,,search()} 中，可以用 @code{'^'} 作为开始来限制匹配到字符串的首位

@example
>>> re.match("c", "abcdef")    # No match
>>> re.search("^c", "abcdef")  # No match
>>> re.search("^a", "abcdef")  # Match
<re.Match object; span=(0, 1), match='a'>
@end example

注意 @ref{18e4,,MULTILINE} 多行模式中函数 @ref{c8b,,match()} 只匹配字符串的开始，但使用 @ref{c8a,,search()} 和以 @code{'^'} 开始的正则表达式会匹配每行的开始

@example
>>> re.match('X', 'A\nB\nX', re.MULTILINE)  # No match
>>> re.search('^X', 'A\nB\nX', re.MULTILINE)  # Match
<re.Match object; span=(4, 5), match='X'>
@end example

@node 制作一个电话本,文字整理,search vs match,正则表达式例子
@anchor{library/re making-a-phonebook}@anchor{1913}
@subsubsection 制作一个电话本


@ref{4d9,,split()} 将字符串用参数传递的样式分隔开。这个方法对于转换文本数据到易读而且容易修改的数据结构，是很有用的，如下面的例子证明。

首先，这里是输入。 它通常来自一个文件，这里我们使用三重引号字符串语法

@example
>>> text = """Ross McFluff: 834.345.1254 155 Elm Street
...
... Ronald Heathmore: 892.345.3428 436 Finley Avenue
... Frank Burger: 925.541.7625 662 South Dogwood Way
...
...
... Heather Albrecht: 548.326.4584 919 Park Place"""
@end example

条目用一个或者多个换行符分开。现在我们将字符串转换为一个列表，每个非空行都有一个条目:

@example
>>> entries = re.split("\n+", text)
>>> entries
['Ross McFluff: 834.345.1254 155 Elm Street',
'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
'Frank Burger: 925.541.7625 662 South Dogwood Way',
'Heather Albrecht: 548.326.4584 919 Park Place']
@end example

最终，将每个条目分割为一个由名字、姓氏、电话号码和地址组成的列表。我们为 @ref{4d9,,split()} 使用了 @code{maxsplit} 形参，因为地址中包含有被我们作为分割模式的空格符:

@example
>>> [re.split(":? ", entry, 3) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
@end example

@code{:?} 样式匹配姓后面的冒号，因此它不出现在结果列表中。如果 @code{maxsplit} 设置为 @code{4} ，我们还可以从地址中获取到房间号:

@example
>>> [re.split(":? ", entry, 4) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
@end example

@node 文字整理,查找所有副词,制作一个电话本,正则表达式例子
@anchor{library/re text-munging}@anchor{1914}
@subsubsection 文字整理


@ref{582,,sub()} 替换字符串中出现的样式的每一个实例。这个例子证明了使用  @ref{582,,sub()} 来整理文字，或者随机化每个字符的位置，除了首位和末尾字符

@example
>>> def repl(m):
...     inner_word = list(m.group(2))
...     random.shuffle(inner_word)
...     return m.group(1) + "".join(inner_word) + m.group(3)
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
@end example

@node 查找所有副词,查找所有的副词及其位置,文字整理,正则表达式例子
@anchor{library/re finding-all-adverbs}@anchor{1915}
@subsubsection 查找所有副词


@ref{a4d,,findall()} 匹配样式 @emph{所有} 的出现，不仅是像 @ref{c8a,,search()} 中的第一个匹配。比如，如果一个作者希望找到文字中的所有副词，他可能会按照以下方法用 @ref{a4d,,findall()}

@example
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly\b", text)
['carefully', 'quickly']
@end example

@node 查找所有的副词及其位置,原始字符串标记,查找所有副词,正则表达式例子
@anchor{library/re finding-all-adverbs-and-their-positions}@anchor{1916}
@subsubsection 查找所有的副词及其位置


如果需要匹配样式的更多信息， @ref{f87,,finditer()} 可以起到作用，它提供了 @ref{98d,,匹配对象} 作为返回值，而不是字符串。继续上面的例子，如果一个作者希望找到所有副词和它的位置，可以按照下面方法使用 @ref{f87,,finditer()}

@example
>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly\b", text):
...     print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
07-16: carefully
40-47: quickly
@end example

@node 原始字符串标记,写一个词法分析器,查找所有的副词及其位置,正则表达式例子
@anchor{library/re raw-string-notation}@anchor{1917}
@subsubsection 原始字符串标记


原始字符串记法 (@code{r"text"}) 保持正则表达式正常。否则，每个正则式里的反斜杠(@code{'\'}) 都必须前缀一个反斜杠来转义。比如，下面两行代码功能就是完全一致的

@example
>>> re.match(r"\W(.)\1\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
>>> re.match("\\W(.)\\1\\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
@end example

当需要匹配一个字符反斜杠，它必须在正则表达式中转义。在原始字符串记法，就是 @code{r"\\"}。否则就必须用 @code{"\\\\"}，来表示同样的意思

@example
>>> re.match(r"\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
>>> re.match("\\\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
@end example

@node 写一个词法分析器,,原始字符串标记,正则表达式例子
@anchor{library/re writing-a-tokenizer}@anchor{1918}
@subsubsection 写一个词法分析器


一个 词法器或词法分析器@footnote{https://en.wikipedia.org/wiki/Lexical_analysis} 分析字符串，并分类成目录组。 这是写一个编译器或解释器的第一步。

文字目录是由正则表达式指定的。这个技术是通过将这些样式合并为一个主正则式，并且循环匹配来实现的

@example
from typing import NamedTuple
import re

class Token(NamedTuple):
    type: str
    value: str
    line: int
    column: int

def tokenize(code):
    keywords = @{'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'@}
    token_specification = [
        ('NUMBER',   r'\d+(\.\d*)?'),  # Integer or decimal number
        ('ASSIGN',   r':='),           # Assignment operator
        ('END',      r';'),            # Statement terminator
        ('ID',       r'[A-Za-z]+'),    # Identifiers
        ('OP',       r'[+\-*/]'),      # Arithmetic operators
        ('NEWLINE',  r'\n'),           # Line endings
        ('SKIP',     r'[ \t]+'),       # Skip over spaces and tabs
        ('MISMATCH', r'.'),            # Any other character
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
    line_num = 1
    line_start = 0
    for mo in re.finditer(tok_regex, code):
        kind = mo.lastgroup
        value = mo.group()
        column = mo.start() - line_start
        if kind == 'NUMBER':
            value = float(value) if '.' in value else int(value)
        elif kind == 'ID' and value in keywords:
            kind = value
        elif kind == 'NEWLINE':
            line_start = mo.end()
            line_num += 1
            continue
        elif kind == 'SKIP':
            continue
        elif kind == 'MISMATCH':
            raise RuntimeError(f'@{value!r@} unexpected on line @{line_num@}')
        yield Token(kind, value, line_num, column)

statements = '@w{'}'
    IF quantity THEN
        total := total + price * quantity;
        tax := price * 0.05;
    ENDIF;
'@w{'}'

for token in tokenize(statements):
    print(token)
@end example

该词法器产生以下的输出

@example
Token(type='IF', value='IF', line=2, column=4)
Token(type='ID', value='quantity', line=2, column=7)
Token(type='THEN', value='THEN', line=2, column=16)
Token(type='ID', value='total', line=3, column=8)
Token(type='ASSIGN', value=':=', line=3, column=14)
Token(type='ID', value='total', line=3, column=17)
Token(type='OP', value='+', line=3, column=23)
Token(type='ID', value='price', line=3, column=25)
Token(type='OP', value='*', line=3, column=31)
Token(type='ID', value='quantity', line=3, column=33)
Token(type='END', value=';', line=3, column=41)
Token(type='ID', value='tax', line=4, column=8)
Token(type='ASSIGN', value=':=', line=4, column=12)
Token(type='ID', value='price', line=4, column=15)
Token(type='OP', value='*', line=4, column=21)
Token(type='NUMBER', value=0.05, line=4, column=23)
Token(type='END', value=';', line=4, column=27)
Token(type='ENDIF', value='ENDIF', line=5, column=4)
Token(type='END', value=';', line=5, column=9)
@end example

@anchor{library/re frie09}@anchor{18e1}@w{(Frie09)} 
Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O'Reilly Media, 2009. 该书的第三版不再包含 Python，但第一版极详细地覆盖了正则表达式模式串的编写。

@node difflib --- 计算差异的辅助工具,textwrap --- 文本自动换行与填充,re --- 正则表达式操作,文本处理服务
@anchor{library/difflib doc}@anchor{1919}@anchor{library/difflib difflib-helpers-for-computing-deltas}@anchor{191a}@anchor{library/difflib module-difflib}@anchor{36}
@subsection @code{difflib} --- 计算差异的辅助工具


@geindex difflib (模块)

@c Markup by Fred L. Drake, Jr. <fdrake@acm.org>

@strong{源代码:} Lib/difflib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/difflib.py}

@c import sys
@c from difflib import *


__________________________________________________________________


此模块提供用于比较序列的类和函数。 例如，它可被用于比较文件，并可产生多种格式的不同文件差异信息，包括 HTML 和上下文以及统一的 diff 数据。 有关比较目录和文件，另请参阅 @ref{7d,,filecmp} 模块。


@deffn {类} difflib.SequenceMatcher

这是一个灵活的类，可用于比较任何类型的序列对，只要序列元素为 @ref{277,,hashable} 对象。 其基本算法要早于由 Ratcliff 和 Obershelp 于 1980 年代末期发表并以“格式塔模式匹配”的夸张名称命名的算法，并且更加有趣一些。 其思路是找到不包含“垃圾”元素的最长连续匹配子序列；所谓“垃圾”元素是指其在某种意义上没有价值，例如空白行或空白符。 （处理垃圾元素是对 Ratcliff 和 Obershelp 算法的一个扩展。） 然后同样的思路将递归地应用于匹配序列的左右序列片段。 这并不能产生最小编辑序列，但确实能产生在人们看来“正确”的匹配。

@strong{耗时:} 基本 Ratcliff-Obershelp 算法在最坏情况下为立方时间而在一般情况下为平方时间。 @ref{a39,,SequenceMatcher} 在最坏情况下为平方时间而在一般情况下的行为受到序列中有多少相同元素这一因素的微妙影响；在最佳情况下则为线性时间。

@strong{自动垃圾启发式计算:} @ref{a39,,SequenceMatcher} 支持使用启发式计算来自动将特定序列项视为垃圾。 这种启发式计算会统计每个单独项在序列中出现的次数。 如果某一项（在第一项之后）的重复次数超过序列长度的 1% 并且序列长度至少有 200 项，该项会被标记为“热门”并被视为序列匹配中的垃圾。 这种启发式计算可以通过在创建 @ref{a39,,SequenceMatcher} 时将 @code{autojunk} 参数设为 @code{False} 来关闭。


3.2 新版功能: @emph{autojunk} 形参。

@end deffn

@geindex Differ (difflib 中的类)
@anchor{library/difflib difflib Differ}@anchor{191b}
@deffn {类} difflib.Differ

这个类的作用是比较由文本行组成的序列，并产生可供人阅读的差异或增量信息。 Differ 统一使用 @ref{a39,,SequenceMatcher} 来完成行序列的比较以及相似（接近匹配）行内部字符序列的比较。

@ref{191b,,Differ} 增量的每一行均以双字母代码打头：


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

双字母代码

@tab

意义

@item

@code{'- '}

@tab

行为序列 1 所独有

@item

@code{'+ '}

@tab

行为序列 2 所独有

@item

@code{'  '}

@tab

行在两序列中相同

@item

@code{'? '}

@tab

行不存在于任一输入序列

@end multitable


以 '@code{?}' 打头的行尝试将视线引至行以外而不存在于任一输入序列的差异。 如果序列包含制表符则这些行可能会令人感到迷惑。
@end deffn

@geindex HtmlDiff (difflib 中的类)
@anchor{library/difflib difflib HtmlDiff}@anchor{191c}
@deffn {类} difflib.HtmlDiff

这个类可用于创建 HTML 表格（或包含表格的完整 HTML 文件）以并排地逐行显示文本比较，行间与行外的更改将突出显示。 此表格可以基于完全或上下文差异模式来生成。

这个类的构造函数：

@geindex __init__() (difflib.HtmlDiff 方法)
@anchor{library/difflib difflib HtmlDiff __init__}@anchor{191d}
@deffn {方法} __init__ (tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)

初始化 @ref{191c,,HtmlDiff} 的实例。

@emph{tabsize} 是一个可选关键字参数，指定制表位的间隔，默认值为 @code{8}。

@emph{wrapcolumn} 是一个可选关键字参数，指定行文本自动打断并换行的列位置，默认值为 @code{None} 表示不自动换行。

@emph{linejunk} 和 @emph{charjunk} 均是可选关键字参数，会传入 @ref{191e,,ndiff()} (被 @ref{191c,,HtmlDiff} 用来生成并排显示的 HTML 差异)。 请参阅 @ref{191e,,ndiff()} 文档了解参数默认值及其说明。
@end deffn

下列是公开的方法

@geindex make_file() (difflib.HtmlDiff 方法)
@anchor{library/difflib difflib HtmlDiff make_file}@anchor{7c6}
@deffn {方法} make_file (fromlines, tolines, fromdesc='@w{'}, todesc='@w{'}, context=False, numlines=5, *, charset='utf-8')

比较 @emph{fromlines} 和 @emph{tolines} (字符串列表) 并返回一个字符串，表示一个完整 HTML 文件，其中包含各行差异的表格，行间与行外的更改将突出显示。

@emph{fromdesc} 和 @emph{todesc} 均是可选关键字参数，指定来源/目标文件的列标题字符串（默认均为空白字符串）。

@emph{context} 和 @emph{numlines} 均是可选关键字参数。 当只要显示上下文差异时就将 @emph{context} 设为 @code{True}，否则默认值 @code{False} 为显示完整文件。 @emph{numlines} 默认为 @code{5}。 当 @emph{context} 为 @code{True} 时 @emph{numlines} 将控制围绕突出显示差异部分的上下文行数。 当 @emph{context} 为 @code{False} 时 @emph{numlines} 将控制在使用 "next" 超链接时突出显示差异部分之前所显示的行数（设为零则会导致 "next" 超链接将下一个突出显示差异部分放在浏览器顶端，不添加任何前导上下文）。

@cartouche
@quotation 注解 
@emph{fromdesc} 和 @emph{todesc} 会被当作未转义的 HTML 来解读，当接收不可信来源的输入时应该适当地进行转义。
@end quotation
@end cartouche


在 3.5 版更改: 增加了 @emph{charset} 关键字参数。 HTML 文档的默认字符集从 @code{'ISO-8859-1'} 更改为 @code{'utf-8'}。

@end deffn

@geindex make_table() (difflib.HtmlDiff 方法)
@anchor{library/difflib difflib HtmlDiff make_table}@anchor{191f}
@deffn {方法} make_table (fromlines, tolines, fromdesc='@w{'}, todesc='@w{'}, context=False, numlines=5)

比较 @emph{fromlines} 和 @emph{tolines} (字符串列表) 并返回一个字符串，表示一个包含各行差异的完整 HTML 表格，行间与行外的更改将突出显示。

此方法的参数与 @ref{7c6,,make_file()} 方法的相同。
@end deffn

@code{Tools/scripts/diff.py} 是这个类的命令行前端，其中包含一个很好的使用示例。
@end deffn

@geindex context_diff() (在 difflib 模块中)
@anchor{library/difflib difflib context_diff}@anchor{1920}
@deffn {函数} difflib.context_diff (a, b, fromfile='@w{'}, tofile='@w{'}, fromfiledate='@w{'}, tofiledate='@w{'}, n=3, lineterm='\n')

比较 @emph{a} 和 @emph{b} (字符串列表)；返回上下文差异格式的增量信息 (一个产生增量行的 @ref{a8c,,generator})。

所谓上下文差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改被显示为之前/之后的样式。 上下文行数由 @emph{n} 设定，默认为三行。

默认情况下，差异控制行（以 @code{***} or @code{---} 表示）是通过末尾换行符来创建的。 这样做的好处是从 @ref{1921,,io.IOBase.readlines()} 创建的输入将得到适用于 @ref{1922,,io.IOBase.writelines()} 的差异信息，因为输入和输出都带有末尾换行符。

对于没有末尾换行符的输入，应将 @emph{lineterm} 参数设为 @code{""}，这样输出内容将统一不带换行符。

上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部分或全部可以使用字符串 @emph{fromfile}, @emph{tofile}, @emph{fromfiledate} 和 @emph{tofiledate} 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定，这些字符串默认为空。

@example
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py'))
*** before.py
--- after.py
***************
*** 1,4 ****
! bacon
! eggs
! ham
  guido
--- 1,4 ----
! python
! eggy
! hamster
  guido
@end example

请参阅 @ref{1923,,difflib 的命令行接口} 获取更详细的示例。
@end deffn

@geindex get_close_matches() (在 difflib 模块中)
@anchor{library/difflib difflib get_close_matches}@anchor{1924}
@deffn {函数} difflib.get_close_matches (word, possibilities, n=3, cutoff=0.6)

返回由最佳“近似”匹配构成的列表。 @emph{word} 为一个指定目标近似匹配的序列（通常为字符串），@emph{possibilities} 为一个由用于匹配 @emph{word} 的序列构成的列表（通常为字符串列表）。

可选参数 @emph{n} (默认为 @code{3}) 指定最多返回多少个近似匹配； @emph{n} 必须大于 @code{0}.

可选参数 @emph{cutoff} (默认为 @code{0.6}) 是一个 [0, 1] 范围内的浮点数。 与 @emph{word} 相似度得分未达到该值的候选匹配将被忽略。

候选匹配中（不超过 @emph{n} 个）的最佳匹配将以列表形式返回，按相似度得分排序，最相似的排在最前面。

@example
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('pineapple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']
@end example
@end deffn

@geindex ndiff() (在 difflib 模块中)
@anchor{library/difflib difflib ndiff}@anchor{191e}
@deffn {函数} difflib.ndiff (a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)

比较 @emph{a} 和 @emph{b} (字符串列表)；返回 @ref{191b,,Differ} 形式的增量信息 (一个产生增量行的 @ref{a8c,,generator})。

可选关键字形参 @emph{linejunk} 和 @emph{charjunk} 均为过滤函数 (或为 @code{None})：

@emph{linejunk}: 此函数接受单个字符串参数，如果其为垃圾字符串则返回真值，否则返回假值。 默认为 @code{None}。 此外还有一个模块层级的函数 @ref{1925,,IS_LINE_JUNK()}，它会过滤掉没有可见字符的行，除非该行添加了至多一个井号符 (@code{'#'}) -- 但是下层的 @ref{a39,,SequenceMatcher} 类会动态分析哪些行的重复频繁到足以形成噪音，这通常会比使用此函数的效果更好。

@emph{charjunk}: 此函数接受一个字符（长度为 1 的字符串)，如果其为垃圾字符则返回真值，否则返回假值。 默认为模块层级的函数 @ref{1926,,IS_CHARACTER_JUNK()}，它会过滤掉空白字符（空格符或制表符；但包含换行符可不是个好主意！）。

@code{Tools/scripts/ndiff.py} 是这个函数的命令行前端。

@example
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> print('@w{'}.join(diff), end="")
- one
?  ^
+ ore
?  ^
- two
- three
?  -
+ tree
+ emu
@end example
@end deffn

@geindex restore() (在 difflib 模块中)
@anchor{library/difflib difflib restore}@anchor{1927}
@deffn {函数} difflib.restore (sequence, which)

返回两个序列中产生增量的那一个。

给出一个由 @ref{1928,,Differ.compare()} 或 @ref{191e,,ndiff()} 产生的 @emph{序列}，提取出来自文件 1 或 2 (@emph{which} 形参) 的行，去除行前缀。

示例:

@example
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> diff = list(diff) # materialize the generated delta into a list
>>> print('@w{'}.join(restore(diff, 1)), end="")
one
two
three
>>> print('@w{'}.join(restore(diff, 2)), end="")
ore
tree
emu
@end example
@end deffn

@geindex unified_diff() (在 difflib 模块中)
@anchor{library/difflib difflib unified_diff}@anchor{1929}
@deffn {函数} difflib.unified_diff (a, b, fromfile='@w{'}, tofile='@w{'}, fromfiledate='@w{'}, tofiledate='@w{'}, n=3, lineterm='\n')

比较 @emph{a} 和 @emph{b} (字符串列表)；返回统一差异格式的增量信息 (一个产生增量行的 @ref{a8c,,generator})。

所以统一差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改被显示为内联的样式（而不是分开的之前/之后文本块）。 上下文行数由 @emph{n} 设定，默认为三行。

默认情况下，差异控制行 (以 @code{---}, @code{+++} 或 @code{@@@@} 表示) 是通过末尾换行符来创建的。 这样做的好处是从 @ref{1921,,io.IOBase.readlines()} 创建的输入将得到适用于 @ref{1922,,io.IOBase.writelines()} 的差异信息，因为输入和输出都带有末尾换行符。

对于没有末尾换行符的输入，应将 @emph{lineterm} 参数设为 @code{""}，这样输出内容将统一不带换行符。

上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部分或全部可以使用字符串 @emph{fromfile}, @emph{tofile}, @emph{fromfiledate} 和 @emph{tofiledate} 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定，这些字符串默认为空。

@example
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
--- before.py
+++ after.py
@@@@ -1,4 +1,4 @@@@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido
@end example

请参阅 @ref{1923,,difflib 的命令行接口} 获取更详细的示例。
@end deffn

@geindex diff_bytes() (在 difflib 模块中)
@anchor{library/difflib difflib diff_bytes}@anchor{7c7}
@deffn {函数} difflib.diff_bytes (dfunc, a, b, fromfile=b'@w{'}, tofile=b'@w{'}, fromfiledate=b'@w{'}, tofiledate=b'@w{'}, n=3, lineterm=b'\n')

使用 @emph{dfunc} 比较 @emph{a} 和 @emph{b} (字节串对象列表)；产生以 @emph{dfunc} 所返回格式表示的差异行列表（也是字节串）。 @emph{dfunc} 必须是可调用对象，通常为 @ref{1929,,unified_diff()} 或 @ref{1920,,context_diff()}。

允许你比较编码未知或不一致的数据。 除 @emph{n} 之外的所有输入都必须为字节串对象而非字符串。 作用方式为无损地将所有输入 (除 @emph{n} 之外) 转换为字符串，并调用 @code{dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)}。 @emph{dfunc} 的输出会被随即转换回字节串，这样你所得到的增量行将具有与 @emph{a} 和 @emph{b} 相同的未知/不一致编码。


3.5 新版功能.

@end deffn

@geindex IS_LINE_JUNK() (在 difflib 模块中)
@anchor{library/difflib difflib IS_LINE_JUNK}@anchor{1925}
@deffn {函数} difflib.IS_LINE_JUNK (line)

对于可忽略的行返回 @code{True}。 如果 @emph{line} 为空行或只包含单个 @code{'#'} 则 @emph{line} 行就是可忽略的，否则就是不可忽略的。 此函数被用作较旧版本 @ref{191e,,ndiff()} 中 @emph{linejunk} 形参的默认值。
@end deffn

@geindex IS_CHARACTER_JUNK() (在 difflib 模块中)
@anchor{library/difflib difflib IS_CHARACTER_JUNK}@anchor{1926}
@deffn {函数} difflib.IS_CHARACTER_JUNK (ch)

对于可忽略的字符返回 @code{True}。 字符 @emph{ch} 如果为空格符或制表符则 @emph{ch} 就是可忽略的，否则就是不可忽略的。 此函数被用作 @ref{191e,,ndiff()} 中 @emph{charjunk} 形参的默认值。
@end deffn


@subsubheading 参见



@table @asis

@item 模式匹配：格式塔方法@footnote{http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970}

John W. Ratcliff 和 D. E. Metzener 对于一种类似算法的讨论。 此文于 1988 年 7 月发表于 Dr. Dobb's Journal@footnote{http://www.drdobbs.com/}。
@end table


@menu
* SequenceMatcher 对象:: 
* SequenceMatcher 的示例:: 
* Differ 对象:: 
* Differ 示例:: 
* difflib 的命令行接口:: 

@end menu

@node SequenceMatcher 对象,SequenceMatcher 的示例,,difflib --- 计算差异的辅助工具
@anchor{library/difflib sequence-matcher}@anchor{192a}@anchor{library/difflib sequencematcher-objects}@anchor{192b}
@subsubsection SequenceMatcher 对象


@ref{a39,,SequenceMatcher} 类具有这样的构造器：

@geindex SequenceMatcher (difflib 中的类)
@anchor{library/difflib difflib SequenceMatcher}@anchor{a39}
@deffn {类} difflib.SequenceMatcher (isjunk=None, a='@w{'}, b='@w{'}, autojunk=True)

可选参数 @emph{isjunk} 必须为 @code{None} (默认值) 或为接受一个序列元素并当且仅当其为应忽略的“垃圾”元素时返回真值的单参数函数。 传入 @code{None} 作为 @emph{isjunk} 的值就相当于传入 @code{lambda x: False}；也就是说不忽略任何值。 例如，传入:

@example
lambda x: x in " \t"
@end example

如果你以字符序列的形式对行进行比较，并且不希望区分空格符或硬制表符。

可选参数 @emph{a} 和 @emph{b} 为要比较的序列；两者默认为空字符串。 两个序列的元素都必须为 @ref{277,,hashable}。

可选参数 @emph{autojunk} 可用于启用自动垃圾启发式计算。


3.2 新版功能: @emph{autojunk} 形参。


SequenceMatcher 对象接受三个数据属性: @emph{bjunk} 是 @emph{b} 当中 @emph{isjunk} 为 @code{True} 的元素集合；@emph{bpopular} 是被启发式计算（如果其未被禁用）视为热门候选的非垃圾元素集合；@emph{b2j} 是将 @emph{b} 当中剩余元素映射到一个它们出现位置列表的字典。 所有三个数据属性将在 @emph{b} 通过 @ref{192c,,set_seqs()} 或 @ref{192d,,set_seq2()} 重置时被重置。


3.2 新版功能: @emph{bjunk} 和 @emph{bpopular} 属性。


@ref{a39,,SequenceMatcher} 对象具有以下方法：

@geindex set_seqs() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher set_seqs}@anchor{192c}
@deffn {方法} set_seqs (a, b)

设置要比较的两个序列。
@end deffn

@ref{a39,,SequenceMatcher} 计算并缓存有关第二个序列的详细信息，这样如果你想要将一个序列与多个序列进行比较，可使用 @ref{192d,,set_seq2()} 一次性地设置该常用序列并重复地对每个其他序列各调用一次 @ref{192e,,set_seq1()}。

@geindex set_seq1() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher set_seq1}@anchor{192e}
@deffn {方法} set_seq1 (a)

设置要比较的第一个序列。 要比较的第二个序列不会改变。
@end deffn

@geindex set_seq2() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher set_seq2}@anchor{192d}
@deffn {方法} set_seq2 (b)

设置要比较的第二个序列。 要比较的第一个序列不会改变。
@end deffn

@geindex find_longest_match() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher find_longest_match}@anchor{108b}
@deffn {方法} find_longest_match (alo=0, ahi=None, blo=0, bhi=None)

找出 @code{a[alo:ahi]} 和 @code{b[blo:bhi]} 中的最长匹配块。

如果 @emph{isjunk} 被省略或为 @code{None}，@ref{108b,,find_longest_match()} 将返回 @code{(i, j, k)} 使得 @code{a[i:i+k]} 等于 @code{b[j:j+k]}，其中 @code{alo <= i <= i+k <= ahi} 并且 @code{blo <= j <= j+k <= bhi}。 对于所有满足这些条件的 @code{(i', j', k')}，如果 @code{i == i'}, @code{j <= j'} 也被满足，则附加条件 @code{k >= k'}, @code{i <= i'}。 换句话说，对于所有最长匹配块，返回在 @emph{a} 当中最先出现的一个，而对于在 @emph{a} 当中最先出现的所有最长匹配块，则返回在 @emph{b} 当中最先出现的一个。

@example
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
@end example

如果提供了 @emph{isjunk}，将按上述规则确定第一个最长匹配块，但额外附加不允许块内出现垃圾元素的限制。 然后将通过（仅）匹配两边的垃圾元素来尽可能地扩展该块。 这样结果块绝对不会匹配垃圾元素，除非同样的垃圾元素正好与有意义的匹配相邻。

这是与之前相同的例子，但是将空格符视为垃圾。 这将防止 @code{' abcd'} 直接与第二个序列末尾的 @code{' abcd'} 相匹配。 而只可以匹配 @code{'abcd'}，并且是匹配第二个序列最左边的 @code{'abcd'}：

@example
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
@end example

如果未找到匹配块，此方法将返回 @code{(alo, blo, 0)}。

此方法将返回一个 @ref{b84,,named tuple} @code{Match(a, b, size)}。


在 3.9 版更改: 加入默认参数。

@end deffn

@geindex get_matching_blocks() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher get_matching_blocks}@anchor{192f}
@deffn {方法} get_matching_blocks ()

返回描述非重叠匹配子序列的三元组列表。 每个三元组的形式为 @code{(i, j, n)}，其含义为 @code{a[i:i+n] == b[j:j+n]}。 这些三元组按 @emph{i} 和 @emph{j} 单调递增排列。

最后一个三元组用于占位，其值为 @code{(len(a), len(b), 0)}。 它是唯一 @code{n == 0} 的三元组。 如果 @code{(i, j, n)} 和 @code{(i', j', n')} 是在列表中相邻的三元组，且后者不是列表中的最后一个三元组，则 @code{i+n < i'} 或 @code{j+n < j'}；换句话说，相邻的三元组总是描述非相邻的相等块。

@c XXX Explain why a dummy is used!

@example
>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
@end example
@end deffn

@geindex get_opcodes() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher get_opcodes}@anchor{1930}
@deffn {方法} get_opcodes ()

返回描述如何将 @emph{a} 变为 @emph{b} 的 5 元组列表，每个元组的形式为 @code{(tag, i1, i2, j1, j2)}。 在第一个元组中 @code{i1 == j1 == 0}，而在其余的元组中 @emph{i1} 等于前一个元组的 @emph{i2}，并且 @emph{j1} 也等于前一个元组的 @emph{j2}。

@emph{tag} 值为字符串，其含义如下：


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'replace'}

@tab

@code{a[i1:i2]} 应由 @code{b[j1:j2]} 替换。

@item

@code{'delete'}

@tab

@code{a[i1:i2]} 应被删除。 请注意在此情况下 @code{j1 == j2}。

@item

@code{'insert'}

@tab

@code{b[j1:j2]} 应插入到 @code{a[i1:i1]}。 请注意在此情况下 @code{i1 == i2}。

@item

@code{'equal'}

@tab

@code{a[i1:i2] == b[j1:j2]} (两个子序列相同)。

@end multitable


例如:

@example
>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
...     print('@{:7@}   a[@{@}:@{@}] --> b[@{@}:@{@}] @{!r:>8@} --> @{!r@}'.format(
...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
delete    a[0:1] --> b[0:0]      'q' --> '@w{'}
equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
replace   a[3:4] --> b[2:3]      'x' --> 'y'
equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
insert    a[6:6] --> b[5:6]       '@w{'} --> 'f'
@end example
@end deffn

@geindex get_grouped_opcodes() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher get_grouped_opcodes}@anchor{1931}
@deffn {方法} get_grouped_opcodes (n=3)

返回一个带有最多 @emph{n} 行上下文的分组的 @ref{a8c,,generator}。

从 @ref{1930,,get_opcodes()} 所返回的组开始，此方法会拆分出较小的更改簇并消除没有更改的间隔区域。

这些分组以与 @ref{1930,,get_opcodes()} 相同的格式返回。
@end deffn

@geindex ratio() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher ratio}@anchor{1932}
@deffn {方法} ratio ()

返回一个取值范围 [0, 1] 的浮点数作为序列相似性度量。

其中 T 是两个序列中元素的总数量，M 是匹配的数量，即 2.0*M / T。 请注意如果两个序列完全相同则该值为 @code{1.0}，如果两者完全不同则为 @code{0.0}。

如果 @ref{192f,,get_matching_blocks()} 或 @ref{1930,,get_opcodes()} 尚未被调用则此方法运算消耗较大，在此情况下你可能需要先调用 @ref{1933,,quick_ratio()} 或 @ref{1934,,real_quick_ratio()} 来获取一个上界。

@cartouche
@quotation 注解 
注意: @ref{1932,,ratio()} 调用的结果可能会取决于参数的顺序。 例如:

@example
>>> SequenceMatcher(None, 'tide', 'diet').ratio()
0.25
>>> SequenceMatcher(None, 'diet', 'tide').ratio()
0.5
@end example
@end quotation
@end cartouche
@end deffn

@geindex quick_ratio() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher quick_ratio}@anchor{1933}
@deffn {方法} quick_ratio ()

相对快速地返回一个 @ref{1932,,ratio()} 的上界。
@end deffn

@geindex real_quick_ratio() (difflib.SequenceMatcher 方法)
@anchor{library/difflib difflib SequenceMatcher real_quick_ratio}@anchor{1934}
@deffn {方法} real_quick_ratio ()

非常快速地返回一个 @ref{1932,,ratio()} 的上界。
@end deffn
@end deffn

这三个返回匹配部分占字符总数的比率的方法可能由于不同的近似级别而给出不一样的结果，但是 @code{quick_ratio()} 和 @code{real_quick_ratio()} 总是会至少与 @code{ratio()} 一样大：

@example
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0
@end example

@node SequenceMatcher 的示例,Differ 对象,SequenceMatcher 对象,difflib --- 计算差异的辅助工具
@anchor{library/difflib id1}@anchor{1935}@anchor{library/difflib sequencematcher-examples}@anchor{1936}
@subsubsection SequenceMatcher 的示例


以下示例比较两个字符串，并将空格视为“垃圾”：

@example
>>> s = SequenceMatcher(lambda x: x == " ",
...                     "private Thread currentThread;",
...                     "private volatile Thread currentThread;")
@end example

@code{ratio()} 返回一个 [0, 1] 范围内的整数作为两个序列相似性的度量。 根据经验，@code{ratio()} 值超过 0.6 就意味着两个序列是近似匹配的：

@example
>>> print(round(s.ratio(), 3))
0.866
@end example

如果你只对两个序列相匹配的位置感兴趣，则 @code{get_matching_blocks()} 就很方便：

@example
>>> for block in s.get_matching_blocks():
...     print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
@end example

请注意 @code{get_matching_blocks()} 返回的最后一个元组总是只用于占位的 @code{(len(a), len(b), 0)}，这也是元组末尾元素（匹配的元素数量）为 @code{0} 的唯一情况。

如果你想要知道如何将第一个序列转成第二个序列，可以使用 @code{get_opcodes()}:

@example
>>> for opcode in s.get_opcodes():
...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
 equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
 equal a[8:29] b[17:38]
@end example


@subsubheading 参见



@itemize *

@item 
此模块中的 @ref{1924,,get_close_matches()} 函数显示了如何基于 @ref{a39,,SequenceMatcher} 构建简单的代码来执行有用的功能。

@item 
使用 @ref{a39,,SequenceMatcher} 构建小型应用的 简易版本控制方案@footnote{https://code.activestate.com/recipes/576729/}。
@end itemize


@node Differ 对象,Differ 示例,SequenceMatcher 的示例,difflib --- 计算差异的辅助工具
@anchor{library/difflib differ-objects}@anchor{1937}@anchor{library/difflib id2}@anchor{1938}
@subsubsection Differ 对象


请注意 @ref{191b,,Differ} 所生成的增量并不保证是 @strong{最小} 差异。 相反，最小差异往往是违反直觉的，因为它们会同步任何可能的地方，有时甚至意外产生相距 100 页的匹配。 将同步点限制为连续匹配保留了一些局部性概念，这偶尔会带来产生更长差异的代价。

@ref{191b,,Differ} 类具有这样的构造器：


@deffn {类} difflib.Differ (linejunk=None, charjunk=None)

可选关键字形参 @emph{linejunk} 和 @emph{charjunk} 均为过滤函数 (或为 @code{None})：

@emph{linejunk}: 接受单个字符串作为参数的函数，如果其为垃圾字符串则返回真值。 默认值为 @code{None}，意味着没有任何行会被视为垃圾行。

@emph{charjunk}: 接受单个字符（长度为 1 的字符串）作为参数的函数，如果其为垃圾字符则返回真值。 默认值为 @code{None}，意味着没有任何字符会被视为垃圾字符。

这些垃圾过滤函数可加快查找差异的匹配速度，并且不会导致任何差异行或字符被忽略。 请阅读 @ref{108b,,find_longest_match()} 方法的 @emph{isjunk} 形参的描述了解详情。

@ref{191b,,Differ} 对象是通过一个单独方法来使用（生成增量）的：

@geindex compare() (difflib.Differ 方法)
@anchor{library/difflib difflib Differ compare}@anchor{1928}
@deffn {方法} compare (a, b)

比较两个由行组成的序列，并生成增量（一个由行组成的序列）。

每个序列必须包含一个以换行符结尾的单行字符串。 这样的序列可以通过文件类对象的 @ref{1921,,readlines()} 方法来获取。 所生成的增量同样由以换行符结尾的字符串构成，可以通过文件类对象的 @ref{1922,,writelines()} 方法原样打印出来。
@end deffn
@end deffn

@node Differ 示例,difflib 的命令行接口,Differ 对象,difflib --- 计算差异的辅助工具
@anchor{library/difflib differ-example}@anchor{1939}@anchor{library/difflib differ-examples}@anchor{193a}
@subsubsection Differ 示例


此示例比较两段文本。 首先我们设置文本为以换行符结尾的单行字符串构成的序列（这样的序列也可以通过文件类对象的 @code{readlines()} 方法来获取）：

@example
>>> text1 = '@w{'}'  1. Beautiful is better than ugly.
...   2. Explicit is better than implicit.
...   3. Simple is better than complex.
...   4. Complex is better than complicated.
... '@w{'}'.splitlines(keepends=True)
>>> len(text1)
4
>>> text1[0][-1]
'\n'
>>> text2 = '@w{'}'  1. Beautiful is better than ugly.
...   3.   Simple is better than complex.
...   4. Complicated is better than complex.
...   5. Flat is better than nested.
... '@w{'}'.splitlines(keepends=True)
@end example

接下来我们实例化一个 Differ 对象：

@example
>>> d = Differ()
@end example

请注意在实例化 @ref{191b,,Differ} 对象时我们可以传入函数来过滤掉“垃圾”行和字符。 详情参见 @ref{191b,,Differ()} 构造器说明。

最后，我们比较两个序列：

@example
>>> result = list(d.compare(text1, text2))
@end example

@code{result} 是一个字符串列表，让我们将其美化打印出来：

@example
>>> from pprint import pprint
>>> pprint(result)
['    1. Beautiful is better than ugly.\n',
 '-   2. Explicit is better than implicit.\n',
 '-   3. Simple is better than complex.\n',
 '+   3.   Simple is better than complex.\n',
 '?     ++\n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^\n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^\n',
 '+   5. Flat is better than nested.\n']
@end example

作为单独的多行字符串显示出来则是这样：

@example
>>> import sys
>>> sys.stdout.writelines(result)
    1. Beautiful is better than ugly.
-   2. Explicit is better than implicit.
-   3. Simple is better than complex.
+   3.   Simple is better than complex.
?     ++
-   4. Complex is better than complicated.
?            ^                     ---- ^
+   4. Complicated is better than complex.
?           ++++ ^                      ^
+   5. Flat is better than nested.
@end example

@node difflib 的命令行接口,,Differ 示例,difflib --- 计算差异的辅助工具
@anchor{library/difflib a-command-line-interface-to-difflib}@anchor{193b}@anchor{library/difflib difflib-interface}@anchor{1923}
@subsubsection difflib 的命令行接口


这个实例演示了如何使用 difflib 来创建一个类似于 @code{diff} 的工具。 它同样包含在 Python 源码发布包中，文件名为 @code{Tools/scripts/diff.py}。

@example
#!/usr/bin/env python3
""" Command line interface to difflib.py providing diffs in four formats:

* ndiff:    lists every line and highlights interline changes.
* context:  highlights clusters of changes in a before/after format.
* unified:  highlights clusters of changes in an inline format.
* html:     generates side by side comparison with change highlights.

"""

import sys, os, difflib, argparse
from datetime import datetime, timezone

def file_mtime(path):
    t = datetime.fromtimestamp(os.stat(path).st_mtime,
                               timezone.utc)
    return t.astimezone().isoformat()

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', action='store_true', default=False,
                        help='Produce a context format diff (default)')
    parser.add_argument('-u', action='store_true', default=False,
                        help='Produce a unified format diff')
    parser.add_argument('-m', action='store_true', default=False,
                        help='Produce HTML side by side diff '
                             '(can use -c and -l in conjunction)')
    parser.add_argument('-n', action='store_true', default=False,
                        help='Produce a ndiff format diff')
    parser.add_argument('-l', '--lines', type=int, default=3,
                        help='Set number of context lines (default 3)')
    parser.add_argument('fromfile')
    parser.add_argument('tofile')
    options = parser.parse_args()

    n = options.lines
    fromfile = options.fromfile
    tofile = options.tofile

    fromdate = file_mtime(fromfile)
    todate = file_mtime(tofile)
    with open(fromfile) as ff:
        fromlines = ff.readlines()
    with open(tofile) as tf:
        tolines = tf.readlines()

    if options.u:
        diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
    elif options.n:
        diff = difflib.ndiff(fromlines, tolines)
    elif options.m:
        diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
    else:
        diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

    sys.stdout.writelines(diff)

if __name__ == '__main__':
    main()
@end example

@node textwrap --- 文本自动换行与填充,unicodedata --- Unicode 数据库,difflib --- 计算差异的辅助工具,文本处理服务
@anchor{library/textwrap doc}@anchor{193c}@anchor{library/textwrap module-textwrap}@anchor{10a}@anchor{library/textwrap textwrap-text-wrapping-and-filling}@anchor{193d}
@subsection @code{textwrap} --- 文本自动换行与填充


@geindex textwrap (模块)

@strong{源代码:} Lib/textwrap.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/textwrap.py}


__________________________________________________________________


@ref{10a,,textwrap} 模块提供了一些快捷函数，以及可以完成所有工作的类 @ref{9d9,,TextWrapper}。 如果你只是要对一两个文本字符串进行自动换行或填充，快捷函数应该就够用了；否则的话，你应该使用 @ref{9d9,,TextWrapper} 的实例来提高效率。

@geindex wrap() (在 textwrap 模块中)
@anchor{library/textwrap textwrap wrap}@anchor{fd1}
@deffn {函数} textwrap.wrap (text, width=70, *, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

对 @emph{text} (字符串) 中的单独段落自动换行以使每行长度最多为 @emph{width} 个字符。 返回由输出行组成的列表，行尾不带换行符。

可选的关键字参数对应于 @ref{9d9,,TextWrapper} 的实例属性，具体文档见下。

请参阅 @ref{193e,,TextWrapper.wrap()} 方法了解有关 @ref{fd1,,wrap()} 行为的详细信息。
@end deffn

@geindex fill() (在 textwrap 模块中)
@anchor{library/textwrap textwrap fill}@anchor{fd2}
@deffn {函数} textwrap.fill (text, width=70, *, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, max_lines=None, placeholder=' [...]')

对 @emph{text} 中的单独段落自动换行，并返回一个包含被自动换行段落的单独字符串。 @ref{fd2,,fill()} 是以下语句的快捷方式

@example
"\n".join(wrap(text, ...))
@end example

特别要说明的是，@ref{fd2,,fill()} 接受与 @ref{fd1,,wrap()} 完全相同的关键字参数。
@end deffn

@geindex shorten() (在 textwrap 模块中)
@anchor{library/textwrap textwrap shorten}@anchor{9dc}
@deffn {函数} textwrap.shorten (text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')

折叠并截短给定的 @emph{text} 以符合给定的 @emph{width}。

首先，将折叠 @emph{text} 中的空格（所有连续空格替换为单个空格）。 如果结果能适合 @emph{width} 则将其返回。 否则将丢弃足够数量的末尾单词以使得剩余单词加 @code{placeholder} 能适合 @code{width}：

@example
>>> textwrap.shorten("Hello  world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello  world!", width=11)
'Hello [...]'
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
'Hello...'
@end example

可选的关键字参数对应于 @ref{9d9,,TextWrapper} 的实际属性，具体见下文。 请注意文本在被传入 @ref{9d9,,TextWrapper} 的 @ref{fd2,,fill()} 函数之前会被折叠，因此改变 @ref{193f,,tabsize}, @ref{1940,,expand_tabs}, @ref{1941,,drop_whitespace} 和 @ref{1942,,replace_whitespace} 的值将没有任何效果。


3.4 新版功能.

@end deffn

@geindex dedent() (在 textwrap 模块中)
@anchor{library/textwrap textwrap dedent}@anchor{1943}
@deffn {函数} textwrap.dedent (text)

移除 @emph{text} 中每一行的任何相同前缀空白符。

这可以用来清除三重引号字符串行左侧空格，而仍然在源码中显示为缩进格式。

请注意制表符和空格符都被视为是空白符，但它们并不相等：以下两行 @code{"  hello"} 和 @code{"\thello"} 不会被视为具有相同的前缀空白符。

只包含空白符的行会在输入时被忽略并在输出时被标准化为单个换行符。

例如:

@example
def test():
    # end first line with \ to avoid the empty line!
    s = '@w{'}'\
    hello
      world
    '@w{'}'
    print(repr(s))          # prints '    hello\n      world\n    '
    print(repr(dedent(s)))  # prints 'hello\n  world\n'
@end example
@end deffn

@geindex indent() (在 textwrap 模块中)
@anchor{library/textwrap textwrap indent}@anchor{b89}
@deffn {函数} textwrap.indent (text, prefix, predicate=None)

将 @emph{prefix} 添加到 @emph{text} 中选定行的开头。

通过调用 @code{text.splitlines(True)} 来对行进行拆分。

默认情况下，@emph{prefix} 会被添加到所有不是只由空白符（包括任何行结束符）组成的行。

例如:

@example
>>> s = 'hello\n\n \nworld'
>>> indent(s, '  ')
'  hello\n\n \n  world'
@end example

可选的 @emph{predicate} 参数可用来控制哪些行要缩进。 例如，可以很容易地为空行或只有空白符的行添加 @emph{prefix}:

@example
>>> print(indent(s, '+ ', lambda line: True))
+ hello
+
+
+ world
@end example


3.3 新版功能.

@end deffn

@ref{fd1,,wrap()}, @ref{fd2,,fill()} 和 @ref{9dc,,shorten()} 的作用方式为创建一个 @ref{9d9,,TextWrapper} 实例并在其上调用单个方法。 该实例不会被重用，因此对于要使用 @ref{fd1,,wrap()} 和/或 @ref{fd2,,fill()} 来处理许多文本字符串的应用来说，创建你自己的 @ref{9d9,,TextWrapper} 对象可能会更有效率。

文本最好在空白符位置自动换行，包括带连字符单词的连字符之后；长单词仅在必要时会被拆分，除非 @ref{1944,,TextWrapper.break_long_words} 被设为假值。

@geindex TextWrapper (textwrap 中的类)
@anchor{library/textwrap textwrap TextWrapper}@anchor{9d9}
@deffn {类} textwrap.TextWrapper (**kwargs)

@ref{9d9,,TextWrapper} 构造器接受多个可选的关键字参数。 每个关键字参数对应一个实例属性，比如说

@example
wrapper = TextWrapper(initial_indent="* ")
@end example

相当于：

@example
wrapper = TextWrapper()
wrapper.initial_indent = "* "
@end example

你可以多次重用相同的 @ref{9d9,,TextWrapper} 对象，并且你也可以在使用期间通过直接向实例属性赋值来修改它的任何选项。

@ref{9d9,,TextWrapper} 的实例属性（以及构造器的关键字参数）如下所示：

@geindex width (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper width}@anchor{1945}
@deffn {属性} width

(默认: @code{70}) 自动换行的最大行长度。 只要输入文本中没有长于 @ref{1945,,width} 的单个单词，@ref{9d9,,TextWrapper} 就能保证没有长于 @ref{1945,,width} 个字符的输出行。
@end deffn

@geindex expand_tabs (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper expand_tabs}@anchor{1940}
@deffn {属性} expand_tabs

(默认: @code{True}) 如果为真值，则 @emph{text} 中所有的制表符将使用 @emph{text} 的 @code{expandtabs()} 方法扩展为空格符。
@end deffn

@geindex tabsize (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper tabsize}@anchor{193f}
@deffn {属性} tabsize

(默认: @code{8}) 如果 @ref{1940,,expand_tabs} 为真值，则 @emph{text} 中所有的制表符将扩展为零个或多个空格，具体取决于当前列位置和给定的制表宽度。


3.3 新版功能.

@end deffn

@geindex replace_whitespace (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper replace_whitespace}@anchor{1942}
@deffn {属性} replace_whitespace

(default: @code{True}) 如果为真值，在制表符扩展之后、自动换行之前，@ref{fd1,,wrap()} 方法将把每个空白字符都替换为单个空格。 会被替换的空白字符如下：制表，换行，垂直制表，进纸和回车 (@code{'\t\n\v\f\r'})。

@cartouche
@quotation 注解 
如果 @ref{1940,,expand_tabs} 为假值且 @ref{1942,,replace_whitespace} 为真值，每个制表符将被替换为单个空格，这与制表符扩展是 @emph{不} 一样的。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果 @ref{1942,,replace_whitespace} 为假值，在一行的中间有可能出现换行符并导致怪异的输出。 因此，文本应当（使用 @ref{17bc,,str.splitlines()} 或类似方法）拆分为段落并分别进行自动换行。
@end quotation
@end cartouche
@end deffn

@geindex drop_whitespace (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper drop_whitespace}@anchor{1941}
@deffn {属性} drop_whitespace

(默认: @code{True}) 如果为真值，每一行开头和末尾的空白字符（在包装之后、缩进之前）会被丢弃。 但是段落开头的空白字符如果后面不带任何非空白字符则不会被丢弃。 如果被丢弃的空白字符占据了一个整行，则该整行将被丢弃。
@end deffn

@geindex initial_indent (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper initial_indent}@anchor{1946}
@deffn {属性} initial_indent

(默认: @code{'@w{'}}) 将被添加到被自动换行输出内容的第一行的字符串。 其长度会被计入第一行的长度。 空字符串不会被缩进。
@end deffn

@geindex subsequent_indent (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper subsequent_indent}@anchor{1947}
@deffn {属性} subsequent_indent

(default: @code{'@w{'}}) 将被添加到被自动换行输出内容除第一行外的所有行的字符串。 其长度会被计入除行一行外的所有行的长度。
@end deffn

@geindex fix_sentence_endings (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper fix_sentence_endings}@anchor{1948}
@deffn {属性} fix_sentence_endings

(默认: @code{False}) 如果为真值，@ref{9d9,,TextWrapper} 将尝试检测句子结尾并确保句子间总是以恰好两个空格符分隔。 对于使用等宽字体的文本来说通常都需要这样。 但是，句子检测算法并不完美：它假定句子结尾是一个小写字母加字符 @code{'.'}, @code{'!'} 或 @code{'?'} 中的一个，并可能带有字符 @code{'"'} 或 @code{"'"}，最后以一个空格结束。 此算法的问题之一是它无法区分以下文本中的 "Dr."

@example
[...] Dr. Frankenstein's monster [...]
@end example

和以下文本中的 "Spot."

@example
[...] See Spot. See Spot run [...]
@end example

@ref{1948,,fix_sentence_endings} 默认为假值。

由于句子检测算法依赖于 @code{string.lowercase} 来确定“小写字母”，以及约定在句点后使用两个空格来分隔处于同一行的句子，因此只适用于英语文本。
@end deffn

@geindex break_long_words (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper break_long_words}@anchor{1944}
@deffn {属性} break_long_words

(默认: @code{True}) 如果为真值，则长度超过 @ref{1945,,width} 的单词将被分开以保证行的长度不会超过 @ref{1945,,width}。 如果为假值，超长单词不会被分开，因而某些行的长度可能会超过 @ref{1945,,width}。 （超长单词将被单独作为一行，以尽量减少超出 @ref{1945,,width} 的情况。）
@end deffn

@geindex break_on_hyphens (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper break_on_hyphens}@anchor{1949}
@deffn {属性} break_on_hyphens

(默认: @code{True}) 如果为真值，将根据英语的惯例首选在空白符和复合词的连字符之后自动换行。 如果为假值，则只有空白符会被视为合适的潜在断行位置，但如果你确实不希望出现分开的单词则你必须将 @ref{1944,,break_long_words} 设为假值。 之前版本的默认行为总是允许分开带有连字符的单词。
@end deffn

@geindex max_lines (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper max_lines}@anchor{9da}
@deffn {属性} max_lines

(默认: @code{None}) 如果不为 @code{None}，则输出内容将最多包含 @emph{max_lines} 行，并使 @emph{placeholder} 出现在输出内容的末尾。


3.4 新版功能.

@end deffn

@geindex ...; placeholder

@geindex placeholder (textwrap.TextWrapper 属性)
@anchor{library/textwrap textwrap TextWrapper placeholder}@anchor{9db}
@deffn {属性} placeholder

(默认: @code{' [...]'}) 该文本将在输出文本被截短时出现在文本末尾。


3.4 新版功能.

@end deffn

@ref{9d9,,TextWrapper} 还提供了一些公有方法，类似于模块层级的便捷函数：

@geindex wrap() (textwrap.TextWrapper 方法)
@anchor{library/textwrap textwrap TextWrapper wrap}@anchor{193e}
@deffn {方法} wrap (text)

对 @emph{text} (字符串) 中的单独段落自动换行以使每行长度最多为 @ref{1945,,width} 个字符。 所有自动换行选项均获取自 @ref{9d9,,TextWrapper} 实例的实例属性。 返回由输出行组成的列表，行尾不带换行符。 如果自动换行输出结果没有任何内容，则返回空列表。
@end deffn

@geindex fill() (textwrap.TextWrapper 方法)
@anchor{library/textwrap textwrap TextWrapper fill}@anchor{194a}
@deffn {方法} fill (text)

对 @emph{text} 中的单独段落自动换行并返回包含被自动换行段落的单独字符串。
@end deffn
@end deffn

@node unicodedata --- Unicode 数据库,stringprep --- 因特网字符串预备,textwrap --- 文本自动换行与填充,文本处理服务
@anchor{library/unicodedata doc}@anchor{194b}@anchor{library/unicodedata module-unicodedata}@anchor{123}@anchor{library/unicodedata unicodedata-unicode-database}@anchor{194c}
@subsection @code{unicodedata} --- Unicode 数据库


@geindex unicodedata (模块)

@geindex Unicode
@geindex character
@geindex Unicode; database


__________________________________________________________________


此模块提供了对 Unicode Character Database (UCD) 的访问，其中定义了所有 Unicode 字符的字符属性。 此数据库中包含的数据编译自 UCD 版本 13.0.0@footnote{https://www.unicode.org/Public/13.0.0/ucd}。

该模块使用与 Unicode 标准附件 #44 “Unicode 字符数据库”@footnote{https://www.unicode.org/reports/tr44/} 中所定义的相同名称和符号。 它定义了以下函数：

@geindex lookup() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata lookup}@anchor{aa6}
@deffn {函数} unicodedata.lookup (name)

按名称查找字符。如果找到具有给定名称的字符，则返回相应的字符。 如果没有找到，则 @ref{3f1,,KeyError} 被引发。


在 3.3 版更改: 已添加对名称别名 @footnote{@w{(1)} 
@indicateurl{https://www.unicode.org/Public/13.0.0/ucd/NameAliases.txt}
} 和命名序列 @footnote{@w{(2)} 
@indicateurl{https://www.unicode.org/Public/13.0.0/ucd/NamedSequences.txt}
} 的支持。

@end deffn

@geindex name() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata name}@anchor{194d}
@deffn {函数} unicodedata.name (chr[, default])

返回分配给字符 @emph{chr} 的名称作为字符串。如果没有定义名称，则返回 @emph{default} ，如果没有给出，则 @ref{16d,,ValueError} 被引发。
@end deffn

@geindex decimal() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata decimal}@anchor{194e}
@deffn {函数} unicodedata.decimal (chr[, default])

返回分配给字符 @emph{chr} 的十进制值作为整数。 如果没有定义这样的值，则返回 @emph{default} ，如果没有给出，则 @ref{16d,,ValueError} 被引发。
@end deffn

@geindex digit() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata digit}@anchor{194f}
@deffn {函数} unicodedata.digit (chr[, default])

返回分配给字符 @emph{chr} 的数字值作为整数。 如果没有定义这样的值，则返回 @emph{default} ，如果没有给出，则 @ref{16d,,ValueError} 被引发。
@end deffn

@geindex numeric() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata numeric}@anchor{ccc}
@deffn {函数} unicodedata.numeric (chr[, default])

返回分配给字符 @emph{chr} 的数值作为浮点数。 如果没有定义这样的值，则返回 @emph{default} ，如果没有给出，则 @ref{16d,,ValueError} 被引发。
@end deffn

@geindex category() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata category}@anchor{1950}
@deffn {函数} unicodedata.category (chr)

返回分配给字符 @emph{chr} 的常规类别为字符串。
@end deffn

@geindex bidirectional() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata bidirectional}@anchor{1951}
@deffn {函数} unicodedata.bidirectional (chr)

返回分配给字符 @emph{chr} 的双向类作为字符串。如果未定义此类值，则返回空字符串。
@end deffn

@geindex combining() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata combining}@anchor{1952}
@deffn {函数} unicodedata.combining (chr)

返回分配给字符 @emph{chr} 的规范组合类作为整数。如果没有定义组合类，则返回 @code{0} 。
@end deffn

@geindex east_asian_width() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata east_asian_width}@anchor{1953}
@deffn {函数} unicodedata.east_asian_width (chr)

返回分配给字符 @emph{chr} 的东亚宽度作为字符串。
@end deffn

@geindex mirrored() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata mirrored}@anchor{1954}
@deffn {函数} unicodedata.mirrored (chr)

返回分配给字符 @emph{chr} 的镜像属性为整数。如果字符在双向文本中被识别为“镜像”字符，则返回 @code{1} ，否则返回 @code{0} 。
@end deffn

@geindex decomposition() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata decomposition}@anchor{1955}
@deffn {函数} unicodedata.decomposition (chr)

返回分配给字符 @emph{chr} 的字符分解映射作为字符串。如果未定义此类映射，则返回空字符串。
@end deffn

@geindex normalize() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata normalize}@anchor{122c}
@deffn {函数} unicodedata.normalize (form, unistr)

返回 Unicode 字符串 @emph{unistr} 的正常形式 @emph{form} 。 @emph{form} 的有效值为 'NFC' 、 'NFKC' 、 'NFD' 和 'NFKD' 。

Unicode 标准基于规范等价和兼容性等效的定义定义了 Unicode 字符串的各种规范化形式。在 Unicode 中，可以以各种方式表示多个字符。 例如，字符 U+00C7 （带有 CEDILLA 的 LATIN CAPITAL LETTER C ）也可以表示为序列 U+0043（ LATIN CAPITAL LETTER C ）U+0327（ COMBINING CEDILLA ）。

对于每个字符，有两种正规形式：正规形式 C 和正规形式 D 。正规形式D（NFD）也称为规范分解，并将每个字符转换为其分解形式。 正规形式C（NFC）首先应用规范分解，然后再次组合预组合字符。

除了这两种形式之外，还有两种基于兼容性等效的其他常规形式。 在 Unicode 中，支持某些字符，这些字符通常与其他字符统一。 例如， U+2160（ROMAN NUMERAL ONE）与 U+0049（LATIN CAPITAL LETTER I）完全相同。 但是， Unicode 支持它与现有字符集（例如 gb2312 ）的兼容性。

正规形式KD（NFKD）将应用兼容性分解，即用其等价项替换所有兼容性字符。 正规形式KC（NFKC）首先应用兼容性分解，然后是规范组合。

即使两个 unicode 字符串被规范化并且人类读者看起来相同，如果一个具有组合字符而另一个没有，则它们可能无法相等。
@end deffn

@geindex is_normalized() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata is_normalized}@anchor{377}
@deffn {函数} unicodedata.is_normalized (form, unistr)

判断 Unicode 字符串 @emph{unistr} 是否为正规形式 @emph{form}。 @emph{form} 的有效值为 'NFC', 'NFKC', 'NFD' 和 'NFKD'。


3.8 新版功能.

@end deffn

此外，该模块暴露了以下常量：

@geindex unidata_version() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata unidata_version}@anchor{1956}
@deffn {数据} unicodedata.unidata_version

此模块中使用的 Unicode 数据库的版本。
@end deffn

@geindex ucd_3_2_0() (在 unicodedata 模块中)
@anchor{library/unicodedata unicodedata ucd_3_2_0}@anchor{e69}
@deffn {数据} unicodedata.ucd_3_2_0

这是一个与整个模块具有相同方法的对象，但对于需要此特定版本的 Unicode 数据库（如 IDNA ）的应用程序，则使用 Unicode 数据库版本 3.2 。
@end deffn

示例：

@example
>>> import unicodedata
>>> unicodedata.lookup('LEFT CURLY BRACKET')
'@{'
>>> unicodedata.name('/')
'SOLIDUS'
>>> unicodedata.decimal('9')
9
>>> unicodedata.decimal('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a decimal
>>> unicodedata.category('A')  # 'L'etter, 'u'ppercase
'Lu'
>>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber
'AN'
@end example

@node stringprep --- 因特网字符串预备,readline --- GNU readline 接口,unicodedata --- Unicode 数据库,文本处理服务
@anchor{library/stringprep doc}@anchor{1957}@anchor{library/stringprep module-stringprep}@anchor{f7}@anchor{library/stringprep stringprep-internet-string-preparation}@anchor{1958}
@subsection @code{stringprep} --- 因特网字符串预备


@geindex stringprep (模块)

@strong{源代码:} Lib/stringprep.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/stringprep.py}


__________________________________________________________________


在标识因特网上的事物（例如主机名），经常需要比较这些标识是否（相等）。 这种比较的具体执行可能会取决于应用域的不同，例如是否要区分大小写等等。 有时也可能需要限制允许的标识为仅由“可打印”字符组成。

@geindex RFC; RFC 3454
RFC 3454@footnote{https://tools.ietf.org/html/rfc3454.html} 定义了在因特网协议中 Unicode 字符串的“预备”过程。 在将字符串连线传输之前，它们会先使用预备过程进行处理，之后它们将具有特定的标准形式。 该 RFC 定义了一系列表格，它们可以被组合为选项配置。 每个配置必须定义所使用的表格，@code{stringprep} 过程的其他可选项也是配置的组成部分。 @code{stringprep} 配置的一个例子是 @code{nameprep}，它被用于国际化域名。

模块 @ref{f7,,stringprep} 仅公开了来自 
@geindex RFC; RFC 3454
RFC 3454@footnote{https://tools.ietf.org/html/rfc3454.html} 的表格。 由于这些如果表格如果表示为字典或列表将会非常庞大，该模块在内部使用 Unicode 字符数据库。 该模块本身的源代码是使用 @code{mkstringprep.py} 工具生成的。

因此，这些表格以函数而非数据结构的形式公开。 在 RFC 中有两种表格：集合与映射。 对于集合，@ref{f7,,stringprep} 提供了“特征函数”，即如果形参是集合的一部分则返回值为 @code{True} 的函数。 对于映射，它提供了映射函数：它会根据给定的键返回所关联的值。 以下是模块中所有可用函数的列表。

@geindex in_table_a1() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_a1}@anchor{1959}
@deffn {函数} stringprep.in_table_a1 (code)

确定 @emph{code} 是否属于 tableA.1 (Unicode 3.2 中的未分配码位)。
@end deffn

@geindex in_table_b1() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_b1}@anchor{195a}
@deffn {函数} stringprep.in_table_b1 (code)

确定 @emph{code} 是否属于 tableB.1 (通常映射为空值)。
@end deffn

@geindex map_table_b2() (在 stringprep 模块中)
@anchor{library/stringprep stringprep map_table_b2}@anchor{195b}
@deffn {函数} stringprep.map_table_b2 (code)

返回 @emph{code} 依据 tableB.2 (配合 NFKC 使用的大小写转换映射) 所映射的值。
@end deffn

@geindex map_table_b3() (在 stringprep 模块中)
@anchor{library/stringprep stringprep map_table_b3}@anchor{195c}
@deffn {函数} stringprep.map_table_b3 (code)

返回 @emph{code} 依据 tableB.3 (不附带正规化的大小写折叠映射) 所映射的值。
@end deffn

@geindex in_table_c11() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c11}@anchor{195d}
@deffn {函数} stringprep.in_table_c11 (code)

确定 @emph{code} 是否属于 tableC.1.1  (ASCII 空白字符)。
@end deffn

@geindex in_table_c12() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c12}@anchor{195e}
@deffn {函数} stringprep.in_table_c12 (code)

确定 @emph{code} 是否属于 tableC.1.2  (非 ASCII 空白字符)。
@end deffn

@geindex in_table_c11_c12() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c11_c12}@anchor{195f}
@deffn {函数} stringprep.in_table_c11_c12 (code)

确定 @emph{code} 是否属于 tableC.1  (空白字符，C.1.1 和 C.1.2 的并集)。
@end deffn

@geindex in_table_c21() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c21}@anchor{1960}
@deffn {函数} stringprep.in_table_c21 (code)

确定 @emph{code} 是否属于 tableC.2.1  (ASCII 控制字符)。
@end deffn

@geindex in_table_c22() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c22}@anchor{1961}
@deffn {函数} stringprep.in_table_c22 (code)

确定 @emph{code} 是否属于 tableC.2.2  (非 ASCII 控制字符)。
@end deffn

@geindex in_table_c21_c22() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c21_c22}@anchor{1962}
@deffn {函数} stringprep.in_table_c21_c22 (code)

确定 @emph{code} 是否属于 tableC.2  (控制字符，C.2.1 和 C.2.2 的并集)。
@end deffn

@geindex in_table_c3() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c3}@anchor{1963}
@deffn {函数} stringprep.in_table_c3 (code)

确定 @emph{code} 是否属于 tableC.3  (私有使用)。
@end deffn

@geindex in_table_c4() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c4}@anchor{1964}
@deffn {函数} stringprep.in_table_c4 (code)

确定 @emph{code} 是否属于 tableC.4  (非字符码位)。
@end deffn

@geindex in_table_c5() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c5}@anchor{1965}
@deffn {函数} stringprep.in_table_c5 (code)

确定 @emph{code} 是否属于 tableC.5  (替代码)。
@end deffn

@geindex in_table_c6() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c6}@anchor{1966}
@deffn {函数} stringprep.in_table_c6 (code)

确定 @emph{code} 是否属于 tableC.6  (不适用于纯文本)。
@end deffn

@geindex in_table_c7() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c7}@anchor{1967}
@deffn {函数} stringprep.in_table_c7 (code)

确定 @emph{code} 是否属于 tableC.7  (不适用于规范表示)。
@end deffn

@geindex in_table_c8() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c8}@anchor{1968}
@deffn {函数} stringprep.in_table_c8 (code)

确定 @emph{code} 是否属于 tableC.8  (改变显示属性或已弃用)。
@end deffn

@geindex in_table_c9() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_c9}@anchor{1969}
@deffn {函数} stringprep.in_table_c9 (code)

确定 @emph{code} 是否属于 tableC.9  (标记字符)。
@end deffn

@geindex in_table_d1() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_d1}@anchor{196a}
@deffn {函数} stringprep.in_table_d1 (code)

确定 @emph{code} 是否属于 tableD.1  (带有双向属性 "R" 或 "AL" 的字符)。
@end deffn

@geindex in_table_d2() (在 stringprep 模块中)
@anchor{library/stringprep stringprep in_table_d2}@anchor{196b}
@deffn {函数} stringprep.in_table_d2 (code)

确定 @emph{code} 是否属于 tableD.2  (带有双向属性 "L" 的字符)。
@end deffn

@node readline --- GNU readline 接口,rlcompleter --- GNU readline 的补全函数,stringprep --- 因特网字符串预备,文本处理服务
@anchor{library/readline doc}@anchor{196c}@anchor{library/readline module-readline}@anchor{de}@anchor{library/readline readline-gnu-readline-interface}@anchor{196d}
@subsection @code{readline} --- GNU readline 接口


@geindex readline (模块)


__________________________________________________________________


@ref{de,,readline} 模块定义了许多方便从 Python 解释器完成和读取/写入历史文件的函数。 此模块可以直接使用，或通过支持在交互提示符下完成 Python 标识符的 @ref{e1,,rlcompleter} 模块使用。 使用此模块进行的设置会同时影响解释器的交互提示符以及内置 @ref{d3b,,input()} 函数提供的提示符。

Readline keybindings may be configured via an initialization file, typically
@code{.inputrc} in your home directory.  See Readline Init File@footnote{https://tiswww.cwru.edu/php/chet/readline/rluserman.html#SEC9}
in the GNU Readline manual for information about the format and
allowable constructs of that file, and the capabilities of the
Readline library in general.

@cartouche
@quotation 注解 
底层的 Readline 库 API 可能使用 @code{libedit} 库来实现而不是 GNU readline。 在 macOS 上 @ref{de,,readline} 模块会在运行时检测所使用的是哪个库。

@code{libedit} 所用的配置文件与 GNU readline 的不同。 如果你要在程序中载入配置字符串你可以在 @code{readline.__doc__} 中检测文本 "libedit" 来区分 GNU readline 和 libedit。

如果你是在 macOS 上使用 @emph{editline}/@code{libedit} readline 模拟，则位于你的主目录中的初始化文件名称为 @code{.editrc}。 例如，@code{~/.editrc} 中的以下内容将开启 @emph{vi} 按键绑定以及 TAB 补全:

@example
python:bind -v
python:bind ^I rl_complete
@end example
@end quotation
@end cartouche

@menu
* 初始化文件:: 
* 行缓冲区:: 
* 历史文件:: 
* 历史列表:: 
* 启动钩子:: 
* Completion:: 
* 示例: 示例<2>. 

@end menu

@node 初始化文件,行缓冲区,,readline --- GNU readline 接口
@anchor{library/readline init-file}@anchor{196e}
@subsubsection 初始化文件


下列函数与初始化文件和用户配置有关：

@geindex parse_and_bind() (在 readline 模块中)
@anchor{library/readline readline parse_and_bind}@anchor{196f}
@deffn {函数} readline.parse_and_bind (string)

执行在 @emph{string} 参数中提供的初始化行。 此函数会调用底层库中的 @code{rl_parse_and_bind()}。
@end deffn

@geindex read_init_file() (在 readline 模块中)
@anchor{library/readline readline read_init_file}@anchor{1970}
@deffn {函数} readline.read_init_file ([filename])

执行一个 readline 初始化文件。 默认文件名为最近所使用的文件名。 此函数会调用底层库中的 @code{rl_read_init_file()}。
@end deffn

@node 行缓冲区,历史文件,初始化文件,readline --- GNU readline 接口
@anchor{library/readline line-buffer}@anchor{1971}
@subsubsection 行缓冲区


下列函数会在行缓冲区上操作。

@geindex get_line_buffer() (在 readline 模块中)
@anchor{library/readline readline get_line_buffer}@anchor{1972}
@deffn {函数} readline.get_line_buffer ()

返回行缓冲区的当前内容 (底层库中的 @code{rl_line_buffer})。
@end deffn

@geindex insert_text() (在 readline 模块中)
@anchor{library/readline readline insert_text}@anchor{1973}
@deffn {函数} readline.insert_text (string)

将文本插入行缓冲区的当前游标位置。 该函数会调用底层库中的 @code{rl_insert_text()}，但会忽略其返回值。
@end deffn

@geindex redisplay() (在 readline 模块中)
@anchor{library/readline readline redisplay}@anchor{1974}
@deffn {函数} readline.redisplay ()

改变屏幕的显示以反映行缓冲区的当前内容。 该函数会调用底层库中的 @code{rl_redisplay()}。
@end deffn

@node 历史文件,历史列表,行缓冲区,readline --- GNU readline 接口
@anchor{library/readline history-file}@anchor{1975}
@subsubsection 历史文件


下列函数会在历史文件上操作：

@geindex read_history_file() (在 readline 模块中)
@anchor{library/readline readline read_history_file}@anchor{1976}
@deffn {函数} readline.read_history_file ([filename])

载入一个 readline 历史文件，并将其添加到历史列表。 默认文件名为 @code{~/.history}。 此函数会调用底层库中的 @code{read_history()}。
@end deffn

@geindex write_history_file() (在 readline 模块中)
@anchor{library/readline readline write_history_file}@anchor{1977}
@deffn {函数} readline.write_history_file ([filename])

将历史列表保存为 readline 历史文件，覆盖任何现有文件。 默认文件名为 @code{~/.history}。 此函数会调用底层库中的 @code{write_history()}。
@end deffn

@geindex append_history_file() (在 readline 模块中)
@anchor{library/readline readline append_history_file}@anchor{835}
@deffn {函数} readline.append_history_file (nelements[, filename])

将历史列表的最后 @emph{nelements} 项添加到历史文件。 默认文件名为 @code{~/.history}。 文件必须已存在。 此函数会调用底层库中的 @code{append_history()}。 此函数仅当 Python 编译包带有支持此功能的库版本时才会存在。


3.5 新版功能.

@end deffn

@geindex get_history_length() (在 readline 模块中)
@geindex set_history_length() (在 readline 模块中)
@anchor{library/readline readline get_history_length}@anchor{1978}
@deffn {函数} readline.get_history_length ()
@anchor{library/readline readline set_history_length}@anchor{1979}
@deffnx {函数} readline.set_history_length (length)

设置或返回需要保存到历史文件的行数。 @ref{1977,,write_history_file()} 函数会通过调用底层库中的 @code{history_truncate_file()} 以使用该值来截取历史文件。 负值意味着不限制历史文件的大小。
@end deffn

@node 历史列表,启动钩子,历史文件,readline --- GNU readline 接口
@anchor{library/readline history-list}@anchor{197a}
@subsubsection 历史列表


以下函数会在全局历史列表上操作：

@geindex clear_history() (在 readline 模块中)
@anchor{library/readline readline clear_history}@anchor{197b}
@deffn {函数} readline.clear_history ()

清除当前历史。 此函数会调用底层库的 @code{clear_history()}。 此 Python 函数仅当 Python 编译包带有支持此功能的库版本时才会存在。
@end deffn

@geindex get_current_history_length() (在 readline 模块中)
@anchor{library/readline readline get_current_history_length}@anchor{197c}
@deffn {函数} readline.get_current_history_length ()

返回历史列表的当前项数。 （此函数不同于 @ref{1978,,get_history_length()}，后者是返回将被写入历史文件的最大行数。）
@end deffn

@geindex get_history_item() (在 readline 模块中)
@anchor{library/readline readline get_history_item}@anchor{197d}
@deffn {函数} readline.get_history_item (index)

返回序号为 @emph{index} 的历史条目的当前内容。 条目序号从一开始。 此函数会调用底层库中的 @code{history_get()}。
@end deffn

@geindex remove_history_item() (在 readline 模块中)
@anchor{library/readline readline remove_history_item}@anchor{197e}
@deffn {函数} readline.remove_history_item (pos)

从历史列表中移除指定位置上的历史条目。 条目位置从零开始。 此函数会调用底层库中的 @code{remove_history()}。
@end deffn

@geindex replace_history_item() (在 readline 模块中)
@anchor{library/readline readline replace_history_item}@anchor{197f}
@deffn {函数} readline.replace_history_item (pos, line)

将指定位置上的历史条目替换为 @emph{line}。 条目位置从零开始。 此函数会调用底层库中的 @code{replace_history_entry()}。
@end deffn

@geindex add_history() (在 readline 模块中)
@anchor{library/readline readline add_history}@anchor{1980}
@deffn {函数} readline.add_history (line)

将 @emph{line} 添加到历史缓冲区，相当于是最近输入的一行。 此函数会调用底层库中的 @code{add_history()}。
@end deffn

@geindex set_auto_history() (在 readline 模块中)
@anchor{library/readline readline set_auto_history}@anchor{678}
@deffn {函数} readline.set_auto_history (enabled)

启用或禁用当通过 readline 读取输入时自动调用 @code{add_history()}。 @emph{enabled} 参数应为一个布尔值，当其为真值时启用自动历史，当其为假值时禁用自动历史。


3.6 新版功能.


@strong{CPython implementation detail:} Auto history is enabled by default, and changes to this do not persist
across multiple sessions.
@end deffn

@node 启动钩子,Completion,历史列表,readline --- GNU readline 接口
@anchor{library/readline startup-hooks}@anchor{1981}
@subsubsection 启动钩子


@geindex set_startup_hook() (在 readline 模块中)
@anchor{library/readline readline set_startup_hook}@anchor{1982}
@deffn {函数} readline.set_startup_hook ([function])

设置或移除底层库的 @code{rl_startup_hook} 回调所发起调用的函数。 如果指定了 @emph{function}，它将被用作新的钩子函数；如果省略或为 @code{None}，任何已安装的函数将被移除。 钩子函数将在 readline 打印第一个提示信息之前不带参数地被调用。
@end deffn

@geindex set_pre_input_hook() (在 readline 模块中)
@anchor{library/readline readline set_pre_input_hook}@anchor{1983}
@deffn {函数} readline.set_pre_input_hook ([function])

设置或移除底层库的 @code{rl_pre_input_hook} 回调所发起调用的函数。 如果指定了 @emph{function}，它将被用作新的钩子函数；如果省略或为 @code{None}，任何已安装的函数将被移除。 钩子函数将在打印第一个提示信息之后、readline 开始读取输入字符之前不带参数地被调用。 此函数仅当 Python 编译包带有支持此功能的库版本时才会存在。
@end deffn

@node Completion,示例<2>,启动钩子,readline --- GNU readline 接口
@anchor{library/readline completion}@anchor{1984}
@subsubsection Completion


以下函数与自定义单词补全函数的实现有关。 这通常使用 Tab 键进行操作，能够提示并自动补全正在输入的单词。 默认情况下，Readline 设置为由 @ref{e1,,rlcompleter} 来补全交互模式解释器的 Python 标识符。 如果 @ref{de,,readline} 模块要配合自定义的补全函数来使用，则需要设置不同的单词分隔符。

@geindex set_completer() (在 readline 模块中)
@anchor{library/readline readline set_completer}@anchor{1985}
@deffn {函数} readline.set_completer ([function])

设置或移除补全函数。 如果指定了 @emph{function}，它将被用作新的补全函数；如果省略或为 @code{None}，任何已安装的补全函数将被移除。 补全函数的调用形式为 @code{function(text, state)}，其中 @emph{state} 为 @code{0}, @code{1}, @code{2}, ..., 直至其返回一个非字符串值。 它应当返回下一个以 @emph{text} 开头的候选补全内容。

已安装的补全函数将由传递给底层库中 @code{rl_completion_matches()} 的 @emph{entry_func} 回调函数来发起调用。 @emph{text} 字符串来自于底层库中 @code{rl_attempted_completion_function} 回调函数的第一个形参。
@end deffn

@geindex get_completer() (在 readline 模块中)
@anchor{library/readline readline get_completer}@anchor{1986}
@deffn {函数} readline.get_completer ()

获取补全函数，如果没有设置补全函数则返回 @code{None}。
@end deffn

@geindex get_completion_type() (在 readline 模块中)
@anchor{library/readline readline get_completion_type}@anchor{1987}
@deffn {函数} readline.get_completion_type ()

获取正在尝试的补全类型。 此函数会将底层库中的 @code{rl_completion_type} 变量作为一个整数返回。
@end deffn

@geindex get_begidx() (在 readline 模块中)
@geindex get_endidx() (在 readline 模块中)
@anchor{library/readline readline get_begidx}@anchor{1988}
@deffn {函数} readline.get_begidx ()
@anchor{library/readline readline get_endidx}@anchor{1989}
@deffnx {函数} readline.get_endidx ()

获取补全域的开始和结束序号。 这些序号就是传给底层库中 @code{rl_attempted_completion_function} 回调函数的 @emph{start} 和 @emph{end} 参数。
@end deffn

@geindex set_completer_delims() (在 readline 模块中)
@geindex get_completer_delims() (在 readline 模块中)
@anchor{library/readline readline set_completer_delims}@anchor{198a}
@deffn {函数} readline.set_completer_delims (string)
@anchor{library/readline readline get_completer_delims}@anchor{198b}
@deffnx {函数} readline.get_completer_delims ()

设置或获取补全的单词分隔符。 此分隔符确定了要考虑补全的单词的开始和结束位置（补全域）。 这些函数会访问底层库的 @code{rl_completer_word_break_characters} 变量。
@end deffn

@geindex set_completion_display_matches_hook() (在 readline 模块中)
@anchor{library/readline readline set_completion_display_matches_hook}@anchor{198c}
@deffn {函数} readline.set_completion_display_matches_hook ([function])

设置或移除补全显示函数。 如果指定了 @emph{function}，它将被用作新的补全显示函数；如果省略或为 @code{None}，任何已安装的补全显示函数将被移除。 此函数会设置或清除底层库的 @code{rl_completion_display_matches_hook} 回调函数。 补全显示函数会在每次需要显示匹配项时以 @code{function(substitution, [matches], longest_match_length)} 的形式被调用。
@end deffn

@node 示例<2>,,Completion,readline --- GNU readline 接口
@anchor{library/readline example}@anchor{198d}@anchor{library/readline readline-example}@anchor{198e}
@subsubsection 示例


以下示例演示了如何使用 @ref{de,,readline} 模块的历史读取或写入函数来自动加载和保存用户主目录下名为 @code{.python_history} 的历史文件。 以下代码通常应当在交互会话期间从用户的 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 文件自动执行。

@example
import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)
@end example

此代码实际上会在 Python 运行于 @ref{9d2,,交互模式} 时自动运行 (参见 @ref{9d5,,Readline 配置})。

以下示例实现了同样的目标，但是通过只添加新历史的方式来支持并发的交互会话。

@example
import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")

try:
    readline.read_history_file(histfile)
    h_len = readline.get_current_history_length()
except FileNotFoundError:
    open(histfile, 'wb').close()
    h_len = 0

def save(prev_h_len, histfile):
    new_h_len = readline.get_current_history_length()
    readline.set_history_length(1000)
    readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)
@end example

以下示例扩展了 @ref{198f,,code.InteractiveConsole} 类以支持历史保存/恢复。

@example
import atexit
import code
import os
import readline

class HistoryConsole(code.InteractiveConsole):
    def __init__(self, locals=None, filename="<console>",
                 histfile=os.path.expanduser("~/.console-history")):
        code.InteractiveConsole.__init__(self, locals, filename)
        self.init_history(histfile)

    def init_history(self, histfile):
        readline.parse_and_bind("tab: complete")
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except FileNotFoundError:
                pass
            atexit.register(self.save_history, histfile)

    def save_history(self, histfile):
        readline.set_history_length(1000)
        readline.write_history_file(histfile)
@end example

@node rlcompleter --- GNU readline 的补全函数,,readline --- GNU readline 接口,文本处理服务
@anchor{library/rlcompleter doc}@anchor{1990}@anchor{library/rlcompleter module-rlcompleter}@anchor{e1}@anchor{library/rlcompleter rlcompleter-completion-function-for-gnu-readline}@anchor{1991}
@subsection @code{rlcompleter} --- GNU readline 的补全函数


@geindex rlcompleter (模块)

@strong{源代码:} Lib/rlcompleter.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/rlcompleter.py}


__________________________________________________________________


@code{rlcompeleter} 通过补全有效的 Python 标识符和关键字定义了一个适用于 @ref{de,,readline} 模块的补全函数。

当此模块在具有可用的 @ref{de,,readline} 模块的 Unix 平台被导入, 一个 @code{Completer} 实例将被自动创建并且它的 @code{complete()} 方法将设置为 @ref{de,,readline} 的补全器.

示例:

@example
>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
readline.__file__         readline.insert_text(      readline.set_completer(
readline.__name__         readline.parse_and_bind(
>>> readline.
@end example

@ref{e1,,rlcompleter} 模块是为了使用 Python 的 @ref{9d2,,交互模式} 而设计的。 除非 Python 是通过 @ref{c00,,-S} 选项运行, 这个模块总是自动地被导入且配置 (参见 @ref{9d5,,Readline 配置})。

在没有 @ref{de,,readline} 的平台, 此模块定义的 @code{Completer} 类仍然可以用于自定义行为.

@menu
* Completer 对象:: 

@end menu

@node Completer 对象,,,rlcompleter --- GNU readline 的补全函数
@anchor{library/rlcompleter completer-objects}@anchor{1992}@anchor{library/rlcompleter id1}@anchor{1993}
@subsubsection Completer 对象


Completer 对象具有以下方法：

@geindex complete() (rlcompleter.Completer 方法)
@anchor{library/rlcompleter rlcompleter Completer complete}@anchor{1994}
@deffn {方法} Completer.complete (text, state)

为 @emph{text} 返回第 @emph{state} 项补全。

如果指定的 @emph{text} 不包含句点字符 (@code{'.'})，它将根据当前 @ref{1,,__main__}, @ref{12,,builtins} 和保留关键字（定义于 @ref{a6,,keyword} 模块）所定义的名称进行补全。

如果为带有句点的名称执行调用，它将尝试尽量求值直到最后一部分为止而不产生附带影响（函数不会被求值，但它可以生成对 @ref{433,,__getattr__()} 的调用），并通过 @ref{e01,,dir()} 函数来匹配剩余部分。 在对表达式求值期间引发的任何异常都会被捕获、静默处理并返回 @ref{204,,None}。
@end deffn

@node 二进制数据服务,数据类型,文本处理服务,Python 标准库
@anchor{library/binary doc}@anchor{1995}@anchor{library/binary binary-data-services}@anchor{1996}@anchor{library/binary binaryservices}@anchor{18b2}
@section 二进制数据服务


本章介绍的模块提供了一些操作二进制数据的基本服务操作。 有关二进制数据的其他操作，特别是与文件格式和网络协议有关的操作，将在相关章节中介绍。

下面描述的一些库 @ref{17a5,,文本处理服务} 也可以使用 ASCII 兼容的二进制格式（例如 @ref{dd,,re} ）或所有二进制数据（例如 @ref{36,,difflib} ）。

另外，请参阅 Python 的内置二进制数据类型的文档 @ref{174d,,二进制序列类型 --- bytes@comma{} bytearray@comma{} memoryview} 。

@menu
* struct: struct --- 将字节串解读为打包的二进制数据. 将字节串解读为打包的二进制数据
* codecs: codecs --- 编解码器注册和相关基类. 编解码器注册和相关基类

@end menu

@node struct --- 将字节串解读为打包的二进制数据,codecs --- 编解码器注册和相关基类,,二进制数据服务
@anchor{library/struct doc}@anchor{1997}@anchor{library/struct module-struct}@anchor{f8}@anchor{library/struct struct-interpret-bytes-as-packed-binary-data}@anchor{1998}
@subsection @code{struct} --- 将字节串解读为打包的二进制数据


@geindex struct (模块)

@strong{源代码：} Lib/struct.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/struct.py}

@geindex C; structures
@geindex packing; binary; data


__________________________________________________________________


此模块可以执行 Python 值和以 Python @ref{172,,bytes} 对象表示的 C 结构之间的转换。 这可以被用来处理存储在文件中或是从网络连接等其他来源获取的二进制数据。 它使用 @ref{1999,,格式字符串} 作为 C 结构布局的精简描述以及与 Python 值的双向转换。

@cartouche
@quotation 注解 
默认情况下，打包给定 C 结构的结果会包含填充字节以使得所涉及的 C 类型保持正确的对齐；类似地，对齐在解包时也会被纳入考虑。 选择此种行为的目的是使得被打包结构的字节能与相应 C 结构在内存中的布局完全一致。 要处理平台独立的数据格式或省略隐式的填充字节，请使用 @code{standard} 大小和对齐而不是 @code{native} 大小和对齐：详情参见 @ref{199a,,字节顺序，大小和对齐方式}。
@end quotation
@end cartouche

某些 @ref{f8,,struct} 的函数（以及 @ref{199b,,Struct} 的方法）接受一个 @emph{buffer} 参数。 这将指向实现了 @ref{174c,,缓冲协议} 并提供只读或是可读写缓冲的对象。 用于此目的的最常见类型为 @ref{172,,bytes} 和 @ref{173,,bytearray}，但许多其他可被视为字节数组的类型也实现了缓冲协议，因此它们无需额外从 @ref{172,,bytes} 对象复制即可被读取或填充。

@menu
* 函数和异常:: 
* 格式字符串:: 
* 类: 类<2>. 

@end menu

@node 函数和异常,格式字符串,,struct --- 将字节串解读为打包的二进制数据
@anchor{library/struct functions-and-exceptions}@anchor{199c}
@subsubsection 函数和异常


此模块定义了下列异常和函数：

@geindex error
@anchor{library/struct struct error}@anchor{d84}
@deffn {例外} struct.error

会在多种场合下被引发的异常；其参数为一个描述错误信息的字符串。
@end deffn

@geindex pack() (在 struct 模块中)
@anchor{library/struct struct pack}@anchor{cde}
@deffn {函数} struct.pack (format, v1, v2, ...)

返回一个 bytes 对象，其中包含根据格式字符串 @emph{format} 打包的值 @emph{v1}, @emph{v2}, ... 参数个数必须与格式字符串所要求的值完全匹配。
@end deffn

@geindex pack_into() (在 struct 模块中)
@anchor{library/struct struct pack_into}@anchor{199d}
@deffn {函数} struct.pack_into (format, buffer, offset, v1, v2, ...)

根据格式字符串 @emph{format} 打包 @emph{v1}, @emph{v2}, ... 等值并将打包的字节串写入可写缓冲区 @emph{buffer} 从 @emph{offset} 开始的位置。 请注意 @emph{offset} 是必需的参数。
@end deffn

@geindex unpack() (在 struct 模块中)
@anchor{library/struct struct unpack}@anchor{1468}
@deffn {函数} struct.unpack (format, buffer)

根据格式字符串 @emph{format} 从缓冲区 @emph{buffer} 解包（假定是由 @code{pack(format, ...)} 打包）。 结果为一个元组，即使其只包含一个条目。 缓冲区的字节大小必须匹配格式所要求的大小，如 @ref{110e,,calcsize()} 所示。
@end deffn

@geindex unpack_from() (在 struct 模块中)
@anchor{library/struct struct unpack_from}@anchor{199e}
@deffn {函数} struct.unpack_from (format, /, buffer, offset=0)

对 @emph{buffer} 从位置 @emph{offset} 开始根据格式字符串 @emph{format} 进行解包。 结果为一个元组，即使其中只包含一个条目。 缓冲区的字节大小从位置 @emph{offset} 开始必须至少为 @ref{110e,,calcsize()} 显示的格式所要求的大小。
@end deffn

@geindex iter_unpack() (在 struct 模块中)
@anchor{library/struct struct iter_unpack}@anchor{9c7}
@deffn {函数} struct.iter_unpack (format, buffer)

根据格式字符串 @emph{format} 以迭代方式从缓冲区 @emph{buffer} 解包。 此函数返回一个迭代器，它将从缓冲区读取相同大小的块直至其内容全部耗尽。 缓冲区的字节大小必须整数倍于格式所要求的大小，如 @ref{110e,,calcsize()} 所示。

每次迭代将产生一个如格式字符串所指定的元组。


3.4 新版功能.

@end deffn

@geindex calcsize() (在 struct 模块中)
@anchor{library/struct struct calcsize}@anchor{110e}
@deffn {函数} struct.calcsize (format)

返回与格式字符串 @emph{format} 相对应的结构的大小（亦即 @code{pack(format, ...)} 所产生的字节串对象的大小）。
@end deffn

@node 格式字符串,类<2>,函数和异常,struct --- 将字节串解读为打包的二进制数据
@anchor{library/struct format-strings}@anchor{199f}@anchor{library/struct struct-format-strings}@anchor{1999}
@subsubsection 格式字符串


格式字符串是用来在打包和解包数据时指定预期布局的机制。 它们使用指定被打包/解包数据类型的 @ref{19a0,,格式字符} 进行构建。 此外，还有一些特殊字符用来控制 @ref{199a,,字节顺序，大小和对齐方式}。

@menu
* 字节顺序，大小和对齐方式:: 
* 格式字符:: 
* 示例: 示例<3>. 

@end menu

@node 字节顺序，大小和对齐方式,格式字符,,格式字符串
@anchor{library/struct byte-order-size-and-alignment}@anchor{19a1}@anchor{library/struct struct-alignment}@anchor{199a}
@subsubsection 字节顺序，大小和对齐方式


默认情况下，C类型以机器的本机格式和字节顺序表示，并在必要时通过跳过填充字节进行正确对齐（根据C编译器使用的规则）。

@geindex @@ (at); in struct format strings
@geindex = (equals); in struct format strings
@geindex < (less); in struct format strings
@geindex > (greater); in struct format strings
@geindex ! (exclamation); in struct format strings

或者，根据下表，格式字符串的第一个字符可用于指示打包数据的字节顺序，大小和对齐方式：


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

字符

@tab

字节顺序

@tab

大小

@tab

对齐方式

@item

@code{@@}

@tab

按原字节

@tab

按原字节

@tab

按原字节

@item

@code{=}

@tab

按原字节

@tab

标准

@tab

无

@item

@code{<}

@tab

小端

@tab

标准

@tab

无

@item

@code{>}

@tab

大端

@tab

标准

@tab

无

@item

@code{!}

@tab

网络（=大端）

@tab

标准

@tab

无

@end multitable


如果第一个字符不是其中之一，则假定为 @code{'@@'} 。

本机字节顺序可能为大端或是小端，取决于主机系统的不同。 例如， Intel x86 和 AMD64 (x86-64) 是小端的；Motorola 68000 和 PowerPC G5 是大端的；ARM 和 Intel Itanium 具有可切换的字节顺序（双端）。 请使用 @code{sys.byteorder} 来检查你的系统字节顺序。

本机大小和对齐方式是使用 C 编译器的 @code{sizeof} 表达式来确定的。 这总是会与本机字节顺序相绑定。

标准大小仅取决于格式字符；请参阅 @ref{19a0,,格式字符} 部分中的表格。

请注意 @code{'@@'} 和 @code{'='} 之间的区别：两个都使用本机字节顺序，但后者的大小和对齐方式是标准化的。

形式 @code{'!'} 代表网络字节顺序总是使用在 IETF RFC 1700@footnote{https://tools.ietf.org/html/rfc1700} 中所定义的大端序。

没有什么方式能指定非本机字节顺序（强制字节对调）；请正确选择使用 @code{'<'} 或 @code{'>'}。

注释:


@enumerate 

@item 
填充只会在连续结构成员之间自动添加。 填充不会添加到已编码结构的开头和末尾。

@item 
当使用非本机大小和对齐方式即 '<', '>', '=', and '!' 时不会添加任何填充。

@item 
要将结构的末尾对齐到符合特定类型的对齐要求，请以该类型代码加重复计数的零作为格式结束。 参见 @ref{19a2,,示例}。
@end enumerate

@node 格式字符,示例<3>,字节顺序，大小和对齐方式,格式字符串
@anchor{library/struct format-characters}@anchor{19a0}@anchor{library/struct id1}@anchor{19a3}
@subsubsection 格式字符


格式字符具有以下含义；C 和 Python 值之间的按其指定类型的转换应当是相当明显的。 ‘标准大小’列是指当使用标准大小时以字节表示的已打包值大小；也就是当格式字符串以 @code{'<'}, @code{'>'}, @code{'!'} 或 @code{'='} 之一开头的情况。 当使用本机大小时，已打包值的大小取决于具体的平台。


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

格式

@tab

C 类型

@tab

Python 类型

@tab

标准大小

@tab

注释

@item

@code{x}

@tab

填充字节

@tab

无

@tab

@tab

@item

@code{c}

@tab

@code{char}

@tab

长度为 1 的字节串

@tab

1

@tab

@item

@code{b}

@tab

@code{signed char}

@tab

整数

@tab

1

@tab

(1), (2)

@item

@code{B}

@tab

@code{unsigned char}

@tab

整数

@tab

1

@tab

(2)

@item

@code{?}

@tab

@code{_Bool}

@tab

bool

@tab

1

@tab

(1)

@item

@code{h}

@tab

@code{short}

@tab

整数

@tab

2

@tab

(2)

@item

@code{H}

@tab

@code{unsigned short}

@tab

整数

@tab

2

@tab

(2)

@item

@code{i}

@tab

@code{int}

@tab

整数

@tab

4

@tab

(2)

@item

@code{I}

@tab

@code{unsigned int}

@tab

整数

@tab

4

@tab

(2)

@item

@code{l}

@tab

@code{long}

@tab

整数

@tab

4

@tab

(2)

@item

@code{L}

@tab

@code{unsigned long}

@tab

整数

@tab

4

@tab

(2)

@item

@code{q}

@tab

@code{long long}

@tab

整数

@tab

8

@tab

(2)

@item

@code{Q}

@tab

@code{unsigned long
long}

@tab

整数

@tab

8

@tab

(2)

@item

@code{n}

@tab

@code{ssize_t}

@tab

整数

@tab

@tab

(3)

@item

@code{N}

@tab

@code{size_t}

@tab

整数

@tab

@tab

(3)

@item

@code{e}

@tab

(6)

@tab

浮点数

@tab

2

@tab

(4)

@item

@code{f}

@tab

@code{float}

@tab

浮点数

@tab

4

@tab

(4)

@item

@code{d}

@tab

@code{double}

@tab

浮点数

@tab

8

@tab

(4)

@item

@code{s}

@tab

@code{char[]}

@tab

字节串

@tab

@tab

@item

@code{p}

@tab

@code{char[]}

@tab

字节串

@tab

@tab

@item

@code{P}

@tab

@code{void *}

@tab

整数

@tab

@tab

(5)

@end multitable



在 3.3 版更改: 增加了对 @code{'n'} 和 @code{'N'} 格式的支持



在 3.6 版更改: 添加了对 @code{'e'} 格式的支持。


注释:


@enumerate 

@item 
@geindex ? (question mark); in struct format strings

@code{'?'} 转换码对应于 C99 定义的 @code{_Bool} 类型。 如果此类型不可用，则使用 @code{char} 来模拟。 在标准模式下，它总是以一个字节表示。

@item 
当尝试使用任何整数转换码打包一个非整数时，如果该非整数具有 @ref{2c9,,__index__()} 方法，则会在打包之前调用该方法将参数转换为一个整数。


在 3.2 版更改: 增加了针对非整数使用 @ref{2c9,,__index__()} 方法的特性。


@item 
@code{'n'} 和 @code{'N'} 转换码仅对本机大小可用（选择为默认或使用 @code{'@@'} 字节顺序字符）。 对于标准大小，你可以使用适合你的应用的任何其他整数格式。

@item 
对于 @code{'f'}, @code{'d'} 和 @code{'e'} 转换码，打包表示形式将使用 IEEE 754 binary32, binary64 或 binary16 格式 (分别对应于 @code{'f'}, @code{'d'} 或 @code{'e'})，无论平台使用何种浮点格式。

@item 
@code{'P'} 格式字符仅对本机字节顺序可用（选择为默认或使用 @code{'@@'} 字节顺序字符）。 字节顺序字符 @code{'='} 选择使用基于主机系统的小端或大端排序。 struct 模块不会将其解读为本机排序，因此 @code{'P'} 格式将不可用。

@item 
IEEE 754 binary16 "半精度" 类型是在 IEEE 754 标准@footnote{https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008} 的 2008 修订版中引入的。 它包含一个符号位，5 个指数位和 11 个精度位（明确存储 10 位），可以完全精确地表示大致范围在 @code{6.1e-05} 和 @code{6.5e+04} 之间的数字。 此类型并不被 C 编译器广泛支持：在一台典型的机器上，可以使用 unsigned short 进行存储，但不会被用于数学运算。 请参阅维基百科页面 half-precision floating-point format@footnote{https://en.wikipedia.org/wiki/Half-precision_floating-point_format} 了解详情。
@end enumerate

格式字符之前可以带有整数重复计数。 例如，格式字符串 @code{'4h'} 的含义与 @code{'hhhh'} 完全相同。

格式之间的空白字符会被忽略；但是计数及其格式字符中不可有空白字符。

对于 @code{'s'} 格式字符，计数会被解析为字节的长度，而不是像其他格式字符那样的重复计数；例如，@code{'10s'} 表示一个 10 字节的字节串，而 @code{'10c'} 表示 10 个字符。 如果未给出计数，则默认值为 1。 对于打包操作，字节串会被适当地截断或填充空字节以符合要求。 对于解包操作，结果字节对象总是恰好具有指定数量的字节。 作为特殊情况，@code{'0s'} 表示一个空字符串（而 @code{'0c'} 表示 0 个字符）。

当使用某一种整数格式 (@code{'b'}, @code{'B'}, @code{'h'}, @code{'H'}, @code{'i'}, @code{'I'}, @code{'l'}, @code{'L'}, @code{'q'}, @code{'Q'}) 打包值 @code{x} 时，如果 @code{x} 在该格式的有效范围之外则将引发 @ref{d84,,struct.error}。


在 3.1 版更改: 在之前版本中，某些整数格式包装了超范围的值并会引发 @ref{15a,,DeprecationWarning} 而不是 @ref{d84,,struct.error}。


@code{'p'} 格式字符用于编码“Pascal 字符串”，即存储在由计数指定的 @emph{固定长度字节} 中的可变长度短字符串。 所存储的第一个字节为字符串长度或 255 中的较小值。 之后是字符串对应的字节。 如果传入 @ref{cde,,pack()} 的字符串过长（超过计数值减 1），则只有字符串前 @code{count-1} 个字节会被存储。 如果字符串短于 @code{count-1}，则会填充空字节以使得恰好使用了 count 个字节。 请注意对于 @ref{1468,,unpack()}，@code{'p'} 格式字符会消耗 @code{count} 个字节，但返回的字符串永远不会包含超过 255 个字节。

@geindex ? (question mark); in struct format strings

对于 @code{'?'} 格式字符，返回值为 @ref{59c,,True} 或 @ref{497,,False}。 在打包时将会使用参数对象的逻辑值。 以本机或标准 bool 类型表示的 0 或 1 将被打包，任何非零值在解包时将为 @code{True}。

@node 示例<3>,,格式字符,格式字符串
@anchor{library/struct examples}@anchor{19a4}@anchor{library/struct struct-examples}@anchor{19a2}
@subsubsection 示例


@cartouche
@quotation 注解 
所有示例都假定使用一台大端机器的本机字节顺序、大小和对齐方式。
@end quotation
@end cartouche

打包/解包三个整数的基础示例:

@example
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8
@end example

解包的字段可通过将它们赋值给变量或将结果包装为一个具名元组来命名:

@example
>>> record = b'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)
@end example

格式字符的顺序可能对大小产生影响，因为满足对齐要求所需的填充是不同的:

@example
>>> pack('ci', b'*', 0x12131415)
b'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, b'*')
b'\x12\x13\x14\x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5
@end example

以下格式 @code{'llh0l'} 指定在末尾有两个填充字节，假定 long 类型按 4 个字节的边界对齐:

@example
>>> pack('llh0l', 1, 2, 3)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
@end example

这仅当本机大小和对齐方式生效时才会起作用；标准大小和对齐方式并不会强制进行任何对齐。


@subsubheading 参见



@table @asis

@item 模块 @ref{6,,array}

被打包为二进制存储的同质数据。

@item 模块 @ref{13b,,xdrlib}

打包和解包 XDR 数据。
@end table


@node 类<2>,,格式字符串,struct --- 将字节串解读为打包的二进制数据
@anchor{library/struct classes}@anchor{19a5}@anchor{library/struct struct-objects}@anchor{19a6}
@subsubsection 类


@ref{f8,,struct} 模块还定义了以下类型：

@geindex Struct (struct 中的类)
@anchor{library/struct struct Struct}@anchor{199b}
@deffn {类} struct.Struct (format)

返回一个新的 Struct 对象，它会根据格式字符串 @emph{format} 来写入和读取二进制数据。 一次性地创建 Struct 对象并调用其方法相比使用同样的格式调用 @ref{f8,,struct} 函数更为高效，因为这样格式字符串只需被编译一次。

@cartouche
@quotation 注解 
传递给 @ref{199b,,Struct} 和模块层级函数的已编译版最新格式字符串会被缓存，因此只使用少量格式字符串的程序无需担心重用单独的 @ref{199b,,Struct} 实例。
@end quotation
@end cartouche

已编译的 Struct 对象支持以下方法和属性：

@geindex pack() (struct.Struct 方法)
@anchor{library/struct struct Struct pack}@anchor{19a7}
@deffn {方法} pack (v1, v2, ...)

等价于 @ref{cde,,pack()} 函数，使用了已编译的格式。 (@code{len(result)} 将等于 @ref{19a8,,size}。)
@end deffn

@geindex pack_into() (struct.Struct 方法)
@anchor{library/struct struct Struct pack_into}@anchor{19a9}
@deffn {方法} pack_into (buffer, offset, v1, v2, ...)

等价于 @ref{199d,,pack_into()} 函数，使用了已编译的格式。
@end deffn

@geindex unpack() (struct.Struct 方法)
@anchor{library/struct struct Struct unpack}@anchor{19aa}
@deffn {方法} unpack (buffer)

等价于 @ref{1468,,unpack()} 函数，使用了已编译的格式。 缓冲区的字节大小必须等于 @ref{19a8,,size}。
@end deffn

@geindex unpack_from() (struct.Struct 方法)
@anchor{library/struct struct Struct unpack_from}@anchor{19ab}
@deffn {方法} unpack_from (buffer, offset=0)

等价于 @ref{199e,,unpack_from()} 函数，使用了已编译的格式。 缓冲区的字节大小从位置 @emph{offset} 开始必须至少为 @ref{19a8,,size}。
@end deffn

@geindex iter_unpack() (struct.Struct 方法)
@anchor{library/struct struct Struct iter_unpack}@anchor{9c8}
@deffn {方法} iter_unpack (buffer)

等价于 @ref{9c7,,iter_unpack()} 函数，使用了已编译的格式。 缓冲区的大小必须为 @ref{19a8,,size} 的整数倍。


3.4 新版功能.

@end deffn

@geindex format (struct.Struct 属性)
@anchor{library/struct struct Struct format}@anchor{595}
@deffn {属性} format

用于构造此 Struct 对象的格式字符串。


在 3.7 版更改: 格式字符串类型现在是 @ref{206,,str} 而不再是 @ref{172,,bytes}。

@end deffn

@geindex size (struct.Struct 属性)
@anchor{library/struct struct Struct size}@anchor{19a8}
@deffn {属性} size

计算出对应于 @ref{5de,,format} 的结构大小（亦即 @ref{cde,,pack()} 方法所产生的字节串对象的大小）。
@end deffn
@end deffn

@node codecs --- 编解码器注册和相关基类,,struct --- 将字节串解读为打包的二进制数据,二进制数据服务
@anchor{library/codecs doc}@anchor{19ac}@anchor{library/codecs codecs-codec-registry-and-base-classes}@anchor{19ad}@anchor{library/codecs ietf-rfc-1700}@anchor{19ae}@anchor{library/codecs module-codecs}@anchor{1b}
@subsection @code{codecs} --- 编解码器注册和相关基类


@geindex codecs (模块)

@strong{源代码：} Lib/codecs.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/codecs.py}

@geindex Unicode
@geindex Codecs
@geindex Codecs; encode
@geindex Codecs; decode
@geindex streams
@geindex stackable; streams


__________________________________________________________________


这个模块定义了标准 Python 编解码器（编码器和解码器）的基类并提供对内部 Python 编解码器注册表的访问，该注册表负责管理编解码器和错误处理的查找过程。 大多数标准编解码器都属于 @ref{1761,,文本编码格式}，它们可将文本编码为字节串（以及将字节串解码为文本），但也提供了一些将文本编码为文本，以及将字节串编码为字节串的编解码器。 自定义编解码器可以在任意类型间进行编码和解码，但某些模块特性被限制为仅适用于 @ref{1761,,文本编码格式} 或将数据编码为 @ref{172,,bytes} 的编解码器。

该模块定义了以下用于使用任何编解码器进行编码和解码的函数：

@geindex encode() (在 codecs 模块中)
@anchor{library/codecs codecs encode}@anchor{8f9}
@deffn {函数} codecs.encode (obj, encoding='utf-8', errors='strict')

使用为 @emph{encoding} 注册的编解码器对 @emph{obj} 进行编码。

可以给定 @emph{Errors} 以设置所需要的错误处理方案。 默认的错误处理方案 @code{'strict'} 表示编码错误将引发 @ref{16d,,ValueError} (或更特定编解码器相关的子类，例如 @ref{331,,UnicodeEncodeError})。 请参阅 @ref{19af,,编解码器基类} 了解有关编解码器错误处理的更多信息。
@end deffn

@geindex decode() (在 codecs 模块中)
@anchor{library/codecs codecs decode}@anchor{8fa}
@deffn {函数} codecs.decode (obj, encoding='utf-8', errors='strict')

使用为 @emph{encoding} 注册的编解码器对 @emph{obj} 进行解码。

可以给定 @emph{Errors} 以设置所需要的错误处理方案。 默认的错误处理方案 @code{'strict'} 表示编码错误将引发 @ref{16d,,ValueError} (或更特定编解码器相关的子类，例如 @ref{332,,UnicodeDecodeError})。 请参阅 @ref{19af,,编解码器基类} 了解有关编解码器错误处理的更多信息。
@end deffn

每种编解码器的完整细节也可以直接查找获取：

@geindex lookup() (在 codecs 模块中)
@anchor{library/codecs codecs lookup}@anchor{239}
@deffn {函数} codecs.lookup (encoding)

在 Python 编解码器注册表中查找编解码器信息，并返回一个 @ref{19b0,,CodecInfo} 对象，其定义见下文。

首先将会在注册表缓存中查找编码，如果未找到，则会扫描注册的搜索函数列表。 如果没有找到 @ref{19b0,,CodecInfo} 对象，则将引发 @ref{17c1,,LookupError}。 否则，@ref{19b0,,CodecInfo} 对象将被存入缓存并返回给调用者。
@end deffn

@geindex CodecInfo (codecs 中的类)
@anchor{library/codecs codecs CodecInfo}@anchor{19b0}
@deffn {类} codecs.CodecInfo (encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)

查找编解码器注册表所得到的编解码器细节信息。 构造器参数将保存为同名的属性：

@geindex name (codecs.CodecInfo 属性)
@anchor{library/codecs codecs CodecInfo name}@anchor{19b1}
@deffn {属性} name

编码名称
@end deffn

@geindex encode (codecs.CodecInfo 属性)
@geindex decode (codecs.CodecInfo 属性)
@anchor{library/codecs codecs CodecInfo encode}@anchor{19b2}
@deffn {属性} encode
@anchor{library/codecs codecs CodecInfo decode}@anchor{19b3}
@deffnx {属性} decode

无状态的编码和解码函数。 它们必须是具有与 Codec 的 @ref{19b4,,encode()} 和 @ref{19b5,,decode()} 方法相同接口的函数或方法 (参见 @ref{19b6,,Codec 接口})。 这些函数或方法应当工作于无状态的模式。
@end deffn

@geindex incrementalencoder (codecs.CodecInfo 属性)
@geindex incrementaldecoder (codecs.CodecInfo 属性)
@anchor{library/codecs codecs CodecInfo incrementalencoder}@anchor{19b7}
@deffn {属性} incrementalencoder
@anchor{library/codecs codecs CodecInfo incrementaldecoder}@anchor{19b8}
@deffnx {属性} incrementaldecoder

增量式的编码器和解码器类或工厂函数。 这些函数必须分别提供由基类 @ref{19b9,,IncrementalEncoder} 和 @ref{19ba,,IncrementalDecoder} 所定义的接口。 增量式编解码器可以保持状态。
@end deffn

@geindex streamwriter (codecs.CodecInfo 属性)
@geindex streamreader (codecs.CodecInfo 属性)
@anchor{library/codecs codecs CodecInfo streamwriter}@anchor{19bb}
@deffn {属性} streamwriter
@anchor{library/codecs codecs CodecInfo streamreader}@anchor{19bc}
@deffnx {属性} streamreader

流式写入器和读取器类或工厂函数。 这些函数必须分别提供由基类 @ref{19bd,,StreamWriter} 和 @ref{19be,,StreamReader} 所定义的接口。 流式编解码器可以保持状态。
@end deffn
@end deffn

为了简化对各种编解码器组件的访问，本模块提供了以下附加函数，它们使用 @ref{239,,lookup()} 来执行编解码器查找：

@geindex getencoder() (在 codecs 模块中)
@anchor{library/codecs codecs getencoder}@anchor{19bf}
@deffn {函数} codecs.getencoder (encoding)

查找给定编码的编解码器并返回其编码器函数。

在编码无法找到时将引发 @ref{17c1,,LookupError}。
@end deffn

@geindex getdecoder() (在 codecs 模块中)
@anchor{library/codecs codecs getdecoder}@anchor{19c0}
@deffn {函数} codecs.getdecoder (encoding)

查找给定编码的编解码器并返回其解码器函数。

在编码无法找到时将引发 @ref{17c1,,LookupError}。
@end deffn

@geindex getincrementalencoder() (在 codecs 模块中)
@anchor{library/codecs codecs getincrementalencoder}@anchor{19c1}
@deffn {函数} codecs.getincrementalencoder (encoding)

查找给定编码的编解码器并返回其增量式编码器类或工厂函数。

在编码无法找到或编解码器不支持增量式编码器时将引发 @ref{17c1,,LookupError}。
@end deffn

@geindex getincrementaldecoder() (在 codecs 模块中)
@anchor{library/codecs codecs getincrementaldecoder}@anchor{19c2}
@deffn {函数} codecs.getincrementaldecoder (encoding)

查找给定编码的编解码器并返回其增量式解码器类或工厂函数。

在编码无法找到或编解码器不支持增量式解码器时将引发 @ref{17c1,,LookupError}。
@end deffn

@geindex getreader() (在 codecs 模块中)
@anchor{library/codecs codecs getreader}@anchor{19c3}
@deffn {函数} codecs.getreader (encoding)

查找给定编码的编解码器并返回其 @ref{19be,,StreamReader} 类或工厂函数。

在编码无法找到时将引发 @ref{17c1,,LookupError}。
@end deffn

@geindex getwriter() (在 codecs 模块中)
@anchor{library/codecs codecs getwriter}@anchor{19c4}
@deffn {函数} codecs.getwriter (encoding)

查找给定编码的编解码器并返回其 @ref{19bd,,StreamWriter} 类或工厂函数。

在编码无法找到时将引发 @ref{17c1,,LookupError}。
@end deffn

自定义编解码器的启用是通过注册适当的编解码器搜索函数：

@geindex register() (在 codecs 模块中)
@anchor{library/codecs codecs register}@anchor{19c5}
@deffn {函数} codecs.register (search_function)

注册一个编解码器搜索函数。 搜索函数预期接收一个参数，即全部以小写字母表示的编码格式名称，其中中连字符和空格会被转换为下划线，并返回一个 @ref{19b0,,CodecInfo} 对象。 在搜索函数无法找到给定编码格式的情况下，它应当返回 @code{None}。


在 3.9 版更改: 连字符和空格会被转换为下划线。


@cartouche
@quotation 注解 
搜索函数的注册目前是不可逆的，这在某些情况下可能导致问题，例如单元测试或模块重载等。
@end quotation
@end cartouche
@end deffn

虽然内置的 @ref{16f,,open()} 和相关联的 @ref{a1,,io} 模块是操作已编码文本文件的推荐方式，但本模块也提供了额外的工具函数和类，允许在操作二进制文件时使用更多各类的编解码器：

@geindex open() (在 codecs 模块中)
@anchor{library/codecs codecs open}@anchor{110c}
@deffn {函数} codecs.open (filename, mode='r', encoding=None, errors='strict', buffering=-1)

使用给定的 @emph{mode} 打开已编码的文件并返回一个 @ref{19c6,,StreamReaderWriter} 的实例，提供透明的编码/解码。 默认的文件模式为 @code{'r'}，表示以读取模式打开文件。

@cartouche
@quotation 注解 
下层的已编码文件总是以二进制模式打开。 在读取和写入时不会自动执行 @code{'\n'} 的转换。 @emph{mode} 参数可以是内置 @ref{16f,,open()} 函数所接受的任意二进制模式；@code{'b'} 会被自动添加。
@end quotation
@end cartouche

@emph{encoding} 指定文件所要使用的编码格式。 允许任何编码为字节串或从字节串解码的编码格式，而文件方法所支持的数据类型则取决于所使用的编解码器。

可以指定 @emph{errors} 来定义错误处理方案。 默认值 @code{'strict'} 表示在出现编码错误时引发 @ref{16d,,ValueError}。

@emph{buffering} 的含义与内置 @ref{16f,,open()} 函数中的相同。 默认值 -1 表示将使用默认的缓冲区大小。
@end deffn

@geindex EncodedFile() (在 codecs 模块中)
@anchor{library/codecs codecs EncodedFile}@anchor{19c7}
@deffn {函数} codecs.EncodedFile (file, data_encoding, file_encoding=None, errors='strict')

返回一个 @ref{1151,,StreamRecoder} 实例，它提供了 @emph{file} 的透明转码包装版本。 当包装版本被关闭时原始文件也会被关闭。

写入已包装文件的数据会根据给定的 @emph{data_encoding} 解码，然后以使用 @emph{file_encoding} 的字节形式写入原始文件。 从原始文件读取的字节串将根据 @emph{file_encoding} 解码，其结果将使用 @emph{data_encoding} 进行编码。

如果 @emph{file_encoding} 未给定，则默认为 @emph{data_encoding}。

可以指定 @emph{errors} 来定义错误处理方案。 默认值 @code{'strict'} 表示在出现编码错误时引发 @ref{16d,,ValueError}。
@end deffn

@geindex iterencode() (在 codecs 模块中)
@anchor{library/codecs codecs iterencode}@anchor{19c8}
@deffn {函数} codecs.iterencode (iterator, encoding, errors='strict', **kwargs)

使用增量式编码器通过迭代来编码由 @emph{iterator} 所提供的输入。 此函数属于 @ref{a8c,,generator}。 @emph{errors} 参数（以及任何其他关键字参数）会被传递给增量式编码器。

此函数要求编解码器接受 @ref{206,,str} 对象形式的文本进行编码。 因此它不支持字节到字节的编码器，例如 @code{base64_codec}。
@end deffn

@geindex iterdecode() (在 codecs 模块中)
@anchor{library/codecs codecs iterdecode}@anchor{19c9}
@deffn {函数} codecs.iterdecode (iterator, encoding, errors='strict', **kwargs)

使用增量式解码器通过迭代来解码由 @emph{iterator} 所提供的输入。 此函数属于 @ref{a8c,,generator}。 @emph{errors} 参数（以及任何其他关键字参数）会被传递给增量式解码器。

此函数要求编解码器接受 @ref{172,,bytes} 对象进行解码。 因此它不支持文本到文本的编码器，例如 @code{rot_13}，但是 @code{rot_13} 可以通过同样效果的 @ref{19c8,,iterencode()} 来使用。
@end deffn

本模块还提供了以下常量，适用于读取和写入依赖于平台的文件：

@geindex BOM() (在 codecs 模块中)
@geindex BOM_BE() (在 codecs 模块中)
@geindex BOM_LE() (在 codecs 模块中)
@geindex BOM_UTF8() (在 codecs 模块中)
@geindex BOM_UTF16() (在 codecs 模块中)
@geindex BOM_UTF16_BE() (在 codecs 模块中)
@geindex BOM_UTF16_LE() (在 codecs 模块中)
@geindex BOM_UTF32() (在 codecs 模块中)
@geindex BOM_UTF32_BE() (在 codecs 模块中)
@geindex BOM_UTF32_LE() (在 codecs 模块中)
@anchor{library/codecs codecs BOM}@anchor{19ca}
@deffn {数据} codecs.BOM
@anchor{library/codecs codecs BOM_BE}@anchor{19cb}
@deffnx {数据} codecs.BOM_BE
@anchor{library/codecs codecs BOM_LE}@anchor{19cc}
@deffnx {数据} codecs.BOM_LE
@anchor{library/codecs codecs BOM_UTF8}@anchor{19cd}
@deffnx {数据} codecs.BOM_UTF8
@anchor{library/codecs codecs BOM_UTF16}@anchor{19ce}
@deffnx {数据} codecs.BOM_UTF16
@anchor{library/codecs codecs BOM_UTF16_BE}@anchor{19cf}
@deffnx {数据} codecs.BOM_UTF16_BE
@anchor{library/codecs codecs BOM_UTF16_LE}@anchor{19d0}
@deffnx {数据} codecs.BOM_UTF16_LE
@anchor{library/codecs codecs BOM_UTF32}@anchor{19d1}
@deffnx {数据} codecs.BOM_UTF32
@anchor{library/codecs codecs BOM_UTF32_BE}@anchor{19d2}
@deffnx {数据} codecs.BOM_UTF32_BE
@anchor{library/codecs codecs BOM_UTF32_LE}@anchor{19d3}
@deffnx {数据} codecs.BOM_UTF32_LE

这些常量定义了多种字节序列，即一些编码格式的 Unicode 字节顺序标记（BOM）。 它们在 UTF-16 和 UTF-32 数据流中被用以指明所使用的字节顺序，并在 UTF-8 中被用作 Unicode 签名。 @ref{19ce,,BOM_UTF16} 是 @ref{19cf,,BOM_UTF16_BE} 或 @ref{19d0,,BOM_UTF16_LE}，具体取决于平台的本机字节顺序，@ref{19ca,,BOM} 是 @ref{19ce,,BOM_UTF16} 的别名, @ref{19cc,,BOM_LE} 是 @ref{19d0,,BOM_UTF16_LE} 的别名，@ref{19cb,,BOM_BE} 是 @ref{19cf,,BOM_UTF16_BE} 的别名。 其他序列则表示 UTF-8 和 UTF-32 编码格式中的 BOM。
@end deffn

@menu
* 编解码器基类:: 
* 编码格式与 Unicode:: 
* 标准编码:: 
* Python 专属的编码格式:: 
* encodings.idna: encodings idna --- 应用程序中的国际化域名. 应用程序中的国际化域名
* encodings.mbcs: encodings mbcs --- Windows ANSI代码页. Windows ANSI代码页
* encodings.utf_8_sig: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器. 带BOM签名的UTF-8编解码器

@end menu

@node 编解码器基类,编码格式与 Unicode,,codecs --- 编解码器注册和相关基类
@anchor{library/codecs codec-base-classes}@anchor{19af}@anchor{library/codecs id1}@anchor{19d4}
@subsubsection 编解码器基类


@ref{1b,,codecs} 模块定义了一系列基类用来定义配合编解码器对象进行工作的接口，并且也可用作定制编解码器实现的基础。

每种编解码器必须定义四个接口以便用作 Python 中的编解码器：无状态编码器、无状态解码器、流读取器和流写入器。 流读取器和写入器通常会重用无状态编码器/解码器来实现文件协议。 编解码器作者还需要定义编解码器将如何处理编码和解码错误。
@anchor{library/codecs surrogateescape}@anchor{19d5}
@menu
* 错误处理方案:: 
* 无状态的编码和解码:: 
* 增量式的编码和解码:: 
* 流式的编码和解码:: 

@end menu

@node 错误处理方案,无状态的编码和解码,,编解码器基类
@anchor{library/codecs error-handlers}@anchor{f7d}@anchor{library/codecs id2}@anchor{19d6}
@subsubsection 错误处理方案


为了简化和标准化错误处理，编解码器可以通过接受 @emph{errors} 字符串参数来实现不同的错误处理方案:

@example
>>> 'German ß, ♬'.encode(encoding='ascii', errors='backslashreplace')
b'German \\xdf, \\u266c'
>>> 'German ß, ♬'.encode(encoding='ascii', errors='xmlcharrefreplace')
b'German &#223;, &#9836;'
@end example

@geindex strict; error handler's name
@geindex ignore; error handler's name
@geindex replace; error handler's name
@geindex backslashreplace; error handler's name
@geindex surrogateescape; error handler's name
@geindex ? (question mark); replacement character
@geindex \ (backslash); escape sequence
@geindex \x; escape sequence
@geindex \u; escape sequence
@geindex \U; escape sequence

以下错误处理句柄可以用于所有的 Python @ref{78c,,标准编码} 编解码器:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

含义

@item

@code{'strict'}

@tab

引发 @ref{d0b,,UnicodeError} (或其子类)，这是默认的方案。 在 @ref{19d7,,strict_errors()} 中实现。

@item

@code{'ignore'}

@tab

忽略错误格式的数据并且不加进一步通知就继续执行。 在 @ref{19d8,,ignore_errors()} 中实现。

@item

@code{'replace'}

@tab

用一个替代标记来替换。 在编码时，使用 @code{?} (ASCII 字符)。 在解码时，使用 @code{�} (U+FFFD，官方的 REPLACEMENT CHARACTER)。 在 @ref{19d9,,replace_errors()} 中实现。

@item

@code{'backslashreplace'}

@tab

用反斜杠转义序列来替换。 在编码时，使用格式为 @code{\xhh} @code{\uxxxx} @code{\Uxxxxxxxx} 的 Unicode 码位十六进制表示形式。 在解码时，使用格式为 @code{\xhh} 的字节值十六进制表示形式。 在 @ref{19da,,backslashreplace_errors()} 中实现。

@item

@code{'surrogateescape'}

@tab

在解码时，将字节替换为 @code{U+DC80} 至 @code{U+DCFF} 范围内的单个代理代码。 当在编码数据时使用 @code{'surrogateescape'} 错误处理方案时，此代理将被转换回相同的字节。 （请参阅 
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383} 了解详情。）

@end multitable


@geindex xmlcharrefreplace; error handler's name
@geindex namereplace; error handler's name
@geindex \N; escape sequence

下列错误处理句柄仅在编码时适用（在 @ref{1761,,文本编码格式} 类别以内）:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

含义

@item

@code{'xmlcharrefreplace'}

@tab

用 XML/HTML 数字字符引用来替换，即格式为 @code{&#num;} 的 Unicode 码位十进制表达形式。 在 @ref{19db,,xmlcharrefreplace_errors()} 中实现。

@item

@code{'namereplace'}

@tab

用 @code{\N@{...@}} 转义序列来替换，出现在花括号中的是来自 Unicode 字符数据库的 Name 属性。 在 @ref{19dc,,namereplace_errors()} 中实现。

@end multitable


@geindex surrogatepass; error handler's name

此外，以下错误处理方案被专门用于指定的编解码器：


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

编解码器

@tab

含义

@item

@code{'surrogatepass'}

@tab

utf-8, utf-16, utf-32,
utf-16-be, utf-16-le,
utf-32-be, utf-32-le

@tab

允许将代理码位 (@code{U+D800} - @code{U+DFFF}) 作为正常码位来编码和解码。 否则这些编解码器会将 @ref{206,,str} 中出现的代理码位视为错误。

@end multitable



3.1 新版功能: @code{'surrogateescape'} 和 @code{'surrogatepass'} 错误处理方案。



在 3.4 版更改: @code{'surrogatepass'} 错误处理器现在可适用于 utf-16* 和 utf-32* 编解码器。



3.5 新版功能: @code{'namereplace'} 错误处理方案。



在 3.5 版更改: @code{'backslashreplace'} 错误处理器现在可适用于解码和转码。


允许的值集合可以通过注册新命名的错误处理方案来扩展：

@geindex register_error() (在 codecs 模块中)
@anchor{library/codecs codecs register_error}@anchor{ec1}
@deffn {函数} codecs.register_error (name, error_handler)

在名称 @emph{name} 之下注册错误处理函数 @emph{error_handler}。 当 @emph{name} 被指定为错误形参时，@emph{error_handler} 参数所指定的对象将在编码和解码期间发生错误的情况下被调用，

对于编码操作，将会调用 @emph{error_handler} 并传入一个 @ref{331,,UnicodeEncodeError} 实例，其中包含有关错误位置的信息。 错误处理程序必须引发此异常或别的异常，或者也可以返回一个元组，其中包含输入的不可编码部分的替换对象，以及应当继续进行编码的位置。 替换对象可以为 @ref{206,,str} 或 @ref{172,,bytes} 类型。 如果替换对象为字节串，编码器将简单地将其复制到输出缓冲区。 如果替换对象为字符串，编码器将对替换对象进行编码。 对原始输入的编码操作会在指定位置继续进行。 负的位置值将被视为相对于输入字符串的末尾。 如果结果位置超出范围则将引发 @ref{f3d,,IndexError}。

解码和转换的做法很相似，不同之处在于将把 @ref{332,,UnicodeDecodeError} 或 @ref{1896,,UnicodeTranslateError} 传给处理程序，并且来自错误处理程序的替换对象将被直接放入输出。
@end deffn

之前注册的错误处理方案（包括标准错误处理方案）可通过名称进行查找：

@geindex lookup_error() (在 codecs 模块中)
@anchor{library/codecs codecs lookup_error}@anchor{ec2}
@deffn {函数} codecs.lookup_error (name)

返回之前在名称 @emph{name} 之下注册的错误处理方案。

在处理方案无法找到时将引发 @ref{17c1,,LookupError}。
@end deffn

以下标准错误处理方案也可通过模块层级函数的方式来使用：

@geindex strict_errors() (在 codecs 模块中)
@anchor{library/codecs codecs strict_errors}@anchor{19d7}
@deffn {函数} codecs.strict_errors (exception)

实现了 @code{'strict'} 错误处理。

每个编码或解码错误都将引发 @ref{d0b,,UnicodeError}。
@end deffn

@geindex ignore_errors() (在 codecs 模块中)
@anchor{library/codecs codecs ignore_errors}@anchor{19d8}
@deffn {函数} codecs.ignore_errors (exception)

实现了 @code{'ignore'} 错误处理。

错误格式的数据会被忽略；编码或解码将继续执行而不再通知。
@end deffn

@geindex replace_errors() (在 codecs 模块中)
@anchor{library/codecs codecs replace_errors}@anchor{19d9}
@deffn {函数} codecs.replace_errors (exception)

实现了 @code{'replace'} 错误处理。

替换 @code{?} (ASCII 字符) 表示编码错误或者 @code{�} (U+FFFD，官方的 REPLACEMENT CHARACTER) 表示解码错误。
@end deffn

@geindex backslashreplace_errors() (在 codecs 模块中)
@anchor{library/codecs codecs backslashreplace_errors}@anchor{19da}
@deffn {函数} codecs.backslashreplace_errors (exception)

实现了 @code{'backslashreplace'} 错误处理。

错误格式的数据会用反斜杠转义序列来替换。 在编码时，使用格式为 @code{\xhh} @code{\uxxxx} @code{\Uxxxxxxxx} 的 Unicode 码位十六进制表示形式。 在解码时，使用格式为 @code{\xhh} 的字节值十六进制表示形式。


在 3.5 版更改: 适用于解码和转码。

@end deffn

@geindex xmlcharrefreplace_errors() (在 codecs 模块中)
@anchor{library/codecs codecs xmlcharrefreplace_errors}@anchor{19db}
@deffn {函数} codecs.xmlcharrefreplace_errors (exception)

实现 @code{'xmlcharrefreplace'} 错误处理（仅限 @ref{1761,,text encoding} 范围内的编码操作）。

不可编码的字符会被替换为适当的 XML/HTML 数值字符引用，即格式为 @code{&#num;} 的十进制形式 Unicode 码位。
@end deffn

@geindex namereplace_errors() (在 codecs 模块中)
@anchor{library/codecs codecs namereplace_errors}@anchor{19dc}
@deffn {函数} codecs.namereplace_errors (exception)

实现 @code{'namereplace'} 错误处理（仅限 @ref{1761,,text encoding} 范围内的编码操作）。

不可编码的字符会被替换为 @code{\N@{...@}} 转义序列。 出现在花括号内的字符集合是来自于 Unicode 字符数据库的 Name 属性。 例如，德语小写字母 @code{'ß'} 将被转换为字符序列 @code{\N@{LATIN SMALL LETTER SHARP S@}}。


3.5 新版功能.

@end deffn

@node 无状态的编码和解码,增量式的编码和解码,错误处理方案,编解码器基类
@anchor{library/codecs codec-objects}@anchor{19b6}@anchor{library/codecs stateless-encoding-and-decoding}@anchor{19dd}
@subsubsection 无状态的编码和解码


基本 @code{Codec} 类定义了这些方法，同时还定义了无状态编码器和解码器的函数接口：

@geindex encode() (codecs.Codec 方法)
@anchor{library/codecs codecs Codec encode}@anchor{19b4}
@deffn {方法} Codec.encode (input, errors='strict')

编码 @emph{input} 对象并返回一个元组 (输出对象, 消耗长度)。 例如，@ref{1761,,text encoding} 会使用特定的字符集编码格式 (例如 @code{cp1252} 或 @code{iso-8859-1}) 将字符串转换为字节串对象。

@emph{errors} 参数定义了要应用的错误处理方案。 默认为 @code{'strict'} 处理方案。

此方法不一定会在 @code{Codec} 实例中保存状态。 可使用必须保存状态的 @ref{19bd,,StreamWriter} 作为编解码器以便高效地进行编码。

编码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象。
@end deffn

@geindex decode() (codecs.Codec 方法)
@anchor{library/codecs codecs Codec decode}@anchor{19b5}
@deffn {方法} Codec.decode (input, errors='strict')

解码 @emph{input} 对象并返回一个元组 (输出对象, 消耗长度)。 例如，@ref{1761,,text encoding} 的解码操作会使用特定的字符集编码格式将字节串对象转换为字符串对象。

对于文本编码格式和字节到字节编解码器，@emph{input} 必须为一个字节串对象或提供了只读缓冲区接口的对象 -- 例如，缓冲区对象和映射到内存的文件。

@emph{errors} 参数定义了要应用的错误处理方案。 默认为 @code{'strict'} 处理方案。

此方法不一定会在 @code{Codec} 实例中保存状态。 可使用必须保存状态的 @ref{19be,,StreamReader} 作为编解码器以便高效地进行解码。

解码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象。
@end deffn

@node 增量式的编码和解码,流式的编码和解码,无状态的编码和解码,编解码器基类
@anchor{library/codecs incremental-encoding-and-decoding}@anchor{19de}
@subsubsection 增量式的编码和解码


@ref{19b9,,IncrementalEncoder} 和 @ref{19ba,,IncrementalDecoder} 类提供了增量式编码和解码的基本接口。 对输入的编码/解码不是通过对无状态编码器/解码器的一次调用，而是通过对增量式编码器/解码器的 @ref{19df,,encode()}/@ref{19e0,,decode()} 方法的多次调用。 增量式编码器/解码器会在方法调用期间跟踪编码/解码过程。

调用 @ref{19df,,encode()}/@ref{19e0,,decode()} 方法后的全部输出相当于将所有通过无状态编码器/解码器进行编码/解码的单个输入连接在一起所得到的输出。

@menu
* IncrementalEncoder 对象:: 
* IncrementalDecoder 对象:: 

@end menu

@node IncrementalEncoder 对象,IncrementalDecoder 对象,,增量式的编码和解码
@anchor{library/codecs incremental-encoder-objects}@anchor{19e1}@anchor{library/codecs incrementalencoder-objects}@anchor{19e2}
@subsubsection IncrementalEncoder 对象


@ref{19b9,,IncrementalEncoder} 类用来对一个输入进行分步编码。 它定义了以下方法，每个增量式编码器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

@geindex IncrementalEncoder (codecs 中的类)
@anchor{library/codecs codecs IncrementalEncoder}@anchor{19b9}
@deffn {类} codecs.IncrementalEncoder (errors='strict')

@ref{19b9,,IncrementalEncoder} 实例的构造器。

所有增量式编码器必须提供此构造器接口。 它们可以自由地添加额外的关键字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

@ref{19b9,,IncrementalEncoder} 可以通过提供 @emph{errors} 关键字参数来实现不同的错误处理方案。 可用的值请参阅 @ref{f7d,,错误处理方案}。

@emph{errors} 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在 @ref{19b9,,IncrementalEncoder} 对象的生命期内在不同的错误处理策略之间进行切换。

@geindex encode() (codecs.IncrementalEncoder 方法)
@anchor{library/codecs codecs IncrementalEncoder encode}@anchor{19df}
@deffn {方法} encode (object, final=False)

编码 @emph{object} (会将编码器的当前状态纳入考虑) 并返回已编码的结果对象。 如果这是对 @ref{8f9,,encode()} 的最终调用则 @emph{final} 必须为真值（默认为假值）。
@end deffn

@geindex reset() (codecs.IncrementalEncoder 方法)
@anchor{library/codecs codecs IncrementalEncoder reset}@anchor{19e3}
@deffn {方法} reset ()

将编码器重置为初始状态。 输出将被丢弃：调用 @code{.encode(object, final=True)}，在必要时传入一个空字节串或字符串，重置编码器并得到输出。
@end deffn

@geindex getstate() (codecs.IncrementalEncoder 方法)
@anchor{library/codecs codecs IncrementalEncoder getstate}@anchor{19e4}
@deffn {方法} getstate ()

返回编码器的当前状态，该值必须为一个整数。 实现应当确保 @code{0} 是最常见的状态。 （比整数更复杂的状态表示可以通过编组/选择状态并将结果字符串的字节数据编码为整数来转换为一个整数值）。
@end deffn

@geindex setstate() (codecs.IncrementalEncoder 方法)
@anchor{library/codecs codecs IncrementalEncoder setstate}@anchor{19e5}
@deffn {方法} setstate (state)

将编码器的状态设为 @emph{state}。 @emph{state} 必须为 @ref{19e4,,getstate()} 所返回的一个编码器状态。
@end deffn
@end deffn

@node IncrementalDecoder 对象,,IncrementalEncoder 对象,增量式的编码和解码
@anchor{library/codecs incremental-decoder-objects}@anchor{19e6}@anchor{library/codecs incrementaldecoder-objects}@anchor{19e7}
@subsubsection IncrementalDecoder 对象


@ref{19ba,,IncrementalDecoder} 类用来对一个输入进行分步解码。 它定义了以下方法，每个增量式解码器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

@geindex IncrementalDecoder (codecs 中的类)
@anchor{library/codecs codecs IncrementalDecoder}@anchor{19ba}
@deffn {类} codecs.IncrementalDecoder (errors='strict')

@ref{19ba,,IncrementalDecoder} 实例的构造器。

所有增量式解码器必须提供此构造器接口。 它们可以自由地添加额外的关键字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

@ref{19ba,,IncrementalDecoder} 可以通过提供 @emph{errors} 关键字参数来实现不同的错误处理方案。 可用的值请参阅 @ref{f7d,,错误处理方案}。

@emph{errors} 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在 @ref{19ba,,IncrementalDecoder} 对象的生命期内在不同的错误处理策略之间进行切换。

@geindex decode() (codecs.IncrementalDecoder 方法)
@anchor{library/codecs codecs IncrementalDecoder decode}@anchor{19e0}
@deffn {方法} decode (object, final=False)

解码 @emph{object} (会将解码器的当前状态纳入考虑) 并返回已解码的结果对象。 如果这是对 @ref{8fa,,decode()} 的最终调用则 @emph{final} 必须为真值（默认为假值）。 如果 @emph{final} 为真值则解码器必须对输入进行完全解码并且必须 刷新所有缓冲区。 如果这无法做到（例如由于在输入结束时字节串序列不完整）则它必须像在无状态的情况下那样初始化错误处理（这可能引发一个异常）。
@end deffn

@geindex reset() (codecs.IncrementalDecoder 方法)
@anchor{library/codecs codecs IncrementalDecoder reset}@anchor{19e8}
@deffn {方法} reset ()

将解码器重置为初始状态。
@end deffn

@geindex getstate() (codecs.IncrementalDecoder 方法)
@anchor{library/codecs codecs IncrementalDecoder getstate}@anchor{19e9}
@deffn {方法} getstate ()

返回解码器的当前状态。 这必须为一个二元组，第一项必须是包含尚未解码的输入的缓冲区。 第二项必须为一个整数，可以表示附加状态信息。 （实现应当确保 @code{0} 是最常见的附加状态信息。） 如果此附加状态信息为 @code{0} 则必须可以将解码器设为没有已缓冲输入并且以 @code{0} 作为附加状态信息，以便将先前已缓冲的输入馈送到解码器使其返回到先前的状态而不产生任何输出。 （比整数更复杂的附加状态信息可以通过编组/选择状态信息并将结果字符串的字节数据编码为整数来转换为一个整数值。）
@end deffn

@geindex setstate() (codecs.IncrementalDecoder 方法)
@anchor{library/codecs codecs IncrementalDecoder setstate}@anchor{19ea}
@deffn {方法} setstate (state)

将解码器的状态设为 @emph{state}。 @emph{state} 必须为 @ref{19e9,,getstate()} 所返回的一个解码器状态。
@end deffn
@end deffn

@node 流式的编码和解码,,增量式的编码和解码,编解码器基类
@anchor{library/codecs stream-encoding-and-decoding}@anchor{19eb}
@subsubsection 流式的编码和解码


@ref{19bd,,StreamWriter} 和 @ref{19be,,StreamReader} 类提供了一些泛用工作接口，可被用来非常方便地实现新的编码格式子模块。 请参阅 @code{encodings.utf_8} 中的示例了解如何做到这一点。

@menu
* StreamWriter 对象:: 
* StreamReader 对象:: 
* StreamReaderWriter 对象:: 
* StreamRecoder 对象:: 

@end menu

@node StreamWriter 对象,StreamReader 对象,,流式的编码和解码
@anchor{library/codecs stream-writer-objects}@anchor{19ec}@anchor{library/codecs streamwriter-objects}@anchor{19ed}
@subsubsection StreamWriter 对象


@ref{19bd,,StreamWriter} 类是 @code{Codec} 的子类，它定义了以下方法，每个流式写入器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

@geindex StreamWriter (codecs 中的类)
@anchor{library/codecs codecs StreamWriter}@anchor{19bd}
@deffn {类} codecs.StreamWriter (stream, errors='strict')

@ref{19bd,,StreamWriter} 实例的构造器。

所有流式写入器必须提供此构造器接口。 它们可以自由地添加额外的关键字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

@emph{stream} 参数必须为一个基于特定编解码器打开用于写入文本或二进制数据的文件类对象。

@ref{19bd,,StreamWriter} 可以通过提供 @emph{errors} 关键字参数来实现不同的错误处理方案。 请参阅 @ref{f7d,,错误处理方案} 了解下层的流式编解码器可支持的标准错误处理方案。

@emph{errors} 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在 @ref{19bd,,StreamWriter} 对象的生命期内在不同的错误处理策略之间进行切换。

@geindex write() (codecs.StreamWriter 方法)
@anchor{library/codecs codecs StreamWriter write}@anchor{19ee}
@deffn {方法} write (object)

将编码后的对象内容写入到流。
@end deffn

@geindex writelines() (codecs.StreamWriter 方法)
@anchor{library/codecs codecs StreamWriter writelines}@anchor{19ef}
@deffn {方法} writelines (list)

将拼接后的字符串可迭代对象写入到流（可能通过重用 @ref{19ee,,write()} 方法）。 无限长或非常大的可迭代对象不受支持。 标准的字节到字节编解码器不支持此方法。
@end deffn

@geindex reset() (codecs.StreamWriter 方法)
@anchor{library/codecs codecs StreamWriter reset}@anchor{19f0}
@deffn {方法} reset ()

重置用于保持内部状态的编解码器缓冲区。

调用此方法应当确保在干净的状态下放入输出数据，以允许直接添加新的干净数据而无须重新扫描整个流来恢复状态。
@end deffn
@end deffn

除了上述的方法，@ref{19bd,,StreamWriter} 还必须继承来自下层流的所有其他方法和属性。

@node StreamReader 对象,StreamReaderWriter 对象,StreamWriter 对象,流式的编码和解码
@anchor{library/codecs stream-reader-objects}@anchor{19f1}@anchor{library/codecs streamreader-objects}@anchor{19f2}
@subsubsection StreamReader 对象


@ref{19be,,StreamReader} 类是 @code{Codec} 的子类，它定义了以下方法，每个流式读取器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

@geindex StreamReader (codecs 中的类)
@anchor{library/codecs codecs StreamReader}@anchor{19be}
@deffn {类} codecs.StreamReader (stream, errors='strict')

@ref{19be,,StreamReader} 实例的构造器。

所有流式读取器必须提供此构造器接口。 它们可以自由地添加额外的关键字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

@emph{stream} 参数必须为一个基于特定编解码器打开用于读取文本或二进制数据的文件类对象。

@ref{19be,,StreamReader} 可以通过提供 @emph{errors} 关键字参数来实现不同的错误处理方案。 请参阅 @ref{f7d,,错误处理方案} 了解下层的流式编解码器可支持的标准错误处理方案。

@emph{errors} 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在 @ref{19be,,StreamReader} 对象的生命期内在不同的错误处理策略之间进行切换。

@emph{errors} 参数所允许的值集合可以使用 @ref{ec1,,register_error()} 来扩展。

@geindex read() (codecs.StreamReader 方法)
@anchor{library/codecs codecs StreamReader read}@anchor{19f3}
@deffn {方法} read (size=-1, chars=-1, firstline=False)

解码来自流的数据并返回结果对象。

@emph{chars} 参数指明要返回的解码后码位或字节数量。 @ref{19f3,,read()} 方法绝不会返回超出请求数量的数据，但如果可用数量不足，它可能返回少于请求数量的数据。

@emph{size} 参数指明要读取并解码的已编码字节或码位的最大数量近似值。 解码器可以适当地修改此设置。 默认值 -1 表示尽可能多地读取并解码。 此形参的目的是防止一次性解码过于巨大的文件。

@emph{firstline} 旗标指明如果在后续行发生解码错误，则仅返回第一行就足够了。

此方法应当使用“贪婪”读取策略，这意味着它应当在编码格式定义和给定大小所允许的情况下尽可能多地读取数据，例如，如果在流上存在可选的编码结束或状态标记，这些内容也应当被读取。
@end deffn

@geindex readline() (codecs.StreamReader 方法)
@anchor{library/codecs codecs StreamReader readline}@anchor{19f4}
@deffn {方法} readline (size=None, keepends=True)

从输入流读取一行并返回解码后的数据。

如果给定了 @emph{size}，则将其作为 size 参数传递给流的 @ref{19f3,,read()} 方法。

如果 @emph{keepends} 为假值，则行结束符将从返回的行中去除。
@end deffn

@geindex readlines() (codecs.StreamReader 方法)
@anchor{library/codecs codecs StreamReader readlines}@anchor{19f5}
@deffn {方法} readlines (sizehint=None, keepends=True)

从输入流读取所有行并将其作为一个行列表返回。

行结束符会使用编解码器的 @ref{8fa,,decode()} 方法来实现，并且如果 @emph{keepends} 为真值则会将其包含在列表条目中。

如果给定了 @emph{sizehint}，则将其作为 @emph{size} 参数传递给流的 @ref{19f3,,read()} 方法。
@end deffn

@geindex reset() (codecs.StreamReader 方法)
@anchor{library/codecs codecs StreamReader reset}@anchor{19f6}
@deffn {方法} reset ()

重置用于保持内部状态的编解码器缓冲区。

请注意不应当对流进行重定位。 使用此方法的主要目的是为了能够从解码错误中恢复。
@end deffn
@end deffn

除了上述的方法，@ref{19be,,StreamReader} 还必须继承来自下层流的所有其他方法和属性。

@node StreamReaderWriter 对象,StreamRecoder 对象,StreamReader 对象,流式的编码和解码
@anchor{library/codecs stream-reader-writer}@anchor{19f7}@anchor{library/codecs streamreaderwriter-objects}@anchor{19f8}
@subsubsection StreamReaderWriter 对象


@ref{19c6,,StreamReaderWriter} 是一个方便的类，允许对同时工作于读取和写入模式的流进行包装。

其设计使得开发者可以使用 @ref{239,,lookup()} 函数所返回的工厂函数来构造实例。

@geindex StreamReaderWriter (codecs 中的类)
@anchor{library/codecs codecs StreamReaderWriter}@anchor{19c6}
@deffn {类} codecs.StreamReaderWriter (stream, Reader, Writer, errors='strict')

创建一个 @ref{19c6,,StreamReaderWriter} 实例。 @emph{stream} 必须为一个文件类对象。 @emph{Reader} 和 @emph{Writer} 必须为分别提供了 @ref{19be,,StreamReader} 和 @ref{19bd,,StreamWriter} 接口的工厂函数或类。 错误处理通过与流式读取器和写入器所定义的相同方式来完成。
@end deffn

@ref{19c6,,StreamReaderWriter} 实例定义了 @ref{19be,,StreamReader} 和 @ref{19bd,,StreamWriter} 类的组合接口。 它们还继承了来自下层流的所有其他方法和属性。

@node StreamRecoder 对象,,StreamReaderWriter 对象,流式的编码和解码
@anchor{library/codecs stream-recoder-objects}@anchor{19f9}@anchor{library/codecs streamrecoder-objects}@anchor{19fa}
@subsubsection StreamRecoder 对象


@ref{1151,,StreamRecoder} 将数据从一种编码格式转换为另一种，这对于处理不同编码环境的情况有时会很有用。

其设计使得开发者可以使用 @ref{239,,lookup()} 函数所返回的工厂函数来构造实例。

@geindex StreamRecoder (codecs 中的类)
@anchor{library/codecs codecs StreamRecoder}@anchor{1151}
@deffn {类} codecs.StreamRecoder (stream, encode, decode, Reader, Writer, errors='strict')

创建一个实现了双向转换的 @ref{1151,,StreamRecoder} 实例: @emph{encode} 和 @emph{decode} 工作于前端 — 对代码可见的数据调用 @code{read()} 和 @code{write()}，而 @emph{Reader} 和 @emph{Writer} 工作于后端 —  @emph{stream} 中的数据。

你可以使用这些对象来进行透明转码，例如从 Latin-1 转为 UTF-8 以及反向转换。

@emph{stream} 参数必须为一个文件类对象。

@emph{encode} 和 @emph{decode} 参数必须遵循 @code{Codec} 接口。 @emph{Reader} 和 @emph{Writer} 必须为分别提供了 @ref{19be,,StreamReader} 和 @ref{19bd,,StreamWriter} 接口对象的工厂函数或类。

错误处理通过与流式读取器和写入器所定义的相同方式来完成。
@end deffn

@ref{1151,,StreamRecoder} 实例定义了 @ref{19be,,StreamReader} 和 @ref{19bd,,StreamWriter} 类的组合接口。 它们还继承了来自下层流的所有其他方法和属性。

@node 编码格式与 Unicode,标准编码,编解码器基类,codecs --- 编解码器注册和相关基类
@anchor{library/codecs encodings-and-unicode}@anchor{19fb}@anchor{library/codecs encodings-overview}@anchor{19fc}
@subsubsection 编码格式与 Unicode


字符串在系统内部存储为 @code{U+0000}--@code{U+10FFFF} 范围内的码位序列。 （请参阅 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 了解有关实现的详情。） 一旦字符串对象要在 CPU 和内存以外使用，字节的大小端顺序和字节数组的存储方式就成为一个影响因素。 如同使用其他编解码器一样，将字符串序列化为字节序列被称为 @emph{编码}，而从字节序列重建字符串被称为 @emph{解码}。 存在许多不同的文本序列化编解码器，它们被统称为 @ref{1761,,文本编码格式}。

最简单的文本编码格式 (称为 @code{'latin-1'} 或 @code{'iso-8859-1'}) 将码位 0--255 映射为字节值 @code{0x0}--@code{0xff}，这意味着包含 @code{U+00FF} 以上码位的字符串对象无法使用此编解码器进行编码。 这样做将引发 @ref{331,,UnicodeEncodeError}，其形式类似下面这样（不过详细的错误信息可能会有所不同）: @code{UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in position 3: ordinal not in range(256)}。

还有另外一组编码格式（所谓的字符映射编码）会选择全部 Unicode 码位的不同子集并设定如何将这些码位映射为字节值 @code{0x0}--@code{0xff}。 要查看这是如何实现的，只需简单地打开相应源码例如 @code{encodings/cp1252.py} (这是一个主要在 Windows 上使用的编码格式)。 其中会有一个包含 256 个字符的字符串常量，指明每个字符所映射的字节值。

所有这些编码格式只能对 Unicode 所定义的 1114112 个码位中的 256 个进行编码。 一种能够存储每个 Unicode 码位的简单而直接的办法就是将每个友们存储为四个连续的字节。 存在两种不同的可能性：以大端序存储或以小端序存储。 这两种编码格式分别被称为 @code{UTF-32-BE} 和 @code{UTF-32-LE}。 他们共有的缺点可以举例说明：如果你在一台小端序的机器上使用 @code{UTF-32-BE} 则你必须在编码和解码时翻转字节。 @code{UTF-32} 避免了这个问题：字节的排列将总是使用自然端序。 当这些字节被具有不同端序的 CPU 读取时，则必须进行字节翻转。 为了能够检测 @code{UTF-16} 或 @code{UTF-32} 字节序列的大小端序，可以使用所谓的 BOM ("字节顺序标记")。 这对应于 Unicode 字符 @code{U+FEFF}。 此字符可被添加到每个 @code{UTF-16} 或 @code{UTF-32} 字节序列的开头。 此字符的字节翻转版本 (@code{0xFFFE}) 是一个不可出现于 Unicode 文本中的非法字符。 因此当发现一个 @code{UTF-16} 或 @code{UTF-32} 字节序列的首个字符是 @code{U+FFFE} 时，就必须在解码时进行字节翻转。 不幸的是字符 @code{U+FEFF} 还有第二个含义 @code{ZERO WIDTH NO-BREAK SPACE}: 即宽度为零并且不允许用来拆分单词的字符。 它可以被用来为语言分析算法提供提示。 在 Unicode 4.0 中使用 @code{U+FEFF} 表示 @code{ZERO WIDTH NO-BREAK SPACE} 已被弃用 (改用 @code{U+2060} (@code{WORD JOINER}) 负责此任务)。 然而 Unicode 软件仍然必须能够处理 @code{U+FEFF} 的两个含义：作为 BOM 它被用来确定已编码字节的存储布局，并在字节序列被解码为字符串后将其去除；作为 @code{ZERO WIDTH NO-BREAK SPACE} 它是一个普通字符，将像其他字符一样被解码。

还有另一种编码格式能够对所有 Unicode 字符进行编码：UTF-8。 UTF-8 是一种 8 位编码，这意味着在 UTF-8 中没有字节顺序问题。 UTF-8 字节序列中的每个字节由两部分组成：标志位（最重要的位）和内容位。 标志位是由零至四个值为 @code{1} 的二进制位加一个值为 @code{0} 的二进制位构成的序列。 Unicode 字符会按以下形式进行编码（其中 x 为内容位，当拼接为一体时将给出对应的 Unicode 字符）:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

范围

@tab

编码

@item

@code{U-00000000} ... @code{U-0000007F}

@tab

0xxxxxxx

@item

@code{U-00000080} ... @code{U-000007FF}

@tab

110xxxxx 10xxxxxx

@item

@code{U-00000800} ... @code{U-0000FFFF}

@tab

1110xxxx 10xxxxxx 10xxxxxx

@item

@code{U-00010000} ... @code{U-0010FFFF}

@tab

11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

@end multitable


Unicode 字符最不重要的一个位就是最右侧的二进制位 x。

由于 UTF-8 是一种 8 位编码格式，因此 BOM 是不必要的，并且已编码字符串中的任何 @code{U+FEFF} 字符（即使是作为第一个字符）都会被视为是 @code{ZERO WIDTH NO-BREAK SPACE}。

在没有外部信息的情况下将不可能毫无疑义地确定一个字符串使用了何种编码格式。 每种字符映射编码格式都可以解码任意的随机字节序列。 然而对 UTF-8 来说这却是不可能的，因为 UTF-8 字节序列具有不允许任意字节序列的特别结构。 为了提升 UTF-8 编码格式检测的可靠性，Microsoft 发明了一种 UTF-8 的变体形式 (Python 称之为 @code{"utf-8-sig"}) 专门用于其 Notepad 程序：在任何 Unicode 字节被写入文件之前，会先写入一个 UTF-8 编码的 BOM (它看起来是这样一个字节序列: @code{0xef}, @code{0xbb}, @code{0xbf})。 由于任何字符映射编码后的文件都不大可能以这些字节值开头 (例如它们会映射为

@quotation


@display
LATIN SMALL LETTER I WITH DIAERESIS@w{ }
RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK@w{ }
INVERTED QUESTION MARK@w{ }
@end display


@end quotation

对于 iso-8859-1 编码格式来说），这提升了根据字节序列来正确猜测 @code{utf-8-sig} 编码格式的成功率。 所以在这里 BOM 的作用并不是帮助确定生成字节序列所使用的字节顺序，而是作为帮助猜测编码格式的记号。 在进行编码时 utf-8-sig 编解码器将把 @code{0xef}, @code{0xbb}, @code{0xbf} 作为头三个字节写入文件。 在进行解码时 @code{utf-8-sig} 将跳过这三个字节，如果它们作为文件的头三个字节出现的话。 在 UTF-8 中并不推荐使用 BOM，通常应当避免它们的出现。

@node 标准编码,Python 专属的编码格式,编码格式与 Unicode,codecs --- 编解码器注册和相关基类
@anchor{library/codecs id3}@anchor{19fd}@anchor{library/codecs standard-encodings}@anchor{78c}
@subsubsection 标准编码


Python 自带了许多内置的编解码器，它们的实现或者是通过 C 函数，或者是通过映射表。 以下表格是按名称排序的编解码器列表，并提供了一些常见别名以及编码格式通常针对的语言。 别名和语言列表都不是详尽无遗的。 请注意仅有大小写区别或使用连字符替代下划线的拼写形式也都是有效的别名；因此，@code{'utf-8'} 是 @code{'utf_8'} 编解码器的有效别名。

@strong{CPython implementation detail:} 有些常见编码格式可以绕过编解码器查找机制来提升性能。 这些优化机会对于 CPython 来说仅能通过一组有限的别名（大小写不敏感）来识别：utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows 专属), ascii, us-ascii, utf-16, utf16, utf-32, utf32, 也包括使用下划线替代连字符的的形式。 使用这些编码格式的其他别名可能会导致更慢的执行速度。


在 3.6 版更改: 可识别针对 us-ascii 的优化机会。


许多字符集都支持相同的语言。 它们在个别字符（例如是否支持 EURO SIGN 等）以及给字符所分配的码位方面存在差异。 特别是对于欧洲语言来说，通常存在以下几种变体：


@itemize *

@item 
某个 ISO 8859 编码集

@item 
某个 Microsoft Windows 编码页，通常是派生自某个 8859 编码集，但会用附加的图形字符来替换控制字符。

@item 
某个 IBM EBCDIC 编码页

@item 
某个 IBM PC 编码页，通常会兼容 ASCII
@end itemize


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

编码

@tab

别名

@tab

语言

@item

ascii

@tab

646, us-ascii

@tab

英语

@item

big5

@tab

big5-tw, csbig5

@tab

繁体中文

@item

big5hkscs

@tab

big5-hkscs, hkscs

@tab

繁体中文

@item

cp037

@tab

IBM037, IBM039

@tab

英语

@item

cp273

@tab

273, IBM273, csIBM273

@tab

德语


3.4 新版功能.


@item

cp424

@tab

EBCDIC-CP-HE, IBM424

@tab

希伯来语

@item

cp437

@tab

437, IBM437

@tab

英语

@item

cp500

@tab

EBCDIC-CP-BE, EBCDIC-CP-CH,
IBM500

@tab

西欧

@item

cp720

@tab

@tab

阿拉伯语

@item

cp737

@tab

@tab

希腊语

@item

cp775

@tab

IBM775

@tab

波罗的海语言

@item

cp850

@tab

850, IBM850

@tab

西欧

@item

cp852

@tab

852, IBM852

@tab

中欧和东欧

@item

cp855

@tab

855, IBM855

@tab

保加利亚语，白俄罗斯语，马其顿语，俄语，塞尔维亚语

@item

cp856

@tab

@tab

希伯来语

@item

cp857

@tab

857, IBM857

@tab

土耳其语

@item

cp858

@tab

858, IBM858

@tab

西欧

@item

cp860

@tab

860, IBM860

@tab

葡萄牙语

@item

cp861

@tab

861, CP-IS, IBM861

@tab

冰岛语

@item

cp862

@tab

862, IBM862

@tab

希伯来语

@item

cp863

@tab

863, IBM863

@tab

加拿大语

@item

cp864

@tab

IBM864

@tab

阿拉伯语

@item

cp865

@tab

865, IBM865

@tab

丹麦语/挪威语

@item

cp866

@tab

866, IBM866

@tab

俄语

@item

cp869

@tab

869, CP-GR, IBM869

@tab

希腊语

@item

cp874

@tab

@tab

泰语

@item

cp875

@tab

@tab

希腊语

@item

cp932

@tab

932, ms932, mskanji, ms-kanji

@tab

日语

@item

cp949

@tab

949, ms949, uhc

@tab

韩语

@item

cp950

@tab

950, ms950

@tab

繁体中文

@item

cp1006

@tab

@tab

乌尔都语

@item

cp1026

@tab

ibm1026

@tab

土耳其语

@item

cp1125

@tab

1125, ibm1125, cp866u, ruscii

@tab

乌克兰语


3.4 新版功能.


@item

cp1140

@tab

ibm1140

@tab

西欧

@item

cp1250

@tab

windows-1250

@tab

中欧和东欧

@item

cp1251

@tab

windows-1251

@tab

保加利亚语，白俄罗斯语，马其顿语，俄语，塞尔维亚语

@item

cp1252

@tab

windows-1252

@tab

西欧

@item

cp1253

@tab

windows-1253

@tab

希腊语

@item

cp1254

@tab

windows-1254

@tab

土耳其语

@item

cp1255

@tab

windows-1255

@tab

希伯来语

@item

cp1256

@tab

windows-1256

@tab

阿拉伯语

@item

cp1257

@tab

windows-1257

@tab

波罗的海语言

@item

cp1258

@tab

windows-1258

@tab

越南语

@item

euc_jp

@tab

eucjp, ujis, u-jis

@tab

日语

@item

euc_jis_2004

@tab

jisx0213, eucjis2004

@tab

日语

@item

euc_jisx0213

@tab

eucjisx0213

@tab

日语

@item

euc_kr

@tab

euckr, korean, ksc5601,
ks_c-5601, ks_c-5601-1987,
ksx1001, ks_x-1001

@tab

韩语

@item

gb2312

@tab

chinese, csiso58gb231280,
euc-cn, euccn, eucgb2312-cn,
gb2312-1980, gb2312-80,
iso-ir-58

@tab

简体中文

@item

gbk

@tab

936, cp936, ms936

@tab

统一汉语

@item

gb18030

@tab

gb18030-2000

@tab

统一汉语

@item

hz

@tab

hzgb, hz-gb, hz-gb-2312

@tab

简体中文

@item

iso2022_jp

@tab

csiso2022jp, iso2022jp,
iso-2022-jp

@tab

日语

@item

iso2022_jp_1

@tab

iso2022jp-1, iso-2022-jp-1

@tab

日语

@item

iso2022_jp_2

@tab

iso2022jp-2, iso-2022-jp-2

@tab

日语，韩语，简体中文，西欧，希腊语

@item

iso2022_jp_2004

@tab

iso2022jp-2004,
iso-2022-jp-2004

@tab

日语

@item

iso2022_jp_3

@tab

iso2022jp-3, iso-2022-jp-3

@tab

日语

@item

iso2022_jp_ext

@tab

iso2022jp-ext, iso-2022-jp-ext

@tab

日语

@item

iso2022_kr

@tab

csiso2022kr, iso2022kr,
iso-2022-kr

@tab

韩语

@item

latin_1

@tab

iso-8859-1, iso8859-1, 8859,
cp819, latin, latin1, L1

@tab

西欧

@item

iso8859_2

@tab

iso-8859-2, latin2, L2

@tab

中欧和东欧

@item

iso8859_3

@tab

iso-8859-3, latin3, L3

@tab

世界语，马耳他语

@item

iso8859_4

@tab

iso-8859-4, latin4, L4

@tab

波罗的海语言

@item

iso8859_5

@tab

iso-8859-5, cyrillic

@tab

保加利亚语，白俄罗斯语，马其顿语，俄语，塞尔维亚语

@item

iso8859_6

@tab

iso-8859-6, arabic

@tab

阿拉伯语

@item

iso8859_7

@tab

iso-8859-7, greek, greek8

@tab

希腊语

@item

iso8859_8

@tab

iso-8859-8, hebrew

@tab

希伯来语

@item

iso8859_9

@tab

iso-8859-9, latin5, L5

@tab

土耳其语

@item

iso8859_10

@tab

iso-8859-10, latin6, L6

@tab

北欧语言

@item

iso8859_11

@tab

iso-8859-11, thai

@tab

泰语

@item

iso8859_13

@tab

iso-8859-13, latin7, L7

@tab

波罗的海语言

@item

iso8859_14

@tab

iso-8859-14, latin8, L8

@tab

凯尔特语

@item

iso8859_15

@tab

iso-8859-15, latin9, L9

@tab

西欧

@item

iso8859_16

@tab

iso-8859-16, latin10, L10

@tab

东南欧

@item

johab

@tab

cp1361, ms1361

@tab

韩语

@item

koi8_r

@tab

@tab

俄语

@item

koi8_t

@tab

@tab

塔吉克


3.5 新版功能.


@item

koi8_u

@tab

@tab

乌克兰语

@item

kz1048

@tab

kz_1048, strk1048_2002, rk1048

@tab

哈萨克语


3.5 新版功能.


@item

mac_cyrillic

@tab

maccyrillic

@tab

保加利亚语，白俄罗斯语，马其顿语，俄语，塞尔维亚语

@item

mac_greek

@tab

macgreek

@tab

希腊语

@item

mac_iceland

@tab

maciceland

@tab

冰岛语

@item

mac_latin2

@tab

maclatin2, maccentraleurope,
mac_centeuro

@tab

中欧和东欧

@item

mac_roman

@tab

macroman, macintosh

@tab

西欧

@item

mac_turkish

@tab

macturkish

@tab

土耳其语

@item

ptcp154

@tab

csptcp154, pt154, cp154,
cyrillic-asian

@tab

哈萨克语

@item

shift_jis

@tab

csshiftjis, shiftjis, sjis,
s_jis

@tab

日语

@item

shift_jis_2004

@tab

shiftjis2004, sjis_2004,
sjis2004

@tab

日语

@item

shift_jisx0213

@tab

shiftjisx0213, sjisx0213,
s_jisx0213

@tab

日语

@item

utf_32

@tab

U32, utf32

@tab

所有语言

@item

utf_32_be

@tab

UTF-32BE

@tab

所有语言

@item

utf_32_le

@tab

UTF-32LE

@tab

所有语言

@item

utf_16

@tab

U16, utf16

@tab

所有语言

@item

utf_16_be

@tab

UTF-16BE

@tab

所有语言

@item

utf_16_le

@tab

UTF-16LE

@tab

所有语言

@item

utf_7

@tab

U7, unicode-1-1-utf-7

@tab

所有语言

@item

utf_8

@tab

U8, UTF, utf8, cp65001

@tab

所有语言

@item

utf_8_sig

@tab

@tab

所有语言

@end multitable



在 3.4 版更改: utf-16* 和 utf-32* 编码器将不再允许编码代理码位 (@code{U+D800}--@code{U+DFFF})。 utf-32* 解码器将不再解码与代理码位相对应的字节序列。



在 3.8 版更改: @code{cp65001} 现在是 @code{utf_8} 的一个别名。


@node Python 专属的编码格式,encodings idna --- 应用程序中的国际化域名,标准编码,codecs --- 编解码器注册和相关基类
@anchor{library/codecs python-specific-encodings}@anchor{19fe}
@subsubsection Python 专属的编码格式


有一些预定义编解码器是 Python 专属的，因此它们在 Python 之外没有意义。 这些编解码器按其所预期的输入和输出类型在下表中列出（请注意虽然文本编码是编解码器最常见的使用场景，但下层的编解码器架构支持任意数据转换而不仅是文本编码）。 对于非对称编解码器，该列描述的含义是编码方向。

@menu
* 文字编码:: 
* 二进制转换:: 
* 文字转换:: 

@end menu

@node 文字编码,二进制转换,,Python 专属的编码格式
@anchor{library/codecs text-encodings}@anchor{19ff}
@subsubsection 文字编码


以下编解码器提供了 @ref{206,,str} 到 @ref{172,,bytes} 的编码和 @ref{6e9,,bytes-like object} 到 @ref{206,,str} 的解码，类似于 Unicode 文本编码。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

编码

@tab

别名

@tab

含义

@item

idna

@tab

@tab

实现 
@geindex RFC; RFC 3490
RFC 3490@footnote{https://tools.ietf.org/html/rfc3490.html}，另请参阅 @ref{75,,encodings.idna} 。仅支持 @code{errors='strict'} 。

@item

mbcs

@tab

ansi,
dbcs

@tab

Windows 专属：根据 ANSI 代码页（CP_ACP）对操作数进行编码。

@item

oem

@tab

@tab

Windows 专属：根据 OEM 代码页（CP_OEMCP）对操作数进行编码。


3.6 新版功能.


@item

palmos

@tab

@tab

PalmOS 3.5 的编码格式

@item

punycode

@tab

@tab

实现 
@geindex RFC; RFC 3492
RFC 3492@footnote{https://tools.ietf.org/html/rfc3492.html}。 不支持有状态编解码器。

@item

raw_unicode_escape

@tab

@tab

Latin-1 编码格式附带对其他码位以 @code{\uXXXX} 和 @code{\UXXXXXXXX} 进行编码。 现有反斜杠不会以任何方式转义。 它被用于 Python 的 pickle 协议。

@item

undefined

@tab

@tab

所有转换都将引发异常，甚至对空字符串也不例外。 错误处理方案会被忽略。

@item

unicode_escape

@tab

@tab

适合用于以 ASCII 编码的 Python 源代码中的 Unicode 字面值内容的编码格式，但引号不会被转义。 对 Latin-1 源代码进行解码。 请注意 Python 源代码实际上默认使用 UTF-8。

@end multitable



在 3.8 版更改: "unicode_internal" 编解码器已被移除。


@node 二进制转换,文字转换,文字编码,Python 专属的编码格式
@anchor{library/codecs binary-transforms}@anchor{8fb}@anchor{library/codecs id4}@anchor{1a00}
@subsubsection 二进制转换


以下编解码器提供了二进制转换: @ref{6e9,,bytes-like object} 到 @ref{172,,bytes} 的映射。 它们不被 @ref{171,,bytes.decode()} 所支持（该方法只生成 @ref{206,,str} 类型的输出）。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

编码

@tab

别名

@tab

含义

@tab

编码器/解码器

@item

base64_codec @footnote{@w{(1)} 
除了 @ref{6e9,,字节类对象}，@code{'base64_codec'} 也接受仅包含 ASCII 的 @ref{206,,str} 实例用于解码
}

@tab

base64, base_64

@tab

将操作数转换为多行 MIME base64 (结果总是包含一个末尾的 @code{'\n'})


在 3.4 版更改: 接受任意 @ref{6e9,,bytes-like object} 作为输入用于编码和解码


@tab

@ref{223,,base64.encodebytes()} /
@ref{224,,base64.decodebytes()}

@item

bz2_codec

@tab

bz2

@tab

使用bz2压缩操作数

@tab

@ref{1a01,,bz2.compress()} /
@ref{abf,,bz2.decompress()}

@item

hex_codec

@tab

hex

@tab

将操作数转换为十六进制表示，每个字节有两位数

@tab

@ref{1a02,,binascii.b2a_hex()} /
@ref{1a03,,binascii.a2b_hex()}

@item

quopri_codec

@tab

quopri,
quotedprintable,
quoted_printable

@tab

将操作数转换为 MIME 带引号的可打印数据

@tab

@ref{1a04,,quopri.encode()} 且 @code{quotetabs=True} / @ref{1a05,,quopri.decode()}

@item

uu_codec

@tab

uu

@tab

使用uuencode转换操作数

@tab

@ref{51c,,uu.encode()} /
@ref{f55,,uu.decode()}

@item

zlib_codec

@tab

zip, zlib

@tab

使用gzip压缩操作数

@tab

@ref{6bf,,zlib.compress()} /
@ref{6c0,,zlib.decompress()}

@end multitable



3.2 新版功能: 恢复二进制转换。



在 3.4 版更改: 恢复二进制转换的别名。


@node 文字转换,,二进制转换,Python 专属的编码格式
@anchor{library/codecs id6}@anchor{1a06}@anchor{library/codecs text-transforms}@anchor{8fc}
@subsubsection 文字转换


以下编解码器提供了文本转换: @ref{206,,str} 到 @ref{206,,str} 的映射。 它不被 @ref{170,,str.encode()} 所支持（该方法只生成 @ref{172,,bytes} 类型的输出）。


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

编码

@tab

别名

@tab

含义

@item

rot_13

@tab

rot13

@tab

返回操作数的凯撒密码加密结果

@end multitable



3.2 新版功能: 恢复 @code{rot_13} 文本转换。



在 3.4 版更改: 恢复 @code{rot13} 别名。


@node encodings idna --- 应用程序中的国际化域名,encodings mbcs --- Windows ANSI代码页,Python 专属的编码格式,codecs --- 编解码器注册和相关基类
@anchor{library/codecs encodings-idna-internationalized-domain-names-in-applications}@anchor{1a07}@anchor{library/codecs module-encodings idna}@anchor{75}
@subsubsection @code{encodings.idna} --- 应用程序中的国际化域名


@geindex encodings.idna (模块)

此模块实现了 
@geindex RFC; RFC 3490
RFC 3490@footnote{https://tools.ietf.org/html/rfc3490.html} (应用程序中的国际化域名) 和 
@geindex RFC; RFC 3492
RFC 3492@footnote{https://tools.ietf.org/html/rfc3492.html} (Nameprep: 用于国际化域名 (IDN) 的 Stringprep 配置文件)。 它是在 @code{punycode} 编码格式和 @ref{f7,,stringprep} 的基础上构建的。

如果你需要来自 
@geindex RFC; RFC 5891
RFC 5891@footnote{https://tools.ietf.org/html/rfc5891.html} 和 
@geindex RFC; RFC 5895
RFC 5895@footnote{https://tools.ietf.org/html/rfc5895.html} 的 IDNA 2008 标准，请使用第三方 idna 模块@footnote{https://pypi.org/project/idna/}。

这些 RFC 共同定义了一个在域名中支持非 ASCII 字符的协议。 一个包含非 ASCII 字符的域名 (例如 @code{www.Alliancefrançaise.nu}) 会被转换为兼容 ASCII 的编码格式 (简称 ACE，例如 @code{www.xn--alliancefranaise-npb.nu})。 随后此域名的 ACE 形式可以用于所有由于特定协议而不允许使用任意字符的场合，例如 DNS 查询，HTTP @code{Host} 字段等等。 此转换是在应用中进行的；如有可能将对用户可见：应用应当透明地将 Unicode 域名标签转换为线上的 IDNA，并在 ACE 标签被呈现给用户之前将其转换回 Unicode。

Python 以多种方式支持这种转换:  @code{idna} 编解码器执行 Unicode 和 ACE 之间的转换，基于在 
@geindex RFC; RFC 3490#section-3.1
section 3.1 of RFC 3490@footnote{https://tools.ietf.org/html/rfc3490.html#section-3.1} 中定义的分隔字符将输入字符串拆分为标签，再根据需要将每个标签转换为 ACE，相反地又会基于 @code{.} 分隔符将输入字节串拆分为标签，再将找到的任何 ACE 标签转换为 Unicode。 此外，@ref{ef,,socket} 模块可透明地将 Unicode 主机名转换为 ACE，以便应用在将它们传给 socket 模块时无须自行转换主机名。 除此之外，许多包含以主机名作为函数参数的模块例如 @ref{93,,http.client} 和 @ref{82,,ftplib} 都接受 Unicode 主机名（并且 @ref{93,,http.client} 也会在 @code{Host} 字段中透明地发送 IDNA 主机名，如果它需要发送该字段的话）。

当从线路接收主机名时（例如反向名称查找），到 Unicode 的转换不会自动被执行：希望向用户提供此种主机名的应用应当将它们解码为 Unicode。

@ref{75,,encodings.idna} 模块还实现了 nameprep 过程，该过程会对主机名执行特定的规范化操作，以实现国际域名的大小写不敏感特性与合并相似的字符。 如果有需要可以直接使用 nameprep 函数。

@geindex nameprep() (在 encodings.idna 模块中)
@anchor{library/codecs encodings idna nameprep}@anchor{1a08}
@deffn {函数} encodings.idna.nameprep (label)

返回 @emph{label} 经过名称处理操作的版本。 该实现目前基于查询字符串，因此 @code{AllowUnassigned} 为真值。
@end deffn

@geindex ToASCII() (在 encodings.idna 模块中)
@anchor{library/codecs encodings idna ToASCII}@anchor{1a09}
@deffn {函数} encodings.idna.ToASCII (label)

将标签转换为 ASCII，规则定义见 
@geindex RFC; RFC 3490
RFC 3490@footnote{https://tools.ietf.org/html/rfc3490.html}。 @code{UseSTD3ASCIIRules} 预设为假值。
@end deffn

@geindex ToUnicode() (在 encodings.idna 模块中)
@anchor{library/codecs encodings idna ToUnicode}@anchor{1a0a}
@deffn {函数} encodings.idna.ToUnicode (label)

将标签转换为 Unicode，规则定义见 
@geindex RFC; RFC 3490
RFC 3490@footnote{https://tools.ietf.org/html/rfc3490.html}。
@end deffn

@node encodings mbcs --- Windows ANSI代码页,encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,encodings idna --- 应用程序中的国际化域名,codecs --- 编解码器注册和相关基类
@anchor{library/codecs encodings-mbcs-windows-ansi-codepage}@anchor{1a0b}@anchor{library/codecs module-encodings mbcs}@anchor{76}
@subsubsection @code{encodings.mbcs} --- Windows ANSI代码页


@geindex encodings.mbcs (模块)

此模块实现ANSI代码页（CP_ACP）。

@ref{14c1,,Availability}: 仅Windows可用


在 3.3 版更改: 支持任何错误处理



在 3.2 版更改: 在 3.2 版之前， @emph{errors} 参数会被忽略；总是会使用 @code{'replace'} 进行编码，并使用 @code{'ignore'} 进行解码。


@node encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,,encodings mbcs --- Windows ANSI代码页,codecs --- 编解码器注册和相关基类
@anchor{library/codecs encodings-utf-8-sig-utf-8-codec-with-bom-signature}@anchor{1a0c}@anchor{library/codecs module-encodings utf_8_sig}@anchor{77}
@subsubsection @code{encodings.utf_8_sig} --- 带BOM签名的UTF-8编解码器


@geindex encodings.utf_8_sig (模块)

此模块实现了 UTF-8 编解码器的一个变种：在编码时将把 UTF-8 已编码 BOM 添加到 UTF-8 编码字节数据的开头。 对于有状态编码器此操作只执行一次（当首次写入字节流时）。 在解码时将跳过数据开头作为可选项的 UTF-8 已编码 BOM。

@node 数据类型,数字和数学模块,二进制数据服务,Python 标准库
@anchor{library/datatypes doc}@anchor{1a0d}@anchor{library/datatypes data-types}@anchor{1a0e}@anchor{library/datatypes datatypes}@anchor{1a0f}
@section 数据类型


本章所描述的模块提供了许多专门的数据类型，如日期和时间、固定类型的数组、堆队列、双端队列、以及枚举。

Python也提供一些内置数据类型，特别是，@ref{164,,dict}、 @ref{1f9,,list}、@ref{1f7,,set}、@ref{1f8,,frozenset}、以及 @ref{1a2,,tuple}。@ref{206,,str} 这个类是用来存储Unicode字符串的，而 @ref{172,,bytes} 和 @ref{173,,bytearray} 这两个类是用来存储二进制数据的。

本章包含以下模块的文档：

@menu
* datetime: datetime --- 基本日期和时间类型. 基本日期和时间类型
* zoneinfo: zoneinfo --- IANA 时区支持. IANA 时区支持
* calendar: calendar --- 日历相关函数. 日历相关函数
* collections: collections --- 容器数据类型. 容器数据类型
* collections.abc: collections abc --- 容器的抽象基类. 容器的抽象基类
* heapq: heapq --- 堆队列算法. 堆队列算法
* bisect: bisect --- 数组二分查找算法. 数组二分查找算法
* array: array --- 高效的数值数组. 高效的数值数组
* weakref: weakref --- 弱引用. 弱引用
* types: types --- 动态类型创建和内置类型名称. 动态类型创建和内置类型名称
* copy: copy --- 浅层 shallow 和深层 deep 复制操作. 浅层 (shallow) 和深层 (deep) 复制操作
* pprint: pprint --- 数据美化输出. 数据美化输出
* reprlib: reprlib --- 另一种 repr 实现. 另一种 repr() 实现
* enum: enum --- 对枚举的支持. 对枚举的支持
* graphlib: graphlib --- 操作类似图的结构的功能. 操作类似图的结构的功能

@end menu

@node datetime --- 基本日期和时间类型,zoneinfo --- IANA 时区支持,,数据类型
@anchor{library/datetime doc}@anchor{1a10}@anchor{library/datetime datetime-basic-date-and-time-types}@anchor{1a11}@anchor{library/datetime module-datetime}@anchor{30}
@subsection @code{datetime} --- 基本日期和时间类型


@geindex datetime (模块)

@strong{源代码：} Lib/datetime.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/datetime.py}


__________________________________________________________________


@c XXX what order should the types be discussed in?

@ref{30,,datetime} 模块提供用于处理日期和时间的类。

在支持日期时间数学运算的同时，实现的关注点更着重于如何能够更有效地解析其属性用于格式化输出和数据操作。


@subsubheading 参见



@table @asis

@item 模块 @ref{14,,calendar}

通用日历相关函数

@item 模块 @ref{10c,,time}

时间的访问和转换

@item @ref{14e,,zoneinfo} 模块

代表 IANA 时区数据库的具体时区。

@item dateutil@footnote{https://dateutil.readthedocs.io/en/stable/} 包

具有扩展时区和解析支持的第三方库。
@end table


@menu
* 感知型对象和简单型对象:: 
* 常量:: 
* 有效的类型:: 
* timedelta 类对象:: 
* date 对象:: 
* datetime 对象:: 
* time 对象:: 
* tzinfo 对象:: 
* timezone 对象:: 
* strftime() 和 strptime() 的行为: strftime 和 strptime 的行为. 

@end menu

@node 感知型对象和简单型对象,常量,,datetime --- 基本日期和时间类型
@anchor{library/datetime aware-and-naive-objects}@anchor{1a12}@anchor{library/datetime datetime-naive-aware}@anchor{1a13}
@subsubsection 感知型对象和简单型对象


日期和时间对象可以根据它们是否包含时区信息而分为“感知型”和“简单型”两类。

充分掌握应用性算法和政治性时间调整信息例如时区和夏令时的情况下，一个 @strong{感知型} 对象就能相对于其他感知型对象来精确定位自身时间点。 感知型对象是用来表示一个没有解释空间的固定时间点。 @footnote{@w{(1)} 
就是说如果我们忽略相对论效应的话。
}

@strong{简单型} 对象没有包含足够多的信息来无歧义地相对于其他 date/time 对象来定位自身时间点。 不论一个简单型对象所代表的是世界标准时间（UTC）、当地时间还是某个其他时区的时间完全取决于具体程序，就像一个特定数字所代表的是米、英里还是质量完全取决于具体程序一样。 简单型对象更易于理解和使用，代价则是忽略了某些现实性考量。

对于要求感知型对象的应用，@ref{19f,,datetime} 和 @ref{5f5,,time} 对象具有一个可选的时区信息属性 @code{tzinfo}，它可被设为抽象类 @ref{180,,tzinfo} 的子类的一个实例。 这些 @ref{180,,tzinfo} 对象会捕获与 UTC 时间的差值、时区名称以及夏令时是否生效等信息。

@ref{30,,datetime} 模块只提供了一个具体的 @ref{180,,tzinfo} 类，即 @ref{ae9,,timezone} 类。 @ref{ae9,,timezone} 类可以表示具有相对于 UTC 的固定时差的简单时区，例如 UTC 本身或北美的 EST 和 EDT 时区等。 支持时间的详细程度取决于具体的应用。 世界各地的时间调整规则往往是政治性多于合理性，经常会发生变化，除了 UTC 之外并没有一个能适合所有应用的标准。

@node 常量,有效的类型,感知型对象和简单型对象,datetime --- 基本日期和时间类型
@anchor{library/datetime constants}@anchor{1a14}
@subsubsection 常量


The @ref{30,,datetime} module exports the following constants:

@geindex MINYEAR() (在 datetime 模块中)
@anchor{library/datetime datetime MINYEAR}@anchor{1a15}
@deffn {数据} datetime.MINYEAR

@ref{19d,,date} 或者 @ref{19f,,datetime} 对象允许的最小年份。 常量 @ref{1a15,,MINYEAR} 是 @code{1} 。
@end deffn

@geindex MAXYEAR() (在 datetime 模块中)
@anchor{library/datetime datetime MAXYEAR}@anchor{1a16}
@deffn {数据} datetime.MAXYEAR

@ref{19d,,date} 或 @ref{19f,,datetime} 对象允许最大的年份。常量 @ref{1a16,,MAXYEAR} 是 @code{9999} 。
@end deffn

@node 有效的类型,timedelta 类对象,常量,datetime --- 基本日期和时间类型
@anchor{library/datetime available-types}@anchor{1a17}
@subsubsection 有效的类型



@deffn {类} datetime.date

一个理想化的简单型日期，它假设当今的公历在过去和未来永远有效。 属性: @ref{1a18,,year}, @ref{1a19,,month}, and @ref{1a1a,,day}。
@end deffn


@deffn {类} datetime.time

一个独立于任何特定日期的理想化时间，它假设每一天都恰好等于 24*60*60 秒。 （这里没有“闰秒”的概念。） 包含属性: @ref{1a1b,,hour}, @ref{1a1c,,minute}, @ref{1a1d,,second}, @ref{1a1e,,microsecond} 和 @ref{1a1f,,tzinfo}。
@end deffn


@deffn {类} datetime.datetime

日期和时间的结合。属性：@ref{1a20,,year}, @ref{1a21,,month}, @ref{1a22,,day}, @ref{1a23,,hour}, @ref{1a24,,minute}, @ref{1a25,,second}, @ref{1a26,,microsecond}, and @ref{1a27,,tzinfo}.
@end deffn


@deffn {类} datetime.timedelta

表示两个 @ref{19d,,date} 对象或者 @ref{5f5,,time} 对象,或者 @ref{19f,,datetime} 对象之间的时间间隔，精确到微秒。
@end deffn


@deffn {类} datetime.tzinfo

一个描述时区信息对象的抽象基类。 用来给 @ref{19f,,datetime} 和 @ref{5f5,,time} 类提供自定义的时间调整概念（例如处理时区和/或夏令时）。
@end deffn


@deffn {类} datetime.timezone

一个实现了 @ref{180,,tzinfo} 抽象基类的子类，用于表示相对于 世界标准时间（UTC）的偏移量。


3.2 新版功能.

@end deffn

这些类型的对象都是不可变的。

子类关系

@example
object
    timedelta
    tzinfo
        timezone
    time
    date
        datetime
@end example

@menu
* 通用的特征属性:: 
* 确定一个对象是感知型还是简单型:: 

@end menu

@node 通用的特征属性,确定一个对象是感知型还是简单型,,有效的类型
@anchor{library/datetime common-properties}@anchor{1a28}
@subsubsection 通用的特征属性


@ref{19d,,date}, @ref{19f,,datetime}, @ref{5f5,,time} 和 @ref{ae9,,timezone} 类型共享这些通用特性:


@itemize -

@item 
这些类型的对象都是不可变的。

@item 
这些类型的对象是可哈希的，这意味着它们可被作为字典的键。

@item 
这些类型的对象支持通过 @ref{ca,,pickle} 模块进行高效的封存。
@end itemize

@node 确定一个对象是感知型还是简单型,,通用的特征属性,有效的类型
@anchor{library/datetime determining-if-an-object-is-aware-or-naive}@anchor{1a29}
@subsubsection 确定一个对象是感知型还是简单型


@ref{19d,,date}  类型的对象都是简单型的。

@ref{5f5,,time} 或 @ref{19f,,datetime} 类型的对象可以是感知型或者简单型。

一个 @ref{19f,,datetime} 对象 @emph{d} 在以下条件同时成立时将是感知型的：


@enumerate 

@item 
@code{d.tzinfo} 不为 @code{None}

@item 
@code{d.tzinfo.utcoffset(d)} 不返回 @code{None}
@end enumerate

在其他情况下，@emph{d} 将是简单型的。

一个 @ref{5f5,,time} 对象 @emph{t} 在以下条件同时成立时将是感知型的：


@enumerate 

@item 
@code{t.tzinfo} 不为 @code{None}

@item 
@code{t.tzinfo.utcoffset(None)} 不返回 @code{None}。
@end enumerate

在其他情况下，@emph{t} 将是简单型的。

感知型和简单型之间的区别不适用于 @ref{2d1,,timedelta} 对象。

@node timedelta 类对象,date 对象,有效的类型,datetime --- 基本日期和时间类型
@anchor{library/datetime datetime-timedelta}@anchor{1a2a}@anchor{library/datetime timedelta-objects}@anchor{1a2b}
@subsubsection @code{timedelta} 类对象


@ref{2d1,,timedelta} 对象表示两个 date 或者 time 的时间间隔。

@geindex timedelta (datetime 中的类)
@anchor{library/datetime datetime timedelta}@anchor{2d1}
@deffn {类} datetime.timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有参数都是可选的并且默认为 @code{0}。 这些参数可以是整数或者浮点数，也可以是正数或者负数。

只有 @emph{days}, @emph{seconds} 和 @emph{microseconds} 会存储在内部。 参数单位的换算规则如下：


@itemize *

@item 
1毫秒会转换成1000微秒。

@item 
1分钟会转换成60秒。

@item 
1小时会转换成3600秒。

@item 
1星期会转换成7天。
@end itemize

并且 days, seconds, microseconds 会经标准化处理以保证表达方式的唯一性，即：


@itemize *

@item 
@code{0 <= microseconds < 1000000}

@item 
@code{0 <= seconds < 3600*24} (一天的秒数)

@item 
@code{-999999999 <= days <= 999999999}
@end itemize

下面的例子演示了如何对 @emph{days}, @emph{seconds} 和 @emph{microseconds} 以外的任意参数执行“合并”操作并标准化为以上三个结果属性:

@example
>>> from datetime import timedelta
>>> delta = timedelta(
...     days=50,
...     seconds=27,
...     microseconds=10,
...     milliseconds=29000,
...     minutes=5,
...     hours=8,
...     weeks=2
... )
>>> # Only days, seconds, and microseconds remain
>>> delta
datetime.timedelta(days=64, seconds=29156, microseconds=10)
@end example

在有任何参数为浮点型并且 microseconds 值为小数的情况下，从所有参数中余下的微秒数将被合并，并使用四舍五入偶不入奇的规则将总计值舍入到最接近的整数微秒值。 如果没有任何参数为浮点型的情况下，则转换和标准化过程将是完全精确的（不会丢失信息）。

如果标准化后的 days 数值超过了指定范围，将会抛出 @ref{a4a,,OverflowError} 异常。

请注意对负数值进行标准化的结果可能会令人感到惊讶。 例如:

@example
>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
@end example
@end deffn

类属性：

@geindex min (datetime.timedelta 属性)
@anchor{library/datetime datetime timedelta min}@anchor{1a2c}
@deffn {属性} timedelta.min

The most negative @ref{2d1,,timedelta} object, @code{timedelta(-999999999)}.
@end deffn

@geindex max (datetime.timedelta 属性)
@anchor{library/datetime datetime timedelta max}@anchor{1a2d}
@deffn {属性} timedelta.max

The most positive @ref{2d1,,timedelta} object, @code{timedelta(days=999999999,
hours=23, minutes=59, seconds=59, microseconds=999999)}.
@end deffn

@geindex resolution (datetime.timedelta 属性)
@anchor{library/datetime datetime timedelta resolution}@anchor{1a2e}
@deffn {属性} timedelta.resolution

两个不相等的 @ref{2d1,,timedelta} 类对象最小的间隔为 @code{timedelta(microseconds=1)}。
@end deffn

需要注意的是，因为标准化的缘故，@code{timedelta.max} > @code{-timedelta.min}，@code{-timedelta.max} 不可以表示一个 @ref{2d1,,timedelta} 类对象。

实例属性（只读）：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

值

@item

@code{days}

@tab

-999999999 至 999999999 ，含999999999

@item

@code{seconds}

@tab

0 至 86399，包含86399

@item

@code{microseconds}

@tab

0 至 999999，包含999999

@end multitable


支持的运算：

@c XXX this table is too wide!


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@item

@code{t1 = t2 + t3}

@tab

@emph{t2} 和 @emph{t3} 的和。 运算后 @emph{t1}-@emph{t2} == @emph{t3} and @emph{t1}-@emph{t3} == @emph{t2} 必为真值。(1)

@item

@code{t1 = t2 - t3}

@tab

@emph{t2} 减 @emph{t3} 的差。 运算后 @emph{t1} == @emph{t2} - @emph{t3} and @emph{t2} == @emph{t1} + @emph{t3} 必为真值。 (1)(6)

@item

@code{t1 = t2 * i or t1 = i * t2}

@tab

乘以一个整数。运算后假如 @code{i != 0} 则 @emph{t1} // i == @emph{t2} 必为真值。

@item

@tab

In general, @emph{t1} * i == @emph{t1} * (i-1) + @emph{t1}
is true. (1)

@item

@code{t1 = t2 * f or t1 = f * t2}

@tab

乘以一个浮点数，结果会被舍入到 timedelta 最接近的整数倍。 精度使用四舍五偶入奇不入规则。

@item

@code{f = t2 / t3}

@tab

总时间 @emph{t2} 除以间隔单位 @emph{t3} (3)。 返回一个 @ref{1fe,,float} 对象。

@item

@code{t1 = t2 / f or t1 = t2 / i}

@tab

除以一个浮点数或整数。 结果会被舍入到 timedelta 最接近的整数倍。 精度使用四舍五偶入奇不入规则。

@item

@code{t1 = t2 // i} or
@code{t1 = t2 // t3}

@tab

计算底数，其余部分（如果有）将被丢弃。在第二种情况下，将返回整数。 （3）

@item

@code{t1 = t2 % t3}

@tab

余数为一个 @ref{2d1,,timedelta} 对象。(3)

@item

@code{q, r = divmod(t1, t2)}

@tab

通过 : @code{q = t1 // t2} (3) and @code{r = t1 % t2} 计算出商和余数。q是一个整数，r是一个 @ref{2d1,,timedelta} 对象。

@item

@code{+t1}

@tab

返回一个相同数值的 @ref{2d1,,timedelta} 对象。

@item

@code{-t1}

@tab

等价于 @ref{2d1,,timedelta}(-@emph{t1.days}, -@emph{t1.seconds}, -@emph{t1.microseconds}), 和 @emph{t1}* -1. (1)(4)

@item

@code{abs(t)}

@tab

当 @code{t.days >= 0`@w{`}时等于 +\ *t*, 当 `@w{`}t.days < 0} 时 -@emph{t} 。 (2)

@item

@code{str(t)}

@tab

返回一个形如 @code{[D day[s], ][H]H:MM:SS[.UUUUUU]} 的字符串，当 @code{t} 为负数的时候，  D 也为负数。 (5)

@item

@code{repr(t)}

@tab

返回一个 @ref{2d1,,timedelta} 对象的字符串表示形式，作为附带正规属性值的构造器调用。

@end multitable


注释:


@enumerate 

@item 
结果正确，但可能会溢出。

@item 
结果正确，不会溢出。

@item 
除以0将会抛出异常  @ref{1fb,,ZeroDivisionError} 。

@item 
-@emph{timedelta.max} 不是一个 @ref{2d1,,timedelta} 类对象。

@item 
@ref{2d1,,timedelta} 对象的字符串表示形式类似于其内部表示形式被规范化。对于负时间增量，这会导致一些不寻常的结果。例如:

@example
>>> timedelta(hours=-5)
datetime.timedelta(days=-1, seconds=68400)
>>> print(_)
-1 day, 19:00:00
@end example

@item 
表达式 @code{t2 - t3} 通常与 @code{t2 + (-t3)} 是等价的，除非 t3 等于 @code{timedelta.max}; 在这种情况下前者会返回结果，而后者则会溢出。
@end enumerate

除了上面列举的操作以外，@ref{2d1,,timedelta} 对象还支持与 @ref{19d,,date} 和 @ref{19f,,datetime} 对象进行特定的相加和相减运算（见下文）。


在 3.2 版更改: 现在已支持 @ref{2d1,,timedelta} 对象与另一个 @ref{2d1,,timedelta} 对象相整除或相除，包括求余运算和 @ref{294,,divmod()} 函数。 现在也支持 @ref{2d1,,timedelta} 对象加上或乘以一个 @ref{1fe,,float} 对象。


支持 @ref{2d1,,timedelta} 对象之间进行比较，但其中有一些注意事项。

@code{==} 或 @code{!=} 比较 @emph{总是} 返回一个 @ref{2c4,,bool} 对象，无论被比较的对象是什么类型:

@example
>>> from datetime import timedelta
>>> delta1 = timedelta(seconds=57)
>>> delta2 = timedelta(hours=25, seconds=2)
>>> delta2 != delta1
True
>>> delta2 == 5
False
@end example

对于所有其他比较 (例如 @code{<} 和 @code{>})，当一个 @ref{2d1,,timedelta} 对象与其他类型的对象比较时，将引发 @ref{1ff,,TypeError}:

@example
>>> delta2 > delta1
True
>>> delta2 > 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'
@end example

在布尔运算中，@ref{2d1,,timedelta} 对象当且仅当其不等于 @code{timedelta(0)} 时则会被视为真值。

实例方法：

@geindex total_seconds() (datetime.timedelta 方法)
@anchor{library/datetime datetime timedelta total_seconds}@anchor{d6c}
@deffn {方法} timedelta.total_seconds ()

返回时间间隔包含了多少秒。造价于 @code{td / timedelta(seconds=1)}。对于其它单位可以直接使用除法的形式 (例如  @code{td / timedelta(microseconds=1)})。

需要注意的是，时间间隔较大时，这个方法的结果中的微秒将会失真（大多数平台上大于270年视为一个较大的时间间隔）。


3.2 新版功能.

@end deffn

@menu
* class;timedelta 用法示例: class timedelta 用法示例. 

@end menu

@node class timedelta 用法示例,,,timedelta 类对象
@anchor{library/datetime examples-of-usage-timedelta}@anchor{1a2f}
@subsubsection class:@cite{timedelta} 用法示例


一个标准化的附加示例:

@example
>>> # Components of another_year add up to exactly 365 days
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)
>>> year == another_year
True
>>> year.total_seconds()
31536000.0
@end example

@ref{2d1,,timedelta} 算术运算的示例:

@example
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> ten_years = 10 * year
>>> ten_years
datetime.timedelta(days=3650)
>>> ten_years.days // 365
10
>>> nine_years = ten_years - year
>>> nine_years
datetime.timedelta(days=3285)
>>> three_years = nine_years // 3
>>> three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
@end example

@node date 对象,datetime 对象,timedelta 类对象,datetime --- 基本日期和时间类型
@anchor{library/datetime date-objects}@anchor{1a30}@anchor{library/datetime datetime-date}@anchor{1a31}
@subsubsection @code{date} 对象


@ref{19d,,date} 对象代表一个理想化历法中的日期（年、月和日），即当今的格列高利历向前后两个方向无限延伸。

公元 1 年 1 月 1日是第 1 日，公元 1 年 1 月 2 日是第 2 日，依此类推。 @footnote{@w{(2)} 
这与 Dershowitz 和 Reingold 所著 @emph{Calendrical Calculations} 中“预期格列高利”历法的定义一致，它是适用于该书中所有运算的基础历法。 请参阅该书了解在预期格利高利历序列与许多其他历法系统之间进行转换的算法。
}

@geindex date (datetime 中的类)
@anchor{library/datetime datetime date}@anchor{19d}
@deffn {类} datetime.date (year, month, day)

所有参数都是必要的。 参数必须是在下面范围内的整数：


@itemize *

@item 
@code{MINYEAR <= year <= MAXYEAR}

@item 
@code{1 <= month <= 12}

@item 
@code{1 <= 日期 <= 给定年月对应的天数}
@end itemize

如果参数不在这些范围内，则抛出 @ref{16d,,ValueError} 异常。
@end deffn

其它构造器，所有的类方法：

@geindex today() (datetime.date 类方法)
@anchor{library/datetime datetime date today}@anchor{1a32}
@deffn {方法} classmethod date.today ()

返回当前的本地日期。

这等价于 @code{date.fromtimestamp(time.time())}。
@end deffn

@geindex fromtimestamp() (datetime.date 类方法)
@anchor{library/datetime datetime date fromtimestamp}@anchor{1a33}
@deffn {方法} classmethod date.fromtimestamp (timestamp)

返回对应于 POSIX 时间戳的当地时间，例如 @ref{436,,time.time()} 返回的就是时间戳。

这可能引发 @ref{a4a,,OverflowError}，如果时间戳数值超出所在平台 C @code{localtime()} 函数的支持范围的话，并且会在 @code{localtime()} 出错时引发 @ref{30b,,OSError}。 通常该数值会被限制在 1970 年至 2038 年之间。 请注意在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 @ref{1a33,,fromtimestamp()} 所忽略。


在 3.3 版更改: 引发 @ref{a4a,,OverflowError} 而不是 @ref{16d,,ValueError}，如果时间戳数值超出所在平台 C @code{localtime()} 函数的支持范围的话，并会在 @code{localtime()} 出错时引发 @ref{30b,,OSError} 而不是 @ref{16d,,ValueError}。

@end deffn

@geindex fromordinal() (datetime.date 类方法)
@anchor{library/datetime datetime date fromordinal}@anchor{1a34}
@deffn {方法} classmethod date.fromordinal (ordinal)

返回对应于预期格列高利历序号的日期，其中公元 1 年 1 月 1 晶的序号为 1。

除非 @code{1 <= ordinal <= date.max.toordinal()} 否则会引发 @ref{16d,,ValueError}。对于任意日期 @emph{d}，@code{date.fromordinal(d.toordinal()) == d}。
@end deffn

@geindex fromisoformat() (datetime.date 类方法)
@anchor{library/datetime datetime date fromisoformat}@anchor{1214}
@deffn {方法} classmethod date.fromisoformat (date_string)

返回一个对应于以 @code{YYYY-MM-DD} 格式给出的 @emph{date_string} 的 @ref{19d,,date} 对象:

@example
>>> from datetime import date
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)
@end example

这是 @ref{1a35,,date.isoformat()} 的逆操作。 它只支持 @code{YYYY-MM-DD} 格式。


3.7 新版功能.

@end deffn

@geindex fromisocalendar() (datetime.date 类方法)
@anchor{library/datetime datetime date fromisocalendar}@anchor{2fc}
@deffn {方法} classmethod date.fromisocalendar (year, week, day)

返回指定 year, week 和 day 所对应 ISO 历法日期的 @ref{19d,,date}。 这是函数 @ref{19e,,date.isocalendar()} 的逆操作。


3.8 新版功能.

@end deffn

类属性：

@geindex min (datetime.date 属性)
@anchor{library/datetime datetime date min}@anchor{1a36}
@deffn {属性} date.min

最小的日期 @code{date(MINYEAR, 1, 1)} 。
@end deffn

@geindex max (datetime.date 属性)
@anchor{library/datetime datetime date max}@anchor{1a37}
@deffn {属性} date.max

最大的日期 ，@code{date(MAXYEAR, 12, 31)}。
@end deffn

@geindex resolution (datetime.date 属性)
@anchor{library/datetime datetime date resolution}@anchor{1a38}
@deffn {属性} date.resolution

两个日期对象的最小间隔，@code{timedelta(days=1)}。
@end deffn

实例属性（只读）：

@geindex year (datetime.date 属性)
@anchor{library/datetime datetime date year}@anchor{1a18}
@deffn {属性} date.year

在 @ref{1a15,,MINYEAR} 和 @ref{1a16,,MAXYEAR} 之间，包含边界。
@end deffn

@geindex month (datetime.date 属性)
@anchor{library/datetime datetime date month}@anchor{1a19}
@deffn {属性} date.month

1 至 12（含）
@end deffn

@geindex day (datetime.date 属性)
@anchor{library/datetime datetime date day}@anchor{1a1a}
@deffn {属性} date.day

返回1到指定年月的天数间的数字。
@end deffn

支持的运算：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@item

@code{date2 = date1 + timedelta}

@tab

@emph{date2} 等于从 @emph{date1} 减去 @code{timedelta.days} 天。 (1)

@item

@code{date2 = date1 - timedelta}

@tab

计算 @emph{date2} 的值使得 @code{date2 + timedelta == date1}。 (2)

@item

@code{timedelta = date1 - date2}

@tab

(3)

@item

@code{date1 < date2}

@tab

如果 @emph{date1} 的时间在 @emph{date2} 之前则认为 @emph{date1} 小于 @emph{date2} 。 (4)

@end multitable


注释:


@enumerate 

@item 
如果 @code{timedelta.days > 0} 则 @emph{date2} 将在时间线上前进，如果 @code{timedelta.days < 0} 则将后退。 操作完成后 @code{date2 - date1 == timedelta.days}。 @code{timedelta.seconds} 和 @code{timedelta.microseconds} 会被忽略。 如果 @code{date2.year} 将小于 @ref{1a15,,MINYEAR} 或大于 @ref{1a16,,MAXYEAR} 则会引发 @ref{a4a,,OverflowError}。

@item 
@code{timedelta.seconds} 和 @code{timedelta.microseconds} 会被忽略。

@item 
此值完全精确且不会溢出。 操作完成后 timedelta.seconds 和 timedelta.microseconds 均为 0，并且 date2 + timedelta == date1。

@item 
换句话说，当且仅当 @code{date1.toordinal() < date2.toordinal()} 时 @code{date1 < date2}。 日期比较会引发 @ref{1ff,,TypeError}，如果比较目标不为 @ref{19d,,date} 对象的话。 不过也可能会返回 @code{NotImplemented}，如果比较目标具有 @code{timetuple()} 属性的话。 这个钩子给予其他日期对象类型实现混合类型比较的机会。 否则，当 @ref{19d,,date} 对象与不同类型的对象比较时将会引发 @ref{1ff,,TypeError}，除非是 @code{==} 或 @code{!=} 比较。 后两种情况将分别返回 @ref{497,,False} 或 @ref{59c,,True}。
@end enumerate

在布尔运算中，所有 @ref{19d,,date} 对象都会被视为真值。

实例方法：

@geindex replace() (datetime.date 方法)
@anchor{library/datetime datetime date replace}@anchor{1a39}
@deffn {方法} date.replace (year=self.year, month=self.month, day=self.day)

返回一个具有同样值的日期，除非通过任何关键字参数给出了某些形参的新值。

示例:

@example
>>> from datetime import date
>>> d = date(2002, 12, 31)
>>> d.replace(day=26)
datetime.date(2002, 12, 26)
@end example
@end deffn

@geindex timetuple() (datetime.date 方法)
@anchor{library/datetime datetime date timetuple}@anchor{1a3a}
@deffn {方法} date.timetuple ()

返回一个 @ref{69a,,time.struct_time}，即 @ref{10c9,,time.localtime()} 所返回的类型。

hours, minutes 和 seconds 值均为 0，且 DST 旗标值为 -1。

@code{d.timetuple()} 等价于:

@example
time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
@end example

其中 @code{yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1} 是当前年份中的日期序号，1 月 1 日的序号为 @code{1}。
@end deffn

@geindex toordinal() (datetime.date 方法)
@anchor{library/datetime datetime date toordinal}@anchor{1a3b}
@deffn {方法} date.toordinal ()

返回日期的预期格列高利历序号，其中公元 1 年 1 月 1 日的序号为 1。 对于任意 @ref{19d,,date} 对象 @emph{d}，@code{date.fromordinal(d.toordinal()) == d}。
@end deffn

@geindex weekday() (datetime.date 方法)
@anchor{library/datetime datetime date weekday}@anchor{1a3c}
@deffn {方法} date.weekday ()

返回一个整数代表星期几，星期一为0，星期天为6。例如， @code{date(2002, 12, 4).weekday() == 2}，表示的是星期三。参阅 @ref{1a3d,,isoweekday()}。
@end deffn

@geindex isoweekday() (datetime.date 方法)
@anchor{library/datetime datetime date isoweekday}@anchor{1a3d}
@deffn {方法} date.isoweekday ()

返回一个整数代表星期几，星期一为1，星期天为7。例如：@code{date(2002, 12, 4).isoweekday() == 3},表示星期三。参见 @ref{1a3c,,weekday()}, @ref{19e,,isocalendar()}。
@end deffn

@geindex isocalendar() (datetime.date 方法)
@anchor{library/datetime datetime date isocalendar}@anchor{19e}
@deffn {方法} date.isocalendar ()

返回一个由三部分组成的 @ref{b84,,named tuple} 对象: @code{year}, @code{week} 和 @code{weekday}。

ISO 历法是一种被广泛使用的格列高利历。 @footnote{@w{(3)} 
请参阅 R. H. van Gent 所著 ` ISO 8601 历法的数学指导 <@indicateurl{https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm}>`_ 以获取更完整的说明。
}

ISO 年由 52 或 53 个完整星期构成，每个星期开始于星期一结束于星期日。 一个 ISO 年的第一个星期就是（格列高利）历法的一年中第一个包含星期四的星期。 这被称为 1 号星期，这个星期四所在的 ISO 年与其所在的格列高利年相同。

例如，2004 年的第一天是星期四，因此 ISO 2004 年的第一个星期开始于 2003 年 12 月 29 日星期一，结束于 2004 年 1 月 4 日星期日:

@example
>>> from datetime import date
>>> date(2003, 12, 29).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=1)
>>> date(2004, 1, 4).isocalendar()
datetime.IsoCalendarDate(year=2004, week=1, weekday=7)
@end example


在 3.9 版更改: 结果由元组改为 @ref{b84,,named tuple}。

@end deffn

@geindex isoformat() (datetime.date 方法)
@anchor{library/datetime datetime date isoformat}@anchor{1a35}
@deffn {方法} date.isoformat ()

返回一个以 ISO 8601 格式 @code{YYYY-MM-DD} 来表示日期的字符串:

@example
>>> from datetime import date
>>> date(2002, 12, 4).isoformat()
'2002-12-04'
@end example

这是 @ref{1214,,date.fromisoformat()} 的逆操作。
@end deffn

@geindex __str__() (datetime.date 方法)
@anchor{library/datetime datetime date __str__}@anchor{1a3e}
@deffn {方法} date.__str__ ()

对于日期对象 @emph{d}, @code{str(d)} 等价于 @code{d.isoformat()} 。
@end deffn

@geindex ctime() (datetime.date 方法)
@anchor{library/datetime datetime date ctime}@anchor{1a3f}
@deffn {方法} date.ctime ()

返回一个表示日期的字符串:

@example
>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
@end example

@code{d.ctime()} 等效于:

@example
time.ctime(time.mktime(d.timetuple()))
@end example

在原生 C @code{ctime()} 函数 (@ref{1a40,,time.ctime()} 会发起调用该函数，但 @ref{1a3f,,date.ctime()} 则不会) 遵循 C 标准的平台上。
@end deffn

@geindex strftime() (datetime.date 方法)
@anchor{library/datetime datetime date strftime}@anchor{63a}
@deffn {方法} date.strftime (format)

返回一个由显式格式字符串所指明的代表日期的字符串。 表示时、分或秒的格式代码值将为 0。 要获取格式指令的完整列表请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@geindex __format__() (datetime.date 方法)
@anchor{library/datetime datetime date __format__}@anchor{1a42}
@deffn {方法} date.__format__ (format)

与 @ref{63a,,date.strftime()} 相同。 此方法使得为 @ref{19d,,date} 对象指定以 @ref{29d,,格式化字符串字面值} 表示的格式化字符串以及使用 @ref{5dd,,str.format()} 进行格式化成为可能。 要获取格式指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@menu
* class;date 用法示例: class date 用法示例. 

@end menu

@node class date 用法示例,,,date 对象
@anchor{library/datetime examples-of-usage-date}@anchor{1a43}
@subsubsection class:@cite{date} 用法示例


计算距离特定事件天数的例子:

@example
>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
202
@end example

使用 @ref{19d,,date} 的更多例子：

@example
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)

>>> # Methods related to formatting string output
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> d.ctime()
'Mon Mar 11 00:00:00 2002'
>>> 'The @{1@} is @{0:%d@}, the @{2@} is @{0:%B@}.'.format(d, "day", "month")
'The day is 11, the month is March.'

>>> # Methods for to extracting 'components' under different calendars
>>> t = d.timetuple()
>>> for i in t:     
...     print(i)
2002                # year
3                   # month
11                  # day
0
0
0
0                   # weekday (0 = Monday)
70                  # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:    
...     print(i)
2002                # ISO year
11                  # ISO week number
1                   # ISO day number ( 1 = Monday )

>>> # A date object is immutable; all operations produce a new object
>>> d.replace(year=2005)
datetime.date(2005, 3, 11)
@end example

@node datetime 对象,time 对象,date 对象,datetime --- 基本日期和时间类型
@anchor{library/datetime datetime-datetime}@anchor{1a44}@anchor{library/datetime datetime-objects}@anchor{1a45}
@subsubsection @code{datetime} 对象


@ref{19f,,datetime} 对象是包含来自 @ref{19d,,date} 对象和 @ref{5f5,,time} 对象的所有信息的单一对象。

与 @ref{19d,,date} 对象一样，@ref{19f,,datetime} 假定当前的格列高利历向前后两个方向无限延伸；与 @ref{5f5,,time} 对象一样，@ref{19f,,datetime} 假定每一天恰好有 3600*24 秒。

构造器 ：

@geindex datetime (datetime 中的类)
@anchor{library/datetime datetime datetime}@anchor{19f}
@deffn {类} datetime.datetime (year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

@emph{year}, @emph{month} 和 @emph{day} 参数是必须的。 @emph{tzinfo} 可以是 @code{None} 或者是一个 @ref{180,,tzinfo} 子类的实例。 其余的参数必须是在下面范围内的整数：


@itemize *

@item 
@code{MINYEAR <= year <= MAXYEAR},

@item 
@code{1 <= month <= 12},

@item 
@code{1 <= day <= 指定年月的天数},

@item 
@code{0 <= hour < 24},

@item 
@code{0 <= minute < 60},

@item 
@code{0 <= second < 60},

@item 
@code{0 <= microsecond < 1000000},

@item 
@code{fold in [0, 1]}.
@end itemize

如果参数不在这些范围内，则抛出 @ref{16d,,ValueError} 异常。


3.6 新版功能: 增加了 @code{fold} 参数。

@end deffn

其它构造器，所有的类方法：

@geindex today() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime today}@anchor{1a46}
@deffn {方法} classmethod datetime.today ()

返回表示当前地方时的 datetime 对象，其中 @ref{1a27,,tzinfo} 为 @code{None}。

等价于:

@example
datetime.fromtimestamp(time.time())
@end example

另请参阅 @ref{1184,,now()}, @ref{f75,,fromtimestamp()}。

此方法的功能等价于 @ref{1184,,now()}，但是不带 @code{tz} 形参。
@end deffn

@geindex now() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime now}@anchor{1184}
@deffn {方法} classmethod datetime.now (tz=None)

返回表示当前地方时的 date 和 time 对象。

如果可选参数 @emph{tz} 为 @code{None} 或未指定，这就类似于 @ref{1a46,,today()}，但该方法会在可能的情况下提供比通过 @ref{436,,time.time()} 时间戳所获时间值更高的精度（例如，在提供了 C @code{gettimeofday()} 函数的平台上就可以做到这一点）。

如果 @emph{tz} 不为 @code{None}，它必须是 @ref{180,,tzinfo} 子类的一个实例，并且当前日期和时间将被转换到 @emph{tz} 时区。

此函数可以替代 @ref{1a46,,today()} 和 @ref{1a47,,utcnow()}。
@end deffn

@geindex utcnow() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime utcnow}@anchor{1a47}
@deffn {方法} classmethod datetime.utcnow ()

返回表示当前 UTC 时间的 date 和 time，其中 @ref{1a27,,tzinfo} 为 @code{None}。

这类似于 @ref{1184,,now()}，但返回的是当前 UTC 日期和时间，类型为简单型 @ref{19f,,datetime} 对象。 感知型的当前 UTC 日期时间可通过调用 @code{datetime.now(timezone.utc)} 来获得。 另请参阅 @ref{1184,,now()}。

@cartouche
@quotation 警告 
由于简单型 @code{datetime} 对象会被许多 @code{datetime} 方法当作本地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因此，创建表示当前 UTC 时间的对象的推荐方式是通过调用 @code{datetime.now(timezone.utc)}。
@end quotation
@end cartouche
@end deffn

@geindex fromtimestamp() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime fromtimestamp}@anchor{f75}
@deffn {方法} classmethod datetime.fromtimestamp (timestamp, tz=None)

返回对应于 POSIX 时间戳例如 @ref{436,,time.time()} 的返回值的本地日期和时间。 如果可选参数 @emph{tz} 为 @code{None} 或未指定，时间戳会被转换为所在平台的本地日期和时间，返回的 @ref{19f,,datetime} 对象将为天真型。

如果 @emph{tz} 不为 @code{None}，它必须是 @ref{180,,tzinfo} 子类的一个实例，并且时间戳将被转换到 @emph{tz} 指定的时区。

@ref{f75,,fromtimestamp()} 可能会引发 @ref{a4a,,OverflowError}，如果时间戳数值超出所在平台 C @code{localtime()} 或 @code{gmtime()} 函数的支持范围的话，并会在 @code{localtime()} 或 @code{gmtime()} 报错时引发 @ref{30b,,OSError}。 通常该数值会被限制在 1970 年至 2038 年之间。 请注意在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 @ref{f75,,fromtimestamp()} 所忽略，结果可能导致两个相差一秒的时间戳产生相同的 @ref{19f,,datetime} 对象。 相比 @ref{f6f,,utcfromtimestamp()} 更推荐使用此方法。


在 3.3 版更改: 引发 @ref{a4a,,OverflowError} 而不是 @ref{16d,,ValueError}，如果时间戳数值超出所在平台 C @code{localtime()} 或 @code{gmtime()} 函数的支持范围的话。 并会在 @code{localtime()} 或 @code{gmtime()} 出错时引发 @ref{30b,,OSError} 而不是 @ref{16d,,ValueError}。



在 3.6 版更改: @ref{f75,,fromtimestamp()} 可能返回 @ref{5f6,,fold} 值设为 1 的实例。

@end deffn

@geindex utcfromtimestamp() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime utcfromtimestamp}@anchor{f6f}
@deffn {方法} classmethod datetime.utcfromtimestamp (timestamp)

返回对应于 POSIX 时间戳的 UTC @ref{19f,,datetime}，其中 @ref{1a27,,tzinfo} 值为 @code{None}。 （结果为简单型对象。）

这可能引发 @ref{a4a,,OverflowError}，如果时间戳数值超出所在平台 C @code{gmtime()} 函数的支持范围的话，并会在 @code{gmtime()} 报错时引发 @ref{30b,,OSError}。 通常该数值会被限制在 1970 至 2038 年之间。

要得到一个感知型 @ref{19f,,datetime} 对象，应调用 @ref{f75,,fromtimestamp()}:

@example
datetime.fromtimestamp(timestamp, timezone.utc)
@end example

在 POSIX 兼容的平台上，它等价于以下表达式:

@example
datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
@end example

不同之处在于后一种形式总是支持完整年份范围：从 @ref{1a15,,MINYEAR} 到 @ref{1a16,,MAXYEAR} 的开区间。

@cartouche
@quotation 警告 
由于简单型 @code{datetime} 对象会被许多 @code{datetime} 方法当作本地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因此，创建表示特定 UTC 时间戳的日期时间对象的推荐方式是通过调用 @code{datetime.fromtimestamp(timestamp, tz=timezone.utc)}。
@end quotation
@end cartouche


在 3.3 版更改: 引发 @ref{a4a,,OverflowError} 而不是 @ref{16d,,ValueError}，如果时间戳数值超出所在平台 C @code{gmtime()} 函数的支持范围的话。 并会在 @code{gmtime()} 出错时引发 @ref{30b,,OSError} 而不是 @ref{16d,,ValueError}。

@end deffn

@geindex fromordinal() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime fromordinal}@anchor{1a48}
@deffn {方法} classmethod datetime.fromordinal (ordinal)

返回对应于预期格列高利历序号的 @ref{19f,,datetime}，其中公元 1 年 1 月 1 日的序号为 1。 除非 @code{1 <= ordinal <= datetime.max.toordinal()} 否则会引发 @ref{16d,,ValueError}。 结果的 hour, minute, second 和 microsecond 值均为 0，并且 @ref{1a27,,tzinfo} 值为 @code{None}。
@end deffn

@geindex combine() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime combine}@anchor{63c}
@deffn {方法} classmethod datetime.combine (date, time, tzinfo=self.tzinfo)

返回一个新的 @ref{19f,,datetime} 对象，对象的日期部分等于给定的 @ref{19d,,date} 对象的值，而其时间部分等于给定的 @ref{5f5,,time} 对象的值。 如果提供了 @emph{tzinfo} 参数，其值会被用来设置结果的 @ref{1a27,,tzinfo} 属性，否则将使用 @emph{time} 参数的 @ref{1a1f,,tzinfo} 属性。

对于任意 @ref{19f,,datetime} 对象 @emph{d}，@code{d == datetime.combine(d.date(), d.time(), d.tzinfo)}。 如果 date 是一个 @ref{19f,,datetime} 对象，它的时间部分和 @ref{1a27,,tzinfo} 属性会被忽略。


在 3.6 版更改: 增加了 @emph{tzinfo} 参数。

@end deffn

@geindex fromisoformat() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime fromisoformat}@anchor{48f}
@deffn {方法} classmethod datetime.fromisoformat (date_string)

返回一个对应于 @ref{1a35,,date.isoformat()} 和 @ref{63b,,datetime.isoformat()} 所提供的某一种 @emph{date_string} 的 @ref{19f,,datetime} 对象。

特别地，此函数支持以下格式的字符串：

@example
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
@end example

其中 @code{*} 可以匹配任意的单个字符。

@cartouche
@quotation 警告 
此函数 @emph{并不} 支持解析任意 ISO 8601 字符串 —— 它的目的只是作为 @ref{63b,,datetime.isoformat()} 的逆操作。 在第三方包 dateutil@footnote{https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse} 中提供了一个更完善的 ISO 8601 解析器 @code{dateutil.parser.isoparse}。
@end quotation
@end cartouche

示例:

@example
>>> from datetime import datetime
>>> datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
>>> datetime.fromisoformat('2011-11-04T00:05:23')
datetime.datetime(2011, 11, 4, 0, 5, 23)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')   
datetime.datetime(2011, 11, 4, 0, 5, 23,
    tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
@end example


3.7 新版功能.

@end deffn

@geindex fromisocalendar() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime fromisocalendar}@anchor{2fd}
@deffn {方法} classmethod datetime.fromisocalendar (year, week, day)

返回以 year, week 和 day 值指明的 ISO 历法日期所对应的 @ref{19f,,datetime}。 该datetime 对象的非日期部分将使用其标准默认值来填充。 这是函数 @ref{1a0,,datetime.isocalendar()} 的逆操作。


3.8 新版功能.

@end deffn

@geindex strptime() (datetime.datetime 类方法)
@anchor{library/datetime datetime datetime strptime}@anchor{fdc}
@deffn {方法} classmethod datetime.strptime (date_string, format)

返回一个对应于 @emph{date_string}，根据 @emph{format} 进行解析得到的 @ref{19f,,datetime} 对象。

这相当于:

@example
datetime(*(time.strptime(date_string, format)[0:6]))
@end example

如果 date_string 和 format 无法被 @ref{e5e,,time.strptime()} 解析或它返回一个不是时间元组的值，则将引发 @ref{16d,,ValueError}。 要获取格式化指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

类属性：

@geindex min (datetime.datetime 属性)
@anchor{library/datetime datetime datetime min}@anchor{f70}
@deffn {属性} datetime.min

最早的可表示 @ref{19f,,datetime}，@code{datetime(MINYEAR, 1, 1, tzinfo=None)}。
@end deffn

@geindex max (datetime.datetime 属性)
@anchor{library/datetime datetime datetime max}@anchor{1a49}
@deffn {属性} datetime.max

最晚的可表示 @ref{19f,,datetime}，@code{datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)}。
@end deffn

@geindex resolution (datetime.datetime 属性)
@anchor{library/datetime datetime datetime resolution}@anchor{1a4a}
@deffn {属性} datetime.resolution

两个不相等的 @ref{19f,,datetime} 对象之间可能的最小间隔，@code{timedelta(microseconds=1)}。
@end deffn

实例属性（只读）：

@geindex year (datetime.datetime 属性)
@anchor{library/datetime datetime datetime year}@anchor{1a20}
@deffn {属性} datetime.year

在 @ref{1a15,,MINYEAR} 和 @ref{1a16,,MAXYEAR} 之间，包含边界。
@end deffn

@geindex month (datetime.datetime 属性)
@anchor{library/datetime datetime datetime month}@anchor{1a21}
@deffn {属性} datetime.month

1 至 12（含）
@end deffn

@geindex day (datetime.datetime 属性)
@anchor{library/datetime datetime datetime day}@anchor{1a22}
@deffn {属性} datetime.day

返回1到指定年月的天数间的数字。
@end deffn

@geindex hour (datetime.datetime 属性)
@anchor{library/datetime datetime datetime hour}@anchor{1a23}
@deffn {属性} datetime.hour

取值范围是 @code{range(24)}。
@end deffn

@geindex minute (datetime.datetime 属性)
@anchor{library/datetime datetime datetime minute}@anchor{1a24}
@deffn {属性} datetime.minute

取值范围是 @code{range(60)}。
@end deffn

@geindex second (datetime.datetime 属性)
@anchor{library/datetime datetime datetime second}@anchor{1a25}
@deffn {属性} datetime.second

取值范围是 @code{range(60)}。
@end deffn

@geindex microsecond (datetime.datetime 属性)
@anchor{library/datetime datetime datetime microsecond}@anchor{1a26}
@deffn {属性} datetime.microsecond

取值范围是 @code{range(1000000)}。
@end deffn

@geindex tzinfo (datetime.datetime 属性)
@anchor{library/datetime datetime datetime tzinfo}@anchor{1a27}
@deffn {属性} datetime.tzinfo

作为 @emph{tzinfo} 参数被传给 @ref{19f,,datetime} 构造器的对象，如果没有传入值则为 @code{None}。
@end deffn

@geindex fold (datetime.datetime 属性)
@anchor{library/datetime datetime datetime fold}@anchor{5f6}
@deffn {属性} datetime.fold

取值范围是 @code{[0, 1]}。 用于在重复的时间段中消除边界时间歧义。 （当夏令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边界时间。


3.6 新版功能.

@end deffn

支持的运算：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

结果

@item

@code{datetime2 = datetime1 + timedelta}

@tab

(1)

@item

@code{datetime2 = datetime1 - timedelta}

@tab

(2)

@item

@code{timedelta = datetime1 - datetime2}

@tab

(3)

@item

@code{datetime1 < datetime2}

@tab

比较 @ref{19f,,datetime} 与 @ref{19f,,datetime}。 (4)

@end multitable



@enumerate 

@item 
datetime2 是从 datetime1 去掉了一段 timedelta 的结果，如果 @code{timedelta.days} > 0 则是在时间线上前进，如果 @code{timedelta.days} < 0 则是在时间线上后退。 该结果具有与输入的 datetime 相同的 @ref{1a27,,tzinfo} 属性，并且操作完成后 datetime2 - datetime1 == timedelta。 如果 datetime2.year 将要小于 @ref{1a15,,MINYEAR} 或大于 @ref{1a16,,MAXYEAR} 则会引发 @ref{a4a,,OverflowError}。 请注意即使输入的是一个感知型对象，该方法也不会进行时区调整。

@item 
计算 datetime2 使得 datetime2 + timedelta == datetime1。 与相加操作一样，结果具有与输入的 datetime 相同的 @ref{1a27,,tzinfo} 属性，即使输入的是一个感知型对象，该方法也不会进行时区调整。

@item 
从一个 @ref{19f,,datetime} 减去一个 @ref{19f,,datetime} 仅对两个操作数均为简单型或均为感知型时有定义。 如果一个是感知型而另一个是简单型，则会引发 @ref{1ff,,TypeError}。

如果两个操作数都是简单型，或都是感知型并且具有相同的 @ref{1a27,,tzinfo} 属性，则 @ref{1a27,,tzinfo} 属性会被忽略，并且结果会是一个使得 @code{datetime2 + t == datetime1} 的 @ref{2d1,,timedelta} 对象 @emph{t}。 在此情况下不会进行时区调整。

如果两个操作数都是感知型且具有不同的 @ref{1a27,,tzinfo} 属性，@code{a-b} 操作的效果就如同 @emph{a} 和 @emph{b} 首先被转换为简单型 UTC 日期时间。 结果将是 @code{(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset())}，除非具体实现绝对不溢出。

@item 
当 @emph{datetime1} 的时间在 @emph{datetime2} 之前则认为 @emph{datetime1} 小于 @emph{datetime2}。

如果比较的一方是简单型而另一方是感知型，则如果尝试进行顺序比较将引发 @ref{1ff,,TypeError}。 对于相等比较，简单型实例将永远不等于感知型实例。

如果两个比较方都是感知型，且具有相同的 @ref{1a27,,tzinfo} 属性，则相同的 @ref{1a27,,tzinfo} 属性会被忽略并对基本日期时间值进行比较。 如果两个比较方都是感知型且具有不同的 @ref{1a27,,tzinfo} 属性，则两个比较方将首先通过减去它们的 UTC 差值（使用 @code{self.utcoffset()} 获取）来进行调整。


在 3.3 版更改: 感知型和简单型 @ref{19f,,datetime} 实例之间的相等比较不会引发 @ref{1ff,,TypeError}。


@cartouche
@quotation 注解 
为了防止比较操作回退为默认的对象地址比较方式，datetime 比较通常会引发 @ref{1ff,,TypeError}，如果比较目标不同样为 @ref{19f,,datetime} 对象的话。 不过也可能会返回 @code{NotImplemented}，如果比较目标具有 @code{timetuple()} 属性的话。 这个钩子给予其他种类的日期对象实现混合类型比较的机会。 如果未实现，则当 @ref{19f,,datetime} 对象与不同类型比较时将会引发 @ref{1ff,,TypeError}，除非是 @code{==} 或 @code{!=} 比较。 后两种情况将分别返回 @ref{497,,False} 或 @ref{59c,,True}。
@end quotation
@end cartouche
@end enumerate

实例方法：

@geindex date() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime date}@anchor{1a4b}
@deffn {方法} datetime.date ()

返回具有同样 year, month 和 day 值的 @ref{19d,,date} 对象。
@end deffn

@geindex time() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime time}@anchor{1a4c}
@deffn {方法} datetime.time ()

返回具有同样 hour, minute, second, microsecond 和 fold 值的 @ref{5f5,,time} 对象。 @ref{1a27,,tzinfo} 值为 @code{None}。 另请参见 @ref{1a4d,,timetz()} 方法。


在 3.6 版更改: fold 值会被复制给返回的 @ref{5f5,,time} 对象。

@end deffn

@geindex timetz() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime timetz}@anchor{1a4d}
@deffn {方法} datetime.timetz ()

返回具有同样 hour, minute, second, microsecond, fold 和 tzinfo 属性性的 @ref{5f5,,time} 对象。 另请参见 @ref{10c,,time()} 方法。


在 3.6 版更改: fold 值会被复制给返回的 @ref{5f5,,time} 对象。

@end deffn

@geindex replace() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime replace}@anchor{1a4e}
@deffn {方法} datetime.replace (year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)

返回一个具有同样属性值的 datetime，除非通过任何关键字参数为某些属性指定了新值。 请注意可以通过指定 @code{tzinfo=None} 来从一个感知型 datetime 创建一个简单型 datetime 而不必转换日期和时间数据。


3.6 新版功能: 增加了 @code{fold} 参数。

@end deffn

@geindex astimezone() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime astimezone}@anchor{2d2}
@deffn {方法} datetime.astimezone (tz=None)

返回一个具有新的 @ref{1a27,,tzinfo} 属性 @emph{tz} 的 @ref{19f,,datetime} 对象，并会调整日期和时间数据使得结果对应的 UTC 时间与 @emph{self} 相同，但为 @emph{tz} 时区的本地时间。

如果给出了 @emph{tz}，则它必须是一个 @ref{180,,tzinfo} 子类的实例，并且其 @ref{1a4f,,utcoffset()} 和 @ref{1a50,,dst()} 方法不可返回 @code{None}。 如果 @emph{self} 为简单型，它会被假定为基于系统时区表示的时间。

如果调用时不传入参数 (或传入 @code{tz=None}) 则将假定目标时区为系统的本地时区。 转换后 datetime 实例的 @code{.tzinfo} 属性将被设为一个 @ref{ae9,,timezone} 实例，时区名称和时差值将从 OS 获取。

如果 @code{self.tzinfo} 为 @emph{tz}，@code{self.astimezone(tz)} 等于 @emph{self}: 不会对日期或时间数据进行调整。 否则结果为 @emph{tz} 时区的本地时间，代表的 UTC 时间与 @emph{self} 相同：在 @code{astz = dt.astimezone(tz)} 之后，@code{astz - astz.utcoffset()} 将具有与 @code{dt - dt.utcoffset()} 相同的日期和时间数据。

如果你只是想要附加一个时区对象 @emph{tz} 到一个 datetime 对象 @emph{dt} 而不调整日期和时间数据，请使用 @code{dt.replace(tzinfo=tz)}。 如果你只想从一个感知型 datetime 对象 @emph{dt} 移除时区对象，请使用 @code{dt.replace(tzinfo=None)}。

请注意默认的 @ref{1a51,,tzinfo.fromutc()} 方法在 @ref{180,,tzinfo} 的子类中可以被重载，从而影响 @ref{2d2,,astimezone()} 的返回结果。 如果忽略出错的情况，@ref{2d2,,astimezone()} 的行为就类似于:

@example
def astimezone(self, tz):
    if self.tzinfo is tz:
        return self
    # Convert self to UTC, and attach the new time zone object.
    utc = (self - self.utcoffset()).replace(tzinfo=tz)
    # Convert from UTC to tz's local time.
    return tz.fromutc(utc)
@end example


在 3.3 版更改: @emph{tz} 现在可以被省略。



在 3.6 版更改: @ref{2d2,,astimezone()} 方法可以由简单型实例调用，这将假定其表示本地时间。

@end deffn

@geindex utcoffset() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime utcoffset}@anchor{1a4f}
@deffn {方法} datetime.utcoffset ()

如果 @ref{1a27,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.utcoffset(self)}，并且在后者不返回 @code{None} 或者一个幅度小于一天的 @ref{2d1,,timedelta} 对象时将引发异常。


在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

@end deffn

@geindex dst() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime dst}@anchor{1a50}
@deffn {方法} datetime.dst ()

如果 @ref{1a27,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.dst(self)}，并且在后者不返回 @code{None} 或者一个幅度小于一天的 @ref{2d1,,timedelta} 对象时将引发异常。


在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

@end deffn

@geindex tzname() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime tzname}@anchor{1a52}
@deffn {方法} datetime.tzname ()

如果 @ref{1a27,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.tzname(self)}，如果后者不返回 @code{None} 或者一个字符串对象则将引发异常。
@end deffn

@geindex timetuple() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime timetuple}@anchor{1a53}
@deffn {方法} datetime.timetuple ()

返回一个 @ref{69a,,time.struct_time}，即 @ref{10c9,,time.localtime()} 所返回的类型。

@code{d.timetuple()} 等价于:

@example
time.struct_time((d.year, d.month, d.day,
                  d.hour, d.minute, d.second,
                  d.weekday(), yday, dst))
@end example

其中 @code{yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1} 是日期在当前年份中的序号，起始序号 @code{1} 表示 1 月 1 日。 结果的 @code{tm_isdst} 旗标的设定会依据 @ref{1a50,,dst()} 方法：如果 @ref{1a27,,tzinfo} 为 @code{None} 或 @ref{1a50,,dst()} 返回 @code{None}，则 @code{tm_isdst} 将设为 @code{-1}；否则如果 @ref{1a50,,dst()} 返回一个非零值，则 @code{tm_isdst} 将设为 @code{1}；在其他情况下 @code{tm_isdst} 将设为 @code{0}。
@end deffn

@geindex utctimetuple() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime utctimetuple}@anchor{1a54}
@deffn {方法} datetime.utctimetuple ()

如果 @ref{19f,,datetime} 实例 @emph{d} 为简单型，这类似于 @code{d.timetuple()}，不同之处在于 @code{tm_isdst} 会强制设为 0，无论 @code{d.dst()} 返回什么结果。 DST 对于 UTC 时间永远无效。

如果 @emph{d} 为感知型， @emph{d} 会通过减去 @code{d.utcoffset()} 来标准化为 UTC 时间，并返回该标准化时间所对应的 @ref{69a,,time.struct_time}。 @code{tm_isdst} 会强制设为 0。 请注意如果 @emph{d}.year 为 @code{MINYEAR} 或 @code{MAXYEAR} 并且 UTC 调整超出一年的边界则可能引发 @ref{a4a,,OverflowError}。

@cartouche
@quotation 警告 
由于简单型 @code{datetime} 对象会被许多 @code{datetime} 方法当作本地时间来处理，最好是使用感知型日期时间来表示 UTC 时间；因此，使用 @code{utcfromtimetuple} 可能会给出误导性的结果。 如果你有一个表示 UTC 的简单型 @code{datetime}，请使用 @code{datetime.replace(tzinfo=timezone.utc)} 将其改为感知型，这样你才能使用 @ref{1a53,,datetime.timetuple()}。
@end quotation
@end cartouche
@end deffn

@geindex toordinal() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime toordinal}@anchor{1a55}
@deffn {方法} datetime.toordinal ()

返回日期的预期格列高利历序号。 与 @code{self.date().toordinal()} 相同。
@end deffn

@geindex timestamp() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime timestamp}@anchor{aca}
@deffn {方法} datetime.timestamp ()

返回对应于 @ref{19f,,datetime} 实例的 POSIX 时间戳。 此返回值是与 @ref{436,,time.time()} 返回值类似的 @ref{1fe,,float} 对象。

简单型 @ref{19f,,datetime} 实例会假定为代表本地时间，并且此方法依赖于平台的 C @code{mktime()} 函数来执行转换。 由于在许多平台上 @ref{19f,,datetime} 支持的范围比 @code{mktime()} 更广，对于极其遥远的过去或未来此方法可能引发 @ref{a4a,,OverflowError}。

对于感知型 @ref{19f,,datetime} 实例，返回值的计算方式为:

@example
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
@end example


3.3 新版功能.



在 3.6 版更改: @ref{aca,,timestamp()} 方法使用 @ref{5f6,,fold} 属性来消除重复间隔中的时间歧义。


@cartouche
@quotation 注解 
没有一个方法能直接从表示 UTC 时间的简单型 @ref{19f,,datetime} 实例获取 POSIX 时间戳。 如果你的应用程序使用此惯例并且你的系统时区不是设为 UTC，你可以通过提供 @code{tzinfo=timezone.utc} 来获取 POSIX 时间戳:

@example
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
@end example

或者通过直接计算时间戳:

@example
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
@end example
@end quotation
@end cartouche
@end deffn

@geindex weekday() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime weekday}@anchor{1a56}
@deffn {方法} datetime.weekday ()

返回一个整数代表星期几，星期一为 0，星期天为 6。 相当于 @code{self.date().weekday()}。 另请参阅 @ref{1a57,,isoweekday()}。
@end deffn

@geindex isoweekday() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime isoweekday}@anchor{1a57}
@deffn {方法} datetime.isoweekday ()

返回一个整数代表星期几，星期一为 1，星期天为 7。 相当于 @code{self.date().isoweekday()}。 另请参阅 @ref{1a56,,weekday()}, @ref{1a0,,isocalendar()}。
@end deffn

@geindex isocalendar() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime isocalendar}@anchor{1a0}
@deffn {方法} datetime.isocalendar ()

返回一个由三部分组成的 @ref{b84,,named tuple}: @code{year}, @code{week} 和 @code{weekday}。 等同于 @code{self.date().isocalendar()}。
@end deffn

@geindex isoformat() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime isoformat}@anchor{63b}
@deffn {方法} datetime.isoformat (sep='T', timespec='auto')

返回一个以 ISO 8601 格式表示的日期和时间字符串：


@itemize -

@item 
@code{YYYY-MM-DDTHH:MM:SS.ffffff}，如果 @ref{1a26,,microsecond} 不为 0

@item 
@code{YYYY-MM-DDTHH:MM:SS}，如果 @ref{1a26,,microsecond} 为 0
@end itemize

如果 @ref{1a4f,,utcoffset()} 返回值不为 @code{None}，则添加一个字符串来给出 UTC 时差：


@itemize -

@item 
@code{YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]}，如果 @ref{1a26,,microsecond} 不为 0

@item 
@code{YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]}，如果 @ref{1a26,,microsecond} 为 0
@end itemize

示例:

@example
>>> from datetime import datetime, timezone
>>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
'2019-05-18T15:17:08.132263'
>>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00+00:00'
@end example

可选参数 @emph{sep} (默认为 @code{'T'}) 为单个分隔字符，会被放在结果的日期和时间两部分之间。 例如:

@example
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     """A time zone with an arbitrary, constant -06:39 offset."""
...     def utcoffset(self, dt):
...         return timedelta(hours=-6, minutes=-39)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
>>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
'2009-11-27T00:00:00.000100-06:39'
@end example

可选参数 @emph{timespec} 要包含的额外时间组件值 (默认为 @code{'auto'})。它可以是以下值之一：


@itemize -

@item 
@code{'auto'}: 如果 @ref{1a26,,microsecond} 为 0 则与 @code{'seconds'} 相同，否则与 @code{'microseconds'} 相同。

@item 
@code{'hours'}: 以两个数码的 @code{HH} 格式 包含 @ref{1a23,,hour}。

@item 
@code{'minutes'}: 以 @code{HH:MM} 格式包含 @ref{1a23,,hour} 和 @ref{1a24,,minute}。

@item 
@code{'seconds'}: 以 @code{HH:MM:SS} 格式包含 @ref{1a23,,hour}, @ref{1a24,,minute} 和 @ref{1a25,,second}。

@item 
@code{'milliseconds'}: 包含完整时间，但将秒值的小数部分截断至毫秒。 格式为 @code{HH:MM:SS.sss}。

@item 
@code{'microseconds'}: 以 @code{HH:MM:SS.ffffff} 格式包含完整时间。
@end itemize

@cartouche
@quotation 注解 
排除掉的时间部分将被截断，而不是被舍入。
@end quotation
@end cartouche

对于无效的 @emph{timespec} 参数将引发 @ref{16d,,ValueError}:

@example
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')   
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'
@end example


3.6 新版功能: 增加了 @emph{timespec} 参数。

@end deffn

@geindex __str__() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime __str__}@anchor{1a58}
@deffn {方法} datetime.__str__ ()

对于 @ref{19f,,datetime} 实例 @emph{d}，@code{str(d)} 等价于 @code{d.isoformat(' ')}。
@end deffn

@geindex ctime() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime ctime}@anchor{1a59}
@deffn {方法} datetime.ctime ()

返回一个表示日期和时间的字符串:

@example
>>> from datetime import datetime
>>> datetime(2002, 12, 4, 20, 30, 40).ctime()
'Wed Dec  4 20:30:40 2002'
@end example

输出字符串将 @emph{并不} 包括时区信息，无论输入的是感知型还是简单型。

@code{d.ctime()} 等效于:

@example
time.ctime(time.mktime(d.timetuple()))
@end example

在原生 C @code{ctime()} 函数 (@ref{1a40,,time.ctime()} 会发起调用该函数，但 @ref{1a59,,datetime.ctime()} 则不会) 遵循 C 标准的平台上。
@end deffn

@geindex strftime() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime strftime}@anchor{639}
@deffn {方法} datetime.strftime (format)

返回一个由显式格式字符串所指明的代表日期和时间的字符串，要获取格式指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@geindex __format__() (datetime.datetime 方法)
@anchor{library/datetime datetime datetime __format__}@anchor{1a5a}
@deffn {方法} datetime.__format__ (format)

与 @ref{639,,datetime.strftime()} 相同。 此方法使得为 @ref{19f,,datetime} 对象指定以 @ref{29d,,格式化字符串字面值} 表示的格式化字符串以及使用 @ref{5dd,,str.format()} 进行格式化成为可能。 要获取格式指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@menu
* 用法示例; datetime: 用法示例 datetime. 

@end menu

@node 用法示例 datetime,,,datetime 对象
@anchor{library/datetime examples-of-usage-datetime}@anchor{1a5b}
@subsubsection 用法示例: @code{datetime}


使用 @ref{19f,,datetime} 对象的例子：

@example
>>> from datetime import datetime, date, time, timezone

>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)

>>> # Using datetime.now()
>>> datetime.now()   
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
>>> datetime.now(timezone.utc)   
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)

>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:   
...     print(it)
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None

>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:   
...     print(it)
...
2006    # ISO year
47      # ISO week
2       # ISO weekday

>>> # Formatting a datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The @{1@} is @{0:%d@}, the @{2@} is @{0:%B@}, the @{3@} is @{0:%I:%M%p@}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
@end example

以下示例定义了一个 @ref{180,,tzinfo} 子类，它捕获 Kabul, Afghanistan 时区的信息，该时区使用 +4 UTC 直到 1945 年，之后则使用 +4:30 UTC:

@example
from datetime import timedelta, datetime, tzinfo, timezone

class KabulTz(tzinfo):
    # Kabul used +4 until 1945, when they moved to +4:30
    UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)

    def utcoffset(self, dt):
        if dt.year < 1945:
            return timedelta(hours=4)
        elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
            # An ambiguous ("imaginary") half-hour range representing
            # a 'fold' in time due to the shift from +4 to +4:30.
            # If dt falls in the imaginary range, use fold to decide how
            # to resolve. See PEP495.
            return timedelta(hours=4, minutes=(30 if dt.fold else 0))
        else:
            return timedelta(hours=4, minutes=30)

    def fromutc(self, dt):
        # Follow same validations as in datetime.tzinfo
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # A custom implementation is required for fromutc as
        # the input to this function is a datetime with utc values
        # but with a tzinfo set to self.
        # See datetime.astimezone or fromtimestamp.
        if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
            return dt + timedelta(hours=4, minutes=30)
        else:
            return dt + timedelta(hours=4)

    def dst(self, dt):
        # Kabul does not observe daylight saving time.
        return timedelta(0)

    def tzname(self, dt):
        if dt >= self.UTC_MOVE_DATE:
            return "+04:30"
        return "+04"
@end example

上述 @code{KabulTz} 的用法:

@example
>>> tz1 = KabulTz()

>>> # Datetime before the change
>>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
>>> print(dt1.utcoffset())
4:00:00

>>> # Datetime after the change
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
>>> print(dt2.utcoffset())
4:30:00

>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(timezone.utc)
>>> dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
>>> dt2 == dt3
True
@end example

@node time 对象,tzinfo 对象,datetime 对象,datetime --- 基本日期和时间类型
@anchor{library/datetime datetime-time}@anchor{1a5c}@anchor{library/datetime time-objects}@anchor{1a5d}
@subsubsection @code{time} 对象


一个 @ref{10c,,time} 对象代表某日的（本地）时间，它独立于任何特定日期，并可通过 @ref{180,,tzinfo} 对象来调整。

@geindex time (datetime 中的类)
@anchor{library/datetime datetime time}@anchor{5f5}
@deffn {类} datetime.time (hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

所有参数都是可选的。 @emph{tzinfo} 可以是 @code{None}，或者是一个 @ref{180,,tzinfo} 子类的实例。 其余的参数必须是在下面范围内的整数：


@itemize *

@item 
@code{0 <= hour < 24},

@item 
@code{0 <= minute < 60},

@item 
@code{0 <= second < 60},

@item 
@code{0 <= microsecond < 1000000},

@item 
@code{fold in [0, 1]}.
@end itemize

如果给出一个此范围以外的参数，则会引发 @ref{16d,,ValueError}。 所有参数值默认为 @code{0}，只有 @emph{tzinfo} 默认为 @ref{204,,None}。
@end deffn

类属性：

@geindex min (datetime.time 属性)
@anchor{library/datetime datetime time min}@anchor{1a5e}
@deffn {属性} time.min

早最的可表示 @ref{5f5,,time}, @code{time(0, 0, 0, 0)}。
@end deffn

@geindex max (datetime.time 属性)
@anchor{library/datetime datetime time max}@anchor{1a5f}
@deffn {属性} time.max

最晚的可表示 @ref{5f5,,time}, @code{time(23, 59, 59, 999999)}。
@end deffn

@geindex resolution (datetime.time 属性)
@anchor{library/datetime datetime time resolution}@anchor{1a60}
@deffn {属性} time.resolution

两个不相等的 @ref{5f5,,time} 对象之间可能的最小间隔，@code{timedelta(microseconds=1)}，但是请注意 @ref{5f5,,time} 对象并不支持算术运算。
@end deffn

实例属性（只读）：

@geindex hour (datetime.time 属性)
@anchor{library/datetime datetime time hour}@anchor{1a1b}
@deffn {属性} time.hour

取值范围是 @code{range(24)}。
@end deffn

@geindex minute (datetime.time 属性)
@anchor{library/datetime datetime time minute}@anchor{1a1c}
@deffn {属性} time.minute

取值范围是 @code{range(60)}。
@end deffn

@geindex second (datetime.time 属性)
@anchor{library/datetime datetime time second}@anchor{1a1d}
@deffn {属性} time.second

取值范围是 @code{range(60)}。
@end deffn

@geindex microsecond (datetime.time 属性)
@anchor{library/datetime datetime time microsecond}@anchor{1a1e}
@deffn {属性} time.microsecond

取值范围是 @code{range(1000000)}。
@end deffn

@geindex tzinfo (datetime.time 属性)
@anchor{library/datetime datetime time tzinfo}@anchor{1a1f}
@deffn {属性} time.tzinfo

作为 tzinfo 参数被传给 @ref{5f5,,time} 构造器的对象，如果没有传入值则为 @code{None}。
@end deffn

@geindex fold (datetime.time 属性)
@anchor{library/datetime datetime time fold}@anchor{1a61}
@deffn {属性} time.fold

取值范围是 @code{[0, 1]}。 用于在重复的时间段中消除边界时间歧义。 （当夏令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边界时间。


3.6 新版功能.

@end deffn

@ref{5f5,,time} 对象支持 @ref{5f5,,time} 与 @ref{5f5,,time} 的比较，当 @emph{a} 时间在 @emph{b} 之前时，则认为 @emph{a} 小于 @emph{b}。 如果比较的一方是简单型而另一方是感知型，则如果尝试进行顺序比较将引发 @ref{1ff,,TypeError}。 对于相等比较，简单型实例将永远不等于感知型实例。

如果两个比较方都是感知型，且具有相同的 @ref{1a1f,,tzinfo} 属性，相同的 @ref{1a1f,,tzinfo} 属性会被忽略并对基本时间值进行比较。 如果两个比较方都是感知型且具有不同的 @ref{1a1f,,tzinfo} 属性，两个比较方将首先通过减去它们的 UTC 时差（从 @code{self.utcoffset()} 获取）来进行调整。 为了防止将混合类型比较回退为基于对象地址的默认比较，当 @ref{5f5,,time} 对象与不同类型的对象比较时，将会引发 @ref{1ff,,TypeError}，除非比较运算符是 @code{==} 或 @code{!=}。 在后两种情况下将分别返回 @ref{497,,False} 或 @ref{59c,,True}。


在 3.3 版更改: 感知型和简单型 @ref{5f5,,time} 实例之间的相等比较不会引发 @ref{1ff,,TypeError}。


在布尔运算时，@ref{5f5,,time} 对象总是被视为真值。


在 3.5 版更改: 在 Python 3.5 之前，如果一个 @ref{5f5,,time} 对象代表 UTC 午夜零时则会被视为假值。 此行为被认为容易引发困惑和错误，因此从 Python 3.5 起已被去除。 详情参见 bpo-13936@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=13936}。


其他构造方法：

@geindex fromisoformat() (datetime.time 类方法)
@anchor{library/datetime datetime time fromisoformat}@anchor{1213}
@deffn {方法} classmethod time.fromisoformat (time_string)

返回对应于 @ref{1a62,,time.isoformat()} 所提供的某种 @emph{time_string} 格式的 @ref{5f5,,time}。 特别地，此函数支持以下格式的字符串：

@example
HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]
@end example

@cartouche
@quotation 警告 
此方法 @emph{并不} 支持解析任意 ISO 8601 字符串。 它的目的只是作为 @ref{1a62,,time.isoformat()} 的逆操作。
@end quotation
@end cartouche

示例:

@example
>>> from datetime import time
>>> time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
>>> time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
>>> time.fromisoformat('04:23:01+04:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
@end example


3.7 新版功能.

@end deffn

实例方法：

@geindex replace() (datetime.time 方法)
@anchor{library/datetime datetime time replace}@anchor{1a63}
@deffn {方法} time.replace (hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, *, fold=0)

返回一个具有同样属性值的 @ref{5f5,,time}，除非通过任何关键字参数指定了某些属性值。 请注意可以通过指定 @code{tzinfo=None} 从一个感知型 @ref{5f5,,time} 创建一个简单型 @ref{5f5,,time}，而不必转换时间数据。


3.6 新版功能: 增加了 @code{fold} 参数。

@end deffn

@geindex isoformat() (datetime.time 方法)
@anchor{library/datetime datetime time isoformat}@anchor{1a62}
@deffn {方法} time.isoformat (timespec='auto')

返回表示为下列 ISO 8601 格式之一的时间字符串：


@itemize -

@item 
@code{HH:MM:SS.ffffff}，如果 @ref{1a1e,,microsecond} 不为 0

@item 
@code{HH:MM:SS}，如果 @ref{1a1e,,microsecond} 为 0

@item 
@code{HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]}，如果 @ref{1a64,,utcoffset()} 不返回 @code{None}

@item 
@code{HH:MM:SS+HH:MM[:SS[.ffffff]]}，如果 @ref{1a1e,,microsecond} 为 0 并且 @ref{1a64,,utcoffset()} 不返回 @code{None}
@end itemize

可选参数 @emph{timespec} 要包含的额外时间组件值 (默认为 @code{'auto'})。它可以是以下值之一：


@itemize -

@item 
@code{'auto'}: 如果 @ref{1a1e,,microsecond} 为 0 则与 @code{'seconds'} 相同，否则与 @code{'microseconds'} 相同。

@item 
@code{'hours'}: 以两个数码的 @code{HH} 格式 包含 @ref{1a1b,,hour}。

@item 
@code{'minutes'}: 以 @code{HH:MM} 格式包含 @ref{1a1b,,hour} 和 @ref{1a1c,,minute}。

@item 
@code{'seconds'}: 以 @code{HH:MM:SS} 格式包含 @ref{1a1b,,hour}, @ref{1a1c,,minute} 和 @ref{1a1d,,second}。

@item 
@code{'milliseconds'}: 包含完整时间，但将秒值的小数部分截断至毫秒。 格式为 @code{HH:MM:SS.sss}。

@item 
@code{'microseconds'}: 以 @code{HH:MM:SS.ffffff} 格式包含完整时间。
@end itemize

@cartouche
@quotation 注解 
排除掉的时间部分将被截断，而不是被舍入。
@end quotation
@end cartouche

对于无效的 @emph{timespec} 参数将引发 @ref{16d,,ValueError}。

示例:

@example
>>> from datetime import time
>>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
'12:34'
>>> dt = time(hour=12, minute=34, second=56, microsecond=0)
>>> dt.isoformat(timespec='microseconds')
'12:34:56.000000'
>>> dt.isoformat(timespec='auto')
'12:34:56'
@end example


3.6 新版功能: 增加了 @emph{timespec} 参数。

@end deffn

@geindex __str__() (datetime.time 方法)
@anchor{library/datetime datetime time __str__}@anchor{1a65}
@deffn {方法} time.__str__ ()

对于时间对象 @emph{t}, @code{str(t)} 等价于 @code{t.isoformat()}。
@end deffn

@geindex strftime() (datetime.time 方法)
@anchor{library/datetime datetime time strftime}@anchor{1a66}
@deffn {方法} time.strftime (format)

返回一个由显式格式字符串所指明的代表时间的字符串。 要获取格式指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@geindex __format__() (datetime.time 方法)
@anchor{library/datetime datetime time __format__}@anchor{1a67}
@deffn {方法} time.__format__ (format)

与 @ref{1a66,,time.strftime()} 相同。 此方法使得为 @ref{5f5,,time} 对象指定以 @ref{29d,,格式化字符串字面值} 表示的格式化字符串以及使用 @ref{5dd,,str.format()} 进行格式化成为可能。 要获取格式指令的完整列表，请参阅 @ref{1a41,,strftime() 和 strptime() 的行为}。
@end deffn

@geindex utcoffset() (datetime.time 方法)
@anchor{library/datetime datetime time utcoffset}@anchor{1a64}
@deffn {方法} time.utcoffset ()

如果 @ref{1a1f,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.utcoffset(None)}，并且在后者不返回 @code{None} 或一个幅度小于一天的 a @ref{2d1,,timedelta} 对象时将引发异常。


在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

@end deffn

@geindex dst() (datetime.time 方法)
@anchor{library/datetime datetime time dst}@anchor{1a68}
@deffn {方法} time.dst ()

如果 @ref{1a1f,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.dst(None)}，并且在后者不返回 @code{None} 或者一个幅度小于一天的 @ref{2d1,,timedelta} 对象时将引发异常。


在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

@end deffn

@geindex tzname() (datetime.time 方法)
@anchor{library/datetime datetime time tzname}@anchor{1a69}
@deffn {方法} time.tzname ()

如果 @ref{1a1f,,tzinfo} 为 @code{None}，则返回 @code{None}，否则返回 @code{self.tzinfo.tzname(None)}，如果后者不返回 @code{None} 或者一个字符串对象则将引发异常。
@end deffn

@menu
* 用法示例; time: 用法示例 time. 

@end menu

@node 用法示例 time,,,time 对象
@anchor{library/datetime examples-of-usage-time}@anchor{1a6a}
@subsubsection 用法示例: @code{time}


使用 @ref{5f5,,time} 对象的例子:

@example
>>> from datetime import time, tzinfo, timedelta
>>> class TZ1(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(hours=1)
...     def dst(self, dt):
...         return timedelta(0)
...     def tzname(self,dt):
...         return "+01:00"
...     def  __repr__(self):
...         return f"@{self.__class__.__name__@}()"
...
>>> t = time(12, 10, 30, tzinfo=TZ1())
>>> t
datetime.time(12, 10, 30, tzinfo=TZ1())
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'+01:00'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
>>> 'The @{@} is @{:%H:%M@}.'.format("time", t)
'The time is 12:10.'
@end example

@node tzinfo 对象,timezone 对象,time 对象,datetime --- 基本日期和时间类型
@anchor{library/datetime datetime-tzinfo}@anchor{1a6b}@anchor{library/datetime tzinfo-objects}@anchor{1a6c}
@subsubsection @code{tzinfo} 对象


@geindex tzinfo (datetime 中的类)
@anchor{library/datetime datetime tzinfo}@anchor{180}
@deffn {类} datetime.tzinfo

这是一个抽象基类，也就是说该类不应被直接实例化。 请定义 @ref{180,,tzinfo} 的子类来捕获有关特定时区的信息。

@ref{180,,tzinfo} 的（某个实体子类）的实例可以被传给 @ref{19f,,datetime} 和 @ref{5f5,,time} 对象的构造器。 这些对象会将它们的属性视为对应于本地时间，并且 @ref{180,,tzinfo} 对象支持展示本地时间与 UTC 的差值、时区名称以及 DST 差值的方法，都是与传给它们的日期或时间对象的相对值。

你需要派生一个实体子类，并且（至少）提供你使用 @ref{19f,,datetime} 方法所需要的标准 @ref{180,,tzinfo} 方法的实现。 @ref{30,,datetime} 模块提供了 @ref{ae9,,timezone}，这是 @ref{180,,tzinfo} 的一个简单实体子类，它能以与 UTC 的固定差值来表示不同的时区，例如 UTC 本身或北美的 EST 和 EDT。

对于封存操作的特殊要求：一个 @ref{180,,tzinfo} 子类必须具有可不带参数调用的 @ref{e2b,,__init__()} 方法，否则它虽然可以被封存，但可能无法再次解封。 这是个技术性要求，在未来可能会被取消。

一个 @ref{180,,tzinfo} 的实体子类可能需要实现以下方法。 具体需要实现的方法取决于感知型 @ref{30,,datetime} 对象如何使用它。 如果有疑问，可以简单地全都实现。
@end deffn

@geindex utcoffset() (datetime.tzinfo 方法)
@anchor{library/datetime datetime tzinfo utcoffset}@anchor{1a6d}
@deffn {方法} tzinfo.utcoffset (dt)

将本地时间与 UTC 时差返回为一个 @ref{2d1,,timedelta} 对象，如果本地时区在 UTC 以东则为正值。 如果本地时区在 UTC 以西则为负值。

这表示与 UTC 的 @emph{总计} 时差；举例来说，如果一个 @ref{180,,tzinfo} 对象同时代表时区和 DST 调整，则 @ref{1a6d,,utcoffset()} 应当返回两者的和。 如果 UTC 时差不确定则返回 @code{None}。 在其他情况下返回值必须为一个 @ref{2d1,,timedelta} 对象，其取值严格限制于 @code{-timedelta(hours=24)} 和 @code{timedelta(hours=24)} 之间（差值的幅度必须小于一天）。 大多数 @ref{1a6d,,utcoffset()} 的实现看起来可能像是以下两者之一:

@example
return CONSTANT                 # fixed-offset class
return CONSTANT + self.dst(dt)  # daylight-aware class
@end example

如果 @ref{1a6d,,utcoffset()} 返回值不为 @code{None}，则 @ref{1a6e,,dst()} 也不应返回 @code{None}。

默认的 @ref{1a6d,,utcoffset()} 实现会引发 @ref{70e,,NotImplementedError}。


在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

@end deffn

@geindex dst() (datetime.tzinfo 方法)
@anchor{library/datetime datetime tzinfo dst}@anchor{1a6e}
@deffn {方法} tzinfo.dst (dt)

将夏令时（DST）调整返回为一个 @ref{2d1,,timedelta} 对象，如果 DST 信息未知则返回 @code{None}。

如果 DST 未启用则返回 @code{timedelta(0)}。 如果 DST 已启用则将差值作为一个 @ref{2d1,,timedelta} 对象返回（参见 @ref{1a6d,,utcoffset()} 了解详情）。 请注意 DST 差值如果可用，就会直接被加入 @ref{1a6d,,utcoffset()} 所返回的 UTC 时差，因此无需额外查询 @ref{1a6e,,dst()} 除非你希望单独获取 DST 信息。 例如，@ref{1a53,,datetime.timetuple()} 会调用其 @ref{1a27,,tzinfo} 属性的 @ref{1a6e,,dst()} 方法来确定应该如何设置 @code{tm_isdst} 旗标，而 @ref{1a51,,tzinfo.fromutc()} 会调用 @ref{1a6e,,dst()} 来在跨越时区时处理 DST 的改变。

一个可以同时处理标准时和夏令时的 @ref{180,,tzinfo} 子类的实例 @emph{tz} 必须在此情形中保持一致：

@code{tz.utcoffset(dt) - tz.dst(dt)}

必须为具有同样的 @ref{180,,tzinfo} 子类实例且 @code{dt.tzinfo == tz} 的每个 @ref{19f,,datetime} 对象 @emph{dt} 返回同样的结果，此表达式会产生时区的“标准时差”，它不应取决于具体日期或时间，只取决于地理位置。 @ref{2d2,,datetime.astimezone()} 的实现依赖此方法，但无法检测违反规则的情况；确保符合规则是程序员的责任。 如果一个 @ref{180,,tzinfo} 子类不能保证这一点，也许可以重载 @ref{1a51,,tzinfo.fromutc()} 的默认实现以便在任何情况下与 @code{astimezone()} 正确配合。

大多数 @ref{1a6e,,dst()} 的实现可能会如以下两者之一:

@example
def dst(self, dt):
    # a fixed-offset class:  doesn't account for DST
    return timedelta(0)
@end example

或者：

@example
def dst(self, dt):
    # Code to set dston and dstoff to the time zone's DST
    # transition times based on the input dt.year, and expressed
    # in standard local time.

    if dston <= dt.replace(tzinfo=None) < dstoff:
        return timedelta(hours=1)
    else:
        return timedelta(0)
@end example

默认的 @ref{1a6e,,dst()} 实现会引发 @ref{70e,,NotImplementedError}。


在 3.7 版更改: DST 差值不再限制为一个整数分钟值。

@end deffn

@geindex tzname() (datetime.tzinfo 方法)
@anchor{library/datetime datetime tzinfo tzname}@anchor{1a6f}
@deffn {方法} tzinfo.tzname (dt)

将对应于 @ref{19f,,datetime} 对象 @emph{dt} 的时区名称作为字符串返回。 @ref{30,,datetime} 模块没有定义任何字符串名称相关内容，也不要求名称有任何特定含义。 例如 "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" 都是有效的返回值。 如果字符串名称未知则返回 @code{None}。 请注意这是一个方法而不是一个固定的字符串，这主要是因为某些 @ref{180,,tzinfo} 子类可能需要根据所传入的特定 @emph{dt} 值返回不同的名称，特别是当 @ref{180,,tzinfo} 类要负责处理夏令时的时候。

默认的 @ref{1a6f,,tzname()} 实现会引发 @ref{70e,,NotImplementedError}。
@end deffn

这些方法会被 @ref{19f,,datetime} 或 @ref{5f5,,time} 对象调用，用来与它们的同名方法相对应。 @ref{19f,,datetime} 对象会将自身作为传入参数，而 @ref{5f5,,time} 对象会将 @code{None} 作为传入参数。 这样 @ref{180,,tzinfo} 子类的方法应当准备好接受 @emph{dt} 参数值为 @code{None} 或是 @ref{19f,,datetime} 类的实例。

当传入 @code{None} 时，应当由类的设计者来决定最佳回应方式。 例如，返回 @code{None} 适用于希望该类提示时间对象不参与 @ref{180,,tzinfo} 协议处理。 让 @code{utcoffset(None)} 返回标准 UTC 时差也许会更有用处，因为并没有其他可用于发现标准时差的约定惯例。

当传入一个 @ref{19f,,datetime} 对象来回应 @ref{19f,,datetime} 方法时，@code{dt.tzinfo} 与 @emph{self} 是同一对象。 @ref{180,,tzinfo} 方法可以依赖这一点，除非用户代码直接调用了 @ref{180,,tzinfo} 方法。 此行为的目的是使得 @ref{180,,tzinfo} 方法将 @emph{dt} 解读为本地时间，而不需要担心其他时区的相关对象。

还有一个额外的 @ref{180,,tzinfo} 方法，某个子类可能会希望重载它：

@geindex fromutc() (datetime.tzinfo 方法)
@anchor{library/datetime datetime tzinfo fromutc}@anchor{1a51}
@deffn {方法} tzinfo.fromutc (dt)

此方法会由默认的 @ref{2d2,,datetime.astimezone()} 实现来调用。 当被其调用时，@code{dt.tzinfo} 为 @emph{self}，并且 @emph{dt} 的日期和时间数据会被视为表示 UTC 时间，@ref{1a51,,fromutc()} 的目标是调整日期和时间数据，返回一个等价的 datetime 来表示 @emph{self} 的本地时间。

大多数 @ref{180,,tzinfo} 子类应该能够毫无问题地继承默认的 @ref{1a51,,fromutc()} 实现。 它的健壮性足以处理固定差值的时区以及同时负责标准时和夏令时的时区，对于后者甚至还能处理 DST 转换时间在各个年份有变化的情况。 一个默认 @ref{1a51,,fromutc()} 实现可能无法在所有情况下正确处理的例子是（与 UTC 的）标准时差取决于所经过的特定日期和时间，这种情况可能由于政治原因而出现。 默认的 @code{astimezone()} 和 @ref{1a51,,fromutc()} 实现可能无法生成你希望的结果，如果这个结果恰好是跨越了标准时差发生改变的时刻当中的某个小时值的话。

忽略针对错误情况的代码，默认 @ref{1a51,,fromutc()} 实现的行为方式如下:

@example
def fromutc(self, dt):
    # raise ValueError error if dt.tzinfo is not self
    dtoff = dt.utcoffset()
    dtdst = dt.dst()
    # raise ValueError if dtoff is None or dtdst is None
    delta = dtoff - dtdst  # this is self's standard offset
    if delta:
        dt += delta   # convert to standard local time
        dtdst = dt.dst()
        # raise ValueError if dtdst is None
    if dtdst:
        return dt + dtdst
    else:
        return dt
@end example
@end deffn

在以下 @code{tzinfo_examples.py} 文件中有一些 @ref{180,,tzinfo} 类的例子：

@example
from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)

# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
#  timezones where UTC offset and/or the DST rules had
#  changed in the past.)
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):

    def fromutc(self, dt):
        assert dt.tzinfo is self
        stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
        args = _time.localtime(stamp)[:6]
        dst_diff = DSTDIFF // SECOND
        # Detect fold
        fold = (args == _time.localtime(stamp - dst_diff))
        return datetime(*args, microsecond=dt.microsecond,
                        tzinfo=self, fold=fold)

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

Local = LocalTimezone()


# A complete implementation of current DST rules for major US time zones.

def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt


# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# http://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006

def us_dst_range(year):
    # Find start and end times for US DST. For years before 1967, return
    # start = end for no DST.
    if 2006 < year:
        dststart, dstend = DSTSTART_2007, DSTEND_2007
    elif 1986 < year < 2007:
        dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
    elif 1966 < year < 1987:
        dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
    else:
        return (datetime(year, 1, 1), ) * 2

    start = first_sunday_on_or_after(dststart.replace(year=year))
    end = first_sunday_on_or_after(dstend.replace(year=year))
    return start, end


class USTimeZone(tzinfo):

    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname

    def __repr__(self):
        return self.reprname

    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname

    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        dt = dt.replace(tzinfo=None)
        if start + HOUR <= dt < end - HOUR:
            # DST is in effect.
            return HOUR
        if end - HOUR <= dt < end:
            # Fold (an ambiguous hour): use dt.fold to disambiguate.
            return ZERO if dt.fold else HOUR
        if start <= dt < start + HOUR:
            # Gap (a non-existent hour): reverse the fold rule.
            return HOUR if dt.fold else ZERO
        # DST is off.
        return ZERO

    def fromutc(self, dt):
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        start = start.replace(tzinfo=self)
        end = end.replace(tzinfo=self)
        std_time = dt + self.stdoffset
        dst_time = std_time + HOUR
        if end <= dst_time < end + HOUR:
            # Repeated hour
            return std_time.replace(fold=1)
        if std_time < start or dst_time >= end:
            # Standard time
            return std_time
        if start <= std_time < end - HOUR:
            # Daylight saving time
            return dst_time


Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
@end example

请注意同时负责标准时和夏令时的 @ref{180,,tzinfo} 子类在每年两次的 DST 转换点上会出现不可避免的微妙问题。具体而言，考虑美国东部时区 (UTC -0500)，它的 EDT 从三月的第二个星期天 1:59 (EST) 之后一分钟开始，并在十一月的第一天星期天 1:59 (EDT) 之后一分钟结束:

@example
  UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
  EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
  EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

  end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM
@end example

当 DST 开始时（即 "start" 行），本地时钟从 1:59 跳到 3:00。 形式为 2:MM 的时间值在那一天是没有意义的，因此在 DST 开始那一天 @code{astimezone(Eastern)} 不会输出包含 @code{hour == 2} 的结果。 例如，在 2016 年春季时钟向前调整时，我们得到:

@example
>>> from datetime import datetime, timezone
>>> from tzinfo_examples import HOUR, Eastern
>>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT
@end example

当 DST 结束时（见 "end" 行），会有更糟糕的潜在问题：本地时间值中有一个小时是不可能没有歧义的：夏令时的最后一小时。 即以北美东部时间表示当天夏令时结束时的形式为 5:MM UTC 的时间。 本地时钟从 1:59 (夏令时) 再次跳回到 1:00 (标准时)。 形式为 1:MM 的本地时间就是有歧义的。 此时 @code{astimezone()} 是通过将两个相邻的 UTC 小时映射到两个相同的本地小时来模仿本地时钟的行为。 在这个北美东部时间的示例中，形式为 5:MM 和 6:MM 的 UTC 时间在转换为北美东部时间时都将被映射到 1:MM，但前一个时间会将 @ref{5f6,,fold} 属性设为 0 而后一个时间会将其设为 1。 例如，在 2016 年秋季时钟往回调整时，我们得到:

@example
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
@end example

请注意不同的 @ref{19f,,datetime} 实例仅通过 @ref{5f6,,fold} 属性值来加以区分，它们在比较时会被视为相等。

不允许时间显示存在歧义的应用需要显式地检查 @ref{5f6,,fold} 属性的值，或者避免使用混合式的 @ref{180,,tzinfo} 子类；当使用 @ref{ae9,,timezone} 或者任何其他固定差值的 @ref{180,,tzinfo} 子类例如仅表示 EST（固定差值 -5 小时）或仅表示 EDT（固定差值 -4 小时）的类时是不会有歧义的。


@subsubheading 参见


@quotation


@table @asis

@item @ref{14e,,zoneinfo}

@ref{30,,datetime} 模块有一个基本 @ref{ae9,,timezone} 类（用来处理任意与 UTC 的固定时差）及其 @ref{1a70,,timezone.utc} 属性（一个 UTC 时区实例）。

@code{zoneinfo} 为 Python 带来了 @emph{IANA时区数据库} （也被称为 Olson 数据库），推荐使用它。
@end table
@end quotation


@table @asis

@item IANA 时区数据库@footnote{https://www.iana.org/time-zones}

该时区数据库 (通常称为 tz, tzdata 或 zoneinfo) 包含大量代码和数据用来表示全球许多有代表性的地点的本地时间的历史信息。 它会定期进行更新以反映各政治实体对时区边界、UTC 差值和夏令时规则的更改。
@end table


@node timezone 对象,strftime 和 strptime 的行为,tzinfo 对象,datetime --- 基本日期和时间类型
@anchor{library/datetime datetime-timezone}@anchor{1a71}@anchor{library/datetime timezone-objects}@anchor{1a72}
@subsubsection @code{timezone} 对象


@ref{ae9,,timezone} 类是 @ref{180,,tzinfo} 的子类，它的每个实例都代表一个以与 UTC 的固定时差来定义的时区。

此类的对象不可被用于代表某些特殊地点的时区信息，这些地点在一年的不同日期会使用不同的时差，或是在历史上对民用时间进行过调整。

@geindex timezone (datetime 中的类)
@anchor{library/datetime datetime timezone}@anchor{ae9}
@deffn {类} datetime.timezone (offset, name=None)

@emph{offset} 参数必须指定为一个 @ref{2d1,,timedelta} 对象，表示本地时间与 UTC 的时差。 它必须严格限制于 @code{-timedelta(hours=24)} 和 @code{timedelta(hours=24)} 之间，否则会引发 @ref{16d,,ValueError}。

@emph{name} 参数是可选的。 如果指定则必须为一个字符串，它将被用作 @ref{1a52,,datetime.tzname()} 方法的返回值。


3.2 新版功能.



在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

@end deffn

@geindex utcoffset() (datetime.timezone 方法)
@anchor{library/datetime datetime timezone utcoffset}@anchor{1a73}
@deffn {方法} timezone.utcoffset (dt)

返回当 @ref{ae9,,timezone} 实例被构造时指定的固定值。

@emph{dt} 参数会被忽略。 返回值是一个 @ref{2d1,,timedelta} 实例，其值等于本地时间与 UTC 之间的时差。


在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。

@end deffn

@geindex tzname() (datetime.timezone 方法)
@anchor{library/datetime datetime timezone tzname}@anchor{1a74}
@deffn {方法} timezone.tzname (dt)

返回当 @ref{ae9,,timezone} 实例被构造时指定的固定值。

如果没有在构造器中提供 @emph{name}，则 @code{tzname(dt)} 所返回的名称将根据 @code{offset} 值按以下规则生成。 如果 @emph{offset} 为 @code{timedelta(0)}，则名称为“UTC”，否则为字符串 @code{UTC±HH:MM}，其中 ± 为 @code{offset} 的正负符号，HH 和 MM 分别为表示 @code{offset.hours} 和 @code{offset.minutes} 的两个数码。


在 3.6 版更改: 由 @code{offset=timedelta(0)} 生成的名称现在为简单的 @cite{'UTC'} 而不再是 @code{'UTC+00:00'}。

@end deffn

@geindex dst() (datetime.timezone 方法)
@anchor{library/datetime datetime timezone dst}@anchor{1a75}
@deffn {方法} timezone.dst (dt)

总是返回 @code{None}。
@end deffn

@geindex fromutc() (datetime.timezone 方法)
@anchor{library/datetime datetime timezone fromutc}@anchor{1a76}
@deffn {方法} timezone.fromutc (dt)

返回 @code{dt + offset}。 @emph{dt} 参数必须为一个感知型 @ref{19f,,datetime} 实例，其中 @code{tzinfo} 值设为 @code{self}。
@end deffn

类属性：

@geindex utc (datetime.timezone 属性)
@anchor{library/datetime datetime timezone utc}@anchor{1a70}
@deffn {属性} timezone.utc

UTC 时区，@code{timezone(timedelta(0))}。
@end deffn

@geindex % (percent); datetime format

@node strftime 和 strptime 的行为,,timezone 对象,datetime --- 基本日期和时间类型
@anchor{library/datetime strftime-and-strptime-behavior}@anchor{1a77}@anchor{library/datetime strftime-strptime-behavior}@anchor{1a41}
@subsubsection @code{strftime()} 和 @code{strptime()} 的行为


@ref{19d,,date}, @ref{19f,,datetime} 和 @ref{5f5,,time} 对象都支持 @code{strftime(format)} 方法，可用来创建由一个显式格式字符串所控制的表示时间的字符串。

相反地，@ref{fdc,,datetime.strptime()} 类会根据表示日期和时间的字符串和相应的格式字符串来创建一个 @ref{19f,,datetime} 对象。

下表提供了 @code{strftime()} 与 @code{strptime()} 的高层级比较：


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

@code{strftime}

@tab

@code{strptime}

@item

用法

@tab

根据给定的格式将对象转换为字符串

@tab

将字符串解析为给定相应格式的 @ref{19f,,datetime} 对象

@item

方法类型

@tab

实例方法

@tab

类方法

@item

方法

@tab

@ref{19d,,date}; @ref{19f,,datetime}; @ref{5f5,,time}

@tab

@ref{19f,,datetime}

@item

签名

@tab

@code{strftime(format)}

@tab

@code{strptime(date_string, format)}

@end multitable


@menu
* strftime() 和 strptime() Format Codes: strftime 和 strptime Format Codes. 
* 技术细节:: 

@end menu

@node strftime 和 strptime Format Codes,技术细节,,strftime 和 strptime 的行为
@anchor{library/datetime strftime-and-strptime-format-codes}@anchor{1a78}
@subsubsection @code{strftime()} 和 @code{strptime()} Format Codes


以下列表显示了 1989 版 C 标准所要求的全部格式代码，它们在带有标准 C 实现的所有平台上均可用。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

指令

@tab

意义

@tab

示例

@tab

注释

@item

@code{%a}

@tab

当地工作日的缩写。

@tab


@display
Sun, Mon, ..., Sat (en_US);@w{ }
So, Mo, ..., Sa (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%A}

@tab

本地化的星期中每日的完整名称。

@tab


@display
Sunday, Monday, ..., Saturday (en_US);@w{ }
Sonntag, Montag, ..., Samstag (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%w}

@tab

以十进制数显示的工作日，其中0表示星期日，6表示星期六。

@tab

0, 1, ..., 6

@tab

@item

@code{%d}

@tab

补零后，以十进制数显示的月份中的一天。

@tab

01, 02, ..., 31

@tab

(9)

@item

@code{%b}

@tab

当地月份的缩写。

@tab


@display
Jan, Feb, ..., Dec (en_US);@w{ }
Jan, Feb, ..., Dez (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%B}

@tab

本地化的月份全名。

@tab


@display
January, February, ..., December (en_US);@w{ }
Januar, Februar, ..., Dezember (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%m}

@tab

补零后，以十进制数显示的月份。

@tab

01, 02, ..., 12

@tab

(9)

@item

@code{%y}

@tab

补零后，以十进制数表示的，不带世纪的年份。

@tab

00, 01, ..., 99

@tab

(9)

@item

@code{%Y}

@tab

十进制数表示的带世纪的年份。

@tab

0001, 0002, ..., 2013,
2014, ..., 9998, 9999

@tab

(2)

@item

@code{%H}

@tab

以补零后的十进制数表示的小时（24 小时制）。

@tab

00, 01, ..., 23

@tab

(9)

@item

@code{%I}

@tab

以补零后的十进制数表示的小时（12 小时制）。

@tab

01, 02, ..., 12

@tab

(9)

@item

@code{%p}

@tab

本地化的 AM 或 PM 。

@tab


@display
AM, PM (en_US);@w{ }
am, pm (de_DE)@w{ }
@end display



@tab

(1),
(3)

@item

@code{%M}

@tab

补零后，以十进制数显示的分钟。

@tab

00, 01, ..., 59

@tab

(9)

@item

@code{%S}

@tab

补零后，以十进制数显示的秒。

@tab

00, 01, ..., 59

@tab

(4),
(9)

@item

@code{%f}

@tab

微秒作为一个十进制数，零填充到 6 位。

@tab

000000, 000001, ...,
999999

@tab

(5)

@item

@code{%z}

@tab

UTC 偏移量，格式为 @code{±HHMM[SS[.ffffff]]} （如果是简单型对象则为空字符串）。

@tab

(空), +0000, -0400, +1030, +063415, -030712.345216

@tab

(6)

@item

@code{%Z}

@tab

时区名称（如果对象为简单型则为空字符串）。

@tab

(空), UTC, GMT

@tab

(6)

@item

@code{%j}

@tab

以补零后的十进制数表示的一年中的日序号。

@tab

001, 002, ..., 366

@tab

(9)

@item

@code{%U}

@tab

以补零后的十进制数表示的一年中的周序号（星期日作为每周的第一天）。 在新的一年中第一个星期日之前的所有日子都被视为是在第 0 周。

@tab

00, 01, ..., 53

@tab

(7),
(9)

@item

@code{%W}

@tab

以补零后的十进制数表示的一年中的周序号（星期一作为每周的第一天）。 在新的一年中第一个星期一之前的所有日子都被视为是在第 0 周。

@tab

00, 01, ..., 53

@tab

(7),
(9)

@item

@code{%c}

@tab

本地化的适当日期和时间表示。

@tab


@display
Tue Aug 16 21:30:00 1988 (en_US);@w{ }
Di 16 Aug 21:30:00 1988 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%x}

@tab

本地化的适当日期表示。

@tab


@display
08/16/88 (None);@w{ }
08/16/1988 (en_US);@w{ }
16.08.1988 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%X}

@tab

本地化的适当时间表示。

@tab


@display
21:30:00 (en_US);@w{ }
21:30:00 (de_DE)@w{ }
@end display



@tab

(1)

@item

@code{%%}

@tab

字面的 @code{'%'} 字符。

@tab

%

@tab

@end multitable


为了方便起见，还包括了C89标准不需要的其他一些指令。这些参数都对应于ISO 8601日期值。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

指令

@tab

意义

@tab

示例

@tab

注释

@item

@code{%G}

@tab

带有世纪的 ISO 8601 年份，表示包含大部分 ISO 星期 (@code{%V}) 的年份。

@tab

0001, 0002, ..., 2013,
2014, ..., 9998, 9999

@tab

(8)

@item

@code{%u}

@tab

以十进制数显示的 ISO 8601 星期中的日序号，其中 1 表示星期一。

@tab

1, 2, ..., 7

@tab

@item

@code{%V}

@tab

以十进制数显示的 ISO 8601 星期，以星期一作为每周的第一天。 第 01 周为包含 1 月 4 日的星期。

@tab

01, 02, ..., 53

@tab

(8),
(9)

@end multitable


这些代码可能不是在所有平台上都可与 @code{strftime()} 方法配合使用。 ISO 8601 年份和 ISO 8601 星期指令并不能与上面的年份和星期序号指令相互替代。 调用 @code{strptime()} 时传入不完整或有歧义的 ISO 8601 指令将引发 @ref{16d,,ValueError}。

对完整格式代码集的支持在不同平台上有所差异，因为 Python 要调用所在平台的 C 库的 @code{strftime()} 函数，而不同平台的差异是很常见的。 要查看你所用平台所支持的完整格式代码集，请参阅 @code{strftime(3)} 文档。不同的平台在处理不支持的格式指定符方面也有差异。


3.6 新版功能: 增加了 @code{%G},  @code{%u}  和 @code{%V}。


@node 技术细节,,strftime 和 strptime Format Codes,strftime 和 strptime 的行为
@anchor{library/datetime technical-detail}@anchor{1a79}
@subsubsection 技术细节


总体而言，@code{d.strftime(fmt)} 类似于 @ref{10c,,time} 模块的 @code{time.strftime(fmt, d.timetuple())}，但是并非所有对象都支持 @code{timetuple()} 方法。

对于 @ref{fdc,,datetime.strptime()} 类方法，默认值为 @code{1900-01-01T00:00:00.000}: 任何未在格式字符串中指定的部分都将从默认值中提取。 @footnote{@w{(4)} 
传入 @code{datetime.strptime('Feb 29', '%b %d')} 将导致错误，因为 @code{1900} 不是闰年。
}

使用 @code{datetime.strptime(date_string, format)} 等价于:

@example
datetime(*(time.strptime(date_string, format)[0:6]))
@end example

除非格式中包含秒以下的部分或时区差值信息，它们在 @code{datetime.strptime} 中受支持但会被 @code{time.strptime} 所丢弃。

对于 @ref{5f5,,time} 对象，年、月、日的格式代码不应被使用，因为 @ref{10c,,time} 对象没有这些值。 如果它们被使用，则年份将被替换为 @code{1900}，而月和日将被替换为 @code{1}。

对于 @ref{19d,,date} 对象，时、分、秒和微秒的格式代码不应被使用，因为 @ref{19d,,date} 对象没有这些值。 如果它们被使用，则它们都将被替换为 @code{0}。

出于相同的原因，对于包含当前区域设置字符集所无法表示的 Unicode 码位的格式字符串的处理方式也取决于具体平台。 在某些平台上这样的码位会不加修改地原样输出，而在其他平台上 @code{strftime} 则可能引发 @ref{d0b,,UnicodeError} 或只返回一个空字符串。

注释:


@enumerate 

@item 
由于此格式依赖于当前区域设置，因此对具体输出值应当保持谨慎预期。 字段顺序会发生改变（例如 "month/day/year" 与 "day/month/year"），并且输出可能包含使用区域设置所指定的默认编码格式的 Unicode 字符（例如如果当前区域为 @code{ja_JP}，则默认编码格式可能为 @code{eucJP}, @code{SJIS} 或 @code{utf-8} 中的一个；使用 @ref{1a7a,,locale.getlocale()} 可确定当前区域设置的编码格式）。

@item 
@code{strptime()} 方法能够解析整个 [1, 9999] 范围内的年份，但 < 1000 的年份必须加零填充为 4 位数字宽度。


在 3.2 版更改: 在之前的版本中，@code{strftime()} 方法只限于 >= 1900 的年份。



在 3.3 版更改: 在版本3.2中，@code{strftime()} 方法只限于 years >= 1000。


@item 
当与 @code{strptime()} 方法一起使用时，如果使用 @code{%I} 指令来解析小时，@code{%p} 指令只影响输出小时字段。

@item 
与 @ref{10c,,time} 模块不同的是， @ref{30,,datetime} 模块不支持闰秒。

@item 
当与 @code{strptime()} 方法一起使用时，@code{%f} 指令可接受一至六个数码及左边的零填充。 @code{%f} 是对 C 标准中格式字符集的扩展（但单独在 datetime 对象中实现，因此它总是可用）。

@item 
对于简单型对象，@code{%z} and @code{%Z} 格式代码会被替换为空字符串。

对于一个感知型对象而言：


@table @asis

@item @code{%z}

@code{utcoffset()} 会被转换为 @code{±HHMM[SS[.ffffff]]} 形式的字符串，其中 @code{HH} 为给出 UTC 时差的小时部分的 2 位数码字符串，@code{MM} 为给出 UTC 时差的分钟部分的 2 位数码字符串，@code{SS} 为给出 UTC 时差的秒部分的 2 位数码字符串，而 @code{ffffff} 为给出 UTC 时差的微秒部分的 6 位数码字符串。 当时差为整数秒时 @code{ffffff} 部分将被省略，而当时差为整数分钟时 @code{ffffff} 和 @code{SS} 部分都将被省略。 例如，如果 @code{utcoffset()} 返回 @code{timedelta(hours=-3, minutes=-30)}，则 @code{%z} 会被替换为字符串 @code{'-0330'}。
@end table


在 3.7 版更改: UTC 时差不再限制为一个整数分钟值。



在 3.7 版更改: 当提供 @code{%z} 指令给 @code{strptime()} 方法时，UTC 差值可以在时、分和秒之间使用冒号分隔符。 例如，@code{'+01:00:00'} 将被解读为一小时的差值。 此外，提供 @code{'Z'} 就相当于 @code{'+00:00'}。



@table @asis

@item @code{%Z}

在 @code{strftime()} 中，如果 @code{tzname()} 返回 @code{None} 则 @code{%Z} 会被替换为一个空字符串；在其他情况下 @code{%Z} 会被替换为返回值，该值必须为一个字符串。

@code{strptime()} 仅接受特定的 @code{%Z} 值:


@enumerate 

@item 
你的机器的区域设置可以是 @code{time.tzname} 中的任何值

@item 
硬编码的值 @code{UTC} 和 @code{GMT}
@end enumerate

这样生活在日本的人可用的值为 @code{JST}, @code{UTC} 和 @code{GMT}，但可能没有 @code{EST}。 它将引发 @code{ValueError} 表示无效的值。
@end table


在 3.2 版更改: 当提供 @code{%z} 指令给 @code{strptime()} 方法时，将产生一个感知型 @ref{19f,,datetime} 对象。 结果的 @code{tzinfo} 将被设为一个 @ref{ae9,,timezone} 实例。


@item 
当与 @code{strptime()} 方法一起使用时，@code{%U} 和 @code{%W} 仅用于指定星期几和日历年份 (@code{%Y}) 的计算。

@item 
类似于 @code{%U} 和 @code{%W}，@code{%V} 仅用于在 @code{strptime()} 格式字符串中指定星期几和 ISO 年份 (@code{%G}) 的计算。 还要注意 @code{%G} 和 @code{%Y} 是不可交换的。

@item 
当于 @code{strptime()} 方法一起使用时，前导的零在格式 @code{%d}, @code{%m}, @code{%H}, @code{%I}, @code{%M}, @code{%S}, @code{%J}, @code{%U}, @code{%W} 和 @code{%V} 中是可选的。 格式 @code{%y} 不要求有前导的零。
@end enumerate

@node zoneinfo --- IANA 时区支持,calendar --- 日历相关函数,datetime --- 基本日期和时间类型,数据类型
@anchor{library/zoneinfo doc}@anchor{1a7b}@anchor{library/zoneinfo module-zoneinfo}@anchor{14e}@anchor{library/zoneinfo zoneinfo-iana-time-zone-support}@anchor{1a7c}
@subsection @code{zoneinfo} --- IANA 时区支持


@geindex zoneinfo (模块)


3.9 新版功能.



__________________________________________________________________


@ref{14e,,zoneinfo} 模块根据 
@geindex Python 提高建议; PEP 615
PEP 615@footnote{https://www.python.org/dev/peps/pep-0615} 的最初说明提供了具体的时区实现来支持 IANA 时区数据库。 按照默认设置，@ref{14e,,zoneinfo} 会在可能的情况下使用系统的时区数据；如果系统时区数据不可用，该库将回退为使用 PyPI 上提供的 tzdata@footnote{https://pypi.org/project/tzdata/} 第一方包。


@subsubheading 参见



@table @asis

@item 模块: @ref{30,,datetime}

提供 @ref{5f5,,time} 和 @ref{19f,,datetime} 类型，@ref{17f,,ZoneInfo} 类被设计为可配合这两个类型使用。

@item 包 tzdata@footnote{https://pypi.org/project/tzdata/}

由 CPython 核心开发者维护以通过 PyPI 提供时区数据的第一方包。
@end table


@menu
* 使用 ZoneInfo:: 
* 数据源:: 
* ZoneInfo 类:: 
* 函数: 函数<2>. 
* 全局变量:: 
* 异常与警告:: 

@end menu

@node 使用 ZoneInfo,数据源,,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo using-zoneinfo}@anchor{1a7d}
@subsubsection 使用 @code{ZoneInfo}


@ref{17f,,ZoneInfo} 是 @ref{180,,datetime.tzinfo} 抽象基类的具体实现，其目标是通过构造器、 @ref{1a4e,,datetime.replace} 方法或 @ref{2d2,,datetime.astimezone} 来与 @code{tzinfo} 建立关联:

@example
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-10-31 12:00:00-07:00

>>> dt.tzname()
'PDT'
@end example

以此方式构造的日期时间对象可兼容日期时间运算并可在无需进一步干预的情况下处理夏令时转换:

@example
>>> dt_add = dt + timedelta(days=1)

>>> print(dt_add)
2020-11-01 12:00:00-08:00

>>> dt_add.tzname()
'PST'
@end example

这些时区还支持在 
@geindex Python 提高建议; PEP 495
PEP 495@footnote{https://www.python.org/dev/peps/pep-0495} 中引入的 @ref{5f6,,fold}。 在可能导致时间歧义的时差转换中（例如夏令时到标准时的转换），当 @code{fold=0} 时会使用转换 @emph{之前} 的时差，而当 @code{fold=1} 时则使用转换 @emph{之后} 的时差，例如:

@example
>>> dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles"))
>>> print(dt)
2020-11-01 01:00:00-07:00

>>> print(dt.replace(fold=1))
2020-11-01 01:00:00-08:00
@end example

当执行来自另一时区的转换时，fold 将被设置为正确的值:

@example
>>> from datetime import timezone
>>> LOS_ANGELES = ZoneInfo("America/Los_Angeles")
>>> dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)

>>> # Before the PDT -> PST transition
>>> print(dt_utc.astimezone(LOS_ANGELES))
2020-11-01 01:00:00-07:00

>>> # After the PDT -> PST transition
>>> print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES))
2020-11-01 01:00:00-08:00
@end example

@node 数据源,ZoneInfo 类,使用 ZoneInfo,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo data-sources}@anchor{1a7e}
@subsubsection 数据源


@code{zoneinfo} 模块不直接提供时区数据，而是在可能的情况下从系统时区数据库或 PyPI 上的第一方包 tzdata@footnote{https://pypi.org/project/tzdata/} 获取时区信息。 某些系统，重要的一点是 Windows 系统也包括在内，并没有可用的 IANA 数据库，因此对于要保证获取时区信息的跨平台兼容性的项目，推荐对 tzdata 声明依赖。 如果系统数据和 tzdata 均不可用，则所有对 @ref{17f,,ZoneInfo} 的调用都将引发 @ref{1a7f,,ZoneInfoNotFoundError}。

@menu
* 配置数据源:: 

@end menu

@node 配置数据源,,,数据源
@anchor{library/zoneinfo configuring-the-data-sources}@anchor{1a80}@anchor{library/zoneinfo zoneinfo-data-configuration}@anchor{1a81}
@subsubsection 配置数据源


当 @code{ZoneInfo(key)} 被调用时，此构造器首先会在 @ref{1a82,,TZPATH} 所指定的目录下搜索匹配 @code{key} 的文件，失败时则会在 tzdata 包中查找匹配。 此行为可通过三种方式来配置:


@enumerate 

@item 
默认的 @ref{1a82,,TZPATH} 未通过其他方式指定时可在 @ref{1a83,,编译时} 进行配置。

@item 
@ref{1a82,,TZPATH} 可使用 @ref{1a84,,环境变量} 进行配置。

@item 
在 @ref{1a85,,运行时}，搜索路径可使用 @ref{1a86,,reset_tzpath()} 函数来修改。
@end enumerate

@menu
* 编译时配置:: 
* 环境配置:: 
* 运行时配置:: 

@end menu

@node 编译时配置,环境配置,,配置数据源
@anchor{library/zoneinfo compile-time-configuration}@anchor{1a87}@anchor{library/zoneinfo zoneinfo-data-compile-time-config}@anchor{1a83}
@subsubsection 编译时配置


默认的 @ref{1a82,,TZPATH} 包括一些时区数据库的通用布署位置（Windows 除外，该系统没有时区数据的“通用”位置）。 在 POSIX 系统中，下游分发者和从源码编译 Python 的开发者知道系统时区数据布署位置，他们可以通过指定编译时选项 @code{TZPATH} (或者更常见的是通过 @code{configure} 旗标 @code{--with-tzpath}) 来改变默认的时区路径，该选项应当是一个由 @ref{14b6,,os.pathsep} 分隔的字符串。

在所有平台上，配置值会在 @ref{a4e,,sysconfig.get_config_var()} 中以 @code{TZPATH} 键的形式提供。

@node 环境配置,运行时配置,编译时配置,配置数据源
@anchor{library/zoneinfo environment-configuration}@anchor{1a88}@anchor{library/zoneinfo zoneinfo-data-environment-var}@anchor{1a84}
@subsubsection 环境配置


当初始化 @ref{1a82,,TZPATH} 时（在导入时或不带参数调用 @ref{1a86,,reset_tzpath()} 时），@code{zoneinfo} 模块将使用环境变量 @code{PYTHONTZPATH}，如果变量存在则会设置搜索路径。

@geindex 环境变量; PYTHONTZPATH
@anchor{library/zoneinfo envvar-PYTHONTZPATH}@anchor{1a89}
@deffn {环境变量} PYTHONTZPATH

这是一个以 @ref{14b6,,os.pathsep} 分隔的字符串，其中包含要使用的时区搜索路径。 它必须仅由绝对路径而非相对路径组成。 在 @code{PYTHONTZPATH} 中指定的相对路径部分将不会被使用，但在其他情况下当指定相对路径时的行为该实现是有定义的；CPython 将引发 @ref{1a8a,,InvalidTZPathWarning}，而其他实现可自由地忽略错误部分或是引发异常。
@end deffn

要设置让系统忽略系统数据并改用 tzdata 包，请设置 @code{PYTHONTZPATH=""}。

@node 运行时配置,,环境配置,配置数据源
@anchor{library/zoneinfo runtime-configuration}@anchor{1a8b}@anchor{library/zoneinfo zoneinfo-data-runtime-config}@anchor{1a85}
@subsubsection 运行时配置


TZ 搜索路径也可在运行时使用 @ref{1a86,,reset_tzpath()} 函数来配置。 通常并不建议如此操作，不过在需要使用指定时区路径（或者需要禁止访问系统时区）的测试函数中使用它则是合理的。

@node ZoneInfo 类,函数<2>,数据源,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo the-zoneinfo-class}@anchor{1a8c}
@subsubsection @code{ZoneInfo} 类


@geindex ZoneInfo (zoneinfo 中的类)
@anchor{library/zoneinfo zoneinfo ZoneInfo}@anchor{17f}
@deffn {类} zoneinfo.ZoneInfo (key)

一个具体的 @ref{180,,datetime.tzinfo} 子类，它代表一个由字符串 @code{key} 所指定的 IANA 时区。 对主构造器的调用将总是返回可进行标识比较的对象；但是另一种方式，对所有的 @code{key} 值通过 @ref{1a8d,,ZoneInfo.clear_cache()} 禁止缓存失效，对以下断言将总是为真值:

@example
a = ZoneInfo(key)
b = ZoneInfo(key)
assert a is b
@end example

@code{key} 必须采用相对的标准化 POSIX 路径的形式，其中没有对上一层级的引用。 如果传入了不合要求的键则构造器将引发 @ref{16d,,ValueError}。

如果没有找到匹配 @code{key} 的文件，构造器将引发 @ref{1a7f,,ZoneInfoNotFoundError}。
@end deffn

@code{ZoneInfo} 类具有两个替代构造器:

@geindex from_file() (zoneinfo.ZoneInfo 类方法)
@anchor{library/zoneinfo zoneinfo ZoneInfo from_file}@anchor{1a8e}
@deffn {方法} classmethod ZoneInfo.from_file (fobj, /, key=None)

基于一个返回字节串的文件类对象（例如一个以二进制模式打开的文件或是一个 @ref{894,,io.BytesIO} 对象）构造 @code{ZoneInfo} 对象。 不同于主构造器，此构造器总是会构造一个新对象。

@code{key} 形参设置时区名称以供 @ref{f01,,__str__()} 和 @ref{453,,__repr__()} 使用。

由此构造器创建的对象不可被封存 (参见 @ref{1a8f,,pickling})。
@end deffn

@geindex no_cache() (zoneinfo.ZoneInfo 类方法)
@anchor{library/zoneinfo zoneinfo ZoneInfo no_cache}@anchor{1a90}
@deffn {方法} classmethod ZoneInfo.no_cache (key)

一个绕过构造器缓存的替代构造器。 它与主构造器很相似，但每次调用都会返回一个新对象。 此构造器在进行测试或演示时最为适用，但它也可以被用来创建具有不同缓存失效策略的系统。

由此构造器创建的对象在被解封时也会绕过反序列化进程的缓存。

@c TODO: Add "See `cache_behavior`_" reference when that section is ready.

@cartouche
@quotation 警告 
使用此构造器可以会以令人惊讶的方式改变日期时间对象的语义，只有在你确定你的需求时才使用它。
@end quotation
@end cartouche
@end deffn

也可以使用以下的类方法:

@geindex clear_cache() (zoneinfo.ZoneInfo 类方法)
@anchor{library/zoneinfo zoneinfo ZoneInfo clear_cache}@anchor{1a8d}
@deffn {方法} classmethod ZoneInfo.clear_cache (*, only_keys=None)

一个可在 @code{ZoneInfo} 类上禁用缓存的方法。 如果不传入参数，则会禁用所有缓存并且下次对每个键调用主构造器将返回一个新实例。

如果将一个键名称的可迭代对象传给 @code{only_keys} 形参，则将只有指定的键会被从缓存中移除。 传给 @code{only_keys} 但在缓存中找不到的键会被忽略。

@c TODO: Add "See `cache_behavior`_" reference when that section is ready.

@cartouche
@quotation 警告 
发起调用此函数可能会以令人惊讶的方式改变使用 @code{ZoneInfo} 的日期时间对象的语义；这会修改进程范围内的全局状态并因此可能产生大范围的影响。 只有在你确定你的需求时才使用它。
@end quotation
@end cartouche
@end deffn

该类具有一个属性:

@geindex key (zoneinfo.ZoneInfo 属性)
@anchor{library/zoneinfo zoneinfo ZoneInfo key}@anchor{1a91}
@deffn {属性} ZoneInfo.key

这是一个只读的 @ref{1a92,,attribute}，它返回传给构造器的 @code{key} 的值，该值应为一个 IANA 时区数据库的查找键 (例如 @code{America/New_York}, @code{Europe/Paris} 或 @code{Asia/Tokyo})。

对于不指定 @code{key} 形参而是基于文件构造时区，该属性将设为 @code{None}。

@cartouche
@quotation 注解 
尽管将这些信息暴露给最终用户是一种比较普通的做法，但是这些值被设计作为代表相关时区的主键而不一定是面向用户的元素。 CLDR (Unicode 通用区域数据存储库) 之类的项目可被用来根据这些键获取更为用户友好的字符串。
@end quotation
@end cartouche
@end deffn

@menu
* 字符串表示:: 
* 封存序列化:: 

@end menu

@node 字符串表示,封存序列化,,ZoneInfo 类
@anchor{library/zoneinfo string-representations}@anchor{1a93}
@subsubsection 字符串表示


当在 @ref{17f,,ZoneInfo} 对象上调用 @ref{206,,str} 时返回的字符串表示默认会使用 @ref{1a91,,ZoneInfo.key} 属性（参见该属性文档中的用法注释）:

@example
>>> zone = ZoneInfo("Pacific/Kwajalein")
>>> str(zone)
'Pacific/Kwajalein'

>>> dt = datetime(2020, 4, 1, 3, 15, tzinfo=zone)
>>> f"@{dt.isoformat()@} [@{dt.tzinfo@}]"
'2020-04-01T03:15:00+12:00 [Pacific/Kwajalein]'
@end example

对于基于文件而非指定 @code{key} 形参所构建的对象，@code{str} 会回退为调用 @ref{8c3,,repr()}。 @code{ZoneInfo} 的 @code{repr} 是由具体实现定义的并且不一定会在不同版本间保持稳定，但它保证不会是一个有效的 @code{ZoneInfo} 键。

@node 封存序列化,,字符串表示,ZoneInfo 类
@anchor{library/zoneinfo pickle-serialization}@anchor{1a94}@anchor{library/zoneinfo pickling}@anchor{1a8f}
@subsubsection 封存序列化


@code{ZoneInfo} 对象的序列化是基于键的，而不是序列化所有过渡数据，并且基于文件构造的 @code{ZoneInfo} 对象（即使是指定了 @code{key} 值的对象）不能被封存。

@code{ZoneInfo} 文件的行为取决于它的构造方式:


@enumerate 

@item 
@code{ZoneInfo(key)}: 当使用主构造器构造时，会基于键序列化一个 @code{ZoneInfo} 对象，而当反序列化时，反序列化过程会使用主构造器，因此预期它们与其他对同一时区的引用会是同一对象。 例如，如果 @code{europe_berlin_pkl} 是一个包含基于 @code{ZoneInfo("Europe/Berlin")} 构建的封存数据的字符串，你可以预期出现以下的行为:

@example
>>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl)
>>> a is b
True
@end example

@item 
@code{ZoneInfo.no_cache(key)}: 当通过绕过缓存的构造器构造时，@code{ZoneInfo} 对象也会基于键序列化，但当反序列化时，反序列化过程会使用绕过缓存的构造器。 如果 @code{europe_berlin_pkl_nc} 是一个包含基于 @code{ZoneInfo.no_cache("Europe/Berlin")} 构造的封存数据的字符串，你可以预期出现以下的行为:

@example
>>> a = ZoneInfo("Europe/Berlin")
>>> b = pickle.loads(europe_berlin_pkl_nc)
>>> a is b
False
@end example

@item 
@code{ZoneInfo.from_file(fobj, /, key=None)}: 当通过文件构造时，@code{ZoneInfo} 对象会在封存时引发异常。 如果最终用户想要封存通过文件构造的 @code{ZoneInfo}，则推荐他们使用包装类型或自定义序列化函数：或者基于键序列化，或者存储文件对象的内容并将其序列化。
@end enumerate

该序列化方法要求所需键的时区数据在序列化和反序列化中均可用，类似于在序列化和反序列化环境中都预期存在对类和函数的引用的方式。 这还意味着在具有不同时区数据版本的环境中当解封被封存的 @code{ZoneInfo} 时并不会保证结果的一致性。

@node 函数<2>,全局变量,ZoneInfo 类,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo functions}@anchor{1a95}
@subsubsection 函数


@geindex available_timezones() (在 zoneinfo 模块中)
@anchor{library/zoneinfo zoneinfo available_timezones}@anchor{1088}
@deffn {函数} zoneinfo.available_timezones ()

获取一个包含可用 IANA 时区的在时区路径的任何位置均可用的全部有效键的集合。 每次调用该函数时都会重新计算。

此函数仅包括规范时区名称而不包括“特殊”时区如位于 @code{posix/} 和 @code{right/} 目录下的时区或 @code{posixrules} 时区。

@cartouche
@quotation 警告 
此函数可能会打开大量的文件，因为确定时区路径上某个文件是否为有效时区的最佳方式是读取开头位置的“魔术字符串”。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
这些值并不被设计用来对外公开给最终用户；对于面向用户的元素，应用程序应当使用 CLDR (Unicode 通用区域数据存储库) 之类来获取更为用户友好的字符串。 另请参阅 @ref{1a91,,ZoneInfo.key} 中的提示性说明。
@end quotation
@end cartouche
@end deffn

@geindex reset_tzpath() (在 zoneinfo 模块中)
@anchor{library/zoneinfo zoneinfo reset_tzpath}@anchor{1a86}
@deffn {函数} zoneinfo.reset_tzpath (to=None)

设置或重置模块的时区搜索路径 (@ref{1a82,,TZPATH})。 当不带参数调用时，@ref{1a82,,TZPATH} 会被设为默认值。

调用 @code{reset_tzpath} 将不会使 @ref{17f,,ZoneInfo} 缓存失效，因而在缓存未命中的情况下对主 @code{ZoneInfo} 构造器的调用将只使用新的 @code{TZPATH}。

@code{to} 形参必须是由字符串或 @ref{5ee,,os.PathLike} 组成的 @ref{138b,,sequence} 或而不是字符串，它们必须都是绝对路径。 如果所传入的不是绝对路径则将引发 @ref{16d,,ValueError}。
@end deffn

@node 全局变量,异常与警告,函数<2>,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo globals}@anchor{1a96}
@subsubsection 全局变量


@geindex TZPATH() (在 zoneinfo 模块中)
@anchor{library/zoneinfo zoneinfo TZPATH}@anchor{1a82}
@deffn {数据} zoneinfo.TZPATH

一个表示时区搜索路径的只读序列 -- 当通过键构造 @code{ZoneInfo} 时，键会与 @code{TZPATH} 中的每个条目进行合并，并使用所找到的第一个文件。

@code{TZPATH} 可以只包含绝对路径，绝不包含相对路径，无论它是如何配置的。

@code{zoneinfo.TZPATH} 所指向的对象可能随着对 @ref{1a86,,reset_tzpath()} 的调用而改变，因此推荐使用 @code{zoneinfo.TZPATH} 而不是从 @code{zoneinfo} 导入 @code{TZPATH} 或是将 @code{zoneinfo.TZPATH} 赋值给一个长期变量。

有关配置时区搜索路径的更多信息，请参阅 @ref{1a81,,配置数据源}。
@end deffn

@node 异常与警告,,全局变量,zoneinfo --- IANA 时区支持
@anchor{library/zoneinfo exceptions-and-warnings}@anchor{1a97}
@subsubsection 异常与警告


@geindex ZoneInfoNotFoundError
@anchor{library/zoneinfo zoneinfo ZoneInfoNotFoundError}@anchor{1a7f}
@deffn {例外} zoneinfo.ZoneInfoNotFoundError

当一个 @ref{17f,,ZoneInfo} 对象的构造由于在系统中找不到指定的键而失败时引发。 这是 @ref{3f1,,KeyError} 的一个子类。
@end deffn

@geindex InvalidTZPathWarning
@anchor{library/zoneinfo zoneinfo InvalidTZPathWarning}@anchor{1a8a}
@deffn {例外} zoneinfo.InvalidTZPathWarning

当 
@geindex PYTHONTZPATH
@geindex 环境变量; PYTHONTZPATH
@ref{1a89,,PYTHONTZPATH} 包含将被过滤掉的无效组件，例如一个相对路径时引发。
@end deffn

@c Links and references:

@node calendar --- 日历相关函数,collections --- 容器数据类型,zoneinfo --- IANA 时区支持,数据类型
@anchor{library/calendar doc}@anchor{1a98}@anchor{library/calendar calendar-general-calendar-related-functions}@anchor{1a99}@anchor{library/calendar module-calendar}@anchor{14}@anchor{library/calendar tzdata}@anchor{1a9a}
@subsection @code{calendar} --- 日历相关函数


@geindex calendar (模块)

@strong{源代码：} Lib/calendar.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/calendar.py}


__________________________________________________________________


这个模块让你可以输出像 Unix @code{cal} 那样的日历，它还提供了其它与日历相关的实用函数。 默认情况下，这些日历把星期一当作一周的第一天，星期天为一周的最后一天（按照欧洲惯例）。 可以使用 @ref{1a9b,,setfirstweekday()} 方法设置一周的第一天为星期天 (6) 或者其它任意一天。 使用整数作为指定日期的参数。 更多相关的函数，参见 @ref{30,,datetime} 和 @ref{10c,,time} 模块。

在这个模块中定义的函数和类都基于一个理想化的日历，现行公历向过去和未来两个方向无限扩展。这与 Dershowitz 和 Reingold 的书 "历法计算" 中所有计算的基本日历 -- "proleptic Gregorian" 日历的定义相符合。 ISO 8601标准还规定了 0 和 负数年份。0年指公元前1年， -1年指公元前2年，依此类推。

@geindex Calendar (calendar 中的类)
@anchor{library/calendar calendar Calendar}@anchor{1a9c}
@deffn {类} calendar.Calendar (firstweekday=0)

创建一个 @ref{1a9c,,Calendar} 对象。 @emph{firstweekday} 是一个整数，用于指定一周的第一天。 @code{0} 是星期一（默认值），@code{6} 是星期天。

@ref{1a9c,,Calendar} 对象提供了一些可被用于准备日历数据格式化的方法。 这个类本身不执行任何格式化操作。 这部分任务应由子类来完成。

@ref{1a9c,,Calendar} 类的实例有下列方法：

@geindex iterweekdays() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar iterweekdays}@anchor{1a9d}
@deffn {方法} iterweekdays ()

返回一个迭代器，迭代器的内容为一星期的数字。迭代器的第一个值与 @ref{1a9e,,firstweekday} 属性的值一至。
@end deffn

@geindex itermonthdates() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar itermonthdates}@anchor{5a9}
@deffn {方法} itermonthdates (year, month)

返回一个迭代器，迭代器的内容为 @emph{year} 年 @emph{month} 月(1-12)的日期。这个迭代器返回当月的所有日期 ( @ref{19d,,datetime.date}  对象)，日期包含了本月头尾用于组成完整一周的日期。
@end deffn

@geindex itermonthdays() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar itermonthdays}@anchor{1a9f}
@deffn {方法} itermonthdays (year, month)

返回一个迭代器，迭代器的内容与 @ref{5a9,,itermonthdates()} 类似，为 @emph{year} 年 @emph{month} 月的日期，但不受 @ref{19d,,datetime.date} 范围限制。返回的日期为当月每一天的日期对应的天数。对于不在当月的日期，显示为 @code{0}。
@end deffn

@geindex itermonthdays2() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar itermonthdays2}@anchor{1aa0}
@deffn {方法} itermonthdays2 (year, month)

返回一个迭代器，迭代器的内容与 @ref{5a9,,itermonthdates()} 类似为 @emph{year} 年 @emph{month} 月的日期，但不受 @ref{19d,,datetime.date} 范围的限制。迭代器中的元素为一个由日期和代表星期几的数字组成的的元组。
@end deffn

@geindex itermonthdays3() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar itermonthdays3}@anchor{5aa}
@deffn {方法} itermonthdays3 (year, month)

返回一个迭代器，迭代器的内容与 @ref{5a9,,itermonthdates()} 类似为 @emph{year} 年 @emph{month} 月的日期，但不受 @ref{19d,,datetime.date} 范围的限制。迭代器的元素为一个由年，月，日组成的元组。


3.7 新版功能.

@end deffn

@geindex itermonthdays4() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar itermonthdays4}@anchor{5ab}
@deffn {方法} itermonthdays4 (year, month)

返回一个迭代器，迭代器的内容与 @ref{5a9,,itermonthdates()} 类似为 @emph{year} 年 @emph{month} 月的日期，但不受 @ref{19d,,datetime.date} 范围的限制。迭代器的元素为一个由年，月，日和代表星期几的数字组成的元组。


3.7 新版功能.

@end deffn

@geindex monthdatescalendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar monthdatescalendar}@anchor{1aa1}
@deffn {方法} monthdatescalendar (year, month)

返回一个表示指定年月的周列表。周列表由七个  @ref{19d,,datetime.date} 对象组成。
@end deffn

@geindex monthdays2calendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar monthdays2calendar}@anchor{1aa2}
@deffn {方法} monthdays2calendar (year, month)

返回一个表示指定年月的周列表。周列表由七个代表日期的数字和代表周几的数字组成的二元元组。
@end deffn

@geindex monthdayscalendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar monthdayscalendar}@anchor{1aa3}
@deffn {方法} monthdayscalendar (year, month)

返回一个表示指定年月的周列表。周列表由七个代表日期的数字组成。
@end deffn

@geindex yeardatescalendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar yeardatescalendar}@anchor{1aa4}
@deffn {方法} yeardatescalendar (year, width=3)

返回可以用来格式化的指定年月的数据。返回的值是一个列表，列表是月份组成的行。每一行包含了最多 @emph{width} 个月(默认为3)。每个月包含了4到6周，每周包含1--7天。每一天使用 @ref{19d,,datetime.date} 对象。
@end deffn

@geindex yeardays2calendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar yeardays2calendar}@anchor{1aa5}
@deffn {方法} yeardays2calendar (year, width=3)

返回可以用来模式化的指定年月的数据(与 @ref{1aa4,,yeardatescalendar()} 类似)。周列表的元素是由表示日期的数字和表示星期几的数字组成的元组。不在这个月的日子为0。
@end deffn

@geindex yeardayscalendar() (calendar.Calendar 方法)
@anchor{library/calendar calendar Calendar yeardayscalendar}@anchor{1aa6}
@deffn {方法} yeardayscalendar (year, width=3)

返回可以用来模式化的指定年月的数据(与 @ref{1aa4,,yeardatescalendar()} 类似)。周列表的元素是表示日期的数字。不在这个月的日子为0。
@end deffn
@end deffn

@geindex TextCalendar (calendar 中的类)
@anchor{library/calendar calendar TextCalendar}@anchor{1aa7}
@deffn {类} calendar.TextCalendar (firstweekday=0)

可以使用这个类生成纯文本日历。

@ref{1aa7,,TextCalendar} 实例有以下方法：

@geindex formatmonth() (calendar.TextCalendar 方法)
@anchor{library/calendar calendar TextCalendar formatmonth}@anchor{1aa8}
@deffn {方法} formatmonth (theyear, themonth, w=0, l=0)

返回一个多行字符串来表示指定年月的日历。@emph{w} 为日期的宽度，但始终保持日期居中。@emph{l} 指定了每星期占用的行数。以上这些还依赖于构造器或者 @ref{1a9b,,setfirstweekday()} 方法指定的周的第一天是哪一天。
@end deffn

@geindex prmonth() (calendar.TextCalendar 方法)
@anchor{library/calendar calendar TextCalendar prmonth}@anchor{1aa9}
@deffn {方法} prmonth (theyear, themonth, w=0, l=0)

与 @ref{1aa8,,formatmonth()} 方法一样，返回一个月的日历。
@end deffn

@geindex formatyear() (calendar.TextCalendar 方法)
@anchor{library/calendar calendar TextCalendar formatyear}@anchor{1aaa}
@deffn {方法} formatyear (theyear, w=2, l=1, c=6, m=3)

返回一个多行字符串，这个字符串为一个 @emph{m} 列日历。可选参数 @emph{w}, @emph{l}, 和 @emph{c} 分别表示日期列数， 周的行数， 和月之间的间隔。同样，以上这些还依赖于构造器或者 @ref{1a9b,,setfirstweekday()} 指定哪一天为一周的第一天。日历的第一年由平台依赖于使用的平台。
@end deffn

@geindex pryear() (calendar.TextCalendar 方法)
@anchor{library/calendar calendar TextCalendar pryear}@anchor{1aab}
@deffn {方法} pryear (theyear, w=2, l=1, c=6, m=3)

与 @ref{1aaa,,formatyear()} 方法一样，返回一整年的日历。
@end deffn
@end deffn

@geindex HTMLCalendar (calendar 中的类)
@anchor{library/calendar calendar HTMLCalendar}@anchor{480}
@deffn {类} calendar.HTMLCalendar (firstweekday=0)

可以使用这个类生成 HTML 日历。

@code{HTMLCalendar} 实例有以下方法：

@geindex formatmonth() (calendar.HTMLCalendar 方法)
@anchor{library/calendar calendar HTMLCalendar formatmonth}@anchor{1aac}
@deffn {方法} formatmonth (theyear, themonth, withyear=True)

返回一个 HTML 表格作为指定年月的日历。 @emph{withyear} 为真，则年份将会包含在表头，否则只显示月份。
@end deffn

@geindex formatyear() (calendar.HTMLCalendar 方法)
@anchor{library/calendar calendar HTMLCalendar formatyear}@anchor{1aad}
@deffn {方法} formatyear (theyear, width=3)

返回一个 HTML 表格作为指定年份的日历。 @emph{width} (默认为3) 用于规定每一行显示月份的数量。
@end deffn

@geindex formatyearpage() (calendar.HTMLCalendar 方法)
@anchor{library/calendar calendar HTMLCalendar formatyearpage}@anchor{1aae}
@deffn {方法} formatyearpage (theyear, width=3, css='calendar.css', encoding=None)

返回一个完整的 HTML 页面作为指定年份的日历。 @emph{width*(默认为3) 用于规定每一行显示的月份数量。 *css} 为层叠样式表的名字。如果不使用任何层叠样式表，可以使用 @ref{204,,None} 。 @emph{encoding} 为输出页面的编码 (默认为系统的默认编码)。
@end deffn

@code{HTMLCalendar} 有以下属性，你可以重载它们来自定义应用日历的样式。

@geindex cssclasses (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclasses}@anchor{1aaf}
@deffn {属性} cssclasses

一个对应星期一到星期天的 CSS class 列表。默认列表为

@example
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
@end example

可以向每天加入其它样式

@example
cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
@end example

需要注意的是，列表的长度必须为7。
@end deffn

@geindex cssclass_noday (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_noday}@anchor{1ab0}
@deffn {属性} cssclass_noday

工作日的 CSS 类在上个月或下个月发生。


3.7 新版功能.

@end deffn

@geindex cssclasses_weekday_head (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclasses_weekday_head}@anchor{1ab1}
@deffn {属性} cssclasses_weekday_head

用于标题行中的工作日名称的 CSS 类 列表。默认值与 @ref{1aaf,,cssclasses} 相同。


3.7 新版功能.

@end deffn

@geindex cssclass_month_head (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_month_head}@anchor{1ab2}
@deffn {属性} cssclass_month_head

月份的头 CSS 类（由 @code{formatmonthname()} 使用）。默认值为 @code{"month"} 。


3.7 新版功能.

@end deffn

@geindex cssclass_month (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_month}@anchor{1ab3}
@deffn {属性} cssclass_month

某个月的月历的 CSS 类（由 @ref{1aac,,formatmonth()} 使用）。默认值为 @code{"month"} 。


3.7 新版功能.

@end deffn

@geindex cssclass_year (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_year}@anchor{1ab4}
@deffn {属性} cssclass_year

某年的年历的 CSS 类（由 @ref{1aad,,formatyear()} 使用）。默认值为 @code{"year"} 。


3.7 新版功能.

@end deffn

@geindex cssclass_year_head (calendar.HTMLCalendar 属性)
@anchor{library/calendar calendar HTMLCalendar cssclass_year_head}@anchor{1ab5}
@deffn {属性} cssclass_year_head

年历的·表头 CSS 类（由 @ref{1aad,,formatyear()} 使用）。默认值为 @code{"year"} 。


3.7 新版功能.

@end deffn

需要注意的是，尽管上面命名的样式类都是单独出现的(如： @code{cssclass_month} @code{cssclass_noday}), 但我们可以使用空格将样式类列表中的多个元素分隔开，例如：

@example
"text-bold text-red"
@end example

下面是一个如何自定义  @code{HTMLCalendar} 的示例

@example
class CustomHTMLCal(calendar.HTMLCalendar):
    cssclasses = [style + " text-nowrap" for style in
                  calendar.HTMLCalendar.cssclasses]
    cssclass_month_head = "text-center month-head"
    cssclass_month = "text-center month"
    cssclass_year = "text-italic lead"
@end example
@end deffn

@geindex LocaleTextCalendar (calendar 中的类)
@anchor{library/calendar calendar LocaleTextCalendar}@anchor{1ab6}
@deffn {类} calendar.LocaleTextCalendar (firstweekday=0, locale=None)

这个子类 @ref{1aa7,,TextCalendar} 可以在构造函数中传递一个语言环境名称，并且返回月份和星期几的名称在特定语言环境中。如果此语言环境包含编码，则包含月份和工作日名称的所有字符串将作为 unicode 返回。
@end deffn

@geindex LocaleHTMLCalendar (calendar 中的类)
@anchor{library/calendar calendar LocaleHTMLCalendar}@anchor{1ab7}
@deffn {类} calendar.LocaleHTMLCalendar (firstweekday=0, locale=None)

This subclass of @ref{480,,HTMLCalendar} can be passed a locale name in the
constructor and will return month and weekday names in the specified
locale. If this locale includes an encoding all strings containing month and
weekday names will be returned as unicode.
@end deffn

@cartouche
@quotation 注解 
这两个类的 @code{formatweekday()} 和 @code{formatmonthname()} 方法临时更改dang当前区域至给定 @emph{locale} 。由于当前的区域设置是进程范围的设置，因此它们不是线程安全的。
@end quotation
@end cartouche

对于简单的文本日历，这个模块提供了以下方法。

@geindex setfirstweekday() (在 calendar 模块中)
@anchor{library/calendar calendar setfirstweekday}@anchor{1a9b}
@deffn {函数} calendar.setfirstweekday (weekday)

设置每一周的开始(@code{0} 表示星期一，@code{6} 表示星期天)。calendar还提供了  @code{MONDAY}, @code{TUESDAY}, @code{WEDNESDAY}, @code{THURSDAY}, @code{FRIDAY}, @code{SATURDAY} 和 @code{SUNDAY} 几个常量方便使用。例如，设置每周的第一天为星期天

@example
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
@end example
@end deffn

@geindex firstweekday() (在 calendar 模块中)
@anchor{library/calendar calendar firstweekday}@anchor{1a9e}
@deffn {函数} calendar.firstweekday ()

返回当前设置的每星期的第一天的数值。
@end deffn

@geindex isleap() (在 calendar 模块中)
@anchor{library/calendar calendar isleap}@anchor{1ab8}
@deffn {函数} calendar.isleap (year)

如果 @emph{year} 是闰年则返回  @ref{59c,,True} ,否则返回 @ref{497,,False}。
@end deffn

@geindex leapdays() (在 calendar 模块中)
@anchor{library/calendar calendar leapdays}@anchor{1ab9}
@deffn {函数} calendar.leapdays (y1, y2)

返回在范围 @emph{y1} 至 @emph{y2} （不包括 y2）之间的闰年的年数，其中 @emph{y1} 和 @emph{y2} 是年份。

此函数适用于跨越一个世纪变化的范围。
@end deffn

@geindex weekday() (在 calendar 模块中)
@anchor{library/calendar calendar weekday}@anchor{1aba}
@deffn {函数} calendar.weekday (year, month, day)

返回某年（ @code{1970} -- ...），某月（ @code{1} -- @code{12} ），某日（ @code{1} -- @code{31} ）是星期几（ @code{0} 是星期一）。
@end deffn

@geindex weekheader() (在 calendar 模块中)
@anchor{library/calendar calendar weekheader}@anchor{1abb}
@deffn {函数} calendar.weekheader (n)

返回一个包含星期几的缩写名的头。 @emph{n} 指定星期几缩写的字符宽度。
@end deffn

@geindex monthrange() (在 calendar 模块中)
@anchor{library/calendar calendar monthrange}@anchor{1abc}
@deffn {函数} calendar.monthrange (year, month)

返回指定 @emph{年份} 的指定 @emph{月份} 的第一天是星期几和这个月的天数。
@end deffn

@geindex monthcalendar() (在 calendar 模块中)
@anchor{library/calendar calendar monthcalendar}@anchor{1abd}
@deffn {函数} calendar.monthcalendar (year, month)

返回表示一个月的日历的矩阵。 每一行代表一周；此月份外的日子由零表示。 每周从周一开始，除非使用 @ref{1a9b,,setfirstweekday()} 改变设置。
@end deffn

@geindex prmonth() (在 calendar 模块中)
@anchor{library/calendar calendar prmonth}@anchor{1abe}
@deffn {函数} calendar.prmonth (theyear, themonth, w=0, l=0)

打印由 @ref{1abf,,month()} 返回的一个月的日历。
@end deffn

@geindex month() (在 calendar 模块中)
@anchor{library/calendar calendar month}@anchor{1abf}
@deffn {函数} calendar.month (theyear, themonth, w=0, l=0)

使用 @ref{1aa7,,TextCalendar} 类的 @code{formatmonth()} 以多行字符串形式返回月份日历。
@end deffn

@geindex prcal() (在 calendar 模块中)
@anchor{library/calendar calendar prcal}@anchor{1ac0}
@deffn {函数} calendar.prcal (year, w=0, l=0, c=6, m=3)

打印由 @ref{14,,calendar()} 返回的整年的日历。
@end deffn

@geindex calendar() (在 calendar 模块中)
@anchor{library/calendar calendar calendar}@anchor{1ac1}
@deffn {函数} calendar.calendar (year, w=2, l=1, c=6, m=3)

使用 @ref{1aa7,,TextCalendar} 类的 @code{formatyear()} 返回整年的3列的日历以多行字符串的形式。
@end deffn

@geindex timegm() (在 calendar 模块中)
@anchor{library/calendar calendar timegm}@anchor{1ac2}
@deffn {函数} calendar.timegm (tuple)

一个不相关但很好用的函数，它接受一个时间元组例如 @ref{10c,,time} 模块中的 @ref{c1a,,gmtime()} 函数的返回并返回相应的 Unix 时间戳值，假定 1970 年开始计数， POSIX 编码。实际上， @ref{c1a,,time.gmtime()} 和 @ref{1ac2,,timegm()} 是彼此相反的。
@end deffn

@ref{14,,calendar} 模块包含以下数据属性：

@geindex day_name() (在 calendar 模块中)
@anchor{library/calendar calendar day_name}@anchor{1ac3}
@deffn {数据} calendar.day_name

在当前语言环境下表示星期几的数组。
@end deffn

@geindex day_abbr() (在 calendar 模块中)
@anchor{library/calendar calendar day_abbr}@anchor{1ac4}
@deffn {数据} calendar.day_abbr

在当前语言环境下表示星期几缩写的数组。
@end deffn

@geindex month_name() (在 calendar 模块中)
@anchor{library/calendar calendar month_name}@anchor{1ac5}
@deffn {数据} calendar.month_name

在当前语言环境下表示一年中月份的数组。这遵循一月的月号为 1 的通常惯例，所以它的长度为 13 且 @code{month_name[0]} 是空字符串。
@end deffn

@geindex month_abbr() (在 calendar 模块中)
@anchor{library/calendar calendar month_abbr}@anchor{1ac6}
@deffn {数据} calendar.month_abbr

在当前语言环境下表示月份简写的数组。这遵循一月的月号为 1 的通常惯例，所以它的长度为 13 且 @code{month_abbr[0]} 是空字符串。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{30,,datetime}

为日期和时间提供与 @ref{10c,,time} 模块相似功能的面向对象接口。

@item 模块 @ref{10c,,time}

底层时间相关函数。
@end table


@node collections --- 容器数据类型,collections abc --- 容器的抽象基类,calendar --- 日历相关函数,数据类型
@anchor{library/collections doc}@anchor{1ac7}@anchor{library/collections collections-container-datatypes}@anchor{1ac8}@anchor{library/collections module-collections}@anchor{1d}
@subsection @code{collections} --- 容器数据类型


@geindex collections (模块)

@strong{Source code:} Lib/collections/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/collections/__init__.py}

@c from collections import *
@c import itertools
@c __name__ = '<doctest>'


__________________________________________________________________


这个模块实现了特定目标的容器，以提供Python标准内建容器  @ref{164,,dict} , @ref{1f9,,list} , @ref{1f7,,set} , 和 @ref{1a2,,tuple} 的替代选择。


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{1a1,,namedtuple()}

@tab

创建命名元组子类的工厂函数

@item

@ref{633,,deque}

@tab

类似列表(list)的容器，实现了在两端快速添加(append)和弹出(pop)

@item

@ref{5ac,,ChainMap}

@tab

类似字典(dict)的容器类，将多个映射集合到一个视图里面

@item

@ref{ac2,,Counter}

@tab

字典的子类，提供了可哈希对象的计数功能

@item

@ref{2f1,,OrderedDict}

@tab

字典的子类，保存了他们被添加的顺序

@item

@ref{c15,,defaultdict}

@tab

字典的子类，提供了一个工厂函数，为字典查询提供一个默认值

@item

@ref{10ca,,UserDict}

@tab

封装了字典对象，简化了字典子类化

@item

@ref{1ac9,,UserList}

@tab

封装了列表对象，简化了列表子类化

@item

@ref{7aa,,UserString}

@tab

封装了字符串对象，简化了字符串子类化

@end multitable



Deprecated since version 3.3, will be removed in version 3.10: 已将 @ref{15e,,容器抽象基类} 移至 @ref{1e,,collections.abc} 模块。 为了保持向下兼容性，它们在 Python 3.9 版的这个模块中仍然存在。


@menu
* ChainMap 对象:: 
* Counter 对象:: 
* deque 对象:: 
* defaultdict 对象:: 
* namedtuple() 命名元组的工厂函数: namedtuple 命名元组的工厂函数. 
* OrderedDict 对象:: 
* UserDict 对象:: 
* UserList 对象:: 
* UserString 对象:: 

@end menu

@node ChainMap 对象,Counter 对象,,collections --- 容器数据类型
@anchor{library/collections chainmap-objects}@anchor{1aca}
@subsubsection @code{ChainMap} 对象



3.3 新版功能.


一个 @ref{5ac,,ChainMap} 类是为了将多个映射快速的链接到一起，这样它们就可以作为一个单元处理。它通常比创建一个新字典和多次调用 @ref{e96,,update()} 要快很多。

这个类可以用于模拟嵌套作用域，并且在模版化的时候比较有用。

@geindex ChainMap (collections 中的类)
@anchor{library/collections collections ChainMap}@anchor{5ac}
@deffn {类} collections.ChainMap (*maps)

一个 @ref{5ac,,ChainMap} 将多个字典或者其他映射组合在一起，创建一个单独的可更新的视图。  如果没有 @emph{maps} 被指定，就提供一个默认的空字典，这样一个新链至少有一个映射。

底层映射被存储在一个列表中。这个列表是公开的，可以通过 @emph{maps} 属性存取和更新。没有其他的状态。

搜索查询底层映射，直到一个键被找到。不同的是，写，更新和删除只操作第一个映射。

一个 @ref{5ac,,ChainMap} 通过引用合并底层映射。 所以，如果一个底层映射更新了，这些更改会反映到 @ref{5ac,,ChainMap} 。

支持所有常用字典方法。另外还有一个  @emph{maps} 属性(attribute)，一个创建子上下文的方法(method)， 一个存取它们首个映射的属性(property):

@geindex maps (collections.ChainMap 属性)
@anchor{library/collections collections ChainMap maps}@anchor{1acb}
@deffn {属性} maps

一个可以更新的映射列表。这个列表是按照第一次搜索到最后一次搜索的顺序组织的。它是仅有的存储状态，可以被修改。列表最少包含一个映射。
@end deffn

@geindex new_child() (collections.ChainMap 方法)
@anchor{library/collections collections ChainMap new_child}@anchor{920}
@deffn {方法} new_child (m=None)

返回一个新的 @ref{5ac,,ChainMap} 类，包含了一个新映射(map)，后面跟随当前实例的全部映射(map)。如果 @code{m} 被指定，它就成为不同新的实例，就是在所有映射前加上 m，如果没有指定，就加上一个空字典，这样的话一个 @code{d.new_child()} 调用等价于 @code{ChainMap(@{@}, *d.maps)} 。这个方法用于创建子上下文，不改变任何父映射的值。


在 3.4 版更改: 添加了 @code{m}  可选参数。

@end deffn

@geindex parents (collections.ChainMap 属性)
@anchor{library/collections collections ChainMap parents}@anchor{1acc}
@deffn {属性} parents

属性返回一个新的 @ref{5ac,,ChainMap} 包含所有的当前实例的映射，除了第一个。这样可以在搜索的时候跳过第一个映射。 使用的场景类似在 @ref{1751,,nested scopes} 嵌套作用域中使用 @ref{d0f,,nonlocal} 关键词。用例也可以类比内建函数  @ref{5e6,,super()} 。一个 @code{d.parents} 的引用等价于 @code{ChainMap(*d.maps[1:])} 。
@end deffn

注意，一个 @ref{5ac,,ChainMap()} 的迭代顺序是通过从后往前扫描所有映射来确定的:

@example
>>> baseline = @{'music': 'bach', 'art': 'rembrandt'@}
>>> adjustments = @{'art': 'van gogh', 'opera': 'carmen'@}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']
@end example

这给出了与 @ref{e96,,dict.update()} 调用序列相同的顺序，从最后一个映射开始:

@example
>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']
@end example


在 3.9 版更改: 增加了对 @code{|} 和 @code{|=} 运算符的支持，相关说明见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。

@end deffn


@subsubheading 参见



@itemize *

@item 
MultiContext class@footnote{https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py} 在 Enthought CodeTools package@footnote{https://github.com/enthought/codetools} 有支持写映射的选项。

@item 
Django 中用于模板的 Context class@footnote{https://github.com/django/django/blob/main/django/template/context.py} 是只读的映射链。 它还具有上下文推送和弹出特性，类似于 @ref{920,,new_child()} 方法和 @ref{1acc,,parents} 特征属性。

@item 
Nested Contexts recipe@footnote{https://code.activestate.com/recipes/577434/} 提供了是否对第一个映射或其他映射进行写和其他修改的选项。

@item 
一个 极简的只读版 Chainmap@footnote{https://code.activestate.com/recipes/305268/}.
@end itemize


@menu
* ChainMap 例子和方法:: 

@end menu

@node ChainMap 例子和方法,,,ChainMap 对象
@anchor{library/collections chainmap-examples-and-recipes}@anchor{1acd}
@subsubsection @code{ChainMap} 例子和方法


这一节提供了多个使用链映射的案例。

模拟Python内部lookup链的例子

@example
import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))
@end example

让用户指定的命令行参数优先于环境变量，优先于默认值的例子

@example
import os, argparse

defaults = @{'color': 'red', 'user': 'guest'@}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = @{k: v for k, v in vars(namespace).items() if v is not None@}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])
@end example

用 @ref{5ac,,ChainMap} 类模拟嵌套上下文的例子

@example
c = ChainMap()        # Create root context
d = c.new_child()     # Create nested child context
e = c.new_child()     # Child of c, independent from d
e.maps[0]             # Current context dictionary -- like Python's locals()
e.maps[-1]            # Root context -- like Python's globals()
e.parents             # Enclosing context chain -- like Python's nonlocals

d['x'] = 1            # Set value in current context
d['x']                # Get first key in the chain of contexts
del d['x']            # Delete from current context
list(d)               # All nested values
k in d                # Check all nested values
len(d)                # Number of nested values
d.items()             # All nested items
dict(d)               # Flatten into a regular dictionary
@end example

@ref{5ac,,ChainMap} 类只更新链中的第一个映射，但lookup会搜索整个链。 然而，如果需要深度写和删除，也可以很容易的通过定义一个子类来实现它

@example
class DeepChainMap(ChainMap):
    'Variant of ChainMap that allows direct updates to inner scopes'

    def __setitem__(self, key, value):
        for mapping in self.maps:
            if key in mapping:
                mapping[key] = value
                return
        self.maps[0][key] = value

    def __delitem__(self, key):
        for mapping in self.maps:
            if key in mapping:
                del mapping[key]
                return
        raise KeyError(key)

>>> d = DeepChainMap(@{'zebra': 'black'@}, @{'elephant': 'blue'@}, @{'lion': 'yellow'@})
>>> d['lion'] = 'orange'         # update an existing key two levels down
>>> d['snake'] = 'red'           # new keys get added to the topmost dict
>>> del d['elephant']            # remove an existing key one level down
>>> d                            # display result
DeepChainMap(@{'zebra': 'black', 'snake': 'red'@}, @{@}, @{'lion': 'orange'@})
@end example

@node Counter 对象,deque 对象,ChainMap 对象,collections --- 容器数据类型
@anchor{library/collections counter-objects}@anchor{1ace}
@subsubsection @code{Counter} 对象


一个计数器工具提供快速和方便的计数。比如

@example
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter(@{'blue': 3, 'red': 2, 'green': 1@})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
@end example

@geindex Counter (collections 中的类)
@anchor{library/collections collections Counter}@anchor{ac2}
@deffn {类} collections.Counter ([iterable-or-mapping])

一个 @ref{ac2,,Counter} 是一个 @ref{164,,dict} 的子类，用于计数可哈希对象。它是一个集合，元素像字典键(key)一样存储，它们的计数存储为值。计数可以是任何整数值，包括0和负数。 @ref{ac2,,Counter} 类有点像其他语言中的 bags或multisets。

元素从一个 @emph{iterable} 被计数或从其他的 @emph{mapping} (or counter)初始化：

@example
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter(@{'red': 4, 'blue': 2@})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
@end example

Counter对象有一个字典接口，如果引用的键没有任何记录，就返回一个0，而不是弹出一个 @ref{3f1,,KeyError} :

@example
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
@end example

设置一个计数为0不会从计数器中移去一个元素。使用 @code{del} 来删除它:

@example
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry
@end example


3.1 新版功能.



在 3.7 版更改: 作为 @ref{164,,dict} 的子类，@ref{ac2,,Counter} 继承了记住插入顺序的功能。 @emph{Counter} 对象进行数学运算时同样会保持顺序。 结果会先按每个元素在运算符左边的出现时间排序，然后再按其在运算符右边的出现时间排序。


Counter 对象在对所有字典可用的方法以外还支持一些附加方法:

@geindex elements() (collections.Counter 方法)
@anchor{library/collections collections Counter elements}@anchor{d6a}
@deffn {方法} elements ()

返回一个迭代器，其中每个元素将重复出现计数值所指定次。 元素会按首次出现的顺序返回。 如果一个元素的计数值小于一，@ref{d6a,,elements()} 将会忽略它。

@example
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
@end example
@end deffn

@geindex most_common() (collections.Counter 方法)
@anchor{library/collections collections Counter most_common}@anchor{d69}
@deffn {方法} most_common ([n])

返回一个列表，其中包含 @emph{n} 个最常见的元素及出现次数，按常见程度由高到低排序。 如果 @emph{n} 被省略或为 @code{None}，@ref{d69,,most_common()} 将返回计数器中的 @emph{所有} 元素。 计数值相等的元素按首次出现的顺序排序：

@example
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
@end example
@end deffn

@geindex subtract() (collections.Counter 方法)
@anchor{library/collections collections Counter subtract}@anchor{c35}
@deffn {方法} subtract ([iterable-or-mapping])

从 @emph{迭代对象} 或 @emph{映射对象} 减去元素。像 @ref{e96,,dict.update()} 但是是减去，而不是替换。输入和输出都可以是0或者负数。

@example
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter(@{'a': 3, 'b': 0, 'c': -3, 'd': -6@})
@end example


3.2 新版功能.

@end deffn

通常字典方法都可用于 @ref{ac2,,Counter} 对象，除了有两个方法工作方式与字典并不相同。

@geindex fromkeys() (collections.Counter 方法)
@anchor{library/collections collections Counter fromkeys}@anchor{1acf}
@deffn {方法} fromkeys (iterable)

这个类方法没有在 @ref{ac2,,Counter} 中实现。
@end deffn

@geindex update() (collections.Counter 方法)
@anchor{library/collections collections Counter update}@anchor{1ad0}
@deffn {方法} update ([iterable-or-mapping])

从 @emph{迭代对象} 计数元素或者 从另一个 @emph{映射对象} (或计数器) 添加。 像 @ref{e96,,dict.update()} 但是是加上，而不是替换。另外，@emph{迭代对象} 应该是序列元素，而不是一个 @code{(key, value)} 对。
@end deffn
@end deffn

@ref{ac2,,Counter} 对象的常用案例

@example
sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts
@end example

提供了几个数学操作，可以结合  @ref{ac2,,Counter} 对象，以生产 multisets (计数器中大于0的元素）。 加和减，结合计数器，通过加上或者减去元素的相应计数。交集和并集返回相应计数的最小或最大值。每种操作都可以接受带符号的计数，但是输出会忽略掉结果为零或者小于零的计数。

@example
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter(@{'a': 4, 'b': 3@})
>>> c - d                       # subtract (keeping only positive counts)
Counter(@{'a': 2@})
>>> c & d                       # intersection:  min(c[x], d[x]) 
Counter(@{'a': 1, 'b': 1@})
>>> c | d                       # union:  max(c[x], d[x])
Counter(@{'a': 3, 'b': 2@})
@end example

单目加和减（一元操作符）意思是从空计数器加或者减去。

@example
>>> c = Counter(a=2, b=-4)
>>> +c
Counter(@{'a': 2@})
>>> -c
Counter(@{'b': 4@})
@end example


3.3 新版功能: 添加了对一元加，一元减和位置集合操作的支持。


@cartouche
@quotation 注解 
计数器主要是为了表达运行的正的计数而设计；但是，小心不要预先排除负数或者其他类型。为了帮助这些用例，这一节记录了最小范围和类型限制。


@itemize *

@item 
@ref{ac2,,Counter} 类是一个字典的子类，不限制键和值。值用于表示计数，但你实际上 @emph{可以} 存储任何其他值。

@item 
@ref{d69,,most_common()} 方法在值需要排序的时候用。

@item 
原地操作比如 @code{c[key] += 1} ， 值类型只需要支持加和减。 所以分数，小数，和十进制都可以用，负值也可以支持。这两个方法 @ref{1ad0,,update()} 和 @ref{c35,,subtract()} 的输入和输出也一样支持负数和0。

@item 
Multiset多集合方法只为正值的使用情况设计。输入可以是负数或者0，但只输出计数为正的值。没有类型限制，但值类型需要支持加，减和比较操作。

@item 
@ref{d6a,,elements()} 方法要求正整数计数。忽略0和负数计数。
@end itemize
@end quotation
@end cartouche


@subsubheading 参见



@itemize *

@item 
Bag class@footnote{https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html} 在 Smalltalk。

@item 
Wikipedia 链接 Multisets@footnote{https://en.wikipedia.org/wiki/Multiset}.

@item 
C++ multisets@footnote{http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm} 教程和例子。

@item 
数学操作和多集合用例，参考 @emph{Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19} 。

@item 
在给定数量和集合元素枚举所有不同的多集合，参考 @ref{ceb,,itertools.combinations_with_replacement()}

@example
map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC
@end example
@end itemize


@node deque 对象,defaultdict 对象,Counter 对象,collections --- 容器数据类型
@anchor{library/collections deque-objects}@anchor{1ad1}
@subsubsection @code{deque} 对象


@geindex deque (collections 中的类)
@anchor{library/collections collections deque}@anchor{633}
@deffn {类} collections.deque ([iterable[, maxlen]])

返回一个新的双向队列对象，从左到右初始化(用方法 @ref{1ad2,,append()}) ，从 @emph{iterable} （迭代对象) 数据创建。如果 @emph{iterable} 没有指定，新队列为空。

Deque队列是由栈或者queue队列生成的（发音是 “deck”，”double-ended queue”的简称）。Deque 支持线程安全，内存高效添加(append)和弹出(pop)，从两端都可以，两个方向的大概开销都是 O(1) 复杂度。

虽然 @ref{1f9,,list} 对象也支持类似操作，不过这里优化了定长操作和 @code{pop(0)} 和 @code{insert(0, v)} 的开销。它们引起 O(n) 内存移动的操作，改变底层数据表达的大小和位置。

如果 @emph{maxlen} 没有指定或者是 @code{None} ，deques 可以增长到任意长度。否则，deque就限定到指定最大长度。一旦限定长度的deque满了，当新项加入时，同样数量的项就从另一端弹出。限定长度deque提供类似Unix filter @code{tail} 的功能。它们同样可以用与追踪最近的交换和其他数据池活动。

双向队列(deque)对象支持以下方法：

@geindex append() (collections.deque 方法)
@anchor{library/collections collections deque append}@anchor{1ad2}
@deffn {方法} append (x)

添加 @emph{x} 到右端。
@end deffn

@geindex appendleft() (collections.deque 方法)
@anchor{library/collections collections deque appendleft}@anchor{1ad3}
@deffn {方法} appendleft (x)

添加 @emph{x} 到左端。
@end deffn

@geindex clear() (collections.deque 方法)
@anchor{library/collections collections deque clear}@anchor{1ad4}
@deffn {方法} clear ()

移除所有元素，使其长度为0.
@end deffn

@geindex copy() (collections.deque 方法)
@anchor{library/collections collections deque copy}@anchor{7a8}
@deffn {方法} copy ()

创建一份浅拷贝。


3.5 新版功能.

@end deffn

@geindex count() (collections.deque 方法)
@anchor{library/collections collections deque count}@anchor{c37}
@deffn {方法} count (x)

计算 deque 中元素等于 @emph{x} 的个数。


3.2 新版功能.

@end deffn

@geindex extend() (collections.deque 方法)
@anchor{library/collections collections deque extend}@anchor{1ad5}
@deffn {方法} extend (iterable)

扩展deque的右侧，通过添加iterable参数中的元素。
@end deffn

@geindex extendleft() (collections.deque 方法)
@anchor{library/collections collections deque extendleft}@anchor{1ad6}
@deffn {方法} extendleft (iterable)

扩展deque的左侧，通过添加iterable参数中的元素。注意，左添加时，在结果中iterable参数中的顺序将被反过来添加。
@end deffn

@geindex index() (collections.deque 方法)
@anchor{library/collections collections deque index}@anchor{7a6}
@deffn {方法} index (x[, start[, stop]])

返回 @emph{x} 在 deque 中的位置（在索引 @emph{start} 之后，索引 @emph{stop} 之前）。 返回第一个匹配项，如果未找到则引发 @ref{16d,,ValueError}。


3.5 新版功能.

@end deffn

@geindex insert() (collections.deque 方法)
@anchor{library/collections collections deque insert}@anchor{7a7}
@deffn {方法} insert (i, x)

在位置 @emph{i} 插入 @emph{x} 。

如果插入会导致一个限长 deque 超出长度 @emph{maxlen} 的话，就引发一个 @ref{f3d,,IndexError}。


3.5 新版功能.

@end deffn

@geindex pop() (collections.deque 方法)
@anchor{library/collections collections deque pop}@anchor{1ad7}
@deffn {方法} pop ()

移去并且返回一个元素，deque 最右侧的那一个。 如果没有元素的话，就引发一个 @ref{f3d,,IndexError}。
@end deffn

@geindex popleft() (collections.deque 方法)
@anchor{library/collections collections deque popleft}@anchor{1ad8}
@deffn {方法} popleft ()

移去并且返回一个元素，deque 最左侧的那一个。 如果没有元素的话，就引发 @ref{f3d,,IndexError}。
@end deffn

@geindex remove() (collections.deque 方法)
@anchor{library/collections collections deque remove}@anchor{1ad9}
@deffn {方法} remove (value)

移除找到的第一个 @emph{value}。 如果没有的话就引发 @ref{16d,,ValueError}。
@end deffn

@geindex reverse() (collections.deque 方法)
@anchor{library/collections collections deque reverse}@anchor{c38}
@deffn {方法} reverse ()

将deque逆序排列。返回 @code{None} 。


3.2 新版功能.

@end deffn

@geindex rotate() (collections.deque 方法)
@anchor{library/collections collections deque rotate}@anchor{1ada}
@deffn {方法} rotate (n=1)

向右循环移动 @emph{n} 步。 如果 @emph{n} 是负数，就向左循环。

如果deque不是空的，向右循环移动一步就等价于 @code{d.appendleft(d.pop())} ， 向左循环一步就等价于 @code{d.append(d.popleft())} 。
@end deffn

Deque对象同样提供了一个只读属性:

@geindex maxlen (collections.deque 属性)
@anchor{library/collections collections deque maxlen}@anchor{d6b}
@deffn {属性} maxlen

Deque的最大尺寸，如果没有限定的话就是 @code{None} 。


3.1 新版功能.

@end deffn
@end deffn

除了以上操作，deque 还支持迭代、封存、@code{len(d)}、@code{reversed(d)}、@code{copy.copy(d)}、@code{copy.deepcopy(d)}、成员检测运算符 @ref{179,,in} 以及下标引用例如通过 @code{d[0]} 访问首个元素等。 索引访问在两端的复杂度均为 O(1) 但在中间则会低至 O(n)。 如需快速随机访问，请改用列表。

Deque从版本3.5开始支持 @code{__add__()}, @code{__mul__()}, 和 @code{__imul__()} 。

示例:

@example
>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print(elem.upper())
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])
@end example

@menu
* deque 用法:: 

@end menu

@node deque 用法,,,deque 对象
@anchor{library/collections deque-recipes}@anchor{1adb}
@subsubsection @code{deque} 用法


这一节展示了deque的多种用法。

限长deque提供了类似Unix @code{tail} 过滤功能

@example
def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n)
@end example

另一个用法是维护一个近期添加元素的序列，通过从右边添加和从左边弹出

@example
def moving_average(iterable, n=3):
    # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
    # http://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable)
    d = deque(itertools.islice(it, n-1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n
@end example

一个 轮询调度器@footnote{https://en.wikipedia.org/wiki/Round-robin_scheduling} 可以通过在 @ref{633,,deque} 中放入迭代器来实现。值从当前迭代器的位置0被取出并暂存(yield)。 如果这个迭代器消耗完毕，就用 @ref{1ad8,,popleft()} 将其从对列中移去；否则，就通过  @ref{1ada,,rotate()} 将它移到队列的末尾

@example
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    iterators = deque(map(iter, iterables))
    while iterators:
        try:
            while True:
                yield next(iterators[0])
                iterators.rotate(-1)
        except StopIteration:
            # Remove an exhausted iterator.
            iterators.popleft()
@end example

@ref{1ada,,rotate()} 方法提供了一种方式来实现 @ref{633,,deque} 切片和删除。 例如， 一个纯的Python @code{del d[n]} 实现依赖于 @code{rotate()} 来定位要弹出的元素

@example
def delete_nth(d, n):
    d.rotate(-n)
    d.popleft()
    d.rotate(n)
@end example

要实现 @ref{633,,deque} 切片， 使用一个类似的方法，应用 @ref{1ada,,rotate()} 将目标元素放到左边。通过 @ref{1ad8,,popleft()} 移去老的条目（entries），通过 @ref{1ad5,,extend()} 添加新的条目， 然后反向 rotate。这个方法可以最小代价实现命令式的栈操作，诸如 @code{dup}, @code{drop}, @code{swap}, @code{over}, @code{pick}, @code{rot}, 和 @code{roll} 。

@node defaultdict 对象,namedtuple 命名元组的工厂函数,deque 对象,collections --- 容器数据类型
@anchor{library/collections defaultdict-objects}@anchor{1adc}
@subsubsection @code{defaultdict} 对象


@geindex defaultdict (collections 中的类)
@anchor{library/collections collections defaultdict}@anchor{c15}
@deffn {类} collections.defaultdict (default_factory=None, /[, ...])

返回一个新的类似字典的对象。 @ref{c15,,defaultdict} 是内置 @ref{164,,dict} 类的子类。 它重载了一个方法并添加了一个可写的实例变量。 其余的功能与 @ref{164,,dict} 类相同因而不在此文档中写明。

本对象包含一个名为 @ref{1add,,default_factory} 的属性，构造时，第一个参数用于为该属性提供初始值，默认为 @code{None}。所有其他参数（包括关键字参数）都相当于传递给 @ref{164,,dict} 的构造函数。

@ref{c15,,defaultdict} 对象除了支持标准 @ref{164,,dict} 的操作，还支持以下方法作为扩展：

@geindex __missing__() (collections.defaultdict 方法)
@anchor{library/collections collections defaultdict __missing__}@anchor{1ade}
@deffn {方法} __missing__ (key)

如果 @ref{1add,,default_factory} 属性为 @code{None}，则调用本方法会抛出 @ref{3f1,,KeyError} 异常，附带参数 @emph{key}。

如果 @ref{1add,,default_factory} 不为 @code{None}，则它会被（不带参数地）调用来为 @emph{key} 提供一个默认值，这个值和 @emph{key} 作为一对键值对被插入到字典中，并作为本方法的返回值返回。

如果调用 @ref{1add,,default_factory} 时抛出了异常，这个异常会原封不动地向外层传递。

在无法找到所需键值时，本方法会被 @ref{164,,dict} 中的 @ref{3ad,,__getitem__()} 方法调用。无论本方法返回了值还是抛出了异常，都会被 @ref{3ad,,__getitem__()} 传递。

注意，@ref{1ade,,__missing__()} @emph{不会} 被 @ref{3ad,,__getitem__()} 以外的其他方法调用。意味着 @code{get()} 会像正常的 dict 那样返回 @code{None}，而不是使用 @ref{1add,,default_factory}。
@end deffn

@ref{c15,,defaultdict} 对象支持以下实例变量：

@geindex default_factory (collections.defaultdict 属性)
@anchor{library/collections collections defaultdict default_factory}@anchor{1add}
@deffn {属性} default_factory

本属性由 @ref{1ade,,__missing__()} 方法来调用。如果构造对象时提供了第一个参数，则本属性会被初始化成那个参数，如果未提供第一个参数，则本属性为 @code{None}。
@end deffn


在 3.9 版更改: 增加了合并 (@code{|}) 与更新 (@code{|=}) 运算符，相关说明见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。

@end deffn

@menu
* defaultdict 例子:: 

@end menu

@node defaultdict 例子,,,defaultdict 对象
@anchor{library/collections defaultdict-examples}@anchor{1adf}
@subsubsection @code{defaultdict} 例子


使用 @ref{1f9,,list} 作为 @ref{1add,,default_factory}，很轻松地将（键-值对组成的）序列转换为（键-列表组成的）字典：

@example
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
@end example

当每个键第一次遇见时，它还没有在字典里面，所以自动创建该条目，即调用 @ref{1add,,default_factory} 方法，返回一个空的 @ref{1f9,,list}。 @code{list.append()} 操作添加值到这个新的列表里。当再次存取该键时，就正常操作，@code{list.append()} 添加另一个值到列表中。这个计数比它的等价方法 @ref{aa7,,dict.setdefault()} 要快速和简单：

@example
>>> d = @{@}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
@end example

设置 @ref{1add,,default_factory} 为 @ref{205,,int}，使 @ref{c15,,defaultdict} 用于计数（类似其他语言中的 bag 或 multiset）：

@example
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]
@end example

当一个字母首次遇到时，它会查询失败，则 @ref{1add,,default_factory} 会调用 @ref{205,,int()} 来提供一个整数 0 作为默认值。后续的自增操作建立起对每个字母的计数。

函数 @ref{205,,int()} 总是返回 0，这是常数函数的特殊情况。一个更快和灵活的方法是使用 lambda 函数，可以提供任何常量值（不只是0）：

@example
>>> def constant_factory(value):
...     return lambda: value
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'
@end example

设置 @ref{1add,,default_factory} 为 @ref{1f7,,set} 使 @ref{c15,,defaultdict} 用于构建 set 集合：

@example
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> sorted(d.items())
[('blue', @{2, 4@}), ('red', @{1, 3@})]
@end example

@node namedtuple 命名元组的工厂函数,OrderedDict 对象,defaultdict 对象,collections --- 容器数据类型
@anchor{library/collections namedtuple-factory-function-for-tuples-with-named-fields}@anchor{1ae0}
@subsubsection @code{namedtuple()} 命名元组的工厂函数


命名元组赋予每个位置一个含义，提供可读性和自文档性。它们可以用于任何普通元组，并添加了通过名字获取值的能力，通过索引值也是可以的。

@geindex namedtuple() (在 collections 模块中)
@anchor{library/collections collections namedtuple}@anchor{1a1}
@deffn {函数} collections.namedtuple (typename, field_names, *, rename=False, defaults=None, module=None)

返回一个新的元组子类，名为 @emph{typename} 。这个新的子类用于创建类元组的对象，可以通过字段名来获取属性值，同样也可以通过索引和迭代获取值。子类实例同样有文档字符串（类名和字段名）另外一个有用的 @ref{453,,__repr__()} 方法，以 @code{name=value} 格式列明了元组内容。

@emph{field_names} 是一个像 @code{[‘x’, ‘y’]} 一样的字符串序列。另外 @emph{field_names} 可以是一个纯字符串，用空白或逗号分隔开元素名，比如 @code{'x y'} 或者 @code{'x, y'} 。

任何有效的Python 标识符都可以作为字段名，除了下划线开头的那些。有效标识符由字母，数字，下划线组成，但首字母不能是数字或下划线，另外不能是关键词 @ref{a6,,keyword} 比如 @emph{class}, @emph{for}, @emph{return}, @emph{global}, @emph{pass}, 或 @emph{raise} 。

如果 @emph{rename} 为真， 无效字段名会自动转换成位置名。比如 @code{['abc', 'def', 'ghi', 'abc']} 转换成 @code{['abc', '_1', 'ghi', '_3']} ， 消除关键词 @code{def}  和重复字段名 @code{abc} 。

@emph{defaults} 可以为 @code{None} 或者是一个默认值的 @ref{c84,,iterable} 。如果一个默认值域必须跟其他没有默认值的域在一起出现，@emph{defaults} 就应用到最右边的参数。比如如果域名 @code{['x', 'y', 'z']} 和默认值 @code{(1, 2)} ，那么 @code{x} 就必须指定一个参数值 ，@code{y} 默认值 @code{1} ， @code{z} 默认值 @code{2} 。

如果 @emph{module} 值有定义，命名元组的 @code{__module__} 属性值就被设置。

命名元组实例没有字典，所以它们要更轻量，并且占用更小内存。

要支持封存操作，应当将命名元组类赋值给一个匹配 @emph{typename} 的变量。


在 3.1 版更改: 添加了对 @emph{rename} 的支持。



在 3.6 版更改: @emph{verbose} 和 @emph{rename} 参数成为 @ref{3d6,,仅限关键字参数}.



在 3.6 版更改: 添加了 @emph{module} 参数。



在 3.7 版更改: 移除了 @emph{verbose} 形参和 @code{_source} 属性。



在 3.7 版更改: 添加了 @emph{defaults} 参数和 @code{_field_defaults} 属性。

@end deffn

@example
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
@end example

命名元组尤其有用于赋值 @ref{29,,csv}  @ref{f2,,sqlite3} 模块返回的元组

@example
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
    print(emp.name, emp.title)
@end example

除了继承元组的方法，命名元组还支持三个额外的方法和两个属性。为了防止字段名冲突，方法和属性以下划线开始。

@geindex _make() (collections.somenamedtuple 类方法)
@anchor{library/collections collections somenamedtuple _make}@anchor{1ae1}
@deffn {方法} classmethod somenamedtuple._make (iterable)

类方法从存在的序列或迭代实例创建一个新实例。

@example
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
@end example
@end deffn

@geindex _asdict() (collections.somenamedtuple 方法)
@anchor{library/collections collections somenamedtuple _asdict}@anchor{2f0}
@deffn {方法} somenamedtuple._asdict ()

返回一个新的 @ref{164,,dict} ，它将字段名称映射到它们对应的值：

@example
>>> p = Point(x=11, y=22)
>>> p._asdict()
@{'x': 11, 'y': 22@}
@end example


在 3.1 版更改: 返回一个 @ref{2f1,,OrderedDict} 而不是  @ref{164,,dict} 。



在 3.8 版更改: 返回一个常规 @ref{164,,dict} 而不是 @ref{2f1,,OrderedDict}。 因为自 Python 3.7 起，常规字典已经保证有序。 如果需要 @ref{2f1,,OrderedDict} 的额外特性，推荐的解决方案是将结果转换为需要的类型: @code{OrderedDict(nt._asdict())}。

@end deffn

@geindex _replace() (collections.somenamedtuple 方法)
@anchor{library/collections collections somenamedtuple _replace}@anchor{1ae2}
@deffn {方法} somenamedtuple._replace (**kwargs)

返回一个新的命名元组实例，并将指定域替换为新的值

@example
>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)

>>> for partnum, record in inventory.items():
...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
@end example
@end deffn

@geindex _fields (collections.somenamedtuple 属性)
@anchor{library/collections collections somenamedtuple _fields}@anchor{1ae3}
@deffn {属性} somenamedtuple._fields

字符串元组列出了字段名。用于提醒和从现有元组创建一个新的命名元组类型。

@example
>>> p._fields            # view the field names
('x', 'y')

>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
@end example
@end deffn

@geindex _field_defaults (collections.somenamedtuple 属性)
@anchor{library/collections collections somenamedtuple _field_defaults}@anchor{1ae4}
@deffn {属性} somenamedtuple._field_defaults

字典将字段名称映射到默认值。

@example
>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._field_defaults
@{'balance': 0@}
>>> Account('premium')
Account(type='premium', balance=0)
@end example
@end deffn

要获取这个名字域的值，使用 @ref{554,,getattr()} 函数 :

@example
>>> getattr(p, 'x')
11
@end example

转换一个字典到命名元组，使用 ** 两星操作符 (所述如 @ref{13b8,,解包实参列表}):

@example
>>> d = @{'x': 11, 'y': 22@}
>>> Point(**d)
Point(x=11, y=22)
@end example

因为一个命名元组是一个正常的Python类，它可以很容易的通过子类更改功能。这里是如何添加一个计算域和定宽输出打印格式:

@example
>>> class Point(namedtuple('Point', ['x', 'y'])):
...     __slots__ = ()
...     @@property
...     def hypot(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
...     def __str__(self):
...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

>>> for p in Point(3, 4), Point(14, 5/7):
...     print(p)
Point: x= 3.000  y= 4.000  hypot= 5.000
Point: x=14.000  y= 0.714  hypot=14.018
@end example

上面的子类设置 @code{__slots__} 为一个空元组。通过阻止创建实例字典保持了较低的内存开销。

子类化对于添加和存储新的名字域是无效的。应当通过 @ref{1ae3,,_fields} 创建一个新的命名元组来实现它:

@example
>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
@end example

文档字符串可以自定义，通过直接赋值给 @code{__doc__} 属性:

@example
>>> Book = namedtuple('Book', ['id', 'title', 'authors'])
>>> Book.__doc__ += ': Hardcover book in active collection'
>>> Book.id.__doc__ = '13-digit ISBN'
>>> Book.title.__doc__ = 'Title of first printing'
>>> Book.authors.__doc__ = 'List of authors sorted by last name'
@end example


在 3.5 版更改: 文档字符串属性变成可写。



@subsubheading 参见



@itemize *

@item 
请参阅 @ref{228,,typing.NamedTuple} ，以获取为命名元组添加类型提示的方法。 它还使用 @ref{d3a,,class} 关键字提供了一种优雅的符号:

@example
class Component(NamedTuple):
    part_number: int
    weight: float
    description: Optional[str] = None
@end example

@item 
对于以字典为底层的可变域名， 参考 @ref{1d9,,types.SimpleNamespace()} 。

@item 
@ref{2f,,dataclasses} 模块提供了一个装饰器和一些函数，用于自动将生成的特殊方法添加到用户定义的类中。
@end itemize


@node OrderedDict 对象,UserDict 对象,namedtuple 命名元组的工厂函数,collections --- 容器数据类型
@anchor{library/collections ordereddict-objects}@anchor{1ae5}
@subsubsection @code{OrderedDict} 对象


有序词典就像常规词典一样，但有一些与排序操作相关的额外功能。由于内置的 @ref{164,,dict} 类获得了记住插入顺序的能力（在 Python 3.7 中保证了这种新行为），它们变得不那么重要了。

一些与 @ref{164,,dict} 的不同仍然存在：


@itemize *

@item 
常规的 @ref{164,,dict} 被设计为非常擅长映射操作。 跟踪插入顺序是次要的。

@item 
@ref{2f1,,OrderedDict} 旨在擅长重新排序操作。 空间效率、迭代速度和更新操作的性能是次要的。

@item 
算法上， @ref{2f1,,OrderedDict} 可以比 @ref{164,,dict} 更好地处理频繁的重新排序操作。 这使其适用于跟踪最近的访问（例如在 LRU cache@footnote{https://medium.com/@@krishankantsinghal/my-first-blog-on-medium-583159139237} 中）。

@item 
对于 @ref{2f1,,OrderedDict} ，相等操作检查匹配顺序。

@item 
@ref{2f1,,OrderedDict} 类的 @code{popitem()} 方法有不同的签名。它接受一个可选参数来指定弹出哪个元素。

@item 
@ref{2f1,,OrderedDict} 类有一个 @code{move_to_end()} 方法，可以有效地将元素移动到任一端。

@item 
Python 3.8之前， @ref{164,,dict} 缺少 @ref{631,,__reversed__()} 方法。
@end itemize

@geindex OrderedDict (collections 中的类)
@anchor{library/collections collections OrderedDict}@anchor{2f1}
@deffn {类} collections.OrderedDict ([items])

返回一个 @ref{164,,dict} 子类的实例，它具有专门用于重新排列字典顺序的方法。


3.1 新版功能.


@geindex popitem() (collections.OrderedDict 方法)
@anchor{library/collections collections OrderedDict popitem}@anchor{d54}
@deffn {方法} popitem (last=True)

有序字典的 @ref{d54,,popitem()} 方法移除并返回一个 (key, value) 键值对。 如果 @emph{last} 值为真，则按 @abbr{LIFO} 后进先出的顺序返回键值对，否则就按 @abbr{FIFO} 先进先出的顺序返回键值对。
@end deffn

@geindex move_to_end() (collections.OrderedDict 方法)
@anchor{library/collections collections OrderedDict move_to_end}@anchor{c36}
@deffn {方法} move_to_end (key, last=True)

将现有 @emph{key} 移动到有序字典的任一端。 如果 @emph{last} 为真值（默认）则将元素移至末尾；如果  @emph{last} 为假值则将元素移至开头。如果 @emph{key} 不存在则会触发 @ref{3f1,,KeyError}:

@example
>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> '@w{'}.join(d.keys())
'acdeb'
>>> d.move_to_end('b', last=False)
>>> '@w{'}.join(d.keys())
'bacde'
@end example


3.2 新版功能.

@end deffn
@end deffn

相对于通常的映射方法，有序字典还另外提供了逆序迭代的支持，通过 @ref{2cd,,reversed()} 。

@ref{2f1,,OrderedDict} 之间的相等测试是顺序敏感的，实现为 @code{list(od1.items())==list(od2.items())} 。 @ref{2f1,,OrderedDict} 对象和其他的  @ref{15f,,Mapping} 的相等测试，是顺序敏感的字典测试。这允许 @ref{2f1,,OrderedDict} 替换为任何字典可以使用的场所。


在 3.5 版更改: @ref{2f1,,OrderedDict} 的项(item)，键(key)和值(value) @ref{1ae6,,视图} 现在支持逆序迭代，通过 @ref{2cd,,reversed()} 。



在 3.6 版更改: 
@geindex Python 提高建议; PEP 468
PEP 468@footnote{https://www.python.org/dev/peps/pep-0468} 赞成将关键词参数的顺序保留， 通过传递给 @ref{2f1,,OrderedDict} 构造器和它的 @code{update()} 方法。



在 3.9 版更改: 增加了合并 (@code{|}) 与更新 (@code{|=}) 运算符，相关说明见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。


@menu
* OrderedDict 例子和用法:: 

@end menu

@node OrderedDict 例子和用法,,,OrderedDict 对象
@anchor{library/collections ordereddict-examples-and-recipes}@anchor{1ae7}
@subsubsection @code{OrderedDict} 例子和用法


创建记住键值 @emph{最后} 插入顺序的有序字典变体很简单。 如果新条目覆盖现有条目，则原始插入位置将更改并移至末尾:

@example
class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.move_to_end(key)
@end example

一个 @ref{2f1,,OrderedDict} 对于实现 @ref{2ff,,functools.lru_cache()} 的变体也很有用:

@example
class LRU:

    def __init__(self, func, maxsize=128):
        self.func = func
        self.maxsize = maxsize
        self.cache = OrderedDict()

    def __call__(self, *args):
        if args in self.cache:
            value = self.cache[args]
            self.cache.move_to_end(args)
            return value
        value = self.func(*args)
        if len(self.cache) >= self.maxsize:
            self.cache.popitem(False)
        self.cache[args] = value
        return value
@end example

@c >>> def square(x):
@c ...     return x ** 2
@c ...
@c >>> s = LRU(square, maxsize=5)
@c >>> actual = [(s(x), s(x)) for x in range(20)]
@c >>> expected = [(x**2, x**2) for x in range(20)]
@c >>> actual == expected
@c True
@c >>> actual = list(s.cache.items())
@c >>> expected = [((x,), x**2) for x in range(15, 20)]
@c >>> actual == expected
@c True

@node UserDict 对象,UserList 对象,OrderedDict 对象,collections --- 容器数据类型
@anchor{library/collections userdict-objects}@anchor{1ae8}
@subsubsection @code{UserDict} 对象


@ref{10ca,,UserDict} 类是用作字典对象的外包装。对这个类的需求已部分由直接创建 @ref{164,,dict} 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的字典可以作为属性来访问。

@geindex UserDict (collections 中的类)
@anchor{library/collections collections UserDict}@anchor{10ca}
@deffn {类} collections.UserDict ([initialdata])

模拟字典的类。 这个实例的内容保存在一个常规字典中，它可以通过  @ref{10ca,,UserDict} 实例的 @ref{1ae9,,data} 属性来访问。 如果提供了 @emph{initialdata}，则 @ref{1ae9,,data} 会用其内容来初始化；请注意对 @emph{initialdata} 的引用将不会被保留，以允许它被用于其他目的。

@ref{10ca,,UserDict} 实例提供了以下属性作为扩展方法和操作的支持:

@geindex data (collections.UserDict 属性)
@anchor{library/collections collections UserDict data}@anchor{1ae9}
@deffn {属性} data

一个真实的字典，用于保存 @ref{10ca,,UserDict} 类的内容。
@end deffn
@end deffn

@node UserList 对象,UserString 对象,UserDict 对象,collections --- 容器数据类型
@anchor{library/collections userlist-objects}@anchor{1aea}
@subsubsection @code{UserList} 对象


这个类封装了列表对象。它是一个有用的基础类，对于你想自定义的类似列表的类，可以继承和覆盖现有的方法，也可以添加新的方法。这样我们可以对列表添加新的行为。

对这个类的需求已部分由直接创建 @ref{1f9,,list} 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的列表可以作为属性来访问。

@geindex UserList (collections 中的类)
@anchor{library/collections collections UserList}@anchor{1ac9}
@deffn {类} collections.UserList ([list])

模拟一个列表。这个实例的内容被保存为一个正常列表，通过 @ref{1ac9,,UserList} 的 @ref{1aeb,,data} 属性存取。实例内容被初始化为一个 @emph{list} 的copy，默认为 @code{[]} 空列表。 @emph{list} 可以是迭代对象，比如一个Python列表，或者一个  @ref{1ac9,,UserList} 对象。

@ref{1ac9,,UserList} 提供了以下属性作为可变序列的方法和操作的扩展:

@geindex data (collections.UserList 属性)
@anchor{library/collections collections UserList data}@anchor{1aeb}
@deffn {属性} data

一个 @ref{1f9,,list} 对象用于存储 @ref{1ac9,,UserList} 的内容。
@end deffn
@end deffn

@strong{子类化的要求:} @ref{1ac9,,UserList} 的子类需要提供一个构造器，可以无参数调用，或者一个参数调用。返回一个新序列的列表操作需要创建一个实现类的实例。它假定了构造器可以以一个参数进行调用，这个参数是一个序列对象，作为数据源。

如果一个分离的类不希望依照这个需求，所有的特殊方法就必须重写；请参照源代码进行修改。

@node UserString 对象,,UserList 对象,collections --- 容器数据类型
@anchor{library/collections userstring-objects}@anchor{1aec}
@subsubsection @code{UserString} 对象


@ref{7aa,,UserString} 类是用作字符串对象的外包装。对这个类的需求已部分由直接创建 @ref{206,,str} 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的字符串可以作为属性来访问。

@geindex UserString (collections 中的类)
@anchor{library/collections collections UserString}@anchor{7aa}
@deffn {类} collections.UserString (seq)

模拟一个字符串对象。这个实例对象的内容保存为一个正常字符串，通过 @ref{7aa,,UserString} 的 @ref{1aed,,data} 属性存取。实例内容初始化设置为 @emph{seq} 的copy。@emph{seq} 参数可以是任何可通过内建 @ref{206,,str()} 函数转换为字符串的对象。

@ref{7aa,,UserString} 提供了以下属性作为字符串方法和操作的额外支持：

@geindex data (collections.UserString 属性)
@anchor{library/collections collections UserString data}@anchor{1aed}
@deffn {属性} data

一个真正的 @ref{206,,str} 对象用来存放 @ref{7aa,,UserString} 类的内容。
@end deffn


在 3.5 版更改: 新方法 @code{__getnewargs__}, @code{__rmod__}, @code{casefold}, @code{format_map}, @code{isprintable}, 和 @code{maketrans}。

@end deffn

@node collections abc --- 容器的抽象基类,heapq --- 堆队列算法,collections --- 容器数据类型,数据类型
@anchor{library/collections abc doc}@anchor{1aee}@anchor{library/collections abc collections-abc-abstract-base-classes-for-containers}@anchor{1aef}@anchor{library/collections abc module-collections abc}@anchor{1e}
@subsection @code{collections.abc} --- 容器的抽象基类


@geindex collections.abc (模块)


3.3 新版功能: 该模块曾是 @ref{1d,,collections} 模块的组成部分。


@strong{源代码：} Lib/_collections_abc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/_collections_abc.py}

@c from collections import *
@c import itertools
@c __name__ = '<doctest>'


__________________________________________________________________


该模块定义了一些 @ref{c0e,,抽象基类}，它们可用于判断一个具体类是否具有某一特定的接口；例如，这个类是否可哈希，或其是否为映射类。


3.9 新版功能: 这些抽象类现在都支持 @code{[]}。 参见 @ref{1030,,GenericAlias 类型} 和 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585}。


@menu
* 容器抽象基类:: 

@end menu

@node 容器抽象基类,,,collections abc --- 容器的抽象基类
@anchor{library/collections abc collections-abstract-base-classes}@anchor{15e}@anchor{library/collections abc id1}@anchor{1af0}
@subsubsection 容器抽象基类


这个容器模块提供了以下 @ref{c0e,,ABCs}:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

抽象基类

@tab

继承自

@tab

抽象方法

@tab

Mixin 方法

@item

@ref{184b,,Container}

@tab

@tab

@code{__contains__}

@tab

@item

@ref{1af1,,Hashable}

@tab

@tab

@code{__hash__}

@tab

@item

@ref{1849,,Iterable}

@tab

@tab

@code{__iter__}

@tab

@item

@ref{184a,,Iterator}

@tab

@ref{1849,,Iterable}

@tab

@code{__next__}

@tab

@code{__iter__}

@item

@ref{630,,Reversible}

@tab

@ref{1849,,Iterable}

@tab

@code{__reversed__}

@tab

@item

@ref{7b2,,Generator}

@tab

@ref{184a,,Iterator}

@tab

@code{send}, @code{throw}

@tab

@code{close}, @code{__iter__}, @code{__next__}

@item

@ref{1af2,,Sized}

@tab

@tab

@code{__len__}

@tab

@item

@ref{27b,,Callable}

@tab

@tab

@code{__call__}

@tab

@item

@ref{62f,,Collection}

@tab

@ref{1af2,,Sized},
@ref{1849,,Iterable},
@ref{184b,,Container}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__}

@tab

@item

@ref{1794,,Sequence}

@tab

@ref{630,,Reversible},
@ref{62f,,Collection}

@tab

@code{__getitem__},
@code{__len__}

@tab

@code{__contains__}, @code{__iter__}, @code{__reversed__},
@code{index}, and @code{count}

@item

@ref{7a9,,MutableSequence}

@tab

@ref{1794,,Sequence}

@tab

@code{__getitem__},
@code{__setitem__},
@code{__delitem__},
@code{__len__},
@code{insert}

@tab

继承自 @ref{1794,,Sequence} 的方法，以及 @code{append}, @code{reverse}, @code{extend}, @code{pop}, @code{remove}，和 @code{__iadd__}

@item

@ref{184d,,ByteString}

@tab

@ref{1794,,Sequence}

@tab

@code{__getitem__},
@code{__len__}

@tab

继承自 @ref{1794,,Sequence} 的方法

@item

@ref{1841,,Set}

@tab

@ref{62f,,Collection}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__}

@tab

@code{__le__}, @code{__lt__}, @code{__eq__}, @code{__ne__},
@code{__gt__}, @code{__ge__}, @code{__and__}, @code{__or__},
@code{__sub__}, @code{__xor__}, and @code{isdisjoint}

@item

@ref{184c,,MutableSet}

@tab

@ref{1841,,Set}

@tab

@code{__contains__},
@code{__iter__},
@code{__len__},
@code{add},
@code{discard}

@tab

继承自 @ref{1841,,Set} 的方法以及 @code{clear}, @code{pop}, @code{remove}, @code{__ior__}, @code{__iand__}, @code{__ixor__}，和  @code{__isub__}

@item

@ref{15f,,Mapping}

@tab

@ref{62f,,Collection}

@tab

@code{__getitem__},
@code{__iter__},
@code{__len__}

@tab

@code{__contains__}, @code{keys}, @code{items}, @code{values},
@code{get}, @code{__eq__}, and @code{__ne__}

@item

@ref{ad7,,MutableMapping}

@tab

@ref{15f,,Mapping}

@tab

@code{__getitem__},
@code{__setitem__},
@code{__delitem__},
@code{__iter__},
@code{__len__}

@tab

继承自 @ref{15f,,Mapping} 的方法以及 @code{pop}, @code{popitem}, @code{clear}, @code{update}，和 @code{setdefault}

@item

@ref{184e,,MappingView}

@tab

@ref{1af2,,Sized}

@tab

@tab

@code{__len__}

@item

@ref{1850,,ItemsView}

@tab

@ref{184e,,MappingView},
@ref{1841,,Set}

@tab

@tab

@code{__contains__},
@code{__iter__}

@item

@ref{184f,,KeysView}

@tab

@ref{184e,,MappingView},
@ref{1841,,Set}

@tab

@tab

@code{__contains__},
@code{__iter__}

@item

@ref{1851,,ValuesView}

@tab

@ref{184e,,MappingView},
@ref{62f,,Collection}

@tab

@tab

@code{__contains__}, @code{__iter__}

@item

@ref{7b3,,Awaitable}

@tab

@tab

@code{__await__}

@tab

@item

@ref{7b4,,Coroutine}

@tab

@ref{7b3,,Awaitable}

@tab

@code{send}, @code{throw}

@tab

@code{close}

@item

@ref{7b6,,AsyncIterable}

@tab

@tab

@code{__aiter__}

@tab

@item

@ref{7b5,,AsyncIterator}

@tab

@ref{7b6,,AsyncIterable}

@tab

@code{__anext__}

@tab

@code{__aiter__}

@item

@ref{632,,AsyncGenerator}

@tab

@ref{7b5,,AsyncIterator}

@tab

@code{asend}, @code{athrow}

@tab

@code{aclose}, @code{__aiter__}, @code{__anext__}

@end multitable


@geindex Container (collections.abc 中的类)
@anchor{library/collections abc collections abc Container}@anchor{184b}
@deffn {类} collections.abc.Container

提供了 @ref{df6,,__contains__()} 方法的抽象基类。
@end deffn

@geindex Hashable (collections.abc 中的类)
@anchor{library/collections abc collections abc Hashable}@anchor{1af1}
@deffn {类} collections.abc.Hashable

提供了 @ref{455,,__hash__()} 方法的抽象基类。
@end deffn

@geindex Sized (collections.abc 中的类)
@anchor{library/collections abc collections abc Sized}@anchor{1af2}
@deffn {类} collections.abc.Sized

提供了 @ref{e98,,__len__()} 方法的抽象基类。
@end deffn

@geindex Callable (collections.abc 中的类)
@anchor{library/collections abc collections abc Callable}@anchor{27b}
@deffn {类} collections.abc.Callable

提供了 @ref{158f,,__call__()} 方法的抽象基类。
@end deffn

@geindex Iterable (collections.abc 中的类)
@anchor{library/collections abc collections abc Iterable}@anchor{1849}
@deffn {类} collections.abc.Iterable

提供了 @ref{611,,__iter__()} 方法的抽象基类。

使用 @code{isinstance(obj, Iterable)} 可以检测一个类是否已经注册到了 @ref{1849,,Iterable} 或者实现了 @ref{611,,__iter__()} 函数，但是无法检测这个类是否能够使用 @ref{3ad,,__getitem__()} 方法进行迭代。检测一个对象是否是 @ref{c84,,iterable} 的唯一可信赖的方法是调用 @code{iter(obj)}。
@end deffn

@geindex Collection (collections.abc 中的类)
@anchor{library/collections abc collections abc Collection}@anchor{62f}
@deffn {类} collections.abc.Collection

集合了 Sized 和 Iterable 类的抽象基类。


3.6 新版功能.

@end deffn

@geindex Iterator (collections.abc 中的类)
@anchor{library/collections abc collections abc Iterator}@anchor{184a}
@deffn {类} collections.abc.Iterator

提供了 @ref{178e,,__iter__()} 和 @ref{d34,,__next__()} 方法的抽象基类。参见 @ref{11ba,,iterator} 的定义。
@end deffn

@geindex Reversible (collections.abc 中的类)
@anchor{library/collections abc collections abc Reversible}@anchor{630}
@deffn {类} collections.abc.Reversible

为可迭代类提供了 @ref{631,,__reversed__()} 方法的抽象基类。


3.6 新版功能.

@end deffn

@geindex Generator (collections.abc 中的类)
@anchor{library/collections abc collections abc Generator}@anchor{7b2}
@deffn {类} collections.abc.Generator

生成器类，实现了 
@geindex Python 提高建议; PEP 342
PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} 中定义的协议，继承并扩展了迭代器，提供了 @ref{15fc,,send()}, @ref{1042,,throw()} 和 @ref{15ff,,close()} 方法。参见 @ref{a8c,,generator} 的定义。


3.5 新版功能.

@end deffn

@geindex Sequence (collections.abc 中的类)
@geindex MutableSequence (collections.abc 中的类)
@geindex ByteString (collections.abc 中的类)
@anchor{library/collections abc collections abc Sequence}@anchor{1794}
@deffn {类} collections.abc.Sequence
@anchor{library/collections abc collections abc MutableSequence}@anchor{7a9}
@deffnx {类} collections.abc.MutableSequence
@anchor{library/collections abc collections abc ByteString}@anchor{184d}
@deffnx {类} collections.abc.ByteString

只读且可变的序列 @ref{138b,,sequences} 的抽象基类。

实现笔记：一些混入（Maxin）方法比如 @ref{611,,__iter__()}, @ref{631,,__reversed__()} 和 @code{index()} 会重复调用底层的 @ref{3ad,,__getitem__()} 方法。因此，如果实现的 @ref{3ad,,__getitem__()} 是常数级访问速度，那么相应的混入方法会有一个线性的表现；然而，如果底层方法是线性实现（例如链表），那么混入方法将会是平方级的表现，这也许就需要被重构了。


在 3.5 版更改: index() 方法支持 @emph{stop} 和 @emph{start} 参数。

@end deffn

@geindex Set (collections.abc 中的类)
@geindex MutableSet (collections.abc 中的类)
@anchor{library/collections abc collections abc Set}@anchor{1841}
@deffn {类} collections.abc.Set
@anchor{library/collections abc collections abc MutableSet}@anchor{184c}
@deffnx {类} collections.abc.MutableSet

只读且可变的集合的抽象基类。
@end deffn

@geindex Mapping (collections.abc 中的类)
@geindex MutableMapping (collections.abc 中的类)
@anchor{library/collections abc collections abc Mapping}@anchor{15f}
@deffn {类} collections.abc.Mapping
@anchor{library/collections abc collections abc MutableMapping}@anchor{ad7}
@deffnx {类} collections.abc.MutableMapping

只读且可变的映射 @ref{c14,,mappings} 的抽象基类。
@end deffn

@geindex MappingView (collections.abc 中的类)
@geindex ItemsView (collections.abc 中的类)
@geindex KeysView (collections.abc 中的类)
@geindex ValuesView (collections.abc 中的类)
@anchor{library/collections abc collections abc MappingView}@anchor{184e}
@deffn {类} collections.abc.MappingView
@anchor{library/collections abc collections abc ItemsView}@anchor{1850}
@deffnx {类} collections.abc.ItemsView
@anchor{library/collections abc collections abc KeysView}@anchor{184f}
@deffnx {类} collections.abc.KeysView
@anchor{library/collections abc collections abc ValuesView}@anchor{1851}
@deffnx {类} collections.abc.ValuesView

映射及其键和值的视图 @ref{1ae6,,views} 的抽象基类。
@end deffn

@geindex Awaitable (collections.abc 中的类)
@anchor{library/collections abc collections abc Awaitable}@anchor{7b3}
@deffn {类} collections.abc.Awaitable

为可等待对象 @ref{61b,,awaitable} 提供的类，可以被用于 @ref{2df,,await} 表达式中。习惯上必须实现 @ref{73f,,__await__()} 方法。

@ref{18a,,协程} 对象和 @ref{7b4,,Coroutine} ABC 的实例都是这个 ABC 的实例。

@cartouche
@quotation 注解 
在 CPython 里，基于生成器的协程（使用 @ref{875,,types.coroutine()} 或 @ref{3b0,,asyncio.coroutine()} 包装的生成器）都是 @emph{可等待对象}，即使他们不含有 @ref{73f,,__await__()} 方法。使用 @code{isinstance(gencoro, Awaitable)} 来检测他们会返回 @code{False}。要使用 @ref{7f4,,inspect.isawaitable()} 来检测他们。
@end quotation
@end cartouche


3.5 新版功能.

@end deffn

@geindex Coroutine (collections.abc 中的类)
@anchor{library/collections abc collections abc Coroutine}@anchor{7b4}
@deffn {类} collections.abc.Coroutine

用于协程兼容类的抽象基类。实现了如下定义在 @ref{158d,,协程对象}: 里的方法： @ref{15fb,,send()}，@ref{15fd,,throw()} 和 @ref{15fe,,close()}。通常的实现里还需要实现 @ref{73f,,__await__()} 方法。所有的 @ref{7b4,,Coroutine} 实例都必须是 @ref{7b3,,Awaitable} 实例。参见 @ref{18a,,coroutine} 的定义。

@cartouche
@quotation 注解 
在 CPython 里，基于生成器的协程（使用 @ref{875,,types.coroutine()} 或 @ref{3b0,,asyncio.coroutine()} 包装的生成器）都是 @emph{可等待对象}，即使他们不含有 @ref{73f,,__await__()} 方法。使用 @code{isinstance(gencoro, Coroutine)} 来检测他们会返回 @code{False}。要使用 @ref{7f4,,inspect.isawaitable()} 来检测他们。
@end quotation
@end cartouche


3.5 新版功能.

@end deffn

@geindex AsyncIterable (collections.abc 中的类)
@anchor{library/collections abc collections abc AsyncIterable}@anchor{7b6}
@deffn {类} collections.abc.AsyncIterable

提供了 @code{__aiter__} 方法的抽象基类。参见 @ref{73d,,asynchronous iterable} 的定义。


3.5 新版功能.

@end deffn

@geindex AsyncIterator (collections.abc 中的类)
@anchor{library/collections abc collections abc AsyncIterator}@anchor{7b5}
@deffn {类} collections.abc.AsyncIterator

提供了 @code{__aiter__} 和 @code{__anext__} 方法的抽象基类。参见 @ref{742,,asynchronous iterator} 的定义。


3.5 新版功能.

@end deffn

@geindex AsyncGenerator (collections.abc 中的类)
@anchor{library/collections abc collections abc AsyncGenerator}@anchor{632}
@deffn {类} collections.abc.AsyncGenerator

为异步生成器类提供的抽象基类，这些类实现了定义在 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525} 和 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 里的协议。


3.6 新版功能.

@end deffn

这些抽象基类让我们可以确定类和示例拥有某些特定的函数，例如：

@example
size = None
if isinstance(myvar, collections.abc.Sized):
    size = len(myvar)
@end example

有些抽象基类也可以用作混入类（mixin），这可以更容易地开发支持容器 API 的类。例如，要写一个支持完整 @ref{1841,,Set} API 的类，只需要提供下面这三个方法： @ref{df6,,__contains__()}, @ref{611,,__iter__()} 和 @ref{e98,,__len__()}。抽象基类会补充上其余的方法，比如 @ref{15d3,,__and__()} 和 @code{isdisjoint()}:

@example
class ListBasedSet(collections.abc.Set):
    '@w{'}' Alternate set implementation favoring space over speed
        and not requiring the set elements to be hashable. '@w{'}'
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)

    def __iter__(self):
        return iter(self.elements)

    def __contains__(self, value):
        return value in self.elements

    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2            # The __and__() method is supported automatically
@end example

当把 @ref{1841,,Set} 和 @ref{184c,,MutableSet} 用作混入类时需注意：


@enumerate 

@item 
由于某些集合操作会创建新集合，默认的混入方法需要一种从可迭代对象里创建新实例的方式。 假定类构造器具有 @code{ClassName(iterable)} 形式的签名。 这样它将执行一个名为 @code{_from_iterable()} 的内部类方法，该方法会调用 @code{cls(iterable)} 来产生一个新集合。 如果 @ref{1841,,Set} 混入类在具有不同构造器签名的类中被使用，你将需要通过类方法或常规方法来重载 @code{_from_iterable()}，以便基于可迭代对象参数来构造新的实例。

@item 
重载比较符时时（想必是为了速度，因为其语义都是固定的），只需要重定义 @ref{d70,,__le__()} 和 @ref{d72,,__ge__()} 函数，然后其他的操作会自动跟进。

@item 
混入集合类 @ref{1841,,Set} 提供了一个 @code{_hash()} 方法为集合计算哈希值，然而， @ref{455,,__hash__()} 函数却没有被定义，因为并不是所有集合都是可哈希并且不可变的。为了使用混入类为集合添加哈希能力，可以同时继承 @ref{1841,,Set()} 和 @ref{1af1,,Hashable()} 类，然后定义 @code{__hash__ = Set._hash}。
@end enumerate


@subsubheading 参见



@itemize *

@item 
OrderedSet recipe@footnote{https://code.activestate.com/recipes/576694/} 是基于 @ref{184c,,MutableSet} 构建的一个示例。

@item 
对于抽象基类，参见 @ref{3,,abc} 模块和 
@geindex Python 提高建议; PEP 3119
PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119}。
@end itemize


@node heapq --- 堆队列算法,bisect --- 数组二分查找算法,collections abc --- 容器的抽象基类,数据类型
@anchor{library/heapq doc}@anchor{1af3}@anchor{library/heapq heapq-heap-queue-algorithm}@anchor{1af4}@anchor{library/heapq module-heapq}@anchor{8d}
@subsection @code{heapq} --- 堆队列算法


@geindex heapq (模块)

@strong{源码：}Lib/heapq.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/heapq.py}


__________________________________________________________________


这个模块提供了堆队列算法的实现，也称为优先队列算法。

堆是一个二叉树，它的每个父节点的值都只会小于或等于所有孩子节点（的值）。 它使用了数组来实现：从零开始计数，对于所有的 @emph{k} ，都有 @code{heap[k] <= heap[2*k+1]} 和 @code{heap[k] <= heap[2*k+2]}。 为了便于比较，不存在的元素被认为是无限大。 堆最有趣的特性在于最小的元素总是在根结点：@code{heap[0]}。

这个API与教材的堆算法实现有所不同，具体区别有两方面：（a）我们使用了从零开始的索引。这使得节点和其孩子节点索引之间的关系不太直观但更加适合，因为 Python 使用从零开始的索引。 （b）我们的 pop 方法返回最小的项而不是最大的项（这在教材中称为“最小堆”；而“最大堆”在教材中更为常见，因为它更适用于原地排序）。

基于这两方面，把堆看作原生的Python list也没什么奇怪的： @code{heap[0]} 表示最小的元素，同时 @code{heap.sort()} 维护了堆的不变性！

要创建一个堆，可以使用list来初始化为 @code{[]} ，或者你可以通过一个函数 @ref{1af5,,heapify()} ，来把一个list转换成堆。

定义了以下函数：

@geindex heappush() (在 heapq 模块中)
@anchor{library/heapq heapq heappush}@anchor{1af6}
@deffn {函数} heapq.heappush (heap, item)

将 @emph{item} 的值加入 @emph{heap} 中，保持堆的不变性。
@end deffn

@geindex heappop() (在 heapq 模块中)
@anchor{library/heapq heapq heappop}@anchor{1af7}
@deffn {函数} heapq.heappop (heap)

弹出并返回 @emph{heap} 的最小的元素，保持堆的不变性。如果堆为空，抛出 @ref{f3d,,IndexError} 。使用 @code{heap[0]} ，可以只访问最小的元素而不弹出它。
@end deffn

@geindex heappushpop() (在 heapq 模块中)
@anchor{library/heapq heapq heappushpop}@anchor{1af8}
@deffn {函数} heapq.heappushpop (heap, item)

将 @emph{item} 放入堆中，然后弹出并返回 @emph{heap} 的最小元素。该组合操作比先调用  @ref{1af6,,heappush()} 再调用 @ref{1af7,,heappop()} 运行起来更有效率。
@end deffn

@geindex heapify() (在 heapq 模块中)
@anchor{library/heapq heapq heapify}@anchor{1af5}
@deffn {函数} heapq.heapify (x)

将list @emph{x} 转换成堆，原地，线性时间内。
@end deffn

@geindex heapreplace() (在 heapq 模块中)
@anchor{library/heapq heapq heapreplace}@anchor{1af9}
@deffn {函数} heapq.heapreplace (heap, item)

弹出并返回 @emph{heap} 中最小的一项，同时推入新的 @emph{item}。 堆的大小不变。 如果堆为空则引发 @ref{f3d,,IndexError}。

这个单步骤操作比 @ref{1af7,,heappop()} 加 @ref{1af6,,heappush()} 更高效，并且在使用固定大小的堆时更为适宜。 pop/push 组合总是会从堆中返回一个元素并将其替换为 @emph{item}。

返回的值可能会比添加的 @emph{item} 更大。 如果不希望如此，可考虑改用 @ref{1af8,,heappushpop()}。 它的 push/pop 组合会返回两个值中较小的一个，将较大的值留在堆中。
@end deffn

该模块还提供了三个基于堆的通用功能函数。

@geindex merge() (在 heapq 模块中)
@anchor{library/heapq heapq merge}@anchor{7db}
@deffn {函数} heapq.merge (*iterables, key=None, reverse=False)

将多个已排序的输入合并为一个已排序的输出（例如，合并来自多个日志文件的带时间戳的条目）。 返回已排序值的 @ref{11ba,,iterator}。

类似于 @code{sorted(itertools.chain(*iterables))} 但返回一个可迭代对象，不会一次性地将数据全部放入内存，并假定每个输入流都是已排序的（从小到大）。

具有两个可选参数，它们都必须指定为关键字参数。

@emph{key} 指定带有单个参数的 @ref{7dc,,key function}，用于从每个输入元素中提取比较键。 默认值为 @code{None} (直接比较元素)。

@emph{reverse} 为一个布尔值。 如果设为 @code{True}，则输入元素将按比较结果逆序进行合并。 要达成与 @code{sorted(itertools.chain(*iterables), reverse=True)} 类似的行为，所有可迭代对象必须是已从大到小排序的。


在 3.5 版更改: 添加了可选的 @emph{key} 和 @emph{reverse} 形参。

@end deffn

@geindex nlargest() (在 heapq 模块中)
@anchor{library/heapq heapq nlargest}@anchor{1afa}
@deffn {函数} heapq.nlargest (n, iterable, key=None)

从 @emph{iterable} 所定义的数据集中返回前 @emph{n} 个最大元素组成的列表。 如果提供了 @emph{key} 则其应指定一个单参数的函数，用于从 @emph{iterable} 的每个元素中提取比较键 (例如 @code{key=str.lower})。 等价于:  @code{sorted(iterable, key=key, reverse=True)[:n]}。
@end deffn

@geindex nsmallest() (在 heapq 模块中)
@anchor{library/heapq heapq nsmallest}@anchor{1afb}
@deffn {函数} heapq.nsmallest (n, iterable, key=None)

从 @emph{iterable} 所定义的数据集中返回前 @emph{n} 个最小元素组成的列表。 如果提供了 @emph{key} 则其应指定一个单参数的函数，用于从 @emph{iterable} 的每个元素中提取比较键 (例如 @code{key=str.lower})。 等价于: @code{sorted(iterable, key=key)[:n]}。
@end deffn

后两个函数在 @emph{n} 值较小时性能最好。 对于更大的值，使用 @ref{54f,,sorted()} 函数会更有效率。 此外，当 @code{n==1} 时，使用内置的 @ref{900,,min()} 和 @ref{901,,max()} 函数会更有效率。 如果需要重复使用这些函数，请考虑将可迭代对象转为真正的堆。

@menu
* 基本示例:: 
* 优先队列实现说明:: 
* 理论:: 

@end menu

@node 基本示例,优先队列实现说明,,heapq --- 堆队列算法
@anchor{library/heapq basic-examples}@anchor{1afc}
@subsubsection 基本示例


堆排序@footnote{https://en.wikipedia.org/wiki/Heapsort} 可以通过将所有值推入堆中然后每次弹出一个最小值项来实现。

@example
>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@end example

这类似于 @code{sorted(iterable)}，但与 @ref{54f,,sorted()} 不同的是这个实现是不稳定的。

堆元素可以为元组。 这适用于将比较值（例如任务优先级）与跟踪的主记录进行赋值的场合:

@example
>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')
@end example

@node 优先队列实现说明,理论,基本示例,heapq --- 堆队列算法
@anchor{library/heapq priority-queue-implementation-notes}@anchor{1afd}
@subsubsection 优先队列实现说明


优先队列@footnote{https://en.wikipedia.org/wiki/Priority_queue} 是堆的常用场合，并且它的实现包含了多个挑战：


@itemize *

@item 
排序稳定性：你该如何令相同优先级的两个任务按它们最初被加入时的顺序返回？

@item 
如果优先级相同且任务没有默认比较顺序，则 (priority, task) 对的元组比较将会中断。

@item 
如果任务优先级发生改变，你该如何将其移至堆中的新位置？

@item 
或者如果一个挂起的任务需要被删除，你该如何找到它并将其移出队列？
@end itemize

针对前两项挑战的一种解决方案是将条目保存为包含优先级、条目计数和任务对象 3 个元素的列表。 条目计数可用来打破平局，这样具有相同优先级的任务将按它们的添加顺序返回。 并且由于没有哪两个条目计数是相同的，元组比较将永远不会直接比较两个任务。

不可比较任务问题的另一种解决方案是创建一个忽略任务条目并且只比较优先级字段的包装器类:

@example
from dataclasses import dataclass, field
from typing import Any

@@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)
@end example

其余的挑战主要包括找到挂起的任务并修改其优先级或将其完全移除。 找到一个任务可使用一个指向队列中条目的字典来实现。

移除条目或改变其优先级的操作实现起来更为困难，因为它会破坏堆结构不变量。 因此，一种可能的解决方案是将条目标记为已移除，再添加一个改变了优先级的新条目:

@example
pq = []                         # list of entries arranged in a heap
entry_finder = @{@}               # mapping of tasks to entries
REMOVED = '<removed-task>'      # placeholder for a removed task
counter = itertools.count()     # unique sequence count

def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')
@end example

@node 理论,,优先队列实现说明,heapq --- 堆队列算法
@anchor{library/heapq theory}@anchor{1afe}
@subsubsection 理论


堆是通过数组来实现的，其中的元素从 0 开始计数，对于所有的 @emph{k} 都有 @code{a[k] <= a[2*k+1]} 且 @code{a[k] <= a[2*k+2]}。 为了便于比较，不存在的元素被视为无穷大。 堆最有趣的特性在于 @code{a[0]} 总是其中最小的元素。

上面的特殊不变量是用来作为一场锦标赛的高效内存表示。 下面的数字是 @emph{k} 而不是 @code{a[k]}:

@example
                               0

              1                                 2

      3               4                5               6

  7       8       9       10      11      12      13      14

15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30
@end example

在上面的树中，每个 @emph{k} 单元都位于 @code{2*k+1} 和 @code{2*k+2} 之上。 体育运动中我们经常见到二元锦标赛模式，每个胜者单元都位于另两个单元之上，并且我们可以沿着树形图向下追溯胜者所遇到的所有对手。 但是，在许多采用这种锦标赛模式的计算机应用程序中，我们并不需要追溯胜者的历史。 为了获得更高的内存利用效率，当一个胜者晋级时，我们会用较低层级的另一条目来替代它，因此规则变为一个单元和它之下的两个单元包含三个不同条目，上方单元“胜过”了两个下方单元。

如果此堆的不变性质始终受到保护，则序号 0 显然是总的赢家。 删除它并找出“下一个”赢家的最简单算法方式是将某个输家（让我们假定是上图中的 30 号单元）移至 0 号位置，然后将这个新的 0 号沿树下行，不断进行值的交换，直到不变性质得到重建。 这显然会是树中条目总数的对数。 通过迭代所有条目，你将得到一个 O(n log n) 复杂度的排序。

此排序有一个很好的特性就是你可以在排序进行期间高效地插入新条目，前提是插入的条目不比你最近取出的 0 号元素“更好”。 这在模拟上下文时特别有用，在这种情况下树保存的是所有传入事件，“胜出”条件是最小调度时间。 当一个事件将其他事件排入执行计划时，它们的调试时间向未来方向延长，这样它们可方便地入堆。 因此，堆结构很适宜用来实现调度器，我的 MIDI 音序器就是用的这个 :-)。

用于实现调度器的各种结构都得到了充分的研究，堆是非常适宜的一种，因为它们的速度相当快，并且几乎是恒定的，最坏的情况与平均情况没有太大差别。 虽然还存在其他总体而言更高效的实现方式，但其最坏的情况却可能非常糟糕。

堆在大磁盘排序中也非常有用。 你应该已经了解大规模排序会有多个“运行轮次”（即预排序的序列，其大小通常与 CPU 内存容量相关），随后这些轮次会进入合并通道，轮次合并的组织往往非常巧妙 @footnote{@w{(1)} 
当前时代的磁盘平衡算法与其说是巧妙，不如说是麻烦，这是由磁盘的寻址能力导致的结果。 在无法寻址的设备例如大型磁带机上，情况则相当不同，开发者必须非常聪明地（极为提前地）确保每次磁带转动都尽可能地高效（就是说能够最好地加入到合并“进程”中）。 有些磁带甚至能够反向读取，这也被用来避免倒带的耗时。 请相信我，真正优秀的磁带机排序看起来是极其壮观的，排序从来都是一门伟大的艺术！ :-)
}。 非常重要的一点是初始排序应产生尽可能长的运行轮次。 锦标赛模式是达成此目标的好办法。 如果你使用全部有用内存来进行锦标赛，替换和安排恰好适合当前运行轮次的条目，你将可以对于随机输入生成两倍于内存大小的运行轮次，对于模糊排序的输入还会有更好的效果。

另外，如果你输出磁盘上的第 0 个条目并获得一个可能不适合当前锦标赛的输入（因为其值要“胜过”上一个输出值），它无法被放入堆中，因此堆的尺寸将缩小。 被释放的内存可以被巧妙地立即重用以逐步构建第二个堆，其增长速度与第一个堆的缩减速度正好相同。 当第一个堆完全消失时，你可以切换新堆并启动新的运行轮次。 这样做既聪明又高效！

总之，堆是值得了解的有用内存结构。 我在一些应用中用到了它们，并且认为保留一个 'heap' 模块是很有意义的。 :-)

@node bisect --- 数组二分查找算法,array --- 高效的数值数组,heapq --- 堆队列算法,数据类型
@anchor{library/bisect doc}@anchor{1aff}@anchor{library/bisect bisect-array-bisection-algorithm}@anchor{1b00}@anchor{library/bisect module-bisect}@anchor{11}
@subsection @code{bisect} --- 数组二分查找算法


@geindex bisect (模块)

@c example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>

@strong{源代码：} Lib/bisect.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/bisect.py}


__________________________________________________________________


这个模块对有序列表提供了支持，使得他们可以在插入新数据仍然保持有序。对于长列表，如果其包含元素的比较操作十分昂贵的话，这可以是对更常见方法的改进。这个模块叫做 @ref{11,,bisect} 因为其使用了基本的二分（bisection）算法。源代码也可以作为很棒的算法示例（边界判断也做好啦！）

定义了以下函数：

@geindex bisect_left() (在 bisect 模块中)
@anchor{library/bisect bisect bisect_left}@anchor{1b01}
@deffn {函数} bisect.bisect_left (a, x, lo=0, hi=len(a))

在 @emph{a} 中找到 @emph{x} 合适的插入点以维持有序。参数 @emph{lo} 和 @emph{hi} 可以被用于确定需要考虑的子集；默认情况下整个列表都会被使用。如果 @emph{x} 已经在 @emph{a} 里存在，那么插入点会在已存在元素之前（也就是左边）。如果 @emph{a} 是列表（list）的话，返回值是可以被放在 @code{list.insert()} 的第一个参数的。

返回的插入点 @emph{i} 可以将数组 @emph{a} 分成两部分。左侧是 @code{all(val < x for val in a[lo:i])} ，右侧是 @code{all(val >= x for val in a[i:hi])} 。
@end deffn

@geindex bisect_right() (在 bisect 模块中)
@geindex bisect() (在 bisect 模块中)
@anchor{library/bisect bisect bisect_right}@anchor{1b02}
@deffn {函数} bisect.bisect_right (a, x, lo=0, hi=len(a))
@anchor{library/bisect bisect bisect}@anchor{1b03}
@deffnx {函数} bisect.bisect (a, x, lo=0, hi=len(a))

类似于 @ref{1b01,,bisect_left()}，但是返回的插入点是 @emph{a} 中已存在元素 @emph{x} 的右侧。

返回的插入点 @emph{i} 可以将数组 @emph{a} 分成两部分。左侧是 @code{all(val <= x for val in a[lo:i])}，右侧是 @code{all(val > x for val in a[i:hi])} for the right side。
@end deffn

@geindex insort_left() (在 bisect 模块中)
@anchor{library/bisect bisect insort_left}@anchor{1b04}
@deffn {函数} bisect.insort_left (a, x, lo=0, hi=len(a))

将 @emph{x} 插入到一个有序序列 @emph{a} 里，并维持其有序。如果 @emph{a} 有序的话，这相当于 @code{a.insert(bisect.bisect_left(a, x, lo, hi), x)}。要注意搜索是 O(log n) 的，插入却是 O(n) 的。
@end deffn

@geindex insort_right() (在 bisect 模块中)
@geindex insort() (在 bisect 模块中)
@anchor{library/bisect bisect insort_right}@anchor{1b05}
@deffn {函数} bisect.insort_right (a, x, lo=0, hi=len(a))
@anchor{library/bisect bisect insort}@anchor{1b06}
@deffnx {函数} bisect.insort (a, x, lo=0, hi=len(a))

类似于 @ref{1b04,,insort_left()}，但是把 @emph{x} 插入到 @emph{a} 中已存在元素 @emph{x} 的右侧。
@end deffn


@subsubheading 参见


SortedCollection recipe@footnote{https://code.activestate.com/recipes/577197-sortedcollection/} 使用 bisect 构造了一个功能完整的集合类，提供了直接的搜索方法和对用于搜索的 key 方法的支持。所有用于搜索的键都是预先计算的，以避免在搜索时对 key 方法的不必要调用。


@menu
* 搜索有序列表:: 
* 其他示例:: 

@end menu

@node 搜索有序列表,其他示例,,bisect --- 数组二分查找算法
@anchor{library/bisect searching-sorted-lists}@anchor{1b07}
@subsubsection 搜索有序列表


上面的 @ref{11,,bisect()} 函数对于找到插入点是有用的，但在一般的搜索任务中可能会有点尴尬。下面 5 个函数展示了如何将其转变成有序列表中的标准查找函数

@example
def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    'Find leftmost item greater than or equal to x'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError
@end example

@node 其他示例,,搜索有序列表,bisect --- 数组二分查找算法
@anchor{library/bisect other-examples}@anchor{1b08}
@subsubsection 其他示例

@anchor{library/bisect bisect-example}@anchor{1b09}
函数 @ref{11,,bisect()} 还可以用于数字表查询。这个例子是使用 @ref{11,,bisect()} 从一个给定的考试成绩集合里，通过一个有序数字表，查出其对应的字母等级：90 分及以上是 'A'，80 到 89 是 'B'，以此类推

@example
>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
...     i = bisect(breakpoints, score)
...     return grades[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
@end example

与 @ref{54f,,sorted()} 函数不同，对于 @ref{11,,bisect()} 函数来说，@emph{key} 或者 @emph{reversed} 参数并没有什么意义。因为这会导致设计效率低下（连续调用 bisect 函数时，是不会 "记住" 过去查找过的键的）。

正相反，最好去搜索预先计算好的键列表，来查找相关记录的索引。

@example
>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])
>>> keys = [r[1] for r in data]         # precomputed list of keys
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)
@end example

@node array --- 高效的数值数组,weakref --- 弱引用,bisect --- 数组二分查找算法,数据类型
@anchor{library/array doc}@anchor{1b0a}@anchor{library/array array-efficient-arrays-of-numeric-values}@anchor{1b0b}@anchor{library/array module-array}@anchor{6}
@subsection @code{array} --- 高效的数值数组


@geindex array (模块)

@geindex arrays


__________________________________________________________________


此模块定义了一种对象类型，可以紧凑地表示基本类型值的数组：字符、整数、浮点数等。 数组属于序列类型，其行为与列表非常相似，不同之处在于其中存储的对象类型是受限的。 类型在对象创建时使用单个字符的 @emph{类型码} 来指定。 已定义的类型码如下：


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

类型码

@tab

C 类型

@tab

Python 类型

@tab

以字节表示的最小尺寸

@tab

注释

@item

@code{'b'}

@tab

signed char

@tab

int

@tab

1

@tab

@item

@code{'B'}

@tab

unsigned char

@tab

int

@tab

1

@tab

@item

@code{'u'}

@tab

wchar_t

@tab

Unicode 字符

@tab

2

@tab

(1)

@item

@code{'h'}

@tab

signed short

@tab

int

@tab

2

@tab

@item

@code{'H'}

@tab

unsigned short

@tab

int

@tab

2

@tab

@item

@code{'i'}

@tab

signed int

@tab

int

@tab

2

@tab

@item

@code{'I'}

@tab

unsigned int

@tab

int

@tab

2

@tab

@item

@code{'l'}

@tab

signed long

@tab

int

@tab

4

@tab

@item

@code{'L'}

@tab

unsigned long

@tab

int

@tab

4

@tab

@item

@code{'q'}

@tab

signed long long

@tab

int

@tab

8

@tab

@item

@code{'Q'}

@tab

unsigned long long

@tab

int

@tab

8

@tab

@item

@code{'f'}

@tab

float

@tab

float

@tab

4

@tab

@item

@code{'d'}

@tab

double

@tab

float

@tab

8

@tab

@end multitable


注释:


@enumerate 

@item 
由于平台的不同它可能为 16 位或 32 位。


在 3.9 版更改: @code{array('u')} 现在使用 @code{wchar_t} 作为 C 类型而不再是已弃用的 @code{Py_UNICODE}。 这个改变不会影响其行为，因为 @code{Py_UNICODE} 自 Python 3.3 起就是 @code{wchar_t} 的别名。



Deprecated since version 3.3, will be removed in version 4.0.

@end enumerate

值的实际表示会由机器的架构决定（严格地说是由 C 实现决定）。 实际大小可通过 @code{itemsize} 属性来获取。

这个模块定义了以下类型：

@geindex array (array 中的类)
@anchor{library/array array array}@anchor{217}
@deffn {类} array.array (typecode[, initializer])

一个包含由 @emph{typecode} 限制类型的条目的新数组，并由可选的 @emph{initializer} 值进行初始化，该值必须为一个列表、@ref{6e9,,bytes-like object} 或包含正确类型元素的可迭代对象。

如果给定一个列表或字符串，该 initializer 会被传给新数组的 @ref{1b0c,,fromlist()}, @ref{1b0d,,frombytes()} 或 @ref{1b0e,,fromunicode()} 方法（见下文）以将初始条目添加到数组中。 否则会将可迭代对象作为 initializer 传给 @ref{1b0f,,extend()} 方法。

引发一个 @ref{fec,,审计事件} @code{array.__new__} 附带参数 @code{typecode}, @code{initializer}。
@end deffn

@geindex typecodes() (在 array 模块中)
@anchor{library/array array typecodes}@anchor{1b10}
@deffn {数据} array.typecodes

包含所有可用类型码的字符串。
@end deffn

数组对象支持普通的序列操作如索引、切片、拼接和重复等。 当使用切片赋值时，所赋的值必须为具有相同类型码的数组对象；所有其他情况都将引发 @ref{1ff,,TypeError}。 数组对象也实现了缓冲区接口，可以用于所有支持 @ref{6e9,,字节类对象} 的场合。

以下数据项和方法也受到支持：

@geindex typecode (array.array 属性)
@anchor{library/array array array typecode}@anchor{1b11}
@deffn {属性} array.typecode

用于创建数组的类型码字符。
@end deffn

@geindex itemsize (array.array 属性)
@anchor{library/array array array itemsize}@anchor{1b12}
@deffn {属性} array.itemsize

在内部表示中一个数组项的字节长度。
@end deffn

@geindex append() (array.array 方法)
@anchor{library/array array array append}@anchor{1b13}
@deffn {方法} array.append (x)

添加一个值为 @emph{x} 的新项到数组末尾。
@end deffn

@geindex buffer_info() (array.array 方法)
@anchor{library/array array array buffer_info}@anchor{1b14}
@deffn {方法} array.buffer_info ()

返回一个元组 @code{(address, length)} 以给出用于存放数组内容的缓冲区元素的当前内存地址和长度。 以字节表示的内存缓冲区大小可通过 @code{array.buffer_info()[1] * array.itemsize} 来计算。 这在使用需要内存地址的低层级（因此不够安全） I/O 接口时会很有用，例如某些 @code{ioctl()} 操作。 只要数组存在并且没有应用改变长度的操作，返回数值就是有效的。

@cartouche
@quotation 注解 
当在 C 或 C++ 编写的代码中使用数组对象时（这是有效使用此类信息的唯一方式），使用数组对象所支持的缓冲区接口更为适宜。 此方法仅保留用作向下兼容，应避免在新代码中使用。 缓冲区接口的文档参见 @ref{174c,,缓冲协议}。
@end quotation
@end cartouche
@end deffn

@geindex byteswap() (array.array 方法)
@anchor{library/array array array byteswap}@anchor{1b15}
@deffn {方法} array.byteswap ()

“字节对调”所有数组项。 此方法只支持大小为 1, 2, 4 或 8 字节的值；对于其他值类型将引发 @ref{3e4,,RuntimeError}。 它适用于从不同字节序机器所生成的文件中读取数据的情况。
@end deffn

@geindex count() (array.array 方法)
@anchor{library/array array array count}@anchor{1b16}
@deffn {方法} array.count (x)

返回 @emph{x} 在数组中的出现次数。
@end deffn

@geindex extend() (array.array 方法)
@anchor{library/array array array extend}@anchor{1b0f}
@deffn {方法} array.extend (iterable)

将来自 @emph{iterable} 的项添加到数组末尾。 如果 @emph{iterable} 是另一个数组，它必须具有 @emph{完全} 相同的类型码；否则将引发 @ref{1ff,,TypeError}。 如果 @emph{iterable} 不是一个数组，则它必须为可迭代对象并且其元素必须为可添加到数组的适当类型。
@end deffn

@geindex frombytes() (array.array 方法)
@anchor{library/array array array frombytes}@anchor{1b0d}
@deffn {方法} array.frombytes (s)

添加来自字节串的项，将字符节解读为机器值的数组（相当于使用 @ref{1b17,,fromfile()} 方法从文件中读取数据）。


3.2 新版功能: @code{fromstring()} 重命名为 @ref{1b0d,,frombytes()} 以使其含义更清晰。

@end deffn

@geindex fromfile() (array.array 方法)
@anchor{library/array array array fromfile}@anchor{1b17}
@deffn {方法} array.fromfile (f, n)

从 @ref{c1d,,file object} @emph{f} 中读取 @emph{n} 项并将它们添加到数组末尾。 如果可用数据少于 @emph{n} 项，则会引发 @ref{d3c,,EOFError}，但可用的项仍然会被插入数组。
@end deffn

@geindex fromlist() (array.array 方法)
@anchor{library/array array array fromlist}@anchor{1b0c}
@deffn {方法} array.fromlist (list)

添加来自 list 的项。 这等价于 @code{for x in list: a.append(x)}，区别在于如果发生类型错误，数组将不会被改变。
@end deffn

@geindex fromunicode() (array.array 方法)
@anchor{library/array array array fromunicode}@anchor{1b0e}
@deffn {方法} array.fromunicode (s)

使用来自给定 Unicode 字符串的数组扩展数组。 数组必须是类型为 @code{'u'} 的数组；否则将引发 @ref{16d,,ValueError}。 请使用 @code{array.frombytes(unicodestring.encode(enc))} 来将 Unicode 数据添加到其他类型的数组。
@end deffn

@geindex index() (array.array 方法)
@anchor{library/array array array index}@anchor{1066}
@deffn {方法} array.index (x)

返回最小的 @emph{i} 使得 @emph{i} 为 @emph{x} 在数组中首次出现的序号。
@end deffn

@geindex insert() (array.array 方法)
@anchor{library/array array array insert}@anchor{1b18}
@deffn {方法} array.insert (i, x)

将值 @emph{x} 作为新项插入数组的 @emph{i} 位置之前。 负值将被视为相对于数组末尾的位置。
@end deffn

@geindex pop() (array.array 方法)
@anchor{library/array array array pop}@anchor{1b19}
@deffn {方法} array.pop ([i])

从数组中移除序号为 @emph{i} 的项并将其返回。 可选参数值默认为 @code{-1}，因此默认将移除并返回末尾项。
@end deffn

@geindex remove() (array.array 方法)
@anchor{library/array array array remove}@anchor{1b1a}
@deffn {方法} array.remove (x)

从数组中移除首次出现的 @emph{x}。
@end deffn

@geindex reverse() (array.array 方法)
@anchor{library/array array array reverse}@anchor{1b1b}
@deffn {方法} array.reverse ()

反转数组中各项的顺序。
@end deffn

@geindex tobytes() (array.array 方法)
@anchor{library/array array array tobytes}@anchor{1b1c}
@deffn {方法} array.tobytes ()

将数组转换为一个机器值数组并返回其字节表示（即相当与通过 @ref{1b1d,,tofile()} 方法写入到文件的字节序列。）


3.2 新版功能: @code{tostring()} 被重命名为 @ref{1b1c,,tobytes()} 以使其含义更清晰。

@end deffn

@geindex tofile() (array.array 方法)
@anchor{library/array array array tofile}@anchor{1b1d}
@deffn {方法} array.tofile (f)

将所有项（作为机器值）写入到 @ref{c1d,,file object} @emph{f}。
@end deffn

@geindex tolist() (array.array 方法)
@anchor{library/array array array tolist}@anchor{1b1e}
@deffn {方法} array.tolist ()

将数组转换为包含相同项的普通列表。
@end deffn

@geindex tounicode() (array.array 方法)
@anchor{library/array array array tounicode}@anchor{1b1f}
@deffn {方法} array.tounicode ()

将数组转换为一个 Unicode 字符串。 数组必须是类型为 @code{'u'} 的数组；否则将引发 @ref{16d,,ValueError}。 请使用 @code{array.tobytes().decode(enc)} 来从其他类型的数组生成 Unicode 字符串。
@end deffn

当一个数组对象被打印或转换为字符串时，它会表示为 @code{array(typecode, initializer)}。 如果数组为空则 @emph{initializer} 会被省略，否则如果 @emph{typecode} 为 @code{'u'} 则它是一个字符串，否则它是一个数字列表。 使用 @ref{c6a,,eval()} 保证能将字符串转换回具有相同类型和值的数组，只要 @ref{217,,array} 类已通过 @code{from array import array} 被引入。 例如:

@example
array('l')
array('u', 'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{f8,,struct}

打包和解包异构二进制数据。

@item 模块 @ref{13b,,xdrlib}

打包和解包用于某些远程过程调用系统的 External Data Representation (XDR) 数据。

@item NumPy@footnote{https://numpy.org/}

NumPy 软件包定义了另一种数组类型。
@end table


@node weakref --- 弱引用,types --- 动态类型创建和内置类型名称,array --- 高效的数值数组,数据类型
@anchor{library/weakref doc}@anchor{1b20}@anchor{library/weakref module-weakref}@anchor{131}@anchor{library/weakref weakref-weak-references}@anchor{1b21}
@subsection @code{weakref} --- 弱引用


@geindex weakref (模块)

@strong{源码：} Lib/weakref.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/weakref.py}


__________________________________________________________________


@ref{131,,weakref} 模块允许Python程序员创建对象的 @emph{weak references} 。

@c When making changes to the examples in this file, be sure to update
@c Lib/test/test_weakref.py::libreftest too!

在下文中，术语 @emph{referent} 表示由弱引用引用的对象。

对对象的弱引用不能保证对象存活：当对像的引用只剩弱引用时， @ref{1013,,garbage collection} 可以销毁引用并将其内存重用于其他内容。但是，在实际销毁对象之前，即使没有强引用，弱引用也一直能返回该对象。

弱引用的主要用途是实现保存大对象的高速缓存或映射，但又不希望大对象仅仅因为它出现在高速缓存或映射中而保持存活。

例如，如果您有许多大型二进制图像对象，则可能希望将名称与每个对象关联起来。如果您使用Python字典将名称映射到图像，或将图像映射到名称，则图像对象将保持活动状态，因为它们在字典中显示为值或键。 @ref{131,,weakref} 模块提供的 @ref{109d,,WeakKeyDictionary} 和 @ref{109c,,WeakValueDictionary} 类可以替代Python字典，使用弱引用来构造映射，这些映射不会仅仅因为它们出现在映射对象中而使对象保持存活。例如，如果一个图像对象是 @ref{109c,,WeakValueDictionary} 中的值，那么当对该图像对象的剩余引用是弱映射对象所持有的弱引用时，垃圾回收可以回收该对象并将其在弱映射对象中相应的条目删除。

@ref{109d,,WeakKeyDictionary} 和 @ref{109c,,WeakValueDictionary} 在它们的实现中使用弱引用，在弱引用上设置回调函数，当键或值被垃圾回收回收时通知弱字典。 @ref{d88,,WeakSet} 实现了 @ref{1f7,,set} 接口，但像 @ref{109d,,WeakKeyDictionary} 一样，只持有其元素的弱引用。

@ref{3c8,,finalize} 提供了注册一个对象被垃圾收集时要调用的清理函数的方式。这比在原始弱引用上设置回调函数更简单，因为模块会自动确保对象被回收前终结器一直保持存活。

这些弱容器类型之一或者 @ref{3c8,,finalize} 就是大多数程序所需要的 - 通常不需要直接创建自己的弱引用。@ref{131,,weakref} 模块暴露了低级机制，以便于高级用途。

并非所有对象都可以被弱引用；可以被弱引用的对象包括类实例，用 Python（而不是用 C）编写的函数，实例方法、集合、冻结集合，某些 @ref{c1d,,文件对象}，@ref{a8c,,生成器}，类型对象，套接字，数组，双端队列，正则表达式模式对象以及代码对象等。


在 3.2 版更改: 添加了对thread.lock，threading.Lock和代码对象的支持。


几个内建类型如 @ref{1f9,,list} 和 @ref{164,,dict} 不直接支持弱引用，但可以通过子类化添加支持:

@example
class Dict(dict):
    pass

obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable
@end example

@strong{CPython implementation detail:} 其他内置类型例如 @ref{1a2,,tuple} 和 @ref{205,,int} 不支持弱引用，即使通过子类化也不支持。

Extension types can easily be made to support weak references; see
@ref{1b22,,弱引用支持}.

当为某个给定类型定义了 @code{__slots__} 时，弱引用支持会被禁用，除非将 @code{'__weakref__'} 字符串也加入到 @code{__slots__} 声明的字符串序列中。 请参阅 @ref{15a6,,__slots__ 文档} 了解详情。

@geindex ref (weakref 中的类)
@anchor{library/weakref weakref ref}@anchor{9ff}
@deffn {类} weakref.ref (object[, callback])

返回对 @emph{对象} 的弱引用。如果原始对象仍然存活，则可以通过调用引用对象来检索原始对象；如果引用的原始对象不再存在，则调用引用对象将得到 @ref{204,,None} 。如果提供了 @emph{回调} 而且值不是 @ref{204,,None} ，并且返回的弱引用对象仍然存活，则在对象即将终结时将调用回调;弱引用对象将作为回调的唯一参数传递；指示物将不再可用。

许多弱引用也允许针对相同对象来构建。 为每个弱引用注册的回调将按从最近注册的回调到最早注册的回调的顺序被调用。

回调所引发的异常将记录于标准错误输出，但无法被传播；它们会按与对象的 @ref{a0d,,__del__()} 方法所引发的异常相同的方式被处理。

如果 @emph{object} 可哈希，则弱引用也为 @ref{277,,hashable}。 即使在 @emph{object} 被删除之后它们仍将保持其哈希值。 如果 @ref{aac,,hash()} 在 @emph{object} 被删除之后才首次被调用，则该调用将引发 @ref{1ff,,TypeError}。

弱引用支持相等检测，但不支持排序比较。 如果被引用对象仍然存在，两个引用具有与它们的被引用对象一致的相等关系（无论 @emph{callback} 是否相同）。 如果删除了任一被引用对象，则仅在两个引用对象为同一对象时两者才相等。

这是一个可子类化的类型而非一个工厂函数。

@geindex __callback__ (weakref.ref 属性)
@anchor{library/weakref weakref ref __callback__}@anchor{a00}
@deffn {属性} __callback__

这个只读属性会返回当前关联到弱引用的回调。 如果回调不存在或弱引用的被引用对象已不存在，则此属性的值为 @code{None}。
@end deffn


在 3.4 版更改: 添加了 @ref{a00,,__callback__} 属性。

@end deffn

@geindex proxy() (在 weakref 模块中)
@anchor{library/weakref weakref proxy}@anchor{381}
@deffn {函数} weakref.proxy (object[, callback])

返回 @emph{object} 的一个使用弱引用的代理。 此函数支持在大多数上下文中使用代理，而不要求显式地对所使用的弱引用对象解除引用。 返回的对象类型将为 @code{ProxyType} 或 @code{CallableProxyType}，具体取决于 @emph{object} 是否可调用。 Proxy 对象不是 @ref{277,,hashable} 对象，无论被引用对象是否可哈希；这可避免与它们的基本可变性质相关的多种问题，并可防止它们被用作字典键。 @emph{callback} 与 @ref{9ff,,ref()} 函数的同名形参含义相同。


在 3.8 版更改: 扩展代理对象所支持的运算符，包括矩阵乘法运算符 @code{@@} 和 @code{@@=}。

@end deffn

@geindex getweakrefcount() (在 weakref 模块中)
@anchor{library/weakref weakref getweakrefcount}@anchor{1b23}
@deffn {函数} weakref.getweakrefcount (object)

返回指向 @emph{object} 的弱引用和代理的数量。
@end deffn

@geindex getweakrefs() (在 weakref 模块中)
@anchor{library/weakref weakref getweakrefs}@anchor{1b24}
@deffn {函数} weakref.getweakrefs (object)

返回由指向 @emph{object} 的所有弱引用和代理构成的列表。
@end deffn

@geindex WeakKeyDictionary (weakref 中的类)
@anchor{library/weakref weakref WeakKeyDictionary}@anchor{109d}
@deffn {类} weakref.WeakKeyDictionary ([dict])

弱引用键的映射类。 当不再存在对键的强引用时，字典中的条目将被丢弃。 这可被用来将额外数据关联到一个应用中其他部分所拥有的对象而无需在那些对象中添加属性。 这对于重载了属性访问的对象来说特别有用。


在 3.9 版更改: 增加了对 @code{|} 和 @code{|=} 运算符的支持，相关说明见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。

@end deffn

@ref{109d,,WeakKeyDictionary} 对象具有一个额外方法可以直接公开内部引用。 这些引用不保证在它们被使用时仍然保持“存活”，因此这些引用的调用结果需要在使用前进行检测。 此方法可用于避免创建会导致垃圾回收器将保留键超出实际需要时长的引用。

@geindex keyrefs() (weakref.WeakKeyDictionary 方法)
@anchor{library/weakref weakref WeakKeyDictionary keyrefs}@anchor{1b25}
@deffn {方法} WeakKeyDictionary.keyrefs ()

返回包含对键的弱引用的可迭代对象。
@end deffn

@geindex WeakValueDictionary (weakref 中的类)
@anchor{library/weakref weakref WeakValueDictionary}@anchor{109c}
@deffn {类} weakref.WeakValueDictionary ([dict])

弱引用值的映射类。 当不再存在对该值的强引用时，字典中的条目将被丢弃。


在 3.9 版更改: 增加了对 @code{|} 和 @code{|=} 运算符的支持，相关说明见 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584}。

@end deffn

@ref{109c,,WeakValueDictionary} 对象具有一个额外方法，此方法存在与 @ref{109d,,WeakKeyDictionary} 对象的 @code{keyrefs()} 方法相同的问题。

@geindex valuerefs() (weakref.WeakValueDictionary 方法)
@anchor{library/weakref weakref WeakValueDictionary valuerefs}@anchor{1b26}
@deffn {方法} WeakValueDictionary.valuerefs ()

返回包含对值的弱引用的可迭代对象。
@end deffn

@geindex WeakSet (weakref 中的类)
@anchor{library/weakref weakref WeakSet}@anchor{d88}
@deffn {类} weakref.WeakSet ([elements])

保持对其元素弱引用的集合类。 当不再有对某个元素的强引用时元素将被丢弃。
@end deffn

@geindex WeakMethod (weakref 中的类)
@anchor{library/weakref weakref WeakMethod}@anchor{9fe}
@deffn {类} weakref.WeakMethod (method)

一个模拟对绑定方法（即在类中定义并在实例中查找的方法）进行弱引用的自定义 @ref{9ff,,ref} 子类。 由于绑定方法是临时性的，标准弱引用无法保持它。 @ref{9fe,,WeakMethod} 包含特别代码用来重新创建绑定方法，直到对象或初始函数被销毁:

@example
>>> class C:
...     def method(self):
...         print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>
@end example


3.4 新版功能.

@end deffn

@geindex finalize (weakref 中的类)
@anchor{library/weakref weakref finalize}@anchor{3c8}
@deffn {类} weakref.finalize (obj, func, /, *args, **kwargs)

返回一个可调用的终结器对象，该对象将在 @emph{obj} 作为垃圾回收时被调用。 与普通的弱引用不同，终结器将总是存活，直到引用对象被回收，这极大地简化了生存期管理。

终结器总是被视为 @emph{存活} 直到它被调用（显式调用或在垃圾回收时隐式调用），调用之后它将 @emph{死亡}。 调用存活的终结器将返回 @code{func(*arg, **kwargs)} 的求值结果，而调用死亡的终结器将返回 @ref{204,,None}。

在垃圾收集期间由终结器回调所引发异常将显示于标准错误输出，但无法被传播。 它们会按与对象的 @ref{a0d,,__del__()} 方法或弱引用的回调所引发异常相同的方式被处理。

当程序退出时，剩余的存活终结器会被调用，除非它们的 @ref{b,,atexit} 属性已被设为假值。 它们会按与创建时相反的顺序被调用。

终结器在 @ref{85c,,interpreter shutdown} 的后期绝不会发起调用其回调函数，此时模块全局变量很可能已被替换为 @ref{204,,None}。

@geindex __call__() (weakref.finalize 方法)
@anchor{library/weakref weakref finalize __call__}@anchor{1b27}
@deffn {方法} __call__ ()

如果 @emph{self} 为存活状态则将其标记为已死亡，并返回调用 @code{func(*args, **kwargs)} 的结果。 如果 @emph{self} 已死亡则返回 @ref{204,,None}。
@end deffn

@geindex detach() (weakref.finalize 方法)
@anchor{library/weakref weakref finalize detach}@anchor{1b28}
@deffn {方法} detach ()

如果 @emph{self} 为存活状态则将其标记为已死亡，并返回元组 @code{(obj, func, args, kwargs)}。 如果 @emph{self} 已死亡则返 @ref{204,,None}。
@end deffn

@geindex peek() (weakref.finalize 方法)
@anchor{library/weakref weakref finalize peek}@anchor{1b29}
@deffn {方法} peek ()

如果 @emph{self} 为存活状态则返回元组 @code{(obj, func, args, kwargs)}。 如果 @emph{self} 已死亡则返回 @ref{204,,None}。
@end deffn

@geindex alive (weakref.finalize 属性)
@anchor{library/weakref weakref finalize alive}@anchor{1b2a}
@deffn {属性} alive

如果终结器为存活状态则该特征属性为真值，否则为假值。
@end deffn

@geindex atexit (weakref.finalize 属性)
@anchor{library/weakref weakref finalize atexit}@anchor{1b2b}
@deffn {属性} atexit

一个可写的布尔型特征属性，默认为真值。 当程序退出时，它会调用所有 @ref{1b2b,,atexit} 为真值的剩余存活终结器。 它们会按与创建时相反的顺序被调用。
@end deffn

@cartouche
@quotation 注解 
很重要的一点是确保 @emph{func}, @emph{args} 和 @emph{kwargs} 不拥有任何对 @emph{obj} 的引用，无论是直接的或是间接的，否则的话 @emph{obj} 将永远不会被作为垃圾回收。 特别地，@emph{func} 不应当是 @emph{obj} 的一个绑定方法。
@end quotation
@end cartouche


3.4 新版功能.

@end deffn

@geindex ReferenceType() (在 weakref 模块中)
@anchor{library/weakref weakref ReferenceType}@anchor{1b2c}
@deffn {数据} weakref.ReferenceType

弱引用对象的类型对象。
@end deffn

@geindex ProxyType() (在 weakref 模块中)
@anchor{library/weakref weakref ProxyType}@anchor{1b2d}
@deffn {数据} weakref.ProxyType

不可调用对象的代理的类型对象。
@end deffn

@geindex CallableProxyType() (在 weakref 模块中)
@anchor{library/weakref weakref CallableProxyType}@anchor{1b2e}
@deffn {数据} weakref.CallableProxyType

可调用对象的代理的类型对象。
@end deffn

@geindex ProxyTypes() (在 weakref 模块中)
@anchor{library/weakref weakref ProxyTypes}@anchor{1b2f}
@deffn {数据} weakref.ProxyTypes

包含所有代理的类型对象的序列。 这可以用于更方便地检测一个对象是否是代理，而不必依赖于两种代理对象的名称。
@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 205

@item PEP 205@footnote{https://www.python.org/dev/peps/pep-0205} - 弱引用

此特性的提议和理由，包括早期实现的链接和其他语言中类似特性的相关信息。
@end table


@menu
* 弱引用对象:: 
* 示例: 示例<4>. 
* 终结器对象:: 
* 比较终结器与 __del__() 方法: 比较终结器与 __del__ 方法. 

@end menu

@node 弱引用对象,示例<4>,,weakref --- 弱引用
@anchor{library/weakref weak-reference-objects}@anchor{1b30}@anchor{library/weakref weakref-objects}@anchor{1b31}
@subsubsection 弱引用对象


弱引用对象没有 @ref{a00,,ref.__callback__} 以外的方法和属性。 一个弱引用对象如果存在，就允许通过调用它来获取引用:

@example
>>> import weakref
>>> class Object:
...     pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> o2 = r()
>>> o is o2
True
@end example

如果引用已不存在，则调用引用对象将返回 @ref{204,,None}:

@example
>>> del o, o2
>>> print(r())
None
@end example

检测一个弱引用对象是否仍然存在应该使用表达式 @code{ref() is not None}。 通常，需要使用引用对象的应用代码应当遵循这样的模式:

@example
# r is a weak reference object
o = r()
if o is None:
    # referent has been garbage collected
    print("Object has been deallocated; can't frobnicate.")
else:
    print("Object is still live!")
    o.do_something_useful()
@end example

使用单独的“存活”测试会在多线程应用中制造竞争条件；其他线程可能导致某个弱引用在该弱引用被调用前就失效；上述的写法在多线程应用和单线程应用中都是安全的。

特别版本的 @ref{9ff,,ref} 对象可以通过子类化来创建。 在 @ref{109c,,WeakValueDictionary} 的实现中就使用了这种方式来减少映射中每个条目的内存开销。 这对于将附加信息关联到引用的情况最为适用，但也可以被用于在调用中插入额外处理来提取引用。

这个例子演示了如何将 @ref{9ff,,ref} 的一个子类用于存储有关对象的附加信息并在引用被访问时影响其所返回的值:

@example
import weakref

class ExtendedRef(weakref.ref):
    def __init__(self, ob, callback=None, /, **annotations):
        super().__init__(ob, callback)
        self.__counter = 0
        for k, v in annotations.items():
            setattr(self, k, v)

    def __call__(self):
        """Return a pair containing the referent and the number of
        times the reference has been called.
        """
        ob = super().__call__()
        if ob is not None:
            self.__counter += 1
            ob = (ob, self.__counter)
        return ob
@end example

@node 示例<4>,终结器对象,弱引用对象,weakref --- 弱引用
@anchor{library/weakref example}@anchor{1b32}@anchor{library/weakref weakref-example}@anchor{1b33}
@subsubsection 示例


这个简单的例子演示了一个应用如何使用对象 ID 来提取之前出现过的对象。 然后对象的 ID 可以在其它数据结构中使用，而无须强制对象保持存活，但处于存活状态的对象也仍然可以通过 ID 来提取。

@c Example contributed by Tim Peters.

@example
import weakref

_id2obj_dict = weakref.WeakValueDictionary()

def remember(obj):
    oid = id(obj)
    _id2obj_dict[oid] = obj
    return oid

def id2obj(oid):
    return _id2obj_dict[oid]
@end example

@node 终结器对象,比较终结器与 __del__ 方法,示例<4>,weakref --- 弱引用
@anchor{library/weakref finalize-examples}@anchor{1b34}@anchor{library/weakref finalizer-objects}@anchor{1b35}
@subsubsection 终结器对象


使用 @ref{3c8,,finalize} 的主要好处在于它能更简便地注册回调函数，而无须保留所返回的终结器对象。 例如

@example
>>> import weakref
>>> class Object:
...     pass
...
>>> kenny = Object()
>>> weakref.finalize(kenny, print, "You killed Kenny!")  
<finalize object at ...; for 'Object' at ...>
>>> del kenny
You killed Kenny!
@end example

终结器也可以被直接调用。 但是终结器最多只能对回调函数发起一次调用。

@example
>>> def callback(x, y, z):
...     print("CALLBACK")
...     return x + y + z
...
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> assert f.alive
>>> assert f() == 6
CALLBACK
>>> assert not f.alive
>>> f()                     # callback not called because finalizer dead
>>> del obj                 # callback not called because finalizer dead
@end example

你可以使用 @ref{1b28,,detach()} 方法来注销一个终结器。 该方法将销毁终结器并返回其被创建时传给构造器的参数。

@example
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> f.detach()                                           
(<...Object object ...>, <function callback ...>, (1, 2), @{'z': 3@})
>>> newobj, func, args, kwargs = _
>>> assert not f.alive
>>> assert newobj is obj
>>> assert func(*args, **kwargs) == 6
CALLBACK
@end example

除非你将 @ref{1b2b,,atexit} 属性设为 @ref{497,,False}，否则终结器在程序退出时如果仍然存活就将被调用。 例如

@example
>>> obj = Object()
>>> weakref.finalize(obj, print, "obj dead or exiting")
<finalize object at ...; for 'Object' at ...>
>>> exit()
obj dead or exiting
@end example

@node 比较终结器与 __del__ 方法,,终结器对象,weakref --- 弱引用
@anchor{library/weakref comparing-finalizers-with-del-methods}@anchor{1b36}
@subsubsection 比较终结器与 @code{__del__()} 方法


假设我们想创建一个类，用它的实例来代表临时目录。 当以下事件中的某一个发生时，这个目录应当与其内容一起被删除：


@itemize *

@item 
对象被作为垃圾回收，

@item 
对象的 @code{remove()} 方法被调用，或

@item 
程序退出。
@end itemize

我们可以尝试使用 @ref{a0d,,__del__()} 方法来实现这个类，如下所示:

@example
class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()

    def remove(self):
        if self.name is not None:
            shutil.rmtree(self.name)
            self.name = None

    @@property
    def removed(self):
        return self.name is None

    def __del__(self):
        self.remove()
@end example

从 Python 3.4 开始，@ref{a0d,,__del__()} 方法不会再阻止循环引用被作为垃圾回收，并且模块全局变量在 @ref{85c,,interpreter shutdown} 期间不会被强制设为 @ref{204,,None}。 因此这段代码在 CPython 上应该会正常运行而不会出现任何问题。

然而，@ref{a0d,,__del__()} 方法的处理会严重地受到具体实现的影响，因为它依赖于解释器垃圾回收实现方式的内部细节。

更健壮的替代方式可以是定义一个终结器，只引用它所需要的特定函数和对象，而不是获取对整个对象状态的访问权:

@example
class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()
        self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

    def remove(self):
        self._finalizer()

    @@property
    def removed(self):
        return not self._finalizer.alive
@end example

像这样定义后，我们的终结器将只接受一个对其完成正确清理目录任务所需细节的引用。 如果对象一直未被作为垃圾回收，终结器仍会在退出时被调用。

基于弱引用的终结器还具有另一项优势，就是它们可被用来为定义由第三方控制的类注册终结器，例如当一个模块被卸载时运行特定代码:

@example
import weakref, sys
def unloading_module():
    # implicit reference to the module globals from the function body
weakref.finalize(sys.modules[__name__], unloading_module)
@end example

@cartouche
@quotation 注解 
如果当程序退出时你恰好在守护线程中创建终结器对象，则有可能该终结器不会在退出时被调用。 但是，在一个守护线程中 @ref{f4d,,atexit.register()}, @code{try: ... finally: ...} 和 @code{with: ...} 同样不能保证执行清理。
@end quotation
@end cartouche

@node types --- 动态类型创建和内置类型名称,copy --- 浅层 shallow 和深层 deep 复制操作,weakref --- 弱引用,数据类型
@anchor{library/types doc}@anchor{1b37}@anchor{library/types module-types}@anchor{121}@anchor{library/types types-dynamic-type-creation-and-names-for-built-in-types}@anchor{1b38}
@subsection @code{types} --- 动态类型创建和内置类型名称


@geindex types (模块)

@strong{源代码:} Lib/types.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/types.py}


__________________________________________________________________


此模块定义了一些工具函数，用于协助动态创建新的类型。

它还为某些对象类型定义了名称，这些名称由标准 Python 解释器所使用，但并不像内置的 @ref{205,,int} 或 @ref{206,,str} 那样对外公开。

最后，它还额外提供了一些类型相关但重要程度不足以作为内置对象的工具类和函数。

@menu
* 动态类型创建:: 
* 标准解释器类型:: 
* 附加工具类和函数:: 
* 协程工具函数:: 

@end menu

@node 动态类型创建,标准解释器类型,,types --- 动态类型创建和内置类型名称
@anchor{library/types dynamic-type-creation}@anchor{1b39}
@subsubsection 动态类型创建


@geindex new_class() (在 types 模块中)
@anchor{library/types types new_class}@anchor{b98}
@deffn {函数} types.new_class (name, bases=(), kwds=None, exec_body=None)

使用适当的元类动态地创建一个类对象。

前三个参数是组成类定义头的部件：类名称，基类 (有序排列)，关键字参数 (例如 @code{metaclass})。

@emph{exec_body} 参数是一个回调函数，用于填充新创建类的命名空间。 它应当接受类命名空间作为其唯一的参数并使用类内容直接更新命名空间。  如果未提供回调函数，则它就等效于传入 @code{lambda ns: None}。


3.3 新版功能.

@end deffn

@geindex prepare_class() (在 types 模块中)
@anchor{library/types types prepare_class}@anchor{b99}
@deffn {函数} types.prepare_class (name, bases=(), kwds=None)

计算适当的元类并创建类命名空间。

参数是组成类定义头的部件：类名称，基类 (有序排列) 以及关键字参数 (例如 @code{metaclass})。

返回值是一个 3 元组: @code{metaclass, namespace, kwds}

@emph{metaclass} 是适当的元类，@emph{namespace} 是预备好的类命名空间而 @emph{kwds} 是所传入 @emph{kwds} 参数移除每个 @code{'metaclass'} 条目后的已更新副本。 如果未传入 @emph{kwds} 参数，这将为一个空字典。


3.3 新版功能.



在 3.6 版更改: 所返回元组中 @code{namespace} 元素的默认值已被改变。 现在当元类没有 @code{__prepare__} 方法时将会使用一个保留插入顺序的映射。

@end deffn


@subsubheading 参见



@table @asis

@item @ref{15ab,,元类}

这些函数所支持的类创建过程的完整细节

@geindex Python 提高建议; PEP 3115

@item PEP 3115@footnote{https://www.python.org/dev/peps/pep-3115} - Python 3000 中的元类

引入 @code{__prepare__} 命名空间钩子
@end table


@geindex resolve_bases() (在 types 模块中)
@anchor{library/types types resolve_bases}@anchor{513}
@deffn {函数} types.resolve_bases (bases)

动态地解析 MRO 条目，具体描述见 
@geindex Python 提高建议; PEP 560
PEP 560@footnote{https://www.python.org/dev/peps/pep-0560}。

此函数会在 @emph{bases} 中查找不是 @ref{709,,type} 的实例的项，并返回一个元组，其中每个具有 @code{__mro_entries__} 方法的此种对象对象将被替换为调用该方法解包后的结果。 如果一个 @emph{bases} 项是 @ref{709,,type} 的实例，或它不具有 @code{__mro_entries__} 方法，则它将不加改变地被包含在返回的元组中。


3.7 新版功能.

@end deffn


@subsubheading 参见


@geindex Python 提高建议; PEP 560
PEP 560@footnote{https://www.python.org/dev/peps/pep-0560} - 对类型模块和泛型类型的核心支持


@node 标准解释器类型,附加工具类和函数,动态类型创建,types --- 动态类型创建和内置类型名称
@anchor{library/types standard-interpreter-types}@anchor{1b3a}
@subsubsection 标准解释器类型


此模块为许多类型提供了实现 Python 解释器所要求的名称。 它刻意地避免了包含某些仅在处理过程中偶然出现的类型，例如 @code{listiterator} 类型。

此种名称的典型应用如 @ref{55a,,isinstance()} 或 @ref{55b,,issubclass()} 检测。

如果你要实例化这些类型中的任何一种，请注意其签名在不同 Python 版本之间可能出现变化。

以下类型有相应的标准名称定义：

@geindex FunctionType() (在 types 模块中)
@geindex LambdaType() (在 types 模块中)
@anchor{library/types types FunctionType}@anchor{1b3b}
@deffn {数据} types.FunctionType
@anchor{library/types types LambdaType}@anchor{1b3c}
@deffnx {数据} types.LambdaType

用户自定义函数以及由 @ref{d01,,lambda}  表达式所创建函数的类型。

引发一个 @ref{fec,,审计事件} @code{function.__new__}，附带参数 @code{code}。

此审计事件只会被函数对象的直接实例化引发，而不会被普通编译所引发。
@end deffn

@geindex GeneratorType() (在 types 模块中)
@anchor{library/types types GeneratorType}@anchor{1b3d}
@deffn {数据} types.GeneratorType

@ref{a8c,,generator} 迭代器对象的类型，由生成器函数创建。
@end deffn

@geindex CoroutineType() (在 types 模块中)
@anchor{library/types types CoroutineType}@anchor{876}
@deffn {数据} types.CoroutineType

@ref{18a,,coroutine} 对象的类型，由 @ref{3b1,,async def} 函数创建。


3.5 新版功能.

@end deffn

@geindex AsyncGeneratorType() (在 types 模块中)
@anchor{library/types types AsyncGeneratorType}@anchor{1b3e}
@deffn {数据} types.AsyncGeneratorType

@ref{166f,,asynchronous generator} 迭代器对象的类型，由异步生成器函数创建。


3.6 新版功能.

@end deffn

@geindex CodeType (types 中的类)
@anchor{library/types types CodeType}@anchor{2d4}
@deffn {类} types.CodeType (**kwargs)

@geindex 內置函数; compile

代码对象的类型，例如 @ref{2ee,,compile()} 的返回值。

引发 @ref{fec,,审计事件} @code{code.__new__} 附带参数 @code{code}, @code{filename}, @code{name}, @code{argcount}, @code{posonlyargcount}, @code{kwonlyargcount}, @code{nlocals}, @code{stacksize}, @code{flags}。

请注意被审计的参数可能与初始化代码所要求的名称或位置不相匹配。 审计事件只会被代码对象的直接实例化引发，而不会被普通编译所引发。

@geindex replace() (types.CodeType 方法)
@anchor{library/types types CodeType replace}@anchor{1b3f}
@deffn {方法} replace (**kwargs)

返回代码对象的一个副本，使用指定的新字段值。


3.8 新版功能.

@end deffn
@end deffn

@geindex CellType() (在 types 模块中)
@anchor{library/types types CellType}@anchor{158c}
@deffn {数据} types.CellType

单元对象的类型：这种对象被用作函数中自由变量的容器。


3.8 新版功能.

@end deffn

@geindex MethodType() (在 types 模块中)
@anchor{library/types types MethodType}@anchor{1b40}
@deffn {数据} types.MethodType

用户自定义类实例方法的类型。
@end deffn

@geindex BuiltinFunctionType() (在 types 模块中)
@geindex BuiltinMethodType() (在 types 模块中)
@anchor{library/types types BuiltinFunctionType}@anchor{1b41}
@deffn {数据} types.BuiltinFunctionType
@anchor{library/types types BuiltinMethodType}@anchor{1b42}
@deffnx {数据} types.BuiltinMethodType

内置函数例如 @ref{292,,len()} 或 @ref{db2,,sys.exit()} 以及内置类方法的类型。 （这里所说的“内置”是指“以 C 语言编写”。）
@end deffn

@geindex WrapperDescriptorType() (在 types 模块中)
@anchor{library/types types WrapperDescriptorType}@anchor{50f}
@deffn {数据} types.WrapperDescriptorType

某些内置数据类型和基类的方法的类型，例如 @ref{e2b,,object.__init__()} 或 @ref{d06,,object.__lt__()}。


3.7 新版功能.

@end deffn

@geindex MethodWrapperType() (在 types 模块中)
@anchor{library/types types MethodWrapperType}@anchor{510}
@deffn {数据} types.MethodWrapperType

某些内置数据类型和基类的 @emph{绑定} 方法的类型。 例如 @code{object().__str__} 所属的类型。


3.7 新版功能.

@end deffn

@geindex MethodDescriptorType() (在 types 模块中)
@anchor{library/types types MethodDescriptorType}@anchor{511}
@deffn {数据} types.MethodDescriptorType

某些内置数据类型方法例如 @ref{1796,,str.join()} 的类型。


3.7 新版功能.

@end deffn

@geindex ClassMethodDescriptorType() (在 types 模块中)
@anchor{library/types types ClassMethodDescriptorType}@anchor{512}
@deffn {数据} types.ClassMethodDescriptorType

某些内置数据类型 @emph{非绑定} 类方法例如 @code{dict.__dict__['fromkeys']} 的类型。


3.7 新版功能.

@end deffn

@geindex ModuleType (types 中的类)
@anchor{library/types types ModuleType}@anchor{7ec}
@deffn {类} types.ModuleType (name, doc=None)

@ref{1616,,模块} 的类型。 构造器接受待创建模块的名称并以其 @ref{171b,,docstring} 作为可选参数。

@cartouche
@quotation 注解 
如果你希望设置各种由导入控制的属性，请使用 @ref{7eb,,importlib.util.module_from_spec()} 来创建一个新模块。
@end quotation
@end cartouche

@geindex __doc__ (types.ModuleType 属性)
@anchor{library/types types ModuleType __doc__}@anchor{1b43}
@deffn {属性} __doc__

模块的 @ref{171b,,docstring}。 默认为 @code{None}。
@end deffn

@geindex __loader__ (types.ModuleType 属性)
@anchor{library/types types ModuleType __loader__}@anchor{1b44}
@deffn {属性} __loader__

用于加载模块的 @ref{1625,,loader}。 默认为 @code{None}。

此属性会匹配保存在 attr:@cite{__spec__} 对象中的 @ref{1b45,,importlib.machinery.ModuleSpec.loader}。

@cartouche
@quotation 注解 
未来的 Python 版本可能会停止默认设置此属性。 为了避免这个潜在变化的影响，如果你明确地需要使用此属性则推荐改从 @ref{1632,,__spec__} 属性读取或是使用 @code{getattr(module, "__loader__", None)}。
@end quotation
@end cartouche


在 3.4 版更改: 默认为 @code{None}。 之前该属性为可选项。

@end deffn

@geindex __name__ (types.ModuleType 属性)
@anchor{library/types types ModuleType __name__}@anchor{1b46}
@deffn {属性} __name__

模块的名称。 应当能匹配 @ref{1b47,,importlib.machinery.ModuleSpec.name}。
@end deffn

@geindex __package__ (types.ModuleType 属性)
@anchor{library/types types ModuleType __package__}@anchor{1b48}
@deffn {属性} __package__

一个模块所属的 @ref{161a,,package}。 如果模块为最高层级的（即不是任何特定包的组成部分）则该属性应设为 @code{'@w{'}}，否则它应设为特定包的名称 (如果模块本身也是一个包则名称可以为 @ref{de0,,__name__})。 默认为 @code{None}。

此属性会匹配保存在 attr:@cite{__spec__} 对象中的 @ref{1b49,,importlib.machinery.ModuleSpec.parent}。

@cartouche
@quotation 注解 
未来的 Python 版本可能停止默认设置此属性。 为了避免这个潜在变化的影响，如果你明确地需要使用此属性则推荐改从 @ref{1632,,__spec__} 属性读取或是使用 @code{getattr(module, "__package__", None)}。
@end quotation
@end cartouche


在 3.4 版更改: 默认为 @code{None}。 之前该属性为可选项。

@end deffn

@geindex __spec__ (types.ModuleType 属性)
@anchor{library/types types ModuleType __spec__}@anchor{1b4a}
@deffn {属性} __spec__

模块的导入系统相关状态的记录。 应当是一个 @ref{1630,,importlib.machinery.ModuleSpec} 的实例。


3.4 新版功能.

@end deffn
@end deffn

@geindex GenericAlias (types 中的类)
@anchor{library/types types GenericAlias}@anchor{27d}
@deffn {类} types.GenericAlias (t_origin, t_args)

@ref{1030,,形参化泛型} 的类型，例如 @code{list[int]}。

@code{t_origin} 应当是一个非形参化的泛型类，例如 @code{list}, @code{tuple} 或 @code{dict}。 @code{t_args} 应当是一个形参化 @code{t_origin} 的 @ref{1a2,,tuple} (长度可以为 1):

@example
>>> from types import GenericAlias

>>> list[int] == GenericAlias(list, (int,))
True
>>> dict[str, int] == GenericAlias(dict, (str, int))
True
@end example


3.9 新版功能.



在 3.9.2 版更改: 此类型现在可以被子类化。

@end deffn

@geindex TracebackType (types 中的类)
@anchor{library/types types TracebackType}@anchor{44a}
@deffn {类} types.TracebackType (tb_next, tb_frame, tb_lasti, tb_lineno)

回溯对象的类型，例如 @code{sys.exc_info()[2]} 中的对象。

请查看 @ref{44b,,语言参考} 了解可用属性和操作的细节，以及动态地创建回溯对象的指南。
@end deffn

@geindex FrameType() (在 types 模块中)
@anchor{library/types types FrameType}@anchor{1b4b}
@deffn {数据} types.FrameType

帧对象的类型，例如 @code{tb.tb_frame} 中的对象，其中 @code{tb} 是一个回溯对象。

请查看 @ref{1594,,语言参考} 了解可用属性和操作的细节。
@end deffn

@geindex GetSetDescriptorType() (在 types 模块中)
@anchor{library/types types GetSetDescriptorType}@anchor{1b4c}
@deffn {数据} types.GetSetDescriptorType

使用 @code{PyGetSetDef} 在扩展模块中定义的对象的类型，例如 @code{FrameType.f_locals} 或 @code{array.array.typecode}。 此类型被用作对象属性的描述器；它的目的与 @ref{30f,,property} 类型相同，但专门针对在扩展模块中定义的类。
@end deffn

@geindex MemberDescriptorType() (在 types 模块中)
@anchor{library/types types MemberDescriptorType}@anchor{1b4d}
@deffn {数据} types.MemberDescriptorType

使用 @code{PyMemberDef} 在扩展模块中定义的对象的类型，例如 @code{datetime.timedelta.days}。 此类型被用作使用标准转换函数的简单 C 数据成员的描述器；它的目的与 @ref{30f,,property} 类型相同，但专门针对在扩展模块中定义的类。

@strong{CPython implementation detail:} 在 Python 的其它实现中，此类型可能与 @code{GetSetDescriptorType} 完全相同。
@end deffn

@geindex MappingProxyType (types 中的类)
@anchor{library/types types MappingProxyType}@anchor{b97}
@deffn {类} types.MappingProxyType (mapping)

一个映射的只读代理。 它提供了对映射条目的动态视图，这意味着当映射发生改变时，视图会反映这些改变。


3.3 新版功能.



在 3.9 版更改: 更新为支持 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} 所新增的合并 (@code{|}) 运算符，它会简单地委托给下层的映射。



@deffn {Describe} key in proxy

如果下层的映射中存在键 @emph{key} 则返回 @code{True}，否则返回 @code{False}。
@end deffn


@deffn {Describe} proxy[key]

返回下层的映射中以 @emph{key} 为键的项。 如果下层的映射中不存在键 @emph{key} 则引发 @ref{3f1,,KeyError}。
@end deffn


@deffn {Describe} iter(proxy)

返回由下层映射的键为元素的迭代器。 这是 @code{iter(proxy.keys())} 的快捷方式。
@end deffn


@deffn {Describe} len(proxy)

返回下层映射中的项数。
@end deffn

@geindex copy() (types.MappingProxyType 方法)
@anchor{library/types types MappingProxyType copy}@anchor{1b4e}
@deffn {方法} copy ()

返回下层映射的浅拷贝。
@end deffn

@geindex get() (types.MappingProxyType 方法)
@anchor{library/types types MappingProxyType get}@anchor{1b4f}
@deffn {方法} get (key[, default])

如果 @emph{key} 存在于下层映射中则返回 @emph{key} 的值，否则返回 @emph{default}。 如果 @emph{default} 未给出则默认为 @code{None}，因而此方法绝不会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex items() (types.MappingProxyType 方法)
@anchor{library/types types MappingProxyType items}@anchor{1b50}
@deffn {方法} items ()

返回由下层映射的项 (@code{(键, 值)} 对) 组成的一个新视图。
@end deffn

@geindex keys() (types.MappingProxyType 方法)
@anchor{library/types types MappingProxyType keys}@anchor{1b51}
@deffn {方法} keys ()

返回由下层映射的键组成的一个新视图。
@end deffn

@geindex values() (types.MappingProxyType 方法)
@anchor{library/types types MappingProxyType values}@anchor{1b52}
@deffn {方法} values ()

返回由下层映射的值组成的一个新视图。
@end deffn


@deffn {Describe} reversed(proxy)

返回一个包含下层映射的键的反向迭代器。


3.9 新版功能.

@end deffn
@end deffn

@node 附加工具类和函数,协程工具函数,标准解释器类型,types --- 动态类型创建和内置类型名称
@anchor{library/types additional-utility-classes-and-functions}@anchor{1b53}
@subsubsection 附加工具类和函数


@geindex SimpleNamespace (types 中的类)
@anchor{library/types types SimpleNamespace}@anchor{1d9}
@deffn {类} types.SimpleNamespace

一个简单的 @ref{3da,,object} 子类，提供了访问其命名空间的属性，以及一个有意义的 repr。

不同于 @ref{3da,,object}，对于 @code{SimpleNamespace} 你可以添加和移除属性。 如果一个 @code{SimpleNamespace} 对象使用关键字参数进行初始化，这些参数会被直接加入下层命名空间。

此类型大致等价于以下代码:

@example
class SimpleNamespace:
    def __init__(self, /, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        items = (f"@{k@}=@{v!r@}" for k, v in self.__dict__.items())
        return "@{@}(@{@})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
           return self.__dict__ == other.__dict__
        return NotImplemented
@end example

@code{SimpleNamespace} 可被用于替代 @code{class NS: pass}。 但是，对于结构化记录类型则应改用 @ref{1a1,,namedtuple()}。


3.3 新版功能.



在 3.9 版更改: repr 中的属性顺序由字母顺序改为插入顺序 (类似 @code{dict})。

@end deffn

@geindex DynamicClassAttribute() (在 types 模块中)
@anchor{library/types types DynamicClassAttribute}@anchor{9e2}
@deffn {函数} types.DynamicClassAttribute (fget=None, fset=None, fdel=None, doc=None)

在类上访问 __getattr__ 的路由属性。

这是一个描述器，用于定义通过实例与通过类访问时具有不同行为的属性。 当实例访问时保持正常行为，但当类访问属性时将被路由至类的 __getattr__ 方法；这是通过引发 AttributeError 来完成的。

这允许有在实例上激活的特性属性，同时又有在类上的同名虚拟属性 (一个例子请参见 @ref{496,,enum.Enum})。


3.4 新版功能.

@end deffn

@node 协程工具函数,,附加工具类和函数,types --- 动态类型创建和内置类型名称
@anchor{library/types coroutine-utility-functions}@anchor{1b54}
@subsubsection 协程工具函数


@geindex coroutine() (在 types 模块中)
@anchor{library/types types coroutine}@anchor{875}
@deffn {函数} types.coroutine (gen_func)

此函数可将 @ref{a8c,,generator} 函数转换为返回基于生成器的协程的 @ref{73c,,coroutine function}。 基于生成器的协程仍然属于 @ref{561,,generator iterator}，但同时又可被视为 @ref{18a,,coroutine} 对象兼 @ref{61b,,awaitable}。 不过，它没有必要实现 @ref{73f,,__await__()} 方法。

如果 @emph{gen_func} 是一个生成器函数，它将被原地修改。

如果 @emph{gen_func} 不是一个生成器函数，则它会被包装。 如果它返回一个 @ref{7b2,,collections.abc.Generator} 的实例，该实例将被包装在一个 @emph{awaitable} 代理对象中。 所有其他对象类型将被原样返回。


3.5 新版功能.

@end deffn

@node copy --- 浅层 shallow 和深层 deep 复制操作,pprint --- 数据美化输出,types --- 动态类型创建和内置类型名称,数据类型
@anchor{library/copy doc}@anchor{1b55}@anchor{library/copy copy-shallow-and-deep-copy-operations}@anchor{1b56}@anchor{library/copy module-copy}@anchor{25}
@subsection @code{copy} --- 浅层 (shallow) 和深层 (deep) 复制操作


@geindex copy (模块)

@strong{源代码:} Lib/copy.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/copy.py}


__________________________________________________________________


Python 的赋值语句不复制对象，而是创建目标和对象的绑定关系。对于自身可变，或包含可变项的集合，有时要生成副本用于改变操作，而不必改变原始对象。本模块提供了通用的浅层复制和深层复制操作，（如下所述）。

接口摘要：

@geindex copy() (在 copy 模块中)
@anchor{library/copy copy copy}@anchor{4da}
@deffn {函数} copy.copy (x)

返回 @emph{x} 的浅层复制。
@end deffn

@geindex deepcopy() (在 copy 模块中)
@anchor{library/copy copy deepcopy}@anchor{4db}
@deffn {函数} copy.deepcopy (x[, memo])

返回 @emph{x} 的深层复制。
@end deffn

@geindex Error
@anchor{library/copy copy Error}@anchor{1b57}
@deffn {例外} copy.Error

针对模块特定错误引发。
@end deffn
@anchor{library/copy shallow-vs-deep-copy}@anchor{138c}
浅层与深层复制的区别仅与复合对象（即包含列表或类的实例等其他对象的对象）相关：


@itemize *

@item 
@emph{浅层复制} 构造一个新的复合对象，然后（在尽可能的范围内）将原始对象中找到的对象的 @emph{引用} 插入其中。

@item 
@emph{深层复制} 构造一个新的复合对象，然后，递归地将在原始对象里找到的对象的 @emph{副本} 插入其中。
@end itemize

深度复制操作通常存在两个问题, 而浅层复制操作并不存在这些问题：


@itemize *

@item 
递归对象 (直接或间接包含对自身引用的复合对象) 可能会导致递归循环。

@item 
由于深层复制会复制所有内容，因此可能会过多复制（例如本应该在副本之间共享的数据）。
@end itemize

@ref{4db,,deepcopy()} 函数用以下方式避免了这些问题：


@itemize *

@item 
保留在当前复制过程中已复制的对象的 "备忘录" （@code{memo}） 字典；以及

@item 
允许用户定义的类重载复制操作或复制的组件集合。
@end itemize

此模块不会复制模块、方法、栈追踪、栈帧、文件、套接字、窗口以及任何相似的类型。 它会通过不加修改地返回原始对象来（浅层或深层地）“复制”函数和类；这与 @ref{ca,,pickle} 模块处理这类问题的方式是兼容的。

制作字典的浅层复制可以使用 @ref{551,,dict.copy()} 方法，而制作列表的浅层复制可以通过赋值整个列表的切片完成，例如，@code{copied_list = original_list[:]}。

@geindex 模块; pickle

类可以使用与控制序列化（pickling）操作相同的接口来控制复制操作，关于这些方法的描述信息请参考 @ref{ca,,pickle} 模块。实际上，@ref{25,,copy} 模块使用的正是从 @ref{26,,copyreg} 模块中注册的 pickle 函数。

@geindex __copy__() (copy protocol)
@geindex __deepcopy__() (copy protocol)

想要给一个类定义它自己的拷贝操作实现，可以通过定义特殊方法 @code{__copy__()} 和 @code{__deepcopy__()}。 调用前者以实现浅层拷贝操作，该方法不用传入额外参数。 调用后者以实现深层拷贝操作；它应传入一个参数即 @code{memo} 字典。 如果 @code{__deepcopy__()} 实现需要创建一个组件的深层拷贝，它应当调用 @ref{4db,,deepcopy()} 函数并以该组件作为第一个参数，而将 memo 字典作为第二个参数。


@subsubheading 参见



@table @asis

@item 模块 @ref{ca,,pickle}

讨论了支持对象状态检索和恢复的特殊方法。
@end table


@node pprint --- 数据美化输出,reprlib --- 另一种 repr 实现,copy --- 浅层 shallow 和深层 deep 复制操作,数据类型
@anchor{library/pprint doc}@anchor{1b58}@anchor{library/pprint module-pprint}@anchor{d2}@anchor{library/pprint pprint-data-pretty-printer}@anchor{1b59}
@subsection @code{pprint} --- 数据美化输出


@geindex pprint (模块)

@strong{源代码：} Lib/pprint.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pprint.py}


__________________________________________________________________


@ref{d2,,pprint} 模块提供了“美化打印”任意 Python 数据结构的功能，这种美化形式可用作对解释器的输入。 如果经格式化的结构包含非基本 Python 类型的对象，则其美化形式可能无法被加载。 包含文件、套接字或类对象，以及许多其他不能用 Python 字面值来表示的对象都有可能导致这样的结果。

格式化后的形式会在可能的情况下以单行来表示对象，并在无法在允许宽度内容纳对象的情况下将其分为多行。 如果你需要调整宽度限制则应显式地构造 @ref{985,,PrettyPrinter} 对象。

字典在计算其显示形式前会先根据键来排序。


在 3.9 版更改: 添加了对美化打印 @ref{1d9,,types.SimpleNamespace} 的支持。


@ref{d2,,pprint} 模块定义了一个类：

@c First the implementation class:

@geindex ...; placeholder

@geindex PrettyPrinter (pprint 中的类)
@anchor{library/pprint pprint PrettyPrinter}@anchor{985}
@deffn {类} pprint.PrettyPrinter (indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)

构造一个 @ref{985,,PrettyPrinter} 实例。 此构造器接受几个关键字形参。 使用 @emph{stream} 关键字可设置输出流；流对象使用的唯一方法是文件协议的 @code{write()} 方法。 如果未指定此关键字，则 @ref{985,,PrettyPrinter} 会选择 @code{sys.stdout}。 每个递归层次的缩进量由 @emph{indent} 指定；默认值为一。 其他值可导致输出看起来有些怪异，，但可使得嵌套结构更易区分。 可被打印的层级数量由 @emph{depth} 控制；如果数据结构的层级被打印得过深，其所包含的下一层级会被替换为 @code{...}。 在默认情况下，对被格式化对象的层级深度没有限制。 希望的输出宽度可使用 @emph{width} 形参来限制；默认值为 80 个字符。 如果一个结构无法在限定宽度内被格式化，则将做到尽可能接近。 如果 @emph{compact} 为假值（默认）则长序列的每一项将被格式化为单独的行。 如果 @emph{compact} 为真值，则将在 @emph{width} 可容纳的的情况下把尽可能多的项放入每个输出行。 如果 @emph{sort_dicts} 为真值（默认），字典将被格式化为按键排序，否则将按插入顺序显示。


在 3.4 版更改: 增加了 @emph{compact} 形参。



在 3.8 版更改: 增加了 @emph{sort_dicts} 形参。

@example
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
@end example

@end deffn

@ref{d2,,pprint} 模块还提供了一些快捷函数：

@geindex pformat() (在 pprint 模块中)
@anchor{library/pprint pprint pformat}@anchor{986}
@deffn {函数} pprint.pformat (object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

@emph{object} 的格式化表示作为字符串返回。 @emph{indent}, @emph{width}, @emph{depth}, @emph{compact} 和 @emph{sort_dicts} 将作为格式化形参被传入 @ref{985,,PrettyPrinter} 构造器。


在 3.4 版更改: 增加了 @emph{compact} 形参。



在 3.8 版更改: 增加了 @emph{sort_dicts} 形参。

@end deffn

@geindex pp() (在 pprint 模块中)
@anchor{library/pprint pprint pp}@anchor{347}
@deffn {函数} pprint.pp (object, *args, sort_dicts=False, **kwargs)

打印 @emph{object} 的格式化表示并附带一个换行符。 如果 @emph{sort_dicts} 为假值（默认），字典将按键的插入顺序显示，否则将按字典键排序。 @emph{args} 和 @emph{kwargs} 将作为格式化形参被传给 @ref{d2,,pprint()}。


3.8 新版功能.

@end deffn

@geindex pprint() (在 pprint 模块中)
@anchor{library/pprint pprint pprint}@anchor{348}
@deffn {函数} pprint.pprint (object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

在 @emph{stream} 上打打印 @emph{object} 的格式化表示，并附带一个换行符。 如果 @emph{stream} 为 @code{None}，则使用 @code{sys.stdout}。 这可以替代 @ref{97a,,print()} 函数在交互式解释器中使用以查看值（你甚至可以执行重新赋值 @code{print = pprint.pprint} 以在特定作用域中使用）。 @emph{indent}, @emph{width}, @emph{depth}, @emph{compact} 和 @emph{sort_dicts} 将作为格式化形参被传给 @ref{985,,PrettyPrinter} 构造器。


在 3.4 版更改: 增加了 @emph{compact} 形参。



在 3.8 版更改: 增加了 @emph{sort_dicts} 形参。

@example
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=...>,
 'spam',
 'eggs',
 'lumberjack',
 'knights',
 'ni']
@end example

@end deffn

@geindex isreadable() (在 pprint 模块中)
@anchor{library/pprint pprint isreadable}@anchor{1b5a}
@deffn {函数} pprint.isreadable (object)

@geindex 內置函数; eval

确定 @emph{object} 的格式化表示是否“可读”，或是否可被用来通过 @ref{c6a,,eval()} 重新构建对象的值。 此函数对于递归对象总是返回 @code{False}。

@example
>>> pprint.isreadable(stuff)
False
@end example
@end deffn

@geindex isrecursive() (在 pprint 模块中)
@anchor{library/pprint pprint isrecursive}@anchor{1b5b}
@deffn {函数} pprint.isrecursive (object)

确定 @emph{object} 是否需要递归表示。
@end deffn

此外还定义了一个支持函数：

@geindex saferepr() (在 pprint 模块中)
@anchor{library/pprint pprint saferepr}@anchor{1b5c}
@deffn {函数} pprint.saferepr (object)

返回 @emph{object} 的字符串表示，并为递归数据结构提供保护。 如果 @emph{object} 的表示形式公开了一个递归条目，该递归引用会被表示为 @code{<Recursion on typename with id=number>}。 该表示因而不会进行其它格式化。

@example
>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
@end example
@end deffn

@menu
* PrettyPrinter 对象:: 
* 示例: 示例<5>. 

@end menu

@node PrettyPrinter 对象,示例<5>,,pprint --- 数据美化输出
@anchor{library/pprint id1}@anchor{1b5d}@anchor{library/pprint prettyprinter-objects}@anchor{1b5e}
@subsubsection PrettyPrinter 对象


@ref{985,,PrettyPrinter} 的实例具有下列方法：

@geindex pformat() (pprint.PrettyPrinter 方法)
@anchor{library/pprint pprint PrettyPrinter pformat}@anchor{1b5f}
@deffn {方法} PrettyPrinter.pformat (object)

返回 @emph{object} 格式化表示。 这会将传给 @ref{985,,PrettyPrinter} 构造器的选项纳入考虑。
@end deffn

@geindex pprint() (pprint.PrettyPrinter 方法)
@anchor{library/pprint pprint PrettyPrinter pprint}@anchor{1b60}
@deffn {方法} PrettyPrinter.pprint (object)

在所配置的流上打印 @emph{object} 的格式化表示，并附加一个换行符。
@end deffn

下列方法提供了与同名函数相对应的实现。 在实例上使用这些方法效率会更高一些，因为不需要创建新的 @ref{985,,PrettyPrinter} 对象。

@geindex isreadable() (pprint.PrettyPrinter 方法)
@anchor{library/pprint pprint PrettyPrinter isreadable}@anchor{1b61}
@deffn {方法} PrettyPrinter.isreadable (object)

@geindex 內置函数; eval

确定对象的格式化表示是否“可读”，或者是否可使用 @ref{c6a,,eval()} 重建对象值。 请注意此方法对于递归对象将返回 @code{False}。 如果设置了 @ref{985,,PrettyPrinter} 的 @emph{depth} 形参并且对象深度超出允许范围，此方法将返回 @code{False}。
@end deffn

@geindex isrecursive() (pprint.PrettyPrinter 方法)
@anchor{library/pprint pprint PrettyPrinter isrecursive}@anchor{1b62}
@deffn {方法} PrettyPrinter.isrecursive (object)

确定对象是否需要递归表示。
@end deffn

此方法作为一个钩子提供，允许子类修改将对象转换为字符串的方式。 默认实现使用 @ref{1b5c,,saferepr()} 实现的内部方式。

@geindex format() (pprint.PrettyPrinter 方法)
@anchor{library/pprint pprint PrettyPrinter format}@anchor{1b63}
@deffn {方法} PrettyPrinter.format (object, context, maxlevels, level)

返回三个值：字符串形式的 @emph{object} 已格式化版本，指明结果是否可读的旗标，以及指明是否检测到递归的旗标。 第一个参数是要表示的对象。 第二个是以对象 @ref{e53,,id()} 为键的字典，这些对象是当前表示上下文的一部分（影响 @emph{object} 表示的直接和间接容器）；如果需要呈现一个已经在 @emph{context} 中表示的对象，则第三个返回值应当为 @code{True}。 对 @ref{1b63,,format()} 方法的递归调用应当将容器的附加条目添加到此字典中。 第三个参数 @emph{maxlevels} 给出了对递归的请求限制；如果没有请求限制则其值将为 @code{0}。 此参数应当不加修改地传给递归调用。 第四个参数 @emph{level} 给出于当前层级；传给递归调用的参数值应当小于当前调用的值。
@end deffn

@node 示例<5>,,PrettyPrinter 对象,pprint --- 数据美化输出
@anchor{library/pprint example}@anchor{1b64}@anchor{library/pprint pprint-example}@anchor{1b65}
@subsubsection 示例


为了演示 @ref{d2,,pprint()} 函数及其形参的几种用法，让我们从 PyPI@footnote{https://pypi.org} 获取关于某个项目的信息:

@example
>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
...     project_info = json.load(resp)['info']
@end example

@ref{d2,,pprint()} 以其基本形式显示了整个对象:

@example
>>> pprint.pprint(project_info)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 2',
                 'Programming Language :: Python :: 2.6',
                 'Programming Language :: Python :: 2.7',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3.2',
                 'Programming Language :: Python :: 3.3',
                 'Programming Language :: Python :: 3.4',
                 'Topic :: Software Development :: Build Tools'],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{'last_day': -1, 'last_month': -1, 'last_week': -1@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{'Download': 'UNKNOWN',
                  'Homepage': 'https://github.com/pypa/sampleproject'@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

结果可以被限制到特定的 @emph{depth} (更深层的内容将使用省略号):

@example
>>> pprint.pprint(project_info, depth=1)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{...@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{...@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

此外，还可以设置建议的最大字符 @emph{width}。 如果一个对象无法被拆分，则将超出指定宽度:

@example
>>> pprint.pprint(project_info, depth=1, width=60)
@{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the '
                'project.\n'
                '\n'
                'The file should use UTF-8 encoding and be '
                'written using ReStructured Text. It\n'
                'will be used to generate the project '
                'webpage on PyPI, and should be written '
                'for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would '
                'include an overview of the project, '
                'basic\n'
                'usage examples, etc. Generally, including '
                'the project changelog in here is not\n'
                'a good idea, although a simple "What\'s '
                'New" section for the most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': @{...@},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': @{...@},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'@}
@end example

@node reprlib --- 另一种 repr 实现,enum --- 对枚举的支持,pprint --- 数据美化输出,数据类型
@anchor{library/reprlib doc}@anchor{1b66}@anchor{library/reprlib module-reprlib}@anchor{df}@anchor{library/reprlib reprlib-alternate-repr-implementation}@anchor{1b67}
@subsection @code{reprlib} --- 另一种 @code{repr()} 实现


@geindex reprlib (模块)

@strong{源代码:} Lib/reprlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/reprlib.py}


__________________________________________________________________


@ref{df,,reprlib} 模块提供了一种对象表示的产生方式，它会对结果字符串的大小进行限制。 该方式被用于 Python 调试器，也适用于某些其他场景。

此模块提供了一个类、一个实例和一个函数：

@geindex Repr (reprlib 中的类)
@anchor{library/reprlib reprlib Repr}@anchor{1b68}
@deffn {类} reprlib.Repr

该类提供了格式化服务 适用于实现与内置 @ref{8c3,,repr()} 相似的方法；其中附加了针对不同对象类型的大小限制，以避免生成超长的表示。
@end deffn

@geindex aRepr() (在 reprlib 模块中)
@anchor{library/reprlib reprlib aRepr}@anchor{1b69}
@deffn {数据} reprlib.aRepr

这是 @ref{1b68,,Repr} 的一个实例，用于提供如下所述的 @ref{1b6a,,repr()} 函数。 改变此对象的属性将会影响 @ref{1b6a,,repr()} 和 Python 调试器所使用的大小限制。
@end deffn

@geindex repr() (在 reprlib 模块中)
@anchor{library/reprlib reprlib repr}@anchor{1b6a}
@deffn {函数} reprlib.repr (obj)

这是 @code{aRepr} 的 @ref{1b6b,,repr()} 方法。 它会返回与同名内置函数所返回字符串相似的字符串，区别在于附带了对多数类型的大小限制。
@end deffn

在大小限制工具以外，此模块还提供了一个装饰器，用于检测对 @ref{453,,__repr__()} 的递归调用并改用一个占位符来替换。

@geindex ...; placeholder

@geindex recursive_repr() (在 reprlib 模块中)
@anchor{library/reprlib reprlib recursive_repr}@anchor{c4a}
@deffn {函数} @@reprlib.recursive_repr (fillvalue="...")

用于为 @ref{453,,__repr__()} 方法检测同一线程内部递归调用的装饰器。 如果执行了递归调用，则会返回 @emph{fillvalue}，否则执行正常的 @ref{453,,__repr__()} 调用。 例如：

@example
>>> from reprlib import recursive_repr
>>> class MyList(list):
...     @@recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>
@end example


3.2 新版功能.

@end deffn

@menu
* Repr 对象:: 
* 子类化 Repr 对象:: 

@end menu

@node Repr 对象,子类化 Repr 对象,,reprlib --- 另一种 repr 实现
@anchor{library/reprlib id1}@anchor{1b6c}@anchor{library/reprlib repr-objects}@anchor{1b6d}
@subsubsection Repr 对象


@ref{1b68,,Repr} 实例对象包含一些属性可以用于为不同对象类型的表示提供大小限制，还包含一些方法可以格式化特定的对象类型。

@geindex maxlevel (reprlib.Repr 属性)
@anchor{library/reprlib reprlib Repr maxlevel}@anchor{1b6e}
@deffn {属性} Repr.maxlevel

创建递归表示形式的深度限制。 默认为 @code{6}。
@end deffn

@geindex maxdict (reprlib.Repr 属性)
@geindex maxlist (reprlib.Repr 属性)
@geindex maxtuple (reprlib.Repr 属性)
@geindex maxset (reprlib.Repr 属性)
@geindex maxfrozenset (reprlib.Repr 属性)
@geindex maxdeque (reprlib.Repr 属性)
@geindex maxarray (reprlib.Repr 属性)
@anchor{library/reprlib reprlib Repr maxdict}@anchor{1b6f}
@deffn {属性} Repr.maxdict
@anchor{library/reprlib reprlib Repr maxlist}@anchor{1b70}
@deffnx {属性} Repr.maxlist
@anchor{library/reprlib reprlib Repr maxtuple}@anchor{1b71}
@deffnx {属性} Repr.maxtuple
@anchor{library/reprlib reprlib Repr maxset}@anchor{1b72}
@deffnx {属性} Repr.maxset
@anchor{library/reprlib reprlib Repr maxfrozenset}@anchor{1b73}
@deffnx {属性} Repr.maxfrozenset
@anchor{library/reprlib reprlib Repr maxdeque}@anchor{1b74}
@deffnx {属性} Repr.maxdeque
@anchor{library/reprlib reprlib Repr maxarray}@anchor{1b75}
@deffnx {属性} Repr.maxarray

代表命名对象类型的条目数量限制。 对于 @ref{1b6f,,maxdict} 的默认值为 @code{4}，对于 @ref{1b75,,maxarray} 为 @code{5}，对于其他则为  @code{6}。
@end deffn

@geindex maxlong (reprlib.Repr 属性)
@anchor{library/reprlib reprlib Repr maxlong}@anchor{1b76}
@deffn {属性} Repr.maxlong

表示整数的最大字符数量。 数码会从中间被丢弃。 默认值为 @code{40}。
@end deffn

@geindex maxstring (reprlib.Repr 属性)
@anchor{library/reprlib reprlib Repr maxstring}@anchor{1b77}
@deffn {属性} Repr.maxstring

表示字符串的字符数量限制。 请注意字符源会使用字符串的“正常”表示形式：如果表示中需要用到转义序列，在缩短表示时它们可能会被破坏。 默认值为 @code{30}。
@end deffn

@geindex maxother (reprlib.Repr 属性)
@anchor{library/reprlib reprlib Repr maxother}@anchor{1b78}
@deffn {属性} Repr.maxother

此限制用于控制在 @ref{1b68,,Repr} 对象上没有特定的格式化方法可用的对象类型的大小。 它会以类似 @ref{1b77,,maxstring} 的方式被应用。 默认值为 @code{20}。
@end deffn

@geindex repr() (reprlib.Repr 方法)
@anchor{library/reprlib reprlib Repr repr}@anchor{1b6b}
@deffn {方法} Repr.repr (obj)

内置 @ref{8c3,,repr()} 的等价形式，它使用实例专属的格式化。
@end deffn

@geindex repr1() (reprlib.Repr 方法)
@anchor{library/reprlib reprlib Repr repr1}@anchor{1b79}
@deffn {方法} Repr.repr1 (obj, level)

供 @ref{1b6b,,repr()} 使用的递归实现。 此方法使用 @emph{obj} 的类型来确定要调用哪个格式化方法，并传入 @emph{obj} 和 @emph{level}。 类型专属的方法应当调用 @ref{1b79,,repr1()} 来执行递归格式化，在递归调用中使用 @code{level - 1} 作为 @emph{level} 的值。
@end deffn


@deffn {方法} Repr.repr_TYPE (obj, level)

特定类型的格式化方法会被实现为基于类型名称来命名的方法。 在方法名称中，@strong{TYPE} 会被替换为 @code{'_'.join(type(obj).__name__.split())}。 对这些方法的分派会由 @ref{1b79,,repr1()} 来处理。 需要对值进行递归格式化的类型专属方法应当调用 @code{self.repr1(subobj, level - 1)}。
@end deffn

@node 子类化 Repr 对象,,Repr 对象,reprlib --- 另一种 repr 实现
@anchor{library/reprlib subclassing-repr-objects}@anchor{1b7a}@anchor{library/reprlib subclassing-reprs}@anchor{1b7b}
@subsubsection 子类化 Repr 对象


通过 @ref{1b79,,Repr.repr1()} 使用动态分派允许 @ref{1b68,,Repr} 的子类添加对额外内置对象类型的支持，或是修改对已支持类型的处理。 这个例子演示了如何添加对文件对象的特殊支持:

@example
import reprlib
import sys

class MyRepr(reprlib.Repr):

    def repr_TextIOWrapper(self, obj, level):
        if obj.name in @{'<stdin>', '<stdout>', '<stderr>'@}:
            return obj.name
        return repr(obj)

aRepr = MyRepr()
print(aRepr.repr(sys.stdin))         # prints '<stdin>'
@end example

@node enum --- 对枚举的支持,graphlib --- 操作类似图的结构的功能,reprlib --- 另一种 repr 实现,数据类型
@anchor{library/enum doc}@anchor{1b7c}@anchor{library/enum enum-support-for-enumerations}@anchor{1b7d}@anchor{library/enum module-enum}@anchor{79}
@subsection @code{enum} --- 对枚举的支持


@geindex enum (模块)


3.4 新版功能.


@strong{源代码：} Lib/enum.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/enum.py}


__________________________________________________________________


枚举是与多个唯一常量值绑定的一组符号名（即成员）。枚举中的成员可以进行身份比较，并且枚举自身也可迭代。

@cartouche
@quotation 注解 
枚举成员名称的大小写

枚举表示的是常量，因此，建议枚举成员名称使用大写字母，本篇的示例将用此种风格。
@end quotation
@end cartouche

@menu
* 模块内容: 模块内容<2>. 
* 创建 Enum:: 
* 枚举成员及其属性的编程访问:: 
* 重复的枚举成员和值:: 
* 确保唯一枚举值:: 
* 使用自动设定的值:: 
* 迭代:: 
* 比较: 比较<2>. 
* 允许的枚举成员和属性:: 
* 受限的 Enum 子类化:: 
* 封存:: 
* 功能性 API:: 
* 派生的枚举:: 
* 何时使用 __new__() 与 __init__(): 何时使用 __new__ 与 __init__. 
* 有趣的示例:: 
* 各种枚举有何区别？:: 

@end menu

@node 模块内容<2>,创建 Enum,,enum --- 对枚举的支持
@anchor{library/enum module-contents}@anchor{1b7e}
@subsubsection 模块内容


本模块定义了四个枚举类，用来定义名称与值的唯一组合: @ref{496,,Enum}、@ref{68e,,IntEnum}、@ref{648,,Flag} 和 @ref{18ed,,IntFlag}。此外，还定义了一个装饰器，@ref{1b7f,,unique()}， 和一个辅助类，@ref{649,,auto}。

@geindex Enum (enum 中的类)
@anchor{library/enum enum Enum}@anchor{496}
@deffn {类} enum.Enum

创建枚举常量的基类。 如需了解另一种构建语法，请参阅 @ref{1b80,,Functional API} 小节。
@end deffn

@geindex IntEnum (enum 中的类)
@anchor{library/enum enum IntEnum}@anchor{68e}
@deffn {类} enum.IntEnum

创建 @ref{205,,int} 子类枚举常量的基类。
@end deffn

@geindex IntFlag (enum 中的类)
@anchor{library/enum enum IntFlag}@anchor{18ed}
@deffn {类} enum.IntFlag

创建可与位运算符搭配使用，又不失去 @ref{18ed,,IntFlag} 成员资格的枚举常量的基类。@ref{18ed,,IntFlag} 成员也是 @ref{205,,int} 的子类。
@end deffn

@geindex Flag (enum 中的类)
@anchor{library/enum enum Flag}@anchor{648}
@deffn {类} enum.Flag

创建可与位运算符搭配使用，又不会失去 @ref{648,,Flag} 成员资格的枚举常量的基类。
@end deffn


@deffn {函数} enum.unique ()

确保一个名称只绑定一个值的 Enum 类装饰器。
@end deffn

@geindex auto (enum 中的类)
@anchor{library/enum enum auto}@anchor{649}
@deffn {类} enum.auto

以合适的值代替 Enum 成员的实例。 初始值默认从 1 开始。
@end deffn


3.6 新版功能: @code{Flag}, @code{IntFlag}, @code{auto}


@node 创建 Enum,枚举成员及其属性的编程访问,模块内容<2>,enum --- 对枚举的支持
@anchor{library/enum creating-an-enum}@anchor{1b81}
@subsubsection 创建 Enum


枚举是由 @ref{d3a,,class} 句法创建的，这种方式易读、易写。 另一种创建方法请参阅 @ref{1b80,,Functional API}。@ref{496,,Enum} 以如下定义枚举：

@example
>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...
@end example

@cartouche
@quotation 注解 
Enum 成员值

成员值可以是 @ref{205,,int}、@ref{206,,str} 等。若无需设定确切值，@ref{649,,auto} 实例可以自动为成员分配合适 的值。将 @ref{649,,auto} 与其他值混用时必须要慎重。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
命名法


@itemize -

@item 
类 @code{Color} 是 @emph{枚举} （或称为 @emph{enum} ）。

@item 
@code{Color.RED}、@code{Color.GREEN} 等属性是 @emph{枚举成员} （或 @emph{enum 成员}），也是常量。

@item 
枚举成员具有 @emph{名称} 和 @emph{值} (例如 @code{Color.RED} 的名称为 @code{RED}，@code{Color.BLUE} 的值为 @code{3} 等等)
@end itemize
@end quotation
@end cartouche

@cartouche
@quotation 注解 
虽然 Enum 由 @ref{d3a,,class} 语法创建，但 Enum 并不是常规的 Python 类。详见 @ref{1b82,,How are Enums different?}。
@end quotation
@end cartouche

枚举成员的字符串表现形式更容易理解：

@example
>>> print(Color.RED)
Color.RED
@end example

同时，它的 @code{repr} 包含更多信息：

@example
>>> print(repr(Color.RED))
<Color.RED: 1>
@end example

枚举成员的 @emph{类型} 就是它所属的枚举：

@example
>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True
>>>
@end example

Enum 成员还包含 name 属性：

@example
>>> print(Color.RED.name)
RED
@end example

枚举按定义的顺序进行迭代：

@example
>>> class Shake(Enum):
...     VANILLA = 7
...     CHOCOLATE = 4
...     COOKIES = 9
...     MINT = 3
...
>>> for shake in Shake:
...     print(shake)
...
Shake.VANILLA
Shake.CHOCOLATE
Shake.COOKIES
Shake.MINT
@end example

枚举成员可哈希，可用于字典和集合：

@example
>>> apples = @{@}
>>> apples[Color.RED] = 'red delicious'
>>> apples[Color.GREEN] = 'granny smith'
>>> apples == @{Color.RED: 'red delicious', Color.GREEN: 'granny smith'@}
True
@end example

@node 枚举成员及其属性的编程访问,重复的枚举成员和值,创建 Enum,enum --- 对枚举的支持
@anchor{library/enum programmatic-access-to-enumeration-members-and-their-attributes}@anchor{1b83}
@subsubsection 枚举成员及其属性的编程访问


有时，要在程序中访问枚举成员（如，开发时不知道颜色的确切值，@code{Color.RED} 不适用的情况）。@code{Enum} 支持如下访问方式：

@example
>>> Color(1)
<Color.RED: 1>
>>> Color(3)
<Color.BLUE: 3>
@end example

用 @emph{name} 访问枚举成员时，可使用项目名称：

@example
>>> Color['RED']
<Color.RED: 1>
>>> Color['GREEN']
<Color.GREEN: 2>
@end example

可访问枚举成员的 @code{name} 或 @code{value}：

@example
>>> member = Color.RED
>>> member.name
'RED'
>>> member.value
1
@end example

@node 重复的枚举成员和值,确保唯一枚举值,枚举成员及其属性的编程访问,enum --- 对枚举的支持
@anchor{library/enum duplicating-enum-members-and-values}@anchor{1b84}
@subsubsection 重复的枚举成员和值


两个枚举成员的名称不能相同：

@example
>>> class Shape(Enum):
...     SQUARE = 2
...     SQUARE = 3
...
Traceback (most recent call last):
...
TypeError: Attempted to reuse key: 'SQUARE'
@end example

但是，两个枚举成员可以有相同的值。假设，成员 A 和 B 的值相同（先定义的是 A），则 B 是 A 的别名。按值查找 A 和 B 的值返回的是 A。按名称查找 B，返回的也是 A：

@example
>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.SQUARE
<Shape.SQUARE: 2>
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> Shape(2)
<Shape.SQUARE: 2>
@end example

@cartouche
@quotation 注解 
不支持创建与已定义属性（其他成员、方法等）同名的成员，也不支持创建与现有成员同名的属性。
@end quotation
@end cartouche

@node 确保唯一枚举值,使用自动设定的值,重复的枚举成员和值,enum --- 对枚举的支持
@anchor{library/enum ensuring-unique-enumeration-values}@anchor{1b85}
@subsubsection 确保唯一枚举值


默认情况下，枚举允许多个名称作为一个值的别名。如需禁用此行为，下述装饰器可以确保枚举中的值仅能只用一次：

@geindex unique() (在 enum 模块中)
@anchor{library/enum enum unique}@anchor{1b7f}
@deffn {函数} @@enum.unique
@end deffn

专用于枚举的 @ref{d3a,,class} 装饰器。 它会搜索一个枚举的 @code{__members__} 并收集所找到的任何别名；只要找到任何别名就会引发 @ref{16d,,ValueError} 并附带相关细节信息:

@example
>>> from enum import Enum, unique
>>> @@unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
@end example

@node 使用自动设定的值,迭代,确保唯一枚举值,enum --- 对枚举的支持
@anchor{library/enum using-automatic-values}@anchor{1b86}
@subsubsection 使用自动设定的值


如果确切的值不重要，你可以使用 @ref{649,,auto}:

@example
>>> from enum import Enum, auto
>>> class Color(Enum):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
@end example

值将由 @code{_generate_next_value_()} 来选择，该函数可以被重载:

@example
>>> class AutoName(Enum):
...     def _generate_next_value_(name, start, count, last_values):
...         return name
...
>>> class Ordinal(AutoName):
...     NORTH = auto()
...     SOUTH = auto()
...     EAST = auto()
...     WEST = auto()
...
>>> list(Ordinal)
[<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
@end example

@cartouche
@quotation 注解 
默认 @code{_generate_next_value_()} 方法的目标是提供所给出的最后一个 @ref{205,,int} 所在序列的下一个 @ref{205,,int}，但这种行为方式属于实现细节并且可能发生改变。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
@code{_generate_next_value_()} 方法定义必须在任何其他成员之前。
@end quotation
@end cartouche

@node 迭代,比较<2>,使用自动设定的值,enum --- 对枚举的支持
@anchor{library/enum iteration}@anchor{1b87}
@subsubsection 迭代


对枚举成员的迭代不会给出别名:

@example
>>> list(Shape)
[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]
@end example

特殊属性 @code{__members__} 是一个从名称到成员的只读有序映射。 它包含枚举中定义的所有名称，包括别名:

@example
>>> for name, member in Shape.__members__.items():
...     name, member
...
('SQUARE', <Shape.SQUARE: 2>)
('DIAMOND', <Shape.DIAMOND: 1>)
('CIRCLE', <Shape.CIRCLE: 3>)
('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)
@end example

@code{__members__} 属性可被用于对枚举成员进行详细的程序化访问。 例如，找出所有别名:

@example
>>> [name for name, member in Shape.__members__.items() if member.name != name]
['ALIAS_FOR_SQUARE']
@end example

@node 比较<2>,允许的枚举成员和属性,迭代,enum --- 对枚举的支持
@anchor{library/enum comparisons}@anchor{1b88}
@subsubsection 比较


枚举成员是按标识号进行比较的:

@example
>>> Color.RED is Color.RED
True
>>> Color.RED is Color.BLUE
False
>>> Color.RED is not Color.BLUE
True
@end example

枚举值之间的排序比较 @emph{不被} 支持。 Enum 成员不属于整数 (另请参阅下文的 @ref{1b89,,IntEnum}):

@example
>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'
@end example

相等比较的定义如下:

@example
>>> Color.BLUE == Color.RED
False
>>> Color.BLUE != Color.RED
True
>>> Color.BLUE == Color.BLUE
True
@end example

与非枚举值的比较将总是不相等（同样地，@ref{68e,,IntEnum} 被显式设计成不同的行为，参见下文）:

@example
>>> Color.BLUE == 2
False
@end example

@node 允许的枚举成员和属性,受限的 Enum 子类化,比较<2>,enum --- 对枚举的支持
@anchor{library/enum allowed-members-and-attributes-of-enumerations}@anchor{1b8a}
@subsubsection 允许的枚举成员和属性


以上示例使用整数作为枚举值。 使用整数相当简洁方便（并由 @ref{1b80,,Functional API} 默认提供），但并不强制要求使用。 在大部分用例中，开发者都关心枚举的实际值是什么。 但如果值 @emph{确实} 重要，则枚举可以使用任意的值。

枚举属于 Python 的类，并可具有普通方法和特殊方法。 如果我们有这样一个枚举:

@example
>>> class Mood(Enum):
...     FUNKY = 1
...     HAPPY = 3
...
...     def describe(self):
...         # self is the member here
...         return self.name, self.value
...
...     def __str__(self):
...         return 'my custom str! @{0@}'.format(self.value)
...
...     @@classmethod
...     def favorite_mood(cls):
...         # cls here is the enumeration
...         return cls.HAPPY
...
@end example

那么:

@example
>>> Mood.favorite_mood()
<Mood.HAPPY: 3>
>>> Mood.HAPPY.describe()
('HAPPY', 3)
>>> str(Mood.FUNKY)
'my custom str! 1'
@end example

对于允许内容的规则如下：以单下划线开头和结尾的名称是由枚举保留而不可使用；在枚举中定义的所有其他属性将成为该枚举的成员，例外项则包括特殊方法成员 (@ref{f01,,__str__()}, @ref{15c4,,__add__()} 等)，描述符 (方法也属于描述符) 以及在 @code{_ignore_} 中列出的变量名。

注意：如果你的枚举定义了 @ref{97d,,__new__()} 和/或 @ref{e2b,,__init__()} 那么给予枚举成员的任何值都会被传入这些方法。 请参阅示例 @ref{1b8b,,Planet}。

@node 受限的 Enum 子类化,封存,允许的枚举成员和属性,enum --- 对枚举的支持
@anchor{library/enum restricted-enum-subclassing}@anchor{1b8c}
@subsubsection 受限的 Enum 子类化


一个新的 @ref{496,,Enum} 类必须基于一个 Enum 类，至多一个实体数据类型以及出于实际需要的任意多个基于 @ref{3da,,object} 的 mixin 类。 这些基类的顺序为:

@example
class EnumName([mix-in, ...,] [data-type,] base-enum):
    pass
@end example

另外，仅当一个枚举未定义任何成员时才允许子类化该枚举。 因此禁止这样的写法:

@example
>>> class MoreColor(Color):
...     PINK = 17
...
Traceback (most recent call last):
...
TypeError: Cannot extend enumerations
@end example

但是允许这样的写法:

@example
>>> class Foo(Enum):
...     def some_behavior(self):
...         pass
...
>>> class Bar(Foo):
...     HAPPY = 1
...     SAD = 2
...
@end example

允许子类化定义了成员的枚举将会导致违反类型与实例的某些重要的不可变规则。 在另一方面，允许在一组枚举之间共享某些通用行为也是有意义的。 （请参阅示例 @ref{1b8d,,OrderedEnum} 。）

@node 封存,功能性 API,受限的 Enum 子类化,enum --- 对枚举的支持
@anchor{library/enum pickling}@anchor{1b8e}
@subsubsection 封存


枚举可以被封存与解封:

@example
>>> from test.test_enum import Fruit
>>> from pickle import dumps, loads
>>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
True
@end example

封存的常规限制同样适用：可封存枚举必须在模块的最高层级中定义，因为解封操作要求它们可以从该模块导入。

@cartouche
@quotation 注解 
使用 pickle 协议版本 4 可以方便地封存嵌套在其他类中的枚举。
@end quotation
@end cartouche

通过在枚举类中定义 @ref{1b8f,,__reduce_ex__()} 可以对 Enum 成员的封存/解封方式进行修改。

@node 功能性 API,派生的枚举,封存,enum --- 对枚举的支持
@anchor{library/enum functional-api}@anchor{1b80}
@subsubsection 功能性 API


@ref{496,,Enum} 类属于可调用对象，它提供了以下功能性 API:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
>>> Animal
<enum 'Animal'>
>>> Animal.ANT
<Animal.ANT: 1>
>>> Animal.ANT.value
1
>>> list(Animal)
[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
@end example

该 API 的主义类似于 @ref{1a1,,namedtuple}。 调用 @ref{496,,Enum} 的第一个参数是枚举的名称。

第二个参数是枚举成员名称的 @emph{来源}。 它可以是一个用空格分隔的名称字符串、名称序列、键/值对 2 元组的序列，或者名称到值的映射（例如字典）。 最后两种选项使得可以为枚举任意赋值；其他选项会自动以从 1 开始递增的整数赋值（使用 @code{start} 形参可指定不同的起始值）。 返回值是一个派生自 @ref{496,,Enum} 的新类。 换句话说，以上对 @code{Animal} 的赋值就等价于:

@example
>>> class Animal(Enum):
...     ANT = 1
...     BEE = 2
...     CAT = 3
...     DOG = 4
...
@end example

默认以 @code{1} 而以 @code{0} 作为起始数值的原因在于 @code{0} 的布尔值为 @code{False}，但所有枚举成员都应被求值为 @code{True}。

对使用功能性 API 创建的枚举执行封存可能会很麻烦，因为要使用帧堆栈的实现细节来尝试并找出枚举是在哪个模块中创建的（例如当你使用了另一个模块中的工具函数就可能失败，在 IronPython 或 Jython 上也可能无效）。 解决办法是显式地指定模块名称，如下所示:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)
@end example

@cartouche
@quotation 警告 
如果未提供 @code{module}，且 Enum 无法确定是哪个模块，新的 Enum 成员将不可被解封；为了让错误尽量靠近源头，封存将被禁用。
@end quotation
@end cartouche

新的 pickle 协议版本 4 在某些情况下同样依赖于 @ref{158a,,__qualname__} 被设为特定位置以便 pickle 能够找到相应的类。 例如，类是否存在于全局作用域的 SomeData 类中:

@example
>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')
@end example

完整的签名为:

@example
Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)
@end example

@*值: 
将被新 Enum 类将记录为其名称的数据。


@*名称: 
Enum 的成员。 这可以是一个空格或逗号分隔的字符串 (起始值将为 1，除非另行指定):

@example
'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
@end example

或是一个名称的迭代器:

@example
['RED', 'GREEN', 'BLUE']
@end example

或是一个 (名称, 值) 对的迭代器:

@example
[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
@end example

或是一个映射:

@example
@{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42@}
@end example


@*模块: 
新 Enum 类所在模块的名称。


@*qualname: 
新 Enum 类在模块中的具体位置。


@*类型: 
要加入新 Enum 类的类型。


@*start: 
当只传入名称时要使用的起始数值。



在 3.5 版更改: 增加了 @emph{start} 形参。


@node 派生的枚举,何时使用 __new__ 与 __init__,功能性 API,enum --- 对枚举的支持
@anchor{library/enum derived-enumerations}@anchor{1b90}
@subsubsection 派生的枚举


@menu
* IntEnum:: 
* IntFlag:: 
* Flag:: 
* 其他事项:: 

@end menu

@node IntEnum,IntFlag,,派生的枚举
@anchor{library/enum intenum}@anchor{1b89}
@subsubsection IntEnum


所提供的第一个变种 @ref{496,,Enum} 同时也是 @ref{205,,int} 的一个子类。 @ref{68e,,IntEnum} 的成员可与整数进行比较；通过扩展，不同类型的整数枚举也可以相互进行比较:

@example
>>> from enum import IntEnum
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Request(IntEnum):
...     POST = 1
...     GET = 2
...
>>> Shape == 1
False
>>> Shape.CIRCLE == 1
True
>>> Shape.CIRCLE == Request.POST
True
@end example

不过，它们仍然不可与标准 @ref{496,,Enum} 枚举进行比较:

@example
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...
>>> Shape.CIRCLE == Color.RED
False
@end example

@ref{68e,,IntEnum} 值在其他方面的行为都如你预期的一样类似于整数:

@example
>>> int(Shape.CIRCLE)
1
>>> ['a', 'b', 'c'][Shape.CIRCLE]
'b'
>>> [i for i in range(Shape.SQUARE)]
[0, 1]
@end example

@node IntFlag,Flag,IntEnum,派生的枚举
@anchor{library/enum intflag}@anchor{1b91}
@subsubsection IntFlag


所提供的下一个 @ref{496,,Enum} 的变种 @ref{18ed,,IntFlag} 同样是基于 @ref{205,,int} 的，不同之处在于 @ref{18ed,,IntFlag} 成员可使用按位运算符 (&, |, ^, ~) 进行组合且结果仍然为 @ref{18ed,,IntFlag} 成员。 如果，正如名称所表明的，@ref{18ed,,IntFlag} 成员同时也是 @ref{205,,int} 的子类，并能在任何使用 @ref{205,,int} 的场合被使用。 @ref{18ed,,IntFlag} 成员进行除按位运算以外的其他运算都将导致失去 @ref{18ed,,IntFlag} 成员资格。


3.6 新版功能.


示例 @ref{18ed,,IntFlag} 类:

@example
>>> from enum import IntFlag
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True
@end example

对于组合同样可以进行命名:

@example
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...     RWX = 7
>>> Perm.RWX
<Perm.RWX: 7>
>>> ~Perm.RWX
<Perm.-8: -8>
@end example

@ref{18ed,,IntFlag} 和 @ref{496,,Enum} 的另一个重要区别在于如果没有设置任何旗标（值为 0），则其布尔值为 @ref{497,,False}:

@example
>>> Perm.R & Perm.X
<Perm.0: 0>
>>> bool(Perm.R & Perm.X)
False
@end example

由于 @ref{18ed,,IntFlag} 成员同时也是 @ref{205,,int} 的子类，因此它们可以相互组合:

@example
>>> Perm.X | 8
<Perm.8|X: 9>
@end example

@node Flag,其他事项,IntFlag,派生的枚举
@anchor{library/enum flag}@anchor{1b92}
@subsubsection Flag


最后一个变种是 @ref{648,,Flag}。 与 @ref{18ed,,IntFlag} 类似，@ref{648,,Flag} 成员可使用按位运算符 (&, |, ^, ~) 进行组合，与 @ref{18ed,,IntFlag} 不同的是它们不可与任何其它 @ref{648,,Flag} 枚举或 @ref{205,,int} 进行组合或比较。 虽然可以直接指定值，但推荐使用 @ref{649,,auto} 作为值以便让 @ref{648,,Flag} 选择适当的值。


3.6 新版功能.


与 @ref{18ed,,IntFlag} 类似，如果 @ref{648,,Flag} 成员的某种组合导致没有设置任何旗标，则其布尔值为 @ref{497,,False}:

@example
>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.RED & Color.GREEN
<Color.0: 0>
>>> bool(Color.RED & Color.GREEN)
False
@end example

单个旗标的值应当为二的乘方 (1, 2, 4, 8, ...)，旗标的组合则无此限制:

@example
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...     WHITE = RED | BLUE | GREEN
...
>>> Color.WHITE
<Color.WHITE: 7>
@end example

对 "no flags set" 条件指定一个名称并不会改变其布尔值:

@example
>>> class Color(Flag):
...     BLACK = 0
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.BLACK
<Color.BLACK: 0>
>>> bool(Color.BLACK)
False
@end example

@cartouche
@quotation 注解 
对于大多数新代码，强烈推荐使用 @ref{496,,Enum} 和 @ref{648,,Flag}，因为 @ref{68e,,IntEnum} 和 @ref{18ed,,IntFlag} 打破了枚举的某些语义约定（例如可以同整数进行比较，并因而导致此行为被传递给其他无关的枚举）。 @ref{68e,,IntEnum} 和 @ref{18ed,,IntFlag} 的使用应当仅限于 @ref{496,,Enum} 和 @ref{648,,Flag} 无法使用的场合；例如，当使用枚举替代整数常量时，或是与其他系统进行交互操作时。
@end quotation
@end cartouche

@node 其他事项,,Flag,派生的枚举
@anchor{library/enum others}@anchor{1b93}
@subsubsection 其他事项


虽然 @ref{68e,,IntEnum} 是 @ref{79,,enum} 模块的一部分，但要独立实现也应该相当容易:

@example
class IntEnum(int, Enum):
    pass
@end example

这里演示了如何定义类似的派生枚举；例如一个混合了 @ref{206,,str} 而不是 @ref{205,,int} 的 @code{StrEnum}。

几条规则：


@enumerate 

@item 
当子类化 @ref{496,,Enum} 时，在基类序列中的混合类型必须出现于 @ref{496,,Enum} 本身之前，如以上 @ref{68e,,IntEnum} 的例子所示。

@item 
虽然 @ref{496,,Enum} 可以拥有任意类型的成员，不过一旦你混合了附加类型，则所有成员必须为相应类型的值，如在上面的例子中即为 @ref{205,,int}。 此限制不适用于仅添加方法而未指定另一数据类型的混合类。

@item 
当混合了另一数据类型时，@code{value} 属性会 @emph{不同于} 枚举成员自身，但它们仍保持等价且比较结果也相等。

@item 
%-style formatting:  @cite{%s} 和 @cite{%r} 会分别调用 @ref{496,,Enum} 类的 @ref{f01,,__str__()} 和 @ref{453,,__repr__()}；其他代码 (例如表示 IntEnum 的 @cite{%i} 或 @cite{%h}) 会将枚举成员视为对应的混合类型。

@item 
@ref{29d,,格式化字符串字面值}, @ref{5dd,,str.format()} 和 @ref{5de,,format()} 将使用混合类型的 @ref{a38,,__format__()} 除非在子类中重载了 @ref{f01,,__str__()} 或 @ref{a38,,__format__()}，在这种情况下将使用被重载的方法或 @ref{496,,Enum} 的方法。 请使用 !s 和 !r 格式代码来强制使用 @ref{496,,Enum} 类的 @ref{f01,,__str__()} 和 @ref{453,,__repr__()} 方法。
@end enumerate

@node 何时使用 __new__ 与 __init__,有趣的示例,派生的枚举,enum --- 对枚举的支持
@anchor{library/enum when-to-use-new-vs-init}@anchor{1b94}
@subsubsection 何时使用 @code{__new__()} 与 @code{__init__()}


当你想要定制 @ref{496,,Enum} 成员的实际值时必须使用 @ref{97d,,__new__()}。 任何其他修改可以用 @ref{97d,,__new__()} 也可以用 @ref{e2b,,__init__()}，应优先使用 @ref{e2b,,__init__()}。

举例来说，如果你要向构造器传入多个条目，但只希望将其中一个作为值:

@example
>>> class Coordinate(bytes, Enum):
...     """
...     Coordinate with binary codes that can be indexed by the int code.
...     """
...     def __new__(cls, value, label, unit):
...         obj = bytes.__new__(cls, [value])
...         obj._value_ = value
...         obj.label = label
...         obj.unit = unit
...         return obj
...     PX = (0, 'P.X', 'km')
...     PY = (1, 'P.Y', 'km')
...     VX = (2, 'V.X', 'km/s')
...     VY = (3, 'V.Y', 'km/s')
...

>>> print(Coordinate['PY'])
Coordinate.PY

>>> print(Coordinate(3))
Coordinate.VY
@end example

@node 有趣的示例,各种枚举有何区别？,何时使用 __new__ 与 __init__,enum --- 对枚举的支持
@anchor{library/enum interesting-examples}@anchor{1b95}
@subsubsection 有趣的示例


虽然 @ref{496,,Enum}, @ref{68e,,IntEnum}, @ref{18ed,,IntFlag} 和 @ref{648,,Flag} 预期可覆盖大多数应用场景，但它们无法覆盖全部。 这里有一些不同类型枚举的方案，它们可以被直接使用，或是作为自行创建的参考示例。

@menu
* 省略值:: 
* OrderedEnum:: 
* DuplicateFreeEnum:: 
* Planet:: 
* TimePeriod:: 

@end menu

@node 省略值,OrderedEnum,,有趣的示例
@anchor{library/enum omitting-values}@anchor{1b96}
@subsubsection 省略值


在许多应用场景中人们都不关心枚举的实际值是什么。 有几个方式可以定义此种类型的简单枚举：


@itemize -

@item 
使用 @ref{649,,auto} 的实例作为值

@item 
使用 @ref{3da,,object} 的实例作为值

@item 
使用描述性的字符串作为值

@item 
使用元组作为值并用自定义的 @ref{97d,,__new__()} 以一个 @ref{205,,int} 值来替代该元组
@end itemize

使用以上任何一种方法均可向用户指明值并不重要，并且使人能够添加、移除或重排序成员而不必改变其余成员的数值。

无论你选择何种方法，你都应当提供一个 @ref{8c3,,repr()} 并且它也需要隐藏（不重要的）值:

@example
>>> class NoValue(Enum):
...     def __repr__(self):
...         return '<%s.%s>' % (self.__class__.__name__, self.name)
...
@end example

@menu
* 使用 auto:: 
* 使用 object:: 
* 使用描述性字符串:: 
* 使用自定义的 __new__(): 使用自定义的 __new__. 

@end menu

@node 使用 auto,使用 object,,省略值
@anchor{library/enum using-auto}@anchor{1b97}
@subsubsection 使用 @code{auto}


使用 @ref{649,,auto} 的形式如下:

@example
>>> class Color(NoValue):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.GREEN
<Color.GREEN>
@end example

@node 使用 object,使用描述性字符串,使用 auto,省略值
@anchor{library/enum using-object}@anchor{1b98}
@subsubsection 使用 @code{object}


使用 @ref{3da,,object} 的形式如下:

@example
>>> class Color(NoValue):
...     RED = object()
...     GREEN = object()
...     BLUE = object()
...
>>> Color.GREEN
<Color.GREEN>
@end example

@node 使用描述性字符串,使用自定义的 __new__,使用 object,省略值
@anchor{library/enum using-a-descriptive-string}@anchor{1b99}
@subsubsection 使用描述性字符串


使用字符串作为值的形式如下:

@example
>>> class Color(NoValue):
...     RED = 'stop'
...     GREEN = 'go'
...     BLUE = 'too fast!'
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
'go'
@end example

@node 使用自定义的 __new__,,使用描述性字符串,省略值
@anchor{library/enum using-a-custom-new}@anchor{1b9a}
@subsubsection 使用自定义的 @code{__new__()}


使用自动编号 @ref{97d,,__new__()} 的形式如下:

@example
>>> class AutoNumber(NoValue):
...     def __new__(cls):
...         value = len(cls.__members__) + 1
...         obj = object.__new__(cls)
...         obj._value_ = value
...         return obj
...
>>> class Color(AutoNumber):
...     RED = ()
...     GREEN = ()
...     BLUE = ()
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
2
@end example

要实现更通用的 @code{AutoNumber}，请添加 @code{*args} 到签名中:

@example
>>> class AutoNumber(NoValue):
...     def __new__(cls, *args):      # this is the only change from above
...         value = len(cls.__members__) + 1
...         obj = object.__new__(cls)
...         obj._value_ = value
...         return obj
...
@end example

这样当你从 @code{AutoNumber} 继承时你将可以编写你自己的 @code{__init__} 来处理任何附加参数:

@example
>>> class Swatch(AutoNumber):
...     def __init__(self, pantone='unknown'):
...         self.pantone = pantone
...     AUBURN = '3497'
...     SEA_GREEN = '1246'
...     BLEACHED_CORAL = () # New color, no Pantone code yet!
...
>>> Swatch.SEA_GREEN
<Swatch.SEA_GREEN: 2>
>>> Swatch.SEA_GREEN.pantone
'1246'
>>> Swatch.BLEACHED_CORAL.pantone
'unknown'
@end example

@cartouche
@quotation 注解 
如果定义了 @ref{97d,,__new__()} 则它会在创建 Enum 成员期间被使用；随后它将被 Enum 的 @ref{97d,,__new__()} 所替换，该方法会在类创建后被用来查找现有成员。
@end quotation
@end cartouche

@node OrderedEnum,DuplicateFreeEnum,省略值,有趣的示例
@anchor{library/enum orderedenum}@anchor{1b8d}
@subsubsection OrderedEnum


一个有序枚举，它不是基于 @ref{68e,,IntEnum}，因此保持了正常的 @ref{496,,Enum} 不变特性（例如不可与其他枚举进行比较）:

@example
>>> class OrderedEnum(Enum):
...     def __ge__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value >= other.value
...         return NotImplemented
...     def __gt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value > other.value
...         return NotImplemented
...     def __le__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value <= other.value
...         return NotImplemented
...     def __lt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value < other.value
...         return NotImplemented
...
>>> class Grade(OrderedEnum):
...     A = 5
...     B = 4
...     C = 3
...     D = 2
...     F = 1
...
>>> Grade.C < Grade.A
True
@end example

@node DuplicateFreeEnum,Planet,OrderedEnum,有趣的示例
@anchor{library/enum duplicatefreeenum}@anchor{1b9b}
@subsubsection DuplicateFreeEnum


如果发现重复的成员名称则将引发错误而不是创建别名:

@example
>>> class DuplicateFreeEnum(Enum):
...     def __init__(self, *args):
...         cls = self.__class__
...         if any(self.value == e.value for e in cls):
...             a = self.name
...             e = cls(self.value).name
...             raise ValueError(
...                 "aliases not allowed in DuplicateFreeEnum:  %r --> %r"
...                 % (a, e))
...
>>> class Color(DuplicateFreeEnum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     GRENE = 2
...
Traceback (most recent call last):
...
ValueError: aliases not allowed in DuplicateFreeEnum:  'GRENE' --> 'GREEN'
@end example

@cartouche
@quotation 注解 
这个例子适用于子类化 Enum 来添加或改变禁用别名以及其他行为。 如果需要的改变只是禁用别名，也可以选择使用 @ref{1b7f,,unique()} 装饰器。
@end quotation
@end cartouche

@node Planet,TimePeriod,DuplicateFreeEnum,有趣的示例
@anchor{library/enum planet}@anchor{1b8b}
@subsubsection Planet


如果定义了 @ref{97d,,__new__()} 或 @ref{e2b,,__init__()} 则枚举成员的值将被传给这些方法:

@example
>>> class Planet(Enum):
...     MERCURY = (3.303e+23, 2.4397e6)
...     VENUS   = (4.869e+24, 6.0518e6)
...     EARTH   = (5.976e+24, 6.37814e6)
...     MARS    = (6.421e+23, 3.3972e6)
...     JUPITER = (1.9e+27,   7.1492e7)
...     SATURN  = (5.688e+26, 6.0268e7)
...     URANUS  = (8.686e+25, 2.5559e7)
...     NEPTUNE = (1.024e+26, 2.4746e7)
...     def __init__(self, mass, radius):
...         self.mass = mass       # in kilograms
...         self.radius = radius   # in meters
...     @@property
...     def surface_gravity(self):
...         # universal gravitational constant  (m3 kg-1 s-2)
...         G = 6.67300E-11
...         return G * self.mass / (self.radius * self.radius)
...
>>> Planet.EARTH.value
(5.976e+24, 6378140.0)
>>> Planet.EARTH.surface_gravity
9.802652743337129
@end example

@node TimePeriod,,Planet,有趣的示例
@anchor{library/enum timeperiod}@anchor{1b9c}
@subsubsection TimePeriod


一个演示如何使用 @code{_ignore_} 属性的例子:

@example
>>> from datetime import timedelta
>>> class Period(timedelta, Enum):
...     "different lengths of time"
...     _ignore_ = 'Period i'
...     Period = vars()
...     for i in range(367):
...         Period['day_%d' % i] = i
...
>>> list(Period)[:2]
[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
>>> list(Period)[-2:]
[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]
@end example

@node 各种枚举有何区别？,,有趣的示例,enum --- 对枚举的支持
@anchor{library/enum how-are-enums-different}@anchor{1b82}
@subsubsection 各种枚举有何区别？


枚举具有自定义的元类，它会影响所派生枚举类及其实例（成员）的各个方面。

@menu
* 枚举类:: 
* 枚举成员（即实例）:: 
* 细节要点:: 

@end menu

@node 枚举类,枚举成员（即实例）,,各种枚举有何区别？
@anchor{library/enum enum-classes}@anchor{1b9d}
@subsubsection 枚举类


@code{EnumMeta} 元类负责提供 @ref{df6,,__contains__()}, @ref{434,,__dir__()}, @ref{611,,__iter__()} 及其他方法以允许用户通过 @ref{496,,Enum} 类来完成一般类做不到的事情，例如 @cite{list(Color)} 或 @cite{some_enum_var in Color}。 @code{EnumMeta} 会负责确保最终 @ref{496,,Enum} 类中的各种其他方法是正确的 (例如 @ref{97d,,__new__()}, @ref{7ab,,__getnewargs__()}, @ref{f01,,__str__()} 和 @ref{453,,__repr__()})。

@node 枚举成员（即实例）,细节要点,枚举类,各种枚举有何区别？
@anchor{library/enum enum-members-aka-instances}@anchor{1b9e}
@subsubsection 枚举成员（即实例）


有关枚举成员最有趣的特点是它们都是单例对象。 @code{EnumMeta} 会在创建 @ref{496,,Enum} 类本身时将它们全部创建完成，然后准备好一个自定义的 @ref{97d,,__new__()}，通过只返回现有的成员实例来确保不会再实例化新的对象。

@node 细节要点,,枚举成员（即实例）,各种枚举有何区别？
@anchor{library/enum finer-points}@anchor{1b9f}
@subsubsection 细节要点


@menu
* 支持的 __dunder__ 名称:: 
* 支持的 _sunder_ 名称:: 
* _Private__names:: 
* Enum 成员类型:: 
* Enum 类和成员的布尔值:: 
* 带有方法的 Enum 类:: 
* 组合 Flag 的成员:: 

@end menu

@node 支持的 __dunder__ 名称,支持的 _sunder_ 名称,,细节要点
@anchor{library/enum supported-dunder-names}@anchor{1ba0}
@subsubsection 支持的 @code{__dunder__} 名称


@code{__members__} 是一个 @code{member_name}:@code{member} 条目的只读有序映射。 它只在类上可用。

如果指定了 @ref{97d,,__new__()}，它必须创建并返回枚举成员；相应地设定成员的 @code{_value_} 也是一个很好的主意。 一旦所有成员都创建完成它就不会再被使用。

@node 支持的 _sunder_ 名称,_Private__names,支持的 __dunder__ 名称,细节要点
@anchor{library/enum supported-sunder-names}@anchor{1ba1}
@subsubsection 支持的 @code{_sunder_} 名称



@itemize -

@item 
@code{_name_} -- 成员的名称

@item 
@code{_value_} -- 成员的值；可以在 @code{__new__} 中设置 / 修改

@item 
@code{_missing_} -- 当未发现某个值时所使用的查找函数；可被重载

@item 
@code{_ignore_} -- 一个名称列表，可以为 @ref{1f9,,list} 或 @ref{206,,str}，它不会被转化为成员，并将从最终类中被移除

@item 
@code{_order_} -- 用于 Python 2/3 代码以确保成员顺序一致（类属性，在类创建期间会被移除）

@item 
@code{_generate_next_value_} -- 用于 @ref{1b80,,Functional API} 并通过 @ref{649,,auto} 为枚举成员获取适当的值；可被重载
@end itemize


3.6 新版功能: @code{_missing_}, @code{_order_}, @code{_generate_next_value_}



3.7 新版功能: @code{_ignore_}


用来帮助 Python 2 / Python 3 代码保持同步提供 @code{_order_} 属性。 它将与枚举的实际顺序进行对照检查，如果两者不匹配则会引发错误:

@example
>>> class Color(Enum):
...     _order_ = 'RED GREEN BLUE'
...     RED = 1
...     BLUE = 3
...     GREEN = 2
...
Traceback (most recent call last):
...
TypeError: member order does not match _order_
@end example

@cartouche
@quotation 注解 
在 Python 2 代码中 @code{_order_} 属性是必须的，因为定义顺序在被记录之前就会丢失。
@end quotation
@end cartouche

@node _Private__names,Enum 成员类型,支持的 _sunder_ 名称,细节要点
@anchor{library/enum private-names}@anchor{1ba2}
@subsubsection _Private__names


@ref{1650,,Private names} will be normal attributes in Python 3.11 instead of either an error
or a member (depending on if the name ends with an underscore). Using these names
in 3.9 and 3.10 will issue a @ref{15a,,DeprecationWarning}.

@node Enum 成员类型,Enum 类和成员的布尔值,_Private__names,细节要点
@anchor{library/enum enum-member-type}@anchor{1ba3}
@subsubsection @code{Enum} 成员类型


@ref{496,,Enum} 成员是其 @ref{496,,Enum} 类的实例，一般通过 @code{EnumClass.member} 的形式来访问。 在特定情况下它们也可通过 @code{EnumClass.member.member} 的形式来访问，但你绝对不应这样做，因为查找可能失败，或者更糟糕地返回你所查找的 @ref{496,,Enum} 成员以外的对象（这也是成员应使用全大写名称的另一个好理由）:

@example
>>> class FieldTypes(Enum):
...     name = 0
...     value = 1
...     size = 2
...
>>> FieldTypes.value.size
<FieldTypes.size: 2>
>>> FieldTypes.size.value
2
@end example

@cartouche
@quotation 注解 
这一行为已被废弃，并将在 3.11 中被删除。
@end quotation
@end cartouche


在 3.5 版更改.


@node Enum 类和成员的布尔值,带有方法的 Enum 类,Enum 成员类型,细节要点
@anchor{library/enum boolean-value-of-enum-classes-and-members}@anchor{1ba4}
@subsubsection @code{Enum} 类和成员的布尔值


混合了非 @ref{496,,Enum} 类型（例如 @ref{205,,int}, @ref{206,,str} 等）的 @ref{496,,Enum} 成员会按所混合类型的规则被求值；在其他情况下，所有成员都将被求值为 @ref{59c,,True}。 要使你的自定义 Enum 的布尔值取决于成员的值，请在你的类中添加以下代码:

@example
def __bool__(self):
    return bool(self.value)
@end example

@ref{496,,Enum} 类总是会被求值为 @ref{59c,,True}。

@node 带有方法的 Enum 类,组合 Flag 的成员,Enum 类和成员的布尔值,细节要点
@anchor{library/enum enum-classes-with-methods}@anchor{1ba5}
@subsubsection 带有方法的 @code{Enum} 类


如果你为你的 @ref{496,,Enum} 子类添加了额外的方法，如同上述的 @ref{1b8b,,Planet} 类一样，这些方法将在对成员执行 @ref{e01,,dir()} 时显示出来，但对类执行时则不会显示:

@example
>>> dir(Planet)
['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
>>> dir(Planet.EARTH)
['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
@end example

@node 组合 Flag 的成员,,带有方法的 Enum 类,细节要点
@anchor{library/enum combining-members-of-flag}@anchor{1ba6}
@subsubsection 组合 @code{Flag} 的成员


如果 Flag 成员的某种组合未被命名，则 @ref{8c3,,repr()} 将包含所有已命名的旗标和值中所有已命名的旗标组合:

@example
>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...     MAGENTA = RED | BLUE
...     YELLOW = RED | GREEN
...     CYAN = GREEN | BLUE
...
>>> Color(3)  # named combination
<Color.YELLOW: 3>
>>> Color(7)      # not named combination
<Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
@end example

@cartouche
@quotation 注解 
In 3.11 unnamed combinations of flags will only produce the canonical flag
members (aka single-value flags).  So @code{Color(7)} would produce something
like @code{<Color.BLUE|GREEN|RED: 7>}.
@end quotation
@end cartouche

@node graphlib --- 操作类似图的结构的功能,,enum --- 对枚举的支持,数据类型
@anchor{library/graphlib doc}@anchor{1ba7}@anchor{library/graphlib graphlib-functionality-to-operate-with-graph-like-structures}@anchor{1ba8}@anchor{library/graphlib module-graphlib}@anchor{89}
@subsection @code{graphlib} --- 操作类似图的结构的功能


@geindex graphlib (模块)

@strong{源代码:} Lib/graphlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/graphlib.py}

@c import graphlib
@c from graphlib import *


__________________________________________________________________


@geindex TopologicalSorter (graphlib 中的类)
@anchor{library/graphlib graphlib TopologicalSorter}@anchor{182}
@deffn {类} graphlib.TopologicalSorter (graph=None)

提供以拓扑方式对可哈希节点的图进行排序的功能。

拓扑排序是指图中顶点的线性排序，使得对于每条从顶点 u 到顶点 v 的有向边 u -> v，顶点 u 都排在顶点 v 之前。 例如，图的顶点可以代表要执行的任务，而边代表某一个任务必须在另一个任务之前执行的约束条件；在这个例子中，拓扑排序只是任务的有效序列。 完全拓扑排序 当且仅当图不包含有向环，也就是说为有向无环图时，完全拓扑排序才是可能的。

如果提供了可选的 @emph{graph} 参数则它必须为一个表示有向无环图的字典，其中的键为节点而值为包含图中该节点的所有上级节点（即具有指向键中的值的边的节点）的可迭代对象。 额外的节点可以使用 @ref{1ba9,,add()} 方法添加到图中。

在通常情况下，对给定的图执行排序所需的步骤如下:

@quotation


@itemize *

@item 
通过可选的初始图创建一个 @ref{182,,TopologicalSorter} 的实例。

@item 
添加额外的节点到图中。

@item 
在图上调用 @ref{1baa,,prepare()}。

@item 
当 @ref{1bab,,is_active()} 为 @code{True} 时，迭代 @ref{1bac,,get_ready()} 所返回的节点并加以处理。 完成处理后在每个节点上调用 @ref{1bad,,done()}。
@end itemize
@end quotation

在只需要对图中的节点进行立即排序并且不涉及并行性的情况下，可以直接使用便捷方法 @ref{1bae,,TopologicalSorter.static_order()}:

@example
>>> graph = @{"D": @{"B", "C"@}, "C": @{"A"@}, "B": @{"A"@}@}
>>> ts = TopologicalSorter(graph)
>>> tuple(ts.static_order())
('A', 'C', 'B', 'D')
@end example

这个类被设计用来在节点就绪时方便地支持对其并行处理。 例如:

@example
topological_sorter = TopologicalSorter()

# Add nodes to 'topological_sorter'...

topological_sorter.prepare()
while topological_sorter.is_active():
    for node in topological_sorter.get_ready():
        # Worker threads or processes take nodes to work on off the
        # 'task_queue' queue.
        task_queue.put(node)

    # When the work for a node is done, workers put the node in
    # 'finalized_tasks_queue' so we can get more nodes to work on.
    # The definition of 'is_active()' guarantees that, at this point, at
    # least one node has been placed on 'task_queue' that hasn't yet
    # been passed to 'done()', so this blocking 'get()' must (eventually)
    # succeed.  After calling 'done()', we loop back to call 'get_ready()'
    # again, so put newly freed nodes on 'task_queue' as soon as
    # logically possible.
    node = finalized_tasks_queue.get()
    topological_sorter.done(node)
@end example

@geindex add() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter add}@anchor{1ba9}
@deffn {方法} add (node, *predecessors)

将一个新节点及其上级节点添加到图中。 @emph{node} 以及 @emph{predecessors} 中的所有元素都必须为可哈希对象。

如果附带相同的节点参数多次调用，则依赖项的集合将为所有被传入依赖项的并集。

可以添加不带依赖项的节点 (即不提供 @emph{predecessors}) 或者重复提供依赖项。 如果有先前未提供的节点包含在 @emph{predecessors} 中则它将被自动添加到图中并且不带自己的上级节点。

如果在 @ref{1baa,,prepare()} 之后被调用则会引发 @ref{16d,,ValueError}。
@end deffn

@geindex prepare() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter prepare}@anchor{1baa}
@deffn {方法} prepare ()

将图标记为已完成并检查图中是否存在环。 如何检测到任何环，则将引发 @ref{1baf,,CycleError}，但 @ref{1bac,,get_ready()} 仍可被用来获取尽可能多的节点直到环阻塞了操作过程。 在调用此函数后，图将无法再修改，因此不能再使用 @ref{1ba9,,add()} 添加更多的节点。
@end deffn

@geindex is_active() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter is_active}@anchor{1bab}
@deffn {方法} is_active ()

如果可以取得更多进展则返回 @code{True}，否则返回 @code{False}。 如果环没有阻塞操作，并且还存在尚未被 @ref{1bac,,TopologicalSorter.get_ready()} 返回的已就绪节点或者已标记为 @ref{1bad,,TopologicalSorter.done()} 的节点数量少于已被 @ref{1bac,,TopologicalSorter.get_ready()} 所返回的节点数量则还可以取得进展。

该类的 @code{__bool__()} 方法要使用此函数，因此除了:

@example
if ts.is_active():
    ...
@end example

可能会简单地执行:

@example
if ts:
    ...
@end example

如果之前未调用 @ref{1baa,,prepare()} 就调用此函数则会引发 @ref{16d,,ValueError}。
@end deffn

@geindex done() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter done}@anchor{1bad}
@deffn {方法} done (*nodes)

将 @ref{1bac,,TopologicalSorter.get_ready()} 所返回的节点集合标记为已处理，解除对 @emph{nodes} 中每个节点的后续节点的阻塞以便在将来通过对 @ref{1bac,,TopologicalSorter.get_ready()} 的调用来返回它们。

如果 @emph{nodes} 中的任何节点已经被之前对该方法的调用标记为已处理或者如果未通过使用 @ref{1ba9,,TopologicalSorter.add()} 将一个节点添加到图中，如果未调用 @ref{1baa,,prepare()} 即调用此方法或者如果节点尚未被 @ref{1bac,,get_ready()} 所返回则将引发 @ref{16d,,ValueError}。
@end deffn

@geindex get_ready() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter get_ready}@anchor{1bac}
@deffn {方法} get_ready ()

返回由所有已就绪节点组成的 @code{tuple}。 初始状态下它将返回所有不带上级节点的节点，并且一旦通过调用 @ref{1bad,,TopologicalSorter.done()} 将它们标记为已处理，之后的调用将返回所有上级节点已被处理的新节点。 一旦无法再取得进展，则会返回空元组。

如果之前未调用 @ref{1baa,,prepare()} 就调用此函数则会引发 @ref{16d,,ValueError}。
@end deffn

@geindex static_order() (graphlib.TopologicalSorter 方法)
@anchor{library/graphlib graphlib TopologicalSorter static_order}@anchor{1bae}
@deffn {方法} static_order ()

返回一个迭代器，它将按照拓扑顺序来迭代所有节点。 当使用此方法时，@ref{1baa,,prepare()} 和 @ref{1bad,,done()} 不应被调用。 此方法等价于:

@example
def static_order(self):
    self.prepare()
    while self.is_active():
        node_group = self.get_ready()
        yield from node_group
        self.done(*node_group)
@end example

所返回的特定顺序可能取决于条目被插入图中的顺序。 例如:

@example
>>> ts = TopologicalSorter()
>>> ts.add(3, 2, 1)
>>> ts.add(1, 0)
>>> print([*ts.static_order()])
[2, 0, 1, 3]

>>> ts2 = TopologicalSorter()
>>> ts2.add(1, 0)
>>> ts2.add(3, 2, 1)
>>> print([*ts2.static_order()])
[0, 2, 1, 3]
@end example

这是由于实际上 "0" 和 "2" 在图中的级别相同（它们将在对 @ref{1bac,,get_ready()} 的同一次调用中被返回） 并且它们之间的顺序是由插入顺序决定的。

如果检测到任何环，则将引发 @ref{1baf,,CycleError}。
@end deffn


3.9 新版功能.

@end deffn

@menu
* 异常: 异常<3>. 

@end menu

@node 异常<3>,,,graphlib --- 操作类似图的结构的功能
@anchor{library/graphlib exceptions}@anchor{1bb0}
@subsubsection 异常


@ref{89,,graphlib} 模块定义了以下异常类:

@geindex CycleError
@anchor{library/graphlib graphlib CycleError}@anchor{1baf}
@deffn {例外} graphlib.CycleError

@ref{16d,,ValueError} 的子类，当特定的图中存在环时将由 @ref{1baa,,TopologicalSorter.prepare()} 引发。 如果存在多个环，则将只报告其中一个未定义的选项并将其包括在异常中。

检测到的环可以通过异常实例的 @code{args} 属性的第二个元素来访问，它由一个节点列表组成，其中的每个节点在图中都是列表中下一个节点的直接上级节点。 在报告的列表中，开头和末尾的节点将是同一对象，以表明它是一个环。
@end deffn

@node 数字和数学模块,函数式编程模块,数据类型,Python 标准库
@anchor{library/numeric doc}@anchor{1bb1}@anchor{library/numeric numeric}@anchor{1bb2}@anchor{library/numeric numeric-and-mathematical-modules}@anchor{1bb3}
@section 数字和数学模块


本章介绍的模块提供与数字和数学相关的函数和数据类型。 @ref{c1,,numbers} 模块定义了数字类型的抽象层次结构。 @ref{b1,,math} 和 @ref{18,,cmath} 模块包含浮点数和复数的各种数学函数。 @ref{35,,decimal} 模块支持使用任意精度算术的十进制数的精确表示。

本章记录以下模块：

@menu
* numbers: numbers --- 数字的抽象基类. 数字的抽象基类
* math: math --- 数学函数. 数学函数
* cmath: cmath --- 关于复数的数学函数. 关于复数的数学函数
* decimal: decimal --- 十进制定点和浮点运算. 十进制定点和浮点运算
* fractions: fractions --- 分数. 分数
* random: random --- 生成伪随机数. 生成伪随机数
* statistics: statistics --- 数学统计函数. 数学统计函数

@end menu

@node numbers --- 数字的抽象基类,math --- 数学函数,,数字和数学模块
@anchor{library/numbers doc}@anchor{1bb4}@anchor{library/numbers module-numbers}@anchor{c1}@anchor{library/numbers numbers-numeric-abstract-base-classes}@anchor{1bb5}
@subsection @code{numbers} --- 数字的抽象基类


@geindex numbers (模块)

@strong{源代码：} Lib/numbers.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/numbers.py}


__________________________________________________________________


@ref{c1,,numbers} 模块 (
@geindex Python 提高建议; PEP 3141
PEP 3141@footnote{https://www.python.org/dev/peps/pep-3141}) 定义了数字 @ref{c0e,,抽象基类} 的层级结构，其中逐级定义了更多操作。 此模块中定义的类型都不可被实例化。

@geindex Number (numbers 中的类)
@anchor{library/numbers numbers Number}@anchor{1584}
@deffn {类} numbers.Number

数字的层次结构的基础。 如果你只想确认参数 @emph{x} 是不是数字而不关心其类型，则使用 @code{isinstance(x, Number)}。
@end deffn

@menu
* 数字的层次:: 
* 类型接口注释。:: 

@end menu

@node 数字的层次,类型接口注释。,,numbers --- 数字的抽象基类
@anchor{library/numbers the-numeric-tower}@anchor{1bb6}
@subsubsection 数字的层次


@geindex Complex (numbers 中的类)
@anchor{library/numbers numbers Complex}@anchor{1587}
@deffn {类} numbers.Complex

这个类型的子类描述了复数并包括了适用于内置 @ref{2c8,,complex} 类型的操作。 这些操作有: 转换为 @ref{2c8,,complex} 和 @ref{2c4,,bool}, @ref{1bb7,,real}, @ref{1bb8,,imag}, @code{+}, @code{-}, @code{*}, @code{/}, @code{**}, @ref{1424,,abs()}, @ref{1bb9,,conjugate()}, @code{==} 以及 @code{!=}。 除 @code{-} 和 @code{!=} 之外所有操作都是抽象的。

@geindex real (numbers.Complex 属性)
@anchor{library/numbers numbers Complex real}@anchor{1bb7}
@deffn {属性} real

抽象的。得到该数字的实数部分。
@end deffn

@geindex imag (numbers.Complex 属性)
@anchor{library/numbers numbers Complex imag}@anchor{1bb8}
@deffn {属性} imag

抽象的。得到该数字的虚数部分。
@end deffn

@geindex conjugate() (numbers.Complex 方法)
@anchor{library/numbers numbers Complex conjugate}@anchor{1bb9}
@deffn {方法} abstractmethod conjugate ()

抽象的。返回共轭复数。例如 @code{(1+3j).conjugate() == (1-3j)}。
@end deffn
@end deffn

@geindex Real (numbers 中的类)
@anchor{library/numbers numbers Real}@anchor{1586}
@deffn {类} numbers.Real

相对于 @ref{1587,,Complex}，@ref{1586,,Real} 加入了只有实数才能进行的操作。

简单的说，它们是：转化至 @ref{1fe,,float}，@ref{dfc,,math.trunc()}、 @ref{d3d,,round()}、 @ref{dfa,,math.floor()}、 @ref{dfb,,math.ceil()}、 @ref{294,,divmod()}、 @code{//}、 @code{%}、 @code{<}、 @code{<=}、 @code{>}、 和 @code{>=}。

实数同样默认支持 @ref{2c8,,complex()}、 @ref{1bb7,,real}、 @ref{1bb8,,imag} 和 @ref{1bb9,,conjugate()}。
@end deffn

@geindex Rational (numbers 中的类)
@anchor{library/numbers numbers Rational}@anchor{d28}
@deffn {类} numbers.Rational

子类型 @ref{1586,,Real} 并加入 @ref{1bba,,numerator} 和 @ref{1bbb,,denominator} 两种属性，这两种属性应该属于最低的级别。加入后，这默认支持 @ref{1fe,,float()}。

@geindex numerator (numbers.Rational 属性)
@anchor{library/numbers numbers Rational numerator}@anchor{1bba}
@deffn {属性} numerator

抽象的。
@end deffn

@geindex denominator (numbers.Rational 属性)
@anchor{library/numbers numbers Rational denominator}@anchor{1bbb}
@deffn {属性} denominator

抽象的。
@end deffn
@end deffn

@geindex Integral (numbers 中的类)
@anchor{library/numbers numbers Integral}@anchor{1585}
@deffn {类} numbers.Integral

子类型 @ref{d28,,Rational} 还增加了到 @ref{205,,int} 的转换操作。 为 @ref{1fe,,float()}, @ref{1bba,,numerator} 和 @ref{1bbb,,denominator} 提供了默认支持。 为 @ref{2d6,,pow()} 方法增加了求余和按位字符串运算的抽象方法: @code{<<}, @code{>>}, @code{&}, @code{^}, @code{|}, @code{~}。
@end deffn

@node 类型接口注释。,,数字的层次,numbers --- 数字的抽象基类
@anchor{library/numbers notes-for-type-implementors}@anchor{1bbc}
@subsubsection 类型接口注释。


实现者需要注意使相等的数字相等并拥有同样的值。当这两个数使用不同的扩展模块时，这其中的差异是很微妙的。例如，用 @ref{2c5,,fractions.Fraction} 实现 @ref{aac,,hash()} 如下:

@example
def __hash__(self):
    if self.denominator == 1:
        # Get integers right.
        return hash(self.numerator)
    # Expensive check, but definitely correct.
    if self == float(self):
        return hash(float(self))
    else:
        # Use tuple's hash to avoid a high collision rate on
        # simple fractions.
        return hash((self.numerator, self.denominator))
@end example

@menu
* 加入更多数字的ABC:: 
* 实现算术运算:: 

@end menu

@node 加入更多数字的ABC,实现算术运算,,类型接口注释。
@anchor{library/numbers adding-more-numeric-abcs}@anchor{1bbd}
@subsubsection 加入更多数字的ABC


当然，这里有更多支持数字的ABC，如果不加入这些，就将缺少层次感。你可以用如下方法在 @ref{1587,,Complex} 和 @ref{1586,,Real} 中加入 @code{MyFoo}:

@example
class MyFoo(Complex): ...
MyFoo.register(Real)
@end example

@node 实现算术运算,,加入更多数字的ABC,类型接口注释。
@anchor{library/numbers id1}@anchor{1bbe}@anchor{library/numbers implementing-the-arithmetic-operations}@anchor{1583}
@subsubsection 实现算术运算


我们希望实现计算，因此，混合模式操作要么调用一个作者知道参数类型的实现，要么转变成为最接近的内置类型并对这个执行操作。对于子类 @ref{1585,,Integral}，这意味着 @ref{15c4,,__add__()} 和 @ref{15c5,,__radd__()} 必须用如下方式定义：

@example
class MyIntegral(Integral):

    def __add__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(self, other)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(self, other)
        else:
            return NotImplemented

    def __radd__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(other, self)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(other, self)
        elif isinstance(other, Integral):
            return int(other) + int(self)
        elif isinstance(other, Real):
            return float(other) + float(self)
        elif isinstance(other, Complex):
            return complex(other) + complex(self)
        else:
            return NotImplemented
@end example

@ref{1587,,Complex} 有 5 种不同的混合类型的操作。 我将上面提到的所有代码作为“模板”称作 @code{MyIntegral} 和 @code{OtherTypeIKnowAbout}。 @code{a} 是  @ref{1587,,Complex} 的子类型 @code{A} 的实例 (@code{a : A <: Complex})，同时 @code{b : B <: Complex}。 我将要计算 @code{a + b}:

@quotation


@enumerate 

@item 
如果 @code{A} 被定义成一个承认 @code{b} 的 @ref{15c4,,__add__()}，一切都没有问题。

@item 
如果 @code{A} 转回成“模板”失败，它将返回一个属于 @ref{15c4,,__add__()} 的值，我们需要避免 @code{B} 定义了一个更加智能的 @ref{15c5,,__radd__()}，因此模板需要返回一个属于 @ref{15c4,,__add__()} 的 @ref{203,,NotImplemented} 。（或者 @code{A} 可能完全不实现 @ref{15c4,,__add__()} 。）

@item 
接着看 @code{B} 的 @ref{15c5,,__radd__()} 。如果它承认 @code{a} ，一切都没有问题。

@item 
如果没有成功回退到模板，就没有更多的方法可以去尝试，因此这里将使用默认的实现。

@item 
如果 @code{B <: A} ， Python 在 @code{A.__add__} 之前尝试 @code{B.__radd__} 。 这是可行的，是通过对 @code{A} 的认识实现的，因此这可以在交给 @ref{1587,,Complex} 处理之前处理这些实例。
@end enumerate
@end quotation

如果 @code{A <: Complex} 和 @code{B <: Real} 没有共享任何资源，那么适当的共享操作涉及内置的 @ref{2c8,,complex} ，并且分别获得 @ref{15c5,,__radd__()} ，因此 @code{a+b == b+a}。

由于对任何一直类型的大部分操作是十分相似的，可以定义一个帮助函数，即一个生成后续或相反的实例的生成器。例如，使用 @ref{2c5,,fractions.Fraction} 如下：

@example
def _operator_fallbacks(monomorphic_operator, fallback_operator):
    def forward(a, b):
        if isinstance(b, (int, Fraction)):
            return monomorphic_operator(a, b)
        elif isinstance(b, float):
            return fallback_operator(float(a), b)
        elif isinstance(b, complex):
            return fallback_operator(complex(a), b)
        else:
            return NotImplemented
    forward.__name__ = '__' + fallback_operator.__name__ + '__'
    forward.__doc__ = monomorphic_operator.__doc__

    def reverse(b, a):
        if isinstance(a, Rational):
            # Includes ints.
            return monomorphic_operator(a, b)
        elif isinstance(a, numbers.Real):
            return fallback_operator(float(a), float(b))
        elif isinstance(a, numbers.Complex):
            return fallback_operator(complex(a), complex(b))
        else:
            return NotImplemented
    reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
    reverse.__doc__ = monomorphic_operator.__doc__

    return forward, reverse

def _add(a, b):
    """a + b"""
    return Fraction(a.numerator * b.denominator +
                    b.numerator * a.denominator,
                    a.denominator * b.denominator)

__add__, __radd__ = _operator_fallbacks(_add, operator.add)

# ...
@end example

@node math --- 数学函数,cmath --- 关于复数的数学函数,numbers --- 数字的抽象基类,数字和数学模块
@anchor{library/math doc}@anchor{1bbf}@anchor{library/math math-mathematical-functions}@anchor{1bc0}@anchor{library/math module-math}@anchor{b1}
@subsection @code{math} --- 数学函数


@geindex math (模块)

@c from math import fsum


__________________________________________________________________


该模块提供了对C标准定义的数学函数的访问。

这些函数不适用于复数；如果你需要计算复数，请使用 @ref{18,,cmath} 模块中的同名函数。将支持计算复数的函数区分开的目的，来自于大多数开发者并不愿意像数学家一样需要学习复数的概念。得到一个异常而不是一个复数结果使得开发者能够更早地监测到传递给这些函数的参数中包含复数，进而调查其产生的原因。

该模块提供了以下函数。除非另有明确说明，否则所有返回值均为浮点数。

@menu
* 数论与表示函数:: 
* 幂函数与对数函数:: 
* 三角函数:: 
* 角度转换:: 
* 双曲函数:: 
* 特殊函数:: 
* 常数:: 

@end menu

@node 数论与表示函数,幂函数与对数函数,,math --- 数学函数
@anchor{library/math number-theoretic-and-representation-functions}@anchor{1bc1}
@subsubsection 数论与表示函数


@geindex ceil() (在 math 模块中)
@anchor{library/math math ceil}@anchor{dfb}
@deffn {函数} math.ceil (x)

返回 @emph{x} 的向上取整，即大于或等于 @emph{x} 的最小的整数。如果 @emph{x} 不是浮点数，委托给 @ref{15f2,,x.__ceil__} ，它应该返回一个 @ref{1585,,Integral} 的值。
@end deffn

@geindex comb() (在 math 模块中)
@anchor{library/math math comb}@anchor{31f}
@deffn {函数} math.comb (n, k)

返回不重复且无顺序地从 @emph{n} 项中选择 @emph{k} 项的方式总数。

当 @code{k <= n} 时取值为 @code{n! / (k! * (n - k)!)}；当 @code{k > n} 时取值为零。

也称为二项式系数，因为它等价于表达式 @code{(1 + x) ** n} 的多项式展开中第 k 项的系数。

如果任一参数不为整数则会引发 @ref{1ff,,TypeError}。 如果任一参数为负数则会引发 @ref{16d,,ValueError}。


3.8 新版功能.

@end deffn

@geindex copysign() (在 math 模块中)
@anchor{library/math math copysign}@anchor{e0b}
@deffn {函数} math.copysign (x, y)

返回一个基于 @emph{x} 的绝对值和 @emph{y} 的符号的浮点数。在支持带符号零的平台上，@code{copysign(1.0, -0.0)} 返回 @emph{-1.0}.
@end deffn

@geindex fabs() (在 math 模块中)
@anchor{library/math math fabs}@anchor{1bc2}
@deffn {函数} math.fabs (x)

返回 @emph{x} 的绝对值。
@end deffn

@geindex factorial() (在 math 模块中)
@anchor{library/math math factorial}@anchor{1fd}
@deffn {函数} math.factorial (x)

以一个整数返回 @emph{x} 的阶乘。 如果 @emph{x} 不是整数或为负数时则将引发 @ref{16d,,ValueError}。


3.9 版后已移除: 接受具有整数值的浮点数 (例如 @code{5.0}) 的行为已被弃用。

@end deffn

@geindex floor() (在 math 模块中)
@anchor{library/math math floor}@anchor{dfa}
@deffn {函数} math.floor (x)

返回 @emph{x} 的向下取整，小于或等于 @emph{x} 的最大整数。如果 @emph{x} 不是浮点数，则委托给 @ref{15f1,,x.__floor__} ，它应返回一个 @ref{1585,,Integral} 值。
@end deffn

@geindex fmod() (在 math 模块中)
@anchor{library/math math fmod}@anchor{16a0}
@deffn {函数} math.fmod (x, y)

返回 @code{fmod(x, y)} ，由平台C库定义。请注意，Python表达式 @code{x % y} 可能不会返回相同的结果。C标准的目的是 @code{fmod(x, y)} 完全（数学上；到无限精度）等于 @code{x - n*y} 对于某个整数 @emph{n} ，使得结果具有 与 @emph{x} 相同的符号和小于 @code{abs(y)} 的幅度。Python的 @code{x % y} 返回带有 @emph{y} 符号的结果，并且可能不能完全计算浮点参数。 例如， @code{fmod(-1e-100, 1e100)} 是 @code{-1e-100} ，但Python的 @code{-1e-100 % 1e100} 的结果是 @code{1e100-1e-100} ，它不能完全表示为浮点数，并且取整为令人惊讶的 @code{1e100} 。 出于这个原因，函数 @ref{16a0,,fmod()} 在使用浮点数时通常是首选，而Python的 @code{x % y} 在使用整数时是首选。
@end deffn

@geindex frexp() (在 math 模块中)
@anchor{library/math math frexp}@anchor{1bc3}
@deffn {函数} math.frexp (x)

以 @code{(m, e)} 对的形式返回 @emph{x} 的尾数和指数。 @emph{m} 是一个浮点数， @emph{e} 是一个整数，正好是 @code{x == m * 2**e} 。 如果 @emph{x} 为零，则返回 @code{(0.0, 0)} ，否则返回 @code{0.5 <= abs(m) < 1} 。这用于以可移植方式“分离”浮点数的内部表示。
@end deffn

@geindex fsum() (在 math 模块中)
@anchor{library/math math fsum}@anchor{e0c}
@deffn {函数} math.fsum (iterable)

返回迭代中的精确浮点值。通过跟踪多个中间部分和来避免精度损失:

@example
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
@end example

该算法的准确性取决于IEEE-754算术保证和舍入模式为半偶的典型情况。在某些非Windows版本中，底层C库使用扩展精度添加，并且有时可能会使中间和加倍，导致它在最低有效位中关闭。

有关待进一步讨论和两种替代方法，参见 ASPN cookbook recipes for accurate floating point summation@footnote{https://code.activestate.com/recipes/393090/}。
@end deffn

@geindex gcd() (在 math 模块中)
@anchor{library/math math gcd}@anchor{1bf}
@deffn {函数} math.gcd (*integers)

返回给定的整数参数的最大公约数。 如果有一个参数非零，则返回值将是能同时整除所有参数的最大正整数。 如果所有参数为零，则返回值为 @code{0}。 不带参数的 @code{gcd()} 返回 @code{0}。


3.5 新版功能.



在 3.9 版更改: 添加了对任意数量的参数的支持。 之前的版本只支持两个参数。

@end deffn

@geindex isclose() (在 math 模块中)
@anchor{library/math math isclose}@anchor{783}
@deffn {函数} math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

若 @emph{a} 和 @emph{b} 的值比较接近则返回 @code{True}，否则返回 @code{False}。

根据给定的绝对和相对容差确定两个值是否被认为是接近的。

@emph{rel_tol} 是相对容差 —— 它是 @emph{a} 和 @emph{b} 之间允许的最大差值，相对于 @emph{a} 或 @emph{b} 的较大绝对值。例如，要设置5％的容差，请传递 @code{rel_tol=0.05} 。默认容差为 @code{1e-09}，确保两个值在大约9位十进制数字内相同。 @emph{rel_tol} 必须大于零。

@emph{abs_tol} 是最小绝对容差 —— 对于接近零的比较很有用。 @emph{abs_tol} 必须至少为零。

如果没有错误发生，结果将是： @code{abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)} 。

IEEE 754特殊值 @code{NaN} ， @code{inf} 和 @code{-inf} 将根据IEEE规则处理。具体来说， @code{NaN} 不被认为接近任何其他值，包括 @code{NaN} 。 @code{inf} 和 @code{-inf} 只被认为接近自己。


3.5 新版功能.



@subsubheading 参见


@geindex Python 提高建议; PEP 485
PEP 485@footnote{https://www.python.org/dev/peps/pep-0485} —— 用于测试近似相等的函数

@end deffn

@geindex isfinite() (在 math 模块中)
@anchor{library/math math isfinite}@anchor{c42}
@deffn {函数} math.isfinite (x)

如果 @emph{x} 既不是无穷大也不是NaN，则返回 @code{True} ，否则返回 @code{False} 。 （注意 @code{0.0} 被认为 @emph{是} 有限的。）


3.2 新版功能.

@end deffn

@geindex isinf() (在 math 模块中)
@anchor{library/math math isinf}@anchor{e09}
@deffn {函数} math.isinf (x)

如果 @emph{x} 是正或负无穷大，则返回 @code{True} ，否则返回 @code{False} 。
@end deffn

@geindex isnan() (在 math 模块中)
@anchor{library/math math isnan}@anchor{e0a}
@deffn {函数} math.isnan (x)

如果 @emph{x} 是 NaN（不是数字），则返回 @code{True} ，否则返回 @code{False} 。
@end deffn

@geindex isqrt() (在 math 模块中)
@anchor{library/math math isqrt}@anchor{320}
@deffn {函数} math.isqrt (n)

返回非负整数 @emph{n} 的整数平方根。 这就是对 @emph{n} 的实际平方根向下取整，或者相当于使得 @emph{a}² ≤ @emph{n} 的最大整数 @emph{a}。

对于某些应用来说，可以更适合取值为使得 @emph{n} ≤ @emph{a}² 的最小整数 @emph{a} ，或者换句话说就是 @emph{n} 的实际平方根向上取整。 对于正数 @emph{n}，这可以使用 @code{a = 1 + isqrt(n - 1)} 来计算。


3.8 新版功能.

@end deffn

@geindex lcm() (在 math 模块中)
@anchor{library/math math lcm}@anchor{1c0}
@deffn {函数} math.lcm (*integers)

返回给定的整数参数的最小公倍数。 如果所有参数均非零，则返回值将是为所有参数的整数倍的最小正整数。 如果参数之一为零，则返回值为 @code{0}。 不带参数的 @code{lcm()} 返回 @code{1}。


3.9 新版功能.

@end deffn

@geindex ldexp() (在 math 模块中)
@anchor{library/math math ldexp}@anchor{1bc4}
@deffn {函数} math.ldexp (x, i)

返回 @code{x * (2**i)} 。 这基本上是函数  @ref{1bc3,,frexp()}  的反函数。
@end deffn

@geindex modf() (在 math 模块中)
@anchor{library/math math modf}@anchor{1bc5}
@deffn {函数} math.modf (x)

返回 @emph{x} 的小数和整数部分。两个结果都带有 @emph{x} 的符号并且是浮点数。
@end deffn

@geindex nextafter() (在 math 模块中)
@anchor{library/math math nextafter}@anchor{1c1}
@deffn {函数} math.nextafter (x, y)

返回 @emph{x} 趋向于 @emph{y} 的最接近的浮点数值。

如果 @emph{x} 等于 @emph{y} 则返回 @emph{y}。

示例：


@itemize *

@item 
@code{math.nextafter(x, math.inf)} 的方向朝上：趋向于正无穷。

@item 
@code{math.nextafter(x, -math.inf)} 的方向朝下：趋向于负无穷。

@item 
@code{math.nextafter(x, 0.0)} 趋向于零。

@item 
@code{math.nextafter(x, math.copysign(math.inf, x))} 趋向于零的反方向。
@end itemize

另请参阅 @ref{1c2,,math.ulp()}。


3.9 新版功能.

@end deffn

@geindex perm() (在 math 模块中)
@anchor{library/math math perm}@anchor{31e}
@deffn {函数} math.perm (n, k=None)

返回不重复且有顺序地从 @emph{n} 项中选择 @emph{k} 项的方式总数。

当 @code{k <= n} 时取值为 @code{n! / (n - k)!}；当 @code{k > n} 时取值为零。

如果 @emph{k} 未指定或为 None，则 @emph{k} 默认值为 @emph{n} 并且函数将返回 @code{n!}。

如果任一参数不为整数则会引发 @ref{1ff,,TypeError}。 如果任一参数为负数则会引发 @ref{16d,,ValueError}。


3.8 新版功能.

@end deffn

@geindex prod() (在 math 模块中)
@anchor{library/math math prod}@anchor{31c}
@deffn {函数} math.prod (iterable, *, start=1)

计算输入的 @emph{iterable} 中所有元素的积。 积的默认 @emph{start} 值为 @code{1}。

当可迭代对象为空时，返回起始值。 此函数特别针对数字值使用，并会拒绝非数字类型。


3.8 新版功能.

@end deffn

@geindex remainder() (在 math 模块中)
@anchor{library/math math remainder}@anchor{4ba}
@deffn {函数} math.remainder (x, y)

返回 IEEE 754 风格的 @emph{x} 相对于 @emph{y} 的余数。对于有限 @emph{x} 和有限非零 @emph{y} ，这是差异 @code{x - n*y} ，其中 @code{n} 是与商 @code{x / y} 的精确值最接近的整数。如果 @code{x / y} 恰好位于两个连续整数之间，则将最接近的 @emph{偶数} 用作 @code{n} 。 余数 @code{r = remainder(x, y)} 因此总是满足 @code{abs(r) <= 0.5 * abs(y)}。

特殊情况遵循IEEE 754：特别是 @code{remainder(x, math.inf)} 对于任何有限 @emph{x} 都是 @emph{x} ，而 @code{remainder(x, 0)} 和 @code{remainder(math.inf, x)} 引发  @ref{16d,,ValueError} 适用于任何非NaN的 @emph{x} 。如果余数运算的结果为零，则该零将具有与 @emph{x} 相同的符号。

在使用IEEE 754二进制浮点的平台上，此操作的结果始终可以完全表示：不会引入舍入错误。


3.7 新版功能.

@end deffn

@geindex trunc() (在 math 模块中)
@anchor{library/math math trunc}@anchor{dfc}
@deffn {函数} math.trunc (x)

返回去除小数部分的 @emph{x} ，只留下整数部分。 这样就可以四舍五入到0了： @code{trunc()} 对于正的 @emph{x} 相当于 @ref{dfa,,floor()} ，对于负的 @emph{x} 相当于 @ref{dfb,,ceil()} 。如果 @emph{x} 不是浮点数，委托给 @ref{15f0,,x.__trunc__} ，它应该返回一个 @ref{1585,,Integral} 值。
@end deffn

@geindex ulp() (在 math 模块中)
@anchor{library/math math ulp}@anchor{1c2}
@deffn {函数} math.ulp (x)

返回浮点数 @emph{x} 的最小有效比特位的值:


@itemize *

@item 
如果 @emph{x} 是 NaN (非数字)，则返回 @emph{x}。

@item 
如果 @emph{x} 为负数，则返回 @code{ulp(-x)}。

@item 
如果 @emph{x} 为正数，则返回 @emph{x}。

@item 
如果 @emph{x} 等于零，则返回 @emph{去正规化的} 可表示最小正浮点数 (小于 @emph{正规化的} 最小正浮点数 @ref{1145,,sys.float_info.min})。

@item 
如果 @emph{x} 等于可表示最大正浮点数，则返回 @emph{x} 的最低有效比特位的值，使得小于 @emph{x} 的第一个浮点数为 @code{x - ulp(x)}。

@item 
在其他情况下 (@emph{x} 是一个有限的正数)，则返回 @emph{x} 的最低有效比特位的值，使得大于 @emph{x} 的第一个浮点数为 @code{x + ulp(x)}。
@end itemize

ULP 即 "Unit in the Last Place" 的缩写。

另请参阅 @ref{1c1,,math.nextafter()} 和 @ref{1145,,sys.float_info.epsilon}。


3.9 新版功能.

@end deffn

注意 @ref{1bc3,,frexp()} 和 @ref{1bc5,,modf()} 具有与它们的C等价函数不同的调用/返回模式：它们采用单个参数并返回一对值，而不是通过 '输出形参' 返回它们的第二个返回参数（Python中没有这样的东西）。

对于 @ref{dfb,,ceil()} ， @ref{dfa,,floor()} 和 @ref{1bc5,,modf()} 函数，请注意 @emph{所有} 足够大的浮点数都是精确整数。Python浮点数通常不超过53位的精度（与平台C double类型相同），在这种情况下，任何浮点 @emph{x} 与 @code{abs(x) >= 2**52} 必然没有小数位。

@node 幂函数与对数函数,三角函数,数论与表示函数,math --- 数学函数
@anchor{library/math power-and-logarithmic-functions}@anchor{1bc6}
@subsubsection 幂函数与对数函数


@geindex exp() (在 math 模块中)
@anchor{library/math math exp}@anchor{d79}
@deffn {函数} math.exp (x)

返回 @emph{e} 次 @emph{x} 幂，其中 @emph{e} = 2.718281... 是自然对数的基数。这通常比 @code{math.e ** x} 或 @code{pow(math.e, x)} 更精确。
@end deffn

@geindex expm1() (在 math 模块中)
@anchor{library/math math expm1}@anchor{c43}
@deffn {函数} math.expm1 (x)

返回 @emph{e} 的 @emph{x} 次幂，减1。这里 @emph{e} 是自然对数的基数。对于小浮点数 @emph{x} ， @code{exp(x) - 1} 中的减法可能导致 significant loss of precision@footnote{https://en.wikipedia.org/wiki/Loss_of_significance}； @ref{c43,,expm1()} 函数提供了一种将此数量计算为全精度的方法:

@example
>>> from math import exp, expm1
>>> exp(1e-5) - 1  # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5)    # result accurate to full precision
1.0000050000166668e-05
@end example


3.2 新版功能.

@end deffn

@geindex log() (在 math 模块中)
@anchor{library/math math log}@anchor{edb}
@deffn {函数} math.log (x[, base])

使用一个参数，返回 @emph{x} 的自然对数（底为 @emph{e} ）。

使用两个参数，返回给定的 @emph{base} 的对数 @emph{x} ，计算为 @code{log(x)/log(base)} 。
@end deffn

@geindex log1p() (在 math 模块中)
@anchor{library/math math log1p}@anchor{e10}
@deffn {函数} math.log1p (x)

返回 @emph{1+x} 的自然对数（以 @emph{e} 为底）。 以对于接近零的 @emph{x} 精确的方式计算结果。
@end deffn

@geindex log2() (在 math 模块中)
@anchor{library/math math log2}@anchor{b06}
@deffn {函数} math.log2 (x)

返回 @emph{x} 以2为底的对数。这通常比 @code{log(x, 2)} 更准确。


3.3 新版功能.



@subsubheading 参见


@ref{1783,,int.bit_length()} 返回表示二进制整数所需的位数，不包括符号和前导零。

@end deffn

@geindex log10() (在 math 模块中)
@anchor{library/math math log10}@anchor{1bc7}
@deffn {函数} math.log10 (x)

返回 @emph{x} 底为10的对数。这通常比 @code{log(x, 10)} 更准确。
@end deffn

@geindex pow() (在 math 模块中)
@anchor{library/math math pow}@anchor{1bc8}
@deffn {函数} math.pow (x, y)

将返回 @code{x} 的 @code{y} 次幂。特殊情况尽可能遵循C99标准的附录'F'。特别是， @code{pow(1.0, x)} 和 @code{pow(x, 0.0)} 总是返回 @code{1.0} ，即使 @code{x} 是零或NaN。 如果 @code{x} 和 @code{y} 都是有限的， @code{x} 是负数， @code{y} 不是整数那么 @code{pow(x, y)} 是未定义的，并且引发 @ref{16d,,ValueError} 。

与内置的 @code{**} 运算符不同， @ref{1bc8,,math.pow()} 将其参数转换为 @ref{1fe,,float} 类型。使用 @code{**} 或内置的 @ref{2d6,,pow()} 函数来计算精确的整数幂。
@end deffn

@geindex sqrt() (在 math 模块中)
@anchor{library/math math sqrt}@anchor{321}
@deffn {函数} math.sqrt (x)

返回 @emph{x} 的平方根。
@end deffn

@node 三角函数,角度转换,幂函数与对数函数,math --- 数学函数
@anchor{library/math trigonometric-functions}@anchor{1bc9}
@subsubsection 三角函数


@geindex acos() (在 math 模块中)
@anchor{library/math math acos}@anchor{1bca}
@deffn {函数} math.acos (x)

返回以弧度为单位的 @emph{x} 的反余弦值。 结果范围在 @code{0} 到 @code{pi} 之间。
@end deffn

@geindex asin() (在 math 模块中)
@anchor{library/math math asin}@anchor{1bcb}
@deffn {函数} math.asin (x)

返回以弧度为单位的 @emph{x} 的反正弦值。 结果范围在 @code{-pi/2} 到 @code{pi/2} 之间。
@end deffn

@geindex atan() (在 math 模块中)
@anchor{library/math math atan}@anchor{1bcc}
@deffn {函数} math.atan (x)

返回以弧度为单位的 @emph{x} 的反正切值。 结果范围在 @code{-pi/2} 到 @code{pi/2} 之间。.
@end deffn

@geindex atan2() (在 math 模块中)
@anchor{library/math math atan2}@anchor{1bcd}
@deffn {函数} math.atan2 (y, x)

以弧度为单位返回 @code{atan(y / x)} 。结果是在 @code{-pi} 和 @code{pi} 之间。从原点到点 @code{(x, y)}  的平面矢量使该角度与正X轴成正比。 @ref{1bcd,,atan2()} 的点的两个输入的符号都是已知的，因此它可以计算角度的正确象限。 例如， @code{atan(1)} 和 @code{atan2(1, 1)}  都是 @code{pi/4} ，但 @code{atan2(-1, -1)} 是 @code{-3*pi/4} 。
@end deffn

@geindex cos() (在 math 模块中)
@anchor{library/math math cos}@anchor{eda}
@deffn {函数} math.cos (x)

返回 @emph{x} 弧度的余弦值。
@end deffn

@geindex dist() (在 math 模块中)
@anchor{library/math math dist}@anchor{31a}
@deffn {函数} math.dist (p, q)

返回 @emph{p} 与 @emph{q} 两点之间的欧几里得距离，以一个坐标序列（或可迭代对象）的形式给出。 两个点必须具有相同的维度。

大致相当于：

@example
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
@end example


3.8 新版功能.

@end deffn

@geindex hypot() (在 math 模块中)
@anchor{library/math math hypot}@anchor{31b}
@deffn {函数} math.hypot (*coordinates)

返回欧几里得范数，@code{sqrt(sum(x**2 for x in coordinates))}。 这是从原点到坐标给定点的向量长度。

对于一个二维点 @code{(x, y)}，这等价于使用毕达哥拉斯定义 @code{sqrt(x*x + y*y)} 计算一个直角三角形的斜边。


在 3.8 版更改: 添加了对 n 维点的支持。 之前的版本只支持二维点。

@end deffn

@geindex sin() (在 math 模块中)
@anchor{library/math math sin}@anchor{ed9}
@deffn {函数} math.sin (x)

返回 @emph{x} 弧度的正弦值。
@end deffn

@geindex tan() (在 math 模块中)
@anchor{library/math math tan}@anchor{1bce}
@deffn {函数} math.tan (x)

返回 @emph{x} 弧度的正切值。
@end deffn

@node 角度转换,双曲函数,三角函数,math --- 数学函数
@anchor{library/math angular-conversion}@anchor{1bcf}
@subsubsection 角度转换


@geindex degrees() (在 math 模块中)
@anchor{library/math math degrees}@anchor{1bd0}
@deffn {函数} math.degrees (x)

将角度 @emph{x} 从弧度转换为度数。
@end deffn

@geindex radians() (在 math 模块中)
@anchor{library/math math radians}@anchor{1bd1}
@deffn {函数} math.radians (x)

将角度 @emph{x} 从度数转换为弧度。
@end deffn

@node 双曲函数,特殊函数,角度转换,math --- 数学函数
@anchor{library/math hyperbolic-functions}@anchor{1bd2}
@subsubsection 双曲函数


双曲函数@footnote{https://en.wikipedia.org/wiki/Hyperbolic_function} 是基于双曲线而非圆来对三角函数进行模拟。

@geindex acosh() (在 math 模块中)
@anchor{library/math math acosh}@anchor{e0d}
@deffn {函数} math.acosh (x)

返回 @emph{x} 的反双曲余弦值。
@end deffn

@geindex asinh() (在 math 模块中)
@anchor{library/math math asinh}@anchor{e0e}
@deffn {函数} math.asinh (x)

返回 @emph{x} 的反双曲正弦值。
@end deffn

@geindex atanh() (在 math 模块中)
@anchor{library/math math atanh}@anchor{e0f}
@deffn {函数} math.atanh (x)

返回 @emph{x} 的反双曲正切值。
@end deffn

@geindex cosh() (在 math 模块中)
@anchor{library/math math cosh}@anchor{1bd3}
@deffn {函数} math.cosh (x)

返回 @emph{x} 的双曲余弦值。
@end deffn

@geindex sinh() (在 math 模块中)
@anchor{library/math math sinh}@anchor{1bd4}
@deffn {函数} math.sinh (x)

返回 @emph{x} 的双曲正弦值。
@end deffn

@geindex tanh() (在 math 模块中)
@anchor{library/math math tanh}@anchor{1bd5}
@deffn {函数} math.tanh (x)

返回 @emph{x} 的双曲正切值。
@end deffn

@node 特殊函数,常数,双曲函数,math --- 数学函数
@anchor{library/math special-functions}@anchor{1bd6}
@subsubsection 特殊函数


@geindex erf() (在 math 模块中)
@anchor{library/math math erf}@anchor{55c}
@deffn {函数} math.erf (x)

返回 @emph{x} 处的 error function@footnote{https://en.wikipedia.org/wiki/Error_function} 。

@ref{55c,,erf()} 函数可用于计算传统的统计函数，如 累积标准正态分布@footnote{https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function}

@example
def phi(x):
    'Cumulative distribution function for the standard normal distribution'
    return (1.0 + erf(x / sqrt(2.0))) / 2.0
@end example


3.2 新版功能.

@end deffn

@geindex erfc() (在 math 模块中)
@anchor{library/math math erfc}@anchor{55d}
@deffn {函数} math.erfc (x)

返回 @emph{x} 处的互补误差函数。 互补错误函数@footnote{https://en.wikipedia.org/wiki/Error_function} 定义为 @code{1.0 - erf(x)}。 它用于 @emph{x} 的大值，从其中减去一个会导致 有效位数损失@footnote{https://en.wikipedia.org/wiki/Loss_of_significance}。


3.2 新版功能.

@end deffn

@geindex gamma() (在 math 模块中)
@anchor{library/math math gamma}@anchor{c44}
@deffn {函数} math.gamma (x)

返回 @emph{x} 处的 伽马函数@footnote{https://en.wikipedia.org/wiki/Gamma_function} 值。


3.2 新版功能.

@end deffn

@geindex lgamma() (在 math 模块中)
@anchor{library/math math lgamma}@anchor{c45}
@deffn {函数} math.lgamma (x)

返回Gamma函数在 @emph{x} 绝对值的自然对数。


3.2 新版功能.

@end deffn

@node 常数,,特殊函数,math --- 数学函数
@anchor{library/math constants}@anchor{1bd7}
@subsubsection 常数


@geindex pi() (在 math 模块中)
@anchor{library/math math pi}@anchor{1bd8}
@deffn {数据} math.pi

数学常数 @emph{π} = 3.141592...，精确到可用精度。
@end deffn

@geindex e() (在 math 模块中)
@anchor{library/math math e}@anchor{1bd9}
@deffn {数据} math.e

数学常数 @emph{e} = 2.718281...，精确到可用精度。
@end deffn

@geindex tau() (在 math 模块中)
@anchor{library/math math tau}@anchor{1bda}
@deffn {数据} math.tau

数学常数 @emph{τ} = 6.283185...，精确到可用精度。Tau 是一个圆周常数，等于 2@emph{π}，圆的周长与半径之比。更多关于 Tau 的信息可参考 Vi Hart 的视频 Pi is (still) Wrong@footnote{https://www.youtube.com/watch?v=jG7vhMMXagQ}。吃两倍多的派来庆祝 Tau 日@footnote{https://tauday.com/} 吧！


3.6 新版功能.

@end deffn

@geindex inf() (在 math 模块中)
@anchor{library/math math inf}@anchor{62a}
@deffn {数据} math.inf

浮点正无穷大。 （对于负无穷大，使用 @code{-math.inf} 。）相当于 @code{float('inf')} 的输出。


3.5 新版功能.

@end deffn

@geindex nan() (在 math 模块中)
@anchor{library/math math nan}@anchor{62b}
@deffn {数据} math.nan

一个浮点的 "非数字"（NaN）值。相当于 @code{float('nan')} 的输出。 由于 IEEE-754标准@footnote{https://en.wikipedia.org/wiki/IEEE_754} 的要求， @code{math.nan} 和 @code{float('nan')} 不被认为等于任何其他数值，包括其本身。要检查一个数字是否为NaN，请使用 @ref{e0a,,isnan()} 函数来测试 NaN ，而不是 @code{is} 或 @code{==}  。 例子:

@example
>>> import math
>>> math.nan == math.nan
False
>>> float('nan') == float('nan')
False
>>> math.isnan(math.nan)
True
>>> math.isnan(float('nan'))
True
@end example


3.5 新版功能.

@end deffn

@strong{CPython implementation detail:} @ref{b1,,math} 模块主要包含围绕平台C数学库函数的简单包装器。特殊情况下的行为在适当情况下遵循C99标准的附录F。当前的实现将引发 @ref{16d,,ValueError} 用于无效操作，如 @code{sqrt(-1.0)} 或 @code{log(0.0)} （其中C99附件F建议发出无效操作信号或被零除）， 和 @ref{a4a,,OverflowError} 用于溢出的结果（例如， @code{exp(1000.0)} ）。除非一个或多个输入参数是NaN，否则不会从上述任何函数返回NaN；在这种情况下，大多数函数将返回一个NaN，但是（再次遵循C99附件F）这个规则有一些例外，例如 @code{pow(float('nan'), 0.0)} 或 @code{hypot(float('nan'), float('inf'))} 。

请注意，Python不会将显式NaN与静默NaN区分开来，并且显式NaN的行为仍未明确。典型的行为是将所有NaN视为静默的。


@subsubheading 参见



@table @asis

@item @ref{18,,cmath} 模块

这里很多函数的复数版本。
@end table


@node cmath --- 关于复数的数学函数,decimal --- 十进制定点和浮点运算,math --- 数学函数,数字和数学模块
@anchor{library/cmath doc}@anchor{1bdb}@anchor{library/cmath cmath-mathematical-functions-for-complex-numbers}@anchor{1bdc}@anchor{library/cmath module-cmath}@anchor{18}
@subsection @code{cmath} --- 关于复数的数学函数


@geindex cmath (模块)


__________________________________________________________________


这一模块提供了一些关于复数的数学函数。 该模块的函数的参数为整数、浮点数或复数。 这些函数的参数也可为一个拥有 @ref{2cc,,__complex__()} 或 @ref{2cb,,__float__()} 方法的 Python 对象，这些方法分别用于将对象转换为复数和浮点数，这些函数作用于转换后的结果。

@cartouche
@quotation 注解 
在具有对于有符号零的硬件和系统级支持的平台上，涉及支割线的函数在支割线的 @emph{两侧} 都是连续的：零的符号可用来区别支割线的一侧和另一侧。 在不支持有符号零的平台上，连续性的规则见下文。
@end quotation
@end cartouche

@menu
* 到极坐标和从极坐标的转换:: 
* 幂函数与对数函数: 幂函数与对数函数<2>. 
* 三角函数: 三角函数<2>. 
* 双曲函数: 双曲函数<2>. 
* 分类函数:: 
* 常数: 常数<2>. 

@end menu

@node 到极坐标和从极坐标的转换,幂函数与对数函数<2>,,cmath --- 关于复数的数学函数
@anchor{library/cmath conversions-to-and-from-polar-coordinates}@anchor{1bdd}
@subsubsection 到极坐标和从极坐标的转换


使用 @emph{矩形坐标} 或 @emph{笛卡尔坐标} 在内部存储 Python 复数 @code{z}。 这完全取决于它的 @emph{实部} @code{z.real} 和 @emph{虚部} @code{z.imag}。 换句话说:

@example
z == z.real + z.imag*1j
@end example

@emph{极坐标} 提供了另一种复数的表示方法。在极坐标中，一个复数 @emph{z} 由模量 @emph{r} 和相位角 @emph{phi} 来定义。模量 @emph{r} 是从 @emph{z} 到坐标原点的距离，而相位角 @emph{phi} 是以弧度为单位的，逆时针的，从正X轴到连接原点和 @emph{z} 的线段间夹角的角度。

下面的函数可用于原生直角坐标与极坐标的相互转换。

@geindex phase() (在 cmath 模块中)
@anchor{library/cmath cmath phase}@anchor{1bde}
@deffn {函数} cmath.phase (x)

将 @emph{x} 的相位 (也称为 @emph{x} 的 @emph{参数}) 返回为一个浮点数。@code{phase(x)} 相当于 @code{math.atan2(x.imag, x.real)}。 结果处于 [-@emph{π}, @emph{π}] 之间，以及这个操作的分支切断处于负实轴上，从上方连续。 在支持有符号零的系统上（这包涵大多数当前的常用系统），这意味着结果的符号与 @code{x.imag} 的符号相同，即使 @code{x.imag} 的值是 0:

@example
>>> phase(complex(-1.0, 0.0))
3.141592653589793
>>> phase(complex(-1.0, -0.0))
-3.141592653589793
@end example
@end deffn

@cartouche
@quotation 注解 
一个复数 @emph{x} 的模数（绝对值）可以通过内置函数 @ref{1424,,abs()} 计算。没有单独的 @ref{18,,cmath} 模块函数用于这个操作。
@end quotation
@end cartouche

@geindex polar() (在 cmath 模块中)
@anchor{library/cmath cmath polar}@anchor{1bdf}
@deffn {函数} cmath.polar (x)

在极坐标中返回 @emph{x} 的表达方式。返回一个数对 @code{(r, phi)}，@emph{r} 是 @emph{x} 的模数，@emph{phi} 是 @emph{x} 的相位角。 @code{polar(x)} 相当于 @code{(abs(x), phase(x))}。
@end deffn

@geindex rect() (在 cmath 模块中)
@anchor{library/cmath cmath rect}@anchor{1be0}
@deffn {函数} cmath.rect (r, phi)

通过极坐标的 @emph{r} 和 @emph{phi} 返回复数 @emph{x}。相当于 @code{r * (math.cos(phi) + math.sin(phi)*1j)}。
@end deffn

@node 幂函数与对数函数<2>,三角函数<2>,到极坐标和从极坐标的转换,cmath --- 关于复数的数学函数
@anchor{library/cmath power-and-logarithmic-functions}@anchor{1be1}
@subsubsection 幂函数与对数函数


@geindex exp() (在 cmath 模块中)
@anchor{library/cmath cmath exp}@anchor{1be2}
@deffn {函数} cmath.exp (x)

返回 @emph{e} 的 @emph{x} 次方，@emph{e} 是自然对数的底数。
@end deffn

@geindex log() (在 cmath 模块中)
@anchor{library/cmath cmath log}@anchor{1be3}
@deffn {函数} cmath.log (x[, base])

返回给定 @emph{base} 的 @emph{x} 的对数。如果没有给定 @emph{base}，返回 @emph{x} 的自然对数。 从 0 到 -∞ 存在一条支割线，沿负实轴之上连续。
@end deffn

@geindex log10() (在 cmath 模块中)
@anchor{library/cmath cmath log10}@anchor{1be4}
@deffn {函数} cmath.log10 (x)

返回底数为 10 的 @emph{x} 的对数。它具有与 @ref{1be3,,log()} 相同的支割线。
@end deffn

@geindex sqrt() (在 cmath 模块中)
@anchor{library/cmath cmath sqrt}@anchor{1be5}
@deffn {函数} cmath.sqrt (x)

返回 @emph{x} 的平方根。 它具有与 @ref{1be3,,log()} 相同的支割线。
@end deffn

@node 三角函数<2>,双曲函数<2>,幂函数与对数函数<2>,cmath --- 关于复数的数学函数
@anchor{library/cmath trigonometric-functions}@anchor{1be6}
@subsubsection 三角函数


@geindex acos() (在 cmath 模块中)
@anchor{library/cmath cmath acos}@anchor{1be7}
@deffn {函数} cmath.acos (x)

返回 @emph{x} 的反余弦。这里有两条支割线：一条沿着实轴从 1 向右延伸到 ∞，从下面连续延伸。另外一条沿着实轴从 -1 向左延伸到 -∞，从上面连续延伸。
@end deffn

@geindex asin() (在 cmath 模块中)
@anchor{library/cmath cmath asin}@anchor{1be8}
@deffn {函数} cmath.asin (x)

返回 @emph{x} 的反正弦。它与 @ref{1be7,,acos()} 有相同的支割线。
@end deffn

@geindex atan() (在 cmath 模块中)
@anchor{library/cmath cmath atan}@anchor{1be9}
@deffn {函数} cmath.atan (x)

返回 @emph{x} 的反正切。它具有两条支割线：一条沿着虚轴从 @code{1j}  延伸到 @code{∞j}，向右持续延伸。另一条是沿着虚轴从 @code{-1j} 延伸到 @code{-∞j} ，向左持续延伸。
@end deffn

@geindex cos() (在 cmath 模块中)
@anchor{library/cmath cmath cos}@anchor{1bea}
@deffn {函数} cmath.cos (x)

返回 @emph{x} 的余弦。
@end deffn

@geindex sin() (在 cmath 模块中)
@anchor{library/cmath cmath sin}@anchor{1beb}
@deffn {函数} cmath.sin (x)

返回 @emph{x} 的正弦。
@end deffn

@geindex tan() (在 cmath 模块中)
@anchor{library/cmath cmath tan}@anchor{1bec}
@deffn {函数} cmath.tan (x)

返回 @emph{x} 的正切。
@end deffn

@node 双曲函数<2>,分类函数,三角函数<2>,cmath --- 关于复数的数学函数
@anchor{library/cmath hyperbolic-functions}@anchor{1bed}
@subsubsection 双曲函数


@geindex acosh() (在 cmath 模块中)
@anchor{library/cmath cmath acosh}@anchor{1bee}
@deffn {函数} cmath.acosh (x)

返回 @emph{x} 的反双曲余弦。它有一条支割线沿着实轴从 1 到  -∞ 向左延伸，从上方持续延伸。
@end deffn

@geindex asinh() (在 cmath 模块中)
@anchor{library/cmath cmath asinh}@anchor{1bef}
@deffn {函数} cmath.asinh (x)

返回 @emph{x} 的反双曲正弦。它有两条支割线：一条沿着虚轴从 @code{1j} 向右持续延伸到 @code{∞j}。另一条是沿着虚轴从 @code{-1j} 向左持续延伸到 @code{-∞j}。
@end deffn

@geindex atanh() (在 cmath 模块中)
@anchor{library/cmath cmath atanh}@anchor{1bf0}
@deffn {函数} cmath.atanh (x)

返回 @emph{x} 的反双曲正切。它有两条支割线：一条是沿着实轴从 @code{1} 延展到 @code{∞}，从下面持续延展。另一条是沿着实轴从 @code{-1} 延展到 @code{-∞}，从上面持续延展。
@end deffn

@geindex cosh() (在 cmath 模块中)
@anchor{library/cmath cmath cosh}@anchor{1bf1}
@deffn {函数} cmath.cosh (x)

返回 @emph{x} 的双曲余弦值。
@end deffn

@geindex sinh() (在 cmath 模块中)
@anchor{library/cmath cmath sinh}@anchor{1bf2}
@deffn {函数} cmath.sinh (x)

返回 @emph{x} 的双曲正弦值。
@end deffn

@geindex tanh() (在 cmath 模块中)
@anchor{library/cmath cmath tanh}@anchor{1bf3}
@deffn {函数} cmath.tanh (x)

返回 @emph{x} 的双曲正切值。
@end deffn

@node 分类函数,常数<2>,双曲函数<2>,cmath --- 关于复数的数学函数
@anchor{library/cmath classification-functions}@anchor{1bf4}
@subsubsection 分类函数


@geindex isfinite() (在 cmath 模块中)
@anchor{library/cmath cmath isfinite}@anchor{1bf5}
@deffn {函数} cmath.isfinite (x)

如果 @emph{x} 的实部和虚部都是有限的，则返回 @code{True}，否则返回 @code{False}。


3.2 新版功能.

@end deffn

@geindex isinf() (在 cmath 模块中)
@anchor{library/cmath cmath isinf}@anchor{1bf6}
@deffn {函数} cmath.isinf (x)

如果 @emph{x} 的实部或者虚部是无穷大的，则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex isnan() (在 cmath 模块中)
@anchor{library/cmath cmath isnan}@anchor{1bf7}
@deffn {函数} cmath.isnan (x)

如果 @emph{x} 的实部或者虚部是 NaN，则返回 @code{True} ，否则返回 @code{False}。
@end deffn

@geindex isclose() (在 cmath 模块中)
@anchor{library/cmath cmath isclose}@anchor{784}
@deffn {函数} cmath.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

若 @emph{a} 和 @emph{b} 的值比较接近则返回 @code{True}，否则返回 @code{False}。

根据给定的绝对和相对容差确定两个值是否被认为是接近的。

@emph{rel_tol} 是相对容差 —— 它是 @emph{a} 和 @emph{b} 之间允许的最大差值，相对于 @emph{a} 或 @emph{b} 的较大绝对值。例如，要设置5％的容差，请传递 @code{rel_tol=0.05} 。默认容差为 @code{1e-09}，确保两个值在大约9位十进制数字内相同。 @emph{rel_tol} 必须大于零。

@emph{abs_tol} 是最小绝对容差 —— 对于接近零的比较很有用。 @emph{abs_tol} 必须至少为零。

如果没有错误发生，结果将是： @code{abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)} 。

IEEE 754特殊值 @code{NaN} ， @code{inf} 和` @cite{-inf`} 将根据IEEE规则处理。具体来说， @code{NaN} 不被认为接近任何其他值，包括 @code{NaN} 。 @code{inf} 和 @code{-inf} 只被认为接近自己。


3.5 新版功能.



@subsubheading 参见


@geindex Python 提高建议; PEP 485
PEP 485@footnote{https://www.python.org/dev/peps/pep-0485} —— 用于测试近似相等的函数

@end deffn

@node 常数<2>,,分类函数,cmath --- 关于复数的数学函数
@anchor{library/cmath constants}@anchor{1bf8}
@subsubsection 常数


@geindex pi() (在 cmath 模块中)
@anchor{library/cmath cmath pi}@anchor{1bf9}
@deffn {数据} cmath.pi

数学常数 @emph{π} ，作为一个浮点数。
@end deffn

@geindex e() (在 cmath 模块中)
@anchor{library/cmath cmath e}@anchor{1bfa}
@deffn {数据} cmath.e

数学常数 @emph{e} ，作为一个浮点数。
@end deffn

@geindex tau() (在 cmath 模块中)
@anchor{library/cmath cmath tau}@anchor{627}
@deffn {数据} cmath.tau

数学常数 @emph{τ} ，作为一个浮点数。


3.6 新版功能.

@end deffn

@geindex inf() (在 cmath 模块中)
@anchor{library/cmath cmath inf}@anchor{628}
@deffn {数据} cmath.inf

浮点正无穷大。相当于 @code{float('inf')}。


3.6 新版功能.

@end deffn

@geindex infj() (在 cmath 模块中)
@anchor{library/cmath cmath infj}@anchor{62c}
@deffn {数据} cmath.infj

具有零实部和正无穷虚部的复数。相当于 @code{complex(0.0, float('inf'))}。


3.6 新版功能.

@end deffn

@geindex nan() (在 cmath 模块中)
@anchor{library/cmath cmath nan}@anchor{629}
@deffn {数据} cmath.nan

浮点“非数字”（NaN）值。相当于 @code{float('nan')}。


3.6 新版功能.

@end deffn

@geindex nanj() (在 cmath 模块中)
@anchor{library/cmath cmath nanj}@anchor{62d}
@deffn {数据} cmath.nanj

具有零实部和 NaN 虚部的复数。相当于 @code{complex(0.0, float('nan'))}。


3.6 新版功能.

@end deffn

@geindex 模块; math

请注意，函数的选择与模块 @ref{b1,,math} 中的函数选择相似，但不完全相同。 拥有两个模块的原因是因为有些用户对复数不感兴趣，甚至根本不知道它们是什么。它们宁愿 @code{math.sqrt(-1)} 引发异常，也不想返回一个复数。 另请注意，被 @ref{18,,cmath} 定义的函数始终会返回一个复数，尽管答案可以表示为一个实数（在这种情况下，复数的虚数部分为零）。

关于支割线的注释：它们是沿着给定函数无法连续的曲线。它们是许多复变函数的必要特征。 假设您需要使用复变函数进行计算，您将会了解支割线的概念。 请参阅几乎所有关于复变函数的（不太基本）的书来获得启发。 对于如何正确地基于数值目的来选择支割线的相关信息，一个良好的参考如下：


@subsubheading 参见


Kahan, W: Branch cuts for complex elementary functions; or, Much ado about nothing's sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165--211.


@node decimal --- 十进制定点和浮点运算,fractions --- 分数,cmath --- 关于复数的数学函数,数字和数学模块
@anchor{library/decimal doc}@anchor{1bfb}@anchor{library/decimal decimal-decimal-fixed-point-and-floating-point-arithmetic}@anchor{1bfc}@anchor{library/decimal module-decimal}@anchor{35}
@subsection @code{decimal} --- 十进制定点和浮点运算


@geindex decimal (模块)

@strong{源码：} Lib/decimal.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/decimal.py}

@c import modules for testing inline doctests with the Sphinx doctest builder

@c import decimal
@c import math
@c from decimal import *
@c # make sure each group gets a fresh context
@c setcontext(Context())

@c # make sure other tests (outside this file) get a fresh context
@c setcontext(Context())


__________________________________________________________________


@ref{35,,decimal} 模块为快速正确舍入的十进制浮点运算提供支持。 与 @ref{1fe,,float} 数据类型相比，它具有以下几个优点：


@itemize *

@item 
Decimal “基于一个浮点模型，它是为人们设计的，并且必然具有最重要的指导原则 —— 计算机必须提供与人们在学校学习的算法相同的算法。” —— 摘自十进制算术规范。

@item 
Decimal 数字的表示是完全精确的。 相比之下，@code{1.1} 和 @code{2.2} 这样的数字在二进制浮点中没有精确的表示。 最终用户通常不希望 @code{1.1 + 2.2} 如二进制浮点数表示那样被显示为 @code{3.3000000000000003}。

@item 
精确性延续到算术中。 在十进制浮点数中，@code{0.1 + 0.1 + 0.1 - 0.3} 恰好等于零。 在二进制浮点数中，结果为 @code{5.5511151231257827e-017} 。 虽然接近于零，但差异妨碍了可靠的相等性检验，并且差异可能会累积。 因此，在具有严格相等不变量的会计应用程序中， decimal 是首选。

@item 
十进制模块包含有效位的概念，因此 @code{1.30 + 1.20} 的结果是 @code{2.50} 。 保留尾随零以表示有效位。 这是货币的惯用表示方法。乘法则沿用 “教科书“ 中：保留被乘数中的所有数字的方法。 例如， @code{1.3 * 1.2} 结果是 @code{1.56} 而 @code{1.30 * 1.20} 结果是 @code{1.5600} 。

@item 
与基于硬件的二进制浮点不同，十进制模块具有用户可更改的精度（默认为28位），可以与给定问题所需的一样大：

@example
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
@end example

@item 
二进制和十进制浮点都是根据已发布的标准实现的。 虽然内置浮点类型只公开其功能的一小部分，但十进制模块公开了标准的所有必需部分。 在需要时，程序员可以完全控制舍入和信号处理。 这包括通过使用异常来阻止任何不精确操作来强制执行精确算术的选项。

@item 
十进制模块旨在支持“无偏见，精确的非连续十进制算术（有时称为定点算术）和舍入浮点算术”。 —— 摘自十进制算术规范。
@end itemize

模块设计以三个概念为中心：十进制数，算术上下文和信号。

十进制数是不可变的。 它有一个符号，系数数字和一个指数。 为了保持重要性，系数数字不会截断尾随零。十进制数也包括特殊值，例如 @code{Infinity} ，@code{-Infinity} ，和 @code{NaN} 。 该标准还区分 @code{-0} 和 @code{+0} 。

算术的上下文是指定精度、舍入规则、指数限制、指示操作结果的标志以及确定符号是否被视为异常的陷阱启用器的环境。 舍入选项包括 @ref{1bfd,,ROUND_CEILING} 、 @ref{1bfe,,ROUND_DOWN} 、 @ref{1bff,,ROUND_FLOOR} 、 @ref{1c00,,ROUND_HALF_DOWN}, @ref{1c01,,ROUND_HALF_EVEN} 、 @ref{1c02,,ROUND_HALF_UP} 、 @ref{1c03,,ROUND_UP} 以及 @ref{1c04,,ROUND_05UP}.

信号是在计算过程中出现的异常条件组。 根据应用程序的需要，信号可能会被忽略，被视为信息，或被视为异常。 十进制模块中的信号有：@ref{1c05,,Clamped} 、 @ref{ad3,,InvalidOperation} 、 @ref{1c06,,DivisionByZero} 、 @ref{1c07,,Inexact} 、 @ref{1c08,,Rounded} 、 @ref{1c09,,Subnormal} 、 @ref{1c0a,,Overflow} 、 @ref{1c0b,,Underflow} 以及 @ref{acd,,FloatOperation} 。

对于每个信号，都有一个标志和一个陷阱启动器。 遇到信号时，其标志设置为 1 ，然后，如果陷阱启用器设置为 1 ，则引发异常。 标志是粘性的，因此用户需要在监控计算之前重置它们。


@subsubheading 参见



@itemize *

@item 
IBM的通用十进制算术规范， The General Decimal Arithmetic Specification@footnote{http://speleotrove.com/decimal/decarith.html}.
@end itemize


@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@menu
* 快速入门教程:: 
* Decimal 对象:: 
* 上下文对象:: 
* 常数: 常数<3>. 
* 舍入模式:: 
* 信号:: 
* 浮点数说明:: 
* 使用线程:: 
* 例程:: 
* Decimal 常见问题:: 

@end menu

@node 快速入门教程,Decimal 对象,,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-tutorial}@anchor{1c0c}@anchor{library/decimal quick-start-tutorial}@anchor{1c0d}
@subsubsection 快速入门教程


通常使用小数的开始是导入模块，使用 @ref{1c0e,,getcontext()} 查看当前上下文，并在必要时为精度、舍入或启用的陷阱设置新值:

@example
>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
        InvalidOperation])

>>> getcontext().prec = 7       # Set a new precision
@end example

可以从整数、字符串、浮点数或元组构造十进制实例。 从整数或浮点构造将执行该整数或浮点值的精确转换。 十进制数包括特殊值，例如 @code{NaN} 代表“非数字”，正的和负的 @code{Infinity}，和 @code{-0}

@example
>>> getcontext().prec = 28
>>> Decimal(10)
Decimal('10')
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal((0, (3, 1, 4), -2))
Decimal('3.14')
>>> Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951')
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724')
>>> Decimal('NaN')
Decimal('NaN')
>>> Decimal('-Infinity')
Decimal('-Infinity')
@end example

如果 @ref{acd,,FloatOperation} 信号被捕获，构造函数中的小数和浮点数的意外混合或排序比较会引发异常

@example
>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') == 3.5
True
@end example


3.3 新版功能.


新 Decimal 的重要性仅由输入的位数决定。 上下文精度和舍入仅在算术运算期间发挥作用。

@example
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
@end example

如果超出了C版本的内部限制，则构造一个十进制将引发 @ref{ad3,,InvalidOperation}

@example
>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
@end example


在 3.3 版更改.


小数与 Python 的其余部分很好地交互。 这是一个小的十进制浮点飞行杂技团：

@example
>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')
@end example

Decimal 也可以使用一些数学函数：

@example
>>> getcontext().prec = 28
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal('10').ln()
Decimal('2.302585092994045684017991455')
>>> Decimal('10').log10()
Decimal('1')
@end example

@code{quantize()} 方法将数字舍入为固定指数。 此方法对于将结果舍入到固定的位置的货币应用程序非常有用：

@example
>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')
@end example

如上所示，@ref{1c0e,,getcontext()} 函数访问当前上下文并允许更改设置。 这种方法满足大多数应用程序的需求。

对于更高级的工作，使用 Context() 构造函数创建备用上下文可能很有用。 要使用备用活动，请使用 @ref{1c0f,,setcontext()} 函数。

根据标准，@ref{35,,decimal} 模块提供了两个现成的标准上下文 @ref{ad1,,BasicContext} 和 @ref{ad2,,ExtendedContext} 。 前者对调试特别有用，因为许多陷阱都已启用：

@example
>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
>>> setcontext(myothercontext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')

>>> ExtendedContext
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[])
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857143')
>>> Decimal(42) / Decimal(0)
Decimal('Infinity')

>>> setcontext(BasicContext)
>>> Decimal(42) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#143>", line 1, in -toplevel-
    Decimal(42) / Decimal(0)
DivisionByZero: x / 0
@end example

上下文还具有用于监视计算期间遇到的异常情况的信号标志。 标志保持设置直到明确清除，因此最好通过使用 @code{clear_flags()} 方法清除每组受监控计算之前的标志。:

@example
>>> setcontext(ExtendedContext)
>>> getcontext().clear_flags()
>>> Decimal(355) / Decimal(113)
Decimal('3.14159292')
>>> getcontext()
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
@end example

@emph{flags} 条目显示对 @code{Pi} 的有理逼近被舍入（超出上下文精度的数字被抛弃）并且结果是不精确的（一些丢弃的数字不为零）。

使用上下文的 @code{traps} 字段中的字典设置单个陷阱：

@example
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(0)
Decimal('Infinity')
>>> getcontext().traps[DivisionByZero] = 1
>>> Decimal(1) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#112>", line 1, in -toplevel-
    Decimal(1) / Decimal(0)
DivisionByZero: x / 0
@end example

大多数程序仅在程序开始时调整当前上下文一次。 并且，在许多应用程序中，数据在循环内单个强制转换为 @ref{2c7,,Decimal} 。 通过创建上下文集和小数，程序的大部分操作数据与其他 Python 数字类型没有区别。

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Decimal 对象,上下文对象,快速入门教程,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-decimal}@anchor{1c10}@anchor{library/decimal decimal-objects}@anchor{1c11}
@subsubsection Decimal 对象


@geindex Decimal (decimal 中的类)
@anchor{library/decimal decimal Decimal}@anchor{2c7}
@deffn {类} decimal.Decimal (value="0", context=None)

根据 @emph{value} 构造一个新的 @ref{2c7,,Decimal} 对象。

@emph{value} 可以是整数，字符串，元组，@ref{1fe,,float} ，或另一个 @ref{2c7,,Decimal} 对象。 如果没有给出 @emph{value}，则返回 @code{Decimal('0')}。 如果 @emph{value} 是一个字符串，它应该在前导和尾随空格字符以及下划线被删除之后符合十进制数字字符串语法:

@example
sign           ::=  '+' | '-'
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator      ::=  'e' | 'E'
digits         ::=  digit [digit]...
decimal-part   ::=  digits '.' [digits] | ['.'] digits
exponent-part  ::=  indicator [sign] digits
infinity       ::=  'Infinity' | 'Inf'
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
numeric-value  ::=  decimal-part [exponent-part] | infinity
numeric-string ::=  [sign] numeric-value | [sign] nan
@end example

当上面出现 @code{digit} 时也允许其他十进制数码。 其中包括来自各种其他语言系统的十进制数码（例如阿拉伯-印地语和天城文的数码）以及全宽数码 @code{'\uff10'} 到 @code{'\uff19'}。

如果 @emph{value} 是一个 @ref{1a2,,tuple} ，它应该有三个组件，一个符号（ @code{0} 表示正数或 @code{1} 表示负数），一个数字的 @ref{1a2,,tuple} 和整数指数。 例如， @code{Decimal((0, (1, 4, 1, 4), -3))} 返回 @code{Decimal('1.414')}。

如果 @emph{value} 是 @ref{1fe,,float} ，则二进制浮点值无损地转换为其精确的十进制等效值。 此转换通常需要53位或更多位数的精度。 例如， @code{Decimal(float('1.1'))} 转换为`@w{`}Decimal('1.100000000000000088817841970012523233890533447265625')`@w{`}。

@emph{context} 精度不会影响存储的位数。 这完全由 @emph{value} 中的位数决定。 例如，@code{Decimal('3.00000')} 记录所有五个零，即使上下文精度只有三。

@emph{context} 参数的目的是确定 @emph{value} 是格式错误的字符串时该怎么做。 如果上下文陷阱 @ref{ad3,,InvalidOperation}，则引发异常；否则，构造函数返回一个新的 Decimal，其值为 @code{NaN}。

构造完成后， @ref{2c7,,Decimal} 对象是不可变的。


在 3.2 版更改: 现在允许构造函数的参数为 @ref{1fe,,float} 实例。



在 3.3 版更改: @ref{1fe,,float} 参数在设置 @ref{acd,,FloatOperation} 陷阱时引发异常。 默认情况下，陷阱已关闭。



在 3.6 版更改: 允许下划线进行分组，就像代码中的整数和浮点文字一样。


十进制浮点对象与其他内置数值类型共享许多属性，例如 @ref{1fe,,float} 和 @ref{205,,int} 。 所有常用的数学运算和特殊方法都适用。 同样，十进制对象可以复制、pickle、打印、用作字典键、用作集合元素、比较、排序和强制转换为另一种类型（例如 @ref{1fe,,float} 或 @ref{205,,int} ）。

算术对十进制对象和算术对整数和浮点数有一些小的差别。 当余数运算符 @code{%} 应用于Decimal对象时，结果的符号是 @emph{被除数} 的符号，而不是除数的符号:

@example
>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')
@end example

整数除法运算符 @code{//} 的行为类似，返回真商的整数部分（截断为零）而不是它的向下取整，以便保留通常的标识 @code{x == (x // y) * y + x % y}:

@example
>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')
@end example

@code{%} 和 @code{//} 运算符实现了 @code{remainder} 和 @code{divide-integer} 操作（分别），如规范中所述。

十进制对象通常不能与浮点数或 @ref{2c5,,fractions.Fraction} 实例在算术运算中结合使用：例如,尝试将 @ref{2c7,,Decimal} 加到 @ref{1fe,,float} ，将引发 @ref{1ff,,TypeError}。 但是，可以使用 Python 的比较运算符来比较 @ref{2c7,,Decimal} 实例 @code{x} 和另一个数字 @code{y} 。 这样可以避免在对不同类型的数字进行相等比较时混淆结果。


在 3.2 版更改: 现在完全支持 @ref{2c7,,Decimal} 实例和其他数字类型之间的混合类型比较。


除了标准的数字属性，十进制浮点对象还有许多专门的方法：

@geindex adjusted() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal adjusted}@anchor{1c12}
@deffn {方法} adjusted ()

在移出系数最右边的数字之后返回调整后的指数，直到只剩下前导数字：@code{Decimal('321e+5').adjusted()} 返回 7 。 用于确定最高有效位相对于小数点的位置。
@end deffn

@geindex as_integer_ratio() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal as_integer_ratio}@anchor{63e}
@deffn {方法} as_integer_ratio ()

返回一对 @code{(n, d)} 整数，表示给定的 @ref{2c7,,Decimal} 实例作为分数、最简形式项并带有正分母:

@example
>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)
@end example

转换是精确的。 在 Infinity 上引发 OverflowError ，在 NaN 上引起 ValueError 。
@end deffn


3.6 新版功能.


@geindex as_tuple() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal as_tuple}@anchor{1c13}
@deffn {方法} as_tuple ()

返回一个 @ref{b84,,named tuple} 表示的数字： @code{DecimalTuple(sign, digits, exponent)}。
@end deffn

@geindex canonical() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal canonical}@anchor{1c14}
@deffn {方法} canonical ()

返回参数的规范编码。 目前，一个 @ref{2c7,,Decimal} 实例的编码始终是规范的，因此该操作返回其参数不变。
@end deffn

@geindex compare() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal compare}@anchor{1c15}
@deffn {方法} compare (other, context=None)

比较两个 Decimal 实例的值。 @ref{1c15,,compare()} 返回一个 Decimal 实例，如果任一操作数是 NaN ，那么结果是 NaN

@example
a or b is a NaN  ==> Decimal('NaN')
a < b            ==> Decimal('-1')
a == b           ==> Decimal('0')
a > b            ==> Decimal('1')
@end example
@end deffn

@geindex compare_signal() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal compare_signal}@anchor{1c16}
@deffn {方法} compare_signal (other, context=None)

除了所有 NaN 信号之外，此操作与 @ref{1c15,,compare()} 方法相同。 也就是说，如果两个操作数都不是信令NaN，那么任何静默的 NaN 操作数都被视为信令NaN。
@end deffn

@geindex compare_total() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal compare_total}@anchor{1c17}
@deffn {方法} compare_total (other, context=None)

使用它们的抽象表示而不是它们的数值来比较两个操作数。 类似于 @ref{1c15,,compare()} 方法，但结果给出了一个总排序 @ref{2c7,,Decimal} 实例。 两个 @ref{2c7,,Decimal} 实例具有相同的数值但不同的表示形式在此排序中比较不相等：

@example
>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')
@end example

静默和发出信号的 NaN 也包括在总排序中。 这个函数的结果是 @code{Decimal('0')} 如果两个操作数具有相同的表示，或是 @code{Decimal('-1')} 如果第一个操作数的总顺序低于第二个操作数，或是 @code{Decimal('1')} 如果第一个操作数在总顺序中高于第二个操作数。 有关总排序的详细信息，请参阅规范。

此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为例外，如果无法准确转换第二个操作数，则C版本可能会引发InvalidOperation。
@end deffn

@geindex compare_total_mag() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal compare_total_mag}@anchor{1c18}
@deffn {方法} compare_total_mag (other, context=None)

比较两个操作数使用它们的抽象表示而不是它们的值，如 @ref{1c17,,compare_total()}，但忽略每个操作数的符号。 @code{x.compare_total_mag(y)} 相当于 @code{x.copy_abs().compare_total(y.copy_abs())}。

此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为例外，如果无法准确转换第二个操作数，则C版本可能会引发InvalidOperation。
@end deffn

@geindex conjugate() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal conjugate}@anchor{1c19}
@deffn {方法} conjugate ()

只返回self，这种方法只符合 Decimal 规范。
@end deffn

@geindex copy_abs() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal copy_abs}@anchor{1c1a}
@deffn {方法} copy_abs ()

返回参数的绝对值。 此操作不受上下文影响并且是静默的：没有更改标志且不执行舍入。
@end deffn

@geindex copy_negate() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal copy_negate}@anchor{1c1b}
@deffn {方法} copy_negate ()

回到参数的否定。 此操作不受上下文影响并且是静默的：没有标志更改且不执行舍入。
@end deffn

@geindex copy_sign() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal copy_sign}@anchor{1c1c}
@deffn {方法} copy_sign (other, context=None)

返回第一个操作数的副本，其符号设置为与第二个操作数的符号相同。 例如：

@example
>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')
@end example

此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为例外，如果无法准确转换第二个操作数，则C版本可能会引发InvalidOperation。
@end deffn

@geindex exp() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal exp}@anchor{ad5}
@deffn {方法} exp (context=None)

返回给定数字的（自然）指数函数`@w{`}e**x`@w{`}的值。结果使用 @ref{1c01,,ROUND_HALF_EVEN} 舍入模式正确舍入。

@example
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')
@end example
@end deffn

@geindex from_float() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal from_float}@anchor{c5a}
@deffn {方法} from_float (f)

将浮点数转换为十进制数的类方法。

注意， @cite{Decimal.from_float(0.1)} 与 @cite{Decimal('0.1')} 不同。 由于 0.1 在二进制浮点中不能精确表示，因此该值存储为最接近的可表示值，即 @cite{0x1.999999999999ap-4} 。 十进制的等效值是`0.1000000000000000055511151231257827021181583404541015625`。

@cartouche
@quotation 注解 
从 Python 3.2 开始，@ref{2c7,,Decimal} 实例也可以直接从 @ref{1fe,,float} 构造。
@end quotation
@end cartouche

@example
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')
@end example


3.1 新版功能.

@end deffn

@geindex fma() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal fma}@anchor{1c1d}
@deffn {方法} fma (other, third, context=None)

混合乘法加法。 返回 self*other+third ，中间乘积 self*other 没有舍入。

@example
>>> Decimal(2).fma(3, 5)
Decimal('11')
@end example
@end deffn

@geindex is_canonical() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_canonical}@anchor{1c1e}
@deffn {方法} is_canonical ()

如果参数是规范的，则为返回 @ref{59c,,True}，否则为 @ref{497,,False} 。 目前，@ref{2c7,,Decimal} 实例总是规范的，所以这个操作总是返回 @ref{59c,,True} 。
@end deffn

@geindex is_finite() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_finite}@anchor{1c1f}
@deffn {方法} is_finite ()

如果参数是一个有限的数，则返回为 @ref{59c,,True} ；如果参数为无穷大或 NaN ，则返回为 @ref{497,,False}。
@end deffn

@geindex is_infinite() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_infinite}@anchor{1c20}
@deffn {方法} is_infinite ()

如果参数为正负无穷大，则返回为 @ref{59c,,True} ，否则为 @ref{497,,False} 。
@end deffn

@geindex is_nan() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_nan}@anchor{1c21}
@deffn {方法} is_nan ()

如果参数为 NaN （无论是否静默），则返回为 @ref{59c,,True} ，否则为 @ref{497,,False} 。
@end deffn

@geindex is_normal() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_normal}@anchor{1c22}
@deffn {方法} is_normal (context=None)

如果参数是一个 @emph{标准的} 有限数则返回 @ref{59c,,True}。 如果参数为零、次标准数、无穷大或 NaN 则返回 @ref{497,,False}。
@end deffn

@geindex is_qnan() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_qnan}@anchor{1c23}
@deffn {方法} is_qnan ()

如果参数为静默 NaN，返回 @ref{59c,,True}，否则返回 @ref{497,,False}。
@end deffn

@geindex is_signed() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_signed}@anchor{1c24}
@deffn {方法} is_signed ()

如果参数带有负号，则返回为 @ref{59c,,True}，否则返回 @ref{497,,False}。注意，0 和 NaN 都可带有符号。
@end deffn

@geindex is_snan() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_snan}@anchor{1c25}
@deffn {方法} is_snan ()

如果参数为显式 NaN，则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。
@end deffn

@geindex is_subnormal() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_subnormal}@anchor{1c26}
@deffn {方法} is_subnormal (context=None)

如果参数为次标准数，则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。
@end deffn

@geindex is_zero() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal is_zero}@anchor{1c27}
@deffn {方法} is_zero ()

如果参数是0（正负皆可），则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。
@end deffn

@geindex ln() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal ln}@anchor{ad6}
@deffn {方法} ln (context=None)

返回操作数的自然对数（以 e 为底）。结果是使用 @ref{1c01,,ROUND_HALF_EVEN} 舍入模式正确舍入的。
@end deffn

@geindex log10() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal log10}@anchor{1c28}
@deffn {方法} log10 (context=None)

返回操作数的以十为底的对数。结果是使用 @ref{1c01,,ROUND_HALF_EVEN} 舍入模式正确舍入的。
@end deffn

@geindex logb() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal logb}@anchor{1c29}
@deffn {方法} logb (context=None)

对于一个非零数，返回其运算数的调整后指数作为一个 @ref{2c7,,Decimal} 实例。 如果运算数为零将返回 @code{Decimal('-Infinity')} 并且产生 the @ref{1c06,,DivisionByZero} 标志。如果运算数是无限大则返回 @code{Decimal('Infinity')} 。
@end deffn

@geindex logical_and() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal logical_and}@anchor{1c2a}
@deffn {方法} logical_and (other, context=None)

@ref{1c2a,,logical_and()} 是需要两个 @emph{逻辑运算数} 的逻辑运算（参考 @ref{1c2b,,逻辑操作数} ）。按位输出两运算数的 @code{and} 运算的结果。
@end deffn

@geindex logical_invert() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal logical_invert}@anchor{1c2c}
@deffn {方法} logical_invert (context=None)

@ref{1c2c,,logical_invert()} 是一个逻辑运算。结果是操作数的按位求反。
@end deffn

@geindex logical_or() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal logical_or}@anchor{1c2d}
@deffn {方法} logical_or (other, context=None)

@ref{1c2d,,logical_or()} 是需要两个 @emph{logical operands} 的逻辑运算（请参阅 @ref{1c2b,,逻辑操作数} ）。结果是两个运算数的按位的 @code{or} 运算。
@end deffn

@geindex logical_xor() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal logical_xor}@anchor{1c2e}
@deffn {方法} logical_xor (other, context=None)

@ref{1c2e,,logical_xor()} 是需要两个 @emph{逻辑运算数} 的逻辑运算（参考 @ref{1c2b,,逻辑操作数} ）。结果是按位输出的两运算数的异或运算。
@end deffn

@geindex max() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal max}@anchor{1c2f}
@deffn {方法} max (other, context=None)

像 @code{max(self, other)} 一样，除了在返回之前应用上下文舍入规则并且用信号通知或忽略 @code{NaN} 值（取决于上下文以及它们是发信号还是安静）。
@end deffn

@geindex max_mag() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal max_mag}@anchor{1c30}
@deffn {方法} max_mag (other, context=None)

与 @ref{1c2f,,max()} 方法相似，但是操作数使用绝对值完成比较。
@end deffn

@geindex min() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal min}@anchor{1c31}
@deffn {方法} min (other, context=None)

像 @code{min(self, other)} 一样，除了在返回之前应用上下文舍入规则并且用信号通知或忽略 @code{NaN} 值（取决于上下文以及它们是发信号还是安静）。
@end deffn

@geindex min_mag() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal min_mag}@anchor{1c32}
@deffn {方法} min_mag (other, context=None)

与 @ref{1c31,,min()} 方法相似，但是操作数使用绝对值完成比较。
@end deffn

@geindex next_minus() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal next_minus}@anchor{1c33}
@deffn {方法} next_minus (context=None)

返回小于给定操作数的上下文中可表示的最大数字（或者当前线程的上下文中的可表示的最大数字如果没有给定上下文）。
@end deffn

@geindex next_plus() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal next_plus}@anchor{1c34}
@deffn {方法} next_plus (context=None)

返回大于给定操作数的上下文中可表示的最小数字（或者当前线程的上下文中的可表示的最小数字如果没有给定上下文）。
@end deffn

@geindex next_toward() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal next_toward}@anchor{1c35}
@deffn {方法} next_toward (other, context=None)

如果两运算数不相等，返回在第二个操作数的方向上最接近第一个操作数的数。如果两操作数数值上相等，返回将符号设置为与第二个运算数相同的第一个运算数的拷贝。
@end deffn

@geindex normalize() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal normalize}@anchor{1c36}
@deffn {方法} normalize (context=None)

通过去除尾随的零并将所有结果等于 @code{Decimal('0')} 的转化为 @code{Decimal('0e0')} 来标准化数字。用于为等效类的属性生成规范值。比如， @code{Decimal('32.100')} 和 @code{Decimal('0.321000e+2')} 都被标准化为相同的值 @code{Decimal('32.1')}。
@end deffn

@geindex number_class() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal number_class}@anchor{1c37}
@deffn {方法} number_class (context=None)

返回一个字符串描述运算数的 @emph{class} 。返回值是以下十个字符串中的一个。


@itemize *

@item 
@code{"-Infinity"} ，指示运算数为负无穷大。

@item 
@code{"-Normal"} ，指示该运算数是负正常数字。

@item 
@code{"-Subnormal"} ，指示该运算数是负的次标准数。

@item 
@code{"-Zero"} ，指示该运算数是负零。

@item 
@code{"-Zero"} ，指示该运算数是正零。

@item 
@code{"+Subnormal"} ，指示该运算数是正的次标准数。

@item 
@code{"+Normal"} ，指示该运算数是正的标准数。

@item 
@code{"+Infinity"} ，指示该运算数是正无穷。

@item 
@code{"NaN"} ，指示该运算数是肃静 NaN （非数字）。

@item 
@code{"sNaN"} ，指示该运算数是信号 NaN 。
@end itemize
@end deffn

@geindex quantize() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal quantize}@anchor{ad9}
@deffn {方法} quantize (exp, rounding=None, context=None)

返回的值等于舍入后的第一个运算数并且具有第二个操作数的指数。

@example
>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')
@end example

与其他运算不同，如果量化运算后的系数长度大于精度，那么会发出一个 @ref{ad3,,InvalidOperation} 信号。这保证了除非有一个错误情况，量化指数恒等于右手运算数的指数。

与其他运算不同，量化永不信号下溢，即使结果不正常且不精确。

如果第二个运算数的指数大于第一个运算数的指数那或许需要舍入。在这种情况下，舍入模式由给定 @code{rounding} 参数决定，其余的由给定 @code{context} 参数决定；如果参数都未给定，使用当前线程上下文的舍入模式。

每当结果的指数大于 @code{Emax} 或小于 @code{Etiny} 就会返回错误。
@end deffn

@geindex radix() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal radix}@anchor{1c38}
@deffn {方法} radix ()

返回 @code{Decimal(10)}，即 @ref{2c7,,Decimal} 类进行所有算术运算所用的数制（基数）。 这是为保持与规范描述的兼容性而加入的。
@end deffn

@geindex remainder_near() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal remainder_near}@anchor{1c39}
@deffn {方法} remainder_near (other, context=None)

返回 @emph{self} 除以 @emph{other} 的余数。 这与 @code{self % other} 的区别在于所选择的余数要使其绝对值最小化。 更准确地说，返回值为 @code{self - n * other} 其中 @code{n} 是最接近 @code{self / other} 的实际值的整数，并且如果两个整数与实际值的差相等则会选择其中的偶数。

如果结果为零则其符号将为 @emph{self} 的符号。

@example
>>> Decimal(18).remainder_near(Decimal(10))
Decimal('-2')
>>> Decimal(25).remainder_near(Decimal(10))
Decimal('5')
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')
@end example
@end deffn

@geindex rotate() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal rotate}@anchor{1c3a}
@deffn {方法} rotate (other, context=None)

返回对第一个操作数的数码按第二个操作数所指定的数量进行轮转的结果。 第二个操作数必须为 -precision 至 precision 精度范围内的整数。 第二个操作数的绝对值给出要轮转的位数。 如果第二个操作数为正值则向左轮转；否则向右轮转。 如有必要第一个操作数的系数会在左侧填充零以达到 precision 所指定的长度。 第一个操作数的符号和指数保持不变。
@end deffn

@geindex same_quantum() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal same_quantum}@anchor{1c3b}
@deffn {方法} same_quantum (other, context=None)

检测自身与 other 是否具有相同的指数或是否均为 @code{NaN}。

此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为例外，如果无法准确转换第二个操作数，则C版本可能会引发InvalidOperation。
@end deffn

@geindex scaleb() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal scaleb}@anchor{1c3c}
@deffn {方法} scaleb (other, context=None)

返回第一个操作数使用第二个操作数对指数进行调整的结果。 等价于返回第一个操作数乘以 @code{10**other} 的结果。 第二个操作数必须为整数。
@end deffn

@geindex shift() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal shift}@anchor{1c3d}
@deffn {方法} shift (other, context=None)

返回第一个操作数的数码按第二个操作数所指定的数量进行移位的结果。 第二个操作数必须为 -precision 至 precision 范围内的整数。 第二个操作数的绝对值给出要移动的位数。 如果第二个操作数为正值则向左移位；否则向右移位。 移入系数的数码为零。 第一个操作数的符号和指数保持不变。
@end deffn

@geindex sqrt() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal sqrt}@anchor{1c3e}
@deffn {方法} sqrt (context=None)

返回参数的平方根精确到完整精度。
@end deffn

@geindex to_eng_string() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal to_eng_string}@anchor{1c3f}
@deffn {方法} to_eng_string (context=None)

转换为字符串，如果需要指数则会使用工程标注法。

工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个数码，并可能要求添加一至两个末尾零。

例如，此方法会将 @code{Decimal('123E+1')} 转换为 @code{Decimal('1.23E+3')}。
@end deffn

@geindex to_integral() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal to_integral}@anchor{1c40}
@deffn {方法} to_integral (rounding=None, context=None)

与 @ref{1c41,,to_integral_value()} 方法相同。 保留 @code{to_integral} 名称是为了与旧版本兼容。
@end deffn

@geindex to_integral_exact() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal to_integral_exact}@anchor{1c42}
@deffn {方法} to_integral_exact (rounding=None, context=None)

舍入到最接近的整数，发出信号 @ref{1c07,,Inexact} 或者如果发生舍入则相应地发出信号 @ref{1c08,,Rounded}。 如果给出 @code{rounding} 形参则由其确定舍入模式，否则由给定的 @code{context} 来确定。 如果没有给定任何形参则会使用当前上下文的舍入模式。
@end deffn

@geindex to_integral_value() (decimal.Decimal 方法)
@anchor{library/decimal decimal Decimal to_integral_value}@anchor{1c41}
@deffn {方法} to_integral_value (rounding=None, context=None)

舍入到最接近的整数而不发出 @ref{1c07,,Inexact} 或 @ref{1c08,,Rounded} 信号。 如果给出 @emph{rounding} 则会应用其所指定的舍入模式；否则使用所提供的 @emph{context} 或当前上下文的舍入方法。
@end deffn
@end deffn

@menu
* 逻辑操作数:: 

@end menu

@node 逻辑操作数,,,Decimal 对象
@anchor{library/decimal logical-operands}@anchor{1c43}@anchor{library/decimal logical-operands-label}@anchor{1c2b}
@subsubsection 逻辑操作数


@code{logical_and()}, @code{logical_invert()}, @code{logical_or()} 和 @code{logical_xor()} 方法期望其参数为 @emph{逻辑操作数}。 @emph{逻辑操作数} 是指数位与符号位均为零的 @ref{2c7,,Decimal} 实例，并且其数字位均为 @code{0} 或 @code{1}。

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 上下文对象,常数<3>,Decimal 对象,decimal --- 十进制定点和浮点运算
@anchor{library/decimal context-objects}@anchor{1c44}@anchor{library/decimal decimal-context}@anchor{1c45}
@subsubsection 上下文对象


上下文是算术运算所在的环境。 它们管理精度、设置舍入规则、确定将哪些信号视为异常，并限制指数的范围。

每个线程都有自己的当前上下文，可使用 @ref{1c0e,,getcontext()} 和 @ref{1c0f,,setcontext()} 函数来读取或修改：

@geindex getcontext() (在 decimal 模块中)
@anchor{library/decimal decimal getcontext}@anchor{1c0e}
@deffn {函数} decimal.getcontext ()

返回活动线程的当前上下文。
@end deffn

@geindex setcontext() (在 decimal 模块中)
@anchor{library/decimal decimal setcontext}@anchor{1c0f}
@deffn {函数} decimal.setcontext (c)

将活动线程的当前上下文设为 @emph{c}。
@end deffn

你也可以使用 @ref{7e4,,with} 语句和 @ref{1844,,localcontext()} 函数来临时改变活动上下文。

@geindex localcontext() (在 decimal 模块中)
@anchor{library/decimal decimal localcontext}@anchor{1844}
@deffn {函数} decimal.localcontext (ctx=None)

返回一个上下文管理器，它将在进入 with 语句时将活动线程的当前上下文设为 @emph{ctx} 的一个副本并在退出 with 语句时恢复之前的上下文。 如果未指定上下文，则会使用当前上下文的一个副本。

例如，以下代码会将当前 decimal 精度设为 42 位，执行一个运算，然后自动恢复之前的上下文:

@example
from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision
@end example
@end deffn

新的上下文也可使用下述的 @ref{ad8,,Context} 构造器来创建。 此外，模块还提供了三种预设的上下文:

@geindex BasicContext (decimal 中的类)
@anchor{library/decimal decimal BasicContext}@anchor{ad1}
@deffn {类} decimal.BasicContext

这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入设为 @ref{1c02,,ROUND_HALF_UP}。 清除所有旗标。 启用所有陷阱（视为异常），但 @ref{1c07,,Inexact}, @ref{1c08,,Rounded} 和 @ref{1c09,,Subnormal} 除外。

由于启用了许多陷阱，此上下文适用于进行调试。
@end deffn

@geindex ExtendedContext (decimal 中的类)
@anchor{library/decimal decimal ExtendedContext}@anchor{ad2}
@deffn {类} decimal.ExtendedContext

这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入设为 @ref{1c01,,ROUND_HALF_EVEN}。 清除所有旗标。 不启用任何陷阱（因此在计算期间不会引发异常）。

由于禁用了陷阱，此上下文适用于希望结果值为 @code{NaN} 或 @code{Infinity} 而不是引发异常的应用。 这允许应用在出现当其他情况下会中止程序的条件时仍能完成运行。
@end deffn

@geindex DefaultContext (decimal 中的类)
@anchor{library/decimal decimal DefaultContext}@anchor{ad0}
@deffn {类} decimal.DefaultContext

此上下文被 @ref{ad8,,Context} 构造器用作新上下文的原型。 改变一个字段（例如精度）的效果将是改变 @ref{ad8,,Context} 构造器所创建的新上下文的默认值。

此上下文最适用于多线程环境。 在线程开始前改变一个字段具有设置全系统默认值的效果。 不推荐在线程开始后改变字段，因为这会要求线程同步避免竞争条件。

在单线程环境中，最好完全不使用此上下文。 而是简单地电显式创建上下文，具体如下所述。

默认值为 @code{prec}=@code{28}, @code{rounding}=@ref{1c01,,ROUND_HALF_EVEN}，并为 @ref{1c0a,,Overflow}, @ref{ad3,,InvalidOperation} 和 @ref{1c06,,DivisionByZero} 启用陷阱。
@end deffn

在已提供的三种上下文之外，还可以使用 @ref{ad8,,Context} 构造器创建新的上下文。

@geindex Context (decimal 中的类)
@anchor{library/decimal decimal Context}@anchor{ad8}
@deffn {类} decimal.Context (prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)

创建一个新上下文。 如果某个字段未指定或为 @ref{204,,None}，则从 @ref{ad0,,DefaultContext} 拷贝默认值。 如果 @emph{flags} 字段未指定或为 @ref{204,,None}，则清空所有旗标。

@emph{prec} 为一个 [@code{1}, @ref{1c46,,MAX_PREC}] 范围内的整数，用于设置该上下文中算术运算的精度。

@emph{rounding} 选项应为 @ref{1c47,,Rounding Modes} 小节中列出的常量之一。

@emph{traps} 和 @emph{flags} 字段列出要设置的任何信号。 通常，新上下文应当只设置 traps 而让 flags 为空。

@emph{Emin} 和 @emph{Emax} 字段给定指数所允许的外部上限。 @emph{Emin} 必须在 [@ref{1c48,,MIN_EMIN}, @code{0}] 范围内，@emph{Emax} 在 [@code{0}, @ref{1c49,,MAX_EMAX}] 范围内。

@emph{capitals} 字段为 @code{0} 或 @code{1} (默认值)。 如果设为 @code{1}，指数将附带打印大写的 @code{E}；其他情况则将使用小写的 @code{e}: @code{Decimal('6.02e+23')}。

@emph{clamp} 字段为 @code{0} (默认值) 或 @code{1}。 如果设为 @code{1}，则 @ref{2c7,,Decimal} 实例的指数 @code{e} 的表示范围在此上下文中将严格限制为 @code{Emin - prec + 1 <= e <= Emax - prec + 1}。 如果 @emph{clamp} 为 @code{0} 则将适用较弱的条件: @ref{2c7,,Decimal} 实例调整后的指数最大值为 @code{Emax}。 当 @emph{clamp} 为 @code{1} 时，一个较大的普通数值将在可能的情况下减小其指数并为其系统添加相应数量的零，以便符合指数值限制；这可以保持数字值但会丢失有效末尾零的信息。 例如:

@example
>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')
@end example

@emph{clamp} 值为 @code{1} 时即允许与在 IEEE 754 中描述的固定宽度十进制交换格式保持兼容性。

@ref{ad8,,Context} 类定义了几种通用方法以及大量直接在给定上下文中进行算术运算的方法。 此外，对于上述的每种 @ref{2c7,,Decimal} 方法（不包括 @code{adjusted()} 和 @code{as_tuple()} 方法）都有一个相应的 @ref{ad8,,Context} 方法。 例如，对于一个 @ref{ad8,,Context} 的实例 @code{C} 和 @ref{2c7,,Decimal} 的实例 @code{x}，@code{C.exp(x)} 就等价于 @code{x.exp(context=C)}。 每个 @ref{ad8,,Context} 方法都接受一个 Python 整数（即 @ref{205,,int} 的实例）在任何接受 Decimal 的实例的地方使用。

@geindex clear_flags() (decimal.Context 方法)
@anchor{library/decimal decimal Context clear_flags}@anchor{1c4a}
@deffn {方法} clear_flags ()

将所有旗标重置为 @code{0}。
@end deffn

@geindex clear_traps() (decimal.Context 方法)
@anchor{library/decimal decimal Context clear_traps}@anchor{1c4b}
@deffn {方法} clear_traps ()

将所有陷阱重置为零 @code{0}。


3.3 新版功能.

@end deffn

@geindex copy() (decimal.Context 方法)
@anchor{library/decimal decimal Context copy}@anchor{1c4c}
@deffn {方法} copy ()

返回上下文的一个副本。
@end deffn

@geindex copy_decimal() (decimal.Context 方法)
@anchor{library/decimal decimal Context copy_decimal}@anchor{1c4d}
@deffn {方法} copy_decimal (num)

返回 Decimal 实例 num 的一个副本。
@end deffn

@geindex create_decimal() (decimal.Context 方法)
@anchor{library/decimal decimal Context create_decimal}@anchor{ad4}
@deffn {方法} create_decimal (num)

基于 @emph{num} 创建一个新 Decimal 实例但使用 @emph{self} 作为上下文。 与 @ref{2c7,,Decimal} 构造器不同，该上下文的精度、舍入方法、旗标和陷阱会被应用于转换过程。

此方法很有用处，因为常量往往被给予高于应用所需的精度。 另一个好处在于立即执行舍入可以消除超出当前精度的数位所导致的意外效果。 在下面的示例中，使用未舍入的输入意味着在总和中添加零会改变结果：

@example
>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')
@end example

此方法实现了 IBM 规格描述中的转换为数字操作。 如果参数为字符串，则不允许有开头或末尾的空格或下划线。
@end deffn

@geindex create_decimal_from_float() (decimal.Context 方法)
@anchor{library/decimal decimal Context create_decimal_from_float}@anchor{1c4e}
@deffn {方法} create_decimal_from_float (f)

基于浮点数 @emph{f} 创建一个新的 Decimal 实例，但会使用 @emph{self} 作为上下文来执行舍入。 与 @ref{c5a,,Decimal.from_float()} 类方法不同，上下文的精度、舍入方法、旗标和陷阱会应用到转换中。

@example
>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
decimal.Inexact: None
@end example


3.1 新版功能.

@end deffn

@geindex Etiny() (decimal.Context 方法)
@anchor{library/decimal decimal Context Etiny}@anchor{1c4f}
@deffn {方法} Etiny ()

返回一个等于 @code{Emin - prec + 1} 的值即次标准化结果中的最小指数值。 当发生向下溢出时，指数会设为 @ref{1c4f,,Etiny}。
@end deffn

@geindex Etop() (decimal.Context 方法)
@anchor{library/decimal decimal Context Etop}@anchor{1c50}
@deffn {方法} Etop ()

返回一个等于 @code{Emax - prec + 1} 的值。
@end deffn

使用 decimal 的通常方式是创建 @ref{2c7,,Decimal} 实例然后对其应用算术运算,这些运算发生在活动线程的当前上下文中。 一种替代方式则是使用上下文的方法在特定上下文中进行计算。 这些方法类似于 @ref{2c7,,Decimal} 类的方法，在此仅简单地重新列出。

@geindex abs() (decimal.Context 方法)
@anchor{library/decimal decimal Context abs}@anchor{1c51}
@deffn {方法} abs (x)

返回 @emph{x} 的绝对值。
@end deffn

@geindex add() (decimal.Context 方法)
@anchor{library/decimal decimal Context add}@anchor{1c52}
@deffn {方法} add (x, y)

返回 @emph{x} 与 @emph{y} 的和。
@end deffn

@geindex canonical() (decimal.Context 方法)
@anchor{library/decimal decimal Context canonical}@anchor{d6d}
@deffn {方法} canonical (x)

返回相同的 Decimal 对象 @emph{x}。
@end deffn

@geindex compare() (decimal.Context 方法)
@anchor{library/decimal decimal Context compare}@anchor{1c53}
@deffn {方法} compare (x, y)

对 @emph{x} 与 @emph{y} 进行数值比较。
@end deffn

@geindex compare_signal() (decimal.Context 方法)
@anchor{library/decimal decimal Context compare_signal}@anchor{1c54}
@deffn {方法} compare_signal (x, y)

对两个操作数进行数值比较。
@end deffn

@geindex compare_total() (decimal.Context 方法)
@anchor{library/decimal decimal Context compare_total}@anchor{1c55}
@deffn {方法} compare_total (x, y)

对两个操作数使用其抽象表示进行比较。
@end deffn

@geindex compare_total_mag() (decimal.Context 方法)
@anchor{library/decimal decimal Context compare_total_mag}@anchor{1c56}
@deffn {方法} compare_total_mag (x, y)

对两个操作数使用其抽象表示进行比较，忽略符号。
@end deffn

@geindex copy_abs() (decimal.Context 方法)
@anchor{library/decimal decimal Context copy_abs}@anchor{1c57}
@deffn {方法} copy_abs (x)

返回 @emph{x} 的副本，符号设为 0。
@end deffn

@geindex copy_negate() (decimal.Context 方法)
@anchor{library/decimal decimal Context copy_negate}@anchor{1c58}
@deffn {方法} copy_negate (x)

返回 @emph{x} 的副本，符号取反。
@end deffn

@geindex copy_sign() (decimal.Context 方法)
@anchor{library/decimal decimal Context copy_sign}@anchor{1c59}
@deffn {方法} copy_sign (x, y)

从 @emph{y} 拷贝符号至 @emph{x}。
@end deffn

@geindex divide() (decimal.Context 方法)
@anchor{library/decimal decimal Context divide}@anchor{1c5a}
@deffn {方法} divide (x, y)

返回 @emph{x} 除以 @emph{y} 的结果。
@end deffn

@geindex divide_int() (decimal.Context 方法)
@anchor{library/decimal decimal Context divide_int}@anchor{1c5b}
@deffn {方法} divide_int (x, y)

返回 @emph{x} 除以 @emph{y} 的结果，截短为整数。
@end deffn

@geindex divmod() (decimal.Context 方法)
@anchor{library/decimal decimal Context divmod}@anchor{1c5c}
@deffn {方法} divmod (x, y)

两个数字相除并返回结果的整数部分。
@end deffn

@geindex exp() (decimal.Context 方法)
@anchor{library/decimal decimal Context exp}@anchor{1c5d}
@deffn {方法} exp (x)

返回 @cite{e ** x}。
@end deffn

@geindex fma() (decimal.Context 方法)
@anchor{library/decimal decimal Context fma}@anchor{1c5e}
@deffn {方法} fma (x, y, z)

返回 @emph{x} 乘以 @emph{y} 再加 @emph{z} 的结果。
@end deffn

@geindex is_canonical() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_canonical}@anchor{d6e}
@deffn {方法} is_canonical (x)

如果 @emph{x} 是规范的则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_finite() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_finite}@anchor{1c5f}
@deffn {方法} is_finite (x)

如果 @emph{x} 为有限的则返回`@w{`}True`@w{`}；否则返回 @code{False}。
@end deffn

@geindex is_infinite() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_infinite}@anchor{1c60}
@deffn {方法} is_infinite (x)

如果 @emph{x} 是无限的则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_nan() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_nan}@anchor{1c61}
@deffn {方法} is_nan (x)

如果 @emph{x} 是 qNaN 或 sNaN 则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_normal() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_normal}@anchor{1c62}
@deffn {方法} is_normal (x)

如果 @emph{x} 是标准数则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_qnan() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_qnan}@anchor{1c63}
@deffn {方法} is_qnan (x)

如果 @emph{x} 是静默 NaN 则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_signed() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_signed}@anchor{1c64}
@deffn {方法} is_signed (x)

@emph{x} 是负数则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_snan() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_snan}@anchor{1c65}
@deffn {方法} is_snan (x)

如果 @emph{x} 是显式 NaN 则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_subnormal() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_subnormal}@anchor{1c66}
@deffn {方法} is_subnormal (x)

如果 @emph{x} 是次标准数则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex is_zero() (decimal.Context 方法)
@anchor{library/decimal decimal Context is_zero}@anchor{1c67}
@deffn {方法} is_zero (x)

如果 @emph{x} 为零则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex ln() (decimal.Context 方法)
@anchor{library/decimal decimal Context ln}@anchor{1c68}
@deffn {方法} ln (x)

返回 @emph{x} 的自然对数（以 e 为底）。
@end deffn

@geindex log10() (decimal.Context 方法)
@anchor{library/decimal decimal Context log10}@anchor{1c69}
@deffn {方法} log10 (x)

返回 @emph{x} 的以 10 为底的对数。
@end deffn

@geindex logb() (decimal.Context 方法)
@anchor{library/decimal decimal Context logb}@anchor{1c6a}
@deffn {方法} logb (x)

返回操作数的 MSD 等级的指数。
@end deffn

@geindex logical_and() (decimal.Context 方法)
@anchor{library/decimal decimal Context logical_and}@anchor{1c6b}
@deffn {方法} logical_and (x, y)

在操作数的每个数位间应用逻辑运算 @emph{and}。
@end deffn

@geindex logical_invert() (decimal.Context 方法)
@anchor{library/decimal decimal Context logical_invert}@anchor{1c6c}
@deffn {方法} logical_invert (x)

反转 @emph{x} 中的所有数位。
@end deffn

@geindex logical_or() (decimal.Context 方法)
@anchor{library/decimal decimal Context logical_or}@anchor{1c6d}
@deffn {方法} logical_or (x, y)

在操作数的每个数位间应用逻辑运算 @emph{or}。
@end deffn

@geindex logical_xor() (decimal.Context 方法)
@anchor{library/decimal decimal Context logical_xor}@anchor{1c6e}
@deffn {方法} logical_xor (x, y)

在操作数的每个数位间应用逻辑运算 @emph{xor}。
@end deffn

@geindex max() (decimal.Context 方法)
@anchor{library/decimal decimal Context max}@anchor{1c6f}
@deffn {方法} max (x, y)

对两个值执行数字比较并返回其中的最大值。
@end deffn

@geindex max_mag() (decimal.Context 方法)
@anchor{library/decimal decimal Context max_mag}@anchor{1c70}
@deffn {方法} max_mag (x, y)

对两个值执行忽略正负号的数字比较。
@end deffn

@geindex min() (decimal.Context 方法)
@anchor{library/decimal decimal Context min}@anchor{1c71}
@deffn {方法} min (x, y)

对两个值执行数字比较并返回其中的最小值。
@end deffn

@geindex min_mag() (decimal.Context 方法)
@anchor{library/decimal decimal Context min_mag}@anchor{1c72}
@deffn {方法} min_mag (x, y)

对两个值执行忽略正负号的数字比较。
@end deffn

@geindex minus() (decimal.Context 方法)
@anchor{library/decimal decimal Context minus}@anchor{1c73}
@deffn {方法} minus (x)

对应于 Python 中的单目前缀取负运算符执行取负操作。
@end deffn

@geindex multiply() (decimal.Context 方法)
@anchor{library/decimal decimal Context multiply}@anchor{1c74}
@deffn {方法} multiply (x, y)

返回 @emph{x} 和 @emph{y} 的积。
@end deffn

@geindex next_minus() (decimal.Context 方法)
@anchor{library/decimal decimal Context next_minus}@anchor{1c75}
@deffn {方法} next_minus (x)

返回小于 @emph{x} 的最大数字表示形式。
@end deffn

@geindex next_plus() (decimal.Context 方法)
@anchor{library/decimal decimal Context next_plus}@anchor{1c76}
@deffn {方法} next_plus (x)

返回大于 @emph{x} 的最小数字表示形式。
@end deffn

@geindex next_toward() (decimal.Context 方法)
@anchor{library/decimal decimal Context next_toward}@anchor{1c77}
@deffn {方法} next_toward (x, y)

返回 @emph{x} 趋向于 @emph{y} 的最接近的数字。
@end deffn

@geindex normalize() (decimal.Context 方法)
@anchor{library/decimal decimal Context normalize}@anchor{1c78}
@deffn {方法} normalize (x)

将 @emph{x} 改写为最简形式。
@end deffn

@geindex number_class() (decimal.Context 方法)
@anchor{library/decimal decimal Context number_class}@anchor{1c79}
@deffn {方法} number_class (x)

返回 @emph{x} 的类的表示。
@end deffn

@geindex plus() (decimal.Context 方法)
@anchor{library/decimal decimal Context plus}@anchor{1c7a}
@deffn {方法} plus (x)

对应于 Python 中的单目前缀取正运算符执行取正操作。 此操作将应用上下文精度和舍入，因此它 @emph{不是} 标识运算。
@end deffn

@geindex power() (decimal.Context 方法)
@anchor{library/decimal decimal Context power}@anchor{1c7b}
@deffn {方法} power (x, y, modulo=None)

返回 @code{x} 的 @code{y} 次方，如果给出了模数 @code{modulo} 则取其余数。

如为两个参数则计算 @code{x**y}。 如果 @code{x} 为负值则 @code{y} 必须为整数。 除非 @code{y} 为整数且结果为有限值并可在 'precision' 位内精确表示否则结果将是不精确的。 上下文的舍入模式将被使用。 结果在 Python 版中总是会被正确地舍入。

@code{Decimal(0) ** Decimal(0)} 结果为 @code{InvalidOperation}，而如果 @code{InvalidOperation} 未被捕获，则结果为 @code{Decimal('NaN')}。


在 3.3 版更改: C 模块计算 @ref{1c7b,,power()} 时会使用已正确舍入的 @ref{1c5d,,exp()} 和 @ref{1c68,,ln()} 函数。 结果是经过良好定义的，但仅限于“几乎总是正确地舍入”。


带有三个参数时，计算 @code{(x**y) % modulo}。 对于三个参数的形式，参数将会应用以下限制：

@quotation


@itemize -

@item 
三个参数必须都是整数

@item 
@code{y} 必须是非负数

@item 
@code{x} 或 @code{y} 至少有一个不为零

@item 
@code{modulo} 必须不为零且至多有 'precision' 位
@end itemize
@end quotation

来自 @code{Context.power(x, y, modulo)} 的结果值等于使用无限精度计算 @code{(x**y) % modulo} 所得到的值，但其计算过程更高效。 结果的指数为零，无论 @code{x}, @code{y} 和 @code{modulo} 的指数是多少。 结果值总是完全精确的。
@end deffn

@geindex quantize() (decimal.Context 方法)
@anchor{library/decimal decimal Context quantize}@anchor{1c7c}
@deffn {方法} quantize (x, y)

返回的值等于 @emph{x} (舍入后)，并且指数为 @emph{y}。
@end deffn

@geindex radix() (decimal.Context 方法)
@anchor{library/decimal decimal Context radix}@anchor{1c7d}
@deffn {方法} radix ()

恰好返回 10，因为这是 Decimal 对象 :)
@end deffn

@geindex remainder() (decimal.Context 方法)
@anchor{library/decimal decimal Context remainder}@anchor{1c7e}
@deffn {方法} remainder (x, y)

返回整除所得到的余数。

结果的符号，如果不为零，则与原始除数的符号相同。
@end deffn

@geindex remainder_near() (decimal.Context 方法)
@anchor{library/decimal decimal Context remainder_near}@anchor{1c7f}
@deffn {方法} remainder_near (x, y)

返回 @code{x - y * n}，其中 @emph{n} 为最接近 @code{x / y} 实际值的整数（如结果为 0 则其符号将与 @emph{x} 的符号相同）。
@end deffn

@geindex rotate() (decimal.Context 方法)
@anchor{library/decimal decimal Context rotate}@anchor{1c80}
@deffn {方法} rotate (x, y)

返回 @emph{x} 翻转 @emph{y} 次的副本。
@end deffn

@geindex same_quantum() (decimal.Context 方法)
@anchor{library/decimal decimal Context same_quantum}@anchor{1c81}
@deffn {方法} same_quantum (x, y)

如果两个操作数具有相同的指数则返回 @code{True}。
@end deffn

@geindex scaleb() (decimal.Context 方法)
@anchor{library/decimal decimal Context scaleb}@anchor{1c82}
@deffn {方法} scaleb (x, y)

返回第一个操作数添加第二个值的指数后的结果。
@end deffn

@geindex shift() (decimal.Context 方法)
@anchor{library/decimal decimal Context shift}@anchor{1c83}
@deffn {方法} shift (x, y)

返回 @emph{x} 变换 @emph{y} 次的副本。
@end deffn

@geindex sqrt() (decimal.Context 方法)
@anchor{library/decimal decimal Context sqrt}@anchor{1c84}
@deffn {方法} sqrt (x)

非负数基于上下文精度的平方根。
@end deffn

@geindex subtract() (decimal.Context 方法)
@anchor{library/decimal decimal Context subtract}@anchor{1c85}
@deffn {方法} subtract (x, y)

返回 @emph{x} 和 @emph{y} 的差。
@end deffn

@geindex to_eng_string() (decimal.Context 方法)
@anchor{library/decimal decimal Context to_eng_string}@anchor{1c86}
@deffn {方法} to_eng_string (x)

转换为字符串，如果需要指数则会使用工程标注法。

工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个数码，并可能要求添加一至两个末尾零。
@end deffn

@geindex to_integral_exact() (decimal.Context 方法)
@anchor{library/decimal decimal Context to_integral_exact}@anchor{1c87}
@deffn {方法} to_integral_exact (x)

舍入到一个整数。
@end deffn

@geindex to_sci_string() (decimal.Context 方法)
@anchor{library/decimal decimal Context to_sci_string}@anchor{1c88}
@deffn {方法} to_sci_string (x)

使用科学计数法将一个数字转换为字符串。
@end deffn
@end deffn

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 常数<3>,舍入模式,上下文对象,decimal --- 十进制定点和浮点运算
@anchor{library/decimal constants}@anchor{1c89}@anchor{library/decimal decimal-rounding-modes}@anchor{1c8a}
@subsubsection 常数


本节中的常量仅与 C 模块相关。 它们也被包含在纯 Python 版本以保持兼容性。


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@tab

32位

@tab

64位

@item

@geindex MAX_PREC() (在 decimal 模块中)
@anchor{library/decimal decimal MAX_PREC}@anchor{1c46}
@deffn {数据} decimal.MAX_PREC
@end deffn

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@geindex MAX_EMAX() (在 decimal 模块中)
@anchor{library/decimal decimal MAX_EMAX}@anchor{1c49}
@deffn {数据} decimal.MAX_EMAX
@end deffn

@tab

@code{425000000}

@tab

@code{999999999999999999}

@item

@geindex MIN_EMIN() (在 decimal 模块中)
@anchor{library/decimal decimal MIN_EMIN}@anchor{1c48}
@deffn {数据} decimal.MIN_EMIN
@end deffn

@tab

@code{-425000000}

@tab

@code{-999999999999999999}

@item

@geindex MIN_ETINY() (在 decimal 模块中)
@anchor{library/decimal decimal MIN_ETINY}@anchor{1c8b}
@deffn {数据} decimal.MIN_ETINY
@end deffn

@tab

@code{-849999999}

@tab

@code{-1999999999999999997}

@end multitable


@geindex HAVE_THREADS() (在 decimal 模块中)
@anchor{library/decimal decimal HAVE_THREADS}@anchor{ace}
@deffn {数据} decimal.HAVE_THREADS

该值为 @code{True}。 已弃用，因为 Python 现在总是启用线程。
@end deffn


3.9 版后已移除.


@geindex HAVE_CONTEXTVAR() (在 decimal 模块中)
@anchor{library/decimal decimal HAVE_CONTEXTVAR}@anchor{1c8c}
@deffn {数据} decimal.HAVE_CONTEXTVAR

默认值为 @code{True}。 如果 Python 的编译带有 @code{--without-decimal-contextvar} 选项，则 C 版本会使用线程局部而不是协程局部上下文并且该值为 @code{False}。 这在某些嵌套上下文场景中将稍快一些。
@end deffn


3.9 新版功能: 向下移植到 3.7 和 3.8。


@node 舍入模式,信号,常数<3>,decimal --- 十进制定点和浮点运算
@anchor{library/decimal rounding-modes}@anchor{1c47}
@subsubsection 舍入模式


@geindex ROUND_CEILING() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_CEILING}@anchor{1bfd}
@deffn {数据} decimal.ROUND_CEILING

舍入方向为 @code{Infinity}。
@end deffn

@geindex ROUND_DOWN() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_DOWN}@anchor{1bfe}
@deffn {数据} decimal.ROUND_DOWN

舍入方向为零。
@end deffn

@geindex ROUND_FLOOR() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_FLOOR}@anchor{1bff}
@deffn {数据} decimal.ROUND_FLOOR

舍入方向为 @code{-Infinity}。
@end deffn

@geindex ROUND_HALF_DOWN() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_HALF_DOWN}@anchor{1c00}
@deffn {数据} decimal.ROUND_HALF_DOWN

舍入到最接近的数，同样接近则舍入方向为零。
@end deffn

@geindex ROUND_HALF_EVEN() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_HALF_EVEN}@anchor{1c01}
@deffn {数据} decimal.ROUND_HALF_EVEN

舍入到最接近的数，同样接近则舍入到最接近的偶数。
@end deffn

@geindex ROUND_HALF_UP() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_HALF_UP}@anchor{1c02}
@deffn {数据} decimal.ROUND_HALF_UP

舍入到最接近的数，同样接近则舍入到零的反方向。
@end deffn

@geindex ROUND_UP() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_UP}@anchor{1c03}
@deffn {数据} decimal.ROUND_UP

舍入到零的反方向。
@end deffn

@geindex ROUND_05UP() (在 decimal 模块中)
@anchor{library/decimal decimal ROUND_05UP}@anchor{1c04}
@deffn {数据} decimal.ROUND_05UP

如果最后一位朝零的方向舍入后为 0 或 5 则舍入到零的反方向；否则舍入方向为零。
@end deffn

@node 信号,浮点数说明,舍入模式,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-signals}@anchor{1c8d}@anchor{library/decimal signals}@anchor{1c8e}
@subsubsection 信号


信号代表在计算期间引发的条件。 每个信号对应于一个上下文旗标和一个上下文陷阱启用器。

上下文旗标将在遇到特定条件时被设定。 在完成计算之后，将为了获得信息而检测旗标（例如确定计算是否精确）。 在检测旗标后，请确保在开始下一次计算之前清除所有旗标。

如果为信号设定了上下文的陷阱启用器，则条件会导致特定的 Python 异常被引发。 举例来说，如果设定了 @ref{1c06,,DivisionByZero} 陷阱，则当遇到此条件时就将引发 @ref{1c06,,DivisionByZero} 异常。

@geindex Clamped (decimal 中的类)
@anchor{library/decimal decimal Clamped}@anchor{1c05}
@deffn {类} decimal.Clamped

修改一个指数以符合表示限制。

通常，限位将在一个指数超出上下文的 @code{Emin} 和 @code{Emax} 限制时发生。 在可能的情况下，会通过给系数添加零来将指数缩减至符合限制。
@end deffn

@geindex DecimalException (decimal 中的类)
@anchor{library/decimal decimal DecimalException}@anchor{1c8f}
@deffn {类} decimal.DecimalException

其他信号的基类，并且也是 @ref{187f,,ArithmeticError} 的一个子类。
@end deffn

@geindex DivisionByZero (decimal 中的类)
@anchor{library/decimal decimal DivisionByZero}@anchor{1c06}
@deffn {类} decimal.DivisionByZero

非无限数被零除的信号。

可在除法、取余队法或对一个数求负数次幂时发生。 如果此信号未被陷阱捕获，则返回 @code{Infinity} 或 @code{-Infinity} 并且由对计算的输入来确定正负符号。
@end deffn

@geindex Inexact (decimal 中的类)
@anchor{library/decimal decimal Inexact}@anchor{1c07}
@deffn {类} decimal.Inexact

表明发生了舍入且结果是不精确的。

有非零数位在舍入期间被丢弃的信号。 舍入结果将被返回。 此信号旗标或陷阱被用于检测结果不精确的情况。
@end deffn

@geindex InvalidOperation (decimal 中的类)
@anchor{library/decimal decimal InvalidOperation}@anchor{ad3}
@deffn {类} decimal.InvalidOperation

执行了一个无效的操作。

表明请求了一个无意义的操作。 如未被陷阱捕获则返回 @code{NaN}。 可能的原因包括:

@example
Infinity - Infinity
0 * Infinity
Infinity / Infinity
x % 0
Infinity % x
sqrt(-x) and x > 0
0 ** 0
x ** (non-integer)
x ** Infinity
@end example
@end deffn

@geindex Overflow (decimal 中的类)
@anchor{library/decimal decimal Overflow}@anchor{1c0a}
@deffn {类} decimal.Overflow

数值的溢出。

表明在发生舍入之后的指数大于 @code{Emax}。 如果未被陷阱捕获，则结果将取决于舍入模式，或者向下舍入为最大的可表示有限数，或者向上舍入为 @code{Infinity}。 无论哪种情况，都将引发 @ref{1c07,,Inexact} 和 @ref{1c08,,Rounded} 信号。
@end deffn

@geindex Rounded (decimal 中的类)
@anchor{library/decimal decimal Rounded}@anchor{1c08}
@deffn {类} decimal.Rounded

发生了舍入，但或许并没有信息丢失。

一旦舍入丢弃了数位就会发出此信号；即使被丢弃的数位是零 (例如将 @code{5.00} 舍入为 @code{5.0})。 如果未被陷阱捕获，则不经修改地返回结果。 此信号用于检测有效位数的丢弃。
@end deffn

@geindex Subnormal (decimal 中的类)
@anchor{library/decimal decimal Subnormal}@anchor{1c09}
@deffn {类} decimal.Subnormal

在舍入之前指数低于 @code{Emin}。

当操作结果是次标准数（即指数过小）时就会发出此信号。 如果未被陷阱捕获，则不经修改过返回结果。
@end deffn

@geindex Underflow (decimal 中的类)
@anchor{library/decimal decimal Underflow}@anchor{1c0b}
@deffn {类} decimal.Underflow

数字向下溢出导致结果舍入到零。

当一个次标准数结果通过舍入转为零时就会发出此信号。 同时还将引发 @ref{1c07,,Inexact} 和 @ref{1c09,,Subnormal} 信号。
@end deffn

@geindex FloatOperation (decimal 中的类)
@anchor{library/decimal decimal FloatOperation}@anchor{acd}
@deffn {类} decimal.FloatOperation

为 float 和 Decimal 的混合启用更严格的语义。

如果信号未被捕获（默认），则在 @ref{2c7,,Decimal} 构造器、@ref{ad4,,create_decimal()} 和所有比较运算中允许 float 和 Decimal 的混合。 转换和比较都是完全精确的。 发生的任何混合运算都将通过在上下文旗标中设置 @ref{acd,,FloatOperation} 来静默地记录。 通过 @ref{c5a,,from_float()} 或 @ref{1c4e,,create_decimal_from_float()} 进行显式转换则不会设置旗标。

在其他情况下（即信号被捕获），则只静默执行相等性比较和显式转换。 所有其他混合运算都将引发 @ref{acd,,FloatOperation}。
@end deffn

以下表格总结了信号的层级结构:

@example
exceptions.ArithmeticError(exceptions.Exception)
    DecimalException
        Clamped
        DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
        Inexact
            Overflow(Inexact, Rounded)
            Underflow(Inexact, Rounded, Subnormal)
        InvalidOperation
        Rounded
        Subnormal
        FloatOperation(DecimalException, exceptions.TypeError)
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 浮点数说明,使用线程,信号,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-notes}@anchor{1c90}@anchor{library/decimal floating-point-notes}@anchor{1c91}
@subsubsection 浮点数说明


@menu
* 通过提升精度来解决舍入错误:: 
* 特殊的值:: 

@end menu

@node 通过提升精度来解决舍入错误,特殊的值,,浮点数说明
@anchor{library/decimal mitigating-round-off-error-with-increased-precision}@anchor{1c92}
@subsubsection 通过提升精度来解决舍入错误


使用十进制浮点数可以消除十进制表示错误（即能够完全精确地表示 @code{0.1} 这样的数）；然而，某些运算在非零数位超出给定的精度时仍然可能导致舍入错误。

舍入错误的影响可能因接近相互抵销的加减运算被放大从而导致丢失有效位。 Knuth 提供了两个指导性示例，其中出现了精度不足的浮点算术舍入，导致加法的交换律和分配律被打破：

@example
# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8

>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.5111111')
>>> u + (v + w)
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.01')
>>> u * (v+w)
Decimal('0.0060000')
@end example

@ref{35,,decimal} 模块则可以通过充分地扩展精度来避免有效位的丢失：

@example
>>> getcontext().prec = 20
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.51111111')
>>> u + (v + w)
Decimal('9.51111111')
>>>
>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.0060000')
>>> u * (v+w)
Decimal('0.0060000')
@end example

@node 特殊的值,,通过提升精度来解决舍入错误,浮点数说明
@anchor{library/decimal special-values}@anchor{1c93}
@subsubsection 特殊的值


@ref{35,,decimal} 模块的数字系统提供了一些特殊的值，包括 @code{NaN}, @code{sNaN}, @code{-Infinity}, @code{Infinity} 以及两种零值 @code{+0} 和 @code{-0}。

无穷大可以使用 @code{Decimal('Infinity')} 来构建。 它们也可以在不捕获 @ref{1c06,,DivisionByZero} 信号捕获时通过除以零来产生。 类似地，当不捕获 @ref{1c0a,,Overflow} 信号时，也可以通过舍入到超出最大可表示数字限制的方式产生无穷大的结果。

无穷大是有符号的（仿射）并可用于算术运算，它们会被当作极其巨大的不确定数字来处理。 例如，无穷大加一个常量结果也将为无穷大。

某些不存在有效结果的运算将会返回 @code{NaN}，或者如果捕获了 @ref{ad3,,InvalidOperation} 信号则会引发一个异常。 例如，@code{0/0} 会返回 @code{NaN} 表示结果“不是一个数字”。 这样的 @code{NaN} 是静默产生的，并且在产生之后参与其它计算时总是会得到 @code{NaN} 的结果。 这种行为对于偶而缺少输入的各类计算都很有用处 --- 它允许在将特定结果标记为无效的同时让计算继续运行。

另一种变体形式是 @code{sNaN}，它在每次运算后会发出信号而不是保持静默。 当对于无效结果需要中断计算进行特别处理时，这是一个很有用的返回值。

Python 中比较运算符的行为在涉及 @code{NaN} 时可能会令人有点惊讶。 相等性检测在操作数中有静默型或信号型 @code{NaN} 时总是会返回 @ref{497,,False} (即使是执行 @code{Decimal('NaN')==Decimal('NaN')})，而不等性检测总是会返回 @ref{59c,,True}。 当尝试使用 @code{<}, @code{<=}, @code{>} 或 @code{>=} 运算符中的任何一个来比较两个 Decimal 值时，如果运算数中有 @code{NaN} 则将引发 @ref{ad3,,InvalidOperation} 信号，如果此信号未被捕获则将返回 @ref{497,,False}。 请注意通用十进制算术规范并未规定直接比较行为；这些涉及 @code{NaN} 的比较规则来自于 IEEE 854 标准 (见第 5.7 节表 3)。 要确保严格符合标准，请改用 @code{compare()} 和 @code{compare-signal()} 方法。

有符号零值可以由向下溢出的运算产生。 它们保留符号是为了让运算结果能以更高的精度传递。 由于它们的大小为零，正零和负零会被视为相等，且它们的符号具有信息。

在这两个不相同但却相等的有符号零之外，还存在几种零的不同表示形式，它们的精度不同但值也都相等。 这需要一些时间来逐渐适应。 对于习惯了标准浮点表示形式的眼睛来说，以下运算返回等于零的值并不是显而易见的：

@example
>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 使用线程,例程,浮点数说明,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-threads}@anchor{1c94}@anchor{library/decimal working-with-threads}@anchor{1c95}
@subsubsection 使用线程


@ref{1c0e,,getcontext()} 函数会为每个线程访问不同的 @ref{ad8,,Context} 对象。 具有单独线程上下文意味着线程可以修改上下文 (例如 @code{getcontext().prec=10}) 而不影响其他线程。

类似的 @ref{1c0f,,setcontext()} 会为当前上下文的目标自动赋值。

如果在调用 @ref{1c0f,,setcontext()} 之前调用了 @ref{1c0e,,getcontext()}，则 @ref{1c0e,,getcontext()} 将自动创建一个新的上下文在当前线程中使用。

新的上下文拷贝自一个名为 @emph{DefaultContext} 的原型上下文。 要控制默认值以便每个线程在应用运行期间都使用相同的值，可以直接修改 @emph{DefaultContext} 对象。 这应当在任何线程启动 @emph{之前} 完成以使得调用 @ref{1c0e,,getcontext()} 的线程之间不会产生竞争条件。 例如:

@example
# Set applicationwide defaults for all threads about to be launched
DefaultContext.prec = 12
DefaultContext.rounding = ROUND_DOWN
DefaultContext.traps = ExtendedContext.traps.copy()
DefaultContext.traps[InvalidOperation] = 1
setcontext(DefaultContext)

# Afterwards, the threads can be started
t1.start()
t2.start()
t3.start()
 . . .
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node 例程,Decimal 常见问题,使用线程,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-recipes}@anchor{1c96}@anchor{library/decimal recipes}@anchor{1c97}
@subsubsection 例程


以下是一些用作工具函数的例程，它们演示了使用 @ref{2c7,,Decimal} 类的各种方式:

@example
def moneyfmt(value, places=2, curr='@w{'}, sep=',', dp='.',
             pos='@w{'}, neg='-', trailneg='@w{'}):
    """Convert Decimal to a money formatted string.

    places:  required number of places after the decimal point
    curr:    optional currency symbol before the sign (may be blank)
    sep:     optional grouping separator (comma, period, space, or blank)
    dp:      decimal point indicator (comma or period)
             only specify as blank when places is zero
    pos:     optional sign for positive numbers: '+', space or blank
    neg:     optional sign for negative numbers: '-', '(', space or blank
    trailneg:optional trailing minus indicator:  '-', ')', space or blank

    >>> d = Decimal('-1234567.8901')
    >>> moneyfmt(d, curr='$')
    '-$1,234,567.89'
    >>> moneyfmt(d, places=0, sep='.', dp='@w{'}, neg='@w{'}, trailneg='-')
    '1.234.568-'
    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
    '($1,234,567.89)'
    >>> moneyfmt(Decimal(123456789), sep=' ')
    '123 456 789.00'
    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
    '<0.02>'

    """
    q = Decimal(10) ** -places      # 2 places --> '0.01'
    sign, digits, exp = value.quantize(q).as_tuple()
    result = []
    digits = list(map(str, digits))
    build, next = result.append, digits.pop
    if sign:
        build(trailneg)
    for i in range(places):
        build(next() if digits else '0')
    if places:
        build(dp)
    if not digits:
        build('0')
    i = 0
    while digits:
        build(next())
        i += 1
        if i == 3 and digits:
            i = 0
            build(sep)
    build(curr)
    build(neg if sign else pos)
    return '@w{'}.join(reversed(result))

def pi():
    """Compute Pi to the current precision.

    >>> print(pi())
    3.141592653589793238462643383

    """
    getcontext().prec += 2  # extra digits for intermediate steps
    three = Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    return +s               # unary plus applies the new precision

def exp(x):
    """Return e raised to the power of x.  Result type matches input type.

    >>> print(exp(Decimal(1)))
    2.718281828459045235360287471
    >>> print(exp(Decimal(2)))
    7.389056098930650227230427461
    >>> print(exp(2.0))
    7.38905609893
    >>> print(exp(2+0j))
    (7.38905609893+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num = 0, 0, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 1
        fact *= i
        num *= x
        s += num / fact
    getcontext().prec -= 2
    return +s

def cos(x):
    """Return the cosine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(cos(Decimal('0.5')))
    0.8775825618903727161162815826
    >>> print(cos(0.5))
    0.87758256189
    >>> print(cos(0.5+0j))
    (0.87758256189+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

def sin(x):
    """Return the sine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(sin(Decimal('0.5')))
    0.4794255386042030002732879352
    >>> print(sin(0.5))
    0.479425538604
    >>> print(sin(0.5+0j))
    (0.479425538604+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s
@end example

@c %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@node Decimal 常见问题,,例程,decimal --- 十进制定点和浮点运算
@anchor{library/decimal decimal-faq}@anchor{1c98}@anchor{library/decimal id1}@anchor{1c99}
@subsubsection Decimal 常见问题


Q. 总是输入 @code{decimal.Decimal('1234.5')} 是否过于笨拙。 在使用交互解释器时有没有最小化输入量的方式？

A. 有些用户会将构造器简写为一个字母：

@example
>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')
@end example

Q. 在带有两个十进制位的定点数应用中，有些输入值具有许多位，需要被舍入。 另一些数则不应具有多余位，需要验证有效性。 这种情况应该用什么方法？

A. 用 @code{quantize()} 方法舍入到固定数量的十进制位。 如果设置了 @ref{1c07,,Inexact} 陷阱，它也适用于验证有效性：

@example
>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
@end example

@example
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
@end example

@example
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
@end example

@example
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None
@end example

Q. 当我使用两个有效位的输入时，我要如何在一个应用中保持有效位不变？

A. 某些运算例如与整数相加、相减和相乘将会自动保留固定的小数位数。 其他运算，例如相除和非整数相乘则将会改变小数位数，需要再加上 @code{quantize()} 处理步骤：

@example
>>> a = Decimal('102.72')           # Initial fixed-point values
>>> b = Decimal('3.17')
>>> a + b                           # Addition preserves fixed-point
Decimal('105.89')
>>> a - b
Decimal('99.55')
>>> a * 42                          # So does integer multiplication
Decimal('4314.24')
>>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
Decimal('325.62')
>>> (b / a).quantize(TWOPLACES)     # And quantize division
Decimal('0.03')
@end example

在开发定点数应用时，更方便的做法是定义处理 @code{quantize()} 步骤的函数：

@example
>>> def mul(x, y, fp=TWOPLACES):
...     return (x * y).quantize(fp)
>>> def div(x, y, fp=TWOPLACES):
...     return (x / y).quantize(fp)
@end example

@example
>>> mul(a, b)                       # Automatically preserve fixed-point
Decimal('325.62')
>>> div(b, a)
Decimal('0.03')
@end example

Q. 表示同一个值有许多方式。 数字 @code{200}, @code{200.000}, @code{2E2} 和 @code{02E+4} 的值都相同但有精度不同。 是否有办法将它们转换为一个可识别的规范值？

A. @code{normalize()} 方法可将所有相同的值映射为统一表示形式：

@example
>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
@end example

Q. 有些十进制值总是被打印为指数表示形式。 是否有办法得到一个非指数表示形式？

A. 对于某些值来说，指数表示形式是表示系数中有效位的唯一办法。 例如，将 @code{5.0E+3} 表示为 @code{5000} 可以让值保持恒定，但是无法显示原本的两位有效数字。

如果一个应用不必关心追踪有效位，则可以很容易地移除指数和末尾的零，丢弃有效位但让值保持不变：

@example
>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
@end example

@example
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
@end example

Q. 是否有办法将一个普通浮点数转换为 @ref{2c7,,Decimal}？

A. 是的，任何二进制浮点数都可以精确地表示为 Decimal 值，但完全精确的转换可能需要比平常感觉更高的精度：

@example
>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')
@end example

Q. 在一个复杂的计算中，我怎样才能保证不会得到由精度不足和舍入异常所导致的虚假结果。

A. 使用 decimal 模块可以很容易地检测结果。 最好的做法是使用更高的精度和不同的舍入模式重新进行计算。 明显不同的结果表明存在精度不足、舍入模式问题、不符合条件的输入或是结果不稳定的算法。

Q. 我发现上下文精度的应用只针对运算结果而不针对输入。在混合使用不同精度的值时有什么需要注意的吗？

A. 是的。 原则上所有值都会被视为精确值，在这些值上进行的算术运算也是如此。 只有结果会被舍入。 对于输入来说其好处是“所输入即所得”。 而其缺点则是如果你忘记了输入没有被舍入，结果看起来可能会很奇怪：

@example
>>> getcontext().prec = 3
>>> Decimal('3.104') + Decimal('2.104')
Decimal('5.21')
>>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Decimal('5.20')
@end example

解决办法是提高精度或使用单目加法运算对输入执行强制舍入：

@example
>>> getcontext().prec = 3
>>> +Decimal('1.23456789')      # unary plus triggers rounding
Decimal('1.23')
@end example

此外，还可以使用 @ref{ad4,,Context.create_decimal()} 方法在创建输入时执行舍入：

@example
>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')
@end example

Q. CPython 实现对于巨大数字是否足够快速？

A. 是的。 在 CPython 和 PyPy3 实现中，decimal 模块的 C/CFFI 版本集成了高速 libmpdec@footnote{https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html} 库用于实现任意精度正确舍入的十进制浮点算术 @footnote{@w{(1)} 

3.3 新版功能.

}。 @code{libmpdec} 会对中等大小的数字使用 Karatsuba 乘法@footnote{https://en.wikipedia.org/wiki/Karatsuba_algorithm} 而对非常巨大的数字使用 数字原理变换@footnote{https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform}。

必须要对任意精度算术适配上下文。 @code{Emin} 和 @code{Emax} 应当总是设为最大值，@code{clamp} 应当总是设为 0 (默认值)。 设置 @code{prec} 需要十分谨慎。

进行大数字算术的最便捷方式也是使用 @code{prec} 的最大值 @footnote{@w{(2)} 

在 3.9 版更改: 此方式现在适用于除了非整数乘方以外的所有精确结果。

}:

@example
>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
>>> x = Decimal(2) ** 256
>>> x / 128
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
@end example

对于不精确的结果，在 64 位平台上 @ref{1c46,,MAX_PREC} 的值太大了，可用的内存将会不足:

@example
>>> Decimal(1) / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError
@end example

在具有超量分配的系统上 (即 Linux)，一种更复杂的方式根据可用的 RAM 大小来调整 @code{prec}。 假设你有 8GB 的 RAM 并期望同时有 10 个操作数，每个最多使用 500MB:

@example
>>> import sys
>>>
>>> # Maximum number of digits for a single operand using 500MB in 8-byte words
>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
>>> maxdigits = 19 * ((500 * 1024**2) // 8)
>>>
>>> # Check that this works:
>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
>>> c.traps[Inexact] = True
>>> setcontext(c)
>>>
>>> # Fill the available precision with nines:
>>> x = Decimal(0).logical_invert() * 9
>>> sys.getsizeof(x)
524288112
>>> x + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  decimal.Inexact: [<class 'decimal.Inexact'>]
@end example

总体而言（特别是在没有超量分配的系统上），如果期望所有计算都是精确的则推荐预估更严格的边界并设置 @ref{1c07,,Inexact} 陷阱。

@node fractions --- 分数,random --- 生成伪随机数,decimal --- 十进制定点和浮点运算,数字和数学模块
@anchor{library/fractions doc}@anchor{1c9a}@anchor{library/fractions fractions-rational-numbers}@anchor{1c9b}@anchor{library/fractions module-fractions}@anchor{81}
@subsection @code{fractions} --- 分数


@geindex fractions (模块)

@strong{源代码} Lib/fractions.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/fractions.py}


__________________________________________________________________


@ref{81,,fractions} 模块支持分数运算。

分数实例可以由一对整数，一个分数，或者一个字符串构建而成。

@geindex Fraction (fractions 中的类)
@anchor{library/fractions fractions Fraction}@anchor{2c5}
@deffn {类} fractions.Fraction (numerator=0, denominator=1)

@deffnx {类} fractions.Fraction (other_fraction)

@deffnx {类} fractions.Fraction (float)

@deffnx {类} fractions.Fraction (decimal)

@deffnx {类} fractions.Fraction (string)

第一个版本要求 @emph{numerator} 和 @emph{denominator} 是 @ref{d28,,numbers.Rational} 的实例，并返回一个新的 @ref{2c5,,Fraction} 实例，其值为 @code{numerator/denominator}。 如果 @emph{denominator} 为 @code{0} 将会引发 @ref{1fb,,ZeroDivisionError}。 第二个版本要求 @emph{other_fraction} 是 @ref{d28,,numbers.Rational} 的实例，并返回一个 @ref{2c5,,Fraction} 实例且与传入值相等。 下两个版本接受 @ref{1fe,,float} 或 @ref{2c7,,decimal.Decimal} 的实例，并返回一个 @ref{2c5,,Fraction} 实例且与传入值完全相等。 请注意由于二进制浮点数通常存在的问题 (参见 @ref{1487,,浮点算术：争议和限制})，@code{Fraction(1.1)} 的参数并不会精确等于 11/10，因此 @code{Fraction(1.1)} 也 @emph{不会} 返回用户所期望的 @code{Fraction(11, 10)}。 （请参阅下文中 @ref{1c9c,,limit_denominator()} 方法的文档。） 构造器的最后一个版本接受一个字符串或 unicode 实例。 此实例的通常形式为:

@example
[sign] numerator ['/' denominator]
@end example

其中的可选项 @code{sign} 可以为 '+' 或 '-' 并且 @code{numerator} 和 @code{denominator} (如果存在) 是十进制数码的字符串。 此外，@ref{1fe,,float} 构造器所接受的任何表示一个有限值的字符串也都为 @ref{2c5,,Fraction} 构造器所接受。 不论哪种形式的输入字符串也都可以带有前缀和/或后缀的空格符。 这里是一些示例:

@example
>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)
@end example

@ref{2c5,,Fraction} 类继承自抽象基类 @ref{d28,,numbers.Rational}，并实现了该类的所有方法和操作。 @ref{2c5,,Fraction} 实例是可哈希的，并应当被视为不可变对象。 此外，@ref{2c5,,Fraction} 还具有以下属性和方法：


在 3.2 版更改: @ref{2c5,,Fraction} 构造器现在接受 @ref{1fe,,float} 和 @ref{2c7,,decimal.Decimal} 实例。



在 3.9 版更改: 现在会使用 @ref{1bf,,math.gcd()} 函数来正规化 @emph{numerator} 和 @emph{denominator}。 @ref{1bf,,math.gcd()} 总是返回 @ref{205,,int} 类型。 在之前版本中，GCD 的类型取决于 @emph{numerator} 和 @emph{denominator} 的类型。


@geindex numerator (fractions.Fraction 属性)
@anchor{library/fractions fractions Fraction numerator}@anchor{1c9d}
@deffn {属性} numerator

最简分数形式的分子。
@end deffn

@geindex denominator (fractions.Fraction 属性)
@anchor{library/fractions fractions Fraction denominator}@anchor{1c9e}
@deffn {属性} denominator

最简分数形式的分母。
@end deffn

@geindex as_integer_ratio() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction as_integer_ratio}@anchor{1c9f}
@deffn {方法} as_integer_ratio ()

返回由两个整数组成的元组，两数之比等于该分数的值且其分母为正数。


3.8 新版功能.

@end deffn

@geindex from_float() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction from_float}@anchor{c5b}
@deffn {方法} from_float (flt)

此类方法可构造一个 @ref{2c5,,Fraction} 来表示 @emph{flt} 的精确值，该参数必须是一个 @ref{1fe,,float}。 请注意 @code{Fraction.from_float(0.3)} 的值并不等于 @code{Fraction(3, 10)}。

@cartouche
@quotation 注解 
从 Python 3.2 开始，在构造 @ref{2c5,,Fraction} 实例时可以直接使用 @ref{1fe,,float}。
@end quotation
@end cartouche
@end deffn

@geindex from_decimal() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction from_decimal}@anchor{c5c}
@deffn {方法} from_decimal (dec)

此类方法可构造一个 @ref{2c5,,Fraction} 来表示 @emph{dec} 的精确值，该参数必须是一个 @ref{2c7,,decimal.Decimal} 实例。

@cartouche
@quotation 注解 
从 Python 3.2 开始，在构造 @ref{2c5,,Fraction} 实例时可以直接使用 @ref{2c7,,decimal.Decimal} 实例。
@end quotation
@end cartouche
@end deffn

@geindex limit_denominator() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction limit_denominator}@anchor{1c9c}
@deffn {方法} limit_denominator (max_denominator=1000000)

找到并返回一个 @ref{2c5,,Fraction} 使得其值最接近 @code{self} 并且分母不大于 max_denominator。 此方法适用于找出给定浮点数的有理数近似值：

@example
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)
@end example

或是用来恢复被表示为一个浮点数的有理数：

@example
>>> from math import pi, cos
>>> Fraction(cos(pi/3))
Fraction(4503599627370497, 9007199254740992)
>>> Fraction(cos(pi/3)).limit_denominator()
Fraction(1, 2)
>>> Fraction(1.1).limit_denominator()
Fraction(11, 10)
@end example
@end deffn

@geindex __floor__() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction __floor__}@anchor{1ca0}
@deffn {方法} __floor__ ()

返回最大的 @ref{205,,int} @code{<= self}。 此方法也可通过 @ref{dfa,,math.floor()} 函数来使用：

@example
>>> from math import floor
>>> floor(Fraction(355, 113))
3
@end example
@end deffn

@geindex __ceil__() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction __ceil__}@anchor{1ca1}
@deffn {方法} __ceil__ ()

返回最小的 @ref{205,,int} @code{>= self}。 此方法也可通过 @ref{dfb,,math.ceil()} 函数来使用。
@end deffn

@geindex __round__() (fractions.Fraction 方法)
@anchor{library/fractions fractions Fraction __round__}@anchor{1ca2}
@deffn {方法} __round__ ()

@deffnx {方法} __round__ (ndigits)

第一个版本返回一个 @ref{205,,int} 使得其值最接近 @code{self}，位值为二分之一时只对偶数舍入。第二个版本会将 @code{self} 舍入到最接近 @code{Fraction(1, 10**ndigits)} 的倍数（如果 @code{ndigits} 为负值则为逻辑运算），位值为二分之一时同样只对偶数舍入。 此方法也可通过 @ref{d3d,,round()} 函数来使用。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item @ref{c1,,numbers} 模块

构成数字塔的所有抽象基类。
@end table


@node random --- 生成伪随机数,statistics --- 数学统计函数,fractions --- 分数,数字和数学模块
@anchor{library/random doc}@anchor{1ca3}@anchor{library/random module-random}@anchor{dc}@anchor{library/random random-generate-pseudo-random-numbers}@anchor{1ca4}
@subsection @code{random} --- 生成伪随机数


@geindex random (模块)

@strong{源码：} Lib/random.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/random.py}


__________________________________________________________________


该模块实现了各种分布的伪随机数生成器。

对于整数，从范围中有统一的选择。 对于序列，存在随机元素的统一选择、用于生成列表的随机排列的函数、以及用于随机抽样而无需替换的函数。

在实数轴上，有计算均匀、正态（高斯）、对数正态、负指数、伽马和贝塔分布的函数。 为了生成角度分布，可以使用 von Mises 分布。

几乎所有模块函数都依赖于基本函数 @ref{1ca5,,random()} ，它在半开放区间 [0.0,1.0) 内均匀生成随机浮点数。 Python 使用 Mersenne Twister 作为核心生成器。 它产生 53 位精度浮点数，周期为 2**19937-1 ，其在 C 中的底层实现既快又线程安全。 Mersenne Twister 是现存最广泛测试的随机数发生器之一。 但是，因为完全确定性，它不适用于所有目的，并且完全不适合加密目的。

这个模块提供的函数实际上是 @ref{1ca6,,random.Random} 类的隐藏实例的绑定方法。 你可以实例化自己的 @ref{1ca6,,Random} 类实例以获取不共享状态的生成器。

如果你想使用自己设计的不同基础生成器，类 @ref{1ca6,,Random} 也可以作为子类：在这种情况下，重载 @code{random()} 、 @code{seed()} 、 @code{getstate()} 以及 @code{setstate()} 方法。可选地，新生成器可以提供 @code{getrandbits()} 方法——这允许 @ref{c93,,randrange()} 在任意大的范围内产生选择。

@ref{dc,,random} 模块还提供 @ref{1ca7,,SystemRandom} 类，它使用系统函数 @ref{5d4,,os.urandom()} 从操作系统提供的源生成随机数。

@cartouche
@quotation 警告 
不应将此模块的伪随机生成器用于安全目的。 有关安全性或加密用途，请参阅 @ref{e4,,secrets} 模块。
@end quotation
@end cartouche


@subsubheading 参见


M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
equidistributed uniform pseudorandom number generator", ACM Transactions on
Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.

Complementary-Multiply-with-Carry recipe@footnote{https://code.activestate.com/recipes/576707/} 用于兼容的替代随机数发生器，具有长周期和相对简单的更新操作。


@menu
* 簿记功能:: 
* 用于字节数据的函数:: 
* 整数用函数:: 
* 序列用函数:: 
* 实值分布:: 
* 替代生成器:: 
* 关于再现性的说明:: 
* 例子:: 
* 例程: 例程<2>. 

@end menu

@node 簿记功能,用于字节数据的函数,,random --- 生成伪随机数
@anchor{library/random bookkeeping-functions}@anchor{1ca8}
@subsubsection 簿记功能


@geindex seed() (在 random 模块中)
@anchor{library/random random seed}@anchor{cdb}
@deffn {函数} random.seed (a=None, version=2)

初始化随机数生成器。

如果 @emph{a} 被省略或为 @code{None} ，则使用当前系统时间。 如果操作系统提供随机源，则使用它们而不是系统时间（有关可用性的详细信息，请参阅 @ref{5d4,,os.urandom()} 函数）。

如果 @emph{a} 是 int 类型，则直接使用。

对于版本2（默认的），@ref{206,,str} 、 @ref{172,,bytes} 或 @ref{173,,bytearray} 对象转换为 @ref{205,,int} 并使用它的所有位。

对于版本1（用于从旧版本的Python再现随机序列），用于 @ref{206,,str} 和 @ref{172,,bytes} 的算法生成更窄的种子范围。


在 3.2 版更改: 已移至版本2方案，该方案使用字符串种子中的所有位。



3.9 版后已移除: 在将来，@emph{seed} 必须是下列类型之一: @emph{NoneType}, @ref{205,,int}, @ref{1fe,,float}, @ref{206,,str}, @ref{172,,bytes} 或 @ref{173,,bytearray}。

@end deffn

@geindex getstate() (在 random 模块中)
@anchor{library/random random getstate}@anchor{1ca9}
@deffn {函数} random.getstate ()

返回捕获生成器当前内部状态的对象。 这个对象可以传递给 @ref{1caa,,setstate()} 来恢复状态。
@end deffn

@geindex setstate() (在 random 模块中)
@anchor{library/random random setstate}@anchor{1caa}
@deffn {函数} random.setstate (state)

@emph{state} 应该是从之前调用 @ref{1ca9,,getstate()} 获得的，并且 @ref{1caa,,setstate()} 将生成器的内部状态恢复到 @ref{1ca9,,getstate()} 被调用时的状态。
@end deffn

@node 用于字节数据的函数,整数用函数,簿记功能,random --- 生成伪随机数
@anchor{library/random functions-for-bytes}@anchor{1cab}
@subsubsection 用于字节数据的函数


@geindex randbytes() (在 random 模块中)
@anchor{library/random random randbytes}@anchor{1099}
@deffn {函数} random.randbytes (n)

生成 @emph{n} 个随机字节。

此方法不可用于生成安全凭据。 那应当使用 @ref{1cac,,secrets.token_bytes()}。


3.9 新版功能.

@end deffn

@node 整数用函数,序列用函数,用于字节数据的函数,random --- 生成伪随机数
@anchor{library/random functions-for-integers}@anchor{1cad}
@subsubsection 整数用函数


@geindex randrange() (在 random 模块中)
@anchor{library/random random randrange}@anchor{c93}
@deffn {函数} random.randrange (stop)

@deffnx {函数} random.randrange (start, stop[, step])

从 @code{range(start, stop, step)} 返回一个随机选择的元素。 这相当于 @code{choice(range(start, stop, step))} ，但实际上并没有构建一个 range 对象。

位置参数模式匹配 @ref{1f6,,range()} 。不应使用关键字参数，因为该函数可能以意外的方式使用它们。


在 3.2 版更改: @ref{c93,,randrange()} 在生成均匀分布的值方面更为复杂。 以前它使用了像`@w{`}int(random()*n)`@w{`}这样的形式，它可以产生稍微不均匀的分布。

@end deffn

@geindex randint() (在 random 模块中)
@anchor{library/random random randint}@anchor{c94}
@deffn {函数} random.randint (a, b)

返回随机整数 @emph{N} 满足 @code{a <= N <= b}。相当于 @code{randrange(a, b+1)}。
@end deffn

@geindex getrandbits() (在 random 模块中)
@anchor{library/random random getrandbits}@anchor{a20}
@deffn {函数} random.getrandbits (k)

返回具有 @emph{k} 个随机比特位的非负 Python 整数。 此方法随 MersenneTwister 生成器一起提供，其他一些生成器也可能将其作为 API 的可选部分提供。 在可能的情况下，@ref{a20,,getrandbits()} 会启用 @ref{c93,,randrange()} 来处理任意大的区间。


在 3.9 版更改: 此方法现在接受零作为 @emph{k} 的值。

@end deffn

@node 序列用函数,实值分布,整数用函数,random --- 生成伪随机数
@anchor{library/random functions-for-sequences}@anchor{1cae}
@subsubsection 序列用函数


@geindex choice() (在 random 模块中)
@anchor{library/random random choice}@anchor{c95}
@deffn {函数} random.choice (seq)

从非空序列 @emph{seq} 返回一个随机元素。 如果 @emph{seq} 为空，则引发 @ref{f3d,,IndexError}。
@end deffn

@geindex choices() (在 random 模块中)
@anchor{library/random random choices}@anchor{675}
@deffn {函数} random.choices (population, weights=None, *, cum_weights=None, k=1)

从 @emph{population} 中有重复地随机选取元素，返回大小为 @emph{k} 的元素列表。 如果 @emph{population} 为空，则引发 @ref{f3d,,IndexError}。

如果指定了 @emph{weight} 序列，则根据相对权重进行选择。 或者，如果给出 @emph{cum_weights} 序列，则根据累积权重（可能使用 @ref{315,,itertools.accumulate()} 计算）进行选择。 例如，相对权重`@w{`}[10, 5, 30, 5]`@w{`}相当于累积权重`@w{`}[10, 15, 45, 50]`@w{`}。 在内部，相对权重在进行选择之前会转换为累积权重，因此提供累积权重可以节省工作量。

如果既未指定 @emph{weight} 也未指定 @emph{cum_weights} ，则以相等的概率进行选择。 如果提供了权重序列，则它必须与 @emph{population} 序列的长度相同。 一个 @ref{1ff,,TypeError} 指定了 @emph{weights} 和*cum_weights*。

@emph{weights} 或 @emph{cum_weights} 可使用 @ref{dc,,random()} 所返回的能与 @ref{1fe,,float} 值进行相互运算的任何数字类型（包括 int、float、Fraction 但不包括 Decimal）。 权重为负值的行为未有定义。 如果权重为负值则将引发 @ref{16d,,ValueError}。

对于给定的种子，具有相等加权的 @ref{675,,choices()} 函数通常产生与重复调用 @ref{c95,,choice()} 不同的序列。 @ref{675,,choices()} 使用的算法使用浮点运算来实现内部一致性和速度。 @ref{c95,,choice()}  使用的算法默认为重复选择的整数运算，以避免因舍入误差引起的小偏差。


3.6 新版功能.



在 3.9 版更改: 如果所有权重均为负值则将引发 @ref{16d,,ValueError}。

@end deffn

@geindex shuffle() (在 random 模块中)
@anchor{library/random random shuffle}@anchor{213}
@deffn {函数} random.shuffle (x[, random])

将序列 @emph{x} 随机打乱位置。

可选参数 @emph{random} 是一个0参数函数，在 [0.0, 1.0) 中返回随机浮点数；默认情况下，这是函数 @ref{1ca5,,random()} 。

要改变一个不可变的序列并返回一个新的打乱列表，请使用`@w{`}sample(x, k=len(x))`@w{`}。

请注意，即使对于小的 @code{len(x)}，@emph{x} 的排列总数也可以快速增长，大于大多数随机数生成器的周期。 这意味着长序列的大多数排列永远不会产生。 例如，长度为2080的序列是可以在 Mersenne Twister 随机数生成器的周期内拟合的最大序列。


Deprecated since version 3.9, will be removed in version 3.11: 可选形参 @emph{random}。

@end deffn

@geindex sample() (在 random 模块中)
@anchor{library/random random sample}@anchor{c96}
@deffn {函数} random.sample (population, k, *, counts=None)

返回从总体序列或集合中选择的唯一元素的 @emph{k} 长度列表。 用于无重复的随机抽样。

返回包含来自总体的元素的新列表，同时保持原始总体不变。 结果列表按选择顺序排列，因此所有子切片也将是有效的随机样本。 这允许抽奖获奖者（样本）被划分为大奖和第二名获胜者（子切片）。

总体成员不必是 @ref{277,,hashable} 或 unique 。 如果总体包含重复，则每次出现都是样本中可能的选择。

重复的元素可以一个个地直接列出，或使用可选的仅限关键字形参 @emph{counts} 来指定。 例如，@code{sample(['red', 'blue'], counts=[4, 2], k=5)} 等价于 @code{sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)}。

要从一系列整数中选择样本，请使用 @ref{1f6,,range()} 对象作为参数。 对于从大量人群中采样，这种方法特别快速且节省空间：@code{sample(range(10000000), k=60)} 。

如果样本大小大于总体大小，则引发 @ref{16d,,ValueError} 。


在 3.9 版更改: 增加了 @emph{counts} 形参。



3.9 版后已移除: 在将来，@emph{population} 必须是一个序列。 @ref{1f7,,set} 的实例将不再被支持。 集合必须先转换为 @ref{1f9,,list} 或 @ref{1a2,,tuple}，最好是固定顺序以使抽样是可重现的。

@end deffn

@node 实值分布,替代生成器,序列用函数,random --- 生成伪随机数
@anchor{library/random id1}@anchor{1caf}@anchor{library/random real-valued-distributions}@anchor{1cb0}
@subsubsection 实值分布


以下函数生成特定的实值分布。如常用数学实践中所使用的那样, 函数参数以分布方程中的相应变量命名;大多数这些方程都可以在任何统计学教材中找到。

@geindex random() (在 random 模块中)
@anchor{library/random random random}@anchor{1ca5}
@deffn {函数} random.random ()

返回 [0.0, 1.0) 范围内的下一个随机浮点数。
@end deffn

@geindex uniform() (在 random 模块中)
@anchor{library/random random uniform}@anchor{1cb1}
@deffn {函数} random.uniform (a, b)

返回一个随机浮点数 @emph{N} ，当 @code{a <= b} 时 @code{a <= N <= b} ，当 @code{b < a} 时 @code{b <= N <= a} 。

取决于等式 @code{a + (b-a) * random()} 中的浮点舍入，终点 @code{b} 可以包括或不包括在该范围内。
@end deffn

@geindex triangular() (在 random 模块中)
@anchor{library/random random triangular}@anchor{1cb2}
@deffn {函数} random.triangular (low, high, mode)

返回一个随机浮点数 @emph{N} ，使得 @code{low <= N <= high} 并在这些边界之间使用指定的 @emph{mode} 。 @emph{low} 和 @emph{high} 边界默认为零和一。 @emph{mode} 参数默认为边界之间的中点，给出对称分布。
@end deffn

@geindex betavariate() (在 random 模块中)
@anchor{library/random random betavariate}@anchor{1cb3}
@deffn {函数} random.betavariate (alpha, beta)

Beta 分布。 参数的条件是 @code{alpha > 0} 和 @code{beta > 0}。 返回值的范围介于 0 和 1 之间。
@end deffn

@geindex expovariate() (在 random 模块中)
@anchor{library/random random expovariate}@anchor{1cb4}
@deffn {函数} random.expovariate (lambd)

指数分布。 @emph{lambd} 是 1.0 除以所需的平均值，它应该是非零的。 （该参数本应命名为 “lambda” ，但这是 Python 中的保留字。）如果 @emph{lambd} 为正，则返回值的范围为 0 到正无穷大；如果 @emph{lambd} 为负，则返回值从负无穷大到 0。
@end deffn

@geindex gammavariate() (在 random 模块中)
@anchor{library/random random gammavariate}@anchor{1cb5}
@deffn {函数} random.gammavariate (alpha, beta)

Gamma 分布。 （ @emph{不是} gamma 函数！ ） 参数的条件是 @code{alpha > 0} 和 @code{beta > 0}。

概率分布函数是:

@example
          x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) =  --------------------------------------
            math.gamma(alpha) * beta ** alpha
@end example
@end deffn

@geindex gauss() (在 random 模块中)
@anchor{library/random random gauss}@anchor{1cb6}
@deffn {函数} random.gauss (mu, sigma)

高斯分布。 @emph{mu} 是平均值，@emph{sigma} 是标准差。 这比下面定义的 @ref{1cb7,,normalvariate()} 函数略快。

多线程注意事项：当两个线程同时调用此方法时，它们有可能将获得相同的返回值。 这可以通过三种办法来避免。 1) 让每个线程使用不同的随机数生成器实例。 2) 在所有调用外面加锁。 3) 改用速度较慢但是线程安全的 @ref{1cb7,,normalvariate()} 函数。
@end deffn

@geindex lognormvariate() (在 random 模块中)
@anchor{library/random random lognormvariate}@anchor{1cb8}
@deffn {函数} random.lognormvariate (mu, sigma)

对数正态分布。 如果你采用这个分布的自然对数，你将得到一个正态分布，平均值为 @emph{mu} 和标准差为 @emph{sigma} 。 @emph{mu} 可以是任何值，@emph{sigma} 必须大于零。
@end deffn

@geindex normalvariate() (在 random 模块中)
@anchor{library/random random normalvariate}@anchor{1cb7}
@deffn {函数} random.normalvariate (mu, sigma)

正态分布。 @emph{mu} 是平均值，@emph{sigma} 是标准差。
@end deffn

@geindex vonmisesvariate() (在 random 模块中)
@anchor{library/random random vonmisesvariate}@anchor{1cb9}
@deffn {函数} random.vonmisesvariate (mu, kappa)

冯·米塞斯分布。 @emph{mu} 是平均角度，以弧度表示，介于0和 2*@emph{pi} 之间，@emph{kappa} 是浓度参数，必须大于或等于零。 如果 @emph{kappa} 等于零，则该分布在 0 到 2*@emph{pi} 的范围内减小到均匀的随机角度。
@end deffn

@geindex paretovariate() (在 random 模块中)
@anchor{library/random random paretovariate}@anchor{1cba}
@deffn {函数} random.paretovariate (alpha)

帕累托分布。 @emph{alpha} 是形状参数。
@end deffn

@geindex weibullvariate() (在 random 模块中)
@anchor{library/random random weibullvariate}@anchor{1cbb}
@deffn {函数} random.weibullvariate (alpha, beta)

威布尔分布。 @emph{alpha} 是比例参数，@emph{beta} 是形状参数。
@end deffn

@node 替代生成器,关于再现性的说明,实值分布,random --- 生成伪随机数
@anchor{library/random alternative-generator}@anchor{1cbc}
@subsubsection 替代生成器


@geindex Random (random 中的类)
@anchor{library/random random Random}@anchor{1ca6}
@deffn {类} random.Random ([seed])

该类实现了 @ref{dc,,random} 模块所用的默认伪随机数生成器。


3.9 版后已移除: 在将来，@emph{seed} 必须是下列类型之一: @code{NoneType}, @ref{205,,int}, @ref{1fe,,float}, @ref{206,,str}, @ref{172,,bytes} 或 @ref{173,,bytearray}。

@end deffn

@geindex SystemRandom (random 中的类)
@anchor{library/random random SystemRandom}@anchor{1ca7}
@deffn {类} random.SystemRandom ([seed])

使用 @ref{5d4,,os.urandom()} 函数的类，用从操作系统提供的源生成随机数。 这并非适用于所有系统。 也不依赖于软件状态，序列不可重现。 因此，@ref{cdb,,seed()} 方法没有效果而被忽略。 @ref{1ca9,,getstate()} 和 @ref{1caa,,setstate()} 方法如果被调用则引发 @ref{70e,,NotImplementedError}。
@end deffn

@node 关于再现性的说明,例子,替代生成器,random --- 生成伪随机数
@anchor{library/random notes-on-reproducibility}@anchor{1cbd}
@subsubsection 关于再现性的说明


有时能够重现伪随机数生成器给出的序列是很有用处的。 通过重用一个种子值，只要没有运行多线程，相同的序列就应当可在多次运行中重现。

大多数随机模块的算法和种子函数都会在 Python 版本中发生变化，但保证两个方面不会改变：


@itemize *

@item 
如果添加了新的播种方法，则将提供向后兼容的播种机。

@item 
当兼容的播种机被赋予相同的种子时，生成器的 @code{random()} 方法将继续产生相同的序列。
@end itemize

@node 例子,例程<2>,关于再现性的说明,random --- 生成伪随机数
@anchor{library/random examples}@anchor{1cbe}@anchor{library/random random-examples}@anchor{c33}
@subsubsection 例子


基本示例:

@example
>>> random()                             # Random float:  0.0 <= x < 1.0
0.37444887175646646

>>> uniform(2.5, 10.0)                   # Random float:  2.5 <= x <= 10.0
3.1800146073117523

>>> expovariate(1 / 5)                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange(10)                        # Integer from 0 to 9 inclusive
7

>>> randrange(0, 101, 2)                 # Even integer from 0 to 100 inclusive
26

>>> choice(['win', 'lose', 'draw'])      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split()
>>> shuffle(deck)                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement
[40, 10, 50, 30]
@end example

模拟:

@example
>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value:  ten, jack, queen, or king.
>>> dealt = sample(['tens', 'low cards'], counts=[16, 36], k=20)
>>> dealt.count('tens') / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial():
...     return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial():
...     return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.7958
@end example

statistical bootstrapping@footnote{https://en.wikipedia.org/wiki/Bootstrapping_(statistics)} 的示例，使用重新采样和替换来估计一个样本的均值的置信区间:

@example
# http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
from statistics import fmean as mean
from random import choices

data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted(mean(choices(data, k=len(data))) for i in range(100))
print(f'The sample mean of @{mean(data):.1f@} has a 90% confidence '
      f'interval from @{means[5]:.1f@} to @{means[94]:.1f@}')
@end example

使用 重新采样排列测试@footnote{https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests} 来确定统计学显著性或者使用  p-值@footnote{https://en.wikipedia.org/wiki/P-value} 来观察药物与安慰剂的作用之间差异的示例:

@example
# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)

n = 10_000
count = 0
combined = drug + placebo
for i in range(n):
    shuffle(combined)
    new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
    count += (new_diff >= observed_diff)

print(f'@{n@} label reshufflings produced only @{count@} instances with a difference')
print(f'at least as extreme as the observed difference of @{observed_diff:.1f@}.')
print(f'The one-sided p-value of @{count / n:.4f@} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')
@end example

多服务器队列的到达时间和服务交付模拟:

@example
from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, median, stdev

average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers  # time when each server becomes available
heapify(servers)
for i in range(1_000_000):
    arrival_time += expovariate(1.0 / average_arrival_interval)
    next_server_available = servers[0]
    wait = max(0.0, next_server_available - arrival_time)
    waits.append(wait)
    service_duration = max(0.0, gauss(average_service_time, stdev_service_time))
    service_completed = arrival_time + wait + service_duration
    heapreplace(servers, service_completed)

print(f'Mean wait: @{mean(waits):.1f@}.  Stdev wait: @{stdev(waits):.1f@}.')
print(f'Median wait: @{median(waits):.1f@}.  Max wait: @{max(waits):.1f@}.')
@end example


@subsubheading 参见


Statistics for Hackers@footnote{https://www.youtube.com/watch?v=Iq9DzN6mvYA} Jake Vanderplas@footnote{https://us.pycon.org/2016/speaker/profile/295/} 撰写的视频教程，使用一些基本概念进行统计分析，包括模拟、抽样、改组和交叉验证。

Economics Simulation@footnote{http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb} Peter Norvig@footnote{http://norvig.com/bio.html} 编写的市场模拟，显示了该模块提供的许多工具和分布的有效使用（高斯、均匀、样本、beta变量、选择、三角和随机范围等）。

A Concrete Introduction to Probability (using Python)@footnote{http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb} Peter Norvig@footnote{http://norvig.com/bio.html} 撰写的教程，涵盖了概率论基础知识，如何编写模拟，以及如何使用 Python 进行数据分析。


@node 例程<2>,,例子,random --- 生成伪随机数
@anchor{library/random recipes}@anchor{1cbf}
@subsubsection 例程


默认的 @ref{1ca5,,random()} 返回在 @emph{0.0 ≤ x < 1.0} 范围内 2⁻⁵³ 的倍数。 所有这些数值间隔相等并能精确表示为 Python 浮点数。 但是在此间隔上有许多其他可表示浮点数是不可能的选择。 例如，@code{0.05954861408025609} 就不是 2⁻⁵³ 的整数倍。

以下规范程序采取了一种不同的方式。 在间隔上的所有浮点数都是可能的选择。 它们的尾数取值来自 @emph{2⁵² ≤ 尾数 < 2⁵³} 范围内整数的均匀分布。 指数取值则来自几何分布，其中小于 @emph{-53} 的指数的出现频率为下一个较大指数的一半。

@example
from random import Random
from math import ldexp

class FullRandom(Random):

    def random(self):
        mantissa = 0x10_0000_0000_0000 | self.getrandbits(52)
        exponent = -53
        x = 0
        while not x:
            x = self.getrandbits(32)
            exponent += x.bit_length() - 32
        return ldexp(mantissa, exponent)
@end example

该类中所有的 @ref{1cb0,,实值分布} 都将使用新的方法:

@example
>>> fr = FullRandom()
>>> fr.random()
0.05954861408025609
>>> fr.expovariate(0.25)
8.87925541791544
@end example

该规范程序在概念上等效于在 @emph{0.0 ≤ x < 1.0} 范围内对所有 2⁻¹⁰⁷⁴ 的倍数进行选择的算法。 所有这样的数字间隔都相等，但大多必须向下舍入为最接近的 Python 浮点数表示形式。 （2⁻¹⁰⁷⁴ 这个数值是等于 @code{math.ulp(0.0)} 的未经正规化的最小正浮点数。）


@subsubheading 参见


生成伪随机浮点数值@footnote{https://allendowney.com/research/rand/downey07randfloat.pdf} 为 Allen B. Downey 所撰写的描述如何生成相比通过 @ref{1ca5,,random()} 正常生成的数值更细粒度浮点数的论文。


@node statistics --- 数学统计函数,,random --- 生成伪随机数,数字和数学模块
@anchor{library/statistics doc}@anchor{1cc0}@anchor{library/statistics module-statistics}@anchor{f5}@anchor{library/statistics statistics-mathematical-statistics-functions}@anchor{1cc1}
@subsection @code{statistics} --- 数学统计函数


@geindex statistics (模块)


3.4 新版功能.


@strong{源代码:} Lib/statistics.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/statistics.py}

@c from statistics import *
@c __name__ = '<doctest>'


__________________________________________________________________


该模块提供了用于计算数字 (@ref{1586,,Real}-valued) 数据的数理统计量的函数。

此模块并不是诸如 NumPy@footnote{https://numpy.org} ， SciPy@footnote{https://www.scipy.org/} 等第三方库或者诸如 Minitab ， SAS ， Matlab 等针对专业统计学家的专有全功能统计软件包的竞品。此模块针对图形和科学计算器的水平。

除非明确注释，这些函数支持 @ref{205,,int} ， @ref{1fe,,float} ， @ref{2c7,,Decimal} 和 @ref{2c5,,Fraction} 。当前不支持同其他类型（是否在数字塔中）的行为。混合类型的集合也是未定义的，并且依赖于实现。如果你输入的数据由混合类型组成，你应该能够使用 @ref{cff,,map()} 来确保一个一致的结果，比如： @code{map(float, input_data)} 。

@menu
* 平均值以及对中心位置的评估:: 
* 对分散程度的评估:: 
* 函数细节:: 
* 异常: 异常<4>. 
* NormalDist 对象:: 

@end menu

@node 平均值以及对中心位置的评估,对分散程度的评估,,statistics --- 数学统计函数
@anchor{library/statistics averages-and-measures-of-central-location}@anchor{1cc2}
@subsubsection 平均值以及对中心位置的评估


这些函数用于计算一个总体或样本的平均值或者典型值。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2d5,,mean()}

@tab

数据的算术平均数（“平均数”）。

@item

@ref{35b,,fmean()}

@tab

快速的，浮点算数平均数。

@item

@ref{35c,,geometric_mean()}

@tab

数据的几何平均数

@item

@ref{690,,harmonic_mean()}

@tab

数据的调和均值

@item

@ref{1cc3,,median()}

@tab

数据的中位数（中间值）

@item

@ref{1cc4,,median_low()}

@tab

数据的低中位数

@item

@ref{1cc5,,median_high()}

@tab

数据的高中位数

@item

@ref{1cc6,,median_grouped()}

@tab

分组数据的中位数，即第50个百分点。

@item

@ref{3e5,,mode()}

@tab

离散的或标称的数据的单个众数（出现最多的值）。

@item

@ref{35d,,multimode()}

@tab

离散的或标称的数据的众数列表（出现最多的值）。

@item

@ref{35e,,quantiles()}

@tab

将数据以相等的概率分为多个间隔。

@end multitable


@node 对分散程度的评估,函数细节,平均值以及对中心位置的评估,statistics --- 数学统计函数
@anchor{library/statistics measures-of-spread}@anchor{1cc7}
@subsubsection 对分散程度的评估


这些函数用于计算总体或样本与典型值或平均值的偏离程度。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{1cc8,,pstdev()}

@tab

数据的总体标准差

@item

@ref{1cc9,,pvariance()}

@tab

数据的总体方差

@item

@ref{1cca,,stdev()}

@tab

数据的样本标准差

@item

@ref{1ccb,,variance()}

@tab

数据的样本方差

@end multitable


@node 函数细节,异常<4>,对分散程度的评估,statistics --- 数学统计函数
@anchor{library/statistics function-details}@anchor{1ccc}
@subsubsection 函数细节


注释：这些函数不需要对提供给它们的数据进行排序。但是，为了方便阅读，大多数例子展示的是已排序的序列。

@geindex mean() (在 statistics 模块中)
@anchor{library/statistics statistics mean}@anchor{2d5}
@deffn {函数} statistics.mean (data)

返回 @emph{data} 的样本算术平均数，形式为序列或迭代器。

算术平均数是数据之和与数据点个数的商。通常称作“平均数”，尽管它指示诸多数学平均数之一。它是数据的中心位置的度量。

若 @emph{data} 为空，将会引发 @ref{1ccd,,StatisticsError}。

一些用法示例：

@example
>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
@end example

@cartouche
@quotation 注解 
平均数会受到 异常值@footnote{https://en.wikipedia.org/wiki/Outlier} 的强烈影响因而不一定能作为数据点的典型样本。 想获得对于 集中趋势@footnote{https://en.wikipedia.org/wiki/Central_tendency} 的更可靠的度量，可以参看 @ref{1cc3,,median()}，但其效率要低一些。

样本均值给出了一个无偏向的真实总体均值的估计，因此当平均抽取所有可能的样本， @code{mean(sample)} 收敛于整个总体的真实均值。如果 @emph{data} 代表整个总体而不是样本，那么 @code{mean(data)} 等同于计算真实整体均值 μ 。
@end quotation
@end cartouche
@end deffn

@geindex fmean() (在 statistics 模块中)
@anchor{library/statistics statistics fmean}@anchor{35b}
@deffn {函数} statistics.fmean (data)

将 @emph{data} 转换成浮点数并且计算算术平均数。

此函数的运行速度比 @ref{2d5,,mean()} 函数快并且它总是返回一个 @ref{1fe,,float}。 @emph{data} 可以为序列或可迭代对象。 如果输入数据集为空，则会引发 @ref{1ccd,,StatisticsError}。

@example
>>> fmean([3.5, 4.0, 5.25])
4.25
@end example


3.8 新版功能.

@end deffn

@geindex geometric_mean() (在 statistics 模块中)
@anchor{library/statistics statistics geometric_mean}@anchor{35c}
@deffn {函数} statistics.geometric_mean (data)

将 @emph{data} 转换成浮点数并且计算几何平均数。

几何平均值使用值的乘积表示 @emph{数据} 的中心趋势或典型值（与使用它们的总和的算术平均值相反）。

如果输入数据集为空、包含零或包含负值则将引发 @ref{1ccd,,StatisticsError}。 @emph{data} 可以是序列或可迭代对象。

无需做出特殊努力即可获得准确的结果。（但是，将来或许会修改。）

@example
>>> round(geometric_mean([54, 24, 36]), 1)
36.0
@end example


3.8 新版功能.

@end deffn

@geindex harmonic_mean() (在 statistics 模块中)
@anchor{library/statistics statistics harmonic_mean}@anchor{690}
@deffn {函数} statistics.harmonic_mean (data)

返回 @emph{data} 调和均值，该参数可以是序列或包含实数值的可迭代对象。

调和均值,也叫次相反均值，所有数据的倒数的算术平均数 @ref{2d5,,mean()} 的倒数。比如说，数据 @emph{a} ， @emph{b} ， @emph{c} 的调和均值等于 @code{3/(1/a + 1/b + 1/c)} 。如果其中一个值为零，结果为零。

调和均值是一种均值类型，是数据中心位置的度量。它通常适合于求比率和比例的平均值，比如速率。

假设一辆车在 40 km/hr 的速度下行驶了 10 km ，然后又以 60 km/hr 的速度行驶了 10 km 。车辆的平均速率是多少？

@example
>>> harmonic_mean([40, 60])
48.0
@end example

假设一名投资者在三家公司各购买了等价值的股票，以 2.5， 3 ， 10 的 P/E (价格/收益) 率。投资者投资组合的平均市盈率是多少？

@example
>>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
3.6
@end example

如果 @emph{data} 为空或者 任何一个元素的值小于零，会引发 @ref{1ccd,,StatisticsError} 。

当前算法在输入中遇到零时会提前退出。这意味着不会测试后续输入的有效性。（此行为将来可能会更改。）


3.6 新版功能.

@end deffn

@geindex median() (在 statistics 模块中)
@anchor{library/statistics statistics median}@anchor{1cc3}
@deffn {函数} statistics.median (data)

使用普通的“取中间两数平均值”方法返回数值数据的中位数（中间值）。 如果 @emph{data} 为空，则将引发 @ref{1ccd,,StatisticsError}。 @emph{data} 可以是序列或可迭代对象。

中位数是衡量中间位置的可靠方式，并且较少受到极端值的影响。 当数据点的总数为奇数时，将返回中间数据点：

@example
>>> median([1, 3, 5])
3
@end example

当数据点的总数为偶数时，中位数将通过对两个中间值求平均进行插值得出：

@example
>>> median([1, 3, 5, 7])
4.0
@end example

这适用于当你的数据是离散的，并且你不介意中位数不是实际数据点的情况。

如果数据是有序的（支持排序操作）但不是数字（不支持加法），请考虑改用 @ref{1cc4,,median_low()} 或 @ref{1cc5,,median_high()}。
@end deffn

@geindex median_low() (在 statistics 模块中)
@anchor{library/statistics statistics median_low}@anchor{1cc4}
@deffn {函数} statistics.median_low (data)

返回数值数据的低中位数。 如果 @emph{data} 为空则将引发 @ref{1ccd,,StatisticsError}。 @emph{data} 可以是序列或可迭代对象。

低中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当其为偶数时，将返回两个中间值中较小的那个。

@example
>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3
@end example

当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时可以使用低中位数。
@end deffn

@geindex median_high() (在 statistics 模块中)
@anchor{library/statistics statistics median_high}@anchor{1cc5}
@deffn {函数} statistics.median_high (data)

返回数据的高中位数。 如果 @emph{data} 为空则将引发 @ref{1ccd,,StatisticsError}。 @emph{data} 可以是序列或可迭代对象。

高中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当其为偶数时，将返回两个中间值中较大的那个。

@example
>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5
@end example

当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时可以使用高中位数。
@end deffn

@geindex median_grouped() (在 statistics 模块中)
@anchor{library/statistics statistics median_grouped}@anchor{1cc6}
@deffn {函数} statistics.median_grouped (data, interval=1)

返回分组的连续数据的中位数，根据第 50 个百分点的位置使用插值来计算。 如果 @emph{data} 为空则将引发 @ref{1ccd,,StatisticsError}。 @emph{data} 可以是序列或可迭代对象。

@example
>>> median_grouped([52, 52, 53, 54])
52.5
@end example

在下面的示例中，数据已经过舍入，这样每个值都代表数据分类的中间点，例如 1 是 0.5--1.5 分类的中间点，2 是 1.5--2.5 分类的中间点，3 是 2.5--3.5 的中间点等待。 根据给定的数据，中间值应落在 3.5--4.5 分类之内，并可使用插值法来进行估算：

@example
>>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7
@end example

可选参数 @emph{interval} 表示分类间隔，默认值为 1。 改变分类间隔自然会改变插件结果：

@example
>>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5
@end example

此函数不会检查数据点之间是否至少相隔 @emph{interval} 的距离。

@strong{CPython implementation detail:} 在某些情况下，@ref{1cc6,,median_grouped()} 可以会将数据点强制转换为浮点数。 此行为在未来有可能会发生改变。


@subsubheading 参见



@itemize *

@item 
"Statistics for the Behavioral Sciences", Frederick J Gravetter and
Larry B Wallnau (8th Edition).

@item 
Gnome Gnumeric 电子表格中的 SSMEDIAN@footnote{https://help.gnome.org/users/gnumeric/stable/gnumeric.html#gnumeric-function-SSMEDIAN} 函数，包括 这篇讨论@footnote{https://mail.gnome.org/archives/gnumeric-list/2011-April/msg00018.html}。
@end itemize

@end deffn

@geindex mode() (在 statistics 模块中)
@anchor{library/statistics statistics mode}@anchor{3e5}
@deffn {函数} statistics.mode (data)

从离散或标称的 @emph{data} 返回单个出现最多的数据点。 此众数（如果存在）是最典型的值，并可用来度量中心的位置。

如果存在具有相同频率的多个众数，则返回在 @emph{data} 中遇到的第一个。 如果想要其中最小或最大的一个，请使用 @code{min(multimode(data))} 或 @code{max(multimode(data))}。 如果输入的 @emph{data} 为空，则会引发 @ref{1ccd,,StatisticsError}。

@code{mode} 将假定是离散数据并返回一个单一的值。 这是通常的学校教学中标准的处理方式：

@example
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
@end example

此众数的独特之处在于它是这个包中唯一还可应用于标称（非数字）数据的统计信息：

@example
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
@end example


在 3.8 版更改: 现在会通过返回所遇到的第一个众数来处理多模数据集。 之前它会在遇到超过一个的众数时引发 @ref{1ccd,,StatisticsError}。

@end deffn

@geindex multimode() (在 statistics 模块中)
@anchor{library/statistics statistics multimode}@anchor{35d}
@deffn {函数} statistics.multimode (data)

返回最频繁出现的值的列表，并按它们在 @emph{data} 中首次出现的位置排序。 如果存在多个众数则将返回一个以上的众数，或者如果 @emph{data} 为空则将返回空列表：

@example
>>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('@w{'})
[]
@end example


3.8 新版功能.

@end deffn

@geindex pstdev() (在 statistics 模块中)
@anchor{library/statistics statistics pstdev}@anchor{1cc8}
@deffn {函数} statistics.pstdev (data, mu=None)

返回总体标准差（总体方差的平方根）。 请参阅 @ref{1cc9,,pvariance()} 了解参数和其他细节。

@example
>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251
@end example
@end deffn

@geindex pvariance() (在 statistics 模块中)
@anchor{library/statistics statistics pvariance}@anchor{1cc9}
@deffn {函数} statistics.pvariance (data, mu=None)

返回非空序列或包含实数值的可迭代对象 @emph{data} 的总体方差。 方差或称相对于均值的二阶距，是对数据变化幅度（延展度或分散度）的度量。 方差值较大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

如果给出了可选的第二个参数 @emph{mu}，它通常是 @emph{data} 的均值。 它也可以被用来计算相对于一个非均值点的二阶距。 如果该参数省略或为 @code{None} (默认值)，则会自动进行算术均值的计算。

使用此函数可根据所有数值来计算方差。 要根据一个样本来估算方差，通常 @ref{1ccb,,variance()} 函数是更好的选择。

如果 @emph{data} 为空则会引发 @ref{1ccd,,StatisticsError}。

示例：

@example
>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25
@end example

如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 @emph{mu} 传入以避免重复计算：

@example
>>> mu = mean(data)
>>> pvariance(data, mu)
1.25
@end example

同样也支持使用 Decimal 和 Fraction 值：

@example
>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)
@end example

@cartouche
@quotation 注解 
当调用时附带完整的总体数据时，这将给出总体方差 σ²。 而当调用时只附带一个样本时，这将给出偏置样本方差 s²，也被称为带有 N 个自由度的方差。

如果你通过某种方式知道了真实的总体平均值 μ，则可以使用此函数来计算一个样本的方差，并将已知的总体平均值作为第二个参数。 假设数据点是总体的一个随机样本，则结果将为总体方差的无偏估计值。
@end quotation
@end cartouche
@end deffn

@geindex stdev() (在 statistics 模块中)
@anchor{library/statistics statistics stdev}@anchor{1cca}
@deffn {函数} statistics.stdev (data, xbar=None)

返回样本标准差（样本方差的平方根）。 请参阅 @ref{1ccb,,variance()} 了解参数和其他细节。

@example
>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
@end example
@end deffn

@geindex variance() (在 statistics 模块中)
@anchor{library/statistics statistics variance}@anchor{1ccb}
@deffn {函数} statistics.variance (data, xbar=None)

返回包含至少两个实数值的可迭代对象 @emph{data} 的样本方差。 方差或称相对于均值的二阶矩，是对数据变化幅度（延展度或分散度）的度量。 方差值较大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

如果给出了可选的第二个参数 @emph{xbar}，它应当是 @emph{data} 的均值。 如果该参数省略或为 @code{None} (默认值)，则会自动进行均值的计算。

当你的数据是总体数据的样本时请使用此函数。 要根据整个总体数据来计算方差，请参见 @ref{1cc9,,pvariance()}。

如果 @emph{data} 包含的值少于两个则会引发 @ref{1ccd,,StatisticsError}。

示例：

@example
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095
@end example

如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 @emph{xbar} 传入以避免重复计算：

@example
>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095
@end example

此函数不会试图检查你所传入的 @emph{xbar} 是否为真实的平均值。 使用任意值作为 @emph{xbar} 可能导致无效或不可能的结果。

同样也支持使用 Decimal 和 Fraction 值：

@example
>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)
@end example

@cartouche
@quotation 注解 
这是附带贝塞尔校正的样本方差 s²，也称为具有 N-1 自由度的方差。 假设数据点具有代表性（即为独立且均匀的分布），则结果应当是对总体方差的无偏估计。

如果你通过某种方式知道了真实的总体平均值 μ 则应当调用 @ref{1cc9,,pvariance()} 函数并将该值作为 @emph{mu} 形参传入以得到一个样本的方差。
@end quotation
@end cartouche
@end deffn

@geindex quantiles() (在 statistics 模块中)
@anchor{library/statistics statistics quantiles}@anchor{35e}
@deffn {函数} statistics.quantiles (data, *, n=4, method='exclusive')

将 @emph{data} 分隔为具有相等概率的 @emph{n} 个连续区间。 返回分隔这些区间的 @code{n - 1} 个分隔点的列表。

将 @emph{n} 设为 4 以使用四分位（默认值）。 将 @emph{n} 设为 10 以使用十分位。 将 @emph{n} 设为 100 以使用百分位，即给出 99 个分隔点来将 @emph{data} 分隔为 100 个大小相等的组。 如果 @emph{n} 小于 1 则将引发 @ref{1ccd,,StatisticsError}。

@emph{data} 可以是包含样本数据的任意可迭代对象。 为了获得有意义的结果，@emph{data} 中数据点的数量应当大于 @emph{n}。 如果数据点的数量小于两个则将引发 @ref{1ccd,,StatisticsError}。

分隔点是通过对两个最接近的数据点进行线性插值得到的。 例如，如果一个分隔点落在两个样本值 @code{100} 和 @code{112} 之间距离三分之一的位置，则分隔点的取值将为 @code{104}。

@emph{method} 用于计算分位值，它会由于 @emph{data} 是包含还是排除总体的最低和最高可能值而有所不同。

默认 @emph{method} 是 “唯一的” 并且被用于在总体中数据采样这样可以有比样本中找到的更多的极端值。落在 @emph{m} 个排序数据点的第 @emph{i-th} 个以下的总体部分被计算为 @code{i / (m + 1)} 。给定九个样本值，方法排序它们并且分配一下的百分位： 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% 。

将 @emph{method} 设为 "inclusive" 可用于描述总体数据或已明确知道包含有总体数据中最极端值的样本。 @emph{data} 中的最小值会被作为第 0 个百分位而最大值会被作为第 100 个百分位。 总体数据里处于 @emph{m} 个已排序数据点中 @emph{第 i 个} 以下的部分会以 @code{(i - 1) / (m - 1)} 来计算。 给定 11 个样本值，该方法会对它们进行排序并赋予以下百分位: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%。

@example
# Decile cut points for empirically sampled data
>>> data = [105, 129, 87, 86, 111, 111, 89, 81, 108, 92, 110,
...         100, 75, 105, 103, 109, 76, 119, 99, 91, 103, 129,
...         106, 101, 84, 111, 74, 87, 86, 103, 103, 106, 86,
...         111, 75, 87, 102, 121, 111, 88, 89, 101, 106, 95,
...         103, 107, 101, 81, 109, 104]
>>> [round(q, 1) for q in quantiles(data, n=10)]
[81.0, 86.2, 89.0, 99.4, 102.5, 103.6, 106.0, 109.8, 111.0]
@end example


3.8 新版功能.

@end deffn

@node 异常<4>,NormalDist 对象,函数细节,statistics --- 数学统计函数
@anchor{library/statistics exceptions}@anchor{1cce}
@subsubsection 异常


只定义了一个异常：

@geindex StatisticsError
@anchor{library/statistics statistics StatisticsError}@anchor{1ccd}
@deffn {例外} statistics.StatisticsError

@ref{16d,,ValueError} 的子类，表示统计相关的异常。
@end deffn

@node NormalDist 对象,,异常<4>,statistics --- 数学统计函数
@anchor{library/statistics normaldist-objects}@anchor{1ccf}
@subsubsection @code{NormalDist} 对象


@ref{35f,,NormalDist} 工具可用于创建和操纵 随机变量@footnote{http://www.stat.yale.edu/Courses/1997-98/101/ranvar.htm} 的正态分布。 这个类将数据度量值的平均值和标准差作为单一实体来处理。

正态分布的概念来自于 中央极限定理@footnote{https://en.wikipedia.org/wiki/Central_limit_theorem} 并且在统计学中有广泛的应用。

@geindex NormalDist (statistics 中的类)
@anchor{library/statistics statistics NormalDist}@anchor{35f}
@deffn {类} statistics.NormalDist (mu=0.0, sigma=1.0)

返回一个新的 @emph{NormalDist} 对象，其中 @emph{mu} 代表 算术平均值@footnote{https://en.wikipedia.org/wiki/Arithmetic_mean} 而 @emph{sigma} 代表 标准差@footnote{https://en.wikipedia.org/wiki/Standard_deviation}。

若 @emph{sigma} 为负数，将会引发 @ref{1ccd,,StatisticsError}。

@geindex mean (statistics.NormalDist 属性)
@anchor{library/statistics statistics NormalDist mean}@anchor{1cd0}
@deffn {属性} mean

一个只读特征属性，表示特定正态分布的 算术平均值@footnote{https://en.wikipedia.org/wiki/Arithmetic_mean}。
@end deffn

@geindex median (statistics.NormalDist 属性)
@anchor{library/statistics statistics NormalDist median}@anchor{1cd1}
@deffn {属性} median

一个只读特征属性，表示特定正态分布的 中位数@footnote{https://en.wikipedia.org/wiki/Median}。
@end deffn

@geindex mode (statistics.NormalDist 属性)
@anchor{library/statistics statistics NormalDist mode}@anchor{1cd2}
@deffn {属性} mode

一个只读特征属性，表示特定正态分布的 众数@footnote{https://en.wikipedia.org/wiki/Mode_(statistics)}。
@end deffn

@geindex stdev (statistics.NormalDist 属性)
@anchor{library/statistics statistics NormalDist stdev}@anchor{1cd3}
@deffn {属性} stdev

一个只读特征属性，表示特定正态分布的 标准差@footnote{https://en.wikipedia.org/wiki/Standard_deviation}。
@end deffn

@geindex variance (statistics.NormalDist 属性)
@anchor{library/statistics statistics NormalDist variance}@anchor{1cd4}
@deffn {属性} variance

一个只读特征属性，表示特定正态分布的 方差@footnote{https://en.wikipedia.org/wiki/Variance}。 等于标准差的平方。
@end deffn

@geindex from_samples() (statistics.NormalDist 类方法)
@anchor{library/statistics statistics NormalDist from_samples}@anchor{1cd5}
@deffn {方法} classmethod from_samples (data)

传入使用 @ref{35b,,fmean()} 和 @ref{1cca,,stdev()} 基于 @emph{data} 估算出的 @emph{mu} 和 @emph{sigma} 形参创建一个正态分布实例。

@emph{data} 可以是任何 @ref{c84,,iterable} 并且应当包含能被转换为 @ref{1fe,,float} 类型的值。 如果 @emph{data} 不包含至少两个元素，则会引发 @ref{1ccd,,StatisticsError}，因为估算中心值至少需要一个点而估算分散度至少需要两个点。
@end deffn

@geindex samples() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist samples}@anchor{1cd6}
@deffn {方法} samples (n, *, seed=None)

对于给定的平均值和标准差生成 @emph{n} 个随机样本。 返回一个由 @ref{1fe,,float} 值组成的 @ref{1f9,,list}。

当给定 @emph{seed} 时，创建一个新的底层随机数生成器实例。 这适用于创建可重现的结果，即使对于多线程上下文也有效。
@end deffn

@geindex pdf() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist pdf}@anchor{1cd7}
@deffn {方法} pdf (x)

使用 概率密度函数 (pdf)@footnote{https://en.wikipedia.org/wiki/Probability_density_function}，计算一个随机变量 @emph{X} 趋向于给定值 @emph{x} 的相对可能性。 在数学意义上，它是当 @emph{dx} 趋向于零时比率 @code{P(x <= X < x+dx) / dx} 的极限。

相对可能性的计算方法是用一个狭窄区间内某个样本出现的概率除以区间的宽度（因此使用“密度”一词）。 由于可能性是相对于其他点的，它的值可以大于 @cite{1.0}。
@end deffn

@geindex cdf() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist cdf}@anchor{1cd8}
@deffn {方法} cdf (x)

使用 累积分布函数 (cdf)@footnote{https://en.wikipedia.org/wiki/Cumulative_distribution_function}，计算一个随机变量 @emph{X} 小于等于 @emph{x} 的概率。 在数学上，它表示为 @code{P(X <= x)}。
@end deffn

@geindex inv_cdf() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist inv_cdf}@anchor{1cd9}
@deffn {方法} inv_cdf (p)

计算反向累积分布函数，也称为 分位数函数@footnote{https://en.wikipedia.org/wiki/Quantile_function} 或 百分点@footnote{https://www.statisticshowto.datasciencecentral.com/inverse-distribution-function/} 函数。 在数学上，它表示为 @code{x : P(X <= x) = p}。

找出随机变量 @emph{X} 的值 @emph{x} 使得该变量小于等于该值的概率等于给定的概率 @emph{p}。
@end deffn

@geindex overlap() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist overlap}@anchor{1cda}
@deffn {方法} overlap (other)

测量两个正态概率分布之间的一致性。 返回介于 0.0 和 1.0 之间的值，给出 两个概率密度函数的重叠区域@footnote{https://www.rasch.org/rmt/rmt101r.htm}。
@end deffn

@geindex quantiles() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist quantiles}@anchor{1cdb}
@deffn {方法} quantiles (n=4)

将指定正态分布划分为 @emph{n} 个相等概率的连续分隔区。 返回这些分隔区对应的 (n - 1) 个分隔点的列表。

将 @emph{n} 设为 4 以使用四分位（默认值）。 将 @emph{n} 设为 10 以使用十分位。将 @emph{n} 设为 100 以使用百分位，即给出 99 个分隔点来将正态分布分隔为 100 个大小相等的组。
@end deffn

@geindex zscore() (statistics.NormalDist 方法)
@anchor{library/statistics statistics NormalDist zscore}@anchor{1cdc}
@deffn {方法} zscore (x)

计算 标准分@footnote{https://www.statisticshowto.com/probability-and-statistics/z-score/} 即以高于或低于正态分布的平均值的标准差数值的形式来描述 @emph{x}: @code{(x - mean) / stdev}.


3.9 新版功能.

@end deffn

@ref{35f,,NormalDist} 的实例支持加上、减去、乘以或除以一个常量。 这些运算被用于转换和缩放。 例如：

@example
>>> temperature_february = NormalDist(5, 2.5)             # Celsius
>>> temperature_february * (9/5) + 32                     # Fahrenheit
NormalDist(mu=41.0, sigma=4.5)
@end example

不允许一个常量除以 @ref{35f,,NormalDist} 的实例，因为结果将不是正态分布。

由于正态分布是由独立变量的累加效应产生的，因此允许表示为 @ref{35f,,NormalDist} 实例的 两组独立正态分布的随机变量相加和相减@footnote{https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables}。 例如：

@example
>>> birth_weights = NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
>>> drug_effects = NormalDist(0.4, 0.15)
>>> combined = birth_weights + drug_effects
>>> round(combined.mean, 1)
3.1
>>> round(combined.stdev, 1)
0.5
@end example


3.8 新版功能.

@end deffn

@menu
* NormalDist 示例和用法:: 

@end menu

@node NormalDist 示例和用法,,,NormalDist 对象
@anchor{library/statistics normaldist-examples-and-recipes}@anchor{1cdd}
@subsubsection @code{NormalDist} 示例和用法


@ref{35f,,NormalDist} 适合用来解决经典概率问题。

举例来说，如果 SAT 考试的历史数据@footnote{https://nces.ed.gov/programs/digest/d17/tables/dt17_226.40.asp} 显示分数呈平均值为 1060 且标准差为 195 的正态分布，则可以确定考试分数处于 1100 和 1200 之间的学生的百分比舍入到最接近的整数应为：

@example
>>> sat = NormalDist(1060, 195)
>>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
>>> round(fraction * 100.0, 1)
18.4
@end example

求 SAT 分数的 四分位@footnote{https://en.wikipedia.org/wiki/Quartile} 和 十分位@footnote{https://en.wikipedia.org/wiki/Decile}：

@example
>>> list(map(round, sat.quantiles()))
[928, 1060, 1192]
>>> list(map(round, sat.quantiles(n=10)))
[810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]
@end example

为了估算一个不易解析的模型分布，@ref{35f,,NormalDist} 可以生成用于 蒙特卡洛模拟@footnote{https://en.wikipedia.org/wiki/Monte_Carlo_method} 的输入样本：

@example
>>> def model(x, y, z):
...     return (3*x + 7*x*y - 5*y) / (11 * z)
...
>>> n = 100_000
>>> X = NormalDist(10, 2.5).samples(n, seed=3652260728)
>>> Y = NormalDist(15, 1.75).samples(n, seed=4582495471)
>>> Z = NormalDist(50, 1.25).samples(n, seed=6582483453)
>>> quantiles(map(model, X, Y, Z))       
[1.4591308524824727, 1.8035946855390597, 2.175091447274739]
@end example

当样本量较大并且成功试验的可能性接近 50% 时，正态分布可以被用来模拟 二项分布@footnote{http://mathworld.wolfram.com/BinomialDistribution.html}。

例如，一次开源会议有 750 名与会者和两个可分别容纳 500 人的会议厅。 会上有一场关于 Python 的演讲和一场关于 Ruby 的演讲。 在往届会议中，65% 的与会者更愿意去听关于 Python 的演讲。 假定人群的偏好没有发生改变，那么 Python 演讲的会议厅不超出其容量上限的可能性是多少？

@example
>>> n = 750             # Sample size
>>> p = 0.65            # Preference for Python
>>> q = 1.0 - p         # Preference for Ruby
>>> k = 500             # Room capacity

>>> # Approximation using the cumulative normal distribution
>>> from math import sqrt
>>> round(NormalDist(mu=n*p, sigma=sqrt(n*p*q)).cdf(k + 0.5), 4)
0.8402

>>> # Solution using the cumulative binomial distribution
>>> from math import comb, fsum
>>> round(fsum(comb(n, r) * p**r * q**(n-r) for r in range(k+1)), 4)
0.8402

>>> # Approximation using a simulation
>>> from random import seed, choices
>>> seed(8675309)
>>> def trial():
...     return choices(('Python', 'Ruby'), (p, q), k=n).count('Python')
>>> mean(trial() <= k for i in range(10_000))
0.8398
@end example

在机器学习问题中也经常会出现正态分布。

Wikipedia 上有一个 朴素贝叶斯分类器的好例子@footnote{https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification}。 挑战的问题是根据对多个正态分布的特征测量值包括身高、体重和足部尺码来预测一个人的性别。

我们得到了由八个人的测量值组成的训练数据集。 假定这些测量值是正态分布的，因此我们用 @ref{35f,,NormalDist} 来总结数据：

@example
>>> height_male = NormalDist.from_samples([6, 5.92, 5.58, 5.92])
>>> height_female = NormalDist.from_samples([5, 5.5, 5.42, 5.75])
>>> weight_male = NormalDist.from_samples([180, 190, 170, 165])
>>> weight_female = NormalDist.from_samples([100, 150, 130, 150])
>>> foot_size_male = NormalDist.from_samples([12, 11, 12, 10])
>>> foot_size_female = NormalDist.from_samples([6, 8, 7, 9])
@end example

接下来，我们遇到一个特征测量值已知但性别未知的新人：

@example
>>> ht = 6.0        # height
>>> wt = 130        # weight
>>> fs = 8          # foot size
@end example

从是男是女各 50% 的 先验概率@footnote{https://en.wikipedia.org/wiki/Prior_probability} 出发，我们通过将该先验概率乘以给定性别的特征度量值的可能性累积值来计算后验概率：

@example
>>> prior_male = 0.5
>>> prior_female = 0.5
>>> posterior_male = (prior_male * height_male.pdf(ht) *
...                   weight_male.pdf(wt) * foot_size_male.pdf(fs))

>>> posterior_female = (prior_female * height_female.pdf(ht) *
...                     weight_female.pdf(wt) * foot_size_female.pdf(fs))
@end example

最终预测值应为最大后验概率值。 这种算法被称为 maximum a posteriori@footnote{https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation} 或 MAP：

@example
>>> 'male' if posterior_male > posterior_female else 'female'
'female'
@end example

@c # This modelines must appear within the last ten lines of the file.
@c kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;

@node 函数式编程模块,文件和目录访问,数字和数学模块,Python 标准库
@anchor{library/functional doc}@anchor{1cde}@anchor{library/functional functional-programming-modules}@anchor{1cdf}
@section 函数式编程模块


本章里描述的模块提供了函数和类，以支持函数式编程风格和在可调用对象上的通用操作。

本章对下列模块进行说明：

@menu
* itertools: itertools --- 为高效循环而创建迭代器的函数. 为高效循环而创建迭代器的函数
* functools: functools --- 高阶函数和可调用对象上的操作. 高阶函数和可调用对象上的操作
* operator: operator --- 标准运算符替代函数. 标准运算符替代函数

@end menu

@node itertools --- 为高效循环而创建迭代器的函数,functools --- 高阶函数和可调用对象上的操作,,函数式编程模块
@anchor{library/itertools doc}@anchor{1ce0}@anchor{library/itertools itertools-functions-creating-iterators-for-efficient-looping}@anchor{1ce1}@anchor{library/itertools module-itertools}@anchor{a3}
@subsection @code{itertools} --- 为高效循环而创建迭代器的函数


@geindex itertools (模块)

@c from itertools import *


__________________________________________________________________


本模块实现一系列 @ref{11ba,,iterator} ，这些迭代器受到APL，Haskell和SML的启发。为了适用于Python，它们都被重新写过。

本模块标准化了一个快速、高效利用内存的核心工具集，这些工具本身或组合都很有用。它们一起形成了“迭代器代数”，这使得在纯Python中有可能创建简洁又高效的专用工具。

例如，SML有一个制表工具： @code{tabulate(f)}，它可产生一个序列 @code{f(0), f(1), ...}。在Python中可以组合 @ref{cff,,map()} 和 @ref{ced,,count()} 实现： @code{map(f, count())}。

这些内置工具同时也能很好地与 @ref{c2,,operator} 模块中的高效函数配合使用。例如，我们可以将两个向量的点积映射到乘法运算符： @code{sum(map(operator.mul, vector1, vector2))} 。

@strong{无穷迭代器：}


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

迭代器

@tab

实参

@tab

结果

@tab

示例

@item

@ref{ced,,count()}

@tab

start, [step]

@tab

start, start+step, start+2*step, ...

@tab

@code{count(10) --> 10 11 12 13 14 ...}

@item

@ref{1ce2,,cycle()}

@tab

p

@tab

p0, p1, ... plast, p0, p1, ...

@tab

@code{cycle('ABCD') --> A B C D A B C D ...}

@item

@ref{122f,,repeat()}

@tab

elem [,n]

@tab

elem, elem, elem, ... 重复无限次或n次

@tab

@code{repeat(10, 3) --> 10 10 10}

@end multitable


@strong{根据最短输入序列长度停止的迭代器：}


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

迭代器

@tab

实参

@tab

结果

@tab

示例

@item

@ref{315,,accumulate()}

@tab

p [,func]

@tab

p0, p0+p1, p0+p1+p2, ...

@tab

@code{accumulate([1,2,3,4,5]) --> 1 3 6 10 15}

@item

@ref{1768,,chain()}

@tab

p, q, ...

@tab

p0, p1, ... plast, q0, q1, ...

@tab

@code{chain('ABC', 'DEF') --> A B C D E F}

@item

@ref{1ce3,,chain.from_iterable()}

@tab

iterable

@tab

p0, p1, ... plast, q0, q1, ...

@tab

@code{chain.from_iterable(['ABC', 'DEF']) --> A B C D E F}

@item

@ref{cec,,compress()}

@tab

data, selectors

@tab

(d[0] if s[0]), (d[1] if s[1]), ...

@tab

@code{compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F}

@item

@ref{1ce4,,dropwhile()}

@tab

pred, seq

@tab

seq[n], seq[n+1], ... 从pred首次真值测试失败开始

@tab

@code{dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1}

@item

@ref{1752,,filterfalse()}

@tab

pred, seq

@tab

seq中pred(x)为假值的元素，x是seq中的元素。

@tab

@code{filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8}

@item

@ref{1ce5,,groupby()}

@tab

iterable[, key]

@tab

根据key(v)值分组的迭代器

@tab

@item

@ref{4b1,,islice()}

@tab

seq, [start,] stop [, step]

@tab

seq[start:stop:step]中的元素

@tab

@code{islice('ABCDEFG', 2, None) --> C D E F G}

@item

@ref{b0e,,starmap()}

@tab

func, seq

@tab

func(*seq[0]), func(*seq[1]), ...

@tab

@code{starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000}

@item

@ref{1ce6,,takewhile()}

@tab

pred, seq

@tab

seq[0], seq[1], ..., 直到pred真值测试失败

@tab

@code{takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4}

@item

@ref{1ce7,,tee()}

@tab

it, n

@tab

it1, it2, ... itn 将一个迭代器拆分为n个迭代器

@tab

@item

@ref{d03,,zip_longest()}

@tab

p, q, ...

@tab

(p[0], q[0]), (p[1], q[1]), ...

@tab

@code{zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-}

@end multitable


@strong{排列组合迭代器：}


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

迭代器

@tab

实参

@tab

结果

@item

@ref{d77,,product()}

@tab

p, q, ... [repeat=1]

@tab

笛卡尔积，相当于嵌套的for循环

@item

@ref{1014,,permutations()}

@tab

p[, r]

@tab

长度r元组，所有可能的排列，无重复元素

@item

@ref{d76,,combinations()}

@tab

p, r

@tab

长度r元组，有序，无重复元素

@item

@ref{ceb,,combinations_with_replacement()}

@tab

p, r

@tab

长度r元组，有序，元素可重复

@end multitable



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

例子

@tab

结果

@item

@code{product('ABCD', repeat=2)}

@tab

@code{AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD}

@item

@code{permutations('ABCD', 2)}

@tab

@code{AB AC AD BA BC BD CA CB CD DA DB DC}

@item

@code{combinations('ABCD', 2)}

@tab

@code{AB AC AD BC BD CD}

@item

@code{combinations_with_replacement('ABCD', 2)}

@tab

@code{AA AB AC AD BB BC BD CC CD DD}

@end multitable


@menu
* Itertool函数:: 
* itertools 配方:: 

@end menu

@node Itertool函数,itertools 配方,,itertools --- 为高效循环而创建迭代器的函数
@anchor{library/itertools itertool-functions}@anchor{1ce8}@anchor{library/itertools itertools-functions}@anchor{1ce9}
@subsubsection Itertool函数


下列模块函数均创建并返回迭代器。有些迭代器不限制输出流长度，所以它们只应在能截断输出流的函数或循环中使用。

@geindex accumulate() (在 itertools 模块中)
@anchor{library/itertools itertools accumulate}@anchor{315}
@deffn {函数} itertools.accumulate (iterable[, func, *, initial=None])

创建一个迭代器，返回累积汇总值或其他双目运算函数的累积结果值（通过可选的 @emph{func} 参数指定）。

如果提供了 @emph{func}，它应当为带有两个参数的函数。 输入 @emph{iterable} 的元素可以是能被 @emph{func} 接受为参数的任意类型。 （例如，对于默认的加法运算，元素可以是任何可相加的类型包括 @ref{2c7,,Decimal} 或 @ref{2c5,,Fraction}。）

通常，输出的元素数量与输入的可迭代对象是一致的。 但是，如果提供了关键字参数 @emph{initial}，则累加会以 @emph{initial} 值开始，这样输出就比输入的可迭代对象多一个元素。

大致相当于：

@example
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
@end example

@emph{func} 参数有几种用法。它可以被设为 @ref{900,,min()} 最终得到一个最小值，或者设为 @ref{901,,max()} 最终得到一个最大值，或设为 @ref{1cea,,operator.mul()} 最终得到一个乘积。摊销表可通过累加利息和支付款项得到。给iterable设置初始值并只将参数 @emph{func} 设为累加总数可以对一阶 递归关系@footnote{https://en.wikipedia.org/wiki/Recurrence_relation} 建模。

@example
>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

# Chaotic recurrence relation https://en.wikipedia.org/wiki/Logistic_map
>>> logistic_map = lambda x, _:  r * x * (1 - x)
>>> r = 3.8
>>> x0 = 0.4
>>> inputs = repeat(x0, 36)     # only the initial value is used
>>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)]
['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
 '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
 '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
 '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']
@end example

参考一个类似函数  @ref{d3f,,functools.reduce()}  ，它只返回一个最终累积值。


3.2 新版功能.



在 3.3 版更改: 增加可选参数 @emph{func} 。



在 3.8 版更改: 添加了可选的 @emph{initial} 形参。

@end deffn

@geindex chain() (在 itertools 模块中)
@anchor{library/itertools itertools chain}@anchor{1768}
@deffn {函数} itertools.chain (*iterables)

创建一个迭代器，它首先返回第一个可迭代对象中所有元素，接着返回下一个可迭代对象中所有元素，直到耗尽所有可迭代对象中的元素。可将多个序列处理为单个序列。大致相当于：

@example
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
@end example
@end deffn

@geindex from_iterable() (itertools.chain 类方法)
@anchor{library/itertools itertools chain from_iterable}@anchor{1ce3}
@deffn {方法} classmethod chain.from_iterable (iterable)

构建类似 @ref{1768,,chain()} 迭代器的另一个选择。从一个单独的可迭代参数中得到链式输入，该参数是延迟计算的。大致相当于：

@example
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
@end example
@end deffn

@geindex combinations() (在 itertools 模块中)
@anchor{library/itertools itertools combinations}@anchor{d76}
@deffn {函数} itertools.combinations (iterable, r)

返回由输入 @emph{iterable} 中元素组成长度为 @emph{r} 的子序列。

组合元组会以字典顺序根据所输入 @emph{iterable} 的顺序发出。 因此，如果所输入 @emph{iterable} 是已排序的，组合元组也将按已排序的顺序生成。

即使元素的值相同，不同位置的元素也被认为是不同的。如果元素各自不同，那么每个组合中没有重复元素。

大致相当于：

@example
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
@end example

@ref{d76,,combinations()} 的代码可被改写为 @ref{1014,,permutations()} 过滤后的子序列，（相对于元素在输入中的位置）元素不是有序的。

@example
def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
@end example

当 @code{0 <= r <= n} 时，返回项的个数是 @code{n! / r! / (n-r)!}；当 @code{r > n} 时，返回项个数为0。
@end deffn

@geindex combinations_with_replacement() (在 itertools 模块中)
@anchor{library/itertools itertools combinations_with_replacement}@anchor{ceb}
@deffn {函数} itertools.combinations_with_replacement (iterable, r)

返回由输入 @emph{iterable} 中元素组成的长度为 @emph{r} 的子序列，允许每个元素可重复出现。

组合元组会以字典顺序根据所输入 @emph{iterable} 的顺序发出。 因此，如果所输入 @emph{iterable} 是已排序的，组合元组也将按已排序的顺序生成。

不同位置的元素是不同的，即使它们的值相同。因此如果输入中的元素都是不同的话，返回的组合中元素也都会不同。

大致相当于：

@example
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
@end example

@ref{ceb,,combinations_with_replacement()} 的代码可被改写为 @code{production()} 过滤后的子序列，（相对于元素在输入中的位置）元素不是有序的。

@example
def combinations_with_replacement(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in product(range(n), repeat=r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
@end example

当 @code{n > 0} 时，返回项个数为 @code{(n+r-1)! / r! / (n-1)!}.


3.1 新版功能.

@end deffn

@geindex compress() (在 itertools 模块中)
@anchor{library/itertools itertools compress}@anchor{cec}
@deffn {函数} itertools.compress (data, selectors)

创建一个迭代器，它返回 @emph{data} 中经 @emph{selectors} 真值测试为 @code{True} 的元素。迭代器在两者较短的长度处停止。大致相当于：

@example
def compress(data, selectors):
    # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
    return (d for d, s in zip(data, selectors) if s)
@end example


3.1 新版功能.

@end deffn

@geindex count() (在 itertools 模块中)
@anchor{library/itertools itertools count}@anchor{ced}
@deffn {函数} itertools.count (start=0, step=1)

创建一个迭代器，它从 @emph{start} 值开始，返回均匀间隔的值。常用于 @ref{cff,,map()} 中的实参来生成连续的数据点。此外，还用于 @ref{d04,,zip()} 来添加序列号。大致相当于：

@example
def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step
@end example

当对浮点数计数时，替换为乘法代码有时精度会更好，例如： @code{(start + step * i for i in count())} 。


在 3.1 版更改: 增加参数 @emph{step} ，允许非整型。

@end deffn

@geindex cycle() (在 itertools 模块中)
@anchor{library/itertools itertools cycle}@anchor{1ce2}
@deffn {函数} itertools.cycle (iterable)

创建一个迭代器，返回 @emph{iterable} 中所有元素并保存一个副本。当取完 @emph{iterable} 中所有元素，返回副本中的所有元素。无限重复。大致相当于：

@example
def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
@end example

注意，该函数可能需要相当大的辅助空间（取决于 @emph{iterable} 的长度）。
@end deffn

@geindex dropwhile() (在 itertools 模块中)
@anchor{library/itertools itertools dropwhile}@anchor{1ce4}
@deffn {函数} itertools.dropwhile (predicate, iterable)

创建一个迭代器，如果 @emph{predicate} 为true，迭代器丢弃这些元素，然后返回其他元素。注意，迭代器在 @emph{predicate} 首次为false之前不会产生任何输出，所以可能需要一定长度的启动时间。大致相当于：

@example
def dropwhile(predicate, iterable):
    # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
    iterable = iter(iterable)
    for x in iterable:
        if not predicate(x):
            yield x
            break
    for x in iterable:
        yield x
@end example
@end deffn

@geindex filterfalse() (在 itertools 模块中)
@anchor{library/itertools itertools filterfalse}@anchor{1752}
@deffn {函数} itertools.filterfalse (predicate, iterable)

创建一个迭代器，只返回 @emph{iterable} 中 @emph{predicate} 为 @code{False} 的元素。如果 @emph{predicate} 是 @code{None}，返回真值测试为false的元素。大致相当于：

@example
def filterfalse(predicate, iterable):
    # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
    if predicate is None:
        predicate = bool
    for x in iterable:
        if not predicate(x):
            yield x
@end example
@end deffn

@geindex groupby() (在 itertools 模块中)
@anchor{library/itertools itertools groupby}@anchor{1ce5}
@deffn {函数} itertools.groupby (iterable, key=None)

创建一个迭代器，返回 @emph{iterable} 中连续的键和组。@emph{key} 是一个计算元素键值函数。如果未指定或为 @code{None}，@emph{key} 缺省为恒等函数（identity function），返回元素不变。一般来说，@emph{iterable} 需用同一个键值函数预先排序。

@ref{1ce5,,groupby()} 操作类似于Unix中的 @code{uniq}。当每次 @emph{key} 函数产生的键值改变时，迭代器会分组或生成一个新组（这就是为什么通常需要使用同一个键值函数先对数据进行排序）。这种行为与SQL的GROUP BY操作不同，SQL的操作会忽略输入的顺序将相同键值的元素分在同组中。

返回的组本身也是一个迭代器，它与 @ref{1ce5,,groupby()} 共享底层的可迭代对象。因为源是共享的，当 @ref{1ce5,,groupby()} 对象向后迭代时，前一个组将消失。因此如果稍后还需要返回结果，可保存为列表：

@example
groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)
@end example

@ref{1ce5,,groupby()} 大致相当于：

@example
class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        self.id = object()
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey, self.id))
    def _grouper(self, tgtkey, id):
        while self.id is id and self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)
@end example
@end deffn

@geindex islice() (在 itertools 模块中)
@anchor{library/itertools itertools islice}@anchor{4b1}
@deffn {函数} itertools.islice (iterable, stop)

@deffnx {函数} itertools.islice (iterable, start, stop[, step])

创建一个迭代器，返回从 @emph{iterable} 里选中的元素。如果 @emph{start} 不是0，跳过 @emph{iterable} 中的元素，直到到达 @emph{start} 这个位置。之后迭代器连续返回元素，除非 @emph{step} 设置的值很高导致被跳过。如果 @emph{stop} 为 @code{None}，迭代器耗光为止；否则，在指定的位置停止。与普通的切片不同，@ref{4b1,,islice()} 不支持将 @emph{start} ， @emph{stop} ，或 @emph{step} 设为负值。可用来从内部数据结构被压平的数据中提取相关字段（例如一个多行报告，它的名称字段出现在每三行上）。大致相当于：

@example
def islice(iterable, *args):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(*args)
    start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
    it = iter(range(start, stop, step))
    try:
        nexti = next(it)
    except StopIteration:
        # Consume *iterable* up to the *start* position.
        for i, element in zip(range(start), iterable):
            pass
        return
    try:
        for i, element in enumerate(iterable):
            if i == nexti:
                yield element
                nexti = next(it)
    except StopIteration:
        # Consume to *stop*.
        for i, element in zip(range(i + 1, stop), iterable):
            pass
@end example

如果 @emph{start} 为 @code{None}，迭代从0开始。如果 @emph{step} 为 @code{None} ，步长缺省为1。
@end deffn

@geindex permutations() (在 itertools 模块中)
@anchor{library/itertools itertools permutations}@anchor{1014}
@deffn {函数} itertools.permutations (iterable, r=None)

连续返回由 @emph{iterable} 元素生成长度为 @emph{r} 的排列。

如果 @emph{r} 未指定或为 @code{None} ，@emph{r} 默认设置为 @emph{iterable} 的长度，这种情况下，生成所有全长排列。

排列元组会以字典顺序根据所输入 @emph{iterable} 的顺序发出。 因此，如果所输入 @emph{iterable} 是已排序的，组合元组也将按已排序的顺序生成。

即使元素的值相同，不同位置的元素也被认为是不同的。如果元素值都不同，每个排列中的元素值不会重复。

大致相当于：

@example
def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return
@end example

@ref{1014,,permutations()} 的代码也可被改写为 @ref{d77,,product()} 的子序列，只要将含有重复元素（来自输入中同一位置的）的项排除。

@example
def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)
@end example

当 @code{0 <= r <= n} ，返回项个数为 @code{n! / (n-r)!} ；当 @code{r > n} ，返回项个数为0。
@end deffn

@geindex product() (在 itertools 模块中)
@anchor{library/itertools itertools product}@anchor{d77}
@deffn {函数} itertools.product (*iterables, repeat=1)

可迭代对象输入的笛卡儿积。

大致相当于生成器表达式中的嵌套循环。例如， @code{product(A, B)} 和 @code{((x,y) for x in A for y in B)} 返回结果一样。

嵌套循环像里程表那样循环变动，每次迭代时将最右侧的元素向后迭代。这种模式形成了一种字典序，因此如果输入的可迭代对象是已排序的，笛卡尔积元组依次序发出。

要计算可迭代对象自身的笛卡尔积，将可选参数 @emph{repeat} 设定为要重复的次数。例如，@code{product(A, repeat=4)} 和 @code{product(A, A, A, A)} 是一样的。

该函数大致相当于下面的代码，只不过实际实现方案不会在内存中创建中间结果。

@example
def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
@end example

在 @ref{d77,,product()} 运行之前，它会完全耗尽输入的可迭代对象，在内存中保留值的临时池以生成结果积。 相应地，它只适用于有限的输入。
@end deffn

@geindex repeat() (在 itertools 模块中)
@anchor{library/itertools itertools repeat}@anchor{122f}
@deffn {函数} itertools.repeat (object[, times])

创建一个迭代器，不断重复 @emph{object} 。除非设定参数 @emph{times} ，否则将无限重复。可用于 @ref{cff,,map()} 函数中的参数，被调用函数可得到一个不变参数。也可用于 @ref{d04,,zip()} 的参数以在元组记录中创建一个不变的部分。

大致相当于：

@example
def repeat(object, times=None):
    # repeat(10, 3) --> 10 10 10
    if times is None:
        while True:
            yield object
    else:
        for i in range(times):
            yield object
@end example

@emph{repeat} 最常见的用途就是在 @emph{map} 或 @emph{zip} 提供一个常量流：

@example
>>> list(map(pow, range(10), repeat(2)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@end example
@end deffn

@geindex starmap() (在 itertools 模块中)
@anchor{library/itertools itertools starmap}@anchor{b0e}
@deffn {函数} itertools.starmap (function, iterable)

创建一个迭代器，使用从可迭代对象中获取的参数来计算该函数。当参数对应的形参已从一个单独可迭代对象组合为元组时（数据已被“预组对”）可用此函数代替 @ref{cff,,map()}。@ref{cff,,map()} 与 @ref{b0e,,starmap()} 之间的区别可以类比 @code{function(a,b)} 与 @code{function(*c)} 的区别。大致相当于:

@example
def starmap(function, iterable):
    # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
    for args in iterable:
        yield function(*args)
@end example
@end deffn

@geindex takewhile() (在 itertools 模块中)
@anchor{library/itertools itertools takewhile}@anchor{1ce6}
@deffn {函数} itertools.takewhile (predicate, iterable)

创建一个迭代器，只要 predicate 为真就从可迭代对象中返回元素。大致相当于:

@example
def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break
@end example
@end deffn

@geindex tee() (在 itertools 模块中)
@anchor{library/itertools itertools tee}@anchor{1ce7}
@deffn {函数} itertools.tee (iterable, n=2)

从一个可迭代对象中返回 @emph{n} 个独立的迭代器。

下面的Python代码能帮助解释 @emph{tee} 做了什么（尽管实际的实现更复杂，而且仅使用了一个底层的 @abbr{FIFO} 队列）。

大致相当于：

@example
def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for i in range(n)]
    def gen(mydeque):
        while True:
            if not mydeque:             # when the local deque is empty
                try:
                    newval = next(it)   # fetch a new value and
                except StopIteration:
                    return
                for d in deques:        # load it to all the deques
                    d.append(newval)
            yield mydeque.popleft()
    return tuple(gen(d) for d in deques)
@end example

一旦 @ref{1ce7,,tee()} 实施了一次分裂，原有的 @emph{iterable} 不应再被使用；否则tee对象无法得知 @emph{iterable} 可能已向后迭代。

@code{tee} 迭代器不是线程安全的。当同时使用由同一个 @ref{1ce7,,tee()} 调用所返回的迭代器时可能引发 @ref{3e4,,RuntimeError}，即使原本的 @emph{iterable} 是线程安全的。

该迭代工具可能需要相当大的辅助存储空间（这取决于要保存多少临时数据）。通常，如果一个迭代器在另一个迭代器开始之前就要使用大部份或全部数据，使用 @ref{1f9,,list()} 会比 @ref{1ce7,,tee()} 更快。
@end deffn

@geindex zip_longest() (在 itertools 模块中)
@anchor{library/itertools itertools zip_longest}@anchor{d03}
@deffn {函数} itertools.zip_longest (*iterables, fillvalue=None)

创建一个迭代器，从每个可迭代对象中收集元素。如果可迭代对象的长度未对齐，将根据 @emph{fillvalue} 填充缺失值。迭代持续到耗光最长的可迭代对象。大致相当于：

@example
def zip_longest(*args, fillvalue=None):
    # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    iterators = [iter(it) for it in args]
    num_active = len(iterators)
    if not num_active:
        return
    while True:
        values = []
        for i, it in enumerate(iterators):
            try:
                value = next(it)
            except StopIteration:
                num_active -= 1
                if not num_active:
                    return
                iterators[i] = repeat(fillvalue)
                value = fillvalue
            values.append(value)
        yield tuple(values)
@end example

如果其中一个可迭代对象有无限长度，@ref{d03,,zip_longest()} 函数应封装在限制调用次数的场景中（例如 @ref{4b1,,islice()} 或 @ref{1ce6,,takewhile()}）。除非指定， @emph{fillvalue} 默认为 @code{None} 。
@end deffn

@node itertools 配方,,Itertool函数,itertools --- 为高效循环而创建迭代器的函数
@anchor{library/itertools id1}@anchor{1ceb}@anchor{library/itertools itertools-recipes}@anchor{cc8}
@subsubsection itertools 配方


本节将展示如何使用现有的 itertools 作为基础构件来创建扩展的工具集。

基本上所有这些西方和许许多多其他的配方都可以通过 Python Package Index 上的 more-itertools 项目@footnote{https://pypi.org/project/more-itertools/} 来安装:

@example
pip install more-itertools
@end example

扩展的工具提供了与底层工具集相同的高性能。保持了超棒的内存利用率，因为一次只处理一个元素，而不是将整个可迭代对象加载到内存。代码量保持得很小，以函数式风格将这些工具连接在一起，有助于消除临时变量。速度依然很快，因为倾向于使用“矢量化”构件来取代解释器开销大的 for 循环和 @ref{a8c,,generator} 。

@example
def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

def prepend(value, iterator):
    "Prepend a single value in front of an iterator"
    # prepend(1, [2, 3, 4]) -> 1 2 3 4
    return chain([value], iterator)

def tabulate(function, start=0):
    "Return function(0), function(1), ..."
    return map(function, count(start))

def tail(n, iterable):
    "Return an iterator over the last n items"
    # tail(3, 'ABCDEFG') --> E F G
    return iter(collections.deque(iterable, maxlen=n))

def consume(iterator, n=None):
    "Advance the iterator n-steps ahead. If n is None, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

def quantify(iterable, pred=bool):
    "Count how many times the predicate is true"
    return sum(map(pred, iterable))

def pad_none(iterable):
    """Returns the sequence elements and then returns None indefinitely.

    Useful for emulating the behavior of the built-in map() function.
    """
    return chain(iterable, repeat(None))

def ncycles(iterable, n):
    "Returns the sequence elements n times"
    return chain.from_iterable(repeat(tuple(iterable), n))

def dotproduct(vec1, vec2):
    return sum(map(operator.mul, vec1, vec2))

def convolve(signal, kernel):
    # See:  https://betterexplained.com/articles/intuitive-convolution/
    # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)
    # convolve(data, [1, -1]) --> 1st finite difference (1st derivative)
    # convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
    kernel = tuple(kernel)[::-1]
    n = len(kernel)
    window = collections.deque([0], maxlen=n) * n
    for x in chain(signal, repeat(0, n-1)):
        window.append(x)
        yield sum(map(operator.mul, kernel, window))

def flatten(list_of_lists):
    "Flatten one level of nesting"
    return chain.from_iterable(list_of_lists)

def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

def partition(pred, iterable):
    "Use a predicate to partition entries into false entries and true entries"
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return map(next, map(operator.itemgetter(1), groupby(iterable, key)))

def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like builtins.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
        iter_except(s.pop, KeyError)                             # non-blocking set iterator

    """
    try:
        if first is not None:
            yield first()            # For database APIs needing an initial cast to db.first()
        while True:
            yield func()
    except exception:
        pass

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

def random_product(*args, repeat=1):
    "Random selection from itertools.product(*args, **kwds)"
    pools = [tuple(pool) for pool in args] * repeat
    return tuple(map(random.choice, pools))

def random_permutation(iterable, r=None):
    "Random selection from itertools.permutations(iterable, r)"
    pool = tuple(iterable)
    r = len(pool) if r is None else r
    return tuple(random.sample(pool, r))

def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(range(n), r))
    return tuple(pool[i] for i in indices)

def random_combination_with_replacement(iterable, r):
    "Random selection from itertools.combinations_with_replacement(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.choices(range(n), k=r))
    return tuple(pool[i] for i in indices)

def nth_combination(iterable, r, index):
    "Equivalent to list(combinations(iterable, r))[index]"
    pool = tuple(iterable)
    n = len(pool)
    if r < 0 or r > n:
        raise ValueError
    c = 1
    k = min(r, n-r)
    for i in range(1, k+1):
        c = c * (n - k + i) // i
    if index < 0:
        index += c
    if index < 0 or index >= c:
        raise IndexError
    result = []
    while r:
        c, n, r = c*r//n, n-1, r-1
        while index >= c:
            index -= c
            c, n = c*(n-r)//n, n-1
        result.append(pool[-1-n])
    return tuple(result)
@end example

@node functools --- 高阶函数和可调用对象上的操作,operator --- 标准运算符替代函数,itertools --- 为高效循环而创建迭代器的函数,函数式编程模块
@anchor{library/functools doc}@anchor{1cec}@anchor{library/functools functools-higher-order-functions-and-operations-on-callable-objects}@anchor{1ced}@anchor{library/functools module-functools}@anchor{83}
@subsection @code{functools} --- 高阶函数和可调用对象上的操作


@geindex functools (模块)

@strong{源代码:} Lib/functools.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/functools.py}

@c import functools
@c from functools import *


__________________________________________________________________


@ref{83,,functools} 模块应用于高阶函数，即参数或（和）返回值为其他函数的函数。 通常来说，此模块的功能适用于所有可调用对象。

@ref{83,,functools} 模块定义了以下函数:

@geindex cache() (在 functools 模块中)
@anchor{library/functools functools cache}@anchor{1cee}
@deffn {函数} @@functools.cache (user_function)

简单轻量级未绑定函数缓存。 有时称为 "memoize"@footnote{https://en.wikipedia.org/wiki/Memoization}。

返回值与 @code{lru_cache(maxsize=None)} 相同，创建一个查找函数参数的字典的简单包装器。 因为它不需要移出旧值，所以比带有大小限制的 @ref{2ff,,lru_cache()} 更小更快。

例如:

@example
@@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600
@end example


3.9 新版功能.

@end deffn

@geindex cached_property() (在 functools 模块中)
@anchor{library/functools functools cached_property}@anchor{300}
@deffn {函数} @@functools.cached_property (func)

将一个类方法转换为特征属性，一次性计算该特征属性的值，然后将其缓存为实例生命周期内的普通属性。 类似于 @ref{30f,,property()} 但增加了缓存功能。 对于在其他情况下实际不可变的高计算资源消耗的实例特征属性来说该函数非常有用。

示例:

@example
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @@cached_property
    def stdev(self):
        return statistics.stdev(self._data)
@end example

@ref{300,,cached_property()} 的设定与 @ref{30f,,property()} 有所不同。 常规的 property 会阻止属性写入，除非定义了 setter。 与之相反，@emph{cached_property} 则允许写入。

@emph{cached_property} 装饰器仅在执行查找且不存在同名属性时才会运行。 当运行时，@emph{cached_property} 会写入同名的属性。 后续的属性读取和写入操作会优先于 @emph{cached_property} 方法，其行为就像普通的属性一样。

缓存的值可通过删除该属性来清空。 这允许 @emph{cached_property} 方法再次运行。

注意，这个装饰器会影响 
@geindex Python 提高建议; PEP 412
PEP 412@footnote{https://www.python.org/dev/peps/pep-0412} 键共享字典的操作。 这意味着相应的字典实例可能占用比通常时更多的空间。

而且，这个装饰器要求每个实例上的 @code{__dict__} 是可变的映射。 这意味着它将不适用于某些类型，例如元类（因为类型实例上的 @code{__dict__} 属性是类命名空间的只读代理），以及那些指定了 @code{__slots__} 但未包括 @code{__dict__} 作为所定义的空位之一的类（因为这样的类根本没有提供 @code{__dict__} 属性）。

如果可变的映射不可用或者如果想要节省空间的键共享，可以通过在 @ref{1cee,,cache()} 之上堆叠一个 @ref{30f,,property()} 来实现类似 @ref{300,,cached_property()} 的效果:

@example
class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @@property
    @@cache
    def stdev(self):
        return statistics.stdev(self._data)
@end example


3.8 新版功能.

@end deffn

@geindex cmp_to_key() (在 functools 模块中)
@anchor{library/functools functools cmp_to_key}@anchor{c31}
@deffn {函数} functools.cmp_to_key (func)

将(旧式的)比较函数转换为新式的 @ref{7dc,,key function} .  在类似于 @ref{54f,,sorted()} ， @ref{900,,min()} ， @ref{901,,max()} ， @ref{1afa,,heapq.nlargest()} ， @ref{1afb,,heapq.nsmallest()} ， @ref{1ce5,,itertools.groupby()} 等函数的 @cite{key} 参数中使用。此函数主要用作将 Python 2 程序转换至新版的转换工具，以保持对比较函数的兼容。

比较函数意为一个可调用对象，该对象接受两个参数并比较它们，结果为小于则返回一个负数，相等则返回零，大于则返回一个正数。key function则是一个接受一个参数，并返回另一个用以排序的值的可调用对象。

示例:

@example
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
@end example

有关排序示例和简要排序教程，请参阅 @ref{1767,,排序指南} 。


3.2 新版功能.

@end deffn

@geindex lru_cache() (在 functools 模块中)
@anchor{library/functools functools lru_cache}@anchor{2ff}
@deffn {函数} @@functools.lru_cache (user_function)

@deffnx {函数} @@functools.lru_cache (maxsize=128, typed=False)

一个为函数提供缓存功能的装饰器，缓存 @emph{maxsize} 组传入参数，在下次以相同参数调用时直接返回上一次的结果。用以节约高开销或I/O函数的调用时间。

由于使用了字典存储缓存，所以该函数的固定参数和关键字参数必须是可哈希的。

不同模式的参数可能被视为不同从而产生多个缓存项，例如, @cite{f(a=1@comma{} b=2)} 和 @cite{f(b=2@comma{} a=1)} 因其参数顺序不同，可能会被缓存两次。

如果指定了 @emph{user_function}，它必须是一个可调用对象。 这允许 @emph{lru_cache} 装饰器被直接应用于一个用户自定义函数，让 @emph{maxsize} 保持其默认值 128:

@example
@@lru_cache
def count_vowels(sentence):
    sentence = sentence.casefold()
    return sum(sentence.count(vowel) for vowel in 'aeiou')
@end example

如果 @emph{maxsize} 设为 @code{None}，LRU 特性将被禁用且缓存可无限增长。

如果 @emph{typed} 设置为true，不同类型的函数参数将被分别缓存。例如， @code{f(3)} 和 @code{f(3.0)} 将被视为不同而分别缓存。

被包装的函数配有一个 @code{cache_parameters()} 函数，该函数返回一个新的 @ref{164,,dict} 用来显示 @emph{maxsize} 和 @emph{typed} 的值。 这只是出于显示信息的目的。 改变值没有任何效果。

为了衡量缓存的有效性以便调整 @emph{maxsize} 形参，被装饰的函数带有一个 @code{cache_info()} 函数。当调用 @code{cache_info()} 函数时，返回一个具名元组，包含命中次数 @emph{hits}，未命中次数 @emph{misses} ，最大缓存数量 @emph{maxsize} 和 当前缓存大小 @emph{currsize}。在多线程环境中，命中数与未命中数是不完全准确的。

该装饰器也提供了一个用于清理/使缓存失效的函数 @code{cache_clear()} 。

原始的未经装饰的函数可以通过 @code{__wrapped__} 属性访问。它可以用于检查、绕过缓存，或使用不同的缓存再次装饰原始函数。

LRU（最久未使用算法）缓存@footnote{https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)} 在最近的调用是即将到来的调用的最佳预测值时性能最好（例如，新闻服务器上最热门文章倾向于每天更改）。 缓存的大小限制可确保缓存不会在长期运行进程如网站服务器上无限制地增长。

一般来说，LRU缓存只在当你想要重用之前计算的结果时使用。因此，用它缓存具有副作用的函数、需要在每次调用时创建不同、易变的对象的函数或者诸如time（）或random（）之类的不纯函数是没有意义的。

静态 Web 内容的 LRU 缓存示例:

@example
@@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://www.python.org/dev/peps/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
@end example

以下是使用缓存通过 动态规划@footnote{https://zh.wikipedia.org/wiki/动态规划}  计算 斐波那契数列@footnote{https://zh.wikipedia.org/wiki/斐波那契数列}  的例子。

@example
@@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
@end example


3.2 新版功能.



在 3.3 版更改: 添加 @emph{typed} 选项。



在 3.8 版更改: 添加了 @emph{user_function} 选项。



3.9 新版功能: 新增函数 @code{cache_parameters()}

@end deffn

@geindex total_ordering() (在 functools 模块中)
@anchor{library/functools functools total_ordering}@anchor{942}
@deffn {函数} @@functools.total_ordering

给定一个声明一个或多个全比较排序方法的类，这个类装饰器实现剩余的方法。这减轻了指定所有可能的全比较操作的工作。

此类必须包含以下方法之一：@ref{d06,,__lt__()} 、@ref{d70,,__le__()}、@ref{d71,,__gt__()} 或 @ref{d72,,__ge__()}。另外，此类必须支持 @ref{454,,__eq__()} 方法。

例如:

@example
@@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
@end example

@cartouche
@quotation 注解 
虽然此装饰器使得创建具有良好行为的完全有序类型变得非常容易，但它 @emph{确实} 是以执行速度更缓慢和派生比较方法的堆栈回溯更复杂为代价的。 如果性能基准测试表明这是特定应用的瓶颈所在，则改为实现全部六个富比较方法应该会轻松提升速度。
@end quotation
@end cartouche


3.2 新版功能.



在 3.4 版更改: 现在已支持从未识别类型的下层比较函数返回 NotImplemented 异常。

@end deffn

@geindex partial() (在 functools 模块中)
@anchor{library/functools functools partial}@anchor{8bf}
@deffn {函数} functools.partial (func, /, *args, **keywords)

返回一个新的 @ref{1cef,,部分对象}，当被调用时其行为类似于 @emph{func} 附带位置参数 @emph{args} 和关键字参数 @emph{keywords} 被调用。 如果为调用提供了更多的参数，它们会被附加到 @emph{args}。 如果提供了额外的关键字参数，它们会扩展并重载 @emph{keywords}。 大致等价于:

@example
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = @{**keywords, **fkeywords@}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
@end example

@ref{8bf,,partial()} 会被“冻结了”一部分函数参数和/或关键字的部分函数应用所使用，从而得到一个具有简化签名的新对象。 例如，@ref{8bf,,partial()} 可用来创建一个行为类似于 @ref{205,,int()} 函数的可调用对象，其中 @emph{base} 参数默认为二：

@example
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
@end example
@end deffn

@geindex partialmethod (functools 中的类)
@anchor{library/functools functools partialmethod}@anchor{3c7}
@deffn {类} functools.partialmethod (func, /, *args, **keywords)

返回一个新的 @ref{3c7,,partialmethod} 描述器，其行为类似 @ref{8bf,,partial} 但它被设计用作方法定义而非直接用作可调用对象。

@emph{func} 必须是一个 @ref{15a8,,descriptor} 或可调用对象（同属两者的对象例如普通函数会被当作描述器来处理）。

当 @emph{func} 是一个描述器（例如普通 Python 函数, @ref{310,,classmethod()}, @ref{311,,staticmethod()}, @code{abstractmethod()} 或其他 @ref{3c7,,partialmethod} 的实例）时, 对 @code{__get__} 的调用会被委托给底层的描述器，并会返回一个适当的 @ref{1cef,,部分对象} 作为结果。

当 @emph{func} 是一个非描述器类可调用对象时，则会动态创建一个适当的绑定方法。 当用作方法时其行为类似普通 Python 函数：将会插入 @emph{self} 参数作为第一个位置参数，其位置甚至会处于提供给 @ref{3c7,,partialmethod} 构造器的 @emph{args} 和 @emph{keywords} 之前。

示例:

@example
>>> class Cell:
...     def __init__(self):
...         self._alive = False
...     @@property
...     def alive(self):
...         return self._alive
...     def set_state(self, state):
...         self._alive = bool(state)
...     set_alive = partialmethod(set_state, True)
...     set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True
@end example


3.4 新版功能.

@end deffn

@geindex reduce() (在 functools 模块中)
@anchor{library/functools functools reduce}@anchor{d3f}
@deffn {函数} functools.reduce (function, iterable[, initializer])

将两个参数的 @emph{function} 从左至右积累地应用到 @emph{iterable} 的条目，以便将该可迭代对象缩减为单一的值。 例如，@code{reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])} 是计算 @code{((((1+2)+3)+4)+5)} 的值。 左边的参数 @emph{x} 是积累值而右边的参数 @emph{y} 则是来自 @emph{iterable} 的更新值。 如果存在可选项 @emph{initializer}，它会被放在参与计算的可迭代对象的条目之前，并在可迭代对象为空时作为默认值。 如果没有给出 @emph{initializer} 并且 @emph{iterable} 仅包含一个条目，则将返回第一项。

大致相当于：

@example
def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value
@end example

请参阅 @ref{315,,itertools.accumulate()} 了解有关可产生所有中间值的迭代器。
@end deffn

@geindex singledispatch() (在 functools 模块中)
@anchor{library/functools functools singledispatch}@anchor{499}
@deffn {函数} @@functools.singledispatch

将一个函数转换为 @ref{302,,单分派} @ref{303,,generic function}。

要定义一个泛型函数，用装饰器 @code{@@singledispatch} 来装饰它。当使用 @code{@@singledispatch} 定义一个函数时，请注意调度发生在第一个参数的类型上:

@example
>>> from functools import singledispatch
>>> @@singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)
@end example

要将重载的实现添加到函数中，请使用泛型函数的 @code{register()} 属性，它可以被用作装饰器。 对于带有类型标注的函数，该装饰器将自动推断第一个参数的类型:

@example
>>> @@fun.register
... def _(arg: int, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @@fun.register
... def _(arg: list, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
@end example

对于不使用类型标注的代码，可以将适当的类型参数显式地传给装饰器本身:

@example
>>> @@fun.register(complex)
... def _(arg, verbose=False):
...     if verbose:
...         print("Better than complicated.", end=" ")
...     print(arg.real, arg.imag)
...
@end example

要启用注册 @ref{1cf0,,lambda} 和现有的函数，也可以使用 @code{register()} 属性的函数形式:

@example
>>> def nothing(arg, verbose=False):
...     print("Nothing.")
...
>>> fun.register(type(None), nothing)
@end example

@code{register()} 属性会返回未被装饰的函数。 这将启用装饰器栈、@ref{ca,,封存}，并为每个变量单独创建单元测试:

@example
>>> @@fun.register(float)
... @@fun.register(Decimal)
... def fun_num(arg, verbose=False):
...     if verbose:
...         print("Half of your number:", end=" ")
...     print(arg / 2)
...
>>> fun_num is fun
False
@end example

在调用时，泛型函数会根据第一个参数的类型进行分派:

@example
>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> fun(None)
Nothing.
>>> fun(1.23)
0.615
@end example

在没有针对特定类型的已注册实现的情况下，会使用其方法解析顺序来查找更通用的实现。 使用 @code{@@singledispatch} 装饰的原始函数将为基本的 @ref{3da,,object} 类型进行注册，这意味着它将在找不到更好的实现时被使用。

如果一个实现被注册到 @ref{c0e,,abstract base class}，则基类的虚拟子类将被发送到该实现:

@example
>>> from collections.abc import Mapping
>>> @@fun.register
... def _(arg: Mapping, verbose=False):
...     if verbose:
...         print("Keys & Values")
...     for key, value in arg.items():
...         print(key, "=>", value)
...
>>> fun(@{"a": "b"@})
a => b
@end example

要检查泛型函数将为给定的类型选择哪个实现，请使用 @code{dispatch()} 属性:

@example
>>> fun.dispatch(float)
<function fun_num at 0x1035a2840>
>>> fun.dispatch(dict)    # note: default implementation
<function fun at 0x103fe0000>
@end example

要访问所有已注册实现，请使用只读的 @code{registry} 属性:

@example
>>> fun.registry.keys()
dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
          <class 'decimal.Decimal'>, <class 'list'>,
          <class 'float'>])
>>> fun.registry[float]
<function fun_num at 0x1035a2840>
>>> fun.registry[object]
<function fun at 0x103fe0000>
@end example


3.4 新版功能.



在 3.7 版更改: @code{register()} 属性现在支持使用类型标注。

@end deffn

@geindex singledispatchmethod (functools 中的类)
@anchor{library/functools functools singledispatchmethod}@anchor{301}
@deffn {类} functools.singledispatchmethod (func)

将一个方法转换为 @ref{302,,单分派} @ref{303,,generic function}。

要定义一个泛型方法，请用 @code{@@singledispatchmethod} 装饰器来装饰它。 当使用 @code{@@singledispatchmethod} 定义一个函数时，请注意发送操作将针对第一个非 @emph{self} 或非 @emph{cls} 参数的类型上:

@example
class Negator:
    @@singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @@neg.register
    def _(self, arg: int):
        return -arg

    @@neg.register
    def _(self, arg: bool):
        return not arg
@end example

@code{@@singledispatchmethod} 支持与其他装饰器如 @ref{310,,@@classmethod} 相嵌套。 请注意为了允许 @code{dispatcher.register}，@code{singledispatchmethod} 必须是 @emph{最外层的} 装饰器。 下面是一个 @code{Negator} 类包含绑定到类的 @code{neg} 方法，而不是一个类实例:

@example
class Negator:
    @@singledispatchmethod
    @@classmethod
    def neg(cls, arg):
        raise NotImplementedError("Cannot negate a")

    @@neg.register
    @@classmethod
    def _(cls, arg: int):
        return -arg

    @@neg.register
    @@classmethod
    def _(cls, arg: bool):
        return not arg
@end example

同样的模式也可被用于其他类似的装饰器: @ref{311,,@@staticmethod}, @ref{ab6,,@@abstractmethod} 等等。


3.8 新版功能.

@end deffn

@geindex update_wrapper() (在 functools 模块中)
@anchor{library/functools functools update_wrapper}@anchor{a44}
@deffn {函数} functools.update_wrapper (wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

更新一个 @emph{wrapper} 函数以使其类似于 @emph{wrapped} 函数。 可选参数为指明原函数的哪些属性要直接被赋值给 wrapper 函数的匹配属性的元组，并且这些 wrapper 函数的属性将使用原函数的对应属性来更新。 这些参数的默认值是模块级常量 @code{WRAPPER_ASSIGNMENTS} (它将被赋值给 wrapper 函数的 @code{__module__}, @code{__name__}, @code{__qualname__}, @code{__annotations__} 和 @code{__doc__} 即文档字符串) 以及 @code{WRAPPER_UPDATES} (它将更新 wrapper 函数的 @code{__dict__} 即实例字典)。

为了允许出于内省和其他目的访问原始函数（例如绕过 @ref{2ff,,lru_cache()} 之类的缓存装饰器），此函数会自动为 wrapper 添加一个指向被包装函数的 @code{__wrapped__} 属性。

此函数的主要目的是在 @ref{174,,decorator} 函数中用来包装被装饰的函数并返回包装器。 如果包装器函数未被更新，则被返回函数的元数据将反映包装器定义而不是原始函数定义，这通常没有什么用处。

@ref{a44,,update_wrapper()} 可以与函数之外的可调用对象一同使用。 在 @emph{assigned} 或 @emph{updated} 中命名的任何属性如果不存在于被包装对象则会被忽略（即该函数将不会尝试在包装器函数上设置它们）。 如果包装器函数自身缺少在 @emph{updated} 中命名的任何属性则仍将引发 @ref{4aa,,AttributeError}。


3.2 新版功能: 自动添加 @code{__wrapped__} 属性。



3.2 新版功能: 默认拷贝 @code{__annotations__} 属性。



在 3.2 版更改: 不存在的属性将不再触发 @ref{4aa,,AttributeError}。



在 3.4 版更改: @code{__wrapped__} 属性现在总是指向被包装的函数，即使该函数定义了 @code{__wrapped__} 属性。 (参见 bpo-17482@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=17482})

@end deffn

@geindex wraps() (在 functools 模块中)
@anchor{library/functools functools wraps}@anchor{95e}
@deffn {函数} @@functools.wraps (wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

这是一个便捷函数，用于在定义包装器函数时发起调用 @ref{a44,,update_wrapper()} 作为函数装饰器。 它等价于 @code{partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)}。 例如:

@example
>>> from functools import wraps
>>> def my_decorator(f):
...     @@wraps(f)
...     def wrapper(*args, **kwds):
...         print('Calling decorated function')
...         return f(*args, **kwds)
...     return wrapper
...
>>> @@my_decorator
... def example():
...     """Docstring"""
...     print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
@end example

如果不使用这个装饰器工厂函数，则 example 函数的名称将变为 @code{'wrapper'}，并且 @code{example()} 原本的文档字符串将会丢失。
@end deffn

@menu
* partial 对象:: 

@end menu

@node partial 对象,,,functools --- 高阶函数和可调用对象上的操作
@anchor{library/functools id1}@anchor{1cf1}@anchor{library/functools partial-objects}@anchor{1cef}
@subsubsection @code{partial} 对象


@ref{8bf,,partial} 对象是由 @ref{8bf,,partial()} 创建的可调用对象。 它们具有三个只读属性：

@geindex func (functools.partial 属性)
@anchor{library/functools functools partial func}@anchor{1cf2}
@deffn {属性} partial.func

一个可调用对象或函数。 对 @ref{8bf,,partial} 对象的调用将被转发给 @ref{1cf2,,func} 并附带新的参数和关键字。
@end deffn

@geindex args (functools.partial 属性)
@anchor{library/functools functools partial args}@anchor{1cf3}
@deffn {属性} partial.args

最左边的位置参数将放置在提供给 @ref{8bf,,partial} 对象调用的位置参数之前。
@end deffn

@geindex keywords (functools.partial 属性)
@anchor{library/functools functools partial keywords}@anchor{1cf4}
@deffn {属性} partial.keywords

当调用 @ref{8bf,,partial} 对象时将要提供的关键字参数。
@end deffn

@ref{8bf,,partial} 对象与 @code{function} 对象的类似之处在于它们都是可调用、可弱引用的对象并可拥有属性。 但两者也存在一些重要的区别。 例如前者不会自动创建 @ref{d37,,__name__} 和 @code{__doc__} 属性。 而且，在类中定义的 @ref{8bf,,partial} 对象的行为类似于静态方法，并且不会在实例属性查找期间转换为绑定方法。

@node operator --- 标准运算符替代函数,,functools --- 高阶函数和可调用对象上的操作,函数式编程模块
@anchor{library/operator doc}@anchor{1cf5}@anchor{library/operator module-operator}@anchor{c2}@anchor{library/operator operator-standard-operators-as-functions}@anchor{1cf6}
@subsection @code{operator} --- 标准运算符替代函数


@geindex operator (模块)

@strong{源代码:} Lib/operator.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/operator.py}

@c import operator
@c from operator import itemgetter, iadd


__________________________________________________________________


@ref{c2,,operator} 模块提供了一套与Python的内置运算符对应的高效率函数。例如，@code{operator.add(x, y)} 与表达式 @code{x+y} 相同。 许多函数名与特殊方法名相同，只是没有双下划线。为了向后兼容性，也保留了许多包含双下划线的函数。为了表述清楚，建议使用没有双下划线的函数。

函数包含的种类有：对象的比较运算、逻辑运算、数学运算以及序列运算。

对象比较函数适用于所有的对象，函数名根据它们对应的比较运算符命名。

@geindex lt() (在 operator 模块中)
@geindex le() (在 operator 模块中)
@geindex eq() (在 operator 模块中)
@geindex ne() (在 operator 模块中)
@geindex ge() (在 operator 模块中)
@geindex gt() (在 operator 模块中)
@geindex __lt__() (在 operator 模块中)
@geindex __le__() (在 operator 模块中)
@geindex __eq__() (在 operator 模块中)
@geindex __ne__() (在 operator 模块中)
@geindex __ge__() (在 operator 模块中)
@geindex __gt__() (在 operator 模块中)
@anchor{library/operator operator lt}@anchor{1cf7}
@deffn {函数} operator.lt (a, b)
@anchor{library/operator operator le}@anchor{1cf8}
@deffnx {函数} operator.le (a, b)
@anchor{library/operator operator eq}@anchor{1cf9}
@deffnx {函数} operator.eq (a, b)
@anchor{library/operator operator ne}@anchor{1cfa}
@deffnx {函数} operator.ne (a, b)
@anchor{library/operator operator ge}@anchor{1cfb}
@deffnx {函数} operator.ge (a, b)
@anchor{library/operator operator gt}@anchor{1cfc}
@deffnx {函数} operator.gt (a, b)
@anchor{library/operator operator __lt__}@anchor{1cfd}
@deffnx {函数} operator.__lt__ (a, b)
@anchor{library/operator operator __le__}@anchor{1cfe}
@deffnx {函数} operator.__le__ (a, b)
@anchor{library/operator operator __eq__}@anchor{1cff}
@deffnx {函数} operator.__eq__ (a, b)
@anchor{library/operator operator __ne__}@anchor{1d00}
@deffnx {函数} operator.__ne__ (a, b)
@anchor{library/operator operator __ge__}@anchor{1d01}
@deffnx {函数} operator.__ge__ (a, b)
@anchor{library/operator operator __gt__}@anchor{1d02}
@deffnx {函数} operator.__gt__ (a, b)

在 @emph{a} 和 @emph{b} 之间进行全比较。具体的，@code{lt(a, b)} 与 @code{a < b} 相同， @code{le(a, b)} 与 @code{a <= b} 相同，@code{eq(a, b)} 与 @code{a == b} 相同，@code{ne(a, b)} 与 @code{a != b} 相同，@code{gt(a, b)} 与 @code{a > b} 相同，@code{ge(a, b)`@w{`}与 `@w{`}a >= b} 相同。注意这些函数可以返回任何值，无论它是否可当作布尔值。关于全比较的更多信息请参考 @ref{16a9,,比较运算} 。
@end deffn

逻辑运算通常也适用于所有对象，并且支持真值检测、标识检测和布尔运算：

@geindex not_() (在 operator 模块中)
@geindex __not__() (在 operator 模块中)
@anchor{library/operator operator not_}@anchor{1d03}
@deffn {函数} operator.not_ (obj)
@anchor{library/operator operator __not__}@anchor{1d04}
@deffnx {函数} operator.__not__ (obj)

返回 @ref{16b5,,not} @emph{obj} 的结果。 （请注意对象实例并没有 @ref{1d04,,__not__()} 方法；只有解释器核心可定义此操作。 结果会受 @ref{d38,,__bool__()} 和 @ref{e98,,__len__()} 方法影响。）
@end deffn

@geindex truth() (在 operator 模块中)
@anchor{library/operator operator truth}@anchor{1d05}
@deffn {函数} operator.truth (obj)

如果 @emph{obj} 为真值则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。 这等价于使用 @ref{2c4,,bool} 构造器。
@end deffn

@geindex is_() (在 operator 模块中)
@anchor{library/operator operator is_}@anchor{1d06}
@deffn {函数} operator.is_ (a, b)

返回 @code{a is b}。 检测对象标识。
@end deffn

@geindex is_not() (在 operator 模块中)
@anchor{library/operator operator is_not}@anchor{1d07}
@deffn {函数} operator.is_not (a, b)

返回 @code{a is not b}。 检测对象标识。
@end deffn

数学和按位运算的种类是最多的：

@geindex abs() (在 operator 模块中)
@geindex __abs__() (在 operator 模块中)
@anchor{library/operator operator abs}@anchor{1d08}
@deffn {函数} operator.abs (obj)
@anchor{library/operator operator __abs__}@anchor{1d09}
@deffnx {函数} operator.__abs__ (obj)

返回 @emph{obj} 的绝对值。
@end deffn

@geindex add() (在 operator 模块中)
@geindex __add__() (在 operator 模块中)
@anchor{library/operator operator add}@anchor{1d0a}
@deffn {函数} operator.add (a, b)
@anchor{library/operator operator __add__}@anchor{1d0b}
@deffnx {函数} operator.__add__ (a, b)

对于数字 @emph{a} 和 @emph{b}，返回 @code{a + b}。
@end deffn

@geindex and_() (在 operator 模块中)
@geindex __and__() (在 operator 模块中)
@anchor{library/operator operator and_}@anchor{1d0c}
@deffn {函数} operator.and_ (a, b)
@anchor{library/operator operator __and__}@anchor{1d0d}
@deffnx {函数} operator.__and__ (a, b)

返回 @emph{x} 和 @emph{y} 按位与的结果。
@end deffn

@geindex floordiv() (在 operator 模块中)
@geindex __floordiv__() (在 operator 模块中)
@anchor{library/operator operator floordiv}@anchor{1d0e}
@deffn {函数} operator.floordiv (a, b)
@anchor{library/operator operator __floordiv__}@anchor{1d0f}
@deffnx {函数} operator.__floordiv__ (a, b)

返回 @code{a // b}。
@end deffn

@geindex index() (在 operator 模块中)
@geindex __index__() (在 operator 模块中)
@anchor{library/operator operator index}@anchor{15ee}
@deffn {函数} operator.index (a)
@anchor{library/operator operator __index__}@anchor{1d10}
@deffnx {函数} operator.__index__ (a)

返回 @emph{a} 转换为整数的结果。 等价于 @code{a.__index__()}。
@end deffn

@geindex inv() (在 operator 模块中)
@geindex invert() (在 operator 模块中)
@geindex __inv__() (在 operator 模块中)
@geindex __invert__() (在 operator 模块中)
@anchor{library/operator operator inv}@anchor{1d11}
@deffn {函数} operator.inv (obj)
@anchor{library/operator operator invert}@anchor{1d12}
@deffnx {函数} operator.invert (obj)
@anchor{library/operator operator __inv__}@anchor{1d13}
@deffnx {函数} operator.__inv__ (obj)
@anchor{library/operator operator __invert__}@anchor{1d14}
@deffnx {函数} operator.__invert__ (obj)

返回数字 @emph{obj} 按位取反的结果。 这等价于 @code{~obj}。
@end deffn

@geindex lshift() (在 operator 模块中)
@geindex __lshift__() (在 operator 模块中)
@anchor{library/operator operator lshift}@anchor{1d15}
@deffn {函数} operator.lshift (a, b)
@anchor{library/operator operator __lshift__}@anchor{1d16}
@deffnx {函数} operator.__lshift__ (a, b)

返回 @emph{a} 左移 @emph{b} 位的结果。
@end deffn

@geindex mod() (在 operator 模块中)
@geindex __mod__() (在 operator 模块中)
@anchor{library/operator operator mod}@anchor{1d17}
@deffn {函数} operator.mod (a, b)
@anchor{library/operator operator __mod__}@anchor{1d18}
@deffnx {函数} operator.__mod__ (a, b)

返回 @code{a % b}。
@end deffn

@geindex mul() (在 operator 模块中)
@geindex __mul__() (在 operator 模块中)
@anchor{library/operator operator mul}@anchor{1cea}
@deffn {函数} operator.mul (a, b)
@anchor{library/operator operator __mul__}@anchor{1d19}
@deffnx {函数} operator.__mul__ (a, b)

对于数字 @emph{a} 和 @emph{b}，返回 @code{a * b}。
@end deffn

@geindex matmul() (在 operator 模块中)
@geindex __matmul__() (在 operator 模块中)
@anchor{library/operator operator matmul}@anchor{816}
@deffn {函数} operator.matmul (a, b)
@anchor{library/operator operator __matmul__}@anchor{1d1a}
@deffnx {函数} operator.__matmul__ (a, b)

返回 @code{a @@ b}。


3.5 新版功能.

@end deffn

@geindex neg() (在 operator 模块中)
@geindex __neg__() (在 operator 模块中)
@anchor{library/operator operator neg}@anchor{1d1b}
@deffn {函数} operator.neg (obj)
@anchor{library/operator operator __neg__}@anchor{1d1c}
@deffnx {函数} operator.__neg__ (obj)

返回 @emph{obj} 取负的结果 (@code{-obj})。
@end deffn

@geindex or_() (在 operator 模块中)
@geindex __or__() (在 operator 模块中)
@anchor{library/operator operator or_}@anchor{1d1d}
@deffn {函数} operator.or_ (a, b)
@anchor{library/operator operator __or__}@anchor{1d1e}
@deffnx {函数} operator.__or__ (a, b)

返回 @emph{a} 和 @emph{b} 按位或的结果。
@end deffn

@geindex pos() (在 operator 模块中)
@geindex __pos__() (在 operator 模块中)
@anchor{library/operator operator pos}@anchor{1d1f}
@deffn {函数} operator.pos (obj)
@anchor{library/operator operator __pos__}@anchor{1d20}
@deffnx {函数} operator.__pos__ (obj)

返回 @emph{obj} 取正的结果 (@code{+obj})。
@end deffn

@geindex pow() (在 operator 模块中)
@geindex __pow__() (在 operator 模块中)
@anchor{library/operator operator pow}@anchor{1d21}
@deffn {函数} operator.pow (a, b)
@anchor{library/operator operator __pow__}@anchor{1d22}
@deffnx {函数} operator.__pow__ (a, b)

对于数字 @emph{a} 和 @emph{b}，返回 @code{a ** b}。
@end deffn

@geindex rshift() (在 operator 模块中)
@geindex __rshift__() (在 operator 模块中)
@anchor{library/operator operator rshift}@anchor{1d23}
@deffn {函数} operator.rshift (a, b)
@anchor{library/operator operator __rshift__}@anchor{1d24}
@deffnx {函数} operator.__rshift__ (a, b)

返回 @emph{a} 右移 @emph{b} 位的结果。
@end deffn

@geindex sub() (在 operator 模块中)
@geindex __sub__() (在 operator 模块中)
@anchor{library/operator operator sub}@anchor{1d25}
@deffn {函数} operator.sub (a, b)
@anchor{library/operator operator __sub__}@anchor{1d26}
@deffnx {函数} operator.__sub__ (a, b)

返回 @code{a - b}。
@end deffn

@geindex truediv() (在 operator 模块中)
@geindex __truediv__() (在 operator 模块中)
@anchor{library/operator operator truediv}@anchor{1d27}
@deffn {函数} operator.truediv (a, b)
@anchor{library/operator operator __truediv__}@anchor{1d28}
@deffnx {函数} operator.__truediv__ (a, b)

返回 @code{a / b} 例如 2/3 将等于 .66 而不是 0。 这也被称为“真”除法。
@end deffn

@geindex xor() (在 operator 模块中)
@geindex __xor__() (在 operator 模块中)
@anchor{library/operator operator xor}@anchor{1d29}
@deffn {函数} operator.xor (a, b)
@anchor{library/operator operator __xor__}@anchor{1d2a}
@deffnx {函数} operator.__xor__ (a, b)

返回 @emph{a} 和 @emph{b} 按位异或的结果。
@end deffn

适用于序列的操作（其中一些也适用于映射）包括：

@geindex concat() (在 operator 模块中)
@geindex __concat__() (在 operator 模块中)
@anchor{library/operator operator concat}@anchor{1d2b}
@deffn {函数} operator.concat (a, b)
@anchor{library/operator operator __concat__}@anchor{1d2c}
@deffnx {函数} operator.__concat__ (a, b)

对于序列 @emph{a} 和 @emph{b}，返回 @code{a + b}。
@end deffn

@geindex contains() (在 operator 模块中)
@geindex __contains__() (在 operator 模块中)
@anchor{library/operator operator contains}@anchor{17a}
@deffn {函数} operator.contains (a, b)
@anchor{library/operator operator __contains__}@anchor{1d2d}
@deffnx {函数} operator.__contains__ (a, b)

返回 @code{b in a} 检测的结果。 请注意操作数是反序的。
@end deffn

@geindex countOf() (在 operator 模块中)
@anchor{library/operator operator countOf}@anchor{17c}
@deffn {函数} operator.countOf (a, b)

返回 @emph{b} 在 @emph{a} 中的出现次数。
@end deffn

@geindex delitem() (在 operator 模块中)
@geindex __delitem__() (在 operator 模块中)
@anchor{library/operator operator delitem}@anchor{1d2e}
@deffn {函数} operator.delitem (a, b)
@anchor{library/operator operator __delitem__}@anchor{1d2f}
@deffnx {函数} operator.__delitem__ (a, b)

移除 @emph{a} 中索引号为 @emph{b} 的值。
@end deffn

@geindex getitem() (在 operator 模块中)
@geindex __getitem__() (在 operator 模块中)
@anchor{library/operator operator getitem}@anchor{1d30}
@deffn {函数} operator.getitem (a, b)
@anchor{library/operator operator __getitem__}@anchor{1d31}
@deffnx {函数} operator.__getitem__ (a, b)

返回 @emph{a} 中索引为 @emph{b} 的值。
@end deffn

@geindex indexOf() (在 operator 模块中)
@anchor{library/operator operator indexOf}@anchor{17b}
@deffn {函数} operator.indexOf (a, b)

返回 @emph{b} 在 @emph{a} 中首次出现所在的索引号。
@end deffn

@geindex setitem() (在 operator 模块中)
@geindex __setitem__() (在 operator 模块中)
@anchor{library/operator operator setitem}@anchor{1d32}
@deffn {函数} operator.setitem (a, b, c)
@anchor{library/operator operator __setitem__}@anchor{1d33}
@deffnx {函数} operator.__setitem__ (a, b, c)

将 @emph{a} 中索引号为 @emph{b} 的值设为 @emph{c}。
@end deffn

@geindex length_hint() (在 operator 模块中)
@anchor{library/operator operator length_hint}@anchor{971}
@deffn {函数} operator.length_hint (obj, default=0)

返回对象 @emph{o} 的估计长度。 首先尝试返回其实际长度，再使用 @ref{903,,object.__length_hint__()} 得出估计值，最后返回默认值。


3.4 新版功能.

@end deffn

@ref{c2,,operator} 模块还定义了一些用于常规属性和条目查找的工具。 这些工具适合用来编写快速字段提取器作为 @ref{cff,,map()}, @ref{54f,,sorted()}, @ref{1ce5,,itertools.groupby()} 或其他需要相应函数参数的函数的参数。

@geindex attrgetter() (在 operator 模块中)
@anchor{library/operator operator attrgetter}@anchor{814}
@deffn {函数} operator.attrgetter (attr)

@deffnx {函数} operator.attrgetter (*attrs)

返回一个可从操作数中获取 @emph{attr} 的可调用对象。 如果请求了一个以上的属性，则返回一个属性元组。 属性名称还可包含点号。 例如：


@itemize *

@item 
在 @code{f = attrgetter('name')} 之后，调用 @code{f(b)} 将返回 @code{b.name}。

@item 
在 @code{f = attrgetter('name', 'date')} 之后，调用 @code{f(b)} 将返回 @code{(b.name, b.date)}。

@item 
在 @code{f = attrgetter('name.first', 'name.last')} 之后，调用 @code{f(b)} 将返回 @code{(b.name.first, b.name.last)}。
@end itemize

等价于:

@example
def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj
@end example
@end deffn

@geindex itemgetter() (在 operator 模块中)
@anchor{library/operator operator itemgetter}@anchor{393}
@deffn {函数} operator.itemgetter (item)

@deffnx {函数} operator.itemgetter (*items)

返回一个使用操作数的 @ref{1d31,,__getitem__()} 方法从操作数中获取 @emph{item} 的可调用对象。 如果指定了多个条目，则返回一个查找值的元组。 例如：


@itemize *

@item 
在 @code{f = itemgetter(2)} 之后，调用 @code{f(r)} 将返回 @code{r[2]}。

@item 
在 @code{g = itemgetter(2, 5, 3)} 之后，调用 @code{g(r)} 将返回 @code{(r[2], r[5], r[3])}。
@end itemize

等价于:

@example
def itemgetter(*items):
    if len(items) == 1:
        item = items[0]
        def g(obj):
            return obj[item]
    else:
        def g(obj):
            return tuple(obj[item] for item in items)
    return g
@end example

传入的条目可以为操作数的 @ref{1d31,,__getitem__()} 所接受的任何类型。 字典接受任意可哈希的值。 列表、元组和字符串接受 index 或 slice 对象：

@example
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1, 3, 5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2, None))('ABCDEFG')
'CDEFG'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
@end example

使用 @ref{393,,itemgetter()} 从元组的记录中提取特定字段的例子：

@example
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
@end example
@end deffn

@geindex methodcaller() (在 operator 模块中)
@anchor{library/operator operator methodcaller}@anchor{815}
@deffn {函数} operator.methodcaller (name, /, *args, **kwargs)

返回一个在操作数上调用 @emph{name} 方法的可调用对象。 如果给出额外的参数和/或关键字参数，它们也将被传给该方法。 例如：


@itemize *

@item 
在 @code{f = methodcaller('name')} 之后，调用 @code{f(b)} 将返回 @code{b.name()}。

@item 
在 @code{f = methodcaller('name', 'foo', bar=1)} 之后，调用 @code{f(b)} 将返回 @code{b.name('foo', bar=1)}。
@end itemize

等价于:

@example
def methodcaller(name, /, *args, **kwargs):
    def caller(obj):
        return getattr(obj, name)(*args, **kwargs)
    return caller
@end example
@end deffn

@menu
* 将运算符映射到函数:: 
* 原地运算符:: 

@end menu

@node 将运算符映射到函数,原地运算符,,operator --- 标准运算符替代函数
@anchor{library/operator mapping-operators-to-functions}@anchor{1d34}@anchor{library/operator operator-map}@anchor{1d35}
@subsubsection 将运算符映射到函数


以下表格显示了抽象运算是如何对应于 Python 语法中的运算符和 @ref{c2,,operator} 模块中的函数的。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

运算

@tab

语法

@tab

函数

@item

加法

@tab

@code{a + b}

@tab

@code{add(a, b)}

@item

字符串拼接

@tab

@code{seq1 + seq2}

@tab

@code{concat(seq1, seq2)}

@item

包含测试

@tab

@code{obj in seq}

@tab

@code{contains(seq, obj)}

@item

除法

@tab

@code{a / b}

@tab

@code{truediv(a, b)}

@item

除法

@tab

@code{a // b}

@tab

@code{floordiv(a, b)}

@item

按位与

@tab

@code{a & b}

@tab

@code{and_(a, b)}

@item

按位异或

@tab

@code{a ^ b}

@tab

@code{xor(a, b)}

@item

按位取反

@tab

@code{~ a}

@tab

@code{invert(a)}

@item

按位或

@tab

@code{a | b}

@tab

@code{or_(a, b)}

@item

取幂

@tab

@code{a ** b}

@tab

@code{pow(a, b)}

@item

标识

@tab

@code{a is b}

@tab

@code{is_(a, b)}

@item

标识

@tab

@code{a is not b}

@tab

@code{is_not(a, b)}

@item

索引赋值

@tab

@code{obj[k] = v}

@tab

@code{setitem(obj, k, v)}

@item

索引删除

@tab

@code{del obj[k]}

@tab

@code{delitem(obj, k)}

@item

索引取值

@tab

@code{obj[k]}

@tab

@code{getitem(obj, k)}

@item

左移

@tab

@code{a << b}

@tab

@code{lshift(a, b)}

@item

取模

@tab

@code{a % b}

@tab

@code{mod(a, b)}

@item

乘法

@tab

@code{a * b}

@tab

@code{mul(a, b)}

@item

矩阵乘法

@tab

@code{a @@ b}

@tab

@code{matmul(a, b)}

@item

取反（算术）

@tab

@code{- a}

@tab

@code{neg(a)}

@item

取反（逻辑）

@tab

@code{not a}

@tab

@code{not_(a)}

@item

正数

@tab

@code{+ a}

@tab

@code{pos(a)}

@item

右移

@tab

@code{a >> b}

@tab

@code{rshift(a, b)}

@item

切片赋值

@tab

@code{seq[i:j] = values}

@tab

@code{setitem(seq, slice(i, j), values)}

@item

切片删除

@tab

@code{del seq[i:j]}

@tab

@code{delitem(seq, slice(i, j))}

@item

切片取值

@tab

@code{seq[i:j]}

@tab

@code{getitem(seq, slice(i, j))}

@item

字符串格式化

@tab

@code{s % obj}

@tab

@code{mod(s, obj)}

@item

减法

@tab

@code{a - b}

@tab

@code{sub(a, b)}

@item

真值测试

@tab

@code{obj}

@tab

@code{truth(obj)}

@item

比较

@tab

@code{a < b}

@tab

@code{lt(a, b)}

@item

比较

@tab

@code{a <= b}

@tab

@code{le(a, b)}

@item

相等

@tab

@code{a == b}

@tab

@code{eq(a, b)}

@item

不等

@tab

@code{a != b}

@tab

@code{ne(a, b)}

@item

比较

@tab

@code{a >= b}

@tab

@code{ge(a, b)}

@item

比较

@tab

@code{a > b}

@tab

@code{gt(a, b)}

@end multitable


@node 原地运算符,,将运算符映射到函数,operator --- 标准运算符替代函数
@anchor{library/operator in-place-operators}@anchor{1d36}
@subsubsection 原地运算符


许多运算都有“原地”版本。 以下列出的是提供对原地运算符相比通常语法更底层访问的函数，例如 @ref{1d37,,statement} @code{x += y} 相当于 @code{x = operator.iadd(x, y)}。 换一种方式来讲就是 @code{z = operator.iadd(x, y)} 等价于语句块 @code{z = x; z += y}。

在这些例子中，请注意当调用一个原地方法时，运算和赋值是分成两个步骤来执行的。 下面列出的原地函数只执行第一步即调用原地方法。 第二步赋值则不加处理。

对于不可变的目标例如字符串、数字和元组，更新的值会被计算，但不会被再被赋值给输入变量：

@example
>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'
@end example

对于可变的目标例如列表和字典，原地方法将执行更新，因此不需要后续赋值操作：

@example
>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
@end example

@geindex iadd() (在 operator 模块中)
@geindex __iadd__() (在 operator 模块中)
@anchor{library/operator operator iadd}@anchor{1d38}
@deffn {函数} operator.iadd (a, b)
@anchor{library/operator operator __iadd__}@anchor{1d39}
@deffnx {函数} operator.__iadd__ (a, b)

@code{a = iadd(a, b)} 等价于 @code{a += b}。
@end deffn

@geindex iand() (在 operator 模块中)
@geindex __iand__() (在 operator 模块中)
@anchor{library/operator operator iand}@anchor{1d3a}
@deffn {函数} operator.iand (a, b)
@anchor{library/operator operator __iand__}@anchor{1d3b}
@deffnx {函数} operator.__iand__ (a, b)

@code{a = iand(a, b)} 等价于 @code{a &= b}。
@end deffn

@geindex iconcat() (在 operator 模块中)
@geindex __iconcat__() (在 operator 模块中)
@anchor{library/operator operator iconcat}@anchor{1d3c}
@deffn {函数} operator.iconcat (a, b)
@anchor{library/operator operator __iconcat__}@anchor{1d3d}
@deffnx {函数} operator.__iconcat__ (a, b)

@code{a = iconcat(a, b)} 等价于 @code{a += b} 其中 @emph{a} 和 @emph{b} 为序列。
@end deffn

@geindex ifloordiv() (在 operator 模块中)
@geindex __ifloordiv__() (在 operator 模块中)
@anchor{library/operator operator ifloordiv}@anchor{1d3e}
@deffn {函数} operator.ifloordiv (a, b)
@anchor{library/operator operator __ifloordiv__}@anchor{1d3f}
@deffnx {函数} operator.__ifloordiv__ (a, b)

@code{a = ifloordiv(a, b)} 等价于 @code{a //= b}。
@end deffn

@geindex ilshift() (在 operator 模块中)
@geindex __ilshift__() (在 operator 模块中)
@anchor{library/operator operator ilshift}@anchor{1d40}
@deffn {函数} operator.ilshift (a, b)
@anchor{library/operator operator __ilshift__}@anchor{1d41}
@deffnx {函数} operator.__ilshift__ (a, b)

@code{a = ilshift(a, b)} 等价于 @code{a <<= b}。
@end deffn

@geindex imod() (在 operator 模块中)
@geindex __imod__() (在 operator 模块中)
@anchor{library/operator operator imod}@anchor{1d42}
@deffn {函数} operator.imod (a, b)
@anchor{library/operator operator __imod__}@anchor{1d43}
@deffnx {函数} operator.__imod__ (a, b)

@code{a = imod(a, b)} 等价于 @code{a %= b}。
@end deffn

@geindex imul() (在 operator 模块中)
@geindex __imul__() (在 operator 模块中)
@anchor{library/operator operator imul}@anchor{1d44}
@deffn {函数} operator.imul (a, b)
@anchor{library/operator operator __imul__}@anchor{1d45}
@deffnx {函数} operator.__imul__ (a, b)

@code{a = imul(a, b)} 等价于 @code{a *= b}。
@end deffn

@geindex imatmul() (在 operator 模块中)
@geindex __imatmul__() (在 operator 模块中)
@anchor{library/operator operator imatmul}@anchor{817}
@deffn {函数} operator.imatmul (a, b)
@anchor{library/operator operator __imatmul__}@anchor{1d46}
@deffnx {函数} operator.__imatmul__ (a, b)

@code{a = imatmul(a, b)} 等价于 @code{a @@= b}。


3.5 新版功能.

@end deffn

@geindex ior() (在 operator 模块中)
@geindex __ior__() (在 operator 模块中)
@anchor{library/operator operator ior}@anchor{1d47}
@deffn {函数} operator.ior (a, b)
@anchor{library/operator operator __ior__}@anchor{1d48}
@deffnx {函数} operator.__ior__ (a, b)

@code{a = ior(a, b)} 等价于 @code{a |= b}。
@end deffn

@geindex ipow() (在 operator 模块中)
@geindex __ipow__() (在 operator 模块中)
@anchor{library/operator operator ipow}@anchor{1d49}
@deffn {函数} operator.ipow (a, b)
@anchor{library/operator operator __ipow__}@anchor{1d4a}
@deffnx {函数} operator.__ipow__ (a, b)

@code{a = ipow(a, b)} 等价于 @code{a **= b}。
@end deffn

@geindex irshift() (在 operator 模块中)
@geindex __irshift__() (在 operator 模块中)
@anchor{library/operator operator irshift}@anchor{1d4b}
@deffn {函数} operator.irshift (a, b)
@anchor{library/operator operator __irshift__}@anchor{1d4c}
@deffnx {函数} operator.__irshift__ (a, b)

@code{a = irshift(a, b)} 等价于 @code{a >>= b}。
@end deffn

@geindex isub() (在 operator 模块中)
@geindex __isub__() (在 operator 模块中)
@anchor{library/operator operator isub}@anchor{1d4d}
@deffn {函数} operator.isub (a, b)
@anchor{library/operator operator __isub__}@anchor{1d4e}
@deffnx {函数} operator.__isub__ (a, b)

@code{a = isub(a, b)} 等价于 @code{a -= b}。
@end deffn

@geindex itruediv() (在 operator 模块中)
@geindex __itruediv__() (在 operator 模块中)
@anchor{library/operator operator itruediv}@anchor{1d4f}
@deffn {函数} operator.itruediv (a, b)
@anchor{library/operator operator __itruediv__}@anchor{1d50}
@deffnx {函数} operator.__itruediv__ (a, b)

@code{a = itruediv(a, b)} 等价于 @code{a /= b}。
@end deffn

@geindex ixor() (在 operator 模块中)
@geindex __ixor__() (在 operator 模块中)
@anchor{library/operator operator ixor}@anchor{1d51}
@deffn {函数} operator.ixor (a, b)
@anchor{library/operator operator __ixor__}@anchor{1d52}
@deffnx {函数} operator.__ixor__ (a, b)

@code{a = ixor(a, b)} 等价于 @code{a ^= b}。
@end deffn

@node 文件和目录访问,数据持久化,函数式编程模块,Python 标准库
@anchor{library/filesys doc}@anchor{1d53}@anchor{library/filesys file-and-directory-access}@anchor{1d54}@anchor{library/filesys filesys}@anchor{1d55}
@section 文件和目录访问


本章中描述的模块处理磁盘文件和目录。 例如，有一些模块用于读取文件的属性，以可移植的方式操作路径以及创建临时文件。 本章的完整模块列表如下：

@menu
* pathlib: pathlib --- 面向对象的文件系统路径. 面向对象的文件系统路径
* os.path: os path --- 常用路径操作. 常用路径操作
* fileinput: fileinput --- 迭代来自多个输入流的行. 迭代来自多个输入流的行
* stat: stat --- 解析 stat 结果. 解析 stat() 结果
* filecmp: filecmp --- 文件及目录的比较. 文件及目录的比较
* tempfile: tempfile --- 生成临时文件和目录. 生成临时文件和目录
* glob: glob --- Unix 风格路径名模式扩展. Unix 风格路径名模式扩展
* fnmatch: fnmatch --- Unix 文件名模式匹配. Unix 文件名模式匹配
* linecache: linecache --- 随机读写文本行. 随机读写文本行
* shutil: shutil --- 高阶文件操作. 高阶文件操作

@end menu

@node pathlib --- 面向对象的文件系统路径,os path --- 常用路径操作,,文件和目录访问
@anchor{library/pathlib doc}@anchor{1d56}@anchor{library/pathlib module-pathlib}@anchor{c8}@anchor{library/pathlib pathlib-object-oriented-filesystem-paths}@anchor{1d57}
@subsection @code{pathlib} --- 面向对象的文件系统路径


@geindex pathlib (模块)


3.4 新版功能.


@strong{源代码} Lib/pathlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pathlib.py}

@geindex path; operations


__________________________________________________________________


该模块提供表示文件系统路径的类，其语义适用于不同的操作系统。路径类被分为提供纯计算操作而没有 I/O 的 @ref{1d58,,纯路径}，以及从纯路径继承而来但提供 I/O 操作的 @ref{1d59,,具体路径}。

@image{python-figures/pathlib-inheritance,,,,png}

如果以前从未用过此模块，或不确定哪个类适合完成任务，那要用的可能就是 @ref{336,,Path}。它在运行代码的平台上实例化为 @ref{1d59,,具体路径}。

在一些用例中纯路径很有用，例如：


@enumerate 

@item 
如果你想要在 Unix 设备上操作 Windows 路径（或者相反）。你不应在 Unix 上实例化一个 @ref{1d5a,,WindowsPath}，但是你可以实例化 @ref{1d5b,,PureWindowsPath}。

@item 
你只想操作路径但不想实际访问操作系统。在这种情况下，实例化一个纯路径是有用的，因为它们没有任何访问操作系统的操作。
@end enumerate


@subsubheading 参见


@geindex Python 提高建议; PEP 428
PEP 428@footnote{https://www.python.org/dev/peps/pep-0428}：pathlib 模块 -- 面向对象的文件系统路径。



@subsubheading 参见


对于底层的路径字符串操作，你也可以使用 @ref{c5,,os.path} 模块。


@menu
* 基础使用:: 
* 纯路径:: 
* 具体路径:: 
* 对应的 os 模块的工具:: 

@end menu

@node 基础使用,纯路径,,pathlib --- 面向对象的文件系统路径
@anchor{library/pathlib basic-use}@anchor{1d5c}
@subsubsection 基础使用


导入主类:

@example
>>> from pathlib import Path
@end example

列出子目录:

@example
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]
@end example

列出当前目录树下的所有 Python 源代码文件:

@example
>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]
@end example

在目录树中移动:

@example
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
@end example

查询路径的属性:

@example
>>> q.exists()
True
>>> q.is_dir()
False
@end example

打开一个文件:

@example
>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'
@end example

@node 纯路径,具体路径,基础使用,pathlib --- 面向对象的文件系统路径
@anchor{library/pathlib id1}@anchor{1d5d}@anchor{library/pathlib pure-paths}@anchor{1d58}
@subsubsection 纯路径


纯路径对象提供了不实际访问文件系统的路径处理操作。有三种方式来访问这些类，也是不同的风格：

@geindex PurePath (pathlib 中的类)
@anchor{library/pathlib pathlib PurePath}@anchor{236}
@deffn {类} pathlib.PurePath (*pathsegments)

一个通用的类，代表当前系统的路径风格（实例化为 @ref{1d5e,,PurePosixPath} 或者 @ref{1d5b,,PureWindowsPath}）:

@example
>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')
@end example

每一个 @emph{pathsegments} 的元素可能是一个代表路径片段的字符串，一个返回字符串的实现了 @ref{5ee,,os.PathLike} 接口的对象，或者另一个路径对象:

@example
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
@end example

当 @emph{pathsegments} 为空的时候，假定为当前目录:

@example
>>> PurePath()
PurePosixPath('.')
@end example

当给出一些绝对路径，最后一位将被当作锚（模仿 @ref{1110,,os.path.join()} 的行为）:

@example
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
@end example

但是，在 Windows 路径中，改变本地根目录并不会丢弃之前盘符的设置:

@example
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
@end example

假斜线和单独的点都会被消除，但是双点 （@code{‘..’}） 不会，以防改变符号链接的含义。

@example
>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')
@end example

（一个很 naïve 的做法是让 @code{PurePosixPath('foo/../bar')} 等同于 @code{PurePosixPath('bar')}，如果 @code{foo} 是一个指向其他目录的符号链接那么这个做法就将出错）

纯路径对象实现了 @ref{5ee,,os.PathLike} 接口，允许它们在任何接受此接口的地方使用。


在 3.6 版更改: 添加了 @ref{5ee,,os.PathLike} 接口支持。

@end deffn

@geindex PurePosixPath (pathlib 中的类)
@anchor{library/pathlib pathlib PurePosixPath}@anchor{1d5e}
@deffn {类} pathlib.PurePosixPath (*pathsegments)

一个 @ref{236,,PurePath} 的子类，路径风格不同于 Windows 文件系统:

@example
>>> PurePosixPath('/etc')
PurePosixPath('/etc')
@end example

@emph{pathsegments} 参数的指定和 @ref{236,,PurePath} 相同。
@end deffn

@geindex PureWindowsPath (pathlib 中的类)
@anchor{library/pathlib pathlib PureWindowsPath}@anchor{1d5b}
@deffn {类} pathlib.PureWindowsPath (*pathsegments)

@ref{236,,PurePath} 的一个子类，路径风格为 Windows 文件系统路径:

@example
>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')
@end example

@emph{pathsegments} 参数的指定和 @ref{236,,PurePath} 相同。
@end deffn

无论你正运行什么系统，你都可以实例化这些类，因为它们提供的操作不做任何系统调用。

@menu
* 通用性质:: 
* 运算符: 运算符<2>. 
* 访问个别部分:: 
* 方法和特征属性:: 

@end menu

@node 通用性质,运算符<2>,,纯路径
@anchor{library/pathlib general-properties}@anchor{1d5f}
@subsubsection 通用性质


路径是不可变并可哈希的。相同风格的路径可以排序与比较。这些性质尊重对应风格的大小写转换语义:

@example
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in @{ PureWindowsPath('foo') @}
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True
@end example

不同风格的路径比较得到不等的结果并且无法被排序:

@example
>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
@end example

@node 运算符<2>,访问个别部分,通用性质,纯路径
@anchor{library/pathlib operators}@anchor{1d60}
@subsubsection 运算符


斜杠 @code{/} 操作符有助于创建子路径，就像 @ref{1110,,os.path.join()} 一样:

@example
>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
@end example

文件对象可用于任何接受 @ref{5ee,,os.PathLike} 接口实现的地方。

@example
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'
@end example

路径的字符串表示法为它自己原始的文件系统路径（以原生形式，例如在 Windows 下使用反斜杠）。你可以传递给任何需要字符串形式路径的函数。

@example
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
@end example

类似地，在路径上调用 @ref{172,,bytes} 将原始文件系统路径作为字节对象给出，就像被 @ref{5f2,,os.fsencode()} 编码一样:

@example
>>> bytes(p)
b'/etc'
@end example

@cartouche
@quotation 注解 
只推荐在 Unix 下调用 @ref{172,,bytes}。在 Windows， unicode 形式是文件系统路径的规范表示法。
@end quotation
@end cartouche

@node 访问个别部分,方法和特征属性,运算符<2>,纯路径
@anchor{library/pathlib accessing-individual-parts}@anchor{1d61}
@subsubsection 访问个别部分


为了访问路径独立的部分 （组件），使用以下特征属性：

@geindex PurePath.parts() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath parts}@anchor{1d62}
@deffn {数据} PurePath.parts

一个元组，可以访问路径的多个组件:

@example
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')
@end example

（注意盘符和本地根目录是如何重组的）
@end deffn

@node 方法和特征属性,,访问个别部分,纯路径
@anchor{library/pathlib methods-and-properties}@anchor{1d63}
@subsubsection 方法和特征属性


@c from pathlib import PurePath, PurePosixPath, PureWindowsPath

纯路径提供以下方法和特征属性：

@geindex PurePath.drive() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath drive}@anchor{1d64}
@deffn {数据} PurePath.drive

一个表示驱动器盘符或命名的字符串，如果存在:

@example
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
'@w{'}
>>> PurePosixPath('/etc').drive
'@w{'}
@end example

UNC 分享也被认作驱动器:

@example
>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
@end example
@end deffn

@geindex PurePath.root() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath root}@anchor{1d65}
@deffn {数据} PurePath.root

一个表示（本地或全局）根的字符串，如果存在:

@example
>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
'@w{'}
>>> PurePosixPath('/etc').root
'/'
@end example

UNC 分享一样拥有根:

@example
>>> PureWindowsPath('//host/share').root
'\\'
@end example
@end deffn

@geindex PurePath.anchor() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath anchor}@anchor{1d66}
@deffn {数据} PurePath.anchor

驱动器和根的联合:

@example
>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
@end example
@end deffn

@geindex PurePath.parents() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath parents}@anchor{1d67}
@deffn {数据} PurePath.parents

An immutable sequence providing access to the logical ancestors of
the path:

@example
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
@end example
@end deffn

@geindex PurePath.parent() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath parent}@anchor{1d68}
@deffn {数据} PurePath.parent

此路径的逻辑父路径:

@example
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')
@end example

你不能超过一个 anchor 或空路径:

@example
>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')
@end example

@cartouche
@quotation 注解 
这是一个单纯的词法操作，因此有以下行为:

@example
>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')
@end example

如果要向上遍历任意文件系统路径，建议首先调用 @ref{1d69,,Path.resolve()} 以解析符号链接并消除 @cite{".."} 部分。
@end quotation
@end cartouche
@end deffn

@geindex PurePath.name() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath name}@anchor{1d6a}
@deffn {数据} PurePath.name

一个表示最后路径组件的字符串，排除了驱动器与根目录，如果存在的话:

@example
>>> PurePosixPath('my/library/setup.py').name
'setup.py'
@end example

UNC 驱动器名不被考虑:

@example
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
'@w{'}
@end example
@end deffn

@geindex PurePath.suffix() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath suffix}@anchor{1d6b}
@deffn {数据} PurePath.suffix

最后一个组件的文件扩展名，如果存在:

@example
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
'@w{'}
@end example
@end deffn

@geindex PurePath.suffixes() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath suffixes}@anchor{1d6c}
@deffn {数据} PurePath.suffixes

路径的文件扩展名列表:

@example
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
@end example
@end deffn

@geindex PurePath.stem() (在 pathlib 模块中)
@anchor{library/pathlib pathlib PurePath stem}@anchor{1d6d}
@deffn {数据} PurePath.stem

最后一个路径组件，除去后缀:

@example
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
@end example
@end deffn

@geindex as_posix() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath as_posix}@anchor{1d6e}
@deffn {方法} PurePath.as_posix ()

返回使用正斜杠（@code{/}）的路径字符串:

@example
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
@end example
@end deffn

@geindex as_uri() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath as_uri}@anchor{1d6f}
@deffn {方法} PurePath.as_uri ()

将路径表示为 @code{file} URL。如果并非绝对路径，抛出 @ref{16d,,ValueError}。

@example
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
@end example
@end deffn

@geindex is_absolute() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath is_absolute}@anchor{1d70}
@deffn {方法} PurePath.is_absolute ()

返回此路径是否为绝对路径。如果路径同时拥有驱动器符与根路径（如果风格允许）则将被认作绝对路径。

@example
>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False

>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
>>> PureWindowsPath('//some/share').is_absolute()
True
@end example
@end deffn

@geindex is_relative_to() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath is_relative_to}@anchor{1d71}
@deffn {方法} PurePath.is_relative_to (*other)

返回此路径是否相对于 @emph{other} 的路径。

@example
>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False
@end example


3.9 新版功能.

@end deffn

@geindex is_reserved() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath is_reserved}@anchor{1d72}
@deffn {方法} PurePath.is_reserved ()

在 @ref{1d5b,,PureWindowsPath}，如果路径是被 Windows 保留的则返回 @code{True}，否则 @code{False}。在 @ref{1d5e,,PurePosixPath}，总是返回 @code{False}。

@example
>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False
@end example

当保留路径上的文件系统被调用，则可能出现玄学失败或者意料之外的效应。
@end deffn

@geindex joinpath() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath joinpath}@anchor{1d73}
@deffn {方法} PurePath.joinpath (*other)

调用此方法等同于将每个 @emph{other} 参数中的项目连接在一起:

@example
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
@end example
@end deffn

@geindex match() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath match}@anchor{1d74}
@deffn {方法} PurePath.match (pattern)

将此路径与提供的通配符风格的模式匹配。如果匹配成功则返回 @code{True}，否则返回 @code{False}。

如果 @emph{pattern} 是相对的，则路径可以是相对路径或绝对路径，并且匹配是从右侧完成的：

@example
>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
@end example

如果 @emph{pattern} 是绝对的，则路径必须是绝对的，并且路径必须完全匹配:

@example
>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
False
@end example

与其他方法一样，是否大小写敏感遵循平台的默认规则:

@example
>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
@end example
@end deffn

@geindex relative_to() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath relative_to}@anchor{1d75}
@deffn {方法} PurePath.relative_to (*other)

计算此路径相对 @emph{other} 表示路径的版本。如果不可计算，则抛出 ValueError:

@example
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 694, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute.
@end example

注意：此函数是 @ref{236,,PurePath} 的一部分并且适用于字符串。 它不会检查或访问下层的文件结构。
@end deffn

@geindex with_name() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath with_name}@anchor{1d76}
@deffn {方法} PurePath.with_name (name)

返回一个新的路径并修改 @ref{1d6a,,name}。如果原本路径没有 name，ValueError 被抛出:

@example
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
@end example
@end deffn

@geindex with_stem() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath with_stem}@anchor{1d77}
@deffn {方法} PurePath.with_stem (stem)

返回一个带有修改后 @ref{1d6d,,stem} 的新路径。 如果原路径没有名称，则会引发 ValueError:

@example
>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_stem('lib')
PureWindowsPath('c:/Downloads/lib.gz')
>>> p = PureWindowsPath('c:/')
>>> p.with_stem('@w{'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
    return self.with_name(stem + self.suffix)
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
@end example


3.9 新版功能.

@end deffn

@geindex with_suffix() (pathlib.PurePath 方法)
@anchor{library/pathlib pathlib PurePath with_suffix}@anchor{11af}
@deffn {方法} PurePath.with_suffix (suffix)

返回一个新的路径并修改 @ref{1d6b,,suffix}。如果原本的路径没有后缀，新的 @emph{suffix} 则被追加以代替。如果 @emph{suffix} 是空字符串，则原本的后缀被移除:

@example
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('@w{'})
PureWindowsPath('README')
@end example
@end deffn

@node 具体路径,对应的 os 模块的工具,纯路径,pathlib --- 面向对象的文件系统路径
@anchor{library/pathlib concrete-paths}@anchor{1d59}@anchor{library/pathlib id2}@anchor{1d78}
@subsubsection 具体路径


具体路径是纯路径的子类。除了后者提供的操作之外，它们还提供了对路径对象进行系统调用的方法。有三种方法可以实例化具体路径:

@geindex Path (pathlib 中的类)
@anchor{library/pathlib pathlib Path}@anchor{336}
@deffn {类} pathlib.Path (*pathsegments)

一个 @ref{236,,PurePath} 的子类，此类以当前系统的路径风格表示路径（实例化为 @ref{1d79,,PosixPath} 或 @ref{1d5a,,WindowsPath}）:

@example
>>> Path('setup.py')
PosixPath('setup.py')
@end example

@emph{pathsegments} 参数的指定和 @ref{236,,PurePath} 相同。
@end deffn

@geindex PosixPath (pathlib 中的类)
@anchor{library/pathlib pathlib PosixPath}@anchor{1d79}
@deffn {类} pathlib.PosixPath (*pathsegments)

一个 @ref{336,,Path} 和 @ref{1d5e,,PurePosixPath} 的子类，此类表示一个非 Windows 文件系统的具体路径:

@example
>>> PosixPath('/etc')
PosixPath('/etc')
@end example

@emph{pathsegments} 参数的指定和 @ref{236,,PurePath} 相同。
@end deffn

@geindex WindowsPath (pathlib 中的类)
@anchor{library/pathlib pathlib WindowsPath}@anchor{1d5a}
@deffn {类} pathlib.WindowsPath (*pathsegments)

@ref{336,,Path} 和 @ref{1d5b,,PureWindowsPath} 的子类，从类表示一个 Windows 文件系统的具体路径:

@example
>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')
@end example

@emph{pathsegments} 参数的指定和 @ref{236,,PurePath} 相同。
@end deffn

你只能实例化与当前系统风格相同的类（允许系统调用作用于不兼容的路径风格可能在应用程序中导致缺陷或失败）:

@example
>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'WindowsPath' on your system
@end example

@menu
* 方法: 方法<2>. 

@end menu

@node 方法<2>,,,具体路径
@anchor{library/pathlib methods}@anchor{1d7a}
@subsubsection 方法


除纯路径方法外，实体路径还提供以下方法。 如果系统调用失败（例如因为路径不存在）这些方法中许多都会引发 @ref{30b,,OSError}。


在 3.8 版更改: 对于包含 OS 层级无法表示字符的路径，@ref{337,,exists()}, @ref{338,,is_dir()}, @ref{339,,is_file()}, @ref{33a,,is_mount()}, @ref{33b,,is_symlink()}, @ref{33c,,is_block_device()}, @ref{33d,,is_char_device()}, @ref{33e,,is_fifo()}, @ref{33f,,is_socket()} 现在将返回 @code{False} 而不是引发异常。


@geindex cwd() (pathlib.Path 类方法)
@anchor{library/pathlib pathlib Path cwd}@anchor{1d7b}
@deffn {方法} classmethod Path.cwd ()

返回一个新的表示当前目录的路径对象（和 @ref{1162,,os.getcwd()} 返回的相同）:

@example
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
@end example
@end deffn

@geindex home() (pathlib.Path 类方法)
@anchor{library/pathlib pathlib Path home}@anchor{824}
@deffn {方法} classmethod Path.home ()

返回一个表示当前用户家目录的新路径对象（和 @ref{333,,os.path.expanduser()} 构造含 @code{~} 路径返回的相同）:

@example
>>> Path.home()
PosixPath('/home/antoine')
@end example

Note that unlike @ref{333,,os.path.expanduser()}, on POSIX systems a
@ref{3f1,,KeyError} or @ref{3e4,,RuntimeError} will be raised, and on Windows systems a
@ref{3e4,,RuntimeError} will be raised if home directory can't be resolved.


3.5 新版功能.

@end deffn

@geindex stat() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path stat}@anchor{1d7c}
@deffn {方法} Path.stat ()

返回一个 @ref{1208,,os.stat_result} 对象，其中包含有关此路径的信息，例如 @ref{328,,os.stat()}。 结果会在每次调用此方法时重新搜索。

@example
>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
@end example
@end deffn

@geindex chmod() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path chmod}@anchor{1d7d}
@deffn {方法} Path.chmod (mode)

改变文件的模式和权限，和 @ref{b18,,os.chmod()} 一样:

@example
>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060
@end example
@end deffn

@geindex exists() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path exists}@anchor{337}
@deffn {方法} Path.exists ()

此路径是否指向一个已存在的文件或目录:

@example
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False
@end example

@cartouche
@quotation 注解 
如果路径指向一个符号链接， @ref{337,,exists()} 返回此符号链接是否指向存在的文件或目录。
@end quotation
@end cartouche
@end deffn

@geindex expanduser() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path expanduser}@anchor{823}
@deffn {方法} Path.expanduser ()

返回展开了包含 @code{~} 和 @code{~user} 的构造，就和 @ref{333,,os.path.expanduser()} 一样:

@example
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')
@end example

Note that unlike @ref{333,,os.path.expanduser()}, on POSIX systems a
@ref{3f1,,KeyError} or @ref{3e4,,RuntimeError} will be raised, and on Windows systems a
@ref{3e4,,RuntimeError} will be raised if home directory can't be resolved.


3.5 新版功能.

@end deffn

@geindex glob() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path glob}@anchor{10cd}
@deffn {方法} Path.glob (pattern)

解析相对于此路径的通配符 @emph{pattern}，产生所有匹配的文件:

@example
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]
@end example

"@code{**}" 模式表示 “此目录以及所有子目录，递归”。换句话说，它启用递归通配:

@example
>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]
@end example

@cartouche
@quotation 注解 
在一个较大的目录树中使用 "@code{**}" 模式可能会消耗非常多的时间。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{pathlib.Path.glob} 附带参数 @code{self}, @code{pattern}。
@end deffn

@geindex group() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path group}@anchor{1d7e}
@deffn {方法} Path.group ()

返回拥有此文件的用户组。如果文件的 GID 无法在系统数据库中找到，将抛出 @ref{3f1,,KeyError} 。
@end deffn

@geindex is_dir() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_dir}@anchor{338}
@deffn {方法} Path.is_dir ()

如果路径指向一个目录（或者一个指向目录的符号链接）则返回 @code{True}，如果指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_file() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_file}@anchor{339}
@deffn {方法} Path.is_file ()

如果路径指向一个正常的文件（或者一个指向正常文件的符号链接）则返回 @code{True}，如果指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_mount() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_mount}@anchor{33a}
@deffn {方法} Path.is_mount ()

如果路径是一个 @emph{挂载点 <mount point>}：在文件系统中被其他不同的文件系统挂载的地点。在 POSIX 系统，此函数检查 @emph{path} 的父级 —— @code{path/..} 是否处于一个和 @emph{path} 不同的设备中，或者 file:@cite{path/..} 和 @emph{path} 是否指向相同设备的相同 i-node —— 这能检测所有 Unix 以及 POSIX 变种上的挂载点。 Windows 上未实现。


3.7 新版功能.

@end deffn

@geindex is_symlink() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_symlink}@anchor{33b}
@deffn {方法} Path.is_symlink ()

如果路径指向符号链接则返回 @code{True}， 否则 @code{False}。

如果路径不存在也返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_socket() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_socket}@anchor{33f}
@deffn {方法} Path.is_socket ()

如果路径指向一个 Unix socket 文件（或者指向 Unix socket 文件的符号链接）则返回 @code{True}，如果指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_fifo() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_fifo}@anchor{33e}
@deffn {方法} Path.is_fifo ()

如果路径指向一个先进先出存储（或者指向先进先出存储的符号链接）则返回 @code{True} ，指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_block_device() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_block_device}@anchor{33c}
@deffn {方法} Path.is_block_device ()

如果文件指向一个块设备（或者指向块设备的符号链接）则返回 @code{True}，指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex is_char_device() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path is_char_device}@anchor{33d}
@deffn {方法} Path.is_char_device ()

如果路径指向一个字符设备（或指向字符设备的符号链接）则返回 @code{True}，指向其他类型的文件则返回 @code{False}。

当路径不存在或者是一个破损的符号链接时也会返回 @code{False}；其他错误（例如权限错误）被传播。
@end deffn

@geindex iterdir() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path iterdir}@anchor{1d7f}
@deffn {方法} Path.iterdir ()

当路径指向一个目录时，产生该路径下的对象的路径:

@example
>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')
@end example

子条目会以任意顺序生成，并且不包括特殊条目 @code{'.'} 和 @code{'..'}。 如果迭代器创建之后有文件在目录中被移除或添加，是否要包括该文件所对应的路径对象并没有明确规定。
@end deffn

@geindex lchmod() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path lchmod}@anchor{1d80}
@deffn {方法} Path.lchmod (mode)

就像 @ref{1d7d,,Path.chmod()} 但是如果路径指向符号链接则是修改符号链接的模式，而不是修改符号链接的目标。
@end deffn

@geindex lstat() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path lstat}@anchor{1d81}
@deffn {方法} Path.lstat ()

就和 @ref{1d7c,,Path.stat()} 一样，但是如果路径指向符号链接，则是返回符号链接而不是目标的信息。
@end deffn

@geindex mkdir() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path mkdir}@anchor{822}
@deffn {方法} Path.mkdir (mode=0o777, parents=False, exist_ok=False)

新建给定路径的目录。如果给出了 @emph{mode} ，它将与当前进程的 @code{umask} 值合并来决定文件模式和访问标志。如果路径已经存在，则抛出 @ref{a42,,FileExistsError}。

如果 @emph{parents} 为真值，任何找不到的父目录都会伴随着此路径被创建；它们会以默认权限被创建，而不考虑 @emph{mode} 设置（模仿 POSIX 的 @code{mkdir -p} 命令）。

如果 @emph{parents} 为假值（默认），则找不到的父级目录会引发 @ref{8b7,,FileNotFoundError}。

如果 @emph{exist_ok} 为 false（默认），则在目标已存在的情况下抛出 @ref{a42,,FileExistsError}。

如果 @emph{exist_ok} 为 true， 则 @ref{a42,,FileExistsError} 异常将被忽略（和 POSIX @code{mkdir -p} 命令行为相同），但是只有在最后一个路径组件不是现存的非目录文件时才生效。


在 3.5 版更改: @emph{exist_ok} 形参被加入。

@end deffn

@geindex open() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path open}@anchor{1d82}
@deffn {方法} Path.open (mode='r', buffering=-1, encoding=None, errors=None, newline=None)

打开路径指向的文件，就像内置的 @ref{16f,,open()} 函数所做的一样:

@example
>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
@end example
@end deffn

@geindex owner() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path owner}@anchor{1d83}
@deffn {方法} Path.owner ()

返回拥有此文件的用户名。如果文件的 UID 无法在系统数据库中找到，则抛出 @ref{3f1,,KeyError}。
@end deffn

@geindex read_bytes() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path read_bytes}@anchor{828}
@deffn {方法} Path.read_bytes ()

以字节对象的形式返回路径指向的文件的二进制内容:

@example
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
@end example


3.5 新版功能.

@end deffn

@geindex read_text() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path read_text}@anchor{826}
@deffn {方法} Path.read_text (encoding=None, errors=None)

以字符串形式返回路径指向的文件的解码后文本内容。

@example
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
@end example

文件先被打开然后关闭。有和 @ref{16f,,open()} 一样的可选形参。


3.5 新版功能.

@end deffn

@geindex readlink() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path readlink}@anchor{1d1}
@deffn {方法} Path.readlink ()

返回符号链接所指向的路径（即 @ref{1d2,,os.readlink()} 的返回值）:

@example
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')
@end example


3.9 新版功能.

@end deffn

@geindex rename() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path rename}@anchor{1d84}
@deffn {方法} Path.rename (target)

将文件或目录重命名为给定的 @emph{target}，并返回一个新的指向 @emph{target} 的 Path 实例。 在 Unix 上，如果 @emph{target} 存在且为一个文件，如果用户有足够权限，则它将被静默地替换。 @emph{target} 可以是一个字符串或者另一个路径对象:

@example
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'
@end example

目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录，而 @emph{不是} 相对于 Path 对象的目录。


在 3.8 版更改: 添加了返回值，返回新的 Path 实例。

@end deffn

@geindex replace() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path replace}@anchor{1d85}
@deffn {方法} Path.replace (target)

将文件或目录重命名为给定的 @emph{target}，并返回一个新的指向 @emph{target} 的 Path 实例。 如果 @emph{target} 指向一个现有文件或空目录，则它将被无条件地替换。

目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录，而 @emph{不是} 相对于 Path 对象的目录。


在 3.8 版更改: 添加了返回值，返回新的 Path 实例。

@end deffn

@geindex resolve() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path resolve}@anchor{1d69}
@deffn {方法} Path.resolve (strict=False)

将路径绝对化，解析任何符号链接。返回新的路径对象:

@example
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')
@end example

"@code{..}" 组件也将被消除（只有这一种方法这么做）:

@example
>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
@end example

如果路径不存在并且 @emph{strict} 设为 @code{True}，则抛出 @ref{8b7,,FileNotFoundError}。如果 @emph{strict} 为 @code{False}，则路径将被尽可能地解析并且任何剩余部分都会被不检查是否存在地追加。如果在解析路径上发生无限循环，则抛出 @ref{3e4,,RuntimeError}。


3.6 新版功能: 加入*strict* 参数（3.6之前的版本相当于strict值为True）

@end deffn

@geindex rglob() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path rglob}@anchor{10ce}
@deffn {方法} Path.rglob (pattern)

这就像调用 @ref{10cd,,Path.glob()} 并在给定的相对 @emph{pattern} 前面添加了 "@code{**/}":

@example
>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]
@end example

引发一个 @ref{fec,,审计事件} @code{pathlib.Path.rglob} 附带参数 @code{self}, @code{pattern}。
@end deffn

@geindex rmdir() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path rmdir}@anchor{1d86}
@deffn {方法} Path.rmdir ()

移除此目录。此目录必须为空的。
@end deffn

@geindex samefile() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path samefile}@anchor{821}
@deffn {方法} Path.samefile (other_path)

返回此目录是否指向与可能是字符串或者另一个路径对象的 @emph{other_path} 相同的文件。语义类似于 @ref{976,,os.path.samefile()} 与 @ref{975,,os.path.samestat()}。

如果两者都以同一原因无法访问，则抛出 @ref{30b,,OSError}。

@example
>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True
@end example


3.5 新版功能.

@end deffn

@geindex symlink_to() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path symlink_to}@anchor{1d87}
@deffn {方法} Path.symlink_to (target, target_is_directory=False)

将此路径创建为指向 @emph{target} 的符号链接。在 Windows 下，如果链接的目标是一个目录则 @emph{target_is_directory} 必须为 true （默认为 @code{False}）。在 POSIX 下， @emph{target_is_directory} 的值将被忽略。

@example
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8
@end example

@cartouche
@quotation 注解 
参数的顺序（link, target) 和 @ref{b20,,os.symlink()} 是相反的。
@end quotation
@end cartouche
@end deffn

@geindex link_to() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path link_to}@anchor{340}
@deffn {方法} Path.link_to (target)

创建硬链接 @emph{target} 指向此路径。

@cartouche
@quotation 警告 
此函数不是将此路径设为指向 @emph{target} 的硬链接，这与函数和参数名的本义不同。 参数顺序 (target, link) 与 @ref{1d87,,Path.symlink_to()} 相反，而与 @ref{b1a,,os.link()} 一致。
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@geindex touch() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path touch}@anchor{1d88}
@deffn {方法} Path.touch (mode=0o666, exist_ok=True)

将给定的路径创建为文件。如果给出了 @emph{mode} 它将与当前进程的 @code{umask} 值合并以确定文件的模式和访问标志。如果文件已经存在，则当 @emph{exist_ok} 为 true 则函数仍会成功（并且将它的修改事件更新为当前事件），否则抛出 @ref{a42,,FileExistsError}。
@end deffn

@geindex unlink() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path unlink}@anchor{1152}
@deffn {方法} Path.unlink (missing_ok=False)

移除此文件或符号链接。如果路径指向目录，则用 @ref{1d86,,Path.rmdir()} 代替。

如果 @emph{missing_ok} 为假值（默认），则如果路径不存在将会引发 @ref{8b7,,FileNotFoundError}。

如果 @emph{missing_ok} 为真值，则 @ref{8b7,,FileNotFoundError} 异常将被忽略（和 POSIX @code{rm -f} 命令的行为相同）。


在 3.8 版更改: 增加了 @emph{missing_ok} 形参。

@end deffn

@geindex write_bytes() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path write_bytes}@anchor{827}
@deffn {方法} Path.write_bytes (data)

将文件以二进制模式打开，写入 @emph{data} 并关闭:

@example
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'
@end example

一个同名的现存文件将被覆盖。


3.5 新版功能.

@end deffn

@geindex write_text() (pathlib.Path 方法)
@anchor{library/pathlib pathlib Path write_text}@anchor{825}
@deffn {方法} Path.write_text (data, encoding=None, errors=None)

将文件以文本模式打开，写入 @emph{data} 并关闭:

@example
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'
@end example

同名的现有文件会被覆盖。 可选形参的含义与 @ref{16f,,open()} 的相同。


3.5 新版功能.

@end deffn

@node 对应的 os 模块的工具,,具体路径,pathlib --- 面向对象的文件系统路径
@anchor{library/pathlib correspondence-to-tools-in-the-os-module}@anchor{1d89}
@subsubsection 对应的 @code{os} 模块的工具


以下是一个映射了 @ref{c4,,os} 与 @ref{236,,PurePath}/@ref{336,,Path} 对应相同的函数的表。

@cartouche
@quotation 注解 
尽管 @ref{1d8a,,os.path.relpath()} 和 @ref{1d75,,PurePath.relative_to()} 拥有相同的重叠的用例，但是它们语义相差很大，不能认为它们等价。
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

os 和 os.path

@tab

pathlib

@item

@ref{d80,,os.path.abspath()}

@tab

@ref{1d69,,Path.resolve()}

@item

@ref{b18,,os.chmod()}

@tab

@ref{1d7d,,Path.chmod()}

@item

@ref{b1b,,os.mkdir()}

@tab

@ref{822,,Path.mkdir()}

@item

@ref{4cc,,os.makedirs()}

@tab

@ref{822,,Path.mkdir()}

@item

@ref{b1d,,os.rename()}

@tab

@ref{1d84,,Path.rename()}

@item

@ref{b1e,,os.replace()}

@tab

@ref{1d85,,Path.replace()}

@item

@ref{b1f,,os.rmdir()}

@tab

@ref{1d86,,Path.rmdir()}

@item

@ref{b1c,,os.remove()}, @ref{b21,,os.unlink()}

@tab

@ref{1152,,Path.unlink()}

@item

@ref{1162,,os.getcwd()}

@tab

@ref{1d7b,,Path.cwd()}

@item

@ref{32c,,os.path.exists()}

@tab

@ref{337,,Path.exists()}

@item

@ref{333,,os.path.expanduser()}

@tab

@ref{823,,Path.expanduser()} 和 @ref{824,,Path.home()}

@item

@ref{b25,,os.listdir()}

@tab

@ref{1d7f,,Path.iterdir()}

@item

@ref{32e,,os.path.isdir()}

@tab

@ref{338,,Path.is_dir()}

@item

@ref{32f,,os.path.isfile()}

@tab

@ref{339,,Path.is_file()}

@item

@ref{32a,,os.path.islink()}

@tab

@ref{33b,,Path.is_symlink()}

@item

@ref{b1a,,os.link()}

@tab

@ref{340,,Path.link_to()}

@item

@ref{b20,,os.symlink()}

@tab

@ref{1d87,,Path.symlink_to()}

@item

@ref{1d2,,os.readlink()}

@tab

@ref{1d1,,Path.readlink()}

@item

@ref{328,,os.stat()}

@tab

@ref{1d7c,,Path.stat()},
@ref{1d83,,Path.owner()},
@ref{1d7e,,Path.group()}

@item

@ref{1d8b,,os.path.isabs()}

@tab

@ref{1d70,,PurePath.is_absolute()}

@item

@ref{1110,,os.path.join()}

@tab

@ref{1d73,,PurePath.joinpath()}

@item

@ref{1d8c,,os.path.basename()}

@tab

@ref{1d6a,,PurePath.name}

@item

@ref{1d8d,,os.path.dirname()}

@tab

@ref{1d68,,PurePath.parent}

@item

@ref{976,,os.path.samefile()}

@tab

@ref{821,,Path.samefile()}

@item

@ref{1d8e,,os.path.splitext()}

@tab

@ref{1d6b,,PurePath.suffix}

@end multitable


@node os path --- 常用路径操作,fileinput --- 迭代来自多个输入流的行,pathlib --- 面向对象的文件系统路径,文件和目录访问
@anchor{library/os path doc}@anchor{1d8f}@anchor{library/os path module-os path}@anchor{c5}@anchor{library/os path os-path-common-pathname-manipulations}@anchor{1d90}
@subsection @code{os.path} --- 常用路径操作


@geindex os.path (模块)

@strong{源代码:} Lib/posixpath.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/posixpath.py} (用于 POSIX) 和 Lib/ntpath.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/ntpath.py} (用于 Windows)。

@geindex path; operations


__________________________________________________________________


此模块实现了一些有用的路径名称相关函数。 要读取或写入文件请参见 @ref{16f,,open()}，对于访问文件系统请参阅 @ref{c4,,os} 模块。 传给 path 形参的可以是字符串、字节串或者任何实现了 @ref{5ee,,os.PathLike} 协议的对象。

与unix shell不同，Python不执行任何 @emph{自动} 路径扩展。当应用程序需要类似shell的路径扩展时，可以显式调用诸如 @ref{333,,expanduser()} 和 @ref{e11,,expandvars()} 之类的函数。 （另请参见 @ref{88,,glob} 模块。）


@subsubheading 参见


@ref{c8,,pathlib} 模块提供高级路径对象。


@cartouche
@quotation 注解 
所有这些函数都仅接受字节或字符串对象作为其参数。如果返回路径或文件名，则结果是相同类型的对象。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
由于不同的操作系统具有不同的路径名称约定，因此标准库中有此模块的几个版本。@ref{c5,,os.path} 模块始终是适合 Python 运行的操作系统的路径模块，因此可用于本地路径。但是，如果操作的路径 @emph{总是} 以一种不同的格式显示，那么也可以分别导入和使用各个模块。它们都具有相同的接口：


@itemize *

@item 
@code{posixpath} 用于Unix 样式的路径

@item 
@code{ntpath} 用于 Windows 路径
@end itemize
@end quotation
@end cartouche


在 3.8 版更改: @ref{32c,,exists()}、@ref{32d,,lexists()}、@ref{32e,,isdir()}、@ref{32f,,isfile()}、@ref{32a,,islink()} 和 @ref{330,,ismount()} 现在遇到系统层面上不可表示的字符或字节的路径时，会返回 @code{False}，而不是抛出异常。


@geindex abspath() (在 os.path 模块中)
@anchor{library/os path os path abspath}@anchor{d80}
@deffn {函数} os.path.abspath (path)

返回路径 @emph{path} 的绝对路径（标准化的）。在大多数平台上，这等同于用 @code{normpath(join(os.getcwd(), path))} 的方式调用 @ref{d7f,,normpath()} 函数。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex basename() (在 os.path 模块中)
@anchor{library/os path os path basename}@anchor{1d8c}
@deffn {函数} os.path.basename (path)

返回路径 @emph{path} 的基本名称。这是将 @emph{path} 传入函数 @ref{1d91,,split()} 之后，返回的一对值中的第二个元素。请注意，此函数的结果与Unix @code{basename} 程序不同。@code{basename} 在 @code{'/foo/bar/'} 上返回 @code{'bar'}，而 @ref{1d8c,,basename()} 函数返回一个空字符串 (@code{'@w{'}})。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex commonpath() (在 os.path 模块中)
@anchor{library/os path os path commonpath}@anchor{81e}
@deffn {函数} os.path.commonpath (paths)

接受包含多个路径的序列 @emph{paths}，返回 @emph{paths} 的最长公共子路径。如果 @emph{paths} 同时包含绝对路径和相对路径，或 @emph{paths} 在不同的驱动器上，或 @emph{paths} 为空，则抛出 @ref{16d,,ValueError} 异常。与 @ref{81f,,commonprefix()} 不同，本方法返回有效路径。

@ref{14c1,,可用性}: Unix, Windows。


3.5 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 序列。

@end deffn

@geindex commonprefix() (在 os.path 模块中)
@anchor{library/os path os path commonprefix}@anchor{81f}
@deffn {函数} os.path.commonprefix (list)

接受包含多个路径的 @emph{列表}，返回所有路径的最长公共前缀（逐字符比较）。如果 @emph{列表} 为空，则返回空字符串 (@code{'@w{'}})。

@cartouche
@quotation 注解 
此函数是逐字符比较，因此可能返回无效路径。要获取有效路径，参见 @ref{81e,,commonpath()}。

@example
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'
@end example
@end quotation
@end cartouche


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex dirname() (在 os.path 模块中)
@anchor{library/os path os path dirname}@anchor{1d8d}
@deffn {函数} os.path.dirname (path)

返回路径 @emph{path} 的目录名称。这是将 @emph{path} 传入函数 @ref{1d91,,split()} 之后，返回的一对值中的第一个元素。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex exists() (在 os.path 模块中)
@anchor{library/os path os path exists}@anchor{32c}
@deffn {函数} os.path.exists (path)

如果 @emph{path} 指向一个已存在的路径或已打开的文件描述符，返回 @code{True}。对于失效的符号链接，返回 @code{False}。在某些平台上，如果使用 @ref{328,,os.stat()} 查询到目标文件没有执行权限，即使 @emph{path} 确实存在，本函数也可能返回 @code{False}。


在 3.3 版更改: @emph{path} 现在可以是一个整数：如果该整数是一个已打开的文件描述符，返回 @code{True}，否则返回 @code{False}。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex lexists() (在 os.path 模块中)
@anchor{library/os path os path lexists}@anchor{32d}
@deffn {函数} os.path.lexists (path)

如果 @emph{path} 指向一个已存在的路径，返回 @code{True}。对于失效的符号链接，也返回 @code{True}。在缺失 @ref{329,,os.lstat()} 的平台上等同于 @ref{32c,,exists()}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex ~ (tilde); home directory expansion

@geindex expanduser() (在 os.path 模块中)
@anchor{library/os path os path expanduser}@anchor{333}
@deffn {函数} os.path.expanduser (path)

在 Unix 和 Windows 上，将参数中开头部分的 @code{~} 或 @code{~user} 替换为当前 @emph{用户} 的家目录并返回。

@geindex 模块; pwd

在 Unix 上，开头的 @code{~} 会被环境变量 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} 代替，如果变量未设置，则通过内置模块 @ref{d6,,pwd} 在 password 目录中查找当前用户的主目录。以 @code{~user} 开头则直接在 password 目录中查找。

在 Windows 上，如果设置了 
@geindex USERPROFILE
@geindex 环境变量; USERPROFILE
@code{USERPROFILE}，就使用这个变量，否则会将 
@geindex HOMEPATH
@geindex 环境变量; HOMEPATH
@code{HOMEPATH} 和 
@geindex HOMEDRIVE
@geindex 环境变量; HOMEDRIVE
@code{HOMEDRIVE} 结合在一起使用。以 @code{~user} 开头则将上述方法生成路径的最后一截目录替换成 user。

如果展开路径失败，或者路径不是以波浪号开头，则路径将保持不变。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.8 版更改: Windows 不再使用 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME}。

@end deffn

@geindex $ (dollar); environment variables expansion
@geindex % (percent); environment variables expansion (Windows)

@geindex expandvars() (在 os.path 模块中)
@anchor{library/os path os path expandvars}@anchor{e11}
@deffn {函数} os.path.expandvars (path)

输入带有环境变量的路径作为参数，返回展开变量以后的路径。@code{$name} 或 @code{$@{name@}} 形式的子字符串被环境变量 @emph{name} 的值替换。格式错误的变量名称和对不存在变量的引用保持不变。

在 Windows 上，除了 @code{$name} 和 @code{$@{name@}} 外，还可以展开 @code{%name%}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex getatime() (在 os.path 模块中)
@anchor{library/os path os path getatime}@anchor{1d92}
@deffn {函数} os.path.getatime (path)

返回 @emph{path} 的最后访问时间。返回值是一个浮点数，为纪元秒数（参见 @ref{10c,,time} 模块）。如果该文件不存在或不可访问，则抛出 @ref{30b,,OSError} 异常。
@end deffn

@geindex getmtime() (在 os.path 模块中)
@anchor{library/os path os path getmtime}@anchor{1d93}
@deffn {函数} os.path.getmtime (path)

返回 @emph{path} 的最后修改时间。返回值是一个浮点数，为纪元秒数（参见 @ref{10c,,time} 模块）。如果该文件不存在或不可访问，则抛出 @ref{30b,,OSError} 异常。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex getctime() (在 os.path 模块中)
@anchor{library/os path os path getctime}@anchor{1d94}
@deffn {函数} os.path.getctime (path)

返回 @emph{path} 在系统中的 ctime，在有些系统（比如 Unix）上，它是元数据的最后修改时间，其他系统（比如 Windows）上，它是 @emph{path} 的创建时间。返回值是一个数，为纪元秒数（参见 @ref{10c,,time} 模块）。如果该文件不存在或不可访问，则抛出 @ref{30b,,OSError} 异常。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex getsize() (在 os.path 模块中)
@anchor{library/os path os path getsize}@anchor{1d95}
@deffn {函数} os.path.getsize (path)

返回 @emph{path} 的大小，以字节为单位。如果该文件不存在或不可访问，则抛出 @ref{30b,,OSError} 异常。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex isabs() (在 os.path 模块中)
@anchor{library/os path os path isabs}@anchor{1d8b}
@deffn {函数} os.path.isabs (path)

如果 @emph{path} 是一个绝对路径，则返回 @code{True}。在 Unix 上，它就是以斜杠开头，而在 Windows 上，它可以是去掉驱动器号后以斜杠（或反斜杠）开头。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex isfile() (在 os.path 模块中)
@anchor{library/os path os path isfile}@anchor{32f}
@deffn {函数} os.path.isfile (path)

如果 @emph{path} 是 @ref{32c,,现有的} 常规文件，则返回 @code{True}。本方法会跟踪符号链接，因此，对于同一路径，@ref{32a,,islink()} 和 @ref{32f,,isfile()} 都可能为 @code{True}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex isdir() (在 os.path 模块中)
@anchor{library/os path os path isdir}@anchor{32e}
@deffn {函数} os.path.isdir (path)

如果 @emph{path} 是 @ref{32c,,现有的} 目录，则返回 @code{True}。本方法会跟踪符号链接，因此，对于同一路径，@ref{32a,,islink()} 和 @ref{32e,,isdir()} 都可能为 @code{True}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex islink() (在 os.path 模块中)
@anchor{library/os path os path islink}@anchor{32a}
@deffn {函数} os.path.islink (path)

如果 @emph{path} 指向的 @ref{32c,,现有} 目录条目是一个符号链接，则返回 @code{True}。如果 Python 运行时不支持符号链接，则总是返回 @code{False}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex ismount() (在 os.path 模块中)
@anchor{library/os path os path ismount}@anchor{330}
@deffn {函数} os.path.ismount (path)

如果路径 @emph{path} 是 @emph{挂载点} （文件系统中挂载其他文件系统的点），则返回 @code{True}。在 POSIX 上，该函数检查 @emph{path} 的父目录 @code{@emph{path}/..} 是否在与 @emph{path} 不同的设备上，或者 @code{@emph{path}/..} 和 @emph{path} 是否指向同一设备上的同一 inode（这一检测挂载点的方法适用于所有 Unix 和 POSIX 变体）。本方法不能可靠地检测同一文件系统上的绑定挂载 (bind mount)。在 Windows 上，盘符和共享 UNC 始终是挂载点，对于任何其他路径，将调用 @code{GetVolumePathName} 来查看它是否与输入的路径不同。


3.4 新版功能: 支持在 Windows 上检测非根挂载点。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex join() (在 os.path 模块中)
@anchor{library/os path os path join}@anchor{1110}
@deffn {函数} os.path.join (path, *paths)

智能地拼接一个或多个路径部分。 返回值是 @emph{path} 和 @emph{*paths} 的所有成员的拼接，其中每个非空部分后面都紧跟一个目录分隔符，最后一个部分除外，这意味着如果最后一个部分为空，则结果将以分隔符结尾。 如果某个部分为绝对路径，则之前的所有部分会被丢弃并从绝对路径部分开始继续拼接。

在 Windows 上，遇到绝对路径部分（例如 @code{r'\foo'}）时，不会重置盘符。如果某部分路径包含盘符，则会丢弃所有先前的部分，并重置盘符。请注意，由于每个驱动器都有一个“当前目录”，所以 @code{os.path.join("c:", "foo")} 表示驱动器 @code{C:} 上当前目录的相对路径 (@code{c:foo})，而不是 @code{c:\foo}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 用于 @emph{path} 和 @emph{paths} 。

@end deffn

@geindex normcase() (在 os.path 模块中)
@anchor{library/os path os path normcase}@anchor{1d96}
@deffn {函数} os.path.normcase (path)

规范路径的大小写。在 Windows 上，将路径中的所有字符都转换为小写，并将正斜杠转换为反斜杠。在其他操作系统上返回原路径。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex normpath() (在 os.path 模块中)
@anchor{library/os path os path normpath}@anchor{d7f}
@deffn {函数} os.path.normpath (path)

@quotation

通过折叠多余的分隔符和对上级目录的引用来标准化路径名，所以 @code{A//B}、@code{A/B/}、@code{A/./B} 和 @code{A/foo/../B} 都会转换成 @code{A/B}。这个字符串操作可能会改变带有符号链接的路径的含义。在 Windows 上，本方法将正斜杠转换为反斜杠。要规范大小写，请使用 @ref{1d96,,normcase()}。
@end quotation

@cartouche
@quotation 注解 
@quotation

在 POSIX 系统上，根据 IEEE Std 1003.1 2013 Edition; 4.13 Pathname Resolution@footnote{http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13}，如果一个路径名称以两个斜杠开始，则开始字符之后的第一个部分将以具体实现所定义的方式来解读，但是超过两个开始字符则将被视为单个字符。
@end quotation


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end quotation
@end cartouche
@end deffn

@geindex realpath() (在 os.path 模块中)
@anchor{library/os path os path realpath}@anchor{334}
@deffn {函数} os.path.realpath (path)

返回指定文件的规范路径，消除路径中存在的任何符号链接（如果操作系统支持）。

@cartouche
@quotation 注解 
当发生符号链接循环时，返回的路径将是该循环的某个组成部分，但不能保证是哪个部分。
@end quotation
@end cartouche


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.8 版更改: 在 Windows 上现在可以正确解析符号链接和交接点 (junction point)。

@end deffn

@geindex relpath() (在 os.path 模块中)
@anchor{library/os path os path relpath}@anchor{1d8a}
@deffn {函数} os.path.relpath (path, start=os.curdir)

返回从当前目录或可选的 @emph{start} 目录至 @emph{path} 的相对文件路径。 这只是一个路径计算：不会访问文件系统来确认 @emph{path} 或 @emph{start} 是否存在或其性质。 在 Windows 上，当 @emph{path} 和 @emph{start} 位于不同驱动器时将引发 @ref{16d,,ValueError}。

@emph{start} 默认为 @ref{1d97,,os.curdir}。

@ref{14c1,,可用性}: Unix, Windows。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex samefile() (在 os.path 模块中)
@anchor{library/os path os path samefile}@anchor{976}
@deffn {函数} os.path.samefile (path1, path2)

如果两个路径都指向相同的文件或目录，则返回 @code{True}。这由设备号和 inode 号确定，在任一路径上调用 @ref{328,,os.stat()} 失败则抛出异常。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加了 Windows 支持。



在 3.4 版更改: Windows现在使用与其他所有平台相同的实现。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex sameopenfile() (在 os.path 模块中)
@anchor{library/os path os path sameopenfile}@anchor{1d98}
@deffn {函数} os.path.sameopenfile (fp1, fp2)

如果文件描述符 @emph{fp1} 和 @emph{fp2} 指向相同文件，则返回 @code{True}。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加了 Windows 支持。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex samestat() (在 os.path 模块中)
@anchor{library/os path os path samestat}@anchor{975}
@deffn {函数} os.path.samestat (stat1, stat2)

如果 stat 元组 @emph{stat1} 和 @emph{stat2} 指向相同文件，则返回 @code{True}。这些 stat 元组可能是由 @ref{75c,,os.fstat()}、@ref{329,,os.lstat()} 或 @ref{328,,os.stat()} 返回的。本函数实现了 @ref{976,,samefile()} 和 @ref{1d98,,sameopenfile()} 底层所使用的比较过程。

@ref{14c1,,可用性}: Unix, Windows。


在 3.4 版更改: 添加了 Windows 支持。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex split() (在 os.path 模块中)
@anchor{library/os path os path split}@anchor{1d91}
@deffn {函数} os.path.split (path)

将路径 @emph{path} 拆分为一对，即 @code{(head, tail)}，其中，@emph{tail} 是路径的最后一部分，而 @emph{head} 里是除最后部分外的所有内容。@emph{tail} 部分不会包含斜杠，如果 @emph{path} 以斜杠结尾，则 @emph{tail} 将为空。如果 @emph{path} 中没有斜杠，@emph{head} 将为空。如果 @emph{path} 为空，则 @emph{head} 和 @emph{tail} 均为空。@emph{head} 末尾的斜杠会被去掉，除非它是根目录（即它仅包含一个或多个斜杠）。在所有情况下，@code{join(head, tail)} 指向的位置都与 @emph{path} 相同（但字符串可能不同）。另请参见函数 @ref{1d8d,,dirname()} 和 @ref{1d8c,,basename()}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex splitdrive() (在 os.path 模块中)
@anchor{library/os path os path splitdrive}@anchor{584}
@deffn {函数} os.path.splitdrive (path)

将路径 @emph{path} 拆分为一对，即 @code{(drive, tail)}，其中 @emph{drive} 是挂载点或空字符串。在没有驱动器概念的系统上，@emph{drive} 将始终为空字符串。在所有情况下，@code{drive + tail} 都与 @emph{path} 相同。

在 Windows 上，本方法将路径拆分为驱动器/UNC 根节点和相对路径。

如果路径 path 包含盘符，则 drive 将包含冒号之前的所有内容包括冒号本身:

@example
>>> splitdrive("c:/dir")
("c:", "/dir")
@end example

如果路径 path 包含 UNC 路径，则 drive 将包含主机名和 share，直至第四个分隔符但不包括该分隔符:

@example
>>> splitdrive("//host/computer/dir")
("//host/computer", "/dir")
@end example


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex splitext() (在 os.path 模块中)
@anchor{library/os path os path splitext}@anchor{1d8e}
@deffn {函数} os.path.splitext (path)

将路径名称 @emph{path} 拆分为 @code{(root, ext)}  对使得 @code{root + ext == path}，并且扩展名 @emph{ext} 为空或以句点打头并最多只包含一个句点。

如果路径 path 不包含扩展名，则 @emph{ext} 将为 @code{'@w{'}}:

@example
>>> splitext('bar')
('bar', '@w{'})
@end example

如果路径 path 包含扩展名，则 @emph{ext} 将被设为该扩展名，包括打头的句点。 请注意在其之前的句点将被忽略:

@example
>>> splitext('foo.bar.exe')
('foo.bar', '.exe')
>>> splitext('/foo/bar.exe')
('/foo/bar', '.exe')
@end example

path 中最后一部分如果以点号开头则会被视为 root 的一部分:

@example
>>> splitext('.cshrc')
('.cshrc', '@w{'})
>>> splitext('/foo/....jpg')
('/foo/....jpg', '@w{'})
@end example


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex supports_unicode_filenames() (在 os.path 模块中)
@anchor{library/os path os path supports_unicode_filenames}@anchor{eb9}
@deffn {数据} os.path.supports_unicode_filenames

如果（在文件系统限制下）允许将任意 Unicode 字符串用作文件名，则为 @code{True}。
@end deffn

@node fileinput --- 迭代来自多个输入流的行,stat --- 解析 stat 结果,os path --- 常用路径操作,文件和目录访问
@anchor{library/fileinput doc}@anchor{1d99}@anchor{library/fileinput fileinput-iterate-over-lines-from-multiple-input-streams}@anchor{1d9a}@anchor{library/fileinput module-fileinput}@anchor{7e}
@subsection @code{fileinput} --- 迭代来自多个输入流的行


@geindex fileinput (模块)

@strong{源代码:} Lib/fileinput.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/fileinput.py}


__________________________________________________________________


此模块实现了一个辅助类和一些函数用来快速编写访问标准输入或文件列表的循环。 如果你只想要读写一个文件请参阅 @ref{16f,,open()}。

典型用法为:

@example
import fileinput
for line in fileinput.input():
    process(line)
@end example

此程序会迭代 @code{sys.argv[1:]} 中列出的所有文件内的行，如果列表为空则会使用 @code{sys.stdin}。 如果有一个文件名为 @code{'-'}，它也会被替换为 @code{sys.stdin} 并且可选参数 @emph{mode} 和 @emph{openhook} 会被忽略。 要指定替代文件列表，请将其作为第一个参数传给 @ref{3d7,,input()}。 也允许使用单个文件。

所有文件都默认以文本模式打开，但你可以通过在调用 @ref{3d7,,input()} 或 @ref{3ac,,FileInput} 时指定 @emph{mode} 形参来重载此行为。 如果在打开或读取文件时发生了 I/O 错误，将会引发 @ref{30b,,OSError}。


在 3.3 版更改: 原来会引发 @ref{a7c,,IOError}；现在它是 @ref{30b,,OSError} 的别名。


如果 @code{sys.stdin} 被使用超过一次，则第二次之后的使用将不返回任何行，除非是被交互式的使用，或都是被显式地重置 (例如使用 @code{sys.stdin.seek(0)})。

空文件打开后将立即被关闭；它们在文件列表中会被注意到的唯一情况只有当最后打开的文件为空的时候。

反回的行不会对换行符做任何处理，这意味着文件中的最后一行可能不带换行符。

想要控制文件的打开方式，你可以通过将 @emph{openhook} 形参传给 @ref{3d7,,fileinput.input()} 或 @ref{3ac,,FileInput()} 来提供一个打开钩子。 此钩子必须为一个函数，它接受两个参数，@emph{filename} 和 @emph{mode}，并返回一个以相应模式打开的文件类对象。 此模块已经提供了两个有用的钩子。

以下函数是此模块的初始接口：

@geindex input() (在 fileinput 模块中)
@anchor{library/fileinput fileinput input}@anchor{3d7}
@deffn {函数} fileinput.input (files=None, inplace=False, backup='@w{'}, *, mode='r', openhook=None)

创建一个 @ref{3ac,,FileInput} 类的实例。 该实例将被用作此模块中函数的全局状态，并且还将在迭代期间被返回使用。 此函数的形参将被继续传递给 @ref{3ac,,FileInput} 类的构造器。

@ref{3ac,,FileInput} 实例可以在 @ref{7e4,,with} 语句中被用作上下文管理器。 在这个例子中，@emph{input} 在 @code{with} 语句结束后将会被关闭，即使发生了异常也是如此:

@example
with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
    for line in f:
        process(line)
@end example


在 3.2 版更改: 可以被用作上下文管理器。



在 3.8 版更改: 关键字形参 @emph{mode} 和 @emph{openhook} 现在是仅限关键字形参。

@end deffn

下列函数会使用 @ref{3d7,,fileinput.input()} 所创建的全局状态；如果没有活动的状态，则会引发 @ref{3e4,,RuntimeError}。

@geindex filename() (在 fileinput 模块中)
@anchor{library/fileinput fileinput filename}@anchor{1d9b}
@deffn {函数} fileinput.filename ()

返回当前被读取的文件名。 在第一行被读取之前，返回 @code{None}。
@end deffn

@geindex fileno() (在 fileinput 模块中)
@anchor{library/fileinput fileinput fileno}@anchor{1d9c}
@deffn {函数} fileinput.fileno ()

返回以整数表示的当前文件“文件描述符”。 当未打开文件时（处在第一行和文件之间），返回 @code{-1}。
@end deffn

@geindex lineno() (在 fileinput 模块中)
@anchor{library/fileinput fileinput lineno}@anchor{1d9d}
@deffn {函数} fileinput.lineno ()

返回已被读取的累计行号。 在第一行被读取之前，返回 @code{0}。 在最后一个文件的最后一行被读取之后，返回该行的行号。
@end deffn

@geindex filelineno() (在 fileinput 模块中)
@anchor{library/fileinput fileinput filelineno}@anchor{1d9e}
@deffn {函数} fileinput.filelineno ()

返回当前文件中的行号。 在第一行被读取之前，返回 @code{0}。 在最后一个文件的最后一行被读取之后，返回此文件中该行的行号。
@end deffn

@geindex isfirstline() (在 fileinput 模块中)
@anchor{library/fileinput fileinput isfirstline}@anchor{1d9f}
@deffn {函数} fileinput.isfirstline ()

如果刚读取的行是其所在文件的第一行则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex isstdin() (在 fileinput 模块中)
@anchor{library/fileinput fileinput isstdin}@anchor{1da0}
@deffn {函数} fileinput.isstdin ()

如果最后读取的行来自 @code{sys.stdin} 则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex nextfile() (在 fileinput 模块中)
@anchor{library/fileinput fileinput nextfile}@anchor{1da1}
@deffn {函数} fileinput.nextfile ()

关闭当前文件以使下次迭代将从下一个文件（如果存在）读取第一行；不是从该文件读取的行将不会被计入累计行数。 直到下一个文件的第一行被读取之后文件名才会改变。 在第一行被读取之前，此函数将不会生效；它不能被用来跳过第一个文件。 在最后一个文件的最后一行被读取之后，此函数将不再生效。
@end deffn

@geindex close() (在 fileinput 模块中)
@anchor{library/fileinput fileinput close}@anchor{1da2}
@deffn {函数} fileinput.close ()

关闭序列。
@end deffn

此模块所提供的实现了序列行为的类同样也可用于子类化：

@geindex FileInput (fileinput 中的类)
@anchor{library/fileinput fileinput FileInput}@anchor{3ac}
@deffn {类} fileinput.FileInput (files=None, inplace=False, backup='@w{'}, *, mode='r', openhook=None)

类 @ref{3ac,,FileInput} 是一个实现；它的方法 @ref{1d9b,,filename()}, @ref{1d9c,,fileno()}, @ref{1d9d,,lineno()}, @ref{1d9e,,filelineno()}, @ref{1d9f,,isfirstline()}, @ref{1da0,,isstdin()}, @ref{1da1,,nextfile()} 和 @ref{1da2,,close()} 对应于此模块中具有相同名称的函数。 此外它还有一个 @ref{1da3,,readline()} 方法可返回下一个输入行，以及一个 @ref{3ad,,__getitem__()} 方法，该方法实现了序列行为。 这种序列必须以严格的序列顺序来读写；随机读写和 @ref{1da3,,readline()} 不可以被混用。

通过 @emph{mode} 你可以指定要传给 @ref{16f,,open()} 的文件模式。 它必须为 @code{'r'}, @code{'rU'}, @code{'U'} 和 @code{'rb'} 中的一个。

@emph{openhook} 如果给出则必须为一个函数，它接受两个参数 @emph{filename} 和 @emph{mode}，并相应地返回一个打开的文件类对象。 你不能同时使用 @emph{inplace} 和 @emph{openhook}。

@ref{3ac,,FileInput} 实例可以在 @ref{7e4,,with} 语句中被用作上下文管理器。 在这个例子中，@emph{input} 在 @code{with} 语句结束后将会被关闭，即使发生了异常也是如此:

@example
with FileInput(files=('spam.txt', 'eggs.txt')) as input:
    process(input)
@end example


在 3.2 版更改: 可以被用作上下文管理器。



3.4 版后已移除: @code{'rU'} 和 @code{'U'} 模式。



3.8 版后已移除: 对 @ref{3ad,,__getitem__()} 方法的支持已弃用。



在 3.8 版更改: 关键字形参 @emph{mode} 和 @emph{openhook} 现在是仅限关键字形参。

@end deffn

@strong{可选的原地过滤:} 如果传递了关键字参数 @code{inplace=True} 给 @ref{3d7,,fileinput.input()} 或 @ref{3ac,,FileInput} 构造器，则文件会被移至备份文件并将标准输出定向到输入文件（如果已存在与备份文件同名的文件，它将被静默地替换）。 这使得编写一个能够原地重写其输入文件的过滤器成为可能。 如果给出了 @emph{backup} 形参 (通常形式为 @code{backup='.<some extension>'})，它将指定备份文件的扩展名，并且备份文件会被保留；默认情况下扩展名为 @code{'.bak'} 并且它会在输出文件关闭时被删除。 在读取标准输入时原地过滤会被禁用。

此模块提供了以下两种打开文件钩子：

@geindex hook_compressed() (在 fileinput 模块中)
@anchor{library/fileinput fileinput hook_compressed}@anchor{1da4}
@deffn {函数} fileinput.hook_compressed (filename, mode)

使用 @ref{8b,,gzip} 和 @ref{13,,bz2} 模块透明地打开 gzip 和 bzip2 压缩的文件（通过扩展名 @code{'.gz'} 和 @code{'.bz2'} 来识别）。 如果文件扩展名不是 @code{'.gz'} 或 @code{'.bz2'}，文件会以正常方式打开（即使用 @ref{16f,,open()} 并且不带任何解压操作）。

使用示例:  @code{fi = fileinput.FileInput(openhook=fileinput.hook_compressed)}
@end deffn

@geindex hook_encoded() (在 fileinput 模块中)
@anchor{library/fileinput fileinput hook_encoded}@anchor{64d}
@deffn {函数} fileinput.hook_encoded (encoding, errors=None)

返回一个通过 @ref{16f,,open()} 打开每个文件的钩子，使用给定的 @emph{encoding} 和 @emph{errors} 来读取文件。

使用示例: @code{fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape"))}


在 3.6 版更改: 添加了可选的 @emph{errors} 形参。

@end deffn

@node stat --- 解析 stat 结果,filecmp --- 文件及目录的比较,fileinput --- 迭代来自多个输入流的行,文件和目录访问
@anchor{library/stat doc}@anchor{1da5}@anchor{library/stat module-stat}@anchor{f4}@anchor{library/stat stat-interpreting-stat-results}@anchor{1da6}
@subsection @code{stat} --- 解析 @code{stat()} 结果


@geindex stat (模块)

@strong{源代码：} Lib/stat.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/stat.py}


__________________________________________________________________


@ref{f4,,stat} 模块定义了一些用于解析 @ref{328,,os.stat()}, @ref{75c,,os.fstat()} 和 @ref{329,,os.lstat()} (如果它们存在) 输出结果的常量和函数。 有关 @code{stat()}, @code{fstat()} 和 @code{lstat()} 调用的完整细节，请参阅你的系统文档。


在 3.4 版更改: stat 模块是通过 C 实现来支持的。


@ref{f4,,stat} 模块定义了以下函数来检测特定文件类型：

@geindex S_ISDIR() (在 stat 模块中)
@anchor{library/stat stat S_ISDIR}@anchor{1da7}
@deffn {函数} stat.S_ISDIR (mode)

如果 mode 来自一个目录则返回非零值。
@end deffn

@geindex S_ISCHR() (在 stat 模块中)
@anchor{library/stat stat S_ISCHR}@anchor{1da8}
@deffn {函数} stat.S_ISCHR (mode)

如果 mode 来自一个字符特殊设备文件则返回非零值。
@end deffn

@geindex S_ISBLK() (在 stat 模块中)
@anchor{library/stat stat S_ISBLK}@anchor{1da9}
@deffn {函数} stat.S_ISBLK (mode)

如果 mode 来自一个块特殊设备文件则返回非零值。
@end deffn

@geindex S_ISREG() (在 stat 模块中)
@anchor{library/stat stat S_ISREG}@anchor{1daa}
@deffn {函数} stat.S_ISREG (mode)

如果 mode 来自一个常规文件则返回非零值。
@end deffn

@geindex S_ISFIFO() (在 stat 模块中)
@anchor{library/stat stat S_ISFIFO}@anchor{1dab}
@deffn {函数} stat.S_ISFIFO (mode)

如果 mode 来自一个 FIFO (命名管道) 则返回非零值。
@end deffn

@geindex S_ISLNK() (在 stat 模块中)
@anchor{library/stat stat S_ISLNK}@anchor{1dac}
@deffn {函数} stat.S_ISLNK (mode)

如果 mode 来自一个符号链接则返回非零值。
@end deffn

@geindex S_ISSOCK() (在 stat 模块中)
@anchor{library/stat stat S_ISSOCK}@anchor{1dad}
@deffn {函数} stat.S_ISSOCK (mode)

如果 mode 来自一个套接字则返回非零值。
@end deffn

@geindex S_ISDOOR() (在 stat 模块中)
@anchor{library/stat stat S_ISDOOR}@anchor{1111}
@deffn {函数} stat.S_ISDOOR (mode)

如果 mode 来自一个门则返回非零值。


3.4 新版功能.

@end deffn

@geindex S_ISPORT() (在 stat 模块中)
@anchor{library/stat stat S_ISPORT}@anchor{1112}
@deffn {函数} stat.S_ISPORT (mode)

如果 mode 来自一个事件端口则返回非零值。


3.4 新版功能.

@end deffn

@geindex S_ISWHT() (在 stat 模块中)
@anchor{library/stat stat S_ISWHT}@anchor{1113}
@deffn {函数} stat.S_ISWHT (mode)

如果 mode 来自一个白输出则返回非零值。


3.4 新版功能.

@end deffn

定义了两个附加函数用于对文件模式进行更一般化的操作：

@geindex S_IMODE() (在 stat 模块中)
@anchor{library/stat stat S_IMODE}@anchor{1dae}
@deffn {函数} stat.S_IMODE (mode)

返回文件模式中可由 @ref{b18,,os.chmod()} 进行设置的部分 --- 即文件的 permission 位，加上 sticky 位、set-group-id 以及 set-user-id 位（在支持这些部分的系统上）。
@end deffn

@geindex S_IFMT() (在 stat 模块中)
@anchor{library/stat stat S_IFMT}@anchor{1daf}
@deffn {函数} stat.S_IFMT (mode)

返回文件模式中描述文件类型的部分（供上面的 @code{S_IS*()} 函数使用）。
@end deffn

通常，你应当使用 @code{os.path.is*()} 函数来检测文件的类型；这里提供的函数则适用于当你要对同一文件执行多项检测并且希望避免每项检测的 @code{stat()} 系统调用开销的情况。 这些函数也适用于检测有关未被 @ref{c5,,os.path} 处理的信息，例如检测块和字符设备等。

示例:

@example
import os, sys
from stat import *

def walktree(top, callback):
    '@w{'}'recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'@w{'}'

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.lstat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print('Skipping %s' % pathname)

def visitfile(file):
    print('visiting', file)

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)
@end example

另外还提供了一个附加的辅助函数用来将文件模式转换为人类易读的字符串：

@geindex filemode() (在 stat 模块中)
@anchor{library/stat stat filemode}@anchor{b7e}
@deffn {函数} stat.filemode (mode)

将文件模式转换为 '-rwxrwxrwx' 形式的字符串。


3.3 新版功能.



在 3.4 版更改: 此函数支持 @ref{9c3,,S_IFDOOR}, @ref{9c4,,S_IFPORT} and @ref{9c5,,S_IFWHT}。

@end deffn

以下所有变量是一些简单的符号索引，用于访问 @ref{328,,os.stat()}, @ref{75c,,os.fstat()} 或 @ref{329,,os.lstat()} 所返回的 10 条目元组。

@geindex ST_MODE() (在 stat 模块中)
@anchor{library/stat stat ST_MODE}@anchor{9c2}
@deffn {数据} stat.ST_MODE

inode 保护模式。
@end deffn

@geindex ST_INO() (在 stat 模块中)
@anchor{library/stat stat ST_INO}@anchor{1db0}
@deffn {数据} stat.ST_INO

Inode 号
@end deffn

@geindex ST_DEV() (在 stat 模块中)
@anchor{library/stat stat ST_DEV}@anchor{1db1}
@deffn {数据} stat.ST_DEV

Inode 所在的设备。
@end deffn

@geindex ST_NLINK() (在 stat 模块中)
@anchor{library/stat stat ST_NLINK}@anchor{1db2}
@deffn {数据} stat.ST_NLINK

Inode 拥有的链接数量。
@end deffn

@geindex ST_UID() (在 stat 模块中)
@anchor{library/stat stat ST_UID}@anchor{1db3}
@deffn {数据} stat.ST_UID

所有者的用户 ID。
@end deffn

@geindex ST_GID() (在 stat 模块中)
@anchor{library/stat stat ST_GID}@anchor{1db4}
@deffn {数据} stat.ST_GID

所有者的用户组ID。
@end deffn

@geindex ST_SIZE() (在 stat 模块中)
@anchor{library/stat stat ST_SIZE}@anchor{1db5}
@deffn {数据} stat.ST_SIZE

以字节为单位的普通文件大小；对于某些特殊文件则是所等待的数据量。
@end deffn

@geindex ST_ATIME() (在 stat 模块中)
@anchor{library/stat stat ST_ATIME}@anchor{1db6}
@deffn {数据} stat.ST_ATIME

上次访问的时间。
@end deffn

@geindex ST_MTIME() (在 stat 模块中)
@anchor{library/stat stat ST_MTIME}@anchor{1db7}
@deffn {数据} stat.ST_MTIME

上次修改的时间。
@end deffn

@geindex ST_CTIME() (在 stat 模块中)
@anchor{library/stat stat ST_CTIME}@anchor{1db8}
@deffn {数据} stat.ST_CTIME

操作系统所报告的 "ctime"。 在某些系统上（例如 Unix）是元数据的最后修改时间，而在其他系统上（例如 Windows）则是创建时间（请参阅系统平台的文档了解相关细节）。
@end deffn

对于“文件大小”的解析可因文件类型的不同而变化。 对于普通文件就是文件的字节数。 对于大部分种类的 Unix（特别包括 Linux）的 FIFO 和套接字来说，“大小”则是指在调用 @ref{328,,os.stat()}, @ref{75c,,os.fstat()} 或 @ref{329,,os.lstat()} 时等待读取的字节数；这在某些时候很有用处，特别是在一个非阻塞的打开后轮询这些特殊文件中的一个时。 其他字符和块设备的文件大小字段的含义还会有更多变化，具体取决于底层系统调用的实现方式。

以下变量定义了在 @ref{9c2,,ST_MODE} 字段中使用的旗标。

使用上面的函数会比使用第一组旗标更容易移植：

@geindex S_IFSOCK() (在 stat 模块中)
@anchor{library/stat stat S_IFSOCK}@anchor{1db9}
@deffn {数据} stat.S_IFSOCK

套接字。
@end deffn

@geindex S_IFLNK() (在 stat 模块中)
@anchor{library/stat stat S_IFLNK}@anchor{1dba}
@deffn {数据} stat.S_IFLNK

符号链接。
@end deffn

@geindex S_IFREG() (在 stat 模块中)
@anchor{library/stat stat S_IFREG}@anchor{1dbb}
@deffn {数据} stat.S_IFREG

普通文件。
@end deffn

@geindex S_IFBLK() (在 stat 模块中)
@anchor{library/stat stat S_IFBLK}@anchor{1dbc}
@deffn {数据} stat.S_IFBLK

块设备。
@end deffn

@geindex S_IFDIR() (在 stat 模块中)
@anchor{library/stat stat S_IFDIR}@anchor{1dbd}
@deffn {数据} stat.S_IFDIR

目录。
@end deffn

@geindex S_IFCHR() (在 stat 模块中)
@anchor{library/stat stat S_IFCHR}@anchor{1dbe}
@deffn {数据} stat.S_IFCHR

字符设备。
@end deffn

@geindex S_IFIFO() (在 stat 模块中)
@anchor{library/stat stat S_IFIFO}@anchor{1dbf}
@deffn {数据} stat.S_IFIFO

先进先出。
@end deffn

@geindex S_IFDOOR() (在 stat 模块中)
@anchor{library/stat stat S_IFDOOR}@anchor{9c3}
@deffn {数据} stat.S_IFDOOR

门。


3.4 新版功能.

@end deffn

@geindex S_IFPORT() (在 stat 模块中)
@anchor{library/stat stat S_IFPORT}@anchor{9c4}
@deffn {数据} stat.S_IFPORT

事件端口。


3.4 新版功能.

@end deffn

@geindex S_IFWHT() (在 stat 模块中)
@anchor{library/stat stat S_IFWHT}@anchor{9c5}
@deffn {数据} stat.S_IFWHT

白输出。


3.4 新版功能.

@end deffn

@cartouche
@quotation 注解 
@ref{9c3,,S_IFDOOR}, @ref{9c4,,S_IFPORT} or @ref{9c5,,S_IFWHT} 等文件类型在不受系统平台支持时会被定义为 0。
@end quotation
@end cartouche

以下旗标还可以 @ref{b18,,os.chmod()} 的在 @emph{mode} 参数中使用：

@geindex S_ISUID() (在 stat 模块中)
@anchor{library/stat stat S_ISUID}@anchor{1dc0}
@deffn {数据} stat.S_ISUID

设置 UID 位。
@end deffn

@geindex S_ISGID() (在 stat 模块中)
@anchor{library/stat stat S_ISGID}@anchor{1dc1}
@deffn {数据} stat.S_ISGID

设置分组 ID 位。 这个位有几种特殊用途。 对于目录它表示该目录将使用 BSD 语义：在其中创建的文件将从目录继承其分组 ID，而不是从创建进程的有效分组 ID 继承，并且在其中创建的目录也将设置 @ref{1dc1,,S_ISGID} 位。 对于没有设置分组执行位 (@ref{1dc2,,S_IXGRP}) 的文件，设置分组 ID 位表示强制性文件/记录锁定 (另请参见 @ref{1dc3,,S_ENFMT})。
@end deffn

@geindex S_ISVTX() (在 stat 模块中)
@anchor{library/stat stat S_ISVTX}@anchor{1dc4}
@deffn {数据} stat.S_ISVTX

固定位。 当对目录设置该位时则意味着此目录中的文件只能由文件所有者、目录所有者或特权进程来重命名或删除。
@end deffn

@geindex S_IRWXU() (在 stat 模块中)
@anchor{library/stat stat S_IRWXU}@anchor{1dc5}
@deffn {数据} stat.S_IRWXU

文件所有者权限的掩码。
@end deffn

@geindex S_IRUSR() (在 stat 模块中)
@anchor{library/stat stat S_IRUSR}@anchor{1dc6}
@deffn {数据} stat.S_IRUSR

所有者具有读取权限。
@end deffn

@geindex S_IWUSR() (在 stat 模块中)
@anchor{library/stat stat S_IWUSR}@anchor{1dc7}
@deffn {数据} stat.S_IWUSR

所有者具有写入权限。
@end deffn

@geindex S_IXUSR() (在 stat 模块中)
@anchor{library/stat stat S_IXUSR}@anchor{1dc8}
@deffn {数据} stat.S_IXUSR

所有者具有执行权限。
@end deffn

@geindex S_IRWXG() (在 stat 模块中)
@anchor{library/stat stat S_IRWXG}@anchor{1dc9}
@deffn {数据} stat.S_IRWXG

组权限的掩码。
@end deffn

@geindex S_IRGRP() (在 stat 模块中)
@anchor{library/stat stat S_IRGRP}@anchor{1dca}
@deffn {数据} stat.S_IRGRP

组具有读取权限。
@end deffn

@geindex S_IWGRP() (在 stat 模块中)
@anchor{library/stat stat S_IWGRP}@anchor{1dcb}
@deffn {数据} stat.S_IWGRP

组具有写入权限。
@end deffn

@geindex S_IXGRP() (在 stat 模块中)
@anchor{library/stat stat S_IXGRP}@anchor{1dc2}
@deffn {数据} stat.S_IXGRP

组具有执行权限。
@end deffn

@geindex S_IRWXO() (在 stat 模块中)
@anchor{library/stat stat S_IRWXO}@anchor{1dcc}
@deffn {数据} stat.S_IRWXO

其他人（不在组中）的权限掩码。
@end deffn

@geindex S_IROTH() (在 stat 模块中)
@anchor{library/stat stat S_IROTH}@anchor{1dcd}
@deffn {数据} stat.S_IROTH

其他人具有读取权限。
@end deffn

@geindex S_IWOTH() (在 stat 模块中)
@anchor{library/stat stat S_IWOTH}@anchor{1dce}
@deffn {数据} stat.S_IWOTH

其他人具有写入权限。
@end deffn

@geindex S_IXOTH() (在 stat 模块中)
@anchor{library/stat stat S_IXOTH}@anchor{1dcf}
@deffn {数据} stat.S_IXOTH

其他人具有执行权限。
@end deffn

@geindex S_ENFMT() (在 stat 模块中)
@anchor{library/stat stat S_ENFMT}@anchor{1dc3}
@deffn {数据} stat.S_ENFMT

System V 执行文件锁定。 此旗标是与 @ref{1dc1,,S_ISGID} 共享的：文件/记录锁定会针对未设置分组执行位 (@ref{1dc2,,S_IXGRP}) 的文件强制执行。
@end deffn

@geindex S_IREAD() (在 stat 模块中)
@anchor{library/stat stat S_IREAD}@anchor{1dd0}
@deffn {数据} stat.S_IREAD

Unix V7 中 @ref{1dc6,,S_IRUSR} 的同义词。
@end deffn

@geindex S_IWRITE() (在 stat 模块中)
@anchor{library/stat stat S_IWRITE}@anchor{1dd1}
@deffn {数据} stat.S_IWRITE

Unix V7 中 @ref{1dc7,,S_IWUSR} 的同义词。
@end deffn

@geindex S_IEXEC() (在 stat 模块中)
@anchor{library/stat stat S_IEXEC}@anchor{1dd2}
@deffn {数据} stat.S_IEXEC

Unix V7 中 @ref{1dc8,,S_IXUSR} 的同义词。
@end deffn

以下旗标可以在 @ref{b17,,os.chflags()} 的 @emph{flags} 参数中使用：

@geindex UF_NODUMP() (在 stat 模块中)
@anchor{library/stat stat UF_NODUMP}@anchor{1dd3}
@deffn {数据} stat.UF_NODUMP

不要转储文件。
@end deffn

@geindex UF_IMMUTABLE() (在 stat 模块中)
@anchor{library/stat stat UF_IMMUTABLE}@anchor{1dd4}
@deffn {数据} stat.UF_IMMUTABLE

文件不能被更改。
@end deffn

@geindex UF_APPEND() (在 stat 模块中)
@anchor{library/stat stat UF_APPEND}@anchor{1dd5}
@deffn {数据} stat.UF_APPEND

文件只能被附加。
@end deffn

@geindex UF_OPAQUE() (在 stat 模块中)
@anchor{library/stat stat UF_OPAQUE}@anchor{1dd6}
@deffn {数据} stat.UF_OPAQUE

当通过联合堆栈查看时，目录是不透明的。
@end deffn

@geindex UF_NOUNLINK() (在 stat 模块中)
@anchor{library/stat stat UF_NOUNLINK}@anchor{1dd7}
@deffn {数据} stat.UF_NOUNLINK

文件不能重命名或删除。
@end deffn

@geindex UF_COMPRESSED() (在 stat 模块中)
@anchor{library/stat stat UF_COMPRESSED}@anchor{1dd8}
@deffn {数据} stat.UF_COMPRESSED

文件是压缩存储的（macOS 10.6+）。
@end deffn

@geindex UF_HIDDEN() (在 stat 模块中)
@anchor{library/stat stat UF_HIDDEN}@anchor{1dd9}
@deffn {数据} stat.UF_HIDDEN

文件不可被显示在 GUI 中（macOS 10.5+）。
@end deffn

@geindex SF_ARCHIVED() (在 stat 模块中)
@anchor{library/stat stat SF_ARCHIVED}@anchor{1dda}
@deffn {数据} stat.SF_ARCHIVED

文件可能已存档。
@end deffn

@geindex SF_IMMUTABLE() (在 stat 模块中)
@anchor{library/stat stat SF_IMMUTABLE}@anchor{1ddb}
@deffn {数据} stat.SF_IMMUTABLE

文件不能被更改。
@end deffn

@geindex SF_APPEND() (在 stat 模块中)
@anchor{library/stat stat SF_APPEND}@anchor{1ddc}
@deffn {数据} stat.SF_APPEND

文件只能被附加。
@end deffn

@geindex SF_NOUNLINK() (在 stat 模块中)
@anchor{library/stat stat SF_NOUNLINK}@anchor{1ddd}
@deffn {数据} stat.SF_NOUNLINK

文件不能重命名或删除。
@end deffn

@geindex SF_SNAPSHOT() (在 stat 模块中)
@anchor{library/stat stat SF_SNAPSHOT}@anchor{1dde}
@deffn {数据} stat.SF_SNAPSHOT

文件有一个快照文件
@end deffn

请参阅 *BSD 或 macOS 系统的指南页 @code{chflags(2)} 来了解详情。

在 Windows 上，以下文件属性常量可被用来检测 @ref{328,,os.stat()} 所返回的 @code{st_file_attributes} 成员中的位。 请参阅 Windows API 文档@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx} 了解有关这些常量含义的详情。

@geindex FILE_ATTRIBUTE_ARCHIVE() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_COMPRESSED() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_DEVICE() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_DIRECTORY() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_ENCRYPTED() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_HIDDEN() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_INTEGRITY_STREAM() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_NORMAL() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_NOT_CONTENT_INDEXED() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_NO_SCRUB_DATA() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_OFFLINE() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_READONLY() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_REPARSE_POINT() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_SPARSE_FILE() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_SYSTEM() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_TEMPORARY() (在 stat 模块中)
@geindex FILE_ATTRIBUTE_VIRTUAL() (在 stat 模块中)
@anchor{library/stat stat FILE_ATTRIBUTE_ARCHIVE}@anchor{1ddf}
@deffn {数据} stat.FILE_ATTRIBUTE_ARCHIVE
@anchor{library/stat stat FILE_ATTRIBUTE_COMPRESSED}@anchor{1de0}
@deffnx {数据} stat.FILE_ATTRIBUTE_COMPRESSED
@anchor{library/stat stat FILE_ATTRIBUTE_DEVICE}@anchor{1de1}
@deffnx {数据} stat.FILE_ATTRIBUTE_DEVICE
@anchor{library/stat stat FILE_ATTRIBUTE_DIRECTORY}@anchor{1de2}
@deffnx {数据} stat.FILE_ATTRIBUTE_DIRECTORY
@anchor{library/stat stat FILE_ATTRIBUTE_ENCRYPTED}@anchor{1de3}
@deffnx {数据} stat.FILE_ATTRIBUTE_ENCRYPTED
@anchor{library/stat stat FILE_ATTRIBUTE_HIDDEN}@anchor{1de4}
@deffnx {数据} stat.FILE_ATTRIBUTE_HIDDEN
@anchor{library/stat stat FILE_ATTRIBUTE_INTEGRITY_STREAM}@anchor{1de5}
@deffnx {数据} stat.FILE_ATTRIBUTE_INTEGRITY_STREAM
@anchor{library/stat stat FILE_ATTRIBUTE_NORMAL}@anchor{1de6}
@deffnx {数据} stat.FILE_ATTRIBUTE_NORMAL
@anchor{library/stat stat FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}@anchor{1de7}
@deffnx {数据} stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
@anchor{library/stat stat FILE_ATTRIBUTE_NO_SCRUB_DATA}@anchor{1de8}
@deffnx {数据} stat.FILE_ATTRIBUTE_NO_SCRUB_DATA
@anchor{library/stat stat FILE_ATTRIBUTE_OFFLINE}@anchor{1de9}
@deffnx {数据} stat.FILE_ATTRIBUTE_OFFLINE
@anchor{library/stat stat FILE_ATTRIBUTE_READONLY}@anchor{1dea}
@deffnx {数据} stat.FILE_ATTRIBUTE_READONLY
@anchor{library/stat stat FILE_ATTRIBUTE_REPARSE_POINT}@anchor{1deb}
@deffnx {数据} stat.FILE_ATTRIBUTE_REPARSE_POINT
@anchor{library/stat stat FILE_ATTRIBUTE_SPARSE_FILE}@anchor{1dec}
@deffnx {数据} stat.FILE_ATTRIBUTE_SPARSE_FILE
@anchor{library/stat stat FILE_ATTRIBUTE_SYSTEM}@anchor{1ded}
@deffnx {数据} stat.FILE_ATTRIBUTE_SYSTEM
@anchor{library/stat stat FILE_ATTRIBUTE_TEMPORARY}@anchor{1dee}
@deffnx {数据} stat.FILE_ATTRIBUTE_TEMPORARY
@anchor{library/stat stat FILE_ATTRIBUTE_VIRTUAL}@anchor{1def}
@deffnx {数据} stat.FILE_ATTRIBUTE_VIRTUAL


3.5 新版功能.

@end deffn

在 Windows 上，以下常量可被用来与 @ref{329,,os.lstat()} 所返回的 @code{st_reparse_tag} 成员进行比较。 这些是最主要的常量，而不是详尽的清单。

@geindex IO_REPARSE_TAG_SYMLINK() (在 stat 模块中)
@geindex IO_REPARSE_TAG_MOUNT_POINT() (在 stat 模块中)
@geindex IO_REPARSE_TAG_APPEXECLINK() (在 stat 模块中)
@anchor{library/stat stat IO_REPARSE_TAG_SYMLINK}@anchor{1df0}
@deffn {数据} stat.IO_REPARSE_TAG_SYMLINK
@anchor{library/stat stat IO_REPARSE_TAG_MOUNT_POINT}@anchor{1df1}
@deffnx {数据} stat.IO_REPARSE_TAG_MOUNT_POINT
@anchor{library/stat stat IO_REPARSE_TAG_APPEXECLINK}@anchor{1df2}
@deffnx {数据} stat.IO_REPARSE_TAG_APPEXECLINK


3.8 新版功能.

@end deffn

@node filecmp --- 文件及目录的比较,tempfile --- 生成临时文件和目录,stat --- 解析 stat 结果,文件和目录访问
@anchor{library/filecmp doc}@anchor{1df3}@anchor{library/filecmp filecmp-file-and-directory-comparisons}@anchor{1df4}@anchor{library/filecmp module-filecmp}@anchor{7d}
@subsection @code{filecmp} --- 文件及目录的比较


@geindex filecmp (模块)

@strong{源代码:} Lib/filecmp.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/filecmp.py}


__________________________________________________________________


@ref{7d,,filecmp} 模块定义了用于比较文件及目录的函数，并且可以选取多种关于时间和准确性的折衷方案。对于文件的比较，另见 @ref{36,,difflib} 模块。

@ref{7d,,filecmp}  模块定义了如下函数：

@geindex cmp() (在 filecmp 模块中)
@anchor{library/filecmp filecmp cmp}@anchor{fd0}
@deffn {函数} filecmp.cmp (f1, f2, shallow=True)

比较名为 @emph{f1} 和 @emph{f2} 的文件，如果它们似乎相等则返回 @code{True} ，否则返回 @code{False} 。

如果 @emph{shallow} 为真值且两个文件的 @ref{328,,os.stat()} 签名信息（文件类型、大小和修改时间）一致，则文件会被视为相同。

在其他情况下，如果文件大小或内容不同则它们会被视为不同。

需要注意，没有外部程序被该函数调用，这赋予了该函数可移植性与效率。

该函数会缓存过去的比较及其结果，且在文件的 @ref{328,,os.stat()} 信息变化后缓存条目失效。所有的缓存可以通过  @ref{93e,,clear_cache()} 清除。
@end deffn

@geindex cmpfiles() (在 filecmp 模块中)
@anchor{library/filecmp filecmp cmpfiles}@anchor{1df5}
@deffn {函数} filecmp.cmpfiles (dir1, dir2, common, shallow=True)

比较在两个目录 @emph{dir1} 和 @emph{dir2} 中，由 @emph{common} 所确定名称的文件。

返回三组文件名列表： @emph{match}, @emph{mismatch}, @emph{errors} 。 @emph{match} 含有相匹配的文件， @emph{mismatch} 含有那些不匹配的，然后 @emph{errors} 列出那些未被比较文件的名称。如果文件不存在于两目录中的任一个，或者用户缺少读取它们的权限，又或者因为其他的一些原因而无法比较，那么这些文件将会被列在 @emph{errors} 中。

参数 @emph{shallow} 具有同 @ref{fd0,,filecmp.cmp()} 一致的含义与默认值。

例如， @code{cmpfiles('a', 'b', ['c', 'd/e'])} 将会比较 @code{a/c} 与 @code{b/c} 以及 @code{a/d/e} 与 @code{b/d/e} 。 @code{'c'} 和 @code{'d/e'} 将会各自出现在返回的三个列表里的某一个列表中。
@end deffn

@geindex clear_cache() (在 filecmp 模块中)
@anchor{library/filecmp filecmp clear_cache}@anchor{93e}
@deffn {函数} filecmp.clear_cache ()

清除 filecmp 缓存。如果一个文件过快地修改，以至于超过底层文件系统记录修改时间的精度，那么该函数可能有助于比较该类文件。


3.4 新版功能.

@end deffn

@menu
* dircmp 类:: 

@end menu

@node dircmp 类,,,filecmp --- 文件及目录的比较
@anchor{library/filecmp dircmp-objects}@anchor{1df6}@anchor{library/filecmp the-dircmp-class}@anchor{1df7}
@subsubsection @code{dircmp} 类


@geindex dircmp (filecmp 中的类)
@anchor{library/filecmp filecmp dircmp}@anchor{940}
@deffn {类} filecmp.dircmp (a, b, ignore=None, hide=None)

创建一个用于比较目录 @emph{a} 和 @emph{b} 的新的目录比较对象。 @emph{ignore} 是需要忽略的文件名列表，且默认为  @ref{93f,,filecmp.DEFAULT_IGNORES} 。 @emph{hide} 是需要隐藏的文件名列表，且默认为 @code{[os.curdir, os.pardir]} 。

@ref{940,,dircmp} 类如 @ref{fd0,,filecmp.cmp()} 中所描述的那样对文件进行 @emph{shallow} 比较。

@ref{940,,dircmp} 类提供以下方法：

@geindex report() (filecmp.dircmp 方法)
@anchor{library/filecmp filecmp dircmp report}@anchor{1df8}
@deffn {方法} report ()

将 @emph{a} 与 @emph{b} 之间的比较打印（到  @ref{428,,sys.stdout} ）。
@end deffn

@geindex report_partial_closure() (filecmp.dircmp 方法)
@anchor{library/filecmp filecmp dircmp report_partial_closure}@anchor{1df9}
@deffn {方法} report_partial_closure ()

打印 @emph{a} 与 @emph{b}  及共同直接子目录的比较结果。
@end deffn

@geindex report_full_closure() (filecmp.dircmp 方法)
@anchor{library/filecmp filecmp dircmp report_full_closure}@anchor{1dfa}
@deffn {方法} report_full_closure ()

打印 @emph{a} 与 @emph{b} 及共同子目录比较结果（递归地）。
@end deffn

@ref{940,,dircmp} 类提供了一些有趣的属性，用以得到关于参与比较的目录树的各种信息。

需要注意，通过 @ref{433,,__getattr__()}  钩子，所有的属性将会惰性求值，因此如果只使用那些计算简便的属性，将不会有速度损失。

@geindex left (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp left}@anchor{1dfb}
@deffn {属性} left

目录 @emph{a} 。
@end deffn

@geindex right (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp right}@anchor{1dfc}
@deffn {属性} right

目录 @emph{b} 。
@end deffn

@geindex left_list (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp left_list}@anchor{1dfd}
@deffn {属性} left_list

经 @emph{hide} 和 @emph{ignore} 过滤，目录 @emph{a} 中的文件与子目录。
@end deffn

@geindex right_list (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp right_list}@anchor{1dfe}
@deffn {属性} right_list

经 @emph{hide} 和 @emph{ignore} 过滤，目录 @emph{b} 中的文件与子目录。
@end deffn

@geindex common (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp common}@anchor{1dff}
@deffn {属性} common

同时存在于目录 @emph{a} 和 @emph{b} 中的文件和子目录。
@end deffn

@geindex left_only (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp left_only}@anchor{1e00}
@deffn {属性} left_only

仅在目录 @emph{a} 中的文件和子目录。
@end deffn

@geindex right_only (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp right_only}@anchor{1e01}
@deffn {属性} right_only

仅在目录 @emph{b} 中的文件和子目录。
@end deffn

@geindex common_dirs (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp common_dirs}@anchor{1e02}
@deffn {属性} common_dirs

同时存在于目录 @emph{a} 和 @emph{b} 中的子目录。
@end deffn

@geindex common_files (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp common_files}@anchor{1e03}
@deffn {属性} common_files

同时存在于目录 @emph{a} 和 @emph{b} 中的文件。
@end deffn

@geindex common_funny (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp common_funny}@anchor{1e04}
@deffn {属性} common_funny

在目录 @emph{a} 和 @emph{b} 中类型不同的名字，或者那些 @ref{328,,os.stat()} 报告错误的名字。
@end deffn

@geindex same_files (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp same_files}@anchor{1e05}
@deffn {属性} same_files

在目录 @emph{a} 和 @emph{b} 中使用类的文件比较操作符相等的文件。
@end deffn

@geindex diff_files (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp diff_files}@anchor{1e06}
@deffn {属性} diff_files

在目录 @emph{a} 和 @emph{b} 中，根据类的文件比较操作符判定内容不等的文件。
@end deffn

@geindex funny_files (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp funny_files}@anchor{1e07}
@deffn {属性} funny_files

在目录 @emph{a} 和 @emph{b} 中无法比较的文件。
@end deffn

@geindex subdirs (filecmp.dircmp 属性)
@anchor{library/filecmp filecmp dircmp subdirs}@anchor{1e08}
@deffn {属性} subdirs

一个将 @ref{1e02,,common_dirs} 中名称映射为 @ref{940,,dircmp} 对象的字典。
@end deffn
@end deffn

@geindex DEFAULT_IGNORES() (在 filecmp 模块中)
@anchor{library/filecmp filecmp DEFAULT_IGNORES}@anchor{93f}
@deffn {属性} filecmp.DEFAULT_IGNORES


3.4 新版功能.


默认被 @ref{940,,dircmp} 忽略的目录列表。
@end deffn

下面是一个简单的例子，使用 @code{subdirs} 属性递归搜索两个目录以显示公共差异文件：

@example
>>> from filecmp import dircmp
>>> def print_diff_files(dcmp):
...     for name in dcmp.diff_files:
...         print("diff_file %s found in %s and %s" % (name, dcmp.left,
...               dcmp.right))
...     for sub_dcmp in dcmp.subdirs.values():
...         print_diff_files(sub_dcmp)
...
>>> dcmp = dircmp('dir1', 'dir2') 
>>> print_diff_files(dcmp) 
@end example

@node tempfile --- 生成临时文件和目录,glob --- Unix 风格路径名模式扩展,filecmp --- 文件及目录的比较,文件和目录访问
@anchor{library/tempfile doc}@anchor{1e09}@anchor{library/tempfile module-tempfile}@anchor{103}@anchor{library/tempfile tempfile-generate-temporary-files-and-directories}@anchor{1e0a}
@subsection @code{tempfile} --- 生成临时文件和目录


@geindex tempfile (模块)

@strong{源代码：} Lib/tempfile.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tempfile.py}

@geindex temporary; file name
@geindex temporary; file


__________________________________________________________________


该模块用于创建临时文件和目录，它可以跨平台使用。@ref{1e0b,,TemporaryFile}、@ref{e16,,NamedTemporaryFile}、@ref{c9e,,TemporaryDirectory} 和 @ref{b87,,SpooledTemporaryFile} 是带有自动清理功能的高级接口，可用作上下文管理器。@ref{1e0c,,mkstemp()} 和 @ref{1e0d,,mkdtemp()} 是低级函数，使用完毕需手动清理。

所有由用户调用的函数和构造函数都带有参数，这些参数可以设置临时文件和临时目录的路径和名称。该模块生成的文件名包括一串随机字符，在公共的临时目录中，这些字符可以让创建文件更加安全。为了保持向后兼容性，参数的顺序有些奇怪。所以为了代码清晰，建议使用关键字参数。

这个模块定义了以下内容供用户调用：

@geindex TemporaryFile() (在 tempfile 模块中)
@anchor{library/tempfile tempfile TemporaryFile}@anchor{1e0b}
@deffn {函数} tempfile.TemporaryFile (mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

返回一个 @ref{1e0e,,file-like object} （文件类对象）作为临时存储区域。创建该文件使用了与 @ref{1e0c,,mkstemp()} 相同的安全规则。它将在关闭后立即销毁（包括垃圾回收机制关闭该对象时）。在 Unix 下，该文件在目录中的条目根本不创建，或者创建文件后立即就被删除了，其他平台不支持此功能。您的代码不应依赖使用此功能创建的临时文件名称，因为它在文件系统中的名称可能是可见的，也可能是不可见的。

生成的对象可以用作上下文管理器（参见 @ref{1e0f,,示例}）。完成上下文或销毁临时文件对象后，临时文件将从文件系统中删除。

@emph{mode} 参数默认值为 @code{'w+b'}，所以创建的文件不用关闭，就可以读取或写入。因为用的是二进制模式，所以无论存的是什么数据，它在所有平台上都表现一致。@emph{buffering}、@emph{encoding}、@emph{errors} 和 @emph{newline} 的含义与 @ref{16f,,open()} 中的相同。

参数 @emph{dir}、@emph{prefix} 和 @emph{suffix} 的含义和默认值都与它们在 @ref{1e0c,,mkstemp()} 中的相同。

在 POSIX 平台上，它返回的对象是真实的文件对象。在其他平台上，它是一个文件类对象 (file-like object)，它的 @code{file} 属性是底层的真实文件对象。

如果可用，则使用 @ref{978,,os.O_TMPFILE} 标志（仅限于 Linux，需要 3.11 及更高版本的内核）。

在 Posix 或 Cygwin 以外的平台上，TemporaryFile 是 NamedTemporaryFile 的别名。

引发一个 @code{tempfile.mkstemp} @ref{fec,,审计事件}，附带参数 @code{fullpath}。


在 3.5 版更改: 如果可用，现在用的是 @ref{978,,os.O_TMPFILE} 标志。



在 3.8 版更改: 添加了 @emph{errors} 参数。

@end deffn

@geindex NamedTemporaryFile() (在 tempfile 模块中)
@anchor{library/tempfile tempfile NamedTemporaryFile}@anchor{e16}
@deffn {函数} tempfile.NamedTemporaryFile (mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)

此函数执行的操作与 @ref{1e0b,,TemporaryFile()} 完全相同，但是会确保该文件在文件系统中具有可见的名称（在 Unix 上表现为目录项不取消链接）。 该名称可从返回的文件类对象的 @code{name} 属性获取。 在指定的临时文件仍然被打开时该名称是否可被用来再次打开文件对于不同平台则有所不同（在 Unix 上可以这样做；在 Windows 上不可以） 如果 @emph{delete} 为（默认的）真值，则文件会在关闭之后立即被删除。 此函数返回的对象始终会是文件类对象，它的 @code{file} 属性是底层的真实文件对象。 这个文件类对象可以在 @ref{7e4,,with} 语句中使用，就像普通的文件一样。

引发一个 @code{tempfile.mkstemp} @ref{fec,,审计事件}，附带参数 @code{fullpath}。


在 3.8 版更改: 添加了 @emph{errors} 参数。

@end deffn

@geindex SpooledTemporaryFile() (在 tempfile 模块中)
@anchor{library/tempfile tempfile SpooledTemporaryFile}@anchor{b87}
@deffn {函数} tempfile.SpooledTemporaryFile (max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

此函数执行的操作与 @ref{1e0b,,TemporaryFile()} 完全相同，但会将数据缓存在内存中，直到文件大小超过 @emph{max_size}，或调用文件的 @code{fileno()} 方法为止，此时数据会被写入磁盘，并且写入操作与 @ref{1e0b,,TemporaryFile()} 相同。

此函数生成的文件对象有一个额外的方法——@code{rollover()}，可以忽略文件大小，让文件立即写入磁盘。

返回的对象是文件类对象 (file-like object)，它的 @code{_file} 属性是 @ref{894,,io.BytesIO} 或 @ref{6f4,,io.TextIOWrapper} 对象（取决于指定的是二进制模式还是文本模式）或真实的文件对象（取决于是否已调用 @code{rollover()}）。文件类对象可以像普通文件一样在 @ref{7e4,,with} 语句中使用。


在 3.3 版更改: 现在，文件的 truncate 方法可接受一个 @code{size} 参数。



在 3.8 版更改: 添加了 @emph{errors} 参数。

@end deffn

@geindex TemporaryDirectory() (在 tempfile 模块中)
@anchor{library/tempfile tempfile TemporaryDirectory}@anchor{c9e}
@deffn {函数} tempfile.TemporaryDirectory (suffix=None, prefix=None, dir=None)

此函数会安全地创建一个临时目录，且使用与 @ref{1e0d,,mkdtemp()} 相同的规则。此函数返回的对象可用作上下文管理器（参见 @ref{1e0f,,示例}）。完成上下文或销毁临时目录对象后，新创建的临时目录及其所有内容将从文件系统中删除。

可以从返回对象的 @code{name} 属性中找到临时目录的名称。当返回的对象用作上下文管理器时，这个 @code{name} 会作为 @ref{7e4,,with} 语句中 @code{as} 子句的目标（如果有 as 的话）。

可以调用 @code{cleanup()} 方法来手动清理目录。

引发一个 @code{tempfile.mkdtemp} @ref{fec,,审计事件}，附带参数 @code{fullpath}。


3.2 新版功能.

@end deffn

@geindex mkstemp() (在 tempfile 模块中)
@anchor{library/tempfile tempfile mkstemp}@anchor{1e0c}
@deffn {函数} tempfile.mkstemp (suffix=None, prefix=None, dir=None, text=False)

以最安全的方式创建一个临时文件。假设所在平台正确实现了 @ref{762,,os.open()} 的 @ref{1e10,,os.O_EXCL} 标志，则创建文件时不会有竞争的情况。该文件只能由创建者读写，如果所在平台用权限位来标记文件是否可执行，那么没有人有执行权。文件描述符不会过继给子进程。

与 @ref{1e0b,,TemporaryFile()} 不同，@ref{1e0c,,mkstemp()} 用户用完临时文件后需要自行将其删除。

如果 @emph{suffix} 不是 @code{None} 则文件名将以该后缀结尾，是 @code{None} 则没有后缀。@ref{1e0c,,mkstemp()} 不会在文件名和后缀之间加点，如果需要加一个点号，请将其放在 @emph{suffix} 的开头。

如果 @emph{prefix} 不是 @code{None}，则文件名将以该前缀开头，是 @code{None}      则使用默认前缀。默认前缀是 @ref{1e11,,gettempprefix()} 或 @ref{1e12,,gettempprefixb()} 函数的返回值（自动调用合适的函数）。

如果 @emph{dir} 不为 @code{None}，则在指定的目录创建文件，是 @code{None} 则使用默认目录。默认目录是从一个列表中选择出来的，这个列表不同平台不一样，但是用户可以设置 @emph{TMPDIR}、@emph{TEMP} 或 @emph{TMP} 环境变量来设置目录的位置。因此，不能保证生成的临时文件路径很规范，比如，通过 @code{os.popen()} 将路径传递给外部命令时仍需要加引号。

如果 @emph{suffix}、@emph{prefix} 和 @emph{dir} 中的任何一个不是 @code{None}，就要保证它们是同一数据类型。如果它们是 bytes，则返回的名称的类型就是 bytes 而不是 str。如果确实要用默认参数，但又想要返回值是 bytes 类型，请传入 @code{suffix=b'@w{'}}。

如果指定了 @emph{text} 且为真值，文件会以文本模式打开。 否则，文件（默认）会以二进制模式打开。

@ref{1e0c,,mkstemp()} 返回一个元组，元组中第一个元素是句柄，它是一个系统级句柄，指向一个打开的文件（等同于 @ref{762,,os.open()} 的返回值），第二元素是该文件的绝对路径。

引发一个 @code{tempfile.mkstemp} @ref{fec,,审计事件}，附带参数 @code{fullpath}。


在 3.5 版更改: 现在，@emph{suffix}、@emph{prefix} 和 @emph{dir} 可以以 bytes 类型按顺序提供，以获得 bytes 类型的返回值。之前只允许使用 str。@emph{suffix} 和 @emph{prefix} 现在可以接受 @code{None}，并且默认为 @code{None} 以使用合适的默认值。



在 3.6 版更改: @emph{dir} 参数现在可接受一个路径类对象 (@ref{47b,,path-like object})。

@end deffn

@geindex mkdtemp() (在 tempfile 模块中)
@anchor{library/tempfile tempfile mkdtemp}@anchor{1e0d}
@deffn {函数} tempfile.mkdtemp (suffix=None, prefix=None, dir=None)

以最安全的方式创建一个临时目录，创建该目录时不会有竞争的情况。该目录只能由创建者读取、写入和搜索。

@ref{1e0d,,mkdtemp()} 用户用完临时目录后需要自行将其删除。

@emph{prefix}、@emph{suffix} 和 @emph{dir} 的含义与它们在 @ref{1e0c,,mkstemp()} 中的相同。

@ref{1e0d,,mkdtemp()} 返回新目录的绝对路径。

引发一个 @code{tempfile.mkdtemp} @ref{fec,,审计事件}，附带参数 @code{fullpath}。


在 3.5 版更改: 现在，@emph{suffix}、@emph{prefix} 和 @emph{dir} 可以以 bytes 类型按顺序提供，以获得 bytes 类型的返回值。之前只允许使用 str。@emph{suffix} 和 @emph{prefix} 现在可以接受 @code{None}，并且默认为 @code{None} 以使用合适的默认值。



在 3.6 版更改: @emph{dir} 参数现在可接受一个路径类对象 (@ref{47b,,path-like object})。

@end deffn

@geindex gettempdir() (在 tempfile 模块中)
@anchor{library/tempfile tempfile gettempdir}@anchor{1e13}
@deffn {函数} tempfile.gettempdir ()

返回放置临时文件的目录的名称。这个方法的返回值就是本模块所有函数的 @emph{dir} 参数的默认值。

Python 搜索标准目录列表，以找到调用者可以在其中创建文件的目录。这个列表是：


@enumerate 

@item 
@geindex TMPDIR
@geindex 环境变量; TMPDIR
@code{TMPDIR} 环境变量指向的目录。

@item 
@geindex TEMP
@geindex 环境变量; TEMP
@code{TEMP} 环境变量指向的目录。

@item 
@geindex TMP
@geindex 环境变量; TMP
@code{TMP} 环境变量指向的目录。

@item 
与平台相关的位置：


@itemize *

@item 
在 Windows 上，依次为 @code{C:\TEMP}、@code{C:\TMP}、@code{\TEMP} 和 @code{\TMP}。

@item 
在所有其他平台上，依次为 @code{/tmp}、@code{/var/tmp} 和 @code{/usr/tmp}。
@end itemize

@item 
不得已时，使用当前工作目录。
@end enumerate

搜索的结果会缓存起来，参见下面 @ref{1e14,,tempdir} 的描述。
@end deffn

@geindex gettempdirb() (在 tempfile 模块中)
@anchor{library/tempfile tempfile gettempdirb}@anchor{1e15}
@deffn {函数} tempfile.gettempdirb ()

与 @ref{1e13,,gettempdir()} 相同，但返回值为字节类型。


3.5 新版功能.

@end deffn

@geindex gettempprefix() (在 tempfile 模块中)
@anchor{library/tempfile tempfile gettempprefix}@anchor{1e11}
@deffn {函数} tempfile.gettempprefix ()

返回用于创建临时文件的文件名前缀，它不包含目录部分。
@end deffn

@geindex gettempprefixb() (在 tempfile 模块中)
@anchor{library/tempfile tempfile gettempprefixb}@anchor{1e12}
@deffn {函数} tempfile.gettempprefixb ()

与 @ref{1e11,,gettempprefix()} 相同，但返回值为字节类型。


3.5 新版功能.

@end deffn

本模块使用一个全局变量来存储由 @ref{1e13,,gettempdir()} 返回的临时文件目录路径。可以直接给它赋值，这样可以覆盖自动选择的路径，但是不建议这样做。本模块中的所有函数都带有一个 @emph{dir} 参数，该参数可用于指定目录，这是推荐的方法。

@geindex tempdir() (在 tempfile 模块中)
@anchor{library/tempfile tempfile tempdir}@anchor{1e14}
@deffn {数据} tempfile.tempdir

当设置为 @code{None} 以外的其他值时，此变量将决定本模块所有函数的 @emph{dir} 参数的默认值。

如果在调用除 @ref{1e11,,gettempprefix()} 外的上述任何函数时 @code{tempdir} 为 @code{None} (默认值) 则它会按照 @ref{1e13,,gettempdir()} 中所描述的算法来初始化。
@end deffn

@menu
* 示例: 示例<6>. 
* 已弃用的函数和变量:: 

@end menu

@node 示例<6>,已弃用的函数和变量,,tempfile --- 生成临时文件和目录
@anchor{library/tempfile examples}@anchor{1e16}@anchor{library/tempfile tempfile-examples}@anchor{1e0f}
@subsubsection 示例


以下是 @ref{103,,tempfile} 模块典型用法的一些示例:

@example
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
@end example

@node 已弃用的函数和变量,,示例<6>,tempfile --- 生成临时文件和目录
@anchor{library/tempfile deprecated-functions-and-variables}@anchor{1e17}@anchor{library/tempfile tempfile-mktemp-deprecated}@anchor{1e18}
@subsubsection 已弃用的函数和变量


创建临时文件有一种历史方法，首先使用 @ref{fc8,,mktemp()} 函数生成一个文件名，然后使用该文件名创建文件。不幸的是，这是不安全的，因为在调用 @ref{fc8,,mktemp()} 与随后尝试创建文件的进程之间的时间里，其他进程可能会使用该名称创建文件。解决方案是将两个步骤结合起来，立即创建文件。这个方案目前被 @ref{1e0c,,mkstemp()} 和上述其他函数所采用。

@geindex mktemp() (在 tempfile 模块中)
@anchor{library/tempfile tempfile mktemp}@anchor{fc8}
@deffn {函数} tempfile.mktemp (suffix='@w{'}, prefix='tmp', dir=None)


2.3 版后已移除: 使用 @ref{1e0c,,mkstemp()} 来代替。


返回一个绝对路径，这个路径指向的文件在调用本方法时不存在。@emph{prefix}、@emph{suffix} 和 @emph{dir} 参数与 @ref{1e0c,,mkstemp()} 中的同名参数类似，不同之处在于不支持字节类型的文件名，不支持 @code{suffix=None} 和 @code{prefix=None}。

@cartouche
@quotation 警告 
使用此功能可能会在程序中引入安全漏洞。当你开始使用本方法返回的文件执行任何操作时，可能有人已经捷足先登了。@ref{fc8,,mktemp()} 的功能可以很轻松地用 @ref{e16,,NamedTemporaryFile()} 代替，当然需要传递 @code{delete=False} 参数:

@example
>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
@end example
@end quotation
@end cartouche
@end deffn

@node glob --- Unix 风格路径名模式扩展,fnmatch --- Unix 文件名模式匹配,tempfile --- 生成临时文件和目录,文件和目录访问
@anchor{library/glob doc}@anchor{1e19}@anchor{library/glob glob-unix-style-pathname-pattern-expansion}@anchor{1e1a}@anchor{library/glob module-glob}@anchor{88}
@subsection @code{glob} --- Unix 风格路径名模式扩展


@geindex glob (模块)

@strong{源代码:} Lib/glob.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/glob.py}

@geindex filenames; pathname expansion


__________________________________________________________________


@geindex * (asterisk); in glob-style wildcards
@geindex ? (question mark); in glob-style wildcards
@geindex [] (square brackets); in glob-style wildcards
@geindex ! (exclamation); in glob-style wildcards
@geindex - (minus); in glob-style wildcards
@geindex . (dot); in glob-style wildcards

@ref{88,,glob} 模块会按照 Unix shell 所使用的规则找出所有匹配特定模式的路径名称，但返回结果的顺序是不确定的。 波浪号扩展不会生效，但 @code{*}, @code{?} 以及用 @code{[]} 表示的字符范围将被正确地匹配。 这是通过配合使用 @ref{390,,os.scandir()} 和 @ref{1e1b,,fnmatch.fnmatch()} 函数来实现的，而不是通过实际发起调用子 shell。

请注意以点号 (@code{.}) 打头的文件只能用同样以点号打头的模式来匹配，这不同于 @ref{1e1b,,fnmatch.fnmatch()} 或 @ref{10cd,,pathlib.Path.glob()}。 （对于波浪号和 shell 变量扩展，请使用 @ref{333,,os.path.expanduser()} 和 @ref{e11,,os.path.expandvars()}。）

对于字面值匹配，请将原字符用方括号括起来。 例如，@code{'[?]'} 将匹配字符 @code{'?'}。


@subsubheading 参见


@ref{c8,,pathlib} 模块提供高级路径对象。


@geindex glob() (在 glob 模块中)
@anchor{library/glob glob glob}@anchor{6c7}
@deffn {函数} glob.glob (pathname, *, recursive=False)

返回匹配 @emph{pathname} 的可能为空的路径名列表，其中的元素必须为包含路径信息的字符串。 @emph{pathname} 可以是绝对路径 (如 @code{/usr/src/Python-1.5/Makefile}) 或相对路径 (如 @code{../../Tools/*/*.gif})，并且可包含 shell 风格的通配符。 结果也将包含无效的符号链接（与在 shell 中一样）。 结果是否排序取决于具体文件系统。 如果某个符合条件的文件在调用此函数期间被移除或添加，是否包括该文件的路径是没有规定的。

@geindex **; in glob-style wildcards

如果 @emph{recursive} 为真值，则模式 "@code{**}" 将匹配目录中的任何文件以及零个或多个目录、子目录和符号链接。 如果模式加了一个 @ref{1e1c,,os.sep} 或 @ref{1e1d,,os.altsep} 则将不匹配文件。

引发一个 @ref{fec,,审计事件} @code{glob.glob} 附带参数 @code{pathname}, @code{recursive}。

@cartouche
@quotation 注解 
在一个较大的目录树中使用 "@code{**}" 模式可能会消耗非常多的时间。
@end quotation
@end cartouche


在 3.5 版更改: 支持使用 "@code{**}" 的递归 glob。

@end deffn

@geindex iglob() (在 glob 模块中)
@anchor{library/glob glob iglob}@anchor{6c8}
@deffn {函数} glob.iglob (pathname, *, recursive=False)

返回一个 @ref{11ba,,iterator}，它会产生与 @ref{88,,glob()} 相同的结果，但不会实际地同时保存它们。

引发一个 @ref{fec,,审计事件} @code{glob.glob} 附带参数 @code{pathname}, @code{recursive}。
@end deffn

@geindex escape() (在 glob 模块中)
@anchor{library/glob glob escape}@anchor{946}
@deffn {函数} glob.escape (pathname)

转义所有特殊字符 (@code{'?'}, @code{'*'} 和 @code{'['})。 这适用于当你想要匹配可能带有特殊字符的任意字符串字面值的情况。 在 drive/UNC 共享点中的特殊字符不会被转义，例如在 Windows 上 @code{escape('//?/c:/Quo vadis?.txt')} 将返回 @code{'//?/c:/Quo vadis[?].txt'}。


3.4 新版功能.

@end deffn

例如，考虑一个包含以下内容的目录：文件 @code{1.gif}, @code{2.txt}, @code{card.gif} 以及一个子目录 @code{sub} 其中只包含一个文件 @code{3.txt}.  @ref{88,,glob()} 将产生如下结果。 请注意路径的任何开头部分都将被保留。:

@example
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
@end example

如果目录包含以 @code{.} 打头的文件，它们默认将不会被匹配。 例如，考虑一个包含 @code{card.gif} 和 @code{.card.gif} 的目录:

@example
>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{7f,,fnmatch}

Shell 风格文件名（而非路径）扩展
@end table


@node fnmatch --- Unix 文件名模式匹配,linecache --- 随机读写文本行,glob --- Unix 风格路径名模式扩展,文件和目录访问
@anchor{library/fnmatch doc}@anchor{1e1e}@anchor{library/fnmatch fnmatch-unix-filename-pattern-matching}@anchor{1e1f}@anchor{library/fnmatch module-fnmatch}@anchor{7f}
@subsection @code{fnmatch} --- Unix 文件名模式匹配


@geindex fnmatch (模块)

@strong{源代码:} Lib/fnmatch.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/fnmatch.py}

@geindex filenames; wildcard expansion

@geindex 模块; re


__________________________________________________________________


此模块提供了 Unix shell 风格的通配符，它们 @emph{并不} 等同于正则表达式（关于后者的文档参见 @ref{dd,,re} 模块）。 shell 风格通配符所使用的特殊字符如下：

@geindex * (asterisk); in glob-style wildcards
@geindex ? (question mark); in glob-style wildcards
@geindex [] (square brackets); in glob-style wildcards
@geindex ! (exclamation); in glob-style wildcards
@geindex - (minus); in glob-style wildcards


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

模式

@tab

意义

@item

@code{*}

@tab

匹配所有

@item

@code{?}

@tab

匹配任何单个字符

@item

@code{[seq]}

@tab

匹配 @emph{seq} 中的任何字符

@item

@code{[!seq]}

@tab

匹配任何不在 @emph{seq} 中的字符

@end multitable


对于字面值匹配，请将原字符用方括号括起来。 例如，@code{'[?]'} 将匹配字符 @code{'?'}。

@geindex 模块; glob

注意文件名分隔符 (Unix 上为 @code{'/'}) @emph{不会} 被此模块特别对待。 请参见 @ref{88,,glob} 模块了解文件名扩展 (@ref{88,,glob} 使用 @ref{1e20,,filter()} 来匹配文件名的各个部分)。 类似地，以一个句点打头的文件名也不会被此模块特别对待，可以通过 @code{*} 和 @code{?} 模式来匹配。

@geindex fnmatch() (在 fnmatch 模块中)
@anchor{library/fnmatch fnmatch fnmatch}@anchor{1e1b}
@deffn {函数} fnmatch.fnmatch (filename, pattern)

检测 @emph{filename} 字符串是否匹配 @emph{pattern} 字符串，返回 @ref{59c,,True} 或 @ref{497,,False}。 两个形参都会使用 @ref{1d96,,os.path.normcase()} 进行大小写正规化。 @ref{1e21,,fnmatchcase()} 可被用于执行大小写敏感的比较，无论这是否为所在操作系统的标准。

这个例子将打印当前目录下带有扩展名 @code{.txt} 的所有文件名:

@example
import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
@end example
@end deffn

@geindex fnmatchcase() (在 fnmatch 模块中)
@anchor{library/fnmatch fnmatch fnmatchcase}@anchor{1e21}
@deffn {函数} fnmatch.fnmatchcase (filename, pattern)

检测 @emph{filename} 是否匹配 @emph{pattern}，返回 @ref{59c,,True} 或 @ref{497,,False}；此比较是大小写敏感的，并且不会应用 @ref{1d96,,os.path.normcase()}。
@end deffn

@geindex filter() (在 fnmatch 模块中)
@anchor{library/fnmatch fnmatch filter}@anchor{1e20}
@deffn {函数} fnmatch.filter (names, pattern)

基于可迭代对象 @emph{names} 中匹配 @emph{pattern} 的元素构造一个列表。 它等价于 @code{[n for n in names if fnmatch(n, pattern)]}，但实现得更有效率。
@end deffn

@geindex translate() (在 fnmatch 模块中)
@anchor{library/fnmatch fnmatch translate}@anchor{11bc}
@deffn {函数} fnmatch.translate (pattern)

返回 shell 风格 @emph{pattern} 转换成的正则表达式以便用于 @ref{c8b,,re.match()}。

示例:

@example
>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'(?s:.*\\.txt)\\Z'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<re.Match object; span=(0, 10), match='foobar.txt'>
@end example
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{88,,glob}

Unix shell 风格路径扩展。
@end table


@node linecache --- 随机读写文本行,shutil --- 高阶文件操作,fnmatch --- Unix 文件名模式匹配,文件和目录访问
@anchor{library/linecache doc}@anchor{1e22}@anchor{library/linecache linecache-random-access-to-text-lines}@anchor{1e23}@anchor{library/linecache module-linecache}@anchor{a8}
@subsection @code{linecache} --- 随机读写文本行


@geindex linecache (模块)

@strong{源代码:} Lib/linecache.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/linecache.py}


__________________________________________________________________


@ref{a8,,linecache} 模块允许从一个 Python 源文件中获取任意的行，并会尝试使用缓存进行内部优化，常应用于从单个文件读取多行的场合。 此模块被 @ref{11c,,traceback} 模块用来提取源码行以便包含在格式化的回溯中。

@ref{1e24,,tokenize.open()} 函数被用于打开文件。 此函数使用 @ref{1e25,,tokenize.detect_encoding()} 来获取文件的编码格式；如果未指明编码格式，则默认编码为 UTF-8。

@ref{a8,,linecache} 模块定义了下列函数：

@geindex getline() (在 linecache 模块中)
@anchor{library/linecache linecache getline}@anchor{804}
@deffn {函数} linecache.getline (filename, lineno, module_globals=None)

从名为 @emph{filename} 的文件中获取 @emph{lineno} 行，此函数绝不会引发异常 --- 出现错误时它将返回 @code{'@w{'}} (所有找到的行都将包含换行符作为结束)。

@geindex module; search; path

如果找不到名为 @emph{filename} 的文件，此函数会先在 @emph{module_globals} 中检查 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} @code{__loader__}。 如果存在这样的加载器并且它定义了 @code{get_source} 方法，则由该方法来确定源行 (如果 @code{get_source()} 返回 @code{None}，则该函数返回 @code{'@w{'}})。 最后，如果 @emph{filename} 是一个相对路径文件名，则它会在模块搜索路径 @code{sys.path} 中按条目的相对位置进行查找。
@end deffn

@geindex clearcache() (在 linecache 模块中)
@anchor{library/linecache linecache clearcache}@anchor{1e26}
@deffn {函数} linecache.clearcache ()

清空缓存。 如果你不再需要之前使用 @ref{804,,getline()} 从文件读取的行即可使用此函数。
@end deffn

@geindex checkcache() (在 linecache 模块中)
@anchor{library/linecache linecache checkcache}@anchor{1e27}
@deffn {函数} linecache.checkcache (filename=None)

检查缓存有效性。 如果缓存中的文件在磁盘上发生了改变，而你需要更新后的版本即可使用此函数。 如果省略了 @emph{filename}，它会检查缓存中的所有条目。
@end deffn

@geindex lazycache() (在 linecache 模块中)
@anchor{library/linecache linecache lazycache}@anchor{803}
@deffn {函数} linecache.lazycache (filename, module_globals)

捕获有关某个非基于文件的模块的足够细节信息，以允许稍后再通过 @ref{804,,getline()} 来获取其中的行，即使当稍后调用时 @emph{module_globals} 为 @code{None}。 这可以避免在实际需要读取行之前执行 I/O，也不必始终保持模块全局变量。


3.5 新版功能.

@end deffn

示例:

@example
>>> import linecache
>>> linecache.getline(linecache.__file__, 8)
'import sys\n'
@end example

@node shutil --- 高阶文件操作,,linecache --- 随机读写文本行,文件和目录访问
@anchor{library/shutil doc}@anchor{1e28}@anchor{library/shutil module-shutil}@anchor{e9}@anchor{library/shutil shutil-high-level-file-operations}@anchor{1e29}
@subsection @code{shutil} --- 高阶文件操作


@geindex shutil (模块)

@c partly based on the docstrings

@strong{源代码：} Lib/shutil.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/shutil.py}

@geindex file; copying
@geindex copying files


__________________________________________________________________


@ref{e9,,shutil} 模块提供了一系列对文件和文件集合的高阶操作。 特别是提供了一些支持文件拷贝和删除的函数。 对于单个文件的操作，请参阅 @ref{c4,,os} 模块。

@cartouche
@quotation 警告 
即便是高阶文件拷贝函数 (@ref{38a,,shutil.copy()}, @ref{38b,,shutil.copy2()}) 也无法拷贝所有的文件元数据。

在 POSIX 平台上，这意味着将丢失文件所有者和组以及 ACL 数据。 在 Mac OS 上，资源钩子和其他元数据不被使用。 这意味着将丢失这些资源并且文件类型和创建者代码将不正确。 在 Windows 上，将不会拷贝文件所有者、ACL 和替代数据流。
@end quotation
@end cartouche

@menu
* 目录和文件操作:: 
* 归档操作:: 
* 查询输出终端的尺寸:: 

@end menu

@node 目录和文件操作,归档操作,,shutil --- 高阶文件操作
@anchor{library/shutil directory-and-files-operations}@anchor{1e2a}@anchor{library/shutil file-operations}@anchor{1e2b}
@subsubsection 目录和文件操作


@geindex copyfileobj() (在 shutil 模块中)
@anchor{library/shutil shutil copyfileobj}@anchor{38e}
@deffn {函数} shutil.copyfileobj (fsrc, fdst[, length])

将文件类对象 @emph{fsrc} 的内容拷贝到文件类对象 @emph{fdst}。 整数值 @emph{length} 如果给出则为缓冲区大小。 特别地， @emph{length} 为负值表示拷贝数据时不对源数据进行分块循环处理；默认情况下会分块读取数据以避免不受控制的内存消耗。 请注意如果 @emph{fsrc} 对象的当前文件位置不为 0，则只有从当前文件位置到文件末尾的内容会被拷贝。
@end deffn

@geindex copyfile() (在 shutil 模块中)
@anchor{library/shutil shutil copyfile}@anchor{389}
@deffn {函数} shutil.copyfile (src, dst, *, follow_symlinks=True)

将名为 @emph{src} 的文件的内容（不包括元数据）拷贝到名为 @emph{dst} 的文件并以尽可能高效的方式返回 @emph{dst}。 @emph{src} 和 @emph{dst} 均为路径类对象或以字符串形式给出的路径名。

@emph{dst} 必须是完整的目标文件名；对于接受目标目录路径的拷贝请参见 @ref{38a,,copy()}。 如果 @emph{src} 和 @emph{dst} 指定了同一个文件，则将引发 @ref{9a3,,SameFileError}。

目标位置必须是可写的；否则将引发 @ref{30b,,OSError} 异常。 如果 @emph{dst} 已经存在，它将被替换。 特殊文件如字符或块设备以及管道无法用此函数来拷贝。

如果 @emph{follow_symlinks} 为假值且 @emph{src} 为符号链接，则将创建一个新的符号链接而不是拷贝 @emph{src} 所指向的文件。

引发一个 @ref{fec,,审计事件} @code{shutil.copyfile} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 曾经是引发 @ref{a7c,,IOError} 而不是 @ref{30b,,OSError}。 增加了 @emph{follow_symlinks} 参数。 现在是返回 @emph{dst}。



在 3.4 版更改: 引发 @ref{9a3,,SameFileError} 而不是 @ref{9a2,,Error}。 由于前者是后者的子类，此改变是向后兼容的。



在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷贝文件。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。

@end deffn

@geindex SameFileError
@anchor{library/shutil shutil SameFileError}@anchor{9a3}
@deffn {例外} shutil.SameFileError

此异常会在 @ref{389,,copyfile()} 中的源和目标为同一文件时被引发。


3.4 新版功能.

@end deffn

@geindex copymode() (在 shutil 模块中)
@anchor{library/shutil shutil copymode}@anchor{1e2c}
@deffn {函数} shutil.copymode (src, dst, *, follow_symlinks=True)

从 @emph{src} 拷贝权限位到 @emph{dst}。 文件的内容、所有者和分组将不受影响。 @emph{src} 和 @emph{dst} 均为路径类对象或字符串形式的路径名。 如果 @emph{follow_symlinks} 为假值，并且 @emph{src} 和 @emph{dst} 均为符号链接，@ref{1e2c,,copymode()} 将尝试修改 @emph{dst} 本身的模式（而非它所指向的文件）。 此功能并不是在所有平台上均可用；请参阅 @ref{b5b,,copystat()} 了解详情。 如果 @ref{1e2c,,copymode()} 无法修改本机平台上的符号链接，而它被要求这样做，它将不做任何操作即返回。

引发一个 @ref{fec,,审计事件} @code{shutil.copymode} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 加入 @emph{follow_symlinks} 参数。

@end deffn

@geindex copystat() (在 shutil 模块中)
@anchor{library/shutil shutil copystat}@anchor{b5b}
@deffn {函数} shutil.copystat (src, dst, *, follow_symlinks=True)

从 @emph{src} 拷贝权限位、最近访问时间、最近修改时间以及旗标到 @emph{dst}。 在 Linux上，@ref{b5b,,copystat()} 还会在可能的情况下拷贝“扩展属性”。 文件的内容、所有者和分组将不受影响。 @emph{src} 和 @emph{dst} 均为路径类对象或字符串形式的路径名。

如果 @emph{follow_symlinks} 为假值，并且 @emph{src} 和 @emph{dst} 均指向符号链接，@ref{b5b,,copystat()} 将作用于符号链接本身而非该符号链接所指向的文件 — 从 @emph{src} 符号链接读取信息，并将信息写入 @emph{dst} 符号链接。

@cartouche
@quotation 注解 
并非所有平台者提供检查和修改符号链接的功能。 Python 本身可以告诉你哪些功能是在本机上可用的。


@itemize *

@item 
如果 @code{os.chmod in os.supports_follow_symlinks} 为 @code{True}，则 @ref{b5b,,copystat()} 可以修改符号链接的权限位。

@item 
如果 @code{os.utime in os.supports_follow_symlinks} 为 @code{True}，则 @ref{b5b,,copystat()} 可以修改符号链接的最近访问和修改时间。

@item 
如果 @code{os.chflags in os.supports_follow_symlinks} 为 @code{True}，则 @ref{b5b,,copystat()} 可以修改符号链接的旗标。 (@code{os.chflags} 不是在所有平台上均可用。)
@end itemize

在此功能部分或全部不可用的平台上，当被要求修改一个符号链接时，@ref{b5b,,copystat()} 将尽量拷贝所有内容。 @ref{b5b,,copystat()} 一定不会返回失败信息。

更多信息请参阅 @ref{1e2d,,os.supports_follow_symlinks}。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{shutil.copystat} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 添加了 @emph{follow_symlinks} 参数并且支持 Linux 扩展属性。

@end deffn

@geindex copy() (在 shutil 模块中)
@anchor{library/shutil shutil copy}@anchor{38a}
@deffn {函数} shutil.copy (src, dst, *, follow_symlinks=True)

将文件 @emph{src} 拷贝到文件或目录 @emph{dst}。 @emph{src} 和 @emph{dst} 应为 @ref{47b,,路径类对象} 或字符串。 如果 @emph{dst} 指定了一个目录，文件将使用 @emph{src} 中的基准文件名拷贝到 @emph{dst} 中。  如果 @emph{dst} 指定了一个已存在的文件，它将被替换。 返回新创建文件所对应的路径。

如果 @emph{follow_symlinks} 为假值且 @emph{src} 为符号链接，则 @emph{dst} 也将被创建为符号链接。 如果 @emph{follow_symlinks} 为真值且 @emph{src} 为符号链接，@emph{dst} 将成为 @emph{src} 所指向的文件的一个副本。

@ref{38a,,copy()} 会拷贝文件数据和文件的权限模式 (参见 @ref{b18,,os.chmod()})。 其他元数据，例如文件的创建和修改时间不会被保留。 要保留所有原有的元数据，请改用 @ref{38b,,copy2()} 。

引发一个 @ref{fec,,审计事件} @code{shutil.copyfile} 附带参数 @code{src}, @code{dst}。

引发一个 @ref{fec,,审计事件} @code{shutil.copymode} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 添加了 @emph{follow_symlinks} 参数。 现在会返回新创建文件的路径。



在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷贝文件。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。

@end deffn

@geindex copy2() (在 shutil 模块中)
@anchor{library/shutil shutil copy2}@anchor{38b}
@deffn {函数} shutil.copy2 (src, dst, *, follow_symlinks=True)

类似于 @ref{38a,,copy()}，区别在于 @ref{38b,,copy2()} 还会尝试保留文件的元数据。

当 @emph{follow_symlinks} 为假值且 @emph{src} 为符号链接时，@ref{38b,,copy2()} 会尝试将来自 @emph{src} 符号链接的所有元数据拷贝到新创建的 @emph{dst} 符号链接。 但是，此功能不是在所有平台上均可用。 在此功能部分或全部不可用的平台上，@ref{38b,,copy2()} 将尽量保留所有元数据；@ref{38b,,copy2()} 一定不会由于无法保留文件元数据而引发异常。

@ref{38b,,copy2()} 会使用 @ref{b5b,,copystat()} 来拷贝文件元数据。 请参阅 @ref{b5b,,copystat()} 了解有关修改符号链接元数据的平台支持的更多信息。

引发一个 @ref{fec,,审计事件} @code{shutil.copyfile} 附带参数 @code{src}, @code{dst}。

引发一个 @ref{fec,,审计事件} @code{shutil.copystat} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 添加了 @emph{follow_symlinks} 参数，还会尝试拷贝扩展文件系统属性（目前仅限 Linux）。 现在会返回新创建文件的路径。



在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷贝文件。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。

@end deffn

@geindex ignore_patterns() (在 shutil 模块中)
@anchor{library/shutil shutil ignore_patterns}@anchor{1e2e}
@deffn {函数} shutil.ignore_patterns (*patterns)

这个工厂函数会创建一个函数，它可被用作 @ref{34e,,copytree()} 的 @emph{ignore} 可调用对象参数，以忽略那些匹配所提供的 glob 风格的 @emph{patterns} 之一的文件和目录。 参见以下示例。
@end deffn

@geindex copytree() (在 shutil 模块中)
@anchor{library/shutil shutil copytree}@anchor{34e}
@deffn {函数} shutil.copytree (src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)

递归地将以 @emph{src} 为根起点的整个目录树拷贝到名为 @emph{dst} 的目录并返回目标目录。 所需的包含 @emph{dst} 的中间目录在默认情况下也将被创建。

目录的权限和时间会通过 @ref{b5b,,copystat()} 来拷贝，单个文件则会使用 @ref{38b,,copy2()} 来拷贝。

如果 @emph{symlinks} 为真值，源目录树中的符号链接会在新目录树中表示为符号链接，并且原链接的元数据在平台允许的情况下也会被拷贝；如果为假值或省略，则会将被链接文件的内容和元数据拷贝到新目录树。

当 @emph{symlinks} 为假值时，如果符号链接所指向的文件不存在，则会在拷贝进程的末尾将一个异常添加到 @ref{9a2,,Error} 异常中的错误列表。 如果你希望屏蔽此异常那就将可选的 @emph{ignore_dangling_symlinks} 旗标设为真值。 请注意此选项在不支持 @ref{b20,,os.symlink()} 的平台上将不起作用。

如果给出了 @emph{ignore}，它必须是一个可调用对象，该对象将接受 @ref{34e,,copytree()} 所访问的目录以及 @ref{b25,,os.listdir()} 所返回的目录内容列表作为其参数。 由于 @ref{34e,,copytree()} 是递归地被调用的，@emph{ignore} 可调用对象对于每个被拷贝目录都将被调用一次。 该可调用对象必须返回一个相对于当前目录的目录和文件名序列（即其第二个参数的子集）；随后这些名称将在拷贝进程中被忽略。 @ref{1e2e,,ignore_patterns()} 可被用于创建这种基于 glob 风格模式来忽略特定名称的可调用对象。

如果发生了（一个或多个）异常，将引发一个附带原因列表的 @ref{9a2,,Error}。

如果给出了 @emph{copy_function}，它必须是一个将被用来拷贝每个文件的可调用对象。 它在被调用时会将源路径和目标路径作为参数传入。 默认情况下，@ref{38b,,copy2()} 将被使用，但任何支持同样签名（与 @ref{38a,,copy()} 一致）都可以使用。

如果 @emph{dirs_exist_ok} 为（默认的）假值且 @emph{dst} 已存在，则会引发 @ref{a42,,FileExistsError}。 如果 @emph{dirs_exist_ok} 为真值，则如果拷贝操作遇到已存在的目录时将继续执行，并且在 @emph{dst} 目录树中的文件将被 @emph{src} 目录树中对应的文件所覆盖。

引发一个 @ref{fec,,审计事件} @code{shutil.copytree} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 当 @emph{symlinks} 为假值时拷贝元数据。 现在会返回 @emph{dst}。



在 3.2 版更改: 添加了 @emph{copy_function} 参数以允许提供定制的拷贝函数。 添加了 @emph{ignore_dangling_symlinks} 参数以便在 @emph{symlinks} 为假值时屏蔽目标不存在的符号链接。



在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷贝文件。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。



3.8 新版功能: @emph{dirs_exist_ok} 形参。

@end deffn

@geindex rmtree() (在 shutil 模块中)
@anchor{library/shutil shutil rmtree}@anchor{350}
@deffn {函数} shutil.rmtree (path, ignore_errors=False, onerror=None)

@geindex directory; deleting

删除一个完整的目录树；@emph{path} 必须指向一个目录（但不能是一个目录的符号链接）。 如果 @emph{ignore_errors} 为真值，删除失败导致的错误将被忽略；如果为假值或是省略，此类错误将通过调用由 @emph{onerror} 所指定的处理程序来处理，或者如果此参数被省略则将引发一个异常。

@cartouche
@quotation 注解 
在支持必要的基于 fd 的函数的平台上，默认会使用 @ref{350,,rmtree()} 的可防御符号链接攻击的版本。 在其他平台上，@ref{350,,rmtree()} 较易遭受符号链接攻击：给定适当的时间和环境，攻击者可以操纵文件系统中的符号链接来删除他们在其他情况下无法访问的文件。 应用程序可以使用 @ref{1e2f,,rmtree.avoids_symlink_attacks} 函数属性来确定此类情况具体是哪一些。
@end quotation
@end cartouche

如果提供了 @emph{onerror}，它必须为接受三个形参的可调用对象: @emph{function}, @emph{path} 和 @emph{excinfo}。

第一个形参 @emph{function} 是引发异常的函数；它依赖于具体的平台和实现。 第二个形参 @emph{path} 将是传递给 @emph{function} 的路径名。 第三个形参 @emph{excinfo} 将是由 @ref{d2f,,sys.exc_info()} 所返回的异常信息。 由 @emph{onerror} 所引发的异常将不会被捕获。

引发一个 @ref{fec,,审计事件} @code{shutil.rmtree} 附带参数 @code{path}。


在 3.3 版更改: 添加了一个防御符号链接攻击的版本，如果平台支持基于 fd 的函数就会被使用。



在 3.8 版更改: 在 Windows 上将不会再在移除连接之前删除目录连接中的内容。


@geindex avoids_symlink_attacks (shutil.rmtree 属性)
@anchor{library/shutil shutil rmtree avoids_symlink_attacks}@anchor{1e2f}
@deffn {属性} rmtree.avoids_symlink_attacks

指明当前平台和实现是否提供防御符号链接攻击的 @ref{350,,rmtree()} 版本。 目前它仅在平台支持基于 fd 的目录访问函数时才返回真值。


3.3 新版功能.

@end deffn
@end deffn

@geindex move() (在 shutil 模块中)
@anchor{library/shutil shutil move}@anchor{38c}
@deffn {函数} shutil.move (src, dst, copy_function=copy2)

递归地将一个文件或目录 (@emph{src}) 移至另一位置 (@emph{dst}) 并返回目标位置。

如果目标是已存在的目录，则 @emph{src} 会被移至该目录下。 如果目标已存在但不是目录，它可能会被覆盖，具体取决于 @ref{b1d,,os.rename()} 的语义。

如果目标是在当前文件系统中，则会使用 @ref{b1d,,os.rename()}。 在其他情况下，@emph{src} 将被拷贝至 @emph{dst}，使用的函数为 @emph{copy_function}，然后目标会被移除。 对于符号链接，则将在 @emph{dst} 之下或以其本身为名称创建一个指向 @emph{src} 目标的新符号链接，并且 @emph{src} 将被移除。

如果给出了 @emph{copy_function}，则它必须为接受两个参数 @emph{src} 和 @emph{dst} 的可调用对象，并将在 @ref{b1d,,os.rename()} 无法使用时被用来将 @emph{src} 拷贝到 @emph{dst}。 如果源是一个目录，则会调用 @ref{34e,,copytree()}，并向它传入 @code{copy_function()}。 默认的 @emph{copy_function} 是 @ref{38b,,copy2()}。 使用 @ref{38a,,copy()} 作为 @emph{copy_function} 允许在无法附带拷贝元数据时让移动操作成功执行，但其代价是不拷贝任何元数据。

引发一个 @ref{fec,,审计事件} @code{shutil.move} 附带参数 @code{src}, @code{dst}。


在 3.3 版更改: 为异类文件系统添加了显式的符号链接处理，以便使它适应 GNU 的 @code{mv} 的行为。 现在会返回 @emph{dst}。



在 3.5 版更改: 增加了 @emph{copy_function} 关键字参数。



在 3.8 版更改: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷贝文件。 参见 @ref{38f,,依赖于具体平台的高效拷贝操作} 一节。



在 3.9 版更改: 接受一个 @ref{47b,,path-like object} 作为 @emph{src} 和 @emph{dst}。

@end deffn

@geindex disk_usage() (在 shutil 模块中)
@anchor{library/shutil shutil disk_usage}@anchor{b59}
@deffn {函数} shutil.disk_usage (path)

返回给定路径的磁盘使用统计数据，形式为一个 @ref{b84,,named tuple}，其中包含 @emph{total}, @emph{used} 和 @emph{free} 属性，分别表示总计、已使用和未使用空间的字节数。 @emph{path} 可以是一个文件或是一个目录。


3.3 新版功能.



在 3.8 版更改: 在 Windows 上，@emph{path} 现在可以是一个文件或目录。


@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex chown() (在 shutil 模块中)
@anchor{library/shutil shutil chown}@anchor{b5a}
@deffn {函数} shutil.chown (path, user=None, group=None)

修改给定 @emph{path} 的所有者 @emph{user} 和/或 @emph{group}。

@emph{user} 可以是一个系统用户名或 uid；@emph{group} 同样如此。 要求至少有一个参数。

另请参阅下层的函数 @ref{b19,,os.chown()}。

引发一个 @ref{fec,,审计事件} @code{shutil.chown} 附带参数 @code{path}, @code{user}, @code{group}。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex which() (在 shutil 模块中)
@anchor{library/shutil shutil which}@anchor{1031}
@deffn {函数} shutil.which (cmd, mode=os.F_OK | os.X_OK, path=None)

返回当给定的 @emph{cmd} 被调用时将要运行的可执行文件的路径。 如果没有 @emph{cmd} 会被调用则返回 @code{None}。

@emph{mode} 是一个传递给 @ref{b16,,os.access()} 的权限掩码，在默认情况下将确定文件是否存在并且为可执行文件。

当未指定 @emph{path} 时，将会使用 @ref{c12,,os.environ()} 的结果，返回 "PATH" 的值或回退为 @ref{1163,,os.defpath}。

在 Windows 上当前目录总是会被添加为 @emph{path} 的第一项，无论你是否使用默认值或提供你自己的路径，这是命令行终端在查找可执行文件时所采用的行为方式。 此外，当在 @emph{path} 中查找 @emph{cmd} 时，还会检查 @code{PATHEXT} 环境变量。 例如，如果你调用 @code{shutil.which("python")}，@ref{1031,,which()} 将搜索 @code{PATHEXT} 来确定它要在 @emph{path} 目录中查找 @code{python.exe}。 例如，在 Windows 上:

@example
>>> shutil.which("python")
'C:\\Python33\\python.EXE'
@end example


3.3 新版功能.



在 3.8 版更改: 现在可以接受 @ref{172,,bytes} 类型。 如果 @emph{cmd} 的类型为 @ref{172,,bytes}，结果的类型也将为 @ref{172,,bytes}。

@end deffn

@geindex Error
@anchor{library/shutil shutil Error}@anchor{9a2}
@deffn {例外} shutil.Error

此异常会收集在多文件操作期间所引发的异常。 对于 @ref{34e,,copytree()}，此异常参数将是一个由三元组 (@emph{srcname}, @emph{dstname}, @emph{exception}) 构成的列表。
@end deffn

@menu
* 依赖于具体平台的高效拷贝操作:: 
* copytree 示例:: 
* rmtree 示例:: 

@end menu

@node 依赖于具体平台的高效拷贝操作,copytree 示例,,目录和文件操作
@anchor{library/shutil platform-dependent-efficient-copy-operations}@anchor{1e30}@anchor{library/shutil shutil-platform-dependent-efficient-copy-operations}@anchor{38f}
@subsubsection 依赖于具体平台的高效拷贝操作


从 Python 3.8 开始，所有涉及文件拷贝的函数 (@ref{389,,copyfile()}, @ref{38a,,copy()}, @ref{38b,,copy2()}, @ref{34e,,copytree()} 以及 @ref{38c,,move()}) 将会使用平台专属的 "fast-copy" 系统调用以便更高效地拷贝文件 (参见 bpo-33671@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33671})。 "fast-copy" 意味着拷贝操作将发生于内核之中，避免像在 "@code{outfd.write(infd.read())}" 中那样使用 Python 用户空间的缓冲区。

在 macOS 上将会使用 fcopyfile@footnote{http://www.manpagez.com/man/3/copyfile/} 来拷贝文件内容（不含元数据）。

在 Linux 上将会使用 @ref{46a,,os.sendfile()}。

在 Windows 上 @ref{389,,shutil.copyfile()} 将会使用更大的默认缓冲区（1 MiB 而非 64 KiB）并且会使用基于 @ref{38d,,memoryview()} 的 @ref{38e,,shutil.copyfileobj()} 变种形式。

如果快速拷贝操作失败并且没有数据被写入目标文件，则 shutil 将在内部静默地回退到使用效率较低的 @ref{38e,,copyfileobj()} 函数。


在 3.8 版更改.


@node copytree 示例,rmtree 示例,依赖于具体平台的高效拷贝操作,目录和文件操作
@anchor{library/shutil copytree-example}@anchor{1e31}@anchor{library/shutil shutil-copytree-example}@anchor{1e32}
@subsubsection copytree 示例


一个使用 @ref{1e2e,,ignore_patterns()} 辅助函数的例子:

@example
from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
@end example

这将会拷贝除 @code{.pyc} 文件和以 @code{tmp} 打头的文件或目录以外的所有条目.

另一个使用 @emph{ignore} 参数来添加记录调用的例子:

@example
from shutil import copytree
import logging

def _logpath(path, names):
    logging.info('Working in %s', path)
    return []   # nothing will be ignored

copytree(source, destination, ignore=_logpath)
@end example

@node rmtree 示例,,copytree 示例,目录和文件操作
@anchor{library/shutil rmtree-example}@anchor{1e33}@anchor{library/shutil shutil-rmtree-example}@anchor{1e34}
@subsubsection rmtree 示例


这个例子演示了如何在 Windows 上删除一个目录树，其中部分文件设置了只读属性位。 它会使用 onerror 回调函数来清除只读属性位并再次尝试删除。 任何后续的失败都将被传播。

@example
import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)
@end example

@node 归档操作,查询输出终端的尺寸,目录和文件操作,shutil --- 高阶文件操作
@anchor{library/shutil archiving-operations}@anchor{c70}@anchor{library/shutil id1}@anchor{1e35}
@subsubsection 归档操作



3.2 新版功能.



在 3.5 版更改: 添加了对 @emph{xztar} 格式的支持。


本模块也提供了用于创建和读取压缩和归档文件的高层级工具。 它们依赖于 @ref{14b,,zipfile} 和 @ref{101,,tarfile} 模块。

@geindex make_archive() (在 shutil 模块中)
@anchor{library/shutil shutil make_archive}@anchor{34f}
@deffn {函数} shutil.make_archive (base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

创建一个归档文件（例如 zip 或 tar）并返回其名称。

@emph{base_name} 是要创建的文件名称，包括路径，去除任何特定格式的扩展名。 @emph{format} 是归档格式：为 "zip" (如果 @ref{14d,,zlib} 模块可用), "tar", "gztar" (如果 @ref{14d,,zlib} 模块可用), "bztar" (如果 @ref{13,,bz2} 模块可用) 或 "xztar" (如果 @ref{ad,,lzma} 模块可用) 中的一个。

@emph{root_dir} 是一个目录，它将作为归档文件的根目录，归档中的所有路径都将是它的相对路径；例如，我们通常会在创建归档之前用 chdir 命令切换到 @emph{root_dir}。

@emph{base_dir} 是我们要执行归档的起始目录；也就是说 @emph{base_dir} 将成为归档中所有文件和目录共有的路径前缀。 @emph{base_dir} 必须相对于 @emph{root_dir} 给出。 请参阅 @ref{1e36,,使用 base_dir 的归档程序示例} 了解如何同时使用 @emph{base_dir} 和 @emph{root_dir}。

@emph{root_dir} 和 @emph{base_dir} 默认均为当前目录。

如果 @emph{dry_run} 为真值，则不会创建归档文件，但将要被执行的操作会被记录到 @emph{logger}。

@emph{owner} 和 @emph{group} 将在创建 tar 归档文件时被使用。 默认会使用当前的所有者和分组。

@emph{logger} 必须是一个兼容 
@geindex Python 提高建议; PEP 282
PEP 282@footnote{https://www.python.org/dev/peps/pep-0282} 的对象，通常为 @ref{4b6,,logging.Logger} 的实例。

@emph{verbose} 参数已不再使用并进入弃用状态。

引发一个 @ref{fec,,审计事件} @code{shutil.make_archive} 并附带参数 @code{base_name}, @code{format}, @code{root_dir}, @code{base_dir}。

@cartouche
@quotation 注解 
这个函数不是线程安全的。
@end quotation
@end cartouche


在 3.8 版更改: 现在对于通过 @code{format="tar"} 创建的归档文件将使用新式的 pax (POSIX.1-2001) 格式而非旧式的 GNU 格式。

@end deffn

@geindex get_archive_formats() (在 shutil 模块中)
@anchor{library/shutil shutil get_archive_formats}@anchor{1e37}
@deffn {函数} shutil.get_archive_formats ()

返回支持的归档格式列表。 所返回序列中的每个元素为一个元组 @code{(name, description)}。

默认情况下 @ref{e9,,shutil} 提供以下格式:


@itemize -

@item 
@emph{zip}: ZIP 文件（如果 @ref{14d,,zlib} 模块可用）。

@item 
@emph{tar}: 未压缩的 tar 文件。 对于新归档文件将使用 POSIX.1-2001 pax 格式。

@item 
@emph{gztar}: gzip 压缩的 tar 文件（如果 @ref{14d,,zlib} 模块可用）。

@item 
@emph{bztar}: bzip2 压缩的 tar 文件（如果 @ref{13,,bz2} 模块可用）。

@item 
@emph{xztar}: xz 压缩的 tar 文件（如果 @ref{ad,,lzma} 模块可用）。
@end itemize

你可以通过使用 @ref{1e38,,register_archive_format()} 注册新的格式或为任何现有格式提供你自己的归档器。
@end deffn

@geindex register_archive_format() (在 shutil 模块中)
@anchor{library/shutil shutil register_archive_format}@anchor{1e38}
@deffn {函数} shutil.register_archive_format (name, function[, extra_args[, description]])

为 @emph{name} 格式注册一个归档器。

@emph{function} 是将被用来解包归档文件的可调用对象。 该可调用对象将接收要创建文件的 @emph{base_name}，再加上要归档内容的 @emph{base_dir} (其默认值为 @ref{1d97,,os.curdir})。 更多参数会被作为关键字参数传入: @emph{owner}, @emph{group}, @emph{dry_run} 和 @emph{logger} (与向 @ref{34f,,make_archive()} 传入的参数一致)。

如果给出了 @emph{extra_args}，则其应为一个 @code{(name, value)} 对的序列，将在归档器可调用对象被使用时作为附加的关键字参数。

@emph{description} 由 @ref{1e37,,get_archive_formats()} 使用，它将返回归档器的列表。 默认值为一个空字符串。
@end deffn

@geindex unregister_archive_format() (在 shutil 模块中)
@anchor{library/shutil shutil unregister_archive_format}@anchor{1e39}
@deffn {函数} shutil.unregister_archive_format (name)

从支持的格式中移除归档格式 @emph{name}。
@end deffn

@geindex unpack_archive() (在 shutil 模块中)
@anchor{library/shutil shutil unpack_archive}@anchor{28b}
@deffn {函数} shutil.unpack_archive (filename[, extract_dir[, format[, filter]]])

解包一个归档文件。 @emph{filename} 是归档文件的完整路径。

@emph{extract_dir} 是归档文件解包的目标目录名称。 如果未提供，则将使用当前工作目录。

@emph{format} 是归档格式：应为 "zip", "tar", "gztar", "bztar" 或 "xztar" 之一。 或者任何通过 @ref{1e3a,,register_unpack_format()} 注册的其他格式。 如果未提供，@ref{28b,,unpack_archive()} 将使用归档文件的扩展名来检查是否注册了对应于该扩展名的解包器。 在未找到任何解包器的情况下，将引发 @ref{16d,,ValueError}。

The keyword-only @emph{filter} argument, which was added in Python 3.9.17,
is passed to the underlying unpacking function.
For zip files, @emph{filter} is not accepted.
For tar files, it is recommended to set it to @code{'data'},
unless using features specific to tar and UNIX-like filesystems.
(See @ref{28c,,Extraction filters} for details.)
The @code{'data'} filter will become the default for tar files
in Python 3.14.

引发一个 @ref{fec,,审计事件} @code{shutil.unpack_archive} 附带参数 @code{filename}, @code{extract_dir}, @code{format}。

@cartouche
@quotation 警告 
绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有可能会在 @emph{extract_dir} 参数所指定的路径之外创建文件，例如某些成员具有以 "/" 打头的绝对路径文件名或是以两个点号 ".." 打头的文件名。
@end quotation
@end cartouche


在 3.7 版更改: 接受一个 @ref{47b,,path-like object} 作为 @emph{filename} 和 @emph{extract_dir}。



在 3.9.17 版更改: Added the @emph{filter} argument.

@end deffn

@geindex register_unpack_format() (在 shutil 模块中)
@anchor{library/shutil shutil register_unpack_format}@anchor{1e3a}
@deffn {函数} shutil.register_unpack_format (name, extensions, function[, extra_args[, description]])

注册一个解包格式。 @emph{name} 为格式名称而 @emph{extensions} 为对应于该格式的扩展名列表，例如 Zip 文件的扩展名为 @code{.zip}。

@emph{function} is the callable that will be used to unpack archives. The
callable will receive:


@itemize -

@item 
the path of the archive, as a positional argument;

@item 
the directory the archive must be extracted to, as a positional argument;

@item 
possibly a @emph{filter} keyword argument, if it was given to
@ref{28b,,unpack_archive()};

@item 
additional keyword arguments, specified by @emph{extra_args} as a sequence
of @code{(name, value)} tuples.
@end itemize

可以提供 @emph{description} 来描述该格式，它将被 @ref{1e3b,,get_unpack_formats()} 返回。
@end deffn

@geindex unregister_unpack_format() (在 shutil 模块中)
@anchor{library/shutil shutil unregister_unpack_format}@anchor{1e3c}
@deffn {函数} shutil.unregister_unpack_format (name)

撤销注册一个解包格式。 @emph{name} 为格式的名称。
@end deffn

@geindex get_unpack_formats() (在 shutil 模块中)
@anchor{library/shutil shutil get_unpack_formats}@anchor{1e3b}
@deffn {函数} shutil.get_unpack_formats ()

返回所有已注册的解包格式列表。 所返回序列中的每个元素为一个元组 @code{(name, extensions, description)}。

默认情况下 @ref{e9,,shutil} 提供以下格式:


@itemize -

@item 
@emph{zip}: ZIP 文件（只有在相应模块可用时才能解包压缩文件）。

@item 
@emph{tar}: 未压缩的 tar 文件。

@item 
@emph{gztar}: gzip 压缩的 tar 文件（如果 @ref{14d,,zlib} 模块可用）。

@item 
@emph{bztar}: bzip2 压缩的 tar 文件（如果 @ref{13,,bz2} 模块可用）。

@item 
@emph{xztar}: xz 压缩的 tar 文件（如果 @ref{ad,,lzma} 模块可用）。
@end itemize

你可以通过使用 @ref{1e3a,,register_unpack_format()} 注册新的格式或为任何现有格式提供你自己的解包器。
@end deffn

@menu
* 归档程序示例:: 
* 使用 base_dir 的归档程序示例:: 

@end menu

@node 归档程序示例,使用 base_dir 的归档程序示例,,归档操作
@anchor{library/shutil archiving-example}@anchor{1e3d}@anchor{library/shutil shutil-archiving-example}@anchor{1e3e}
@subsubsection 归档程序示例


在这个示例中，我们创建了一个 gzip 压缩的 tar 归档文件，其中包含用户的 @code{.ssh} 目录下的所有文件:

@example
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'
@end example

结果归档文件中包含有:

@example
$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
-rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
-rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
-rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
-rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
-rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
-rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
-rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts
@end example

@node 使用 base_dir 的归档程序示例,,归档程序示例,归档操作
@anchor{library/shutil archiving-example-with-base-dir}@anchor{1e3f}@anchor{library/shutil shutil-archiving-example-with-basedir}@anchor{1e36}
@subsubsection 使用 @emph{base_dir} 的归档程序示例


在这个例子中，与 @ref{1e3e,,上面的例子} 类似，我们演示了如何使用 @ref{34f,,make_archive()}，但这次是使用 @emph{base_dir}。 我们现在具有如下的目录结构:

@example
$ tree tmp
tmp
└── root
    └── structure
        ├── content
            └── please_add.txt
        └── do_not_add.txt
@end example

在最终的归档中，应当会包括 @code{please_add.txt}，但不应当包括 @code{do_not_add.txt}。 因此我们使用以下代码:

@example
>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> make_archive(
...     archive_name,
...     'tar',
...     root_dir='tmp/root',
...     base_dir='structure/content',
... )
'/Users/tarek/my_archive.tar'
@end example

列出结果归档中的文件我们将会得到:

@example
$ python -m tarfile -l /Users/tarek/myarchive.tar
structure/content/
structure/content/please_add.txt
@end example

@node 查询输出终端的尺寸,,归档操作,shutil --- 高阶文件操作
@anchor{library/shutil querying-the-size-of-the-output-terminal}@anchor{1e40}
@subsubsection 查询输出终端的尺寸


@geindex get_terminal_size() (在 shutil 模块中)
@anchor{library/shutil shutil get_terminal_size}@anchor{b2e}
@deffn {函数} shutil.get_terminal_size (fallback=(columns, lines))

获取终端窗口的尺寸。

对于两个维度中的每一个，会分别检查环境变量 @code{COLUMNS} 和 @code{LINES}。 如果定义了这些变量并且其值为正整数，则将使用这些值。

如果未定义 @code{COLUMNS} 或 @code{LINES}，这是通常的情况，则连接到 @ref{1e41,,sys.__stdout__} 的终端将通过发起调用 @ref{b2d,,os.get_terminal_size()} 被查询。

如果由于系统不支持查询，或是由于我们未连接到某个终端而导致查询终端尺寸不成功，则会使用在 @code{fallback} 形参中给出的值。 @code{fallback} 默认为 @code{(80, 24)}，这是许多终端模拟器所使用的默认尺寸。

返回的值是一个 @ref{1e42,,os.terminal_size} 类型的具名元组。

另请参阅: The Single UNIX Specification, Version 2, Other Environment Variables@footnote{http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003}.


3.3 新版功能.

@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{c4,,os}

操作系统接口，包括处理比 Python @ref{c1d,,文件对象} 更低级别文件的功能。

@item 模块 @ref{a1,,io}

Python的内置 I/O 库，包括抽象类和一些具体的类，如文件 I/O 。

@item 内置函数 @ref{16f,,open()}

使用 Python 打开文件进行读写的标准方法。
@end table


@node 数据持久化,数据压缩和存档,文件和目录访问,Python 标准库
@anchor{library/persistence doc}@anchor{1e43}@anchor{library/persistence data-persistence}@anchor{1e44}@anchor{library/persistence other-environment-variables}@anchor{1e45}@anchor{library/persistence persistence}@anchor{1e46}
@section 数据持久化


本章中描述的模块支持在磁盘上以持久形式存储 Python 数据。 @ref{ca,,pickle} 和 @ref{b0,,marshal} 模块可以将许多 Python 数据类型转换为字节流，然后从字节中重新创建对象。 各种与 DBM 相关的模块支持一系列基于散列的文件格式，这些格式存储字符串到其他字符串的映射。

本章中描述的模块列表是：

@menu
* pickle: pickle --- Python 对象序列化. Python 对象序列化
* copyreg: copyreg --- 注册配合 pickle 模块使用的函数. 注册配合 pickle 模块使用的函数
* shelve: shelve --- Python 对象持久化. Python 对象持久化
* marshal: marshal --- 内部 Python 对象序列化. 内部 Python 对象序列化
* dbm: dbm --- Unix "数据库" 接口. Unix "数据库" 接口
* sqlite3: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块. SQLite 数据库 DB-API 2.0 接口模块

@end menu

@node pickle --- Python 对象序列化,copyreg --- 注册配合 pickle 模块使用的函数,,数据持久化
@anchor{library/pickle doc}@anchor{1e47}@anchor{library/pickle module-pickle}@anchor{ca}@anchor{library/pickle pickle-python-object-serialization}@anchor{1e48}
@subsection @code{pickle} --- Python 对象序列化


@geindex pickle (模块)

@strong{源代码：} Lib/pickle.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pickle.py}

@geindex persistence
@geindex persistent; objects
@geindex serializing; objects
@geindex marshalling; objects
@geindex flattening; objects
@geindex pickling; objects


__________________________________________________________________


模块 @ref{ca,,pickle} 实现了对一个 Python 对象结构的二进制序列化和反序列化。 @emph{"pickling"} 是将 Python 对象及其所拥有的层次结构转化为一个字节流的过程，而 @emph{"unpickling"} 是相反的操作，会将（来自一个 @ref{140a,,binary file} 或者 @ref{6e9,,bytes-like object} 的）字节流转化回一个对象层次结构。 pickling（和 unpickling）也被称为“序列化”, “编组” @footnote{@w{(1)} 
不要把它与 @ref{b0,,marshal} 模块混淆。
} 或者 “平面化”。而为了避免混乱，此处采用术语 “封存 (pickling)” 和 “解封 (unpickling)”。

@cartouche
@quotation 警告 
@code{pickle} 模块 @strong{并不安全}。 你只应该对你信任的数据进行 unpickle 操作。

构建恶意的 pickle 数据来 @strong{在解封时执行任意代码} 是可能的。 绝对不要对不信任来源的数据和可能被篡改过的数据进行解封。

请考虑使用 @ref{8e,,hmac} 来对数据进行签名，确保数据没有被篡改。

在你处理不信任数据时，更安全的序列化格式如 @ref{a4,,json} 可能更为适合。参见  @ref{1e49,,与 json 模块的比较} 。
@end quotation
@end cartouche

@menu
* 与其他 Python 模块间的关系:: 
* 数据流格式:: 
* 模块接口:: 
* 可以被封存/解封的对象:: 
* 封存类实例:: 
* 类型，函数和其他对象的自定义归约:: 
* 外部缓冲区:: 
* 限制全局变量:: 
* 性能: 性能<2>. 
* 示例: 示例<8>. 

@end menu

@node 与其他 Python 模块间的关系,数据流格式,,pickle --- Python 对象序列化
@anchor{library/pickle relationship-to-other-python-modules}@anchor{1e4a}
@subsubsection 与其他 Python 模块间的关系


@menu
* 与 marshal 间的关系:: 
* 与 json 模块的比较:: 

@end menu

@node 与 marshal 间的关系,与 json 模块的比较,,与其他 Python 模块间的关系
@anchor{library/pickle comparison-with-marshal}@anchor{1e4b}
@subsubsection 与 @code{marshal} 间的关系


Python 有一个更原始的序列化模块称为 @ref{b0,,marshal}，但一般地 @ref{ca,,pickle} 应该是序列化 Python 对象时的首选。@ref{b0,,marshal} 存在主要是为了支持 Python 的 @code{.pyc} 文件.

@ref{ca,,pickle} 模块与 @ref{b0,,marshal} 在如下几方面显著地不同：


@itemize *

@item 
@ref{ca,,pickle} 模块会跟踪已被序列化的对象，所以该对象之后再次被引用时不会再次被序列化。@ref{b0,,marshal} 不会这么做。

这隐含了递归对象和共享对象。递归对象指包含对自己的引用的对象。这种对象并不会被 marshal 接受，并且实际上尝试 marshal 递归对象会让你的 Python 解释器崩溃。对象共享发生在对象层级中存在多处引用同一对象时。@ref{ca,,pickle} 只会存储这些对象一次，并确保其他的引用指向同一个主副本。共享对象将保持共享，这可能对可变对象非常重要。

@item 
@ref{b0,,marshal} 不能被用于序列化用户定义类及其实例。@ref{ca,,pickle} 能够透明地存储并保存类实例，然而此时类定义必须能够从与被存储时相同的模块被引入。

@item 
同样用于序列化的 @ref{b0,,marshal} 格式不保证数据能移植到不同的 Python 版本中。因为它的主要任务是支持 @code{.pyc} 文件，必要时会以破坏向后兼容的方式更改这种序列化格式，为此 Python 的实现者保留了更改格式的权利。@ref{ca,,pickle} 序列化格式可以在不同版本的 Python 中实现向后兼容，前提是选择了合适的 pickle 协议。如果你的数据要在 Python 2 与 Python 3 之间跨越传递，封存和解封的代码在 2 和 3 之间也是不同的。
@end itemize

@node 与 json 模块的比较,,与 marshal 间的关系,与其他 Python 模块间的关系
@anchor{library/pickle comparison-with-json}@anchor{1e49}@anchor{library/pickle id2}@anchor{1e4c}
@subsubsection 与 @code{json} 模块的比较


Pickle 协议和 JSON (JavaScript Object Notation)@footnote{http://json.org} 间有着本质的不同：


@itemize *

@item 
JSON 是一个文本序列化格式（它输出 unicode 文本，尽管在大多数时候它会接着以 @code{utf-8} 编码），而 pickle 是一个二进制序列化格式；

@item 
JSON 是我们可以直观阅读的，而 pickle 不是；

@item 
JSON是可互操作的，在Python系统之外广泛使用，而pickle则是Python专用的；

@item 
默认情况下，JSON 只能表示 Python 内置类型的子集，不能表示自定义的类；但 pickle 可以表示大量的 Python 数据类型（可以合理使用 Python 的对象内省功能自动地表示大多数类型，复杂情况可以通过实现 @ref{1e4d,,specific object APIs} 来解决）。

@item 
不像pickle，对一个不信任的JSON进行反序列化的操作本身不会造成任意代码执行漏洞。
@end itemize


@subsubheading 参见


@ref{a4,,json} 模块:一个允许JSON序列化和反序列化的标准库模块


@node 数据流格式,模块接口,与其他 Python 模块间的关系,pickle --- Python 对象序列化
@anchor{library/pickle data-stream-format}@anchor{1e4e}@anchor{library/pickle pickle-protocols}@anchor{670}
@subsubsection 数据流格式


@geindex External Data Representation

@ref{ca,,pickle} 所使用的数据格式仅可用于 Python。这样做的好处是没有外部标准给该格式强加限制，比如 JSON 或 XDR（不能表示共享指针）标准；但这也意味着非 Python 程序可能无法重新读取 pickle 封存的 Python 对象。

默认情况下，@ref{ca,,pickle} 格式使用相对紧凑的二进制来存储。如果需要让文件更小，可以高效地 @ref{1e4f,,压缩} 由 pickle 封存的数据。

@ref{cb,,pickletools} 模块包含了相应的工具用于分析 @ref{ca,,pickle} 生成的数据流。@ref{cb,,pickletools} 源码中包含了对 pickle 协议使用的操作码的大量注释。

当前共有 6 种不同的协议可用于封存操作。 使用的协议版本越高，读取所生成 pickle 对象所需的 Python 版本就要越新。


@itemize *

@item 
v0 版协议是原始的“人类可读”协议，并且向后兼容早期版本的 Python。

@item 
v1 版协议是较早的二进制格式，它也与早期版本的 Python 兼容。

@item 
第 2 版协议是在 Python 2.3 中引入的。 它为 @ref{1e50,,新式类} 提供了更高效的封存机制。 请参考 
@geindex Python 提高建议; PEP 307
PEP 307@footnote{https://www.python.org/dev/peps/pep-0307} 了解第 2 版协议带来的改进的相关信息。

@item 
v3 版协议是在 Python 3.0 中引入的。 它显式地支持 @ref{172,,bytes} 字节对象，不能使用 Python 2.x 解封。这是 Python 3.0-3.7 的默认协议。

@item 
v4 版协议添加于 Python 3.4。它支持存储非常大的对象，能存储更多种类的对象，还包括一些针对数据格式的优化。它是Python 3.8使用的默认协议。有关第 4 版协议带来改进的信息，请参阅 
@geindex Python 提高建议; PEP 3154
PEP 3154@footnote{https://www.python.org/dev/peps/pep-3154}。

@item 
第 5 版协议是在 Python 3.8 中加入的。 它增加了对带外数据的支持，并可加速带内数据处理。 请参阅 
@geindex Python 提高建议; PEP 574
PEP 574@footnote{https://www.python.org/dev/peps/pep-0574} 了解第 5 版协议所带来的改进的详情。
@end itemize

@cartouche
@quotation 注解 
序列化是一种比持久化更底层的概念，虽然 @ref{ca,,pickle} 读取和写入的是文件对象，但它不处理持久对象的命名问题，也不处理对持久对象的并发访问（甚至更复杂）的问题。@ref{ca,,pickle} 模块可以将复杂对象转换为字节流，也可以将字节流转换为具有相同内部结构的对象。处理这些字节流最常见的做法是将它们写入文件，但它们也可以通过网络发送或存储在数据库中。@ref{e7,,shelve} 模块提供了一个简单的接口，用于在 DBM 类型的数据库文件上封存和解封对象。
@end quotation
@end cartouche

@node 模块接口,可以被封存/解封的对象,数据流格式,pickle --- Python 对象序列化
@anchor{library/pickle module-interface}@anchor{1e51}
@subsubsection 模块接口


要序列化某个包含层次结构的对象，只需调用 @ref{ecb,,dumps()} 函数即可。同样，要反序列化数据流，可以调用 @ref{6c4,,loads()} 函数。但是，如果要对序列化和反序列化加以更多的控制，可以分别创建 @ref{342,,Pickler} 或 @ref{1e52,,Unpickler} 对象。

@ref{ca,,pickle} 模块包含了以下常量：

@geindex HIGHEST_PROTOCOL() (在 pickle 模块中)
@anchor{library/pickle pickle HIGHEST_PROTOCOL}@anchor{ecc}
@deffn {数据} pickle.HIGHEST_PROTOCOL

整数，可用的最高 @ref{670,,协议版本}。此值可以作为 @emph{协议} 值传递给 @ref{1e53,,dump()} 和 @ref{ecb,,dumps()} 函数，以及 @ref{342,,Pickler} 的构造函数。
@end deffn

@geindex DEFAULT_PROTOCOL() (在 pickle 模块中)
@anchor{library/pickle pickle DEFAULT_PROTOCOL}@anchor{1e54}
@deffn {数据} pickle.DEFAULT_PROTOCOL

整数，用于 pickle 数据的默认 @ref{670,,协议版本}。它可能小于 @ref{ecc,,HIGHEST_PROTOCOL}。当前默认协议是 v4，它在 Python 3.4 中首次引入，与之前的版本不兼容。


在 3.0 版更改: 默认协议版本是 3。



在 3.8 版更改: 默认协议版本是 4。

@end deffn

@ref{ca,,pickle} 模块提供了以下方法，让封存过程更加方便：

@geindex dump() (在 pickle 模块中)
@anchor{library/pickle pickle dump}@anchor{1e53}
@deffn {函数} pickle.dump (obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

将对象 @emph{obj} 封存以后的对象写入已打开的 @ref{c1d,,file object} @emph{file}。它等同于 @code{Pickler(file, protocol).dump(obj)}。

参数 @emph{file}、@emph{protocol}、@emph{fix_imports} 和 @emph{buffer_callback} 的含义与它们在 @ref{342,,Pickler} 的构造函数中的含义相同。


在 3.8 版更改: 加入了 @emph{buffer_callback} 参数。

@end deffn

@geindex dumps() (在 pickle 模块中)
@anchor{library/pickle pickle dumps}@anchor{ecb}
@deffn {函数} pickle.dumps (obj, protocol=None, *, fix_imports=True, buffer_callback=None)

将 @emph{obj} 封存以后的对象作为 @ref{172,,bytes} 类型直接返回，而不是将其写入到文件。

参数 @emph{protocol}、@emph{fix_imports} 和 @emph{buffer_callback} 的含义与它们在 @ref{342,,Pickler} 的构造函数中的含义相同。


在 3.8 版更改: 加入了 @emph{buffer_callback} 参数。

@end deffn

@geindex load() (在 pickle 模块中)
@anchor{library/pickle pickle load}@anchor{6c3}
@deffn {函数} pickle.load (file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)

从已打开的 @ref{c1d,,file object} @emph{文件} 中读取封存后的对象，重建其中特定对象的层次结构并返回。它相当于 @code{Unpickler(file).load()}。

Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象以外的其他字节将被忽略。

参数 @emph{file}、@emph{fix_imports}、@emph{encoding}、@emph{errors}、@emph{strict} 和 @emph{buffers} 的含义与它们在 @ref{1e52,,Unpickler} 的构造函数中的含义相同。


在 3.8 版更改: 加入了 @emph{buffers} 参数。

@end deffn

@geindex loads() (在 pickle 模块中)
@anchor{library/pickle pickle loads}@anchor{6c4}
@deffn {函数} pickle.loads (data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)

重建并返回一个对象的封存表示形式 @emph{data} 的对象层级结构。 @emph{data} 必须为 @ref{6e9,,bytes-like object}。

Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象以外的其他字节将被忽略。

参数 @emph{fix_imports}, @emph{encoding}, @emph{errors}, @emph{strict} 和 @emph{buffers} 的含义与在 @ref{1e52,,Unpickler} 构造器中的含义相同。


在 3.8 版更改: 加入了 @emph{buffers} 参数。

@end deffn

@ref{ca,,pickle} 模块定义了以下 3 个异常：

@geindex PickleError
@anchor{library/pickle pickle PickleError}@anchor{1e55}
@deffn {例外} pickle.PickleError

其他 pickle 异常的基类。它是 @ref{2e3,,Exception} 的一个子类。
@end deffn

@geindex PicklingError
@anchor{library/pickle pickle PicklingError}@anchor{1e56}
@deffn {例外} pickle.PicklingError

当 @ref{342,,Pickler} 遇到无法解封的对象时抛出此错误。它是 @ref{1e55,,PickleError} 的子类。

参考 @ref{1e57,,可以被封存/解封的对象} 来了解哪些对象可以被封存。
@end deffn

@geindex UnpicklingError
@anchor{library/pickle pickle UnpicklingError}@anchor{1e58}
@deffn {例外} pickle.UnpicklingError

当解封出错时抛出此异常，例如数据损坏或对象不安全。它是 @ref{1e55,,PickleError} 的子类。

注意，解封时可能还会抛出其他异常，包括（但不限于） AttributeError、EOFError、ImportError 和 IndexError。
@end deffn

@ref{ca,,pickle} 模块包含了 3 个类，@ref{342,,Pickler}、@ref{1e52,,Unpickler} 和 @ref{f6d,,PickleBuffer}：

@geindex Pickler (pickle 中的类)
@anchor{library/pickle pickle Pickler}@anchor{342}
@deffn {类} pickle.Pickler (file, protocol=None, *, fix_imports=True, buffer_callback=None)

它接受一个二进制文件用于写入 pickle 数据流。

可选参数 @emph{protocol} 是一个整数，告知 pickler 使用指定的协议，可选择的协议范围从 0 到 @ref{ecc,,HIGHEST_PROTOCOL}。如果没有指定，这一参数默认值为 @ref{1e54,,DEFAULT_PROTOCOL}。指定一个负数就相当于指定 @ref{ecc,,HIGHEST_PROTOCOL}。

参数 @emph{file} 必须有一个 write() 方法，该 write() 方法要能接收字节作为其唯一参数。因此，它可以是一个打开的磁盘文件（用于写入二进制内容），也可以是一个 @ref{894,,io.BytesIO} 实例，也可以是满足这一接口的其他任何自定义对象。

如果 @emph{fix_imports} 为 True 且 @emph{protocol} 小于 3，pickle 将尝试将 Python 3 中的新名称映射到 Python 2 中的旧模块名称，因此 Python 2 也可以读取封存的数据流。

如果 @emph{buffer_callback} 为 None（默认情况），缓冲区视图（buffer view）将会作为 pickle 流的一部分被序列化到 @emph{file} 中。

如果 @emph{buffer_callback} 不为 None，那它可以用缓冲区视图调用任意次。如果某次调用返回了 False 值（例如 None），则给定的缓冲区是 @ref{1e59,,带外的}，否则缓冲区是带内的（例如保存在了 pickle 流里面）。

如果 @emph{buffer_callback} 不是 None 且 @emph{protocol} 是 None 或小于 5，就会出错。


在 3.8 版更改: 加入了 @emph{buffer_callback} 参数。


@geindex dump() (pickle.Pickler 方法)
@anchor{library/pickle pickle Pickler dump}@anchor{11bb}
@deffn {方法} dump (obj)

将 @emph{obj} 封存后的内容写入已打开的文件对象，该文件对象已经在构造函数中指定。
@end deffn

@geindex persistent_id() (pickle.Pickler 方法)
@anchor{library/pickle pickle Pickler persistent_id}@anchor{1e5a}
@deffn {方法} persistent_id (obj)

默认无动作，子类继承重载时使用。

如果 @ref{1e5a,,persistent_id()} 返回 @code{None}，@emph{obj} 会被照常 pickle。如果返回其他值，@ref{342,,Pickler} 会将这个函数的返回值作为 @emph{obj} 的持久化 ID（Pickler 本应得到序列化数据流并将其写入文件，若此函数有返回值，则得到此函数的返回值并写入文件）。这个持久化 ID 的解释应当定义在 @ref{1e5b,,Unpickler.persistent_load()} 中（该方法定义还原对象的过程，并返回得到的对象）。注意，@ref{1e5a,,persistent_id()} 的返回值本身不能拥有持久化 ID。

参阅 @ref{1e5c,,持久化外部对象} 获取详情和使用示例。
@end deffn

@geindex dispatch_table (pickle.Pickler 属性)
@anchor{library/pickle pickle Pickler dispatch_table}@anchor{b4d}
@deffn {属性} dispatch_table

Pickler 对象的 dispatch 表是 @ref{1e5d,,copyreg.pickle()} 中用到的 @emph{reduction 函数} 的注册。dispatch 表本身是一个 class 到其 reduction 函数的映射键值对。一个 reduction 函数只接受一个参数，就是其关联的 class，函数行为应当遵守 @ref{2d7,,__reduce__()} 接口规范。

Pickler 对象默认并没有 @ref{b4d,,dispatch_table} 属性，该对象默认使用 @ref{26,,copyreg} 模块中定义的全局 dispatch 表。如果要为特定 Pickler 对象自定义序列化过程，可以将 @ref{b4d,,dispatch_table} 属性设置为类字典对象（dict-like object）。另外，如果 @ref{342,,Pickler} 的子类设置了 @ref{b4d,,dispatch_table} 属性，则该子类的实例会使用这个表作为默认的 dispatch 表。

参阅 @ref{1e5e,,Dispatch 表} 获取使用示例。


3.3 新版功能.

@end deffn

@geindex reducer_override() (pickle.Pickler 方法)
@anchor{library/pickle pickle Pickler reducer_override}@anchor{343}
@deffn {方法} reducer_override (obj)

可以在 @ref{342,,Pickler} 的子类中定义的特殊 reducer。此方法的优先级高于 @ref{b4d,,dispatch_table} 中的任何 reducer。它应该与 @ref{2d7,,__reduce__()} 方法遵循相同的接口，它也可以返回 @code{NotImplemented}，这将使用 @ref{b4d,,dispatch_table} 里注册的 reducer 来封存 @code{obj}。

参阅 @ref{1e5f,,类型，函数和其他对象的自定义归约} 获取详细的示例。


3.8 新版功能.

@end deffn

@geindex fast (pickle.Pickler 属性)
@anchor{library/pickle pickle Pickler fast}@anchor{1e60}
@deffn {属性} fast

已弃用。设为 True 则启用快速模式。快速模式禁用了“备忘录” (memo) 的使用，即不生成多余的 PUT 操作码来加快封存过程。不应将其与自指 (self-referential) 对象一起使用，否则将导致 @ref{342,,Pickler} 无限递归。

如果需要进一步提高 pickle 的压缩率，请使用 @ref{1e61,,pickletools.optimize()}。
@end deffn
@end deffn

@geindex Unpickler (pickle 中的类)
@anchor{library/pickle pickle Unpickler}@anchor{1e52}
@deffn {类} pickle.Unpickler (file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None)

它接受一个二进制文件用于读取 pickle 数据流。

Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。

参数 @emph{file} 必须有三个方法，read() 方法接受一个整数参数，readinto() 方法接受一个缓冲区作为参数，readline() 方法不需要参数，这与 @ref{689,,io.BufferedIOBase} 里定义的接口是相同的。因此 @emph{file} 可以是一个磁盘上用于二进制读取的文件，也可以是一个 @ref{894,,io.BytesIO} 实例，也可以是满足这一接口的其他任何自定义对象。

可选的参数是 @emph{fix_imports}, @emph{encoding} 和 @emph{errors}，用于控制由Python 2 生成的 pickle 流的兼容性。如果 @emph{fix_imports} 为 True，则 pickle 将尝试将旧的 Python 2 名称映射到 Python 3 中对应的新名称。@emph{encoding} 和 @emph{errors} 参数告诉 pickle 如何解码 Python 2 存储的 8 位字符串实例；这两个参数默认分别为 'ASCII' 和 'strict'。@emph{encoding} 参数可置为 'bytes' 来将这些 8 位字符串实例读取为字节对象。读取 NumPy array 和 Python 2 存储的 @ref{19f,,datetime}、@ref{19d,,date} 和 @ref{5f5,,time} 实例时，请使用 @code{encoding='latin1'}。

如果 @emph{buffers} 为 None（默认值），则反序列化所需的所有数据都必须包含在 pickle 流中。这意味着在实例化 @ref{342,,Pickler} 时（或调用 @ref{1e53,,dump()} 或 @ref{ecb,,dumps()} 时），参数 @emph{buffer_callback} 为 None。

如果 @emph{buffers} 不为 None，则每次 pickle 流引用 @ref{1e59,,带外} 缓冲区视图时，消耗的对象都应该是可迭代的启用缓冲区的对象。这样的缓冲区应该按顺序地提供给 Pickler 对象的 @emph{buffer_callback} 方法。


在 3.8 版更改: 加入了 @emph{buffers} 参数。


@geindex load() (pickle.Unpickler 方法)
@anchor{library/pickle pickle Unpickler load}@anchor{1e62}
@deffn {方法} load ()

从构造函数中指定的文件对象里读取封存好的对象，重建其中特定对象的层次结构并返回。封存对象以外的其他字节将被忽略。
@end deffn

@geindex persistent_load() (pickle.Unpickler 方法)
@anchor{library/pickle pickle Unpickler persistent_load}@anchor{1e5b}
@deffn {方法} persistent_load (pid)

默认抛出 @ref{1e58,,UnpicklingError} 异常。

如果定义了此方法，@ref{1e5b,,persistent_load()} 应当返回持久化 ID @emph{pid} 所指定的对象。 如果遇到无效的持久化 ID，则应当引发 @ref{1e58,,UnpicklingError}。

参阅 @ref{1e5c,,持久化外部对象} 获取详情和使用示例。
@end deffn

@geindex find_class() (pickle.Unpickler 方法)
@anchor{library/pickle pickle Unpickler find_class}@anchor{1e63}
@deffn {方法} find_class (module, name)

如有必要，导入 @emph{module} 模块并返回其中名叫 @emph{name} 的对象，其中 @emph{module} 和 @emph{name} 参数都是 @ref{206,,str} 对象。注意，不要被这个函数的名字迷惑， @ref{1e63,,find_class()} 同样可以用来导入函数。

子类可以重载此方法，来控制加载对象的类型和加载对象的方式，从而尽可能降低安全风险。参阅 @ref{1e64,,限制全局变量} 获取更详细的信息。

引发一个 @ref{fec,,审计事件} @code{pickle.find_class} 附带参数 @code{module}、@code{name}。
@end deffn
@end deffn

@geindex PickleBuffer (pickle 中的类)
@anchor{library/pickle pickle PickleBuffer}@anchor{f6d}
@deffn {类} pickle.PickleBuffer (buffer)

缓冲区的包装器 (wrapper)，缓冲区中包含着可封存的数据。@emph{buffer} 必须是一个 @ref{174c,,buffer-providing} 对象，比如 @ref{6e9,,bytes-like object} 或多维数组。

@ref{f6d,,PickleBuffer} 本身就可以生成缓冲区对象，因此可以将其传递给需要缓冲区生成器的其他 API，比如 @ref{38d,,memoryview}。

@ref{f6d,,PickleBuffer} 对象只能用 pickle 版本 5 及以上协议进行序列化。它们符合 @ref{1e59,,带外序列化} 的条件。


3.8 新版功能.


@geindex raw() (pickle.PickleBuffer 方法)
@anchor{library/pickle pickle PickleBuffer raw}@anchor{1e65}
@deffn {方法} raw ()

返回该缓冲区底层内存区域的 @ref{38d,,memoryview}。 返回的对象是一维的、C 连续布局的 memoryview，格式为 @code{B} (无符号字节)。 如果缓冲区既不是 C 连续布局也不是 Fortran 连续布局的，则抛出 @ref{1881,,BufferError} 异常。
@end deffn

@geindex release() (pickle.PickleBuffer 方法)
@anchor{library/pickle pickle PickleBuffer release}@anchor{1e66}
@deffn {方法} release ()

释放由 PickleBuffer 占用的底层缓冲区。
@end deffn
@end deffn

@node 可以被封存/解封的对象,封存类实例,模块接口,pickle --- Python 对象序列化
@anchor{library/pickle pickle-picklable}@anchor{1e57}@anchor{library/pickle what-can-be-pickled-and-unpickled}@anchor{1e67}
@subsubsection 可以被封存/解封的对象


下列类型可以被封存：


@itemize *

@item 
@code{None}, @code{True} 和 @code{False};

@item 
整数、浮点数、复数;

@item 
字符串、字节串、字节数组;

@item 
只包含可封存对象的元组、列表、集合和字典;

@item 
functions (built-in and user-defined) defined at the top level of a module
(using @ref{e8b,,def}, not @ref{d01,,lambda});

@item 
classes defined at the top level of a module;

@item 
某些类实例，这些类的 @ref{5fe,,__dict__} 属性值或 @ref{ecd,,__getstate__()} 函数的返回值可以被封存（详情参阅 @ref{1e4d,,封存类实例} 这一段）。
@end itemize

尝试封存不能被封存的对象会抛出 @ref{1e56,,PicklingError} 异常，异常发生时，可能有部分字节已经被写入指定文件中。尝试封存递归层级很深的对象时，可能会超出最大递归层级限制，此时会抛出 @ref{731,,RecursionError} 异常，可以通过 @ref{f43,,sys.setrecursionlimit()} 调整递归层级，不过请谨慎使用这个函数，因为可能会导致解释器崩溃。

Note that functions (built-in and user-defined) are pickled by fully qualified
name, not by value. @footnote{@w{(2)} 
这就是为什么 @ref{d01,,lambda} 函数不可以被封存：所有的匿名函数都有同一个名字：@code{<lambda>}。
}  This means that only the function name is
pickled, along with the name of the module the function is defined in.  Neither
the function's code, nor any of its function attributes are pickled.  Thus the
defining module must be importable in the unpickling environment, and the module
must contain the named object, otherwise an exception will be raised. @footnote{@w{(3)} 
抛出的异常有可能是 @ref{16c,,ImportError} 或 @ref{4aa,,AttributeError}，也可能是其他异常。
}

类似地，类也是按完整限定名称来封存的，因此在解封环境中也会应用相同的限制。 请注意类的代码或数据都不会被封存，因此在下面的示例中类属性 @code{attr} 不会在解封环境中被恢复:

@example
class Foo:
    attr = 'A class attribute'

picklestring = pickle.dumps(Foo)
@end example

这些限制决定了为什么可封存的函数和类必须在一个模块的最高层级上定义。

类似的，在封存类的实例时，其类体和类数据不会跟着实例一起被封存，只有实例数据会被封存。这样设计是有目的的，在将来修复类中的错误、给类增加方法之后，仍然可以载入原来版本类实例的封存数据来还原该实例。如果你准备长期使用一个对象，可能会同时存在较多版本的类体，可以为对象添加版本号，这样就可以通过类的 @ref{2d8,,__setstate__()} 方法将老版本转换成新版本。

@node 封存类实例,类型，函数和其他对象的自定义归约,可以被封存/解封的对象,pickle --- Python 对象序列化
@anchor{library/pickle pickle-inst}@anchor{1e4d}@anchor{library/pickle pickling-class-instances}@anchor{1e68}
@subsubsection 封存类实例


在本节中，我们描述了可用于定义、自定义和控制如何封存和解封类实例的通用流程。

通常，使一个实例可被封存不需要附加任何代码。Pickle 默认会通过 Python 的内省机制获得实例的类及属性。而当实例解封时，它的 @ref{e2b,,__init__()} 方法通常 @emph{不会} 被调用。其默认动作是：先创建一个未初始化的实例，然后还原其属性，下面的代码展示了这种行为的实现机制：

@example
def save(obj):
    return (obj.__class__, obj.__dict__)

def restore(cls, attributes):
    obj = cls.__new__(cls)
    obj.__dict__.update(attributes)
    return obj
@end example

类可以改变默认行为，只需定义以下一种或几种特殊方法：

@geindex __getnewargs_ex__() (object 方法)
@anchor{library/pickle object __getnewargs_ex__}@anchor{1e69}
@deffn {方法} object.__getnewargs_ex__ ()

对于使用第 2 版或更高版协议的 pickle，实现了 @ref{1e69,,__getnewargs_ex__()} 方法的类可以控制在解封时传给 @ref{97d,,__new__()} 方法的参数。本方法必须返回一对 @code{(args, kwargs)} 用于构建对象，其中 @emph{args} 是表示位置参数的 tuple，而 @emph{kwargs} 是表示命名参数的 dict。它们会在解封时传递给 @ref{97d,,__new__()} 方法。

如果类的 @ref{97d,,__new__()} 方法只接受关键字参数，则应当实现这个方法。否则，为了兼容性，更推荐实现 @ref{7ab,,__getnewargs__()} 方法。


在 3.6 版更改: @ref{1e69,,__getnewargs_ex__()} 现在可用于第 2 和第 3 版协议。

@end deffn

@geindex __getnewargs__() (object 方法)
@anchor{library/pickle object __getnewargs__}@anchor{7ab}
@deffn {方法} object.__getnewargs__ ()

这个方法与上一个 @ref{1e69,,__getnewargs_ex__()} 方法类似，但仅支持位置参数。它要求返回一个 tuple 类型的 @code{args}，用于解封时传递给 @ref{97d,,__new__()} 方法。

如果定义了 @ref{1e69,,__getnewargs_ex__()}，那么 @ref{7ab,,__getnewargs__()} 就不会被调用。


在 3.6 版更改: 在 Python 3.6 前，第 2、3 版协议会调用 @ref{7ab,,__getnewargs__()}，更高版本协议会调用 @ref{1e69,,__getnewargs_ex__()}。

@end deffn

@geindex __getstate__() (object 方法)
@anchor{library/pickle object __getstate__}@anchor{ecd}
@deffn {方法} object.__getstate__ ()

类还可以进一步控制其实例的封存过程。如果类定义了 @ref{ecd,,__getstate__()}，它就会被调用，其返回的对象是被当做实例内容来封存的，否则封存的是实例的 __dict__。如果 @ref{ecd,,__getstate__()} 未定义，实例的 @ref{5fe,,__dict__} 会被照常封存。
@end deffn

@geindex __setstate__() (object 方法)
@anchor{library/pickle object __setstate__}@anchor{2d8}
@deffn {方法} object.__setstate__ (state)

当解封时，如果类定义了 @ref{2d8,,__setstate__()}，就会在已解封状态下调用它。此时不要求实例的 state 对象必须是 dict。没有定义此方法的话，先前封存的 state 对象必须是 dict，且该 dict 内容会在解封时赋给新实例的 __dict__。

@cartouche
@quotation 注解 
如果 @ref{ecd,,__getstate__()} 返回 False，那么在解封时就不会调用 @ref{2d8,,__setstate__()} 方法。
@end quotation
@end cartouche
@end deffn

参考 @ref{1e6a,,处理有状态的对象} 一段获取如何使用 @ref{ecd,,__getstate__()} 和 @ref{2d8,,__setstate__()} 方法的更多信息。

@cartouche
@quotation 注解 
在解封时，实例的某些方法例如 @ref{433,,__getattr__()}, @ref{552,,__getattribute__()} 或 @ref{ef6,,__setattr__()} 可能会被调用。 由于这些方法可能要求某些内部不变量为真值，因此该类型应当实现 @ref{97d,,__new__()} 以建立这样的不变量，因为当解封一个实例时 @ref{e2b,,__init__()} 并不会被调用。
@end quotation
@end cartouche

@geindex copy; protocol

可以看出，其实 pickle 并不直接调用上面的几个函数。事实上，这几个函数是复制协议的一部分，它们实现了 @ref{2d7,,__reduce__()} 这一特殊接口。复制协议提供了统一的接口，用于在封存或复制对象的过程中取得所需数据。@footnote{@w{(4)} 
@ref{25,,copy} 模块使用这一协议实现浅层 (shallow) 和深层 (deep) 复制操作。
}

尽管这个协议功能很强，但是直接在类中实现 @ref{2d7,,__reduce__()} 接口容易产生错误。因此，设计类时应当尽可能的使用高级接口（比如 @ref{1e69,,__getnewargs_ex__()}、@ref{ecd,,__getstate__()} 和 @ref{2d8,,__setstate__()}）。后面仍然可以看到直接实现 @ref{2d7,,__reduce__()} 接口的状况，可能别无他法，可能为了获得更好的性能，或者两者皆有之。

@geindex __reduce__() (object 方法)
@anchor{library/pickle object __reduce__}@anchor{2d7}
@deffn {方法} object.__reduce__ ()

该接口当前定义如下。@ref{2d7,,__reduce__()} 方法不带任何参数，并且应返回字符串或最好返回一个元组（返回的对象通常称为“reduce 值”）。

如果返回字符串，该字符串会被当做一个全局变量的名称。它应该是对象相对于其模块的本地名称，pickle 模块会搜索模块命名空间来确定对象所属的模块。这种行为常在单例模式使用。

如果返回的是元组，则应当包含 2 到 6 个元素，可选元素可以省略或设置为 @code{None}。每个元素代表的意义如下：

@c XXX Mention __newobj__ special-case?


@itemize *

@item 
一个可调用对象，该对象会在创建对象的最初版本时调用。

@item 
可调用对象的参数，是一个元组。如果可调用对象不接受参数，必须提供一个空元组。

@item 
可选元素，用于表示对象的状态，将被传给前述的 @ref{2d8,,__setstate__()} 方法。 如果对象没有此方法，则这个元素必须是字典类型，并会被添加至 @ref{5fe,,__dict__} 属性中。

@item 
可选元素，一个返回连续项的迭代器（而不是序列）。这些项会被 @code{obj.append(item)} 逐个加入对象，或被 @code{obj.extend(list_of_items)} 批量加入对象。这个元素主要用于 list 的子类，也可以用于那些正确实现了 @code{append()} 和 @code{extend()} 方法的类。（具体是使用 @code{append()} 还是 @code{extend()} 取决于 pickle 协议版本以及待插入元素的项数，所以这两个方法必须同时被类支持。）

@item 
可选元素，一个返回连续键值对的迭代器（而不是序列）。这些键值对将会以 @code{obj[key] = value} 的方式存储于对象中。该元素主要用于 dict 子类，也可以用于那些实现了 @ref{d32,,__setitem__()} 的类。

@item 
可选元素，一个带有 @code{(obj, state)} 签名的可调用对象。该可调用对象允许用户以编程方式控制特定对象的状态更新行为，而不是使用 @code{obj} 的静态 @ref{2d8,,__setstate__()} 方法。如果此处不是 @code{None}，则此可调用对象的优先级高于 @code{obj} 的 @ref{2d8,,__setstate__()}。


3.8 新版功能: 新增了元组的第 6 项，可选元素 @code{(obj, state)}。

@end itemize
@end deffn

@geindex __reduce_ex__() (object 方法)
@anchor{library/pickle object __reduce_ex__}@anchor{1b8f}
@deffn {方法} object.__reduce_ex__ (protocol)

作为替代选项，也可以实现 @ref{1b8f,,__reduce_ex__()} 方法。 此方法的唯一不同之处在于它应接受一个整型参数用于指定协议版本。 如果定义了这个函数，则会覆盖 @ref{2d7,,__reduce__()} 的行为。 此外，@ref{2d7,,__reduce__()} 方法会自动成为扩展版方法的同义词。 这个函数主要用于为以前的 Python 版本提供向后兼容的 reduce 值。
@end deffn

@menu
* 持久化外部对象:: 
* Dispatch 表:: 
* 处理有状态的对象:: 

@end menu

@node 持久化外部对象,Dispatch 表,,封存类实例
@anchor{library/pickle persistence-of-external-objects}@anchor{1e6b}@anchor{library/pickle pickle-persistent}@anchor{1e5c}
@subsubsection 持久化外部对象


@geindex persistent_id (pickle protocol)
@geindex persistent_load (pickle protocol)

为了获取对象持久化的利益， @ref{ca,,pickle} 模块支持引用已封存数据流之外的对象。 这样的对象是通过一个持久化 ID 来引用的，它应当是一个由字母数字类字符组成的字符串 (对于第 0 版协议) @footnote{@w{(5)} 
对于字符数字类字符的限制是由于持久化 ID 在协议版本 0 中是由分行符来分隔的。 因此如果持久化 ID 中出现了任何形式的分行符，封存结果就将变得无法读取。
} 或是一个任意对象 (用于任意新版协议)。

@ref{ca,,pickle} 模块不提供对持久化 ID 的解析工作，它将解析工作分配给用户定义的方法，分别是 pickler 中的 @ref{1e5a,,persistent_id()} 方法和 unpickler 中的 @ref{1e5b,,persistent_load()} 方法。

要通过持久化 ID 将外部对象封存，必须在 pickler 中实现 @ref{1e5a,,persistent_id()} 方法，该方法接受需要被封存的对象作为参数，返回一个 @code{None} 或返回该对象的持久化 ID。如果返回 @code{None}，该对象会被按照默认方式封存为数据流。如果返回字符串形式的持久化 ID，则会封存这个字符串并加上一个标记，这样 unpickler 才能将其识别为持久化 ID。

要解封外部对象，Unpickler 必须实现 @ref{1e5b,,persistent_load()} 方法，接受一个持久化 ID 对象作为参数并返回一个引用的对象。

下面是一个全面的例子，展示了如何使用持久化 ID 来封存外部对象。

@example
# Simple example presenting how persistent ID can be used to pickle
# external objects by reference.

import pickle
import sqlite3
from collections import namedtuple

# Simple class representing a record in our database.
MemoRecord = namedtuple("MemoRecord", "key, task")

class DBPickler(pickle.Pickler):

    def persistent_id(self, obj):
        # Instead of pickling MemoRecord as a regular class instance, we emit a
        # persistent ID.
        if isinstance(obj, MemoRecord):
            # Here, our persistent ID is simply a tuple, containing a tag and a
            # key, which refers to a specific record in the database.
            return ("MemoRecord", obj.key)
        else:
            # If obj does not have a persistent ID, return None. This means obj
            # needs to be pickled as usual.
            return None


class DBUnpickler(pickle.Unpickler):

    def __init__(self, file, connection):
        super().__init__(file)
        self.connection = connection

    def persistent_load(self, pid):
        # This method is invoked whenever a persistent ID is encountered.
        # Here, pid is the tuple returned by DBPickler.
        cursor = self.connection.cursor()
        type_tag, key_id = pid
        if type_tag == "MemoRecord":
            # Fetch the referenced record from the database and return it.
            cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
            key, task = cursor.fetchone()
            return MemoRecord(key, task)
        else:
            # Always raises an error if you cannot return the correct object.
            # Otherwise, the unpickler will think None is the object referenced
            # by the persistent ID.
            raise pickle.UnpicklingError("unsupported persistent object")


def main():
    import io
    import pprint

    # Initialize and populate our database.
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
    tasks = (
        'give food to fish',
        'prepare group meeting',
        'fight with a zebra',
        )
    for task in tasks:
        cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))

    # Fetch the records to be pickled.
    cursor.execute("SELECT * FROM memos")
    memos = [MemoRecord(key, task) for key, task in cursor]
    # Save the records using our custom DBPickler.
    file = io.BytesIO()
    DBPickler(file).dump(memos)

    print("Pickled records:")
    pprint.pprint(memos)

    # Update a record, just for good measure.
    cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")

    # Load the records from the pickle data stream.
    file.seek(0)
    memos = DBUnpickler(file, conn).load()

    print("Unpickled records:")
    pprint.pprint(memos)


if __name__ == '__main__':
    main()
@end example

@node Dispatch 表,处理有状态的对象,持久化外部对象,封存类实例
@anchor{library/pickle dispatch-tables}@anchor{1e6c}@anchor{library/pickle pickle-dispatch}@anchor{1e5e}
@subsubsection Dispatch 表


如果想对某些类进行自定义封存，而又不想在类中增加用于封存的代码，就可以创建带有特殊 dispatch 表的 pickler。

在 @ref{26,,copyreg} 模块的 @code{copyreg.dispatch_table} 中定义了全局 dispatch 表。因此，可以使用 @code{copyreg.dispatch_table} 修改后的副本作为自有 dispatch 表。

例如

@example
f = io.BytesIO()
p = pickle.Pickler(f)
p.dispatch_table = copyreg.dispatch_table.copy()
p.dispatch_table[SomeClass] = reduce_SomeClass
@end example

创建了一个带有自有 dispatch 表的 @ref{342,,pickle.Pickler} 实例，它可以对 @code{SomeClass} 类进行特殊处理。另外，下列代码

@example
class MyPickler(pickle.Pickler):
    dispatch_table = copyreg.dispatch_table.copy()
    dispatch_table[SomeClass] = reduce_SomeClass
f = io.BytesIO()
p = MyPickler(f)
@end example

完成同样的操作，但所有 @code{MyPickler} 的实例都会共享一个私有分发表。 另一方面，代码

@example
copyreg.pickle(SomeClass, reduce_SomeClass)
f = io.BytesIO()
p = pickle.Pickler(f)
@end example

会修改由 @ref{26,,copyreg} 模块的所有用户共享的全局分发表。

@node 处理有状态的对象,,Dispatch 表,封存类实例
@anchor{library/pickle handling-stateful-objects}@anchor{1e6d}@anchor{library/pickle pickle-state}@anchor{1e6a}
@subsubsection 处理有状态的对象


@geindex __getstate__() (copy protocol)
@geindex __setstate__() (copy protocol)

下面的示例展示了如何修改类在封存时的行为。其中 @code{TextReader} 类打开了一个文本文件，每次调用其 @code{readline()} 方法则返回行号和该行的字符。 在封存这个 @code{TextReader} 的实例时，@emph{除了} 文件对象，其他属性都会被保存。 当解封实例时，需要重新打开文件，然后从上次的位置开始继续读取。实现这些功能需要实现 @ref{2d8,,__setstate__()} 和 @ref{ecd,,__getstate__()} 方法。

@example
class TextReader:
    """Print and number lines in a text file."""

    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename)
        self.lineno = 0

    def readline(self):
        self.lineno += 1
        line = self.file.readline()
        if not line:
            return None
        if line.endswith('\n'):
            line = line[:-1]
        return "%i: %s" % (self.lineno, line)

    def __getstate__(self):
        # Copy the object's state from self.__dict__ which contains
        # all our instance attributes. Always use the dict.copy()
        # method to avoid modifying the original state.
        state = self.__dict__.copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        self.__dict__.update(state)
        # Restore the previously opened file's state. To do so, we need to
        # reopen it and read from it until the line count is restored.
        file = open(self.filename)
        for _ in range(self.lineno):
            file.readline()
        # Finally, save the file.
        self.file = file
@end example

使用方法如下所示：

@example
>>> reader = TextReader("hello.txt")
>>> reader.readline()
'1: Hello world!'
>>> reader.readline()
'2: I am line number two.'
>>> new_reader = pickle.loads(pickle.dumps(reader))
>>> new_reader.readline()
'3: Goodbye!'
@end example

@node 类型，函数和其他对象的自定义归约,外部缓冲区,封存类实例,pickle --- Python 对象序列化
@anchor{library/pickle custom-reduction-for-types-functions-and-other-objects}@anchor{1e6e}@anchor{library/pickle reducer-override}@anchor{1e5f}
@subsubsection 类型，函数和其他对象的自定义归约



3.8 新版功能.


有时，@ref{b4d,,dispatch_table} 可能不够灵活。 特别是当我们想要基于对象类型以外的其他规则来对封存进行定制，或是当我们想要对函数和类的封存进行定制的时候。

对于那些情况，可能要基于 @ref{342,,Pickler} 类进行子类化并实现 @ref{343,,reducer_override()} 方法。 此方法可返回任意的归约元组 (参见 @ref{2d7,,__reduce__()})。 它也可以选择返回 @code{NotImplemented} 来回退到传统行为。

如果同时定义了 @ref{b4d,,dispatch_table} 和 @ref{343,,reducer_override()}，则 @ref{343,,reducer_override()} 方法具有优先权。

@cartouche
@quotation 注解 
出于性能理由，可能不会为以下对象调用 @ref{343,,reducer_override()}: @code{None}, @code{True}, @code{False}, 以及 @ref{205,,int}, @ref{1fe,,float}, @ref{172,,bytes}, @ref{206,,str}, @ref{164,,dict}, @ref{1f7,,set}, @ref{1f8,,frozenset}, @ref{1f9,,list} 和 @ref{1a2,,tuple} 的具体实例。
@end quotation
@end cartouche

以下是一个简单的例子，其中我们允许封存并重新构建一个给定的类:

@example
import io
import pickle

class MyClass:
    my_attribute = 1

class MyPickler(pickle.Pickler):
    def reducer_override(self, obj):
        """Custom reducer for MyClass."""
        if getattr(obj, "__name__", None) == "MyClass":
            return type, (obj.__name__, obj.__bases__,
                          @{'my_attribute': obj.my_attribute@})
        else:
            # For any other object, fallback to usual reduction
            return NotImplemented

f = io.BytesIO()
p = MyPickler(f)
p.dump(MyClass)

del MyClass

unpickled_class = pickle.loads(f.getvalue())

assert isinstance(unpickled_class, type)
assert unpickled_class.__name__ == "MyClass"
assert unpickled_class.my_attribute == 1
@end example

@node 外部缓冲区,限制全局变量,类型，函数和其他对象的自定义归约,pickle --- Python 对象序列化
@anchor{library/pickle out-of-band-buffers}@anchor{1e6f}@anchor{library/pickle pickle-oob}@anchor{1e59}
@subsubsection 外部缓冲区



3.8 新版功能.


在某些场景中，@ref{ca,,pickle} 模块会被用来传输海量的数据。 因此，最小化内存复制次数以保证性能和节省资源是很重要的。 但是 @ref{ca,,pickle} 模块的正常运作会将图类对象结构转换为字节序列流，因此在本质上就要从封存流中来回复制数据。

如果 @emph{provider} (待传输对象类型的实现) 和 @emph{consumer} (通信系统的实现) 都支持 pickle 第 5 版或更高版本所提供的外部传输功能，则此约束可以被撤销。

@menu
* 提供方 API:: 
* 使用方 API:: 
* 示例: 示例<7>. 

@end menu

@node 提供方 API,使用方 API,,外部缓冲区
@anchor{library/pickle provider-api}@anchor{1e70}
@subsubsection 提供方 API


大的待封存数据对象必须实现协议 5 及以上版本专属的 @ref{1b8f,,__reduce_ex__()} 方法，该方法将为任意大的数据返回一个 @ref{f6d,,PickleBuffer} 实例（而不是 @ref{172,,bytes} 对象等）。

@ref{f6d,,PickleBuffer} 对象会 @emph{表明} 底层缓冲区可被用于外部数据传输。 那些对象仍将保持与 @ref{ca,,pickle} 模块的正常用法兼容。 但是，使用方也可以选择告知 @ref{ca,,pickle} 它们将自行处理那些缓冲区。

@node 使用方 API,示例<7>,提供方 API,外部缓冲区
@anchor{library/pickle consumer-api}@anchor{1e71}
@subsubsection 使用方 API


当序列化一个对象图时，通信系统可以启用对所生成 @ref{f6d,,PickleBuffer} 对象的定制处理。

发送端需要传递 @emph{buffer_callback} 参数到 @ref{342,,Pickler} (或是到 @ref{1e53,,dump()} 或 @ref{ecb,,dumps()} 函数)，该回调函数将在封存对象图时附带每个所生成的 @ref{f6d,,PickleBuffer} 被调用。 由 @emph{buffer_callback} 所累积的缓冲区的数据将不会被拷贝到 pickle 流，而是仅插入一个简单的标记。

接收端需要传递 @emph{buffers} 参数到 @ref{1e52,,Unpickler} (或是到 @ref{6c3,,load()} 或 @ref{6c4,,loads()} 函数)，其值是一个由缓冲区组成的可迭代对象，它会被传递给 @emph{buffer_callback}。 该可迭代对象应当按其被传递给 @emph{buffer_callback} 时的顺序产生缓冲区。 这些缓冲区将提供对象重构造器所期望的数据，对这些数据的封存产生了原本的 @ref{f6d,,PickleBuffer} 对象。

在发送端和接受端之间，通信系统可以自由地实现它自己用于外部缓冲区的传输机制。 潜在的优化包括使用共享内存或基于特定数据类型的压缩等。

@node 示例<7>,,使用方 API,外部缓冲区
@anchor{library/pickle example}@anchor{1e72}
@subsubsection 示例


下面是一个小例子，在其中我们实现了一个 @ref{173,,bytearray} 的子类，能够用于外部缓冲区封存:

@example
class ZeroCopyByteArray(bytearray):

    def __reduce_ex__(self, protocol):
        if protocol >= 5:
            return type(self)._reconstruct, (PickleBuffer(self),), None
        else:
            # PickleBuffer is forbidden with pickle protocols <= 4.
            return type(self)._reconstruct, (bytearray(self),)

    @@classmethod
    def _reconstruct(cls, obj):
        with memoryview(obj) as m:
            # Get a handle over the original buffer object
            obj = m.obj
            if type(obj) is cls:
                # Original buffer object is a ZeroCopyByteArray, return it
                # as-is.
                return obj
            else:
                return cls(obj)
@end example

重构造器 (@code{_reconstruct} 类方法) 会在缓冲区的提供对象具有正确类型时返回该对象。 在此小示例中这是模拟零拷贝行为的便捷方式。

在使用方，我们可以按通常方式封存那些对象，它们在反序列化时将提供原始对象的一个副本:

@example
b = ZeroCopyByteArray(b"abc")
data = pickle.dumps(b, protocol=5)
new_b = pickle.loads(data)
print(b == new_b)  # True
print(b is new_b)  # False: a copy was made
@end example

但是如果我们传入 @emph{buffer_callback} 然后在反序列化时给回累积的缓冲区，我们就能够取回原始对象:

@example
b = ZeroCopyByteArray(b"abc")
buffers = []
data = pickle.dumps(b, protocol=5, buffer_callback=buffers.append)
new_b = pickle.loads(data, buffers=buffers)
print(b == new_b)  # True
print(b is new_b)  # True: no copy was made
@end example

这个例子受限于 @ref{173,,bytearray} 会自行分配内存这一事实：你无法基于另一个对象的内存创建 @ref{173,,bytearray} 的实例。 但是，第三方数据类型例如 NumPy 数组则没有这种限制，允许在单独进程或系统间传输时使用零拷贝的封存（或是尽可能少地拷贝） 。


@subsubheading 参见


@geindex Python 提高建议; PEP 574
PEP 574@footnote{https://www.python.org/dev/peps/pep-0574} -- 带有外部数据缓冲区的 pickle 协议 5


@node 限制全局变量,性能<2>,外部缓冲区,pickle --- Python 对象序列化
@anchor{library/pickle pickle-restrict}@anchor{1e64}@anchor{library/pickle restricting-globals}@anchor{1e73}
@subsubsection 限制全局变量


@geindex find_class() (pickle protocol)

默认情况下，解封将会导入在 pickle 数据中找到的任何类或函数。 对于许多应用来说，此行为是不可接受的，因为它会允许解封器导入并发起调用任意代码。 只须考虑当这个手工构建的 pickle 数据流被加载时会做什么:

@example
>>> import pickle
>>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
hello world
0
@end example

在这个例子里，解封器导入 @ref{e8e,,os.system()} 函数然后应用字符串参数 "echo hello world"。 虽然这个例子不具攻击性，但是不难想象别人能够通过此方式对你的系统造成损害。

出于这样的理由，你可能会希望通过定制 @ref{1e63,,Unpickler.find_class()} 来控制要解封的对象。 与其名称所提示的不同，@ref{1e63,,Unpickler.find_class()} 会在执行对任何全局对象（例如一个类或一个函数）的请求时被调用。 因此可以完全禁止全局对象或是将它们限制在一个安全的子集中。

下面的例子是一个解封器，它只允许某一些安全的来自 @ref{12,,builtins} 模块的类被加载:

@example
import builtins
import io
import pickle

safe_builtins = @{
    'range',
    'complex',
    'set',
    'frozenset',
    'slice',
@}

class RestrictedUnpickler(pickle.Unpickler):

    def find_class(self, module, name):
        # Only allow safe classes from builtins.
        if module == "builtins" and name in safe_builtins:
            return getattr(builtins, name)
        # Forbid everything else.
        raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                     (module, name))

def restricted_loads(s):
    """Helper function analogous to pickle.loads()."""
    return RestrictedUnpickler(io.BytesIO(s)).load()
@end example

我们这个解封器完成其功能的一个示例用法:

@example
>>> restricted_loads(pickle.dumps([1, 2, range(15)]))
[1, 2, range(0, 15)]
>>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'os.system' is forbidden
>>> restricted_loads(b'cbuiltins\neval\n'
...                  b'(S\'getattr(__import__("os"), "system")'
...                  b'("echo hello world")\'\ntR.')
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'builtins.eval' is forbidden
@end example

@c XXX Add note about how extension codes could evade our protection
@c mechanism (e.g. cached classes do not invokes find_class()).

正如我们这个例子所显示的，对于允许解封的对象你必须要保持谨慎。 因此如果要保证安全，你可以考虑其他选择例如 @ref{148,,xmlrpc.client} 中的编组 API 或是第三方解决方案。

@node 性能<2>,示例<8>,限制全局变量,pickle --- Python 对象序列化
@anchor{library/pickle performance}@anchor{1e74}
@subsubsection 性能


较新版本的 pickle 协议（第 2 版或更高）具有针对某些常见特性和内置类型的高效二进制编码格式。 此外，@ref{ca,,pickle} 模块还拥有一个以 C 编写的透明优化器。

@node 示例<8>,,性能<2>,pickle --- Python 对象序列化
@anchor{library/pickle examples}@anchor{1e75}@anchor{library/pickle pickle-example}@anchor{1e76}
@subsubsection 示例


对于最简单的代码，请使用 @ref{1e53,,dump()} 和 @ref{6c3,,load()} 函数。

@example
import pickle

# An arbitrary collection of objects supported by pickle.
data = @{
    'a': [1, 2.0, 3+4j],
    'b': ("character string", b"byte string"),
    'c': @{None, True, False@}
@}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
@end example

以下示例读取之前封存的数据。

@example
import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)
@end example

@c XXX: Add examples showing how to optimize pickles for size (like using

@c pickletools.optimize() or the gzip module).


@subsubheading 参见



@table @asis

@item 模块 @ref{26,,copyreg}

为扩展类型提供 pickle 接口所需的构造函数。

@item 模块 @ref{cb,,pickletools}

用于处理和分析已封存数据的工具。

@item 模块 @ref{e7,,shelve}

带索引的数据库，用于存放对象，使用了 @ref{ca,,pickle} 模块。

@item 模块 @ref{25,,copy}

浅层 (shallow) 和深层 (deep) 复制对象操作

@item 模块 @ref{b0,,marshal}

高效地序列化内置类型的数据。
@end table


@node copyreg --- 注册配合 pickle 模块使用的函数,shelve --- Python 对象持久化,pickle --- Python 对象序列化,数据持久化
@anchor{library/copyreg doc}@anchor{1e77}@anchor{library/copyreg copyreg-register-pickle-support-functions}@anchor{1e78}@anchor{library/copyreg module-copyreg}@anchor{26}
@subsection @code{copyreg} --- 注册配合 @code{pickle} 模块使用的函数


@geindex copyreg (模块)

@strong{源代码:} Lib/copyreg.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/copyreg.py}

@geindex 模块; pickle
@geindex 模块; copy


__________________________________________________________________


@ref{26,,copyreg} 模块提供了可在封存特定对象时使用的一种定义函数方式。 @ref{ca,,pickle} 和 @ref{25,,copy} 模块会在封存/拷贝特定对象时使用这些函数。 此模块提供了非类对象构造器的相关配置信息。 这样的构造器可以是工厂函数或类实例。

@geindex constructor() (在 copyreg 模块中)
@anchor{library/copyreg copyreg constructor}@anchor{1e79}
@deffn {函数} copyreg.constructor (object)

将 @emph{object} 声明为一个有效的构造器。 如果 @emph{object} 是不可调用的（因而不是一个有效的构造器）则会引发 @ref{1ff,,TypeError}。
@end deffn

@geindex pickle() (在 copyreg 模块中)
@anchor{library/copyreg copyreg pickle}@anchor{1e5d}
@deffn {函数} copyreg.pickle (type, function, constructor=None)

声明该 @emph{function} 应当被用作 @emph{type} 类型对象的“归约函数”。 @emph{function} 应当返回字符串或包含两到三个元素的元组。

如果提供了可选的 @emph{constructor} 形参，它应当是一个可被用于重建相应对象的可调用对象，在调用该对象时要附带在执行封存操作时由 @emph{function} 所返回的参数所组成的元组。 如果 @emph{constructor} 不是可调用对象则将引发 @ref{1ff,,TypeError}。

请查看 @ref{ca,,pickle} 模块了解 @emph{function} 和 @emph{constructor} 所要求的接口的详情。 请注意一个 pickler 对象或 @ref{342,,pickle.Pickler} 的子类的 @ref{b4d,,dispatch_table} 属性也可以被用来声明归约函数。
@end deffn

@menu
* 示例: 示例<9>. 

@end menu

@node 示例<9>,,,copyreg --- 注册配合 pickle 模块使用的函数
@anchor{library/copyreg example}@anchor{1e7a}
@subsubsection 示例


以下示例将会显示如何注册一个封存函数，以及如何来使用它：

@example
>>> import copyreg, copy, pickle
>>> class C:
...     def __init__(self, a):
...         self.a = a
...
>>> def pickle_c(c):
...     print("pickling a C instance...")
...     return C, (c.a,)
...
>>> copyreg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)  
pickling a C instance...
>>> p = pickle.dumps(c)  
pickling a C instance...
@end example

@node shelve --- Python 对象持久化,marshal --- 内部 Python 对象序列化,copyreg --- 注册配合 pickle 模块使用的函数,数据持久化
@anchor{library/shelve doc}@anchor{1e7b}@anchor{library/shelve module-shelve}@anchor{e7}@anchor{library/shelve shelve-python-object-persistence}@anchor{1e7c}
@subsection @code{shelve} --- Python 对象持久化


@geindex shelve (模块)

@strong{源代码:} Lib/shelve.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/shelve.py}

@geindex 模块; pickle


__________________________________________________________________


"Shelf" 是一种持久化的类似字典的对象。 与 "dbm" 数据库的区别在于 Shelf 中的值（不是键！）实际上可以为任意 Python 对象 --- 即 @ref{ca,,pickle} 模块能够处理的任何东西。 这包括大部分类实例、递归数据类型，以及包含大量共享子对象的对象。 键则为普通的字符串。

@geindex open() (在 shelve 模块中)
@anchor{library/shelve shelve open}@anchor{1e7d}
@deffn {函数} shelve.open (filename, flag='c', protocol=None, writeback=False)

打开一个持久化字典。 filename 指定下层数据库的基准文件名。 作为附带效果，会为 filename 添加一个扩展名并且可能创建更多的文件。 默认情况下，下层数据库会以读写模式打开。 可选的 @emph{flag} 形参具有与 @ref{927,,dbm.open()} @emph{flag} 形参相同的含义。

默认会使用第 3 版 pickle 协议来序列化值。  pickle 协议版本可通过 @emph{protocol} 形参来指定。

由于 Python 语义的限制，Shelf 对象无法确定一个可变的持久化字典条目在何时被修改。 默认情况下 @emph{只有} 在被修改对象再赋值给 shelf 时才会写入该对象 (参见 @ref{1e7e,,示例})。 如果可选的 @emph{writeback} 形参设为 @code{True}，则所有被访问的条目都将在内存中被缓存，并会在 @ref{1e7f,,sync()} 和 @ref{1e80,,close()} 时被写入；这可以使得对持久化字典中可变条目的修改更方便，但是如果访问的条目很多，这会消耗大量内存作为缓存，并会使得关闭操作变得非常缓慢，因为所有被访问的条目都需要写回到字典（无法确定被访问的条目中哪个是可变的，也无法确定哪个被实际修改了）。

@cartouche
@quotation 注解 
请不要依赖于 Shelf 的自动关闭功能；当你不再需要时应当总是显式地调用 @ref{1e80,,close()}，或者使用 @ref{1e7d,,shelve.open()} 作为上下文管理器:

@example
with shelve.open('spam') as db:
    db['eggs'] = 'eggs'
@end example
@end quotation
@end cartouche
@end deffn
@anchor{library/shelve shelve-security}@anchor{1e81}
@cartouche
@quotation 警告 
由于 @ref{e7,,shelve} 模块需要 @ref{ca,,pickle} 的支持，因此从不可靠的来源载入 shelf 是不安全的。 与 pickle 一样，载入 Shelf 时可以执行任意代码。
@end quotation
@end cartouche

Shelf 对象支持字典所支持的大多数方法和运算（除了拷贝、构造器以及 @code{|} 和 @code{|=} 运算符）。 这样就能方便地将基于字典的脚本转换为要求持久化存储的脚本。

额外支持的两个方法：

@geindex sync() (shelve.Shelf 方法)
@anchor{library/shelve shelve Shelf sync}@anchor{1e7f}
@deffn {方法} Shelf.sync ()

如果 Shelf 打开时将 @emph{writeback} 设为 @ref{59c,,True} 则写回缓存中的所有条目。 如果可行还会清空缓存并将持久化字典同步到磁盘。 此方法会在使用 @ref{1e80,,close()} 关闭 Shelf 时自动被调用。
@end deffn

@geindex close() (shelve.Shelf 方法)
@anchor{library/shelve shelve Shelf close}@anchor{1e80}
@deffn {方法} Shelf.close ()

同步并关闭持久化 @emph{dict} 对象。 对已关闭 Shelf 的操作将失败并引发 @ref{16d,,ValueError}。
@end deffn


@subsubheading 参见


持久化字典方案@footnote{https://code.activestate.com/recipes/576642/}，使用了广泛支持的存储格式并具有原生字典的速度。


@menu
* 限制:: 
* 示例: 示例<10>. 

@end menu

@node 限制,示例<10>,,shelve --- Python 对象持久化
@anchor{library/shelve restrictions}@anchor{1e82}
@subsubsection 限制


@quotation

@geindex 模块; dbm.ndbm
@geindex 模块; dbm.gnu
@end quotation


@itemize *

@item 
可选择使用哪种数据库包 (例如 @ref{34,,dbm.ndbm} 或 @ref{33,,dbm.gnu}) 取决于支持哪种接口。 因此使用 @ref{31,,dbm} 直接打开数据库是不安全的。 如果使用了 @ref{31,,dbm}，数据库同样会（不幸地）受限于它 --- 这意味着存储在数据库中的（封存形式的）对象尺寸应当较小，并且在少数情况下键冲突有可能导致数据库拒绝更新。

@item 
@ref{e7,,shelve} 模块不支持对 Shelf 对象的 @emph{并发} 读/写访问。 （多个同时读取访问则是安全的。） 当一个程序打开一个 shelve 对象来写入时，不应再有其他程序同时打开它来读取或写入。 Unix 文件锁定可被用来解决此问题，但这在不同 Unix 版本上会存在差异，并且需要有关所用数据库实现的细节知识。
@end itemize

@geindex Shelf (shelve 中的类)
@anchor{library/shelve shelve Shelf}@anchor{9a0}
@deffn {类} shelve.Shelf (dict, protocol=None, writeback=False, keyencoding='utf-8')

@ref{ad7,,collections.abc.MutableMapping} 的一个子类，它会将封存的值保存在 @emph{dict} 对象中。

默认会使用第 3 版 pickle 协议来序列化值。 pickle 协议版本可通过 @emph{protocol} 形参来指定。 请参阅 @ref{ca,,pickle} 文档来查看 pickle 协议的相关讨论。

如果 @emph{writeback} 形参为 @code{True}，对象将为所有访问过的条目保留缓存并在同步和关闭时将它们写回到 @emph{dict}。 这允许对可变的条目执行自然操作，但是会消耗更多内存并让同步和关闭花费更长时间。

@emph{keyencoding} 形参是在下层字典被使用之前用于编码键的编码格式。

@ref{9a0,,Shelf} 对象还可以被用作上下文管理器，在这种情况下它将在 @ref{7e4,,with} 语句块结束时自动被关闭。


在 3.2 版更改: 添加了 @emph{keyencoding} 形参；之前，键总是使用 UTF-8 编码。



在 3.4 版更改: 添加了上下文管理器支持

@end deffn

@geindex BsdDbShelf (shelve 中的类)
@anchor{library/shelve shelve BsdDbShelf}@anchor{1855}
@deffn {类} shelve.BsdDbShelf (dict, protocol=None, writeback=False, keyencoding='utf-8')

@ref{9a0,,Shelf} 的一个子类，将 @code{first()}, @code{next()}, @code{previous()}, @code{last()} 和 @code{set_location()} 对外公开，在来自 pybsddb@footnote{https://www.jcea.es/programacion/pybsddb.htm} 的第三方 @code{bsddb} 模块中可用，但在其他数据库模块中不可用。 传给构造器的 @emph{dict} 对象必须支持这些方法。 这通常是通过调用 @code{bsddb.hashopen()}, @code{bsddb.btopen()} 或 @code{bsddb.rnopen()} 之一来完成的。  可选的 @emph{protocol}, @emph{writeback} 和 @emph{keyencoding} 形参具有与 @ref{9a0,,Shelf} 类相同的含义。
@end deffn

@geindex DbfilenameShelf (shelve 中的类)
@anchor{library/shelve shelve DbfilenameShelf}@anchor{1856}
@deffn {类} shelve.DbfilenameShelf (filename, flag='c', protocol=None, writeback=False)

@ref{9a0,,Shelf} 的一个子类，它接受一个 @emph{filename} 而非字典类对象。 下层文件将使用 @ref{927,,dbm.open()} 来打开。 默认情况下，文件将以读写模式打开。 可选的 @emph{flag} 形参具有与 @ref{1e7d,,open()} 函数相同的含义。 可选的 @emph{protocol} 和 @emph{writeback} 形参具有与 @ref{9a0,,Shelf} 类相同的含义。
@end deffn

@node 示例<10>,,限制,shelve --- Python 对象持久化
@anchor{library/shelve example}@anchor{1e83}@anchor{library/shelve shelve-example}@anchor{1e7e}
@subsubsection 示例


对接口的总结如下 (@code{key} 为字符串，@code{data} 为任意对象):

@example
import shelve

d = shelve.open(filename)  # open -- file may get suffix added by low-level
                           # library

d[key] = data              # store data at key (overwrites old data if
                           # using an existing key)
data = d[key]              # retrieve a COPY of data at key (raise KeyError
                           # if no such key)
del d[key]                 # delete data stored at key (raises KeyError
                           # if no such key)

flag = key in d            # true if the key exists
klist = list(d.keys())     # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]        # this works as expected, but...
d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']             # extracts the copy
temp.append(5)             # mutates the copy
d['xx'] = temp             # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()                  # close it
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{31,,dbm}

@code{dbm} 风格数据库的泛型接口。

@item 模块 @ref{ca,,pickle}

@ref{e7,,shelve} 所使用的对象序列化。
@end table


@node marshal --- 内部 Python 对象序列化,dbm --- Unix "数据库" 接口,shelve --- Python 对象持久化,数据持久化
@anchor{library/marshal doc}@anchor{1e84}@anchor{library/marshal marshal-internal-python-object-serialization}@anchor{1e85}@anchor{library/marshal module-marshal}@anchor{b0}
@subsection @code{marshal} --- 内部 Python 对象序列化


@geindex marshal (模块)


__________________________________________________________________


此模块包含一此能以二进制格式来读写 Python 值的函数。 这种格式是 Python 专属的，但是独立于特定的机器架构（即你可以在一台 PC 上写入某个 Python 值，将文件传到一台 Sun 上并在那里读取它）。 这种格式的细节有意不带文档说明；它可能在不同 Python 版本中发生改变（但这种情况极少发生）。 @footnote{@w{(1)} 
此模块的名称来源于 Modula-3 (及其他语言) 的设计者所使用的术语，他们使用术语 "marshal" 来表示以自包含的形式传输数据。 严格地说，将数据从内部形式转换为外部形式 (例如用于 RPC 缓冲区) 称为 "marshal" 而其逆过程则称为 "unmarshal"。
}

@geindex 模块; pickle
@geindex 模块; shelve

这不是一个通用的“持久化”模块。 对于通用的持久化以及通过 RPC 调用传递 Python 对象，请参阅 @ref{ca,,pickle} 和 @ref{e7,,shelve} 等模块。 @ref{b0,,marshal} 模块主要是为了支持读写 @code{.pyc} 文件形式“伪编译”代码的 Python 模块。 因此，Python 维护者保留在必要时以不向下兼容的方式修改 marshal 格式的权利。 如果你要序列化和反序列化 Python 对象，请改用 @ref{ca,,pickle} 模块 -- 其执行效率相当，版本独立性有保证，并且 pickle 还支持比 marshal 更多样的对象类型。

@cartouche
@quotation 警告 
@ref{b0,,marshal} 模块对于错误或恶意构建的数据来说是不安全的。 永远不要 unmarshal 来自不受信任的或未经验证的来源的数据。
@end quotation
@end cartouche

@geindex object; code
@geindex code object

不是所有 Python 对象类型都受支持；一般来说，此模块只能写入和读取不依赖于特定 Python 调用的对象。 下列类型是受支持的：布尔值、整数、浮点数、复数、字符串、字节串、字节数组、元组、列表、集合、冻结集合、字典和代码对象，需要了解的一点是元组、列表、集合、冻结集合和字典只在其所包含的值也是这些值时才受支持。 单例对象 @ref{204,,None}, @ref{1770,,Ellipsis} and @ref{58a,,StopIteration} 也可以被 marshal 和 unmarshal。 对于 @emph{version} 低于 3 的格式，递归列表、集合和字典无法被写入（见下文）。

有些函数可以读/写文件，还有些函数可以操作字节类对象。

这个模块定义了以下函数：

@geindex dump() (在 marshal 模块中)
@anchor{library/marshal marshal dump}@anchor{1e86}
@deffn {函数} marshal.dump (value, file[, version])

向打开的文件写入值。 值必须为受支持的类型。 文件必须为可写的 @ref{140a,,binary file}。

如果值具有（或所包含的对象具有）不受支持的类型，则会引发 @ref{16d,,ValueError} --- 但是将向文件写入垃圾数据。 对象也将不能正确地通过 @ref{1174,,load()} 重新读取。

@emph{version} 参数指明 @code{dump} 应当使用的数据格式（见下文）。

引发一个 @ref{fec,,审计事件} @code{marshal.dumps}，附带参数 @code{value}, @code{version}。
@end deffn

@geindex load() (在 marshal 模块中)
@anchor{library/marshal marshal load}@anchor{1174}
@deffn {函数} marshal.load (file)

从打开的文件读取一个值并返回。 如果读不到有效的值（例如由于数据为不同 Python 版本的不兼容 marshal 格式），则会引发 @ref{d3c,,EOFError}, @ref{16d,,ValueError} 或 @ref{1ff,,TypeError}。 文件必须为可读的 @ref{140a,,binary file}。

引发一个 @ref{fec,,审计事件} @code{marshal.load}，没有附带参数。

@cartouche
@quotation 注解 
如果通过 @ref{1e86,,dump()} marshal 了一个包含不受支持类型的对象，@ref{1174,,load()} 将为不可 marshal 的类型替换 @code{None}。
@end quotation
@end cartouche


在 3.9.7 版更改: 使用此调用为每个代码对象引发一个 @code{code.__new__} 审计事件。 现在它会为整个载入操作引发单个 @code{marshal.load} 事件。

@end deffn

@geindex dumps() (在 marshal 模块中)
@anchor{library/marshal marshal dumps}@anchor{895}
@deffn {函数} marshal.dumps (value[, version])

返回将通过 @code{dump(value, file)} 被写入一个文件的字节串对象。 值必须属于受支持的类型。 如果值属于（或包含的对象属于）不受支持的类型则会引发 @ref{16d,,ValueError}。

@emph{version} 参数指明 @code{dumps} 应当使用的数据类型（见下文）。

引发一个 @ref{fec,,审计事件} @code{marshal.dumps}，附带参数 @code{value}, @code{version}。
@end deffn

@geindex loads() (在 marshal 模块中)
@anchor{library/marshal marshal loads}@anchor{1e87}
@deffn {函数} marshal.loads (bytes)

将 @ref{6e9,,bytes-like object} 转换为一个值。 如果找不到有效的值，则会引发 @ref{d3c,,EOFError}, @ref{16d,,ValueError} 或 @ref{1ff,,TypeError}。 输入的额外字节串会被忽略。

引发一个 @ref{fec,,审计事件} @code{marshal.loads}，附带参数 @code{bytes}。


在 3.9.7 版更改: 使用此调用为每个代码对象引发一个 @code{code.__new__} 审计事件。 现在它会为整个载入操作引发单个 @code{marshal.loads} 事件。

@end deffn

此外，还定义了以下常量：

@geindex version() (在 marshal 模块中)
@anchor{library/marshal marshal version}@anchor{1e88}
@deffn {数据} marshal.version

指明模块所使用的格式。 第 0 版为历史格式，第 1 版为共享固化的字符串，第 2 版对浮点数使用二进制格式。 第 3 版添加了对于对象实例化和递归的支持。 目前使用的为第 4 版。
@end deffn

@node dbm --- Unix "数据库" 接口,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,marshal --- 内部 Python 对象序列化,数据持久化
@anchor{library/dbm doc}@anchor{1e89}@anchor{library/dbm dbm-interfaces-to-unix-databases}@anchor{1e8a}@anchor{library/dbm module-dbm}@anchor{31}
@subsection @code{dbm} --- Unix "数据库" 接口


@geindex dbm (模块)

@strong{源代码:} Lib/dbm/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dbm/__init__.py}


__________________________________________________________________


@ref{31,,dbm} 是一种泛用接口，针对各种 DBM 数据库 --- 包括 @ref{33,,dbm.gnu} 或 @ref{34,,dbm.ndbm}。 如果未安装这些模块中的任何一种，则将使用 @ref{32,,dbm.dumb} 模块中慢速但简单的实现。 还有一个适用于 Oracle Berkeley DB 的 第三方接口@footnote{https://www.jcea.es/programacion/pybsddb.htm}。

@geindex error
@anchor{library/dbm dbm error}@anchor{1e8b}
@deffn {例外} dbm.error

一个元组，其中包含每个受支持的模块可引发的异常，另外还有一个名为 @ref{1e8b,,dbm.error} 的特殊异常作为第一项 --- 后者最在引发 @ref{1e8b,,dbm.error} 时被使用。
@end deffn

@geindex whichdb() (在 dbm 模块中)
@anchor{library/dbm dbm whichdb}@anchor{1e8c}
@deffn {函数} dbm.whichdb (filename)

此函数会猜测各种简单数据库模块中的哪一个是可用的 --- @ref{33,,dbm.gnu}, @ref{34,,dbm.ndbm} 还是 @ref{32,,dbm.dumb} --- 应该被用来打开给定的文件。

返回下列值中的一个：如果文件由于不可读或不存在而无法打开则返回 @code{None}；如果文件的格式无法猜测则返回空字符串 (@code{'@w{'}})；或是包含所需模块名称的字符串，例如 @code{'dbm.ndbm'} 或 @code{'dbm.gnu'}。
@end deffn

@geindex open() (在 dbm 模块中)
@anchor{library/dbm dbm open}@anchor{927}
@deffn {函数} dbm.open (file, flag='r', mode=0o666)

打开数据库文件 @emph{file} 并返回一个相应的对象。

如果数据库文件已存在，则使用 @ref{1e8c,,whichdb()} 函数来确定其类型和要使用的适当模块；如果文件不存在，则会使用上述可导入模块中的第一个。

可选的 @emph{flag} 参数可以是：


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'r'}

@tab

以只读方式打开现有数据库（默认）

@item

@code{'w'}

@tab

以读写方式打开现有数据库

@item

@code{'c'}

@tab

以读写方式打开数据库，如果不存在则创建它

@item

@code{'n'}

@tab

始终创建一个新的空数据库，以读写方式打开

@end multitable


可选的 @emph{mode} 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用。 其默认值为八进制数 @code{0o666} (并将被当前的 umask 所修改)。
@end deffn

@ref{927,,open()} 所返回的对象支持与字典相同的基本功能；可以存储、获取和删除键及其对应的值，并可使用 @ref{179,,in} 运算符和 @code{keys()} 方法，以及 @code{get()} 和 @code{setdefault()}。


在 3.2 版更改: 现在 @code{get()} 和 @code{setdefault()} 在所有数据库模块中均可用。



在 3.8 版更改: 从只读数据库中删除键将引发数据库模块专属的错误而不是 @ref{3f1,,KeyError}。


键和值总是被存储为字节串。 这意味着当使用字符串时它们会在被存储之前隐式地转换至默认编码格式。

这些对象也支持在 @ref{7e4,,with} 语句中使用，当语句结束时将自动关闭它们。


在 3.4 版更改: 向 @ref{927,,open()} 所返回的对象添加了上下文管理协议的原生支持。


以下示例记录了一些主机名和对应的标题，随后将数据库的内容打印出来。:

@example
import dbm

# Open database, creating it if necessary.
with dbm.open('cache', 'c') as db:

    # Record some values
    db[b'hello'] = b'there'
    db['www.python.org'] = 'Python Website'
    db['www.cnn.com'] = 'Cable News Network'

    # Note that the keys are considered bytes now.
    assert db[b'www.python.org'] == b'Python Website'
    # Notice how the value is now in bytes.
    assert db['www.cnn.com'] == b'Cable News Network'

    # Often-used methods of the dict interface work too.
    print(db.get('python.org', b'not present'))

    # Storing a non-string key or value will raise an exception (most
    # likely a TypeError).
    db['www.yahoo.com'] = 4

# db is automatically closed when leaving the with statement.
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{e7,,shelve}

存储非字符串数据的持久化模块。
@end table


以下部分描述了各个单独的子模块。

@menu
* dbm.gnu: dbm gnu --- GNU 对 dbm 的重解析. GNU 对 dbm 的重解析
* dbm.ndbm: dbm ndbm --- 基于 ndbm 的接口. 基于 ndbm 的接口
* dbm.dumb: dbm dumb --- 便携式 DBM 实现. 便携式 DBM 实现

@end menu

@node dbm gnu --- GNU 对 dbm 的重解析,dbm ndbm --- 基于 ndbm 的接口,,dbm --- Unix "数据库" 接口
@anchor{library/dbm dbm-gnu-gnu-s-reinterpretation-of-dbm}@anchor{1e8d}@anchor{library/dbm module-dbm gnu}@anchor{33}
@subsubsection @code{dbm.gnu} --- GNU 对 dbm 的重解析


@geindex dbm.gnu (模块)

@strong{源代码:} Lib/dbm/gnu.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dbm/gnu.py}


__________________________________________________________________


此模块与 @ref{31,,dbm} 模块很相似，但是改用 GNU 库 @code{gdbm} 来提供某些附加功能。 请注意由 @ref{33,,dbm.gnu} 与 @ref{34,,dbm.ndbm} 所创建的文件格式是不兼容的。

@ref{33,,dbm.gnu} 模块提供了对 GNU DBM 库的接口。 @code{dbm.gnu.gdbm} 对象的行为类似于映射（字典），区别在于其键和值总是会在存储之前被转换为字节串。 打印 @code{gdbm} 对象不会打印出键和值，并且 @code{items()} 和 @code{values()} 等方法也不受支持。

@geindex error
@anchor{library/dbm dbm gnu error}@anchor{3ef}
@deffn {例外} dbm.gnu.error

针对 @ref{33,,dbm.gnu} 专属错误例如 I/O 错误引发。 @ref{3f1,,KeyError} 的引发则针对一般映射错误例如指定了不正确的键。
@end deffn

@geindex open() (在 dbm.gnu 模块中)
@anchor{library/dbm dbm gnu open}@anchor{11b0}
@deffn {函数} dbm.gnu.open (filename[, flag[, mode]])

打开一个 @code{gdbm} 数据库并返回 @code{gdbm} 对象。 @emph{filename} 参数为数据库文件名称。

可选的 @emph{flag} 参数可以是：


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'r'}

@tab

以只读方式打开现有数据库（默认）

@item

@code{'w'}

@tab

以读写方式打开现有数据库

@item

@code{'c'}

@tab

以读写方式打开数据库，如果不存在则创建它

@item

@code{'n'}

@tab

始终创建一个新的空数据库，以读写方式打开

@end multitable


下列附加字符可被添加至旗标以控制数据库的打开方式：


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'f'}

@tab

以快速模式打开数据库。写入数据库将不会同步。

@item

@code{'s'}

@tab

同步模式。这将导致数据库的更改立即写入文件。

@item

@code{'u'}

@tab

不要锁定数据库。

@end multitable


不是所有旗标都可用于所有版本的 @code{gdbm}。 模块常量 @code{open_flags} 为包含受支持旗标字符的字符串。 如果指定了无效的旗标则会引发 @ref{3ef,,error}。

可选的 @emph{mode} 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用。 其默认值为八进制数 @code{0o666}。

除了与字典类似的方法，@code{gdbm} 对象还有以下方法：

@geindex firstkey() (dbm.gnu.gdbm 方法)
@anchor{library/dbm dbm gnu gdbm firstkey}@anchor{1e8e}
@deffn {方法} gdbm.firstkey ()

使用此方法和 @ref{1e8f,,nextkey()} 方法可以循环遍历数据库中的每个键。 遍历的顺序是按照 @code{gdbm} 的内部哈希值，而不会根据键的值排序。 此方法将返回起始键。
@end deffn

@geindex nextkey() (dbm.gnu.gdbm 方法)
@anchor{library/dbm dbm gnu gdbm nextkey}@anchor{1e8f}
@deffn {方法} gdbm.nextkey (key)

在遍历中返回 @emph{key} 之后的的下一个键。 以下代码将打印数据库 @code{db} 中的每个键，而不会在内存中创建一个包含所有键的列表:

@example
k = db.firstkey()
while k is not None:
    print(k)
    k = db.nextkey(k)
@end example
@end deffn

@geindex reorganize() (dbm.gnu.gdbm 方法)
@anchor{library/dbm dbm gnu gdbm reorganize}@anchor{1e90}
@deffn {方法} gdbm.reorganize ()

如果你进行了大量删除操作并且想要缩减 @code{gdbm} 文件所使用的空间，此例程将可重新组织数据库。 除非使用此重组功能否则 @code{gdbm} 对象不会缩减数据库文件大小；在其他情况下，被删除的文件空间将会保留并在添加新的 (键, 值) 对时被重用。
@end deffn

@geindex sync() (dbm.gnu.gdbm 方法)
@anchor{library/dbm dbm gnu gdbm sync}@anchor{1e91}
@deffn {方法} gdbm.sync ()

当以快速模式打开数据库时，此方法会将任何未写入数据强制写入磁盘。
@end deffn

@geindex close() (dbm.gnu.gdbm 方法)
@anchor{library/dbm dbm gnu gdbm close}@anchor{1e92}
@deffn {方法} gdbm.close ()

关闭 @code{gdbm} 数据库。
@end deffn
@end deffn

@node dbm ndbm --- 基于 ndbm 的接口,dbm dumb --- 便携式 DBM 实现,dbm gnu --- GNU 对 dbm 的重解析,dbm --- Unix "数据库" 接口
@anchor{library/dbm dbm-ndbm-interface-based-on-ndbm}@anchor{1e93}@anchor{library/dbm module-dbm ndbm}@anchor{34}
@subsubsection @code{dbm.ndbm} --- 基于 ndbm 的接口


@geindex dbm.ndbm (模块)

@strong{源代码:} Lib/dbm/ndbm.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dbm/ndbm.py}


__________________________________________________________________


@ref{34,,dbm.ndbm} 模块提供了对 Unix "(n)dbm" 库的接口。 Dbm 对象的行为类似于映射（字典），区别在于其键和值总是被存储为字节串。 打印 @code{dbm} 对象不会打印出键和值，并且 @code{items()} 和 @code{values()} 等方法也不受支持。

此模块可与 "经典classic" ndbm 接口或 GNU GDBM 兼容接口一同使用。 在 Unix 上，@code{configure} 脚本将尝试定位适当的头文件来简化此模块的构建。

@geindex error
@anchor{library/dbm dbm ndbm error}@anchor{3f0}
@deffn {例外} dbm.ndbm.error

针对 @ref{34,,dbm.ndbm} 专属错误例如 I/O 错误引发。 @ref{3f1,,KeyError} 的引发则针对一般映射错误例如指定了不正确的键。
@end deffn

@geindex library() (在 dbm.ndbm 模块中)
@anchor{library/dbm dbm ndbm library}@anchor{1e94}
@deffn {数据} dbm.ndbm.library

所使用的 @code{ndbm} 实现库的名称。
@end deffn

@geindex open() (在 dbm.ndbm 模块中)
@anchor{library/dbm dbm ndbm open}@anchor{11b1}
@deffn {函数} dbm.ndbm.open (filename[, flag[, mode]])

打开一个 dbm 数据库并返回 @code{ndbm} 对象。 @emph{filename} 参数为数据库文件名称（不带 @code{.dir} 或 @code{.pag} 扩展名）。

可选的 @emph{flag} 参数必须是下列值之一：


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'r'}

@tab

以只读方式打开现有数据库（默认）

@item

@code{'w'}

@tab

以读写方式打开现有数据库

@item

@code{'c'}

@tab

以读写方式打开数据库，如果不存在则创建它

@item

@code{'n'}

@tab

始终创建一个新的空数据库，以读写方式打开

@end multitable


可选的 @emph{mode} 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用。 其默认值为八进制数 @code{0o666} (并将被当前的 umask 所修改)。

除了与字典类似的方法，@code{ndbm} 对象还有以下方法：

@geindex close() (dbm.ndbm.ndbm 方法)
@anchor{library/dbm dbm ndbm ndbm close}@anchor{1e95}
@deffn {方法} ndbm.close ()

关闭 @code{ndbm} 数据库。
@end deffn
@end deffn

@node dbm dumb --- 便携式 DBM 实现,,dbm ndbm --- 基于 ndbm 的接口,dbm --- Unix "数据库" 接口
@anchor{library/dbm dbm-dumb-portable-dbm-implementation}@anchor{1e96}@anchor{library/dbm module-dbm dumb}@anchor{32}
@subsubsection @code{dbm.dumb} --- 便携式 DBM 实现


@geindex dbm.dumb (模块)

@strong{源代码:} Lib/dbm/dumb.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dbm/dumb.py}

@geindex databases

@cartouche
@quotation 注解 
@ref{32,,dbm.dumb} 模块的目的是在更健壮的模块不可用时作为 @ref{31,,dbm} 模块的最终回退项。 @ref{32,,dbm.dumb} 不是为高速运行而编写的，也不像其他数据库模块一样被经常使用。
@end quotation
@end cartouche


__________________________________________________________________


@ref{32,,dbm.dumb} 模块提供了一个完全以 Python 编写的持久化字典类接口。 不同于 @ref{33,,dbm.gnu} 等其他模块，它不需要外部库。 与其他持久化映射一样，它的键和值也总是被存储为字节串。

该模块定义以下内容：

@geindex error
@anchor{library/dbm dbm dumb error}@anchor{3ee}
@deffn {例外} dbm.dumb.error

针对 @ref{32,,dbm.dumb} 专属错误例如 I/O 错误引发。  @ref{3f1,,KeyError} 的引发则针对一般映射例如指定了不正确的键。
@end deffn

@geindex open() (在 dbm.dumb 模块中)
@anchor{library/dbm dbm dumb open}@anchor{3e9}
@deffn {函数} dbm.dumb.open (filename[, flag[, mode]])

打开一个 @code{dumbdbm} 数据库并返回 dumbdbm 对象。 @emph{filename} 参数为数据库文件的主名称（不带任何特定扩展名）。 创建一个 dumbdbm 数据库时将创建多个带有 @code{.dat} 和 @code{.dir} 扩展名的文件。

可选的 @emph{flag} 参数可以是：


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

意义

@item

@code{'r'}

@tab

以只读方式打开现有数据库（默认）

@item

@code{'w'}

@tab

以读写方式打开现有数据库

@item

@code{'c'}

@tab

以读写方式打开数据库，如果不存在则创建它

@item

@code{'n'}

@tab

始终创建一个新的空数据库，以读写方式打开

@end multitable


可选的 @emph{mode} 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用。 其默认值为八进制数 @code{0o666} (并将被当前的 umask 所修改)。

@cartouche
@quotation 警告 
当载入包含足够巨大/复杂条目的数据库时有可能导致 Python 解释器的崩溃，这是由于 Python AST 编译器有栈深度限制。
@end quotation
@end cartouche


在 3.5 版更改: @ref{3e9,,open()} 在 flag 值为 @code{'n'} 时将总是创建一个新的数据库。



在 3.8 版更改: 附带 @code{'r'} 旗标打开的数据库现在将是只读的。 附带 @code{'r'} 和 @code{'w'} 旗标的打开操作不会再创建数据库。


除了 @ref{ad7,,collections.abc.MutableMapping} 类所提供的方法，@code{dumbdbm} 对象还提供了以下方法：

@geindex sync() (dbm.dumb.dumbdbm 方法)
@anchor{library/dbm dbm dumb dumbdbm sync}@anchor{1e97}
@deffn {方法} dumbdbm.sync ()

同步磁盘上的目录和数据文件。 此方法会由 @code{Shelve.sync()} 方法来调用。
@end deffn

@geindex close() (dbm.dumb.dumbdbm 方法)
@anchor{library/dbm dbm dumb dumbdbm close}@anchor{1e98}
@deffn {方法} dumbdbm.close ()

关闭 @code{dumbdbm} 数据库。
@end deffn
@end deffn

@node sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,,dbm --- Unix "数据库" 接口,数据持久化
@anchor{library/sqlite3 doc}@anchor{1e99}@anchor{library/sqlite3 module-sqlite3}@anchor{f2}@anchor{library/sqlite3 sqlite3-db-api-2-0-interface-for-sqlite-databases}@anchor{1e9a}
@subsection @code{sqlite3} --- SQLite 数据库 DB-API 2.0 接口模块


@geindex sqlite3 (模块)

@strong{源代码：} Lib/sqlite3/@footnote{https://github.com/python/cpython/tree/3.9/Lib/sqlite3/}


__________________________________________________________________


SQLite 是一个C语言库，它可以提供一种轻量级的基于磁盘的数据库，这种数据库不需要独立的服务器进程，也允许需要使用一种非标准的 SQL 查询语言来访问它。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程序原型，然后再迁移到更大的数据库，比如 PostgreSQL 或 Oracle。

The sqlite3 module was written by Gerhard Häring.  It provides an SQL interface
compliant with the DB-API 2.0 specification described by 
@geindex Python 提高建议; PEP 249
PEP 249@footnote{https://www.python.org/dev/peps/pep-0249}.

要使用这个模块，请先创建一个 @ref{4e7,,Connection} 对象来代表数据库。 在这里数据将会存储在 @code{example.db} 文件中:

@example
import sqlite3
con = sqlite3.connect('example.db')
@end example

特殊路径名称 @code{:memory:} 可被提供用来在 RAM 中创建一个临时数据库。

一旦建立了 @ref{4e7,,Connection}，即可创建一个 @ref{1e9b,,Cursor} 对象并调用其 @ref{1e9c,,execute()} 方法来执行 SQL 命令:

@example
cur = con.cursor()

# Create table
cur.execute('@w{'}'CREATE TABLE stocks
               (date text, trans text, symbol text, qty real, price real)'@w{'}')

# Insert a row of data
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
con.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
con.close()
@end example

保存的数据将是持久化的：它可在后续会话中被重载，即使是在重启 Python 解释器之后:

@example
import sqlite3
con = sqlite3.connect('example.db')
cur = con.cursor()
@end example

要在执行 SELECT 语句之后获取数据，你可以把游标当作一个 @ref{11ba,,iterator}，调用游标的 @ref{1e9d,,fetchone()} 方法来获取一个匹配的行，或者调用 @ref{1e9e,,fetchall()} 来得到一个包含多个匹配行的列表。

下面是一个使用迭代器形式的例子：

@example
>>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
@end example
@anchor{library/sqlite3 sqlite3-placeholders}@anchor{1e9f}
SQL 操作通常会需要使用来自 Python 变量的值。 不过，请避免使用 Python 的字符串操作来拼装查询，因为这样易受 SQL 注入攻击（请在 xkcd webcomic@footnote{https://xkcd.com/327/} 查看有关这会造成什么后果的一个幽默例子）:

@example
# Never do this -- insecure!
symbol = 'RHAT'
cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
@end example

为此，应使用 DB-API 的形参替换。 要将一个变量插入到查询字符串中，请在字符串中放一个占位符，并通过提供包含多个值的 @code{元组} 作为游标的 @ref{1e9c,,execute()} 方法的第二个参数来将实际值替换到查询中。 SQL 语句可以使用两种类别的占位符之一：问号占位符（问号风格）或名称占位符（名称风格）。 对于问号风格，@code{parameters} 必须是一个 @ref{138b,,序列}。 对于名称风格，它可以是一个 @ref{138b,,序列} 或者 @ref{164,,dict} 实例。 @ref{138b,,序列} 的长度必须匹配占位符的数量，否则会引发 @ref{f79,,ProgrammingError}。 如果给出的是一个 @ref{164,,dict}，则它必须包含与全部名称形参相对应的键。 任何额外的条目都会被忽略。 下面是一个同时包含这两种风格的例子:

@example
import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table lang (name, first_appeared)")

# This is the qmark style:
cur.execute("insert into lang values (?, ?)", ("C", 1972))

# The qmark style used with executemany():
lang_list = [
    ("Fortran", 1957),
    ("Python", 1991),
    ("Go", 2009),
]
cur.executemany("insert into lang values (?, ?)", lang_list)

# And this is the named style:
cur.execute("select * from lang where first_appeared=:year", @{"year": 1972@})
print(cur.fetchall())

con.close()
@end example


@subsubheading 参见



@table @asis

@item @indicateurl{https://www.sqlite.org}

SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数据类型。

@item @indicateurl{https://www.w3schools.com/sql/}

学习 SQL 语法的教程、参考和例子。

@geindex Python 提高建议; PEP 249

@item PEP 249@footnote{https://www.python.org/dev/peps/pep-0249} - DB-API 2.0 规范

Marc-André Lemburg 写的 PEP。
@end table


@menu
* 模块函数和常量:: 
* 连接对象（Connection）:: 
* Cursor 对象:: 
* 行对象:: 
* 异常: 异常<5>. 
* SQLite 与 Python 类型:: 
* 控制事务:: 
* 有效使用 sqlite3:: 

@end menu

@node 模块函数和常量,连接对象（Connection）,,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 module-functions-and-constants}@anchor{1ea0}@anchor{library/sqlite3 sqlite3-module-contents}@anchor{1ea1}
@subsubsection 模块函数和常量


@geindex apilevel() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 apilevel}@anchor{1ea2}
@deffn {数据} sqlite3.apilevel

指明所支持的 DB-API 级别的字符串常量。 根据 DB-API 的需要设置。 硬编码为 @code{"2.0"}。
@end deffn

@geindex paramstyle() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 paramstyle}@anchor{1ea3}
@deffn {数据} sqlite3.paramstyle

指明 @ref{f2,,sqlite3} 模块所预期的形参标记格式化类型。 根据 DB-API 的需要设置。 硬编码为 @code{"qmark"}。

@cartouche
@quotation 注解 
@ref{f2,,sqlite3} 模块同时支持 @code{qmark} 和 @code{numeric} DB-API 形参风格，因为这是下层的 SQLite 库所支持的。 不过，DB-API 不允许 @code{paramstyle} 属性有多个值。
@end quotation
@end cartouche
@end deffn

@geindex version() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 version}@anchor{1ea4}
@deffn {数据} sqlite3.version

这个模块的版本号，是一个字符串。不是 SQLite 库的版本号。
@end deffn

@geindex version_info() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 version_info}@anchor{1ea5}
@deffn {数据} sqlite3.version_info

这个模块的版本号，是一个由整数组成的元组。不是 SQLite 库的版本号。
@end deffn

@geindex sqlite_version() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 sqlite_version}@anchor{1ea6}
@deffn {数据} sqlite3.sqlite_version

使用中的 SQLite 库的版本号，是一个字符串。
@end deffn

@geindex sqlite_version_info() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 sqlite_version_info}@anchor{1ea7}
@deffn {数据} sqlite3.sqlite_version_info

使用中的 SQLite 库的版本号，是一个整数组成的元组。
@end deffn

@geindex threadsafety() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 threadsafety}@anchor{1ea8}
@deffn {数据} sqlite3.threadsafety

DB-API 要求的整数，声明了 @ref{f2,,sqlite3} 模块支持的线程安全级别。 目前硬编码为 @code{1}，意味着 @emph{"线程可以共享模块，但不能共享连接。"} 然而，这不一定总是对的。 你可以使用以下查询来检查底层 SQLite 库的编译时线程模式:

@example
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("""
    select * from pragma_compile_options
    where compile_options like 'THREADSAFE=%'
""").fetchall()
@end example

注意 SQLITE_THREADSAFE 级别@footnote{https://sqlite.org/compile.html#threadsafe} 与 DB-API 2.0 @code{threadsafety} 级别不一致。
@end deffn

@geindex PARSE_DECLTYPES() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 PARSE_DECLTYPES}@anchor{1ea9}
@deffn {数据} sqlite3.PARSE_DECLTYPES

这个常量可以作为 @ref{4e9,,connect()} 函数的 @emph{detect_types} 参数。

设置这个参数后，@ref{f2,,sqlite3} 模块将解析它返回的每一列申明的类型。它会申明的类型的第一个单词，比如“integer primary key”，它会解析出“integer”，再比如“number(10)”，它会解析出“number”。然后，它会在转换器字典里查找那个类型注册的转换器函数，并调用它。
@end deffn

@geindex PARSE_COLNAMES() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 PARSE_COLNAMES}@anchor{1eaa}
@deffn {数据} sqlite3.PARSE_COLNAMES

这个常量可以作为 @ref{4e9,,connect()} 函数的 @emph{detect_types} 参数。

设置此参数可使得 SQLite 接口解析它所返回的每一列的列名。 它将在其中查找形式为 [mytype] 的字符串，然后将 'mytype' 确定为列的类型。 它将尝试在转换器字典中查找 'mytype' 条目，然后用找到的转换器函数来返回值。 在 @ref{1eab,,Cursor.description} 中找到的列名并不包括类型，举例来说，如果你在你的 SQL 中使用了像 @code{'as "Expiration date [datetime]"'} 这样的写法，那么我们将解析出在第一个 @code{'['} 之前的所有内容并去除前导空格作为列名：即列名将为 "Expiration date"。
@end deffn

@geindex connect() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 connect}@anchor{4e9}
@deffn {函数} sqlite3.connect (database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

连接 SQLite 数据库 @emph{database}。默认返回 @ref{4e7,,Connection} 对象，除非使用了自定义的 @emph{factory} 参数。

@emph{database} 是准备打开的数据库文件的路径（绝对路径或相对于当前目录的相对路径），它是 @ref{47b,,path-like object}。你也可以用 @code{":memory:"} 在内存中打开一个数据库。

当一个数据库被多个连接访问的时候，如果其中一个进程修改这个数据库，在这个事务提交之前，这个 SQLite 数据库将会被一直锁定。@emph{timeout} 参数指定了这个连接等待锁释放的超时时间，超时之后会引发一个异常。这个超时时间默认是 5.0（5秒）。

@emph{isolation_level} 参数，请查看 @ref{4e7,,Connection} 对象的 @ref{1eac,,isolation_level} 属性。

SQLite 原生只支持5种类型：TEXT，INTEGER，REAL，BLOB 和 NULL。如果你想用其它类型，你必须自己添加相应的支持。使用 @emph{detect_types} 参数和模块级别的 @ref{1ead,,register_converter()} 函数注册**转换器** 可以简单的实现。

@emph{detect_types} 默认为 0 (即关闭，不进行类型检测)，你可以将其设为任意的 @ref{1ea9,,PARSE_DECLTYPES} 和 @ref{1eaa,,PARSE_COLNAMES} 组合来启用类型检测。 由于 SQLite 的行为，生成的字段类型 (例如 @code{max(data)}) 不能被检测，即使在设置了 @emph{detect_types} 形参时也是如此。 在此情况下，返回的类型为 @ref{206,,str}。

默认情况下，@emph{check_same_thread} 为 @ref{59c,,True}，只有当前的线程可以使用该连接。 如果设置为 @ref{497,,False}，则多个线程可以共享返回的连接。 当多个线程使用同一个连接的时候，用户应该把写操作进行序列化，以避免数据损坏。

默认情况下，当调用 connect 方法的时候，@ref{f2,,sqlite3} 模块使用了它的 @ref{4e7,,Connection} 类。当然，你也可以创建 @ref{4e7,,Connection} 类的子类，然后创建提供了 @emph{factory} 参数的 @ref{4e9,,connect()} 方法。

详情请查阅当前手册的 @ref{1eae,,SQLite 与 Python 类型} 部分。

@ref{f2,,sqlite3} 模块在内部使用语句缓存来避免 SQL 解析开销。 如果要显式设置当前连接可以缓存的语句数，可以设置 @emph{cached_statements} 参数。 当前实现的默认值是缓存100条语句。

如果 @emph{uri} 为 @ref{59c,,True}，@emph{database} 会被解释为 @abbr{URI,Uniform Resource Identifier}，带有文件路径和可选的查询字符串。 scheme 部分 @emph{必须} 是 @code{"file:"}。 path 可以是一个相对或绝对的文件路径。 查询字符串允许我们向 SQLite 传递参数。一些有用的 URI 技巧包括:

@example
# Open a database in read-only mode.
con = sqlite3.connect("file:template.db?mode=ro", uri=True)

# Don't implicitly create a new database file if it does not already exist.
# Will raise sqlite3.OperationalError if unable to open a database file.
con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True)

# Create a shared named in-memory database.
con1 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
con2 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
con1.executescript("create table t(t); insert into t values(28);")
rows = con2.execute("select * from t").fetchall()
@end example

关于这个功能的更多信息，包括可识别的参数列表，可以在 SQLite URI 文档@footnote{https://www.sqlite.org/uri.html} 中找到。

引发一个 @ref{fec,,审计事件} @code{sqlite3.connect}，附带参数 @code{database}。


在 3.4 版更改: 增加了 @emph{uri} 参数。



在 3.7 版更改: @emph{database} 现在可以是一个 @ref{47b,,path-like object} 对象了，不仅仅是字符串。

@end deffn

@geindex register_converter() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 register_converter}@anchor{1ead}
@deffn {函数} sqlite3.register_converter (typename, callable)

注册一个回调对象 @emph{callable}, 用来转换数据库中的字节串为自定的 Python 类型。所有类型为 @emph{typename} 的数据库的值在转换时，都会调用这个回调对象。通过指定 @ref{4e9,,connect()} 函数的 @emph{detect-types} 参数来设置类型检测的方式。注意，@emph{typename} 与查询语句中的类型名进行匹配时不区分大小写。
@end deffn

@geindex register_adapter() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 register_adapter}@anchor{1eaf}
@deffn {函数} sqlite3.register_adapter (type, callable)

注册一个回调对象 @emph{callable}，用来转换自定义Python类型为一个 SQLite 支持的类型。 这个回调对象 @emph{callable} 仅接受一个 Python 值作为参数，而且必须返回以下某个类型的值：int，float，str 或 bytes。
@end deffn

@geindex complete_statement() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 complete_statement}@anchor{1eb0}
@deffn {函数} sqlite3.complete_statement (sql)

如果字符串 @emph{sql} 包含一个或多个完整的 SQL 语句（以分号结束）则返回 @ref{59c,,True}。它不会验证 SQL 语法是否正确，仅会验证字符串字面上是否完整，以及是否以分号结束。

它可以用来构建一个 SQLite shell，下面是一个例子：

@example
# A minimal SQLite shell for experiments

import sqlite3

con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()

buffer = ""

print("Enter your SQL commands to execute in sqlite3.")
print("Enter a blank line to exit.")

while True:
    line = input()
    if line == "":
        break
    buffer += line
    if sqlite3.complete_statement(buffer):
        try:
            buffer = buffer.strip()
            cur.execute(buffer)

            if buffer.lstrip().upper().startswith("SELECT"):
                print(cur.fetchall())
        except sqlite3.Error as e:
            print("An error occurred:", e.args[0])
        buffer = ""

con.close()
@end example
@end deffn

@geindex enable_callback_tracebacks() (在 sqlite3 模块中)
@anchor{library/sqlite3 sqlite3 enable_callback_tracebacks}@anchor{1eb1}
@deffn {函数} sqlite3.enable_callback_tracebacks (flag)

默认情况下，您不会获得任何用户定义函数中的回溯消息，比如聚合，转换器，授权器回调等。如果要调试它们，可以设置 @emph{flag} 参数为 @code{True} 并调用此函数。 之后，回调中的回溯信息将会输出到 @code{sys.stderr}。 再次使用 @ref{497,,False} 来禁用该功能。
@end deffn

@node 连接对象（Connection）,Cursor 对象,模块函数和常量,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 connection-objects}@anchor{1eb2}@anchor{library/sqlite3 sqlite3-connection-objects}@anchor{1eb3}
@subsubsection 连接对象（Connection）


@geindex Connection (sqlite3 中的类)
@anchor{library/sqlite3 sqlite3 Connection}@anchor{4e7}
@deffn {类} sqlite3.Connection

SQLite 数据库连接对象有如下的属性和方法：

@geindex isolation_level (sqlite3.Connection 属性)
@anchor{library/sqlite3 sqlite3 Connection isolation_level}@anchor{1eac}
@deffn {属性} isolation_level

获取或设置当前默认的隔离级别。 表示自动提交模式的 @ref{204,,None} 以及 "DEFERRED", "IMMEDIATE" 或 "EXCLUSIVE" 其中之一。 详细描述请参阅 @ref{1eb4,,控制事务}。
@end deffn

@geindex in_transaction (sqlite3.Connection 属性)
@anchor{library/sqlite3 sqlite3 Connection in_transaction}@anchor{1eb5}
@deffn {属性} in_transaction

如果是在活动事务中（还没有提交改变），返回 @ref{59c,,True}，否则，返回 @ref{497,,False}。它是一个只读属性。


3.2 新版功能.

@end deffn

@geindex cursor() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection cursor}@anchor{1eb6}
@deffn {方法} cursor (factory=Cursor)

这个方法接受一个可选参数 @emph{factory}，如果要指定这个参数，它必须是一个可调用对象，而且必须返回 @ref{1e9b,,Cursor} 类的一个实例或者子类。
@end deffn

@geindex commit() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection commit}@anchor{1eb7}
@deffn {方法} commit ()

这个方法提交当前事务。如果没有调用这个方法，那么从上一次提交 @code{commit()} 以来所有的变化在其他数据库连接上都是不可见的。如果你往数据库里写了数据，但是又查询不到，请检查是否忘记了调用这个方法。
@end deffn

@geindex rollback() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection rollback}@anchor{1eb8}
@deffn {方法} rollback ()

这个方法回滚从上一次调用 @ref{1eb7,,commit()} 以来所有数据库的改变。
@end deffn

@geindex close() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection close}@anchor{1eb9}
@deffn {方法} close ()

关闭数据库连接。注意，它不会自动调用 @ref{1eb7,,commit()} 方法。如果在关闭数据库连接之前没有调用 @ref{1eb7,,commit()}，那么你的修改将会丢失！
@end deffn

@geindex execute() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection execute}@anchor{1eba}
@deffn {方法} execute (sql[, parameters])

创建一个新的 @ref{1e9b,,Cursor} 对象，并在其上使用给出的 @emph{sql} 和 @emph{parameters} 调用 @ref{1e9c,,execute()}。 返回新的游标对象。
@end deffn

@geindex executemany() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection executemany}@anchor{1ebb}
@deffn {方法} executemany (sql[, parameters])

创建一个新的 @ref{1e9b,,Cursor} 对象，并在其上使用给出的 @emph{sql} 和 @emph{parameters} 调用 @ref{1ebc,,executemany()}。 返回新的游标对象。
@end deffn

@geindex executescript() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection executescript}@anchor{1ebd}
@deffn {方法} executescript (sql_script)

创建一个新的 @ref{1e9b,,Cursor} 对象，并在其上使用给出的 @emph{sql_script} 调用 @ref{1ebe,,executescript()}。 返回新的游标对象。
@end deffn

@geindex create_function() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection create_function}@anchor{111d}
@deffn {方法} create_function (name, num_params, func, *, deterministic=False)

创建一个可以在 SQL 语句中使用的用户自定义函数，函数名为 @emph{name}。 @emph{num_params} 为该函数所接受的形参个数（如果 @emph{num_params} 为 -1，则该函数可接受任意数量的参数）， @emph{func} 是一个 Python 可调用对象，它将作为 SQL 函数被调用。 如果 @emph{deterministic} 为真值，则所创建的函数将被标记为 deterministic@footnote{https://sqlite.org/deterministic.html}，这允许 SQLite 执行额外的优化。 此旗标在 SQLite 3.8.3 或更高版本中受到支持，如果在旧版本中使用将引发 @ref{1ebf,,NotSupportedError}。

此函数可返回任何 SQLite 所支持的类型: bytes, str, int, float 和 @code{None}。


在 3.8 版更改: 增加了 @emph{deterministic} 形参。


示例:

@example
import sqlite3
import hashlib

def md5sum(t):
    return hashlib.md5(t).hexdigest()

con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", (b"foo",))
print(cur.fetchone()[0])

con.close()
@end example
@end deffn

@geindex create_aggregate() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection create_aggregate}@anchor{111c}
@deffn {方法} create_aggregate (name, num_params, aggregate_class)

创建一个自定义的聚合函数。

参数中 @emph{aggregate_class} 类必须实现两个方法：@code{step} 和 @code{finalize}。@code{step} 方法接受 @emph{num_params} 个参数（如果 @emph{num_params} 为 -1，那么这个函数可以接受任意数量的参数）；@code{finalize} 方法返回最终的聚合结果。

@code{finalize} 方法可以返回任何 SQLite 支持的类型：bytes，str，int，float 和 @code{None}。

示例:

@example
import sqlite3

class MySum:
    def __init__(self):
        self.count = 0

    def step(self, value):
        self.count += value

    def finalize(self):
        return self.count

con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
cur = con.cursor()
cur.execute("create table test(i)")
cur.execute("insert into test(i) values (1)")
cur.execute("insert into test(i) values (2)")
cur.execute("select mysum(i) from test")
print(cur.fetchone()[0])

con.close()
@end example
@end deffn

@geindex create_collation() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection create_collation}@anchor{1ec0}
@deffn {方法} create_collation (name, callable)

使用 @emph{name} 和 @emph{callable} 创建排序规则。这个 @emph{callable} 接受两个字符串对象，如果第一个小于第二个则返回 -1， 如果两个相等则返回 0，如果第一个大于第二个则返回 1。注意，这是用来控制排序的（SQL 中的 ORDER BY），所以它不会影响其它的 SQL 操作。

注意，这个 @emph{callable} 可调用对象会把它的参数作为 Python 字节串，通常会以 UTF-8 编码格式对它进行编码。

以下示例显示了使用“错误方式”进行排序的自定义排序规则：

@example
import sqlite3

def collate_reverse(string1, string2):
    if string1 == string2:
        return 0
    elif string1 < string2:
        return 1
    else:
        return -1

con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)

cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
    print(row)
con.close()
@end example

要移除一个排序规则，需要调用 @code{create_collation} 并设置 callable 参数为 @code{None}。

@example
con.create_collation("reverse", None)
@end example
@end deffn

@geindex interrupt() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection interrupt}@anchor{1ec1}
@deffn {方法} interrupt ()

可以从不同的线程调用这个方法来终止所有查询操作，这些查询操作可能正在连接上执行。此方法调用之后， 查询将会终止，而且查询的调用者会获得一个异常。
@end deffn

@geindex set_authorizer() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection set_authorizer}@anchor{111e}
@deffn {方法} set_authorizer (authorizer_callback)

此方法注册一个授权回调对象。每次在访问数据库中某个表的某一列的时候，这个回调对象将会被调用。如果要允许访问，则返回 @code{SQLITE_OK}，如果要终止整个 SQL 语句，则返回 @code{SQLITE_DENY}，如果这一列需要当做 NULL 值处理，则返回 @code{SQLITE_IGNORE}。这些常量可以在  @ref{f2,,sqlite3} 模块中找到。

回调的第一个参数表示要授权的操作类型。 第二个和第三个参数将是参数或 @ref{204,,None}，具体取决于第一个参数的值。 第 4 个参数是数据库的名称（“main”，“temp”等），如果需要的话。 第 5 个参数是负责访问尝试的最内层触发器或视图的名称，或者如果此访问尝试直接来自输入 SQL 代码，则为 @ref{204,,None}。

请参阅 SQLite 文档，了解第一个参数的可能值以及第二个和第三个参数的含义，具体取决于第一个参数。 所有必需的常量都可以在 @ref{f2,,sqlite3} 模块中找到。
@end deffn

@geindex set_progress_handler() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection set_progress_handler}@anchor{111f}
@deffn {方法} set_progress_handler (handler, n)

此例程注册回调。 对SQLite虚拟机的每个多指令调用回调。 如果要在长时间运行的操作期间从SQLite调用（例如更新用户界面），这非常有用。

如果要清除以前安装的任何进度处理程序，调用该方法时请将 @emph{handler} 参数设置为 @ref{204,,None}。

从处理函数返回非零值将终止当前正在执行的查询并导致它引发 @ref{1ec2,,OperationalError} 异常。
@end deffn

@geindex set_trace_callback() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection set_trace_callback}@anchor{b6e}
@deffn {方法} set_trace_callback (trace_callback)

为每个 SQLite 后端实际执行的 SQL 语句注册要调用的 @emph{trace_callback}。

传递给回调的唯一参数是正在执行的语句（作为 @ref{206,,str} ）。回调的返回值被忽略。请注意，后端不仅运行传递给 @ref{1e9c,,Cursor.execute()} 方法的语句。其他来源包括 sqlite3 模块的 @ref{1eb4,,事务管理} 和当前数据库中定义的触发器的执行。

将传入的 @emph{trace_callback} 设为 @ref{204,,None} 将禁用跟踪回调。

@cartouche
@quotation 注解 
在跟踪回调中产生的异常不会被传播。作为开发和调试的辅助手段，使用 @ref{1eb1,,enable_callback_tracebacks()} 来启用打印跟踪回调中产生的异常的回调。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@geindex enable_load_extension() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection enable_load_extension}@anchor{c72}
@deffn {方法} enable_load_extension (enabled)

此例程允许/禁止SQLite引擎从共享库加载SQLite扩展。 SQLite扩展可以定义新功能，聚合或全新的虚拟表实现。 一个众所周知的扩展是与SQLite一起分发的全文搜索扩展。

默认情况下禁用可加载扩展。 见 @footnote{@w{(1)} 
The sqlite3 module is not built with loadable extension support by
default, because some platforms (notably macOS) have SQLite
libraries which are compiled without this feature. To get loadable
extension support, you must pass @code{--enable-loadable-sqlite-extensions} to
configure.
}.


3.2 新版功能.


@example
import sqlite3

con = sqlite3.connect(":memory:")

# enable extension loading
con.enable_load_extension(True)

# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")

# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")

# disable extension loading again
con.enable_load_extension(False)

# example from SQLite wiki
con.execute("create virtual table recipe using fts3(name, ingredients)")
con.executescript("""
    insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
    insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
    insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
    insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
    """)
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
    print(row)

con.close()
@end example
@end deffn

@geindex load_extension() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection load_extension}@anchor{c73}
@deffn {方法} load_extension (path)

这个例程从一个共享库中加载一个 SQLite 扩展。在使用这个例程之前，你必须用 @ref{c72,,enable_load_extension()} 来启用扩展加载。

默认情况下禁用可加载扩展。 见 @footnote{@w{(1)} 
The sqlite3 module is not built with loadable extension support by
default, because some platforms (notably macOS) have SQLite
libraries which are compiled without this feature. To get loadable
extension support, you must pass @code{--enable-loadable-sqlite-extensions} to
configure.
}.


3.2 新版功能.

@end deffn

@geindex row_factory (sqlite3.Connection 属性)
@anchor{library/sqlite3 sqlite3 Connection row_factory}@anchor{1ec3}
@deffn {属性} row_factory

您可以将此属性更改为可接受游标和原始行作为元组的可调用对象，并将返回实际结果行。 这样，您可以实现更高级的返回结果的方法，例如返回一个可以按名称访问列的对象。

示例:

@example
import sqlite3

def dict_factory(cursor, row):
    d = @{@}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

con.close()
@end example

如果返回一个元组是不够的，并且你想要对列进行基于名称的访问，你应该考虑将 @ref{1ec3,,row_factory} 设置为高度优化的 @ref{857,,sqlite3.Row} 类型。 @ref{857,,Row} 提供基于索引和不区分大小写的基于名称的访问，几乎没有内存开销。 它可能比您自己的基于字典的自定义方法甚至基于 db_row 的解决方案更好。

@c XXX what's a db_row-based solution?
@end deffn

@geindex text_factory (sqlite3.Connection 属性)
@anchor{library/sqlite3 sqlite3 Connection text_factory}@anchor{1ec4}
@deffn {属性} text_factory

使用此属性可以控制为 @code{TEXT} 数据类型返回的对象。 默认情况下，此属性设置为 @ref{206,,str} 和 @ref{f2,,sqlite3} 模块将返回 @code{TEXT} 的 @ref{206,,str}  对象。 如果要返回 @ref{172,,bytes} ，可以将其设置为 @ref{172,,bytes}。

您还可以将其设置为接受单个 bytestring 参数的任何其他可调用对象，并返回结果对象。

请参阅以下示例代码以进行说明：

@example
import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()

AUSTRIA = "Österreich"

# by default, rows are returned as str
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA

# but we can make sqlite3 always return bytestrings ...
con.text_factory = bytes
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) is bytes
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")

# we can also implement a custom text_factory ...
# here we implement one that appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
row = cur.fetchone()
assert row[0] == "barfoo"

con.close()
@end example
@end deffn

@geindex total_changes (sqlite3.Connection 属性)
@anchor{library/sqlite3 sqlite3 Connection total_changes}@anchor{1ec5}
@deffn {属性} total_changes

返回自打开数据库连接以来已修改，插入或删除的数据库行的总数。
@end deffn

@geindex iterdump() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection iterdump}@anchor{1ec6}
@deffn {方法} iterdump ()

返回以SQL文本格式转储数据库的迭代器。 保存内存数据库以便以后恢复时很有用。 此函数提供与 @code{sqlite3} shell 中的 @code{.dump} 命令相同的功能。

示例:

@example
# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3

con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)
con.close()
@end example
@end deffn

@geindex backup() (sqlite3.Connection 方法)
@anchor{library/sqlite3 sqlite3 Connection backup}@anchor{4e8}
@deffn {方法} backup (target, *, pages=-1, progress=None, name="main", sleep=0.250)

即使在 SQLite 数据库被其他客户端访问时，或者同时由同一连接访问，该方法也会对其进行备份。 该副本将写入强制参数 @emph{target}，该参数必须是另一个 @ref{4e7,,Connection} 实例。

默认情况下，或者当 @emph{pages} 为 @code{0} 或负整数时，整个数据库将在一个步骤中复制；否则该方法一次循环复制 @emph{pages} 规定数量的页面。

如果指定了 @emph{progress}，则它必须为 @code{None} 或一个将在每次迭代时附带三个整数参数执行的可调用对象，这三个参数分别是前一次迭代的状态 @emph{status}，将要拷贝的剩余页数 @emph{remaining} 以及总页数 @emph{total}。

@emph{name} 参数指定将被拷贝的数据库名称：它必须是一个字符串，其内容为表示主数据库的默认值 @code{"main"}，表示临时数据库的 @code{"temp"} 或是在 @code{ATTACH DATABASE} 语句的 @code{AS} 关键字之后指定表示附加数据库的名称。

@emph{sleep} 参数指定在备份剩余页的连续尝试之间要休眠的秒数，可以指定为一个整数或一个浮点数值。

示例一，将现有数据库复制到另一个数据库中：

@example
import sqlite3

def progress(status, remaining, total):
    print(f'Copied @{total-remaining@} of @{total@} pages...')

con = sqlite3.connect('existing_db.db')
bck = sqlite3.connect('backup.db')
with bck:
    con.backup(bck, pages=1, progress=progress)
bck.close()
con.close()
@end example

示例二，将现有数据库复制到临时副本中：

@example
import sqlite3

source = sqlite3.connect('existing_db.db')
dest = sqlite3.connect(':memory:')
source.backup(dest)
@end example

可用性：SQLite 3.6.11 或以上版本


3.7 新版功能.

@end deffn
@end deffn

@node Cursor 对象,行对象,连接对象（Connection）,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 cursor-objects}@anchor{1ec7}@anchor{library/sqlite3 sqlite3-cursor-objects}@anchor{1ec8}
@subsubsection Cursor 对象


@geindex Cursor (sqlite3 中的类)
@anchor{library/sqlite3 sqlite3 Cursor}@anchor{1e9b}
@deffn {类} sqlite3.Cursor

@ref{1e9b,,Cursor} 游标实例具有以下属性和方法。

@geindex ? (question mark); in SQL statements

@geindex ; (colon); in SQL statements

@geindex execute() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor execute}@anchor{1e9c}
@deffn {方法} execute (sql[, parameters])

执行一条 SQL 语句。 可以使用 @ref{1e9f,,占位符} 将值绑定到语句中。

@ref{1e9c,,execute()} 将只执行一条单独的 SQL 语句。 如果你尝试用它执行超过一条语句，将会引发 @ref{1ec9,,Warning}。 如果你想要用一次调用执行多条 SQL 语句请使用 @ref{1ebe,,executescript()}。
@end deffn

@geindex executemany() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor executemany}@anchor{1ebc}
@deffn {方法} executemany (sql, seq_of_parameters)

执行一条 @ref{1e9f,,带形参的} SQL 命令，使用所有形参序列或在序列 @emph{seq_of_parameters} 中找到的映射。 @ref{f2,,sqlite3} 模块还允许使用 @ref{11ba,,iterator} 代替序列来产生形参。

@example
import sqlite3

class IterChars:
    def __init__(self):
        self.count = ord('a')

    def __iter__(self):
        return self

    def __next__(self):
        if self.count > ord('z'):
            raise StopIteration
        self.count += 1
        return (chr(self.count - 1),) # this is a 1-tuple

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)

cur.execute("select c from characters")
print(cur.fetchall())

con.close()
@end example

这是一个使用生成器 @ref{a8c,,generator} 的简短示例：

@example
import sqlite3
import string

def char_generator():
    for c in string.ascii_lowercase:
        yield (c,)

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

cur.executemany("insert into characters(c) values (?)", char_generator())

cur.execute("select c from characters")
print(cur.fetchall())

con.close()
@end example
@end deffn

@geindex executescript() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor executescript}@anchor{1ebe}
@deffn {方法} executescript (sql_script)

这是用于一次性执行多条 SQL 语句的非标准便捷方法。 它会首先发出一条 @code{COMMIT} 语句，然后执行通过参数获得的 SQL 脚本。 此方法会忽略 @code{isolation_level}；任何事件控制都必须被添加到 @emph{sql_script}。

@emph{sql_script} 可以是一个 @ref{206,,str} 类的实例。

示例:

@example
import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
    create table person(
        firstname,
        lastname,
        age
    );

    create table book(
        title,
        author,
        published
    );

    insert into book(title, author, published)
    values (
        'Dirk Gently'@w{'}s Holistic Detective Agency',
        'Douglas Adams',
        1987
    );
    """)
con.close()
@end example
@end deffn

@geindex fetchone() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor fetchone}@anchor{1e9d}
@deffn {方法} fetchone ()

获取一个查询结果集的下一行，返回一个单独序列，或是在没有更多可用数据时返回 @ref{204,,None}。
@end deffn

@geindex fetchmany() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor fetchmany}@anchor{1eca}
@deffn {方法} fetchmany (size=cursor.arraysize)

获取下一个多行查询结果集，返回一个列表。 当没有更多可用行时将返回一个空列表。

每次调用获取的行数由 @emph{size} 形参指定。 如果没有给出该形参，则由 cursor 的 arraysize 决定要获取的行数。 此方法将基于 size 形参值尝试获取指定数量的行。 如果获取不到指定的行数，则可能返回较少的行。

请注意 @emph{size} 形参会涉及到性能方面的考虑。为了获得优化的性能，通常最好是使用 arraysize 属性。 如果使用 @emph{size} 形参，则最好在从一个 @ref{1eca,,fetchmany()} 调用到下一个调用之间保持相同的值。
@end deffn

@geindex fetchall() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor fetchall}@anchor{1e9e}
@deffn {方法} fetchall ()

获取一个查询结果的所有（剩余）行，返回一个列表。 请注意 cursor 的 arraysize 属性会影响此操作的执行效率。 当没有可用行时将返回一个空列表。
@end deffn

@geindex close() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor close}@anchor{1ecb}
@deffn {方法} close ()

立即关闭 cursor（而不是在当 @code{__del__} 被调用的时候）。

从这一时刻起该 cursor 将不再可用，如果再尝试用该 cursor 执行任何操作将引发 @ref{f79,,ProgrammingError} 异常。
@end deffn

@geindex setinputsizes() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor setinputsizes}@anchor{1ecc}
@deffn {方法} setinputsizes (sizes)

由 DB-API 要求。在 @ref{f2,,sqlite3} 中不做任何事情。
@end deffn

@geindex setoutputsize() (sqlite3.Cursor 方法)
@anchor{library/sqlite3 sqlite3 Cursor setoutputsize}@anchor{1ecd}
@deffn {方法} setoutputsize (size[, column])

由 DB-API 要求。在 @ref{f2,,sqlite3} 中不做任何事情。
@end deffn

@geindex rowcount (sqlite3.Cursor 属性)
@anchor{library/sqlite3 sqlite3 Cursor rowcount}@anchor{1ece}
@deffn {属性} rowcount

虽然 @ref{f2,,sqlite3} 模块的 @ref{1e9b,,Cursor} 类实现了此属性，但数据库引擎本身对于确定 "受影响行"/"已选择行" 的支持并不完善。

对于 @ref{1ebc,,executemany()} 语句，修改行数会被汇总至 @ref{1ece,,rowcount}。

根据 Python DB API 规格描述的要求，@ref{1ece,,rowcount} 属性 "当未在 cursor 上执行 @code{executeXX()} 或者上一次操作的 rowcount 不是由接口确定时为 -1"。 这包括 @code{SELECT} 语句，因为我们无法确定一次查询将产生的行计数，而要等获取了所有行时才会知道。

在 SQLite 的 3.6.5 版之前，如果你执行 @code{DELETE FROM table} 时不附带任何条件，则 @ref{1ece,,rowcount} 将被设为 0。
@end deffn

@geindex lastrowid (sqlite3.Cursor 属性)
@anchor{library/sqlite3 sqlite3 Cursor lastrowid}@anchor{67f}
@deffn {属性} lastrowid

这个只读的属性提供了最后插入的行的 ID 。它只在使用 @ref{1e9c,,execute()} 方法的 @code{INSERT} 或 @code{REPLACE} 语句成功后被更新。对于其他语句，在 @ref{1ebc,,executemany()} 或 @ref{1ebe,,executescript()} 之后，或者如果插入失败， @code{lastrowid} 值将保持不变。 @code{lastrowid} 的初始值是 @ref{204,,None} 。

@cartouche
@quotation 注解 
对 @code{WITHOUT ROWID} 表的插入不被记录。
@end quotation
@end cartouche


在 3.6 版更改: 增加了 @code{REPLACE} 语句的支持。

@end deffn

@geindex arraysize (sqlite3.Cursor 属性)
@anchor{library/sqlite3 sqlite3 Cursor arraysize}@anchor{1ecf}
@deffn {属性} arraysize

用于控制 @ref{1eca,,fetchmany()} 返回行数的可读取/写入属性。 该属性的默认值为 1，表示每次调用将获取单独一行。
@end deffn

@geindex description (sqlite3.Cursor 属性)
@anchor{library/sqlite3 sqlite3 Cursor description}@anchor{1eab}
@deffn {属性} description

这个只读属性将提供上一次查询的列名称。 为了与 Python DB API 保持兼容，它会为每个列返回一个 7 元组，每个元组的最后六个条目均为 @ref{204,,None}。

对于没有任何匹配行的 @code{SELECT} 语句同样会设置该属性。
@end deffn

@geindex connection (sqlite3.Cursor 属性)
@anchor{library/sqlite3 sqlite3 Cursor connection}@anchor{1ed0}
@deffn {属性} connection

这个只读属性将提供 @ref{1e9b,,Cursor} 对象所使用的 SQLite 数据库 @ref{4e7,,Connection}。 通过调用 @ref{1eb6,,con.cursor()} 创建的 @ref{1e9b,,Cursor} 对象所包含的 @ref{1ed0,,connection} 属性将指向 @emph{con}:

@example
>>> con = sqlite3.connect(":memory:")
>>> cur = con.cursor()
>>> cur.connection == con
True
@end example
@end deffn
@end deffn

@node 行对象,异常<5>,Cursor 对象,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 row-objects}@anchor{1ed1}@anchor{library/sqlite3 sqlite3-row-objects}@anchor{1ed2}
@subsubsection 行对象


@geindex Row (sqlite3 中的类)
@anchor{library/sqlite3 sqlite3 Row}@anchor{857}
@deffn {类} sqlite3.Row

一个 @ref{857,,Row} 实例，该实例将作为用于 @ref{4e7,,Connection} 对象的高度优化的 @ref{1ec3,,row_factory}。 它的大部分行为都会模仿元组的特性。

它支持使用列名称的映射访问以及索引、迭代、文本表示、相等检测和 @ref{292,,len()} 等操作。

如果两个 @ref{857,,Row} 对象具有完全相同的列并且其成员均相等，则它们的比较结果为相等。

@geindex keys() (sqlite3.Row 方法)
@anchor{library/sqlite3 sqlite3 Row keys}@anchor{1ed3}
@deffn {方法} keys ()

此方法会在一次查询之后立即返回一个列名称的列表，它是 @ref{1eab,,Cursor.description} 中每个元组的第一个成员。
@end deffn


在 3.5 版更改: 添加了对切片操作的支持。

@end deffn

让我们假设我们如上面的例子所示初始化一个表:

@example
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute('@w{'}'create table stocks
(date text, trans text, symbol text,
 qty real, price real)'@w{'}')
cur.execute("""insert into stocks
            values ('2006-01-05','BUY','RHAT',100,35.14)""")
con.commit()
cur.close()
@end example

现在我们将 @ref{857,,Row} 插入:

@example
>>> con.row_factory = sqlite3.Row
>>> cur = con.cursor()
>>> cur.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = cur.fetchone()
>>> type(r)
<class 'sqlite3.Row'>
>>> tuple(r)
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
>>> len(r)
5
>>> r[2]
'RHAT'
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
>>> r['qty']
100.0
>>> for member in r:
...     print(member)
...
2006-01-05
BUY
RHAT
100.0
35.14
@end example

@node 异常<5>,SQLite 与 Python 类型,行对象,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 exceptions}@anchor{1ed4}@anchor{library/sqlite3 sqlite3-exceptions}@anchor{1ed5}
@subsubsection 异常


@geindex Warning
@anchor{library/sqlite3 sqlite3 Warning}@anchor{1ec9}
@deffn {例外} sqlite3.Warning

@ref{2e3,,Exception} 的一个子类。
@end deffn

@geindex Error
@anchor{library/sqlite3 sqlite3 Error}@anchor{1ed6}
@deffn {例外} sqlite3.Error

此模块中其他异常的基类。 它是 @ref{2e3,,Exception} 的一个子类。
@end deffn

@geindex DatabaseError
@anchor{library/sqlite3 sqlite3 DatabaseError}@anchor{1ed7}
@deffn {例外} sqlite3.DatabaseError

针对数据库相关错误引发的异常。
@end deffn

@geindex IntegrityError
@anchor{library/sqlite3 sqlite3 IntegrityError}@anchor{1ed8}
@deffn {例外} sqlite3.IntegrityError

当数据库的关系一致性受到影响时引发的异常。 例如外键检查失败等。 它是 @ref{1ed7,,DatabaseError} 的子类。
@end deffn

@geindex ProgrammingError
@anchor{library/sqlite3 sqlite3 ProgrammingError}@anchor{f79}
@deffn {例外} sqlite3.ProgrammingError

编程错误引发的异常，例如表未找到或已存在，SQL 语句存在语法错误，指定的形参数量错误等。 它是 @ref{1ed7,,DatabaseError} 的子类。
@end deffn

@geindex OperationalError
@anchor{library/sqlite3 sqlite3 OperationalError}@anchor{1ec2}
@deffn {例外} sqlite3.OperationalError

与数据库操作相关而不一定能受程序员掌控的错误引发的异常，例如发生非预期的连接中断，数据源名称未找到，事务无法被执行等。 它是 @ref{1ed7,,DatabaseError} 的子类。
@end deffn

@geindex NotSupportedError
@anchor{library/sqlite3 sqlite3 NotSupportedError}@anchor{1ebf}
@deffn {例外} sqlite3.NotSupportedError

在使用了某个数据库不支持的方法或数据库 API 时引发的异常，例如在一个不支持事务或禁用了事务的连接上调用 @ref{1eb8,,rollback()} 方法等。 它是 @ref{1ed7,,DatabaseError} 的子类。
@end deffn

@node SQLite 与 Python 类型,控制事务,异常<5>,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 sqlite-and-python-types}@anchor{1ed9}@anchor{library/sqlite3 sqlite3-types}@anchor{1eae}
@subsubsection SQLite 与 Python 类型


@menu
* 概述: 概述<7>. 
* 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。:: 
* 将SQLite 值转换为自定义Python 类型:: 
* 默认适配器和转换器:: 

@end menu

@node 概述<7>,使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,,SQLite 与 Python 类型
@anchor{library/sqlite3 introduction}@anchor{1eda}
@subsubsection 概述


SQLite 原生支持如下的类型： @code{NULL}，@code{INTEGER}，@code{REAL}，@code{TEXT}，@code{BLOB}。

因此可以将以下Python类型发送到SQLite而不会出现任何问题：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} 
@headitem

Python 类型

@tab

SQLite 类型

@item

@ref{204,,None}

@tab

@code{NULL}

@item

@ref{205,,int}

@tab

@code{INTEGER}

@item

@ref{1fe,,float}

@tab

@code{REAL}

@item

@ref{206,,str}

@tab

@code{TEXT}

@item

@ref{172,,bytes}

@tab

@code{BLOB}

@end multitable


这是SQLite类型默认转换为Python类型的方式：


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

SQLite 类型

@tab

Python 类型

@item

@code{NULL}

@tab

@ref{204,,None}

@item

@code{INTEGER}

@tab

@ref{205,,int}

@item

@code{REAL}

@tab

@ref{1fe,,float}

@item

@code{TEXT}

@tab

取决于 @ref{1ec4,,text_factory} , 默认为 @ref{206,,str}

@item

@code{BLOB}

@tab

@ref{172,,bytes}

@end multitable


@ref{f2,,sqlite3} 模块的类型系统可通过两种方式来扩展：你可以通过对象适配将额外的 Python 类型保存在 SQLite 数据库中，你也可以让 @ref{f2,,sqlite3} 模块通过转换器将 SQLite 类型转换为不同的 Python 类型。

@node 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,将SQLite 值转换为自定义Python 类型,概述<7>,SQLite 与 Python 类型
@anchor{library/sqlite3 using-adapters-to-store-additional-python-types-in-sqlite-databases}@anchor{1edb}
@subsubsection 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。


如上文所述，SQLite 只包含对有限类型集的原生支持。 要让 SQLite 能使用其他 Python 类型，你必须将它们 @strong{适配} 至 sqlite3 模块所支持的 SQLite 类型中的一种：NoneType, int, float, str, bytes。

有两种方式能让 @ref{f2,,sqlite3} 模块将某个定制的 Python 类型适配为受支持的类型。

@menu
* 让对象自行适配:: 
* 注册可调用的适配器:: 

@end menu

@node 让对象自行适配,注册可调用的适配器,,使用适配器将额外的 Python 类型保存在 SQLite 数据库中。
@anchor{library/sqlite3 letting-your-object-adapt-itself}@anchor{1edc}
@subsubsection 让对象自行适配


如果类是你自己编写的，这将是一个很好的方式。 假设你有这样一个类:

@example
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
@end example

现在你可将这种点对象保存在一个 SQLite 列中。 首先你必须选择一种受支持的类型用来表示点对象。 让我们就用 str 并使用一个分号来分隔坐标值。 然后你需要给你的类加一个方法 @code{__conform__(self, protocol)}，它必须返回转换后的值。 形参 @emph{protocol} 将为 @code{PrepareProtocol}。

@example
import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return "%f;%f" % (self.x, self.y)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

con.close()
@end example

@node 注册可调用的适配器,,让对象自行适配,使用适配器将额外的 Python 类型保存在 SQLite 数据库中。
@anchor{library/sqlite3 registering-an-adapter-callable}@anchor{1edd}
@subsubsection 注册可调用的适配器


另一种可能的做法是创建一个将该类型转换为字符串表示的函数并使用 @ref{1eaf,,register_adapter()} 注册该函数。

@example
import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

def adapt_point(point):
    return "%f;%f" % (point.x, point.y)

sqlite3.register_adapter(Point, adapt_point)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

con.close()
@end example

@ref{f2,,sqlite3} 模块有两个适配器可用于 Python 的内置 @ref{19d,,datetime.date} 和 @ref{19f,,datetime.datetime} 类型。 现在假设我们想要存储 @ref{19f,,datetime.datetime} 对象，但不是表示为 ISO 格式，而是表示为 Unix 时间戳。

@example
import sqlite3
import datetime
import time

def adapt_datetime(ts):
    return time.mktime(ts.timetuple())

sqlite3.register_adapter(datetime.datetime, adapt_datetime)

con = sqlite3.connect(":memory:")
cur = con.cursor()

now = datetime.datetime.now()
cur.execute("select ?", (now,))
print(cur.fetchone()[0])

con.close()
@end example

@node 将SQLite 值转换为自定义Python 类型,默认适配器和转换器,使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,SQLite 与 Python 类型
@anchor{library/sqlite3 converting-sqlite-values-to-custom-python-types}@anchor{1ede}
@subsubsection 将SQLite 值转换为自定义Python 类型


编写适配器让你可以将定制的 Python 类型发送给 SQLite。 但要令它真正有用，我们需要实现从 Python 到 SQLite 再回到 Python 的双向转换。

输入转换器。

让我们回到 @code{Point} 类。 我们以字符串形式在 SQLite 中存储了 x 和 y 坐标值。

首先，我们将定义一个转换器函数，它接受这样的字符串作为形参并根据该参数构造一个 @code{Point} 对象。

@cartouche
@quotation 注解 
转换器函数在调用时 @strong{总是} 会附带一个 @ref{172,,bytes} 对象，无论你将何种数据类型的值发给 SQLite。
@end quotation
@end cartouche

@example
def convert_point(s):
    x, y = map(float, s.split(b";"))
    return Point(x, y)
@end example

现在你需要让 @ref{f2,,sqlite3} 模块知道你从数据库中选取的其实是一个点对象。 有两种方式都可以做到这件事：


@itemize *

@item 
隐式的声明类型

@item 
显式的通过列名
@end itemize

这两种方式会在 @ref{1ea1,,模块函数和常量} 一节中描述，相应条目为 @ref{1ea9,,PARSE_DECLTYPES} 和 @ref{1eaa,,PARSE_COLNAMES} 常量。

下面的示例说明了这两种方法。

@example
import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "(%f;%f)" % (self.x, self.y)

def adapt_point(point):
    return ("%f;%f" % (point.x, point.y)).encode('ascii')

def convert_point(s):
    x, y = list(map(float, s.split(b";")))
    return Point(x, y)

# Register the adapter
sqlite3.register_adapter(Point, adapt_point)

# Register the converter
sqlite3.register_converter("point", convert_point)

p = Point(4.0, -3.2)

#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print("with declared types:", cur.fetchone()[0])
cur.close()
con.close()

#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print("with column names:", cur.fetchone()[0])
cur.close()
con.close()
@end example

@node 默认适配器和转换器,,将SQLite 值转换为自定义Python 类型,SQLite 与 Python 类型
@anchor{library/sqlite3 default-adapters-and-converters}@anchor{1edf}
@subsubsection 默认适配器和转换器


对于 datetime 模块中的 date 和 datetime 类型已提供了默认的适配器。 它们将会以 ISO 日期/ISO 时间戳的形式发给 SQLite。

默认转换器使用的注册名称是针对 @ref{19d,,datetime.date} 的 "date" 和针对 @ref{19f,,datetime.datetime} 的 "timestamp"。

通过这种方式，你可以在大多数情况下使用 Python 的 date/timestamp 对象而无须任何额外处理。 适配器的格式还与实验性的 SQLite date/time 函数兼容。

下面的示例演示了这一点。

@example
import sqlite3
import datetime

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")

today = datetime.date.today()
now = datetime.datetime.now()

cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute("select d, ts from test")
row = cur.fetchone()
print(today, "=>", row[0], type(row[0]))
print(now, "=>", row[1], type(row[1]))

cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
row = cur.fetchone()
print("current_date", row[0], type(row[0]))
print("current_timestamp", row[1], type(row[1]))

con.close()
@end example

如果存储在 SQLite 中的时间戳的小数位多于 6 个数字，则时间戳转换器会将该值截断至微秒精度。

@cartouche
@quotation 注解 
默认的 "时间戳" 转换器忽略了数据库中的 UTC 偏移，总是返回一个原生的 @ref{19f,,datetime.datetime} 对象。要在时间戳中保留 UTC 偏移，可以不使用转换器，或者用 @ref{1ead,,register_converter()} 注册一个偏移感知的转换器。
@end quotation
@end cartouche

@node 控制事务,有效使用 sqlite3,SQLite 与 Python 类型,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 controlling-transactions}@anchor{1ee0}@anchor{library/sqlite3 sqlite3-controlling-transactions}@anchor{1eb4}
@subsubsection 控制事务


底层的 @code{sqlite3} 库默认会以 @code{autocommit} 模式运行，但 Python 的 @ref{f2,,sqlite3} 模块默认则不使用此模式。

@code{autocommit} 模式意味着修改数据库的操作会立即生效。 @code{BEGIN} 或 @code{SAVEPOINT} 语句会禁用 @code{autocommit} 模式，而用于结束外层事务的 @code{COMMIT}, @code{ROLLBACK} 或 @code{RELEASE} 则会恢复 @code{autocommit} 模式。

Python 的 @ref{f2,,sqlite3} 模块默认会在数据修改语言 (DML) 类语句 (即 @code{INSERT}/@code{UPDATE}/@code{DELETE}/@code{REPLACE}) 之前隐式地执行一条 @code{BEGIN} 语句。

你可以控制 @ref{f2,,sqlite3} 隐式执行的 @code{BEGIN} 语句的种类，具体做法是通过将 @emph{isolation_level} 形参传给 @ref{4e9,,connect()} 调用，或者通过指定连接的 @code{isolation_level} 属性。 如果你没有指定 @emph{isolation_level}，将使用基本的 @code{BEGIN}，它等价于指定 @code{DEFERRED}。 其他可能的值为 @code{IMMEDIATE} 和 @code{EXCLUSIVE}。

你可以禁用 @ref{f2,,sqlite3} 模块的隐式事务管理，具体做法是将 @code{isolation_level} 设为 @code{None}。 这将使得下层的 @code{sqlite3} 库采用 @code{autocommit} 模式。 随后你可以通过在代码中显式地使用 @code{BEGIN}, @code{ROLLBACK}, @code{SAVEPOINT} 和 @code{RELEASE} 语句来完全控制事务状态。

请注意 @ref{1ebe,,executescript()} 会忽略 @code{isolation_level}；任何事务控制必要要显式地添加。


在 3.6 版更改: 以前 @ref{f2,,sqlite3} 会在 DDL 语句之前隐式地提交未完成事务。 现在则不会再这样做。


@node 有效使用 sqlite3,,控制事务,sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块
@anchor{library/sqlite3 using-sqlite3-efficiently}@anchor{1ee1}
@subsubsection 有效使用 @code{sqlite3}


@menu
* 使用快捷方式:: 
* 通过名称而不是索引访问索引:: 
* 使用连接作为上下文管理器:: 

@end menu

@node 使用快捷方式,通过名称而不是索引访问索引,,有效使用 sqlite3
@anchor{library/sqlite3 using-shortcut-methods}@anchor{1ee2}
@subsubsection 使用快捷方式


使用 @ref{4e7,,Connection} 对象的非标准 @code{execute()}, @code{executemany()} 和 @code{executescript()} 方法，可以更简洁地编写代码，因为不必显式创建（通常是多余的） @ref{1e9b,,Cursor} 对象。相反， @ref{1e9b,,Cursor} 对象是隐式创建的，这些快捷方法返回游标对象。这样，只需对 @ref{4e7,,Connection} 对象调用一次，就能直接执行 @code{SELECT} 语句并遍历对象。

@example
import sqlite3

langs = [
    ("C++", 1985),
    ("Objective-C", 1984),
]

con = sqlite3.connect(":memory:")

# Create the table
con.execute("create table lang(name, first_appeared)")

# Fill the table
con.executemany("insert into lang(name, first_appeared) values (?, ?)", langs)

# Print the table contents
for row in con.execute("select name, first_appeared from lang"):
    print(row)

print("I just deleted", con.execute("delete from lang").rowcount, "rows")

# close is not a shortcut method and it's not called automatically,
# so the connection object should be closed manually
con.close()
@end example

@node 通过名称而不是索引访问索引,使用连接作为上下文管理器,使用快捷方式,有效使用 sqlite3
@anchor{library/sqlite3 accessing-columns-by-name-instead-of-by-index}@anchor{1ee3}
@subsubsection 通过名称而不是索引访问索引


@ref{f2,,sqlite3} 模块的一个有用功能是内置的 @ref{857,,sqlite3.Row} 类，该类旨在用作行工厂。

该类的行装饰器可以用索引（如元组）和不区分大小写的名称访问：

@example
import sqlite3

con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row

cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
    assert row[0] == row["name"]
    assert row["name"] == row["nAmE"]
    assert row[1] == row["age"]
    assert row[1] == row["AgE"]

con.close()
@end example

@node 使用连接作为上下文管理器,,通过名称而不是索引访问索引,有效使用 sqlite3
@anchor{library/sqlite3 using-the-connection-as-a-context-manager}@anchor{1ee4}
@subsubsection 使用连接作为上下文管理器


连接对象可以用来作为上下文管理器，它可以自动提交或者回滚事务。如果出现异常，事务会被回滚；否则，事务会被提交。

@example
import sqlite3

con = sqlite3.connect(":memory:")
con.execute("create table lang (id integer primary key, name varchar unique)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into lang(name) values (?)", ("Python",))

# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught
try:
    with con:
        con.execute("insert into lang(name) values (?)", ("Python",))
except sqlite3.IntegrityError:
    print("couldn't add Python twice")

# Connection object used as context manager only commits or rollbacks transactions,
# so the connection object should be closed manually
con.close()
@end example

@node 数据压缩和存档,文件格式,数据持久化,Python 标准库
@anchor{library/archiving doc}@anchor{1e4f}@anchor{library/archiving archiving}@anchor{1ee5}@anchor{library/archiving data-compression-and-archiving}@anchor{1ee6}
@section 数据压缩和存档


本章中描述的模块支持 zlib、gzip、bzip2 和 lzma 数据压缩算法，以及创建 ZIP 和 tar 格式的归档文件。参见由 @ref{e9,,shutil} 模块提供的 @ref{c70,,归档操作} 。

@menu
* zlib: zlib --- 与 gzip 兼容的压缩. 与 gzip 兼容的压缩
* gzip: gzip --- 对 gzip 格式的支持. 对 gzip 格式的支持
* bz2: bz2 --- 对 bzip2 压缩算法的支持. 对 bzip2 压缩算法的支持
* lzma: lzma --- 用 LZMA 算法压缩. 用 LZMA 算法压缩
* zipfile: zipfile --- 使用ZIP存档. 使用ZIP存档
* tarfile: tarfile --- 读写tar归档文件. 读写tar归档文件

@end menu

@node zlib --- 与 gzip 兼容的压缩,gzip --- 对 gzip 格式的支持,,数据压缩和存档
@anchor{library/zlib doc}@anchor{1ee7}@anchor{library/zlib module-zlib}@anchor{14d}@anchor{library/zlib zlib-compression-compatible-with-gzip}@anchor{1ee8}
@subsection @code{zlib} --- 与 @code{gzip} 兼容的压缩


@geindex zlib (模块)


__________________________________________________________________


对于需要数据压缩的应用，此模块中的函数允许使用 zlib 库进行压缩和解压缩。 zlib 库的项目主页是 @indicateurl{https://www.zlib.net}。 已知此 Python 模块与 1.1.3 之前版本的 zlib 库存在不兼容；1.1.3 版则存在一个 安全缺陷@footnote{https://zlib.net/zlib_faq.html#faq33}，因此我们推荐使用 1.1.4 或更新的版本。

zlib 的函数有很多选项，一般需要按特定顺序使用。本文档没有覆盖全部的用法。更多详细信息请于 @indicateurl{http://www.zlib.net/manual.html} 参阅官方手册。

要读写 @code{.gz} 格式的文件，请参考 @ref{8b,,gzip} 模块。

此模块中可用的异常和函数如下：

@geindex error
@anchor{library/zlib zlib error}@anchor{1ee9}
@deffn {例外} zlib.error

在压缩或解压缩过程中发生错误时的异常。
@end deffn

@geindex adler32() (在 zlib 模块中)
@anchor{library/zlib zlib adler32}@anchor{1eea}
@deffn {函数} zlib.adler32 (data[, value])

计算 @emph{data} 的 Adler-32 校验值。(Adler-32 校验的可靠性与 CRC32 基本相当，但比计算 CRC32 更高效。) 计算的结果是一个 32 位的整数。参数 @emph{value} 是校验时的起始值，其默认值为 1。借助参数 @emph{value} 可为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。


在 3.0 版更改: 结果值将始终为无符号类型。 要在使用 Python 2 或更早版本时生成同样的数值，请使用 @code{adler32(data) & 0xffffffff}。

@end deffn

@geindex compress() (在 zlib 模块中)
@anchor{library/zlib zlib compress}@anchor{6bf}
@deffn {函数} zlib.compress (data, /, level=-1)

压缩 @emph{data} 中的字节，返回含有已压缩内容的 bytes 对象。参数 @emph{level} 为整数，可取值为 @code{0} 到 @code{9} 或 @code{-1}，用于指定压缩等级。@code{1} (Z_BEST_SPEED) 表示最快速度和最低压缩率，@code{9} (Z_BEST_COMPRESSION) 表示最慢速度和最高压缩率。@code{0} (Z_NO_COMPRESSION) 表示不压缩。参数默认值为 @code{-1} (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压缩率之间的平衡 (一般相当于设压缩等级为 6)。函数发生错误时抛出 @ref{1ee9,,error} 异常。


在 3.6 版更改: 现在，@emph{level} 可作为关键字参数。

@end deffn

@geindex compressobj() (在 zlib 模块中)
@anchor{library/zlib zlib compressobj}@anchor{1eeb}
@deffn {函数} zlib.compressobj (level=-1, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

返回一个 压缩对象，用来压缩内存中难以容下的数据流。

参数 @emph{level} 为压缩等级，是整数，可取值为 @code{0} 到 @code{9} 或 @code{-1}。@code{1} (Z_BEST_SPEED) 表示最快速度和最低压缩率，@code{9} (Z_BEST_COMPRESSION) 表示最慢速度和最高压缩率。@code{0} (Z_NO_COMPRESSION) 表示不压缩。参数默认值为 @code{-1} (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压缩率之间的平衡 (一般相当于设压缩等级为 6)。

@emph{method} 表示压缩算法。现在只支持 @code{DEFLATED} 这个算法。

参数 @emph{wbits} 指定压缩数据时所使用的历史缓冲区的大小 (窗口大小)，并指定压缩输出是否包含头部或尾部。参数的默认值是 @code{15} (MAX_WBITS)。参数的值分为几个范围：


@itemize *

@item 
+9 至 +15：窗口大小以二为底的对数。 即这些值对应着 512 至 32768 的窗口大小。 更大的值会提供更好的压缩，同时内存开销也会更大。 压缩输出会包含 zlib 特定格式的头部和尾部。

@item 
−9 至 −15：绝对值为窗口大小以二为底的对数。 压缩输出仅包含压缩数据，没有头部和尾部。

@item 
+25 至 +31 = 16 + (9 至 15)：后 4 个比特位为窗口大小以二为底的对数。 压缩输出包含一个基本的 @code{gzip} 头部，并以校验和为尾部。
@end itemize

参数 @emph{memLevel} 指定内部压缩操作时所占用内存大小。参数取 @code{1} 到 @code{9}。更大的值占用更多的内存，同时速度也更快输出也更小。

参数 @emph{strategy} 用于调节压缩算法。可取值为  @code{Z_DEFAULT_STRATEGY}、@code{Z_FILTERED}、@code{Z_HUFFMAN_ONLY}、@code{Z_RLE} (zlib 1.2.0.1) 或 @code{Z_FIXED} (zlib 1.2.2.2)。

参数 @emph{zdict} 指定预定义的压缩字典。它是一个字节序列 (如 @ref{172,,bytes} 对象)，其中包含用户认为要压缩的数据中可能频繁出现的子序列。频率高的子序列应当放在字典的尾部。


在 3.3 版更改: 添加关键字参数 @emph{zdict}。

@end deffn

@geindex crc32() (在 zlib 模块中)
@anchor{library/zlib zlib crc32}@anchor{1eec}
@deffn {函数} zlib.crc32 (data[, value])

@geindex Cyclic Redundancy Check
@geindex checksum; Cyclic Redundancy Check

计算 @emph{data} 的 CRC (循环冗余校验) 值。计算的结果是一个 32 位的整数。参数 @emph{value} 是校验时的起始值，其默认值为 0。借助参数 @emph{value} 可为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。


在 3.0 版更改: 结果值将始终为无符号类型。 要在使用 Python 2 或更早版本时生成同样的数值，请使用 @code{crc32(data) & 0xffffffff}。

@end deffn

@geindex decompress() (在 zlib 模块中)
@anchor{library/zlib zlib decompress}@anchor{6c0}
@deffn {函数} zlib.decompress (data, /, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)

解压 @emph{data} 中的字节，返回含有已解压内容的 bytes 对象。参数 @emph{wbits} 取决于 @emph{data} 的格式，具体参见下边的说明。@emph{bufsize} 为输出缓冲区的起始大小。函数发生错误时抛出 @ref{1ee9,,error} 异常。
@anchor{library/zlib decompress-wbits}@anchor{1eed}
@emph{wbits} 形参控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部和尾部格式。 它类似于 @ref{1eeb,,compressobj()} 的形参，但可接受更大范围的值：


@itemize *

@item 
+8 至 +15：窗口尺寸以二为底的对数。 输入必须包含 zlib 头部和尾部。

@item 
0：根据 zlib 头部自动确定窗口大小。 只从 zlib 1.2.3.5 版起受支持。

@item 
−8 至 −15：使用 @emph{wbits} 的绝对值作为窗口大小以二为底的对数。 输入必须为原始数据流，没有头部和尾部。

@item 
+24 至 +31 = 16 + (8 至 15)：使用后 4 个比特位作为窗口大小以二为底的对数。 输入必须包括 gzip 头部和尾部。

@item 
+40 至 +47 = 32 + (8 至 15)：使用后 4 个比特位作为窗口大小以二为底的对数，并且自动接受 zlib 或 gzip 格式。
@end itemize

当解压缩一个数据流时，窗口大小必须不小于用于压缩数据流的原始窗口大小；使用太小的值可能导致 @ref{1ee9,,error} 异常。 默认 @emph{wbits} 值对应于最大的窗口大小并且要求包括 zlib 头部和尾部。

@emph{bufsize} 是用于存放解压数据的缓冲区初始大小。 如果需要更大空间，缓冲区大小将按需增加，因此你不需要让这个值完全精确；对其进行调整仅会节省一点对 @code{malloc()} 的调用次数。


在 3.6 版更改: @emph{wbits} 和 @emph{bufsize} 可用作关键字参数。

@end deffn

@geindex decompressobj() (在 zlib 模块中)
@anchor{library/zlib zlib decompressobj}@anchor{1eee}
@deffn {函数} zlib.decompressobj (wbits=MAX_WBITS[, zdict])

返回一个解压对象，用来解压无法被一次性放入内存的数据流。

@emph{wbits} 形参控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部和尾部格式。 它的含义与 @ref{1eed,,对 decompress() 的描述} 相同。

@emph{zdict} 形参指定指定一个预定义的压缩字典。 如果提供了此形参，它必须与产生将解压数据的压缩器所使用的字典相同。

@cartouche
@quotation 注解 
如果 @emph{zdict} 是一个可变对象 (例如 @ref{173,,bytearray})，则你不可在对 @ref{1eee,,decompressobj()} 的调用和对解压器的 @code{decompress()} 方法的调用之间修改其内容。
@end quotation
@end cartouche


在 3.3 版更改: 增加了 @emph{zdict} 形参。

@end deffn

压缩对象支持以下方法：

@geindex compress() (zlib.Compress 方法)
@anchor{library/zlib zlib Compress compress}@anchor{1eef}
@deffn {方法} Compress.compress (data)

压缩 @emph{data} 并返回 bytes 对象，这个对象含有 @emph{data} 的部分或全部内容的已压缩数据。所得的对象必须拼接在上一次调用 @ref{6bf,,compress()} 方法所得数据的后面。缓冲区中可能留存部分输入以供下一次调用。
@end deffn

@geindex flush() (zlib.Compress 方法)
@anchor{library/zlib zlib Compress flush}@anchor{1ef0}
@deffn {方法} Compress.flush ([mode])

压缩所有缓冲区的数据并返回已压缩的数据。参数 @emph{mode} 可以传入的常量为：@code{Z_NO_FLUSH}、@code{Z_PARTIAL_FLUSH}、@code{Z_SYNC_FLUSH}、@code{Z_FULL_FLUSH}、@code{Z_BLOCK} (zlib 1.2.3.4) 或 @code{Z_FINISH}。默认值为 @code{Z_FINISH}。@code{Z_FINISH} 关闭已压缩数据流并不允许再压缩其他数据，@code{Z_FINISH}  以外的值皆允许这个对象继续压缩数据。调用 @ref{1ef0,,flush()} 方法并将 @emph{mode} 设为 @code{Z_FINISH} 后会无法再次调用 @ref{6bf,,compress()}，此时只能删除这个对象。
@end deffn

@geindex copy() (zlib.Compress 方法)
@anchor{library/zlib zlib Compress copy}@anchor{1ef1}
@deffn {方法} Compress.copy ()

返回此压缩对象的一个拷贝。它可以用来高效压缩一系列拥有相同前缀的数据。
@end deffn


在 3.8 版更改: 添加了对压缩对象执行 @ref{4da,,copy.copy()} 和 @ref{4db,,copy.deepcopy()} 的支持。


解压缩对象支持以下方法：

@geindex unused_data (zlib.Decompress 属性)
@anchor{library/zlib zlib Decompress unused_data}@anchor{1ef2}
@deffn {属性} Decompress.unused_data

一个 bytes 对象，其中包含压缩数据结束之后的任何字节数据。 也就是说，它将为 @code{b""} 直到包含压缩数据的末尾字节可用。 如果整个结果字节串都包含压缩数据，它将为一个空的 bytes 对象 @code{b""}。
@end deffn

@geindex unconsumed_tail (zlib.Decompress 属性)
@anchor{library/zlib zlib Decompress unconsumed_tail}@anchor{1ef3}
@deffn {属性} Decompress.unconsumed_tail

一个 bytes 对象，其中包含未被上一次 @ref{6c0,,decompress()} 调用所消耗的任何数据。 此数据不能被 zlib 机制看到，因此你必须将其送回（可能要附带额外的数据拼接）到后续的 @ref{6c0,,decompress()} 方法调用以获得正确的输出。
@end deffn

@geindex eof (zlib.Decompress 属性)
@anchor{library/zlib zlib Decompress eof}@anchor{ba6}
@deffn {属性} Decompress.eof

一个布尔值，指明是否已到达压缩数据流的末尾。

这使得区分正确构造的压缩数据流和不完整或被截断的压缩数据流成为可能。


3.3 新版功能.

@end deffn

@geindex decompress() (zlib.Decompress 方法)
@anchor{library/zlib zlib Decompress decompress}@anchor{1ef4}
@deffn {方法} Decompress.decompress (data, max_length=0)

解压缩 @emph{data} 并返回 bytes 对象，其中包含对应于 @emph{string} 中至少一部分数据的解压缩数据。 此数据应当被拼接到之前任何对 @ref{6c0,,decompress()} 方法的调用所产生的输出。 部分输入数据可能会被保留在内部缓冲区以供后续处理。

如果可选的形参 @emph{max_length} 非零则返回值将不会长于 @emph{max_length}。 这可能意味着不是所有已压缩输入都能被处理；并且未被消耗的数据将被保存在 @ref{1ef3,,unconsumed_tail} 属性中。 如果要继续解压缩则这个字节串必须被传给对 @ref{6c0,,decompress()} 的后续调用。 如果 @emph{max_length} 为零则整个输入都会被解压缩，并且 @ref{1ef3,,unconsumed_tail} 将为空。


在 3.6 版更改: @emph{max_length} 可用作关键字参数。

@end deffn

@geindex flush() (zlib.Decompress 方法)
@anchor{library/zlib zlib Decompress flush}@anchor{1ef5}
@deffn {方法} Decompress.flush ([length])

所有挂起的输入会被处理，并且返回包含剩余未压缩输出的 bytes 对象。 在调用 @ref{1ef5,,flush()} 之后，@ref{6c0,,decompress()} 方法将无法被再次调用；唯一可行的操作是删除该对象。

可选的形参 @emph{length} 设置输出缓冲区的初始大小。
@end deffn

@geindex copy() (zlib.Decompress 方法)
@anchor{library/zlib zlib Decompress copy}@anchor{1ef6}
@deffn {方法} Decompress.copy ()

返回解压缩对象的一个拷贝。 它可以用来在数据流的中途保存解压缩器的状态以便加快随机查找数据流后续位置的速度。
@end deffn


在 3.8 版更改: 添加了对解压缩对象执行 @ref{4da,,copy.copy()} 和 @ref{4db,,copy.deepcopy()} 的支持。


通过下列常量可获取模块所使用的 zlib 库的版本信息：

@geindex ZLIB_VERSION() (在 zlib 模块中)
@anchor{library/zlib zlib ZLIB_VERSION}@anchor{1ef7}
@deffn {数据} zlib.ZLIB_VERSION

构建此模块时所用的 zlib 库的版本字符串。它的值可能与运行时所加载的 zlib 不同。运行时加载的 zlib 库的版本字符串为 @ref{ba7,,ZLIB_RUNTIME_VERSION}。
@end deffn

@geindex ZLIB_RUNTIME_VERSION() (在 zlib 模块中)
@anchor{library/zlib zlib ZLIB_RUNTIME_VERSION}@anchor{ba7}
@deffn {数据} zlib.ZLIB_RUNTIME_VERSION

解释器所加载的 zlib 库的版本字符串。


3.3 新版功能.

@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{8b,,gzip}

读写 @code{gzip} 格式的文件。

@item @indicateurl{http://www.zlib.net}

zlib 库项目主页。

@item @indicateurl{http://www.zlib.net/manual.html}

zlib 库用户手册。提供了库的许多功能的解释和用法。
@end table


@node gzip --- 对 gzip 格式的支持,bz2 --- 对 bzip2 压缩算法的支持,zlib --- 与 gzip 兼容的压缩,数据压缩和存档
@anchor{library/gzip doc}@anchor{1ef8}@anchor{library/gzip gzip-support-for-gzip-files}@anchor{1ef9}@anchor{library/gzip module-gzip}@anchor{8b}
@subsection @code{gzip} --- 对 @code{gzip} 格式的支持


@geindex gzip (模块)

@strong{源代码：} Lib/gzip.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/gzip.py}


__________________________________________________________________


此模块提供的简单接口帮助用户压缩和解压缩文件，功能类似于 GNU 应用程序 @code{gzip} 和 @code{gunzip}。

数据压缩由 @ref{14d,,zlib} 模块提供。

@ref{8b,,gzip} 模块提供 @ref{207,,GzipFile} 类和 @ref{1efa,,open()}、@ref{309,,compress()}、@ref{c63,,decompress()} 几个便利的函数。@ref{207,,GzipFile} 类可以读写 @code{gzip} 格式的文件，还能自动压缩和解压缩数据，这让操作压缩文件如同操作普通的 @ref{c1d,,file object} 一样方便。

注意，此模块不支持部分可以被 @code{gzip} 和 @code{gunzip} 解压的格式，如利用 @code{compress} 或 @code{pack} 压缩所得的文件。

这个模块定义了以下内容：

@geindex open() (在 gzip 模块中)
@anchor{library/gzip gzip open}@anchor{1efa}
@deffn {函数} gzip.open (filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

以二进制方式或者文本方式打开一个 gzip 格式的压缩文件，返回一个 @ref{c1d,,file object}。

@emph{filename} 参数可以是一个实际的文件名（一个 @ref{206,,str} 对象或者 @ref{172,,bytes} 对象），或者是一个用来读写的已存在的文件对象。

@emph{mode} 参数可以是二进制模式： @code{'r'}, @code{'rb'}, @code{'a'}, @code{'ab'}, @code{'w'}, @code{'wb'}, @code{'x'} or @code{'xb'} , 或者是文本模式 @code{'rt'}, @code{'at'}, @code{'wt'}, or @code{'xt'}。默认值是 @code{'rb'}。

The @emph{compresslevel} argument is an integer from 0 to 9, as for the
@ref{207,,GzipFile} constructor.

对于二进制模式，这个函数等价于 @ref{207,,GzipFile} 构造器：@code{GzipFile(filename, mode, compresslevel)}。在这个例子中，@emph{encoding}, @emph{errors} 和 @emph{newline} 三个参数一定不要设置。

对于文本模式，将会创建一个 @ref{207,,GzipFile} 对象，并将它封装到一个 @ref{6f4,,io.TextIOWrapper} 实例中， 这个实例默认了指定编码，错误抓获行为和行。


在 3.3 版更改: 支持 @emph{filename} 为一个文件对象，支持文本模式和 @emph{encoding}, @emph{errors} 和 @emph{newline} 参数。



在 3.4 版更改: 支持 @code{'x'}, @code{'xb'} 和`@w{`}'xt'`@w{`} 三种模式。



在 3.6 版更改: 接受一个 @ref{47b,,path-like object}。

@end deffn

@geindex BadGzipFile
@anchor{library/gzip gzip BadGzipFile}@anchor{30a}
@deffn {例外} gzip.BadGzipFile

针对无效 gzip 文件引发的异常。 它继承自 @ref{30b,,OSError}。 针对无效 gzip 文件也可能引发 @ref{d3c,,EOFError} 和 @ref{1ee9,,zlib.error}。


3.8 新版功能.

@end deffn

@geindex GzipFile (gzip 中的类)
@anchor{library/gzip gzip GzipFile}@anchor{207}
@deffn {类} gzip.GzipFile (filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

@ref{207,,GzipFile} 类的构造器支持 @code{truncate()} 的异常，与 @ref{c1d,,file object} 的大多数方法非常相似。@emph{fileobj} 和 @emph{filename} 至少有一个不为空。

新的实例基于  @emph{fileobj}，它可以是一个普通文件，一个 @ref{894,,io.BytesIO} 对象，或者任何一个与文件相似的对象。当 @emph{filename} 是一个文件对象时，它的默认值是 @code{None}。

当  @emph{fileobj} 为 @code{None} 时， @emph{filename} 参数只用于  @code{gzip} 文件头中，这个文件有可能包含未压缩文件的源文件名。如果文件可以被识别，默认 @emph{fileobj} 的文件名；否则默认为空字符串，在这种情况下文件头将不包含源文件名。

@emph{mode} 参数可以是 @code{'r'}, @code{'rb'}, @code{'a'}, @code{'ab'}, @code{'w'}, @code{'wb'}, @code{'x'} 或 @code{'xb'} 中的一个，具体取决于文件将被读取还是被写入。 如果可识别则默认为 @emph{fileobj} 的模式；否则默认为 @code{'rb'}。 在未来的 Python 发布版中将不再使用 @emph{fileobj} 的模式。 最好总是指定 @emph{mode} 为写入模式。

需要注意的是，文件默认使用二进制模式打开。 如果要以文本模式打开一个压缩文件，请使用 @ref{1efa,,open()} 方法 (或者使用 @ref{6f4,,io.TextIOWrapper} 包装 @ref{207,,GzipFile})。

@emph{compresslevel} 参数是一个从 @code{0} 到 @code{9} 的整数，用于控制压缩等级；@code{1} 最快但压缩比例最小，@code{9} 最慢但压缩比例最大。 @code{0} 不压缩。默认为 @code{9}。

@emph{mtime} 参数是一个可选的数字时间戳用于写入流的最后修改字段，。@emph{mtime} 只在压缩模式中使用。如果省略或者值为 @code{None}，则使用当前时间。更多细节，详见 @ref{1efb,,mtime} 属性。

调用 @ref{207,,GzipFile} 的 @code{close()} 方法不会关闭 @emph{fileobj}，因为你可以希望增加其它内容到已经压缩的数中。你可以将一个 @ref{894,,io.BytesIO} 对象作为 @emph{fileobj}，也可以使用 @ref{894,,io.BytesIO} 的 @ref{1efc,,getvalue()} 方法从内存缓存中恢复数据。

@ref{207,,GzipFile} 支持 @ref{689,,io.BufferedIOBase} 类的接口, 包括迭代和 @ref{7e4,,with} 语句。只有 @code{truncate()} 方法没有实现。

@ref{207,,GzipFile} 还提供了以下的方法和属性:

@geindex peek() (gzip.GzipFile 方法)
@anchor{library/gzip gzip GzipFile peek}@anchor{c62}
@deffn {方法} peek (n)

在不移动文件指针的情况下读取  @emph{n} 个未压缩字节。最多只有一个单独的读取流来服务这个方法调用。返回的字节数不一定刚好等于要求的数量。

@cartouche
@quotation 注解 
调用 @ref{c62,,peek()} 并没有改变 @ref{207,,GzipFile} 的文件指针，它可能改变潜在文件对象(例如： @ref{207,,GzipFile} 使用 @emph{fileobj} 参数进行初始化)。
@end quotation
@end cartouche


3.2 新版功能.

@end deffn

@geindex mtime (gzip.GzipFile 属性)
@anchor{library/gzip gzip GzipFile mtime}@anchor{1efb}
@deffn {属性} mtime

在解压的过程中，最后修改时间字段的值可能来自于这个属性，以整数的形式出现。在读取任何文件头信息前，初始值为 @code{None}。

所有 @code{gzip} 东方压缩流中必须包含时间戳这个字段。以便于像 @code{gunzip}这样的程序可以使用时间戳。格式与 @ref{436,,time.time()} 的返回值和  @ref{328,,os.stat()} 对象的 @ref{1efd,,st_mtime} 属性值一样。
@end deffn


在 3.1 版更改: 支持 @ref{7e4,,with} 语句，构造器参数 @emph{mtime} 和  @ref{1efb,,mtime} 属性。



在 3.2 版更改: 添加了对零填充和不可搜索文件的支持。



在 3.3 版更改: 实现 @ref{1efe,,io.BufferedIOBase.read1()}  方法。



在 3.4 版更改: 支持 @code{'x'} and @code{'xb'} 两种模式。



在 3.5 版更改: 支持写入任意 @ref{6e9,,bytes-like objects}。@ref{1eff,,read()} 方法可以接受`@w{`}None`@w{`}为参数。



在 3.6 版更改: 接受一个 @ref{47b,,path-like object}。



3.9 版后已移除: 打开 @ref{207,,GzipFile} 用于写入而不指定 @emph{mode} 参数的做法已被弃用。

@end deffn

@geindex compress() (在 gzip 模块中)
@anchor{library/gzip gzip compress}@anchor{309}
@deffn {函数} gzip.compress (data, compresslevel=9, *, mtime=None)

压缩 @emph{data}，返回一个包含压缩数据的 @ref{172,,bytes} 对象。 @emph{compresslevel} 和 @emph{mtime} 的含义与上文中 @ref{207,,GzipFile} 构造器的相同。


3.2 新版功能.



在 3.8 版更改: 添加了 @emph{mtime} 形参用于可重复的输出。

@end deffn

@geindex decompress() (在 gzip 模块中)
@anchor{library/gzip gzip decompress}@anchor{c63}
@deffn {函数} gzip.decompress (data)

解压缩 @emph{data}，返回一个包含未压缩数据的 @ref{172,,bytes} 对象。


3.2 新版功能.

@end deffn

@menu
* 用法示例:: 
* 命令行界面:: 

@end menu

@node 用法示例,命令行界面,,gzip --- 对 gzip 格式的支持
@anchor{library/gzip examples-of-usage}@anchor{1f00}@anchor{library/gzip gzip-usage-examples}@anchor{1f01}
@subsubsection 用法示例


读取压缩文件示例：

@example
import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()
@end example

创建GZIP 文件示例：

@example
import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)
@end example

使用 GZIP 压缩已有的文件示例：

@example
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
@end example

使用 GZIP 压缩二进制字符串示例：

@example
import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{14d,,zlib}

支持 @code{gzip} 格式所需要的基本压缩模块。
@end table


@node 命令行界面,,用法示例,gzip --- 对 gzip 格式的支持
@anchor{library/gzip command-line-interface}@anchor{1f02}
@subsubsection 命令行界面


@ref{8b,,gzip} 模块提供了简单的命令行界面用于压缩和解压缩文件。

在执行后 @ref{8b,,gzip} 模块会保留输入文件。


在 3.8 版更改: 添加一个带有用法说明的新命令行界面命令。 默认情况下，当你要执行 CLI 时，默认压缩等级为 6。


@menu
* 命令行选项:: 

@end menu

@node 命令行选项,,,命令行界面
@anchor{library/gzip command-line-options}@anchor{1f03}
@subsubsection 命令行选项


@geindex gzip command line option; file
@anchor{library/gzip cmdoption-gzip-arg-file}@anchor{1f04}
@deffn {程序选项} file

如果 @emph{file} 未指定，则从 @ref{427,,sys.stdin} 读取。
@end deffn

@geindex gzip command line option; --fast
@anchor{library/gzip cmdoption-gzip-fast}@anchor{1f05}
@deffn {程序选项} @w{-}@w{-}fast

指明最快速的压缩方法（较低压缩率）。
@end deffn

@geindex gzip command line option; --best
@anchor{library/gzip cmdoption-gzip-best}@anchor{1f06}
@deffn {程序选项} @w{-}@w{-}best

指明最慢速的压缩方法（最高压缩率）。
@end deffn

@geindex gzip command line option; -d
@geindex gzip command line option; --decompress
@anchor{library/gzip cmdoption-gzip-d}@anchor{1f07}
@deffn {程序选项} @w{-}d, @w{-}@w{-}decompress

解压缩给定的文件。
@end deffn

@geindex gzip command line option; -h
@geindex gzip command line option; --help
@anchor{library/gzip cmdoption-gzip-h}@anchor{1f08}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

显示帮助消息。
@end deffn

@node bz2 --- 对 bzip2 压缩算法的支持,lzma --- 用 LZMA 算法压缩,gzip --- 对 gzip 格式的支持,数据压缩和存档
@anchor{library/bz2 doc}@anchor{1f09}@anchor{library/bz2 bz2-support-for-bzip2-compression}@anchor{1f0a}@anchor{library/bz2 module-bz2}@anchor{13}
@subsection @code{bz2} --- 对 @code{bzip2} 压缩算法的支持


@geindex bz2 (模块)

@strong{源代码：} Lib/bz2.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/bz2.py}


__________________________________________________________________


此模块提供了使用 bzip2 压缩算法压缩和解压数据的一套完整的接口。

@ref{13,,bz2} 模块包含：


@itemize *

@item 
用于读写压缩文件的 @ref{abe,,open()} 函数和 @ref{225,,BZ2File} 类。

@item 
用于增量压缩和解压的 @ref{1f0b,,BZ2Compressor} 和 @ref{1f0c,,BZ2Decompressor} 类。

@item 
用于一次性压缩和解压的 @ref{1a01,,compress()} 和 @ref{abf,,decompress()} 函数。
@end itemize

此模块中的所有类都能安全地从多个线程访问。

@menu
* 文件压缩和解压:: 
* 增量压缩和解压:: 
* 一次性压缩或解压缩:: 
* 用法示例: 用法示例<2>. 

@end menu

@node 文件压缩和解压,增量压缩和解压,,bz2 --- 对 bzip2 压缩算法的支持
@anchor{library/bz2 de-compression-of-files}@anchor{1f0d}
@subsubsection 文件压缩和解压


@geindex open() (在 bz2 模块中)
@anchor{library/bz2 bz2 open}@anchor{abe}
@deffn {函数} bz2.open (filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

以二进制或文本模式打开 bzip2 压缩文件，返回一个 @ref{c1d,,file object}。

和 @ref{225,,BZ2File} 的构造函数类似，@emph{filename} 参数可以是一个实际的文件名（@ref{206,,str} 或 @ref{172,,bytes} 对象），或是已有的可供读取或写入的文件对象。

@emph{mode} 参数可设为二进制模式的 @code{'r'}、@code{'rb'}、@code{'w'}、@code{'wb'}、@code{'x'}、@code{'xb'}、@code{'a'} 或 @code{'ab'}，或者文本模式的 @code{'rt'}、@code{'wt'}、@code{'xt'} 或 @code{'at'}。默认是 @code{'rb'}。

@emph{compresslevel} 参数是 1 到 9 的整数，和 @ref{225,,BZ2File} 的构造函数一样。

对于二进制模式，这个函数等价于 @ref{225,,BZ2File} 构造器: @code{BZ2File(filename, mode, compresslevel=compresslevel)}。 在这种情况下，不可提供 @emph{encoding}, @emph{errors} 和 @emph{newline} 参数。

对于文本模式，将会创建一个 @ref{225,,BZ2File} 对象，并将它包装到一个 @ref{6f4,,io.TextIOWrapper} 实例中，此实例带有指定的编码格式、错误处理行为和行结束符。


3.3 新版功能.



在 3.4 版更改: 添加了 @code{'x'} (单独创建) 模式。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex BZ2File (bz2 中的类)
@anchor{library/bz2 bz2 BZ2File}@anchor{225}
@deffn {类} bz2.BZ2File (filename, mode='r', *, compresslevel=9)

用二进制模式打开 bzip2 压缩文件。

如果 @emph{filename} 是一个 @ref{206,,str} 或 @ref{172,,bytes} 对象，则打开名称对应的文件目录。 否则的话，@emph{filename} 应当是一个 @ref{c1d,,file object}，它将被用来读取或写入压缩数据。

@emph{mode} 参数可以是表示读取的 @code{'r'} (默认值)，表示覆写的 @code{'w'}，表示单独创建的 @code{'x'}，或表示添加的 @code{'a'}。 这些模式还可分别以 @code{'rb'}, @code{'wb'}, @code{'xb'} 和 @code{'ab'} 的等价形式给出。

如果 @emph{filename} 是一个文件对象（而不是实际的文件名），则 @code{'w'} 模式并不会截断文件，而是会等价于 @code{'a'}。

如果 @emph{mode} 为 @code{'w'} 或 @code{'a'}，则 @emph{compresslevel} 可以是 @code{1} 到 @code{9} 之间的整数，用于指定压缩等级: @code{1} 产生最低压缩率，而 @code{9} (默认值) 产生最高压缩率。

如果 @emph{mode} 为 @code{'r'}，则输入文件可以为多个压缩流的拼接。

@ref{225,,BZ2File} 提供了 @ref{689,,io.BufferedIOBase} 所指定的所有成员，但 @code{detach()} 和 @code{truncate()} 除外。 并支持迭代和 @ref{7e4,,with} 语句。

@ref{225,,BZ2File} 还提供了以下方法：

@geindex peek() (bz2.BZ2File 方法)
@anchor{library/bz2 bz2 BZ2File peek}@anchor{1f0e}
@deffn {方法} peek ([n])

返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据（除非为 EOF）。 实际返回的字节数不确定。

@cartouche
@quotation 注解 
虽然调用 @ref{1f0e,,peek()} 不会改变 @ref{225,,BZ2File} 的文件位置，但它可能改变下层文件对象的位置（举例来说如果 @ref{225,,BZ2File} 是通过传入一个文件对象作为 @emph{filename} 的话）。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn


在 3.1 版更改: 添加了对 @ref{7e4,,with} 语句的支持。



在 3.3 版更改: 添加了 @code{fileno()}, @code{readable()}, @code{seekable()}, @code{writable()}, @code{read1()} 和 @code{readinto()} 方法。



在 3.3 版更改: 添加了对 @emph{filename} 使用 @ref{c1d,,file object} 而非实际文件名的支持。



在 3.3 版更改: 添加了 @code{'a'} (append) 模式，以及对读取多数据流文件的支持。



在 3.4 版更改: 添加了 @code{'x'} (单独创建) 模式。



在 3.5 版更改: @ref{1eff,,read()} 方法现在接受 @code{None} 作为参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.9 版更改: @emph{buffering} 形参已被移除。 它自 Python 3.0 起即被忽略并弃用。 请传入一个打开文件对象来控制文件的打开方式。

@emph{compresslevel} 形参成为仅限关键字参数。

@end deffn

@node 增量压缩和解压,一次性压缩或解压缩,文件压缩和解压,bz2 --- 对 bzip2 压缩算法的支持
@anchor{library/bz2 incremental-de-compression}@anchor{1f0f}
@subsubsection 增量压缩和解压


@geindex BZ2Compressor (bz2 中的类)
@anchor{library/bz2 bz2 BZ2Compressor}@anchor{1f0b}
@deffn {类} bz2.BZ2Compressor (compresslevel=9)

创建一个新的压缩器对象。 此对象可被用来执行增量数据压缩。 对于一次性压缩，请改用 @ref{1a01,,compress()} 函数。

如果给定 @emph{compresslevel}，它必须为 @code{1} 至 @code{9} 之间的整数。 默认值为 @code{9}。

@geindex compress() (bz2.BZ2Compressor 方法)
@anchor{library/bz2 bz2 BZ2Compressor compress}@anchor{1f10}
@deffn {方法} compress (data)

向压缩器对象提供数据。 在可能的情况下返回一段已压缩数据，否则返回空字节串。

当你已结束向压缩器提供数据时，请调用 @ref{1f11,,flush()} 方法来完成压缩进程。
@end deffn

@geindex flush() (bz2.BZ2Compressor 方法)
@anchor{library/bz2 bz2 BZ2Compressor flush}@anchor{1f11}
@deffn {方法} flush ()

结束压缩进程，返回内部缓冲中剩余的压缩完成的数据。

调用此方法之后压缩器对象将不可再被使用。
@end deffn
@end deffn

@geindex BZ2Decompressor (bz2 中的类)
@anchor{library/bz2 bz2 BZ2Decompressor}@anchor{1f0c}
@deffn {类} bz2.BZ2Decompressor

创建一个新的解压缩器对象。 此对象可被用来执行增量数据解压缩。 对于一次性解压缩，请改用 @ref{abf,,decompress()} 函数。

@cartouche
@quotation 注解 
这个类不会透明地处理包含多个已压缩数据流的输入，这不同于 @ref{abf,,decompress()} 和 @ref{225,,BZ2File}。 如果你需要通过 @ref{1f0c,,BZ2Decompressor} 来解压缩多个数据流输入，你必须为每个数据流都使用新的解压缩器。
@end quotation
@end cartouche

@geindex decompress() (bz2.BZ2Decompressor 方法)
@anchor{library/bz2 bz2 BZ2Decompressor decompress}@anchor{7a0}
@deffn {方法} decompress (data, max_length=-1)

解压缩 @emph{data} (一个 @ref{6e9,,bytes-like object})，返回字节串形式的解压缩数据。 某些 @emph{data} 可以在内部被缓冲，以便用于后续的 @ref{abf,,decompress()} 调用。 返回的数据应当与之前任何 @ref{abf,,decompress()} 调用的输出进行拼接。

如果 @emph{max_length} 为非负数，将返回至多 @emph{max_length} 个字节的解压缩数据。 如果达到此限制并且可以产生后续输出，则 @ref{1f12,,needs_input} 属性将被设为 @code{False}。 在这种情况下，下一次 @ref{7a0,,decompress()} 调用提供的 @emph{data} 可以为 @code{b'@w{'}} 以获取更多的输出。

如果所有输入数据都已被解压缩并返回（或是因为它少于 @emph{max_length} 个字节，或是因为 @emph{max_length} 为负数），则 @ref{1f12,,needs_input} 属性将被设为 @code{True}。

在到达数据流末尾之后再尝试解压缩数据会引发 @cite{EOFError}。 在数据流末尾之后获取的任何数据都会被忽略并存储至 @ref{1f13,,unused_data} 属性。


在 3.5 版更改: 添加了 @emph{max_length} 形参。

@end deffn

@geindex eof (bz2.BZ2Decompressor 属性)
@anchor{library/bz2 bz2 BZ2Decompressor eof}@anchor{1f14}
@deffn {属性} eof

若达到了数据流的末尾标记则为 @code{True}。


3.3 新版功能.

@end deffn

@geindex unused_data (bz2.BZ2Decompressor 属性)
@anchor{library/bz2 bz2 BZ2Decompressor unused_data}@anchor{1f13}
@deffn {属性} unused_data

在压缩数据流的末尾之后获取的数据。

如果在达到数据流末尾之前访问此属性，其值将为 @code{b'@w{'}}。
@end deffn

@geindex needs_input (bz2.BZ2Decompressor 属性)
@anchor{library/bz2 bz2 BZ2Decompressor needs_input}@anchor{1f12}
@deffn {属性} needs_input

如果在要求新的未解压缩输入之前 @ref{7a0,,decompress()} 方法可以提供更多的解压缩数据则为 @code{False}。


3.5 新版功能.

@end deffn
@end deffn

@node 一次性压缩或解压缩,用法示例<2>,增量压缩和解压,bz2 --- 对 bzip2 压缩算法的支持
@anchor{library/bz2 one-shot-de-compression}@anchor{1f15}
@subsubsection 一次性压缩或解压缩


@geindex compress() (在 bz2 模块中)
@anchor{library/bz2 bz2 compress}@anchor{1a01}
@deffn {函数} bz2.compress (data, compresslevel=9)

压缩 @emph{data}，此参数为一个 @ref{6e9,,字节类对象}。

如果给定 @emph{compresslevel}，它必须为 @code{1} 至 @code{9} 之间的整数。 默认值为 @code{9}。

对于增量压缩，请改用 @ref{1f0b,,BZ2Compressor}。
@end deffn

@geindex decompress() (在 bz2 模块中)
@anchor{library/bz2 bz2 decompress}@anchor{abf}
@deffn {函数} bz2.decompress (data)

解压缩 @emph{data}，此参数为一个 @ref{6e9,,字节类对象}。

如果 @emph{data} 是多个压缩数据流的拼接，则解压缩所有数据流。

对于增量解压缩，请改用 @ref{1f0c,,BZ2Decompressor}。


在 3.3 版更改: 支持了多数据流的输入。

@end deffn

@node 用法示例<2>,,一次性压缩或解压缩,bz2 --- 对 bzip2 压缩算法的支持
@anchor{library/bz2 bz2-usage-examples}@anchor{1f16}@anchor{library/bz2 examples-of-usage}@anchor{1f17}
@subsubsection 用法示例


以下是 @ref{13,,bz2} 模块典型用法的一些示例。

使用 @ref{1a01,,compress()} 和 @ref{abf,,decompress()} 来显示往复式的压缩：

@example
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True
@end example

使用 @ref{1f0b,,BZ2Compressor} 进行增量压缩：

@example
>>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()
@end example

上面的示例使用了十分“非随机”的数据流（即 @cite{b"z"} 块数据流）。 随机数据的压缩率通常很差，而有序、重复的数据通常会产生很高的压缩率。

用二进制模式写入和读取 bzip2 压缩文件：

@example
>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()
>>> content == data  # Check equality to original object after round-trip
True
@end example

@c import os
@c os.remove("myfile.bz2")

@node lzma --- 用 LZMA 算法压缩,zipfile --- 使用ZIP存档,bz2 --- 对 bzip2 压缩算法的支持,数据压缩和存档
@anchor{library/lzma doc}@anchor{1f18}@anchor{library/lzma lzma-compression-using-the-lzma-algorithm}@anchor{1f19}@anchor{library/lzma module-lzma}@anchor{ad}
@subsection @code{lzma} --- 用 LZMA 算法压缩


@geindex lzma (模块)


3.3 新版功能.


@strong{源代码：} Lib/lzma.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/lzma.py}


__________________________________________________________________


此模块提供了可以压缩和解压缩使用 LZMA 压缩算法的数据的类和便携函数。 其中还包含支持 @code{xz} 工具所使用的 @code{.xz} 和旧式 @code{.lzma} 文件格式的文件接口，以及相应的原始压缩数据流。

此模块所提供的接口与 @ref{13,,bz2} 模块的非常类似。 但是，请注意 @ref{a1f,,LZMAFile} @emph{不是} 线程安全的，这与 @ref{225,,bz2.BZ2File} 不同，因此如果你需要在多个线程中使用单个 @ref{a1f,,LZMAFile} 实例，则需要通过锁来保护它。

@geindex LZMAError
@anchor{library/lzma lzma LZMAError}@anchor{1f1a}
@deffn {例外} lzma.LZMAError

当在压缩或解压缩期间或是在初始化压缩器/解压缩器的状态期间发生错误时此异常会被引发。
@end deffn

@menu
* 读写压缩文件:: 
* 在内存中压缩和解压缩数据:: 
* 杂项: 杂项<2>. 
* 指定自定义的过滤器链:: 
* 示例: 示例<11>. 

@end menu

@node 读写压缩文件,在内存中压缩和解压缩数据,,lzma --- 用 LZMA 算法压缩
@anchor{library/lzma reading-and-writing-compressed-files}@anchor{1f1b}
@subsubsection 读写压缩文件


@geindex open() (在 lzma 模块中)
@anchor{library/lzma lzma open}@anchor{1f1c}
@deffn {函数} lzma.open (filename, mode="rb", *, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None)

以二进制或文本模式打开 LZMA 压缩文件，返回一个 @ref{c1d,,file object}。

@emph{filename} 参数可以是一个实际的文件名（以 @ref{206,,str}, @ref{172,,bytes} 或 @ref{47b,,路径类} 对象的形式给出），在此情况下会打开指定名称的文件，或者可以是一个用于读写的现有文件对象。

@emph{mode} 参数可以是二进制模式的 @code{"r"}, @code{"rb"}, @code{"w"}, @code{"wb"}, @code{"x"}, @code{"xb"}, @code{"a"} 或 @code{"ab"}，或者文本模式的 @code{"rt"}, @code{"wt"}, @code{"xt"} 或 @code{"at"}。 默认值为 @code{"rb"}。

当打开一个文件用于读取时，@emph{format} 和 @emph{filters} 参数具有与 @ref{1f1d,,LZMADecompressor} 的参数相同的含义。 在此情况下，@emph{check} 和 @emph{preset} 参数不应被使用。

当打开一个文件用于写入的，@emph{format}, @emph{check}, @emph{preset} 和 @emph{filters} 参数具有与 @ref{1f1e,,LZMACompressor} 的参数相同的含义。

对于二进制模式，这个函数等价于 @ref{a1f,,LZMAFile} 构造器: @code{LZMAFile(filename, mode, ...)}。 在这种情况下，不可提供 @emph{encoding}, @emph{errors} 和 @emph{newline} 参数。

对于文本模式，将会创建一个 @ref{a1f,,LZMAFile} 对象，并将它包装到一个 @ref{6f4,,io.TextIOWrapper} 实例中，此实例带有指定的编码格式、错误处理行为和行结束符。


在 3.4 版更改: 增加了对 @code{"x"}, @code{"xb"} 和 @code{"xt"} 模式的支持。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex LZMAFile (lzma 中的类)
@anchor{library/lzma lzma LZMAFile}@anchor{a1f}
@deffn {类} lzma.LZMAFile (filename=None, mode="r", *, format=None, check=-1, preset=None, filters=None)

以二进制模式打开一个 LZMA 压缩文件。

@ref{a1f,,LZMAFile} 可以包装在一个已打开的 @ref{c1d,,file object} 中，或者是在给定名称的文件上直接操作。 @emph{filename} 参数指定所包装的文件对象，或是要打开的文件名称（类型为 @ref{206,,str}, @ref{172,,bytes} 或 @ref{47b,,路径类} 对象）。 如果是包装现有的文件对象，被包装的文件在 @ref{a1f,,LZMAFile} 被关闭时将不会被关闭。

@emph{mode} 参数可以是表示读取的 @code{"r"} (默认值)，表示覆写的 @code{"w"}，表示单独创建的 @code{"x"}，或表示添加的 @code{"a"}。 这些模式还可以分别以 @code{"rb"}, @code{"wb"}, @code{"xb"} 和 @code{"ab"} 的等价形式给出。

如果 @emph{filename} 是一个文件对象（而不是实际的文件名），则 @code{"w"} 模式并不会截断文件，而会等价于 @code{"a"}。

当打开一个文件用于读取时，输入文件可以为多个独立压缩流的拼接。 它们会被作为单个逻辑流被透明地解码。

当打开一个文件用于读取时，@emph{format} 和 @emph{filters} 参数具有与 @ref{1f1d,,LZMADecompressor} 的参数相同的含义。 在此情况下，@emph{check} 和 @emph{preset} 参数不应被使用。

当打开一个文件用于写入的，@emph{format}, @emph{check}, @emph{preset} 和 @emph{filters} 参数具有与 @ref{1f1e,,LZMACompressor} 的参数相同的含义。

@ref{a1f,,LZMAFile} 支持 @ref{689,,io.BufferedIOBase} 所指定的所有成员，但 @code{detach()} 和 @code{truncate()} 除外。 并支持迭代和 @ref{7e4,,with} 语句。

也提供以下方法：

@geindex peek() (lzma.LZMAFile 方法)
@anchor{library/lzma lzma LZMAFile peek}@anchor{1f1f}
@deffn {方法} peek (size=-1)

返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据，除非已经到达 EOF。 实际返回的字节数不确定（会忽略 @emph{size} 参数）。

@cartouche
@quotation 注解 
虽然调用 @ref{1f1f,,peek()} 不会改变 @ref{a1f,,LZMAFile} 的文件位置，但它可能改变下层文件对象的位置（举例来说如果 @ref{a1f,,LZMAFile} 是通过传入一个文件对象作为 @emph{filename} 的话）。
@end quotation
@end cartouche
@end deffn


在 3.4 版更改: 增加了对 @code{"x"} 和 @code{"xb"} 模式的支持。



在 3.5 版更改: @ref{1eff,,read()} 方法现在接受 @code{None} 作为参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@node 在内存中压缩和解压缩数据,杂项<2>,读写压缩文件,lzma --- 用 LZMA 算法压缩
@anchor{library/lzma compressing-and-decompressing-data-in-memory}@anchor{1f20}
@subsubsection 在内存中压缩和解压缩数据


@geindex LZMACompressor (lzma 中的类)
@anchor{library/lzma lzma LZMACompressor}@anchor{1f1e}
@deffn {类} lzma.LZMACompressor (format=FORMAT_XZ, check=-1, preset=None, filters=None)

创建一个压缩器对象，此对象可被用来执行增量压缩。

压缩单个数据块的更便捷方式请参阅 @ref{1f21,,compress()}。

@emph{format} 参数指定应当使用哪种容器格式。 可能的值有：


@itemize *

@item 

@table @asis

@item @code{FORMAT_XZ}: @code{.xz} 容器格式。

这是默认格式。
@end table

@item 

@table @asis

@item @code{FORMAT_ALONE}: 传统的 @code{.lzma} 容器格式。

这种格式相比 @code{.xz} 更为受限 -- 它不支持一致性检查或多重过滤器。
@end table

@item 

@table @asis

@item @code{FORMAT_RAW}: 原始数据流，不使用任何容器格式。

这个格式描述器不支持一致性检查，并且要求你必须指定一个自定义的过滤器链（用于压缩和解压缩）。 此外，以这种方式压缩的数据不可使用 @code{FORMAT_AUTO} 来解压缩 (参见 @ref{1f1d,,LZMADecompressor})。
@end table
@end itemize

@emph{check} 参数指定要包含在压缩数据中的一致性检查类型。 这种检查在解压缩时使用，以确保数据没有被破坏。 可能的值是：


@itemize *

@item 
@code{CHECK_NONE}: 没有一致性检查。 这是 @code{FORMAT_ALONE} 和 @code{FORMAT_RAW} 的默认值（也是唯一可接受的值）。

@item 
@code{CHECK_CRC32}: 32 位循环冗余检查。

@item 
@code{CHECK_CRC64}: 64 位循环冗余检查。 这是 @code{FORMAT_XZ} 的默认值。

@item 
@code{CHECK_SHA256}: 256 位安全哈希算法。
@end itemize

如果指定的检查不受支持，则会引发 @ref{1f1a,,LZMAError}。

压缩设置可被指定为一个预设的压缩等级（通过 @emph{preset} 参数）或以自定义过滤器链来详细设置（通过 @emph{filters} 参数）。

@emph{preset} 参数（如果提供）应当为一个 @code{0} 到 @code{9} (包括边界) 之间的整数，可以选择与常数 @code{PRESET_EXTREME} 进行 OR 运算。 如果 @emph{preset} 和 @emph{filters} 均未给出，则默认行为是使用 @code{PRESET_DEFAULT} (预设等级 @code{6})。 更高的预设等级会产生更小的输出，但会使得压缩过程更缓慢。

@cartouche
@quotation 注解 
除了更加 CPU 密集，使用更高的预设等级来压缩还需要更多的内存（并产生需要更多内存来解压缩的输出）。 例如使用预设等级 @code{9} 时，一个 @ref{1f1e,,LZMACompressor} 对象的开销可以高达 800 MiB。 出于这样的原因，通常最好是保持使用默认预设等级。
@end quotation
@end cartouche

@emph{filters} 参数（如果提供）应当指定一个过滤器链。 详情参见 @ref{1f22,,指定自定义的过滤器链}。

@geindex compress() (lzma.LZMACompressor 方法)
@anchor{library/lzma lzma LZMACompressor compress}@anchor{1f23}
@deffn {方法} compress (data)

压缩 @emph{data} (一个 @ref{172,,bytes} object)，返回包含针对输入的至少一部分已压缩数据的 @ref{172,,bytes} 对象。 一部 @emph{data} 可能会被放入内部缓冲区，以便用于后续的 @ref{1f21,,compress()} 和 @ref{1f24,,flush()} 调用。 返回的数据应当与之前任何 @ref{1f21,,compress()} 调用的输出进行拼接。
@end deffn

@geindex flush() (lzma.LZMACompressor 方法)
@anchor{library/lzma lzma LZMACompressor flush}@anchor{1f24}
@deffn {方法} flush ()

结束压缩进程，返回包含保存在压缩器的内部缓冲区中的任意数据的 @ref{172,,bytes} 对象。

调用此方法之后压缩器将不可再被使用。
@end deffn
@end deffn

@geindex LZMADecompressor (lzma 中的类)
@anchor{library/lzma lzma LZMADecompressor}@anchor{1f1d}
@deffn {类} lzma.LZMADecompressor (format=FORMAT_AUTO, memlimit=None, filters=None)

创建一个压缩器对象，此对象可被用来执行增量解压缩。

一次性解压缩整个压缩数据流的更便捷方式请参阅 @ref{1f25,,decompress()}。

@emph{format} 参数指定应当被使用的容器格式。 默认值为 @code{FORMAT_AUTO}，它可以解压缩 @code{.xz} 和 @code{.lzma} 文件。 其他可能的值为 @code{FORMAT_XZ}, @code{FORMAT_ALONE} 和 @code{FORMAT_RAW}。

@emph{memlimit} 参数指定解压缩器可以使用的内存上限（字节数）。 当使用此参数时，如果不可能在给定内存上限之内解压缩输入数据则解压缩将失败并引发 @ref{1f1a,,LZMAError}。

@emph{filters} 参数指定用于创建被解压缩数据流的过滤器链。 此参数在 @emph{format} 为 @code{FORMAT_RAW} 时要求提供，但对于其他格式不应使用。 有关过滤器链的更多信息请参阅 @ref{1f22,,指定自定义的过滤器链}。

@cartouche
@quotation 注解 
这个类不会透明地处理包含多个已压缩数据流的输入，这不同于 @ref{1f25,,decompress()} 和 @ref{a1f,,LZMAFile}。 要通过 @ref{1f1d,,LZMADecompressor} 来解压缩多个数据流输入，你必须为每个数据流都创建一个新的解压缩器。
@end quotation
@end cartouche

@geindex decompress() (lzma.LZMADecompressor 方法)
@anchor{library/lzma lzma LZMADecompressor decompress}@anchor{80f}
@deffn {方法} decompress (data, max_length=-1)

解压缩 @emph{data} (一个 @ref{6e9,,bytes-like object})，返回字节串形式的解压缩数据。 某些 @emph{data} 可以在内部被缓冲，以便用于后续的 @ref{1f25,,decompress()} 调用。 返回的数据应当与之前任何 @ref{1f25,,decompress()} 调用的输出进行拼接。

如果 @emph{max_length} 为非负数，将返回至多 @emph{max_length} 个字节的解压缩数据。 如果达到此限制并且可以产生后续输出，则 @ref{1f26,,needs_input} 属性将被设为 @code{False}。 在这种情况下，下一次 @ref{80f,,decompress()} 调用提供的 @emph{data} 可以为 @code{b'@w{'}} 以获取更多的输出。

如果所有输入数据都已被解压缩并返回（或是因为它少于 @emph{max_length} 个字节，或是因为 @emph{max_length} 为负数），则 @ref{1f26,,needs_input} 属性将被设为 @code{True}。

在到达数据流末尾之后再尝试解压缩数据会引发 @cite{EOFError}。 在数据流末尾之后获取的任何数据都会被忽略并存储至 @ref{1f27,,unused_data} 属性。


在 3.5 版更改: 添加了 @emph{max_length} 形参。

@end deffn

@geindex check (lzma.LZMADecompressor 属性)
@anchor{library/lzma lzma LZMADecompressor check}@anchor{1f28}
@deffn {属性} check

输入流使用的一致性检查的 ID。 这可能为 @code{CHECK_UNKNOWN} 直到已解压了足够的输入数据来确定它所使用的一致性检查。
@end deffn

@geindex eof (lzma.LZMADecompressor 属性)
@anchor{library/lzma lzma LZMADecompressor eof}@anchor{1f29}
@deffn {属性} eof

若达到了数据流末尾标识符则为 @code{True}。
@end deffn

@geindex unused_data (lzma.LZMADecompressor 属性)
@anchor{library/lzma lzma LZMADecompressor unused_data}@anchor{1f27}
@deffn {属性} unused_data

压缩数据流的末尾还有数据。

在达到数据流末尾之前，这个值将为 @code{b""}。
@end deffn

@geindex needs_input (lzma.LZMADecompressor 属性)
@anchor{library/lzma lzma LZMADecompressor needs_input}@anchor{1f26}
@deffn {属性} needs_input

如果在要求新的未解压缩输入之前 @ref{80f,,decompress()} 方法可以提供更多的解压缩数据则为 @code{False}。


3.5 新版功能.

@end deffn
@end deffn

@geindex compress() (在 lzma 模块中)
@anchor{library/lzma lzma compress}@anchor{1f21}
@deffn {函数} lzma.compress (data, format=FORMAT_XZ, check=-1, preset=None, filters=None)

压缩 @emph{data} (一个 @ref{172,,bytes} 对象)，返回包含压缩数据的 @ref{172,,bytes} 对象。

参见上文的 @ref{1f1e,,LZMACompressor} 了解有关 @emph{format}, @emph{check}, @emph{preset} 和 @emph{filters} 参数的说明。
@end deffn

@geindex decompress() (在 lzma 模块中)
@anchor{library/lzma lzma decompress}@anchor{1f25}
@deffn {函数} lzma.decompress (data, format=FORMAT_AUTO, memlimit=None, filters=None)

解压缩 @emph{data} (一个 @ref{172,,bytes} 对象)，返回包含解压缩数据的 @ref{172,,bytes} 对象。

如果 @emph{data} 是多个单独压缩数据流的拼接，则解压缩所有相应数据流，并返回结果的拼接。

参见上文的 @ref{1f1d,,LZMADecompressor} 了解有关 @emph{format}, @emph{memlimit} 和 @emph{filters} 参数的说明。
@end deffn

@node 杂项<2>,指定自定义的过滤器链,在内存中压缩和解压缩数据,lzma --- 用 LZMA 算法压缩
@anchor{library/lzma miscellaneous}@anchor{1f2a}
@subsubsection 杂项


@geindex is_check_supported() (在 lzma 模块中)
@anchor{library/lzma lzma is_check_supported}@anchor{1f2b}
@deffn {函数} lzma.is_check_supported (check)

如果本系统支持给定的一致性检查则返回 @code{True}。

@code{CHECK_NONE} 和 @code{CHECK_CRC32} 总是受支持。 @code{CHECK_CRC64} 和 @code{CHECK_SHA256} 或许不可用，如果你正在使用基于受限制特性集编译的 @code{liblzma} 版本的话。
@end deffn

@node 指定自定义的过滤器链,示例<11>,杂项<2>,lzma --- 用 LZMA 算法压缩
@anchor{library/lzma filter-chain-specs}@anchor{1f22}@anchor{library/lzma specifying-custom-filter-chains}@anchor{1f2c}
@subsubsection 指定自定义的过滤器链


过滤器链描述符是由字典组成的序列，其中每个字典包含单个过滤器的 ID 和选项。 每个字典必须包含键 @code{"id"}，并可能包含额外的键用来指定基于过滤器的选项。 有效的过滤器 ID 如下：


@itemize *

@item 

@table @asis

@item 压缩过滤器：


@itemize *

@item 
@code{FILTER_LZMA1} (配合 @code{FORMAT_ALONE} 使用)

@item 
@code{FILTER_LZMA2} (配合 @code{FORMAT_XZ} 和 @code{FORMAT_RAW} 使用)
@end itemize
@end table

@item 

@table @asis

@item Delta 过滤器：


@itemize *

@item 
@code{FILTER_DELTA}
@end itemize
@end table

@item 

@table @asis

@item Branch-Call-Jump (BCJ) 过滤器：


@itemize *

@item 
@code{FILTER_X86}

@item 
@code{FILTER_IA64}

@item 
@code{FILTER_ARM}

@item 
@code{FILTER_ARMTHUMB}

@item 
@code{FILTER_POWERPC}

@item 
@code{FILTER_SPARC}
@end itemize
@end table
@end itemize

一个过滤器链最多可由 4 个过滤器组成，并且不能为空。 过滤器链中的最后一个过滤器必须为压缩过滤器，其他过滤器必须为 Delta 或 BCJ 过滤器。

压缩过滤器支持下列选项（指定为表示过滤器的字典中的附加条目）：

@quotation


@itemize *

@item 
@code{preset}: 压缩预设选项，用于作为未显式指定的选项的默认值的来源。

@item 
@code{dict_size}: 以字节表示的字典大小。 这应当在 4 KiB 和 1.5 GiB 之间（包含边界）。

@item 
@code{lc}: 字面值上下文的比特数。

@item 
@code{lp}: 字面值位置的比特数。 总计值 @code{lc + lp} 必须不大于 4。

@item 
@code{pb}: 位置的比特数；必须不大于 4。

@item 
@code{mode}: @code{MODE_FAST} 或 @code{MODE_NORMAL}。

@item 
@code{nice_len}: 对于一个匹配应当被视为“适宜长度”的值。 这应当小于或等于 273。

@item 
@code{mf}: 要使用的匹配查找器 -- @code{MF_HC3}, @code{MF_HC4}, @code{MF_BT2}, @code{MF_BT3} 或 @code{MF_BT4}。

@item 
@code{depth}: 匹配查找器使用的最大查找深度。 0 (默认值) 表示基于其他过滤器选项自动选择。
@end itemize
@end quotation

Delta 过滤器保存字节数据之间的差值，在特定环境下可产生更具重复性的输入。 它支持一个 @code{dist} 选项，指明要减去的字节之间的差值大小。 默认值为 1，即相邻字节之间的差值。

BCJ 过滤器主要作用于机器码。 它们会转换机器码内的相对分支、调用和跳转以使用绝对寻址，其目标是提升冗余度以供压缩器利用。 这些过滤器支持一个 @code{start_offset} 选项，指明应当被映射到输入数据开头的地址。 默认值为 0。

@node 示例<11>,,指定自定义的过滤器链,lzma --- 用 LZMA 算法压缩
@anchor{library/lzma examples}@anchor{1f2d}
@subsubsection 示例


在已压缩的数据中读取:

@example
import lzma
with lzma.open("file.xz") as f:
    file_content = f.read()
@end example

创建一个压缩文件:

@example
import lzma
data = b"Insert Data Here"
with lzma.open("file.xz", "w") as f:
    f.write(data)
@end example

在内存中压缩文件:

@example
import lzma
data_in = b"Insert Data Here"
data_out = lzma.compress(data_in)
@end example

增量压缩:

@example
import lzma
lzc = lzma.LZMACompressor()
out1 = lzc.compress(b"Some data\n")
out2 = lzc.compress(b"Another piece of data\n")
out3 = lzc.compress(b"Even more data\n")
out4 = lzc.flush()
# Concatenate all the partial results:
result = b"".join([out1, out2, out3, out4])
@end example

写入已压缩数据到已打开的文件:

@example
import lzma
with open("file.xz", "wb") as f:
    f.write(b"This data will not be compressed\n")
    with lzma.open(f, "w") as lzf:
        lzf.write(b"This *will* be compressed\n")
    f.write(b"Not compressed\n")
@end example

使用自定义过滤器链创建一个已压缩文件:

@example
import lzma
my_filters = [
    @{"id": lzma.FILTER_DELTA, "dist": 5@},
    @{"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME@},
]
with lzma.open("file.xz", "w", filters=my_filters) as f:
    f.write(b"blah blah blah")
@end example

@node zipfile --- 使用ZIP存档,tarfile --- 读写tar归档文件,lzma --- 用 LZMA 算法压缩,数据压缩和存档
@anchor{library/zipfile doc}@anchor{1f2e}@anchor{library/zipfile module-zipfile}@anchor{14b}@anchor{library/zipfile zipfile-work-with-zip-archives}@anchor{1f2f}
@subsection @code{zipfile} --- 使用ZIP存档


@geindex zipfile (模块)

@strong{源代码：} Lib/zipfile.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/zipfile.py}


__________________________________________________________________


ZIP 文件格式是一个常用的归档与压缩标准。 这个模块提供了创建、读取、写入、添加及列出 ZIP 文件的工具。 任何对此模块的进阶使用都将需要理解此格式，其定义参见 PKZIP 应用程序笔记@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT}。

此模块目前不能处理分卷 ZIP 文件。它可以处理使用 ZIP64 扩展（超过 4 GB 的 ZIP 文件）的 ZIP 文件。它支持解密 ZIP 归档中的加密文件，但是目前不能创建一个加密的文件。解密非常慢，因为它是使用原生 Python 而不是 C 实现的。

这个模块定义了以下内容：

@geindex BadZipFile
@anchor{library/zipfile zipfile BadZipFile}@anchor{1f30}
@deffn {例外} zipfile.BadZipFile

为损坏的 ZIP 文件抛出的错误。


3.2 新版功能.

@end deffn

@geindex BadZipfile
@anchor{library/zipfile zipfile BadZipfile}@anchor{1f31}
@deffn {例外} zipfile.BadZipfile

@ref{1f30,,BadZipFile} 的别名，与旧版本 Python 保持兼容性。


3.2 版后已移除.

@end deffn

@geindex LargeZipFile
@anchor{library/zipfile zipfile LargeZipFile}@anchor{1f32}
@deffn {例外} zipfile.LargeZipFile

当 ZIP 文件需要 ZIP64 功能但是未启用时会抛出此错误。
@end deffn


@deffn {类} zipfile.ZipFile

用于读写 ZIP 文件的类。 欲了解构造函数的描述，参阅段落 @ref{1f33,,ZipFile 对象}。
@end deffn


@deffn {类} zipfile.Path

用于 zip 文件的兼容 pathlib 的包装器。 详情参见 @ref{1f34,,Path 对象}。


3.8 新版功能.

@end deffn


@deffn {类} zipfile.PyZipFile

用于创建包含 Python 库的 ZIP 归档的类。
@end deffn

@geindex ZipInfo (zipfile 中的类)
@anchor{library/zipfile zipfile ZipInfo}@anchor{6bb}
@deffn {类} zipfile.ZipInfo (filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))

用于表示档案内一个成员信息的类。 此类的实例会由 @ref{52b,,ZipFile} 对象的 @ref{1f35,,getinfo()} 和 @ref{1f36,,infolist()} 方法返回。 大多数 @ref{14b,,zipfile} 模块的用户都不必创建它们，只需使用此模块所创建的实例。 @emph{filename} 应当是档案成员的全名，@emph{date_time} 应当是包含六个字段的描述最近修改时间的元组；这些字段的描述请参阅 @ref{1f37,,ZipInfo 对象}。
@end deffn

@geindex is_zipfile() (在 zipfile 模块中)
@anchor{library/zipfile zipfile is_zipfile}@anchor{d8a}
@deffn {函数} zipfile.is_zipfile (filename)

根据文件的 Magic Number，如果 @emph{filename} 是一个有效的 ZIP 文件则返回 @code{True}，否则返回 @code{False}。 @emph{filename} 也可能是一个文件或类文件对象。


在 3.1 版更改: 支持文件或类文件对象。

@end deffn

@geindex ZIP_STORED() (在 zipfile 模块中)
@anchor{library/zipfile zipfile ZIP_STORED}@anchor{1f38}
@deffn {数据} zipfile.ZIP_STORED

未被压缩的归档成员的数字常数。
@end deffn

@geindex ZIP_DEFLATED() (在 zipfile 模块中)
@anchor{library/zipfile zipfile ZIP_DEFLATED}@anchor{1f39}
@deffn {数据} zipfile.ZIP_DEFLATED

常用的 ZIP 压缩方法的数字常数。需要 @ref{14d,,zlib} 模块。
@end deffn

@geindex ZIP_BZIP2() (在 zipfile 模块中)
@anchor{library/zipfile zipfile ZIP_BZIP2}@anchor{1f3a}
@deffn {数据} zipfile.ZIP_BZIP2

BZIP2 压缩方法的数字常数。需要 @ref{13,,bz2} 模块。


3.3 新版功能.

@end deffn

@geindex ZIP_LZMA() (在 zipfile 模块中)
@anchor{library/zipfile zipfile ZIP_LZMA}@anchor{1f3b}
@deffn {数据} zipfile.ZIP_LZMA

LZMA 压缩方法的数字常数。需要 @ref{ad,,lzma} 模块。


3.3 新版功能.


@cartouche
@quotation 注解 
ZIP 文件格式规范包括自 2001 年以来对 bzip2 压缩的支持，以及自 2006 年以来对 LZMA 压缩的支持。但是，一些工具（包括较旧的 Python 版本）不支持这些压缩方法，并且可能拒绝完全处理 ZIP 文件，或者无法提取单个文件。
@end quotation
@end cartouche
@end deffn


@subsubheading 参见



@table @asis

@item PKZIP 应用程序笔记@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT}

Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

@item Info-ZIP 主页@footnote{http://www.info-zip.org/}

有关 Info-ZIP 项目的 ZIP 存档程序和开发库的信息。
@end table


@menu
* ZipFile 对象:: 
* Path 对象:: 
* PyZipFile 对象:: 
* ZipInfo 对象:: 
* 命令行界面: 命令行界面<2>. 
* 解压缩的障碍:: 

@end menu

@node ZipFile 对象,Path 对象,,zipfile --- 使用ZIP存档
@anchor{library/zipfile id1}@anchor{1f3c}@anchor{library/zipfile zipfile-objects}@anchor{1f33}
@subsubsection ZipFile 对象


@geindex ZipFile (zipfile 中的类)
@anchor{library/zipfile zipfile ZipFile}@anchor{52b}
@deffn {类} zipfile.ZipFile (file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)

打开一个 ZIP 文件，@emph{file} 为一个指向文件的路径（字符串），一个类文件对象或者一个 @ref{47b,,path-like object}。

形参 @emph{mode} 应当为 @code{'r'} 来读取一个存在的文件，@code{'w'} 来截断并写入新的文件， @code{'a'} 来添加到一个存在的文件，或者 @code{'x'} 来仅新建并写入新的文件。如果 @emph{mode} 为 @code{'x'} 并且 @emph{file} 指向已经存在的文件，则抛出 @ref{a42,,FileExistsError}。如果 @emph{mode} 为 @code{'a'} 且 @emph{file} 为已存在的文件，则格外的文件将被加入。如果 @emph{file} 不指向 ZIP 文件，之后一个新的 ZIP 归档将被追加为此文件。这是为了将 ZIP 归档添加到另一个文件（例如 @code{python.exe}）。如果 @emph{mode} 为 @code{'a'} 并且文件不存在， 则会新建。如果 @emph{mode} 为 @code{'r'} 或 @code{'a'}， 则文件应当可定位。

@emph{compression} 是在写入归档时要使用的 ZIP 压缩方法，应为 @ref{1f38,,ZIP_STORED}, @ref{1f39,,ZIP_DEFLATED}, @ref{1f3a,,ZIP_BZIP2} 或 @ref{1f3b,,ZIP_LZMA}；不可识别的值将导致引发 @ref{70e,,NotImplementedError}。 如果指定了 @ref{1f39,,ZIP_DEFLATED}, @ref{1f3a,,ZIP_BZIP2} 或 @ref{1f3b,,ZIP_LZMA} 但相应的模块 (@ref{14d,,zlib}, @ref{13,,bz2} 或 @ref{ad,,lzma}) 不可用，则会引发 @ref{3e4,,RuntimeError}。 默认值为 @ref{1f38,,ZIP_STORED}。

如果 @emph{allowZip64} 为 @code{True} (默认值) 则当 zipfile 大于 4 GiB 时 zipfile 将创建使用 ZIP64 扩展的 ZIP 文件。 如果该参数为 @code{false} 则当 ZIP 文件需要 ZIP64 扩展时 @ref{14b,,zipfile} 将引发异常。

@emph{compresslevel} 形参控制在将文件写入归档时要使用的压缩等级。 当使用 @ref{1f38,,ZIP_STORED} 或 @ref{1f3b,,ZIP_LZMA} 时无压缩效果。 当使用 @ref{1f39,,ZIP_DEFLATED} 时接受整数 @code{0} 至 @code{9} (更多信息参见 @ref{1eeb,,zlib})。 当使用 @ref{1f3a,,ZIP_BZIP2} 时接受整数 @code{1} 至 @code{9} (更多信息参见 @ref{225,,bz2})。

@emph{strict_timestamps} 参数在设为 @code{False} 时允许压缩早于 1980-01-01 的文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于 2107-12-31 的文件发生，时间戳也会被设为该上限值。

如果创建文件时使用 @code{'w'}, @code{'x'} 或 @code{'a'} 模式并且未向归档添加任何文件就执行了 @ref{1f3d,,closed}，则会将适当的空归档 ZIP 结构写入文件。

ZipFile 也是一个上下文管理器，因此支持 @ref{7e4,,with} 语句。 在这个示例中，@emph{myzip} 将在 @code{with} 语句块执行完成之后被关闭 --- 即使是发生了异常:

@example
with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')
@end example


3.2 新版功能: 添加了将 @ref{52b,,ZipFile} 用作上下文管理员的功能。



在 3.3 版更改: 添加了对 @ref{13,,bzip2} 和 @ref{ad,,lzma} 压缩的支持。



在 3.4 版更改: 默认启用 ZIP64 扩展。



在 3.5 版更改: 添加了对不可查找数据流的支持。 并添加了对 @code{'x'} 模式的支持。



在 3.6 版更改: 在此之前，对于不可识别的压缩值将引发普通的 @ref{3e4,,RuntimeError}。



在 3.6.2 版更改: @emph{file} 形参接受一个 @ref{47b,,path-like object}。



在 3.7 版更改: 添加了 @emph{compresslevel} 形参。



3.8 新版功能: @emph{strict_timestamps} 仅限关键字参数

@end deffn

@geindex close() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile close}@anchor{1f3d}
@deffn {方法} ZipFile.close ()

关闭归档文件。 你必须在退出程序之前调用 @ref{1f3d,,close()} 否则将不会写入关键记录数据。
@end deffn

@geindex getinfo() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile getinfo}@anchor{1f35}
@deffn {方法} ZipFile.getinfo (name)

返回一个 @ref{6bb,,ZipInfo} 对象，其中包含有关归档成员 @emph{name} 的信息。 针对一个目前并不包含于归档中的名称调用 @ref{1f35,,getinfo()} 将会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex infolist() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile infolist}@anchor{1f36}
@deffn {方法} ZipFile.infolist ()

返回一个列表，其中包含每个归档成员的 @ref{6bb,,ZipInfo} 对象。 如果是打开一个现有归档则这些对象的排列顺序与它们对应条目在磁盘上的实际 ZIP 文件中的顺序一致。
@end deffn

@geindex namelist() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile namelist}@anchor{1f3e}
@deffn {方法} ZipFile.namelist ()

返回按名称排序的归档成员列表。
@end deffn

@geindex open() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile open}@anchor{6bd}
@deffn {方法} ZipFile.open (name, mode='r', pwd=None, *, force_zip64=False)

以二进制文件类对象的形式访问一个归档成员。 @emph{name} 可以是归档内某个文件的名称也可以是某个 @ref{6bb,,ZipInfo} 对象。 如果包含了 @emph{mode} 形参，则它必须为 @code{'r'} (默认值) 或 @code{'w'}。  @emph{pwd} 为用于解密已加密 ZIP 文件的密码。

@ref{6bd,,open()} 也是一个上下文管理器，因此支持 @ref{7e4,,with} 语句:

@example
with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())
@end example

如果 @emph{mode} 为 @code{'r'} 则文件类对象 (@code{ZipExtFile}) 将为只读并且提供下列方法: @ref{1eff,,read()}, @ref{1883,,readline()}, @ref{1921,,readlines()}, @ref{1f3f,,seek()}, @ref{1f40,,tell()}, @ref{611,,__iter__()}, @ref{d34,,__next__()}。 这些对象可独立于 ZipFile 进行操作。

如果 @code{mode='w'} 则返回一个可写入的文件句柄，它将支持 @ref{68a,,write()} 方法。 当一个可写入的文件句柄被打开时，尝试读写 ZIP 文件中的其他文件将会引发 @ref{16d,,ValueError}。

当写入一个文件时，如果文件大小不能预先确定但是可能超过 2 GiB，可传入 @code{force_zip64=True} 以确保标头格式能够支持超大文件。 如果文件大小可以预先确定，则在构造 @ref{6bb,,ZipInfo} 对象时应设置 @ref{1f41,,file_size}，并将其用作 @emph{name} 形参。

@cartouche
@quotation 注解 
@ref{6bd,,open()}, @ref{d89,,read()} 和 @ref{1f42,,extract()} 方法可接受文件名或 @ref{6bb,,ZipInfo} 对象。 当尝试读取一个包含重复名称成员的 ZIP 文件时你将发现此功能很有好处。
@end quotation
@end cartouche


在 3.6 版更改: 移除了对 @code{mode='U'} 的支持。 请使用 @ref{6f4,,io.TextIOWrapper} 以在 @ref{6f5,,universal newlines} 模式中读取已压缩的文本文件。



在 3.6 版更改: 现在 @ref{6bd,,ZipFile.open()} 可以被用来配合 @code{mode='w'} 选项将文件写入归档。



在 3.6 版更改: 在已关闭的 ZipFile 上调用 @ref{6bd,,open()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则会引发 @ref{3e4,,RuntimeError}。

@end deffn

@geindex extract() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile extract}@anchor{1f42}
@deffn {方法} ZipFile.extract (member, path=None, pwd=None)

从归档中提取出一个成员放入当前工作目录；@emph{member} 必须为成员的完整名称或 @ref{6bb,,ZipInfo} 对象。 成员的文件信息会尽可能精确地被提取。 @emph{path} 指定一个要提取到的不同目录。 @emph{member} 可以是一个文件名或 @ref{6bb,,ZipInfo} 对象。 @emph{pwd} 是用于解密文件的密码。

返回所创建的经正规化的路径（对应于目录或新文件）。

@cartouche
@quotation 注解 
如果一个成员文件名为绝对路径，则将去掉驱动器/UNC共享点和前导的（反）斜杠，例如: @code{///foo/bar} 在 Unix 上将变为 @code{foo/bar}，而 @code{C:\foo\bar} 在 Windows 上将变为 @code{foo\bar}。 并且一个成员文件名中的所有 @code{".."} 都将被移除，例如: @code{../../foo../../ba..r} 将变为 @code{foo../ba..r}。 在 Windows 上非法字符 (@code{:}, @code{<}, @code{>}, @code{|}, @code{"}, @code{?}, and @code{*}) 会被替换为下划线 (@code{_})。
@end quotation
@end cartouche


在 3.6 版更改: 在已关闭的 ZipFile 上调用 @ref{1f42,,extract()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则将引发 @ref{3e4,,RuntimeError}。



在 3.6.2 版更改: @emph{path} 形参接受一个 @ref{47b,,path-like object}。

@end deffn

@geindex extractall() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile extractall}@anchor{1f43}
@deffn {方法} ZipFile.extractall (path=None, members=None, pwd=None)

从归档中提取出所有成员放入当前工作目录。 @emph{path} 指定一个要提取到的不同目录。 @emph{members} 为可选项且必须为 @ref{1f3e,,namelist()} 所返回列表的一个子集。 @emph{pwd} 是用于解密文件的密码。

@cartouche
@quotation 警告 
绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有可能在 @emph{path} 之外创建文件，例如某些成员具有以 @code{"/"} 开始的文件名或带有两个点号 @code{".."} 的文件名。 此模块会尝试防止这种情况。 参见 @ref{1f42,,extract()} 的注释。
@end quotation
@end cartouche


在 3.6 版更改: 在已关闭的 ZipFile 上调用 @ref{1f43,,extractall()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则将引发 @ref{3e4,,RuntimeError}。



在 3.6.2 版更改: @emph{path} 形参接受一个 @ref{47b,,path-like object}。

@end deffn

@geindex printdir() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile printdir}@anchor{1f44}
@deffn {方法} ZipFile.printdir ()

将归档的目录表打印到 @code{sys.stdout}。
@end deffn

@geindex setpassword() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile setpassword}@anchor{1f45}
@deffn {方法} ZipFile.setpassword (pwd)

设置 @emph{pwd} 为用于提取已加密文件的默认密码。
@end deffn

@geindex read() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile read}@anchor{d89}
@deffn {方法} ZipFile.read (name, pwd=None)

返回归档中文件 @emph{name} 的字节数据。 @emph{name} 是归档中文件的名称，或是一个 @ref{6bb,,ZipInfo} 对象。 归档必须以读取或追加方式打开。 @emph{pwd} 为用于已加密文件的密码，并且如果指定该参数则它将覆盖通过 @ref{1f45,,setpassword()} 设置的默认密码。  on a ZipFile that uses a compression method 在使用 @ref{1f38,,ZIP_STORED} , @ref{1f39,,ZIP_DEFLATED}, @ref{1f3a,,ZIP_BZIP2} 或 @ref{1f3b,,ZIP_LZMA} 以外的压缩方法的 ZipFile 上调用 @ref{d89,,read()} 将引发 @ref{70e,,NotImplementedError}。 如果相应的压缩模块不可用也会引发错误。


在 3.6 版更改: 在已关闭的 ZipFile 上调用 @ref{d89,,read()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则会引发 @ref{3e4,,RuntimeError}。

@end deffn

@geindex testzip() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile testzip}@anchor{1f46}
@deffn {方法} ZipFile.testzip ()

读取归档中的所有文件并检查它们的 CRC 和文件头。 返回第一个已损坏文件的名称，在其他情况下则返回 @code{None}。


在 3.6 版更改: 在已关闭的 ZipFile 上调用 @ref{1f46,,testzip()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则将引发 @ref{3e4,,RuntimeError}。

@end deffn

@geindex write() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile write}@anchor{70f}
@deffn {方法} ZipFile.write (filename, arcname=None, compress_type=None, compresslevel=None)

将名为 @emph{filename} 的文件写入归档，给予的归档名为 @emph{arcname} (默认情况下将与 @emph{filename} 一致，但是不带驱动器盘符并会移除开头的路径分隔符)。 @emph{compress_type} 如果给出，它将覆盖作为构造器 @emph{compression} 形参对于新条目所给出的值。 类似地，@emph{compresslevel} 如果给出也将覆盖构造器。 归档必须使用 @code{'w'}, @code{'x'} 或 @code{'a'} 模式打开。

@cartouche
@quotation 注解 
归档名称应当是基于归档根目录的相对路径，也就是说，它们不应以路径分隔符开头。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果 @code{arcname} (或 @code{filename}，如果 @code{arcname} 未给出) 包含一个空字节，则归档中该文件的名称将在空字节位置被截断。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
文件名开头有一个斜杠可能导致存档文件无法在 Windows 系统上的某些 zip 程序中打开。
@end quotation
@end cartouche


在 3.6 版更改: 在使用 @code{'r'} 模式创建的 ZipFile 或已关闭的 ZipFile 上调用 @ref{70f,,write()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则会引发 @ref{3e4,,RuntimeError}。

@end deffn

@geindex writestr() (zipfile.ZipFile 方法)
@anchor{library/zipfile zipfile ZipFile writestr}@anchor{d8b}
@deffn {方法} ZipFile.writestr (zinfo_or_arcname, data, compress_type=None, compresslevel=None)

将一个文件写入归档。 内容为 @emph{data}，它可以是一个 @ref{206,,str} 或 @ref{172,,bytes} 的实例；如果是 @ref{206,,str}，则会先使用 UTF-8 进行编码。 @emph{zinfo_or_arcname} 可以是它在归档中将被给予的名称，或者是 @ref{6bb,,ZipInfo} 的实例。 如果它是一个实例，则至少必须给定文件名、日期和时间。 如果它是一个名称，则日期和时间会被设为当前日期和时间。 归档必须以 @code{'w'}, @code{'x'} 或 @code{'a'} 模式打开。

如果给定了 @emph{compress_type}，它将会覆盖作为新条目构造器的 @emph{compression} 形参或在 @emph{zinfo_or_arcname} (如果是一个 @ref{6bb,,ZipInfo} 实例) 中所给出的值。 类似地，如果给定了 @emph{compresslevel}，它将会覆盖构造器。

@cartouche
@quotation 注解 
当传入一个 @ref{6bb,,ZipInfo} 实例作为 @emph{zinfo_or_arcname} 形参时，所使用的压缩方法将为在给定的 @ref{6bb,,ZipInfo} 实例的 @emph{compress_type} 成员中指定的方法。 默认情况下，@ref{6bb,,ZipInfo} 构造器将将此成员设为 @ref{1f38,,ZIP_STORED}。
@end quotation
@end cartouche


在 3.2 版更改: @emph{compress_type} 参数。



在 3.6 版更改: 在使用 @code{'r'} 模式创建的 ZipFile 或已关闭的 ZipFile 上调用 @ref{d8b,,writestr()} 将引发 @ref{16d,,ValueError}。 在之前的版本中则会引发 @ref{3e4,,RuntimeError}。

@end deffn

以下数据属性也是可用的:

@geindex filename (zipfile.ZipFile 属性)
@anchor{library/zipfile zipfile ZipFile filename}@anchor{1f47}
@deffn {属性} ZipFile.filename

ZIP 文件的名称。
@end deffn

@geindex debug (zipfile.ZipFile 属性)
@anchor{library/zipfile zipfile ZipFile debug}@anchor{1f48}
@deffn {属性} ZipFile.debug

要使用的调试输出等级。 这可以设为从 @code{0} (默认无输出) 到 @code{3} (最多输出) 的值。 调试信息会被写入 @code{sys.stdout}。
@end deffn

@geindex comment (zipfile.ZipFile 属性)
@anchor{library/zipfile zipfile ZipFile comment}@anchor{1f49}
@deffn {属性} ZipFile.comment

关联到 ZIP 文件的 @ref{172,,bytes} 对象形式的说明。 如果将说明赋给以 @code{'w'}, @code{'x'} 或 @code{'a'} 模式创建的 @ref{52b,,ZipFile} 实例，它的长度不应超过 65535 字节。 超过此长度的说明将被截断。
@end deffn

@node Path 对象,PyZipFile 对象,ZipFile 对象,zipfile --- 使用ZIP存档
@anchor{library/zipfile id2}@anchor{1f4a}@anchor{library/zipfile path-objects}@anchor{1f34}
@subsubsection Path 对象


@geindex Path (zipfile 中的类)
@anchor{library/zipfile zipfile Path}@anchor{10b0}
@deffn {类} zipfile.Path (root, at='@w{'})

根据 @code{root} zipfile (它可以是一个 @ref{52b,,ZipFile} 实例或适合传给 @ref{52b,,ZipFile} 构造器的 @code{file}) 构造一个 Path 对象。

@code{at} 指定此 Path 在 zipfile 中的位置，例如 'dir/file.txt', 'dir/' 或 '@w{'}。 默认为空字符串，即指定跟目录。
@end deffn

Path 对象会公开 @ref{336,,pathlib.Path} 对象的下列特性:

Path 对象可以使用 @code{/} 操作符进行遍历。

@geindex name (zipfile.Path 属性)
@anchor{library/zipfile zipfile Path name}@anchor{1f4b}
@deffn {属性} Path.name

最终的路径组成部分。
@end deffn

@geindex open() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path open}@anchor{1f4c}
@deffn {方法} Path.open (mode='r', *, pwd, **)

在当前路径上发起调用 @ref{6bd,,ZipFile.open()}。 允许通过支持的模式打开用于读取或写入文本或二进制数据: 'r', 'w', 'rb', 'wb'。 当以文本模式打开时位置和关键字参数会被传给 @ref{6f4,,io.TextIOWrapper}，在其他情况下则会被忽略。 @code{pwd} 是要传给 @ref{6bd,,ZipFile.open()}  的 @code{pwd} 形参。


在 3.9 版更改: 增加了对以文本和二进制模式打开的支持。 现在默认为文本模式。

@end deffn

@geindex iterdir() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path iterdir}@anchor{1f4d}
@deffn {方法} Path.iterdir ()

枚举当前目录的子目录。
@end deffn

@geindex is_dir() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path is_dir}@anchor{1f4e}
@deffn {方法} Path.is_dir ()

如果当前上下文引用了一个目录则返回 @code{True}。
@end deffn

@geindex is_file() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path is_file}@anchor{1f4f}
@deffn {方法} Path.is_file ()

如果当前上下文引用了一个文件则返回 @code{True}。
@end deffn

@geindex exists() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path exists}@anchor{1f50}
@deffn {方法} Path.exists ()

如果当前上下文引用了 zip 文件内的一个文件或目录则返回 @code{True}。
@end deffn

@geindex read_text() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path read_text}@anchor{1f51}
@deffn {方法} Path.read_text (*, **)

读取当前文件为 unicode 文本。 位置和关键字参数会被传递给 @ref{6f4,,io.TextIOWrapper} (@code{buffer} 除外，它将由上下文确定)。
@end deffn

@geindex read_bytes() (zipfile.Path 方法)
@anchor{library/zipfile zipfile Path read_bytes}@anchor{1f52}
@deffn {方法} Path.read_bytes ()

读取当前文件为字节串。
@end deffn

@node PyZipFile 对象,ZipInfo 对象,Path 对象,zipfile --- 使用ZIP存档
@anchor{library/zipfile id3}@anchor{1f53}@anchor{library/zipfile pyzipfile-objects}@anchor{1f54}
@subsubsection PyZipFile 对象


@ref{a09,,PyZipFile} 构造器接受与 @ref{52b,,ZipFile} 构造器相同的形参，以及一个额外的形参 @emph{optimize}。

@geindex PyZipFile (zipfile 中的类)
@anchor{library/zipfile zipfile PyZipFile}@anchor{a09}
@deffn {类} zipfile.PyZipFile (file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)


3.2 新版功能: @emph{optimize} 形参。



在 3.4 版更改: 默认启用 ZIP64 扩展。


实例在 @ref{52b,,ZipFile} 对象所具有的方法以外还附加了一个方法:

@geindex writepy() (zipfile.PyZipFile 方法)
@anchor{library/zipfile zipfile PyZipFile writepy}@anchor{a08}
@deffn {方法} writepy (pathname, basename='@w{'}, filterfunc=None)

查找 @code{*.py} 文件并将相应的文件添加到归档。

如果 @ref{a09,,PyZipFile} 的 @emph{optimize} 形参未给定或为 @code{-1}，则相应的文件为 @code{*.pyc} 文件，并在必要时进行编译。

如果 @ref{a09,,PyZipFile} 的 @emph{optimize} 形参为 @code{0}, @code{1} 或 @code{2}，则限具有相应优化级别 (参见 @ref{2ee,,compile()}) 的文件会被添加到归档，并在必要时进行编译。

如果 @emph{pathname} 是文件，则文件名必须以 @code{.py} 为后缀，并且只有 (相应的 @code{*.pyc}) 文件会被添加到最高层级（不带路径信息）。 如果 @emph{pathname} 不是以 @code{.py} 为后缀的文件，则将引发 @ref{3e4,,RuntimeError}。 如果它是目录，并且该目录不是一个包目录，则所有的 @code{*.pyc} 文件会被添加到最高层级。 如果目录是一个包目录，则所有的 @code{*.pyc} 会被添加到包名所表示的文件路径下，并且如果有任何子目录为包目录，则会以排好的顺序递归地添加这些目录。

@emph{basename} 仅限在内部使用。

如果给定 @emph{filterfunc}，则它必须是一个接受单个字符串参数的函数。 在将其添加到归档之前它将被传入每个路径（包括每个单独的完整路径）。 如果 @emph{filterfunc} 返回假值，则路径将不会被添加，而如果它是一个目录则其内容将被忽略。 例如，如果我们的测试文件全都位于 @code{test} 目录或以字符串 @code{test_} 打头，则我们可以使用一个 @emph{filterfunc} 来排除它们:

@example
>>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
...     fn = os.path.basename(s)
...     return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)
@end example

@ref{a08,,writepy()} 方法会产生带有这样一些文件名的归档:

@example
string.pyc                   # Top level name
test/__init__.pyc            # Package directory
test/testall.pyc             # Module test.testall
test/bogus/__init__.pyc      # Subpackage directory
test/bogus/myfile.pyc        # Submodule test.bogus.myfile
@end example


3.4 新版功能: @emph{filterfunc} 形参。



在 3.6.2 版更改: @emph{pathname} 形参接受一个 @ref{47b,,path-like object}。



在 3.7 版更改: 递归排序目录条目。

@end deffn
@end deffn

@node ZipInfo 对象,命令行界面<2>,PyZipFile 对象,zipfile --- 使用ZIP存档
@anchor{library/zipfile id4}@anchor{1f55}@anchor{library/zipfile zipinfo-objects}@anchor{1f37}
@subsubsection ZipInfo 对象


@ref{6bb,,ZipInfo} 类的实例会通过 @ref{1f35,,getinfo()} 和 @ref{52b,,ZipFile} 对象的 @ref{1f36,,infolist()} 方法返回。 每个对象将存储关于 ZIP 归档的一个成员的信息。

有一个类方法可以为文件系统文件创建 @ref{6bb,,ZipInfo} 实例:

@geindex from_file() (zipfile.ZipInfo 类方法)
@anchor{library/zipfile zipfile ZipInfo from_file}@anchor{6ba}
@deffn {方法} classmethod ZipInfo.from_file (filename, arcname=None, *, strict_timestamps=True)

为文件系统中的文件构造一个 @ref{6bb,,ZipInfo} 实例，并准备将其添加到一个 zip 文件。

@emph{filename} 应为文件系统中某个文件或目录的路径。

如果指定了 @emph{arcname}，它会被用作归档中的名称。 如果未指定 @emph{arcname}，则所用名称与 @emph{filename} 相同，但将去除任何驱动器盘符和打头的路径分隔符。

@emph{strict_timestamps} 参数在设为 @code{False} 时允许压缩早于 1980-01-01 的文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于 2107-12-31 的文件发生，时间戳也会被设为该上限值。


3.6 新版功能.



在 3.6.2 版更改: @emph{filename} 形参接受一个 @ref{47b,,path-like object}。



3.8 新版功能: @emph{strict_timestamps} 仅限关键字参数

@end deffn

实例具有下列方法和属性:

@geindex is_dir() (zipfile.ZipInfo 方法)
@anchor{library/zipfile zipfile ZipInfo is_dir}@anchor{6bc}
@deffn {方法} ZipInfo.is_dir ()

如果此归档成员是一个目录则返回 @code{True}。

这会使用条目的名称：目录应当总是以 @code{/} 结尾。


3.6 新版功能.

@end deffn

@geindex filename (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo filename}@anchor{1f56}
@deffn {属性} ZipInfo.filename

归档中的文件名称。
@end deffn

@geindex date_time (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo date_time}@anchor{1f57}
@deffn {属性} ZipInfo.date_time

上次修改存档成员的时间和日期。这是六个值的元组：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

值

@item

@code{0}

@tab

Year (>= 1980)

@item

@code{1}

@tab

月（1为基数）

@item

@code{2}

@tab

月份中的日期（1为基数）

@item

@code{3}

@tab

小时（0为基数）

@item

@code{4}

@tab

分钟（0为基数）

@item

@code{5}

@tab

秒（0为基数）

@end multitable


@cartouche
@quotation 注解 
ZIP文件格式不支持1980年以前的时间戳。
@end quotation
@end cartouche
@end deffn

@geindex compress_type (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo compress_type}@anchor{1f58}
@deffn {属性} ZipInfo.compress_type

归档成员的压缩类型。
@end deffn

@geindex comment (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo comment}@anchor{1f59}
@deffn {属性} ZipInfo.comment

@ref{172,,bytes} 对象形式的单个归档成员的注释。
@end deffn

@geindex extra (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo extra}@anchor{1f5a}
@deffn {属性} ZipInfo.extra

扩展字段数据。 PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT} 包含一些保存于该 @ref{172,,bytes} 对象中的内部结构的注释。
@end deffn

@geindex create_system (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo create_system}@anchor{1f5b}
@deffn {属性} ZipInfo.create_system

创建 ZIP 归档所用的系统。
@end deffn

@geindex create_version (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo create_version}@anchor{1f5c}
@deffn {属性} ZipInfo.create_version

创建 ZIP 归档所用的 PKZIP 版本。
@end deffn

@geindex extract_version (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo extract_version}@anchor{1f5d}
@deffn {属性} ZipInfo.extract_version

需要用来提取归档的 PKZIP 版本。
@end deffn

@geindex reserved (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo reserved}@anchor{1f5e}
@deffn {属性} ZipInfo.reserved

必须为零。
@end deffn

@geindex flag_bits (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo flag_bits}@anchor{1f5f}
@deffn {属性} ZipInfo.flag_bits

ZIP 标志位。
@end deffn

@geindex volume (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo volume}@anchor{1f60}
@deffn {属性} ZipInfo.volume

文件头的分卷号。
@end deffn

@geindex internal_attr (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo internal_attr}@anchor{1f61}
@deffn {属性} ZipInfo.internal_attr

内部属性。
@end deffn

@geindex external_attr (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo external_attr}@anchor{1f62}
@deffn {属性} ZipInfo.external_attr

外部文件属性。
@end deffn

@geindex header_offset (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo header_offset}@anchor{1f63}
@deffn {属性} ZipInfo.header_offset

文件头的字节偏移量。
@end deffn

@geindex CRC (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo CRC}@anchor{1f64}
@deffn {属性} ZipInfo.CRC

未压缩文件的 CRC-32。
@end deffn

@geindex compress_size (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo compress_size}@anchor{1f65}
@deffn {属性} ZipInfo.compress_size

已压缩数据的大小。
@end deffn

@geindex file_size (zipfile.ZipInfo 属性)
@anchor{library/zipfile zipfile ZipInfo file_size}@anchor{1f41}
@deffn {属性} ZipInfo.file_size

未压缩文件的大小。
@end deffn

@node 命令行界面<2>,解压缩的障碍,ZipInfo 对象,zipfile --- 使用ZIP存档
@anchor{library/zipfile command-line-interface}@anchor{1f66}@anchor{library/zipfile zipfile-commandline}@anchor{1f67}
@subsubsection 命令行界面


@ref{14b,,zipfile} 模块提供了简单的命令行接口用于与 ZIP 归档的交互。

如果你想要创建一个新的 ZIP 归档，请在 @ref{1f68,,-c} 选项后指定其名称然后列出应当被包含的文件名:

@example
$ python -m zipfile -c monty.zip spam.txt eggs.txt
@end example

传入一个目录也是可接受的:

@example
$ python -m zipfile -c monty.zip life-of-brian_1979/
@end example

如果你想要将一个 ZIP 归档提取到指定的目录，请使用 @ref{1f69,,-e} 选项:

@example
$ python -m zipfile -e monty.zip target-dir/
@end example

要获取一个 ZIP 归档中的文件列表，请使用 @ref{1f6a,,-l} 选项:

@example
$ python -m zipfile -l monty.zip
@end example

@menu
* 命令行选项: 命令行选项<2>. 

@end menu

@node 命令行选项<2>,,,命令行界面<2>
@anchor{library/zipfile command-line-options}@anchor{1f6b}
@subsubsection 命令行选项


@geindex zipfile command line option; -l <zipfile>
@geindex zipfile command line option; --list <zipfile>
@anchor{library/zipfile cmdoption-zipfile-l}@anchor{1f6a}
@deffn {程序选项} @w{-}l <zipfile>
@anchor{library/zipfile cmdoption-zipfile-list}@anchor{1f6c}
@deffnx {程序选项} @w{-}@w{-}list <zipfile>

列出一个 zipfile 中的文件名。
@end deffn

@geindex zipfile command line option; -c <zipfile> <source1> ... <sourceN>
@geindex zipfile command line option; --create <zipfile> <source1> ... <sourceN>
@anchor{library/zipfile cmdoption-zipfile-c}@anchor{1f68}
@deffn {程序选项} @w{-}c <zipfile> <source1> ... <sourceN>
@anchor{library/zipfile cmdoption-zipfile-create}@anchor{1f6d}
@deffnx {程序选项} @w{-}@w{-}create <zipfile> <source1> ... <sourceN>

基于源文件创建 zipfile。
@end deffn

@geindex zipfile command line option; -e <zipfile> <output_dir>
@geindex zipfile command line option; --extract <zipfile> <output_dir>
@anchor{library/zipfile cmdoption-zipfile-e}@anchor{1f69}
@deffn {程序选项} @w{-}e <zipfile> <output_dir>
@anchor{library/zipfile cmdoption-zipfile-extract}@anchor{1f6e}
@deffnx {程序选项} @w{-}@w{-}extract <zipfile> <output_dir>

将 zipfile 提取到目标目录中。
@end deffn

@geindex zipfile command line option; -t <zipfile>
@geindex zipfile command line option; --test <zipfile>
@anchor{library/zipfile cmdoption-zipfile-t}@anchor{1f6f}
@deffn {程序选项} @w{-}t <zipfile>
@anchor{library/zipfile cmdoption-zipfile-test}@anchor{1f70}
@deffnx {程序选项} @w{-}@w{-}test <zipfile>

检测 zipfile 是否有效。
@end deffn

@node 解压缩的障碍,,命令行界面<2>,zipfile --- 使用ZIP存档
@anchor{library/zipfile decompression-pitfalls}@anchor{1f71}
@subsubsection 解压缩的障碍


zipfile 模块的提取操作可能会由于下面列出的障碍而失败。

@menu
* 由于文件本身:: 
* 文件系统限制:: 
* 资源限制:: 
* 中断:: 
* 提取的默认行为:: 

@end menu

@node 由于文件本身,文件系统限制,,解压缩的障碍
@anchor{library/zipfile from-file-itself}@anchor{1f72}
@subsubsection 由于文件本身


解压缩可能由于不正确的密码 / CRC 校验和 / ZIP 格式或不受支持的压缩 / 解密方法而失败。

@node 文件系统限制,资源限制,由于文件本身,解压缩的障碍
@anchor{library/zipfile file-system-limitations}@anchor{1f73}
@subsubsection 文件系统限制


超出特定文件系统上的限制可能会导致解压缩失败。 例如目录条目所允许的字符、文件名的长度、路径名的长度、单个文件的大小以及文件的数量等等。

@node 资源限制,中断,文件系统限制,解压缩的障碍
@anchor{library/zipfile resources-limitations}@anchor{1f74}@anchor{library/zipfile zipfile-resources-limitations}@anchor{1f75}
@subsubsection 资源限制


缺乏内存或磁盘空间将会导致解压缩失败。 例如，作用于 zipfile 库的解压缩炸弹 (即 ZIP bomb@footnote{https://en.wikipedia.org/wiki/Zip_bomb}) 就可能造成磁盘空间耗尽。

@node 中断,提取的默认行为,资源限制,解压缩的障碍
@anchor{library/zipfile interruption}@anchor{1f76}
@subsubsection 中断


在解压缩期间中断执行，例如按下 ctrl-C 或杀死解压缩进程可能会导致归档文件的解压缩不完整。

@node 提取的默认行为,,中断,解压缩的障碍
@anchor{library/zipfile default-behaviors-of-extraction}@anchor{1f77}
@subsubsection 提取的默认行为


不了解提取的默认行为可能导致不符合期望的解压缩结果。 例如，当提取相同归档两次时，它会不经询问地覆盖文件。

@node tarfile --- 读写tar归档文件,,zipfile --- 使用ZIP存档,数据压缩和存档
@anchor{library/tarfile doc}@anchor{1f78}@anchor{library/tarfile module-tarfile}@anchor{101}@anchor{library/tarfile pkzip-application-note}@anchor{1f79}@anchor{library/tarfile tarfile-read-and-write-tar-archive-files}@anchor{1f7a}
@subsection @code{tarfile} --- 读写tar归档文件


@geindex tarfile (模块)

@strong{源代码:} Lib/tarfile.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tarfile.py}


__________________________________________________________________


@ref{101,,tarfile} 模块可以用来读写 tar 归档，包括使用 gzip, bz2 和 lzma 压缩的归档。 请使用 @ref{14b,,zipfile} 模块来读写 @code{.zip} 文件，或者使用 @ref{c70,,shutil} 的高层级函数。

一些事实和数字:


@itemize *

@item 
读写 @ref{8b,,gzip}, @ref{13,,bz2} 和 @ref{ad,,lzma} 解压的归档要求相应的模块可用。

@item 
支持读取 / 写入 POSIX.1-1988 (ustar) 格式。

@item 
对 GNU tar 格式的读/写支持，包括 @emph{longname} 和 @emph{longlink} 扩展，对所有种类 @emph{sparse} 扩展的只读支持，包括 sparse 文件的恢复。

@item 
对 POSIX.1-2001 (pax) 格式的读/写支持。

@item 
处理目录、正常文件、硬链接、符号链接、fifo 管道、字符设备和块设备，并且能够获取和恢复文件信息例如时间戳、访问权限和所有者等。
@end itemize


在 3.3 版更改: 添加了对 @ref{ad,,lzma} 压缩的支持。


@geindex open() (在 tarfile 模块中)
@anchor{library/tarfile tarfile open}@anchor{85f}
@deffn {函数} tarfile.open (name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

针对路径名 @emph{name} 返回 @ref{c66,,TarFile} 对象。 有关 @ref{c66,,TarFile} 对象以及所允许的关键字参数的详细信息请参阅 @ref{1f7b,,TarFile 对象}。

@emph{mode} 必须是 @code{'filemode[:compression]'} 形式的字符串，其默认值为 @code{'r'}。 以下是模式组合的完整列表:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

模式

@tab

动作

@item

@code{'r' or 'r:*'}

@tab

打开和读取使用透明压缩（推荐）。

@item

@code{'r:'}

@tab

打开和读取不使用压缩。

@item

@code{'r:gz'}

@tab

打开和读取使用gzip 压缩。

@item

@code{'r:bz2'}

@tab

打开和读取使用bzip2 压缩。

@item

@code{'r:xz'}

@tab

打开和读取使用lzma 压缩。

@item

@code{'x'} 或 @code{'x:'}

@tab

创建tarfile不进行压缩。如果文件已经存在，则抛出 @ref{a42,,FileExistsError} 异常。

@item

@code{'x:gz'}

@tab

使用gzip压缩创建tarfile。如果文件已经存在，则抛出 @ref{a42,,FileExistsError} 异常。

@item

@code{'x:bz2'}

@tab

使用bzip2 压缩创建tarfile。如果文件已经存在，则抛出 @ref{a42,,FileExistsError} 异常。

@item

@code{'x:xz'}

@tab

使用lzma 压缩创建tarfile。如果文件已经存在，则抛出 @ref{a42,,FileExistsError} 异常。

@item

@code{'a' or 'a:'}

@tab

打开以便在没有压缩的情况下追加。如果文件不存在，则创建该文件。

@item

@code{'w' or 'w:'}

@tab

打开用于未压缩的写入。

@item

@code{'w:gz'}

@tab

打开用于 gzip 压缩的写入。

@item

@code{'w:bz2'}

@tab

打开用于 bzip2 压缩的写入。

@item

@code{'w:xz'}

@tab

打开用于 lzma 压缩的写入。

@end multitable


请注意 @code{'a:gz'}, @code{'a:bz2'} 或 @code{'a:xz'} 是不可能的组合。 如果 @emph{mode} 不适用于打开特定（压缩的）文件用于读取，则会引发 @ref{fbc,,ReadError}。 请使用 @emph{mode} @code{'r'} 来避免这种情况。 如果某种压缩方法不受支持，则会引发 @ref{1f7c,,CompressionError}。

如果指定了 @emph{fileobj}，它会被用作对应于 @emph{name} 的以二进制模式打开的 @ref{c1d,,file object} 的替代。 它会被设定为处在位置 0。

对于 @code{'w:gz'}, @code{'r:gz'}, @code{'w:bz2'}, @code{'r:bz2'}, @code{'x:gz'}, @code{'x:bz2'} 等模式，@ref{85f,,tarfile.open()} 接受关键字参数 @emph{compresslevel} (默认值为 @code{9}) 来指定文件的压缩等级。

对于 @code{'w:xz'} 和 @code{'x:xz'} 模式，@ref{85f,,tarfile.open()} 接受关键字参数 @emph{preset} 来指定文件的压缩等级。

针对特殊的目的，还存在第二种 @emph{mode} 格式: @code{'filemode|[compression]'}。 @ref{85f,,tarfile.open()} 将返回一个将其数据作为数据块流来处理的 @ref{c66,,TarFile} 对象。 对此文件将不能执行随机查找。 如果给定了 @emph{fileobj}，它可以是任何具有 @code{read()} 或 @code{write()} 方法 (由 @emph{mode} 确定) 的对象。 @emph{bufsize} 指定块大小，默认值为 @code{20 * 512} 字节。 可与此格式组合使用的有 @code{sys.stdin}, 套接字 @ref{c1d,,file object} 或磁带设备等。 但是，对于这样的 @ref{c66,,TarFile} 对象存在不允许随机访问的限制，参见 @ref{1f7d,,示例}。 目前可用的模式如下:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

模式

@tab

动作

@item

@code{'r|*'}

@tab

打开 tar 块的 @emph{流} 以进行透明压缩读取。

@item

@code{'r|'}

@tab

打开一个未压缩的 tar 块的 @emph{stream} 用于读取。

@item

@code{'r|gz'}

@tab

打开一个 gzip 压缩的 @emph{stream} 用于读取。

@item

@code{'r|bz2'}

@tab

打开一个 bzip2 压缩的 @emph{stream} 用于读取。

@item

@code{'r|xz'}

@tab

打开一个 lzma 压缩 @emph{stream} 用于读取。

@item

@code{'w|'}

@tab

打开一个未压缩的 @emph{stream} 用于写入。

@item

@code{'w|gz'}

@tab

打开一个 gzip 压缩的 @emph{stream} 用于写入。

@item

@code{'w|bz2'}

@tab

打开一个 bzip2 压缩的 @emph{stream} 用于写入。

@item

@code{'w|xz'}

@tab

打开一个 lzma 压缩的 @emph{stream} 用于写入。

@end multitable



在 3.5 版更改: 添加了 @code{'x'} (仅创建) 模式。



在 3.6 版更改: @emph{name} 形参接受一个 @ref{47b,,path-like object}。

@end deffn


@deffn {类} tarfile.TarFile

用于读取和写入 tar 归档的类。 请不要直接使用这个类：而要使用 @ref{85f,,tarfile.open()}。 参见 @ref{1f7b,,TarFile 对象}。
@end deffn

@geindex is_tarfile() (在 tarfile 模块中)
@anchor{library/tarfile tarfile is_tarfile}@anchor{10e9}
@deffn {函数} tarfile.is_tarfile (name)

如果 @emph{name} 是一个 @ref{101,,tarfile} 能读取的 tar 归档文件则返回 @ref{59c,,True}。 @emph{name} 可以为 @ref{206,,str}，文件或文件类对象。


在 3.9 版更改: 支持文件或类文件对象。

@end deffn

@ref{101,,tarfile} 模块定义了以下异常:

@geindex TarError
@anchor{library/tarfile tarfile TarError}@anchor{1f7e}
@deffn {例外} tarfile.TarError

所有 @ref{101,,tarfile} 异常的基类。
@end deffn

@geindex ReadError
@anchor{library/tarfile tarfile ReadError}@anchor{fbc}
@deffn {例外} tarfile.ReadError

当一个不能被 @ref{101,,tarfile} 模块处理或者因某种原因而无效的 tar 归档被打开时将被引发。
@end deffn

@geindex CompressionError
@anchor{library/tarfile tarfile CompressionError}@anchor{1f7c}
@deffn {例外} tarfile.CompressionError

当一个压缩方法不受支持或者当数据无法被正确解码时将被引发。
@end deffn

@geindex StreamError
@anchor{library/tarfile tarfile StreamError}@anchor{1f7f}
@deffn {例外} tarfile.StreamError

当达到流式 @ref{c66,,TarFile} 对象的典型限制时将被引发。
@end deffn

@geindex ExtractError
@anchor{library/tarfile tarfile ExtractError}@anchor{1f80}
@deffn {例外} tarfile.ExtractError

当使用 @ref{861,,TarFile.extract()} 时针对 @emph{non-fatal} 所引发的异常，但是仅限 @ref{1f81,,TarFile.errorlevel}@code{== 2}。
@end deffn

@geindex HeaderError
@anchor{library/tarfile tarfile HeaderError}@anchor{1f82}
@deffn {例外} tarfile.HeaderError

如果获取的缓冲区无效则会由 @ref{1f83,,TarInfo.frombuf()} 引发的异常。
@end deffn

@geindex FilterError
@anchor{library/tarfile tarfile FilterError}@anchor{1f84}
@deffn {例外} tarfile.FilterError

Base class for members @ref{1f85,,refused} by
filters.

@geindex tarinfo (tarfile.FilterError 属性)
@anchor{library/tarfile tarfile FilterError tarinfo}@anchor{1f86}
@deffn {属性} tarinfo

Information about the member that the filter refused to extract,
as @ref{1f87,,TarInfo}.
@end deffn
@end deffn

@geindex AbsolutePathError
@anchor{library/tarfile tarfile AbsolutePathError}@anchor{1f88}
@deffn {例外} tarfile.AbsolutePathError

Raised to refuse extracting a member with an absolute path.
@end deffn

@geindex OutsideDestinationError
@anchor{library/tarfile tarfile OutsideDestinationError}@anchor{1f89}
@deffn {例外} tarfile.OutsideDestinationError

Raised to refuse extracting a member outside the destination directory.
@end deffn

@geindex SpecialFileError
@anchor{library/tarfile tarfile SpecialFileError}@anchor{1f8a}
@deffn {例外} tarfile.SpecialFileError

Raised to refuse extracting a special file (e.g. a device or pipe).
@end deffn

@geindex AbsoluteLinkError
@anchor{library/tarfile tarfile AbsoluteLinkError}@anchor{1f8b}
@deffn {例外} tarfile.AbsoluteLinkError

Raised to refuse extracting a symbolic link with an absolute path.
@end deffn

@geindex LinkOutsideDestinationError
@anchor{library/tarfile tarfile LinkOutsideDestinationError}@anchor{1f8c}
@deffn {例外} tarfile.LinkOutsideDestinationError

Raised to refuse extracting a symbolic link pointing outside the destination
directory.
@end deffn

以下常量在模块层级上可用:

@geindex ENCODING() (在 tarfile 模块中)
@anchor{library/tarfile tarfile ENCODING}@anchor{1f8d}
@deffn {数据} tarfile.ENCODING

默认的字符编码格式：在 Windows 上为 @code{'utf-8'}，其他系统上则为 @ref{5f8,,sys.getfilesystemencoding()} 所返回的值。
@end deffn

以下常量各自定义了一个 @ref{101,,tarfile} 模块能够创建的 tar 归档格式。 相关细节请参阅 @ref{1f8e,,受支持的 tar 格式} 小节。

@geindex USTAR_FORMAT() (在 tarfile 模块中)
@anchor{library/tarfile tarfile USTAR_FORMAT}@anchor{1f8f}
@deffn {数据} tarfile.USTAR_FORMAT

POSIX.1-1988 (ustar) 格式。
@end deffn

@geindex GNU_FORMAT() (在 tarfile 模块中)
@anchor{library/tarfile tarfile GNU_FORMAT}@anchor{1f90}
@deffn {数据} tarfile.GNU_FORMAT

GNU tar 格式。
@end deffn

@geindex PAX_FORMAT() (在 tarfile 模块中)
@anchor{library/tarfile tarfile PAX_FORMAT}@anchor{1f91}
@deffn {数据} tarfile.PAX_FORMAT

POSIX.1-2001 (pax) 格式。
@end deffn

@geindex DEFAULT_FORMAT() (在 tarfile 模块中)
@anchor{library/tarfile tarfile DEFAULT_FORMAT}@anchor{1f92}
@deffn {数据} tarfile.DEFAULT_FORMAT

用于创建归档的默认格式。 目前为 @ref{1f91,,PAX_FORMAT}。


在 3.8 版更改: 新归档的默认格式已更改为 @ref{1f91,,PAX_FORMAT} 而不再是 @ref{1f90,,GNU_FORMAT}。

@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{14b,,zipfile}

@ref{14b,,zipfile} 标准模块的文档。

@item @ref{c70,,归档操作}

标准 @ref{e9,,shutil} 模块所提供的高层级归档工具的文档。

@item GNU tar manual@comma{} Basic Tar Format@footnote{https://www.gnu.org/software/tar/manual/html_node/Standard.html}

针对 tar 归档文件的文档，包含 GNU tar 扩展。
@end table


@menu
* TarFile 对象:: 
* TarInfo 对象:: 
* Extraction filters:: 
* 命令行界面: 命令行界面<3>. 
* 示例: 示例<12>. 
* 受支持的 tar 格式:: 
* Unicode 问题:: 

@end menu

@node TarFile 对象,TarInfo 对象,,tarfile --- 读写tar归档文件
@anchor{library/tarfile id1}@anchor{1f93}@anchor{library/tarfile tarfile-objects}@anchor{1f7b}
@subsubsection TarFile 对象


@ref{c66,,TarFile} 对象提供了一个 tar 归档的接口。 一个 tar 归档就是数据块的序列。 一个归档成员（被保存文件）是由一个标头块加多个数据块组成的。 一个文件可以在一个 tar 归档中多次被保存。 每个归档成员都由一个 @ref{c67,,TarInfo} 对象来代表，详情参见 @ref{1f87,,TarInfo 对象}。

@ref{c66,,TarFile} 对象可在 @ref{7e4,,with} 语句中作为上下文管理器使用。 当语句块结束时它将自动被关闭。 请注意在发生异常事件时被打开用于写入的归档将不会被终结；只有内部使用的文件对象将被关闭。 相关用例请参见 @ref{1f7d,,示例}。


3.2 新版功能: 添加了对上下文管理器协议的支持。


@geindex TarFile (tarfile 中的类)
@anchor{library/tarfile tarfile TarFile}@anchor{c66}
@deffn {类} tarfile.TarFile (name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=1)

下列所有参数都是可选项并且也可作为实例属性来访问。

@emph{name} 是归档的路径名称。 @emph{name} 可以是一个 @ref{47b,,path-like object}。 如果给定了 @emph{fileobj} 则它可以被省略。 在此情况下，如果对象的 @code{name} 属性存在则它会被使用。

@emph{mode} 可以为 @code{'r'} 表示从现有归档读取，@code{'a'} 表示将数据追加到现有文件，@code{'w'} 表示创建新文件覆盖现有文件，或者 @code{'x'} 表示仅在文件不存在时创建新文件。

如果给定了 @emph{fileobj}，它会被用于读取或写入数据。 如果可以被确定，则 @emph{mode} 会被 @emph{fileobj} 的模式所覆盖。 @emph{fileobj} 的使用将从位置 0 开始。

@cartouche
@quotation 注解 
当 @ref{c66,,TarFile} 被关闭时，@emph{fileobj} 不会被关闭。
@end quotation
@end cartouche

@emph{format} 控制用于写入的归档格式。 它必须为在模块层级定义的常量 @ref{1f8f,,USTAR_FORMAT}, @ref{1f90,,GNU_FORMAT} 或 @ref{1f91,,PAX_FORMAT} 中的一个。 当读取时，格式将被自动检测，即使单个归档中存在不同的格式。

@emph{tarinfo} 参数可以被用来将默认的 @ref{c67,,TarInfo} 类替换为另一个。

如果 @emph{dereference} 为 @ref{497,,False}，则会将符号链接和硬链接添加到归档中。 如果为 @ref{59c,,True}，则会将目标文件的内容添加到归档中。 在不支持符号链接的系统上参数将不起作用。

如果 @emph{ignore_zeros} 为 @ref{497,,False}，则会将空的数据块当作归档的末尾来处理。 如果为 @ref{59c,,True}，则会跳过空的（和无效的）数据块并尝试获取尽可能多的成员。 此参数仅适用于读取拼接的或损坏的归档。

@emph{debug} 可设为从 @code{0} (无调试消息) 到 @code{3} (全部调试消息)。 消息会被写入到 @code{sys.stderr}。

@emph{errorlevel} controls how extraction errors are handled,
see @code{the corresponding attribute}.

@emph{encoding} 和 @emph{errors} 参数定义了读取或写入归档所使用的字符编码格式以及要如何处理转换错误。 默认设置将适用于大多数用户。 要深入了解详情可参阅 @ref{1f94,,Unicode 问题} 小节。

可选的 @emph{pax_headers} 参数是字符串的字典，如果 @emph{format} 为 @ref{1f91,,PAX_FORMAT} 它将被作为 pax 全局标头被添加。


在 3.2 版更改: 使用 @code{'surrogateescape'} 作为 @emph{errors} 参数的默认值。



在 3.5 版更改: 添加了 @code{'x'} (仅创建) 模式。



在 3.6 版更改: @emph{name} 形参接受一个 @ref{47b,,path-like object}。

@end deffn

@geindex open() (tarfile.TarFile 类方法)
@anchor{library/tarfile tarfile TarFile open}@anchor{1f95}
@deffn {方法} classmethod TarFile.open (...)

作为替代的构造器。 @ref{85f,,tarfile.open()} 函数实际上是这个类方法的快捷方式。
@end deffn

@geindex getmember() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile getmember}@anchor{f91}
@deffn {方法} TarFile.getmember (name)

返回成员 @emph{name} 的 @ref{c67,,TarInfo} 对象。 如果 @emph{name} 在归档中找不到，则会引发 @ref{3f1,,KeyError}。

@cartouche
@quotation 注解 
如果一个成员在归档中出现超过一次，它的最后一次出现会被视为是最新的版本。
@end quotation
@end cartouche
@end deffn

@geindex getmembers() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile getmembers}@anchor{863}
@deffn {方法} TarFile.getmembers ()

以 @ref{c67,,TarInfo} 对象列表的形式返回归档的成员。 列表的顺序与归档中成员的顺序一致。
@end deffn

@geindex getnames() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile getnames}@anchor{1f96}
@deffn {方法} TarFile.getnames ()

以名称列表的形式返回成员。 它的顺序与 @ref{863,,getmembers()} 所返回列表的顺序一致。
@end deffn

@geindex list() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile list}@anchor{862}
@deffn {方法} TarFile.list (verbose=True, *, members=None)

将内容清单打印到 @code{sys.stdout}。 如果 @emph{verbose} 为 @ref{497,,False}，则将只打印成员名称。 如果为 @ref{59c,,True}，则输出将类似于 @code{ls -l} 的输出效果。 如果给定了可选的 @emph{members}，它必须为 @ref{863,,getmembers()} 所返回的列表的一个子集。


在 3.5 版更改: 添加了 @emph{members} 形参。

@end deffn

@geindex next() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile next}@anchor{1f97}
@deffn {方法} TarFile.next ()

当 @ref{c66,,TarFile} 被打开用于读取时，以 @ref{c67,,TarInfo} 对象的形式返回归档的下一个成员。 如果不再有可用对象则返回 @ref{204,,None}。
@end deffn

@geindex extractall() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile extractall}@anchor{860}
@deffn {方法} TarFile.extractall (path=".", members=None, *, numeric_owner=False, filter=None)

将归档中的所有成员提取到当前工作目录或 @emph{path} 目录。 如果给定了可选的 @emph{members}，则它必须为 @ref{863,,getmembers()} 所返回的列表的一个子集。 字典信息例如所有者、修改时间和权限会在所有成员提取完毕后被设置。 这样做是为了避免两个问题：目录的修改时间会在每当在其中创建文件时被重置。 并且如果目录的权限不允许写入，提取文件到目录的操作将失败。

如果 @emph{numeric_owner} 为 @ref{59c,,True}，则将使用来自 tarfile 的 uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下，则会使用来自 tarfile 的名称值。

The @emph{filter} argument, which was added in Python 3.9.17, specifies how
@code{members} are modified or rejected before extraction.
See @ref{28c,,Extraction filters} for details.
It is recommended to set this explicitly depending on which @emph{tar} features
you need to support.

@cartouche
@quotation 警告 
绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有可能在 @emph{path} 之外创建文件，例如某些成员具有以 @code{"/"} 开始的绝对路径文件名或带有两个点号 @code{".."} 的文件名。

Set @code{filter='data'} to prevent the most dangerous security issues,
and read the @ref{28c,,Extraction filters} section for details.
@end quotation
@end cartouche


在 3.5 版更改: 添加了 @emph{numeric_owner} 形参。



在 3.6 版更改: @emph{path} 形参接受一个 @ref{47b,,path-like object}。



在 3.9.17 版更改: 添加了 @emph{filter} 形参。

@end deffn

@geindex extract() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile extract}@anchor{861}
@deffn {方法} TarFile.extract (member, path="", set_attrs=True, *, numeric_owner=False, filter=None)

从归档中提取出一个成员放入当前工作目录，将使用其完整名称。 成员的文件信息会尽可能精确地被提取。 @emph{member} 可以是一个文件名或 @ref{c67,,TarInfo} 对象。 你可以使用 @emph{path} 指定一个不同的目录。 @emph{path} 可以是一个 @ref{47b,,path-like object}。 将会设置文件属性 (owner, mtime, mode) 除非 @emph{set_attrs} 为假值。

The @emph{numeric_owner} and @emph{filter} arguments are the same as
for @ref{860,,extractall()}.

@cartouche
@quotation 注解 
@ref{861,,extract()} 方法不会处理某些提取问题。 在大多数情况下你应当考虑使用 @ref{860,,extractall()} 方法。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
查看 @ref{860,,extractall()} 的警告信息。

Set @code{filter='data'} to prevent the most dangerous security issues,
and read the @ref{28c,,Extraction filters} section for details.
@end quotation
@end cartouche


在 3.2 版更改: 添加了 @emph{set_attrs} 形参。



在 3.5 版更改: 添加了 @emph{numeric_owner} 形参。



在 3.6 版更改: @emph{path} 形参接受一个 @ref{47b,,path-like object}。



在 3.9.17 版更改: 添加了 @emph{filter} 形参。

@end deffn

@geindex extractfile() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile extractfile}@anchor{1f98}
@deffn {方法} TarFile.extractfile (member)

将归档中的一个成员提取为文件对象。 @emph{member} 可以是一个文件名或 @ref{c67,,TarInfo} 对象。 如果 @emph{member} 是一个常规文件或链接，则会返回一个 @ref{c64,,io.BufferedReader} 对象。 对于所有其他现有成员，则都将返回 @ref{204,,None}。 如果 @emph{member} 未在归档中出现，则会引发 @ref{3f1,,KeyError}。


在 3.3 版更改: 返回一个 @ref{c64,,io.BufferedReader} 对象。

@end deffn

@geindex errorlevel (tarfile.TarFile 属性)
@anchor{library/tarfile tarfile TarFile errorlevel}@anchor{1f81}
@deffn {属性} TarFile.errorlevel: int

If @emph{errorlevel} is @code{0}, errors are ignored when using @ref{861,,TarFile.extract()}
and @ref{860,,TarFile.extractall()}.
Nevertheless, they appear as error messages in the debug output when
@emph{debug} is greater than 0.
If @code{1} (the default), all @emph{fatal} errors are raised as @ref{30b,,OSError} or
@ref{1f84,,FilterError} exceptions. If @code{2}, all @emph{non-fatal} errors are raised
as @ref{1f7e,,TarError} exceptions as well.

Some exceptions, e.g. ones caused by wrong argument types or data
corruption, are always raised.

Custom @ref{28c,,extraction filters}
should raise @ref{1f84,,FilterError} for @emph{fatal} errors
and @ref{1f80,,ExtractError} for @emph{non-fatal} ones.

Note that when an exception is raised, the archive may be partially
extracted. It is the user’s responsibility to clean up.
@end deffn

@geindex extraction_filter (tarfile.TarFile 属性)
@anchor{library/tarfile tarfile TarFile extraction_filter}@anchor{1f99}
@deffn {属性} TarFile.extraction_filter


3.9.17 新版功能.


The @ref{28c,,extraction filter} used
as a default for the @emph{filter} argument of @ref{861,,extract()}
and @ref{860,,extractall()}.

The attribute may be @code{None} or a callable.
String names are not allowed for this attribute, unlike the @emph{filter}
argument to @ref{861,,extract()}.

If @code{extraction_filter} is @code{None} (the default),
calling an extraction method without a @emph{filter} argument will
use the @ref{1f9a,,fully_trusted} filter for
compatibility with previous Python versions.

In Python 3.12+, leaving @code{extraction_filter=None} will emit a
@code{DeprecationWarning}.

In Python 3.14+, leaving @code{extraction_filter=None} will cause
extraction methods to use the @ref{1f9b,,data} filter by default.

The attribute may be set on instances or overridden in subclasses.
It also is possible to set it on the @code{TarFile} class itself to set a
global default, although, since it affects all uses of @emph{tarfile},
it is best practice to only do so in top-level applications or
@ref{eb,,site configuration}.
To set a global default this way, a filter function needs to be wrapped in
@ref{311,,staticmethod()} to prevent injection of a @code{self} argument.
@end deffn

@geindex add() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile add}@anchor{583}
@deffn {方法} TarFile.add (name, arcname=None, recursive=True, *, filter=None)

将文件 @emph{name} 添加到归档。 @emph{name} 可以为任意类型的文件（目录、fifo、符号链接等等）。 如果给出 @emph{arcname} 则它将为归档中的文件指定一个替代名称。 默认情况下会递归地添加目录。 这可以通过将 @emph{recursive} 设为 @ref{497,,False} 来避免。 递归操作会按排序顺序添加条目。 如果给定了 @emph{filter}，它应当为一个接受 @ref{c67,,TarInfo} 对象并返回已修改 @ref{c67,,TarInfo} 对象的函数。 如果它返回 @ref{204,,None} 则 @ref{c67,,TarInfo} 对象将从归档中被排除。 具体示例参见 @ref{1f7d,,示例}。


在 3.2 版更改: 添加了 @emph{filter} 形参。



在 3.7 版更改: 递归操作按排序顺序添加条目。

@end deffn

@geindex addfile() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile addfile}@anchor{1f9c}
@deffn {方法} TarFile.addfile (tarinfo, fileobj=None)

将 @ref{c67,,TarInfo} 对象 @emph{tarinfo} 添加到归档。 如果给定了 @emph{fileobj}，它应当是一个 @ref{140a,,binary file}，并会从中读取 @code{tarinfo.size} 个字节添加到归档。 你可以直接创建 @ref{c67,,TarInfo} 对象，或是使用 @ref{1f9d,,gettarinfo()} 来创建。
@end deffn

@geindex gettarinfo() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile gettarinfo}@anchor{1f9d}
@deffn {方法} TarFile.gettarinfo (name=None, arcname=None, fileobj=None)

基于 @ref{328,,os.stat()} 的结果或者现有文件的相同数据创建一个 @ref{c67,,TarInfo}。 文件或者是命名为 @emph{name}，或者是使用文件描述符指定为一个 @ref{c1d,,file object} @emph{fileobj}。 @emph{name} 可以是一个 @ref{47b,,path-like object}。 如果给定了 @emph{arcname}，则它将为归档中的文件指定一个替代名称，在其他情况下，名称将从 @emph{fileobj} 的 @ref{1f9e,,name} 属性或 @emph{name} 参数获取。 名称应当是一个文本字符串。

你可以在使用 @ref{1f9c,,addfile()} 添加 @ref{c67,,TarInfo} 的某些属性之前修改它们。 如果文件对象不是从文件开头进行定位的普通文件对象，@ref{1f9f,,size} 之类的属性就可能需要修改。 例如 @ref{207,,GzipFile} 之类的文件就属于这种情况。  @ref{1fa0,,name} 也可以被修改，在这种情况下 @emph{arcname} 可以是一个占位字符串。


在 3.6 版更改: @emph{name} 形参接受一个 @ref{47b,,path-like object}。

@end deffn

@geindex close() (tarfile.TarFile 方法)
@anchor{library/tarfile tarfile TarFile close}@anchor{1fa1}
@deffn {方法} TarFile.close ()

关闭 @ref{c66,,TarFile}。 在写入模式下，会向归档添加两个表示结束的零数据块。
@end deffn

@geindex pax_headers (tarfile.TarFile 属性)
@anchor{library/tarfile tarfile TarFile pax_headers}@anchor{1fa2}
@deffn {属性} TarFile.pax_headers

一个包含 pax 全局标头的键值对的字典。
@end deffn

@node TarInfo 对象,Extraction filters,TarFile 对象,tarfile --- 读写tar归档文件
@anchor{library/tarfile id2}@anchor{1fa3}@anchor{library/tarfile tarinfo-objects}@anchor{1f87}
@subsubsection TarInfo 对象


@ref{c67,,TarInfo} 对象代表 @ref{c66,,TarFile} 中的一个文件。 除了会存储所有必要的文件属性（例如文件类型、大小、时间、权限、所有者等），它还提供了一些确定文件类型的有用方法。 此对象 @emph{并不} 包含文件数据本身。

@ref{c67,,TarInfo} objects are returned by @ref{c66,,TarFile}'s methods
@ref{f91,,getmember()}, @ref{863,,getmembers()} and
@ref{1f9d,,gettarinfo()}.

Modifying the objects returned by @code{getmember()} or
@code{getmembers()} will affect all subsequent
operations on the archive.
For cases where this is unwanted, you can use @ref{25,,copy.copy()} or
call the @code{replace()} method to create a modified copy in one step.

Several attributes can be set to @code{None} to indicate that a piece of metadata
is unused or unknown.
Different @ref{c67,,TarInfo} methods handle @code{None} differently:


@itemize -

@item 
The @ref{861,,extract()} or @ref{860,,extractall()} methods will
ignore the corresponding metadata, leaving it set to a default.

@item 
@ref{1f9c,,addfile()} will fail.

@item 
@ref{862,,list()} will print a placeholder string.
@end itemize


在 3.9.17 版更改: Added @code{replace()} and handling of @code{None}.


@geindex TarInfo (tarfile 中的类)
@anchor{library/tarfile tarfile TarInfo}@anchor{c67}
@deffn {类} tarfile.TarInfo (name="")

创建一个 @ref{c67,,TarInfo} 对象。
@end deffn

@geindex frombuf() (tarfile.TarInfo 类方法)
@anchor{library/tarfile tarfile TarInfo frombuf}@anchor{1f83}
@deffn {方法} classmethod TarInfo.frombuf (buf, encoding, errors)

基于字符串缓冲区 @emph{buf} 创建并返回一个 @ref{c67,,TarInfo} 对象。

如果缓冲区无效则会引发 @ref{1f82,,HeaderError}。
@end deffn

@geindex fromtarfile() (tarfile.TarInfo 类方法)
@anchor{library/tarfile tarfile TarInfo fromtarfile}@anchor{1fa4}
@deffn {方法} classmethod TarInfo.fromtarfile (tarfile)

从 @ref{c66,,TarFile} 对象 @emph{tarfile} 读取下一个成员并将其作为 @ref{c67,,TarInfo} 对象返回。
@end deffn

@geindex tobuf() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo tobuf}@anchor{1fa5}
@deffn {方法} TarInfo.tobuf (format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')

基于 @ref{c67,,TarInfo} 对象创建一个字符串缓冲区。 有关参数的信息请参见 @ref{c66,,TarFile} 类的构造器。


在 3.2 版更改: 使用 @code{'surrogateescape'} 作为 @emph{errors} 参数的默认值。

@end deffn

@code{TarInfo} 对象具有以下公有数据属性:

@geindex name (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo name}@anchor{1fa0}
@deffn {属性} TarInfo.name: str

归档成员的名称。
@end deffn

@geindex size (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo size}@anchor{1f9f}
@deffn {属性} TarInfo.size: int

以字节表示的大小。
@end deffn

@geindex mtime (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo mtime}@anchor{1fa6}
@deffn {属性} TarInfo.mtime: int | float

Time of last modification in seconds since the @ref{1fa7,,epoch},
as in @ref{1efd,,os.stat_result.st_mtime}.


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex mode (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo mode}@anchor{1fa8}
@deffn {属性} TarInfo.mode: int

Permission bits, as for @ref{b18,,os.chmod()}.


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex type (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo type}@anchor{1fa9}
@deffn {属性} TarInfo.type

文件类型。 @emph{type} 通常为以下常量之一: @code{REGTYPE}, @code{AREGTYPE}, @code{LNKTYPE}, @code{SYMTYPE}, @code{DIRTYPE}, @code{FIFOTYPE}, @code{CONTTYPE}, @code{CHRTYPE}, @code{BLKTYPE}, @code{GNUTYPE_SPARSE}。 要更方便地确定一个 @ref{c67,,TarInfo} 对象的类型，请使用下述的 @code{is*()} 方法。
@end deffn

@geindex linkname (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo linkname}@anchor{1faa}
@deffn {属性} TarInfo.linkname: str

目标文件名的名称，该属性仅在类型为 @code{LNKTYPE} 和 @code{SYMTYPE} 的 @ref{c67,,TarInfo} 对象中存在。
@end deffn

@geindex uid (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo uid}@anchor{1fab}
@deffn {属性} TarInfo.uid: int

最初保存该成员的用户的用户 ID。


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex gid (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo gid}@anchor{1fac}
@deffn {属性} TarInfo.gid: int

最初保存该成员的用户的分组 ID。


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex uname (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo uname}@anchor{1fad}
@deffn {属性} TarInfo.uname: str

用户名。


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex gname (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo gname}@anchor{1fae}
@deffn {属性} TarInfo.gname: str

分组名。


在 3.9.17 版更改: Can be set to @code{None} for @ref{861,,extract()} and
@ref{860,,extractall()}, causing extraction to skip applying this
attribute.

@end deffn

@geindex pax_headers (tarfile.TarInfo 属性)
@anchor{library/tarfile tarfile TarInfo pax_headers}@anchor{1faf}
@deffn {属性} TarInfo.pax_headers: dict

一个包含所关联的 pax 扩展标头的键值对的字典。
@end deffn


@deffn {方法} TarInfo.replace(name=..., mtime=..., mode=..., linkname=...,

@deffnx {方法} uid=..., gid=..., uname=..., gname=...,

@deffnx {方法} deep=True)


3.9.17 新版功能.


Return a @emph{new} copy of the @code{TarInfo} object with the given attributes
changed. For example, to return a @code{TarInfo} with the group name set to
@code{'staff'}, use:

@example
new_tarinfo = old_tarinfo.replace(gname='staff')
@end example

By default, a deep copy is made.
If @emph{deep} is false, the copy is shallow, i.e. @code{pax_headers}
and any custom attributes are shared with the original @code{TarInfo} object.
@end deffn

@ref{c67,,TarInfo} 对象还提供了一些便捷查询方法:

@geindex isfile() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isfile}@anchor{1fb0}
@deffn {方法} TarInfo.isfile ()

如果 @code{Tarinfo} 对象为普通文件则返回 @ref{59c,,True}。
@end deffn

@geindex isreg() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isreg}@anchor{1fb1}
@deffn {方法} TarInfo.isreg ()

与 @ref{1fb0,,isfile()} 相同。
@end deffn

@geindex isdir() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isdir}@anchor{1fb2}
@deffn {方法} TarInfo.isdir ()

如果为目录则返回 @ref{59c,,True}。
@end deffn

@geindex issym() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo issym}@anchor{1fb3}
@deffn {方法} TarInfo.issym ()

如果为符号链接则返回 @ref{59c,,True}。
@end deffn

@geindex islnk() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo islnk}@anchor{1fb4}
@deffn {方法} TarInfo.islnk ()

如果为硬链接则返回 @ref{59c,,True}。
@end deffn

@geindex ischr() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo ischr}@anchor{1fb5}
@deffn {方法} TarInfo.ischr ()

如果为字符设备则返回 @ref{59c,,True}。
@end deffn

@geindex isblk() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isblk}@anchor{1fb6}
@deffn {方法} TarInfo.isblk ()

如果为块设备则返回 @ref{59c,,True}。
@end deffn

@geindex isfifo() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isfifo}@anchor{1fb7}
@deffn {方法} TarInfo.isfifo ()

如果为 FIFO 则返回 @ref{59c,,True}。.
@end deffn

@geindex isdev() (tarfile.TarInfo 方法)
@anchor{library/tarfile tarfile TarInfo isdev}@anchor{1fb8}
@deffn {方法} TarInfo.isdev ()

如果为字符设备、块设备或 FIFO 之一则返回 @ref{59c,,True}。
@end deffn

@node Extraction filters,命令行界面<3>,TarInfo 对象,tarfile --- 读写tar归档文件
@anchor{library/tarfile extraction-filters}@anchor{1fb9}@anchor{library/tarfile tarfile-extraction-filter}@anchor{28c}
@subsubsection Extraction filters



3.9.17 新版功能.


The @emph{tar} format is designed to capture all details of a UNIX-like filesystem,
which makes it very powerful.
Unfortunately, the features make it easy to create tar files that have
unintended -- and possibly malicious -- effects when extracted.
For example, extracting a tar file can overwrite arbitrary files in various
ways (e.g.  by using absolute paths, @code{..} path components, or symlinks that
affect later members).

In most cases, the full functionality is not needed.
Therefore, @emph{tarfile} supports extraction filters: a mechanism to limit
functionality, and thus mitigate some of the security issues.


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 706

@item PEP 706@footnote{https://www.python.org/dev/peps/pep-0706}

Contains further motivation and rationale behind the design.
@end table


The @emph{filter} argument to @ref{861,,TarFile.extract()} or @ref{860,,extractall()}
can be:


@itemize *

@item 
the string @code{'fully_trusted'}: Honor all metadata as specified in the
archive.
Should be used if the user trusts the archive completely, or implements
their own complex verification.

@item 
the string @code{'tar'}: Honor most @emph{tar}-specific features (i.e. features of
UNIX-like filesystems), but block features that are very likely to be
surprising or malicious. See @ref{1fba,,tar_filter()} for details.

@item 
the string @code{'data'}: Ignore or block most features specific to UNIX-like
filesystems. Intended for extracting cross-platform data archives.
See @ref{1f9b,,data_filter()} for details.

@item 
@code{None} (default): Use @ref{1f99,,TarFile.extraction_filter}.

If that is also @code{None} (the default), the @code{'fully_trusted'}
filter will be used (for compatibility with earlier versions of Python).

In Python 3.12, the default will emit a @code{DeprecationWarning}.

In Python 3.14, the @code{'data'} filter will become the default instead.
It's possible to switch earlier; see @ref{1f99,,TarFile.extraction_filter}.

@item 
A callable which will be called for each extracted member with a
@ref{1f87,,TarInfo} describing the member and the destination
path to where the archive is extracted (i.e. the same path is used for all
members):

@example
filter(/, member: TarInfo, path: str) -> TarInfo | None
@end example

The callable is called just before each member is extracted, so it can
take the current state of the disk into account.
It can:


@itemize -

@item 
return a @ref{c67,,TarInfo} object which will be used instead of the metadata
in the archive, or

@item 
return @code{None}, in which case the member will be skipped, or

@item 
raise an exception to abort the operation or skip the member,
depending on @ref{1f81,,errorlevel}.
Note that when extraction is aborted, @ref{860,,extractall()} may leave
the archive partially extracted. It does not attempt to clean up.
@end itemize
@end itemize

@menu
* Default named filters:: 
* Filter errors:: 
* Hints for further verification:: 
* Supporting older Python versions:: 
* Stateful extraction filter example:: 

@end menu

@node Default named filters,Filter errors,,Extraction filters
@anchor{library/tarfile default-named-filters}@anchor{1fbb}
@subsubsection Default named filters


The pre-defined, named filters are available as functions, so they can be
reused in custom filters:

@geindex fully_trusted_filter() (在 tarfile 模块中)
@anchor{library/tarfile tarfile fully_trusted_filter}@anchor{1f9a}
@deffn {函数} tarfile.fully_trusted_filter (/, member, path)

Return @emph{member} unchanged.

This implements the @code{'fully_trusted'} filter.
@end deffn

@geindex tar_filter() (在 tarfile 模块中)
@anchor{library/tarfile tarfile tar_filter}@anchor{1fba}
@deffn {函数} tarfile.tar_filter (/, member, path)

Implements the @code{'tar'} filter.


@itemize -

@item 
Strip leading slashes (@code{/} and @ref{1e1c,,os.sep}) from filenames.

@item 
@ref{1f85,,Refuse} to extract files with absolute
paths (in case the name is absolute
even after stripping slashes, e.g. @code{C:/foo} on Windows).
This raises @ref{1f88,,AbsolutePathError}.

@item 
@ref{1f85,,Refuse} to extract files whose absolute
path (after following symlinks) would end up outside the destination.
This raises @ref{1f89,,OutsideDestinationError}.

@item 
Clear high mode bits (setuid, setgid, sticky) and group/other write bits
(@code{S_IWOTH}).
@end itemize

Return the modified @code{TarInfo} member.
@end deffn

@geindex data_filter() (在 tarfile 模块中)
@anchor{library/tarfile tarfile data_filter}@anchor{1f9b}
@deffn {函数} tarfile.data_filter (/, member, path)

Implements the @code{'data'} filter.
In addition to what @code{tar_filter} does:


@itemize -

@item 
@ref{1f85,,Refuse} to extract links (hard or soft)
that link to absolute paths, or ones that link outside the destination.

This raises @ref{1f8b,,AbsoluteLinkError} or
@ref{1f8c,,LinkOutsideDestinationError}.

Note that such files are refused even on platforms that do not support
symbolic links.

@item 
@ref{1f85,,Refuse} to extract device files
(including pipes).
This raises @ref{1f8a,,SpecialFileError}.

@item 
For regular files, including hard links:


@itemize -

@item 
Set the owner read and write permissions
(@code{S_IWUSR}).

@item 
Remove the group & other executable permission
(@code{S_IXOTH})
if the owner doesn’t have it (@ref{1dc8,,S_IXUSR}).
@end itemize

@item 
For other files (directories), set @code{mode} to @code{None}, so
that extraction methods skip applying permission bits.

@item 
Set user and group info (@code{uid}, @code{gid}, @code{uname}, @code{gname})
to @code{None}, so that extraction methods skip setting it.
@end itemize

Return the modified @code{TarInfo} member.
@end deffn

@node Filter errors,Hints for further verification,Default named filters,Extraction filters
@anchor{library/tarfile filter-errors}@anchor{1fbc}@anchor{library/tarfile tarfile-extraction-refuse}@anchor{1f85}
@subsubsection Filter errors


When a filter refuses to extract a file, it will raise an appropriate exception,
a subclass of @ref{1f84,,FilterError}.
This will abort the extraction if @ref{1f81,,TarFile.errorlevel} is 1 or more.
With @code{errorlevel=0} the error will be logged and the member will be skipped,
but extraction will continue.

@node Hints for further verification,Supporting older Python versions,Filter errors,Extraction filters
@anchor{library/tarfile hints-for-further-verification}@anchor{1fbd}
@subsubsection Hints for further verification


Even with @code{filter='data'}, @emph{tarfile} is not suited for extracting untrusted
files without prior inspection.
Among other issues, the pre-defined filters do not prevent denial-of-service
attacks. Users should do additional checks.

Here is an incomplete list of things to consider:


@itemize *

@item 
Extract to a @ref{1e0d,,new temporary directory}
to prevent e.g. exploiting pre-existing links, and to make it easier to
clean up after a failed extraction.

@item 
When working with untrusted data, use external (e.g. OS-level) limits on
disk, memory and CPU usage.

@item 
Check filenames against an allow-list of characters
(to filter out control characters, confusables, foreign path separators,
etc.).

@item 
Check that filenames have expected extensions (discouraging files that
execute when you “click on them”, or extension-less files like Windows special device names).

@item 
Limit the number of extracted files, total size of extracted data,
filename length (including symlink length), and size of individual files.

@item 
Check for files that would be shadowed on case-insensitive filesystems.
@end itemize

Also note that:


@itemize *

@item 
Tar files may contain multiple versions of the same file.
Later ones are expected to overwrite any earlier ones.
This feature is crucial to allow updating tape archives, but can be abused
maliciously.

@item 
@emph{tarfile} does not protect against issues with “live” data,
e.g. an attacker tinkering with the destination (or source) directory while
extraction (or archiving) is in progress.
@end itemize

@node Supporting older Python versions,Stateful extraction filter example,Hints for further verification,Extraction filters
@anchor{library/tarfile supporting-older-python-versions}@anchor{1fbe}
@subsubsection Supporting older Python versions


Extraction filters were added to Python 3.12, and are backported to older
versions as security updates.
To check whether the feature is available, use e.g.
@code{hasattr(tarfile, 'data_filter')} rather than checking the Python version.

The following examples show how to support Python versions with and without
the feature.
Note that setting @code{extraction_filter} will affect any subsequent operations.


@itemize *

@item 
Fully trusted archive:

@example
my_tarfile.extraction_filter = (lambda member, path: member)
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter if available, but revert to Python 3.11 behavior
(@code{'fully_trusted'}) if this feature is not available:

@example
my_tarfile.extraction_filter = getattr(tarfile, 'data_filter',
                                       (lambda member, path: member))
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter; @emph{fail} if it is not available:

@example
my_tarfile.extractall(filter=tarfile.data_filter)
@end example

or:

@example
my_tarfile.extraction_filter = tarfile.data_filter
my_tarfile.extractall()
@end example

@item 
Use the @code{'data'} filter; @emph{warn} if it is not available:

@example
if hasattr(tarfile, 'data_filter'):
    my_tarfile.extractall(filter='data')
else:
    # remove this when no longer needed
    warn_the_user('Extracting may be unsafe; consider updating Python')
    my_tarfile.extractall()
@end example
@end itemize

@node Stateful extraction filter example,,Supporting older Python versions,Extraction filters
@anchor{library/tarfile stateful-extraction-filter-example}@anchor{1fbf}
@subsubsection Stateful extraction filter example


While @emph{tarfile}'s extraction methods take a simple @emph{filter} callable,
custom filters may be more complex objects with an internal state.
It may be useful to write these as context managers, to be used like this:

@example
with StatefulFilter() as filter_func:
    tar.extractall(path, filter=filter_func)
@end example

Such a filter can be written as, for example:

@example
class StatefulFilter:
    def __init__(self):
        self.file_count = 0

    def __enter__(self):
        return self

    def __call__(self, member, path):
        self.file_count += 1
        return member

    def __exit__(self, *exc_info):
        print(f'@{self.file_count@} files extracted')
@end example

@node 命令行界面<3>,示例<12>,Extraction filters,tarfile --- 读写tar归档文件
@anchor{library/tarfile command-line-interface}@anchor{1fc0}@anchor{library/tarfile tarfile-commandline}@anchor{9d7}
@subsubsection 命令行界面



3.4 新版功能.


@ref{101,,tarfile} 模块提供了简单的命令行接口以便与 tar 归档进行交互。

如果你想要创建一个新的 tar 归档，请在 @ref{1fc1,,-c} 选项后指定其名称然后列出应当被包含的文件名:

@example
$ python -m tarfile -c monty.tar  spam.txt eggs.txt
@end example

传入一个字典也是可接受的:

@example
$ python -m tarfile -c monty.tar life-of-brian_1979/
@end example

如果你想要将一个 tar 归档提取到指定的目录，请使用 @ref{1fc2,,-e} 选项:

@example
$ python -m tarfile -e monty.tar
@end example

你也可以通过传入目录名称将一个 tar 归档提取到不同的目录:

@example
$ python -m tarfile -e monty.tar  other-dir/
@end example

要获取一个 tar 归档中文件的列表，请使用 @ref{1fc3,,-l} 选项:

@example
$ python -m tarfile -l monty.tar
@end example

@menu
* 命令行选项: 命令行选项<3>. 

@end menu

@node 命令行选项<3>,,,命令行界面<3>
@anchor{library/tarfile command-line-options}@anchor{1fc4}
@subsubsection 命令行选项


@geindex tarfile command line option; -l <tarfile>
@geindex tarfile command line option; --list <tarfile>
@anchor{library/tarfile cmdoption-tarfile-l}@anchor{1fc3}
@deffn {程序选项} @w{-}l <tarfile>
@anchor{library/tarfile cmdoption-tarfile-list}@anchor{1fc5}
@deffnx {程序选项} @w{-}@w{-}list <tarfile>

列出一个 tarfile 中的文件名。
@end deffn

@geindex tarfile command line option; -c <tarfile> <source1> ... <sourceN>
@geindex tarfile command line option; --create <tarfile> <source1> ... <sourceN>
@anchor{library/tarfile cmdoption-tarfile-c}@anchor{1fc1}
@deffn {程序选项} @w{-}c <tarfile> <source1> ... <sourceN>
@anchor{library/tarfile cmdoption-tarfile-create}@anchor{1fc6}
@deffnx {程序选项} @w{-}@w{-}create <tarfile> <source1> ... <sourceN>

基于源文件创建 tarfile。
@end deffn

@geindex tarfile command line option; -e <tarfile> [<output_dir>]
@geindex tarfile command line option; --extract <tarfile> [<output_dir>]
@anchor{library/tarfile cmdoption-tarfile-e}@anchor{1fc2}
@deffn {程序选项} @w{-}e <tarfile> [<output_dir>]
@anchor{library/tarfile cmdoption-tarfile-extract}@anchor{1fc7}
@deffnx {程序选项} @w{-}@w{-}extract <tarfile> [<output_dir>]

如果未指定 @emph{output_dir} 则会将 tarfile 提取到当前目录。
@end deffn

@geindex tarfile command line option; -t <tarfile>
@geindex tarfile command line option; --test <tarfile>
@anchor{library/tarfile cmdoption-tarfile-t}@anchor{1fc8}
@deffn {程序选项} @w{-}t <tarfile>
@anchor{library/tarfile cmdoption-tarfile-test}@anchor{1fc9}
@deffnx {程序选项} @w{-}@w{-}test <tarfile>

检测 tarfile 是否有效。
@end deffn

@geindex tarfile command line option; -v
@geindex tarfile command line option; --verbose
@anchor{library/tarfile cmdoption-tarfile-v}@anchor{1fca}
@deffn {程序选项} @w{-}v, @w{-}@w{-}verbose

更详细地输出结果。
@end deffn

@geindex tarfile command line option; --filter <filtername>
@anchor{library/tarfile cmdoption-tarfile-filter}@anchor{1fcb}
@deffn {程序选项} @w{-}@w{-}filter <filtername>

Specifies the @emph{filter} for @code{--extract}.
See @ref{28c,,Extraction filters} for details.
Only string names are accepted (that is, @code{fully_trusted}, @code{tar},
and @code{data}).


3.9.17 新版功能.

@end deffn

@node 示例<12>,受支持的 tar 格式,命令行界面<3>,tarfile --- 读写tar归档文件
@anchor{library/tarfile examples}@anchor{1fcc}@anchor{library/tarfile tar-examples}@anchor{1f7d}
@subsubsection 示例


如何将整个 tar 归档提取到当前工作目录:

@example
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
@end example

如何通过 @ref{860,,TarFile.extractall()} 使用生成器函数而非列表来提取一个 tar 归档的子集:

@example
import os
import tarfile

def py_files(members):
    for tarinfo in members:
        if os.path.splitext(tarinfo.name)[1] == ".py":
            yield tarinfo

tar = tarfile.open("sample.tar.gz")
tar.extractall(members=py_files(tar))
tar.close()
@end example

如何基于一个文件名列表创建未压缩的 tar 归档:

@example
import tarfile
tar = tarfile.open("sample.tar", "w")
for name in ["foo", "bar", "quux"]:
    tar.add(name)
tar.close()
@end example

使用 @ref{7e4,,with} 语句的同一个示例:

@example
import tarfile
with tarfile.open("sample.tar", "w") as tar:
    for name in ["foo", "bar", "quux"]:
        tar.add(name)
@end example

如何读取一个 gzip 压缩的 tar 归档并显示一些成员信息:

@example
import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
    print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
    if tarinfo.isreg():
        print("a regular file.")
    elif tarinfo.isdir():
        print("a directory.")
    else:
        print("something else.")
tar.close()
@end example

如何创建一个归档并使用 @ref{583,,TarFile.add()} 中的 @emph{filter} 形参来重置用户信息:

@example
import tarfile
def reset(tarinfo):
    tarinfo.uid = tarinfo.gid = 0
    tarinfo.uname = tarinfo.gname = "root"
    return tarinfo
tar = tarfile.open("sample.tar.gz", "w:gz")
tar.add("foo", filter=reset)
tar.close()
@end example

@node 受支持的 tar 格式,Unicode 问题,示例<12>,tarfile --- 读写tar归档文件
@anchor{library/tarfile supported-tar-formats}@anchor{1fcd}@anchor{library/tarfile tar-formats}@anchor{1f8e}
@subsubsection 受支持的 tar 格式


通过 @ref{101,,tarfile} 模块可以创建三种 tar 格式:


@itemize *

@item 
The POSIX.1-1988 ustar 格式 (@ref{1f8f,,USTAR_FORMAT})。 它支持最多 256 个字符的文件名长度和最多 100 个字符的链接名长度。 文件大小上限为 8 GiB。 这是一种老旧但广受支持的格式。

@item 
GNU tar 格式 (@ref{1f90,,GNU_FORMAT})。 它支持长文件名和链接名、大于 8 GiB 的文件以及稀疏文件。 它是 GNU/Linux 系统上的事实标准。 @ref{101,,tarfile} 完全支持针对长名称的 GNU tar 扩展，稀疏文件支持则限制为只读。

@item 
POSIX.1-2001 pax 格式 (@ref{1f91,,PAX_FORMAT})。 它是几乎无限制的最灵活格式。 它支持长文件名和链接名，大文件以及使用便捷方式存储路径名。 现代的 tar 实现，包括 GNU tar, bsdtar/libarchive 和 star，完全支持扩展 @emph{pax} 特性；某些老旧或不维护的库可能不受支持，但应当会将 @emph{pax} 归档视为广受支持的 @emph{ustar} 格式。 这是目前新建归档的默认格式。

它扩展了现有的 @emph{ustar} 格式，包括用于无法以其他方式存储的附加标头。 存在两种形式的 pax 标头：扩展标头只影响后续的文件标头，全局标头则适用于完整归档并会影响所有后续的文件。 为了便于移植，在 pax 标头中的所有数据均以 @emph{UTF-8} 编码。
@end itemize

还有一些 tar 格式的其他变种，它们可以被读取但不能被创建:


@itemize *

@item 
古老的 V7 格式。 这是来自 Unix 第七版的第一个 tar 格式，它只存储常规文件和目录。 名称长度不能超过 100 个字符，并且没有用户/分组名信息。 某些归档在带有非 ASCII 字符字段的情况下会产生计算错误的标头校验和。

@item 
SunOS tar 扩展格式。 此格式是 POSIX.1-2001 pax 格式的一个变种，但并不保持兼容。
@end itemize

@node Unicode 问题,,受支持的 tar 格式,tarfile --- 读写tar归档文件
@anchor{library/tarfile tar-unicode}@anchor{1f94}@anchor{library/tarfile unicode-issues}@anchor{1fce}
@subsubsection Unicode 问题


最初 tar 格式被设计用来在磁带机上生成备份，主要关注于保存文件系统信息。 现在 tar 归档通常用于文件分发和在网络上交换归档。 最初格式（它是所有其他格式的基础）的一个问题是它没有支持不同字符编码格式的概念。 例如，一个在 @emph{UTF-8} 系统上创建的普通 tar 归档如果包含非 @emph{ASCII} 字符则将无法在 @emph{Latin-1} 系统上被正确读取。 文本元数据（例如文件名，链接名，用户/分组名）将变为损坏状态。 不幸的是，没有什么办法能够自动检测一个归档的编码格式。 pax 格式被设计用来解决这个问题。 它使用通用字符编码格式 @emph{UTF-8} 来存储非 ASCII 元数据。

在 @ref{101,,tarfile} 中字符转换的细节由 @ref{c66,,TarFile} 类的 @emph{encoding} 和 @emph{errors} 关键字参数控制。

@emph{encoding} 定义了用于归档中元数据的字符编码格式。 默认值为 @ref{5f8,,sys.getfilesystemencoding()} 或是回退选项 @code{'ascii'}。 根据归档是被读取还是被写入，元数据必须被解码或编码。 如果没有正确设置 @emph{encoding}，转换可能会失败。

@emph{errors} 参数定义了不能被转换的字符将如何处理。 可能的取值在 @ref{f7d,,错误处理方案} 小节列出。 默认方案为 @code{'surrogateescape'}，它也被 Python 用于文件系统调用，参见 @ref{1fcf,,文件名，命令行参数，以及环境变量。}。

对于 @ref{1f91,,PAX_FORMAT} 归档（默认格式），@emph{encoding} 通常是不必要的，因为所有元数据都使用 @emph{UTF-8} 来存储。 @emph{encoding} 仅在解码二进制 pax 标头或存储带有替代字符的字符串等少数场景下会被使用。

@node 文件格式,加密服务,数据压缩和存档,Python 标准库
@anchor{library/fileformats doc}@anchor{1fd0}@anchor{library/fileformats file-formats}@anchor{1fd1}@anchor{library/fileformats fileformats}@anchor{1fd2}
@section 文件格式


本章中描述的模块解析各种不是标记语言且与电子邮件无关的杂项文件格式。

@menu
* csv: csv --- CSV 文件读写. CSV 文件读写
* configparser: configparser --- 配置文件解析器. 配置文件解析器
* netrc: netrc --- netrc 文件处理. netrc 文件处理
* plistlib: plistlib --- 生成与解析 Apple plist 文件. 生成与解析 Apple .plist 文件

@end menu

@node csv --- CSV 文件读写,configparser --- 配置文件解析器,,文件格式
@anchor{library/csv doc}@anchor{1fd3}@anchor{library/csv csv-csv-file-reading-and-writing}@anchor{1fd4}@anchor{library/csv module-csv}@anchor{29}
@subsection @code{csv} --- CSV 文件读写


@geindex csv (模块)

@strong{源代码：} Lib/csv.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/csv.py}

@geindex csv
@geindex data; tabular


__________________________________________________________________


CSV (Comma Separated Values) 格式是电子表格和数据库中最常见的输入、输出文件格式。在 
@geindex RFC; RFC 4180
RFC 4180@footnote{https://tools.ietf.org/html/rfc4180.html} 规范推出的很多年前，CSV 格式就已经被开始使用了，由于当时并没有合理的标准，不同应用程序读写的数据会存在细微的差别。这种差别让处理多个来源的 CSV 文件变得困难。但尽管分隔符会变化，此类文件的大致格式是相似的，所以编写一个单独的模块以高效处理此类数据，将程序员从读写数据的繁琐细节中解放出来是有可能的。

@ref{29,,csv} 模块实现了 CSV 格式表单数据的读写。其提供了诸如“以兼容 Excel 的方式输出数据文件”或“读取 Excel 程序输出的数据文件”的功能，程序员无需知道 Excel 所采用 CSV 格式的细节。此模块同样可以用于定义其他应用程序可用的 CSV 格式或定义特定需求的 CSV 格式。

@ref{29,,csv} 模块中的 @ref{1064,,reader} 类和 @ref{ec8,,writer} 类可用于读写序列化的数据。也可使用 @ref{2f5,,DictReader} 类和 @ref{c54,,DictWriter} 类以字典的形式读写数据。


@subsubheading 参见



@table @asis

@item 该实现在“Python 增强提议” - PEP @cite{305} (CSV 文件 API)  中被提出

《Python 增强提议》提出了对 Python 的这一补充。
@end table


@menu
* 模块内容: 模块内容<3>. 
* 变种与格式参数:: 
* Reader 对象:: 
* Writer 对象:: 
* 示例: 示例<13>. 

@end menu

@node 模块内容<3>,变种与格式参数,,csv --- CSV 文件读写
@anchor{library/csv csv-contents}@anchor{1fd5}@anchor{library/csv module-contents}@anchor{1fd6}
@subsubsection 模块内容


@ref{29,,csv} 模块定义了以下函数：

@geindex universal newlines; csv.reader function

@geindex reader() (在 csv 模块中)
@anchor{library/csv csv reader}@anchor{1064}
@deffn {函数} csv.reader (csvfile, dialect='excel', **fmtparams)

返回一个 reader 对象，该对象将逐行遍历 @emph{csvfile}。@emph{csvfile} 可以是任何对象，只要这个对象支持 @ref{11ba,,iterator} 协议并在每次调用 @code{__next__()} 方法时都返回字符串，@ref{c1d,,文件对象} 和列表对象均适用。如果 @emph{csvfile} 是文件对象，则打开它时应使用 @code{newline='@w{'}}。 @footnote{@w{(1)} 
如果没有指定 @code{newline='@w{'}}，则嵌入引号中的换行符将无法正确解析，并且在写入时，使用 @code{\r\n} 换行的平台会有多余的 @code{\r} 写入。由于 csv 模块会执行自己的（@ref{6f5,,通用}）换行符处理，因此指定 @code{newline='@w{'}} 应该总是安全的。
} 可选参数 @emph{dialect} 是用于不同的 CSV 变种的特定参数组。它可以是 @ref{fb8,,Dialect} 类的子类的实例，也可以是 @ref{1fd7,,list_dialects()} 函数返回的字符串之一。另一个可选关键字参数 @emph{fmtparams} 可以覆写当前变种格式中的单个格式设置。有关变种和格式设置参数的完整详细信息，请参见 @ref{1fd8,,变种与格式参数} 部分。

csv 文件的每一行都读取为一个由字符串组成的列表。除非指定了 @code{QUOTE_NONNUMERIC} 格式选项（在这种情况下，未加引号的字段会转换为浮点数），否则不会执行自动数据类型转换。

一个简短的用法示例:

@example
>>> import csv
>>> with open('eggs.csv', newline='@w{'}) as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
@end example
@end deffn

@geindex writer() (在 csv 模块中)
@anchor{library/csv csv writer}@anchor{ec8}
@deffn {函数} csv.writer (csvfile, dialect='excel', **fmtparams)

返回一个 writer 对象，该对象负责将用户的数据在给定的文件类对象上转换为带分隔符的字符串。 @emph{csvfile} 可以是任何具有 @code{write()} 方法的对象。 如果 @emph{csvfile} 是一个文件对象，则打开它时应使用 @code{newline='@w{'}} @footnote{@w{(1)} 
如果没有指定 @code{newline='@w{'}}，则嵌入引号中的换行符将无法正确解析，并且在写入时，使用 @code{\r\n} 换行的平台会有多余的 @code{\r} 写入。由于 csv 模块会执行自己的（@ref{6f5,,通用}）换行符处理，因此指定 @code{newline='@w{'}} 应该总是安全的。
}。 可以给出可选的 @emph{dialect} 形参用来定义一组特定 CSV 变种专属的形参。 它可以是 @ref{fb8,,Dialect} 类的某个子类的实例或是 @ref{1fd7,,list_dialects()} 函数所返回的字符串之一。 还可以给出另一个可选的 @emph{fmtparams} 关键字参数来覆盖当前变种中的单个格式化形参。 有关各个变种和格式化形参的完整细节，请参阅 @ref{1fd8,,变种与格式参数} 部分。 为了尽量简化与实现 DB API 的模块之间的接口，@ref{204,,None} 值会被当作空字符串写入。 虽然这个转换是不可逆的，但它可以简化 SQL NULL 数据值到 CSV 文件的转储而无需预处理从 @code{cursor.fetch*} 调用返回的数据。 在被写入之前所有其他非字符串数据都会先用 @ref{206,,str()} 来转转为字符串。

一个简短的用法示例:

@example
import csv
with open('eggs.csv', 'w', newline='@w{'}) as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
@end example
@end deffn

@geindex register_dialect() (在 csv 模块中)
@anchor{library/csv csv register_dialect}@anchor{1fd9}
@deffn {函数} csv.register_dialect (name[, dialect[, **fmtparams]])

将 @emph{dialect} 与 @emph{name} 关联起来。  @emph{name} 必须是字符串。 变种的指定可以通过传入一个 @ref{fb8,,Dialect} 的子类，或通过 @emph{fmtparams} 关键字参数，或是两者同时传入，此时关键字参数会覆盖 dialect 形参。 有关变种和格式化形参的完整细节，请参阅 @ref{1fd8,,变种与格式参数} 部分。
@end deffn

@geindex unregister_dialect() (在 csv 模块中)
@anchor{library/csv csv unregister_dialect}@anchor{1fda}
@deffn {函数} csv.unregister_dialect (name)

从变种注册表中删除 @emph{name} 对应的变种。如果 @emph{name} 不是已注册的变种名称，则抛出 @ref{1fdb,,Error} 异常。
@end deffn

@geindex get_dialect() (在 csv 模块中)
@anchor{library/csv csv get_dialect}@anchor{1fdc}
@deffn {函数} csv.get_dialect (name)

返回 @emph{name} 对应的变种。如果 @emph{name} 不是已注册的变种名称，则抛出 @ref{1fdb,,Error} 异常。该函数返回的是不可变的 @ref{fb8,,Dialect} 对象。
@end deffn

@geindex list_dialects() (在 csv 模块中)
@anchor{library/csv csv list_dialects}@anchor{1fd7}
@deffn {函数} csv.list_dialects ()

返回所有已注册变种的名称。
@end deffn

@geindex field_size_limit() (在 csv 模块中)
@anchor{library/csv csv field_size_limit}@anchor{1fdd}
@deffn {函数} csv.field_size_limit ([new_limit])

返回解析器当前允许的最大字段大小。如果指定了 @emph{new_limit}，则它将成为新的最大字段大小。
@end deffn

@ref{29,,csv} 模块定义了以下类：

@geindex DictReader (csv 中的类)
@anchor{library/csv csv DictReader}@anchor{2f5}
@deffn {类} csv.DictReader (f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

创建一个对象，该对象在操作上类似于常规 reader，但是将每行中的信息映射到一个 @ref{164,,dict}，该 dict 的键由 @emph{fieldnames} 可选参数给出。

@emph{fieldnames} 参数是一个 @ref{138b,,sequence}。如果省略 @emph{fieldnames}，则文件 @emph{f} 第一行中的值将用作字段名。无论字段名是如何确定的，字典都将保留其原始顺序。

如果某一行中的字段多于字段名，则剩余数据会被放入一个列表，并与 @emph{restkey} 所指定的字段名 (默认为 @code{None}) 一起保存。 如果某个非空白行的字段少于字段名，则缺失的值会使用 @emph{restval} 的值来填充 (默认为 @code{None})。

所有其他可选或关键字参数都传递给底层的 @ref{1064,,reader} 实例。


在 3.6 版更改: 返回的行现在的类型是 @code{OrderedDict}。



在 3.8 版更改: 现在，返回的行是 @ref{164,,dict} 类型。


一个简短的用法示例:

@example
>>> import csv
>>> with open('names.csv', newline='@w{'}) as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

>>> print(row)
@{'first_name': 'John', 'last_name': 'Cleese'@}
@end example
@end deffn

@geindex DictWriter (csv 中的类)
@anchor{library/csv csv DictWriter}@anchor{c54}
@deffn {类} csv.DictWriter (f, fieldnames, restval='@w{'}, extrasaction='raise', dialect='excel', *args, **kwds)

创建一个对象，该对象在操作上类似常规 writer，但会将字典映射到输出行。 @emph{fieldnames} 参数是由键组成的 @ref{1e,,序列}，它指定字典中值的顺序，这些值会按指定顺序传递给 @code{writerow()} 方法并写入文件 @emph{f}。 如果字典缺少 @emph{fieldnames} 中的键，则可选参数 @emph{restval} 用于指定要写入的值。 如果传递给 @code{writerow()} 方法的字典的某些键在 @emph{fieldnames} 中找不到，则可选参数 @emph{extrasaction} 用于指定要执行的操作。 如果将其设置为默认值 @code{'raise'}，则会引发 @ref{16d,,ValueError}。 如果将其设置为 @code{'ignore'}，则字典中的其他键值将被忽略。 所有其他可选或关键字参数都传递给底层的 @ref{ec8,,writer} 实例。

注意，与 @ref{2f5,,DictReader} 类不同，@ref{c54,,DictWriter} 类的 @emph{fieldnames} 参数不是可选参数。

一个简短的用法示例:

@example
import csv

with open('names.csv', 'w', newline='@w{'}) as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow(@{'first_name': 'Baked', 'last_name': 'Beans'@})
    writer.writerow(@{'first_name': 'Lovely', 'last_name': 'Spam'@})
    writer.writerow(@{'first_name': 'Wonderful', 'last_name': 'Spam'@})
@end example
@end deffn

@geindex Dialect (csv 中的类)
@anchor{library/csv csv Dialect}@anchor{fb8}
@deffn {类} csv.Dialect

@ref{fb8,,Dialect} 类是一个容器类，其属性包含有如何处理双引号、空白符、分隔符等的信息。 由于缺少严格的 CSV 规格描述，不同的应用程序会产生略有差别的 CSV 数据。  @ref{fb8,,Dialect} 实例定义了 @ref{1064,,reader} 和 @ref{ec8,,writer} 实例将具有怎样的行为。

所有可用的 @ref{fb8,,Dialect} 名称会由 @ref{1fd7,,list_dialects()} 返回，并且它们可由特定的 @ref{1064,,reader} 和 @ref{ec8,,writer} 类通过它们的初始化函数 (@code{__init__}) 来注册，例如:

@example
import csv

with open('students.csv', 'w', newline='@w{'}) as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
@end example
@end deffn

@geindex excel (csv 中的类)
@anchor{library/csv csv excel}@anchor{1fde}
@deffn {类} csv.excel

@ref{1fde,,excel} 类定义了 Excel 生成的 CSV 文件的常规属性。它在变种注册表中的名称是 @code{'excel'}。
@end deffn

@geindex excel_tab (csv 中的类)
@anchor{library/csv csv excel_tab}@anchor{1fdf}
@deffn {类} csv.excel_tab

@ref{1fdf,,excel_tab} 类定义了 Excel 生成的、制表符分隔的 CSV 文件的常规属性。它在变种注册表中的名称是 @code{'excel-tab'}。
@end deffn

@geindex unix_dialect (csv 中的类)
@anchor{library/csv csv unix_dialect}@anchor{c53}
@deffn {类} csv.unix_dialect

@ref{c53,,unix_dialect} 类定义了在 UNIX 系统上生成的 CSV 文件的常规属性，即使用 @code{'\n'} 作为换行符，且所有字段都有引号包围。它在变种注册表中的名称是 @code{'unix'}。


3.2 新版功能.

@end deffn

@geindex Sniffer (csv 中的类)
@anchor{library/csv csv Sniffer}@anchor{1fe0}
@deffn {类} csv.Sniffer

@ref{1fe0,,Sniffer} 类用于推断 CSV 文件的格式。

@ref{1fe0,,Sniffer} 类提供了两个方法：

@geindex sniff() (csv.Sniffer 方法)
@anchor{library/csv csv Sniffer sniff}@anchor{1fe1}
@deffn {方法} sniff (sample, delimiters=None)

分析给定的 @emph{sample} 并返回一个 @ref{fb8,,Dialect} 子类，该子类中包含了分析出的格式参数。如果给出可选的 @emph{delimiters} 参数，则该参数会被解释为字符串，该字符串包含了可能的有效定界符。
@end deffn

@geindex has_header() (csv.Sniffer 方法)
@anchor{library/csv csv Sniffer has_header}@anchor{1fe2}
@deffn {方法} has_header (sample)

分析示例文本（假定为 CSV 格式），如果第一行很可能是一系列列标题，则返回 @ref{59c,,True}。
@end deffn
@end deffn

使用 @ref{1fe0,,Sniffer} 的示例：

@example
with open('example.csv', newline='@w{'}) as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...
@end example

@ref{29,,csv} 模块定义了以下常量：

@geindex QUOTE_ALL() (在 csv 模块中)
@anchor{library/csv csv QUOTE_ALL}@anchor{1fe3}
@deffn {数据} csv.QUOTE_ALL

指示 @ref{ec8,,writer} 对象给所有字段加上引号。
@end deffn

@geindex QUOTE_MINIMAL() (在 csv 模块中)
@anchor{library/csv csv QUOTE_MINIMAL}@anchor{1fe4}
@deffn {数据} csv.QUOTE_MINIMAL

指示 @ref{ec8,,writer} 对象仅为包含特殊字符（例如 @emph{定界符}、@emph{引号字符} 或 @emph{行结束符} 中的任何字符）的字段加上引号。
@end deffn

@geindex QUOTE_NONNUMERIC() (在 csv 模块中)
@anchor{library/csv csv QUOTE_NONNUMERIC}@anchor{1fe5}
@deffn {数据} csv.QUOTE_NONNUMERIC

指示 @ref{ec8,,writer} 对象为所有非数字字段加上引号。

指示 reader 将所有未用引号引出的字段转换为 @emph{float} 类型。
@end deffn

@geindex QUOTE_NONE() (在 csv 模块中)
@anchor{library/csv csv QUOTE_NONE}@anchor{1fe6}
@deffn {数据} csv.QUOTE_NONE

指示 @ref{ec8,,writer} 对象不使用引号引出字段。当 @emph{定界符} 出现在输出数据中时，其前面应该有 @emph{转义符}。如果未设置 @emph{转义符}，则遇到任何需要转义的字符时，writer 都会抛出 @ref{1fdb,,Error} 异常。

指示 @ref{1064,,reader} 不对引号字符进行特殊处理。
@end deffn

@ref{29,,csv} 模块定义了以下异常：

@geindex Error
@anchor{library/csv csv Error}@anchor{1fdb}
@deffn {例外} csv.Error

该异常可能由任何发生错误的函数抛出。
@end deffn

@node 变种与格式参数,Reader 对象,模块内容<3>,csv --- CSV 文件读写
@anchor{library/csv csv-fmt-params}@anchor{1fd8}@anchor{library/csv dialects-and-formatting-parameters}@anchor{1fe7}
@subsubsection 变种与格式参数


为了更容易指定输入和输出记录的格式，特定的一组格式参数组合为一个 dialect（变种）。一个 dialect 是一个 @ref{fb8,,Dialect} 类的子类，它具有一组特定的方法和一个 @code{validate()} 方法。创建 @ref{1064,,reader} 或 @ref{ec8,,writer} 对象时，程序员可以将某个字符串或 @ref{fb8,,Dialect} 类的子类指定为 dialect 参数。要想补充或覆盖 @emph{dialect} 参数，程序员还可以单独指定某些格式参数，这些参数的名称与下面 @ref{fb8,,Dialect} 类定义的属性相同。

Dialect 类支持以下属性：

@geindex delimiter (csv.Dialect 属性)
@anchor{library/csv csv Dialect delimiter}@anchor{1fe8}
@deffn {属性} Dialect.delimiter

一个用于分隔字段的单字符，默认为 @code{','}。
@end deffn

@geindex doublequote (csv.Dialect 属性)
@anchor{library/csv csv Dialect doublequote}@anchor{1fe9}
@deffn {属性} Dialect.doublequote

控制出现在字段中的 @emph{引号字符} 本身应如何被引出。当该属性为 @ref{59c,,True} 时，双写引号字符。如果该属性为 @ref{497,,False}，则在 @emph{引号字符} 的前面放置 @emph{转义符}。默认值为 @ref{59c,,True}。

在输出时，如果 @emph{doublequote} 是 @ref{497,,False}，且 @emph{转义符} 未指定，且在字段中发现 @emph{引号字符} 时，会抛出 @ref{1fdb,,Error} 异常。
@end deffn

@geindex escapechar (csv.Dialect 属性)
@anchor{library/csv csv Dialect escapechar}@anchor{1fea}
@deffn {属性} Dialect.escapechar

一个用于 writer 的单字符，用来在 @emph{quoting} 设置为 @ref{1fe6,,QUOTE_NONE} 的情况下转义 @emph{定界符}，在 @emph{doublequote} 设置为 @ref{497,,False} 的情况下转义 @emph{引号字符}。在读取时，@emph{escapechar} 去除了其后所跟字符的任何特殊含义。该属性默认为 @ref{204,,None}，表示禁用转义。
@end deffn

@geindex lineterminator (csv.Dialect 属性)
@anchor{library/csv csv Dialect lineterminator}@anchor{1feb}
@deffn {属性} Dialect.lineterminator

放在 @ref{ec8,,writer} 产生的行的结尾，默认为 @code{'\r\n'}。

@cartouche
@quotation 注解 
@ref{1064,,reader} 经过硬编码，会识别 @code{'\r'} 或 @code{'\n'} 作为行尾，并忽略 @emph{lineterminator}。未来可能会更改这一行为。
@end quotation
@end cartouche
@end deffn

@geindex quotechar (csv.Dialect 属性)
@anchor{library/csv csv Dialect quotechar}@anchor{1fec}
@deffn {属性} Dialect.quotechar

一个单字符，用于包住含有特殊字符的字段，特殊字符如 @emph{定界符} 或 @emph{引号字符} 或换行符。默认为 @code{'"'}。
@end deffn

@geindex quoting (csv.Dialect 属性)
@anchor{library/csv csv Dialect quoting}@anchor{1fed}
@deffn {属性} Dialect.quoting

控制 writer 何时生成引号，以及 reader 何时识别引号。该属性可以等于任何 @code{QUOTE_*} 常量（参见 @ref{1fd5,,模块内容} 段落），默认为 @ref{1fe4,,QUOTE_MINIMAL}。
@end deffn

@geindex skipinitialspace (csv.Dialect 属性)
@anchor{library/csv csv Dialect skipinitialspace}@anchor{1fee}
@deffn {属性} Dialect.skipinitialspace

如果为 @ref{59c,,True}，则忽略 @emph{定界符} 之后的空格。默认值为 @ref{497,,False}。
@end deffn

@geindex strict (csv.Dialect 属性)
@anchor{library/csv csv Dialect strict}@anchor{1fef}
@deffn {属性} Dialect.strict

如果为 @code{True}，则在输入错误的 CSV 时抛出 @ref{1fdb,,Error} 异常。默认值为 @code{False}。
@end deffn

@node Reader 对象,Writer 对象,变种与格式参数,csv --- CSV 文件读写
@anchor{library/csv reader-objects}@anchor{1ff0}
@subsubsection Reader 对象


Reader 对象（@ref{2f5,,DictReader} 实例和 @ref{1064,,reader()} 函数返回的对象）具有以下公开方法：

@geindex __next__() (csv.csvreader 方法)
@anchor{library/csv csv csvreader __next__}@anchor{1ff1}
@deffn {方法} csvreader.__next__ ()

返回 reader 的可迭代对象的下一行，它可以是一个列表（如果对象是由 @ref{1064,,reader()} 返回）或字典（如果是一个 @ref{2f5,,DictReader} 实例），根据当前 @ref{fb8,,Dialect} 来解析。 通常你应当以 @code{next(reader)} 的形式来调用它。
@end deffn

Reader 对象具有以下公开属性：

@geindex dialect (csv.csvreader 属性)
@anchor{library/csv csv csvreader dialect}@anchor{1ff2}
@deffn {属性} csvreader.dialect

变种描述，只读，供解析器使用。
@end deffn

@geindex line_num (csv.csvreader 属性)
@anchor{library/csv csv csvreader line_num}@anchor{1ff3}
@deffn {属性} csvreader.line_num

源迭代器已经读取了的行数。它与返回的记录数不同，因为记录可能跨越多行。
@end deffn

DictReader 对象具有以下公开属性：

@geindex fieldnames (csv.csvreader 属性)
@anchor{library/csv csv csvreader fieldnames}@anchor{1ff4}
@deffn {属性} csvreader.fieldnames

字段名称。如果在创建对象时未传入字段名称，则首次访问时或从文件中读取第一条记录时会初始化此属性。
@end deffn

@node Writer 对象,示例<13>,Reader 对象,csv --- CSV 文件读写
@anchor{library/csv writer-objects}@anchor{1ff5}
@subsubsection Writer 对象


@code{Writer} 对象（@ref{c54,,DictWriter} 实例和 @ref{ec8,,writer()} 函数返回的对象）具有下面的公开方法。对于 @code{Writer} 对象，@emph{行} 必须是（一组可迭代的）字符串或数字。对于 @ref{c54,,DictWriter} 对象，@emph{行} 必须是一个字典，这个字典将字段名映射为字符串或数字（数字要先经过 @ref{206,,str()} 转换类型）。请注意，输出的复数会有括号包围。这样其他程序读取 CSV 文件时可能会有一些问题（假设它们完全支持复数）。

@geindex writerow() (csv.csvwriter 方法)
@anchor{library/csv csv csvwriter writerow}@anchor{7c1}
@deffn {方法} csvwriter.writerow (row)

将 @emph{row} 形参写入到 writer 的文件对象，根据当前 @ref{fb8,,Dialect} 进行格式化。 返回对下层文件对象的 @emph{write} 方法的调用的返回值。


在 3.5 版更改: 开始支持任意类型的迭代器。

@end deffn

@geindex writerows() (csv.csvwriter 方法)
@anchor{library/csv csv csvwriter writerows}@anchor{1ff6}
@deffn {方法} csvwriter.writerows (rows)

将 @emph{rows*（即能迭代出多个上述 *row} 对象的迭代器）中的所有元素写入 writer 的文件对象，并根据当前设置的变种进行格式化。
@end deffn

Writer 对象具有以下公开属性：

@geindex dialect (csv.csvwriter 属性)
@anchor{library/csv csv csvwriter dialect}@anchor{1ff7}
@deffn {属性} csvwriter.dialect

变种描述，只读，供 writer 使用。
@end deffn

DictWriter 对象具有以下公开方法：

@geindex writeheader() (csv.DictWriter 方法)
@anchor{library/csv csv DictWriter writeheader}@anchor{c55}
@deffn {方法} DictWriter.writeheader ()

在 writer 的文件对象中，写入一行字段名称（字段名称在构造函数中指定），并根据当前设置的变种进行格式化。本方法的返回值就是内部使用的 @ref{7c1,,csvwriter.writerow()} 方法的返回值。


3.2 新版功能.



在 3.8 版更改: 现在 @ref{c55,,writeheader()} 也返回其内部使用的 @ref{7c1,,csvwriter.writerow()} 方法的返回值。

@end deffn

@node 示例<13>,,Writer 对象,csv --- CSV 文件读写
@anchor{library/csv csv-examples}@anchor{1ff8}@anchor{library/csv examples}@anchor{1ff9}
@subsubsection 示例


读取 CSV 文件最简单的一个例子:

@example
import csv
with open('some.csv', newline='@w{'}) as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
@end example

读取其他格式的文件:

@example
import csv
with open('passwd', newline='@w{'}) as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)
@end example

相应最简单的写入示例是:

@example
import csv
with open('some.csv', 'w', newline='@w{'}) as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)
@end example

由于使用 @ref{16f,,open()} 来读取 CSV 文件，因此默认情况下，将使用系统默认编码来解码文件并转换为 unicode（请参阅 @ref{4b4,,locale.getpreferredencoding()}）。要使用其他编码来解码文件，请使用 open 的 @code{encoding} 参数:

@example
import csv
with open('some.csv', newline='@w{'}, encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
@end example

这同样适用于写入非系统默认编码的内容：打开输出文件时，指定 encoding 参数。

注册一个新的变种:

@example
import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='@w{'}) as f:
    reader = csv.reader(f, 'unixpwd')
@end example

Reader 的更高级用法——捕获并报告错误:

@example
import csv, sys
filename = 'some.csv'
with open(filename, newline='@w{'}) as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print(row)
    except csv.Error as e:
        sys.exit('file @{@}, line @{@}: @{@}'.format(filename, reader.line_num, e))
@end example

尽管该模块不直接支持解析字符串，但仍可如下轻松完成:

@example
import csv
for row in csv.reader(['one,two,three']):
    print(row)
@end example

@node configparser --- 配置文件解析器,netrc --- netrc 文件处理,csv --- CSV 文件读写,文件格式
@anchor{library/configparser doc}@anchor{1ffa}@anchor{library/configparser configparser-configuration-file-parser}@anchor{1ffb}@anchor{library/configparser module-configparser}@anchor{22}
@subsection @code{configparser} --- 配置文件解析器


@geindex configparser (模块)

@strong{源代码:} Lib/configparser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/configparser.py}

@geindex .ini; file
@geindex configuration; file
@geindex ini file
@geindex Windows ini file


__________________________________________________________________


此模块提供了它实现一种基本配置语言 @ref{5ad,,ConfigParser} 类，这种语言所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编写能够由最终用户来自定义的 Python 程序。

@cartouche
@quotation 注解 
这个库 @emph{并不} 能够解析或写入在 Windows Registry 扩展版本 INI 语法中所使用的值-类型前缀。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item 模块 @ref{e8,,shlex}

支持创建可被用作应用配置文件的替代的 Unix 终端式微语言。

@item 模块 @ref{a4,,json}

json 模块实现了一个 JavaScript 语法的子集，它也可被用于这种目的。
@end table


@c import configparser

@c import os
@c os.remove("example.ini")

@menu
* 快速起步:: 
* 支持的数据类型:: 
* 回退值:: 
* 受支持的 INI 文件结构:: 
* 值的插值:: 
* 映射协议访问:: 
* 定制解析器行为:: 
* 旧式 API 示例:: 
* ConfigParser 对象:: 
* RawConfigParser 对象:: 
* 异常: 异常<6>. 

@end menu

@node 快速起步,支持的数据类型,,configparser --- 配置文件解析器
@anchor{library/configparser quick-start}@anchor{1ffc}
@subsubsection 快速起步


让我们准备一个非常基本的配置文件，它看起来是这样的:

@example
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no
@end example

INI 文件的结构描述见 @ref{1ffd,,以下章节}。 总的来说，这种文件由多个节组成，每个节包含多个带有值的键。 @ref{22,,configparser} 类可以读取和写入这种文件。 让我们先通过程序方式来创建上述的配置文件。

@example
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = @{'ServerAliveInterval': '45',
...                      'Compression': 'yes',
...                      'CompressionLevel': '9'@}
>>> config['bitbucket.org'] = @{@}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = @{@}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022'     # mutates the parser
>>> topsecret['ForwardX11'] = 'no'  # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
...   config.write(configfile)
...
@end example

如你所见，我们可以把配置解析器当作一个字典来处理。 两者确实存在差异，@ref{1ffe,,将在后文说明}，但是其行为非常接近于字典所具有一般行为。

现在我们已经创建并保存了一个配置文件，让我们再将它读取出来并探究其中包含的数据。

@example
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']:  
...     print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
@end example

正如我们在上面所看到的，相关的 API 相当直观。 唯一有些神奇的地方是 @code{DEFAULT} 小节，它为所有其他小节提供了默认值 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}。 还要注意小节中的键大小写不敏感并且会存储为小写形式 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}。

@node 支持的数据类型,回退值,快速起步,configparser --- 配置文件解析器
@anchor{library/configparser supported-datatypes}@anchor{2000}
@subsubsection 支持的数据类型


配置解析器并不会猜测配置文件中值的类型，而总是将它们在内部存储为字符串。 这意味着如果你需要其他数据类型，你应当自己来转换:

@example
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
@end example

由于这种任务十分常用，配置解析器提供了一系列便捷的获取方法来处理整数、浮点数和布尔值。 最后一个类型的处理最为有趣，因为简单地将值传给 @code{bool()} 是没有用的，@code{bool('False')} 仍然会是 @code{True}。 为解决这个问题配置解析器还提供了 @ref{2001,,getboolean()}。 这个方法对大小写不敏感并可识别 @code{'yes'}/@code{'no'}, @code{'on'}/@code{'off'}, @code{'true'}/@code{'false'} 和 @code{'1'}/@code{'0'} @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
} 等布尔值。 例如:

@example
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
@end example

除了 @ref{2001,,getboolean()}，配置解析器还提供了同类的 @ref{2002,,getint()} 和 @ref{2003,,getfloat()} 方法。 你可以注册你自己的转换器并或是定制已提供的转换器。 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}

@node 回退值,受支持的 INI 文件结构,支持的数据类型,configparser --- 配置文件解析器
@anchor{library/configparser fallback-values}@anchor{2004}
@subsubsection 回退值


与字典类似，你可以使用某个小节的 @code{get()} 方法来提供回退值:

@example
>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
@end example

请注意默认值会优先于回退值。 例如，在我们的示例中 @code{'CompressionLevel'} 键仅在 @code{'DEFAULT'} 小节被指定。 如果你尝试在 @code{'topsecret.server.com'} 小节获取它，我们将总是获取到默认值，即使我们指定了一个回退值:

@example
>>> topsecret.get('CompressionLevel', '3')
'9'
@end example

还需要注意的一点是解析器层级的 @code{get()} 方法提供了自定义的更复杂接口，它被维护用于向下兼容。 当使用此方法时，回退值可以通过 @code{fallback} 仅限关键字参数来提供:

@example
>>> config.get('bitbucket.org', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'
@end example

同样的 @code{fallback} 参数也可在 @ref{2002,,getint()}, @ref{2003,,getfloat()} 和 @ref{2001,,getboolean()} 方法中使用，例如:

@example
>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
@end example

@node 受支持的 INI 文件结构,值的插值,回退值,configparser --- 配置文件解析器
@anchor{library/configparser supported-ini-file-structure}@anchor{1ffd}
@subsubsection 受支持的 INI 文件结构


配置文件是由小节组成的，每个小节都有一个 @code{[section]} 标头，加上多个由特定字符串 (默认为 @code{=} 或 @code{:} @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}) 分隔的键/值条目。 在默认情况下，小节名对大小写敏感而键对大小写不敏感 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}。 键和值开头和末尾的空格会被移除。 在解释器配置允许时值可以被省略 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}，在此情况下键/值分隔符也可以被省略。 值还可以跨越多行，只要值的其他行带有比第一行更深的缩进。 依据解析器的具体模式，空白行可能会被视为多行值的组成部分或是被忽略。

在默认情况下，有效的节名称可以是不包含 '\n' 或 ']' 的任意字符串。 要改变此设定，请参阅 @ref{2005,,ConfigParser.SECTCRE}。

配置文件可以包含注释，要带有指定字符前缀 (默认为 @code{#} 和 @code{;} @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
})。 注释可以单独出现于原本的空白行，并可使用缩进。 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}

例如:

@example
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?
@end example

@node 值的插值,映射协议访问,受支持的 INI 文件结构,configparser --- 配置文件解析器
@anchor{library/configparser interpolation-of-values}@anchor{2006}
@subsubsection 值的插值


在核心功能之上，@ref{5ad,,ConfigParser} 还支持插值。 这意味着值可以在被 @code{get()} 调用返回之前进行预处理。

@geindex % (percent); interpolation in configuration files

@geindex BasicInterpolation (configparser 中的类)
@anchor{library/configparser configparser BasicInterpolation}@anchor{2007}
@deffn {类} configparser.BasicInterpolation

默认实现由 @ref{5ad,,ConfigParser} 来使用。 它允许值包含引用了相同小节中其他值或者特殊的默认小节中的值的格式字符串 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}。 额外的默认值可以在初始化时提供。

例如:

@example
[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

[Escape]
# use a %% to escape the % sign (% is the only character that needs to be escaped):
gain: 80%%
@end example

在上面的例子里，@ref{5ad,,ConfigParser} 的 @emph{interpolation} 设为 @code{BasicInterpolation()}，这会将 @code{%(home_dir)s} 求解为 @code{home_dir} 的值 (在这里是 @code{/Users})。 @code{%(my_dir)s} 的将被实际求解为 @code{/Users/lumberjack}。 所有插值都是按需进行的，这样引用链中使用的键不必以任何特定顺序在配置文件中指明。

当 @code{interpolation} 设为 @code{None} 时，解析器会简单地返回 @code{%(my_dir)s/Pictures} 作为 @code{my_pictures} 的值，并返回 @code{%(home_dir)s/lumberjack} 作为 @code{my_dir} 的值。
@end deffn

@geindex $ (dollar); interpolation in configuration files

@geindex ExtendedInterpolation (configparser 中的类)
@anchor{library/configparser configparser ExtendedInterpolation}@anchor{cb2}
@deffn {类} configparser.ExtendedInterpolation

一个用于插值的替代处理程序实现了更高级的语法，它被用于 @code{zc.buildout} 中的实例。 扩展插值使用 @code{$@{section:option@}} 来表示来自外部小节的值。 插值可以跨越多个层级。 为了方便使用，@code{section:} 部分可被省略，插值会默认作用于当前小节（可能会从特殊小节获取默认值）。

例如，上面使用基本插值描述的配置，使用扩展插值将是这个样子:

@example
[Paths]
home_dir: /Users
my_dir: $@{home_dir@}/lumberjack
my_pictures: $@{my_dir@}/Pictures

[Escape]
# use a $$ to escape the $ sign ($ is the only character that needs to be escaped):
cost: $$80
@end example

来自其他小节的值也可以被获取:

@example
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: $@{Common:system_dir@}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: $@{Common:home_dir@}/twosheds
my_pictures: $@{my_dir@}/Pictures
python_dir: $@{Frameworks:path@}/Python/Versions/$@{Frameworks:Python@}
@end example
@end deffn

@node 映射协议访问,定制解析器行为,值的插值,configparser --- 配置文件解析器
@anchor{library/configparser mapping-protocol-access}@anchor{1ffe}
@subsubsection 映射协议访问



3.2 新版功能.


映射协议访问这个通用名称是指允许以字典的方式来使用自定义对象的功能。 在 @ref{22,,configparser} 中，映射接口的实现使用了 @code{parser['section']['option']} 标记法。

@code{parser['section']} 专门为解析器中的小节数据返回一个代理。 这意味着其中的值不会被拷贝，而是在需要时从原始解析器中获取。 更为重要的是，当值在小节代理上被修改时，它们其实是在原始解析器中发生了改变。

@ref{22,,configparser} 对象的行为会尽可能地接近真正的字典。 映射接口是完整而且遵循 @ref{ad7,,MutableMapping} ABC 规范的。 但是，还是有一些差异应当被纳入考虑:


@itemize *

@item 
默认情况下，小节中的所有键是以大小写不敏感的方式来访问的 @footnote{@w{(1)} 
配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行为，请参阅 @ref{1fff,,Customizing Parser Behaviour} 一节。
}。 例如 @code{for option in parser["section"]} 只会产生 @code{optionxform} 形式的选项键名称。 也就是说默认使用小写字母键名。 与此同时，对于一个包含键 @code{'a'} 的小节，以下两个表达式均将返回 @code{True}:

@example
"a" in parser["section"]
"A" in parser["section"]
@end example

@item 
所有小节也包括 @code{DEFAULTSECT}，这意味着对一个小节执行 @code{.clear()} 可能无法使得该小节显示为空。 这是因为默认值是无法从小节中被删除的（因为从技术上说它们并不在那里）。 如果它们在小节中被覆盖，删除将导致默认值重新变为可见。 尝试删除默认值将会引发 @ref{3f1,,KeyError}。

@item 
@code{DEFAULTSECT} 无法从解析器中被移除:


@itemize *

@item 
尝试删除将引发 @ref{16d,,ValueError}，

@item 
@code{parser.clear()} 会保留其原状，

@item 
@code{parser.popitem()} 绝不会将其返回。
@end itemize

@item 
@code{parser.get(section, option, **kwargs)} - 第二个参数 @strong{并非} 回退值。 但是请注意小节层级的 @code{get()} 方法可同时兼容映射协议和经典配置解析器 API。

@item 
@code{parser.items()} 兼容映射协议（返回 @emph{section_name}, @emph{section_proxy} 对的列表，包括 DEFAULTSECT）。 但是，此方法也可以带参数发起调用: @code{parser.items(section, raw, vars)}。 这种调用形式返回指定 @code{section} 的 @emph{option}, @emph{value} 对的列表，将展开所有插值（除非提供了 @code{raw=True} 选项）。
@end itemize

映射协议是在现有的传统 API 之上实现的，以便重载原始接口的子类仍然具有符合预期的有效映射。

@node 定制解析器行为,旧式 API 示例,映射协议访问,configparser --- 配置文件解析器
@anchor{library/configparser customizing-parser-behaviour}@anchor{1fff}
@subsubsection 定制解析器行为


INI 格式的变种数量几乎和使用此格式的应用一样多。 @ref{22,,configparser} 花费了很大力气来为尽量大范围的可用 INI 样式提供支持。 默认的可用功能主要由历史状况来确定，你很可能会想要定制某些特性。

改变特定配置解析器行为的最常见方式是使用 @ref{e2b,,__init__()} 选项:


@itemize *

@item 
@emph{defaults}，默认值: @code{None}

此选项接受一个键值对的字典，它将被首先放入 @code{DEFAULT} 小节。 这实现了一种优雅的方式来支持简洁的配置文件，它不必指定与已记录的默认值相同的值。

提示：如果你想要为特定的小节指定默认的值，请在读取实际文件之前使用 @code{read_dict()}。

@item 
@emph{dict_type}，默认值: @ref{164,,dict}

此选项主要影响映射协议的行为和写入配置文件的外观。 使用标准字典时，每个小节是按照它们被加入解析器的顺序保存的。 在小节内的选项也是如此。

还有其他替换的字典类型可以使用，例如在写回数据时对小节和选项进行排序。

请注意：存在其他方式只用一次操作来添加键值对的集合。 当你在这些操作中使用一个常规字典时，键将按顺序进行排列。 例如:

@example
>>> parser = configparser.ConfigParser()
>>> parser.read_dict(@{'section1': @{'key1': 'value1',
...                                'key2': 'value2',
...                                'key3': 'value3'@},
...                   'section2': @{'keyA': 'valueA',
...                                'keyB': 'valueB',
...                                'keyC': 'valueC'@},
...                   'section3': @{'foo': 'x',
...                                'bar': 'y',
...                                'baz': 'z'@}
... @})
>>> parser.sections()
['section1', 'section2', 'section3']
>>> [option for option in parser['section3']]
['foo', 'bar', 'baz']
@end example

@item 
@emph{allow_no_value}，默认值: @code{False}

已知某些配置文件会包括不带值的设置，但其在其他方面均符合 @ref{22,,configparser} 所支持的语法。 构造器的 @emph{allow_no_value} 形参可用于指明应当接受这样的值:

@example
>>> import configparser

>>> sample_config = """
... [mysqld]
...   user = mysql
...   pid-file = /var/run/mysqld/mysqld.pid
...   skip-external-locking
...   old_passwords = 1
...   skip-bdb
...   # we don't need ACID today
...   skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)

>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'

>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]

>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
  ...
KeyError: 'does-not-exist'
@end example

@item 
@emph{delimiters}，默认值: @code{('=', ':')}

分隔符是用于在小节内分隔键和值的子字符串。 在一行中首次出现的分隔子字符串会被视为一个分隔符。 这意味着值可以包含分隔符（但键不可以）。

另请参见 @ref{2008,,ConfigParser.write()} 的 @emph{space_around_delimiters} 参数。

@item 
@emph{comment_prefixes}，默认值: @code{('#', ';')}

@item 
@emph{inline_comment_prefixes}，默认值: @code{None}

注释前缀是配置文件中用于标示一条有效注释的开头的字符串。 @emph{comment_prefixes} 仅用在被视为空白的行（可以缩进）之前而 @emph{inline_comment_prefixes} 可用在每个有效值之后（例如小节名称、选项以及空白的行）。 默认情况下禁用行内注释，并且 @code{'#'} 和 @code{';'} 都被用作完整行注释的前缀。


在 3.2 版更改: 在之前的 @ref{22,,configparser} 版本中行为匹配 @code{comment_prefixes=('#',';')} 和 @code{inline_comment_prefixes=(';',)}。


请注意配置解析器不支持对注释前缀的转义，因此使用 @emph{inline_comment_prefixes} 可能妨碍用户将被用作注释前缀的字符指定为可选值。 当有疑问时，请避免设置 @emph{inline_comment_prefixes}。 在许多情况下，在多行值的一行开头存储注释前缀字符的唯一方式是进行前缀插值，例如:

@example
>>> from configparser import ConfigParser, ExtendedInterpolation
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> # the default BasicInterpolation could be used as well
>>> parser.read_string("""
... [DEFAULT]
... hash = #
...
... [hashes]
... shebang =
...   $@{hash@}!/usr/bin/env python
...   $@{hash@} -*- coding: utf-8 -*-
...
... extensions =
...   enabled_extension
...   another_extension
...   #disabled_by_comment
...   yet_another_extension
...
... interpolation not necessary = if # is not at line start
... even in multiline values = line #1
...   line #2
...   line #3
... """)
>>> print(parser['hashes']['shebang'])

#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print(parser['hashes']['extensions'])

enabled_extension
another_extension
yet_another_extension
>>> print(parser['hashes']['interpolation not necessary'])
if # is not at line start
>>> print(parser['hashes']['even in multiline values'])
line #1
line #2
line #3
@end example

@item 
@emph{strict}，默认值: @code{True}

当设为 @code{True} 时，解析器在从单一源读取 (使用 @code{read_file()}, @code{read_string()} 或 @code{read_dict()}) 期间将不允许任何小节或选项出现重复。 推荐在新的应用中使用严格解析器。


在 3.2 版更改: 在之前的 @ref{22,,configparser} 版本中行为匹配 @code{strict=False}。


@item 
@emph{empty_lines_in_values}，默认值: @code{True}

在配置解析器中，值可以包含多行，只要它们的缩进级别低于它们所对应的键。 默认情况下解析器还会将空行视为值的一部分。 于此同时，键本身也可以任意缩进以提升可读性。 因此，当配置文件变得非常庞大而复杂时，用户很容易失去对文件结构的掌控。 例如:

@example
[Section]
key = multiline
  value with a gotcha

 this = is still a part of the multiline value of 'key'
@end example

在用户查看时这可能会特别有问题，如果她是使用比例字体来编辑文件的话。 这就是为什么当你的应用不需要带有空行的值时，你应该考虑禁用它们。 这将使得空行每次都会作为键之间的分隔。 在上面的示例中，空行产生了两个键，@code{key} 和 @code{this}。

@item 
@emph{default_section}，默认值: @code{configparser.DEFAULTSECT} (即: @code{"DEFAULT"})

允许设置一个保存默认值的特殊节在其他节或插值等目的中使用的惯例是这个库所拥有的一个强大概念，使得用户能够创建复杂的声明性配置。 这种特殊节通常称为 @code{"DEFAULT"} 但也可以被定制为指向任何其他有效的节名称。 一些典型的值包括: @code{"general"} 或 @code{"common"}。 所提供的名称在从任意节读取的时候被用于识别默认的节，而且也会在将配置写回文件时被使用。 它的当前值可以使用 @code{parser_instance.default_section} 属性来获取，并且可以在运行时被修改（即将文件从一种格式转换为另一种格式）。

@item 
@emph{interpolation}，默认值: @code{configparser.BasicInterpolation}

插值行为可以用通过提供 @emph{interpolation} 参数提供自定义处理程序的方式来定制。 @code{None} 可用来完全禁用插值，@code{ExtendedInterpolation()} 提供了一种更高级的变体形式，它的设计受到了 @code{zc.buildout} 的启发。 有关该主题的更多信息请参见 @ref{2006,,专门的文档章节}。 @ref{965,,RawConfigParser} 具有默认的值 @code{None}。

@item 
@emph{converters}，默认值: 不设置

配置解析器提供了可选的值获取方法用来执行类型转换。 默认实现包括 @ref{2002,,getint()}, @ref{2003,,getfloat()} 以及 @ref{2001,,getboolean()}。 如果还需要其他获取方法，用户可以在子类中定义它们，或者传入一个字典，其中每个键都是一个转换器的名称而每个值都是一个实现了特定转换的可调用对象。 例如，传入 @code{@{'decimal': decimal.Decimal@}} 将对解释器对象和所有节代理添加 @code{getdecimal()}。 换句话说，可以同时编写 @code{parser_instance.getdecimal('section', 'key', fallback=0)} 和 @code{parser_instance['section'].getdecimal('key', 0)}。

如果转换器需要访问解析器的状态，可以在配置解析器子类上作为一个方法来实现。 如果该方法的名称是以 @code{get} 打头的，它将在所有节代理上以兼容字典的形式提供（参见上面的 @code{getdecimal()} 示例）。
@end itemize

更多高级定制选项可通过重载这些解析器属性的默认值来达成。 默认值是在类中定义的，因此它们可以通过子类或属性赋值来重载。

@geindex BOOLEAN_STATES (configparser.ConfigParser 属性)
@anchor{library/configparser configparser ConfigParser BOOLEAN_STATES}@anchor{2009}
@deffn {属性} ConfigParser.BOOLEAN_STATES

默认情况下当使用 @ref{2001,,getboolean()} 时，配置解析器会将下列值视为 @code{True}: @code{'1'}, @code{'yes'}, @code{'true'}, @code{'on'} 而将下列值视为 @code{False}: @code{'0'}, @code{'no'}, @code{'false'}, @code{'off'}。 你可以通过指定一个自定义的字符串键及其对应的布尔值字典来重载此行为。 例如:

@example
>>> custom = configparser.ConfigParser()
>>> custom['section1'] = @{'funky': 'nope'@}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = @{'sure': True, 'nope': False@}
>>> custom['section1'].getboolean('funky')
False
@end example

其他典型的布尔值对包括 @code{accept}/@code{reject} 或 @code{enabled}/@code{disabled}。
@end deffn


@deffn {方法} ConfigParser.optionxform (option)

这个方法会转换每次 read, get, 或 set 操作的选项名称。 默认会将名称转换为小写形式。 这也意味着当一个配置文件被写入时，所有键都将为小写形式。 如果此行为不合适则要重载此方法。 例如:

@example
>>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']
@end example

@cartouche
@quotation 注解 
optionxform 函数会将选项名称转换为规范形式。 这应该是一个幂等函数：如果名称已经为规范形式，则应不加修改地将其返回。
@end quotation
@end cartouche
@end deffn

@geindex SECTCRE (configparser.ConfigParser 属性)
@anchor{library/configparser configparser ConfigParser SECTCRE}@anchor{2005}
@deffn {属性} ConfigParser.SECTCRE

一个已编译正则表达式会被用来解析节标头。 默认将 @code{[section]} 匹配到名称 @code{"section"}。 空格会被视为节名称的一部分，因此 @code{[  larch  ]} 将被读取为一个名称为 @code{"  larch  "} 的节。 如果此行为不合适则要重载此属性。 例如:

@example
>>> import re
>>> config = """
... [Section 1]
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', '  Section 2  ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']
@end example

@cartouche
@quotation 注解 
虽然 ConfigParser 对象也使用 @code{OPTCRE} 属性来识别选项行，但并不推荐重载它，因为这会与构造器选项 @emph{allow_no_value} 和 @emph{delimiters} 产生冲突。
@end quotation
@end cartouche
@end deffn

@node 旧式 API 示例,ConfigParser 对象,定制解析器行为,configparser --- 配置文件解析器
@anchor{library/configparser legacy-api-examples}@anchor{200a}
@subsubsection 旧式 API 示例


主要出于向下兼容性的考虑，@ref{22,,configparser} 还提供了一种采用显式 @code{get}/@code{set} 方法的旧式 API。 虽然以下介绍的方法存在有效的用例，但对于新项目仍建议采用映射协议访问。 旧式 API 在多数时候都更复杂、更底层并且完全违反直觉。

一个写入配置文件的示例:

@example
import configparser

config = configparser.RawConfigParser()

# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
    config.write(configfile)
@end example

一个再次读取配置文件的示例:

@example
import configparser

config = configparser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
    print(config.get('Section1', 'foo'))
@end example

要获取插值，请使用 @ref{5ad,,ConfigParser}:

@example
import configparser

cfg = configparser.ConfigParser()
cfg.read('example.cfg')

# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False))  # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True))   # -> "%(bar)s is %(baz)s!"

# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars=@{'bar': 'Documentation',
                                       'baz': 'evil'@}))

# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
      # -> "No such things as monsters."

# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:

print(cfg.get('Section1', 'monster', fallback=None))
      # -> None
@end example

默认值在两种类型的 ConfigParser 中均可用。 它们将在当某个选项未在别处定义时被用于插值。

@example
import configparser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser(@{'bar': 'Life', 'baz': 'hard'@})
config.read('example.cfg')

print(config.get('Section1', 'foo'))     # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo'))     # -> "Life is hard!"
@end example

@node ConfigParser 对象,RawConfigParser 对象,旧式 API 示例,configparser --- 配置文件解析器
@anchor{library/configparser configparser-objects}@anchor{200b}@anchor{library/configparser id12}@anchor{200c}
@subsubsection ConfigParser 对象


@geindex ConfigParser (configparser 中的类)
@anchor{library/configparser configparser ConfigParser}@anchor{5ad}
@deffn {类} configparser.ConfigParser (defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters=@{@})

主配置解析器。 当给定 @emph{defaults} 时，它会被初始化为包含固有默认值的字典。 当给定 @emph{dict_type} 时，它将被用来创建包含节、节中的选项以及默认值的字典。

当给定 @emph{delimiters} 时，它会被用作分隔键与值的子字符串的集合。 当给定 @emph{comment_prefixes} 时，它将被用作在否则为空行的注释的前缀子字符串的集合。 注释可以被缩进。 当给定 @emph{inline_comment_prefixes} 时，它将被用作非空行的注释的前缀子字符串的集合。

当 @emph{strict} 为 @code{True} (默认值) 时，解析器在从单个源（文件、字符串或字典）读取时将不允许任何节或选项出现重复，否则会引发 @ref{cd8,,DuplicateSectionError} 或 @ref{cd9,,DuplicateOptionError}。 当 @emph{empty_lines_in_values} 为 @code{False} (默认值: @code{True}) 时，每个空行均表示一个选项的结束。 在其他情况下，一个多行选项内部的空行会被保留为值的一部分。 当 @emph{allow_no_value} 为 @code{True} (默认值: @code{False}) 时，将接受没有值的选项；此种选项的值将为 @code{None} 并且它们会以不带末尾分隔符的形式被序列化。

当给定 @emph{default_section} 时，它将指定存放其他节的默认值和用于插值的特殊节的名称 (通常命名为 @code{"DEFAULT"})。 该值可通过使用 @code{default_section} 实例属性在运行时被读取或修改。

插值行为可通过给出 @emph{interpolation} 参数提供自定义处理程序的方式来定制。 @code{None} 可用来完全禁用插值，@code{ExtendedInterpolation()} 提供了一种更高级的变体形式，它的设计受到了 @code{zc.buildout} 的启发。 有关该主题的更多信息请参见 @ref{2006,,专门的文档章节}。

插值中使用的所有选项名称将像任何其他选项名称引用一样通过 @ref{200d,,optionxform()} 方法来传递。 例如，使用 @ref{200d,,optionxform()} 的默认实现（它会将选项名称转换为小写形式）时，值 @code{foo %(bar)s} 和 @code{foo %(BAR)s} 是等价的。

当给定 @emph{converters} 时，它应当为一个字典，其中每个键代表一个类型转换器的名称而每个值则为实现从字符串到目标数据类型的转换的可调用对象。 每个转换器会获得其在解析器对象和节代理上对应的 @code{get*()} 方法。


在 3.1 版更改: 默认的 @emph{dict_type} 为 @ref{2f1,,collections.OrderedDict}。



在 3.2 版更改: 添加了 @emph{allow_no_value}, @emph{delimiters}, @emph{comment_prefixes}, @emph{strict}, @emph{empty_lines_in_values}, @emph{default_section} 以及 @emph{interpolation}。



在 3.5 版更改: 添加了 @emph{converters} 参数。



在 3.7 版更改: @emph{defaults} 参数会通过 @ref{200e,,read_dict()} 来读取，提供全解析器范围内一致的行为：非字符串类型的键和值会被隐式地转换为字符串。



在 3.8 版更改: 默认的 @emph{dict_type} 为 @ref{164,,dict}，因为它现在会保留插入顺序。


@geindex defaults() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser defaults}@anchor{200f}
@deffn {方法} defaults ()

返回包含实例范围内默认值的字典。
@end deffn

@geindex sections() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser sections}@anchor{2010}
@deffn {方法} sections ()

返回可用节的列表；@emph{default section} 不包括在该列表中。
@end deffn

@geindex add_section() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser add_section}@anchor{cd7}
@deffn {方法} add_section (section)

向实例添加一个名为 @emph{section} 的节。 如果给定名称的节已存在，将会引发 @ref{cd8,,DuplicateSectionError}。 如果传入了 @emph{default section} 名称，则会引发 @ref{16d,,ValueError}。 节名称必须为字符串；如果不是则会引发 @ref{1ff,,TypeError}。


在 3.2 版更改: 非字符串的节名称将引发 @ref{1ff,,TypeError}。

@end deffn

@geindex has_section() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser has_section}@anchor{2011}
@deffn {方法} has_section (section)

指明相应名称的 @emph{section} 是否存在于配置中。 @emph{default section} 不包含在内。
@end deffn

@geindex options() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser options}@anchor{2012}
@deffn {方法} options (section)

返回指定 @emph{section} 中可用选项的列表。
@end deffn

@geindex has_option() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser has_option}@anchor{2013}
@deffn {方法} has_option (section, option)

如果给定的 @emph{section} 存在并且包含给定的 @emph{option} 则返回 @ref{59c,,True}；否则返回 @ref{497,,False}。 如果指定的 @emph{section} 为 @ref{204,,None} 或空字符串，则会使用 DEFAULT。
@end deffn

@geindex read() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser read}@anchor{1221}
@deffn {方法} read (filenames, encoding=None)

尝试读取并解析一个包含文件名的可迭代对象，返回一个被成功解析的文件名列表。

如果 @emph{filenames} 为字符串、@ref{172,,bytes} 对象或 @ref{47b,,path-like object}，它会被当作单个文件来处理。 如果 @emph{filenames} 中名称对应的某个文件无法被打开，该文件将被忽略。 这样的设计使得你可以指定包含多个潜在配置文件位置的可迭代对象（例如当前目录、用户家目录以及某个系统级目录），存在于该可迭代对象中的所有配置文件都将被读取。

如果名称对应的文件全都不存在，则 @ref{5ad,,ConfigParser} 实例将包含一个空数据集。 一个要求从文件加载初始值的应用应当在调用 @ref{1221,,read()} 来获取任何可选文件之前使用 @ref{2014,,read_file()} 来加载所要求的一个或多个文件:

@example
import configparser, os

config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
            encoding='cp1250')
@end example


3.2 新版功能: @emph{encoding} 形参。 在之前的版本中，所有文件都将使用 @ref{16f,,open()} 的默认编码格式来读取。



3.6.1 新版功能: @emph{filenames} 形参接受一个 @ref{47b,,path-like object}。



3.7 新版功能: @emph{filenames} 形参接受一个 @ref{172,,bytes} 对象。

@end deffn

@geindex read_file() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser read_file}@anchor{2014}
@deffn {方法} read_file (f, source=None)

从 @emph{f} 读取并解析配置数据，它必须是一个产生 Unicode 字符串的可迭代对象（例如以文本模式打开的文件）。

可选参数 @emph{source} 指定要读取的文件名称。 如果未给出并且 @emph{f} 具有 @code{name} 属性，则该属性会被用作 @emph{source}；默认值为 @code{'<???>'}。


3.2 新版功能: 替代 @ref{2015,,readfp()}。

@end deffn

@geindex read_string() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser read_string}@anchor{2016}
@deffn {方法} read_string (string, source='<string>')

从字符串中解析配置数据。

可选参数 @emph{source} 指定一个所传入字符串的上下文专属名称。 如果未给出，则会使用 @code{'<string>'}。 这通常应为一个文件系统路径或 URL。


3.2 新版功能.

@end deffn

@geindex read_dict() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser read_dict}@anchor{200e}
@deffn {方法} read_dict (dictionary, source='<dict>')

从任意一个提供了类似于字典的 @code{items()} 方法的对象加载配置。 键为节名称，值为包含节中所出现的键和值的字典。 如果所用的字典类型会保留顺序，则节和其中的键将按顺序加入。 值会被自动转换为字符串。

可选参数 @emph{source} 指定一个所传入字曲的上下文专属名称。 如果未给出，则会使用 @code{<dict>}。

此方法可被用于在解析器之间拷贝状态。


3.2 新版功能.

@end deffn

@geindex get() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser get}@anchor{cd5}
@deffn {方法} get (section, option, *, raw=False, vars=None[, fallback])

获取指定名称的 @emph{section} 的一个 @emph{option} 的值。 如果提供了 @emph{vars}，则它必须为一个字典。 @emph{option} 的查找顺序为 @emph{vars*（如果有提供）、*section} 以及 @emph{DEFAULTSECT}。 如果未找到该键并且提供了 @emph{fallback}，则它会被用作回退值。 可以提供 @code{None} 作为 @emph{fallback} 值。

所有 @code{'%'} 插值会在返回值中被展开，除非 @emph{raw} 参数为真值。 插值键所使用的值会按与选项相同的方式来查找。


在 3.2 版更改: @emph{raw}, @emph{vars} 和 @emph{fallback} 都是仅限关键字参数，以防止用户试图使用第三个参数作业为 @emph{fallback} 回退值（特别是在使用映射 协议的时候）。

@end deffn

@geindex getint() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser getint}@anchor{2002}
@deffn {方法} getint (section, option, *, raw=False, vars=None[, fallback])

将在指定 @emph{section} 中的 @emph{option} 强制转换为整数的便捷方法。 参见 @ref{cd5,,get()} 获取对于 @emph{raw}, @emph{vars} 和 @emph{fallback} 的解释。
@end deffn

@geindex getfloat() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser getfloat}@anchor{2003}
@deffn {方法} getfloat (section, option, *, raw=False, vars=None[, fallback])

将在指定 @emph{section} 中的 @emph{option} 强制转换为浮点数的便捷方法。 参见 @ref{cd5,,get()} 获取对于 @emph{raw}, @emph{vars} 和 @emph{fallback} 的解释。
@end deffn

@geindex getboolean() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser getboolean}@anchor{2001}
@deffn {方法} getboolean (section, option, *, raw=False, vars=None[, fallback])

将在指定 @emph{section} 中的 @emph{option} 强制转换为布尔值的便捷方法。 请注意选项所接受的值为 @code{'1'}, @code{'yes'}, @code{'true'} 和 @code{'on'}，它们会使得此方法返回 @code{True}，以及 @code{'0'}, @code{'no'}, @code{'false'} 和 @code{'off'}，它们会使得此方法返回 @code{False}。 这些字符串值会以对大小写不敏感的方式被检测。 任何其他值都将导致引发 @ref{16d,,ValueError}。 参见 @ref{cd5,,get()} 获取对于 @emph{raw}, @emph{vars} 和 @emph{fallback} 的解释。
@end deffn

@geindex items() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser items}@anchor{2017}
@deffn {方法} items (raw=False, vars=None)

@deffnx {方法} items (section, raw=False, vars=None)

当未给出 @emph{section} 时，将返回由 @emph{section_name}, @emph{section_proxy} 对组成的列表，包括 DEFAULTSECT。

在其他情况下，将返回给定的 @emph{section} 中的 option 的 @emph{name}, @emph{value} 对组成的列表。 可选参数具有与 @ref{cd5,,get()} 方法的参数相同的含义。


在 3.8 版更改: @emph{vars} 中的条目将不在结果中出现。 之前的行为混淆了实际的解析器选项和为插值提供的变量。

@end deffn

@geindex set() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser set}@anchor{cd6}
@deffn {方法} set (section, option, value)

如果给定的节存在，则将所给出的选项设为指定的值；在其他情况下将引发 @ref{2018,,NoSectionError}。 @emph{option} 和 @emph{value} 必须为字符串；如果不是则将引发 @ref{1ff,,TypeError}。
@end deffn

@geindex write() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser write}@anchor{2008}
@deffn {方法} write (fileobject, space_around_delimiters=True)

将配置的表示形式写入指定的 @ref{c1d,,file object}，该对象必须以文本模式打开（接受字符串）。 此表示形式可由将来的 @ref{1221,,read()} 调用进行解析。 如果 @emph{space_around_delimiters} 为真值，键和值之前的分隔符两边将加上空格。
@end deffn

@cartouche
@quotation 注解 
原始配置文件中的注释在写回配置时不会被保留。 具体哪些会被当作注释，取决于为 @emph{comment_prefix} 和 @emph{inline_comment_prefix} 所指定的值。
@end quotation
@end cartouche

@geindex remove_option() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser remove_option}@anchor{2019}
@deffn {方法} remove_option (section, option)

将指定的 @emph{option} 从指定的 @emph{section} 中移除。 如果指定的节不存在则会引发 @ref{2018,,NoSectionError}。 如果要移除的选项存在则返回 @ref{59c,,True}；在其他情况下将返回 @ref{497,,False}。
@end deffn

@geindex remove_section() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser remove_section}@anchor{201a}
@deffn {方法} remove_section (section)

从配置中移除指定的 @emph{section}。 如果指定的节确实存在则返回 @code{True}。 在其他情况下将返回 @code{False}。
@end deffn

@geindex optionxform() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser optionxform}@anchor{200d}
@deffn {方法} optionxform (option)

将选项名 @emph{option} 转换为输入文件中的形式或客户端代码所传入的应当在内部结构中使用的形式。 默认实现将返回 @emph{option} 的小写形式版本；子类可以重载此行为，或者客户端代码也可以在实例上设置一个具有此名称的属性来影响此行为。

你不需要子类化解析器来使用此方法，你也可以在一个实例上设置它，或使用一个接受字符串参数并返回字符串的函数。 例如将它设为 @code{str} 将使得选项名称变得大小写敏感:

@example
cfgparser = ConfigParser()
cfgparser.optionxform = str
@end example

请注意当读取配置文件时，选项名称两边的空格将在调用 @ref{200d,,optionxform()} 之前被去除。
@end deffn

@geindex readfp() (configparser.ConfigParser 方法)
@anchor{library/configparser configparser ConfigParser readfp}@anchor{2015}
@deffn {方法} readfp (fp, filename=None)


3.2 版后已移除: 使用 @ref{2014,,read_file()} 来代替。



在 3.2 版更改: @ref{2015,,readfp()} 现在将在 @emph{fp} 上执行迭代而不是调用 @code{fp.readline()}。


对于调用 @ref{2015,,readfp()} 时传入不支持迭代的参数的现有代码，可以在文件类对象外使用以下生成器作为包装器:

@example
def readline_generator(fp):
    line = fp.readline()
    while line:
        yield line
        line = fp.readline()
@end example

不再使用 @code{parser.readfp(fp)} 而是改用 @code{parser.read_file(readline_generator(fp))}。
@end deffn
@end deffn

@geindex MAX_INTERPOLATION_DEPTH() (在 configparser 模块中)
@anchor{library/configparser configparser MAX_INTERPOLATION_DEPTH}@anchor{201b}
@deffn {数据} configparser.MAX_INTERPOLATION_DEPTH

当 @emph{raw} 形参为假值时 @code{get()} 所采用的递归插值的最大深度。 这只在使用默认的 @emph{interpolation} 时会起作用。
@end deffn

@node RawConfigParser 对象,异常<6>,ConfigParser 对象,configparser --- 配置文件解析器
@anchor{library/configparser id14}@anchor{201c}@anchor{library/configparser rawconfigparser-objects}@anchor{201d}
@subsubsection RawConfigParser 对象


@geindex RawConfigParser (configparser 中的类)
@anchor{library/configparser configparser RawConfigParser}@anchor{965}
@deffn {类} configparser.RawConfigParser (defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])

旧式 @ref{5ad,,ConfigParser}。 它默认禁用插值并且允许通过不安全的 @code{add_section} 和 @code{set} 方法以及旧式 @code{defaults=} 关键字参数处理来设置非字符串的节名、选项名和值。


在 3.8 版更改: 默认的 @emph{dict_type} 为 @ref{164,,dict}，因为它现在会保留插入顺序。


@cartouche
@quotation 注解 
考虑改用 @ref{5ad,,ConfigParser}，它会检查内部保存的值的类型。 如果你不想要插值，你可以使用 @code{ConfigParser(interpolation=None)}。
@end quotation
@end cartouche

@geindex add_section() (configparser.RawConfigParser 方法)
@anchor{library/configparser configparser RawConfigParser add_section}@anchor{201e}
@deffn {方法} add_section (section)

向实例添加一个名为 @emph{section} 的节。 如果给定名称的节已存在，将会引发 @ref{cd8,,DuplicateSectionError}。 如果传入了 @emph{default section} 名称，则会引发 @ref{16d,,ValueError}。

不检查 @emph{section} 以允许用户创建以非字符串命名的节。 此行为已不受支持并可能导致内部错误。
@end deffn

@geindex set() (configparser.RawConfigParser 方法)
@anchor{library/configparser configparser RawConfigParser set}@anchor{201f}
@deffn {方法} set (section, option, value)

如果给定的节存在，则将给定的选项设为指定的值；在其他情况下将引发 @ref{2018,,NoSectionError}。 虽然可能使用 @ref{965,,RawConfigParser} (或使用 @ref{5ad,,ConfigParser} 并将 @emph{raw} 形参设为真值) 以便实现非字符串值的 @emph{internal} 存储，但是完整功能（包括插值和输出到文件）只能使用字符串值来实现。

此方法允许用户在内部将非字符串值赋给键。 此行为已不受支持并会在尝试写入到文件或在非原始模式下获取数据时导致错误。 @strong{请使用映射协议 API}，它不允许出现这样的赋值。
@end deffn
@end deffn

@node 异常<6>,,RawConfigParser 对象,configparser --- 配置文件解析器
@anchor{library/configparser exceptions}@anchor{2020}
@subsubsection 异常


@geindex Error
@anchor{library/configparser configparser Error}@anchor{2021}
@deffn {例外} configparser.Error

所有其他 @ref{22,,configparser} 异常的基类。
@end deffn

@geindex NoSectionError
@anchor{library/configparser configparser NoSectionError}@anchor{2018}
@deffn {例外} configparser.NoSectionError

当找不到指定节时引发的异常。
@end deffn

@geindex DuplicateSectionError
@anchor{library/configparser configparser DuplicateSectionError}@anchor{cd8}
@deffn {例外} configparser.DuplicateSectionError

当调用 @code{add_section()} 时传入已存在的节名称，或者在严格解析器中当单个输入文件、字符串或字典内出现重复的节时引发的异常。


3.2 新版功能: 将可选的 @code{source} 和 @code{lineno} 属性和参数添加到 @ref{e2b,,__init__()}。

@end deffn

@geindex DuplicateOptionError
@anchor{library/configparser configparser DuplicateOptionError}@anchor{cd9}
@deffn {例外} configparser.DuplicateOptionError

当单个选项在从单个文件、字符串或字典读取时出现两次时引发的异常。 这会捕获拼写错误和大小写敏感相关的错误，例如一个字典可能包含两个键分别代表同一个大小写不敏感的配置键。
@end deffn

@geindex NoOptionError
@anchor{library/configparser configparser NoOptionError}@anchor{2022}
@deffn {例外} configparser.NoOptionError

当指定的选项未在指定的节中被找到时引发的异常。
@end deffn

@geindex InterpolationError
@anchor{library/configparser configparser InterpolationError}@anchor{2023}
@deffn {例外} configparser.InterpolationError

当执行字符串插值发生问题时所引发的异常的基类。
@end deffn

@geindex InterpolationDepthError
@anchor{library/configparser configparser InterpolationDepthError}@anchor{2024}
@deffn {例外} configparser.InterpolationDepthError

当字符串插值由于迭代次数超出 @ref{201b,,MAX_INTERPOLATION_DEPTH} 而无法完成所引发的异常。 为 @ref{2023,,InterpolationError} 的子类。
@end deffn

@geindex InterpolationMissingOptionError
@anchor{library/configparser configparser InterpolationMissingOptionError}@anchor{2025}
@deffn {例外} configparser.InterpolationMissingOptionError

当从某个值引用的选项并不存在时引发的异常。 为 @ref{2023,,InterpolationError} 的子类。
@end deffn

@geindex InterpolationSyntaxError
@anchor{library/configparser configparser InterpolationSyntaxError}@anchor{2026}
@deffn {例外} configparser.InterpolationSyntaxError

当将要执行替换的源文本不符合要求的语法时引发的异常。 为 @ref{2023,,InterpolationError} 的子类。
@end deffn

@geindex MissingSectionHeaderError
@anchor{library/configparser configparser MissingSectionHeaderError}@anchor{2027}
@deffn {例外} configparser.MissingSectionHeaderError

当尝试解析一个不带节标头的文件时引发的异常。
@end deffn

@geindex ParsingError
@anchor{library/configparser configparser ParsingError}@anchor{2028}
@deffn {例外} configparser.ParsingError

当尝试解析一个文件而发生错误时引发的异常。


在 3.2 版更改: @code{filename} 属性和 @ref{e2b,,__init__()} 参数被重命名为 @code{source} 以保持一致性。

@end deffn

@node netrc --- netrc 文件处理,plistlib --- 生成与解析 Apple plist 文件,configparser --- 配置文件解析器,文件格式
@anchor{library/netrc doc}@anchor{2029}@anchor{library/netrc module-netrc}@anchor{be}@anchor{library/netrc netrc-netrc-file-processing}@anchor{202a}
@subsection @code{netrc} --- netrc 文件处理


@geindex netrc (模块)

@strong{源代码:} Lib/netrc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/netrc.py}


__________________________________________________________________


@ref{121d,,netrc} 类解析并封装了 Unix 的 @code{ftp} 程序和其他 FTP 客户端所使用的 netrc 文件格式。

@geindex netrc (netrc 中的类)
@anchor{library/netrc netrc netrc}@anchor{121d}
@deffn {类} netrc.netrc ([file])

@ref{121d,,netrc} 的实例或其子类的实例会被用来封装来自 netrc 文件的数据。 如果有初始化参数，它将指明要解析的文件。 如果未给出参数，则位于用户家目录的 @code{.netrc} 文件 -- 即 @ref{333,,os.path.expanduser()} 所确定的文件 -- 将会被读取。 在其他情况下，则将引发 @ref{8b7,,FileNotFoundError} 异常。 解析错误将引发 @ref{202b,,NetrcParseError} 并附带诊断信息，包括文件名、行号以及终止令牌。 如果在 POSIX 系统上未指明参数，则当 @code{.netrc} 文件中有密码时，如果文件归属或权限不安全（归属的用户不是运行进程的用户，或者可供任何其他用户读取或写入）将引发 @ref{202b,,NetrcParseError}。 这实现了与 ftp 和其他使用 @code{.netrc} 的程序同等的安全行为。


在 3.4 版更改: 添加了 POSIX 权限检查。



在 3.7 版更改: 当未将 @emph{file} 作为参数传入时会使用 @ref{333,,os.path.expanduser()} 来查找 @code{.netrc} 文件的位置。

@end deffn

@geindex NetrcParseError
@anchor{library/netrc netrc NetrcParseError}@anchor{202b}
@deffn {例外} netrc.NetrcParseError

当在源文本中遇到语法错误时由 @ref{121d,,netrc} 类引发的异常。 此异常的实例提供了三个有用属性:  @code{msg} 为错误的文本说明，@code{filename} 为源文件的名称，而 @code{lineno} 给出了错误所在的行号。
@end deffn

@menu
* netrc 对象:: 

@end menu

@node netrc 对象,,,netrc --- netrc 文件处理
@anchor{library/netrc id1}@anchor{202c}@anchor{library/netrc netrc-objects}@anchor{202d}
@subsubsection netrc 对象


@ref{121d,,netrc} 实例具有下列方法:

@geindex authenticators() (netrc.netrc 方法)
@anchor{library/netrc netrc netrc authenticators}@anchor{202e}
@deffn {方法} netrc.authenticators (host)

针对 @emph{host} 的身份验证者返回一个 3 元组 @code{(login, account, password)}。 如果 netrc 文件不包含针对给定主机的条目，则返回关联到 'default' 条目的元组。 如果匹配的主机或默认条目均不可用，则返回 @code{None}。
@end deffn

@geindex __repr__() (netrc.netrc 方法)
@anchor{library/netrc netrc netrc __repr__}@anchor{202f}
@deffn {方法} netrc.__repr__ ()

将类数据以 netrc 文件的格式转储为一个字符串。 （这会丢弃注释并可能重排条目顺序。）
@end deffn

@ref{121d,,netrc} 的实例具有一些公共实例变量:

@geindex hosts (netrc.netrc 属性)
@anchor{library/netrc netrc netrc hosts}@anchor{2030}
@deffn {属性} netrc.hosts

将主机名映射到 @code{(login, account, password)} 元组的字典。 如果存在 'default' 条目，则会表示为使用该名称的伪主机。
@end deffn

@geindex macros (netrc.netrc 属性)
@anchor{library/netrc netrc netrc macros}@anchor{2031}
@deffn {属性} netrc.macros

将宏名称映射到字符串列表的字典。
@end deffn

@cartouche
@quotation 注解 
密码会被限制为 ASCII 字符集的一个子集。 所有 ASCII 标点符号均可用作密码，但是要注意空白符和非打印字符不允许用作密码。 这是 .netrc 文件解析方式带来的限制，在未来可能会被解除。
@end quotation
@end cartouche

@node plistlib --- 生成与解析 Apple plist 文件,,netrc --- netrc 文件处理,文件格式
@anchor{library/plistlib doc}@anchor{2032}@anchor{library/plistlib module-plistlib}@anchor{cf}@anchor{library/plistlib plistlib-generate-and-parse-apple-plist-files}@anchor{2033}
@subsection @code{plistlib} --- 生成与解析 Apple @code{.plist} 文件


@geindex plistlib (模块)

@c (harvested from docstrings in the original file)

@strong{源代码:} Lib/plistlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/plistlib.py}

@geindex plist; file
@geindex property list


__________________________________________________________________


此模块提供了可读写 Apple "property list" 文件的接口，它主要用于 macOS 和 iOS 系统。 此模块同时支持二进制和 XML plist 文件。

property list (@code{.plist}) 文件格式是一种简单的序列化格式，它支持一些基本对象类型，例如字典、列表、数字和字符串等。 通常使用一个字典作为最高层级对象。

要写入和解析 plist 文件，请使用 @ref{221,,dump()} 和 @ref{21f,,load()} 函数。

要以字节串对象形式操作 plist 数据，请使用 @ref{222,,dumps()} 和 @ref{220,,loads()}。

值可以为字符串、整数、浮点数、布尔值、元组、列表、字典（但只允许用字符串作为键）、@ref{172,,bytes}、@ref{173,,bytearray} 或 @ref{19f,,datetime.datetime} 对象。


在 3.4 版更改: 新版 API，旧版 API 已被弃用。 添加了对二进制 plist 格式的支持。



在 3.8 版更改: 添加了在二进制 plist 中读写 @ref{345,,UID} 令牌的支持，例如用于 NSKeyedArchiver 和 NSKeyedUnarchiver。



在 3.9 版更改: 旧 API 已被移除。



@subsubheading 参见



@table @asis

@item PList 指南页面@footnote{https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/}

针对该文件格式的 Apple 文档。
@end table


这个模块定义了以下函数：

@geindex load() (在 plistlib 模块中)
@anchor{library/plistlib plistlib load}@anchor{21f}
@deffn {函数} plistlib.load (fp, *, fmt=None, dict_type=dict)

读取 plist 文件。 @emph{fp} 应当可读并且为二进制文件对象。 返回已解包的根对象（通常是一个字典）。

@emph{fmt} 为文件的格式，有效的值如下:


@itemize *

@item 
@ref{204,,None}: 自动检测文件格式

@item 
@ref{97f,,FMT_XML}: XML 文件格式

@item 
@ref{980,,FMT_BINARY}: 二进制 plist 格式
@end itemize

@emph{dict_type} 为字典用来从 plist 文件读取的类型。

@ref{97f,,FMT_XML} 格式的 XML 数据 会使用来自 @ref{141,,xml.parsers.expat} 的 Expat 解析器 -- 请参阅其文档了解错误格式 XML 可能引发的异常。 未知元素将被 plist 解析器直接略过。

当文件无法被解析时二进制格式的解析器将引发 @code{InvalidFileException}。


3.4 新版功能.

@end deffn

@geindex loads() (在 plistlib 模块中)
@anchor{library/plistlib plistlib loads}@anchor{220}
@deffn {函数} plistlib.loads (data, *, fmt=None, dict_type=dict)

从一个 bytes 对象加载 plist。 参阅 @ref{21f,,load()} 获取相应关键字参数的说明。


3.4 新版功能.

@end deffn

@geindex dump() (在 plistlib 模块中)
@anchor{library/plistlib plistlib dump}@anchor{221}
@deffn {函数} plistlib.dump (value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)

将 @emph{value} 写入 plist 文件。 @emph{Fp} 应当可写并且为二进制文件对象。

@emph{fmt} 参数指定 plist 文件的格式，可以是以下值之一:


@itemize *

@item 
@ref{97f,,FMT_XML}: XML 格式的 plist 文件

@item 
@ref{980,,FMT_BINARY}: 二进制格式的 plist 文件
@end itemize

当 @emph{sort_keys} 为真值（默认）时字典的键将经过排序再写入 plist，否则将按字典的迭代顺序写入。

当 @emph{skipkeys} 为假值（默认）时该函数将在字典的键不为字符串时引发 @ref{1ff,,TypeError}，否则将跳过这样的键。

如果对象是不受支持的类型或者是包含不受支持类型的对象的容器则将引发 @ref{1ff,,TypeError}。

对于无法在（二进制）plist 文件中表示的整数值，将会引发 @ref{a4a,,OverflowError}。


3.4 新版功能.

@end deffn

@geindex dumps() (在 plistlib 模块中)
@anchor{library/plistlib plistlib dumps}@anchor{222}
@deffn {函数} plistlib.dumps (value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)

将 @emph{value} 以 plist 格式字节串对象的形式返回。 参阅 @ref{221,,dump()} 的文档获取此函数的关键字参数的说明。


3.4 新版功能.

@end deffn

可以使用以下的类:

@geindex UID (plistlib 中的类)
@anchor{library/plistlib plistlib UID}@anchor{345}
@deffn {类} plistlib.UID (data)

包装一个 @ref{205,,int}。 该类将在读取或写入 NSKeyedArchiver 编码的数据时被使用，其中包含 UID（参见 PList 指南）。

它具有一个属性 @code{data}，可以被用来提取 UID 的 int 值。 @code{data} 的取值范围必须为 @code{0 <= data < 2**64}。


3.8 新版功能.

@end deffn

可以使用以下的常量:

@geindex FMT_XML() (在 plistlib 模块中)
@anchor{library/plistlib plistlib FMT_XML}@anchor{97f}
@deffn {数据} plistlib.FMT_XML

用于 plist 文件的 XML 格式。


3.4 新版功能.

@end deffn

@geindex FMT_BINARY() (在 plistlib 模块中)
@anchor{library/plistlib plistlib FMT_BINARY}@anchor{980}
@deffn {数据} plistlib.FMT_BINARY

用于 plist 文件的二进制格式。


3.4 新版功能.

@end deffn

@menu
* 示例: 示例<14>. 

@end menu

@node 示例<14>,,,plistlib --- 生成与解析 Apple plist 文件
@anchor{library/plistlib examples}@anchor{2034}
@subsubsection 示例


生成一个 plist:

@example
pl = dict(
    aString = "Doodah",
    aList = ["A", "B", 12, 32.1, [1, 2, 3]],
    aFloat = 0.1,
    anInt = 728,
    aDict = dict(
        anotherString = "<hello & hi there!>",
        aThirdString = "M\xe4ssig, Ma\xdf",
        aTrueValue = True,
        aFalseValue = False,
    ),
    someData = b"<binary gunk>",
    someMoreData = b"<lots of binary gunk>" * 10,
    aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
)
with open(fileName, 'wb') as fp:
    dump(pl, fp)
@end example

解析一个 plist:

@example
with open(fileName, 'rb') as fp:
    pl = load(fp)
print(pl["aKey"])
@end example

@node 加密服务,通用操作系统服务,文件格式,Python 标准库
@anchor{library/crypto doc}@anchor{2035}@anchor{library/crypto crypto}@anchor{2036}@anchor{library/crypto cryptographic-services}@anchor{2037}
@section 加密服务


@geindex cryptography

本章中描述的模块实现了加密性质的各种算法。 它们可以在安装时自行选择。 在 Unix 系统上，@ref{28,,crypt} 模块也可以使用。 以下是为内容概要：

@menu
* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 生成管理密码的安全随机数. 生成管理密码的安全随机数

@end menu

@node hashlib --- 安全哈希与消息摘要,hmac --- 基于密钥的消息验证,,加密服务
@anchor{library/hashlib doc}@anchor{2038}@anchor{library/hashlib hashlib-secure-hashes-and-message-digests}@anchor{2039}@anchor{library/hashlib module-hashlib}@anchor{8c}
@subsection @code{hashlib} --- 安全哈希与消息摘要


@geindex hashlib (模块)

@strong{源码：} Lib/hashlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/hashlib.py}

@geindex message digest@comma{} MD5
@geindex secure hash algorithm@comma{} SHA1@comma{} SHA224@comma{} SHA256@comma{} SHA384@comma{} SHA512

@c import hashlib


__________________________________________________________________


这个模块针对不同的安全哈希和消息摘要算法实现了一个通用的接口。包括 FIPS 的 SHA1, SHA224, SHA256, SHA384, and SHA512 (定义于 FIPS 180-2) 算法，以及 RSA 的 MD5 算法( 定义于 Internet 
@geindex RFC; RFC 1321
RFC 1321@footnote{https://tools.ietf.org/html/rfc1321.html})。术语“安全哈希”和“消息摘要”是可互换的，较旧的算法被称为消息摘要，现代术语是安全哈希。

@cartouche
@quotation 注解 
如果你想找到 adler32 或 crc32 哈希函数，它们在 @ref{14d,,zlib} 模块中。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
有些算法已知存在哈希碰撞弱点，请参考最后的“另请参阅”段。
@end quotation
@end cartouche

@menu
* 哈希算法:: 
* SHAKE 可变长度摘要:: 
* 密钥派生:: 
* BLAKE2:: 

@end menu

@node 哈希算法,SHAKE 可变长度摘要,,hashlib --- 安全哈希与消息摘要
@anchor{library/hashlib hash-algorithms}@anchor{203a}@anchor{library/hashlib id1}@anchor{203b}
@subsubsection 哈希算法


每种类型的 @emph{hash} 都有一个构造器方法。 它们都返回一个具有相同的简单接口的 hash 对象。 例如，使用 use @code{sha256()} 创建一个 SHA-256 hash 对象。 你可以使用 @code{update()} 方法向这个对象输入 @ref{6e9,,字节类对象} (通常是 @ref{172,,bytes})。 在任何时候你都可以使用 @code{digest()} 或 @code{hexdigest()} 方法获得到目前为止输入这个对象的拼接数据的 @emph{digest}。

@cartouche
@quotation 注解 
为了更好的多线程性能，在对象创建或者更新时，若数据大于2047字节则 Python 的 @ref{20f,,GIL} 会被释放。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
向 @code{update()} 输入字符串对象是不被支持的，因为哈希基于字节而非字符。
@end quotation
@end cartouche

@geindex OpenSSL; (use in module hashlib)

此模块中总是可用的哈希算法构造器有 @code{sha1()}, @code{sha224()}, @code{sha256()}, @code{sha384()}, @code{sha512()}, @ref{64f,,blake2b()} 和 @ref{650,,blake2s()}。 @code{md5()} 通常也是可用的，但如果你在使用少见的 "FIPS 兼容" 的 Python 编译版本则可能会找不到它。 此外还可能有一些附加的算法，具体取决于你的平台上的 Python 所使用的 OpenSSL 库。 在大部分平台上可用的还有 @code{sha3_224()}, @code{sha3_256()}, @code{sha3_384()}, @code{sha3_512()}, @code{shake_128()}, @code{shake_256()} 等等。·


3.6 新版功能: SHA3 (Keccak) 和 SHAKE 构造器 @code{sha3_224()}, @code{sha3_256()}, @code{sha3_384()}, @code{sha3_512()}, @code{shake_128()}, @code{shake_256()}.



3.6 新版功能: 添加了 @ref{64f,,blake2b()} 和 @ref{650,,blake2s()} 。

@anchor{library/hashlib hashlib-usedforsecurity}@anchor{203c}

在 3.9 版更改: 所有 hashlib 的构造器都接受仅限关键字参数 @emph{usedforsecurity} 且其默认值为 @code{True}。 设为假值即允许在受限的环境中使用不安全且阻塞的哈希算法。 @code{False} 表示此哈希算法不可用于安全场景，例如用作非加密的单向压缩函数。

现在 hashlib 会使用 OpenSSL 1.1.1 或更新版本的 SHA3 和 SHAKE。


例如，如果想获取字节串 @code{b'Nobody inspects the spammish repetition'} 的摘要:

@example
>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\x03\x1e\xdd@}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
>>> m.digest_size
32
>>> m.block_size
64
@end example

更简要的写法：

@example
>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
@end example

@geindex new() (在 hashlib 模块中)
@anchor{library/hashlib hashlib new}@anchor{107a}
@deffn {函数} hashlib.new (name[, data], *, usedforsecurity=True)

一个接受所希望的算法对应的字符串 @emph{name} 作为第一个形参的通用构造器。 它还允许访问上面列出的哈希算法以及你的 OpenSSL 库可能提供的任何其他算法。 同名的构造器要比 @ref{107a,,new()} 更快所以应当优先使用。
@end deffn

使用 @ref{107a,,new()} 并附带由 OpenSSL 所提供了算法:

@example
>>> h = hashlib.new('sha256')
>>> h.update(b"Nobody inspects the spammish repetition")
>>> h.hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'
@end example

Hashlib 提供下列常量属性：

@geindex algorithms_guaranteed() (在 hashlib 模块中)
@anchor{library/hashlib hashlib algorithms_guaranteed}@anchor{dca}
@deffn {数据} hashlib.algorithms_guaranteed

一个集合，其中包含此模块在所有平台上都保证支持的哈希算法的名称。 请注意 'md5' 也在此清单中，虽然某些上游厂商提供了一个怪异的排除了此算法的 "FIPS 兼容" Python 编译版本。


3.2 新版功能.

@end deffn

@geindex algorithms_available() (在 hashlib 模块中)
@anchor{library/hashlib hashlib algorithms_available}@anchor{dcb}
@deffn {数据} hashlib.algorithms_available

一个集合，其中包含在所运行的 Python 解释器上可用的哈希算法的名称。 将这些名称传给 @ref{107a,,new()} 时将可被识别。 @ref{dca,,algorithms_guaranteed} 将总是它的一个子集。 同样的算法在此集合中可能以不同的名称出现多次（这是 OpenSSL 的原因）。


3.2 新版功能.

@end deffn

下列值会以构造器所返回的哈希对象的常量属性的形式被提供:

@geindex hash.digest_size() (在 hashlib 模块中)
@anchor{library/hashlib hashlib hash digest_size}@anchor{203d}
@deffn {数据} hash.digest_size

以字节表示的结果哈希对象的大小。
@end deffn

@geindex hash.block_size() (在 hashlib 模块中)
@anchor{library/hashlib hashlib hash block_size}@anchor{203e}
@deffn {数据} hash.block_size

以字节表示的哈希算法的内部块大小。
@end deffn

hash 对象具有以下属性：

@geindex name (hashlib.hash 属性)
@anchor{library/hashlib hashlib hash name}@anchor{948}
@deffn {属性} hash.name

此哈希对象的规范名称，总是为小写形式并且总是可以作为 @ref{107a,,new()} 的形参用来创建另一个此类型的哈希对象。


在 3.4 版更改: 该属性名称自被引入起即存在于 CPython 中，但在 Python 3.4 之前并未正式指明，因此可能不存在于某些平台上。

@end deffn

哈希对象具有下列方法:

@geindex update() (hashlib.hash 方法)
@anchor{library/hashlib hashlib hash update}@anchor{203f}
@deffn {方法} hash.update (data)

用 @ref{6e9,,bytes-like object} 来更新哈希对象。 重复调用相当于单次调用并传入所有参数的拼接结果: @code{m.update(a); m.update(b)} 等价于 @code{m.update(a+b)}。


在 3.1 版更改: 当使用 OpenSSL 提供的哈希算法在大于 2047 字节的数据上执行哈希更新时 Python GIL 会被释放以允许其他线程运行。

@end deffn

@geindex digest() (hashlib.hash 方法)
@anchor{library/hashlib hashlib hash digest}@anchor{2040}
@deffn {方法} hash.digest ()

返回当前已传给 @ref{203f,,update()} 方法的数据摘要。 这是一个大小为 @ref{203d,,digest_size} 的字节串对象，字节串中可包含 0 至 255 的完整取值范围。
@end deffn

@geindex hexdigest() (hashlib.hash 方法)
@anchor{library/hashlib hashlib hash hexdigest}@anchor{2041}
@deffn {方法} hash.hexdigest ()

类似于 @ref{2040,,digest()} 但摘要会以两倍长度字符串对象的形式返回，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安全地交换数据值。
@end deffn

@geindex copy() (hashlib.hash 方法)
@anchor{library/hashlib hashlib hash copy}@anchor{2042}
@deffn {方法} hash.copy ()

返回哈希对象的副本（“克隆”）。 这可被用来高效地计算共享相同初始子串的数据的摘要。
@end deffn

@node SHAKE 可变长度摘要,密钥派生,哈希算法,hashlib --- 安全哈希与消息摘要
@anchor{library/hashlib shake-variable-length-digests}@anchor{2043}
@subsubsection SHAKE 可变长度摘要


@code{shake_128()} 和 @code{shake_256()} 算法提供安全的 length_in_bits//2 至 128 或 256 位可变长度摘要。 为此，它们的摘要需指定一个长度。 SHAKE 算法不限制最大长度。

@geindex digest() (hashlib.shake 方法)
@anchor{library/hashlib hashlib shake digest}@anchor{11a6}
@deffn {方法} shake.digest (length)

返回当前已传给 @code{update()} 方法的数据摘要。 这是一个大小为 @emph{length} 的字节串对象，字节串中可包含 0 to 255 的完整取值范围。
@end deffn

@geindex hexdigest() (hashlib.shake 方法)
@anchor{library/hashlib hashlib shake hexdigest}@anchor{11a7}
@deffn {方法} shake.hexdigest (length)

类似于 @ref{11a6,,digest()} 但摘要会以两倍长度字符串对象的形式返回，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安全地交换数据值。
@end deffn

@node 密钥派生,BLAKE2,SHAKE 可变长度摘要,hashlib --- 安全哈希与消息摘要
@anchor{library/hashlib key-derivation}@anchor{2044}
@subsubsection 密钥派生


密钥派生和密钥延展算法被设计用于安全密码哈希。 @code{sha1(password)} 这样的简单算法无法防御暴力攻击。 好的密码哈希函数必须可以微调、放慢步调，并且包含 加盐@footnote{https://en.wikipedia.org/wiki/Salt_%28cryptography%29}。

@geindex pbkdf2_hmac() (在 hashlib 模块中)
@anchor{library/hashlib hashlib pbkdf2_hmac}@anchor{8dd}
@deffn {函数} hashlib.pbkdf2_hmac (hash_name, password, salt, iterations, dklen=None)

此函数提供 PKCS#5 基于密码的密钥派生函数 2。 它使用 HMAC 作为伪随机函数。

字符串 @emph{hash_name} 是要求用于 HMAC 的哈希摘要算法的名称，例如 'sha1' 或 'sha256'。 @emph{password} 和 @emph{salt} 会以字节串缓冲区的形式被解析。 应用和库应当将 @emph{password} 限制在合理长度 (例如 1024)。 @emph{salt} 应当为适当来源例如 @ref{5d4,,os.urandom()} 的大约 16 个或更多的字节串数据。

@emph{iterations} 数值应当基于哈希算法和算力来选择。 在 2013 年时，建议至少为 100,000 次 SHA-256 迭代。

@emph{dklen} 为派生密钥的长度。 如果 @emph{dklen} 为 @code{None} 则会使用哈希算法 @emph{hash_name} 的摘要大小，例如 SHA-512 为 64。

@example
>>> import hashlib
>>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
>>> dk.hex()
'0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'
@end example


3.4 新版功能.


@cartouche
@quotation 注解 
随同 OpenSSL 提供了一个快速的 @emph{pbkdf2_hmac} 实现。 Python 实现是使用 @ref{8e,,hmac} 的内联版本。 它的速度大约要慢上三倍并且不会释放 GIL。
@end quotation
@end cartouche
@end deffn

@geindex scrypt() (在 hashlib 模块中)
@anchor{library/hashlib hashlib scrypt}@anchor{5d5}
@deffn {函数} hashlib.scrypt (password, *, salt, n, r, p, maxmem=0, dklen=64)

此函数提供基于密码加密的密钥派生函数，其定义参见 
@geindex RFC; RFC 7914
RFC 7914@footnote{https://tools.ietf.org/html/rfc7914.html}。

@emph{password} 和 @emph{salt} 必须为 @ref{6e9,,字节类对象}。 应用和库应当将 @emph{password} 限制在合理长度 (例如 1024)。 @emph{salt} 应当为适当来源例如 @ref{5d4,,os.urandom()} 的大约 16 个或更多的字节串数据。

@emph{n} 为 CPU/内存开销因子，@emph{r} 为块大小，@emph{p} 为并行化因子，@emph{maxmem} 为内存限制 (OpenSSL 1.1.0 默认为 32 MiB)。 @emph{dklen} 为派生密钥的长度。

@ref{14c1,,可用性}: OpenSSL 1.1+。


3.6 新版功能.

@end deffn

@node BLAKE2,,密钥派生,hashlib --- 安全哈希与消息摘要
@anchor{library/hashlib blake2}@anchor{2045}
@subsubsection BLAKE2


@geindex blake2b@comma{} blake2s

BLAKE2@footnote{https://blake2.net} 是在 
@geindex RFC; RFC 7693
RFC 7693@footnote{https://tools.ietf.org/html/rfc7693.html} 中定义的加密哈希函数，它有两种形式:


@itemize *

@item 
@strong{BLAKE2b}，针对 64 位平台进行优化，并会生成长度介于 1 和 64 字节之间任意大小的摘要。

@item 
@strong{BLAKE2s}，针对 8 至 32 位平台进行优化，并会生成长度介于 1 和 32 字节之间任意大小的摘要。
@end itemize

BLAKE2 支持 @strong{keyed mode} (HMAC@footnote{https://en.wikipedia.org/wiki/Hash-based_message_authentication_code} 的更快速更简单的替代), @strong{salted hashing}, @strong{personalization} 和 @strong{tree hashing}.

此模块的哈希对象遵循标准库 @ref{8c,,hashlib} 对象的 API。

@menu
* 创建哈希对象:: 
* 常数: 常数<4>. 
* 示例: 示例<15>. 
* 开发人员:: 

@end menu

@node 创建哈希对象,常数<4>,,BLAKE2
@anchor{library/hashlib creating-hash-objects}@anchor{2046}
@subsubsection 创建哈希对象


新哈希对象可通过调用构造器函数来创建:

@geindex blake2b() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2b}@anchor{64f}
@deffn {函数} hashlib.blake2b (data=b'@w{'}, *, digest_size=64, key=b'@w{'}, salt=b'@w{'}, person=b'@w{'}, fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)
@end deffn

@geindex blake2s() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2s}@anchor{650}
@deffn {函数} hashlib.blake2s (data=b'@w{'}, *, digest_size=32, key=b'@w{'}, salt=b'@w{'}, person=b'@w{'}, fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False, usedforsecurity=True)
@end deffn

这些函数返回用于计算 BLAKE2b 或 BLAKE2s 的相应的哈希对象。 它们接受下列可选通用形参:


@itemize *

@item 
@emph{data}: 要哈希的初始数据块，它必须为 @ref{6e9,,bytes-like object}。 它只能作为位置参数传入。

@item 
@emph{digest_size}: 以字节数表示的输出摘要大小。

@item 
@emph{key}: 用于密钥哈希的密钥（对于 BLAKE2b 最长 64 字节，对于 BLAKE2s 最长 32 字节）。

@item 
@emph{salt}: 用于随机哈希的盐值（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s 最长 8 字节）。

@item 
@emph{person}: 个性化字符串（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s 最长 8 字节）。
@end itemize

下表显示了常规参数的限制（以字节为单位）：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

Hash

@tab

目标长度

@tab

长度（键）

@tab

长度（盐）

@tab

长度（个人）

@item

BLAKE2b

@tab

64

@tab

64

@tab

16

@tab

16

@item

BLAKE2s

@tab

32

@tab

32

@tab

8

@tab

8

@end multitable


@cartouche
@quotation 注解 
BLAKE2 规格描述为盐值和个性化形参定义了固定的长度，但是为了方便起见，此实现接受指定在长度以内的任意大小的字节串。 如果形参长度小于指定值，它将以零值进行填充，因此举例来说，@code{b'salt'} 和 @code{b'salt\x00'} 为相同的值 (@emph{key} 的情况则并非如此。)
@end quotation
@end cartouche

如下面的模块 @ref{2047,,constants} 所描述，这些是可用的大小取值。

构造器函数还接受下列树形哈希形参:


@itemize *

@item 
@emph{fanout}: 扇出值 (0 至 255，如无限制即为 0，连续模式下为 1)。

@item 
@emph{depth}: 树的最大深度 (1 至 255，如无限制则为 255，连续模式下为 1)。

@item 
@emph{leaf_size}: 叶子的最大字节长度 (0 至 @code{2**32-1}，如无限制或在连续模式下则为 0)。

@item 
@emph{node_offset}: 节点的偏移量 (对于 BLAKE2b 为 0 至 @code{2**64-1}，对于 BLAKE2s 为 0 至 @code{2**48-1}，对于最多边的第一个叶子或在连续模式下则为 0)。

@item 
@emph{node_depth}: 节点深度 (0 至 255，对于叶子或在连续模式下则为 0)。

@item 
@emph{inner_size}: 内部摘要大小 (对于 BLAKE2b 为 0 至 64，对于 BLAKE2s 为 0 至 32，连续模式下则为 0)。

@item 
@emph{last_node}: 一个布尔值，指明所处理的节点是否为最后一个 (连续模式下则为 @cite{False})。
@end itemize


@float Figure

@image{python-figures/hashlib-blake2-tree,,,Explanation of tree mode parameters.,png}

@end float


请参阅 BLAKE2 规格描述@footnote{https://blake2.net/blake2_20130129.pdf} 第 2.10 节获取有关树形哈希的完整说明。

@node 常数<4>,示例<15>,创建哈希对象,BLAKE2
@anchor{library/hashlib constants}@anchor{2047}
@subsubsection 常数


@geindex blake2b.SALT_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2b SALT_SIZE}@anchor{2048}
@deffn {数据} blake2b.SALT_SIZE
@end deffn

@geindex blake2s.SALT_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2s SALT_SIZE}@anchor{2049}
@deffn {数据} blake2s.SALT_SIZE
@end deffn

盐值长度（构造器所接受的最大长度）。

@geindex blake2b.PERSON_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2b PERSON_SIZE}@anchor{204a}
@deffn {数据} blake2b.PERSON_SIZE
@end deffn

@geindex blake2s.PERSON_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2s PERSON_SIZE}@anchor{204b}
@deffn {数据} blake2s.PERSON_SIZE
@end deffn

个性化字符串长度（构造器所接受的最大长度）。

@geindex blake2b.MAX_KEY_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2b MAX_KEY_SIZE}@anchor{204c}
@deffn {数据} blake2b.MAX_KEY_SIZE
@end deffn

@geindex blake2s.MAX_KEY_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2s MAX_KEY_SIZE}@anchor{204d}
@deffn {数据} blake2s.MAX_KEY_SIZE
@end deffn

最大密钥长度。

@geindex blake2b.MAX_DIGEST_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2b MAX_DIGEST_SIZE}@anchor{204e}
@deffn {数据} blake2b.MAX_DIGEST_SIZE
@end deffn

@geindex blake2s.MAX_DIGEST_SIZE() (在 hashlib 模块中)
@anchor{library/hashlib hashlib blake2s MAX_DIGEST_SIZE}@anchor{204f}
@deffn {数据} blake2s.MAX_DIGEST_SIZE
@end deffn

哈希函数可输出的最大摘要长度。

@node 示例<15>,开发人员,常数<4>,BLAKE2
@anchor{library/hashlib examples}@anchor{2050}
@subsubsection 示例


@menu
* 简单哈希:: 
* 使用不同的摘要大小:: 
* 密钥哈希:: 
* 随机哈希:: 
* 个性化:: 
* 树形模式:: 

@end menu

@node 简单哈希,使用不同的摘要大小,,示例<15>
@anchor{library/hashlib simple-hashing}@anchor{2051}
@subsubsection 简单哈希


要计算某个数据的哈希值，你应该首先通过调用适当的构造器函数 (@ref{64f,,blake2b()} 或 @ref{650,,blake2s()}) 来构造一个哈希对象，然后通过在该对象上调用 @code{update()} 来更新目标数据，最后通过调用 @code{digest()} (或针对十六进制编码字符串的 @code{hexdigest()}) 来获取该对象的摘要。

@example
>>> from hashlib import blake2b
>>> h = blake2b()
>>> h.update(b'Hello world')
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

作为快捷方式，你可以直接以位置参数的形式向构造器传入第一个数据块来直接更新:

@example
>>> from hashlib import blake2b
>>> blake2b(b'Hello world').hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

你可以多次调用 @ref{203f,,hash.update()} 至你所想要的任意次数以迭代地更新哈希值:

@example
>>> from hashlib import blake2b
>>> items = [b'Hello', b' ', b'world']
>>> h = blake2b()
>>> for item in items:
...     h.update(item)
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'
@end example

@node 使用不同的摘要大小,密钥哈希,简单哈希,示例<15>
@anchor{library/hashlib using-different-digest-sizes}@anchor{2052}
@subsubsection 使用不同的摘要大小


BLAKE2 具有可配置的摘要大小，对于 BLAKE2b 最多 64 字节，对于 BLAKE2s 最多 32 字节。 例如，要使用 BLAKE2b 来替代 SHA-1 而不改变输出大小，我们可以让 BLAKE2b 产生 20 个字节的摘要:

@example
>>> from hashlib import blake2b
>>> h = blake2b(digest_size=20)
>>> h.update(b'Replacing SHA1 with the more secure function')
>>> h.hexdigest()
'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c'
>>> h.digest_size
20
>>> len(h.digest())
20
@end example

不同摘要大小的哈希对象具有完全不同的输出（较短哈希值 @emph{并非} 较长哈希值的前缀）；即使输出长度相同，BLAKE2b 和 BLAKE2s 也会产生不同的输出:

@example
>>> from hashlib import blake2b, blake2s
>>> blake2b(digest_size=10).hexdigest()
'6fa1d8fcfd719046d762'
>>> blake2b(digest_size=11).hexdigest()
'eb6ec15daf9546254f0809'
>>> blake2s(digest_size=10).hexdigest()
'1bf21a98c78a1c376ae9'
>>> blake2s(digest_size=11).hexdigest()
'567004bf96e4a25773ebf4'
@end example

@node 密钥哈希,随机哈希,使用不同的摘要大小,示例<15>
@anchor{library/hashlib keyed-hashing}@anchor{2053}
@subsubsection 密钥哈希


带密钥的哈希运算可被用于身份验证，作为 基于哈希的消息验证代码@footnote{https://en.wikipedia.org/wiki/HMAC} (HMAC) 的一种更快速更简单的替代。 BLAKE2 可被安全地用于前缀 MAC 模式，这是由于它从 BLAKE 继承而来的不可区分特性。

这个例子演示了如何使用密钥 @code{b'pseudorandom key'} 来为 @code{b'message data'} 获取一个（十六进制编码的）128 位验证代码:

@example
>>> from hashlib import blake2b
>>> h = blake2b(key=b'pseudorandom key', digest_size=16)
>>> h.update(b'message data')
>>> h.hexdigest()
'3d363ff7401e02026f4a4687d4863ced'
@end example

作为实际的例子，一个 Web 应用可为发送给用户的 cookies 进行对称签名，并在之后对其进行验证以确保它们没有被篡改:

@example
>>> from hashlib import blake2b
>>> from hmac import compare_digest
>>>
>>> SECRET_KEY = b'pseudorandomly generated server secret key'
>>> AUTH_SIZE = 16
>>>
>>> def sign(cookie):
...     h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)
...     h.update(cookie)
...     return h.hexdigest().encode('utf-8')
>>>
>>> def verify(cookie, sig):
...     good_sig = sign(cookie)
...     return compare_digest(good_sig, sig)
>>>
>>> cookie = b'user-alice'
>>> sig = sign(cookie)
>>> print("@{0@},@{1@}".format(cookie.decode('utf-8'), sig))
user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'
>>> verify(cookie, sig)
True
>>> verify(b'user-bob', sig)
False
>>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')
False
@end example

即使存在原生的密钥哈希模式，BLAKE2 也同样可在 @ref{8e,,hmac} 模块的 HMAC 构造过程中使用:

@example
>>> import hmac, hashlib
>>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
>>> m.update(b'message')
>>> m.hexdigest()
'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'
@end example

@node 随机哈希,个性化,密钥哈希,示例<15>
@anchor{library/hashlib randomized-hashing}@anchor{2054}
@subsubsection 随机哈希


用户可通过设置 @emph{salt} 形参来为哈希函数引入随机化。 随机哈希适用于防止对数字签名中使用的哈希函数进行碰撞攻击。

@quotation

随机哈希被设计用来处理当一方（消息准备者）要生成由另一方（消息签名者）进行签名的全部或部分消息的情况。 如果消息准备者能够找到加密哈希函数的碰撞现象（即两条消息产生相同的哈希值），则他们就可以准备将产生相同哈希值和数字签名但却具有不同结果的有意义的消息版本（例如向某个账户转入 $1,000,000 而不是 $10）。 加密哈希函数的设计都是以防碰撞性能为其主要目标之一的，但是当前针对加密哈希函数的集中攻击可能导致特定加密哈希函数所提供的防碰撞性能低于预期。 随机哈希为签名者提供了额外的保护，可以降低准备者在数字签名生成过程中使得两条或更多条消息最终产生相同哈希值的可能性 --- 即使为特定哈希函数找到碰撞现象是可行的。 但是，当消息的所有部分均由签名者准备时，使用随机哈希可能降低数字签名所提供的安全性。

(NIST SP-800-106 "数字签名的随机哈希"@footnote{https://csrc.nist.gov/publications/detail/sp/800-106/final})
@end quotation

在 BLAKE2 中，盐值会在初始化期间作为对哈希函数的一次性输入而不是对每个压缩函数的输入来处理。

@cartouche
@quotation 警告 
使用 BLAKE2 或任何其他通用加密哈希函数例如 SHA-256 进行 @emph{加盐哈希} (或纯哈希) 并不适用于哈希密码。 请参阅 BLAKE2 FAQ@footnote{https://blake2.net/#qa} 了解更多信息。
@end quotation
@end cartouche


@example
>>> import os
>>> from hashlib import blake2b
>>> msg = b'some message'
>>> # Calculate the first hash with a random salt.
>>> salt1 = os.urandom(blake2b.SALT_SIZE)
>>> h1 = blake2b(salt=salt1)
>>> h1.update(msg)
>>> # Calculate the second hash with a different random salt.
>>> salt2 = os.urandom(blake2b.SALT_SIZE)
>>> h2 = blake2b(salt=salt2)
>>> h2.update(msg)
>>> # The digests are different.
>>> h1.digest() != h2.digest()
True
@end example

@node 个性化,树形模式,随机哈希,示例<15>
@anchor{library/hashlib personalization}@anchor{2055}
@subsubsection 个性化


出于不同的目的强制让哈希函数为相同的输入生成不同的摘要有时也是有用的。 正如 Skein 哈希函数的作者所言:

@quotation

我们建议所有应用设计者慎重考虑这种做法；我们已看到有许多协议在协议的某一部分中计算出来的哈希值在另一个完全不同的部分中也可以被使用，因为两次哈希计算是针对类似或相关的数据进行的，这样攻击者可以强制应用为相同的输入生成哈希值。 个性化协议中所使用的每个哈希函数将有效地阻止这种类型的攻击。

(Skein 哈希函数族@footnote{http://www.skein-hash.info/sites/default/files/skein1.3.pdf}, p. 21)
@end quotation

BLAKE2 可通过向 @emph{person} 参数传入字节串来进行个性化:

@example
>>> from hashlib import blake2b
>>> FILES_HASH_PERSON = b'MyApp Files Hash'
>>> BLOCK_HASH_PERSON = b'MyApp Block Hash'
>>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'
>>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'
@end example

个性化配合密钥模式也可被用来从单个密钥派生出多个不同密钥。

@example
>>> from hashlib import blake2s
>>> from base64 import b64decode, b64encode
>>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=')
>>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest()
>>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest()
>>> print(b64encode(enc_key).decode('utf-8'))
rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=
>>> print(b64encode(mac_key).decode('utf-8'))
G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=
@end example

@node 树形模式,,个性化,示例<15>
@anchor{library/hashlib tree-mode}@anchor{2056}
@subsubsection 树形模式


以下是对包含两个叶子节点的最小树进行哈希的例子:

@example
  10
 /  \
00  01
@end example

这个例子使用 64 字节内部摘要，返回 32 字节最终摘要:

@example
>>> from hashlib import blake2b
>>>
>>> FANOUT = 2
>>> DEPTH = 2
>>> LEAF_SIZE = 4096
>>> INNER_SIZE = 64
>>>
>>> buf = bytearray(6000)
>>>
>>> # Left leaf
... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=0, last_node=False)
>>> # Right leaf
... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=1, node_depth=0, last_node=True)
>>> # Root node
... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=1, last_node=True)
>>> h10.update(h00.digest())
>>> h10.update(h01.digest())
>>> h10.hexdigest()
'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'
@end example

@node 开发人员,,示例<15>,BLAKE2
@anchor{library/hashlib credits}@anchor{2057}
@subsubsection 开发人员


BLAKE2@footnote{https://blake2.net} 是由 @emph{Jean-Philippe Aumasson}, @emph{Samuel Neves}, @emph{Zooko Wilcox-O'Hearn} 和 @emph{Christian Winnerlein} 基于 @emph{Jean-Philippe Aumasson}, @emph{Luca Henzen}, @emph{Willi Meier} 和 @emph{Raphael C.-W. Phan} 所创造的 SHA-3@footnote{https://en.wikipedia.org/wiki/NIST_hash_function_competition} 入围方案 BLAKE@footnote{https://131002.net/blake/} 进行设计的。

它使用的核心算法来自由 @emph{Daniel J. Bernstein} 所设计的 ChaCha@footnote{https://cr.yp.to/chacha.html} 加密。

stdlib 实现是基于 pyblake2@footnote{https://pythonhosted.org/pyblake2/} 模块的。 它由 @emph{Dmitry Chestnykh} 在 @emph{Samuel Neves} 所编写的 C 实现的基础上编写。 此文档拷贝自 pyblake2@footnote{https://pythonhosted.org/pyblake2/} 并由 @emph{Dmitry Chestnykh} 撰写。

C 代码由 @emph{Christian Heimes} 针对 Python 进行了部分的重写。

以下公共领域贡献同时适用于 C 哈希函数实现、扩展代码和本文档:

@quotation

在法律许可的范围内，作者已将此软件的全部版权以及关联和邻接权利贡献到全球公共领域。 此软件的发布不附带任何担保。

你应该已收到此软件附带的 CC0 公共领域专属证书的副本。 如果没有，请参阅 @indicateurl{https://creativecommons.org/publicdomain/zero/1.0/}。
@end quotation

根据创意分享公共领域贡献 1.0 通用规范，下列人士为此项目的开发提供了帮助或对公共领域的修改作出了贡献:


@itemize *

@item 
@emph{Alexandr Sokolovskiy}
@end itemize


@subsubheading 参见



@table @asis

@item 模块 @ref{8e,,hmac}

使用哈希运算来生成消息验证代码的模块。

@item 模块 @ref{d,,base64}

针对非二进制环境对二进制哈希值进行编辑的另一种方式。

@item @indicateurl{https://blake2.net}

BLAKE2 官方网站

@item @indicateurl{https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf}

有关安全哈希算法的 FIPS 180-2 出版物。

@item @indicateurl{https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms}

包含关于哪些算法存在已知问题以及对其使用所造成的影响的信息的 Wikipedia 文章。

@item @indicateurl{https://www.ietf.org/rfc/rfc2898.txt}

PKCS #5: 基于密码的加密规范描述 2.0 版
@end table


@node hmac --- 基于密钥的消息验证,secrets --- 生成管理密码的安全随机数,hashlib --- 安全哈希与消息摘要,加密服务
@anchor{library/hmac doc}@anchor{2058}@anchor{library/hmac hmac-keyed-hashing-for-message-authentication}@anchor{2059}@anchor{library/hmac module-hmac}@anchor{8e}
@subsection @code{hmac} --- 基于密钥的消息验证


@geindex hmac (模块)

@strong{源代码:} Lib/hmac.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/hmac.py}


__________________________________________________________________


此模块实现了 HMAC 算法，算法的描述参见 
@geindex RFC; RFC 2104
RFC 2104@footnote{https://tools.ietf.org/html/rfc2104.html}。

@geindex new() (在 hmac 模块中)
@anchor{library/hmac hmac new}@anchor{3f5}
@deffn {函数} hmac.new (key, msg=None, digestmod='@w{'})

返回一个新的 hmac 对象。 @emph{key} 是一个指定密钥的 bytes 或 bytearray 对象。 如果提供了 @emph{msg}，将会调用 @code{update(msg)} 方法。 @emph{digestmod} 为 HMAC 对象所用的摘要名称、摘要构造器或模块。 它可以是适用于 @ref{107a,,hashlib.new()} 的任何名称。 虽然该参数位置靠后，但它却是必须的。


在 3.4 版更改: 形参 @emph{key} 可以为 bytes 或 bytearray 对象。 形参 @emph{msg} 可以为 @ref{8c,,hashlib} 所支持的任意类型。 形参 @emph{digestmod} 可以为某种哈希算法的名称。



Deprecated since version 3.4, removed in version 3.8: MD5 作为 @emph{digestmod} 的隐式默认摘要已被弃用。 digestmod 形参现在是必须的。 请将其作为关键字参数传入以避免当你没有初始 msg 时将导致的麻烦。

@end deffn

@geindex digest() (在 hmac 模块中)
@anchor{library/hmac hmac digest}@anchor{49f}
@deffn {函数} hmac.digest (key, msg, digest)

基于给定密钥 @emph{key} 和 @emph{digest} 返回 @emph{msg} 的摘要。 此函数等价于 @code{HMAC(key, msg, digest).digest()}，但使用了优化的 C 或内联实现，对放入内存的消息能处理得更快。 形参 @emph{key}, @emph{msg} 和 @emph{digest} 具有与 @ref{3f5,,new()} 中相同的含义。

作为 CPython 的实现细节，优化的 C 实现仅当 @emph{digest} 为字符串并且是一个 OpenSSL 所支持的摘要算法的名称时才会被使用。


3.7 新版功能.

@end deffn

HMAC 对象具有下列方法:

@geindex update() (hmac.HMAC 方法)
@anchor{library/hmac hmac HMAC update}@anchor{94a}
@deffn {方法} HMAC.update (msg)

用 @emph{msg} 来更新 hmac 对象。 重复调用相当于单次调用并传入所有参数的拼接结果: @code{m.update(a); m.update(b)} 等价于 @code{m.update(a + b)}。


在 3.4 版更改: 形参 @emph{msg} 可以为 @ref{8c,,hashlib} 所支持的任何类型。

@end deffn

@geindex digest() (hmac.HMAC 方法)
@anchor{library/hmac hmac HMAC digest}@anchor{205a}
@deffn {方法} HMAC.digest ()

返回当前已传给 @ref{94a,,update()} 方法的字节串数据的摘要。 这个字节串数据的长度将与传给构造器的摘要的长度 @emph{digest_size} 相同。 它可以包含非 ASCII 的字节，包括 NUL 字节。

@cartouche
@quotation 警告 
在验证例程运行期间将 @ref{49f,,digest()} 的输出与外部提供的摘要进行比较时，建议使用 @ref{af3,,compare_digest()} 函数而不是 @code{==} 运算符以减少定时攻击防御力的不足。
@end quotation
@end cartouche
@end deffn

@geindex hexdigest() (hmac.HMAC 方法)
@anchor{library/hmac hmac HMAC hexdigest}@anchor{205b}
@deffn {方法} HMAC.hexdigest ()

类似于 @ref{49f,,digest()} 但摘要会以两倍长度字符串的形式返回，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安全地交换数据值。

@cartouche
@quotation 警告 
在验证例程运行期间将 @ref{205b,,hexdigest()} 的输出与外部提供的摘要进行比较时，建议使用 @ref{af3,,compare_digest()} 函数而不是 @code{==} 运算符以减少定时攻击防御力的不足。
@end quotation
@end cartouche
@end deffn

@geindex copy() (hmac.HMAC 方法)
@anchor{library/hmac hmac HMAC copy}@anchor{205c}
@deffn {方法} HMAC.copy ()

返回 hmac 对象的副本（“克隆）。 这可被用来高效地计算共享相同初始子串的数据的摘要。
@end deffn

hash 对象具有以下属性：

@geindex digest_size (hmac.HMAC 属性)
@anchor{library/hmac hmac HMAC digest_size}@anchor{94d}
@deffn {属性} HMAC.digest_size

以字节表示的结果 HMAC 摘要的大小。
@end deffn

@geindex block_size (hmac.HMAC 属性)
@anchor{library/hmac hmac HMAC block_size}@anchor{94b}
@deffn {属性} HMAC.block_size

以字节表示的哈希算法的内部块大小。


3.4 新版功能.

@end deffn

@geindex name (hmac.HMAC 属性)
@anchor{library/hmac hmac HMAC name}@anchor{94c}
@deffn {属性} HMAC.name

HMAC 的规范名称，总是为小写形式，例如 @code{hmac-md5}。


3.4 新版功能.

@end deffn


3.9 版后已移除: 未写入文档的属性 @code{HMAC.digest_cons}, @code{HMAC.inner} 和 @code{HMAC.outer} 属于内部实现细节，将在 Python 3.10 中被移除。


这个模块还提供了下列辅助函数:

@geindex compare_digest() (在 hmac 模块中)
@anchor{library/hmac hmac compare_digest}@anchor{af3}
@deffn {函数} hmac.compare_digest (a, b)

返回 @code{a == b}。 此函数使用一种经专门设计的方式通过避免基于内容的短路行为来防止定时分析，使得它适合处理密码。 @emph{a} 和 @emph{b} 必须为相同的类型：或者是 @ref{206,,str} (仅限 ASCII 字符，如 @ref{205b,,HMAC.hexdigest()} 的返回值)，或者是 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
如果 @emph{a} 和 @emph{b} 具有不同的长度，或者如果发生了错误，定时攻击在理论上可以获取有关 @emph{a} 和 @emph{b} 的类型和长度信息 — 但不能获取它们的值。
@end quotation
@end cartouche


3.3 新版功能.



在 3.9 版更改: 此函数在可能的情况下会在内部使用 OpenSSL 的 @code{CRYPTO_memcmp()}。

@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{8c,,hashlib}

提供安全哈希函数的 Python 模块。
@end table


@node secrets --- 生成管理密码的安全随机数,,hmac --- 基于密钥的消息验证,加密服务
@anchor{library/secrets doc}@anchor{205d}@anchor{library/secrets module-secrets}@anchor{e4}@anchor{library/secrets secrets-generate-secure-random-numbers-for-managing-secrets}@anchor{205e}
@subsection @code{secrets} --- 生成管理密码的安全随机数


@geindex secrets (模块)


3.6 新版功能.


@c from secrets import *
@c __name__ = '<doctest>'

@strong{源代码:} Lib/secrets.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/secrets.py}


__________________________________________________________________


@ref{e4,,secrets} 模块用于生成高度加密的随机数，适于管理密码、账户验证、安全凭据及机密数据。

最好用 @ref{e4,,secrets} 替代 @ref{dc,,random} 模块的默认伪随机数生成器，该生成器适用于建模和模拟，不宜用于安全与加密。


@subsubheading 参见


@geindex Python 提高建议; PEP 506
PEP 506@footnote{https://www.python.org/dev/peps/pep-0506}


@menu
* 随机数:: 
* 生成 Token:: 
* 其他功能:: 
* 应用技巧与最佳实践:: 

@end menu

@node 随机数,生成 Token,,secrets --- 生成管理密码的安全随机数
@anchor{library/secrets random-numbers}@anchor{205f}
@subsubsection 随机数


@ref{e4,,secrets} 模块是操作系统提供的最安全地随机性来源。

@geindex SystemRandom (secrets 中的类)
@anchor{library/secrets secrets SystemRandom}@anchor{2060}
@deffn {类} secrets.SystemRandom

用操作系统提供的最高质量源生成随机数的类。详见 @ref{1ca7,,random.SystemRandom}。
@end deffn

@geindex choice() (在 secrets 模块中)
@anchor{library/secrets secrets choice}@anchor{2061}
@deffn {函数} secrets.choice (sequence)

返回从非空序列中随机选取的元素。
@end deffn

@geindex randbelow() (在 secrets 模块中)
@anchor{library/secrets secrets randbelow}@anchor{2062}
@deffn {函数} secrets.randbelow (n)

返回 [0, @emph{n}) 范围内的随机整数。
@end deffn

@geindex randbits() (在 secrets 模块中)
@anchor{library/secrets secrets randbits}@anchor{2063}
@deffn {函数} secrets.randbits (k)

返回 @emph{k} 个随机比特位的整数。
@end deffn

@node 生成 Token,其他功能,随机数,secrets --- 生成管理密码的安全随机数
@anchor{library/secrets generating-tokens}@anchor{2064}
@subsubsection 生成 Token


@ref{e4,,secrets} 模块提供了生成安全 Token 的函数，适用于密码重置、密保 URL 等应用场景。

@geindex token_bytes() (在 secrets 模块中)
@anchor{library/secrets secrets token_bytes}@anchor{1cac}
@deffn {函数} secrets.token_bytes ([nbytes=None])

返回含 @emph{nbytes} 个字节的随机字节字符串。如果未提供 @emph{nbytes}，或*nbytes* 为 @code{None}，则使用合理的默认值。

@example
>>> token_bytes(16)  
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
@end example
@end deffn

@geindex token_hex() (在 secrets 模块中)
@anchor{library/secrets secrets token_hex}@anchor{2065}
@deffn {函数} secrets.token_hex ([nbytes=None])

返回十六进制随机文本字符串。字符串有 @emph{nbytes} 个随机字节，每个字节转换为两个十六进制数码。未提供 @emph{nbytes} 或为 @code{None} 时，则使用合理的默认值。

@example
>>> token_hex(16)  
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
@end example
@end deffn

@geindex token_urlsafe() (在 secrets 模块中)
@anchor{library/secrets secrets token_urlsafe}@anchor{2066}
@deffn {函数} secrets.token_urlsafe ([nbytes=None])

返回安全的 URL 随机文本字符串，包含 @emph{nbytes} 个随机字节。文本用 Base64 编码，平均来说，每个字节对应 1.3 个结果字符。未提供 @emph{nbytes} 或为 @code{None} 时，则使用合理的默认值。

@example
>>> token_urlsafe(16)  
'Drmhze6EPcv0fN_81Bj-nA'
@end example
@end deffn

@menu
* Token 应当使用多少个字节？:: 

@end menu

@node Token 应当使用多少个字节？,,,生成 Token
@anchor{library/secrets how-many-bytes-should-tokens-use}@anchor{2067}
@subsubsection Token 应当使用多少个字节？


为了在面对 暴力攻击@footnote{https://en.wikipedia.org/wiki/Brute-force_attack} 时保证安全，Token 的随机性必须足够高。随着计算机推衍能力的不断提升，随机性的安全标准也要不断提高。比如 2015 年，32 字节（256 位）的随机性对于 @ref{e4,,secrets} 模块的典型用例就已经足够了。

要自行管理 Token 长度的用户，可以通过为 @code{token_*} 函数指定 @ref{205,,int} 参数显式指定 Token 要使用多大的随机性。该参数以字节数表示随机性大小。

反之，如果未提供参数，或参数为 @code{None}，则 @code{token_*} 函数将使用合理的默认值。

@cartouche
@quotation 注解 
该默认值随时可能会改变，比如，版本更新的时候。
@end quotation
@end cartouche

@node 其他功能,应用技巧与最佳实践,生成 Token,secrets --- 生成管理密码的安全随机数
@anchor{library/secrets other-functions}@anchor{2068}
@subsubsection 其他功能


@geindex compare_digest() (在 secrets 模块中)
@anchor{library/secrets secrets compare_digest}@anchor{2069}
@deffn {函数} secrets.compare_digest (a, b)

字符串 @emph{a} 与 @emph{b} 相等则返回 @code{True}，否则返回 @code{False}，这种方式可降低 定时攻击@footnote{https://codahale.com/a-lesson-in-timing-attacks/} 的风险。详见 @ref{af3,,hmac.compare_digest()}。
@end deffn

@node 应用技巧与最佳实践,,其他功能,secrets --- 生成管理密码的安全随机数
@anchor{library/secrets recipes-and-best-practices}@anchor{206a}
@subsubsection 应用技巧与最佳实践


本节展示了一些使用 @ref{e4,,secrets} 管理基本安全级别的应用技巧和最佳实践。

生成长度为八个字符的字母数字密码：

@example
import string
import secrets
alphabet = string.ascii_letters + string.digits
password = '@w{'}.join(secrets.choice(alphabet) for i in range(8))
@end example

@cartouche
@quotation 注解 
应用程序不能 以可恢复的格式存储密码@footnote{http://cwe.mitre.org/data/definitions/257.html}，无论是用纯文本还是加密。 它们应当使用高加密强度的单向（不可恢复）哈希函数来加盐并生成哈希值。
@end quotation
@end cartouche

生成长度为十个字符的字母数字密码，包含至少一个小写字母，至少一个大写字母以及至少三个数字：

@example
import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
    password = '@w{'}.join(secrets.choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and sum(c.isdigit() for c in password) >= 3):
        break
@end example

生成 XKCD 风格的密码串@footnote{https://xkcd.com/936/}：

@example
import secrets
# On standard Linux systems, use a convenient dictionary file.
# Other platforms may need to provide their own word-list.
with open('/usr/share/dict/words') as f:
    words = [word.strip() for word in f]
    password = ' '.join(secrets.choice(words) for i in range(4))
@end example

生成临时密保 URL，包含密码恢复应用的安全 Token：

@example
import secrets
url = 'https://example.com/reset=' + secrets.token_urlsafe()
@end example

@c # This modeline must appear within the last ten lines of the file.
@c kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;

@node 通用操作系统服务,并发执行,加密服务,Python 标准库
@anchor{library/allos doc}@anchor{206b}@anchor{library/allos allos}@anchor{206c}@anchor{library/allos generic-operating-system-services}@anchor{206d}
@section 通用操作系统服务


本章中描述的各模块提供了在（几乎）所有的操作系统上可用的操作系统特性的接口，例如文件和时钟。这些接口通常以 Unix 或 C 接口为参照对象设计，不过在大多数其他系统上也可用。这里有一个概述：

@menu
* os: os --- 多种操作系统接口. 多种操作系统接口
* io: io --- 处理流的核心工具. 处理流的核心工具
* time: time --- 时间的访问和转换. 时间的访问和转换
* argparse: argparse --- 命令行选项、参数和子命令解析器. 命令行选项、参数和子命令解析器
* getopt: getopt --- C 风格的命令行选项解析器. C 风格的命令行选项解析器
* logging: logging --- Python 的日志记录工具. Python 的日志记录工具
* logging.config: logging config --- 日志记录配置. 日志记录配置
* logging.handlers: logging handlers --- 日志处理程序. 日志处理程序
* getpass: getpass --- 便携式密码输入工具. 便携式密码输入工具
* curses: curses --- 终端字符单元显示的处理. 终端字符单元显示的处理
* curses.textpad: curses textpad --- 用于 curses 程序的文本输入控件. 用于 curses 程序的文本输入控件
* curses.ascii: curses ascii --- 用于 ASCII 字符的工具. 用于 ASCII 字符的工具
* curses.panel: curses panel --- curses 的面板栈扩展. curses 的面板栈扩展
* platform: platform --- 获取底层平台的标识数据. 获取底层平台的标识数据
* errno: errno --- 标准 errno 系统符号. 标准 errno 系统符号
* ctypes: ctypes --- Python 的外部函数库. Python 的外部函数库

@end menu

@node os --- 多种操作系统接口,io --- 处理流的核心工具,,通用操作系统服务
@anchor{library/os doc}@anchor{206e}@anchor{library/os module-os}@anchor{c4}@anchor{library/os os-miscellaneous-operating-system-interfaces}@anchor{206f}
@subsection @code{os} --- 多种操作系统接口


@geindex os (模块)

@strong{源代码：} Lib/os.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/os.py}


__________________________________________________________________


本模块提供了一种使用与操作系统相关的功能的便捷式途径。 如果你只是想读写一个文件，请参阅 @ref{16f,,open()}，如果你想操作文件路径，请参阅 @ref{c5,,os.path} 模块，如果你想读取通过命令行给出的所有文件中的所有行，请参阅 @ref{7e,,fileinput} 模块。 为了创建临时文件和目录，请参阅 @ref{103,,tempfile} 模块，对于高级文件和目录处理，请参阅 @ref{e9,,shutil} 模块。

关于这些函数的可用性的说明：


@itemize *

@item 
Python中所有依赖于操作系统的内置模块的设计都是这样，只要不同的操作系统某一相同的功能可用，它就使用相同的接口。例如，函数 @code{os.stat(path)} 以相同的格式返回关于 @emph{path} 的状态信息（该格式源于 POSIX 接口）。

@item 
特定于某一操作系统的扩展通过操作 @ref{c4,,os} 模块也是可用的，但是使用它们当然是对可移植性的一种威胁。

@item 
所有接受路径或文件名的函数都同时支持字节串和字符串对象，并在返回路径或文件名时使用相应类型的对象作为结果。

@item 
在 VxWorks 系统上，os.fork, os.execv 和 os.spawn*p* 不被支持。
@end itemize

@cartouche
@quotation 注解 
如果使用无效或无法访问的文件名与路径，或者其他类型正确但操作系统不接受的参数，此模块的所有函数都抛出 @ref{30b,,OSError} （或者它的子类）。
@end quotation
@end cartouche

@geindex error
@anchor{library/os os error}@anchor{2070}
@deffn {例外} os.error

内建的 @ref{30b,,OSError} 异常的一个别名。
@end deffn

@geindex name() (在 os 模块中)
@anchor{library/os os name}@anchor{2071}
@deffn {数据} os.name

导入的依赖特定操作系统的模块的名称。以下名称目前已注册: @code{'posix'}, @code{'nt'}, @code{'java'}.


@subsubheading 参见


@ref{3db,,sys.platform} 有更详细的描述. @ref{b41,,os.uname()} 只给出系统提供的版本信息。

@ref{ce,,platform} 模块对系统的标识有更详细的检查。

@end deffn
@anchor{library/os os-filenames}@anchor{1fcf}
@menu
* 文件名，命令行参数，以及环境变量。:: 
* 进程参数:: 
* 创建文件对象:: 
* 文件描述符操作:: 
* 文件和目录:: 
* 进程管理:: 
* 调度器接口:: 
* 其他系统信息:: 
* 随机数: 随机数<2>. 

@end menu

@node 文件名，命令行参数，以及环境变量。,进程参数,,os --- 多种操作系统接口
@anchor{library/os file-names-command-line-arguments-and-environment-variables}@anchor{2072}@anchor{library/os filesystem-encoding}@anchor{2073}
@subsubsection 文件名，命令行参数，以及环境变量。


在 Python 中，使用字符串类型表示文件名、命令行参数和环境变量。 在某些系统上，在将这些字符串传递给操作系统之前，必须将这些字符串解码为字节。 Python 使用文件系统编码来执行此转换（请参阅 @ref{5f8,,sys.getfilesystemencoding()} ）。


在 3.1 版更改: 在某些系统上，使用文件系统编码进行转换可能会失败。 在这种情况下，Python 会使用 @ref{19d5,,代理转义编码错误处理器}，这意味着在解码时，不可解码的字节被 Unicode 字符 U+DCxx 替换，并且这些字节在编码时再次转换为原始字节。


文件系统编码必须保证成功解码小于 128 的所有字节。如果文件系统编码无法提供此保证， API 函数可能会引发 UnicodeErrors 。

@node 进程参数,创建文件对象,文件名，命令行参数，以及环境变量。,os --- 多种操作系统接口
@anchor{library/os os-procinfo}@anchor{2074}@anchor{library/os process-parameters}@anchor{2075}
@subsubsection 进程参数


这些函数和数据项提供了操作当前进程和用户的信息。

@geindex ctermid() (在 os 模块中)
@anchor{library/os os ctermid}@anchor{2076}
@deffn {函数} os.ctermid ()

返回与进程控制终端对应的文件名。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex environ() (在 os 模块中)
@anchor{library/os os environ}@anchor{c12}
@deffn {数据} os.environ

一个 @ref{c14,,mapping} 对象，其中键值是代表进程环境的字符串。 例如，@code{environ['HOME']} 是你的主目录（在某些平台上）的路径名，相当于 C 中的 @code{getenv("HOME")}。

这个映射是在第一次导入 @ref{c4,,os} 模块时捕获的，通常作为 Python 启动时处理 @code{site.py} 的一部分。除了通过直接修改 @ref{c12,,os.environ} 之外，在此之后对环境所做的更改不会反映在 @ref{c12,,os.environ} 中。

该映射除了可以用于查询环境外，还能用于修改环境。当该映射被修改时，将自动调用 @ref{1ce,,putenv()}。

在Unix系统上，键和值会使用 @ref{5f8,,sys.getfilesystemencoding()} 和 @code{'surrogateescape'} 的错误处理。如果你想使用其他的编码，使用 @ref{c6e,,environb}。

@cartouche
@quotation 注解 
直接调用 @ref{1ce,,putenv()} 并不会影响 @ref{c12,,os.environ} ，所以推荐直接修改 @ref{c12,,os.environ} 。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
在某些平台上，包括 FreeBSD 和 macOS，设置 @code{environ} 可能导致内存泄漏。 请参阅 @code{putenv()} 的系统文档。
@end quotation
@end cartouche

可以删除映射中的元素来删除对应的环境变量。当从 @ref{c12,,os.environ} 删除元素时，以及调用 @code{pop()} 或 @code{clear()} 之一时，将自动调用 @ref{1cd,,unsetenv()}。


在 3.9 版更改: 已更新并支持了 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} 的合并 (@code{|}) 和更新 (@code{|=}) 运算符。

@end deffn

@geindex environb() (在 os 模块中)
@anchor{library/os os environb}@anchor{c6e}
@deffn {数据} os.environb

@ref{c12,,environ} 的字节版本：一个 @ref{c14,,mapping} 对象，其中键值都是 @ref{172,,bytes} 对象，代表进程环境。 @ref{c12,,environ} 和 @ref{c6e,,environb} 是同步的（修改 @ref{c6e,,environb} 会更新 @ref{c12,,environ}，反之亦然）。

只有在 @ref{c6c,,supports_bytes_environ} 为 @code{True} 的时候 @ref{c6e,,environb} 才是可用的。


3.2 新版功能.



在 3.9 版更改: 已更新并支持了 
@geindex Python 提高建议; PEP 584
PEP 584@footnote{https://www.python.org/dev/peps/pep-0584} 的合并 (@code{|}) 和更新 (@code{|=}) 运算符。

@end deffn


@deffn {函数} os.chdir (path)

@deffnx {函数} os.fchdir (fd)

@deffnx {函数} os.getcwd ()

以上函数请参阅 @ref{2077,,文件和目录} 。
@end deffn

@geindex fsencode() (在 os 模块中)
@anchor{library/os os fsencode}@anchor{5f2}
@deffn {函数} os.fsencode (filename)

将 @ref{47b,,路径类} @emph{filename} 编码为文件系统编码，使用 @code{'surrogateescape'} 错误回调方法，在 Windows 上会使用 @code{'strict'}，@ref{172,,bytes} 类型则原样返回。

@ref{5f1,,fsdecode()} 是此函数的逆向函数。


3.2 新版功能.



在 3.6 版更改: 增加对实现了 @ref{5ee,,os.PathLike} 接口的对象的支持。

@end deffn

@geindex fsdecode() (在 os 模块中)
@anchor{library/os os fsdecode}@anchor{5f1}
@deffn {函数} os.fsdecode (filename)

将 @ref{47b,,路径类} @emph{filename} 从文件系统编码方式解码，编码方式应使用的是 @code{'surrogateescape'} 错误回调方法，在 Windows 上应使用的是 @code{'strict'} 方法。@ref{206,,str} 字符串则原样返回。

@ref{5f2,,fsencode()} 是此函数的逆向函数。


3.2 新版功能.



在 3.6 版更改: 增加对实现了 @ref{5ee,,os.PathLike} 接口的对象的支持。

@end deffn

@geindex fspath() (在 os 模块中)
@anchor{library/os os fspath}@anchor{5f0}
@deffn {函数} os.fspath (path)

返回路径的文件系统表示。

如果传入的是 @ref{206,,str} 或 @ref{172,,bytes} 类型的字符串，将原样返回。否则 @ref{5ef,,__fspath__()} 将被调用，如果得到的是一个 @ref{206,,str} 或 @ref{172,,bytes} 类型的对象，那就返回这个值。其他所有情况则会抛出 @ref{1ff,,TypeError}  异常。


3.6 新版功能.

@end deffn

@geindex PathLike (os 中的类)
@anchor{library/os os PathLike}@anchor{5ee}
@deffn {类} os.PathLike

某些对象用于表示文件系统中的路径（如 @ref{236,,pathlib.PurePath} 对象），本类是这些对象的 @ref{c0e,,抽象基类}。


3.6 新版功能.


@geindex __fspath__() (os.PathLike 方法)
@anchor{library/os os PathLike __fspath__}@anchor{5ef}
@deffn {方法} abstractmethod __fspath__ ()

返回当前对象的文件系统表示。

这个方法只应该返回一个 @ref{206,,str} 字符串或 @ref{172,,bytes} 字节串，请优先选择 @ref{206,,str} 字符串。
@end deffn
@end deffn

@geindex getenv() (在 os 模块中)
@anchor{library/os os getenv}@anchor{2078}
@deffn {函数} os.getenv (key, default=None)

如果环境变量 @emph{key} 存在，则返回它的值；如果不存在，则返回 @emph{default} 。@emph{key} , @emph{default} 和结果都是字符串。注意，由于 @ref{2078,,getenv()} 使用了 @ref{c12,,os.environ} ，所以 @ref{2078,,getenv()} 的映射也同样在导入时被捕获，并且该函数可能无法反映未来的环境变化。

在Unix系统上，键和值会使用 @ref{5f8,,sys.getfilesystemencoding()} 和`@w{`}'surrogateescape'`@w{`} 错误处理进行解码。如果你想使用其他的编码，使用 @ref{c6d,,os.getenvb()}。

@ref{14c1,,可用性}: 大部分的Unix系统，Windows。
@end deffn

@geindex getenvb() (在 os 模块中)
@anchor{library/os os getenvb}@anchor{c6d}
@deffn {函数} os.getenvb (key, default=None)

如果环境变量 @emph{key} 存在，则返回它的值；如果不存在，则返回 @emph{default} 。@emph{key} , @emph{default} 和结果都是字节。注意，由于 @ref{c6d,,getenvb()} 使用了 @ref{c6e,,os.environb} ，所以 @ref{c6d,,getenvb()} 的映射也同样在导入时被捕获，并且该函数可能无法反映未来的环境变化。

@ref{c6d,,getenvb()} 仅在 @ref{c6c,,supports_bytes_environ} 为 @code{True} 时可用。

@ref{14c1,,可用性}: 大部分的Unix系统。


3.2 新版功能.

@end deffn

@geindex get_exec_path() (在 os 模块中)
@anchor{library/os os get_exec_path}@anchor{2079}
@deffn {函数} os.get_exec_path (env=None)

返回将用于搜索可执行文件的目录列表，与在外壳程序中启动一个进程时相似。指定的 @emph{env} 应为用于搜索 PATH 的环境变量字典。默认情况下，当 @emph{env} 为 @code{None} 时，将会使用 @ref{c12,,environ} 。


3.2 新版功能.

@end deffn

@geindex getegid() (在 os 模块中)
@anchor{library/os os getegid}@anchor{207a}
@deffn {函数} os.getegid ()

返回当前进程的有效组ID。对应当前进程执行文件的 "set id" 位。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex geteuid() (在 os 模块中)
@anchor{library/os os geteuid}@anchor{207b}
@deffn {函数} os.geteuid ()

@geindex user; effective id

返回当前进程的有效用户ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getgid() (在 os 模块中)
@anchor{library/os os getgid}@anchor{207c}
@deffn {函数} os.getgid ()

@geindex process; group

返回当前进程的实际组ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getgrouplist() (在 os 模块中)
@anchor{library/os os getgrouplist}@anchor{b3f}
@deffn {函数} os.getgrouplist (user, group)

Return list of group ids that @emph{user} belongs to. If @emph{group} is not in the
list, it is included; typically, @emph{group} is specified as the group ID
field from the password record for @emph{user}, because that group ID will
otherwise be potentially omitted.

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex getgroups() (在 os 模块中)
@anchor{library/os os getgroups}@anchor{207d}
@deffn {函数} os.getgroups ()

返回当前进程对应的组ID列表

@ref{14c1,,可用性}: Unix。

@cartouche
@quotation 注解 
在 macOS 中，@ref{207d,,getgroups()} 会和其他 Unix 平台有所不同。 如果 Python 解释器是在 @code{10.5} 或更早版本中部署的，则 @ref{207d,,getgroups()} 会返回与当前用户进程相关联的有效组 ID 列表；该列表受限于系统预定义的条目数量，通常为 16，并且在适当的权限下还可通过调用 @ref{207e,,setgroups()} 来修改。 如果是在高于 @code{10.5} 的版本中部署的，则  @ref{207d,,getgroups()} 会返回与进程的有效用户 ID 相关联的当前组访问列表；组访问列表可能会在进程的生命周期之内发生改变，它不会受对 @ref{207e,,setgroups()} 的调用影响，且其长度也不被限制为 16。 部署目标值 @code{MACOSX_DEPLOYMENT_TARGET} 可以通过 @ref{a4e,,sysconfig.get_config_var()} 来获取。
@end quotation
@end cartouche
@end deffn

@geindex getlogin() (在 os 模块中)
@anchor{library/os os getlogin}@anchor{207f}
@deffn {函数} os.getlogin ()

返回通过控制终端进程进行登录的用户名。在多数情况下，使用 @ref{2080,,getpass.getuser()} 会更有效，因为后者会通过检查环境变量 
@geindex LOGNAME
@geindex 环境变量; LOGNAME
@code{LOGNAME} 或 
@geindex USERNAME
@geindex 环境变量; USERNAME
@code{USERNAME} 来查找用户，再由 @code{pwd.getpwuid(os.getuid())[0]} 来获取当前用户 ID 的登录名。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex getpgid() (在 os 模块中)
@anchor{library/os os getpgid}@anchor{2081}
@deffn {函数} os.getpgid (pid)

根据进程id @emph{pid} 返回进程的组 ID 列表。如果 @emph{pid} 为 0，则返回当前进程的进程组 ID 列表

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getpgrp() (在 os 模块中)
@anchor{library/os os getpgrp}@anchor{2082}
@deffn {函数} os.getpgrp ()

@geindex process; group

返回当时进程组的ID

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getpid() (在 os 模块中)
@anchor{library/os os getpid}@anchor{2083}
@deffn {函数} os.getpid ()

@geindex process; id

返回当前进程ID
@end deffn

@geindex getppid() (在 os 模块中)
@anchor{library/os os getppid}@anchor{2084}
@deffn {函数} os.getppid ()

@geindex process; id of parent

返回父进程ID。当父进程已经结束，在Unix中返回的ID是初始进程(1)中的一个，在Windows中仍然是同一个进程ID，该进程ID有可能已经被进行进程所占用。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加WIndows的支持。

@end deffn

@geindex getpriority() (在 os 模块中)
@anchor{library/os os getpriority}@anchor{b2a}
@deffn {函数} os.getpriority (which, who)

@geindex process; scheduling priority

获取程序调度优先级。@emph{which} 参数值可以是 @ref{2085,,PRIO_PROCESS}，@ref{2086,,PRIO_PGRP}，或 @ref{2087,,PRIO_USER} 中的一个，@emph{who} 是相对于 @emph{which} (@ref{2085,,PRIO_PROCESS} 的进程标识符，@ref{2086,,PRIO_PGRP} 的进程组标识符和 @ref{2087,,PRIO_USER} 的用户ID)。当 @emph{who} 为 0 时（分别）表示调用的进程，调用进程的进程组或调用进程所属的真实用户 ID。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex PRIO_PROCESS() (在 os 模块中)
@geindex PRIO_PGRP() (在 os 模块中)
@geindex PRIO_USER() (在 os 模块中)
@anchor{library/os os PRIO_PROCESS}@anchor{2085}
@deffn {数据} os.PRIO_PROCESS
@anchor{library/os os PRIO_PGRP}@anchor{2086}
@deffnx {数据} os.PRIO_PGRP
@anchor{library/os os PRIO_USER}@anchor{2087}
@deffnx {数据} os.PRIO_USER

函数 @ref{b2a,,getpriority()} 和 @ref{b2b,,setpriority()} 的参数。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex getresuid() (在 os 模块中)
@anchor{library/os os getresuid}@anchor{d7b}
@deffn {函数} os.getresuid ()

返回一个由 (ruid, euid, suid) 所组成的元组，分别表示当前进程的真实用户ID，有效用户ID和甲暂存用户ID。

@ref{14c1,,可用性}: Unix。


3.2 新版功能.

@end deffn

@geindex getresgid() (在 os 模块中)
@anchor{library/os os getresgid}@anchor{d7a}
@deffn {函数} os.getresgid ()

返回一个由 (rgid, egid, sgid) 所组成的元组，分别表示当前进程的真实组ID，有效组ID和暂存组ID。

@ref{14c1,,可用性}: Unix。


3.2 新版功能.

@end deffn

@geindex getuid() (在 os 模块中)
@anchor{library/os os getuid}@anchor{2088}
@deffn {函数} os.getuid ()

@geindex user; id

返回当前进程的真实用户ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex initgroups() (在 os 模块中)
@anchor{library/os os initgroups}@anchor{d7e}
@deffn {函数} os.initgroups (username, gid)

调用系统 initgroups()，使用指定用户所在的所有值来初始化组访问列表，包括指定的组ID。

@ref{14c1,,可用性}: Unix。


3.2 新版功能.

@end deffn

@geindex putenv() (在 os 模块中)
@anchor{library/os os putenv}@anchor{1ce}
@deffn {函数} os.putenv (key, value)

@geindex environment variables; setting

将名为 @emph{key} 的环境变量值设置为 @emph{value}。该变量名修改会影响由 @ref{e8e,,os.system()}， @ref{3d3,,popen()} ，@ref{a4b,,fork()} 和 @ref{2089,,execv()} 发起的子进程。

对 @ref{c12,,os.environ} 中的项目的赋值会自动转化为对 @ref{1ce,,putenv()} 的相应调用；然而，对 @ref{1ce,,putenv()} 的调用并不更新 @ref{c12,,os.environ} ，所以实际上最好是赋值到 @ref{c12,,os.environ} 的项目。这也适用于 @ref{2078,,getenv()} 和 @ref{c6d,,getenvb()} ，它们分别使用 @ref{c12,,os.environ} 和 @ref{c6e,,os.environb} 在它们的实现中。

@cartouche
@quotation 注解 
在某些平台上，包括 FreeBSD 和 macOS，设置 @code{environ} 可能导致内存泄漏。 请参阅 @code{putenv()} 的系统文档。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{os.putenv}，附带参数 @code{key}, @code{value}。


在 3.9 版更改: 该函数现在总是可用。

@end deffn

@geindex setegid() (在 os 模块中)
@anchor{library/os os setegid}@anchor{208a}
@deffn {函数} os.setegid (egid)

设置当前进程的有效组ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex seteuid() (在 os 模块中)
@anchor{library/os os seteuid}@anchor{208b}
@deffn {函数} os.seteuid (euid)

设置当前进程的有效用户ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setgid() (在 os 模块中)
@anchor{library/os os setgid}@anchor{208c}
@deffn {函数} os.setgid (gid)

设置当前进程的组ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setgroups() (在 os 模块中)
@anchor{library/os os setgroups}@anchor{207e}
@deffn {函数} os.setgroups (groups)

将 @emph{group} 参数值设置为与当进程相关联的附加组ID列表。@emph{group} 参数必须为一个序列，每个元素应为每个组的数字ID。该操作通常只适用于超级用户。

@ref{14c1,,可用性}: Unix。

@cartouche
@quotation 注解 
在 macOS 中，@emph{groups} 的长度不能超过系统定义的最大有效组 ID 数量，通常为 16。 对于未返回与调用 setgroups() 产生的相同组列表的情况，请参阅 @ref{207d,,getgroups()} 的文档。
@end quotation
@end cartouche
@end deffn

@geindex setpgrp() (在 os 模块中)
@anchor{library/os os setpgrp}@anchor{208d}
@deffn {函数} os.setpgrp ()

根据已实现的版本（如果有）来调用系统 @code{setpgrp()} 或 @code{setpgrp(0, 0)} 。相关说明，请参考 Unix 手册。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setpgid() (在 os 模块中)
@anchor{library/os os setpgid}@anchor{208e}
@deffn {函数} os.setpgid (pid, pgrp)

使用系统调用 @code{setpgid()}，将 @emph{pid} 对应进程的组ID设置为 @emph{pgrp}。相关说明，请参考 Unix 手册。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setpriority() (在 os 模块中)
@anchor{library/os os setpriority}@anchor{b2b}
@deffn {函数} os.setpriority (which, who, priority)

@geindex process; scheduling priority

设置程序调度优先级。 @emph{which} 的值为 @ref{2085,,PRIO_PROCESS}, @ref{2086,,PRIO_PGRP} 或 @ref{2087,,PRIO_USER} 之一，而 @emph{who} 会相对于 @emph{which} (@ref{2085,,PRIO_PROCESS} 的进程标识符, @ref{2086,,PRIO_PGRP} 的进程组标识符和 @ref{2087,,PRIO_USER} 的用户 ID) 被解析。 @emph{who} 值为零 (分别) 表示调用进程，调用进程的进程组或调用进程的真实用户 ID。 @emph{priority} 是范围在 -20 至 19 的值。 默认优先级为 0；较小的优先级数值会更优先被调度。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex setregid() (在 os 模块中)
@anchor{library/os os setregid}@anchor{208f}
@deffn {函数} os.setregid (rgid, egid)

设置当前进程的真实和有效组ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setresgid() (在 os 模块中)
@anchor{library/os os setresgid}@anchor{d7c}
@deffn {函数} os.setresgid (rgid, egid, sgid)

设置当前进程的真实，有效和暂存组ID。

@ref{14c1,,可用性}: Unix。


3.2 新版功能.

@end deffn

@geindex setresuid() (在 os 模块中)
@anchor{library/os os setresuid}@anchor{d7d}
@deffn {函数} os.setresuid (ruid, euid, suid)

设置当前进程的真实，有效和暂存用户ID。

@ref{14c1,,可用性}: Unix。


3.2 新版功能.

@end deffn

@geindex setreuid() (在 os 模块中)
@anchor{library/os os setreuid}@anchor{2090}
@deffn {函数} os.setreuid (ruid, euid)

设置当前进程的真实和有效用户ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getsid() (在 os 模块中)
@anchor{library/os os getsid}@anchor{2091}
@deffn {函数} os.getsid (pid)

调用系统调用 @code{getsid()}。相关说明，请参考 Unix 手册。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setsid() (在 os 模块中)
@anchor{library/os os setsid}@anchor{1129}
@deffn {函数} os.setsid ()

使用系统调用 @code{getsid()}。相关说明，请参考 Unix 手册。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex setuid() (在 os 模块中)
@anchor{library/os os setuid}@anchor{2092}
@deffn {函数} os.setuid (uid)

@geindex user; id@comma{} setting

设置当前进程的用户ID。

@ref{14c1,,可用性}: Unix。
@end deffn

@c placed in this section since it relates to errno.... a little weak

@geindex strerror() (在 os 模块中)
@anchor{library/os os strerror}@anchor{2093}
@deffn {函数} os.strerror (code)

根据 @emph{code} 中的错误码返回错误消息。 在某些平台上当给出未知错误码时 @code{strerror()} 将返回 @code{NULL} 并会引发 @ref{16d,,ValueError}。
@end deffn

@geindex supports_bytes_environ() (在 os 模块中)
@anchor{library/os os supports_bytes_environ}@anchor{c6c}
@deffn {数据} os.supports_bytes_environ

如果操作系统上原生环境类型是字节型则为 @code{True} (例如在 Windows 上为 @code{False})。


3.2 新版功能.

@end deffn

@geindex umask() (在 os 模块中)
@anchor{library/os os umask}@anchor{2094}
@deffn {函数} os.umask (mask)

设定当前数值掩码并返回之前的掩码。
@end deffn

@geindex uname() (在 os 模块中)
@anchor{library/os os uname}@anchor{b41}
@deffn {函数} os.uname ()

@geindex gethostname() (in module socket)
@geindex gethostbyaddr() (in module socket)

返回当前操作系统的识别信息。返回值是一个有5个属性的对象：


@itemize *

@item 
@code{sysname} - 操作系统名

@item 
@code{nodename} - 机器在网络上的名称（需要先设定）

@item 
@code{release} - 操作系统发行信息

@item 
@code{version} - 操作系统版本信息

@item 
@code{machine} - 硬件标识符
@end itemize

为了向后兼容，该对象也是可迭代的，像是一个按照 @code{sysname}，@code{nodename}，@code{release}，@code{version}，和 @code{machine} 顺序组成的元组。

有些系统会将 @code{nodename} 截短为 8 个字符或截短至前缀部分；获取主机名的一个更好方式是 @ref{2095,,socket.gethostname()}  或甚至可以用 @code{socket.gethostbyaddr(socket.gethostname())}。

@ref{14c1,,可用性}: 较新的 Unix 版本。


在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象，同时具有命名的属性。

@end deffn

@geindex unsetenv() (在 os 模块中)
@anchor{library/os os unsetenv}@anchor{1cd}
@deffn {函数} os.unsetenv (key)

@geindex environment variables; deleting

取消设置（删除）名为 @emph{key} 的环境变量。变量名的改变会影响由 @ref{e8e,,os.system()}，@ref{3d3,,popen()}，@ref{a4b,,fork()} 和 @ref{2089,,execv()} 触发的子进程。

删除 @ref{c12,,os.environ} 中的项目会自动转化为对 @ref{1cd,,unsetenv()} 的相应调用；然而，对 @ref{1cd,,unsetenv()} 的调用并不更新 @ref{c12,,os.environ} ，所以实际上最好是删除 @ref{c12,,os.environ} 的项目。

引发一个 @ref{fec,,审计事件} @code{os.unsetenv}，附带参数 @code{key}。


在 3.9 版更改: 该函数现在总是可用，并且在 Windows 上也可用。

@end deffn

@node 创建文件对象,文件描述符操作,进程参数,os --- 多种操作系统接口
@anchor{library/os file-object-creation}@anchor{2096}@anchor{library/os os-newstreams}@anchor{2097}
@subsubsection 创建文件对象


这些函数创建新的 @ref{c1d,,file objects} 。（参见 @ref{762,,open()} 以获取打开文件描述符的相关信息。）

@geindex fdopen() (在 os 模块中)
@anchor{library/os os fdopen}@anchor{1593}
@deffn {函数} os.fdopen (fd, *args, **kwargs)

返回打开文件描述符 @emph{fd} 对应文件的对象。类似内建 @ref{16f,,open()} 函数，二者接受同样的参数。不同之处在于 @ref{1593,,fdopen()} 第一个参数应该为整数。
@end deffn

@node 文件描述符操作,文件和目录,创建文件对象,os --- 多种操作系统接口
@anchor{library/os file-descriptor-operations}@anchor{2098}@anchor{library/os os-fd-ops}@anchor{2099}
@subsubsection 文件描述符操作


这些函数对文件描述符所引用的 I/O 流进行操作。

文件描述符是一些小的整数，对应于当前进程所打开的文件。例如，标准输入的文件描述符通常是0，标准输出是1，标准错误是2。之后被进程打开的文件的文件描述符会被依次指定为3，4，5等。“文件描述符”这个词有点误导性，在 Unix 平台中套接字和管道也被文件描述符所引用。

当需要时，可以用 @ref{209a,,fileno()} 可以获得 @ref{c1d,,file object} 所对应的文件描述符。需要注意的是，直接使用文件描述符会绕过文件对象的方法，会忽略如数据内部缓冲等情况。

@geindex close() (在 os 模块中)
@anchor{library/os os close}@anchor{4e1}
@deffn {函数} os.close (fd)

关闭文件描述符 @emph{fd}。

@cartouche
@quotation 注解 
该功能适用于低级 I/O 操作，必须用于 @ref{762,,os.open()} 或 @ref{209b,,pipe()} 返回的文件描述符。若要关闭由内建函数 @ref{16f,,open()}、@ref{3d3,,popen()} 或 @ref{1593,,fdopen()} 返回的 "文件对象"，则应使用其相应的 @ref{1190,,close()} 方法。
@end quotation
@end cartouche
@end deffn

@geindex closerange() (在 os 模块中)
@anchor{library/os os closerange}@anchor{209c}
@deffn {函数} os.closerange (fd_low, fd_high)

关闭从 @emph{fd_low} （包括）到 @emph{fd_high} （排除）间的文件描述符，并忽略错误。类似（但快于）:

@example
for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass
@end example
@end deffn

@geindex copy_file_range() (在 os 模块中)
@anchor{library/os os copy_file_range}@anchor{209d}
@deffn {函数} os.copy_file_range (src, dst, count, offset_src=None, offset_dst=None)

从文件描述符 @emph{src} 复制 @emph{count} 字节，从偏移量 @emph{offset_src} 开始读取，到文件描述符 @emph{dst}，从偏移量 @emph{offset_dst} 开始写入。如果 @emph{offset_src} 为 None，则 @emph{src} 将从当前位置开始读取；@emph{offset_dst} 同理。@emph{src} 和 @emph{dst} 指向的文件必须处于相同的文件系统，否则将会抛出一个 @ref{1886,,errno} 被设为 @ref{209e,,errno.EXDEV} 的 @ref{30b,,OSError} 。

此复制的完成没有额外的从内核到用户空间再回到内核的数据转移花费。另外，一些文件系统可能实现额外的优化。完成复制就如同打开两个二进制文件一样。

返回值是复制的字节的数目。这可能低于需求的数目。

@ref{14c1,,Availability}: Linux kernel >= 4.5 或 glibc >= 2.27。


3.8 新版功能.

@end deffn

@geindex device_encoding() (在 os 模块中)
@anchor{library/os os device_encoding}@anchor{fb3}
@deffn {函数} os.device_encoding (fd)

如果连接到终端，则返回一个与 @emph{fd} 关联的设备描述字符，否则返回 @ref{204,,None}。
@end deffn

@geindex dup() (在 os 模块中)
@anchor{library/os os dup}@anchor{1132}
@deffn {函数} os.dup (fd)

返回一个文件描述符 @emph{fd} 的副本。该文件描述符的副本是 @ref{8f1,,不可继承的}。

在 Windows 中，当复制一个标准流（0: stdin, 1: stdout, 2: stderr）时，新的文件描述符是 @ref{8f1,,可继承的}。


在 3.4 版更改: 新的文件描述符现在是不可继承的。

@end deffn

@geindex dup2() (在 os 模块中)
@anchor{library/os os dup2}@anchor{4cd}
@deffn {函数} os.dup2 (fd, fd2, inheritable=True)

把文件描述符 @emph{fd} 复制为 @emph{fd2}，必要时先关闭后者。返回 @emph{fd2}。新的文件描述符默认是 @ref{8f1,,可继承的}，除非在 @emph{inheritable} 为 @code{False} 时，是不可继承的。


在 3.4 版更改: 添加可选参数 @emph{inheritable}。



在 3.7 版更改: 成功时返回 @emph{fd2}，以过去的版本中，总是返回 @code{None}。

@end deffn

@geindex fchmod() (在 os 模块中)
@anchor{library/os os fchmod}@anchor{759}
@deffn {函数} os.fchmod (fd, mode)

将 @emph{fd} 指定文件的权限状态修改为 @emph{mode}。可以参考 @ref{b18,,chmod()} 中列出 @emph{mode} 的可用值。从Python 3.3开始，这相当于 @code{os.chmod(fd, mode)}。

引发一个 @ref{fec,,审计事件} @code{os.chmod}，附带参数 @code{path}、@code{mode}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex fchown() (在 os 模块中)
@anchor{library/os os fchown}@anchor{75a}
@deffn {函数} os.fchown (fd, uid, gid)

分别将 @emph{fd} 指定文件的所有者和组 ID 修改为 @emph{uid} 和 @emph{gid} 的值。若不想变更其中的某个 ID，可将相应值设为 -1。参考  @ref{b19,,chown()}。从 Python 3.3 开始，这相当于 @code{os.chown(fd, uid, gid)}。

引发一个 @ref{fec,,审计事件} @code{os.chown}，附带参数 @code{path}、@code{uid}、@code{gid}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex fdatasync() (在 os 模块中)
@anchor{library/os os fdatasync}@anchor{75b}
@deffn {函数} os.fdatasync (fd)

强制将文件描述符 @emph{fd} 指定文件写入磁盘。不强制更新元数据。

@ref{14c1,,可用性}: Unix。

@cartouche
@quotation 注解 
该功能在 MacOS 中不可用。
@end quotation
@end cartouche
@end deffn

@geindex fpathconf() (在 os 模块中)
@anchor{library/os os fpathconf}@anchor{209f}
@deffn {函数} os.fpathconf (fd, name)

返回与打开的文件有关的系统配置信息。@emph{name} 指定要查找的配置名称，它可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。当前操作系统已定义的名称在 @code{pathconf_names} 字典中给出。对于未包含在该映射中的配置名称，也可以传递一个整数作为 @emph{name}。

如果 @emph{name} 是一个字符串且不是已定义的名称，将抛出 @ref{16d,,ValueError} 异常。如果当前系统不支持 @emph{name} 指定的配置名称，即使该名称存在于 @code{pathconf_names}，也会抛出 @ref{30b,,OSError} 异常，错误码为 @ref{114d,,errno.EINVAL}。

从 Python 3.3 起，此功能等价于 @code{os.pathconf(fd, name)}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex fstat() (在 os 模块中)
@anchor{library/os os fstat}@anchor{75c}
@deffn {函数} os.fstat (fd)

获取文件描述符 @emph{fd} 的状态. 返回一个 @ref{1208,,stat_result} 对象。

从 Python 3.3 起，此功能等价于 @code{os.stat(fd)}。


@subsubheading 参见


@ref{328,,stat()} 函数。

@end deffn

@geindex fstatvfs() (在 os 模块中)
@anchor{library/os os fstatvfs}@anchor{75d}
@deffn {函数} os.fstatvfs (fd)

返回文件系统的信息，该文件系统是文件描述符 @emph{fd} 指向的文件所在的文件系统，与 @ref{b27,,statvfs()} 一样。从 Python 3.3 开始，它等效于 @code{os.statvfs(fd)}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex fsync() (在 os 模块中)
@anchor{library/os os fsync}@anchor{75e}
@deffn {函数} os.fsync (fd)

强制将文件描述符 @emph{fd} 指向的文件写入磁盘。在 Unix，这将调用原生 @code{fsync()} 函数；在 Windows，则是 MS @code{_commit()} 函数。

如果要写入的是缓冲区内的 Python @ref{c1d,,文件对象} @emph{f}，请先执行 @code{f.flush()}，然后执行 @code{os.fsync(f.fileno())}，以确保与 @emph{f} 关联的所有内部缓冲区都写入磁盘。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex ftruncate() (在 os 模块中)
@anchor{library/os os ftruncate}@anchor{75f}
@deffn {函数} os.ftruncate (fd, length)

截断文件描述符 @emph{fd} 指向的文件，以使其最大为 @emph{length} 字节。从 Python 3.3 开始，它等效于 @code{os.truncate(fd, length)}。

引发一个 @ref{fec,,审计事件} @code{os.truncate}，附带参数 @code{fd}, @code{length}。

@ref{14c1,,可用性}: Unix, Windows。


在 3.5 版更改: 添加了 Windows 支持

@end deffn

@geindex get_blocking() (在 os 模块中)
@anchor{library/os os get_blocking}@anchor{81a}
@deffn {函数} os.get_blocking (fd)

获取文件描述符的阻塞模式：如果设置了 @ref{81c,,O_NONBLOCK} 标志位，返回 @code{False}，如果该标志位被清除，返回 @code{True}。

参见 @ref{81b,,set_blocking()} 和 @ref{20a0,,socket.socket.setblocking()}。

@ref{14c1,,可用性}: Unix。


3.5 新版功能.

@end deffn

@geindex isatty() (在 os 模块中)
@anchor{library/os os isatty}@anchor{fb2}
@deffn {函数} os.isatty (fd)

如果文件描述符 @emph{fd} 打开且已连接至 tty 设备（或类 tty 设备），返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex lockf() (在 os 模块中)
@anchor{library/os os lockf}@anchor{b3e}
@deffn {函数} os.lockf (fd, cmd, len)

在打开的文件描述符上，使用、测试或删除 POSIX 锁。@emph{fd} 是一个打开的文件描述符。@emph{cmd} 指定要进行的操作，它们是 @ref{20a1,,F_LOCK}、@ref{20a2,,F_TLOCK}、@ref{20a3,,F_ULOCK} 或 @ref{20a4,,F_TEST} 中的一个。@emph{len} 指定哪部分文件需要锁定。

引发一个 @ref{fec,,审计事件} @code{os.lockf}，附带参数 @code{fd}、@code{cmd}、@code{len}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex F_LOCK() (在 os 模块中)
@geindex F_TLOCK() (在 os 模块中)
@geindex F_ULOCK() (在 os 模块中)
@geindex F_TEST() (在 os 模块中)
@anchor{library/os os F_LOCK}@anchor{20a1}
@deffn {数据} os.F_LOCK
@anchor{library/os os F_TLOCK}@anchor{20a2}
@deffnx {数据} os.F_TLOCK
@anchor{library/os os F_ULOCK}@anchor{20a3}
@deffnx {数据} os.F_ULOCK
@anchor{library/os os F_TEST}@anchor{20a4}
@deffnx {数据} os.F_TEST

标志位，用于指定 @ref{b3e,,lockf()} 进行哪一种操作。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex lseek() (在 os 模块中)
@anchor{library/os os lseek}@anchor{b42}
@deffn {函数} os.lseek (fd, pos, how)

将文件描述符 @emph{fd} 的当前位置设置为 @emph{pos}，位置的计算方式 @emph{how} 如下：设置为 @ref{e61,,SEEK_SET} 或 @code{0} 表示从文件开头计算，设置为 @ref{e62,,SEEK_CUR} 或 @code{1} 表示从文件当前位置计算，设置为 @ref{e63,,SEEK_END} 或 @code{2} 表示文件末尾计算。返回新指针位置，这个位置是从文件开头计算的，单位是字节。
@end deffn

@geindex SEEK_SET() (在 os 模块中)
@geindex SEEK_CUR() (在 os 模块中)
@geindex SEEK_END() (在 os 模块中)
@anchor{library/os os SEEK_SET}@anchor{e61}
@deffn {数据} os.SEEK_SET
@anchor{library/os os SEEK_CUR}@anchor{e62}
@deffnx {数据} os.SEEK_CUR
@anchor{library/os os SEEK_END}@anchor{e63}
@deffnx {数据} os.SEEK_END

@ref{b42,,lseek()} 函数的参数，它们的值分别为 0、1 和 2。


3.3 新版功能: 某些操作系统可能支持其他值，例如 @code{os.SEEK_HOLE} 或 @code{os.SEEK_DATA}。

@end deffn

@geindex open() (在 os 模块中)
@anchor{library/os os open}@anchor{762}
@deffn {函数} os.open (path, flags, mode=0o777, *, dir_fd=None)

打开文件 @emph{path}，根据 @emph{flags} 设置各种标志位，并根据 @emph{mode} 设置其权限状态。当计算 @emph{mode} 时，会首先根据当前 umask 值将部分权限去除。本方法返回新文件的描述符。新的文件描述符是 @ref{8f1,,不可继承} 的。

有关 flag 和 mode 取值的说明，请参见 C 运行时文档。标志位常量（如 @ref{20a5,,O_RDONLY} 和 @ref{20a6,,O_WRONLY}）在 @ref{c4,,os} 模块中定义。特别地，在 Windows 上需要添加 @ref{20a7,,O_BINARY} 才能以二进制模式打开文件。

本函数带有 @emph{dir_fd} 参数，支持 @ref{b14,,基于目录描述符的相对路径}。

引发一个 @ref{fec,,审计事件} @code{open}，附带参数 @code{path}、@code{mode}、@code{flags}。


在 3.4 版更改: 新的文件描述符现在是不可继承的。


@cartouche
@quotation 注解 
本函数适用于底层的 I/O。常规用途请使用内置函数 @ref{16f,,open()}，该函数的 @code{read()} 和 @code{write()} 方法（及其他方法）会返回 @ref{c1d,,文件对象}。要将文件描述符包装在文件对象中，请使用 @ref{1593,,fdopen()}。
@end quotation
@end cartouche


3.3 新版功能: @emph{dir_fd} 参数。



在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函数现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

以下常量是 @ref{762,,open()} 函数 @emph{flags} 参数的选项。可以用按位或运算符 @code{|} 将它们组合使用。部分常量并非在所有平台上都可用。有关其可用性和用法的说明，请参阅 @code{open(2)} 手册（Unix 上）或 MSDN@footnote{https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx} （Windows 上）。

@geindex O_RDONLY() (在 os 模块中)
@geindex O_WRONLY() (在 os 模块中)
@geindex O_RDWR() (在 os 模块中)
@geindex O_APPEND() (在 os 模块中)
@geindex O_CREAT() (在 os 模块中)
@geindex O_EXCL() (在 os 模块中)
@geindex O_TRUNC() (在 os 模块中)
@anchor{library/os os O_RDONLY}@anchor{20a5}
@deffn {数据} os.O_RDONLY
@anchor{library/os os O_WRONLY}@anchor{20a6}
@deffnx {数据} os.O_WRONLY
@anchor{library/os os O_RDWR}@anchor{20a8}
@deffnx {数据} os.O_RDWR
@anchor{library/os os O_APPEND}@anchor{20a9}
@deffnx {数据} os.O_APPEND
@anchor{library/os os O_CREAT}@anchor{20aa}
@deffnx {数据} os.O_CREAT
@anchor{library/os os O_EXCL}@anchor{1e10}
@deffnx {数据} os.O_EXCL
@anchor{library/os os O_TRUNC}@anchor{20ab}
@deffnx {数据} os.O_TRUNC

上述常量在 Unix 和 Windows 上均可用。
@end deffn

@geindex O_DSYNC() (在 os 模块中)
@geindex O_RSYNC() (在 os 模块中)
@geindex O_SYNC() (在 os 模块中)
@geindex O_NDELAY() (在 os 模块中)
@geindex O_NONBLOCK() (在 os 模块中)
@geindex O_NOCTTY() (在 os 模块中)
@geindex O_CLOEXEC() (在 os 模块中)
@anchor{library/os os O_DSYNC}@anchor{20ac}
@deffn {数据} os.O_DSYNC
@anchor{library/os os O_RSYNC}@anchor{20ad}
@deffnx {数据} os.O_RSYNC
@anchor{library/os os O_SYNC}@anchor{20ae}
@deffnx {数据} os.O_SYNC
@anchor{library/os os O_NDELAY}@anchor{20af}
@deffnx {数据} os.O_NDELAY
@anchor{library/os os O_NONBLOCK}@anchor{81c}
@deffnx {数据} os.O_NONBLOCK
@anchor{library/os os O_NOCTTY}@anchor{20b0}
@deffnx {数据} os.O_NOCTTY
@anchor{library/os os O_CLOEXEC}@anchor{aab}
@deffnx {数据} os.O_CLOEXEC

这个常数仅在 Unix 系统中可用。


在 3.3 版更改: 增加 @ref{aab,,O_CLOEXEC} 常量。

@end deffn

@geindex O_BINARY() (在 os 模块中)
@geindex O_NOINHERIT() (在 os 模块中)
@geindex O_SHORT_LIVED() (在 os 模块中)
@geindex O_TEMPORARY() (在 os 模块中)
@geindex O_RANDOM() (在 os 模块中)
@geindex O_SEQUENTIAL() (在 os 模块中)
@geindex O_TEXT() (在 os 模块中)
@anchor{library/os os O_BINARY}@anchor{20a7}
@deffn {数据} os.O_BINARY
@anchor{library/os os O_NOINHERIT}@anchor{20b1}
@deffnx {数据} os.O_NOINHERIT
@anchor{library/os os O_SHORT_LIVED}@anchor{20b2}
@deffnx {数据} os.O_SHORT_LIVED
@anchor{library/os os O_TEMPORARY}@anchor{20b3}
@deffnx {数据} os.O_TEMPORARY
@anchor{library/os os O_RANDOM}@anchor{20b4}
@deffnx {数据} os.O_RANDOM
@anchor{library/os os O_SEQUENTIAL}@anchor{20b5}
@deffnx {数据} os.O_SEQUENTIAL
@anchor{library/os os O_TEXT}@anchor{20b6}
@deffnx {数据} os.O_TEXT

这个常数仅在 Windows 系统中可用。
@end deffn

@geindex O_ASYNC() (在 os 模块中)
@geindex O_DIRECT() (在 os 模块中)
@geindex O_DIRECTORY() (在 os 模块中)
@geindex O_NOFOLLOW() (在 os 模块中)
@geindex O_NOATIME() (在 os 模块中)
@geindex O_PATH() (在 os 模块中)
@geindex O_TMPFILE() (在 os 模块中)
@geindex O_SHLOCK() (在 os 模块中)
@geindex O_EXLOCK() (在 os 模块中)
@anchor{library/os os O_ASYNC}@anchor{20b7}
@deffn {数据} os.O_ASYNC
@anchor{library/os os O_DIRECT}@anchor{20b8}
@deffnx {数据} os.O_DIRECT
@anchor{library/os os O_DIRECTORY}@anchor{20b9}
@deffnx {数据} os.O_DIRECTORY
@anchor{library/os os O_NOFOLLOW}@anchor{20ba}
@deffnx {数据} os.O_NOFOLLOW
@anchor{library/os os O_NOATIME}@anchor{20bb}
@deffnx {数据} os.O_NOATIME
@anchor{library/os os O_PATH}@anchor{977}
@deffnx {数据} os.O_PATH
@anchor{library/os os O_TMPFILE}@anchor{978}
@deffnx {数据} os.O_TMPFILE
@anchor{library/os os O_SHLOCK}@anchor{e64}
@deffnx {数据} os.O_SHLOCK
@anchor{library/os os O_EXLOCK}@anchor{e65}
@deffnx {数据} os.O_EXLOCK

上述常量是扩展常量，如果 C 库未定义它们，则不存在。


在 3.4 版更改: 在支持的系统上增加 @ref{977,,O_PATH}。增加 @ref{978,,O_TMPFILE}，仅在 Linux Kernel 3.11 或更高版本可用。

@end deffn

@geindex openpty() (在 os 模块中)
@anchor{library/os os openpty}@anchor{20bc}
@deffn {函数} os.openpty ()

@geindex 模块; pty

打开一对新的伪终端，返回一对文件描述符 @code{（主，从）}，分别为 pty 和 tty。新的文件描述符是 @ref{8f1,,不可继承} 的。对于（稍微）轻量一些的方法，请使用 @ref{d5,,pty} 模块。

@ref{14c1,,可用性}: 某些 Unix。


在 3.4 版更改: 新的文件描述符不再可继承。

@end deffn

@geindex pipe() (在 os 模块中)
@anchor{library/os os pipe}@anchor{209b}
@deffn {函数} os.pipe ()

创建一个管道，返回一对分别用于读取和写入的文件描述符 @code{(r, w)}。新的文件描述符是 @ref{8f1,,不可继承} 的。

@ref{14c1,,可用性}: Unix, Windows。


在 3.4 版更改: 新的文件描述符不再可继承。

@end deffn

@geindex pipe2() (在 os 模块中)
@anchor{library/os os pipe2}@anchor{b13}
@deffn {函数} os.pipe2 (flags)

创建带有 @emph{flags} 标志位的管道。可通过对以下一个或多个值进行“或”运算来构造这些 @emph{flags}：@ref{81c,,O_NONBLOCK}、@ref{aab,,O_CLOEXEC}。返回一对分别用于读取和写入的文件描述符 @code{(r, w)}。

@ref{14c1,,可用性}: 某些 Unix。


3.3 新版功能.

@end deffn

@geindex posix_fallocate() (在 os 模块中)
@anchor{library/os os posix_fallocate}@anchor{764}
@deffn {函数} os.posix_fallocate (fd, offset, len)

确保为 @emph{fd} 指向的文件分配了足够的磁盘空间，该空间从偏移量 @emph{offset} 开始，到 @emph{len} 字节为止。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex posix_fadvise() (在 os 模块中)
@anchor{library/os os posix_fadvise}@anchor{763}
@deffn {函数} os.posix_fadvise (fd, offset, len, advice)

声明即将以特定模式访问数据，使内核可以提前进行优化。数据范围是从 @emph{fd} 所指向文件的 @emph{offset} 开始，持续 @emph{len} 个字节。@emph{advice} 的取值是如下之一：@ref{20bd,,POSIX_FADV_NORMAL}, @ref{20be,,POSIX_FADV_SEQUENTIAL}, @ref{20bf,,POSIX_FADV_RANDOM}, @ref{20c0,,POSIX_FADV_NOREUSE}, @ref{20c1,,POSIX_FADV_WILLNEED} 或 @ref{20c2,,POSIX_FADV_DONTNEED}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex POSIX_FADV_NORMAL() (在 os 模块中)
@geindex POSIX_FADV_SEQUENTIAL() (在 os 模块中)
@geindex POSIX_FADV_RANDOM() (在 os 模块中)
@geindex POSIX_FADV_NOREUSE() (在 os 模块中)
@geindex POSIX_FADV_WILLNEED() (在 os 模块中)
@geindex POSIX_FADV_DONTNEED() (在 os 模块中)
@anchor{library/os os POSIX_FADV_NORMAL}@anchor{20bd}
@deffn {数据} os.POSIX_FADV_NORMAL
@anchor{library/os os POSIX_FADV_SEQUENTIAL}@anchor{20be}
@deffnx {数据} os.POSIX_FADV_SEQUENTIAL
@anchor{library/os os POSIX_FADV_RANDOM}@anchor{20bf}
@deffnx {数据} os.POSIX_FADV_RANDOM
@anchor{library/os os POSIX_FADV_NOREUSE}@anchor{20c0}
@deffnx {数据} os.POSIX_FADV_NOREUSE
@anchor{library/os os POSIX_FADV_WILLNEED}@anchor{20c1}
@deffnx {数据} os.POSIX_FADV_WILLNEED
@anchor{library/os os POSIX_FADV_DONTNEED}@anchor{20c2}
@deffnx {数据} os.POSIX_FADV_DONTNEED

用于 @ref{763,,posix_fadvise()} 的 @emph{advice} 参数的标志位，指定可能使用的访问模式。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex pread() (在 os 模块中)
@anchor{library/os os pread}@anchor{4c8}
@deffn {函数} os.pread (fd, n, offset)

从文件描述符 @emph{fd} 所指向文件的偏移位置 @emph{offset} 开始，读取至多 @emph{n} 个字节，而保持文件偏移量不变。

返回所读取字节的字节串 (bytestring)。如果到达了 @emph{fd} 指向的文件末尾，则返回空字节对象。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex preadv() (在 os 模块中)
@anchor{library/os os preadv}@anchor{4c6}
@deffn {函数} os.preadv (fd, buffers, offset, flags=0)

从文件描述符 @emph{fd} 所指向文件的偏移位置 @emph{offset} 开始，将数据读取至可变 @ref{6e9,,字节类对象} 缓冲区 @emph{buffers} 中，保持文件偏移量不变。将数据依次存放到每个缓冲区中，填满一个后继续存放到序列中的下一个缓冲区，来保存其余数据。

flags 参数可以由零个或多个标志位进行按位或运算来得到：


@itemize -

@item 
@ref{20c3,,RWF_HIPRI}

@item 
@ref{20c4,,RWF_NOWAIT}
@end itemize

返回实际读取的字节总数，该总数可以小于所有对象的总容量。

操作系统可能对允许使用的缓冲区数量有限制（使用 @ref{20c5,,sysconf()} 获取 @code{'SC_IOV_MAX'} 值）。

本方法结合了 @ref{4c7,,os.readv()} 和 @ref{4c8,,os.pread()} 的功能。

@ref{14c1,,可用性}：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版本，OpenBSD 2.7 或更高版本，AIX 7.1 或更高版本。使用标志位需要 Linux 4.6 或更高版本。


3.7 新版功能.

@end deffn

@geindex RWF_NOWAIT() (在 os 模块中)
@anchor{library/os os RWF_NOWAIT}@anchor{20c4}
@deffn {数据} os.RWF_NOWAIT

不要等待无法立即获得的数据。如果指定了此标志，那么当需要从后备存储器中读取数据，或等待文件锁时，系统调用将立即返回。

如果成功读取数据，则返回读取的字节数。如果未读取到数据，则返回 @code{-1}，并将错误码 errno 置为 @ref{1897,,errno.EAGAIN}。

@ref{14c1,,可用性}：Linux 4.14 或更高版本。


3.7 新版功能.

@end deffn

@geindex RWF_HIPRI() (在 os 模块中)
@anchor{library/os os RWF_HIPRI}@anchor{20c3}
@deffn {数据} os.RWF_HIPRI

高优先级读/写。允许基于块的文件系统对设备进行轮询，这样可以降低延迟，但可能会占用更多资源。

目前在 Linux 上，此功能仅在使用 @ref{20b8,,O_DIRECT} 标志打开的文件描述符上可用。

@ref{14c1,,可用性}：Linux 4.6 或更高版本。


3.7 新版功能.

@end deffn

@geindex pwrite() (在 os 模块中)
@anchor{library/os os pwrite}@anchor{4cb}
@deffn {函数} os.pwrite (fd, str, offset)

将 @emph{str} 中的字节串 (bytestring) 写入文件描述符 @emph{fd} 的偏移位置 @emph{offset} 处，保持文件偏移量不变。

返回实际写入的字节数。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex pwritev() (在 os 模块中)
@anchor{library/os os pwritev}@anchor{4c9}
@deffn {函数} os.pwritev (fd, buffers, offset, flags=0)

将缓冲区 @emph{buffers} 的内容写入文件描述符 @emph{fd} 的偏移位置 @emph{offset} 处，保持文件偏移量不变。缓冲区 @emph{buffers} 必须是由 @ref{6e9,,字节类对象} 组成的序列。缓冲区以数组顺序处理。先写入第一个缓冲区的全部内容，再写入第二个缓冲区，照此继续。

flags 参数可以由零个或多个标志位进行按位或运算来得到：


@itemize -

@item 
@ref{20c6,,RWF_DSYNC}

@item 
@ref{20c7,,RWF_SYNC}
@end itemize

返回实际写入的字节总数。

操作系统可能对允许使用的缓冲区数量有限制（使用 @ref{20c5,,sysconf()} 获取 @code{'SC_IOV_MAX'} 值）。

本方法结合了 @ref{4ca,,os.writev()} 和 @ref{4cb,,os.pwrite()} 的功能。

@ref{14c1,,可用性}：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版本，OpenBSD 2.7 或更高版本，AIX 7.1 或更高版本。使用标志位需要 Linux 4.7 或更高版本。


3.7 新版功能.

@end deffn

@geindex RWF_DSYNC() (在 os 模块中)
@anchor{library/os os RWF_DSYNC}@anchor{20c6}
@deffn {数据} os.RWF_DSYNC

提供立即写入功能，等效于 @ref{20ac,,O_DSYNC} @code{open(2)} 标志。该标志仅作用于系统调用写入的数据。

@ref{14c1,,可用性}：Linux 4.7 或更高版本。


3.7 新版功能.

@end deffn

@geindex RWF_SYNC() (在 os 模块中)
@anchor{library/os os RWF_SYNC}@anchor{20c7}
@deffn {数据} os.RWF_SYNC

提供立即写入功能，等效于 @ref{20ae,,O_SYNC} @code{open(2)} 标志。该标志仅作用于系统调用写入的数据。

@ref{14c1,,可用性}：Linux 4.7 或更高版本。


3.7 新版功能.

@end deffn

@geindex read() (在 os 模块中)
@anchor{library/os os read}@anchor{765}
@deffn {函数} os.read (fd, n)

从文件描述符 @emph{fd} 中读取至多 @emph{n} 个字节。

返回所读取字节的字节串 (bytestring)。如果到达了 @emph{fd} 指向的文件末尾，则返回空字节对象。

@cartouche
@quotation 注解 
该功能适用于低级 I/O 操作，必须用于 @ref{762,,os.open()} 或 @ref{209b,,pipe()} 返回的文件描述符。若要读取由内建函数 @ref{16f,,open()}、@ref{3d3,,popen()}、@ref{1593,,fdopen()} 或 @ref{427,,sys.stdin} 返回的 "文件对象"，则应使用其相应的 @code{read()} 或 @code{readline()} 方法。
@end quotation
@end cartouche


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函数现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex sendfile() (在 os 模块中)
@anchor{library/os os sendfile}@anchor{46a}
@deffn {函数} os.sendfile (out_fd, in_fd, offset, count)

@deffnx {函数} os.sendfile (out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)

将文件描述符 @emph{in_fd} 中的 @emph{count} 字节复制到文件描述符 @emph{out_fd} 的偏移位置 @emph{offset} 处。返回复制的字节数，如果到达 EOF，返回 @code{0}。

定义了 @ref{46a,,sendfile()} 的所有平台均支持第一种函数用法。

在 Linux 上，将 @emph{offset} 设置为 @code{None}，则从 @emph{in_fd} 的当前位置开始读取，并更新 @emph{in_fd} 的位置。

第二种情况可以被用于 macOS 和 FreeBSD，其中 @emph{headers} 和 @emph{trailers} 是任意的缓冲区序列，它们会在写入来自 @emph{in_fd} 的数据之前被写入。 它的返回内容与第一种情况相同。

在 macOS 和 FreeBSD 上，传入 @code{0} 值作为 @emph{count} 将指定持续发送直至到达 @emph{in_fd} 的末尾。

所有平台都支持将套接字作为 @emph{out_fd} 文件描述符，有些平台也支持其他类型（如常规文件或管道）。

跨平台应用程序不应使用 @emph{headers}、@emph{trailers} 和 @emph{flags} 参数。

@ref{14c1,,可用性}: Unix。

@cartouche
@quotation 注解 
有关 @ref{46a,,sendfile()} 的高级封装，参见 @ref{843,,socket.socket.sendfile()}。
@end quotation
@end cartouche


3.3 新版功能.



在 3.9 版更改: @emph{out} 和 @emph{in} 参数被重命名为 @emph{out_fd} 和 @emph{in_fd}。

@end deffn

@geindex set_blocking() (在 os 模块中)
@anchor{library/os os set_blocking}@anchor{81b}
@deffn {函数} os.set_blocking (fd, blocking)

设置指定文件描述符的阻塞模式：如果 blocking 为 @code{False}，则为该描述符设置 @ref{81c,,O_NONBLOCK} 标志位，反之则清除该标志位。

参见 @ref{81a,,get_blocking()} 和 @ref{20a0,,socket.socket.setblocking()}。

@ref{14c1,,可用性}: Unix。


3.5 新版功能.

@end deffn

@geindex SF_NODISKIO() (在 os 模块中)
@geindex SF_MNOWAIT() (在 os 模块中)
@geindex SF_SYNC() (在 os 模块中)
@anchor{library/os os SF_NODISKIO}@anchor{20c8}
@deffn {数据} os.SF_NODISKIO
@anchor{library/os os SF_MNOWAIT}@anchor{20c9}
@deffnx {数据} os.SF_MNOWAIT
@anchor{library/os os SF_SYNC}@anchor{20ca}
@deffnx {数据} os.SF_SYNC

@ref{46a,,sendfile()} 函数的参数（假设当前实现支持这些参数）。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex readv() (在 os 模块中)
@anchor{library/os os readv}@anchor{4c7}
@deffn {函数} os.readv (fd, buffers)

从文件描述符 @emph{fd} 将数据读取至多个可变的 @ref{6e9,,字节类对象} 缓冲区 @emph{buffers} 中。将数据依次存放到每个缓冲区中，填满一个后继续存放到序列中的下一个缓冲区，来保存其余数据。

返回实际读取的字节总数，该总数可以小于所有对象的总容量。

操作系统可能对允许使用的缓冲区数量有限制（使用 @ref{20c5,,sysconf()} 获取 @code{'SC_IOV_MAX'} 值）。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex tcgetpgrp() (在 os 模块中)
@anchor{library/os os tcgetpgrp}@anchor{20cb}
@deffn {函数} os.tcgetpgrp (fd)

返回与 @emph{fd} 指定的终端相关联的进程组（@emph{fd} 是由 @ref{762,,os.open()} 返回的已打开的文件描述符）。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex tcsetpgrp() (在 os 模块中)
@anchor{library/os os tcsetpgrp}@anchor{20cc}
@deffn {函数} os.tcsetpgrp (fd, pg)

设置与 @emph{fd} 指定的终端相关联的进程组为 @emph{pg*（*fd} 是由 @ref{762,,os.open()} 返回的已打开的文件描述符）。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex ttyname() (在 os 模块中)
@anchor{library/os os ttyname}@anchor{20cd}
@deffn {函数} os.ttyname (fd)

返回一个字符串，该字符串表示与文件描述符 @emph{fd} 关联的终端。如果 @emph{fd} 没有与终端关联，则抛出异常。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex write() (在 os 模块中)
@anchor{library/os os write}@anchor{76b}
@deffn {函数} os.write (fd, str)

将 @emph{str} 中的字节串 (bytestring) 写入文件描述符 @emph{fd}。

返回实际写入的字节数。

@cartouche
@quotation 注解 
该功能适用于低级 I/O 操作，必须用于 @ref{762,,os.open()} 或 @ref{209b,,pipe()} 返回的文件描述符。若要写入由内建函数 @ref{16f,,open()}、@ref{3d3,,popen()}、@ref{1593,,fdopen()}、@ref{428,,sys.stdout} 或 @ref{1eb,,sys.stderr} 返回的 "文件对象"，则应使用其相应的 @code{write()} 方法。
@end quotation
@end cartouche


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函数现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex writev() (在 os 模块中)
@anchor{library/os os writev}@anchor{4ca}
@deffn {函数} os.writev (fd, buffers)

将缓冲区 @emph{buffers} 的内容写入文件描述符 @emph{fd}。缓冲区 @emph{buffers} 必须是由 @ref{6e9,,字节类对象} 组成的序列。缓冲区以数组顺序处理。先写入第一个缓冲区的全部内容，再写入第二个缓冲区，照此继续。

返回实际写入的字节总数。

操作系统可能对允许使用的缓冲区数量有限制（使用 @ref{20c5,,sysconf()} 获取 @code{'SC_IOV_MAX'} 值）。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@menu
* 查询终端的尺寸:: 
* 文件描述符的继承:: 

@end menu

@node 查询终端的尺寸,文件描述符的继承,,文件描述符操作
@anchor{library/os querying-the-size-of-a-terminal}@anchor{20ce}@anchor{library/os terminal-size}@anchor{20cf}
@subsubsection 查询终端的尺寸



3.3 新版功能.


@geindex get_terminal_size() (在 os 模块中)
@anchor{library/os os get_terminal_size}@anchor{b2d}
@deffn {函数} os.get_terminal_size (fd=STDOUT_FILENO)

返回终端窗口的尺寸，格式为 @code{(columns, lines)}，它是类型为 @ref{1e42,,terminal_size} 的元组。

可选参数 @code{fd} （默认为 @code{STDOUT_FILENO} 或标准输出）指定应查询的文件描述符。

如果文件描述符未连接到终端，则抛出 @ref{30b,,OSError} 异常。

@ref{b2e,,shutil.get_terminal_size()} 是供常规使用的高阶函数，@code{os.get_terminal_size} 是其底层的实现。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex terminal_size (os 中的类)
@anchor{library/os os terminal_size}@anchor{1e42}
@deffn {类} os.terminal_size

元组的子类，存储终端窗口尺寸 @code{(columns, lines)}。

@geindex columns (os.terminal_size 属性)
@anchor{library/os os terminal_size columns}@anchor{20d0}
@deffn {属性} columns

终端窗口的宽度，单位为字符。
@end deffn

@geindex lines (os.terminal_size 属性)
@anchor{library/os os terminal_size lines}@anchor{20d1}
@deffn {属性} lines

终端窗口的高度，单位为字符。
@end deffn
@end deffn

@node 文件描述符的继承,,查询终端的尺寸,文件描述符操作
@anchor{library/os fd-inheritance}@anchor{8f1}@anchor{library/os inheritance-of-file-descriptors}@anchor{20d2}
@subsubsection 文件描述符的继承



3.4 新版功能.


每个文件描述符都有一个 "inheritable"（可继承）标志位，该标志位控制了文件描述符是否可以由子进程继承。从 Python 3.4 开始，由 Python 创建的文件描述符默认是不可继承的。

在 UNIX 上，执行新程序时，不可继承的文件描述符在子进程中是关闭的，其他文件描述符将被继承。

在 Windows 上，不可继承的句柄和文件描述符在子进程中是关闭的，但标准流（文件描述符 0、1 和 2 即标准输入、标准输出和标准错误）是始终继承的。如果使用 @ref{20d3,,spawn*} 函数，所有可继承的句柄和文件描述符都将被继承。如果使用 @ref{f9,,subprocess} 模块，将关闭除标准流以外的所有文件描述符，并且仅当 @emph{close_fds} 参数为 @code{False} 时才继承可继承的句柄。

@geindex get_inheritable() (在 os 模块中)
@anchor{library/os os get_inheritable}@anchor{8f2}
@deffn {函数} os.get_inheritable (fd)

获取指定文件描述符的“可继承”标志位（为布尔值）。
@end deffn

@geindex set_inheritable() (在 os 模块中)
@anchor{library/os os set_inheritable}@anchor{8f3}
@deffn {函数} os.set_inheritable (fd, inheritable)

设置指定文件描述符的“可继承”标志位。
@end deffn

@geindex get_handle_inheritable() (在 os 模块中)
@anchor{library/os os get_handle_inheritable}@anchor{8f4}
@deffn {函数} os.get_handle_inheritable (handle)

获取指定句柄的“可继承”标志位（为布尔值）。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex set_handle_inheritable() (在 os 模块中)
@anchor{library/os os set_handle_inheritable}@anchor{8f5}
@deffn {函数} os.set_handle_inheritable (handle, inheritable)

设置指定句柄的“可继承”标志位。

@ref{14c1,,可用性}: Windows。
@end deffn

@node 文件和目录,进程管理,文件描述符操作,os --- 多种操作系统接口
@anchor{library/os files-and-directories}@anchor{20d4}@anchor{library/os os-file-dir}@anchor{2077}
@subsubsection 文件和目录


在某些 Unix 平台上，许多函数支持以下一项或多项功能：
@anchor{library/os path-fd}@anchor{4c4}

@itemize *

@item 
@strong{指定文件描述符为参数：} 通常在 @ref{c4,,os} 模块中提供给函数的 @emph{path} 参数必须是表示文件路径的字符串，但是，某些函数现在可以接受其 @emph{path} 参数为打开文件描述符，该函数将对描述符指向的文件进行操作。（对于 POSIX 系统，Python 将调用以 @code{f} 开头的函数变体（如调用 @code{fchdir} 而不是 @code{chdir}）。）

可以用 @ref{b28,,os.supports_fd} 检查某个函数在你的平台上是否支持将 @emph{path} 参数指定为文件描述符。如果不支持，使用该功能将抛出 @ref{70e,,NotImplementedError} 异常。

如果该函数还支持 @emph{dir_fd} 或 @emph{follow_symlinks} 参数，那么用文件描述符作为 @emph{path} 后就不能再指定上述参数了。
@end itemize
@anchor{library/os dir-fd}@anchor{b14}

@itemize *

@item 
@strong{基于目录描述符的相对路径：} 如果 @emph{dir_fd} 不是 @code{None}，它就应该是一个指向目录的文件描述符，这时待操作的 path 应该是相对路径，相对路径是相对于前述目录的。如果 path 是绝对路径，则 @emph{dir_fd} 将被忽略。（对于 POSIX 系统，Python 将调用该函数的变体，变体以 @code{at} 结尾，可能以 @code{f} 开头（如调用 @code{faccessat} 而不是 @code{access}）。

可以用 @ref{b23,,os.supports_dir_fd} 检查某个函数在你的平台上是否支持 @emph{dir_fd}。如果不支持，使用该功能将抛出 @ref{70e,,NotImplementedError} 异常。
@end itemize
@anchor{library/os follow-symlinks}@anchor{b15}

@itemize *

@item 
@strong{不跟踪符号链接：} 如果 @emph{follow_symlinks} 为 @code{False}，并且待操作路径的最后一个元素是符号链接，则该函数将在符号链接本身而不是链接所指向的文件上操作。（对于 POSIX 系统，Python 将调用该函数的 @code{l...} 变体。）

可以用 @ref{1e2d,,os.supports_follow_symlinks} 检查某个函数在你的平台上是否支持 @emph{follow_symlinks}。如果不支持，使用该功能将抛出 @ref{70e,,NotImplementedError} 异常。
@end itemize

@geindex access() (在 os 模块中)
@anchor{library/os os access}@anchor{b16}
@deffn {函数} os.access (path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)

使用 实际用户ID/用户组ID 测试对 @emph{path} 的访问。请注意，大多数测试操作将使用 有效用户ID/用户组ID，因此可以在 suid/sgid 环境中运用此例程，来测试调用用户是否具有对 @emph{path} 的指定访问权限。@emph{mode} 为 @ref{20d5,,F_OK} 时用于测试 @emph{path} 是否存在，也可以对 @ref{20d6,,R_OK}、@ref{20d7,,W_OK} 和 @ref{20d8,,X_OK} 中的一个或多个进行“或”运算来测试指定权限。允许访问则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。更多信息请参见 Unix 手册页 @code{access(2)}。

本函数支持指定 @ref{b14,,基于目录描述符的相对路径} 和 @ref{b15,,不跟踪符号链接}。

如果 @emph{effective_ids} 为 @code{True}，@ref{b16,,access()} 将使用 有效用户ID/用户组ID 而非 实际用户ID/用户组ID 进行访问检查。您的平台可能不支持 @emph{effective_ids}，您可以使用 @ref{b29,,os.supports_effective_ids} 检查它是否可用。如果不可用，使用它时会抛出 @ref{70e,,NotImplementedError} 异常。

@cartouche
@quotation 注解 
使用 @ref{b16,,access()} 来检查用户是否具有某项权限（如打开文件的权限），然后再使用 @ref{16f,,open()} 打开文件，这样做存在一个安全漏洞，因为用户可能会在检查和打开文件之间的时间里做其他操作。推荐使用 @ref{20d9,,EAFP} 技术。如:

@example
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
@end example

最好写成:

@example
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
@end example
@end quotation
@end cartouche

@cartouche
@quotation 注解 
即使 @ref{b16,,access()} 指示 I/O 操作会成功，但实际操作仍可能失败，尤其是对网络文件系统的操作，其权限语义可能超出常规的 POSIX 权限位模型。
@end quotation
@end cartouche


在 3.3 版更改: 添加 @emph{dir_fd}、@emph{effective_ids} 和 @emph{follow_symlinks} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex F_OK() (在 os 模块中)
@geindex R_OK() (在 os 模块中)
@geindex W_OK() (在 os 模块中)
@geindex X_OK() (在 os 模块中)
@anchor{library/os os F_OK}@anchor{20d5}
@deffn {数据} os.F_OK
@anchor{library/os os R_OK}@anchor{20d6}
@deffnx {数据} os.R_OK
@anchor{library/os os W_OK}@anchor{20d7}
@deffnx {数据} os.W_OK
@anchor{library/os os X_OK}@anchor{20d8}
@deffnx {数据} os.X_OK

作为 @ref{b16,,access()} 的 @emph{mode} 参数的可选值，分别测试 @emph{path} 的存在性、可读性、可写性和可执行性。
@end deffn

@geindex chdir() (在 os 模块中)
@anchor{library/os os chdir}@anchor{16e}
@deffn {函数} os.chdir (path)

@geindex directory; changing

将当前工作目录更改为 @emph{path}。

本函数支持 @ref{4c4,,指定文件描述符为参数}。其中，描述符必须指向打开的目录，不能是打开的文件。

本函数可以抛出 @ref{30b,,OSError} 及其子类的异常，如 @ref{8b7,,FileNotFoundError}、@ref{700,,PermissionError} 和 @ref{a84,,NotADirectoryError} 异常。

引发一个 @ref{fec,,审计事件} @code{os.chdir}，附带参数 @code{path}。


3.3 新版功能: 在某些平台上新增支持将 @emph{path} 参数指定为文件描述符。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex chflags() (在 os 模块中)
@anchor{library/os os chflags}@anchor{b17}
@deffn {函数} os.chflags (path, flags, *, follow_symlinks=True)

将 @emph{path} 的 flags 设置为其他由数字表示的 @emph{flags}。@emph{flags} 可以用以下值按位或组合起来（以下值在 @ref{f4,,stat} 模块中定义）：


@itemize *

@item 
@ref{1dd3,,stat.UF_NODUMP}

@item 
@ref{1dd4,,stat.UF_IMMUTABLE}

@item 
@ref{1dd5,,stat.UF_APPEND}

@item 
@ref{1dd6,,stat.UF_OPAQUE}

@item 
@ref{1dd7,,stat.UF_NOUNLINK}

@item 
@ref{1dd8,,stat.UF_COMPRESSED}

@item 
@ref{1dd9,,stat.UF_HIDDEN}

@item 
@ref{1dda,,stat.SF_ARCHIVED}

@item 
@ref{1ddb,,stat.SF_IMMUTABLE}

@item 
@ref{1ddc,,stat.SF_APPEND}

@item 
@ref{1ddd,,stat.SF_NOUNLINK}

@item 
@ref{1dde,,stat.SF_SNAPSHOT}
@end itemize

本函数支持 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.chflags}，附带参数 @code{path}、@code{flags}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能: @emph{follow_symlinks} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex chmod() (在 os 模块中)
@anchor{library/os os chmod}@anchor{b18}
@deffn {函数} os.chmod (path, mode, *, dir_fd=None, follow_symlinks=True)

将 @emph{path} 的 mode 更改为其他由数字表示的 @emph{mode}。@emph{mode} 可以用以下值之一，也可以将它们按位或组合起来（以下值在 @ref{f4,,stat} 模块中定义）：


@itemize *

@item 
@ref{1dc0,,stat.S_ISUID}

@item 
@ref{1dc1,,stat.S_ISGID}

@item 
@ref{1dc3,,stat.S_ENFMT}

@item 
@ref{1dc4,,stat.S_ISVTX}

@item 
@ref{1dd0,,stat.S_IREAD}

@item 
@ref{1dd1,,stat.S_IWRITE}

@item 
@ref{1dd2,,stat.S_IEXEC}

@item 
@ref{1dc5,,stat.S_IRWXU}

@item 
@ref{1dc6,,stat.S_IRUSR}

@item 
@ref{1dc7,,stat.S_IWUSR}

@item 
@ref{1dc8,,stat.S_IXUSR}

@item 
@ref{1dc9,,stat.S_IRWXG}

@item 
@ref{1dca,,stat.S_IRGRP}

@item 
@ref{1dcb,,stat.S_IWGRP}

@item 
@ref{1dc2,,stat.S_IXGRP}

@item 
@ref{1dcc,,stat.S_IRWXO}

@item 
@ref{1dcd,,stat.S_IROTH}

@item 
@ref{1dce,,stat.S_IWOTH}

@item 
@ref{1dcf,,stat.S_IXOTH}
@end itemize

本函数支持 @ref{4c4,,指定文件描述符}、@ref{b14,,指定基于目录描述符的相对路径} 和 @ref{b15,,不跟踪符号链接}。

@cartouche
@quotation 注解 
尽管 Windows 支持 @ref{b18,,chmod()}，但只能用它设置文件的只读标志（@code{stat.S_IWRITE} 和 @code{stat.S_IREAD} 常量或对应的整数值）。所有其他标志位都会被忽略。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{os.chmod}，附带参数 @code{path}、@code{mode}、@code{dir_fd}。


3.3 新版功能: 添加了指定 @emph{path} 为文件描述符的支持，以及 @emph{dir_fd} 和 @emph{follow_symlinks} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex chown() (在 os 模块中)
@anchor{library/os os chown}@anchor{b19}
@deffn {函数} os.chown (path, uid, gid, *, dir_fd=None, follow_symlinks=True)

将 @emph{path} 的用户和组 ID 分别修改为数字形式的 @emph{uid} 和 @emph{gid}。若要使其中某个 ID 保持不变，请将其置为 -1。

本函数支持 @ref{4c4,,指定文件描述符}、@ref{b14,,指定基于目录描述符的相对路径} 和 @ref{b15,,不跟踪符号链接}。

参见更高阶的函数 @ref{b5a,,shutil.chown()}，除了数字 ID 之外，它也接受名称。

引发一个 @ref{fec,,审计事件} @code{os.chown}，附带参数 @code{path}、@code{uid}、@code{gid}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能: 添加了指定 @emph{path} 为文件描述符的支持，以及 @emph{dir_fd} 和 @emph{follow_symlinks} 参数。



在 3.6 版更改: 支持 @ref{47b,,类路径对象}。

@end deffn

@geindex chroot() (在 os 模块中)
@anchor{library/os os chroot}@anchor{10c8}
@deffn {函数} os.chroot (path)

将当前进程的根目录更改为 @emph{path}。

@ref{14c1,,可用性}: Unix。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex fchdir() (在 os 模块中)
@anchor{library/os os fchdir}@anchor{758}
@deffn {函数} os.fchdir (fd)

将当前工作目录更改为文件描述符 @emph{fd} 指向的目录。fd 必须指向打开的目录而非文件。从 Python 3.3 开始，它等效于 @code{os.chdir(fd)}。

引发一个 @ref{fec,,审计事件} @code{os.chdir}，附带参数 @code{path}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getcwd() (在 os 模块中)
@anchor{library/os os getcwd}@anchor{1162}
@deffn {函数} os.getcwd ()

返回表示当前工作目录的字符串。
@end deffn

@geindex getcwdb() (在 os 模块中)
@anchor{library/os os getcwdb}@anchor{3e2}
@deffn {函数} os.getcwdb ()

返回表示当前工作目录的字节串 (bytestring)。


在 3.8 版更改: 在 Windows 上，本函数现在会使用 UTF-8 编码格式而不是 ANSI 代码页：请参看 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} 了解具体原因。 该函数在 Windows 上不再被弃用。

@end deffn

@geindex lchflags() (在 os 模块中)
@anchor{library/os os lchflags}@anchor{20da}
@deffn {函数} os.lchflags (path, flags)

将 @emph{path} 的 flags 设置为其他由数字表示的 @emph{flags}，与 @ref{b17,,chflags()} 类似，但不跟踪符号链接。从 Python 3.3 开始，它等效于 @code{os.chflags(path, flags, follow_symlinks=False)}。

引发一个 @ref{fec,,审计事件} @code{os.chflags}，附带参数 @code{path}、@code{flags}。

@ref{14c1,,可用性}: Unix。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex lchmod() (在 os 模块中)
@anchor{library/os os lchmod}@anchor{11a9}
@deffn {函数} os.lchmod (path, mode)

将 @emph{path} 的权限状态修改为 @emph{mode}。如果 path 是符号链接，则影响符号链接本身而非链接目标。可以参考 @ref{b18,,chmod()} 中列出 @emph{mode} 的可用值。从 Python 3.3 开始，它等效于 @code{os.chmod(path, mode, follow_symlinks=False)}。

引发一个 @ref{fec,,审计事件} @code{os.chmod}，附带参数 @code{path}、@code{mode}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex lchown() (在 os 模块中)
@anchor{library/os os lchown}@anchor{20db}
@deffn {函数} os.lchown (path, uid, gid)

将 @emph{path} 的用户和组 ID 分别修改为数字形式的 @emph{uid} 和 @emph{gid}，本函数不跟踪符号链接。从 Python 3.3 开始，它等效于 @code{os.chown(path, uid, gid, follow_symlinks=False)}。

引发一个 @ref{fec,,审计事件} @code{os.chown}，附带参数 @code{path}、@code{uid}、@code{gid}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex link() (在 os 模块中)
@anchor{library/os os link}@anchor{b1a}
@deffn {函数} os.link (src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)

创建一个指向 @emph{src} 的硬链接，名为 @emph{dst}。

本函数支持将 @emph{src_dir_fd} 和 @emph{dst_dir_fd} 中的一个或两个指定为 @ref{b14,,基于目录描述符的相对路径}，支持 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.link} 附带参数 @code{src}、@code{dst}、@code{src_dir_fd}、@code{dst_dir_fd}。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加了对 Windows 的支持。



3.3 新版功能: 添加 @emph{src_dir_fd}、@emph{dst_dir_fd} 和 @emph{follow_symlinks} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{src} 和 @emph{dst}。

@end deffn

@geindex listdir() (在 os 模块中)
@anchor{library/os os listdir}@anchor{b25}
@deffn {函数} os.listdir (path='.')

返回一个包含由 @emph{path} 指定目录中条目名称组成的列表。 该列表按任意顺序排列，并且不包括特殊条目 @code{'.'} 和 @code{'..'}，即使它们存在于目录中。 如果有文件在调用此函数期间在被移除或添加到目录中，是否要包括该文件的名称并没有规定。

@emph{path} 可以是 @ref{47b,,类路径对象}。如果 @emph{path} 是（直接传入或通过 @ref{5ee,,PathLike} 接口间接传入） @code{bytes} 类型，则返回的文件名也将是 @code{bytes} 类型，其他情况下是 @code{str} 类型。

本函数也支持 @ref{4c4,,指定文件描述符为参数}，其中描述符必须指向目录。

引发一个 @ref{fec,,审计事件} @code{os.listdir}，附带参数 @code{path}。

@cartouche
@quotation 注解 
要将 @code{str} 类型的文件名编码为 @code{bytes}，请使用 @ref{5f2,,fsencode()}。
@end quotation
@end cartouche


@subsubheading 参见


@ref{390,,scandir()} 函数返回目录内文件名的同时，也返回文件属性信息，它在某些具体情况下能提供更好的性能。



在 3.2 版更改: @emph{path} 变为可选参数。



3.3 新版功能: 新增支持将 @emph{path} 参数指定为打开的文件描述符。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex lstat() (在 os 模块中)
@anchor{library/os os lstat}@anchor{329}
@deffn {函数} os.lstat (path, *, dir_fd=None)

在给定路径上执行本函数，其操作相当于 @code{lstat()} 系统调用，类似于 @ref{328,,stat()} 但不跟踪符号链接。返回值是 @ref{1208,,stat_result} 对象。

在不支持符号链接的平台上，本函数是 @ref{328,,stat()} 的别名。

从 Python 3.3 起，此功能等价于 @code{os.stat(path, dir_fd=dir_fd, follow_symlinks=False)}。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。


@subsubheading 参见


@ref{328,,stat()} 函数。



在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。



在 3.3 版更改: 添加了 @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.8 版更改: 目前在 Windows 上，遇到表示另一个路径的重解析点（即名称代理，包括符号链接和目录结点），本函数将打开它。其他种类的重解析点由 @ref{328,,stat()} 交由操作系统解析。

@end deffn

@geindex mkdir() (在 os 模块中)
@anchor{library/os os mkdir}@anchor{b1b}
@deffn {函数} os.mkdir (path, mode=0o777, *, dir_fd=None)

创建一个名为 @emph{path} 的目录，应用以数字表示的权限模式 @emph{mode}。

如果目录已经存在， @ref{a42,,FileExistsError} 会被提出。如果路径中的父目录不存在，则会引发 @ref{8b7,,FileNotFoundError} 。
@anchor{library/os mkdir-modebits}@anchor{20dc}
某些系统会忽略 @emph{mode}。如果没有忽略它，那么将首先从它中减去当前的 umask 值。如果除最后 9 位（即 @emph{mode} 八进制的最后 3 位）之外，还设置了其他位，则其他位的含义取决于各个平台。在某些平台上，它们会被忽略，应显式调用 @ref{b18,,chmod()} 进行设置。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

如果需要创建临时目录，请参阅 @ref{103,,tempfile} 模块中的 @ref{1e0d,,tempfile.mkdtemp()} 函数。

引发一个 @ref{fec,,审计事件} @code{os.mkdir}，附带参数 @code{path}、@code{mode}、@code{dir_fd}。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex makedirs() (在 os 模块中)
@anchor{library/os os makedirs}@anchor{4cc}
@deffn {函数} os.makedirs (name, mode=0o777, exist_ok=False)

@geindex directory; creating
@geindex UNC paths; and os.makedirs()

递归目录创建函数。与 @ref{b1b,,mkdir()} 类似，但会自动创建到达最后一级目录所需要的中间目录。

@emph{mode} 参数会传递给 @ref{b1b,,mkdir()}，用来创建最后一级目录，对于该参数的解释，请参阅 @ref{20dc,,mkdir() 中的描述}。要设置某些新建的父目录的权限，可以在调用 @ref{4cc,,makedirs()} 之前设置 umask。现有父目录的权限不会更改。

如果 @emph{exist_ok} 为 @code{False} (默认值)，则如果目标目录已存在将引发 @ref{a42,,FileExistsError}。

@cartouche
@quotation 注解 
如果要创建的路径元素包含 @ref{20dd,,pardir} (如 UNIX 系统中的 "..") @ref{4cc,,makedirs()} 将无法明确目标。
@end quotation
@end cartouche

本函数能正确处理 UNC 路径。

引发一个 @ref{fec,,审计事件} @code{os.mkdir}，附带参数 @code{path}、@code{mode}、@code{dir_fd}。


3.2 新版功能: @emph{exist_ok} 参数。



在 3.4.1 版更改: 在 Python 3.4.1 以前，如果 @emph{exist_ok} 为 @code{True}，且目录已存在，且 @emph{mode} 与现有目录的权限不匹配，@ref{4cc,,makedirs()} 仍会抛出错误。由于无法安全地实现此行为，因此在 Python 3.4.1 中将该行为删除。请参阅 bpo-21082@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=21082}。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.7 版更改: @emph{mode} 参数不再影响新创建的中间目录的权限。

@end deffn

@geindex mkfifo() (在 os 模块中)
@anchor{library/os os mkfifo}@anchor{760}
@deffn {函数} os.mkfifo (path, mode=0o666, *, dir_fd=None)

创建一个名为 @emph{path} 的 FIFO（命名管道，一种先进先出队列），具有以数字表示的权限状态 @emph{mode}。将从 mode 中首先减去当前的 umask 值。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

FIFO 是可以像常规文件一样访问的管道。FIFO 如果没有被删除（如使用 @ref{b21,,os.unlink()}），会一直存在。通常，FIFO 用作“客户端”和“服务器”进程之间的汇合点：服务器打开 FIFO 进行读取，而客户端打开 FIFO 进行写入。请注意，@ref{760,,mkfifo()} 不会打开 FIFO --- 它只是创建汇合点。

@ref{14c1,,可用性}: Unix。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex mknod() (在 os 模块中)
@anchor{library/os os mknod}@anchor{761}
@deffn {函数} os.mknod (path, mode=0o600, device=0, *, dir_fd=None)

创建一个名为 @emph{path} 的文件系统节点（文件，设备专用文件或命名管道）。@emph{mode} 指定权限和节点类型，方法是将权限与下列节点类型 @code{stat.S_IFREG}、@code{stat.S_IFCHR}、@code{stat.S_IFBLK} 和 @code{stat.S_IFIFO} 之一（按位或）组合（这些常量可以在 @ref{f4,,stat} 模块中找到）。对于 @code{stat.S_IFCHR} 和 @code{stat.S_IFBLK}，@emph{device} 参数指定了新创建的设备专用文件（可能会用到 @ref{20de,,os.makedev()}），否则该参数将被忽略。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex major() (在 os 模块中)
@anchor{library/os os major}@anchor{20df}
@deffn {函数} os.major (device)

提取主设备号，提取自原始设备号（通常是 @code{stat} 中的 @code{st_dev} 或 @code{st_rdev} 字段）。
@end deffn

@geindex minor() (在 os 模块中)
@anchor{library/os os minor}@anchor{20e0}
@deffn {函数} os.minor (device)

提取次设备号，提取自原始设备号（通常是 @code{stat} 中的 @code{st_dev} 或 @code{st_rdev} 字段）。
@end deffn

@geindex makedev() (在 os 模块中)
@anchor{library/os os makedev}@anchor{20de}
@deffn {函数} os.makedev (major, minor)

将主设备号和次设备号组合成原始设备号。
@end deffn

@geindex pathconf() (在 os 模块中)
@anchor{library/os os pathconf}@anchor{b26}
@deffn {函数} os.pathconf (path, name)

返回所给名称的文件有关的系统配置信息。@emph{name} 指定要查找的配置名称，它可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。当前操作系统已定义的名称在 @code{pathconf_names} 字典中给出。对于未包含在该映射中的配置名称，也可以传递一个整数作为 @emph{name}。

如果 @emph{name} 是一个字符串且不是已定义的名称，将抛出 @ref{16d,,ValueError} 异常。如果当前系统不支持 @emph{name} 指定的配置名称，即使该名称存在于 @code{pathconf_names}，也会抛出 @ref{30b,,OSError} 异常，错误码为 @ref{114d,,errno.EINVAL}。

本函数支持 @ref{4c4,,指定文件描述符为参数}。

@ref{14c1,,可用性}: Unix。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex pathconf_names() (在 os 模块中)
@anchor{library/os os pathconf_names}@anchor{20e1}
@deffn {数据} os.pathconf_names

字典，表示映射关系，为 @ref{b26,,pathconf()} 和 @ref{209f,,fpathconf()} 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex readlink() (在 os 模块中)
@anchor{library/os os readlink}@anchor{1d2}
@deffn {函数} os.readlink (path, *, dir_fd=None)

返回一个字符串，为符号链接指向的实际路径。其结果可以是绝对或相对路径。如果是相对路径，则可用 @code{os.path.join(os.path.dirname(path), result)} 转换为绝对路径。

如果 @emph{path} 是字符串对象（直接传入或通过 @ref{5ee,,PathLike} 接口间接传入），则结果也将是字符串对象，且此类调用可能会引发 UnicodeDecodeError。如果 @emph{path} 是字节对象（直接传入或间接传入），则结果将会是字节对象。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

当尝试解析的路径可能含有链接时，请改用 @ref{334,,realpath()} 以正确处理递归和平台差异。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。



3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 在 Unix 上可以接受一个 @ref{47b,,类路径对象}。



在 3.8 版更改: 在 Windows 上接受 @ref{47b,,类路径对象} 和字节对象。



在 3.8 版更改: 增加了对目录链接的支持，且返回值改为了“替换路径”的形式（通常带有 @code{\\?\} 前缀），而不是先前那样返回可选的 "print name" 字段。

@end deffn

@geindex remove() (在 os 模块中)
@anchor{library/os os remove}@anchor{b1c}
@deffn {函数} os.remove (path, *, dir_fd=None)

移除（删除）文件 @emph{path}。 如果 @emph{path} 是目录，则会引发 @ref{a83,,IsADirectoryError}。 请使用 @ref{b1f,,rmdir()} 来删除目录。 如果文件不存在，则会引发 @ref{8b7,,FileNotFoundError}。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

在 Windows 上，尝试删除正在使用的文件会抛出异常。而在 Unix 上，虽然该文件的条目会被删除，但分配给文件的存储空间仍然不可用，直到原始文件不再使用为止。

本函数在语义上与 @ref{b21,,unlink()} 相同。

引发一个 @ref{fec,,审计事件} @code{os.remove}，附带参数 @code{path}、@code{dir_fd}。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex removedirs() (在 os 模块中)
@anchor{library/os os removedirs}@anchor{20e2}
@deffn {函数} os.removedirs (name)

@geindex directory; deleting

递归删除目录。工作方式类似于 @ref{b1f,,rmdir()}，不同之处在于，如果成功删除了末尾一级目录，@ref{20e2,,removedirs()} 会尝试依次删除 @emph{path} 中提到的每个父目录，直到抛出错误为止（但该错误会被忽略，因为这通常表示父目录不是空目录）。例如，@code{os.removedirs('foo/bar/baz')} 将首先删除目录 @code{'foo/bar/baz'}，然后如果 @code{'foo/bar'} 和 @code{'foo'} 为空，则继续删除它们。如果无法成功删除末尾一级目录，则抛出 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{os.remove}，附带参数 @code{path}、@code{dir_fd}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex rename() (在 os 模块中)
@anchor{library/os os rename}@anchor{b1d}
@deffn {函数} os.rename (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

将文件或目录 @emph{src} 重命名为 @emph{dst}。如果 @emph{dst} 已存在，则下列情况下将会操作失败，并抛出 @ref{30b,,OSError} 的子类：

在 Windows 上，如果 @emph{dst} 已存在，则抛出 @ref{a42,,FileExistsError} 异常。

在 Unix 上，如果 @emph{src} 是文件而 @emph{dst} 是目录，将抛出 @ref{a83,,IsADirectoryError} 异常，反之则抛出 @ref{a84,,NotADirectoryError} 异常。如果两者都是目录且 @emph{dst} 为空，则 @emph{dst} 将被静默替换。如果 @emph{dst} 是非空目录，则抛出 @ref{30b,,OSError} 异常。如果两者都是文件，则在用户具有权限的情况下，将对 @emph{dst} 进行静默替换。如果 @emph{src} 和 @emph{dst} 在不同的文件系统上，则本操作在某些 Unix 分支上可能会失败。如果成功，重命名操作将是一个原子操作（这是 POSIX 的要求）。

本函数支持将 @emph{src_dir_fd} 和 @emph{dst_dir_fd} 中的一个或两个指定为 @ref{b14,,基于目录描述符的相对路径}。

如果需要在不同平台上都能替换目标，请使用 @ref{b1e,,replace()}。

引发一个 @ref{fec,,审计事件} @code{os.rename} 附带参数 @code{src}、@code{dst}、@code{src_dir_fd}、@code{dst_dir_fd}。


3.3 新版功能: @emph{src_dir_fd} 和 @emph{dst_dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{src} 和 @emph{dst}。

@end deffn

@geindex renames() (在 os 模块中)
@anchor{library/os os renames}@anchor{20e3}
@deffn {函数} os.renames (old, new)

递归重命名目录或文件。工作方式类似 @ref{b1d,,rename()}，除了会首先创建新路径所需的中间目录。重命名后，将调用 @ref{20e2,,removedirs()} 删除旧路径中不需要的目录。

@cartouche
@quotation 注解 
如果用户没有权限删除末级的目录或文件，则本函数可能会无法建立新的目录结构。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{os.rename} 附带参数 @code{src}、@code{dst}、@code{src_dir_fd}、@code{dst_dir_fd}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{old} 和 @emph{new}。

@end deffn

@geindex replace() (在 os 模块中)
@anchor{library/os os replace}@anchor{b1e}
@deffn {函数} os.replace (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

将文件或目录 @emph{src} 重命名为 @emph{dst}。如果 @emph{dst} 是非空目录，将抛出 @ref{30b,,OSError} 异常。如果 @emph{dst} 已存在且为文件，则在用户具有权限的情况下，将对其进行静默替换。如果 @emph{src} 和 @emph{dst} 在不同的文件系统上，本操作可能会失败。如果成功，重命名操作将是一个原子操作（这是 POSIX 的要求）。

本函数支持将 @emph{src_dir_fd} 和 @emph{dst_dir_fd} 中的一个或两个指定为 @ref{b14,,基于目录描述符的相对路径}。

引发一个 @ref{fec,,审计事件} @code{os.rename} 附带参数 @code{src}、@code{dst}、@code{src_dir_fd}、@code{dst_dir_fd}。


3.3 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{src} 和 @emph{dst}。

@end deffn

@geindex rmdir() (在 os 模块中)
@anchor{library/os os rmdir}@anchor{b1f}
@deffn {函数} os.rmdir (path, *, dir_fd=None)

移除（删除）目录 @emph{path}。如果目录不存在或不为空，则会分别抛出 @ref{8b7,,FileNotFoundError} 或 @ref{30b,,OSError} 异常。要删除整个目录树，可以使用 @ref{350,,shutil.rmtree()}。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

引发一个 @ref{fec,,审计事件} @code{os.rmdir}，附带参数 @code{path}、@code{dir_fd}。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex scandir() (在 os 模块中)
@anchor{library/os os scandir}@anchor{390}
@deffn {函数} os.scandir (path='.')

返回一个 @ref{5f3,,os.DirEntry} 对象的迭代器，它们对应于由 @emph{path} 指定目录中的条目。 这些条目会以任意顺序生成，并且不包括特殊条目 @code{'.'} 和 @code{'..'}。 如果有文件在迭代器创建之后在目录中被移除或添加，是否要包括该文件对应的条目并没有规定。

如果需要文件类型或文件属性信息，使用 @ref{390,,scandir()} 代替 @ref{b25,,listdir()} 可以大大提高这部分代码的性能，因为如果操作系统在扫描目录时返回的是 @ref{5f3,,os.DirEntry} 对象，则该对象包含了这些信息。所有 @ref{5f3,,os.DirEntry} 的方法都可能执行一次系统调用，但是 @ref{20e4,,is_dir()} 和 @ref{752,,is_file()} 通常只在有符号链接时才执行一次系统调用。@ref{20e5,,os.DirEntry.stat()} 在 Unix 上始终需要一次系统调用，而在 Windows 上只在有符号链接时才需要。

@emph{path} 可以是 @ref{47b,,类路径对象}。如果 @emph{path} 是（直接传入或通过 @ref{5ee,,PathLike} 接口间接传入的） @code{bytes} 类型，那么每个 @ref{5f3,,os.DirEntry} 的 @ref{20e6,,name} 和 @ref{20e7,,path} 属性将是 @code{bytes} 类型，其他情况下是 @code{str} 类型。

本函数也支持 @ref{4c4,,指定文件描述符为参数}，其中描述符必须指向目录。

引发一个 @ref{fec,,审计事件} @code{os.scandir}，附带参数 @code{path}。

@ref{390,,scandir()} 迭代器支持 @ref{66b,,上下文管理} 协议，并具有以下方法：

@geindex close() (os.scandir 方法)
@anchor{library/os os scandir close}@anchor{66a}
@deffn {方法} scandir.close ()

关闭迭代器并释放占用的资源。

当迭代器迭代完毕，或垃圾回收，或迭代过程出错时，将自动调用本方法。但仍建议显式调用它或使用 @ref{7e4,,with} 语句。


3.6 新版功能.

@end deffn

下面的例子演示了 @ref{390,,scandir()} 的简单用法，用来显示给定 @emph{path} 中所有不以 @code{'.'} 开头的文件（不包括目录）。@code{entry.is_file()} 通常不会增加一次额外的系统调用:

@example
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
@end example

@cartouche
@quotation 注解 
在基于 Unix 的系统上，@ref{390,,scandir()} 使用系统的 opendir()@footnote{http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html} 和 readdir()@footnote{http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html} 函数。在 Windows 上，它使用 Win32 FindFirstFileW@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx} 和 FindNextFileW@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx} 函数。
@end quotation
@end cartouche


3.5 新版功能.



3.6 新版功能: 添加了对 @ref{66b,,上下文管理} 协议和 @ref{66a,,close()} 方法的支持。如果 @ref{390,,scandir()} 迭代器没有迭代完毕且没有显式关闭，其析构函数将发出 @ref{5d3,,ResourceWarning} 警告。

本函数接受一个 @ref{47b,,类路径对象}。



在 3.7 版更改: 在 Unix 上新增支持 @ref{4c4,,指定文件描述符为参数}。

@end deffn

@geindex DirEntry (os 中的类)
@anchor{library/os os DirEntry}@anchor{5f3}
@deffn {类} os.DirEntry

由 @ref{390,,scandir()} 生成的对象，用于显示目录内某个条目的文件路径和其他文件属性。

@ref{390,,scandir()} 将在不进行额外系统调用的情况下，提供尽可能多的此类信息。每次进行 @code{stat()} 或 @code{lstat()} 系统调用时，@code{os.DirEntry} 对象会将结果缓存下来。

@code{os.DirEntry} 实例不适合存储在长期存在的数据结构中，如果你知道文件元数据已更改，或者自调用 @ref{390,,scandir()} 以来已经经过了很长时间，请调用 @code{os.stat(entry.path)} 来获取最新信息。

因为 @code{os.DirEntry} 方法可以进行系统调用，所以它也可能抛出 @ref{30b,,OSError} 异常。如需精确定位错误，可以逐个调用 @code{os.DirEntry} 中的方法来捕获 @ref{30b,,OSError}，并适当处理。

为了能直接用作 @ref{47b,,类路径对象}，@code{os.DirEntry} 实现了 @ref{5ee,,PathLike} 接口。

@code{os.DirEntry} 实例所包含的属性和方法如下：

@geindex name (os.DirEntry 属性)
@anchor{library/os os DirEntry name}@anchor{20e6}
@deffn {属性} name

本条目的基本文件名，是根据 @ref{390,,scandir()} 的 @emph{path} 参数得出的相对路径。

如果 @ref{390,,scandir()} 的 @emph{path} 参数是 @code{bytes} 类型，则 @ref{2071,,name} 属性也是 @code{bytes} 类型，否则为 @code{str}。使用 @ref{5f1,,fsdecode()} 解码 byte 类型的文件名。
@end deffn

@geindex path (os.DirEntry 属性)
@anchor{library/os os DirEntry path}@anchor{20e7}
@deffn {属性} path

本条目的完整路径：等效于 @code{os.path.join(scandir_path, entry.name)}，其中 @emph{scandir_path} 就是 @ref{390,,scandir()} 的 @emph{path} 参数。仅当 @ref{390,,scandir()} 的 @emph{path} 参数为绝对路径时，本路径才是绝对路径。如果 @ref{390,,scandir()} 的 @emph{path} 参数是 @ref{4c4,,文件描述符}，则 @ref{c5,,path} 属性与上述 @ref{2071,,name} 属性相同。

如果 @ref{390,,scandir()} 的 @emph{path} 参数是 @code{bytes} 类型，则 @ref{c5,,path} 属性也是 @code{bytes} 类型，否则为 @code{str}。使用 @ref{5f1,,fsdecode()} 解码 byte 类型的文件名。
@end deffn

@geindex inode() (os.DirEntry 方法)
@anchor{library/os os DirEntry inode}@anchor{20e8}
@deffn {方法} inode ()

返回本条目的索引节点号 (inode number)。

这一结果是缓存在 @code{os.DirEntry} 对象中的，请调用 @code{os.stat(entry.path, follow_symlinks=False).st_ino} 来获取最新信息。

一开始没有缓存时，在 Windows 上需要一次系统调用，但在 Unix 上不需要。
@end deffn

@geindex is_dir() (os.DirEntry 方法)
@anchor{library/os os DirEntry is_dir}@anchor{20e4}
@deffn {方法} is_dir (*, follow_symlinks=True)

如果本条目是目录，或是指向目录的符号链接，则返回 @code{True}。如果本条目是文件，或指向任何其他类型的文件，或该目录不再存在，则返回 @code{False}。

如果 @emph{follow_symlinks} 是 @code{False}，那么仅当本条目为目录时返回 @code{True} （不跟踪符号链接），如果本条目是任何类型的文件，或该文件不再存在，则返回 @code{False}。

这一结果是缓存在 @code{os.DirEntry} 对象中的，且 @emph{follow_symlinks} 为 @code{True} 和 @code{False} 时的缓存是分开的。请调用 @ref{328,,os.stat()} 和 @ref{1da7,,stat.S_ISDIR()} 来获取最新信息。

一开始没有缓存时，大多数情况下不需要系统调用。特别是对于非符号链接，Windows 和 Unix 都不需要系统调用，除非某些 Unix 文件系统（如网络文件系统）返回了 @code{dirent.d_type == DT_UNKNOWN}。如果本条目是符号链接，则需要一次系统调用来跟踪它（除非 @emph{follow_symlinks} 为 @code{False}）。

本方法可能抛出 @ref{30b,,OSError} 异常，如 @ref{700,,PermissionError} 异常，但 @ref{8b7,,FileNotFoundError} 异常会被内部捕获且不会抛出。
@end deffn

@geindex is_file() (os.DirEntry 方法)
@anchor{library/os os DirEntry is_file}@anchor{752}
@deffn {方法} is_file (*, follow_symlinks=True)

如果本条目是文件，或是指向文件的符号链接，则返回 @code{True}。如果本条目是目录，或指向目录，或指向其他非文件条目，或该文件不再存在，则返回 @code{False}。

如果 @emph{follow_symlinks} 是 @code{False}，那么仅当本条目为文件时返回 @code{True} （不跟踪符号链接），如果本条目是目录或其他非文件条目，或该文件不再存在，则返回 @code{False}。

这一结果是缓存在 @code{os.DirEntry} 对象中的。缓存、系统调用、异常抛出都与 @ref{20e4,,is_dir()} 一致。
@end deffn

@geindex is_symlink() (os.DirEntry 方法)
@anchor{library/os os DirEntry is_symlink}@anchor{20e9}
@deffn {方法} is_symlink ()

如果本条目是符号链接（即使是断开的链接），返回 @code{True}。如果是目录或任何类型的文件，或本条目不再存在，返回 @code{False}。

这一结果是缓存在 @code{os.DirEntry} 对象中的，请调用 @ref{32a,,os.path.islink()} 来获取最新信息。

一开始没有缓存时，大多数情况下不需要系统调用。其实 Windows 和 Unix 都不需要系统调用，除非某些 Unix 文件系统（如网络文件系统）返回了 @code{dirent.d_type == DT_UNKNOWN}。

本方法可能抛出 @ref{30b,,OSError} 异常，如 @ref{700,,PermissionError} 异常，但 @ref{8b7,,FileNotFoundError} 异常会被内部捕获且不会抛出。
@end deffn

@geindex stat() (os.DirEntry 方法)
@anchor{library/os os DirEntry stat}@anchor{20e5}
@deffn {方法} stat (*, follow_symlinks=True)

返回本条目对应的 @ref{1208,,stat_result} 对象。本方法默认会跟踪符号链接，要获取符号链接本身的 stat，请添加 @code{follow_symlinks=False} 参数。

在 Unix 上，本方法需要一次系统调用。在 Windows 上，仅在 @emph{follow_symlinks} 为 @code{True} 且该条目是一个重解析点（如符号链接或目录结点）时，才需要一次系统调用。

在 Windows 上，@ref{1208,,stat_result} 的 @code{st_ino}、@code{st_dev} 和 @code{st_nlink} 属性总是为零。请调用 @ref{328,,os.stat()} 以获得这些属性。

这一结果是缓存在 @code{os.DirEntry} 对象中的，且 @emph{follow_symlinks} 为 @code{True} 和 @code{False} 时的缓存是分开的。请调用 @ref{328,,os.stat()} 来获取最新信息。
@end deffn

注意，@code{os.DirEntry} 和 @ref{336,,pathlib.Path} 的几个属性和方法之间存在很好的对应关系。具体来说是 @code{name} 属性，以及 @code{is_dir()}、@code{is_file()}、@code{is_symlink()} 和 @code{stat()} 方法，在两个类中具有相同的含义。


3.5 新版功能.



在 3.6 版更改: 添加了对 @ref{5ee,,PathLike} 接口的支持。在 Windows 上添加了对 @ref{172,,bytes} 类型路径的支持。

@end deffn

@geindex stat() (在 os 模块中)
@anchor{library/os os stat}@anchor{328}
@deffn {函数} os.stat (path, *, dir_fd=None, follow_symlinks=True)

获取文件或文件描述符的状态。在所给路径上执行等效于 @code{stat()} 系统调用的操作。@emph{path} 可以是字符串类型，或（直接传入或通过 @ref{5ee,,PathLike} 接口间接传入的） bytes 类型，或打开的文件描述符。返回一个 @ref{1208,,stat_result} 对象。

本函数默认会跟踪符号链接，要获取符号链接本身的 stat，请添加 @code{follow_symlinks=False} 参数，或使用 @ref{329,,lstat()}。

本函数支持 @ref{4c4,,指定文件描述符为参数} 和 @ref{b15,,不跟踪符号链接}。

在 Windows 上，传入 @code{follow_symlinks=False} 将禁用所有名称代理重解析点，其中包括符号链接和目录结点。其他类型的重解析点将直接打开，比如不像链接的或系统无法跟踪的重解析点。当多个链接形成一个链时，本方法可能会返回原始链接的 stat，无法完整遍历到非链接的对象。在这种情况下，要获取最终路径的 stat，请使用 @ref{334,,os.path.realpath()} 函数尽可能地解析路径，并在解析结果上调用 @ref{329,,lstat()}。这不适用于空链接或交接点，否则会抛出异常。

@geindex 模块; stat

示例:

@example
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
@end example


@subsubheading 参见


@ref{75c,,fstat()} 和 @ref{329,,lstat()} 函数。



3.3 新版功能: 增加 @emph{dir_fd} 和 @emph{follow_symlinks} 参数，可指定文件描述符代替路径。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.8 版更改: 在 Windows 上，本方法将跟踪系统能解析的所有重解析点，并且传入 @code{follow_symlinks=False} 会停止跟踪所有名称代理重解析点。现在，如果操作系统遇到无法跟踪的重解析点，@emph{stat} 将返回原始路径的信息，就像已指定 @code{follow_symlinks=False} 一样，而不会抛出异常。

@end deffn

@geindex stat_result (os 中的类)
@anchor{library/os os stat_result}@anchor{1208}
@deffn {类} os.stat_result

本对象的属性大致对应于 @code{stat} 结构体成员，主要作为 @ref{328,,os.stat()}、@ref{75c,,os.fstat()} 和 @ref{329,,os.lstat()} 的返回值。

属性：

@geindex st_mode (os.stat_result 属性)
@anchor{library/os os stat_result st_mode}@anchor{20ea}
@deffn {属性} st_mode

文件模式：包括文件类型和文件模式位（即权限位）。
@end deffn

@geindex st_ino (os.stat_result 属性)
@anchor{library/os os stat_result st_ino}@anchor{20eb}
@deffn {属性} st_ino

与平台有关，但如果不为零，则根据 @code{st_dev} 值唯一地标识文件。通常：


@itemize *

@item 
在 Unix 上该值表示索引节点号 (inode number)。

@item 
在 Windows 上该值表示 文件索引号@footnote{https://msdn.microsoft.com/en-us/library/aa363788} 。
@end itemize
@end deffn

@geindex st_dev (os.stat_result 属性)
@anchor{library/os os stat_result st_dev}@anchor{20ec}
@deffn {属性} st_dev

该文件所在设备的标识符。
@end deffn

@geindex st_nlink (os.stat_result 属性)
@anchor{library/os os stat_result st_nlink}@anchor{20ed}
@deffn {属性} st_nlink

硬链接的数量。
@end deffn

@geindex st_uid (os.stat_result 属性)
@anchor{library/os os stat_result st_uid}@anchor{20ee}
@deffn {属性} st_uid

文件所有者的用户 ID。
@end deffn

@geindex st_gid (os.stat_result 属性)
@anchor{library/os os stat_result st_gid}@anchor{20ef}
@deffn {属性} st_gid

文件所有者的用户组 ID。
@end deffn

@geindex st_size (os.stat_result 属性)
@anchor{library/os os stat_result st_size}@anchor{20f0}
@deffn {属性} st_size

文件大小（以字节为单位），文件可以是常规文件或符号链接。符号链接的大小是它包含的路径的长度，不包括末尾的空字节。
@end deffn

时间戳：

@geindex st_atime (os.stat_result 属性)
@anchor{library/os os stat_result st_atime}@anchor{20f1}
@deffn {属性} st_atime

最近的访问时间，以秒为单位。
@end deffn

@geindex st_mtime (os.stat_result 属性)
@anchor{library/os os stat_result st_mtime}@anchor{1efd}
@deffn {属性} st_mtime

最近的修改时间，以秒为单位。
@end deffn

@geindex st_ctime (os.stat_result 属性)
@anchor{library/os os stat_result st_ctime}@anchor{20f2}
@deffn {属性} st_ctime

取决于平台：


@itemize *

@item 
在 Unix 上表示最近的元数据更改时间，

@item 
在 Windows 上表示创建时间，以秒为单位。
@end itemize
@end deffn

@geindex st_atime_ns (os.stat_result 属性)
@anchor{library/os os stat_result st_atime_ns}@anchor{20f3}
@deffn {属性} st_atime_ns

最近的访问时间，以纳秒表示，为整数。
@end deffn

@geindex st_mtime_ns (os.stat_result 属性)
@anchor{library/os os stat_result st_mtime_ns}@anchor{20f4}
@deffn {属性} st_mtime_ns

最近的修改时间，以纳秒表示，为整数。
@end deffn

@geindex st_ctime_ns (os.stat_result 属性)
@anchor{library/os os stat_result st_ctime_ns}@anchor{20f5}
@deffn {属性} st_ctime_ns

取决于平台：


@itemize *

@item 
在 Unix 上表示最近的元数据更改时间，

@item 
在 Windows 上表示创建时间，以纳秒表示，为整数。
@end itemize
@end deffn

@cartouche
@quotation 注解 
@ref{20f1,,st_atime}、@ref{1efd,,st_mtime} 和 @ref{20f2,,st_ctime} 属性的确切含义和分辨率取决于操作系统和文件系统。例如，在使用 FAT 或 FAT32 文件系统的 Windows 上，@ref{1efd,,st_mtime} 有 2 秒的分辨率，而 @ref{20f1,,st_atime} 仅有 1 天的分辨率。详细信息请参阅操作系统文档。

类似地，尽管 @ref{20f3,,st_atime_ns}、@ref{20f4,,st_mtime_ns} 和 @ref{20f5,,st_ctime_ns} 始终以纳秒表示，但许多系统并不提供纳秒精度。在确实提供纳秒精度的系统上，用于存储 @ref{20f1,,st_atime}、@ref{1efd,,st_mtime} 和 @ref{20f2,,st_ctime} 的浮点对象无法保留所有精度，因此不够精确。如果需要确切的时间戳，则应始终使用 @ref{20f3,,st_atime_ns}、@ref{20f4,,st_mtime_ns} 和 @ref{20f5,,st_ctime_ns}。
@end quotation
@end cartouche

在某些 Unix 系统上（如 Linux 上），以下属性可能也可用：

@geindex st_blocks (os.stat_result 属性)
@anchor{library/os os stat_result st_blocks}@anchor{20f6}
@deffn {属性} st_blocks

为文件分配的字节块数，每块 512 字节。文件是稀疏文件时，它可能小于 @ref{20f0,,st_size}/512。
@end deffn

@geindex st_blksize (os.stat_result 属性)
@anchor{library/os os stat_result st_blksize}@anchor{20f7}
@deffn {属性} st_blksize

“首选的” 块大小，用于提高文件系统 I/O 效率。写入文件时块大小太小可能会导致读取-修改-重写效率低下。
@end deffn

@geindex st_rdev (os.stat_result 属性)
@anchor{library/os os stat_result st_rdev}@anchor{20f8}
@deffn {属性} st_rdev

设备类型（如果是 inode 设备）。
@end deffn

@geindex st_flags (os.stat_result 属性)
@anchor{library/os os stat_result st_flags}@anchor{20f9}
@deffn {属性} st_flags

用户定义的文件标志位。
@end deffn

在其他 Unix 系统上（如 FreeBSD 上），以下属性可能可用（但仅当 root 使用它们时才被填充）：

@geindex st_gen (os.stat_result 属性)
@anchor{library/os os stat_result st_gen}@anchor{20fa}
@deffn {属性} st_gen

文件生成号。
@end deffn

@geindex st_birthtime (os.stat_result 属性)
@anchor{library/os os stat_result st_birthtime}@anchor{20fb}
@deffn {属性} st_birthtime

文件创建时间。
@end deffn

在 Solaris 及其衍生版本上，以下属性可能也可用：

@geindex st_fstype (os.stat_result 属性)
@anchor{library/os os stat_result st_fstype}@anchor{4ce}
@deffn {属性} st_fstype

文件所在文件系统的类型的唯一标识，为字符串。
@end deffn

在 macOS 系统上，以下属性可能也可用：

@geindex st_rsize (os.stat_result 属性)
@anchor{library/os os stat_result st_rsize}@anchor{20fc}
@deffn {属性} st_rsize

文件的实际大小。
@end deffn

@geindex st_creator (os.stat_result 属性)
@anchor{library/os os stat_result st_creator}@anchor{20fd}
@deffn {属性} st_creator

文件的创建者。
@end deffn

@geindex st_type (os.stat_result 属性)
@anchor{library/os os stat_result st_type}@anchor{20fe}
@deffn {属性} st_type

文件类型。
@end deffn

在 Windows 系统上，以下属性也可用：

@geindex st_file_attributes (os.stat_result 属性)
@anchor{library/os os stat_result st_file_attributes}@anchor{819}
@deffn {属性} st_file_attributes

Windows 文件属性：@code{dwFileAttributes}，由 @code{GetFileInformationByHandle()} 返回的 @code{BY_HANDLE_FILE_INFORMATION} 结构体的成员之一。请参阅 @ref{f4,,stat} 模块中的 @code{FILE_ATTRIBUTE_*} 常量。
@end deffn

@geindex st_reparse_tag (os.stat_result 属性)
@anchor{library/os os stat_result st_reparse_tag}@anchor{20ff}
@deffn {属性} st_reparse_tag

当 @ref{819,,st_file_attributes} 存在 @code{FILE_ATTRIBUTE_REPARSE_POINT} 集合时，本字段包含重解析点类型标记。请参阅 @ref{f4,,stat} 模块中的 @code{IO_REPARSE_TAG_*} 常量。
@end deffn

标准模块 @ref{f4,,stat} 中定义了函数和常量，这些函数和常量可用于从 @code{stat} 结构体中提取信息。（在 Windows 上，某些项填充的是虚值。）

为了向后兼容，一个 @ref{1208,,stat_result} 实例还可以作为至少包含 10 个整数的元组访问，以提供 @code{stat} 结构中最重要（和可移植）的成员，整数顺序为 @ref{20ea,,st_mode}, @ref{20eb,,st_ino}, @ref{20ec,,st_dev}, @ref{20ed,,st_nlink}, @ref{20ee,,st_uid}, @ref{20ef,,st_gid}, @ref{20f0,,st_size}, @ref{20f1,,st_atime}, @ref{1efd,,st_mtime}, @ref{20f2,,st_ctime}。某些实现可能在末尾还有更多项。为了与旧版 Python 兼容，以元组形式访问 @ref{1208,,stat_result} 始终返回整数。


3.3 新版功能: 添加了 @ref{20f3,,st_atime_ns}、@ref{20f4,,st_mtime_ns} 和 @ref{20f5,,st_ctime_ns} 成员。



3.5 新版功能: 在 Windows 上添加了 @ref{819,,st_file_attributes} 成员。



在 3.5 版更改: 在 Windows 上，如果可用，会返回文件索引作为 @ref{20eb,,st_ino} 的值。



3.7 新版功能: 在 Solaris 及其衍生版本上添加了 @ref{4ce,,st_fstype} 成员。



3.8 新版功能: 在 Windows 上添加了 @ref{20ff,,st_reparse_tag} 成员。



在 3.8 版更改: 在 Windows 上，@ref{20ea,,st_mode} 成员现在可以根据需要将特殊文件标识为 @code{S_IFCHR}、@code{S_IFIFO} 或 @code{S_IFBLK}。

@end deffn

@geindex statvfs() (在 os 模块中)
@anchor{library/os os statvfs}@anchor{b27}
@deffn {函数} os.statvfs (path)

在所给的路径上执行 @code{statvfs()} 系统调用。返回值是一个对象，其属性描述了所给路径上的文件系统，并且与 @code{statvfs} 结构体的成员相对应，即：@code{f_bsize}, @code{f_frsize}, @code{f_blocks}, @code{f_bfree}, @code{f_bavail}, @code{f_files}, @code{f_ffree}, @code{f_favail}, @code{f_flag}, @code{f_namemax}, @code{f_fsid}。

为 @code{f_flag} 属性位定义了两个模块级常量：如果存在 @code{ST_RDONLY} 位，则文件系统以只读挂载；如果存在 @code{ST_NOSUID} 位，则文件系统禁用或不支持 setuid/setgid 位。

为基于 GNU/glibc 的系统还定义了额外的模块级常量。它们是 @code{ST_NODEV} （禁止访问设备专用文件），@code{ST_NOEXEC} （禁止执行程序），@code{ST_SYNCHRONOUS} （写入后立即同步），@code{ST_MANDLOCK} （允许文件系统上的强制锁定），@code{ST_WRITE} （写入文件/目录/符号链接），@code{ST_APPEND} （仅追加文件），@code{ST_IMMUTABLE} （不可变文件），@code{ST_NOATIME} （不更新访问时间），@code{ST_NODIRATIME} （不更新目录访问时间），@code{ST_RELATIME} （相对于 mtime/ctime 更新访问时间）。

本函数支持 @ref{4c4,,指定文件描述符为参数}。

@ref{14c1,,可用性}: Unix。


在 3.2 版更改: 添加了 @code{ST_RDONLY} 和 @code{ST_NOSUID} 常量。



3.3 新版功能: 新增支持将 @emph{path} 参数指定为打开的文件描述符。



在 3.4 版更改: 添加了 @code{ST_NODEV}、@code{ST_NOEXEC}、@code{ST_SYNCHRONOUS}、@code{ST_MANDLOCK}、@code{ST_WRITE}、@code{ST_APPEND}、@code{ST_IMMUTABLE}、@code{ST_NOATIME}、@code{ST_NODIRATIME} 和 @code{ST_RELATIME} 常量。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



3.7 新版功能: 添加了 @code{f_fsid}。

@end deffn

@geindex supports_dir_fd() (在 os 模块中)
@anchor{library/os os supports_dir_fd}@anchor{b23}
@deffn {数据} os.supports_dir_fd

一个 @ref{1f7,,set} 对象，指示 @ref{c4,,os} 模块中的哪些函数接受一个打开的文件描述符作为 @emph{dir_fd} 参数。不同平台提供的功能不同，且 Python 用于实现 @emph{dir_fd} 参数的底层函数并非在 Python 支持的所有平台上都可用。考虑到一致性，支持 @emph{dir_fd} 的函数始终允许指定描述符，但如果在底层不支持时调用了该函数，则会抛出异常。（在所有平台上始终支持将 @emph{dir_fd} 指定为 @code{None}。）

要检查某个函数是否接受打开的文件描述符作为 @emph{dir_fd} 参数，请在 @code{supports_dir_fd} 前使用 @code{in} 运算符。例如，如果 @ref{328,,os.stat()} 在当前平台上接受打开的文件描述符作为 @emph{dir_fd} 参数，则此表达式的计算结果为 @code{True}:

@example
os.stat in os.supports_dir_fd
@end example

目前 @emph{dir_fd} 参数仅在 Unix 平台上有效，在 Windows 上均无效。


3.3 新版功能.

@end deffn

@geindex supports_effective_ids() (在 os 模块中)
@anchor{library/os os supports_effective_ids}@anchor{b29}
@deffn {数据} os.supports_effective_ids

一个 @ref{1f7,,set} 对象，指示 @ref{b16,,os.access()} 是否允许在当前平台上将其 @emph{effective_ids} 参数指定为 @code{True}。（所有平台都支持将 @emph{effective_ids} 指定为 @code{False}。）如果当前平台支持，则集合将包含 @ref{b16,,os.access()}，否则集合为空。

如果当前平台上的 @ref{b16,,os.access()} 支持 @code{effective_ids=True}，则此表达式的计算结果为 @code{True}:

@example
os.access in os.supports_effective_ids
@end example

目前仅 Unix 平台支持 @emph{effective_ids}，Windows 不支持。


3.3 新版功能.

@end deffn

@geindex supports_fd() (在 os 模块中)
@anchor{library/os os supports_fd}@anchor{b28}
@deffn {数据} os.supports_fd

一个 @ref{1f7,,set} 对象，指示在当前平台上 @ref{c4,,os} 模块中的哪些函数接受一个打开的文件描述符作为 @emph{path} 参数。不同平台提供的功能不同，且 Python 所使用到的底层函数（用于实现接受描述符作为 @emph{path}）并非在 Python 支持的所有平台上都可用。

要判断某个函数是否接受打开的文件描述符作为 @emph{path} 参数，请在 @code{supports_fd} 前使用 @code{in} 运算符。例如，如果 @ref{16e,,os.chdir()} 在当前平台上接受打开的文件描述符作为 @emph{path} 参数，则此表达式的计算结果为 @code{True}:

@example
os.chdir in os.supports_fd
@end example


3.3 新版功能.

@end deffn

@geindex supports_follow_symlinks() (在 os 模块中)
@anchor{library/os os supports_follow_symlinks}@anchor{1e2d}
@deffn {数据} os.supports_follow_symlinks

一个 @ref{1f7,,set} 对象，指示在当前平台上 @ref{c4,,os} 模块中的哪些函数的 @emph{follow_symlinks} 参数可指定为 @code{False}。不同平台提供的功能不同，且 Python 用于实现 @emph{follow_symlinks} 的底层函数并非在 Python 支持的所有平台上都可用。考虑到一致性，支持 @emph{follow_symlinks} 的函数始终允许将其指定为 @code{False}，但如果在底层不支持时调用了该函数，则会抛出异常。（在所有平台上始终支持将 @emph{follow_symlinks} 指定为 @code{True}。）

要检查某个函数的 @emph{follow_symlinks} 参数是否可以指定为 @code{False}，请在 @code{supports_follow_symlinks} 前使用 @code{in} 运算符。例如，如果在当前平台上调用 @ref{328,,os.stat()} 时可以指定 @code{follow_symlinks=False}，则此表达式的计算结果为 @code{True}:

@example
os.stat in os.supports_follow_symlinks
@end example


3.3 新版功能.

@end deffn

@geindex symlink() (在 os 模块中)
@anchor{library/os os symlink}@anchor{b20}
@deffn {函数} os.symlink (src, dst, target_is_directory=False, *, dir_fd=None)

创建一个指向 @emph{src} 的符号链接，名为 @emph{dst}。

在 Windows 上，符号链接可以表示文件或目录两种类型，并且不会动态改变类型。如果目标存在，则新建链接的类型将与目标一致。否则，如果 @emph{target_is_directory} 为 @code{True}，则符号链接将创建为目录链接，为 @code{False} （默认）将创建为文件链接。在非 Windows 平台上，@emph{target_is_directory} 被忽略。

本函数支持 @ref{b14,,基于目录描述符的相对路径}。

@cartouche
@quotation 注解 
在 Windows 10 或更高版本上，如果启用了开发人员模式，非特权帐户可以创建符号链接。如果开发人员模式不可用/未启用，则需要 @emph{SeCreateSymbolicLinkPrivilege} 权限，或者该进程必须以管理员身份运行。

当本函数由非特权账户调用时，抛出 @ref{30b,,OSError} 异常。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{os.symlink}，附带参数 @code{src}、@code{dst}、@code{dir_fd}。

@ref{14c1,,可用性}: Unix, Windows。


在 3.2 版更改: 添加对 Windows 6.0 (Vista) 符号链接的支持。



3.3 新版功能: 添加了 @emph{dir_fd} 参数，现在在非 Windows 平台上允许 @emph{target_is_directory} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{src} 和 @emph{dst}。



在 3.8 版更改: 针对启用了开发人员模式的 Windows，添加了非特权账户创建符号链接的支持。

@end deffn

@geindex sync() (在 os 模块中)
@anchor{library/os os sync}@anchor{b3d}
@deffn {函数} os.sync ()

强制将所有内容写入磁盘。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex truncate() (在 os 模块中)
@anchor{library/os os truncate}@anchor{81d}
@deffn {函数} os.truncate (path, length)

截断 @emph{path} 对应的文件，以使其最大为 @emph{length} 字节。

本函数支持 @ref{4c4,,指定文件描述符为参数}。

引发一个 @ref{fec,,审计事件} @code{os.truncate}，附带参数 @code{path}, @code{length}。

@ref{14c1,,可用性}: Unix, Windows。


3.3 新版功能.



在 3.5 版更改: 添加了 Windows 支持



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex unlink() (在 os 模块中)
@anchor{library/os os unlink}@anchor{b21}
@deffn {函数} os.unlink (path, *, dir_fd=None)

移除（删除）文件 @emph{path}。该函数在语义上与 @ref{b1c,,remove()} 相同，@code{unlink} 是其传统的 Unix 名称。请参阅 @ref{b1c,,remove()} 的文档以获取更多信息。

引发一个 @ref{fec,,审计事件} @code{os.remove}，附带参数 @code{path}、@code{dir_fd}。


3.3 新版功能: @emph{dir_fd} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex utime() (在 os 模块中)
@anchor{library/os os utime}@anchor{b22}
@deffn {函数} os.utime (path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)

设置文件 @emph{path} 的访问时间和修改时间。

@ref{b22,,utime()} 有 @emph{times} 和 @emph{ns} 两个可选参数，它们指定了设置给 @emph{path} 的时间，用法如下：


@itemize -

@item 
如果指定 @emph{ns}，它必须是一个 @code{(atime_ns, mtime_ns)} 形式的二元组，其中每个成员都是一个表示纳秒的整数。

@item 
如果 @emph{times} 不为 @code{None}，则它必须是 @code{(atime, mtime)} 形式的二元组，其中每个成员都是一个表示秒的 int 或 float。

@item 
如果 @emph{times} 为 @code{None} 且未指定 @emph{ns}，则相当于指定 @code{ns=(atime_ns, mtime_ns)}，其中两个时间均为当前时间。
@end itemize

同时为 @emph{times} 和 @emph{ns} 指定元组会出错。

注意，根据操作系统记录访问时间和修改时间的分辨率，后续的 @ref{328,,stat()} 调用可能不会返回此处设置的确切时间。请参阅 @ref{328,,stat()}。保留精确时间的最佳方法是使用 @ref{328,,os.stat()} 结果对象中的 @emph{st_atime_ns} 和 @emph{st_mtime_ns} 字段，并将 @emph{ns} 参数设置为 @cite{utime}。

本函数支持 @ref{4c4,,指定文件描述符}、@ref{b14,,指定基于目录描述符的相对路径} 和 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.utime}，附带参数 @code{path}、@code{times}、@code{ns}、@code{dir_fd}。


3.3 新版功能: 新增支持将 @emph{path} 参数指定为打开的文件描述符，以及支持 @emph{dir_fd}、@emph{follow_symlinks} 和 @emph{ns} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex walk() (在 os 模块中)
@anchor{library/os os walk}@anchor{751}
@deffn {函数} os.walk (top, topdown=True, onerror=None, followlinks=False)

@geindex directory; walking
@geindex directory; traversal

生成目录树中的文件名，方式是按上->下或下->上顺序浏览目录树。对于以 @emph{top} 为根的目录树中的每个目录（包括 @emph{top} 本身），它都会生成一个三元组 @code{(dirpath, dirnames, filenames)}。

@emph{dirpath} 是表示目录路径的字符串。 @emph{dirnames} 是 @emph{dirpath} 中子目录名称组成的列表 (excluding @code{'.'} and @code{'..'})。 @emph{filenames} 是 @emph{dirpath} 中非目录文件名称组成的列表。 请注意列表中的名称不带路径部分。 要获取 @emph{dirpath} 中文件或目录的完整路径（以 @emph{top} 打头），请执行 @code{os.path.join(dirpath, name)}。 列表是否排序取决于具体文件系统。 如果有文件或列表生成期间被移除或添加到 @emph{dirpath} 目录中，是否要包括该文件的名称并没有规定。

如果可选参数 @emph{topdown} 为 @code{True} 或未指定，则在所有子目录的三元组之前生成父目录的三元组（目录是自上而下生成的）。如果 @emph{topdown} 为 @code{False}，则在所有子目录的三元组生成之后再生成父目录的三元组（目录是自下而上生成的）。无论 @emph{topdown} 为何值，在生成目录及其子目录的元组之前，都将检索全部子目录列表。

当 @emph{topdown} 为 @code{True} 时，调用者可以就地修改 @emph{dirnames} 列表（也许用到了 @ref{13d1,,del} 或切片），而 @ref{751,,walk()} 将仅仅递归到仍保留在 @emph{dirnames} 中的子目录内。这可用于减少搜索、加入特定的访问顺序，甚至可在继续 @ref{751,,walk()} 之前告知 @ref{751,,walk()} 由调用者新建或重命名的目录的信息。当 @emph{topdown} 为 @code{False} 时，修改 @emph{dirnames} 对 walk 的行为没有影响，因为在自下而上模式中，@emph{dirnames} 中的目录是在 @emph{dirpath} 本身之前生成的。

默认将忽略 @ref{390,,scandir()} 调用中的错误。如果指定了可选参数 @emph{onerror}，它应该是一个函数。出错时它会被调用，参数是一个 @ref{30b,,OSError} 实例。它可以报告错误然后继续遍历，或者抛出异常然后中止遍历。注意，可以从异常对象的 @code{filename} 属性中获取出错的文件名。

@ref{751,,walk()} 默认不会递归进指向目录的符号链接。可以在支持符号链接的系统上将 @emph{followlinks} 设置为 @code{True}，以访问符号链接指向的目录。

@cartouche
@quotation 注解 
注意，如果链接指向自身的父目录，则将 @emph{followlinks} 设置为 @code{True} 可能导致无限递归。@ref{751,,walk()} 不会记录它已经访问过的目录。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果传入的是相对路径，请不要在恢复 @ref{751,,walk()} 之间更改当前工作目录。@ref{751,,walk()} 不会更改当前目录，并假定其调用者也不会更改当前目录。
@end quotation
@end cartouche

下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节数，CVS 子目录不会被遍历:

@example
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
@end example

在下一个示例（@ref{350,,shutil.rmtree()} 的简单实现）中，必须使树自下而上遍历，因为 @ref{b1f,,rmdir()} 只允许在目录为空时删除目录:

@example
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
@end example

引发一个 @ref{fec,,审计事件} @code{os.walk}，附带参数 @code{top}, @code{topdown}, @code{onerror}, @code{followlinks}。


在 3.5 版更改: 现在，本函数调用的是 @ref{390,,os.scandir()} 而不是 @ref{b25,,os.listdir()}，从而减少了调用 @ref{328,,os.stat()} 的次数而变得更快。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex fwalk() (在 os 模块中)
@anchor{library/os os fwalk}@anchor{4c3}
@deffn {函数} os.fwalk (top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)

@geindex directory; walking
@geindex directory; traversal

本方法的行为与 @ref{751,,walk()} 完全一样，除了它产生的是 4 元组 @code{(dirpath, dirnames, filenames, dirfd)}，并且它支持 @code{dir_fd}。

@emph{dirpath}、@emph{dirnames} 和 @emph{filenames} 与 @ref{751,,walk()} 输出的相同，@emph{dirfd} 是指向目录 @emph{dirpath} 的文件描述符。

本函数始终支持 @ref{b14,,基于目录描述符的相对路径} 和 @ref{b15,,不跟踪符号链接}。但是请注意，与其他函数不同，@ref{4c3,,fwalk()} 的 @emph{follow_symlinks} 的默认值为 @code{False}。

@cartouche
@quotation 注解 
由于 @ref{4c3,,fwalk()} 会生成文件描述符，而它们仅在下一个迭代步骤前有效，因此如果要将描述符保留更久，则应复制它们（比如使用 @ref{1132,,dup()}）。
@end quotation
@end cartouche

下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节数，CVS 子目录不会被遍历:

@example
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
    print(root, "consumes", end="")
    print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
          end="")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
@end example

在下一个示例中，必须使树自下而上遍历，因为 @ref{b1f,,rmdir()} 只允许在目录为空时删除目录:

@example
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
    for name in files:
        os.unlink(name, dir_fd=rootfd)
    for name in dirs:
        os.rmdir(name, dir_fd=rootfd)
@end example

引发一个 @ref{fec,,审计事件} @code{os.fwalk}，附带参数 @code{top}, @code{topdown}, @code{onerror}, @code{follow_symlinks}, @code{dir_fd}。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.7 版更改: 添加了对 @ref{172,,bytes} 类型路径的支持。

@end deffn

@geindex memfd_create() (在 os 模块中)
@anchor{library/os os memfd_create}@anchor{327}
@deffn {函数} os.memfd_create (name[, flags=os.MFD_CLOEXEC])

创建一个匿名文件，返回指向该文件的文件描述符。@emph{flags} 必须是系统上可用的 @code{os.MFD_*} 常量之一（或将它们按位“或”组合起来）。新文件描述符默认是 @ref{8f1,,不可继承的}。

@emph{name} 提供的名称会被用作文件名，并且 @code{/proc/self/fd/} 目录中相应符号链接的目标将显示为该名称。显示的名称始终以 @code{memfd:} 为前缀，并且仅用于调试目的。名称不会影响文件描述符的行为，因此多个文件可以有相同的名称，不会有副作用。

@ref{14c1,,可用性}：Linux 3.17 或更高版本，且装有 glibc 2.27 或更高版本。


3.8 新版功能.

@end deffn

@geindex MFD_CLOEXEC() (在 os 模块中)
@geindex MFD_ALLOW_SEALING() (在 os 模块中)
@geindex MFD_HUGETLB() (在 os 模块中)
@geindex MFD_HUGE_SHIFT() (在 os 模块中)
@geindex MFD_HUGE_MASK() (在 os 模块中)
@geindex MFD_HUGE_64KB() (在 os 模块中)
@geindex MFD_HUGE_512KB() (在 os 模块中)
@geindex MFD_HUGE_1MB() (在 os 模块中)
@geindex MFD_HUGE_2MB() (在 os 模块中)
@geindex MFD_HUGE_8MB() (在 os 模块中)
@geindex MFD_HUGE_16MB() (在 os 模块中)
@geindex MFD_HUGE_32MB() (在 os 模块中)
@geindex MFD_HUGE_256MB() (在 os 模块中)
@geindex MFD_HUGE_512MB() (在 os 模块中)
@geindex MFD_HUGE_1GB() (在 os 模块中)
@geindex MFD_HUGE_2GB() (在 os 模块中)
@geindex MFD_HUGE_16GB() (在 os 模块中)
@anchor{library/os os MFD_CLOEXEC}@anchor{2100}
@deffn {数据} os.MFD_CLOEXEC
@anchor{library/os os MFD_ALLOW_SEALING}@anchor{2101}
@deffnx {数据} os.MFD_ALLOW_SEALING
@anchor{library/os os MFD_HUGETLB}@anchor{2102}
@deffnx {数据} os.MFD_HUGETLB
@anchor{library/os os MFD_HUGE_SHIFT}@anchor{2103}
@deffnx {数据} os.MFD_HUGE_SHIFT
@anchor{library/os os MFD_HUGE_MASK}@anchor{2104}
@deffnx {数据} os.MFD_HUGE_MASK
@anchor{library/os os MFD_HUGE_64KB}@anchor{2105}
@deffnx {数据} os.MFD_HUGE_64KB
@anchor{library/os os MFD_HUGE_512KB}@anchor{2106}
@deffnx {数据} os.MFD_HUGE_512KB
@anchor{library/os os MFD_HUGE_1MB}@anchor{2107}
@deffnx {数据} os.MFD_HUGE_1MB
@anchor{library/os os MFD_HUGE_2MB}@anchor{2108}
@deffnx {数据} os.MFD_HUGE_2MB
@anchor{library/os os MFD_HUGE_8MB}@anchor{2109}
@deffnx {数据} os.MFD_HUGE_8MB
@anchor{library/os os MFD_HUGE_16MB}@anchor{210a}
@deffnx {数据} os.MFD_HUGE_16MB
@anchor{library/os os MFD_HUGE_32MB}@anchor{210b}
@deffnx {数据} os.MFD_HUGE_32MB
@anchor{library/os os MFD_HUGE_256MB}@anchor{210c}
@deffnx {数据} os.MFD_HUGE_256MB
@anchor{library/os os MFD_HUGE_512MB}@anchor{210d}
@deffnx {数据} os.MFD_HUGE_512MB
@anchor{library/os os MFD_HUGE_1GB}@anchor{210e}
@deffnx {数据} os.MFD_HUGE_1GB
@anchor{library/os os MFD_HUGE_2GB}@anchor{210f}
@deffnx {数据} os.MFD_HUGE_2GB
@anchor{library/os os MFD_HUGE_16GB}@anchor{2110}
@deffnx {数据} os.MFD_HUGE_16GB

以上标志位可以传递给 @ref{327,,memfd_create()}。

@ref{14c1,,可用性}：Linux 3.17 或更高版本，且装有 glibc 2.27 或更高版本。@code{MFD_HUGE*} 标志仅在 Linux 4.14 及以上可用。


3.8 新版功能.

@end deffn

@menu
* Linux 扩展属性:: 

@end menu

@node Linux 扩展属性,,,文件和目录
@anchor{library/os linux-extended-attributes}@anchor{2111}
@subsubsection Linux 扩展属性



3.3 新版功能.


这些函数仅在 Linux 上可用。

@geindex getxattr() (在 os 模块中)
@anchor{library/os os getxattr}@anchor{b2f}
@deffn {函数} os.getxattr (path, attribute, *, follow_symlinks=True)

返回 @emph{path} 的扩展文件系统属性 @emph{attribute} 的值。@emph{attribute} 可以是 bytes 或 str （直接传入或通过 @ref{5ee,,PathLike} 接口间接传入）。如果是 str，则使用文件系统编码来编码字符串。

本函数支持 @ref{4c4,,指定文件描述符为参数} 和 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.getxattr}，附带参数 @code{path}、@code{attribute}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{path} 和 @emph{attribute}。

@end deffn

@geindex listxattr() (在 os 模块中)
@anchor{library/os os listxattr}@anchor{b30}
@deffn {函数} os.listxattr (path=None, *, follow_symlinks=True)

返回一个列表，包含 @emph{path} 的所有扩展文件系统属性。列表中的属性都表示为字符串，它们是根据文件系统编码解码出来的。如果 @emph{path} 为 @code{None}，则 @ref{b30,,listxattr()} 将检查当前目录。

本函数支持 @ref{4c4,,指定文件描述符为参数} 和 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.listxattr}，附带参数 @code{path}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex removexattr() (在 os 模块中)
@anchor{library/os os removexattr}@anchor{b31}
@deffn {函数} os.removexattr (path, attribute, *, follow_symlinks=True)

从 @emph{path} 中删除扩展文件系统属性 @emph{attribute}。@emph{attribute} 应该是 bytes 或 str （直接传入或通过 @ref{5ee,,PathLike} 接口间接传入）。如果是 str，则使用文件系统编码来编码字符串。

本函数支持 @ref{4c4,,指定文件描述符为参数} 和 @ref{b15,,不跟踪符号链接}。

引发一个 @ref{fec,,审计事件} @code{os.removexattr}，附带参数 @code{path}、@code{attribute}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{path} 和 @emph{attribute}。

@end deffn

@geindex setxattr() (在 os 模块中)
@anchor{library/os os setxattr}@anchor{b32}
@deffn {函数} os.setxattr (path, attribute, value, flags=0, *, follow_symlinks=True)

将 @emph{path} 的扩展文件系统属性 @emph{attribute} 设为 @emph{value}。 @emph{attribute} 必须是没有内嵌 NUL 的字节串或字符串（直接或通过 @ref{5ee,,PathLike} 间接传入）。 如果是字符串，则使用文件系统编码格式进行编码。 @emph{flags} 可以为 @ref{2112,,XATTR_REPLACE} 或 @ref{2113,,XATTR_CREATE}。 如果指定 @ref{2112,,XATTR_REPLACE} 而该属性不存在，则将引发 @code{ENODATA}。 如果指定 @ref{2113,,XATTR_CREATE} 而该属性已存在，则将不创建该属性并将引发 @code{EEXISTS}。

本函数支持 @ref{4c4,,指定文件描述符为参数} 和 @ref{b15,,不跟踪符号链接}。

@cartouche
@quotation 注解 
Linux kernel 2.6.39 以下版本的一个 bug 导致在某些文件系统上，flags 参数会被忽略。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{os.setxattr}，附带参数 @code{path}、@code{attribute}、@code{value}、@code{flags}。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象} 作为 @emph{path} 和 @emph{attribute}。

@end deffn

@geindex XATTR_SIZE_MAX() (在 os 模块中)
@anchor{library/os os XATTR_SIZE_MAX}@anchor{2114}
@deffn {数据} os.XATTR_SIZE_MAX

一条扩展属性的值的最大大小。在当前的 Linux 上是 64 KiB。
@end deffn

@geindex XATTR_CREATE() (在 os 模块中)
@anchor{library/os os XATTR_CREATE}@anchor{2113}
@deffn {数据} os.XATTR_CREATE

这是 @ref{b32,,setxattr()} 的 flags 参数的可取值，它表示该操作必须创建一个属性。
@end deffn

@geindex XATTR_REPLACE() (在 os 模块中)
@anchor{library/os os XATTR_REPLACE}@anchor{2112}
@deffn {数据} os.XATTR_REPLACE

这是 @ref{b32,,setxattr()} 的 flags 参数的可取值，它表示该操作必须替换现有属性。
@end deffn

@node 进程管理,调度器接口,文件和目录,os --- 多种操作系统接口
@anchor{library/os os-process}@anchor{2115}@anchor{library/os process-management}@anchor{2116}
@subsubsection 进程管理


下列函数可用于创建和管理进程。

所有 @ref{2117,,exec*} 函数都接受一个参数列表，用来给新程序加载到它的进程中。在所有情况下，传递给新程序的第一个参数是程序本身的名称，而不是用户在命令行上输入的参数。对于 C 程序员来说，这就是传递给 @code{main()} 函数的 @code{argv[0]}。例如，@code{os.execv('/bin/echo', ['foo', 'bar'])} 只会在标准输出上打印 @code{bar}，而 @code{foo} 会被忽略。

@geindex abort() (在 os 模块中)
@anchor{library/os os abort}@anchor{2118}
@deffn {函数} os.abort ()

发送 @code{SIGABRT} 信号到当前进程。在 Unix 上，默认行为是生成一个核心转储。在 Windows 上，该进程立即返回退出代码 @code{3}。请注意，使用 @ref{b61,,signal.signal()} 可以为 @code{SIGABRT} 注册 Python 信号处理程序，而调用本函数将不会调用按前述方法注册的程序。
@end deffn

@geindex add_dll_directory() (在 os 模块中)
@anchor{library/os os add_dll_directory}@anchor{2fa}
@deffn {函数} os.add_dll_directory (path)

将路径添加到 DLL 搜索路径。

当需要解析扩展模块的依赖时（扩展模块本身通过 @ref{262,,sys.path} 解析），会使用该搜索路径，@ref{2a,,ctypes} 也会使用该搜索路径。

要移除目录，可以在返回的对象上调用 @strong{close()}，也可以在 @ref{7e4,,with} 语句内使用本方法。

参阅 Microsoft 文档@footnote{https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5} 获取如何加载 DLL 的信息。

引发一个 @ref{fec,,审计事件} @code{os.add_dll_directory}，附带参数 @code{path}。

@ref{14c1,,可用性}: Windows。


3.8 新版功能: 早期版本的 CPython 解析 DLL 时用的是当前进程的默认行为。这会导致不一致，比如不是每次都会去搜索 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 和当前工作目录，且系统函数（如 @code{AddDllDirectory} ）失效。

在 3.8 中，DLL 的两种主要加载方式现在可以显式覆盖进程的行为，以确保一致性。请参阅 @ref{3f4,,移植说明} 了解如何更新你的库。

@end deffn

@geindex execl() (在 os 模块中)
@geindex execle() (在 os 模块中)
@geindex execlp() (在 os 模块中)
@geindex execlpe() (在 os 模块中)
@geindex execv() (在 os 模块中)
@geindex execve() (在 os 模块中)
@geindex execvp() (在 os 模块中)
@geindex execvpe() (在 os 模块中)
@anchor{library/os os execl}@anchor{2117}
@deffn {函数} os.execl (path, arg0, arg1, ...)
@anchor{library/os os execle}@anchor{2119}
@deffnx {函数} os.execle (path, arg0, arg1, ..., env)
@anchor{library/os os execlp}@anchor{211a}
@deffnx {函数} os.execlp (file, arg0, arg1, ...)
@anchor{library/os os execlpe}@anchor{211b}
@deffnx {函数} os.execlpe (file, arg0, arg1, ..., env)
@anchor{library/os os execv}@anchor{2089}
@deffnx {函数} os.execv (path, args)
@anchor{library/os os execve}@anchor{b24}
@deffnx {函数} os.execve (path, args, env)
@anchor{library/os os execvp}@anchor{211c}
@deffnx {函数} os.execvp (file, args)
@anchor{library/os os execvpe}@anchor{211d}
@deffnx {函数} os.execvpe (file, args, env)

这些函数都将执行一个新程序，以替换当前进程。它们没有返回值。在 Unix 上，新程序会加载到当前进程中，且进程号与调用者相同。过程中的错误会被报告为 @ref{30b,,OSError} 异常。

当前进程会被立即替换。打开的文件对象和描述符都不会刷新，因此如果这些文件上可能缓冲了数据，则应在调用 @ref{2117,,exec*} 函数之前使用 @code{sys.stdout.flush()} 或 @ref{75e,,os.fsync()} 刷新它们。

@ref{2117,,exec*} 函数的 "l" 和 "v" 变体不同在于命令行参数的传递方式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数作为 @code{execl*()} 函数的附加参数传入即可。当参数数量可变时，"v" 变体更方便，参数以列表或元组的形式作为 @emph{args} 参数传递。在这两种情况下，子进程的第一个参数都应该是即将运行的命令名称，但这不是强制性的。

结尾包含 "p" 的变体（@ref{211a,,execlp()}、@ref{211b,,execlpe()}、@ref{211c,,execvp()} 和 @ref{211d,,execvpe()} ）将使用 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量来查找程序 @emph{file}。当环境被替换时（使用下一段讨论的 @ref{2117,,exec*e} 变体之一），
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 变量将来自于新环境。其他变体 @ref{2117,,execl()}、@ref{2119,,execle()}、@ref{2089,,execv()} 和 @ref{b24,,execve()} 不使用 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 变量来查找程序，因此 @emph{path} 必须包含正确的绝对或相对路径。

对于 @ref{2119,,execle()}、@ref{211b,,execlpe()}、@ref{b24,,execve()} 和 @ref{211d,,execvpe()} （都以 "e" 结尾），@emph{env} 参数是一个映射，用于定义新进程的环境变量（代替当前进程的环境变量）。而函数 @ref{2117,,execl()}、@ref{211a,,execlp()}、@ref{2089,,execv()} 和 @ref{211c,,execvp()} 会将当前进程的环境变量过继给新进程。

某些平台上的 @ref{b24,,execve()} 可以将 @emph{path} 指定为打开的文件描述符。当前平台可能不支持此功能，可以使用 @ref{b28,,os.supports_fd} 检查它是否支持。如果不可用，则使用它会抛出 @ref{70e,,NotImplementedError} 异常。

引发一个 @ref{fec,,审计事件} @code{os.exec}，附带参数 @code{path}、@code{args}、@code{env}。

@ref{14c1,,可用性}: Unix, Windows。


3.3 新版功能: 新增支持将 @ref{b24,,execve()} 的 @emph{path} 参数指定为打开的文件描述符。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex _exit() (在 os 模块中)
@anchor{library/os os _exit}@anchor{188f}
@deffn {函数} os._exit (n)

以状态码 @emph{n} 退出进程，不会调用清理处理程序，不会刷新 stdio，等等。

@cartouche
@quotation 注解 
退出的标准方法是使用 @code{sys.exit(n)}。而 @ref{188f,,_exit()} 通常只应在 @ref{a4b,,fork()} 出的子进程中使用。
@end quotation
@end cartouche
@end deffn

以下是已定义的退出代码，可以用于 @ref{188f,,_exit()}，尽管它们不是必需的。这些退出代码通常用于 Python 编写的系统程序，例如邮件服务器的外部命令传递程序。

@cartouche
@quotation 注解 
其中部分退出代码在部分 Unix 平台上可能不可用，因为平台间存在差异。如果底层平台定义了这些常量，那上层也会定义。
@end quotation
@end cartouche

@geindex EX_OK() (在 os 模块中)
@anchor{library/os os EX_OK}@anchor{211e}
@deffn {数据} os.EX_OK

退出代码，表示未发生任何错误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_USAGE() (在 os 模块中)
@anchor{library/os os EX_USAGE}@anchor{211f}
@deffn {数据} os.EX_USAGE

退出代码，表示命令使用不正确，如给出的参数数量有误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_DATAERR() (在 os 模块中)
@anchor{library/os os EX_DATAERR}@anchor{2120}
@deffn {数据} os.EX_DATAERR

退出代码，表示输入数据不正确。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_NOINPUT() (在 os 模块中)
@anchor{library/os os EX_NOINPUT}@anchor{2121}
@deffn {数据} os.EX_NOINPUT

退出代码，表示某个输入文件不存在或不可读。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_NOUSER() (在 os 模块中)
@anchor{library/os os EX_NOUSER}@anchor{2122}
@deffn {数据} os.EX_NOUSER

退出代码，表示指定的用户不存在。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_NOHOST() (在 os 模块中)
@anchor{library/os os EX_NOHOST}@anchor{2123}
@deffn {数据} os.EX_NOHOST

退出代码，表示指定的主机不存在。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_UNAVAILABLE() (在 os 模块中)
@anchor{library/os os EX_UNAVAILABLE}@anchor{2124}
@deffn {数据} os.EX_UNAVAILABLE

退出代码，表示所需的服务不可用。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_SOFTWARE() (在 os 模块中)
@anchor{library/os os EX_SOFTWARE}@anchor{2125}
@deffn {数据} os.EX_SOFTWARE

退出代码，表示检测到内部软件错误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_OSERR() (在 os 模块中)
@anchor{library/os os EX_OSERR}@anchor{2126}
@deffn {数据} os.EX_OSERR

退出代码，表示检测到操作系统错误，例如无法 fork 或创建管道。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_OSFILE() (在 os 模块中)
@anchor{library/os os EX_OSFILE}@anchor{2127}
@deffn {数据} os.EX_OSFILE

退出代码，表示某些系统文件不存在、无法打开或发生其他错误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_CANTCREAT() (在 os 模块中)
@anchor{library/os os EX_CANTCREAT}@anchor{2128}
@deffn {数据} os.EX_CANTCREAT

退出代码，表示无法创建用户指定的输出文件。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_IOERR() (在 os 模块中)
@anchor{library/os os EX_IOERR}@anchor{2129}
@deffn {数据} os.EX_IOERR

退出代码，表示对某些文件进行读写时发生错误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_TEMPFAIL() (在 os 模块中)
@anchor{library/os os EX_TEMPFAIL}@anchor{212a}
@deffn {数据} os.EX_TEMPFAIL

退出代码，表示发生了暂时性故障。它可能并非意味着真正的错误，例如在可重试的情况下无法建立网络连接。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_PROTOCOL() (在 os 模块中)
@anchor{library/os os EX_PROTOCOL}@anchor{212b}
@deffn {数据} os.EX_PROTOCOL

退出代码，表示协议交换是非法的、无效的或无法解读的。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_NOPERM() (在 os 模块中)
@anchor{library/os os EX_NOPERM}@anchor{212c}
@deffn {数据} os.EX_NOPERM

退出代码，表示没有足够的权限执行该操作（但不适用于文件系统问题）。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_CONFIG() (在 os 模块中)
@anchor{library/os os EX_CONFIG}@anchor{212d}
@deffn {数据} os.EX_CONFIG

退出代码，表示发生某种配置错误。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex EX_NOTFOUND() (在 os 模块中)
@anchor{library/os os EX_NOTFOUND}@anchor{212e}
@deffn {数据} os.EX_NOTFOUND

退出代码，表示的内容类似于“找不到条目”。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex fork() (在 os 模块中)
@anchor{library/os os fork}@anchor{a4b}
@deffn {函数} os.fork ()

Fork 出一个子进程。在子进程中返回 @code{0}，在父进程中返回子进程的进程号。如果发生错误，则抛出 @ref{30b,,OSError} 异常。

注意，当从线程中使用 @code{fork()} 时，某些平台（包括 FreeBSD <= 6.3 和 Cygwin）存在已知问题。

引发一个 @ref{fec,,审计事件} @code{os.fork}，没有附带参数。


在 3.8 版更改: 不再支持在子解释器中调用 @code{fork()} （将抛出 @ref{3e4,,RuntimeError} 异常）。


@cartouche
@quotation 警告 
有关 SSL 模块与 fork() 结合的应用，请参阅 @ref{f3,,ssl}。
@end quotation
@end cartouche

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex forkpty() (在 os 模块中)
@anchor{library/os os forkpty}@anchor{212f}
@deffn {函数} os.forkpty ()

Fork 出一个子进程，使用新的伪终端作为子进程的控制终端。返回一对 @code{(pid, fd)}，其中 @emph{pid} 在子进程中为 @code{0}，这是父进程中新子进程的进程号，而 @emph{fd} 是伪终端主设备的文件描述符。对于更便于移植的方法，请使用 @ref{d5,,pty} 模块。如果发生错误，则抛出 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{os.forkpty}，没有附带参数。


在 3.8 版更改: 不再支持在子解释器中调用 @code{forkpty()} （将抛出 @ref{3e4,,RuntimeError} 异常）。


@ref{14c1,,可用性}: 某些 Unix。
@end deffn

@geindex kill() (在 os 模块中)
@anchor{library/os os kill}@anchor{dc1}
@deffn {函数} os.kill (pid, sig)

@geindex process; killing
@geindex process; signalling

将信号 @emph{sig} 发送至进程 @emph{pid}。特定平台上可用的信号常量定义在 @ref{ea,,signal} 模块中。

Windows： @ref{2130,,signal.CTRL_C_EVENT} 和 @ref{2131,,signal.CTRL_BREAK_EVENT} 信号是特殊信号，只能发送给共享同一个控制台窗口的控制台进程，如某些子进程。@emph{sig} 取任何其他值将导致该进程被 TerminateProcess API 无条件终止，且退出代码为 @emph{sig}。Windows 版本的 @ref{dc1,,kill()} 还需要传入待结束进程的句柄。

另请参阅 @ref{b5e,,signal.pthread_kill()}。

引发一个 @ref{fec,,审计事件} @code{os.kill}，附带参数 @code{pid}、@code{sig}。


3.2 新版功能: Windows 支持。

@end deffn

@geindex killpg() (在 os 模块中)
@anchor{library/os os killpg}@anchor{112a}
@deffn {函数} os.killpg (pgid, sig)

@geindex process; killing
@geindex process; signalling

将信号 @emph{sig} 发送给进程组 @emph{pgid}。

引发一个 @ref{fec,,审计事件} @code{os.killpg}，附带参数 @code{pgid}、@code{sig}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex nice() (在 os 模块中)
@anchor{library/os os nice}@anchor{b2c}
@deffn {函数} os.nice (increment)

将进程的优先级（nice 值）增加 @emph{increment}，返回新的 nice 值。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex pidfd_open() (在 os 模块中)
@anchor{library/os os pidfd_open}@anchor{158}
@deffn {函数} os.pidfd_open (pid, flags=0)

返回一个文件描述符，它指向进程 @emph{pid}。该描述符可用于管理进程，避免出现竞争和信号。@emph{flags} 参数提供给将来扩展使用，当前没有定义标志值。

更多详细信息请参阅 @code{pidfd_open(2)} 手册页。

@ref{14c1,,可用性}: Linux 5.3+。


3.9 新版功能.

@end deffn

@geindex plock() (在 os 模块中)
@anchor{library/os os plock}@anchor{2132}
@deffn {函数} os.plock (op)

将程序段锁定到内存中。@emph{op} 的值（定义在 @code{<sys/lock.h>} 中）决定了哪些段被锁定。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex popen() (在 os 模块中)
@anchor{library/os os popen}@anchor{3d3}
@deffn {函数} os.popen (cmd, mode='r', buffering=-1)

打开一个管道，它通往 / 接受自命令 @emph{cmd}。返回值是连接到管道的文件对象，根据 @emph{mode} 是 @code{'r'} （默认）还是 @code{'w'} 决定该对象可以读取还是写入。@emph{buffering} 参数与内置函数 @ref{16f,,open()} 相应的参数含义相同。返回的文件对象只能读写文本字符串，不能是字节类型。

如果子进程成功退出，则 @code{close} 方法返回 @ref{204,,None}。如果发生错误，则返回子进程的返回码。在 POSIX 系统上，如果返回码为正，则它就是进程返回值左移一个字节后的值。如果返回码为负，则进程是被信号终止的，返回码取反后就是该信号。（例如，如果子进程被终止，则返回值可能是 @code{- signal.SIGKILL}。）在 Windows 系统上，返回值包含子进程的返回码（有符号整数）。

在 Unix 上，@ref{1cf,,waitstatus_to_exitcode()} 可以将 @code{close} 方法的返回值（即退出状态，不能是 @code{None}）转换为退出码。在 Windows 上，@code{close} 方法的结果直接就是退出码（或 @code{None} ）。

本方法是使用 @ref{3e3,,subprocess.Popen} 实现的，如需更强大的方法来管理和沟通子进程，请参阅该类的文档。
@end deffn

@geindex posix_spawn() (在 os 模块中)
@anchor{library/os os posix_spawn}@anchor{388}
@deffn {函数} os.posix_spawn (path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

包装 @code{posix_spawn()} C 库 API，使其可以从 Python 调用。

大多数用户应使用 @ref{4fb,,subprocess.run()} 代替 @ref{388,,posix_spawn()}。

仅位置参数 (Positional-only arguments) @emph{path}、@emph{args} 和 @emph{env} 与 @ref{b24,,execve()} 中的类似。

@emph{path} 形参是可执行文件的路径，@emph{path} 中应当包含目录。 使用 @ref{1196,,posix_spawnp()} 可传入不带目录的可执行文件。

@emph{file_actions} 参数可以是由元组组成的序列，序列描述了对子进程中指定文件描述符采取的操作，这些操作会在 C 库实现的 @code{fork()} 和 @code{exec()} 步骤间完成。每个元组的第一个元素必须是下面列出的三个类型指示符之一，用于描述元组剩余的元素：

@geindex POSIX_SPAWN_OPEN() (在 os 模块中)
@anchor{library/os os POSIX_SPAWN_OPEN}@anchor{2133}
@deffn {数据} os.POSIX_SPAWN_OPEN

(@code{os.POSIX_SPAWN_OPEN}, @emph{fd}, @emph{path}, @emph{flags}, @emph{mode})

执行 @code{os.dup2(os.open(path, flags, mode), fd)}。
@end deffn

@geindex POSIX_SPAWN_CLOSE() (在 os 模块中)
@anchor{library/os os POSIX_SPAWN_CLOSE}@anchor{2134}
@deffn {数据} os.POSIX_SPAWN_CLOSE

(@code{os.POSIX_SPAWN_CLOSE}, @emph{fd})

执行 @code{os.close(fd)}。
@end deffn

@geindex POSIX_SPAWN_DUP2() (在 os 模块中)
@anchor{library/os os POSIX_SPAWN_DUP2}@anchor{2135}
@deffn {数据} os.POSIX_SPAWN_DUP2

(@code{os.POSIX_SPAWN_DUP2}, @emph{fd}, @emph{new_fd})

执行 @code{os.dup2(fd, new_fd)}。
@end deffn

这些元组对应于 C 库 @code{posix_spawn_file_actions_addopen()}， @code{posix_spawn_file_actions_addclose()} 和 @code{posix_spawn_file_actions_adddup2()} API 调用，它们为调用 @code{posix_spawn()} 自身做准备。

@emph{setpgroup} 参数将子进程的进程组设置为指定值。如果指定值为 0，则子进程的进程组 ID 将与其进程 ID 相同。如果未设置 @emph{setpgroup} 值，则子进程将继承父进程的进程组 ID。本参数对应于 C 库 @code{POSIX_SPAWN_SETPGROUP} 标志。

如果 @emph{resetids} 参数为 @code{True}，则会将子进程的有效用户 ID 和有效组 ID 重置为父进程的实际用户 ID 和实际组 ID。如果该参数为 @code{False}，则子进程保留父进程的有效用户 ID 和有效组 ID。无论哪种情况，若在可执行文件上启用了 “设置用户 ID” 和 “设置组 ID” 权限位，它们将覆盖有效用户 ID 和有效组 ID 的设置。本参数对应于 C 库 @code{POSIX_SPAWN_RESETIDS} 标志。

如果 @emph{setsid} 参数为 @code{True}，它将为 @cite{posix_spawn} 新建一个会话 ID。@emph{setsid} 需要 @code{POSIX_SPAWN_SETSID} 或 @code{POSIX_SPAWN_SETSID_NP} 标志，否则会抛出 @ref{70e,,NotImplementedError} 异常。

@emph{setsigmask} 参数将信号掩码设置为指定的信号集合。如果未使用该参数，则子进程将继承父进程的信号掩码。本参数对应于 C 库 @code{POSIX_SPAWN_SETSIGMASK} 标志。

@emph{sigdef} 参数将集合中所有信号的操作全部重置为默认。本参数对应于 C 库 @code{POSIX_SPAWN_SETSIGDEF} 标志。

@emph{scheduler} 参数必须是一个元组，其中包含调度器策略（可选）以及携带了调度器参数的 @ref{2136,,sched_param} 实例。在调度器策略所在位置为 @code{None} 表示未提供该值。本参数是 C 库 @code{POSIX_SPAWN_SETSCHEDPARAM} 和 @code{POSIX_SPAWN_SETSCHEDULER} 标志的组合。

引发一个 @ref{fec,,审计事件} @code{os.posix_spawn}，附带参数 @code{path}、@code{argv}、@code{env}。


3.8 新版功能.


@ref{14c1,,可用性}: Unix。
@end deffn

@geindex posix_spawnp() (在 os 模块中)
@anchor{library/os os posix_spawnp}@anchor{1196}
@deffn {函数} os.posix_spawnp (path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

包装 @code{posix_spawnp()} C 库 API，使其可以从 Python 调用。

与 @ref{388,,posix_spawn()} 相似，但是系统会在 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量指定的目录列表中搜索可执行文件 @emph{executable} （与 @code{execvp(3)} 相同）。

引发一个 @ref{fec,,审计事件} @code{os.posix_spawn}，附带参数 @code{path}、@code{argv}、@code{env}。


3.8 新版功能.


@ref{14c1,,可用性}: 请参阅 @ref{388,,posix_spawn()} 文档。
@end deffn

@geindex register_at_fork() (在 os 模块中)
@anchor{library/os os register_at_fork}@anchor{4c5}
@deffn {函数} os.register_at_fork (*, before=None, after_in_parent=None, after_in_child=None)

注册可调用对象，在使用 @ref{a4b,,os.fork()} 或类似的进程克隆 API 派生新的子进程时，这些对象会运行。参数是可选的，且为仅关键字 (Keyword-only) 参数。每个参数指定一个不同的调用点。


@itemize *

@item 
@emph{before} 是一个函数，在 fork 子进程前调用。

@item 
@emph{after_in_parent} 是一个函数，在 fork 子进程后从父进程调用。

@item 
@emph{after_in_child} 是一个函数，从子进程中调用。
@end itemize

只有希望控制权回到 Python 解释器时，才进行这些调用。典型的 @ref{f9,,子进程} 启动时不会触发它们，因为子进程不会重新进入解释器。

在注册的函数中，用于 fork 前运行的函数将按与注册相反的顺序调用。用于 fork 后（从父进程或子进程）运行的函数按注册顺序调用。

注意，第三方 C 代码的 @code{fork()} 调用可能不会调用这些函数，除非它显式调用了 @ref{53e,,PyOS_BeforeFork()}、@ref{53f,,PyOS_AfterFork_Parent()} 和 @ref{3f8,,PyOS_AfterFork_Child()}。

函数注册后无法注销。

@ref{14c1,,可用性}: Unix。


3.7 新版功能.

@end deffn

@geindex spawnl() (在 os 模块中)
@geindex spawnle() (在 os 模块中)
@geindex spawnlp() (在 os 模块中)
@geindex spawnlpe() (在 os 模块中)
@geindex spawnv() (在 os 模块中)
@geindex spawnve() (在 os 模块中)
@geindex spawnvp() (在 os 模块中)
@geindex spawnvpe() (在 os 模块中)
@anchor{library/os os spawnl}@anchor{20d3}
@deffn {函数} os.spawnl (mode, path, ...)
@anchor{library/os os spawnle}@anchor{2137}
@deffnx {函数} os.spawnle (mode, path, ..., env)
@anchor{library/os os spawnlp}@anchor{2138}
@deffnx {函数} os.spawnlp (mode, file, ...)
@anchor{library/os os spawnlpe}@anchor{2139}
@deffnx {函数} os.spawnlpe (mode, file, ..., env)
@anchor{library/os os spawnv}@anchor{213a}
@deffnx {函数} os.spawnv (mode, path, args)
@anchor{library/os os spawnve}@anchor{213b}
@deffnx {函数} os.spawnve (mode, path, args, env)
@anchor{library/os os spawnvp}@anchor{213c}
@deffnx {函数} os.spawnvp (mode, file, args)
@anchor{library/os os spawnvpe}@anchor{213d}
@deffnx {函数} os.spawnvpe (mode, file, args, env)

在新进程中执行程序 @emph{path}。

（注意，@ref{f9,,subprocess} 模块提供了更强大的工具来生成新进程并跟踪执行结果，使用该模块比使用这些函数更好。尤其应当检查 @ref{bca,,使用 subprocess 模块替换旧函数} 部分。）

@emph{mode} 为 @ref{213e,,P_NOWAIT} 时，本函数返回新进程的进程号。@emph{mode} 为 @ref{213f,,P_WAIT} 时，如果进程正常退出，返回退出代码，如果被终止，返回 @code{-signal}，其中 @emph{signal} 是终止进程的信号。在 Windows 上，进程号实际上是进程句柄，因此可以与 @ref{76a,,waitpid()} 函数一起使用。

注意在 VxWorks 上，新进程被终止时，本函数不会返回 @code{-signal}，而是会抛出 OSError 异常。

@ref{20d3,,spawn*} 函数的 "l" 和 "v" 变体不同在于命令行参数的传递方式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数作为 @code{spawnl*()} 函数的附加参数传入即可。当参数数量可变时，"v" 变体更方便，参数以列表或元组的形式作为 @emph{args} 参数传递。在这两种情况下，子进程的第一个参数都必须是即将运行的命令名称。

结尾包含第二个 "p" 的变体（@ref{2138,,spawnlp()}、@ref{2139,,spawnlpe()}、@ref{213c,,spawnvp()} 和 @ref{213d,,spawnvpe()}）将使用 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量来查找程序 @emph{file}。当环境被替换时（使用下一段讨论的 @ref{20d3,,spawn*e} 变体之一），
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 变量将来自于新环境。其他变体 @ref{20d3,,spawnl()}、@ref{2137,,spawnle()}、@ref{213a,,spawnv()} 和 @ref{213b,,spawnve()} 不使用 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 变量来查找程序，因此 @emph{path} 必须包含正确的绝对或相对路径。

对于 @ref{2137,,spawnle()}、@ref{2139,,spawnlpe()}、@ref{213b,,spawnve()} 和 @ref{213d,,spawnvpe()} （都以 "e" 结尾），@emph{env} 参数是一个映射，用于定义新进程的环境变量（代替当前进程的环境变量）。而函数 @ref{20d3,,spawnl()}、@ref{2138,,spawnlp()}、@ref{213a,,spawnv()} 和 @ref{213c,,spawnvp()} 会将当前进程的环境变量过继给新进程。注意，@emph{env} 字典中的键和值必须是字符串。无效的键或值将导致函数出错，返回值为 @code{127}。

例如，以下对 @ref{2138,,spawnlp()} 和 @ref{213d,,spawnvpe()} 的调用是等效的:

@example
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
@end example

引发一个 @ref{fec,,审计事件} @code{os.spawn}，附带参数 @code{mode}、@code{path}、@code{args}、@code{env}。

@ref{14c1,,可用性}: Unix, Windows。@ref{2138,,spawnlp()}、@ref{2139,,spawnlpe()}、@ref{213c,,spawnvp()} 和 @ref{213d,,spawnvpe()} 在 Windows 上不可用。@ref{2137,,spawnle()} 和 @ref{213b,,spawnve()} 在 Windows 上不是线程安全的，建议使用 @ref{f9,,subprocess} 模块替代。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex P_NOWAIT() (在 os 模块中)
@geindex P_NOWAITO() (在 os 模块中)
@anchor{library/os os P_NOWAIT}@anchor{213e}
@deffn {数据} os.P_NOWAIT
@anchor{library/os os P_NOWAITO}@anchor{2140}
@deffnx {数据} os.P_NOWAITO

@ref{20d3,,spawn*} 系列函数的 @emph{mode} 参数的可取值。如果给出这些值中的任何一个，则 @code{spawn*()} 函数将在创建新进程后立即返回，且返回值为进程号。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex P_WAIT() (在 os 模块中)
@anchor{library/os os P_WAIT}@anchor{213f}
@deffn {数据} os.P_WAIT

@ref{20d3,,spawn*} 系列函数的 @emph{mode} 参数的可取值。如果将 @emph{mode} 指定为该值，则 @code{spawn*()} 函数将在新进程运行完毕后返回，运行成功则返回进程的退出代码，被信号终止则返回 @code{-signal}。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex P_DETACH() (在 os 模块中)
@geindex P_OVERLAY() (在 os 模块中)
@anchor{library/os os P_DETACH}@anchor{2141}
@deffn {数据} os.P_DETACH
@anchor{library/os os P_OVERLAY}@anchor{2142}
@deffnx {数据} os.P_OVERLAY

@ref{20d3,,spawn*} 系列函数的 @emph{mode} 参数的可取值。它们比上面列出的值可移植性差。@ref{2141,,P_DETACH} 与 @ref{213e,,P_NOWAIT} 相似，但是新进程会与父进程的控制台脱离。使用 @ref{2142,,P_OVERLAY} 则会替换当前进程，@ref{20d3,,spawn*} 函数将不会返回。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex startfile() (在 os 模块中)
@anchor{library/os os startfile}@anchor{2143}
@deffn {函数} os.startfile (path[, operation])

使用已关联的应用程序打开文件。

当 @emph{operation} 未指定或指定为 @code{'open'} 时，这类似于在 Windows 资源管理器中双击文件，或在交互式命令行中将文件名作为 @code{start} 命令的参数：通过扩展名相关联的应用程序（如果有）打开文件。

当指定另一个 @emph{operation} 时，它必须是一个“命令动词” ("command verb")，该词指定对文件执行的操作。Microsoft 文档中的常用动词有 @code{'print'} 和 @code{'edit'} （用于文件），以及 @code{'explore'} 和 @code{'find'} （用于目录）。

关联的应用程序启动后 @ref{2143,,startfile()} 就会立即返回。 本函数没有等待应用程序关闭的选项，也没有办法检索应用程序的退出状态。 @emph{path} 形参是基于当前目录的相对路径。 如果要使用绝对路径，请确保第一个字符不是斜杠 (@code{'/'})；如果是斜杠的话则底层的 Win32 @code{ShellExecute()} 函数将失效。 请使用 @ref{d7f,,os.path.normpath()} 函数来确保路径已针对 Win32 正确编码。

为了减少解释器的启动开销，直到第一次调用本函数后，才解析 Win32 @code{ShellExecute()} 函数。如果无法解析该函数​​，则抛出 @ref{70e,,NotImplementedError} 异常。

引发一个 @ref{fec,,审计事件} @code{os.startfile}，附带参数 @code{path}、@code{operation}。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex system() (在 os 模块中)
@anchor{library/os os system}@anchor{e8e}
@deffn {函数} os.system (command)

在子外壳程序中执行此命令（一个字符串）。 这是通过调用标准 C 函数 @code{system()} 来实现的，并受到同样的限制。 对 @ref{427,,sys.stdin} 的更改等不会反映在所执行命令的环境中。 如果 @emph{command} 生成了任何输出，它将被发送到解释器的标准输出流。 C 标准没有指明这个 C 函数返回值的含义，因此这个 Python 函数的返回值取决于具体系统。

在 Unix 上，返回值为进程的退出状态，以针对 @ref{768,,wait()} 而指定的格式进行编码。

在 Windows 上，返回值是运行 @emph{command} 后系统 Shell 返回的值。该 Shell 由 Windows 环境变量 
@geindex COMSPEC
@geindex 环境变量; COMSPEC
@code{COMSPEC}: 给出：通常是 @code{cmd.exe}，它会返回命令的退出状态。在使用非原生 Shell 的系统上，请查阅 Shell 的文档。

@ref{f9,,subprocess} 模块提供了更强大的工具来生成新进程并跟踪执行结果，使用该模块比使用本函数更好。参阅 @ref{f9,,subprocess} 文档中的 @ref{bca,,使用 subprocess 模块替换旧函数} 部分以获取有用的帮助。

在 Unix 上，@ref{1cf,,waitstatus_to_exitcode()} 可以将返回值（即退出状态）转换为退出码。在 Windows 上，返回值就是退出码。

引发一个 @ref{fec,,审计事件} @code{os.system}，附带参数 @code{command}。

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex times() (在 os 模块中)
@anchor{library/os os times}@anchor{b40}
@deffn {函数} os.times ()

返回当前的全局进程时间。返回值是一个有 5 个属性的对象：


@itemize *

@item 
@code{user} - 用户时间

@item 
@code{system} - 系统时间

@item 
@code{children_user} - 所有子进程的用户时间

@item 
@code{children_system} - 所有子进程的系统时间

@item 
@code{elapsed} - 从过去的固定时间点起，经过的真实时间
@end itemize

为了向后兼容，该对象的行为也类似于五元组，按照 @code{user}，@code{system}，@code{children_user}，@code{children_system} 和 @code{elapsed} 顺序组成。

在 Unix 上请参阅 @code{times(2)} 和 @code{times(3)} 手册页，在 Windows 上请参阅 the GetProcessTimes MSDN@footnote{https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes} 。在 Windows 上，只有 @code{user} 和 @code{system} 是已知的，其他属性均为零。

@ref{14c1,,可用性}: Unix, Windows。


在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象，同时具有命名的属性。

@end deffn

@geindex wait() (在 os 模块中)
@anchor{library/os os wait}@anchor{768}
@deffn {函数} os.wait ()

等待子进程执行完毕，返回一个元组，包含其 pid 和退出状态指示：一个 16 位数字，其低字节是终止该进程的信号编号，高字节是退出状态码（信号编号为零的情况下），如果生成了核心文件，则低字节的高位会置位。

可以使用 @ref{1cf,,waitstatus_to_exitcode()} 来将退出状态转换为退出码。

@ref{14c1,,可用性}: Unix。


@subsubheading 参见


@ref{76a,,waitpid()} 可以等待特定的子进程执行完毕，且支持更多选项。

@end deffn

@geindex waitid() (在 os 模块中)
@anchor{library/os os waitid}@anchor{769}
@deffn {函数} os.waitid (idtype, id, options)

等待一个或多个子进程执行完毕。@emph{idtype} 可以是 @ref{2144,,P_PID}, @ref{2145,,P_PGID}, @ref{2146,,P_ALL}, 或 @ref{1cc,,P_PIDFD} （Linux 可用）。@emph{id} 指定要等待的 pid。@emph{options} 是由 @ref{2147,,WEXITED}、@ref{2148,,WSTOPPED} 或 @ref{2149,,WCONTINUED} 中的一个或多个进行或运算构造的，且额外可以与 @ref{214a,,WNOHANG} 或 @ref{214b,,WNOWAIT} 进行或运算。返回值是一个对象，对应着 @code{siginfo_t} 结构体中的数据，即： @code{si_pid}, @code{si_uid}, @code{si_signo}, @code{si_status}, @code{si_code} 或 @code{None} （如果指定了 @ref{214a,,WNOHANG} 且没有子进程处于等待状态）。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex P_PID() (在 os 模块中)
@geindex P_PGID() (在 os 模块中)
@geindex P_ALL() (在 os 模块中)
@anchor{library/os os P_PID}@anchor{2144}
@deffn {数据} os.P_PID
@anchor{library/os os P_PGID}@anchor{2145}
@deffnx {数据} os.P_PGID
@anchor{library/os os P_ALL}@anchor{2146}
@deffnx {数据} os.P_ALL

@ref{769,,waitid()} 的 @emph{idtype} 参数的可取值。它们影响 @emph{id} 的解释方式。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex P_PIDFD() (在 os 模块中)
@anchor{library/os os P_PIDFD}@anchor{1cc}
@deffn {数据} os.P_PIDFD

这是仅 Linux 上存在的一种 @emph{idtype}，它表示 @emph{id} 是指向一个进程的文件描述符。

@ref{14c1,,可用性}: Linux 5.4+


3.9 新版功能.

@end deffn

@geindex WEXITED() (在 os 模块中)
@geindex WSTOPPED() (在 os 模块中)
@geindex WNOWAIT() (在 os 模块中)
@anchor{library/os os WEXITED}@anchor{2147}
@deffn {数据} os.WEXITED
@anchor{library/os os WSTOPPED}@anchor{2148}
@deffnx {数据} os.WSTOPPED
@anchor{library/os os WNOWAIT}@anchor{214b}
@deffnx {数据} os.WNOWAIT

用于 @ref{769,,waitid()} 的 @emph{options} 参数的标志位，指定要等待的子进程信号。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.

@end deffn

@geindex CLD_EXITED() (在 os 模块中)
@geindex CLD_KILLED() (在 os 模块中)
@geindex CLD_DUMPED() (在 os 模块中)
@geindex CLD_TRAPPED() (在 os 模块中)
@geindex CLD_STOPPED() (在 os 模块中)
@geindex CLD_CONTINUED() (在 os 模块中)
@anchor{library/os os CLD_EXITED}@anchor{214c}
@deffn {数据} os.CLD_EXITED
@anchor{library/os os CLD_KILLED}@anchor{1ca}
@deffnx {数据} os.CLD_KILLED
@anchor{library/os os CLD_DUMPED}@anchor{214d}
@deffnx {数据} os.CLD_DUMPED
@anchor{library/os os CLD_TRAPPED}@anchor{214e}
@deffnx {数据} os.CLD_TRAPPED
@anchor{library/os os CLD_STOPPED}@anchor{1cb}
@deffnx {数据} os.CLD_STOPPED
@anchor{library/os os CLD_CONTINUED}@anchor{214f}
@deffnx {数据} os.CLD_CONTINUED

@ref{769,,waitid()} 返回的结果中，@code{si_code} 的可取值。

@ref{14c1,,可用性}: Unix。


3.3 新版功能.



在 3.9 版更改: 添加了 @ref{1ca,,CLD_KILLED} 和 @ref{1cb,,CLD_STOPPED} 值。

@end deffn

@geindex waitpid() (在 os 模块中)
@anchor{library/os os waitpid}@anchor{76a}
@deffn {函数} os.waitpid (pid, options)

本函数的细节在 Unix 和 Windows 上有不同之处。

在 Unix 上：等待进程号为 @emph{pid} 的子进程执行完毕，返回一个元组，内含其进程 ID 和退出状态指示（编码与 @ref{768,,wait()} 相同）。调用的语义受整数 @emph{options} 的影响，常规操作下该值应为 @code{0}。

如果 @emph{pid} 大于 @code{0}，则 @ref{76a,,waitpid()} 会获取该指定进程的状态信息。如果 @emph{pid} 为 @code{0}，则获取当前进程所在进程组中的所有子进程的状态。如果 @emph{pid} 为 @code{-1}，则获取当前进程的子进程状态。如果 @emph{pid} 小于 @code{-1}，则获取进程组 @code{-pid} （ @emph{pid} 的绝对值）中所有进程的状态。

当系统调用返回 -1 时，将抛出带有错误码的 @ref{30b,,OSError} 异常。

在 Windows 上：等待句柄为 @emph{pid} 的进程执行完毕，返回一个元组，内含 @emph{pid} 以及左移 8 位后的退出状态码（移位简化了跨平台使用本函数）。小于或等于 @code{0} 的 @emph{pid} 在 Windows 上没有特殊含义，且会抛出异常。整数值 @emph{options} 无效。@emph{pid} 可以指向任何 ID 已知的进程，不一定是子进程。调用 @ref{20d3,,spawn*} 函数时传入 @ref{213e,,P_NOWAIT} 将返回合适的进程句柄。

可以使用 @ref{1cf,,waitstatus_to_exitcode()} 来将退出状态转换为退出码。


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此函数现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex wait3() (在 os 模块中)
@anchor{library/os os wait3}@anchor{766}
@deffn {函数} os.wait3 (options)

与 @ref{76a,,waitpid()} 相似，差别在于没有进程 ID 参数，且返回一个 3 元组，其中包括子进程 ID，退出状态指示和资源使用信息。关于资源使用信息的详情，请参考 @ref{e0,,resource}.@ref{e66,,getrusage()}。option 参数与传入 @ref{76a,,waitpid()} 和 @ref{767,,wait4()} 的相同。

可以使用 @ref{1cf,,waitstatus_to_exitcode()} 来将退出状态转换为退出码。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex wait4() (在 os 模块中)
@anchor{library/os os wait4}@anchor{767}
@deffn {函数} os.wait4 (pid, options)

与 @ref{76a,,waitpid()} 相似，差别在本方法返回一个 3 元组，其中包括子进程 ID，退出状态指示和资源使用信息。关于资源使用信息的详情，请参考 @ref{e0,,resource}.@ref{e66,,getrusage()}。@ref{767,,wait4()} 的参数与 @ref{76a,,waitpid()} 的参数相同。

可以使用 @ref{1cf,,waitstatus_to_exitcode()} 来将退出状态转换为退出码。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex waitstatus_to_exitcode() (在 os 模块中)
@anchor{library/os os waitstatus_to_exitcode}@anchor{1cf}
@deffn {函数} os.waitstatus_to_exitcode (status)

将等待状态转换为退出码。

在 Unix 上：


@itemize *

@item 
如果进程正常退出（当 @code{WIFEXITED(status)} 为真值），则返回进程退出状态 (返回 @code{WEXITSTATUS(status)}): 结果值大于等于 0。

@item 
如果进程被信号终止（当 @code{WIFSIGNALED(status)} 为真值），则返回 @code{-signum} 其中 @emph{signum} 为导致进程终止的信号数值 (返回 @code{-WTERMSIG(status)}): 结果值小于 0。

@item 
否则将抛出 @ref{16d,,ValueError} 异常。
@end itemize

在 Windows 上，返回 @emph{status} 右移 8 位的结果。

在 Unix 上，如果进程正被追踪或 @ref{76a,,waitpid()} 附带 @ref{2150,,WUNTRACED} 选项被调用，则调用者必须先检查 @code{WIFSTOPPED(status)} 是否为真值。 如果 @code{WIFSTOPPED(status)} 为真值则此函数不可被调用。


@subsubheading 参见


@ref{2151,,WIFEXITED()}, @ref{2152,,WEXITSTATUS()}, @ref{2153,,WIFSIGNALED()}, @ref{2154,,WTERMSIG()}, @ref{2155,,WIFSTOPPED()}, @ref{2156,,WSTOPSIG()} 函数。



3.9 新版功能.

@end deffn

@geindex WNOHANG() (在 os 模块中)
@anchor{library/os os WNOHANG}@anchor{214a}
@deffn {数据} os.WNOHANG

用于 @ref{76a,,waitpid()} 的选项，如果没有立即可用的子进程状态，则立即返回。在这种情况下，函数返回 @code{(0, 0)}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WCONTINUED() (在 os 模块中)
@anchor{library/os os WCONTINUED}@anchor{2149}
@deffn {数据} os.WCONTINUED

被任务控制 (job control) 停止的子进程，如果上次报告状态后已恢复运行，则此选项将报告这些子进程。

@ref{14c1,,可用性}: 部分 Unix 系统。
@end deffn

@geindex WUNTRACED() (在 os 模块中)
@anchor{library/os os WUNTRACED}@anchor{2150}
@deffn {数据} os.WUNTRACED

已停止的子进程，如果自停止以来尚未报告其当前状态，则此选项将报告这些子进程。

@ref{14c1,,可用性}: Unix。
@end deffn

下列函数采用进程状态码作为参数，状态码由 @ref{e8e,,system()}、@ref{768,,wait()} 或 @ref{76a,,waitpid()} 返回。它们可用于确定进程上发生的操作。

@geindex WCOREDUMP() (在 os 模块中)
@anchor{library/os os WCOREDUMP}@anchor{2157}
@deffn {函数} os.WCOREDUMP (status)

如果为该进程生成了核心转储，返回 @code{True}，否则返回 @code{False}。

此函数应当仅在 @ref{2153,,WIFSIGNALED()} 为真值时使用。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WIFCONTINUED() (在 os 模块中)
@anchor{library/os os WIFCONTINUED}@anchor{2158}
@deffn {函数} os.WIFCONTINUED (status)

如果一个已停止的子进程通过传送 @ref{2159,,SIGCONT} 获得恢复（如果该进程是从任务控制停止后再继续的）则返回 @code{True}，否则返回 @code{False}。

参见 @ref{2149,,WCONTINUED} 选项。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WIFSTOPPED() (在 os 模块中)
@anchor{library/os os WIFSTOPPED}@anchor{2155}
@deffn {函数} os.WIFSTOPPED (status)

如果进程是通过传送一个信号来停止的则返回 @code{True}，否则返回 @code{False}。

@ref{2155,,WIFSTOPPED()} 只有在当 @ref{76a,,waitpid()} 调用是通过使用 @ref{2150,,WUNTRACED} 选项来完成或者当该进程正被追踪时 (参见 @code{ptrace(2)}) 才返回 @code{True}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WIFSIGNALED() (在 os 模块中)
@anchor{library/os os WIFSIGNALED}@anchor{2153}
@deffn {函数} os.WIFSIGNALED (status)

如果进程是通过一个信号来终止的则返回 @code{True} ，否则返回 @code{False}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WIFEXITED() (在 os 模块中)
@anchor{library/os os WIFEXITED}@anchor{2151}
@deffn {函数} os.WIFEXITED (status)

如果进程正常终止退出则返回 @code{True}，也就是说通过调用 @code{exit()} 或 @code{_exit()}，或者通过从 @code{main()} 返回；在其他情况下则返回 @code{False}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WEXITSTATUS() (在 os 模块中)
@anchor{library/os os WEXITSTATUS}@anchor{2152}
@deffn {函数} os.WEXITSTATUS (status)

返回进程退出状态。

此函数应当仅在 @ref{2151,,WIFEXITED()} 为真值时使用。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WSTOPSIG() (在 os 模块中)
@anchor{library/os os WSTOPSIG}@anchor{2156}
@deffn {函数} os.WSTOPSIG (status)

返回导致进程停止的信号。

此函数应当仅在 @ref{2155,,WIFSTOPPED()} 为真值时使用。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex WTERMSIG() (在 os 模块中)
@anchor{library/os os WTERMSIG}@anchor{2154}
@deffn {函数} os.WTERMSIG (status)

返回导致进程终止的信号的编号。

此函数应当仅在 @ref{2153,,WIFSIGNALED()} 为真值时使用。

@ref{14c1,,可用性}: Unix。
@end deffn

@node 调度器接口,其他系统信息,进程管理,os --- 多种操作系统接口
@anchor{library/os interface-to-the-scheduler}@anchor{215a}
@subsubsection 调度器接口


这些函数控制操作系统如何为进程分配 CPU 时间。 它们仅在某些 Unix 平台上可用。 更多细节信息请查阅你所用 Unix 的指南页面。


3.3 新版功能.


以下调度策略如果被操作系统支持就会对外公开。

@geindex SCHED_OTHER() (在 os 模块中)
@anchor{library/os os SCHED_OTHER}@anchor{215b}
@deffn {数据} os.SCHED_OTHER

默认调度策略。
@end deffn

@geindex SCHED_BATCH() (在 os 模块中)
@anchor{library/os os SCHED_BATCH}@anchor{215c}
@deffn {数据} os.SCHED_BATCH

用于 CPU 密集型进程的调度策略，它会尽量为计算机中的其余任务保留交互性。
@end deffn

@geindex SCHED_IDLE() (在 os 模块中)
@anchor{library/os os SCHED_IDLE}@anchor{215d}
@deffn {数据} os.SCHED_IDLE

用于极低优先级的后台任务的调度策略。
@end deffn

@geindex SCHED_SPORADIC() (在 os 模块中)
@anchor{library/os os SCHED_SPORADIC}@anchor{215e}
@deffn {数据} os.SCHED_SPORADIC

用于偶发型服务程序的调度策略。
@end deffn

@geindex SCHED_FIFO() (在 os 模块中)
@anchor{library/os os SCHED_FIFO}@anchor{215f}
@deffn {数据} os.SCHED_FIFO

先进先出的调度策略。
@end deffn

@geindex SCHED_RR() (在 os 模块中)
@anchor{library/os os SCHED_RR}@anchor{2160}
@deffn {数据} os.SCHED_RR

循环式的调度策略。
@end deffn

@geindex SCHED_RESET_ON_FORK() (在 os 模块中)
@anchor{library/os os SCHED_RESET_ON_FORK}@anchor{2161}
@deffn {数据} os.SCHED_RESET_ON_FORK

此旗标可与任何其他调度策略进行 OR 运算。 当带有此旗标的进程设置分叉时，其子进程的调度策略和优先级会被重置为默认值。
@end deffn

@geindex sched_param (os 中的类)
@anchor{library/os os sched_param}@anchor{2136}
@deffn {类} os.sched_param (sched_priority)

这个类表示在 @ref{b3a,,sched_setparam()}, @ref{b3b,,sched_setscheduler()} 和 @ref{b36,,sched_getparam()} 中使用的可修改调度形参。 它属于不可变对象。

目前它只有一个可能的形参：

@geindex sched_priority (os.sched_param 属性)
@anchor{library/os os sched_param sched_priority}@anchor{2162}
@deffn {属性} sched_priority

一个调度策略的调度优先级。
@end deffn
@end deffn

@geindex sched_get_priority_min() (在 os 模块中)
@anchor{library/os os sched_get_priority_min}@anchor{b34}
@deffn {函数} os.sched_get_priority_min (policy)

获取 @emph{policy} 的最小优先级数值。 @emph{policy} 是以上调度策略常量之一。
@end deffn

@geindex sched_get_priority_max() (在 os 模块中)
@anchor{library/os os sched_get_priority_max}@anchor{b33}
@deffn {函数} os.sched_get_priority_max (policy)

获取 @emph{policy} 的最高优先级数值。 @emph{policy} 是以上调度策略常量之一。
@end deffn

@geindex sched_setscheduler() (在 os 模块中)
@anchor{library/os os sched_setscheduler}@anchor{b3b}
@deffn {函数} os.sched_setscheduler (pid, policy, param)

设置 PID 为 @emph{pid} 的进程的调度策略。@emph{pid} 为 0 指的是调用本方法的进程。@emph{policy} 是以上调度策略常量之一。@emph{param} 是一个 @ref{2136,,sched_param} 实例。
@end deffn

@geindex sched_getscheduler() (在 os 模块中)
@anchor{library/os os sched_getscheduler}@anchor{b37}
@deffn {函数} os.sched_getscheduler (pid)

返回 PID 为 @emph{pid} 的进程的调度策略。@emph{pid} 为 0 指的是调用本方法的进程。返回的结果是以上调度策略常量之一。
@end deffn

@geindex sched_setparam() (在 os 模块中)
@anchor{library/os os sched_setparam}@anchor{b3a}
@deffn {函数} os.sched_setparam (pid, param)

设置 PID 为 @emph{pid} 的进程的调度参数。 @emph{pid} 为 0 表示调用方过程。  @emph{param} 是一个 @ref{2136,,sched_param} 实例。
@end deffn

@geindex sched_getparam() (在 os 模块中)
@anchor{library/os os sched_getparam}@anchor{b36}
@deffn {函数} os.sched_getparam (pid)

返回 PID 为 @emph{pid} 的进程的调度参数为一个 @ref{2136,,sched_param} 实例。@emph{pid} 为 0 指的是调用本方法的进程。
@end deffn

@geindex sched_rr_get_interval() (在 os 模块中)
@anchor{library/os os sched_rr_get_interval}@anchor{b38}
@deffn {函数} os.sched_rr_get_interval (pid)

返回 PID 为 @emph{pid} 的进程在时间片轮转调度下的时间片长度（单位为秒）。@emph{pid} 为 0 指的是调用本方法的进程。
@end deffn

@geindex sched_yield() (在 os 模块中)
@anchor{library/os os sched_yield}@anchor{b3c}
@deffn {函数} os.sched_yield ()

自愿放弃 CPU。
@end deffn

@geindex sched_setaffinity() (在 os 模块中)
@anchor{library/os os sched_setaffinity}@anchor{b39}
@deffn {函数} os.sched_setaffinity (pid, mask)

将 PID 为 @emph{pid} 的进程（为零则为当前进程）限制到一组 CPU 上。@emph{mask} 是整数的可迭代对象，表示应将进程限制在其中的一组 CPU。
@end deffn

@geindex sched_getaffinity() (在 os 模块中)
@anchor{library/os os sched_getaffinity}@anchor{b35}
@deffn {函数} os.sched_getaffinity (pid)

返回 PID 为 @emph{pid} 的进程（为零则为当前进程）被限制到的那一组 CPU。
@end deffn

@node 其他系统信息,随机数<2>,调度器接口,os --- 多种操作系统接口
@anchor{library/os miscellaneous-system-information}@anchor{2163}@anchor{library/os os-path}@anchor{2164}
@subsubsection 其他系统信息


@geindex confstr() (在 os 模块中)
@anchor{library/os os confstr}@anchor{2165}
@deffn {函数} os.confstr (name)

返回字符串格式的系统配置信息。@emph{name} 指定要查找的配置名称，它可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（POSIX，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。当前操作系统已定义的名称在 @code{confstr_names} 字典的键中给出。对于未包含在该映射中的配置名称，也可以传递一个整数作为 @emph{name}。

如果 @emph{name} 指定的配置值未定义，返回 @code{None}。

如果 @emph{name} 是一个字符串且不是已定义的名称，将抛出 @ref{16d,,ValueError} 异常。如果当前系统不支持 @emph{name} 指定的配置名称，即使该名称存在于 @code{confstr_names}，也会抛出 @ref{30b,,OSError} 异常，错误码为 @ref{114d,,errno.EINVAL}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex confstr_names() (在 os 模块中)
@anchor{library/os os confstr_names}@anchor{2166}
@deffn {数据} os.confstr_names

字典，表示映射关系，为 @ref{2165,,confstr()} 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex cpu_count() (在 os 模块中)
@anchor{library/os os cpu_count}@anchor{973}
@deffn {函数} os.cpu_count ()

返回系统的 CPU 数量。不确定则返回 @code{None}。

该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由 @code{len(os.sched_getaffinity(0))} 方法获得。


3.4 新版功能.

@end deffn

@geindex getloadavg() (在 os 模块中)
@anchor{library/os os getloadavg}@anchor{2167}
@deffn {函数} os.getloadavg ()

返回系统运行队列中最近 1、5 和 15 分钟内的平均进程数。无法获得平均负载则抛出 @ref{30b,,OSError} 异常。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex sysconf() (在 os 模块中)
@anchor{library/os os sysconf}@anchor{20c5}
@deffn {函数} os.sysconf (name)

返回整数格式的系统配置信息。如果 @emph{name} 指定的配置值未定义，返回 @code{-1}。对 @ref{2165,,confstr()} 的 @emph{name} 参数的注释在此处也适用。当前已知的配置名称在 @code{sysconf_names} 字典中提供。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex sysconf_names() (在 os 模块中)
@anchor{library/os os sysconf_names}@anchor{2168}
@deffn {数据} os.sysconf_names

字典，表示映射关系，为 @ref{20c5,,sysconf()} 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称。

@ref{14c1,,可用性}: Unix。
@end deffn

以下数据值用于支持对路径本身的操作。所有平台都有定义。

对路径的高级操作在 @ref{c5,,os.path} 模块中定义。

@geindex . (dot); in pathnames

@geindex curdir() (在 os 模块中)
@anchor{library/os os curdir}@anchor{1d97}
@deffn {数据} os.curdir

操作系统用来表示当前目录的常量字符串。在 Windows 和 POSIX 上是 @code{'.'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex ..; in pathnames

@geindex pardir() (在 os 模块中)
@anchor{library/os os pardir}@anchor{20dd}
@deffn {数据} os.pardir

操作系统用来表示父目录的常量字符串。在 Windows 和 POSIX 上是 @code{'..'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex / (slash); in pathnames

@geindex \ (backslash); in pathnames (Windows)

@geindex sep() (在 os 模块中)
@anchor{library/os os sep}@anchor{1e1c}
@deffn {数据} os.sep

操作系统用来分隔路径不同部分的字符。在 POSIX 上是 @code{'/'}，在 Windows 上是是 @code{'\\'}。注意，仅了解它不足以能解析或连接路径，请使用 @ref{1d91,,os.path.split()} 和 @ref{1110,,os.path.join()}，但它有时是有用的。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex / (slash); in pathnames

@geindex altsep() (在 os 模块中)
@anchor{library/os os altsep}@anchor{1e1d}
@deffn {数据} os.altsep

操作系统用来分隔路径不同部分的替代字符。如果仅存在一个分隔符，则为 @code{None}。在 @code{sep} 是反斜杠的 Windows 系统上，该值被设为 @code{'/'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex . (dot); in pathnames

@geindex extsep() (在 os 模块中)
@anchor{library/os os extsep}@anchor{2169}
@deffn {数据} os.extsep

分隔基本文件名与扩展名的字符，如 @code{os.py} 中的 @code{'.'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex ; (colon); path separator (POSIX)
@geindex ; (semicolon)

@geindex pathsep() (在 os 模块中)
@anchor{library/os os pathsep}@anchor{14b6}
@deffn {数据} os.pathsep

操作系统通常用于分隔搜索路径（如 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}）中不同部分的字符，如 POSIX 上是 @code{':'}，Windows 上是 @code{';'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex defpath() (在 os 模块中)
@anchor{library/os os defpath}@anchor{1163}
@deffn {数据} os.defpath

在环境变量没有 @code{'PATH'} 键的情况下，@ref{2117,,exec*p*} and @ref{20d3,,spawn*p*} 使用的默认搜索路径。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex linesep() (在 os 模块中)
@anchor{library/os os linesep}@anchor{1762}
@deffn {数据} os.linesep

当前平台用于分隔（或终止）行的字符串。它可以是单个字符，如 POSIX 上是 @code{'\n'}，也可以是多个字符，如 Windows 上是 @code{'\r\n'}。在写入以文本模式（默认模式）打开的文件时，请不要使用 @emph{os.linesep} 作为行终止符，请在所有平台上都使用一个 @code{'\n'} 代替。
@end deffn

@geindex devnull() (在 os 模块中)
@anchor{library/os os devnull}@anchor{119b}
@deffn {数据} os.devnull

空设备的文件路径。如 POSIX 上为 @code{'/dev/null'}，Windows 上为 @code{'nul'}。在 @ref{c5,,os.path} 中也可用。
@end deffn

@geindex RTLD_LAZY() (在 os 模块中)
@geindex RTLD_NOW() (在 os 模块中)
@geindex RTLD_GLOBAL() (在 os 模块中)
@geindex RTLD_LOCAL() (在 os 模块中)
@geindex RTLD_NODELETE() (在 os 模块中)
@geindex RTLD_NOLOAD() (在 os 模块中)
@geindex RTLD_DEEPBIND() (在 os 模块中)
@anchor{library/os os RTLD_LAZY}@anchor{b43}
@deffn {数据} os.RTLD_LAZY
@anchor{library/os os RTLD_NOW}@anchor{b44}
@deffnx {数据} os.RTLD_NOW
@anchor{library/os os RTLD_GLOBAL}@anchor{b45}
@deffnx {数据} os.RTLD_GLOBAL
@anchor{library/os os RTLD_LOCAL}@anchor{b46}
@deffnx {数据} os.RTLD_LOCAL
@anchor{library/os os RTLD_NODELETE}@anchor{b47}
@deffnx {数据} os.RTLD_NODELETE
@anchor{library/os os RTLD_NOLOAD}@anchor{b48}
@deffnx {数据} os.RTLD_NOLOAD
@anchor{library/os os RTLD_DEEPBIND}@anchor{b49}
@deffnx {数据} os.RTLD_DEEPBIND

@ref{b4a,,setdlopenflags()} 和 @ref{f18,,getdlopenflags()} 函数所使用的标志。请参阅 Unix 手册页 @code{dlopen(3)} 获取不同标志的含义。


3.3 新版功能.

@end deffn

@node 随机数<2>,,其他系统信息,os --- 多种操作系统接口
@anchor{library/os random-numbers}@anchor{216a}
@subsubsection 随机数


@geindex getrandom() (在 os 模块中)
@anchor{library/os os getrandom}@anchor{66c}
@deffn {函数} os.getrandom (size, flags=0)

获得最多为 @emph{size} 的随机字节。本函数返回的字节数可能少于请求的字节数。

这些字节可用于为用户空间的随机数生成器提供种子，或用于加密目的。

@code{getrandom()} 依赖于从设备驱动程序和其他环境噪声源收集的熵。不必要地读取大量数据将对使用 @code{/dev/random} 和 @code{/dev/urandom} 设备的其他用户产生负面影响。

flags 参数是一个位掩码，可以是零个或多个下列值以或运算组合： @ref{216b,,os.GRND_RANDOM} 和 @ref{216c,,GRND_NONBLOCK}。

另请参阅 Linux getrandom() 手册页@footnote{http://man7.org/linux/man-pages/man2/getrandom.2.html} 。

@ref{14c1,,可用性}：Linux 3.17 或更高版本。


3.6 新版功能.

@end deffn

@geindex urandom() (在 os 模块中)
@anchor{library/os os urandom}@anchor{5d4}
@deffn {函数} os.urandom (size)

返回大小为 @emph{size} 的字节串，它是适合加密使用的随机字节。

本函数从系统指定的随机源获取随机字节。对于加密应用程序，返回的数据应有足够的不可预测性，尽管其确切的品质取决于操作系统的实现。

在 Linux 上，如果 @code{getrandom()} 系统调用可用，它将以阻塞模式使用：阻塞直到系统的 urandom 熵池初始化完毕（内核收集了 128 位熵）。原理请参阅 
@geindex Python 提高建议; PEP 524
PEP 524@footnote{https://www.python.org/dev/peps/pep-0524}。在 Linux 上，@ref{66c,,getrandom()} 可以以非阻塞模式（使用 @ref{216c,,GRND_NONBLOCK} 标志）获取随机字节，或者轮询直到系统的 urandom 熵池初始化完毕。

在类 Unix 系统上，随机字节是从 @code{/dev/urandom} 设备读取的。如果 @code{/dev/urandom} 设备不可用或不可读，则抛出 @ref{70e,,NotImplementedError} 异常。

在 Windows 上将使用 @code{CryptGenRandom()}。


@subsubheading 参见


@ref{e4,,secrets} 模块提供了更高级的功能。所在平台会提供随机数生成器，有关其易于使用的接口，请参阅 @ref{1ca7,,random.SystemRandom}。



在 3.6.0 版更改: 在 Linux 上，@code{getrandom()} 现在以阻塞模式使用，以提高安全性。



在 3.5.2 版更改: 在 Linux 上，如果 @code{getrandom()} 系统调用阻塞（urandom 熵池尚未初始化完毕），则退回一步读取 @code{/dev/urandom}。



在 3.5 版更改: 在 Linux 3.17 和更高版本上，现在使用 @code{getrandom()} 系统调用（如果可用）。在 OpenBSD 5.6 和更高版本上，现在使用 @code{getentropy()} C 函数。这些函数避免了使用内部文件描述符。

@end deffn

@geindex GRND_NONBLOCK() (在 os 模块中)
@anchor{library/os os GRND_NONBLOCK}@anchor{216c}
@deffn {数据} os.GRND_NONBLOCK

默认情况下，从 @code{/dev/random} 读取时，如果没有可用的随机字节，则 @ref{66c,,getrandom()} 会阻塞；从 @code{/dev/urandom} 读取时，如果熵池尚未初始化，则会阻塞。

如果设置了 @ref{216c,,GRND_NONBLOCK} 标志，则这些情况下 @ref{66c,,getrandom()} 不会阻塞，而是立即抛出 @ref{a81,,BlockingIOError} 异常。


3.6 新版功能.

@end deffn

@geindex GRND_RANDOM() (在 os 模块中)
@anchor{library/os os GRND_RANDOM}@anchor{216b}
@deffn {数据} os.GRND_RANDOM

如果设置了此标志位，那么将从 @code{/dev/random} 池而不是 @code{/dev/urandom} 池中提取随机字节。


3.6 新版功能.

@end deffn

@node io --- 处理流的核心工具,time --- 时间的访问和转换,os --- 多种操作系统接口,通用操作系统服务
@anchor{library/io doc}@anchor{216d}@anchor{library/io io-core-tools-for-working-with-streams}@anchor{216e}@anchor{library/io module-io}@anchor{a1}
@subsection @code{io} --- 处理流的核心工具


@geindex io (模块)

@strong{源代码:} Lib/io.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/io.py}


__________________________________________________________________


@menu
* 概述: 概述<8>. 
* 高阶模块接口:: 
* 类的层次结构:: 
* 性能: 性能<3>. 

@end menu

@node 概述<8>,高阶模块接口,,io --- 处理流的核心工具
@anchor{library/io io-overview}@anchor{175d}@anchor{library/io overview}@anchor{216f}
@subsubsection 概述


@geindex file object; io module

@ref{a1,,io} 模块提供了 Python 用于处理各种 I/O 类型的主要工具。三种主要的 I/O类型分别为: @emph{文本 I/O}, @emph{二进制 I/O} 和 @emph{原始 I/O}。这些是泛型类型，有很多种后端存储可以用在他们上面。一个隶属于任何这些类型的具体对象被称作 @ref{c1d,,file object}。 其他同类的术语还有 @emph{流} 和 @emph{类文件对象}。

独立于其类别，每个具体流对象也将具有各种功能：它可以是只读，只写或读写。它还可以允许任意随机访问（向前或向后寻找任何位置），或仅允许顺序访问（例如在套接字或管道的情况下）。

所有流对提供给它们的数据类型都很敏感。例如将 @ref{206,,str} 对象给二进制流的 @code{write()} 方法会引发 @ref{1ff,,TypeError}。将 @ref{172,,bytes} 对象提供给文本流的 @code{write()} 方法也是如此。


在 3.3 版更改: 由于 @ref{a7c,,IOError} 现在是 @ref{30b,,OSError} 的别名，因此用于引发 @ref{a7c,,IOError} 的操作现在会引发 @ref{30b,,OSError} 。


@menu
* 文本 I/O:: 
* 二进制 I/O:: 
* 原始 I/O:: 

@end menu

@node 文本 I/O,二进制 I/O,,概述<8>
@anchor{library/io text-i-o}@anchor{2170}
@subsubsection 文本 I/O


文本I/O预期并生成 @ref{206,,str} 对象。这意味着，无论何时后台存储是由字节组成的（例如在文件的情况下），数据的编码和解码都是透明的，并且可以选择转换特定于平台的换行符。

创建文本流的最简单方法是使用 @ref{16f,,open()}，可以选择指定编码：

@example
f = open("myfile.txt", "r", encoding="utf-8")
@end example

内存中文本流也可以作为 @ref{924,,StringIO} 对象使用：

@example
f = io.StringIO("some initial text data")
@end example

@ref{d09,,TextIOBase} 的文档中详细描述了文本流的API

@node 二进制 I/O,原始 I/O,文本 I/O,概述<8>
@anchor{library/io binary-i-o}@anchor{2171}
@subsubsection 二进制 I/O


二进制I/O（也称为缓冲I/O）预期 @ref{6e9,,bytes-like objects} 并生成  @ref{172,,bytes} 对象。不执行编码、解码或换行转换。这种类型的流可以用于所有类型的非文本数据，并且还可以在需要手动控制文本数据的处理时使用。

创建二进制流的最简单方法是使用 @ref{16f,,open()}，并在模式字符串中指定 @code{'b'} ：

@example
f = open("myfile.jpg", "rb")
@end example

内存中二进制流也可以作为 @ref{894,,BytesIO} 对象使用：

@example
f = io.BytesIO(b"some initial binary data: \x00\x01")
@end example

@ref{689,,BufferedIOBase} 的文档中详细描述了二进制流的API

其他库模块可以提供额外的方式来创建文本或二进制流。参见 @ref{bf5,,socket.socket.makefile()} 的示例。

@node 原始 I/O,,二进制 I/O,概述<8>
@anchor{library/io raw-i-o}@anchor{2172}
@subsubsection 原始 I/O


原始 I/O（也称为 @emph{非缓冲 I/O}）通常用作二进制和文本流的低级构建块。用户代码直接操作原始流的用法非常罕见。不过，可以通过在禁用缓冲的情况下以二进制模式打开文件来创建原始流：

@example
f = open("myfile.jpg", "rb", buffering=0)
@end example

@ref{afa,,RawIOBase} 的文档中详细描述了原始流的API

@node 高阶模块接口,类的层次结构,概述<8>,io --- 处理流的核心工具
@anchor{library/io high-level-module-interface}@anchor{2173}
@subsubsection 高阶模块接口


@geindex DEFAULT_BUFFER_SIZE() (在 io 模块中)
@anchor{library/io io DEFAULT_BUFFER_SIZE}@anchor{175f}
@deffn {数据} io.DEFAULT_BUFFER_SIZE

包含模块缓冲I/O类使用的默认缓冲区大小的整数。（如果可能） @ref{16f,,open()} 将使用文件的blksize（由 @ref{328,,os.stat()} 获得）。
@end deffn

@geindex open() (在 io 模块中)
@anchor{library/io io open}@anchor{757}
@deffn {函数} io.open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

这是内置的 @ref{16f,,open()} 函数的别名。

@code{open} 附带参数 @code{path}、@code{mode}、@code{flags} 会引发 @ref{fec,,审计事件}。
@end deffn

@geindex open_code() (在 io 模块中)
@anchor{library/io io open_code}@anchor{f59}
@deffn {函数} io.open_code (path)

以 @code{'rb'} 模式打开提供的文件。如果目的是将文件内容做为可执行代码，则应使用此函数。

@code{path} 应当为 @ref{206,,str} 类型并且是一个绝对路径。

此函数的行为可以由对 @ref{2174,,PyFile_SetOpenCodeHook()} 的先期调用所重载。 但是，如果 @code{path} 为 @ref{206,,str} 类型并且是一个绝对路径，@code{open_code(path)} 的行为应当总是与 @code{open(path, 'rb')} 一致。 重载此行为的目的是为了给文件附加额外的验证或预处理。


3.8 新版功能.

@end deffn

@geindex BlockingIOError
@anchor{library/io io BlockingIOError}@anchor{2175}
@deffn {例外} io.BlockingIOError

这是内置的 @ref{a81,,BlockingIOError} 异常的兼容性别名。
@end deffn

@geindex UnsupportedOperation
@anchor{library/io io UnsupportedOperation}@anchor{10cc}
@deffn {例外} io.UnsupportedOperation

在流上调用不支持的操作时引发的继承 @ref{30b,,OSError} 和 @ref{16d,,ValueError} 的异常。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{fd,,sys}

包含标准IO流: @ref{427,,sys.stdin}, @ref{428,,sys.stdout} 和 @ref{1eb,,sys.stderr} 。
@end table


@node 类的层次结构,性能<3>,高阶模块接口,io --- 处理流的核心工具
@anchor{library/io class-hierarchy}@anchor{2176}
@subsubsection 类的层次结构


I/O 流被安排为按类的层次结构实现。 首先是 @ref{c0e,,抽象基类} (ABC)，用于指定流的各种类别，然后是提供标准流实现的具体类。

@quotation

@cartouche
@quotation 注解 
抽象基类还提供某些方法的默认实现，以帮助实现具体的流类。例如 @ref{689,,BufferedIOBase} 提供了 @code{readinto()} 和 @ref{1883,,readline()} 的未优化实现。
@end quotation
@end cartouche
@end quotation

I/O层次结构的顶部是抽象基类 @ref{313,,IOBase} 。它定义了流的基本接口。但是请注意，对流的读取和写入之间没有分离。如果实现不支持指定的操作，则会引发 @ref{10cc,,UnsupportedOperation} 。

抽象基类 @ref{afa,,RawIOBase} 是 @ref{313,,IOBase} 的子类。它负责将字节读取和写入流中。 @ref{afa,,RawIOBase} 的子类 @ref{d74,,FileIO} 提供计算机文件系统中文件的接口。

抽象基类 @ref{689,,BufferedIOBase} 继承了 @ref{313,,IOBase} ，处理原始二进制流（ @ref{afa,,RawIOBase} ）上的缓冲。其子类 @ref{1763,,BufferedWriter} 、 @ref{c64,,BufferedReader} 和 @ref{2177,,BufferedRWPair} 分别缓冲可读、可写以及可读写的原始二进制流。 @ref{1764,,BufferedRandom} 提供了带缓冲的可随机访问流接口。 @ref{689,,BufferedIOBase} 的另一个子类 @ref{894,,BytesIO} 是内存中字节流。

抽象基类 @ref{d09,,TextIOBase} 继承了 @ref{313,,IOBase} 。它处理可表示文本的流，并处理字符串的编码和解码。类 @ref{6f4,,TextIOWrapper} 继承了 @ref{d09,,TextIOBase} ，是原始缓冲流（ @ref{689,,BufferedIOBase} ）的缓冲文本接口。最后， @ref{924,,StringIO} 是文本的内存流。

参数名不是规范的一部分，只有 @ref{16f,,open()} 的参数才用作关键字参数。

下表总结了抽象基类提供的 @ref{a1,,io} 模块：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

抽象基类

@tab

继承

@tab

抽象方法

@tab

Mixin方法和属性

@item

@ref{313,,IOBase}

@tab

@tab

@code{fileno}, @code{seek}, 和 @code{truncate}

@tab

@code{close}, @code{closed}, @code{__enter__}, @code{__exit__}, @code{flush}, @code{isatty}, @code{__iter__}, @code{__next__}, @code{readable}, @code{readline}, @code{readlines}, @code{seekable}, @code{tell}, @code{writable} 和 @code{writelines}

@item

@ref{afa,,RawIOBase}

@tab

@ref{313,,IOBase}

@tab

@code{readinto} 和 @code{write}

@tab

继承 @ref{313,,IOBase} 方法, @code{read}, 和 @code{readall}

@item

@ref{689,,BufferedIOBase}

@tab

@ref{313,,IOBase}

@tab

@code{detach}, @code{read}, @code{read1}, 和 @code{write}

@tab

继承 @ref{313,,IOBase} 方法, @code{readinto}, 和 @code{readinto1}

@item

@ref{d09,,TextIOBase}

@tab

@ref{313,,IOBase}

@tab

@code{detach}, @code{read}, @code{readline}, 和 @code{write}

@tab

继承 @ref{313,,IOBase} 方法, @code{encoding}, @code{errors}, 和 @code{newlines}

@end multitable


@menu
* I/O 基类:: 
* 原始文件 I/O:: 
* 缓冲流:: 
* 文本 I/O: 文本 I/O<2>. 

@end menu

@node I/O 基类,原始文件 I/O,,类的层次结构
@anchor{library/io i-o-base-classes}@anchor{2178}
@subsubsection I/O 基类


@geindex IOBase (io 中的类)
@anchor{library/io io IOBase}@anchor{313}
@deffn {类} io.IOBase

所有 I/O 类的抽象基类。

此类为许多方法提供了空的抽象实现，派生类可以有选择地重写。默认实现代表一个无法读取、写入或查找的文件。

尽管 @ref{313,,IOBase} 没有声明 @code{read()} 或 @code{write()} ，因为它们的签名会有所不同，但是实现和客户端应该将这些方法视为接口的一部分。此外，当调用不支持的操作时可能会引发 @ref{16d,,ValueError} （或 @ref{10cc,,UnsupportedOperation} ）。

从文件读取或写入文件的二进制数据的基本类型为 @ref{172,,bytes} 。其他 @ref{6e9,,bytes-like objects} 也可以作为方法参数。文本I/O类使用 @ref{206,,str} 数据。

请注意，在关闭的流上调用任何方法（甚至查询）都是未定义的（undefined）。在这种情况下，实现可能会引发 @ref{16d,,ValueError} 。

@ref{313,,IOBase} （及其子类）支持迭代器协议，这意味着可以迭代 @ref{313,,IOBase} 对象以产生流中的行。根据流是二进制流（产生字节）还是文本流（产生字符串），行的定义略有不同。请参见下面的 @ref{1883,,readline()} 。

@ref{313,,IOBase} 也是一个上下文管理器，因此支持 @ref{7e4,,with} 语句。 在这个示例中，@emph{file} 将在 @code{with} 语句块执行完成之后被关闭 --- 即使是发生了异常:

@example
with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')
@end example

@ref{313,,IOBase} 提供以下数据属性和方法：

@geindex close() (io.IOBase 方法)
@anchor{library/io io IOBase close}@anchor{1190}
@deffn {方法} close ()

刷新并关闭此流。如果文件已经关闭，则此方法无效。文件关闭后，对文件的任何操作（例如读取或写入）都会引发 @ref{16d,,ValueError} 。

为方便起见，允许多次调用此方法。但是，只有第一个调用才会生效。
@end deffn

@geindex closed (io.IOBase 属性)
@anchor{library/io io IOBase closed}@anchor{1191}
@deffn {属性} closed

如果流已关闭，则返回 True。
@end deffn

@geindex fileno() (io.IOBase 方法)
@anchor{library/io io IOBase fileno}@anchor{209a}
@deffn {方法} fileno ()

返回流的底层文件描述符（整数）---如果存在。如果 IO 对象不使用文件描述符，则会引发 @ref{30b,,OSError} 。
@end deffn

@geindex flush() (io.IOBase 方法)
@anchor{library/io io IOBase flush}@anchor{2179}
@deffn {方法} flush ()

刷新流的写入缓冲区（如果适用）。这对只读和非阻塞流不起作用。
@end deffn

@geindex isatty() (io.IOBase 方法)
@anchor{library/io io IOBase isatty}@anchor{1760}
@deffn {方法} isatty ()

如果流是交互式的（即连接到终端/tty设备），则返回 @code{True} 。
@end deffn

@geindex readable() (io.IOBase 方法)
@anchor{library/io io IOBase readable}@anchor{217a}
@deffn {方法} readable ()

如果可以读取流，则返回 @code{True} 。否则为 @code{False} ，且 @code{read()} 将引发 @ref{30b,,OSError} 错误。
@end deffn

@geindex readline() (io.IOBase 方法)
@anchor{library/io io IOBase readline}@anchor{1883}
@deffn {方法} readline (size=-1, /)

从流中读取并返回一行。如果指定了 @emph{size}，将至多读取 @emph{size} 个字节。

对于二进制文件行结束符总是 @code{b'\n'}；对于文本文件，可以用将 @emph{newline} 参数传给 @ref{16f,,open()} 的方式来选择要识别的行结束符。
@end deffn

@geindex readlines() (io.IOBase 方法)
@anchor{library/io io IOBase readlines}@anchor{1921}
@deffn {方法} readlines (hint=-1, /)

从流中读取并返回包含多行的列表。可以指定 @emph{hint} 来控制要读取的行数：如果（以字节/字符数表示的）所有行的总大小超出了 @emph{hint} 则将不会读取更多的行。

@code{0} 或更小的 @emph{hint} 值以及 @code{None}，会被视为没有 hint。

请注意使用 @code{for line in file: ...} 就足够对文件对象进行迭代了，可以不必调用 @code{file.readlines()}。
@end deffn

@geindex seek() (io.IOBase 方法)
@anchor{library/io io IOBase seek}@anchor{1f3f}
@deffn {方法} seek (offset, whence=SEEK_SET, /)

将流位置修改到给定的字节 @emph{offset}。 @emph{offset} 将相对于由 @emph{whence} 指定的位置进行解析。 @emph{whence} 的默认值为 @code{SEEK_SET}。 @emph{whence} 的可用值有：


@itemize *

@item 
@code{SEEK_SET} 或 @code{0} -- 流的开头（默认值）；@emph{offset} 应为零或正值

@item 
@code{SEEK_CUR} or @code{1} -- 当前流位置；@emph{offset} 可以为负值

@item 
@code{SEEK_END} or @code{2} -- 流的末尾；@emph{offset} 通常为负值
@end itemize

返回新的绝对位置。


3.1 新版功能: @code{SEEK_*} 常量.



3.3 新版功能: 某些操作系统还可支持其他的值，例如 @code{os.SEEK_HOLE} 或 @code{os.SEEK_DATA}。特定文件的可用值还会取决于它是以文本还是二进制模式打开。

@end deffn

@geindex seekable() (io.IOBase 方法)
@anchor{library/io io IOBase seekable}@anchor{217b}
@deffn {方法} seekable ()

如果流支持随机访问则返回 @code{True}。 如为 @code{False}，则 @ref{1f3f,,seek()}, @ref{1f40,,tell()} 和 @ref{d75,,truncate()} 将引发 @ref{30b,,OSError}。
@end deffn

@geindex tell() (io.IOBase 方法)
@anchor{library/io io IOBase tell}@anchor{1f40}
@deffn {方法} tell ()

返回当前流的位置。
@end deffn

@geindex truncate() (io.IOBase 方法)
@anchor{library/io io IOBase truncate}@anchor{d75}
@deffn {方法} truncate (size=None, /)

将流的大小调整为给定的 @emph{size} 个字节（如果未指定 @emph{size} 则调整至当前位置）。 当前的流位置不变。 这个调整操作可扩展或减小当前文件大小。 在扩展的情况下，新文件区域的内容取决于具体平台（在大多数系统上，额外的字节会填充为零）。 返回新的文件大小。


在 3.5 版更改: 现在Windows在扩展时将文件填充为零。

@end deffn

@geindex writable() (io.IOBase 方法)
@anchor{library/io io IOBase writable}@anchor{217c}
@deffn {方法} writable ()

如果流支持写入则返回 @code{True}。 如为 @code{False}，则 @code{write()} 和 @ref{d75,,truncate()} 将引发 @ref{30b,,OSError}。
@end deffn

@geindex writelines() (io.IOBase 方法)
@anchor{library/io io IOBase writelines}@anchor{1922}
@deffn {方法} writelines (lines, /)

将行列表写入到流。 不会添加行分隔符，因此通常所提供的每一行都带有末尾行分隔符。
@end deffn

@geindex __del__() (io.IOBase 方法)
@anchor{library/io io IOBase __del__}@anchor{217d}
@deffn {方法} __del__ ()

为对象销毁进行准备。 @ref{313,,IOBase} 提供了此方法的默认实现，该实现会调用实例的 @ref{1190,,close()} 方法。
@end deffn
@end deffn

@geindex RawIOBase (io 中的类)
@anchor{library/io io RawIOBase}@anchor{afa}
@deffn {类} io.RawIOBase

原始二进制流的基类。 它继承自 @ref{313,,IOBase} 。

原始二进制流通常会提供对下层 OS 设备或 API 的低层级访问，而不是尝试将其封装到高层级的基元中（此功能是在更高层级的缓冲二进制流和文本流中实现的，将在下文中描述）。

@ref{afa,,RawIOBase} 在 @ref{313,,IOBase} 的现有成员以外还提供了下列方法:

@geindex read() (io.RawIOBase 方法)
@anchor{library/io io RawIOBase read}@anchor{7fd}
@deffn {方法} read (size=-1, /)

从对象中读取 @emph{size} 个字节并将其返回。 作为一个便捷选项，如果 @emph{size} 未指定或为 -1，则返回所有字节直到 EOF。 在其他情况下，仅会执行一次系统调用。 如果操作系统调用返回字节数少于 @emph{size} 则此方法也可能返回少于 @emph{size} 个字节。

如果返回 0 个字节而 @emph{size} 不为零 0，这表明到达文件末尾。 如果处于非阻塞模式并且没有更多字节可用，则返回 @code{None}。

默认实现会转至 @ref{217e,,readall()} 和 @ref{7fe,,readinto()}。
@end deffn

@geindex readall() (io.RawIOBase 方法)
@anchor{library/io io RawIOBase readall}@anchor{217e}
@deffn {方法} readall ()

从流中读取并返回所有字节直到 EOF，如有必要将对流执行多次调用。
@end deffn

@geindex readinto() (io.RawIOBase 方法)
@anchor{library/io io RawIOBase readinto}@anchor{7fe}
@deffn {方法} readinto (b, /)

将字节数据读入预先分配的可写 @ref{6e9,,bytes-like object} @emph{b}，并返回所读取的字节数。 例如，@emph{b} 可以是一个 @ref{173,,bytearray}。 如果对象处理非阻塞模式并且没有更多字节可用，则返回 @code{None}。
@end deffn

@geindex write() (io.RawIOBase 方法)
@anchor{library/io io RawIOBase write}@anchor{217f}
@deffn {方法} write (b, /)

将给定的 @ref{6e9,,bytes-like object} @emph{b} 写入到下层的原始流，并返回所写入的字节数。 这可以少于 @emph{b} 的总字节数，具体取决于下层原始流的设定，特别是如果它处于非阻塞模式的话。 如果原始流设为非阻塞并且不能真正向其写入单个字节时则返回 @code{None}。 调用者可以在此方法返回后释放或改变 @emph{b}，因此该实现应该仅在方法调用期间访问 @emph{b}。
@end deffn
@end deffn

@geindex BufferedIOBase (io 中的类)
@anchor{library/io io BufferedIOBase}@anchor{689}
@deffn {类} io.BufferedIOBase

支持某种缓冲的二进制流的基类。 它继承自 @ref{313,,IOBase}。

与 @ref{afa,,RawIOBase} 的主要差别在于 @ref{1eff,,read()}, @ref{2180,,readinto()} 和 @ref{68a,,write()} 等方法将（分别）尝试按照要求读取尽可能多的输入或是耗尽所有给定的输出，其代价是可能会执行一次以上的系统调用。

除此之外，那些方法还可能引发 @ref{a81,,BlockingIOError}，如果下层的原始数据流处于非阻塞模式并且无法接受或给出足够数据的话；不同于对应的 @ref{afa,,RawIOBase} 方法，它们将永远不会返回 @code{None}。

并且，@ref{1eff,,read()} 方法也没有转向 @ref{2180,,readinto()} 的默认实现。

典型的 @ref{689,,BufferedIOBase} 实现不应当继承自 @ref{afa,,RawIOBase} 实现，而要包装一个该实现，正如 @ref{1763,,BufferedWriter} 和 @ref{c64,,BufferedReader} 所做的那样。

@ref{689,,BufferedIOBase} 在 @ref{313,,IOBase} 的现有成员以外还提供或重载了下列数据属性和方法:

@geindex raw (io.BufferedIOBase 属性)
@anchor{library/io io BufferedIOBase raw}@anchor{2181}
@deffn {属性} raw

由 @ref{689,,BufferedIOBase} 处理的下层原始流 (@ref{afa,,RawIOBase} 的实例)。 它不是 @ref{689,,BufferedIOBase} API 的组成部分并且不存在于某些实现中。
@end deffn

@geindex detach() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase detach}@anchor{2182}
@deffn {方法} detach ()

从缓冲区分离出下层原始流并将其返回。

在原始流被分离之后，缓冲区将处于不可用的状态。

某些缓冲区例如 @ref{894,,BytesIO} 并无可从此方法返回的单独原始流的概念。 它们将会引发 @ref{10cc,,UnsupportedOperation}。


3.1 新版功能.

@end deffn

@geindex read() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase read}@anchor{1eff}
@deffn {方法} read (size=-1, /)

读取并返回最多 @emph{size} 个字节。 如果此参数被省略、为 @code{None} 或为负值，则读取并返回所有数据直到 EOF。 如果流已经到达 EOF 则返回一个空的 @ref{172,,bytes} 对象。

如果此参数为正值，并且下层原始流不可交互，则可能发起多个原始读取以满足字节计数（直至先遇到 EOF）。 但对于可交互原始流，则将至多发起一个原始读取，并且简短的结果并不意味着已到达 EOF。

@ref{a81,,BlockingIOError} 会在下层原始流不处于阻塞模式，并且当前没有可用数据时被引发。
@end deffn

@geindex read1() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase read1}@anchor{1efe}
@deffn {方法} read1 (size=-1, /)

通过至多一次对下层流的 @ref{7fd,,read()} (或 @ref{7fe,,readinto()}) 方法的调用读取并返回至多 @emph{size} 个字节。 这适用于在 @ref{689,,BufferedIOBase} 对象之上实现你自己的缓冲区的情况。

如果 @emph{size} 为 @code{-1} (默认值)，则返回任意数量的字节（多于零字节，除非已到达 EOF）。
@end deffn

@geindex readinto() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase readinto}@anchor{2180}
@deffn {方法} readinto (b, /)

将字节数据读入预先分配的可写 @ref{6e9,,bytes-like object} @emph{b} 并返回所读取的字节数。 例如，@emph{b} 可以是一个 @ref{173,,bytearray}。

类似于 @ref{1eff,,read()}，可能对下层原始流发起多次读取，除非后者为交互式。

@ref{a81,,BlockingIOError} 会在下层原始流不处于阻塞模式，并且当前没有可用数据时被引发。
@end deffn

@geindex readinto1() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase readinto1}@anchor{7fc}
@deffn {方法} readinto1 (b, /)

将字节数据读入预先分配的可写 @ref{6e9,,bytes-like object} @emph{b}，其中至多使用一次对下层原始流 @ref{7fd,,read()} (或 @ref{7fe,,readinto()}) 方法的调用。 返回所读取的字节数。

@ref{a81,,BlockingIOError} 会在下层原始流不处于阻塞模式，并且当前没有可用数据时被引发。


3.5 新版功能.

@end deffn

@geindex write() (io.BufferedIOBase 方法)
@anchor{library/io io BufferedIOBase write}@anchor{68a}
@deffn {方法} write (b, /)

写入给定的 @ref{6e9,,bytes-like object} @emph{b}，并返回写入的字节数 (总是等于 @emph{b} 的字节长度，因为如果写入失败则会引发 @ref{30b,,OSError})。 根据具体实现的不同，这些字节可能被实际写入下层流，或是出于运行效率和冗余等考虑而暂存于缓冲区。

当处于非阻塞模式时，如果需要将数据写入原始流但它无法在不阻塞的情况下接受所有数据则将引发 @ref{a81,,BlockingIOError}。

调用者可能会在此方法返回后释放或改变 @emph{b}，因此该实现应当仅在方法调用期间访问 @emph{b}。
@end deffn
@end deffn

@node 原始文件 I/O,缓冲流,I/O 基类,类的层次结构
@anchor{library/io raw-file-i-o}@anchor{2183}
@subsubsection 原始文件 I/O


@geindex FileIO (io 中的类)
@anchor{library/io io FileIO}@anchor{d74}
@deffn {类} io.FileIO (name, mode='r', closefd=True, opener=None)

代表一个包含字节数据的 OS 层级文件的原始二进制流。 它继承自 @ref{afa,,RawIOBase}。

@emph{name} 可以是以下两项之一：


@itemize *

@item 
代表将被打开的文件路径的字符串或 @ref{172,,bytes} 对象。 在此情况下 closefd 必须为 @code{True} (默认值) 否则将会引发异常。

@item 
代表一个现有 OS 层级文件描述符的号码的整数，作为结果的 @ref{d74,,FileIO} 对象将可访问该文件。 当 FileIO 对象被关闭时此 fd 也将被关闭，除非 @emph{closefd} 设为 @code{False}。
@end itemize

@emph{mode} 可以为 @code{'r'}, @code{'w'}, @code{'x'} 或 @code{'a'} 分别表示读取（默认模式）、写入、独占新建或添加。 如果以写入或添加模式打开的文件不存在将自动新建；当以写入模式打开时文件将先清空。 以新建模式打开时如果文件已存在则将引发 @ref{a42,,FileExistsError}。 以新建模式打开文件也意味着要写入，因此该模式的行为与 @code{'w'} 类似。 在模式中附带 @code{'+'} 将允许同时读取和写入。

该类的 @code{read()} (当附带正值参数调用时), @code{readinto()} 和 @code{write()} 方法将只执行一次系统调用。

可以通过传入一个可调用对象作为 @emph{opener} 来使用自定义文件打开器。 然后通过调用 @emph{opener} 并传入 (@emph{name}, @emph{flags}) 来获取文件对象所对应的下层文件描述符。 @emph{opener} 必须返回一个打开文件描述符（传入 @ref{762,,os.open} 作为 @emph{opener} 的结果在功能上将与传入 @code{None} 类似）。

新创建的文件是 @ref{8f1,,不可继承的}。

有关 opener 参数的示例，请参见内置函数 @ref{16f,,open()} 。


在 3.3 版更改: 增加了 @emph{opener} 参数。增加了 @code{'x'} 模式。



在 3.4 版更改: 文件现在禁止继承。


@ref{d74,,FileIO} 在继承自 @ref{afa,,RawIOBase} 和 @ref{313,,IOBase} 的现有成员以外还提供了以下数据属性和方法:

@geindex mode (io.FileIO 属性)
@anchor{library/io io FileIO mode}@anchor{2184}
@deffn {属性} mode

构造函数中给定的模式。
@end deffn

@geindex name (io.FileIO 属性)
@anchor{library/io io FileIO name}@anchor{1f9e}
@deffn {属性} name

文件名。当构造函数中没有给定名称时，这是文件的文件描述符。
@end deffn
@end deffn

@node 缓冲流,文本 I/O<2>,原始文件 I/O,类的层次结构
@anchor{library/io buffered-streams}@anchor{2185}
@subsubsection 缓冲流


相比原始 I/O，缓冲 I/O 流提供了针对 I/O 设备的更高层级接口。

@geindex BytesIO (io 中的类)
@anchor{library/io io BytesIO}@anchor{894}
@deffn {类} io.BytesIO (initial_bytes=b'@w{'})

一个使用内在字节缓冲区的二进制流。 它继承自 @ref{689,,BufferedIOBase}。 在 @ref{1190,,close()} 方法被调用时将会丢弃缓冲区。

可选参数 @emph{initial_bytes} 是一个包含初始数据的 @ref{6e9,,bytes-like object}。

@ref{894,,BytesIO} 在继承自 @ref{689,,BufferedIOBase} 和 @ref{313,,IOBase} 的成员以外还提供或重载了下列方法:

@geindex getbuffer() (io.BytesIO 方法)
@anchor{library/io io BytesIO getbuffer}@anchor{c48}
@deffn {方法} getbuffer ()

返回一个对应于缓冲区内容的可读写视图而不必拷贝其数据。 此外，改变视图将透明地更新缓冲区内容:

@example
>>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'
@end example

@cartouche
@quotation 注解 
只要视图保持存在，@ref{894,,BytesIO} 对象就无法被改变大小或关闭。
@end quotation
@end cartouche


3.2 新版功能.

@end deffn

@geindex getvalue() (io.BytesIO 方法)
@anchor{library/io io BytesIO getvalue}@anchor{1efc}
@deffn {方法} getvalue ()

返回包含整个缓冲区内容的 @ref{172,,bytes}。
@end deffn

@geindex read1() (io.BytesIO 方法)
@anchor{library/io io BytesIO read1}@anchor{2186}
@deffn {方法} read1 (size=-1, /)

在 @ref{894,,BytesIO} 中，这与 @ref{1eff,,read()} 相同。


在 3.7 版更改: @emph{size} 参数现在是可选的。

@end deffn

@geindex readinto1() (io.BytesIO 方法)
@anchor{library/io io BytesIO readinto1}@anchor{2187}
@deffn {方法} readinto1 (b, /)

在 @ref{894,,BytesIO} 中，这与 @ref{2180,,readinto()} 相同。


3.5 新版功能.

@end deffn
@end deffn

@geindex BufferedReader (io 中的类)
@anchor{library/io io BufferedReader}@anchor{c64}
@deffn {类} io.BufferedReader (raw, buffer_size=DEFAULT_BUFFER_SIZE)

一个提供对可读、不可查找的 @ref{afa,,RawIOBase} 原始二进制流的高层级访问的缓冲二进制流。 它继承自 @ref{689,,BufferedIOBase}。

当从此对象读取数据时，可能会从下层原始流请求更大量的数据，并存放到内部缓冲区中。 接下来可以在后续读取时直接返回缓冲数据。

根据给定的可读 @emph{raw} 流和 @emph{buffer_size} 创建 @ref{c64,,BufferedReader} 的构造器。 如果省略 @emph{buffer_size}，则会使用 @ref{175f,,DEFAULT_BUFFER_SIZE}。

@ref{c64,,BufferedReader} 在继承自 @ref{689,,BufferedIOBase} 和 @ref{313,,IOBase} 的成员以外还提供或重载了下列方法:

@geindex peek() (io.BufferedReader 方法)
@anchor{library/io io BufferedReader peek}@anchor{2188}
@deffn {方法} peek (size=0, /)

从流返回字节数据而不前移位置。 完成此调用将至多读取一次原始流。 返回的字节数量可能少于或多于请求的数量。
@end deffn

@geindex read() (io.BufferedReader 方法)
@anchor{library/io io BufferedReader read}@anchor{2189}
@deffn {方法} read (size=-1, /)

读取并返回 @emph{size} 个字节，如果 @emph{size} 未给定或为负值，则读取至 EOF 或是在非阻塞模式下读取调用将会阻塞。
@end deffn

@geindex read1() (io.BufferedReader 方法)
@anchor{library/io io BufferedReader read1}@anchor{218a}
@deffn {方法} read1 (size=-1, /)

在原始流上通过单次调用读取并返回至多 @emph{size} 个字节。 如果至少缓冲了一个字节，则只返回缓冲的字节。 在其他情况下，将执行一次原始流读取。


在 3.7 版更改: @emph{size} 参数现在是可选的。

@end deffn
@end deffn

@geindex BufferedWriter (io 中的类)
@anchor{library/io io BufferedWriter}@anchor{1763}
@deffn {类} io.BufferedWriter (raw, buffer_size=DEFAULT_BUFFER_SIZE)

一个提供对可写、不可查找的 @ref{afa,,RawIOBase} 原始二进制流的高层级访问的缓冲二进制流。 它继承自 @ref{689,,BufferedIOBase}。

当写入到此对象时，数据通常会被放入到内部缓冲区中。 缓冲区将在满足某些条件的情况下被写到下层的 @ref{afa,,RawIOBase} 对象，包括:


@itemize *

@item 
当缓冲区对于所有挂起数据而言太小时；

@item 
当 @ref{218b,,flush()} 被调用时

@item 
当（为 @ref{1764,,BufferedRandom} 对象）请求 @code{seek()} 时；

@item 
当 @ref{1763,,BufferedWriter} 对象被关闭或销毁时。
@end itemize

该构造器会为给定的可写 @emph{raw} 流创建一个 @ref{1763,,BufferedWriter}。 如果未给定 @emph{buffer_size}，则使用默认的 @ref{175f,,DEFAULT_BUFFER_SIZE}。

@ref{1763,,BufferedWriter} 在继承自 @ref{689,,BufferedIOBase} 和 @ref{313,,IOBase} 的成员以外还提供或重载了下列方法:

@geindex flush() (io.BufferedWriter 方法)
@anchor{library/io io BufferedWriter flush}@anchor{218b}
@deffn {方法} flush ()

将缓冲区中保存的字节数据强制放入原始流。 如果原始流发生阻塞则应当引发 @ref{a81,,BlockingIOError}。
@end deffn

@geindex write() (io.BufferedWriter 方法)
@anchor{library/io io BufferedWriter write}@anchor{218c}
@deffn {方法} write (b, /)

写入 @ref{6e9,,bytes-like object} @emph{b} 并返回写入的字节数。 当处于非阻塞模式时，如果缓冲区需要被写入但原始流发生阻塞则将引发 @ref{a81,,BlockingIOError}。
@end deffn
@end deffn

@geindex BufferedRandom (io 中的类)
@anchor{library/io io BufferedRandom}@anchor{1764}
@deffn {类} io.BufferedRandom (raw, buffer_size=DEFAULT_BUFFER_SIZE)

一个提供对不可查找的 @ref{afa,,RawIOBase} 原始二进制流的高层级访问的缓冲二进制流。 它继承自 @ref{c64,,BufferedReader} 和 @ref{1763,,BufferedWriter}。

该构造器会为在第一个参数中给定的可查找原始流创建一个读取器和写入器。 如果省略 @emph{buffer_size} 则使用默认的 @ref{175f,,DEFAULT_BUFFER_SIZE}。

@ref{1764,,BufferedRandom} 能做到 @ref{c64,,BufferedReader} 或 @ref{1763,,BufferedWriter} 所能做的任何事。 此外，还会确保实现 @code{seek()} 和 @code{tell()}。
@end deffn

@geindex BufferedRWPair (io 中的类)
@anchor{library/io io BufferedRWPair}@anchor{2177}
@deffn {类} io.BufferedRWPair (reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, /)

一个提供对两个不可查找的 @ref{afa,,RawIOBase} 原始二进制流的高层级访问的缓冲二进制流 --- 一个可读，另一个可写。 它继承自 @ref{689,,BufferedIOBase}。

@emph{reader} 和 @emph{writer} 分别是可读和可写的 @ref{afa,,RawIOBase} 对象。 如果省略 @emph{buffer_size} 则使用默认的 @ref{175f,,DEFAULT_BUFFER_SIZE}。

@ref{2177,,BufferedRWPair} 实现了 @ref{689,,BufferedIOBase} 的所有方法，但 @ref{2182,,detach()} 除外，调用该方法将引发 @ref{10cc,,UnsupportedOperation}。

@cartouche
@quotation 警告 
@ref{2177,,BufferedRWPair} 不会尝试同步访问其下层的原始流。 你不应当将传给它与读取器和写入器相同的对象；而要改用 @ref{1764,,BufferedRandom}。
@end quotation
@end cartouche
@end deffn

@node 文本 I/O<2>,,缓冲流,类的层次结构
@anchor{library/io id1}@anchor{218d}
@subsubsection 文本 I/O


@geindex TextIOBase (io 中的类)
@anchor{library/io io TextIOBase}@anchor{d09}
@deffn {类} io.TextIOBase

文本流的基类。 该类提供了基于字符和行的流 I/O 接口。 它继承自 @ref{313,,IOBase}。

@ref{d09,,TextIOBase} 在来自 @ref{313,,IOBase} 的成员以外还提供或重载了以下数据属性和方法:

@geindex encoding (io.TextIOBase 属性)
@anchor{library/io io TextIOBase encoding}@anchor{218e}
@deffn {属性} encoding

用于将流的字节串解码为字符串以及将字符串编码为字节串的编码格式名称。
@end deffn

@geindex errors (io.TextIOBase 属性)
@anchor{library/io io TextIOBase errors}@anchor{218f}
@deffn {属性} errors

解码器或编码器的错误设置。
@end deffn

@geindex newlines (io.TextIOBase 属性)
@anchor{library/io io TextIOBase newlines}@anchor{2190}
@deffn {属性} newlines

一个字符串、字符串元组或者 @code{None}，表示目前已经转写的新行。 根据具体实现和初始构造器旗标的不同，此属性或许会不可用。
@end deffn

@geindex buffer (io.TextIOBase 属性)
@anchor{library/io io TextIOBase buffer}@anchor{d0a}
@deffn {属性} buffer

由 @ref{d09,,TextIOBase} 处理的下层二进制缓冲区（为一个 @ref{689,,BufferedIOBase} 的实例）。 它不是 @ref{d09,,TextIOBase} API 的组成部分并且不存在于某些实现中。
@end deffn

@geindex detach() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase detach}@anchor{2191}
@deffn {方法} detach ()

从 @ref{d09,,TextIOBase} 分离出下层二进制缓冲区并将其返回。

在下层缓冲区被分离后，@ref{d09,,TextIOBase} 将处于不可用的状态。

某些 @ref{d09,,TextIOBase} 的实现，例如 @ref{924,,StringIO} 可能并无下层缓冲区的概念，因此调用此方法将引发 @ref{10cc,,UnsupportedOperation}。


3.1 新版功能.

@end deffn

@geindex read() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase read}@anchor{2192}
@deffn {方法} read (size=-1, /)

从流中读取至多 @emph{size} 个字符并以单个 @ref{206,,str} 的形式返回。 如果 @emph{size} 为负值或 @code{None}，则读取至 EOF。
@end deffn

@geindex readline() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase readline}@anchor{1da3}
@deffn {方法} readline (size=-1, /)

读取至换行符或 EOF 并返回单个 @code{str}。 如果流已经到达 EOF，则将返回一个空字符串。

如果指定了 @emph{size} ，最多将读取 @emph{size} 个字符。
@end deffn

@geindex seek() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase seek}@anchor{2193}
@deffn {方法} seek (offset, whence=SEEK_SET, /)

将流位置改为给定的偏移位置 @emph{offset}。 具体行为取决于 @emph{whence} 形参。 @emph{whence} 的默认值为 @code{SEEK_SET}。


@itemize *

@item 
@code{SEEK_SET} 或 @code{0}: 从流的开始位置起查找（默认值）；@emph{offset} 必须为 @ref{2194,,TextIOBase.tell()} 所返回的数值或为零。 任何其他 @emph{offset} 值都将导致未定义的行为。

@item 
@code{SEEK_CUR} 或 @code{1}: "查找" 到当前位置；@emph{offset} 必须为零，表示无操作（所有其他值均不受支持）。

@item 
@code{SEEK_END} 或 @code{2}: 查找到流的末尾；@emph{offset} 必须为零（所有其他值均不受支持）。
@end itemize

以不透明数字形式返回新的绝对位置。


3.1 新版功能: @code{SEEK_*} 常量.

@end deffn

@geindex tell() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase tell}@anchor{2194}
@deffn {方法} tell ()

以不透明数字形式返回当前流的位置。 该数字通常并不代表下层二进制存储中对应的字节数。
@end deffn

@geindex write() (io.TextIOBase 方法)
@anchor{library/io io TextIOBase write}@anchor{2195}
@deffn {方法} write (s, /)

将字符串 @emph{s} 写入到流并返回写入的字符数。
@end deffn
@end deffn

@geindex TextIOWrapper (io 中的类)
@anchor{library/io io TextIOWrapper}@anchor{6f4}
@deffn {类} io.TextIOWrapper (buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)

一个提供对 @ref{689,,BufferedIOBase} 缓冲二进制流的高层级访问的缓冲文本流。 它继承自 @ref{d09,,TextIOBase}。

@emph{encoding} 给出流被解码或编码时将使用的编码格式。 它默认为 @ref{4b4,,locale.getpreferredencoding(False)}。

@emph{errors} 是一个可选的字符串，它指明编码格式和编码格式错误的处理方式。 传入 @code{'strict'} 将在出现编码格式错误时引发 @ref{16d,,ValueError} (默认值 @code{None} 具有相同的效果)，传入 @code{'ignore'} 将忽略错误。 (请注意忽略编码格式错误会导致数据丢失。)  @code{'replace'} 会在出现错误数据时插入一个替换标记 (例如 @code{'?'})。 @code{'backslashreplace'} 将把错误数据替换为一个反斜杠转义序列。 在写入时，还可以使用 @code{'xmlcharrefreplace'} (替换为适当的 XML 字符引用)  或 @code{'namereplace'} (替换为 @code{\N@{...@}} 转义序列)。 任何其他通过 @ref{ec1,,codecs.register_error()} 注册的错误处理方式名称也可以被接受。

@geindex universal newlines; io.TextIOWrapper class

@emph{newline} 控制行结束符处理方式。 它可以为 @code{None}, @code{'@w{'}}, @code{'\n'}, @code{'\r'} 和 @code{'\r\n'}。 其工作原理如下:


@itemize *

@item 
当从流读取输入时，如果 @emph{newline} 为 @code{None}，则将启用 @ref{6f5,,universal newlines} 模式。 输入中的行结束符可以为 @code{'\n'}, @code{'\r'} 或 @code{'\r\n'}，在返回给调用者之前它们会被统一转写为 @code{'\n'}。 如果 @emph{newline} 为 @code{'@w{'}}，也会启用通用换行模式，但行结束符会不加转写即返回给调用者。 如果 @emph{newline} 具有任何其他合法的值，则输入行将仅由给定的字符串结束，并且行结束符会不加转写即返回给调用者。

@item 
将输出写入流时，如果 @emph{newline} 为 @code{None}，则写入的任何 @code{'\n'} 字符都将转换为系统默认行分隔符 @ref{1762,,os.linesep}。如果 @emph{newline} 是 @code{'@w{'}} 或 @code{'\n'}，则不进行翻译。如果 @emph{newline} 是任何其他合法值，则写入的任何 @code{'\n'} 字符将被转换为给定的字符串。
@end itemize

如果 @emph{line_buffering} 为 @code{True}，则当一个写入调用包含换行符或回车时将会应用 @code{flush()}。

如果 @emph{write_through} 为 @code{True}，对 @code{write()} 的调用会确保不被缓冲：在 @ref{6f4,,TextIOWrapper} 对象上写入的任何数据会立即交给其下层的 @emph{buffer} 来处理。


在 3.3 版更改: 已添加 @emph{write_through} 参数



在 3.3 版更改: 默认的 @emph{encoding} 现在将为 @code{locale.getpreferredencoding(False)} 而非 @code{locale.getpreferredencoding()}。 不要使用 @ref{2196,,locale.setlocale()} 来临时改变区域编码格式，要使用当前区域编码格式而不是用户的首选编码格式。


@ref{6f4,,TextIOWrapper} 在继承自 @ref{d09,,TextIOBase} 和 @ref{313,,IOBase} 的现有成员以外还提供了以下数据属性和方法:

@geindex line_buffering (io.TextIOWrapper 属性)
@anchor{library/io io TextIOWrapper line_buffering}@anchor{2197}
@deffn {属性} line_buffering

是否启用行缓冲。
@end deffn

@geindex write_through (io.TextIOWrapper 属性)
@anchor{library/io io TextIOWrapper write_through}@anchor{2198}
@deffn {属性} write_through

写入是否要立即传给下层的二进制缓冲。


3.7 新版功能.

@end deffn

@geindex reconfigure() (io.TextIOWrapper 方法)
@anchor{library/io io TextIOWrapper reconfigure}@anchor{4ac}
@deffn {方法} reconfigure (*[, encoding][, errors][, newline][,                      line_buffering][, write_through])

使用 @emph{encoding}, @emph{errors}, @emph{newline}, @emph{line_buffering} 和 @emph{write_through} 的新设置来重新配置此文本流。

未指定的形参将保留当前设定，例外情况是当指定了 @emph{encoding} 但未指定 @emph{errors} 时将会使用 @code{errors='strict'}。

如果已经有数据从流中被读取则将无法再改变编码格式或行结束符。 另一方面，在写入数据之后再改变编码格式则是可以的。

此方法会在设置新的形参之前执行隐式的流刷新。


3.7 新版功能.

@end deffn
@end deffn

@geindex StringIO (io 中的类)
@anchor{library/io io StringIO}@anchor{924}
@deffn {类} io.StringIO (initial_value='@w{'}, newline='\n')

一个使用内存文本缓冲的文本流。 它继承自 @ref{d09,,TextIOBase}。

当 @ref{1190,,close()} 方法被调用时将会丢弃文本缓冲区。

缓冲区的初始值可通过提供 @emph{initial_value} 来设置。 如果启用了行结束符转写，换行将以 @ref{2195,,write()} 所用的方式被编码。 数据流位置将被设为缓冲区的开头。

@emph{newline} 参数的规则与 @ref{6f4,,TextIOWrapper} 所用的一致，不同之处在于当将输出写入到流时，如果 @emph{newline} 为 @code{None}，则在所有平台上换行符都会被写入为 @code{\n}。

@ref{924,,StringIO} 在继承自 @ref{d09,,TextIOBase} 和 @ref{313,,IOBase} 的现有成员以外还提供了以下方法:

@geindex getvalue() (io.StringIO 方法)
@anchor{library/io io StringIO getvalue}@anchor{2199}
@deffn {方法} getvalue ()

返回一个包含缓冲区全部内容的 @code{str}。 换行符会以与 @ref{2192,,read()} 相同的方式被编码，但是流的位置不会被改变。
@end deffn

用法示例：

@example
import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
@end example
@end deffn

@geindex universal newlines; io.IncrementalNewlineDecoder class

@geindex IncrementalNewlineDecoder (io 中的类)
@anchor{library/io io IncrementalNewlineDecoder}@anchor{219a}
@deffn {类} io.IncrementalNewlineDecoder

用于在 @ref{6f5,,universal newlines} 模式下解码换行符的辅助编解码器。 它继承自 @ref{19ba,,codecs.IncrementalDecoder}。
@end deffn

@node 性能<3>,,类的层次结构,io --- 处理流的核心工具
@anchor{library/io performance}@anchor{219b}
@subsubsection 性能


本节讨论所提供的具体 I/O 实现的性能。

@menu
* 二进制 I/O: 二进制 I/O<2>. 
* 文本 I/O: 文本 I/O<3>. 
* 多线程: 多线程<3>. 
* 可重入性:: 

@end menu

@node 二进制 I/O<2>,文本 I/O<3>,,性能<3>
@anchor{library/io id2}@anchor{219c}
@subsubsection 二进制 I/O


即使在用户请求单个字节时，也只读取和写入大块数据。通过该方法，缓冲 I/O 隐藏了操作系统调用和执行无缓冲 I/O 例程时的任何低效性。增益取决于操作系统和执行的 I/O 类型。例如，在某些现代操作系统上（例如 Linux），无缓冲磁盘 I/O 可以与缓冲 I/O 一样快。但最重要的是，无论平台和支持设备如何，缓冲 I/O 都能提供可预测的性能。因此，对于二进制数据，应首选使用缓冲的 I/O 而不是未缓冲的 I/O 。

@node 文本 I/O<3>,多线程<3>,二进制 I/O<2>,性能<3>
@anchor{library/io id3}@anchor{219d}
@subsubsection 文本 I/O


二进制存储（如文件）上的文本 I/O 比同一存储上的二进制 I/O 慢得多，因为它需要使用字符编解码器在Unicode和二进制数据之间进行转换。这在处理大量文本数据（如大型日志文件）时会变得非常明显。此外，由于使用的重构算法 @code{TextIOWrapper.tell()} 和 @code{TextIOWrapper.seek()} 都相当慢。

@ref{924,,StringIO} 是原生的内存 Unicode 容器，速度与 @ref{894,,BytesIO} 相似。

@node 多线程<3>,可重入性,文本 I/O<3>,性能<3>
@anchor{library/io multi-threading}@anchor{219e}
@subsubsection 多线程


@ref{d74,,FileIO} 对象是线程安全的，只要它们封装的操作系统调用（比如Unix下的 @code{read(2)} ）也是线程安全的。

二进制缓冲对象（例如 @ref{c64,,BufferedReader}, @ref{1763,,BufferedWriter}, @ref{1764,,BufferedRandom} 和 @ref{2177,,BufferedRWPair}）使用锁来保护其内部结构；因此，可以安全地一次从多个线程中调用它们。

@ref{6f4,,TextIOWrapper} 对象不再是线程安全的。

@node 可重入性,,多线程<3>,性能<3>
@anchor{library/io reentrancy}@anchor{219f}
@subsubsection 可重入性


二进制缓冲对象（ @ref{c64,,BufferedReader} ， @ref{1763,,BufferedWriter} ， @ref{1764,,BufferedRandom} 和 @ref{2177,,BufferedRWPair} 的实例）不是可重入的。虽然在正常情况下不会发生可重入调用，但仍可能会在 @ref{ea,,signal} 处理程序执行 I/O 时产生。如果线程尝试重入已经访问的缓冲对象，则会引发 @ref{3e4,,RuntimeError} 。注意，这并不禁止其他线程进入缓冲对象。

上面的内容隐式地扩展到文本文件中，因为 @ref{16f,,open()} 函数将把缓冲对象封装在 @ref{6f4,,TextIOWrapper} 中。 这包括标准流，因而也会影响内置的 @ref{97a,,print()} 函数。

@node time --- 时间的访问和转换,argparse --- 命令行选项、参数和子命令解析器,io --- 处理流的核心工具,通用操作系统服务
@anchor{library/time doc}@anchor{21a0}@anchor{library/time module-time}@anchor{10c}@anchor{library/time time-time-access-and-conversions}@anchor{21a1}
@subsection @code{time} --- 时间的访问和转换


@geindex time (模块)


__________________________________________________________________


该模块提供了各种与时间相关的函数。相关功能还可以参阅 @ref{30,,datetime} 和 @ref{14,,calendar} 模块。

尽管所有平台皆可使用此模块，但模块内的函数并非所有平台都可用。此模块中定义的大多数函数的实现都是调用其所在平台的C语言库的同名函数。因为这些函数的语义可能因平台而异，所以使用时最好查阅对应平台的相关文档。

下面是一些术语和惯例的解释.
@anchor{library/time epoch}@anchor{1fa7}
@geindex epoch


@itemize *

@item 
@emph{epoch} 是时间开始的点，其值取决于平台。对于Unix， epoch 是1970年1月1日00:00:00（UTC）。要找出给定平台上的 epoch ，请查看 @code{time.gmtime(0)} 。
@end itemize

@geindex seconds since the epoch


@itemize *

@item 
术语 @emph{纪元秒数} 是指自 epoch （纪元）时间点以来经过的总秒数，通常不包括 闰秒@footnote{https://en.wikipedia.org/wiki/Leap_second}。 在所有符合 POSIX 标准的平台上，闰秒都不会记录在总秒数中。
@end itemize

@geindex Year 2038


@itemize *

@item 
此模块中的函数可能无法处理纪元之前或遥远未来的日期和时间。“遥远未来”的定义由对应的C语言库决定；对于32位系统，它通常是指2038年及以后。
@end itemize

@geindex 2-digit years


@itemize *

@item 
函数 @ref{e5e,,strptime()} 在接收到 @code{%y} 格式代码时可以解析使用 2 位数表示的年份。当解析 2 位数年份时，函数会按照 POSIX 和 ISO C 标准进行年份转换：数值 69--99 被映射为 1969--1999；数值 0--68 被映射为 2000--2068。
@end itemize

@geindex UTC
@geindex Coordinated Universal Time
@geindex Greenwich Mean Time


@itemize *

@item 
UTC是协调世界时（Coordinated Universal Time）的缩写。它以前也被称为格林威治标准时间（GMT）。使用UTC而不是CUT作为缩写是英语与法语（Temps Universel Coordonné）之间妥协的结果，不是什么低级错误。
@end itemize

@geindex Daylight Saving Time


@itemize *

@item 
DST是夏令时（Daylight Saving Time）的缩写，在一年的某一段时间中将当地时间调整（通常）一小时。 DST的规则非常神奇（由当地法律确定），并且每年的起止时间都不同。C语言库中有一个表格，记录了各地的夏令时规则（实际上，为了灵活性，C语言库通常是从某个系统文件中读取这张表）。从这个角度而言，这张表是夏令时规则的唯一权威真理。

@item 
由于平台限制，各种实时函数的精度可能低于其值或参数所要求（或给定）的精度。例如，在大多数Unix系统上，时钟频率仅为每秒50或100次。

@item 
另一方面， @ref{436,,time()} 和 @ref{77d,,sleep()} 的精度优于它们的Unix等价物：时间表示为浮点数，@ref{436,,time()} 返回最准确的时间 （使用Unix @code{gettimeofday()} 如果可用），并且 @ref{77d,,sleep()} 将接受非零分数的时间（Unix @code{select()} 用于实现此功能，如果可用）。

@item 
时间值由 @ref{c1a,,gmtime()}，@ref{10c9,,localtime()} 和 @ref{e5e,,strptime()} 返回，并被 @ref{c3e,,asctime()}， @ref{c3f,,mktime()} 和 @ref{c40,,strftime()} 接受，是一个 9 个整数的序列。 @ref{c1a,,gmtime()}， @ref{10c9,,localtime()} 和 @ref{e5e,,strptime()} 的返回值还提供各个字段的属性名称。

请参阅 @ref{69a,,struct_time} 以获取这些对象的描述。


在 3.3 版更改: 在平台支持相应的 @code{struct tm} 成员时，@ref{69a,,struct_time} 类型被扩展提供 @code{tm_gmtoff} 和 @code{tm_zone} 属性。



在 3.6 版更改: @ref{69a,,struct_time} 的属性 @code{tm_gmtoff} 和 @code{tm_zone} 现在可在所有平台上使用。


@item 
使用以下函数在时间表示之间进行转换：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

从

@tab

到

@tab

使用

@item

自纪元以来的秒数

@tab

UTC 的 @ref{69a,,struct_time}

@tab

@ref{c1a,,gmtime()}

@item

自纪元以来的秒数

@tab

本地时间的 @ref{69a,,struct_time}

@tab

@ref{10c9,,localtime()}

@item

UTC 的 @ref{69a,,struct_time}

@tab

自纪元以来的秒数

@tab

@ref{1ac2,,calendar.timegm()}

@item

本地时间的 @ref{69a,,struct_time}

@tab

自纪元以来的秒数

@tab

@ref{c3f,,mktime()}

@end multitable

@end itemize

@menu
* 函数: 函数<3>. 
* Clock ID 常量:: 
* 时区常量:: 

@end menu

@node 函数<3>,Clock ID 常量,,time --- 时间的访问和转换
@anchor{library/time functions}@anchor{21a2}@anchor{library/time time-functions}@anchor{21a3}
@subsubsection 函数


@geindex asctime() (在 time 模块中)
@anchor{library/time time asctime}@anchor{c3e}
@deffn {函数} time.asctime ([t])

转换由 @ref{c1a,,gmtime()} 或 @ref{10c9,,localtime()} 所返回的表示时间的元组或 @ref{69a,,struct_time} 为以下形式的字符串: @code{'Sun Jun 20 23:21:05 1993'}。 日期字段的长度为两个字符，如果日期只有一个数字则会以零填充，例如: @code{'Wed Jun  9 04:26:40 1993'}。

如果未提供 @emph{t}，则会使用 @ref{10c9,,localtime()} 所返回的当前时间。  @ref{c3e,,asctime()} 不会使用区域设置信息。

@cartouche
@quotation 注解 
与同名的C函数不同， @ref{c3e,,asctime()} 不添加尾随换行符。
@end quotation
@end cartouche
@end deffn

@geindex pthread_getcpuclockid() (在 time 模块中)
@anchor{library/time time pthread_getcpuclockid}@anchor{508}
@deffn {函数} time.pthread_getcpuclockid (thread_id)

返回指定的 @emph{thread_id} 的特定于线程的CPU时间时钟的 @emph{clk_id} 。

使用 @ref{21b,,threading.Thread} 对象的 @ref{b90,,threading.get_ident()} 或 @ref{21a4,,ident} 属性为 @emph{thread_id} 获取合适的值。

@cartouche
@quotation 警告 
传递无效的或过期的 @emph{thread_id} 可能会导致未定义的行为，例如段错误。
@end quotation
@end cartouche

@ref{14c1,,可用性} ： Unix（有关详细信息，请参见 @code{pthread_getcpuclockid(3)} 的手册页）。


3.7 新版功能.

@end deffn

@geindex clock_getres() (在 time 模块中)
@anchor{library/time time clock_getres}@anchor{b93}
@deffn {函数} time.clock_getres (clk_id)

返回指定时钟 @emph{clk_id} 的分辨率（精度）。有关 @emph{clk_id} 的可接受值列表，请参阅 @ref{21a5,,Clock ID 常量} 。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex clock_gettime() (在 time 模块中)
@anchor{library/time time clock_gettime}@anchor{b94}
@deffn {函数} time.clock_gettime (clk_id) -> float

返回指定 @emph{clk_id} 时钟的时间。有关 @emph{clk_id} 的可接受值列表，请参阅 @ref{21a5,,Clock ID 常量} 。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex clock_gettime_ns() (在 time 模块中)
@anchor{library/time time clock_gettime_ns}@anchor{437}
@deffn {函数} time.clock_gettime_ns (clk_id) -> int

与 @ref{b94,,clock_gettime()} 相似，但返回时间为纳秒。

@ref{14c1,,Availability}: Unix.


3.7 新版功能.

@end deffn

@geindex clock_settime() (在 time 模块中)
@anchor{library/time time clock_settime}@anchor{b95}
@deffn {函数} time.clock_settime (clk_id, time: float)

设置指定 @emph{clk_id} 时钟的时间。 目前， @ref{fb9,,CLOCK_REALTIME} 是 @emph{clk_id} 唯一可接受的值。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex clock_settime_ns() (在 time 模块中)
@anchor{library/time time clock_settime_ns}@anchor{438}
@deffn {函数} time.clock_settime_ns (clk_id, time: int)

与 @ref{b95,,clock_settime()} 相似，但设置时间为纳秒。

@ref{14c1,,Availability}: Unix.


3.7 新版功能.

@end deffn

@geindex ctime() (在 time 模块中)
@anchor{library/time time ctime}@anchor{1a40}
@deffn {函数} time.ctime ([secs])

转换以距离初始纪元的秒数表示的时间为以下形式的字符串: @code{'Sun Jun 20 23:21:05 1993'} 代表本地时间。 日期字段的长度为两个字符，如果日期只有一个数字则会以零填充，例如: @code{'Wed Jun  9 04:26:40 1993'}。

如果 @emph{secs} 未提供或为 @ref{204,,None}，则使用 @ref{436,,time()} 所返回的当前时间。 @code{ctime(secs)} 等价于 @code{asctime(localtime(secs))}。 @ref{1a40,,ctime()} 不会使用区域设置信息。
@end deffn

@geindex get_clock_info() (在 time 模块中)
@anchor{library/time time get_clock_info}@anchor{b92}
@deffn {函数} time.get_clock_info (name)

获取有关指定时钟的信息作为命名空间对象。 支持的时钟名称和读取其值的相应函数是：


@itemize *

@item 
@code{'monotonic'}: @ref{868,,time.monotonic()}

@item 
@code{'perf_counter'}: @ref{3d4,,time.perf_counter()}

@item 
@code{'process_time'}: @ref{3d5,,time.process_time()}

@item 
@code{'thread_time'}: @ref{1e8,,time.thread_time()}

@item 
@code{'time'}: @ref{436,,time.time()}
@end itemize

结果具有以下属性：


@itemize -

@item 
@emph{adjustable} ： 如果时钟可以自动更改（例如通过NTP守护程序）或由系统管理员手动更改，则为 @code{True} ，否则为 @code{False} 。

@item 
@emph{implementation} ： 用于获取时钟值的基础C函数的名称。有关可能的值，请参阅 @ref{21a5,,Clock ID 常量} 。

@item 
@emph{monotonic} ：如果时钟不能倒退，则为 @code{True} ，否则为 @code{False} 。

@item 
@emph{resolution} ： 以秒为单位的时钟分辨率（ @ref{1fe,,float} ）
@end itemize


3.3 新版功能.

@end deffn

@geindex gmtime() (在 time 模块中)
@anchor{library/time time gmtime}@anchor{c1a}
@deffn {函数} time.gmtime ([secs])

将以自 epoch 开始的秒数表示的时间转换为 UTC 的 @ref{69a,,struct_time} ，其中 dst 标志始终为零。 如果未提供 @emph{secs} 或为 @ref{204,,None} ，则使用 @ref{436,,time()} 所返回的当前时间。 一秒以内的小数将被忽略。 有关 @ref{69a,,struct_time} 对象的说明请参见上文。 有关此函数的逆操作请参阅 @ref{1ac2,,calendar.timegm()}。
@end deffn

@geindex localtime() (在 time 模块中)
@anchor{library/time time localtime}@anchor{10c9}
@deffn {函数} time.localtime ([secs])

与 @ref{c1a,,gmtime()} 相似但转换为当地时间。如果未提供 @emph{secs} 或为 @ref{204,,None} ，则使用由 @ref{436,,time()} 返回的当前时间。当 DST 适用于给定时间时，dst标志设置为 @code{1} 。

@ref{10c9,,localtime()} 可能会引发 @ref{a4a,,OverflowError} ，如果时间戳超出平台 C @code{localtime()} 或 @code{gmtime()} 函数支持的范围，并会在  @code{localtime()} 或 @code{gmtime()} 失败时引发 @ref{30b,,OSError} 。这通常被限制在1970至2038年之间。
@end deffn

@geindex mktime() (在 time 模块中)
@anchor{library/time time mktime}@anchor{c3f}
@deffn {函数} time.mktime (t)

这是 @ref{10c9,,localtime()} 的反函数。它的参数是 @ref{69a,,struct_time} 或者完整的 9 元组（因为需要 dst 标志；如果它是未知的则使用 @code{-1} 作为dst标志），它表示 @emph{local} 的时间，而不是 UTC 。它返回一个浮点数，以便与 @ref{436,,time()} 兼容。如果输入值不能表示为有效时间，则 @ref{a4a,,OverflowError} 或 @ref{16d,,ValueError} 将被引发（这取决于Python或底层C库是否捕获到无效值）。它可以生成时间的最早日期取决于平台。
@end deffn

@geindex monotonic() (在 time 模块中)
@anchor{library/time time monotonic}@anchor{868}
@deffn {函数} time.monotonic () -> float

（以小数表示的秒为单位）返回一个单调时钟的值，即不能倒退的时钟。 该时钟不受系统时钟更新的影响。 返回值的参考点未被定义，因此只有两次调用之间的差值才是有效的。


3.3 新版功能.



在 3.5 版更改: 该功能现在始终可用且始终在系统范围内。

@end deffn

@geindex monotonic_ns() (在 time 模块中)
@anchor{library/time time monotonic_ns}@anchor{439}
@deffn {函数} time.monotonic_ns () -> int

与 @ref{868,,monotonic()} 相似，但是返回时间为纳秒数。


3.7 新版功能.

@end deffn

@geindex perf_counter() (在 time 模块中)
@anchor{library/time time perf_counter}@anchor{3d4}
@deffn {函数} time.perf_counter () -> float

@geindex benchmarking

（以小数表示的秒为单位）返回一个性能计数器的值，即用于测量较短持续时间的具有最高有效精度的时钟。 它会包括睡眠状态所消耗的时间并且作用于全系统范围。 返回值的参考点未被定义，因此只有两次调用之间的差值才是有效的。


3.3 新版功能.

@end deffn

@geindex perf_counter_ns() (在 time 模块中)
@anchor{library/time time perf_counter_ns}@anchor{43a}
@deffn {函数} time.perf_counter_ns () -> int

与 @ref{3d4,,perf_counter()} 相似，但是返回时间为纳秒。


3.7 新版功能.

@end deffn

@geindex process_time() (在 time 模块中)
@anchor{library/time time process_time}@anchor{3d5}
@deffn {函数} time.process_time () -> float

@geindex CPU time
@geindex processor time
@geindex benchmarking

（以小数表示的秒为单位）返回当前进程的系统和用户 CPU 时间的总计值。 它不包括睡眠状态所消耗的时间。 根据定义它只作用于进程范围。 返回值的参考点未被定义，因此只有两次调用之间的差值才是有效的。


3.3 新版功能.

@end deffn

@geindex process_time_ns() (在 time 模块中)
@anchor{library/time time process_time_ns}@anchor{43b}
@deffn {函数} time.process_time_ns () -> int

与 @ref{3d5,,process_time()} 相似，但是返回时间为纳秒。


3.7 新版功能.

@end deffn

@geindex sleep() (在 time 模块中)
@anchor{library/time time sleep}@anchor{77d}
@deffn {函数} time.sleep (secs)

调用该方法的线程将被暂停执行 @cite{secs} 秒。参数可以是浮点数，以表示更为精确的睡眠时长。由于任何捕获到的信号都会终止 @ref{77d,,sleep()} 引发的该睡眠过程并开始执行信号的处理例程，因此实际的暂停时长可能小于请求的时长；此外，由于系统需要调度其他活动，实际暂停时长也可能比请求的时间长。


在 3.5 版更改: 现在，即使该睡眠过程被信号中断，该函数也会保证调用它的线程至少会睡眠 @emph{secs} 秒。信号处理例程抛出异常的情况除外。（欲了解我们做出这次改变的原因，请参见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} ）

@end deffn

@geindex % (percent); datetime format

@geindex strftime() (在 time 模块中)
@anchor{library/time time strftime}@anchor{c40}
@deffn {函数} time.strftime (format[, t])

转换一个元组或 @ref{69a,,struct_time} 表示的由 @ref{c1a,,gmtime()} 或 @ref{10c9,,localtime()} 返回的时间到由 @emph{format} 参数指定的字符串。如果未提供 @emph{t} ，则使用由 @ref{10c9,,localtime()} 返回的当前时间。 @emph{format} 必须是一个字符串。如果 @emph{t} 中的任何字段超出允许范围，则引发 @ref{16d,,ValueError} 。

0是时间元组中任何位置的合法参数；如果它通常是非法的，则该值被强制改为正确的值。

以下指令可以嵌入 @emph{format} 字符串中。它们显示时没有可选的字段宽度和精度规范，并被 @ref{c40,,strftime()} 结果中的指示字符替换：


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

指令

@tab

意义

@tab

注释

@item

@code{%a}

@tab

本地化的缩写星期中每日的名称。

@tab

@item

@code{%A}

@tab

本地化的星期中每日的完整名称。

@tab

@item

@code{%b}

@tab

本地化的月缩写名称。

@tab

@item

@code{%B}

@tab

本地化的月完整名称。

@tab

@item

@code{%c}

@tab

本地化的适当日期和时间表示。

@tab

@item

@code{%d}

@tab

十进制数 [01,31] 表示的月中日。

@tab

@item

@code{%H}

@tab

十进制数 [00,23] 表示的小时（24小时制）。

@tab

@item

@code{%I}

@tab

十进制数 [01,12] 表示的小时（12小时制）。

@tab

@item

@code{%j}

@tab

十进制数 [001,366] 表示的年中日。

@tab

@item

@code{%m}

@tab

十进制数 [01,12] 表示的月。

@tab

@item

@code{%M}

@tab

十进制数 [00,59] 表示的分钟。

@tab

@item

@code{%p}

@tab

本地化的 AM 或 PM 。

@tab

(1)

@item

@code{%S}

@tab

十进制数 [00,61] 表示的秒。

@tab

(2)

@item

@code{%U}

@tab

十进制数 [00,53] 表示的一年中的周数（星期日作为一周的第一天）。 在第一个星期日之前的新年中的所有日子都被认为是在第 0 周。

@tab

(3)

@item

@code{%w}

@tab

十进制数 [0(星期日),6] 表示的周中日。

@tab

@item

@code{%W}

@tab

十进制数 [00,53] 表示的一年中的周数（星期一作为一周的第一天）。 在第一个星期一之前的新年中的所有日子被认为是在第 0 周。

@tab

(3)

@item

@code{%x}

@tab

本地化的适当日期表示。

@tab

@item

@code{%X}

@tab

本地化的适当时间表示。

@tab

@item

@code{%y}

@tab

十进制数 [00,99] 表示的没有世纪的年份。

@tab

@item

@code{%Y}

@tab

十进制数表示的带世纪的年份。

@tab

@item

@code{%z}

@tab

时区偏移以格式 +HHMM 或 -HHMM 形式的 UTC/GMT 的正或负时差指示，其中H表示十进制小时数字，M表示小数分钟数字 [-23:59, +23:59] 。@footnote{@w{(1)} 
现在不推荐使用 @code{%Z} ，但是所有 ANSI C 库都不支持扩展为首选小时/分钟偏移量的`@w{`}%z`@w{`}转义符。 此外，严格的 1982 年原始 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 标准要求两位数的年份（@code{%y`@w{`}而不是`@w{`}%Y}），但是实际在2000年之前很久就转移到了4位数年。之后， 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 已经废弃了，4位数的年份首先被推荐 
@geindex RFC; RFC 1123
@uref{https://tools.ietf.org/html/rfc1123.html,RFC 1123} ，然后被 
@geindex RFC; RFC 2822
@uref{https://tools.ietf.org/html/rfc2822.html,RFC 2822} 强制执行。
}

@tab

@item

@code{%Z}

@tab

时区名称（如果不存在时区，则不包含字符）。已弃用。 @footnote{@w{(1)} 
现在不推荐使用 @code{%Z} ，但是所有 ANSI C 库都不支持扩展为首选小时/分钟偏移量的`@w{`}%z`@w{`}转义符。 此外，严格的 1982 年原始 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 标准要求两位数的年份（@code{%y`@w{`}而不是`@w{`}%Y}），但是实际在2000年之前很久就转移到了4位数年。之后， 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 已经废弃了，4位数的年份首先被推荐 
@geindex RFC; RFC 1123
@uref{https://tools.ietf.org/html/rfc1123.html,RFC 1123} ，然后被 
@geindex RFC; RFC 2822
@uref{https://tools.ietf.org/html/rfc2822.html,RFC 2822} 强制执行。
}

@tab

@item

@code{%%}

@tab

字面的 @code{'%'} 字符。

@tab

@end multitable


注释:


@enumerate 

@item 
当与 @ref{e5e,,strptime()} 函数一起使用时，如果使用 @code{%I} 指令来解析小时， @code{%p} 指令只影响输出小时字段。

@item 
范围真的是 @code{0} 到 @code{61} ；值 @code{60} 在表示 leap seconds@footnote{https://en.wikipedia.org/wiki/Leap_second} 的时间戳中有效，并且由于历史原因支持值 @code{61} 。

@item 
当与 @ref{e5e,,strptime()} 函数一起使用时， @code{%U} 和 @code{%W} 仅用于指定星期几和年份的计算。
@end enumerate

下面是一个示例，一个与 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} Internet电子邮件标准以兼容的日期格式。  @footnote{@w{(1)} 
现在不推荐使用 @code{%Z} ，但是所有 ANSI C 库都不支持扩展为首选小时/分钟偏移量的`@w{`}%z`@w{`}转义符。 此外，严格的 1982 年原始 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 标准要求两位数的年份（@code{%y`@w{`}而不是`@w{`}%Y}），但是实际在2000年之前很久就转移到了4位数年。之后， 
@geindex RFC; RFC 822
@uref{https://tools.ietf.org/html/rfc822.html,RFC 822} 已经废弃了，4位数的年份首先被推荐 
@geindex RFC; RFC 1123
@uref{https://tools.ietf.org/html/rfc1123.html,RFC 1123} ，然后被 
@geindex RFC; RFC 2822
@uref{https://tools.ietf.org/html/rfc2822.html,RFC 2822} 强制执行。
}

@example
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'
@end example

某些平台可能支持其他指令，但只有此处列出的指令具有 ANSI C 标准化的含义。要查看平台支持的完整格式代码集，请参阅 @code{strftime(3)} 文档。

在某些平台上，可选的字段宽度和精度规范可以按照以下顺序紧跟在指令的初始 @code{'%'} 之后；这也不可移植。字段宽度通常为2，除了 @code{%j} ，它是3。
@end deffn

@geindex % (percent); datetime format

@geindex strptime() (在 time 模块中)
@anchor{library/time time strptime}@anchor{e5e}
@deffn {函数} time.strptime (string[, format])

根据格式解析表示时间的字符串。 返回值为一个被 @ref{c1a,,gmtime()} 或 @ref{10c9,,localtime()} 返回的 @ref{69a,,struct_time} 。

@emph{format} 参数使用与 @ref{c40,,strftime()} 相同的指令。 它默认为匹配 @ref{1a40,,ctime()} 所返回的格式 @code{"%a %b %d %H:%M:%S %Y"`} 。 如果 @emph{string} 不能根据 @emph{format} 来解析，或者解析后它有多余的数据，则会引发 @ref{16d,,ValueError}。 当无法推断出更准确的值时，用于填充任何缺失数据的默认值是 @code{(1900, 1, 1, 0, 0, 0, 0, 1, -1)} 。 @emph{string} 和 @emph{format} 都必须为字符串。

例如:

@example
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")   
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
@end example

支持 @code{%Z} 指令是基于 @code{tzname} 中包含的值以及 @code{daylight} 是否为真。因此，它是特定于平台的，除了识别始终已知的 UTC 和 GMT （并且被认为是非夏令时时区）。

仅支持文档中指定的指令。因为每个平台都实现了 @code{strftime()} ，它有时会提供比列出的指令更多的指令。但是 @code{strptime()} 独立于任何平台，因此不一定支持所有未记录为支持的可用指令。
@end deffn

@geindex struct_time (time 中的类)
@anchor{library/time time struct_time}@anchor{69a}
@deffn {类} time.struct_time

返回的时间值序列的类型为 @ref{c1a,,gmtime()} 、 @ref{10c9,,localtime()} 和 @ref{e5e,,strptime()} 。它是一个带有 @ref{b84,,named tuple} 接口的对象：可以通过索引和属性名访问值。 存在以下值：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

属性

@tab

值

@item

0

@tab

@code{tm_year}

@tab

（例如，1993）

@item

1

@tab

@code{tm_mon}

@tab

range [1, 12]

@item

2

@tab

@code{tm_mday}

@tab

range [1, 31]

@item

3

@tab

@code{tm_hour}

@tab

range [0, 23]

@item

4

@tab

@code{tm_min}

@tab

range [0, 59]

@item

5

@tab

@code{tm_sec}

@tab

range [0, 61]； 见 @ref{c40,,strftime()} 介绍中的 @strong{(2)}

@item

6

@tab

@code{tm_wday}

@tab

range [0, 6] ，周一为 0

@item

7

@tab

@code{tm_yday}

@tab

range [1, 366]

@item

8

@tab

@code{tm_isdst}

@tab

0, 1 或 -1；如下所示

@item

N/A

@tab

@code{tm_zone}

@tab

时区名称的缩写

@item

N/A

@tab

@code{tm_gmtoff}

@tab

以秒为单位的UTC以东偏离

@end multitable


请注意，与C结构不同，月份值是 [1,12] 的范围，而不是 [0,11] 。

在调用 @ref{c3f,,mktime()} 时， @code{tm_isdst} 可以在夏令时生效时设置为1，而在夏令时不生效时设置为0。 值-1表示这是未知的，并且通常会导致填写正确的状态。

当一个长度不正确的元组被传递给期望 @ref{69a,,struct_time} 的函数，或者具有错误类型的元素时，会引发 @ref{1ff,,TypeError} 。
@end deffn

@geindex time() (在 time 模块中)
@anchor{library/time time time}@anchor{436}
@deffn {函数} time.time () -> float

返回以浮点数表示的从 @ref{1fa7,,epoch} 开始的秒数的时间值。 epoch 的具体日期和 leap seconds@footnote{https://en.wikipedia.org/wiki/Leap_second} 的处理取决于平台。 在 Windows 和大多数 Unix 系统中， epoch 是 1970 年 1 月 1 日 00:00:00 (UTC)，并且闰秒将不计入从 epoch 开始的秒数。 这通常被称为 Unix 时间@footnote{https://en.wikipedia.org/wiki/Unix_time}。 要了解给定平台上 epoch 的具体定义，请查看 @code{gmtime(0)}。

请注意，即使时间总是作为浮点数返回，但并非所有系统都提供高于1秒的精度。虽然此函数通常返回非递减值，但如果在两次调用之间设置了系统时钟，则它可以返回比先前调用更低的值。

返回的数字 @ref{436,,time()} 可以通过将其传递给 @ref{c1a,,gmtime()} 函数或转换为UTC中更常见的时间格式（即年、月、日、小时等）或通过将它传递给 @ref{10c9,,localtime()} 函数获得本地时间。在这两种情况下都返回一个 @ref{69a,,struct_time} 对象，日历日期组件可以从中作为属性访问。
@end deffn

@geindex thread_time() (在 time 模块中)
@anchor{library/time time thread_time}@anchor{1e8}
@deffn {函数} time.thread_time () -> float

@geindex CPU time
@geindex processor time
@geindex benchmarking

（以小数表示的秒为单位）返回当前线程的系统和用户 CPU 时间的总计值。 它不包括睡眠状态所消耗的时间。 根据定义它只作用于线程范围。 返回值的参考点未被定义，因此只有两次调用之间的差值才是有效的。

@ref{14c1,,可用性} ： Windows、 Linux、 Unix 系统支持 @code{CLOCK_THREAD_CPUTIME_ID} 。


3.7 新版功能.

@end deffn

@geindex thread_time_ns() (在 time 模块中)
@anchor{library/time time thread_time_ns}@anchor{507}
@deffn {函数} time.thread_time_ns () -> int

与 @ref{1e8,,thread_time()} 相似，但返回纳秒时间。


3.7 新版功能.

@end deffn

@geindex time_ns() (在 time 模块中)
@anchor{library/time time time_ns}@anchor{43c}
@deffn {函数} time.time_ns () -> int

与 @ref{436,,time()} 相似，但返回时间为用整数表示的自 @ref{1fa7,,epoch} 以来所经过的纳秒数。


3.7 新版功能.

@end deffn

@geindex tzset() (在 time 模块中)
@anchor{library/time time tzset}@anchor{21a6}
@deffn {函数} time.tzset ()

重置库例程使用的时间转换规则。环境变量 
@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 指定如何完成。它还将设置变量 @code{tzname} （来自 
@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 环境变量）， @code{timezone} （UTC的西部非DST秒）， @code{altzone} （UTC以西的DST秒）和 @code{daylight} （如果此时区没有任何夏令时规则则为0，如果有夏令时适用的时间，无论过去、现在或未来，则为非零）。

@ref{14c1,,Availability}: Unix.

@cartouche
@quotation 注解 
虽然在很多情况下，更改 
@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 环境变量而不调用 @ref{21a6,,tzset()} 可能会影响函数的输出，例如 @ref{10c9,,localtime()} ，不应该依赖此行为。

@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 不应该包含空格。
@end quotation
@end cartouche

@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 环境变量的标准格式是（为了清晰起见，添加了空格）:

@example
std offset [dst [offset [,start[/time], end[/time]]]]
@end example

组件的位置是：


@table @asis

@item @code{std} 和 @code{dst}

三个或更多字母数字，给出时区缩写。这些将传到 time.tzname

@item @code{offset}

偏移量的形式为： @code{± hh[:mm[:ss]]} 。这表示添加到达UTC的本地时间的值。如果前面有 '-' ，则时区位于本初子午线的东边；否则，在它是西边。如果dst之后没有偏移，则假设夏令时比标准时间提前一小时。

@item @code{start[/time], end[/time]}

指示何时更改为DST和从DST返回。开始日期和结束日期的格式为以下之一：


@table @asis

@item @code{J@emph{n}}

Julian日 @emph{n} （1 <= @emph{n} <= 365）。闰日不计算在内，因此在所有年份中，2月28日是第59天，3月1日是第60天。

@item @code{@emph{n}}

从零开始的Julian日（0 <= @emph{n} <= 365）。 闰日计入，可以引用2月29日。

@item @code{M@emph{m}.@emph{n}.@emph{d}}

一年中 @emph{m} 月的第 @emph{n} 周（1 <= @emph{n} <= 5 ，1 <= @emph{m} <= 12 ，第 5 周表示 “可能在 @emph{m} 月第 4 周或第 5 周出现的最后第 @emph{d} 日”）的第 @emph{d} 天（0 <= @emph{d} <= 6）。 第 1 周是第 @emph{d} 天发生的第一周。 第 0 天是星期天。
@end table

@code{time} 的格式与 @code{offset} 的格式相同，但不允许使用前导符号（ '-' 或 '+' ）。如果没有给出时间，则默认值为02:00:00。
@end table

@example
>>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'02:07:36 05/08/03 EDT'
>>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'
@end example

在许多Unix系统（包括 *BSD ， Linux ， Solaris 和 Darwin 上），使用系统的区域信息（ @code{tzfile(5)} ）数据库来指定时区规则会更方便。为此，将 
@geindex TZ
@geindex 环境变量; TZ
@code{TZ} 环境变量设置为所需时区数据文件的路径，相对于系统 'zoneinfo' 时区数据库的根目录，通常位于 @code{/usr/share/zoneinfo} 。 例如，@code{'US/Eastern'} 、 @code{'Australia/Melbourne'} 、 @code{'Egypt'} 或 @code{'Europe/Amsterdam'}。

@example
>>> os.environ['TZ'] = 'US/Eastern'
>>> time.tzset()
>>> time.tzname
('EST', 'EDT')
>>> os.environ['TZ'] = 'Egypt'
>>> time.tzset()
>>> time.tzname
('EET', 'EEST')
@end example
@end deffn

@node Clock ID 常量,时区常量,函数<3>,time --- 时间的访问和转换
@anchor{library/time clock-id-constants}@anchor{21a7}@anchor{library/time time-clock-id-constants}@anchor{21a5}
@subsubsection Clock ID 常量


这些常量用作 @ref{b93,,clock_getres()} 和 @ref{b94,,clock_gettime()} 的参数。

@geindex CLOCK_BOOTTIME() (在 time 模块中)
@anchor{library/time time CLOCK_BOOTTIME}@anchor{503}
@deffn {数据} time.CLOCK_BOOTTIME

与 @ref{504,,CLOCK_MONOTONIC} 相同，除了它还包括系统暂停的任何时间。

这允许应用程序获得一个暂停感知的单调时钟，而不必处理 @ref{fb9,,CLOCK_REALTIME} 的复杂性，如果使用 @code{settimeofday()} 或类似的时间更改时间可能会有不连续性。

@ref{14c1,,可用性}: Linux 2.6.39 或更新


3.7 新版功能.

@end deffn

@geindex CLOCK_HIGHRES() (在 time 模块中)
@anchor{library/time time CLOCK_HIGHRES}@anchor{21a8}
@deffn {数据} time.CLOCK_HIGHRES

Solaris OS 有一个 @code{CLOCK_HIGHRES} 计时器，试图使用最佳硬件源，并可能提供接近纳秒的分辨率。 @code{CLOCK_HIGHRES} 是不可调节的高分辨率时钟。

@ref{14c1,,可用性}: Solaris.


3.3 新版功能.

@end deffn

@geindex CLOCK_MONOTONIC() (在 time 模块中)
@anchor{library/time time CLOCK_MONOTONIC}@anchor{504}
@deffn {数据} time.CLOCK_MONOTONIC

无法设置的时钟，表示自某些未指定的起点以来的单调时间。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex CLOCK_MONOTONIC_RAW() (在 time 模块中)
@anchor{library/time time CLOCK_MONOTONIC_RAW}@anchor{21a9}
@deffn {数据} time.CLOCK_MONOTONIC_RAW

类似于 @ref{504,,CLOCK_MONOTONIC} ，但可以访问不受NTP调整影响的原始硬件时间。

@ref{14c1,,可用性}: Linux 2.6.28 和更新版本， macOS 10.12 和更新版本。


3.3 新版功能.

@end deffn

@geindex CLOCK_PROCESS_CPUTIME_ID() (在 time 模块中)
@anchor{library/time time CLOCK_PROCESS_CPUTIME_ID}@anchor{21aa}
@deffn {数据} time.CLOCK_PROCESS_CPUTIME_ID

来自CPU的高分辨率每进程计时器。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex CLOCK_PROF() (在 time 模块中)
@anchor{library/time time CLOCK_PROF}@anchor{505}
@deffn {数据} time.CLOCK_PROF

来自CPU的高分辨率每进程计时器。

@ref{14c1,,可用性}: FreeBSD， NetBSD 7 或更新， OpenBSD.


3.7 新版功能.

@end deffn

@geindex CLOCK_TAI() (在 time 模块中)
@anchor{library/time time CLOCK_TAI}@anchor{109b}
@deffn {数据} time.CLOCK_TAI

国际原子时间@footnote{https://www.nist.gov/pml/time-and-frequency-division/nist-time-frequently-asked-questions-faq#tai}

该系统必须有一个当前闰秒表以便能给出正确的回答。 PTP 或 NTP 软件可以用来维护闰秒表。

@ref{14c1,,可用性}: Linux。


3.9 新版功能.

@end deffn

@geindex CLOCK_THREAD_CPUTIME_ID() (在 time 模块中)
@anchor{library/time time CLOCK_THREAD_CPUTIME_ID}@anchor{21ab}
@deffn {数据} time.CLOCK_THREAD_CPUTIME_ID

特定于线程的CPU时钟。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex CLOCK_UPTIME() (在 time 模块中)
@anchor{library/time time CLOCK_UPTIME}@anchor{506}
@deffn {数据} time.CLOCK_UPTIME

该时间的绝对值是系统运行且未暂停的时间，提供准确的正常运行时间测量，包括绝对值和间隔值。

@ref{14c1,,可用性}: FreeBSD， OpenBSD 5.5 或更新。


3.7 新版功能.

@end deffn

@geindex CLOCK_UPTIME_RAW() (在 time 模块中)
@anchor{library/time time CLOCK_UPTIME_RAW}@anchor{36c}
@deffn {数据} time.CLOCK_UPTIME_RAW

单调递增的时钟，记录从一个任意起点开始的时间，不受频率或时间调整的影响，并且当系统休眠时将不会递增。

@ref{14c1,,可用性}: macOS 10.12 和更新版本。


3.8 新版功能.

@end deffn

以下常量是唯一可以发送到 @ref{b95,,clock_settime()} 的参数。

@geindex CLOCK_REALTIME() (在 time 模块中)
@anchor{library/time time CLOCK_REALTIME}@anchor{fb9}
@deffn {数据} time.CLOCK_REALTIME

系统范围的实时时钟。 设置此时钟需要适当的权限。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@node 时区常量,,Clock ID 常量,time --- 时间的访问和转换
@anchor{library/time time-timezone-constants}@anchor{21ac}@anchor{library/time timezone-constants}@anchor{21ad}
@subsubsection 时区常量


@geindex altzone() (在 time 模块中)
@anchor{library/time time altzone}@anchor{21ae}
@deffn {数据} time.altzone

本地DST时区的偏移量，以UTC为单位的秒数，如果已定义。如果当地DST时区在UTC以东（如在西欧，包括英国），则是负数。 只有当 @code{daylight} 非零时才使用它。 见下面的注释。
@end deffn

@geindex daylight() (在 time 模块中)
@anchor{library/time time daylight}@anchor{21af}
@deffn {数据} time.daylight

如果定义了DST时区，则为非零。 见下面的注释。
@end deffn

@geindex timezone() (在 time 模块中)
@anchor{library/time time timezone}@anchor{21b0}
@deffn {数据} time.timezone

本地（非DST）时区的偏移量，UTC以西的秒数（西欧大部分地区为负，美国为正，英国为零）。 见下面的注释。
@end deffn

@geindex tzname() (在 time 模块中)
@anchor{library/time time tzname}@anchor{21b1}
@deffn {数据} time.tzname

两个字符串的元组：第一个是本地非DST时区的名称，第二个是本地DST时区的名称。 如果未定义DST时区，则不应使用第二个字符串。 见下面的注释。
@end deffn

@cartouche
@quotation 注解 
对于上述时区常量（ @ref{21ae,,altzone} 、 @ref{21af,,daylight} 、 @ref{21b0,,timezone} 和 @ref{21b1,,tzname} ），该值由模块加载时有效的时区规则确定，或者最后一次 @ref{21a6,,tzset()} 被调用时，并且在过去的时间可能不正确。建议使用来自 @ref{10c9,,localtime()} 结果的 @code{tm_gmtoff} 和 @code{tm_zone} 来获取时区信息。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item 模块 @ref{30,,datetime}

更多面向对象的日期和时间接口。

@item 模块 @ref{a9,,locale}

国际化服务。 区域设置会影响 @ref{c40,,strftime()} 和 @ref{e5e,,strptime()}  中许多格式说明符的解析。

@item 模块 @ref{14,,calendar}

一般日历相关功能。这个模块的 @code{timegm()} 是函数 @ref{c1a,,gmtime()} 的反函数。
@end table


@node argparse --- 命令行选项、参数和子命令解析器,getopt --- C 风格的命令行选项解析器,time --- 时间的访问和转换,通用操作系统服务
@anchor{library/argparse doc}@anchor{21b2}@anchor{library/argparse argparse-parser-for-command-line-options-arguments-and-sub-commands}@anchor{21b3}@anchor{library/argparse module-argparse}@anchor{5}
@subsection @code{argparse} --- 命令行选项、参数和子命令解析器


@geindex argparse (模块)


3.2 新版功能.


@strong{源代码：} Lib/argparse.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/argparse.py}


__________________________________________________________________


@subsubheading 教程



此页面包含该 API 的参考信息。有关 Python 命令行解析更细致的介绍，请参阅 @ref{21b4,,argparse 教程}。

@ref{5,,argparse} 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数，然后 @ref{5,,argparse} 将弄清如何从 @ref{cce,,sys.argv} 解析出那些参数。 @ref{5,,argparse} 模块还会自动生成帮助和使用手册，并在用户给程序传入无效参数时报出错误信息。

@menu
* 示例: 示例<16>. 
* ArgumentParser 对象:: 
* add_argument() 方法: add_argument 方法. 
* parse_args() 方法: parse_args 方法. 
* 其它实用工具:: 
* 升级 optparse 代码:: 

@end menu

@node 示例<16>,ArgumentParser 对象,,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse example}@anchor{21b5}
@subsubsection 示例


以下代码是一个 Python 程序，它获取一个整数列表并计算总和或者最大值：

@example
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
@end example

假设上面的 Python 代码保存在名为 @code{prog.py} 的文件中，它可以在命令行运行并提供有用的帮助消息：

@example
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)
@end example

当使用适当的参数运行时，它会输出命令行传入整数的总和或者最大值：

@example
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10
@end example

如果传入无效参数，则会报出错误：

@example
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
@end example

以下部分将引导你完成这个示例。

@menu
* 创建一个解析器:: 
* 添加参数:: 
* 解析参数:: 

@end menu

@node 创建一个解析器,添加参数,,示例<16>
@anchor{library/argparse creating-a-parser}@anchor{21b6}
@subsubsection 创建一个解析器


使用 @ref{5,,argparse} 的第一步是创建一个 @ref{792,,ArgumentParser} 对象：

@example
>>> parser = argparse.ArgumentParser(description='Process some integers.')
@end example

@ref{792,,ArgumentParser} 对象包含将命令行解析成 Python 数据类型所需的全部信息。

@node 添加参数,解析参数,创建一个解析器,示例<16>
@anchor{library/argparse adding-arguments}@anchor{21b7}
@subsubsection 添加参数


给一个 @ref{792,,ArgumentParser} 添加程序参数信息是通过调用 @ref{21b8,,add_argument()} 方法完成的。通常，这些调用指定 @ref{792,,ArgumentParser} 如何获取命令行字符串并将其转换为对象。这些信息在 @ref{21b9,,parse_args()} 调用时被存储和使用。例如：

@example
>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')
@end example

稍后，调用 @ref{21b9,,parse_args()} 将返回一个具有 @code{integers} 和 @code{accumulate} 两个属性的对象。@code{integers} 属性将是一个包含一个或多个整数的列表，而 @code{accumulate} 属性当命令行中指定了 @code{--sum} 参数时将是 @ref{31d,,sum()} 函数，否则则是 @ref{901,,max()} 函数。

@node 解析参数,,添加参数,示例<16>
@anchor{library/argparse parsing-arguments}@anchor{21ba}
@subsubsection 解析参数


@ref{792,,ArgumentParser} 通过 @ref{21b9,,parse_args()} 方法解析参数。它将检查命令行，把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下，这意味着一个简单的 @ref{21bb,,Namespace} 对象将从命令行参数中解析出的属性构建：

@example
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
@end example

在脚本中，通常 @ref{21b9,,parse_args()} 会被不带参数调用，而 @ref{792,,ArgumentParser} 将自动从 @ref{cce,,sys.argv} 中确定命令行参数。

@node ArgumentParser 对象,add_argument 方法,示例<16>,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse argumentparser-objects}@anchor{21bc}
@subsubsection ArgumentParser 对象


@geindex ArgumentParser (argparse 中的类)
@anchor{library/argparse argparse ArgumentParser}@anchor{792}
@deffn {类} argparse.ArgumentParser (prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)

创建一个新的 @ref{792,,ArgumentParser} 对象。所有的参数都应当作为关键字参数传入。每个参数在下面都有它更详细的描述，但简而言之，它们是：


@itemize *

@item 
@ref{21bd,,prog} - 程序的名称（默认：@code{sys.argv[0]}）

@item 
@ref{21be,,usage} - 描述程序用途的字符串（默认值：从添加到解析器的参数生成）

@item 
@ref{21bf,,description} - 在参数帮助文档之前显示的文本（默认值：无）

@item 
@ref{21c0,,epilog} - 在参数帮助文档之后显示的文本（默认值：无）

@item 
@ref{21c1,,parents} - 一个 @ref{792,,ArgumentParser} 对象的列表，它们的参数也应包含在内

@item 
@ref{21c2,,formatter_class} - 用于自定义帮助文档输出格式的类

@item 
@ref{21c3,,prefix_chars} - 可选参数的前缀字符集合（默认值：'-'）

@item 
@ref{21c4,,fromfile_prefix_chars} - 当需要从文件中读取其他参数时，用于标识文件名的前缀字符集合（默认值：@code{None}）

@item 
@ref{21c5,,argument_default} - 参数的全局默认值（默认值： @code{None}）

@item 
@ref{21c6,,conflict_handler} - 解决冲突选项的策略（通常是不必要的）

@item 
@ref{21c7,,add_help} - 为解析器添加一个 @code{-h/--help} 选项（默认值： @code{True}）

@item 
@ref{794,,allow_abbrev} - 如果缩写是无歧义的，则允许缩写长选项 （默认值：@code{True}）

@item 
@ref{21c8,,exit_on_error} - 决定当错误发生时是否让 ArgumentParser 附带错误信息退出。 (默认值: @code{True})
@end itemize


在 3.5 版更改: 添加 @emph{allow_abbrev} 参数。



在 3.8 版更改: 在之前的版本中，@emph{allow_abbrev} 还会禁用短旗标分组，例如 @code{-vv} 表示为 @code{-v -v}。



在 3.9 版更改: 添加了 @emph{exit_on_error} 形参。

@end deffn

以下部分描述这些参数如何使用。

@menu
* prog:: 
* usage:: 
* description:: 
* epilog:: 
* parents:: 
* formatter_class:: 
* prefix_chars:: 
* fromfile_prefix_chars:: 
* argument_default:: 
* allow_abbrev:: 
* conflict_handler:: 
* add_help:: 
* exit_on_error:: 

@end menu

@node prog,usage,,ArgumentParser 对象
@anchor{library/argparse prog}@anchor{21bd}
@subsubsection prog


默认情况下，@ref{792,,ArgumentParser} 对象使用 @code{sys.argv[0]} 来确定如何在帮助消息中显示程序名称。这一默认值几乎总是可取的，因为它将使帮助消息与从命令行调用此程序的方式相匹配。例如，对于有如下代码的名为 @code{myprogram.py} 的文件：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
@end example

该程序的帮助信息将显示 @code{myprogram.py} 作为程序名称（无论程序从何处被调用）：

@example
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
$ cd ..
$ python subdir/myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
@end example

要更改这样的默认行为，可以使用 @code{prog=} 参数为 @ref{792,,ArgumentParser} 提供另一个值：

@example
>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]

optional arguments:
 -h, --help  show this help message and exit
@end example

需要注意的是，无论是从 @code{sys.argv[0]} 或是从 @code{prog=} 参数确定的程序名称，都可以在帮助消息里通过 @code{%(prog)s} 格式串来引用。

@example
>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program
@end example

@node usage,description,prog,ArgumentParser 对象
@anchor{library/argparse usage}@anchor{21be}
@subsubsection usage


默认情况下，@ref{792,,ArgumentParser} 根据它包含的参数来构建用法消息：

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
@end example

可以通过 @code{usage=} 关键字参数覆盖这一默认消息：

@example
>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help
@end example

在用法消息中可以使用 @code{%(prog)s} 格式说明符来填入程序名称。

@node description,epilog,usage,ArgumentParser 对象
@anchor{library/argparse description}@anchor{21bf}
@subsubsection description


大多数对 @ref{792,,ArgumentParser} 构造方法的调用都会使用 @code{description=} 关键字参数。 这个参数简要描述这个程序做什么以及怎么做。 在帮助消息中，这个描述会显示在命令行用法字符串和各种参数的帮助消息之间:

@example
>>> parser = argparse.ArgumentParser(description='A foo that bars')
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit
@end example

在默认情况下，description 将被换行以便适应给定的空间。如果想改变这种行为，见 @ref{21c2,,formatter_class} 参数。

@node epilog,parents,description,ArgumentParser 对象
@anchor{library/argparse epilog}@anchor{21c0}
@subsubsection epilog


一些程序喜欢在 description 参数后显示额外的对程序的描述。这种文字能够通过给 @ref{792,,ArgumentParser}:: 提供 @code{epilog=} 参数而被指定。

@example
>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

And that's how you'd foo a bar
@end example

和 @ref{21bf,,description} 参数一样，@code{epilog=} text 在默认情况下会换行，但是这种行为能够被调整通过提供 @ref{21c2,,formatter_class} 参数给 @code{ArgumentParse}.

@node parents,formatter_class,epilog,ArgumentParser 对象
@anchor{library/argparse parents}@anchor{21c1}
@subsubsection parents


有些时候，少数解析器会使用同一系列参数。 单个解析器能够通过提供 @code{parents=} 参数给 @ref{792,,ArgumentParser} 而使用相同的参数而不是重复这些参数的定义。@code{parents=} 参数使用 @ref{792,,ArgumentParser} 对象的列表，从它们那里收集所有的位置和可选的行为，然后将这写行为加到正在构建的 @ref{792,,ArgumentParser} 对象。

@example
>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument('--parent', type=int)

>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument('foo')
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
Namespace(foo='XXX', parent=2)

>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> bar_parser.add_argument('--bar')
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)
@end example

请注意大多数父解析器会指定 @code{add_help=False} . 否则， @code{ArgumentParse} 将会看到两个 @code{-h/--help} 选项（一个在父参数中一个在子参数中）并且产生一个错误。

@cartouche
@quotation 注解 
你在通过`@w{`}parents=`@w{`} 传递解析器之前必须完全初始化它们。 如果你在子解析器之后改变父解析器，这些改变将不会反映在子解析器上。
@end quotation
@end cartouche

@node formatter_class,prefix_chars,parents,ArgumentParser 对象
@anchor{library/argparse formatter-class}@anchor{21c2}
@subsubsection formatter_class


@ref{792,,ArgumentParser} 对象允许通过指定备用格式化类来自定义帮助格式。目前，有四种这样的类。

@geindex RawDescriptionHelpFormatter (argparse 中的类)
@geindex RawTextHelpFormatter (argparse 中的类)
@geindex ArgumentDefaultsHelpFormatter (argparse 中的类)
@geindex MetavarTypeHelpFormatter (argparse 中的类)
@anchor{library/argparse argparse RawDescriptionHelpFormatter}@anchor{21c9}
@deffn {类} argparse.RawDescriptionHelpFormatter
@anchor{library/argparse argparse RawTextHelpFormatter}@anchor{21ca}
@deffnx {类} argparse.RawTextHelpFormatter
@anchor{library/argparse argparse ArgumentDefaultsHelpFormatter}@anchor{fcb}
@deffnx {类} argparse.ArgumentDefaultsHelpFormatter
@anchor{library/argparse argparse MetavarTypeHelpFormatter}@anchor{21cb}
@deffnx {类} argparse.MetavarTypeHelpFormatter
@end deffn

@ref{21c9,,RawDescriptionHelpFormatter} 和 @ref{21ca,,RawTextHelpFormatter} 在正文的描述和展示上给与了更多的控制。@ref{792,,ArgumentParser} 对象会将 @ref{21bf,,description} 和 @ref{21c0,,epilog} 的文字在命令行中自动换行。

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     description='@w{'}'this description
...         was indented weird
...             but that is okay'@w{'}',
...     epilog='@w{'}'
...             likewise for this epilog whose whitespace will
...         be cleaned up and whose words will be wrapped
...         across a couple lines'@w{'}')
>>> parser.print_help()
usage: PROG [-h]

this description was indented weird but that is okay

optional arguments:
 -h, --help  show this help message and exit

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
@end example

传 @ref{21c9,,RawDescriptionHelpFormatter} 给 @code{formatter_class=} 表示 @ref{21bf,,description} 和 @ref{21c0,,epilog} 已经被正确的格式化了，不能在命令行中被自动换行:

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.RawDescriptionHelpFormatter,
...     description=textwrap.dedent('@w{'}'\
...         Please do not mess up this text!
...         --------------------------------
...             I have indented it
...             exactly the way
...             I want it
...         '@w{'}'))
>>> parser.print_help()
usage: PROG [-h]

Please do not mess up this text!
--------------------------------
   I have indented it
   exactly the way
   I want it

optional arguments:
 -h, --help  show this help message and exit
@end example

@ref{21ca,,RawTextHelpFormatter} 保留所有种类文字的空格，包括参数的描述。然而，多重的新行会被替换成一行。如果你想保留多重的空白行，可以在新行之间加空格。

@ref{fcb,,ArgumentDefaultsHelpFormatter} 自动添加默认的值的信息到每一个帮助信息的参数中:

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar ...]

positional arguments:
 bar         BAR! (default: [1, 2, 3])

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   FOO! (default: 42)
@end example

@ref{21cb,,MetavarTypeHelpFormatter} 为它的值在每一个参数中使用 @ref{21cc,,type} 的参数名当作它的显示名（而不是使用通常的格式 @ref{21cd,,dest} ):

@example
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.MetavarTypeHelpFormatter)
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', type=float)
>>> parser.print_help()
usage: PROG [-h] [--foo int] float

positional arguments:
  float

optional arguments:
  -h, --help  show this help message and exit
  --foo int
@end example

@node prefix_chars,fromfile_prefix_chars,formatter_class,ArgumentParser 对象
@anchor{library/argparse prefix-chars}@anchor{21c3}
@subsubsection prefix_chars


许多命令行会使用 @code{-} 当作前缀，比如 @code{-f/--foo}。如果解析器需要支持不同的或者额外的字符，比如像 @code{+f} 或者 @code{/foo} 的选项，可以在参数解析构建器中使用 @code{prefix_chars=} 参数。

@example
>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
>>> parser.add_argument('+f')
>>> parser.add_argument('++bar')
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')
@end example

@code{prefix_chars=} 参数默认使用 @code{'-'}。 提供一组不包括 @code{-} 的字符将导致 @code{-f/--foo} 选项不被允许。

@node fromfile_prefix_chars,argument_default,prefix_chars,ArgumentParser 对象
@anchor{library/argparse fromfile-prefix-chars}@anchor{21c4}
@subsubsection fromfile_prefix_chars


在某些时候，例如在处理一个特别长的参数列表的时候，把参数列表存入一个文件中而不是在命令行中打印出来会更有意义。 如果提供 @code{fromfile_prefix_chars=} 参数给 @ref{792,,ArgumentParser} 构造器，则任何以指定字符打头的参数都将被当作文件来处理，并将被它们包含的参数所替代。 举例来说:

@example
>>> with open('args.txt', 'w') as fp:
...     fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@@args.txt'])
Namespace(f='bar')
@end example

从文件读取的参数在默认情况下必须一个一行（但是可参见  @ref{21ce,,convert_arg_line_to_args()}）并且它们被视为与命令行上的原始文件引用参数位于同一位置。所以在以上例子中，@code{['-f', 'foo', '@@args.txt']} 的表示和 @code{['-f', 'foo', '-f', 'bar']} 的表示相同。

@code{fromfile_prefix_chars=} 参数默认为 @code{None}，意味着参数不会被当作文件对待。

@node argument_default,allow_abbrev,fromfile_prefix_chars,ArgumentParser 对象
@anchor{library/argparse argument-default}@anchor{21c5}
@subsubsection argument_default


一般情况下，参数默认会通过设置一个默认到 @ref{21b8,,add_argument()} 或者调用带一组指定键值对的 @ref{21cf,,ArgumentParser.set_defaults()} 方法。但是有些时候，为参数指定一个普遍适用的解析器会更有用。这能够通过传输 @code{argument_default=} 关键词参数给 @ref{792,,ArgumentParser} 来完成。举个栗子，要全局禁止在 @ref{21b9,,parse_args()} 中创建属性，我们提供 @code{argument_default=SUPPRESS}:

@example
>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar', nargs='?')
>>> parser.parse_args(['--foo', '1', 'BAR'])
Namespace(bar='BAR', foo='1')
>>> parser.parse_args([])
Namespace()
@end example

@node allow_abbrev,conflict_handler,argument_default,ArgumentParser 对象
@anchor{library/argparse allow-abbrev}@anchor{794}@anchor{library/argparse id1}@anchor{21d0}
@subsubsection allow_abbrev


正常情况下，当你向 @ref{792,,ArgumentParser} 的 @ref{21b9,,parse_args()} 方法传入一个参数列表时，它会 @ref{793,,recognizes abbreviations}。

这个特性可以设置 @code{allow_abbrev} 为 @code{False} 来关闭:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
>>> parser.add_argument('--foobar', action='store_true')
>>> parser.add_argument('--foonley', action='store_false')
>>> parser.parse_args(['--foon'])
usage: PROG [-h] [--foobar] [--foonley]
PROG: error: unrecognized arguments: --foon
@end example


3.5 新版功能.


@node conflict_handler,add_help,allow_abbrev,ArgumentParser 对象
@anchor{library/argparse conflict-handler}@anchor{21c6}
@subsubsection conflict_handler


@ref{792,,ArgumentParser} 对象不允许在相同选项字符串下有两种行为。默认情况下， @ref{792,,ArgumentParser} 对象会产生一个异常如果去创建一个正在使用的选项字符串参数。

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
Traceback (most recent call last):
 ..
ArgumentError: argument --foo: conflicting option string(s): --foo
@end example

有些时候（例如：使用 @ref{21c1,,parents}），重写旧的有相同选项字符串的参数会更有用。为了产生这种行为， @code{'resolve'} 值可以提供给 @ref{792,,ArgumentParser} 的 @code{conflict_handler=} 参数:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
>>> parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 -f FOO      old foo help
 --foo FOO   new foo help
@end example

注意 @ref{792,,ArgumentParser} 对象只能移除一个行为如果它所有的选项字符串都被重写。所以，在上面的例子中，旧的 @code{-f/--foo} 行为 回合 @code{-f} 行为保持一样, 因为只有 @code{--foo} 选项字符串被重写。

@node add_help,exit_on_error,conflict_handler,ArgumentParser 对象
@anchor{library/argparse add-help}@anchor{21c7}
@subsubsection add_help


默认情况下，ArgumentParser 对象添加一个简单的显示解析器帮助信息的选项。举个栗子，考虑一个名为 @code{myprogram.py} 的文件包含如下代码:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
@end example

如果 @code{-h} or @code{--help} 在命令行中被提供, 参数解析器帮助信息会打印:

@example
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
@end example

有时候可能会需要关闭额外的帮助信息。这可以通过在 @ref{792,,ArgumentParser} 中设置 @code{add_help=} 参数为 @code{False} 来实现。

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help
@end example

帮助选项一般为 @code{-h/--help}。如果 @code{prefix_chars=} 被指定并且没有包含 @code{-} 字符，在这种情况下， @code{-h} @code{--help} 不是有效的选项。此时， @code{prefix_chars} 的第一个字符将用作帮助选项的前缀。

@example
>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
>>> parser.print_help()
usage: PROG [+h]

optional arguments:
  +h, ++help  show this help message and exit
@end example

@node exit_on_error,,add_help,ArgumentParser 对象
@anchor{library/argparse exit-on-error}@anchor{21c8}
@subsubsection exit_on_error


正常情况下，当你向 @ref{792,,ArgumentParser} 的 @ref{21b9,,parse_args()} 方法传入一个无效的参数列表时，它将会退出并发出错误信息。

如果用户想要手动捕获错误，可通过将 @code{exit_on_error} 设为 @code{False} 来启用该特性:

@example
>>> parser = argparse.ArgumentParser(exit_on_error=False)
>>> parser.add_argument('--integers', type=int)
_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
>>> try:
...     parser.parse_args('--integers a'.split())
... except argparse.ArgumentError:
...     print('Catching an argumentError')
...
Catching an argumentError
@end example


3.9 新版功能.


@node add_argument 方法,parse_args 方法,ArgumentParser 对象,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse the-add-argument-method}@anchor{21d1}
@subsubsection add_argument() 方法


@geindex add_argument() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser add_argument}@anchor{21b8}
@deffn {方法} ArgumentParser.add_argument (name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描述，长话短说有：


@itemize *

@item 
@ref{21d2,,name or flags} - 一个命名或者一个选项字符串的列表，例如 @code{foo} 或 @code{-f, --foo}。

@item 
@ref{21d3,,action} - 当参数在命令行中出现时使用的动作基本类型。

@item 
@ref{21d4,,nargs} - 命令行参数应当消耗的数目。

@item 
@ref{21d5,,const} - 被一些 @ref{21d3,,action} 和 @ref{21d4,,nargs} 选择所需求的常数。

@item 
@ref{21d6,,default} - 当参数未在命令行中出现并且也不存在于命名空间对象时所产生的值。

@item 
@ref{21cc,,type} - 命令行参数应当被转换成的类型。

@item 
@ref{21d7,,choices} - 可用的参数的容器。

@item 
@ref{21d8,,required} - 此命令行选项是否可省略 （仅选项可用）。

@item 
@ref{21d9,,help} - 一个此选项作用的简单描述。

@item 
@ref{21da,,metavar} - 在使用方法消息中使用的参数值示例。

@item 
@ref{21cd,,dest} - 被添加到 @ref{21b9,,parse_args()} 所返回对象上的属性名。
@end itemize
@end deffn

以下部分描述这些参数如何使用。

@menu
* name or flags:: 
* action:: 
* nargs:: 
* const:: 
* default:: 
* type:: 
* choices:: 
* required:: 
* help:: 
* metavar:: 
* dest:: 
* Action 类:: 

@end menu

@node name or flags,action,,add_argument 方法
@anchor{library/argparse name-or-flags}@anchor{21d2}
@subsubsection name or flags


@ref{21b8,,add_argument()} 方法必须知道它是否是一个选项，例如 @code{-f} 或 @code{--foo}，或是一个位置参数，例如一组文件名。 第一个传递给 @ref{21b8,,add_argument()} 的参数必须是一系列旗标或者是一个简单的参数名。例如，可选参数可以被这样创建:

@example
>>> parser.add_argument('-f', '--foo')
@end example

而位置参数可以这么创建:

@example
>>> parser.add_argument('bar')
@end example

当 @ref{21b9,,parse_args()} 被调用，选项会以 @code{-} 前缀识别，剩下的参数则会被假定为位置参数:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')
>>> parser.parse_args(['--foo', 'FOO'])
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar
@end example

@node action,nargs,name or flags,add_argument 方法
@anchor{library/argparse action}@anchor{21d3}
@subsubsection action


@ref{792,,ArgumentParser} 对象将命令行参数与动作相关联。这些动作可以做与它们相关联的命令行参数的任何事，尽管大多数动作只是简单的向 @ref{21b9,,parse_args()} 返回的对象上添加属性。@code{action} 命名参数指定了这个命令行参数应当如何处理。供应的动作有：


@itemize *

@item 
@code{'store'} - 存储参数的值。这是默认的动作。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')
@end example

@item 
@code{'store_const'} - 存储被 @ref{21d5,,const} 命名参数指定的值。 @code{'store_const'} 动作通常用在选项中来指定一些标志。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)
@end example

@item 
@code{'store_true'} and @code{'store_false'} - 这些是 @code{'store_const'} 分别用作存储 @code{True} 和 @code{False} 值的特殊用例。另外，它们的默认值分别为 @code{False} 和 @code{True}。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
@end example

@item 
@code{'append'} - 存储一个列表，并且将每个参数值追加到列表中。在允许多次使用选项时很有用。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
@end example

@item 
@code{'append_const'} - 这存储一个列表，并将 @ref{21d5,,const} 命名参数指定的值追加到列表中。（注意 @ref{21d5,,const} 命名参数默认为 @code{None}。）`@w{`}'append_const'`@w{`} 动作一般在多个参数需要在同一列表中存储常数时会有用。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])
@end example

@item 
@code{'count'} - 计算一个关键字参数出现的数目或次数。例如，对于一个增长的详情等级来说有用:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
@end example

请注意，@emph{default} 将为 @code{None}，除非显式地设为 @emph{0}。

@item 
@code{'help'} - 打印所有当前解析器中的选项和参数的完整帮助信息，然后退出。默认情况下，一个 help 动作会被自动加入解析器。关于输出是如何创建的，参与 @ref{792,,ArgumentParser}。

@item 
@code{'version'} - 期望有一个 @code{version=} 命名参数在 @ref{21b8,,add_argument()} 调用中，并打印版本信息并在调用后退出:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
>>> parser.parse_args(['--version'])
PROG 2.0
@end example

@item 
@code{'extend'} - 这会存储一个列表，并将每个参数值加入到列表中。 示例用法:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
>>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
Namespace(foo=['f1', 'f2', 'f3', 'f4'])
@end example


3.8 新版功能.

@end itemize

你还可以通过传递一个 Action 子类或实现相同接口的其他对象来指定任意操作。 @code{BooleanOptionalAction} 在 @code{argparse} 中可用并会添加对布尔型操作例如 @code{--foo} 和 @code{--no-foo} 的支持:

@example
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)
@end example


3.9 新版功能.


创建自定义动作的推荐方式是扩展 @ref{f74,,Action}，重载 @code{__call__} 方法以及可选的 @code{__init__} 和 @code{format_usage} 方法。

一个自定义动作的例子:

@example
>>> class FooAction(argparse.Action):
...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
...         if nargs is not None:
...             raise ValueError("nargs not allowed")
...         super().__init__(option_strings, dest, **kwargs)
...     def __call__(self, parser, namespace, values, option_string=None):
...         print('%r %r %r' % (namespace, values, option_string))
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')
@end example

更多描述，见 @ref{f74,,Action}。

@node nargs,const,action,add_argument 方法
@anchor{library/argparse nargs}@anchor{21d4}
@subsubsection nargs


ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作。 @code{nargs} 命名参数关联不同数目的命令行参数到单一动作。支持的值有：


@itemize *

@item 
@code{N} （一个整数）。命令行中的 @code{N} 个参数会被聚集到一个列表中。 例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])
@end example

注意 @code{nargs=1} 会产生一个单元素列表。这和默认的元素本身是不同的。
@end itemize

@geindex ? (question mark); in argparse module


@itemize *

@item 
@code{'?'}。 如果可能的话，会从命令行中消耗一个参数，并产生一个单独项。 如果当前没有命令行参数，将会产生 @ref{21d6,,default} 值。 注意对于可选参数来说，还有一个额外情况 —— 出现了选项字符串但没有跟随命令行参数，在此情况下将会产生 @ref{21d5,,const} 值。 一些说明这种情况的例子如下:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')
@end example

@code{nargs='?'} 的一个更普遍用法是允许可选的输入或输出文件:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
...                     default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
...                     default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
@end example
@end itemize

@geindex * (asterisk); in argparse module


@itemize *

@item 
@code{'*'}。所有当前命令行参数被聚集到一个列表中。注意通过 @code{nargs='*'} 来实现多个位置参数通常没有意义，但是多个选项是可能的。例如:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
@end example
@end itemize

@geindex + (plus); in argparse module


@itemize *

@item 
@code{'+'}。和 @code{'*'} 类似，所有当前命令行参数被聚集到一个列表中。另外，当前没有至少一个命令行参数时会产生一个错误信息。例如:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args(['a', 'b'])
Namespace(foo=['a', 'b'])
>>> parser.parse_args([])
usage: PROG [-h] foo [foo ...]
PROG: error: the following arguments are required: foo
@end example
@end itemize

如果不提供 @code{nargs} 命名参数，则消耗参数的数目将被 @ref{21d3,,action} 决定。通常这意味着单一项目（非列表）消耗单一命令行参数。

@node const,default,nargs,add_argument 方法
@anchor{library/argparse const}@anchor{21d5}
@subsubsection const


@ref{21b8,,add_argument()}  的`@w{`}const`@w{`} 参数用于保存不从命令行中读取但被各种 @ref{792,,ArgumentParser} 动作需求的常数值。最常用的两例为：


@itemize *

@item 
当 @ref{21b8,,add_argument()} 通过 @code{action='store_const'} 或 @code{action='append_const} 调用时。这些动作将 @code{const} 值添加到 @ref{21b9,,parse_args()} 返回的对象的属性中。在 @ref{21d3,,action} 的描述中查看案例。

@item 
当 @ref{21b8,,add_argument()} 通过选项（例如 @code{-f} 或 @code{--foo}）调用并且 @code{nargs='?'} 时。这会创建一个可以跟随零个或一个命令行参数的选项。当解析命令行时，如果选项后没有参数，则将用 @code{const} 代替。在 @ref{21d4,,nargs} 描述中查看案例。
@end itemize

对 @code{'store_const'} 和 @code{'append_const'} 动作， @code{const} 命名参数必须给出。对其他动作，默认为 @code{None}。

@node default,type,const,add_argument 方法
@anchor{library/argparse default}@anchor{21d6}
@subsubsection default


所有选项和一些位置参数可能在命令行中被忽略。@ref{21b8,,add_argument()} 的命名参数 @code{default}，默认值为 @code{None}，指定了在命令行参数未出现时应当使用的值。对于选项， @code{default} 值在选项未在命令行中出现时使用:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args(['--foo', '2'])
Namespace(foo='2')
>>> parser.parse_args([])
Namespace(foo=42)
@end example

如果目标命名空间已经有一个属性集，则 @emph{default} 动作不会覆盖它:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
Namespace(foo=101)
@end example

如果 @code{default} 值是一个字符串，解析器解析此值就像一个命令行参数。特别是，在将属性设置在 @ref{21bb,,Namespace} 的返回值之前，解析器应用任何提供的 @ref{21cc,,type} 转换参数。否则解析器使用原值:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)
@end example

对于 @ref{21d4,,nargs} 等于 @code{?} 或 @code{*} 的位置参数， @code{default} 值在没有命令行参数出现时使用。

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
>>> parser.parse_args(['a'])
Namespace(foo='a')
>>> parser.parse_args([])
Namespace(foo=42)
@end example

提供 @code{default=argparse.SUPPRESS} 导致命令行参数未出现时没有属性被添加:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
>>> parser.parse_args([])
Namespace()
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')
@end example

@node type,choices,default,add_argument 方法
@anchor{library/argparse type}@anchor{21cc}
@subsubsection type


默认情况下，解析器会将命令行参数当作简单字符串读入。 然而，命令行字符串经常应当被解读为其他类型，例如 @ref{1fe,,float} 或 @ref{205,,int}。 @ref{21b8,,add_argument()} 的 @code{type} 关键字允许执行任何必要的类型检查和类型转换。

如果 @ref{21cc,,type} 关键字使用了 @ref{21d6,,default} 关键字，则类型转换器仅会在默认值为字符串时被应用。

传给 @code{type} 的参数可以是任何接受单个字符串的可调用对象。 如果函数引发了 @code{ArgumentTypeError}, @ref{1ff,,TypeError} 或 @ref{16d,,ValueError}，异常会被捕获并显示经过良好格式化的错误消息。 其他异常类型则不会被处理。

普通内置类型和函数可被用作类型转换器:

@example
import argparse
import pathlib

parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
parser.add_argument('datapath', type=pathlib.Path)
@end example

用户自定义的函数也可以被使用:

@example
>>> def hyphenated(string):
...     return '-'.join([word[:4] for word in string.casefold().split()])
...
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument('short_title', type=hyphenated)
>>> parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')
@end example

不建议将 @ref{2c4,,bool()} 函数用作类型转换器。 它所做的只是将空字符串转为 @code{False} 而将非空字符串转为 @code{True}。 这通常不是用户所想要的。

通常，@code{type} 关键字是仅应被用于只会引发上述三种被支持的异常的简单转换的便捷选项。 任何具有更复杂错误处理或资源管理的转换都应当在参数被解析后由下游代码来完成。

例如，JSON 或 YAML 转换具有复杂的错误情况，要求给出比 @code{type} 关键字所能给出的更好的报告。 @ref{801,,JSONDecodeError} 将不会被良好地格式化而 @code{FileNotFound} 异常则完全不会被处理。

即使 @ref{917,,FileType} 在用于 @code{type} 关键字时也存在限制。 如果一个参数使用了 @emph{FileType} 并且有一个后续参数出错，则将报告一个错误但文件并不会被自动关闭。 在此情况下，更好的做法是等待直到解析器运行完毕再使用 @ref{7e4,,with} 语句来管理文件。

对于简单地检查一组固定值的类型检查器，请考虑改用 @ref{21d7,,choices} 关键字。

@node choices,required,type,add_argument 方法
@anchor{library/argparse choices}@anchor{21d7}
@subsubsection choices


某些命令行参数应当从一组受限值中选择。 这可通过将一个容器对象作为 @emph{choices} 关键字参数传给 @ref{21b8,,add_argument()} 来处理。 当执行命令行解析时，参数值将被检查，如果参数不是可接受的值之一就将显示错误消息:

@example
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] @{rock,paper,scissors@}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
@end example

请注意 @emph{choices} 容器包含的内容会在执行任意 @ref{21cc,,type} 转换之后被检查，因此 @emph{choices} 容器中对象的类型应当与指定的 @ref{21cc,,type} 相匹配:

@example
>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] @{1,2,3@}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
@end example

任何容器都可作为 @emph{choices} 值传入，因此 @ref{1f9,,list} 对象，@ref{1f7,,set} 对象以及自定义容器都是受支持的。

不建议使用 @ref{496,,enum.Enum}，因为要控制其在用法、帮助和错误消息中的外观是很困难的。

已格式化的选项会覆盖默认的 @emph{metavar}，该值一般是派生自 @emph{dest}。 这通常就是你所需要的，因为用户永远不会看到 @emph{dest} 形参。 如果不想要这样的显示（或许因为有很多选择），只需指定一个显式的 @ref{21da,,metavar}。

@node required,help,choices,add_argument 方法
@anchor{library/argparse required}@anchor{21d8}
@subsubsection required


通常，@ref{5,,argparse} 模块会认为 @code{-f} 和 @code{--bar} 等旗标是指明 @emph{可选的} 参数，它们总是可以在命令行中被忽略。 要让一个选项成为 @emph{必需的}，则可以将 @code{True} 作为 @code{required=} 关键字参数传给 @ref{21b8,,add_argument()}:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: [-h] --foo FOO
: error: the following arguments are required: --foo
@end example

如这个例子所示，如果一个选项被标记为 @code{required}，则当该选项未在命令行中出现时，@ref{21b9,,parse_args()} 将会报告一个错误。

@cartouche
@quotation 注解 
必需的选项通常被认为是不适宜的，因为用户会预期 @emph{options} 都是 @emph{可选的}，因此在可能的情况下应当避免使用它们。
@end quotation
@end cartouche

@node help,metavar,required,add_argument 方法
@anchor{library/argparse help}@anchor{21d9}
@subsubsection help


@code{help} 值是一个包含参数简短描述的字符串。 当用户请求帮助时（一般是通过在命令行中使用 @code{-h} 或 @code{--help} 的方式），这些 @code{help} 描述将随每个参数一同显示:

@example
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
...                     help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
...                     help='one of the bars to be frobbled')
>>> parser.parse_args(['-h'])
usage: frobble [-h] [--foo] bar [bar ...]

positional arguments:
 bar     one of the bars to be frobbled

optional arguments:
 -h, --help  show this help message and exit
 --foo   foo the bars before frobbling
@end example

@code{help} 字符串可包括各种格式描述符以避免重复使用程序名称或参数 @ref{21d6,,default} 等文本。 有效的描述符包括程序名称 @code{%(prog)s} 和传给 @ref{21b8,,add_argument()} 的大部分关键字参数，例如 @code{%(default)s}, @code{%(type)s} 等等:

@example
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
...                     help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
usage: frobble [-h] [bar]

positional arguments:
 bar     the bar to frobble (default: 42)

optional arguments:
 -h, --help  show this help message and exit
@end example

由于帮助字符串支持 %-formatting，如果你希望在帮助字符串中显示 @code{%} 字面值，你必须将其转义为 @code{%%}。

@ref{5,,argparse} 支持静默特定选项的帮助，具体做法是将 @code{help} 的值设为 @code{argparse.SUPPRESS}:

@example
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

optional arguments:
  -h, --help  show this help message and exit
@end example

@node metavar,dest,help,add_argument 方法
@anchor{library/argparse metavar}@anchor{21da}
@subsubsection metavar


当 @ref{792,,ArgumentParser} 生成帮助消息时，它需要用某种方式来引用每个预期的参数。 默认情况下，ArgumentParser 对象使用 @ref{21cd,,dest} 值作为每个对象的 "name"。 默认情况下，对于位置参数动作，@ref{21cd,,dest} 值将被直接使用，而对于可选参数动作，@ref{21cd,,dest} 值将被转为大写形式。 因此，一个位置参数 @code{dest='bar'} 的引用形式将为 @code{bar}。 一个带有单独命令行参数的可选参数 @code{--foo} 的引用形式将为 @code{FOO}。 示例如下:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo FOO] bar

positional arguments:
 bar

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO
@end example

可以使用 @code{metavar} 来指定一个替代名称:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
 XXX

optional arguments:
 -h, --help  show this help message and exit
 --foo YYY
@end example

请注意 @code{metavar} 仅改变 @emph{显示的} 名称 -  @ref{21b9,,parse_args()} 对象的属性名称仍然会由 @ref{21cd,,dest} 值确定。

不同的 @code{nargs} 值可能导致 metavar 被多次使用。 提供一个元组给 @code{metavar} 即为每个参数指定不同的显示信息:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz
@end example

@node dest,Action 类,metavar,add_argument 方法
@anchor{library/argparse dest}@anchor{21cd}
@subsubsection dest


大多数 @ref{792,,ArgumentParser} 动作会添加一些值作为 @ref{21b9,,parse_args()} 所返回对象的一个属性。 该属性的名称由 @ref{21b8,,add_argument()} 的 @code{dest} 关键字参数确定。 对于位置参数动作，@code{dest} 通常会作为 @ref{21b8,,add_argument()} 的第一个参数提供:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args(['XXX'])
Namespace(bar='XXX')
@end example

对于可选参数动作，@code{dest} 的值通常取自选项字符串。 @ref{792,,ArgumentParser} 会通过接受第一个长选项字符串并去掉开头的 @code{--} 字符串来生成 @code{dest} 的值。 如果没有提供长选项字符串，则 @code{dest} 将通过接受第一个短选项字符串并去掉开头的 @code{-} 字符来获得。 任何内部的 @code{-} 字符都将被转换为 @code{_} 字符以确保字符串是有效的属性名称。 下面的例子显示了这种行为:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')
@end example

@code{dest} 允许提供自定义属性名称:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
@end example

@node Action 类,,dest,add_argument 方法
@anchor{library/argparse action-classes}@anchor{21db}
@subsubsection Action 类


Action 类实现了 Action API，它是一个返回可调用对象的可调用对象，返回的可调用对象可处理来自命令行的参数。 任何遵循此 API 的对象均可作为 @code{action} 形参传给 @code{add_argument()}。

@geindex Action (argparse 中的类)
@anchor{library/argparse argparse Action}@anchor{f74}
@deffn {类} argparse.Action (option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
@end deffn

Action 对象会被 ArgumentParser 用来表示解析从命令行中的一个或多个字符串中解析出单个参数所必须的信息。 Action 类必须接受两个位置参数以及传给 @ref{21b8,,ArgumentParser.add_argument()} 的任何关键字参数，除了 @code{action} 本身。

Action 的实例（或作为or return value of any callable to the @code{action} 形参的任何可调用对象的返回值）应当定义 "dest", "option_strings", "default", "type", "required", "help" 等属性。 确保这些属性被定义的最容易方式是调用 @code{Action.__init__}。

Action 的实例应当为可调用对象，因此所有子类都必须重载 @code{__call__} 方法，该方法应当接受四个形参:


@itemize *

@item 
@code{parser} - 包含此动作的 ArgumentParser 对象。

@item 
@code{namespace} - 将由 @ref{21b9,,parse_args()} 返回的 @ref{21bb,,Namespace} 对象。 大多数动作会使用 @ref{1742,,setattr()} 为此对象添加属性。

@item 
@code{values} - 已关联的命令行参数，并提供相应的类型转换。 类型转换由 @ref{21b8,,add_argument()} 的 @ref{21cc,,type} 关键字参数来指定。

@item 
@code{option_string} - 被用来发起调用此动作的选项字符串。 @code{option_string} 参数是可选的，且此参数在动作关联到位置参数时将被略去。
@end itemize

@code{__call__} 方法可以执行任意动作，但通常将基于 @code{dest} 和 @code{values} 来设置 @code{namespace} 的属性。

动作子类可定义 @code{format_usage} 方法，该方法不带参数，所返回的字符串将被用于打印程序的用法说明。 如果未提供此方法，则将使用适当的默认值。

@node parse_args 方法,其它实用工具,add_argument 方法,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse the-parse-args-method}@anchor{21dc}
@subsubsection parse_args() 方法


@geindex parse_args() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser parse_args}@anchor{21b9}
@deffn {方法} ArgumentParser.parse_args (args=None, namespace=None)

将参数字符串转换为对象并将其设为命名空间的属性。 返回带有成员的命名空间。

之前对 @ref{21b8,,add_argument()} 的调用决定了哪些对象被创建以及它们如何被赋值。 请参阅 @ref{21b8,,add_argument()} 的文档了解详情。


@itemize *

@item 
@ref{21dd,,args} - 要解析的字符串列表。 默认值是从 @ref{cce,,sys.argv} 获取。

@item 
@ref{21de,,namespace} - 用于获取属性的对象。 默认值是一个新的空 @ref{21bb,,Namespace} 对象。
@end itemize
@end deffn

@menu
* 选项值语法:: 
* 无效的参数:: 
* 包含 - 的参数:: 
* 参数缩写（前缀匹配）:: 
* 在 sys.argv 以外: 在 sys argv 以外. 
* 命名空间对象:: 

@end menu

@node 选项值语法,无效的参数,,parse_args 方法
@anchor{library/argparse option-value-syntax}@anchor{21df}
@subsubsection 选项值语法


@ref{21b9,,parse_args()} 方法支持多种指定选项值的方式（如果它接受选项的话）。 在最简单的情况下，选项和它的值是作为两个单独参数传入的:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('--foo')
>>> parser.parse_args(['-x', 'X'])
Namespace(foo=None, x='X')
>>> parser.parse_args(['--foo', 'FOO'])
Namespace(foo='FOO', x=None)
@end example

对于长选项（名称长度超过一个字符的选项），选项和值也可以作为单个命令行参数传入，使用 @code{=} 分隔它们即可:

@example
>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)
@end example

对于短选项（长度只有一个字符的选项），选项和它的值可以拼接在一起:

@example
>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')
@end example

有些短选项可以使用单个 @code{-} 前缀来进行合并，如果仅有最后一个选项（或没有任何选项）需要值的话:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args(['-xyzZ'])
Namespace(x=True, y=True, z='Z')
@end example

@node 无效的参数,包含 - 的参数,选项值语法,parse_args 方法
@anchor{library/argparse invalid-arguments}@anchor{21e0}
@subsubsection 无效的参数


在解析命令行时，@ref{21b9,,parse_args()} 会检测多种错误，包括有歧义的选项、无效的类型、无效的选项、错误的位置参数个数等等。 当遇到这种错误时，它将退出并打印出错误文本同时附带用法消息:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', nargs='?')

>>> # invalid type
>>> parser.parse_args(['--foo', 'spam'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: argument --foo: invalid int value: 'spam'

>>> # invalid option
>>> parser.parse_args(['--bar'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: no such option: --bar

>>> # wrong number of arguments
>>> parser.parse_args(['spam', 'badger'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger
@end example

@node 包含 - 的参数,参数缩写（前缀匹配）,无效的参数,parse_args 方法
@anchor{library/argparse arguments-containing}@anchor{21e1}
@subsubsection 包含 @code{-} 的参数


@ref{21b9,,parse_args()} 方法会在用户明显出错时尝试给出错误信息，但某些情况本身就存在歧义。 例如，命令行参数 @code{-1} 可能是尝试指定一个选项也可能是尝试提供一个位置参数。 @ref{21b9,,parse_args()} 方法在此会谨慎行事：位置参数只有在它们看起来像负数并且解析器中没有任何选项看起来像负数时才能以 @code{-} 打头。:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('foo', nargs='?')

>>> # no negative number options, so -1 is a positional argument
>>> parser.parse_args(['-x', '-1'])
Namespace(foo=None, x='-1')

>>> # no negative number options, so -1 and -5 are positional arguments
>>> parser.parse_args(['-x', '-1', '-5'])
Namespace(foo='-5', x='-1')

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-1', dest='one')
>>> parser.add_argument('foo', nargs='?')

>>> # negative number options present, so -1 is an option
>>> parser.parse_args(['-1', 'X'])
Namespace(foo=None, one='X')

>>> # negative number options present, so -2 is an option
>>> parser.parse_args(['-2'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: no such option: -2

>>> # negative number options present, so both -1s are options
>>> parser.parse_args(['-1', '-1'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument
@end example

如果你有必须以 @code{-} 打头的位置参数并且看起来不像负数，你可以插入伪参数 @code{'--'} 以告诉 @ref{21b9,,parse_args()} 在那之后的内容是一个位置参数:

@example
>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)
@end example

@node 参数缩写（前缀匹配）,在 sys argv 以外,包含 - 的参数,parse_args 方法
@anchor{library/argparse argument-abbreviations-prefix-matching}@anchor{21e2}@anchor{library/argparse prefix-matching}@anchor{793}
@subsubsection 参数缩写（前缀匹配）


@ref{21b9,,parse_args()} 方法 @ref{794,,在默认情况下} 允许将长选项缩写为前缀，如果缩写无歧义（即前缀与一个特定选项相匹配）的话:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-bacon')
>>> parser.add_argument('-badger')
>>> parser.parse_args('-bac MMM'.split())
Namespace(bacon='MMM', badger=None)
>>> parser.parse_args('-bad WOOD'.split())
Namespace(bacon=None, badger='WOOD')
>>> parser.parse_args('-ba BA'.split())
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
PROG: error: ambiguous option: -ba could match -badger, -bacon
@end example

可产生一个以上选项的参数会引发错误。 此特定可通过将 @ref{794,,allow_abbrev} 设为 @code{False} 来禁用。

@node 在 sys argv 以外,命名空间对象,参数缩写（前缀匹配）,parse_args 方法
@anchor{library/argparse args}@anchor{21dd}@anchor{library/argparse beyond-sys-argv}@anchor{21e3}
@subsubsection 在 @code{sys.argv} 以外


有时在 @ref{cce,,sys.argv} 以外用 ArgumentParser 解析参数也是有用的。 这可以通过将一个字符串列表传给 @ref{21b9,,parse_args()} 来实现。 它适用于在交互提示符下进行检测:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=range(10),
...     nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...     default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
@end example

@node 命名空间对象,,在 sys argv 以外,parse_args 方法
@anchor{library/argparse namespace}@anchor{21de}@anchor{library/argparse the-namespace-object}@anchor{21e4}
@subsubsection 命名空间对象


@geindex Namespace (argparse 中的类)
@anchor{library/argparse argparse Namespace}@anchor{21bb}
@deffn {类} argparse.Namespace

由 @ref{21b9,,parse_args()} 默认使用的简单类，可创建一个存放属性的对象并将其返回。
@end deffn

这个类被有意做得很简单，只是一个具有可读字符串表示形式的 @ref{3da,,object}。 如果你更喜欢类似字典的属性视图，你可以使用标准 Python 中惯常的 @ref{11b6,,vars()}:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
@{'foo': 'BAR'@}
@end example

另一个用处是让 @ref{792,,ArgumentParser} 为一个已存在对象而不是为一个新的 @ref{21bb,,Namespace} 对象的属性赋值。 这可以通过指定 @code{namespace=} 关键字参数来实现:

@example
>>> class C:
...     pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'
@end example

@node 其它实用工具,升级 optparse 代码,parse_args 方法,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse other-utilities}@anchor{21e5}
@subsubsection 其它实用工具


@menu
* 子命令:: 
* FileType 对象:: 
* 参数组:: 
* 互斥:: 
* 解析器默认值:: 
* 打印帮助:: 
* 部分解析:: 
* 自定义文件解析:: 
* 退出方法:: 
* 混合解析:: 

@end menu

@node 子命令,FileType 对象,,其它实用工具
@anchor{library/argparse sub-commands}@anchor{21e6}
@subsubsection 子命令


@geindex add_subparsers() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser add_subparsers}@anchor{5a7}
@deffn {方法} ArgumentParser.add_subparsers ([title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])

许多程序都会将其功能拆分为一系列子命令，例如，@code{svn} 程序包含的子命令有 @code{svn checkout}, @code{svn update} 和 @code{svn commit}。 当一个程序能执行需要多组不同种类命令行参数时这种拆分功能的方式是一个非常好的主意。 @ref{792,,ArgumentParser} 通过 @ref{5a7,,add_subparsers()} 方法支持创建这样的子命令。 @ref{5a7,,add_subparsers()} 方法通常不带参数地调用并返回一个特殊的动作对象。 这种对象只有一个方法 @code{add_parser()}，它接受一个命令名称和任意多个 @ref{792,,ArgumentParser} 构造器参数，并返回一个可以通常方式进行修改的 @ref{792,,ArgumentParser} 对象。

形参的描述


@itemize *

@item 
title - 输出帮助的子解析器分组的标题；如果提供了描述则默认为 "subcommands"，否则使用位置参数的标题

@item 
description - 输出帮助中对子解析器的描述，默认为 @code{None}

@item 
prog - 将与子命令帮助一同显示的用法信息，默认为程序名称和子解析器参数之前的任何位置参数。

@item 
parser_class - 将被用于创建子解析器实例的类，默认为当前解析器类（例如 ArgumentParser）

@item 
@ref{21d3,,action} - 当此参数在命令行中出现时要执行动作的基本类型

@item 
@ref{21cd,,dest} - 将被用于保存子命令名称的属性名；默认为 @code{None} 即不保存任何值

@item 
@ref{21d8,,required} - 是否必须要提供子命令，默认为 @code{False} (在 3.7 中新增)

@item 
@ref{21d9,,help} - 在输出帮助中的子解析器分组帮助信息，默认为 @code{None}

@item 
@ref{21da,,metavar} - 帮助信息中表示可用子命令的字符串；默认为 @code{None} 并以 @{cmd1, cmd2, ..@} 的形式表示子命令
@end itemize

一些使用示例:

@example
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)
@end example

请注意 @ref{21b9,,parse_args()} 返回的对象将只包含主解析器和由命令行所选择的子解析器的属性（而没有任何其他子解析器）。 因此在上面的例子中，当指定了 @code{a} 命令时，将只存在 @code{foo} 和 @code{bar} 属性，而当指定了 @code{b} 命令时，则只存在 @code{foo} 和 @code{baz} 属性。

类似地，当从一个子解析器请求帮助消息时，只有该特定解析器的帮助消息会被打印出来。 帮助消息将不包括父解析器或同级解析器的消息。 （每个子解析器命令一条帮助消息，但是，也可以像上面那样通过提供 @code{help=} 参数给 @code{add_parser()} 来给出。）

@example
>>> parser.parse_args(['--help'])
usage: PROG [-h] [--foo] @{a,b@} ...

positional arguments:
  @{a,b@}   sub-command help
    a     a help
    b     b help

optional arguments:
  -h, --help  show this help message and exit
  --foo   foo help

>>> parser.parse_args(['a', '--help'])
usage: PROG a [-h] bar

positional arguments:
  bar     bar help

optional arguments:
  -h, --help  show this help message and exit

>>> parser.parse_args(['b', '--help'])
usage: PROG b [-h] [--baz @{X,Y,Z@}]

optional arguments:
  -h, --help     show this help message and exit
  --baz @{X,Y,Z@}  baz help
@end example

@ref{5a7,,add_subparsers()} 方法也支持 @code{title} 和 @code{description} 关键字参数。 当两者都存在时，子解析器的命令将出现在输出帮助消息中它们自己的分组内。 例如:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] @{foo,bar@} ...

optional arguments:
  -h, --help  show this help message and exit

subcommands:
  valid subcommands

  @{foo,bar@}   additional help
@end example

此外，@code{add_parser} 还支持附加的 @code{aliases} 参数，它允许多个字符串指向同一子解析器。 这个例子类似于 @code{svn}，将别名 @code{co} 设为 @code{checkout} 的缩写形式:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
>>> checkout.add_argument('foo')
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')
@end example

一个特别有效的处理子命令的方式是将 @ref{5a7,,add_subparsers()} 方法与对 @ref{21cf,,set_defaults()} 的调用结合起来使用，这样每个子解析器就能知道应当执行哪个 Python 函数。 例如:

@example
>>> # sub-command functions
>>> def foo(args):
...     print(args.x * args.y)
...
>>> def bar(args):
...     print('((%s))' % args.z)
...
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('bar XYZYX'.split())
>>> args.func(args)
((XYZYX))
@end example

通过这种方式，你可以在参数解析结束后让 @ref{21b9,,parse_args()} 执行调用适当函数的任务。 像这样将函数关联到动作通常是你处理每个子解析器的不同动作的最简便方式。 但是，如果有必要检查被发起调用的子解析器的名称，则 @ref{5a7,,add_subparsers()} 调用的 @code{dest} 关键字参数将可实现:

@example
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')
@end example


在 3.7 版更改: 新增 @emph{required} 关键字参数。

@end deffn

@node FileType 对象,参数组,子命令,其它实用工具
@anchor{library/argparse filetype-objects}@anchor{21e7}
@subsubsection FileType 对象


@geindex FileType (argparse 中的类)
@anchor{library/argparse argparse FileType}@anchor{917}
@deffn {类} argparse.FileType (mode='r', bufsize=-1, encoding=None, errors=None)

@ref{917,,FileType} 工厂类用于创建可作为 @ref{21b8,,ArgumentParser.add_argument()} 的 type 参数传入的对象。 以 @ref{917,,FileType} 对象作为其类型的参数将使用命令行参数以所请求模式、缓冲区大小、编码格式和错误处理方式打开文件（请参阅 @ref{16f,,open()} 函数了解详情）:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
@end example

FileType 对象能理解伪参数 @code{'-'} 并会自动将其转换为 @code{sys.stdin} 用于可读的 @ref{917,,FileType} 对象，或是 @code{sys.stdout} 用于可写的 @ref{917,,FileType} 对象:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', type=argparse.FileType('r'))
>>> parser.parse_args(['-'])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
@end example


3.4 新版功能: @emph{encodings} 和 @emph{errors} 关键字参数。

@end deffn

@node 参数组,互斥,FileType 对象,其它实用工具
@anchor{library/argparse argument-groups}@anchor{21e8}
@subsubsection 参数组


@geindex add_argument_group() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser add_argument_group}@anchor{21e9}
@deffn {方法} ArgumentParser.add_argument_group (title=None, description=None)

在默认情况下，@ref{792,,ArgumentParser} 会在显示帮助消息时将命令行参数分为“位置参数”和“可选参数”两组。 当存在比默认更好的参数分组概念时，可以使用 @ref{21e9,,add_argument_group()} 方法来创建适当的分组:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group = parser.add_argument_group('group')
>>> group.add_argument('--foo', help='foo help')
>>> group.add_argument('bar', help='bar help')
>>> parser.print_help()
usage: PROG [--foo FOO] bar

group:
  bar    bar help
  --foo FOO  foo help
@end example

@ref{21e9,,add_argument_group()} 方法返回一个具有 @ref{21b8,,add_argument()} 方法的参数分组对象，这与常规的 @ref{792,,ArgumentParser} 一样。 当一个参数被加入分组时，解析器会将它视为一个正常的参数，但是会在不同的帮助消息分组中显示该参数。 @ref{21e9,,add_argument_group()} 方法接受 @emph{title} 和 @emph{description} 参数，它们可被用来定制显示内容:

@example
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group1 = parser.add_argument_group('group1', 'group1 description')
>>> group1.add_argument('foo', help='foo help')
>>> group2 = parser.add_argument_group('group2', 'group2 description')
>>> group2.add_argument('--bar', help='bar help')
>>> parser.print_help()
usage: PROG [--bar BAR] foo

group1:
  group1 description

  foo    foo help

group2:
  group2 description

  --bar BAR  bar help
@end example

请注意任意不在你的自定义分组中的参数最终都将回到通常的“位置参数”和“可选参数”分组中。
@end deffn

@node 互斥,解析器默认值,参数组,其它实用工具
@anchor{library/argparse mutual-exclusion}@anchor{21ea}
@subsubsection 互斥


@geindex add_mutually_exclusive_group() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser add_mutually_exclusive_group}@anchor{21eb}
@deffn {方法} ArgumentParser.add_mutually_exclusive_group (required=False)

创建一个互斥组。 @ref{5,,argparse} 将会确保互斥组中只有一个参数在命令行中可用:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo
@end example

@ref{21eb,,add_mutually_exclusive_group()} 方法也接受一个 @emph{required} 参数，表示在互斥组中至少有一个参数是需要的:

@example
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required
@end example

注意，目前互斥参数组不支持 @ref{21e9,,add_argument_group()} 的 @emph{title} 和 @emph{description} 参数。
@end deffn

@node 解析器默认值,打印帮助,互斥,其它实用工具
@anchor{library/argparse parser-defaults}@anchor{21ec}
@subsubsection 解析器默认值


@geindex set_defaults() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser set_defaults}@anchor{21cf}
@deffn {方法} ArgumentParser.set_defaults (**kwargs)

在大多数时候，@ref{21b9,,parse_args()} 所返回对象的属性将完全通过检查命令行参数和参数动作来确定。 @ref{21cf,,set_defaults()} 则允许加入一些无须任何命令行检查的额外属性:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.set_defaults(bar=42, baz='badger')
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)
@end example

请注意解析器层级的默认值总是会覆盖参数层级的默认值:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
>>> parser.set_defaults(foo='spam')
>>> parser.parse_args([])
Namespace(foo='spam')
@end example

解析器层级默认值在需要多解析器时会特别有用。 请参阅 @ref{5a7,,add_subparsers()} 方法了解此类型的一个示例。
@end deffn

@geindex get_default() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser get_default}@anchor{21ed}
@deffn {方法} ArgumentParser.get_default (dest)

获取一个命名空间属性的默认值，该值是由 @ref{21b8,,add_argument()} 或 @ref{21cf,,set_defaults()} 设置的:

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='badger')
>>> parser.get_default('foo')
'badger'
@end example
@end deffn

@node 打印帮助,部分解析,解析器默认值,其它实用工具
@anchor{library/argparse printing-help}@anchor{21ee}
@subsubsection 打印帮助


在大多数典型应用中，@ref{21b9,,parse_args()} 将负责任何用法和错误消息的格式化和打印。 但是，也可使用某些其他格式化方法:

@geindex print_usage() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser print_usage}@anchor{21ef}
@deffn {方法} ArgumentParser.print_usage (file=None)

打印一段简短描述，说明应当如何在命令行中发起调用 @ref{792,,ArgumentParser}。 如果 @emph{file} 为 @code{None}，则默认使用 @ref{428,,sys.stdout}。
@end deffn

@geindex print_help() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser print_help}@anchor{21f0}
@deffn {方法} ArgumentParser.print_help (file=None)

打印一条帮助消息，包括程序用法和通过 @ref{792,,ArgumentParser} 注册的相关参数信息。 如果 @emph{file} 为 @code{None}，则默认使用 @ref{428,,sys.stdout}。
@end deffn

还存在这些方法的几个变化形式，它们只返回字符串而不打印消息:

@geindex format_usage() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser format_usage}@anchor{1119}
@deffn {方法} ArgumentParser.format_usage ()

返回一个包含简短描述的字符串，说明应当如何在命令行中发起调用 @ref{792,,ArgumentParser}。
@end deffn

@geindex format_help() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser format_help}@anchor{21f1}
@deffn {方法} ArgumentParser.format_help ()

反回一个包含帮助消息的字符串，包括程序用法和通过 @ref{792,,ArgumentParser} 注册的相关参数信息。
@end deffn

@node 部分解析,自定义文件解析,打印帮助,其它实用工具
@anchor{library/argparse partial-parsing}@anchor{21f2}
@subsubsection 部分解析


@geindex parse_known_args() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser parse_known_args}@anchor{21f3}
@deffn {方法} ArgumentParser.parse_known_args (args=None, namespace=None)
@end deffn

有时一个脚本可能只解析部分命令行参数，而将其余的参数继续传递给另一个脚本或程序。 在这种情况下，@ref{21f3,,parse_known_args()} 方法会很有用处。 它的作用方式很类似 @ref{21b9,,parse_args()} 但区别在于当存在额外参数时它不会产生错误。 而是会返回一个由两个条目构成的元组，其中包含带成员的命名空间和剩余参数字符串的列表。

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('bar')
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
@end example

@cartouche
@quotation 警告 
@ref{793,,前缀匹配} 规则应用于 @code{parse_known_args()}。 一个选项即使只是已知选项的前缀部分解析器也能识别该选项，不会将其放入剩余参数列表。
@end quotation
@end cartouche

@node 自定义文件解析,退出方法,部分解析,其它实用工具
@anchor{library/argparse customizing-file-parsing}@anchor{21f4}
@subsubsection 自定义文件解析


@geindex convert_arg_line_to_args() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser convert_arg_line_to_args}@anchor{21ce}
@deffn {方法} ArgumentParser.convert_arg_line_to_args (arg_line)

从文件读取的参数（见 @ref{792,,ArgumentParser} 的 @emph{fromfile_prefix_chars} 关键字参数）将是一行读取一个参数。 @ref{21ce,,convert_arg_line_to_args()} 可被重载以使用更复杂的读取方式。

此方法接受从参数文件读取的字符串形式的单个参数 @emph{arg_line}。 它返回从该字符串解析出的参数列表。 此方法将在每次按顺序从参数文件读取一行时被调用一次。

此方法的一个有用的重载是将每个以空格分隔的单词视为一个参数。 下面的例子演示了如何实现此重载:

@example
class MyArgumentParser(argparse.ArgumentParser):
    def convert_arg_line_to_args(self, arg_line):
        return arg_line.split()
@end example
@end deffn

@node 退出方法,混合解析,自定义文件解析,其它实用工具
@anchor{library/argparse exiting-methods}@anchor{21f5}
@subsubsection 退出方法


@geindex exit() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser exit}@anchor{21f6}
@deffn {方法} ArgumentParser.exit (status=0, message=None)

此方法将终结程序，退出时附带指定的 @emph{status}，并且如果给出了 @emph{message} 则会在退出前将其打印输出。 用户可重载此方法以不同方式来处理这些步骤:

@example
class ErrorCatchingArgumentParser(argparse.ArgumentParser):
    def exit(self, status=0, message=None):
        if status:
            raise Exception(f'Exiting because of an error: @{message@}')
        exit(status)
@end example
@end deffn

@geindex error() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser error}@anchor{21f7}
@deffn {方法} ArgumentParser.error (message)

此方法将向标准错误打印包括 @emph{message} 的用法消息并附带状态码 2 终结程序。
@end deffn

@node 混合解析,,退出方法,其它实用工具
@anchor{library/argparse intermixed-parsing}@anchor{21f8}
@subsubsection 混合解析


@geindex parse_intermixed_args() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser parse_intermixed_args}@anchor{45a}
@deffn {方法} ArgumentParser.parse_intermixed_args (args=None, namespace=None)
@end deffn

@geindex parse_known_intermixed_args() (argparse.ArgumentParser 方法)
@anchor{library/argparse argparse ArgumentParser parse_known_intermixed_args}@anchor{21f9}
@deffn {方法} ArgumentParser.parse_known_intermixed_args (args=None, namespace=None)
@end deffn

许多 Unix 命令允许用户混用可选参数与位置参数。 @ref{45a,,parse_intermixed_args()} 和 @ref{21f9,,parse_known_intermixed_args()} 方法均支持这种解析风格。

这些解析器并不支持所有的 argparse 特性，并且当未支持的特性被使用时将会引发异常。 特别地，子解析器，@code{argparse.REMAINDER} 以及同时包括可选与位置参数的互斥分组是不受支持的。

下面的例子显示了 @ref{21f3,,parse_known_args()} 与 @ref{45a,,parse_intermixed_args()} 之间的差异：前者会将 @code{['2', '3']} 返回为未解析的参数，而后者会将所有位置参数收集至 @code{rest} 中。

@example
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('cmd')
>>> parser.add_argument('rest', nargs='*', type=int)
>>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
>>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
@end example

@ref{21f9,,parse_known_intermixed_args()} 返回由两个条目组成的元组，其中包含带成员的命名空间以及剩余参数字符串列表。 当存在任何剩余的未解析参数字符串时 @ref{45a,,parse_intermixed_args()} 将引发一个错误。


3.7 新版功能.


@node 升级 optparse 代码,,其它实用工具,argparse --- 命令行选项、参数和子命令解析器
@anchor{library/argparse id2}@anchor{21fa}@anchor{library/argparse upgrading-optparse-code}@anchor{c05}
@subsubsection 升级 optparse 代码


起初，@ref{5,,argparse} 曾经尝试通过 @ref{c3,,optparse} 来维持兼容性。 但是，@ref{c3,,optparse} 很难透明地扩展，特别是那些为支持新的 @code{nargs=} 描述方式和更好的用法消息所需的修改。当When most everything in @ref{c3,,optparse} 中几乎所有内容都已被复制粘贴或打上补丁时，维持向下兼容看来已是不切实际的。

@ref{5,,argparse} 模块在许多方面对标准库的 @ref{c3,,optparse} 模块进行了增强，包括:


@itemize *

@item 
处理位置参数。

@item 
支持子命令。

@item 
允许替代选项前缀例如 @code{+} 和 @code{/}。

@item 
处理零个或多个以及一个或多个风格的参数。

@item 
生成更具信息量的用法消息。

@item 
提供用于定制 @code{type} 和 @code{action} 的更为简单的接口。
@end itemize

从 @ref{c3,,optparse} 到 @ref{5,,argparse} 的部分升级路径:


@itemize *

@item 
将所有 @ref{21fb,,optparse.OptionParser.add_option()} 调用替换为 @ref{21b8,,ArgumentParser.add_argument()} 调用。

@item 
将 @code{(options, args) = parser.parse_args()} 替换为 @code{args = parser.parse_args()} 并为位置参数添加额外的 @ref{21b8,,ArgumentParser.add_argument()} 调用。 请注意之前所谓的 @code{options} 在 @ref{5,,argparse} 上下文中被称为 @code{args}。

@item 
通过使用 @ref{45a,,parse_intermixed_args()} 而非 @ref{21b9,,parse_args()} 来替换 @ref{21fc,,optparse.OptionParser.disable_interspersed_args()}。

@item 
将回调动作和 @code{callback_*} 关键字参数替换为 @code{type} 或 @code{action} 参数。

@item 
将 @code{type} 关键字参数字符串名称替换为相应的类型对象（例如 int, float, complex 等）。

@item 
将 @code{optparse.Values} 替换为 @ref{21bb,,Namespace} 并将 @code{optparse.OptionError} 和 @code{optparse.OptionValueError} 替换为 @code{ArgumentError}。

@item 
将隐式参数字符串例如使用标准 Python 字典语法的 @code{%default} 或 @code{%prog} 替换为格式字符串，即 @code{%(default)s} 和 @code{%(prog)s}。

@item 
将 OptionParser 构造器 @code{version} 参数替换为对 @code{parser.add_argument('--version', action='version', version='<the version>')} 的调用。
@end itemize

@node getopt --- C 风格的命令行选项解析器,logging --- Python 的日志记录工具,argparse --- 命令行选项、参数和子命令解析器,通用操作系统服务
@anchor{library/getopt doc}@anchor{21fd}@anchor{library/getopt getopt-c-style-parser-for-command-line-options}@anchor{21fe}@anchor{library/getopt module-getopt}@anchor{85}
@subsection @code{getopt} --- C 风格的命令行选项解析器


@geindex getopt (模块)

@strong{源代码:} Lib/getopt.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/getopt.py}

@cartouche
@quotation 注解 
@ref{85,,getopt} 模块是一个命令行选项解析器，其 API 设计会让 C @code{getopt()} 函数的用户感到熟悉。 不熟悉 C @code{getopt()} 函数或者希望写更少代码并获得更完善帮助和错误消息的用户应当考虑改用 @ref{5,,argparse} 模块。
@end quotation
@end cartouche


__________________________________________________________________


此模块可协助脚本解析 @code{sys.argv} 中的命令行参数。 它支持与 Unix @code{getopt()} 函数相同的惯例（包括形式如 '@code{-}' 与 '@code{--}' 的参数的特殊含义）。 也能通过可选的第三个参数来使用与 GNU 软件所支持形式相类似的长选项。

此模块提供了两个函数和一个异常:

@geindex getopt() (在 getopt 模块中)
@anchor{library/getopt getopt getopt}@anchor{21ff}
@deffn {函数} getopt.getopt (args, shortopts, longopts=[])

解析命令行选项与形参列表。 @emph{args} 为要解析的参数列表，不包含最开头的对正在运行的程序的引用。 通常这意味着 @code{sys.argv[1:]}。 @emph{shortopts} 为脚本所要识别的字母选项，包含要求后缀一个冒号 (@code{':'}；即与 Unix @code{getopt()} 所用的格式相同) 的选项。

@cartouche
@quotation 注解 
与 GNU @code{getopt()} 不同，在非选项参数之后，所有后续参数都会被视为非选项。 这类似于非 GNU Unix 系统的运作方式。
@end quotation
@end cartouche

如果指定了 @emph{longopts}，则必须为一个由应当被支持的长选项名称组成的列表。 开头的 @code{'--'} 字符不应被包括在选项名称中。 要求参数的长选项后应当带一个等号 (@code{'='})。 可选参数不被支持。 如果想仅接受长选项，则 @emph{shortopts} 应为一个空字符串。 命令行中的长选项只要提供了恰好能匹配可接受选项之一的选项名称前缀即可被识别。 举例来说，如果 @emph{longopts} 为 @code{['foo', 'frob']}，则选项 @code{--fo} 将匹配为 @code{--foo}，但 @code{--f} 将不能得到唯一匹配，因此将引发 @ref{2200,,GetoptError}。

返回值由两个元素组成：第一个是 @code{(option, value)} 对的列表；第二个是在去除该选项列表后余下的程序参数列表（这也就是 @emph{args} 的尾部切片）。每个被返回的选项与值对的第一个元素是选项，短选项前缀一个连字符 (例如 @code{'-x'})，长选项则前缀两个连字符 (例如 @code{'--long-option'})，第二个元素是选项参数，如果选项不带参数则为空字符串。 列表中选项的排列顺序与它们被解析的顺序相同，因此允许多次出现。 长选项与短选项可以混用。
@end deffn

@geindex gnu_getopt() (在 getopt 模块中)
@anchor{library/getopt getopt gnu_getopt}@anchor{2201}
@deffn {函数} getopt.gnu_getopt (args, shortopts, longopts=[])

此函数与 @ref{85,,getopt()} 类似，区别在于它默认使用 GNU 风格的扫描模式。 这意味着选项和非选项参数可能会混在一起。 @ref{85,,getopt()} 函数将在遇到非选项参数时立即停止处理选项。

如果选项字符串的第一个字符为 @code{'+'}，或者如果设置了环境变量 
@geindex POSIXLY_CORRECT
@geindex 环境变量; POSIXLY_CORRECT
@code{POSIXLY_CORRECT}，则选项处理会在遇到非选项参数时立即停止。
@end deffn

@geindex GetoptError
@anchor{library/getopt getopt GetoptError}@anchor{2200}
@deffn {例外} getopt.GetoptError

This is raised当参数列表中出现不可识别的选项或者当一个需要参数的选项未带参数时将引发此异常。 此异常的参数是一个指明错误原因的字符串。 对于长选项，将一个参数传给不需要参数的选项也将导致引发此异常。 @code{msg} 和 @code{opt} 属性会给出错误消息和关联的选项；如果没有关联到异常的特定选项，则 @code{opt} 将为空字符串。
@end deffn

@c XXX deprecated?

@geindex error
@anchor{library/getopt getopt error}@anchor{2202}
@deffn {例外} getopt.error

@ref{2200,,GetoptError} 的别名；用于向后兼容。
@end deffn

一个仅使用 Unix 风格选项的例子:

@example
>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', '@w{'}), ('-b', '@w{'}), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
@end example

使用长选项名也同样容易:

@example
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', '@w{'}), ('--output-file', 'abc.def'), ('-x', '@w{'})]
>>> args
['a1', 'a2']
@end example

在脚本中，典型的用法类似这样:

@example
import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()
@end example

请注意通过 @ref{5,,argparse} 模块可以使用更少的代码并附带更详细的帮助与错误消息生成等价的命令行接口:

@example
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    args = parser.parse_args()
    # ... do something with args.output ...
    # ... do something with args.verbose ..
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{5,,argparse}

替代的命令行选项和参数解析库。
@end table


@node logging --- Python 的日志记录工具,logging config --- 日志记录配置,getopt --- C 风格的命令行选项解析器,通用操作系统服务
@anchor{library/logging doc}@anchor{2203}@anchor{library/logging logging-logging-facility-for-python}@anchor{2204}@anchor{library/logging module-logging}@anchor{aa}
@subsection @code{logging} --- Python 的日志记录工具


@geindex logging (模块)

@strong{源代码：} Lib/logging/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/logging/__init__.py}

@geindex Errors; logging

@subsubheading Important



此页面仅包含 API 参考信息。教程信息和更多高级用法的讨论，请参阅


@itemize *

@item 
@ref{c4c,,基础教程}

@item 
@ref{c4d,,进阶教程}

@item 
@ref{c4e,,日志操作手册}
@end itemize


__________________________________________________________________


这个模块为应用与库实现了灵活的事件日志系统的函数与类。

使用标准库提供的 logging API 最主要的好处是，所有的 Python 模块都可能参与日志输出，包括你自己的日志消息和第三方模块的日志消息。

这个模块提供许多强大而灵活的功能。如果对 logging 不太熟悉， 掌握它最好的方式就是查看它对应的教程（详见右侧的链接）。

该模块定义的基础类和函数都列在下面。


@itemize *

@item 
记录器暴露了应用程序代码直接使用的接口。

@item 
处理器将日志记录（由记录器创建）发送到适当的目标。

@item 
过滤器提供了更细粒度的功能，用于确定要输出的日志记录。

@item 
格式器指定最终输出中日志记录的样式。
@end itemize

@menu
* 记录器对象:: 
* 日志级别:: 
* 处理器对象:: 
* 格式器对象:: 
* 过滤器对象:: 
* LogRecord 属性:: 
* LogRecord 属性: LogRecord 属性<2>. 
* LoggerAdapter 对象:: 
* 线程安全:: 
* 模块级函数:: 
* 模块级属性:: 
* 与警告模块集成:: 

@end menu

@node 记录器对象,日志级别,,logging --- Python 的日志记录工具
@anchor{library/logging logger}@anchor{2205}@anchor{library/logging logger-objects}@anchor{2206}
@subsubsection 记录器对象


记录器有以下的属性和方法。注意 @emph{永远} 不要直接实例化记录器，应当通过模块级别的函数 @code{logging.getLogger(name)} 。多次使用相同的名字调用 @ref{235,,getLogger()} 会一直返回相同的 Logger 对象的引用。

@code{name} 一般是句点分割的层级值, 像`@w{`}foo.bar.baz`@w{`} (尽管也可以只是普通的 @code{foo})。层次结构列表中位于下方的记录器是列表中较高位置的记录器的子级。例如，有个名叫 @code{foo} 的记录器，而名字是 @code{foo.bar}，@code{foo.bar.baz}，和 @code{foo.bam} 的记录器都是 @code{foo} 的子级。记录器的名字分级类似 Python 包的层级，如果使用建议的结构 @code{logging.getLogger(__name__)} 在每个模块的基础上组织记录器，则与之完全相同。这是因为在模块里，@code{__name__} 是该模块在 Python 包命名空间中的名字。

@geindex Logger (logging 中的类)
@anchor{library/logging logging Logger}@anchor{4b6}
@deffn {类} logging.Logger

@geindex propagate (logging.Logger 属性)
@anchor{library/logging logging Logger propagate}@anchor{2207}
@deffn {属性} propagate

如果这个属性为真，记录到这个记录器的事件除了会发送到此记录器的所有处理程序外，还会传递给更高级别（祖先）记录器的处理器，此外任何关联到这个记录器的处理器。消息会直接传递给祖先记录器的处理器 —— 不考虑祖先记录器的级别和过滤器。

如果为假，记录消息将不会传递给当前记录器的祖先记录器的处理器。

举例说明：如果名为 @code{A.B.C} 的记录器的传播属性求值为真，则任何通过调用诸如 @code{logging.getLogger('A.B.C').error(...)} 之类的方法记录到 @code{A.B.C} 的事件，在第一次被传递到 @code{A.B.C} 上附加的处理器后，将[取决于传递该记录器的级别和过滤器设置]依次传递给附加到名为 @code{A.B}，@code{A} 的记录器和根记录器的所有处理器。如果 @code{A.B.C}、@code{A.B}、@code{A} 组成的链中，任一记录器的 @code{propagate} 属性设置为假，那么这将是最后一个其处理器会收到事件的记录器，此后传播在该点停止。

构造器将这个属性初始化为 @code{True}。

@cartouche
@quotation 注解 
如果将处理器附加到记录器 @emph{和} 其一个或多个祖先记录器，它可能发出多次相同的记录。通常，不需要将处理器附加到一个以上的记录器上 —— 如果把它附加到记录器层次结构中最高的适当记录器上，则它将看到所有后代记录器记录的所有事件，前提是它们的传播设置保留为 @code{True}。仅将处理器附加到根记录器，通过传播来处理其余部分这种方案是比较常用的。
@end quotation
@end cartouche
@end deffn

@geindex setLevel() (logging.Logger 方法)
@anchor{library/logging logging Logger setLevel}@anchor{2208}
@deffn {方法} setLevel (level)

给记录器设置阈值为 @emph{level} 。日志等级小于 @emph{level} 会被忽略。严重性为 @emph{level} 或更高的日志消息将由该记录器的任何一个或多个处理器发出，除非将处理器的级别设置为比 @emph{level} 更高的级别。

创建记录器时，级别默认设置为 @code{NOTSET} （当记录器是根记录器时，将处理所有消息；如果记录器不是根记录器，则将委托给父级）。请注意，根记录器的默认级别为 @code{WARNING} 。

委派给父级的意思是如果记录器的级别设置为 NOTSET，将遍历其祖先记录器，直到找到级别不是 NOTSET 的记录器，或者到根记录器为止。

如果发现某个父级的级别不是 NOTSET ，那么该父级的级别将被视为发起搜索的记录器的有效级别，并用于确定如何处理日志事件。

如果搜索到达根记录器，并且其级别为 NOTSET，则将处理所有消息。否则，将使用根记录器的级别作为有效级别。

参见 @ref{2209,,日志级别} 级别列表。


在 3.2 版更改: 现在 @emph{level} 参数可以接受形如 'INFO' 的级别字符串表示形式，以代替形如 @code{INFO} 的整数常量。 但是请注意，级别在内部存储为整数，并且 @ref{220a,,getEffectiveLevel()} 和 @ref{220b,,isEnabledFor()} 等方法的传入/返回值也为整数。

@end deffn

@geindex isEnabledFor() (logging.Logger 方法)
@anchor{library/logging logging Logger isEnabledFor}@anchor{220b}
@deffn {方法} isEnabledFor (level)

指示此记录器是否将处理级别为 @emph{level} 的消息。此方法首先检查由 @code{logging.disable(level)} 设置的模块级的级别，然后检查由 @ref{220a,,getEffectiveLevel()} 确定的记录器的有效级别。
@end deffn

@geindex getEffectiveLevel() (logging.Logger 方法)
@anchor{library/logging logging Logger getEffectiveLevel}@anchor{220a}
@deffn {方法} getEffectiveLevel ()

指示此记录器的有效级别。如果通过 @ref{2208,,setLevel()} 设置了除 @code{NOTSET} 以外的值，则返回该值。否则，将层次结构遍历到根，直到找到除 @code{NOTSET} 以外的其他值，然后返回该值。返回的值是一个整数，通常为 @code{logging.DEBUG}、 @code{logging.INFO} 等等。
@end deffn

@geindex getChild() (logging.Logger 方法)
@anchor{library/logging logging Logger getChild}@anchor{d5b}
@deffn {方法} getChild (suffix)

返回由后缀确定的该记录器的后代记录器。 因此，@code{logging.getLogger('abc').getChild('def.ghi')} 与 @code{logging.getLogger('abc.def.ghi')} 将返回相同的记录器。 这是一个便捷方法，当使用如 @code{__name__} 而不是字符串字面值命名父记录器时很有用。


3.2 新版功能.

@end deffn

@geindex debug() (logging.Logger 方法)
@anchor{library/logging logging Logger debug}@anchor{80b}
@deffn {方法} debug (msg, *args, **kwargs)

在此记录器上记录 @code{DEBUG} 级别的消息。 @emph{msg} 是消息格式字符串，而 @emph{args} 是用于字符串格式化操作合并到 @emph{msg} 的参数。（注意，这里的意思是可以在格式字符串中使用关键字，及单个字典参数。）未提供 @emph{args} 时，不会对 @emph{msg} 执行 ％ 格式化操作。

@emph{kwargs} 中会检查四个关键字参数： @emph{exc_info} ，@emph{stack_info} ，@emph{stacklevel} 和 @emph{extra} 。

如果 @emph{exc_info} 的求值结果不为 false ，则它将异常信息添加到日志消息中。如果提供了异常元组（按照 @ref{d2f,,sys.exc_info()} 返回的格式）或异常实例，则它将被使用；否则，调用 @ref{d2f,,sys.exc_info()} 以获取异常信息。

第二个可选关键字参数是 @emph{stack_info}，默认为 @code{False}。如果为  True，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意，这与通过指定 @emph{exc_info} 显示的堆栈信息不同：前者是从堆栈底部到当前线程中的日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，跟踪异常而打开的堆栈帧的信息。

您可以独立于 @emph{exc_info} 来指定 @emph{stack_info}，例如，即使在未引发任何异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题行之后打印：

@example
Stack (most recent call last):
@end example

这模仿了显示异常帧时所使用的 @code{Traceback (most recent call last):} 。

第三个可选关键字参数是 @emph{stacklevel} ，默认为 @code{1} 。如果大于 1 ，则在为日志记录事件创建的 @ref{9f5,,LogRecord} 中计算行号和函数名时，将跳过相应数量的堆栈帧。可以在记录帮助器时使用它，以便记录的函数名称，文件名和行号不是帮助器的函数/方法的信息，而是其调用方的信息。此参数是 @ref{12f,,warnings} 模块中的同名等效参数。

第四个关键字参数是 @emph{extra} ，传递一个字典，该字典用于填充为日志记录事件创建的、带有用户自定义属性的 @ref{9f5,,LogRecord} 中的 __dict__ 。然后可以按照需求使用这些自定义属性。例如，可以将它们合并到已记录的消息中：

@example
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = @{'clientip': '192.168.0.1', 'user': 'fbloggs'@}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)
@end example

输出类似于

@example
2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
@end example

@emph{extra} 中传入的字典的键不应与日志系统使用的键冲突。（有关日志系统使用哪些键的更多信息，请参见 @ref{220c,,Formatter} 的文档。）

如果在已记录的消息中使用这些属性，则需要格外小心。例如，在上面的示例中，@ref{220c,,Formatter} 已设置了格式字符串，其在 @ref{9f5,,LogRecord} 的属性字典中键值为 “clientip” 和 “user”。如果缺少这些内容，则将不会记录该消息，因为会引发字符串格式化异常。因此，在这种情况下，您始终需要使用 @emph{extra} 字典传递这些键。

尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执行相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如在上面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下，很可能将专门的 @ref{220c,,Formatter} 与特定的 @ref{220d,,Handler} 一起使用。


在 3.2 版更改: 增加了 @emph{stack_info} 参数。



在 3.5 版更改: @emph{exc_info} 参数现在可以接受异常实例。



在 3.8 版更改: 增加了 @emph{stacklevel} 参数。

@end deffn

@geindex info() (logging.Logger 方法)
@anchor{library/logging logging Logger info}@anchor{220e}
@deffn {方法} info (msg, *args, **kwargs)

在此记录器上记录 @code{INFO} 级别的消息。参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex warning() (logging.Logger 方法)
@anchor{library/logging logging Logger warning}@anchor{2210}
@deffn {方法} warning (msg, *args, **kwargs)

在此记录器上记录 @code{WARNING} 级别的消息。参数解释同 @ref{220f,,debug()}。

@cartouche
@quotation 注解 
有一个功能上与 @code{warning} 一致的方法 @code{warn}。由于 @code{warn} 已被弃用，请勿再用 —— 改为使用 @code{warning}。
@end quotation
@end cartouche
@end deffn

@geindex error() (logging.Logger 方法)
@anchor{library/logging logging Logger error}@anchor{2211}
@deffn {方法} error (msg, *args, **kwargs)

在此记录器上记录 @code{ERROR} 级别的消息。参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex critical() (logging.Logger 方法)
@anchor{library/logging logging Logger critical}@anchor{80a}
@deffn {方法} critical (msg, *args, **kwargs)

在此记录器上记录 @code{CRITICAL} 级别的消息。参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex log() (logging.Logger 方法)
@anchor{library/logging logging Logger log}@anchor{808}
@deffn {方法} log (level, msg, *args, **kwargs)

在此记录器上记录 @emph{level} 整数代表的级别的消息。参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex exception() (logging.Logger 方法)
@anchor{library/logging logging Logger exception}@anchor{809}
@deffn {方法} exception (msg, *args, **kwargs)

在此记录器上记录 @code{ERROR} 级别的消息。参数解释同 @ref{220f,,debug()}。异常信息将添加到日志消息中。仅应从异常处理程序中调用此方法。
@end deffn

@geindex addFilter() (logging.Logger 方法)
@anchor{library/logging logging Logger addFilter}@anchor{2212}
@deffn {方法} addFilter (filter)

将指定的过滤器 @emph{filter} 添加到此记录器。
@end deffn

@geindex removeFilter() (logging.Logger 方法)
@anchor{library/logging logging Logger removeFilter}@anchor{2213}
@deffn {方法} removeFilter (filter)

从此记录器中删除指定的过滤器 @emph{filter}。
@end deffn

@geindex filter() (logging.Logger 方法)
@anchor{library/logging logging Logger filter}@anchor{2214}
@deffn {方法} filter (record)

将此记录器的过滤器应用于记录，如果记录能被处理则返回 @code{True}。过滤器会被依次使用，直到其中一个返回假值为止。如果它们都不返回假值，则记录将被处理（传递给处理器）。如果返回任一为假值，则不会对该记录做进一步处理。
@end deffn

@geindex addHandler() (logging.Logger 方法)
@anchor{library/logging logging Logger addHandler}@anchor{2215}
@deffn {方法} addHandler (hdlr)

将指定的处理器 @emph{hdlr} 添加到此记录器。
@end deffn

@geindex removeHandler() (logging.Logger 方法)
@anchor{library/logging logging Logger removeHandler}@anchor{2216}
@deffn {方法} removeHandler (hdlr)

从此记录器中删除指定的处理器 @emph{hdlr}。
@end deffn

@geindex findCaller() (logging.Logger 方法)
@anchor{library/logging logging Logger findCaller}@anchor{2217}
@deffn {方法} findCaller (stack_info=False, stacklevel=1)

查找调用源的文件名和行号，以 文件名，行号，函数名称和堆栈信息 4元素元组的形式返回。堆栈信息将返回 @code{None}，除非 @emph{stack_info} 为 @code{True}。

@emph{stacklevel} 参数用于调用 @ref{220f,,debug()} 和其他 API。如果大于 1，则多余部分将用于跳过堆栈帧，然后再确定要返回的值。当从帮助器/包装器代码调用日志记录 API 时，这通常很有用，以便事件日志中的信息不是来自帮助器/包装器代码，而是来自调用它的代码。
@end deffn

@geindex handle() (logging.Logger 方法)
@anchor{library/logging logging Logger handle}@anchor{2218}
@deffn {方法} handle (record)

通过将记录传递给与此记录器及其祖先关联的所有处理器来处理（直到某个 @emph{propagate} 值为 false）。此方法用于从套接字接收的未序列化的以及在本地创建的记录。使用 @ref{2214,,filter()} 进行记录器级别过滤。
@end deffn

@geindex makeRecord() (logging.Logger 方法)
@anchor{library/logging logging Logger makeRecord}@anchor{2219}
@deffn {方法} makeRecord (name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

这是一种工厂方法，可以在子类中对其进行重写以创建专门的 @ref{9f5,,LogRecord} 实例。
@end deffn

@geindex hasHandlers() (logging.Logger 方法)
@anchor{library/logging logging Logger hasHandlers}@anchor{221a}
@deffn {方法} hasHandlers ()

检查此记录器是否配置了任何处理器。通过在此记录器及其记录器层次结构中的父级中查找处理器完成此操作。如果找到处理器则返回 @code{True}，否则返回 @code{False}。只要找到 “propagate” 属性设置为假值的记录器，该方法就会停止搜索层次结构 —— 其将是最后一个检查处理器是否存在的记录器。


3.2 新版功能.

@end deffn


在 3.7 版更改: 现在可以对处理器进行序列化和反序列化。

@end deffn

@node 日志级别,处理器对象,记录器对象,logging --- Python 的日志记录工具
@anchor{library/logging levels}@anchor{2209}@anchor{library/logging logging-levels}@anchor{221b}
@subsubsection 日志级别


日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具有相对于预定义级别的特定值，那么这你可能对以下内容感兴趣。如果你定义具有相同数值的级别，它将覆盖预定义的值；预定义的名称将失效。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

级别

@tab

数值

@item

@code{CRITICAL}

@tab

50

@item

@code{ERROR}

@tab

40

@item

@code{WARNING}

@tab

30

@item

@code{INFO}

@tab

20

@item

@code{DEBUG}

@tab

10

@item

@code{NOTSET}

@tab

0

@end multitable


@node 处理器对象,格式器对象,日志级别,logging --- Python 的日志记录工具
@anchor{library/logging handler}@anchor{221c}@anchor{library/logging handler-objects}@anchor{221d}
@subsubsection 处理器对象


Handler 有以下属性和方法。注意不要直接实例化 @ref{220d,,Handler} ；这个类用来派生其他更有用的子类。但是，子类的 @ref{e2b,,__init__()} 方法需要调用 @ref{221e,,Handler.__init__()} 。

@geindex Handler (logging 中的类)
@anchor{library/logging logging Handler}@anchor{220d}
@deffn {类} logging.Handler

@geindex __init__() (logging.Handler 方法)
@anchor{library/logging logging Handler __init__}@anchor{221e}
@deffn {方法} __init__ (level=NOTSET)

初始化 @ref{220d,,Handler} 实例时，需要设置它的级别，将过滤列表置为空，并且创建锁（通过 @ref{221f,,createLock()} ）来序列化对 I/O 的访问。
@end deffn

@geindex createLock() (logging.Handler 方法)
@anchor{library/logging logging Handler createLock}@anchor{221f}
@deffn {方法} createLock ()

初始化一个线程锁，用来序列化对底层的 I/O 功能的访问，底层的 I/O 功能可能不是线程安全的。
@end deffn

@geindex acquire() (logging.Handler 方法)
@anchor{library/logging logging Handler acquire}@anchor{2220}
@deffn {方法} acquire ()

获取由 @ref{221f,,createLock()} 创建的线程锁。
@end deffn

@geindex release() (logging.Handler 方法)
@anchor{library/logging logging Handler release}@anchor{2221}
@deffn {方法} release ()

释放由 @ref{2220,,acquire()} 获取的线程锁。
@end deffn

@geindex setLevel() (logging.Handler 方法)
@anchor{library/logging logging Handler setLevel}@anchor{2222}
@deffn {方法} setLevel (level)

给处理器设置阈值为 @emph{level} 。日志级别小于 @emph{level} 将被忽略。创建处理器时，日志级别被设置为 @code{NOTSET} （所有的消息都会被处理）。

参见 @ref{2209,,日志级别} 级别列表。


在 3.2 版更改: @emph{level} 形参现在接受像 'INFO' 这样的字符串形式的级别表达方式，也可以使用像 @code{INFO} 这样的整数常量。

@end deffn

@geindex setFormatter() (logging.Handler 方法)
@anchor{library/logging logging Handler setFormatter}@anchor{2223}
@deffn {方法} setFormatter (fmt)

将此处理器的 @ref{220c,,Formatter} 设置为 @emph{fmt}。
@end deffn

@geindex addFilter() (logging.Handler 方法)
@anchor{library/logging logging Handler addFilter}@anchor{2224}
@deffn {方法} addFilter (filter)

将指定的过滤器 @emph{filter} 添加到此处理器。
@end deffn

@geindex removeFilter() (logging.Handler 方法)
@anchor{library/logging logging Handler removeFilter}@anchor{2225}
@deffn {方法} removeFilter (filter)

从此处理器中删除指定的过滤器 @emph{filter} 。
@end deffn

@geindex filter() (logging.Handler 方法)
@anchor{library/logging logging Handler filter}@anchor{2226}
@deffn {方法} filter (record)

将此处理器的过滤器应用于记录，在要处理记录时返回 @code{True} 。依次查询过滤器，直到其中一个返回假值为止。如果它们都不返回假值，则将发出记录。如果返回一个假值，则处理器将不会发出记录。
@end deffn

@geindex flush() (logging.Handler 方法)
@anchor{library/logging logging Handler flush}@anchor{2227}
@deffn {方法} flush ()

确保所有日志记录从缓存输出。此版本不执行任何操作，并且应由子类实现。
@end deffn

@geindex close() (logging.Handler 方法)
@anchor{library/logging logging Handler close}@anchor{2228}
@deffn {方法} close ()

回收处理器使用的所有资源。此版本不输出，但从内部处理器列表中删除处理器，内部处理器在 @ref{2229,,shutdown()} 被调用时关闭 。子类应确保从重写的 @ref{2228,,close()} 方法中调用此方法。
@end deffn

@geindex handle() (logging.Handler 方法)
@anchor{library/logging logging Handler handle}@anchor{222a}
@deffn {方法} handle (record)

经已添加到处理器的过滤器过滤后，有条件地发出指定的日志记录。用获取/释放 I/O 线程锁包装了记录的实际发出行为。
@end deffn

@geindex handleError() (logging.Handler 方法)
@anchor{library/logging logging Handler handleError}@anchor{222b}
@deffn {方法} handleError (record)

调用 @ref{222c,,emit()} 期间遇到异常时，应从处理器中调用此方法。如果模块级属性 @code{raiseExceptions} 是 @code{False}，则异常将被静默忽略。这是大多数情况下日志系统需要的 —— 大多数用户不会关心日志系统中的错误，他们对应用程序错误更感兴趣。但是，你可以根据需要将其替换为自定义处理器。指定的记录是发生异常时正在处理的记录。（@code{raiseExceptions} 的默认值是 @code{True}，因为这在开发过程中是比较有用的）。
@end deffn

@geindex format() (logging.Handler 方法)
@anchor{library/logging logging Handler format}@anchor{222d}
@deffn {方法} format (record)

如果设置了格式器则用其对记录进行格式化。否则，使用模块的默认格式器。
@end deffn

@geindex emit() (logging.Handler 方法)
@anchor{library/logging logging Handler emit}@anchor{222c}
@deffn {方法} emit (record)

执行实际记录给定日志记录所需的操作。这个版本应由子类实现，因此这里直接引发 @ref{70e,,NotImplementedError} 异常。
@end deffn
@end deffn

有关作为标准随附的处理器列表，请参见 @ref{ac,,logging.handlers}。

@node 格式器对象,过滤器对象,处理器对象,logging --- Python 的日志记录工具
@anchor{library/logging formatter-objects}@anchor{222e}@anchor{library/logging id1}@anchor{222f}
@subsubsection 格式器对象


@ref{220c,,Formatter} 对象拥有以下的属性和方法。一般情况下，它们负责将 @ref{9f5,,LogRecord} 转换为可由人或外部系统解释的字符串。基础的 @ref{220c,,Formatter} 允许指定格式字符串。如果未提供任何值，则使用默认值 @code{'%(message)s'} ，它仅将消息包括在日志记录调用中。要在格式化输出中包含其他信息（如时间戳），请阅读下文。

格式器可以使用格式化字符串来初始化，该字符串利用 @ref{9f5,,LogRecord} 的属性 —— 例如上述默认值，用户的消息和参数预先格式化为 @ref{9f5,,LogRecord} 的 @emph{message} 属性后被使用。此格式字符串包含标准的 Python %-s 样式映射键。有关字符串格式的更多信息，请参见 @ref{1388,,printf 风格的字符串格式化}。

@ref{2230,,LogRecord 属性} 一节中给出了 @ref{9f5,,LogRecord} 中有用的映射键。

@geindex Formatter (logging 中的类)
@anchor{library/logging logging Formatter}@anchor{220c}
@deffn {类} logging.Formatter (fmt=None, datefmt=None, style='%', validate=True)

返回 @ref{220c,,Formatter} 类的新实例。实例将使用整个消息的格式字符串以及消息的日期/时间部分的格式字符串进行初始化。如果未指定 @emph{fmt} ，则使用 @code{'%(message)s'}。如果未指定 @emph{datefmt}，则使用  @ref{2231,,formatTime()} 文档中描述的格式。

@emph{style} 形参可以是 '%', '@{' 或 '$' 之一，它决定格式字符串将如何与数据进行合并：使用 %-formatting, @ref{5dd,,str.format()} 或是 @ref{4f9,,string.Template}。 这仅适用于格式字符串 @emph{fmt} (例如 @code{'%(message)s'} 或 @code{@{message@}})，不适用于传递给 @code{Logger.debug} 的实际日志消息等；请参阅 @ref{2232,,生效于整个应用程序的格式化样式} 了解有关在日志消息中使用 @{- 和 $-formatting 的更多详情。


在 3.2 版更改: 加入了 @emph{style}  形参。



在 3.8 版更改: 加入*validate* 参数。不正确或不匹配的样式和格式将引发 @code{ValueError} 错误。例如: @code{logging.Formatter('%(asctime)s - %(message)s', style='@{')}。


@geindex format() (logging.Formatter 方法)
@anchor{library/logging logging Formatter format}@anchor{2233}
@deffn {方法} format (record)

记录的属性字典用作字符串格式化操作的参数。返回结果字符串。在格式化字典之前，需要执行几个准备步骤。 使用 @emph{msg} % @emph{args} 计算记录的 @emph{message} 属性。如果格式化字符串包含 @code{'(asctime)'}，则调用 @ref{2231,,formatTime()} 来格式化事件时间。如果有异常信息，则使用 @ref{2234,,formatException()} 将其格式化并附加到消息中。请注意，格式化的异常信息缓存在属性 @emph{exc_text} 中。这很有用，因为可以对异常信息进行序列化并通过网络发送，但是如果您有不止一个定制了异常信息格式的 @ref{220c,,Formatter} 子类，则应格外小心。在这种情况下，您必须在格式器完成格式化后清除缓存的值，以便下一个处理事件的格式器不使用缓存的值，而是重新计算它。

如果栈信息可用，它将被添加在异常信息之后，如有必要请使用 @ref{2235,,formatStack()} 来转换它。
@end deffn

@geindex formatTime() (logging.Formatter 方法)
@anchor{library/logging logging Formatter formatTime}@anchor{2231}
@deffn {方法} formatTime (record, datefmt=None)

此方法应由想要使用格式化时间的格式器中的 @ref{5de,,format()} 调用。可以在格式器中重写此方法以提供任何特定要求，但是基本行为如下：如果指定了 @emph{datefmt} （字符串），则将其用于 @ref{c40,,time.strftime()} 来格式化记录的创建时间。否则，使用格式 '%Y-%m-%d %H:%M:%S,uuu'，其中 uuu 部分是毫秒值，其他字母根据 @ref{c40,,time.strftime()} 文档。这种时间格式的示例为 @code{2003-01-23 00:29:50,411}。返回结果字符串。

此函数使用一个用户可配置函数将创建时间转换为元组。 默认情况下，使用 @ref{10c9,,time.localtime()}；要为特定格式化程序实例更改此项，请将实例的 @code{converter} 属性设为具有与 @ref{10c9,,time.localtime()} 或 @ref{c1a,,time.gmtime()} 相同签名的函数。 要为所有格式化程序更改此项，例如当你希望所有日志时间都显示为 GMT，请在 @code{Formatter} 类中设置 @code{converter} 属性。


在 3.3 版更改: 在之前版本中，默认格式是被硬编码的，例如这个例子: @code{2010-09-06 22:38:15,292} 其中逗号之前的部分由 strptime 格式字符串 (@code{'%Y-%m-%d %H:%M:%S'}) 处理，而逗号之后的部分为毫秒值。 因为 strptime 没有表示毫秒的占位符，毫秒值使用了另外的格式字符串来添加 @code{'%s,%03d'} --- 这两个格式字符串代码都是硬编码在该方法中的。 经过修改，这些字符串被定义为类层级的属性，当需要时可以在实例层级上被重载。 属性的名称为 @code{default_time_format} (用于 strptime 格式字符串) 和 @code{default_msec_format} (用于添加毫秒值)。



在 3.9 版更改: @code{default_msec_format} 可以为 @code{None}。

@end deffn

@geindex formatException() (logging.Formatter 方法)
@anchor{library/logging logging Formatter formatException}@anchor{2234}
@deffn {方法} formatException (exc_info)

将指定的异常信息（由 @ref{d2f,,sys.exc_info()} 返回的标准异常元组）格式化为字符串。默认实现只是使用了 @ref{2236,,traceback.print_exception()}。 结果字符串将被返回。
@end deffn

@geindex formatStack() (logging.Formatter 方法)
@anchor{library/logging logging Formatter formatStack}@anchor{2235}
@deffn {方法} formatStack (stack_info)

将指定的堆栈信息（由 @ref{873,,traceback.print_stack()} 返回的字符串，但移除末尾的换行符）格式化为字符串。 默认实现只是返回输入值。
@end deffn
@end deffn

@node 过滤器对象,LogRecord 属性,格式器对象,logging --- Python 的日志记录工具
@anchor{library/logging filter}@anchor{2237}@anchor{library/logging filter-objects}@anchor{2238}
@subsubsection 过滤器对象


@code{Filters} 可被 @code{Handlers} 和 @code{Loggers} 用来实现比按层级提供更复杂的过滤操作。 基本过滤器类只允许低于日志记录器层级结构中低于特定层级的事件。 例如，一个用 'A.B' 初始化的过滤器将允许 'A.B', 'A.B.C', 'A.B.C.D', 'A.B.D' 等日志记录器所记录的事件。 但 'A.BB', 'B.A.B' 等则不允许。 如果用空字符串初始化，则所有事件都会通过。

@geindex Filter (logging 中的类)
@anchor{library/logging logging Filter}@anchor{c51}
@deffn {类} logging.Filter (name='@w{'})

返回一个 @ref{c51,,Filter} 类的实例。 如果指定了 @emph{name}，则它将被用来为日志记录器命名，该类及其子类将通过该过滤器允许指定事件通过。 如果 @emph{name} 为空字符串，则允许所有事件通过。

@geindex filter() (logging.Filter 方法)
@anchor{library/logging logging Filter filter}@anchor{2239}
@deffn {方法} filter (record)

是否要记录指定的记录？返回零表示否，非零表示是。如果认为合适，则可以通过此方法就地修改记录。
@end deffn
@end deffn

请注意关联到处理器的过滤器会在事件由处理器发出之前被查询，而关联到日志记录器的过滤器则会在有事件被记录的的任何时候（使用 @ref{220f,,debug()}, @ref{223a,,info()} 等等）在将事件发送给处理器之前被查询。 这意味着由后代日志记录器生成的事件将不会被父代日志记录器的过滤器设置所过滤，除非该过滤器也已被应用于后代日志记录器。

你实际上不需要子类化 @code{Filter} ：你可以传入任何一个包含有相同语义的 @code{filter} 方法的实例。


在 3.2 版更改: 你不需要创建专门的 @code{Filter} 类，或使用具有 @code{filter} 方法的其他类：你可以使用一个函数（或其他可调用对象）作为过滤器。 过滤逻辑将检查过滤器对象是否具有 @code{filter} 属性：如果有，就会将它当作是 @code{Filter} 并调用它的 @ref{2239,,filter()} 方法。 在其他情况下，则会将它当作是可调用对象并将记录作为唯一的形参进行调用。 返回值应当与 @ref{2239,,filter()} 的返回值相一致。


尽管过滤器主要被用来构造比层级更复杂的规则以过滤记录，但它们可以查看由它们关联的处理器或记录器所处理的每条记录：当你想要执行统计特定记录器或处理器共处理了多少条记录，或是在所处理的 @ref{9f5,,LogRecord} 中添加、修改或移除属性这样的任务时该特性将很有用处。 显然改变 LogRecord 时需要相当小心，但将上下文信息注入日志确实是被允许的 (参见 @ref{223b,,利用 Filter 传递上下文信息})。

@node LogRecord 属性,LogRecord 属性<2>,过滤器对象,logging --- Python 的日志记录工具
@anchor{library/logging log-record}@anchor{223c}@anchor{library/logging logrecord-objects}@anchor{223d}
@subsubsection LogRecord 属性


@ref{9f5,,LogRecord} 实例是每当有日志被记录时由 @ref{4b6,,Logger} 自动创建的，并且可通过 @ref{223e,,makeLogRecord()} 手动创建（例如根据从网络接收的已封存事件创建）。

@geindex LogRecord (logging 中的类)
@anchor{library/logging logging LogRecord}@anchor{9f5}
@deffn {类} logging.LogRecord (name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

包含与被记录的事件相关的所有信息。

主要信息是在 @code{msg} 和 @code{args} 中传递的，它们使用 @code{msg % args} 组合到一起以创建记录的 @code{message} 字段。

@*参数: 

@itemize *

@item 
@code{name} -- 用于记录由此 LogRecord 所表示事件的记录器名称。 请注意此名称将始终为该值，即使它可能是由附加到不同（祖先）日志记录器的处理器所发出的。

@item 
@code{level} -- 以数字表示的日志记录事件层级（如 DEBUG, INFO 等）。 请注意这会转换为 LogRecord 的 @emph{两个} 属性: @code{levelno} 为数字值而 @code{levelname} 为对应的层级名称。

@item 
@code{pathname} -- 进行日志记录调用的文件的完整路径名。

@item 
@code{lineno} -- 记录调用所在源文件中的行号。

@item 
@code{msg} -- 事件描述消息，可能为带有可变数据占位符的格式字符串。

@item 
@code{args} -- 要合并到 @emph{msg} 参数以获得事件描述的可变数据。

@item 
@code{exc_info} -- 包含当前异常信息的异常元组，或者如果没有可用异常信息则为 @code{None}。

@item 
@code{func} -- 发起调用日志记录调用的函数或方法名称。

@item 
@code{sinfo} -- 一个文本字符串，表示当前线程中从堆栈底部直到日志记录调用的堆栈信息。
@end itemize


@geindex getMessage() (logging.LogRecord 方法)
@anchor{library/logging logging LogRecord getMessage}@anchor{223f}
@deffn {方法} getMessage ()

在将 @ref{9f5,,LogRecord} 实例与任何用户提供的参数合并之后，返回此实例的消息。 如果用户提供给日志记录调用的消息参数不是字符串，则会在其上调用 @ref{206,,str()} 以将它转换为字符串。 此方法允许将用户定义的类用作消息，类的 @code{__str__} 方法可以返回要使用的实际格式字符串。
@end deffn


在 3.2 版更改: 通过提供用于创建记录的工厂方法已使得 @ref{9f5,,LogRecord} 的创建更易于配置。 该工厂方法可使用 @ref{2240,,getLogRecordFactory()} 和 @ref{2241,,setLogRecordFactory()} （在此可查看工厂方法的签名）来设置。


在创建时可使用此功能将你自己的值注入 @ref{9f5,,LogRecord}。 你可以使用以下模式:

@example
old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
@end example

通过此模式，多个工厂方法可以被链接起来，并且只要它们不重载彼此的属性或是在无意中覆盖了上面列出的标准属性，就不会发生意外。
@end deffn

@node LogRecord 属性<2>,LoggerAdapter 对象,LogRecord 属性,logging --- Python 的日志记录工具
@anchor{library/logging id2}@anchor{2242}@anchor{library/logging logrecord-attributes}@anchor{2230}
@subsubsection LogRecord 属性


LogRecord 具有许多属性，它们大多数来自于传递给构造器的形参。 （请注意 LogRecord 构造器形参与 LogRecord 属性的名称并不总是完全彼此对应的。） 这些属性可被用于将来自记录的数据合并到格式字符串中。 下面的表格（按字母顺序）列出了属性名称、它们的含义以及相应的 %-style 格式字符串内占位符。

如果是使用 @{@}-格式化（@ref{5dd,,str.format()}），你可以将 @code{@{attrname@}} 用作格式字符串内的占位符。 如果是使用 $-格式化（@ref{4f9,,string.Template}），则会使用 @code{$@{attrname@}} 的形式。 当然在这两种情况下，都应当将 @code{attrname} 替换为你想要使用的实际属性名称。

在 @{@}-格式化的情况下，你可以在属性名称之后放置指定的格式化旗标，并用冒号来分隔两者。 例如，占位符 @code{@{msecs:03d@}} 会将毫秒值 @code{4} 格式化为 @code{004}。 请参看 @ref{5dd,,str.format()} 文档了解你所能使用的选项的完整细节。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性名称

@tab

格式

@tab

描述

@item

args

@tab

此属性不需要用户进行格式化。

@tab

合并到 @code{msg} 以产生 @code{message} 的包含参数的元组，或是其中的值将被用于合并的字典（当只有一个参数且其类型为字典时）。

@item

asctime

@tab

@code{%(asctime)s}

@tab

表示 @ref{9f5,,LogRecord} 何时被创建的供人查看时间值。 默认形式为 '2003-07-08 16:49:45,896' （逗号之后的数字为时间的毫秒部分）。

@item

created

@tab

@code{%(created)f}

@tab

@ref{9f5,,LogRecord} 被创建的时间（即 @ref{436,,time.time()} 的返回值）。

@item

exc_info

@tab

此属性不需要用户进行格式化。

@tab

异常元组（例如 @code{sys.exc_info}）或者如未发生异常则为 @code{None}。

@item

filename

@tab

@code{%(filename)s}

@tab

@code{pathname} 的文件名部分。

@item

funcName

@tab

@code{%(funcName)s}

@tab

函数名包括调用日志记录.

@item

levelname

@tab

@code{%(levelname)s}

@tab

消息文本记录级别（@code{'DEBUG'}，@code{'INFO'}，@code{'WARNING'}，@code{'ERROR'}，@code{'CRITICAL'}）。

@item

levelno

@tab

@code{%(levelno)s}

@tab

消息数字的记录级别 (@code{DEBUG}, @code{INFO}, @code{WARNING}, @code{ERROR}, @code{CRITICAL}).

@item

lineno

@tab

@code{%(lineno)d}

@tab

发出日志记录调用所在的源行号（如果可用）。

@item

message

@tab

@code{%(message)s}

@tab

记入日志的消息，即 @code{msg % args} 的结果。 这是在发起调用 @ref{2233,,Formatter.format()} 时设置的。

@item

module

@tab

@code{%(module)s}

@tab

模块 (@code{filename} 的名称部分)。

@item

msecs

@tab

@code{%(msecs)d}

@tab

@ref{9f5,,LogRecord} 被创建的时间的毫秒部分。

@item

msg

@tab

此属性不需要用户进行格式化。

@tab

在原始日志记录调用中传入的格式字符串。 与 @code{args} 合并以产生 @code{message}，或是一个任意对象 (参见 @ref{2243,,使用任意对象作为消息})。

@item

name

@tab

@code{%(name)s}

@tab

用于记录调用的日志记录器名称。

@item

pathname

@tab

@code{%(pathname)s}

@tab

发出日志记录调用的源文件的完整路径名（如果可用）。

@item

process

@tab

@code{%(process)d}

@tab

进程ID（如果可用）

@item

processName

@tab

@code{%(processName)s}

@tab

进程名（如果可用）

@item

relativeCreated

@tab

@code{%(relativeCreated)d}

@tab

以毫秒数表示的 LogRecord 被创建的时间，即相对于 logging 模块被加载时间的差值。

@item

stack_info

@tab

此属性不需要用户进行格式化。

@tab

当前线程中从堆栈底部起向上直到包括日志记录调用并引发创建当前记录堆栈帧创建的堆栈帧信息（如果可用）。

@item

thread

@tab

@code{%(thread)d}

@tab

线程ID（如果可用）

@item

threadName

@tab

@code{%(threadName)s}

@tab

线程名（如果可用）

@end multitable



在 3.1 版更改: 添加了 @emph{processName}


@node LoggerAdapter 对象,线程安全,LogRecord 属性<2>,logging --- Python 的日志记录工具
@anchor{library/logging logger-adapter}@anchor{2244}@anchor{library/logging loggeradapter-objects}@anchor{2245}
@subsubsection LoggerAdapter 对象


@ref{d5c,,LoggerAdapter} 实例会被用来方便地将上下文信息传入日志记录调用。 要获取用法示例，请参阅 @ref{2246,,添加上下文信息到你的日志记录输出} 部分。

@geindex LoggerAdapter (logging 中的类)
@anchor{library/logging logging LoggerAdapter}@anchor{d5c}
@deffn {类} logging.LoggerAdapter (logger, extra)

返回一个 @ref{d5c,,LoggerAdapter} 的实例，该实例的初始化使用了下层的 @ref{4b6,,Logger} 实例和一个字典类对象。

@geindex process() (logging.LoggerAdapter 方法)
@anchor{library/logging logging LoggerAdapter process}@anchor{2247}
@deffn {方法} process (msg, kwargs)

修改传递给日志记录调用的消息和/或关键字参数以便插入上下文信息。 此实现接受以 @emph{extra} 形式传给构造器的对象并使用 'extra' 键名将其加入 @emph{kwargs}。 返回值为一个 (@emph{msg}, @emph{kwargs}) 元组，其包含（可能经过修改的）传入参数。
@end deffn
@end deffn

在上述方法之外，@ref{d5c,,LoggerAdapter} 还支持 @ref{4b6,,Logger} 的下列方法: @ref{80b,,debug()}, @ref{220e,,info()}，@ref{2210,,warning()}，@ref{2211,,error()}, @ref{809,,exception()}, @ref{80a,,critical()}，@ref{808,,log()}，@ref{220b,,isEnabledFor()}，@ref{220a,,getEffectiveLevel()}，@ref{2208,,setLevel()} 以及 @ref{221a,,hasHandlers()}。 这些方法具有与它们在 @ref{4b6,,Logger} 中的对应方法相同的签名，因此你可以互换使用这两种类型的实例。


在 3.2 版更改: @ref{220b,,isEnabledFor()}, @ref{220a,,getEffectiveLevel()}, @ref{2208,,setLevel()} 和 @ref{221a,,hasHandlers()} 方法已被添加到 @ref{d5c,,LoggerAdapter}。 这些方法会委托给下层的日志记录器。



在 3.6 版更改: 增加了 @code{manager} 属性和 @code{_log()} 方法，它们会委托给下层的日志记录器并允许适配器嵌套。


@node 线程安全,模块级函数,LoggerAdapter 对象,logging --- Python 的日志记录工具
@anchor{library/logging thread-safety}@anchor{2248}
@subsubsection 线程安全


logging 模块的目标是使客户端不必执行任何特殊操作即可确保线程安全。 它通过使用线程锁来达成这个目标；用一个锁来序列化对模块共享数据的访问，并且每个处理程序也会创建一个锁来序列化对其下层 I/O 的访问。

如果你要使用 @ref{ea,,signal} 模块来实现异步信号处理程序，则可能无法在这些处理程序中使用 logging。 这是因为 @ref{10b,,threading} 模块中的锁实现并非总是可重入的，所以无法从此类信号处理程序发起调用。

@node 模块级函数,模块级属性,线程安全,logging --- Python 的日志记录工具
@anchor{library/logging module-level-functions}@anchor{2249}
@subsubsection 模块级函数


在上述的类之外，还有一些模块级的函数。

@geindex getLogger() (在 logging 模块中)
@anchor{library/logging logging getLogger}@anchor{235}
@deffn {函数} logging.getLogger (name=None)

返回具有指定 name 的日志记录器，或者当 name 为 @code{None} 时返回层级结构中的根日志记录器。 如果指定了 name，它通常是以点号分隔的带层级结构的名称，如 @emph{'a'}、@emph{'a.b'} 或 @emph{'a.b.c.d'}。 这些名称的选择完全取决于使用 logging 的开发者。

所有用给定的 name 对该函数的调用都将返回相同的日志记录器实例。 这意味着日志记录器实例不需要在应用的各部分间传递。
@end deffn

@geindex getLoggerClass() (在 logging 模块中)
@anchor{library/logging logging getLoggerClass}@anchor{224a}
@deffn {函数} logging.getLoggerClass ()

返回标准的 @ref{4b6,,Logger} 类，或是最近传给 @ref{224b,,setLoggerClass()} 的类。 此函数可以从一个新的类定义中调用，以确保安装自定义的 @ref{4b6,,Logger} 类不会撤销其他代码已经应用的自定义操作。 例如:

@example
class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here
@end example
@end deffn

@geindex getLogRecordFactory() (在 logging 模块中)
@anchor{library/logging logging getLogRecordFactory}@anchor{2240}
@deffn {函数} logging.getLogRecordFactory ()

返回一个被用来创建 @ref{9f5,,LogRecord} 的可调用对象。


3.2 新版功能: 此函数与 @ref{2241,,setLogRecordFactory()} 一起提供，以允许开发者对表示日志记录事件的 @ref{9f5,,LogRecord} 的构造有更好的控制。


请参阅 @ref{2241,,setLogRecordFactory()} 了解有关如何调用该工厂方法的更多信息。
@end deffn

@geindex debug() (在 logging 模块中)
@anchor{library/logging logging debug}@anchor{220f}
@deffn {函数} logging.debug (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{DEBUG} 级别的消息。 @emph{msg} 是消息格式字符串，而 @emph{args} 是要使用字符串格式化运算符合并到 @emph{msg} 的参数。 （请注意这意味着你可以在格式字符串中使用关键字以及单个字典参数。）

在 @emph{kwargs} 中有三个关键字参数会被检查: @emph{exc_info} 参数如果不为假值则会将异常信息添加到日志记录消息。 如果提供了异常元组（为 @ref{d2f,,sys.exc_info()} 的返回值格式）或异常实例则它会被使用；在其他情况下，会调用 @ref{d2f,,sys.exc_info()} 以获取异常信息。

第二个可选关键字参数是 @emph{stack_info}，默认为 @code{False}。如果为  True，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意，这与通过指定 @emph{exc_info} 显示的堆栈信息不同：前者是从堆栈底部到当前线程中的日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，跟踪异常而打开的堆栈帧的信息。

您可以独立于 @emph{exc_info} 来指定 @emph{stack_info}，例如，即使在未引发任何异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题行之后打印：

@example
Stack (most recent call last):
@end example

这模仿了显示异常帧时所使用的 @code{Traceback (most recent call last):} 。

第三个可选关键字参数是 @emph{extra}，它可被用来传递一个字典，该字典会被用来填充为日志记录事件创建并附带用户自定义属性的 LogRecord 的 __dict__。 之后将可按你的需要使用这些自定义属性。 例如，可以将它们合并到已记录的消息中。 举例来说:

@example
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = @{'clientip': '192.168.0.1', 'user': 'fbloggs'@}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
@end example

应当会打印出这样的内容:

@example
2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
@end example

@emph{extra} 中传入的字典的键不应与日志系统使用的键冲突。（有关日志系统使用哪些键的更多信息，请参见 @ref{220c,,Formatter} 的文档。）

如果你选择在已记录的消息中使用这些属性，则需要格外小心。 例如在上面的示例中，@ref{220c,,Formatter} 已设置了格式字符串，其在 LogRecord 的属性字典中应有 'clientip' 和 'user'。 如果缺少这些属性，消息将不被记录，因为会引发字符串格式化异常，你始终需要传入带有这些键的 @emph{extra} 字典。

尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执行相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如在上面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下，很可能将专门的 @ref{220c,,Formatter} 与特定的 @ref{220d,,Handler} 一起使用。


在 3.2 版更改: 增加了 @emph{stack_info} 参数。

@end deffn

@geindex info() (在 logging 模块中)
@anchor{library/logging logging info}@anchor{223a}
@deffn {函数} logging.info (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{INFO} 级别的消息。 参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex warning() (在 logging 模块中)
@anchor{library/logging logging warning}@anchor{224c}
@deffn {函数} logging.warning (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{WARNING} 级别的消息。 参数解释同 @ref{220f,,debug()}。

@cartouche
@quotation 注解 
有一个已过时方法 @code{warn} 其功能与 @code{warning} 一致。 由于 @code{warn} 已被弃用，请不要使用它 —— 而是改用 @code{warning}。
@end quotation
@end cartouche
@end deffn

@geindex error() (在 logging 模块中)
@anchor{library/logging logging error}@anchor{224d}
@deffn {函数} logging.error (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{ERROR} 级别的消息。 参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex critical() (在 logging 模块中)
@anchor{library/logging logging critical}@anchor{224e}
@deffn {函数} logging.critical (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{CRITICAL} 级别的消息。 参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex exception() (在 logging 模块中)
@anchor{library/logging logging exception}@anchor{224f}
@deffn {函数} logging.exception (msg, *args, **kwargs)

在根日志记录器上记录一条 @code{ERROR} 级别的消息。 参数解释同 @ref{220f,,debug()}。 异常信息将被添加到日志消息中。 此函数应当仅从异常处理程序中调用。
@end deffn

@geindex log() (在 logging 模块中)
@anchor{library/logging logging log}@anchor{2250}
@deffn {函数} logging.log (level, msg, *args, **kwargs)

在根日志记录器上记录一条 @emph{level} 级别的消息。 其他参数解释同 @ref{220f,,debug()}。
@end deffn

@geindex disable() (在 logging 模块中)
@anchor{library/logging logging disable}@anchor{1017}
@deffn {函数} logging.disable (level=CRITICAL)

为所有日志记录器提供重载的级别 @emph{level}，其优先级高于日志记录器自己的级别。 当需要临时限制整个应用程序中的日志记录输出时，此功能会很有用。 它的效果是禁用所有重要程度为 @emph{level} 及以下的日志记录调用，因此如果你附带 INFO 值调用它，则所有 INFO 和 DEBUG 事件就会被丢弃，而重要程度为 WARNING 以及上的事件将根据日志记录器的当前有效级别来处理。 如果 @code{logging.disable(logging.NOTSET)} 被调用，它将移除这个重载的级别，因此日志记录输出会再次取决于单个日志记录器的有效级别。

请注意如果你定义了任何高于 @code{CRITICAL} 的自定义日志级别（并不建议这样做），你就将无法沿用 @emph{level} 形参的默认值，而必须显式地提供适当的值。


在 3.7 版更改: @emph{level} 形参默认级别为 @code{CRITICAL}。 请参阅 bpo-28524@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=28524} 了解此项改变的更多细节。

@end deffn

@geindex addLevelName() (在 logging 模块中)
@anchor{library/logging logging addLevelName}@anchor{2251}
@deffn {函数} logging.addLevelName (level, levelName)

在一个内部字典中关联级别 @emph{level} 与文本 @emph{levelName}，该字典会被用来将数字级别映射为文本表示形式，例如在 @ref{220c,,Formatter} 格式化消息的时候。 此函数也可被用来定义你自己的级别。 唯一的限制是自定义的所有级别必须使用此函数来注册，级别值必须为正整数并且其应随严重程度而递增。

@cartouche
@quotation 注解 
如果你考虑要定义你自己的级别，请参阅 @ref{2252,,自定义级别} 部分。
@end quotation
@end cartouche
@end deffn

@geindex getLevelName() (在 logging 模块中)
@anchor{library/logging logging getLevelName}@anchor{2253}
@deffn {函数} logging.getLevelName (level)

返回日志记录级别 @emph{level} 的字符串表示。

如果 @emph{level} 为预定义的级别 @code{CRITICAL}, @code{ERROR}, @code{WARNING}, @code{INFO} 或 @code{DEBUG} 之一则你会得到相应的字符串。 如果你使用 @ref{2251,,addLevelName()} 将级别关联到名称则返回你为 @emph{level} 所关联的名称。 如果传入了与已定义级别相对应的数字值，则返回对应的字符串表示。

@emph{level} 形参也接受级别的字符串表示例如 'INFO'。 在这种情况下，此函数将返回级别所对应的数字值。

如果未传入可匹配的数字或字符串值，则返回字符串 'Level %s' % level。

@cartouche
@quotation 注解 
级别在内部以整数表示（因为它们在日志记录逻辑中需要进行比较）。 此函数被用于在整数级别与通过 @code{%(levelname)s} 格式描述符方式在格式化日志输出中显示的级别名称之间进行相互的转换 (参见 @ref{2230,,LogRecord 属性})。
@end quotation
@end cartouche


在 3.4 版更改: 在早于 3.4 的 Python 版本中，此函数也可传入一个字符串形式的级别名称，并将返回对应的级别数字值。 此未记入文档的行为被视为是一个错误，并在 Python 3.4 中被移除，但又在 3.4.2 中被恢复以保持向下兼容性。

@end deffn

@geindex makeLogRecord() (在 logging 模块中)
@anchor{library/logging logging makeLogRecord}@anchor{223e}
@deffn {函数} logging.makeLogRecord (attrdict)

创建并返回一个新的 @ref{9f5,,LogRecord} 实例，实例属性由 @emph{attrdict} 定义。 此函数适用于接受一个通过套接字传输的封存好的 @ref{9f5,,LogRecord} 属性字典，并在接收端将其重建为一个 @ref{9f5,,LogRecord} 实例。
@end deffn

@geindex basicConfig() (在 logging 模块中)
@anchor{library/logging logging basicConfig}@anchor{318}
@deffn {函数} logging.basicConfig (**kwargs)

通过使用默认的 @ref{220c,,Formatter} 创建一个 @ref{c4f,,StreamHandler} 并将其加入根日志记录器来为日志记录系统执行基本配置。 如果没有为根日志记录器定义处理器则 @ref{220f,,debug()}, @ref{223a,,info()}, @ref{224c,,warning()}, @ref{224d,,error()} 和 @ref{224e,,critical()} 等函数将自动调用 @ref{318,,basicConfig()}。

如果根日志记录器已配置了处理器则此函数将不执行任何操作，除非关键字参数 @emph{force} 被设为 @code{True}。

@cartouche
@quotation 注解 
此函数应当在其他线程启动之前从主线程被调用。 在 2.7.1 和 3.2 之前的 Python 版本中，如果此函数从多个线程被调用，一个处理器（在极少的情况下）有可能被多次加入根日志记录器，导致非预期的结果例如日志中的消息出现重复。
@end quotation
@end cartouche

支持以下关键字参数。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

格式

@tab

描述

@item

@emph{filename}

@tab

使用指定的文件名而不是 StreamHandler 创建 FileHandler。

@item

@emph{filemode}

@tab

如果指定了 @emph{filename}，则用此 @ref{175c,,模式} 打开该文件。 默认模式为 @code{'a'}。

@item

@emph{format}

@tab

使用指定的格式字符串作为处理器。 默认为属性以冒号分隔的 @code{levelname}, @code{name} 和 @code{message}。

@item

@emph{datefmt}

@tab

使用指定的日期/时间格式，与 @ref{c40,,time.strftime()} 所接受的格式相同。

@item

@emph{style}

@tab

如果指定了 @emph{format}，将为格式字符串使用此风格。 @code{'%'}, @code{'@{'} 或 @code{'$'} 分别对应于 @ref{1388,,printf 风格}, @ref{5dd,,str.format()} 或 @ref{4f9,,string.Template}。 默认为 @code{'%'}。

@item

@emph{level}

@tab

设置根记录器级别去指定 @ref{2209,,level}.

@item

@emph{stream}

@tab

使用指定的流初始化 StreamHandler。 请注意此参数与 @emph{filename} 是不兼容的 - 如果两者同时存在，则会引发 @code{ValueError}。

@item

@emph{handlers}

@tab

如果指定，这应为一个包含要加入根日志记录器的已创建处理器的可迭代对象。 任何尚未设置格式描述符的处理器将被设置为在此函数中创建的默认格式描述符。 请注意此参数与 @emph{filename} 或 @emph{stream} 不兼容 —— 如果两者同时存在，则会引发 @code{ValueError}。

@item

@emph{force}

@tab

如果将此关键字参数指定为 true，则在执行其他参数指定的配置之前，将移除并关闭附加到根记录器的所有现有处理器。

@item

@emph{encoding}

@tab

如果此关键字参数与 @emph{filename} 一同被指定，则该值会在创建 FileHandler 时被使用，因而也会在打开输出文件时被使用。

@item

@emph{errors}

@tab

如果此关键字参数与 @emph{filename} 一同被指定，则该值会在创建 FileHandler 时被使用，因而也会在打开输出文件时被使用。 如果未指定，则会使用值 'backslashreplace'。 请注意如果指定为 @code{None}，它将被原样传给 func:@cite{open}，这意味着将会与传入 'errors' 一样处理。

@end multitable



在 3.2 版更改: 增加了 @emph{style} 参数。



在 3.3 版更改: 增加了 @emph{handlers} 参数。 增加了额外的检查来捕获指定不兼容参数的情况 (例如同时指定 @emph{handlers} 与 @emph{stream}  或 @emph{filename}，或者同时指定 @emph{stream} 与 @emph{filename})。



在 3.8 版更改: 增加了 @emph{force} 参数。



在 3.9 版更改: 增加了 @emph{encoding} 和 @emph{errors} 参数。

@end deffn

@geindex shutdown() (在 logging 模块中)
@anchor{library/logging logging shutdown}@anchor{2229}
@deffn {函数} logging.shutdown ()

通过刷新和关闭所有处理程序来通知日志记录系统执行有序停止。 此函数应当在应用退出时被调用并且在此调用之后不应再使用日志记录系统。

当 logging 模块被导入时，它会将此函数注册为退出处理程序 (参见 @ref{b,,atexit})，因此通常不需要手动执行该操作。
@end deffn

@geindex setLoggerClass() (在 logging 模块中)
@anchor{library/logging logging setLoggerClass}@anchor{224b}
@deffn {函数} logging.setLoggerClass (klass)

通知日志记录系统在实例化日志记录器时使用 @emph{klass} 类。 该类应当定义 @ref{e2b,,__init__()} 使其只要求一个 name 参数，并且 @ref{e2b,,__init__()} 应当调用 @code{Logger.__init__()}。 此函数通常会在需要使用自定义日志记录器行为的应用程序实例化任何日志记录器之前被调用。 在此调用之后，在任何其他时刻都不要使用该子类来直接实例化日志记录器：请继续使用 @ref{235,,logging.getLogger()} API 来获取你的日志记录器。
@end deffn

@geindex setLogRecordFactory() (在 logging 模块中)
@anchor{library/logging logging setLogRecordFactory}@anchor{2241}
@deffn {函数} logging.setLogRecordFactory (factory)

设置一个用来创建 @ref{9f5,,LogRecord} 的可调用对象。

@*参数: 
@code{factory} -- 用来实例化日志记录的工厂可调用对象。



3.2 新版功能: 此函数与 @ref{2240,,getLogRecordFactory()} 一起提供，以便允许开发者对如何构造表示日志记录事件的 @ref{9f5,,LogRecord} 有更好的控制。


可调用对象 factory 具有如下签名:

@code{factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)}

@quotation

@*name: 
日志记录器名称


@*level: 
日志记录级别（数字）。


@*fn: 
进行日志记录调用的文件的完整路径名。


@*lno: 
记录调用所在文件中的行号。


@*msg: 
日志消息。


@*args: 
日志记录消息的参数。


@*exc_info: 
异常元组，或 @code{None} 。


@*func: 
调用日志记录调用的函数或方法的名称。


@*sinfo: 
与 @ref{873,,traceback.print_stack()} 所提供的类似的栈回溯信息，显示调用的层级结构。


@*kwargs: 
其他关键字参数。

@end quotation
@end deffn

@node 模块级属性,与警告模块集成,模块级函数,logging --- Python 的日志记录工具
@anchor{library/logging module-level-attributes}@anchor{2254}
@subsubsection 模块级属性


@geindex lastResort() (在 logging 模块中)
@anchor{library/logging logging lastResort}@anchor{c50}
@deffn {属性} logging.lastResort

通过此属性提供的“最后处理者”。 这是一个以 @code{WARNING} 级别写入到 @code{sys.stderr} 的 @ref{c4f,,StreamHandler}，用于在没有任何日志记录配置的情况下处理日志记录事件。 最终结果就是将消息打印到 @code{sys.stderr}，这会替代先前形式为 "no handlers could be found for logger XYZ" 的错误消息。 如果出于某种原因你需要先前的行为，可将 @code{lastResort} 设为 @code{None}。


3.2 新版功能.

@end deffn

@node 与警告模块集成,,模块级属性,logging --- Python 的日志记录工具
@anchor{library/logging integration-with-the-warnings-module}@anchor{2255}
@subsubsection 与警告模块集成


@ref{2256,,captureWarnings()} 函数可用来将 @ref{aa,,logging} 和 @ref{12f,,warnings} 模块集成。

@geindex captureWarnings() (在 logging 模块中)
@anchor{library/logging logging captureWarnings}@anchor{2256}
@deffn {函数} logging.captureWarnings (capture)

此函数用于打开和关闭日志系统对警告的捕获。

如果 @emph{capture} 是 @code{True}，则 @ref{12f,,warnings} 模块发出的警告将重定向到日志记录系统。具体来说，将使用 @ref{1176,,warnings.formatwarning()} 格式化警告信息，并将结果字符串使用 @code{WARNING} 等级记录到名为 @code{'py.warnings'} 的记录器中。

如果 @emph{capture} 是 @code{False}，则将停止将警告重定向到日志记录系统，并且将警告重定向到其原始目标（即在  @code{captureWarnings(True)}  调用之前的有效目标）。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{ab,,logging.config} 模块

日志记录模块的配置 API 。

@item @ref{ac,,logging.handlers} 模块

日志记录模块附带的有用处理器。

@geindex Python 提高建议; PEP 282

@item PEP 282@footnote{https://www.python.org/dev/peps/pep-0282} - Logging 系统

该提案描述了Python标准库中包含的这个特性。

@item Original Python logging package@footnote{https://old.red-dove.com/python_logging.html}

这是该 @ref{aa,,logging} 包的原始来源。该站点提供的软件包版本适用于 Python 1.5.2、2.1.x 和 2.2.x，它们不被 @ref{aa,,logging} 包含在标准库中。
@end table


@node logging config --- 日志记录配置,logging handlers --- 日志处理程序,logging --- Python 的日志记录工具,通用操作系统服务
@anchor{library/logging config doc}@anchor{2257}@anchor{library/logging config logging-config-logging-configuration}@anchor{2258}@anchor{library/logging config module-logging config}@anchor{ab}
@subsection @code{logging.config} --- 日志记录配置


@geindex logging.config (模块)

@strong{源代码：} Lib/logging/config.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/logging/config.py}

@subsubheading Important



此页面仅包含参考信息。有关教程，请参阅


@itemize *

@item 
@ref{c4c,,基础教程}

@item 
@ref{c4d,,进阶教程}

@item 
@ref{c4e,,日志操作手册}
@end itemize


__________________________________________________________________


这一节描述了用于配置 logging 模块的 API。

@menu
* 配置函数:: 
* 安全考量:: 
* 配置字典架构:: 
* 配置文件格式:: 

@end menu

@node 配置函数,安全考量,,logging config --- 日志记录配置
@anchor{library/logging config configuration-functions}@anchor{2259}@anchor{library/logging config logging-config-api}@anchor{d58}
@subsubsection 配置函数


下列函数可配置 logging 模块。 它们位于 @ref{ab,,logging.config} 模块中。 它们的使用是可选的 --- 要配置 logging 模块你可以使用这些函数，也可以通过调用主 API (在 @ref{aa,,logging} 本身定义) 并定义在 @ref{aa,,logging} 或 @ref{ac,,logging.handlers} 中声明的处理程序。

@geindex dictConfig() (在 logging.config 模块中)
@anchor{library/logging config logging config dictConfig}@anchor{c07}
@deffn {函数} logging.config.dictConfig (config)

从一个字典获取日志记录配置。 字典的内容描述见下文的 @ref{225a,,配置字典架构}。

如果在配置期间遇到错误，此函数将引发 @ref{16d,,ValueError}, @ref{1ff,,TypeError}, @ref{4aa,,AttributeError} 或 @ref{16c,,ImportError} 并附带适当的描述性消息。 下面是将会引发错误的（可能不完整的）条件列表:


@itemize *

@item 
@code{level} 不是字符串或者不是对应于实际日志记录级别的字符串。

@item 
@code{propagate} 值不是布尔类型。

@item 
id 没有对应的目标。

@item 
在增量调用期间发现不存在的处理程序 id。

@item 
无效的日志记录器名称。

@item 
无法解析为内部或外部对象。
@end itemize

解析由 @code{DictConfigurator} 类执行，该类的构造器可传入用于配置的字典，并且具有 @code{configure()} 方法。 @ref{ab,,logging.config} 模块具有可调用属性 @code{dictConfigClass}，其初始值设为 @code{DictConfigurator}。 你可以使用你自己的适当实现来替换 @code{dictConfigClass} 的值。

@ref{c07,,dictConfig()} 会调用 @code{dictConfigClass} 并传入指定的字典，然后在所返回的对象上调用 @code{configure()} 方法以使配置生效:

@example
def dictConfig(config):
    dictConfigClass(config).configure()
@end example

例如，@code{DictConfigurator} 的子类可以在它自己的 @ref{e2b,,__init__()} 中调用 @code{DictConfigurator.__init__()}，然后设置可以在后续 @code{configure()} 调用中使用的自定义前缀。 @code{dictConfigClass} 将被绑定到这个新的子类，然后就可以与在默认的未定制状态下完全相同的方式调用 @ref{c07,,dictConfig()}。


3.2 新版功能.

@end deffn

@geindex fileConfig() (在 logging.config 模块中)
@anchor{library/logging config logging config fileConfig}@anchor{4b8}
@deffn {函数} logging.config.fileConfig (fname, defaults=None, disable_existing_loggers=True)

从一个 @ref{22,,configparser} 格式文件中读取日志记录配置。 文件格式应当与 @ref{225b,,配置文件格式} 中的描述一致。 此函数可在应用程序中被多次调用，以允许最终用户在多个预设配置中进行选择（如果开发者提供了展示选项并加载选定配置的机制）。

@*参数: 

@itemize *

@item 
@code{fname} -- 一个文件名，或一个文件类对象，或是一个派生自 @ref{965,,RawConfigParser} 的实例。 如果传入了一个派生自 @code{RawConfigParser} 的实例，它会被原样使用。 否则，将会实例化一个 @code{Configparser}，并且它会从作为 @code{fname} 传入的对象中读取配置。 如果存在 @ref{de,,readline()} 方法，则它会被当作一个文件类对象并使用 @ref{2014,,read_file()} 来读取；在其它情况下，它会被当作一个文件名并传递给 @ref{1221,,read()}。

@item 
@code{defaults} -- 要传递给 ConfigParser 的默认值可在此参数中指定。

@item 
@code{disable_existing_loggers} -- 如果指定为 @code{False}，则当执行此调用时已存在的日志记录器会保持启用。 默认值为 @code{True} 因为这将以向下兼容方式启用旧行为。 此行为是禁用任何现有的非根日志记录器除非它们或它们的上级在日志记录配置中被显式地命名。
@end itemize



在 3.4 版更改: 现在接受 @ref{965,,RawConfigParser} 子类的实例作为 @code{fname} 的值。 这有助于:


@itemize *

@item 
使用一个配置文件，其中日志记录配置只是全部应用程序配置的一部分。

@item 
使用从一个文件读取的配置，它随后会在被传给 @code{fileConfig} 之前由使用配置的应用程序来修改（例如基于命令行参数或运行时环境的其他部分）。
@end itemize

@end deffn

@geindex listen() (在 logging.config 模块中)
@anchor{library/logging config logging config listen}@anchor{966}
@deffn {函数} logging.config.listen (port=DEFAULT_LOGGING_CONFIG_PORT, verify=None)

在指定的端口上启动套接字服务器，并监听新的配置。 如果未指定端口，则会使用模块默认的 @code{DEFAULT_LOGGING_CONFIG_PORT}。 日志记录配置将作为适合由 @ref{c07,,dictConfig()} 或 @ref{4b8,,fileConfig()} 进行处理的文件来发送。 返回一个 @ref{21b,,Thread} 实例，你可以在该实例上调用 @ref{225c,,start()} 来启动服务器，对该服务器你可以在适当的时候执行 @ref{c3b,,join()}。 要停止该服务器，请调用 @ref{225d,,stopListening()}。

如果指定 @code{verify} 参数，则它应当是一个可调用对象，该对象应当验证通过套接字接收的字节数据是否有效且应被处理。 这可以通过对通过套接字发送的内容进行加密和/或签名来完成，这样 @code{verify} 可调用对象就能执行签名验证和/或解密。 @code{verify} 可调用对象的调用会附带一个参数 —— 通过套接字接收的字节数据 —— 并应当返回要处理的字节数据，或者返回 @code{None} 来指明这些字节数据应当被丢弃。 返回的字节数据可以与传入的字节数据相同（例如在只执行验证的时候），或者也可以完全不同（例如在可能执行了解密的时候）。

要将配置发送到套接字，请读取配置文件并将其作为字节序列发送到套接字，字节序列要以使用 @code{struct.pack('>L', n)} 打包为二进制格式的四字节长度的字符串打头。
@anchor{library/logging config logging-eval-security}@anchor{225e}
@cartouche
@quotation 注解 
因为配置的各部分是通过 @ref{c6a,,eval()} 传递的，使用此函数可能让用户面临安全风险。虽然此函数仅绑定到 @code{localhost} 上的套接字，因此并不接受来自远端机器的连接，但在某些场景中不受信任的代码可以在调用 @ref{966,,listen()} 的进程的账户下运行。具体来说，如果如果调用 @ref{966,,listen()} 的进程在用户无法彼此信任的多用户机器上运行，则恶意用户就能简单地通过连接到受害者的 @ref{966,,listen()} 套接字并发送运行攻击者想在受害者的进程上执行的任何代码的配置的方式，安排运行几乎任意的代码。如果是使用默认端口这会特别容易做到，即便使用了不同端口也不难做到。要避免发生这种情况的风险，请在 @ref{966,,listen()} 中使用 @code{verify} 参数来防止未经认可的配置被应用。
@end quotation
@end cartouche


在 3.4 版更改: 添加了 @code{verify} 参数。


@cartouche
@quotation 注解 
如果你希望将配置发送给未禁用现有日志记录器的监听器，你将需要使用 JSON 格式的配置，该格式将使用 @ref{c07,,dictConfig()} 进行配置。 此方法允许你在你发送的配置中将 @code{disable_existing_loggers} 指定为 @code{False}。
@end quotation
@end cartouche
@end deffn

@geindex stopListening() (在 logging.config 模块中)
@anchor{library/logging config logging config stopListening}@anchor{225d}
@deffn {函数} logging.config.stopListening ()

停止通过对 @ref{966,,listen()} 的调用所创建的监听服务器。 此函数的调用通常会先于在 @ref{966,,listen()} 的返回值上调用 @code{join()}。
@end deffn

@node 安全考量,配置字典架构,配置函数,logging config --- 日志记录配置
@anchor{library/logging config security-considerations}@anchor{225f}
@subsubsection 安全考量


日志配置功能试图提供便利，从某种角度来说，这是通过将配置文件中的文本转换为日志配置中使用的 Python 对象来完成的 —— 如 @ref{2260,,用户定义对象} 中所述。但是，这些相同的机制（从用户定义的模块中导入可调用对象并使用配置中的参数调用它们）可用于调用您指定的任何代码，因此您应该*非常谨慎*地处理来自非信任源的配置文件。并且在实际加载前，您应该确信加载不会导致坏事情。

@node 配置字典架构,配置文件格式,安全考量,logging config --- 日志记录配置
@anchor{library/logging config configuration-dictionary-schema}@anchor{2261}@anchor{library/logging config logging-config-dictschema}@anchor{225a}
@subsubsection 配置字典架构


描述日志记录配置需要列出要创建的不同对象及它们之间的连接；例如，你可以创建一个名为 'console' 的处理程序，然后名为 'startup' 的日志记录器将可以把它的消息发送给 'console' 处理程序。 这些对象并不仅限于 @ref{aa,,logging} 模块所提供的对象，因为你还可以编写你自己的格式化或处理程序类。 这些类的形参可能还需要包括 @code{sys.stderr} 这样的外部对象。 描述这些对象和连接的语法会在下面的 @ref{2262,,对象连接} 中定义。

@menu
* 字典架构细节:: 
* 增量配置:: 
* 对象连接:: 
* 用户定义对象:: 
* 访问外部对象:: 
* 访问内部对象:: 
* 导入解析与定制导入器:: 

@end menu

@node 字典架构细节,增量配置,,配置字典架构
@anchor{library/logging config dictionary-schema-details}@anchor{2263}
@subsubsection 字典架构细节


传给 @ref{c07,,dictConfig()} 的字典必须包含以下的键:


@itemize *

@item 
@emph{version} - 应设为代表架构版本的整数值。 目前唯一有效的值是 1，使用此键可允许架构在继续演化的同时保持向下兼容性。
@end itemize

所有其他键都是可选项，但如存在它们将根据下面的描述来解读。 在下面提到 'configuring dict' 的所有情况下，都将检查它的特殊键 @code{'()'} 以确定是否需要自定义实例化。 如果需要，则会使用下面 @ref{2260,,用户定义对象} 所描述的机制来创建一个实例；否则，会使用上下文来确定要实例化的对象。


@itemize *

@item 
@emph{formatters} - 对应的值将是一个字典，其中每个键是一个格式器 ID 而每个值则是一个描述如何配置相应 @ref{220c,,Formatter} 实例的字典。

将在配置字典中搜索键 @code{format} 和 @code{datefmt} (默认值均为 @code{None}) 并且这些键会被用于构造 @ref{220c,,Formatter} 实例。


在 3.8 版更改: 一个 @code{validate} 键 (默认值为 @code{True}) 可被添加到配置字典的 @code{formatters} 部分，这会被用来验证格式的有效性。


@item 
@emph{filters} - 对应的值将是一个字典，其中每个键是一个过滤器 ID 而每个值则是一个描述如何配置相应 Filter 实例的字典。

将在配置字典中搜索键 @code{name} (默认值为空字符串) 并且该键会被用于构造 @ref{c51,,logging.Filter} 实例。

@item 
@emph{handlers} - 对应的值将是一个字典，其中每个键是一个处理程序 ID 而每个值则是一个描述如何配置相应 Handler 实例的字典。

将在配置字典中搜索下列键:


@itemize *

@item 
@code{class} (强制)。 这是处理程序类的完整限定名称。

@item 
@code{level} (可选)。 处理程序的级别。

@item 
@code{formatter} (可选)。 处理程序所对应格式化器的 ID。

@item 
@code{filters} (可选)。 由处理程序所对应过滤器的 ID 组成的列表。
@end itemize

所有 @emph{其他} 键会被作为关键字参数传递给处理程序类的构造器。 例如，给定如下配置:

@example
handlers:
  console:
    class : logging.StreamHandler
    formatter: brief
    level   : INFO
    filters: [allow_foo]
    stream  : ext://sys.stdout
  file:
    class : logging.handlers.RotatingFileHandler
    formatter: precise
    filename: logconfig.log
    maxBytes: 1024
    backupCount: 3
@end example

ID 为 @code{console} 的处理程序会被实例化为 @ref{c4f,,logging.StreamHandler}，并使用 @code{sys.stdout} 作为下层流。 ID 为 @code{file} 的处理程序会被实例化为 @ref{2264,,logging.handlers.RotatingFileHandler}，并附带关键字参数 @code{filename='logconfig.log', maxBytes=1024, backupCount=3}。

@item 
@emph{loggers} - 对应的值将是一个字典，其中每个键是一个日志记录器名称而每个值则是一个描述如何配置相应 Logger 实例的字典。

将在配置字典中搜索下列键:


@itemize *

@item 
@code{level} (可选)。 日志记录器的级别。

@item 
@code{propagate} (可选)。 日志记录器的传播设置。

@item 
@code{filters} (可选)。 由日志记录器对应过滤器的 ID 组成的列表。

@item 
@code{handlers} (可选)。 由日志记录器对应处理程序的 ID 组成的列表。
@end itemize

指定的日志记录器将根据指定的级别、传播、过滤器和处理程序来配置。

@item 
@emph{root} - 这将成为根日志记录器对应的配置。 配置的处理方式将与所有日志记录器一致，除了 @code{propagate} 设置将不可用之外。

@item 
@emph{incremental} - 配置是否要被解读为在现有配置上新增。 该值默认为 @code{False}，这意味着指定的配置将以与当前 @ref{4b8,,fileConfig()} API 所使用的相同语义来替代现有的配置。

如果指定的值为 @code{True}，配置会按照 @ref{2265,,增量配置} 部分所描述的方式来处理。

@item 
@emph{disable_existing_loggers} - 是否要禁用任何现有的非根日志记录器。 该设置对应于 @ref{4b8,,fileConfig()} 中的同名形参。 如果省略，则此形参默认为 @code{True}。 如果 @emph{incremental} 为 @code{True} 则该省会被忽略。
@end itemize

@node 增量配置,对象连接,字典架构细节,配置字典架构
@anchor{library/logging config incremental-configuration}@anchor{2266}@anchor{library/logging config logging-config-dict-incremental}@anchor{2265}
@subsubsection 增量配置


为增量配置提供完全的灵活性是很困难的。 例如，由于过滤器和格式化器这样的对象是匿名的，一旦完成配置，在增加配置时就不可能引用这些匿名对象。

此外，一旦完成了配置，在运行时任意改变日志记录器、处理程序、过滤器、格式化器的对象图就不是很有必要；日志记录器和处理程序的详细程度只需通过设置级别即可实现控制（对于日志记录器则可设置传播旗标）。 在多线程环境中以安全的方式任意改变对象图也许会导致问题；虽然并非不可能，但这样做的好处不足以抵销其所增加的实现复杂度。

这样，当配置字典的 @code{incremental} 键存在且为 @code{True} 时，系统将完全忽略任何 @code{formatters} 和 @code{filters} 条目，并仅会处理 @code{handlers} 条目中的 @code{level} 设置，以及 @code{loggers} 和 @code{root} 条目中的 @code{level} 和 @code{propagate} 设置。

使用配置字典中的值可让配置以封存字典对象的形式通过线路传送给套接字监听器。 这样，长时间运行的应用程序的日志记录的详细程度可随时间改变而无须停止并重新启动应用程序。

@node 对象连接,用户定义对象,增量配置,配置字典架构
@anchor{library/logging config logging-config-dict-connections}@anchor{2262}@anchor{library/logging config object-connections}@anchor{2267}
@subsubsection 对象连接


该架构描述了一组日志记录对象 —— 日志记录器、处理程序、格式化器、过滤器 —— 它们在对象图中彼此连接。 因此，该架构需要能表示对象之间的连接。 例如，在配置完成后，一个特定的日志记录器关联到了一个特定的处理程序。 出于讨论的目的，我们可以说该日志记录器代表两者间连接的源头，而处理程序则代表对应的目标。 当然在已配置对象中这是由包含对处理程序的引用的日志记录器来代表的。 在配置字典中，这是通过给每个目标对象一个 ID 来无歧义地标识它，然后在源头对象中使用该 ID 来实现的。

因此，举例来说，考虑以下 YAML 代码段:

@example
formatters:
  brief:
    # configuration for formatter with id 'brief' goes here
  precise:
    # configuration for formatter with id 'precise' goes here
handlers:
  h1: #This is an id
   # configuration of handler with id 'h1' goes here
   formatter: brief
  h2: #This is another id
   # configuration of handler with id 'h2' goes here
   formatter: precise
loggers:
  foo.bar.baz:
    # other configuration for logger 'foo.bar.baz'
    handlers: [h1, h2]
@end example

（注：这里使用 YAML 是因为它的可读性比表示字典的等价 Python 源码形式更好。）

日志记录器 ID 就是日志记录器的名称，它会在程序中被用来获取对日志记录器的引用，例如 @code{foo.bar.baz}。 格式化器和过滤器的 ID 可以是任意字符串值 (例如上面的 @code{brief}, @code{precise}) 并且它们是瞬态的，因为它们仅对处理配置字典有意义并会被用来确定对象之间的连接，而当配置调用完成时不会在任何地方保留。

上面的代码片段指明名为 @code{foo.bar.baz} 的日志记录器应当关联到两个处理程序，它们的 ID 是 @code{h1} 和 @code{h2}。 @code{h1} 的格式化器的 ID 是 @code{brief}，而 @code{h2} 的格式化器的 ID 是 @code{precise}。

@node 用户定义对象,访问外部对象,对象连接,配置字典架构
@anchor{library/logging config logging-config-dict-userdef}@anchor{2260}@anchor{library/logging config user-defined-objects}@anchor{2268}
@subsubsection 用户定义对象


此架构支持用户定义对象作为处理程序、过滤器和格式化器。 （日志记录器的不同实例不需要具有不同类型，因此这个配置架构并不支持用户定义日志记录器类。）

要配置的对象是由字典描述的，其中包含它们的配置详情。 在某些地方，日志记录系统将能够从上下文中推断出如何实例化一个对象，但是当要实例化一个用户自定义对象时，系统将不知道要如何做。 为了提供用户自定义对象实例化的完全灵活性，用户需要提供一个‘工厂’函数 —— 即在调用时传入配置字典并返回实例化对象的可调用对象。 这是用一个通过特殊键 @code{'()'} 来访问的工厂函数的绝对导入路径来标示的。 下面是一个实际的例子:

@example
formatters:
  brief:
    format: '%(message)s'
  default:
    format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
    datefmt: '%Y-%m-%d %H:%M:%S'
  custom:
      (): my.package.customFormatterFactory
      bar: baz
      spam: 99.9
      answer: 42
@end example

上面的 YAML 代码片段定义了三个格式化器。 第一个的 ID 为 @code{brief}，是带有特殊格式字符串的标准 @ref{220c,,logging.Formatter} 实例。 第二个的 ID 为 @code{default}，具有更长的格式同时还显式地定义了时间格式，并将最终实例化一个带有这两个格式字符串的 @ref{220c,,logging.Formatter}。 以 Python 源代码形式显示的 @code{brief} 和 @code{default} 格式化器分别具有下列配置子字典:

@example
@{
  'format' : '%(message)s'
@}
@end example

和:

@example
@{
  'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
  'datefmt' : '%Y-%m-%d %H:%M:%S'
@}
@end example

并且由于这些字典不包含特殊键 @code{'()'}，实例化方式是从上下文中推断出来的：结果会创建标准的 @ref{220c,,logging.Formatter} 实例。 第三个格式器的 ID 为 @code{custom}，对应配置子字典为:

@example
@{
  '()' : 'my.package.customFormatterFactory',
  'bar' : 'baz',
  'spam' : 99.9,
  'answer' : 42
@}
@end example

并且它包含特殊键 @code{'()'}，这意味着需要用户自定义实例化方式。 在此情况下，将使用指定的工厂可调用对象。 如果它本身就是一个可调用对象则将被直接使用 —— 否则如果你指定了一个字符串（如这个例子所示）则将使用正常的导入机制来定位实例的可调用对象。 调用该可调用对象将传入配置子字典中 @strong{剩余的} 条目作为关键字参数。 在上面的例子中，调用将预期返回 ID 为 @code{custom} 的格式化器:

@example
my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
@end example

将 @code{'()'} 用作特殊键是因为它不是一个有效的关键字形参名称，这样就不会与调用中使用的关键字参数发生冲突。 @code{'()'} 还被用作表明对应值为可调用对象的助记符。

@node 访问外部对象,访问内部对象,用户定义对象,配置字典架构
@anchor{library/logging config access-to-external-objects}@anchor{2269}@anchor{library/logging config logging-config-dict-externalobj}@anchor{226a}
@subsubsection 访问外部对象


有时一个配置需要引用配置以外的对象，例如 @code{sys.stderr}。 如果配置字典是使用 Python 代码构造的，这会很直观，但是当配置是通过文本文件（例如 JSON, YAML）提供的时候就会引发问题。 在一个文本文件中，没有将 @code{sys.stderr} 与字符串字面值 @code{'sys.stderr'} 区分开来的标准方式。  为了实现这种区分，配置系统会在字符串值中查找规定的特殊前缀并对其做特殊处理。 例如，如果在配置中将字符串字面值 @code{'ext://sys.stderr'} 作为一个值来提供，则 @code{ext://} 将被去除而该值的剩余部分将使用正常导入机制来处理。

此类前缀的处理方式类似于协议处理：存在一种通用机制来查找与正则表达式 @code{^(?P<prefix>[a-z]+)://(?P<suffix>.*)$} 相匹配的前缀，如果识别出了 @code{prefix}，则 @code{suffix} 会以与前缀相对应的方式来处理并且处理的结果将替代原字符串值。 如果未识别出前缀，则原字符串将保持不变。

@node 访问内部对象,导入解析与定制导入器,访问外部对象,配置字典架构
@anchor{library/logging config access-to-internal-objects}@anchor{226b}@anchor{library/logging config logging-config-dict-internalobj}@anchor{226c}
@subsubsection 访问内部对象


除了外部对象，有时还需要引用配置中的对象。 这将由配置系统针对它所了解的内容隐式地完成。 例如，在日志记录器或处理程序中表示 @code{level} 的字符串值 @code{'DEBUG'} 将被自动转换为值 @code{logging.DEBUG}，而 @code{handlers}, @code{filters} 和 @code{formatter} 条目将接受一个对象 ID 并解析为适当的目标对象。

但是，对于 @ref{aa,,logging} 模块所不了解的用户自定义对象则需要一种更通用的机制。 例如，考虑 @ref{226d,,logging.handlers.MemoryHandler}，它接受一个 @code{target} 参数即其所委托的另一个处理程序。 由于系统已经知道存在该类，因而在配置中，给定的 @code{target} 只需为相应目标处理程序的的对象 ID 即可，而系统将根据该 ID 解析出处理程序。 但是，如果用户定义了一个具有 @code{alternate} 处理程序的 @code{my.package.MyHandler}，则配置程序将不知道 @code{alternate} 指向的是一个处理程序。 为了应对这种情况，通用解析系统允许用户指定:

@example
handlers:
  file:
    # configuration of file handler goes here

  custom:
    (): my.package.MyHandler
    alternate: cfg://handlers.file
@end example

字符串字面值 @code{'cfg://handlers.file'} 将按照与 @code{ext://} 前缀类似的方式被解析为结果字符串，但查找操作是在配置自身而不是在导入命名空间中进行。 该机制允许按点号或按索引来访问，与 @code{str.format} 所提供的方式类似。 这样，给定以下代码段:

@example
handlers:
  email:
    class: logging.handlers.SMTPHandler
    mailhost: localhost
    fromaddr: my_app@@domain.tld
    toaddrs:
      - support_team@@domain.tld
      - dev_team@@domain.tld
    subject: Houston, we have a problem.
@end example

在该配置中，字符串 @code{'cfg://handlers'} 将解析为带有 @code{handlers} 键的字典，字符串 @code{'cfg://handlers.email} 将解析为 @code{handlers} 字典中带有 @code{email} 键的字典，依此类推。 字符串 @code{'cfg://handlers.email.toaddrs[1]} 将解析为 @code{'dev_team.domain.tld'} 而字符串 @code{'cfg://handlers.email.toaddrs[0]'} 将解析为值 @code{'support_team@@domain.tld'}。 @code{subject} 值可以使用 @code{'cfg://handlers.email.subject'} 或者等价的 @code{'cfg://handlers.email[subject]'} 来访问。 后一种形式仅在键包含空格或非字母数字类字符的情况下才需要使用。 如果一个索引仅由十进制数码构成，则将尝试使用相应的整数值来访问，如果有必要则将回退为字符串值。

给定字符串 @code{cfg://handlers.myhandler.mykey.123}，这将解析为 @code{config_dict['handlers']['myhandler']['mykey']['123']}。 如果字符串被指定为 @code{cfg://handlers.myhandler.mykey[123]}，系统将尝试从 @code{config_dict['handlers']['myhandler']['mykey'][123]} 中提取值，并在尝试失败时回退为 @code{config_dict['handlers']['myhandler']['mykey']['123']}。

@node 导入解析与定制导入器,,访问内部对象,配置字典架构
@anchor{library/logging config import-resolution-and-custom-importers}@anchor{226e}@anchor{library/logging config logging-import-resolution}@anchor{226f}
@subsubsection 导入解析与定制导入器


导入解析默认使用内置的 @ref{16b,,__import__()} 函数来执行导入。 你可能想要将其替换为你自己的导入机制：如果是这样的话，你可以替换 @code{DictConfigurator} 或其超类 @code{BaseConfigurator} 类的 @code{importer} 属性。 但是你必须小心谨慎，因为函数是从类中通过描述器方式来访问的。 如果你使用 Python 可调用对象来执行导入，并且你希望在类层级而不是在实例层级上定义它，则你需要用 @ref{311,,staticmethod()} 来装饰它。 例如:

@example
from importlib import import_module
from logging.config import BaseConfigurator

BaseConfigurator.importer = staticmethod(import_module)
@end example

如果你是在一个配置器的 @emph{实例} 上设置导入可调用对象则你不需要用 @ref{311,,staticmethod()} 来装饰。

@node 配置文件格式,,配置字典架构,logging config --- 日志记录配置
@anchor{library/logging config configuration-file-format}@anchor{2270}@anchor{library/logging config logging-config-fileformat}@anchor{225b}
@subsubsection 配置文件格式


@ref{4b8,,fileConfig()} 所能理解的配置文件格式是基于 @ref{22,,configparser} 功能的。 该文件必须包含 @code{[loggers]}, @code{[handlers]} 和 @code{[formatters]} 等小节，它们通过名称来标识文件中定义的每种类型的实体。 对于每个这样的实体，都有单独的小节来标识实体的配置方式。 因此，对于 @code{[loggers]} 小节中名为 @code{log01} 的日志记录器，相应的配置详情保存在 @code{[logger_log01]} 小节中。 类似地，对于 @code{[handlers]} 小节中名为 @code{hand01} 的处理程序，其配置将保存在名为 @code{[handler_hand01]} 的小节中，而对于 @code{[formatters]} 小节中名为 @code{form01} 的格式化器，其配置将在名为 @code{[formatter_form01]} 的小节中指定。 根日志记录器的配置必须在名为 @code{[logger_root]} 的小节中指定。

@cartouche
@quotation 注解 
@ref{4b8,,fileConfig()} API 比 @ref{c07,,dictConfig()} API 更旧因而没有提供涵盖日志记录特定方面的功能。 例如，你无法配置 @ref{c51,,Filter} 对象，该对象使用 @ref{4b8,,fileConfig()} 提供超出简单整数级别的消息过滤功能。 如果你想要在你的日志记录配置中包含 @ref{c51,,Filter} 的实例，你将必须使用 @ref{c07,,dictConfig()}。 请注意未来还将向 @ref{c07,,dictConfig()} 添加对配置功能的强化，因此值得考虑在方便的时候转换到这个新 API。
@end quotation
@end cartouche

在文件中这些小节的例子如下所示。

@example
[loggers]
keys=root,log02,log03,log04,log05,log06,log07

[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09

[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
@end example

根日志记录器必须指定一个级别和一个处理程序列表。 根日志小节的例子如下所示。

@example
[logger_root]
level=NOTSET
handlers=hand01
@end example

@code{level} 条目可以为 @code{DEBUG, INFO, WARNING, ERROR, CRITICAL} 或 @code{NOTSET} 之一。 其中 @code{NOTSET} 仅适用于根日志记录器，表示将会记录所有消息。 级别值会在 @code{logging} 包命名空间的上下文中通过 @ref{c6a,,eval()} 来得出。

@code{handlers} 条目是以逗号分隔的处理程序名称列表，它必须出现于 @code{[handlers]} 小节并且在配置文件中有相应的小节。

对于根日志记录器以外的日志记录器，还需要某些附加信息。 下面的例子演示了这些信息。

@example
[logger_parser]
level=DEBUG
handlers=hand01
propagate=1
qualname=compiler.parser
@end example

@code{level} 和 @code{handlers} 条目的解释方式与根日志记录器的一致，不同之处在于如果一个非根日志记录器的级别被指定为 @code{NOTSET}，则系统会咨询更高层级的日志记录器来确定该日志记录器的有效级别。 @code{propagate} 条目设为 1 表示消息必须从此日志记录器传播到更高层级的处理程序，设为 0 表示消息 @strong{不会} 传播到更高层级的处理程序。 @code{qualname} 条目是日志记录器的层级通道名称，也就是应用程序获取日志记录器所用的名称。

指定处理程序配置的小节说明如下。

@example
[handler_hand01]
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)
@end example

@code{class} 条目指明处理程序的类（由 @code{logging} 包命名空间中的 @ref{c6a,,eval()} 来确定）。 @code{level} 会以与日志记录器相同的方式来解读，@code{NOTSET} 会被视为表示‘记录一切消息’。

@code{formatter} 条目指明此处理程序的格式化器的键名称。 如为空白，则会使用默认的格式化器 (@code{logging._defaultFormatter})。 如果指定了名称，则它必须出现于 @code{[formatters]} 小节并且在配置文件中有相应的小节。

@code{args} 条目，当在 @code{logging} 包命名空间的上下文中执行 @ref{c6a,,eval()} 时将是传给处理程序类构造器的参数列表。 请参阅相应处理程序的构造器说明或者下面的示例，以了解典型的条目是如何构造的。 如果未提供，则默认为 @code{()}。

可选的 @code{kwargs} 条目，当在 @code{logging} 包命名空间的上下文中执行 @ref{c6a,,eval()} 时将是传给处理程序的构造器的关键字参数字典。 如果未提供，则默认为 @code{@{@}}。

@example
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')

[handler_hand03]
class=handlers.SocketHandler
level=INFO
formatter=form03
args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

[handler_hand04]
class=handlers.DatagramHandler
level=WARN
formatter=form04
args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)

[handler_hand05]
class=handlers.SysLogHandler
level=ERROR
formatter=form05
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

[handler_hand06]
class=handlers.NTEventLogHandler
level=CRITICAL
formatter=form06
args=('Python Application', '@w{'}, 'Application')

[handler_hand07]
class=handlers.SMTPHandler
level=WARN
formatter=form07
args=('localhost', 'from@@abc', ['user1@@abc', 'user2@@xyz'], 'Logger Subject')
kwargs=@{'timeout': 10.0@}

[handler_hand08]
class=handlers.MemoryHandler
level=NOTSET
formatter=form08
target=
args=(10, ERROR)

[handler_hand09]
class=handlers.HTTPHandler
level=NOTSET
formatter=form09
args=('localhost:9022', '/log', 'GET')
kwargs=@{'secure': True@}
@end example

指定格式化器配置的小节说明如下。

@example
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
@end example

@code{format} 是整个格式字符串，而 @code{datefmt} 条目则是兼容 @code{strftime()} 的日期/时间格式字符串。 如果为空，此包将替换任何接近于日期格式字符串 @code{'%Y-%m-%d %H:%M:%S'} 的内容。 此格式还指定了毫秒，并使用逗号分隔符将其附加到结果当中。 此格式的时间示例如 @code{2003-01-23 00:29:50,411}。

@code{class} 条目是可选的。 它指明格式化器类的名称（形式为带点号的模块名加类名。） 此选项适用于实例化 @ref{220c,,Formatter} 的子类。 @ref{220c,,Formatter} 的子类可通过扩展或收缩格式来显示异常回溯信息。

@cartouche
@quotation 注解 
由于如上所述使用了 @ref{c6a,,eval()}，因此使用 @ref{966,,listen()} 通过套接字来发送和接收配置会导致潜在的安全风险。 此风险仅限于相互间没有信任的多个用户在同一台机器上运行代码的情况；请参阅 @ref{966,,listen()} 了解更多信息。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item 模块 @ref{aa,,logging}

日志记录模块的 API 参考。

@item 模块 @ref{ac,,logging.handlers}

日志记录模块附带的有用处理程序。
@end table


@node logging handlers --- 日志处理程序,getpass --- 便携式密码输入工具,logging config --- 日志记录配置,通用操作系统服务
@anchor{library/logging handlers doc}@anchor{2271}@anchor{library/logging handlers logging-handlers-logging-handlers}@anchor{2272}@anchor{library/logging handlers module-logging handlers}@anchor{ac}
@subsection @code{logging.handlers} --- 日志处理程序


@geindex logging.handlers (模块)

@strong{源代码:} Lib/logging/handlers.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/logging/handlers.py}

@subsubheading Important



此页面仅包含参考信息。有关教程，请参阅


@itemize *

@item 
@ref{c4c,,基础教程}

@item 
@ref{c4d,,进阶教程}

@item 
@ref{c4e,,日志记录操作手册}
@end itemize


__________________________________________________________________


这个包提供了以下有用的处理程序。 请注意有三个处理程序类 (@ref{c4f,,StreamHandler}, @ref{2273,,FileHandler} 和 @ref{cee,,NullHandler}) 实际上是在 @ref{aa,,logging} 模块本身定义的，但其文档与其他处理程序一同记录在此。

@menu
* StreamHandler:: 
* FileHandler:: 
* NullHandler:: 
* WatchedFileHandler:: 
* BaseRotatingHandler:: 
* RotatingFileHandler:: 
* TimedRotatingFileHandler:: 
* SocketHandler:: 
* DatagramHandler:: 
* SysLogHandler:: 
* NTEventLogHandler:: 
* SMTPHandler:: 
* MemoryHandler:: 
* HTTPHandler:: 
* QueueHandler:: 
* QueueListener:: 

@end menu

@node StreamHandler,FileHandler,,logging handlers --- 日志处理程序
@anchor{library/logging handlers stream-handler}@anchor{2274}@anchor{library/logging handlers streamhandler}@anchor{2275}
@subsubsection StreamHandler


@ref{c4f,,StreamHandler} 类位于核心 @ref{aa,,logging} 包，它可将日志记录输出发送到数据流例如 @emph{sys.stdout}, @emph{sys.stderr} 或任何文件类对象（或者更精确地说，任何支持 @code{write()} 和 @code{flush()} 方法的对象）。

@geindex StreamHandler (logging 中的类)
@anchor{library/logging handlers logging StreamHandler}@anchor{c4f}
@deffn {类} logging.StreamHandler (stream=None)

返回一个新的 @ref{c4f,,StreamHandler} 类。 如果指定了 @emph{stream}，则实例将用它作为日志记录输出；在其他情况下将使用 @emph{sys.stderr}。

@geindex emit() (logging.StreamHandler 方法)
@anchor{library/logging handlers logging StreamHandler emit}@anchor{2276}
@deffn {方法} emit (record)

如果指定了一个格式化器，它会被用来格式化记录。 随后记录会被写入到 @ref{2277,,terminator} 之后的流中。 如果存在异常信息，则会使用 @ref{2236,,traceback.print_exception()} 来格式化并添加到流中。
@end deffn

@geindex flush() (logging.StreamHandler 方法)
@anchor{library/logging handlers logging StreamHandler flush}@anchor{2278}
@deffn {方法} flush ()

通过调用流的 @ref{2278,,flush()} 方法来刷新它。 请注意 @code{close()} 方法是继承自 @ref{220d,,Handler} 的所以没有输出，因此有时可能需要显式地调用 @ref{2278,,flush()}。
@end deffn

@geindex setStream() (logging.StreamHandler 方法)
@anchor{library/logging handlers logging StreamHandler setStream}@anchor{4b7}
@deffn {方法} setStream (stream)

将实例的流设为指定值，如果两者不一致的话。 旧的流会在设置新的流之前被刷新。

@*参数: 
@code{stream} -- 处理程序应当使用的流。


@*返回: 
旧的流，如果流已被改变的话，如果未被改变则为 @emph{None}。



3.7 新版功能.

@end deffn

@geindex terminator (logging.StreamHandler 属性)
@anchor{library/logging handlers logging StreamHandler terminator}@anchor{2277}
@deffn {属性} terminator

当将已格式化的记录写入到流时被用作终止符的字符串。 默认值为 @code{'\n'}。

如果你不希望以换行符终止，你可以将处理程序类实例的 @code{terminator} 属性设为空字符串。

在较早的版本中，终止符被硬编码为 @code{'\n'}。


3.2 新版功能.

@end deffn
@end deffn

@node FileHandler,NullHandler,StreamHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers file-handler}@anchor{2279}@anchor{library/logging handlers filehandler}@anchor{227a}
@subsubsection FileHandler


@ref{2273,,FileHandler} 类位于核心 @ref{aa,,logging} 包，它可将日志记录输出到磁盘文件中。 它从 @ref{c4f,,StreamHandler} 继承了输出功能。

@geindex FileHandler (logging 中的类)
@anchor{library/logging handlers logging FileHandler}@anchor{2273}
@deffn {类} logging.FileHandler (filename, mode='a', encoding=None, delay=False, errors=None)

返回一个 @ref{2273,,FileHandler} 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 @emph{mode}，则会使用 @code{'a'}。 如果 @emph{encoding} 不为 @code{None}，则会将其用作打开文件的编码格式。 如果 @emph{delay} 为真值，则文件打开会被推迟至第一次调用 @ref{227b,,emit()} 时。 默认情况下，文件会无限增长。 如果指定了 @emph{errors}，它会被用于确定编码格式错误的处理方式。


在 3.6 版更改: 除了字符串值，也接受 @ref{336,,Path} 对象作为 @emph{filename} 参数。



在 3.9 版更改: 增加了 @emph{errors} 形参。


@geindex close() (logging.FileHandler 方法)
@anchor{library/logging handlers logging FileHandler close}@anchor{227c}
@deffn {方法} close ()

关闭文件。
@end deffn

@geindex emit() (logging.FileHandler 方法)
@anchor{library/logging handlers logging FileHandler emit}@anchor{227b}
@deffn {方法} emit (record)

将记录输出到文件。
@end deffn
@end deffn

@node NullHandler,WatchedFileHandler,FileHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers null-handler}@anchor{227d}@anchor{library/logging handlers nullhandler}@anchor{227e}
@subsubsection NullHandler



3.1 新版功能.


@ref{cee,,NullHandler} 类位于核心 @ref{aa,,logging} 包，它不执行任何格式化或输出。 它实际上是一个供库开发者使用的‘无操作’处理程序。

@geindex NullHandler (logging 中的类)
@anchor{library/logging handlers logging NullHandler}@anchor{cee}
@deffn {类} logging.NullHandler

返回一个 @ref{cee,,NullHandler} 类的新实例。

@geindex emit() (logging.NullHandler 方法)
@anchor{library/logging handlers logging NullHandler emit}@anchor{227f}
@deffn {方法} emit (record)

此方法不执行任何操作。
@end deffn

@geindex handle() (logging.NullHandler 方法)
@anchor{library/logging handlers logging NullHandler handle}@anchor{2280}
@deffn {方法} handle (record)

此方法不执行任何操作。
@end deffn

@geindex createLock() (logging.NullHandler 方法)
@anchor{library/logging handlers logging NullHandler createLock}@anchor{2281}
@deffn {方法} createLock ()

此方法会对锁返回 @code{None}，因为没有下层 I/O 的访问需要被序列化。
@end deffn
@end deffn

请参阅 @ref{2282,,配置库的日志记录} 了解有关如何使用 @ref{cee,,NullHandler} 的更多信息。

@node WatchedFileHandler,BaseRotatingHandler,NullHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers watched-file-handler}@anchor{2283}@anchor{library/logging handlers watchedfilehandler}@anchor{2284}
@subsubsection WatchedFileHandler


@ref{2285,,WatchedFileHandler} 类位于 @ref{ac,,logging.handlers} 模块，这个 @code{FileHandler} 用于监视它所写入日志记录的文件。 如果文件发生变化，它会被关闭并使用文件名重新打开。

发生文件更改可能是由于使用了执行文件轮换的程序例如 @emph{newsyslog} 和 @emph{logrotate}。 这个处理程序在 Unix/Linux 下使用，它会监视文件来查看自上次发出数据后是否有更改。 （如果文件的设备或 inode 发生变化就认为已被更改。） 如果文件被更改，则会关闭旧文件流，并再打开文件以获得新文件流。

这个处理程序不适合在 Windows 下使用，因为在 Windows 下打开的日志文件无法被移动或改名 —— 日志记录会使用排他的锁来打开文件 —— 因此这样的处理程序是没有必要的。 此外，@emph{ST_INO} 在 Windows 下不受支持；@ref{328,,stat()} 将总是为该值返回零。

@geindex WatchedFileHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers WatchedFileHandler}@anchor{2285}
@deffn {类} logging.handlers.WatchedFileHandler (filename, mode='a', encoding=None, delay=False, errors=None)

返回一个 @ref{2285,,WatchedFileHandler} 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 @emph{mode}，则会使用 @code{'a'}。 如果 @emph{encoding} 不为 @code{None}，则会将其用作打开文件的编码格式。 如果 @emph{delay} 为真值，则文件打开会被推迟至第一次调用 @ref{2286,,emit()} 时。 默认情况下，文件会无限增长。 如果提供了 @emph{errors}，它会被用于确定编码格式错误的处理方式。


在 3.6 版更改: 除了字符串值，也接受 @ref{336,,Path} 对象作为 @emph{filename} 参数。



在 3.9 版更改: 增加了 @emph{errors} 形参。


@geindex reopenIfNeeded() (logging.handlers.WatchedFileHandler 方法)
@anchor{library/logging handlers logging handlers WatchedFileHandler reopenIfNeeded}@anchor{664}
@deffn {方法} reopenIfNeeded ()

检查文件是否已更改。 如果已更改，则会刷新并关闭现有流然后重新打开文件，这通常是将记录输出到文件的先导操作。


3.6 新版功能.

@end deffn

@geindex emit() (logging.handlers.WatchedFileHandler 方法)
@anchor{library/logging handlers logging handlers WatchedFileHandler emit}@anchor{2286}
@deffn {方法} emit (record)

将记录输出到文件，但如果文件已更改则会先调用 @ref{664,,reopenIfNeeded()} 来重新打开它。
@end deffn
@end deffn

@node BaseRotatingHandler,RotatingFileHandler,WatchedFileHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers base-rotating-handler}@anchor{2287}@anchor{library/logging handlers baserotatinghandler}@anchor{2288}
@subsubsection BaseRotatingHandler


@ref{2289,,BaseRotatingHandler} 类位于 @ref{ac,,logging.handlers} 模块中，它是轮换文件处理程序类 @ref{2264,,RotatingFileHandler} 和 @ref{962,,TimedRotatingFileHandler} 的基类。 你不需要实例化此类，但它具有你可能需要重载的属性和方法。

@geindex BaseRotatingHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers BaseRotatingHandler}@anchor{2289}
@deffn {类} logging.handlers.BaseRotatingHandler (filename, mode, encoding=None, delay=False, errors=None)

类的形参与 @code{FileHandler} 的相同。 其属性有:

@geindex namer (logging.handlers.BaseRotatingHandler 属性)
@anchor{library/logging handlers logging handlers BaseRotatingHandler namer}@anchor{228a}
@deffn {属性} namer

如果此属性被设为一个可调用对象，则 @ref{228b,,rotation_filename()} 方法会委托给该可调用对象。 传给该可调用对象的形参与传给 @ref{228b,,rotation_filename()} 的相同。

@cartouche
@quotation 注解 
namer 函数会在轮换期间被多次调用，因此它应当尽可能的简单快速。 它还应当对给定的输入每次都返回相同的输出，否则轮换行为可能无法按预期工作。

还有一点值得注意的是当使用命名器来保存文件名中要在轮换中使用的特定属性时必须小心处理。 例如，@ref{2264,,RotatingFileHandler} 会要求有一组名称中包含连续整数的日志文件，以便轮换的效果能满足预期，而 @ref{962,,TimedRotatingFileHandler} 会通过确定要删除的最旧文件（根据传递纵使中处理句柄的初始化器的 @code{backupCount} 形参）来删除旧的日志文件。 为了达成这样的效果，文件名应当是可以使用文件名的日期/时间部分来排序的，而且命名器需要遵循此排序。 （如果想使用不遵循此规则的命名器，则需要在一个重载了 @ref{228c,,getFilesToDelete()} 方法的 @ref{962,,TimedRotatingFileHandler} 的子类中使用它以便与自定义的命名规则进行配合。）
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@geindex rotator (logging.handlers.BaseRotatingHandler 属性)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotator}@anchor{228d}
@deffn {属性} rotator

如果此属性被设为一个可调用对象，则 @ref{228e,,rotate()} 方法会委托给该可调用对象。 传给该可调用对象的形参与传给 @ref{228e,,rotate()} 的相同。


3.3 新版功能.

@end deffn

@geindex rotation_filename() (logging.handlers.BaseRotatingHandler 方法)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotation_filename}@anchor{228b}
@deffn {方法} rotation_filename (default_name)

当轮换时修改日志文件的文件名。

提供该属性以便可以提供自定义文件名。

默认实现会调用处理程序的 'namer' 属性，如果它是可调用对象的话，并传给它默认的名称。 如果该属性不是可调用对象 (默认值为 @code{None})，则将名称原样返回。

@*参数: 
@code{default_name} -- 日志文件的默认名称。



3.3 新版功能.

@end deffn

@geindex rotate() (logging.handlers.BaseRotatingHandler 方法)
@anchor{library/logging handlers logging handlers BaseRotatingHandler rotate}@anchor{228e}
@deffn {方法} rotate (source, dest)

当执行轮换时，轮换当前日志。

默认实现会调用处理程序的 'rotator' 属性，如果它是可调用对象的话，并传给它 source 和 dest 参数。 如果该属性不是可调用对象 (默认值为 @code{None})，则将源简单地重命名为目标。

@*参数: 

@itemize *

@item 
@code{source} -- 源文件名。 这通常为基本文件名，例如 'test.log'。

@item 
@code{dest} -- 目标文件名。 这通常是源被轮换后的名称，例如 'test.log.1'。
@end itemize



3.3 新版功能.

@end deffn
@end deffn

该属性存在的理由是让你不必进行子类化 —— 你可以使用与 @ref{2264,,RotatingFileHandler} 和 @ref{962,,TimedRotatingFileHandler} 的实例相同的可调用对象。 如果 namer 或 rotator 可调用对象引发了异常，将会按照与 @code{emit()} 调用期间的任何其他异常相同的方式来处理，例如通过处理程序的 @code{handleError()} 方法。

如果你需要对轮换进程执行更多的修改，你可以重载这些方法。

请参阅 @ref{228f,,利用 rotator 和 namer 自定义日志轮换操作} 获取具体示例。

@node RotatingFileHandler,TimedRotatingFileHandler,BaseRotatingHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers rotating-file-handler}@anchor{2290}@anchor{library/logging handlers rotatingfilehandler}@anchor{2291}
@subsubsection RotatingFileHandler


@ref{2264,,RotatingFileHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持磁盘日志文件的轮换。

@geindex RotatingFileHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers RotatingFileHandler}@anchor{2264}
@deffn {类} logging.handlers.RotatingFileHandler (filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)

返回一个 @ref{2264,,RotatingFileHandler} 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 @emph{mode}，则会使用 @code{'a'}。 如果 @emph{encoding} 不为 @code{None}，则会将其用作打开文件的编码格式。 如果 @emph{delay} 为真值，则文件打开会被推迟至第一次调用 @ref{2292,,emit()}。 默认情况下，文件会无限增长。 如果提供了 @emph{errors}，它会被用于确定编码格式错误的处理方式。

你可以使用 @emph{maxBytes} 和 @emph{backupCount} 值来允许文件以预定的大小执行 @emph{rollover}。 当即将超出预定大小时，将关闭旧文件并打开一个新文件用于输出。 只要当前日志文件长度接近 @emph{maxBytes} 就会发生轮换；但是如果 @emph{maxBytes} 或 @emph{backupCount} 两者之一的值为零，就不会发生轮换，因此你通常要设置 @emph{backupCount} 至少为 1，而 @emph{maxBytes} 不能为零。 当 @emph{backupCount} 为非零值时，系统将通过为原文件名添加扩展名 '.1', '.2' 等来保存旧日志文件。 例如，当 @emph{backupCount} 为 5 而基本文件名为 @code{app.log} 时，你将得到 @code{app.log}, @code{app.log.1}, @code{app.log.2} 直至 @code{app.log.5}。 当前被写入的文件总是 @code{app.log}。 当此文件写满时，它会被关闭并重户名为 @code{app.log.1}，而如果文件 @code{app.log.1}, @code{app.log.2} 等存在，则它们会被分别重命名为 @code{app.log.2}, @code{app.log.3} 等等。


在 3.6 版更改: 除了字符串值，也接受 @ref{336,,Path} 对象作为 @emph{filename} 参数。



在 3.9 版更改: 增加了 @emph{errors} 形参。


@geindex doRollover() (logging.handlers.RotatingFileHandler 方法)
@anchor{library/logging handlers logging handlers RotatingFileHandler doRollover}@anchor{2293}
@deffn {方法} doRollover ()

执行上文所描述的轮换。
@end deffn

@geindex emit() (logging.handlers.RotatingFileHandler 方法)
@anchor{library/logging handlers logging handlers RotatingFileHandler emit}@anchor{2292}
@deffn {方法} emit (record)

将记录输出到文件，以适应上文所描述的轮换。
@end deffn
@end deffn

@node TimedRotatingFileHandler,SocketHandler,RotatingFileHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers timed-rotating-file-handler}@anchor{2294}@anchor{library/logging handlers timedrotatingfilehandler}@anchor{2295}
@subsubsection TimedRotatingFileHandler


@ref{962,,TimedRotatingFileHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持基于特定时间间隔的磁盘日志文件轮换。

@geindex TimedRotatingFileHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler}@anchor{962}
@deffn {类} logging.handlers.TimedRotatingFileHandler (filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)

返回一个新的 @ref{962,,TimedRotatingFileHandler} 类实例。 指定的文件会被打开并用作日志记录的流。 对于轮换操作它还会设置文件名前缀。 轮换的发生是基于 @emph{when} 和 @emph{interval} 的积。

你可以使用 @emph{when} 来指定 @emph{interval} 的类型。 可能的值列表如下。 请注意它们不是大小写敏感的。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

间隔类型

@tab

如果/如何使用 @emph{atTime}

@item

@code{'S'}

@tab

秒

@tab

忽略

@item

@code{'M'}

@tab

分钟

@tab

忽略

@item

@code{'H'}

@tab

小时

@tab

忽略

@item

@code{'D'}

@tab

天

@tab

忽略

@item

@code{'W0'-'W6'}

@tab

工作日(0=星期一)

@tab

用于计算初始轮换时间

@item

@code{'midnight'}

@tab

如果未指定 @emph{atTime} 则在午夜执行轮换，否则将使用 @emph{atTime}。

@tab

用于计算初始轮换时间

@end multitable


当使用基于星期的轮换时，星期一为 'W0'，星期二为 'W1'，以此类推直至星期日为 'W6'。 在这种情况下，传入的 @emph{interval} 值不会被使用。

系统将通过为文件名添加扩展名来保存旧日志文件。 扩展名是基于日期和时间的，根据轮换间隔的长短使用 strftime 格式 @code{%Y-%m-%d_%H-%M-%S} 或是其中有变动的部分。

当首次计算下次轮换的时间时（即当处理程序被创建时），现有日志文件的上次被修改时间或者当前时间会被用来计算下次轮换的发生时间。

如果 @emph{utc} 参数为真值，将使用 UTC 时间；否则会使用本地时间。

如果 @emph{backupCount} 不为零，则最多将保留 @emph{backupCount} 个文件，而如果当轮换发生时创建了更多的文件，则最旧的文件会被删除。 删除逻辑使用间隔时间来确定要删除的文件，因此改变间隔时间可能导致旧文件被继续保留。

如果 @emph{delay} 为真值，则会将文件打开延迟到首次调用 @ref{2296,,emit()} 的时候。

如果 @emph{atTime} 不为 @code{None}，则它必须是一个 @code{datetime.time} 的实例，该实例指定轮换在一天内的发生时间，用于轮换被设为“在午夜”或“在每星期的某一天”之类的情况。 请注意在这些情况下，@emph{atTime} 值实际上会被用于计算 @emph{初始} 轮换，而后续轮换将会通过正常的间隔时间计算来得出。

如果指定了 @emph{errors}，它会被用来确定编码错误的处理方式。

@cartouche
@quotation 注解 
初始轮换时间的计算是在处理程序被初始化时执行的。 后续轮换时间的计算则仅在轮换发生时执行，而只有当提交输出时轮换才会发生。 如果不记住这一点，你就可能会感到困惑。 例如，如果设置时间间隔为“每分钟”，那并不意味着你总会看到（文件名中）带有间隔一分钟时间的日志文件；如果在应用程序执行期间，日志记录输出的生成频率高于每分钟一次，@emph{那么} 你可以预期看到间隔一分钟时间的日志文件。 另一方面，如果（假设）日志记录消息每五分钟才输出一次，那么文件时间将会存在对应于没有输出（因而没有轮换）的缺失。
@end quotation
@end cartouche


在 3.4 版更改: 添加了 @emph{atTime} 形参。



在 3.6 版更改: 除了字符串值，也接受 @ref{336,,Path} 对象作为 @emph{filename} 参数。



在 3.9 版更改: 增加了 @emph{errors} 形参。


@geindex doRollover() (logging.handlers.TimedRotatingFileHandler 方法)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler doRollover}@anchor{2297}
@deffn {方法} doRollover ()

执行上文所描述的轮换。
@end deffn

@geindex emit() (logging.handlers.TimedRotatingFileHandler 方法)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler emit}@anchor{2296}
@deffn {方法} emit (record)

将记录输出到文件，以适应上文所描述的轮换。
@end deffn

@geindex getFilesToDelete() (logging.handlers.TimedRotatingFileHandler 方法)
@anchor{library/logging handlers logging handlers TimedRotatingFileHandler getFilesToDelete}@anchor{228c}
@deffn {方法} getFilesToDelete ()

返回由应当作为轮转的一部分被删除的文件名组成的列表。 它们是由处理程序写入的最旧的备份日志文件的绝对路径。
@end deffn
@end deffn

@node SocketHandler,DatagramHandler,TimedRotatingFileHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers socket-handler}@anchor{2298}@anchor{library/logging handlers sockethandler}@anchor{2299}
@subsubsection SocketHandler


@ref{963,,SocketHandler} 类位于 @ref{ac,,logging.handlers} 模块，它会将日志记录输出发送到网络套接字。 基类所使用的是 TCP 套接字。

@geindex SocketHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers SocketHandler}@anchor{963}
@deffn {类} logging.handlers.SocketHandler (host, port)

返回一个 @ref{963,,SocketHandler} 类的新实例，该实例旨在与使用 @emph{host} 与 @emph{port} 给定地址的远程主机进行通信。


在 3.4 版更改: 如果 @code{port} 指定为 @code{None}，会使用 @code{host} 中的值来创建一个 Unix 域套接字 —— 在其他情况下，则会创建一个 TCP 套接字。


@geindex close() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler close}@anchor{229a}
@deffn {方法} close ()

关闭套接字。
@end deffn

@geindex emit() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler emit}@anchor{229b}
@deffn {方法} emit ()

对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套接字存在错误，则静默地丢弃数据包。 如果连接在此之前丢失，则重新建立连接。 要在接收端将记录解封并输出到 @ref{9f5,,LogRecord}，请使用 @ref{223e,,makeLogRecord()} 函数。
@end deffn

@geindex handleError() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler handleError}@anchor{229c}
@deffn {方法} handleError ()

处理在 @ref{229b,,emit()} 期间发生的错误。 最可能的原因是连接丢失。 关闭套接字以便我们能在下次事件时重新尝试。
@end deffn

@geindex makeSocket() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler makeSocket}@anchor{229d}
@deffn {方法} makeSocket ()

这是一个工厂方法，它允许子类定义它们想要的套接字的准确类型。 默认实现会创建一个 TCP 套接字 (@ref{d5a,,socket.SOCK_STREAM})。
@end deffn

@geindex makePickle() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler makePickle}@anchor{229e}
@deffn {方法} makePickle (record)

将记录的属性字典封存为带有长度前缀的二进制格式，并将其返回以准备通过套接字进行传输。 此操作在细节上相当于:

@example
data = pickle.dumps(record_attr_dict, 1)
datalen = struct.pack('>L', len(data))
return datalen + data
@end example

请注意封存操作不是绝对安全的。 如果你关心安全问题，你可能会想要重载此方法以实现更安全的机制。 例如，你可以使用 HMAC 对封存对象进行签名然后在接收端验证它们，或者你也可以在接收端禁用全局对象的解封操作。
@end deffn

@geindex send() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler send}@anchor{229f}
@deffn {方法} send (packet)

将封存后的字节串 @emph{packet} 发送到套接字。 所发送字节串的格式与 @ref{229e,,makePickle()} 文档中的描述一致。

此函数允许部分发送，这可能会在网络繁忙时发生。
@end deffn

@geindex createSocket() (logging.handlers.SocketHandler 方法)
@anchor{library/logging handlers logging handlers SocketHandler createSocket}@anchor{22a0}
@deffn {方法} createSocket ()

尝试创建一个套接字；失败时将使用指数化回退算法处理。 在失败初次发生时，处理程序将丢弃它正尝试发送的消息。 当后续消息交由同一实例处理时，它将不会尝试连接直到经过一段时间以后。 默认形参设置为初始延迟一秒，如果在延迟之后连接仍然无法建立，处理程序将每次把延迟翻倍直至达到 30 秒的最大值。

此行为由下列处理程序属性控制:


@itemize *

@item 
@code{retryStart} (初始延迟，默认为 1.0 秒)。

@item 
@code{retryFactor} (倍数，默认为 2.0)。

@item 
@code{retryMax} (最大延迟，默认为 30.0 秒)。
@end itemize

这意味着如果远程监听器在处理程序被使用 @emph{之后} 启动，你可能会丢失消息（因为处理程序在延迟结束之前甚至不会尝试连接，而在延迟期间静默地丢弃消息）。
@end deffn
@end deffn

@node DatagramHandler,SysLogHandler,SocketHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers datagram-handler}@anchor{22a1}@anchor{library/logging handlers datagramhandler}@anchor{22a2}
@subsubsection DatagramHandler


@ref{964,,DatagramHandler} 类位于 @ref{ac,,logging.handlers} 模块，它继承自 @ref{963,,SocketHandler}，支持通过 UDP 套接字发送日志记录消息。

@geindex DatagramHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers DatagramHandler}@anchor{964}
@deffn {类} logging.handlers.DatagramHandler (host, port)

返回一个 @ref{964,,DatagramHandler} 类的新实例，该实例旨在与使用 @emph{host} 与 @emph{port} 给定地址的远程主机进行通信。


在 3.4 版更改: 如果 @code{port} 指定为 @code{None}，会使用 @code{host} 中的值来创建一个 Unix 域套接字 —— 在其他情况下，则会创建一个 UDP 套接字。


@geindex emit() (logging.handlers.DatagramHandler 方法)
@anchor{library/logging handlers logging handlers DatagramHandler emit}@anchor{22a3}
@deffn {方法} emit ()

对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套接字存在错误，则静默地丢弃数据包。 要在接收端将记录解封并输出到 @ref{9f5,,LogRecord}，请使用 @ref{223e,,makeLogRecord()} 函数。
@end deffn

@geindex makeSocket() (logging.handlers.DatagramHandler 方法)
@anchor{library/logging handlers logging handlers DatagramHandler makeSocket}@anchor{22a4}
@deffn {方法} makeSocket ()

@ref{963,,SocketHandler} 的工厂方法会在此被重载以创建一个 UDP 套接字 (@ref{d59,,socket.SOCK_DGRAM})。
@end deffn

@geindex send() (logging.handlers.DatagramHandler 方法)
@anchor{library/logging handlers logging handlers DatagramHandler send}@anchor{22a5}
@deffn {方法} send (s)

将封存后的字节串发送到套接字。 所发送字节串的格式与 @ref{229e,,SocketHandler.makePickle()} 文档中的描述一致。
@end deffn
@end deffn

@node SysLogHandler,NTEventLogHandler,DatagramHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers syslog-handler}@anchor{22a6}@anchor{library/logging handlers sysloghandler}@anchor{22a7}
@subsubsection SysLogHandler


@ref{b04,,SysLogHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持将日志记录消息发送到远程或本地 Unix syslog。

@geindex SysLogHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers SysLogHandler}@anchor{b04}
@deffn {类} logging.handlers.SysLogHandler (address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)

返回一个 @ref{b04,,SysLogHandler} 类的新实例用来与通过 @emph{address} 以 @code{(host, port)} 元组形式给出地址的远程 Unix 机器进行通讯。 如果未指定 @emph{address}，则使用 @code{('localhost', 514)}。 该地址会被用于打开套接字。 提供 @code{(host, port)} 元组的一种替代方式是提供字符串形式的地址，例如 '/dev/log'。 在这种情况下，会使用 Unix 域套接字将消息发送到 syslog。 如果未指定 @emph{facility}，则使用 @code{LOG_USER}。 打开的套接字类型取决于 @emph{socktype} 参数，该参数的默认值为 @ref{d59,,socket.SOCK_DGRAM} 即打开一个 UDP 套接字。 要打开一个 TCP 套接字（用来配合较新的 syslog 守护程序例如 rsyslog 使用），请指定值为 @ref{d5a,,socket.SOCK_STREAM}。

请注意如果你的服务器不是在 UDP 端口 514 上进行侦听，则 @ref{b04,,SysLogHandler} 可能无法正常工作。 在这种情况下，请检查你应当为域套接字所使用的地址 —— 它依赖于具体的系统。 例如，在 Linux 上通常为 '/dev/log' 而在 OS/X 上则为 '/var/run/syslog'。 你需要检查你的系统平台并使用适当的地址（如果你的应用程序需要在多个平台上运行则可能需要在运行时进行这样的检查）。 在 Windows 上，你大概必须要使用 UDP 选项。


在 3.2 版更改: 添加了 @emph{socktype}。


@geindex close() (logging.handlers.SysLogHandler 方法)
@anchor{library/logging handlers logging handlers SysLogHandler close}@anchor{22a8}
@deffn {方法} close ()

关闭连接远程主机的套接字。
@end deffn

@geindex emit() (logging.handlers.SysLogHandler 方法)
@anchor{library/logging handlers logging handlers SysLogHandler emit}@anchor{22a9}
@deffn {方法} emit (record)

记录会被格式化，然后发送到 syslog 服务器。 如果存在异常信息，则它 @emph{不会} 被发送到服务器。


在 3.2.1 版更改: (参见: bpo-12168@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12168}。) 在较早的版本中，发送至 syslog 守护程序的消息总是以一个 NUL 字节结束，因为守护程序的早期版本期望接收一个以 NUL 结束的消息 —— 即使它不包含于对应的规范说明 (
@geindex RFC; RFC 5424
RFC 5424@footnote{https://tools.ietf.org/html/rfc5424.html})。 这些守护程序的较新版本不再期望接收 NUL 字节，如果其存在则会将其去除，而最新的守护程序（更紧密地遵循 RFC 5424）会将 NUL 字节作为消息的一部分传递出去。

为了在面对所有这些不同守护程序行为时能够更方便地处理 syslog 消息，通过使用类层级属性 @code{append_nul}，添加 NUL 字节的操作已被作为可配置项。 该属性默认为 @code{True} (保留现有行为) 但可在 @code{SysLogHandler} 实例上设为 @code{False} 以便让实例 @emph{不会} 添加 NUL 结束符。



在 3.3 版更改: (参见: bpo-12419@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12419}。) 在较早的版本中，没有 "ident" 或 "tag" 前缀工具可以用来标识消息的来源。 现在则可以使用一个类层级属性来设置它，该属性默认为 @code{""} 表示保留现有行为，但可在 @code{SysLogHandler} 实例上重载以便让实例不会为所处理的每条消息添加标识。 请注意所提供的标识必须为文本而非字节串，并且它会被原封不动地添加到消息中。

@end deffn

@geindex encodePriority() (logging.handlers.SysLogHandler 方法)
@anchor{library/logging handlers logging handlers SysLogHandler encodePriority}@anchor{22aa}
@deffn {方法} encodePriority (facility, priority)

将功能和优先级编码为一个整数。 你可以传入字符串或者整数 —— 如果传入的是字符串，则会使用内部的映射字典将其转换为整数。

符号 @code{LOG_} 的值在 @ref{b04,,SysLogHandler} 中定义并且是 @code{sys/syslog.h} 头文件中所定义值的镜像。

@strong{优先级}


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

名称（字符串）

@tab

符号值

@item

@code{alert}

@tab

LOG_ALERT

@item

@code{crit} 或 @code{critical}

@tab

LOG_CRIT

@item

@code{debug}

@tab

LOG_DEBUG

@item

@code{emerg} 或 @code{panic}

@tab

LOG_EMERG

@item

@code{err} 或 @code{error}

@tab

LOG_ERR

@item

@code{info}

@tab

LOG_INFO

@item

@code{notice}

@tab

LOG_NOTICE

@item

@code{warn} 或 @code{warning}

@tab

LOG_WARNING

@end multitable


@strong{设备}


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

名称（字符串）

@tab

符号值

@item

@code{auth}

@tab

LOG_AUTH

@item

@code{authpriv}

@tab

LOG_AUTHPRIV

@item

@code{cron}

@tab

LOG_CRON

@item

@code{daemon}

@tab

LOG_DAEMON

@item

@code{ftp}

@tab

LOG_FTP

@item

@code{kern}

@tab

LOG_KERN

@item

@code{lpr}

@tab

LOG_LPR

@item

@code{mail}

@tab

LOG_MAIL

@item

@code{news}

@tab

LOG_NEWS

@item

@code{syslog}

@tab

LOG_SYSLOG

@item

@code{user}

@tab

LOG_USER

@item

@code{uucp}

@tab

LOG_UUCP

@item

@code{local0}

@tab

LOG_LOCAL0

@item

@code{local1}

@tab

LOG_LOCAL1

@item

@code{local2}

@tab

LOG_LOCAL2

@item

@code{local3}

@tab

LOG_LOCAL3

@item

@code{local4}

@tab

LOG_LOCAL4

@item

@code{local5}

@tab

LOG_LOCAL5

@item

@code{local6}

@tab

LOG_LOCAL6

@item

@code{local7}

@tab

LOG_LOCAL7

@end multitable

@end deffn

@geindex mapPriority() (logging.handlers.SysLogHandler 方法)
@anchor{library/logging handlers logging handlers SysLogHandler mapPriority}@anchor{22ab}
@deffn {方法} mapPriority (levelname)

将日志记录级别名称映射到 syslog 优先级名称。 如果你使用自定义级别，或者如果默认算法不适合你的需要，你可能需要重载此方法。 默认算法将 @code{DEBUG}, @code{INFO}, @code{WARNING}, @code{ERROR} 和 @code{CRITICAL} 映射到等价的 syslog 名称，并将所有其他级别名称映射到 'warning'。
@end deffn
@end deffn

@node NTEventLogHandler,SMTPHandler,SysLogHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers nt-eventlog-handler}@anchor{22ac}@anchor{library/logging handlers nteventloghandler}@anchor{22ad}
@subsubsection NTEventLogHandler


@ref{22ae,,NTEventLogHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持将日志记录消息发送到本地 Windows NT, Windows 2000 或 Windows XP 事件日志。 在你使用它之前，你需要安装 Mark Hammond 的 Python Win32 扩展。

@geindex NTEventLogHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers NTEventLogHandler}@anchor{22ae}
@deffn {类} logging.handlers.NTEventLogHandler (appname, dllname=None, logtype='Application')

返回一个 @ref{22ae,,NTEventLogHandler} 类的新实例。 @emph{appname} 用来定义出现在事件日志中的应用名称。 将使用此名称创建适当的注册表条目。 @emph{dllname} 应当给出要包含在日志中的消息定义的 .dll 或 .exe 的完整限定路径名称（如未指定则会使用 @code{'win32service.pyd'} —— 此文件随 Win32 扩展安装且包含一些基本的消息定义占位符。 请注意使用这些占位符将使你的事件日志变得很大，因为整个消息源都会被放入日志。 如果你希望有较小的日志，你必须自行传入包含你想要在事件日志中使用的消息定义的 .dll 或 .exe 名称）。 @emph{logtype} 为 @code{'Application'}, @code{'System'} 或 @code{'Security'} 之一，且默认值为 @code{'Application'}。

@geindex close() (logging.handlers.NTEventLogHandler 方法)
@anchor{library/logging handlers logging handlers NTEventLogHandler close}@anchor{22af}
@deffn {方法} close ()

这时，你就可以从注册表中移除作为事件日志条目来源的应用名称。 但是，如果你这样做，你将无法如你所预期的那样在事件日志查看器中看到这些事件 —— 它必须能访问注册表来获取 .dll 名称。 当前版本并不会这样做。
@end deffn

@geindex emit() (logging.handlers.NTEventLogHandler 方法)
@anchor{library/logging handlers logging handlers NTEventLogHandler emit}@anchor{22b0}
@deffn {方法} emit (record)

确定消息 ID，事件类别和事件类型，然后将消息记录到 NT 事件日志中。
@end deffn

@geindex getEventCategory() (logging.handlers.NTEventLogHandler 方法)
@anchor{library/logging handlers logging handlers NTEventLogHandler getEventCategory}@anchor{22b1}
@deffn {方法} getEventCategory (record)

返回记录的事件类别。 如果你希望指定你自己的类别就要重载此方法。 此版本将返回 0。
@end deffn

@geindex getEventType() (logging.handlers.NTEventLogHandler 方法)
@anchor{library/logging handlers logging handlers NTEventLogHandler getEventType}@anchor{22b2}
@deffn {方法} getEventType (record)

返回记录的事件类型。 如果你希望指定你自己的类型就要重载此方法。 此版本将使用处理程序的 typemap 属性来执行映射，该属性在 @ref{e2b,,__init__()} 被设置为一个字典，其中包含 @code{DEBUG}, @code{INFO}, @code{WARNING}, @code{ERROR} 和 @code{CRITICAL} 的映射。 如果你使用你自己的级别，你将需要重载此方法或者在处理程序的 @emph{typemap} 属性中放置一个合适的字典。
@end deffn

@geindex getMessageID() (logging.handlers.NTEventLogHandler 方法)
@anchor{library/logging handlers logging handlers NTEventLogHandler getMessageID}@anchor{22b3}
@deffn {方法} getMessageID (record)

返回记录的消息 ID。 如果你使用你自己的消息，你可以通过将 @emph{msg} 传给日志记录器作为 ID 而非格式字符串实现此功能。 然后，你可以在这里使用字典查找来获取消息 ID。 此版本将返回 1，是 @code{win32service.pyd} 中的基本消息 ID。
@end deffn
@end deffn

@node SMTPHandler,MemoryHandler,NTEventLogHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers smtp-handler}@anchor{22b4}@anchor{library/logging handlers smtphandler}@anchor{22b5}
@subsubsection SMTPHandler


@ref{22b6,,SMTPHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持将日志记录消息通过 SMTP 发送到一个电子邮件地址。

@geindex SMTPHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers SMTPHandler}@anchor{22b6}
@deffn {类} logging.handlers.SMTPHandler (mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)

返回一个 @ref{22b6,,SMTPHandler} 类的新实例。 该实例使用电子邮件的发件人、收件人地址和主题行进行初始化。 @emph{toaddrs} 应当为字符串列表。 要指定一个非标准 SMTP 端口，请使用 (host, port) 元组格式作为 @emph{mailhost} 参数。 如果你使用一个字符串，则会使用标准 SMTP 端口。 如果你的 SMTP 服务器要求验证，你可以指定一个 (username, password) 元组作为 @emph{credentials} 参数。

要指定使用安全协议 (TLS)，请传入一个元组作为 @emph{secure} 参数。 这将仅在提供了验证凭据时才能被使用。 元组应当或是一个空元组，或是一个包含密钥文件名的单值元组，或是一个包含密钥文件和证书文件的 2 值元组。 （此元组会被传给 @ref{b65,,smtplib.SMTP.starttls()} 方法。）

可以使用 @emph{timeout} 参数为与 SMTP 服务器的通信指定超时限制。


3.3 新版功能: 增加了 @emph{timeout} 参数。


@geindex emit() (logging.handlers.SMTPHandler 方法)
@anchor{library/logging handlers logging handlers SMTPHandler emit}@anchor{22b7}
@deffn {方法} emit (record)

对记录执行格式化并将其发送到指定的地址。
@end deffn

@geindex getSubject() (logging.handlers.SMTPHandler 方法)
@anchor{library/logging handlers logging handlers SMTPHandler getSubject}@anchor{22b8}
@deffn {方法} getSubject (record)

如果你想要指定一个基于记录的主题行，请重载此方法。
@end deffn
@end deffn

@node MemoryHandler,HTTPHandler,SMTPHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers memory-handler}@anchor{22b9}@anchor{library/logging handlers memoryhandler}@anchor{22ba}
@subsubsection MemoryHandler


@ref{226d,,MemoryHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持在内存中缓冲日志记录，并定期将其刷新到 @emph{target} 处理程序中。 刷新会在缓冲区满的时候，或是在遇到特定或更高严重程度事件的时候发生。

@ref{226d,,MemoryHandler} 是更通用的 @ref{22bb,,BufferingHandler} 的子类，后者属于抽象类。 它会在内存中缓冲日志记录。 当每条记录被添加到缓冲区时，会通过调用 @code{shouldFlush()} 来检查缓冲区是否应当刷新。 如果应当刷新，则要使用 @code{flush()} 来执行刷新。

@geindex BufferingHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers BufferingHandler}@anchor{22bb}
@deffn {类} logging.handlers.BufferingHandler (capacity)

使用指定容量的缓冲区初始化处理程序。 这里，@emph{capacity} 是指缓冲的日志记录数量。

@geindex emit() (logging.handlers.BufferingHandler 方法)
@anchor{library/logging handlers logging handlers BufferingHandler emit}@anchor{22bc}
@deffn {方法} emit (record)

将记录添加到缓冲区。 如果 @ref{22bd,,shouldFlush()} 返回真值，则会调用 @ref{22be,,flush()} 来处理缓冲区。
@end deffn

@geindex flush() (logging.handlers.BufferingHandler 方法)
@anchor{library/logging handlers logging handlers BufferingHandler flush}@anchor{22be}
@deffn {方法} flush ()

你可以重载此方法来实现自定义的刷新行为。 此版本只是将缓冲区清空。
@end deffn

@geindex shouldFlush() (logging.handlers.BufferingHandler 方法)
@anchor{library/logging handlers logging handlers BufferingHandler shouldFlush}@anchor{22bd}
@deffn {方法} shouldFlush (record)

如果缓冲区容量已满则返回 @code{True}。 可以重载此方法以实现自定义的刷新策略。
@end deffn
@end deffn

@geindex MemoryHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers MemoryHandler}@anchor{226d}
@deffn {类} logging.handlers.MemoryHandler (capacity, flushLevel=ERROR, target=None, flushOnClose=True)

返回一个 @ref{226d,,MemoryHandler} 类的新实例。 该实例使用 @emph{capacity} 指定的缓冲区大小（要缓冲的记录数量）来初始化。 如果 @emph{flushLevel} 未指定，则使用 @code{ERROR}。 如果未指定 @emph{target}，则需要在此处理程序执行任何实际操作之前使用 @ref{22bf,,setTarget()} 来设置目标。 如果 @emph{flushOnClose} 指定为 @code{False}，则当处理程序被关闭时 @emph{不会} 刷新缓冲区。 如果未指定或指定为 @code{True}，则当处理程序被关闭时将会发生之前的缓冲区刷新行为。


在 3.6 版更改: 增加了 @emph{flushOnClose} 形参。


@geindex close() (logging.handlers.MemoryHandler 方法)
@anchor{library/logging handlers logging handlers MemoryHandler close}@anchor{22c0}
@deffn {方法} close ()

调用 @ref{22c1,,flush()}，设置目标为 @code{None} 并清空缓冲区。
@end deffn

@geindex flush() (logging.handlers.MemoryHandler 方法)
@anchor{library/logging handlers logging handlers MemoryHandler flush}@anchor{22c1}
@deffn {方法} flush ()

对于 @ref{226d,,MemoryHandler}，刷新是指将缓冲的记录发送到目标，如果存在目标的话。 当此行为发生时缓冲区也将被清空。 如果你想要不同的行为请重载此方法。
@end deffn

@geindex setTarget() (logging.handlers.MemoryHandler 方法)
@anchor{library/logging handlers logging handlers MemoryHandler setTarget}@anchor{22bf}
@deffn {方法} setTarget (target)

设置此处理程序的目标处理程序。
@end deffn

@geindex shouldFlush() (logging.handlers.MemoryHandler 方法)
@anchor{library/logging handlers logging handlers MemoryHandler shouldFlush}@anchor{22c2}
@deffn {方法} shouldFlush (record)

检测缓冲区是否已满或是有记录为 @emph{flushLevel} 或更高级别。
@end deffn
@end deffn

@node HTTPHandler,QueueHandler,MemoryHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers http-handler}@anchor{22c3}@anchor{library/logging handlers httphandler}@anchor{22c4}
@subsubsection HTTPHandler


@ref{80c,,HTTPHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持使用 @code{GET} 或 @code{POST} 语义将日志记录消息发送到 Web 服务器。

@geindex HTTPHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers HTTPHandler}@anchor{80c}
@deffn {类} logging.handlers.HTTPHandler (host, url, method='GET', secure=False, credentials=None, context=None)

返回一个 @ref{80c,,HTTPHandler} 类的新实例。 @emph{host} 可以为 @code{host:port} 的形式，如果你需要使用指定端口号的话。 如果没有指定 @emph{method}，则会使用 @code{GET}。 如果 @emph{secure} 为真值，则将使用 HTTPS 连接。 @emph{context} 形参可以设为一个 @ref{4f2,,ssl.SSLContext} 实例以配置用于 HTTPS 连接的 SSL 设置。 如果指定了 @emph{credentials}，它应当为包含 userid 和 password 的二元组，该元组将被放入使用 Basic 验证的 HTTP 'Authorization' 标头中。 如果你指定了 credentials，你还应当指定 secure=True 这样你的 userid 和 password 就不会以明文在线路上传输。


在 3.5 版更改: 增加了 @emph{context} 形参。


@geindex mapLogRecord() (logging.handlers.HTTPHandler 方法)
@anchor{library/logging handlers logging handlers HTTPHandler mapLogRecord}@anchor{22c5}
@deffn {方法} mapLogRecord (record)

基于 @code{record} 提供一个字典，它将被执行 URL 编码并发送至 Web 服务器。 默认实现仅返回 @code{record.__dict__}。 在只需将 @ref{9f5,,LogRecord} 的某个子集发送至 Web 服务器，或者需要对发送至服务器的内容进行更多定制时可以重载此方法。
@end deffn

@geindex emit() (logging.handlers.HTTPHandler 方法)
@anchor{library/logging handlers logging handlers HTTPHandler emit}@anchor{22c6}
@deffn {方法} emit (record)

将记录以经 URL 编码的形式发送至 Web 服务器。 会使用 @ref{22c5,,mapLogRecord()} 方法来将要发送的记录转换为字典。
@end deffn

@cartouche
@quotation 注解 
由于记录发送至 Web 服务器所需的预处理与通用的格式化操作不同，使用 @ref{2223,,setFormatter()} 来指定一个 @ref{220c,,Formatter} 用于 @ref{80c,,HTTPHandler} 是没有效果的。 此处理程序不会调用 @ref{222d,,format()}，而是调用 @ref{22c5,,mapLogRecord()} 然后再调用 @ref{884,,urllib.parse.urlencode()} 来以适合发送至 Web 服务器的形式对字典进行编码。
@end quotation
@end cartouche
@end deffn

@node QueueHandler,QueueListener,HTTPHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers queue-handler}@anchor{22c7}@anchor{library/logging handlers queuehandler}@anchor{22c8}
@subsubsection QueueHandler



3.2 新版功能.


@ref{22c9,,QueueHandler} 类位于 @ref{ac,,logging.handlers} 模块，它支持将日志记录消息发送到一个队列，例如在 @ref{da,,queue} 或 @ref{b7,,multiprocessing} 模块中实现的队列。

配合 @ref{80d,,QueueListener} 类使用，@ref{22c9,,QueueHandler} 可用来使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序以及其他服务于客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任何潜在的慢速操作（例如通过 @ref{22b6,,SMTPHandler} 发送邮件）都要在单独的线程上完成。

@geindex QueueHandler (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers QueueHandler}@anchor{22c9}
@deffn {类} logging.handlers.QueueHandler (queue)

返回一个 @ref{22c9,,QueueHandler} 类的新实例。 该实例使用队列来初始化以向其发送消息。 @emph{queue} 可以为任何队列类对象；它由 @ref{22ca,,enqueue()} 方法来使用，该方法需要知道如何向其发送消息。 队列 @emph{不要求} 具有任务跟踪 API，这意味着你可以为 @emph{queue} 使用 @ref{4d5,,SimpleQueue} 实例。

@geindex emit() (logging.handlers.QueueHandler 方法)
@anchor{library/logging handlers logging handlers QueueHandler emit}@anchor{22cb}
@deffn {方法} emit (record)

将准备 LogRecord 的结果排入队列。 如果发生了异常（例如由于有界队列已满），则会调用 @ref{222b,,handleError()} 方法来处理错误。 这可能导致记录被静默地丢弃 (如果 @code{logging.raiseExceptions} 为 @code{False}) 或者消息被打印到 @code{sys.stderr} (如果 @code{logging.raiseExceptions} 为 @code{True})。
@end deffn

@geindex prepare() (logging.handlers.QueueHandler 方法)
@anchor{library/logging handlers logging handlers QueueHandler prepare}@anchor{22cc}
@deffn {方法} prepare (record)

准备用于队列的记录。 此方法返回的对象会被排入队列。

基本实现会格式化记录以合并消息、参数以及可能存在的异常信息。 它还会从记录中原地移除无法封存的条目。

如果你想要将记录转换为 dict 或 JSON 字符串，或者发送记录被修改后的副本而让初始记录保持原样，则你可能会想要重载此方法。
@end deffn

@geindex enqueue() (logging.handlers.QueueHandler 方法)
@anchor{library/logging handlers logging handlers QueueHandler enqueue}@anchor{22ca}
@deffn {方法} enqueue (record)

使用 @code{put_nowait()} 将记录排入队列；如果你想要使用阻塞行为，或超时设置，或自定义的队列实现，则你可能会想要重载此方法。
@end deffn
@end deffn

@node QueueListener,,QueueHandler,logging handlers --- 日志处理程序
@anchor{library/logging handlers queue-listener}@anchor{22cd}@anchor{library/logging handlers queuelistener}@anchor{22ce}
@subsubsection QueueListener



3.2 新版功能.


@ref{80d,,QueueListener} 类位于 @ref{ac,,logging.handlers} 模块，它支持从一个队列接收日志记录消息，例如在 @ref{da,,queue} 或 @ref{b7,,multiprocessing} 模块中实现的队列。 消息是在内部线程中从队列接收并在同一线程上传递到一个或多个处理程序进行处理的。 尽管 @ref{80d,,QueueListener} 本身并不是一个处理程序，但由于它要与 @ref{22c9,,QueueHandler} 配合工作，因此也在此处介绍。

配合 @ref{22c9,,QueueHandler} 类使用，@ref{80d,,QueueListener} 可用来使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序以及其他服务与客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任何潜在的慢速动作（例如通过 @ref{22b6,,SMTPHandler} 发送邮件）都要在单独的线程上完成。

@geindex QueueListener (logging.handlers 中的类)
@anchor{library/logging handlers logging handlers QueueListener}@anchor{80d}
@deffn {类} logging.handlers.QueueListener (queue, *handlers, respect_handler_level=False)

返回一个 @ref{80d,,QueueListener} 类的新实例。 该实例初始化时要传入一个队列以向其发送消息，还要传入一个处理程序列表用来处理放置在队列中的条目。 队列可以是任何队列类对象；它会被原样传给 @ref{22cf,,dequeue()} 方法，该方法需要知道如何从其获取消息。 队列 @emph{不要求} 具有任务跟踪 API（但如提供则会使用它），这意味着你可以为 @emph{queue} 使用 @ref{4d5,,SimpleQueue} 实例。

如果 @code{respect_handler_level} 为 @code{True}，则在决定是否将消息传递给处理程序之前会遵循处理程序的级别（与消息的级别进行比较）；在其他情况下，其行为与之前的 Python 版本一致 —— 总是将每条消息传递给每个处理程序。


在 3.5 版更改: 增加了 @code{respect_handler_level} 参数。


@geindex dequeue() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener dequeue}@anchor{22cf}
@deffn {方法} dequeue (block)

从队列移出一条记录并将其返回，可以选择阻塞。

基本实现使用 @code{get()}。 如果你想要使用超时设置或自定义的队列实现，则你可能会想要重载此方法。
@end deffn

@geindex prepare() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener prepare}@anchor{22d0}
@deffn {方法} prepare (record)

准备一条要处理的记录。

该实现只是返回传入的记录。 如果你想要对记录执行任何自定义的 marshal 操作或在将其传给处理程序之前进行调整，则你可能会想要重载此方法。
@end deffn

@geindex handle() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener handle}@anchor{22d1}
@deffn {方法} handle (record)

处理一条记录。

此方法简单地循环遍历处理程序，向它们提供要处理的记录。 实际传给处理程序的对象就是从 @ref{22d0,,prepare()} 返回的对象。
@end deffn

@geindex start() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener start}@anchor{22d2}
@deffn {方法} start ()

启动监听器。

此方法启动一个后台线程来监视 LogRecords 队列以进行处理。
@end deffn

@geindex stop() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener stop}@anchor{22d3}
@deffn {方法} stop ()

停止监听器。

此方法要求线程终止，然后等待它完成终止操作。 请注意在你的应用程序退出之前如果你没有调用此方法，则可能会有一些记录在留在队列中，它们将不会被处理。
@end deffn

@geindex enqueue_sentinel() (logging.handlers.QueueListener 方法)
@anchor{library/logging handlers logging handlers QueueListener enqueue_sentinel}@anchor{22d4}
@deffn {方法} enqueue_sentinel ()

将一个标记写入队列以通知监听器退出。 此实现会使用 @code{put_nowait()}。 如果你想要使得超时设置或自定义的队列实现，则你可能会想要重载此方法。


3.3 新版功能.

@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{aa,,logging}

日志记录模块的 API 参考。

@item 模块 @ref{ab,,logging.config}

日志记录模块的配置 API 。
@end table


@node getpass --- 便携式密码输入工具,curses --- 终端字符单元显示的处理,logging handlers --- 日志处理程序,通用操作系统服务
@anchor{library/getpass doc}@anchor{22d5}@anchor{library/getpass getpass-portable-password-input}@anchor{22d6}@anchor{library/getpass module-getpass}@anchor{86}
@subsection @code{getpass} --- 便携式密码输入工具


@geindex getpass (模块)

@c Windows (& Mac?) support by Guido van Rossum.

@strong{源代码:} Lib/getpass.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/getpass.py}


__________________________________________________________________


@ref{86,,getpass} 模块提供了两个函数：

@geindex getpass() (在 getpass 模块中)
@anchor{library/getpass getpass getpass}@anchor{22d7}
@deffn {函数} getpass.getpass (prompt='Password: ', stream=None)

提示用户输入一个密码且不会回显。 用户会看到字符串 @emph{prompt} 作为提示，其默认值为 @code{'Password: '}。 在 Unix 上，如有必要提示会使用替换错误句柄写入到文件类对象 @emph{stream}。 @emph{stream} 默认指向控制终端 (@code{/dev/tty})，如果不可用则指向 @code{sys.stderr} (此参数在 Windows 上会被忽略)。

如果回显自由输入不可用则 getpass() 将回退为打印一条警告消息到 @emph{stream} 并且从 @code{sys.stdin} 读取同时发出 @ref{22d8,,GetPassWarning}。

@cartouche
@quotation 注解 
如果你从 IDLE 内部调用 getpass，输入可能是在你启动 IDLE 的终端中而非在 IDLE 窗口本身中完成。
@end quotation
@end cartouche
@end deffn

@geindex GetPassWarning
@anchor{library/getpass getpass GetPassWarning}@anchor{22d8}
@deffn {例外} getpass.GetPassWarning

一个当密码输入可能被回显时发出的 @ref{18ae,,UserWarning} 子类。
@end deffn

@geindex getuser() (在 getpass 模块中)
@anchor{library/getpass getpass getuser}@anchor{2080}
@deffn {函数} getpass.getuser ()

返回用户的“登录名称”。

此函数会按顺序检查环境变量 
@geindex LOGNAME
@geindex 环境变量; LOGNAME
@code{LOGNAME}, 
@geindex USER
@geindex 环境变量; USER
@code{USER}, 
@geindex LNAME
@geindex 环境变量; LNAME
@code{LNAME} 和 
@geindex USERNAME
@geindex 环境变量; USERNAME
@code{USERNAME}，并返回其中第一个被设置为非空字符串的值。 如果均未设置，则在支持 @ref{d6,,pwd} 模块的系统上将返回来自密码数据库的登录名，否则将引发一个异常。

通常情况下，此函数应优先于 @ref{207f,,os.getlogin()} 使用。
@end deffn

@node curses --- 终端字符单元显示的处理,curses textpad --- 用于 curses 程序的文本输入控件,getpass --- 便携式密码输入工具,通用操作系统服务
@anchor{library/curses doc}@anchor{22d9}@anchor{library/curses curses-terminal-handling-for-character-cell-displays}@anchor{22da}@anchor{library/curses module-curses}@anchor{2b}
@subsection @code{curses} --- 终端字符单元显示的处理


@geindex curses (模块)


__________________________________________________________________


@ref{2b,,curses} 模块提供了 curses 库的接口，这是可移植高级终端处理的事实标准。

虽然 curses 在 Unix 环境中使用最为广泛，但也有适用于 Windows，DOS 以及其他可能的系统的版本。此扩展模块旨在匹配 ncurses 的 API，这是一个部署在 Linux 和 Unix 的 BSD 变体上的开源 curses 库。

@cartouche
@quotation 注解 
每当文档提到 @strong{字符} 时，它可以被指定为一个整数，一个单字符 Unicode 字符串或者一个单字节的字节字符串。

每当此文档提到 @strong{字符串} 时，它可以被指定为一个 Unicode 字符串或者一个字节字符串。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
从 5.4 版本开始，ncurses 库使用 @code{nl_langinfo} 函数来决定如何解释非 ASCII 数据。这意味着你需要在程序中调用 @ref{2196,,locale.setlocale()} 函数，并使用一种系统中可用的编码方法来编码 Unicode 字符串。这个例子使用了系统默认的编码:

@example
import locale
locale.setlocale(locale.LC_ALL, '@w{'})
code = locale.getpreferredencoding()
@end example

然后使用 @emph{code} 作为 @ref{170,,str.encode()} 调用的编码。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item 模块 @ref{2c,,curses.ascii}

在 ASCII 字符上工作的工具，无论你的区域设置是什么。

@item 模块 @ref{2d,,curses.panel}

为 curses 窗口添加深度的面板栈扩展。

@item 模块 @ref{2e,,curses.textpad}

用于使 curses 支持 @code{Emacs} 式绑定的可编辑文本部件。

@item @ref{22db,,用 Python 进行 Curses 编程}

关于配合 Python 使用 curses 的教学材料，由 Andrew Kuchling 和 Eric Raymond 撰写。
@end table

Python 源码发布包的 Tools/demo/@footnote{https://github.com/python/cpython/tree/3.9/Tools/demo/} 目录包含了一些使用此模块所提供的 curses 绑定的示例程序。


@menu
* 函数: 函数<4>. 
* Window 对象:: 
* 常量: 常量<2>. 

@end menu

@node 函数<4>,Window 对象,,curses --- 终端字符单元显示的处理
@anchor{library/curses curses-functions}@anchor{22dc}@anchor{library/curses functions}@anchor{22dd}
@subsubsection 函数


@ref{2b,,curses} 模块定义了以下异常：

@geindex error
@anchor{library/curses curses error}@anchor{22de}
@deffn {例外} curses.error

当 curses 库中函数返回一个错误时引发的异常。
@end deffn

@cartouche
@quotation 注解 
只要一个函数或方法的 @emph{x} 或 @emph{y} 参数是可选项，它们会默认为当前光标位置。 而当 @emph{attr} 是可选项时，它会默认为 @code{A_NORMAL}。
@end quotation
@end cartouche

@ref{2b,,curses} 模块定义了以下函数：

@geindex baudrate() (在 curses 模块中)
@anchor{library/curses curses baudrate}@anchor{22df}
@deffn {函数} curses.baudrate ()

以每秒比特数为单位返回终端输出速度。 在软件终端模拟器上它将具有一个固定的最高值。 此函数出于历史原因被包括；在以前，它被用于写输出循环以提供时间延迟，并偶尔根据线路速度来改变接口。
@end deffn

@geindex beep() (在 curses 模块中)
@anchor{library/curses curses beep}@anchor{22e0}
@deffn {函数} curses.beep ()

发出短促的提醒声音。
@end deffn

@geindex can_change_color() (在 curses 模块中)
@anchor{library/curses curses can_change_color}@anchor{22e1}
@deffn {函数} curses.can_change_color ()

根据程序员能否改变终端显示的颜色返回 @code{True} 或 @code{False}。
@end deffn

@geindex cbreak() (在 curses 模块中)
@anchor{library/curses curses cbreak}@anchor{22e2}
@deffn {函数} curses.cbreak ()

进入 cbreak 模式。 在 cbreak 模式（有时也称为“稀有”模式）通常的 tty 行缓冲会被关闭并且字符可以被一个一个地读取。 但是，与原始模式不同，特殊字符（中断、退出、挂起和流程控制）会在 tty 驱动和调用程序上保留其效果。 首先调用 @ref{22e3,,raw()} 然后调用 @ref{22e2,,cbreak()} 会将终端置于 cbreak 模式。
@end deffn

@geindex color_content() (在 curses 模块中)
@anchor{library/curses curses color_content}@anchor{22e4}
@deffn {函数} curses.color_content (color_number)

返回颜色值 @emph{color_number} 中红、绿和蓝（RGB）分量的强度，此强度值必须介于 @code{0} 和 @code{COLORS - 1} 之间。 返回一个 3 元组，其中包含给定颜色的 R,G,B 值，它们必须介于 @code{0} (无分量) 和 @code{1000} (最大分量) 之间。
@end deffn

@geindex color_pair() (在 curses 模块中)
@anchor{library/curses curses color_pair}@anchor{22e5}
@deffn {函数} curses.color_pair (pair_number)

返回用于以指定颜色对显示文本的属性值。 仅支持前 256 个颜色对。 该属性值可与 @code{A_STANDOUT}, @code{A_REVERSE} 以及其他 @code{A_*} 属性组合使用。 @ref{22e6,,pair_number()} 是此函数的对应操作。
@end deffn

@geindex curs_set() (在 curses 模块中)
@anchor{library/curses curses curs_set}@anchor{22e7}
@deffn {函数} curses.curs_set (visibility)

设置光标状态。 @emph{visibility} 可设为 @code{0}, @code{1} 或 @code{2} 表示不可见、正常与高度可见。 如果终端支持所请求的可见性，则返回之前的光标状态；否则会引发异常。 在许多终端上，“正常可见”模式为下划线光标而“高度可见”模式为方块形光标。
@end deffn

@geindex def_prog_mode() (在 curses 模块中)
@anchor{library/curses curses def_prog_mode}@anchor{22e8}
@deffn {函数} curses.def_prog_mode ()

将当前终端模式保存为 "program" 模式，即正在运行的程序使用 curses 的模式。 （与其相对的是 "shell" 模式，即程序不使用 curses。） 对 @ref{22e9,,reset_prog_mode()} 的后续调用将恢复此模式。
@end deffn

@geindex def_shell_mode() (在 curses 模块中)
@anchor{library/curses curses def_shell_mode}@anchor{22ea}
@deffn {函数} curses.def_shell_mode ()

将当前终端模式保存为 "shell" 模式，即正在运行的程序不使用 curses 的模式。 （与其相对的是 "program" 模式，即程序使用 功能。） 对 @ref{22eb,,reset_shell_mode()} 的后续调用将恢复此模式。
@end deffn

@geindex delay_output() (在 curses 模块中)
@anchor{library/curses curses delay_output}@anchor{22ec}
@deffn {函数} curses.delay_output (ms)

在输出中插入 @emph{ms} 毫秒的暂停。
@end deffn

@geindex doupdate() (在 curses 模块中)
@anchor{library/curses curses doupdate}@anchor{22ed}
@deffn {函数} curses.doupdate ()

更新物理屏幕。 curses 库会保留两个数据结构，一个代表当前物理屏幕的内容以及一个虚拟屏幕代表需要的后续状态。 @ref{22ed,,doupdate()} 整体更新物理屏幕以匹配虚拟屏幕。

虚拟屏幕可以通过在写入操作例如在一个窗口上执行 @ref{22ee,,addstr()} 之后调用 @ref{22ef,,noutrefresh()} 来刷新。 普通的 @ref{22f0,,refresh()} 调用只是简单的 @code{noutrefresh()} 加 @code{doupdate()}；如果你需要更新多个窗口，你可以通过在所有窗口上发出 @code{noutrefresh()} 调用再加单次 @code{doupdate()} 来提升性能并可减少屏幕闪烁。
@end deffn

@geindex echo() (在 curses 模块中)
@anchor{library/curses curses echo}@anchor{22f1}
@deffn {函数} curses.echo ()

进入 echo 模式。 在 echo 模式下，输入的每个字符都会在输入后回显到屏幕上。
@end deffn

@geindex endwin() (在 curses 模块中)
@anchor{library/curses curses endwin}@anchor{22f2}
@deffn {函数} curses.endwin ()

撤销库的初始化，使终端返回正常状态。
@end deffn

@geindex erasechar() (在 curses 模块中)
@anchor{library/curses curses erasechar}@anchor{22f3}
@deffn {函数} curses.erasechar ()

将用户的当前擦除字符以单字节字节串对象的形式返回。 在 Unix 操作系统下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设置的。
@end deffn

@geindex filter() (在 curses 模块中)
@anchor{library/curses curses filter}@anchor{22f4}
@deffn {函数} curses.filter ()

如果要使用 @ref{22f4,,filter()} 例程，它必须在调用 @ref{22f5,,initscr()} 之前被调用。 其效果是在这些调用期间，
@geindex LINES
@geindex 环境变量; LINES
@code{LINES} 会被设为 @code{1}；@code{clear}, @code{cup}, @code{cud}, @code{cud1}, @code{cuu1}, @code{cuu}, @code{vpa} 等功能会被禁用；而 @code{home} 字符串会被设为 @code{cr} 的值。 其影响是光标会被限制在当前行内，屏幕刷新也是如此。 这可被用于启用单字符模式的行编辑而不触及屏幕的其余部分。
@end deffn

@geindex flash() (在 curses 模块中)
@anchor{library/curses curses flash}@anchor{22f6}
@deffn {函数} curses.flash ()

闪烁屏幕。 也就是将其改为反显并在很短的时间内将其改回原状。 有些人更喜欢这样的‘视觉响铃’而非 @ref{22e0,,beep()} 所产生的听觉提醒信号。
@end deffn

@geindex flushinp() (在 curses 模块中)
@anchor{library/curses curses flushinp}@anchor{22f7}
@deffn {函数} curses.flushinp ()

刷新所有输入缓冲区。 这会丢弃任何已被用户输入但尚未被程序处理的预输入内容。
@end deffn

@geindex getmouse() (在 curses 模块中)
@anchor{library/curses curses getmouse}@anchor{22f8}
@deffn {函数} curses.getmouse ()

在 @ref{22f9,,getch()} 返回 @code{KEY_MOUSE} 以发出鼠标事件信号之后，应当调用此方法来获取加入队列的鼠标事件，事件以一个 5 元组 @code{(id, x, y, z, bstate)} 来表示。 @emph{id} 为用于区分多个设置的 ID 值， @emph{x}, @emph{y}, @emph{z} 为事件的坐标。 (@emph{z} 目前未被使用。) @emph{bstate} 为一个整数值，其各比特位将设置用于表示事件类型，并将是下列常量中一个或多个按位 OR 的结果，其中 @emph{n} 是以 1 至 4 表示的键号: @code{BUTTONn_PRESSED}, @code{BUTTONn_RELEASED}, @code{BUTTONn_CLICKED}, @code{BUTTONn_DOUBLE_CLICKED}, @code{BUTTONn_TRIPLE_CLICKED}, @code{BUTTON_SHIFT}, @code{BUTTON_CTRL}, @code{BUTTON_ALT}。
@end deffn

@geindex getsyx() (在 curses 模块中)
@anchor{library/curses curses getsyx}@anchor{22fa}
@deffn {函数} curses.getsyx ()

将当前虚拟屏幕光标的坐标作为元组 @code{(y, x)} 返回。 如果 @ref{22fb,,leaveok} 当前为 @code{True}，则返回 @code{(-1, -1)}。
@end deffn

@geindex getwin() (在 curses 模块中)
@anchor{library/curses curses getwin}@anchor{22fc}
@deffn {函数} curses.getwin (file)

读取由之前的 @code{putwin()} 调用存放在文件中的窗口相关数据。 该例程随后将使用该数据创建并初始化一个新窗口，并返回该新窗口对象。
@end deffn

@geindex has_colors() (在 curses 模块中)
@anchor{library/curses curses has_colors}@anchor{22fd}
@deffn {函数} curses.has_colors ()

如果终端能显示彩色则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex has_ic() (在 curses 模块中)
@anchor{library/curses curses has_ic}@anchor{22fe}
@deffn {函数} curses.has_ic ()

如果终端具有插入和删除字符的功能则返回 @code{True}。 此函数仅是出于历史原因而被包括的，因为所有现代软件终端模拟器都具有这些功能。
@end deffn

@geindex has_il() (在 curses 模块中)
@anchor{library/curses curses has_il}@anchor{22ff}
@deffn {函数} curses.has_il ()

如果终端具有插入和删除字符功能，或者能够使用滚动区域来模拟这些功能则返回 @code{True}。 此函数仅是出于历史原因而被包括的，因为所有现代软件终端模拟器都具有这些功能。
@end deffn

@geindex has_key() (在 curses 模块中)
@anchor{library/curses curses has_key}@anchor{2300}
@deffn {函数} curses.has_key (ch)

接受一个键值 @emph{ch}，并在当前终端类型能识别出具有该值的键时返回 @code{True}。
@end deffn

@geindex halfdelay() (在 curses 模块中)
@anchor{library/curses curses halfdelay}@anchor{2301}
@deffn {函数} curses.halfdelay (tenths)

用于半延迟模式，与 cbreak 模式的类似之处是用户所键入的字符会立即对程序可用。 但是，在阻塞 @emph{tenths} 个十分之一秒之后，如果还未输入任何内容则将引发异常。 @emph{tenths} 值必须为 @code{1} 和 @code{255} 之间的数字。 使用 @ref{2302,,nocbreak()} 可退出半延迟模式。
@end deffn

@geindex init_color() (在 curses 模块中)
@anchor{library/curses curses init_color}@anchor{2303}
@deffn {函数} curses.init_color (color_number, r, g, b)

更改某个颜色的定义，接受要更改的颜色编号以及三个 RGB 值（表示红绿蓝三分量的强度）。 @emph{color_number} 值必须为 @code{0} 和 @cite{COLORS - 1} 之间的数字。 @emph{r}, @emph{g}, @emph{b} 值必须为 @code{0} 和 @code{1000} 之间的数字。 当使用 @ref{2303,,init_color()} 时，出现在屏幕上的对应颜色会立即按照新定义来更改。 此函数在大多数终端上都是无操作的；它仅会在 @ref{22e1,,can_change_color()} 返回 @code{True} 时生效。
@end deffn

@geindex init_pair() (在 curses 模块中)
@anchor{library/curses curses init_pair}@anchor{2304}
@deffn {函数} curses.init_pair (pair_number, fg, bg)

更改某个颜色对的定义。 它接受三个参数：要更改的颜色对编号，前景色编号和背景色编号。 @emph{pair_number} 值必须为 @code{1} 和 @code{COLOR_PAIRS - 1} 之间的数字（并且 @code{0} 号颜色对固定为黑底白字而无法更改）。 @emph{fg} 和 @emph{bg} 参数必须为 @code{0} 和 @code{COLORS - 1} 之间的数字，或者在调用 @ref{2305,,use_default_colors()} 之后则为 @code{-1}。 如果颜色对之前已被初始化，则屏幕会被刷新使得出现在屏幕上的该颜色会立即按照新定义来更改。
@end deffn

@geindex initscr() (在 curses 模块中)
@anchor{library/curses curses initscr}@anchor{22f5}
@deffn {函数} curses.initscr ()

初始化库。 返回代表整个屏幕的 @ref{2306,,窗口} 对象。

@cartouche
@quotation 注解 
如果打开终端时发生错误，则下层的 curses 库可能会导致解释器退出。
@end quotation
@end cartouche
@end deffn

@geindex is_term_resized() (在 curses 模块中)
@anchor{library/curses curses is_term_resized}@anchor{2307}
@deffn {函数} curses.is_term_resized (nlines, ncols)

如果 @ref{2308,,resize_term()} 会修改窗口结构则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex isendwin() (在 curses 模块中)
@anchor{library/curses curses isendwin}@anchor{2309}
@deffn {函数} curses.isendwin ()

如果 @ref{22f2,,endwin()} 已经被调用（即 curses 库已经被撤销初始化则返回 @code{True}。
@end deffn

@geindex keyname() (在 curses 模块中)
@anchor{library/curses curses keyname}@anchor{230a}
@deffn {函数} curses.keyname (k)

将编号为 @emph{k} 的键名称作为字节串对象返回。 生成可打印 ASCII 字符的键名称就是键所对应的字符。 Ctrl-键组合的键名称则是一个两字节的字节串对象，它由插入符 (@code{b'^'}) 加对应的可打印 ASCII 字符组成。 Alt-键组合 (128--255) 的键名称则是由前缀 @code{b'M-'} 加对应的可打印 ASCII 字符组成的字节串对象。
@end deffn

@geindex killchar() (在 curses 模块中)
@anchor{library/curses curses killchar}@anchor{230b}
@deffn {函数} curses.killchar ()

将用户的当前行删除字符以单字节字节串对象的形式返回。 在 Unix 操作系统下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设置的。
@end deffn

@geindex longname() (在 curses 模块中)
@anchor{library/curses curses longname}@anchor{230c}
@deffn {函数} curses.longname ()

返回一个字节串对象，其中包含描述当前终端的 terminfo 长名称字段。 详细描述的最大长度为 128 个字符。 它仅在调用 @ref{22f5,,initscr()} 之后才会被定义。
@end deffn

@geindex meta() (在 curses 模块中)
@anchor{library/curses curses meta}@anchor{230d}
@deffn {函数} curses.meta (flag)

如果 @emph{flag} 为 @code{True}，则允许输入 8 比特位的字符。 如果 @emph{flag} 为 @code{False}，则只允许 7 比特位的字符。
@end deffn

@geindex mouseinterval() (在 curses 模块中)
@anchor{library/curses curses mouseinterval}@anchor{230e}
@deffn {函数} curses.mouseinterval (interval)

以毫秒为单位设置能够被识别为点击的按下和释放事件之间可以间隔的最长时间，并返回之前的间隔值。 默认值为 200 毫秒，即五分之一秒。
@end deffn

@geindex mousemask() (在 curses 模块中)
@anchor{library/curses curses mousemask}@anchor{230f}
@deffn {函数} curses.mousemask (mousemask)

设置要报告的鼠标事件，并返回一个元组 @code{(availmask, oldmask)}。 @emph{availmask} 表明指定的鼠标事件中哪些可以被报告；当完全失败时将返回 @code{0}。 @emph{oldmask} 是给定窗口的鼠标事件之前的掩码值。 如果从未调用此函数，则不会报告任何鼠标事件。
@end deffn

@geindex napms() (在 curses 模块中)
@anchor{library/curses curses napms}@anchor{2310}
@deffn {函数} curses.napms (ms)

休眠 @emph{ms} 毫秒。
@end deffn

@geindex newpad() (在 curses 模块中)
@anchor{library/curses curses newpad}@anchor{2311}
@deffn {函数} curses.newpad (nlines, ncols)

创建并返回一个指向具有给定行数和列数新的面板数据结构的指针。 将面板作为窗口对象返回。

面板类似于窗口，区别在于它不受屏幕大小的限制，并且不必与屏幕的特定部分相关联。 面板可以在需要使用大窗口时使用，并且每次只需将窗口的一部分放在屏幕上。 面板不会发生自动刷新（例如由于滚动或输入回显）。 面板的 @ref{22f0,,refresh()} 和 @ref{22ef,,noutrefresh()} 方法需要 6 个参数来指定面板要显示的部分以及要用于显示的屏幕位置。 这些参数是 @emph{pminrow}, @emph{pmincol}, @emph{sminrow}, @emph{smincol}, @emph{smaxrow}, @emph{smaxcol}；@emph{p} 参数表示要显示的面板区域的左上角而 @emph{s} 参数定义了要显示的面板区域在屏幕上的剪切框。
@end deffn

@geindex newwin() (在 curses 模块中)
@anchor{library/curses curses newwin}@anchor{2312}
@deffn {函数} curses.newwin (nlines, ncols)

@deffnx {函数} curses.newwin (nlines, ncols, begin_y, begin_x)

返回一个新的 @ref{2306,,窗口}，其左上角位于 @code{(begin_y, begin_x)}，并且其高度/宽度为 @emph{nlines}/@emph{ncols}。

默认情况下，窗口将从指定位置扩展到屏幕的右下角。
@end deffn

@geindex nl() (在 curses 模块中)
@anchor{library/curses curses nl}@anchor{2313}
@deffn {函数} curses.nl ()

进入 newline 模式。 此模式会在输入时将回车转换为换行符，并在输出时将换行符转换为回车加换行。 newline 模式会在初始时启用。
@end deffn

@geindex nocbreak() (在 curses 模块中)
@anchor{library/curses curses nocbreak}@anchor{2302}
@deffn {函数} curses.nocbreak ()

退出 cbreak 模式。 返回具有行缓冲的正常 "cooked" 模式。
@end deffn

@geindex noecho() (在 curses 模块中)
@anchor{library/curses curses noecho}@anchor{2314}
@deffn {函数} curses.noecho ()

退出 echo 模式。 关闭输入字符的回显。
@end deffn

@geindex nonl() (在 curses 模块中)
@anchor{library/curses curses nonl}@anchor{2315}
@deffn {函数} curses.nonl ()

退出 newline 模式。 停止在输入时将回车转换为换行，并停止在输出时从换行到换行/回车的底层转换（但这不会改变 @code{addch('\n')} 的行为，此行为总是在虚拟屏幕上执行相当于回车加换行的操作）。 当停止转换时，curses 有时能使纵向移动加快一些；并且，它将能够在输入时检测回车键。
@end deffn

@geindex noqiflush() (在 curses 模块中)
@anchor{library/curses curses noqiflush}@anchor{2316}
@deffn {函数} curses.noqiflush ()

当使用 @code{noqiflush()} 例程时，与 @code{INTR}, @code{QUIT} 和 @code{SUSP} 字符相关联的输入和输出队列的正常刷新将不会被执行。 如果你希望在处理程序退出后还能继续输出，就像没有发生过中断一样，你可能会想要在信号处理程序中调用 @code{noqiflush()}。
@end deffn

@geindex noraw() (在 curses 模块中)
@anchor{library/curses curses noraw}@anchor{2317}
@deffn {函数} curses.noraw ()

退出 raw 模式。 返回具有行缓冲的正常 "cooked" 模式。
@end deffn

@geindex pair_content() (在 curses 模块中)
@anchor{library/curses curses pair_content}@anchor{2318}
@deffn {函数} curses.pair_content (pair_number)

返回包含对应于所请求颜色对的元组 @code{(fg, bg)}。 @emph{pair_number} 的值必须在 @code{0} 和 @code{COLOR_PAIRS - 1} 之间。
@end deffn

@geindex pair_number() (在 curses 模块中)
@anchor{library/curses curses pair_number}@anchor{22e6}
@deffn {函数} curses.pair_number (attr)

返回通过属性值 @emph{attr} 所设置的颜色对的编号。 @ref{22e5,,color_pair()} 是此函数的对应操作。
@end deffn

@geindex putp() (在 curses 模块中)
@anchor{library/curses curses putp}@anchor{2319}
@deffn {函数} curses.putp (str)

等价于 @code{tputs(str, 1, putchar)}；为当前终端发出指定 terminfo 功能的值。 请注意 @ref{2319,,putp()} 的输出总是前往标准输出。
@end deffn

@geindex qiflush() (在 curses 模块中)
@anchor{library/curses curses qiflush}@anchor{231a}
@deffn {函数} curses.qiflush ([flag])

如果 @emph{flag} 为 @code{False}，则效果与调用 @ref{2316,,noqiflush()} 相同。 如果 @emph{flag} 为 @code{True} 或未提供参数，则在读取这些控制字符时队列将被刷新。
@end deffn

@geindex raw() (在 curses 模块中)
@anchor{library/curses curses raw}@anchor{22e3}
@deffn {函数} curses.raw ()

进入 raw 模式。 在 raw 模式下，正常的行缓冲和对中断、退出、挂起和流程控制键的处理会被关闭；字符会被逐个地提交给 curses 输入函数。
@end deffn

@geindex reset_prog_mode() (在 curses 模块中)
@anchor{library/curses curses reset_prog_mode}@anchor{22e9}
@deffn {函数} curses.reset_prog_mode ()

将终端恢复到 "program" 模式，如之前由 @ref{22e8,,def_prog_mode()} 所保存的一样。
@end deffn

@geindex reset_shell_mode() (在 curses 模块中)
@anchor{library/curses curses reset_shell_mode}@anchor{22eb}
@deffn {函数} curses.reset_shell_mode ()

将终端恢复到 "shell" 模式，如之前由 @ref{22ea,,def_shell_mode()} 所保存的一样。
@end deffn

@geindex resetty() (在 curses 模块中)
@anchor{library/curses curses resetty}@anchor{231b}
@deffn {函数} curses.resetty ()

将终端模式恢复到最后一次调用 @ref{231c,,savetty()} 时的状态。
@end deffn

@geindex resize_term() (在 curses 模块中)
@anchor{library/curses curses resize_term}@anchor{2308}
@deffn {函数} curses.resize_term (nlines, ncols)

由 @ref{231d,,resizeterm()} 用来执行大部分工作的后端函数；当调整窗口大小时，@ref{2308,,resize_term()} 会以空白填充扩展区域。 调用方应用程序应当以适当的数据填充这些区域。 @code{resize_term()} 函数会尝试调整所有窗口的大小。 但是，由于面板的调用约定，在不与应用程序进行额外交互的情况下是无法调整其大小的。
@end deffn

@geindex resizeterm() (在 curses 模块中)
@anchor{library/curses curses resizeterm}@anchor{231d}
@deffn {函数} curses.resizeterm (nlines, ncols)

将标准窗口和当前窗口的大小调整为指定的尺寸，并调整由 curses 库所使用的记录窗口尺寸的其他记录数据（特别是 SIGWINCH 处理程序）。
@end deffn

@geindex savetty() (在 curses 模块中)
@anchor{library/curses curses savetty}@anchor{231c}
@deffn {函数} curses.savetty ()

将终端模式的当前状态保存在缓冲区中，可供 @ref{231b,,resetty()} 使用。
@end deffn

@geindex get_escdelay() (在 curses 模块中)
@anchor{library/curses curses get_escdelay}@anchor{198}
@deffn {函数} curses.get_escdelay ()

提取通过 @ref{199,,set_escdelay()} 设置的值。


3.9 新版功能.

@end deffn

@geindex set_escdelay() (在 curses 模块中)
@anchor{library/curses curses set_escdelay}@anchor{199}
@deffn {函数} curses.set_escdelay (ms)

设置读取一个转义字符后要等待的毫秒数，以区分在键盘上输入的单个转义字符与通过光标和功能键发送的转义序列。


3.9 新版功能.

@end deffn

@geindex get_tabsize() (在 curses 模块中)
@anchor{library/curses curses get_tabsize}@anchor{19a}
@deffn {函数} curses.get_tabsize ()

提取通过 @ref{19b,,set_tabsize()} 设置的值。


3.9 新版功能.

@end deffn

@geindex set_tabsize() (在 curses 模块中)
@anchor{library/curses curses set_tabsize}@anchor{19b}
@deffn {函数} curses.set_tabsize (size)

设置 curses 库在将制表符添加到窗口时将制表符转换为空格所使用的列数。


3.9 新版功能.

@end deffn

@geindex setsyx() (在 curses 模块中)
@anchor{library/curses curses setsyx}@anchor{231e}
@deffn {函数} curses.setsyx (y, x)

将虚拟屏幕光标设置到 @emph{y}, @emph{x}。 如果 @emph{y} 和 @emph{x} 均为 @code{-1}，则 @ref{22fb,,leaveok} 将设为 @code{True}。
@end deffn

@geindex setupterm() (在 curses 模块中)
@anchor{library/curses curses setupterm}@anchor{231f}
@deffn {函数} curses.setupterm (term=None, fd=-1)

初始化终端。 @emph{term} 为给出终端名称的字符串或为 @code{None}；如果省略或为 @code{None}，则将使用 
@geindex TERM
@geindex 环境变量; TERM
@code{TERM} 环境变量的值。 @emph{fd} 是任何初始化序列将被发送到的文件描述符；如未指定或为 @code{-1}，则将使用 @code{sys.stdout} 的文件描述符。
@end deffn

@geindex start_color() (在 curses 模块中)
@anchor{library/curses curses start_color}@anchor{2320}
@deffn {函数} curses.start_color ()

如果程序员想要使用颜色，则必须在任何其他颜色操作例程被调用之前调用它。 在 @ref{22f5,,initscr()} 之后立即调用此例程是一个很好的做法。

@ref{2320,,start_color()} 会初始化八种基本颜色（黑、红、绿、黄、蓝、品、青和白）以及 @ref{2b,,curses} 模块中的两个全局变量 @code{COLORS} 和 @code{COLOR_PAIRS}，其中包含终端可支持的颜色和颜色对的最大数量。 它还会将终端中的颜色恢复为终端刚启动时的值。
@end deffn

@geindex termattrs() (在 curses 模块中)
@anchor{library/curses curses termattrs}@anchor{2321}
@deffn {函数} curses.termattrs ()

返回终端所支持的所有视频属性逻辑 OR 的值。 此信息适用于当 curses 程序需要对屏幕外观进行完全控制的情况。
@end deffn

@geindex termname() (在 curses 模块中)
@anchor{library/curses curses termname}@anchor{2322}
@deffn {函数} curses.termname ()

将环境变量 
@geindex TERM
@geindex 环境变量; TERM
@code{TERM} 的值截短至 14 个字节，作为字节串对象返回。
@end deffn

@geindex tigetflag() (在 curses 模块中)
@anchor{library/curses curses tigetflag}@anchor{2323}
@deffn {函数} curses.tigetflag (capname)

将与 terminfo 功能名称 @emph{capname} 相对应的布尔功能值以整数形式返回。 如果 @emph{capname} 不是一个布尔功能则返回 @code{-1}，如果其被取消或不存在于终端描述中则返回 @code{0}。
@end deffn

@geindex tigetnum() (在 curses 模块中)
@anchor{library/curses curses tigetnum}@anchor{2324}
@deffn {函数} curses.tigetnum (capname)

将与 terminfo 功能名称 @emph{capname} 相对应的数字功能值以整数形式返回。 如果 @emph{capname} 不是一个数字功能则返回 @code{-2}，如果其被取消或不存在于终端描述中则返回 @code{-1}。
@end deffn

@geindex tigetstr() (在 curses 模块中)
@anchor{library/curses curses tigetstr}@anchor{2325}
@deffn {函数} curses.tigetstr (capname)

将与 terminfo 功能名称 @emph{capname} 相对应的字符串功能值以字节串对象形式返回。 如果 @emph{capname} 不是一个 terminfo "字符串功能" 或者如果其被取消或不存在于终端描述中则返回 @code{None}。
@end deffn

@geindex tparm() (在 curses 模块中)
@anchor{library/curses curses tparm}@anchor{2326}
@deffn {函数} curses.tparm (str[, ...])

使用提供的形参初始化字节串对象 @emph{str}，其中 @emph{str} 应当是从 terminfo 数据库获取的参数化字符串。 例如 @code{tparm(tigetstr("cup"), 5, 3)} 的结果可能为 @code{b'\033[6;4H'}，实际结果将取决于终端类型。
@end deffn

@geindex typeahead() (在 curses 模块中)
@anchor{library/curses curses typeahead}@anchor{2327}
@deffn {函数} curses.typeahead (fd)

指定将被用于预输入检查的文件描述符 @emph{fd}。 如果 @emph{fd} 为 @code{-1}，则不执行预输入检查。

curses 库会在更新屏幕时通过定期查找预输入来执行 "断行优化"。 如果找到了输入，并且输入是来自于 tty，则会将当前更新推迟至 refresh 或 doupdate 再次被调用的时候，以便允许更快地响应预先输入的命令。 此函数允许为预输入检查指定其他的文件描述符。
@end deffn

@geindex unctrl() (在 curses 模块中)
@anchor{library/curses curses unctrl}@anchor{2328}
@deffn {函数} curses.unctrl (ch)

返回一个字节串对象作为字符 @emph{ch} 的可打印表示形式。 控制字符会表示为一个变换符加相应的字符，例如 @code{b'^C'}。 可打印字符则会保持原样。
@end deffn

@geindex ungetch() (在 curses 模块中)
@anchor{library/curses curses ungetch}@anchor{2329}
@deffn {函数} curses.ungetch (ch)

推送 @emph{ch} 以便让下一个 @ref{22f9,,getch()} 返回该字符。

@cartouche
@quotation 注解 
在 @code{getch()} 被调用之前只能推送一个 @emph{ch}。
@end quotation
@end cartouche
@end deffn

@geindex update_lines_cols() (在 curses 模块中)
@anchor{library/curses curses update_lines_cols}@anchor{7c3}
@deffn {函数} curses.update_lines_cols ()

更新 
@geindex LINES
@geindex 环境变量; LINES
@code{LINES} 和 
@geindex COLS
@geindex 环境变量; COLS
@code{COLS}。 适用于检测屏幕大小的手动调整。


3.5 新版功能.

@end deffn

@geindex unget_wch() (在 curses 模块中)
@anchor{library/curses curses unget_wch}@anchor{ac8}
@deffn {函数} curses.unget_wch (ch)

推送 @emph{ch} 以便让下一个 @ref{ac7,,get_wch()} 返回该字符。

@cartouche
@quotation 注解 
在 @code{get_wch()} 被调用之前只能推送一个 @emph{ch}。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@geindex ungetmouse() (在 curses 模块中)
@anchor{library/curses curses ungetmouse}@anchor{232a}
@deffn {函数} curses.ungetmouse (id, x, y, z, bstate)

将 @code{KEY_MOUSE} 事件推送到输入队列，将其与给定的状态数据进行关联。
@end deffn

@geindex use_env() (在 curses 模块中)
@anchor{library/curses curses use_env}@anchor{232b}
@deffn {函数} curses.use_env (flag)

如果使用此函数，则应当在调用 @ref{22f5,,initscr()} 或 newterm 之前调用它。 当 @emph{flag} 为 @code{False} 时，将会使用在 terminfo 数据库中指定的行和列的值，即使设置了环境变量 
@geindex LINES
@geindex 环境变量; LINES
@code{LINES} 和 
@geindex COLUMNS
@geindex 环境变量; COLUMNS
@code{COLUMNS} (默认使用)，或者如果 curses 是在窗口中运行（在此情况下如果未设置 
@geindex LINES
@geindex 环境变量; LINES
@code{LINES} 和 
@geindex COLUMNS
@geindex 环境变量; COLUMNS
@code{COLUMNS} 则默认行为将是使用窗口大小）。
@end deffn

@geindex use_default_colors() (在 curses 模块中)
@anchor{library/curses curses use_default_colors}@anchor{2305}
@deffn {函数} curses.use_default_colors ()

允许在支持此特性的终端上使用默认的颜色值。 使用此函数可在你的应用程序中支持透明效果。 默认颜色会被赋给颜色编号 @code{-1}。 举例来说，在调用此函数后，@code{init_pair(x, curses.COLOR_RED, -1)} 会将颜色对 @emph{x} 初始化为红色前景和默认颜色背景。
@end deffn

@geindex wrapper() (在 curses 模块中)
@anchor{library/curses curses wrapper}@anchor{3cc}
@deffn {函数} curses.wrapper (func, /, *args, **kwargs)

初始化 curses 并调用另一个可调用对象 @emph{func}，该对象应当为你的使用 curses 的应用程序的其余部分。 如果应用程序引发了异常，此函数将在重新引发异常并生成回溯信息之前将终端恢复到正常状态。 随后可调用对象 @emph{func} 会被传入主窗口 'stdscr' 作为其第一个参数，再带上其他所有传给 @code{wrapper()} 的参数。 在调用 @emph{func} 之前，@code{wrapper()} 会启用 cbreak 模式，关闭回显，启用终端键盘，并在终端具有颜色支持的情况下初始化颜色。 在退出时（无论是正常退出还是异常退出）它会恢复 cooked 模式，打开回显，并禁用终端键盘。
@end deffn

@node Window 对象,常量<2>,函数<4>,curses --- 终端字符单元显示的处理
@anchor{library/curses curses-window-objects}@anchor{2306}@anchor{library/curses window-objects}@anchor{232c}
@subsubsection Window 对象


Window 对象会由上面的 @ref{22f5,,initscr()} 和 @ref{2312,,newwin()} 返回，它具有以下方法和属性:

@geindex addch() (curses.window 方法)
@anchor{library/curses curses window addch}@anchor{232d}
@deffn {方法} window.addch (ch[, attr])

@deffnx {方法} window.addch (y, x, ch[, attr])

将带有属性 @emph{attr} 的字符 @emph{ch} 绘制到 @code{(y, x)}，覆盖之前在该位置上绘制的任何字符。 默认情况下，字符的位置和属性均为窗口对象的当前设置。

@cartouche
@quotation 注解 
在窗口、子窗口或面板之外写入会引发 @ref{22de,,curses.error}。 尝试在窗口、子窗口或面板的右下角写入将在字符被打印之后导致异常被引发。
@end quotation
@end cartouche
@end deffn

@geindex addnstr() (curses.window 方法)
@anchor{library/curses curses window addnstr}@anchor{232e}
@deffn {方法} window.addnstr (str, n[, attr])

@deffnx {方法} window.addnstr (y, x, str, n[, attr])

将带有属性 @emph{attr} 的字符串 @emph{str} 中的至多 @emph{n} 个字符绘制到 @code{(y, x)}，覆盖之前在屏幕上的任何内容。
@end deffn

@geindex addstr() (curses.window 方法)
@anchor{library/curses curses window addstr}@anchor{22ee}
@deffn {方法} window.addstr (str[, attr])

@deffnx {方法} window.addstr (y, x, str[, attr])

将带有属性 @emph{attr} 的字符串 @emph{str} 绘制到 @code{(y, x)}，覆盖之前在屏幕上的任何内容。

@cartouche
@quotation 注解 

@itemize *

@item 
在窗口、子窗口或面板之外写入会引发 @ref{22de,,curses.error}。 尝试在窗口、子窗口或面板的右下角写入将在字符串被打印之后导致异常被引发。

@item 
此 Python 模块的后端 ncurses 中的一个缺陷@footnote{https://bugs.python.org/issue35924} 会在调整窗口大小时导致段错误。 此缺陷已在 ncurses-6.1-20190511 中被修复。 如果你必须使用较早版本的 ncurses，则你只要在调用 @ref{22ee,,addstr()} 时不传入嵌入了换行符的 @emph{str} 即可避免触发此错误。 请为每一行分别调用 @ref{22ee,,addstr()}。
@end itemize
@end quotation
@end cartouche
@end deffn

@geindex attroff() (curses.window 方法)
@anchor{library/curses curses window attroff}@anchor{232f}
@deffn {方法} window.attroff (attr)

从应用于写入到当前窗口的 "background" 集中移除属性 @emph{attr}。
@end deffn

@geindex attron() (curses.window 方法)
@anchor{library/curses curses window attron}@anchor{2330}
@deffn {方法} window.attron (attr)

向应用于写入到当前窗口的 "background" 集中添加属性 @emph{attr}。
@end deffn

@geindex attrset() (curses.window 方法)
@anchor{library/curses curses window attrset}@anchor{2331}
@deffn {方法} window.attrset (attr)

将 "background" 属性集设为 @emph{attr}。 该集合初始时为 @code{0} (无属性)。
@end deffn

@geindex bkgd() (curses.window 方法)
@anchor{library/curses curses window bkgd}@anchor{2332}
@deffn {方法} window.bkgd (ch[, attr])

将窗口 background 特征属性设为带有属性 @emph{attr} 的字符 @emph{ch}。 随后此修改将应用于放置到该窗口中的每个字符。


@itemize *

@item 
窗口中每个字符的属性会被修改为新的 background 属性。

@item 
不论之前的 background 字符出现在哪里，它都会被修改为新的 background 字符。
@end itemize
@end deffn

@geindex bkgdset() (curses.window 方法)
@anchor{library/curses curses window bkgdset}@anchor{2333}
@deffn {方法} window.bkgdset (ch[, attr])

设置窗口的背景。 窗口的背景由字符和属性的任意组合构成。 背景的属性部分会与写入窗口的所有非空白字符合并（即 OR 运算）。 背景和字符和属性部分均会与空白字符合并。 背景将成为字符的特征属性并在任何滚动与插入/删除行/字符操作中与字符一起移动。
@end deffn

@geindex border() (curses.window 方法)
@anchor{library/curses curses window border}@anchor{2334}
@deffn {方法} window.border ([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])

在窗口边缘绘制边框。每个参数指定用于边界特定部分的字符;请参阅下表了解更多详情。

@cartouche
@quotation 注解 
任何形参的值为 @code{0} 都将导致该形参使用默认字符。 关键字形参 @emph{不可} 被使用。 默认字符在下表中列出:
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

参数

@tab

描述

@tab

默认值

@item

@emph{ls}

@tab

左侧

@tab

@code{ACS_VLINE}

@item

@emph{rs}

@tab

右侧

@tab

@code{ACS_VLINE}

@item

@emph{ts}

@tab

顶部

@tab

@code{ACS_HLINE}

@item

@emph{bs}

@tab

底部

@tab

@code{ACS_HLINE}

@item

@emph{tl}

@tab

左上角

@tab

@code{ACS_ULCORNER}

@item

@emph{tr}

@tab

右上角

@tab

@code{ACS_URCORNER}

@item

@emph{bl}

@tab

左下角

@tab

@code{ACS_LLCORNER}

@item

@emph{br}

@tab

右下角

@tab

@code{ACS_LRCORNER}

@end multitable

@end deffn

@geindex box() (curses.window 方法)
@anchor{library/curses curses window box}@anchor{2335}
@deffn {方法} window.box ([vertch, horch])

类似于 @ref{2334,,border()}，但 @emph{ls} 和 @emph{rs} 均为 @emph{vertch} 而 @emph{ts} 和 @emph{bs} 均为 @emph{horch}。 此函数总是会使用默认的转角字符。
@end deffn

@geindex chgat() (curses.window 方法)
@anchor{library/curses curses window chgat}@anchor{2336}
@deffn {方法} window.chgat (attr)

@deffnx {方法} window.chgat (num, attr)

@deffnx {方法} window.chgat (y, x, attr)

@deffnx {方法} window.chgat (y, x, num, attr)

在当前光标位置或是在所提供的位置 @code{(y, x)} 设置 @emph{num} 个字符的属性。 如果 @emph{num} 未给出或为 @code{-1}，则将属性设置到所有字符上直至行尾。 如果提供了位置 @code{(y, x)} 则此函数会将光标移至该位置。 修改过的行将使用 @ref{2337,,touchline()} 方法处理以便下次窗口刷新时内容会重新显示。
@end deffn

@geindex clear() (curses.window 方法)
@anchor{library/curses curses window clear}@anchor{2338}
@deffn {方法} window.clear ()

类似于 @ref{2339,,erase()}，但还会导致在下次调用 @ref{22f0,,refresh()} 时整个窗口被重新绘制。
@end deffn

@geindex clearok() (curses.window 方法)
@anchor{library/curses curses window clearok}@anchor{233a}
@deffn {方法} window.clearok (flag)

如果 @emph{flag} 为 @code{True}，则在下次调用 @ref{22f0,,refresh()} 时将完全清除窗口。
@end deffn

@geindex clrtobot() (curses.window 方法)
@anchor{library/curses curses window clrtobot}@anchor{233b}
@deffn {方法} window.clrtobot ()

从光标位置开始擦除直至窗口末端：光标以下的所有行都会被删除，然后会执行 @ref{233c,,clrtoeol()} 的等效操作。
@end deffn

@geindex clrtoeol() (curses.window 方法)
@anchor{library/curses curses window clrtoeol}@anchor{233c}
@deffn {方法} window.clrtoeol ()

从光标位置开始擦除直至行尾。
@end deffn

@geindex cursyncup() (curses.window 方法)
@anchor{library/curses curses window cursyncup}@anchor{233d}
@deffn {方法} window.cursyncup ()

更新窗口所有上级窗口的当前光标位置以反映窗口的当前光标位置。
@end deffn

@geindex delch() (curses.window 方法)
@anchor{library/curses curses window delch}@anchor{233e}
@deffn {方法} window.delch ([y, x])

删除位于 @code{(y, x)} 的任何字符。
@end deffn

@geindex deleteln() (curses.window 方法)
@anchor{library/curses curses window deleteln}@anchor{233f}
@deffn {方法} window.deleteln ()

删除在光标之下的行。 所有后续的行都会上移一行。
@end deffn

@geindex derwin() (curses.window 方法)
@anchor{library/curses curses window derwin}@anchor{2340}
@deffn {方法} window.derwin (begin_y, begin_x)

@deffnx {方法} window.derwin (nlines, ncols, begin_y, begin_x)

"derive window" 的缩写，@ref{2340,,derwin()} 与调用 @ref{2341,,subwin()} 等效，不同之处在于 @emph{begin_y} 和 @emph{begin_x} 是想对于窗口的初始位置，而不是相对于整个屏幕。 返回代表所派生窗口的窗口对象。
@end deffn

@geindex echochar() (curses.window 方法)
@anchor{library/curses curses window echochar}@anchor{2342}
@deffn {方法} window.echochar (ch[, attr])

使用属性 @emph{attr} 添加字符 @emph{ch}，并立即在窗口上调用 @ref{22f0,,refresh()}。
@end deffn

@geindex enclose() (curses.window 方法)
@anchor{library/curses curses window enclose}@anchor{2343}
@deffn {方法} window.enclose (y, x)

检测给定的相对屏幕的字符-单元格坐标是否被给定的窗口所包围，返回 @code{True} 或 @code{False}。 它适用于确定是哪个屏幕窗口子集包围着某个鼠标事件的位置。
@end deffn

@geindex encoding (curses.window 属性)
@anchor{library/curses curses window encoding}@anchor{ac6}
@deffn {属性} window.encoding

用于编码方法参数（Unicode 字符串和字符）的编码格式。 encoding 属性是在创建子窗口时从父窗口继承的，例如通过 @ref{2341,,window.subwin()}。 默认情况下，会使用当前区域的编码格式 (参见 @ref{4b4,,locale.getpreferredencoding()})。


3.3 新版功能.

@end deffn

@geindex erase() (curses.window 方法)
@anchor{library/curses curses window erase}@anchor{2339}
@deffn {方法} window.erase ()

清空窗口。
@end deffn

@geindex getbegyx() (curses.window 方法)
@anchor{library/curses curses window getbegyx}@anchor{2344}
@deffn {方法} window.getbegyx ()

返回左上角坐标的元组 @code{(y, x)}。
@end deffn

@geindex getbkgd() (curses.window 方法)
@anchor{library/curses curses window getbkgd}@anchor{2345}
@deffn {方法} window.getbkgd ()

返回给定窗口的当前背景字符/属性对。
@end deffn

@geindex getch() (curses.window 方法)
@anchor{library/curses curses window getch}@anchor{22f9}
@deffn {方法} window.getch ([y, x])

获取一个字符。 请注意所返回的整数 @emph{不一定} 要在 ASCII 范围以内：功能键、小键盘键等等是由大于 255 的数字表示的。 在无延迟模式下，如果没有输入则返回 @code{-1}，在其他情况下都会等待直至有键被按下。
@end deffn

@geindex get_wch() (curses.window 方法)
@anchor{library/curses curses window get_wch}@anchor{ac7}
@deffn {方法} window.get_wch ([y, x])

获取一个宽字符。 对于大多数键都是返回一个字符，对于功能键、小键盘键和其他特殊键则是返回一个整数。 在无延迟模式下，如果没有输入则引发一个异常。


3.3 新版功能.

@end deffn

@geindex getkey() (curses.window 方法)
@anchor{library/curses curses window getkey}@anchor{2346}
@deffn {方法} window.getkey ([y, x])

获取一个字符，返回一个字符串而不是像 @ref{22f9,,getch()} 那样返回一个整数。 功能键、小键盘键和其他特殊键则是返回一个包含键名的多字节字符串。 在无延迟模式下，如果没有输入则引发一个异常。
@end deffn

@geindex getmaxyx() (curses.window 方法)
@anchor{library/curses curses window getmaxyx}@anchor{2347}
@deffn {方法} window.getmaxyx ()

返回窗口高度和宽度的元组 @code{(y, x)}。
@end deffn

@geindex getparyx() (curses.window 方法)
@anchor{library/curses curses window getparyx}@anchor{2348}
@deffn {方法} window.getparyx ()

将此窗口相对于父窗口的起始坐标作为元组 @code{(y, x)} 返回。 如果此窗口没有父窗口则返回 @code{(-1, -1)}。
@end deffn

@geindex getstr() (curses.window 方法)
@anchor{library/curses curses window getstr}@anchor{2349}
@deffn {方法} window.getstr ()

@deffnx {方法} window.getstr (n)

@deffnx {方法} window.getstr (y, x)

@deffnx {方法} window.getstr (y, x, n)

从用户读取一个字节串对象，附带基本的行编辑功能。
@end deffn

@geindex getyx() (curses.window 方法)
@anchor{library/curses curses window getyx}@anchor{234a}
@deffn {方法} window.getyx ()

返回当前光标相对于窗口左上角的位置的元组 @code{(y, x)}。
@end deffn

@geindex hline() (curses.window 方法)
@anchor{library/curses curses window hline}@anchor{234b}
@deffn {方法} window.hline (ch, n)

@deffnx {方法} window.hline (y, x, ch, n)

显示一条起始于 @code{(y, x)} 长度为 @emph{n} 个字符 @emph{ch} 的水平线。
@end deffn

@geindex idcok() (curses.window 方法)
@anchor{library/curses curses window idcok}@anchor{234c}
@deffn {方法} window.idcok (flag)

如果 @emph{flag} 为 @code{False}，curses 将不再考虑使用终端的硬件插入/删除字符功能；如果 @emph{flag} 为 @code{True}，则会启用字符插入和删除。 当 curses 首次初始化时，默认会启用字符插入/删除。
@end deffn

@geindex idlok() (curses.window 方法)
@anchor{library/curses curses window idlok}@anchor{234d}
@deffn {方法} window.idlok (flag)

如果 @emph{flag} 为 @code{True}，@ref{2b,,curses} 将尝试使用硬件行编辑功能。 否则，行插入/删除会被禁用。
@end deffn

@geindex immedok() (curses.window 方法)
@anchor{library/curses curses window immedok}@anchor{234e}
@deffn {方法} window.immedok (flag)

如果 @emph{flag} 为 @code{True}，窗口图像中的任何改变都会自动导致窗口被刷新；你不必再自己调用 @ref{22f0,,refresh()}。 但是，这可能会由于重复调用 wrefresh 而显著降低性能。 此选项默认被禁用。
@end deffn

@geindex inch() (curses.window 方法)
@anchor{library/curses curses window inch}@anchor{234f}
@deffn {方法} window.inch ([y, x])

返回窗口中给定位置上的字符。 下面的 8 个比特位是字符本身，上面的比特位则为属性。
@end deffn

@geindex insch() (curses.window 方法)
@anchor{library/curses curses window insch}@anchor{2350}
@deffn {方法} window.insch (ch[, attr])

@deffnx {方法} window.insch (y, x, ch[, attr])

将带有属性 @emph{attr} 的字符 @emph{ch} 绘制到 @code{(y, x)}，将该行从位置 @emph{x} 开始右移一个字符。
@end deffn

@geindex insdelln() (curses.window 方法)
@anchor{library/curses curses window insdelln}@anchor{2351}
@deffn {方法} window.insdelln (nlines)

在指定窗口的当前行上方插入 @emph{nlines} 行。 下面的 @emph{nlines} 行将丢失。 对于 @emph{nlines} 为负值的情况，则从光标下方的行开始删除 @emph{nlines} 行，并将其余的行向上移动。 下面的 @emph{nlines} 行会被清空。 当前光标位置将保持不变。
@end deffn

@geindex insertln() (curses.window 方法)
@anchor{library/curses curses window insertln}@anchor{2352}
@deffn {方法} window.insertln ()

在光标下方插入一个空行。 所有后续的行都会下移一行。
@end deffn

@geindex insnstr() (curses.window 方法)
@anchor{library/curses curses window insnstr}@anchor{2353}
@deffn {方法} window.insnstr (str, n[, attr])

@deffnx {方法} window.insnstr (y, x, str, n[, attr])

在光标下方的字符之前插入一个至多为 @emph{n} 个字符的字符串（字符数量将与该行相匹配）。 如果 @emph{n} 为零或负数，则插入整个字符串。 光标右边的所有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（在移到可能指定的 @emph{y}, @emph{x} 之后）。
@end deffn

@geindex insstr() (curses.window 方法)
@anchor{library/curses curses window insstr}@anchor{2354}
@deffn {方法} window.insstr (str[, attr])

@deffnx {方法} window.insstr (y, x, str[, attr])

在光标下方的字符之前插入一个字符串（字符数量将与该行相匹配）。 光标右边的所有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（在移到可能指定的 @emph{y}, @emph{x} 之后）。
@end deffn

@geindex instr() (curses.window 方法)
@anchor{library/curses curses window instr}@anchor{2355}
@deffn {方法} window.instr ([n])

@deffnx {方法} window.instr (y, x[, n])

返回从窗口的当前光标位置，或者指定的  @emph{y}, @emph{x} 开始提取的字符所对应的字节串对象。 属性会从字符中去除。 如果指定了 @emph{n}，@ref{2355,,instr()} 将返回长度至多为 @emph{n} 个字符的字符串（不包括末尾的 NUL）。
@end deffn

@geindex is_linetouched() (curses.window 方法)
@anchor{library/curses curses window is_linetouched}@anchor{2356}
@deffn {方法} window.is_linetouched (line)

如果指定的行自上次调用 @ref{22f0,,refresh()} 后发生了改变则返回 @code{True}；否则返回 @code{False}。 如果 @emph{line} 对于给定的窗口不可用则会引发 @ref{22de,,curses.error} 异常。
@end deffn

@geindex is_wintouched() (curses.window 方法)
@anchor{library/curses curses window is_wintouched}@anchor{2357}
@deffn {方法} window.is_wintouched ()

如果指定的窗口自上次调用 @ref{22f0,,refresh()} 后发生了改变则返回 @code{True}；否则返回 @code{False}。
@end deffn

@geindex keypad() (curses.window 方法)
@anchor{library/curses curses window keypad}@anchor{2358}
@deffn {方法} window.keypad (flag)

如果 @emph{flag} 为 @code{True}，则某些键（小键盘键、功能键等）生成的转义序列将由 @ref{2b,,curses} 来解析。 如果 @emph{flag} 为 @code{False}，转义序列将保持在输入流中的原样。
@end deffn

@geindex leaveok() (curses.window 方法)
@anchor{library/curses curses window leaveok}@anchor{22fb}
@deffn {方法} window.leaveok (flag)

如果 @emph{flag} 为 @code{True}，则在更新时光标将停留在原地，而不是在“光标位置”。 这将可以减少光标的移动。 在可能的情况下光标将变为不可见。

如果 @emph{flag} 为 @code{False}，光标在更新后将总是位于“光标位置”。
@end deffn

@geindex move() (curses.window 方法)
@anchor{library/curses curses window move}@anchor{2359}
@deffn {方法} window.move (new_y, new_x)

将光标移至 @code{(new_y, new_x)}。
@end deffn

@geindex mvderwin() (curses.window 方法)
@anchor{library/curses curses window mvderwin}@anchor{235a}
@deffn {方法} window.mvderwin (y, x)

让窗口在其父窗口内移动。 窗口相对于屏幕的参数不会被更改。 此例程用于在屏幕的相同物理位置显示父窗口的不同部分。
@end deffn

@geindex mvwin() (curses.window 方法)
@anchor{library/curses curses window mvwin}@anchor{235b}
@deffn {方法} window.mvwin (new_y, new_x)

移动窗口以使其左上角位于 @code{(new_y, new_x)}。
@end deffn

@geindex nodelay() (curses.window 方法)
@anchor{library/curses curses window nodelay}@anchor{235c}
@deffn {方法} window.nodelay (flag)

如果 @emph{flag} 为 @code{True}，则 @ref{22f9,,getch()} 将为非阻塞的。
@end deffn

@geindex notimeout() (curses.window 方法)
@anchor{library/curses curses window notimeout}@anchor{235d}
@deffn {方法} window.notimeout (flag)

如果 @emph{flag} 为 @code{True}，则转义序列将不会发生超时。

如果 @emph{flag} 为 @code{False}，则在几毫秒之后，转义序列将不会被解析，并将保持在输入流中的原样。
@end deffn

@geindex noutrefresh() (curses.window 方法)
@anchor{library/curses curses window noutrefresh}@anchor{22ef}
@deffn {方法} window.noutrefresh ()

标记为刷新但保持等待。 此函数会更新代表预期窗口状态的数据结构，但并不强制更新物理屏幕。 要完成后者，请调用 @ref{22ed,,doupdate()}。
@end deffn

@geindex overlay() (curses.window 方法)
@anchor{library/curses curses window overlay}@anchor{235e}
@deffn {方法} window.overlay (destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

将窗口覆盖在 @emph{destwin} 上方。 窗口的大小不必相同，只有重叠的区域会被复制。 此复制是非破坏性的，这意味着当前背景字符不会覆盖掉 @emph{destwin} 的旧内容。

为了获得对被复制区域的细粒度控制，可以使用 @ref{235e,,overlay()} 的第二种形式。 @emph{sminrow} 和 @emph{smincol} 是源窗口的左上角坐标，而其他变量则在目标窗口中标记出一个矩形。
@end deffn

@geindex overwrite() (curses.window 方法)
@anchor{library/curses curses window overwrite}@anchor{235f}
@deffn {方法} window.overwrite (destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

将窗口覆盖在 @emph{destwin} 上方。 窗口的大小不必相同，此时只有重叠的区域会被复制。 此复制是破坏性的，这意味着当前背景字符会覆盖掉 @emph{destwin} 的旧内容。

为了获得对被复制区域的细粒度控制，可以使用 @ref{235f,,overwrite()} 的第二种形式。 @emph{sminrow} 和 @emph{smincol} 是源窗口的左上角坐标，而其他变量则在目标窗口中标记出一个矩形。
@end deffn

@geindex putwin() (curses.window 方法)
@anchor{library/curses curses window putwin}@anchor{2360}
@deffn {方法} window.putwin (file)

将关联到窗口的所有数据写入到所提供的文件对象。 此信息可在以后使用 @ref{22fc,,getwin()} 函数来提取。
@end deffn

@geindex redrawln() (curses.window 方法)
@anchor{library/curses curses window redrawln}@anchor{2361}
@deffn {方法} window.redrawln (beg, num)

指明从 @emph{beg} 行开始的 @emph{num} 个屏幕行已被破坏并且应当在下次 @ref{22f0,,refresh()} 调用时完全重绘。
@end deffn

@geindex redrawwin() (curses.window 方法)
@anchor{library/curses curses window redrawwin}@anchor{2362}
@deffn {方法} window.redrawwin ()

触碰整个窗口，以使其在下次 @ref{22f0,,refresh()} 调用时完全重绘。
@end deffn

@geindex refresh() (curses.window 方法)
@anchor{library/curses curses window refresh}@anchor{22f0}
@deffn {方法} window.refresh ([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])

立即更新显示（将实际屏幕与之前的绘制/删除方法进行同步）。

6 个可选参数仅在窗口为使用 @ref{2311,,newpad()} 创建的面板时可被指定。 需要额外的形参来指定所涉及到的是面板和屏幕的哪一部分。 @emph{pminrow} 和 @emph{pmincol} 指定要在面板中显示的矩形的左上角。 @emph{sminrow}, @emph{smincol}, @emph{smaxrow} 和 @emph{smaxcol} 指定要在屏幕中显示的矩形的边。 要在面板中显示的矩形的右下角是根据屏幕坐标计算出来的，由于矩形的大小必须相同。 两个矩形都必须完全包含在其各自的结构之内。 负的 @emph{pminrow}, @emph{pmincol}, @emph{sminrow} 或 @emph{smincol} 值会被视为将它们设为零值。
@end deffn

@geindex resize() (curses.window 方法)
@anchor{library/curses curses window resize}@anchor{2363}
@deffn {方法} window.resize (nlines, ncols)

为 curses 窗口重新分配存储空间以将其尺寸调整为指定的值。 如果任一维度的尺寸大于当前值，则窗口的数据将以具有合并了当前背景渲染（由 @ref{2333,,bkgdset()} 设置）的空白来填充。
@end deffn

@geindex scroll() (curses.window 方法)
@anchor{library/curses curses window scroll}@anchor{2364}
@deffn {方法} window.scroll ([lines=1])

将屏幕或滚动区域向上滚动 @emph{lines} 行。
@end deffn

@geindex scrollok() (curses.window 方法)
@anchor{library/curses curses window scrollok}@anchor{2365}
@deffn {方法} window.scrollok (flag)

控制当一个窗口的光标移出窗口或滚动区域边缘时会发生什么，这可能是在底端行执行换行操作，或者在最后一行输入最后一个字符导致的结果。 如果 @emph{flag} 为 @code{False}，光标会留在底端行。 如果 @emph{flag} 为 @code{True}，窗口会向上滚动一行。 请注意为了在终端上获得实际的滚动效果，还需要调用 @ref{234d,,idlok()}。
@end deffn

@geindex setscrreg() (curses.window 方法)
@anchor{library/curses curses window setscrreg}@anchor{2366}
@deffn {方法} window.setscrreg (top, bottom)

设置从 @emph{top} 行至 @emph{bottom} 行的滚动区域。 所有滚动操作将在此区域中进行。
@end deffn

@geindex standend() (curses.window 方法)
@anchor{library/curses curses window standend}@anchor{2367}
@deffn {方法} window.standend ()

关闭 standout 属性。 在某些终端上此操作会有关闭所有属性的副作用。
@end deffn

@geindex standout() (curses.window 方法)
@anchor{library/curses curses window standout}@anchor{2368}
@deffn {方法} window.standout ()

启用属性 @emph{A_STANDOUT}。
@end deffn

@geindex subpad() (curses.window 方法)
@anchor{library/curses curses window subpad}@anchor{2369}
@deffn {方法} window.subpad (begin_y, begin_x)

@deffnx {方法} window.subpad (nlines, ncols, begin_y, begin_x)

返回一个子窗口，其左上角位于 @code{(begin_y, begin_x)}，并且其宽度/高度为 @emph{ncols}/@emph{nlines}。
@end deffn

@geindex subwin() (curses.window 方法)
@anchor{library/curses curses window subwin}@anchor{2341}
@deffn {方法} window.subwin (begin_y, begin_x)

@deffnx {方法} window.subwin (nlines, ncols, begin_y, begin_x)

返回一个子窗口，其左上角位于 @code{(begin_y, begin_x)}，并且其宽度/高度为 @emph{ncols}/@emph{nlines}。

默认情况下，子窗口将从指定位置扩展到窗口的右下角。
@end deffn

@geindex syncdown() (curses.window 方法)
@anchor{library/curses curses window syncdown}@anchor{236a}
@deffn {方法} window.syncdown ()

触碰已在上级窗口上被触碰的每个位置。 此例程由 @ref{22f0,,refresh()} 调用，因此几乎从不需要手动调用。
@end deffn

@geindex syncok() (curses.window 方法)
@anchor{library/curses curses window syncok}@anchor{236b}
@deffn {方法} window.syncok (flag)

如果 @emph{flag} 为 @code{True}，则 @ref{236c,,syncup()} 会在窗口发生改变的任何时候自动被调用。
@end deffn

@geindex syncup() (curses.window 方法)
@anchor{library/curses curses window syncup}@anchor{236c}
@deffn {方法} window.syncup ()

触碰已在窗口中被改变的此窗口的各个上级窗口中的所有位置。
@end deffn

@geindex timeout() (curses.window 方法)
@anchor{library/curses curses window timeout}@anchor{236d}
@deffn {方法} window.timeout (delay)

为窗口设置阻塞或非阻塞读取行为。 如果 @emph{delay} 为负值，则会使用阻塞读取（这将无限期地等待输入）。 如果 @emph{delay} 为零，则会使用非阻塞读取，并且当没有输入在等待时 @ref{22f9,,getch()} 将返回 @code{-1}。 如果 @emph{delay} 为正值，则 @ref{22f9,,getch()} 将阻塞 @emph{delay} 毫秒，并且当此延时结束时仍无输入将返回 @code{-1}。
@end deffn

@geindex touchline() (curses.window 方法)
@anchor{library/curses curses window touchline}@anchor{2337}
@deffn {方法} window.touchline (start, count[, changed])

假定从行 @emph{start} 开始的 @emph{count} 行已被更改。 如果提供了 @emph{changed}，它将指明是将受影响的行标记为已更改 (@emph{changed}@code{=True}) 还是未更改 (@emph{changed}@code{=False})。
@end deffn

@geindex touchwin() (curses.window 方法)
@anchor{library/curses curses window touchwin}@anchor{236e}
@deffn {方法} window.touchwin ()

假定整个窗口已被更改，其目的是用于绘制优化。
@end deffn

@geindex untouchwin() (curses.window 方法)
@anchor{library/curses curses window untouchwin}@anchor{236f}
@deffn {方法} window.untouchwin ()

将自上次调用 @ref{22f0,,refresh()} 以来窗口中的所有行标记为未改变。
@end deffn

@geindex vline() (curses.window 方法)
@anchor{library/curses curses window vline}@anchor{2370}
@deffn {方法} window.vline (ch, n)

@deffnx {方法} window.vline (y, x, ch, n)

显示一条起始于 @code{(y, x)} 长度为 @emph{n} 个字符 @emph{ch} 的垂直线。
@end deffn

@node 常量<2>,,Window 对象,curses --- 终端字符单元显示的处理
@anchor{library/curses constants}@anchor{2371}
@subsubsection 常量


@ref{2b,,curses} 模块定义了以下数据成员:

@geindex ERR() (在 curses 模块中)
@anchor{library/curses curses ERR}@anchor{2372}
@deffn {数据} curses.ERR

一些返回整数的 curses 例程，例如 @ref{22f9,,getch()}，在失败时将返回 @ref{2372,,ERR}。
@end deffn

@geindex OK() (在 curses 模块中)
@anchor{library/curses curses OK}@anchor{2373}
@deffn {数据} curses.OK

一些返回整数的 curses 例程，例如 @ref{2310,,napms()}，在成功时将返回 @ref{2373,,OK}。
@end deffn

@geindex version() (在 curses 模块中)
@anchor{library/curses curses version}@anchor{2374}
@deffn {数据} curses.version

一个代表当前模块版本的字节串对象。 也作 @code{__version__}。
@end deffn

@geindex ncurses_version() (在 curses 模块中)
@anchor{library/curses curses ncurses_version}@anchor{2f7}
@deffn {数据} curses.ncurses_version

一个具名元组，它包含构成 ncurses 库版本号的三个数字: @emph{major}, @emph{minor} 和 @emph{patch}。 三个值均为整数。 三个值也可通过名称来访问，因此 @code{curses.ncurses_version[0]} 等价于 @code{curses.ncurses_version.major}，依此类推。

可用性：如果使用了 ncurses 库。


3.8 新版功能.

@end deffn

有些常量可用于指定字符单元属性。 实际可用的常量取决于具体的系统。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

含义

@item

@code{A_ALTCHARSET}

@tab

备用字符集模式

@item

@code{A_BLINK}

@tab

闪烁模式

@item

@code{A_BOLD}

@tab

粗体模式

@item

@code{A_DIM}

@tab

暗淡模式

@item

@code{A_INVIS}

@tab

不可见或空白模式

@item

@code{A_ITALIC}

@tab

斜体模式

@item

@code{A_NORMAL}

@tab

正常属性

@item

@code{A_PROTECT}

@tab

保护模式

@item

@code{A_REVERSE}

@tab

反转背景色和前景色

@item

@code{A_STANDOUT}

@tab

突出模式

@item

@code{A_UNDERLINE}

@tab

下划线模式

@item

@code{A_HORIZONTAL}

@tab

水平突出显示

@item

@code{A_LEFT}

@tab

左高亮

@item

@code{A_LOW}

@tab

底部高亮

@item

@code{A_RIGHT}

@tab

右高亮

@item

@code{A_TOP}

@tab

顶部高亮

@item

@code{A_VERTICAL}

@tab

垂直突出显示

@item

@code{A_CHARTEXT}

@tab

用于提取字符的位掩码

@end multitable



3.7 新版功能: @code{A_ITALIC} was added.


有几个常量可用于提取某些方法返回的相应属性。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

位掩码

@tab

含义

@item

@code{A_ATTRIBUTES}

@tab

用于提取属性的位掩码

@item

@code{A_CHARTEXT}

@tab

用于提取字符的位掩码

@item

@code{A_COLOR}

@tab

用于提取颜色对字段信息的位掩码

@end multitable


键由名称以 @code{KEY_} 开头的整数常量引用。确切的可用键取决于系统。

@c XXX this table is far too large! should it be alphabetized?


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

关键常数

@tab

键

@item

@code{KEY_MIN}

@tab

最小键值

@item

@code{KEY_BREAK}

@tab

中断键（不可靠）

@item

@code{KEY_DOWN}

@tab

向下箭头

@item

@code{KEY_UP}

@tab

向上箭头

@item

@code{KEY_LEFT}

@tab

向左箭头

@item

@code{KEY_RIGHT}

@tab

向右箭头

@item

@code{KEY_HOME}

@tab

Home 键 (上+左箭头)

@item

@code{KEY_BACKSPACE}

@tab

退格（不可靠）

@item

@code{KEY_F0}

@tab

功能键。 支持至多 64 个功能键。

@item

@code{KEY_Fn}

@tab

功能键 @emph{n} 的值

@item

@code{KEY_DL}

@tab

删除行

@item

@code{KEY_IL}

@tab

插入行

@item

@code{KEY_DC}

@tab

删除字符

@item

@code{KEY_IC}

@tab

插入字符或进入插入模式

@item

@code{KEY_EIC}

@tab

退出插入字符模式

@item

@code{KEY_CLEAR}

@tab

清空屏幕

@item

@code{KEY_EOS}

@tab

清空至屏幕底部

@item

@code{KEY_EOL}

@tab

清空至行尾

@item

@code{KEY_SF}

@tab

向前滚动 1 行

@item

@code{KEY_SR}

@tab

向后滚动 1 行 (反转)

@item

@code{KEY_NPAGE}

@tab

下一页

@item

@code{KEY_PPAGE}

@tab

上一页

@item

@code{KEY_STAB}

@tab

设置制表符

@item

@code{KEY_CTAB}

@tab

清除制表符

@item

@code{KEY_CATAB}

@tab

清除所有制表符

@item

@code{KEY_ENTER}

@tab

回车或发送 (不可靠)

@item

@code{KEY_SRESET}

@tab

软 (部分) 重置 (不可靠)

@item

@code{KEY_RESET}

@tab

重置或硬重置 (不可靠)

@item

@code{KEY_PRINT}

@tab

打印

@item

@code{KEY_LL}

@tab

Home 向下或到底 (左下)

@item

@code{KEY_A1}

@tab

键盘的左上角

@item

@code{KEY_A3}

@tab

键盘的右上角

@item

@code{KEY_B2}

@tab

键盘的中心

@item

@code{KEY_C1}

@tab

键盘左下方

@item

@code{KEY_C3}

@tab

键盘右下方

@item

@code{KEY_BTAB}

@tab

回退制表符

@item

@code{KEY_BEG}

@tab

Beg (开始)

@item

@code{KEY_CANCEL}

@tab

取消

@item

@code{KEY_CLOSE}

@tab

关闭

@item

@code{KEY_COMMAND}

@tab

Cmd (命令行)

@item

@code{KEY_COPY}

@tab

复制

@item

@code{KEY_CREATE}

@tab

创建

@item

@code{KEY_END}

@tab

End

@item

@code{KEY_EXIT}

@tab

退出

@item

@code{KEY_FIND}

@tab

查找

@item

@code{KEY_HELP}

@tab

帮助

@item

@code{KEY_MARK}

@tab

标记

@item

@code{KEY_MESSAGE}

@tab

消息

@item

@code{KEY_MOVE}

@tab

移动

@item

@code{KEY_NEXT}

@tab

下一个

@item

@code{KEY_OPEN}

@tab

打开

@item

@code{KEY_OPTIONS}

@tab

选项

@item

@code{KEY_PREVIOUS}

@tab

Prev (上一个)

@item

@code{KEY_REDO}

@tab

重做

@item

@code{KEY_REFERENCE}

@tab

Ref (引用)

@item

@code{KEY_REFRESH}

@tab

刷新

@item

@code{KEY_REPLACE}

@tab

替换

@item

@code{KEY_RESTART}

@tab

重启

@item

@code{KEY_RESUME}

@tab

恢复

@item

@code{KEY_SAVE}

@tab

保存

@item

@code{KEY_SBEG}

@tab

Shift + Beg (开始)

@item

@code{KEY_SCANCEL}

@tab

Shift + Cancel

@item

@code{KEY_SCOMMAND}

@tab

Shift + Command

@item

@code{KEY_SCOPY}

@tab

Shift + Copy

@item

@code{KEY_SCREATE}

@tab

Shift + Create

@item

@code{KEY_SDC}

@tab

Shift + 删除字符

@item

@code{KEY_SDL}

@tab

Shift + 删除行

@item

@code{KEY_SELECT}

@tab

选择

@item

@code{KEY_SEND}

@tab

Shift + End

@item

@code{KEY_SEOL}

@tab

Shift + 清空行

@item

@code{KEY_SEXIT}

@tab

Shift + 退出

@item

@code{KEY_SFIND}

@tab

Shift + 查找

@item

@code{KEY_SHELP}

@tab

Shift + 帮助

@item

@code{KEY_SHOME}

@tab

Shift + Home

@item

@code{KEY_SIC}

@tab

Shift + 输入

@item

@code{KEY_SLEFT}

@tab

Shift + 向左箭头

@item

@code{KEY_SMESSAGE}

@tab

Shift + 消息

@item

@code{KEY_SMOVE}

@tab

Shift + 移动

@item

@code{KEY_SNEXT}

@tab

Shift + 下一个

@item

@code{KEY_SOPTIONS}

@tab

Shift + 选项

@item

@code{KEY_SPREVIOUS}

@tab

Shift + 上一个

@item

@code{KEY_SPRINT}

@tab

Shift + 打印

@item

@code{KEY_SREDO}

@tab

Shift + 重做

@item

@code{KEY_SREPLACE}

@tab

Shift + 替换

@item

@code{KEY_SRIGHT}

@tab

Shift + 向右箭头

@item

@code{KEY_SRSUME}

@tab

Shift + 恢复

@item

@code{KEY_SSAVE}

@tab

Shift + 保存

@item

@code{KEY_SSUSPEND}

@tab

Shift + 挂起

@item

@code{KEY_SUNDO}

@tab

Shift + 撤销

@item

@code{KEY_SUSPEND}

@tab

挂起

@item

@code{KEY_UNDO}

@tab

撤销操作

@item

@code{KEY_MOUSE}

@tab

鼠标事件已发生

@item

@code{KEY_RESIZE}

@tab

终端大小改变事件

@item

@code{KEY_MAX}

@tab

最大键值

@end multitable


在VT100及其软件仿真（例如X终端仿真器）上，通常至少有四个功能键（ @code{KEY_F1}, @code{KEY_F2}, @code{KEY_F3}, @code{KEY_F4} ）可用，并且箭头键以明显的方式映射到 @code{KEY_UP}, @code{KEY_DOWN}, @code{KEY_LEFT} 和 @code{KEY_RIGHT} 。如果您的机器有一个PC键盘，可以安全地使用箭头键和十二个功能键（旧的PC键盘可能只有十个功能键）;此外，以下键盘映射是标准的：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@headitem

键帽

@tab

常数

@item

@code{Insert}

@tab

KEY_IC

@item

@code{Delete}

@tab

KEY_DC

@item

@code{Home}

@tab

KEY_HOME

@item

@code{End}

@tab

KEY_END

@item

@code{Page Up}

@tab

KEY_PPAGE

@item

@code{Page Down}

@tab

KEY_NPAGE

@end multitable


下表列出了替代字符集中的字符。 这些字符继承自 VT100 终端，在 X 终端等软件模拟器上通常均为可用。 当没有可用的图形时，curses 会回退为粗糙的可打印 ASCII 近似符号。

@cartouche
@quotation 注解 
只有在调用 @ref{22f5,,initscr()} 之后才能使用它们
@end quotation
@end cartouche


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ACS代码

@tab

含义

@item

@code{ACS_BBSS}

@tab

右上角的别名

@item

@code{ACS_BLOCK}

@tab

实心方块

@item

@code{ACS_BOARD}

@tab

正方形

@item

@code{ACS_BSBS}

@tab

水平线的别名

@item

@code{ACS_BSSB}

@tab

左上角的别名

@item

@code{ACS_BSSS}

@tab

顶部 T 型的别名

@item

@code{ACS_BTEE}

@tab

底部 T 型

@item

@code{ACS_BULLET}

@tab

正方形

@item

@code{ACS_CKBOARD}

@tab

棋盘（点刻）

@item

@code{ACS_DARROW}

@tab

向下箭头

@item

@code{ACS_DEGREE}

@tab

等级符

@item

@code{ACS_DIAMOND}

@tab

菱形

@item

@code{ACS_GEQUAL}

@tab

大于或等于

@item

@code{ACS_HLINE}

@tab

水平线

@item

@code{ACS_LANTERN}

@tab

灯形符号

@item

@code{ACS_LARROW}

@tab

向左箭头

@item

@code{ACS_LEQUAL}

@tab

小于或等于

@item

@code{ACS_LLCORNER}

@tab

左下角

@item

@code{ACS_LRCORNER}

@tab

右下角

@item

@code{ACS_LTEE}

@tab

左侧 T 型

@item

@code{ACS_NEQUAL}

@tab

不等号

@item

@code{ACS_PI}

@tab

字母π

@item

@code{ACS_PLMINUS}

@tab

正负号

@item

@code{ACS_PLUS}

@tab

加号

@item

@code{ACS_RARROW}

@tab

向右箭头

@item

@code{ACS_RTEE}

@tab

右侧 T 型

@item

@code{ACS_S1}

@tab

扫描线 1

@item

@code{ACS_S3}

@tab

扫描线3

@item

@code{ACS_S7}

@tab

扫描线7

@item

@code{ACS_S9}

@tab

扫描线 9

@item

@code{ACS_SBBS}

@tab

右下角的别名

@item

@code{ACS_SBSB}

@tab

垂直线的别名

@item

@code{ACS_SBSS}

@tab

右侧 T 型的别名

@item

@code{ACS_SSBB}

@tab

左下角的别名

@item

@code{ACS_SSBS}

@tab

底部 T 型的别名

@item

@code{ACS_SSSB}

@tab

左侧 T 型的别名

@item

@code{ACS_SSSS}

@tab

交叉或大加号的替代名称

@item

@code{ACS_STERLING}

@tab

英镑

@item

@code{ACS_TTEE}

@tab

顶部 T 型

@item

@code{ACS_UARROW}

@tab

向上箭头

@item

@code{ACS_ULCORNER}

@tab

左上角

@item

@code{ACS_URCORNER}

@tab

右上角

@item

@code{ACS_VLINE}

@tab

垂线

@end multitable


下表列出了预定义的颜色：


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

颜色

@item

@code{COLOR_BLACK}

@tab

黑色

@item

@code{COLOR_BLUE}

@tab

蓝色

@item

@code{COLOR_CYAN}

@tab

青色（浅绿蓝色）

@item

@code{COLOR_GREEN}

@tab

绿色

@item

@code{COLOR_MAGENTA}

@tab

洋红色（紫红色）

@item

@code{COLOR_RED}

@tab

红色

@item

@code{COLOR_WHITE}

@tab

白色

@item

@code{COLOR_YELLOW}

@tab

黄色

@end multitable


@node curses textpad --- 用于 curses 程序的文本输入控件,curses ascii --- 用于 ASCII 字符的工具,curses --- 终端字符单元显示的处理,通用操作系统服务
@anchor{library/curses curses-textpad-text-input-widget-for-curses-programs}@anchor{2375}@anchor{library/curses module-curses textpad}@anchor{2e}
@subsection @code{curses.textpad} --- 用于 curses 程序的文本输入控件


@geindex curses.textpad (模块)

@ref{2e,,curses.textpad} 模块提供了一个 @ref{2376,,Textbox} 类，该类在 curses 窗口中处理基本的文本编辑，支持一组与 Emacs 类似的键绑定（因此这也适用于 Netscape Navigator, BBedit 6.x, FrameMaker 和许多其他程序）。 该模块还提供了一个绘制矩形的函数，适用于容纳文本框或其他目的。

@ref{2e,,curses.textpad} 模块定义了以下函数:

@geindex rectangle() (在 curses.textpad 模块中)
@anchor{library/curses curses textpad rectangle}@anchor{2377}
@deffn {函数} curses.textpad.rectangle (win, uly, ulx, lry, lrx)

绘制一个矩形。 第一个参数必须为窗口对象；其余参数均为相对于该窗口的坐标值。 第二和第三个参数为要绘制的矩形的左上角的 y 和 x 坐标值；第四和第五个参数为其右下角的 y 和 x 坐标值。 将会使用 VT100/IBM PC 形式的字符在可用的终端上（包括 xterm 和大多数其他软件终端模拟器）绘制矩形。 在其他情况下则将使用 ASCII  横杠、竖线和加号绘制。
@end deffn

@menu
* 文本框对象:: 

@end menu

@node 文本框对象,,,curses textpad --- 用于 curses 程序的文本输入控件
@anchor{library/curses curses-textpad-objects}@anchor{2378}@anchor{library/curses textbox-objects}@anchor{2379}
@subsubsection 文本框对象


你可以通过如下方式实例化一个 @ref{2376,,Textbox}:

@geindex Textbox (curses.textpad 中的类)
@anchor{library/curses curses textpad Textbox}@anchor{2376}
@deffn {类} curses.textpad.Textbox (win)

返回一个文本框控件对象。 @emph{win} 参数必须是一个 curses @ref{2306,,窗口} 对象，文本框将被包含在其中。 文本框的编辑光标在初始时位于包含窗口的左上角，坐标值为 @code{(0, 0)}。 实例的 @ref{237a,,stripspaces} 旗标初始时为启用。

@ref{2376,,Textbox} 对象具有以下方法:

@geindex edit() (curses.textpad.Textbox 方法)
@anchor{library/curses curses textpad Textbox edit}@anchor{237b}
@deffn {方法} edit ([validator])

这是你通常将使用的入口点。 它接受编辑按键直到键入了一个终止按键。 如果提供了 @emph{validator}，它必须是一个函数。 它将在每次按键时被调用并传入相应的按键作作为形参；命令发送将在结果上执行。 此方法会以字符串形式返回窗口内容；是否包括窗口中的空白将受到 @ref{237a,,stripspaces} 属性的影响。
@end deffn

@geindex do_command() (curses.textpad.Textbox 方法)
@anchor{library/curses curses textpad Textbox do_command}@anchor{237c}
@deffn {方法} do_command (ch)

处理单个按键命令。以下是支持的特殊按键：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

按键

@tab

动作

@item

@code{Control-A}

@tab

转到窗口的左边缘。

@item

@code{Control-B}

@tab

光标向左，如果可能，包含前一行。

@item

@code{Control-D}

@tab

删除光标下的字符。

@item

@code{Control-E}

@tab

前往右边缘（stripspaces 关闭时）或者行尾（stripspaces 启用时）。

@item

@code{Control-F}

@tab

向右移动光标，适当时换行到下一行。

@item

@code{Control-G}

@tab

终止，返回窗口内容。

@item

@code{Control-H}

@tab

向后删除字符。

@item

@code{Control-J}

@tab

如果窗口是1行则终止，否则插入换行符。

@item

@code{Control-K}

@tab

如果行为空，则删除它，否则清除到行尾。

@item

@code{Control-L}

@tab

刷新屏幕。

@item

@code{Control-N}

@tab

光标向下;向下移动一行。

@item

@code{Control-O}

@tab

在光标位置插入一个空行。

@item

@code{Control-P}

@tab

光标向上;向上移动一行。

@end multitable


如果光标位于无法移动的边缘，则移动操作不执行任何操作。在可能的情况下，支持以下同义词：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

按键

@item

@code{KEY_LEFT}

@tab

@code{Control-B}

@item

@code{KEY_RIGHT}

@tab

@code{Control-F}

@item

@code{KEY_UP}

@tab

@code{Control-P}

@item

@code{KEY_DOWN}

@tab

@code{Control-N}

@item

@code{KEY_BACKSPACE}

@tab

@code{Control-h}

@end multitable


所有其他按键将被视为插入给定字符并右移的命令（带有自动折行）。
@end deffn

@geindex gather() (curses.textpad.Textbox 方法)
@anchor{library/curses curses textpad Textbox gather}@anchor{237d}
@deffn {方法} gather ()

以字符串形式返回窗口内容；是否包括窗口中的空白将受到 @ref{237a,,stripspaces} 成员的影响。
@end deffn

@geindex stripspaces (curses.textpad.Textbox 属性)
@anchor{library/curses curses textpad Textbox stripspaces}@anchor{237a}
@deffn {属性} stripspaces

此属性是控制窗口中空白解读方式的旗标。 当启用时，每一行的末尾空白会被忽略；任何将光标定位至末尾空白的光标动作都将改为前往该行末尾，并且在收集窗口内容时将去除末尾空白。
@end deffn
@end deffn

@node curses ascii --- 用于 ASCII 字符的工具,curses panel --- curses 的面板栈扩展,curses textpad --- 用于 curses 程序的文本输入控件,通用操作系统服务
@anchor{library/curses ascii doc}@anchor{237e}@anchor{library/curses ascii curses-ascii-utilities-for-ascii-characters}@anchor{237f}@anchor{library/curses ascii module-curses ascii}@anchor{2c}
@subsection @code{curses.ascii} --- 用于 ASCII 字符的工具


@geindex curses.ascii (模块)


__________________________________________________________________


@ref{2c,,curses.ascii} 模块提供了一些 ASCII 字符的名称常量以及在各种 ASCII 字符类中执行成员检测的函数。 所提供的控制字符常量如下:


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名称

@tab

含义

@item

@code{NUL}

@tab

@item

@code{SOH}

@tab

标题开始，控制台中断

@item

@code{STX}

@tab

文本开始

@item

@code{ETX}

@tab

文本结束

@item

@code{EOT}

@tab

传输结束

@item

@code{ENQ}

@tab

查询，附带 @code{ACK} 流量控制

@item

@code{ACK}

@tab

确认

@item

@code{BEL}

@tab

蜂鸣器

@item

@code{BS}

@tab

退格

@item

@code{TAB}

@tab

制表符

@item

@code{HT}

@tab

@code{TAB} 的别名： "水平制表符”

@item

@code{LF}

@tab

换行

@item

@code{NL}

@tab

@code{LF} 的别名： "新行"

@item

@code{VT}

@tab

垂直制表符

@item

@code{FF}

@tab

换页

@item

@code{CR}

@tab

回车

@item

@code{SO}

@tab

Shift-out，开始替换字符集

@item

@code{SI}

@tab

Shift-in，恢复默认字符集

@item

@code{DLE}

@tab

Data-link escape，数据链接转义

@item

@code{DC1}

@tab

XON，用于流程控制

@item

@code{DC2}

@tab

Device control 2，块模式流程控制

@item

@code{DC3}

@tab

XOFF，用于流程控制

@item

@code{DC4}

@tab

设备控制4

@item

@code{NAK}

@tab

否定确认

@item

@code{SYN}

@tab

同步空闲

@item

@code{ETB}

@tab

末端传输块

@item

@code{CAN}

@tab

取消

@item

@code{EM}

@tab

媒体结束

@item

@code{SUB}

@tab

替换

@item

@code{ESC}

@tab

退出

@item

@code{FS}

@tab

文件分隔符

@item

@code{GS}

@tab

组分隔符

@item

@code{RS}

@tab

Record separator，块模式终止符

@item

@code{US}

@tab

单位分隔符

@item

@code{SP}

@tab

空格

@item

@code{DEL}

@tab

删除

@end multitable


请注意其中有许多在现今已经没有实际作用。 这些助记符是来源于数字计算机之前的电传打印机规范。

此模块提供了下列函数，对应于标准 C 库中的函数:

@geindex isalnum() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isalnum}@anchor{2380}
@deffn {函数} curses.ascii.isalnum (c)

检测 ASCII 字母数字类字符；它等价于 @code{isalpha(c) 或 isdigit(c)}。
@end deffn

@geindex isalpha() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isalpha}@anchor{2381}
@deffn {函数} curses.ascii.isalpha (c)

检测 ASCII 字母类字符；它等价于 @code{isupper(c) or islower(c)}。
@end deffn

@geindex isascii() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isascii}@anchor{2382}
@deffn {函数} curses.ascii.isascii (c)

检测字符值是否在 7 位 ASCII 集范围内。
@end deffn

@geindex isblank() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isblank}@anchor{2383}
@deffn {函数} curses.ascii.isblank (c)

检测 ASCII 空白字符；包括空格或水平制表符。
@end deffn

@geindex iscntrl() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii iscntrl}@anchor{2384}
@deffn {函数} curses.ascii.iscntrl (c)

检测 ASCII 控制字符（在 0x00 到 0x1f 或 0x7f 范围内）。
@end deffn

@geindex isdigit() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isdigit}@anchor{2385}
@deffn {函数} curses.ascii.isdigit (c)

检测 ASCII 十进制数码，即 @code{'0'} 至 @code{'9'}。 它等价于 @code{c in string.digits}。
@end deffn

@geindex isgraph() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isgraph}@anchor{2386}
@deffn {函数} curses.ascii.isgraph (c)

检测任意 ASCII 可打印字符，不包括空白符。
@end deffn

@geindex islower() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii islower}@anchor{2387}
@deffn {函数} curses.ascii.islower (c)

检测 ASCII 小写字母字符。
@end deffn

@geindex isprint() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isprint}@anchor{2388}
@deffn {函数} curses.ascii.isprint (c)

检测任意 ASCII 可打印字符，包括空白符。
@end deffn

@geindex ispunct() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii ispunct}@anchor{2389}
@deffn {函数} curses.ascii.ispunct (c)

检测任意 ASCII 可打印字符，不包括空白符或字母数字类字符。
@end deffn

@geindex isspace() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isspace}@anchor{238a}
@deffn {函数} curses.ascii.isspace (c)

检测 ASCII 空白字符；包括空格，换行，回车，进纸，水平制表和垂直制表。
@end deffn

@geindex isupper() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isupper}@anchor{238b}
@deffn {函数} curses.ascii.isupper (c)

检测 ASCII 大写字母字符。
@end deffn

@geindex isxdigit() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isxdigit}@anchor{238c}
@deffn {函数} curses.ascii.isxdigit (c)

检测 ASCII 十六进制数码。 这等价于 @code{c in string.hexdigits}。
@end deffn

@geindex isctrl() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii isctrl}@anchor{238d}
@deffn {函数} curses.ascii.isctrl (c)

检测 ASCII 控制字符（码位值 0 至 31）。
@end deffn

@geindex ismeta() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii ismeta}@anchor{238e}
@deffn {函数} curses.ascii.ismeta (c)

检测非 ASCII 字符（码位值 0x80 及以上）。
@end deffn

这些函数接受整数或单字符字符串；当参数为字符串时，会先使用内置函数 @ref{1588,,ord()} 进行转换。

请注意所有这些函数都是检测根据你传入的字符串的字符所生成的码位值；它们实际上完全不会知晓本机的字符编码格式。

以下两个函数接受单字符字符串或整数形式的字节值；它们会返回相同类型的值。

@geindex ascii() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii ascii}@anchor{238f}
@deffn {函数} curses.ascii.ascii (c)

返回对应于 @emph{c} 的下个 7 比特位的 ASCII 值。
@end deffn

@geindex ctrl() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii ctrl}@anchor{2390}
@deffn {函数} curses.ascii.ctrl (c)

返回对应于给定字符的控制字符（字符比特值会与 0x1f 进行按位与运算）。
@end deffn

@geindex alt() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii alt}@anchor{2391}
@deffn {函数} curses.ascii.alt (c)

返回对应于给定 ASCII 字符的 8 比特位字符（字符比特值会与 0x80 进行按位或运算）。
@end deffn

以下函数接受单字符字符串或整数值；它会返回一个字符串。

@geindex ^ (caret); in curses module
@geindex ! (exclamation); in curses module

@geindex unctrl() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii unctrl}@anchor{2392}
@deffn {函数} curses.ascii.unctrl (c)

返回 ASCII 字符 @emph{c} 的字符串表示形式。 如果 @emph{c} 是可打印字符，则字符串为字符本身。 如果该字符是控制字符 (0x00--0x1f) 则字符串由一个插入符 (@code{'^'}) 加相应的大写字母组成。 如果该字符是 ASCII 删除符 (0x7f) 则字符串为 @code{'^?'}。 如果该字符设置了元比特位 (0x80)，元比特位会被去除，应用以上规则后将在结果之前添加 @code{'!'}。
@end deffn

@geindex controlnames() (在 curses.ascii 模块中)
@anchor{library/curses ascii curses ascii controlnames}@anchor{2393}
@deffn {数据} curses.ascii.controlnames

一个 33 元素的字符串数据，其中按从 0 (NUL) 到 0x1f (US) 的顺序包含了三十二个 ASCII 控制字符的 ASCII 助记符，另加空格符的助记符 @code{SP}。
@end deffn

@node curses panel --- curses 的面板栈扩展,platform --- 获取底层平台的标识数据,curses ascii --- 用于 ASCII 字符的工具,通用操作系统服务
@anchor{library/curses panel doc}@anchor{2394}@anchor{library/curses panel curses-panel-a-panel-stack-extension-for-curses}@anchor{2395}@anchor{library/curses panel module-curses panel}@anchor{2d}
@subsection @code{curses.panel} --- curses 的面板栈扩展


@geindex curses.panel (模块)


__________________________________________________________________


面板是具有添加深度功能的窗口，因此它们可以从上至下堆叠为栈，只有显示每个窗口的可见部分会显示出来。 面板可以在栈中被添加、上移或下移，也可以被移除。

@menu
* 函数: 函数<5>. 
* Panel 对象:: 

@end menu

@node 函数<5>,Panel 对象,,curses panel --- curses 的面板栈扩展
@anchor{library/curses panel cursespanel-functions}@anchor{2396}@anchor{library/curses panel functions}@anchor{2397}
@subsubsection 函数


@ref{2d,,curses.panel} 模块定义了以下函数:

@geindex bottom_panel() (在 curses.panel 模块中)
@anchor{library/curses panel curses panel bottom_panel}@anchor{2398}
@deffn {函数} curses.panel.bottom_panel ()

返回面板栈中的底部面板。
@end deffn

@geindex new_panel() (在 curses.panel 模块中)
@anchor{library/curses panel curses panel new_panel}@anchor{2399}
@deffn {函数} curses.panel.new_panel (win)

返回一个面板对象，将其与给定的窗口 @emph{win} 相关联。 请注意你必须显式地保持所返回的面板对象。 如果你不这样做，面板对象会被垃圾回收并从面板栈中被移除。
@end deffn

@geindex top_panel() (在 curses.panel 模块中)
@anchor{library/curses panel curses panel top_panel}@anchor{239a}
@deffn {函数} curses.panel.top_panel ()

返回面板栈中的顶部面板。
@end deffn

@geindex update_panels() (在 curses.panel 模块中)
@anchor{library/curses panel curses panel update_panels}@anchor{239b}
@deffn {函数} curses.panel.update_panels ()

在面板栈发生改变后更新虚拟屏幕。 这不会调用 @ref{22ed,,curses.doupdate()}，因此你不必自己执行此操作。
@end deffn

@node Panel 对象,,函数<5>,curses panel --- curses 的面板栈扩展
@anchor{library/curses panel curses-panel-objects}@anchor{239c}@anchor{library/curses panel panel-objects}@anchor{239d}
@subsubsection Panel 对象


Panel 对象，如上面 @ref{2399,,new_panel()} 所返回的对象，是带有栈顺序的多个窗口。 总是会有一个窗口与确定内容的面板相关联，面板方法会负责窗口在面板栈中的深度。

Panel 对象具有以下方法:

@geindex above() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel above}@anchor{239e}
@deffn {方法} Panel.above ()

返回当前面板之上的面板。
@end deffn

@geindex below() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel below}@anchor{239f}
@deffn {方法} Panel.below ()

返回当前面板之下的面板。
@end deffn

@geindex bottom() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel bottom}@anchor{23a0}
@deffn {方法} Panel.bottom ()

将面板推至栈底部。
@end deffn

@geindex hidden() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel hidden}@anchor{23a1}
@deffn {方法} Panel.hidden ()

如果面板被隐藏（不可见）则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex hide() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel hide}@anchor{23a2}
@deffn {方法} Panel.hide ()

隐藏面板。 这不会删除对象，它只是让窗口在屏幕上不可见。
@end deffn

@geindex move() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel move}@anchor{23a3}
@deffn {方法} Panel.move (y, x)

将面板移至屏幕坐标 @code{(y, x)}。
@end deffn

@geindex replace() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel replace}@anchor{23a4}
@deffn {方法} Panel.replace (win)

将与面板相关联的窗口改为窗口 @emph{win}。
@end deffn

@geindex set_userptr() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel set_userptr}@anchor{23a5}
@deffn {方法} Panel.set_userptr (obj)

将面板的用户指向设为 @emph{obj}。 这被用来将任意数据与面板相关联，数据可以是任何 Python 对象。
@end deffn

@geindex show() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel show}@anchor{23a6}
@deffn {方法} Panel.show ()

显示面板（面板可能已被隐藏）。
@end deffn

@geindex top() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel top}@anchor{23a7}
@deffn {方法} Panel.top ()

将面板推至栈顶部。
@end deffn

@geindex userptr() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel userptr}@anchor{23a8}
@deffn {方法} Panel.userptr ()

返回面板的用户指针。 这可以是任何 Python 对象。
@end deffn

@geindex window() (curses.panel.Panel 方法)
@anchor{library/curses panel curses panel Panel window}@anchor{23a9}
@deffn {方法} Panel.window ()

返回与面板相关联的窗口对象。
@end deffn

@node platform --- 获取底层平台的标识数据,errno --- 标准 errno 系统符号,curses panel --- curses 的面板栈扩展,通用操作系统服务
@anchor{library/platform doc}@anchor{23aa}@anchor{library/platform module-platform}@anchor{ce}@anchor{library/platform platform-access-to-underlying-platform-s-identifying-data}@anchor{23ab}
@subsection @code{platform} ---  获取底层平台的标识数据


@geindex platform (模块)

@strong{源代码：} Lib/platform.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/platform.py}


__________________________________________________________________


@cartouche
@quotation 注解 
特定平台按字母顺序排列，Linux 包括在 Unix 小节之中。
@end quotation
@end cartouche

@menu
* 跨平台:: 
* Java平台:: 
* Windows平台:: 
* macOS 平台:: 
* Unix 平台:: 

@end menu

@node 跨平台,Java平台,,platform --- 获取底层平台的标识数据
@anchor{library/platform cross-platform}@anchor{23ac}
@subsubsection 跨平台


@geindex architecture() (在 platform 模块中)
@anchor{library/platform platform architecture}@anchor{1197}
@deffn {函数} platform.architecture (executable=sys.executable, bits='@w{'}, linkage='@w{'})

查询给定的可执行文件（默认为 Python 解释器二进制码文件）来获取各种架构信息。

返回一个元素 @code{(bits, linkage)}，其中包含可执行文件所使用的位架构和链接格式信息。 这两个值均以字符串形式返回。

无法确定的值将返回为形参预设所给出的值。 如果给出的位数为 @code{'@w{'}}，则会使用 @code{sizeof(pointer)} (或者当 Python 版本 < 1.5.2 时为 @code{sizeof(long)}) 作为所支持的指针大小的提示。

此函数依赖于系统的 @code{file} 命令来执行实际的操作。 这在几乎所有 Unix 平台和某些非 Unix 平台上只有当可执行文件指向 Python 解释器时才可用。 当以上要求不满足时将会使用合理的默认值。

@cartouche
@quotation 注解 
在 macOS (也许还有其他平台) 上，可执行文件可能是包含多种架构的通用文件。

要获取当前解释器的“64 位性”，更可靠的做法是查询 @ref{c1e,,sys.maxsize} 属性:

@example
is_64bits = sys.maxsize > 2**32
@end example
@end quotation
@end cartouche
@end deffn

@geindex machine() (在 platform 模块中)
@anchor{library/platform platform machine}@anchor{23ad}
@deffn {函数} platform.machine ()

返回机器类型，例如 @code{'i386'}。 如果该值无法确定则会返回一个空字符串。
@end deffn

@geindex node() (在 platform 模块中)
@anchor{library/platform platform node}@anchor{23ae}
@deffn {函数} platform.node ()

返回计算机的网络名称（可能不是完整限定名称！）。 如果该值无法确定则会返回一个空字符串。
@end deffn

@geindex platform() (在 platform 模块中)
@anchor{library/platform platform platform}@anchor{119c}
@deffn {函数} platform.platform (aliased=0, terse=0)

返回一个标识底层平台的字符串，其中带有尽可能多的有用信息。

输出信息的目标是“人类易读”而非机器易解析。 它在不同平台上可能看起来不一致，这是有意为之的。

如果 @emph{aliased} 为真值，此函数将使用各种平台不同与其通常名称的别名来报告系统名称，例如 SunOS 将被报告为 Solaris。 @ref{23af,,system_alias()} 函数将被用于实现此功能。

将 @emph{terse} 设为真值将导致此函数只返回标识平台所必须的最小量信息。


在 3.8 版更改: 在 macOS 上，此函数现在会在 @ref{119d,,mac_ver()} 返回的发布版字符串非空时使用它，以便获取 macOS 版本而非 darwin 版本。

@end deffn

@geindex processor() (在 platform 模块中)
@anchor{library/platform platform processor}@anchor{23b0}
@deffn {函数} platform.processor ()

返回（真实的）处理器名称，例如 @code{'amdk6'}。

如果该值无法确定则将返回空字符串。 请注意许多平台都不提供此信息或是简单地返回与 @ref{23ad,,machine()} 相同的值。 NetBSD 则会提供此信息。
@end deffn

@geindex python_build() (在 platform 模块中)
@anchor{library/platform platform python_build}@anchor{23b1}
@deffn {函数} platform.python_build ()

返回一个元组 @code{(buildno, builddate)}，以字符串表示的 Python 编译代码和日期。
@end deffn

@geindex python_compiler() (在 platform 模块中)
@anchor{library/platform platform python_compiler}@anchor{23b2}
@deffn {函数} platform.python_compiler ()

返回一个标识用于编译 Python 的编译器的的字符串。
@end deffn

@geindex python_branch() (在 platform 模块中)
@anchor{library/platform platform python_branch}@anchor{23b3}
@deffn {函数} platform.python_branch ()

返回一个标识 Python 实现的 SCM 分支的字符串。
@end deffn

@geindex python_implementation() (在 platform 模块中)
@anchor{library/platform platform python_implementation}@anchor{23b4}
@deffn {函数} platform.python_implementation ()

返回一个标识 Python 实现的字符串。 可能的返回值有: 'CPython', 'IronPython', 'Jython', 'PyPy'。
@end deffn

@geindex python_revision() (在 platform 模块中)
@anchor{library/platform platform python_revision}@anchor{23b5}
@deffn {函数} platform.python_revision ()

返回一个标识 Python 实现的 SCM 修订版的字符串。
@end deffn

@geindex python_version() (在 platform 模块中)
@anchor{library/platform platform python_version}@anchor{23b6}
@deffn {函数} platform.python_version ()

将 Python 版本以字符串 @code{'major.minor.patchlevel'} 形式返回。

请注意此返回值不同于 Python @code{sys.version}，它将总是包括 patchlevel (默认为 0)。
@end deffn

@geindex python_version_tuple() (在 platform 模块中)
@anchor{library/platform platform python_version_tuple}@anchor{23b7}
@deffn {函数} platform.python_version_tuple ()

将 Python 版本以字符串元组 @code{(major, minor, patchlevel)} 形式返回。

请注意此返回值不同于 Python @code{sys.version}，它将总是包括 patchlevel (默认为 @code{'0'})。
@end deffn

@geindex release() (在 platform 模块中)
@anchor{library/platform platform release}@anchor{23b8}
@deffn {函数} platform.release ()

返回系统的发布版本，例如 @code{'2.2.0'} 或 @code{'NT'}，如果该值无法确定则将返回一个空字符串。
@end deffn

@geindex system() (在 platform 模块中)
@anchor{library/platform platform system}@anchor{23b9}
@deffn {函数} platform.system ()

返回系统平台/OS的名称，例如 @code{'Linux'}, @code{'Darwin'}, @code{'Java'}, @code{'Windows'}。 如果该值无法确定则将返回一个空字符串。
@end deffn

@geindex system_alias() (在 platform 模块中)
@anchor{library/platform platform system_alias}@anchor{23af}
@deffn {函数} platform.system_alias (system, release, version)

返回别名为某些系统所使用的常见营销名称的 @code{(system, release, version)}。 它还会在可能导致混淆的情况下对信息进行一些重排序操作。
@end deffn

@geindex version() (在 platform 模块中)
@anchor{library/platform platform version}@anchor{23ba}
@deffn {函数} platform.version ()

返回系统的发布版本信息，例如 @code{'#3 on degas'}。 如果该值无法确定则将返回一个空字符串。
@end deffn

@geindex uname() (在 platform 模块中)
@anchor{library/platform platform uname}@anchor{119a}
@deffn {函数} platform.uname ()

具有高可移植性的 uname 接口。 返回包含六个属性的 @ref{1a1,,namedtuple()}: @ref{23b9,,system}, @ref{23ae,,node}, @ref{23b8,,release}, @ref{23ba,,version}, @ref{23ad,,machine} 和 @ref{23b0,,processor}。

请注意此函数添加的第六个属性 (@ref{23b0,,processor}) 并不存在于 @ref{b41,,os.uname()} 的结果中。 并且前两个属性的属性名称也不一致；@ref{b41,,os.uname()} 是将它们称为 @code{sysname} 和 @code{nodename}。

无法确定的条目会被设为 @code{'@w{'}}。


在 3.3 版更改: 结果由元组改为 @ref{1a1,,namedtuple()} 。

@end deffn

@node Java平台,Windows平台,跨平台,platform --- 获取底层平台的标识数据
@anchor{library/platform java-platform}@anchor{23bb}
@subsubsection Java平台


@geindex java_ver() (在 platform 模块中)
@anchor{library/platform platform java_ver}@anchor{23bc}
@deffn {函数} platform.java_ver (release='@w{'}, vendor='@w{'}, vminfo=('@w{'}, '@w{'}, '@w{'}), osinfo=('@w{'}, '@w{'}, '@w{'}))

Jython 的版本接口

返回一个元组 @code{(release, vendor, vminfo, osinfo)}，其中 @emph{vminfo} 为元组 @code{(vm_name, vm_release, vm_vendor)} 而 @emph{osinfo} 为元组 @code{(os_name, os_version, os_arch)}。 无法确定的值将设为由形参所给出的默认值 (默认均为 @code{'@w{'}})。
@end deffn

@node Windows平台,macOS 平台,Java平台,platform --- 获取底层平台的标识数据
@anchor{library/platform windows-platform}@anchor{23bd}
@subsubsection Windows平台


@geindex win32_ver() (在 platform 模块中)
@anchor{library/platform platform win32_ver}@anchor{108a}
@deffn {函数} platform.win32_ver (release='@w{'}, version='@w{'}, csd='@w{'}, ptype='@w{'})

从 Windows 注册表获取额外的版本信息并返回一个元组 @code{(release, version, csd, ptype)} 表示 OS 发行版, 版本号, CSD 级别 (Service Pack) 和 OS 类型 (多个/单个处理器)。无法确定的值被设置为作为参数给出的默认值（这些参数都默认为一个空字符串）。

一点提示: @emph{ptype} 在单个处理器的 NT 机器上为 @code{'Uniprocessor Free'} 而在多个处理器的机器上为 @code{'Multiprocessor Free'}。 @emph{'Free'} 是指该 OS 版本没有调试代码。 它还可能显示 @emph{'Checked'} 表示该 OS 版本使用了调试代码，即检测参数、范围等的代码。
@end deffn

@geindex win32_edition() (在 platform 模块中)
@anchor{library/platform platform win32_edition}@anchor{23be}
@deffn {函数} platform.win32_edition ()

返回一个代表当前 Windows 版本的字符串，或者在该值无法确定时返回 @code{None} 。 可能的值包括但不限于 @code{'Enterprise'}, @code{'IoTUAP'}, @code{'ServerStandard'} 和 @code{'nanoserver'}。


3.8 新版功能.

@end deffn

@geindex win32_is_iot() (在 platform 模块中)
@anchor{library/platform platform win32_is_iot}@anchor{23bf}
@deffn {函数} platform.win32_is_iot ()

如果 @ref{23be,,win32_edition()} 返回的 Windows 版本被识别为 IoT 版则返回 @code{True}。


3.8 新版功能.

@end deffn

@node macOS 平台,Unix 平台,Windows平台,platform --- 获取底层平台的标识数据
@anchor{library/platform macos-platform}@anchor{23c0}
@subsubsection macOS 平台


@geindex mac_ver() (在 platform 模块中)
@anchor{library/platform platform mac_ver}@anchor{119d}
@deffn {函数} platform.mac_ver (release='@w{'}, versioninfo=('@w{'}, '@w{'}, '@w{'}), machine='@w{'})

获取 macOS 版本信息并将其返回为元组 @code{(release, versioninfo, machine)}，其中 @emph{versioninfo} 是一个元组 @code{(version, dev_stage, non_release_version)}。

无法确定的条目会被设为 @code{'@w{'}}。 所有元组条目均为字符串。
@end deffn

@node Unix 平台,,macOS 平台,platform --- 获取底层平台的标识数据
@anchor{library/platform unix-platforms}@anchor{23c1}
@subsubsection Unix 平台


@geindex libc_ver() (在 platform 模块中)
@anchor{library/platform platform libc_ver}@anchor{1199}
@deffn {函数} platform.libc_ver (executable=sys.executable, lib='@w{'}, version='@w{'}, chunksize=16384)

尝试确定可执行文件（默认为 Python 解释器）所链接到的 libc 版本。 返回一个字符串元组 @code{(lib, version)}，当查找失败时其默认值将设为给定的形参值。

请注意此函数对于不同 libc 版本向可执行文件添加符号的方式有深层的关联，可能仅适用于使用 @code{gcc} 编译出来的可执行文件。

文件将按 @emph{chunksize} 个字节的分块来读取和扫描。
@end deffn

@node errno --- 标准 errno 系统符号,ctypes --- Python 的外部函数库,platform --- 获取底层平台的标识数据,通用操作系统服务
@anchor{library/errno doc}@anchor{23c2}@anchor{library/errno errno-standard-errno-system-symbols}@anchor{23c3}@anchor{library/errno module-errno}@anchor{7a}
@subsection @code{errno} --- 标准 errno 系统符号


@geindex errno (模块)


__________________________________________________________________


该模块提供了标准的 @code{errno} 系统符号。每个符号的值都是相应的整数值。名称和描述借用自 @code{linux/include/errno.h} ，它应该是全包含的。

@geindex errorcode() (在 errno 模块中)
@anchor{library/errno errno errorcode}@anchor{23c4}
@deffn {数据} errno.errorcode

提供从 errno 值到底层系统中字符串名称的映射的字典。例如， @code{errno.errorcode[errno.EPERM]} 映射为 @code{'EPERM'} 。
@end deffn

如果要将数字的错误代码转换为错误信息，请使用 @ref{2093,,os.strerror()}。

在下面的列表中，当前平台上没有使用的符号没有被本模块定义。 已定义的符号的具体列表可参见 @code{errno.errorcode.keys()}。 可用的符号包括：

@geindex EPERM() (在 errno 模块中)
@anchor{library/errno errno EPERM}@anchor{18a7}
@deffn {数据} errno.EPERM

操作不允许。这个错误被映射到异常 @ref{700,,PermissionError} 。
@end deffn

@geindex ENOENT() (在 errno 模块中)
@anchor{library/errno errno ENOENT}@anchor{18a3}
@deffn {数据} errno.ENOENT

没有这样的文件或目录。这个错误被映射到异常 @ref{8b7,,FileNotFoundError} 。
@end deffn

@geindex ESRCH() (在 errno 模块中)
@anchor{library/errno errno ESRCH}@anchor{18a8}
@deffn {数据} errno.ESRCH

没有这样的进程。这个错误被映射到异常 @ref{a85,,ProcessLookupError} 。
@end deffn

@geindex EINTR() (在 errno 模块中)
@anchor{library/errno errno EINTR}@anchor{755}
@deffn {数据} errno.EINTR

系统调用中断。这个错误被映射到异常 @ref{756,,InterruptedError} 。
@end deffn

@geindex EIO() (在 errno 模块中)
@anchor{library/errno errno EIO}@anchor{23c5}
@deffn {数据} errno.EIO

I/O 错误
@end deffn

@geindex ENXIO() (在 errno 模块中)
@anchor{library/errno errno ENXIO}@anchor{23c6}
@deffn {数据} errno.ENXIO

无此设备或地址
@end deffn

@geindex E2BIG() (在 errno 模块中)
@anchor{library/errno errno E2BIG}@anchor{23c7}
@deffn {数据} errno.E2BIG

参数列表过长
@end deffn

@geindex ENOEXEC() (在 errno 模块中)
@anchor{library/errno errno ENOEXEC}@anchor{23c8}
@deffn {数据} errno.ENOEXEC

执行格式错误
@end deffn

@geindex EBADF() (在 errno 模块中)
@anchor{library/errno errno EBADF}@anchor{230}
@deffn {数据} errno.EBADF

错误的文件号
@end deffn

@geindex ECHILD() (在 errno 模块中)
@anchor{library/errno errno ECHILD}@anchor{189c}
@deffn {数据} errno.ECHILD

没有子进程。这个错误被映射到异常 @ref{a82,,ChildProcessError} 。
@end deffn

@geindex EAGAIN() (在 errno 模块中)
@anchor{library/errno errno EAGAIN}@anchor{1897}
@deffn {数据} errno.EAGAIN

再试一次。这个错误被映射到异常 @ref{a81,,BlockingIOError} 。
@end deffn

@geindex ENOMEM() (在 errno 模块中)
@anchor{library/errno errno ENOMEM}@anchor{23c9}
@deffn {数据} errno.ENOMEM

内存不足
@end deffn

@geindex EACCES() (在 errno 模块中)
@anchor{library/errno errno EACCES}@anchor{18a6}
@deffn {数据} errno.EACCES

权限被拒绝。 这个错误被映射到异常 @ref{700,,PermissionError} 。
@end deffn

@geindex EFAULT() (在 errno 模块中)
@anchor{library/errno errno EFAULT}@anchor{23ca}
@deffn {数据} errno.EFAULT

错误的地址
@end deffn

@geindex ENOTBLK() (在 errno 模块中)
@anchor{library/errno errno ENOTBLK}@anchor{23cb}
@deffn {数据} errno.ENOTBLK

需要块设备
@end deffn

@geindex EBUSY() (在 errno 模块中)
@anchor{library/errno errno EBUSY}@anchor{23cc}
@deffn {数据} errno.EBUSY

设备或资源忙
@end deffn

@geindex EEXIST() (在 errno 模块中)
@anchor{library/errno errno EEXIST}@anchor{18a2}
@deffn {数据} errno.EEXIST

文件存在。这个错误被映射到异常 @ref{a42,,FileExistsError} 。
@end deffn

@geindex EXDEV() (在 errno 模块中)
@anchor{library/errno errno EXDEV}@anchor{209e}
@deffn {数据} errno.EXDEV

跨设备链接
@end deffn

@geindex ENODEV() (在 errno 模块中)
@anchor{library/errno errno ENODEV}@anchor{23cd}
@deffn {数据} errno.ENODEV

无此设备
@end deffn

@geindex ENOTDIR() (在 errno 模块中)
@anchor{library/errno errno ENOTDIR}@anchor{18a5}
@deffn {数据} errno.ENOTDIR

不是一个目录。这个错误被映射到异常 @ref{a84,,NotADirectoryError} 。
@end deffn

@geindex EISDIR() (在 errno 模块中)
@anchor{library/errno errno EISDIR}@anchor{18a4}
@deffn {数据} errno.EISDIR

是一个目录。这个错误被映射到异常 @ref{a83,,IsADirectoryError} 。
@end deffn

@geindex EINVAL() (在 errno 模块中)
@anchor{library/errno errno EINVAL}@anchor{114d}
@deffn {数据} errno.EINVAL

无效的参数
@end deffn

@geindex ENFILE() (在 errno 模块中)
@anchor{library/errno errno ENFILE}@anchor{23ce}
@deffn {数据} errno.ENFILE

文件表溢出
@end deffn

@geindex EMFILE() (在 errno 模块中)
@anchor{library/errno errno EMFILE}@anchor{23cf}
@deffn {数据} errno.EMFILE

打开的文件过多
@end deffn

@geindex ENOTTY() (在 errno 模块中)
@anchor{library/errno errno ENOTTY}@anchor{23d0}
@deffn {数据} errno.ENOTTY

不是打字机
@end deffn

@geindex ETXTBSY() (在 errno 模块中)
@anchor{library/errno errno ETXTBSY}@anchor{23d1}
@deffn {数据} errno.ETXTBSY

文本文件忙
@end deffn

@geindex EFBIG() (在 errno 模块中)
@anchor{library/errno errno EFBIG}@anchor{23d2}
@deffn {数据} errno.EFBIG

文件过大
@end deffn

@geindex ENOSPC() (在 errno 模块中)
@anchor{library/errno errno ENOSPC}@anchor{23d3}
@deffn {数据} errno.ENOSPC

设备已无可用空间
@end deffn

@geindex ESPIPE() (在 errno 模块中)
@anchor{library/errno errno ESPIPE}@anchor{23d4}
@deffn {数据} errno.ESPIPE

非法查找
@end deffn

@geindex EROFS() (在 errno 模块中)
@anchor{library/errno errno EROFS}@anchor{23d5}
@deffn {数据} errno.EROFS

只读文件系统
@end deffn

@geindex EMLINK() (在 errno 模块中)
@anchor{library/errno errno EMLINK}@anchor{23d6}
@deffn {数据} errno.EMLINK

链接过多
@end deffn

@geindex EPIPE() (在 errno 模块中)
@anchor{library/errno errno EPIPE}@anchor{189d}
@deffn {数据} errno.EPIPE

管道中断。这个错误被映射到异常 @ref{a87,,BrokenPipeError} 。
@end deffn

@geindex EDOM() (在 errno 模块中)
@anchor{library/errno errno EDOM}@anchor{23d7}
@deffn {数据} errno.EDOM

数学参数超出函数范围
@end deffn

@geindex ERANGE() (在 errno 模块中)
@anchor{library/errno errno ERANGE}@anchor{23d8}
@deffn {数据} errno.ERANGE

数学运算结果无法表示
@end deffn

@geindex EDEADLK() (在 errno 模块中)
@anchor{library/errno errno EDEADLK}@anchor{23d9}
@deffn {数据} errno.EDEADLK

将发生资源死锁
@end deffn

@geindex ENAMETOOLONG() (在 errno 模块中)
@anchor{library/errno errno ENAMETOOLONG}@anchor{23da}
@deffn {数据} errno.ENAMETOOLONG

文件名过长
@end deffn

@geindex ENOLCK() (在 errno 模块中)
@anchor{library/errno errno ENOLCK}@anchor{23db}
@deffn {数据} errno.ENOLCK

没有可用的记录锁
@end deffn

@geindex ENOSYS() (在 errno 模块中)
@anchor{library/errno errno ENOSYS}@anchor{23dc}
@deffn {数据} errno.ENOSYS

功能未实现
@end deffn

@geindex ENOTEMPTY() (在 errno 模块中)
@anchor{library/errno errno ENOTEMPTY}@anchor{23dd}
@deffn {数据} errno.ENOTEMPTY

目录非空
@end deffn

@geindex ELOOP() (在 errno 模块中)
@anchor{library/errno errno ELOOP}@anchor{23de}
@deffn {数据} errno.ELOOP

遇到过多的符号链接
@end deffn

@geindex EWOULDBLOCK() (在 errno 模块中)
@anchor{library/errno errno EWOULDBLOCK}@anchor{1899}
@deffn {数据} errno.EWOULDBLOCK

操作会阻塞。这个错误被映射到异常 @ref{a81,,BlockingIOError} 。
@end deffn

@geindex ENOMSG() (在 errno 模块中)
@anchor{library/errno errno ENOMSG}@anchor{23df}
@deffn {数据} errno.ENOMSG

没有所需类型的消息
@end deffn

@geindex EIDRM() (在 errno 模块中)
@anchor{library/errno errno EIDRM}@anchor{23e0}
@deffn {数据} errno.EIDRM

标识符被移除
@end deffn

@geindex ECHRNG() (在 errno 模块中)
@anchor{library/errno errno ECHRNG}@anchor{23e1}
@deffn {数据} errno.ECHRNG

信道编号超出范围
@end deffn

@geindex EL2NSYNC() (在 errno 模块中)
@anchor{library/errno errno EL2NSYNC}@anchor{23e2}
@deffn {数据} errno.EL2NSYNC

级别 2 未同步
@end deffn

@geindex EL3HLT() (在 errno 模块中)
@anchor{library/errno errno EL3HLT}@anchor{23e3}
@deffn {数据} errno.EL3HLT

级别 3 已停止
@end deffn

@geindex EL3RST() (在 errno 模块中)
@anchor{library/errno errno EL3RST}@anchor{23e4}
@deffn {数据} errno.EL3RST

级别 3 重置
@end deffn

@geindex ELNRNG() (在 errno 模块中)
@anchor{library/errno errno ELNRNG}@anchor{23e5}
@deffn {数据} errno.ELNRNG

链接编号超出范围
@end deffn

@geindex EUNATCH() (在 errno 模块中)
@anchor{library/errno errno EUNATCH}@anchor{23e6}
@deffn {数据} errno.EUNATCH

未附加协议驱动
@end deffn

@geindex ENOCSI() (在 errno 模块中)
@anchor{library/errno errno ENOCSI}@anchor{23e7}
@deffn {数据} errno.ENOCSI

没有可用的 CSI 结构
@end deffn

@geindex EL2HLT() (在 errno 模块中)
@anchor{library/errno errno EL2HLT}@anchor{23e8}
@deffn {数据} errno.EL2HLT

级别 2 已停止
@end deffn

@geindex EBADE() (在 errno 模块中)
@anchor{library/errno errno EBADE}@anchor{23e9}
@deffn {数据} errno.EBADE

无效的交换
@end deffn

@geindex EBADR() (在 errno 模块中)
@anchor{library/errno errno EBADR}@anchor{23ea}
@deffn {数据} errno.EBADR

无效的请求描述符
@end deffn

@geindex EXFULL() (在 errno 模块中)
@anchor{library/errno errno EXFULL}@anchor{23eb}
@deffn {数据} errno.EXFULL

交换已满
@end deffn

@geindex ENOANO() (在 errno 模块中)
@anchor{library/errno errno ENOANO}@anchor{23ec}
@deffn {数据} errno.ENOANO

没有阳极
@end deffn

@geindex EBADRQC() (在 errno 模块中)
@anchor{library/errno errno EBADRQC}@anchor{23ed}
@deffn {数据} errno.EBADRQC

无效的请求码·
@end deffn

@geindex EBADSLT() (在 errno 模块中)
@anchor{library/errno errno EBADSLT}@anchor{23ee}
@deffn {数据} errno.EBADSLT

无效的槽位
@end deffn

@geindex EDEADLOCK() (在 errno 模块中)
@anchor{library/errno errno EDEADLOCK}@anchor{23ef}
@deffn {数据} errno.EDEADLOCK

文件锁定死锁错误
@end deffn

@geindex EBFONT() (在 errno 模块中)
@anchor{library/errno errno EBFONT}@anchor{23f0}
@deffn {数据} errno.EBFONT

错误的字体文件格式
@end deffn

@geindex ENOSTR() (在 errno 模块中)
@anchor{library/errno errno ENOSTR}@anchor{23f1}
@deffn {数据} errno.ENOSTR

设备不是流
@end deffn

@geindex ENODATA() (在 errno 模块中)
@anchor{library/errno errno ENODATA}@anchor{23f2}
@deffn {数据} errno.ENODATA

没有可用的数据
@end deffn

@geindex ETIME() (在 errno 模块中)
@anchor{library/errno errno ETIME}@anchor{23f3}
@deffn {数据} errno.ETIME

计时器已到期
@end deffn

@geindex ENOSR() (在 errno 模块中)
@anchor{library/errno errno ENOSR}@anchor{23f4}
@deffn {数据} errno.ENOSR

流资源不足
@end deffn

@geindex ENONET() (在 errno 模块中)
@anchor{library/errno errno ENONET}@anchor{23f5}
@deffn {数据} errno.ENONET

机器不在网络上
@end deffn

@geindex ENOPKG() (在 errno 模块中)
@anchor{library/errno errno ENOPKG}@anchor{23f6}
@deffn {数据} errno.ENOPKG

包未安装
@end deffn

@geindex EREMOTE() (在 errno 模块中)
@anchor{library/errno errno EREMOTE}@anchor{23f7}
@deffn {数据} errno.EREMOTE

对象是远程的
@end deffn

@geindex ENOLINK() (在 errno 模块中)
@anchor{library/errno errno ENOLINK}@anchor{23f8}
@deffn {数据} errno.ENOLINK

链接已被切断
@end deffn

@geindex EADV() (在 errno 模块中)
@anchor{library/errno errno EADV}@anchor{23f9}
@deffn {数据} errno.EADV

广告错误
@end deffn

@geindex ESRMNT() (在 errno 模块中)
@anchor{library/errno errno ESRMNT}@anchor{23fa}
@deffn {数据} errno.ESRMNT

挂载错误
@end deffn

@geindex ECOMM() (在 errno 模块中)
@anchor{library/errno errno ECOMM}@anchor{23fb}
@deffn {数据} errno.ECOMM

发送时通讯错误
@end deffn

@geindex EPROTO() (在 errno 模块中)
@anchor{library/errno errno EPROTO}@anchor{23fc}
@deffn {数据} errno.EPROTO

协议错误
@end deffn

@geindex EMULTIHOP() (在 errno 模块中)
@anchor{library/errno errno EMULTIHOP}@anchor{23fd}
@deffn {数据} errno.EMULTIHOP

已尝试多跳
@end deffn

@geindex EDOTDOT() (在 errno 模块中)
@anchor{library/errno errno EDOTDOT}@anchor{23fe}
@deffn {数据} errno.EDOTDOT

RFS 专属错误
@end deffn

@geindex EBADMSG() (在 errno 模块中)
@anchor{library/errno errno EBADMSG}@anchor{23ff}
@deffn {数据} errno.EBADMSG

非数据消息
@end deffn

@geindex EOVERFLOW() (在 errno 模块中)
@anchor{library/errno errno EOVERFLOW}@anchor{2400}
@deffn {数据} errno.EOVERFLOW

值相对于已定义数据类型过大
@end deffn

@geindex ENOTUNIQ() (在 errno 模块中)
@anchor{library/errno errno ENOTUNIQ}@anchor{2401}
@deffn {数据} errno.ENOTUNIQ

名称在网络上不唯一
@end deffn

@geindex EBADFD() (在 errno 模块中)
@anchor{library/errno errno EBADFD}@anchor{2402}
@deffn {数据} errno.EBADFD

文件描述符处于错误状态
@end deffn

@geindex EREMCHG() (在 errno 模块中)
@anchor{library/errno errno EREMCHG}@anchor{2403}
@deffn {数据} errno.EREMCHG

远端地址已改变
@end deffn

@geindex ELIBACC() (在 errno 模块中)
@anchor{library/errno errno ELIBACC}@anchor{2404}
@deffn {数据} errno.ELIBACC

无法访问所需的共享库
@end deffn

@geindex ELIBBAD() (在 errno 模块中)
@anchor{library/errno errno ELIBBAD}@anchor{2405}
@deffn {数据} errno.ELIBBAD

访问已损坏的共享库
@end deffn

@geindex ELIBSCN() (在 errno 模块中)
@anchor{library/errno errno ELIBSCN}@anchor{2406}
@deffn {数据} errno.ELIBSCN

a.out 中的 .lib 部分已损坏
@end deffn

@geindex ELIBMAX() (在 errno 模块中)
@anchor{library/errno errno ELIBMAX}@anchor{2407}
@deffn {数据} errno.ELIBMAX

尝试链接过多的共享库
@end deffn

@geindex ELIBEXEC() (在 errno 模块中)
@anchor{library/errno errno ELIBEXEC}@anchor{2408}
@deffn {数据} errno.ELIBEXEC

无法直接执行共享库
@end deffn

@geindex EILSEQ() (在 errno 模块中)
@anchor{library/errno errno EILSEQ}@anchor{2409}
@deffn {数据} errno.EILSEQ

非法字节序列
@end deffn

@geindex ERESTART() (在 errno 模块中)
@anchor{library/errno errno ERESTART}@anchor{240a}
@deffn {数据} errno.ERESTART

已中断系统调用需要重启
@end deffn

@geindex ESTRPIPE() (在 errno 模块中)
@anchor{library/errno errno ESTRPIPE}@anchor{240b}
@deffn {数据} errno.ESTRPIPE

流管道错误
@end deffn

@geindex EUSERS() (在 errno 模块中)
@anchor{library/errno errno EUSERS}@anchor{240c}
@deffn {数据} errno.EUSERS

用户过多
@end deffn

@geindex ENOTSOCK() (在 errno 模块中)
@anchor{library/errno errno ENOTSOCK}@anchor{240d}
@deffn {数据} errno.ENOTSOCK

在非套接字上执行套接字操作
@end deffn

@geindex EDESTADDRREQ() (在 errno 模块中)
@anchor{library/errno errno EDESTADDRREQ}@anchor{240e}
@deffn {数据} errno.EDESTADDRREQ

需要目标地址
@end deffn

@geindex EMSGSIZE() (在 errno 模块中)
@anchor{library/errno errno EMSGSIZE}@anchor{240f}
@deffn {数据} errno.EMSGSIZE

消息过长
@end deffn

@geindex EPROTOTYPE() (在 errno 模块中)
@anchor{library/errno errno EPROTOTYPE}@anchor{2410}
@deffn {数据} errno.EPROTOTYPE

套接字的协议类型错误
@end deffn

@geindex ENOPROTOOPT() (在 errno 模块中)
@anchor{library/errno errno ENOPROTOOPT}@anchor{2411}
@deffn {数据} errno.ENOPROTOOPT

协议不可用
@end deffn

@geindex EPROTONOSUPPORT() (在 errno 模块中)
@anchor{library/errno errno EPROTONOSUPPORT}@anchor{2412}
@deffn {数据} errno.EPROTONOSUPPORT

协议不受支持
@end deffn

@geindex ESOCKTNOSUPPORT() (在 errno 模块中)
@anchor{library/errno errno ESOCKTNOSUPPORT}@anchor{2413}
@deffn {数据} errno.ESOCKTNOSUPPORT

套接字类型不受支持
@end deffn

@geindex EOPNOTSUPP() (在 errno 模块中)
@anchor{library/errno errno EOPNOTSUPP}@anchor{2414}
@deffn {数据} errno.EOPNOTSUPP

操作在传输端点上不受支持
@end deffn

@geindex EPFNOSUPPORT() (在 errno 模块中)
@anchor{library/errno errno EPFNOSUPPORT}@anchor{2415}
@deffn {数据} errno.EPFNOSUPPORT

协议族不受支持
@end deffn

@geindex EAFNOSUPPORT() (在 errno 模块中)
@anchor{library/errno errno EAFNOSUPPORT}@anchor{2416}
@deffn {数据} errno.EAFNOSUPPORT

地址族不受协议支持
@end deffn

@geindex EADDRINUSE() (在 errno 模块中)
@anchor{library/errno errno EADDRINUSE}@anchor{2417}
@deffn {数据} errno.EADDRINUSE

地址已被使用
@end deffn

@geindex EADDRNOTAVAIL() (在 errno 模块中)
@anchor{library/errno errno EADDRNOTAVAIL}@anchor{2418}
@deffn {数据} errno.EADDRNOTAVAIL

无法分配要求的地址
@end deffn

@geindex ENETDOWN() (在 errno 模块中)
@anchor{library/errno errno ENETDOWN}@anchor{2419}
@deffn {数据} errno.ENETDOWN

网络已断开
@end deffn

@geindex ENETUNREACH() (在 errno 模块中)
@anchor{library/errno errno ENETUNREACH}@anchor{1168}
@deffn {数据} errno.ENETUNREACH

网络不可达
@end deffn

@geindex ENETRESET() (在 errno 模块中)
@anchor{library/errno errno ENETRESET}@anchor{241a}
@deffn {数据} errno.ENETRESET

网络因重置而断开连接
@end deffn

@geindex ECONNABORTED() (在 errno 模块中)
@anchor{library/errno errno ECONNABORTED}@anchor{189f}
@deffn {数据} errno.ECONNABORTED

软件导致连接中止。这个错误被映射到异常 @ref{a88,,ConnectionAbortedError} 。
@end deffn

@geindex ECONNRESET() (在 errno 模块中)
@anchor{library/errno errno ECONNRESET}@anchor{18a1}
@deffn {数据} errno.ECONNRESET

连接被对方重置。这个错误被映射到异常 @ref{a8a,,ConnectionResetError} 。
@end deffn

@geindex ENOBUFS() (在 errno 模块中)
@anchor{library/errno errno ENOBUFS}@anchor{241b}
@deffn {数据} errno.ENOBUFS

没有可用的缓冲区空间
@end deffn

@geindex EISCONN() (在 errno 模块中)
@anchor{library/errno errno EISCONN}@anchor{241c}
@deffn {数据} errno.EISCONN

传输端点已连接
@end deffn

@geindex ENOTCONN() (在 errno 模块中)
@anchor{library/errno errno ENOTCONN}@anchor{241d}
@deffn {数据} errno.ENOTCONN

传输端点未连接
@end deffn

@geindex ESHUTDOWN() (在 errno 模块中)
@anchor{library/errno errno ESHUTDOWN}@anchor{189e}
@deffn {数据} errno.ESHUTDOWN

在传输端点关闭后无法发送。这个错误被映射到异常 @ref{a87,,BrokenPipeError} 。
@end deffn

@geindex ETOOMANYREFS() (在 errno 模块中)
@anchor{library/errno errno ETOOMANYREFS}@anchor{241e}
@deffn {数据} errno.ETOOMANYREFS

引用过多：无法拼接
@end deffn

@geindex ETIMEDOUT() (在 errno 模块中)
@anchor{library/errno errno ETIMEDOUT}@anchor{18a9}
@deffn {数据} errno.ETIMEDOUT

连接超时。这个错误被映射到异常 @ref{a86,,TimeoutError} 。
@end deffn

@geindex ECONNREFUSED() (在 errno 模块中)
@anchor{library/errno errno ECONNREFUSED}@anchor{18a0}
@deffn {数据} errno.ECONNREFUSED

连接被拒绝。这个错误被映射到异常 @ref{a89,,ConnectionRefusedError} 。
@end deffn

@geindex EHOSTDOWN() (在 errno 模块中)
@anchor{library/errno errno EHOSTDOWN}@anchor{241f}
@deffn {数据} errno.EHOSTDOWN

主机已关闭
@end deffn

@geindex EHOSTUNREACH() (在 errno 模块中)
@anchor{library/errno errno EHOSTUNREACH}@anchor{2420}
@deffn {数据} errno.EHOSTUNREACH

没有到主机的路由
@end deffn

@geindex EALREADY() (在 errno 模块中)
@anchor{library/errno errno EALREADY}@anchor{1898}
@deffn {数据} errno.EALREADY

操作已经在进行中。这个错误被映射到异常 @ref{a81,,BlockingIOError} 。
@end deffn

@geindex EINPROGRESS() (在 errno 模块中)
@anchor{library/errno errno EINPROGRESS}@anchor{189a}
@deffn {数据} errno.EINPROGRESS

操作现在正在进行中。这个错误被映射到异常 @ref{a81,,BlockingIOError} 。
@end deffn

@geindex ESTALE() (在 errno 模块中)
@anchor{library/errno errno ESTALE}@anchor{2421}
@deffn {数据} errno.ESTALE

过期的 NFS 文件句柄
@end deffn

@geindex EUCLEAN() (在 errno 模块中)
@anchor{library/errno errno EUCLEAN}@anchor{2422}
@deffn {数据} errno.EUCLEAN

结构需要清理
@end deffn

@geindex ENOTNAM() (在 errno 模块中)
@anchor{library/errno errno ENOTNAM}@anchor{2423}
@deffn {数据} errno.ENOTNAM

不是 XENIX 命名类型文件
@end deffn

@geindex ENAVAIL() (在 errno 模块中)
@anchor{library/errno errno ENAVAIL}@anchor{2424}
@deffn {数据} errno.ENAVAIL

没有可用的 XENIX 信标
@end deffn

@geindex EISNAM() (在 errno 模块中)
@anchor{library/errno errno EISNAM}@anchor{2425}
@deffn {数据} errno.EISNAM

是命名类型文件
@end deffn

@geindex EREMOTEIO() (在 errno 模块中)
@anchor{library/errno errno EREMOTEIO}@anchor{2426}
@deffn {数据} errno.EREMOTEIO

远程 I/O 错误
@end deffn

@geindex EDQUOT() (在 errno 模块中)
@anchor{library/errno errno EDQUOT}@anchor{2427}
@deffn {数据} errno.EDQUOT

超出配额
@end deffn

@node ctypes --- Python 的外部函数库,,errno --- 标准 errno 系统符号,通用操作系统服务
@anchor{library/ctypes doc}@anchor{2428}@anchor{library/ctypes ctypes-a-foreign-function-library-for-python}@anchor{2429}@anchor{library/ctypes module-ctypes}@anchor{2a}
@subsection @code{ctypes} --- Python 的外部函数库


@geindex ctypes (模块)


__________________________________________________________________


@ref{2a,,ctypes} 是 Python 的外部函数库。它提供了与 C 兼容的数据类型，并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进行封装。

@menu
* ctypes 教程:: 
* ctypes 参考手册:: 

@end menu

@node ctypes 教程,ctypes 参考手册,,ctypes --- Python 的外部函数库
@anchor{library/ctypes ctypes-ctypes-tutorial}@anchor{242a}@anchor{library/ctypes ctypes-tutorial}@anchor{242b}
@subsubsection ctypes 教程


注：本教程中的示例代码使用 @ref{66,,doctest} 来保证它们能正确运行。 由于有些代码示例在 Linux, Windows 或 macOS 上的行为有所不同，它们在注释中包含了一些 doctest 指令。

注意：部分示例代码引用了 ctypes @ref{242c,,c_int} 类型。在 @code{sizeof(long) == sizeof(int)} 的平台上此类型是 @ref{242d,,c_long} 的一个别名。所以，在程序输出 @ref{242d,,c_long} 而不是你期望的 @ref{242c,,c_int} 时不必感到迷惑 --- 它们实际上是同一种类型。

@menu
* 载入动态连接库:: 
* 操作导入的动态链接库中的函数:: 
* 调用函数:: 
* 基础数据类型:: 
* 调用函数，继续:: 
* 使用自定义的数据类型调用函数:: 
* 指定必选参数的类型(函数原型): 指定必选参数的类型 函数原型. 
* 返回类型:: 
* 传递指针（或以引用方式传递形参）:: 
* 结构体和联合:: 
* 结构体/联合字段对齐及字节顺序:: 
* 结构体和联合中的位域:: 
* 数组:: 
* 指针:: 
* 类型转换:: 
* 不完整类型:: 
* 回调函数:: 
* 访问 dll 的导出变量:: 
* 意外:: 
* 变长数据类型:: 

@end menu

@node 载入动态连接库,操作导入的动态链接库中的函数,,ctypes 教程
@anchor{library/ctypes ctypes-loading-dynamic-link-libraries}@anchor{242e}@anchor{library/ctypes loading-dynamic-link-libraries}@anchor{242f}
@subsubsection 载入动态连接库


@ref{2a,,ctypes} 导出了 @emph{cdll} 对象，在 Windows 系统中还导出了 @emph{windll} 和 @emph{oledll} 对象用于载入动态连接库。

通过操作这些对象的属性，你可以载入外部的动态链接库。@emph{cdll} 载入按标准的 @code{cdecl} 调用协议导出的函数，而 @emph{windll} 导入的库按 @code{stdcall} 调用协议调用其中的函数。 @emph{oledll} 也按 @code{stdcall} 调用协议调用其中的函数，并假定该函数返回的是 Windows @code{HRESULT} 错误代码，并当函数调用失败时，自动根据该代码甩出一个 @ref{30b,,OSError} 异常。


在 3.3 版更改: 原来在 Windows 下抛出的异常类型 @ref{a7e,,WindowsError} 现在是 @ref{30b,,OSError} 的一个别名。


这是一些 Windows 下的例子。注意：@code{msvcrt} 是微软 C 标准库，包含了大部分 C 标准函数，这些函数都是以 cdecl 调用协议进行调用的。

@example
>>> from ctypes import *
>>> print(windll.kernel32)  
<WinDLL 'kernel32', handle ... at ...>
>>> print(cdll.msvcrt)      
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt      
>>>
@end example

Windows 会自动添加通常的 @code{.dll} 文件扩展名。

@cartouche
@quotation 注解 
通过 @code{cdll.msvcrt} 调用的标准 C 函数，可能会导致调用一个过时的，与当前 Python 所不兼容的函数。因此，请尽量使用标准的 Python 函数，而不要使用 @code{msvcrt} 模块。
@end quotation
@end cartouche

在 Linux 下，必须使用 @emph{包含} 文件扩展名的文件名来导入共享库。因此不能简单使用对象属性的方式来导入库。因此，你可以使用方法 @code{LoadLibrary()}，或构造 CDLL 对象来导入库。

@example
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle ... at ...>
>>>
@end example

@c XXX Add section for macOS.

@node 操作导入的动态链接库中的函数,调用函数,载入动态连接库,ctypes 教程
@anchor{library/ctypes accessing-functions-from-loaded-dlls}@anchor{2430}@anchor{library/ctypes ctypes-accessing-functions-from-loaded-dlls}@anchor{2431}
@subsubsection 操作导入的动态链接库中的函数


通过操作dll对象的属性来操作这些函数。

@example
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
@end example

注意：Win32 系统的动态库，比如 @code{kernel32} 和 @code{user32}，通常会同时导出同一个函数的 ANSI 版本和 UNICODE 版本。UNICODE 版本通常会在名字最后以 @code{W} 结尾，而 ANSI 版本的则以 @code{A} 结尾。 win32的 @code{GetModuleHandle} 函数会根据一个模块名返回一个 @emph{模块句柄}，该函数暨同时包含这样的两个版本的原型函数，并通过宏 UNICODE 是否定义，来决定宏 @code{GetModuleHandle} 导出的是哪个具体函数。

@example
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
@end example

@emph{windll} 不会通过这样的魔法手段来帮你决定选择哪一种函数，你必须显式的调用 @code{GetModuleHandleA} 或 @code{GetModuleHandleW}，并分别使用字节对象或字符串对象作参数。

有时候，dlls的导出的函数名不符合 Python 的标识符规范，比如 @code{"??2@@YAPAXI@@Z"}。此时，你必须使用 @ref{554,,getattr()} 方法来获得该函数。

@example
>>> getattr(cdll.msvcrt, "??2@@YAPAXI@@Z")  
<_FuncPtr object at 0x...>
>>>
@end example

Windows 下，有些 dll 导出的函数没有函数名，而是通过其顺序号调用。对此类函数，你也可以通过 dll 对象的数值索引来操作这些函数。

@example
>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
@end example

@node 调用函数,基础数据类型,操作导入的动态链接库中的函数,ctypes 教程
@anchor{library/ctypes calling-functions}@anchor{2432}@anchor{library/ctypes ctypes-calling-functions}@anchor{2433}
@subsubsection 调用函数


你可以貌似是调用其它 Python 函数那样直接调用这些函数。在这个例子中，我们调用了 @code{time()} 函数，该函数返回一个系统时间戳（从 Unix 时间起点到现在的秒数），而`@w{`}GetModuleHandleA()`@w{`} 函数返回一个 win32 模块句柄。

此函数中调用的两个函数都使用了空指针（用 @code{None} 作为空指针）:

@example
>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
@end example

如果你用 @code{cdecl} 调用方式调用 @code{stdcall} 约定的函数，则会甩出一个异常 @ref{16d,,ValueError}。反之亦然。

@example
>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
@end example

你必须阅读这些库的头文件或说明文档来确定它们的调用协议。

在 Windows 中，@ref{2a,,ctypes} 使用 win32 结构化异常处理来防止由于在调用函数时使用非法参数导致的程序崩溃。

@example
>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
@end example

然而，总有许多办法，通过调用 @ref{2a,,ctypes} 使得 Python 程序崩溃。因此，你必须小心使用。 @ref{7b,,faulthandler} 模块可以用于帮助诊断程序崩溃的原因。（比如由于错误的C库函数调用导致的段错误）。

@code{None}，整型，字节对象和（UNICODE）字符串是仅有的可以直接作为函数参数使用的四种Python本地数据类型。@cite{None`} 作为C的空指针 (@code{NULL})，字节和字符串类型作为一个指向其保存数据的内存块指针 （@code{char *} 或 @code{wchar_t *})。Python 的整型则作为平台默认的C的 @code{int} 类型，他们的数值被截断以适应C类型的整型长度。

在我们开始调用函数前，我们必须先了解作为函数参数的 @ref{2a,,ctypes} 数据类型。

@node 基础数据类型,调用函数，继续,调用函数,ctypes 教程
@anchor{library/ctypes ctypes-fundamental-data-types}@anchor{2434}@anchor{library/ctypes fundamental-data-types}@anchor{2435}
@subsubsection 基础数据类型


@ref{2a,,ctypes} 定义了一些和C兼容的基本数据类型：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ctypes 类型

@tab

C 类型

@tab

Python 数据类型

@item

@ref{2436,,c_bool}

@tab

@code{_Bool}

@tab

bool (1)

@item

@ref{2437,,c_char}

@tab

@code{char}

@tab

单字符字节串对象

@item

@ref{2438,,c_wchar}

@tab

@code{wchar_t}

@tab

单字符字符串

@item

@ref{2439,,c_byte}

@tab

@code{char}

@tab

int

@item

@ref{243a,,c_ubyte}

@tab

@code{unsigned char}

@tab

int

@item

@ref{243b,,c_short}

@tab

@code{short}

@tab

int

@item

@ref{243c,,c_ushort}

@tab

@code{unsigned short}

@tab

int

@item

@ref{242c,,c_int}

@tab

@code{int}

@tab

int

@item

@ref{243d,,c_uint}

@tab

@code{unsigned int}

@tab

int

@item

@ref{242d,,c_long}

@tab

@code{long}

@tab

int

@item

@ref{243e,,c_ulong}

@tab

@code{unsigned long}

@tab

int

@item

@ref{243f,,c_longlong}

@tab

@code{__int64} 或 @code{long long}

@tab

int

@item

@ref{2440,,c_ulonglong}

@tab

@code{unsigned __int64} 或 @code{unsigned long long}

@tab

int

@item

@ref{2441,,c_size_t}

@tab

@code{size_t}

@tab

int

@item

@ref{ca7,,c_ssize_t}

@tab

@code{ssize_t} 或 @ref{391,,Py_ssize_t}

@tab

int

@item

@ref{2442,,c_float}

@tab

@code{float}

@tab

float

@item

@ref{100f,,c_double}

@tab

@code{double}

@tab

float

@item

@ref{1010,,c_longdouble}

@tab

@code{long double}

@tab

float

@item

@ref{2443,,c_char_p}

@tab

@code{char *} (NUL terminated)

@tab

字节串对象或 @code{None}

@item

@ref{ff4,,c_wchar_p}

@tab

@code{wchar_t *} (NUL terminated)

@tab

字符串或 @code{None}

@item

@ref{2444,,c_void_p}

@tab

@code{void *}

@tab

int 或 @code{None}

@end multitable



@enumerate 

@item 
构造函数接受任何具有真值的对象。
@end enumerate

所有这些类型都可以通过使用正确类型和值的可选初始值调用它们来创建:

@example
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
@end example

由于这些类型是可变的，它们的值也可以在以后更改:

@example
>>> i = c_int(42)
>>> print(i)
c_long(42)
>>> print(i.value)
42
>>> i.value = -99
>>> print(i.value)
-99
>>>
@end example

当给指针类型的对象 @ref{2443,,c_char_p}, @ref{ff4,,c_wchar_p} 和 @ref{2444,,c_void_p} 等赋值时，将改变它们所指向的 @emph{内存地址}，而 @emph{不是} 它们所指向的内存区域的 @emph{内容} (这是理所当然的，因为 Python 的 bytes 对象是不可变的):

@example
>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s)              # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s)                # first object is unchanged
Hello, World
>>>
@end example

但你要注意不能将它们传递给会改变指针所指内存的函数。如果你需要可改变的内存块，ctypes 提供了 @ref{2445,,create_string_buffer()} 函数，它提供多种方式创建这种内存块。当前的内存块内容可以通过 @code{raw} 属性存取，如果你希望将它作为NUL结束的字符串，请使用 @code{value} 属性:

@example
>>> from ctypes import *
>>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>
@end example

@ref{2445,,create_string_buffer()} 函数替代以前的ctypes版本中的 @code{c_buffer()} 函数 (仍然可当作别名使用)和 @code{c_string()} 函数。@ref{1120,,create_unicode_buffer()} 函数创建包含 unicode 字符的可变内存块，与之对应的C语言类型是 @code{wchar_t}。

@node 调用函数，继续,使用自定义的数据类型调用函数,基础数据类型,ctypes 教程
@anchor{library/ctypes calling-functions-continued}@anchor{2446}@anchor{library/ctypes ctypes-calling-functions-continued}@anchor{2447}
@subsubsection 调用函数，继续


注意 printf 将打印到真正标准输出设备，而*不是* @ref{428,,sys.stdout}，因此这些实例只能在控制台提示符下工作，而不能在 @emph{IDLE} 或 @emph{PythonWin} 中运行。

@example
>>> printf = libc.printf
>>> printf(b"Hello, %s\n", b"World!")
Hello, World!
14
>>> printf(b"Hello, %S\n", "World!")
Hello, World!
14
>>> printf(b"%d bottles of beer\n", 42)
42 bottles of beer
19
>>> printf(b"%f bottles of beer\n", 42.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
>>>
@end example

正如前面所提到过的，除了整数、字符串以及字节串之外，所有的 Python 类型都必须使用它们对应的 @ref{2a,,ctypes} 类型包装，才能够被正确地转换为所需的C语言类型。

@example
>>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
An int 1234, a double 3.140000
31
>>>
@end example

@node 使用自定义的数据类型调用函数,指定必选参数的类型 函数原型,调用函数，继续,ctypes 教程
@anchor{library/ctypes calling-functions-with-your-own-custom-data-types}@anchor{2448}@anchor{library/ctypes ctypes-calling-functions-with-own-custom-data-types}@anchor{2449}
@subsubsection 使用自定义的数据类型调用函数


你也可以通过自定义  @ref{2a,,ctypes} 参数转换方式来允许自定义类型作为参数。 @ref{2a,,ctypes} 会寻找 @code{_as_parameter_} 属性并使用它作为函数参数。当然，它必须是数字、字符串或者二进制字符串:

@example
>>> class Bottles:
...     def __init__(self, number):
...         self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> printf(b"%d bottles of beer\n", bottles)
42 bottles of beer
19
>>>
@end example

如果你不想把实例的数据存储到 @code{_as_parameter_} 属性。可以通过定义 @ref{30f,,property} 函数计算出这个属性。

@node 指定必选参数的类型 函数原型,返回类型,使用自定义的数据类型调用函数,ctypes 教程
@anchor{library/ctypes ctypes-specifying-required-argument-types}@anchor{244a}@anchor{library/ctypes specifying-the-required-argument-types-function-prototypes}@anchor{244b}
@subsubsection 指定必选参数的类型(函数原型)


可以通过设置 @code{argtypes} 属性的方法指定从 DLL 中导出函数的必选参数类型。

@code{argtypes} 必须是一个 C 数据类型的序列 (这里的 @code{printf} 可能不是个好例子，因为它是变长参数，而且每个参数的类型依赖于格式化字符串，不过尝试这个功能也很方便):

@example
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>>
@end example

指定数据类型可以防止不合理的参数传递（就像 C 函数的原型），并且会自动尝试将参数转换为需要的类型:

@example
>>> printf(b"%d %d %d", 1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: wrong type
>>> printf(b"%s %d %f\n", b"X", 2, 3)
X 2 3.000000
13
>>>
@end example

如果你想通过自定义类型传递参数给函数，必须实现 @code{from_param()} 类方法，才能够将此自定义类型用于 @code{argtypes} 序列。@code{from_param()} 类方法接受一个 Python 对象作为函数输入，它应该进行类型检查或者其他必要的操作以保证接收到的对象是合法的，然后返回这个对象，或者它的 @code{_as_parameter_} 属性，或者其他你想要传递给 C 函数的参数。这里也一样，返回的结果必须是整型、字符串、二进制字符串、 @ref{2a,,ctypes} 类型，或者一个具有 @code{_as_parameter_} 属性的对象。

@node 返回类型,传递指针（或以引用方式传递形参）,指定必选参数的类型 函数原型,ctypes 教程
@anchor{library/ctypes ctypes-return-types}@anchor{244c}@anchor{library/ctypes return-types}@anchor{244d}
@subsubsection 返回类型


默认情况下都会假定函数返回 C @code{int} 类型。 其他返回类型可以通过设置函数对象的 @code{restype} 属性来指定。

这是个更高级的例子，它调用了 @code{strchr} 函数，这个函数接收一个字符串指针以及一个字符作为参数，返回另一个字符串指针。

@example
>>> strchr = libc.strchr
>>> strchr(b"abcdef", ord("d"))  
8059983
>>> strchr.restype = c_char_p    # c_char_p is a pointer to a string
>>> strchr(b"abcdef", ord("d"))
b'def'
>>> print(strchr(b"abcdef", ord("x")))
None
>>>
@end example

如果希望避免上述的 @code{ord("x")} 调用，可以设置  @code{argtypes} 属性，第二个参数就会将单字符的 Python 二进制字符对象转换为 C 字符:

@example
>>> strchr.restype = c_char_p
>>> strchr.argtypes = [c_char_p, c_char]
>>> strchr(b"abcdef", b"d")
'def'
>>> strchr(b"abcdef", b"def")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: one character string expected
>>> print(strchr(b"abcdef", b"x"))
None
>>> strchr(b"abcdef", b"d")
'def'
>>>
@end example

如果外部函数返回了一个整数，你也可以使用要给可调用的 Python 对象（比如函数或者类）作为 @code{restype} 属性的值。将会以 C 函数返回的 @emph{整数} 对象作为参数调用这个可调用对象，执行后的结果作为最终函数返回值。这在错误返回值校验和自动抛出异常等方面比较有用。

@example
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA  
>>> def ValidHandle(value):
...     if value == 0:
...         raise WinError()
...     return value
...
>>>
>>> GetModuleHandle.restype = ValidHandle  
>>> GetModuleHandle(None)  
486539264
>>> GetModuleHandle("something silly")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in ValidHandle
OSError: [Errno 126] The specified module could not be found.
>>>
@end example

@code{WinError} 函数可以调用 Windows 的  @code{FormatMessage()} API 获取错误码的字符串说明，然后 @emph{返回} 一个异常。 @code{WinError} 接收一个可选的错误码作为参数，如果没有的话，它将调用  @ref{244e,,GetLastError()} 获取错误码。

请注意，使用 @code{errcheck}  属性可以实现更强大的错误检查手段；详情请见参考手册。

@node 传递指针（或以引用方式传递形参）,结构体和联合,返回类型,ctypes 教程
@anchor{library/ctypes ctypes-passing-pointers}@anchor{244f}@anchor{library/ctypes passing-pointers-or-passing-parameters-by-reference}@anchor{2450}
@subsubsection 传递指针（或以引用方式传递形参）


有时候 C 函数接口可能由于要往某个地址写入值，或者数据太大不适合作为值传递，从而希望接收一个 @emph{指针} 作为数据参数类型。这和 @emph{传递参数引用} 类似。

@ref{2a,,ctypes} 暴露了 @ref{2451,,byref()} 函数用于通过引用传递参数，使用 @ref{2452,,pointer()} 函数也能达到同样的效果，只不过 @ref{2452,,pointer()} 需要更多步骤，因为它要先构造一个真实指针对象。所以在 Python 代码本身不需要使用这个指针对象的情况下，使用 @ref{2451,,byref()} 效率更高。

@example
>>> i = c_int()
>>> f = c_float()
>>> s = create_string_buffer(b'\000' * 32)
>>> print(i.value, f.value, repr(s.value))
0 0.0 b'@w{'}
>>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
...             byref(i), byref(f), s)
3
>>> print(i.value, f.value, repr(s.value))
1 3.1400001049 b'Hello'
>>>
@end example

@node 结构体和联合,结构体/联合字段对齐及字节顺序,传递指针（或以引用方式传递形参）,ctypes 教程
@anchor{library/ctypes ctypes-structures-unions}@anchor{2453}@anchor{library/ctypes structures-and-unions}@anchor{2454}
@subsubsection 结构体和联合


结构体和联合必须继承自 @ref{2a,,ctypes} 模块中的 @ref{2455,,Structure} 和 @ref{2456,,Union} 。子类必须定义 @code{_fields_} 属性。 @code{_fields_} 是一个二元组列表，二元组中包含 @emph{field name} 和 @emph{field type} 。

type 字段必须是一个 @ref{2a,,ctypes} 类型，比如  @ref{242c,,c_int}，或者其他 @ref{2a,,ctypes} 类型: 结构体、联合、数组、指针。

这是一个简单的 POINT 结构体，它包含名称为 @emph{x} 和 @emph{y} 的两个变量，还展示了如何通过构造函数初始化结构体。

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print(point.x, point.y)
10 20
>>> point = POINT(y=5)
>>> print(point.x, point.y)
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: too many initializers
>>>
@end example

当然，你可以构造更复杂的结构体。一个结构体可以通过设置 type 字段包含其他结构体或者自身。

这是以一个 RECT 结构体，他包含了两个 POINT ，分别叫 @emph{upperleft} 和 @emph{lowerright}:

@example
>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>
@end example

嵌套结构体可以通过几种方式构造初始化:

@example
>>> r = RECT(POINT(1, 2), POINT(3, 4))
>>> r = RECT((1, 2), (3, 4))
@end example

可以通过 @emph{类} 获取字段 @ref{15a8,,descriptor} ，它能提供很多有用的调试信息。

@example
>>> print(POINT.x)
<Field type=c_long, ofs=0, size=4>
>>> print(POINT.y)
<Field type=c_long, ofs=4, size=4>
>>>
@end example
@anchor{library/ctypes ctypes-structureunion-alignment-byte-order}@anchor{2457}
@cartouche
@quotation 警告 
@ref{2a,,ctypes} 不支持带位域的结构体、联合以值的方式传给函数。这可能在 32 位 x86 平台上可以正常工作，但是对于一般情况，这种行为是未定义的。带位域的结构体、联合应该总是通过指针传递给函数。
@end quotation
@end cartouche

@node 结构体/联合字段对齐及字节顺序,结构体和联合中的位域,结构体和联合,ctypes 教程
@anchor{library/ctypes structure-union-alignment-and-byte-order}@anchor{2458}
@subsubsection 结构体/联合字段对齐及字节顺序


默认情况下，结构体和联合的字段与 C 的字节对齐是一样的。也可以在定义子类的时候指定类的 @code{_pack_} 属性来覆盖这种行为。 它必须设置为一个正整数，表示字段的最大对齐字节。这和 MSVC 中的 @code{#pragma pack(n)} 功能一样。

@ref{2a,,ctypes} 中的结构体和联合使用的是本地字节序。要使用非本地字节序，可以使用 @ref{2459,,BigEndianStructure}, @ref{245a,,LittleEndianStructure}, @code{BigEndianUnion}, and @code{LittleEndianUnion} 作为基类。这些类不能包含指针字段。

@node 结构体和联合中的位域,数组,结构体/联合字段对齐及字节顺序,ctypes 教程
@anchor{library/ctypes bit-fields-in-structures-and-unions}@anchor{245b}@anchor{library/ctypes ctypes-bit-fields-in-structures-unions}@anchor{245c}
@subsubsection 结构体和联合中的位域


结构体和联合中是可以包含位域字段的。位域只能用于整型字段，位长度通过 @code{_fields_} 中的第三个参数指定:

@example
>>> class Int(Structure):
...     _fields_ = [("first_16", c_int, 16),
...                 ("second_16", c_int, 16)]
...
>>> print(Int.first_16)
<Field type=c_long, ofs=0:0, bits=16>
>>> print(Int.second_16)
<Field type=c_long, ofs=0:16, bits=16>
>>>
@end example

@node 数组,指针,结构体和联合中的位域,ctypes 教程
@anchor{library/ctypes arrays}@anchor{245d}@anchor{library/ctypes ctypes-arrays}@anchor{245e}
@subsubsection 数组


数组是一个序列，包含指定个数元素，且必须类型相同。

创建数组类型的推荐方式是使用一个类型乘以一个正数:

@example
TenPointsArrayType = POINT * 10
@end example

下面是一个构造的数据案例，结构体中包含了4个 POINT 和一些其他东西。

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class MyStruct(Structure):
...     _fields_ = [("a", c_int),
...                 ("b", c_float),
...                 ("point_array", POINT * 4)]
>>>
>>> print(len(MyStruct().point_array))
4
>>>
@end example

和平常一样，通过调用它创建实例:

@example
arr = TenPointsArrayType()
for pt in arr:
    print(pt.x, pt.y)
@end example

以上代码会打印几行 @code{0 0} ，因为数组内容被初始化为 0.

也能通过指定正确类型的数据来初始化:

@example
>>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print(ii)
<c_long_Array_10 object at 0x...>
>>> for i in ii: print(i, end=" ")
...
1 2 3 4 5 6 7 8 9 10
>>>
@end example

@node 指针,类型转换,数组,ctypes 教程
@anchor{library/ctypes ctypes-pointers}@anchor{245f}@anchor{library/ctypes pointers}@anchor{2460}
@subsubsection 指针


可以将 @ref{2a,,ctypes} 类型数据传入 @ref{2452,,pointer()} 函数创建指针:

@example
>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>
@end example

指针实例拥有 @ref{2461,,contents} 属性，它返回指针指向的真实对象，如上面的 @code{i} 对象:

@example
>>> pi.contents
c_long(42)
>>>
@end example

注意 @ref{2a,,ctypes} 并没有 OOR （返回原始对象）, 每次访问这个属性时都会构造返回一个新的相同对象:

@example
>>> pi.contents is i
False
>>> pi.contents is pi.contents
False
>>>
@end example

将这个指针的 contents 属性赋值为另一个 @ref{242c,,c_int} 实例将会导致该指针指向该实例的内存地址:

@example
>>> i = c_int(99)
>>> pi.contents = i
>>> pi.contents
c_long(99)
>>>
@end example

@c XXX Document dereferencing pointers, and that it is preferred over the
@c .contents attribute.

指针对象也可以通过整数下标进行访问:

@example
>>> pi[0]
99
>>>
@end example

通过整数下标赋值可以改变指针所指向的真实内容:

@example
>>> print(i)
c_long(99)
>>> pi[0] = 22
>>> print(i)
c_long(22)
>>>
@end example

使用 0 以外的索引也是合法的，但是你必须确保知道自己为什么这么做，就像 C 语言中: 你可以访问或者修改任意内存内容。 通常只会在函数接收指针是才会使用这种特性，而且你 @emph{知道} 这个指针指向的是一个数组而不是单个值。

内部细节,  @ref{2452,,pointer()} 函数不只是创建了一个指针实例，它首先创建了一个指针 @emph{类型} 。这是通过调用 @ref{2462,,POINTER()} 函数实现的，它接收  @ref{2a,,ctypes} 类型为参数，返回一个新的类型:

@example
>>> PI = POINTER(c_int)
>>> PI
<class 'ctypes.LP_c_long'>
>>> PI(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected c_long instead of int
>>> PI(c_int(42))
<ctypes.LP_c_long object at 0x...>
>>>
@end example

无参调用指针类型可以创建一个 @code{NULL} 指针。 @code{NULL} 指针的布尔值是 @code{False}

@example
>>> null_ptr = POINTER(c_int)()
>>> print(bool(null_ptr))
False
>>>
@end example

解引用指针的时候， @ref{2a,,ctypes} 会帮你检测是否指针为 @code{NULL} (但是解引用无效的 非 @code{NULL} 指针仍会导致 Python 崩溃):

@example
>>> null_ptr[0]
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>

>>> null_ptr[0] = 1234
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>
@end example

@node 类型转换,不完整类型,指针,ctypes 教程
@anchor{library/ctypes ctypes-type-conversions}@anchor{2463}@anchor{library/ctypes type-conversions}@anchor{2464}
@subsubsection 类型转换


通常情况下, ctypes 具有严格的类型检查。这代表着, 如果在函数 @code{argtypes} 中或者结构体定义成员中有 @code{POINTER(c_int)} 类型，只有相同类型的实例才会被接受。 也有一些例外。比如，你可以传递兼容的数组实例给指针类型。所以，对于  @code{POINTER(c_int)} ，ctypes 也可以接受 c_int 类型的数组:

@example
>>> class Bar(Structure):
...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
...     print(bar.values[i])
...
1
2
3
>>>
@end example

另外，如果一个函数 @code{argtypes} 列表中的参数显式的定义为指针类型(如 @code{POINTER(c_int)} )，指针所指向的 类型 (这个例子中是 @code{c_int} )也可以传递给函数。ctypes 会自动调用对应的 @ref{2451,,byref()} 转换。

可以给指针内容赋值为 None 将其设置为 @code{Null}

@example
>>> bar.values = None
>>>
@end example

@c XXX list other conversions...

有时候你拥有一个不兼容的类型。 在 C 中，你可以将一个类型强制转换为另一个。 @ref{2a,,ctypes} 中的 a @ref{1194,,cast()} 函数提供了相同的功能。 上面的结构体  @code{Bar} 的 @code{value} 字段接收  @code{POINTER(c_int)} 指针或者 @ref{242c,,c_int} 数组，但是不能接受其他类型的实例:

@example
>>> bar.values = (c_byte * 4)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
>>>
@end example

这种情况下, 需要手动使用 @ref{1194,,cast()} 函数。

@ref{1194,,cast()} 函数可以将一个指针实例强制转换为另一种 ctypes 类型。 @ref{1194,,cast()} 接收两个参数，一个 ctypes 指针对象或者可以被转换为指针的其他类型对象，和一个 ctypes 指针类型。 返回第二个类型的一个实例，该返回实例和第一个参数指向同一片内存空间:

@example
>>> a = (c_byte * 4)()
>>> cast(a, POINTER(c_int))
<ctypes.LP_c_long object at ...>
>>>
@end example

所以  @ref{1194,,cast()} 可以用来给结构体 @code{Bar} 的 @code{values} 字段赋值:

@example
>>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
>>> print(bar.values[0])
0
>>>
@end example

@node 不完整类型,回调函数,类型转换,ctypes 教程
@anchor{library/ctypes ctypes-incomplete-types}@anchor{2465}@anchor{library/ctypes incomplete-types}@anchor{2466}
@subsubsection 不完整类型


@emph{不完整类型} 即还没有定义成员的结构体、联合或者数组。在 C 中，它们通常用于前置声明，然后在后面定义:

@example
struct cell; /* forward declaration */

struct cell @{
    char *name;
    struct cell *next;
@};
@end example

直接翻译成 ctypes 的代码如下，但是这行不通:

@example
>>> class cell(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("next", POINTER(cell))]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>>
@end example

因为新的 @code{cell 类} 在 class 语句结束之前还没有完成定义。在  @ref{2a,,ctypes} 中，我们可以先定义 @code{cell} 类，在 class 语句结束之后再设置 @code{_fields_} 属性:

@example
>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>
@end example

让我们试试。我们定义两个 @code{cell} 实例，让它们互相指向对方，然后通过指针链式访问几次:

@example
>>> c1 = cell()
>>> c1.name = b"foo"
>>> c2 = cell()
>>> c2.name = b"bar"
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
...     print(p.name, end=" ")
...     p = p.next[0]
...
foo bar foo bar foo bar foo bar
>>>
@end example

@node 回调函数,访问 dll 的导出变量,不完整类型,ctypes 教程
@anchor{library/ctypes callback-functions}@anchor{2467}@anchor{library/ctypes ctypes-callback-functions}@anchor{2468}
@subsubsection 回调函数


@ref{2a,,ctypes} 允许创建一个指向 Python 可调用对象的 C 函数。它们有时候被称为 @emph{回调函数} 。

首先，你必须为回调函数创建一个类，这个类知道调用约定，包括返回值类型以及函数接收的参数类型及个数。

@ref{2469,,CFUNCTYPE()} 工厂函数使用 @code{cdecl} 调用约定创建回调函数类型。在 Windows 上， @ref{246a,,WINFUNCTYPE()} 工厂函数使用 @code{stdcall} 调用约定为回调函数创建类型。

这些工厂函数的第一个参数是返回值类型，回调函数的参数类型作为剩余参数。

这里展示一个使用 C 标准库函数  @code{qsort()} 的例子，它使用一个回调函数对数据进行排序。 @code{qsort()} 将用来给整数数组排序:

@example
>>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
>>> qsort = libc.qsort
>>> qsort.restype = None
>>>
@end example

@code{qsort()} 必须接收的参数，一个指向待排序数据的指针，元素个数，每个元素的大小，以及一个指向排序函数的指针，即回调函数。然后回调函数接收两个元素的指针，如果第一个元素小于第二个，则返回一个负整数，如果相等则返回0，否则返回一个正整数。

所以，我们的回调函数要接收两个整数指针，返回一个整数。首先我们创建回调函数的 @code{类型}

@example
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>>
@end example

首先，这是一个简单的回调，它会显示传入的值:

@example
>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>>
@end example

结果:

@example
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)  
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 5 7
py_cmp_func 1 7
>>>
@end example

现在我们可以比较两个元素并返回有用的结果了:

@example
>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>>
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) 
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
@end example

我们可以轻易地验证，现在数组是有序的了:

@example
>>> for i in ia: print(i, end=" ")
...
1 5 7 33 99
>>>
@end example

这些工厂函数可以当作装饰器工厂，所以可以这样写:

@example
>>> @@CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
... def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>
@end example

@cartouche
@quotation 注解 
请确保你维持的 @ref{2469,,CFUNCTYPE()} 对象的引用周期与它们在 C 代码中的使用期一样长。 @ref{2a,,ctypes} 不会确保这一点，如果不这样做，它们可能会被垃圾回收，导致程序在执行回调函数时发生崩溃。

注意，如果回调函数在Python之外的另外一个线程使用(比如，外部代码调用这个回调函数)， ctypes 会在每一次调用上创建一个虚拟 Python 线程。这个行为在大多数情况下是合理的，但也意味着如果有数据使用 @ref{f57,,threading.local} 方式存储，将无法访问，就算它们是在同一个 C 线程中调用的 。
@end quotation
@end cartouche

@node 访问 dll 的导出变量,意外,回调函数,ctypes 教程
@anchor{library/ctypes accessing-values-exported-from-dlls}@anchor{246b}@anchor{library/ctypes ctypes-accessing-values-exported-from-dlls}@anchor{246c}
@subsubsection 访问 dll 的导出变量


一些动态链接库不仅仅导出函数，也会导出变量。一个例子就是 Python 库本身的 @ref{246d,,Py_OptimizeFlag} ，根据启动选项 @ref{788,,-O} 、 @ref{789,,-OO} 的不同，它是值可能为 0、1、2 的整型。

@ref{2a,,ctypes} 可以通过  @code{in_dll()} 类方法访问这类变量 。 @emph{pythonapi} 是用于访问 Python C 接口的预定义符号:

@example
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
>>> print(opt_flag)
c_long(0)
>>>
@end example

如果解释器使用 @ref{788,,-O} 选项启动，这个例子会打印 @code{c_long(1)} ， 如果使用 @ref{789,,-OO} 启动，则会打印 @code{c_long(2)} 。

一个扩展例子,  同时也展示了使用指针访问 Python 导出的 @ref{246e,,PyImport_FrozenModules} 指针对象。

对文档中这个值的解释说明

@quotation

该指针被初始化为指向 @code{struct _frozen} 数组，以 @code{NULL} 或者 0 作为结束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以此来提供动态创建的冻结模块集合。
@end quotation

这足以证明修改这个指针是很有用的。为了让实例大小不至于太长，这里只展示如何使用 @ref{2a,,ctypes} 读取这个表:

@example
>>> from ctypes import *
>>>
>>> class struct_frozen(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("code", POINTER(c_ubyte)),
...                 ("size", c_int)]
...
>>>
@end example

我们定义了  @code{struct _frozen}  数据类型，接着就可以获取这张表的指针了:

@example
>>> FrozenTable = POINTER(struct_frozen)
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
>>>
@end example

由于 @code{table} 是指向 @code{struct_frozen} 数组的 @code{指针} ，我们可以遍历它，只不过需要自己判断循环是否结束，因为指针本身并不包含长度。它早晚会因为访问到野指针或者什么的把自己搞崩溃，所以我们最好在遇到  @code{NULL} 后就让它退出循环:

@example
>>> for item in table:
...     if item.name is None:
...         break
...     print(item.name.decode("ascii"), item.size)
...
_frozen_importlib 31764
_frozen_importlib_external 41499
__hello__ 161
__phello__ -161
__phello__.spam 161
>>>
@end example

Python 的冻结模块和冻结包(由负 @code{size} 成员表示)并不是广为人知的事情，它们仅仅用于实验。例如，可以使用 @code{import __hello__} 尝试一下这个功能。

@node 意外,变长数据类型,访问 dll 的导出变量,ctypes 教程
@anchor{library/ctypes ctypes-surprises}@anchor{246f}@anchor{library/ctypes surprises}@anchor{2470}
@subsubsection 意外


@ref{2a,,ctypes} 也有自己的边界，有时候会发生一些意想不到的事情。

比如下面的例子:

@example
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class RECT(Structure):
...     _fields_ = ("a", POINT), ("b", POINT)
...
>>> p1 = POINT(1, 2)
>>> p2 = POINT(3, 4)
>>> rc = RECT(p1, p2)
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1 2 3 4
>>> # now swap the two points
>>> rc.a, rc.b = rc.b, rc.a
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
3 4 3 4
>>>
@end example

嗯。我们预想应该打印 @code{3 4 1 2} 。但是为什么呢? 这是 @code{rc.a, rc.b = rc.b, rc.a} 这行代码展开后的步骤:

@example
>>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
>>> rc.b = temp1
>>>
@end example

注意 @code{temp0} 和 @code{temp1} 对象始终引用了对象 @code{rc} 的内容。然后执行 @code{rc.a = temp0} 会把 @code{temp0} 的内容拷贝到 @code{rc} 的空间。这也改变了  @code{temp1} 的内容。最终导致赋值语句 @code{rc.b = temp1} 没有产生预想的效果。

记住，访问被包含在结构体、联合、数组中的对象并不会将其 @emph{复制} 出来，而是得到了一个代理对象，它是对根对象的内部内容的一层包装。

下面是另一个可能和预期有偏差的例子:

@example
>>> s = c_char_p()
>>> s.value = b"abc def ghi"
>>> s.value
b'abc def ghi'
>>> s.value is s.value
False
>>>
@end example

@cartouche
@quotation 注解 
使用  @ref{2443,,c_char_p}  实例化的对象只能将其值设置为 bytes 或者整数。
@end quotation
@end cartouche

为什么这里打印了 @code{False} ？ ctypes 实例是一些内存块加上一些用于访问这些内存块的 @ref{15a8,,descriptor} 组成。将 Python 对象存储在内存块并不会存储对象本身，而是存储了对象的 @code{内容} 。每次访问对象的内容都会构造一个新的 Python 对象。

@node 变长数据类型,,意外,ctypes 教程
@anchor{library/ctypes ctypes-variable-sized-data-types}@anchor{2471}@anchor{library/ctypes variable-sized-data-types}@anchor{2472}
@subsubsection 变长数据类型


@ref{2a,,ctypes} 对变长数组和结构体提供了一些支持 。

The @ref{2473,,resize()} function can be used to resize the memory buffer of an
existing ctypes object.  The function takes the object as first argument, and
the requested size in bytes as the second argument.  The memory block cannot be
made smaller than the natural memory block specified by the objects type, a
@ref{16d,,ValueError} is raised if this is tried:

@example
>>> short_array = (c_short * 4)()
>>> print(sizeof(short_array))
8
>>> resize(short_array, 4)
Traceback (most recent call last):
    ...
ValueError: minimum size is 8
>>> resize(short_array, 32)
>>> sizeof(short_array)
32
>>> sizeof(type(short_array))
8
>>>
@end example

这非常好，但是要怎么访问数组中额外的元素呢？因为数组类型已经定义包含4个元素，导致我们访问新增元素时会产生以下错误:

@example
>>> short_array[:]
[0, 0, 0, 0]
>>> short_array[7]
Traceback (most recent call last):
    ...
IndexError: invalid index
>>>
@end example

使用  @ref{2a,,ctypes} 访问变长数据类型的一个可行方法是利用 Python 的动态特性，根据具体情况，在知道这个数据的大小后，(重新)指定这个数据的类型。

@node ctypes 参考手册,,ctypes 教程,ctypes --- Python 的外部函数库
@anchor{library/ctypes ctypes-ctypes-reference}@anchor{2474}@anchor{library/ctypes ctypes-reference}@anchor{2475}
@subsubsection ctypes 参考手册


@menu
* 寻找动态链接库:: 
* 加载动态链接库:: 
* 外部函数:: 
* 函数原型:: 
* 工具函数:: 
* 数据类型: 数据类型<2>. 
* 基础数据类型: 基础数据类型<2>. 
* 结构化数据类型:: 
* 数组与指针:: 

@end menu

@node 寻找动态链接库,加载动态链接库,,ctypes 参考手册
@anchor{library/ctypes ctypes-finding-shared-libraries}@anchor{2476}@anchor{library/ctypes finding-shared-libraries}@anchor{2477}
@subsubsection 寻找动态链接库


在编译型语言中，动态链接库会在编译、链接或者程序运行时访问。

The purpose of the @code{find_library()} function is to locate a library in a way
similar to what the compiler or runtime loader does (on platforms with several
versions of a shared library the most recent should be loaded), while the ctypes
library loaders act like when a program is run, and call the runtime loader
directly.

@code{ctypes.util} 模块提供了一个函数，可以帮助确定需要加载的库。


@deffn {数据} ctypes.util.find_library (name)

尝试寻找一个库然后返回其路径名， @emph{name} 是库名称, 且去除了 @emph{lib} 等前缀和 @code{.so} 、 @code{.dylib} 、版本号等后缀(这是 posix 连接器 @code{-l} 选项使用的格式)。如果没有找到对应的库，则返回 @code{None} 。
@end deffn

确切的功能取决于系统。

在 Linux 上， @code{find_library()} 会尝试运行外部程序(@code{/sbin/ldconfig}, @code{gcc}, @code{objdump} 以及 @code{ld}) 来寻找库文件。返回库文件的文件名。


在 3.6 版更改: 在Linux 上，如果其他方式找不到的话，会使用环境变量 @code{LD_LIBRARY_PATH} 搜索动态链接库。


这是一些例子:

@example
>>> from ctypes.util import find_library
>>> find_library("m")
'libm.so.6'
>>> find_library("c")
'libc.so.6'
>>> find_library("bz2")
'libbz2.so.1.0'
>>>
@end example

在 macOS 上，@code{find_library()} 会尝试几种预定义的命名方案和路径来定位库，如果成功则将返回完整的路径名称:

@example
>>> from ctypes.util import find_library
>>> find_library("c")
'/usr/lib/libc.dylib'
>>> find_library("m")
'/usr/lib/libm.dylib'
>>> find_library("bz2")
'/usr/lib/libbz2.dylib'
>>> find_library("AGL")
'/System/Library/Frameworks/AGL.framework/AGL'
>>>
@end example

在 Windows 上，  @code{find_library()} 在系统路径中搜索，然后返回全路径，但是如果没有预定义的命名方案， @code{find_library("c")} 调用会返回 @code{None}

使用  @ref{2a,,ctypes} 包装动态链接库，更好的方式 @emph{可能} 是在开发的时候就确定名称，然后硬编码到包装模块中去，而不是在运行时使用 @code{find_library()} 寻找库。

@node 加载动态链接库,外部函数,寻找动态链接库,ctypes 参考手册
@anchor{library/ctypes ctypes-loading-shared-libraries}@anchor{2478}@anchor{library/ctypes loading-shared-libraries}@anchor{2479}
@subsubsection 加载动态链接库


有很多方式可以将动态链接库加载到 Python 进程。其中之一是实例化以下类的其中一个:

@geindex CDLL (ctypes 中的类)
@anchor{library/ctypes ctypes CDLL}@anchor{2f9}
@deffn {类} ctypes.CDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

此类的实例即已加载的动态链接库。库中的函数使用标准 C 调用约定，并假定返回 @code{int} 。

在 Windows 上创建 @ref{2f9,,CDLL} 实例可能会失败，即使 DLL 名称确实存在。 当某个被加载 DLL 所依赖的 DLL 未找到时，将引发 @ref{30b,,OSError} 错误并附带消息 @emph{"[WinError 126] The specified module could not be found".} 此错误消息不包含缺失 DLL 的名称，因为 Windows API 并不会返回此类信息，这使得此错误难以诊断。 要解决此错误并确定是哪一个 DLL 未找到，你需要找出所依赖的 DLL 列表并使用 Windows 调试与跟踪工具确定是哪一个未找到。
@end deffn


@subsubheading 参见


Microsoft DUMPBIN 工具@footnote{https://docs.microsoft.com/cpp/build/reference/dependents} -- 一个用于查找 DLL 依赖的工具。


@geindex OleDLL (ctypes 中的类)
@anchor{library/ctypes ctypes OleDLL}@anchor{247a}
@deffn {类} ctypes.OleDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

仅 Windows : 此类的实例即加载好的动态链接库，其中的函数使用 @code{stdcall} 调用约定，并且假定返回 windows 指定的 @ref{247b,,HRESULT} 返回码。 @ref{247b,,HRESULT} 的值包含的信息说明函数调用成功还是失败，以及额外错误码。 如果返回值表示失败，会自动抛出 @ref{30b,,OSError} 异常。


在 3.3 版更改: 以前是引发 @ref{a7e,,WindowsError}。

@end deffn

@geindex WinDLL (ctypes 中的类)
@anchor{library/ctypes ctypes WinDLL}@anchor{247c}
@deffn {类} ctypes.WinDLL (name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

仅 Windows: 此类的实例即加载好的动态链接库，其中的函数使用 @code{stdcall} 调用约定，并假定默认返回 @code{int} 。
@end deffn

调用动态库导出的函数之前，Python会释放 @ref{60b,,global interpreter lock} ，并在调用后重新获取。

@geindex PyDLL (ctypes 中的类)
@anchor{library/ctypes ctypes PyDLL}@anchor{247d}
@deffn {类} ctypes.PyDLL (name, mode=DEFAULT_MODE, handle=None)

这个类实例的行为与 @ref{2f9,,CDLL} 类似，只不过 @emph{不会} 在调用函数的时候释放 GIL 锁，且调用结束后会检查 Python 错误码。 如果错误码被设置，会抛出一个 Python 异常。

所以，它只在直接调用 Python C 接口函数的时候有用。
@end deffn

通过使用至少一个参数（共享库的路径名）调用它们，可以实例化所有这些类。也可以传入一个已加载的动态链接库作为 @code{handler} 参数，其他情况会调用系统底层的  @code{dlopen} 或 @code{LoadLibrary} 函数将库加载到进程，并获取其句柄。

@emph{mode} 可以指定库加载方式。详情请参见  @code{dlopen(3)} 手册页。 在 Windows 上， 会忽略 @emph{mode} ，在 posix 系统上， 总是会加上 RTLD_NOW ，且无法配置。

@emph{use_errno} 参数如果设置为 true，可以启用ctypes的机制，通过一种安全的方法获取系统的  @ref{7a,,errno} 错误码。 @ref{2a,,ctypes} 维护了一个线程局部变量，它是系统 @ref{7a,,errno} 的一份拷贝；如果调用了使用 @code{use_errno=True} 创建的外部函数， @ref{7a,,errno} 的值会与 ctypes 自己拷贝的那一份进行交换，函数执行完后立即再交换一次。

The function @ref{247e,,ctypes.get_errno()} returns the value of the ctypes private
copy, and the function @ref{247f,,ctypes.set_errno()} changes the ctypes private copy
to a new value and returns the former value.

@emph{use_last_error}  参数如果设置为 true，可以在 Windows 上启用相同的策略，它是通过 Windows API 函数 @ref{244e,,GetLastError()}  和 @code{SetLastError()} 管理的。 @ref{2480,,ctypes.get_last_error()} 和 @ref{2481,,ctypes.set_last_error()} 可用于获取和设置 ctypes 自己维护的 windows 错误码拷贝。

@emph{winmode} 参数用于在 Windows 平台上指定库的加载方式( 因为 @emph{mode} 会被忽略)。他接受任何与 Win32 API 的 @code{LoadLibraryEx} 的标志兼容的值作为参数。省略时，默认设置使用最安全的DLL加载的标志，以避免DLL劫持等问题。传入 DLL 的全路径是保证正确加载库及其依赖最安全的方法。


在 3.8 版更改: 增加了  @emph{winmode} 参数。



@deffn {数据} ctypes.RTLD_GLOBAL

用于 @emph{mode} 参数的标识值。在此标识不可用的系统上，它被定义为整数0。
@end deffn


@deffn {数据} ctypes.RTLD_LOCAL

Flag to use as @emph{mode} parameter.  On platforms where this is not available, it
is the same as @emph{RTLD_GLOBAL}.
@end deffn


@deffn {数据} ctypes.DEFAULT_MODE

加载动态链接库的默认模式。在 OSX 10.3 上，它是 @emph{RTLD_GLOBAL} ，其余系统上是 @emph{RTLD_LOCAL} 。
@end deffn

这些类的实例没有共用方法。动态链接库的导出函数可以通过属性或者索引的方式访问。注意，通过属性的方式访问会缓存这个函数，因而每次访问它时返回的都是同一个对象。另一方面，通过索引访问，每次都会返回一个新的对象:

@example
>>> from ctypes import CDLL
>>> libc = CDLL("libc.so.6")  # On Linux
>>> libc.time == libc.time
True
>>> libc['time'] == libc['time']
False
@end example

还有下面这些属性可用，他们的名称以下划线开头，以避免和导出函数重名:

@geindex _handle (ctypes.PyDLL 属性)
@anchor{library/ctypes ctypes PyDLL _handle}@anchor{2482}
@deffn {属性} PyDLL._handle

用于访问库的系统句柄。
@end deffn

@geindex _name (ctypes.PyDLL 属性)
@anchor{library/ctypes ctypes PyDLL _name}@anchor{2483}
@deffn {属性} PyDLL._name

传入构造函数的库名称。
@end deffn

共享库也可以通用使用一个预制对象来加载，这种对象是 @ref{2484,,LibraryLoader} 类的实例，具体做法或是通过调用 @code{LoadLibrary()} 方法，或是通过将库作为加载器实例的属性来提取。

@geindex LibraryLoader (ctypes 中的类)
@anchor{library/ctypes ctypes LibraryLoader}@anchor{2484}
@deffn {类} ctypes.LibraryLoader (dlltype)

加载共享库的类。 @emph{dlltype} 应当为 @ref{2f9,,CDLL}, @ref{247d,,PyDLL}, @ref{247c,,WinDLL} 或 @ref{247a,,OleDLL} 类型之一。

@ref{433,,__getattr__()} 具有特殊的行为：它允许通过将一个共享库作为库加载器实例的属性进行访问来加载它。 加载结果将被缓存，因此重复的属性访问每次都会返回相同的库。

@geindex LoadLibrary() (ctypes.LibraryLoader 方法)
@anchor{library/ctypes ctypes LibraryLoader LoadLibrary}@anchor{2485}
@deffn {方法} LoadLibrary (name)

加载一个共享库到进程中并将其返回。 此方法总是返回一个新的库实例。
@end deffn
@end deffn

可用的预制库加载器有如下这些:


@deffn {数据} ctypes.cdll

创建 @ref{2f9,,CDLL} 实例。
@end deffn


@deffn {数据} ctypes.windll

仅限 Windows：创建 @ref{247c,,WinDLL} 实例.
@end deffn


@deffn {数据} ctypes.oledll

仅限 Windows：创建 @ref{247a,,OleDLL} 实例。
@end deffn


@deffn {数据} ctypes.pydll

创建 @ref{247d,,PyDLL} 实例。
@end deffn

要直接访问 C Python api，可以使用一个现成的 Python 共享库对象:


@deffn {数据} ctypes.pythonapi

一个 @ref{247d,,PyDLL} 的实例，它将 Python C API 函数作为属性公开。 请注意所有这些函数都应返回 C @code{int}，当然这也不是绝对的，因此你必须分配正确的 @code{restype} 属性以使用这些函数。
@end deffn

引发一个 @ref{fec,,审计事件} @code{ctypes.dlopen}，附带参数 @code{name}。

引发一个审计事件 @code{ctypes.dlsym}，附带参数 @code{library}, @code{name}。

引发一个审计事件 @code{ctypes.dlsym/handle}，附带参数 @code{handle}, @code{name}。

@node 外部函数,函数原型,加载动态链接库,ctypes 参考手册
@anchor{library/ctypes ctypes-foreign-functions}@anchor{2486}@anchor{library/ctypes foreign-functions}@anchor{2487}
@subsubsection 外部函数


正如之前小节的说明，外部函数可作为被加载共享库的属性来访问。 用此方式创建的函数对象默认接受任意数量的参数，接受任意 ctypes 数据实例作为参数，并且返回库加载器所指定的默认结果类型。 它们是一个私有类的实例:

@geindex _FuncPtr (ctypes 中的类)
@anchor{library/ctypes ctypes _FuncPtr}@anchor{2488}
@deffn {类} ctypes._FuncPtr

C 可调用外部函数的基类。

外部函数的实例也是兼容 C 的数据类型；它们代表 C 函数指针。

此行为可通过对外部函数对象的特殊属性赋值来自定义。

@geindex restype (ctypes._FuncPtr 属性)
@anchor{library/ctypes ctypes _FuncPtr restype}@anchor{2489}
@deffn {属性} restype

赋值为一个 ctypes 类型来指定外部函数的结果类型。 使用 @code{None} 表示 @code{void}，即不返回任何结果的函数。

赋值为一个不为 ctypes 类型的可调用 Python 对象也是可以的，在此情况下函数应返回 C @code{int}，该可调用对象将附带此整数被调用，以允许进一步的处理或错误检测。 这种用法已被弃用，为了更灵活的后续处理或错误检测请使用一个 ctypes 数据类型作为 @ref{2489,,restype} 并将 @ref{248a,,errcheck} 属性赋值为一个可调用对象。
@end deffn

@geindex argtypes (ctypes._FuncPtr 属性)
@anchor{library/ctypes ctypes _FuncPtr argtypes}@anchor{248b}
@deffn {属性} argtypes

赋值为一个 ctypes 类型的元组来指定函数所接受的参数类型。 使用 @code{stdcall} 调用规范的函数只能附带与此元组长度相同数量的参数进行调用；使用 C 调用规范的函数还可接受额外的未指明参数。

当外部函数被调用时，每个实际参数都会被传给 @ref{248b,,argtypes} 元组中条目的 @code{from_param()} 类方法，此方法允许将实际参数适配为此外部函数所接受的对象。 例如，@ref{248b,,argtypes} 元组中的 @ref{2443,,c_char_p} 条目将使用 ctypes 约定规则把作为参数传入的字符串转换为字节串对象。

新增：现在可以将不是 ctypes 类型的条目放入 argtypes，但每个条目都必须具有 @code{from_param()} 方法用于返回可作为参数的值（整数、字符串、ctypes 实例）。 这样就允许定义可将自定义对象适配为函数形参的适配器。
@end deffn

@geindex errcheck (ctypes._FuncPtr 属性)
@anchor{library/ctypes ctypes _FuncPtr errcheck}@anchor{248a}
@deffn {属性} errcheck

将一个 Python 函数或其他可调用对象赋值给此属性。 该可调用对象将附带三个及以上的参数被调用。


@deffn {函数} callable (result, func, arguments)

@emph{result} 是外部函数返回的结果，由 @code{restype} 属性指明。

@emph{func} 是外部函数对象本身，这样就允许重新使用相同的可调用对象来对多个函数进行检查或后续处理。

@emph{arguments} 是一个包含最初传递给函数调用的形参的元组，这样就允许对所用参数的行为进行特别处理。
@end deffn

此函数所返回的对象将会由外部函数调用返回，但它还可以在外部函数调用失败时检查结果并引发异常。
@end deffn
@end deffn

@geindex ArgumentError
@anchor{library/ctypes ctypes ArgumentError}@anchor{248c}
@deffn {例外} ctypes.ArgumentError

此异常会在外部函数无法对某个传入参数执行转换时被引发。
@end deffn

引发一个审计事件 @code{ctypes.seh_exception} 并附带参数 @code{code}。

引发一个审计事件 @code{ctypes.call_function}，附带参数 @code{func_pointer}, @code{arguments}。

@node 函数原型,工具函数,外部函数,ctypes 参考手册
@anchor{library/ctypes ctypes-function-prototypes}@anchor{248d}@anchor{library/ctypes function-prototypes}@anchor{248e}
@subsubsection 函数原型


外部函数也可通过实例化函数原型来创建。 函数原型类似于 C 中的函数原型；它们在不定义具体实现的情况下描述了一个函数（返回类型、参数类型、调用约定）。 工厂函数必须使用函数所需要的结果类型和参数类型来调用，并可被用作装饰器工厂函数，在此情况下可以通过 @code{@@wrapper} 语法应用于函数。 请参阅 @ref{2468,,回调函数} 了解有关示例。

@geindex CFUNCTYPE() (在 ctypes 模块中)
@anchor{library/ctypes ctypes CFUNCTYPE}@anchor{2469}
@deffn {函数} ctypes.CFUNCTYPE (restype, *argtypes, use_errno=False, use_last_error=False)

返回的函数原型会创建使用标准 C 调用约定的函数。 该函数在调用过程中将释放 GIL。 如果 @emph{use_errno} 设为真值，则在调用之前和之后系统 @ref{7a,,errno} 变量的 ctypes 私有副本会与真正的 @ref{7a,,errno} 值进行交换；@emph{use_last_error} 会为 Windows 错误码执行同样的操作。
@end deffn

@geindex WINFUNCTYPE() (在 ctypes 模块中)
@anchor{library/ctypes ctypes WINFUNCTYPE}@anchor{246a}
@deffn {函数} ctypes.WINFUNCTYPE (restype, *argtypes, use_errno=False, use_last_error=False)

仅限 Windows：返回的函数原型会创建使用 @code{stdcall} 调用约定的函数。 该函数在调用过程中将会释放 GIL。 @emph{use_errno} 和 @emph{use_last_error} 具有与上文中相同的含义。
@end deffn

@geindex PYFUNCTYPE() (在 ctypes 模块中)
@anchor{library/ctypes ctypes PYFUNCTYPE}@anchor{248f}
@deffn {函数} ctypes.PYFUNCTYPE (restype, *argtypes)

返回的函数原型会创建使用 Python 调用约定的函数。 该函数在调用过程中将 @emph{不会} 释放 GIL。
@end deffn

这些工厂函数所创建的函数原型可通过不同的方式来实例化，具体取决于调用中的类型与数量:

@quotation


@deffn {函数} prototype (address)

在指定地址上返回一个外部函数，地址值必须为整数。
@end deffn


@deffn {函数} prototype (callable)

基于 Python @emph{callable} 创建一个 C 可调用函数（回调函数）。
@end deffn


@deffn {函数} prototype (func_spec[, paramflags])

返回由一个共享库导出的外部函数。 @emph{func_spec} 必须为一个 2 元组 @code{(name_or_ordinal, library)}。 第一项是字符串形式的所导出函数名称，或小整数形式的所导出函数序号。 第二项是该共享库实例。
@end deffn


@deffn {函数} prototype (vtbl_index, name[, paramflags[, iid]])

返回将调用一个 COM 方法的外部函数。 @emph{vtbl_index} 虚拟函数表中的索引。 @emph{name} 是 COM 方法的名称。 @emph{iid} 是可选的指向接口标识符的指针，它被用于扩展的错误报告。

COM 方法使用特殊的调用约定：除了在 @code{argtypes} 元组中指定的形参，它们还要求一个指向 COM 接口的指针作为第一个参数。
@end deffn

可选的 @emph{paramflags} 形参会创建相比上述特性具有更多功能的外部函数包装器。

@emph{paramflags} 必须为一个与 @code{argtypes} 长度相同的元组。

此元组中的每一项都包含有关形参的更多信息，它必须为包含一个、两个或更多条目的元组。

第一项是包含形参指令旗标组合的整数。

@quotation


@table @asis

@item 1

指定函数的一个输入形参。

@item 2

输出形参。 外部函数会填入一个值。

@item 4

默认为整数零值的输入形参。
@end table
@end quotation

可选的第二项是字符串形式的形参名称。 如果指定此项，则可以使用该形参名称来调用外部函数。

可选的第三项是该形参的默认值。
@end quotation

这个例子演示了如何包装 Windows 的 @code{MessageBoxW} 函数以使其支持默认形参和已命名参数。 相应 windows 头文件的 C 声明是这样的:

@example
WINUSERAPI int WINAPI
MessageBoxW(
    HWND hWnd,
    LPCWSTR lpText,
    LPCWSTR lpCaption,
    UINT uType);
@end example

这是使用 @ref{2a,,ctypes} 的包装:

@example
>>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
>>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
@end example

现在 @code{MessageBox} 外部函数可以通过以下方式来调用:

@example
>>> MessageBox()
>>> MessageBox(text="Spam, spam, spam")
>>> MessageBox(flags=2, text="foo bar")
@end example

第二个例子演示了输出形参。 这个 win32 @code{GetWindowRect} 函数通过将指定窗口的维度拷贝至调用者必须提供的 @code{RECT} 结构体来提取这些值。 这是相应的 C 声明:

@example
WINUSERAPI BOOL WINAPI
GetWindowRect(
     HWND hWnd,
     LPRECT lpRect);
@end example

这是使用 @ref{2a,,ctypes} 的包装:

@example
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
>>> paramflags = (1, "hwnd"), (2, "lprect")
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
>>>
@end example

带有输出形参的函数如果输出形参存在单一值则会自动返回该值，或是当输出形参存在多个值时返回包含这些值的元组，因此当 GetWindowRect 被调用时现在将返回一个 RECT 实例。

输出形参可以与 @code{errcheck} 协议相结合以执行进一步的输出处理与错误检查。 Win32 @code{GetWindowRect} API 函数返回一个 @code{BOOL} 来表示成功或失败，因此此函数可执行错误检查，并在 API 调用失败时引发异常:

@example
>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     return args
...
>>> GetWindowRect.errcheck = errcheck
>>>
@end example

如果 @code{errcheck} 不加更改地返回它所接收的参数元组，则 @ref{2a,,ctypes} 会继续对输出形参执行常规处理。 如果你希望返回一个窗口坐标的元组而非 @code{RECT} 实例，你可以从函数中提取这些字段并返回它们，常规处理将不会再执行:

@example
>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     rc = args[1]
...     return rc.left, rc.top, rc.bottom, rc.right
...
>>> GetWindowRect.errcheck = errcheck
>>>
@end example

@node 工具函数,数据类型<2>,函数原型,ctypes 参考手册
@anchor{library/ctypes ctypes-utility-functions}@anchor{2490}@anchor{library/ctypes utility-functions}@anchor{2491}
@subsubsection 工具函数


@geindex addressof() (在 ctypes 模块中)
@anchor{library/ctypes ctypes addressof}@anchor{2492}
@deffn {函数} ctypes.addressof (obj)

以整数形式返回内存缓冲区地址。 @emph{obj} 必须为一个 ctypes 类型的实例。

引发一个 @ref{fec,,审计事件} @code{ctypes.addressof}，附带参数 @code{obj}。
@end deffn

@geindex alignment() (在 ctypes 模块中)
@anchor{library/ctypes ctypes alignment}@anchor{2493}
@deffn {函数} ctypes.alignment (obj_or_type)

返回一个 ctypes 类型的对齐要求。 @emph{obj_or_type} 必须为一个 ctypes 类型或实例。
@end deffn

@geindex byref() (在 ctypes 模块中)
@anchor{library/ctypes ctypes byref}@anchor{2451}
@deffn {函数} ctypes.byref (obj[, offset])

返回指向 @emph{obj} 的轻量指针，该对象必须为一个 ctypes 类型的实例。 @emph{offset} 默认值为零，且必须为一个将被添加到内部指针值的整数。

@code{byref(obj, offset)} 对应于这段 C 代码:

@example
(((char *)&obj) + offset)
@end example

返回的对象只能被用作外部函数调用形参。 它的行为类似于 @code{pointer(obj)}，但构造起来要快很多。
@end deffn

@geindex cast() (在 ctypes 模块中)
@anchor{library/ctypes ctypes cast}@anchor{1194}
@deffn {函数} ctypes.cast (obj, type)

此函数类似于 C 的强制转换运算符。 它返回一个 @emph{type} 的新实例，该实例指向与 @emph{obj} 相同的内存块。 @emph{type} 必须为指针类型，而 @emph{obj} 必须为可以被作为指针来解读的对象。
@end deffn

@geindex create_string_buffer() (在 ctypes 模块中)
@anchor{library/ctypes ctypes create_string_buffer}@anchor{2445}
@deffn {函数} ctypes.create_string_buffer (init_or_size, size=None)

此函数会创建一个可变的字符缓冲区。 返回的对象是一个 @ref{2437,,c_char} 的 ctypes 数组。

@emph{init_or_size} 必须是一个指明数组大小的整数，或者是一个将被用来初始化数组条目的字节串对象。

如果将一个字节串对象指定为第一个参数，则将使缓冲区大小比其长度多一项以便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个参数以允许在不使用字节串长度的情况下指定数组大小。

引发一个 @ref{fec,,审计事件} @code{ctypes.create_string_buffer}，附带参数 @code{init}, @code{size}。
@end deffn

@geindex create_unicode_buffer() (在 ctypes 模块中)
@anchor{library/ctypes ctypes create_unicode_buffer}@anchor{1120}
@deffn {函数} ctypes.create_unicode_buffer (init_or_size, size=None)

此函数会创建一个可变的 unicode 字符缓冲区。 返回的对象是一个 @ref{2438,,c_wchar} 的 ctypes 数组。

@emph{init_or_size} 必须是一个指明数组大小的整数，或者是一个将被用来初始化数组条目的字符串。

如果将一个字符串指定为第一个参数，则将使缓冲区大小比其长度多一项以便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个参数以允许在不使用字符串长度的情况下指定数组大小。

引发一个 @ref{fec,,审计事件} @code{ctypes.create_unicode_buffer}，附带参数 @code{init}, @code{size}。
@end deffn

@geindex DllCanUnloadNow() (在 ctypes 模块中)
@anchor{library/ctypes ctypes DllCanUnloadNow}@anchor{2494}
@deffn {函数} ctypes.DllCanUnloadNow ()

仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子。 它将由 _ctypes 扩展 dll 所导出的 DllCanUnloadNow 函数来调用。
@end deffn

@geindex DllGetClassObject() (在 ctypes 模块中)
@anchor{library/ctypes ctypes DllGetClassObject}@anchor{2495}
@deffn {函数} ctypes.DllGetClassObject ()

仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子。 它将由 @code{_ctypes} 扩展 dll 所导出的 DllGetClassObject 函数来调用。
@end deffn

@geindex find_library() (在 ctypes.util 模块中)
@anchor{library/ctypes ctypes util find_library}@anchor{70b}
@deffn {函数} ctypes.util.find_library (name)

尝试寻找一个库并返回路径名称。 @emph{name} 是库名称并且不带任何前缀如 @code{lib} 以及后缀如 @code{.so}，@code{.dylib} 或版本号（形式与 posix 链接器选项 @code{-l} 所用的一致）。 如果找不到库，则返回 @code{None}。

确切的功能取决于系统。
@end deffn

@geindex find_msvcrt() (在 ctypes.util 模块中)
@anchor{library/ctypes ctypes util find_msvcrt}@anchor{2496}
@deffn {函数} ctypes.util.find_msvcrt ()

仅限 Windows：返回 Python 以及扩展模块所使用的 VC 运行时库的文件名。 如果无法确定库名称，则返回 @code{None}。

如果你需要通过调用 @code{free(void *)} 来释放内存，例如某个扩展模块所分配的内存，重要的一点是你应当使用分配内存的库中的函数。
@end deffn

@geindex FormatError() (在 ctypes 模块中)
@anchor{library/ctypes ctypes FormatError}@anchor{2497}
@deffn {函数} ctypes.FormatError ([code])

仅限 Windows：返回错误码 @emph{code} 的文本描述。 如果未指定错误码，则会通过调用 Windows api 函数 GetLastError 来获得最新的错误码。
@end deffn

@geindex GetLastError() (在 ctypes 模块中)
@anchor{library/ctypes ctypes GetLastError}@anchor{244e}
@deffn {函数} ctypes.GetLastError ()

仅限 Windows：返回 Windows 在调用线程中设置的最新错误码。 此函数会直接调用 Windows @cite{GetLastError()} 函数，它并不返回错误码的 ctypes 私有副本。
@end deffn

@geindex get_errno() (在 ctypes 模块中)
@anchor{library/ctypes ctypes get_errno}@anchor{247e}
@deffn {函数} ctypes.get_errno ()

返回调用线程中系统 @ref{7a,,errno} 变量的 ctypes 私有副本的当前值。

引发一个 @ref{fec,,审计事件} @code{ctypes.get_errno}，不附带任何参数。
@end deffn

@geindex get_last_error() (在 ctypes 模块中)
@anchor{library/ctypes ctypes get_last_error}@anchor{2480}
@deffn {函数} ctypes.get_last_error ()

仅限 Windows：返回调用线程中系统 @code{LastError} 变量的 ctypes 私有副本的当前值。

引发一个 @ref{fec,,审计事件} @code{ctypes.get_last_error}，不附带任何参数。
@end deffn

@geindex memmove() (在 ctypes 模块中)
@anchor{library/ctypes ctypes memmove}@anchor{2498}
@deffn {函数} ctypes.memmove (dst, src, count)

与标准 C memmove 库函数相同：将 @emph{count} 个字节从 @emph{src} 拷贝到 @emph{dst}。 @emph{dst} 和 @emph{src} 必须为整数或可被转换为指针的 ctypes 实例。
@end deffn

@geindex memset() (在 ctypes 模块中)
@anchor{library/ctypes ctypes memset}@anchor{2499}
@deffn {函数} ctypes.memset (dst, c, count)

与标准 C memset 库函数相同：将位于地址 @emph{dst} 的内存块用 @emph{count} 个字节的 @emph{c} 值填充。 @emph{dst} 必须为指定地址的整数或 ctypes 实例。
@end deffn

@geindex POINTER() (在 ctypes 模块中)
@anchor{library/ctypes ctypes POINTER}@anchor{2462}
@deffn {函数} ctypes.POINTER (type)

这个工厂函数创建并返回一个新的 ctypes 指针类型。 指针类型会被缓存并在内部重用，因此重复调用此函数耗费不大。 @emph{type} 必须为 ctypes 类型。
@end deffn

@geindex pointer() (在 ctypes 模块中)
@anchor{library/ctypes ctypes pointer}@anchor{2452}
@deffn {函数} ctypes.pointer (obj)

此函数会创建一个新的指向 @emph{obj} 的指针实例。 返回的对象类型为 @code{POINTER(type(obj))}。

注意：如果你只是想向外部函数调用传递一个对象指针，你应当使用更为快速的 @code{byref(obj)}。
@end deffn

@geindex resize() (在 ctypes 模块中)
@anchor{library/ctypes ctypes resize}@anchor{2473}
@deffn {函数} ctypes.resize (obj, size)

此函数可改变 @emph{obj} 的内部内存缓冲区大小，其参数必须为 ctypes 类型的实例。 没有可能将缓冲区设为小于对象类型的本机大小值，该值由 @code{sizeof(type(obj))} 给出，但将缓冲区加大则是可能的。
@end deffn

@geindex set_errno() (在 ctypes 模块中)
@anchor{library/ctypes ctypes set_errno}@anchor{247f}
@deffn {函数} ctypes.set_errno (value)

设置调用线程中系统 @ref{7a,,errno} 变量的 ctypes 私有副本的当前值为 @emph{value} 并返回原来的值。

引发一个 @ref{fec,,审计事件} @code{ctypes.set_errno} 附带参数 @code{errno}。
@end deffn

@geindex set_last_error() (在 ctypes 模块中)
@anchor{library/ctypes ctypes set_last_error}@anchor{2481}
@deffn {函数} ctypes.set_last_error (value)

仅限 Windows：设置调用线程中系统 @code{LastError} 变量的 ctypes 私有副本的当前值为 @emph{value} 并返回原来的值。

引发一个 @ref{fec,,审计事件} @code{ctypes.set_last_error}，附带参数 @code{error}。
@end deffn

@geindex sizeof() (在 ctypes 模块中)
@anchor{library/ctypes ctypes sizeof}@anchor{249a}
@deffn {函数} ctypes.sizeof (obj_or_type)

返回 ctypes 类型或实例的内存缓冲区以字节表示的大小。 其功能与 C @code{sizeof} 运算符相同。
@end deffn

@geindex string_at() (在 ctypes 模块中)
@anchor{library/ctypes ctypes string_at}@anchor{249b}
@deffn {函数} ctypes.string_at (address, size=-1)

此函数返回从内存地址 @emph{address} 开始的以字节串表示的 C 字符串。 如果指定了 size，则将其用作长度，否则将假定字符串以零值结尾。

引发一个 @ref{fec,,审计事件} @code{ctypes.string_at}，附带参数 @code{address}, @code{size}。
@end deffn

@geindex WinError() (在 ctypes 模块中)
@anchor{library/ctypes ctypes WinError}@anchor{249c}
@deffn {函数} ctypes.WinError (code=None, descr=None)

仅限 Windows：此函数可能是 ctypes 中名字起得最差的函数。 它会创建一个 OSError 的实例。 如果未指定 @emph{code}，则会调用 @code{GetLastError} 来确定错误码。 如果未指定 @emph{descr}，则会调用 @ref{2497,,FormatError()} 来获取错误的文本描述。


在 3.3 版更改: 以前是会创建一个 @ref{a7e,,WindowsError} 的实例。

@end deffn

@geindex wstring_at() (在 ctypes 模块中)
@anchor{library/ctypes ctypes wstring_at}@anchor{249d}
@deffn {函数} ctypes.wstring_at (address, size=-1)

此函数返回从内存地址 @emph{address} 开始的以字符串表示的宽字节字符串。 如果指定了 @emph{size}，则将其用作字符串中的字符数量，否则将假定字符串以零值结尾。

引发一个 @ref{fec,,审计事件} @code{ctypes.wstring_at}，附带参数 @code{address}, @code{size}。
@end deffn

@node 数据类型<2>,基础数据类型<2>,工具函数,ctypes 参考手册
@anchor{library/ctypes ctypes-data-types}@anchor{249e}@anchor{library/ctypes data-types}@anchor{249f}
@subsubsection 数据类型


@geindex _CData (ctypes 中的类)
@anchor{library/ctypes ctypes _CData}@anchor{122d}
@deffn {类} ctypes._CData

这个非公有类是所有 ctypes 数据类型的共同基类。 另外，所有 ctypes 类型的实例都包含一个存放 C 兼容数据的内存块；该内存块的地址可由 @ref{2492,,addressof()} 辅助函数返回。 还有一个实例变量被公开为 @ref{24a0,,_objects}；此变量包含其他在内存块包含指针的情况下需要保持存活的 Python 对象。

ctypes 数据类型的通用方法，它们都是类方法（严谨地说，它们是 @ref{15bf,,metaclass} 的方法）:

@geindex from_buffer() (ctypes._CData 方法)
@anchor{library/ctypes ctypes _CData from_buffer}@anchor{24a1}
@deffn {方法} from_buffer (source[, offset])

此方法返回一个共享 @emph{source} 对象缓冲区的 ctypes 实例。 @emph{source} 对象必须支持可写缓冲区接口。 可选的 @emph{offset} 形参指定以字节表示的源缓冲区内偏移量；默认值为零。 如果源缓冲区不够大则会引发 @ref{16d,,ValueError}。

引发一个 @ref{fec,,审计事件} @code{ctypes.cdata/buffer} 附带参数 @code{pointer}, @code{size}, @code{offset}。
@end deffn

@geindex from_buffer_copy() (ctypes._CData 方法)
@anchor{library/ctypes ctypes _CData from_buffer_copy}@anchor{24a2}
@deffn {方法} from_buffer_copy (source[, offset])

此方法创建一个 ctypes 实例，从 @emph{source} 对象缓冲区拷贝缓冲区，该对象必须是可读的。 可选的 @emph{offset} 形参指定以字节表示的源缓冲区内偏移量；默认值为零。 如果源缓冲区不够大则会引发 @ref{16d,,ValueError}。

引发一个 @ref{fec,,审计事件} @code{ctypes.cdata/buffer} 附带参数 @code{pointer}, @code{size}, @code{offset}。
@end deffn

@geindex from_address() (ctypes._CData 方法)
@anchor{library/ctypes ctypes _CData from_address}@anchor{24a3}
@deffn {方法} from_address (address)

此方法会使用 @emph{address} 所指定的内存返回一个 ctypes 类型的实例，该参数必须为一个整数。

引发一个 @ref{fec,,审计事件} @code{ctypes.cdata}，附带参数 @code{address}。
@end deffn

@geindex from_param() (ctypes._CData 方法)
@anchor{library/ctypes ctypes _CData from_param}@anchor{24a4}
@deffn {方法} from_param (obj)

此方法会将 @emph{obj} 适配为一个 ctypes 类型。 它调用时会在当该类型存在于外部函数的 @code{argtypes} 元组时传入外部函数调用所使用的实际对象；它必须返回一个可被用作函数调用参数的对象。

所有 ctypes 数据类型都带有这个类方法的默认实现，它通常会返回 @emph{obj}，如果该对象是此类型的实例的话。 某些类型也能接受其他对象。
@end deffn

@geindex in_dll() (ctypes._CData 方法)
@anchor{library/ctypes ctypes _CData in_dll}@anchor{24a5}
@deffn {方法} in_dll (library, name)

此方法返回一个由共享库导出的 ctypes 类型。 @emph{name} 为导出数据的符号名称，@emph{library} 为所加载的共享库。
@end deffn

ctypes 数据类型的通用实例变量:

@geindex _b_base_ (ctypes._CData 属性)
@anchor{library/ctypes ctypes _CData _b_base_}@anchor{24a6}
@deffn {属性} _b_base_

有时 ctypes 数据实例并不拥有它们所包含的内存块，它们只是共享了某个基对象的部分内存块。 @ref{24a6,,_b_base_} 只读成员是拥有内存块的根 ctypes 对象。
@end deffn

@geindex _b_needsfree_ (ctypes._CData 属性)
@anchor{library/ctypes ctypes _CData _b_needsfree_}@anchor{24a7}
@deffn {属性} _b_needsfree_

这个只读变量在 ctypes 数据实例自身已分配了内存块时为真值，否则为假值。
@end deffn

@geindex _objects (ctypes._CData 属性)
@anchor{library/ctypes ctypes _CData _objects}@anchor{24a0}
@deffn {属性} _objects

这个成员或者为 @code{None}，或者为一个包含需要保持存活以使内存块的内存保持有效的 Python 对象的字典。 这个对象只是出于调试目的而对外公开；绝对不要修改此字典的内容。
@end deffn
@end deffn

@node 基础数据类型<2>,结构化数据类型,数据类型<2>,ctypes 参考手册
@anchor{library/ctypes ctypes-fundamental-data-types-2}@anchor{24a8}@anchor{library/ctypes id1}@anchor{24a9}
@subsubsection 基础数据类型


@geindex _SimpleCData (ctypes 中的类)
@anchor{library/ctypes ctypes _SimpleCData}@anchor{24aa}
@deffn {类} ctypes._SimpleCData

这个非公有类是所有基本 ctypes 数据类型的基类。 它在这里被提及是因为它包含基本 ctypes 数据类型共有的属性。 @ref{24aa,,_SimpleCData} 是 @ref{122d,,_CData} 的子类，因此继承了其方法和属性。 非指针及不包含指针的 ctypes 数据类型现在将可以被封存。

实例拥有一个属性:

@geindex value (ctypes._SimpleCData 属性)
@anchor{library/ctypes ctypes _SimpleCData value}@anchor{24ab}
@deffn {属性} value

这个属性包含实例的实际值。 对于整数和指针类型，它是一个整数，对于字符类型，它是一个单字符字符串对象或字符串，对于字符指针类型，它是一个 Python 字节串对象或字符串。

当从 ctypes 实例提取 @code{value} 属性时，通常每次会返回一个新的对象。 @ref{2a,,ctypes} 并 @emph{没有} 实现原始对象返回，它总是会构造一个新的对象。 所有其他 ctypes 对象实例也同样如此。
@end deffn
@end deffn

基本数据类型当作为外部函数调用结果被返回或者作为结构字段成员或数组项被提取时，会透明地转换为原生 Python 类型。 换句话说，如果某个外部函数具有 @ref{2443,,c_char_p} 的 @code{restype}，你将总是得到一个 Python 字节串对象，而 @emph{不是} 一个 @ref{2443,,c_char_p} 实例。

@c XXX above is false, it actually returns a Unicode string

基本数据类型的子类并 @emph{没有} 继续此行为。 因此，如果一个外部函数的 @code{restype} 是 @ref{2444,,c_void_p} 的一个子类，你将从函数调用得到一个该子类的实例。 当然，你可以通过访问 @code{value} 属性来获取指针的值。

这些是基本 ctypes 数据类型:

@geindex c_byte (ctypes 中的类)
@anchor{library/ctypes ctypes c_byte}@anchor{2439}
@deffn {类} ctypes.c_byte

代表 C @code{signed char} 数据类型，并将值解读为一个小整数。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_char (ctypes 中的类)
@anchor{library/ctypes ctypes c_char}@anchor{2437}
@deffn {类} ctypes.c_char

代表 C @code{char} 数据类型，并将值解读为单个字符。 该构造器接受一个可选的字符串初始化器，字符串的长度必须恰好为一个字符。
@end deffn

@geindex c_char_p (ctypes 中的类)
@anchor{library/ctypes ctypes c_char_p}@anchor{2443}
@deffn {类} ctypes.c_char_p

当指向一个以零为结束符的字符串时代表 C @code{char *} 数据类型。 对于通用字符指针来说也可能指向二进制数据，必须要使用 @code{POINTER(c_char)}。 该构造器接受一个整数地址，或者一个字节串对象。
@end deffn

@geindex c_double (ctypes 中的类)
@anchor{library/ctypes ctypes c_double}@anchor{100f}
@deffn {类} ctypes.c_double

代表 C @code{double} 数据类型。 该构造器接受一个可选的浮点数初始化器。
@end deffn

@geindex c_longdouble (ctypes 中的类)
@anchor{library/ctypes ctypes c_longdouble}@anchor{1010}
@deffn {类} ctypes.c_longdouble

代表 C @code{long double} 数据类型。 该构造器接受一个可选的浮点数初始化器。 在 @code{sizeof(long double) == sizeof(double)} 的平台上它是 @ref{100f,,c_double} 的一个别名。
@end deffn

@geindex c_float (ctypes 中的类)
@anchor{library/ctypes ctypes c_float}@anchor{2442}
@deffn {类} ctypes.c_float

代表 C @code{float} 数据类型。 该构造器接受一个可选的浮点数初始化器。
@end deffn

@geindex c_int (ctypes 中的类)
@anchor{library/ctypes ctypes c_int}@anchor{242c}
@deffn {类} ctypes.c_int

代表 C @code{signed int} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。 在 @code{sizeof(int) == sizeof(long)} 的平台上它是 @ref{242d,,c_long} 的一个别名。
@end deffn

@geindex c_int8 (ctypes 中的类)
@anchor{library/ctypes ctypes c_int8}@anchor{24ac}
@deffn {类} ctypes.c_int8

代表 C 8 位 @code{signed int} 数据类型。 通常是 @ref{2439,,c_byte} 的一个别名。
@end deffn

@geindex c_int16 (ctypes 中的类)
@anchor{library/ctypes ctypes c_int16}@anchor{24ad}
@deffn {类} ctypes.c_int16

代表 C 16 位 @code{signed int} 数据类型。 通常是 @ref{243b,,c_short} 的一个别名。
@end deffn

@geindex c_int32 (ctypes 中的类)
@anchor{library/ctypes ctypes c_int32}@anchor{24ae}
@deffn {类} ctypes.c_int32

代表 C 32 位 @code{signed int} 数据类型。 通常是 @ref{242c,,c_int} 的一个别名。
@end deffn

@geindex c_int64 (ctypes 中的类)
@anchor{library/ctypes ctypes c_int64}@anchor{24af}
@deffn {类} ctypes.c_int64

代表 C 64 位 @code{signed int} 数据类型。 通常是 @ref{243f,,c_longlong} 的一个别名。
@end deffn

@geindex c_long (ctypes 中的类)
@anchor{library/ctypes ctypes c_long}@anchor{242d}
@deffn {类} ctypes.c_long

代表 C @code{signed long} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_longlong (ctypes 中的类)
@anchor{library/ctypes ctypes c_longlong}@anchor{243f}
@deffn {类} ctypes.c_longlong

代表 C @code{signed long long} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_short (ctypes 中的类)
@anchor{library/ctypes ctypes c_short}@anchor{243b}
@deffn {类} ctypes.c_short

代表 C @code{signed short} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_size_t (ctypes 中的类)
@anchor{library/ctypes ctypes c_size_t}@anchor{2441}
@deffn {类} ctypes.c_size_t

代表 C @code{size_t} 数据类型。
@end deffn

@geindex c_ssize_t (ctypes 中的类)
@anchor{library/ctypes ctypes c_ssize_t}@anchor{ca7}
@deffn {类} ctypes.c_ssize_t

代表 C @code{ssize_t} 数据类型。


3.2 新版功能.

@end deffn

@geindex c_ubyte (ctypes 中的类)
@anchor{library/ctypes ctypes c_ubyte}@anchor{243a}
@deffn {类} ctypes.c_ubyte

代表 C @code{unsigned char} 数据类型，它将值解读为一个小整数。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_uint (ctypes 中的类)
@anchor{library/ctypes ctypes c_uint}@anchor{243d}
@deffn {类} ctypes.c_uint

代表 C @code{unsigned int} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。 在 @code{sizeof(int) == sizeof(long)} 的平台上它是 @ref{243e,,c_ulong} 的一个别名。
@end deffn

@geindex c_uint8 (ctypes 中的类)
@anchor{library/ctypes ctypes c_uint8}@anchor{24b0}
@deffn {类} ctypes.c_uint8

代表 C 8 位 @code{unsigned int} 数据类型。 通常是 @ref{243a,,c_ubyte} 的一个别名。
@end deffn

@geindex c_uint16 (ctypes 中的类)
@anchor{library/ctypes ctypes c_uint16}@anchor{24b1}
@deffn {类} ctypes.c_uint16

代表 C 16 位 @code{unsigned int} 数据类型。 通常是 @ref{243c,,c_ushort} 的一个别名。
@end deffn

@geindex c_uint32 (ctypes 中的类)
@anchor{library/ctypes ctypes c_uint32}@anchor{24b2}
@deffn {类} ctypes.c_uint32

代表 C 32 位 @code{unsigned int} 数据类型。 通常是 @ref{243d,,c_uint} 的一个别名。
@end deffn

@geindex c_uint64 (ctypes 中的类)
@anchor{library/ctypes ctypes c_uint64}@anchor{24b3}
@deffn {类} ctypes.c_uint64

代表 C 64 位 @code{unsigned int} 数据类型。 通常是 @ref{2440,,c_ulonglong} 的一个别名。
@end deffn

@geindex c_ulong (ctypes 中的类)
@anchor{library/ctypes ctypes c_ulong}@anchor{243e}
@deffn {类} ctypes.c_ulong

代表 C @code{unsigned long} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_ulonglong (ctypes 中的类)
@anchor{library/ctypes ctypes c_ulonglong}@anchor{2440}
@deffn {类} ctypes.c_ulonglong

代表 C @code{unsigned long long} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_ushort (ctypes 中的类)
@anchor{library/ctypes ctypes c_ushort}@anchor{243c}
@deffn {类} ctypes.c_ushort

代表 C @code{unsigned short} 数据类型。 该构造器接受一个可选的整数初始化器；不会执行溢出检查。
@end deffn

@geindex c_void_p (ctypes 中的类)
@anchor{library/ctypes ctypes c_void_p}@anchor{2444}
@deffn {类} ctypes.c_void_p

代表 C @code{void *} 类型。 该值被表示为整数形式。 该构造器接受一个可选的整数初始化器。
@end deffn

@geindex c_wchar (ctypes 中的类)
@anchor{library/ctypes ctypes c_wchar}@anchor{2438}
@deffn {类} ctypes.c_wchar

代表 C @code{wchar_t} 数据类型，并将值解读为一单个字符的 unicode 字符串。 该构造器接受一个可选的字符串初始化器，字符串的长度必须恰好为一个字符。
@end deffn

@geindex c_wchar_p (ctypes 中的类)
@anchor{library/ctypes ctypes c_wchar_p}@anchor{ff4}
@deffn {类} ctypes.c_wchar_p

代表 C @code{wchar_t *} 数据类型，它必须为指向以零为结束符的宽字符串的指针。 该构造器接受一个整数地址或者一个字符串。
@end deffn

@geindex c_bool (ctypes 中的类)
@anchor{library/ctypes ctypes c_bool}@anchor{2436}
@deffn {类} ctypes.c_bool

代表 C @code{bool} 数据类型 (更准确地说是 C99 @code{_Bool})。 它的值可以为 @code{True} 或 @code{False}，并且该构造器接受任何具有逻辑值的对象。
@end deffn

@geindex HRESULT (ctypes 中的类)
@anchor{library/ctypes ctypes HRESULT}@anchor{247b}
@deffn {类} ctypes.HRESULT

Windows 专属：代表一个 @code{HRESULT} 值，它包含某个函数或方法调用的成功或错误信息。
@end deffn

@geindex py_object (ctypes 中的类)
@anchor{library/ctypes ctypes py_object}@anchor{24b4}
@deffn {类} ctypes.py_object

代表 C @ref{5bd,,PyObject *} 数据类型。 不带参数地调用此构造器将创建一个 @code{NULL} @ref{5bd,,PyObject *} 指针。
@end deffn

@code{ctypes.wintypes} 模块提供了其他许多 Windows 专属的数据类型，例如 @code{HWND}, @code{WPARAM} 或 @code{DWORD}。 还定义了一些有用的结构体例如 @code{MSG} 或 @code{RECT}。

@node 结构化数据类型,数组与指针,基础数据类型<2>,ctypes 参考手册
@anchor{library/ctypes ctypes-structured-data-types}@anchor{24b5}@anchor{library/ctypes structured-data-types}@anchor{24b6}
@subsubsection 结构化数据类型


@geindex Union (ctypes 中的类)
@anchor{library/ctypes ctypes Union}@anchor{2456}
@deffn {类} ctypes.Union (*args, **kw)

本机字节序的联合所对应的抽象基类。
@end deffn

@geindex BigEndianStructure (ctypes 中的类)
@anchor{library/ctypes ctypes BigEndianStructure}@anchor{2459}
@deffn {类} ctypes.BigEndianStructure (*args, **kw)

@emph{大端} 字节序的结构体所对应的抽象基类。
@end deffn

@geindex LittleEndianStructure (ctypes 中的类)
@anchor{library/ctypes ctypes LittleEndianStructure}@anchor{245a}
@deffn {类} ctypes.LittleEndianStructure (*args, **kw)

@emph{小端} 字节序的结构体所对应的抽象基类。
@end deffn

非本机字节序的结构体不能包含指针类型字段，或任何其他包含指针类型字段的数据类型。

@geindex Structure (ctypes 中的类)
@anchor{library/ctypes ctypes Structure}@anchor{2455}
@deffn {类} ctypes.Structure (*args, **kw)

@emph{本机} 字节序的结构体所对应的抽象基类。

实际的结构体和联合类型必须通过子类化这些类型之一来创建，并且至少要定义一个 @ref{24b7,,_fields_} 类变量。 @ref{2a,,ctypes} 将创建 @ref{15a8,,descriptor}，它允许通过直接属性访问来读取和写入字段。 这些是

@geindex _fields_ (ctypes.Structure 属性)
@anchor{library/ctypes ctypes Structure _fields_}@anchor{24b7}
@deffn {属性} _fields_

一个定义结构体字段的序列。 其中的条目必须为 2 元组或 3 元组。 元组的第一项是字段名称，第二项指明字段类型；它可以是任何 ctypes 数据类型。

对于整数类型字段例如 @ref{242c,,c_int}，可以给定第三个可选项。 它必须是一个定义字段比特位宽度的小正整数。

字段名称在一个结构体或联合中必须唯一。 不会检查这个唯一性，但当名称出现重复时将只有一个字段可被访问。

可以在定义 Structure 子类的类语句 @emph{之后} 再定义 @ref{24b7,,_fields_} 类变量，这将允许创建直接或间接引用其自身的数据类型:

@example
class List(Structure):
    pass
List._fields_ = [("pnext", POINTER(List)),
                 ...
                ]
@end example

但是，@ref{24b7,,_fields_} 类变量必须在类型第一次被使用（创建实例，调用 @ref{249a,,sizeof()} 等等）之前进行定义。 在此之后对 @ref{24b7,,_fields_} 类变量赋值将会引发 AttributeError。

可以定义结构体类型的子类，它们会继承基类的字段再加上在子类中定义的任何 @ref{24b7,,_fields_}。
@end deffn

@geindex _pack_ (ctypes.Structure 属性)
@anchor{library/ctypes ctypes Structure _pack_}@anchor{24b8}
@deffn {属性} _pack_

一个可选的小整数，它允许覆盖实体中结构体字段的对齐方式。 当 @ref{24b7,,_fields_} 被赋值时必须已经定义了 @ref{24b8,,_pack_}，否则它将没有效果。
@end deffn

@geindex _anonymous_ (ctypes.Structure 属性)
@anchor{library/ctypes ctypes Structure _anonymous_}@anchor{24b9}
@deffn {属性} _anonymous_

一个可选的序列，它会列出未命名（匿名）字段的名称。 当 @ref{24b7,,_fields_} 被赋值时必须已经定义了 @ref{24b9,,_anonymous_}，否则它将没有效果。

在此变量中列出的字段必须为结构体或联合类型字段。 @ref{2a,,ctypes} 将在结构体类型中创建描述器以允许直接访问嵌套字段，而无需创建对应的结构体或联合字段。

以下是一个示例类型（Windows）:

@example
class _U(Union):
    _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                ("lpadesc", POINTER(ARRAYDESC)),
                ("hreftype", HREFTYPE)]

class TYPEDESC(Structure):
    _anonymous_ = ("u",)
    _fields_ = [("u", _U),
                ("vt", VARTYPE)]
@end example

@code{TYPEDESC} 结构体描述了一个 COM 数据类型，@code{vt} 字段指明哪个联合字段是有效的。 由于 @code{u} 字段被定义为匿名字段，现在可以直接从 TYPEDESC 实例访问成员。 @code{td.lptdesc} 和 @code{td.u.lptdesc} 是等价的，但前者速度更快，因为它不需要创建临时的联合实例:

@example
td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
@end example
@end deffn

可以定义结构体的子类，它们会继承基类的字段。 如果子类定义具有单独的 @ref{24b7,,_fields_} 变量，在其中指定的字段会被添加到基类的字段中。

结构体和联合的构造器均可接受位置和关键字参数。 位置参数用于按照 @ref{24b7,,_fields_} 中的出现顺序来初始化成员字段。 构造器中的关键字参数会被解读为属性赋值，因此它们将以相应的名称来初始化 @ref{24b7,,_fields_}，或为不存在于 @ref{24b7,,_fields_} 中的名称创建新的属性。
@end deffn

@node 数组与指针,,结构化数据类型,ctypes 参考手册
@anchor{library/ctypes arrays-and-pointers}@anchor{24ba}@anchor{library/ctypes ctypes-arrays-pointers}@anchor{24bb}
@subsubsection 数组与指针


@geindex Array (ctypes 中的类)
@anchor{library/ctypes ctypes Array}@anchor{118e}
@deffn {类} ctypes.Array (*args)

数组的抽象基类。

创建实体数组类型的推荐方式是通过将任意 @ref{2a,,ctypes} 数据类型与一个非负整数相乘。 作为替代方式，你也可以子类化这个类型并定义 @ref{24bc,,_length_} 和 @ref{24bd,,_type_} 类变量。 数组元素可使用标准的抽取和切片操作来进行读写；对于切片读取，结果对象本身 @emph{不是} 一个 @ref{118e,,Array}。

@geindex _length_ (ctypes.Array 属性)
@anchor{library/ctypes ctypes Array _length_}@anchor{24bc}
@deffn {属性} _length_

一个指明数组中元素数量的正整数。 超出范围的抽取会导致 @ref{f3d,,IndexError}。 该值将由 @ref{292,,len()} 返回。
@end deffn

@geindex _type_ (ctypes.Array 属性)
@anchor{library/ctypes ctypes Array _type_}@anchor{24bd}
@deffn {属性} _type_

指明数组中每个元素的类型。
@end deffn

Array 子类构造器可接受位置参数，用来按顺序初始化元素。
@end deffn

@geindex _Pointer (ctypes 中的类)
@anchor{library/ctypes ctypes _Pointer}@anchor{24be}
@deffn {类} ctypes._Pointer

私有对象，指针的抽象基类。

实际的指针类型是通过调用 @ref{2462,,POINTER()} 并附带其将指向的类型来创建的；这会由 @ref{2452,,pointer()} 自动完成。

如果一个指针指向的是数组，则其元素可使用标准的抽取和切片方式来读写。 指针对象没有长度，因此 @ref{292,,len()} 将引发 @ref{1ff,,TypeError}。 抽取负值将会从指针 @emph{之前} 的内存中读取（与 C 一样），并且超出范围的抽取将可能因非法访问而导致崩溃（视你的运气而定）。

@geindex _type_ (ctypes._Pointer 属性)
@anchor{library/ctypes ctypes _Pointer _type_}@anchor{24bf}
@deffn {属性} _type_

指明所指向的类型。
@end deffn

@geindex contents (ctypes._Pointer 属性)
@anchor{library/ctypes ctypes _Pointer contents}@anchor{2461}
@deffn {属性} contents

返回指针所指向的对象。 对此属性赋值会使指针改为指向所赋值的对象。
@end deffn
@end deffn

@node 并发执行,网络和进程间通信,通用操作系统服务,Python 标准库
@anchor{library/concurrency doc}@anchor{24c0}@anchor{library/concurrency concurrency}@anchor{24c1}@anchor{library/concurrency concurrent-execution}@anchor{24c2}
@section 并发执行


本章中描述的模块支持并发执行代码。 适当的工具选择取决于要执行的任务（CPU密集型或IO密集型）和偏好的开发风格（事件驱动的协作式多任务或抢占式多任务处理）。 这是一个概述：

@menu
* threading: threading --- 基于线程的并行. 基于线程的并行
* multiprocessing: multiprocessing --- 基于进程的并行. 基于进程的并行
* multiprocessing.shared_memory: multiprocessing shared_memory --- 可从进程直接访问的共享内存. 可从进程直接访问的共享内存
* concurrent 包:: 
* concurrent.futures: concurrent futures --- 启动并行任务. 启动并行任务
* subprocess: subprocess --- 子进程管理. 子进程管理
* sched: sched --- 事件调度器. 事件调度器
* queue: queue --- 一个同步的队列类. 一个同步的队列类
* contextvars: contextvars --- 上下文变量. 上下文变量
* _thread: _thread --- 底层多线程 API. 底层多线程 API

@end menu

@node threading --- 基于线程的并行,multiprocessing --- 基于进程的并行,,并发执行
@anchor{library/threading doc}@anchor{24c3}@anchor{library/threading module-threading}@anchor{10b}@anchor{library/threading threading-thread-based-parallelism}@anchor{24c4}
@subsection @code{threading} --- 基于线程的并行


@geindex threading (模块)

@strong{源代码:} Lib/threading.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/threading.py}


__________________________________________________________________


这个模块在较低级的模块 @ref{2,,_thread} 基础上建立较高级的线程接口。参见： @ref{da,,queue}  模块。


在 3.7 版更改: 这个模块曾经为可选项，但现在总是可用。


@cartouche
@quotation 注解 
虽然他们没有在下面列出，这个模块仍然支持Python 2.x系列的这个模块下以 @code{camelCase} （驼峰法）命名的方法和函数。
@end quotation
@end cartouche

@strong{CPython implementation detail:} 在 CPython 中，由于存在 @ref{60b,,全局解释器锁}，同一时刻只有一个线程可以执行 Python 代码（虽然某些性能导向的库可能会去除此限制）。 如果你想让你的应用更好地利用多核心计算机的计算资源，推荐你使用 @ref{b7,,multiprocessing} 或 @ref{196,,concurrent.futures.ProcessPoolExecutor}。 但是，如果你想要同时运行多个 I/O 密集型任务，则多线程仍然是一个合适的模型。

这个模块定义了以下函数：

@geindex active_count() (在 threading 模块中)
@anchor{library/threading threading active_count}@anchor{24c5}
@deffn {函数} threading.active_count ()

返回当前存活的 @ref{21b,,Thread} 对象的数量。 返回值与 @ref{fdb,,enumerate()} 所返回的列表长度一致。
@end deffn

@geindex current_thread() (在 threading 模块中)
@anchor{library/threading threading current_thread}@anchor{24c6}
@deffn {函数} threading.current_thread ()

返回当前对应调用者的控制线程的 @ref{21b,,Thread} 对象。如果调用者的控制线程不是利用 @ref{10b,,threading} 创建，会返回一个功能受限的虚拟线程对象。
@end deffn

@geindex excepthook() (在 threading 模块中)
@anchor{library/threading threading excepthook}@anchor{365}
@deffn {函数} threading.excepthook (args, /)

处理由 @ref{366,,Thread.run()} 引发的未捕获异常。

@emph{args} 参数具有以下属性:


@itemize *

@item 
@emph{exc_type}: 异常类型

@item 
@emph{exc_value}: 异常值，可以是 @code{None}.

@item 
@emph{exc_traceback}: 异常回溯，可以是 @code{None}.

@item 
@emph{thread}: 引发异常的线程，可以为 @code{None}。
@end itemize

如果 @emph{exc_type} 为 @ref{6fd,,SystemExit}，则异常会被静默地忽略。 在其他情况下，异常将被打印到 @ref{1eb,,sys.stderr}。

如果此函数引发了异常，则会调用 @ref{1ae,,sys.excepthook()} 来处理它。

@ref{365,,threading.excepthook()} 可以被重载以控制由 @ref{366,,Thread.run()} 引发的未捕获异常的处理方式。

使用定制钩子存放 @emph{exc_value} 可能会创建引用循环。 它应当在不再需要异常时被显式地清空以打破引用循环。

使用定制钩子存放 @emph{thread} 可能会在它设为被终结对象时将其重生。 请避免在定制钩子完成后存放 @emph{thread} 以避免对象的重生。


@subsubheading 参见


@ref{1ae,,sys.excepthook()} 处理未捕获的异常。



3.8 新版功能.

@end deffn

@geindex get_ident() (在 threading 模块中)
@anchor{library/threading threading get_ident}@anchor{b90}
@deffn {函数} threading.get_ident ()

返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义，主要是用作 magic cookie，比如作为含有线程相关数据的字典的索引。线程标识符可能会在线程退出，新线程创建时被复用。


3.3 新版功能.

@end deffn

@geindex get_native_id() (在 threading 模块中)
@anchor{library/threading threading get_native_id}@anchor{367}
@deffn {函数} threading.get_native_id ()

返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后该值可能会被 OS 回收再利用）。

@ref{14c1,,可用性}: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX。


3.8 新版功能.

@end deffn

@geindex enumerate() (在 threading 模块中)
@anchor{library/threading threading enumerate}@anchor{fdb}
@deffn {函数} threading.enumerate ()

返回当前所有存活的 @ref{21b,,Thread} 对象的列表。 该列表包括守护线程以及 @ref{24c6,,current_thread()} 创建的空线程。 它不包括已终结的和尚未开始的线程。 但是，主线程将总是结果的一部分，即使是在已终结的时候。
@end deffn

@geindex main_thread() (在 threading 模块中)
@anchor{library/threading threading main_thread}@anchor{9de}
@deffn {函数} threading.main_thread ()

返回主 @ref{21b,,Thread} 对象。一般情况下，主线程是Python解释器开始时创建的线程。


3.4 新版功能.

@end deffn

@geindex settrace() (在 threading 模块中)
@anchor{library/threading threading settrace}@anchor{24c7}
@deffn {函数} threading.settrace (func)

@geindex trace function

为所有 @ref{10b,,threading} 模块开始的线程设置追踪函数。在每个线程的 @ref{366,,run()} 方法被调用前，@emph{func} 会被传递给 @ref{f08,,sys.settrace()} 。
@end deffn

@geindex setprofile() (在 threading 模块中)
@anchor{library/threading threading setprofile}@anchor{24c8}
@deffn {函数} threading.setprofile (func)

@geindex profile function

为所有 @ref{10b,,threading} 模块开始的线程设置性能测试函数。在每个线程的 @ref{366,,run()} 方法被调用前，@emph{func} 会被传递给 @ref{f07,,sys.setprofile()} 。
@end deffn

@geindex stack_size() (在 threading 模块中)
@anchor{library/threading threading stack_size}@anchor{24c9}
@deffn {函数} threading.stack_size ([size])

返回创建线程时用的堆栈大小。可选参数 @emph{size} 指定之后新建的线程的堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是32,768(32KiB)的一个正整数。如果 @emph{size} 没有指定，默认是0。如果不支持改变线程堆栈大小，会抛出 @ref{3e4,,RuntimeError} 错误。如果指定的堆栈大小不合法，会抛出 @ref{16d,,ValueError} 错误并且不会修改堆栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是使用4096的倍数作为堆栈大小）。

@ref{14c1,,适用于}: Windows，具有 POSIX 线程的系统。
@end deffn

这个模块同时定义了以下常量：

@geindex TIMEOUT_MAX() (在 threading 模块中)
@anchor{library/threading threading TIMEOUT_MAX}@anchor{24ca}
@deffn {数据} threading.TIMEOUT_MAX

阻塞函数（ @ref{865,,Lock.acquire()}, @ref{866,,RLock.acquire()}, @ref{fe2,,Condition.wait()}, ...）中形参 @emph{timeout} 允许的最大值。传入超过这个值的 timeout 会抛出 @ref{a4a,,OverflowError} 异常。


3.2 新版功能.

@end deffn

这个模块定义了许多类，详见以下部分。

该模块的设计基于 Java的线程模型。 但是，在Java里面，锁和条件变量是每个对象的基础特性，而在Python里面，这些被独立成了单独的对象。 Python 的 @ref{21b,,Thread} 类只是 Java 的 Thread 类的一个子集；目前还没有优先级，没有线程组，线程还不能被销毁、停止、暂停、恢复或中断。 Java 的 Thread 类的静态方法在实现时会映射为模块级函数。

下述方法的执行都是原子性的。

@menu
* 线程本地数据:: 
* 线程对象:: 
* 锁对象:: 
* 递归锁对象:: 
* 条件对象:: 
* 信号量对象:: 
* 事件对象:: 
* 定时器对象:: 
* 栅栏对象:: 
* 在 with 语句中使用锁、条件和信号量:: 

@end menu

@node 线程本地数据,线程对象,,threading --- 基于线程的并行
@anchor{library/threading thread-local-data}@anchor{24cb}
@subsubsection 线程本地数据


线程本地数据是特定线程的数据。管理线程本地数据，只需要创建一个 @ref{f57,,local} （或者一个子类型）的实例并在实例中储存属性：

@example
mydata = threading.local()
mydata.x = 1
@end example

在不同的线程中，实例的值会不同。

@geindex local (threading 中的类)
@anchor{library/threading threading local}@anchor{f57}
@deffn {类} threading.local

一个代表线程本地数据的类。

更多相关细节和大量示例，参见 @code{_threading_local} 模块的文档。
@end deffn

@node 线程对象,锁对象,线程本地数据,threading --- 基于线程的并行
@anchor{library/threading id1}@anchor{24cc}@anchor{library/threading thread-objects}@anchor{24cd}
@subsubsection 线程对象


The @ref{21b,,Thread} class represents an activity that is run in a separate
thread of control.  There are two ways to specify the activity: by passing a
callable object to the constructor, or by overriding the @ref{366,,run()}
method in a subclass.  No other methods (except for the constructor) should be
overridden in a subclass.  In other words, @emph{only}  override the
@code{__init__()} and @ref{366,,run()} methods of this class.

当线程对象一旦被创建，其活动必须通过调用线程的 @ref{225c,,start()} 方法开始。 这会在独立的控制线程中发起调用 @ref{366,,run()} 方法。

一旦线程活动开始，该线程会被认为是 '存活的' 。当它的 @ref{366,,run()} 方法终结了（不管是正常的还是抛出未被处理的异常），就不是'存活的'。 @ref{21c,,is_alive()} 方法用于检查线程是否存活。

其他线程可以调用一个线程的 @ref{c3b,,join()} 方法。这会阻塞调用该方法的线程，直到被调用 @ref{c3b,,join()} 方法的线程终结。

线程有名字。名字可以传递给构造函数，也可以通过 @ref{24ce,,name} 属性读取或者修改。

如果 @ref{366,,run()} 方法引发了异常，则会调用 @ref{365,,threading.excepthook()} 来处理它。 在默认情况下，@ref{365,,threading.excepthook()} 会静默地忽略 @ref{6fd,,SystemExit}。

一个线程可以被标记成一个“守护线程”。 这个标识的意义是，当剩下的线程都是守护线程时，整个 Python 程序将会退出。 初始值继承于创建线程。 这个标识可以通过 @ref{24cf,,daemon} 特征属性或者 @emph{daemon} 构造器参数来设置。

@cartouche
@quotation 注解 
守护线程在程序关闭时会突然关闭。他们的资源（例如已经打开的文档，数据库事务等等）可能没有被正确释放。如果你想你的线程正常停止，设置他们成为非守护模式并且使用合适的信号机制，例如： @ref{b8e,,Event}。
@end quotation
@end cartouche

有个 "主线程" 对象；这对应Python程序里面初始的控制线程。它不是一个守护线程。

"虚拟线程对象" 是可以被创建的。这些是对应于“外部线程”的线程对象，它们是在线程模块外部启动的控制线程，例如直接来自C代码。虚拟线程对象功能受限；他们总是被认为是存活的和守护模式，不能被 @ref{c3b,,join()} 。因为无法检测外来线程的终结，它们永远不会被删除。

@geindex Thread (threading 中的类)
@anchor{library/threading threading Thread}@anchor{21b}
@deffn {类} threading.Thread (group=None, target=None, name=None, args=(), kwargs=@{@}, *, daemon=None)

应当始终使用关键字参数调用此构造函数。 参数如下：

@emph{group} 应该为 @code{None}；为了日后扩展 @code{ThreadGroup} 类实现而保留。

@emph{target} 是用于 @ref{366,,run()} 方法调用的可调用对象。默认是 @code{None}，表示不需要调用任何方法。

@emph{name} 是线程名称。默认情况下，由 "Thread-@emph{N}" 格式构成一个唯一的名称，其中 @emph{N} 是小的十进制数。

@emph{args} 是用于调用目标函数的参数元组。默认是 @code{()}。

@emph{kwargs} 是用于调用目标函数的关键字参数字典。默认是 @code{@{@}}。

如果不是 @code{None}，@emph{daemon} 参数将显式地设置该线程是否为守护模式。 如果是 @code{None} (默认值)，线程将继承当前线程的守护模式属性。

如果子类型重载了构造函数，它一定要确保在做任何事前，先发起调用基类构造器(@code{Thread.__init__()})。


在 3.3 版更改: 加入 @emph{daemon} 参数。


@geindex start() (threading.Thread 方法)
@anchor{library/threading threading Thread start}@anchor{225c}
@deffn {方法} start ()

开始线程活动。

它在一个线程里最多只能被调用一次。 它安排对象的 @ref{366,,run()} 方法在一个独立的控制线程中被调用。

如果同一个线程对象中调用这个方法的次数大于一次，会抛出 @ref{3e4,,RuntimeError} 。
@end deffn

@geindex run() (threading.Thread 方法)
@anchor{library/threading threading Thread run}@anchor{366}
@deffn {方法} run ()

代表线程活动的方法。

你可以在子类型里重载这个方法。 标准的 @ref{366,,run()} 方法会对作为 @emph{target} 参数传递给该对象构造器的可调用对象（如果存在）发起调用，并附带从 @emph{args} 和 @emph{kwargs} 参数分别获取的位置和关键字参数。
@end deffn

@geindex join() (threading.Thread 方法)
@anchor{library/threading threading Thread join}@anchor{c3b}
@deffn {方法} join (timeout=None)

等待，直到线程终结。这会阻塞调用这个方法的线程，直到被调用 @ref{c3b,,join()} 的线程终结 -- 不管是正常终结还是抛出未处理异常 -- 或者直到发生超时，超时选项是可选的。

当 @emph{timeout} 参数存在而且不是 @code{None} 时，它应该是一个用于指定操作超时的以秒为单位的浮点数（或者分数）。因为 @ref{c3b,,join()} 总是返回 @code{None} ，所以你一定要在 @ref{c3b,,join()} 后调用 @ref{21c,,is_alive()} 才能判断是否发生超时 -- 如果线程仍然存活，则 @ref{c3b,,join()} 超时。

当 @emph{timeout} 参数不存在或者是 @code{None} ，这个操作会阻塞直到线程终结。

一个线程可以被 @ref{c3b,,join()} 很多次。

如果尝试加入当前线程会导致死锁， @ref{c3b,,join()} 会引起 @ref{3e4,,RuntimeError}  异常。如果尝试 @ref{c3b,,join()} 一个尚未开始的线程，也会抛出相同的异常。
@end deffn

@geindex name (threading.Thread 属性)
@anchor{library/threading threading Thread name}@anchor{24ce}
@deffn {属性} name

只用于识别的字符串。它没有语义。多个线程可以赋予相同的名称。 初始名称由构造函数设置。
@end deffn

@geindex getName() (threading.Thread 方法)
@geindex setName() (threading.Thread 方法)
@anchor{library/threading threading Thread getName}@anchor{24d0}
@deffn {方法} getName ()
@anchor{library/threading threading Thread setName}@anchor{24d1}
@deffnx {方法} setName ()

旧的 @ref{24ce,,name} 取值/设值 API；请改为直接以特征属性方式使用它。
@end deffn

@geindex ident (threading.Thread 属性)
@anchor{library/threading threading Thread ident}@anchor{21a4}
@deffn {属性} ident

这个线程的 '线程标识符'，如果线程尚未开始则为 @code{None} 。这是个非零整数。参见  @ref{b90,,get_ident()} 函数。当一个线程退出而另外一个线程被创建，线程标识符会被复用。即使线程退出后，仍可得到标识符。
@end deffn

@geindex native_id (threading.Thread 属性)
@anchor{library/threading threading Thread native_id}@anchor{368}
@deffn {属性} native_id

此线程的原生集成线程 ID。 这是一个非负整数，或者如果线程还未启动则为 @code{None}。 请参阅 @ref{367,,get_native_id()} 函数。 这表示线程 ID (@code{TID}) 已被 OS (内核) 赋值给线程。 它的值可能被用来在全系统范围内唯一地标识这个特定线程（直到线程终结，在那之后该值可能会被 OS 回收再利用）。

@cartouche
@quotation 注解 
类似于进程 ID，线程 ID 的有效期（全系统范围内保证唯一）将从线程被创建开始直到线程被终结。
@end quotation
@end cartouche

@ref{14c1,,可用性}: 需要 @ref{367,,get_native_id()} 函数。


3.8 新版功能.

@end deffn

@geindex is_alive() (threading.Thread 方法)
@anchor{library/threading threading Thread is_alive}@anchor{21c}
@deffn {方法} is_alive ()

返回线程是否存活。

当 @ref{366,,run()} 方法刚开始直到 @ref{366,,run()} 方法刚结束，这个方法返回 @code{True} 。模块函数 @ref{fdb,,enumerate()} 返回包含所有存活线程的列表。
@end deffn

@geindex daemon (threading.Thread 属性)
@anchor{library/threading threading Thread daemon}@anchor{24cf}
@deffn {属性} daemon

一个表示这个线程是（True）否（False）守护线程的布尔值。一定要在调用 @ref{225c,,start()} 前设置好，不然会抛出 @ref{3e4,,RuntimeError} 。初始值继承于创建线程；主线程不是守护线程，因此主线程创建的所有线程默认都是 @ref{24cf,,daemon} = @code{False}。

当没有存活的非守护线程时，整个Python程序才会退出。
@end deffn

@geindex isDaemon() (threading.Thread 方法)
@geindex setDaemon() (threading.Thread 方法)
@anchor{library/threading threading Thread isDaemon}@anchor{24d2}
@deffn {方法} isDaemon ()
@anchor{library/threading threading Thread setDaemon}@anchor{24d3}
@deffnx {方法} setDaemon ()

旧的 @ref{24cf,,daemon} 取值/设值 API；请改为直接以特性属性方式使用它。
@end deffn
@end deffn

@node 锁对象,递归锁对象,线程对象,threading --- 基于线程的并行
@anchor{library/threading id2}@anchor{24d4}@anchor{library/threading lock-objects}@anchor{24d5}
@subsubsection 锁对象


原始锁是一个在锁定时不属于特定线程的同步基元组件。在Python中，它是能用的最低级的同步基元组件，由 @ref{2,,_thread}  扩展模块直接实现。

原始锁处于 "锁定" 或者 "非锁定" 两种状态之一。它被创建时为非锁定状态。它有两个基本方法， @ref{865,,acquire()} 和 @ref{24d6,,release()} 。当状态为非锁定时， @ref{865,,acquire()}  将状态改为 锁定 并立即返回。当状态是锁定时， @ref{865,,acquire()} 将阻塞至其他线程调用 @ref{24d6,,release()}  将其改为非锁定状态，然后 @ref{865,,acquire()} 调用重置其为锁定状态并返回。  @ref{24d6,,release()} 只在锁定状态下调用； 它将状态改为非锁定并立即返回。如果尝试释放一个非锁定的锁，则会引发 @ref{3e4,,RuntimeError}  异常。

锁同样支持 @ref{24d7,,上下文管理协议}。

当多个线程在 @ref{865,,acquire()} 等待状态转变为未锁定被阻塞，然后 @ref{24d6,,release()} 重置状态为未锁定时，只有一个线程能继续执行；至于哪个等待线程继续执行没有定义，并且会根据实现而不同。

所有方法的执行都是原子性的。

@geindex Lock (threading 中的类)
@anchor{library/threading threading Lock}@anchor{24d8}
@deffn {类} threading.Lock

实现原始锁对象的类。一旦一个线程获得一个锁，会阻塞随后尝试获得锁的线程，直到它被释放；任何线程都可以释放它。

需要注意的是 @code{Lock} 其实是一个工厂函数，返回平台支持的具体锁类中最有效的版本的实例。

@geindex acquire() (threading.Lock 方法)
@anchor{library/threading threading Lock acquire}@anchor{865}
@deffn {方法} acquire (blocking=True, timeout=-1)

可以阻塞或非阻塞地获得锁。

当调用时参数 @emph{blocking} 设置为 @code{True} （缺省值），阻塞直到锁被释放，然后将锁锁定并返回 @code{True} 。

在参数 @emph{blocking} 被设置为 @code{False} 的情况下调用，将不会发生阻塞。如果调用时 @emph{blocking} 设为 @code{True} 会阻塞，并立即返回 @code{False} ；否则，将锁锁定并返回 @code{True}。

当浮点型 @emph{timeout} 参数被设置为正值调用时，只要无法获得锁，将最多阻塞 @emph{timeout} 设定的秒数。@emph{timeout} 参数被设置为  @code{-1} 时将无限等待。当 @emph{blocking} 为 false 时，@emph{timeout} 指定的值将被忽略。

如果成功获得锁，则返回 @code{True}，否则返回 @code{False} (例如发生 @emph{超时} 的时候)。


在 3.2 版更改: 新的 @emph{timeout} 形参。



在 3.2 版更改: 现在如果底层线程实现支持，则可以通过POSIX上的信号中断锁的获取。

@end deffn

@geindex release() (threading.Lock 方法)
@anchor{library/threading threading Lock release}@anchor{24d6}
@deffn {方法} release ()

释放一个锁。这个方法可以在任何线程中调用，不单指获得锁的线程。

当锁被锁定，将它重置为未锁定，并返回。如果其他线程正在等待这个锁解锁而被阻塞，只允许其中一个允许。

在未锁定的锁调用时，会引发 @ref{3e4,,RuntimeError} 异常。

没有返回值。
@end deffn

@geindex locked() (threading.Lock 方法)
@anchor{library/threading threading Lock locked}@anchor{24d9}
@deffn {方法} locked ()

如果获得了锁则返回真值。
@end deffn
@end deffn

@node 递归锁对象,条件对象,锁对象,threading --- 基于线程的并行
@anchor{library/threading id3}@anchor{24da}@anchor{library/threading rlock-objects}@anchor{24db}
@subsubsection 递归锁对象


重入锁是一个可以被同一个线程多次获取的同步基元组件。在内部，它在基元锁的锁定/非锁定状态上附加了 "所属线程" 和 "递归等级" 的概念。在锁定状态下，某些线程拥有锁 ； 在非锁定状态下， 没有线程拥有它。

若要锁定锁，线程调用其 @ref{866,,acquire()} 方法；一旦线程拥有了锁，方法将返回。若要解锁，线程调用 @ref{24d6,,release()} 方法。 @ref{865,,acquire()}/@ref{24d6,,release()} 对可以嵌套；只有最终 @ref{24d6,,release()} (最外面一对的 @ref{24d6,,release()} ) 将锁解开，才能让其他线程继续处理 @ref{865,,acquire()} 阻塞。

递归锁也支持 @ref{24d7,,上下文管理协议}。

@geindex RLock (threading 中的类)
@anchor{library/threading threading RLock}@anchor{cc2}
@deffn {类} threading.RLock

此类实现了重入锁对象。重入锁必须由获取它的线程释放。一旦线程获得了重入锁，同一个线程再次获取它将不阻塞；线程必须在每次获取它时释放一次。

需要注意的是 @code{RLock} 其实是一个工厂函数，返回平台支持的具体递归锁类中最有效的版本的实例。

@geindex acquire() (threading.RLock 方法)
@anchor{library/threading threading RLock acquire}@anchor{866}
@deffn {方法} acquire (blocking=True, timeout=-1)

可以阻塞或非阻塞地获得锁。

当无参数调用时： 如果这个线程已经拥有锁，递归级别增加一，并立即返回。否则，如果其他线程拥有该锁，则阻塞至该锁解锁。一旦锁被解锁(不属于任何线程)，则抢夺所有权，设置递归等级为一，并返回。如果多个线程被阻塞，等待锁被解锁，一次只有一个线程能抢到锁的所有权。在这种情况下，没有返回值。

当发起调用时将 @emph{blocking} 参数设为真值，则执行与无参数调用时一样的操作，然后返回 @code{True}。

当发起调用时将 @emph{blocking} 参数设为假值，则不进行阻塞。 如果一个无参数调用将要阻塞，则立即返回 @code{False}；在其他情况下，执行与无参数调用时一样的操作，然后返回 @code{True}。

当发起调用时将浮点数的 @emph{timeout} 参数设为正值时，只要无法获得锁，将最多阻塞 @emph{timeout} 所指定的秒数。 如果已经获得锁则返回 @code{True}，如果超时则返回假值。


在 3.2 版更改: 新的 @emph{timeout} 形参。

@end deffn

@geindex release() (threading.RLock 方法)
@anchor{library/threading threading RLock release}@anchor{24dc}
@deffn {方法} release ()

释放锁，自减递归等级。如果减到零，则将锁重置为非锁定状态(不被任何线程拥有)，并且，如果其他线程正被阻塞着等待锁被解锁，则仅允许其中一个线程继续。如果自减后，递归等级仍然不是零，则锁保持锁定，仍由调用线程拥有。

只有当前线程拥有锁才能调用这个方法。如果锁被释放后调用这个方法，会引起 @ref{3e4,,RuntimeError} 异常。

没有返回值。
@end deffn
@end deffn

@node 条件对象,信号量对象,递归锁对象,threading --- 基于线程的并行
@anchor{library/threading condition-objects}@anchor{24dd}@anchor{library/threading id4}@anchor{24de}
@subsubsection 条件对象


条件变量总是与某种类型的锁对象相关联，锁对象可以通过传入获得，或者在缺省的情况下自动创建。当多个条件变量需要共享同一个锁时，传入一个锁很有用。锁是条件对象的一部分，你不必单独地跟踪它。

条件变量遵循 @ref{24d7,,上下文管理协议} ：使用 @code{with} 语句会在它包围的代码块内获取关联的锁。  @ref{24df,,acquire()} 和 @ref{24e0,,release()} 方法也能调用关联锁的相关方法。

其它方法必须在持有关联的锁的情况下调用。 @ref{fe2,,wait()} 方法释放锁，然后阻塞直到其它线程调用 @ref{f71,,notify()} 方法或 @ref{24e1,,notify_all()} 方法唤醒它。一旦被唤醒， @ref{fe2,,wait()} 方法重新获取锁并返回。它也可以指定超时时间。

The @ref{f71,,notify()} method wakes up one of the threads waiting for
the condition variable, if any are waiting.  The @ref{24e1,,notify_all()}
method wakes up all threads waiting for the condition variable.

注意： @ref{f71,,notify()} 方法和 @ref{24e1,,notify_all()} 方法并不会释放锁，这意味着被唤醒的线程不会立即从它们的 @ref{fe2,,wait()} 方法调用中返回，而是会在调用了 @ref{f71,,notify()} 方法或 @ref{24e1,,notify_all()} 方法的线程最终放弃了锁的所有权后返回。

使用条件变量的典型编程风格是将锁用于同步某些共享状态的权限，那些对状态的某些特定改变感兴趣的线程，它们重复调用 @ref{fe2,,wait()} 方法，直到看到所期望的改变发生；而对于修改状态的线程，它们将当前状态改变为可能是等待者所期待的新状态后，调用 @ref{f71,,notify()} 方法或者 @ref{24e1,,notify_all()} 方法。例如，下面的代码是一个通用的无限缓冲区容量的生产者-消费者情形：

@example
# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
@end example

使用 @code{while} 循环检查所要求的条件成立与否是有必要的，因为 @ref{fe2,,wait()} 方法可能要经过不确定长度的时间后才会返回，而此时导致 @ref{f71,,notify()} 方法调用的那个条件可能已经不再成立。这是多线程编程所固有的问题。 @ref{24e2,,wait_for()} 方法可自动化条件检查，并简化超时计算。

@example
# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()
@end example

选择 @ref{f71,,notify()} 还是 @ref{24e1,,notify_all()} ，取决于一次状态改变是只能被一个还是能被多个等待线程所用。例如在一个典型的生产者-消费者情形中，添加一个项目到缓冲区只需唤醒一个消费者线程。

@geindex Condition (threading 中的类)
@anchor{library/threading threading Condition}@anchor{b8b}
@deffn {类} threading.Condition (lock=None)

实现条件变量对象的类。一个条件变量对象允许一个或多个线程在被其它线程所通知之前进行等待。

如果给出了非 @code{None} 的 @emph{lock} 参数，则它必须为 @ref{24d8,,Lock} 或者 @ref{cc2,,RLock} 对象，并且它将被用作底层锁。否则，将会创建新的 @ref{cc2,,RLock} 对象，并将其用作底层锁。


在 3.3 版更改: 从工厂函数变为类。


@geindex acquire() (threading.Condition 方法)
@anchor{library/threading threading Condition acquire}@anchor{24df}
@deffn {方法} acquire (*args)

请求底层锁。此方法调用底层锁的相应方法，返回值是底层锁相应方法的返回值。
@end deffn

@geindex release() (threading.Condition 方法)
@anchor{library/threading threading Condition release}@anchor{24e0}
@deffn {方法} release ()

释放底层锁。此方法调用底层锁的相应方法。没有返回值。
@end deffn

@geindex wait() (threading.Condition 方法)
@anchor{library/threading threading Condition wait}@anchor{fe2}
@deffn {方法} wait (timeout=None)

等待直到被通知或发生超时。如果线程在调用此方法时没有获得锁，将会引发 @ref{3e4,,RuntimeError} 异常。

这个方法释放底层锁，然后阻塞，直到在另外一个线程中调用同一个条件变量的 @ref{f71,,notify()} 或 @ref{24e1,,notify_all()} 唤醒它，或者直到可选的超时发生。一旦被唤醒或者超时，它重新获得锁并返回。

当提供了 @emph{timeout} 参数且不是 @code{None} 时，它应该是一个浮点数，代表操作的超时时间，以秒为单位（可以为小数）。

当底层锁是个 @ref{cc2,,RLock} ，不会使用它的 @ref{24e0,,release()} 方法释放锁，因为当它被递归多次获取时，实际上可能无法解锁。相反，使用了 @ref{cc2,,RLock} 类的内部接口，即使多次递归获取它也能解锁它。 然后，在重新获取锁时，使用另一个内部接口来恢复递归级别。

返回 @code{True} ，除非提供的 @emph{timeout} 过期，这种情况下返回 @code{False}。


在 3.2 版更改: 很明显，方法总是返回 @code{None}。

@end deffn

@geindex wait_for() (threading.Condition 方法)
@anchor{library/threading threading Condition wait_for}@anchor{24e2}
@deffn {方法} wait_for (predicate, timeout=None)

等待，直到条件计算为真。 @emph{predicate} 应该是一个可调用对象而且它的返回值可被解释为一个布尔值。可以提供 @emph{timeout} 参数给出最大等待时间。

这个实用方法会重复地调用 @ref{fe2,,wait()} 直到满足判断式或者发生超时。返回值是判断式最后一个返回值，而且如果方法发生超时会返回 @code{False} 。

忽略超时功能，调用此方法大致相当于编写:

@example
while not predicate():
    cv.wait()
@end example

因此，规则同样适用于 @ref{fe2,,wait()} ：锁必须在被调用时保持获取，并在返回时重新获取。 随着锁定执行判断式。


3.2 新版功能.

@end deffn

@geindex notify() (threading.Condition 方法)
@anchor{library/threading threading Condition notify}@anchor{f71}
@deffn {方法} notify (n=1)

默认唤醒一个等待这个条件的线程。如果调用线程在没有获得锁的情况下调用这个方法，会引发 @ref{3e4,,RuntimeError} 异常。

这个方法唤醒最多 @emph{n} 个正在等待这个条件变量的线程；如果没有线程在等待，这是一个空操作。

当前实现中，如果至少有 @emph{n} 个线程正在等待，准确唤醒 @emph{n} 个线程。但是依赖这个行为并不安全。未来，优化的实现有时会唤醒超过 @emph{n} 个线程。

注意：被唤醒的线程并没有真正恢复到它调用的 @ref{fe2,,wait()} ，直到它可以重新获得锁。 因为 @ref{f71,,notify()} 不释放锁，其调用者才应该这样做。
@end deffn

@geindex notify_all() (threading.Condition 方法)
@anchor{library/threading threading Condition notify_all}@anchor{24e1}
@deffn {方法} notify_all ()

唤醒所有正在等待这个条件的线程。这个方法行为与 @ref{f71,,notify()} 相似，但并不只唤醒单一线程，而是唤醒所有等待线程。如果调用线程在调用这个方法时没有获得锁，会引发 @ref{3e4,,RuntimeError} 异常。
@end deffn
@end deffn

@node 信号量对象,事件对象,条件对象,threading --- 基于线程的并行
@anchor{library/threading id5}@anchor{24e3}@anchor{library/threading semaphore-objects}@anchor{24e4}
@subsubsection 信号量对象


这是计算机科学史上最古老的同步原语之一，早期的荷兰科学家 Edsger W. Dijkstra 发明了它。（他使用名称 @code{P()} 和 @code{V()} 而不是 @ref{cc0,,acquire()} 和 @ref{24e5,,release()} ）。

一个信号量管理一个内部计数器，该计数器因 @ref{cc0,,acquire()} 方法的调用而递减，因 @ref{24e5,,release()} 方法的调用而递增。 计数器的值永远不会小于零；当 @ref{cc0,,acquire()} 方法发现计数器为零时，将会阻塞，直到其它线程调用 @ref{24e5,,release()} 方法。

信号量对象也支持 @ref{24d7,,上下文管理协议} 。

@geindex Semaphore (threading 中的类)
@anchor{library/threading threading Semaphore}@anchor{b8c}
@deffn {类} threading.Semaphore (value=1)

该类实现信号量对象。信号量对象管理一个原子性的计数器，代表 @ref{24e5,,release()} 方法的调用次数减去 @ref{cc0,,acquire()} 的调用次数再加上一个初始值。如果需要， @ref{cc0,,acquire()} 方法将会阻塞直到可以返回而不会使得计数器变成负数。在没有显式给出 @emph{value} 的值时，默认为1。

可选参数 @emph{value} 赋予内部计数器初始值，默认值为 @code{1} 。如果 @emph{value} 被赋予小于0的值，将会引发 @ref{16d,,ValueError} 异常。


在 3.3 版更改: 从工厂函数变为类。


@geindex acquire() (threading.Semaphore 方法)
@anchor{library/threading threading Semaphore acquire}@anchor{cc0}
@deffn {方法} acquire (blocking=True, timeout=None)

获取一个信号量。

在不带参数的情况下调用时：


@itemize *

@item 
如果在进入时内部计数器的值大于零，则将其减一并立即返回 @code{True}.

@item 
如果在进入时内部计数器的值为零，则将会阻塞直到被对 @ref{24e5,,release()} 的调用唤醒。 一旦被唤醒（并且计数器的值大于 0），则将计数器减 1 并返回 @code{True}。 每次对 @ref{24e5,,release()} 的调用将只唤醒一个线程。 线程被唤醒的次序是不可确定的。
@end itemize

当发起调用时将 @emph{blocking} 设为假值，则不进行阻塞。 如果一个无参数调用将要阻塞，则立即返回 @code{False}；在其他情况下，执行与无参数调用时一样的操作，然后返回 @code{True}。

当发起调用时如果 @emph{timeout} 不为 @code{None}，则它将阻塞最多 @emph{timeout} 秒。 请求在此时段时未能成功完成获取则将返回 @code{False}。 在其他情况下返回 @code{True}。


在 3.2 版更改: 新的 @emph{timeout} 形参。

@end deffn

@geindex release() (threading.Semaphore 方法)
@anchor{library/threading threading Semaphore release}@anchor{24e5}
@deffn {方法} release (n=1)

释放一个信号量，将内部计数器的值增加 @emph{n}。 当进入时值为零且有其他线程正在等待它再次变为大于零时，则唤醒那 @emph{n} 个线程。


在 3.9 版更改: 增加了 @emph{n} 形参以一次性释放多个等待线程。

@end deffn
@end deffn

@geindex BoundedSemaphore (threading 中的类)
@anchor{library/threading threading BoundedSemaphore}@anchor{b8d}
@deffn {类} threading.BoundedSemaphore (value=1)

该类实现有界信号量。有界信号量通过检查以确保它当前的值不会超过初始值。如果超过了初始值，将会引发 @ref{16d,,ValueError} 异常。在大多情况下，信号量用于保护数量有限的资源。如果信号量被释放的次数过多，则表明出现了错误。没有指定时， @emph{value} 的值默认为1。


在 3.3 版更改: 从工厂函数变为类。

@end deffn

@menu
* Semaphore 例子:: 

@end menu

@node Semaphore 例子,,,信号量对象
@anchor{library/threading semaphore-example}@anchor{24e6}@anchor{library/threading semaphore-examples}@anchor{24e7}
@subsubsection @code{Semaphore} 例子


信号量通常用于保护数量有限的资源，例如数据库服务器。在资源数量固定的任何情况下，都应该使用有界信号量。在生成任何工作线程前，应该在主线程中初始化信号量。

@example
maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)
@end example

工作线程生成后，当需要连接服务器时，这些线程将调用信号量的 acquire 和 release 方法：

@example
with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()
@end example

使用有界信号量能减少这种编程错误：信号量的释放次数多于其请求次数。

@node 事件对象,定时器对象,信号量对象,threading --- 基于线程的并行
@anchor{library/threading event-objects}@anchor{24e8}@anchor{library/threading id6}@anchor{24e9}
@subsubsection 事件对象


这是线程之间通信的最简单机制之一：一个线程发出事件信号，而其他线程等待该信号。

一个事件对象管理一个内部标识，调用 @ref{24ea,,set()} 方法可将其设置为 true ，调用  @ref{24eb,,clear()} 方法可将其设置为 false ，调用 @ref{d87,,wait()} 方法将进入阻塞直到标识为 true 。

@geindex Event (threading 中的类)
@anchor{library/threading threading Event}@anchor{b8e}
@deffn {类} threading.Event

实现事件对象的类。事件对象管理一个内部标识，调用 @ref{24ea,,set()} 方法可将其设置为true。调用  @ref{24eb,,clear()} 方法可将其设置为 false 。调用 @ref{d87,,wait()} 方法将进入阻塞直到标识为true。这个标识初始时为 false 。


在 3.3 版更改: 从工厂函数变为类。


@geindex is_set() (threading.Event 方法)
@anchor{library/threading threading Event is_set}@anchor{24ec}
@deffn {方法} is_set ()

当且仅当内部标识为 true 时返回 @code{True} 。
@end deffn

@geindex set() (threading.Event 方法)
@anchor{library/threading threading Event set}@anchor{24ea}
@deffn {方法} set ()

将内部标识设置为 true 。所有正在等待这个事件的线程将被唤醒。当标识为 true 时，调用 @ref{d87,,wait()} 方法的线程不会被被阻塞。
@end deffn

@geindex clear() (threading.Event 方法)
@anchor{library/threading threading Event clear}@anchor{24eb}
@deffn {方法} clear ()

将内部标识设置为 false 。之后调用 @ref{d87,,wait()} 方法的线程将会被阻塞，直到调用 @ref{24ea,,set()} 方法将内部标识再次设置为 true 。
@end deffn

@geindex wait() (threading.Event 方法)
@anchor{library/threading threading Event wait}@anchor{d87}
@deffn {方法} wait (timeout=None)

阻塞线程直到内部变量为 true 。如果调用时内部标识为 true，将立即返回。否则将阻塞线程，直到调用 @ref{24ea,,set()} 方法将标识设置为 true 或者发生可选的超时。

当提供了timeout参数且不是 @code{None} 时，它应该是一个浮点数，代表操作的超时时间，以秒为单位（可以为小数）。

当且仅当内部旗标在等待调用之前或者等待开始之后被设为真值时此方法将返回 @code{True}，也就是说，它将总是返回 @code{True} 除非设定了超时且操作发生了超时。


在 3.1 版更改: 很明显，方法总是返回 @code{None}。

@end deffn
@end deffn

@node 定时器对象,栅栏对象,事件对象,threading --- 基于线程的并行
@anchor{library/threading id7}@anchor{24ed}@anchor{library/threading timer-objects}@anchor{24ee}
@subsubsection 定时器对象


此类表示一个操作应该在等待一定的时间之后运行 --- 相当于一个定时器。 @ref{b8f,,Timer} 类是 @ref{21b,,Thread} 类的子类，因此可以像一个自定义线程一样工作。

与线程一样，通过调用 @code{start()} 方法启动定时器。而 @ref{24ef,,cancel()} 方法可以停止计时器（在计时结束前）， 定时器在执行其操作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。

例如:

@example
def hello():
    print("hello, world")

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed
@end example

@geindex Timer (threading 中的类)
@anchor{library/threading threading Timer}@anchor{b8f}
@deffn {类} threading.Timer (interval, function, args=None, kwargs=None)

创建一个定时器，在经过 @emph{interval} 秒的间隔事件后，将会用参数 @emph{args} 和关键字参数 @emph{kwargs} 调用 @emph{function}。如果 @emph{args} 为 @code{None} （默认值），则会使用一个空列表。如果 @emph{kwargs} 为 @code{None} （默认值），则会使用一个空字典。


在 3.3 版更改: 从工厂函数变为类。


@geindex cancel() (threading.Timer 方法)
@anchor{library/threading threading Timer cancel}@anchor{24ef}
@deffn {方法} cancel ()

停止定时器并取消执行计时器将要执行的操作。仅当计时器仍处于等待状态时有效。
@end deffn
@end deffn

@node 栅栏对象,在 with 语句中使用锁、条件和信号量,定时器对象,threading --- 基于线程的并行
@anchor{library/threading barrier-objects}@anchor{24f0}
@subsubsection 栅栏对象



3.2 新版功能.


栅栏类提供一个简单的同步原语，用于应对固定数量的线程需要彼此相互等待的情况。线程调用 @ref{24f1,,wait()} 方法后将阻塞，直到所有线程都调用了 @ref{24f1,,wait()} 方法。此时所有线程将被同时释放。

栅栏对象可以被多次使用，但进程的数量不能改变。

这是一个使用简便的方法实现客户端进程与服务端进程同步的例子：

@example
b = Barrier(2, timeout=5)

def server():
    start_server()
    b.wait()
    while True:
        connection = accept_connection()
        process_server_connection(connection)

def client():
    b.wait()
    while True:
        connection = make_connection()
        process_client_connection(connection)
@end example

@geindex Barrier (threading 中的类)
@anchor{library/threading threading Barrier}@anchor{c3a}
@deffn {类} threading.Barrier (parties, action=None, timeout=None)

创建一个需要 @emph{parties} 个线程的栅栏对象。如果提供了可调用的 @emph{action} 参数，它会在所有线程被释放时在其中一个线程中自动调用。 @emph{timeout} 是默认的超时时间，如果没有在 @ref{24f1,,wait()} 方法中指定超时时间的话。

@geindex wait() (threading.Barrier 方法)
@anchor{library/threading threading Barrier wait}@anchor{24f1}
@deffn {方法} wait (timeout=None)

冲出栅栏。当栅栏中所有线程都已经调用了这个函数，它们将同时被释放。如果提供了 @emph{timeout} 参数，这里的 @emph{timeout} 参数优先于创建栅栏对象时提供的 @emph{timeout} 参数。

函数返回值是一个整数，取值范围在0到 @emph{parties} -- 1，在每个线程中的返回值不相同。可用于从所有线程中选择唯一的一个线程执行一些特别的工作。例如：

@example
i = barrier.wait()
if i == 0:
    # Only one thread needs to print this
    print("passed the barrier")
@end example

如果创建栅栏对象时在构造函数中提供了 @emph{action} 参数，它将在其中一个线程释放前被调用。如果此调用引发了异常，栅栏对象将进入损坏态。

如果发生了超时，栅栏对象将进入破损态。

如果栅栏对象进入破损态，或重置栅栏时仍有线程等待释放，将会引发 @ref{c3c,,BrokenBarrierError} 异常。
@end deffn

@geindex reset() (threading.Barrier 方法)
@anchor{library/threading threading Barrier reset}@anchor{24f2}
@deffn {方法} reset ()

重置栅栏为默认的初始态。如果栅栏中仍有线程等待释放，这些线程将会收到 @ref{c3c,,BrokenBarrierError} 异常。

请注意使用此函数时，如果存在状态未知的其他线程，则可能需要执行外部同步。 如果栅栏已损坏则最好将其废弃并新建一个。
@end deffn

@geindex abort() (threading.Barrier 方法)
@anchor{library/threading threading Barrier abort}@anchor{24f3}
@deffn {方法} abort ()

使栅栏处于损坏状态。 这将导致任何现有和未来对 @ref{24f1,,wait()} 的调用失败并引发 @ref{c3c,,BrokenBarrierError}。 例如可以在需要中止某个线程时使用此方法，以避免应用程序的死锁。

更好的方式是：创建栅栏时提供一个合理的超时时间，来自动避免某个线程出错。
@end deffn

@geindex parties (threading.Barrier 属性)
@anchor{library/threading threading Barrier parties}@anchor{24f4}
@deffn {属性} parties

冲出栅栏所需要的线程数量。
@end deffn

@geindex n_waiting (threading.Barrier 属性)
@anchor{library/threading threading Barrier n_waiting}@anchor{24f5}
@deffn {属性} n_waiting

当前时刻正在栅栏中阻塞的线程数量。
@end deffn

@geindex broken (threading.Barrier 属性)
@anchor{library/threading threading Barrier broken}@anchor{24f6}
@deffn {属性} broken

一个布尔值，值为 @code{True} 表明栅栏为破损态。
@end deffn
@end deffn

@geindex BrokenBarrierError
@anchor{library/threading threading BrokenBarrierError}@anchor{c3c}
@deffn {例外} threading.BrokenBarrierError

异常类，是 @ref{3e4,,RuntimeError} 异常的子类，在 @ref{c3a,,Barrier} 对象重置时仍有线程阻塞时和对象进入破损态时被引发。
@end deffn

@node 在 with 语句中使用锁、条件和信号量,,栅栏对象,threading --- 基于线程的并行
@anchor{library/threading using-locks-conditions-and-semaphores-in-the-with-statement}@anchor{24f7}@anchor{library/threading with-locks}@anchor{24d7}
@subsubsection 在 @code{with} 语句中使用锁、条件和信号量


这个模块提供的带有 @code{acquire()} 和 @code{release()} 方法的对象，可以被用作 @ref{7e4,,with} 语句的上下文管理器。当进入语句块时 @code{acquire()} 方法会被调用，退出语句块时 @code{release()} 会被调用。因此，以下片段:

@example
with some_lock:
    # do something...
@end example

相当于:

@example
some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()
@end example

现在 @ref{24d8,,Lock} 、 @ref{cc2,,RLock} 、 @ref{b8b,,Condition} 、 @ref{b8c,,Semaphore} 和 @ref{b8d,,BoundedSemaphore} 对象可以用作 @ref{7e4,,with} 语句的上下文管理器。

@node multiprocessing --- 基于进程的并行,multiprocessing shared_memory --- 可从进程直接访问的共享内存,threading --- 基于线程的并行,并发执行
@anchor{library/multiprocessing doc}@anchor{24f8}@anchor{library/multiprocessing module-multiprocessing}@anchor{b7}@anchor{library/multiprocessing multiprocessing-process-based-parallelism}@anchor{24f9}
@subsection @code{multiprocessing} --- 基于进程的并行


@geindex multiprocessing (模块)

@strong{源代码} Lib/multiprocessing/@footnote{https://github.com/python/cpython/tree/3.9/Lib/multiprocessing/}


__________________________________________________________________


@menu
* 概述: 概述<9>. 
* 参考:: 
* 编程指导:: 
* 示例: 示例<17>. 

@end menu

@node 概述<9>,参考,,multiprocessing --- 基于进程的并行
@anchor{library/multiprocessing introduction}@anchor{24fa}
@subsubsection 概述


@ref{b7,,multiprocessing} 是一个支持使用与 @ref{10b,,threading} 模块类似的 API 来产生进程的包。 @ref{b7,,multiprocessing} 包同时提供了本地和远程并发操作，通过使用子进程而非线程有效地绕过了 @ref{60b,,全局解释器锁}。 因此，@ref{b7,,multiprocessing} 模块允许程序员充分利用给定机器上的多个处理器。 它在 Unix 和 Windows 上均可运行。

@ref{b7,,multiprocessing} 模块还引入了在 @ref{10b,,threading} 模块中没有的API。一个主要的例子就是 @ref{96f,,Pool} 对象，它提供了一种快捷的方法，赋予函数并行化处理一系列输入值的能力，可以将输入数据分配给不同进程处理（数据并行）。下面的例子演示了在模块中定义此类函数的常见做法，以便子进程可以成功导入该模块。这个数据并行的基本例子使用了 @ref{96f,,Pool} ，

@example
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))
@end example

将在标准输出中打印

@example
[1, 4, 9]
@end example

@menu
* Process 类:: 
* 上下文和启动方法:: 
* 在进程之间交换对象:: 
* 进程间同步:: 
* 进程间共享状态:: 
* 使用工作进程:: 

@end menu

@node Process 类,上下文和启动方法,,概述<9>
@anchor{library/multiprocessing the-process-class}@anchor{24fb}
@subsubsection @code{Process} 类


在 @ref{b7,,multiprocessing} 中，通过创建一个 @ref{4c1,,Process} 对象然后调用它的 @code{start()} 方法来生成进程。 @ref{4c1,,Process} 和 @ref{21b,,threading.Thread} API 相同。 一个简单的多进程程序示例是:

@example
from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
@end example

要显示所涉及的各个进程ID，这是一个扩展示例:

@example
from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

if __name__ == '__main__':
    info('main line')
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
@end example

关于为什么 @code{if __name__ == '__main__'} 部分是必需的解释，请参见 @ref{24fc,,编程指导}。

@node 上下文和启动方法,在进程之间交换对象,Process 类,概述<9>
@anchor{library/multiprocessing contexts-and-start-methods}@anchor{24fd}
@subsubsection 上下文和启动方法

@anchor{library/multiprocessing multiprocessing-start-methods}@anchor{96a}
根据不同的平台， @ref{b7,,multiprocessing} 支持三种启动进程的方法。这些 @emph{启动方法} 有

@quotation


@table @asis

@item @emph{spawn}

父进程会启动一个全新的 python 解释器进程。 子进程将只继承那些运行进程对象的 @ref{24fe,,run()} 方法所必需的资源。 特别地，来自父进程的非必需文件描述符和句柄将不会被继承。 使用此方法启动进程相比使用 @emph{fork} 或 @emph{forkserver} 要慢上许多。

可在Unix和Windows上使用。 Windows上的默认设置。

@item @emph{fork}

父进程使用 @ref{a4b,,os.fork()} 来产生 Python 解释器分叉。子进程在开始时实际上与父进程相同。父进程的所有资源都由子进程继承。请注意，安全分叉多线程进程是棘手的。

只存在于Unix。Unix中的默认值。

@item @emph{forkserver}

程序启动并选择 @emph{forkserver} 启动方法时，将启动服务器进程。 从那时起，每当需要一个新进程时，父进程就会连接到服务器并请求它分叉一个新进程。 分叉服务器进程是单线程的，因此使用 @ref{a4b,,os.fork()}  是安全的。 没有不必要的资源被继承。

可在Unix平台上使用，支持通过Unix管道传递文件描述符。
@end table
@end quotation


在 3.8 版更改: 对于 macOS，@emph{spawn} 启动方式是默认方式。 因为 @emph{fork} 可能导致subprocess崩溃，被认为是不安全的，查看 bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725} 。



在 3.4 版更改: 在所有unix平台上添加支持了 @emph{spawn} ，并且为一些unix平台添加了 @emph{forkserver} 。在Windows上子进程不再继承所有可继承的父进程句柄。


在 Unix 上通过 @emph{spawn} 和 @emph{forkserver} 方式启动多进程会同时启动一个 @emph{资源追踪} 进程，负责追踪当前程序的进程产生的、并且不再被使用的命名系统资源(如命名信号量以及 @ref{24ff,,SharedMemory}  对象)。当所有进程退出后，资源追踪会负责释放这些仍被追踪的的对象。通常情况下是不会有这种对象的，但是假如一个子进程被某个信号杀死，就可能存在这一类资源的“泄露”情况。（泄露的信号量以及共享内存不会被释放，直到下一次系统重启，对于这两类资源来说，这是一个比较大的问题，因为操作系统允许的命名信号量的数量是有限的，而共享内存也会占据主内存的一片空间）

要选择一个启动方法，你应该在主模块的 @code{if __name__ == '__main__'} 子句中调用 @ref{96d,,set_start_method()} 。例如：

@example
import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    mp.set_start_method('spawn')
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()
@end example

在程序中 @ref{96d,,set_start_method()} 不应该被多次调用。

或者，你可以使用 @ref{96e,,get_context()} 来获取上下文对象。上下文对象与 multiprocessing 模块具有相同的API，并允许在同一程序中使用多种启动方法。:

@example
import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()
@end example

请注意，对象在不同上下文创建的进程间可能并不兼容。 特别是，使用 @emph{fork} 上下文创建的锁不能传递给使用 @emph{spawn} 或 @emph{forkserver} 启动方法启动的进程。

想要使用特定启动方法的库应该使用 @ref{96e,,get_context()} 以避免干扰库用户的选择。

@cartouche
@quotation 警告 
@code{'spawn'} 和 @code{'forkserver'} 启动方法当前不能在Unix上和“冻结的”可执行内容一同使用（例如，有类似 @strong{PyInstaller} 和 @strong{cx_Freeze} 的包产生的二进制文件）。 @code{'fork'} 启动方法可以使用。
@end quotation
@end cartouche

@node 在进程之间交换对象,进程间同步,上下文和启动方法,概述<9>
@anchor{library/multiprocessing exchanging-objects-between-processes}@anchor{2500}
@subsubsection 在进程之间交换对象


@ref{b7,,multiprocessing} 支持进程之间的两种通信通道：

@strong{队列}

@quotation

@ref{f72,,Queue} 类是一个近似 @ref{de6,,queue.Queue} 的克隆。 例如:

@example
from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())    # prints "[42, None, 'hello']"
    p.join()
@end example

队列是线程和进程安全的。
@end quotation

@strong{管道}

@quotation

@ref{2501,,Pipe()} 函数返回一个由管道连接的连接对象，默认情况下是双工（双向）。例如:

@example
from multiprocessing import Process, Pipe

def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "[42, None, 'hello']"
    p.join()
@end example

返回的两个连接对象 @ref{2501,,Pipe()} 表示管道的两端。每个连接对象都有 @code{send()} 和 @code{recv()} 方法（相互之间的）。请注意，如果两个进程（或线程）同时尝试读取或写入管道的 @emph{同一} 端，则管道中的数据可能会损坏。当然，在不同进程中同时使用管道的不同端的情况下不存在损坏的风险。
@end quotation

@node 进程间同步,进程间共享状态,在进程之间交换对象,概述<9>
@anchor{library/multiprocessing synchronization-between-processes}@anchor{2502}
@subsubsection 进程间同步


对于所有在 @ref{10b,,threading} 存在的同步原语，@ref{b7,,multiprocessing} 中都有类似的等价物。例如，可以使用锁来确保一次只有一个进程打印到标准输出:

@example
from multiprocessing import Process, Lock

def f(l, i):
    l.acquire()
    try:
        print('hello world', i)
    finally:
        l.release()

if __name__ == '__main__':
    lock = Lock()

    for num in range(10):
        Process(target=f, args=(lock, num)).start()
@end example

不使用锁的情况下，来自于多进程的输出很容易产生混淆。

@node 进程间共享状态,使用工作进程,进程间同步,概述<9>
@anchor{library/multiprocessing sharing-state-between-processes}@anchor{2503}
@subsubsection 进程间共享状态


如上所述，在进行并发编程时，通常最好尽量避免使用共享状态。使用多个进程时尤其如此。

但是，如果你真的需要使用一些共享数据，那么 @ref{b7,,multiprocessing} 提供了两种方法。

@strong{共享内存}

@quotation

可以使用 @ref{2504,,Value} 或 @ref{2505,,Array} 将数据存储在共享内存映射中。例如，以下代码:

@example
from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])
@end example

将打印

@example
3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
@end example

创建 @code{num} 和 @code{arr} 时使用的 @code{'d'} 和 @code{'i'} 参数是 @ref{6,,array} 模块使用的类型的 typecode ： @code{'d'} 表示双精度浮点数， @code{'i'} 表示有符号整数。这些共享对象将是进程和线程安全的。

为了更灵活地使用共享内存，可以使用 @ref{bd,,multiprocessing.sharedctypes} 模块，该模块支持创建从共享内存分配的任意ctypes对象。
@end quotation

@strong{服务进程}

@quotation

由 @ref{668,,Manager()} 返回的管理器对象控制一个服务进程，该进程保存Python对象并允许其他进程使用代理操作它们。

@ref{668,,Manager()} 返回的管理器支持类型： @ref{1f9,,list} 、 @ref{164,,dict} 、 @ref{2506,,Namespace} 、 @ref{2507,,Lock} 、 @ref{2508,,RLock} 、 @ref{2509,,Semaphore} 、 @ref{250a,,BoundedSemaphore} 、 @ref{250b,,Condition} 、 @ref{250c,,Event} 、 @ref{250d,,Barrier} 、 @ref{f72,,Queue} 、 @ref{2504,,Value} 和 @ref{2505,,Array} 。例如

@example
from multiprocessing import Process, Manager

def f(d, l):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))

        p = Process(target=f, args=(d, l))
        p.start()
        p.join()

        print(d)
        print(l)
@end example

将打印

@example
@{0.25: None, 1: '1', '2': 2@}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
@end example

使用服务进程的管理器比使用共享内存对象更灵活，因为它们可以支持任意对象类型。此外，单个管理器可以通过网络由不同计算机上的进程共享。但是，它们比使用共享内存慢。
@end quotation

@node 使用工作进程,,进程间共享状态,概述<9>
@anchor{library/multiprocessing using-a-pool-of-workers}@anchor{250e}
@subsubsection 使用工作进程


@ref{96f,,Pool} 类表示一个工作进程池。它具有允许以几种不同方式将任务分配到工作进程的方法。

例如:

@example
from multiprocessing import Pool, TimeoutError
import time
import os

def f(x):
    return x*x

if __name__ == '__main__':
    # start 4 worker processes
    with Pool(processes=4) as pool:

        # print "[0, 1, 4,..., 81]"
        print(pool.map(f, range(10)))

        # print same numbers in arbitrary order
        for i in pool.imap_unordered(f, range(10)):
            print(i)

        # evaluate "f(20)" asynchronously
        res = pool.apply_async(f, (20,))      # runs in *only* one process
        print(res.get(timeout=1))             # prints "400"

        # evaluate "os.getpid()" asynchronously
        res = pool.apply_async(os.getpid, ()) # runs in *only* one process
        print(res.get(timeout=1))             # prints the PID of that process

        # launching multiple evaluations asynchronously *may* use more processes
        multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
        print([res.get(timeout=1) for res in multiple_results])

        # make a single worker sleep for 10 secs
        res = pool.apply_async(time.sleep, (10,))
        try:
            print(res.get(timeout=1))
        except TimeoutError:
            print("We lacked patience and got a multiprocessing.TimeoutError")

        print("For the moment, the pool remains available for more work")

    # exiting the 'with'-block has stopped the pool
    print("Now the pool is closed and no longer available")
@end example

请注意，进程池的方法只能由创建它的进程使用。

@cartouche
@quotation 注解 
这个包中的功能要求子进程可以导入 @code{__main__} 模块。虽然这在 @ref{24fc,,编程指导} 中有描述，但还是需要提前说明一下。这意味着一些示例在交互式解释器中不起作用，比如 @ref{96f,,multiprocessing.pool.Pool} 示例。例如:

@example
>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
...     return x*x
...
>>> with p:
...   p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
Traceback (most recent call last):
Traceback (most recent call last):
Traceback (most recent call last):
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'
@end example

（如果尝试执行上面的代码，它会以一种半随机的方式将三个完整的堆栈内容交替输出，然后你只能以某种方式停止父进程。)
@end quotation
@end cartouche

@node 参考,编程指导,概述<9>,multiprocessing --- 基于进程的并行
@anchor{library/multiprocessing reference}@anchor{250f}
@subsubsection 参考


@ref{b7,,multiprocessing} 包主要复制了 @ref{10b,,threading} 模块的API。

@menu
* Process 和异常:: 
* 管道和队列:: 
* 杂项: 杂项<3>. 
* 连接（Connection）对象:: 
* 同步原语:: 
* 共享 ctypes 对象:: 
* 管理器:: 
* 代理对象:: 
* 进程池:: 
* 监听器及客户端:: 
* 认证密码:: 
* 日志: 日志<2>. 
* multiprocessing.dummy 模块: multiprocessing dummy 模块. 

@end menu

@node Process 和异常,管道和队列,,参考
@anchor{library/multiprocessing process-and-exceptions}@anchor{2510}
@subsubsection @code{Process} 和异常


@geindex Process (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Process}@anchor{4c1}
@deffn {类} multiprocessing.Process (group=None, target=None, name=None, args=(), kwargs=@{@}, *, daemon=None)

进程对象表示在单独进程中运行的活动。 @ref{4c1,,Process} 类拥有和 @ref{21b,,threading.Thread} 等价的大部分方法。

应始终使用关键字参数调用构造函数。 @emph{group} 应该始终是 @code{None} ；它仅用于兼容 @ref{21b,,threading.Thread} 。 @emph{target} 是由 @ref{24fe,,run()} 方法调用的可调用对象。它默认为 @code{None} ，意味着什么都没有被调用。 @emph{name} 是进程名称（有关详细信息，请参阅 @ref{2511,,name} ）。 @emph{args} 是目标调用的参数元组。 @emph{kwargs} 是目标调用的关键字参数字典。如果提供，则键参数 @emph{daemon} 将进程 @ref{2512,,daemon} 标志设置为 @code{True} 或 @code{False} 。如果是 @code{None} （默认值），则该标志将从创建的进程继承。

默认情况下，不会将任何参数传递给 @emph{target} 。

如果子类重写构造函数，它必须确保它在对进程执行任何其他操作之前调用基类构造函数（ @code{Process.__init__()} ）。


在 3.3 版更改: 加入 @emph{daemon} 参数。


@geindex run() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process run}@anchor{24fe}
@deffn {方法} run ()

表示进程活动的方法。

你可以在子类中重载此方法。标准 @ref{24fe,,run()} 方法调用传递给对象构造函数的可调用对象作为目标参数（如果有），分别从 @emph{args} 和 @emph{kwargs} 参数中获取顺序和关键字参数。
@end deffn

@geindex start() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process start}@anchor{2513}
@deffn {方法} start ()

启动进程活动。

这个方法每个进程对象最多只能调用一次。它会将对象的 @ref{24fe,,run()} 方法安排在一个单独的进程中调用。
@end deffn

@geindex join() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process join}@anchor{2514}
@deffn {方法} join ([timeout])

如果可选参数 @emph{timeout} 是 @code{None} （默认值），则该方法将阻塞，直到调用 @ref{2514,,join()} 方法的进程终止。如果 @emph{timeout} 是一个正数，它最多会阻塞 @emph{timeout} 秒。请注意，如果进程终止或方法超时，则该方法返回 @code{None} 。检查进程的 @ref{2515,,exitcode} 以确定它是否终止。

一个进程可以被 join 多次。

进程无法join自身，因为这会导致死锁。尝试在启动进程之前join进程是错误的。
@end deffn

@geindex name (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process name}@anchor{2511}
@deffn {属性} name

进程的名称。该名称是一个字符串，仅用于识别目的。它没有语义。可以为多个进程指定相同的名称。

初始名称由构造器设定。 如果没有为构造器提供显式名称，则会构造一个形式为 'Process-N@w{[1]}:N@w{[2]}:...:N@w{[k]}' 的名称，其中每个 N@w{[k]} 是其父亲的第 N 个孩子。
@end deffn

@geindex is_alive() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process is_alive}@anchor{2516}
@deffn {方法} is_alive ()

返回进程是否还活着。

粗略地说，从 @ref{2513,,start()} 方法返回到子进程终止之前，进程对象仍处于活动状态。
@end deffn

@geindex daemon (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process daemon}@anchor{2512}
@deffn {属性} daemon

进程的守护标志，一个布尔值。这必须在 @ref{2513,,start()} 被调用之前设置。

初始值继承自创建进程。

当进程退出时，它会尝试终止其所有守护进程子进程。

请注意，不允许在守护进程中创建子进程。这是因为当守护进程由于父进程退出而中断时，其子进程会变成孤儿进程。 另外，这些 @strong{不是} Unix 守护进程或服务，它们是正常进程，如果非守护进程已经退出，它们将被终止（并且不被合并）。
@end deffn

除了 @ref{21b,,threading.Thread} API ，@ref{4c1,,Process} 对象还支持以下属性和方法：

@geindex pid (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process pid}@anchor{2517}
@deffn {属性} pid

返回进程ID。在生成该进程之前，这将是 @code{None} 。
@end deffn

@geindex exitcode (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process exitcode}@anchor{2515}
@deffn {属性} exitcode

子进程的退出代码。如果该进程尚未终止则为 @code{None} 。

如果子进程的 @ref{24fe,,run()} 方法正常返回，退出代码将是 0 。 如果它通过 @ref{db2,,sys.exit()} 终止，并有一个整数参数 @emph{N} ，退出代码将是 @emph{N} 。

如果子进程由于在 @ref{24fe,,run()} 内的未捕获异常而终止，退出代码将是 1 。 如果它是由信号 @emph{N} 终止的，退出代码将是负值 @emph{-N} 。
@end deffn

@geindex authkey (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process authkey}@anchor{2518}
@deffn {属性} authkey

进程的身份验证密钥（字节字符串）。

当 @ref{b7,,multiprocessing} 初始化时，主进程使用 @ref{5d4,,os.urandom()} 分配一个随机字符串。

当创建 @ref{4c1,,Process} 对象时，它将继承其父进程的身份验证密钥，尽管可以通过将 @ref{2518,,authkey} 设置为另一个字节字符串来更改。

参见 @ref{2519,,认证密码} 。
@end deffn

@geindex sentinel (multiprocessing.Process 属性)
@anchor{library/multiprocessing multiprocessing Process sentinel}@anchor{b0b}
@deffn {属性} sentinel

系统对象的数字句柄，当进程结束时将变为 "ready" 。

如果要使用 @ref{b0a,,multiprocessing.connection.wait()} 一次等待多个事件，可以使用此值。否则调用 @ref{2514,,join()} 更简单。

在Windows上，这是一个操作系统句柄，可以与 @code{WaitForSingleObject} 和 @code{WaitForMultipleObjects} 系列API调用一起使用。在Unix上，这是一个文件描述符，可以使用来自 @ref{e5,,select} 模块的原语。


3.3 新版功能.

@end deffn

@geindex terminate() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process terminate}@anchor{251a}
@deffn {方法} terminate ()

终止进程。 在Unix上，这是使用 @code{SIGTERM} 信号完成的；在Windows上使用 @code{TerminateProcess()} 。 请注意，不会执行退出处理程序和finally子句等。

请注意，进程的后代进程将不会被终止 —— 它们将简单地变成孤立的。

@cartouche
@quotation 警告 
如果在关联进程使用管道或队列时使用此方法，则管道或队列可能会损坏，并可能无法被其他进程使用。类似地，如果进程已获得锁或信号量等，则终止它可能导致其他进程死锁。
@end quotation
@end cartouche
@end deffn

@geindex kill() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process kill}@anchor{4c0}
@deffn {方法} kill ()

与 @ref{251a,,terminate()} 相同，但在Unix上使用 @code{SIGKILL} 信号。


3.7 新版功能.

@end deffn

@geindex close() (multiprocessing.Process 方法)
@anchor{library/multiprocessing multiprocessing Process close}@anchor{4bf}
@deffn {方法} close ()

关闭 @ref{4c1,,Process} 对象，释放与之关联的所有资源。如果底层进程仍在运行，则会引发 @ref{16d,,ValueError} 。一旦 @ref{4bf,,close()} 成功返回， @ref{4c1,,Process} 对象的大多数其他方法和属性将引发 @ref{16d,,ValueError} 。


3.7 新版功能.

@end deffn

注意 @ref{2513,,start()} 、 @ref{2514,,join()} 、 @ref{2516,,is_alive()} 、 @ref{251a,,terminate()} 和 @ref{2515,,exitcode} 方法只能由创建进程对象的进程调用。

@ref{4c1,,Process} 一些方法的示例用法：

@example
 >>> import multiprocessing, time, signal
 >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
 >>> print(p, p.is_alive())
 <Process ... initial> False
 >>> p.start()
 >>> print(p, p.is_alive())
 <Process ... started> True
 >>> p.terminate()
 >>> time.sleep(0.1)
 >>> print(p, p.is_alive())
 <Process ... stopped exitcode=-SIGTERM> False
 >>> p.exitcode == -signal.SIGTERM
 True
@end example
@end deffn

@geindex ProcessError
@anchor{library/multiprocessing multiprocessing ProcessError}@anchor{251b}
@deffn {例外} multiprocessing.ProcessError

所有 @ref{b7,,multiprocessing} 异常的基类。
@end deffn

@geindex BufferTooShort
@anchor{library/multiprocessing multiprocessing BufferTooShort}@anchor{251c}
@deffn {例外} multiprocessing.BufferTooShort

当提供的缓冲区对象太小而无法读取消息时， @code{Connection.recv_bytes_into()} 引发的异常。

如果 @code{e} 是一个 @ref{251c,,BufferTooShort} 实例，那么 @code{e.args[0]} 将把消息作为字节字符串给出。
@end deffn

@geindex AuthenticationError
@anchor{library/multiprocessing multiprocessing AuthenticationError}@anchor{251d}
@deffn {例外} multiprocessing.AuthenticationError

出现身份验证错误时引发。
@end deffn

@geindex TimeoutError
@anchor{library/multiprocessing multiprocessing TimeoutError}@anchor{251e}
@deffn {例外} multiprocessing.TimeoutError

有超时的方法超时时引发。
@end deffn

@node 管道和队列,杂项<3>,Process 和异常,参考
@anchor{library/multiprocessing pipes-and-queues}@anchor{251f}
@subsubsection 管道和队列


使用多进程时，一般使用消息机制实现进程间通信，尽可能避免使用同步原语，例如锁。

消息机制包含： @ref{2501,,Pipe()} (可以用于在两个进程间传递消息)，以及队列(能够在多个生产者和消费者之间通信)。

@ref{f72,,Queue}, @ref{1c4,,SimpleQueue} 以及 @ref{2520,,JoinableQueue} 都是多生产者，多消费者，并且实现了 @abbr{FIFO} 的队列类型，其表现与标准库中的 @ref{de6,,queue.Queue} 类相似。 不同之处在于 @ref{f72,,Queue}  缺少标准库的 @ref{de6,,queue.Queue} 从 Python 2.5 开始引入的 @ref{2521,,task_done()} 和 @ref{2522,,join()} 方法。

如果你使用了 @ref{2520,,JoinableQueue} ，那么你 @strong{必须} 对每个已经移出队列的任务调用 @ref{2523,,JoinableQueue.task_done()}。 不然的话用于统计未完成任务的信号量最终会溢出并抛出异常。

另外还可以通过使用一个管理器对象创建一个共享队列，详见  @ref{2524,,管理器} 。

@cartouche
@quotation 注解 
@ref{b7,,multiprocessing} 使用了普通的 @ref{2525,,queue.Empty} 和 @ref{2526,,queue.Full} 异常去表示超时。 你需要从 @ref{da,,queue} 中导入它们，因为它们并不在 @ref{b7,,multiprocessing} 的命名空间中。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
当一个对象被放入一个队列中时，这个对象首先会被一个后台线程用 pickle 序列化，并将序列化后的数据通过一个底层管道的管道传递到队列中。 这种做法会有点让人惊讶，但一般不会出现什么问题。 如果它们确实妨碍了你，你可以使用一个由管理器 @ref{2524,,manager} 创建的队列替换它。


@enumerate 

@item 
将一个对象放入一个空队列后，可能需要极小的延迟，队列的方法 @ref{2527,,empty()}  才会返回  @ref{497,,False} 。而  @ref{2528,,get_nowait()} 可以不抛出 @ref{2525,,queue.Empty} 直接返回。

@item 
如果有多个进程同时将对象放入队列，那么在队列的另一端接受到的对象可能是无序的。但是由同一个进程放入的多个对象的顺序在另一端输出时总是一样的。
@end enumerate
@end quotation
@end cartouche

@cartouche
@quotation 警告 
如果一个进程在尝试使用 @ref{f72,,Queue} 期间被 @ref{251a,,Process.terminate()} 或 @ref{dc1,,os.kill()} 调用终止了，那么队列中的数据很可能被破坏。 这可能导致其他进程在尝试使用该队列时发生异常。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
正如刚才提到的，如果一个子进程将一些对象放进队列中 (并且它没有用  @ref{2529,,JoinableQueue.cancel_join_thread} 方法)，那么这个进程在所有缓冲区的对象被刷新进管道之前，是不会终止的。

这意味着，除非你确定所有放入队列中的对象都已经被消费了，否则如果你试图等待这个进程，你可能会陷入死锁中。相似地，如果该子进程不是后台进程，那么父进程可能在试图等待所有非后台进程退出时挂起。

注意用管理器创建的队列不存在这个问题，详见  @ref{24fc,,编程指导} 。
@end quotation
@end cartouche

该 @ref{252a,,示例} 展示了如何使用队列实现进程间通信。

@geindex Pipe() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing Pipe}@anchor{2501}
@deffn {函数} multiprocessing.Pipe ([duplex])

返回一对 @ref{252b,,Connection} 对象 @code{(conn1, conn2)} ， 分别表示管道的两端。

如果 @emph{duplex} 被置为 @code{True} (默认值)，那么该管道是双向的。如果 @emph{duplex} 被置为 @code{False} ，那么该管道是单向的，即 @code{conn1} 只能用于接收消息，而  @code{conn2} 仅能用于发送消息。
@end deffn

@geindex Queue (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Queue}@anchor{f72}
@deffn {类} multiprocessing.Queue ([maxsize])

返回一个使用一个管道和少量锁和信号量实现的共享队列实例。当一个进程将一个对象放进队列中时，一个写入线程会启动并将对象从缓冲区写入管道中。

一旦超时，将抛出标准库 @ref{da,,queue}  模块中常见的异常 @ref{2525,,queue.Empty} 和 @ref{2526,,queue.Full}。

除了 @ref{2521,,task_done()} 和 @ref{2522,,join()} 之外，@ref{f72,,Queue}  实现了标准库类 @ref{de6,,queue.Queue} 中所有的方法。

@geindex qsize() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue qsize}@anchor{252c}
@deffn {方法} qsize ()

返回队列的大致长度。由于多线程或者多进程的上下文，这个数字是不可靠的。

请注意，这可能会在Unix平台上引起 @ref{70e,,NotImplementedError} ，如 macOS ，因为其上没有实现 @code{sem_getvalue()} 。
@end deffn

@geindex empty() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue empty}@anchor{2527}
@deffn {方法} empty ()

如果队列是空的，返回 @code{True} ，反之返回 @code{False} 。 由于多线程或多进程的环境，该状态是不可靠的。
@end deffn

@geindex full() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue full}@anchor{252d}
@deffn {方法} full ()

如果队列是满的，返回 @code{True} ，反之返回 @code{False} 。 由于多线程或多进程的环境，该状态是不可靠的。
@end deffn

@geindex put() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue put}@anchor{11ac}
@deffn {方法} put (obj[, block[, timeout]])

将 obj 放入队列。如果可选参数 @emph{block} 是 @code{True} (默认值) 而且 @emph{timeout} 是 @code{None} (默认值), 将会阻塞当前进程，直到有空的缓冲槽。如果 @emph{timeout} 是正数，将会在阻塞了最多 @emph{timeout} 秒之后还是没有可用的缓冲槽时抛出 @ref{2526,,queue.Full}  异常。反之 (@emph{block} 是 @code{False} 时)，仅当有可用缓冲槽时才放入对象，否则抛出 @ref{2526,,queue.Full} 异常 (在这种情形下 @emph{timeout} 参数会被忽略)。


在 3.8 版更改: 如果队列已经关闭，会抛出  @ref{16d,,ValueError}  而不是  @ref{241,,AssertionError} 。

@end deffn

@geindex put_nowait() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue put_nowait}@anchor{252e}
@deffn {方法} put_nowait (obj)

相当于 @code{put(obj, False)}。
@end deffn

@geindex get() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue get}@anchor{11ad}
@deffn {方法} get ([block[, timeout]])

从队列中取出并返回对象。如果可选参数 @emph{block} 是 @code{True} (默认值) 而且 @emph{timeout} 是 @code{None} (默认值), 将会阻塞当前进程，直到队列中出现可用的对象。如果 @emph{timeout} 是正数，将会在阻塞了最多 @emph{timeout} 秒之后还是没有可用的对象时抛出 @ref{2525,,queue.Empty} 异常。反之 (@emph{block} 是 @code{False} 时)，仅当有可用对象能够取出时返回，否则抛出 @ref{2525,,queue.Empty} 异常 (在这种情形下 @emph{timeout} 参数会被忽略)。


在 3.8 版更改: 如果队列已经关闭，会抛出 @ref{16d,,ValueError} 而不是 @ref{30b,,OSError} 。

@end deffn

@geindex get_nowait() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue get_nowait}@anchor{2528}
@deffn {方法} get_nowait ()

相当于 @code{get(False)}。
@end deffn

@ref{f72,,multiprocessing.Queue} 类有一些在 @ref{de6,,queue.Queue} 类中没有出现的方法。这些方法在大多数情形下并不是必须的。

@geindex close() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue close}@anchor{f73}
@deffn {方法} close ()

指示当前进程将不会再往队列中放入对象。一旦所有缓冲区中的数据被写入管道之后，后台的线程会退出。这个方法在队列被gc回收时会自动调用。
@end deffn

@geindex join_thread() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue join_thread}@anchor{252f}
@deffn {方法} join_thread ()

等待后台线程。这个方法仅在调用了 @ref{f73,,close()} 方法之后可用。这会阻塞当前进程，直到后台线程退出，确保所有缓冲区中的数据都被写入管道中。

默认情况下，如果一个不是队列创建者的进程试图退出，它会尝试等待这个队列的后台线程。这个进程可以使用  @ref{2529,,cancel_join_thread()} 让  @ref{252f,,join_thread()} 方法什么都不做直接跳过。
@end deffn

@geindex cancel_join_thread() (multiprocessing.Queue 方法)
@anchor{library/multiprocessing multiprocessing Queue cancel_join_thread}@anchor{2529}
@deffn {方法} cancel_join_thread ()

防止 @ref{252f,,join_thread()} 方法阻塞当前进程。具体而言，这防止进程退出时自动等待后台线程退出。详见 @ref{252f,,join_thread()}。

可能这个方法称为”@code{allow_exit_without_flush()}“ 会更好。这有可能会导致正在排队进入队列的数据丢失，大多数情况下你不需要用到这个方法，仅当你不关心底层管道中可能丢失的数据，只是希望进程能够马上退出时使用。
@end deffn

@cartouche
@quotation 注解 
该类的功能依赖于宿主操作系统具有可用的共享信号量实现。否则该类将被禁用，任何试图实例化一个 @ref{f72,,Queue} 对象的操作都会抛出 @ref{16c,,ImportError} 异常，更多信息详见 bpo-3770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3770} 。后续说明的任何专用队列对象亦如此。
@end quotation
@end cartouche
@end deffn

@geindex SimpleQueue (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing SimpleQueue}@anchor{1c4}
@deffn {类} multiprocessing.SimpleQueue

这是一个简化的 @ref{f72,,Queue} 类的实现，很像带锁的 @ref{2501,,Pipe} 。

@geindex close() (multiprocessing.SimpleQueue 方法)
@anchor{library/multiprocessing multiprocessing SimpleQueue close}@anchor{1c5}
@deffn {方法} close ()

关闭队列：释放内部资源。

队列在被关闭后就不可再被使用。 例如不可再调用 @ref{2530,,get()}, @ref{2531,,put()} 和 @ref{2532,,empty()} 等方法。


3.9 新版功能.

@end deffn

@geindex empty() (multiprocessing.SimpleQueue 方法)
@anchor{library/multiprocessing multiprocessing SimpleQueue empty}@anchor{2532}
@deffn {方法} empty ()

如果队列为空返回 @code{True} ，否则返回 @code{False} 。
@end deffn

@geindex get() (multiprocessing.SimpleQueue 方法)
@anchor{library/multiprocessing multiprocessing SimpleQueue get}@anchor{2530}
@deffn {方法} get ()

从队列中移出并返回一个对象。
@end deffn

@geindex put() (multiprocessing.SimpleQueue 方法)
@anchor{library/multiprocessing multiprocessing SimpleQueue put}@anchor{2531}
@deffn {方法} put (item)

将  @emph{item} 放入队列。
@end deffn
@end deffn

@geindex JoinableQueue (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing JoinableQueue}@anchor{2520}
@deffn {类} multiprocessing.JoinableQueue ([maxsize])

@ref{2520,,JoinableQueue} 类是 @ref{f72,,Queue} 的子类，额外添加了 @ref{2523,,task_done()} 和 @ref{2533,,join()} 方法。

@geindex task_done() (multiprocessing.JoinableQueue 方法)
@anchor{library/multiprocessing multiprocessing JoinableQueue task_done}@anchor{2523}
@deffn {方法} task_done ()

指出之前进入队列的任务已经完成。由队列的消费者进程使用。对于每次调用  @ref{11ad,,get()}  获取的任务，执行完成后调用  @ref{2523,,task_done()}  告诉队列该任务已经处理完成。

如果 @ref{2522,,join()} 方法正在阻塞之中，该方法会在所有对象都被处理完的时候返回 (即对之前使用  @ref{11ac,,put()}  放进队列中的所有对象都已经返回了对应的  @ref{2523,,task_done()}  ) 。

如果被调用的次数多于放入队列中的项目数量，将引发 @ref{16d,,ValueError} 异常 。
@end deffn

@geindex join() (multiprocessing.JoinableQueue 方法)
@anchor{library/multiprocessing multiprocessing JoinableQueue join}@anchor{2533}
@deffn {方法} join ()

阻塞至队列中所有的元素都被接收和处理完毕。

当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者进程调用 @ref{2523,,task_done()} 表示这个条目已经被回收，该条目所有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候， @code{join()} 阻塞被解除。
@end deffn
@end deffn

@node 杂项<3>,连接（Connection）对象,管道和队列,参考
@anchor{library/multiprocessing miscellaneous}@anchor{2534}
@subsubsection 杂项


@geindex active_children() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing active_children}@anchor{2535}
@deffn {函数} multiprocessing.active_children ()

返回当前进程存活的子进程的列表。

调用该方法有“等待”已经结束的进程的副作用。
@end deffn

@geindex cpu_count() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing cpu_count}@anchor{974}
@deffn {函数} multiprocessing.cpu_count ()

返回系统的CPU数量。

该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由 @code{len(os.sched_getaffinity(0))} 方法获得。

当 CPU 的数量无法确定时，会引发 @ref{70e,,NotImplementedError} 。


@subsubheading 参见


@ref{973,,os.cpu_count()}

@end deffn

@geindex current_process() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing current_process}@anchor{2536}
@deffn {函数} multiprocessing.current_process ()

返回与当前进程相对应的 @ref{4c1,,Process} 对象。

和 @ref{24c6,,threading.current_thread()} 相同。
@end deffn

@geindex parent_process() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing parent_process}@anchor{2537}
@deffn {函数} multiprocessing.parent_process ()

返回父进程  @ref{4c1,,Process}  对象，和父进程调用 @ref{2536,,current_process()} 返回的对象一样。如果一个进程已经是主进程， @code{parent_process} 会返回 @code{None}.


3.8 新版功能.

@end deffn

@geindex freeze_support() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing freeze_support}@anchor{2538}
@deffn {函数} multiprocessing.freeze_support ()

为使用了 @ref{b7,,multiprocessing}  的程序，提供冻结以产生 Windows 可执行文件的支持。(在 @strong{py2exe}, @strong{PyInstaller} 和 @strong{cx_Freeze} 上测试通过)

需要在 main 模块的 @code{if __name__ == '__main__'} 该行之后马上调用该函数。例如：

@example
from multiprocessing import Process, freeze_support

def f():
    print('hello world!')

if __name__ == '__main__':
    freeze_support()
    Process(target=f).start()
@end example

如果没有调用  @code{freeze_support()} 在尝试运行被冻结的可执行文件时会抛出 @ref{3e4,,RuntimeError} 异常。

对  @code{freeze_support()} 的调用在非 Windows 平台上是无效的。如果该模块在 Windows 平台的 Python 解释器中正常运行 (该程序没有被冻结)， 调用`@w{`}freeze_support()`@w{`} 也是无效的。
@end deffn

@geindex get_all_start_methods() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing get_all_start_methods}@anchor{96b}
@deffn {函数} multiprocessing.get_all_start_methods ()

返回支持的启动方法的列表，该列表的首项即为默认选项。可能的启动方法有  @code{'fork'} ， @code{'spawn'} 和`@w{`}'forkserver'`@w{`} 。在 Windows 中，只有  @code{'spawn'} 是可用的。 Unix 平台总是支持 @code{'fork'} 和 @code{'spawn'} ，且 @code{'fork'} 是默认值。


3.4 新版功能.

@end deffn

@geindex get_context() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing get_context}@anchor{96e}
@deffn {函数} multiprocessing.get_context (method=None)

返回一个 Context 对象。该对象具有和 @ref{b7,,multiprocessing} 模块相同的API。

如果 @emph{method} 设置成  @code{None}  那么将返回默认上下文对象。否则  @emph{method}  应该是 @code{'fork'}, @code{'spawn'}, @code{'forkserver'} 。 如果指定的启动方法不存在，将抛出  @ref{16d,,ValueError}  异常。


3.4 新版功能.

@end deffn

@geindex get_start_method() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing get_start_method}@anchor{96c}
@deffn {函数} multiprocessing.get_start_method (allow_none=False)

返回启动进程时使用的启动方法名。

如果启动方法已经固定，并且   @emph{allow_none} 被设置成 False ，那么启动方法将被固定为默认的启动方法，并且返回其方法名。如果启动方法没有设定，并且 @emph{allow_none} 被设置成 True ，那么将返回  @code{None}  。

返回值将为  @code{'fork'} ,  @code{'spawn'} , @code{'forkserver'} 或者 @code{None} 。  @code{'fork'} 是 Unix 的默认值， @code{'spawn'} 是 Windows 和 macOS 的默认值。
@end deffn


在 3.8 版更改: 对于 macOS，@emph{spawn} 启动方式是默认方式。 因为 @emph{fork} 可能导致subprocess崩溃，被认为是不安全的，查看 bpo-33725@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=33725} 。


3.4 新版功能.



@geindex set_executable() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing set_executable}@anchor{2539}
@deffn {函数} multiprocessing.set_executable (executable)

设置在启动子进程时使用的 Python 解释器路径。 ( 默认使用  @ref{3a5,,sys.executable}  ) 嵌入式编程人员可能需要这样做：

@example
set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
@end example

以使他们可以创建子进程。


在 3.4 版更改: 现在在 Unix 平台上使用  @code{'spawn'}  启动方法时支持调用该方法。

@end deffn

@geindex set_start_method() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing set_start_method}@anchor{96d}
@deffn {函数} multiprocessing.set_start_method (method)

设置启动子进程的方法。 @emph{method}  可以是  @code{'fork'} ,  @code{'spawn'}  或者 @code{'forkserver'}  。

注意这最多只能调用一次，并且需要藏在 main 模块中，由  @code{if __name__ == '__main__'} 进行保护。


3.4 新版功能.

@end deffn

@cartouche
@quotation 注解 
@ref{b7,,multiprocessing}   并没有包含类似  @ref{24c5,,threading.active_count()} , @ref{fdb,,threading.enumerate()} ,  @ref{24c7,,threading.settrace()} , @ref{24c8,,threading.setprofile()}, @ref{b8f,,threading.Timer} ,  或者 @ref{f57,,threading.local}  的方法和类。
@end quotation
@end cartouche

@node 连接（Connection）对象,同步原语,杂项<3>,参考
@anchor{library/multiprocessing connection-objects}@anchor{253a}
@subsubsection 连接（Connection）对象


Connection 对象允许收发可以序列化的对象或字符串。它们可以看作面向消息的连接套接字。

通常使用  @ref{2501,,Pipe}   创建 Connection 对象。详见 ：  @ref{253b,,监听器及客户端}.

@geindex Connection (multiprocessing.connection 中的类)
@anchor{library/multiprocessing multiprocessing connection Connection}@anchor{252b}
@deffn {类} multiprocessing.connection.Connection

@geindex send() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection send}@anchor{253c}
@deffn {方法} send (obj)

将一个对象发送到连接的另一端，可以用  @ref{253d,,recv()}  读取。

发送的对象必须是可以序列化的，过大的对象 (  接近 32MiB+ ，这个值取决于操作系统 ) 有可能引发   @ref{16d,,ValueError}   异常。
@end deffn

@geindex recv() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection recv}@anchor{253d}
@deffn {方法} recv ()

返回一个由另一端使用 @ref{253c,,send()} 发送的对象。该方法会一直阻塞直到接收到对象。 如果对端关闭了连接或者没有东西可接收，将抛出   @ref{d3c,,EOFError}  异常。
@end deffn

@geindex fileno() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection fileno}@anchor{253e}
@deffn {方法} fileno ()

返回由连接对象使用的描述符或者句柄。
@end deffn

@geindex close() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection close}@anchor{253f}
@deffn {方法} close ()

关闭连接对象。

当连接对象被垃圾回收时会自动调用。
@end deffn

@geindex poll() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection poll}@anchor{2540}
@deffn {方法} poll ([timeout])

返回连接对象中是否有可以读取的数据。

如果未指定  @emph{timeout} ，此方法会马上返回。如果  @emph{timeout} 是一个数字，则指定了最大阻塞的秒数。如果  @emph{timeout} 是   @code{None}  ，那么将一直等待，不会超时。

注意通过使用  @ref{b0a,,multiprocessing.connection.wait()}   可以一次轮询多个连接对象。
@end deffn

@geindex send_bytes() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection send_bytes}@anchor{2541}
@deffn {方法} send_bytes (buffer[, offset[, size]])

从一个  @ref{6e9,,bytes-like object}   （字节类对象）对象中取出字节数组并作为一条完整消息发送。

如果由  @emph{offset}  给定了在 @emph{buffer} 中读取数据的位置。 如果给定了 @emph{size} ，那么将会从缓冲区中读取多个字节。 过大的缓冲区 ( 接近 32MiB+ ，此值依赖于操作系统 ) 有可能引发   @ref{16d,,ValueError}  异常。
@end deffn

@geindex recv_bytes() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection recv_bytes}@anchor{2542}
@deffn {方法} recv_bytes ([maxlength])

以字符串形式返回一条从连接对象另一端发送过来的字节数据。此方法在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有数据可读取，将抛出  @ref{d3c,,EOFError}  异常。

如果给定了  @emph{maxlength} 并且消息长于  @emph{maxlength} 那么将抛出 @ref{30b,,OSError} 并且该连接对象将不再可读。


在 3.3 版更改: 曾经该函数抛出 @ref{a7c,,IOError}  ，现在这是 @ref{30b,,OSError} 的别名。

@end deffn

@geindex recv_bytes_into() (multiprocessing.connection.Connection 方法)
@anchor{library/multiprocessing multiprocessing connection Connection recv_bytes_into}@anchor{2543}
@deffn {方法} recv_bytes_into (buffer[, offset])

将一条完整的字节数据消息读入  @emph{buffer}  中并返回消息的字节数。 此方法在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有数据可读取，将抛出  @ref{d3c,,EOFError}  异常。

@emph{buffer} must be a writable @ref{6e9,,bytes-like object}.  If
@emph{offset} is given then the message will be written into the buffer from
that position.  Offset must be a non-negative integer less than the
length of @emph{buffer} (in bytes).

如果缓冲区太小，则将引发  @code{BufferTooShort}  异常，并且完整的消息将会存放在异常实例      @code{e}  的 @code{e.args[0]}  中。
@end deffn


在 3.3 版更改: 现在连接对象自身可以通过 @ref{253c,,Connection.send()}   和  @ref{253d,,Connection.recv()}  在进程之间传递。



3.3 新版功能: 连接对象现已支持上下文管理协议 -- 参见 see @ref{15f5,,上下文管理器类型}  。 @ref{1843,,__enter__()}   返回连接对象，   @ref{1845,,__exit__()}   会调用  @ref{253f,,close()}  。

@end deffn

例如:

@example
>>> from multiprocessing import Pipe
>>> a, b = Pipe()
>>> a.send([1, 'hello', None])
>>> b.recv()
[1, 'hello', None]
>>> b.send_bytes(b'thank you')
>>> a.recv_bytes()
b'thank you'
>>> import array
>>> arr1 = array.array('i', range(5))
>>> arr2 = array.array('i', [0] * 10)
>>> a.send_bytes(arr1)
>>> count = b.recv_bytes_into(arr2)
>>> assert count == len(arr1) * arr1.itemsize
>>> arr2
array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])
@end example
@anchor{library/multiprocessing multiprocessing-recv-pickle-security}@anchor{2544}
@cartouche
@quotation 警告 
@ref{253d,,Connection.recv()} 方法会自动解封它收到的数据，除非你能够信任发送消息的进程，否则此处可能有安全风险。

因此，  除非连接对象是由 @code{Pipe()} 产生的，否则你应该仅在使用了某种认证手段之后才使用 @ref{253d,,recv()} 和 @ref{253c,,send()} 方法。 参考 @ref{2519,,认证密码}。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
如果一个进程在试图读写管道时被终止了，那么管道中的数据很可能是不完整的，因为此时可能无法确定消息的边界。
@end quotation
@end cartouche

@node 同步原语,共享 ctypes 对象,连接（Connection）对象,参考
@anchor{library/multiprocessing synchronization-primitives}@anchor{2545}
@subsubsection 同步原语


通常来说同步原语在多进程环境中并不像它们在多线程环境中那么必要。参考  @ref{10b,,threading}  模块的文档。

注意可以使用管理器对象创建同步原语，参考 @ref{2524,,管理器} 。

@geindex Barrier (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Barrier}@anchor{250d}
@deffn {类} multiprocessing.Barrier (parties[, action[, timeout]])

类似  @ref{c3a,,threading.Barrier} 的栅栏对象。


3.3 新版功能.

@end deffn

@geindex BoundedSemaphore (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing BoundedSemaphore}@anchor{250a}
@deffn {类} multiprocessing.BoundedSemaphore ([value])

非常类似 @ref{b8d,,threading.BoundedSemaphore}  的有界信号量对象。

一个小小的不同在于，它的  @code{acquire}  方法的第一个参数名是和  @ref{2546,,Lock.acquire()} 一样的 @emph{block} 。

@cartouche
@quotation 注解 
在 macOS 平台上， 该对象于  @ref{2509,,Semaphore}  不同在于  @code{sem_getvalue()} 方法并没有在该平台上实现。
@end quotation
@end cartouche
@end deffn

@geindex Condition (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Condition}@anchor{250b}
@deffn {类} multiprocessing.Condition ([lock])

条件变量：   @ref{b8b,,threading.Condition} 的别名。

指定的 @emph{lock} 参数应该是 @ref{b7,,multiprocessing}  模块中的   @ref{2507,,Lock}   或者  @ref{2508,,RLock} 对象。


在 3.3 版更改: 新增了 @ref{24e2,,wait_for()}  方法。

@end deffn

@geindex Event (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Event}@anchor{250c}
@deffn {类} multiprocessing.Event

A clone of @ref{b8e,,threading.Event}.
@end deffn

@geindex Lock (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Lock}@anchor{2507}
@deffn {类} multiprocessing.Lock

原始锁（非递归锁）对象，类似于   @ref{24d8,,threading.Lock}  。一旦一个进程或者线程拿到了锁，后续的任何其他进程或线程的其他请求都会被阻塞直到锁被释放。任何进程或线程都可以释放锁。除非另有说明，否则 @ref{2507,,multiprocessing.Lock}  用于进程或者线程的概念和行为都和 @ref{24d8,,threading.Lock}  一致。

注意   @ref{2507,,Lock}  实际上是一个工厂函数。它返回由默认上下文初始化的  @code{multiprocessing.synchronize.Lock}  对象。

@ref{2507,,Lock} supports the @ref{66b,,context manager} protocol and thus may be
used in @ref{7e4,,with} statements.

@geindex acquire() (multiprocessing.Lock 方法)
@anchor{library/multiprocessing multiprocessing Lock acquire}@anchor{2546}
@deffn {方法} acquire (block=True, timeout=None)

获得锁，阻塞或非阻塞的。

如果  @emph{block}   参数被设为  @code{True}   ( 默认值 ) ， 对该方法的调用在锁处于释放状态之前都会阻塞，然后将锁设置为锁住状态并返回   @code{True}  。需要注意的是第一个参数名与   @ref{865,,threading.Lock.acquire()}  的不同。

如果 @emph{block} 参数被设置成 @code{False} ，方法的调用将不会阻塞。 如果锁当前处于锁住状态，将返回   @code{False}  ； 否则将锁设置成锁住状态，并返回 @code{True} 。

当  @emph{timeout} 是一个正浮点数时，会在等待锁的过程中最多阻塞等待 @emph{timeout} 秒，当  @emph{timeout} 是负数时，效果和  @emph{timeout} 为0时一样，当  @emph{timeout} 是 @code{None} （默认值）时，等待时间是无限长。需要注意的是，对于 @emph{timeout} 参数是负数和 @code{None} 的情况, 其行为与  @ref{865,,threading.Lock.acquire()} 是不一样的。当 @emph{block} 参数 为 @code{False} 时，  @emph{timeout} 并没有实际用处，会直接忽略。否则，函数会在拿到锁后返回 @code{True} 或者 超时没拿到锁后返回 @code{False} 。
@end deffn

@geindex release() (multiprocessing.Lock 方法)
@anchor{library/multiprocessing multiprocessing Lock release}@anchor{2547}
@deffn {方法} release ()

释放锁，可以在任何进程、线程使用，并不限于锁的拥有者。

当尝试释放一个没有被持有的锁时，会抛出 @ref{16d,,ValueError} 异常，除此之外其行为与 @ref{24d6,,threading.Lock.release()} 一样。
@end deffn
@end deffn

@geindex RLock (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing RLock}@anchor{2508}
@deffn {类} multiprocessing.RLock

递归锁对象: 类似于 @ref{cc2,,threading.RLock} 。递归锁必须由持有线程、进程亲自释放。如果某个进程或者线程拿到了递归锁，这个进程或者线程可以再次拿到这个锁而不需要等待。但是这个进程或者线程的拿锁操作和释放锁操作的次数必须相同。

注意 @ref{2508,,RLock} 是一个工厂函数，调用后返回一个使用默认 context 初始化的 @code{multiprocessing.synchronize.RLock} 实例。

@ref{2508,,RLock} 支持 @ref{66b,,context manager}，所以可在 @ref{7e4,,with} 语句内使用。

@geindex acquire() (multiprocessing.RLock 方法)
@anchor{library/multiprocessing multiprocessing RLock acquire}@anchor{2548}
@deffn {方法} acquire (block=True, timeout=None)

获得锁，阻塞或非阻塞的。

当 @emph{block} 参数设置为 @code{True} 时，会一直阻塞直到锁处于空闲状态（没有被任何进程、线程拥有），除非当前进程或线程已经拥有了这把锁。然后当前进程/线程会持有这把锁（在锁没有其他持有者的情况下），锁内的递归等级加一，并返回 @code{True} . 注意， 这个函数第一个参数的行为和 @ref{866,,threading.RLock.acquire()} 的实现有几个不同点，包括参数名本身。

当 @emph{block} 参数是 @code{False} , 将不会阻塞，如果此时锁被其他进程或者线程持有，当前进程、线程获取锁操作失败，锁的递归等级也不会改变，函数返回 @code{False} ,  如果当前锁已经处于释放状态，则当前进程、线程则会拿到锁，并且锁内的递归等级加一，函数返回 @code{True} 。

@emph{timeout} 参数的使用方法及行为与 @ref{2546,,Lock.acquire()} 一样。但是要注意 @emph{timeout} 的其中一些行为和 @ref{866,,threading.RLock.acquire()} 中实现的行为是不同的。
@end deffn

@geindex release() (multiprocessing.RLock 方法)
@anchor{library/multiprocessing multiprocessing RLock release}@anchor{2549}
@deffn {方法} release ()

释放锁，使锁内的递归等级减一。如果释放后锁内的递归等级降低为0，则会重置锁的状态为释放状态（即没有被任何进程、线程持有），重置后如果有有其他进程和线程在等待这把锁，他们中的一个会获得这个锁而继续运行。如果释放后锁内的递归等级还没到达0，则这个锁仍将保持未释放状态且当前进程和线程仍然是持有者。

只有当前进程或线程是锁的持有者时，才允许调用这个方法。如果当前进程或线程不是这个锁的拥有者，或者这个锁处于已释放的状态(即没有任何拥有者)，调用这个方法会抛出 @ref{241,,AssertionError} 异常。注意这里抛出的异常类型和 @ref{24dc,,threading.RLock.release()} 中实现的行为不一样。
@end deffn
@end deffn

@geindex Semaphore (multiprocessing 中的类)
@anchor{library/multiprocessing multiprocessing Semaphore}@anchor{2509}
@deffn {类} multiprocessing.Semaphore ([value])

一种信号量对象:  类似于  @ref{b8c,,threading.Semaphore}.

一个小小的不同在于，它的  @code{acquire}  方法的第一个参数名是和  @ref{2546,,Lock.acquire()} 一样的 @emph{block} 。
@end deffn

@cartouche
@quotation 注解 
在 macOS 上，不支持  @code{sem_timedwait} ，所以，调用 @code{acquire()} 时如果使用 timeout 参数，会通过循环sleep来模拟这个函数的行为。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
假如信号 SIGINT 是来自于 @code{Ctrl-C} ，并且主线程被 @code{BoundedSemaphore.acquire()}, @ref{2546,,Lock.acquire()}, @ref{2548,,RLock.acquire()}, @code{Semaphore.acquire()}, @code{Condition.acquire()} 或 @code{Condition.wait()} 阻塞，则调用会立即中断同时抛出 @ref{2d3,,KeyboardInterrupt} 异常。

这和 @ref{10b,,threading} 的行为不同，此模块中当执行对应的阻塞调用时，SIGINT 会被忽略。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
这个包的某些功能依赖于宿主机系统的共享信号量的实现，如果系统没有这个特性， @code{multiprocessing.synchronize} 会被禁用，尝试导入这个模块会引发 @ref{16c,,ImportError} 异常，详细信息请查看 bpo-3770@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=3770} 。
@end quotation
@end cartouche

@node 共享 ctypes 对象,管理器,同步原语,参考
@anchor{library/multiprocessing shared-ctypes-objects}@anchor{254a}
@subsubsection 共享 @code{ctypes} 对象


在共享内存上创建可被子进程继承的共享对象时是可行的。

@geindex Value() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing Value}@anchor{2504}
@deffn {函数} multiprocessing.Value (typecode_or_type, *args, lock=True)

返回一个从共享内存上创建的 @ref{2a,,ctypes} 对象。默认情况下返回的对象实际上是经过了同步器包装过的。可以通过 @ref{2504,,Value} 的 @emph{value} 属性访问这个对象本身。

@emph{typecode_or_type} 指明了返回的对象类型: 它可能是一个 ctypes 类型或者  @ref{6,,array}  模块中每个类型对应的单字符长度的字符串。 @emph{*args} 会透传给这个类的构造函数。

如果 @emph{lock} 参数是 @code{True} （默认值）, 将会新建一个递归锁用于同步对于此值的访问操作。 如果 @emph{lock} 是 @ref{2507,,Lock} 或者 @ref{2508,,RLock} 对象，那么这个传入的锁将会用于同步对这个值的访问操作，如果 @emph{lock} 是 @code{False} , 那么对这个对象的访问将没有锁保护，也就是说这个变量不是进程安全的。

诸如 @code{+=} 这类的操作会引发独立的读操作和写操作，也就是说这类操作符并不具有原子性。所以，如果你想让递增共享变量的操作具有原子性，仅仅以这样的方式并不能达到要求:

@example
counter.value += 1
@end example

共享对象内部关联的锁是递归锁(默认情况下就是)的情况下， 你可以采用这种方式

@example
with counter.get_lock():
    counter.value += 1
@end example

注意 @emph{lock} 只能是命名参数。
@end deffn

@geindex Array() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing Array}@anchor{2505}
@deffn {函数} multiprocessing.Array (typecode_or_type, size_or_initializer, *, lock=True)

从共享内存中申请并返回一个具有ctypes类型的数组对象。默认情况下返回值实际上是被同步器包装过的数组对象。

@emph{typecode_or_type} 指明了返回的数组中的元素类型: 它可能是一个 ctypes 类型或者  @ref{6,,array} 模块中每个类型对应的单字符长度的字符串。 如果 @emph{size_or_initializer} 是一个整数，那就会当做数组的长度，并且整个数组的内存会初始化为0。否则，如果  @emph{size_or_initializer} 会被当成一个序列用于初始化数组中的每一个元素，并且会根据元素个数自动判断数组的长度。

如果 @emph{lock} 为 @code{True} (默认值) 则将创建一个新的锁对象用于同步对值的访问。 如果 @emph{lock} 为一个 @ref{2507,,Lock} 或 @ref{2508,,RLock} 对象则该对象将被用于同步对值的访问。 如果 @emph{lock} 为 @code{False} 则对返回对象的访问将不会自动得到锁的保护，也就是说它不是“进程安全的”。

请注意 @emph{lock} 是一个仅限关键字参数。

请注意 @ref{2437,,ctypes.c_char} 的数组具有 @emph{value} 和 @emph{raw} 属性，允许被用来保存和提取字符串。
@end deffn

@menu
* multiprocessing.sharedctypes 模块: multiprocessing sharedctypes 模块. 

@end menu

@node multiprocessing sharedctypes 模块,,,共享 ctypes 对象
@anchor{library/multiprocessing module-multiprocessing sharedctypes}@anchor{bd}@anchor{library/multiprocessing the-multiprocessing-sharedctypes-module}@anchor{254b}
@subsubsection @code{multiprocessing.sharedctypes} 模块


@geindex multiprocessing.sharedctypes (模块)

@ref{bd,,multiprocessing.sharedctypes} 模块提供了一些函数，用于分配来自共享内存的、可被子进程继承的 @ref{2a,,ctypes} 对象。

@cartouche
@quotation 注解 
虽然可以将指针存储在共享内存中，但请记住它所引用的是特定进程地址空间中的位置。 而且，指针很可能在第二个进程的上下文中无效，尝试从第二个进程对指针进行解引用可能会导致崩溃。
@end quotation
@end cartouche

@geindex RawArray() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes RawArray}@anchor{254c}
@deffn {函数} multiprocessing.sharedctypes.RawArray (typecode_or_type, size_or_initializer)

从共享内存中申请并返回一个 ctypes 数组。

@emph{typecode_or_type} 指明了返回的数组中的元素类型: 它可能是一个 ctypes 类型或者  @ref{6,,array} 模块中使用的类型字符。 如果 @emph{size_or_initializer} 是一个整数，那就会当做数组的长度，并且整个数组的内存会初始化为0。否则，如果  @emph{size_or_initializer} 会被当成一个序列用于初始化数组中的每一个元素，并且会根据元素个数自动判断数组的长度。

注意对元素的访问、赋值操作可能是非原子操作 - 使用 @ref{254d,,Array()} , 从而借助其中的锁保证操作的原子性。
@end deffn

@geindex RawValue() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes RawValue}@anchor{254e}
@deffn {函数} multiprocessing.sharedctypes.RawValue (typecode_or_type, *args)

从共享内存中申请并返回一个 ctypes 对象。

@emph{typecode_or_type} 指明了返回的对象类型: 它可能是一个 ctypes 类型或者  @ref{6,,array}  模块中每个类型对应的单字符长度的字符串。 @emph{*args} 会透传给这个类的构造函数。

注意对 value 的访问、赋值操作可能是非原子操作 - 使用 @ref{254f,,Value()} ，从而借助其中的锁保证操作的原子性。

请注意 @ref{2437,,ctypes.c_char} 的数组具有 @emph{value} 和 @emph{raw} 属性，允许被用来保存和提取字符串 - 请查看 @ref{2a,,ctypes} 文档。
@end deffn

@geindex Array() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes Array}@anchor{254d}
@deffn {函数} multiprocessing.sharedctypes.Array (typecode_or_type, size_or_initializer, *, lock=True)

返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对象，这取决于 @emph{lock} 参数的值，除此之外，和 @ref{254c,,RawArray()} 一样。

如果 @emph{lock} 为 @code{True} (默认值) 则将创建一个新的锁对象用于同步对值的访问。 如果 @emph{lock} 为一个 @code{Lock} 或 @code{RLock} 对象则该对象将被用于同步对值的访问。 如果 @emph{lock} 为 @code{False} 则对返回对象的访问将不会自动得到锁的保护，也就是说它不是“进程安全的”。

注意 @emph{lock} 只能是命名参数。
@end deffn

@geindex Value() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes Value}@anchor{254f}
@deffn {函数} multiprocessing.sharedctypes.Value (typecode_or_type, *args, lock=True)

返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对象，这取决于 @emph{lock} 参数的值，除此之外，和 @code{RawArray()} 一样。

如果 @emph{lock} 为 @code{True} (默认值) 则将创建一个新的锁对象用于同步对值的访问。 如果 @emph{lock} 为一个 @code{Lock} 或 @code{RLock} 对象则该对象将被用于同步对值的访问。 如果 @emph{lock} 为 @code{False} 则对返回对象的访问将不会自动得到锁的保护，也就是说它不是“进程安全的”。

注意 @emph{lock} 只能是命名参数。
@end deffn

@geindex copy() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes copy}@anchor{2550}
@deffn {函数} multiprocessing.sharedctypes.copy (obj)

从共享内存中申请一片空间将 ctypes 对象 @emph{obj} 过来，然后返回一个新的 ctypes 对象。
@end deffn

@geindex synchronized() (在 multiprocessing.sharedctypes 模块中)
@anchor{library/multiprocessing multiprocessing sharedctypes synchronized}@anchor{812}
@deffn {函数} multiprocessing.sharedctypes.synchronized (obj[, lock])

将一个 ctypes 对象包装为进程安全的对象并返回，使用 @emph{lock} 同步对于它的操作。如果 @emph{lock} 是 @code{None} (默认值) ，则会自动创建一个 @ref{2508,,multiprocessing.RLock} 对象。

同步器包装后的对象会在原有对象基础上额外增加两个方法: @code{get_obj()} 返回被包装的对象，  @code{get_lock()} 返回内部用于同步的锁。

需要注意的是，访问包装后的ctypes对象会比直接访问原来的纯 ctypes 对象慢得多。


在 3.5 版更改: 同步器包装后的对象支持 @ref{66b,,context manager} 协议。

@end deffn

下面的表格对比了创建普通ctypes对象和基于共享内存上创建共享ctypes对象的语法。（表格中的 @code{MyStruct} 是 @ref{2455,,ctypes.Structure} 的子类）


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

ctypes

@tab

使用类型的共享ctypes

@tab

使用 typecode 的共享 ctypes

@item

c_double(2.4)

@tab

RawValue(c_double, 2.4)

@tab

RawValue('d', 2.4)

@item

MyStruct(4, 6)

@tab

RawValue(MyStruct, 4, 6)

@tab

@item

(c_short * 7)()

@tab

RawArray(c_short, 7)

@tab

RawArray('h', 7)

@item

(c_int * 3)(9, 2, 8)

@tab

RawArray(c_int, (9, 2, 8))

@tab

RawArray('i', (9, 2, 8))

@end multitable


下面是一个在子进程中修改多个ctypes对象的例子。

@example
from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

def modify(n, x, s, A):
    n.value **= 2
    x.value **= 2
    s.value = s.value.upper()
    for a in A:
        a.x **= 2
        a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
    x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', b'hello world', lock=lock)
    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n, x, s, A))
    p.start()
    p.join()

    print(n.value)
    print(x.value)
    print(s.value)
    print([(a.x, a.y) for a in A])
@end example

输出如下

@example
49
0.1111111111111111
HELLO WORLD
[(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
@end example

@node 管理器,代理对象,共享 ctypes 对象,参考
@anchor{library/multiprocessing managers}@anchor{2551}@anchor{library/multiprocessing multiprocessing-managers}@anchor{2524}
@subsubsection 管理器


管理器提供了一种创建共享数据的方法，从而可以在不同进程中共享，甚至可以通过网络跨机器共享数据。管理器维护一个用于管理 @emph{共享对象} 的服务。其他进程可以通过代理访问这些共享对象。

@geindex multiprocessing.Manager() (內置函数)
@anchor{library/multiprocessing multiprocessing Manager}@anchor{668}
@deffn {函数} multiprocessing.Manager ()

返回一个已启动的 @ref{2552,,SyncManager} 管理器对象，这个对象可以用于在不同进程中共享数据。返回的管理器对象对应了一个已经启动的子进程，并且拥有一系列方法可以用于创建共享对象、返回对应的代理。
@end deffn
@anchor{library/multiprocessing module-multiprocessing managers}@anchor{ba}
@geindex multiprocessing.managers (模块)

当管理器被垃圾回收或者父进程退出时，管理器进程会立即退出。管理器类定义在 @ref{ba,,multiprocessing.managers} 模块:

@geindex BaseManager (multiprocessing.managers 中的类)
@anchor{library/multiprocessing multiprocessing managers BaseManager}@anchor{2553}
@deffn {类} multiprocessing.managers.BaseManager ([address[, authkey]])

创建一个 BaseManager 对象。

一旦创建，应该及时调用 @ref{2554,,start()} 或者  @code{get_server().serve_forever()} 以确保管理器对象对应的管理进程已经启动。

@emph{address} 是管理器服务进程监听的地址。如果 @emph{address} 是 @code{None} ,则允许和任意主机的请求建立连接。

@emph{authkey} 是认证标识，用于检查连接服务进程的请求合法性。如果 @emph{authkey} 是 @code{None}, 则会使用 @code{current_process().authkey} , 否则，就使用 @emph{authkey} , 需要保证它必须是 byte 类型的字符串。

@geindex start() (multiprocessing.managers.BaseManager 方法)
@anchor{library/multiprocessing multiprocessing managers BaseManager start}@anchor{2554}
@deffn {方法} start ([initializer[, initargs]])

为管理器开启一个子进程，如果 @emph{initializer} 不是 @code{None} , 子进程在启动时将会调用  @code{initializer(*initargs)} 。
@end deffn

@geindex get_server() (multiprocessing.managers.BaseManager 方法)
@anchor{library/multiprocessing multiprocessing managers BaseManager get_server}@anchor{2555}
@deffn {方法} get_server ()

返回一个  @code{Server}  对象，它是管理器在后台控制的真实的服务。 @code{Server}  对象拥有 @code{serve_forever()} 方法。

@example
>>> from multiprocessing.managers import BaseManager
>>> manager = BaseManager(address=('@w{'}, 50000), authkey=b'abc')
>>> server = manager.get_server()
>>> server.serve_forever()
@end example

@code{Server} 额外拥有一个 @ref{2556,,address} 属性。
@end deffn

@geindex connect() (multiprocessing.managers.BaseManager 方法)
@anchor{library/multiprocessing multiprocessing managers BaseManager connect}@anchor{2557}
@deffn {方法} connect ()

将本地管理器对象连接到一个远程管理器进程:

@example
>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
>>> m.connect()
@end example
@end deffn

@geindex shutdown() (multiprocessing.managers.BaseManager 方法)
@anchor{library/multiprocessing multiprocessing managers BaseManager shutdown}@anchor{2558}
@deffn {方法} shutdown ()

停止管理器的进程。这个方法只能用于已经使用 @ref{2554,,start()} 启动的服务进程。

它可以被多次调用。
@end deffn

@geindex register() (multiprocessing.managers.BaseManager 方法)
@anchor{library/multiprocessing multiprocessing managers BaseManager register}@anchor{2559}
@deffn {方法} register (typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])

一个 classmethod，可以将一个类型或者可调用对象注册到管理器类。

@emph{typeid} 是一种 "类型标识符"，用于唯一表示某种共享对象类型，必须是一个字符串。

@emph{callable} 是一个用来为此类型标识符创建对象的可调用对象。如果一个管理器实例将使用 @ref{2557,,connect()} 方法连接到服务器，或者 @emph{create_method} 参数为 @code{False}，那么这里可留下 @code{None}。

@emph{proxytype} 是  @ref{255a,,BaseProxy}  的子类，可以根据 @emph{typeid} 为共享对象创建一个代理，如果是 @code{None} , 则会自动创建一个代理类。

@emph{exposed} 是一个函数名组成的序列，用来指明只有这些方法可以使用 @ref{255b,,BaseProxy._callmethod()} 代理。(如果 @emph{exposed} 是 @code{None}, 则会在 @code{proxytype._exposed_} 存在的情况下转而使用它) 当暴露的方法列表没有指定的时候，共享对象的所有 “公共方法” 都会被代理。（这里的“公共方法”是指所有拥有 @ref{158f,,__call__()} 方法并且不是以 @code{'_'} 开头的属性）

@emph{method_to_typeid} 是一个映射，用来指定那些应该返回代理对象的暴露方法所返回的类型。（如果 @emph{method_to_typeid} 是 @code{None}, 则 @code{proxytype._method_to_typeid_} 会在存在的情况下被使用）如果方法名称不在这个映射中或者映射是 @code{None} ,则方法返回的对象会是一个值拷贝。

@emph{create_method} 指明，是否要创建一个以 @emph{typeid} 命名并返回一个代理对象的方法，这个函数会被服务进程用于创建共享对象，默认为 @code{True} 。
@end deffn

@ref{2553,,BaseManager} 实例也有一个只读属性。

@geindex address (multiprocessing.managers.BaseManager 属性)
@anchor{library/multiprocessing multiprocessing managers BaseManager address}@anchor{2556}
@deffn {属性} address

管理器所用的地址。
@end deffn


在 3.3 版更改: 管理器对象支持上下文管理协议 - 查看 @ref{15f5,,上下文管理器类型} 。@ref{1843,,__enter__()} 启动服务进程（如果它还没有启动）并且返回管理器对象， @ref{1845,,__exit__()} 会调用 @ref{2558,,shutdown()} 。

在之前的版本中，如果管理器服务进程没有启动， @ref{1843,,__enter__()} 不会负责启动它。

@end deffn

@geindex SyncManager (multiprocessing.managers 中的类)
@anchor{library/multiprocessing multiprocessing managers SyncManager}@anchor{2552}
@deffn {类} multiprocessing.managers.SyncManager

@ref{2553,,BaseManager} 的子类，可用于进程的同步。这个类型的对象使用 @ref{668,,multiprocessing.Manager()} 创建。

它拥有一系列方法，可以为大部分常用数据类型创建并返回 @ref{667,,代理对象} 代理，用于进程间同步。甚至包括共享列表和字典。

@geindex Barrier() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Barrier}@anchor{255c}
@deffn {方法} Barrier (parties[, action[, timeout]])

创建一个共享的 @ref{c3a,,threading.Barrier} 对象并返回它的代理。


3.3 新版功能.

@end deffn

@geindex BoundedSemaphore() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager BoundedSemaphore}@anchor{255d}
@deffn {方法} BoundedSemaphore ([value])

创建一个共享的 @ref{b8d,,threading.BoundedSemaphore} 对象并返回它的代理。
@end deffn

@geindex Condition() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Condition}@anchor{255e}
@deffn {方法} Condition ([lock])

创建一个共享的 @ref{b8b,,threading.Condition} 对象并返回它的代理。

如果提供了 @emph{lock} 参数，那它必须是 @ref{24d8,,threading.Lock} 或 @ref{cc2,,threading.RLock} 的代理对象。


在 3.3 版更改: 新增了 @ref{24e2,,wait_for()}  方法。

@end deffn

@geindex Event() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Event}@anchor{255f}
@deffn {方法} Event ()

创建一个共享的 @ref{b8e,,threading.Event} 对象并返回它的代理。
@end deffn

@geindex Lock() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Lock}@anchor{2560}
@deffn {方法} Lock ()

创建一个共享的 @ref{24d8,,threading.Lock} 对象并返回它的代理。
@end deffn

@geindex Namespace() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Namespace}@anchor{2561}
@deffn {方法} Namespace ()

创建一个共享的 @ref{2506,,Namespace} 对象并返回它的代理。
@end deffn

@geindex Queue() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Queue}@anchor{2562}
@deffn {方法} Queue ([maxsize])

创建一个共享的 @ref{de6,,queue.Queue} 对象并返回它的代理。
@end deffn

@geindex RLock() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager RLock}@anchor{2563}
@deffn {方法} RLock ()

创建一个共享的 @ref{cc2,,threading.RLock} 对象并返回它的代理。
@end deffn

@geindex Semaphore() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Semaphore}@anchor{2564}
@deffn {方法} Semaphore ([value])

创建一个共享的 @ref{b8c,,threading.Semaphore} 对象并返回它的代理。
@end deffn

@geindex Array() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Array}@anchor{2565}
@deffn {方法} Array (typecode, sequence)

创建一个数组并返回它的代理。
@end deffn

@geindex Value() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager Value}@anchor{2566}
@deffn {方法} Value (typecode, value)

创建一个具有可写 @code{value} 属性的对象并返回它的代理。
@end deffn

@geindex dict() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager dict}@anchor{2567}
@deffn {方法} dict ()

@deffnx {方法} dict (mapping)

@deffnx {方法} dict (sequence)

创建一个共享的 @ref{164,,dict} 对象并返回它的代理。
@end deffn

@geindex list() (multiprocessing.managers.SyncManager 方法)
@anchor{library/multiprocessing multiprocessing managers SyncManager list}@anchor{2568}
@deffn {方法} list ()

@deffnx {方法} list (sequence)

创建一个共享的 @ref{1f9,,list} 对象并返回它的代理。
@end deffn


在 3.6 版更改: 共享对象能够嵌套。例如, 共享的容器对象如共享列表，可以包含另一个共享对象，他们全都会在 @ref{2552,,SyncManager} 中进行管理和同步。

@end deffn

@geindex Namespace (multiprocessing.managers 中的类)
@anchor{library/multiprocessing multiprocessing managers Namespace}@anchor{2506}
@deffn {类} multiprocessing.managers.Namespace

一个可以注册到 @ref{2552,,SyncManager} 的类型。

命名空间对象没有公共方法，但是拥有可写的属性。直接print会显示所有属性的值。

值得一提的是，当对命名空间对象使用代理的时候，访问所有名称以 @code{'_'} 开头的属性都只是代理器上的属性，而不是命名空间对象的属性。

@example
>>> manager = multiprocessing.Manager()
>>> Global = manager.Namespace()
>>> Global.x = 10
>>> Global.y = 'hello'
>>> Global._z = 12.3    # this is an attribute of the proxy
>>> print(Global)
Namespace(x=10, y='hello')
@end example
@end deffn

@menu
* 自定义管理器:: 
* 使用远程管理器:: 

@end menu

@node 自定义管理器,使用远程管理器,,管理器
@anchor{library/multiprocessing customized-managers}@anchor{2569}
@subsubsection 自定义管理器


要创建一个自定义的管理器，需要新建一个 @ref{2553,,BaseManager} 的子类，然后使用这个管理器类上的 @ref{2559,,register()} 类方法将新类型或者可调用方法注册上去。例如:

@example
from multiprocessing.managers import BaseManager

class MathsClass:
    def add(self, x, y):
        return x + y
    def mul(self, x, y):
        return x * y

class MyManager(BaseManager):
    pass

MyManager.register('Maths', MathsClass)

if __name__ == '__main__':
    with MyManager() as manager:
        maths = manager.Maths()
        print(maths.add(4, 3))         # prints 7
        print(maths.mul(7, 8))         # prints 56
@end example

@node 使用远程管理器,,自定义管理器,管理器
@anchor{library/multiprocessing using-a-remote-manager}@anchor{256a}
@subsubsection 使用远程管理器


可以将管理器服务运行在一台机器上，然后使用客户端从其他机器上访问。(假设它们的防火墙允许)

运行下面的代码可以启动一个服务，此付包含了一个共享队列，允许远程客户端访问:

@example
>>> from multiprocessing.managers import BaseManager
>>> from queue import Queue
>>> queue = Queue()
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue', callable=lambda:queue)
>>> m = QueueManager(address=('@w{'}, 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()
@end example

远程客户端可以通过下面的方式访问服务:

@example
>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.put('hello')
@end example

也可以通过下面的方式:

@example
>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.get()
'hello'
@end example

本地进程也可以访问这个队列，利用上面的客户端代码通过远程方式访问:

@example
>>> from multiprocessing import Process, Queue
>>> from multiprocessing.managers import BaseManager
>>> class Worker(Process):
...     def __init__(self, q):
...         self.q = q
...         super().__init__()
...     def run(self):
...         self.q.put('local hello')
...
>>> queue = Queue()
>>> w = Worker(queue)
>>> w.start()
>>> class QueueManager(BaseManager): pass
...
>>> QueueManager.register('get_queue', callable=lambda: queue)
>>> m = QueueManager(address=('@w{'}, 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()
@end example

@node 代理对象,进程池,管理器,参考
@anchor{library/multiprocessing multiprocessing-proxy-objects}@anchor{667}@anchor{library/multiprocessing proxy-objects}@anchor{256b}
@subsubsection 代理对象


代理是一个 @emph{指向} 其他共享对象的对象，这个对象(很可能)在另外一个进程中。共享对象也可以说是代理 @emph{指涉} 的对象。多个代理对象可能指向同一个指涉对象。

代理对象代理了指涉对象的一系列方法调用(虽然并不是指涉对象的每个方法都有必要被代理)。通过这种方式，代理的使用方法可以和它的指涉对象一样:

@example
>>> from multiprocessing import Manager
>>> manager = Manager()
>>> l = manager.list([i*i for i in range(10)])
>>> print(l)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(repr(l))
<ListProxy object, typeid 'list' at 0x...>
>>> l[4]
16
>>> l[2:5]
[4, 9, 16]
@end example

注意，对代理使用 @ref{206,,str()} 函数会返回指涉对象的字符串表示，但是 @ref{8c3,,repr()} 却会返回代理本身的内部字符串表示。

被代理的对象很重要的一点是必须可以被序列化，这样才能允许他们在进程间传递。因此，指涉对象可以包含 @ref{667,,代理对象} 。这允许管理器中列表、字典或者其他 @ref{667,,代理对象} 对象之间的嵌套。

@example
>>> a = manager.list()
>>> b = manager.list()
>>> a.append(b)         # referent of a now contains referent of b
>>> print(a, b)
[<ListProxy object, typeid 'list' at ...>] []
>>> b.append('hello')
>>> print(a[0], b)
['hello'] ['hello']
@end example

类似地，字典和列表代理也可以相互嵌套:

@example
>>> l_outer = manager.list([ manager.dict() for i in range(2) ])
>>> d_first_inner = l_outer[0]
>>> d_first_inner['a'] = 1
>>> d_first_inner['b'] = 2
>>> l_outer[1]['c'] = 3
>>> l_outer[1]['z'] = 26
>>> print(l_outer[0])
@{'a': 1, 'b': 2@}
>>> print(l_outer[1])
@{'c': 3, 'z': 26@}
@end example

如果指涉对象包含了普通 @ref{1f9,,list} 或 @ref{164,,dict} 对象，对这些内部可变对象的修改不会通过管理器传播，因为代理无法得知被包含的值什么时候被修改了。但是把存放在容器代理中的值本身是会通过管理器传播的（会触发代理对象中的 @code{__setitem__} ）从而有效修改这些对象，所以可以把修改过的值重新赋值给容器代理:

@example
# create a list proxy and append a mutable object (a dictionary)
lproxy = manager.list()
lproxy.append(@{@})
# now mutate the dictionary
d = lproxy[0]
d['a'] = 1
d['b'] = 2
# at this point, the changes to d are not yet synced, but by
# updating the dictionary, the proxy is notified of the change
lproxy[0] = d
@end example

在大多是使用情形下，这种实现方式并不比嵌套 @ref{667,,代理对象} 方便，但是依然演示了对于同步的一种控制级别。

@cartouche
@quotation 注解 
@ref{b7,,multiprocessing} 中的代理类并没有提供任何对于代理值比较的支持。所以，我们会得到如下结果:

@example
>>> manager.list([1,2,3]) == [1,2,3]
False
@end example

当需要比较值的时候，应该替换为使用指涉对象的拷贝。
@end quotation
@end cartouche

@geindex BaseProxy (multiprocessing.managers 中的类)
@anchor{library/multiprocessing multiprocessing managers BaseProxy}@anchor{255a}
@deffn {类} multiprocessing.managers.BaseProxy

代理对象是 @ref{255a,,BaseProxy} 派生类的实例。

@geindex _callmethod() (multiprocessing.managers.BaseProxy 方法)
@anchor{library/multiprocessing multiprocessing managers BaseProxy _callmethod}@anchor{255b}
@deffn {方法} _callmethod (methodname[, args[, kwds]])

调用指涉对象的方法并返回结果。

如果 @code{proxy} 是一个代理且其指涉的是 @code{obj} , 那么下面的表达式:

@example
proxy._callmethod(methodname, args, kwds)
@end example

相当于求取以下表达式的值:

@example
getattr(obj, methodname)(*args, **kwds)
@end example

于管理器进程。

返回结果会是一个值拷贝或者一个新的共享对象的代理 - 见函数 @ref{2559,,BaseManager.register()} 中关于参数 @emph{method_to_typeid} 的文档。

如果这个调用熬出了异常，则这个异常会被 @ref{255b,,_callmethod()} 透传出来。如果是管理器进程本身抛出的一些其他异常，则会被 @ref{255b,,_callmethod()} 转换为 @code{RemoteError} 异常重新抛出。

特别注意，如果 @emph{methodname} 没有 @emph{暴露} 出来，将会引发一个异常。

@ref{255b,,_callmethod()} 的一个使用示例:

@example
>>> l = manager.list(range(10))
>>> l._callmethod('__len__')
10
>>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
[2, 3, 4, 5, 6]
>>> l._callmethod('__getitem__', (20,))          # equivalent to l[20]
Traceback (most recent call last):
...
IndexError: list index out of range
@end example
@end deffn

@geindex _getvalue() (multiprocessing.managers.BaseProxy 方法)
@anchor{library/multiprocessing multiprocessing managers BaseProxy _getvalue}@anchor{256c}
@deffn {方法} _getvalue ()

返回指涉对象的一份拷贝。

如果指涉对象无法序列化，则会抛出一个异常。
@end deffn

@geindex __repr__() (multiprocessing.managers.BaseProxy 方法)
@anchor{library/multiprocessing multiprocessing managers BaseProxy __repr__}@anchor{256d}
@deffn {方法} __repr__ ()

返回代理对象的内部字符串表示。
@end deffn

@geindex __str__() (multiprocessing.managers.BaseProxy 方法)
@anchor{library/multiprocessing multiprocessing managers BaseProxy __str__}@anchor{256e}
@deffn {方法} __str__ ()

返回指涉对象的内部字符串表示。
@end deffn
@end deffn

@menu
* 清理:: 

@end menu

@node 清理,,,代理对象
@anchor{library/multiprocessing cleanup}@anchor{256f}
@subsubsection 清理


代理对象使用了一个弱引用回调函数，当它被垃圾回收时，会将自己从拥有此指涉对象的管理器上反注册，

当共享对象没有被任何代理器引用时，会被管理器进程删除。

@node 进程池,监听器及客户端,代理对象,参考
@anchor{library/multiprocessing module-multiprocessing pool}@anchor{bb}@anchor{library/multiprocessing process-pools}@anchor{2570}
@subsubsection 进程池


@geindex multiprocessing.pool (模块)

可以创建一个进程池，它将使用 @ref{96f,,Pool} 类执行提交给它的任务。

@geindex Pool (multiprocessing.pool 中的类)
@anchor{library/multiprocessing multiprocessing pool Pool}@anchor{96f}
@deffn {类} multiprocessing.pool.Pool ([processes[, initializer[, initargs[, maxtasksperchild[, context]]]]])

一个进程池对象，它控制可以提交作业的工作进程池。它支持带有超时和回调的异步结果，以及一个并行的 map 实现。

@emph{processes} 是要使用的工作进程数目。如果 @emph{processes} 为 @code{None}，则使用 @ref{973,,os.cpu_count()} 返回的值。

如果 @emph{initializer} 不为 @code{None}，则每个工作进程将会在启动时调用 @code{initializer(*initargs)}。

@emph{maxtasksperchild} 是一个工作进程在它退出或被一个新的工作进程代替之前能完成的任务数量，为了释放未使用的资源。默认的 @emph{maxtasksperchild} 是 @code{None}，意味着工作进程寿与池齐。

@emph{context} 可被用于指定启动的工作进程的上下文。通常一个进程池是使用函数 @code{multiprocessing.Pool()} 或者一个上下文对象的 @ref{96f,,Pool()} 方法创建的。在这两种情况下， @emph{context} 都是适当设置的。

注意，进程池对象的方法只有创建它的进程能够调用。

@cartouche
@quotation 警告 
@ref{bb,,multiprocessing.pool} 对象具有需要正确管理的内部资源 （像任何其他资源一样），具体方式是将进程池用作上下文管理器，或者手动调用 @ref{2571,,close()} 和 @ref{2572,,terminate()}。 未做此类操作将导致进程在终结阶段挂起。

请注意依赖垃圾回收器来销毁进程池是 @strong{不正确} 的做法，因为 CPython 并不保证会调用进程池终结程序（请参阅 @ref{a0d,,object.__del__()} 来了解详情）。
@end quotation
@end cartouche


3.2 新版功能: @emph{maxtasksperchild}



3.4 新版功能: @emph{context}


@cartouche
@quotation 注解 
通常来说，@ref{96f,,Pool} 中的 Worker 进程的生命周期和进程池的工作队列一样长。一些其他系统中（如 Apache, mod_wsgi 等）也可以发现另一种模式，他们会让工作进程在完成一些任务后退出，清理、释放资源，然后启动一个新的进程代替旧的工作进程。 @ref{96f,,Pool} 的 @emph{maxtasksperchild} 参数给用户提供了这种能力。
@end quotation
@end cartouche

@geindex apply() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool apply}@anchor{2573}
@deffn {方法} apply (func[, args[, kwds]])

使用 @emph{args} 参数以及 @emph{kwds} 命名参数调用 @emph{func} , 它会返回结果前阻塞。这种情况下，@ref{2574,,apply_async()} 更适合并行化工作。另外 @emph{func} 只会在一个进程池中的一个工作进程中执行。
@end deffn

@geindex apply_async() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool apply_async}@anchor{2574}
@deffn {方法} apply_async (func[, args[, kwds[, callback[, error_callback]]]])

@ref{2573,,apply()} 方法的一个变种，返回一个 @ref{2575,,AsyncResult} 对象。

如果指定了 @emph{callback} , 它必须是一个接受单个参数的可调用对象。当执行成功时， @emph{callback} 会被用于处理执行后的返回结果，否则，调用 @emph{error_callback} 。

如果指定了 @emph{error_callback} , 它必须是一个接受单个参数的可调用对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给 @emph{error_callback} 执行。

回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。
@end deffn

@geindex map() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool map}@anchor{b0f}
@deffn {方法} map (func, iterable[, chunksize])

内置 @ref{cff,,map()} 函数的并行版本 (但它只支持一个 @emph{iterable} 参数，对于多个可迭代对象请参阅 @ref{b0c,,starmap()})。 它会保持阻塞直到获得结果。

这个方法会将可迭代对象分割为许多块，然后提交给进程池。可以将 @emph{chunksize} 设置为一个正整数从而（近似）指定每个块的大小可以。

注意对于很长的迭代对象，可能消耗很多内存。可以考虑使用 @ref{2576,,imap()} 或 @ref{2577,,imap_unordered()} 并且显示指定 @emph{chunksize} 以提升效率。
@end deffn

@geindex map_async() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool map_async}@anchor{b10}
@deffn {方法} map_async (func, iterable[, chunksize[, callback[, error_callback]]])

@ref{b0f,,map()} 方法的一个变种，返回一个 @ref{2575,,AsyncResult} 对象。

如果指定了 @emph{callback} , 它必须是一个接受单个参数的可调用对象。当执行成功时， @emph{callback} 会被用于处理执行后的返回结果，否则，调用 @emph{error_callback} 。

如果指定了 @emph{error_callback} , 它必须是一个接受单个参数的可调用对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给 @emph{error_callback} 执行。

回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。
@end deffn

@geindex imap() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool imap}@anchor{2576}
@deffn {方法} imap (func, iterable[, chunksize])

@ref{b0f,,map()} 的延迟执行版本。

@emph{chunksize} 参数的作用和 @ref{b0f,,map()} 方法的一样。对于很长的迭代器，给 @emph{chunksize} 设置一个很大的值会比默认值 @code{1} @strong{极大} 地加快执行速度。

同样，如果 @emph{chunksize} 是 @code{1} , 那么 @ref{2576,,imap()} 方法所返回的迭代器的 @code{next()} 方法拥有一个可选的 @emph{timeout} 参数： 如果无法在 @emph{timeout} 秒内执行得到结果，则`@w{`}next(timeout)`@w{`} 会抛出 @ref{251e,,multiprocessing.TimeoutError} 异常。
@end deffn

@geindex imap_unordered() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool imap_unordered}@anchor{2577}
@deffn {方法} imap_unordered (func, iterable[, chunksize])

和 @ref{2576,,imap()} 相同，只不过通过迭代器返回的结果是任意的。（当进程池中只有一个工作进程的时候，返回结果的顺序才能认为是"有序"的）
@end deffn

@geindex starmap() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool starmap}@anchor{b0c}
@deffn {方法} starmap (func, iterable[, chunksize])

和 @ref{b0f,,map()} 类似，不过 @emph{iterable} 中的每一项会被解包再作为函数参数。

比如可迭代对象 @code{[(1,2), (3, 4)]} 会转化为等价于 @code{[func(1,2), func(3,4)]} 的调用。


3.3 新版功能.

@end deffn

@geindex starmap_async() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool starmap_async}@anchor{b0d}
@deffn {方法} starmap_async (func, iterable[, chunksize[, callback[, error_callback]]])

相当于 @ref{b0c,,starmap()} 与 @ref{b10,,map_async()} 的结合，迭代 @emph{iterable} 的每一项，解包作为 @emph{func} 的参数并执行，返回用于获取结果的对象。


3.3 新版功能.

@end deffn

@geindex close() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool close}@anchor{2571}
@deffn {方法} close ()

阻止后续任务提交到进程池，当所有任务执行完成后，工作进程会退出。
@end deffn

@geindex terminate() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool terminate}@anchor{2572}
@deffn {方法} terminate ()

不必等待未完成的任务，立即停止工作进程。当进程池对象被垃圾回收时，会立即调用 @ref{2572,,terminate()}。
@end deffn

@geindex join() (multiprocessing.pool.Pool 方法)
@anchor{library/multiprocessing multiprocessing pool Pool join}@anchor{2578}
@deffn {方法} join ()

等待工作进程结束。调用 @ref{2578,,join()} 前必须先调用 @ref{2571,,close()} 或者 @ref{2572,,terminate()} 。
@end deffn


3.3 新版功能: 进程池对象现在支持上下文管理器协议 - 参见 @ref{15f5,,上下文管理器类型} 。@ref{1843,,__enter__()} 返回进程池对象, @ref{1845,,__exit__()} 会调用 @ref{2572,,terminate()} 。

@end deffn

@geindex AsyncResult (multiprocessing.pool 中的类)
@anchor{library/multiprocessing multiprocessing pool AsyncResult}@anchor{2575}
@deffn {类} multiprocessing.pool.AsyncResult

@ref{2574,,Pool.apply_async()} 和 @ref{b10,,Pool.map_async()} 返回对象所属的类。

@geindex get() (multiprocessing.pool.AsyncResult 方法)
@anchor{library/multiprocessing multiprocessing pool AsyncResult get}@anchor{2579}
@deffn {方法} get ([timeout])

用于获取执行结果。如果 @emph{timeout} 不是 @code{None} 并且在 @emph{timeout} 秒内仍然没有执行完得到结果，则抛出 @ref{251e,,multiprocessing.TimeoutError} 异常。如果远程调用发生异常，这个异常会通过 @ref{2579,,get()} 重新抛出。
@end deffn

@geindex wait() (multiprocessing.pool.AsyncResult 方法)
@anchor{library/multiprocessing multiprocessing pool AsyncResult wait}@anchor{257a}
@deffn {方法} wait ([timeout])

阻塞，直到返回结果，或者 @emph{timeout} 秒后超时。
@end deffn

@geindex ready() (multiprocessing.pool.AsyncResult 方法)
@anchor{library/multiprocessing multiprocessing pool AsyncResult ready}@anchor{257b}
@deffn {方法} ready ()

返回执行状态，是否已经完成。
@end deffn

@geindex successful() (multiprocessing.pool.AsyncResult 方法)
@anchor{library/multiprocessing multiprocessing pool AsyncResult successful}@anchor{257c}
@deffn {方法} successful ()

判断调用是否已经完成并且未引发异常。 如果还未获得结果则将引发 @ref{16d,,ValueError}。


在 3.7 版更改: 如果没有执行完，会抛出 @ref{16d,,ValueError}  异常而不是 @ref{241,,AssertionError} 。

@end deffn
@end deffn

下面的例子演示了进程池的用法:

@example
from multiprocessing import Pool
import time

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=4) as pool:         # start 4 worker processes
        result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
        print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow

        print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

        it = pool.imap(f, range(10))
        print(next(it))                     # prints "0"
        print(next(it))                     # prints "1"
        print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow

        result = pool.apply_async(time.sleep, (10,))
        print(result.get(timeout=1))        # raises multiprocessing.TimeoutError
@end example

@node 监听器及客户端,认证密码,进程池,参考
@anchor{library/multiprocessing listeners-and-clients}@anchor{257d}@anchor{library/multiprocessing module-multiprocessing connection}@anchor{b8}@anchor{library/multiprocessing multiprocessing-listeners-clients}@anchor{253b}
@subsubsection 监听器及客户端


@geindex multiprocessing.connection (模块)

通常情况下，进程间通过队列或者 @ref{2501,,Pipe()} 返回的 @ref{252b,,Connection} 传递消息。

不过，@ref{b8,,multiprocessing.connection} 模块其实提供了一些更灵活的特性。最基础的用法是通过它抽象出来的高级API来操作socket或者Windows命名管道。也提供一些高级用法，如通过 @ref{8e,,hmac} 模块来支持 @emph{摘要认证}，以及同时监听多个管道连接。

@geindex deliver_challenge() (在 multiprocessing.connection 模块中)
@anchor{library/multiprocessing multiprocessing connection deliver_challenge}@anchor{257e}
@deffn {函数} multiprocessing.connection.deliver_challenge (connection, authkey)

发送一个随机生成的消息到另一端，并等待回复。

如果收到的回复与使用 @emph{authkey} 作为键生成的信息摘要匹配成功，就会发送一个欢迎信息给管道另一端。否则抛出 @ref{251d,,AuthenticationError} 异常。
@end deffn

@geindex answer_challenge() (在 multiprocessing.connection 模块中)
@anchor{library/multiprocessing multiprocessing connection answer_challenge}@anchor{257f}
@deffn {函数} multiprocessing.connection.answer_challenge (connection, authkey)

接收一条信息，使用 @emph{authkey} 作为键计算信息摘要，然后将摘要发送回去。

如果没有收到欢迎消息，就抛出 @ref{251d,,AuthenticationError} 异常。
@end deffn

@geindex Client() (在 multiprocessing.connection 模块中)
@anchor{library/multiprocessing multiprocessing connection Client}@anchor{2580}
@deffn {函数} multiprocessing.connection.Client (address[, family[, authkey]])

尝试使用 @emph{address} 地址上的监听器建立一个连接，返回 @ref{252b,,Connection} 。

连接的类型取决于 @emph{family} 参数，但是通常可以省略，因为可以通过 @emph{address} 的格式推导出来。(查看 @ref{2581,,地址格式} )

如果提供了 @emph{authkey} 参数并且不是 None，那它必须是一个字符串并且会被当做基于 HMAC 认证的密钥。如果 @emph{authkey} 是None 则不会有认证行为。认证失败抛出 @ref{251d,,AuthenticationError} 异常，请查看 See @ref{2519,,认证密码} 。
@end deffn

@geindex Listener (multiprocessing.connection 中的类)
@anchor{library/multiprocessing multiprocessing connection Listener}@anchor{10b4}
@deffn {类} multiprocessing.connection.Listener ([address[, family[, backlog[, authkey]]]])

可以监听连接请求，是对于绑定套接字或者 Windows 命名管道的封装。

@emph{address} 是监听器对象中的绑定套接字或命名管道使用的地址。

@cartouche
@quotation 注解 
如果使用 '0.0.0.0' 作为监听地址，那么在Windows上这个地址无法建立连接。想要建立一个可连接的端点，应该使用 '127.0.0.1' 。
@end quotation
@end cartouche

@emph{family} 是套接字(或者命名管道)使用的类型。它可以是以下一种:  @code{'AF_INET'} ( TCP 套接字类型), @code{'AF_UNIX'} ( Unix 域套接字) 或者 @code{'AF_PIPE'} ( Windows 命名管道)。其中只有第一个保证各平台可用。如果 @emph{family} 是 @code{None} ,那么 family 会根据 @emph{address} 的格式自动推导出来。如果 @emph{address} 也是 @code{None} , 则取默认值。默认值为可用类型中速度最快的。见 @ref{2581,,地址格式} 。注意，如果 @emph{family} 是 @code{'AF_UNIX'} 而address是`@w{`}None`@w{`} ,套接字会在一个 @ref{1e0c,,tempfile.mkstemp()} 创建的私有临时目录中创建。

如果监听器对象使用了套接字，@emph{backlog} (默认值为1) 会在套接字绑定后传递给它的 @ref{844,,listen()} 方法。

如果提供了 @emph{authkey} 参数并且不是 None，那它必须是一个字符串并且会被当做基于 HMAC 认证的密钥。如果 @emph{authkey} 是None 则不会有认证行为。认证失败抛出 @ref{251d,,AuthenticationError} 异常，请查看 See @ref{2519,,认证密码} 。

@geindex accept() (multiprocessing.connection.Listener 方法)
@anchor{library/multiprocessing multiprocessing connection Listener accept}@anchor{2582}
@deffn {方法} accept ()

接受一个连接并返回一个 @ref{252b,,Connection} 对象，其连接到的监听器对象已绑定套接字或者命名管道。如果已经尝试过认证并且失败了，则会抛出 @ref{251d,,AuthenticationError} 异常。
@end deffn

@geindex close() (multiprocessing.connection.Listener 方法)
@anchor{library/multiprocessing multiprocessing connection Listener close}@anchor{2583}
@deffn {方法} close ()

关闭监听器对象上的绑定套接字或者命名管道。此函数会在监听器被垃圾回收后自动调用。不过仍然建议显式调用函数关闭。
@end deffn

监听器对象拥有下列只读属性:

@geindex address (multiprocessing.connection.Listener 属性)
@anchor{library/multiprocessing multiprocessing connection Listener address}@anchor{2584}
@deffn {属性} address

监听器对象使用的地址。
@end deffn

@geindex last_accepted (multiprocessing.connection.Listener 属性)
@anchor{library/multiprocessing multiprocessing connection Listener last_accepted}@anchor{2585}
@deffn {属性} last_accepted

最后一个连接所使用的地址。如果没有的话就是 @code{None} 。
@end deffn


3.3 新版功能: 监听器对象现在支持了上下文管理协议 - 见 @ref{15f5,,上下文管理器类型} 。 @ref{1843,,__enter__()} 返回一个监听器对象, @ref{1845,,__exit__()} 会调用 @ref{2583,,close()} 。

@end deffn

@geindex wait() (在 multiprocessing.connection 模块中)
@anchor{library/multiprocessing multiprocessing connection wait}@anchor{b0a}
@deffn {函数} multiprocessing.connection.wait (object_list, timeout=None)

一直等待直到 @emph{object_list} 中某个对象处于就绪状态。返回 @emph{object_list} 中处于就绪状态的对象。如果 @emph{timeout} 是一个浮点型，该方法会最多阻塞这么多秒。如果 @emph{timeout} 是 @code{None} ，则会允许阻塞的事件没有限制。timeout为负数的情况下和为0的情况相同。

对于 Unix 和 Windows ，满足下列条件的对象可以出现在 @emph{object_list} 中


@itemize *

@item 
可读的 @ref{252b,,Connection} 对象；

@item 
一个已连接并且可读的 @ref{771,,socket.socket} 对象；或者

@item 
@ref{4c1,,Process} 对象中的 @ref{b0b,,sentinel} 属性。
@end itemize

当一个连接或者套接字对象拥有有效的数据可被读取的时候，或者另一端关闭后，这个对象就处于就绪状态。

@strong{Unix}: @code{wait(object_list, timeout)} 和 @code{select.select(object_list, [], [], timeout)} 几乎相同。差别在于，如果 @ref{770,,select.select()} 被信号中断，它会抛出一个附带错误号为 @code{EINTR} 的 @ref{30b,,OSError} 异常，而 @ref{b0a,,wait()} 不会。

@strong{Windows}: @emph{object_list} 中的元素必须是一个表示为整数的可等待的句柄(按照 Win32 函数 @code{WaitForMultipleObjects()} 的文档中所定义) 或者一个拥有 @code{fileno()} 方法的对象，这个对象返回一个套接字句柄或者管道句柄。（注意管道和套接字两种句柄 @strong{不是} 可等待的句柄）


3.3 新版功能.

@end deffn

@strong{示例}

下面的服务代码创建了一个使用 @code{'secret password'} 作为认证密码的监听器。它会等待连接然后发送一些数据给客户端:

@example
from multiprocessing.connection import Listener
from array import array

address = ('localhost', 6000)     # family is deduced to be 'AF_INET'

with Listener(address, authkey=b'secret password') as listener:
    with listener.accept() as conn:
        print('connection accepted from', listener.last_accepted)

        conn.send([2.25, None, 'junk', float])

        conn.send_bytes(b'hello')

        conn.send_bytes(array('i', [42, 1729]))
@end example

下面的代码连接到服务然后从服务器上j接收一些数据:

@example
from multiprocessing.connection import Client
from array import array

address = ('localhost', 6000)

with Client(address, authkey=b'secret password') as conn:
    print(conn.recv())                  # => [2.25, None, 'junk', float]

    print(conn.recv_bytes())            # => 'hello'

    arr = array('i', [0, 0, 0, 0, 0])
    print(conn.recv_bytes_into(arr))    # => 8
    print(arr)                          # => array('i', [42, 1729, 0, 0, 0])
@end example

下面的代码使用了 @ref{b0a,,wait()} ，以便在同时等待多个进程发来消息。

@example
import time, random
from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait

def foo(w):
    for i in range(10):
        w.send((i, current_process().name))
    w.close()

if __name__ == '__main__':
    readers = []

    for i in range(4):
        r, w = Pipe(duplex=False)
        readers.append(r)
        p = Process(target=foo, args=(w,))
        p.start()
        # We close the writable end of the pipe now to be sure that
        # p is the only process which owns a handle for it.  This
        # ensures that when p closes its handle for the writable end,
        # wait() will promptly report the readable end as being ready.
        w.close()

    while readers:
        for r in wait(readers):
            try:
                msg = r.recv()
            except EOFError:
                readers.remove(r)
            else:
                print(msg)
@end example

@menu
* 地址格式:: 

@end menu

@node 地址格式,,,监听器及客户端
@anchor{library/multiprocessing address-formats}@anchor{2586}@anchor{library/multiprocessing multiprocessing-address-formats}@anchor{2581}
@subsubsection 地址格式



@itemize *

@item 
@code{'AF_INET'} 地址是 @code{(hostname, port)}  形式的元组类型，其中 @emph{hostname} 是一个字符串，@emph{port} 是整数。

@item 
@code{'AF_UNIX'} 地址是文件系统上文件名的字符串。

@item 
@code{'AF_PIPE'} 地址是一个 @code{r'\.\pipe@{PipeName@}'} 形式的字符串。 要使用 @ref{2580,,Client()} 来连接到远程计算机上一个名为 @emph{ServerName} 的命名管道，则应当改用 @code{r'\@emph{ServerName}\pipe@{PipeName@}'} 形式的地址。
@end itemize

注意，使用两个反斜线开头的字符串默认被当做 @code{'AF_PIPE'} 地址而不是 @code{'AF_UNIX'}  。

@node 认证密码,日志<2>,监听器及客户端,参考
@anchor{library/multiprocessing authentication-keys}@anchor{2587}@anchor{library/multiprocessing multiprocessing-auth-keys}@anchor{2519}
@subsubsection 认证密码


当使用 @ref{253d,,Connection.recv} 接收数据时，数据会自动被反序列化。不幸的是，对于一个不可信的数据源发来的数据，反序列化是存在安全风险的。所以 @ref{10b4,,Listener} 和 @ref{2580,,Client()} 之间使用 @ref{8e,,hmac} 模块进行摘要认证。

认证密钥是一个 byte 类型的字符串，可以认为是和密码一样的东西，连接建立好后，双方都会要求另一方证明知道认证密钥。（这个证明过程不会通过连接发送密钥）

如果要求认证但是没有指定认证密钥，则会使用 @code{current_process().authkey} 的返回值 (参见 @ref{4c1,,Process} )。 这个值会被当前进程所创建的任何 @ref{4c1,,Process} 对象自动继承。 这意味着（默认情况下）当一个多进程程序的所有进程在彼此之间建立连接的时候，会共享同一个认证密钥。

@ref{5d4,,os.urandom()} 也可以用来生成合适的认证密钥。

@node 日志<2>,multiprocessing dummy 模块,认证密码,参考
@anchor{library/multiprocessing logging}@anchor{2588}
@subsubsection 日志


当前模块也提供了一些对 logging 的支持。注意， @ref{aa,,logging} 模块本身并没有使用进程间共享的锁，所以来自于多个进程的日志可能（具体取决于使用的日志 handler 类型）相互覆盖或者混杂。

@geindex get_logger() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing get_logger}@anchor{2589}
@deffn {函数} multiprocessing.get_logger ()

返回 @ref{b7,,multiprocessing} 使用的 logger，必要的话会创建一个新的。

如果创建的首个 logger 日志级别为 @code{logging.NOTSET} 并且没有默认 handler。通过这个 logger 打印的消息不会传递到根 logger。

注意在 Windows 上，子进程只会继承父进程 logger 的日志级别 - 对于logger的其他自定义项不会继承。
@end deffn

@geindex log_to_stderr() (在 multiprocessing 模块中)
@anchor{library/multiprocessing multiprocessing log_to_stderr}@anchor{258a}
@deffn {函数} multiprocessing.log_to_stderr (level=None)

此函数会调用 @ref{2589,,get_logger()} 但是会在返回的 logger 上增加一个 handler，将所有输出都使用 @code{'[%(levelname)s/%(processName)s] %(message)s'} 的格式发送到 @ref{1eb,,sys.stderr} 。你可以通过传递一个 @code{level} 参数来修改记录器的 @code{levelname} 。
@end deffn

下面是一个在交互式解释器中打开日志功能的例子:

@example
>>> import multiprocessing, logging
>>> logger = multiprocessing.log_to_stderr()
>>> logger.setLevel(logging.INFO)
>>> logger.warning('doomed')
[WARNING/MainProcess] doomed
>>> m = multiprocessing.Manager()
[INFO/SyncManager-...] child process calling self.run()
[INFO/SyncManager-...] created temp directory /.../pymp-...
[INFO/SyncManager-...] manager serving at '/.../listener-...'
>>> del m
[INFO/MainProcess] sending shutdown message to manager
[INFO/SyncManager-...] manager exiting with exitcode 0
@end example

要查看日志等级的完整列表，见 @ref{aa,,logging} 模块。

@node multiprocessing dummy 模块,,日志<2>,参考
@anchor{library/multiprocessing module-multiprocessing dummy}@anchor{b9}@anchor{library/multiprocessing the-multiprocessing-dummy-module}@anchor{258b}
@subsubsection @code{multiprocessing.dummy} 模块


@geindex multiprocessing.dummy (模块)

@ref{b9,,multiprocessing.dummy} 复制了 @ref{b7,,multiprocessing} 的 API，不过是在 @ref{10b,,threading} 模块之上包装了一层。

特别地，@ref{b9,,multiprocessing.dummy} 所提供的 @code{Pool} 函数会返回一个 @ref{1019,,ThreadPool} 的实例，该类是 @ref{96f,,Pool} 的子类，它支持所有相同的方法调用但会使用一个工作线程池而非工作进程池。

@geindex ThreadPool (multiprocessing.pool 中的类)
@anchor{library/multiprocessing multiprocessing pool ThreadPool}@anchor{1019}
@deffn {类} multiprocessing.pool.ThreadPool ([processes[, initializer[, initargs]]])

一个线程池对象，用来控制可向其提交任务的工作线程池。 @ref{1019,,ThreadPool} 实例与 @ref{96f,,Pool} 实例是完全接口兼容的，并且它们的资源也必须被正确地管理，或者是将线程池作为上下文管理器来使用，或者是通过手动调用 @ref{2571,,close()} 和 @ref{2572,,terminate()}。

@emph{processes} 是要使用的工作线程数目。 如果 @emph{processes} 为 @code{None}，则使用 @ref{973,,os.cpu_count()} 返回的值。

如果 @emph{initializer} 不为 @code{None}，则每个工作进程将会在启动时调用 @code{initializer(*initargs)}。

不同于 @ref{96f,,Pool}，@emph{maxtasksperchild} 和 @emph{context} 不可被提供。

@quotation

@cartouche
@quotation 注解 
@ref{1019,,ThreadPool} 具有与 @ref{96f,,Pool} 相同的接口，它围绕一个进程池进行设计并且先于 @ref{21,,concurrent.futures} 模块的引入。 因此，它继承了一些对于基于线程的池来说没有意义的操作，并且它具有自己的用于表示异步任务状态的类型 @ref{2575,,AsyncResult}，该类型不为任何其他库所知。

用户通常应该倾向于使用 @ref{18c,,concurrent.futures.ThreadPoolExecutor}，它拥有从一开始就围绕线程进行设计的更简单接口，并且返回与许多其他库相兼容的 @ref{c09,,concurrent.futures.Future} 实例，包括 @ref{9,,asyncio} 库。
@end quotation
@end cartouche
@end quotation
@end deffn

@node 编程指导,示例<17>,参考,multiprocessing --- 基于进程的并行
@anchor{library/multiprocessing multiprocessing-programming}@anchor{24fc}@anchor{library/multiprocessing programming-guidelines}@anchor{258c}
@subsubsection 编程指导


使用 @ref{b7,,multiprocessing} 时，应遵循一些指导原则和习惯用法。

@menu
* 所有start方法:: 
* spawn 和 forkserver 启动方式:: 

@end menu

@node 所有start方法,spawn 和 forkserver 启动方式,,编程指导
@anchor{library/multiprocessing all-start-methods}@anchor{258d}
@subsubsection 所有start方法


下面这些适用于所有start方法。

避免共享状态

@quotation

应该尽可能避免在进程间传递大量数据，越少越好。

最好坚持使用队列或者管道进行进程间通信，而不是底层的同步原语。
@end quotation

可序列化

@quotation

保证所代理的方法的参数是可以序列化的。
@end quotation

代理的线程安全性

@quotation

不要在多线程中同时使用一个代理对象，除非你用锁保护它。

（而在不同进程中使用 @emph{相同} 的代理对象却没有问题。）
@end quotation

使用 Join 避免僵尸进程

@quotation

在 Unix 上，如果一个进程执行完成但是没有被 join，就会变成僵尸进程。一般来说，僵尸进程不会很多，因为每次新启动进程（或者 @ref{2535,,active_children()} 被调用）时，所有已执行完成且没有被 join 的进程都会自动被 join，而且对一个执行完的进程调用 @ref{2516,,Process.is_alive} 也会 join 这个进程。尽管如此，对自己启动的进程显式调用 join 依然是最佳实践。
@end quotation

继承优于序列化、反序列化

@quotation

当使用 @emph{spawn} 或者 @emph{forkserver} 的启动方式时，@ref{b7,,multiprocessing}  中的许多类型都必须是可序列化的，这样子进程才能使用它们。但是通常我们都应该避免使用管道和队列发送共享对象到另外一个进程，而是重新组织代码，对于其他进程创建出来的共享对象，让那些需要访问这些对象的子进程可以直接将这些对象从父进程继承过来。
@end quotation

避免杀死进程

@quotation

通过 @ref{251a,,Process.terminate} 停止一个进程很容易导致这个进程正在使用的共享资源（如锁、信号量、管道和队列）损坏或者变得不可用，无法在其他进程中继续使用。

所以，最好只对那些从来不使用共享资源的进程调用 @ref{251a,,Process.terminate} 。
@end quotation

Join 使用队列的进程

@quotation

记住，往队列放入数据的进程会一直等待直到队列中所有项被"feeder" 线程传给底层管道。（子进程可以调用队列的 @ref{2529,,Queue.cancel_join_thread} 方法禁止这种行为）

这意味着，任何使用队列的时候，你都要确保在进程join之前，所有存放到队列中的项将会被其他进程、线程完全消费。否则不能保证这个写过队列的进程可以正常终止。记住非精灵进程会自动 join 。

下面是一个会导致死锁的例子:

@example
from multiprocessing import Process, Queue

def f(q):
    q.put('X' * 1000000)

if __name__ == '__main__':
    queue = Queue()
    p = Process(target=f, args=(queue,))
    p.start()
    p.join()                    # this deadlocks
    obj = queue.get()
@end example

交换最后两行可以修复这个问题（或者直接删掉 @code{p.join()}）。
@end quotation

显式传递资源给子进程

@quotation

在Unix上，使用 @emph{fork} 方式启动的子进程可以使用父进程中全局创建的共享资源。不过，最好是显式将资源对象通过参数的形式传递给子进程。

除了（部分原因）让代码兼容 Windows 以及其他的进程启动方式外，这种形式还保证了在子进程生命期这个对象是不会被父进程垃圾回收的。如果父进程中的某些对象被垃圾回收会导致资源释放，这就变得很重要。

所以对于实例：

@example
from multiprocessing import Process, Lock

def f():
    ... do something using "lock" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f).start()
@end example

应当重写成这样：

@example
from multiprocessing import Process, Lock

def f(l):
    ... do something using "l" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f, args=(lock,)).start()
@end example
@end quotation

谨防将 @ref{427,,sys.stdin} 数据替换为 “类似文件的对象”

@quotation

@ref{b7,,multiprocessing} 原本会无条件地这样调用:

@example
os.close(sys.stdin.fileno())
@end example

在  @code{multiprocessing.Process._bootstrap()}  方法中 —— 这会导致与"进程中的进程"相关的一些问题。这已经被修改成了:

@example
sys.stdin.close()
sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)
@end example

它解决了进程相互冲突导致文件描述符错误的根本问题，但是对使用带缓冲的“文件类对象”替换 @ref{427,,sys.stdin()} 作为输出的应用程序造成了潜在的危险。如果多个进程调用了此文件类对象的 @ref{1190,,close()} 方法，会导致相同的数据多次刷写到此对象，损坏数据。

如果你写入文件类对象并实现了自己的缓存，可以在每次追加缓存数据时记录当前进程id，从而将其变成 fork 安全的，当发现进程id变化后舍弃之前的缓存，例如:

@example
@@property
def cache(self):
    pid = os.getpid()
    if pid != self._pid:
        self._pid = pid
        self._cache = []
    return self._cache
@end example

需要更多信息，请查看 bpo-5155@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5155}, bpo-5313@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5313} 以及 bpo-5331@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=5331}
@end quotation

@node spawn 和 forkserver 启动方式,,所有start方法,编程指导
@anchor{library/multiprocessing the-spawn-and-forkserver-start-methods}@anchor{258e}
@subsubsection @emph{spawn} 和 @emph{forkserver} 启动方式


相对于 @emph{fork} 启动方式，有一些额外的限制。

更依赖序列化

@quotation

@code{Process.__init__()} 的所有参数都必须可序列化。同样的，当你继承 @ref{4c1,,Process} 时，需要保证当调用 @ref{2513,,Process.start} 方法时，实例可以被序列化。
@end quotation

全局变量

@quotation

记住，如果子进程中的代码尝试访问一个全局变量，它所看到的值（如果有）可能和父进程中执行 @ref{2513,,Process.start} 那一刻的值不一样。

当全局变量知识模块级别的常量时，是不会有问题的。
@end quotation

安全导入主模块

@quotation

确保主模块可以被新启动的Python解释器安全导入而不会引发什么副作用（比如又启动了一个子进程）

例如，使用 @emph{spawn} 或 @emph{forkserver} 启动方式执行下面的模块，会引发 @ref{3e4,,RuntimeError} 异常而失败。

@example
from multiprocessing import Process

def foo():
    print('hello')

p = Process(target=foo)
p.start()
@end example

应该通过下面的方法使用 @code{if __name__ == '__main__':} ，从而保护程序"入口点":

@example
from multiprocessing import Process, freeze_support, set_start_method

def foo():
    print('hello')

if __name__ == '__main__':
    freeze_support()
    set_start_method('spawn')
    p = Process(target=foo)
    p.start()
@end example

（如果程序将正常运行而不是冻结，则可以省略 @code{freeze_support()} 行）

这允许新启动的 Python 解释器安全导入模块然后运行模块中的 @code{foo()} 函数。

如果主模块中创建了进程池或者管理器，这个规则也适用。
@end quotation

@node 示例<17>,,编程指导,multiprocessing --- 基于进程的并行
@anchor{library/multiprocessing examples}@anchor{258f}@anchor{library/multiprocessing multiprocessing-examples}@anchor{252a}
@subsubsection 示例


创建和使用自定义管理器、代理的示例:

@example
from multiprocessing import freeze_support
from multiprocessing.managers import BaseManager, BaseProxy
import operator

##

class Foo:
    def f(self):
        print('you called Foo.f()')
    def g(self):
        print('you called Foo.g()')
    def _h(self):
        print('you called Foo._h()')

# A simple generator function
def baz():
    for i in range(10):
        yield i*i

# Proxy type for generator objects
class GeneratorProxy(BaseProxy):
    _exposed_ = ['__next__']
    def __iter__(self):
        return self
    def __next__(self):
        return self._callmethod('__next__')

# Function to return the operator module
def get_operator_module():
    return operator

##

class MyManager(BaseManager):
    pass

# register the Foo class; make `f()` and `g()` accessible via proxy
MyManager.register('Foo1', Foo)

# register the Foo class; make `g()` and `_h()` accessible via proxy
MyManager.register('Foo2', Foo, exposed=('g', '_h'))

# register the generator function baz; use `GeneratorProxy` to make proxies
MyManager.register('baz', baz, proxytype=GeneratorProxy)

# register get_operator_module(); make public functions accessible via proxy
MyManager.register('operator', get_operator_module)

##

def test():
    manager = MyManager()
    manager.start()

    print('-' * 20)

    f1 = manager.Foo1()
    f1.f()
    f1.g()
    assert not hasattr(f1, '_h')
    assert sorted(f1._exposed_) == sorted(['f', 'g'])

    print('-' * 20)

    f2 = manager.Foo2()
    f2.g()
    f2._h()
    assert not hasattr(f2, 'f')
    assert sorted(f2._exposed_) == sorted(['g', '_h'])

    print('-' * 20)

    it = manager.baz()
    for i in it:
        print('<%d>' % i, end=' ')
    print()

    print('-' * 20)

    op = manager.operator()
    print('op.add(23, 45) =', op.add(23, 45))
    print('op.pow(2, 94) =', op.pow(2, 94))
    print('op._exposed_ =', op._exposed_)

##

if __name__ == '__main__':
    freeze_support()
    test()
@end example

使用 @ref{96f,,Pool}:

@example
import multiprocessing
import time
import random
import sys

#
# Functions used by test code
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % (
        multiprocessing.current_process().name,
        func.__name__, args, result
        )

def calculatestar(args):
    return calculate(*args)

def mul(a, b):
    time.sleep(0.5 * random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5 * random.random())
    return a + b

def f(x):
    return 1.0 / (x - 5.0)

def pow3(x):
    return x ** 3

def noop(x):
    pass

#
# Test code
#

def test():
    PROCESSES = 4
    print('Creating pool with %d processes\n' % PROCESSES)

    with multiprocessing.Pool(PROCESSES) as pool:
        #
        # Tests
        #

        TASKS = [(mul, (i, 7)) for i in range(10)] + \
                [(plus, (i, 8)) for i in range(10)]

        results = [pool.apply_async(calculate, t) for t in TASKS]
        imap_it = pool.imap(calculatestar, TASKS)
        imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)

        print('Ordered results using pool.apply_async():')
        for r in results:
            print('\t', r.get())
        print()

        print('Ordered results using pool.imap():')
        for x in imap_it:
            print('\t', x)
        print()

        print('Unordered results using pool.imap_unordered():')
        for x in imap_unordered_it:
            print('\t', x)
        print()

        print('Ordered results using pool.map() --- will block till complete:')
        for x in pool.map(calculatestar, TASKS):
            print('\t', x)
        print()

        #
        # Test error handling
        #

        print('Testing error handling:')

        try:
            print(pool.apply(f, (5,)))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.apply()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(pool.map(f, list(range(10))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.map()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(list(pool.imap(f, list(range(10)))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from list(pool.imap())')
        else:
            raise AssertionError('expected ZeroDivisionError')

        it = pool.imap(f, list(range(10)))
        for i in range(10):
            try:
                x = next(it)
            except ZeroDivisionError:
                if i == 5:
                    pass
            except StopIteration:
                break
            else:
                if i == 5:
                    raise AssertionError('expected ZeroDivisionError')

        assert i == 9
        print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
        print()

        #
        # Testing timeouts
        #

        print('Testing ApplyResult.get() with timeout:', end=' ')
        res = pool.apply_async(calculate, TASKS[0])
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % res.get(0.02))
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()

        print('Testing IMapIterator.next() with timeout:', end=' ')
        it = pool.imap(calculatestar, TASKS)
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % it.next(0.02))
            except StopIteration:
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()


if __name__ == '__main__':
    multiprocessing.freeze_support()
    test()
@end example

一个演示如何使用队列来向一组工作进程提供任务并收集结果的例子：

@example
import time
import random

from multiprocessing import Process, Queue, current_process, freeze_support

#
# Function run by worker processes
#

def worker(input, output):
    for func, args in iter(input.get, 'STOP'):
        result = calculate(func, args)
        output.put(result)

#
# Function used to calculate result
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % \
        (current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def mul(a, b):
    time.sleep(0.5*random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5*random.random())
    return a + b

#
#
#

def test():
    NUMBER_OF_PROCESSES = 4
    TASKS1 = [(mul, (i, 7)) for i in range(20)]
    TASKS2 = [(plus, (i, 8)) for i in range(10)]

    # Create queues
    task_queue = Queue()
    done_queue = Queue()

    # Submit tasks
    for task in TASKS1:
        task_queue.put(task)

    # Start worker processes
    for i in range(NUMBER_OF_PROCESSES):
        Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results
    print('Unordered results:')
    for i in range(len(TASKS1)):
        print('\t', done_queue.get())

    # Add more tasks using `put()`
    for task in TASKS2:
        task_queue.put(task)

    # Get and print some more results
    for i in range(len(TASKS2)):
        print('\t', done_queue.get())

    # Tell child processes to stop
    for i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')


if __name__ == '__main__':
    freeze_support()
    test()
@end example

@node multiprocessing shared_memory --- 可从进程直接访问的共享内存,concurrent 包,multiprocessing --- 基于进程的并行,并发执行
@anchor{library/multiprocessing shared_memory doc}@anchor{2590}@anchor{library/multiprocessing shared_memory module-multiprocessing shared_memory}@anchor{bc}@anchor{library/multiprocessing shared_memory multiprocessing-shared-memory-provides-shared-memory-for-direct-access-across-processes}@anchor{2591}
@subsection @code{multiprocessing.shared_memory} --- 可从进程直接访问的共享内存


@geindex multiprocessing.shared_memory (模块)

@strong{源代码:} Lib/multiprocessing/shared_memory.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/multiprocessing/shared_memory.py}


3.8 新版功能.


@geindex Shared Memory
@geindex POSIX Shared Memory
@geindex Named Shared Memory


__________________________________________________________________


该模块提供了一个 @ref{24ff,,SharedMemory} 类，用于分配和管理多核或对称多处理器（SMP）机器上进程间的共享内存。为了协助管理不同进程间的共享内存生命周期，@code{multiprocessing.managers} 模块也提供了一个 @ref{2553,,BaseManager} 的子类： @code{SharedMemoryManager}。

本模块中，共享内存是指 "System V 类型" 的共享内存块（虽然实现方式可能不完全一致）而不是 “分布式共享内存”。这种类型的的共享内存允许不同进程读写一片公共（或者共享）的易失性存储区域。一般来说，进程被限制只能访问属于自己进程空间的内存，但是共享内存允许跨进程共享数据，从而避免通过进程间发送消息的形式传递数据。与通过磁盘、套接字或者其他要求序列化、反序列化和复制数据的共享形式相比，直接通过内存共享数据拥有更出色的性能。

@geindex SharedMemory (multiprocessing.shared_memory 中的类)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory}@anchor{24ff}
@deffn {类} multiprocessing.shared_memory.SharedMemory (name=None, create=False, size=0)

创建一个新的共享内存块或者连接到一片已经存在的共享内存块。每个共享内存块都被指定了一个全局唯一的名称。通过这种方式，进程可以使用一个特定的名字创建共享内存区块，然后其他进程使用同样的名字连接到这个共享内存块。

作为一种跨进程共享数据的方式，共享内存块的寿命可能超过创建它的原始进程。一个共享内存块可能同时被多个进程使用，当一个进程不再需要访问这个共享内存块的时候，应该调用 @ref{2592,,close()} 方法。当一个共享内存块不被任何进程使用的时候，应该调用 @ref{2593,,unlink()} 方法以保证必要的清理。

@emph{name} 是共享内存的唯一名称，字符串类型。如果创建一个新共享内存块的时候，名称指定为 @code{None}  (默认值)，将会随机产生一个新名称。

@emph{create} 指定创建一个新的共享内存块 (@code{True}) 还是连接到已存在的共享内存块 (@code{False}) 。

如果是新创建共享内存块则 @emph{size} 用于指定块的大小为多少字节。由于某些平台是以内存页大小为最小单位来分配内存的，最终得到的内存块大小可能大于或等于要求的大小。如果是连接到已经存在的共享内存块， @code{size} 参数会被忽略。

@geindex close() (multiprocessing.shared_memory.SharedMemory 方法)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory close}@anchor{2592}
@deffn {方法} close ()

关闭实例对于共享内存的访问连接。所有实例确认自己不再需要使用共享内存的时候都应该调用 @code{close()} ，以保证必要的资源清理。调用 @code{close()} 并不会销毁共享内存区域。
@end deffn

@geindex unlink() (multiprocessing.shared_memory.SharedMemory 方法)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory unlink}@anchor{2593}
@deffn {方法} unlink ()

请求销毁底层的共享内存块。 为了执行必要的资源清理，在所有使用这个共享内存块的进程中，@code{unlink()} 应该调用一次（且只能调用一次）。 发出此销毁请求后，共享内存块可能会、也可能不会立即销毁，且此行为在不同操作系统之间可能不同。 调用 @code{unlink()} 后再尝试访问其中的数据可能导致内存错误。 注意：最后一个关闭共享内存访问权限的进程可以以任意顺序调用 @code{unlink()} 和 @ref{2592,,close()}。
@end deffn

@geindex buf (multiprocessing.shared_memory.SharedMemory 属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory buf}@anchor{2594}
@deffn {属性} buf

共享内存块内容的 memoryview 。
@end deffn

@geindex name (multiprocessing.shared_memory.SharedMemory 属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory name}@anchor{2595}
@deffn {属性} name

共享内存块的唯一标识，只读属性。
@end deffn

@geindex size (multiprocessing.shared_memory.SharedMemory 属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory size}@anchor{2596}
@deffn {属性} size

共享内存块的字节大小，只读属性。
@end deffn
@end deffn

以下示例展示了 @ref{24ff,,SharedMemory} 底层的用法:

@example
>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
@end example

以下示例展示了一个现实中的例子，使用  @ref{24ff,,SharedMemory} 类和 NumPy arrays@footnote{https://www.numpy.org/} 结合, 从两个 Python shell 中访问同一个 @code{numpy.ndarray} :

@example
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
@end example

@geindex SharedMemoryManager (multiprocessing.managers 中的类)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager}@anchor{2597}
@deffn {类} multiprocessing.managers.SharedMemoryManager ([address[, authkey]])

@ref{2553,,BaseManager} 的子类，可用于管理跨进程的共享内存块。

调用 @ref{2597,,SharedMemoryManager}  实例上的 @ref{2554,,start()} 方法会启动一个新进程。这个新进程的唯一目的就是管理所有由它创建的共享内存块的生命周期。想要释放此进程管理的所有共享内存块，可以调用实例的 @ref{2558,,shutdown()} 方法。这会触发执行它管理的所有  @ref{2598,,SharedMemory} 对象的 @code{SharedMemory.unlink()} 方法，然后停止这个进程。通过  @code{SharedMemoryManager} 创建 @code{SharedMemory} 实例，我们可以避免手动跟踪和释放共享内存资源。

这个类提供了创建和返回 @ref{2598,,SharedMemory} 实例的方法，以及以共享内存为基础创建一个列表类对象 (@ref{2599,,ShareableList}) 的方法。

有关继承的可选输入参数 @emph{address} 和 @emph{authkey}  以及他们如何用于从进程连接已经存在的 @code{SharedMemoryManager} 服务，参见 @ref{2553,,multiprocessing.managers.BaseManager} 。

@geindex SharedMemory() (multiprocessing.managers.SharedMemoryManager 方法)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager SharedMemory}@anchor{2598}
@deffn {方法} SharedMemory (size)

使用 @code{size} 参数，创建一个新的指定字节大小的 @ref{2598,,SharedMemory} 对象并返回。
@end deffn

@geindex ShareableList() (multiprocessing.managers.SharedMemoryManager 方法)
@anchor{library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager ShareableList}@anchor{2599}
@deffn {方法} ShareableList (sequence)

创建并返回一个新的 @ref{2599,,ShareableList} 对象，通过输入参数 @code{sequence} 初始化。
@end deffn
@end deffn

下面的案例展示了 @code{SharedMemoryManager} 的基本机制:

@example
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
@end example

以下案例展示了 @code{SharedMemoryManager} 对象的一种可能更方便的使用方式，通过 @ref{7e4,,with} 语句来保证所有共享内存块在使用完后被释放。

@example
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
@end example

在 @ref{7e4,,with} 语句中使用 @code{SharedMemoryManager}  对象的时候，使用这个管理器创建的共享内存块会在  @ref{7e4,,with} 语句代码块结束后被释放。

@geindex ShareableList (multiprocessing.shared_memory 中的类)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList}@anchor{109e}
@deffn {类} multiprocessing.shared_memory.ShareableList (sequence=None, *, name=None)

提供一个可修改的类 list 对象，其中所有值都存放在共享内存块中。这限制了可被存储在其中的值只能是 @code{int}, @code{float}, @code{bool}, @code{str}  （每条数据小于10M）, @code{bytes} （每条数据小于10M）以及 @code{None} 这些内置类型。它另一个显著区别于内置 @code{list} 类型的地方在于它的长度无法修改（比如，没有 append, insert 等操作）且不支持通过切片操作动态创建新的 @ref{109e,,ShareableList}  实例。

@emph{sequence} 会被用来为一个新的 @code{ShareableList} 填充值。 设为 @code{None} 则会基于唯一的共享内存名称关联到已经存在的 @code{ShareableList}。

@emph{name} 是所请求的共享内存的唯一名称，与 @ref{24ff,,SharedMemory} 的定义中所描述的一致。 当关联到现有的 @code{ShareableList} 时，则指明其共享内存块的唯一名称并将 @code{sequence} 设为 @code{None}。

@geindex count() (multiprocessing.shared_memory.ShareableList 方法)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList count}@anchor{259a}
@deffn {方法} count (value)

返回 @code{value} 出现的次数。
@end deffn

@geindex index() (multiprocessing.shared_memory.ShareableList 方法)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList index}@anchor{259b}
@deffn {方法} index (value)

返回 @code{value} 首次出现的位置，如果 @code{value} 不存在, 则抛出 @ref{16d,,ValueError} 异常。
@end deffn

@geindex format (multiprocessing.shared_memory.ShareableList 属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList format}@anchor{259c}
@deffn {属性} format

包含由所有当前存储值所使用的 @ref{f8,,struct} 打包格式的只读属性。
@end deffn

@geindex shm (multiprocessing.shared_memory.ShareableList 属性)
@anchor{library/multiprocessing shared_memory multiprocessing shared_memory ShareableList shm}@anchor{259d}
@deffn {属性} shm

存储了值的 @ref{24ff,,SharedMemory} 实例。
@end deffn
@end deffn

下面的例子演示了 @ref{109e,,ShareableList} 实例的基本用法:

@example
>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported
@end example

下面的例子演示了一个、两个或多个进程如何通过提供下层的共享内存块名称来访问同一个 @ref{109e,,ShareableList}:

@example
>>> b = shared_memory.ShareableList(range(5))         # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink()
@end example

@node concurrent 包,concurrent futures --- 启动并行任务,multiprocessing shared_memory --- 可从进程直接访问的共享内存,并发执行
@anchor{library/concurrent doc}@anchor{259e}@anchor{library/concurrent the-concurrent-package}@anchor{259f}
@subsection @code{concurrent} 包


目前，此包中只有一个模块：


@itemize *

@item 
@ref{21,,concurrent.futures} —— 启动并行任务
@end itemize

@node concurrent futures --- 启动并行任务,subprocess --- 子进程管理,concurrent 包,并发执行
@anchor{library/concurrent futures doc}@anchor{25a0}@anchor{library/concurrent futures concurrent-futures-launching-parallel-tasks}@anchor{25a1}@anchor{library/concurrent futures module-concurrent futures}@anchor{21}
@subsection @code{concurrent.futures} --- 启动并行任务


@geindex concurrent.futures (模块)


3.2 新版功能.


@strong{源码:} Lib/concurrent/futures/thread.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/thread.py} 和 Lib/concurrent/futures/process.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/process.py}


__________________________________________________________________


@ref{21,,concurrent.futures} 模块提供异步执行回调高层接口。

异步执行可以由 @ref{18c,,ThreadPoolExecutor} 使用线程或由 @ref{196,,ProcessPoolExecutor} 使用单独的进程来实现。 两者都是实现抽像类 @ref{25a2,,Executor} 定义的接口。

@menu
* Executor 对象:: 
* ThreadPoolExecutor:: 
* ProcessPoolExecutor:: 
* Future 对象:: 
* 模块函数:: 
* Exception 类:: 

@end menu

@node Executor 对象,ThreadPoolExecutor,,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures executor-objects}@anchor{25a3}
@subsubsection Executor 对象


@geindex Executor (concurrent.futures 中的类)
@anchor{library/concurrent futures concurrent futures Executor}@anchor{25a2}
@deffn {类} concurrent.futures.Executor

抽象类提供异步执行调用方法。要通过它的子类调用，而不是直接调用。

@quotation

@geindex submit() (concurrent.futures.Executor 方法)
@anchor{library/concurrent futures concurrent futures Executor submit}@anchor{3ce}
@deffn {方法} submit (fn, /, *args, **kwargs)

调度可调用对象 @emph{fn}，以 @code{fn(*args, **kwargs)} 方式执行并返回一个代表该可调用对象的执行的 @ref{c09,,Future} 对象。

@example
with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())
@end example
@end deffn

@geindex map() (concurrent.futures.Executor 方法)
@anchor{library/concurrent futures concurrent futures Executor map}@anchor{7bb}
@deffn {方法} map (func, *iterables, timeout=None, chunksize=1)

类似于 @ref{cff,,map(func@comma{} *iterables)} 函数，除了以下两点：


@itemize *

@item 
@emph{iterables} 是立即执行而不是延迟执行的；

@item 
@emph{func} 是异步执行的，对 @emph{func} 的多个调用可以并发执行。
@end itemize

如果 @ref{d34,,__next__()} 已被调用且返回的结果在对 @ref{7bb,,Executor.map()} 的原始调用经过 @emph{timeout} 秒后还不可用，则已返回的迭代器将引发 @ref{25a4,,concurrent.futures.TimeoutError}。 @emph{timeout} 可以为 int 或 float 类型。 如果 @emph{timeout} 未指定或为 @code{None}，则不限制等待时间。

如果 @emph{func} 调用引发一个异常，当从迭代器中取回它的值时这个异常将被引发。

使用 @ref{196,,ProcessPoolExecutor} 时，这个方法会将 @emph{iterables} 分割任务块并作为独立的任务并提交到执行池中。这些块的大概数量可以由 @emph{chunksize} 指定正整数设置。 对很长的迭代器来说，使用大的 @emph{chunksize} 值比默认值 1 能显著地提高性能。 @emph{chunksize} 对 @ref{18c,,ThreadPoolExecutor} 没有效果。


在 3.5 版更改: 加入 @emph{chunksize} 参数。

@end deffn

@geindex shutdown() (concurrent.futures.Executor 方法)
@anchor{library/concurrent futures concurrent futures Executor shutdown}@anchor{195}
@deffn {方法} shutdown (wait=True, *, cancel_futures=False)

当待执行的 future 对象完成执行后向执行者发送信号，它就会释放正在使用的任何资源。 在关闭后调用 @ref{3ce,,Executor.submit()} 和 @ref{7bb,,Executor.map()} 将会引发 @ref{3e4,,RuntimeError}。

如果 @emph{wait} 为 @code{True} 则此方法只有在所有待执行的 future 对象完成执行且释放已分配的资源后才会返回。 如果 @emph{wait} 为 @code{False}，方法立即返回，所有待执行的 future 对象完成执行后会释放已分配的资源。 不管 @emph{wait} 的值是什么，整个 Python 程序将等到所有待执行的 future 对象完成执行后才退出。

如果 @emph{cancel_futures} 为 @code{True}，此方法将取消所有执行器还未开始运行的挂起的 Future。 任何已完成或正在运行的 Future 将不会被取消，无论 @emph{cancel_futures} 的值是什么？

如果 @emph{cancel_futures} 和 @emph{wait} 均为 @code{True}，则执行器已开始运行的所有 Future 将在此方法返回之前完成。 其余的 Future 会被取消。

如果使用 @ref{7e4,,with} 语句，你就可以避免显式调用这个方法，它将会停止 @ref{25a2,,Executor} (就好像 @ref{195,,Executor.shutdown()} 调用时 @emph{wait} 设为 @code{True} 一样等待):

@example
import shutil
with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
@end example


在 3.9 版更改: 增加了 @emph{cancel_futures}。

@end deffn
@end quotation
@end deffn

@node ThreadPoolExecutor,ProcessPoolExecutor,Executor 对象,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures threadpoolexecutor}@anchor{25a5}
@subsubsection ThreadPoolExecutor


@ref{18c,,ThreadPoolExecutor} 是 @ref{25a2,,Executor} 的子类，它使用线程池来异步执行调用。

当可调用对象已关联了一个 @ref{c09,,Future} 然后在等待另一个 @ref{c09,,Future} 的结果时就会导致死锁情况。例如:

@example
import time
def wait_on_b():
    time.sleep(5)
    print(b.result())  # b will never complete because it is waiting on a.
    return 5

def wait_on_a():
    time.sleep(5)
    print(a.result())  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)
@end example

And:

@example
def wait_on_future():
    f = executor.submit(pow, 5, 2)
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print(f.result())

executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)
@end example

@geindex ThreadPoolExecutor (concurrent.futures 中的类)
@anchor{library/concurrent futures concurrent futures ThreadPoolExecutor}@anchor{18c}
@deffn {类} concurrent.futures.ThreadPoolExecutor (max_workers=None, thread_name_prefix='@w{'}, initializer=None, initargs=())

@ref{25a2,,Executor} 的一个子类，使用最多 @emph{max_workers} 个线程的线程池来异步执行调用。

@emph{initializer} 是在每个工作者线程开始处调用的一个可选可调用对象。 @emph{initargs} 是传递给初始化器的元组参数。任何向池提交更多工作的尝试， @emph{initializer} 都将引发一个异常，当前所有等待的工作都会引发一个 @ref{25a6,,BrokenThreadPool}。


在 3.5 版更改: 如果 @emph{max_workers} 为 @code{None} 或没有指定，将默认为机器处理器的个数，假如 @ref{18c,,ThreadPoolExecutor} 侧重于 I/O 操作而不是 CPU 运算，那么可以乘以 @code{5}，同时工作线程的数量可以比 @ref{196,,ProcessPoolExecutor} 的数量高。



3.6 新版功能: 添加 @emph{thread_name_prefix} 参数允许用户控制由线程池创建的 @ref{21b,,threading.Thread} 工作线程名称以方便调试。



在 3.7 版更改: 加入 @emph{initializer} 和*initargs* 参数。



在 3.8 版更改: @emph{max_workers} 的默认值已改为 @code{min(32, os.cpu_count() + 4)}。 这个默认值会保留至少 5 个工作线程用于 I/O 密集型任务。 对于那些释放了 GIL 的 CPU 密集型任务，它最多会使用 32 个 CPU 核心。这样能够避免在多核机器上不知不觉地使用大量资源。

现在 ThreadPoolExecutor 在启动 @emph{max_workers} 个工作线程之前也会重用空闲的工作线程。

@end deffn

@menu
* ThreadPoolExecutor 例子:: 

@end menu

@node ThreadPoolExecutor 例子,,,ThreadPoolExecutor
@anchor{library/concurrent futures id1}@anchor{25a7}@anchor{library/concurrent futures threadpoolexecutor-example}@anchor{c0a}
@subsubsection ThreadPoolExecutor 例子


@example
import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://nonexistant-subdomain.python.org/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = @{executor.submit(load_url, url, 60): url for url in URLS@}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
@end example

@node ProcessPoolExecutor,Future 对象,ThreadPoolExecutor,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures processpoolexecutor}@anchor{25a8}
@subsubsection ProcessPoolExecutor


@ref{196,,ProcessPoolExecutor} 类是 @ref{25a2,,Executor} 的子类，它使用进程池来异步地执行调用。 @ref{196,,ProcessPoolExecutor} 会使用 @ref{b7,,multiprocessing} 模块，这允许它绕过 @ref{60b,,全局解释器锁} 但也意味着只可以处理和返回可封存的对象。

@code{__main__} 模块必须可以被工作者子进程导入。这意味着 @ref{196,,ProcessPoolExecutor} 不可以工作在交互式解释器中。

从提交给 @ref{196,,ProcessPoolExecutor} 的回调中调用 @ref{25a2,,Executor} 或 @ref{c09,,Future} 方法会导致死锁。

@geindex ProcessPoolExecutor (concurrent.futures 中的类)
@anchor{library/concurrent futures concurrent futures ProcessPoolExecutor}@anchor{196}
@deffn {类} concurrent.futures.ProcessPoolExecutor (max_workers=None, mp_context=None, initializer=None, initargs=())

异步地执行调用的 @ref{25a2,,Executor} 子类使用最多具有 @emph{max_workers} 个进程的进程池。 如果 @emph{max_workers} 为 @code{None} 或未给出，它将默认为机器的处理器个数。 如果 @emph{max_workers} 小于等于 @code{0}，则将引发 @ref{16d,,ValueError}。 在 Windows 上，@emph{max_workers} 必须小于等于 @code{61}，否则将引发 @ref{16d,,ValueError}。 如果 @emph{max_workers} 为 @code{None}，则所选择的默认值最多为 @code{61}，即使存在更多的处理器。 @emph{mp_context} 可以是一个多进程上下文或是 None。 它将被用来启动工作进程。 如果 @emph{mp_context} 为 @code{None} 或未给出，则将使用默认的多进程上下文。

@emph{initializer} 是一个可选的可调用对象，它会在每个工作进程启动时被调用；@emph{initargs} 是传给 initializer 的参数元组。 如果 @emph{initializer} 引发了异常，则所有当前在等待的任务以及任何向进程池提交更多任务的尝试都将引发 @ref{25a9,,BrokenProcessPool}。


在 3.3 版更改: 如果其中一个工作进程被突然终止，@code{BrokenProcessPool} 就会马上触发。 可预计的行为没有定义，但执行器上的操作或它的 future 对象会被冻结或死锁。



在 3.7 版更改: 添加 @emph{mp_context} 参数允许用户控制由进程池创建给工作者进程的开始方法 。

加入 @emph{initializer} 和*initargs* 参数。

@end deffn

@menu
* ProcessPoolExecutor 例子:: 

@end menu

@node ProcessPoolExecutor 例子,,,ProcessPoolExecutor
@anchor{library/concurrent futures id2}@anchor{25aa}@anchor{library/concurrent futures processpoolexecutor-example}@anchor{c0b}
@subsubsection ProcessPoolExecutor 例子


@example
import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()
@end example

@node Future 对象,模块函数,ProcessPoolExecutor,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures future-objects}@anchor{25ab}
@subsubsection Future 对象


@ref{c09,,Future} 类将可调用对象封装为异步执行。@ref{c09,,Future} 实例由 @ref{3ce,,Executor.submit()} 创建。

@geindex Future (concurrent.futures 中的类)
@anchor{library/concurrent futures concurrent futures Future}@anchor{c09}
@deffn {类} concurrent.futures.Future

将可调用对象封装为异步执行。@ref{c09,,Future} 实例由 @ref{3ce,,Executor.submit()} 创建，除非测试，不应直接创建。

@quotation

@geindex cancel() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future cancel}@anchor{25ac}
@deffn {方法} cancel ()

尝试取消调用。 如果调用正在执行或已结束运行不能被取消则该方法将返回 @code{False}，否则调用会被取消并且该方法将返回 @code{True}。
@end deffn

@geindex cancelled() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future cancelled}@anchor{25ad}
@deffn {方法} cancelled ()

如果调用成功取消返回 @code{True}。
@end deffn

@geindex running() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future running}@anchor{25ae}
@deffn {方法} running ()

如果调用正在执行而且不能被取消那么返回`@w{`}True`@w{`}。
@end deffn

@geindex done() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future done}@anchor{25af}
@deffn {方法} done ()

如果调用已被取消或正常结束那么返回 @code{True}。
@end deffn

@geindex result() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future result}@anchor{25b0}
@deffn {方法} result (timeout=None)

返回调用返回的值。如果调用还没完成那么这个方法将等待 @emph{timeout} 秒。如果在 @emph{timeout} 秒内没有执行完成，@ref{25a4,,concurrent.futures.TimeoutError} 将会被触发。@emph{timeout} 可以是整数或浮点数。如果 @emph{timeout} 没有指定或为 @code{None}，那么等待时间就没有限制。

如果 futrue 在完成前被取消则 @ref{2e4,,CancelledError} 将被触发。

如果调用引发了一个异常，这个方法也会引发同样的异常。
@end deffn

@geindex exception() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future exception}@anchor{25b1}
@deffn {方法} exception (timeout=None)

返回由调用引发的异常。如果调用还没完成那么这个方法将等待 @emph{timeout} 秒。如果在 @emph{timeout} 秒内没有执行完成，@ref{25a4,,concurrent.futures.TimeoutError} 将会被触发。@emph{timeout} 可以是整数或浮点数。如果 @emph{timeout} 没有指定或为 @code{None}，那么等待时间就没有限制。

如果 futrue 在完成前被取消则 @ref{2e4,,CancelledError} 将被触发。

如果调用正常完成那么返回 @code{None}。
@end deffn

@geindex add_done_callback() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future add_done_callback}@anchor{25b2}
@deffn {方法} add_done_callback (fn)

附加可调用 @emph{fn} 到 future 对象。当 future 对象被取消或完成运行时，将会调用 @emph{fn}，而这个 future 对象将作为它唯一的参数。

加入的可调用对象总被属于添加它们的进程中的线程按加入的顺序调用。如果可调用对象引发一个 @ref{2e3,,Exception} 子类，它会被记录下来并被忽略掉。如果可调用对象引发一个 @ref{2e2,,BaseException} 子类，这个行为没有定义。

如果 future 对象已经完成或已取消，@emph{fn} 会被立即调用。
@end deffn
@end quotation

下面这些 @ref{c09,,Future} 方法用于单元测试和 @ref{25a2,,Executor} 实现。

@quotation

@geindex set_running_or_notify_cancel() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future set_running_or_notify_cancel}@anchor{25b3}
@deffn {方法} set_running_or_notify_cancel ()

这个方法只可以在执行关联 @ref{c09,,Future}  工作之前由 @ref{25a2,,Executor} 实现调用或由单测试调用。

如果这个方法返回  @code{False} 那么 @ref{c09,,Future} 已被取消，即 @ref{25ac,,Future.cancel()} 已被调用并返回 @code{True} 。等待 @ref{c09,,Future} 完成 (即通过 @ref{126b,,as_completed()} 或 @ref{f9c,,wait()}) 的线程将被唤醒。

如果这个方法返回 @code{True} 那么 @ref{c09,,Future} 不会被取消并已将它变为正在运行状态，也就是说调用 @ref{25ae,,Future.running()} 时将返回 @cite{True}。

这个方法只可以被调用一次并且不能在调用 @ref{25b4,,Future.set_result()} 或 @ref{25b5,,Future.set_exception()} 之后再调用。
@end deffn

@geindex set_result() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future set_result}@anchor{25b4}
@deffn {方法} set_result (result)

设置将 @ref{c09,,Future} 关联工作的结果给 @emph{result} 。

这个方法只可以由 @ref{25a2,,Executor} 实现和单元测试使用。


在 3.8 版更改: 如果 @ref{c09,,Future} 已经完成则此方法会引发 @ref{25b6,,concurrent.futures.InvalidStateError}。

@end deffn

@geindex set_exception() (concurrent.futures.Future 方法)
@anchor{library/concurrent futures concurrent futures Future set_exception}@anchor{25b5}
@deffn {方法} set_exception (exception)

设置 @ref{c09,,Future} 关联工作的结果给 @ref{2e3,,Exception} @emph{exception} 。

这个方法只可以由 @ref{25a2,,Executor} 实现和单元测试使用。


在 3.8 版更改: 如果 @ref{c09,,Future} 已经完成则此方法会引发 @ref{25b6,,concurrent.futures.InvalidStateError}。

@end deffn
@end quotation
@end deffn

@node 模块函数,Exception 类,Future 对象,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures module-functions}@anchor{25b7}
@subsubsection 模块函数


@geindex wait() (在 concurrent.futures 模块中)
@anchor{library/concurrent futures concurrent futures wait}@anchor{f9c}
@deffn {函数} concurrent.futures.wait (fs, timeout=None, return_when=ALL_COMPLETED)

等待由 @emph{fs} 指定的 @ref{c09,,Future} 实例（可能由不同的 @ref{25a2,,Executor} 实例创建）完成。 重复传给 @emph{fs} 的 future 会被移除并将只返回一次。 返回一个由集合组成的具名 2 元组。 第一个集合的名称为 @code{done}，包含在等待完成之前已完成的 future（包括正常结束或被取消的 future）。 第二个集合的名称为 @code{not_done}，包含未完成的 future（包括挂起的或正在运行的 future）。

@emph{timeout} 可以用来控制返回前最大的等待秒数。 @emph{timeout} 可以为 int 或 float 类型。 如果 @emph{timeout} 未指定或为 @code{None} ，则不限制等待时间。

@emph{return_when} 指定此函数应在何时返回。它必须为以下常数之一:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

描述

@item

@code{FIRST_COMPLETED}

@tab

函数将在任意可等待对象结束或取消时返回。

@item

@code{FIRST_EXCEPTION}

@tab

函数将在任意可等待对象因引发异常而结束时返回。当没有引发任何异常时它就相当于 @code{ALL_COMPLETED}。

@item

@code{ALL_COMPLETED}

@tab

函数将在所有可等待对象结束或取消时返回。

@end multitable

@end deffn

@geindex as_completed() (在 concurrent.futures 模块中)
@anchor{library/concurrent futures concurrent futures as_completed}@anchor{126b}
@deffn {函数} concurrent.futures.as_completed (fs, timeout=None)

返回一个包含 @emph{fs} 所指定的 @ref{c09,,Future} 实例（可能由不同的 @ref{25a2,,Executor} 实例创建）的迭代器，这些实例会在完成时生成 future 对象（包括正常结束或被取消的 future 对象）。 任何由 @emph{fs} 所指定的重复 future 对象将只被返回一次。 任何在 @ref{126b,,as_completed()} 被调用之前完成的 future 对象将优先被生成。 如果 @ref{d34,,__next__()} 被调用并且在对 @ref{126b,,as_completed()} 的原始调用 @emph{timeout} 秒之后结果仍不可用，则返回的迭代器将引发 @ref{25a4,,concurrent.futures.TimeoutError}。 @emph{timeout} 可以为整数或浮点数。 如果 @emph{timeout} 未指定或为 @code{None}，则不限制等待时间。
@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 3148

@item PEP 3148@footnote{https://www.python.org/dev/peps/pep-3148} -- futures - 异步执行指令。

该提案描述了Python标准库中包含的这个特性。
@end table


@node Exception 类,,模块函数,concurrent futures --- 启动并行任务
@anchor{library/concurrent futures exception-classes}@anchor{25b8}
@subsubsection Exception 类


@geindex CancelledError
@anchor{library/concurrent futures concurrent futures CancelledError}@anchor{2e4}
@deffn {例外} concurrent.futures.CancelledError

future 对象被取消时会触发。
@end deffn

@geindex TimeoutError
@anchor{library/concurrent futures concurrent futures TimeoutError}@anchor{25a4}
@deffn {例外} concurrent.futures.TimeoutError

future 对象执行超出给定的超时数值时引发。
@end deffn

@geindex BrokenExecutor
@anchor{library/concurrent futures concurrent futures BrokenExecutor}@anchor{25b9}
@deffn {例外} concurrent.futures.BrokenExecutor

当执行器被某些原因中断而且不能用来提交或执行新任务时就会被引发派生于 @ref{3e4,,RuntimeError} 的异常类。


3.7 新版功能.

@end deffn

@geindex InvalidStateError
@anchor{library/concurrent futures concurrent futures InvalidStateError}@anchor{25b6}
@deffn {例外} concurrent.futures.InvalidStateError

当某个操作在一个当前状态所不允许的 future 上执行时将被引发。


3.8 新版功能.

@end deffn

@geindex BrokenThreadPool
@anchor{library/concurrent futures concurrent futures thread BrokenThreadPool}@anchor{25a6}
@deffn {例外} concurrent.futures.thread.BrokenThreadPool

当 @code{ThreadPoolExecutor} 中的其中一个工作者初始化失败时会引发派生于 @ref{25b9,,BrokenExecutor} 的异常类。


3.7 新版功能.

@end deffn

@geindex BrokenProcessPool
@anchor{library/concurrent futures concurrent futures process BrokenProcessPool}@anchor{25a9}
@deffn {例外} concurrent.futures.process.BrokenProcessPool

当 @code{ThreadPoolExecutor} 中的其中一个工作者不完整终止时(比如，被外部杀死)会引发派生于 @ref{25b9,,BrokenExecutor} ( 原名 @ref{3e4,,RuntimeError} ) 的异常类。


3.3 新版功能.

@end deffn

@node subprocess --- 子进程管理,sched --- 事件调度器,concurrent futures --- 启动并行任务,并发执行
@anchor{library/subprocess doc}@anchor{25ba}@anchor{library/subprocess module-subprocess}@anchor{f9}@anchor{library/subprocess subprocess-subprocess-management}@anchor{25bb}
@subsection @code{subprocess} --- 子进程管理


@geindex subprocess (模块)

@strong{源代码:} Lib/subprocess.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/subprocess.py}


__________________________________________________________________


@ref{f9,,subprocess} 模块允许你生成新的进程，连接它们的输入、输出、错误管道，并且获取它们的返回码。此模块打算代替一些老旧的模块与功能：

@example
os.system
os.spawn*
@end example

在下面的段落中，你可以找到关于 @ref{f9,,subprocess} 模块如何代替这些模块和功能的相关信息。


@subsubheading 参见


@geindex Python 提高建议; PEP 324
PEP 324@footnote{https://www.python.org/dev/peps/pep-0324} -- 提出 subprocess 模块的 PEP


@menu
* 使用 subprocess 模块:: 
* 安全考量: 安全考量<2>. 
* Popen 对象:: 
* Windows Popen 助手:: 
* 较旧的高阶 API:: 
* 使用 subprocess 模块替换旧函数:: 
* 旧式的 Shell 发起函数:: 
* 注释: 注释<2>. 

@end menu

@node 使用 subprocess 模块,安全考量<2>,,subprocess --- 子进程管理
@anchor{library/subprocess using-the-subprocess-module}@anchor{25bc}
@subsubsection 使用 @code{subprocess} 模块


推荐的调用子进程的方式是在任何它支持的用例中使用 @ref{4fb,,run()} 函数。对于更进阶的用例，也可以使用底层的 @ref{3e3,,Popen} 接口。

@ref{4fb,,run()} 函数是在 Python 3.5 被添加的；如果你需要与旧版本保持兼容，查看 @ref{25bd,,较旧的高阶 API} 段落。

@geindex run() (在 subprocess 模块中)
@anchor{library/subprocess subprocess run}@anchor{4fb}
@deffn {函数} subprocess.run (args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

运行被 @emph{arg} 描述的指令。等待指令完成，然后返回一个 @ref{859,,CompletedProcess} 实例。

以上显示的参数仅仅是最简单的一些，下面 @ref{25be,,常用参数} 描述（因此在缩写签名中使用仅关键字标示）。完整的函数头和 @ref{3e3,,Popen} 的构造函数一样，此函数接受的大多数参数都被传递给该接口。（@emph{timeout}, @emph{input}, @emph{check} 和 @emph{capture_output} 除外）。

如果 @emph{capture_output} 设为 true，stdout 和 stderr 将会被捕获。在使用时，内置的 @ref{3e3,,Popen} 对象将自动用 @code{stdout=PIPE} 和 @code{stderr=PIPE} 创建。@emph{stdout} 和 @emph{stderr} 参数不应当与 @emph{capture_output} 同时提供。如果你希望捕获并将两个流合并在一起，使用 @code{stdout=PIPE} 和 @code{stderr=STDOUT} 来代替 @emph{capture_output}。

@emph{timeout} 参数将被传递给 @ref{25bf,,Popen.communicate()}。如果发生超时，子进程将被杀死并等待。 @ref{25c0,,TimeoutExpired} 异常将在子进程中断后被抛出。

@emph{input} 参数将被传递给 @ref{25bf,,Popen.communicate()} 以及子进程的标准输入。 如果使用此参数，它必须是一个字节序列。 如果指定了 @emph{encoding} 或 @emph{errors} 或者将 @emph{text} 设置为 @code{True}，那么也可以是一个字符串。 当使用此参数时，在创建内部 @ref{3e3,,Popen} 对象时将自动带上 @code{stdin=PIPE}，并且不能再手动指定 @emph{stdin} 参数。

如果 @emph{check} 设为 True, 并且进程以非零状态码退出, 一个 @ref{d85,,CalledProcessError} 异常将被抛出. 这个异常的属性将设置为参数, 退出码, 以及标准输出和标准错误, 如果被捕获到.

如果 @emph{encoding} 或者 @emph{error} 被指定, 或者 @emph{text} 被设为 True, 标准输入, 标准输出和标准错误的文件对象将通过指定的 @emph{encoding} 和 @emph{errors} 以文本模式打开, 否则以默认的 @ref{6f4,,io.TextIOWrapper} 打开. @emph{universal_newline} 参数等同于 @emph{text} 并且提供了向后兼容性. 默认情况下, 文件对象是以二进制模式打开的.

如果 @emph{env} 不是 @code{None}, 它必须是一个字典, 为新的进程设置环境变量; 它用于替换继承的当前进程的环境的默认行为. 它将直接被传递给 @ref{3e3,,Popen}.

例如:

@example
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'@w{'})
@end example


3.5 新版功能.



在 3.6 版更改: 添加了 @emph{encoding} 和 @emph{errors} 形参.



在 3.7 版更改: 添加了 @emph{text} 形参, 作为 @emph{universal_newlines} 的一个更好理解的别名. 添加了 @emph{capture_output} 形参.



在 3.9.17 版更改: Changed Windows shell search order for @code{shell=True}. The current
directory and @code{%PATH%} are replaced with @code{%COMSPEC%} and
@code{%SystemRoot%\System32\cmd.exe}. As a result, dropping a
malicious program named @code{cmd.exe} into a current directory no
longer works.

@end deffn

@geindex CompletedProcess (subprocess 中的类)
@anchor{library/subprocess subprocess CompletedProcess}@anchor{859}
@deffn {类} subprocess.CompletedProcess

@ref{4fb,,run()} 的返回值, 代表一个进程已经结束.

@geindex args (subprocess.CompletedProcess 属性)
@anchor{library/subprocess subprocess CompletedProcess args}@anchor{25c1}
@deffn {属性} args

被用作启动进程的参数. 可能是一个列表或字符串.
@end deffn

@geindex returncode (subprocess.CompletedProcess 属性)
@anchor{library/subprocess subprocess CompletedProcess returncode}@anchor{25c2}
@deffn {属性} returncode

子进程的退出状态码. 通常来说, 一个为 0 的退出码表示进程运行正常.

一个负值 @code{-N} 表示子进程被信号 @code{N} 中断 (仅 POSIX).
@end deffn

@geindex stdout (subprocess.CompletedProcess 属性)
@anchor{library/subprocess subprocess CompletedProcess stdout}@anchor{25c3}
@deffn {属性} stdout

从子进程捕获到的标准输出. 一个字节序列, 或一个字符串, 如果 @ref{4fb,,run()} 是设置了 @emph{encoding}, @emph{errors} 或者 @code{text=True} 来运行的. 如果未有捕获, 则为 @code{None}.

如果你通过 @code{stderr=subprocess.STDOUT} 运行进程，标准输入和标准错误将被组合在这个属性中，并且 @ref{25c4,,stderr} 将为 @code{None}。
@end deffn

@geindex stderr (subprocess.CompletedProcess 属性)
@anchor{library/subprocess subprocess CompletedProcess stderr}@anchor{25c4}
@deffn {属性} stderr

捕获到的子进程的标准错误. 一个字节序列, 或者一个字符串, 如果 @ref{4fb,,run()} 是设置了参数 @emph{encoding}, @emph{errors} 或者 @code{text=True} 运行的. 如果未有捕获, 则为 @code{None}.
@end deffn

@geindex check_returncode() (subprocess.CompletedProcess 方法)
@anchor{library/subprocess subprocess CompletedProcess check_returncode}@anchor{25c5}
@deffn {方法} check_returncode ()

如果 @ref{25c2,,returncode} 非零, 抛出 @ref{d85,,CalledProcessError}.
@end deffn


3.5 新版功能.

@end deffn

@geindex DEVNULL() (在 subprocess 模块中)
@anchor{library/subprocess subprocess DEVNULL}@anchor{b81}
@deffn {数据} subprocess.DEVNULL

可被 @ref{3e3,,Popen} 的 @emph{stdin}, @emph{stdout} 或者 @emph{stderr} 参数使用的特殊值, 表示使用特殊文件 @ref{119b,,os.devnull}.


3.3 新版功能.

@end deffn

@geindex PIPE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess PIPE}@anchor{4fc}
@deffn {数据} subprocess.PIPE

可被 @ref{3e3,,Popen} 的 @emph{stdin}, @emph{stdout} 或者 @emph{stderr} 参数使用的特殊值, 表示打开标准流的管道. 常用于 @ref{25bf,,Popen.communicate()}.
@end deffn

@geindex STDOUT() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STDOUT}@anchor{25c6}
@deffn {数据} subprocess.STDOUT

可被 @ref{3e3,,Popen} 的 @emph{stdin} ， @emph{stdout} 或者 @emph{stderr} 参数使用的特殊值， 表示标准错误与标准输出使用同一句柄。
@end deffn

@geindex SubprocessError
@anchor{library/subprocess subprocess SubprocessError}@anchor{25c7}
@deffn {例外} subprocess.SubprocessError

此模块的其他异常的基类。


3.3 新版功能.

@end deffn

@geindex TimeoutExpired
@anchor{library/subprocess subprocess TimeoutExpired}@anchor{25c0}
@deffn {例外} subprocess.TimeoutExpired

@ref{25c7,,SubprocessError} 的子类，等待子进程的过程中发生超时时被抛出。

@geindex cmd (subprocess.TimeoutExpired 属性)
@anchor{library/subprocess subprocess TimeoutExpired cmd}@anchor{25c8}
@deffn {属性} cmd

用于创建子进程的指令。
@end deffn

@geindex timeout (subprocess.TimeoutExpired 属性)
@anchor{library/subprocess subprocess TimeoutExpired timeout}@anchor{25c9}
@deffn {属性} timeout

超时秒数。
@end deffn

@geindex output (subprocess.TimeoutExpired 属性)
@anchor{library/subprocess subprocess TimeoutExpired output}@anchor{25ca}
@deffn {属性} output

Output of the child process if it was captured by @ref{4fb,,run()} or
@ref{9ca,,check_output()}.  Otherwise, @code{None}.  This is always
@ref{172,,bytes} when any output was captured regardless of the
@code{text=True} setting.  It may remain @code{None} instead of @code{b'@w{'}}
when no output was observed.
@end deffn

@geindex stdout (subprocess.TimeoutExpired 属性)
@anchor{library/subprocess subprocess TimeoutExpired stdout}@anchor{25cb}
@deffn {属性} stdout

对 output 的别名，对应的有 @ref{25cc,,stderr}。
@end deffn

@geindex stderr (subprocess.TimeoutExpired 属性)
@anchor{library/subprocess subprocess TimeoutExpired stderr}@anchor{25cc}
@deffn {属性} stderr

Stderr output of the child process if it was captured by @ref{4fb,,run()}.
Otherwise, @code{None}.  This is always @ref{172,,bytes} when stderr output
was captured regardless of the @code{text=True} setting.  It may remain
@code{None} instead of @code{b'@w{'}} when no stderr output was observed.
@end deffn


3.3 新版功能.



在 3.5 版更改: 添加了 @emph{stdout} 和 @emph{stderr} 属性。

@end deffn

@geindex CalledProcessError
@anchor{library/subprocess subprocess CalledProcessError}@anchor{d85}
@deffn {例外} subprocess.CalledProcessError

@ref{25c7,,SubprocessError} 的子类，当一个由 @ref{25cd,,check_call()}, @ref{9ca,,check_output()} 或 @ref{4fb,,run()} (附带 @code{check=True}) 运行的进程返回了非零退出状态码时将被引发。

@geindex returncode (subprocess.CalledProcessError 属性)
@anchor{library/subprocess subprocess CalledProcessError returncode}@anchor{25ce}
@deffn {属性} returncode

子进程的退出状态。如果程序由一个信号终止，这将会被设为一个负的信号码。
@end deffn

@geindex cmd (subprocess.CalledProcessError 属性)
@anchor{library/subprocess subprocess CalledProcessError cmd}@anchor{25cf}
@deffn {属性} cmd

用于创建子进程的指令。
@end deffn

@geindex output (subprocess.CalledProcessError 属性)
@anchor{library/subprocess subprocess CalledProcessError output}@anchor{25d0}
@deffn {属性} output

子进程的输出， 如果被 @ref{4fb,,run()} 或 @ref{9ca,,check_output()} 捕获。否则为 @code{None}。
@end deffn

@geindex stdout (subprocess.CalledProcessError 属性)
@anchor{library/subprocess subprocess CalledProcessError stdout}@anchor{25d1}
@deffn {属性} stdout

对 output 的别名，对应的有 @ref{25d2,,stderr}。
@end deffn

@geindex stderr (subprocess.CalledProcessError 属性)
@anchor{library/subprocess subprocess CalledProcessError stderr}@anchor{25d2}
@deffn {属性} stderr

子进程的标准错误输出，如果被 @ref{4fb,,run()} 捕获。 否则为 @code{None}。
@end deffn


在 3.5 版更改: 添加了 @emph{stdout} 和 @emph{stderr} 属性。

@end deffn

@menu
* 常用参数:: 
* Popen 构造函数:: 
* 异常: 异常<7>. 

@end menu

@node 常用参数,Popen 构造函数,,使用 subprocess 模块
@anchor{library/subprocess frequently-used-arguments}@anchor{25be}@anchor{library/subprocess id1}@anchor{25d3}
@subsubsection 常用参数


为了支持丰富的使用案例， @ref{3e3,,Popen} 的构造函数（以及方便的函数）接受大量可选的参数。对于大多数典型的用例，许多参数可以被安全地留以它们的默认值。通常需要的参数有：

@quotation

@emph{args} 被所有调用需要，应当为一个字符串，或者一个程序参数序列。提供一个参数序列通常更好，它可以更小心地使用参数中的转义字符以及引用（例如允许文件名中的空格）。如果传递一个简单的字符串，则 @emph{shell} 参数必须为 @ref{59c,,True} （见下文）或者该字符串中将被运行的程序名必须用简单的命名而不指定任何参数。

@emph{stdin}, @emph{stdout} 和 @emph{stderr} 分别指定了被执行程序的标准输入、标准输出和标准错误文件句柄。 合法的值包括 @ref{4fc,,PIPE}、@ref{b81,,DEVNULL}、现存的文件描述符（一个正整数）、现存的带有合法文件描述符的文件对象以及 @code{None}。 @ref{4fc,,PIPE} 表示应该新建一个连接子进程的管道。 @ref{b81,,DEVNULL} 表示将使用特殊的文件 @ref{119b,,os.devnull}。 当使用默认设置 @code{None} 时，将不会进行任何重定向；子进程的文件流将继承自父进程。 另外，@emph{stderr} 可以为 @ref{25c6,,STDOUT}，这表示来自子进程的 stderr 数据应当被捕获到与 @emph{stdout} 相同的文件句柄中。

@geindex universal newlines; subprocess module

如果 @emph{encoding} 或 @emph{errors} 被指定，或者 @emph{text} （也名为 @emph{universal_newlines}）为真，则文件对象 @emph{stdin} 、 @emph{stdout} 与 @emph{stderr} 将会使用在此次调用中指定的 @emph{encoding} 和 @emph{errors} 以文本模式打开或者为默认的 @ref{6f4,,io.TextIOWrapper}。

当构造函数的 @emph{newline} 参数为 @code{None} 时。对于 @emph{stdin}， 输入的换行符 @code{'\n'} 将被转换为默认的换行符 @ref{1762,,os.linesep}。对于 @emph{stdout} 和 @emph{stderr}， 所有输出的换行符都被转换为 @code{'\n'}。更多信息，查看 @ref{6f4,,io.TextIOWrapper} 类的文档。

如果文本模式未被使用， @emph{stdin}， @emph{stdout} 和 @emph{stderr} 将会以二进制流模式打开。没有编码与换行符转换发生。


3.6 新版功能: 添加了 @emph{encoding} 和 @emph{errors} 形参。



3.7 新版功能: 添加了 @emph{text} 形参作为 @emph{universal_newlines} 的别名。


@cartouche
@quotation 注解 
文件对象 @ref{25d4,,Popen.stdin} 、 @ref{25d5,,Popen.stdout} 和 @ref{25d6,,Popen.stderr} 的换行符属性不会被 @ref{25bf,,Popen.communicate()} 方法更新。
@end quotation
@end cartouche

如果 @emph{shell} 设为 @code{True},，则使用 shell 执行指定的指令。如果您主要使用 Python 增强的控制流（它比大多数系统 shell 提供的强大），并且仍然希望方便地使用其他 shell 功能，如 shell 管道、文件通配符、环境变量展开以及 @code{~} 展开到用户家目录，这将非常有用。但是，注意 Python 自己也实现了许多类似 shell 的特性（例如 @ref{88,,glob}, @ref{7f,,fnmatch}, @ref{751,,os.walk()}, @ref{e11,,os.path.expandvars()}, @ref{333,,os.path.expanduser()} 和 @ref{e9,,shutil}）。


在 3.3 版更改: 当 @emph{universal_newline} 被设为 @code{True}，则类使用 @ref{4b4,,locale.getpreferredencoding(False)} 编码来代替 @code{locale.getpreferredencoding()}。关于它们的区别的更多信息，见 @ref{6f4,,io.TextIOWrapper}。


@cartouche
@quotation 注解 
在使用 @code{shell=True} 之前， 请阅读 @ref{25d7,,Security Considerations} 段落。
@end quotation
@end cartouche
@end quotation

这些选项以及所有其他选项在 @ref{3e3,,Popen} 构造函数文档中有更详细的描述。

@node Popen 构造函数,异常<7>,常用参数,使用 subprocess 模块
@anchor{library/subprocess popen-constructor}@anchor{25d8}
@subsubsection Popen 构造函数


此模块的底层的进程创建与管理由 @ref{3e3,,Popen} 类处理。它提供了很大的灵活性，因此开发者能够处理未被便利函数覆盖的不常见用例。

@geindex Popen (subprocess 中的类)
@anchor{library/subprocess subprocess Popen}@anchor{3e3}
@deffn {类} subprocess.Popen (args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None)

在一个新的进程中执行子程序。在 POSIX，此类使用类似于 @ref{211c,,os.execvp()} 的行为来执行子程序。在 Windows，此类使用了 Windows @code{CreateProcess()} 函数。 @ref{3e3,,Popen} 的参数如下：

@emph{args} 应当是一个程序参数的序列或者是一个单独的字符串或 @ref{47b,,path-like object}。 默认情况下，如果 @emph{args} 是序列则要运行的程序为 @emph{args} 中的第一项。 如果 @emph{args} 是字符串，则其解读依赖于具体平台，如下所述。 请查看 @emph{shell} 和 @emph{executable} 参数了解其与默认行为的其他差异。 除非另有说明，否则推荐以序列形式传入 @emph{args}。

向外部函数传入序列形式参数的一个例子如下:

@example
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
@end example

在 POSIX，如果 @emph{args} 是一个字符串，此字符串被作为将被执行的程序的命名或路径解释。但是，只有在不传递任何参数给程序的情况下才能这么做。

@cartouche
@quotation 注解 
将 shell 命令拆分为参数序列的方式可能并不很直观，特别是在复杂的情况下。 @ref{211,,shlex.split()} 可以演示如何确定 @emph{args} 适当的拆分形式:

@example
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
@end example

特别注意，由 shell 中的空格分隔的选项（例如 @emph{-input}）和参数（例如 @emph{eggs.txt} ）位于分开的列表元素中，而在需要时使用引号或反斜杠转义的参数在 shell （例如包含空格的文件名或上面显示的 @emph{echo} 命令）是单独的列表元素。
@end quotation
@end cartouche

在 Windows，如果 @emph{args} 是一个序列，他将通过一个在 @ref{25d9,,在 Windows 上将参数列表转换为一个字符串} 描述的方式被转换为一个字符串。这是因为底层的 @code{CreateProcess()} 只处理字符串。


在 3.6 版更改: 在 POSIX 上如果 @emph{shell} 为 @code{False} 并且序列包含路径类对象则 @emph{args} 形参可以接受一个 @ref{47b,,path-like object}。



在 3.8 版更改: 如果在Windows 上 @emph{shell} 为 @code{False} 并且序列包含字节串和路径类对象则 @emph{args} 形参可以接受一个 @ref{47b,,path-like object}。


参数 @emph{shell} （默认为 @code{False}）指定是否使用 shell 执行程序。如果 @emph{shell} 为 @code{True}，更推荐将 @emph{args} 作为字符串传递而非序列。

在 POSIX，当 @code{shell=True}， shell 默认为 @code{/bin/sh}。如果 @emph{args} 是一个字符串，此字符串指定将通过 shell 执行的命令。这意味着字符串的格式必须和在命令提示符中所输入的完全相同。这包括，例如，引号和反斜杠转义包含空格的文件名。如果 @emph{args} 是一个序列，第一项指定了命令，另外的项目将作为传递给 shell （而非命令） 的参数对待。也就是说， @ref{3e3,,Popen} 等同于:

@example
Popen(['/bin/sh', '-c', args[0], args[1], ...])
@end example

在 Windows，使用 @code{shell=True}，环境变量 
@geindex COMSPEC
@geindex 环境变量; COMSPEC
@code{COMSPEC} 指定了默认 shell。在 Windows 你唯一需要指定 @code{shell=True} 的情况是你想要执行内置在 shell 中的命令（例如 @code{dir} 或者 @code{copy}）。在运行一个批处理文件或者基于控制台的可执行文件时，不需要 @code{shell=True}。

@cartouche
@quotation 注解 
在使用 @code{shell=True} 之前， 请阅读 @ref{25d7,,Security Considerations} 段落。
@end quotation
@end cartouche

@emph{bufsize} 将在 @ref{16f,,open()} 函数创建了 stdin/stdout/stderr 管道文件对象时作为对应的参数供应:


@itemize -

@item 
@code{0} 表示不使用缓冲区 （读取与写入是一个系统调用并且可以返回短内容）

@item 
@code{1} 表示行缓冲（只有 @code{universal_newlines=True} 时才有用，例如，在文本模式中）

@item 
任何其他正值表示使用一个约为对应大小的缓冲区

@item 
负的 @emph{bufsize} （默认）表示使用系统默认的 io.DEFAULT_BUFFER_SIZE。
@end itemize


在 3.3.1 版更改: @emph{bufsize} 现在默认为 -1 来启用缓冲，以符合大多数代码所期望的行为。在 Python 3.2.4 和 3.3.1 之前的版本中，它错误地将默认值设为了为 @code{0}，这是无缓冲的并且允许短读取。这是无意的，并且与大多数代码所期望的 Python 2 的行为不一致。


@emph{executable} 参数指定一个要执行的替换程序。这很少需要。当 @code{shell=True}， @emph{executable} 替换 @emph{args} 指定运行的程序。但是，原始的 @emph{args} 仍然被传递给程序。大多数程序将被 @emph{args} 指定的程序作为命令名对待，这可以与实际运行的程序不同。在 POSIX， @emph{args} 名作为实际调用程序中可执行文件的显示名称，例如 @code{ps}。如果 @code{shell=True}，在 POSIX， @emph{executable} 参数指定用于替换默认 shell @code{/bin/sh} 的 shell。


在 3.6 版更改: 在POSIX 上 @emph{executable} 形参可以接受一个 @ref{47b,,path-like object}。



在 3.8 版更改: 在Windows 上 @emph{executable} 形参可以接受一个字节串和 @ref{47b,,path-like object}。



在 3.9.17 版更改: Changed Windows shell search order for @code{shell=True}. The current
directory and @code{%PATH%} are replaced with @code{%COMSPEC%} and
@code{%SystemRoot%\System32\cmd.exe}. As a result, dropping a
malicious program named @code{cmd.exe} into a current directory no
longer works.


@emph{stdin}, @emph{stdout} 和 @emph{stderr} 分别指定了被执行程序的标准输入、标准输出和标准错误文件句柄。 合法的值包括 @ref{4fc,,PIPE}、@ref{b81,,DEVNULL}、现存的文件描述符（一个正整数）、现存的带有合法文件描述符的 @ref{c1d,,file object} 以及 @code{None}。 @ref{4fc,,PIPE} 表示应该新建一个连接子进程的管道。 @ref{b81,,DEVNULL} 表示将使用特殊的文件 @ref{119b,,os.devnull}。 当使用默认设置 @code{None} 时，将不会进行任何重定向；子进程的文件流将继承自父进程。 另外，@emph{stderr} 可以为 @ref{25c6,,STDOUT}，这表示来自子进程的 stderr 数据应当被捕获到与 stdout 相同的文件句柄中。

如果 @emph{preexec_fn} 被设为一个可调用对象，此对象将在子进程刚创建时被调用。（仅 POSIX）

@cartouche
@quotation 警告 
@emph{preexec_fn} 形参在应用程序中存在多线程时是不安全的。子进程在调用前可能死锁。如果你必须使用它，保持警惕！最小化你调用的库的数量。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果你需要修改子进程环境，使用 @emph{env} 形参而非在 @emph{preexec_fn} 中进行。 @emph{start_new_session} 形参可以代替之前常用的 @emph{preexec_fn} 来在子进程中调用 os.setsid()。
@end quotation
@end cartouche


在 3.8 版更改: @emph{preexec_fn} 形参在子解释器中已不再受支持。 在子解释器中使用此形参将引发 @ref{3e4,,RuntimeError}。 这个新限制可能会影响部署在 mod_wsgi, uWSGI 和其他嵌入式环境中的应用。


如果 @emph{close_fds} 为真，所有文件描述符除了 @code{0}, @code{1}, @code{2} 之外都会在子进程执行前关闭。而当 @emph{close_fds} 为假时，文件描述符遵守它们继承的标志，如 @ref{8f1,,文件描述符的继承} 所述。

在 Windows，如果 @emph{close_fds} 为真， 则子进程不会继承任何句柄，除非在 @code{STARTUPINFO.IpAttributeList} 的 @code{handle_list} 的键中显式传递，或者通过标准句柄重定向传递。


在 3.2 版更改: @emph{close_fds} 的默认值已经从 @ref{497,,False} 修改为上述值。



在 3.7 版更改: 在 Windows，当重定向标准句柄时 @emph{close_fds} 的默认值从 @ref{497,,False} 变为 @ref{59c,,True}。现在重定向标准句柄时有可能设置 @emph{close_fds} 为 @ref{59c,,True}。（标准句柄指三个 stdio 的句柄）


@emph{pass_fds} 是一个可选的在父子进程间保持打开的文件描述符序列。提供任何 @emph{pass_fds} 将强制 @emph{close_fds} 为 @ref{59c,,True}。（仅 POSIX）


在 3.2 版更改: 加入了 @emph{pass_fds} 形参。


如果 @emph{cwd} 不为 @code{None}，此函数在执行子进程前会将当前工作目录改为 @emph{cwd}。 @emph{cwd} 可以是一个字符串、字节串或 @ref{47b,,路径类对象} 。 特别地，当可执行文件的路径为相对路径时，此函数会相对于*cwd* 来查找 @emph{executable} (或 @emph{args} 中的第一个条目)。


在 3.6 版更改: 在 POSIX 上 @emph{cwd} 形参接受一个 @ref{47b,,path-like object}。



在 3.7 版更改: 在 Windows 上 @emph{cwd} 形参接受一个 @ref{47b,,path-like object}。



在 3.8 版更改: 在 Windows 上 @emph{cwd} 形参接受一个字节串对象。


 如果 @emph{restore_signals} 为 true（默认值），则 Python 设置为 SIG_IGN 的所有信号将在 exec 之前的子进程中恢复为 SIG_DFL。目前，这包括 SIGPIPE ，SIGXFZ 和 SIGXFSZ 信号。 （仅 POSIX）


在 3.2 版更改: @emph{restore_signals} 被加入。


如果 @emph{start_new_session} 为 true，则 setsid() 系统调用将在子进程执行之前被执行。（仅 POSIX）


在 3.2 版更改: @emph{start_new_session} 被添加。


如果 @emph{group} 不为 @code{None}，则 setregid() 系统调用将于子进程执行之前在下级进程中进行。 如果所提供的值为一个字符串，将通过 @ref{11ab,,grp.getgrnam()} 来查找它，并将使用 @code{gr_gid} 中的值。 如果该值为一个整数，它将被原样传递。 （POSIX 专属）

@ref{14c1,,可用性}: POSIX


3.9 新版功能.


如果 @emph{extra_groups} 不为 @code{None}，则 setgroups() 系统调用将于子进程之前在下级进程中进行。 在 @emph{extra_groups} 中提供的字符串将通过 @ref{11ab,,grp.getgrnam()} 来查找，并将使用 @code{gr_gid} 中的值。 整数值将被原样传递。 （POSIX 专属）

@ref{14c1,,可用性}: POSIX


3.9 新版功能.


如果 @emph{user} 不为 @code{None}，则 setreuid() 系统调用将于子进程执行之前在下级进程中进行。 如果所提供的值为一个字符串，将通过 @ref{11aa,,pwd.getpwnam()} 来查找它，并将使用 @code{pw_uid} 中的值。 如果该值为一个整数，它将被原样传递。 （POSIX 专属）

@ref{14c1,,可用性}: POSIX


3.9 新版功能.


如果 @emph{umask} 不为负值，则 umask() 系统调用将在子进程执行之前在下级进程中进行。

@ref{14c1,,可用性}: POSIX


3.9 新版功能.


如果 @emph{env} 不为 @code{None}，则必须为一个为新进程定义了环境变量的字典；这些用于替换继承的当前进程环境的默认行为。

@cartouche
@quotation 注解 
如果指定， @emph{env} 必须提供所有被子进程需求的变量。在 Windows，为了运行一个 side-by-side assembly@footnote{https://en.wikipedia.org/wiki/Side-by-Side_Assembly} ，指定的 @emph{env} @strong{必须} 包含一个有效的 
@geindex SystemRoot
@geindex 环境变量; SystemRoot
@code{SystemRoot}。
@end quotation
@end cartouche

如果 @emph{encoding} 或 @emph{errors} 被指定，或者 @emph{text} 为 true，则文件对象 @emph{stdin}, @emph{stdout} 和 @emph{stderr} 将会以指定的编码和 @emph{errors} 以文本模式打开，如同 @ref{25be,,常用参数} 所述。 @emph{universal_newlines} 参数等同于 @emph{text} 并且提供向后兼容性。默认情况下，文件对象都以二进制模式打开。


3.6 新版功能: @emph{encoding} 和 @emph{errors} 被添加。



3.7 新版功能: @emph{text} 作为 @emph{universal_newlines} 的一个更具可读性的别名被添加。


如果给出， @emph{startupinfo} 将是一个将被传递给底层的 @code{CreateProcess} 函数的 @ref{25da,,STARTUPINFO} 对象。 @emph{creationflags}，如果给出，可以是一个或多个以下标志之一：

@quotation


@itemize *

@item 
@ref{25db,,CREATE_NEW_CONSOLE}

@item 
@ref{25dc,,CREATE_NEW_PROCESS_GROUP}

@item 
@ref{25dd,,ABOVE_NORMAL_PRIORITY_CLASS}

@item 
@ref{25de,,BELOW_NORMAL_PRIORITY_CLASS}

@item 
@ref{25df,,HIGH_PRIORITY_CLASS}

@item 
@ref{25e0,,IDLE_PRIORITY_CLASS}

@item 
@ref{25e1,,NORMAL_PRIORITY_CLASS}

@item 
@ref{25e2,,REALTIME_PRIORITY_CLASS}

@item 
@ref{25e3,,CREATE_NO_WINDOW}

@item 
@ref{25e4,,DETACHED_PROCESS}

@item 
@ref{25e5,,CREATE_DEFAULT_ERROR_MODE}

@item 
@ref{25e6,,CREATE_BREAKAWAY_FROM_JOB}
@end itemize
@end quotation

Popen 对象支持通过 @ref{7e4,,with} 语句作为上下文管理器，在退出时关闭文件描述符并等待进程:

@example
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
@end example

引发一个 @ref{fec,,审计事件} @code{subprocess.Popen}，附带参数 @code{executable}, @code{args}, @code{cwd}, @code{env}。


在 3.2 版更改: 添加了上下文管理器支持。



在 3.6 版更改: 现在，如果 Popen 析构时子进程仍然在运行，则析构器会发送一个 @ref{5d3,,ResourceWarning} 警告。



在 3.8 版更改: 在某些情况下 Popen 可以使用 @ref{388,,os.posix_spawn()} 以获得更好的性能。在适用于 Linux 的 Windows 子系统和 QEMU 用户模拟器上，使用 @ref{388,,os.posix_spawn()} 的 Popen 构造器不再会因找不到程序等错误而引发异常，而是上下级进程失败并返回一个非零的 @ref{10ee,,returncode}。

@end deffn

@node 异常<7>,,Popen 构造函数,使用 subprocess 模块
@anchor{library/subprocess exceptions}@anchor{25e7}
@subsubsection 异常


在子进程中抛出的异常，在新的进程开始执行前，将会被再次在父进程中抛出。

被引发的最一般异常是 @ref{30b,,OSError}。 例如这会在尝试执行一个不存在的文件时发生。 应用程序应当为 @ref{30b,,OSError} 异常做好准备。 请注意，如果 @code{shell=True}，则 @ref{30b,,OSError} 仅会在未找到选定的 shell 本身时被引发。 要确定 shell 是否未找到所请求的应用程序，必须检查来自子进程的返回码或输出。

如果 @ref{3e3,,Popen} 调用时有无效的参数，则一个 @ref{16d,,ValueError} 将被抛出。

@ref{25cd,,check_call()} 与 @ref{9ca,,check_output()} 在调用的进程返回非零退出码时将抛出 @ref{d85,,CalledProcessError}。

所有接受 @emph{timeout} 形参的函数与方法，例如 @ref{4fd,,call()} 和 @ref{25bf,,Popen.communicate()} 将会在进程退出前超时到期时抛出 @ref{25c0,,TimeoutExpired}。

此模块中定义的异常都继承自 @ref{25c7,,SubprocessError}。

@quotation


3.3 新版功能: 基类 @ref{25c7,,SubprocessError} 被添加。

@end quotation

@node 安全考量<2>,Popen 对象,使用 subprocess 模块,subprocess --- 子进程管理
@anchor{library/subprocess security-considerations}@anchor{25d7}@anchor{library/subprocess subprocess-security}@anchor{25e8}
@subsubsection 安全考量


不像一些其他的 popen 功能，此实现绝不会隐式调用一个系统 shell。这意味着任何字符，包括 shell 元字符，可以安全地被传递给子进程。如果 shell 被明确地调用，通过 @code{shell=True} 设置，则确保所有空白字符和元字符被恰当地包裹在引号内以避免 shell 注入@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection} 漏洞就由应用程序负责了。

当使用 @code{shell=True}， @ref{b57,,shlex.quote()} 函数可以作为在将被用于构造 shell 指令的字符串中转义空白字符以及 shell 元字符的方案。

@node Popen 对象,Windows Popen 助手,安全考量<2>,subprocess --- 子进程管理
@anchor{library/subprocess popen-objects}@anchor{25e9}
@subsubsection Popen 对象


@ref{3e3,,Popen} 类的实例拥有以下方法：

@geindex poll() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen poll}@anchor{25ea}
@deffn {方法} Popen.poll ()

检查子进程是否已被终止。设置并返回 @ref{10ee,,returncode} 属性。否则返回 @code{None}。
@end deffn

@geindex wait() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen wait}@anchor{693}
@deffn {方法} Popen.wait (timeout=None)

等待子进程被终止。设置并返回 @ref{10ee,,returncode} 属性。

如果进程在 @emph{timeout} 秒后未中断，抛出一个 @ref{25c0,,TimeoutExpired} 异常，可以安全地捕获此异常并重新等待。

@cartouche
@quotation 注解 
当 @code{stdout=PIPE} 或者 @code{stderr=PIPE} 并且子进程产生了足以阻塞 OS 管道缓冲区接收更多数据的输出到管道时，将会发生死锁。当使用管道时用 @ref{25bf,,Popen.communicate()} 来规避它。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
此函数使用了一个 busy loop （非阻塞调用以及短睡眠） 实现。使用 @ref{9,,asyncio} 模块进行异步等待： 参阅 @ref{3bc,,asyncio.create_subprocess_exec}。
@end quotation
@end cartouche


在 3.3 版更改: @emph{timeout} 被添加

@end deffn

@geindex communicate() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen communicate}@anchor{25bf}
@deffn {方法} Popen.communicate (input=None, timeout=None)

与进程交互：将数据发送到 stdin。 从 stdout 和 stderr 读取数据，直到抵达文件结尾。 等待进程终止并设置 @ref{10ee,,returncode} 属性。 可选的 @emph{input} 参数应为要发送到下级进程的数据，或者如果没有要发送到下级进程的数据则为 @code{None}。 如果流是以文本模式打开的，则 @emph{input} 必须为字符串。 在其他情况下，它必须为字节串。

@ref{25bf,,communicate()} 返回一个 @code{(stdout_data, stderr_data)} 元组。如果文件以文本模式打开则为字符串；否则字节。

注意如果你想要向进程的 stdin 传输数据，你需要通过 @code{stdin=PIPE} 创建此 Popen 对象。类似的，要从结果元组获取任何非 @code{None} 值，你同样需要设置 @code{stdout=PIPE} 或者 @code{stderr=PIPE}。

如果进程在 @emph{timeout} 秒后未终止，一个 @ref{25c0,,TimeoutExpired} 异常将被抛出。捕获此异常并重新等待将不会丢失任何输出。

如果超时到期，子进程不会被杀死，所以为了正确清理一个行为良好的应用程序应该杀死子进程并完成通讯。

@example
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
@end example

@cartouche
@quotation 注解 
内存里数据读取是缓冲的，所以如果数据尺寸过大或无限，不要使用此方法。
@end quotation
@end cartouche


在 3.3 版更改: @emph{timeout} 被添加

@end deffn

@geindex send_signal() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen send_signal}@anchor{10ed}
@deffn {方法} Popen.send_signal (signal)

将信号 @emph{signal} 发送给子进程。

如果进程已完成则不做任何操作。

@cartouche
@quotation 注解 
在 Windows， SIGTERM 是一个 @ref{25eb,,terminate()} 的别名。 CTRL_C_EVENT 和 CTRL_BREAK_EVENT 可以被发送给以包含 @code{CREATE_NEW_PROCESS} 的 @emph{creationflags} 形参启动的进程。
@end quotation
@end cartouche
@end deffn

@geindex terminate() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen terminate}@anchor{25eb}
@deffn {方法} Popen.terminate ()

停止子进程。 在 POSIX 操作系统上，此方法会发送 SIGTERM 给子进程。 在 Windows 上则会调用 Win32 API 函数 @code{TerminateProcess()} 来停止子进程。
@end deffn

@geindex kill() (subprocess.Popen 方法)
@anchor{library/subprocess subprocess Popen kill}@anchor{25ec}
@deffn {方法} Popen.kill ()

杀死子进程。 在 POSIX 操作系统上，此函数会发送 SIGKILL 给子进程。 在 Windows 上 @ref{25ec,,kill()} 则是 @ref{25eb,,terminate()} 的别名。
@end deffn

以下属性也是可用的：

@geindex args (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen args}@anchor{25ed}
@deffn {属性} Popen.args

@emph{args} 参数传递给 @ref{3e3,,Popen} -- 一个程序参数的序列或者一个简单字符串。


3.3 新版功能.

@end deffn

@geindex stdin (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen stdin}@anchor{25d4}
@deffn {属性} Popen.stdin

如果 @emph{stdin} 参数为 @ref{4fc,,PIPE}，此属性是一个类似 @ref{16f,,open()} 返回的可写的流对象。如果 @emph{encoding} 或 @emph{errors} 参数被指定或者 @emph{universal_newlines} 参数为 @code{True}，则此流是一个文本流，否则是字节流。如果 @emph{stdin} 参数非 @ref{4fc,,PIPE}， 此属性为 @code{None}。
@end deffn

@geindex stdout (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen stdout}@anchor{25d5}
@deffn {属性} Popen.stdout

如果 @emph{stdout} 参数是 @ref{4fc,,PIPE}，此属性是一个类似 @ref{16f,,open()} 返回的可读流。从流中读取子进程提供的输出。如果 @emph{encoding} 或 @emph{errors} 参数被指定或者 @emph{universal_newlines} 参数为 @code{True}，此流为文本流，否则为字节流。如果 @emph{stdout} 参数非 @ref{4fc,,PIPE}，此属性为 @code{None}。
@end deffn

@geindex stderr (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen stderr}@anchor{25d6}
@deffn {属性} Popen.stderr

如果 @emph{stderr} 参数是 @ref{4fc,,PIPE}，此属性是一个类似 @ref{16f,,open()} 返回的可读流。从流中读取子进程提供的输出。如果 @emph{encoding} 或 @emph{errors} 参数被指定或者 @emph{universal_newlines} 参数为 @code{True}，此流为文本流，否则为字节流。如果 @emph{stderr} 参数非 @ref{4fc,,PIPE}，此属性为 @code{None}。
@end deffn

@cartouche
@quotation 警告 
使用 @ref{25bf,,communicate()} 而非 @ref{25d4,,.stdin.write}， @ref{25d5,,.stdout.read} 或者 @ref{25d6,,.stderr.read} 来避免由于任意其他 OS 管道缓冲区被子进程填满阻塞而导致的死锁。
@end quotation
@end cartouche

@geindex pid (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen pid}@anchor{25ee}
@deffn {属性} Popen.pid

子进程的进程号。

注意如果你设置了 @emph{shell} 参数为 @code{True}，则这是生成的子 shell 的进程号。
@end deffn

@geindex returncode (subprocess.Popen 属性)
@anchor{library/subprocess subprocess Popen returncode}@anchor{10ee}
@deffn {属性} Popen.returncode

此进程的退出码，由 @ref{25ea,,poll()} 和 @ref{693,,wait()} 设置（以及直接由 @ref{25bf,,communicate()} 设置）。一个 @code{None} 值 表示此进程仍未结束。

一个负值 @code{-N} 表示子进程被信号 @code{N} 中断 (仅 POSIX).
@end deffn

@node Windows Popen 助手,较旧的高阶 API,Popen 对象,subprocess --- 子进程管理
@anchor{library/subprocess windows-popen-helpers}@anchor{25ef}
@subsubsection Windows Popen 助手


@ref{25da,,STARTUPINFO} 类和以下常数仅在 Windows 有效。

@geindex STARTUPINFO (subprocess 中的类)
@anchor{library/subprocess subprocess STARTUPINFO}@anchor{25da}
@deffn {类} subprocess.STARTUPINFO (*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

在 @ref{3e3,,Popen} 创建时部分支持 Windows 的 STARTUPINFO@footnote{https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx} 结构。接下来的属性仅能通过关键词参数设置。


在 3.7 版更改: 仅关键词参数支持被加入。


@geindex dwFlags (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO dwFlags}@anchor{25f0}
@deffn {属性} dwFlags

一个位域，用于确定属性 @ref{25da,,STARTUPINFO} 是否在进程创建窗口时使用。

@example
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
@end example
@end deffn

@geindex hStdInput (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdInput}@anchor{25f1}
@deffn {属性} hStdInput

如果 @ref{25f0,,dwFlags} 被指定为 @ref{25f2,,STARTF_USESTDHANDLES}，此值是进程的标准输入句柄，如果 @ref{25f2,,STARTF_USESTDHANDLES} 未指定，则默认的标准输入是键盘缓冲区。
@end deffn

@geindex hStdOutput (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdOutput}@anchor{25f3}
@deffn {属性} hStdOutput

如果 @ref{25f0,,dwFlags} 指定为 @ref{25f2,,STARTF_USESTDHANDLES}，此属性是进程的标准输出句柄。除此之外，此此属性将被忽略并且默认标准输出是控制台窗口缓冲区。
@end deffn

@geindex hStdError (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO hStdError}@anchor{25f4}
@deffn {属性} hStdError

如果 @ref{25f0,,dwFlags} 被指定为 @ref{25f2,,STARTF_USESTDHANDLES}，则此属性是进程的标准错误句柄。除此之外，此属性将被忽略并且默认标准错误为控制台窗口的缓冲区。
@end deffn

@geindex wShowWindow (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO wShowWindow}@anchor{25f5}
@deffn {属性} wShowWindow

如果 @ref{25f0,,dwFlags} 指定了 @ref{25f6,,STARTF_USESHOWWINDOW}，此属性可为能被指定为 函数 ShowWindow@footnote{https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx} 的nCmdShow 的形参的任意值，除了 @code{SW_SHOWDEFAULT}。如此之外，此属性被忽略。

@ref{25f7,,SW_HIDE} 被提供给此属性。它在 @ref{3e3,,Popen} 由 @code{shell=True} 调用时使用。
@end deffn

@geindex lpAttributeList (subprocess.STARTUPINFO 属性)
@anchor{library/subprocess subprocess STARTUPINFO lpAttributeList}@anchor{59d}
@deffn {属性} lpAttributeList

@code{STARTUPINFOEX} 给出的用于进程创建的额外属性字典，参阅 UpdateProcThreadAttribute@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx}。

支持的属性：


@table @asis

@item @strong{handle_list}

将被继承的句柄的序列。如果非空， @emph{close_fds} 必须为 true。

当传递给 @ref{3e3,,Popen} 构造函数时，这些句柄必须暂时地能被 @ref{8f5,,os.set_handle_inheritable()} 继承，否则 @ref{30b,,OSError} 将以 Windows error @code{ERROR_INVALID_PARAMETER} (87) 抛出。

@cartouche
@quotation 警告 
在多线程进程中，请谨慎使用，以便在将此功能与对继承所有句柄的其他进程创建函数（例如 @ref{e8e,,os.system()}）的并发调用相结合时，避免泄漏标记为可继承的句柄。这也应用于临时性创建可继承句柄的标准句柄重定向。
@end quotation
@end cartouche
@end table


3.7 新版功能.

@end deffn
@end deffn

@menu
* Windows 常数:: 

@end menu

@node Windows 常数,,,Windows Popen 助手
@anchor{library/subprocess windows-constants}@anchor{25f8}
@subsubsection Windows 常数


@ref{f9,,subprocess} 模块曝出以下常数。

@geindex STD_INPUT_HANDLE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STD_INPUT_HANDLE}@anchor{25f9}
@deffn {数据} subprocess.STD_INPUT_HANDLE

标准输入设备，这是控制台输入缓冲区 @code{CONIN$}。
@end deffn

@geindex STD_OUTPUT_HANDLE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STD_OUTPUT_HANDLE}@anchor{25fa}
@deffn {数据} subprocess.STD_OUTPUT_HANDLE

标准输出设备。最初，这是活动控制台屏幕缓冲区 @code{CONOUT$}。
@end deffn

@geindex STD_ERROR_HANDLE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STD_ERROR_HANDLE}@anchor{25fb}
@deffn {数据} subprocess.STD_ERROR_HANDLE

标准错误设备。最初，这是活动控制台屏幕缓冲区 @code{CONOUT$}。
@end deffn

@geindex SW_HIDE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess SW_HIDE}@anchor{25f7}
@deffn {数据} subprocess.SW_HIDE

隐藏窗口。另一个窗口将被激活。
@end deffn

@geindex STARTF_USESTDHANDLES() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STARTF_USESTDHANDLES}@anchor{25f2}
@deffn {数据} subprocess.STARTF_USESTDHANDLES

指明 @ref{25f1,,STARTUPINFO.hStdInput}, @ref{25f3,,STARTUPINFO.hStdOutput} 和 @ref{25f4,,STARTUPINFO.hStdError} 属性包含额外的信息。
@end deffn

@geindex STARTF_USESHOWWINDOW() (在 subprocess 模块中)
@anchor{library/subprocess subprocess STARTF_USESHOWWINDOW}@anchor{25f6}
@deffn {数据} subprocess.STARTF_USESHOWWINDOW

指明 @ref{25f5,,STARTUPINFO.wShowWindow} 属性包含额外的信息。
@end deffn

@geindex CREATE_NEW_CONSOLE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess CREATE_NEW_CONSOLE}@anchor{25db}
@deffn {数据} subprocess.CREATE_NEW_CONSOLE

新的进程将有新的控制台，而不是继承父进程的（默认）控制台。
@end deffn

@geindex CREATE_NEW_PROCESS_GROUP() (在 subprocess 模块中)
@anchor{library/subprocess subprocess CREATE_NEW_PROCESS_GROUP}@anchor{25dc}
@deffn {数据} subprocess.CREATE_NEW_PROCESS_GROUP

用于指明将创建一个新的进程组的 @ref{3e3,,Popen} @code{creationflags} 形参。 这个旗标对于在子进程上使用 @ref{dc1,,os.kill()} 来说是必须的。

如果指定了 @ref{25db,,CREATE_NEW_CONSOLE} 则这个旗标会被忽略。
@end deffn

@geindex ABOVE_NORMAL_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess ABOVE_NORMAL_PRIORITY_CLASS}@anchor{25dd}
@deffn {数据} subprocess.ABOVE_NORMAL_PRIORITY_CLASS

用于指明一个新进程将具有高于平均的优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex BELOW_NORMAL_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess BELOW_NORMAL_PRIORITY_CLASS}@anchor{25de}
@deffn {数据} subprocess.BELOW_NORMAL_PRIORITY_CLASS

用于指明一个新进程将具有低于平均的优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex HIGH_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess HIGH_PRIORITY_CLASS}@anchor{25df}
@deffn {数据} subprocess.HIGH_PRIORITY_CLASS

用于指明一个新进程将具有高优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex IDLE_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess IDLE_PRIORITY_CLASS}@anchor{25e0}
@deffn {数据} subprocess.IDLE_PRIORITY_CLASS

用于指明一个新进程将具有空闲（最低）优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex NORMAL_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess NORMAL_PRIORITY_CLASS}@anchor{25e1}
@deffn {数据} subprocess.NORMAL_PRIORITY_CLASS

用于指明一个新进程将具有正常（默认）优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex REALTIME_PRIORITY_CLASS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess REALTIME_PRIORITY_CLASS}@anchor{25e2}
@deffn {数据} subprocess.REALTIME_PRIORITY_CLASS

用于指明一个新进程将具有实时优先级的 @ref{3e3,,Popen} @code{creationflags} 形参。 你应当几乎永远不使用 REALTIME_PRIORITY_CLASS，因为这会中断管理鼠标输入、键盘输入以及后台磁盘刷新的系统线程。 这个类只适用于直接与硬件“对话”，或者执行短暂任务具有受限中断的应用。


3.7 新版功能.

@end deffn

@geindex CREATE_NO_WINDOW() (在 subprocess 模块中)
@anchor{library/subprocess subprocess CREATE_NO_WINDOW}@anchor{25e3}
@deffn {数据} subprocess.CREATE_NO_WINDOW

指明一个新进程将不会创建窗口的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@geindex DETACHED_PROCESS() (在 subprocess 模块中)
@anchor{library/subprocess subprocess DETACHED_PROCESS}@anchor{25e4}
@deffn {数据} subprocess.DETACHED_PROCESS

指明一个新进程将不会继承其父控制台的 @ref{3e3,,Popen} @code{creationflags} 形参。 这个值不能与 CREATE_NEW_CONSOLE 一同使用。


3.7 新版功能.

@end deffn

@geindex CREATE_DEFAULT_ERROR_MODE() (在 subprocess 模块中)
@anchor{library/subprocess subprocess CREATE_DEFAULT_ERROR_MODE}@anchor{25e5}
@deffn {数据} subprocess.CREATE_DEFAULT_ERROR_MODE

指明一个新进程不会继承调用方进程的错误模式的 @ref{3e3,,Popen} @code{creationflags} 形参。 新进程会转为采用默认的错误模式。 这个特性特别适用于运行时禁用硬错误的多线程 shell 应用。


3.7 新版功能.

@end deffn

@geindex CREATE_BREAKAWAY_FROM_JOB() (在 subprocess 模块中)
@anchor{library/subprocess subprocess CREATE_BREAKAWAY_FROM_JOB}@anchor{25e6}
@deffn {数据} subprocess.CREATE_BREAKAWAY_FROM_JOB

指明一个新进程不会关联到任务的 @ref{3e3,,Popen} @code{creationflags} 形参。


3.7 新版功能.

@end deffn

@node 较旧的高阶 API,使用 subprocess 模块替换旧函数,Windows Popen 助手,subprocess --- 子进程管理
@anchor{library/subprocess call-function-trio}@anchor{25bd}@anchor{library/subprocess older-high-level-api}@anchor{25fc}
@subsubsection 较旧的高阶 API


在 Python 3.5 之前，这三个函数组成了 subprocess 的高阶 API。 现在你可以在许多情况下使用 @ref{4fb,,run()}，但有大量现在代码仍会调用这些函数。

@geindex call() (在 subprocess 模块中)
@anchor{library/subprocess subprocess call}@anchor{4fd}
@deffn {函数} subprocess.call (args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

运行由 @emph{args} 所描述的命令。 等待命令完成，然后返回 @ref{10ee,,returncode} 属性。

需要捕获 stdout 或 stderr 的代码应当改用 @ref{4fb,,run()}:

@example
run(...).returncode
@end example

要屏蔽 stdout 或 stderr，可提供 @ref{b81,,DEVNULL} 这个值。

上面显示的参数只是常见的一些。 完整的函数签名与 @ref{3e3,,Popen} 构造器的相同 —— 此函数会将所提供的 @emph{timeout} 之外的全部参数直接传递给目标接口。

@cartouche
@quotation 注解 
请不要在此函数中使用 @code{stdout=PIPE} 或 @code{stderr=PIPE}。 如果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读取时它将会阻塞。
@end quotation
@end cartouche


在 3.3 版更改: @emph{timeout} 被添加



在 3.9.17 版更改: Changed Windows shell search order for @code{shell=True}. The current
directory and @code{%PATH%} are replaced with @code{%COMSPEC%} and
@code{%SystemRoot%\System32\cmd.exe}. As a result, dropping a
malicious program named @code{cmd.exe} into a current directory no
longer works.

@end deffn

@geindex check_call() (在 subprocess 模块中)
@anchor{library/subprocess subprocess check_call}@anchor{25cd}
@deffn {函数} subprocess.check_call (args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

附带参数运行命令。 等待命令完成。 如果返回码为零则正常返回，否则引发 @ref{d85,,CalledProcessError}。 @ref{d85,,CalledProcessError} 对象将在 @ref{25ce,,returncode} 属性中保存返回码。 如果 @ref{25cd,,check_call()} 无法开始进程则它将传播已被引发的异常。

需要捕获 stdout 或 stderr 的代码应当改用 @ref{4fb,,run()}:

@example
run(..., check=True)
@end example

要屏蔽 stdout 或 stderr，可提供 @ref{b81,,DEVNULL} 这个值。

上面显示的参数只是常见的一些。 完整的函数签名与 @ref{3e3,,Popen} 构造器的相同 —— 此函数会将所提供的 @emph{timeout} 之外的全部参数直接传递给目标接口。

@cartouche
@quotation 注解 
请不要在此函数中使用 @code{stdout=PIPE} 或 @code{stderr=PIPE}。 如果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读取时它将会阻塞。
@end quotation
@end cartouche


在 3.3 版更改: @emph{timeout} 被添加



在 3.9.17 版更改: Changed Windows shell search order for @code{shell=True}. The current
directory and @code{%PATH%} are replaced with @code{%COMSPEC%} and
@code{%SystemRoot%\System32\cmd.exe}. As a result, dropping a
malicious program named @code{cmd.exe} into a current directory no
longer works.

@end deffn

@geindex check_output() (在 subprocess 模块中)
@anchor{library/subprocess subprocess check_output}@anchor{9ca}
@deffn {函数} subprocess.check_output (args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

附带参数运行命令并返回其输出。

如果返回码非零则会引发 @ref{d85,,CalledProcessError}。 @ref{d85,,CalledProcessError} 对象将在 @ref{25ce,,returncode} 属性中保存返回码并在 @ref{25d0,,output} 属性中保存所有输出。

这相当于:

@example
run(..., check=True, stdout=PIPE).stdout
@end example

上面显示的参数只是常见的一些。 完整的函数签名与 @ref{4fb,,run()} 的大致相同 —— 大部分参数会通过该接口直接传递。 存在一个与 @ref{4fb,,run()} 行为不同的 API 差异：传递 @code{input=None} 的行为将与 @code{input=b'@w{'}} (或 @code{input='@w{'}}，具体取决于其他参数) 一样而不是使用父对象的标准输入文件处理。

默认情况下，此函数将把数据返回为已编码的字节串。 输出数据的实际编码格式将取决于发起调用的命令，因此解码为文本的操作往往需要在应用程序层级上进行处理。

此行为可以通过设置 @emph{text}, @emph{encoding}, @emph{errors} 或将 @emph{universal_newlines} 设为 @code{True} 来重载，具体描述见 @ref{25be,,常用参数} 和 @ref{4fb,,run()}。

要在结果中同时捕获标准错误，请使用 @code{stderr=subprocess.STDOUT}:

@example
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
@end example


3.1 新版功能.



在 3.3 版更改: @emph{timeout} 被添加



在 3.4 版更改: 增加了对 @emph{input} 关键字参数的支持。



在 3.6 版更改: 增加了 @emph{encoding} 和 @emph{errors}。 详情参见 @ref{4fb,,run()}。



3.7 新版功能: @emph{text} 作为 @emph{universal_newlines} 的一个更具可读性的别名被添加。



在 3.9.17 版更改: Changed Windows shell search order for @code{shell=True}. The current
directory and @code{%PATH%} are replaced with @code{%COMSPEC%} and
@code{%SystemRoot%\System32\cmd.exe}. As a result, dropping a
malicious program named @code{cmd.exe} into a current directory no
longer works.

@end deffn

@node 使用 subprocess 模块替换旧函数,旧式的 Shell 发起函数,较旧的高阶 API,subprocess --- 子进程管理
@anchor{library/subprocess replacing-older-functions-with-the-subprocess-module}@anchor{25fd}@anchor{library/subprocess subprocess-replacements}@anchor{bca}
@subsubsection 使用 @code{subprocess} 模块替换旧函数


在这一节中，"a 改为 b" 意味着 b 可以被用作 a 的替代。

@cartouche
@quotation 注解 
在这一节中的所有 "a" 函数会在找不到被执行的程序时（差不多）静默地失败；"b" 替代函数则会改为引发 @ref{30b,,OSError}。

此外，在使用 @ref{9ca,,check_output()} 时如果替代函数所请求的操作产生了非零返回值则将失败并引发 @ref{d85,,CalledProcessError}。 操作的输出仍能以所引发异常的 @ref{25d0,,output} 属性的方式被访问。
@end quotation
@end cartouche

在下列例子中，我们假定相关的函数都已从 @ref{f9,,subprocess} 模块中导入了。

@menu
* 替代 /bin/sh shell 命令替换:: 
* 替代 shell 管道:: 
* 替代 os.system(): 替代 os system. 
* 替代 os.spawn 函数族: 替代 os spawn 函数族. 
* 替代 os.popen()@comma{} os.popen2()@comma{} os.popen3(): 替代 os popen os popen2 os popen3. 
* 来自 popen2 模块的替代函数:: 

@end menu

@node 替代 /bin/sh shell 命令替换,替代 shell 管道,,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-bin-sh-shell-command-substitution}@anchor{25fe}
@subsubsection 替代 @code{/bin/sh} shell 命令替换


@example
output=$(mycmd myarg)
@end example

改为:

@example
output = check_output(["mycmd", "myarg"])
@end example

@node 替代 shell 管道,替代 os system,替代 /bin/sh shell 命令替换,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-shell-pipeline}@anchor{25ff}
@subsubsection 替代 shell 管道


@example
output=$(dmesg | grep hda)
@end example

改为:

@example
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
@end example

启动 p2 之后再执行 @code{p1.stdout.close()} 调用很重要，这是为了让 p1 能在 p2 先于 p1 退出时接收到 SIGPIPE。

另外，对于受信任的输入，shell 本身的管道支持仍然可被直接使用:

@example
output=$(dmesg | grep hda)
@end example

改为:

@example
output=check_output("dmesg | grep hda", shell=True)
@end example

@node 替代 os system,替代 os spawn 函数族,替代 shell 管道,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-os-system}@anchor{2600}
@subsubsection 替代 @code{os.system()}


@example
sts = os.system("mycmd" + " myarg")
# becomes
retcode = call("mycmd" + " myarg", shell=True)
@end example

注释:


@itemize *

@item 
通过 shell 来调用程序通常是不必要的。

@item 
@ref{4fd,,call()} 返回值的编码方式与 @ref{e8e,,os.system()} 的不同。

@item 
@ref{e8e,,os.system()} 函数在命令运行期间会忽略 SIGINT 和 SIGQUIT 信号，但调用方必须在使用 @ref{f9,,subprocess} 模块时分别执行此操作。
@end itemize

一个更现实的例子如下所示:

@example
try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)
@end example

@node 替代 os spawn 函数族,替代 os popen os popen2 os popen3,替代 os system,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-the-os-spawn-family}@anchor{2601}
@subsubsection 替代 @code{os.spawn} 函数族


P_NOWAIT 示例:

@example
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
@end example

P_WAIT 示例:

@example
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
@end example

Vector 示例:

@example
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
@end example

Environment 示例:

@example
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env=@{"PATH": "/usr/bin"@})
@end example

@node 替代 os popen os popen2 os popen3,来自 popen2 模块的替代函数,替代 os spawn 函数族,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-os-popen-os-popen2-os-popen3}@anchor{2602}
@subsubsection 替代 @code{os.popen()}, @code{os.popen2()}, @code{os.popen3()}


@example
(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
@end example

@example
(child_stdin,
 child_stdout,
 child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)
@end example

@example
(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
@end example

返回码以如下方式处理转写:

@example
pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print("There were some errors")
@end example

@node 来自 popen2 模块的替代函数,,替代 os popen os popen2 os popen3,使用 subprocess 模块替换旧函数
@anchor{library/subprocess replacing-functions-from-the-popen2-module}@anchor{2603}
@subsubsection 来自 @code{popen2} 模块的替代函数


@cartouche
@quotation 注解 
如果 popen2 函数的 cmd 参数是一个字符串，命令会通过 /bin/sh 来执行。 如果是一个列表，命令会被直接执行。
@end quotation
@end cartouche

@example
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
@end example

@example
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
@end example

@code{popen2.Popen3} 和 @code{popen2.Popen4} 基本上类似于 @ref{3e3,,subprocess.Popen}，不同之处在于:


@itemize *

@item 
@ref{3e3,,Popen} 如果执行失败会引发一个异常。

@item 
@emph{capturestderr} 参数被替换为 @emph{stderr} 参数。

@item 
必须指定 @code{stdin=PIPE} 和 @code{stdout=PIPE}。

@item 
popen2 默认会关闭所有文件描述符，但对于 @ref{3e3,,Popen} 你必须指明 @code{close_fds=True} 以才能在所有平台或较旧的 Python 版本中确保此行为。
@end itemize

@node 旧式的 Shell 发起函数,注释<2>,使用 subprocess 模块替换旧函数,subprocess --- 子进程管理
@anchor{library/subprocess legacy-shell-invocation-functions}@anchor{2604}
@subsubsection 旧式的 Shell 发起函数


此模块还提供了以下来自 2.x @code{commands} 模块的旧版函数。 这些操作会隐式地发起调用系统 shell 并且上文所描述的有关安全与异常处理一致性保证都不适用于这些函数。

@geindex getstatusoutput() (在 subprocess 模块中)
@anchor{library/subprocess subprocess getstatusoutput}@anchor{9cb}
@deffn {函数} subprocess.getstatusoutput (cmd)

返回在 shell 中执行 @emph{cmd} 产生的 @code{(exitcode, output)}。

在 shell 中以 @code{Popen.check_output()} 执行字符串 @emph{cmd} 并返回一个 2 元组 @code{(exitcode, output)}。 会使用当前区域设置的编码格式；请参阅 @ref{25be,,常用参数} 中的说明来了解详情。

末尾的一个换行符会从输出中被去除。 命令的退出码可被解读为子进程的返回码。 例如:

@example
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(1, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(127, 'sh: /bin/junk: not found')
>>> subprocess.getstatusoutput('/bin/kill $$')
(-15, '@w{'})
@end example

@ref{14c1,,可用性}: POSIX 和 Windows。


在 3.3.4 版更改: 添加了 Windows 支持。

此函数现在返回 (exitcode, output) 而不是像 Python 3.3.3 及更早的版本那样返回 (status, output)。 exitcode 的值与 @ref{10ee,,returncode} 相同。

@end deffn

@geindex getoutput() (在 subprocess 模块中)
@anchor{library/subprocess subprocess getoutput}@anchor{2605}
@deffn {函数} subprocess.getoutput (cmd)

返回在 shell 中执行 @emph{cmd} 产生的输出（stdout 和 stderr）。

类似于 @ref{9cb,,getstatusoutput()}，但退出码会被忽略并且返回值为包含命令输出的字符串。 例如:

@example
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'
@end example

@ref{14c1,,可用性}: POSIX 和 Windows。


在 3.3.4 版更改: 添加了 Windows 支持

@end deffn

@node 注释<2>,,旧式的 Shell 发起函数,subprocess --- 子进程管理
@anchor{library/subprocess notes}@anchor{2606}
@subsubsection 注释


@menu
* 在 Windows 上将参数列表转换为一个字符串:: 

@end menu

@node 在 Windows 上将参数列表转换为一个字符串,,,注释<2>
@anchor{library/subprocess converting-an-argument-sequence-to-a-string-on-windows}@anchor{2607}@anchor{library/subprocess converting-argument-sequence}@anchor{25d9}
@subsubsection 在 Windows 上将参数列表转换为一个字符串


在 Windows 上，@emph{args} 序列会被转换为可使用以下规则来解析的字符串（对应于 MS C 运行时所使用的规则）:


@enumerate 

@item 
参数以空白符分隔，即空格符或制表符。

@item 
用双引号标示的字符串会被解读为单个参数，而不再考虑其中的空白符。 一个参数可以嵌套用引号标示的字符串。

@item 
带有一个反斜杠前缀的双引号会被解读为双引号字面值。

@item 
反斜杠会按字面值解读，除非它是作为双引号的前缀。

@item 
如果反斜杠被作为双引号的前缀，则每个反斜杠对会被解读为一个反斜杠字面值。 如果反斜杠数量为奇数，则最后一个反斜杠会如规则 3 所描述的那样转义下一个双引号。
@end enumerate


@subsubheading 参见



@table @asis

@item @ref{e8,,shlex}

此模块提供了用于解析和转义命令行的函数。
@end table


@node sched --- 事件调度器,queue --- 一个同步的队列类,subprocess --- 子进程管理,并发执行
@anchor{library/sched doc}@anchor{2608}@anchor{library/sched module-sched}@anchor{e3}@anchor{library/sched sched-event-scheduler}@anchor{2609}
@subsection @code{sched} --- 事件调度器


@geindex sched (模块)

@strong{源码：} Lib/sched.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/sched.py}

@geindex event scheduling


__________________________________________________________________


@ref{e3,,sched} 模块定义了一个实现通用事件调度程序的类：

@geindex scheduler (sched 中的类)
@anchor{library/sched sched scheduler}@anchor{b52}
@deffn {类} sched.scheduler (timefunc=time.monotonic, delayfunc=time.sleep)

@ref{b52,,scheduler} 类定义了一个调度事件的通用接口。 它需要两个函数来实际处理“外部世界” —— @emph{timefunc} 应当不带参数地调用，并返回一个数字（“时间”，可以为任意单位）。 @emph{delayfunc} 函数应当带一个参数调用，与 @emph{timefunc} 的输出相兼容，并且应当延迟其所指定的时间单位。 每个事件运行后还将调用 @emph{delayfunc} 并传入参数 @code{0} 以允许其他线程有机会在多线程应用中运行。


在 3.3 版更改: @emph{timefunc} 和 @emph{delayfunc} 参数是可选的。



在 3.3 版更改: @ref{b52,,scheduler} 类可以安全的在多线程环境中使用。

@end deffn

示例:

@example
>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     s.enter(5, 1, print_time, kwargs=@{'a': 'keyword'@})
...     s.run()
...     print(time.time())
...
>>> print_some_times()
930343690.257
From print_time 930343695.274 positional
From print_time 930343695.275 keyword
From print_time 930343700.273 default
930343700.276
@end example

@menu
* 调度器对象:: 

@end menu

@node 调度器对象,,,sched --- 事件调度器
@anchor{library/sched id1}@anchor{260a}@anchor{library/sched scheduler-objects}@anchor{260b}
@subsubsection 调度器对象


@ref{b52,,scheduler} 实例拥有以下方法和属性：

@geindex enterabs() (sched.scheduler 方法)
@anchor{library/sched sched scheduler enterabs}@anchor{b54}
@deffn {方法} scheduler.enterabs (time, priority, action, argument=(), kwargs=@{@})

安排一个新事件。 @emph{time} 参数应该有一个数字类型兼容的返回值，与传递给构造函数的 @emph{timefunc} 函数的返回值兼容。 计划在相同 @emph{time} 的事件将按其 @emph{priority} 的顺序执行。 数字越小表示优先级越高。

执行事件意为执行 @code{action(*argument, **kwargs)}。 @emph{argument} 是包含有 @emph{action} 的位置参数的序列。 @emph{kwargs} 是包含 @emph{action} 的关键字参数的字典。

返回值是一个事件，可用于以后取消事件（ 参见 @ref{260c,,cancel()} ）。


在 3.3 版更改: @emph{argument} 参数是可选的。



在 3.3 版更改: 添加了 @emph{kwargs} 形参。

@end deffn

@geindex enter() (sched.scheduler 方法)
@anchor{library/sched sched scheduler enter}@anchor{b53}
@deffn {方法} scheduler.enter (delay, priority, action, argument=(), kwargs=@{@})

安排延后 @emph{delay} 时间单位的事件。 除了相对时间，其他参数、效果和返回值与 @ref{b54,,enterabs()} 的相同。


在 3.3 版更改: @emph{argument} 参数是可选的。



在 3.3 版更改: 添加了 @emph{kwargs} 形参。

@end deffn

@geindex cancel() (sched.scheduler 方法)
@anchor{library/sched sched scheduler cancel}@anchor{260c}
@deffn {方法} scheduler.cancel (event)

从队列中删除事件。 如果 @emph{event} 不是当前队列中的事件，则此方法将引发 @ref{16d,,ValueError}。
@end deffn

@geindex empty() (sched.scheduler 方法)
@anchor{library/sched sched scheduler empty}@anchor{260d}
@deffn {方法} scheduler.empty ()

如果事件队列为空则返回 @code{True}。
@end deffn

@geindex run() (sched.scheduler 方法)
@anchor{library/sched sched scheduler run}@anchor{b51}
@deffn {方法} scheduler.run (blocking=True)

运行所有预定事件。 此方法将等待（使用传递给构造函数的 @code{delayfunc()} 函数）进行下一个事件，然后执行它，依此类推，直到没有更多的计划事件。

如果 @emph{blocking} 为false，则执行由于最快到期（如果有）的预定事件，然后在调度程序中返回下一个预定调用的截止时间（如果有）。

@emph{action} 或 @emph{delayfunc} 都可以引发异常。 在任何一种情况下，调度程序都将保持一致状态并传播异常。 如果 @emph{action} 引发异常，则在将来调用 @ref{b51,,run()} 时不会尝试该事件。

如果一系列事件的运行时间大于下一个事件发生前的可用时间，那么调度程序将完全落后。 没有事件会被丢弃；调用代码负责取消不再相关的事件。


在 3.3 版更改: 添加了 @emph{blocking} 形参。

@end deffn

@geindex queue (sched.scheduler 属性)
@anchor{library/sched sched scheduler queue}@anchor{260e}
@deffn {属性} scheduler.queue

只读属性按照将要运行的顺序返回即将发生的事件列表。 每个事件都显示为 @ref{b84,,named tuple} ，包含以下字段：time、priority、action、argument、kwargs。
@end deffn

@node queue --- 一个同步的队列类,contextvars --- 上下文变量,sched --- 事件调度器,并发执行
@anchor{library/queue doc}@anchor{260f}@anchor{library/queue module-queue}@anchor{da}@anchor{library/queue queue-a-synchronized-queue-class}@anchor{2610}
@subsection @code{queue} --- 一个同步的队列类


@geindex queue (模块)

@strong{源代码:} Lib/queue.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/queue.py}


__________________________________________________________________


@ref{da,,queue} 模块实现了多生产者、多消费者队列。这特别适用于消息必须安全地在多线程间交换的线程编程。模块中的 @ref{de6,,Queue} 类实现了所有所需的锁定语义。

模块实现了三种类型的队列，它们的区别仅仅是条目取回的顺序。在 @abbr{FIFO} 队列中，先添加的任务先取回。在 @abbr{LIFO} 队列中，最近被添加的条目先取回(操作类似一个堆栈)。优先级队列中，条目将保持排序( 使用 @ref{8d,,heapq} 模块 ) 并且最小值的条目第一个返回。

在内部，这三个类型的队列使用锁来临时阻塞竞争线程；然而，它们并未被设计用于线程的重入性处理。

此外，模块实现了一个 "简单的"  @abbr{FIFO} 队列类型， @ref{4d5,,SimpleQueue} ，这个特殊实现为小功能在交换中提供额外的保障。

@ref{da,,queue} 模块定义了下列类和异常：

@geindex Queue (queue 中的类)
@anchor{library/queue queue Queue}@anchor{de6}
@deffn {类} queue.Queue (maxsize=0)

Constructor for a @abbr{FIFO} queue.  @emph{maxsize} is
an integer that sets the upperbound
limit on the number of items that can be placed in the queue.  Insertion will
block once this size has been reached, until queue items are consumed.  If
@emph{maxsize} is less than or equal to zero, the queue size is infinite.
@end deffn

@geindex LifoQueue (queue 中的类)
@anchor{library/queue queue LifoQueue}@anchor{1853}
@deffn {类} queue.LifoQueue (maxsize=0)

@abbr{LIFO} 队列构造函数。 @emph{maxsize} 是个整数，用于设置可以放入队列中的项目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消费掉。如果 @emph{maxsize} 小于等于零，队列尺寸为无限大。
@end deffn

@geindex PriorityQueue (queue 中的类)
@anchor{library/queue queue PriorityQueue}@anchor{1854}
@deffn {类} queue.PriorityQueue (maxsize=0)

优先级队列构造函数。 @emph{maxsize} 是个整数，用于设置可以放入队列中的项目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消费掉。如果 @emph{maxsize} 小于等于零，队列尺寸为无限大。

最小值先被取出( 最小值条目是由 @code{sorted(list(entries))[0]} 返回的条目)。条目的典型模式是一个以下形式的元组： @code{(priority_number, data)} 。

如果 @emph{data} 元素没有可比性，数据将被包装在一个类中，忽略数据值，仅仅比较优先级数字 ：

@example
from dataclasses import dataclass, field
from typing import Any

@@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)
@end example
@end deffn

@geindex SimpleQueue (queue 中的类)
@anchor{library/queue queue SimpleQueue}@anchor{4d5}
@deffn {类} queue.SimpleQueue

无界的 @abbr{FIFO} 队列构造函数。简单的队列，缺少任务跟踪等高级功能。


3.7 新版功能.

@end deffn

@geindex Empty
@anchor{library/queue queue Empty}@anchor{2525}
@deffn {例外} queue.Empty

对空的 @ref{de6,,Queue} 对象，调用非阻塞的 @ref{2611,,get()} (or  @ref{2612,,get_nowait()}) 时，引发的异常。
@end deffn

@geindex Full
@anchor{library/queue queue Full}@anchor{2526}
@deffn {例外} queue.Full

对满的 @ref{de6,,Queue} 对象，调用非阻塞的 @ref{2613,,put()} (or @ref{2614,,put_nowait()}) 时，引发的异常。
@end deffn

@menu
* Queue对象:: 
* SimpleQueue 对象:: 

@end menu

@node Queue对象,SimpleQueue 对象,,queue --- 一个同步的队列类
@anchor{library/queue queue-objects}@anchor{2615}@anchor{library/queue queueobjects}@anchor{2616}
@subsubsection Queue对象


队列对象 (@ref{de6,,Queue}, @ref{1853,,LifoQueue}, 或者 @ref{1854,,PriorityQueue}) 提供下列描述的公共方法。

@geindex qsize() (queue.Queue 方法)
@anchor{library/queue queue Queue qsize}@anchor{2617}
@deffn {方法} Queue.qsize ()

返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞，qsize() < maxsize 也不保证 put() 不被阻塞。
@end deffn

@geindex empty() (queue.Queue 方法)
@anchor{library/queue queue Queue empty}@anchor{2618}
@deffn {方法} Queue.empty ()

如果队列为空，返回 @code{True} ，否则返回 @code{False} 。如果 empty() 返回 @code{True} ，不保证后续调用的 put() 不被阻塞。类似的，如果 empty() 返回 @code{False} ，也不保证后续调用的 get() 不被阻塞。
@end deffn

@geindex full() (queue.Queue 方法)
@anchor{library/queue queue Queue full}@anchor{2619}
@deffn {方法} Queue.full ()

如果队列是满的返回 @code{True} ，否则返回 @code{False} 。如果 full() 返回 @code{True} 不保证后续调用的 get() 不被阻塞。类似的，如果 full() 返回 @code{False} 也不保证后续调用的 put() 不被阻塞。
@end deffn

@geindex put() (queue.Queue 方法)
@anchor{library/queue queue Queue put}@anchor{2613}
@deffn {方法} Queue.put (item, block=True, timeout=None)

将 @emph{item} 放入队列。如果可选参数 @emph{block} 是 true 并且 @emph{timeout} 是 @code{None} (默认)，则在必要时阻塞至有空闲插槽可用。如果 @emph{timeout} 是个正数，将最多阻塞 @emph{timeout} 秒，如果在这段时间没有可用的空闲插槽，将引发 @ref{2526,,Full} 异常。反之 (@emph{block} 是 false)，如果空闲插槽立即可用，则把 @emph{item} 放入队列，否则引发 @ref{2526,,Full} 异常 ( 在这种情况下，@emph{timeout} 将被忽略)。
@end deffn

@geindex put_nowait() (queue.Queue 方法)
@anchor{library/queue queue Queue put_nowait}@anchor{2614}
@deffn {方法} Queue.put_nowait (item)

相当于 @code{put(item, block=False)}。
@end deffn

@geindex get() (queue.Queue 方法)
@anchor{library/queue queue Queue get}@anchor{2611}
@deffn {方法} Queue.get (block=True, timeout=None)

从队列中移除并返回一个项目。如果可选参数 @emph{block} 是 true 并且 @emph{timeout} 是 @code{None} (默认值)，则在必要时阻塞至项目可得到。如果 @emph{timeout} 是个正数，将最多阻塞 @emph{timeout} 秒，如果在这段时间内项目不能得到，将引发 @ref{2525,,Empty} 异常。反之 (@emph{block} 是 false) , 如果一个项目立即可得到，则返回一个项目，否则引发 @ref{2525,,Empty} 异常 (这种情况下，@emph{timeout} 将被忽略)。

POSIX系统3.0之前，以及所有版本的Windows系统中，如果 @emph{block} 是 true 并且 @emph{timeout} 是 @code{None} ， 这个操作将进入基础锁的不间断等待。这意味着，没有异常能发生，尤其是 SIGINT 将不会触发 @ref{2d3,,KeyboardInterrupt} 异常。
@end deffn

@geindex get_nowait() (queue.Queue 方法)
@anchor{library/queue queue Queue get_nowait}@anchor{2612}
@deffn {方法} Queue.get_nowait ()

相当于 @code{get(False)} 。
@end deffn

提供了两个方法，用于支持跟踪 排队的任务 是否 被守护的消费者线程 完整的处理。

@geindex task_done() (queue.Queue 方法)
@anchor{library/queue queue Queue task_done}@anchor{2521}
@deffn {方法} Queue.task_done ()

表示前面排队的任务已经被完成。被队列的消费者线程使用。每个 @ref{2611,,get()} 被用于获取一个任务， 后续调用 @ref{2521,,task_done()} 告诉队列，该任务的处理已经完成。

如果 @ref{2522,,join()} 当前正在阻塞，在所有条目都被处理后，将解除阻塞(意味着每个 @ref{2613,,put()} 进队列的条目的 @ref{2521,,task_done()} 都被收到)。

如果被调用的次数多于放入队列中的项目数量，将引发 @ref{16d,,ValueError} 异常 。
@end deffn

@geindex join() (queue.Queue 方法)
@anchor{library/queue queue Queue join}@anchor{2522}
@deffn {方法} Queue.join ()

阻塞至队列中所有的元素都被接收和处理完毕。

当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者线程调用 @ref{2521,,task_done()} 表示这个条目已经被回收，该条目所有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候， @ref{2522,,join()} 阻塞被解除。
@end deffn

如何等待排队的任务被完成的示例：

@example
import threading, queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on @{item@}')
        print(f'Finished @{item@}')
        q.task_done()

# turn-on the worker thread
threading.Thread(target=worker, daemon=True).start()

# send thirty task requests to the worker
for item in range(30):
    q.put(item)
print('All task requests sent\n', end='@w{'})

# block until all tasks are done
q.join()
print('All work completed')
@end example

@node SimpleQueue 对象,,Queue对象,queue --- 一个同步的队列类
@anchor{library/queue simplequeue-objects}@anchor{261a}
@subsubsection SimpleQueue 对象


@ref{4d5,,SimpleQueue} 对象提供下列描述的公共方法。

@geindex qsize() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue qsize}@anchor{261b}
@deffn {方法} SimpleQueue.qsize ()

返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞。
@end deffn

@geindex empty() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue empty}@anchor{261c}
@deffn {方法} SimpleQueue.empty ()

如果队列为空，返回 @code{True} ，否则返回 @code{False} 。如果 empty() 返回 @code{False} ，不保证后续调用的 get() 不被阻塞。
@end deffn

@geindex put() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue put}@anchor{261d}
@deffn {方法} SimpleQueue.put (item, block=True, timeout=None)

将 @emph{item} 放入队列。此方法永不阻塞，始终成功（除了潜在的低级错误，例如内存分配失败）。可选参数 @emph{block} 和 @emph{timeout} 仅仅是为了保持 @ref{2613,,Queue.put()} 的兼容性而提供，其值被忽略。

@strong{CPython implementation detail:} This method has a C implementation which is reentrant.  That is, a
@code{put()} or @code{get()} call can be interrupted by another @code{put()}
call in the same thread without deadlocking or corrupting internal
state inside the queue.  This makes it appropriate for use in
destructors such as @code{__del__} methods or @ref{131,,weakref} callbacks.
@end deffn

@geindex put_nowait() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue put_nowait}@anchor{261e}
@deffn {方法} SimpleQueue.put_nowait (item)

相当于 @code{put(item, block=False)}，为保持与 @ref{2614,,Queue.put_nowait()} 的兼容性而提供。
@end deffn

@geindex get() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue get}@anchor{261f}
@deffn {方法} SimpleQueue.get (block=True, timeout=None)

从队列中移除并返回一个项目。如果可选参数 @emph{block} 是 true 并且 @emph{timeout} 是 @code{None} (默认值)，则在必要时阻塞至项目可得到。如果 @emph{timeout} 是个正数，将最多阻塞 @emph{timeout} 秒，如果在这段时间内项目不能得到，将引发 @ref{2525,,Empty} 异常。反之 (@emph{block} 是 false) , 如果一个项目立即可得到，则返回一个项目，否则引发 @ref{2525,,Empty} 异常 (这种情况下，@emph{timeout} 将被忽略)。
@end deffn

@geindex get_nowait() (queue.SimpleQueue 方法)
@anchor{library/queue queue SimpleQueue get_nowait}@anchor{2620}
@deffn {方法} SimpleQueue.get_nowait ()

相当于 @code{get(False)} 。
@end deffn


@subsubheading 参见



@table @asis

@item 类 @ref{f72,,multiprocessing.Queue}

一个用于多进程上下文的队列类（而不是多线程）。
@end table

@ref{633,,collections.deque} 是无界队列的一个替代实现，具有快速的不需要锁并且支持索引的原子化 @ref{1ad2,,append()} 和 @ref{1ad8,,popleft()} 操作。


@node contextvars --- 上下文变量,_thread --- 底层多线程 API,queue --- 一个同步的队列类,并发执行
@anchor{library/contextvars doc}@anchor{2621}@anchor{library/contextvars contextvars-context-variables}@anchor{2622}@anchor{library/contextvars module-contextvars}@anchor{24}
@subsection @code{contextvars} --- 上下文变量


@geindex contextvars (模块)


__________________________________________________________________


本模块提供了相关API用于管理、存储和访问上下文相关的状态。 @ref{2623,,ContextVar} 类用于声明 @emph{上下文变量} 并与其一起使用。函数 @ref{2624,,copy_context()}  和类 @ref{2625,,Context} 用于管理当前上下文和异步框架中。

在多并发环境中，有状态上下文管理器应该使用上下文变量，而不是 @ref{f57,,threading.local()} 来防止他们的状态意外泄露到其他代码。

更多信息参见  
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} 。


3.7 新版功能.


@menu
* 上下文变量:: 
* 手动上下文管理:: 
* asyncio 支持:: 

@end menu

@node 上下文变量,手动上下文管理,,contextvars --- 上下文变量
@anchor{library/contextvars context-variables}@anchor{2626}
@subsubsection 上下文变量


@geindex ContextVar (contextvars 中的类)
@anchor{library/contextvars contextvars ContextVar}@anchor{2623}
@deffn {类} contextvars.ContextVar (name[, *, default])

此类用于声明一个新的上下文变量，如:

@example
var: ContextVar[int] = ContextVar('var', default=42)
@end example

@emph{name} 参数用于内省和调试，必需。

调用 @ref{2627,,ContextVar.get()}  时，如果上下文中没有找到此变量的值，则返回可选的仅命名参数 @emph{default}  。

@strong{重要：} 上下文变量应该在顶级模块中创建，且永远不要在闭包中创建。  @ref{2625,,Context} 对象拥有对上下文变量的强引用，这可以让上下文变量被垃圾收集器正确回收。

@geindex name (contextvars.ContextVar 属性)
@anchor{library/contextvars contextvars ContextVar name}@anchor{2628}
@deffn {属性} name

上下文变量的名称，只读属性。


3.7.1 新版功能.

@end deffn

@geindex get() (contextvars.ContextVar 方法)
@anchor{library/contextvars contextvars ContextVar get}@anchor{2627}
@deffn {方法} get ([default])

返回当前上下文中此上下文变量的值。

如果当前上下文中此变量没有值，则此方法会:


@itemize *

@item 
如果提供了得 话，返回传入的 @emph{default} 值；或者

@item 
返回上下文变量本身的默认值， 如果创建此上下文变量时提供了默认值；或者

@item 
抛出  @ref{17c1,,LookupError} 异常。
@end itemize
@end deffn

@geindex set() (contextvars.ContextVar 方法)
@anchor{library/contextvars contextvars ContextVar set}@anchor{2629}
@deffn {方法} set (value)

调用此方法设置上下文变量在当前上下文中的值。

必选参数 @emph{value} 是上下文变量的新值。

返回一个 @ref{262a,,Token}  对象，可通过 @ref{262b,,ContextVar.reset()}  方法将上下文变量还原为之前某个状态。
@end deffn

@geindex reset() (contextvars.ContextVar 方法)
@anchor{library/contextvars contextvars ContextVar reset}@anchor{262b}
@deffn {方法} reset (token)

将上下文变量重置为调用 @ref{2629,,ContextVar.set()} 之前、创建 @emph{token} 时候的状态。

例如:

@example
var = ContextVar('var')

token = var.set('new value')
# code that uses 'var'; var.get() returns 'new value'.
var.reset(token)

# After the reset call the var has no value again, so
# var.get() would raise a LookupError.
@end example
@end deffn
@end deffn

@geindex Token (contextvars 中的类)
@anchor{library/contextvars contextvars Token}@anchor{262a}
@deffn {类} contextvars.Token

@ref{2629,,ContextVar.set()} 方法返回 @emph{Token} 对象。此对象可以传递给 @ref{262b,,ContextVar.reset()} 方法用于将上下文变量还原为调用 @emph{set} 前的状态。

@geindex var (contextvars.Token 属性)
@anchor{library/contextvars contextvars Token var}@anchor{262c}
@deffn {属性} var

只读属性。指向创建此 token 的 @ref{2623,,ContextVar} 对象。
@end deffn

@geindex old_value (contextvars.Token 属性)
@anchor{library/contextvars contextvars Token old_value}@anchor{262d}
@deffn {属性} old_value

一个只读属性。 会被设为在创建此令牌的 @ref{2629,,ContextVar.set()} 方法调用之前该变量所具有的值。 如果调用之前变量没有设置值，则它指向 @ref{262e,,Token.MISSING} 。
@end deffn

@geindex MISSING (contextvars.Token 属性)
@anchor{library/contextvars contextvars Token MISSING}@anchor{262e}
@deffn {属性} MISSING

@ref{262d,,Token.old_value} 会用到的一个标记对象。
@end deffn
@end deffn

@node 手动上下文管理,asyncio 支持,上下文变量,contextvars --- 上下文变量
@anchor{library/contextvars manual-context-management}@anchor{262f}
@subsubsection 手动上下文管理


@geindex copy_context() (在 contextvars 模块中)
@anchor{library/contextvars contextvars copy_context}@anchor{2624}
@deffn {函数} contextvars.copy_context ()

返回当前上下文中 @ref{2625,,Context} 对象的拷贝。

以下代码片段会获取当前上下文的拷贝并打印设置到其中的所有变量及其值:

@example
ctx: Context = copy_context()
print(list(ctx.items()))
@end example

此函数复杂度为 O(1) ，也就是说对于只包含几个上下文变量和很多上下文变量的情况，他们是一样快的。
@end deffn

@geindex Context (contextvars 中的类)
@anchor{library/contextvars contextvars Context}@anchor{2625}
@deffn {类} contextvars.Context

@ref{2623,,ContextVars} 中所有值的映射。

@code{Context()} 创建一个不包含任何值的空上下文。如果要获取当前上下文的拷贝，使用 @ref{2624,,copy_context()} 函数。

Every thread will have a different top-level @ref{2625,,Context}
object. This means that a @ref{2623,,ContextVar} object behaves in a similar
fashion to @ref{f57,,threading.local()} when values are assigned in different
threads.

Context 实现了 @ref{15f,,collections.abc.Mapping} 接口。

@geindex run() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context run}@anchor{2630}
@deffn {方法} run (callable, *args, **kwargs)

按照 @emph{run} 方法中的参数在上下文对象中执行 @code{callable(*args, **kwargs)} 代码。返回执行结果，如果发生异常，则将异常透传出来。

@emph{callable} 对上下文变量所做的任何修改都会保留在上下文对象中:

@example
var = ContextVar('var')
var.set('spam')

def main():
    # 'var' was set to 'spam' before
    # calling 'copy_context()' and 'ctx.run(main)', so:
    # var.get() == ctx[var] == 'spam'

    var.set('ham')

    # Now, after setting 'var' to 'ham':
    # var.get() == ctx[var] == 'ham'

ctx = copy_context()

# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)

# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'

# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'
@end example

当在多个系统线程或者递归调用同一个上下文对象的此方法，抛出 @ref{3e4,,RuntimeError} 异常。
@end deffn

@geindex copy() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context copy}@anchor{2631}
@deffn {方法} copy ()

返回此上下文对象的浅拷贝。
@end deffn


@deffn {Describe} var in context

如果*context* 中含有名称为 @emph{var} 的变量，返回 @code{True} ， 否则返回 @code{False} 。
@end deffn


@deffn {Describe} context[var]

返回名称为 @emph{var} 的 @ref{2623,,ContextVar} 变量。如果上下文对象中不包含这个变量，则抛出 @ref{3f1,,KeyError} 异常。
@end deffn

@geindex get() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context get}@anchor{2632}
@deffn {方法} get (var[, default])

如果 @emph{var} 在上下文对象中具有值则返回 @emph{var} 的值。 在其他情况下返回 @emph{default}。 如果未给出 @emph{default} 则返回 @code{None}。
@end deffn


@deffn {Describe} iter(context)

返回一个存储在上下文对象中的变量的迭代器。
@end deffn


@deffn {Describe} len(proxy)

返回上下文对象中所设的变量的数量。
@end deffn

@geindex keys() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context keys}@anchor{2633}
@deffn {方法} keys ()

返回上下文对象中的所有变量的列表。
@end deffn

@geindex values() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context values}@anchor{2634}
@deffn {方法} values ()

返回上下文对象中所有变量值的列表。
@end deffn

@geindex items() (contextvars.Context 方法)
@anchor{library/contextvars contextvars Context items}@anchor{2635}
@deffn {方法} items ()

返回包含上下文对象中所有变量及其值的 2 元组的列表。
@end deffn
@end deffn

@node asyncio 支持,,手动上下文管理,contextvars --- 上下文变量
@anchor{library/contextvars asyncio-support}@anchor{2636}
@subsubsection asyncio 支持


上下文变量在 @ref{9,,asyncio} 中有原生的支持并且无需任何额外配置即可被使用。 例如，以下是一个简单的回显服务器，它使用上下文变量来让远程客户端的地址在处理该客户端的 Task 中可用:

@example
import asyncio
import contextvars

client_addr_var = contextvars.ContextVar('client_addr')

def render_goodbye():
    # The address of the currently handled client can be accessed
    # without passing it explicitly to this function.

    client_addr = client_addr_var.get()
    return f'Good bye, client @@ @{client_addr@}\n'.encode()

async def handle_request(reader, writer):
    addr = writer.transport.get_extra_info('socket').getpeername()
    client_addr_var.set(addr)

    # In any code that we call is now possible to get
    # client's address by calling 'client_addr_var.get()'.

    while True:
        line = await reader.readline()
        print(line)
        if not line.strip():
            break
        writer.write(line)

    writer.write(render_goodbye())
    writer.close()

async def main():
    srv = await asyncio.start_server(
        handle_request, '127.0.0.1', 8081)

    async with srv:
        await srv.serve_forever()

asyncio.run(main())

# To test it you can use telnet:
#     telnet 127.0.0.1 8081
@end example

以下是上述某些服务的支持模块：

@node _thread --- 底层多线程 API,,contextvars --- 上下文变量,并发执行
@anchor{library/_thread doc}@anchor{2637}@anchor{library/_thread module-_thread}@anchor{2}@anchor{library/_thread thread-low-level-threading-api}@anchor{2638}
@subsection @code{_thread} --- 底层多线程 API


@geindex _thread (模块)

@geindex light-weight processes
@geindex processes@comma{} light-weight
@geindex binary semaphores
@geindex semaphores@comma{} binary


__________________________________________________________________


该模块提供了操作多个线程（也被称为 @emph{轻量级进程} 或 @emph{任务}）的底层原语 —— 多个控制线程共享全局数据空间。为了处理同步问题，也提供了简单的锁机制（也称为 @emph{互斥锁} 或 @emph{二进制信号}）。@ref{10b,,threading} 模块基于该模块提供了更易用的高级多线程 API。

@geindex pthreads
@geindex threads; POSIX


在 3.7 版更改: 这个模块曾经是可选的，但现在总是可用的。


这个模块定义了以下常量和函数：

@geindex error
@anchor{library/_thread _thread error}@anchor{2639}
@deffn {例外} _thread.error

发生线程相关错误时抛出。


在 3.3 版更改: 现在是内建异常 @ref{3e4,,RuntimeError} 的别名。

@end deffn

@geindex LockType() (在 _thread 模块中)
@anchor{library/_thread _thread LockType}@anchor{263a}
@deffn {数据} _thread.LockType

锁对象的类型。
@end deffn

@geindex start_new_thread() (在 _thread 模块中)
@anchor{library/_thread _thread start_new_thread}@anchor{1149}
@deffn {函数} _thread.start_new_thread (function, args[, kwargs])

开启一个新线程并返回其标识。 线程执行函数 @emph{function} 并附带参数列表 @emph{args} (必须是元组)。 可选的 @emph{kwargs} 参数指定一个关键字参数字典。

当函数返回时，线程会静默地退出。

当函数因某个未处理异常而终结时，@ref{361,,sys.unraisablehook()} 会被调用以处理异常。 钩子参数的 @emph{object} 属性为 @emph{function}。 在默认情况下，会打印堆栈回溯然后该线程将退出（但其他线程会继续运行）。

当函数引发 @ref{6fd,,SystemExit} 异常时，它会被静默地忽略。


在 3.8 版更改: 现在会使用 @ref{361,,sys.unraisablehook()} 来处理未处理的异常。

@end deffn

@geindex interrupt_main() (在 _thread 模块中)
@anchor{library/_thread _thread interrupt_main}@anchor{263b}
@deffn {函数} _thread.interrupt_main ()

模拟一个 @ref{263c,,signal.SIGINT} 信号到达主线程的效果。 线程可以使用这个函数来中断主线程。

如果 Python 没有处理 @ref{263c,,signal.SIGINT} (将它设为 @ref{263d,,signal.SIG_DFL} 或 @ref{263e,,signal.SIG_IGN})，此函数将不做任何事。
@end deffn

@geindex exit() (在 _thread 模块中)
@anchor{library/_thread _thread exit}@anchor{263f}
@deffn {函数} _thread.exit ()

抛出 @ref{6fd,,SystemExit} 异常。如果没有捕获的话，这个异常会使线程退出。
@end deffn

@c function:: exit_prog(status)
@c 
@c    Exit all threads and report the value of the integer argument
@c    *status* as the exit status of the entire program.
@c    **Caveat:** code in pending :keyword:`finally` clauses, in this thread
@c    or in other threads, is not executed.

@geindex allocate_lock() (在 _thread 模块中)
@anchor{library/_thread _thread allocate_lock}@anchor{2640}
@deffn {函数} _thread.allocate_lock ()

返回一个新的锁对象。锁中的方法在后面描述。初始情况下锁处于解锁状态。
@end deffn

@geindex get_ident() (在 _thread 模块中)
@anchor{library/_thread _thread get_ident}@anchor{2641}
@deffn {函数} _thread.get_ident ()

返回当前线程的 “线程描述符”。它是一个非零的整型数。它的值没有什么含义，主要是作为 magic cookie 使用，比如作为含有线程相关数据的字典的索引。线程描述符可能会在线程退出，新线程创建时复用。
@end deffn

@geindex get_native_id() (在 _thread 模块中)
@anchor{library/_thread _thread get_native_id}@anchor{2642}
@deffn {函数} _thread.get_native_id ()

返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后该值可能会被 OS 回收再利用）。

@ref{14c1,,可用性}: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX。


3.8 新版功能.

@end deffn

@geindex stack_size() (在 _thread 模块中)
@anchor{library/_thread _thread stack_size}@anchor{2643}
@deffn {函数} _thread.stack_size ([size])

返回新建线程时使用的堆栈大小。可选参数 @emph{size} 指定之后新建的线程的堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是32,768(32KiB)的一个正整数。如果*size*没有指定，默认是0。如果不支持改变线程堆栈大小，会抛出 @ref{3e4,,RuntimeError} 错误。如果指定的堆栈大小不合法，会抛出 @ref{16d,,ValueError} 错误并且不会修改堆栈大小。32KiB是当前最小的能保证解释器足够堆栈空间的堆栈大小。需要注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是使用4096的倍数作为堆栈大小）

@ref{14c1,,可用性}: Windows，具有 POSIX 线程的系统。
@end deffn

@geindex TIMEOUT_MAX() (在 _thread 模块中)
@anchor{library/_thread _thread TIMEOUT_MAX}@anchor{2644}
@deffn {数据} _thread.TIMEOUT_MAX

@code{Lock.acquire()} 方法中 @emph{timeout} 参数允许的最大值。传入超过这个值的 timeout 会抛出 @ref{a4a,,OverflowError} 异常。


3.2 新版功能.

@end deffn

锁对象有以下方法：

@geindex acquire() (_thread.lock 方法)
@anchor{library/_thread _thread lock acquire}@anchor{2645}
@deffn {方法} lock.acquire (waitflag=1, timeout=-1)

没有任何可选参数时，该方法无条件申请获得锁，有必要的话会等待其他线程释放锁（同时只有一个线程能获得锁 —— 这正是锁存在的原因）。

如果传入了整型参数 @emph{waitflag}，具体的行为取决于传入的值：如果是 0 的话，只会在能够立刻获取到锁时才获取，不会等待，如果是非零的话，会像之前提到的一样，无条件获取锁。

如果传入正浮点数参数 @emph{timeout}，相当于指定了返回之前等待得最大秒数。如果传入负的 @emph{timeout}，相当于无限期等待。如果 @emph{waitflag} 是 0 的话，不能指定 @emph{timeout}。

如果成功获取到所会返回 @code{True}，否则返回 @code{False}。


在 3.2 版更改: @emph{timeout} 形参是新增的。



在 3.2 版更改: 现在获取锁的操作可以被 POSIX 信号中断。

@end deffn

@geindex release() (_thread.lock 方法)
@anchor{library/_thread _thread lock release}@anchor{2646}
@deffn {方法} lock.release ()

释放锁。锁必须已经被获取过，但不一定是同一个线程获取的。
@end deffn

@geindex locked() (_thread.lock 方法)
@anchor{library/_thread _thread lock locked}@anchor{2647}
@deffn {方法} lock.locked ()

返回锁的状态：如果已被某个线程获取，返回 @code{True}，否则返回 @code{False}。
@end deffn

除了这些方法之外，锁对象也可以通过 @ref{7e4,,with} 语句使用，例如：

@example
import _thread

a_lock = _thread.allocate_lock()

with a_lock:
    print("a_lock is locked while this executes")
@end example

@strong{注意事项：}

@quotation

@geindex 模块; signal
@end quotation


@itemize *

@item 
线程与中断奇怪地交互：@ref{2d3,,KeyboardInterrupt} 异常可能会被任意一个线程捕获。（如果 @ref{ea,,signal} 模块可用的话，中断总是会进入主线程。）

@item 
调用 @ref{db2,,sys.exit()} 或是抛出 @ref{6fd,,SystemExit} 异常等效于调用 @ref{263f,,_thread.exit()}。

@item 
不可能中断锁的 @code{acquire()} 方法 —— @ref{2d3,,KeyboardInterrupt} 一场会在锁获取到之后发生。

@item 
当主线程退出时，由系统决定其他线程是否存活。在大多数系统中，这些线程会直接被杀掉，不会执行 @ref{e3f,,try} ... @ref{2c3,,finally} 语句，也不会执行对象析构函数。

@item 
当主线程退出时，不会进行正常的清理工作（除非使用了 @ref{e3f,,try} ... @ref{2c3,,finally} 语句），标准 I/O 文件也不会刷新。
@end itemize

@node 网络和进程间通信,互联网数据处理,并发执行,Python 标准库
@anchor{library/ipc doc}@anchor{2648}@anchor{library/ipc ipc}@anchor{2649}@anchor{library/ipc networking-and-interprocess-communication}@anchor{264a}
@section 网络和进程间通信


本章介绍的模块提供了网络和进程间通信的机制。

某些模块仅适用于同一台机器上的两个进程，例如 @ref{ea,,signal} 和 @ref{b3,,mmap} 。 其他模块支持两个或多个进程可用于跨机器通信的网络协议。

本章中描述的模块列表是：

@menu
* asyncio: asyncio --- 异步 I/O. 异步 I/O
* socket: socket --- 底层网络接口. 底层网络接口
* ssl: ssl --- 套接字对象的 TLS/SSL 包装器. 套接字对象的 TLS/SSL 包装器
* select: select --- 等待 I/O 完成. 等待 I/O 完成
* selectors: selectors --- 高级 I/O 复用库. 高级 I/O 复用库
* signal: signal --- 设置异步事件处理程序. 设置异步事件处理程序
* mmap: mmap --- 内存映射文件支持. 内存映射文件支持

@end menu

@node asyncio --- 异步 I/O,socket --- 底层网络接口,,网络和进程间通信
@anchor{library/asyncio doc}@anchor{264b}@anchor{library/asyncio asyncio-asynchronous-i-o}@anchor{264c}@anchor{library/asyncio module-asyncio}@anchor{9}
@subsection @code{asyncio} --- 异步 I/O


@geindex asyncio (模块)


__________________________________________________________________


@subsubheading Hello World!



@example
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
@end example

asyncio 是用来编写 @strong{并发} 代码的库，使用 @strong{async/await} 语法。

asyncio 被用作多个提供高性能 Python 异步框架的基础，包括网络和网站服务，数据库连接库，分布式任务队列等等。

asyncio 往往是构建 IO 密集型和高层级 @strong{结构化} 网络代码的最佳选择。

asyncio 提供一组 @strong{高层级} API 用于:


@itemize *

@item 
并发地 @ref{264d,,运行 Python 协程} 并对其执行过程实现完全控制;

@item 
执行 @ref{264e,,网络 IO 和 IPC};

@item 
控制 @ref{264f,,子进程};

@item 
通过 @ref{2650,,队列} 实现分布式任务;

@item 
@ref{2651,,同步} 并发代码;
@end itemize

此外，还有一些 @strong{低层级} API 以支持 @emph{库和框架的开发者} 实现:


@itemize *

@item 
创建和管理 @ref{741,,事件循环}，以提供异步 API 用于 @ref{46e,,网络化}, 运行 @ref{2652,,子进程}，处理 @ref{2653,,OS 信号} 等等;

@item 
使用 @ref{2654,,transports} 实现高效率协议;

@item 
通过 async/await 语法 @ref{2655,,桥接} 基于回调的库和代码。
@end itemize

@c We use the "rubric" directive here to avoid creating
@c the "Reference" subsection in the TOC.

@subsubheading 参考引用


@menu
* 协程与任务:: 
* 流:: 
* 同步原语: 同步原语<2>. 
* 子进程:: 
* 队列集:: 
* 异常: 异常<9>. 
* 事件循环:: 
* Futures:: 
* 传输和协议:: 
* 策略:: 
* 平台支持:: 
* 高层级 API 索引:: 
* 低层级 API 索引:: 
* 用 asyncio 开发:: 

@end menu

@node 协程与任务,流,,asyncio --- 异步 I/O
@anchor{library/asyncio-task doc}@anchor{2656}@anchor{library/asyncio-task coroutines-and-tasks}@anchor{2657}
@subsubsection 协程与任务


本节将简述用于协程与任务的高层级 API。

@menu
* 协程: 协程<3>. 
* 可等待对象: 可等待对象<2>. 
* 运行 asyncio 程序:: 
* 创建任务:: 
* 休眠:: 
* 并发运行任务:: 
* 屏蔽取消操作:: 
* 超时:: 
* 简单等待:: 
* 在线程中运行:: 
* 跨线程调度:: 
* 内省:: 
* Task 对象:: 
* 基于生成器的协程:: 

@end menu

@node 协程<3>,可等待对象<2>,,协程与任务
@anchor{library/asyncio-task coroutine}@anchor{264d}@anchor{library/asyncio-task coroutines}@anchor{2658}
@subsubsection 协程


通过 async/await 语法来声明 @ref{18a,,协程} 是编写 asyncio 应用的推荐方式。 例如，以下代码段会打印 "hello"，等待 1 秒，再打印 "world":

@example
>>> import asyncio

>>> async def main():
...     print('hello')
...     await asyncio.sleep(1)
...     print('world')

>>> asyncio.run(main())
hello
world
@end example

注意：简单地调用一个协程并不会使其被调度执行

@example
>>> main()
<coroutine object main at 0x1053bb7c8>
@end example

要真正运行一个协程，asyncio 提供了三种主要机制:


@itemize *

@item 
@ref{18d,,asyncio.run()} 函数用来运行最高层级的入口点 "main()" 函数 (参见上面的示例。)

@item 
等待一个协程。以下代码段会在等待 1 秒后打印 "hello"，然后 @emph{再次} 等待 2 秒后打印 "world":

@example
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at @{time.strftime('%X')@}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at @{time.strftime('%X')@}")

asyncio.run(main())
@end example

预期的输出:

@example
started at 17:13:52
hello
world
finished at 17:13:55
@end example

@item 
@ref{2e8,,asyncio.create_task()} 函数用来并发运行作为 asyncio @ref{2e7,,任务} 的多个协程。

让我们修改以上示例，@emph{并发} 运行两个 @code{say_after} 协程:

@example
async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at @{time.strftime('%X')@}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at @{time.strftime('%X')@}")
@end example

注意，预期的输出显示代码段的运行时间比之前快了 1 秒:

@example
started at 17:14:32
hello
world
finished at 17:14:34
@end example
@end itemize

@node 可等待对象<2>,运行 asyncio 程序,协程<3>,协程与任务
@anchor{library/asyncio-task asyncio-awaitables}@anchor{2659}@anchor{library/asyncio-task awaitables}@anchor{265a}
@subsubsection 可等待对象


如果一个对象可以在 @ref{2df,,await}  语句中使用，那么它就是 @strong{可等待} 对象。许多 asyncio API 都被设计为接受可等待对象。

@emph{可等待} 对象有三种主要类型: @strong{协程}, @strong{任务} 和 @strong{Future}.

@subsubheading 协程


Python 协程属于 @emph{可等待} 对象，因此可以在其他协程中被等待:

@example
import asyncio

async def nested():
    return 42

async def main():
    # Nothing happens if we just call "nested()".
    # A coroutine object is created but not awaited,
    # so it *won't run at all*.
    nested()

    # Let's do it differently now and await it:
    print(await nested())  # will print "42".

asyncio.run(main())
@end example

@cartouche
@quotation 重要 
在本文档中 "协程" 可用来表示两个紧密关联的概念:


@itemize *

@item 
@emph{协程函数}: 定义形式为 @ref{3b1,,async def} 的函数;

@item 
@emph{协程对象}: 调用 @emph{协程函数} 所返回的对象。
@end itemize
@end quotation
@end cartouche

asyncio 也支持旧式的 @ref{265b,,基于生成器的} 协程。

@subsubheading 任务


@emph{任务} 被用来“并行的”调度协程

当一个协程通过 @ref{2e8,,asyncio.create_task()} 等函数被封装为一个 @emph{任务}，该协程会被自动调度执行:

@example
import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

asyncio.run(main())
@end example

@subsubheading Future 对象


@ref{54e,,Future} 是一种特殊的 @strong{低层级} 可等待对象，表示一个异步操作的 @strong{最终结果}。

当一个 Future 对象 @emph{被等待}，这意味着协程将保持等待直到该 Future 对象在其他地方操作完毕。

在 asyncio 中需要 Future 对象以便允许通过 async/await 使用基于回调的代码。

通常情况下 @strong{没有必要} 在应用层级的代码中创建 Future 对象。

Future 对象有时会由库和某些 asyncio API 暴露给用户，用作可等待对象:

@example
async def main():
    await function_that_returns_a_future_object()

    # this is also valid:
    await asyncio.gather(
        function_that_returns_a_future_object(),
        some_python_coroutine()
    )
@end example

一个很好的返回对象的低层级函数的示例是 @ref{190,,loop.run_in_executor()}。

@node 运行 asyncio 程序,创建任务,可等待对象<2>,协程与任务
@anchor{library/asyncio-task running-an-asyncio-program}@anchor{265c}
@subsubsection 运行 asyncio 程序


@geindex run() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio run}@anchor{18d}
@deffn {函数} asyncio.run (coro, *, debug=False)

执行 @ref{18a,,coroutine} @emph{coro} 并返回结果。

此函数会运行传入的协程，负责管理 asyncio 事件循环，@emph{终结异步生成器}，并关闭线程池。

当有其他 asyncio 事件循环在同一线程中运行时，此函数不能被调用。

如果 @emph{debug} 为 @code{True}，事件循环将以调试模式运行。

此函数总是会创建一个新的事件循环并在结束时关闭之。它应当被用作  asyncio 程序的主入口点，理想情况下应当只被调用一次。

示例:

@example
async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())
@end example


3.7 新版功能.



在 3.9 版更改: 更新为使用 @ref{18b,,loop.shutdown_default_executor()}。


@cartouche
@quotation 注解 
@code{asyncio.run()} 的源代码可以在 Lib/asyncio/runners.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/runners.py} 中找到。
@end quotation
@end cartouche
@end deffn

@node 创建任务,休眠,运行 asyncio 程序,协程与任务
@anchor{library/asyncio-task creating-tasks}@anchor{265d}
@subsubsection 创建任务


@geindex create_task() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio create_task}@anchor{2e8}
@deffn {函数} asyncio.create_task (coro, *, name=None)

将 @emph{coro} @ref{264d,,协程} 封装为一个 @ref{2e7,,Task} 并调度其执行。返回 Task 对象。

@emph{name} 不为 @code{None}，它将使用 @ref{2ea,,Task.set_name()} 来设为任务的名称。

该任务会在 @ref{465,,get_running_loop()} 返回的循环中执行，如果当前线程没有在运行的循环则会引发 @ref{3e4,,RuntimeError}。

@cartouche
@quotation 重要 
保存一个指向此函数的结果的引用，以避免任务在执行期间消失。
@end quotation
@end cartouche


3.7 新版功能.



在 3.8 版更改: 添加了 @code{name} 形参。

@end deffn

@node 休眠,并发运行任务,创建任务,协程与任务
@anchor{library/asyncio-task sleeping}@anchor{265e}
@subsubsection 休眠


@geindex sleep() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio sleep}@anchor{3b2}
@deffn {函数} coroutine asyncio.sleep (delay, result=None, *, loop=None)

阻塞 @emph{delay} 指定的秒数。

如果指定了 @emph{result}，则当协程完成时将其返回给调用者。

@code{sleep()} 总是会挂起当前任务，以允许其他任务运行。

将 delay 设为 0 将提供一个经优化的路径以允许其他任务运行。 这可供长期间运行的函数使用以避免在函数调用的全过程中阻塞事件循环。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@anchor{library/asyncio-task asyncio-example-sleep}@anchor{265f}
以下协程示例运行 5 秒，每秒显示一次当前日期:

@example
import asyncio
import datetime

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())
@end example
@end deffn

@node 并发运行任务,屏蔽取消操作,休眠,协程与任务
@anchor{library/asyncio-task running-tasks-concurrently}@anchor{2660}
@subsubsection 并发运行任务


@geindex gather() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio gather}@anchor{3b3}
@deffn {函数} awaitable asyncio.gather (*aws, loop=None, return_exceptions=False)

@emph{并发} 运行 @emph{aws} 序列中的 @ref{2659,,可等待对象}。

如果 @emph{aws} 中的某个可等待对象为协程，它将自动被作为一个任务调度。

如果所有可等待对象都成功完成，结果将是一个由所有返回值聚合而成的列表。结果值的顺序与 @emph{aws} 中可等待对象的顺序一致。

如果 @emph{return_exceptions} 为 @code{False} (默认)，所引发的首个异常会立即传播给等待 @code{gather()} 的任务。@emph{aws} 序列中的其他可等待对象 @strong{不会被取消} 并将继续运行。

如果 @emph{return_exceptions} 为 @code{True}，异常会和成功的结果一样处理，并聚合至结果列表。

如果 @code{gather()} @emph{被取消}，所有被提交 (尚未完成) 的可等待对象也会 @emph{被取消}。

如果 @emph{aws} 序列中的任一 Task 或 Future 对象 @emph{被取消}，它将被当作引发了 @ref{2e1,,CancelledError} 一样处理 -- 在此情况下 @code{gather()} 调用 @strong{不会} 被取消。这是为了防止一个已提交的 Task/Future 被取消导致其他 Tasks/Future 也被取消。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@anchor{library/asyncio-task asyncio-example-gather}@anchor{2661}
示例:

@example
import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task @{name@}: Compute factorial(@{number@}), currently i=@{i@}...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task @{name@}: factorial(@{number@}) = @{f@}")
    return f

async def main():
    # Schedule three calls *concurrently*:
    L = await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2), currently i=2...
#     Task B: Compute factorial(3), currently i=2...
#     Task C: Compute factorial(4), currently i=2...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3), currently i=3...
#     Task C: Compute factorial(4), currently i=3...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4), currently i=4...
#     Task C: factorial(4) = 24
#     [2, 6, 24]
@end example

@cartouche
@quotation 注解 
如果 @emph{return_exceptions} 为 False，则在 gather() 被标记为已完成后取消它将不会取消任何已提交的可等待对象。 例如，在将一个异常传播给调用者之后，gather 可被标记为已完成，因此，在从 gather 捕获一个（由可等待对象所引发的）异常之后调用 @code{gather.cancel()} 将不会取消任何其他可等待对象。
@end quotation
@end cartouche


在 3.7 版更改: 如果 @emph{gather} 本身被取消，则无论 @emph{return_exceptions} 取值为何，消息都会被传播。

@end deffn

@node 屏蔽取消操作,超时,并发运行任务,协程与任务
@anchor{library/asyncio-task shielding-from-cancellation}@anchor{2662}
@subsubsection 屏蔽取消操作


@geindex shield() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio shield}@anchor{3b4}
@deffn {函数} awaitable asyncio.shield (aw, *, loop=None)

保护一个 @ref{2659,,可等待对象} 防止其被 @ref{2663,,取消}。

如果 @emph{aw} 是一个协程，它将自动被作为任务调度。

以下语句:

@example
res = await shield(something())
@end example

相当于:

@example
res = await something()
@end example

@emph{不同之处} 在于如果包含它的协程被取消，在 @code{something()} 中运行的任务不会被取消。从 @code{something()} 的角度看来，取消操作并没有发生。然而其调用者已被取消，因此 "await" 表达式仍然会引发 @ref{2e1,,CancelledError}。

如果通过其他方式取消 @code{something()} (例如在其内部操作) 则 @code{shield()} 也会取消。

如果希望完全忽略取消操作 (不推荐) 则 @code{shield()} 函数需要配合一个 try/except 代码段，如下所示:

@example
try:
    res = await shield(something())
except CancelledError:
    res = None
@end example


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@end deffn

@node 超时,简单等待,屏蔽取消操作,协程与任务
@anchor{library/asyncio-task timeouts}@anchor{2664}
@subsubsection 超时


@geindex wait_for() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio wait_for}@anchor{191}
@deffn {函数} coroutine asyncio.wait_for (aw, timeout, *, loop=None)

等待 @emph{aw} @ref{2659,,可等待对象} 完成，指定 timeout 秒数后超时。

如果 @emph{aw} 是一个协程，它将自动被作为任务调度。

@emph{timeout} 可以为 @code{None}，也可以为 float 或 int 型数值表示的等待秒数。如果 @emph{timeout} 为 @code{None}，则等待直到完成。

如果发生超时，任务将取消并引发 @ref{2665,,asyncio.TimeoutError}.

要避免任务 @ref{2663,,取消}，可以加上 @ref{3b4,,shield()}。

此函数将等待直到 Future 确实被取消，所以总等待时间可能超过 @emph{timeout}。 如果在取消期间发生了异常，异常将会被传播。

如果等待被取消，则 @emph{aw} 指定的对象也会被取消。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@anchor{library/asyncio-task asyncio-example-waitfor}@anchor{2666}
示例:

@example
async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

asyncio.run(main())

# Expected output:
#
#     timeout!
@end example


在 3.7 版更改: 当 @emph{aw} 因超时被取消，@code{wait_for} 会等待 @emph{aw} 被取消。之前版本则将立即引发 @ref{2665,,asyncio.TimeoutError}。

@end deffn

@node 简单等待,在线程中运行,超时,协程与任务
@anchor{library/asyncio-task waiting-primitives}@anchor{2667}
@subsubsection 简单等待


@geindex wait() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio wait}@anchor{208}
@deffn {函数} coroutine asyncio.wait (aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)

并发地运行 @emph{aws} 可迭代对象中的 @ref{2659,,可等待对象} 并进入阻塞状态直到满足 @emph{return_when} 所指定的条件。

@emph{aws} 可迭代对象必须不为空。

返回两个 Task/Future 集合: @code{(done, pending)}。

用法:

@example
done, pending = await asyncio.wait(aws)
@end example

如指定 @emph{timeout} (float 或 int 类型) 则它将被用于控制返回之前等待的最长秒数。

请注意此函数不会引发 @ref{2665,,asyncio.TimeoutError}。当超时发生时，未完成的 Future 或 Task 将在指定秒数后被返回。

@emph{return_when} 指定此函数应在何时返回。它必须为以下常数之一:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

描述

@item

@code{FIRST_COMPLETED}

@tab

函数将在任意可等待对象结束或取消时返回。

@item

@code{FIRST_EXCEPTION}

@tab

函数将在任意可等待对象因引发异常而结束时返回。当没有引发任何异常时它就相当于 @code{ALL_COMPLETED}。

@item

@code{ALL_COMPLETED}

@tab

函数将在所有可等待对象结束或取消时返回。

@end multitable


与 @ref{191,,wait_for()} 不同，@code{wait()} 在超时发生时不会取消可等待对象。


3.8 版后已移除: 如果 @emph{aws} 中的某个可等待对象为协程，它将自动被作为任务调度。直接向 @code{wait()} 传入协程对象已弃用，因为这会导致 @ref{2668,,令人迷惑的行为}。



Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@anchor{library/asyncio-task asyncio-example-wait-coroutine}@anchor{2668}
@cartouche
@quotation 注解 
@code{wait()} 会自动以任务的形式调度协程，之后将以 @code{(done, pending)} 集合形式返回显式创建的任务对象。因此以下代码并不会有预期的行为:

@example
async def foo():
    return 42

coro = foo()
done, pending = await asyncio.wait(@{coro@})

if coro in done:
    # This branch will never be run!
@end example

以上代码段的修正方法如下:

@example
async def foo():
    return 42

task = asyncio.create_task(foo())
done, pending = await asyncio.wait(@{task@})

if task in done:
    # Everything will work as expected now.
@end example
@end quotation
@end cartouche


Deprecated since version 3.8, will be removed in version 3.11: 直接向 @code{wait()} 传入协程对象的方式已弃用。

@end deffn

@geindex as_completed() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio as_completed}@anchor{3b5}
@deffn {函数} asyncio.as_completed (aws, *, loop=None, timeout=None)

并发地运行 @emph{aws} 可迭代对象中的 @ref{2659,,可等待对象}。 返回一个协程的迭代器。 所返回的每个协程可被等待以从剩余的可等待对象的可迭代对象中获得最早的下一个结果。

如果在所有 Future 对象完成前发生超时则将引发 @ref{2665,,asyncio.TimeoutError}。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


示例:

@example
for coro in as_completed(aws):
    earliest_result = await coro
    # ...
@end example
@end deffn

@node 在线程中运行,跨线程调度,简单等待,协程与任务
@anchor{library/asyncio-task running-in-threads}@anchor{2669}
@subsubsection 在线程中运行


@geindex to_thread() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio to_thread}@anchor{18f}
@deffn {函数} coroutine asyncio.to_thread (func, /, *args, **kwargs)

在不同的线程中异步地运行函数 @emph{func}。

向此函数提供的任何 *args 和 **kwargs 会被直接传给 @emph{func}。 并且，当前 @ref{2625,,contextvars.Context} 会被传播，允许在不同的线程中访问来自事件循环的上下文变量。

返回一个可被等待以获取 @emph{func} 的最终结果的协程。

这个协程函数主要是用于执行在其他情况下会阻塞事件循环的 IO 密集型函数/方法。 例如:

@example
def blocking_io():
    print(f"start blocking_io at @{time.strftime('%X')@}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at @{time.strftime('%X')@}")

async def main():
    print(f"started main at @{time.strftime('%X')@}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at @{time.strftime('%X')@}")


asyncio.run(main())

# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
@end example

在任何协程中直接调用 @cite{blocking_io()} 将会在调用期间阻塞事件循环，导致额外的 1 秒运行时间。 而通过改用 @cite{asyncio.to_thread()}，我们可以在不同的线程中运行它从而不会阻塞事件循环。

@cartouche
@quotation 注解 
由于 @ref{20f,,GIL} 的存在，@cite{asyncio.to_thread()} 通常只能被用来将 IO 密集型函数变为非阻塞的。 但是，对于会释放 GIL 的扩展模块或无此限制的替代性 Python 实现来说，@cite{asyncio.to_thread()} 也可被用于 CPU 密集型函数。
@end quotation
@end cartouche


3.9 新版功能.

@end deffn

@node 跨线程调度,内省,在线程中运行,协程与任务
@anchor{library/asyncio-task scheduling-from-other-threads}@anchor{266a}
@subsubsection 跨线程调度


@geindex run_coroutine_threadsafe() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio run_coroutine_threadsafe}@anchor{61c}
@deffn {函数} asyncio.run_coroutine_threadsafe (coro, loop)

向指定事件循环提交一个协程。（线程安全）

返回一个 @ref{c09,,concurrent.futures.Future} 以等待来自其他 OS 线程的结果。

此函数应该从另一个 OS 线程中调用，而非事件循环运行所在线程。示例:

@example
# Create a coroutine
coro = asyncio.sleep(1, result=3)

# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)

# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
@end example

如果在协程内产生了异常，将会通知返回的 Future 对象。它也可被用来取消事件循环中的任务:

@example
try:
    result = future.result(timeout)
except asyncio.TimeoutError:
    print('The coroutine took too long, cancelling the task...')
    future.cancel()
except Exception as exc:
    print(f'The coroutine raised an exception: @{exc!r@}')
else:
    print(f'The coroutine returned: @{result!r@}')
@end example

查看 @ref{266b,,并发和多线程} 章节的文档。

不同与其他 asyncio 函数，此函数要求显式地传入 @emph{loop} 参数。


3.5.1 新版功能.

@end deffn

@node 内省,Task 对象,跨线程调度,协程与任务
@anchor{library/asyncio-task introspection}@anchor{266c}
@subsubsection 内省


@geindex current_task() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio current_task}@anchor{229}
@deffn {函数} asyncio.current_task (loop=None)

返回当前运行的 @ref{2e7,,Task} 实例，如果没有正在运行的任务则返回 @code{None}。

如果 @emph{loop} 为 @code{None} 则会使用 @ref{465,,get_running_loop()} 获取当前事件循环。


3.7 新版功能.

@end deffn

@geindex all_tasks() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio all_tasks}@anchor{22a}
@deffn {函数} asyncio.all_tasks (loop=None)

返回事件循环所运行的未完成的 @ref{2e7,,Task} 对象的集合。

如果 @emph{loop} 为 @code{None}，则会使用 @ref{465,,get_running_loop()} 获取当前事件循环。


3.7 新版功能.

@end deffn

@node Task 对象,基于生成器的协程,内省,协程与任务
@anchor{library/asyncio-task task-object}@anchor{266d}
@subsubsection Task 对象


@geindex Task (asyncio 中的类)
@anchor{library/asyncio-task asyncio Task}@anchor{2e7}
@deffn {类} asyncio.Task (coro, *, loop=None, name=None)

一个与 @ref{54e,,Future 类似} 的对象，可运行 Python @ref{264d,,协程}。非线程安全。

Task 对象被用来在事件循环中运行协程。如果一个协程在等待一个 Future 对象，Task 对象会挂起该协程的执行并等待该 Future 对象完成。当该 Future 对象 @emph{完成}，被打包的协程将恢复执行。

事件循环使用协同日程调度: 一个事件循环每次运行一个 Task 对象。而一个 Task 对象会等待一个 Future 对象完成，该事件循环会运行其他 Task、回调或执行 IO 操作。

使用高层级的 @ref{2e8,,asyncio.create_task()} 函数来创建 Task 对象，也可用低层级的 @ref{2e9,,loop.create_task()} 或 @ref{619,,ensure_future()} 函数。不建议手动实例化 Task 对象。

要取消一个正在运行的 Task 对象可使用 @ref{2663,,cancel()} 方法。调用此方法将使该 Task 对象抛出一个 @ref{2e1,,CancelledError} 异常给打包的协程。如果取消期间一个协程正在等待一个 Future 对象，该 Future 对象也将被取消。

@ref{266e,,cancelled()} 可被用来检测 Task 对象是否被取消。如果打包的协程没有抑制 @ref{2e1,,CancelledError} 异常并且确实被取消，该方法将返回 @code{True}。

@ref{2e7,,asyncio.Task} 从 @ref{54e,,Future} 继承了其除 @ref{266f,,Future.set_result()} 和 @ref{2670,,Future.set_exception()} 以外的所有 API。

Task 对象支持 @ref{24,,contextvars} 模块。当一个 Task 对象被创建，它将复制当前上下文，然后在复制的上下文中运行其协程。


在 3.7 版更改: 加入对 @ref{24,,contextvars} 模块的支持。



在 3.8 版更改: 添加了 @code{name} 形参。



Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


@geindex cancel() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task cancel}@anchor{2663}
@deffn {方法} cancel (msg=None)

请求取消 Task 对象。

这将安排在下一轮事件循环中抛出一个 @ref{2e1,,CancelledError} 异常给被封包的协程。

协程在之后有机会进行清理甚至使用 @ref{e3f,,try} ... ... @code{except CancelledError} ... @ref{2c3,,finally} 代码块抑制异常来拒绝请求。不同于 @ref{2671,,Future.cancel()}，@ref{2663,,Task.cancel()} 不保证 Task 会被取消，虽然抑制完全取消并不常见，也很不鼓励这样做。


在 3.9 版更改: 增加了 @code{msg} 形参。

@anchor{library/asyncio-task asyncio-example-task-cancel}@anchor{2672}
以下示例演示了协程是如何侦听取消请求的:

@example
async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now
@end example
@end deffn

@geindex cancelled() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task cancelled}@anchor{266e}
@deffn {方法} cancelled ()

如果 Task 对象 @emph{被取消} 则返回 @code{True}。

当使用 @ref{2663,,cancel()} 发出取消请求时 Task 会被 @emph{取消}，其封包的协程将传播被抛入的 @ref{2e1,,CancelledError} 异常。
@end deffn

@geindex done() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task done}@anchor{2673}
@deffn {方法} done ()

如果 Task 对象 @emph{已完成} 则返回 @code{True}。

当 Task 所封包的协程返回一个值、引发一个异常或 Task 本身被取消时，则会被认为 @emph{已完成}。
@end deffn

@geindex result() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task result}@anchor{2674}
@deffn {方法} result ()

返回 Task 的结果。

如果 Task 对象 @emph{已完成}，其封包的协程的结果会被返回 (或者当协程引发异常时，该异常会被重新引发。)

如果 Task 对象 @emph{被取消}，此方法会引发一个 @ref{2e1,,CancelledError} 异常。

如果 Task 对象的结果还不可用，此方法会引发一个 @ref{2675,,InvalidStateError} 异常。
@end deffn

@geindex exception() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task exception}@anchor{2676}
@deffn {方法} exception ()

返回 Task 对象的异常。

如果所封包的协程引发了一个异常，该异常将被返回。如果所封包的协程正常返回则该方法将返回 @code{None}。

如果 Task 对象 @emph{被取消}，此方法会引发一个 @ref{2e1,,CancelledError} 异常。

如果 Task 对象尚未 @emph{完成}，此方法将引发一个 @ref{2675,,InvalidStateError} 异常。
@end deffn

@geindex add_done_callback() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task add_done_callback}@anchor{2677}
@deffn {方法} add_done_callback (callback, *, context=None)

添加一个回调，将在 Task 对象 @emph{完成} 时被运行。

此方法应该仅在低层级的基于回调的代码中使用。

要了解更多细节请查看 @ref{462,,Future.add_done_callback()} 的文档。
@end deffn

@geindex remove_done_callback() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task remove_done_callback}@anchor{2678}
@deffn {方法} remove_done_callback (callback)

从回调列表中移除 @emph{callback} 指定的回调。

此方法应该仅在低层级的基于回调的代码中使用。

要了解更多细节请查看 @ref{2679,,Future.remove_done_callback()} 的文档。
@end deffn

@geindex get_stack() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task get_stack}@anchor{267a}
@deffn {方法} get_stack (*, limit=None)

返回此 Task 对象的栈框架列表。

如果所封包的协程未完成，这将返回其挂起所在的栈。如果协程已成功完成或被取消，这将返回一个空列表。如果协程被一个异常终止，这将返回回溯框架列表。

框架总是从按从旧到新排序。

每个被挂起的协程只返回一个栈框架。

可选的 @emph{limit} 参数指定返回框架的数量上限；默认返回所有框架。返回列表的顺序要看是返回一个栈还是一个回溯：栈返回最新的框架，回溯返回最旧的框架。(这与 traceback 模块的行为保持一致。)
@end deffn

@geindex print_stack() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task print_stack}@anchor{267b}
@deffn {方法} print_stack (*, limit=None, file=None)

打印此 Task 对象的栈或回溯。

此方法产生的输出类似于 traceback 模块通过 @ref{267a,,get_stack()} 所获取的框架。

@emph{limit} 参数会直接传递给 @ref{267a,,get_stack()}。

@emph{file} 参数是输出所写入的 I/O 流；默认情况下输出会写入 @ref{1eb,,sys.stderr}。
@end deffn

@geindex get_coro() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task get_coro}@anchor{2e6}
@deffn {方法} get_coro ()

返回由 @ref{2e7,,Task} 包装的协程对象。


3.8 新版功能.

@end deffn

@geindex get_name() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task get_name}@anchor{2eb}
@deffn {方法} get_name ()

返回 Task 的名称。

如果没有一个 Task 名称被显式地赋值，默认的 asyncio Task 实现会在实例化期间生成一个默认名称。


3.8 新版功能.

@end deffn

@geindex set_name() (asyncio.Task 方法)
@anchor{library/asyncio-task asyncio Task set_name}@anchor{2ea}
@deffn {方法} set_name (value)

设置 Task 的名称。

@emph{value} 参数可以为任意对象，它随后会被转换为字符串。

在默认的 Task 实现中，名称将在任务对象的 @ref{8c3,,repr()} 输出中可见。


3.8 新版功能.

@end deffn
@end deffn

@node 基于生成器的协程,,Task 对象,协程与任务
@anchor{library/asyncio-task asyncio-generator-based-coro}@anchor{265b}@anchor{library/asyncio-task generator-based-coroutines}@anchor{267c}
@subsubsection 基于生成器的协程


@cartouche
@quotation 注解 
对基于生成器的协程的支持已被 @strong{弃用} 并将在 Python 3.11 中被移除。
@end quotation
@end cartouche

基于生成器的协程是 async/await 语法的前身。它们是使用 @code{yield from} 语句创建的 Python 生成器，可以等待 Future 和其他协程。

基于生成器的协程应该使用 @ref{3b0,,@@asyncio.coroutine} 装饰，虽然这并非强制。

@geindex coroutine() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio coroutine}@anchor{3b0}
@deffn {函数} @@asyncio.coroutine

用来标记基于生成器的协程的装饰器。

此装饰器使得旧式的基于生成器的协程能与 async/await 代码相兼容:

@example
@@asyncio.coroutine
def old_style_coroutine():
    yield from asyncio.sleep(1)

async def main():
    await old_style_coroutine()
@end example

此装饰器不应该被用于 @ref{3b1,,async def} 协程。


Deprecated since version 3.8, will be removed in version 3.11: 请改用 @ref{3b1,,async def}。

@end deffn

@geindex iscoroutine() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio iscoroutine}@anchor{267d}
@deffn {函数} asyncio.iscoroutine (obj)

如果 @emph{obj} 是一个 @ref{264d,,协程对象} 则返回 @code{True}。

此方法不同于 @ref{7f2,,inspect.iscoroutine()} 因为它对基于生成器的协程返回 @code{True}。
@end deffn

@geindex iscoroutinefunction() (在 asyncio 模块中)
@anchor{library/asyncio-task asyncio iscoroutinefunction}@anchor{267e}
@deffn {函数} asyncio.iscoroutinefunction (func)

如果 @emph{func} 是一个 @ref{264d,,协程函数} 则返回 @code{True}。

此方法不同于 @ref{7f3,,inspect.iscoroutinefunction()} 因为它对以 @ref{3b0,,@@coroutine} 装饰的基于生成器的协程函数返回 @code{True}。
@end deffn

@node 流,同步原语<2>,协程与任务,asyncio --- 异步 I/O
@anchor{library/asyncio-stream doc}@anchor{267f}@anchor{library/asyncio-stream asyncio-streams}@anchor{264e}@anchor{library/asyncio-stream streams}@anchor{2680}
@subsubsection 流


@strong{源码:} Lib/asyncio/streams.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/streams.py}


__________________________________________________________________


流是用于处理网络连接的支持 async/await 的高层级原语。 流允许发送和接收数据，而不需要使用回调或低级协议和传输。
@anchor{library/asyncio-stream asyncio-example-stream}@anchor{2681}
下面是一个使用 asyncio streams 编写的 TCP echo 客户端示例:

@example
import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: @{message!r@}')
    writer.write(message.encode())
    await writer.drain()

    data = await reader.read(100)
    print(f'Received: @{data.decode()!r@}')

    print('Close the connection')
    writer.close()
    await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))
@end example

参见下面的 @ref{2682,,Examples} 部分。

@subsubheading Stream 函数


下面的高级 asyncio 函数可以用来创建和处理流:

@geindex open_connection() (在 asyncio 模块中)
@anchor{library/asyncio-stream asyncio open_connection}@anchor{474}
@deffn {函数} coroutine asyncio.open_connection (host=None, port=None, *, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None)

建立网络连接并返回一对 @code{(reader, writer)} 对象。

返回的 @emph{reader} 和 @emph{writer} 对象是 @ref{114e,,StreamReader} 和 @ref{114f,,StreamWriter} 类的实例。

@emph{loop} 参数是可选的，当从协程中等待该函数时，总是可以自动确定。

@emph{limit} 确定返回的 @ref{114e,,StreamReader} 实例使用的缓冲区大小限制。默认情况下，@emph{limit} 设置为 64 KiB 。

其余的参数直接传递到 @ref{2ec,,loop.create_connection()} 。


3.7 新版功能: @emph{ssl_handshake_timeout} 形参。



3.8 新版功能: 增加了 @emph{happy_eyeballs_delay} 和 @emph{interleave} 形参。

@end deffn

@geindex start_server() (在 asyncio 模块中)
@anchor{library/asyncio-stream asyncio start_server}@anchor{475}
@deffn {函数} coroutine asyncio.start_server (client_connected_cb, host=None, port=None, *, loop=None, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)

启动套接字服务。

当一个新的客户端连接被建立时，回调函数 @emph{client_connected_cb} 会被调用。该函数会接收到一对参数 @code{(reader, writer)} ，reader是类 @ref{114e,,StreamReader} 的实例，而writer是类 @ref{114f,,StreamWriter} 的实例。

@emph{client_connected_cb} 即可以是普通的可调用对象也可以是一个 @ref{264d,,协程函数}; 如果它是一个协程函数，它将自动作为 @ref{2e7,,Task} 被调度。

@emph{loop} 参数是可选的。当在一个协程中await该方法时，该参数始终可以自动确定。

@emph{limit} 确定返回的 @ref{114e,,StreamReader} 实例使用的缓冲区大小限制。默认情况下，@emph{limit} 设置为 64 KiB 。

余下的参数将会直接传递给 @ref{46e,,loop.create_server()}.


3.7 新版功能: The @emph{ssl_handshake_timeout} and @emph{start_serving} parameters.

@end deffn

@subsubheading Unix 套接字


@geindex open_unix_connection() (在 asyncio 模块中)
@anchor{library/asyncio-stream asyncio open_unix_connection}@anchor{2683}
@deffn {函数} coroutine asyncio.open_unix_connection (path=None, *, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)

建立一个 Unix 套接字连接并返回 @code{(reader, writer)} 这对返回值。

与 @ref{474,,open_connection()} 相似，但是是在 Unix 套接字上的操作。

请看文档 @ref{2684,,loop.create_unix_connection()}.

@ref{14c1,,可用性}: Unix。


3.7 新版功能: @emph{ssl_handshake_timeout} 形参。



在 3.7 版更改: @emph{path} 现在是一个 @ref{47b,,path-like object}

@end deffn

@geindex start_unix_server() (在 asyncio 模块中)
@anchor{library/asyncio-stream asyncio start_unix_server}@anchor{2685}
@deffn {函数} coroutine asyncio.start_unix_server (client_connected_cb, path=None, *, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)

启动一个 Unix 套接字服务。

与 @ref{475,,start_server()} 相似，但是是在 Unix 套接字上的操作。

请看文档 @ref{46f,,loop.create_unix_server()}.

@ref{14c1,,可用性}: Unix。


3.7 新版功能: The @emph{ssl_handshake_timeout} and @emph{start_serving} parameters.



在 3.7 版更改: @emph{path} 形参现在可以是 @ref{47b,,path-like object} 对象。

@end deffn

@menu
* StreamReader:: 
* StreamWriter:: 
* 示例: 示例<18>. 

@end menu

@node StreamReader,StreamWriter,,流
@anchor{library/asyncio-stream streamreader}@anchor{2686}
@subsubsection StreamReader


@geindex StreamReader (asyncio 中的类)
@anchor{library/asyncio-stream asyncio StreamReader}@anchor{114e}
@deffn {类} asyncio.StreamReader

这个类表示一个读取器对象，该对象提供api以便于从IO流中读取数据。

不推荐直接实例化 @emph{StreamReader} 对象，建议使用 @ref{474,,open_connection()} 和 @ref{475,,start_server()} 来获取 @emph{StreamReader} 实例。

@geindex read() (asyncio.StreamReader 方法)
@anchor{library/asyncio-stream asyncio StreamReader read}@anchor{2687}
@deffn {方法} coroutine read (n=-1)

至多读取 @emph{n} 个byte。  如果没有设置 @emph{n} , 则自动置为 @code{-1} ， -1时表示读至 EOF 并返回所有读取的byte。

如果读到EOF，且内部缓冲区为空，则返回一个空的 @code{bytes} 对象。
@end deffn

@geindex readline() (asyncio.StreamReader 方法)
@anchor{library/asyncio-stream asyncio StreamReader readline}@anchor{2688}
@deffn {方法} coroutine readline ()

读取一行，其中“行”指的是以 @code{\n} 结尾的字节序列。

如果读到EOF而没有找到 @code{\n} ，该方法返回部分读取的数据。

如果读到EOF，且内部缓冲区为空，则返回一个空的 @code{bytes} 对象。
@end deffn

@geindex readexactly() (asyncio.StreamReader 方法)
@anchor{library/asyncio-stream asyncio StreamReader readexactly}@anchor{621}
@deffn {方法} coroutine readexactly (n)

精确读取 @emph{n} 个 bytes，不会超过也不能少于。

如果在读取完 @emph{n} 个byte之前读取到EOF，则会引发 @ref{1026,,IncompleteReadError} 异常。使用 @ref{2689,,IncompleteReadError.partial} 属性来获取到达流结束之前读取的 bytes 字符串。
@end deffn

@geindex readuntil() (asyncio.StreamReader 方法)
@anchor{library/asyncio-stream asyncio StreamReader readuntil}@anchor{620}
@deffn {方法} coroutine readuntil (separator=b'\n')

从流中读取数据直至遇到 @emph{separator}

成功后，数据和指定的separator将从内部缓冲区中删除(或者说被消费掉)。返回的数据将包括在末尾的指定separator。

如果读取的数据量超过了配置的流限制，将引发 @ref{268a,,LimitOverrunError} 异常，数据将留在内部缓冲区中并可以再次读取。

如果在找到完整的separator之前到达EOF，则会引发 @ref{1026,,IncompleteReadError} 异常，并重置内部缓冲区。 @ref{2689,,IncompleteReadError.partial} 属性可能包含指定separator的一部分。


3.5.2 新版功能.

@end deffn

@geindex at_eof() (asyncio.StreamReader 方法)
@anchor{library/asyncio-stream asyncio StreamReader at_eof}@anchor{268b}
@deffn {方法} at_eof ()

如果缓冲区为空并且 @code{feed_eof()} 被调用，则返回 @code{True} 。
@end deffn
@end deffn

@node StreamWriter,示例<18>,StreamReader,流
@anchor{library/asyncio-stream streamwriter}@anchor{268c}
@subsubsection StreamWriter


@geindex StreamWriter (asyncio 中的类)
@anchor{library/asyncio-stream asyncio StreamWriter}@anchor{114f}
@deffn {类} asyncio.StreamWriter

这个类表示一个写入器对象，该对象提供api以便于写数据至IO流中。

不建议直接实例化 @emph{StreamWriter}；而应改用 @ref{474,,open_connection()} 和 @ref{475,,start_server()}。

@geindex write() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter write}@anchor{268d}
@deffn {方法} write (data)

此方法会尝试立即将 @emph{data} 写入到下层的套接字。 如果写入失败，数据会被排入内部写缓冲队列直到可以被发送。

此方法应当与 @code{drain()} 方法一起使用:

@example
stream.write(data)
await stream.drain()
@end example
@end deffn

@geindex writelines() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter writelines}@anchor{268e}
@deffn {方法} writelines (data)

此方法会立即尝试将一个字节串列表（或任何可迭代对象）写入到下层的套接字。 如果写入失败，数据会被排入内部写缓冲队列直到可以被发送。

此方法应当与 @code{drain()} 方法一起使用:

@example
stream.writelines(lines)
await stream.drain()
@end example
@end deffn

@geindex close() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter close}@anchor{268f}
@deffn {方法} close ()

此方法会关闭流以及下层的套接字。

此方法应与 @code{wait_closed()} 方法一起使用:

@example
stream.close()
await stream.wait_closed()
@end example
@end deffn

@geindex can_write_eof() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter can_write_eof}@anchor{2690}
@deffn {方法} can_write_eof ()

如果下层的传输支持 @ref{2691,,write_eof()} 方法则返回`@w{`}True`@w{`}，否则返回 @code{False}。
@end deffn

@geindex write_eof() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter write_eof}@anchor{2691}
@deffn {方法} write_eof ()

在已缓冲的写入数据被刷新后关闭流的写入端。
@end deffn

@geindex transport (asyncio.StreamWriter 属性)
@anchor{library/asyncio-stream asyncio StreamWriter transport}@anchor{2692}
@deffn {属性} transport

返回下层的 asyncio 传输。
@end deffn

@geindex get_extra_info() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter get_extra_info}@anchor{2693}
@deffn {方法} get_extra_info (name, default=None)

访问可选的传输信息；详情参见 @ref{3f2,,BaseTransport.get_extra_info()}。
@end deffn

@geindex drain() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter drain}@anchor{2694}
@deffn {方法} coroutine drain ()

等待直到可以适当地恢复写入到流。 示例:

@example
writer.write(data)
await writer.drain()
@end example

这是一个与下层的 IO 写缓冲区进行交互的流程控制方法。 当缓冲区大小达到最高水位（最大上限）时，@emph{drain()} 会阻塞直到缓冲区大小减少至最低水位以便恢复写入。 当没有要等待的数据时，@ref{2694,,drain()} 会立即返回。
@end deffn

@geindex is_closing() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter is_closing}@anchor{468}
@deffn {方法} is_closing ()

如果流已被关闭或正在被关闭则返回 @code{True}。


3.7 新版功能.

@end deffn

@geindex wait_closed() (asyncio.StreamWriter 方法)
@anchor{library/asyncio-stream asyncio StreamWriter wait_closed}@anchor{467}
@deffn {方法} coroutine wait_closed ()

等待直到流被关闭。

应当在 @ref{268f,,close()} 之后被调用以便等待直到下层的连接被关闭。


3.7 新版功能.

@end deffn
@end deffn

@node 示例<18>,,StreamWriter,流
@anchor{library/asyncio-stream examples}@anchor{2682}
@subsubsection 示例


@menu
* 使用流的 TCP 回显客户端:: 
* 使用流的 TCP 回显服务器:: 
* 获取 HTTP 标头:: 
* 注册一个打开的套接字以等待使用流的数据:: 

@end menu

@node 使用流的 TCP 回显客户端,使用流的 TCP 回显服务器,,示例<18>
@anchor{library/asyncio-stream asyncio-tcp-echo-client-streams}@anchor{2695}@anchor{library/asyncio-stream tcp-echo-client-using-streams}@anchor{2696}
@subsubsection 使用流的 TCP 回显客户端


使用 @ref{474,,asyncio.open_connection()} 函数的 TCP 回显客户端:

@example
import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: @{message!r@}')
    writer.write(message.encode())

    data = await reader.read(100)
    print(f'Received: @{data.decode()!r@}')

    print('Close the connection')
    writer.close()

asyncio.run(tcp_echo_client('Hello World!'))
@end example


@subsubheading 参见


使用低层级 @ref{2ec,,loop.create_connection()} 方法的 @ref{2697,,TCP 回显客户端协议} 示例。


@node 使用流的 TCP 回显服务器,获取 HTTP 标头,使用流的 TCP 回显客户端,示例<18>
@anchor{library/asyncio-stream asyncio-tcp-echo-server-streams}@anchor{2698}@anchor{library/asyncio-stream tcp-echo-server-using-streams}@anchor{2699}
@subsubsection 使用流的 TCP 回显服务器


TCP 回显服务器使用 @ref{475,,asyncio.start_server()} 函数:

@example
import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')

    print(f"Received @{message!r@} from @{addr!r@}")

    print(f"Send: @{message!r@}")
    writer.write(data)
    await writer.drain()

    print("Close the connection")
    writer.close()

async def main():
    server = await asyncio.start_server(
        handle_echo, '127.0.0.1', 8888)

    addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
    print(f'Serving on @{addrs@}')

    async with server:
        await server.serve_forever()

asyncio.run(main())
@end example


@subsubheading 参见


使用 @ref{46e,,loop.create_server()} 方法的 @ref{269a,,TCP 回显服务器协议} 示例。


@node 获取 HTTP 标头,注册一个打开的套接字以等待使用流的数据,使用流的 TCP 回显服务器,示例<18>
@anchor{library/asyncio-stream get-http-headers}@anchor{269b}
@subsubsection 获取 HTTP 标头


查询命令行传入 URL 的 HTTP 标头的简单示例:

@example
import asyncio
import urllib.parse
import sys

async def print_http_headers(url):
    url = urllib.parse.urlsplit(url)
    if url.scheme == 'https':
        reader, writer = await asyncio.open_connection(
            url.hostname, 443, ssl=True)
    else:
        reader, writer = await asyncio.open_connection(
            url.hostname, 80)

    query = (
        f"HEAD @{url.path or '/'@} HTTP/1.0\r\n"
        f"Host: @{url.hostname@}\r\n"
        f"\r\n"
    )

    writer.write(query.encode('latin-1'))
    while True:
        line = await reader.readline()
        if not line:
            break

        line = line.decode('latin1').rstrip()
        if line:
            print(f'HTTP header> @{line@}')

    # Ignore the body, close the socket
    writer.close()

url = sys.argv[1]
asyncio.run(print_http_headers(url))
@end example

用法:

@example
python example.py http://example.com/path/page.html
@end example

或使用 HTTPS:

@example
python example.py https://example.com/path/page.html
@end example

@node 注册一个打开的套接字以等待使用流的数据,,获取 HTTP 标头,示例<18>
@anchor{library/asyncio-stream asyncio-example-create-connection-streams}@anchor{269c}@anchor{library/asyncio-stream register-an-open-socket-to-wait-for-data-using-streams}@anchor{269d}
@subsubsection 注册一个打开的套接字以等待使用流的数据


使用 @ref{474,,open_connection()} 函数实现等待直到套接字接收到数据的协程:

@example
import asyncio
import socket

async def wait_for_data():
    # Get a reference to the current event loop because
    # we want to access low-level APIs.
    loop = asyncio.get_running_loop()

    # Create a pair of connected sockets.
    rsock, wsock = socket.socketpair()

    # Register the open socket to wait for data.
    reader, writer = await asyncio.open_connection(sock=rsock)

    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())

    # Wait for data
    data = await reader.read(100)

    # Got data, we are done: close the socket
    print("Received:", data.decode())
    writer.close()

    # Close the second socket
    wsock.close()

asyncio.run(wait_for_data())
@end example


@subsubheading 参见


使用低层级协议以及 @ref{2ec,,loop.create_connection()} 方法的 @ref{269e,,注册一个打开的套接字以等待使用协议的数据} 示例。

使用低层级的 @ref{269f,,loop.add_reader()} 方法来监视文件描述符的 @ref{26a0,,监视文件描述符以读取事件} 示例。


@node 同步原语<2>,子进程,流,asyncio --- 异步 I/O
@anchor{library/asyncio-sync doc}@anchor{26a1}@anchor{library/asyncio-sync asyncio-sync}@anchor{2651}@anchor{library/asyncio-sync synchronization-primitives}@anchor{26a2}
@subsubsection 同步原语


@strong{源代码:} Lib/asyncio/locks.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/locks.py}


__________________________________________________________________


asyncio 同步原语被设计为与 @ref{10b,,threading} 模块的类似，但有两个关键注意事项:


@itemize *

@item 
asyncio 原语不是线程安全的，因此它们不应被用于 OS 线程同步 (而应当使用 @ref{10b,,threading})；

@item 
这些同步原语的方法不接受 @emph{timeout} 参数；请使用 @ref{191,,asyncio.wait_for()} 函数来执行带有超时的操作。
@end itemize

asyncio 具有下列基本同步原语:


@itemize *

@item 
@ref{3b6,,Lock}

@item 
@ref{3b7,,Event}

@item 
@ref{3b8,,Condition}

@item 
@ref{3b9,,Semaphore}

@item 
@ref{3ba,,BoundedSemaphore}
@end itemize


__________________________________________________________________


@menu
* Lock:: 
* Event:: 
* Condition:: 
* Semaphore:: 
* BoundedSemaphore:: 

@end menu

@node Lock,Event,,同步原语<2>
@anchor{library/asyncio-sync lock}@anchor{26a3}
@subsubsection Lock


@geindex Lock (asyncio 中的类)
@anchor{library/asyncio-sync asyncio Lock}@anchor{3b6}
@deffn {类} asyncio.Lock (*, loop=None)

实现一个用于 asyncio 任务的互斥锁。 非线程安全。

asyncio 锁可被用来保证对共享资源的独占访问。

使用 Lock 的推荐方式是通过 @ref{740,,async with} 语句:

@example
lock = asyncio.Lock()

# ... later
async with lock:
    # access shared state
@end example

这等价于:

@example
lock = asyncio.Lock()

# ... later
await lock.acquire()
try:
    # access shared state
finally:
    lock.release()
@end example


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


@geindex acquire() (asyncio.Lock 方法)
@anchor{library/asyncio-sync asyncio Lock acquire}@anchor{26a4}
@deffn {方法} coroutine acquire ()

获取锁。

此方法会等待直至锁为 @emph{unlocked}，将其设为 @emph{locked} 并返回 @code{True}。

当有一个以上的协程在 @ref{26a4,,acquire()} 中被阻塞则会等待解锁，最终只有一个协程会被执行。

锁的获取是 @emph{公平的}: 被执行的协程将是第一个开始等待锁的协程。
@end deffn

@geindex release() (asyncio.Lock 方法)
@anchor{library/asyncio-sync asyncio Lock release}@anchor{26a5}
@deffn {方法} release ()

释放锁。

当锁为 @emph{locked} 时，将其设为 @emph{unlocked} 并返回。

如果锁为 @emph{unlocked}，则会引发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex locked() (asyncio.Lock 方法)
@anchor{library/asyncio-sync asyncio Lock locked}@anchor{26a6}
@deffn {方法} locked ()

如果锁为 @emph{locked} 则返回 @code{True}。
@end deffn
@end deffn

@node Event,Condition,Lock,同步原语<2>
@anchor{library/asyncio-sync event}@anchor{26a7}
@subsubsection Event


@geindex Event (asyncio 中的类)
@anchor{library/asyncio-sync asyncio Event}@anchor{3b7}
@deffn {类} asyncio.Event (*, loop=None)

事件对象。 该对象不是线程安全的。

asyncio 事件可被用来通知多个 asyncio 任务已经有事件发生。

Event 对象会管理一个内部旗标，可通过 @ref{26a8,,set()} 方法将其设为 @emph{true} 并通过 @ref{26a9,,clear()} 方法将其重设为 @emph{false}。 @ref{26aa,,wait()} 方法会阻塞直至该旗标被设为 @emph{true}。 该旗标初始时会被设为 @emph{false}。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@anchor{library/asyncio-sync asyncio-example-sync-event}@anchor{26ab}
示例:

@example
async def waiter(event):
    print('waiting for it ...')
    await event.wait()
    print('... got it!')

async def main():
    # Create an Event object.
    event = asyncio.Event()

    # Spawn a Task to wait until 'event' is set.
    waiter_task = asyncio.create_task(waiter(event))

    # Sleep for 1 second and set the event.
    await asyncio.sleep(1)
    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

asyncio.run(main())
@end example

@geindex wait() (asyncio.Event 方法)
@anchor{library/asyncio-sync asyncio Event wait}@anchor{26aa}
@deffn {方法} coroutine wait ()

等待直至事件被设置。

如果事件已被设置，则立即返回 @code{True}。 否则将阻塞直至另一个任务调用 @ref{26a8,,set()}。
@end deffn

@geindex set() (asyncio.Event 方法)
@anchor{library/asyncio-sync asyncio Event set}@anchor{26a8}
@deffn {方法} set ()

设置事件。

所有等待事件被设置的任务将被立即唤醒。
@end deffn

@geindex clear() (asyncio.Event 方法)
@anchor{library/asyncio-sync asyncio Event clear}@anchor{26a9}
@deffn {方法} clear ()

清空（取消设置）事件。

通过 @ref{26aa,,wait()} 进行等待的任务现在将会阻塞直至 @ref{26a8,,set()} 方法被再次调用。
@end deffn

@geindex is_set() (asyncio.Event 方法)
@anchor{library/asyncio-sync asyncio Event is_set}@anchor{26ac}
@deffn {方法} is_set ()

如果事件已被设置则返回 @code{True}。
@end deffn
@end deffn

@node Condition,Semaphore,Event,同步原语<2>
@anchor{library/asyncio-sync condition}@anchor{26ad}
@subsubsection Condition


@geindex Condition (asyncio 中的类)
@anchor{library/asyncio-sync asyncio Condition}@anchor{3b8}
@deffn {类} asyncio.Condition (lock=None, *, loop=None)

条件对象。 该对象不是线程安全的。

asyncio 条件原语可被任务用于等待某个事件发生，然后获取对共享资源的独占访问。

在本质上，Condition 对象合并了 @ref{3b7,,Event} 和 @ref{3b6,,Lock} 的功能。 多个 Condition 对象有可能共享一个 Lock，这允许关注于共享资源的特定状态的不同任务实现对共享资源的协同独占访问。

可选的 @emph{lock} 参数必须为 @ref{3b6,,Lock} 对象或 @code{None}。 在后一种情况下会自动创建一个新的 Lock 对象。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


使用 Condition 的推荐方式是通过 @ref{740,,async with} 语句:

@example
cond = asyncio.Condition()

# ... later
async with cond:
    await cond.wait()
@end example

这等价于:

@example
cond = asyncio.Condition()

# ... later
await cond.acquire()
try:
    await cond.wait()
finally:
    cond.release()
@end example

@geindex acquire() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition acquire}@anchor{26ae}
@deffn {方法} coroutine acquire ()

获取下层的锁。

此方法会等待直至下层的锁为 @emph{unlocked}，将其设为 @emph{locked} 并返回 returns @code{True}。
@end deffn

@geindex notify() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition notify}@anchor{26af}
@deffn {方法} notify (n=1)

唤醒最多 @emph{n} 个正在等待此条件的任务（默认为 1 个）。 如果没有任务正在等待则此方法为空操作。

锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个 @emph{unlocked} 锁调用则会引发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex locked() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition locked}@anchor{26b0}
@deffn {方法} locked ()

如果下层的锁已被获取则返回 @code{True}。
@end deffn

@geindex notify_all() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition notify_all}@anchor{26b1}
@deffn {方法} notify_all ()

唤醒所有正在等待此条件的任务。

此方法的行为类似于 @ref{26af,,notify()}，但会唤醒所有正在等待的任务。

锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个 @emph{unlocked} 锁调用则会引发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex release() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition release}@anchor{26b2}
@deffn {方法} release ()

释放下层的锁。

当在未锁定的锁上发起调用时，会引发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex wait() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition wait}@anchor{26b3}
@deffn {方法} coroutine wait ()

等待直至收到通知。

当此方法被调用时如果调用方任务未获得锁，则会引发 @ref{3e4,,RuntimeError}。

这个方法会释放下层的锁，然后保持阻塞直到被 @ref{26af,,notify()} 或 @ref{26b1,,notify_all()} 调用所唤醒。 一旦被唤醒，Condition 会重新获取它的锁并且此方法将返回 @code{True}。
@end deffn

@geindex wait_for() (asyncio.Condition 方法)
@anchor{library/asyncio-sync asyncio Condition wait_for}@anchor{26b4}
@deffn {方法} coroutine wait_for (predicate)

等待直到目标值变为 @emph{true}。

目标必须为一个可调用对象，其结果将被解读为一个布尔值。 最终的值将为返回值。
@end deffn
@end deffn

@node Semaphore,BoundedSemaphore,Condition,同步原语<2>
@anchor{library/asyncio-sync semaphore}@anchor{26b5}
@subsubsection Semaphore


@geindex Semaphore (asyncio 中的类)
@anchor{library/asyncio-sync asyncio Semaphore}@anchor{3b9}
@deffn {类} asyncio.Semaphore (value=1, *, loop=None)

信号量对象。 该对象不是线程安全的。

信号量会管理一个内部计数器，该计数器会随每次 @ref{26b6,,acquire()} 调用递减并随每次 @ref{26b7,,release()} 调用递增。 计数器的值永远不会降到零以下；当 @ref{26b6,,acquire()} 发现其值为零时，它将保持阻塞直到有某个任务调用了 @ref{26b7,,release()}。

可选的 @emph{value} 参数用来为内部计数器赋初始值 (默认值为 @code{1})。 如果给定的值小于 @code{0} 则会引发 @ref{16d,,ValueError}。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


使用 Semaphore 的推荐方式是通过 @ref{740,,async with} 语句。:

@example
sem = asyncio.Semaphore(10)

# ... later
async with sem:
    # work with shared resource
@end example

这等价于:

@example
sem = asyncio.Semaphore(10)

# ... later
await sem.acquire()
try:
    # work with shared resource
finally:
    sem.release()
@end example

@geindex acquire() (asyncio.Semaphore 方法)
@anchor{library/asyncio-sync asyncio Semaphore acquire}@anchor{26b6}
@deffn {方法} coroutine acquire ()

获取一个信号量。

如果内部计数器的值大于零，则将其减一并立即返回 @code{True}。 如果其值为零，则会等待直到 @ref{26b7,,release()} 并调用并返回 @code{True}。
@end deffn

@geindex locked() (asyncio.Semaphore 方法)
@anchor{library/asyncio-sync asyncio Semaphore locked}@anchor{26b8}
@deffn {方法} locked ()

如果信号量对象无法被立即获取则返回 @code{True}。
@end deffn

@geindex release() (asyncio.Semaphore 方法)
@anchor{library/asyncio-sync asyncio Semaphore release}@anchor{26b7}
@deffn {方法} release ()

释放一个信号量对象，将内部计数器的值加一。 可以唤醒一个正在等待获取信号量对象的任务。

不同于 @ref{3ba,,BoundedSemaphore}，@ref{3b9,,Semaphore} 允许执行的 @code{release()} 调用多于 @code{acquire()} 调用。
@end deffn
@end deffn

@node BoundedSemaphore,,Semaphore,同步原语<2>
@anchor{library/asyncio-sync boundedsemaphore}@anchor{26b9}
@subsubsection BoundedSemaphore


@geindex BoundedSemaphore (asyncio 中的类)
@anchor{library/asyncio-sync asyncio BoundedSemaphore}@anchor{3ba}
@deffn {类} asyncio.BoundedSemaphore (value=1, *, loop=None)

绑定的信号量对象。 该对象不是线程安全的。

BoundedSemaphore 是特殊版本的 @ref{3b9,,Semaphore}，如果在 @ref{26b7,,release()} 中内部计数器值增加到初始 @emph{value} 以上它将引发一个 @ref{16d,,ValueError}。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@end deffn


__________________________________________________________________



在 3.9 版更改: 使用 @code{await lock} 或 @code{yield from lock} 以及/或者 @ref{7e4,,with} 语句 (@code{with await lock}, @code{with (yield from lock)}) 来获取锁的操作已被移除。 请改用 @code{async with lock}。


@node 子进程,队列集,同步原语<2>,asyncio --- 异步 I/O
@anchor{library/asyncio-subprocess doc}@anchor{26ba}@anchor{library/asyncio-subprocess asyncio-subprocess}@anchor{264f}@anchor{library/asyncio-subprocess subprocesses}@anchor{26bb}
@subsubsection 子进程


@strong{源代码:} Lib/asyncio/subprocess.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/subprocess.py}, Lib/asyncio/base_subprocess.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_subprocess.py}


__________________________________________________________________


本节介绍了用于创建和管理子进程的高层级 async/await asyncio API。
@anchor{library/asyncio-subprocess asyncio-example-subprocess-shell}@anchor{26bc}
下面的例子演示了如何用 asyncio 运行一个 shell 命令并获取其结果:

@example
import asyncio

async def run(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)

    stdout, stderr = await proc.communicate()

    print(f'[@{cmd!r@} exited with @{proc.returncode@}]')
    if stdout:
        print(f'[stdout]\n@{stdout.decode()@}')
    if stderr:
        print(f'[stderr]\n@{stderr.decode()@}')

asyncio.run(run('ls /zzz'))
@end example

将打印:

@example
['ls /zzz' exited with 1]
[stderr]
ls: /zzz: No such file or directory
@end example

由于所有 asyncio 子进程函数都是异步的并且 asyncio 提供了许多工具用来配合这些函数使用，因此并行地执行和监视多个子进程十分容易。 要修改上面的例子来同时运行多个命令确实是非常简单的:

@example
async def main():
    await asyncio.gather(
        run('ls /zzz'),
        run('sleep 1; echo "hello"'))

asyncio.run(main())
@end example

另请参阅 @ref{26bd,,Examples} 小节。

@menu
* 创建子进程:: 
* 常数: 常数<5>. 
* 与子进程交互:: 

@end menu

@node 创建子进程,常数<5>,,子进程
@anchor{library/asyncio-subprocess creating-subprocesses}@anchor{26be}
@subsubsection 创建子进程


@geindex create_subprocess_exec() (在 asyncio 模块中)
@anchor{library/asyncio-subprocess asyncio create_subprocess_exec}@anchor{3bc}
@deffn {函数} coroutine asyncio.create_subprocess_exec (program, *args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)

创建一个子进程。

@emph{limit} 参数为 @code{Process.stdout} 和 @code{Process.stderr} 设置 @ref{114e,,StreamReader} 包装器的缓冲区上限（如果将 @ref{4fc,,subprocess.PIPE} 传给了 @emph{stdout} 和 @emph{stderr} 参数）。

返回一个 @ref{26bf,,Process} 实例。

有关其他形参的说明请查阅 @ref{2652,,loop.subprocess_exec()} 的文档。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@end deffn

@geindex create_subprocess_shell() (在 asyncio 模块中)
@anchor{library/asyncio-subprocess asyncio create_subprocess_shell}@anchor{3bd}
@deffn {函数} coroutine asyncio.create_subprocess_shell (cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)

运行 @emph{cmd} shell 命令。

@emph{limit} 参数为 @code{Process.stdout} 和 @code{Process.stderr} 设置 @ref{114e,,StreamReader} 包装器的缓冲区上限（如果将 @ref{4fc,,subprocess.PIPE} 传给了 @emph{stdout} 和 @emph{stderr} 参数）。

返回一个 @ref{26bf,,Process} 实例。

有关其他形参的说明请查阅 @ref{26c0,,loop.subprocess_shell()} 的文档。

@cartouche
@quotation 重要 
应用程序要负责确保正确地转义所有空白字符和特殊字符以防止 shell 注入@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection} 漏洞。 @ref{b57,,shlex.quote()} 函数可以被用来正确地转义字符串中可以被用来构造 shell 命令的空白字符和特殊 shell 字符。
@end quotation
@end cartouche


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。

@end deffn

@cartouche
@quotation 注解 
如果使用了 @ref{2e5,,ProactorEventLoop} 则子进程将在 Windows 中可用。 详情参见 @ref{26c1,,Windows 上的子进程支持}。
@end quotation
@end cartouche


@subsubheading 参见


asyncio 还有下列 @emph{低层级} API 可配合子进程使用: @ref{2652,,loop.subprocess_exec()}, @ref{26c0,,loop.subprocess_shell()}, @ref{26c2,,loop.connect_read_pipe()}, @ref{26c3,,loop.connect_write_pipe()} 以及 @ref{26c4,,子进程传输} 和 @ref{26c5,,子进程协议}。


@node 常数<5>,与子进程交互,创建子进程,子进程
@anchor{library/asyncio-subprocess constants}@anchor{26c6}
@subsubsection 常数


@geindex asyncio.subprocess.PIPE (內置变量)
@anchor{library/asyncio-subprocess asyncio subprocess PIPE}@anchor{26c7}
@deffn {数据} asyncio.subprocess.PIPE

可以被传递给 @emph{stdin}, @emph{stdout} 或 @emph{stderr} 形参。

如果 @emph{PIPE} 被传递给 @emph{stdin} 参数，则 @ref{26c8,,Process.stdin} 属性将会指向一个 @code{StreamWriter} 实例。

如果 @emph{PIPE} 被传递给 @emph{stdout} 或 @emph{stderr} 参数，则 @ref{26c9,,Process.stdout} 和 @ref{26ca,,Process.stderr} 属性将会指向 @code{StreamReader} 实例。
@end deffn

@geindex asyncio.subprocess.STDOUT (內置变量)
@anchor{library/asyncio-subprocess asyncio subprocess STDOUT}@anchor{26cb}
@deffn {数据} asyncio.subprocess.STDOUT

可以用作 @emph{stderr} 参数的特殊值，表示标准错误应当被重定向到标准输出。
@end deffn

@geindex asyncio.subprocess.DEVNULL (內置变量)
@anchor{library/asyncio-subprocess asyncio subprocess DEVNULL}@anchor{26cc}
@deffn {数据} asyncio.subprocess.DEVNULL

可以用作 @emph{stdin}, @emph{stdout} 或 @emph{stderr} 参数来处理创建函数的特殊值。 它表示将为相应的子进程流使用特殊文件 @ref{119b,,os.devnull}。
@end deffn

@node 与子进程交互,,常数<5>,子进程
@anchor{library/asyncio-subprocess interacting-with-subprocesses}@anchor{26cd}
@subsubsection 与子进程交互


@ref{3bc,,create_subprocess_exec()} 和 @ref{3bd,,create_subprocess_shell()} 函数都返回 @emph{Process} 类的实例。 @emph{Process} 是一个高层级包装器，它允许与子进程通信并监视其完成情况。

@geindex asyncio.subprocess.Process (內置类)
@anchor{library/asyncio-subprocess asyncio subprocess Process}@anchor{26bf}
@deffn {类} asyncio.subprocess.Process

一个用于包装 @code{create_subprocess_exec()} and @code{create_subprocess_shell()} 函数创建的 OS 进程的对象。

这个类被设计为具有与 @ref{3e3,,subprocess.Popen} 类相似的 API，但两者有一些重要的差异:


@itemize *

@item 
不同于 Popen，Process 实例没有与 @ref{25ea,,poll()} 方法等价的方法；

@item 
@ref{26ce,,communicate()} 和 @ref{26cf,,wait()} 方法没有 @emph{timeout} 形参；要使用 @code{wait_for()} 函数；

@item 
@ref{26cf,,Process.wait()} 方法是异步的，而 @ref{693,,subprocess.Popen.wait()} 方法则被实现为阻塞型忙循环；

@item 
@emph{universal_newlines} 形参不被支持。
@end itemize

这个类 @ref{266b,,不是线程安全的}。

请参阅  @ref{26d0,,子进程和线程} 部分。

@geindex wait() (asyncio.subprocess.Process 方法)
@anchor{library/asyncio-subprocess asyncio subprocess Process wait}@anchor{26cf}
@deffn {方法} coroutine wait ()

等待子进程终结。

设置并返回 @ref{26d1,,returncode} 属性。

@cartouche
@quotation 注解 
当使用 @code{stdout=PIPE} 或 @code{stderr=PIPE} 并且子进程产生了足以阻塞 OS 管道缓冲区等待接收更多的数据的输出时，此方法会发生死锁。 当使用管道时请使用 @ref{26ce,,communicate()} 方法来避免这种情况。
@end quotation
@end cartouche
@end deffn

@geindex communicate() (asyncio.subprocess.Process 方法)
@anchor{library/asyncio-subprocess asyncio subprocess Process communicate}@anchor{26ce}
@deffn {方法} coroutine communicate (input=None)

与进程交互:


@enumerate 

@item 
发送数据到 @emph{stdin} (如果 @emph{input} 不为 @code{None})；

@item 
从 @emph{stdout} 和 @emph{stderr} 读取数据，直至到达 EOF；

@item 
等待进程终结。
@end enumerate

可选的 @emph{input} 参数为将被发送到子进程的数据 (@ref{172,,bytes} 对象)。

返回一个元组 @code{(stdout_data, stderr_data)}。

如果在将 @emph{input} 写入到 @emph{stdin} 时引发了 @ref{a87,,BrokenPipeError} 或 @ref{a8a,,ConnectionResetError} 异常，异常会被忽略。 此条件会在进程先于所有数据被写入到 @emph{stdin} 之前退出时发生。

如果想要将数据发送到进程的 @emph{stdin}，则创建进程时必须使用 @code{stdin=PIPE}。 类似地，要在结果元组中获得任何不为 @code{None} 的值，则创建进程时必须使用 @code{stdout=PIPE} 和/或 @code{stderr=PIPE} 参数。

注意，数据读取在内存中是带缓冲的，因此如果数据量过大或不受则不要使用此方法。
@end deffn

@geindex send_signal() (asyncio.subprocess.Process 方法)
@anchor{library/asyncio-subprocess asyncio subprocess Process send_signal}@anchor{26d2}
@deffn {方法} send_signal (signal)

将信号 @emph{signal} 发送给子进程。

@cartouche
@quotation 注解 
在 Windows 上，@code{SIGTERM} 是 @ref{26d3,,terminate()} 的别名。 @code{CTRL_C_EVENT} 和 @code{CTRL_BREAK_EVENT} 可被发送给创建时设置了 @emph{creationflags} 形参且其中包括 @code{CREATE_NEW_PROCESS_GROUP} 的进程。
@end quotation
@end cartouche
@end deffn

@geindex terminate() (asyncio.subprocess.Process 方法)
@anchor{library/asyncio-subprocess asyncio subprocess Process terminate}@anchor{26d3}
@deffn {方法} terminate ()

停止子进程。

在 POSIX 系统中此方法会发送 @ref{26d4,,signal.SIGTERM} 给子进程。

在 Windows 上会调用 Win32 API 函数 @code{TerminateProcess()} 以停止子进程。
@end deffn

@geindex kill() (asyncio.subprocess.Process 方法)
@anchor{library/asyncio-subprocess asyncio subprocess Process kill}@anchor{26d5}
@deffn {方法} kill ()

杀掉子进程。

在 POSIX 系统中此方法会发送 @code{SIGKILL} 给子进程。

在 Windows 上此方法是 @ref{26d3,,terminate()} 的别名。
@end deffn

@geindex stdin (asyncio.subprocess.Process 属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stdin}@anchor{26c8}
@deffn {属性} stdin

标准输入流 (@code{StreamWriter}) 或者如果进程创建时设置了 @code{stdin=None} 则为 @code{None}。
@end deffn

@geindex stdout (asyncio.subprocess.Process 属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stdout}@anchor{26c9}
@deffn {属性} stdout

标准输出流 (@code{StreamReader}) 或者如果进程创建时设置了 @code{stdout=None} 则为 @code{None}。
@end deffn

@geindex stderr (asyncio.subprocess.Process 属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process stderr}@anchor{26ca}
@deffn {属性} stderr

标准错误流 (@code{StreamReader}) 或者如果进程创建时设置了 @code{stderr=None} 则为 @code{None}。
@end deffn

@cartouche
@quotation 警告 
使用 @ref{26ce,,communicate()} 方法而非 @ref{26c8,,process.stdin.write()}, @ref{26c9,,await process.stdout.read()} 或 @ref{26ca,,await process.stderr.read()}。 这可以避免由于流暂停读取或写入并阻塞子进程而导致的死锁。
@end quotation
@end cartouche

@geindex pid (asyncio.subprocess.Process 属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process pid}@anchor{26d6}
@deffn {属性} pid

进程标识号（PID）。

注意对于由Note that for processes created by the @code{create_subprocess_shell()} 函数所创建的进程，这个属性将是所生成的 shell 的 PID。
@end deffn

@geindex returncode (asyncio.subprocess.Process 属性)
@anchor{library/asyncio-subprocess asyncio subprocess Process returncode}@anchor{26d1}
@deffn {属性} returncode

当进程退出时返回其代号。

@code{None} 值表示进程尚未终止。

一个负值 @code{-N} 表示子进程被信号 @code{N} 中断 (仅 POSIX).
@end deffn
@end deffn

@menu
* 子进程和线程:: 
* 示例: 示例<19>. 

@end menu

@node 子进程和线程,示例<19>,,与子进程交互
@anchor{library/asyncio-subprocess asyncio-subprocess-threads}@anchor{26d0}@anchor{library/asyncio-subprocess subprocess-and-threads}@anchor{26d7}
@subsubsection 子进程和线程


标准 asyncio 事件循环默认支持从不同线程中运行子进程。

在 Windows 上子进程（默认）只由 @ref{2e5,,ProactorEventLoop} 提供，@ref{26d8,,SelectorEventLoop} 没有子进程支持。

在 UNIX 上会使用 @emph{child watchers} 来让子进程结束等待，详情请参阅 @ref{26d9,,进程监视器}。


在 3.8 版更改: UNIX 对于从不同线程中无限制地生成子进程会切换为使用 @ref{26da,,ThreadedChildWatcher}。

使用 @emph{不活动的} 当前子监视器生成子进程将引发 @ref{3e4,,RuntimeError}。


请注意其他的事件循环实现可能有其本身的限制；请查看它们各自的文档。


@subsubheading 参见


@ref{266b,,asyncio 中的并发和多线程} 章节。


@node 示例<19>,,子进程和线程,与子进程交互
@anchor{library/asyncio-subprocess examples}@anchor{26bd}
@subsubsection 示例


一个使用 @ref{26bf,,Process} 类来控制子进程并用 @ref{114e,,StreamReader} 类来从其标准输出读取信息的示例。
@anchor{library/asyncio-subprocess asyncio-example-create-subprocess-exec}@anchor{26db}
这个子进程是由 @ref{3bc,,create_subprocess_exec()} 函数创建的:

@example
import asyncio
import sys

async def get_date():
    code = 'import datetime; print(datetime.datetime.now())'

    # Create the subprocess; redirect the standard output
    # into a pipe.
    proc = await asyncio.create_subprocess_exec(
        sys.executable, '-c', code,
        stdout=asyncio.subprocess.PIPE)

    # Read one line of output.
    data = await proc.stdout.readline()
    line = data.decode('ascii').rstrip()

    # Wait for the subprocess exit.
    await proc.wait()
    return line

date = asyncio.run(get_date())
print(f"Current date: @{date@}")
@end example

另请参阅使用低层级 API 编写的 @ref{26dc,,相同示例}。

@node 队列集,异常<9>,子进程,asyncio --- 异步 I/O
@anchor{library/asyncio-queue doc}@anchor{26dd}@anchor{library/asyncio-queue asyncio-queues}@anchor{2650}@anchor{library/asyncio-queue queues}@anchor{26de}
@subsubsection 队列集


@strong{源代码:} Lib/asyncio/queues.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/queues.py}


__________________________________________________________________


asyncio 队列被设计成与 @ref{da,,queue} 模块类似。尽管 asyncio队列不是线程安全的，但是他们是被设计专用于 async/await 代码。

注意asyncio 的队列没有 @emph{timeout} 形参；请使用 @ref{191,,asyncio.wait_for()} 函数为队列添加超时操作。

参见下面的 @ref{26df,,Examples} 部分

@menu
* 队列:: 
* 优先级队列:: 
* 后进先出队列:: 
* 异常: 异常<8>. 
* 示例: 示例<20>. 

@end menu

@node 队列,优先级队列,,队列集
@anchor{library/asyncio-queue queue}@anchor{26e0}
@subsubsection 队列


@geindex Queue (asyncio 中的类)
@anchor{library/asyncio-queue asyncio Queue}@anchor{3bb}
@deffn {类} asyncio.Queue (maxsize=0, *, loop=None)

先进，先出（FIFO）队列

如果 @emph{maxsize} 小于等于零，则队列尺寸是无限的。如果是大于 @code{0} 的整数，则当队列达到 @emph{maxsize} 时， @code{await put()} 将阻塞至某个元素被 @ref{26e1,,get()} 取出。

不像标准库中的并发型 @ref{da,,queue} ，队列的尺寸一直是已知的，可以通过调用 @ref{26e2,,qsize()} 方法返回。


Deprecated since version 3.8, will be removed in version 3.10: @emph{loop} 形参。


这个类 @ref{266b,,不是线程安全的}。

@geindex maxsize (asyncio.Queue 属性)
@anchor{library/asyncio-queue asyncio Queue maxsize}@anchor{26e3}
@deffn {属性} maxsize

队列中可存放的元素数量。
@end deffn

@geindex empty() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue empty}@anchor{26e4}
@deffn {方法} empty ()

如果队列为空返回 @code{True} ，否则返回 @code{False} 。
@end deffn

@geindex full() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue full}@anchor{26e5}
@deffn {方法} full ()

如果有 @ref{26e3,,maxsize} 个条目在队列中，则返回 @code{True} 。

如果队列用 @code{maxsize=0} （默认）初始化，则 @ref{26e5,,full()} 永远不会返回 @code{True} 。
@end deffn

@geindex get() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue get}@anchor{26e1}
@deffn {方法} coroutine get ()

从队列中删除并返回一个元素。如果队列为空，则等待，直到队列中有元素。
@end deffn

@geindex get_nowait() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue get_nowait}@anchor{26e6}
@deffn {方法} get_nowait ()

立即返回一个队列中的元素，如果队列内有值，否则引发异常  @ref{26e7,,QueueEmpty} 。
@end deffn

@geindex join() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue join}@anchor{79c}
@deffn {方法} coroutine join ()

阻塞至队列中所有的元素都被接收和处理完毕。

当条目添加到队列的时候，未完成任务的计数就会增加。每当消费协程调用 @ref{79d,,task_done()} 表示这个条目已经被回收，该条目所有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候， @ref{79c,,join()} 阻塞被解除。
@end deffn

@geindex put() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue put}@anchor{26e8}
@deffn {方法} coroutine put (item)

添加一个元素进队列。如果队列满了，在添加元素之前，会一直等待空闲插槽可用。
@end deffn

@geindex put_nowait() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue put_nowait}@anchor{26e9}
@deffn {方法} put_nowait (item)

不阻塞的放一个元素入队列。

如果没有立即可用的空闲槽，引发 @ref{26ea,,QueueFull} 异常。
@end deffn

@geindex qsize() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue qsize}@anchor{26e2}
@deffn {方法} qsize ()

返回队列用的元素数量。
@end deffn

@geindex task_done() (asyncio.Queue 方法)
@anchor{library/asyncio-queue asyncio Queue task_done}@anchor{79d}
@deffn {方法} task_done ()

表明前面排队的任务已经完成，即get出来的元素相关操作已经完成。

由队列使用者控制。每个 @ref{26e1,,get()} 用于获取一个任务，任务最后调用 @ref{79d,,task_done()} 告诉队列，这个任务已经完成。

如果 @ref{79c,,join()} 当前正在阻塞，在所有条目都被处理后，将解除阻塞(意味着每个 @ref{26e8,,put()} 进队列的条目的 @ref{79d,,task_done()} 都被收到)。

如果被调用的次数多于放入队列中的项目数量，将引发 @ref{16d,,ValueError} 。
@end deffn
@end deffn

@node 优先级队列,后进先出队列,队列,队列集
@anchor{library/asyncio-queue priority-queue}@anchor{26eb}
@subsubsection 优先级队列


@geindex PriorityQueue (asyncio 中的类)
@anchor{library/asyncio-queue asyncio PriorityQueue}@anchor{26ec}
@deffn {类} asyncio.PriorityQueue

@ref{3bb,,Queue} 的变体；按优先级顺序取出条目 (最小的先取出)。

条目通常是 @code{(priority_number, data)} 形式的元组。
@end deffn

@node 后进先出队列,异常<8>,优先级队列,队列集
@anchor{library/asyncio-queue lifo-queue}@anchor{26ed}
@subsubsection 后进先出队列


@geindex LifoQueue (asyncio 中的类)
@anchor{library/asyncio-queue asyncio LifoQueue}@anchor{26ee}
@deffn {类} asyncio.LifoQueue

@ref{3bb,,Queue} 的变体，先取出最近添加的条目（后进，先出）。
@end deffn

@node 异常<8>,示例<20>,后进先出队列,队列集
@anchor{library/asyncio-queue exceptions}@anchor{26ef}
@subsubsection 异常


@geindex QueueEmpty
@anchor{library/asyncio-queue asyncio QueueEmpty}@anchor{26e7}
@deffn {例外} asyncio.QueueEmpty

当队列为空的时候，调用 @ref{26e6,,get_nowait()} 方法而引发这个异常。
@end deffn

@geindex QueueFull
@anchor{library/asyncio-queue asyncio QueueFull}@anchor{26ea}
@deffn {例外} asyncio.QueueFull

当队列中条目数量已经达到它的 @emph{maxsize} 的时候，调用 @ref{26e9,,put_nowait()} 方法而引发的异常。
@end deffn

@node 示例<20>,,异常<8>,队列集
@anchor{library/asyncio-queue examples}@anchor{26df}
@subsubsection 示例

@anchor{library/asyncio-queue asyncio-example-queue-dist}@anchor{26f0}
队列能被用于多个的并发任务的工作量分配：

@example
import asyncio
import random
import time


async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()

        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)

        # Notify the queue that the "work item" has been processed.
        queue.task_done()

        print(f'@{name@} has slept for @{sleep_for:.2f@} seconds')


async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()

    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)

    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-@{i@}', queue))
        tasks.append(task)

    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at

    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

    print('====')
    print(f'3 workers slept in parallel for @{total_slept_for:.2f@} seconds')
    print(f'total expected sleep time: @{total_sleep_time:.2f@} seconds')


asyncio.run(main())
@end example

@node 异常<9>,事件循环,队列集,asyncio --- 异步 I/O
@anchor{library/asyncio-exceptions doc}@anchor{26f1}@anchor{library/asyncio-exceptions asyncio-exceptions}@anchor{26f2}@anchor{library/asyncio-exceptions exceptions}@anchor{26f3}
@subsubsection 异常


@strong{源代码:} Lib/asyncio/exceptions.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/exceptions.py}


__________________________________________________________________


@geindex TimeoutError
@anchor{library/asyncio-exceptions asyncio TimeoutError}@anchor{2665}
@deffn {例外} asyncio.TimeoutError

该操作已超过规定的截止日期。

@cartouche
@quotation 重要 
这个异常与内置 @ref{a86,,TimeoutError} 异常不同。
@end quotation
@end cartouche
@end deffn

@geindex CancelledError
@anchor{library/asyncio-exceptions asyncio CancelledError}@anchor{2e1}
@deffn {例外} asyncio.CancelledError

该操作已被取消。

取消asyncio任务时，可以捕获此异常以执行自定义操作。在几乎所有情况下，都必须重新引发异常。


在 3.8 版更改: @ref{2e1,,CancelledError} 现在是 @ref{2e2,,BaseException} 的子类。

@end deffn

@geindex InvalidStateError
@anchor{library/asyncio-exceptions asyncio InvalidStateError}@anchor{2675}
@deffn {例外} asyncio.InvalidStateError

@ref{2e7,,Task} 或 @ref{54e,,Future} 的内部状态无效。

在为已设置结果值的未来对象设置结果值等情况下，可以引发此问题。
@end deffn

@geindex SendfileNotAvailableError
@anchor{library/asyncio-exceptions asyncio SendfileNotAvailableError}@anchor{26f4}
@deffn {例外} asyncio.SendfileNotAvailableError

"sendfile" 系统调用不适用于给定的套接字或文件类型。

子类 @ref{3e4,,RuntimeError} 。
@end deffn

@geindex IncompleteReadError
@anchor{library/asyncio-exceptions asyncio IncompleteReadError}@anchor{1026}
@deffn {例外} asyncio.IncompleteReadError

请求的读取操作未完全完成。

由 @ref{264e,,asyncio stream APIs} 提出

此异常是 @ref{d3c,,EOFError} 的子类。

@geindex expected (asyncio.IncompleteReadError 属性)
@anchor{library/asyncio-exceptions asyncio IncompleteReadError expected}@anchor{26f5}
@deffn {属性} expected

预期字节的总数（ @ref{205,,int} ）。
@end deffn

@geindex partial (asyncio.IncompleteReadError 属性)
@anchor{library/asyncio-exceptions asyncio IncompleteReadError partial}@anchor{2689}
@deffn {属性} partial

到达流结束之前读取的 @ref{172,,bytes} 字符串。
@end deffn
@end deffn

@geindex LimitOverrunError
@anchor{library/asyncio-exceptions asyncio LimitOverrunError}@anchor{268a}
@deffn {例外} asyncio.LimitOverrunError

在查找分隔符时达到缓冲区大小限制。

由 @ref{264e,,asyncio stream APIs} 提出

@geindex consumed (asyncio.LimitOverrunError 属性)
@anchor{library/asyncio-exceptions asyncio LimitOverrunError consumed}@anchor{26f6}
@deffn {属性} consumed

要消耗的字节总数。
@end deffn
@end deffn

@node 事件循环,Futures,异常<9>,asyncio --- 异步 I/O
@anchor{library/asyncio-eventloop doc}@anchor{26f7}@anchor{library/asyncio-eventloop event-loop}@anchor{26f8}
@subsubsection 事件循环


@strong{源代码:} Lib/asyncio/events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/events.py}, Lib/asyncio/base_events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py}


__________________________________________________________________


@subsubheading 前言


事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调，执行网络 IO 操作，以及运行子进程。

应用开发者通常应当使用高层级的 asyncio 函数，例如 @ref{18d,,asyncio.run()}，应当很少有必要引用循环对象或调用其方法。 本节所针对的主要是低层级代码、库和框架的编写者，他们需要更细致地控制事件循环行为。

@subsubheading 获取事件循环


以下低层级函数可被用于获取、设置或创建事件循环:

@geindex get_running_loop() (在 asyncio 模块中)
@anchor{library/asyncio-eventloop asyncio get_running_loop}@anchor{465}
@deffn {函数} asyncio.get_running_loop ()

返回当前 OS 线程中正在运行的事件循环。

如果没有正在运行的事件循环则会引发 @ref{3e4,,RuntimeError}。 此函数只能由协程或回调来调用。


3.7 新版功能.

@end deffn

@geindex get_event_loop() (在 asyncio 模块中)
@anchor{library/asyncio-eventloop asyncio get_event_loop}@anchor{466}
@deffn {函数} asyncio.get_event_loop ()

获取当前事件循环。

如果当前 OS 线程没有设置当前事件循环，该 OS 线程为主线程，并且 @ref{26f9,,set_event_loop()} 还没有被调用，则 asyncio 将创建一个新的事件循环并将其设为当前事件循环。

由于此函数具有相当复杂的行为（特别是在使用了自定义事件循环策略的时候），更推荐在协程和回调中使用 @ref{465,,get_running_loop()} 函数而非 @ref{466,,get_event_loop()}。

应该考虑使用 @ref{18d,,asyncio.run()} 函数而非使用低层级函数来手动创建和关闭事件循环。
@end deffn

@geindex set_event_loop() (在 asyncio 模块中)
@anchor{library/asyncio-eventloop asyncio set_event_loop}@anchor{26f9}
@deffn {函数} asyncio.set_event_loop (loop)

将 @emph{loop} 设置为当前 OS 线程的当前事件循环。
@end deffn

@geindex new_event_loop() (在 asyncio 模块中)
@anchor{library/asyncio-eventloop asyncio new_event_loop}@anchor{26fa}
@deffn {函数} asyncio.new_event_loop ()

创建并返回一个新的事件循环对象。
@end deffn

请注意 @ref{466,,get_event_loop()}, @ref{26f9,,set_event_loop()} 以及 @ref{26fa,,new_event_loop()} 函数的行为可以通过 @ref{26fb,,设置自定义事件循环策略} 来改变。

@subsubheading 内容


本文档包含下列小节:


@itemize *

@item 
@ref{26fc,,事件循环方法集} 章节是事件循环APIs的参考文档；

@item 
@ref{26fd,,回调处理} 章节是从调度方法 例如 @ref{45e,,loop.call_soon()}  和 @ref{460,,loop.call_later()} 中返回 @ref{121f,,Handle} 和 @ref{26fe,,TimerHandle} 实例的文档。

@item 
@ref{26ff,,Server Objects} 章节记录了从事件循环方法返回的类型，比如 @ref{46e,,loop.create_server()} ；

@item 
@ref{2700,,Event Loop Implementations} 章节记录了 @ref{26d8,,SelectorEventLoop} 和 @ref{2e5,,ProactorEventLoop} 类；

@item 
@ref{2701,,Examples} 章节展示了如何使用某些事件循环API。
@end itemize

@menu
* 事件循环方法集:: 
* 回调处理:: 
* Server 对象:: 
* 事件循环实现:: 
* 示例: 示例<21>. 

@end menu

@node 事件循环方法集,回调处理,,事件循环
@anchor{library/asyncio-eventloop asyncio-event-loop}@anchor{741}@anchor{library/asyncio-eventloop event-loop-methods}@anchor{26fc}
@subsubsection 事件循环方法集


事件循环有下列 @strong{低级} APIs：

@menu
* 运行和停止循环:: 
* 安排回调:: 
* 调度延迟回调:: 
* 创建 Future 和 Task:: 
* 打开网络连接:: 
* 创建网络服务:: 
* 传输文件:: 
* TLS 升级:: 
* 监控文件描述符:: 
* 直接使用 socket 对象:: 
* DNS:: 
* 使用管道:: 
* Unix 信号:: 
* 在线程或者进程池中执行代码。:: 
* 错误处理API:: 
* 开启调试模式:: 
* 运行子进程:: 

@end menu

@node 运行和停止循环,安排回调,,事件循环方法集
@anchor{library/asyncio-eventloop running-and-stopping-the-loop}@anchor{2702}
@subsubsection 运行和停止循环


@geindex run_until_complete() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop run_until_complete}@anchor{61a}
@deffn {方法} loop.run_until_complete (future)

运行直到 @emph{future} (  @ref{54e,,Future} 的实例 ) 被完成。

如果参数是 @ref{264d,,coroutine object} ，将被隐式调度为 @ref{2e7,,asyncio.Task} 来运行。

返回 Future 的结果 或者引发相关异常。
@end deffn

@geindex run_forever() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop run_forever}@anchor{2703}
@deffn {方法} loop.run_forever ()

运行事件循环直到 @ref{622,,stop()} 被调用。

如果 @ref{622,,stop()} 在调用 @ref{2703,,run_forever()} 之前被调用，循环将轮询一次 I/O 选择器并设置超时为零，再运行所有已加入计划任务的回调来响应 I/O 事件（以及已加入计划任务的事件），然后退出。

如果 @ref{622,,stop()} 在 @ref{2703,,run_forever()} 运行期间被调用，循环将运行当前批次的回调然后退出。 请注意在此情况下由回调加入计划任务的新回调将不会运行；它们将会在下次 @ref{2703,,run_forever()} 或 @ref{61a,,run_until_complete()} 被调用时运行。
@end deffn

@geindex stop() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop stop}@anchor{622}
@deffn {方法} loop.stop ()

停止事件循环。
@end deffn

@geindex is_running() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop is_running}@anchor{2704}
@deffn {方法} loop.is_running ()

返回 @code{True} 如果事件循环当前正在运行。
@end deffn

@geindex is_closed() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop is_closed}@anchor{798}
@deffn {方法} loop.is_closed ()

如果事件循环已经被关闭，返回 @code{True} 。
@end deffn

@geindex close() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop close}@anchor{2705}
@deffn {方法} loop.close ()

关闭事件循环。

当这个函数被调用的时候，循环必须处于非运行状态。pending状态的回调将被丢弃。

此方法清除所有的队列并立即关闭执行器，不会等待执行器完成。

这个方法是幂等的和不可逆的。事件循环关闭后，不应调用其他方法。
@end deffn

@geindex shutdown_asyncgens() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop shutdown_asyncgens}@anchor{623}
@deffn {方法} coroutine loop.shutdown_asyncgens ()

安排所有当前打开的 @ref{166f,,asynchronous generator} 对象通过 @ref{176,,aclose()} 调用来关闭。 在调用此方法后，如果有新的异步生成器被迭代事件循环将会发出警告。 这应当被用来可靠地完成所有已加入计划任务的异步生成器。

请注意当使用 @ref{18d,,asyncio.run()} 时不必调用此函数。

示例:

@example
try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
@end example


3.6 新版功能.

@end deffn

@geindex shutdown_default_executor() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop shutdown_default_executor}@anchor{18b}
@deffn {方法} coroutine loop.shutdown_default_executor ()

安排默认执行器的关闭并等待它合并 @code{ThreadPoolExecutor} 中的所有线程。 在调用此方法后，如果在使用默认执行器期间调用了 @ref{190,,loop.run_in_executor()} 则将会引发 @ref{3e4,,RuntimeError}。

请注意当使用 @ref{18d,,asyncio.run()} 时不必调用此函数。


3.9 新版功能.

@end deffn

@node 安排回调,调度延迟回调,运行和停止循环,事件循环方法集
@anchor{library/asyncio-eventloop scheduling-callbacks}@anchor{2706}
@subsubsection 安排回调


@geindex call_soon() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop call_soon}@anchor{45e}
@deffn {方法} loop.call_soon (callback, *args, context=None)

安排 @emph{callback} @ref{2707,,callback} 在事件循环的下一次迭代时附带 @emph{args} 参数被调用。

回调按其注册顺序被调用。每个回调仅被调用一次。

可选的仅关键字型参数 @emph{context} 允许为要运行的 @emph{callback} 指定一个自定义 @ref{2625,,contextvars.Context} 。如果没有提供 @emph{context} ，则使用当前上下文。

返回一个能用来取消回调的 @ref{121f,,asyncio.Handle} 实例。

这个方法不是线程安全的。
@end deffn

@geindex call_soon_threadsafe() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop call_soon_threadsafe}@anchor{45f}
@deffn {方法} loop.call_soon_threadsafe (callback, *args, context=None)

@ref{45e,,call_soon()} 的线程安全变体。必须被用于安排 @emph{来自其他线程} 的回调。

如果在已被关闭的循环上调用则会引发 @ref{3e4,,RuntimeError}。 这可能会在主应用程序被关闭时在二级线程上发生。

查看 @ref{266b,,并发和多线程} 章节的文档。
@end deffn


在 3.7 版更改: 仅用于关键字形参的参数  @emph{context}  已经被添加。请参阅： 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} 查看更多细节。

@anchor{library/asyncio-eventloop asyncio-pass-keywords}@anchor{2708}
@cartouche
@quotation 注解 
大多数 @ref{9,,asyncio} 的调度函数不让传递关键字参数。为此，请使用 @ref{8bf,,functools.partial()} ：

@example
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
@end example

使用 partial 对象通常比使用lambda更方便，asyncio 在调试和错误消息中能更好的呈现 partial 对象。
@end quotation
@end cartouche

@node 调度延迟回调,创建 Future 和 Task,安排回调,事件循环方法集
@anchor{library/asyncio-eventloop asyncio-delayed-calls}@anchor{2709}@anchor{library/asyncio-eventloop scheduling-delayed-callbacks}@anchor{270a}
@subsubsection 调度延迟回调


事件循环提供安排调度函数在将来某个时刻调用的机制。事件循环使用单调时钟来跟踪时间。

@geindex call_later() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop call_later}@anchor{460}
@deffn {方法} loop.call_later (delay, callback, *args, context=None)

安排 @emph{callback} 在给定的 @emph{delay} 秒（可以是 int 或者 float）后被调用。

返回一个 @ref{26fe,,asyncio.TimerHandle} 实例，该实例能用于取消回调。

@emph{callback} 只被调用一次。如果两个回调被安排在同样的时间点，执行顺序未限定。

可选的位置参数 @emph{args} 在被调用的时候传递给  @emph{callback}  。 如果你想把关键字参数传递给 @emph{callback} ，请使用 @ref{8bf,,functools.partial()} 。

可选的仅关键字型参数 @emph{context} 允许为要运行的 @emph{callback} 指定一个自定义 @ref{2625,,contextvars.Context} 。如果没有提供 @emph{context} ，则使用当前上下文。


在 3.7 版更改: 仅用于关键字形参的参数  @emph{context}  已经被添加。请参阅： 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} 查看更多细节。



在 3.8 版更改: 在 Python 3.7 和更早版本的默认事件循环实现中， @emph{delay} 不能超过一天。 这在 Python 3.8 中已被修复。

@end deffn

@geindex call_at() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop call_at}@anchor{461}
@deffn {方法} loop.call_at (when, callback, *args, context=None)

安排 @emph{callback} 在给定的绝对时间戳 @emph{when} (int 或 float) 被调用，使用与 @ref{270b,,loop.time()} 同样的时间参考。

这个函数的行为与 @ref{460,,call_later()} 相同。

返回一个 @ref{26fe,,asyncio.TimerHandle} 实例，该实例能用于取消回调。


在 3.7 版更改: 仅用于关键字形参的参数  @emph{context}  已经被添加。请参阅： 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} 查看更多细节。



在 3.8 版更改: 在 Python 3.7 和更早版本的默认事件循环实现中，@emph{when} 和当前时间相差不能超过一天。 在这 Python 3.8 中已被修复。

@end deffn

@geindex time() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop time}@anchor{270b}
@deffn {方法} loop.time ()

根据时间循环内部的单调时钟，返回当前时间为一个 @ref{1fe,,float} 值。
@end deffn

@cartouche
@quotation 注解 

在 3.8 版更改: 在 Python 3.7 和更早版本中超时 (相对的 @emph{delay} 或绝对的 @emph{when}) 不能超过一天。 这在 Python 3.8 中已被修复。

@end quotation
@end cartouche


@subsubheading 参见


@ref{3b2,,asyncio.sleep()} 函数


@node 创建 Future 和 Task,打开网络连接,调度延迟回调,事件循环方法集
@anchor{library/asyncio-eventloop creating-futures-and-tasks}@anchor{270c}
@subsubsection 创建 Future 和 Task


@geindex create_future() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_future}@anchor{61e}
@deffn {方法} loop.create_future ()

创建一个附加到事件循环中的 @ref{54e,,asyncio.Future} 对象。

这是在asyncio中创建Futures的首选方式。这让第三方事件循环可以提供Future 对象的替代实现(更好的性能或者功能)。


3.5.2 新版功能.

@end deffn

@geindex create_task() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_task}@anchor{2e9}
@deffn {方法} loop.create_task (coro, *, name=None)

安排一个 @ref{264d,,协程} 的执行。返回一个  @ref{2e7,,Task}  对象。

三方的事件循环可以使用它们自己定义的 @ref{2e7,,Task} 类的子类来实现互操作性。这个例子里，返回值的类型是 @ref{2e7,,Task} 的子类。

如果提供了 @emph{name} 参数且不为 @code{None}，它会使用 @ref{2ea,,Task.set_name()} 来设为任务的名称。


在 3.8 版更改: 添加了 @code{name} 形参。

@end deffn

@geindex set_task_factory() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop set_task_factory}@anchor{79a}
@deffn {方法} loop.set_task_factory (factory)

设置一个任务工厂，它将由 @ref{2e9,,loop.create_task()} 来使用。

如果 @emph{factory} 为 @code{None} 则将设置默认的任务工厂。 在其他情况下，@emph{factory} 必须为一个 @emph{可调用对象} 且签名匹配 @code{(loop, coro)}，其中 @emph{loop} 是对活动事件循环的引用，而 @emph{coro} 是一个协程对象。 该可调用对象必须返回一个兼容 @ref{54e,,asyncio.Future} 的对象。
@end deffn

@geindex get_task_factory() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop get_task_factory}@anchor{79b}
@deffn {方法} loop.get_task_factory ()

返回一个任务工厂，或者如果是使用默认值则返回 @code{None}。
@end deffn

@node 打开网络连接,创建网络服务,创建 Future 和 Task,事件循环方法集
@anchor{library/asyncio-eventloop opening-network-connections}@anchor{270d}
@subsubsection 打开网络连接


@geindex create_connection() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_connection}@anchor{2ec}
@deffn {方法} coroutine loop.create_connection (protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None)

打开一个流式传输连接，连接到由 @emph{host} 和 @emph{port} 指定的地址。

套接字族可以是 @ref{f76,,AF_INET} 或 @ref{f77,,AF_INET6}，具体取决于 @emph{host} (或 @emph{family} 参数，如果有提供的话)。

套接字类型将为 @ref{d5a,,SOCK_STREAM}。

@emph{protocol_factory} 必须为一个返回 @ref{270e,,asyncio 协议} 实现的可调用对象。

这个方法会尝试在后台创建连接。当创建成功，返回 @code{(transport, protocol)} 组合。

基本操作的时间顺序如下：


@enumerate 

@item 
创建连接并为其创建一个 @ref{270f,,传输}。

@item 
不带参数地调用 @emph{protocol_factory} 并预期返回一个 @ref{270e,,协议} 实例。

@item 
协议实例通过调用其 @ref{2710,,connection_made()} 方法与传输进行配对。

@item 
成功时返回一个 @code{(transport, protocol)} 元组。
@end enumerate

创建的传输是一个具体实现相关的双向流。

其他参数：


@itemize *

@item 
@emph{ssl}: 如果给定该参数且不为假值，则会创建一个 SSL/TLS 传输（默认创建一个纯 TCP 传输）。 如果 @emph{ssl} 是一个 @ref{4f2,,ssl.SSLContext} 对象，则会使用此上下文来创建传输对象；如果 @emph{ssl} 为 @ref{59c,,True}，则会使用从 @ref{9b0,,ssl.create_default_context()} 返回的默认上下文。


@subsubheading 参见


@ref{2711,,SSL/TLS安全事项}


@item 
@emph{server_hostname} 设置或重载目标服务器的证书将要匹配的主机名。 应当只在 @emph{ssl} 不为 @code{None} 时传入。 默认情况下会使用 @emph{host} 参数的值。 如果 @emph{host} 为空那就没有默认值，你必须为 @emph{server_hostname} 传入一个值。 如果 @emph{server_hostname} 为空字符串，则主机名匹配会被禁用（这是一个严重的安全风险，使得潜在的中间人攻击成为可能）。

@item 
@emph{family}，@emph{proto}，@emph{flags} 是可选的地址族，协议和标志，通过传递给 getaddrinfo() 来解析 @emph{host}。如果给出，这些应该都是来自 @ref{ef,,socket} 模块相应的常量的整数。

@item 
如果给出 @emph{happy_eyeballs_delay}，它将为此链接启用 Happy Eyeballs。 该函数应当为一个表示在开始下一个并行尝试之前要等待连接尝试完成的秒数的浮点数。 这也就是在 
@geindex RFC; RFC 8305
RFC 8305@footnote{https://tools.ietf.org/html/rfc8305.html} 中定义的 "连接尝试延迟"。 该 RFC 所推荐的合理默认值为 @code{0.25} (250 毫秒)。

@item 
@emph{interleave} 控制当主机名解析为多个 IP 地址时的地址重排序。 如果该参数为 @code{0} 或未指定，则不会进行重排序，这些地址会按 @ref{5a4,,getaddrinfo()} 所返回的顺序进行尝试。 如果指定了一个正整数，这些地址会按地址族交错排列，而指定的整数会被解读为 
@geindex RFC; RFC 8305
RFC 8305@footnote{https://tools.ietf.org/html/rfc8305.html} 所定义的 "首个地址族计数"。 如果 @emph{happy_eyeballs_delay} 未指定则默认值为 @code{0}，否则为 @code{1}。

@item 
如果给出 @emph{sock}，它应当是一个已存在、已连接并将被传输所使用的 @ref{771,,socket.socket} 对象。 如果给出了 @emph{sock}，则 @emph{host}, @emph{port}, @emph{family}, @emph{proto}, @emph{flags}, @emph{happy_eyeballs_delay}, @emph{interleave} 和 @emph{local_addr} 都不应当被指定。

@item 
如果给出 @emph{local_addr}，它应当是一个用来在本地绑定套接字的 @code{(local_host, local_port)} 元组。 @emph{local_host} 和 @emph{local_port} 会使用 @code{getaddrinfo()} 来查找，这与 @emph{host} 和 @emph{port} 类似。

@item 
@emph{ssl_handshake_timeout} 是（用于 TLS 连接的）在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 @code{None} 则使用 (默认的) @code{60.0}。
@end itemize


3.8 新版功能: 增加了 @emph{happy_eyeballs_delay} 和 @emph{interleave} 形参。

Happy Eyeballs 算法：成功使用双栈主机。 当服务器的 IPv4 路径和协议工作正常，但服务器的 IPv6 路径和协议工作不正常时，双栈客户端应用程序相比单独 IPv4 客户端会感受到明显的连接延迟。 这是不可接受的因为它会导致双栈客户端糟糕的用户体验。 此文档指明了减少这种用户可见延迟的算法要求并提供了具体的算法。

详情参见: @indicateurl{https://tools.ietf.org/html/rfc6555}



3.7 新版功能: @emph{ssl_handshake_timeout} 形参。



在 3.6 版更改: 套接字选项 @code{TCP_NODELAY} 默认已为所有 TCP 连接进行了设置。



在 3.5 版更改: @ref{2e5,,ProactorEventLoop} 类中添加 SSL/TLS 支持。



@subsubheading 参见


@ref{474,,open_connection()} 函数是一个高层级的替代 API。 它返回一对 (@ref{114e,,StreamReader}, @ref{114f,,StreamWriter})，可在 async/await 代码中直接使用。

@end deffn

@geindex create_datagram_endpoint() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_datagram_endpoint}@anchor{189}
@deffn {方法} coroutine loop.create_datagram_endpoint (protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)

@cartouche
@quotation 注解 
形参 @emph{reuse_address} 已不再受支持，因为使用 @code{SO_REUSEADDR} 会对 UDP 造成显著的安全问题。 显式地传入 @code{reuse_address=True} 将会引发异常。

当具有不同 UID 的多个进程将套接字赋给具有 @code{SO_REUSEADDR} 的相同 UDP 套接字地址时，传入的数据包可能会在套接字间随机分配。

对于受支持的平台，@emph{reuse_port} 可以被用作类似功能的替代。 通过 @emph{reuse_port} 将改用 @code{SO_REUSEPORT}，它能够防止具有不同 UID 的进程将套接字赋给相同的套接字地址。
@end quotation
@end cartouche

创建一个数据报连接。

套接字族可以是 @ref{f76,,AF_INET}, @ref{f77,,AF_INET6} 或 @ref{f78,,AF_UNIX}，具体取决于 @emph{host} (或 @emph{family} 参数，如果有提供的话)。

socket类型将是 @ref{d59,,SOCK_DGRAM} 。

@emph{protocol_factory} 必须为一个返回 @ref{270e,,协议} 实现的可调用对象。

成功时返回一个 @code{(transport, protocol)} 元组。

其他参数：


@itemize *

@item 
如果给出 @emph{local_addr}，它应当是一个用来在本地绑定套接字的 @code{(local_host, local_port)} 元组。 @emph{local_host} 和 @emph{local_port} 是使用 @ref{5a4,,getaddrinfo()} 来查找的。

@item 
@emph{remote_addr}，如果指定的话，就是一个 @code{(remote_host, remote_port)} 元组，用于同一个远程地址连接。@emph{remote_host} 和 @emph{remote_port} 是使用 @ref{5a4,,getaddrinfo()} 来查找的。

@item 
@emph{family}, @emph{proto}, @emph{flags} 是可选的地址族，协议和标志，其会被传递给 @ref{5a4,,getaddrinfo()} 来完成 @emph{host} 的解析。如果要指定的话，这些都应该是来自于 @ref{ef,,socket} 模块的对应常量。

@item 
@emph{reuse_port} 告知内核，只要在创建时都设置了这个旗标，就允许此端点绑定到其他现有端点所绑定的相同端口上。 这个选项在 Windows 和某些 Unix 上不受支持。 如果 @code{SO_REUSEPORT} 常量未定义则此功能就是不受支持的。

@item 
@emph{allow_broadcast} 告知内核允许此端点向广播地址发送消息。

@item 
@emph{sock} 可选择通过指定此值用于使用一个预先存在的，已经处于连接状态的 @ref{771,,socket.socket} 对象，并将其提供给此传输对象使用。如果指定了这个值， @emph{local_addr} 和 @emph{remote_addr} 就应该被忽略 (必须为 @ref{204,,None})。
@end itemize

参见 @ref{2712,,UDP echo 客户端协议}  和 @ref{2713,,UDP echo 服务端协议} 的例子。


在 3.4.4 版更改: 添加了 @emph{family}, @emph{proto}, @emph{flags}, @emph{reuse_address}, @emph{reuse_port}, @emph{allow_broadcast} 和 @emph{sock} 等参数。



在 3.8.1 版更改: 出于安全考虑，@emph{reuse_address} 形参已不再受支持。



在 3.8 版更改: 添加WIndows的支持。

@end deffn

@geindex create_unix_connection() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_unix_connection}@anchor{2684}
@deffn {方法} coroutine loop.create_unix_connection (protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)

创建Unix 连接

套接字族将为 @ref{f78,,AF_UNIX}；套接字类型将为 @ref{d5a,,SOCK_STREAM}。

成功时返回一个 @code{(transport, protocol)} 元组。

@emph{path} 是所要求的 Unix 域套接字的名字，除非指定了 @emph{sock} 形参。 抽象的 Unix 套接字, @ref{206,,str}, @ref{172,,bytes} 和 @ref{336,,Path} 路径都是受支持的。

请查看 @ref{2ec,,loop.create_connection()} 方法的文档了解有关此方法的参数的信息。

@ref{14c1,,可用性}: Unix。


3.7 新版功能: @emph{ssl_handshake_timeout} 形参。



在 3.7 版更改: @emph{path} 形参现在可以是 @ref{47b,,path-like object} 对象。

@end deffn

@node 创建网络服务,传输文件,打开网络连接,事件循环方法集
@anchor{library/asyncio-eventloop creating-network-servers}@anchor{2714}
@subsubsection 创建网络服务


@geindex create_server() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_server}@anchor{46e}
@deffn {方法} coroutine loop.create_server (protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)

创建TCP服务 (socket 类型 @ref{d5a,,SOCK_STREAM} ) 监听 @emph{host} 地址的 @emph{port} 端口。

返回一个 @ref{46d,,Server} 对象。

参数：


@itemize *

@item 
@emph{protocol_factory} 必须为一个返回 @ref{270e,,协议} 实现的可调用对象。

@item 
@emph{host} 形参可被设为几种类型，它确定了服务器所应监听的位置:


@itemize -

@item 
如果 @emph{host} 是一个字符串，则 TCP 服务器会被绑定到 @emph{host} 所指明的单一网络接口。

@item 
如果 @emph{host} 是一个字符串序列，则 TCP 服务器会被绑定到序列所指明的所有网络接口。

@item 
如果 @emph{host} 是一个空字符串或 @code{None}，则会应用所有接口并将返回包含多个套接字的列表（通常是一个 IPv4 的加一个 IPv6 的）。
@end itemize

@item 
可以设置 @emph{port} 参数来指定服务器应该监听哪个端口。如果为 @code{0} 或者 @code{None} （默认），将选择一个随机的未使用的端口（注意，如果 @emph{host} 解析到多个网络接口，将为每个接口选择一个不同的随机端口）。

@item 
@emph{family} 可被设为 @ref{f76,,socket.AF_INET} 或 @ref{f77,,AF_INET6} 以强制此套接字使用 IPv4 或 IPv6。 如果未设定，则 @emph{family} 将通过主机名称来确定 (默认为 @code{AF_UNSPEC})。

@item 
@emph{flags} 是用于 @ref{5a4,,getaddrinfo()} 的位掩码。

@item 
可以选择指定 @emph{sock} 以便使用预先存在的套接字对象。 如果指定了此参数，则不可再指定 @emph{host} 和 @emph{port}。

@item 
@emph{backlog} 是传递给 @ref{844,,listen()} 的最大排队连接的数量（默认为100）。

@item 
@emph{ssl} 可被设置为一个 @ref{4f2,,SSLContext} 实例以在所接受的连接上启用 TLS。

@item 
@emph{reuse_address} 告知内核要重用一个处于 @code{TIME_WAIT} 状态的本地套接字，而不是等待其自然超时失效。 如果未指定此参数则在 Unix 上将自动设置为 @code{True}。

@item 
@emph{reuse_port} 告知内核，只要在创建的时候都设置了这个标志，就允许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在 Windows 上是不支持的。

@item 
@emph{ssl_handshake_timeout} 是（用于 TLS 服务器的）在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 (默认值) @code{None} 则为 @code{60.0} 秒。

@item 
@emph{start_serving} 设置成 @code{True} (默认值) 会导致创建server并立即开始接受连接。设置成 @code{False} ，用户需要等待 @ref{470,,Server.start_serving()} 或者 @ref{471,,Server.serve_forever()} 以使server开始接受连接。
@end itemize


3.7 新版功能: 增加了 @emph{ssl_handshake_timeout} 和 @emph{start_serving} 形参。



在 3.6 版更改: 套接字选项 @code{TCP_NODELAY} 默认已为所有 TCP 连接进行了设置。



在 3.5 版更改: @ref{2e5,,ProactorEventLoop} 类中添加 SSL/TLS 支持。



在 3.5.1 版更改: @emph{host} 形参可以是一个字符串的序列。



@subsubheading 参见


@ref{475,,start_server()} 函数是一个高层级的替代 API，它返回一对 @ref{114e,,StreamReader} 和 @ref{114f,,StreamWriter}，可在 async/await 代码中使用。

@end deffn

@geindex create_unix_server() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop create_unix_server}@anchor{46f}
@deffn {方法} coroutine loop.create_unix_server (protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)

与 @ref{46e,,loop.create_server()} 类似但是专用于 @ref{f78,,AF_UNIX} 套接字族。

@emph{path} 是必要的 Unix 域套接字名称，除非提供了 @emph{sock} 参数。 抽象的 Unix 套接字, @ref{206,,str}, @ref{172,,bytes} 和 @ref{336,,Path} 路径都是受支持的。

请查看 @ref{46e,,loop.create_server()} 方法的文档了解有关此方法的参数的信息。

@ref{14c1,,可用性}: Unix。


3.7 新版功能: The @emph{ssl_handshake_timeout} and @emph{start_serving} parameters.



在 3.7 版更改: @emph{path} 形参现在可以是 @ref{336,,Path} 对象。

@end deffn

@geindex connect_accepted_socket() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop connect_accepted_socket}@anchor{476}
@deffn {方法} coroutine loop.connect_accepted_socket (protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None)

将已被接受的连接包装成一个传输/协议对。

此方法可被服务器用来接受 asyncio 以外的连接，但是使用 asyncio 来处理它们。

参数：


@itemize *

@item 
@emph{protocol_factory} 必须为一个返回 @ref{270e,,协议} 实现的可调用对象。

@item 
@emph{sock} 是一个预先存在的套接字对象，它是由 @ref{772,,socket.accept} 返回的。

@item 
@emph{ssl} 可被设置为一个 @ref{4f2,,SSLContext} 以在接受的连接上启用 SSL。

@item 
@emph{ssl_handshake_timeout} 是(为一个SSL连接)在中止连接前，等待SSL握手完成的时间【单位秒】。如果为 @code{None} (缺省) 则是 @code{60.0} 秒。
@end itemize

返回一个 @code{(transport, protocol)} 对。


3.7 新版功能: @emph{ssl_handshake_timeout} 形参。



3.5.3 新版功能.

@end deffn

@node 传输文件,TLS 升级,创建网络服务,事件循环方法集
@anchor{library/asyncio-eventloop transferring-files}@anchor{2715}
@subsubsection 传输文件


@geindex sendfile() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sendfile}@anchor{2716}
@deffn {方法} coroutine loop.sendfile (transport, file, offset=0, count=None, *, fallback=True)

将 @emph{file} 通过 @emph{transport} 发送。 返回所发送的字节总数。

如果可用的话，该方法将使用高性能的 @ref{46a,,os.sendfile()}。

@emph{file} 必须是个二进制模式打开的常规文件对象。

@emph{offset} 指明从何处开始读取文件。 如果指定了 @emph{count}，它是要传输的字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使此方法引发了错误，并可以使用 @ref{1f40,,file.tell()} 来获取实际发送的字节总数。

@emph{fallback} 设为 @code{True} 会使得 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件（例如 Windows 或 Unix 上的 SSL 套接字）。

如果系统不支持 @emph{sendfile} 系统调用且 @emph{fallback} 为 @code{False} 则会引发 @ref{26f4,,SendfileNotAvailableError}。


3.7 新版功能.

@end deffn

@node TLS 升级,监控文件描述符,传输文件,事件循环方法集
@anchor{library/asyncio-eventloop tls-upgrade}@anchor{2717}
@subsubsection TLS 升级


@geindex start_tls() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop start_tls}@anchor{463}
@deffn {方法} coroutine loop.start_tls (transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None)

将现有基于传输的连接升级到 TLS。

返回一个新的传输实例，其中 @emph{protocol} 必须在 @emph{await} 之后立即开始使用。 传给 @emph{start_tls} 方法的 @emph{transport} 实例应永远不会被再次使用。

参数：


@itemize *

@item 
@emph{transport} 和 @emph{protocol} 实例的方法与 @ref{46e,,create_server()} 和 @ref{2ec,,create_connection()} 所返回的类似。

@item 
@emph{sslcontext} ：一个已经配置好的 @ref{4f2,,SSLContext} 实例。

@item 
当服务端连接已升级时 (如 @ref{46e,,create_server()} 所创建的对象) @emph{server_side} 会传入 @code{True}。

@item 
@emph{server_hostname} ：设置或者覆盖目标服务器证书中相对应的主机名。

@item 
@emph{ssl_handshake_timeout} 是（用于 TLS 连接的）在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 @code{None} 则使用 (默认的) @code{60.0}。
@end itemize


3.7 新版功能.

@end deffn

@node 监控文件描述符,直接使用 socket 对象,TLS 升级,事件循环方法集
@anchor{library/asyncio-eventloop watching-file-descriptors}@anchor{2718}
@subsubsection 监控文件描述符


@geindex add_reader() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop add_reader}@anchor{269f}
@deffn {方法} loop.add_reader (fd, callback, *args)

开始监视 @emph{fd} 文件描述符以获取读取的可用性，一旦 @emph{fd} 可用于读取，使用指定的参数调用 @emph{callback} 。
@end deffn

@geindex remove_reader() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop remove_reader}@anchor{2719}
@deffn {方法} loop.remove_reader (fd)

停止对文件描述符 @emph{fd} 读取可用性的监视。
@end deffn

@geindex add_writer() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop add_writer}@anchor{271a}
@deffn {方法} loop.add_writer (fd, callback, *args)

开始监视 @emph{fd} 文件描述符的写入可用性，一旦 @emph{fd} 可用于写入，使用指定的参数调用 @emph{callback} 。

使用 @ref{8bf,,functools.partial()} @ref{2708,,传递关键字参数}  给 @emph{callback}.
@end deffn

@geindex remove_writer() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop remove_writer}@anchor{271b}
@deffn {方法} loop.remove_writer (fd)

停止对文件描述符 @emph{fd} 的写入可用性监视。
@end deffn

另请查看 @ref{271c,,平台支持} 一节了解以上方法的某些限制。

@node 直接使用 socket 对象,DNS,监控文件描述符,事件循环方法集
@anchor{library/asyncio-eventloop working-with-socket-objects-directly}@anchor{271d}
@subsubsection 直接使用 socket 对象


通常，使用基于传输的 API 的协议实现，例如 @ref{2ec,,loop.create_connection()} 和 @ref{46e,,loop.create_server()} 比直接使用套接字的实现更快。 但是，在某些应用场景下性能并不非常重要，直接使用 @ref{771,,socket} 对象会更方便。

@geindex sock_recv() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_recv}@anchor{5a1}
@deffn {方法} coroutine loop.sock_recv (sock, nbytes)

从 @emph{sock} 接收至多 @emph{nbytes}。 @ref{774,,socket.recv()} 的异步版本。

返回接收到的数据【bytes对象类型】。

@emph{sock} 必须是个非阻塞socket。


在 3.7 版更改: 虽然这个方法总是被记录为协程方法，但它在 Python 3.7 之前的发行版中会返回一个 @ref{54e,,Future}。 从 Python 3.7 开始它则是一个 @code{async def} 方法。

@end deffn

@geindex sock_recv_into() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_recv_into}@anchor{464}
@deffn {方法} coroutine loop.sock_recv_into (sock, buf)

从 @emph{sock} 接收数据放入 @emph{buf} 缓冲区。 模仿了阻塞型的 @ref{d82,,socket.recv_into()} 方法。

返回写入缓冲区的字节数。

@emph{sock} 必须是个非阻塞socket。


3.7 新版功能.

@end deffn

@geindex sock_sendall() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_sendall}@anchor{5a2}
@deffn {方法} coroutine loop.sock_sendall (sock, data)

将 @emph{data} 发送到 @emph{sock} 套接字。 @ref{778,,socket.sendall()} 的异步版本。

此方法会持续发送数据到套接字直至 @emph{data} 中的所有数据发送完毕或是有错误发生。 当成功时会返回 @code{None}。 当发生错误时，会引发一个异常。 此外，没有办法能确定有多少数据或是否有数据被连接的接收方成功处理。

@emph{sock} 必须是个非阻塞socket。


在 3.7 版更改: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前，该方法返回 @ref{54e,,Future} ，从Python 3.7 开始，这个方法是 @code{async def} 方法。

@end deffn

@geindex sock_connect() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_connect}@anchor{79e}
@deffn {方法} coroutine loop.sock_connect (sock, address)

将 @emph{sock} 连接到位于 @emph{address} 的远程套接字。

@ref{773,,socket.connect()} 的异步版本。

@emph{sock} 必须是个非阻塞socket。


在 3.5.2 版更改: @code{address} 不再需要被解析。 @code{sock_connect} 将尝试检查 @emph{address} 是否已通过调用 @ref{238,,socket.inet_pton()} 被解析。 如果没有，则将使用 @ref{5a4,,loop.getaddrinfo()} 来解析 @emph{address}。



@subsubheading 参见


@ref{2ec,,loop.create_connection()} 和  @ref{474,,asyncio.open_connection()} 。

@end deffn

@geindex sock_accept() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_accept}@anchor{5a3}
@deffn {方法} coroutine loop.sock_accept (sock)

接受一个连接。 模仿了阻塞型的 @ref{772,,socket.accept()} 方法。

此 @emph{scoket} 必须绑定到一个地址上并且监听连接。返回值是一个 @code{(conn, address)} 对，其中 @emph{conn} 是一个 @emph{新*的套接字对象，用于在此连接上收发数据，*address} 是连接的另一端的套接字所绑定的地址。

@emph{sock} 必须是个非阻塞socket。


在 3.7 版更改: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前，该方法返回 @ref{54e,,Future} ，从Python 3.7 开始，这个方法是 @code{async def} 方法。



@subsubheading 参见


@ref{46e,,loop.create_server()} 和 @ref{475,,start_server()}。

@end deffn

@geindex sock_sendfile() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop sock_sendfile}@anchor{469}
@deffn {方法} coroutine loop.sock_sendfile (sock, file, offset=0, count=None, *, fallback=True)

在可能的情况下使用高性能的 @ref{46a,,os.sendfile} 发送文件。 返回所发送的字节总数。

@ref{843,,socket.sendfile()} 的异步版本。

@emph{sock} 必须为非阻塞型的 @ref{d5a,,socket.SOCK_STREAM} @ref{771,,socket}。

@emph{file} 必须是个用二进制方式打开的常规文件对象。

@emph{offset} 指明从何处开始读取文件。 如果指定了 @emph{count}，它是要传输的字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使此方法引发了错误，并可以使用 @ref{1f40,,file.tell()} 来获取实际发送的字节总数。

当 @emph{fallback} 被设为 @code{True} 时，会使用 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件（例如 Windows 或 Unix 上的 SSL 套接字）。

如果系统不支持 @emph{sendfile} 并且 @emph{fallback} 为 @code{False} ，引发 @ref{26f4,,SendfileNotAvailableError} 异常。

@emph{sock} 必须是个非阻塞socket。


3.7 新版功能.

@end deffn

@node DNS,使用管道,直接使用 socket 对象,事件循环方法集
@anchor{library/asyncio-eventloop dns}@anchor{271e}
@subsubsection DNS


@geindex getaddrinfo() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop getaddrinfo}@anchor{5a4}
@deffn {方法} coroutine loop.getaddrinfo (host, port, *, family=0, type=0, proto=0, flags=0)

异步版的 @ref{271f,,socket.getaddrinfo()} 。
@end deffn

@geindex getnameinfo() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop getnameinfo}@anchor{5a5}
@deffn {方法} coroutine loop.getnameinfo (sockaddr, flags=0)

异步版的 @ref{2720,,socket.getnameinfo()} 。
@end deffn


在 3.7 版更改: @emph{getaddrinfo} 和 @emph{getnameinfo} 方法一直被标记返回一个协程，但是Python 3.7之前，实际返回的是 @ref{54e,,asyncio.Future} 对象。从Python 3.7 开始，这两个方法是协程。


@node 使用管道,Unix 信号,DNS,事件循环方法集
@anchor{library/asyncio-eventloop working-with-pipes}@anchor{2721}
@subsubsection 使用管道


@geindex connect_read_pipe() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop connect_read_pipe}@anchor{26c2}
@deffn {方法} coroutine loop.connect_read_pipe (protocol_factory, pipe)

在事件循环中注册 @emph{pipe} 的读取端。

@emph{protocol_factory} 必须为一个返回 @ref{270e,,asyncio 协议} 实现的可调用对象。

@emph{pipe} 是个 @ref{c1d,,类似文件型对象}.

返回一对 @code{(transport, protocol)}，其中 @emph{transport} 支持 @ref{2722,,ReadTransport} 接口而 @emph{protocol} 是由 @emph{protocol_factory} 所实例化的对象。

使用 @ref{26d8,,SelectorEventLoop} 事件循环， @emph{pipe} 被设置为非阻塞模式。
@end deffn

@geindex connect_write_pipe() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop connect_write_pipe}@anchor{26c3}
@deffn {方法} coroutine loop.connect_write_pipe (protocol_factory, pipe)

在事件循环中注册 @emph{pipe} 的写入端。

@emph{protocol_factory} 必须为一个返回 @ref{270e,,asyncio 协议} 实现的可调用对象。

@emph{pipe} 是个 @ref{c1d,,类似文件型对象}.

返回一对 @code{(transport, protocol)}，其中 @emph{transport} 支持 @ref{2723,,WriteTransport} 接口而 @emph{protocol} 是由 @emph{protocol_factory} 所实例化的对象。

使用 @ref{26d8,,SelectorEventLoop} 事件循环， @emph{pipe} 被设置为非阻塞模式。
@end deffn

@cartouche
@quotation 注解 
在 Windows 中 @ref{26d8,,SelectorEventLoop} 不支持上述方法。 对于 Windows 请改用 @ref{2e5,,ProactorEventLoop}。
@end quotation
@end cartouche


@subsubheading 参见


@ref{2652,,loop.subprocess_exec()} 和 @ref{26c0,,loop.subprocess_shell()} 方法。


@node Unix 信号,在线程或者进程池中执行代码。,使用管道,事件循环方法集
@anchor{library/asyncio-eventloop unix-signals}@anchor{2724}
@subsubsection Unix 信号


@geindex add_signal_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop add_signal_handler}@anchor{2653}
@deffn {方法} loop.add_signal_handler (signum, callback, *args)

设置 @emph{callback} 作为 @emph{signum} 信号的处理程序。

此回调将与该事件循环中其他加入队列的回调和可运行协程一起由 @emph{loop} 发起调用。 不同与使用 @ref{b61,,signal.signal()} 注册的信号处理程序，使用此函数注册的回调可以与事件循环进行交互。

如果信号数字非法或者不可捕获，就抛出一个 @ref{16d,,ValueError} 。如果建立处理器的过程中出现问题，会抛出一个 @ref{3e4,,RuntimeError} 。

使用 @ref{8bf,,functools.partial()} @ref{2708,,传递关键字参数}  给 @emph{callback}.

和 @ref{b61,,signal.signal()} 一样，这个函数只能在主线程中调用。
@end deffn

@geindex remove_signal_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop remove_signal_handler}@anchor{2725}
@deffn {方法} loop.remove_signal_handler (sig)

移除 @emph{sig} 信号的处理程序。

如果信号处理程序被移除则返回 @code{True}，否则如果给定信号未设置处理程序则返回 @code{False}。

@ref{14c1,,可用性}: Unix。
@end deffn


@subsubheading 参见


@ref{ea,,signal} 模块。


@node 在线程或者进程池中执行代码。,错误处理API,Unix 信号,事件循环方法集
@anchor{library/asyncio-eventloop executing-code-in-thread-or-process-pools}@anchor{2726}
@subsubsection 在线程或者进程池中执行代码。


@geindex run_in_executor() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop run_in_executor}@anchor{190}
@deffn {方法} awaitable loop.run_in_executor (executor, func, *args)

安排在指定的执行器中调用 @emph{func} 。

The @emph{executor} argument should be an @ref{25a2,,concurrent.futures.Executor}
instance. The default executor is used if @emph{executor} is @code{None}.

示例:

@example
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())
@end example

这个方法返回一个 @ref{54e,,asyncio.Future} 对象。

使用 @ref{8bf,,functools.partial()} @ref{2708,,传递关键字参数}  给 @emph{func} 。


在 3.5.3 版更改: @ref{190,,loop.run_in_executor()} 不会再配置它所创建的线程池执行器的 @code{max_workers}，而是将其留给线程池执行器 (@ref{18c,,ThreadPoolExecutor}) 来设置默认值。

@end deffn

@geindex set_default_executor() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop set_default_executor}@anchor{3a9}
@deffn {方法} loop.set_default_executor (executor)

将 @emph{executor} 设为 @ref{190,,run_in_executor()} 所使用的默认执行器。 @emph{executor} 应当是 @ref{18c,,ThreadPoolExecutor} 的实例。


3.8 版后已移除: 使用不是Using an executor that is not an instance of @ref{18c,,ThreadPoolExecutor} 实例的执行器的做法已被弃用并将在 Python 3.9 中引起错误。


@emph{executor} 必须是个 @ref{18c,,concurrent.futures.ThreadPoolExecutor} 的实例。
@end deffn

@node 错误处理API,开启调试模式,在线程或者进程池中执行代码。,事件循环方法集
@anchor{library/asyncio-eventloop error-handling-api}@anchor{2727}
@subsubsection 错误处理API


允许自定义事件循环中如何去处理异常。

@geindex set_exception_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop set_exception_handler}@anchor{2728}
@deffn {方法} loop.set_exception_handler (handler)

将 @emph{handler} 设置为新的事件循环异常处理器。

如果 @emph{handler} 为 @code{None}，将设置默认的异常处理程序。 在其他情况下，@emph{handler} 必须是一个可调用对象且签名匹配 @code{(loop, context)}，其中 @code{loop} 是对活动事件循环的引用，而 @code{context} 是一个包含异常详情的 @code{dict} (请查看 @ref{2729,,call_exception_handler()} 文档来获取关于上下文的更多信息)。
@end deffn

@geindex get_exception_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop get_exception_handler}@anchor{61f}
@deffn {方法} loop.get_exception_handler ()

返回当前的异常处理器，如果没有设置异常处理器，则返回 @code{None} 。


3.5.2 新版功能.

@end deffn

@geindex default_exception_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop default_exception_handler}@anchor{272a}
@deffn {方法} loop.default_exception_handler (context)

默认的异常处理器。

此方法会在发生异常且未设置异常处理程序时被调用。 此方法也可以由想要具有不同于默认处理程序的行为的自定义异常处理程序来调用。

@emph{context} 参数和 @ref{2729,,call_exception_handler()} 中的同名参数完全相同。
@end deffn

@geindex call_exception_handler() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop call_exception_handler}@anchor{2729}
@deffn {方法} loop.call_exception_handler (context)

调用当前事件循环异常处理器。

@emph{context} 是个包含下列键的 @code{dict} 对象(未来版本的Python可能会引入新键)：


@itemize *

@item 
'message': 错误消息；

@item 
'exception' （可选）: 异常对象；

@item 
'future' （可选）:  @ref{54e,,asyncio.Future} 实例。

@item 
'task' (可选): @ref{2e7,,asyncio.Task} 实例；

@item 
'handle' （可选）: @ref{121f,,asyncio.Handle} 实例；

@item 
'protocol' （可选）: @ref{270e,,Protocol} 实例；

@item 
'transport' （可选）: @ref{270f,,Transport} 实例；

@item 
'socket' (可选): @ref{771,,socket.socket} 实例；

@item 

@table @asis

@item 'asyncgen' (可选): 异步生成器，它导致了

这个异常
@end table
@end itemize

@cartouche
@quotation 注解 
此方法不应在子类化的事件循环中被重载。 对于自定义的异常处理，请使用 @ref{2728,,set_exception_handler()} 方法。
@end quotation
@end cartouche
@end deffn

@node 开启调试模式,运行子进程,错误处理API,事件循环方法集
@anchor{library/asyncio-eventloop enabling-debug-mode}@anchor{272b}
@subsubsection 开启调试模式


@geindex get_debug() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop get_debug}@anchor{797}
@deffn {方法} loop.get_debug ()

获取事件循环调试模式状态（@ref{2c4,,bool}）。

如果环境变量 
@geindex PYTHONASYNCIODEBUG
@geindex 环境变量; PYTHONASYNCIODEBUG
@ref{14bd,,PYTHONASYNCIODEBUG} 是一个非空字符串，就返回 @code{True} ，否则就返回 @code{False} 。
@end deffn

@geindex set_debug() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop set_debug}@anchor{796}
@deffn {方法} loop.set_debug (enabled: bool)

设置事件循环的调试模式。


在 3.7 版更改: 现在也可以通过新的 @ref{160,,Python 开发模式} 来启用调试模式。

@end deffn


@subsubheading 参见


@ref{14be,,debug mode of asyncio}.


@node 运行子进程,,开启调试模式,事件循环方法集
@anchor{library/asyncio-eventloop running-subprocesses}@anchor{272c}
@subsubsection 运行子进程


本小节所描述的方法都是低层级的。 在常规 async/await 代码中请考虑改用高层级的 @ref{3bd,,asyncio.create_subprocess_shell()} 和 @ref{3bc,,asyncio.create_subprocess_exec()} 便捷函数。

@cartouche
@quotation 注解 
在 Windows 中，默认的事件循环 @ref{2e5,,ProactorEventLoop} 支持子进程，而 @ref{26d8,,SelectorEventLoop} 不支持。参见 @ref{26c1,,Windows 中的子进程支持} 。
@end quotation
@end cartouche

@geindex subprocess_exec() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop subprocess_exec}@anchor{2652}
@deffn {方法} coroutine loop.subprocess_exec (protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

用 @emph{args} 指定的一个或者多个字符串型参数创建一个子进程。

@emph{args} 必须是个由下列形式的字符串组成的列表：


@itemize *

@item 
@ref{206,,str};

@item 
或者由 @ref{2073,,文件系统编码格式} 编码的 @ref{172,,bytes}。
@end itemize

第一个字符串指定可执行程序，其余的字符串指定其参数。 所有字符串参数共同组成了程序的 @code{argv}。

此方法类似于调用标准库 @ref{3e3,,subprocess.Popen} 类，设置 @code{shell=False} 并将字符串列表作为第一个参数传入；但是，@ref{3e3,,Popen} 只接受一个单独的字符串列表参数，而 @emph{subprocess_exec} 接受多个字符串参数。

@emph{protocol_factory} 必须为一个返回 @ref{272d,,asyncio.SubprocessProtocol} 类的子类的可调用对象。

其他参数：


@itemize *

@item 
@emph{stdin} 可以是以下对象之一:


@itemize *

@item 
一个文件类对象，表示要使用 @ref{26c3,,connect_write_pipe()} 连接到子进程的标准输入流的管道

@item 
@ref{4fc,,subprocess.PIPE} 常量（默认），将创建并连接一个新的管道。

@item 
@code{None} 值，这将使得子进程继承来自此进程的文件描述符

@item 
@ref{b81,,subprocess.DEVNULL} 常量，这表示将使用特殊的 @ref{119b,,os.devnull} 文件
@end itemize

@item 
@emph{stdout} 可以是以下对象之一:


@itemize *

@item 
一个文件类对象，表示要使用 @ref{26c3,,connect_write_pipe()} 连接到子进程的标准输出流的管道

@item 
@ref{4fc,,subprocess.PIPE} 常量（默认），将创建并连接一个新的管道。

@item 
@code{None} 值，这将使得子进程继承来自此进程的文件描述符

@item 
@ref{b81,,subprocess.DEVNULL} 常量，这表示将使用特殊的 @ref{119b,,os.devnull} 文件
@end itemize

@item 
@emph{stderr} 可以是以下对象之一:


@itemize *

@item 
一个文件类对象，表示要使用 @ref{26c3,,connect_write_pipe()} 连接到子进程的标准错误流的管道

@item 
@ref{4fc,,subprocess.PIPE} 常量（默认），将创建并连接一个新的管道。

@item 
@code{None} 值，这将使得子进程继承来自此进程的文件描述符

@item 
@ref{b81,,subprocess.DEVNULL} 常量，这表示将使用特殊的 @ref{119b,,os.devnull} 文件

@item 
@ref{25c6,,subprocess.STDOUT} 常量，将把标准错误流连接到进程的标准输出流
@end itemize

@item 
所有其他关键字参数会被不加解释地传给 @ref{3e3,,subprocess.Popen}，除了 @emph{bufsize}, @emph{universal_newlines}, @emph{shell}, @emph{text}, @emph{encoding} 和 @emph{errors}，它们都不应当被指定。

@code{asyncio} 子进程 API 不支持将流解码为文本。 可以使用 @ref{171,,bytes.decode()} 来将从流返回的字节串转换为文本。
@end itemize

其他参数的文档，请参阅 @ref{3e3,,subprocess.Popen} 类的构造函数。

返回一对 @code{(transport, protocol)}，其中 @emph{transport} 来自 @ref{272e,,asyncio.SubprocessTransport} 基类而 @emph{protocol} 是由 @emph{protocol_factory} 所实例化的对象。
@end deffn

@geindex subprocess_shell() (asyncio.loop 方法)
@anchor{library/asyncio-eventloop asyncio loop subprocess_shell}@anchor{26c0}
@deffn {方法} coroutine loop.subprocess_shell (protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

基于 @emph{cmd} 创建一个子进程，该参数可以是一个 @ref{206,,str} 或者按 @ref{2073,,文件系统编码格式} 编码得到的 @ref{172,,bytes} ，使用平台的 "shell" 语法。

这类似与用 @code{shell=True} 调用标准库的 @ref{3e3,,subprocess.Popen} 类。

@emph{protocol_factory} 必须为一个返回 @ref{272d,,SubprocessProtocol} 类的子类的可调用对象。

请参阅 @ref{2652,,subprocess_exec()} 了解有关其余参数的详情。

返回一对 @code{(transport, protocol)}，其中 @emph{transport} 来自 @ref{272e,,SubprocessTransport} 基类而 @emph{protocol} 是由 @emph{protocol_factory} 所实例化的对象。
@end deffn

@cartouche
@quotation 注解 
应用程序要负责确保正确地转义所有空白字符和特殊字符以防止 shell 注入@footnote{https://en.wikipedia.org/wiki/Shell_injection#Shell_injection} 漏洞。 @ref{b57,,shlex.quote()} 函数可以被用来正确地转义字符串中可能被用来构造 shell 命令的空白字符和特殊字符。
@end quotation
@end cartouche

@node 回调处理,Server 对象,事件循环方法集,事件循环
@anchor{library/asyncio-eventloop callback-handles}@anchor{26fd}
@subsubsection 回调处理


@geindex Handle (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio Handle}@anchor{121f}
@deffn {类} asyncio.Handle

由 @ref{45e,,loop.call_soon()}, @ref{45f,,loop.call_soon_threadsafe()} 所返回的回调包装器对象。

@geindex cancel() (asyncio.Handle 方法)
@anchor{library/asyncio-eventloop asyncio Handle cancel}@anchor{272f}
@deffn {方法} cancel ()

取消回调。 如果此回调已被取消或已被执行，此方法将没有任何效果。
@end deffn

@geindex cancelled() (asyncio.Handle 方法)
@anchor{library/asyncio-eventloop asyncio Handle cancelled}@anchor{477}
@deffn {方法} cancelled ()

如果此回调已被取消则返回 @code{True}。


3.7 新版功能.

@end deffn
@end deffn

@geindex TimerHandle (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio TimerHandle}@anchor{26fe}
@deffn {类} asyncio.TimerHandle

由 @ref{460,,loop.call_later()} 和 @ref{461,,loop.call_at()} 所返回的回调包装器对象。

这个类是 @ref{121f,,Handle} 的子类。

@geindex when() (asyncio.TimerHandle 方法)
@anchor{library/asyncio-eventloop asyncio TimerHandle when}@anchor{473}
@deffn {方法} when ()

返回加入计划任务的回调时间，以 @ref{1fe,,float} 值表示的秒数。

时间值是一个绝对时间戳，使用与 @ref{270b,,loop.time()} 相同的时间引用。


3.7 新版功能.

@end deffn
@end deffn

@node Server 对象,事件循环实现,回调处理,事件循环
@anchor{library/asyncio-eventloop server-objects}@anchor{26ff}
@subsubsection Server 对象


Server 对象可使用 @ref{46e,,loop.create_server()}, @ref{46f,,loop.create_unix_server()}, @ref{475,,start_server()} 和 @ref{2685,,start_unix_server()} 等函数来创建。

请不要直接实例化该类。

@geindex Server (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio Server}@anchor{46d}
@deffn {类} asyncio.Server

@emph{Server} 对象是异步上下文管理器。当用于 @code{async with} 语句时，异步上下文管理器可以确保 Server 对象被关闭，并且在 @code{async with} 语句完成后，不接受新的连接。

@example
srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
@end example


在 3.7 版更改: Python3.7 开始，Server 对象是一个异步上下文管理器。


@geindex close() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server close}@anchor{2730}
@deffn {方法} close ()

停止服务：关闭监听的套接字并且设置 @ref{5a6,,sockets} 属性为 @code{None} 。

用于表示已经连进来的客户端连接会保持打开的状态。

服务器是被异步关闭的，使用 @ref{2731,,wait_closed()} 协程来等待服务器关闭。
@end deffn

@geindex get_loop() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server get_loop}@anchor{46c}
@deffn {方法} get_loop ()

返回与服务器对象相关联的事件循环。


3.7 新版功能.

@end deffn

@geindex start_serving() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server start_serving}@anchor{470}
@deffn {方法} coroutine start_serving ()

开始接受连接。

这个方法是幂等的【相同参数重复执行，能获得相同的结果】，所以此方法能在服务已经运行的时候调用。

传给 @ref{46e,,loop.create_server()} 和 @ref{475,,asyncio.start_server()} 的 @emph{start_serving} 仅限关键字形参允许创建不接受初始连接的 Server 对象。 在此情况下可以使用 @code{Server.start_serving()} 或 @ref{471,,Server.serve_forever()} 让 Server 对象开始接受连接。


3.7 新版功能.

@end deffn

@geindex serve_forever() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server serve_forever}@anchor{471}
@deffn {方法} coroutine serve_forever ()

开始接受连接，直到协程被取消。 @code{serve_forever} 任务的取消将导致服务器被关闭。

如果服务器已经在接受连接了，这个方法可以被调用。每个 @emph{Server} 对象，仅能有一个 @code{serve_forever} 任务。

示例:

@example
async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))
@end example


3.7 新版功能.

@end deffn

@geindex is_serving() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server is_serving}@anchor{472}
@deffn {方法} is_serving ()

如果服务器正在接受新连接的状态，返回 @code{True} 。


3.7 新版功能.

@end deffn

@geindex wait_closed() (asyncio.Server 方法)
@anchor{library/asyncio-eventloop asyncio Server wait_closed}@anchor{2731}
@deffn {方法} coroutine wait_closed ()

等待 @ref{2730,,close()} 方法执行完毕。
@end deffn

@geindex sockets (asyncio.Server 属性)
@anchor{library/asyncio-eventloop asyncio Server sockets}@anchor{5a6}
@deffn {属性} sockets

服务器监听的 @ref{771,,socket.socket} 对象列表。


在 3.7 版更改: 在 Python 3.7 之前 @code{Server.sockets} 会直接返回内部的服务器套接字列表。 在 3.7 版则会返回该列表的副本。

@end deffn
@end deffn

@node 事件循环实现,示例<21>,Server 对象,事件循环
@anchor{library/asyncio-eventloop asyncio-event-loops}@anchor{2732}@anchor{library/asyncio-eventloop event-loop-implementations}@anchor{2700}
@subsubsection 事件循环实现


asyncio 带有两种不同的事件循环实现: @ref{26d8,,SelectorEventLoop} 和 @ref{2e5,,ProactorEventLoop}。

默认情况下 asyncio 被配置为在 Unix 上使用 @ref{26d8,,SelectorEventLoop} 而在 Windows 上使用 @ref{2e5,,ProactorEventLoop}。

@geindex SelectorEventLoop (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio SelectorEventLoop}@anchor{26d8}
@deffn {类} asyncio.SelectorEventLoop

基于 @ref{e6,,selectors} 模块的事件循环。

使用给定平台中最高效的可用 @emph{selector}。 也可以手动配置要使用的特定 selector:

@example
import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
@end example

@ref{14c1,,可用性}: Unix, Windows。
@end deffn

@geindex ProactorEventLoop (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio ProactorEventLoop}@anchor{2e5}
@deffn {类} asyncio.ProactorEventLoop

用 "I/O Completion Ports" (IOCP) 构建的专为Windows 的事件循环。

@ref{14c1,,可用性}: Windows。


@subsubheading 参见


有关 I/O 完成端口的 MSDN 文档@footnote{https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports}。

@end deffn

@geindex AbstractEventLoop (asyncio 中的类)
@anchor{library/asyncio-eventloop asyncio AbstractEventLoop}@anchor{234}
@deffn {类} asyncio.AbstractEventLoop

asyncio 兼容事件循环的抽象基类。

@ref{741,,事件循环方法} 一节列出了 @code{AbstractEventLoop} 的替代实现应当定义的所有方法。
@end deffn

@node 示例<21>,,事件循环实现,事件循环
@anchor{library/asyncio-eventloop examples}@anchor{2701}
@subsubsection 示例


请注意本节中的所有示例都 @strong{有意地} 演示了如何使用低层级的事件循环 API，例如 @ref{2703,,loop.run_forever()} 和 @ref{45e,,loop.call_soon()}。 现代的 asyncio 应用很少需要以这样的方式编写；请考虑使用高层级的函数例如 @ref{18d,,asyncio.run()}。

@menu
* call_soon() 的 Hello World 示例。: call_soon 的 Hello World 示例。. 
* 使用 call_later() 来展示当前的日期: 使用 call_later 来展示当前的日期. 
* 监控一个文件描述符的读事件:: 
* 为SIGINT和SIGTERM设置信号处理器:: 

@end menu

@node call_soon 的 Hello World 示例。,使用 call_later 来展示当前的日期,,示例<21>
@anchor{library/asyncio-eventloop asyncio-example-lowlevel-helloworld}@anchor{2733}@anchor{library/asyncio-eventloop hello-world-with-call-soon}@anchor{2734}
@subsubsection call_soon() 的 Hello World 示例。


一个使用 @ref{45e,,loop.call_soon()} 方法来安排回调的示例。 回调会显示 @code{"Hello World"} 然后停止事件循环:

@example
import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.get_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
@end example


@subsubheading 参见


一个类似的 @ref{264d,,Hello World} 示例，使用协程和 @ref{18d,,run()} 函数创建。


@node 使用 call_later 来展示当前的日期,监控一个文件描述符的读事件,call_soon 的 Hello World 示例。,示例<21>
@anchor{library/asyncio-eventloop asyncio-example-call-later}@anchor{2735}@anchor{library/asyncio-eventloop display-the-current-date-with-call-later}@anchor{2736}
@subsubsection 使用 call_later() 来展示当前的日期


一个每秒刷新显示当前日期的示例。 回调使用 @ref{460,,loop.call_later()} 方法在 5 秒后将自身重新加入计划日程，然后停止事件循环:

@example
import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.get_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
@end example


@subsubheading 参见


一个类似的 @ref{265f,,current date} 示例，使用协程和 @ref{18d,,run()} 函数创建。


@node 监控一个文件描述符的读事件,为SIGINT和SIGTERM设置信号处理器,使用 call_later 来展示当前的日期,示例<21>
@anchor{library/asyncio-eventloop asyncio-example-watch-fd}@anchor{26a0}@anchor{library/asyncio-eventloop watch-a-file-descriptor-for-read-events}@anchor{2737}
@subsubsection 监控一个文件描述符的读事件


使用 @ref{269f,,loop.add_reader()} 方法，等到文件描述符收到一些数据，然后关闭事件循环：

@example
import asyncio
from socket import socketpair

# Create a pair of connected file descriptors
rsock, wsock = socketpair()

loop = asyncio.get_event_loop()

def reader():
    data = rsock.recv(100)
    print("Received:", data.decode())

    # We are done: unregister the file descriptor
    loop.remove_reader(rsock)

    # Stop the event loop
    loop.stop()

# Register the file descriptor for read event
loop.add_reader(rsock, reader)

# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())

try:
    # Run the event loop
    loop.run_forever()
finally:
    # We are done. Close sockets and the event loop.
    rsock.close()
    wsock.close()
    loop.close()
@end example


@subsubheading 参见



@itemize *

@item 
一个类似的 @ref{269e,,示例}，使用传输、协议和 @ref{2ec,,loop.create_connection()} 方法创建。

@item 
另一个类似的 @ref{269c,,示例}，使用了高层级的 @ref{474,,asyncio.open_connection()} 函数和流。
@end itemize


@node 为SIGINT和SIGTERM设置信号处理器,,监控一个文件描述符的读事件,示例<21>
@anchor{library/asyncio-eventloop asyncio-example-unix-signals}@anchor{2738}@anchor{library/asyncio-eventloop set-signal-handlers-for-sigint-and-sigterm}@anchor{2739}
@subsubsection 为SIGINT和SIGTERM设置信号处理器


（这个 @code{signals} 示例只适用于 Unix。）

使用 @ref{2653,,loop.add_signal_handler()} 方法为信号 @code{SIGINT} 和 @code{SIGTERM} 注册处理程序:

@example
import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in @{'SIGINT', 'SIGTERM'@}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid @{os.getpid()@}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())
@end example

@node Futures,传输和协议,事件循环,asyncio --- 异步 I/O
@anchor{library/asyncio-future doc}@anchor{273a}@anchor{library/asyncio-future asyncio-futures}@anchor{2655}@anchor{library/asyncio-future futures}@anchor{273b}
@subsubsection Futures


@strong{源代码:} Lib/asyncio/futures.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/futures.py}, Lib/asyncio/base_futures.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_futures.py}


__________________________________________________________________


@emph{Future} 对象用来链接  @strong{底层回调式代码} 和高层异步/等待式代码。

@menu
* Future 函数:: 
* Future 对象: Future 对象<2>. 

@end menu

@node Future 函数,Future 对象<2>,,Futures
@anchor{library/asyncio-future future-functions}@anchor{273c}
@subsubsection Future 函数


@geindex isfuture() (在 asyncio 模块中)
@anchor{library/asyncio-future asyncio isfuture}@anchor{273d}
@deffn {函数} asyncio.isfuture (obj)

如果 @emph{obj} 为下面任意对象，返回 @code{True}：


@itemize *

@item 
一个 @ref{54e,,asyncio.Future} 类的实例，

@item 
一个 @ref{2e7,,asyncio.Task} 类的实例，

@item 
带有  @code{_asyncio_future_blocking} 属性的类似 Future 的对象。
@end itemize


3.5 新版功能.

@end deffn

@geindex ensure_future() (在 asyncio 模块中)
@anchor{library/asyncio-future asyncio ensure_future}@anchor{619}
@deffn {函数} asyncio.ensure_future (obj, *, loop=None)

返回：


@itemize *

@item 
@emph{obj} 参数会是保持原样，如果 @emph{obj} 是 @ref{54e,,Future}、 @ref{2e7,,Task} 或 类似 Future 的对象(  @ref{273d,,isfuture()}  用于测试。)

@item 
封装了 @emph{obj} 的 @ref{2e7,,Task} 对象，如果 @emph{obj} 是一个协程 (使用 @ref{267d,,iscoroutine()} 进行检测)；在此情况下该协程将通过 @code{ensure_future()} 加入执行计划。

@item 
等待 @emph{obj} 的 @ref{2e7,,Task} 对象，如果 @emph{obj} 是一个可等待对象( @ref{7f4,,inspect.isawaitable()} 用于测试)
@end itemize

如果 @emph{obj} 不是上述对象会引发一个 @ref{1ff,,TypeError} 异常。

@cartouche
@quotation 重要 
查看 @ref{2e8,,create_task()} 函数，它是创建新任务的首选途径。

保存一个指向此函数的结果的引用，以避免任务在执行期间消失。
@end quotation
@end cartouche


在 3.5.1 版更改: 这个函数接受任意 @ref{61b,,awaitable} 对象。

@end deffn

@geindex wrap_future() (在 asyncio 模块中)
@anchor{library/asyncio-future asyncio wrap_future}@anchor{273e}
@deffn {函数} asyncio.wrap_future (future, *, loop=None)

将一个 @ref{c09,,concurrent.futures.Future} 对象封装到 @ref{54e,,asyncio.Future} 对象中。
@end deffn

@node Future 对象<2>,,Future 函数,Futures
@anchor{library/asyncio-future future-object}@anchor{273f}
@subsubsection Future 对象


@geindex Future (asyncio 中的类)
@anchor{library/asyncio-future asyncio Future}@anchor{54e}
@deffn {类} asyncio.Future (*, loop=None)

一个 Future 代表一个异步运算的最终结果。线程不安全。

Future 是一个 @ref{61b,,awaitable} 对象。协程可以等待 Future 对象直到它们有结果或异常集合或被取消。

通常 Future 用于支持底层回调式代码(例如在协议实现中使用asyncio @ref{2654,,transports}) 与高层异步/等待式代码交互。

经验告诉我们永远不要面向用户的接口暴露 Future 对象，同时建议使用 @ref{61e,,loop.create_future()} 来创建 Future 对象。这种方法可以让 Future 对象使用其它的事件循环实现，它可以注入自己的优化实现。


在 3.7 版更改: 加入对 @ref{24,,contextvars} 模块的支持。


@geindex result() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future result}@anchor{2740}
@deffn {方法} result ()

返回 Future 的结果。

如果 Future 状态为 @emph{完成} ，并由 @ref{266f,,set_result()} 方法设置一个结果，则返回这个结果。

如果 Future 状态为 @emph{完成} ，并由  @ref{2670,,set_exception()} 方法设置一个异常，那么这个方法会引发异常。

如果 Future 已 @emph{取消}，方法会引发一个 @ref{2e1,,CancelledError} 异常。

如果 Future 的结果还不可用，此方法会引发一个 @ref{2675,,InvalidStateError} 异常。
@end deffn

@geindex set_result() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future set_result}@anchor{266f}
@deffn {方法} set_result (result)

将 Future 标记为 @emph{完成} 并设置结果。

如果 Future 已经 @emph{完成}  则抛出一个 @ref{2675,,InvalidStateError} 错误。
@end deffn

@geindex set_exception() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future set_exception}@anchor{2670}
@deffn {方法} set_exception (exception)

将 Future 标记为 @emph{完成} 并设置一个异常。

如果 Future 已经 @emph{完成}  则抛出一个 @ref{2675,,InvalidStateError} 错误。
@end deffn

@geindex done() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future done}@anchor{2741}
@deffn {方法} done ()

如果 Future 为已 @emph{完成} 则返回 @code{True} 。

如果 Future 为 @emph{取消} 或调用 @ref{266f,,set_result()} 设置了结果或调用 @ref{2670,,set_exception()} 设置了异常，那么它就是 @emph{完成} 。
@end deffn

@geindex cancelled() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future cancelled}@anchor{2742}
@deffn {方法} cancelled ()

如果 Future 已 @emph{取消} 则返回 @code{True}

这个方法通常在设置结果或异常前用来检查 Future 是否已 @emph{取消} 。

@example
if not fut.cancelled():
    fut.set_result(42)
@end example
@end deffn

@geindex add_done_callback() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future add_done_callback}@anchor{462}
@deffn {方法} add_done_callback (callback, *, context=None)

添加一个在 Future @emph{完成} 时运行的回调函数。

调用 @emph{callback} 时，Future 对象是它的唯一参数。

如果调用这个方法时 Future 已经 @emph{完成}，回调函数会被 @ref{45e,,loop.call_soon()} 调度。

可选键值类的参数 @emph{context} 允许 @emph{callback} 运行在一个指定的自定义 @ref{2625,,contextvars.Context} 对象中。如果没有提供 @emph{context} ，则使用当前上下文。

可以用 @ref{8bf,,functools.partial()} 给回调函数传递参数，例如:

@example
# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))
@end example


在 3.7 版更改: 加入键值类形参  @emph{context}。请参阅 
@geindex Python 提高建议; PEP 567
PEP 567@footnote{https://www.python.org/dev/peps/pep-0567} 查看更多细节。

@end deffn

@geindex remove_done_callback() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future remove_done_callback}@anchor{2679}
@deffn {方法} remove_done_callback (callback)

从回调列表中移除 @emph{callback} 。

返回被移除的回调函数的数量，通常为1，除非一个回调函数被添加多次。
@end deffn

@geindex cancel() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future cancel}@anchor{2671}
@deffn {方法} cancel (msg=None)

取消 Future 并调度回调函数。

如果 Future 已经 @emph{完成} 或 @emph{取消} ，返回 @code{False} 。否则将 Future 状态改为 @emph{取消} 并在调度回调函数后返回 @code{True} 。


在 3.9 版更改: 增加了 @code{msg} 形参。

@end deffn

@geindex exception() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future exception}@anchor{2743}
@deffn {方法} exception ()

返回 Future 已设置的异常。

只有 Future 在 @emph{完成} 时才返回异常（或者 @code{None} ，如果没有设置异常）。

如果 Future 已 @emph{取消}，方法会引发一个 @ref{2e1,,CancelledError} 异常。

如果 Future 还没 @emph{完成} ，这个方法会引发一个 @ref{2675,,InvalidStateError} 异常。
@end deffn

@geindex get_loop() (asyncio.Future 方法)
@anchor{library/asyncio-future asyncio Future get_loop}@anchor{46b}
@deffn {方法} get_loop ()

返回 Future 对象已绑定的事件循环。


3.7 新版功能.

@end deffn
@end deffn
@anchor{library/asyncio-future asyncio-example-future}@anchor{2744}
这个例子创建一个 Future 对象，创建和调度一个异步任务去设置 Future 结果，然后等待其结果:

@example
async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())
@end example

@cartouche
@quotation 重要 
该 Future 对象是为了模仿 @ref{c09,,concurrent.futures.Future} 类。主要差异包含：


@itemize -

@item 
与 asyncio 的 Future 不同，@ref{c09,,concurrent.futures.Future}  实例不是可等待对象。

@item 
@ref{2740,,asyncio.Future.result()} 和 @ref{2743,,asyncio.Future.exception()} 不接受 @emph{timeout} 参数。

@item 
Future 没有 @emph{完成} 时 @ref{2740,,asyncio.Future.result()} 和 @ref{2743,,asyncio.Future.exception()} 抛出一个 @ref{2675,,InvalidStateError} 异常。

@item 
使用 @ref{462,,asyncio.Future.add_done_callback()} 注册的回调函数不会立即调用，而是被 @ref{45e,,loop.call_soon()} 调度。

@item 
asyncio Future 不能兼容  @ref{f9c,,concurrent.futures.wait()} 和 @ref{126b,,concurrent.futures.as_completed()} 函数。

@item 
@ref{2671,,asyncio.Future.cancel()} 接受一个可选的 @code{msg} 参数，但 @code{concurrent.futures.cancel()} 无此参数。
@end itemize
@end quotation
@end cartouche

@node 传输和协议,策略,Futures,asyncio --- 异步 I/O
@anchor{library/asyncio-protocol doc}@anchor{2745}@anchor{library/asyncio-protocol asyncio-transports-protocols}@anchor{2654}@anchor{library/asyncio-protocol transports-and-protocols}@anchor{2746}
@subsubsection 传输和协议


@subsubheading 前言


传输和协议会被像 @ref{2ec,,loop.create_connection()} 这类 @strong{底层} 事件循环接口使用。它们使用基于回调的编程风格支持网络或IPC协议（如HTTP）的高性能实现。

基本上，传输和协议应只在库和框架上使用，而不应该在高层的异步应用中使用它们。

本文档包含  @ref{2747,,Transports} 和 @ref{2748,,Protocols} 。

@subsubheading 概述


在最顶层，传输只关心 @strong{怎样} 传送字节内容，而协议决定传送 @strong{哪些} 字节内容(还要在一定程度上考虑何时)。

也可以这样说：从传输的角度来看，传输是套接字(或类似的I/O终端)的抽象，而协议是应用程序的抽象。

换另一种说法，传输和协议一起定义网络I/0和进程间I/O的抽象接口。

传输对象和协议对象总是一对一关系：协议调用传输方法来发送数据，而传输在接收到数据时调用协议方法传递数据。

大部分面向连接的事件循环方法(如 @ref{2ec,,loop.create_connection()} ) 通常接受  @emph{protocol_factory} 参数为接收到的链接创建 @emph{协议} 对象，并用 @emph{传输} 对象来表示。这些方法一般会返回 @code{(transport, protocol)} 元组。

@subsubheading 内容


本文档包含下列小节:


@itemize *

@item 
@ref{2747,,传输} 部分记载异步IO @ref{2749,,BaseTransport} 、 @ref{2722,,ReadTransport} 、 @ref{2723,,WriteTransport} 、 @ref{274a,,Transport} 、 @ref{f8d,,DatagramTransport} 和 @ref{272e,,SubprocessTransport} 等类。

@item 
The @ref{2748,,Protocols} section documents asyncio @ref{274b,,BaseProtocol},
@ref{274c,,Protocol}, @ref{3f3,,BufferedProtocol},
@ref{274d,,DatagramProtocol}, and @ref{272d,,SubprocessProtocol} classes.

@item 
@ref{274e,,例子} 部分展示怎样使用传输、协议和底层事件循环接口。
@end itemize

@menu
* 传输:: 
* 协议:: 
* 示例: 示例<22>. 

@end menu

@node 传输,协议,,传输和协议
@anchor{library/asyncio-protocol asyncio-transport}@anchor{270f}@anchor{library/asyncio-protocol transports}@anchor{2747}
@subsubsection 传输


@strong{源码:} Lib/asyncio/transports.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/transports.py}


__________________________________________________________________


传输属于 @ref{9,,asyncio} 模块中的类，用来抽象各种通信通道。

传输对象总是由 @ref{741,,异步IO事件循环} 实例化。

异步IO实现TCP、UDP、SSL和子进程管道的传输。传输上可用的方法由传输的类型决定。

传输类属于 @ref{266b,,线程不安全} 。

@menu
* 传输层级:: 
* 基础传输:: 
* 只读传输:: 
* 只写传输:: 
* 数据报传输:: 
* 子进程传输:: 

@end menu

@node 传输层级,基础传输,,传输
@anchor{library/asyncio-protocol transports-hierarchy}@anchor{274f}
@subsubsection 传输层级


@geindex BaseTransport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio BaseTransport}@anchor{2749}
@deffn {类} asyncio.BaseTransport

所有传输的基类。包含所有异步IO传输共用的方法。
@end deffn

@geindex WriteTransport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio WriteTransport}@anchor{2723}
@deffn {类} asyncio.WriteTransport (BaseTransport)

只写链接的基础传输。

@emph{WriteTransport} 类的实例由 @ref{26c3,,loop.connect_write_pipe()} 事件循环方法返回，也被子进程相关的方法如 @ref{2652,,loop.subprocess_exec()} 使用。
@end deffn

@geindex ReadTransport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio ReadTransport}@anchor{2722}
@deffn {类} asyncio.ReadTransport (BaseTransport)

只读链接的基础传输。

@emph{ReadTransport} 类的实例由 @ref{26c2,,loop.connect_read_pipe()} 事件循环方法返回，也被子进程相关的方法如 @ref{2652,,loop.subprocess_exec()} 使用。
@end deffn

@geindex Transport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio Transport}@anchor{274a}
@deffn {类} asyncio.Transport (WriteTransport, ReadTransport)

接口代表一个双向传输，如TCP链接。

用户不用直接实例化传输；调用一个功能函数，给它传递协议工厂和其它需要的信息就可以创建传输和协议。

@emph{传输} 类实例由如  @ref{2ec,,loop.create_connection()} 、 @ref{2684,,loop.create_unix_connection()} 、  @ref{46e,,loop.create_server()} 、  @ref{2716,,loop.sendfile()} 等这类事件循环方法使用或返回。
@end deffn

@geindex DatagramTransport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio DatagramTransport}@anchor{f8d}
@deffn {类} asyncio.DatagramTransport (BaseTransport)

数据报(UDP)传输链接。

@emph{DatagramTransport} 类实例由事件循环方法 @ref{189,,loop.create_datagram_endpoint()} 返回。
@end deffn

@geindex SubprocessTransport (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio SubprocessTransport}@anchor{272e}
@deffn {类} asyncio.SubprocessTransport (BaseTransport)

表示父进程和子进程之间连接的抽象。

@emph{SubprocessTransport} 类的实例由事件循环方法 @ref{26c0,,loop.subprocess_shell()}  和  @ref{2652,,loop.subprocess_exec()} 返回。
@end deffn

@node 基础传输,只读传输,传输层级,传输
@anchor{library/asyncio-protocol base-transport}@anchor{2750}
@subsubsection 基础传输


@geindex close() (asyncio.BaseTransport 方法)
@anchor{library/asyncio-protocol asyncio BaseTransport close}@anchor{2751}
@deffn {方法} BaseTransport.close ()

关闭传输。

如果传输具有发送数据缓冲区，将会异步发送已缓存的数据。在所有已缓存的数据都已处理后，就会将 @ref{204,,None} 作为协议 @ref{2752,,protocol.connection_lost()} 方法的参数并进行调用。在这之后，传输不再接收任何数据。
@end deffn

@geindex is_closing() (asyncio.BaseTransport 方法)
@anchor{library/asyncio-protocol asyncio BaseTransport is_closing}@anchor{61d}
@deffn {方法} BaseTransport.is_closing ()

返回 @code{True} ，如果传输正在关闭或已经关闭。。
@end deffn

@geindex get_extra_info() (asyncio.BaseTransport 方法)
@anchor{library/asyncio-protocol asyncio BaseTransport get_extra_info}@anchor{3f2}
@deffn {方法} BaseTransport.get_extra_info (name, default=None)

返回 传输或它使用的相关资源信息。

@emph{name} 是表示要获取传输特定信息的字符串。

@emph{default} 是在信息不可用或传输不支持第三方事件循环实现或当前平台查询时返回的值。

例如下面代码尝试获取传输相关套接字对象:

@example
sock = transport.get_extra_info('socket')
if sock is not None:
    print(sock.getsockopt(...))
@end example

传输可查询信息类别:


@itemize *

@item 
套接字:


@itemize -

@item 
@code{'peername'}: 套接字链接时的远端地址，@ref{2753,,socket.socket.getpeername()} 方法的结果 (出错时为 @code{None} )

@item 
@code{'socket'}: @ref{771,,socket.socket} 实例

@item 
@code{'sockname'}: 套接字本地地址， @ref{2754,,socket.socket.getsockname()} 方法的结果
@end itemize

@item 
SSL套接字


@itemize -

@item 
@code{'compression'}: 用字符串指定压缩算法，或者链接没有压缩时为 @code{None}  ；@ref{b76,,ssl.SSLSocket.compression()} 的结果。

@item 
@code{'cipher'}: 一个三值的元组，包含使用密码的名称，定义使用的SSL协议的版本，使用的加密位数。  @ref{2755,,ssl.SSLSocket.cipher()} 的结果。

@item 
@code{'peercert'}: 远端凭证；  @ref{9c0,,ssl.SSLSocket.getpeercert()} 结果。

@item 
@code{'sslcontext'}: @ref{4f2,,ssl.SSLContext} 实例

@item 
@code{'ssl_object'}: @ref{4f1,,ssl.SSLObject} 或 @ref{192,,ssl.SSLSocket} 实例
@end itemize

@item 
管道：


@itemize -

@item 
@code{'pipe'}: 管道对象
@end itemize

@item 
子进程：


@itemize -

@item 
@code{'subprocess'}: @ref{3e3,,subprocess.Popen} 实例
@end itemize
@end itemize
@end deffn

@geindex set_protocol() (asyncio.BaseTransport 方法)
@anchor{library/asyncio-protocol asyncio BaseTransport set_protocol}@anchor{2756}
@deffn {方法} BaseTransport.set_protocol (protocol)

设置一个新协议。

只有两种协议都写明支持切换才能完成切换协议。
@end deffn

@geindex get_protocol() (asyncio.BaseTransport 方法)
@anchor{library/asyncio-protocol asyncio BaseTransport get_protocol}@anchor{2757}
@deffn {方法} BaseTransport.get_protocol ()

返回当前协议。
@end deffn

@node 只读传输,只写传输,基础传输,传输
@anchor{library/asyncio-protocol read-only-transports}@anchor{2758}
@subsubsection 只读传输


@geindex is_reading() (asyncio.ReadTransport 方法)
@anchor{library/asyncio-protocol asyncio ReadTransport is_reading}@anchor{478}
@deffn {方法} ReadTransport.is_reading ()

如果传输接收到新数据时返回 @code{True} 。


3.7 新版功能.

@end deffn

@geindex pause_reading() (asyncio.ReadTransport 方法)
@anchor{library/asyncio-protocol asyncio ReadTransport pause_reading}@anchor{47a}
@deffn {方法} ReadTransport.pause_reading ()

暂停传输的接收端。@ref{2759,,protocol.data_received()} 方法将不会收到数据，除非 @ref{479,,resume_reading()}  被调用。


在 3.7 版更改: 这个方法幂等的， 它可以在传输已经暂停或关闭时调用。

@end deffn

@geindex resume_reading() (asyncio.ReadTransport 方法)
@anchor{library/asyncio-protocol asyncio ReadTransport resume_reading}@anchor{479}
@deffn {方法} ReadTransport.resume_reading ()

恢复接收端。如果有数据可读取时，协议方法 @ref{2759,,protocol.data_received()} 将再次被调用。


在 3.7 版更改: 这个方法幂等的， 它可以在传输已经准备好读取数据时调用。

@end deffn

@node 只写传输,数据报传输,只读传输,传输
@anchor{library/asyncio-protocol write-only-transports}@anchor{275a}
@subsubsection 只写传输


@geindex abort() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport abort}@anchor{275b}
@deffn {方法} WriteTransport.abort ()

立即关闭传输，不会等待已提交的操作处理完毕。已缓存的数据将会丢失。不会接收更多数据。   最终 @ref{204,,None} 将作为协议的 @ref{2752,,protocol.connection_lost()}  方法的参数被调用。
@end deffn

@geindex can_write_eof() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport can_write_eof}@anchor{275c}
@deffn {方法} WriteTransport.can_write_eof ()

如果传输支持 @ref{275d,,write_eof()} 返回  @ref{59c,,True} 否则返回  @ref{497,,False}  。
@end deffn

@geindex get_write_buffer_size() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport get_write_buffer_size}@anchor{275e}
@deffn {方法} WriteTransport.get_write_buffer_size ()

返回传输使用输出缓冲区的当前大小。
@end deffn

@geindex get_write_buffer_limits() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport get_write_buffer_limits}@anchor{799}
@deffn {方法} WriteTransport.get_write_buffer_limits ()

获取写入流控制 @emph{high} 和 @emph{low} 高低标记位。返回元组 @code{(low, high)} ， @emph{low} 和 @emph{high} 为正字节数。

使用 @ref{275f,,set_write_buffer_limits()} 设置限制。


3.4.2 新版功能.

@end deffn

@geindex set_write_buffer_limits() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport set_write_buffer_limits}@anchor{275f}
@deffn {方法} WriteTransport.set_write_buffer_limits (high=None, low=None)

设置写入流控制 @emph{high} 和 @emph{low} 高低标记位。

这两个值（以字节数表示）控制何时调用协议的 @ref{2760,,protocol.pause_writing()} 和 @ref{2761,,protocol.resume_writing()} 方法。 如果指明，则低水位必须小于或等于高水位。 @emph{high} 和 @emph{low} 都不能为负值。

@ref{2760,,pause_writing()} 会在缓冲区尺寸大于或等于 @emph{high} 值时被调用。 如果写入已经被暂停，@ref{2761,,resume_writing()} 会在缓冲区尺寸小于或等于 @emph{low} 值时被调用。

默认值是实现专属的。 如果只给出了高水位值，则低水位值默认为一个小于或等于高水位值的实现传属值。 将 @emph{high} 设为零会强制将 @emph{low} 也设为零，并使得 @ref{2760,,pause_writing()} 在缓冲区变为非空的任何时刻被调用。 将 @emph{low} 设为零会使得 @ref{2761,,resume_writing()} 在缓冲区为空时只被调用一次。 对于上下限都使用零值通常是不够优化的，因为它减少了并发执行 I/O 和计算的机会。

可使用 @ref{799,,get_write_buffer_limits()} 来获取上下限值。
@end deffn

@geindex write() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport write}@anchor{2762}
@deffn {方法} WriteTransport.write (data)

将一些 @emph{data} 字节串写入传输。

此方法不会阻塞；它会缓冲数据并安排其被异步地发出。
@end deffn

@geindex writelines() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport writelines}@anchor{2763}
@deffn {方法} WriteTransport.writelines (list_of_data)

将数据字节串的列表（或任意可迭代对象）写入传输。 这在功能上等价于在可迭代对象产生的每个元素上调用 @ref{2762,,write()}，但其实现可能更为高效。
@end deffn

@geindex write_eof() (asyncio.WriteTransport 方法)
@anchor{library/asyncio-protocol asyncio WriteTransport write_eof}@anchor{275d}
@deffn {方法} WriteTransport.write_eof ()

在刷新所有已缓冲数据之后关闭传输的写入端。 数据仍可以被接收。

如果传输（例如 SSL）不支持半关闭的连接，此方法会引发 @ref{70e,,NotImplementedError}。
@end deffn

@node 数据报传输,子进程传输,只写传输,传输
@anchor{library/asyncio-protocol datagram-transports}@anchor{2764}
@subsubsection 数据报传输


@geindex sendto() (asyncio.DatagramTransport 方法)
@anchor{library/asyncio-protocol asyncio DatagramTransport sendto}@anchor{2765}
@deffn {方法} DatagramTransport.sendto (data, addr=None)

将 @emph{data} 字节串发送到 @emph{addr} (基于传输的目标地址) 所给定的远端对等方。 如果 @emph{addr} 为 @ref{204,,None}，则将数据发送到传输创建时给定的目标地址。

此方法不会阻塞；它会缓冲数据并安排其被异步地发出。
@end deffn

@geindex abort() (asyncio.DatagramTransport 方法)
@anchor{library/asyncio-protocol asyncio DatagramTransport abort}@anchor{2766}
@deffn {方法} DatagramTransport.abort ()

立即关闭传输，不会等待已提交的操作执行完毕。 已缓存的数据将会丢失。 不会接收更多的数据。 协议的 @ref{2752,,protocol.connection_lost()} 方法最终将附带 @ref{204,,None} 作为参数被调用。
@end deffn

@node 子进程传输,,数据报传输,传输
@anchor{library/asyncio-protocol asyncio-subprocess-transports}@anchor{26c4}@anchor{library/asyncio-protocol subprocess-transports}@anchor{2767}
@subsubsection 子进程传输


@geindex get_pid() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_pid}@anchor{2768}
@deffn {方法} SubprocessTransport.get_pid ()

将子进程的进程 ID 以整数形式返回。
@end deffn

@geindex get_pipe_transport() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_pipe_transport}@anchor{2769}
@deffn {方法} SubprocessTransport.get_pipe_transport (fd)

返回对应于整数文件描述符 @emph{fd} 的通信管道的传输:


@itemize *

@item 
@code{0}: 标准输入 (@emph{stdin}) 的可读流式传输，如果子进程创建时未设置 @code{stdin=PIPE} 则为 @ref{204,,None}

@item 
@code{1}: 标准输出 (@emph{stdout}) 的可写流式传输，如果子进程创建时未设置 @code{stdout=PIPE} 则为 @ref{204,,None}

@item 
@code{2}: 标准错误 (@emph{stderr}) 的可写流式传输，如果子进程创建时未设置 @code{stderr=PIPE} 则为 @ref{204,,None}

@item 
其他 @emph{fd}: @ref{204,,None}
@end itemize
@end deffn

@geindex get_returncode() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport get_returncode}@anchor{276a}
@deffn {方法} SubprocessTransport.get_returncode ()

返回整数形式的进程返回码，或者如果还未返回则为 @ref{204,,None}，这类似于 @ref{10ee,,subprocess.Popen.returncode} 属性。
@end deffn

@geindex kill() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport kill}@anchor{276b}
@deffn {方法} SubprocessTransport.kill ()

杀死子进程。

在 POSIX 系统中，函数会发送 SIGKILL 到子进程。 在 Windows 中，此方法是 @ref{276c,,terminate()} 的别名。

另请参见 @ref{25ec,,subprocess.Popen.kill()}。
@end deffn

@geindex send_signal() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport send_signal}@anchor{276d}
@deffn {方法} SubprocessTransport.send_signal (signal)

发送 @emph{signal} 编号到子进程，与 @ref{10ed,,subprocess.Popen.send_signal()} 一样。
@end deffn

@geindex terminate() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport terminate}@anchor{276c}
@deffn {方法} SubprocessTransport.terminate ()

停止子进程。

在 POSIX 系统中，此方法会发送 SIGTERM 到子进程。 在 Windows 中，则会调用 Windows API 函数 TerminateProcess() 来停止子进程。

另请参见 @ref{25eb,,subprocess.Popen.terminate()}。
@end deffn

@geindex close() (asyncio.SubprocessTransport 方法)
@anchor{library/asyncio-protocol asyncio SubprocessTransport close}@anchor{276e}
@deffn {方法} SubprocessTransport.close ()

通过调用 @ref{276b,,kill()} 方法来杀死子进程。

如果子进程尚未返回，并关闭 @emph{stdin}, @emph{stdout} 和 @emph{stderr} 管道的传输。
@end deffn

@node 协议,示例<22>,传输,传输和协议
@anchor{library/asyncio-protocol asyncio-protocol}@anchor{270e}@anchor{library/asyncio-protocol protocols}@anchor{2748}
@subsubsection 协议


@strong{源码:} Lib/asyncio/protocols.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/protocols.py}


__________________________________________________________________


asyncio 提供了一组抽象基类，它们应当被用于实现网络协议。 这些类被设计为与 @ref{270f,,传输} 配合使用。

抽象基础协议类的子类可以实现其中的部分或全部方法。 所有这些方法都是回调：它们由传输或特定事件调用，例如当数据被接收的时候。 基础协议方法应当由相应的传输来调用。

@menu
* 基础协议:: 
* 基础协议: 基础协议<2>. 
* 流式协议:: 
* 缓冲流协议:: 
* 数据报协议:: 
* 子进程协议:: 

@end menu

@node 基础协议,基础协议<2>,,协议
@anchor{library/asyncio-protocol base-protocols}@anchor{276f}
@subsubsection 基础协议


@geindex BaseProtocol (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio BaseProtocol}@anchor{274b}
@deffn {类} asyncio.BaseProtocol

带有所有协议的共享方法的基础协议。
@end deffn

@geindex Protocol (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio Protocol}@anchor{274c}
@deffn {类} asyncio.Protocol (BaseProtocol)

用于实现流式协议（TCP, Unix 套接字等等）的基类。
@end deffn

@geindex BufferedProtocol (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio BufferedProtocol}@anchor{3f3}
@deffn {类} asyncio.BufferedProtocol (BaseProtocol)

用于实现可对接收缓冲区进行手动控制的流式协议的基类。
@end deffn

@geindex DatagramProtocol (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio DatagramProtocol}@anchor{274d}
@deffn {类} asyncio.DatagramProtocol (BaseProtocol)

用于实现数据报（UDP）协议的基类。
@end deffn

@geindex SubprocessProtocol (asyncio 中的类)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol}@anchor{272d}
@deffn {类} asyncio.SubprocessProtocol (BaseProtocol)

用于实现与子进程通信（单向管道）的协议的基类。
@end deffn

@node 基础协议<2>,流式协议,基础协议,协议
@anchor{library/asyncio-protocol base-protocol}@anchor{2770}
@subsubsection 基础协议


所有 asyncio 协议均可实现基础协议回调。

@subsubheading 连接回调


连接回调会在所有协议上被调用，每个成功的连接将恰好调用一次。 所有其他协议回调只能在以下两个方法之间被调用。

@geindex connection_made() (asyncio.BaseProtocol 方法)
@anchor{library/asyncio-protocol asyncio BaseProtocol connection_made}@anchor{2710}
@deffn {方法} BaseProtocol.connection_made (transport)

连接建立时被调用。

@emph{transport} 参数是代表连接的传输。 此协议负责将引用保存至对应的传输。
@end deffn

@geindex connection_lost() (asyncio.BaseProtocol 方法)
@anchor{library/asyncio-protocol asyncio BaseProtocol connection_lost}@anchor{2752}
@deffn {方法} BaseProtocol.connection_lost (exc)

连接丢失或关闭时将被调用。

方法的参数是一个异常对象或为 @ref{204,,None}。 后者意味着收到了常规的 EOF，或者连接被连接的一端取消或关闭。
@end deffn

@subsubheading 流程控制回调


流程控制回调可由传输来调用以暂停或恢复协议所执行的写入操作。

请查看 @ref{275f,,set_write_buffer_limits()} 方法的文档了解详情。

@geindex pause_writing() (asyncio.BaseProtocol 方法)
@anchor{library/asyncio-protocol asyncio BaseProtocol pause_writing}@anchor{2760}
@deffn {方法} BaseProtocol.pause_writing ()

当传输的缓冲区升至高水位以上时将被调用。
@end deffn

@geindex resume_writing() (asyncio.BaseProtocol 方法)
@anchor{library/asyncio-protocol asyncio BaseProtocol resume_writing}@anchor{2761}
@deffn {方法} BaseProtocol.resume_writing ()

当传输的缓冲区降到低水位以下时将被调用。
@end deffn

如果缓冲区大小等于高水位值，则 @ref{2760,,pause_writing()} 不会被调用：缓冲区大小必须要高于该值。

相反地，@ref{2761,,resume_writing()} 会在缓冲区大小等于或小于低水位值时被调用。 这些结束条件对于当两个水位取零值时也能确保符合预期的行为是很重要的。

@node 流式协议,缓冲流协议,基础协议<2>,协议
@anchor{library/asyncio-protocol streaming-protocols}@anchor{2771}
@subsubsection 流式协议


事件方法，例如 @ref{46e,,loop.create_server()}, @ref{46f,,loop.create_unix_server()}, @ref{2ec,,loop.create_connection()}, @ref{2684,,loop.create_unix_connection()}, @ref{476,,loop.connect_accepted_socket()}, @ref{26c2,,loop.connect_read_pipe()} 和 @ref{26c3,,loop.connect_write_pipe()} 都接受返回流式协议的工厂。

@geindex data_received() (asyncio.Protocol 方法)
@anchor{library/asyncio-protocol asyncio Protocol data_received}@anchor{2759}
@deffn {方法} Protocol.data_received (data)

当收到数据时被调用。 @emph{data} 为包含入站数据的非空字节串对象。

数据是否会被缓冲、分块或重组取决于具体传输。 通常，你不应依赖于特定的语义而应使你的解析具有通用性和灵活性。 但是，数据总是要以正确的顺序被接收。

此方法在连接打开期间可以被调用任意次数。

但是，@ref{2772,,protocol.eof_received()} 最多只会被调用一次。 一旦 @cite{eof_received()} 被调用，@code{data_received()} 就不会再被调用。
@end deffn

@geindex eof_received() (asyncio.Protocol 方法)
@anchor{library/asyncio-protocol asyncio Protocol eof_received}@anchor{2772}
@deffn {方法} Protocol.eof_received ()

当发出信号的另一端不再继续发送数据时（例如通过调用 @ref{275d,,transport.write_eof()}，如果另一端也使用 asyncio 的话）被调用。

此方法可能返回假值 (包括 @code{None})，在此情况下传输将会自行关闭。 相反地，如果此方法返回真值，将以所用的协议来确定是否要关闭传输。 由于默认实现是返回 @code{None}，因此它会隐式地关闭连接。

某些传输，包括 SSL 在内，并不支持半关闭的连接，在此情况下从该方法返回真值将导致连接被关闭。
@end deffn

状态机：

@example
start -> connection_made
    [-> data_received]*
    [-> eof_received]?
-> connection_lost -> end
@end example

@node 缓冲流协议,数据报协议,流式协议,协议
@anchor{library/asyncio-protocol buffered-streaming-protocols}@anchor{2773}
@subsubsection 缓冲流协议



3.7 新版功能.


带缓冲的协议可与任何支持 @ref{2771,,流式协议} 的事件循环方法配合使用。

@code{BufferedProtocol} 实现允许显式手动分配和控制接收缓冲区。 随后事件循环可以使用协议提供的缓冲区来避免不必要的数据复制。 这对于接收大量数据的协议来说会有明显的性能提升。  复杂的协议实现能显著地减少缓冲区分配的数量。

以下回调是在 @ref{3f3,,BufferedProtocol} 实例上被调用的:

@geindex get_buffer() (asyncio.BufferedProtocol 方法)
@anchor{library/asyncio-protocol asyncio BufferedProtocol get_buffer}@anchor{2774}
@deffn {方法} BufferedProtocol.get_buffer (sizehint)

调用后会分配新的接收缓冲区。

@emph{sizehint} 是推荐的返回缓冲区最小尺寸。 返回小于或大于 @emph{sizehint} 推荐尺寸的缓冲区也是可接受的。 当设为 -1 时，缓冲区尺寸可以是任意的。 返回尺寸为零的缓冲区则是错误的。

@code{get_buffer()} 必须返回一个实现了 @ref{174c,,缓冲区协议} 的对象。
@end deffn

@geindex buffer_updated() (asyncio.BufferedProtocol 方法)
@anchor{library/asyncio-protocol asyncio BufferedProtocol buffer_updated}@anchor{2775}
@deffn {方法} BufferedProtocol.buffer_updated (nbytes)

用接收的数据更新缓冲区时被调用。

@emph{nbytes} 是被写入到缓冲区的字节总数。
@end deffn

@geindex eof_received() (asyncio.BufferedProtocol 方法)
@anchor{library/asyncio-protocol asyncio BufferedProtocol eof_received}@anchor{2776}
@deffn {方法} BufferedProtocol.eof_received ()

请查看 @ref{2772,,protocol.eof_received()} 方法的文档。
@end deffn

在连接期间 @ref{2774,,get_buffer()} 可以被调用任意次数。 但是，@ref{2772,,protocol.eof_received()} 最多只能被调用一次，如果被调用，则在此之后 @ref{2774,,get_buffer()} 和 @ref{2775,,buffer_updated()} 不能再被调用。

状态机：

@example
start -> connection_made
    [-> get_buffer
        [-> buffer_updated]?
    ]*
    [-> eof_received]?
-> connection_lost -> end
@end example

@node 数据报协议,子进程协议,缓冲流协议,协议
@anchor{library/asyncio-protocol datagram-protocols}@anchor{2777}
@subsubsection 数据报协议


数据报协议实例应当由传递给 @ref{189,,loop.create_datagram_endpoint()} 方法的协议工厂来构造。

@geindex datagram_received() (asyncio.DatagramProtocol 方法)
@anchor{library/asyncio-protocol asyncio DatagramProtocol datagram_received}@anchor{2778}
@deffn {方法} DatagramProtocol.datagram_received (data, addr)

当接收到数据报时被调用。 @emph{data} 是包含传入数据的字节串对象。 @emph{addr} 是发送数据的对等端地址；实际的格式取决于具体传输。
@end deffn

@geindex error_received() (asyncio.DatagramProtocol 方法)
@anchor{library/asyncio-protocol asyncio DatagramProtocol error_received}@anchor{2779}
@deffn {方法} DatagramProtocol.error_received (exc)

当前一个发送或接收操作引发 @ref{30b,,OSError} 时被调用。  @emph{exc} 是 @ref{30b,,OSError} 的实例。

此方法会在当传输（例如UDP）检测到无法将数据报传给接收方等极少数情况下被调用。 而在大多数情况下，无法送达的数据报将被静默地丢弃。
@end deffn

@cartouche
@quotation 注解 
在 BSD 系统（macOS, FreeBSD 等等）上，数据报协议不支持流控制，因为没有可靠的方式来检测因写入多过包所导致的发送失败。

套接字总是显示为 'ready' 且多余的包会被丢弃。 有一定的可能性会引发 @ref{30b,,OSError} 并设置 @code{errno} 为 @ref{241b,,errno.ENOBUFS}；如果此异常被引发，它将被报告给 @ref{2779,,DatagramProtocol.error_received()}，在其他情况下则会被忽略。
@end quotation
@end cartouche

@node 子进程协议,,数据报协议,协议
@anchor{library/asyncio-protocol asyncio-subprocess-protocols}@anchor{26c5}@anchor{library/asyncio-protocol subprocess-protocols}@anchor{277a}
@subsubsection 子进程协议


子进程协议实例应当由传递给 @ref{2652,,loop.subprocess_exec()} 和 @ref{26c0,,loop.subprocess_shell()} 方法的协议工厂函数来构造。

@geindex pipe_data_received() (asyncio.SubprocessProtocol 方法)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol pipe_data_received}@anchor{277b}
@deffn {方法} SubprocessProtocol.pipe_data_received (fd, data)

当子进程向其 stdout 或 stderr 管道写入数据时被调用。

@emph{fd} 是以整数表示的管道文件描述符。

@emph{data} 是包含已接收数据的非空字节串对象。
@end deffn

@geindex pipe_connection_lost() (asyncio.SubprocessProtocol 方法)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol pipe_connection_lost}@anchor{277c}
@deffn {方法} SubprocessProtocol.pipe_connection_lost (fd, exc)

与子进程通信的其中一个管道关闭时被调用。

@emph{fd} 以整数表示的已关闭文件描述符。
@end deffn

@geindex process_exited() (asyncio.SubprocessProtocol 方法)
@anchor{library/asyncio-protocol asyncio SubprocessProtocol process_exited}@anchor{277d}
@deffn {方法} SubprocessProtocol.process_exited ()

子进程退出时被调用。
@end deffn

@node 示例<22>,,协议,传输和协议
@anchor{library/asyncio-protocol examples}@anchor{274e}
@subsubsection 示例


@menu
* TCP 回显服务器:: 
* TCP 回显客户端:: 
* UDP 回显服务器:: 
* UDP 回显客户端:: 
* 链接已存在的套接字:: 
* loop.subprocess_exec() 与 SubprocessProtocol: loop subprocess_exec 与 SubprocessProtocol. 

@end menu

@node TCP 回显服务器,TCP 回显客户端,,示例<22>
@anchor{library/asyncio-protocol asyncio-example-tcp-echo-server-protocol}@anchor{269a}@anchor{library/asyncio-protocol tcp-echo-server}@anchor{277e}
@subsubsection TCP 回显服务器


使用 @ref{46e,,loop.create_server()} 方法创建 TCP 回显服务器，发回已接收的数据，并关闭连接:

@example
import asyncio


class EchoServerProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        peername = transport.get_extra_info('peername')
        print('Connection from @{@}'.format(peername))
        self.transport = transport

    def data_received(self, data):
        message = data.decode()
        print('Data received: @{!r@}'.format(message))

        print('Send: @{!r@}'.format(message))
        self.transport.write(data)

        print('Close the client socket')
        self.transport.close()


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    server = await loop.create_server(
        lambda: EchoServerProtocol(),
        '127.0.0.1', 8888)

    async with server:
        await server.serve_forever()


asyncio.run(main())
@end example


@subsubheading 参见


@ref{2698,,使用流的 TCP 回显服务器} 示例，使用了高层级的 @ref{475,,asyncio.start_server()} 函数。


@node TCP 回显客户端,UDP 回显服务器,TCP 回显服务器,示例<22>
@anchor{library/asyncio-protocol asyncio-example-tcp-echo-client-protocol}@anchor{2697}@anchor{library/asyncio-protocol tcp-echo-client}@anchor{277f}
@subsubsection TCP 回显客户端


使用 @ref{2ec,,loop.create_connection()} 方法的 TCP 回显客户端，发送数据并等待，直到连接被关闭:

@example
import asyncio


class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        transport.write(self.message.encode())
        print('Data sent: @{!r@}'.format(self.message))

    def data_received(self, data):
        print('Data received: @{!r@}'.format(data.decode()))

    def connection_lost(self, exc):
        print('The server closed the connection')
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = 'Hello World!'

    transport, protocol = await loop.create_connection(
        lambda: EchoClientProtocol(message, on_con_lost),
        '127.0.0.1', 8888)

    # Wait until the protocol signals that the connection
    # is lost and close the transport.
    try:
        await on_con_lost
    finally:
        transport.close()


asyncio.run(main())
@end example


@subsubheading 参见


@ref{2695,,使用流的 TCP 回显客户端} 示例，使用了高层级的 @ref{474,,asyncio.open_connection()} 函数。


@node UDP 回显服务器,UDP 回显客户端,TCP 回显客户端,示例<22>
@anchor{library/asyncio-protocol asyncio-udp-echo-server-protocol}@anchor{2713}@anchor{library/asyncio-protocol udp-echo-server}@anchor{2780}
@subsubsection UDP 回显服务器


使用 @ref{189,,loop.create_datagram_endpoint()} 方法的 UDP 回显服务器，发回已接收的数据:

@example
import asyncio


class EchoServerProtocol:
    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message = data.decode()
        print('Received %r from %s' % (message, addr))
        print('Send %r to %s' % (message, addr))
        self.transport.sendto(data, addr)


async def main():
    print("Starting UDP server")

    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    # One protocol instance will be created to serve all
    # client requests.
    transport, protocol = await loop.create_datagram_endpoint(
        lambda: EchoServerProtocol(),
        local_addr=('127.0.0.1', 9999))

    try:
        await asyncio.sleep(3600)  # Serve for 1 hour.
    finally:
        transport.close()


asyncio.run(main())
@end example

@node UDP 回显客户端,链接已存在的套接字,UDP 回显服务器,示例<22>
@anchor{library/asyncio-protocol asyncio-udp-echo-client-protocol}@anchor{2712}@anchor{library/asyncio-protocol udp-echo-client}@anchor{2781}
@subsubsection UDP 回显客户端


使用 @ref{189,,loop.create_datagram_endpoint()} 方法的 UDP 回显客户端，发送数据并在收到回应时关闭传输:

@example
import asyncio


class EchoClientProtocol:
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost
        self.transport = None

    def connection_made(self, transport):
        self.transport = transport
        print('Send:', self.message)
        self.transport.sendto(self.message.encode())

    def datagram_received(self, data, addr):
        print("Received:", data.decode())

        print("Close the socket")
        self.transport.close()

    def error_received(self, exc):
        print('Error received:', exc)

    def connection_lost(self, exc):
        print("Connection closed")
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = "Hello World!"

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: EchoClientProtocol(message, on_con_lost),
        remote_addr=('127.0.0.1', 9999))

    try:
        await on_con_lost
    finally:
        transport.close()


asyncio.run(main())
@end example

@node 链接已存在的套接字,loop subprocess_exec 与 SubprocessProtocol,UDP 回显客户端,示例<22>
@anchor{library/asyncio-protocol asyncio-example-create-connection}@anchor{269e}@anchor{library/asyncio-protocol connecting-existing-sockets}@anchor{2782}
@subsubsection 链接已存在的套接字


附带一个协议使用 @ref{2ec,,loop.create_connection()} 方法，等待直到套接字接收数据:

@example
import asyncio
import socket


class MyProtocol(asyncio.Protocol):

    def __init__(self, on_con_lost):
        self.transport = None
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        print("Received:", data.decode())

        # We are done: close the transport;
        # connection_lost() will be called automatically.
        self.transport.close()

    def connection_lost(self, exc):
        # The socket has been closed
        self.on_con_lost.set_result(True)


async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()
    on_con_lost = loop.create_future()

    # Create a pair of connected sockets
    rsock, wsock = socket.socketpair()

    # Register the socket to wait for data.
    transport, protocol = await loop.create_connection(
        lambda: MyProtocol(on_con_lost), sock=rsock)

    # Simulate the reception of data from the network.
    loop.call_soon(wsock.send, 'abc'.encode())

    try:
        await protocol.on_con_lost
    finally:
        transport.close()
        wsock.close()

asyncio.run(main())
@end example


@subsubheading 参见


使用低层级的 @ref{269f,,loop.add_reader()} 方法来注册一个 FD 的 @ref{26a0,,监视文件描述符以读取事件} 示例。

使用在协程中通过 @ref{474,,open_connection()} 函数创建的高层级流的 @ref{269c,,注册一个打开的套接字以等待使用流的数据} 示例。


@node loop subprocess_exec 与 SubprocessProtocol,,链接已存在的套接字,示例<22>
@anchor{library/asyncio-protocol asyncio-example-subprocess-proto}@anchor{26dc}@anchor{library/asyncio-protocol loop-subprocess-exec-and-subprocessprotocol}@anchor{2783}
@subsubsection loop.subprocess_exec() 与 SubprocessProtocol


一个使用子进程协议来获取子进程的输出并等待子进程退出的示例。

这个子进程是由 @ref{2652,,loop.subprocess_exec()} 方法创建的:

@example
import asyncio
import sys

class DateProtocol(asyncio.SubprocessProtocol):
    def __init__(self, exit_future):
        self.exit_future = exit_future
        self.output = bytearray()

    def pipe_data_received(self, fd, data):
        self.output.extend(data)

    def process_exited(self):
        self.exit_future.set_result(True)

async def get_date():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    code = 'import datetime; print(datetime.datetime.now())'
    exit_future = asyncio.Future(loop=loop)

    # Create the subprocess controlled by DateProtocol;
    # redirect the standard output into a pipe.
    transport, protocol = await loop.subprocess_exec(
        lambda: DateProtocol(exit_future),
        sys.executable, '-c', code,
        stdin=None, stderr=None)

    # Wait for the subprocess exit using the process_exited()
    # method of the protocol.
    await exit_future

    # Close the stdout pipe.
    transport.close()

    # Read the output which was collected by the
    # pipe_data_received() method of the protocol.
    data = bytes(protocol.output)
    return data.decode('ascii').rstrip()

date = asyncio.run(get_date())
print(f"Current date: @{date@}")
@end example

另请参阅使用高层级 API 编写的 @ref{26db,,相同示例}。

@node 策略,平台支持,传输和协议,asyncio --- 异步 I/O
@anchor{library/asyncio-policy doc}@anchor{2784}@anchor{library/asyncio-policy asyncio-policies}@anchor{26fb}@anchor{library/asyncio-policy policies}@anchor{2785}
@subsubsection 策略


事件循环策略是各个进程的全局对象 ，它控制事件循环的管理。每个事件循环都有一个默认策略，可以使用策略API更改和定制该策略。

策略定义了“上下文”的概念，每个上下文管理一个单独的事件循环。默认策略将*context*定义为当前线程。

通过使用自定义事件循环策略，可以自定义 @ref{466,,get_event_loop()} 、 @ref{26f9,,set_event_loop()}  和 @ref{26fa,,new_event_loop()} 函数的行为。

策略对象应该实现 @ref{2786,,AbstractEventLoopPolicy} 抽象基类中定义的API。

@menu
* 获取和设置策略:: 
* 策略对象:: 
* 进程监视器:: 
* 自定义策略:: 

@end menu

@node 获取和设置策略,策略对象,,策略
@anchor{library/asyncio-policy getting-and-setting-the-policy}@anchor{2787}
@subsubsection 获取和设置策略


可以使用下面函数获取和设置当前进程的策略:

@geindex get_event_loop_policy() (在 asyncio 模块中)
@anchor{library/asyncio-policy asyncio get_event_loop_policy}@anchor{2788}
@deffn {函数} asyncio.get_event_loop_policy ()

返回当前进程域的策略。
@end deffn

@geindex set_event_loop_policy() (在 asyncio 模块中)
@anchor{library/asyncio-policy asyncio set_event_loop_policy}@anchor{2789}
@deffn {函数} asyncio.set_event_loop_policy (policy)

将 @emph{policy} 设置为当前进程域策略。

如果 @emph{policy} 设为 @code{None} 将恢复默认策略。
@end deffn

@node 策略对象,进程监视器,获取和设置策略,策略
@anchor{library/asyncio-policy policy-objects}@anchor{278a}
@subsubsection 策略对象


抽象事件循环策略基类定义如下:

@geindex AbstractEventLoopPolicy (asyncio 中的类)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy}@anchor{2786}
@deffn {类} asyncio.AbstractEventLoopPolicy

异步策略的抽象基类。

@geindex get_event_loop() (asyncio.AbstractEventLoopPolicy 方法)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy get_event_loop}@anchor{278b}
@deffn {方法} get_event_loop ()

为当前上下文获取事件循环。

返回一个实现  @ref{234,,AbstractEventLoop}  接口的事件循环对象。

该方法永远不应返回 @code{None}。


在 3.6 版更改.

@end deffn

@geindex set_event_loop() (asyncio.AbstractEventLoopPolicy 方法)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy set_event_loop}@anchor{278c}
@deffn {方法} set_event_loop (loop)

将当前上下文的事件循环设置为  @emph{loop} 。
@end deffn

@geindex new_event_loop() (asyncio.AbstractEventLoopPolicy 方法)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy new_event_loop}@anchor{278d}
@deffn {方法} new_event_loop ()

创建并返回一个新的事件循环对象。

该方法永远不应返回 @code{None}。
@end deffn

@geindex get_child_watcher() (asyncio.AbstractEventLoopPolicy 方法)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy get_child_watcher}@anchor{278e}
@deffn {方法} get_child_watcher ()

获取子进程监视器对象。

返回一个实现 @ref{278f,,AbstractChildWatcher} 接口的监视器对象。

该函数仅支持Unix。
@end deffn

@geindex set_child_watcher() (asyncio.AbstractEventLoopPolicy 方法)
@anchor{library/asyncio-policy asyncio AbstractEventLoopPolicy set_child_watcher}@anchor{2790}
@deffn {方法} set_child_watcher (watcher)

将当前子进程监视器设置为 @emph{watcher} 。

该函数仅支持Unix。
@end deffn
@end deffn

asyncio附带下列内置策略:

@geindex DefaultEventLoopPolicy (asyncio 中的类)
@anchor{library/asyncio-policy asyncio DefaultEventLoopPolicy}@anchor{2791}
@deffn {类} asyncio.DefaultEventLoopPolicy

默认的 asyncio 策略。 在 Unix 上使用 @ref{26d8,,SelectorEventLoop} 而在 Windows 上使用 @ref{2e5,,ProactorEventLoop}。

不需要手动安装默认策略。asyncio已配置成自动使用默认策略。


在 3.8 版更改: 在 Windows 上，现在默认会使用 @ref{2e5,,ProactorEventLoop}。

@end deffn

@geindex WindowsSelectorEventLoopPolicy (asyncio 中的类)
@anchor{library/asyncio-policy asyncio WindowsSelectorEventLoopPolicy}@anchor{2792}
@deffn {类} asyncio.WindowsSelectorEventLoopPolicy

一个使用 @ref{26d8,,SelectorEventLoop} 事件循环实现的替代事件循环策略。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex WindowsProactorEventLoopPolicy (asyncio 中的类)
@anchor{library/asyncio-policy asyncio WindowsProactorEventLoopPolicy}@anchor{2793}
@deffn {类} asyncio.WindowsProactorEventLoopPolicy

使用  @ref{2e5,,ProactorEventLoop} 事件循环实现的另一种事件循环策略。

@ref{14c1,,可用性}: Windows。
@end deffn

@node 进程监视器,自定义策略,策略对象,策略
@anchor{library/asyncio-policy asyncio-watchers}@anchor{26d9}@anchor{library/asyncio-policy process-watchers}@anchor{2794}
@subsubsection 进程监视器


进程监视器允许定制事件循环如何监视Unix子进程。具体来说，事件循环需要知道子进程何时退出。

在asyncio中子进程由  @ref{3bc,,create_subprocess_exec()} 和 @ref{2652,,loop.subprocess_exec()} 函数创建。

asyncio 定义了 @ref{278f,,AbstractChildWatcher} 抽象基类，子监视器必须要实现它，并具有四种不同实现: @ref{26da,,ThreadedChildWatcher} (已配置为默认使用), @ref{2795,,MultiLoopChildWatcher}, @ref{2796,,SafeChildWatcher} 和 @ref{2797,,FastChildWatcher}。

请参阅  @ref{26d0,,子进程和线程} 部分。

以下两个函数可用于自定义子进程监视器实现，它将被asyncio事件循环使用:

@geindex get_child_watcher() (在 asyncio 模块中)
@anchor{library/asyncio-policy asyncio get_child_watcher}@anchor{2798}
@deffn {函数} asyncio.get_child_watcher ()

返回当前策略的当前子监视器。
@end deffn

@geindex set_child_watcher() (在 asyncio 模块中)
@anchor{library/asyncio-policy asyncio set_child_watcher}@anchor{2799}
@deffn {函数} asyncio.set_child_watcher (watcher)

将当前策略的子监视器设置为 @emph{watcher} 。@emph{watcher} 必须实现 @ref{278f,,AbstractChildWatcher} 基类定义的方法。
@end deffn

@cartouche
@quotation 注解 
第三方事件循环实现可能不支持自定义子监视器。对于这样的事件循环，禁止使用 @ref{2799,,set_child_watcher()} 或不起作用。
@end quotation
@end cartouche

@geindex AbstractChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher}@anchor{278f}
@deffn {类} asyncio.AbstractChildWatcher

@geindex add_child_handler() (asyncio.AbstractChildWatcher 方法)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher add_child_handler}@anchor{279a}
@deffn {方法} add_child_handler (pid, callback, *args)

注册一个新的子处理回调函数。

安排 @code{callback(pid, returncode, *args)} 在进程的PID与 @emph{pid} 相等时调用。指定另一个同进程的回调函数替换之前的回调处理函数。

回调函数 @emph{callback} 必须是线程安全。
@end deffn

@geindex remove_child_handler() (asyncio.AbstractChildWatcher 方法)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher remove_child_handler}@anchor{279b}
@deffn {方法} remove_child_handler (pid)

删除进程PID与 @emph{pid} 相等的进程的处理函数。

处理函数成功删除时返回 @code{True} ，没有删除时返回 @code{False} 。
@end deffn

@geindex attach_loop() (asyncio.AbstractChildWatcher 方法)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher attach_loop}@anchor{279c}
@deffn {方法} attach_loop (loop)

给一个事件循环绑定监视器。

如果监视器之前已绑定另一个事件循环，那么在绑定新循环前会先解绑原来的事件循环。

注意：循环有可能是 @code{None} 。
@end deffn

@geindex is_active() (asyncio.AbstractChildWatcher 方法)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher is_active}@anchor{279d}
@deffn {方法} is_active ()

如果监视器已准备好使用则返回 @code{True}。

使用 @emph{不活动的} 当前子监视器生成子进程将引发 @ref{3e4,,RuntimeError}。


3.8 新版功能.

@end deffn

@geindex close() (asyncio.AbstractChildWatcher 方法)
@anchor{library/asyncio-policy asyncio AbstractChildWatcher close}@anchor{279e}
@deffn {方法} close ()

关闭监视器。

必须调用这个方法以确保相关资源会被清理。
@end deffn
@end deffn

@geindex ThreadedChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio ThreadedChildWatcher}@anchor{26da}
@deffn {类} asyncio.ThreadedChildWatcher

此实现会为每个生成的子进程启动一具新的等待线程。

即使是当 asyncio 事件循环运行在非主 OS 线程上时它也能可靠地工作。

当处理大量子进程时不存在显著的开销 (每次子进程结束时为 @emph{O(1)})，但当每个进程启动一个线程时则需要额外的内存。

此监视器会默认被使用。


3.8 新版功能.

@end deffn

@geindex MultiLoopChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio MultiLoopChildWatcher}@anchor{2795}
@deffn {类} asyncio.MultiLoopChildWatcher

此实现会在实例化时注册一个 @code{SIGCHLD} 信号处理程序。 这可能会破坏为 @code{SIGCHLD} 信号安装自定义处理程序的第三方代码。

此监视器会在收到 @code{SIGCHLD} 信号时通过显式地轮询每个进程来避免干扰其他代码生成的进程。

该监视器一旦被安装就不会限制从不同线程运行子进程。

该解决方案是安全的，但在处理大量进程时会有显著的开销 (每收到一个 @code{SIGCHLD} 时为 @emph{O(n)})。


3.8 新版功能.

@end deffn

@geindex SafeChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio SafeChildWatcher}@anchor{2796}
@deffn {类} asyncio.SafeChildWatcher

该实现会使用主线程中的活动事件循环来处理 @code{SIGCHLD} 信号。 如果主线程没有正在运行的事件循环，则其他线程无法生成子进程 (会引发 @ref{3e4,,RuntimeError})。

此监视器会在收到 @code{SIGCHLD} 信号时通过显式地轮询每个进程来避免干扰其他代码生成的进程。

该解决方案与 @ref{2795,,MultiLoopChildWatcher} 同样安全并同样具有 @emph{O(N)} 复杂度，但需要主线程有正在运行的事件循环才能工作。
@end deffn

@geindex FastChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio FastChildWatcher}@anchor{2797}
@deffn {类} asyncio.FastChildWatcher

这种实现直接调用  @code{os.waitpid(-1)} 来获取所有已结束的进程，可能会中断其它代码洐生进程并等待它们结束。

在处理大量子监视器时没有明显的开销( @emph{O(1)}  每次子监视器结束)。

该解决方案需要主线程有正在运行的事件循环才能工作，这与 @ref{2796,,SafeChildWatcher} 一样。
@end deffn

@geindex PidfdChildWatcher (asyncio 中的类)
@anchor{library/asyncio-policy asyncio PidfdChildWatcher}@anchor{18e}
@deffn {类} asyncio.PidfdChildWatcher

这个实现会轮询处理文件描述符 (pidfds) 以等待子进程终结。 在某些方面，@ref{18e,,PidfdChildWatcher} 是一个“理想的”子进程监视器实现。 它不需要使用信号或线程，不会介入任何在事件循环以外发起的进程，并能随事件循环发起的子进程数量进行线性伸缩。 其主要缺点在于 pidfds 是 Linux 专属的，并且仅在较近版本的核心（5.3+）上可用。


3.9 新版功能.

@end deffn

@node 自定义策略,,进程监视器,策略
@anchor{library/asyncio-policy custom-policies}@anchor{279f}
@subsubsection 自定义策略


要实现一个新的事件循环策略，建议子类化 @ref{2791,,DefaultEventLoopPolicy} 并重写需要定制行为的方法，例如:

@example
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):

    def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        loop = super().get_event_loop()
        # Do something with loop ...
        return loop

asyncio.set_event_loop_policy(MyEventLoopPolicy())
@end example

@node 平台支持,高层级 API 索引,策略,asyncio --- 异步 I/O
@anchor{library/asyncio-platforms doc}@anchor{27a0}@anchor{library/asyncio-platforms asyncio-platform-support}@anchor{271c}@anchor{library/asyncio-platforms platform-support}@anchor{27a1}
@subsubsection 平台支持


@ref{9,,asyncio} 模块被设计为可移植的,但由于平台的底层架构和功能，一些平台存在细微的差异和限制。

@menu
* 所有平台:: 
* Windows: Windows<57>. 
* macOS: macOS<33>. 

@end menu

@node 所有平台,Windows<57>,,平台支持
@anchor{library/asyncio-platforms all-platforms}@anchor{27a2}
@subsubsection 所有平台



@itemize *

@item 
@ref{269f,,loop.add_reader()} 和 @ref{271a,,loop.add_writer()} 不能用来监视文件I/O。
@end itemize

@node Windows<57>,macOS<33>,所有平台,平台支持
@anchor{library/asyncio-platforms windows}@anchor{27a3}
@subsubsection Windows


@strong{源代码:} Lib/asyncio/proactor_events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/proactor_events.py}, Lib/asyncio/windows_events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/windows_events.py}, Lib/asyncio/windows_utils.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/windows_utils.py}


__________________________________________________________________



在 3.8 版更改: 在 Windows 上，@ref{2e5,,ProactorEventLoop} 现在是默认的事件循环。


Windows上的所有事件循环都不支持以下方法:


@itemize *

@item 
不支持 @ref{2684,,loop.create_unix_connection()} 和 @ref{46f,,loop.create_unix_server()} 。 @ref{f78,,socket.AF_UNIX} 套接字相关参数仅限于Unix。

@item 
不支持 @ref{2653,,loop.add_signal_handler()} 和 @ref{2725,,loop.remove_signal_handler()} 。
@end itemize

@ref{26d8,,SelectorEventLoop} 有下列限制:


@itemize *

@item 
@ref{27a4,,SelectSelector} 只被用于等待套接字事件：它支持套接字且最多支持512个套接字。

@item 
@ref{269f,,loop.add_reader()} 和 @ref{271a,,loop.add_writer()} 只接受套接字处理回调函数(如管道、文件描述符等都不支持)。

@item 
因为不支持管道，所以  @ref{26c2,,loop.connect_read_pipe()} 和 @ref{26c3,,loop.connect_write_pipe()} 方法没有实现。

@item 
不支持 @ref{264f,,Subprocesses} ，也就是  @ref{2652,,loop.subprocess_exec()} 和 @ref{26c0,,loop.subprocess_shell()} 方法没有实现。
@end itemize

@ref{2e5,,ProactorEventLoop} 有下列限制:


@itemize *

@item 
不支持  @ref{269f,,loop.add_reader()} 和 @ref{271a,,loop.add_writer()} 方法。
@end itemize

Windows上单调时钟的分辨率大约为 15.6 毫秒。最佳的分辨率是 0.5 毫秒。分辨率依赖于具体的硬件（HPET@footnote{https://zh.wikipedia.org/wiki/高精度事件计时器}）和Windows的设置。

@menu
* Windows的子进程支持:: 

@end menu

@node Windows的子进程支持,,,Windows<57>
@anchor{library/asyncio-platforms asyncio-windows-subprocess}@anchor{26c1}@anchor{library/asyncio-platforms subprocess-support-on-windows}@anchor{27a5}
@subsubsection Windows的子进程支持


在 Windows 上，默认的事件循环 @ref{2e5,,ProactorEventLoop} 支持子进程，而 @ref{26d8,,SelectorEventLoop} 则不支持。

也不支持 @ref{2790,,policy.set_child_watcher()} 函数，@ref{2e5,,ProactorEventLoop} 有不同的机制来监视子进程。

@node macOS<33>,,Windows<57>,平台支持
@anchor{library/asyncio-platforms macos}@anchor{27a6}
@subsubsection macOS


完整支持流行的macOS版本。

@subsubheading macOS <= 10.8


在 macOS 10.6, 10.7 和 10.8 上，默认的事件循环使用 @ref{27a7,,selectors.KqueueSelector}，在这些版本上它并不支持字符设备。 可以手工配置 @ref{26d8,,SelectorEventLoop} 来使用 @ref{27a4,,SelectSelector} 或 @ref{557,,PollSelector} 以在这些较老版本的 macOS 上支持字符设备。 例如:

@example
import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
@end example

@node 高层级 API 索引,低层级 API 索引,平台支持,asyncio --- 异步 I/O
@anchor{library/asyncio-api-index doc}@anchor{27a8}@anchor{library/asyncio-api-index high-level-api-index}@anchor{27a9}
@subsubsection 高层级 API 索引


这个页面列举了所有能用于 async/wait 的高层级asyncio API 集。

@menu
* Tasks:: 
* 队列集: 队列集<2>. 
* 子进程集:: 
* 流: 流<2>. 
* 同步:: 
* 异常: 异常<10>. 

@end menu

@node Tasks,队列集<2>,,高层级 API 索引
@anchor{library/asyncio-api-index tasks}@anchor{27aa}
@subsubsection Tasks


运行异步程序，创建Task对象，等待多件事运行超时的公共集。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{18d,,run()}

@tab

创建事件循环，运行一个协程，关闭事件循环。

@item

@ref{2e8,,create_task()}

@tab

启动一个asyncio的Task对象。

@item

@code{await} @ref{3b2,,sleep()}

@tab

休眠几秒。

@item

@code{await} @ref{3b3,,gather()}

@tab

并发执行所有事件的调度和等待。

@item

@code{await} @ref{191,,wait_for()}

@tab

有超时控制的运行。

@item

@code{await} @ref{3b4,,shield()}

@tab

屏蔽取消操作

@item

@code{await} @ref{208,,wait()}

@tab

完成情况的监控器

@item

@ref{229,,current_task()}

@tab

返回当前Task对象

@item

@ref{22a,,all_tasks()}

@tab

返回事件循环中所有的task对象。

@item

@ref{2e7,,Task}

@tab

Task对象

@item

@ref{18f,,to_thread()}

@tab

在不同的 OS 线程中异步地运行一个函数。

@item

@ref{61c,,run_coroutine_threadsafe()}

@tab

从其他OS线程中调度一个协程。

@item

@code{for in} @ref{3b5,,as_completed()}

@tab

用 @code{for} 循环监控完成情况。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{2661,,使用 asyncio.gather() 并行运行}.

@item 
@ref{2666,,使用 asyncio.wait_for() 强制超时}.

@item 
@ref{2672,,撤销协程}.

@item 
@ref{265f,,asyncio.sleep() 的用法}.

@item 
请主要参阅 @ref{264d,,协程与任务文档}.
@end itemize

@node 队列集<2>,子进程集,Tasks,高层级 API 索引
@anchor{library/asyncio-api-index queues}@anchor{27ab}
@subsubsection 队列集


队列集被用于多个异步Task对象的运行调度，实现连接池以及发布/订阅模式。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{3bb,,Queue}

@tab

先进先出队列

@item

@ref{26ec,,PriorityQueue}

@tab

优先级队列。

@item

@ref{26ee,,LifoQueue}

@tab

后进先出队列。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{26f0,,使用 asyncio.Queue 在多个并发任务间分配工作量}.

@item 
请参阅 @ref{2650,,队列集文档}.
@end itemize

@node 子进程集,流<2>,队列集<2>,高层级 API 索引
@anchor{library/asyncio-api-index subprocesses}@anchor{27ac}
@subsubsection 子进程集


用于生成子进程和运行shell命令的工具包。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{3bc,,create_subprocess_exec()}

@tab

创建一个子进程。

@item

@code{await} @ref{3bd,,create_subprocess_shell()}

@tab

运行一个shell命令。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{26bc,,执行一个shell命令}.

@item 
请参阅 @ref{264f,,子进程 APIs} 相关文档.
@end itemize

@node 流<2>,同步,子进程集,高层级 API 索引
@anchor{library/asyncio-api-index streams}@anchor{27ad}
@subsubsection 流


用于网络IO处理的高级API集。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{474,,open_connection()}

@tab

建立一个TCP连接。

@item

@code{await} @ref{2683,,open_unix_connection()}

@tab

建立一个Unix socket连接。

@item

@code{await} @ref{475,,start_server()}

@tab

启动TCP服务。

@item

@code{await} @ref{2685,,start_unix_server()}

@tab

启动一个Unix socket服务。

@item

@ref{114e,,StreamReader}

@tab

接收网络数据的高级async/await对象。

@item

@ref{114f,,StreamWriter}

@tab

发送网络数据的高级async/await对象。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{2681,,TCP 客户端样例}.

@item 
请参阅 @ref{264e,,streams APIs} 文档。
@end itemize

@node 同步,异常<10>,流<2>,高层级 API 索引
@anchor{library/asyncio-api-index synchronization}@anchor{27ae}
@subsubsection 同步


能被用于Task对象集的，类似线程的同步基元组件。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{3b6,,Lock}

@tab

互斥锁。

@item

@ref{3b7,,Event}

@tab

事件对象。

@item

@ref{3b8,,Condition}

@tab

条件对象

@item

@ref{3b9,,Semaphore}

@tab

信号量

@item

@ref{3ba,,BoundedSemaphore}

@tab

有界的信号量。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{26ab,,asyncio.Event 的用法}.

@item 
请参阅asyncio文档 @ref{2651,,synchronization primitives}.
@end itemize

@node 异常<10>,,同步,高层级 API 索引
@anchor{library/asyncio-api-index exceptions}@anchor{27af}
@subsubsection 异常



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2665,,asyncio.TimeoutError}

@tab

类似 @ref{191,,wait_for()} 等函数在超时时候被引发。请注意 @code{asyncio.TimeoutError} 与内建异常 @ref{a86,,TimeoutError} 无关。

@item

@ref{2e1,,asyncio.CancelledError}

@tab

当一个Task对象被取消的时候被引发。请参阅 @ref{2663,,Task.cancel()}。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{2672,,在取消请求发生的运行代码中如何处理CancelledError异常}.

@item 
请参阅完整的 @ref{26f2,,asyncio 专用异常} 列表.
@end itemize

@node 低层级 API 索引,用 asyncio 开发,高层级 API 索引,asyncio --- 异步 I/O
@anchor{library/asyncio-llapi-index doc}@anchor{27b0}@anchor{library/asyncio-llapi-index low-level-api-index}@anchor{27b1}
@subsubsection 低层级 API 索引


本页列出所有低层级的 asyncio API。

@menu
* 获取事件循环:: 
* 事件循环方法集: 事件循环方法集<2>. 
* 传输: 传输<2>. 
* 协议: 协议<2>. 
* 事件循环策略:: 

@end menu

@node 获取事件循环,事件循环方法集<2>,,低层级 API 索引
@anchor{library/asyncio-llapi-index obtaining-the-event-loop}@anchor{27b2}
@subsubsection 获取事件循环



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{465,,asyncio.get_running_loop()}

@tab

获取当前运行的事件循环 @strong{首选} 函数。

@item

@ref{466,,asyncio.get_event_loop()}

@tab

获得一个事件循环实例(当前或通过策略)。

@item

@ref{26f9,,asyncio.set_event_loop()}

@tab

通过当前策略将事件循环设置当前事件循环。

@item

@ref{26fa,,asyncio.new_event_loop()}

@tab

创建一个新的事件循环。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{2744,,使用asyncio.get_running_loop()}。
@end itemize

@node 事件循环方法集<2>,传输<2>,获取事件循环,低层级 API 索引
@anchor{library/asyncio-llapi-index event-loop-methods}@anchor{27b3}
@subsubsection 事件循环方法集


查阅 @ref{741,,事件循环方法} 相关的主要文档段落 。

@subsubheading 生命周期



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{61a,,loop.run_until_complete()}

@tab

运行一个期程/任务/可等待对象直到完成。

@item

@ref{2703,,loop.run_forever()}

@tab

一直运行事件循环。

@item

@ref{622,,loop.stop()}

@tab

停止事件循环。

@item

@ref{2705,,loop.close()}

@tab

关闭事件循环。

@item

@ref{2704,,loop.is_running()}

@tab

返回 @code{True} ， 如果事件循环正在运行。

@item

@ref{798,,loop.is_closed()}

@tab

返回 @code{True} ，如果事件循环已经被关闭 。

@item

@code{await} @ref{623,,loop.shutdown_asyncgens()}

@tab

关闭异步生成器。

@end multitable


@subsubheading 调试



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{796,,loop.set_debug()}

@tab

开启或禁用调试模式。

@item

@ref{797,,loop.get_debug()}

@tab

获取当前测试模式。

@end multitable


@subsubheading 调度回调函数



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{45e,,loop.call_soon()}

@tab

尽快调用回调。

@item

@ref{45f,,loop.call_soon_threadsafe()}

@tab

@ref{45e,,loop.call_soon()} 方法线程安全的变体。

@item

@ref{460,,loop.call_later()}

@tab

在给定时间 @emph{之后} 调用回调函数。

@item

@ref{461,,loop.call_at()}

@tab

在 @emph{指定} 时间调用回调函数。

@end multitable


@subsubheading 线程/进程池



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{190,,loop.run_in_executor()}

@tab

在  @ref{21,,concurrent.futures} 执行器中运行一个独占CPU或其它阻塞函数。

@item

@ref{3a9,,loop.set_default_executor()}

@tab

设置  @ref{190,,loop.run_in_executor()} 默认执行器。

@end multitable


@subsubheading 任务与期程



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{61e,,loop.create_future()}

@tab

创建一个 @ref{54e,,Future} 对象。

@item

@ref{2e9,,loop.create_task()}

@tab

将协程当作 @ref{2e7,,Task} 一样调度。

@item

@ref{79a,,loop.set_task_factory()}

@tab

设置 @ref{2e9,,loop.create_task()} 使用的工厂，它将用来创建  @ref{2e7,,Tasks}  。

@item

@ref{79b,,loop.get_task_factory()}

@tab

获取 @ref{2e9,,loop.create_task()} 使用的工厂，它用来创建  @ref{2e7,,Tasks}  。

@end multitable


@subsubheading DNS



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{5a4,,loop.getaddrinfo()}

@tab

异步版的 @ref{271f,,socket.getaddrinfo()} 。

@item

@code{await} @ref{5a5,,loop.getnameinfo()}

@tab

异步版的 @ref{2720,,socket.getnameinfo()} 。

@end multitable


@subsubheading 网络和IPC



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{2ec,,loop.create_connection()}

@tab

打开一个TCP链接。

@item

@code{await} @ref{46e,,loop.create_server()}

@tab

创建一个TCP服务。

@item

@code{await} @ref{2684,,loop.create_unix_connection()}

@tab

打开一个Unix socket连接。

@item

@code{await} @ref{46f,,loop.create_unix_server()}

@tab

创建一个Unix socket服务。

@item

@code{await} @ref{476,,loop.connect_accepted_socket()}

@tab

将 @ref{771,,socket} 包装成  @code{(transport, protocol)} 对。

@item

@code{await} @ref{189,,loop.create_datagram_endpoint()}

@tab

打开一个数据报(UDP)连接。

@item

@code{await} @ref{2716,,loop.sendfile()}

@tab

通过传输通道发送一个文件。

@item

@code{await} @ref{463,,loop.start_tls()}

@tab

将一个已建立的链接升级到TLS。

@item

@code{await} @ref{26c2,,loop.connect_read_pipe()}

@tab

将管道读取端包装成  @code{(transport, protocol)} 对。

@item

@code{await} @ref{26c3,,loop.connect_write_pipe()}

@tab

将管道写入端包装成  @code{(transport, protocol)} 对。

@end multitable


@subsubheading 套接字



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{await} @ref{5a1,,loop.sock_recv()}

@tab

从 @ref{771,,socket} 接收数据。

@item

@code{await} @ref{464,,loop.sock_recv_into()}

@tab

从 @ref{771,,socket} 接收数据到一个缓冲区中。

@item

@code{await} @ref{5a2,,loop.sock_sendall()}

@tab

发送数据到 @ref{771,,socket} 。

@item

@code{await} @ref{79e,,loop.sock_connect()}

@tab

链接 @code{await} @ref{79e,,loop.sock_connect()} 。

@item

@code{await} @ref{5a3,,loop.sock_accept()}

@tab

接受一个 @ref{771,,socket} 链接。

@item

@code{await} @ref{469,,loop.sock_sendfile()}

@tab

利用 @ref{771,,socket} 发送一个文件。

@item

@ref{269f,,loop.add_reader()}

@tab

开始对一个文件描述符的可读性的监视。

@item

@ref{2719,,loop.remove_reader()}

@tab

停止对一个文件描述符的可读性的监视。

@item

@ref{271a,,loop.add_writer()}

@tab

开始对一个文件描述符的可写性的监视。

@item

@ref{271b,,loop.remove_writer()}

@tab

停止对一个文件描述符的可写性的监视。

@end multitable


@subsubheading Unix信号



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2653,,loop.add_signal_handler()}

@tab

给 @ref{ea,,signal} 添加一个处理回调函数。

@item

@ref{2725,,loop.remove_signal_handler()}

@tab

删除 @ref{ea,,signal} 的处理回调函数。

@end multitable


@subsubheading 子进程



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2652,,loop.subprocess_exec()}

@tab

衍生一个子进程

@item

@ref{26c0,,loop.subprocess_shell()}

@tab

从终端命令衍生一个子进程。

@end multitable


@subsubheading 错误处理



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2729,,loop.call_exception_handler()}

@tab

调用异常处理器。

@item

@ref{2728,,loop.set_exception_handler()}

@tab

设置一个新的异常处理器。

@item

@ref{61f,,loop.get_exception_handler()}

@tab

获取当前异常处理器。

@item

@ref{272a,,loop.default_exception_handler()}

@tab

默认异常处理器实现。

@end multitable


@subsubheading 示例



@itemize *

@item 
@ref{2733,,使用 asyncio.get_event_loop() 和 loop.run_forever()}.

@item 
@ref{2735,,使用 loop.call_later()}.

@item 
使用 @code{loop.create_connection()} 实现 @ref{2697,,echo客户端}.

@item 
使用 @code{loop.create_connection()} 去 @ref{269e,,链接socket}.

@item 
@ref{26a0,,使用add_reader()监听FD(文件描述符)的读取事件}.

@item 
@ref{2738,,使用loop.add_signal_handler()}.

@item 
@ref{26dc,,使用loop.add_signal_handler()}。
@end itemize

@node 传输<2>,协议<2>,事件循环方法集<2>,低层级 API 索引
@anchor{library/asyncio-llapi-index transports}@anchor{27b4}
@subsubsection 传输


所有传输都实现以下方法:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2751,,transport.close()}

@tab

关闭传输。

@item

@ref{61d,,transport.is_closing()}

@tab

返回 @code{True} ，如果传输正在关闭或已经关闭。

@item

@ref{3f2,,transport.get_extra_info()}

@tab

请求传输的相关信息。

@item

@ref{2756,,transport.set_protocol()}

@tab

设置一个新协议。

@item

@ref{2757,,transport.get_protocol()}

@tab

返回当前协议。

@end multitable


传输可以接收数据(TCP和Unix链接，管道等)。它通过 @ref{2ec,,loop.create_connection()}, @ref{2684,,loop.create_unix_connection()}, @ref{26c2,,loop.connect_read_pipe()} 等方法返回。

@subsubheading 读取传输



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{478,,transport.is_reading()}

@tab

返回 @code{True} ，如果传输正在接收。

@item

@ref{47a,,transport.pause_reading()}

@tab

暂停接收。

@item

@ref{479,,transport.resume_reading()}

@tab

继续接收。

@end multitable


传输可以发送数据(TCP和Unix链接，管道等)。它通过 @ref{2ec,,loop.create_connection()}, @ref{2684,,loop.create_unix_connection()}, @ref{26c3,,loop.connect_write_pipe()} 等方法返回。

@subsubheading 写入传输



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2762,,transport.write()}

@tab

向传输写入数据。

@item

@ref{2762,,transport.write()}

@tab

向传输写入缓冲。

@item

@ref{275c,,transport.can_write_eof()}

@tab

返回  @ref{59c,,True} ，如果传输支持发送 EOF。

@item

@ref{275d,,transport.write_eof()}

@tab

在冲洗已缓冲的数据后关闭传输和发送EOF。

@item

@ref{275b,,transport.abort()}

@tab

立即关闭传输。

@item

@ref{275e,,transport.get_write_buffer_size()}

@tab

返回写入流控制的高位标记位和低位标记位。

@item

@ref{275f,,transport.set_write_buffer_limits()}

@tab

设置新的写入流控制的高位标记位和低位标记位。

@end multitable


由 @ref{189,,loop.create_datagram_endpoint()} 返回的传输:

@subsubheading 数据报传输



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2765,,transport.sendto()}

@tab

发送数据到远程链接端。

@item

@ref{2766,,transport.abort()}

@tab

立即关闭传输。

@end multitable


基于子进程的底层抽象传输，它由 @ref{2652,,loop.subprocess_exec()} 和 @ref{26c0,,loop.subprocess_shell()} 返回:

@subsubheading 子进程传输



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2768,,transport.get_pid()}

@tab

返回子进程的进程ID。

@item

@ref{2769,,transport.get_pipe_transport()}

@tab

返回请求通信管道 (@emph{stdin}, @emph{stdout}, 或 @emph{stderr})的传输。

@item

@ref{276a,,transport.get_returncode()}

@tab

返回子进程的返回代号。

@item

@ref{276b,,transport.kill()}

@tab

杀死子进程。

@item

@ref{276d,,transport.send_signal()}

@tab

发送一个信号到子进程。

@item

@ref{276c,,transport.terminate()}

@tab

停止子进程。

@item

@ref{276e,,transport.close()}

@tab

杀死子进程并关闭所有管道。

@end multitable


@node 协议<2>,事件循环策略,传输<2>,低层级 API 索引
@anchor{library/asyncio-llapi-index protocols}@anchor{27b5}
@subsubsection 协议


协议类可以由下面 @strong{回调方法} 实现：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{2710,,connection_made()}

@tab

链接建立时被调用。

@item

@code{callback} @ref{2752,,connection_lost()}

@tab

链接丢失或关闭时被调用。

@item

@code{callback} @ref{2760,,pause_writing()}

@tab

传输的缓冲区超过高位标记位时被调用。

@item

@code{callback} @ref{2761,,resume_writing()}

@tab

传输的缓冲区传送到低位标记位时被调用。

@end multitable


@subsubheading 流协议 (TCP, Unix 套接字, 管道)



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{2759,,data_received()}

@tab

接收到数据时被调用。

@item

@code{callback} @ref{2772,,eof_received()}

@tab

接收到EOF时被调用。

@end multitable


@subsubheading 缓冲流协议



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{2774,,get_buffer()}

@tab

调用后会分配新的接收缓冲区。

@item

@code{callback} @ref{2775,,buffer_updated()}

@tab

用接收的数据更新缓冲区时被调用。

@item

@code{callback} @ref{2776,,eof_received()}

@tab

接收到EOF时被调用。

@end multitable


@subsubheading 数据报协议



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{2778,,datagram_received()}

@tab

接收到数据报时被调用。

@item

@code{callback} @ref{2779,,error_received()}

@tab

前一个发送或接收操作引发  @ref{30b,,OSError} 时被调用。

@end multitable


@subsubheading 子进程协议



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{callback} @ref{277b,,pipe_data_received()}

@tab

子进程向 @emph{stdout} 或 @emph{stderr} 管道写入数据时被调用。

@item

@code{callback} @ref{277c,,pipe_connection_lost()}

@tab

与子进程通信的其中一个管道关闭时被调用。

@item

@code{callback} @ref{277d,,process_exited()}

@tab

子进程退出时被调用。

@end multitable


@node 事件循环策略,,协议<2>,低层级 API 索引
@anchor{library/asyncio-llapi-index event-loop-policies}@anchor{27b6}
@subsubsection 事件循环策略


策略是改变 @ref{466,,asyncio.get_event_loop()} 这类函数行为的一个底层机制。更多细节可以查阅 @ref{26fb,,策略部分}。

@subsubheading 访问策略



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@ref{2788,,asyncio.get_event_loop_policy()}

@tab

返回当前进程域的策略。

@item

@ref{2789,,asyncio.set_event_loop_policy()}

@tab

设置一个新的进程域策略。

@item

@ref{2786,,AbstractEventLoopPolicy}

@tab

策略对象的基类。

@end multitable


@node 用 asyncio 开发,,低层级 API 索引,asyncio --- 异步 I/O
@anchor{library/asyncio-dev doc}@anchor{27b7}@anchor{library/asyncio-dev asyncio-dev}@anchor{27b8}@anchor{library/asyncio-dev developing-with-asyncio}@anchor{27b9}
@subsubsection 用 asyncio 开发


异步编程与传统的“顺序”编程不同。

本页列出常见的错误和陷阱，并解释如何避免它们。

@menu
* Debug 模式:: 
* 并发性和多线程:: 
* 运行阻塞的代码:: 
* 日志: 日志<3>. 
* 检测 never-awaited 协同程序:: 
* 检测就再也没异常:: 

@end menu

@node Debug 模式,并发性和多线程,,用 asyncio 开发
@anchor{library/asyncio-dev asyncio-debug-mode}@anchor{14be}@anchor{library/asyncio-dev debug-mode}@anchor{27ba}
@subsubsection Debug 模式


默认情况下，asyncio以生产模式运行。为了简化开发，asyncio还有一种*debug 模式* 。

有几种方法可以启用异步调试模式:


@itemize *

@item 
将 
@geindex PYTHONASYNCIODEBUG
@geindex 环境变量; PYTHONASYNCIODEBUG
@ref{14bd,,PYTHONASYNCIODEBUG} 环境变量设置为 @code{1} 。

@item 
使用 @ref{160,,Python 开发模式}。

@item 
将 @code{debug=True} 传递给 @ref{18d,,asyncio.run()} 。

@item 
调用 @ref{796,,loop.set_debug()} 。
@end itemize

除了启用调试模式外，还要考虑:


@itemize *

@item 
将 @ref{27bb,,asyncio logger} 的日志级别设置为 @code{logging.DEBUG}，例如，下面的代码片段可以在应用程序启动时运行:

@example
logging.basicConfig(level=logging.DEBUG)
@end example

@item 
配置 @ref{12f,,warnings} 模块以显示 @ref{5d3,,ResourceWarning} 警告。一种方法是使用 @ref{15b,,-W} @code{default} 命令行选项。
@end itemize

启用调试模式时:


@itemize *

@item 
asyncio 检查 @ref{27bc,,未被等待的协程} 并记录他们；这将消除“被遗忘的等待”问题。

@item 
许多非线程安全的异步 APIs (例如 @ref{45e,,loop.call_soon()} 和 @ref{461,,loop.call_at()} 方法)，如果从错误的线程调用，则会引发异常。

@item 
如果执行I/O操作花费的时间太长，则记录I/O选择器的执行时间。

@item 
执行时间超过100毫秒的回调将会载入日志。 属性 @code{loop.slow_callback_duration} 可用于设置以秒为单位的最小执行持续时间，这被视为“缓慢”。
@end itemize

@node 并发性和多线程,运行阻塞的代码,Debug 模式,用 asyncio 开发
@anchor{library/asyncio-dev asyncio-multithreading}@anchor{266b}@anchor{library/asyncio-dev concurrency-and-multithreading}@anchor{27bd}
@subsubsection 并发性和多线程


事件循环在线程中运行(通常是主线程)，并在其线程中执行所有回调和任务。当一个任务在事件循环中运行时，没有其他任务可以在同一个线程中运行。当一个任务执行一个 @code{await} 表达式时，正在运行的任务被挂起，事件循环执行下一个任务。

要调度来自另一 OS 线程的 @ref{2707,,callback}，应该使用 @ref{45f,,loop.call_soon_threadsafe()} 方法。 例如:

@example
loop.call_soon_threadsafe(callback, *args)
@end example

几乎所有异步对象都不是线程安全的，这通常不是问题，除非在任务或回调函数之外有代码可以使用它们。如果需要这样的代码来调用低级异步API，应该使用 @ref{45f,,loop.call_soon_threadsafe()} 方法，例如:

@example
loop.call_soon_threadsafe(fut.cancel)
@end example

要从不同的OS线程调度一个协程对象，应该使用 @ref{61c,,run_coroutine_threadsafe()} 函数。它返回一个 @ref{c09,,concurrent.futures.Future} 。查询结果:

@example
async def coro_func():
     return await asyncio.sleep(1, 42)

# Later in another OS thread:

future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
# Wait for the result:
result = future.result()
@end example

为了能够处理信号和执行子进程，事件循环必须运行于主线程中。

方法 @ref{190,,loop.run_in_executor()} 可以和 @ref{18c,,concurrent.futures.ThreadPoolExecutor} 一起使用，用于在一个不同的操作系统线程中执行阻塞代码，并避免阻塞运行事件循环的那个操作系统线程。

目前没有什么办法能直接从另一个进程 (例如通过 @ref{b7,,multiprocessing} 启动的进程) 安排协程或回调。 @ref{741,,事件循环方法} 小节列出了可以从管道读取并监视文件描述符而不会阻塞事件循环的 API。 此外，asyncio 的 @ref{264f,,子进程} API 提供了一种启动进程并从事件循环与其通信的办法。 最后，之前提到的 @ref{190,,loop.run_in_executor()} 方法也可配合 @ref{196,,concurrent.futures.ProcessPoolExecutor} 使用以在另一个进程中执行代码。

@node 运行阻塞的代码,日志<3>,并发性和多线程,用 asyncio 开发
@anchor{library/asyncio-dev asyncio-handle-blocking}@anchor{27be}@anchor{library/asyncio-dev running-blocking-code}@anchor{27bf}
@subsubsection 运行阻塞的代码


不应该直接调用阻塞( CPU 绑定)代码。例如，如果一个函数执行1秒的 CPU 密集型计算，那么所有并发异步任务和 IO 操作都将延迟1秒。

可以用执行器在不同的线程甚至不同的进程中运行任务，以避免使用事件循环阻塞 OS 线程。 请参阅 @ref{190,,loop.run_in_executor()} 方法了解详情。

@node 日志<3>,检测 never-awaited 协同程序,运行阻塞的代码,用 asyncio 开发
@anchor{library/asyncio-dev asyncio-logger}@anchor{27bb}@anchor{library/asyncio-dev logging}@anchor{27c0}
@subsubsection 日志


asyncio使用 @ref{aa,,logging} 模块，所有日志记录都是通过 @code{"asyncio"} logger执行的。

默认日志级别是 @code{logging.INFO} 。可以很容易地调整:

@example
logging.getLogger("asyncio").setLevel(logging.WARNING)
@end example

@node 检测 never-awaited 协同程序,检测就再也没异常,日志<3>,用 asyncio 开发
@anchor{library/asyncio-dev asyncio-coroutine-not-scheduled}@anchor{27bc}@anchor{library/asyncio-dev detect-never-awaited-coroutines}@anchor{27c1}
@subsubsection 检测 never-awaited 协同程序


当协程函数被调用而不是被等待时 (即执行 @code{coro()} 而不是 @code{await coro()}) 或者协程没有通过 @ref{2e8,,asyncio.create_task()} 被排入计划日程，asyncio 将会发出一条 @ref{3ea,,RuntimeWarning}:

@example
import asyncio

async def test():
    print("never scheduled")

async def main():
    test()

asyncio.run(main())
@end example

输出:

@example
test.py:7: RuntimeWarning: coroutine 'test' was never awaited
  test()
@end example

调试模式的输出:

@example
test.py:7: RuntimeWarning: coroutine 'test' was never awaited
Coroutine created at (most recent call last)
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

  < .. >

  File "../t.py", line 7, in main
    test()
  test()
@end example

通常的修复方法是等待协程或者调用 @ref{2e8,,asyncio.create_task()} 函数:

@example
async def main():
    await test()
@end example

@node 检测就再也没异常,,检测 never-awaited 协同程序,用 asyncio 开发
@anchor{library/asyncio-dev detect-never-retrieved-exceptions}@anchor{27c2}
@subsubsection 检测就再也没异常


如果调用 @ref{2670,,Future.set_exception()} ，但不等待 Future 对象，将异常传播到用户代码。在这种情况下，当 Future 对象被垃圾收集时，asyncio将发出一条日志消息。

未处理异常的例子:

@example
import asyncio

async def bug():
    raise Exception("not consumed")

async def main():
    asyncio.create_task(bug())

asyncio.run(main())
@end example

输出:

@example
Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
  exception=Exception('not consumed')>

Traceback (most recent call last):
  File "test.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed
@end example

@ref{14be,,激活调试模式} 以获取任务创建处的跟踪信息:

@example
asyncio.run(main(), debug=True)
@end example

调试模式的输出:

@example
Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
    exception=Exception('not consumed') created at asyncio/tasks.py:321>

source_traceback: Object created at (most recent call last):
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

< .. >

Traceback (most recent call last):
  File "../t.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed
@end example

@cartouche
@quotation 注解 
asyncio 的源代码可以在 Lib/asyncio/@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/} 中找到。
@end quotation
@end cartouche

@node socket --- 底层网络接口,ssl --- 套接字对象的 TLS/SSL 包装器,asyncio --- 异步 I/O,网络和进程间通信
@anchor{library/socket doc}@anchor{27c3}@anchor{library/socket module-socket}@anchor{ef}@anchor{library/socket socket-low-level-networking-interface}@anchor{27c4}
@subsection @code{socket} --- 底层网络接口


@geindex socket (模块)

@strong{源代码:} Lib/socket.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/socket.py}


__________________________________________________________________


这个模块提供了访问 BSD @emph{套接字} 的接口。在所有现代 Unix 系统、Windows、macOS 和其他一些平台上可用。

@cartouche
@quotation 注解 
一些行为可能因平台不同而异，因为调用的是操作系统的套接字API。
@end quotation
@end cartouche

@geindex 对象; socket

这个Python接口是用Python的面向对象风格对Unix系统调用和套接字库接口的直译：函数 @code{socket()} 返回一个 @emph{套接字对象} ，其方法是对各种套接字系统调用的实现。形参类型一般与C接口相比更高级：例如在Python文件 @code{read()} 和 @code{write()} 操作中，接收操作的缓冲区分配是自动的，发送操作的缓冲区长度是隐式的。


@subsubheading 参见



@table @asis

@item 模块 @ref{f0,,socketserver}

用于简化网络服务端编写的类。

@item 模块 @ref{f3,,ssl}

套接字对象的TLS/SSL封装。
@end table


@menu
* 套接字协议族:: 
* 模块内容: 模块内容<4>. 
* 套接字对象:: 
* 关于套接字超时的说明:: 
* 示例: 示例<23>. 

@end menu

@node 套接字协议族,模块内容<4>,,socket --- 底层网络接口
@anchor{library/socket socket-families}@anchor{27c5}
@subsubsection 套接字协议族


根据系统以及构建选项，此模块提供了各种套接字协议簇。

特定的套接字对象需要的地址格式将根据此套接字对象被创建时指定的地址族被自动选择。套接字地址表示如下：


@itemize -

@item 
一个绑定在文件系统节点上的 @ref{f78,,AF_UNIX} 套接字的地址表示为一个字符串，使用文件系统字符编码和 @code{'surrogateescape'} 错误回调方法（see 
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383}）。一个地址在 Linux 的抽象命名空间被返回为带有初始的 null 字节的 @ref{6e9,,字节类对象} ；注意在这个命名空间种的套接字可能与普通文件系统套接字通信，所以打算运行在 Linux 上的程序可能需要解决两种地址类型。当传递为参数时，一个字符串或字节类对象可以用于任一类型的地址。


在 3.3 版更改: 之前，@ref{f78,,AF_UNIX} 套接字路径被假设使用 UTF-8 编码。



在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end itemize
@anchor{library/socket host-port}@anchor{27c6}

@itemize -

@item 
一对 @code{(host, port)} 被用于 @ref{f76,,AF_INET} 地址族，@emph{host} 是一个表示为互联网域名表示法之内的主机名或者一个 IPv4 地址的字符串，例如 @code{'daring.cwi.nl'} 或 @code{'100.50.200.5'}，@emph{port} 是一个整数。


@itemize -

@item 
对于 IPv4 地址，有两种可接受的特殊形式被用来代替一个主机地址： @code{'@w{'}} 代表 @code{INADDR_ANY}，用来绑定到所有接口；字符串 @code{'<broadcast>'} 代表 @code{INADDR_BROADCAST}。此行为不兼容 IPv6，因此，如果你的 Python 程序打算支持 IPv6，则可能需要避开这些。
@end itemize

@item 
对于 @ref{f77,,AF_INET6} 地址族，使用一个四元组 @code{(host, port, flowinfo, scope_id)}，其中 @emph{flowinfo} 和 @emph{scope_id} 代表了 C 库 @code{struct sockaddr_in6} 中的 @code{sin6_flowinfo} 和 @code{sin6_scope_id} 成员。对于 @ref{ef,,socket} 模块中的方法， @emph{flowinfo} 和 @emph{scope_id} 可以被省略，只为了向后兼容。注意，省略 @emph{scope_id} 可能会导致操作带有领域 (Scope) 的 IPv6 地址时出错。


在 3.7 版更改: 对于多播地址（其 @emph{scope_id} 起作用），@emph{地址} 中可以不包含 @code{%scope_id} （或 @code{zone id} ）部分，这部分是多余的，可以放心省略（推荐）。


@item 
@code{AF_NETLINK} 套接字由一对 @code{(pid, groups)} 表示。

@item 
指定 @code{AF_TIPC} 地址族可以使用仅 Linux 支持的 TIPC 协议。TIPC 是一种开放的、非基于 IP 的网络协议，旨在用于集群计算环境。其地址用元组表示，其中的字段取决于地址类型。一般元组形式为 @code{(addr_type, v1, v2, v3 [, scope])}，其中：


@itemize -

@item 
@emph{addr_type} 取 @code{TIPC_ADDR_NAMESEQ}、@code{TIPC_ADDR_NAME} 或 @code{TIPC_ADDR_ID} 中的一个。

@item 
@emph{scope} 取 @code{TIPC_ZONE_SCOPE}、@code{TIPC_CLUSTER_SCOPE} 和 @code{TIPC_NODE_SCOPE} 中的一个。

@item 
如果 @emph{addr_type} 为 @code{TIPC_ADDR_NAME}，那么 @emph{v1} 是服务器类型，@emph{v2} 是端口标识符，@emph{v3} 应为 0。

如果 @emph{addr_type} 为 @code{TIPC_ADDR_NAMESEQ}，那么 @emph{v1} 是服务器类型，@emph{v2} 是端口号下限，而 @emph{v3} 是端口号上限。

如果 @emph{addr_type} 为 @code{TIPC_ADDR_ID}，那么 @emph{v1} 是节点 (node)，@emph{v2} 是 ref，@emph{v3} 应为 0。
@end itemize

@item 
@ref{27c7,,AF_CAN} 地址族使用元组 @code{(interface, )}，其中 @emph{interface} 是表示网络接口名称的字符串，如 @code{'can0'}。网络接口名 @code{'@w{'}} 可以用于接收本族所有网络接口的数据包。


@itemize -

@item 
@ref{27c8,,CAN_ISOTP} 协议接受一个元组 @code{(interface, rx_addr, tx_addr)}，其中两个额外参数都是无符号长整数，都表示 CAN 标识符（标准或扩展标识符）。

@item 
@ref{1e4,,CAN_J1939} 协议接受一个元组 @code{(interface, name, pgn, addr)}，其中额外参数有：表示 ECU 名称的 64 位无符号整数，表示参数组号 (Parameter Group Number, PGN) 的 32 位无符号整数，以及表示地址的 8 位整数。
@end itemize

@item 
@code{PF_SYSTEM} 协议簇的 @code{SYSPROTO_CONTROL} 协议接受一个字符串或元组 @code{(id, unit)}。其中字符串是内核控件的名称，该控件使用动态分配的 ID。而如果 ID 和内核控件的单元 (unit) 编号都已知，或使用了已注册的 ID，可以采用元组。


3.3 新版功能.


@item 
@code{AF_BLUETOOTH} 支持以下协议和地址格式：


@itemize -

@item 
@code{BTPROTO_L2CAP} 接受 @code{(bdaddr, psm)}，其中 @code{bdaddr} 为字符串格式的蓝牙地址，@code{psm} 是一个整数。

@item 
@code{BTPROTO_RFCOMM} 接受 @code{(bdaddr, channel)}，其中 @code{bdaddr} 为字符串格式的蓝牙地址，@code{channel} 是一个整数。

@item 
@code{BTPROTO_HCI} 接受 @code{(device_id,)}，其中 @code{device_id} 为整数或字符串，它表示接口对应的蓝牙地址（具体取决于你的系统，NetBSD 和 DragonFlyBSD 需要蓝牙地址字符串，其他系统需要整数）。


在 3.2 版更改: 添加了对 NetBSD 和 DragonFlyBSD 的支持。


@item 
@code{BTPROTO_SCO} 接受 @code{bdaddr}，其中 @code{bdaddr} 是 @ref{172,,bytes} 对象，其中含有字符串格式的蓝牙地址（如 @code{b'12:23:34:45:56:67'} ），FreeBSD 不支持此协议。
@end itemize

@item 
@ref{685,,AF_ALG} 是一个仅 Linux 可用的、基于套接字的接口，用于连接内核加密算法。算法套接字可用包括 2 至 4 个元素的元组来配置 @code{(type, name [, feat [, mask]])}，其中：


@itemize -

@item 
@emph{type} 是表示算法类型的字符串，如 @code{aead}、@code{hash}、@code{skcipher} 或 @code{rng}。

@item 
@emph{name} 是表示算法类型和操作模式的字符串，如 @code{sha256}、@code{hmac(sha256)}、@code{cbc(aes)} 或 @code{drbg_nopr_ctr_aes256}。

@item 
@emph{feat} 和 @emph{mask} 是无符号 32 位整数。
@end itemize

@ref{14c1,,Availability}: Linux 2.6.38, some algorithm types require more recent Kernels.


3.6 新版功能.


@item 
@ref{4e2,,AF_VSOCK} 用于支持虚拟机与宿主机之间的通讯。该套接字用 @code{(CID, port)} 元组表示，其中 Context ID (CID) 和 port 都是整数。

@ref{14c1,,Availability}: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5.


3.7 新版功能.


@item 
@ref{27c9,,AF_PACKET} 是一个底层接口，直接连接至网卡。数据包使用元组 @code{(ifname, proto[, pkttype[, hatype[, addr]]])} 表示，其中：


@itemize -

@item 
@emph{ifname} - 指定设备名称的字符串。

@item 
@emph{proto} - 一个用网络字节序表示的整数，指定以太网协议版本号。

@item 
@emph{pkttype} - 指定数据包类型的整数（可选）：


@itemize -

@item 
@code{PACKET_HOST} （默认） - 寻址到本地主机的数据包。

@item 
@code{PACKET_BROADCAST} - 物理层广播的数据包。

@item 
@code{PACKET_MULTIHOST} - 发送到物理层多播地址的数据包。

@item 
@code{PACKET_OTHERHOST} - 被（处于混杂模式的）网卡驱动捕获的、发送到其他主机的数据包。

@item 
@code{PACKET_OUTGOING} - 来自本地主机的、回环到一个套接字的数据包。
@end itemize

@item 
@emph{hatype} - 可选整数，指定 ARP 硬件地址类型。

@item 
@emph{addr} - 可选的类字节串对象，用于指定硬件物理地址，其解释取决于各设备。
@end itemize

@quotation

@ref{14c1,,Availability}: Linux >= 2.2.
@end quotation

@item 
@ref{27ca,,AF_QIPCRTR} 是一个仅 Linux 可用的、基于套接字的接口，用于与高通平台中协处理器上运行的服务进行通信。该地址簇用一个 @code{(node, port)} 元组表示，其中 @emph{node} 和 @emph{port} 为非负整数。

@quotation

@ref{14c1,,Availability}: Linux >= 4.7.
@end quotation


3.8 新版功能.


@item 
@code{IPPROTO_UDPLITE} 是一种 UDP 的变体，允许指定数据包的哪一部分计算入校验码内。它添加了两个可以修改的套接字选项。@code{self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)} 修改传出数据包的哪一部分计算入校验码内，而 @code{self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)} 将过滤掉计算入校验码的数据太少的数据包。在这两种情况下，@code{length} 都应在 @code{range(8, 2**16, 8)} 范围内。

对于 IPv4，应使用 @code{socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)} 来构造这样的套接字；对于 IPv6，应使用 @code{socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE)} 来构造这样的套接字。

@ref{14c1,,Availability}: Linux >= 2.6.20, FreeBSD >= 10.1-RELEASE


3.9 新版功能.

@end itemize

如果你在 IPv4/v6 套接字地址的 @emph{host} 部分中使用了一个主机名，此程序可能会表现不确定行为，因为 Python 使用 DNS 解析返回的第一个地址。套接字地址在实际的 IPv4/v6 中以不同方式解析，根据 DNS 解析和/或 host 配置。为了确定行为，在 @emph{host} 部分中使用数字的地址。

所有的错误都抛出异常。对于无效的参数类型和内存溢出异常情况可能抛出普通异常；从 Python 3.3 开始，与套接字或地址语义有关的错误抛出 @ref{30b,,OSError} 或它的子类之一（常用 @ref{a7f,,socket.error}）。

可以用 @ref{20a0,,setblocking()} 设置非阻塞模式。一个基于超时的 generalization 通过 @ref{27cb,,settimeout()} 支持。

@node 模块内容<4>,套接字对象,套接字协议族,socket --- 底层网络接口
@anchor{library/socket module-contents}@anchor{27cc}
@subsubsection 模块内容


@ref{ef,,socket} 模块包含下列元素。

@menu
* 异常: 异常<11>. 
* 常数: 常数<6>. 
* 函数: 函数<6>. 

@end menu

@node 异常<11>,常数<6>,,模块内容<4>
@anchor{library/socket exceptions}@anchor{27cd}
@subsubsection 异常


@geindex error
@anchor{library/socket socket error}@anchor{a7f}
@deffn {例外} socket.error

一个被弃用的 @ref{30b,,OSError} 的别名。


在 3.3 版更改: 根据 
@geindex Python 提高建议; PEP 3151
PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151}，这个类是 @ref{30b,,OSError} 的别名。

@end deffn

@geindex herror
@anchor{library/socket socket herror}@anchor{27ce}
@deffn {例外} socket.herror

@ref{30b,,OSError} 的子类，本异常通常表示与地址相关的错误，比如那些在 POSIX C API 中使用了 @emph{h_errno} 的函数，包括 @ref{ff9,,gethostbyname_ex()} 和 @ref{ff8,,gethostbyaddr()}。附带的值是一对 @code{(h_errno, string)}，代表库调用返回的错误。@emph{h_errno} 是一个数字，而 @emph{string} 表示 @emph{h_errno} 的描述，它们由 C 函数 @code{hstrerror()} 返回。


在 3.3 版更改: 此类是 @ref{30b,,OSError} 的子类。

@end deffn

@geindex gaierror
@anchor{library/socket socket gaierror}@anchor{27cf}
@deffn {例外} socket.gaierror

@ref{30b,,OSError} 的子类，本异常来自 @ref{271f,,getaddrinfo()} 和 @ref{2720,,getnameinfo()}，表示与地址相关的错误。附带的值是一对 @code{(error, string)}，代表库调用返回的错误。@emph{string} 表示 @emph{error} 的描述，它由 C 函数 @code{gai_strerror()} 返回。数字值 @emph{error} 与本模块中定义的 @code{EAI_*} 常量之一匹配。


在 3.3 版更改: 此类是 @ref{30b,,OSError} 的子类。

@end deffn

@geindex timeout
@anchor{library/socket socket timeout}@anchor{ce1}
@deffn {例外} socket.timeout

@ref{30b,,OSError} 的子类，当套接字发生超时，且事先已调用过 @ref{27cb,,settimeout()} （或隐式地通过 @ref{27d0,,setdefaulttimeout()} ）启用了超时，则会抛出此异常。附带的值是一个字符串，其值总是 "timed out"。


在 3.3 版更改: 此类是 @ref{30b,,OSError} 的子类。

@end deffn

@node 常数<6>,函数<6>,异常<11>,模块内容<4>
@anchor{library/socket constants}@anchor{27d1}
@subsubsection 常数


@quotation

AF_* 和 SOCK_* 常量现在都在 @code{AddressFamily} 和 @code{SocketKind} 这两个 @ref{68e,,IntEnum} 集合内。


3.4 新版功能.

@end quotation

@geindex AF_UNIX() (在 socket 模块中)
@geindex AF_INET() (在 socket 模块中)
@geindex AF_INET6() (在 socket 模块中)
@anchor{library/socket socket AF_UNIX}@anchor{f78}
@deffn {数据} socket.AF_UNIX
@anchor{library/socket socket AF_INET}@anchor{f76}
@deffnx {数据} socket.AF_INET
@anchor{library/socket socket AF_INET6}@anchor{f77}
@deffnx {数据} socket.AF_INET6

这些常量表示地址（和协议）簇，用于 @code{socket()} 的第一个参数。如果 @ref{f78,,AF_UNIX} 常量未定义，即表示不支持该协议。不同系统可能会有更多其他常量可用。
@end deffn

@geindex SOCK_STREAM() (在 socket 模块中)
@geindex SOCK_DGRAM() (在 socket 模块中)
@geindex SOCK_RAW() (在 socket 模块中)
@geindex SOCK_RDM() (在 socket 模块中)
@geindex SOCK_SEQPACKET() (在 socket 模块中)
@anchor{library/socket socket SOCK_STREAM}@anchor{d5a}
@deffn {数据} socket.SOCK_STREAM
@anchor{library/socket socket SOCK_DGRAM}@anchor{d59}
@deffnx {数据} socket.SOCK_DGRAM
@anchor{library/socket socket SOCK_RAW}@anchor{27d2}
@deffnx {数据} socket.SOCK_RAW
@anchor{library/socket socket SOCK_RDM}@anchor{27d3}
@deffnx {数据} socket.SOCK_RDM
@anchor{library/socket socket SOCK_SEQPACKET}@anchor{27d4}
@deffnx {数据} socket.SOCK_SEQPACKET

这些常量表示套接字类型，用于 @code{socket()} 的第二个参数。不同系统可能会有更多其他常量可用。（一般只有 @ref{d5a,,SOCK_STREAM} 和 @ref{d59,,SOCK_DGRAM} 可用）
@end deffn

@geindex SOCK_CLOEXEC() (在 socket 模块中)
@geindex SOCK_NONBLOCK() (在 socket 模块中)
@anchor{library/socket socket SOCK_CLOEXEC}@anchor{59a}
@deffn {数据} socket.SOCK_CLOEXEC
@anchor{library/socket socket SOCK_NONBLOCK}@anchor{599}
@deffnx {数据} socket.SOCK_NONBLOCK

这两个常量（如果已定义）可以与上述套接字类型结合使用，允许你设置这些原子性相关的 flags （从而避免可能的竞争条件和单独调用的需要）。


@subsubheading 参见


Secure File Descriptor Handling （安全地处理文件描述符）@footnote{http://udrepper.livejournal.com/20407.html} 提供了更详尽的解释。


@ref{14c1,,可用性}： Linux >= 2.6.27。


3.2 新版功能.

@end deffn

@geindex SOMAXCONN() (在 socket 模块中)

@deffn {数据} SO_*
@anchor{library/socket socket SOMAXCONN}@anchor{845}
@deffnx {数据} socket.SOMAXCONN

@deffnx {数据} MSG_*

@deffnx {数据} SOL_*

@deffnx {数据} SCM_*

@deffnx {数据} IPPROTO_*

@deffnx {数据} IPPORT_*

@deffnx {数据} INADDR_*

@deffnx {数据} IP_*

@deffnx {数据} IPV6_*

@deffnx {数据} EAI_*

@deffnx {数据} AI_*

@deffnx {数据} NI_*

@deffnx {数据} TCP_*

此列表内的许多常量，记载在 Unix 文档中的套接字和/或 IP 协议部分，同时也定义在本 socket 模块中。它们通常用于套接字对象的 @code{setsockopt()} 和 @code{getsockopt()} 方法的参数中。在大多数情况下，仅那些在 Unix 头文件中有定义的符号会在本模块中定义，部分符号提供了默认值。


在 3.6 版更改: 添加了 @code{SO_DOMAIN}, @code{SO_PROTOCOL}, @code{SO_PEERSEC}, @code{SO_PASSSEC}, @code{TCP_USER_TIMEOUT}, @code{TCP_CONGESTION}。



在 3.6.5 版更改: 在 Windows 上，如果 Windows 运行时支持，则 @code{TCP_FASTOPEN}、@code{TCP_KEEPCNT} 可用。



在 3.7 版更改: 添加了 @code{TCP_NOTSENT_LOWAT}。

在 Windows 上，如果 Windows 运行时支持，则 @code{TCP_KEEPIDLE}、@code{TCP_KEEPINTVL} 可用。

@end deffn

@geindex AF_CAN() (在 socket 模块中)
@geindex PF_CAN() (在 socket 模块中)
@anchor{library/socket socket AF_CAN}@anchor{27c7}
@deffn {数据} socket.AF_CAN
@anchor{library/socket socket PF_CAN}@anchor{27d5}
@deffnx {数据} socket.PF_CAN

@deffnx {数据} SOL_CAN_*

@deffnx {数据} CAN_*

此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。

@ref{14c1,,可用性}： Linux >= 2.6.25。


3.3 新版功能.

@end deffn

@geindex CAN_BCM() (在 socket 模块中)
@anchor{library/socket socket CAN_BCM}@anchor{9a9}
@deffn {数据} socket.CAN_BCM

@deffnx {数据} CAN_BCM_*

CAN 协议簇内的 CAN_BCM 是广播管理器（Bbroadcast Manager -- BCM）协议，广播管理器常量在 Linux 文档中有所记载，在本 socket 模块中也有定义。

@ref{14c1,,可用性}： Linux >= 2.6.25。

@cartouche
@quotation 注解 
@code{CAN_BCM_CAN_FD_FRAME} 旗标仅在 Linux >= 4.8 时可用。
@end quotation
@end cartouche


3.4 新版功能.

@end deffn

@geindex CAN_RAW_FD_FRAMES() (在 socket 模块中)
@anchor{library/socket socket CAN_RAW_FD_FRAMES}@anchor{8bc}
@deffn {数据} socket.CAN_RAW_FD_FRAMES

在 CAN_RAW 套接字中启用 CAN FD 支持，默认是禁用的。它使应用程序可以发送 CAN 和 CAN FD 帧。但是，从套接字读取时，也必须同时接受 CAN 和 CAN FD 帧。

此常量在 Linux 文档中有所记载。

@ref{14c1,,可用性}： Linux >= 3.6。


3.5 新版功能.

@end deffn

@geindex CAN_RAW_JOIN_FILTERS() (在 socket 模块中)
@anchor{library/socket socket CAN_RAW_JOIN_FILTERS}@anchor{1e3}
@deffn {数据} socket.CAN_RAW_JOIN_FILTERS

加入已应用的 CAN 过滤器，这样只有与所有 CAN 过滤器匹配的 CAN 帧才能传递到用户空间。

此常量在 Linux 文档中有所记载。

@ref{14c1,,可用性}： Linux >= 4.1。


3.9 新版功能.

@end deffn

@geindex CAN_ISOTP() (在 socket 模块中)
@anchor{library/socket socket CAN_ISOTP}@anchor{27c8}
@deffn {数据} socket.CAN_ISOTP

CAN 协议簇中的 CAN_ISOTP 就是 ISO-TP (ISO 15765-2) 协议。ISO-TP 常量在 Linux 文档中有所记载。

@ref{14c1,,可用性}： Linux >= 2.6.25。


3.7 新版功能.

@end deffn

@geindex CAN_J1939() (在 socket 模块中)
@anchor{library/socket socket CAN_J1939}@anchor{1e4}
@deffn {数据} socket.CAN_J1939

CAN 协议族中的 CAN_J1939 即 SAE J1939 协议。 J1939 常量记录在 Linux 文档中。

@ref{14c1,,可用性}： Linux >= 5.4。


3.9 新版功能.

@end deffn

@geindex AF_PACKET() (在 socket 模块中)
@geindex PF_PACKET() (在 socket 模块中)
@anchor{library/socket socket AF_PACKET}@anchor{27c9}
@deffn {数据} socket.AF_PACKET
@anchor{library/socket socket PF_PACKET}@anchor{27d6}
@deffnx {数据} socket.PF_PACKET

@deffnx {数据} PACKET_*

此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。

@ref{14c1,,可用性}： Linux >= 2.2。
@end deffn

@geindex AF_RDS() (在 socket 模块中)
@geindex PF_RDS() (在 socket 模块中)
@geindex SOL_RDS() (在 socket 模块中)
@anchor{library/socket socket AF_RDS}@anchor{27d7}
@deffn {数据} socket.AF_RDS
@anchor{library/socket socket PF_RDS}@anchor{27d8}
@deffnx {数据} socket.PF_RDS
@anchor{library/socket socket SOL_RDS}@anchor{27d9}
@deffnx {数据} socket.SOL_RDS

@deffnx {数据} RDS_*

此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块中。

@ref{14c1,,可用性}： Linux >= 2.6.30。


3.3 新版功能.

@end deffn

@geindex SIO_RCVALL() (在 socket 模块中)
@geindex SIO_KEEPALIVE_VALS() (在 socket 模块中)
@geindex SIO_LOOPBACK_FAST_PATH() (在 socket 模块中)
@anchor{library/socket socket SIO_RCVALL}@anchor{27da}
@deffn {数据} socket.SIO_RCVALL
@anchor{library/socket socket SIO_KEEPALIVE_VALS}@anchor{27db}
@deffnx {数据} socket.SIO_KEEPALIVE_VALS
@anchor{library/socket socket SIO_LOOPBACK_FAST_PATH}@anchor{682}
@deffnx {数据} socket.SIO_LOOPBACK_FAST_PATH

@deffnx {数据} RCVALL_*

Windows 的 WSAIoctl() 的常量。这些常量用于套接字对象的 @ref{681,,ioctl()} 方法的参数。


在 3.6 版更改: 添加了 @code{SIO_LOOPBACK_FAST_PATH}。

@end deffn


@deffn {数据} TIPC_*

TIPC 相关常量，与 C socket API 导出的常量一致。更多信息请参阅 TIPC 文档。
@end deffn

@geindex AF_ALG() (在 socket 模块中)
@geindex SOL_ALG() (在 socket 模块中)
@anchor{library/socket socket AF_ALG}@anchor{685}
@deffn {数据} socket.AF_ALG
@anchor{library/socket socket SOL_ALG}@anchor{27dc}
@deffnx {数据} socket.SOL_ALG

@deffnx {数据} ALG_*

用于 Linux 内核加密算法的常量。

@ref{14c1,,可用性}： Linux >= 2.6.38。


3.6 新版功能.

@end deffn

@geindex AF_VSOCK() (在 socket 模块中)
@geindex IOCTL_VM_SOCKETS_GET_LOCAL_CID() (在 socket 模块中)
@anchor{library/socket socket AF_VSOCK}@anchor{4e2}
@deffn {数据} socket.AF_VSOCK
@anchor{library/socket socket IOCTL_VM_SOCKETS_GET_LOCAL_CID}@anchor{27dd}
@deffnx {数据} socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID

@deffnx {数据} VMADDR*

@deffnx {数据} SO_VM*

用于 Linux 宿主机/虚拟机通讯的常量。

@ref{14c1,,可用性}： Linux >= 4.8。


3.7 新版功能.

@end deffn

@geindex AF_LINK() (在 socket 模块中)
@anchor{library/socket socket AF_LINK}@anchor{9aa}
@deffn {数据} socket.AF_LINK

@ref{14c1,,可用性}: BSD、macOS。


3.4 新版功能.

@end deffn

@geindex has_ipv6() (在 socket 模块中)
@anchor{library/socket socket has_ipv6}@anchor{27de}
@deffn {数据} socket.has_ipv6

本常量为一个布尔值，该值指示当前平台是否支持 IPv6。
@end deffn

@geindex BDADDR_ANY() (在 socket 模块中)
@geindex BDADDR_LOCAL() (在 socket 模块中)
@anchor{library/socket socket BDADDR_ANY}@anchor{27df}
@deffn {数据} socket.BDADDR_ANY
@anchor{library/socket socket BDADDR_LOCAL}@anchor{27e0}
@deffnx {数据} socket.BDADDR_LOCAL

这些是字符串常量，包含蓝牙地址，这些地址具有特殊含义。例如，当用 @code{BTPROTO_RFCOMM} 指定绑定套接字时， @ref{27df,,BDADDR_ANY} 表示“任何地址”。
@end deffn

@geindex HCI_FILTER() (在 socket 模块中)
@geindex HCI_TIME_STAMP() (在 socket 模块中)
@geindex HCI_DATA_DIR() (在 socket 模块中)
@anchor{library/socket socket HCI_FILTER}@anchor{27e1}
@deffn {数据} socket.HCI_FILTER
@anchor{library/socket socket HCI_TIME_STAMP}@anchor{27e2}
@deffnx {数据} socket.HCI_TIME_STAMP
@anchor{library/socket socket HCI_DATA_DIR}@anchor{27e3}
@deffnx {数据} socket.HCI_DATA_DIR

与 @code{BTPROTO_HCI} 一起使用。 @ref{27e1,,HCI_FILTER} 在 NetBSD 或 DragonFlyBSD 上不可用。 @ref{27e2,,HCI_TIME_STAMP} 和 @ref{27e3,,HCI_DATA_DIR} 在 FreeBSD、NetBSD 或 DragonFlyBSD 上不可用。
@end deffn

@geindex AF_QIPCRTR() (在 socket 模块中)
@anchor{library/socket socket AF_QIPCRTR}@anchor{27ca}
@deffn {数据} socket.AF_QIPCRTR

高通 IPC 路由协议的常数，用于与提供远程处理器的服务进行通信。

@ref{14c1,,可用性}： Linux >= 4.7。
@end deffn

@node 函数<6>,,常数<6>,模块内容<4>
@anchor{library/socket functions}@anchor{27e4}
@subsubsection 函数


@menu
* 创建套接字:: 
* 其他功能: 其他功能<2>. 

@end menu

@node 创建套接字,其他功能<2>,,函数<6>
@anchor{library/socket creating-sockets}@anchor{27e5}
@subsubsection 创建套接字


下列函数都能创建 @ref{27e6,,套接字对象}.

@geindex socket (socket 中的类)
@anchor{library/socket socket socket}@anchor{771}
@deffn {类} socket.socket (family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

使用给定的地址族、套接字类型和协议号创建一个新的套接字。 地址族应为 @ref{f76,,AF_INET} (默认值), @ref{f77,,AF_INET6}, @ref{f78,,AF_UNIX}, @ref{27c7,,AF_CAN}, @ref{27c9,,AF_PACKET} 或 @ref{27d7,,AF_RDS} 之一。 套接字类型应为 @ref{d5a,,SOCK_STREAM} (默认值), @ref{d59,,SOCK_DGRAM}, @ref{27d2,,SOCK_RAW} 或其他可能的 @code{SOCK_} 常量之一。 协议号通常为零并且可以省略，或在协议族为 @ref{27c7,,AF_CAN} 的情况下，协议应为 @code{CAN_RAW}, @ref{9a9,,CAN_BCM}, @ref{27c8,,CAN_ISOTP} 或 @ref{1e4,,CAN_J1939} 之一。

如果指定了 @emph{fileno}，那么将从这一指定的文件描述符中自动检测 @emph{family}、@emph{type} 和 @emph{proto} 的值。如果调用本函数时显式指定了 @emph{family}、@emph{type} 或 @emph{proto} 参数，可以覆盖自动检测的值。这只会影响 Python 表示诸如 @ref{2753,,socket.getpeername()} 一类函数的返回值的方式，而不影响实际的操作系统资源。与 @ref{27e7,,socket.fromfd()} 不同，@emph{fileno} 将返回原先的套接字，而不是复制出新的套接字。这有助于在分离的套接字上调用 @ref{4e0,,socket.close()} 来关闭它。

新创建的套接字是 @ref{8f1,,不可继承的}。

引发一个 @ref{fec,,审计事件} @code{socket.__new__} 附带参数 @code{self}、@code{family}、@code{type}、@code{protocol}。


在 3.3 版更改: 添加了 AF_CAN 簇。添加了 AF_RDS 簇。



在 3.4 版更改: 添加了 CAN_BCM 协议。



在 3.4 版更改: 返回的套接字现在是不可继承的。



在 3.7 版更改: 添加了 CAN_ISOTP 协议。



在 3.7 版更改: 当将 @ref{599,,SOCK_NONBLOCK} 或 @ref{59a,,SOCK_CLOEXEC} 标志位应用于 @emph{type} 上时，它们会被清除，且 @ref{59b,,socket.type} 反映不出它们。但它们仍将传递给底层系统的 @cite{socket()} 调用。因此，

@example
sock = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
@end example

仍将在支持 @code{SOCK_NONBLOCK} 的系统上创建一个非阻塞的套接字，但是 @code{sock.type} 会被置为 @code{socket.SOCK_STREAM}。



在 3.9 版更改: 添加了 CAN_J1939 协议。

@end deffn

@geindex socketpair() (在 socket 模块中)
@anchor{library/socket socket socketpair}@anchor{585}
@deffn {函数} socket.socketpair ([family[, type[, proto]]])

构建一对已连接的套接字对象，使用给定的地址簇、套接字类型和协议号。地址簇、套接字类型和协议号与上述 @code{socket()} 函数相同。默认地址簇为 @ref{f78,,AF_UNIX} （需要当前平台支持，不支持则默认为 @ref{f76,,AF_INET} ）。

新创建的套接字都是 @ref{8f1,,不可继承的}。


在 3.2 版更改: 现在，返回的套接字对象支持全部套接字 API，而不是全部 API 的一个子集。



在 3.4 版更改: 返回的套接字现在都是不可继承的。



在 3.5 版更改: 添加了 Windows 支持。

@end deffn

@geindex create_connection() (在 socket 模块中)
@anchor{library/socket socket create_connection}@anchor{c77}
@deffn {函数} socket.create_connection (address[, timeout[, source_address]])

连接到一个 TCP 服务，该服务正在侦听 Internet @emph{address} （用二元组 @code{(host, port)} 表示）。连接后返回套接字对象。这是比 @ref{773,,socket.connect()} 更高级的函数：如果 @emph{host} 是非数字主机名，它将尝试从 @ref{f76,,AF_INET} 和 @ref{f77,,AF_INET6} 解析它，然后依次尝试连接到所有可能的地址，直到连接成功。这使得编写兼容 IPv4 和 IPv6 的客户端变得容易。

传入可选参数 @emph{timeout} 可以在套接字实例上设置超时（在尝试连接前）。如果未提供 @emph{timeout}，则使用由 @ref{27e8,,getdefaulttimeout()} 返回的全局默认超时设置。

如果提供了 @emph{source_address}，它必须为二元组 @code{(host, port)}，以便套接字在连接之前绑定为其源地址。如果 host 或 port 分别为 '@w{'} 或 0，则使用操作系统默认行为。


在 3.2 版更改: 添加了 @emph{source_address}。

@end deffn

@geindex create_server() (在 socket 模块中)
@anchor{library/socket socket create_server}@anchor{352}
@deffn {函数} socket.create_server (address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)

便捷函数，创建绑定到 @emph{address} （二元组 @code{(host, port)} ）的 TCP 套接字，返回套接字对象。

@emph{family} 应设置为 @ref{f76,,AF_INET} 或 @ref{f77,,AF_INET6}。@emph{backlog} 是传递给 @ref{844,,socket.listen()} 的队列大小，当它为 @code{0} 则表示默认的合理值。@emph{reuse_port} 表示是否设置 @code{SO_REUSEPORT} 套接字选项。

如果 @emph{dualstack_ipv6} 为 true 且平台支持，则套接字能接受 IPv4 和 IPv6 连接，否则将抛出 @ref{16d,,ValueError} 异常。大多数 POSIX 平台和 Windows 应该支持此功能。启用此功能后，@ref{2753,,socket.getpeername()} 在进行 IPv4 连接时返回的地址将是一个（映射到 IPv4 的）IPv6 地址。在默认启用该功能的平台上（如 Linux），如果 @emph{dualstack_ipv6} 为 false，即显式禁用此功能。该参数可以与 @ref{353,,has_dualstack_ipv6()} 结合使用：

@example
import socket

addr = ("", 8080)  # all interfaces, port 8080
if socket.has_dualstack_ipv6():
    s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
else:
    s = socket.create_server(addr)
@end example

@cartouche
@quotation 注解 
在 POSIX 平台上，设置 @code{SO_REUSEADDR} 套接字选项是为了立即重用以前绑定在同一 @emph{address} 上并保持 TIME_WAIT 状态的套接字。
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@geindex has_dualstack_ipv6() (在 socket 模块中)
@anchor{library/socket socket has_dualstack_ipv6}@anchor{353}
@deffn {函数} socket.has_dualstack_ipv6 ()

如果平台支持创建 IPv4 和 IPv6 连接都可以处理的 TCP 套接字，则返回 @code{True}。


3.8 新版功能.

@end deffn

@geindex fromfd() (在 socket 模块中)
@anchor{library/socket socket fromfd}@anchor{27e7}
@deffn {函数} socket.fromfd (fd, family, type, proto=0)

复制文件描述符 @emph{fd} （一个由文件对象的 @code{fileno()} 方法返回的整数），然后从结果中构建一个套接字对象。地址簇、套接字类型和协议号与上述 @code{socket()} 函数相同。文件描述符应指向一个套接字，但不会专门去检查——如果文件描述符是无效的，则对该对象的后续操作可能会失败。本函数很少用到，但是在将套接字作为标准输入或输出传递给程序（如 Unix inet 守护程序启动的服务器）时，可以使用本函数获取或设置套接字选项。套接字将处于阻塞模式。

新创建的套接字是 @ref{8f1,,不可继承的}。


在 3.4 版更改: 返回的套接字现在是不可继承的。

@end deffn

@geindex fromshare() (在 socket 模块中)
@anchor{library/socket socket fromshare}@anchor{597}
@deffn {函数} socket.fromshare (data)

根据 @ref{596,,socket.share()} 方法获得的数据实例化套接字。套接字将处于阻塞模式。

@ref{14c1,,可用性}: Windows。


3.3 新版功能.

@end deffn

@geindex SocketType() (在 socket 模块中)
@anchor{library/socket socket SocketType}@anchor{27e9}
@deffn {数据} socket.SocketType

这是一个 Python 类型对象，表示套接字对象的类型。它等同于 @code{type(socket(...))}。
@end deffn

@node 其他功能<2>,,创建套接字,函数<6>
@anchor{library/socket other-functions}@anchor{27ea}
@subsubsection 其他功能


@ref{ef,,socket} 模块还提供多种网络相关服务：

@geindex close() (在 socket 模块中)
@anchor{library/socket socket close}@anchor{4e0}
@deffn {函数} socket.close (fd)

关闭一个套接字文件描述符。它类似于 @ref{4e1,,os.close()}，但专用于套接字。在某些平台上（特别是在 Windows 上），@ref{4e1,,os.close()} 对套接字文件描述符无效。


3.7 新版功能.

@end deffn

@geindex getaddrinfo() (在 socket 模块中)
@anchor{library/socket socket getaddrinfo}@anchor{271f}
@deffn {函数} socket.getaddrinfo (host, port, family=0, type=0, proto=0, flags=0)

将 @emph{host}/@emph{port} 参数转换为 5 元组的序列，其中包含创建（连接到某服务的）套接字所需的所有参数。@emph{host} 是域名，是字符串格式的 IPv4/v6 地址或 @code{None}。@emph{port} 是字符串格式的服务名称，如 @code{'http'} 、端口号（数字）或 @code{None}。传入 @code{None} 作为 @emph{host} 和 @emph{port} 的值，相当于将 @code{NULL} 传递给底层 C API。

可以指定 @emph{family}、@emph{type} 和 @emph{proto} 参数，以缩小返回的地址列表。向这些参数分别传入 0 表示保留全部结果范围。@emph{flags} 参数可以是 @code{AI_*} 常量中的一个或多个，它会影响结果的计算和返回。例如，@code{AI_NUMERICHOST} 会禁用域名解析，此时如果 @emph{host} 是域名，则会抛出错误。

本函数返回一个列表，其中的 5 元组具有以下结构：

@code{(family, type, proto, canonname, sockaddr)}

在这些元组中，@emph{family}, @emph{type}, @emph{proto} 都是整数且其作用是被传入 @code{socket()} 函数。 如果 @code{AI_CANONNAME} 是 @emph{flags} 参数的一部分则 @emph{canonname} 将是表示 @emph{host} 规范名称的字符串；否则 @emph{canonname} 将为空。 @emph{sockaddr} 是一个描述套接字地址的元组，其具体格式取决于返回的 @emph{family} (对于 @ref{f76,,AF_INET} 为 @code{(address, port)} 2 元组，对于 @ref{f77,,AF_INET6} 则为 @code{(address, port, flowinfo, scope_id)} 4 元组)，其作用是被传入 @ref{773,,socket.connect()} 方法。

引发一个 @ref{fec,,审计事件} @code{socket.getaddrinfo} 附带参数 @code{host}、@code{port}、@code{family}、@code{type}、@code{protocol}。

下面的示例获取了 TCP 连接地址信息，假设该连接通过 80 端口连接至 @code{example.org} （如果系统未启用 IPv6，则结果可能会不同）:

@example
>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
 6, '@w{'}, ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
 (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
 6, '@w{'}, ('93.184.216.34', 80))]
@end example


在 3.2 版更改: 现在可以使用关键字参数的形式来传递参数。



在 3.7 版更改: 对于 IPv6 多播地址，表示地址的字符串将不包含 @code{%scope_id} 部分。

@end deffn

@geindex getfqdn() (在 socket 模块中)
@anchor{library/socket socket getfqdn}@anchor{27eb}
@deffn {函数} socket.getfqdn ([name])

返回 @emph{name} 的完整限定域名。 如果 @emph{name} 被省略或为空，则将其解读为本地主机。 要查找完整限定名称，将先检查 @ref{ff8,,gethostbyaddr()} 所返回的主机名，然后是主机的别名（如果存在）。 包括句点的第一个名称将会被选择。 对于没有完整限定域名而提供了 @emph{name} 的情况，则会将其原样返回。 如果 @emph{name} 为空或等于 @code{'0.0.0.0'}，则返回来自 @ref{2095,,gethostname()} 的主机名。
@end deffn

@geindex gethostbyname() (在 socket 模块中)
@anchor{library/socket socket gethostbyname}@anchor{27ec}
@deffn {函数} socket.gethostbyname (hostname)

将主机名转换为 IPv4 地址格式。IPv4 地址以字符串格式返回，如 @code{'100.50.200.5'}。如果主机名本身是 IPv4 地址，则原样返回。更完整的接口请参考 @ref{ff9,,gethostbyname_ex()}。 @ref{27ec,,gethostbyname()} 不支持 IPv6 名称解析，应使用 @ref{271f,,getaddrinfo()} 来支持 IPv4/v6 双协议栈。

引发一个 @ref{fec,,审计事件} @code{socket.gethostbyname}，附带参数 @code{hostname}。
@end deffn

@geindex gethostbyname_ex() (在 socket 模块中)
@anchor{library/socket socket gethostbyname_ex}@anchor{ff9}
@deffn {函数} socket.gethostbyname_ex (hostname)

将一个主机名转换为 IPv4 地址格式的扩展接口。 返回一个三元组 @code{(hostname, aliaslist, ipaddrlist)} 其中 @emph{hostname} 是主机的首选主机名，@emph{aliaslist} 是同一地址的其他主机名的列表（可能为空），而 @emph{ipaddrlist} 是同一主机上同一接口的 IPv4 地址列表（通常为单个地址但并不总是如此）。 @ref{ff9,,gethostbyname_ex()} 不支持 IPv6 名称解析，应当改用 @ref{271f,,getaddrinfo()} 来提供 IPv4/v6 双栈支持。

引发一个 @ref{fec,,审计事件} @code{socket.gethostbyname}，附带参数 @code{hostname}。
@end deffn

@geindex gethostname() (在 socket 模块中)
@anchor{library/socket socket gethostname}@anchor{2095}
@deffn {函数} socket.gethostname ()

返回一个字符串，包含当前正在运行 Python 解释器的机器的主机名。

引发一个 @ref{fec,,审计事件} @code{socket.gethostname}，没有附带参数。

注意： @ref{2095,,gethostname()} 并不总是返回全限定域名，必要的话请使用 @ref{27eb,,getfqdn()}。
@end deffn

@geindex gethostbyaddr() (在 socket 模块中)
@anchor{library/socket socket gethostbyaddr}@anchor{ff8}
@deffn {函数} socket.gethostbyaddr (ip_address)

返回三元组 @code{(hostname, aliaslist, ipaddrlist)}，其中 @emph{hostname} 是响应给定 @emph{ip_address} 的主要主机名，@emph{aliaslist} 是相同地址的其他可用主机名的列表（可能为空），而 @emph{ipaddrlist} 是 IPv4/v6 地址列表，包含相同主机名、相同接口的不同地址（很可能仅包含一个地址）。要查询全限定域名，请使用函数 @ref{27eb,,getfqdn()}。@ref{ff8,,gethostbyaddr()} 支持 IPv4 和 IPv6。

引发一个 @ref{fec,,审计事件} @code{socket.gethostbyaddr}，附带参数 @code{ip_address}。
@end deffn

@geindex getnameinfo() (在 socket 模块中)
@anchor{library/socket socket getnameinfo}@anchor{2720}
@deffn {函数} socket.getnameinfo (sockaddr, flags)

将套接字地址 @emph{sockaddr} 转换为二元组 @code{(host, port)}。@emph{host} 的形式可能是全限定域名，或是由数字表示的地址，具体取决于 @emph{flags} 的设置。同样，@emph{port} 可以包含字符串格式的端口名称或数字格式的端口号。

对于 IPv6 地址，如果 @emph{sockaddr} 包含有意义的 @emph{scope_id}，则 @code{%scope_id} 会被附加到主机部分。 这种情况通常发生在多播地址上。

关于 @emph{flags} 的更多信息可参阅 @code{getnameinfo(3)}。

引发一个 @ref{fec,,审计事件} @code{socket.getnameinfo}，附带参数 @code{sockaddr}。
@end deffn

@geindex getprotobyname() (在 socket 模块中)
@anchor{library/socket socket getprotobyname}@anchor{27ed}
@deffn {函数} socket.getprotobyname (protocolname)

将 Internet 协议名称（如 @code{'icmp'} ）转换为常量，该常量适用于 @code{socket()} 函数的第三个（可选）参数。通常只有在 "raw" 模式 (@ref{27d2,,SOCK_RAW}) 中打开的套接字才需要使用该常量。在正常的套接字模式下，协议省略或为零时，会自动选择正确的协议。
@end deffn

@geindex getservbyname() (在 socket 模块中)
@anchor{library/socket socket getservbyname}@anchor{27ee}
@deffn {函数} socket.getservbyname (servicename[, protocolname])

将 Internet 服务名称和协议名称转换为该服务的端口号。协议名称是可选的，如果提供的话应为 @code{'tcp'} 或 @code{'udp'}，否则将匹配出所有协议。

引发一个 @ref{fec,,审计事件} @code{socket.getservbyname}，附带参数 @code{servicename}、@code{protocolname}。
@end deffn

@geindex getservbyport() (在 socket 模块中)
@anchor{library/socket socket getservbyport}@anchor{27ef}
@deffn {函数} socket.getservbyport (port[, protocolname])

将 Internet 端口号和协议名称转换为该服务的服务名称。协议名称是可选的，如果提供的话应为 @code{'tcp'} 或 @code{'udp'}，否则将匹配出所有协议。

引发一个 @ref{fec,,审计事件} @code{socket.getservbyport}，附带参数 @code{port}、@code{protocolname}。
@end deffn

@geindex ntohl() (在 socket 模块中)
@anchor{library/socket socket ntohl}@anchor{27f0}
@deffn {函数} socket.ntohl (x)

将 32 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。
@end deffn

@geindex ntohs() (在 socket 模块中)
@anchor{library/socket socket ntohs}@anchor{577}
@deffn {函数} socket.ntohs (x)

将 16 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。


3.7 版后已移除: 如果 @emph{x} 不符合 16 位无符号整数，但符合 C 语言的正整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未来版本的 Python 将对此抛出异常。

@end deffn

@geindex htonl() (在 socket 模块中)
@anchor{library/socket socket htonl}@anchor{27f1}
@deffn {函数} socket.htonl (x)

将 32 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。
@end deffn

@geindex htons() (在 socket 模块中)
@anchor{library/socket socket htons}@anchor{576}
@deffn {函数} socket.htons (x)

将 16 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。


3.7 版后已移除: 如果 @emph{x} 不符合 16 位无符号整数，但符合 C 语言的正整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未来版本的 Python 将对此抛出异常。

@end deffn

@geindex inet_aton() (在 socket 模块中)
@anchor{library/socket socket inet_aton}@anchor{237}
@deffn {函数} socket.inet_aton (ip_string)

将 IPv4 地址从点分十进制字符串格式（如 '123.45.67.89' ）转换为 32 位压缩二进制格式，转换后为字节对象，长度为四个字符。与那些使用标准 C 库，且需要 @code{struct in_addr} 类型的对象的程序交换信息时，本函数很有用。 该类型即本函数返回的 32 位压缩二进制的 C 类型。

@ref{237,,inet_aton()} 也接受句点数少于三的字符串，详情请参阅 Unix 手册 @code{inet(3)}。

如果传入本函数的 IPv4 地址字符串无效，则抛出 @ref{30b,,OSError}。注意，具体什么样的地址有效取决于 @code{inet_aton()} 的底层 C 实现。

@ref{237,,inet_aton()} 不支持 IPv6，在 IPv4/v6 双协议栈下应使用 @ref{238,,inet_pton()} 来代替。
@end deffn

@geindex inet_ntoa() (在 socket 模块中)
@anchor{library/socket socket inet_ntoa}@anchor{27f2}
@deffn {函数} socket.inet_ntoa (packed_ip)

将 32 位压缩 IPv4 地址（一个 @ref{6e9,,类字节对象}，长 4 个字节）转换为标准的点分十进制字符串形式（如 '123.45.67.89' ）。与那些使用标准 C 库，且需要 @code{struct in_addr} 类型的对象的程序交换信息时，本函数很有用。 该类型即本函数参数中的 32 位压缩二进制数据的 C 类型。

如果传入本函数的字节序列长度不是 4 个字节，则抛出 @ref{30b,,OSError}。@ref{27f2,,inet_ntoa()} 不支持 IPv6，在 IPv4/v6 双协议栈下应使用 @ref{9ab,,inet_ntop()} 来代替。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn

@geindex inet_pton() (在 socket 模块中)
@anchor{library/socket socket inet_pton}@anchor{238}
@deffn {函数} socket.inet_pton (address_family, ip_string)

将特定地址簇的 IP 地址（字符串）转换为压缩二进制格式。当库或网络协议需要接受 @code{struct in_addr} 类型的对象（类似 @ref{237,,inet_aton()} ）或 @code{struct in6_addr} 类型的对象时，@ref{238,,inet_pton()} 很有用。

目前 @emph{address_family} 支持 @ref{f76,,AF_INET} 和 @ref{f77,,AF_INET6}。如果 IP 地址字符串 @emph{ip_string} 无效，则抛出 @ref{30b,,OSError}。注意，具体什么地址有效取决于 @emph{address_family} 的值和 @code{inet_pton()} 的底层实现。

@ref{14c1,,可用性}： Unix（可能非所有平台都可用）、Windows。


在 3.4 版更改: 添加了 Windows 支持

@end deffn

@geindex inet_ntop() (在 socket 模块中)
@anchor{library/socket socket inet_ntop}@anchor{9ab}
@deffn {函数} socket.inet_ntop (address_family, packed_ip)

将压缩 IP 地址（一个 @ref{6e9,,类字节对象}，数个字节长）转换为标准的、特定地址簇的字符串形式（如 @code{'7.10.0.5'} 或 @code{'5aef:2b::8'} ）。当库或网络协议返回 @code{struct in_addr} 类型的对象（类似 @ref{27f2,,inet_ntoa()} ）或 @code{struct in6_addr} 类型的对象时，@ref{9ab,,inet_ntop()} 很有用。

目前 @emph{address_family} 支持 @ref{f76,,AF_INET} 和 @ref{f77,,AF_INET6}。如果字节对象 @emph{packed_ip} 与指定的地址簇长度不符，则抛出 @ref{16d,,ValueError}。针对 @ref{9ab,,inet_ntop()} 调用的错误则抛出 @ref{30b,,OSError}。

@ref{14c1,,可用性}： Unix（可能非所有平台都可用）、Windows。


在 3.4 版更改: 添加了 Windows 支持



在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn

@c XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any
@c non-Unix platforms?  The old (obsolete?) 4.2BSD form of the
@c interface, in which struct msghdr has no msg_control or
@c msg_controllen members, is not currently supported.

@geindex CMSG_LEN() (在 socket 模块中)
@anchor{library/socket socket CMSG_LEN}@anchor{11a2}
@deffn {函数} socket.CMSG_LEN (length)

返回给定 @emph{length} 所关联数据的辅助数据项的总长度（不带尾部填充）。此值通常用作 @ref{776,,recvmsg()} 接收一个辅助数据项的缓冲区大小，但是 
@geindex RFC; RFC 3542
RFC 3542@footnote{https://tools.ietf.org/html/rfc3542.html} 要求可移植应用程序使用 @ref{11a1,,CMSG_SPACE()}，以此将尾部填充的空间计入，即使该项在缓冲区的最后。如果 @emph{length} 超出允许范围，则抛出 @ref{a4a,,OverflowError}。

@ref{14c1,,可用性}： 大多数 Unix 平台，其他平台也可能可用。


3.3 新版功能.

@end deffn

@geindex CMSG_SPACE() (在 socket 模块中)
@anchor{library/socket socket CMSG_SPACE}@anchor{11a1}
@deffn {函数} socket.CMSG_SPACE (length)

返回 @ref{776,,recvmsg()} 所需的缓冲区大小，以接收给定 @emph{length} 所关联数据的辅助数据项，带有尾部填充。接收多个项目所需的缓冲区空间是关联数据长度的 @ref{11a1,,CMSG_SPACE()} 值的总和。如果 @emph{length} 超出允许范围，则抛出 @ref{a4a,,OverflowError}。

请注意，某些系统可能支持辅助数据，但不提供本函数。还需注意，如果使用本函数的结果来设置缓冲区大小，可能无法精确限制可接收的辅助数据量，因为可能会有其他数据写入尾部填充区域。

@ref{14c1,,可用性}： 大多数 Unix 平台，其他平台也可能可用。


3.3 新版功能.

@end deffn

@geindex getdefaulttimeout() (在 socket 模块中)
@anchor{library/socket socket getdefaulttimeout}@anchor{27e8}
@deffn {函数} socket.getdefaulttimeout ()

返回用于新套接字对象的默认超时（以秒为单位的浮点数）。值 @code{None} 表示新套接字对象没有超时。首次导入 socket 模块时，默认值为 @code{None}。
@end deffn

@geindex setdefaulttimeout() (在 socket 模块中)
@anchor{library/socket socket setdefaulttimeout}@anchor{27d0}
@deffn {函数} socket.setdefaulttimeout (timeout)

设置用于新套接字对象的默认超时（以秒为单位的浮点数）。首次导入 socket 模块时，默认值为 @code{None}。可能的取值及其各自的含义请参阅 @ref{27cb,,settimeout()}。
@end deffn

@geindex sethostname() (在 socket 模块中)
@anchor{library/socket socket sethostname}@anchor{b68}
@deffn {函数} socket.sethostname (name)

将计算机的主机名设置为 @emph{name}。如果权限不足将抛出 @ref{30b,,OSError}。

引发一个 @ref{fec,,审计事件} @code{socket.sethostname}，附带参数 @code{name}。

@ref{14c1,,Availability}: Unix.


3.3 新版功能.

@end deffn

@geindex if_nameindex() (在 socket 模块中)
@anchor{library/socket socket if_nameindex}@anchor{354}
@deffn {函数} socket.if_nameindex ()

返回一个列表，包含网络接口（网卡）信息二元组（整数索引，名称字符串）。系统调用失败则抛出 @ref{30b,,OSError}。

@ref{14c1,,可用性}: Unix, Windows。


3.3 新版功能.



在 3.8 版更改: 添加了 Windows 支持。


@cartouche
@quotation 注解 
在 Windows 中网络接口在不同上下文中具有不同的名称（所有名称见对应示例）:


@itemize *

@item 
UUID: @code{@{FB605B73-AAC2-49A6-9A2F-25416AEA0573@}}

@item 
名称: @code{ethernet_32770}

@item 
友好名称: @code{vEthernet (nat)}

@item 
描述: @code{Hyper-V Virtual Ethernet Adapter}
@end itemize

此函数返回列表中第二种形式的名称，在此示例中为 @code{ethernet_32770}。
@end quotation
@end cartouche
@end deffn

@geindex if_nametoindex() (在 socket 模块中)
@anchor{library/socket socket if_nametoindex}@anchor{355}
@deffn {函数} socket.if_nametoindex (if_name)

返回网络接口名称相对应的索引号。如果没有所给名称的接口，则抛出 @ref{30b,,OSError}。

@ref{14c1,,可用性}: Unix, Windows。


3.3 新版功能.



在 3.8 版更改: 添加了 Windows 支持。



@subsubheading 参见


"Interface name" 为 @ref{354,,if_nameindex()} 中所描述的名称。

@end deffn

@geindex if_indextoname() (在 socket 模块中)
@anchor{library/socket socket if_indextoname}@anchor{356}
@deffn {函数} socket.if_indextoname (if_index)

返回网络接口索引号相对应的接口名称。如果没有所给索引号的接口，则抛出 @ref{30b,,OSError}。

@ref{14c1,,可用性}: Unix, Windows。


3.3 新版功能.



在 3.8 版更改: 添加了 Windows 支持。



@subsubheading 参见


"Interface name" 为 @ref{354,,if_nameindex()} 中所描述的名称。

@end deffn

@geindex send_fds() (在 socket 模块中)
@anchor{library/socket socket send_fds}@anchor{1e5}
@deffn {函数} socket.send_fds (sock, buffers, fds[, flags[, address]])

将文件描述符列表 @emph{fds} 通过一个 @ref{f78,,AF_UNIX} 套接字 @emph{sock} 进行发送。 @emph{fds} 形参是由文件描述符构成的序列。 请查看 @code{sendmsg()} 获取这些形参的文档。

@ref{14c1,,可用性}: 支持 @ref{779,,sendmsg()} 和 @code{SCM_RIGHTS} 机制的 Unix 系统。


3.9 新版功能.

@end deffn

@geindex recv_fds() (在 socket 模块中)
@anchor{library/socket socket recv_fds}@anchor{1e6}
@deffn {函数} socket.recv_fds (sock, bufsize, maxfds[, flags])

接收至多 @emph{maxfds} 个来自 @ref{f78,,AF_UNIX} 套接字 @emph{sock} 的文件描述符。 返回 @code{(msg, list(fds), flags, addr)}。 请查看 @code{recvmsg()} 获取有些形参的文档。

@ref{14c1,,可用性}: 支持 @ref{776,,recvmsg()} 和 @code{SCM_RIGHTS} 机制的 Unix 系统。


3.9 新版功能.


@cartouche
@quotation 注解 
位于文件描述符列表末尾的任何被截断整数。
@end quotation
@end cartouche
@end deffn

@node 套接字对象,关于套接字超时的说明,模块内容<4>,socket --- 底层网络接口
@anchor{library/socket id1}@anchor{27f3}@anchor{library/socket socket-objects}@anchor{27e6}
@subsubsection 套接字对象


套接字对象具有以下方法。除了 @ref{bf5,,makefile()}，其他都与套接字专用的 Unix 系统调用相对应。


在 3.2 版更改: 添加了对 @ref{66b,,上下文管理器} 协议的支持。退出上下文管理器与调用 @ref{4e0,,close()} 等效。


@geindex accept() (socket.socket 方法)
@anchor{library/socket socket socket accept}@anchor{772}
@deffn {方法} socket.accept ()

接受一个连接。此 socket 必须绑定到一个地址上并且监听连接。返回值是一个 @code{(conn, address)} 对，其中 @emph{conn} 是一个 @emph{新} 的套接字对象，用于在此连接上收发数据，@emph{address} 是连接另一端的套接字所绑定的地址。

新创建的套接字是 @ref{8f1,,不可继承的}。


在 3.4 版更改: 该套接字现在是不可继承的。



在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex bind() (socket.socket 方法)
@anchor{library/socket socket socket bind}@anchor{27f4}
@deffn {方法} socket.bind (address)

将套接字绑定到 @emph{address}。套接字必须尚未绑定。（ @emph{address} 的格式取决于地址簇 —— 参见上文）

引发一个 @ref{fec,,审计事件} @code{socket.bind}，附带参数 @code{self}、@code{address}。
@end deffn

@geindex close() (socket.socket 方法)
@anchor{library/socket socket socket close}@anchor{701}
@deffn {方法} socket.close ()

将套接字标记为关闭。当 @ref{bf5,,makefile()} 创建的所有文件对象都关闭时，底层系统资源（如文件描述符）也将关闭。一旦上述情况发生，将来对套接字对象的所有操作都会失败。对端将接收不到任何数据（清空队列数据后）。

垃圾回收时，套接字会自动关闭，但建议显式 @ref{4e0,,close()} 它们，或在它们周围使用 @ref{7e4,,with} 语句。


在 3.6 版更改: 现在，如果底层的 @code{close()} 调用出错，会抛出 @ref{30b,,OSError}。


@cartouche
@quotation 注解 
@ref{4e0,,close()} 释放与连接相关联的资源，但不一定立即关闭连接。如果需要及时关闭连接，请在调用 @ref{4e0,,close()} 之前调用 @ref{27f5,,shutdown()}。
@end quotation
@end cartouche
@end deffn

@geindex connect() (socket.socket 方法)
@anchor{library/socket socket socket connect}@anchor{773}
@deffn {方法} socket.connect (address)

连接到 @emph{address} 处的远程套接字。（ @emph{address} 的格式取决于地址簇 —— 参见上文）

如果连接被信号中断，则本方法将等待，直到连接完成。如果信号处理程序未抛出异常，且套接字阻塞中或已超时，则在超时后抛出 @ref{ce1,,socket.timeout}。对于非阻塞套接字，如果连接被信号中断，则本方法将抛出 @ref{756,,InterruptedError} 异常（或信号处理程序抛出的异常）。

引发一个 @ref{fec,,审计事件} @code{socket.connect}，附带参数 @code{self}、@code{address}。


在 3.5 版更改: 本方法现在将等待，直到连接完成，而不是在以下情况抛出 @ref{756,,InterruptedError} 异常。该情况为，连接被信号中断，信号处理程序未抛出异常，且套接字阻塞中或已超时（具体解释请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} ）。

@end deffn

@geindex connect_ex() (socket.socket 方法)
@anchor{library/socket socket socket connect_ex}@anchor{27f6}
@deffn {方法} socket.connect_ex (address)

类似于 @code{connect(address)}，但是对于 C 级别的 @code{connect()} 调用返回的错误，本函数将返回错误指示器，而不是抛出异常（对于其他问题，如“找不到主机”，仍然可以抛出异常）。如果操作成功，则错误指示器为 @code{0}，否则为 @code{errno} 变量的值。这对支持如异步连接很有用。

引发一个 @ref{fec,,审计事件} @code{socket.connect}，附带参数 @code{self}、@code{address}。
@end deffn

@geindex detach() (socket.socket 方法)
@anchor{library/socket socket socket detach}@anchor{c76}
@deffn {方法} socket.detach ()

将套接字对象置于关闭状态，而底层的文件描述符实际并不关闭。返回该文件描述符，使其可以重新用于其他目的。


3.2 新版功能.

@end deffn

@geindex dup() (socket.socket 方法)
@anchor{library/socket socket socket dup}@anchor{27f7}
@deffn {方法} socket.dup ()

创建套接字的副本。

新创建的套接字是 @ref{8f1,,不可继承的}。


在 3.4 版更改: 该套接字现在是不可继承的。

@end deffn

@geindex fileno() (socket.socket 方法)
@anchor{library/socket socket socket fileno}@anchor{27f8}
@deffn {方法} socket.fileno ()

返回套接字的文件描述符（一个小整数），失败返回 -1。配合 @ref{770,,select.select()} 使用很有用。

在 Windows 下，此方法返回的小整数在允许使用文件描述符的地方无法使用（如 @ref{1593,,os.fdopen()} ）。Unix 无此限制。
@end deffn

@geindex get_inheritable() (socket.socket 方法)
@anchor{library/socket socket socket get_inheritable}@anchor{8f6}
@deffn {方法} socket.get_inheritable ()

获取套接字文件描述符或套接字句柄的 @ref{8f1,,可继承标志} ：如果子进程可以继承套接字则为 @code{True}，否则为 @code{False}。


3.4 新版功能.

@end deffn

@geindex getpeername() (socket.socket 方法)
@anchor{library/socket socket socket getpeername}@anchor{2753}
@deffn {方法} socket.getpeername ()

返回套接字连接到的远程地址。举例而言，这可以用于查找远程 IPv4/v6 套接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）部分系统不支持此函数。
@end deffn

@geindex getsockname() (socket.socket 方法)
@anchor{library/socket socket socket getsockname}@anchor{2754}
@deffn {方法} socket.getsockname ()

返回套接字本身的地址。举例而言，这可以用于查找 IPv4/v6 套接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）
@end deffn

@geindex getsockopt() (socket.socket 方法)
@anchor{library/socket socket socket getsockopt}@anchor{683}
@deffn {方法} socket.getsockopt (level, optname[, buflen])

返回指定套接字选项的值（参阅 Unix 手册页 @code{getsockopt(2)} ）。所需的符号常量（ @code{SO_*} 等）已定义在本模块中。如果未指定 @emph{buflen}，则认为该选项值为整数，由本函数返回该整数值。如果指定 @emph{buflen}，则它定义了用于存放选项值的缓冲区的最大长度，且该缓冲区将作为字节对象返回。对缓冲区的解码工作由调用者自行完成（针对编码为字节串的 C 结构，其解码方法请参阅可选的内置模块 @ref{f8,,struct} ）。
@end deffn

@geindex getblocking() (socket.socket 方法)
@anchor{library/socket socket socket getblocking}@anchor{4df}
@deffn {方法} socket.getblocking ()

如果套接字处于阻塞模式，返回 @code{True}，非阻塞模式返回 @code{False}。

这相当于检测 @code{socket.gettimeout() == 0}。


3.7 新版功能.

@end deffn

@geindex gettimeout() (socket.socket 方法)
@anchor{library/socket socket socket gettimeout}@anchor{27f9}
@deffn {方法} socket.gettimeout ()

返回套接字操作相关的超时秒数（浮点数），未设置超时则返回 @code{None}。它反映最后一次调用 @ref{20a0,,setblocking()} 或 @ref{27cb,,settimeout()} 后的设置。
@end deffn

@geindex ioctl() (socket.socket 方法)
@anchor{library/socket socket socket ioctl}@anchor{681}
@deffn {方法} socket.ioctl (control, option)

@*平台: 
Windows


@ref{681,,ioctl()} 方法是 WSAIoctl 系统接口的有限接口。请参考 Win32 文档@footnote{https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx} 以获取更多信息。

在其他平台上，可以使用通用的 @ref{27fa,,fcntl.fcntl()} 和 @ref{eaa,,fcntl.ioctl()} 函数，它们接受套接字对象作为第一个参数。

当前仅支持以下控制码： @code{SIO_RCVALL}、@code{SIO_KEEPALIVE_VALS} 和 @code{SIO_LOOPBACK_FAST_PATH}。


在 3.6 版更改: 添加了 @code{SIO_LOOPBACK_FAST_PATH}。

@end deffn

@geindex listen() (socket.socket 方法)
@anchor{library/socket socket socket listen}@anchor{844}
@deffn {方法} socket.listen ([backlog])

启动一个服务器用于接受连接。如果指定 @emph{backlog}，则它最低为 0（小于 0 会被置为 0），它指定系统允许暂未 accept 的连接数，超过后将拒绝新连接。未指定则自动设为合理的默认值。


在 3.5 版更改: @emph{backlog} 参数现在是可选的。

@end deffn

@geindex makefile() (socket.socket 方法)
@anchor{library/socket socket socket makefile}@anchor{bf5}
@deffn {方法} socket.makefile (mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

@geindex I/O control; buffering

返回与套接字关联的 @ref{c1d,,文件对象}。返回的对象的具体类型取决于 @ref{bf5,,makefile()} 的参数。这些参数的解释方式与内置的 @ref{16f,,open()} 函数相同，其中 @emph{mode} 的值仅支持 @code{'r'} （默认），@code{'w'} 和 @code{'b'}。

套接字必须处于阻塞模式，它可以有超时，但是如果发生超时，文件对象的内部缓冲区可能会以不一致的状态结尾。

关闭 @ref{bf5,,makefile()} 返回的文件对象不会关闭原始套接字，除非所有其他文件对象都已关闭且在套接字对象上调用了 @ref{4e0,,socket.close()}。

@cartouche
@quotation 注解 
在 Windows 上，由 @ref{bf5,,makefile()} 创建的文件类对象无法作为带文件描述符的文件对象使用，如无法作为 @ref{3e3,,subprocess.Popen()} 的流参数。
@end quotation
@end cartouche
@end deffn

@geindex recv() (socket.socket 方法)
@anchor{library/socket socket socket recv}@anchor{774}
@deffn {方法} socket.recv (bufsize[, flags])

从套接字接收数据。返回值是一个字节对象，表示接收到的数据。@emph{bufsize} 指定一次接收的最大数据量。可选参数 @emph{flags} 的含义请参阅 Unix 手册页 @code{recv(2)}，它默认为零。

@cartouche
@quotation 注解 
为了最佳匹配硬件和网络的实际情况，@emph{bufsize} 的值应为 2 的相对较小的幂，如 4096。
@end quotation
@end cartouche


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex recvfrom() (socket.socket 方法)
@anchor{library/socket socket socket recvfrom}@anchor{775}
@deffn {方法} socket.recvfrom (bufsize[, flags])

从套接字接收数据。返回值是一对 @code{(bytes, address)}，其中 @emph{bytes} 是字节对象，表示接收到的数据，@emph{address} 是发送端套接字的地址。可选参数 @emph{flags} 的含义请参阅 Unix 手册页 @code{recv(2)}，它默认为零。（ @emph{address} 的格式取决于地址簇 —— 参见上文）


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。



在 3.7 版更改: 对于多播 IPv6 地址，@emph{address} 的第一项不会再包含 @code{%scope_id} 部分。 要获得完整的 IPv6 地址请使用 @ref{2720,,getnameinfo()}。

@end deffn

@geindex recvmsg() (socket.socket 方法)
@anchor{library/socket socket socket recvmsg}@anchor{776}
@deffn {方法} socket.recvmsg (bufsize[, ancbufsize[, flags]])

从套接字接收普通数据（至多 @emph{bufsize} 字节）和辅助数据。@emph{ancbufsize} 参数设置用于接收辅助数据的内部缓冲区的大小（以字节为单位），默认为 0，表示不接收辅助数据。可以使用 @ref{11a1,,CMSG_SPACE()} 或 @ref{11a2,,CMSG_LEN()} 计算辅助数据缓冲区的合适大小，无法放入缓冲区的项目可能会被截断或丢弃。@emph{flags} 参数默认为 0，其含义与 @ref{774,,recv()} 中的相同。

返回值是一个四元组： @code{(data, ancdata, msg_flags, address)}。@emph{data} 项是一个 @ref{172,,bytes} 对象，用于保存接收到的非辅助数据。@emph{ancdata} 项是零个或多个元组 @code{(cmsg_level, cmsg_type, cmsg_data)} 组成的列表，表示接收到的辅助数据（控制消息）：@emph{cmsg_level} 和 @emph{cmsg_type} 是分别表示协议级别和协议类型的整数，而 @emph{cmsg_data} 是保存相关数据的 @ref{172,,bytes} 对象。@emph{msg_flags} 项由各种标志按位或组成，表示接收消息的情况，详细信息请参阅系统文档。如果接收端套接字断开连接，则 @emph{address} 是发送端套接字的地址（如果有），否则该值无指定。

某些系统上可以利用 @ref{f78,,AF_UNIX} 套接字通过 @ref{779,,sendmsg()} 和 @ref{776,,recvmsg()} 在进程之间传递文件描述符。使用此功能时（通常仅限于 @ref{d5a,,SOCK_STREAM} 套接字），@ref{776,,recvmsg()} 将在其辅助数据中返回以下格式的项 @code{(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)}，其中 @emph{fds} 是一个 @ref{172,,bytes} 对象，是新文件描述符表示为原生 C @code{int} 类型的二进制数组。如果 @ref{776,,recvmsg()} 在系统调用返回后抛出异常，它将首先关闭此机制接收到的所有文件描述符。

对于仅接收到一部分的辅助数据项，一些系统没有指示其截断长度。如果某个项目可能超出了缓冲区的末尾，@ref{776,,recvmsg()} 将发出 @ref{3ea,,RuntimeWarning}，并返回其在缓冲区内的部分，前提是该对象被截断于关联数据开始后。

在支持 @code{SCM_RIGHTS} 机制的系统上，下方的函数将最多接收 @emph{maxfds} 个文件描述符，返回消息数据和包含描述符的列表（同时忽略意外情况，如接收到无关的控制消息）。另请参阅 @ref{779,,sendmsg()}。

@example
import socket, array

def recv_fds(sock, msglen, maxfds):
    fds = array.array("i")   # Array of ints
    msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
            # Append data, ignoring any truncated integers at the end.
            fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
    return msg, list(fds)
@end example

@ref{14c1,,可用性}： 大多数 Unix 平台，其他平台也可能可用。


3.3 新版功能.



在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex recvmsg_into() (socket.socket 方法)
@anchor{library/socket socket socket recvmsg_into}@anchor{b67}
@deffn {方法} socket.recvmsg_into (buffers[, ancbufsize[, flags]])

从套接字接收普通数据和辅助数据，其行为与 @ref{776,,recvmsg()} 相同，但将非辅助数据分散到一系列缓冲区中，而不是返回新的字节对象。@emph{buffers} 参数必须是可迭代对象，它迭代出可供写入的缓冲区（如 @ref{173,,bytearray} 对象），这些缓冲区将被连续的非辅助数据块填充，直到数据全部写完或缓冲区用完为止。在允许使用的缓冲区数量上，操作系统可能会有限制（ @ref{20c5,,sysconf()} 的 @code{SC_IOV_MAX} 值）。@emph{ancbufsize} 和 @emph{flags} 参数的含义与 @ref{776,,recvmsg()} 中的相同。

返回值为四元组： @code{(nbytes, ancdata, msg_flags, address)}，其中 @emph{nbytes} 是写入缓冲区的非辅助数据的字节总数，而 @emph{ancdata}、@emph{msg_flags} 和 @emph{address} 与 @ref{776,,recvmsg()} 中的相同。

示例:

@example
>>> import socket
>>> s1, s2 = socket.socketpair()
>>> b1 = bytearray(b'----')
>>> b2 = bytearray(b'0123456789')
>>> b3 = bytearray(b'--------------')
>>> s1.send(b'Mary had a little lamb')
22
>>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
(22, [], 0, None)
>>> [b1, b2, b3]
[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
@end example

@ref{14c1,,可用性}： 大多数 Unix 平台，其他平台也可能可用。


3.3 新版功能.

@end deffn

@geindex recvfrom_into() (socket.socket 方法)
@anchor{library/socket socket socket recvfrom_into}@anchor{d83}
@deffn {方法} socket.recvfrom_into (buffer[, nbytes[, flags]])

从套接字接收数据，将其写入 @emph{buffer} 而不是创建新的字节串。返回值是一对 @code{(nbytes, address)}，其中 @emph{nbytes} 是收到的字节数，@emph{address} 是发送端套接字的地址。可选参数 @emph{flags} 的含义请参阅 Unix 手册页 @code{recv(2)}，它默认为零。（ @emph{address} 的格式取决于地址簇 —— 参见上文）
@end deffn

@geindex recv_into() (socket.socket 方法)
@anchor{library/socket socket socket recv_into}@anchor{d82}
@deffn {方法} socket.recv_into (buffer[, nbytes[, flags]])

从套接字接收至多 @emph{nbytes} 个字节，将其写入缓冲区而不是创建新的字节串。如果 @emph{nbytes} 未指定（或指定为 0），则接收至所给缓冲区的最大可用大小。返回接收到的字节数。可选参数 @emph{flags} 的含义请参阅 Unix 手册页 @code{recv(2)}，它默认为零。
@end deffn

@geindex send() (socket.socket 方法)
@anchor{library/socket socket socket send}@anchor{777}
@deffn {方法} socket.send (bytes[, flags])

发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 @emph{flags} 的含义与上述 @ref{774,,recv()} 中的相同。本方法返回已发送的字节数。应用程序要负责检查所有数据是否已发送，如果仅传输了部分数据，程序需要自行尝试传输其余数据。有关该主题的更多信息，请参考 @ref{27fb,,套接字编程指南}。


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex sendall() (socket.socket 方法)
@anchor{library/socket socket socket sendall}@anchor{778}
@deffn {方法} socket.sendall (bytes[, flags])

发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 @emph{flags} 的含义与上述 @ref{774,,recv()} 中的相同。与 @ref{777,,send()} 不同，本方法持续从 @emph{bytes} 发送数据，直到所有数据都已发送或发生错误为止。成功后会返回 @code{None}。出错后会抛出一个异常，此时并没有办法确定成功发送了多少数据。


在 3.5 版更改: 每次成功发送数据后，套接字超时不再重置。现在，套接字超时是发送所有数据的最大总持续时间。



在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex sendto() (socket.socket 方法)
@anchor{library/socket socket socket sendto}@anchor{77a}
@deffn {方法} socket.sendto (bytes, address)

@deffnx {方法} socket.sendto (bytes, flags, address)

发送数据给套接字。本套接字不应连接到远程套接字，而应由 @emph{address} 指定目标套接字。可选参数 @emph{flags} 的含义与上述 @ref{774,,recv()} 中的相同。本方法返回已发送的字节数。（ @emph{address} 的格式取决于地址簇 —— 参见上文。）

引发一个 @ref{fec,,审计事件} @code{socket.sendto}，附带参数 @code{self}、@code{address}。


在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex sendmsg() (socket.socket 方法)
@anchor{library/socket socket socket sendmsg}@anchor{779}
@deffn {方法} socket.sendmsg (buffers[, ancdata[, flags[, address]]])

将普通数据和辅助数据发送给套接字，将从一系列缓冲区中收集非辅助数据，并将其拼接为一条消息。@emph{buffers} 参数指定的非辅助数据应为可迭代的 @ref{6e9,,字节类对象} （如 @ref{172,,bytes} 对象），在允许使用的缓冲区数量上，操作系统可能会有限制（ @ref{20c5,,sysconf()} 的 @code{SC_IOV_MAX} 值）。@emph{ancdata} 参数指定的辅助数据（控制消息）应为可迭代对象，迭代出零个或多个 @code{(cmsg_level, cmsg_type, cmsg_data)} 元组，其中 @emph{cmsg_level} 和 @emph{cmsg_type} 是分别指定协议级别和协议类型的整数，而 @emph{cmsg_data} 是保存相关数据的字节类对象。请注意，某些系统（特别是没有 @ref{11a1,,CMSG_SPACE()} 的系统）可能每次调用仅支持发送一条控制消息。@emph{flags} 参数默认为 0，与 @ref{777,,send()} 中的含义相同。如果 @emph{address} 指定为除 @code{None} 以外的值，它将作为消息的目标地址。返回值是已发送的非辅助数据的字节数。

在支持 @code{SCM_RIGHTS} 机制的系统上，下方的函数通过一个 @ref{f78,,AF_UNIX} 套接字来发送文件描述符列表 @emph{fds}。另请参阅 @ref{776,,recvmsg()}。

@example
import socket, array

def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
@end example

@ref{14c1,,可用性}： 大多数 Unix 平台，其他平台也可能可用。

引发一个 @ref{fec,,审计事件} @code{socket.sendmsg}，附带参数 @code{self}、@code{address}。


3.3 新版功能.



在 3.5 版更改: 如果系统调用被中断，但信号处理程序没有触发异常，此方法现在会重试系统调用，而不是触发 @ref{756,,InterruptedError} 异常 (原因详见 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475})。

@end deffn

@geindex sendmsg_afalg() (socket.socket 方法)
@anchor{library/socket socket socket sendmsg_afalg}@anchor{686}
@deffn {方法} socket.sendmsg_afalg ([msg], *, op[, iv[, assoclen[, flags]]])

为 @ref{685,,AF_ALG} 套接字定制的 @ref{779,,sendmsg()} 版本。可为 @ref{685,,AF_ALG} 套接字设置模式、IV、AEAD 关联数据的长度和标志位。

@ref{14c1,,可用性}： Linux >= 2.6.38。


3.6 新版功能.

@end deffn

@geindex sendfile() (socket.socket 方法)
@anchor{library/socket socket socket sendfile}@anchor{843}
@deffn {方法} socket.sendfile (file, offset=0, count=None)

使用高性能的 @ref{46a,,os.sendfile} 发送文件，直到达到文件的 EOF 为止，返回已发送的字节总数。@emph{file} 必须是一个以二进制模式打开的常规文件对象。如果 @ref{46a,,os.sendfile} 不可用（如 Windows）或 @emph{file} 不是常规文件，将使用 @ref{777,,send()} 代替。@emph{offset} 指示从哪里开始读取文件。如果指定了 @emph{count}，它确定了要发送的字节总数，而不会持续发送直到达到文件的 EOF。返回时或发生错误时，文件位置将更新，在这种情况下，@ref{1f40,,file.tell()} 可用于确定已发送的字节数。套接字必须为 @ref{d5a,,SOCK_STREAM} 类型。不支持非阻塞的套接字。


3.5 新版功能.

@end deffn

@geindex set_inheritable() (socket.socket 方法)
@anchor{library/socket socket socket set_inheritable}@anchor{8f7}
@deffn {方法} socket.set_inheritable (inheritable)

设置套接字文件描述符或套接字句柄的 @ref{8f1,,可继承标志}。


3.4 新版功能.

@end deffn

@geindex setblocking() (socket.socket 方法)
@anchor{library/socket socket socket setblocking}@anchor{20a0}
@deffn {方法} socket.setblocking (flag)

设置套接字为阻塞或非阻塞模式：如果 @emph{flag} 为 false，则将套接字设置为非阻塞，否则设置为阻塞。

本方法是某些 @ref{27cb,,settimeout()} 调用的简写：


@itemize *

@item 
@code{sock.setblocking(True)} 相当于 @code{sock.settimeout(None)}

@item 
@code{sock.setblocking(False)} 相当于 @code{sock.settimeout(0.0)}
@end itemize


在 3.7 版更改: 本方法不再对 @ref{59b,,socket.type} 属性设置 @ref{599,,SOCK_NONBLOCK} 标志。

@end deffn

@geindex settimeout() (socket.socket 方法)
@anchor{library/socket socket socket settimeout}@anchor{27cb}
@deffn {方法} socket.settimeout (value)

为阻塞套接字的操作设置超时。@emph{value} 参数可以是非负浮点数，表示秒，也可以是 @code{None}。如果赋为一个非零值，那么如果在操作完成前超过了超时时间 @emph{value}，后续的套接字操作将抛出 @ref{ce1,,timeout} 异常。如果赋为 0，则套接字将处于非阻塞模式。如果指定为 @code{None}，则套接字将处于阻塞模式。

更多信息请查阅 @ref{27fc,,关于套接字超时的说明}。


在 3.7 版更改: 本方法不再修改 @ref{59b,,socket.type} 属性的 @ref{599,,SOCK_NONBLOCK} 标志。

@end deffn

@geindex setsockopt() (socket.socket 方法)
@anchor{library/socket socket socket setsockopt}@anchor{684}
@deffn {方法} socket.setsockopt (level, optname, value: int)
@end deffn


@deffn {方法} socket.setsockopt (level, optname, value: buffer)
@end deffn


@deffn {方法} socket.setsockopt (level, optname, None, optlen: int)

@geindex 模块; struct

设置给定套接字选项的值（参阅 Unix 手册页 @code{setsockopt(2)} ）。所需的符号常量（ @code{SO_*} 等）已定义在本 @ref{ef,,socket} 模块中。该值可以是整数、@code{None} 或表示缓冲区的 @ref{6e9,,字节类对象}。在后一种情况下，由调用者确保字节串中包含正确的数据位（关于将 C 结构体编码为字节串的方法，请参阅可选的内置模块 @ref{f8,,struct} ）。当 @emph{value} 设置为 @code{None} 时，必须设置 @emph{optlen} 参数。这相当于调用 @code{setsockopt()} C 函数时使用了 @code{optval=NULL} 和 @code{optlen=optlen} 参数。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。



在 3.6 版更改: 添加了 setsockopt(level, optname, None, optlen: int) 调用形式。

@end deffn

@geindex shutdown() (socket.socket 方法)
@anchor{library/socket socket socket shutdown}@anchor{27f5}
@deffn {方法} socket.shutdown (how)

关闭一半或全部的连接。如果 @emph{how} 为 @code{SHUT_RD}，则后续不再允许接收。如果 @emph{how} 为 @code{SHUT_WR}，则后续不再允许发送。如果 @emph{how} 为 @code{SHUT_RDWR}，则后续的发送和接收都不允许。
@end deffn

@geindex share() (socket.socket 方法)
@anchor{library/socket socket socket share}@anchor{596}
@deffn {方法} socket.share (process_id)

复制套接字，并准备将其与目标进程共享。目标进程必须以 @emph{process_id} 形式提供。然后可以利用某种形式的进程间通信，将返回的字节对象传递给目标进程，还可以使用 @ref{597,,fromshare()} 在新进程中重新创建套接字。一旦本方法调用完毕，就可以安全地将套接字关闭，因为操作系统已经为目标进程复制了该套接字。

@ref{14c1,,可用性}: Windows。


3.3 新版功能.

@end deffn

注意此处没有 @code{read()} 或 @code{write()} 方法，请使用不带 @emph{flags} 参数的 @ref{774,,recv()} 和 @ref{777,,send()} 来替代。

套接字对象还具有以下（只读）属性，这些属性与传入 @ref{771,,socket} 构造函数的值相对应。

@geindex family (socket.socket 属性)
@anchor{library/socket socket socket family}@anchor{27fd}
@deffn {属性} socket.family

套接字的协议簇。
@end deffn

@geindex type (socket.socket 属性)
@anchor{library/socket socket socket type}@anchor{59b}
@deffn {属性} socket.type

套接字的类型。
@end deffn

@geindex proto (socket.socket 属性)
@anchor{library/socket socket socket proto}@anchor{27fe}
@deffn {属性} socket.proto

套接字的协议。
@end deffn

@node 关于套接字超时的说明,示例<23>,套接字对象,socket --- 底层网络接口
@anchor{library/socket notes-on-socket-timeouts}@anchor{27ff}@anchor{library/socket socket-timeouts}@anchor{27fc}
@subsubsection 关于套接字超时的说明


一个套接字对象可以处于以下三种模式之一：阻塞、非阻塞或超时。套接字默认以阻塞模式创建，但是可以调用 @ref{27d0,,setdefaulttimeout()} 来更改。


@itemize *

@item 
在 @emph{blocking mode} （阻塞模式）中，操作将阻塞，直到操作完成或系统返回错误（如连接超时）。

@item 
在 @emph{non-blocking mode} （非阻塞模式）中，如果操作无法立即完成，则操作将失败（不幸的是，不同系统返回的错误不同）：位于 @ref{e5,,select} 中的函数可用于了解套接字何时以及是否可以读取或写入。

@item 
在 @emph{timeout mode} （超时模式）下，如果无法在指定的超时内完成操作（抛出 @ref{ce1,,timeout} 异常），或如果系统返回错误，则操作将失败。
@end itemize

@cartouche
@quotation 注解 
在操作系统层面上，@emph{超时模式} 下的套接字在内部都设置为非阻塞模式。同时，阻塞和超时模式在文件描述符和套接字对象之间共享，这些描述符和对象均应指向同一个网络端点。如果，比如你决定使用套接字的 @ref{27f8,,fileno()}，这一实现细节可能导致明显的结果。
@end quotation
@end cartouche

@menu
* 超时与 connect 方法:: 
* 超时与 accept 方法:: 

@end menu

@node 超时与 connect 方法,超时与 accept 方法,,关于套接字超时的说明
@anchor{library/socket timeouts-and-the-connect-method}@anchor{2800}
@subsubsection 超时与 @code{connect} 方法


@ref{773,,connect()} 操作也受超时设置的约束，通常建议在调用 @ref{773,,connect()} 之前调用 @ref{27cb,,settimeout()}，或将超时参数直接传递给 @ref{c77,,create_connection()}。但是，无论 Python 套接字超时设置如何，系统网络栈都有可能返回自带的连接超时错误。

@node 超时与 accept 方法,,超时与 connect 方法,关于套接字超时的说明
@anchor{library/socket timeouts-and-the-accept-method}@anchor{2801}
@subsubsection 超时与 @code{accept} 方法


如果 @ref{27e8,,getdefaulttimeout()} 的值不是 @ref{204,,None}，则 @ref{772,,accept()} 方法返回的套接字将继承该超时值。若是 None，返回的套接字行为取决于侦听套接字的设置：


@itemize *

@item 
如果侦听套接字处于 @emph{阻塞模式} 或 @emph{超时模式}，则 @ref{772,,accept()} 返回的套接字处于 @emph{阻塞模式}；

@item 
如果侦听套接字处于 @emph{非阻塞模式}，那么 @ref{772,,accept()} 返回的套接字是阻塞还是非阻塞取决于操作系统。如果要确保跨平台时的正确行为，建议手动覆盖此设置。
@end itemize

@node 示例<23>,,关于套接字超时的说明,socket --- 底层网络接口
@anchor{library/socket example}@anchor{2802}@anchor{library/socket socket-example}@anchor{2803}
@subsubsection 示例


以下是 4 个使用 TCP/IP 协议的最小示例程序：一台服务器，它将收到的所有数据原样返回（仅服务于一个客户端），还有一个使用该服务器的客户端。注意，服务器必须按序执行 @code{socket()}, @ref{27f4,,bind()}, @ref{844,,listen()}, @ref{772,,accept()} （可能需要重复执行 @ref{772,,accept()} 以服务多个客户端），而客户端仅需要按序执行 @code{socket()}, @ref{773,,connect()}。还须注意，服务器不在侦听套接字上发送 @ref{778,,sendall()}/@ref{774,,recv()}，而是在 @ref{772,,accept()} 返回的新套接字上发送。

前两个示例仅支持 IPv4。

@example
# Echo server program
import socket

HOST = '@w{'}                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data: break
            conn.sendall(data)
@end example

@example
# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
@end example

下两个例子与上两个很像，但是同时支持 IPv4 和 IPv6。 服务端将监听第一个可用的地址族（它本应同时监听两个）。 在大多数支持 IPv6 的系统上，IPv6 将有优先权并且服务端可能不会接受 IPv4 流量。 客户端将尝试连接到作为名称解析结果被返回的所有地址，并将流量发送给连接成功的第一个地址。

@example
# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.bind(sa)
        s.listen(1)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)
@end example

@example
# Echo client program
import socket
import sys

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
with s:
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
@end example

下面的例子演示了如何在 Windows 上使用原始套接字编写一个非常简单的网络嗅探器。 这个例子需要管理员权限来修改接口:

@example
import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
print(s.recvfrom(65565))

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
@end example

下面的例子演示了如何使用 socket 接口与采用原始套接字协议的 CAN 网络进行通信。 要改为通过广播管理器协议来使用 CAN，则要用以下方式打开一个 socket:

@example
socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
@end example

在绑定 (@code{CAN_RAW}) 或连接 (@ref{9a9,,CAN_BCM}) socket 之后，你将可以在 socket 对象上正常使用 @ref{777,,socket.send()} 以及 @ref{774,,socket.recv()} 操作（及同类操作）。

最后一个例子可能需要特别的权限:

@example
import socket
import struct


# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)

can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)

def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)

def dissect_can_frame(frame):
    can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
    return (can_id, can_dlc, data[:can_dlc])


# create a raw socket and bind it to the 'vcan0' interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(('vcan0',))

while True:
    cf, addr = s.recvfrom(can_frame_size)

    print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))

    try:
        s.send(cf)
    except OSError:
        print('Error sending CAN frame')

    try:
        s.send(build_can_frame(0x01, b'\x01\x02\x03'))
    except OSError:
        print('Error sending CAN frame')
@end example

多次运行一个示例，且每次执行之间等待时间过短，可能导致这个错误:

@example
OSError: [Errno 98] Address already in use
@end example

这是因为前一次运行使套接字处于 @code{TIME_WAIT} 状态，无法立即重用。

要防止这种情况，需要设置一个 @ref{ef,,socket} 标志 @code{socket.SO_REUSEADDR}:

@example
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
@end example

@code{SO_REUSEADDR} 标志告诉内核将处于 @code{TIME_WAIT} 状态的本地套接字重新使用，而不必等到固有的超时到期。


@subsubheading 参见


关于套接字编程（C 语言）的介绍，请参阅以下文章：


@itemize -

@item 
@emph{An Introductory 4.3BSD Interprocess Communication Tutorial}，作者 Stuart Sechrest

@item 
@emph{An Advanced 4.3BSD Interprocess Communication Tutorial}，作者 Samuel J.  Leffler et al,
@end itemize

两篇文章都在 UNIX 开发者手册，补充文档 1（第 PS1:7 和 PS1:8 节）中。那些特定于平台的参考资料，它们包含与套接字有关的各种系统调用，也是套接字语义细节的宝贵信息来源。对于 Unix，请参考手册页。对于 Windows，请参阅 WinSock（或 Winsock 2）规范。如果需要支持 IPv6 的 API，读者可能希望参考 
@geindex RFC; RFC 3493
RFC 3493@footnote{https://tools.ietf.org/html/rfc3493.html}，标题为 Basic Socket Interface Extensions for IPv6。


@node ssl --- 套接字对象的 TLS/SSL 包装器,select --- 等待 I/O 完成,socket --- 底层网络接口,网络和进程间通信
@anchor{library/ssl doc}@anchor{2804}@anchor{library/ssl module-ssl}@anchor{f3}@anchor{library/ssl ssl-tls-ssl-wrapper-for-socket-objects}@anchor{2805}
@subsection @code{ssl} --- 套接字对象的 TLS/SSL 包装器


@geindex ssl (模块)

@strong{源代码:} Lib/ssl.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/ssl.py}

@geindex OpenSSL; (use in module ssl)

@geindex TLS
@geindex SSL
@geindex Transport Layer Security
@geindex Secure Sockets Layer


__________________________________________________________________


该模块提供了对传输层安全（通常称为 "安全套接字层"）加密和网络套接字的对等认证设施的访问，包括客户端和服务器端。 该模块使用 OpenSSL 库。它可以在所有现代 Unix 系统、 Windows 、 macOS 和可能的其他平台上使用，只要 OpenSSL 安装在该平台上。

@cartouche
@quotation 注解 
某些行为可能具有平台依赖，因为调用是根据操作系统的嵌套字API。不同版本的Open SSL也会引起差异：例如Open SSL版本1.0.1 自带TLSv1.1 和 TLSv1.2
@end quotation
@end cartouche

@cartouche
@quotation 警告 
在阅读 @ref{2711,,安全考量} 前不要使用此模块。 这样做可能会导致虚假的安全感，因为ssl模块的默认设置不一定适合你的应用程序。
@end quotation
@end cartouche

本文档记录"ssl"模块的对象和函数；更多关于TLS,SSL,和证书的信息，请参阅下方的“详情”选项

本模块提供了一个类 @ref{192,,ssl.SSLSocket}，它派生自 @ref{771,,socket.socket} 类型，并提供类似套接字的包装器，也能够对通过带 SSL 套接字的数据进行加密和解密。 它支持一些额外方法例如 @code{getpeercert()}，该方法可从连接的另一端获取证书，还有 @code{cipher()}，该方法可获取安全连接所使用的密码。

对于更复杂的应用程序，@ref{4f2,,ssl.SSLContext} 类有助于管理设置项和证书，进而可以被使用 @ref{4f3,,SSLContext.wrap_socket()} 方法创建的 SSL 套接字继承。


在 3.5.3 版更改: 更新以支持和 OpenSSL 1.1.0 的链接



在 3.6 版更改: OpenSSL 0.9.8、1.0.0 和 1.0.1 已过时，将不再被支持。在 ssl 模块未来的版本中，最低需要 OpenSSL 1.0.2 或 1.1.0。


@menu
* 方法、常量和异常处理:: 
* SSL 套接字:: 
* SSL 上下文:: 
* 证书:: 
* 示例: 示例<24>. 
* 关于非阻塞套接字的说明:: 
* 内存 BIO 支持: 内存 BIO 支持<2>. 
* SSL 会话:: 
* 安全考量: 安全考量<3>. 
* TLS 1.3: TLS 1 3. 
* LibreSSL 支持:: 

@end menu

@node 方法、常量和异常处理,SSL 套接字,,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl functions-constants-and-exceptions}@anchor{2806}
@subsubsection 方法、常量和异常处理


@menu
* 套接字创建:: 
* 上下文创建:: 
* 异常: 异常<12>. 
* 随机生成:: 
* 证书处理:: 
* 常量: 常量<3>. 

@end menu

@node 套接字创建,上下文创建,,方法、常量和异常处理
@anchor{library/ssl socket-creation}@anchor{2807}
@subsubsection 套接字创建


从 Python 3.2 和 2.7.9 开始，建议使用 @ref{4f2,,SSLContext} 实例的 @ref{4f3,,SSLContext.wrap_socket()} 来将套接字包装为 @ref{192,,SSLSocket} 对象。 辅助函数 @ref{9b0,,create_default_context()} 会返回一个新的带有安全默认设置的上下文。 旧的 @ref{579,,wrap_socket()} 函数已被弃用，因为它效率较差并且不支持服务器名称提示（SNI）和主机匹配。

客户端套接字实例，采用默认上下文和IPv4/IPv6双栈:

@example
import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
@end example

客户端套接字示例，带有自定义上下文和IPv4:

@example
hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
@end example

服务器套接字实例，在localhost上监听IPv4:

@example
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...
@end example

@node 上下文创建,异常<12>,套接字创建,方法、常量和异常处理
@anchor{library/ssl context-creation}@anchor{2808}
@subsubsection 上下文创建


便捷函数，可以帮助创建 @ref{4f2,,SSLContext} 对象，用于常见的目的。

@geindex create_default_context() (在 ssl 模块中)
@anchor{library/ssl ssl create_default_context}@anchor{9b0}
@deffn {函数} ssl.create_default_context (purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)

返回一个新的 @ref{4f2,,SSLContext} 对象，使用给定 @emph{purpose} 的默认设置。 该设置由 @ref{f3,,ssl} 模块选择，并且通常是代表一个比直接调用 @ref{4f2,,SSLContext} 构造器时更高的安全等级。

@emph{cafile}, @emph{capath}, @emph{cadata} 代表用于进行证书核验的可选受信任 CA 证书，与 @ref{8e2,,SSLContext.load_verify_locations()} 的一致。 如果三个参数均为 @ref{204,,None}，此函数可以转而选择信任系统的默认 CA 证书。

设置为: @ref{2809,,PROTOCOL_TLS}, @ref{c79,,OP_NO_SSLv2} 和 @ref{280a,,OP_NO_SSLv3}，带有不含 RC4 及未认证的高强度加密密码套件。 传入 @ref{9bb,,SERVER_AUTH} 作为 @emph{purpose} 会将 @ref{280b,,verify_mode} 设为 @ref{280c,,CERT_REQUIRED} 并加载 CA 证书 (若给出 @emph{cafile}, @emph{capath} 或 @emph{cadata} 之一) 或用 @ref{9ba,,SSLContext.load_default_certs()} 加载默认 CA 证书。

当 @ref{280d,,keylog_filename} 受支持并且设置了环境变量 
@geindex SSLKEYLOGFILE
@geindex 环境变量; SSLKEYLOGFILE
@code{SSLKEYLOGFILE} 时，@ref{9b0,,create_default_context()} 会启用密钥日志记录。

@cartouche
@quotation 注解 
协议、选项、密码和其他设置可随时更改为更具约束性的值而无须事先弃用。 这些值代表了兼容性和安全性之间的合理平衡。

如果你的应用需要特定的设置，你应当创建一个 @ref{4f2,,SSLContext} 并自行应用设置。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果你发现当某些较旧的客户端或服务器尝试与用此函数创建的 @ref{4f2,,SSLContext} 进行连接时收到了报错提示 "Protocol or cipher suite mismatch"，这可能是因为它们只支持 SSL3.0 而它被此函数用 @ref{280a,,OP_NO_SSLv3} 排除掉了。 SSL3.0 被广泛认为 完全不可用@footnote{https://en.wikipedia.org/wiki/POODLE}。 如果你仍希望继续使用此函数但仍允许 SSL 3.0 连接，你可以使用以下代码重新启用它们:

@example
ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &= ~ssl.OP_NO_SSLv3
@end example
@end quotation
@end cartouche


3.4 新版功能.



在 3.4.4 版更改: RC4 被从默认密码字符串中丢弃。



在 3.6 版更改: ChaCha20/Poly1305 被添加到默认密码字符串中。

3DES 被从默认密码字符串中丢弃。



在 3.8 版更改: 增加了对密钥日志记录至 
@geindex SSLKEYLOGFILE
@geindex 环境变量; SSLKEYLOGFILE
@code{SSLKEYLOGFILE} 的支持。

@end deffn

@node 异常<12>,随机生成,上下文创建,方法、常量和异常处理
@anchor{library/ssl exceptions}@anchor{280e}
@subsubsection 异常


@geindex SSLError
@anchor{library/ssl ssl SSLError}@anchor{ce2}
@deffn {例外} ssl.SSLError

引发此异常以提示来自下层 SSL 实现（目前由 OpenSSL 库提供）的错误。 它表示在下层网络连接之上叠加的高层级加密和验证层存在某种问题。 此错误是 @ref{30b,,OSError} 的一个子类型。 @ref{ce2,,SSLError} 实例的错误和消息是由 OpenSSL 库提供的。


在 3.3 版更改: @ref{ce2,,SSLError} 曾经是 @ref{a7f,,socket.error} 的一个子类型。


@geindex library (ssl.SSLError 属性)
@anchor{library/ssl ssl SSLError library}@anchor{b79}
@deffn {属性} library

一个字符串形式的助记符，用来指明发生错误的 OpenSSL 子模块，例如 @code{SSL}, @code{PEM} 或 @code{X509}。 可能的取值范围依赖于 OpenSSL 的版本。


3.3 新版功能.

@end deffn

@geindex reason (ssl.SSLError 属性)
@anchor{library/ssl ssl SSLError reason}@anchor{b7a}
@deffn {属性} reason

一个字符串形式的助记符，用来指明发生错误的原因，例如 @code{CERTIFICATE_VERIFY_FAILED}。 可能的取值范围依赖于 OpenSSL 的版本。


3.3 新版功能.

@end deffn
@end deffn

@geindex SSLZeroReturnError
@anchor{library/ssl ssl SSLZeroReturnError}@anchor{280f}
@deffn {例外} ssl.SSLZeroReturnError

@ref{ce2,,SSLError} 的子类，当尝试读取或写入且 SSL 连接已被完全关闭时会被引发。 请注意这并不意味着下层的传输（读取 TCP）已被关闭。


3.3 新版功能.

@end deffn

@geindex SSLWantReadError
@anchor{library/ssl ssl SSLWantReadError}@anchor{84f}
@deffn {例外} ssl.SSLWantReadError

@ref{ce2,,SSLError} 的子类，当尝试读取或写入数据，但在请求被满足之前还需要在下层的 TCP 传输上接收更多数据时会被 @ref{2810,,非阻塞型 SSL 套接字} 引发。


3.3 新版功能.

@end deffn

@geindex SSLWantWriteError
@anchor{library/ssl ssl SSLWantWriteError}@anchor{850}
@deffn {例外} ssl.SSLWantWriteError

@ref{ce2,,SSLError} 的子类，当尝试读取或写入数据，但在请求被满足之前还需要在下层的 TCP 传输上发送更多数据时会被 @ref{2810,,非阻塞型 SSL 套接字} 引发。


3.3 新版功能.

@end deffn

@geindex SSLSyscallError
@anchor{library/ssl ssl SSLSyscallError}@anchor{2811}
@deffn {例外} ssl.SSLSyscallError

@ref{ce2,,SSLError} 的子类，当尝试在 SSL 套接字上执行操作时遇到系统错误时会被引发。 不幸的是，没有简单的方式能检查原始 errno 编号。


3.3 新版功能.

@end deffn

@geindex SSLEOFError
@anchor{library/ssl ssl SSLEOFError}@anchor{2812}
@deffn {例外} ssl.SSLEOFError

@ref{ce2,,SSLError} 的子类，当 SSL 连接被突然终止时会被引发。 通常，当遇到此错误时你不应再尝试重用下层的传输。


3.3 新版功能.

@end deffn

@geindex SSLCertVerificationError
@anchor{library/ssl ssl SSLCertVerificationError}@anchor{4ec}
@deffn {例外} ssl.SSLCertVerificationError

@ref{ce2,,SSLError} 的子类，当证书验证失败时会被引发。


3.7 新版功能.


@geindex verify_code (ssl.SSLCertVerificationError 属性)
@anchor{library/ssl ssl SSLCertVerificationError verify_code}@anchor{2813}
@deffn {属性} verify_code

一个数字形式的错误编号，用于表示验证错误。
@end deffn

@geindex verify_message (ssl.SSLCertVerificationError 属性)
@anchor{library/ssl ssl SSLCertVerificationError verify_message}@anchor{2814}
@deffn {属性} verify_message

用于表示验证错误的人类可读的字符串。
@end deffn
@end deffn

@geindex CertificateError
@anchor{library/ssl ssl CertificateError}@anchor{2815}
@deffn {例外} ssl.CertificateError

@ref{4ec,,SSLCertVerificationError} 的别名。


在 3.7 版更改: 此异常现在是 @ref{4ec,,SSLCertVerificationError} 的别名。

@end deffn

@node 随机生成,证书处理,异常<12>,方法、常量和异常处理
@anchor{library/ssl random-generation}@anchor{2816}
@subsubsection 随机生成


@geindex RAND_bytes() (在 ssl 模块中)
@anchor{library/ssl ssl RAND_bytes}@anchor{b70}
@deffn {函数} ssl.RAND_bytes (num)

返回 @emph{num} 个高加密强度伪随机字节数据。 如果 PRNG 未使用足够的数据作为随机种子或者如果当前 RAND 方法不支持该操作则会引发 @ref{ce2,,SSLError}。 @ref{2817,,RAND_status()} 可被用来检查 PRNG 的状态而 @ref{2818,,RAND_add()} 可被用来为 PRNG 设置随机种子。

对于几乎所有应用程序都更推荐使用 @ref{5d4,,os.urandom()}。

请阅读维基百科文章 Cryptographically secure pseudorandom number generator (CSPRNG)@footnote{https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator} 以了解对于高加密强度生成器的具体要求。


3.3 新版功能.

@end deffn

@geindex RAND_pseudo_bytes() (在 ssl 模块中)
@anchor{library/ssl ssl RAND_pseudo_bytes}@anchor{b71}
@deffn {函数} ssl.RAND_pseudo_bytes (num)

返回 (bytes, is_cryptographic): bytes 是 @emph{num} 个伪随机字节数据，如果所生成的字节数据为高加密强度则 is_cryptographic 为 @code{True}。 如果当前 RAND 方法不支持此操作则会引发 @ref{ce2,,SSLError}。

所生成的伪随机字节序列如果具有足够的长度则将会具有唯一性，并是并非不可预测。 它们可被用于非加密目的以及加密协议中的特定目的，但通常不可被用于密钥生成等目的。

对于几乎所有应用程序都更推荐使用 @ref{5d4,,os.urandom()}。


3.3 新版功能.



3.6 版后已移除: OpenSSL 已弃用了 @ref{b71,,ssl.RAND_pseudo_bytes()}，请改用 @ref{b70,,ssl.RAND_bytes()}。

@end deffn

@geindex RAND_status() (在 ssl 模块中)
@anchor{library/ssl ssl RAND_status}@anchor{2817}
@deffn {函数} ssl.RAND_status ()

如果 SSL 伪随机数生成器已使用‘足够的’随机性作为种子则返回  @code{True}，否则返回 @code{False}。 你可以使用 @ref{2819,,ssl.RAND_egd()} 和 @ref{2818,,ssl.RAND_add()} 来增加伪随机数生成器的随机性。
@end deffn

@geindex RAND_egd() (在 ssl 模块中)
@anchor{library/ssl ssl RAND_egd}@anchor{2819}
@deffn {函数} ssl.RAND_egd (path)

如果你在某处运行了一个熵收集守护程序（EGD），且 @emph{path} 是向其打开的套接字连接路径名，此函数将从该套接字读取 256 个字节的随机性数据，并将其添加到 SSL 伪随机数生成器以增加所生成密钥的安全性。 此操作通常只在没有更好随机性源的系统上才是必要的。

请查看 @indicateurl{http://egd.sourceforge.net/} 或 @indicateurl{http://prngd.sourceforge.net/} 来了解有关熵收集守护程序源的信息。

@ref{14c1,,可用性}: 对于 LibreSSL 和 OpenSSL > 1.1.0 不可用。
@end deffn

@geindex RAND_add() (在 ssl 模块中)
@anchor{library/ssl ssl RAND_add}@anchor{2818}
@deffn {函数} ssl.RAND_add (bytes, entropy)

将给定的 @emph{bytes} 混合到 SSL 伪随机数生成器中。 形参 @emph{entropy} (float 类型) 是数据所包含的熵的下界 (因此你可以总是使用 @code{0.0})。 请查看 
@geindex RFC; RFC 1750
RFC 1750@footnote{https://tools.ietf.org/html/rfc1750.html} 了解有关熵源的更多信息。


在 3.5 版更改: 现在接受可写的 @ref{6e9,,字节类对象}。

@end deffn

@node 证书处理,常量<3>,随机生成,方法、常量和异常处理
@anchor{library/ssl certificate-handling}@anchor{281a}
@subsubsection 证书处理


@c import ssl

@geindex match_hostname() (在 ssl 模块中)
@anchor{library/ssl ssl match_hostname}@anchor{4eb}
@deffn {函数} ssl.match_hostname (cert, hostname)

验证 @emph{cert} (使用 @ref{9c0,,SSLSocket.getpeercert()} 所返回的已解码格式) 是否匹配给定的 @emph{hostname}。 所应用的规则是在 
@geindex RFC; RFC 2818
RFC 2818@footnote{https://tools.ietf.org/html/rfc2818.html}, 
@geindex RFC; RFC 5280
RFC 5280@footnote{https://tools.ietf.org/html/rfc5280.html} 和 
@geindex RFC; RFC 6125
RFC 6125@footnote{https://tools.ietf.org/html/rfc6125.html} 中描述的检查 HTTPS 服务器身份的规则。 除了 HTTPS，此函数还应当适用于各种基于 SSL 协议的服务器身份检查操作，例如 FTPS, IMAPS, POPS 等等。

失败时引发 @ref{2815,,CertificateError}。 成功时此函数无返回值:

@example
>>> cert = @{'subject': ((('commonName', 'example.com'),),)@}
>>> ssl.match_hostname(cert, "example.com")
>>> ssl.match_hostname(cert, "example.org")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
@end example


3.2 新版功能.



在 3.3.3 版更改: 此函数现在遵循 
@geindex RFC; RFC 6125
RFC 6125@footnote{https://tools.ietf.org/html/rfc6125.html}, 6.4.3 小节，它不会匹配多个通配符 (例如 @code{*.*.com} 或 @code{*a*.example.org}) 也不匹配国际化域名 (IDN) 片段内部的通配符。 IDN A 标签例如 @code{www*.xn--pthon-kva.org} 仍然受支持，但 @code{x*.python.org} 不再能匹配 @code{xn--tda.python.org}。



在 3.5 版更改: 现在支持匹配存在于证书的 subjectAltName 字段中的 IP 地址。



在 3.7 版更改: 此函数不再被用于 TLS 连接。 主机匹配现在是由 OpenSSL 执行的。

允许位于段的最左端且为唯一字符的通配符。 部分通配符例如 @code{www*.example.com} 已不再受支持。



3.7 版后已移除.

@end deffn

@geindex cert_time_to_seconds() (在 ssl 模块中)
@anchor{library/ssl ssl cert_time_to_seconds}@anchor{851}
@deffn {函数} ssl.cert_time_to_seconds (cert_time)

返回距离 Unix 纪元零时的秒数，给定的 @code{cert_time} 字符串代表来自证书的 "notBefore" 或 "notAfter" 日期值，采用 @code{"%b %d %H:%M:%S %Y %Z"} strptime 格式（C 区域）。

以下为示例代码:

@example
>>> import ssl
>>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
>>> timestamp  
1515144883
>>> from datetime import datetime
>>> print(datetime.utcfromtimestamp(timestamp))  
2018-01-05 09:34:43
@end example

"notBefore" 或 "notAfter" 日期值必须使用 GMT (
@geindex RFC; RFC 5280
RFC 5280@footnote{https://tools.ietf.org/html/rfc5280.html})。


在 3.5 版更改: 将输入时间解读为 UTC 时间，基于输入字符串中指明的 'GMT' 时区。 在之前使用的是本地时区。 返回一个整数（不带输入格式中秒的分数部分）

@end deffn

@geindex get_server_certificate() (在 ssl 模块中)
@anchor{library/ssl ssl get_server_certificate}@anchor{b7b}
@deffn {函数} ssl.get_server_certificate (addr, ssl_version=PROTOCOL_TLS, ca_certs=None)

带 SSL 保护的服务器的地址 @code{addr} 以 (@emph{hostname}, @emph{port-number}) 对的形式给出，获取服务器的证书，并将其以 PEM 编码字符串的形式返回。 如果指定了 @code{ssl_version}，则使用该版本的 SSL 协议尝试连接服务器。 如果指定了 @code{ca_certs}，它应当是一个包含根证书列表的文件，使用与 @ref{4f3,,SSLContext.wrap_socket()} 中同名形参一致的格式。 该调用将尝试根据指定的根证书集来验证服务器证书，如果验证失败则该调用也将失败。


在 3.3 版更改: 此函数现在是 IPv6 兼容的。-compatible.



在 3.5 版更改: 默认的 @emph{ssl_version} 从 @ref{281b,,PROTOCOL_SSLv3} 改为 @ref{2809,,PROTOCOL_TLS} 以保证与现代服务器的最大兼容性。

@end deffn

@geindex DER_cert_to_PEM_cert() (在 ssl 模块中)
@anchor{library/ssl ssl DER_cert_to_PEM_cert}@anchor{281c}
@deffn {函数} ssl.DER_cert_to_PEM_cert (DER_cert_bytes)

根据给定的 DER 编码字节块形式的证书，返回同一证书的 PEM 编码字符串版本。
@end deffn

@geindex PEM_cert_to_DER_cert() (在 ssl 模块中)
@anchor{library/ssl ssl PEM_cert_to_DER_cert}@anchor{281d}
@deffn {函数} ssl.PEM_cert_to_DER_cert (PEM_cert_string)

根据给定的 ASCII PEM 字符串形式的证书，返回同一证书的 DER 编码字节序列。
@end deffn

@geindex get_default_verify_paths() (在 ssl 模块中)
@anchor{library/ssl ssl get_default_verify_paths}@anchor{9b1}
@deffn {函数} ssl.get_default_verify_paths ()

返回包含 OpenSSL 的默认 cafile 和 capath 的路径的命名元组。 此路径与 @ref{9b2,,SSLContext.set_default_verify_paths()} 所使用的相同。 返回值是一个 @ref{b84,,named tuple} @code{DefaultVerifyPaths}:


@itemize *

@item 
@code{cafile} - 解析出的 cafile 路径或者如果文件不存在则为 @code{None},

@item 
@code{capath} - 解析出的 capath 路径或者如果目录不存在则为 @code{None},

@item 
@code{openssl_cafile_env} - 指向一个 cafile 的 OpenSSL 环境键,

@item 
@code{openssl_cafile} - 一个 cafile 的硬编码路径,

@item 
@code{openssl_capath_env} - 指向一个 capath 的 OpenSSL 环境键,

@item 
@code{openssl_capath} - 一个 capath 目录的硬编码路径
@end itemize

@ref{14c1,,可用性}: LibreSSL 会忽略环境变量 @code{openssl_cafile_env} 和 @code{openssl_capath_env}。


3.4 新版功能.

@end deffn

@geindex enum_certificates() (在 ssl 模块中)
@anchor{library/ssl ssl enum_certificates}@anchor{9bd}
@deffn {函数} ssl.enum_certificates (store_name)

从 Windows 的系统证书库中检索证书。 @emph{store_name} 可以是 @code{CA}, @code{ROOT} 或 @code{MY} 中的一个。 Windows 也可能会提供额外的证书库。

此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。 encoding_type 指明 cert_bytes 的编码格式。 它可以为 @code{x509_asn} 以表示 X.509 ASN.1 数据或是 @code{pkcs_7_asn} 以表示 PKCS#7 ASN.1 数据。 trust 以 OIDS 集合的形式指明证书的目的，或者如果证书对于所有目的都可以信任则为 @code{True}。

示例:

@example
>>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', @{'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'@}),
 (b'data...', 'x509_asn', True)]
@end example

@ref{14c1,,可用性}: Windows。


3.4 新版功能.

@end deffn

@geindex enum_crls() (在 ssl 模块中)
@anchor{library/ssl ssl enum_crls}@anchor{9be}
@deffn {函数} ssl.enum_crls (store_name)

Windows 的系统证书库中检索 CRL。 @emph{store_name} 可以是 @code{CA}, @code{ROOT} 或 @code{MY} 中的一个。 Windows 也可能会提供额外的证书库。

此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。 encoding_type 指明 cert_bytes 的编码格式。 它可以为 @code{x509_asn} 以表示 X.509 ASN.1 数据或是 @code{pkcs_7_asn} 以表示 PKCS#7 ASN.1 数据。

@ref{14c1,,可用性}: Windows。


3.4 新版功能.

@end deffn

@geindex wrap_socket() (在 ssl 模块中)
@anchor{library/ssl ssl wrap_socket}@anchor{579}
@deffn {函数} ssl.wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)

接受一个 @ref{771,,socket.socket} 的实例 @code{sock}，并返回一个 @ref{192,,ssl.SSLSocket} 的实例，该类型是 @ref{771,,socket.socket} 的子类型，它将下层的套接字包装在一个 SSL 上下文中。 @code{sock} 必须是一个 @ref{d5a,,SOCK_STREAM} 套接字；其他套接字类型不被支持。

在内部，该函数会创建一个 @ref{4f2,,SSLContext}，其协议版本为 @emph{ssl_version} 且 @ref{281e,,SSLContext.options} 设为 @emph{cert_reqs}。 如果设置了 @emph{keyfile}, @emph{certfile}, @emph{ca_certs} 或 @emph{ciphers} 等形参，则参数值会被传给 @ref{b72,,SSLContext.load_cert_chain()}, @ref{8e2,,SSLContext.load_verify_locations()} 以及 @ref{281f,,SSLContext.set_ciphers()}。

参数 @emph{server_side}, @emph{do_handshake_on_connect} 和 @emph{suppress_ragged_eofs} 具有与 @ref{4f3,,SSLContext.wrap_socket()} 相同的含义。


3.7 版后已移除: 从 Python 3.2 和 2.7.9 开始，建议使用 @ref{4f3,,SSLContext.wrap_socket()} 来代替 @ref{579,,wrap_socket()}。 模块级函数的功能受限并且将创建不安全的客户端套接字，不带服务器名称提示或主机名匹配。

@end deffn

@node 常量<3>,,证书处理,方法、常量和异常处理
@anchor{library/ssl constants}@anchor{2820}
@subsubsection 常量


@quotation

所有常量现在都是 @ref{68e,,enum.IntEnum} 或 @ref{18ed,,enum.IntFlag} 多项集的成员。


3.6 新版功能.

@end quotation

@geindex CERT_NONE() (在 ssl 模块中)
@anchor{library/ssl ssl CERT_NONE}@anchor{2821}
@deffn {数据} ssl.CERT_NONE

@ref{280b,,SSLContext.verify_mode} 或 @ref{579,,wrap_socket()} 的 @code{cert_reqs} 形参可能的取值。 @ref{2822,,PROTOCOL_TLS_CLIENT} 除外，这是默认的模式。 对于客户端套接字，几乎任何证书都是可接受的。 验证错误例如不受信任或过期的证书错误会被忽略并且不会中止 TLS/SSL 握手。

在服务器模式下，不会从客户端请求任何证书，因此客户端不会发送任何用于客户端证书身份验证的证书。

参见下文对于 @ref{2711,,安全考量} 的讨论。
@end deffn

@geindex CERT_OPTIONAL() (在 ssl 模块中)
@anchor{library/ssl ssl CERT_OPTIONAL}@anchor{2823}
@deffn {数据} ssl.CERT_OPTIONAL

@ref{280b,,SSLContext.verify_mode} 或 @ref{579,,wrap_socket()} 的 @code{cert_reqs} 形参可能的取值。 @ref{2823,,CERT_OPTIONAL} 具有与 @ref{280c,,CERT_REQUIRED} 相同的含义。 对于客户端套接字推荐改用 @ref{280c,,CERT_REQUIRED}。

在服务器模式下，客户端证书请求会被发送给客户端。 客户端可以忽略请求也可以发送一个证书以执行 TLS 客户端证书身份验证。 如果客户端选择发送证书，则将对其执行验证。 任何验证错误都将立即中止 TLS 握手。

使用此设置要求将一组有效的 CA 证书传递给 @ref{8e2,,SSLContext.load_verify_locations()} 或是作为 @ref{579,,wrap_socket()} 的 @code{ca_certs} 形参值。
@end deffn

@geindex CERT_REQUIRED() (在 ssl 模块中)
@anchor{library/ssl ssl CERT_REQUIRED}@anchor{280c}
@deffn {数据} ssl.CERT_REQUIRED

@ref{280b,,SSLContext.verify_mode} 或 @ref{579,,wrap_socket()} 的 @code{cert_reqs} 形参可能的取值。 在此模式下，需要从套接字连接的另一端获取证书；如果未提供证书或验证失败则将引发 @ref{ce2,,SSLError}。 此模式 @strong{不能} 在客户端模式下对证书进行验证，因为它不会匹配主机名。 @ref{2824,,check_hostname} 也必须被启用以验证证书的真实性。 @ref{2822,,PROTOCOL_TLS_CLIENT} 会使用 @ref{280c,,CERT_REQUIRED} 并默认启用 @ref{2824,,check_hostname}。

对于服务器套接字，此模式会提供强制性的 TLS 客户端证书验证。 客户端证书请求会被发送给客户端并且客户端必须提供有效且受信任的证书。

使用此设置要求将一组有效的 CA 证书传递给 @ref{8e2,,SSLContext.load_verify_locations()} 或是作为 @ref{579,,wrap_socket()} 的 @code{ca_certs} 形参值。
@end deffn

@geindex VerifyMode (ssl 中的类)
@anchor{library/ssl ssl VerifyMode}@anchor{2825}
@deffn {类} ssl.VerifyMode

CERT_* 常量的 @ref{68e,,enum.IntEnum} 多项集。


3.6 新版功能.

@end deffn

@geindex VERIFY_DEFAULT() (在 ssl 模块中)
@anchor{library/ssl ssl VERIFY_DEFAULT}@anchor{9b6}
@deffn {数据} ssl.VERIFY_DEFAULT

@ref{9b5,,SSLContext.verify_flags} 可能的取值。 在此模式下，证书吊销列表（CRL）并不会被检查。 OpenSSL 默认不要求也不验证 CRL。


3.4 新版功能.

@end deffn

@geindex VERIFY_CRL_CHECK_LEAF() (在 ssl 模块中)
@anchor{library/ssl ssl VERIFY_CRL_CHECK_LEAF}@anchor{9b7}
@deffn {数据} ssl.VERIFY_CRL_CHECK_LEAF

@ref{9b5,,SSLContext.verify_flags} 可能的取值。 在此模式下， 只会检查对等证书而不检查任何中间 CA 证书。 此模式要求提供由对等证书颁发者（其直接上级 CA）签名的有效 CRL。 如果未使用 @ref{8e2,,SSLContext.load_verify_locations} 加载正确的 CRL，则验证将失败。


3.4 新版功能.

@end deffn

@geindex VERIFY_CRL_CHECK_CHAIN() (在 ssl 模块中)
@anchor{library/ssl ssl VERIFY_CRL_CHECK_CHAIN}@anchor{9b8}
@deffn {数据} ssl.VERIFY_CRL_CHECK_CHAIN

@ref{9b5,,SSLContext.verify_flags} 可能的取值。 在此模式下，会检查对等证书链中所有证书的 CRL。


3.4 新版功能.

@end deffn

@geindex VERIFY_X509_STRICT() (在 ssl 模块中)
@anchor{library/ssl ssl VERIFY_X509_STRICT}@anchor{9b9}
@deffn {数据} ssl.VERIFY_X509_STRICT

@ref{9b5,,SSLContext.verify_flags} 可能的取值，用于禁用已损坏 X.509 证书的绕过操作。


3.4 新版功能.

@end deffn

@geindex VERIFY_X509_TRUSTED_FIRST() (在 ssl 模块中)
@anchor{library/ssl ssl VERIFY_X509_TRUSTED_FIRST}@anchor{2826}
@deffn {数据} ssl.VERIFY_X509_TRUSTED_FIRST

@ref{9b5,,SSLContext.verify_flags} 可能的取值。 它指示 OpenSSL 在构建用于验证某个证书的信任链时首选受信任的证书。 此旗标将默认被启用。


3.4.4 新版功能.

@end deffn

@geindex VerifyFlags (ssl 中的类)
@anchor{library/ssl ssl VerifyFlags}@anchor{2827}
@deffn {类} ssl.VerifyFlags

VERIFY_* 常量的 @ref{18ed,,enum.IntFlag} 多项集。


3.6 新版功能.

@end deffn

@geindex PROTOCOL_TLS() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLS}@anchor{2809}
@deffn {数据} ssl.PROTOCOL_TLS

选择客户端和服务器均支持的最高协议版本。 此选项名称并不准确，实际上 "SSL" 和 "TLS" 协议均可被选择。


3.6 新版功能.

@end deffn

@geindex PROTOCOL_TLS_CLIENT() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLS_CLIENT}@anchor{2822}
@deffn {数据} ssl.PROTOCOL_TLS_CLIENT

像 @ref{2809,,PROTOCOL_TLS} 一样地自动协商最高协议版本，但是只支持客户端 @ref{192,,SSLSocket} 连接。 此协议默认会启用 @ref{280c,,CERT_REQUIRED} 和 @ref{2824,,check_hostname}。


3.6 新版功能.

@end deffn

@geindex PROTOCOL_TLS_SERVER() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLS_SERVER}@anchor{2828}
@deffn {数据} ssl.PROTOCOL_TLS_SERVER

像 @ref{2809,,PROTOCOL_TLS} 一样地自动协商最高协议版本，但是只支持服务器 @ref{192,,SSLSocket} 连接。


3.6 新版功能.

@end deffn

@geindex PROTOCOL_SSLv23() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_SSLv23}@anchor{2829}
@deffn {数据} ssl.PROTOCOL_SSLv23

@ref{2809,,PROTOCOL_TLS} 的别名。


3.6 版后已移除: 请改用 @ref{2809,,PROTOCOL_TLS}。

@end deffn

@geindex PROTOCOL_SSLv2() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_SSLv2}@anchor{282a}
@deffn {数据} ssl.PROTOCOL_SSLv2

选择 SSL 版本 2 作为通道加密协议。

如果 OpenSSL 编译时使用了 @code{OPENSSL_NO_SSL2} 旗标则此协议将不可用。

@cartouche
@quotation 警告 
SSL 版本 2 并不安全。 极不建议使用它。
@end quotation
@end cartouche


3.6 版后已移除: OpenSSL 已经移除了对 SSLv2 的支持。

@end deffn

@geindex PROTOCOL_SSLv3() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_SSLv3}@anchor{281b}
@deffn {数据} ssl.PROTOCOL_SSLv3

选择 SSL 版本 3 作为通道加密协议。

如果 OpenSSL 编译时使用了 @code{OPENSSL_NO_SSLv3} 旗标则此协议将不可用。

@cartouche
@quotation 警告 
SSL 版本 3 并不安全。 极不建议使用它。
@end quotation
@end cartouche


3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用默认协议 @ref{2809,,PROTOCOL_TLS} 并附带 @ref{280a,,OP_NO_SSLv3} 等旗标。

@end deffn

@geindex PROTOCOL_TLSv1() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLSv1}@anchor{282b}
@deffn {数据} ssl.PROTOCOL_TLSv1

选择 TLS 版本 1.0 作为通道加密协议。


3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用默认协议 @ref{2809,,PROTOCOL_TLS} 并附带 @ref{280a,,OP_NO_SSLv3} 等旗标。

@end deffn

@geindex PROTOCOL_TLSv1_1() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLSv1_1}@anchor{9ae}
@deffn {数据} ssl.PROTOCOL_TLSv1_1

选择 TLS 版本 1.1 作为通道加密协议。 仅适用于 openssl 版本 1.0.1+。


3.4 新版功能.



3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用默认协议 @ref{2809,,PROTOCOL_TLS} 并附带 @ref{280a,,OP_NO_SSLv3} 等旗标。

@end deffn

@geindex PROTOCOL_TLSv1_2() (在 ssl 模块中)
@anchor{library/ssl ssl PROTOCOL_TLSv1_2}@anchor{9af}
@deffn {数据} ssl.PROTOCOL_TLSv1_2

选译 TLS 版本 1.2 作为通道加密协议。 这是最新的版本，也应是能提供最大保护的最佳选择，如果通信双方都支持它的话。 仅适用于 openssl 版本 1.0.1+。


3.4 新版功能.



3.6 版后已移除: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用默认协议 @ref{2809,,PROTOCOL_TLS} 并附带 @ref{280a,,OP_NO_SSLv3} 等旗标。

@end deffn

@geindex OP_ALL() (在 ssl 模块中)
@anchor{library/ssl ssl OP_ALL}@anchor{282c}
@deffn {数据} ssl.OP_ALL

对存在于其他 SSL 实现中的各种缺陷启用绕过操作。 默认会设置此选项。 没有必要设置与 OpenSSL 的 @code{SSL_OP_ALL} 常量同名的旗标。


3.2 新版功能.

@end deffn

@geindex OP_NO_SSLv2() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_SSLv2}@anchor{c79}
@deffn {数据} ssl.OP_NO_SSLv2

阻止 SSLv2 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 SSLv2 作为协议版本。


3.2 新版功能.



3.6 版后已移除: SSLv2 已被弃用

@end deffn

@geindex OP_NO_SSLv3() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_SSLv3}@anchor{280a}
@deffn {数据} ssl.OP_NO_SSLv3

阻止 SSLv3 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 SSLv3 作为协议版本。


3.2 新版功能.



3.6 版后已移除: SSLv3 已被弃用

@end deffn

@geindex OP_NO_TLSv1() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_TLSv1}@anchor{282d}
@deffn {数据} ssl.OP_NO_TLSv1

阻止 TLSv1 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 TLSv1 作为协议版本。


3.2 新版功能.



3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用，请改用新的 @ref{4f5,,SSLContext.minimum_version} 和 @ref{4f6,,SSLContext.maximum_version}。

@end deffn

@geindex OP_NO_TLSv1_1() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_TLSv1_1}@anchor{282e}
@deffn {数据} ssl.OP_NO_TLSv1_1

阻止 TLSv1.1 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 TLSv1.1 作为协议版本。 仅适用于 openssl 版本 1.0.1+。


3.4 新版功能.



3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。

@end deffn

@geindex OP_NO_TLSv1_2() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_TLSv1_2}@anchor{282f}
@deffn {数据} ssl.OP_NO_TLSv1_2

阻止 TLSv1.2 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 TLSv1.2 作为协议版本。 仅适用于 openssl 版本 1.0.1+。


3.4 新版功能.



3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。

@end deffn

@geindex OP_NO_TLSv1_3() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_TLSv1_3}@anchor{2830}
@deffn {数据} ssl.OP_NO_TLSv1_3

阻止 TLSv1.3 连接。 此选项仅可与 @ref{2809,,PROTOCOL_TLS} 结合使用。 它会阻止对等方选择 TLSv1.3 作为协议版本。 TLS 1.3 适用于 OpenSSL 1.1.1 或更新的版本。 当 Python 编译是基于较旧版本的 OpenSSL 时，该旗标默认为 @emph{0}。


3.7 新版功能.



3.7 版后已移除: 此选项自 OpenSSL 1.1.0 起已被弃用。 它被添加到 2.7.15, 3.6.3 和 3.7.0 是为了向下兼容 OpenSSL 1.0.2。

@end deffn

@geindex OP_NO_RENEGOTIATION() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_RENEGOTIATION}@anchor{2831}
@deffn {数据} ssl.OP_NO_RENEGOTIATION

禁用所有 TLSv1.2 和更早版本的重协商操作。 不发送 HelloRequest 消息，并忽略通过 ClientHello 发起的重协商请求。

此选项仅适用于 OpenSSL 1.1.0h 及更新的版本。


3.7 新版功能.

@end deffn

@geindex OP_CIPHER_SERVER_PREFERENCE() (在 ssl 模块中)
@anchor{library/ssl ssl OP_CIPHER_SERVER_PREFERENCE}@anchor{b7c}
@deffn {数据} ssl.OP_CIPHER_SERVER_PREFERENCE

使用服务器的密码顺序首选项，而不是客户端的首选项。 此选项在客户端套接字和 SSLv2 服务器套接字上无效。


3.3 新版功能.

@end deffn

@geindex OP_SINGLE_DH_USE() (在 ssl 模块中)
@anchor{library/ssl ssl OP_SINGLE_DH_USE}@anchor{2832}
@deffn {数据} ssl.OP_SINGLE_DH_USE

阻止对于单独的 SSL 会话重用相同的 DH 密钥。 这会提升前向保密性但需要更多的计算资源。 此选项仅适用于服务器套接字。


3.3 新版功能.

@end deffn

@geindex OP_SINGLE_ECDH_USE() (在 ssl 模块中)
@anchor{library/ssl ssl OP_SINGLE_ECDH_USE}@anchor{2833}
@deffn {数据} ssl.OP_SINGLE_ECDH_USE

阻止对于单独的 SSL 会话重用相同的 ECDH 密钥。 这会提升前向保密性但需要更多的计算资源。 此选项仅适用于服务器套接字。


3.3 新版功能.

@end deffn

@geindex OP_ENABLE_MIDDLEBOX_COMPAT() (在 ssl 模块中)
@anchor{library/ssl ssl OP_ENABLE_MIDDLEBOX_COMPAT}@anchor{2834}
@deffn {数据} ssl.OP_ENABLE_MIDDLEBOX_COMPAT

在 TLS 1.3 握手中发送虚拟更改密码规格（CCS）消息以使得 TLS 1.3 连接看起来更像是 TLS 1.2 连接。

此选项仅适用于 OpenSSL 1.1.1 及更新的版本。


3.8 新版功能.

@end deffn

@geindex OP_NO_COMPRESSION() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_COMPRESSION}@anchor{b77}
@deffn {数据} ssl.OP_NO_COMPRESSION

在 SSL 通道上禁用压缩。 这适用于应用协议支持自己的压缩方案的情况。

此选项仅适用于 OpenSSL 1.0.0 及更新的版本。


3.3 新版功能.

@end deffn

@geindex Options (ssl 中的类)
@anchor{library/ssl ssl Options}@anchor{2835}
@deffn {类} ssl.Options

OP_* 常量的 @ref{18ed,,enum.IntFlag} 多项集。
@end deffn

@geindex OP_NO_TICKET() (在 ssl 模块中)
@anchor{library/ssl ssl OP_NO_TICKET}@anchor{2836}
@deffn {数据} ssl.OP_NO_TICKET

阻止客户端请求会话凭据。


3.6 新版功能.

@end deffn

@geindex OP_IGNORE_UNEXPECTED_EOF() (在 ssl 模块中)
@anchor{library/ssl ssl OP_IGNORE_UNEXPECTED_EOF}@anchor{ff0}
@deffn {数据} ssl.OP_IGNORE_UNEXPECTED_EOF

忽略 TLS 连接的意外关闭。

此选项仅适用于 OpenSSL 3.0.0 及更新的版本。


3.10 新版功能.

@end deffn

@geindex HAS_ALPN() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_ALPN}@anchor{84c}
@deffn {数据} ssl.HAS_ALPN

OpenSSL 库是否具有对 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://tools.ietf.org/html/rfc7301.html} 中描述的 @emph{应用层协议协商} TLS 扩展的内置支持。


3.5 新版功能.

@end deffn

@geindex HAS_NEVER_CHECK_COMMON_NAME() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_NEVER_CHECK_COMMON_NAME}@anchor{2837}
@deffn {数据} ssl.HAS_NEVER_CHECK_COMMON_NAME

OpenSSL 库是否具有对不检测目标通用名称的内置支持且 @ref{4ed,,SSLContext.hostname_checks_common_name} 为可写状态。


3.7 新版功能.

@end deffn

@geindex HAS_ECDH() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_ECDH}@anchor{2838}
@deffn {数据} ssl.HAS_ECDH

OpenSSL 库是否具有对基于椭圆曲线的 Diffie-Hellman 密钥交换的内置支持。 此常量应当为真值，除非发布者明确地禁用了此功能。


3.3 新版功能.

@end deffn

@geindex HAS_SNI() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_SNI}@anchor{2839}
@deffn {数据} ssl.HAS_SNI

OpenSSL 库是否具有对 @emph{服务器名称提示} 扩展（在 
@geindex RFC; RFC 6066
RFC 6066@footnote{https://tools.ietf.org/html/rfc6066.html} 中定义）的内置支持。


3.2 新版功能.

@end deffn

@geindex HAS_NPN() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_NPN}@anchor{283a}
@deffn {数据} ssl.HAS_NPN

OpenSSL 库是否具有对 应用层协议协商@footnote{https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation} 中描述的 @emph{下一协议协商} 的内置支持。 当此常量为真值时，你可以使用 @ref{b78,,SSLContext.set_npn_protocols()} 方法来公告你想要支持的协议。


3.3 新版功能.

@end deffn

@geindex HAS_SSLv2() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_SSLv2}@anchor{283b}
@deffn {数据} ssl.HAS_SSLv2

OpenSSL 库是否具有对 SSL 2.0 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex HAS_SSLv3() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_SSLv3}@anchor{283c}
@deffn {数据} ssl.HAS_SSLv3

OpenSSL 库是否具有对 SSL 3.0 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex HAS_TLSv1() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_TLSv1}@anchor{283d}
@deffn {数据} ssl.HAS_TLSv1

OpenSSL 库是否具有对 TLS 1.0 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex HAS_TLSv1_1() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_TLSv1_1}@anchor{4f7}
@deffn {数据} ssl.HAS_TLSv1_1

OpenSSL 库是否具有对 TLS 1.1 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex HAS_TLSv1_2() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_TLSv1_2}@anchor{283e}
@deffn {数据} ssl.HAS_TLSv1_2

OpenSSL 库是否具有对 TLS 1.2 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex HAS_TLSv1_3() (在 ssl 模块中)
@anchor{library/ssl ssl HAS_TLSv1_3}@anchor{283f}
@deffn {数据} ssl.HAS_TLSv1_3

OpenSSL 库是否具有对 TLS 1.3 协议的内置支持。


3.7 新版功能.

@end deffn

@geindex CHANNEL_BINDING_TYPES() (在 ssl 模块中)
@anchor{library/ssl ssl CHANNEL_BINDING_TYPES}@anchor{2840}
@deffn {数据} ssl.CHANNEL_BINDING_TYPES

受支持的 TLS 通道绑定类型组成的列表。 此列表中的字符串可被用作传给 @ref{b75,,SSLSocket.get_channel_binding()} 的参数。


3.3 新版功能.

@end deffn

@geindex OPENSSL_VERSION() (在 ssl 模块中)
@anchor{library/ssl ssl OPENSSL_VERSION}@anchor{c7a}
@deffn {数据} ssl.OPENSSL_VERSION

解释器所加载的 OpenSSL 库的版本字符串:

@example
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k  26 Jan 2017'
@end example


3.2 新版功能.

@end deffn

@geindex OPENSSL_VERSION_INFO() (在 ssl 模块中)
@anchor{library/ssl ssl OPENSSL_VERSION_INFO}@anchor{c7b}
@deffn {数据} ssl.OPENSSL_VERSION_INFO

代表 OpenSSL 库的版本信息的五个整数所组成的元组:

@example
>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)
@end example


3.2 新版功能.

@end deffn

@geindex OPENSSL_VERSION_NUMBER() (在 ssl 模块中)
@anchor{library/ssl ssl OPENSSL_VERSION_NUMBER}@anchor{c7c}
@deffn {数据} ssl.OPENSSL_VERSION_NUMBER

OpenSSL 库的原始版本号，以单个整数表示:

@example
>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'
@end example


3.2 新版功能.

@end deffn

@geindex ALERT_DESCRIPTION_HANDSHAKE_FAILURE() (在 ssl 模块中)
@geindex ALERT_DESCRIPTION_INTERNAL_ERROR() (在 ssl 模块中)
@anchor{library/ssl ssl ALERT_DESCRIPTION_HANDSHAKE_FAILURE}@anchor{2841}
@deffn {数据} ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE
@anchor{library/ssl ssl ALERT_DESCRIPTION_INTERNAL_ERROR}@anchor{2842}
@deffnx {数据} ssl.ALERT_DESCRIPTION_INTERNAL_ERROR

@deffnx {数据} ALERT_DESCRIPTION_*

来自 
@geindex RFC; RFC 5246
RFC 5246@footnote{https://tools.ietf.org/html/rfc5246.html} 等文档的警报描述。 IANA TLS Alert Registry@footnote{https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6} 中包含了这个列表及对定义其含义的 RFC 引用。

被用作 @ref{9bf,,SSLContext.set_servername_callback()} 中的回调函数的返回值。


3.4 新版功能.

@end deffn

@geindex AlertDescription (ssl 中的类)
@anchor{library/ssl ssl AlertDescription}@anchor{2843}
@deffn {类} ssl.AlertDescription

ALERT_DESCRIPTION_* 常量的 @ref{68e,,enum.IntEnum} 多项集。


3.6 新版功能.

@end deffn

@geindex Purpose.SERVER_AUTH() (在 ssl 模块中)
@anchor{library/ssl ssl Purpose SERVER_AUTH}@anchor{9bb}
@deffn {数据} Purpose.SERVER_AUTH

@ref{9b0,,create_default_context()} 和 @ref{9ba,,SSLContext.load_default_certs()} 的选项值。 这个值表明此上下文可以被用来验证 Web 服务器（因此，它将被用来创建客户端套接字）。


3.4 新版功能.

@end deffn

@geindex Purpose.CLIENT_AUTH() (在 ssl 模块中)
@anchor{library/ssl ssl Purpose CLIENT_AUTH}@anchor{9bc}
@deffn {数据} Purpose.CLIENT_AUTH

@ref{9b0,,create_default_context()} 和 @ref{9ba,,SSLContext.load_default_certs()} 的选项值。 这个值表明此上下文可以被用来验证 Web 客户端（因此，它将被用来创建服务器端套接字）。


3.4 新版功能.

@end deffn

@geindex SSLErrorNumber (ssl 中的类)
@anchor{library/ssl ssl SSLErrorNumber}@anchor{2844}
@deffn {类} ssl.SSLErrorNumber

SSL_ERROR_* 常量的 @ref{68e,,enum.IntEnum} 多项集。


3.6 新版功能.

@end deffn

@geindex TLSVersion (ssl 中的类)
@anchor{library/ssl ssl TLSVersion}@anchor{2845}
@deffn {类} ssl.TLSVersion

@ref{4f6,,SSLContext.maximum_version} 和 @ref{4f5,,SSLContext.minimum_version} 中的 SSL 和 TLS 版本的 @ref{68e,,enum.IntEnum} 多项集。


3.7 新版功能.

@end deffn

@geindex MINIMUM_SUPPORTED (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion MINIMUM_SUPPORTED}@anchor{2846}
@deffn {属性} TLSVersion.MINIMUM_SUPPORTED
@end deffn

@geindex MAXIMUM_SUPPORTED (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion MAXIMUM_SUPPORTED}@anchor{2847}
@deffn {属性} TLSVersion.MAXIMUM_SUPPORTED

受支持的最低和最高 SSL 或 TLS 版本。 这些常量被称为魔术常量。 它们的值并不反映可用的最低和最高 TLS/SSL 版本。
@end deffn

@geindex SSLv3 (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion SSLv3}@anchor{2848}
@deffn {属性} TLSVersion.SSLv3
@end deffn

@geindex TLSv1 (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion TLSv1}@anchor{2849}
@deffn {属性} TLSVersion.TLSv1
@end deffn

@geindex TLSv1_1 (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion TLSv1_1}@anchor{284a}
@deffn {属性} TLSVersion.TLSv1_1
@end deffn

@geindex TLSv1_2 (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion TLSv1_2}@anchor{284b}
@deffn {属性} TLSVersion.TLSv1_2
@end deffn

@geindex TLSv1_3 (ssl.TLSVersion 属性)
@anchor{library/ssl ssl TLSVersion TLSv1_3}@anchor{284c}
@deffn {属性} TLSVersion.TLSv1_3

SSL 3.0 至 TLS 1.3。
@end deffn

@node SSL 套接字,SSL 上下文,方法、常量和异常处理,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl ssl-sockets}@anchor{284d}
@subsubsection SSL 套接字


@geindex SSLSocket (ssl 中的类)
@anchor{library/ssl ssl SSLSocket}@anchor{192}
@deffn {类} ssl.SSLSocket (socket.socket)

SSL 套接字提供了 @ref{27e6,,套接字对象} 的下列方法:


@itemize -

@item 
@ref{772,,accept()}

@item 
@ref{27f4,,bind()}

@item 
@ref{701,,close()}

@item 
@ref{773,,connect()}

@item 
@ref{c76,,detach()}

@item 
@ref{27f8,,fileno()}

@item 
@ref{2753,,getpeername()}, @ref{2754,,getsockname()}

@item 
@ref{683,,getsockopt()}, @ref{684,,setsockopt()}

@item 
@ref{27f9,,gettimeout()}, @ref{27cb,,settimeout()},
@ref{20a0,,setblocking()}

@item 
@ref{844,,listen()}

@item 
@ref{bf5,,makefile()}

@item 
@ref{774,,recv()}, @ref{d82,,recv_into()}
(but passing a non-zero @code{flags} argument is not allowed)

@item 
@ref{777,,send()}, @ref{778,,sendall()} (with
the same limitation)

@item 
@ref{843,,sendfile()} (but @ref{46a,,os.sendfile} will be used
for plain-text sockets only, else @ref{777,,send()} will be used)

@item 
@ref{27f5,,shutdown()}
@end itemize

但是，由于 SSL（和 TLS）协议在 TCP 之上具有自己的框架，因此 SSL 套接字抽象在某些方面可能与常规的 OS 层级套接字存在差异。 特别是要查看 @ref{2810,,非阻塞型套接字说明}。

@ref{192,,SSLSocket} 的实例必须使用 @ref{4f3,,SSLContext.wrap_socket()} 方法来创建。


在 3.5 版更改: 新增了 @code{sendfile()} 方法。



在 3.5 版更改: @code{shutdown()} 不会在每次接收或发送字节数据后重置套接字超时。 现在套接字超时为关闭的最大总持续时间。



3.6 版后已移除: 直接创建 @ref{192,,SSLSocket} 实例的做法已被弃用，请使用 @ref{4f3,,SSLContext.wrap_socket()} 来包装套接字。



在 3.7 版更改: @ref{192,,SSLSocket} 的实例必须使用 @ref{4f3,,wrap_socket()} 来创建。 在较早的版本中，直接创建实例是可能的。 但这从未被记入文档或是被正式支持。

@end deffn

SSL 套接字还具有下列方法和属性:

@geindex read() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket read}@anchor{854}
@deffn {方法} SSLSocket.read (len=1024, buffer=None)

从 SSL 套接字读取至多 @emph{len} 个字节的数据并将结果作为 @code{bytes} 实例返回。 如果指定了 @emph{buffer}，则改为读取到缓冲区，并返回所读取的字节数。

如果套接字为 @ref{2810,,非阻塞型} 则会引发 @ref{84f,,SSLWantReadError} 或 @ref{850,,SSLWantWriteError} 且读取将阻塞。

由于在任何时候重新协商都是可能的，因此调用 @ref{854,,read()} 也可能导致写入操作。


在 3.5 版更改: 套接字超时在每次接收或发送字节数据后不会再被重置。 现在套接字超时为读取至多 @emph{len} 个字节数据的最大总持续时间。



3.6 版后已移除: 请使用 @code{recv()} 来代替 @ref{854,,read()}。

@end deffn

@geindex write() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket write}@anchor{855}
@deffn {方法} SSLSocket.write (buf)

将 @emph{buf} 写入到 SSL 套接字并返回所写入的字节数。 @emph{buf} 参数必须为支持缓冲区接口的对象。

如果套接字为 @ref{2810,,非阻塞型} 则会引发 @ref{84f,,SSLWantReadError} 或 @ref{850,,SSLWantWriteError} 且读取将阻塞。

由于在任何时候重新协商都是可能的，因此调用 @ref{855,,write()} 也可能导致读取操作。


在 3.5 版更改: 套接字超时在每次接收或发送字节数据后不会再被重置。 现在套接字超时为写入 @emph{buf} 的最大总持续时间。



3.6 版后已移除: 请使用 @code{send()} 来代替 @ref{855,,write()}。

@end deffn

@cartouche
@quotation 注解 
@ref{854,,read()} 和 @ref{855,,write()} 方法是读写未加密的应用级数据，并将其解密/加密为带加密的线路级数据的低层级方法。 这些方法需要有激活的 SSL 连接，即握手已完成而 @ref{284e,,SSLSocket.unwrap()} 尚未被调用。

通常你应当使用套接字 API 方法例如 @ref{774,,recv()} 和 @ref{777,,send()} 来代替这些方法。
@end quotation
@end cartouche

@geindex do_handshake() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket do_handshake}@anchor{853}
@deffn {方法} SSLSocket.do_handshake ()

执行 SSL 设置握手。


在 3.4 版更改: 当套接字的 @ref{284f,,context} 的 @ref{2824,,check_hostname} 属性为真值时此握手方法还会执行 @ref{4eb,,match_hostname()}。



在 3.5 版更改: 套接字超时在每次接收或发送字节数据时不会再被重置。 现在套接字超时为握手的最大总持续时间。



在 3.7 版更改: 主机名或 IP 地址会在握手期间由 OpenSSL 进行匹配。 函数 @ref{4eb,,match_hostname()} 将不再被使用。 在 OpenSSL 拒绝主机名和 IP 地址的情况下，握手将提前被中止并向对等方发送 TLS 警告消息。

@end deffn

@geindex getpeercert() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket getpeercert}@anchor{9c0}
@deffn {方法} SSLSocket.getpeercert (binary_form=False)

如果连接另一端的对等方没有证书，则返回 @code{None}。 如果 SSL 握手还未完成，则会引发 @ref{16d,,ValueError}。

如果 @code{binary_form} 形参为 @ref{497,,False}，并且从对等方接收到了证书，此方法将返回一个 @ref{164,,dict} 实例。 如果证书未通过验证，则字典将为空。 如果证书通过验证，它将返回由多个密钥组成的字典，其中包括 @code{subject} (证书颁发给的主体) 和 @code{issuer} (颁发证书的主体)。 如果证书包含一个 @emph{Subject Alternative Name} 扩展的实例 (see 
@geindex RFC; RFC 3280
RFC 3280@footnote{https://tools.ietf.org/html/rfc3280.html})，则字典中还将有一个 @code{subjectAltName} 键。

@code{subject} 和 @code{issuer} 字段都是包含在证书中相应字段的数据结构中给出的相对专有名称（RDN）序列的元组，每个 RDN 均为 name-value 对的序列。 这里是一个实际的示例:

@example
@{'issuer': ((('countryName', 'IL'),),
            (('organizationName', 'StartCom Ltd.'),),
            (('organizationalUnitName',
              'Secure Digital Certificate Signing'),),
            (('commonName',
              'StartCom Class 2 Primary Intermediate Server CA'),)),
 'notAfter': 'Nov 22 08:15:19 2013 GMT',
 'notBefore': 'Nov 21 03:09:52 2011 GMT',
 'serialNumber': '95F0',
 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'California'),),
             (('localityName', 'San Francisco'),),
             (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
             (('commonName', '*.eff.org'),),
             (('emailAddress', 'hostmaster@@eff.org'),)),
 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
 'version': 3@}
@end example

@cartouche
@quotation 注解 
要验证特定服务的证书，你可以使用 @ref{4eb,,match_hostname()} 函数。
@end quotation
@end cartouche

如果 @code{binary_form} 形参为 @ref{59c,,True}，并且提供了证书，此方法会将整个证书的 DER 编码形式作为字节序列返回，或者如果对等方未提供证书则返回 @ref{204,,None}。 对等方是否提供证书取决于 SSL 套接字的角色:


@itemize *

@item 
对于客户端 SSL 套接字，服务器将总是提供证书，无论是否需要进行验证;

@item 
对于服务器 SSL 套接字，客户端将仅在服务器要求时才提供证书；因此如果你使用了 @ref{2821,,CERT_NONE} (而不是 @ref{2823,,CERT_OPTIONAL} 或 @ref{280c,,CERT_REQUIRED}) 则 @ref{9c0,,getpeercert()} 将返回 @ref{204,,None}。
@end itemize


在 3.2 版更改: 返回的字典包括额外的条目例如 @code{issuer} 和 @code{notBefore}。



在 3.4 版更改: 如果握手未完成则会引发 @ref{16d,,ValueError}。 返回的字典包括额外的 X509v3 扩展条目例如 @code{crlDistributionPoints}, @code{caIssuers} 和 @code{OCSP} URI。



在 3.9 版更改: IPv6 地址字符串不再附带末尾换行符。

@end deffn

@geindex cipher() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket cipher}@anchor{2755}
@deffn {方法} SSLSocket.cipher ()

返回由三个值组成的元组，其中包含所使用的密码名称，定义其使用方式的 SSL 协议版本，以及所使用的加密比特位数。 如果尚未建立连接，则返回 @code{None}。
@end deffn

@geindex shared_ciphers() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket shared_ciphers}@anchor{852}
@deffn {方法} SSLSocket.shared_ciphers ()

返回在握手期间由客户端共享的密码列表。 所返回列表的每个条目都是由三个值组成的元组，其中包括密码名称，定义其使用方式的 SSL 协议版本，以及密码所使用的加密比特位数。 如果尚未建立连接或套接字为客户端套接字则 @ref{852,,shared_ciphers()} 将返回 @code{None}。


3.5 新版功能.

@end deffn

@geindex compression() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket compression}@anchor{b76}
@deffn {方法} SSLSocket.compression ()

以字符串形式返回所使用的压缩算法，或者如果连接没有使用压缩则返回 @code{None}。

如果高层级的协议支持自己的压缩机制，你可以使用 @ref{b77,,OP_NO_COMPRESSION} 来禁用 SSL 层级的压缩。


3.3 新版功能.

@end deffn

@geindex get_channel_binding() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket get_channel_binding}@anchor{b75}
@deffn {方法} SSLSocket.get_channel_binding (cb_type="tls-unique")

为当前连接获取字节串形式的通道绑定数据。 如果尚未连接或握手尚未完成则返回 @code{None}。

@emph{cb_type} 形参允许选择需要的通道绑定类型。 有效的通道绑定类型在 @ref{2840,,CHANNEL_BINDING_TYPES} 列表中列出。 目前只支持由 
@geindex RFC; RFC 5929
RFC 5929@footnote{https://tools.ietf.org/html/rfc5929.html} 所定义的 'tls-unique' 通道绑定。 如果请求了一个不受支持的通道绑定类型则将引发 @ref{16d,,ValueError}。


3.3 新版功能.

@end deffn

@geindex selected_alpn_protocol() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket selected_alpn_protocol}@anchor{84b}
@deffn {方法} SSLSocket.selected_alpn_protocol ()

返回在 TLS 握手期间所选择的协议。 如果 @ref{84a,,SSLContext.set_alpn_protocols()} 未被调用，如果另一方不支持 ALPN，如果此套接字不支持任何客户端所用的协议，或者如果握手尚未发生，则将返回 @code{None}。


3.5 新版功能.

@end deffn

@geindex selected_npn_protocol() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket selected_npn_protocol}@anchor{2850}
@deffn {方法} SSLSocket.selected_npn_protocol ()

返回在Return the higher-level protocol that was selected during the TLS/SSL 握手期间所选择的高层级协议。 如果 @ref{b78,,SSLContext.set_npn_protocols()} 未被调用，或者如果另一方不支持 NPN，或者如果握手尚未发生，则将返回 @code{None}。


3.3 新版功能.

@end deffn

@geindex unwrap() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket unwrap}@anchor{284e}
@deffn {方法} SSLSocket.unwrap ()

执行 SSL 关闭握手，这会从下层的套接字中移除 TLS 层，并返回下层的套接字对象。 这可被用来通过一个连接将加密操作转为非加密。 返回的套接字应当总是被用于同连接另一方的进一步通信，而不是原始的套接字。
@end deffn

@geindex verify_client_post_handshake() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket verify_client_post_handshake}@anchor{359}
@deffn {方法} SSLSocket.verify_client_post_handshake ()

向一个 TLS 1.3 客户端请求握手后身份验证（PHA）。 只有在初始 TLS 握手之后且双方都启用了 PHA 的情况下才能为服务器端套接字的 TLS 1.3 连接启用 PHA，参见 @ref{358,,SSLContext.post_handshake_auth}。

此方法不会立即执行证书交换。 服务器端会在下一次写入事件期间发送 CertificateRequest 并期待客户端在下一次读取事件期间附带证书进行响应。

如果有任何前置条件未被满足（例如非 TLS 1.3，PHA 未启用），则会引发 @ref{ce2,,SSLError}。

@cartouche
@quotation 注解 
仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 没有 TLS 1.3 支持，此方法将引发 @ref{70e,,NotImplementedError}。
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@geindex version() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket version}@anchor{84e}
@deffn {方法} SSLSocket.version ()

以字符串形式返回由连接协商确定的实际 SSL 协议版本，或者如果未建立安全连接则返回 @code{None}。 在撰写本文档时，可能的返回值包括 @code{"SSLv2"}, @code{"SSLv3"}, @code{"TLSv1"}, @code{"TLSv1.1"} 和 @code{"TLSv1.2"}。 最新的 OpenSSL 版本可能会定义更多的返回值。


3.5 新版功能.

@end deffn

@geindex pending() (ssl.SSLSocket 方法)
@anchor{library/ssl ssl SSLSocket pending}@anchor{2851}
@deffn {方法} SSLSocket.pending ()

返回在连接上等待被读取的已解密字节数。
@end deffn

@geindex context (ssl.SSLSocket 属性)
@anchor{library/ssl ssl SSLSocket context}@anchor{284f}
@deffn {属性} SSLSocket.context

此 SSL 套接字所联结的 @ref{4f2,,SSLContext} 对象。 如果 SSL 套接字是使用已弃用的 @ref{579,,wrap_socket()} 函数 (而非 @ref{4f3,,SSLContext.wrap_socket()}) 创建的，则这将是为此 SSL 套接字创建的自定义上下文对象。


3.2 新版功能.

@end deffn

@geindex server_side (ssl.SSLSocket 属性)
@anchor{library/ssl ssl SSLSocket server_side}@anchor{2852}
@deffn {属性} SSLSocket.server_side

一个布尔值，对于服务器端套接字为 @code{True} 而对于客户端套接字则为 @code{False}。


3.2 新版功能.

@end deffn

@geindex server_hostname (ssl.SSLSocket 属性)
@anchor{library/ssl ssl SSLSocket server_hostname}@anchor{4ef}
@deffn {属性} SSLSocket.server_hostname

服务器的主机名: @ref{206,,str} 类型，对于服务器端套接字或者如果构造器中未指定主机名则为 @code{None}。


3.2 新版功能.



在 3.7 版更改: 现在该属性将始终为 ASCII 文本。 当 @code{server_hostname} 为一个国际化域名（IDN）时，该属性现在会保存为 A 标签形式 (@code{"xn--pythn-mua.org"}) 而非 U 标签形式 (@code{"pythön.org"})。

@end deffn

@geindex session (ssl.SSLSocket 属性)
@anchor{library/ssl ssl SSLSocket session}@anchor{2853}
@deffn {属性} SSLSocket.session

用于 SSL 连接的 @ref{68c,,SSLSession}。 该会话将在执行 TLS 握手后对客户端和服务器端套接字可用。 对于客户端套接字该会话可以在调用 @ref{853,,do_handshake()} 之前被设置以重用一个会话。


3.6 新版功能.

@end deffn

@geindex session_reused (ssl.SSLSocket 属性)
@anchor{library/ssl ssl SSLSocket session_reused}@anchor{2854}
@deffn {属性} SSLSocket.session_reused


3.6 新版功能.

@end deffn

@node SSL 上下文,证书,SSL 套接字,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl ssl-contexts}@anchor{2855}
@subsubsection SSL 上下文



3.2 新版功能.


SSL 上下文可保存各种比单独 SSL 连接寿命更长的数据，例如 SSL 配置选项，证书和私钥等。 它还可为服务器端套接字管理缓存，以加快来自相同客户端的重复连接。

@geindex SSLContext (ssl 中的类)
@anchor{library/ssl ssl SSLContext}@anchor{4f2}
@deffn {类} ssl.SSLContext (protocol=PROTOCOL_TLS)

创建一个新的 SSL 上下文。 你可以传入 @emph{protocol}，它必须为此模块中定义的 @code{PROTOCOL_*} 常量之一。 该形参指定要使用哪个 SSL 协议版本。 通常，服务器会选择一个特定的协议版本，而客户端必须适应服务器的选择。 大多数版本都不能与其他版本互操作。 如果未指定，则默认值为 @ref{2809,,PROTOCOL_TLS}；它提供了与其他版本的最大兼容性。

这个表显示了客户端（横向）的哪个版本能够连接服务器（纵向）的哪个版本。

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
@item

@emph{客户端} / @strong{服务器}

@tab

@strong{SSLv2}

@tab

@strong{SSLv3}

@tab

@strong{TLS} @footnote{@w{(3)} 
TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 @ref{2809,,PROTOCOL_TLS} 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。
}

@tab

@strong{TLSv1}

@tab

@strong{TLSv1.1}

@tab

@strong{TLSv1.2}

@item

@emph{SSLv2}

@tab

是

@tab

否

@tab

否 @footnote{@w{(1)} 
@ref{4f2,,SSLContext} 默认设置 @ref{c79,,OP_NO_SSLv2} 以禁用 SSLv2。
}

@tab

否

@tab

否

@tab

否

@item

@emph{SSLv3}

@tab

否

@tab

是

@tab

否 @footnote{@w{(2)} 
@ref{4f2,,SSLContext} 默认设置 @ref{280a,,OP_NO_SSLv3} 以禁用 SSLv3。
}

@tab

否

@tab

否

@tab

否

@item

@emph{TLS} (@emph{SSLv23}) @footnote{@w{(3)} 
TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 @ref{2809,,PROTOCOL_TLS} 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。
}

@tab

否 @footnote{@w{(1)} 
@ref{4f2,,SSLContext} 默认设置 @ref{c79,,OP_NO_SSLv2} 以禁用 SSLv2。
}

@tab

否 @footnote{@w{(2)} 
@ref{4f2,,SSLContext} 默认设置 @ref{280a,,OP_NO_SSLv3} 以禁用 SSLv3。
}

@tab

是

@tab

是

@tab

是

@tab

是

@item

@emph{TLSv1}

@tab

否

@tab

否

@tab

是

@tab

是

@tab

否

@tab

否

@item

@emph{TLSv1.1}

@tab

否

@tab

否

@tab

是

@tab

否

@tab

是

@tab

否

@item

@emph{TLSv1.2}

@tab

否

@tab

否

@tab

是

@tab

否

@tab

否

@tab

是

@end multitable

@end quotation


@subsubheading 参见


@ref{9b0,,create_default_context()} 让 @ref{f3,,ssl} 为特定目标选择安全设置。



在 3.6 版更改: 上下文会使用安全默认值来创建。 默认设置的选项有 @ref{b77,,OP_NO_COMPRESSION}, @ref{b7c,,OP_CIPHER_SERVER_PREFERENCE}, @ref{2832,,OP_SINGLE_DH_USE}, @ref{2833,,OP_SINGLE_ECDH_USE}, @ref{c79,,OP_NO_SSLv2} (except for @ref{282a,,PROTOCOL_SSLv2}) 和 @ref{280a,,OP_NO_SSLv3} (except for @ref{281b,,PROTOCOL_SSLv3})。 初始密码集列表只包含 @code{HIGH} 密码，不包含 @code{NULL} 密码和 @code{MD5} 密码 (@ref{282a,,PROTOCOL_SSLv2} 除外)。

@end deffn

@ref{4f2,,SSLContext} 对象具有以下方法和属性:

@geindex cert_store_stats() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext cert_store_stats}@anchor{9b3}
@deffn {方法} SSLContext.cert_store_stats ()

获取以字典表示的有关已加载的 X.509 证书数量，被标记为 CA 证书的 X.509 证书数量以及证书吊销列表的统计信息。

具有一个 CA 证书和一个其他证书的上下文示例:

@example
>>> context.cert_store_stats()
@{'crl': 0, 'x509_ca': 1, 'x509': 2@}
@end example


3.4 新版功能.

@end deffn

@geindex load_cert_chain() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext load_cert_chain}@anchor{b72}
@deffn {方法} SSLContext.load_cert_chain (certfile, keyfile=None, password=None)

加载一个私钥及对应的证书。 @emph{certfile} 字符串必须为以 PEM 格式表示的单个文件路径，该文件中包含证书以及确立证书真实性所需的任意数量的 CA 证书。 如果存在 @emph{keyfile} 字符串，它必须指向一个包含私钥的文件。 否则私钥也将从 @emph{certfile} 中提取。 请参阅 @ref{2856,,证书} 中的讨论来了解有关如何将证书存储至 @emph{certfile} 的更多信息。

@emph{password} 参数可以是一个函数，调用时将得到用于解密私钥的密码。 它在私钥被加密且需要密码时才会被调用。 它调用时将不带任何参数，并且应当返回一个字符串、字节串或字节数组。 如果返回值是一个字符串，在用它解密私钥之前它将以 UTF-8 进行编码。 或者也可以直接将字符串、字节串或字节数组值作为 @emph{password} 参数提供。 如果私钥未被加密且不需要密码则它将被忽略。

如果未指定 @emph{password} 参数且需要一个密码，将会使用 OpenSSL 内置的密码提示机制来交互式地提示用户输入密码。

如果私钥不能匹配证书则会引发 @ref{ce2,,SSLError}。


在 3.3 版更改: 新增可选参数 @emph{password}。

@end deffn

@geindex load_default_certs() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext load_default_certs}@anchor{9ba}
@deffn {方法} SSLContext.load_default_certs (purpose=Purpose.SERVER_AUTH)

从默认位置加载一组默认的 "证书颁发机构" (CA) 证书。 在 Windows 上它将从 @code{CA} 和 @code{ROOT} 系统存储中加载 CA 证书。 在所有系统上它会调用 @ref{9b2,,SSLContext.set_default_verify_paths()} 。 将来该方法也可能会从其他位置加载 CA 证书。

@emph{purpose} 旗标指明要加载哪一类 CA 证书。 默认设置 @ref{9bb,,Purpose.SERVER_AUTH} 加载被标记且被信任用于 TLS Web 服务器验证（客户端套接字）的证书。 @ref{9bc,,Purpose.CLIENT_AUTH} 则加载用于在服务器端进行客户端证书验证的 CA 证书。


3.4 新版功能.

@end deffn

@geindex load_verify_locations() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext load_verify_locations}@anchor{8e2}
@deffn {方法} SSLContext.load_verify_locations (cafile=None, capath=None, cadata=None)

当 @ref{280b,,verify_mode} 不为 @ref{2821,,CERT_NONE} 时加载一组用于验证其他对等方证书的 "证书颁发机构" (CA) 证书。 必须至少指定 @emph{cafile} 或 @emph{capath} 中的一个。

此方法还可加载 PEM 或 DER 格式的证书吊销列表 (CRL)，为此必须正确配置 @ref{9b5,,SSLContext.verify_flags}。

如果存在 @emph{cafile} 字符串，它应为 PEM 格式的级联 CA 证书文件的路径。 请参阅 @ref{2856,,证书} 中的讨论来了解有关如何处理此文件中的证书的更多信息。

如果存在 @emph{capath} 字符串，它应为包含多个 PEM 格式的 CA 证书的目录的路径，并遵循 OpenSSL 专属布局@footnote{https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html}。

如果存在 @emph{cadata} 对象，它应为一个或多个 PEM 编码的证书的 ASCII 字符串或者 DER 编码的证书的 @ref{6e9,,bytes-like object}。 与 @emph{capath} 一样 PEM 编码的证书之外的多余行会被忽略，但至少要有一个证书。


在 3.4 版更改: 新增可选参数 @emph{cadata}

@end deffn

@geindex get_ca_certs() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext get_ca_certs}@anchor{9b4}
@deffn {方法} SSLContext.get_ca_certs (binary_form=False)

获取已离开法人 "证书颁发机构" (CA) 证书列表。 如果 @code{binary_form} 形参为 @ref{497,,False} 则每个列表条目都是一个类似于 @ref{9c0,,SSLSocket.getpeercert()} 输出的字典。 在其他情况下此方法将返回一个 DER 编码的证书的列表。 返回的列表不包含来自 @emph{capath} 的证书，除非 SSL 连接请求并加载了一个证书。

@cartouche
@quotation 注解 
capath 目录中的证书不会被加载，除非它们已至少被使用过一次。
@end quotation
@end cartouche


3.4 新版功能.

@end deffn

@geindex get_ciphers() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext get_ciphers}@anchor{68d}
@deffn {方法} SSLContext.get_ciphers ()

获取已启用密码的列表。 该列表将按密码的优先级排序。 参见 @ref{281f,,SSLContext.set_ciphers()}。

示例:

@example
>>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
>>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
>>> ctx.get_ciphers()  # OpenSSL 1.0.x
[@{'alg_bits': 256,
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'id': 50380848,
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1/SSLv3',
  'strength_bits': 256@},
 @{'alg_bits': 128,
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'id': 50380847,
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1/SSLv3',
  'strength_bits': 128@}]
@end example

在 OpenSSL 1.1 及更新的版本中密码字典会包含额外的字段:

@example
>>> ctx.get_ciphers()  # OpenSSL 1.1+
[@{'aead': True,
  'alg_bits': 256,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'digest': None,
  'id': 50380848,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1.2',
  'strength_bits': 256,
  'symmetric': 'aes-256-gcm'@},
 @{'aead': True,
  'alg_bits': 128,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'digest': None,
  'id': 50380847,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1.2',
  'strength_bits': 128,
  'symmetric': 'aes-128-gcm'@}]
@end example

@ref{14c1,,可用性}: OpenSSL 1.0.2+。


3.6 新版功能.

@end deffn

@geindex set_default_verify_paths() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext set_default_verify_paths}@anchor{9b2}
@deffn {方法} SSLContext.set_default_verify_paths ()

从构建 OpenSSL 库时定义的文件系统路径中加载一组默认的 "证书颁发机构" (CA) 证书。 不幸的是，没有一种简单的方式能知道此方法是否执行成功：如果未找到任何证书也不会返回错误。 不过，当 OpenSSL 库是作为操作系统的一部分被提供时，它的配置应当是正确的。
@end deffn

@geindex set_ciphers() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext set_ciphers}@anchor{281f}
@deffn {方法} SSLContext.set_ciphers (ciphers)

为使用此上下文创建的套接字设置可用密码。 它应当为 OpenSSL 密码列表格式@footnote{https://www.openssl.org/docs/manmaster/man1/ciphers.html} 的字符串。 如果没有可被选择的密码（由于编译时选项或其他配置禁止使用所指定的任何密码），则将引发 @ref{ce2,,SSLError}。

@cartouche
@quotation 注解 
在连接后，SSL 套接字的 @ref{2755,,SSLSocket.cipher()} 方法将给出当前所选择的密码。

在默认情况下 OpenSSL 1.1.1 会启用 TLS 1.3 密码套件。 该套件不能通过 @ref{281f,,set_ciphers()} 来禁用。
@end quotation
@end cartouche
@end deffn

@geindex set_alpn_protocols() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext set_alpn_protocols}@anchor{84a}
@deffn {方法} SSLContext.set_alpn_protocols (protocols)

指定在 SSL/TLS 握手期间套接字应当通告的协议。 它应为由 ASCII 字符串组成的列表，例如 @code{['http/1.1', 'spdy/2']}，按首选顺序排列。 协议的选择将在握手期间发生，并依据 
@geindex RFC; RFC 7301
RFC 7301@footnote{https://tools.ietf.org/html/rfc7301.html} 来执行。 在握手成功后，@ref{84b,,SSLSocket.selected_alpn_protocol()} 方法将返回已达成一致的协议。

如果 @ref{84c,,HAS_ALPN} 为 @code{False} 则此方法将引发 @ref{70e,,NotImplementedError}。

当双方都支持 ALPN 但不能就协议达成一致时 OpenSSL 1.1.0 至 1.1.0e 将中止并引发 @ref{ce2,,SSLError}。 1.1.0f+ 的行为类似于 1.0.2，@ref{84b,,SSLSocket.selected_alpn_protocol()} 返回 None。


3.5 新版功能.

@end deffn

@geindex set_npn_protocols() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext set_npn_protocols}@anchor{b78}
@deffn {方法} SSLContext.set_npn_protocols (protocols)

指定在Specify which protocols the socket should advertise during the SSL/TLS 握手期间套接字应当通告的协议。 它应为由字符串组成的列表，例如 @code{['http/1.1', 'spdy/2']}，按首选顺序排列。 协议的选择将在握手期间发生，并将依据 应用层协议协商@footnote{https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation} 来执行。 在握手成功后，@ref{2850,,SSLSocket.selected_npn_protocol()} 方法将返回已达成一致的协议。

如果 @ref{283a,,HAS_NPN} 为 @code{False} 则此方法将引发 @ref{70e,,NotImplementedError}。


3.3 新版功能.

@end deffn

@geindex sni_callback (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext sni_callback}@anchor{1005}
@deffn {属性} SSLContext.sni_callback

注册一个回调函数，当 TLS 客户端指定了一个服务器名称提示时，该回调函数将在 SSL/TLS 服务器接收到 TLS Client Hello 握手消息后被调用。 服务器名称提示机制的定义见 
@geindex RFC; RFC 6066
RFC 6066@footnote{https://tools.ietf.org/html/rfc6066.html} section 3 - Server Name Indication。

每个 @code{SSLContext} 只能设置一个回调。 如果 @emph{sni_callback} 被设置为 @code{None} 则会禁用回调。 对该函数的后续调用将禁用之前注册的回调。

此回调函数将附带三个参数来调用；第一个参数是 @ref{192,,ssl.SSLSocket}，第二个参数是代表客户端准备与之通信的服务器的字符串 (或者如果 TLS Client Hello 不包含服务器名称则为 @ref{204,,None}) 而第三个参数是原来的 @ref{4f2,,SSLContext}。 服务器名称参数为文本形式。 对于国际化域名，服务器名称是一个 IDN A 标签 (@code{"xn--pythn-mua.org"})。

此回调的一个典型用法是将 @ref{192,,ssl.SSLSocket} 的 @ref{284f,,SSLSocket.context} 属性修改为一个 @ref{4f2,,SSLContext} 类型的新对象，该对象代表与服务器相匹配的证书链。

由于 TLS 连接处于早期协商阶段，因此仅能使用有限的方法和属性例如 @ref{84b,,SSLSocket.selected_alpn_protocol()} 和 @ref{284f,,SSLSocket.context}。 @ref{9c0,,SSLSocket.getpeercert()}, @ref{2755,,SSLSocket.cipher()} 和 @ref{b76,,SSLSocket.compression()} 方法要求 TLS 连接已经过 TLS Client Hello 因而将既不返回有意义的值，也不能安全地调用它们。

@emph{sni_callback} 函数必须返回 @code{None} 以允许 TLS 协商继续进行。 如果想要 TLS 失败，则可以返回常量 @ref{2842,,ALERT_DESCRIPTION_*}。 其他返回值将导致 TLS 的致命错误 @ref{2842,,ALERT_DESCRIPTION_INTERNAL_ERROR}。

如果从 @emph{sni_callback} 函数引发了异常，则 TLS 连接将终止并发出 TLS 致命警告消息 @ref{2841,,ALERT_DESCRIPTION_HANDSHAKE_FAILURE}。

如果 OpenSSL library 库在构建时定义了 OPENSSL_NO_TLSEXT 则此方法将返回 @ref{70e,,NotImplementedError}。


3.7 新版功能.

@end deffn

@geindex set_servername_callback (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext set_servername_callback}@anchor{9bf}
@deffn {属性} SSLContext.set_servername_callback (server_name_callback)

这是被保留用于向下兼容的旧式 API。 在可能的情况下，你应当改用 @ref{1005,,sni_callback}。 给出的 @emph{server_name_callback} 类似于 @emph{sni_callback}，不同之处在于当服务器主机名是 IDN 编码的国际化域名时，@emph{server_name_callback} 会接收到一个已编码的 U 标签 (@code{"pythön.org"})。

如果发生了服务器名称解码错误。 TLS 连接将终止并向客户端发出 @ref{2842,,ALERT_DESCRIPTION_INTERNAL_ERROR} 最严重 TLS 警告消息。


3.4 新版功能.

@end deffn

@geindex load_dh_params() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext load_dh_params}@anchor{b73}
@deffn {方法} SSLContext.load_dh_params (dhfile)

加载密钥生成参数用于 Diffie-Hellman (DH) 密钥交换。 使用 DH 密钥交换能以消耗（服务器和客户端的）计算资源为代价提升前向保密性。 @emph{dhfile} 参数应当为指向一个包含 PEM 格式的 DH 形参的文件的路径。

此设置不会应用于客户端套接字。 你还可以使用 @ref{2832,,OP_SINGLE_DH_USE} 选项来进一步提升安全性。


3.3 新版功能.

@end deffn

@geindex set_ecdh_curve() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext set_ecdh_curve}@anchor{b74}
@deffn {方法} SSLContext.set_ecdh_curve (curve_name)

为基于椭圆曲线的 Elliptic Curve-based Diffie-Hellman (ECDH) 密钥交换设置曲线名称。 ECDH 显著快于常规 DH 同时据信同样安全。 @emph{curve_name} 形参应为描述某个知名椭圆曲线的字符串，例如受到广泛支持的曲线 @code{prime256v1}。

此设置不会应用于客户端套接字。 你还可以使用 @ref{2833,,OP_SINGLE_ECDH_USE} 选项来进一步提升安全性。

如果 @ref{2838,,HAS_ECDH} 为 @code{False} 则此方法将不可用。


3.3 新版功能.



@subsubheading 参见



@table @asis

@item SSL/TLS 与完美的前向保密性@footnote{https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy}

Vincent Bernat。
@end table

@end deffn

@geindex wrap_socket() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext wrap_socket}@anchor{4f3}
@deffn {方法} SSLContext.wrap_socket (sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)

包装一个现有的 Python 套接字 @emph{sock} 并返回一个 @ref{2857,,SSLContext.sslsocket_class} 的实例 (默认为 @ref{192,,SSLSocket})。 返回的 SSL 套接字会绑定上下文、设置以及证书。 @emph{sock} 必须是一个 @ref{d5a,,SOCK_STREAM} 套接字；其他套接字类型不被支持。

形参 @code{server_side} 是一个布尔值，它标明希望从该套接字获得服务器端行为还是客户端行为。

对于客户端套接字，上下文的构造会延迟执行；如果下层的套接字尚未连接，上下文的构造将在对套接字调用 @code{connect()} 之后执行。 对于服务器端套接字，如果套接字没有远端对等方，它会被视为一个监听套接字，并且服务器端 SSL 包装操作会在通过 @code{accept()} 方法所接受的客户端连接上自动执行。 此方法可能会引发 @ref{ce2,,SSLError}。

在客户端连接上，可选形参 @emph{server_hostname} 指定所要连接的服务的主机名。 这允许单个服务器托管具有单独证书的多个基于 SSL 的服务，很类似于 HTTP 虚拟主机。 如果 @emph{server_side} 为真值则指定 @emph{server_hostname} 将引发 @ref{16d,,ValueError}。

形参 @code{do_handshake_on_connect} 指明是否要在调用 @code{socket.connect()} 之后自动执行 SSL 握手，还是要通过发起调用 @ref{853,,SSLSocket.do_handshake()} 方法让应用程序显式地调用它。 显式地调用 @ref{853,,SSLSocket.do_handshake()} 可给予程序对握手中所涉及的套接字 I/O 阻塞行为的控制。

形参 @code{suppress_ragged_eofs} 指明 @code{SSLSocket.recv()} 方法应当如何从连接的另一端发送非预期的 EOF 信号。 如果指定为 @ref{59c,,True} (默认值)，它将返回正常的 EOF (空字节串对象) 来响应从下层套接字引发的非预期的 EOF 错误；如果指定为 @ref{497,,False}，它将向调用方引发异常。

@emph{session}，参见 @ref{2853,,session}。


在 3.5 版更改: 总是允许传送 server_hostname，即使 OpenSSL 没有 SNI。



在 3.6 版更改: 增加了 @emph{session} 参数。


在 3.7 版更改: 此方法返回 @ref{2857,,SSLContext.sslsocket_class} 的实例而非硬编码的 @ref{192,,SSLSocket}。


@end deffn

@geindex sslsocket_class (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext sslsocket_class}@anchor{2857}
@deffn {属性} SSLContext.sslsocket_class

@ref{4f3,,SSLContext.wrap_socket()} 的返回类型，默认为 @ref{192,,SSLSocket}。 该属性可以在类实例上被重载以便返回自定义的 @ref{192,,SSLSocket} 的子类。


3.7 新版功能.

@end deffn

@geindex wrap_bio() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext wrap_bio}@anchor{4f4}
@deffn {方法} SSLContext.wrap_bio (incoming, outgoing, server_side=False, server_hostname=None, session=None)

包装 BIO 对象 @emph{incoming} 和 @emph{outgoing} 并返回一个 @ref{2858,,SSLContext.sslobject_class} (默认为 @ref{4f1,,SSLObject}) 的实例。 SSL 例程将从 BIO 中读取输入数据并将数据写入到 outgoing BIO。

@emph{server_side}, @emph{server_hostname} 和 @emph{session} 形参具有与 @ref{4f3,,SSLContext.wrap_socket()} 中相同的含义。


在 3.6 版更改: 增加了 @emph{session} 参数。



在 3.7 版更改: 此方法返回 @ref{2858,,SSLContext.sslobject_class} 的实例则非硬编码的 @ref{4f1,,SSLObject}。

@end deffn

@geindex sslobject_class (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext sslobject_class}@anchor{2858}
@deffn {属性} SSLContext.sslobject_class

@ref{4f4,,SSLContext.wrap_bio()} 的返回类型，默认为 @ref{4f1,,SSLObject}。 该属性可以在类实例上被重载以便返回自定义的 @ref{4f1,,SSLObject} 的子类。


3.7 新版功能.

@end deffn

@geindex session_stats() (ssl.SSLContext 方法)
@anchor{library/ssl ssl SSLContext session_stats}@anchor{2859}
@deffn {方法} SSLContext.session_stats ()

获取由此上下文所创建或管理的 SSL 会话的相关统计信息。 返回将每个 信息片@footnote{https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html} 的名称映射到其数字值的字典。 例如，以下是自上下文被创建以来会话缓存中命中和未命中的总数:

@example
>>> stats = context.session_stats()
>>> stats['hits'], stats['misses']
(0, 0)
@end example
@end deffn

@geindex check_hostname (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext check_hostname}@anchor{2824}
@deffn {属性} SSLContext.check_hostname

是否要将匹配 @ref{853,,SSLSocket.do_handshake()} 中对等方证书的主机名。 该上下文的 @ref{280b,,verify_mode} 必须被设为 @ref{2823,,CERT_OPTIONAL} 或 @ref{280c,,CERT_REQUIRED}，并且你必须将 @emph{server_hostname} 传给 @ref{4f3,,wrap_socket()} 以便匹配主机名。 启用主机名检查会自动将 @ref{280b,,verify_mode} 从 @ref{2821,,CERT_NONE} 设为 @ref{280c,,CERT_REQUIRED}。 只要启用了主机名检查就无法将其设回 @ref{2821,,CERT_NONE}。 @ref{2822,,PROTOCOL_TLS_CLIENT} 协议默认启用主机名检查。 对于其他协议，则必须显式地启用主机名检查。

示例:

@example
import socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))
@end example


3.4 新版功能.



在 3.7 版更改: 现在当主机名检查被启用且 @ref{280b,,verify_mode} 为 @ref{2821,,CERT_NONE} 时 @ref{280b,,verify_mode} 会自动更改为 @ref{280c,,CERT_REQUIRED}。 在之前版本中同样的操作将失败并引发 @ref{16d,,ValueError}。


@cartouche
@quotation 注解 
此特性要求 OpenSSL 0.9.8f 或更新的版本。
@end quotation
@end cartouche
@end deffn

@geindex keylog_filename (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext keylog_filename}@anchor{280d}
@deffn {属性} SSLContext.keylog_filename

每当生成或接收到密钥时，将 TLS 密钥写入到一个密钥日志文件。 密钥日志文件的设计仅适用于调试目的。 文件的格式由 NSS 指明并为许多流量分析工具例如 Wireshark 所使用。 日志文件会以追加模式打开。 写入操作会在线程之间同步，但不会在进程之间同步。


3.8 新版功能.


@cartouche
@quotation 注解 
此特性要求 OpenSSL 1.1.1 或更新的版本。
@end quotation
@end cartouche
@end deffn

@geindex maximum_version (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext maximum_version}@anchor{4f6}
@deffn {属性} SSLContext.maximum_version

一个代表所支持的最高 TLS 版本的 @ref{2845,,TLSVersion} 枚举成员。 该值默认为 @ref{2847,,TLSVersion.MAXIMUM_SUPPORTED}。 这个属性对于 @ref{2809,,PROTOCOL_TLS}, @ref{2822,,PROTOCOL_TLS_CLIENT} 和 @ref{2828,,PROTOCOL_TLS_SERVER} 以外的其他协议来说都是只读的。

@ref{4f6,,maximum_version}, @ref{4f5,,minimum_version} 和 @ref{281e,,SSLContext.options} 等属性都会影响上下文所支持的 SSL 和 TLS 版本。 这个实现不会阻止无效的组合。 例如一个 @ref{281e,,options} 为 @ref{282f,,OP_NO_TLSv1_2} 而 @ref{4f6,,maximum_version} 设为 @ref{284b,,TLSVersion.TLSv1_2} 的上下文将无法建立 TLS 1.2 连接。

@cartouche
@quotation 注解 
除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这个属性将不可用。
@end quotation
@end cartouche


3.7 新版功能.

@end deffn

@geindex minimum_version (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext minimum_version}@anchor{4f5}
@deffn {属性} SSLContext.minimum_version

与 @ref{4f6,,SSLContext.maximum_version} 类似，区别在于它是所支持的最低版本或为 @ref{2846,,TLSVersion.MINIMUM_SUPPORTED}。

@cartouche
@quotation 注解 
除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这个属性将不可用。
@end quotation
@end cartouche


3.7 新版功能.

@end deffn

@geindex num_tickets (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext num_tickets}@anchor{285a}
@deffn {属性} SSLContext.num_tickets

控制 @code{TLS_PROTOCOL_SERVER} 上下文的 TLS 1.3  会话凭据数量。 这个设置不会影响 TLS 1.0 到 1.2 连接。

@cartouche
@quotation 注解 
除非 ssl 模块使用 OpenSSL 1.1.1 或更新的版本编译否则这个属性将不可用。
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@geindex options (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext options}@anchor{281e}
@deffn {属性} SSLContext.options

一个代表此上下文中所启用的 SSL 选项集的整数。 默认值为 @ref{282c,,OP_ALL}，但你也可以通过在选项间进行 OR 运算来指定其他选项例如 @ref{c79,,OP_NO_SSLv2}。

@cartouche
@quotation 注解 
对于 0.9.8m 之前的 OpenSSL 版本，只能设置选项，而不能清除它们。 尝试（通过重置相应比特位）清除选项将会引发 @ref{16d,,ValueError}。
@end quotation
@end cartouche


在 3.6 版更改: @ref{281e,,SSLContext.options} 返回 @ref{2835,,Options} 旗标:

@example
>>> ssl.create_default_context().options  
<Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>
@end example

@end deffn

@geindex post_handshake_auth (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext post_handshake_auth}@anchor{358}
@deffn {属性} SSLContext.post_handshake_auth

启用 TLS 1.3 握手后客户端身份验证。 握手后验证默认是被禁用的，服务器只能在初始握手期间请求 TLS 客户端证书。 当启用时，服务器可以在握手之后的任何时候请求 TLS 客户端证书。

当在客户端套接字上启用时，客户端会向服务器发信号说明它支持握手后身份验证。

当在服务器端套接字上启用时，@ref{280b,,SSLContext.verify_mode} 也必须被设为 @ref{2823,,CERT_OPTIONAL} 或 @ref{280c,,CERT_REQUIRED}。 实际的客户端证书交换会被延迟直至 @ref{359,,SSLSocket.verify_client_post_handshake()} 被调用并执行了一些 I/O 操作后再进行。

@cartouche
@quotation 注解 
仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 如果没有 TLS 1.3 支持，该属性值将为 None 且不可被更改
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@geindex protocol (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext protocol}@anchor{285b}
@deffn {属性} SSLContext.protocol

构造上下文时所选择的协议版本。 这个属性是只读的。
@end deffn

@geindex hostname_checks_common_name (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext hostname_checks_common_name}@anchor{4ed}
@deffn {属性} SSLContext.hostname_checks_common_name

在没有目标替代名称扩展的情况下 @ref{2824,,check_hostname} 是否要回退为验证证书的通用名称（默认为真值）。

@cartouche
@quotation 注解 
仅在 OpenSSL 1.1.0 或更新的版本上可写。
@end quotation
@end cartouche


3.7 新版功能.



在 3.9.3 版更改: 此旗标在 OpenSSL 1.1.1k 之前的版本上不起作用。 Python 3.8.9, 3.9.3, 和 3.10 包含了针对之前版本的变通处理。

@end deffn

@geindex verify_flags (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext verify_flags}@anchor{9b5}
@deffn {属性} SSLContext.verify_flags

证书验证操作的旗标。 你可以通过对 @ref{9b7,,VERIFY_CRL_CHECK_LEAF} 等值执行 OR 运算来设置组合旗标。 在默认情况下 OpenSSL 不会要求也不会验证证书吊销列表（CRL）。 仅在 openssl 版本 0.9.8+ 上可用。


3.4 新版功能.



在 3.6 版更改: @ref{9b5,,SSLContext.verify_flags} 返回 @ref{2827,,VerifyFlags} 旗标:

@example
>>> ssl.create_default_context().verify_flags  
<VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
@end example

@end deffn

@geindex verify_mode (ssl.SSLContext 属性)
@anchor{library/ssl ssl SSLContext verify_mode}@anchor{280b}
@deffn {属性} SSLContext.verify_mode

是否要尝试验证其他对等方的证书以及如果验证失败应采取何种行为。 该属性值必须为 @ref{2821,,CERT_NONE}, @ref{2823,,CERT_OPTIONAL} 或 @ref{280c,,CERT_REQUIRED} 之一。


在 3.6 版更改: @ref{280b,,SSLContext.verify_mode} 返回 @ref{2825,,VerifyMode} 枚举:

@example
>>> ssl.create_default_context().verify_mode
<VerifyMode.CERT_REQUIRED: 2>
@end example

@end deffn

@geindex certificates

@geindex X509 certificate

@node 证书,示例<24>,SSL 上下文,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl certificates}@anchor{285c}@anchor{library/ssl ssl-certificates}@anchor{2856}
@subsubsection 证书


总的来说证书是公钥/私钥系统的一个组成部分。 在这个系统中，每 个 @emph{主体} (可能是一台机器、一个人或者一个组织) 都会分配到唯一的包含两部分的加密密钥。 一部分密钥是公开的，称为 @emph{公钥}；另一部分密钥是保密的，称为 @emph{私钥}。 这两个部分是互相关联的，就是说如果你用其中一个部分来加密一条消息，你将能用并且 @strong{只能} 用另一个部分来解密它。

在一个证书中包含有两个主体的相关信息。 它包含 @emph{目标方} 的名称和目标方的公钥。 它还包含由第二个主体 @emph{颁发方} 所发布的声明：目标方的身份与他们所宣称的一致，包含的公钥也确实是目标方的公钥。 颁发方的声明使用颁发方的私钥进行签名，该私钥的内容只有颁发方自己才知道。 但是，任何人都可以找到颁发方的公钥，用它来解密这个声明，并将其与证书中的其他信息进行比较来验证颁发方声明的真实性。 证书还包含有关其有效期限的信息。 这被表示为两个字段，即 "notBefore" 和 "notAfter"。

在 Python 中应用证书时，客户端或服务器可以用证书来证明自己的身份。 还可以要求网络连接的另一方提供证书，提供的证书可以用于验证以满足客户端或服务器的验证要求。 如果验证失败，连接尝试可被设置为引发一个异常。 验证是由下层的 OpenSSL 框架来自动执行的；应用程序本身不必关注其内部的机制。 但是应用程序通常需要提供一组证书以允许此过程的发生。

Python 使用文件来包含证书。 它们应当采用 "PEM" 格式 (参见 
@geindex RFC; RFC 1422
RFC 1422@footnote{https://tools.ietf.org/html/rfc1422.html})，这是一种带有头部行和尾部行的 base-64 编码包装形式:

@example
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
@end example

@menu
* 证书链:: 
* CA 证书:: 
* 合并的密钥和证书:: 
* 自签名证书:: 

@end menu

@node 证书链,CA 证书,,证书
@anchor{library/ssl certificate-chains}@anchor{285d}
@subsubsection 证书链


包含证书的 Python 文件可以包含一系列的证书，有时被称为 @emph{证书链}。 这个证书链应当以 "作为" 客户端或服务器的主体的专属证书打头，然后是证书颁发方的证书，然后是 @emph{上述} 证书的颁发方的证书，证书链就这样不断上溯直到你得到一个 @emph{自签名} 的证书，即具有相同目标方和颁发方的证书，有时也称为 @emph{根证书}。 在证书文件中这些证书应当被拼接为一体。 例如，假设我们有一个包含三个证书的证书链，以我们的服务器证书打头，然后是为我们的服务器证书签名的证书颁发机构的证书，最后是为证书颁发机构的证书颁发证书的机构的根证书:

@example
-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----
@end example

@node CA 证书,合并的密钥和证书,证书链,证书
@anchor{library/ssl ca-certificates}@anchor{285e}
@subsubsection CA 证书


如果你想要求对连接的另一方的证书进行验证，你必须提供一个 "CA 证书" 文件，其中包含了你愿意信任的每个颁发方的证书链。 同样地，这个文件的内容就是这些证书链拼接在一起的结果。 为了进行验证，Python 将使用它在文件中找到的第一个匹配的证书链。 可以通过调用 @ref{9ba,,SSLContext.load_default_certs()} 来使用系统平台的证书文件，这可以由 @ref{9b0,,create_default_context()} 自动完成。

@node 合并的密钥和证书,自签名证书,CA 证书,证书
@anchor{library/ssl combined-key-and-certificate}@anchor{285f}
@subsubsection 合并的密钥和证书


私钥往往与证书存储在相同的文件中；在此情况下，只需要将 @code{certfile} 形参传给 @ref{b72,,SSLContext.load_cert_chain()} 和 @ref{579,,wrap_socket()}。 如果私钥是与证书一起存储的，则它应当放在证书链的第一个证书之前:

@example
-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
@end example

@node 自签名证书,,合并的密钥和证书,证书
@anchor{library/ssl self-signed-certificates}@anchor{2860}
@subsubsection 自签名证书


如果你准备创建一个提供 SSL 加密连接服务的服务器，你需要为该服务获取一份证书。 有许多方式可以获取合适的证书，例如从证书颁发机构购买。 另一种常见做法是生成自签名证书。 生成自签名证书的最简单方式是使用 OpenSSL 软件包，代码如下所示:

@example
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@@myserver.mygroup.myorganization.com
%
@end example

自签名证书的缺点在于它是它自身的根证书，因此不会存在于别人的已知（且信任的）根证书缓存当中。

@node 示例<24>,关于非阻塞套接字的说明,证书,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl examples}@anchor{2861}
@subsubsection 示例


@menu
* 检测 SSL 支持:: 
* 客户端操作:: 
* 服务器端操作:: 

@end menu

@node 检测 SSL 支持,客户端操作,,示例<24>
@anchor{library/ssl testing-for-ssl-support}@anchor{2862}
@subsubsection 检测 SSL 支持


要检测一个 Python 安装版中是否带有 SSL 支持，用户代码应当使用以下例程:

@example
try:
    import ssl
except ImportError:
    pass
else:
    ...  # do something that requires SSL support
@end example

@node 客户端操作,服务器端操作,检测 SSL 支持,示例<24>
@anchor{library/ssl client-side-operation}@anchor{2863}
@subsubsection 客户端操作


这个例子创建了一个 SSL 上下文并使用客户端套接字的推荐安全设置，包括自动证书验证:

@example
>>> context = ssl.create_default_context()
@end example

如果你喜欢自行调整安全设置，你可能需要从头创建一个上下文（但是请请注意避免不正确的设置）:

@example
>>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
@end example

(这段代码假定你的操作系统将所有 CA 证书打包存放于 @code{/etc/ssl/certs/ca-bundle.crt}；如果不是这样，你将收到报错信息，必须修改此位置)

@ref{2822,,PROTOCOL_TLS_CLIENT} 协议配置用于证书验证和主机名验证的上下文。 @ref{280b,,verify_mode} 设为 @ref{280c,,CERT_REQUIRED} 而 @ref{2824,,check_hostname} 设为 @code{True}。 所有其他协议都会使用不安全的默认值创建 SSL 上下文。

当你使用此上下文去连接服务器时，@ref{280c,,CERT_REQUIRED} 和 @ref{2824,,check_hostname} 会验证服务器证书；它将确认服务器证书使用了某个 CA 证书进行签名，检查签名是否正确，并验证其他属性例如主机名的有效性和身份真实性:

@example
>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
...                            server_hostname="www.python.org")
>>> conn.connect(("www.python.org", 443))
@end example

你可以随后获取该证书:

@example
>>> cert = conn.getpeercert()
@end example

可视化检查显示证书能够证明目标服务 (即 HTTPS 主机 @code{www.python.org}) 的身份:

@example
>>> pprint.pprint(cert)
@{'OCSP': ('http://ocsp.digicert.com',),
 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                           'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
 'issuer': ((('countryName', 'US'),),
            (('organizationName', 'DigiCert Inc'),),
            (('organizationalUnitName', 'www.digicert.com'),),
            (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
 'notAfter': 'Sep  9 12:00:00 2016 GMT',
 'notBefore': 'Sep  5 00:00:00 2014 GMT',
 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
 'subject': ((('businessCategory', 'Private Organization'),),
             (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
             (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
             (('serialNumber', '3359300'),),
             (('streetAddress', '16 Allen Rd'),),
             (('postalCode', '03894-4801'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'NH'),),
             (('localityName', 'Wolfeboro'),),
             (('organizationName', 'Python Software Foundation'),),
             (('commonName', 'www.python.org'),)),
 'subjectAltName': (('DNS', 'www.python.org'),
                    ('DNS', 'python.org'),
                    ('DNS', 'pypi.org'),
                    ('DNS', 'docs.python.org'),
                    ('DNS', 'testpypi.org'),
                    ('DNS', 'bugs.python.org'),
                    ('DNS', 'wiki.python.org'),
                    ('DNS', 'hg.python.org'),
                    ('DNS', 'mail.python.org'),
                    ('DNS', 'packaging.python.org'),
                    ('DNS', 'pythonhosted.org'),
                    ('DNS', 'www.pythonhosted.org'),
                    ('DNS', 'test.pythonhosted.org'),
                    ('DNS', 'us.pycon.org'),
                    ('DNS', 'id.python.org')),
 'version': 3@}
@end example

现在 SSL 通道已建立并已验证了证书，你可以继续与服务器对话了:

@example
>>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
>>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
 b'Server: nginx',
 b'Content-Type: text/html; charset=utf-8',
 b'X-Frame-Options: SAMEORIGIN',
 b'Content-Length: 45679',
 b'Accept-Ranges: bytes',
 b'Via: 1.1 varnish',
 b'Age: 2188',
 b'X-Served-By: cache-lcy1134-LCY',
 b'X-Cache: HIT',
 b'X-Cache-Hits: 11',
 b'Vary: Cookie',
 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
 b'Connection: close',
 b'@w{'},
 b'@w{'}]
@end example

参见下文对于 @ref{2711,,安全考量} 的讨论。

@node 服务器端操作,,客户端操作,示例<24>
@anchor{library/ssl server-side-operation}@anchor{2864}
@subsubsection 服务器端操作


对于服务器操作，通常你需要在文件中存放服务器证书和私钥各一份。 你将首先创建一个包含密钥和证书的上下文，这样客户端就能检查你的身份真实性。 然后你将打开一个套接字，将其绑定到一个端口，在其上调用 @code{listen()}，并开始等待客户端连接:

@example
import socket, ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

bindsocket = socket.socket()
bindsocket.bind(('myaddr.example.com', 10023))
bindsocket.listen(5)
@end example

当有客户端连接时，你将在套接字上调用 @code{accept()} 以从另一端获取新的套接字，并使用上下文的 @ref{4f3,,SSLContext.wrap_socket()} 方法来为连接创建一个服务器端 SSL 套接字:

@example
while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()
@end example

随后你将从 @code{connstream} 读取数据并对其进行处理，直至你结束与客户端的会话（或客户端结束与你的会话）:

@example
def deal_with_client(connstream):
    data = connstream.recv(1024)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        data = connstream.recv(1024)
    # finished with client
@end example

并返回至监听新的客户端连接（当然，真正的服务器应当会在单独的线程中处理每个客户端连接，或者将套接字设为 @ref{2810,,非阻塞模式} 并使用事件循环）。

@node 关于非阻塞套接字的说明,内存 BIO 支持<2>,示例<24>,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl notes-on-non-blocking-sockets}@anchor{2865}@anchor{library/ssl ssl-nonblocking}@anchor{2810}
@subsubsection 关于非阻塞套接字的说明


在非阻塞模式下 SSL 套接字的行为与常规套接字略有不同。 当使用非阻塞模式时，你需要注意下面这些事情:


@itemize -

@item 
如果一个 I/O 操作会阻塞，大多数 @ref{192,,SSLSocket} 方法都将引发 @ref{850,,SSLWantWriteError} 或 @ref{84f,,SSLWantReadError} 而非 @ref{a81,,BlockingIOError}。 如果有必要在下层套接字上执行读取操作将引发 @ref{84f,,SSLWantReadError}，在下层套接字上执行写入操作则将引发 @ref{850,,SSLWantWriteError}。 请注意尝试 @emph{写入} 到 SSL 套接字可能需要先从下层套接字 @emph{读取}，而尝试从 SSL 套接字 @emph{读取} 则可能需要先向下层套接字 @emph{写入}。


在 3.5 版更改: 在较早的 Python 版本中，@code{SSLSocket.send()} 方法会返回零值而非引发 @ref{850,,SSLWantWriteError} 或 @ref{84f,,SSLWantReadError}。


@item 
调用 @ref{770,,select()} 将告诉你可以从 OS 层级的套接字读取（或向其写入），但这并不意味着在上面的 SSL 层有足够的数据。 例如，可能只有部分 SSL 帧已经到达。 因此，你必须准备好处理 @code{SSLSocket.recv()} 和 @code{SSLSocket.send()} 失败的情况，并在再次调用 @ref{770,,select()} 之后重新尝试。

@item 
相反地，由于 SSL 层具有自己的帧机制，一个 SSL 套接字可能仍有可读取的数据而 @ref{770,,select()} 并不知道这一点。 因此，你应当先调用 @code{SSLSocket.recv()} 取走所有潜在的可用数据，然后只在必要时对 @ref{770,,select()} 调用执行阻塞。

(当然，类似的保留规则在使用其他原语例如 @ref{2866,,poll()}，或 @ref{e6,,selectors} 模块中的原语时也适用)

@item 
SSL 握手本身将是非阻塞的: @ref{853,,SSLSocket.do_handshake()} 方法必须不断重试直至其成功返回。 下面是一个使用 @ref{770,,select()} 来等待套接字就绪的简短例子:

@example
while True:
    try:
        sock.do_handshake()
        break
    except ssl.SSLWantReadError:
        select.select([sock], [], [])
    except ssl.SSLWantWriteError:
        select.select([], [sock], [])
@end example
@end itemize


@subsubheading 参见


@ref{9,,asyncio} 模块支持 @ref{2810,,非阻塞 SSL 套接字} 并提供了更高层级的 API。 它会使用 @ref{e6,,selectors} 模块来轮询事件并处理 @ref{850,,SSLWantWriteError}, @ref{84f,,SSLWantReadError} 和 @ref{a81,,BlockingIOError} 等异常。 它还会异步地执行 SSL 握手。


@node 内存 BIO 支持<2>,SSL 会话,关于非阻塞套接字的说明,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl memory-bio-support}@anchor{2867}
@subsubsection 内存 BIO 支持



3.5 新版功能.


自从 SSL 模块在 Python 2.6 起被引入之后，@ref{192,,SSLSocket} 类提供了两个互相关联但彼此独立的功能分块:


@itemize -

@item 
SSL 协议处理

@item 
网络 IO
@end itemize

网络 IO API 与 @ref{771,,socket.socket} 所提供的功能一致，@ref{192,,SSLSocket} 也是从那里继承而来的。 这允许 SSL 套接字被用作常规套接字的替代，使得向现有应用程序添加 SSL 支持变得非常容易。

将 SSL 协议处理与网络 IO 结合使用通常都能运行良好，但在某些情况下则不能。 此情况的一个例子是 async IO 框架，该框架要使用不同的 IO 多路复用模型而非 (基于就绪状态的) "在文件描述器上执行选择/轮询" 模型，该模型是 @ref{771,,socket.socket} 和内部 OpenSSL 套接字 IO 例程正常运行的假设前提。 这种情况在该模型效率不高的 Windows 平台上最为常见。 为此还提供了一个 @ref{192,,SSLSocket} 的简化形式，称为 @ref{4f1,,SSLObject}。

@geindex SSLObject (ssl 中的类)
@anchor{library/ssl ssl SSLObject}@anchor{4f1}
@deffn {类} ssl.SSLObject

@ref{192,,SSLSocket} 的简化形式，表示一个不包含任何网络 IO 方法的 SSL 协议实例。 这个类通常由想要通过内存缓冲区为 SSL 实现异步 IO 的框架作者来使用。

这个类在低层级 SSL 对象上实现了一个接口，与 OpenSSL 所实现的类似。 此对象会捕获 SSL 连接的状态但其本身不提供任何网络 IO。 IO 需要通过单独的 "BIO" 对象来执行，该对象是 OpenSSL 的 IO 抽象层。

这个类没有公有构造器。 @ref{4f1,,SSLObject} 实例必须使用 @ref{4f4,,wrap_bio()} 方法来创建。 此方法将创建 @ref{4f1,,SSLObject} 实例并将其绑定到一个 BIO 对。 其中 @emph{incoming} BIO 用来将数据从 Python 传递到 SSL 协议实例，而 @emph{outgoing} BIO 用来进行数据反向传递。

可以使用以下方法：


@itemize -

@item 
@ref{284f,,context}

@item 
@ref{2852,,server_side}

@item 
@ref{4ef,,server_hostname}

@item 
@ref{2853,,session}

@item 
@ref{2854,,session_reused}

@item 
@ref{854,,read()}

@item 
@ref{855,,write()}

@item 
@ref{9c0,,getpeercert()}

@item 
@ref{84b,,selected_alpn_protocol()}

@item 
@ref{2850,,selected_npn_protocol()}

@item 
@ref{2755,,cipher()}

@item 
@ref{852,,shared_ciphers()}

@item 
@ref{b76,,compression()}

@item 
@ref{2851,,pending()}

@item 
@ref{853,,do_handshake()}

@item 
@ref{359,,verify_client_post_handshake()}

@item 
@ref{284e,,unwrap()}

@item 
@ref{b75,,get_channel_binding()}

@item 
@ref{84e,,version()}
@end itemize

与 @ref{192,,SSLSocket} 相比，此对象缺少下列特性:


@itemize -

@item 
任何形式的网络 IO; @code{recv()} 和 @code{send()} 仅对下层的 @ref{848,,MemoryBIO} 缓冲区执行读取和写入。

@item 
不存在 @emph{do_handshake_on_connect} 机制。 你必须总是手动调用 @ref{853,,do_handshake()} 来开始握手操作。

@item 
不存在对 @emph{suppress_ragged_eofs} 的处理。 所有违反协议的文件结束条件将通过 @ref{2812,,SSLEOFError} 异常来报告。

@item 
方法 @ref{284e,,unwrap()} 的调用不返回任何东西，不会如 SSL 套接字那样返回下层的套接字。

@item 
@emph{server_name_callback} 回调被传给 @ref{9bf,,SSLContext.set_servername_callback()} 时将获得一个 @ref{4f1,,SSLObject} 实例而非 @ref{192,,SSLSocket} 实例作为其第一个形参。
@end itemize

有关 @ref{4f1,,SSLObject} 用法的一些说明:


@itemize -

@item 
在 @ref{4f1,,SSLObject} 上的所有 IO 都是 @ref{2810,,非阻塞的}。 这意味着例如 @ref{854,,read()} 在其需要比 incoming BIO 可用的更多数据时将会引发 @ref{84f,,SSLWantReadError}。

@item 
不存在模块层级的 @code{wrap_bio()} 调用，就像 @ref{4f3,,wrap_socket()} 那样。 @ref{4f1,,SSLObject} 总是通过 @ref{4f2,,SSLContext} 来创建。
@end itemize


在 3.7 版更改: @ref{4f1,,SSLObject} 的实例必须使用 @ref{4f4,,wrap_bio()} 来创建。 在较早的版本中，直接创建实例是可能的。 但这从未被记入文档或是被正式支持。

@end deffn

SSLObject 会使用内存缓冲区与外部世界通信。 @ref{848,,MemoryBIO} 类提供了可被用于此目的的内存缓冲区。 它包装了一个 OpenSSL 内存 BIO (Basic IO) 对象:

@geindex MemoryBIO (ssl 中的类)
@anchor{library/ssl ssl MemoryBIO}@anchor{848}
@deffn {类} ssl.MemoryBIO

一个可被用来在 Python 和 SSL 协议实例之间传递数据的内存缓冲区。

@geindex pending (ssl.MemoryBIO 属性)
@anchor{library/ssl ssl MemoryBIO pending}@anchor{2868}
@deffn {属性} pending

返回当前存在于内存缓冲区的字节数。
@end deffn

@geindex eof (ssl.MemoryBIO 属性)
@anchor{library/ssl ssl MemoryBIO eof}@anchor{2869}
@deffn {属性} eof

一个表明内存 BIO 目前是否位于文件末尾的布尔值。
@end deffn

@geindex read() (ssl.MemoryBIO 方法)
@anchor{library/ssl ssl MemoryBIO read}@anchor{286a}
@deffn {方法} read (n=-1)

从内存缓冲区读取至多 @emph{n} 个字节。 如果 @emph{n} 未指定或为负值，则返回全部字节数据。
@end deffn

@geindex write() (ssl.MemoryBIO 方法)
@anchor{library/ssl ssl MemoryBIO write}@anchor{286b}
@deffn {方法} write (buf)

将字节数据从 @emph{buf} 写入到内存 BIO。 @emph{buf} 参数必须为支持缓冲区协议的对象。

返回值为写入的字节数，它总是与 @emph{buf} 的长度相等。
@end deffn

@geindex write_eof() (ssl.MemoryBIO 方法)
@anchor{library/ssl ssl MemoryBIO write_eof}@anchor{286c}
@deffn {方法} write_eof ()

将一个 EOF 标记写入到内存 BIO。 在此方法被调用以后，再调用 @ref{286b,,write()} 将是非法的。 属性 @ref{2869,,eof} will 在缓冲区当前的所有数据都被读取之后将变为真值。
@end deffn
@end deffn

@node SSL 会话,安全考量<3>,内存 BIO 支持<2>,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl ssl-session}@anchor{286d}
@subsubsection SSL 会话



3.6 新版功能.


@geindex SSLSession (ssl 中的类)
@anchor{library/ssl ssl SSLSession}@anchor{68c}
@deffn {类} ssl.SSLSession

@ref{2853,,session} 所使用的会话对象。

@geindex id (ssl.SSLSession 属性)
@anchor{library/ssl ssl SSLSession id}@anchor{286e}
@deffn {属性} id
@end deffn

@geindex time (ssl.SSLSession 属性)
@anchor{library/ssl ssl SSLSession time}@anchor{286f}
@deffn {属性} time
@end deffn

@geindex timeout (ssl.SSLSession 属性)
@anchor{library/ssl ssl SSLSession timeout}@anchor{2870}
@deffn {属性} timeout
@end deffn

@geindex ticket_lifetime_hint (ssl.SSLSession 属性)
@anchor{library/ssl ssl SSLSession ticket_lifetime_hint}@anchor{2871}
@deffn {属性} ticket_lifetime_hint
@end deffn

@geindex has_ticket (ssl.SSLSession 属性)
@anchor{library/ssl ssl SSLSession has_ticket}@anchor{2872}
@deffn {属性} has_ticket
@end deffn
@end deffn

@node 安全考量<3>,TLS 1 3,SSL 会话,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl security-considerations}@anchor{2873}@anchor{library/ssl ssl-security}@anchor{2711}
@subsubsection 安全考量


@menu
* 最佳默认值:: 
* 手动设置:: 
* 多进程:: 

@end menu

@node 最佳默认值,手动设置,,安全考量<3>
@anchor{library/ssl best-defaults}@anchor{2874}
@subsubsection 最佳默认值


针对 @strong{客户端使用}，如果你对于安全策略没有任何特殊要求，则强烈推荐你使用 @ref{9b0,,create_default_context()} 函数来创建你的 SSL 上下文。 它将加载系统的受信任 CA 证书，启用证书验证和主机名检查，并尝试合理地选择安全的协议和密码设置。

例如，以下演示了你应当如何使用 @ref{1df,,smtplib.SMTP} 类来创建指向一个 SMTP 服务器的受信任且安全的连接:

@example
>>> import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
@end example

如果连接需要客户端证书，可使用 @ref{b72,,SSLContext.load_cert_chain()} 来添加。

作为对比，如果你通过自行调用 @ref{4f2,,SSLContext} 构造器来创建 SSL 上下文，它默认将不会启用证书验证和主机名检查。 如果你这样做，请阅读下面的段落以达到良好的安全级别。

@node 手动设置,多进程,最佳默认值,安全考量<3>
@anchor{library/ssl manual-settings}@anchor{2875}
@subsubsection 手动设置


@menu
* 验证证书:: 
* 协议版本:: 
* 密码选择:: 

@end menu

@node 验证证书,协议版本,,手动设置
@anchor{library/ssl verifying-certificates}@anchor{2876}
@subsubsection 验证证书


当直接调用 @ref{4f2,,SSLContext} 构造器时，默认会使用 @ref{2821,,CERT_NONE}。 由于它不会验证对等方的身份真实性，因此是不安全的，特别是在客户端模式下，大多数时候你都希望能保证你所连接的服务器的身份真实性。 因此，当处于客户端模式时，强烈推荐使用 @ref{280c,,CERT_REQUIRED}。 但是，光这样还不够；你还必须检查服务器证书，这可以通过调用 @ref{9c0,,SSLSocket.getpeercert()} 来获取并匹配目标服务。 对于许多协议和应用来说，服务可通过主机名来标识；在此情况下，可以使用 @ref{4eb,,match_hostname()} 函数。 这种通用检测会在 @ref{2824,,SSLContext.check_hostname} 被启用时自动执行。


在 3.7 版更改: 主机名匹配现在是由 OpenSSL 来执行的。 Python 不会再使用 @ref{4eb,,match_hostname()}。


在服务器模式下，如果你想要使用 SSL 层来验证客户端（而不是使用更高层级的验证机制），你也必须要指定 @ref{280c,,CERT_REQUIRED} 并以类似方式检查客户端证书。

@node 协议版本,密码选择,验证证书,手动设置
@anchor{library/ssl protocol-versions}@anchor{2877}
@subsubsection 协议版本


SSL 版本 2 和 3 被认为是不安全的因而使用它们会有风险。 如果你想要客户端和服务器之间有最大的兼容性，推荐使用 @ref{2822,,PROTOCOL_TLS_CLIENT} 或 @ref{2828,,PROTOCOL_TLS_SERVER} 作为协议版本。 SSLv2 和 SSLv3 默认会被禁用。

@example
>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> client_context.options |= ssl.OP_NO_TLSv1
>>> client_context.options |= ssl.OP_NO_TLSv1_1
@end example

前面创建的 SSL 上下文将只允许 TLSv1.2 及更新版本（如果你的系统支持）的服务器连接。 @ref{2822,,PROTOCOL_TLS_CLIENT} 默认会使用证书验证和主机名检查。 你必须将证书加载到上下文中。

@node 密码选择,,协议版本,手动设置
@anchor{library/ssl cipher-selection}@anchor{2878}
@subsubsection 密码选择


如果你有更高级的安全要求，也可以通过 @ref{281f,,SSLContext.set_ciphers()} 方法在协商 SSL 会话时对所启用的加密进行微调。 从 Python 3.2.3 开始，ssl 默认会禁用某些较弱的加密，但你还可能希望进一步限制加密选项。 请确保仔细阅读 OpenSSL 文档中有关 加密列表格式@footnote{https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT} 的部分。 如果你想要检查给定的加密列表启用了哪些加密，可以使用 @ref{68d,,SSLContext.get_ciphers()} 或所在系统的 @code{openssl ciphers} 命令。

@node 多进程,,手动设置,安全考量<3>
@anchor{library/ssl multi-processing}@anchor{2879}
@subsubsection 多进程


如果使用此模块作为多进程应用的一部分（例如使用 @ref{b7,,multiprocessing} 或 @ref{21,,concurrent.futures} 模块），请注意 OpenSSL 的内部随机数字生成器并不能正确处理分支进程。 应用程序必须修改父进程的 PRNG 状态，如果它们要使用任何包含 @ref{a4b,,os.fork()} 的 SSL 特性的话。 任何对 @ref{2818,,RAND_add()}, @ref{b70,,RAND_bytes()} 或 @ref{b71,,RAND_pseudo_bytes()} 都可以 做到这一点。

@node TLS 1 3,LibreSSL 支持,安全考量<3>,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl ssl-tlsv1-3}@anchor{4f0}@anchor{library/ssl tls-1-3}@anchor{287a}
@subsubsection TLS 1.3



3.7 新版功能.


Python 通过 OpenSSL 1.1.1 提供了临时性和实验性的 TLS 1.3 支持。 这个新协议的行为与之前版本的 TLS/SSL 略有不同。 某些新的 TLS 1.3 特性暂时还不可用。


@itemize -

@item 
TLS 1.3 使用一组不同的加密套件集。 默认情况下所有 AES-GCM 和 ChaCha20 加密套件都会被启用。 @ref{281f,,SSLContext.set_ciphers()} 方法还不能启用或禁用任何 TLS 1.3 加密，但 @ref{68d,,SSLContext.get_ciphers()} 会返回它们。

@item 
会话凭据不再会作为初始握手的组成部分被发送而是以不同的方式来处理。 @ref{2853,,SSLSocket.session} 和 @ref{68c,,SSLSession} 与 TLS 1.3 不兼容。

@item 
客户端证书在初始握手期间也不会再被验证。 服务器可以在任何时候请求证书。 客户端会在它们从服务器发送或接收应用数据时处理证书请求。

@item 
早期数据、延迟的 TLS 客户端证书请求、签名算法配置和密钥重生成等 TLS 1.3 特性尚未被支持。
@end itemize

@node LibreSSL 支持,,TLS 1 3,ssl --- 套接字对象的 TLS/SSL 包装器
@anchor{library/ssl libressl-support}@anchor{287b}@anchor{library/ssl ssl-libressl}@anchor{287c}
@subsubsection LibreSSL 支持


LibreSSL 是 OpenSSL 1.0.1 的一个分支。 ssl 模块包含对 LibreSSL 的有限支持。 当 ssl 模块使用 LibreSSL 进行编译时某些特性将不可用。


@itemize *

@item 
LibreSSL >= 2.6.1 不再支持 NPN。  @ref{b78,,SSLContext.set_npn_protocols()} 和 @ref{2850,,SSLSocket.selected_npn_protocol()} 方法将不可用。

@item 
@ref{9b2,,SSLContext.set_default_verify_paths()} 会忽略环境变量 
@geindex SSL_CERT_FILE
@geindex 环境变量; SSL_CERT_FILE
@code{SSL_CERT_FILE} 和 
@geindex SSL_CERT_PATH
@geindex 环境变量; SSL_CERT_PATH
@code{SSL_CERT_PATH}，虽然 @ref{9b1,,get_default_verify_paths()} 仍然支持它们。
@end itemize


@subsubheading 参见



@table @asis

@item Class @ref{771,,socket.socket}

下层 @ref{ef,,socket} 类的文档

@item SSL/TLS 高强度加密：概述@footnote{https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html}

Apache HTTP Server文档介绍

@geindex RFC; RFC 1422

@item RFC 1422: 因特网电子邮件的隐私加强：第二部分：基于证书的密钥管理@footnote{https://tools.ietf.org/html/rfc1422.html}

Steve Kent

@geindex RFC; RFC 4086

@item RFC 4086: 确保安全的随机性要求@footnote{https://tools.ietf.org/html/rfc4086.html}

Donald E., Jeffrey I. Schiller

@geindex RFC; RFC 5280

@item RFC 5280: 互联网 X.509 公钥基础架构证书和证书吊销列表 (CRL) 配置文件@footnote{https://tools.ietf.org/html/rfc5280.html}

D. Cooper

@geindex RFC; RFC 5246

@item RFC 5246: 传输层安全性 (TLS) 协议版本 1.2@footnote{https://tools.ietf.org/html/rfc5246.html}

T. Dierks et. al.

@geindex RFC; RFC 6066

@item RFC 6066: 传输层安全性 (TLS) 的扩展@footnote{https://tools.ietf.org/html/rfc6066.html}

D. Eastlake

@item IANA TLS: 传输层安全性 (TLS) 的参数@footnote{https://www.iana.org/assignments/tls-parameters/tls-parameters.xml}

IANA

@geindex RFC; RFC 7525

@item RFC 7525: 传输层安全性 (TLS) 和数据报传输层安全性 (DTLS) 的安全使用建议@footnote{https://tools.ietf.org/html/rfc7525.html}

IETF

@item Mozilla 的服务器端 TLS 建议@footnote{https://wiki.mozilla.org/Security/Server_Side_TLS}

Mozilla
@end table


@node select --- 等待 I/O 完成,selectors --- 高级 I/O 复用库,ssl --- 套接字对象的 TLS/SSL 包装器,网络和进程间通信
@anchor{library/select doc}@anchor{287d}@anchor{library/select module-select}@anchor{e5}@anchor{library/select select-waiting-for-i-o-completion}@anchor{287e}
@subsection @code{select} --- 等待 I/O 完成


@geindex select (模块)


__________________________________________________________________


该模块提供了对 @code{select()} 和 @code{poll()} 函数的访问，这些函数在大多数操作系统中是可用的。在 Solaris 及其衍生版本上可用 @code{devpoll()}，在 Linux 2.5+ 上可用 @code{epoll()}，在大多数 BSD 上可用 @code{kqueue()}。注意，在 Windows 上，本模块仅适用于套接字；在其他操作系统上，本模块也适用于其他文件类型（特别地，在 Unix 上也适用于管道）。本模块不能用于常规文件，不能检测出（自上次读取文件后）文件是否有新数据写入。

@cartouche
@quotation 注解 
@ref{e6,,selectors} 模块是在 @ref{e5,,select} 模块原型的基础上进行高级且高效的 I/O 复用。推荐用户改用 @ref{e6,,selectors} 模块，除非用户希望对 OS 级的函数原型进行精确控制。
@end quotation
@end cartouche

该模块定义以下内容：

@geindex error
@anchor{library/select select error}@anchor{a80}
@deffn {例外} select.error

一个被弃用的 @ref{30b,,OSError} 的别名。


在 3.3 版更改: 根据 
@geindex Python 提高建议; PEP 3151
PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151}，这个类是 @ref{30b,,OSError} 的别名。

@end deffn

@geindex devpoll() (在 select 模块中)
@anchor{library/select select devpoll}@anchor{99b}
@deffn {函数} select.devpoll ()

（仅支持 Solaris 及其衍生版本）返回一个 @code{/dev/poll} 轮询对象，请参阅下方 @ref{287f,,/dev/poll 轮询对象} 获取 devpoll 对象所支持的方法。

@code{devpoll()} 对象与实例化时允许的文件描述符数量有关，如果在程序中降低了此数值，@code{devpoll()} 调用将失败。如果程序提高了此数值，@code{devpoll()} 可能会返回一个不完整的活动文件描述符列表。

新的文件描述符是 @ref{8f1,,不可继承的}。


3.3 新版功能.



在 3.4 版更改: 新的文件描述符现在是不可继承的。

@end deffn

@geindex epoll() (在 select 模块中)
@anchor{library/select select epoll}@anchor{999}
@deffn {函数} select.epoll (sizehint=-1, flags=0)

（仅支持 Linux 2.5.44 或更高版本）返回一个 edge poll 对象，该对象可作为 I/O 事件的边缘触发或水平触发接口。

@emph{sizehint} 指示 epoll 预计需要注册的事件数。它必须为正数，或为 @cite{-1} 以使用默认值。它仅在 @code{epoll_create1()} 不可用的旧系统上会被用到，其他情况下它没有任何作用（尽管仍会检查其值）。

@emph{flags} 已经弃用且完全被忽略。但是，如果提供该值，则它必须是 @code{0} 或 @code{select.EPOLL_CLOEXEC}，否则会抛出 @code{OSError} 异常。

请参阅下方 @ref{2880,,边缘触发和水平触发的轮询 (epoll) 对象} 获取 epoll 对象所支持的方法。

@code{epoll} 对象支持上下文管理器：当在 @ref{7e4,,with} 语句中使用时，新建的文件描述符会在运行至语句块结束时自动关闭。

新的文件描述符是 @ref{8f1,,不可继承的}。


在 3.3 版更改: 增加了 @emph{flags} 参数。



在 3.4 版更改: 增加了对 @ref{7e4,,with} 语句的支持。新的文件描述符现在是不可继承的。



3.4 版后已移除: @emph{flags} 参数。现在默认采用 @code{select.EPOLL_CLOEXEC} 标志。使用 @ref{8f3,,os.set_inheritable()} 来让文件描述符可继承。

@end deffn

@geindex poll() (在 select 模块中)
@anchor{library/select select poll}@anchor{2866}
@deffn {函数} select.poll ()

（部分操作系统不支持）返回一个 poll 对象，该对象支持注册和注销文件描述符，支持对描述符进行轮询以获取 I/O 事件。请参阅下方 @ref{2881,,Poll 对象} 获取 poll 对象所支持的方法。
@end deffn

@geindex kqueue() (在 select 模块中)
@anchor{library/select select kqueue}@anchor{2882}
@deffn {函数} select.kqueue ()

（仅支持 BSD）返回一个内核队列对象，请参阅下方 @ref{2883,,Kqueue 对象} 获取 kqueue 对象所支持的方法。

新的文件描述符是 @ref{8f1,,不可继承的}。


在 3.4 版更改: 新的文件描述符现在是不可继承的。

@end deffn

@geindex kevent() (在 select 模块中)
@anchor{library/select select kevent}@anchor{2884}
@deffn {函数} select.kevent (ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)

（仅支持 BSD）返回一个内核事件对象，请参阅下方 @ref{2885,,Kevent 对象} 获取 kevent 对象所支持的方法。
@end deffn

@geindex select() (在 select 模块中)
@anchor{library/select select select}@anchor{770}
@deffn {函数} select.select (rlist, wlist, xlist[, timeout])

这是一个明白直观的 Unix @code{select()} 系统调用接口。 前三个参数是由‘可等待对象’组成的序列：可以是代表文件描述符的整数，或是带有名为 @ref{209a,,fileno()} 的返回这样的整数的无形参方法的对象:


@itemize *

@item 
@emph{rlist}：等待，直到可以开始读取

@item 
@emph{wlist}：等待，直到可以开始写入

@item 
@emph{xlist}：等待“异常情况”（请参阅当前系统的手册，以获取哪些情况称为异常情况）
@end itemize

允许空的可迭代对象，但是否接受三个空的可迭代对象则取决于具体平台。 （已知在 Unix 上可行但在 Windows 上不可行。） 可选的 @emph{timeout} 参数以一个浮点数表示超时秒数。 当省略 @emph{timeout} 参数时该函数将阻塞直到至少有一个文件描述符准备就绪。 超时值为零表示执行轮询且永不阻塞。

返回值是三个列表，包含已就绪对象，返回的三个列表是前三个参数的子集。当超时时间已到且没有文件描述符就绪时，返回三个空列表。

@geindex socket() (in module socket)
@geindex popen() (in module os)

可迭代对象中可接受的对象类型有 Python @ref{c1d,,文件对象} (例如 @code{sys.stdin} 以及 @ref{16f,,open()} 或 @ref{3d3,,os.popen()} 所返回的对象)，由 @ref{771,,socket.socket()} 返回的套接字对象等。 你也可以自定义一个 @emph{wrapper} 类，只要它具有适当的 @ref{209a,,fileno()} 方法（该方法要确实返回一个文件描述符，而不能只是一个随机整数）。

@cartouche
@quotation 注解 
@geindex WinSock

Windows 上不接受文件对象，但接受套接字。在 Windows 上，底层的 @code{select()} 函数由 WinSock 库提供，且不处理不是源自 WinSock 的文件描述符。
@end quotation
@end cartouche


在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，不会抛出 @ref{756,,InterruptedError} 异常。除非信号处理程序抛出异常（相关原理请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@end deffn

@geindex PIPE_BUF() (在 select 模块中)
@anchor{library/select select PIPE_BUF}@anchor{c60}
@deffn {属性} select.PIPE_BUF

当一个管道已经被 @ref{770,,select()}、@ref{2866,,poll()} 或本模块中的某个接口报告为可写入时，可以在不阻塞该管道的情况下写入的最小字节数。它不适用于套接字等其他类型的文件类对象。

POSIX 上须保证该值不小于 512。

@ref{14c1,,可用性}: Unix


3.2 新版功能.

@end deffn

@menu
* /dev/poll 轮询对象:: 
* 边缘触发和水平触发的轮询 (epoll) 对象: 边缘触发和水平触发的轮询 epoll 对象. 
* Poll 对象:: 
* Kqueue 对象:: 
* Kevent 对象:: 

@end menu

@node /dev/poll 轮询对象,边缘触发和水平触发的轮询 epoll 对象,,select --- 等待 I/O 完成
@anchor{library/select dev-poll-polling-objects}@anchor{2886}@anchor{library/select devpoll-objects}@anchor{287f}
@subsubsection @code{/dev/poll} 轮询对象


Solaris 及其衍生版本具备 @code{/dev/poll}。@code{select()} 复杂度为 O（最高文件描述符），@code{poll()} 为 O（文件描述符数量），而 @code{/dev/poll} 为 O（活动的文件描述符）。

@code{/dev/poll} 的行为与标准 @code{poll()} 对象十分类似。

@geindex close() (select.devpoll 方法)
@anchor{library/select select devpoll close}@anchor{99d}
@deffn {方法} devpoll.close ()

关闭轮询对象的文件描述符。


3.4 新版功能.

@end deffn

@geindex closed (select.devpoll 属性)
@anchor{library/select select devpoll closed}@anchor{99e}
@deffn {属性} devpoll.closed

如果轮询对象已关闭，则返回 @code{True}。


3.4 新版功能.

@end deffn

@geindex fileno() (select.devpoll 方法)
@anchor{library/select select devpoll fileno}@anchor{99c}
@deffn {方法} devpoll.fileno ()

返回轮询对象的文件描述符对应的数字。


3.4 新版功能.

@end deffn

@geindex register() (select.devpoll 方法)
@anchor{library/select select devpoll register}@anchor{2887}
@deffn {方法} devpoll.register (fd[, eventmask])

在轮询对象中注册文件描述符。这样，将来调用 @ref{2866,,poll()} 方法时将检查文件描述符是否有未处理的 I/O 事件。@emph{fd} 可以是整数，也可以是带有 @ref{209a,,fileno()} 方法的对象（该方法返回一个整数）。文件对象已经实现了 @code{fileno()}，因此它们也可以用作参数。

@emph{eventmask} 是可选的位掩码，用于指定要检查的事件类型。这些常量与 @code{poll()} 对象所用的相同。本参数的默认值是常量 @code{POLLIN}、@code{POLLPRI} 和 @code{POLLOUT} 的组合。

@cartouche
@quotation 警告 
注册已注册过的文件描述符不会报错，但是结果是不确定的。正确的操作是先注销或直接修改它。与 @code{poll()} 相比，这是一个重要的区别。
@end quotation
@end cartouche
@end deffn

@geindex modify() (select.devpoll 方法)
@anchor{library/select select devpoll modify}@anchor{2888}
@deffn {方法} devpoll.modify (fd[, eventmask])

此方法先执行 @ref{2889,,unregister()} 后执行 @ref{2887,,register()}。直接执行此操作效率（稍微）高一些。
@end deffn

@geindex unregister() (select.devpoll 方法)
@anchor{library/select select devpoll unregister}@anchor{2889}
@deffn {方法} devpoll.unregister (fd)

删除轮询对象正在跟踪的某个文件描述符。与 @ref{2887,,register()} 方法类似，@emph{fd} 可以是整数，也可以是带有 @ref{209a,,fileno()} 方法的对象（该方法返回一个整数）。

尝试删除从未注册过的文件描述符将被安全地忽略。
@end deffn

@geindex poll() (select.devpoll 方法)
@anchor{library/select select devpoll poll}@anchor{76c}
@deffn {方法} devpoll.poll ([timeout])

轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能有多个 @code{(fd, event)} 二元组，其中包含了要报告事件或错误的描述符。@emph{fd} 是文件描述符，@emph{event} 是一个位掩码，表示该描述符所报告的事件 --- @code{POLLIN} 表示可以读取，@code{POLLOUT} 表示该描述符可以写入，依此类推。空列表表示调用超时，没有任何文件描述符报告事件。如果指定了 @emph{timeout}，它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果 @emph{timeout} 为空，-1 或 @ref{204,,None}，则本调用将阻塞，直到轮询对象发生事件为止。


在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，不会抛出 @ref{756,,InterruptedError} 异常。除非信号处理程序抛出异常（相关原理请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@end deffn

@node 边缘触发和水平触发的轮询 epoll 对象,Poll 对象,/dev/poll 轮询对象,select --- 等待 I/O 完成
@anchor{library/select edge-and-level-trigger-polling-epoll-objects}@anchor{288a}@anchor{library/select epoll-objects}@anchor{2880}
@subsubsection 边缘触发和水平触发的轮询 (epoll) 对象


@quotation

@indicateurl{https://linux.die.net/man/4/epoll}

@emph{eventmask}


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{EPOLLIN}

@tab

可读

@item

@code{EPOLLOUT}

@tab

可写

@item

@code{EPOLLPRI}

@tab

紧急数据读取

@item

@code{EPOLLERR}

@tab

在关联的文件描述符上有错误情况发生

@item

@code{EPOLLHUP}

@tab

关联的文件描述符已挂起

@item

@code{EPOLLET}

@tab

设置触发方式为边缘触发，默认为水平触发

@item

@code{EPOLLONESHOT}

@tab

设置 one-shot 模式。触发一次事件后，该描述符会在轮询对象内部被禁用。

@item

@code{EPOLLEXCLUSIVE}

@tab

当已关联的描述符发生事件时，仅唤醒一个 epoll 对象。默认（如果未设置此标志）是唤醒所有轮询该描述符的 epoll 对象。

@item

@code{EPOLLRDHUP}

@tab

流套接字的对侧关闭了连接或关闭了写入到一半的连接。

@item

@code{EPOLLRDNORM}

@tab

等同于 @code{EPOLLIN}

@item

@code{EPOLLRDBAND}

@tab

可以读取优先数据带。

@item

@code{EPOLLWRNORM}

@tab

等同于 @code{EPOLLOUT}

@item

@code{EPOLLWRBAND}

@tab

可以写入优先级数据。

@item

@code{EPOLLMSG}

@tab

忽略

@end multitable



3.6 新版功能: 增加了 @code{EPOLLEXCLUSIVE}。仅支持 Linux Kernel 4.5 或更高版本。

@end quotation

@geindex close() (select.epoll 方法)
@anchor{library/select select epoll close}@anchor{99a}
@deffn {方法} epoll.close ()

关闭用于控制 epoll 对象的文件描述符。
@end deffn

@geindex closed (select.epoll 属性)
@anchor{library/select select epoll closed}@anchor{288b}
@deffn {属性} epoll.closed

如果 epoll 对象已关闭，则返回 @code{True}。
@end deffn

@geindex fileno() (select.epoll 方法)
@anchor{library/select select epoll fileno}@anchor{288c}
@deffn {方法} epoll.fileno ()

返回文件描述符对应的数字，该描述符用于控制 epoll 对象。
@end deffn

@geindex fromfd() (select.epoll 方法)
@anchor{library/select select epoll fromfd}@anchor{288d}
@deffn {方法} epoll.fromfd (fd)

根据给定的文件描述符创建 epoll 对象。
@end deffn

@geindex register() (select.epoll 方法)
@anchor{library/select select epoll register}@anchor{288e}
@deffn {方法} epoll.register (fd[, eventmask])

在 epoll 对象中注册一个文件描述符。
@end deffn

@geindex modify() (select.epoll 方法)
@anchor{library/select select epoll modify}@anchor{288f}
@deffn {方法} epoll.modify (fd, eventmask)

修改一个已注册的文件描述符。
@end deffn

@geindex unregister() (select.epoll 方法)
@anchor{library/select select epoll unregister}@anchor{22f}
@deffn {方法} epoll.unregister (fd)

从 epoll 对象中删除一个已注册的文件描述符。


在 3.9 版更改: 此方法不会再忽略 @ref{230,,EBADF} 错误。

@end deffn

@geindex poll() (select.epoll 方法)
@anchor{library/select select epoll poll}@anchor{76d}
@deffn {方法} epoll.poll (timeout=None, maxevents=-1)

等待事件发生，timeout 是浮点数，单位为秒。


在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，不会抛出 @ref{756,,InterruptedError} 异常。除非信号处理程序抛出异常（相关原理请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@end deffn

@node Poll 对象,Kqueue 对象,边缘触发和水平触发的轮询 epoll 对象,select --- 等待 I/O 完成
@anchor{library/select poll-objects}@anchor{2881}@anchor{library/select polling-objects}@anchor{2890}
@subsubsection Poll 对象


大多数 Unix 系统支持 @code{poll()} 系统调用，为服务器提供了更好的可伸缩性，使服务器可以同时服务于大量客户端。@code{poll()} 的伸缩性更好，因为该调用内部仅列出所关注的文件描述符，而 @code{select()} 会构造一个 bitmap，在其中将所关注的描述符所对应的 bit 打开，然后重新遍历整个 bitmap。因此 @code{select()} 复杂度是 O（最高文件描述符），而 @code{poll()} 是 O（文件描述符数量）。

@geindex register() (select.poll 方法)
@anchor{library/select select poll register}@anchor{2891}
@deffn {方法} poll.register (fd[, eventmask])

在轮询对象中注册文件描述符。这样，将来调用 @ref{2866,,poll()} 方法时将检查文件描述符是否有未处理的 I/O 事件。@emph{fd} 可以是整数，也可以是带有 @ref{209a,,fileno()} 方法的对象（该方法返回一个整数）。文件对象已经实现了 @code{fileno()}，因此它们也可以用作参数。

@emph{eventmask} 是可选的位掩码，用于指定要检查的事件类型，它可以是常量 @code{POLLIN}、@code{POLLPRI} 和 @code{POLLOUT} 的组合，如下表所述。如果未指定本参数，默认将会检查所有 3 种类型的事件。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{POLLIN}

@tab

有要读取的数据

@item

@code{POLLPRI}

@tab

有紧急数据需要读取

@item

@code{POLLOUT}

@tab

准备输出：写不会阻塞

@item

@code{POLLERR}

@tab

某种错误条件

@item

@code{POLLHUP}

@tab

挂起

@item

@code{POLLRDHUP}

@tab

流套接字的对侧关闭了连接，或关闭了写入到一半的连接

@item

@code{POLLNVAL}

@tab

无效的请求：描述符未打开

@end multitable


注册已注册过的文件描述符不会报错，且等同于只注册一次该描述符。
@end deffn

@geindex modify() (select.poll 方法)
@anchor{library/select select poll modify}@anchor{2892}
@deffn {方法} poll.modify (fd, eventmask)

修改一个已注册的文件描述符，等同于 @code{register(fd, eventmask)}。尝试修改未注册的文件描述符会抛出 @ref{30b,,OSError} 异常，错误码为 @code{ENOENT}。
@end deffn

@geindex unregister() (select.poll 方法)
@anchor{library/select select poll unregister}@anchor{2893}
@deffn {方法} poll.unregister (fd)

删除轮询对象正在跟踪的某个文件描述符。与 @ref{2891,,register()} 方法类似，@emph{fd} 可以是整数，也可以是带有 @ref{209a,,fileno()} 方法的对象（该方法返回一个整数）。

尝试删除从未注册过的文件描述符会抛出 @ref{3f1,,KeyError} 异常。
@end deffn

@geindex poll() (select.poll 方法)
@anchor{library/select select poll poll}@anchor{76f}
@deffn {方法} poll.poll ([timeout])

轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能有多个 @code{(fd, event)} 二元组，其中包含了要报告事件或错误的描述符。@emph{fd} 是文件描述符，@emph{event} 是一个位掩码，表示该描述符所报告的事件 --- @code{POLLIN} 表示可以读取，@code{POLLOUT} 表示该描述符可以写入，依此类推。空列表表示调用超时，没有任何文件描述符报告事件。如果指定了 @emph{timeout}，它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果 @emph{timeout} 为空、负数 或 @ref{204,,None}，则本调用将阻塞，直到轮询对象发生事件为止。


在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，不会抛出 @ref{756,,InterruptedError} 异常。除非信号处理程序抛出异常（相关原理请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@end deffn

@node Kqueue 对象,Kevent 对象,Poll 对象,select --- 等待 I/O 完成
@anchor{library/select id1}@anchor{2894}@anchor{library/select kqueue-objects}@anchor{2883}
@subsubsection Kqueue 对象


@geindex close() (select.kqueue 方法)
@anchor{library/select select kqueue close}@anchor{2895}
@deffn {方法} kqueue.close ()

关闭用于控制 kqueue 对象的文件描述符。
@end deffn

@geindex closed (select.kqueue 属性)
@anchor{library/select select kqueue closed}@anchor{2896}
@deffn {属性} kqueue.closed

如果 kqueue 对象已关闭，则返回 @code{True}。
@end deffn

@geindex fileno() (select.kqueue 方法)
@anchor{library/select select kqueue fileno}@anchor{2897}
@deffn {方法} kqueue.fileno ()

返回文件描述符对应的数字，该描述符用于控制 epoll 对象。
@end deffn

@geindex fromfd() (select.kqueue 方法)
@anchor{library/select select kqueue fromfd}@anchor{2898}
@deffn {方法} kqueue.fromfd (fd)

根据给定的文件描述符创建 kqueue 对象。
@end deffn

@geindex control() (select.kqueue 方法)
@anchor{library/select select kqueue control}@anchor{76e}
@deffn {方法} kqueue.control (changelist, max_events[, timeout]) -> eventlist

Kevent 的低级接口


@itemize -

@item 
changelist 必须是一个可迭代对象，迭代出 kevent 对象，否则置为 @code{None}。

@item 
max_events 必须是 0 或一个正整数。

@item 
timeout 单位为秒（一般为浮点数），默认为 @code{None}，即永不超时。
@end itemize


在 3.5 版更改: 现在，当本函数被信号中断时，重试超时将从头开始计时，不会抛出 @ref{756,,InterruptedError} 异常。除非信号处理程序抛出异常（相关原理请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475}）。

@end deffn

@node Kevent 对象,,Kqueue 对象,select --- 等待 I/O 完成
@anchor{library/select id2}@anchor{2899}@anchor{library/select kevent-objects}@anchor{2885}
@subsubsection Kevent 对象


@indicateurl{https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2}

@geindex ident (select.kevent 属性)
@anchor{library/select select kevent ident}@anchor{289a}
@deffn {属性} kevent.ident

用于区分事件的标识值。其解释取决于筛选器，但该值通常是文件描述符。在构造函数中，该标识值可以是整数或带有 @ref{209a,,fileno()} 方法的对象。kevent 在内部存储整数。
@end deffn

@geindex filter (select.kevent 属性)
@anchor{library/select select kevent filter}@anchor{289b}
@deffn {属性} kevent.filter

内核筛选器的名称。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_FILTER_READ}

@tab

获取描述符，并在有数据可读时返回

@item

@code{KQ_FILTER_WRITE}

@tab

获取描述符，并在有数据可写时返回

@item

@code{KQ_FILTER_AIO}

@tab

AIO 请求

@item

@code{KQ_FILTER_VNODE}

@tab

当在 @emph{fflag} 中监视的一个或多个请求事件发生时返回

@item

@code{KQ_FILTER_PROC}

@tab

监视进程ID上的事件

@item

@code{KQ_FILTER_NETDEV}

@tab

观察网络设备上的事件 [在 macOS 上不可用]

@item

@code{KQ_FILTER_SIGNAL}

@tab

每当监视的信号传递到进程时返回

@item

@code{KQ_FILTER_TIMER}

@tab

建立一个任意的计时器

@end multitable

@end deffn

@geindex flags (select.kevent 属性)
@anchor{library/select select kevent flags}@anchor{289c}
@deffn {属性} kevent.flags

筛选器操作。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_EV_ADD}

@tab

添加或修改事件

@item

@code{KQ_EV_DELETE}

@tab

从队列中删除事件

@item

@code{KQ_EV_ENABLE}

@tab

Permitscontrol() 返回事件

@item

@code{KQ_EV_DISABLE}

@tab

禁用事件

@item

@code{KQ_EV_ONESHOT}

@tab

在第一次发生后删除事件

@item

@code{KQ_EV_CLEAR}

@tab

检索事件后重置状态

@item

@code{KQ_EV_SYSFLAGS}

@tab

内部事件

@item

@code{KQ_EV_FLAG1}

@tab

内部事件

@item

@code{KQ_EV_EOF}

@tab

筛选特定EOF条件

@item

@code{KQ_EV_ERROR}

@tab

请参阅返回值

@end multitable

@end deffn

@geindex fflags (select.kevent 属性)
@anchor{library/select select kevent fflags}@anchor{289d}
@deffn {属性} kevent.fflags

筛选特定标志。

@code{KQ_FILTER_READ} 和  @code{KQ_FILTER_WRITE} 筛选标志：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_NOTE_LOWAT}

@tab

套接字缓冲区的低水线

@end multitable


@code{KQ_FILTER_VNODE} 筛选标志：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_NOTE_DELETE}

@tab

已调用 @emph{unlink()}

@item

@code{KQ_NOTE_WRITE}

@tab

发生写入

@item

@code{KQ_NOTE_EXTEND}

@tab

文件已扩展

@item

@code{KQ_NOTE_ATTRIB}

@tab

属性已更改

@item

@code{KQ_NOTE_LINK}

@tab

链接计数已更改

@item

@code{KQ_NOTE_RENAME}

@tab

文件已重命名

@item

@code{KQ_NOTE_REVOKE}

@tab

对文件的访问权限已被撤销

@end multitable


@code{KQ_FILTER_PROC} filter flags:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_NOTE_EXIT}

@tab

进程已退出

@item

@code{KQ_NOTE_FORK}

@tab

该进程调用了 @emph{fork()}

@item

@code{KQ_NOTE_EXEC}

@tab

进程已执行新进程

@item

@code{KQ_NOTE_PCTRLMASK}

@tab

内部筛选器标志

@item

@code{KQ_NOTE_PDATAMASK}

@tab

内部筛选器标志

@item

@code{KQ_NOTE_TRACK}

@tab

跨  @emph{fork()} 执行进程

@item

@code{KQ_NOTE_CHILD}

@tab

在  @emph{NOTE_TRACK} 的子进程上返回

@item

@code{KQ_NOTE_TRACKERR}

@tab

无法附加到子对象

@end multitable


@code{KQ_FILTER_NETDEV} 过滤器旗标 (在 macOS 上不可用):


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{KQ_NOTE_LINKUP}

@tab

链接已建立

@item

@code{KQ_NOTE_LINKDOWN}

@tab

链接已断开

@item

@code{KQ_NOTE_LINKINV}

@tab

链接状态无效

@end multitable

@end deffn

@geindex data (select.kevent 属性)
@anchor{library/select select kevent data}@anchor{289e}
@deffn {属性} kevent.data

筛选特定数据。
@end deffn

@geindex udata (select.kevent 属性)
@anchor{library/select select kevent udata}@anchor{289f}
@deffn {属性} kevent.udata

用户自定义值。
@end deffn

@node selectors --- 高级 I/O 复用库,signal --- 设置异步事件处理程序,select --- 等待 I/O 完成,网络和进程间通信
@anchor{library/selectors doc}@anchor{28a0}@anchor{library/selectors module-selectors}@anchor{e6}@anchor{library/selectors selectors-high-level-i-o-multiplexing}@anchor{28a1}
@subsection @code{selectors} --- 高级 I/O 复用库


@geindex selectors (模块)


3.4 新版功能.


@strong{源码:} Lib/selectors.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/selectors.py}


__________________________________________________________________


@menu
* 概述: 概述<10>. 
* 类: 类<3>. 
* 示例: 示例<25>. 

@end menu

@node 概述<10>,类<3>,,selectors --- 高级 I/O 复用库
@anchor{library/selectors introduction}@anchor{28a2}
@subsubsection 概述


此模块允许高层级且高效率的 I/O 复用，它建立在 @ref{e5,,select} 模块原型的基础之上。 推荐用户改用此模块，除非他们希望对所使用的 OS 层级原型进行精确控制。

它定义了一个 @ref{28a3,,BaseSelector} 抽象基类，以及多个实际的实现 (@ref{27a7,,KqueueSelector}, @ref{556,,EpollSelector}...)，它们可被用于在多个文件对象上等待 I/O 就绪通知。 在下文中，"文件对象" 是指任何具有 @code{fileno()} 方法的对象，或是一个原始文件描述器。 参见 @ref{c1d,,file object}。

@ref{28a4,,DefaultSelector} 是一个指向当前平台上可用的最高效实现的别名：这应为大多数用户的默认选择。

@cartouche
@quotation 注解 
受支持的文件对象类型取决于具体平台：在 Windows 上，支持套接字但不支持管道，而在 Unix 上两者均受支持（某些其他类型也可能受支持，例如 fifo 或特殊文件设备等）。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item @ref{e5,,select}

低层级的 I/O 多路复用模块。
@end table


@node 类<3>,示例<25>,概述<10>,selectors --- 高级 I/O 复用库
@anchor{library/selectors classes}@anchor{28a5}
@subsubsection 类


类的层次结构:

@example
BaseSelector
+-- SelectSelector
+-- PollSelector
+-- EpollSelector
+-- DevpollSelector
+-- KqueueSelector
@end example

下文中，@emph{events} 一个位掩码，指明哪些 I/O 事件要在给定的文件对象上执行等待。 它可以是以下模块级常量的组合:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常量

@tab

含意

@item

@code{EVENT_READ}

@tab

可读

@item

@code{EVENT_WRITE}

@tab

可写

@end multitable

@end quotation

@geindex SelectorKey (selectors 中的类)
@anchor{library/selectors selectors SelectorKey}@anchor{28a6}
@deffn {类} selectors.SelectorKey

@ref{28a6,,SelectorKey} 是一个 @ref{1a1,,namedtuple}，用来将文件对象关联到其下层的文件描述器、选定事件掩码和附加数据等。 它会被某些 @ref{28a3,,BaseSelector} 方法返回。

@geindex fileobj (selectors.SelectorKey 属性)
@anchor{library/selectors selectors SelectorKey fileobj}@anchor{28a7}
@deffn {属性} fileobj

已注册的文件对象。
@end deffn

@geindex fd (selectors.SelectorKey 属性)
@anchor{library/selectors selectors SelectorKey fd}@anchor{28a8}
@deffn {属性} fd

下层的文件描述器。
@end deffn

@geindex events (selectors.SelectorKey 属性)
@anchor{library/selectors selectors SelectorKey events}@anchor{28a9}
@deffn {属性} events

必须在此文件对象上被等待的事件。
@end deffn

@geindex data (selectors.SelectorKey 属性)
@anchor{library/selectors selectors SelectorKey data}@anchor{28aa}
@deffn {属性} data

可选的关联到此文件对象的不透明数据：例如，这可被用来存储各个客户端的会话 ID。
@end deffn
@end deffn

@geindex BaseSelector (selectors 中的类)
@anchor{library/selectors selectors BaseSelector}@anchor{28a3}
@deffn {类} selectors.BaseSelector

一个 @ref{28a3,,BaseSelector}，用来在多个文件对象上等待 I/O 事件就绪。 它支持文件流注册、注销，以及在这些流上等待 I/O 事件的方法。 它是一个抽象基类，因此不能被实例化。 请改用 @ref{28a4,,DefaultSelector}，或者 @ref{27a4,,SelectSelector}, @ref{27a7,,KqueueSelector} 等。 如果你想要指明使用某个实现，并且你的平台支持它的话。 @ref{28a3,,BaseSelector} 及其具体实现支持 @ref{66b,,context manager} 协议。

@geindex register() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector register}@anchor{28ab}
@deffn {方法} abstractmethod register (fileobj, events, data=None)

注册一个用于选择的文件对象，在其上监视 I/O 事件。

@emph{fileobj} 是要监视的文件对象。 它可以是整数形式的文件描述符或者具有 @code{fileno()} 方法的对象。 @emph{events} 是要监视的事件的位掩码。 @emph{data} 是一个不透明对象。

这将返回一个新的 @ref{28a6,,SelectorKey} 实例，或在出现无效事件掩码或文件描述符时引发 @ref{16d,,ValueError}，或在文件对象已被注册时引发 @ref{3f1,,KeyError}。
@end deffn

@geindex unregister() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector unregister}@anchor{28ac}
@deffn {方法} abstractmethod unregister (fileobj)

注销对一个文件对象的选择，移除对它的监视。 在文件对象被关闭之前应当先将其注销。

@emph{fileobj} 必须是之前已注册的文件对象。

这将返回已关联的 @ref{28a6,,SelectorKey} 实例，或者如果 @emph{fileobj} 未注册则会引发 @ref{3f1,,KeyError}。 It will raise @ref{16d,,ValueError} 如果 @emph{fileobj} 无效（例如它没有 @code{fileno()} 方法或其 @code{fileno()} 方法返回无效值）。
@end deffn

@geindex modify() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector modify}@anchor{559}
@deffn {方法} modify (fileobj, events, data=None)

更改已注册文件对象所监视的事件或所附带的数据。

这等价于 @code{BaseSelector.unregister(fileobj)()} 加 @code{BaseSelector.register(fileobj, events, data)()}，区别在于它可以被更高效地实现。

这将返回一个新的 @ref{28a6,,SelectorKey} 实例，或在出现无效事件掩码或文件描述符时引发 @ref{16d,,ValueError}，或在文件对象未被注册时引发 @ref{3f1,,KeyError}。
@end deffn

@geindex select() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector select}@anchor{28ad}
@deffn {方法} abstractmethod select (timeout=None)

等待直到有已注册的文件对象就绪，或是超过时限。

如果 @code{timeout > 0}，这指定以秒数表示的最大等待时间。 如果 @code{timeout <= 0}，调用将不会阻塞，并将报告当前就绪的文件对象。 如果 @emph{timeout} 为 @code{None}，调用将阻塞直到某个被监视的文件对象就绪。

这将返回由 @code{(key, events)} 元组构成的列表，每项各表示一个就绪的文件对象。

@emph{key} 是对应于就绪文件对象的 @ref{28a6,,SelectorKey} 实例。 @emph{events} 是在此文件对象上等待的事件位掩码。

@cartouche
@quotation 注解 
如果当前进程收到一个信号，此方法可在任何文件对象就绪之前或超出时限时返回：在此情况下，将返回一个空列表。
@end quotation
@end cartouche


在 3.5 版更改: 现在当被某个信号中断时，如果信号处理程序没有引发异常，选择器会用重新计算的超时值进行重试（请查看 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} 其理由），而不是在超时之前返回空的事件列表。

@end deffn

@geindex close() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector close}@anchor{28ae}
@deffn {方法} close ()

关闭选择器。

必须调用这个方法以确保下层资源会被释放。 选择器被关闭后将不可再使用。
@end deffn

@geindex get_key() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector get_key}@anchor{28af}
@deffn {方法} get_key (fileobj)

返回关联到某个已注册文件对象的键。

此方法将返回关联到文件对象的 @ref{28a6,,SelectorKey} 实例，或在文件对象未注册时引发 @ref{3f1,,KeyError}。
@end deffn

@geindex get_map() (selectors.BaseSelector 方法)
@anchor{library/selectors selectors BaseSelector get_map}@anchor{28b0}
@deffn {方法} abstractmethod get_map ()

返回从文件对象到选择器键的映射。

这将返回一个将已注册文件对象映射到与其相关联的 @ref{28a6,,SelectorKey} 实例的 @ref{15f,,Mapping} 实例。
@end deffn
@end deffn

@geindex DefaultSelector (selectors 中的类)
@anchor{library/selectors selectors DefaultSelector}@anchor{28a4}
@deffn {类} selectors.DefaultSelector

默认的选择器类，使用当前平台上可用的最高效实现。 这应为大多数用户的默认选择。
@end deffn

@geindex SelectSelector (selectors 中的类)
@anchor{library/selectors selectors SelectSelector}@anchor{27a4}
@deffn {类} selectors.SelectSelector

基于 @ref{770,,select.select()} 的选择器。
@end deffn

@geindex PollSelector (selectors 中的类)
@anchor{library/selectors selectors PollSelector}@anchor{557}
@deffn {类} selectors.PollSelector

基于 @ref{2866,,select.poll()} 的选择器。
@end deffn

@geindex EpollSelector (selectors 中的类)
@anchor{library/selectors selectors EpollSelector}@anchor{556}
@deffn {类} selectors.EpollSelector

基于 @ref{999,,select.epoll()} 的选择器。

@geindex fileno() (selectors.EpollSelector 方法)
@anchor{library/selectors selectors EpollSelector fileno}@anchor{28b1}
@deffn {方法} fileno ()

此方法将返回由下层 @ref{999,,select.epoll()} 对象所使用的文件描述符。
@end deffn
@end deffn

@geindex DevpollSelector (selectors 中的类)
@anchor{library/selectors selectors DevpollSelector}@anchor{558}
@deffn {类} selectors.DevpollSelector

基于 @ref{99b,,select.devpoll()} 的选择器。

@geindex fileno() (selectors.DevpollSelector 方法)
@anchor{library/selectors selectors DevpollSelector fileno}@anchor{28b2}
@deffn {方法} fileno ()

此方法将返回由下层 @ref{99b,,select.devpoll()} 对象所使用的文件描述符。
@end deffn


3.5 新版功能.

@end deffn

@geindex KqueueSelector (selectors 中的类)
@anchor{library/selectors selectors KqueueSelector}@anchor{27a7}
@deffn {类} selectors.KqueueSelector

基于 @ref{2882,,select.kqueue()} 的选择器。

@geindex fileno() (selectors.KqueueSelector 方法)
@anchor{library/selectors selectors KqueueSelector fileno}@anchor{28b3}
@deffn {方法} fileno ()

此方法将返回由下层 @ref{2882,,select.kqueue()} 对象所使用的文件描述符。
@end deffn
@end deffn

@node 示例<25>,,类<3>,selectors --- 高级 I/O 复用库
@anchor{library/selectors examples}@anchor{28b4}
@subsubsection 示例


下面是一个简单的回显服务器实现:

@example
import selectors
import socket

sel = selectors.DefaultSelector()

def accept(sock, mask):
    conn, addr = sock.accept()  # Should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False)
    sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
    data = conn.recv(1000)  # Should be ready
    if data:
        print('echoing', repr(data), 'to', conn)
        conn.send(data)  # Hope it won't block
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind(('localhost', 1234))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
    events = sel.select()
    for key, mask in events:
        callback = key.data
        callback(key.fileobj, mask)
@end example

@node signal --- 设置异步事件处理程序,mmap --- 内存映射文件支持,selectors --- 高级 I/O 复用库,网络和进程间通信
@anchor{library/signal doc}@anchor{28b5}@anchor{library/signal module-signal}@anchor{ea}@anchor{library/signal signal-set-handlers-for-asynchronous-events}@anchor{28b6}
@subsection @code{signal} --- 设置异步事件处理程序


@geindex signal (模块)


__________________________________________________________________


该模块提供了在 Python 中使用信号处理程序的机制。

@menu
* 一般规则:: 
* 模块内容: 模块内容<5>. 
* 示例: 示例<26>. 
* 对于 SIGPIPE 的说明:: 
* 有关信号处理句柄和异常的注释:: 

@end menu

@node 一般规则,模块内容<5>,,signal --- 设置异步事件处理程序
@anchor{library/signal general-rules}@anchor{28b7}
@subsubsection 一般规则


@ref{b61,,signal.signal()} 函数允许定义在接收到信号时执行的自定义处理程序。少量的默认处理程序已经设置： @ref{28b8,,SIGPIPE} 被忽略（因此管道和套接字上的写入错误可以报告为普通的 Python 异常）以及如果父进程没有更改 @ref{263c,,SIGINT} ，则其会被翻译成 @ref{2d3,,KeyboardInterrupt} 异常。

一旦设置，特定信号的处理程序将保持安装，直到它被显式重置（ Python 模拟 BSD 样式接口而不管底层实现），但 @ref{28b9,,SIGCHLD} 的处理程序除外，它遵循底层实现。

@menu
* 执行 Python 信号处理程序:: 
* 信号与线程:: 

@end menu

@node 执行 Python 信号处理程序,信号与线程,,一般规则
@anchor{library/signal execution-of-python-signal-handlers}@anchor{28ba}
@subsubsection 执行 Python 信号处理程序


Python 信号处理程序不会在低级（ C ）信号处理程序中执行。相反，低级信号处理程序设置一个标志，告诉 @ref{28bb,,virtual machine} 稍后执行相应的 Python 信号处理程序（例如在下一个 @ref{713,,bytecode} 指令）。这会导致：


@itemize *

@item 
捕获同步错误是没有意义的，例如 @ref{28bc,,SIGFPE} 或 @ref{28bd,,SIGSEGV} ，它们是由 C 代码中的无效操作引起的。Python 将从信号处理程序返回到 C 代码，这可能会再次引发相同的信号，导致 Python 显然的挂起。 从Python 3.3开始，你可以使用 @ref{7b,,faulthandler} 模块来报告同步错误。

@item 
纯 C 中实现的长时间运行的计算（例如在大量文本上的正则表达式匹配）可以在任意时间内不间断地运行，而不管接收到任何信号。计算完成后将调用 Python 信号处理程序。

@item 
如果处理句柄引发了异常，它将在主线程中“凭空”被引发。 请参阅 @ref{1884,,下面的注释} 讨论相关细节。
@end itemize

@node 信号与线程,,执行 Python 信号处理程序,一般规则
@anchor{library/signal id1}@anchor{28be}@anchor{library/signal signals-and-threads}@anchor{28bf}
@subsubsection 信号与线程


Python 信号处理程序总是会在主 Python 主解释器的主线程中执行，即使信号是在另一个线程中接收的。 这意味着信号不能被用作线程间通信的手段。 你可以改用 @ref{10b,,threading} 模块中的同步原语。

此外，只有主解释器的主线程才被允许设置新的信号处理程序。

@node 模块内容<5>,示例<26>,一般规则,signal --- 设置异步事件处理程序
@anchor{library/signal module-contents}@anchor{28c0}
@subsubsection 模块内容



在 3.5 版更改: 信号（ SIG* ），处理程序（ @ref{263d,,SIG_DFL} ， @ref{263e,,SIG_IGN}）和 sigmask（ @ref{28c1,,SIG_BLOCK} ， @ref{28c2,,SIG_UNBLOCK} ， @ref{28c3,,SIG_SETMASK} ）下面列出的相关常量变成了 @ref{68e,,enums} 。 @ref{28c4,,getsignal()} ， @ref{b5d,,pthread_sigmask()} ， @ref{b5f,,sigpending()} 和 @ref{b60,,sigwait()} 函数返回人类可读的 @ref{68e,,enums} 。


在 @ref{ea,,signal} 模块中定义的变量是：

@geindex SIG_DFL() (在 signal 模块中)
@anchor{library/signal signal SIG_DFL}@anchor{263d}
@deffn {数据} signal.SIG_DFL

这是两种标准信号处理选项之一；它只会执行信号的默认函数。 例如，在大多数系统上，对于 @code{SIGQUIT} 的默认操作是转储核心并退出，而对于 @ref{28b9,,SIGCHLD} 的默认操作是简单地忽略它。
@end deffn

@geindex SIG_IGN() (在 signal 模块中)
@anchor{library/signal signal SIG_IGN}@anchor{263e}
@deffn {数据} signal.SIG_IGN

这是另一个标准信号处理程序，它将简单地忽略给定的信号。
@end deffn

@geindex SIGABRT() (在 signal 模块中)
@anchor{library/signal signal SIGABRT}@anchor{28c5}
@deffn {数据} signal.SIGABRT

来自 @code{abort(3)} 的中止信号。
@end deffn

@geindex SIGALRM() (在 signal 模块中)
@anchor{library/signal signal SIGALRM}@anchor{28c6}
@deffn {数据} signal.SIGALRM

来自 @code{alarm(2)} 的计时器信号。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGBREAK() (在 signal 模块中)
@anchor{library/signal signal SIGBREAK}@anchor{28c7}
@deffn {数据} signal.SIGBREAK

来自键盘的中断 (CTRL + BREAK)。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex SIGBUS() (在 signal 模块中)
@anchor{library/signal signal SIGBUS}@anchor{28c8}
@deffn {数据} signal.SIGBUS

总线错误 (非法的内存访问)。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGCHLD() (在 signal 模块中)
@anchor{library/signal signal SIGCHLD}@anchor{28b9}
@deffn {数据} signal.SIGCHLD

子进程被停止或终结。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGCLD() (在 signal 模块中)
@anchor{library/signal signal SIGCLD}@anchor{28c9}
@deffn {数据} signal.SIGCLD

@ref{28b9,,SIGCHLD} 的别名。
@end deffn

@geindex SIGCONT() (在 signal 模块中)
@anchor{library/signal signal SIGCONT}@anchor{2159}
@deffn {数据} signal.SIGCONT

如果进程当前已停止则继续执行它

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGFPE() (在 signal 模块中)
@anchor{library/signal signal SIGFPE}@anchor{28bc}
@deffn {数据} signal.SIGFPE

浮点异常。 例如除以零。


@subsubheading 参见


当除法或求余运算的第二个参数为零时会引发 @ref{1fb,,ZeroDivisionError} 。

@end deffn

@geindex SIGHUP() (在 signal 模块中)
@anchor{library/signal signal SIGHUP}@anchor{28ca}
@deffn {数据} signal.SIGHUP

在控制终端上检测到挂起或控制进程的终止。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGILL() (在 signal 模块中)
@anchor{library/signal signal SIGILL}@anchor{28cb}
@deffn {数据} signal.SIGILL

非法指令。
@end deffn

@geindex SIGINT() (在 signal 模块中)
@anchor{library/signal signal SIGINT}@anchor{263c}
@deffn {数据} signal.SIGINT

来自键盘的中断 (CTRL + C)。

默认的动作是引发 @ref{2d3,,KeyboardInterrupt}。
@end deffn

@geindex SIGKILL() (在 signal 模块中)
@anchor{library/signal signal SIGKILL}@anchor{28cc}
@deffn {数据} signal.SIGKILL

终止信号。

它不能被捕获、阻塞或忽略。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGPIPE() (在 signal 模块中)
@anchor{library/signal signal SIGPIPE}@anchor{28b8}
@deffn {数据} signal.SIGPIPE

损坏的管道：写入到没有读取器的管道。

默认的动作是忽略此信号。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGSEGV() (在 signal 模块中)
@anchor{library/signal signal SIGSEGV}@anchor{28bd}
@deffn {数据} signal.SIGSEGV

段错误：无效的内存引用。
@end deffn

@geindex SIGTERM() (在 signal 模块中)
@anchor{library/signal signal SIGTERM}@anchor{26d4}
@deffn {数据} signal.SIGTERM

终结信号。
@end deffn

@geindex SIGUSR1() (在 signal 模块中)
@anchor{library/signal signal SIGUSR1}@anchor{28cd}
@deffn {数据} signal.SIGUSR1

用户自定义信号 1。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGUSR2() (在 signal 模块中)
@anchor{library/signal signal SIGUSR2}@anchor{28ce}
@deffn {数据} signal.SIGUSR2

用户自定义信号 2。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex SIGWINCH() (在 signal 模块中)
@anchor{library/signal signal SIGWINCH}@anchor{28cf}
@deffn {数据} signal.SIGWINCH

窗口调整大小信号。

@ref{14c1,,可用性}: Unix。
@end deffn


@deffn {数据} SIG*

所有信号编号都是符号化定义的。 例如，挂起信号被定义为 @ref{28ca,,signal.SIGHUP}；变量的名称与 C 程序中使用的名称相同，具体见 @code{<signal.h>}。 '@code{signal()}' 的 Unix 手册页面列出了现有的信号 (在某些系统上这是 @code{signal(2)}，在其他系统中此列表则是在 @code{signal(7)} 中)。 请注意并非所有系统都会定义相同的信号名称集；只有系统所定义的名称才会由此模块来定义。
@end deffn

@geindex CTRL_C_EVENT() (在 signal 模块中)
@anchor{library/signal signal CTRL_C_EVENT}@anchor{2130}
@deffn {数据} signal.CTRL_C_EVENT

对应于 @code{Ctrl+C} 击键事件的信号。此信号只能用于 @ref{dc1,,os.kill()} 。

@ref{14c1,,可用性}: Windows。


3.2 新版功能.

@end deffn

@geindex CTRL_BREAK_EVENT() (在 signal 模块中)
@anchor{library/signal signal CTRL_BREAK_EVENT}@anchor{2131}
@deffn {数据} signal.CTRL_BREAK_EVENT

对应于 @code{Ctrl+Break} 击键事件的信号。此信号只能用于 @ref{dc1,,os.kill()} 。

@ref{14c1,,可用性}: Windows。


3.2 新版功能.

@end deffn

@geindex NSIG() (在 signal 模块中)
@anchor{library/signal signal NSIG}@anchor{28d0}
@deffn {数据} signal.NSIG

比最高信号数多一。
@end deffn

@geindex ITIMER_REAL() (在 signal 模块中)
@anchor{library/signal signal ITIMER_REAL}@anchor{28d1}
@deffn {数据} signal.ITIMER_REAL

实时递减间隔计时器，并在到期时发送 @ref{28c6,,SIGALRM} 。
@end deffn

@geindex ITIMER_VIRTUAL() (在 signal 模块中)
@anchor{library/signal signal ITIMER_VIRTUAL}@anchor{28d2}
@deffn {数据} signal.ITIMER_VIRTUAL

仅在进程执行时递减间隔计时器，并在到期时发送 SIGVTALRM 。
@end deffn

@geindex ITIMER_PROF() (在 signal 模块中)
@anchor{library/signal signal ITIMER_PROF}@anchor{28d3}
@deffn {数据} signal.ITIMER_PROF

当进程执行时以及当系统替进程执行时都会减小间隔计时器。 这个计时器与 ITIMER_VIRTUAL 相配结，通常被用于分析应用程序在用户和内核空间中花费的时间。 SIGPROF 会在超期时被发送。
@end deffn

@geindex SIG_BLOCK() (在 signal 模块中)
@anchor{library/signal signal SIG_BLOCK}@anchor{28c1}
@deffn {数据} signal.SIG_BLOCK

@ref{b5d,,pthread_sigmask()} 的 @emph{how} 形参的一个可能的值，表明信号将会被阻塞。


3.3 新版功能.

@end deffn

@geindex SIG_UNBLOCK() (在 signal 模块中)
@anchor{library/signal signal SIG_UNBLOCK}@anchor{28c2}
@deffn {数据} signal.SIG_UNBLOCK

@ref{b5d,,pthread_sigmask()} 的 @emph{how} 形参的是个可能的值，表明信号将被解除阻塞。


3.3 新版功能.

@end deffn

@geindex SIG_SETMASK() (在 signal 模块中)
@anchor{library/signal signal SIG_SETMASK}@anchor{28c3}
@deffn {数据} signal.SIG_SETMASK

@ref{b5d,,pthread_sigmask()} 的 @emph{how} 形参的一个可能的值，表明信号掩码将要被替换。


3.3 新版功能.

@end deffn

@ref{ea,,signal} 模块定义了一个异常:

@geindex ItimerError
@anchor{library/signal signal ItimerError}@anchor{28d4}
@deffn {例外} signal.ItimerError

作为来自下层 @ref{28d5,,setitimer()} 或 @ref{28d6,,getitimer()} 实现错误的信号被引发。 如果将无效的定时器或负的时间值传给 @ref{28d5,,setitimer()} 就导致这个错误。 此错误是 @ref{30b,,OSError} 的子类型。


3.3 新版功能: 此错误是 @ref{a7c,,IOError} 的子类型，现在则是 @ref{30b,,OSError} 的别名。

@end deffn

@ref{ea,,signal} 模块定义了以下函数:

@geindex alarm() (在 signal 模块中)
@anchor{library/signal signal alarm}@anchor{28d7}
@deffn {函数} signal.alarm (time)

如果 @emph{time} 值非零，则此函数将要求将一个 @ref{28c6,,SIGALRM} 信号在 @emph{time} 秒内发往进程。 任何在之前排入计划的警报都会被取消（在任何时刻都只能有一个警报被排入计划）。 后续的返回值将是任何之前设置的警报被传入之前的秒数。 如果 @emph{time} 值为零，则不会将任何警报排入计划，并且任何已排入计划的警报都会被取消。 如果返回值为零，则目前没有任何警报被排入计划。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{alarm(2)}。
@end deffn

@geindex getsignal() (在 signal 模块中)
@anchor{library/signal signal getsignal}@anchor{28c4}
@deffn {函数} signal.getsignal (signalnum)

返回当前用于信号 @emph{signalnum} 的信号处理程序。 返回值可以是一个 Python 可调用对象，或是特殊值 @ref{263e,,signal.SIG_IGN}, @ref{263d,,signal.SIG_DFL} 或 @ref{204,,None} 之一。 在这里，@ref{263e,,signal.SIG_IGN} 表示信号在之前被忽略，@ref{263d,,signal.SIG_DFL} 表示之前在使用默认的信号处理方式，而 @code{None} 表示之前的信号处理程序未由 Python 安装。
@end deffn

@geindex strsignal() (在 signal 模块中)
@anchor{library/signal signal strsignal}@anchor{11ae}
@deffn {函数} signal.strsignal (signalnum)

返回信号 @emph{signalnum} 的系统描述，例如 "Interrupt", "Segmentation fault" 等等。 如果信号无法被识别则返回 @ref{204,,None}。


3.8 新版功能.

@end deffn

@geindex valid_signals() (在 signal 模块中)
@anchor{library/signal signal valid_signals}@anchor{28d8}
@deffn {函数} signal.valid_signals ()

返回本平台上的有效信号编号集。 这可能会少于 @code{range(1, NSIG)}，如果某些信号被系统保留作为内部使用的话。


3.8 新版功能.

@end deffn

@geindex pause() (在 signal 模块中)
@anchor{library/signal signal pause}@anchor{28d9}
@deffn {函数} signal.pause ()

使进程休眠直至接收到一个信号；然后将会调用适当的处理程序。 返回空值。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{signal(2)}。

另请参阅 @ref{b60,,sigwait()}, @ref{77c,,sigwaitinfo()}, @ref{77b,,sigtimedwait()} 和 @ref{b5f,,sigpending()}。
@end deffn

@geindex raise_signal() (在 signal 模块中)
@anchor{library/signal signal raise_signal}@anchor{28da}
@deffn {函数} signal.raise_signal (signum)

向调用方进程发送一个信号。 返回空值。


3.8 新版功能.

@end deffn

@geindex pidfd_send_signal() (在 signal 模块中)
@anchor{library/signal signal pidfd_send_signal}@anchor{1dd}
@deffn {函数} signal.pidfd_send_signal (pidfd, sig, siginfo=None, flags=0)

发送信号 @emph{sig} 到文件描述符 @emph{pidfd} 所指向的进程。 Python 目前不支持 @emph{siginfo} 形参；它必须为 @code{None}。 提供 @emph{flags} 参数是为了将来扩展；当前未定义旗标值。

更多信息请参阅 @code{pidfd_send_signal(2)} 手册页面。

@ref{14c1,,可用性}: Linux 5.1+


3.9 新版功能.

@end deffn

@geindex pthread_kill() (在 signal 模块中)
@anchor{library/signal signal pthread_kill}@anchor{b5e}
@deffn {函数} signal.pthread_kill (thread_id, signalnum)

将信号 @emph{signalnum} 发送至与调用者在同一进程中另一线程 @emph{thread_id}。 目标线程可被用于执行任何代码（Python或其它）。 但是，如果目标线程是在执行 Python 解释器，则 Python 信号处理程序将 @ref{28bf,,由主解释器的主线程来执行}。 因此，将信号发送给特定 Python 线程的唯一作用在于强制让一个正在运行的系统调用失败并抛出 @ref{756,,InterruptedError}。

使用 @ref{b90,,threading.get_ident()} 或 @ref{21b,,threading.Thread} 对象的 @ref{21a4,,ident} 属性为 @emph{thread_id} 获取合适的值。

如果 @emph{signalnum} 为 0，则不会发送信号，但仍然会执行错误检测；这可被用来检测目标线程是否仍在运行。

引发一个 @ref{fec,,审计事件} @code{signal.pthread_kill}，附带参数 @code{thread_id}, @code{signalnum}。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{pthread_kill(3)}。

另请参阅 @ref{dc1,,os.kill()}。


3.3 新版功能.

@end deffn

@geindex pthread_sigmask() (在 signal 模块中)
@anchor{library/signal signal pthread_sigmask}@anchor{b5d}
@deffn {函数} signal.pthread_sigmask (how, mask)

获取和/或修改调用方线程的信号掩码。 信号掩码是一组传送过程目前为调用者而阻塞的信号集。 返回旧的信号掩码作为一组信号。

该调用的行为取决于 @emph{how} 的值，具体见下。


@itemize *

@item 
@ref{28c1,,SIG_BLOCK}: 被阻塞信号集是当前集与 @emph{mask} 参数的并集。

@item 
@ref{28c2,,SIG_UNBLOCK}: @emph{mask} 中的信号会从当前已阻塞信号集中被移除。 允许尝试取消对一个非阻塞信号的阻塞。

@item 
@ref{28c3,,SIG_SETMASK}: 已阻塞信号集会被设为 @emph{mask} 参数的值。
@end itemize

@emph{mask} 是一个信号编号集合 (例如 @{@ref{263c,,signal.SIGINT}, @ref{26d4,,signal.SIGTERM}@})。 请使用 @ref{28d8,,valid_signals()} 表示包含所有信号的完全掩码。

例如，@code{signal.pthread_sigmask(signal.SIG_BLOCK, [])} 会读取调用方线程的信号掩码。

@ref{28cc,,SIGKILL} 和 @code{SIGSTOP} 不能被阻塞。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{sigprocmask(3)} 和 @code{pthread_sigmask(3)}。

另请参阅 @ref{28d9,,pause()}, @ref{b5f,,sigpending()} 和 @ref{b60,,sigwait()}。


3.3 新版功能.

@end deffn

@geindex setitimer() (在 signal 模块中)
@anchor{library/signal signal setitimer}@anchor{28d5}
@deffn {函数} signal.setitimer (which, seconds, interval=0.0)

设置由 @emph{which} 指明的给定间隔计时器 (@ref{28d1,,signal.ITIMER_REAL}, @ref{28d2,,signal.ITIMER_VIRTUAL} 或 @ref{28d3,,signal.ITIMER_PROF} 之一) 在 @emph{seconds} 秒 (接受浮点数值，为与 @ref{28d7,,alarm()} 之差) 之后开始并在每 @emph{interval} 秒间隔时 (如果 @emph{interval} 不为零) 启动。 由 @emph{which} 指明的间隔计时器可通过将 @emph{seconds} 设为零来清空。

当一个间隔计时器启动时，会有信号发送至进程。 所发送的具体信号取决于所使用的计时器；@ref{28d1,,signal.ITIMER_REAL} 将发送 @ref{28c6,,SIGALRM}, @ref{28d2,,signal.ITIMER_VIRTUAL} 将发送 @code{SIGVTALRM}, 而 @ref{28d3,,signal.ITIMER_PROF} 将发送 @code{SIGPROF}.

原有的值会以元组: (delay, interval) 的形式被返回。

尝试传入无效的计时器将导致 @ref{28d4,,ItimerError}。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getitimer() (在 signal 模块中)
@anchor{library/signal signal getitimer}@anchor{28d6}
@deffn {函数} signal.getitimer (which)

返回由 @emph{which} 指明的给定间隔计时器当前的值。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex set_wakeup_fd() (在 signal 模块中)
@anchor{library/signal signal set_wakeup_fd}@anchor{4dd}
@deffn {函数} signal.set_wakeup_fd (fd, *, warn_on_full_buffer=True)

将唤醒文件描述符设为 @emph{fd}。 当接收到信号时，会将信号编号以单个字节的形式写入 fd。 这可被其它库用来唤醒一次 poll 或 select 调用，以允许该信号被完全地处理。

原有的唤醒 fd 会被返回（或者如果未启用文件描述符唤醒则返回 -1）。 如果 @emph{fd} 为 -1，文件描述符唤醒会被禁用。 如果不为 -1，则 @emph{fd} 必须为非阻塞型。 需要由库来负责在重新调用 poll 或 select 之前从 @emph{fd} 移除任何字节数据。

当启用线程用时，此函数只能从 @ref{28bf,,主解释器的主线程} 被调用；尝试从另一线程调用它将导致 @ref{16d,,ValueError} 异常被引发。

使用此函数有两种通常的方式。 在两种方式下，当有信号到达时你都是用 fd 来唤醒，但之后它们在确定达到的一个或多个信号 @emph{which} 时存在差异。

在第一种方式下，我们从 fd 的缓冲区读取数据，这些字节值会给你信号编号。 这种方式很简单，但在少数情况下会发生问题：通常 fd 将有缓冲区空间大小限制，如果信号到达得太多且太快，缓冲区可能会爆满，有些信号可能丢失。 如果你使用此方式，则你应当设置 @code{warn_on_full_buffer=True}，当信号丢失时这至少能将警告消息打印到 stderr。

在第二种方式下，我们 @emph{只会} 将唤醒 fd 用于唤醒，而忽略实际的字节值。 在此情况下，我们所关心的只有 fd 的缓冲区为空还是不为空；爆满的缓冲区完全不会导致问题。 如果你使用此方式，则你应当设置 @code{warn_on_full_buffer=False}，这样你的用户就不会被虚假的警告消息所迷惑。


在 3.5 版更改: 在 Windows 上，此函数现在也支持套接字处理。



在 3.7 版更改: 添加了 @code{warn_on_full_buffer} 形参。

@end deffn

@geindex siginterrupt() (在 signal 模块中)
@anchor{library/signal signal siginterrupt}@anchor{b62}
@deffn {函数} signal.siginterrupt (signalnum, flag)

更改系统调用重启行为：如果 @emph{flag} 为 @ref{497,,False}，系统调用将在被信号 @emph{signalnum} 中断时重启，否则系统调用将被中断。 返回空值。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{siginterrupt(3)}。

请注意用 @ref{ea,,signal()} 安装信号处理程序将重启行为重置为可通过显式调用 @code{siginterrupt()} 并为给定信号的 @emph{flag} 设置真值来实现中断。
@end deffn

@geindex signal() (在 signal 模块中)
@anchor{library/signal signal signal}@anchor{b61}
@deffn {函数} signal.signal (signalnum, handler)

将信号 @emph{signalnum} 的处理程序设为函数 @emph{handler}。 @emph{handler} 可以为接受两个参数（见下）的 Python 可调用对象，或者为特殊值 @ref{263e,,signal.SIG_IGN} 或 @ref{263d,,signal.SIG_DFL} 之一。 之前的信号处理程序将被返回（参见上文 @ref{28c4,,getsignal()} 的描述）。 （更多信息请参阅 Unix 手册页面 @code{signal(2)}。）

当启用线程用时，此函数只能从 @ref{28bf,,主解释器的主线程} 被调用；尝试从另一线程调用它将导致 @ref{16d,,ValueError} 异常被引发。

@emph{handler} 将附带两个参数调用：信号编号和当前堆栈帧 (@code{None} 或一个帧对象；有关帧对象的描述请参阅 @ref{1594,,类型层级结构描述} 或者参阅 @ref{a0,,inspect} 模块中的属性描述)。

在 Windows 上，@ref{ea,,signal()} 调用只能附带 @ref{28c5,,SIGABRT}, @ref{28bc,,SIGFPE}, @ref{28cb,,SIGILL}, @ref{263c,,SIGINT}, @ref{28bd,,SIGSEGV}, @ref{26d4,,SIGTERM} 或 @ref{28c7,,SIGBREAK}。 任何其他值都将引发 @ref{16d,,ValueError}。 请注意不是所有系统都定义了同样的信号名称集合；如果一个信号名称未被定义为 @code{SIG*} 模块层级常量则将引发 @ref{4aa,,AttributeError}。
@end deffn

@geindex sigpending() (在 signal 模块中)
@anchor{library/signal signal sigpending}@anchor{b5f}
@deffn {函数} signal.sigpending ()

检查正在等待传送给调用方线程的信号集合（即在阻塞期间被引发的信号）。 返回正在等待的信号集合。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{sigpending(2)}。

另请参阅 @ref{28d9,,pause()}, @ref{b5d,,pthread_sigmask()} 和 @ref{b60,,sigwait()}。


3.3 新版功能.

@end deffn

@geindex sigwait() (在 signal 模块中)
@anchor{library/signal signal sigwait}@anchor{b60}
@deffn {函数} signal.sigwait (sigset)

挂起调用方线程的执行直到信号集合 @emph{sigset} 中指定的信号之一被传送。 此函数会接受该信号（将其从等待信号列表中移除），并返回信号编号。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{sigwait(3)}。

另请参阅 @ref{28d9,,pause()}, @ref{b5d,,pthread_sigmask()}, @ref{b5f,,sigpending()}, @ref{77c,,sigwaitinfo()} 和 @ref{77b,,sigtimedwait()}。


3.3 新版功能.

@end deffn

@geindex sigwaitinfo() (在 signal 模块中)
@anchor{library/signal signal sigwaitinfo}@anchor{77c}
@deffn {函数} signal.sigwaitinfo (sigset)

挂起调用方线程的执行直到信号集合 @emph{sigset} 中指定的信号之一被传送。 此函数会接受该信号并将其从等待信号列表中移除。 如果 @emph{sigset} 中的信号之一已经在等待调用方线程，此函数将立即返回并附带有关该信号的信息。 被传送信号的信号处理程序不会被调用。 如果该函数被某个不在 @emph{sigset} 中的信号中断则会引发 @ref{756,,InterruptedError}。

返回值是一个代表 @code{siginfo_t} 结构体所包含数据的对象，具体为: @code{si_signo}, @code{si_code}, @code{si_errno}, @code{si_pid}, @code{si_uid}, @code{si_status}, @code{si_band}。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{sigwaitinfo(2)}。

另请参阅 @ref{28d9,,pause()}, @ref{b60,,sigwait()} 和 @ref{77b,,sigtimedwait()}。


3.3 新版功能.



在 3.5 版更改: 当被某个 不在 @emph{sigset} 中的信号中断时本函数将进行重试并且信号处理程序不会引发异常（请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} 了解其理由）。

@end deffn

@geindex sigtimedwait() (在 signal 模块中)
@anchor{library/signal signal sigtimedwait}@anchor{77b}
@deffn {函数} signal.sigtimedwait (sigset, timeout)

类似于 @ref{77c,,sigwaitinfo()}，但会接受一个额外的 @emph{timeout} 参数来指定超时限制。 如果将 @emph{timeout} 指定为 @code{0}，则会执行轮询。 如果发生超时则返回 @ref{204,,None}。

@ref{14c1,,可用性}: Unix。 更多信息请参见手册页面 @code{sigtimedwait(2)}。

另请参阅 @ref{28d9,,pause()}, @ref{b60,,sigwait()} 和 @ref{77c,,sigwaitinfo()}。


3.3 新版功能.



在 3.5 版更改: 现在当此函数被某个不在 @emph{sigset} 中的信号中断时将以计算出的 @emph{timeout} 进行重试并且信号处理程序不会引发异常（请参阅 
@geindex Python 提高建议; PEP 475
PEP 475@footnote{https://www.python.org/dev/peps/pep-0475} 了解其理由）。

@end deffn

@node 示例<26>,对于 SIGPIPE 的说明,模块内容<5>,signal --- 设置异步事件处理程序
@anchor{library/signal example}@anchor{28db}@anchor{library/signal signal-example}@anchor{28dc}
@subsubsection 示例


这是一个最小示例程序。 它使用 @ref{28d7,,alarm()} 函数来限制等待打开一个文件所花费的时间；这在文件为无法开启的串行设备时会很有用处，此情况通常会导致 @ref{762,,os.open()} 无限期地挂起。  解决办法是在打开文件之前设置 5 秒钟的 alarm；如果操作耗时过长，将会发送 alarm 信号，并且处理程序会引发一个异常。

@example
import signal, os

def handler(signum, frame):
    print('Signal handler called with signal', signum)
    raise OSError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)

# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)

signal.alarm(0)          # Disable the alarm
@end example

@node 对于 SIGPIPE 的说明,有关信号处理句柄和异常的注释,示例<26>,signal --- 设置异步事件处理程序
@anchor{library/signal note-on-sigpipe}@anchor{28dd}
@subsubsection 对于 SIGPIPE 的说明


将你的程序用管道输出到工具例如 @code{head(1)} 将会导致 @ref{28b8,,SIGPIPE} 信号在其标准输出的接收方提前关闭时被发送到你的进程。 这将引发一个异常例如 @code{BrokenPipeError: [Errno 32] Broken pipe}。 要处理这种情况，请对你的入口点进行包装以捕获此异常，如下所示:

@example
import os
import sys

def main():
    try:
        # simulate large output (your code replaces this loop)
        for x in range(10000):
            print("y")
        # flush output here to force SIGPIPE to be triggered
        # while inside this try block.
        sys.stdout.flush()
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)  # Python exits with error code 1 on EPIPE

if __name__ == '__main__':
    main()
@end example

请不要将 @ref{28b8,,SIGPIPE} 的处置方式设为 @ref{263d,,SIG_DFL} 以避免 @ref{a87,,BrokenPipeError}。 这样做还会在你的程序所写入的任何套接字连接中断时导致你的程序异常退出。

@node 有关信号处理句柄和异常的注释,,对于 SIGPIPE 的说明,signal --- 设置异步事件处理程序
@anchor{library/signal handlers-and-exceptions}@anchor{1884}@anchor{library/signal note-on-signal-handlers-and-exceptions}@anchor{28de}
@subsubsection 有关信号处理句柄和异常的注释


如果一个信号处理句柄引发了异常，该异常将被传播到主线程并可能在任何 @ref{713,,bytecode} 指令之后被引发，在执行期间的任何时候都可能出现 @ref{2d3,,KeyboardInterrupt}。 大多数 Python 代码，包括标准库的代码都不能对此进行健壮性处理，因此 @ref{2d3,,KeyboardInterrupt} (或由信号处理句柄所导致的任何其他异常) 可能会在极少数情况下使程序处于非预期的状态。

为了展示这个问题，请考虑以下代码:

@example
class SpamContext:
    def __init__(self):
        self.lock = threading.Lock()

    def __enter__(self):
        # If KeyboardInterrupt occurs here, everything is fine
        self.lock.acquire()
        # If KeyboardInterrupt occcurs here, __exit__ will not be called
        ...
        # KeyboardInterrupt could occur just before the function returns

    def __exit__(self, exc_type, exc_val, exc_tb):
        ...
        self.lock.release()
@end example

对于许多程序，特别是那些在遇到 @ref{2d3,,KeyboardInterrupt} 只需直接退出的程序来说，这不是个问题，但是高复杂度或要求高可靠性的应用程序则应当避免由于信号处理句柄引发异常。 他们还应当避免将捕获 @ref{2d3,,KeyboardInterrupt} 作为程序关闭的优雅方式。 相反地，他们应当安装自己的 @ref{263c,,SIGINT} 处理句柄。 下面是一个避免了 @ref{2d3,,KeyboardInterrupt} 的 HTTP 服务器示例:

@example
import signal
import socket
from selectors import DefaultSelector, EVENT_READ
from http.server import HTTPServer, SimpleHTTPRequestHandler

interrupt_read, interrupt_write = socket.socketpair()

def handler(signum, frame):
    print('Signal handler called with signal', signum)
    interrupt_write.send(b'\0')
signal.signal(signal.SIGINT, handler)

def serve_forever(httpd):
    sel = DefaultSelector()
    sel.register(interrupt_read, EVENT_READ)
    sel.register(httpd, EVENT_READ)

    while True:
        for key, _ in sel.select():
            if key.fileobj == interrupt_read:
                interrupt_read.recv(1)
                return
            if key.fileobj == httpd:
                httpd.handle_request()

print("Serving on port 8000")
httpd = HTTPServer(('@w{'}, 8000), SimpleHTTPRequestHandler)
serve_forever(httpd)
print("Shutdown...")
@end example

@node mmap --- 内存映射文件支持,,signal --- 设置异步事件处理程序,网络和进程间通信
@anchor{library/mmap doc}@anchor{28df}@anchor{library/mmap mmap-memory-mapped-file-support}@anchor{28e0}@anchor{library/mmap module-mmap}@anchor{b3}
@subsection @code{mmap} --- 内存映射文件支持


@geindex mmap (模块)


__________________________________________________________________


内存映射文件对象的行为既像 @ref{173,,bytearray} 又像 @ref{c1d,,文件对象}。 你可以在大部分接受 @ref{173,,bytearray} 的地方使用 mmap 对象；例如，你可以使用 @ref{dd,,re} 模块来搜索一个内存映射文件。 你也可以通过执行 @code{obj[index] = 97} 来修改单个字节，或者通过对切片赋值来修改一个子序列: @code{obj[i1:i2] = b'...'}。 你还可以在文件的当前位置开始读取和写入数据，并使用 @code{seek()} 前往另一个位置。

内存映射文件是由 @ref{323,,mmap} 构造函数创建的，其在 Unix 和 Windows 上是不同的。 无论哪种情况，你都必须为一个打开的文件提供文件描述符以进行更新。 如果你希望映射一个已有的 Python 文件对象，请使用该对象的 @code{fileno()} 方法来获取 @emph{fileno} 参数的正确值。 否则，你可以使用 @ref{762,,os.open()} 函数来打开这个文件，这会直接返回一个文件描述符（结束时仍然需要关闭该文件）。

@cartouche
@quotation 注解 
如果要为可写的缓冲文件创建内存映射，则应当首先 @ref{2179,,flush()} 该文件。 这确保了对缓冲区的本地修改在内存映射中可用。
@end quotation
@end cartouche

对于 Unix 和 Windows 版本的构造函数，可以将 @emph{access} 指定为可选的关键字参数。 @emph{access} 接受以下四个值之一： @code{ACCESS_READ} ， @code{ACCESS_WRITE} 或 @code{ACCESS_COPY} 分别指定只读，直写或写时复制内存，或 @code{ACCESS_DEFAULT} 推迟到 @emph{prot} 。 @emph{access} 可以在 Unix 和 Windows 上使用。如果未指定 @emph{access} ，则 Windows mmap 返回直写映射。这三种访问类型的初始内存值均取自指定的文件。向 @code{ACCESS_READ} 内存映射赋值会引发 @ref{1ff,,TypeError} 异常。 向 @code{ACCESS_WRITE} 内存映射赋值会影响内存和底层的文件。 向 @code{ACCESS_COPY} 内存映射赋值会影响内存，但不会更新底层的文件。


在 3.7 版更改: 添加了 @code{ACCESS_DEFAULT} 常量。


要映射匿名内存，应将 -1 作为 fileno 和 length 一起传递。

@geindex mmap (mmap 中的类)
@anchor{library/mmap mmap mmap}@anchor{323}
@deffn {类} mmap.mmap (fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])

@strong{（ Windows 版本）} 映射被文件句柄 @emph{fileno} 指定的文件的 @emph{length} 个字节，并创建一个 mmap 对象。如果 @emph{length} 大于当前文件大小，则文件将扩展为包含 @emph{length} 个字节。如果 @emph{length} 为 @code{0}，则映射的最大长度为当前文件大小。如果文件为空， Windows 会引发异常（你无法在Windows上创建空映射）。

如果 @emph{tagname} 被指定且不是 @code{None} ，则是为映射提供标签名称的字符串。 Windows 允许你对同一文件拥有许多不同的映射。如果指定现有标签的名称，则会打开该标签，否则将创建该名称的新标签。如果省略此参数或设置为 @code{None} ，则创建的映射不带名称。避免使用 tag 参数将有助于使代码在Unix和Windows之间可移植。

@emph{offset} 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的偏移。 @emph{offset} 默认为0。 @emph{offeset} 必须是 @code{ALLOCATIONGRANULARITY} 的倍数。

引发一个 @ref{fec,,审计事件} @code{mmap.__new__} 附带参数 @code{fileno}, @code{length}, @code{access}, @code{offset}。
@end deffn


@deffn {类} mmap.mmap (fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])

@strong{(Unix 版本)} 映射文件描述符 @emph{fileno} 指定的文件的 @emph{length} 个字节，并返回一个 mmap 对象。如果 @emph{length} 为 @code{0} ，则当调用 @ref{323,,mmap} 时，映射的最大长度将为文件的当前大小。

@emph{flags} 指明映射的性质。 @code{MAP_PRIVATE} 会创建私有的写入时拷贝映射，因此对 mmap 对象内容的修改将为该进程所私有，而 @code{MAP_SHARED} 会创建与其他映射同一文件区域的进程所共享的映射。 默认值为 @code{MAP_SHARED}。

如果指明了 @emph{prot}，它将给出所需的内存保护方式；最有用的两个值是 @code{PROT_READ} 和 @code{PROT_WRITE}，分别指明页面为可读或可写。 @emph{prot} 默认为 @code{PROT_READ | PROT_WRITE}。

可以指定 @emph{access} 作为替代 @emph{flags} 和 @emph{prot} 的可选关键字形参。 同时指定 @emph{flags}, @emph{prot} 和 @emph{access} 将导致错误。 请参阅上文中 @emph{access} 的描述了解有关如何使用此形参的信息。

@emph{offset} 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的偏移。 @emph{offset} 默认为 0。 @emph{offset} 必须是 @code{ALLOCATIONGRANULARITY} 的倍数，它在 Unix 系统上等价于 @code{PAGESIZE}。

To ensure validity of the created memory mapping the file specified
by the descriptor @emph{fileno} is internally automatically synchronized
with physical backing store on macOS and OpenVMS.

这个例子演示了使用 @ref{323,,mmap} 的简单方式:

@example
import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write(b"Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print(mm.readline())  # prints b"Hello Python!\n"
    # read content via slice notation
    print(mm[:5])  # prints b"Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = b" world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print(mm.readline())  # prints b"Hello  world!\n"
    # close the map
    mm.close()
@end example

@ref{323,,mmap} 也可以在 @ref{7e4,,with} 语句中被用作上下文管理器:

@example
import mmap

with mmap.mmap(-1, 13) as mm:
    mm.write(b"Hello world!")
@end example


3.2 新版功能: 上下文管理器支持。


下面的例子演示了如何创建一个匿名映射并在父进程和子进程之间交换数据。:

@example
import mmap
import os

mm = mmap.mmap(-1, 13)
mm.write(b"Hello world!")

pid = os.fork()

if pid == 0:  # In a child process
    mm.seek(0)
    print(mm.readline())

    mm.close()
@end example

引发一个 @ref{fec,,审计事件} @code{mmap.__new__} 附带参数 @code{fileno}, @code{length}, @code{access}, @code{offset}。

映射内存的文件对象支持以下方法:

@geindex close() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap close}@anchor{28e1}
@deffn {方法} close ()

关闭 mmap。 后续调用该对象的其他方法将导致引发 ValueError 异常。 此方法将不会关闭打开的文件。
@end deffn

@geindex closed (mmap.mmap 属性)
@anchor{library/mmap mmap mmap closed}@anchor{28e2}
@deffn {属性} closed

如果文件已关闭则返回 @code{True}。


3.2 新版功能.

@end deffn

@geindex find() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap find}@anchor{28e3}
@deffn {方法} find (sub[, start[, end]])

返回子序列 @emph{sub} 在对象内被找到的最小索引号，使得 @emph{sub} 被包含在 [@emph{start}, @emph{end}] 范围中。 可选参数 @emph{start} 和 @emph{end} 会被解读为切片表示法。 如果未找到则返回 @code{-1}。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn

@geindex flush() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap flush}@anchor{3ed}
@deffn {方法} flush ([offset[, size]])

将对文件的内存副本的修改刷新至磁盘。 如果不使用此调用则无法保证在对象被销毁前将修改写回存储。 如果指定了 @emph{offset} 和 @emph{size}，则只将对指定范围内字节的修改刷新至磁盘；在其他情况下，映射的全部范围都会被刷新。 @emph{offset} 必须为 @code{PAGESIZE} 或 @code{ALLOCATIONGRANULARITY} 的倍数。

返回 @code{None} 以表示成功。 当调用失败时将引发异常。


在 3.8 版更改: 在之前版本中，成功时将返回非零值；在 Windows 下当发生错误时将返回零。 在 Unix 下 成功时将返回零值；当发生错误时将引发异常。

@end deffn

@geindex madvise() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap madvise}@anchor{324}
@deffn {方法} madvise (option[, start[, length]])

将有关内存区域的建议 @emph{option} 发送至内核，从 @emph{start} 开始扩展 @emph{length} 个字节。 @emph{option} 必须为系统中可用的 @ref{28e4,,MADV_* 常量} 之一。 如果省略 @emph{start} 和 @emph{length}，则会包含整个映射。 在某些系统中（包括 Linux），@emph{start} 必须为 @code{PAGESIZE} 的倍数。

可用性: 具有 @code{madvise()} 系统调用的系统。


3.8 新版功能.

@end deffn

@geindex move() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap move}@anchor{28e5}
@deffn {方法} move (dest, src, count)

将从偏移量 @emph{src} 开始的 @emph{count} 个字节拷贝到目标索引号 @emph{dest}。 如果 mmap 创建时设置了 @code{ACCESS_READ}，则调用 move 将引发 @ref{1ff,,TypeError} 异常。
@end deffn

@geindex read() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap read}@anchor{b08}
@deffn {方法} read ([n])

返回一个 @ref{172,,bytes}，其中包含从当前文件位置开始的至多 @emph{n} 个字节。 如果参数省略，为 @code{None} 或负数，则返回从当前文件位置开始直至映射结尾的所有字节。 文件位置会被更新为返回字节数据之后的位置。


在 3.3 版更改: 参数可被省略或为 @code{None}。

@end deffn

@geindex read_byte() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap read_byte}@anchor{28e6}
@deffn {方法} read_byte ()

将当前文件位置上的一个字节以整数形式返回，并让文件位置前进 1。
@end deffn

@geindex readline() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap readline}@anchor{28e7}
@deffn {方法} readline ()

返回一个单独的行，从当前文件位置开始直到下一个换行符。 文件位置会被更新为返回字节数据之后的位置。
@end deffn

@geindex resize() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap resize}@anchor{28e8}
@deffn {方法} resize (newsize)

改变映射以及下层文件的大小，如果存在的话。 如果 mmap 创建时设置了 @code{ACCESS_READ} 或 @code{ACCESS_COPY}，则改变映射大小将引发 @ref{1ff,,TypeError} 异常。
@end deffn

@geindex rfind() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap rfind}@anchor{28e9}
@deffn {方法} rfind (sub[, start[, end]])

返回子序列 @emph{sub} 在对象内被找到的最大索引号，使得 @emph{sub} 被包含在 [@emph{start}, @emph{end}] 范围中。 可选参数 @emph{start} 和 @emph{end} 会被解读为切片表示法。 如果未找到则返回 @code{-1}。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn

@geindex seek() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap seek}@anchor{28ea}
@deffn {方法} seek (pos[, whence])

设置文件的当前位置。 @emph{whence} 参数为可选项并且默认为 @code{os.SEEK_SET} 或 @code{0} (绝对文件定位)；其他值还有 @code{os.SEEK_CUR} 或 @code{1} (相对当前位置查找) 和 @code{os.SEEK_END} 或 @code{2} (相对文件末尾查找)。
@end deffn

@geindex size() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap size}@anchor{28eb}
@deffn {方法} size ()

返回文件的长度，该数值可以大于内存映射区域的大小。
@end deffn

@geindex tell() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap tell}@anchor{28ec}
@deffn {方法} tell ()

返回文件指针的当前位置。
@end deffn

@geindex write() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap write}@anchor{28ed}
@deffn {方法} write (bytes)

将 @emph{bytes} 中的字节数据写入文件指针当前位置的内存并返回写入的字节总数 (一定不小于 @code{len(bytes)}，因为如果写入失败，将会引发 @ref{16d,,ValueError})。 在字节数据被写入后文件位置将会更新。 如果 mmap 创建时设置了 @code{ACCESS_READ}，则向其写入将引发 @ref{1ff,,TypeError} 异常。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。



在 3.6 版更改: 现在会返回写入的字节总数。

@end deffn

@geindex write_byte() (mmap.mmap 方法)
@anchor{library/mmap mmap mmap write_byte}@anchor{28ee}
@deffn {方法} write_byte (byte)

将整数值 @emph{byte} 写入文件指针当前位置的内存；文件位置前进 @code{1}。 如果 mmap 创建时设置了 @code{ACCESS_READ}，则向其写入将引发 @ref{1ff,,TypeError} 异常。
@end deffn
@end deffn

@menu
* MADV_* 常量:: 

@end menu

@node MADV_* 常量,,,mmap --- 内存映射文件支持
@anchor{library/mmap madv-constants}@anchor{28ef}@anchor{library/mmap madvise-constants}@anchor{28e4}
@subsubsection MADV_* 常量


@geindex MADV_NORMAL() (在 mmap 模块中)
@geindex MADV_RANDOM() (在 mmap 模块中)
@geindex MADV_SEQUENTIAL() (在 mmap 模块中)
@geindex MADV_WILLNEED() (在 mmap 模块中)
@geindex MADV_DONTNEED() (在 mmap 模块中)
@geindex MADV_REMOVE() (在 mmap 模块中)
@geindex MADV_DONTFORK() (在 mmap 模块中)
@geindex MADV_DOFORK() (在 mmap 模块中)
@geindex MADV_HWPOISON() (在 mmap 模块中)
@geindex MADV_MERGEABLE() (在 mmap 模块中)
@geindex MADV_UNMERGEABLE() (在 mmap 模块中)
@geindex MADV_SOFT_OFFLINE() (在 mmap 模块中)
@geindex MADV_HUGEPAGE() (在 mmap 模块中)
@geindex MADV_NOHUGEPAGE() (在 mmap 模块中)
@geindex MADV_DONTDUMP() (在 mmap 模块中)
@geindex MADV_DODUMP() (在 mmap 模块中)
@geindex MADV_FREE() (在 mmap 模块中)
@geindex MADV_NOSYNC() (在 mmap 模块中)
@geindex MADV_AUTOSYNC() (在 mmap 模块中)
@geindex MADV_NOCORE() (在 mmap 模块中)
@geindex MADV_CORE() (在 mmap 模块中)
@geindex MADV_PROTECT() (在 mmap 模块中)
@anchor{library/mmap mmap MADV_NORMAL}@anchor{28f0}
@deffn {数据} mmap.MADV_NORMAL
@anchor{library/mmap mmap MADV_RANDOM}@anchor{28f1}
@deffnx {数据} mmap.MADV_RANDOM
@anchor{library/mmap mmap MADV_SEQUENTIAL}@anchor{28f2}
@deffnx {数据} mmap.MADV_SEQUENTIAL
@anchor{library/mmap mmap MADV_WILLNEED}@anchor{28f3}
@deffnx {数据} mmap.MADV_WILLNEED
@anchor{library/mmap mmap MADV_DONTNEED}@anchor{28f4}
@deffnx {数据} mmap.MADV_DONTNEED
@anchor{library/mmap mmap MADV_REMOVE}@anchor{28f5}
@deffnx {数据} mmap.MADV_REMOVE
@anchor{library/mmap mmap MADV_DONTFORK}@anchor{28f6}
@deffnx {数据} mmap.MADV_DONTFORK
@anchor{library/mmap mmap MADV_DOFORK}@anchor{28f7}
@deffnx {数据} mmap.MADV_DOFORK
@anchor{library/mmap mmap MADV_HWPOISON}@anchor{28f8}
@deffnx {数据} mmap.MADV_HWPOISON
@anchor{library/mmap mmap MADV_MERGEABLE}@anchor{28f9}
@deffnx {数据} mmap.MADV_MERGEABLE
@anchor{library/mmap mmap MADV_UNMERGEABLE}@anchor{28fa}
@deffnx {数据} mmap.MADV_UNMERGEABLE
@anchor{library/mmap mmap MADV_SOFT_OFFLINE}@anchor{28fb}
@deffnx {数据} mmap.MADV_SOFT_OFFLINE
@anchor{library/mmap mmap MADV_HUGEPAGE}@anchor{28fc}
@deffnx {数据} mmap.MADV_HUGEPAGE
@anchor{library/mmap mmap MADV_NOHUGEPAGE}@anchor{28fd}
@deffnx {数据} mmap.MADV_NOHUGEPAGE
@anchor{library/mmap mmap MADV_DONTDUMP}@anchor{28fe}
@deffnx {数据} mmap.MADV_DONTDUMP
@anchor{library/mmap mmap MADV_DODUMP}@anchor{28ff}
@deffnx {数据} mmap.MADV_DODUMP
@anchor{library/mmap mmap MADV_FREE}@anchor{2900}
@deffnx {数据} mmap.MADV_FREE
@anchor{library/mmap mmap MADV_NOSYNC}@anchor{2901}
@deffnx {数据} mmap.MADV_NOSYNC
@anchor{library/mmap mmap MADV_AUTOSYNC}@anchor{2902}
@deffnx {数据} mmap.MADV_AUTOSYNC
@anchor{library/mmap mmap MADV_NOCORE}@anchor{2903}
@deffnx {数据} mmap.MADV_NOCORE
@anchor{library/mmap mmap MADV_CORE}@anchor{2904}
@deffnx {数据} mmap.MADV_CORE
@anchor{library/mmap mmap MADV_PROTECT}@anchor{2905}
@deffnx {数据} mmap.MADV_PROTECT

这些选项可被传给 @ref{324,,mmap.madvise()}。 不是每个选项都存在于每个系统中。

可用性: 具有 madvise() 系统调用的系统。


3.8 新版功能.

@end deffn

@node 互联网数据处理,结构化标记处理工具,网络和进程间通信,Python 标准库
@anchor{library/netdata doc}@anchor{2906}@anchor{library/netdata internet-data-handling}@anchor{2907}@anchor{library/netdata netdata}@anchor{2908}
@section 互联网数据处理


本章介绍了支持处理互联网上常用数据格式的模块。

@menu
* email: email --- 电子邮件与 MIME 处理包. 电子邮件与 MIME 处理包
* json: json --- JSON 编码和解码器. JSON 编码和解码器
* mailbox: mailbox --- 操作多种格式的邮箱. 操作多种格式的邮箱
* mimetypes: mimetypes --- 映射文件名到 MIME 类型. 映射文件名到 MIME 类型
* base64: base64 --- Base16 Base32 Base64 Base85 数据编码. Base16, Base32, Base64, Base85 数据编码
* binhex: binhex --- 对binhex4文件进行编码和解码. 对binhex4文件进行编码和解码
* binascii: binascii --- 二进制和 ASCII 码互转. 二进制和 ASCII 码互转
* quopri: quopri --- 编码与解码经过 MIME 转码的可打印数据. 编码与解码经过 MIME 转码的可打印数据

@end menu

@node email --- 电子邮件与 MIME 处理包,json --- JSON 编码和解码器,,互联网数据处理
@anchor{library/email doc}@anchor{2909}@anchor{library/email email-an-email-and-mime-handling-package}@anchor{290a}@anchor{library/email module-email}@anchor{67}
@subsection @code{email} --- 电子邮件与 MIME 处理包


@geindex email (模块)

@strong{源代码:} Lib/email/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/__init__.py}


__________________________________________________________________


@ref{67,,email} 包是一个用于管理电子邮件消息的库。 它 @emph{并非} 被设计为执行向 SMTP (
@geindex RFC; RFC 2821
RFC 2821@footnote{https://tools.ietf.org/html/rfc2821.html}), NNTP 或其他服务器发送电子邮件消息的操作；这些是 @ref{ed,,smtplib} 和 @ref{c0,,nntplib} 等模块的功能。 @ref{67,,email} 包试图尽可能地遵循 RFC，支持 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 和 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://tools.ietf.org/html/rfc6532.html}，以及与 MIME 相关的各个 RFC 例如 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html}, 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://tools.ietf.org/html/rfc2046.html}, 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html}, 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://tools.ietf.org/html/rfc2183.html} 和 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html}。

email 包的总体结构可以分为三个主要组件，另外还有第四个组件用于控制其他组件的行为。

这个包的中心组件是代表电子邮件消息的“对象模型”。 应用程序主要通过在 @ref{70,,message} 子模块中定义的对象模型接口与这个包进行交互。 应用程序可以使用此 API 来询问有关现有电子邮件的问题、构造新的电子邮件，或者添加或移除自身也使用相同对象模型接口的电子邮件子组件。 也就是说，遵循电子邮件消息及其 MIME 子组件的性质，电子邮件对象模型是所有提供 @ref{645,,EmailMessage} API 的对象所构成的树状结构。

这个包的另外两个主要组件是 @ref{72,,parser} 和 @ref{6c,,generator}。 parser 接受电子邮件消息的序列化版本（字节流）并将其转换为 @ref{645,,EmailMessage} 对象树。 generator 接受  @ref{645,,EmailMessage} 并将其转回序列化的字节流。 (parser 和 generator 还能处理文本字符流，但不建议这种用法，因为这很容易导致某种形式的无效消息。

控制组件是 @ref{73,,policy} 模块。 每一个 @ref{645,,EmailMessage}、每一个 @ref{6c,,generator} 和每一个 @ref{72,,parser} 都有一个相关联的 @ref{73,,policy} 对象来控制其行为。 通常应用程序只有在 @ref{645,,EmailMessage} 被创建时才需要指明控制策略，或者通过直接实例代 @ref{645,,EmailMessage}  来新建电子邮件，或者通过使用 @ref{72,,parser} 来解析输入流。 但是策略也可以在使用 @ref{6c,,generator} 序列化消息时被更改。 例如，这允许从磁盘解析通用电子邮件消息，而在将消息发送到电子邮件服务器时使用标准 SMTP 设置对其进行序列化。

email 包会尽量地对应用程序隐藏各种控制类 RFC 的细节。 从概念上讲应用程序应当能够将电子邮件消息视为 Unicode 文本和二进制附件的结构化树，而不必担心在序列化时要如何表示它们。 但在实际中，经常有必要至少了解一部分控制类 MIME 消息及其结构的规划，特别是 MIME "内容类型" 的名称和性质以及它们是如何标识多部分文档的。 在大多数情况下这些知识应当仅对于更复杂的应用程序来说才是必需的，并且即便在那时它也应当仅是特定的高层级结构，而不是如何表示这些结构的细节信息。 由于 MIME 内容类型被广泛应用于现代因特网软件（而非只是电子邮件），因此这对许多程序员来说将是很熟悉的概念。

以下小节描述了 @ref{67,,email} 包的具体功能。 我们会从 @ref{70,,message} 对象模型开始，它是应用程序将要使用的主要接口，之后是 @ref{72,,parser} 和 @ref{6c,,generator} 组件。 然后我们会介绍 @ref{73,,policy} 控制组件，它将完成对这个库的主要组件的处理。

接下来的三个小节会介绍这个包可能引发的异常以及 @ref{72,,parser} 可能检测到的缺陷（即与 RFC 不相符）。 然后我们会介绍 @ref{6e,,headerregistry} 和 @ref{69,,contentmanager} 子组件，它们分别提供了用于更精细地操纵标题和载荷的工具。 这两个组件除了包含使用与生成非简单消息的相关特性，还记录了它们的可扩展性 API，这将是高级应用程序所感兴趣的内容。

在此之后是一组使用之前小节所介绍的 API 的基本部分的示例。

前面的内容是 email 包的现代（对 Unicode 支持良好）API。 从 @ref{644,,Message} 类开始的其余小节则介绍了旧式  @ref{643,,compat32} API，它会更直接地处理如何表示电子邮件消息的细节。 @ref{643,,compat32} API @emph{不会} 向应用程序隐藏 RFC 的相关细节，但对于需要进行此种层级操作的应用程序来说将是很有用的工具。 此文档对于因向下兼容理由而仍然使用 @ref{643,,compat32} API 的应用程序也是很适合的。


在 3.6 版更改: 文档经过重新组织和撰写以鼓励使用新的 @ref{645,,EmailMessage}/@ref{ae0,,EmailPolicy} API。


@ref{67,,email} 包文档的内容:

@menu
* email.message; 表示一封电子邮件信息: email message 表示一封电子邮件信息. 
* email.parser; 解析电子邮件信息: email parser 解析电子邮件信息. 
* email.generator; 生成 MIME 文档: email generator 生成 MIME 文档. 
* email.policy; Policy 对象: email policy Policy 对象. 
* email.errors; 异常和缺陷类: email errors 异常和缺陷类. 
* email.headerregistry; 自定义标头对象: email headerregistry 自定义标头对象. 
* email.contentmanager; 管理 MIME 内容: email contentmanager 管理 MIME 内容. 
* email; 示例: email 示例. 
* email.message.Message; 使用 compat32 API 来表示电子邮件消息: email message Message 使用 compat32 API 来表示电子邮件消息. 
* email.mime; 从头创建电子邮件和 MIME 对象: email mime 从头创建电子邮件和 MIME 对象. 
* email.header; 国际化标头: email header 国际化标头. 
* email.charset; 表示字符集: email charset 表示字符集. 
* email.encoders; 编码器: email encoders 编码器. 
* email.utils; 其他工具: email utils 其他工具. 
* email.iterators; 迭代器: email iterators 迭代器. 

@end menu

@node email message 表示一封电子邮件信息,email parser 解析电子邮件信息,,email --- 电子邮件与 MIME 处理包
@anchor{library/email message doc}@anchor{290b}@anchor{library/email message email-message-representing-an-email-message}@anchor{290c}@anchor{library/email message module-email message}@anchor{70}
@subsubsection @code{email.message}: 表示一封电子邮件信息


@geindex email.message (模块)

@strong{源代码:} Lib/email/message.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/message.py}


__________________________________________________________________



3.6 新版功能: @footnote{@w{(1)} 
原先在3.4版本中以 @ref{a6a,,provisional module} 添加。过时的文档被移动至 @ref{290d,,email.message.Message; 使用 compat32 API 来表示电子邮件消息} 。
}


位于 @ref{67,,email} 包的中心的类就是 @ref{645,,EmailMessage} 类。这个类导入自 @ref{70,,email.message} 模块。它是 @ref{67,,email} 对象模型的基类。@ref{645,,EmailMessage} 为设置和查询头字段内容、访问信息体的内容、以及创建和修改结构化信息提供了核心功能。

一份电子邮件信息由 @emph{标头} 和 @emph{载荷} （又被称为 @emph{内容} ）组成。 标头遵循 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 或者 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://tools.ietf.org/html/rfc6532.html} 风格的字段名和值，字段名和字段值之间由一个冒号隔开。 这个冒号既不属于字段名，也不属于字段值。信息的载荷可能是一段简单的文字消息，也可能是一个二进制的对象，更可能是由多个拥有各自标头和载荷的子信息组成的结构化子信息序列。 对于后者类型的载荷，信息的 MIME 类型将会被指明为诸如 @code{multipart/*} 或 @code{message/rfc822} 的类型。

@ref{645,,EmailMessage} 对象所提供的抽象概念模型是一个头字段组成的有序字典加一个代表 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 标准的信息体的 @emph{载荷} 。 载荷有可能是一系列子 @code{EmailMessage} 对象的列表。你除了可以通过一般的字典方法来访问头字段名和值，还可以使用特制方法来访问头的特定字段（比如说 MIME 内容类型字段）、操纵载荷、生成信息的序列化版本、递归遍历对象树。

@ref{645,,EmailMessage} 的类字典接口的字典索引是头字段名，头字段名必须是ASCII值。字典值是带有一些附加方法的字符串。虽然头字段的存储和获取都是保留其原始大小写的，但是字段名的匹配是大小写不敏感的。与真正的字典不同，键与键之间不但存在顺序关系，还可以重复。我们提供了额外的方法来处理含有重复键的头。

@emph{载荷} 是多样的。对于简单的信息对象，它是字符串或字节对象；对于诸如 @code{multipart/*} 和 @code{message/rfc822} 信息对象的 MIME 容器文档，它是一个 @ref{645,,EmailMessage} 对象列表。

@geindex EmailMessage (email.message 中的类)
@anchor{library/email message email message EmailMessage}@anchor{645}
@deffn {类} email.message.EmailMessage (policy=default)

如果指定了 @emph{policy} ，消息将由这个 @emph{policy} 所指定的规则来更新和序列化信息的表达。如果没有指定 @emph{policy} ，其将默认使用 @ref{290e,,default} 策略。这个策略遵循电子邮件的RFC标准，除了行终止符号（RFC要求使用 @code{\r\n} ，此策略使用Python标准的 @code{\n} 行终止符）。请前往 @ref{73,,policy} 的文档获取更多信息。

@geindex as_string() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage as_string}@anchor{290f}
@deffn {方法} as_string (unixfrom=False, maxheaderlen=None, policy=None)

以一段扁平的字符串的形式返回整个信息对象。若可选的 @emph{unixform} 参数为真，返回的字符串会包含信封头。 @emph{unixform} 的默认值是 @code{False} 。为了保持与基类 @ref{644,,Message} 的兼容性， @emph{maxheaderlen} 是被接受的，但是其默认值是 @code{None} 。这个默认值表示行长度由策略的 @code{max_line_length} 属性所控制。从信息实例所获取到的策略可以通过 @emph{policy} 参数重写。这样可以对该方法所产生的输出进行略微的控制，因为指定的 @emph{policy} 会被传递到 @ref{c27,,Generator} 当中。

扁平化信息可能会对 @ref{645,,EmailMessage} 做出修改。这是因为为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，MIME 边界字段可能会被生成或被修改）。

请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需要使用更加灵活的API来序列化信息，请参见 @ref{c27,,email.generator.Generator} 。同时请注意，当 @ref{7cf,,utf8} 属性为其默认值 @code{False} 的时候，本方法将限制其行为为生成以“7 bit clean”方式序列化的信息。


在 3.6 版更改: @emph{maxheaderlen} 没有被指定时的默认行为从默认为0修改为默认为策略的 @emph{max_line_length} 值。

@end deffn

@geindex __str__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __str__}@anchor{2910}
@deffn {方法} __str__ ()

与 @code{as_string(policy=self.policy.clone(utf8=True))} 等价。这将让 @code{str(msg)} 产生的字符串包含人类可读的的序列化信息内容。


在 3.4 版更改: 本方法开始使用 @code{utf8=True} ，而非 @ref{290f,,as_string()} 的直接替身。使用 @code{utf8=True} 会产生类似于 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html} 的信息表达。

@end deffn

@geindex as_bytes() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage as_bytes}@anchor{2911}
@deffn {方法} as_bytes (unixfrom=False, policy=None)

以字节串对象的形式返回整个扁平化后的消息。 当可选的 @emph{unixfrom} 为真值时，返回的字符串会包含信封标头。 @emph{unixfrom} 的默认值为 @code{False}。 @emph{policy} 参数可被用于重载从消息实例获取的默认 policy。 这可被用来控制该方法所产生的部分格式效果，因为指定的 @emph{policy} 将被传递给 @ref{c28,,BytesGenerator}。

扁平化信息可能会对 @ref{645,,EmailMessage} 做出修改。这是因为为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，MIME 边界字段可能会被生成或被修改）。

请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需要使用更加灵活的API来序列化信息，请参见 @ref{c28,,email.generator.BytesGenerator} 。
@end deffn

@geindex __bytes__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __bytes__}@anchor{2912}
@deffn {方法} __bytes__ ()

与 @ref{2911,,as_bytes()} 等价。这将让 @code{bytes(msg)} 产生一个包含序列化信息内容的字节序列对象。
@end deffn

@geindex is_multipart() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage is_multipart}@anchor{2913}
@deffn {方法} is_multipart ()

如果该信息的载荷是一个子 @ref{645,,EmailMessage} 对象列表，返回 @code{True} ；否则返回 @code{False} 。在 @ref{2913,,is_multipart()} 返回 @code{True} 的场合下，载荷应当是一个字符串对象（有可能是一个使用了内容传输编码进行编码的二进制载荷）。请注意， @ref{2913,,is_multipart()} 返回 @code{True} 不意味着 @code{msg.get_content_maintype() == 'multipart'} 也会返回 @code{True} 。举个例子， @code{is_multipart} 在 @ref{645,,EmailMessage} 是 @code{message/rfc822} 类型的信息的情况下，其返回值也是 @code{True} 。
@end deffn

@geindex set_unixfrom() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage set_unixfrom}@anchor{2914}
@deffn {方法} set_unixfrom (unixfrom)

将信息的信封头设置为 @emph{unixform} ，这应当是一个字符串。（在  @ref{2915,,mboxMessage} 中有关于这个头的一段简短介绍。）
@end deffn

@geindex get_unixfrom() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_unixfrom}@anchor{2916}
@deffn {方法} get_unixfrom ()

返回消息的信封头。如果信封头从未被设置过，默认返回 @code{None} 。
@end deffn

以下方法实现了对信息的头字段进行访问的类映射接口。请留意，只是类映射接口，这与平常的映射接口（比如说字典映射）有一些语义上的不同。举个例子，在一个字典当中，键之间不可重复，但是信息头字段是可以重复的。不光如此，在字典当中调用 @ref{2917,,keys()} 方法返回的结果，其顺序没有保证；但是在一个 @ref{645,,EmailMessage} 对象当中，返回的头字段永远以其在原信息当中出现的顺序，或以其加入信息的顺序为序。任何删了后又重新加回去的头字段总是添加在当时列表的末尾。

这些语义上的不同是刻意而为之的，是出于在绝大多数常见使用情景中都方便的初衷下设计的。

还请留意，无论在什么情况下，消息当中的任何信封头字段都不会包含在映射接口当中。

@geindex __len__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __len__}@anchor{2918}
@deffn {方法} __len__ ()

返回头字段的总数，重复的也计算在内。
@end deffn

@geindex __contains__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __contains__}@anchor{2919}
@deffn {方法} __contains__ (name)

如果消息对象中有一个名为 @emph{name} 的字段，其返回值为 @code{True} 。匹配无视大小写差异， @emph{name} 也不包含末尾的的冒号。  @code{in} 操作符的实现中用到了这个方法，比如说：

@example
if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])
@end example
@end deffn

@geindex __getitem__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __getitem__}@anchor{291a}
@deffn {方法} __getitem__ (name)

返回头字段名对应的字段值。 @emph{name} 不含冒号分隔符。如果字段未找到，返回 @code{None} 。 @ref{3f1,,KeyError} 异常永不抛出。

请注意，如果对应名字的字段找到了多个，具体返回哪个字段值是未定义的。请使用 @ref{291b,,get_all()} 方法获取当前匹配字段名的所有字段值。

使用标准策略（非 @code{compat32}）时，返回值是 @ref{291c,,email.headerregistry.BaseHeader} 的某个子类的一个实例。
@end deffn

@geindex __setitem__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __setitem__}@anchor{291d}
@deffn {方法} __setitem__ (name, val)

在信息头中添加名为 @emph{name} 值为 @emph{val} 的字段。这个字段会被添加在已有字段列表的结尾处。

请注意，这个方法 @emph{既不会} 覆盖 @emph{也不会} 删除任何字段名重名的已有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 @emph{name} 字段名的字段，你需要先把旧字段删除。例如：

@example
del msg['subject']
msg['subject'] = 'Python roolz!'
@end example

如果 @code{policy} 明确要求某些字段是唯一的（至少标准策略就有这么做），对这些字段在已有同名字段的情况下仍然调用此方法尝试为字段名赋值会引发 @ref{16d,,ValueError} 异常。这是为了一致性而刻意设计出的行为，不过我们随时可能会突然觉得“还是在这种情况下自动把旧字段删除比较好吧”而把这个行为改掉，所以不要以为这是特性而依赖这个行为。
@end deffn

@geindex __delitem__() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage __delitem__}@anchor{291e}
@deffn {方法} __delitem__ (name)

删除信息头当中字段名匹配 @emph{name} 的所有字段。如果匹配指定名称的字段没有找到，也不会抛出任何异常。
@end deffn

@geindex keys() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage keys}@anchor{2917}
@deffn {方法} keys ()

以列表形式返回消息头中所有的字段名。
@end deffn

@geindex values() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage values}@anchor{291f}
@deffn {方法} values ()

以列表形式返回消息头中所有的字段值。
@end deffn

@geindex items() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage items}@anchor{2920}
@deffn {方法} items ()

以二元元组的列表形式返回消息头中所有的字段名和字段值。
@end deffn

@geindex get() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get}@anchor{2921}
@deffn {方法} get (name, failobj=None)

返回对应字段名的字段值。这个方法与 @ref{291a,,__getitem__()} 是一样的，只不过如果对应字段名的字段没有找到，该方法会返回 @emph{failobj} 。这个参数是可选的（默认值为 @code{None} ）。
@end deffn

以下是一些与头有关的更多有用方法：

@geindex get_all() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_all}@anchor{291b}
@deffn {方法} get_all (name, failobj=None)

返回字段名为 @emph{name} 的所有字段值的列表。如果信息内不存在匹配的字段，返回 @emph{failobj} （其默认值为 @code{None} ）。
@end deffn

@geindex add_header() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage add_header}@anchor{2922}
@deffn {方法} add_header (_name, _value, **_params)

高级头字段设定。这个方法与 @ref{291d,,__setitem__()} 类似，不过你可以使用关键字参数为字段提供附加参数。 @emph{_name} 是字段名， @emph{_value} 是字段 @emph{主} 值。

对于关键字参数字典 @emph{_params} 的每个键值对而言，它的键被用作参数的名字，其中下划线被替换为短横杠（毕竟短横杠不是合法的Python标识符）。一般来讲，参数以 @code{键="值"} 的方式添加，除非值是 @code{None} 。要真的是这样的话，只有键会被添加。

如果值含有非ASCII字符，你可以将值写成 @code{(CHARSET, LANGUAGE, VALUE)} 形式的三元组，这样你可以人为控制字符的字符集和语言。 @code{CHARSET} 是一个字符串，它为你的值的编码命名； @code{LANGUAGE} 一般可以直接设为 @code{None} ，也可以直接设为空字符串（其他可能取值参见 :rfc`2231` ）； @code{VALUE} 是一个字符串值，其包含非ASCII的码点。如果你没有使用三元组，你的字符串又含有非ASCII字符，那么它就会使用 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 中， @code{CHARSET} 为 @code{utf-8} ， @code{LANGUAGE} 为 @code{None} 的格式编码。

例如：

@example
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
@end example

会添加一个形如下文的头字段：

@example
Content-Disposition: attachment; filename="bud.gif"
@end example

带有非ASCII字符的拓展接口：

@example
msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '@w{'}, 'Fußballer.ppt'))
@end example
@end deffn

@geindex replace_header() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage replace_header}@anchor{2923}
@deffn {方法} replace_header (_name, _value)

替换头字段。只会替换掉信息内找到的第一个字段名匹配 @emph{_name} 的字段值。字段的顺序不变，原字段名的大小写也不变。如果没有找到匹配的字段，抛出 @ref{3f1,,KeyError} 异常。
@end deffn

@geindex get_content_type() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content_type}@anchor{2924}
@deffn {方法} get_content_type ()

返回信息的内容类型，其形如 @code{maintype/subtype} ，强制全小写。如果信息的 @code{Content-Type} 头字段不存在则返回 @ref{2925,,get_default_type()} 的返回值；如果信息的 @code{Content-Type} 头字段无效则返回 @code{text/plain} 。

（根据 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 所述，信息永远都有一个默认类型，所以 @ref{2924,,get_content_type()} 一定会返回一个值。 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 定义信息的默认类型为 @code{text/plain} 或 @code{message/rfc822} ，其中后者仅出现在消息头位于一个 @code{multipart/digest} 容器中的场合中。如果消息头的 @code{Content-Type} 字段所指定的类型是无效的， 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 令其默认类型为 @code{text/plain} 。）
@end deffn

@geindex get_content_maintype() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content_maintype}@anchor{2926}
@deffn {方法} get_content_maintype ()

返回信息的主要内容类型。准确来说，此方法返回的是 @ref{2924,,get_content_type()} 方法所返回的形如 @code{maintype/subtype} 的字符串当中的 @code{maintype} 部分。
@end deffn

@geindex get_content_subtype() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content_subtype}@anchor{2927}
@deffn {方法} get_content_subtype ()

返回信息的子内容类型。准确来说，此方法返回的是 @ref{2924,,get_content_type()} 方法所返回的形如 @code{maintype/subtype} 的字符串当中的 @code{subtype} 部分。
@end deffn

@geindex get_default_type() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_default_type}@anchor{2925}
@deffn {方法} get_default_type ()

返回默认的内容类型。绝大多数的信息，其默认内容类型都是 @code{text/plain} 。作为 @code{multipart/digest} 容器内子部分的信息除外，它们的默认内容类型是 @code{message/rfc822} 。
@end deffn

@geindex set_default_type() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage set_default_type}@anchor{2928}
@deffn {方法} set_default_type (ctype)

设置默认的内容类型。 尽管并非强制，但是 @emph{ctype} 仍应当是 @code{text/plain} 或 @code{message/rfc822} 二者取一。默认内容类型并不存储在 @code{Content-Type} 头字段当中，所以设置此项的唯一作用就是决定当 @code{Content-Type} 头字段在信息中不存在时，@code{get_content_type} 方法的返回值。
@end deffn

@geindex set_param() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage set_param}@anchor{2929}
@deffn {方法} set_param (param, value, header='Content-Type', requote=True, charset=None, language='@w{'}, replace=False)

在 @code{Content-Type} 头字段当中设置一个参数。如果该参数已于字段中存在，将其旧值替换为 @emph{value} 。如果 @emph{header} 是 @code{Content-Type} （默认值），并且该头字段于信息中尚未存在，则会先添加该字段，将其值设置为 @code{text/plain} ，并附加参数值。可选的 @emph{header} 可以让你指定 @code{Content-Type} 之外的另一个头字段。

如果值包含非ASCII字符，其字符集和语言可以通过可选参数 @emph{charset} 和 @emph{language} 显式指定。可选参数 @emph{language} 指定 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 当中的语言，其默认值是空字符串。 @emph{charset} 和 @emph{language} 都应当字符串。默认使用的是 @code{utf8} @emph{charset} ，@emph{language} 为 @code{None} 。

如果 @emph{replace} 为 @code{False} （默认值），该头字段会被移动到所有头字段列表的末尾。如果 @emph{replace} 为 @code{True} ，字段会被原地更新。

于 @ref{645,,EmailMessage} 对象而言， @emph{requote} 参数已被弃用。

请注意，头字段已有的参数值可以通过头字段的 @code{params} 属性来访问（举例： @code{msg['Content-Type'].params['charset']} ）。


在 3.4 版更改: 添加了 @code{replace} 关键字。

@end deffn

@geindex del_param() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage del_param}@anchor{292a}
@deffn {方法} del_param (param, header='content-type', requote=True)

从 @code{Content-Type} 头字段中完全移去给定的参数。头字段会被原地重写，重写后的字段不含参数和值。可选的 @emph{header} 可以让你指定 @code{Content-Type} 之外的另一个字段。

于 @ref{645,,EmailMessage} 对象而言， @emph{requote} 参数已被弃用。
@end deffn

@geindex get_filename() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_filename}@anchor{292b}
@deffn {方法} get_filename (failobj=None)

返回信息头当中 @code{Content-Disposition} 字段当中名为 @code{filename} 的参数值。如果该字段当中没有此参数，该方法会退而寻找 @code{Content-Type} 字段当中的 @code{name} 参数值。如果这个也没有找到，或者这些个字段压根就不存在，返回 @emph{failobj} 。返回的字符串永远按照 @ref{292c,,email.utils.unquote()} 方法去除引号。
@end deffn

@geindex get_boundary() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_boundary}@anchor{292d}
@deffn {方法} get_boundary (failobj=None)

返回信息头当中 @code{Content-Type} 字段当中名为 @code{boundary} 的参数值。如果字段当中没有此参数，或者这些个字段压根就不存在，返回 @emph{failobj} 。返回的字符串永远按照 @ref{292c,,email.utils.unquote()} 方法去除引号。
@end deffn

@geindex set_boundary() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage set_boundary}@anchor{292e}
@deffn {方法} set_boundary (boundary)

将 @code{Content-Type} 头字段的 @code{boundary} 参数设置为 @emph{boundary} 。 @ref{292e,,set_boundary()} 方法永远都会在必要的时候为 @emph{boundary} 添加引号。如果信息对象中没有 @code{Content-Type} 头字段，抛出 @ref{292f,,HeaderParseError} 异常。

请注意使用这个方法与直接删除旧的 @code{Content-Type} 头字段然后使用 @ref{2922,,add_header()} 方法添加一个带有新边界值参数的 @code{Content-Type} 头字段有细微差距。 @ref{292e,,set_boundary()} 方法会保留 @code{Content-Type} 头字段在原信息头当中的位置。
@end deffn

@geindex get_content_charset() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content_charset}@anchor{2930}
@deffn {方法} get_content_charset (failobj=None)

返回 @code{Content-Type} 头字段中的 @code{charset} 参数，强制小写。如果字段当中没有此参数，或者这个字段压根不存在，返回 @emph{failobj} 。
@end deffn

@geindex get_charsets() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_charsets}@anchor{2931}
@deffn {方法} get_charsets (failobj=None)

返回一个包含了信息内所有字符集名字的列表。 如果信息是 @code{multipart} 类型的，那么列表当中的每一项都对应其载荷的子部分的字符集名字。 否则，该列表是一个长度为 1 的列表。

列表当中的每一项都是一个字符串，其值为对应子部分的 @code{Content-Type} 头字段的 @code{charset} 参数值。如果该子部分没有此头字段，或者没有此参数，或者其主要 MIME 类型并非 @code{text} ，那么列表中的那一项即为 @emph{failobj} 。
@end deffn

@geindex is_attachment() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage is_attachment}@anchor{2932}
@deffn {方法} is_attachment ()

如果信息头当中存在一个名为 @code{Content-Disposition} 的字段，且该字段的值为 @code{attachment} （大小写无关），返回 @code{True} 。否则，返回 @code{False} 。


在 3.4.2 版更改: 为了与 @ref{2933,,is_multipart()} 方法一致，is_attachment 现在是一个方法，不再是属性了。

@end deffn

@geindex get_content_disposition() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content_disposition}@anchor{2934}
@deffn {方法} get_content_disposition ()

如果信息的 @code{Content-Disposition} 头字段存在，返回其字段值；否则返回 @code{None} 。返回的值均为小写，不包含参数。如果信息遵循 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://tools.ietf.org/html/rfc2183.html} 标准，则此方法的返回值只可能在 @emph{inline} 、 @emph{attachment} 和 @code{None} 之间选择。


3.5 新版功能.

@end deffn

下列方法与信息内容（载荷）之访问与操控有关。

@geindex walk() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage walk}@anchor{2935}
@deffn {方法} walk ()

@ref{2935,,walk()} 方法是一个多功能生成器。它可以被用来以深度优先顺序遍历信息对象树的所有部分和子部分。一般而言， @ref{2935,,walk()} 会被用作 @code{for} 循环的迭代器，每一次迭代都返回其下一个子部分。

以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型。

@c from email import message_from_binary_file
@c with open('../Lib/test/test_email/data/msg_16.txt', 'rb') as f:
@c     msg = message_from_binary_file(f)

@example
>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
@end example

@code{walk} 会遍历所有 @ref{2913,,is_multipart()} 方法返回 @code{True} 的部分之子部分，哪怕 @code{msg.get_content_maintype() == 'multipart'} 返回的是 @code{False} 。使用 @code{_structure} 除错帮助函数可以帮助我们在下面这个例子当中看清楚这一点：

@example
>>> from email.iterators import _structure
>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain
@end example

在这里， @code{message} 的部分并非 @code{multiparts} ，但是它们真的包含子部分！ @code{is_multipart()} 返回 @code{True} ， @code{walk} 也深入进这些子部分中。
@end deffn

@geindex get_body() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_body}@anchor{2936}
@deffn {方法} get_body (preferencelist=('related', 'html', 'plain'))

返回信息的 MIME 部分。这个部分是最可能成为信息体的部分。

@emph{preferencelist} 必须是一个字符串序列，其内容从 @code{related} 、 @code{html} 和 @code{plain} 这三者组成的集合中选取。这个序列代表着返回的部分的内容类型之偏好。

在 @code{get_body} 方法被调用的对象上寻找匹配的候选者。

如果 @code{related} 未包括在 @emph{preferencelist} 中，可考虑将所遇到的任意相关的根部分（或根部分的子部分）在该（子）部分与一个首选项相匹配时作为候选项。

当遇到一个 @code{multipart/related} 时，将检查 @code{start} 形参并且如果找到了一个匹配 @code{Content-ID} 的部分，在查找候选匹配时只考虑它。 在其他情况下则只考虑 @code{multipart/related} 的第一个（默认的根）部分。

如果一个部分具有 @code{Content-Disposition} 标头，则当标头值为 @code{inline} 时将只考虑将该部分作为候选匹配。

如果没有任何候选部分匹配 @emph{preferencelist} 中的任何首选项，则返回 @code{None}。

注: (1) 对于大多数应用来说有意义的 @emph{preferencelist} 组合仅有 @code{('plain',)}, @code{('html', 'plain')} 以及默认的 @code{('related', 'html', 'plain')}。 (2) 由于匹配是从调用 @code{get_body} 的对象开始的，因此在 @code{multipart/related} 上调用 @code{get_body} 将返回对象本身，除非 @emph{preferencelist} 具有非默认值。 (3) 未指定 @code{Content-Type} 或者 @code{Content-Type} 标头无效的消息（或消息部分）将被当作具有 @code{text/plain} 类型来处理，这有时可能导致 @code{get_body} 返回非预期的结果。
@end deffn

@geindex iter_attachments() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage iter_attachments}@anchor{2937}
@deffn {方法} iter_attachments ()

返回包含所有不是候选 "body" 部分的消息的直接子部分的迭代器。 也就是说，跳过首次出现的每个 @code{text/plain}, @code{text/html}, @code{multipart/related} 或 @code{multipart/alternative} (除非通过 @code{Content-Disposition: attachment} 将它们显式地标记为附件)，并返回所有的其余部分。 当直接应用于 @code{multipart/related} 时，将返回包含除根部分之外所有相关部分的迭代器（即由 @code{start} 形参所指向的部分，或者当没有 @code{start} 形参或 @code{start} 形参不能匹配任何部分的 @code{Content-ID} 时则为第一部分）。 当直接应用于 @code{multipart/alternative} 或非 @code{multipart} 时，将返回一个空迭代器。
@end deffn

@geindex iter_parts() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage iter_parts}@anchor{2938}
@deffn {方法} iter_parts ()

返回包含消息的所有直接子部分的迭代器，对于非 @code{multipart} 将为空对象。 （另请参阅 @ref{2935,,walk()}。）
@end deffn

@geindex get_content() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage get_content}@anchor{2939}
@deffn {方法} get_content (*args, content_manager=None, **kw)

调用 @emph{content_manager} 的 @ref{293a,,get_content()} 方法，将自身作为消息对象传入，并将其他参数或关键字作为额外参数传入。 如果未指定 @emph{content_manager}，则会使用当前 @ref{73,,policy} 所指定的 @code{content_manager}。
@end deffn

@geindex set_content() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage set_content}@anchor{fcc}
@deffn {方法} set_content (*args, content_manager=None, **kw)

调用 @emph{content_manager} 的 @ref{293b,,set_content()} 方法，将自身作为消息传入，并将其他参数或关键字作为额外参数传入。 如果未指定 @emph{content_manager}，则会使用当前 @ref{73,,policy} 所指定的 @code{content_manager}。
@end deffn

@geindex make_related() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage make_related}@anchor{293c}
@deffn {方法} make_related (boundary=None)

将非 @code{multipart} 消息转换为 @code{multipart/related} 消息，将任何现有的 @code{Content-} 标头和载荷移入 @code{multipart} 的（新加）首部分。 如果指定了 @emph{boundary}，会用它作为 multipart 中的分界字符串，否则会在必要时自动创建分界（例如当消息被序列化时）。
@end deffn

@geindex make_alternative() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage make_alternative}@anchor{293d}
@deffn {方法} make_alternative (boundary=None)

将非 @code{multipart} 或 @code{multipart/related} 转换为 @code{multipart/alternative}，将任何现有的 @code{Content-} 标头和载荷移入 @code{multipart} 的（新加）首部分。 如果指定了 @emph{boundary}，会用它作为 multipart 中的分界字符串，否则会在必要时自动创建分界（例如当消息被序列化时）。
@end deffn

@geindex make_mixed() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage make_mixed}@anchor{293e}
@deffn {方法} make_mixed (boundary=None)

将非 @code{multipart}, @code{multipart/related} 或 @code{multipart-alternative} 转换为 @code{multipart/mixed}，将任何现有的 @code{Content-} 标头和载荷移入 @code{multipart} 的（新加）首部分。 如果指定了 @emph{boundary}，会用它作为 multipart 中的分界字符串，否则会在必要时自动创建分界（例如当消息被序列化时）。
@end deffn

@geindex add_related() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage add_related}@anchor{293f}
@deffn {方法} add_related (*args, content_manager=None, **kw)

如果消息为 @code{multipart/related}，则创建一个新的消息对象，将所有参数传给其 @ref{fcc,,set_content()} 方法，并将其 @ref{2940,,attach()} 到 @code{multipart}。 如果消息为非 @code{multipart}，则先调用 @ref{293c,,make_related()} 然后再继续上述步骤。 如果消息为任何其他类型的 @code{multipart}，则会引发 @ref{1ff,,TypeError}。 如果未指定 @emph{content_manager}，则使用当前 @ref{73,,policy} 所指定的 @code{content_manager}。 如果添加的部分没有 @code{Content-Disposition} 标头，则会添加一个值为 @code{inline} 的标头。
@end deffn

@geindex add_alternative() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage add_alternative}@anchor{2941}
@deffn {方法} add_alternative (*args, content_manager=None, **kw)

如果消息为 @code{multipart/alternative}，则创建一个新的消息对象，将所有参数传给其 @ref{fcc,,set_content()} 方法，并将其 @ref{2940,,attach()} 到 @code{multipart}。 如果消息为非 @code{multipart} 或 @code{multipart/related}，则先调用 @ref{293d,,make_alternative()} 然后再继续上述步骤。 如果消息为任何其他类型的 @code{multipart}，则会引发 @ref{1ff,,TypeError}。 如果未指定 @emph{content_manager}，则会使用当前 @ref{73,,policy} 所指定的 @code{content_manager}。
@end deffn

@geindex add_attachment() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage add_attachment}@anchor{2942}
@deffn {方法} add_attachment (*args, content_manager=None, **kw)

如果消息为 @code{multipart/mixed}，则创建一个新的消息对象，将所有参数传给其 @ref{fcc,,set_content()} 方法，并将其 @ref{2940,,attach()} 到 @code{multipart}。 如果消息为非 @code{multipart}, @code{multipart/related} 或 @code{multipart/alternative}，则先调用 @ref{293e,,make_mixed()} 然后再继续上述步骤。 如果未指定 @emph{content_manager}，则使用当前 @ref{73,,policy} 所指定的 @code{content_manager}。 如果添加的部分没有 @code{Content-Disposition} 标头，则会添加一个值为 @code{attachment} 的标头。 此方法对于显式附件 (@code{Content-Disposition: attachment}) 和 @code{inline} 附件 (@code{Content-Disposition: inline}) 均可使用，只须向 @code{content_manager} 传入适当的选项即可。
@end deffn

@geindex clear() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage clear}@anchor{2943}
@deffn {方法} clear ()

移除所有载荷和所有标头。
@end deffn

@geindex clear_content() (email.message.EmailMessage 方法)
@anchor{library/email message email message EmailMessage clear_content}@anchor{2944}
@deffn {方法} clear_content ()

移除载荷以及所有 @code{Content-} 标头，其他标头不加改变并且保持其原有顺序。
@end deffn

@ref{645,,EmailMessage} 对象具有下列实例属性:

@geindex preamble (email.message.EmailMessage 属性)
@anchor{library/email message email message EmailMessage preamble}@anchor{2945}
@deffn {属性} preamble

MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永远不可见，因为它处在标准 MIME 保护范围之外。 但是，当查看消息的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变得可见。

@emph{preamble} 属性包含 MIME 文档开头部分的这些处于保护范围之外的文本。 当 @ref{bf4,,Parser} 在标头之后及第一个分界字符串之前发现一些文本时，它会将这些文本赋值给消息的 @emph{preamble} 属性。 当 @ref{c27,,Generator} 写出 MIME 消息的纯文本表示形式时，如果它发现消息具有 @emph{preamble} 属性，它将在标头及第一个分界之间区域写出这些文本。 请参阅 @ref{72,,email.parser} 和 @ref{6c,,email.generator} 了解更多细节。

请注意如果消息对象没有前导文本，则 @emph{preamble} 属性将为 @code{None}。
@end deffn

@geindex epilogue (email.message.EmailMessage 属性)
@anchor{library/email message email message EmailMessage epilogue}@anchor{2946}
@deffn {属性} epilogue

@emph{epilogue} 属性的作用方式与 @emph{preamble} 相同，区别在于它包含在最后一个分界及消息结尾之间出现的文本。 与 @ref{2945,,preamble} 类似，如果没有附加文本，则此属性将为 @code{None}。
@end deffn

@geindex defects (email.message.EmailMessage 属性)
@anchor{library/email message email message EmailMessage defects}@anchor{2947}
@deffn {属性} defects

@emph{defects} 属性包含在解析消息时发现的所有问题的列表。 请参阅 @ref{6b,,email.errors} 了解可能的解析缺陷的详细描述。
@end deffn
@end deffn

@geindex MIMEPart (email.message 中的类)
@anchor{library/email message email message MIMEPart}@anchor{93a}
@deffn {类} email.message.MIMEPart (policy=default)

这个类代表 MIME 消息的子部分。 它与 @ref{645,,EmailMessage} 相似，不同之处在于当 @ref{fcc,,set_content()} 被调用时不会添加 @code{MIME-Version} 标头，因为子部分不需要有它们自己的 @code{MIME-Version} 标头。
@end deffn

@node email parser 解析电子邮件信息,email generator 生成 MIME 文档,email message 表示一封电子邮件信息,email --- 电子邮件与 MIME 处理包
@anchor{library/email parser doc}@anchor{2948}@anchor{library/email parser email-parser-parsing-email-messages}@anchor{2949}@anchor{library/email parser module-email parser}@anchor{72}
@subsubsection @code{email.parser}: 解析电子邮件信息


@geindex email.parser (模块)

@strong{源代码}: Lib/email/parser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/parser.py}


__________________________________________________________________


使用以下两种方法的其中一种以创建消息对象结构：直接创建一个 @ref{645,,EmailMessage} 对象，使用字典接口添加消息头，并且使用 @ref{fcc,,set_content()} 和其他相关方法添加消息负载；或者通过解析一个电子邮件消息的序列化表达来创建消息对象结构。

@ref{67,,email} 包提供了一个可以理解包含 MIME 文档在内的绝大多数电子邮件文档结构的标准语法分析程序。 你可以传递给语法分析程序一个字节串、字符串或者文件对象，语法分析程序会返回给你对应于该对象结构的根 @ref{645,,EmailMessage} 实例。 对于简单的、非 MIME 的消息，这个根对象的负载很可能就是一个包含了该消息文字内容的字符串。 对于 MIME 消息，调用根对象的 @ref{2913,,is_multipart()} 方法会返回 @code{True}，其子项可以通过负载操纵方法来进行访问，例如 @ref{2936,,get_body()}、@ref{2938,,iter_parts()} 还有 @ref{2935,,walk()}。

事实上你可以使用的语法分析程序接口有两种: @ref{bf4,,Parser} API 和增量式的 @ref{294a,,FeedParser} API。当你的全部消息内容都在内存当中，或者整个消息都保存在文件系统内的一个文件当中的时候，@ref{bf4,,Parser} API非常有用。当你从可能会为了等待更多输入而阻塞的数据流当中读取消息（比如从套接字当中读取电子邮件消息）的时候，@ref{294a,,FeedParser} 会更合适。@ref{294a,,FeedParser} 会增量读取并解析消息，并且只有在你关闭语法分析程序的时候才会返回根对象。

请注意，语法分析程序可以进行有限的拓展，你当然也可以完全从零开始实现你自己的语法分析程序。将 @ref{67,,email} 包中内置的语法分析程序和 @ref{645,,EmailMessage} 类连接起来的所有逻辑代码都包含在 @code{policy} 类当中，所以如有必要，自定义的语法分析程序可以通过实现自定义的对应 @code{policy} 方法来创建对应的消息对象树。

@menu
* FeedParser API:: 
* Parser API:: 
* 附加说明:: 

@end menu

@node FeedParser API,Parser API,,email parser 解析电子邮件信息
@anchor{library/email parser feedparser-api}@anchor{294b}
@subsubsection FeedParser API


从 @code{email.feedparser} 模块导入的 @ref{c24,,BytesFeedParser}  类提供了一个适合于增量解析电子邮件消息的API，比如说在从一个可能会阻塞（例如套接字）的源当中读取消息文字的场合中它就会变得很有用。当然， @ref{c24,,BytesFeedParser} 也可以用来解析一个已经完整包含在一个 @ref{6e9,,bytes-like object} 、字符串或文件内的电子邮件消息，但是在这些场合下使用 @ref{c25,,BytesParser} API可能会更加方便。这两个语法分析程序API的语义和最终结果是一致的。

@ref{c24,,BytesFeedParser} 的API十分简洁易懂：你创建一个语法分析程序的实例，向它不断输入大量的字节直到尽头，然后关闭这个语法分析程序就可以拿到根消息对象了。 在处理符合标准的消息的时候 @ref{c24,,BytesFeedParser} 非常准确；在处理不符合标准的消息的时候它做的也不差，但这视消息损坏的程度而定。它会向消息对象的 @ref{2947,,defects} 属性中写入它从消息中找到的问题列表。关于它能找到的所有问题类型的列表，详见 @ref{6b,,email.errors} 模块。

这里是 @ref{c24,,BytesFeedParser} 的 API：

@geindex BytesFeedParser (email.parser 中的类)
@anchor{library/email parser email parser BytesFeedParser}@anchor{c24}
@deffn {类} email.parser.BytesFeedParser (_factory=None, *, policy=policy.compat32)

创建一个 @ref{c24,,BytesFeedParser} 实例。可选的 @emph{_factory} 参数是一个不带参数的可调用对象；如果没有被指定，就会使用 @emph{policy} 参数的 @ref{642,,message_factory} 属性。 每当需要一个新的消息对象的时候，@emph{_factory} 都会被调用。

如果指定了 @emph{policy} 参数，它就会使用这个参数所指定的规则来更新消息的表达方式。 如果没有设定 @emph{policy} 参数，它就会使用 @ref{add,,compat32} 策略。 这个策略维持了对 Python 3.2 版本的 email 包的后向兼容性，并且使用 @ref{644,,Message} 作为默认的工厂。 其他策略使用 @ref{645,,EmailMessage} 作为默认的 @emph{_factory}。 关于 @emph{policy} 还会控制什么，参见 @ref{73,,policy} 的文档。

注：@strong{一定要指定policy关键字}。在未来版本的Python当中，它的默认值会变成 @ref{290e,,email.policy.default} 。


3.2 新版功能.



在 3.3 版更改: 添加了 @emph{policy} 关键字。



在 3.6 版更改: @emph{_factory} 默认为策略 @code{message_factory}。


@geindex feed() (email.parser.BytesFeedParser 方法)
@anchor{library/email parser email parser BytesFeedParser feed}@anchor{294c}
@deffn {方法} feed (data)

向语法分析程序输入更多数据。@emph{data} 应当是一个包含一行或多行内容的 @ref{6e9,,bytes-like object}。 行内容可以是不完整的，语法分析程序会妥善的将这些不完整的行缝合在一起。每一行可以使用以下三种常见的终止符号的其中一种：回车符、换行符或回车符加换行符（三者甚至可以混合使用）。
@end deffn

@geindex close() (email.parser.BytesFeedParser 方法)
@anchor{library/email parser email parser BytesFeedParser close}@anchor{294d}
@deffn {方法} close ()

完成之前输入的所有数据的解析并返回根消息对象。如果在这个方法被调用之后仍然调用 @ref{294c,,feed()} 方法，结果是未定义的。
@end deffn
@end deffn

@geindex FeedParser (email.parser 中的类)
@anchor{library/email parser email parser FeedParser}@anchor{294a}
@deffn {类} email.parser.FeedParser (_factory=None, *, policy=policy.compat32)

行为跟 @ref{c24,,BytesFeedParser} 类一致，只不过向 @ref{294c,,feed()} 方法输入的内容必须是字符串。它的实用性有限，因为这种消息只有在其只含有ASCII文字，或者 @code{utf8} 被设置为 @code{True} 且没有二进制格式的附件的时候，才会有效。


在 3.3 版更改: 添加了 @emph{policy} 关键字。

@end deffn

@node Parser API,附加说明,FeedParser API,email parser 解析电子邮件信息
@anchor{library/email parser parser-api}@anchor{294e}
@subsubsection Parser API


@ref{c25,,BytesParser} 类从 @ref{72,,email.parser} 模块导入，当消息的完整内容包含在一个 @ref{6e9,,bytes-like object} 或文件中时它提供了可用于解析消息的 API。 @ref{72,,email.parser} 模块还提供了 @ref{bf4,,Parser} 用来解析字符串，以及只用来解析消息头的 @ref{ae4,,BytesHeaderParser} 和 @ref{ae5,,HeaderParser}，如果你只对消息头感兴趣就可以使用后两者。 在这种场合下 @ref{ae4,,BytesHeaderParser} 和 @ref{ae5,,HeaderParser} 速度非常快，因为它们并不会尝试解析消息体，而是将载荷设为原始数据。

@geindex BytesParser (email.parser 中的类)
@anchor{library/email parser email parser BytesParser}@anchor{c25}
@deffn {类} email.parser.BytesParser (_class=None, *, policy=policy.compat32)

创建一个 @ref{c25,,BytesParser} 实例。 @emph{_class} 和 @emph{policy} 参数在含义和语义上与 @ref{c24,,BytesFeedParser} 的 @emph{_factory} 和 @emph{policy} 参数一致。

注：@strong{一定要指定policy关键字}。在未来版本的Python当中，它的默认值会变成 @ref{290e,,email.policy.default} 。


在 3.3 版更改: 移除了在2.4版本中被弃用的 @emph{strict} 参数。新增了 @emph{policy} 关键字。



在 3.6 版更改: @emph{_class} 默认为策略 @code{message_factory}。


@geindex parse() (email.parser.BytesParser 方法)
@anchor{library/email parser email parser BytesParser parse}@anchor{294f}
@deffn {方法} parse (fp, headersonly=False)

从二进制的类文件对象 @emph{fp} 中读取全部数据、解析其字节内容、并返回消息对象。 @emph{fp} 必须同时支持 @ref{1883,,readline()} 方法和 @code{read()} 方法。

@emph{fp} 内包含的字节内容必须是一块遵循 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} （如果 @code{utf8} 为 @code{True}，则为 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://tools.ietf.org/html/rfc6532.html} ）格式风格的消息头和消息头延续行，并可能紧跟一个信封头。 头块要么以数据结束，要么以一个空行为终止。 跟着头块的是消息体（消息体内可能包含 MIME 编码的子部分，这也包括 @code{Content-Transfer-Encoding} 字段为 @code{8bit} 的子部分）。

可选的 @emph{headersonly} 指示了是否应当在读取完消息头后就终止。默认值为 @code{False} ，意味着它会解析整个文件的全部内容。
@end deffn

@geindex parsebytes() (email.parser.BytesParser 方法)
@anchor{library/email parser email parser BytesParser parsebytes}@anchor{2950}
@deffn {方法} parsebytes (bytes, headersonly=False)

与 @ref{294f,,parse()} 方法类似，只不过它要求输入为一个 @ref{6e9,,bytes-like object} 而不是类文件对象。于一个 @ref{6e9,,bytes-like object} 调用此方法相当于先将这些字节包装于一个 @ref{894,,BytesIO} 实例中，然后调用 @ref{294f,,parse()} 方法。

可选的 @emph{headersonly} 与 @ref{294f,,parse()} 方法中的 @emph{headersonly} 是一致的。
@end deffn


3.2 新版功能.

@end deffn

@geindex BytesHeaderParser (email.parser 中的类)
@anchor{library/email parser email parser BytesHeaderParser}@anchor{ae4}
@deffn {类} email.parser.BytesHeaderParser (_class=None, *, policy=policy.compat32)

除了 @emph{headersonly} 默认为 @code{True}，其他与 @ref{c25,,BytesParser} 类完全一样。


3.3 新版功能.

@end deffn

@geindex Parser (email.parser 中的类)
@anchor{library/email parser email parser Parser}@anchor{bf4}
@deffn {类} email.parser.Parser (_class=None, *, policy=policy.compat32)

这个类与 @ref{c25,,BytesParser} 一样，但是处理字符串输入。


在 3.3 版更改: 移除了 @emph{strict} 参数。添加了 @emph{policy} 关键字。



在 3.6 版更改: @emph{_class} 默认为策略 @code{message_factory}。


@geindex parse() (email.parser.Parser 方法)
@anchor{library/email parser email parser Parser parse}@anchor{2951}
@deffn {方法} parse (fp, headersonly=False)

从文本模式的文件类对象 @emph{fp} 读取所有数据，解析所读取的文本，并返回根消息对象。 @emph{fp} 必须同时支持文件类对象上的 @ref{1da3,,readline()} 和 @ref{2192,,read()} 方法。

除了文字模式的要求外，这个方法跟 @ref{294f,,BytesParser.parse()}  的运行方式一致。
@end deffn

@geindex parsestr() (email.parser.Parser 方法)
@anchor{library/email parser email parser Parser parsestr}@anchor{2952}
@deffn {方法} parsestr (text, headersonly=False)

与 @ref{2951,,parse()} 方法类似，只不过它要求输入为一个字符串而不是类文件对象。于一个字符串对象调用此方法相当于先将 @emph{text} 包装于一个 @ref{924,,StringIO} 实例中，然后调用 @ref{2951,,parse()}  方法。

可选的 @emph{headersonly} 与 @ref{2951,,parse()} 方法中的 @emph{headersonly} 是一致的。
@end deffn
@end deffn

@geindex HeaderParser (email.parser 中的类)
@anchor{library/email parser email parser HeaderParser}@anchor{ae5}
@deffn {类} email.parser.HeaderParser (_class=None, *, policy=policy.compat32)

除了 @emph{headersonly} 默认为 @code{True} ，其他与 @ref{bf4,,Parser} 类完全一样。
@end deffn

考虑到从一个字符串或一个文件对象中创建一个消息对象是非常常见的任务，我们提供了四个方便的函数。它们于顶层 @ref{67,,email} 包命名空间内可用。

@geindex message_from_bytes() (在 email 模块中)
@anchor{library/email parser email message_from_bytes}@anchor{c22}
@deffn {函数} email.message_from_bytes (s, _class=None, *, policy=policy.compat32)

从一个 @ref{6e9,,bytes-like object} 中返回消息对象。 这与 @code{BytesParser().parsebytes(s)} 等价。 可选的 @emph{_class} 和 @emph{policy} 参数与 @ref{c25,,BytesParser} 类的构造函数的参数含义一致。


3.2 新版功能.



在 3.3 版更改: 移除了 @emph{strict} 参数。添加了 @emph{policy} 关键字。

@end deffn

@geindex message_from_binary_file() (在 email 模块中)
@anchor{library/email parser email message_from_binary_file}@anchor{c23}
@deffn {函数} email.message_from_binary_file (fp, _class=None, *, policy=policy.compat32)

从打开的二进制 @ref{c1d,,file object} 中返回消息对象。 这与 @code{BytesParser().parse(fp)} 等价。 @emph{_class} 和 @emph{policy} 参数与 @ref{c25,,BytesParser} 类的构造函数的参数含义一致。


3.2 新版功能.



在 3.3 版更改: 移除了 @emph{strict} 参数。添加了 @emph{policy} 关键字。

@end deffn

@geindex message_from_string() (在 email 模块中)
@anchor{library/email parser email message_from_string}@anchor{2953}
@deffn {函数} email.message_from_string (s, _class=None, *, policy=policy.compat32)

从一个字符串中返回消息对象。 这与 @code{Parser().parsestr(s)} 等价。 @emph{_class} 和 @emph{policy} 参数与 @ref{bf4,,Parser} 类的构造函数的参数含义一致。


在 3.3 版更改: 移除了 @emph{strict} 参数。添加了 @emph{policy} 关键字。

@end deffn

@geindex message_from_file() (在 email 模块中)
@anchor{library/email parser email message_from_file}@anchor{2954}
@deffn {函数} email.message_from_file (fp, _class=None, *, policy=policy.compat32)

从一个打开的 @ref{c1d,,file object} 中返回消息对象。 这与 @code{Parser().parse(fp)} 等价。 @emph{_class} 和 @emph{policy} 参数与 @ref{bf4,,Parser} 类的构造函数的参数含义一致。


在 3.3 版更改: 移除了 @emph{strict} 参数。添加了 @emph{policy} 关键字。



在 3.6 版更改: @emph{_class} 默认为策略 @code{message_factory}。

@end deffn

这里是一个展示了你如何在Python交互式命令行中使用 @ref{c22,,message_from_bytes()} 的例子：

@example
>>> import email
>>> msg = email.message_from_bytes(myBytes)  
@end example

@node 附加说明,,Parser API,email parser 解析电子邮件信息
@anchor{library/email parser additional-notes}@anchor{2955}
@subsubsection 附加说明


在解析语义的时候请注意：


@itemize *

@item 
大多数非 @code{multipart} 类型的消息都会被解析为一个带有字符串负载的消息对象。这些对象在调用 @ref{2913,,is_multipart()} 的时候会返回 @code{False} ，调用 @ref{2938,,iter_parts()} 的时候会产生一个空列表。

@item 
所有 @code{multipart} 类型的消息都会被解析成一个容器消息对象。该对象的负载是一个子消息对象列表。外层的容器消息在调用 @ref{2913,,is_multipart()} 的时候会返回 @code{True} ，在调用 @ref{2938,,iter_parts()} 的时候会产生一个子部分列表。

@item 
大多数内容类型为 @code{message/*} （例如 @code{message/delivery-status} 和 @code{message/rfc822} ）的消息也会被解析为一个负载是长度为1的列表的容器对象。在它们身上调用 @ref{2913,,is_multipart()} 方法会返回 @code{True} ，调用 @ref{2938,,iter_parts()} 所产生的单个元素会是一个子消息对象。

@item 
一些不遵循标准的消息在其内部关于它是否为 @code{multipart} 类型前后不一。这些消息可能在消息头的 @code{Content-Type} 字段中写明为 @code{multipart} ，但它们的 @ref{2913,,is_multipart()} 方法的返回值可能是 @code{False} 。如果这种消息被 @ref{294a,,FeedParser} 类解析，它们的 @emph{defects} 属性列表当中会有一个 @code{MultipartInvariantViolationDefect} 类的实例。关于更多信息，详见 @ref{6b,,email.errors} 。
@end itemize

@node email generator 生成 MIME 文档,email policy Policy 对象,email parser 解析电子邮件信息,email --- 电子邮件与 MIME 处理包
@anchor{library/email generator doc}@anchor{2956}@anchor{library/email generator email-generator-generating-mime-documents}@anchor{2957}@anchor{library/email generator module-email generator}@anchor{6c}
@subsubsection @code{email.generator}: 生成 MIME 文档


@geindex email.generator (模块)

@strong{源代码:} Lib/email/generator.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/generator.py}


__________________________________________________________________


最普通的一种任务是生成由消息对象结构体表示的电子邮件消息的扁平（序列化）版本。 如果你想通过 @ref{83d,,smtplib.SMTP.sendmail()} 或 @ref{c0,,nntplib} 模块来发送你的消息或是将消息打印到控制台就将需要这样做。 接受一个消息对象结构体并生成其序列化表示就是这些生成器类的工作。

与 @ref{72,,email.parser} 模块一样，你并不会受限于已捆绑生成器的功能；你可以自己从头写一个。 不过，已捆绑生成器知道如何以符合标准的方式来生成大多数电子邮件，应该能够很好地处理 MIME 和非 MIME 电子邮件消息，并且被设计为面向字节的解析和生成操作是互逆的，它假定两者都使用同样的非转换型 @ref{73,,policy}。 也就是说，通过 @ref{c25,,BytesParser} 类来解析序列化字节流然后再使用 @ref{c28,,BytesGenerator} 来重新生成序列化字节流应当得到与输入相同的结果 @footnote{@w{(1)} 
此语句假定你使用了正确的 @code{unixfrom} 设置，并且没有用于自动调整的 @code{policy} 设置调用（例如 @code{refold_source} 必须为 @code{none}，这 @emph{不是} 默认值）。 这也不是 100% 为真，因为如果消息不遵循 RFC 标准则有时实际原始文本的信息会在解析错误恢复时丢失。 它的目标是在可能的情况下修复这些后续边缘情况。
}。 （而另一方面，在由程序所构造的 @ref{645,,EmailMessage} 上使用生成器可能导致对默认填入的 @ref{645,,EmailMessage} 对象的改变。。）

可以使用 @ref{c27,,Generator} 类将消息扁平化为文本（而非二进制数据）的序列化表示形式，但是由于 Unicode 无法直接表示二进制数据，因此消息有必要被转换为仅包含 ASCII 字符的数据，这将使用标准电子邮件 RFC 内容传输编码格式技术来编码电子邮件消息以便通过非 “8 比特位兼容”的信道来传输。

为了适应 SMIME 签名消息的可重现处理过程，@ref{c27,,Generator} 禁用了针对 @code{multipart/signed} 类型的消息部分及所有子部分的标头折叠。

@geindex BytesGenerator (email.generator 中的类)
@anchor{library/email generator email generator BytesGenerator}@anchor{c28}
@deffn {类} email.generator.BytesGenerator (outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

返回一个 @ref{c28,,BytesGenerator} 对象，该对象将把提供给 @ref{2958,,flatten()} 方法的任何消息或者提供给 @ref{2959,,write()} 方法的任何经过代理转义编码的文本写入到 @ref{1e0e,,file-like object} @emph{outfp}。 @emph{outfp} 必须支持接受二进制数据的 @code{write} 方法。

如果可选的 @emph{mangle_from_} 为 @code{True}，则会将一个 @code{>} 字符放到恰好以字符串 @code{"From "} 打头，即开头文本为 @code{From} 加一个空格的的行前面。 @emph{mangle_from_} 默认为 @emph{policy} 的 @ref{7cd,,mangle_from_} 设置值 (对于 @ref{643,,compat32} 策略为 @code{True}，对于所有其他策略则为 @code{False})。 @emph{mangle_from_} 被设计为在当消息以 unix mbox 格式存储时使用 (参见 @ref{ae,,mailbox} 和 WHY THE CONTENT-LENGTH FORMAT IS BAD@footnote{https://www.jwz.org/doc/content-length.html})。

如果 @emph{maxheaderlen} 不为 @code{None}，则重新折叠任何长于 @emph{maxheaderlen} 的标头行，或者如果为 @code{0}，则不重新包装任何标头。 如果 @emph{manheaderlen} 为 @code{None} (默认值)，则根据 @emph{policy} 设置包装标头和其他消息行。

如果指定了 @emph{policy}，则使用该策略来控制消息的生成。 如果 @emph{policy} 为 @code{None} (默认值)，则使用与传递给 @code{flatten} 的 @ref{644,,Message} 或 @ref{645,,EmailMessage} 对象相关联的策略来控制消息的生成。 请参阅 @ref{73,,email.policy} 了解有关 @emph{policy} 所控制内容的详情。


3.2 新版功能.



在 3.3 版更改: 添加了*policy*关键字。



在 3.6 版更改: @emph{mangle_from_} 和 @emph{maxheaderlen} 形参的默认行为是遵循策略。


@geindex flatten() (email.generator.BytesGenerator 方法)
@anchor{library/email generator email generator BytesGenerator flatten}@anchor{2958}
@deffn {方法} flatten (msg, unixfrom=False, linesep=None)

将将以 @emph{msg} 为根的消息对象结构体的文本表示形式打印到创建 @ref{c28,,BytesGenerator} 实例时指定的输出文件。

如果 @ref{73,,policy} 选项 @ref{295a,,cte_type} 为 @code{8bit} (默认值)，则会将未被修改的原始已解析消息中的任何标头拷贝到输出，其中会重新生成与原始数据相同的高比特位组字节数据，并保留具有它们的任何消息体部分的非 ASCII @code{Content-Transfer-Encoding}。 如果 @code{cte_type} 为 @code{7bit}，则会根据需要使用兼容 ASCII 的 @code{Content-Transfer-Encoding} 来转换高比特位组字节数据。 也就是说，将具有非 ASCII @code{Content-Transfer-Encoding} (@code{Content-Transfer-Encoding: 8bit}) 的部分转换为兼容 ASCII 的 @code{Content-Transfer-Encoding}，并使用 MIME @code{unknown-8bit} 字符集来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

@c XXX: There should be an option that just does the RFC
@c compliance transformation on headers but leaves CTE 8bit parts alone.

如果 @emph{unixfrom} 为 @code{True}，则会在根消息对象的第一个 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 标头之前打印 Unix mailbox 格式 (参见 @ref{ae,,mailbox}) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建一个标准标头。 默认值为 @code{False}。 请注意对于子部分来说，不会打印任何封包标头。

如果 @emph{linesep} 不为 @code{None}，则会将其用作扁平化消息的所有行之间的分隔符。 如果 @emph{linesep} 为 @code{None} (默认值)，则使用在 @emph{policy} 中指定的值。

@c XXX: flatten should take a *policy* keyword.
@end deffn

@geindex clone() (email.generator.BytesGenerator 方法)
@anchor{library/email generator email generator BytesGenerator clone}@anchor{295b}
@deffn {方法} clone (fp)

返回此 @ref{c28,,BytesGenerator} 实例的独立克隆，具有完全相同的选项设置，而 @emph{fp} 为新的 @emph{outfp}。
@end deffn

@geindex write() (email.generator.BytesGenerator 方法)
@anchor{library/email generator email generator BytesGenerator write}@anchor{2959}
@deffn {方法} write (s)

使用 @code{ASCII} 编解码器和 @code{surrogateescape} 错误处理程序编码 @emph{s}，并将其传递给传入到 @ref{c28,,BytesGenerator} 的构造器的 @emph{outfp} 的 @emph{write} 方法 。
@end deffn
@end deffn

作为一个便捷工具，@ref{645,,EmailMessage} 提供了 @ref{2911,,as_bytes()} 和 @code{bytes(aMessage)} (即 @ref{2912,,__bytes__()}) 等方法，它们简单地生成一个消息对象的序列化二进制表示形式。 更多细节请参阅 @ref{70,,email.message}。

因为字符串无法表示二进制数据，@ref{c27,,Generator} 类必须将任何消息中扁平化的任何二进制数据转换为兼容 ASCII 的格式，具体将其转换为兼容 ASCII 的 @code{Content-Transfer_Encoding}。 使用电子邮件 RFC 的术语，你可以将其视作 @ref{c27,,Generator} 序列化为不 "支持 8 比特" 的 I/O 流。 换句话说，大部分应用程序将需要使用 @ref{c28,,BytesGenerator}，而非 @ref{c27,,Generator}。

@geindex Generator (email.generator 中的类)
@anchor{library/email generator email generator Generator}@anchor{c27}
@deffn {类} email.generator.Generator (outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

返回一个 @ref{c27,,Generator}，它将把提供给 @ref{295c,,flatten()} 方法的任何消息，或者提供给 @ref{295d,,write()} 方法的任何文本写入到 @ref{1e0e,,file-like object} @emph{outfp}。 @emph{outfp} 必须支持接受字符串数据的 @code{write} 方法。

如果可选的 @emph{mangle_from_} 为 @code{True}，则会将一个 @code{>} 字符放到恰好以字符串 @code{"From "} 打头，即开头文本为 @code{From} 加一个空格的的行前面。 @emph{mangle_from_} 默认为 @emph{policy} 的 @ref{7cd,,mangle_from_} 设置值 (对于 @ref{643,,compat32} 策略为 @code{True}，对于所有其他策略则为 @code{False})。 @emph{mangle_from_} 被设计为在当消息以 unix mbox 格式存储时使用 (参见 @ref{ae,,mailbox} 和 WHY THE CONTENT-LENGTH FORMAT IS BAD@footnote{https://www.jwz.org/doc/content-length.html})。

如果 @emph{maxheaderlen} 不为 @code{None}，则重新折叠任何长于 @emph{maxheaderlen} 的标头行，或者如果为 @code{0}，则不重新包装任何标头。 如果 @emph{manheaderlen} 为 @code{None} (默认值)，则根据 @emph{policy} 设置包装标头和其他消息行。

如果指定了 @emph{policy}，则使用该策略来控制消息的生成。 如果 @emph{policy} 为 @code{None} (默认值)，则使用与传递给 @code{flatten} 的 @ref{644,,Message} 或 @ref{645,,EmailMessage} 对象相关联的策略来控制消息的生成。 请参阅 @ref{73,,email.policy} 了解有关 @emph{policy} 所控制内容的详情。


在 3.3 版更改: 添加了*policy*关键字。



在 3.6 版更改: @emph{mangle_from_} 和 @emph{maxheaderlen} 形参的默认行为是遵循策略。


@geindex flatten() (email.generator.Generator 方法)
@anchor{library/email generator email generator Generator flatten}@anchor{295c}
@deffn {方法} flatten (msg, unixfrom=False, linesep=None)

将以 @emph{msg} 为根的消息对象结构体的文本表示形式打印到当 @ref{c27,,Generator} 实例被创建时所指定的输出文件。

如果 @ref{73,,policy} 选项 @ref{295a,,cte_type} 为 @code{8bit}，则视同选项被设为 @code{7bit} 来生成消息。 （这是必需的，因为字符串无法表示非 ASCII 字节数据。） 将使用兼容 ASCII 的 @code{Content-Transfer-Encoding} 按需转换任何具有高比特位组的字节数据。 也就是说，将具有非 ASCII @code{Content-Transfer-Encoding} (@code{Content-Transfer-Encoding: 8bit}) 的部分转换为兼容 ASCII 的 @code{Content-Transfer-Encoding}，并使用 MIME @code{unknown-8bit} 字符集来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

如果 @emph{unixfrom} 为 @code{True}，则会在根消息对象的第一个 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 标头之前打印 Unix mailbox 格式 (参见 @ref{ae,,mailbox}) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建一个标准标头。 默认值为 @code{False}。 请注意对于子部分来说，不会打印任何封包标头。

如果 @emph{linesep} 不为 @code{None}，则会将其用作扁平化消息的所有行之间的分隔符。 如果 @emph{linesep} 为 @code{None} (默认值)，则使用在 @emph{policy} 中指定的值。

@c XXX: flatten should take a *policy* keyword.


在 3.2 版更改: 添加了对重编码 @code{8bit} 消息体的支持，以及 @emph{linesep} 参数。

@end deffn

@geindex clone() (email.generator.Generator 方法)
@anchor{library/email generator email generator Generator clone}@anchor{295e}
@deffn {方法} clone (fp)

返回此 @ref{c27,,Generator} 实例的独立克隆，具有完全相同的选项设置，而 @emph{fp} 为新的 @emph{outfp}。
@end deffn

@geindex write() (email.generator.Generator 方法)
@anchor{library/email generator email generator Generator write}@anchor{295d}
@deffn {方法} write (s)

将 @emph{s} 写入到传给 @ref{c27,,Generator} 的构造器的 @emph{outfp} 的 @emph{write} 方法。 这足够为 @ref{c27,,Generator} 实际提供可用于 @ref{97a,,print()} 函数的文件类 API。
@end deffn
@end deffn

作为一个便捷工具，@ref{645,,EmailMessage} 提供了 @ref{290f,,as_string()} 和 @code{str(aMessage)} (即 @ref{2910,,__str__()}) 等方法，它们简单地生成一个消息对象的已格式化字符串表示形式。 更多细节请参阅 @ref{70,,email.message}。

@ref{6c,,email.generator} 模块还提供了一个派生类 @ref{641,,DecodedGenerator}，它类似于 @ref{c27,,Generator} 基类，不同之处在于非 @code{text} 部分不会被序列化，而是被表示为 基于模板并填写了有关该部分的信息的字符串输出流的形式。

@geindex DecodedGenerator (email.generator 中的类)
@anchor{library/email generator email generator DecodedGenerator}@anchor{641}
@deffn {类} email.generator.DecodedGenerator (outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None)

行为类似于 @ref{c27,,Generator}，不同之处在于对传给 @ref{295c,,Generator.flatten()} 的消息的任何子部分，如果该子部分的主类型为 @code{text}，则打印该子部分的已解码载荷，而如果其主类型不为 @code{text}，则不直接打印它而是使用来自该部分的信息填入字符串 @emph{fmt} 并将填写完成的字符串打印出来。

要填入 @emph{fmt}，则执行 @code{fmt % part_info}，其中 @code{part_info} 是由下列键和值组成的字典:


@itemize *

@item 
@code{type} -- 非 @code{text} 部分的完整 MIME 类型

@item 
@code{maintype} -- 非 @code{text} 部分的主 MIME 类型

@item 
@code{subtype} -- 非 @code{text} 部分的子 MIME 类型

@item 
@code{filename} -- 非 @code{text} 部分的文件名

@item 
@code{description} -- 与非 @code{text} 部分相关联的描述

@item 
@code{encoding} -- 非 @code{text} 部分的内容转换编码格式
@end itemize

如果 @emph{fmt} 为 @code{None}，则使用下列默认 @emph{fmt}:

@quotation

"[忽略消息的非文本 (%(type)s) 部分，文件名 %(filename)s]"
@end quotation

可选的 @emph{_mangle_from_} 和 @emph{maxheaderlen} 与 @ref{c27,,Generator} 基类的相同。
@end deffn

@node email policy Policy 对象,email errors 异常和缺陷类,email generator 生成 MIME 文档,email --- 电子邮件与 MIME 处理包
@anchor{library/email policy doc}@anchor{295f}@anchor{library/email policy email-policy-policy-objects}@anchor{2960}@anchor{library/email policy module-email policy}@anchor{73}
@subsubsection @code{email.policy}: Policy 对象


@geindex email.policy (模块)


3.3 新版功能.


@strong{源代码:} Lib/email/policy.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/policy.py}


__________________________________________________________________


@ref{67,,email} 的主要焦点是按照各种电子邮件和 MIME RFC 的描述来处理电子邮件消息。 但是电子邮件消息的基本格式（一个由名称加冒号加值的标头字段构成的区块，后面再加一个空白行和任意的‘消息体’）是在电子邮件领域以外也获得应用的格式。 这些应用的规则有些与主要电子邮件 RFC 十分接近，有些则很不相同。 即使是操作电子邮件，有时也可能需要打破严格的 RFC 规则，例如生成可与某些并不遵循标准的电子邮件服务器互联的电子邮件，或者是实现希望应用某些破坏标准的操作方式的扩展。

Policy 对象给予 email 包处理这些不同用例的灵活性。

@ref{adc,,Policy} 对象封装了一组属性和方法用来在使用期间控制 email 包中各个组件的行为。 @ref{adc,,Policy} 实例可以被传给 email 包中的多个类和方法以更改它们的默认行为。 可设置的值及其默认值如下所述。

在 email 包中的所有类会使用一个默认的策略。 对于所有 @ref{72,,parser} 类及相关的便捷函数，还有对于 @ref{644,,Message} 类来说，它是 @ref{add,,Compat32} 策略，通过其对应的预定义实例 @ref{643,,compat32} 来使用。 这个策略提供了与 Python3.3 版之前的 email 包的完全向下兼容性（在某些情况下，也包括对缺陷的兼容性）。

传给 @ref{645,,EmailMessage} 的 @emph{policy} 关键字的默认值是 @ref{ae0,,EmailPolicy} 策略，表示为其预定义的实例 @ref{290e,,default}。

在创建 @ref{644,,Message} 或 @ref{645,,EmailMessage} 对象时，它需要一个策略。 如果消息是由 @ref{72,,parser} 创建的，则传给该解析器的策略将是它所创建的消息所使用的策略。 如果消息是由程序创建的，则该策略可以在创建它的时候指定。 当消息被传递给 @ref{6c,,generator} 时，生成器默认会使用来自该消息的策略，但你也可以将指定的策略传递给生成器，这将覆盖存储在消息对象上的策略。

@ref{72,,email.parser} 类和解析器便捷函数的 @emph{policy} 关键字的默认值在未来的 Python 版本中 @strong{将会改变}。 因此在调用任何 @ref{72,,parser} 模块所描述的类和函数时你应当 @strong{总是显式地指定你想要使用的策略}。

本文档的第一部分介绍了 @ref{adc,,Policy} 的特性，它是一个 @ref{c0e,,abstract base class}，定义了所有策略对象包括 @ref{643,,compat32} 的共有特性。 这些特性包括一些由 email 包内部调用的特定钩子方法，自定义策略可以重载这些方法以获得不同行为。 第二部分描述了实体类 @ref{ae0,,EmailPolicy} 和 @ref{add,,Compat32}，它们分别实现了提供标准行为和向下兼容行为与特性的钩子。

@ref{adc,,Policy} 实例是不可变的，但它们可以被克隆，接受与类构造器一致的关键字参数并返回一个新的 @ref{adc,,Policy} 实例，新实例是原实例的副本，但具有被改变的指定属性。

例如，以下代码可以被用来从一个 Unix 系统的磁盘文件中读取电子邮件消息并将其传递给系统的 @code{sendmail} 程序:

@c from unittest import mock
@c mocker = mock.patch('subprocess.Popen')
@c m = mocker.start()
@c proc = mock.MagicMock()
@c m.return_value = proc
@c proc.stdin.close.return_value = None
@c mymsg = open('mymsg.txt', 'w')
@c mymsg.write('To: abc@xyz.com\n\n')
@c mymsg.flush()

@example
>>> from email import message_from_binary_file
>>> from email.generator import BytesGenerator
>>> from email import policy
>>> from subprocess import Popen, PIPE
>>> with open('mymsg.txt', 'rb') as f:
...     msg = message_from_binary_file(f, policy=policy.default)
>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
>>> g.flatten(msg)
>>> p.stdin.close()
>>> rc = p.wait()
@end example

@c mymsg.close()
@c mocker.stop()
@c import os
@c os.remove('mymsg.txt')

这里我们让 @ref{c28,,BytesGenerator} 在创建要送入 @code{sendmail's} @code{stdin} 的二进制字串时使用符合 RFC 的行分隔字符，默认的策略将会使用 @code{\n} 行分隔符。

某些 email 包的方法接受一个 @emph{policy} 关键字参数，允许为该方法重载策略。 例如，以下代码使用了来自之前示例的 @emph{msg} 对象的 @ref{937,,as_bytes()} 方法并使用其运行所在平台的本机行分隔符将消息写入一个文件:

@example
>>> import os
>>> with open('converted.txt', 'wb') as f:
...     f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
17
@end example

Policy 对象也可使用加法运算符进行组合来产生一个新策略对象，其设置是被加总对象的非默认值的组合:

@example
>>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
>>> compat_strict = policy.compat32.clone(raise_on_defect=True)
>>> compat_strict_SMTP = compat_SMTP + compat_strict
@end example

此运算不满足交换律；也就是说对象的添加顺序很重要。 见以下演示:

@example
>>> policy100 = policy.compat32.clone(max_line_length=100)
>>> policy80 = policy.compat32.clone(max_line_length=80)
>>> apolicy = policy100 + policy80
>>> apolicy.max_line_length
80
>>> apolicy = policy80 + policy100
>>> apolicy.max_line_length
100
@end example

@geindex Policy (email.policy 中的类)
@anchor{library/email policy email policy Policy}@anchor{adc}
@deffn {类} email.policy.Policy (**kw)

这是所有策略类的 @ref{c0e,,abstract base class}。 它提供了一些简单方法的默认实现，以及不可变特征属性，@ref{ade,,clone()} 方法以及构造器语义的实现。

可以向策略类的构造器传入各种关键字参数。 可以指定的参数是该类的任何非方法特征属性，以及实体类的任何额外非方法特征属性。 在构造器中指定的值将覆盖相应属性的默认值。

这个类定义了下列特征属性，因此下列值可以被传给任何策略类的构造器:

@geindex max_line_length (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy max_line_length}@anchor{2961}
@deffn {属性} max_line_length

序列化输出中任何行的最大长度，不计入行字符的末尾。 默认值为 78，基于 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html}。 值为 @code{0} 或 @ref{204,,None} 表示完全没有行包装。
@end deffn

@geindex linesep (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy linesep}@anchor{2962}
@deffn {属性} linesep

用来在序列化输出中确定行的字符串。 默认值为 @code{\n} 因为这是 Python 所使用的内部行结束符规范，但 RFC 的要求是 @code{\r\n}。
@end deffn

@geindex cte_type (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy cte_type}@anchor{295a}
@deffn {属性} cte_type

控制可能要求使用的内容传输编码格式类型。 可能的值包括:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{7bit}

@tab

所有数据必须为 "纯 7 比特位" (仅 ASCII)。 这意味着在必要情况下数据将使用可打印引用形式或 base64 编码格式进行编码。

@item

@code{8bit}

@tab

数据不会被限制为纯 7 比特位。 标头中的数据仍要求仅 ASCII 因此将被编码（参阅下文的 @ref{2963,,fold_binary()} 和 @ref{7cf,,utf8} 了解例外情况），但消息体部分可能使用 @code{8bit} CTE。

@end multitable


@code{cte_type} 值为 @code{8bit} 仅适用于 @code{BytesGenerator} 而非 @code{Generator}，因为字符串不能包含二进制数据。 如果 @code{Generator} 运行于指定了 @code{cte_type=8bit} 的策略，它的行为将与 @code{cte_type} 为 @code{7bit} 相同。
@end deffn

@geindex raise_on_defect (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy raise_on_defect}@anchor{2964}
@deffn {属性} raise_on_defect

如为 @ref{59c,,True}，则遇到的任何缺陷都将引发错误。 如为 @ref{497,,False} (默认值)，则缺陷将被传递给 @ref{2965,,register_defect()} 方法。
@end deffn

@geindex mangle_from_ (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy mangle_from_}@anchor{7cd}
@deffn {属性} mangle_from_

如为 @ref{59c,,True}，则消息体中以 @emph{"From "} 开头的行会通过在其前面放一个 @code{>} 来进行转义。 当消息被生成器执行序列化时会使用此形参。 默认值t: @ref{497,,False}。


3.5 新版功能: @emph{mangle_from_} 形参。

@end deffn

@geindex message_factory (email.policy.Policy 属性)
@anchor{library/email policy email policy Policy message_factory}@anchor{642}
@deffn {属性} message_factory

用来构造新的空消息对象的工厂函数。 在构建消息时由解析器使用。 默认为 @code{None}，在此情况下会使用 @ref{644,,Message}。


3.6 新版功能.

@end deffn

下列 @ref{adc,,Policy} 方法是由使用 email 库的代码来调用以创建具有自室外设置的策略实例:

@geindex clone() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy clone}@anchor{ade}
@deffn {方法} clone (**kw)

返回一个新的 @ref{adc,,Policy} 实例，其属性与当前实例具有相同的值，除非是那些由关键字参数给出了新值的属性。
@end deffn

其余的 @ref{adc,,Policy} 方法是由 email 包代码来调用的，而不应当被使用 email 包的应用程序所调用。 自定义的策略必须实现所有这些方法。

@geindex handle_defect() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy handle_defect}@anchor{2966}
@deffn {方法} handle_defect (obj, defect)

处理在 @emph{obj} 上发现的 @emph{defect}。 当 email 包调用此方法时，@emph{defect} 将总是 @code{Defect} 的一个子类。

默认实现会检查 @ref{2964,,raise_on_defect} 旗标。 如果其为 @code{True}，则 @emph{defect} 会被作为异常来引发。 如果其为 @code{False} (默认值)，则 @emph{obj} 和 @emph{defect} 会被传递给 @ref{2965,,register_defect()}。
@end deffn

@geindex register_defect() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy register_defect}@anchor{2965}
@deffn {方法} register_defect (obj, defect)

在 @emph{obj} 上注册一个 @emph{defect}。 在 email 包中，@emph{defect} 将总是 @code{Defect} 的一个子类。

默认实现会调用 @emph{obj} 的 @code{defects} 属性的 @code{append} 方法。 当 email 包调用 @ref{2966,,handle_defect} 时，@emph{obj} 通常将具有一个带 @code{append} 方法的 @code{defects} 属性。 配合 email 包使用的自定义对象类型（例如自定义的 @code{Message} 对象）也应当提供这样的属性，否则在被解析消息中的缺陷将引发非预期的错误。
@end deffn

@geindex header_max_count() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy header_max_count}@anchor{2967}
@deffn {方法} header_max_count (name)

返回名为 @emph{name} 的标头的最大允许数量。

当添加一个标头到 @ref{645,,EmailMessage} 或 @ref{644,,Message} 对象时被调用。 如果返回值不为 @code{0} 或 @code{None}，并且已有的名称为 @emph{name} 的标头数量大于等于所返回的值，则会引发 @ref{16d,,ValueError}。

由于 @code{Message.__setitem__} 的默认行为是将值添加到标头列表，因此很容易不知情地创建重复的标头。 此方法允许在程序中限制可以被添加到 @code{Message} 中的特定标头的实例数量。 （解析器不会考虑此限制，它将忠实地产生被解析消息中存在的任意数量的标头。）

默认实现对于所有标头名称都返回 @code{None}。
@end deffn

@geindex header_source_parse() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy header_source_parse}@anchor{2968}
@deffn {方法} header_source_parse (sourcelines)

email 包调用此方法时将传入一个字符串列表，其中每个字符串以在被解析源中找到的行分隔符结束。 第一行包括字段标头名称和分隔符。 源中的所有空白符都会被保留。 此方法应当返回 @code{(name, value)} 元组以保存至 @code{Message} 中来代表被解析的标头。

如果一个实现希望保持与现有 email 包策略的兼容性，则 @emph{name} 应当为保留大小写形式的名称（所有字符直至 '@code{:}' 分隔符），而 @emph{value} 应当为展开后的值（移除所有行分隔符，但空白符保持不变），并移除开头的空白符。

@emph{sourcelines} 可以包含经替代转义的二进制数据。

此方法没有默认实现
@end deffn

@geindex header_store_parse() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy header_store_parse}@anchor{2969}
@deffn {方法} header_store_parse (name, value)

当一个应用通过程序代码修改 @code{Message} (而不是由解析器创建 @code{Message}) 时，email 包会调用此方法并附带应用程序所提供的名称和值。 此方法应当返回 @code{(name, value)} 元组以保存至 @code{Message} 中用来表示标头。

如果一个实现希望保持与现有 email 包策略的兼容性，则 @emph{name} 和 @emph{value} 应当为字符串或字符串的子类，它们不会修改在参数中传入的内容。

此方法没有默认实现
@end deffn

@geindex header_fetch_parse() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy header_fetch_parse}@anchor{296a}
@deffn {方法} header_fetch_parse (name, value)

当标头被应用程序所请求时，email 包会调用此方法并附带当前保存在 @code{Message} 中的 @emph{name} 和 @emph{value}，并且无论此方法返回什么它都会被回传给应用程序作为被提取标头的值。 请注意可能会有多个相同名称的标头被保存在 @code{Message} 中；此方法会将指定标头的名称和值返回给应用程序。

@emph{value} 可能包含经替代转义的二进制数据。 此方法所返回的值应当没有经替代转义的二进制数据。

此方法没有默认实现
@end deffn

@geindex fold() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy fold}@anchor{296b}
@deffn {方法} fold (name, value)

email 包调用此方法时会附带当前保存在 @code{Message} 中的给定标头的 @emph{name} 和 @emph{value}。 此方法应当返回一个代表该标头的（根据策略设置）通过处理 @emph{name} 和 @emph{value} 并在适当位置插入 @ref{2962,,linesep} 字符来正确地“折叠”的字符串。 请参阅 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 了解有关折叠电子邮件标头的规则的讨论。

@emph{value} 可能包含经替代转义的二进制数据。 此方法所返回的字符串应当没有经替代转义的二进制数据。
@end deffn

@geindex fold_binary() (email.policy.Policy 方法)
@anchor{library/email policy email policy Policy fold_binary}@anchor{2963}
@deffn {方法} fold_binary (name, value)

与 @ref{296b,,fold()} 类似，不同之处在于返回的值应当为字节串对象而非字符串。

@emph{value} 可能包含经替代转义的二进制数据。 这些数据可以在被返回的字节串对象中被转换回二进制数据。
@end deffn
@end deffn

@geindex EmailPolicy (email.policy 中的类)
@anchor{library/email policy email policy EmailPolicy}@anchor{ae0}
@deffn {类} email.policy.EmailPolicy (**kw)

这个实体 @ref{adc,,Policy} 提供了完全遵循当前电子邮件 RFC 的行为。 这包括 (但不限于) 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html}, 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 以及当前的各种 MIME RFC。

此策略添加了新的标头解析和折叠算法。 标头不是简单的字符串，而是带有依赖于字段类型的属性的 @code{str} 的子类。 这个解析和折叠算法完整实现了 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 和 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html}。

@ref{642,,message_factory} 属性的默认值为 @ref{645,,EmailMessage}。

除了上面列出的适用于所有策略的可设置属性，此策略还添加了下列额外属性:


3.6 新版功能: @footnote{@w{(1)} 
最初在 3.3 中作为 @ref{a6a,,暂定特性} 添加。
}


@geindex utf8 (email.policy.EmailPolicy 属性)
@anchor{library/email policy email policy EmailPolicy utf8}@anchor{7cf}
@deffn {属性} utf8

如为 @code{False}，则遵循 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html}，通过编码为“已编码字”来支持标头中的非 ASCII 字符。 如为 @code{True}，则遵循 
@geindex RFC; RFC 6532
RFC 6532@footnote{https://tools.ietf.org/html/rfc6532.html} 并对标头使用 @code{utf-8} 编码格式。 以此方式格式化的消息可被传递给支持 @code{SMTPUTF8} 扩展 (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html}) 的 SMTP 服务器。
@end deffn

@geindex refold_source (email.policy.EmailPolicy 属性)
@anchor{library/email policy email policy EmailPolicy refold_source}@anchor{296c}
@deffn {属性} refold_source

如果 @code{Message} 对象中标头的值源自 @ref{72,,parser} (而非由程序设置)，此属性会表明当将消息转换回序列化形式时是否应当由生成器来重新折叠该值。 可能的值如下:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{none}

@tab

所有源值使用原始折叠

@item

@code{long}

@tab

具有任何长度超过 @code{max_line_length} 的行的源值将被折叠

@item

@code{all}

@tab

所有值会被重新折叠。

@end multitable


默认值为 @code{long}。
@end deffn

@geindex header_factory (email.policy.EmailPolicy 属性)
@anchor{library/email policy email policy EmailPolicy header_factory}@anchor{296d}
@deffn {属性} header_factory

该可调用对象接受两个参数，@code{name} 和 @code{value}，其中 @code{name} 为标头字段名而 @code{value} 为展开后的标头字段值，并返回一个表示该标头的字符串子类。 已提供的默认 @code{header_factory} (参见 @ref{6e,,headerregistry}) 支持对各种地址和日期 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 标头字段类型及主要 MIME 标头字段类型的自定义解析。 未来还将添加对其他自定义解析的支持。
@end deffn

@geindex content_manager (email.policy.EmailPolicy 属性)
@anchor{library/email policy email policy EmailPolicy content_manager}@anchor{93b}
@deffn {属性} content_manager

此对象至少有两个方法: get_content 和 set_content。 当一个 @ref{645,,EmailMessage} 对象的 @ref{2939,,get_content()} 或 @ref{fcc,,set_content()} 方法被调用时，它会调用此对象的相应方法，将消息对象作为其第一个参数，并将传给它的任何参数或关键字作为附加参数传入。 默认情况下 @code{content_manager} 会被设为 @ref{296e,,raw_data_manager}。


3.4 新版功能.

@end deffn

这个类提供了下列对 @ref{adc,,Policy} 的抽象方法的具体实现:

@geindex header_max_count() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy header_max_count}@anchor{296f}
@deffn {方法} header_max_count (name)

返回用来表示具有给定名称的标头的专用类的 @ref{2970,,max_count} 属性的值。
@end deffn

@geindex header_source_parse() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy header_source_parse}@anchor{2971}
@deffn {方法} header_source_parse (sourcelines)

此名称会被作为到 '@code{:}' 止的所有内容来解析。 该值是通过从第一行的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末尾回车符或换行符来确定的。
@end deffn

@geindex header_store_parse() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy header_store_parse}@anchor{2972}
@deffn {方法} header_store_parse (name, value)

name 将会被原样返回。 如果输入值具有 @code{name} 属性并可在忽略大小写的情况下匹配 @emph{name}，则 value 也会被原样返回。 在其他情况下 @emph{name} 和 @emph{value} 会被传递给 @code{header_factory}，并将结果标头对象作为值返回。 在此情况下如果输入值包含 CR 或 LF 字符则会引发 @code{ValueError}。
@end deffn

@geindex header_fetch_parse() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy header_fetch_parse}@anchor{2973}
@deffn {方法} header_fetch_parse (name, value)

如果值具有 @code{name} 属性，它会被原样返回。 在其他情况下 @emph{name} 和移除了所有 CR 和 LF 字符的 @emph{value} 会被传递给 @code{header_factory}，并返回结果标头对象。 任何经替代转义的字节串会被转换为 unicode 未知字符字形。
@end deffn

@geindex fold() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy fold}@anchor{2974}
@deffn {方法} fold (name, value)

标头折叠是由 @ref{296c,,refold_source} 策略设置来控制的。 当且仅当一个值没有 @code{name} 属性（具有 @code{name} 属性就意味着它是某种标头对象）它才会被当作是“源值”。 如果一个原值需要按照策略来重新折叠，则会通过将 @emph{name} 和去除了所有 CR 和 LF 字符的 @emph{value} 传递给 @code{header_factory} 来将其转换为标头对象。 标头对象的折叠是通过调用其 @code{fold} 方法并附带当前策略来完成的。

源值会使用 @ref{17bc,,splitlines()} 来拆分成多行。 如果该值不被重新折叠，则会使用策略中的 @code{linesep} 重新合并这些行并将其返回。 例外的是包含非 ascii 二进制数据的行。 在此情况下无论 @code{refold_source} 如何设置该值都会被重新折叠，这会导致二进制数据使用 @code{unknown-8bit} 字符集进行 CTE 编码。
@end deffn

@geindex fold_binary() (email.policy.EmailPolicy 方法)
@anchor{library/email policy email policy EmailPolicy fold_binary}@anchor{2975}
@deffn {方法} fold_binary (name, value)

如果 @ref{295a,,cte_type} 为 @code{7bit} 则与 @ref{2974,,fold()} 类似，不同之处在于返回的值是字节串。

如果 @ref{295a,,cte_type} 为 @code{8bit}，则将非 ASCII 二进制数据转换回字节串。 带有二进制数据的标头不会被重新折叠，无论 @code{refold_header} 设置如何，因为无法知晓该二进制数据是由单字节字符还是多字节字符组成的。
@end deffn
@end deffn

以下 @ref{ae0,,EmailPolicy} 的实例提供了适用于特定应用领域的默认值。 请注意在未来这些实例（特别是 @code{HTTP} 实例）的行为可能会被调整以便更严格地遵循与其领域相关的 RFC。

@geindex default() (在 email.policy 模块中)
@anchor{library/email policy email policy default}@anchor{290e}
@deffn {数据} email.policy.default

一个未改变任何默认值的 @code{EmailPolicy} 实例。 此策略使用标准的 Python @code{\n} 行结束符而非遵循 RFC 的 @code{\r\n}。
@end deffn

@geindex SMTP() (在 email.policy 模块中)
@anchor{library/email policy email policy SMTP}@anchor{2976}
@deffn {数据} email.policy.SMTP

适用于按照符合电子邮件 RFC 的方式来序列化消息。 与 @code{default} 类似，但 @code{linesep} 被设为遵循 RFC 的 @code{\r\n}。
@end deffn

@geindex SMTPUTF8() (在 email.policy 模块中)
@anchor{library/email policy email policy SMTPUTF8}@anchor{2977}
@deffn {数据} email.policy.SMTPUTF8

与 @code{SMTP} 类似但是 @ref{7cf,,utf8} 为 @code{True}。 适用于在不使用标头内已编码字的情况下对消息进行序列化。 如果发送方或接收方地址具有非 ASCII 字符则应当只被用于 SMTP 传输  (@ref{83e,,smtplib.SMTP.send_message()} 方法会自动如此处理)。
@end deffn

@geindex HTTP() (在 email.policy 模块中)
@anchor{library/email policy email policy HTTP}@anchor{2978}
@deffn {数据} email.policy.HTTP

适用于序列化标头以在 HTTP 通信中使用。 与 @code{SMTP} 类似但是 @code{max_line_length} 被设为 @code{None} (无限制)。
@end deffn

@geindex strict() (在 email.policy 模块中)
@anchor{library/email policy email policy strict}@anchor{2979}
@deffn {数据} email.policy.strict

便捷实例。 与 @code{default} 类似但是 @code{raise_on_defect} 被设为 @code{True}。 这样可以允许通过以下写法来严格地设置任何策略:

@example
somepolicy + policy.strict
@end example
@end deffn

因为所有这些 @ref{ae0,,EmailPolicies}，email 包的高效 API 相比 Python 3.2 API 发生了以下几方面变化:

@quotation


@itemize *

@item 
在 @ref{644,,Message} 中设置标头将使得该标头被解析并创建一个标头对象。

@item 
从 @ref{644,,Message} 提取标头将使得该标头被解析并创建和返回一个标头对象。

@item 
任何标头对象或任何由于策略设置而被重新折叠的标头都会使用一种完全实现了 RFC 折叠算法的算法来进行折叠，包括知道在休息需要并允许已编码字。
@end itemize
@end quotation

从应用程序的视角来看，这意味着任何通过 @ref{645,,EmailMessage} 获得的标头都是具有附加属性的标头对象，其字符串值都是该标头的完全解码后的 unicode 值。 类似地，可以使用 unicode 对象为一个标头赋予新的值，或创建一个新的标头对象，并且该策略将负责把该 unicode 字符串转换为正确的 RFC 已编码形式。

标头对象及其属性的描述见 @ref{6e,,headerregistry}。

@geindex Compat32 (email.policy 中的类)
@anchor{library/email policy email policy Compat32}@anchor{add}
@deffn {类} email.policy.Compat32 (**kw)

这个实体 @ref{adc,,Policy} 为向下兼容策略。 它复制了 Python 3.2 中 email 包的行为。 @ref{73,,policy} 模块还定义了该类的一个实例 @ref{643,,compat32}，用来作为默认策略。 因此 email 包的默认行为会保持与 Python 3.2 的兼容性。

下列属性具有与 @ref{adc,,Policy} 默认值不同的值:

@geindex mangle_from_ (email.policy.Compat32 属性)
@anchor{library/email policy email policy Compat32 mangle_from_}@anchor{297a}
@deffn {属性} mangle_from_

默认值为 @code{True}。
@end deffn

这个类提供了下列对 @ref{adc,,Policy} 的抽象方法的具体实现:

@geindex header_source_parse() (email.policy.Compat32 方法)
@anchor{library/email policy email policy Compat32 header_source_parse}@anchor{297b}
@deffn {方法} header_source_parse (sourcelines)

此名称会被作为到 '@code{:}' 止的所有内容来解析。 该值是通过从第一行的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末尾回车符或换行符来确定的。
@end deffn

@geindex header_store_parse() (email.policy.Compat32 方法)
@anchor{library/email policy email policy Compat32 header_store_parse}@anchor{297c}
@deffn {方法} header_store_parse (name, value)

name 和 value 会被原样返回。
@end deffn

@geindex header_fetch_parse() (email.policy.Compat32 方法)
@anchor{library/email policy email policy Compat32 header_fetch_parse}@anchor{297d}
@deffn {方法} header_fetch_parse (name, value)

如果 value 包含二进制数据，则会使用 @code{unknown-8bit} 字符集来将其转换为 @ref{fce,,Header} 对象。 在其他情况下它会被原样返回。
@end deffn

@geindex fold() (email.policy.Compat32 方法)
@anchor{library/email policy email policy Compat32 fold}@anchor{297e}
@deffn {方法} fold (name, value)

标头会使用 @ref{fce,,Header} 折叠算法进行折叠，该算法保留 value 中现有的换行，并将每个结果行的长度折叠至 @code{max_line_length}。 非 ASCII 二进制数据会使用 @code{unknown-8bit} 字符串进行 CTE 编码。
@end deffn

@geindex fold_binary() (email.policy.Compat32 方法)
@anchor{library/email policy email policy Compat32 fold_binary}@anchor{297f}
@deffn {方法} fold_binary (name, value)

标头会使用 @ref{fce,,Header} 折叠算法进行折叠，该算法保留 value 中现有的换行，并将每个结果行的长度折叠至 @code{max_line_length}。 如果 @code{cte_type} 为 @code{7bit}，则非 ascii 二进制数据会使用 @code{unknown-8bit} 字符集进行 CTE 编码。 在其他情况下则会使用原始的源标头，这将保留其现有的换行和所包含的任何（不符合 RFC 的）二进制数据。
@end deffn
@end deffn

@geindex compat32() (在 email.policy 模块中)
@anchor{library/email policy email policy compat32}@anchor{643}
@deffn {数据} email.policy.compat32

@ref{add,,Compat32} 的实例，提供与 Python 3.2 中的 email 包行为的向下兼容性。
@end deffn

@node email errors 异常和缺陷类,email headerregistry 自定义标头对象,email policy Policy 对象,email --- 电子邮件与 MIME 处理包
@anchor{library/email errors doc}@anchor{2980}@anchor{library/email errors email-errors-exception-and-defect-classes}@anchor{2981}@anchor{library/email errors module-email errors}@anchor{6b}
@subsubsection @code{email.errors}: 异常和缺陷类


@geindex email.errors (模块)

@strong{源代码:} Lib/email/errors.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/errors.py}


__________________________________________________________________


以下异常类在 @ref{6b,,email.errors} 模块中定义：

@geindex MessageError
@anchor{library/email errors email errors MessageError}@anchor{2982}
@deffn {例外} email.errors.MessageError

这是 @ref{67,,email} 包可以引发的所有异常的基类。 它源自标准异常 @ref{2e3,,Exception} 类，这个类没有定义其他方法。
@end deffn

@geindex MessageParseError
@anchor{library/email errors email errors MessageParseError}@anchor{2983}
@deffn {例外} email.errors.MessageParseError

这是由 @ref{bf4,,Parser} 类引发的异常的基类。它派生自 @ref{2982,,MessageError}。 @ref{6e,,headerregistry} 使用的解析器也在内部使用这个类。
@end deffn

@geindex HeaderParseError
@anchor{library/email errors email errors HeaderParseError}@anchor{292f}
@deffn {例外} email.errors.HeaderParseError

在解析消息的 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 标头时，某些错误条件下会触发，此类派生自 @ref{2983,,MessageParseError}。 如果在调用方法时内容类型未知，则 @ref{292e,,set_boundary()} 方法将引发此错误。 当尝试创建一个看起来包含嵌入式标头的标头时 @ref{fce,,Header} 可能会针对某些 base64 解码错误引发此错误（也就是说，应该是一个 没有前导空格并且看起来像标题的延续行）。
@end deffn

@geindex BoundaryError
@anchor{library/email errors email errors BoundaryError}@anchor{2984}
@deffn {例外} email.errors.BoundaryError

已弃用和不再使用的。
@end deffn

@geindex MultipartConversionError
@anchor{library/email errors email errors MultipartConversionError}@anchor{2985}
@deffn {例外} email.errors.MultipartConversionError

当使用 @code{add_payload()} 将有效负载添加到 @ref{644,,Message} 对象时，有效负载已经是一个标量，而消息的 @code{Content-Type} 主类型不是 @code{multipart} 或者缺少时触发该异常。 @ref{2985,,MultipartConversionError} 多重继承自 @ref{2982,,MessageError} 和内置的 @ref{1ff,,TypeError}。

由于 @code{Message.add_payload()} 已被弃用，此异常实际上极少会被引发。 但是如果在派生自 @ref{fa5,,MIMENonMultipart} 的类 (例如 @ref{2986,,MIMEImage}) 的实例上调用 @ref{2940,,attach()} 方法也可以引发此异常。
@end deffn

以下是 @ref{294a,,FeedParser} 在解析消息时可发现的缺陷列表。 请注意这些缺陷会在问题被发现时加入到消息中，因此举例来说，如果某条嵌套在 @code{multipart/alternative} 中的消息具有错误的标头，该嵌套消息对象就会有一条缺陷，但外层消息对象则没有。

所有缺陷类都是 @code{email.errors.MessageDefect} 的子类。


@itemize *

@item 
@code{NoBoundaryInMultipartDefect} -- 一条消息宣称有多个部分，但却没有 @code{boundary} 形参。

@item 
@code{StartBoundaryNotFoundDefect} -- 在 @code{Content-Type} 标头中宣称的开始边界无法被找到。

@item 
@code{CloseBoundaryNotFoundDefect} -- 找到了开始边界，但相应的结束边界无法被找到。


3.3 新版功能.


@item 
@code{FirstHeaderLineIsContinuationDefect} -- 消息以一个继续行作为其第一个标头行。

@item 
@code{MisplacedEnvelopeHeaderDefect} - 在标头块中间发现了一个 "Unix From" 标头。

@item 
@code{MissingHeaderBodySeparatorDefect} - 在解析没有前缀空格但又不包含 ':' 的标头期间找到一行内容。 解析将假定该行表示消息体的第一行以继续执行。


3.3 新版功能.


@item 
@code{MalformedHeaderDefect} -- 找到一个缺失了冒号或格式错误的标头。


3.3 版后已移除: 此缺陷在近几个 Python 版本中已不再使用。


@item 
@code{MultipartInvariantViolationDefect} -- 一条消息宣称为 @code{multipart}，但无法找到任何子部分。 请注意当一条消息有此缺陷时，其 @ref{2933,,is_multipart()} 方法可能返回 @code{False}，即使其内容类型宣称为 @code{multipart}。

@item 
@code{InvalidBase64PaddingDefect} -- 当解码一个 base64 编码的字节分块时，填充的数据不正确。 虽然添加了足够的填充数据以执行解码，但作为结果的已解码字节串可能无效。

@item 
@code{InvalidBase64CharactersDefect} -- 当解码一个 base64 编码的字节分块时，遇到了 base64 字符表以外的字符。 这些字符会被忽略，但作为结果的已解码字节串可能无效。

@item 
@code{InvalidBase64LengthDefect} -- 当解码一个 base64 编码的字节分块时，非填充 base64 字符的数量无效（比 4 的倍数多 1）。 已编码分块会保持原样。
@end itemize

@node email headerregistry 自定义标头对象,email contentmanager 管理 MIME 内容,email errors 异常和缺陷类,email --- 电子邮件与 MIME 处理包
@anchor{library/email headerregistry doc}@anchor{2987}@anchor{library/email headerregistry email-headerregistry-custom-header-objects}@anchor{2988}@anchor{library/email headerregistry module-email headerregistry}@anchor{6e}
@subsubsection @code{email.headerregistry}: 自定义标头对象


@geindex email.headerregistry (模块)

@strong{源代码:} Lib/email/headerregistry.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/headerregistry.py}


__________________________________________________________________



3.6 新版功能: @footnote{@w{(1)} 
最初在 3.3 中作为 @ref{a6a,,暂定模块} 添加
}


标头是由 @ref{206,,str} 的自定义子类来表示的。 用于表示给定标头的特定类则由创建标头时生效的 @ref{73,,policy} 的 @ref{296d,,header_factory} 确定。 这一节记录了 email 包为处理兼容 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 的电子邮件消息所实现的特定 @code{header_factory}，它不仅为各种标头类型提供了自定义的标头对象，还为应用程序提供了添加其自定义标头类型的扩展机制。

当使用派生自 @ref{ae0,,EmailPolicy} 的任何策略对象时，所有标头都通过 @ref{2989,,HeaderRegistry} 产生并且以 @ref{291c,,BaseHeader} 作为其最后一个基类。 每个标头类都有一个由该标头类型确定的附加基类。 例如，许多标头都以 @ref{298a,,UnstructuredHeader} 类作为其另一个基类。 一个标头专用的第二个类是由标头名称使用存储在 @ref{2989,,HeaderRegistry} 中的查找表来确定的。 所有这些都针对典型应用程序进行透明的管理，但也为修改默认行为提供了接口，以便由更复杂的应用使用。

以下各节首先记录了标头基类及其属性，然后是用于修改 @ref{2989,,HeaderRegistry} 行为的 API，最后是用于表示从结构化标头解析的数据的支持类。

@geindex BaseHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry BaseHeader}@anchor{291c}
@deffn {类} email.headerregistry.BaseHeader (name, value)

@emph{name} 和 @emph{value} 会从 @ref{296d,,header_factory} 调用传递给 @code{BaseHeader}。 任何标头对象的字符串值都是完成解码为 unicode 的 @emph{value}。

这个基类定义了下列只读属性:

@geindex name (email.headerregistry.BaseHeader 属性)
@anchor{library/email headerregistry email headerregistry BaseHeader name}@anchor{298b}
@deffn {属性} name

标头的名称（字段在 ':' 之前的部分）。 这就是 @emph{name} 的 @ref{296d,,header_factory} 调用所传递的值；也就是说会保持大小写形式。
@end deffn

@geindex defects (email.headerregistry.BaseHeader 属性)
@anchor{library/email headerregistry email headerregistry BaseHeader defects}@anchor{298c}
@deffn {属性} defects

一个包含 @code{HeaderDefect} 实例的元组，这些实例报告了在解析期间发现的任何 RFC 合规性问题。 email 包会尝试尽可能地检测合规性问题。 请参阅 @ref{6b,,errors} 模块了解可能被报告的缺陷类型的相关讨论。
@end deffn

@geindex max_count (email.headerregistry.BaseHeader 属性)
@anchor{library/email headerregistry email headerregistry BaseHeader max_count}@anchor{2970}
@deffn {属性} max_count

此类型标头可具有相同 @code{name} 的最大数量。 @code{None} 值表示无限制。 此属性的 @code{BaseHeader} 值为 @code{None}；专用的标头类预期将根据需要重载这个值。
@end deffn

@code{BaseHeader} 还提供了以下方法，它由 email 库代码调用，通常不应当由应用程序来调用。

@geindex fold() (email.headerregistry.BaseHeader 方法)
@anchor{library/email headerregistry email headerregistry BaseHeader fold}@anchor{298d}
@deffn {方法} fold (*, policy)

返回一个字符串，其中包含用来根据 @emph{policy} 正确地折叠标头的 @ref{2962,,linesep} 字符。  @ref{295a,,cte_type} 为 @code{8bit} 时将被作为 @code{7bit} 来处理，因为标头不能包含任意二进制数据。 如果 @ref{7cf,,utf8} 为 @code{False}，则非 ASCII 数据将根据 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 来编码。
@end deffn

@code{BaseHeader} 本身不能被用于创建标头对象。 它定义了一个与每个专用标头相配合的协议以便生成标头对象。 具体来说，@code{BaseHeader} 要求专用类提供一个名为 @code{parse} 的 @ref{310,,classmethod()}。 此方法的调用形式如下:

@example
parse(string, kwds)
@end example

@code{kwds} 是包含了一个预初始化键 @code{defects} 的字典。 @code{defects} 是一个空列表。 parse 方法应当将任何已检测到的缺陷添加到此列表中。 在返回时，@code{kwds} 字典 @emph{必须} 至少包含 @code{decoded} 和 @code{defects} 等键的值。 @code{decoded} 应当是标头的字符串值（即完全解码为 unicode 的标头值）。 parse 方法应当假定 @emph{string} 可能包含 content-transfer-encoded 部分，但也应当正确地处理全部有效的 unicode 字符以便它能解析未经编码的标头值。

随后 @code{BaseHeader} 的 @code{__new__} 会创建标头实例，并调用其 @code{init} 方法。 专属类如果想要设置 @code{BaseHeader} 自身所提供的属性之外的附加属性，只需提供一个 @code{init} 方法。 这样的 @code{init} 看起来应该是这样:

@example
def init(self, /, *args, **kw):
    self._myattr = kw.pop('myattr')
    super().init(*args, **kw)
@end example

也就是说，专属类放入 @code{kwds} 字典的任何额外内容都应当被移除和处理，并且 @code{kw} (和 @code{args}) 的剩余内容会被传递给 @code{BaseHeader} @code{init} 方法。
@end deffn

@geindex UnstructuredHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry UnstructuredHeader}@anchor{298a}
@deffn {类} email.headerregistry.UnstructuredHeader

"非结构化" 标头是 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 中默认的标头类型。 任何没有指定语法的标头都会被视为是非结构化的。 非结构化标头的经典例子是 @code{Subject} 标头。

在 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 中，非结构化标头是指一段以 ASCII 字符集表示的任意文本。 但是 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 具有一个 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 兼容机制用来将标头值中的非 ASCII 文本编码为 ASCII 字符。 当包含已编码字的 @emph{value} 被传递给构造器时，@code{UnstructuredHeader} 解析器会按照非结构化文本的 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 规则将此类已编码字转换为 unicode。 解析器会使用启发式机制来尝试解码一些不合规的已编码字。 在此种情况下各类缺陷，例如已编码字或未编码文本中的无效字符问题等缺陷将会被注册。

此标头类型未提供附加属性。
@end deffn

@geindex DateHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry DateHeader}@anchor{298e}
@deffn {类} email.headerregistry.DateHeader

@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 为电子邮件标头内的日期指定了非常明确的格式。 @code{DateHeader} 解析器会识别该日期格式，并且也能识别间或出现的一些“不规范”变种形式。

这个标头类型提供了以下附加属性。

@geindex datetime (email.headerregistry.DateHeader 属性)
@anchor{library/email headerregistry email headerregistry DateHeader datetime}@anchor{298f}
@deffn {属性} datetime

如果标头值能被识别为某一种有效的日期形式，此属性将包含一个代表该日期的 @ref{19f,,datetime} 实例。 如果输入日期的时区被指定为 @code{-0000} (表示为 UTC 但不包含源时区的相关信息)，则 @ref{298f,,datetime} 将为简单型 @ref{19f,,datetime}。 如果找到了特定的时区时差值 (包括 @cite{+0000})，则 @ref{298f,,datetime} 将包含使用 @ref{ae9,,datetime.timezone} 来记录时区时差时的感知型 @code{datetime}。
@end deffn

标头的 @code{decoded} 值是由按照 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 对 @code{datetime} 进行格式化来确定的；也就是说，它会被设为:

@example
email.utils.format_datetime(self.datetime)
@end example

当创建 @code{DateHeader} 时，@emph{value} 可以为 @ref{19f,,datetime} 实例。 例如这意味着以下代码是有效的并能实现人们预期的行为:

@example
msg['Date'] = datetime(2011, 7, 15, 21)
@end example

因为这是个简单型 @code{datetime} 它将被解读为 UTC 时间戳，并且结果值的时区将为 @code{-0000}。 使用来自 @ref{74,,utils} 模块的 @ref{ae8,,localtime()} 函数会更有用:

@example
msg['Date'] = utils.localtime()
@end example

这个例子将日期标头设为使用当前时区时差值的当前时间和日期。
@end deffn

@geindex AddressHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry AddressHeader}@anchor{2990}
@deffn {类} email.headerregistry.AddressHeader

地址标头是最复杂的结构化标头类型之一。 @code{AddressHeader} 类提供了适合任何地址标头的泛用型接口。

这个标头类型提供了以下附加属性。

@geindex groups (email.headerregistry.AddressHeader 属性)
@anchor{library/email headerregistry email headerregistry AddressHeader groups}@anchor{2991}
@deffn {属性} groups

编码了在标头值中找到的地址和分组的 @ref{2992,,Group} 对象的元组。 非分组成员的地址在此列表中表示为 @ref{2993,,display_name} 为 @code{None} 的单地址 @code{Groups}。
@end deffn

@geindex addresses (email.headerregistry.AddressHeader 属性)
@anchor{library/email headerregistry email headerregistry AddressHeader addresses}@anchor{2994}
@deffn {属性} addresses

编码了来自标头值的所有单独地址的 @ref{2995,,Address} 对象的元组。 如果标头值包含任何分组，则来自分组的单个地址将包含在该分组出现在值中的点上列出（也就是说，地址列表会被“展平”为一维列表）。
@end deffn

标头的 @code{decoded} 值将为所有已编码字解码为 unicode 的结果。   @ref{75,,idna} 编码的域名也将被解码为 unicode。 @code{decoded} 值是通过对 @code{groups} 属性的元素的 @ref{206,,str} 值使用 @code{', '} 进行 @ref{1796,,join} 来设置的。

可以使用 @ref{2995,,Address} 与 @ref{2992,,Group} 对象的任意组合的列表来设置一个地址标头的值。 @code{display_name} 为 @code{None} 的 @code{Group} 对象将被解读为单独地址，这允许一个地址列表可以附带通过使用从源标头的 @code{groups} 属性获取的列表而保留原分组。
@end deffn

@geindex SingleAddressHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry SingleAddressHeader}@anchor{2996}
@deffn {类} email.headerregistry.SingleAddressHeader

@ref{2990,,AddressHeader} 的子类，添加了一个额外的属性:

@geindex address (email.headerregistry.SingleAddressHeader 属性)
@anchor{library/email headerregistry email headerregistry SingleAddressHeader address}@anchor{2997}
@deffn {属性} address

由标头值编码的单个地址。 如果标头值实际上包含一个以上的地址（这在默认 @ref{73,,policy} 下将违反 RFC），则访问此属性将导致 @ref{16d,,ValueError}。
@end deffn
@end deffn

上述类中许多还具有一个 @code{Unique} 变体 (例如 @code{UniqueUnstructuredHeader})。 其唯一差别是在 @code{Unique} 变体中 @ref{2970,,max_count} 被设为 1。

@geindex MIMEVersionHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader}@anchor{2998}
@deffn {类} email.headerregistry.MIMEVersionHeader

实际上 @code{MIME-Version} 标头只有一个有效的值，即 @code{1.0}。 为了将来的扩展，这个标头类还支持其他的有效版本号。 如果一个版本号是 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 的有效值，则标头对象的以下属性将具有不为 @code{None} 的值:

@geindex version (email.headerregistry.MIMEVersionHeader 属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader version}@anchor{2999}
@deffn {属性} version

字符串形式的版本号。 任何空格和/或注释都会被移除。
@end deffn

@geindex major (email.headerregistry.MIMEVersionHeader 属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader major}@anchor{299a}
@deffn {属性} major

整数形式的主版本号
@end deffn

@geindex minor (email.headerregistry.MIMEVersionHeader 属性)
@anchor{library/email headerregistry email headerregistry MIMEVersionHeader minor}@anchor{299b}
@deffn {属性} minor

整数形式的次版本号
@end deffn
@end deffn

@geindex ParameterizedMIMEHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry ParameterizedMIMEHeader}@anchor{299c}
@deffn {类} email.headerregistry.ParameterizedMIMEHeader

MIME 标头都以前缀 'Content-' 打头。 每个特定标头都具有特定的值，其描述在该标头的类之中。 有些也可以接受一个具有通用格式的补充形参形表。 这个类被用作所有接受形参的 MIME 标头的基类。

@geindex params (email.headerregistry.ParameterizedMIMEHeader 属性)
@anchor{library/email headerregistry email headerregistry ParameterizedMIMEHeader params}@anchor{299d}
@deffn {属性} params

一个将形参名映射到形参值的字典。
@end deffn
@end deffn

@geindex ContentTypeHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader}@anchor{299e}
@deffn {类} email.headerregistry.ContentTypeHeader

处理 @code{Content-Type} 标头的  @ref{299c,,ParameterizedMIMEHeader} 类。

@geindex content_type (email.headerregistry.ContentTypeHeader 属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader content_type}@anchor{299f}
@deffn {属性} content_type

@code{maintype/subtype} 形式的内容类型字符串。
@end deffn

@geindex maintype (email.headerregistry.ContentTypeHeader 属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader maintype}@anchor{29a0}
@deffn {属性} maintype
@end deffn

@geindex subtype (email.headerregistry.ContentTypeHeader 属性)
@anchor{library/email headerregistry email headerregistry ContentTypeHeader subtype}@anchor{29a1}
@deffn {属性} subtype
@end deffn
@end deffn

@geindex ContentDispositionHeader (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry ContentDispositionHeader}@anchor{29a2}
@deffn {类} email.headerregistry.ContentDispositionHeader

处理 @code{Content-Disposition} 标头的 @ref{299c,,ParameterizedMIMEHeader} 类。

@geindex content_disposition (email.headerregistry.ContentDispositionHeader 属性)
@anchor{library/email headerregistry email headerregistry ContentDispositionHeader content_disposition}@anchor{29a3}
@deffn {属性} content_disposition

@code{inline} 和 @code{attachment} 是仅有的常用有效值。
@end deffn
@end deffn

@geindex ContentTransferEncoding (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry ContentTransferEncoding}@anchor{29a4}
@deffn {类} email.headerregistry.ContentTransferEncoding

处理 @code{Content-Transfer-Encoding} 标头。

@geindex cte (email.headerregistry.ContentTransferEncoding 属性)
@anchor{library/email headerregistry email headerregistry ContentTransferEncoding cte}@anchor{29a5}
@deffn {属性} cte

可用的有效值为 @code{7bit}, @code{8bit}, @code{base64} 和 @code{quoted-printable}。 更多信息请参阅 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html}。
@end deffn
@end deffn

@geindex HeaderRegistry (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry HeaderRegistry}@anchor{2989}
@deffn {类} email.headerregistry.HeaderRegistry (base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)

这是由 @ref{ae0,,EmailPolicy} 在默认情况下使用的工厂函数。 @code{HeaderRegistry} 会使用 @emph{base_class} 和从它所保存的注册表中获取的专用类来构建用于动态地创建标头实例的类。 当给定的标头名称未在注册表中出现时，则会使用由 @emph{default_class} 所指定的类作为专用类。 当 @emph{use_default_map} 为 @code{True} (默认值) 时，则会在初始化期间把将标头名称与类的标准映射拷贝到注册表中。  @emph{base_class} 始终会是所生成类的 @code{__bases__} 列表中的最后一个类。

默认的映射有:

@quotation

@*subject: 
UniqueUnstructuredHeader


@*date: 
UniqueDateHeader


@*resent-date: 
DateHeader


@*orig-date: 
UniqueDateHeader


@*sender: 
UniqueSingleAddressHeader


@*resent-sender: 
SingleAddressHeader


@*到: 
UniqueAddressHeader


@*resent-to: 
AddressHeader


@*cc: 
UniqueAddressHeader


@*resent-cc: 
AddressHeader


@*bcc: 
UniqueAddressHeader


@*resent-bcc: 
AddressHeader


@*从: 
UniqueAddressHeader


@*resent-from: 
AddressHeader


@*reply-to: 
UniqueAddressHeader


@*mime-version: 
MIMEVersionHeader


@*content-type: 
ContentTypeHeader


@*content-disposition: 
ContentDispositionHeader


@*content-transfer-encoding: 
ContentTransferEncodingHeader


@*message-id: 
MessageIDHeader

@end quotation

@code{HeaderRegistry} 具有下列方法:

@geindex map_to_type() (email.headerregistry.HeaderRegistry 方法)
@anchor{library/email headerregistry email headerregistry HeaderRegistry map_to_type}@anchor{29a6}
@deffn {方法} map_to_type (self, name, cls)

@emph{name} 是要映射的标头名称。 它将在注册表中被转换为小写形式。 @emph{cls} 是要与 @emph{base_class} 一起被用来创建用于实例化与 @emph{name} 相匹配的标头的类的专用类。
@end deffn

@geindex __getitem__() (email.headerregistry.HeaderRegistry 方法)
@anchor{library/email headerregistry email headerregistry HeaderRegistry __getitem__}@anchor{29a7}
@deffn {方法} __getitem__ (name)

构造并返回一个类来处理 @emph{name} 标头的创建。
@end deffn

@geindex __call__() (email.headerregistry.HeaderRegistry 方法)
@anchor{library/email headerregistry email headerregistry HeaderRegistry __call__}@anchor{29a8}
@deffn {方法} __call__ (name, value)

从注册表获得与 @emph{name} 相关联的专用标头 (如果 @emph{name} 未在注册表中出现则使用 @emph{default_class}) 并将其与 @emph{base_class} 相组合以产生类，调用被构造类的构造器，传入相同的参数列表，并最终返回由此创建的类实例。
@end deffn
@end deffn

以下的类是用于表示从结构化标头解析的数据的类，并且通常会由应用程序使用以构造结构化的值并赋给特定的标头。

@geindex Address (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry Address}@anchor{2995}
@deffn {类} email.headerregistry.Address (display_name='@w{'}, username='@w{'}, domain='@w{'}, addr_spec=None)

用于表示电子邮件地址的类。 地址的一般形式为:

@example
[display_name] <username@@domain>
@end example

或者：

@example
username@@domain
@end example

其中每个部分都必须符合在 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 中阐述的特定语法规则。

为了方便起见可以指定 @emph{addr_spec} 来替代 @emph{username} 和 @emph{domain}，在此情况下 @emph{username} 和 @emph{domain} 将从 @emph{addr_spec} 中解析。 @emph{addr_spec} 应当是一个正确地引用了 RFC 的字符串；如果它不是 @code{Address} 则将引发错误。 Unicode 字符也允许使用并将在序列化时被正确地编码。 但是，根据 RFC，地址的 username 部分 @emph{不允许} 有 unicode。

@geindex display_name (email.headerregistry.Address 属性)
@anchor{library/email headerregistry email headerregistry Address display_name}@anchor{29a9}
@deffn {属性} display_name

地址的显示名称部分（如果有的话）并去除所有引用项。 如果地址没有显示名称，则此属性将为空字符串。
@end deffn

@geindex username (email.headerregistry.Address 属性)
@anchor{library/email headerregistry email headerregistry Address username}@anchor{29aa}
@deffn {属性} username

地址的 @code{username} 部分，去除所有引用项。
@end deffn

@geindex domain (email.headerregistry.Address 属性)
@anchor{library/email headerregistry email headerregistry Address domain}@anchor{29ab}
@deffn {属性} domain

地址的 @code{domain} 部分。
@end deffn

@geindex addr_spec (email.headerregistry.Address 属性)
@anchor{library/email headerregistry email headerregistry Address addr_spec}@anchor{29ac}
@deffn {属性} addr_spec

地址的 @code{username@@domain} 部分，经过正确引用处理以作为纯地址使用（上面显示的第二种形式）。 此属性不可变。
@end deffn

@geindex __str__() (email.headerregistry.Address 方法)
@anchor{library/email headerregistry email headerregistry Address __str__}@anchor{29ad}
@deffn {方法} __str__ ()

对象的 @code{str} 值是根据 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 规则进行引用处理的地址，但不带任何非 ASCII 字符的 Content Transfer Encoding。
@end deffn

为了支持 SMTP (
@geindex RFC; RFC 5321
RFC 5321@footnote{https://tools.ietf.org/html/rfc5321.html})，@code{Address} 会处理一种特殊情况：如果 @code{username} 和 @code{domain} 均为空字符串 (或为 @code{None})，则 @code{Address} 的字符串值为 @code{<>}。
@end deffn

@geindex Group (email.headerregistry 中的类)
@anchor{library/email headerregistry email headerregistry Group}@anchor{2992}
@deffn {类} email.headerregistry.Group (display_name=None, addresses=None)

用于表示地址组的类。 地址组的一般形式为:

@example
display_name: [address-list];
@end example

作为处理由组和单个地址混合构成的列表的便捷方式，@code{Group} 也可以通过将 @emph{display_name} 设为 @code{None} 以用来表示不是某个组的一部分的单独地址并提供单独地址的列表作为 @emph{addresses}。

@geindex display_name (email.headerregistry.Group 属性)
@anchor{library/email headerregistry email headerregistry Group display_name}@anchor{2993}
@deffn {属性} display_name

组的 @code{display_name}。 如果其为 @code{None} 并且恰好有一个 @code{Address} 在 @code{addresses} 中，则 @code{Group} 表示一个不在某个组中的单独地址。
@end deffn

@geindex addresses (email.headerregistry.Group 属性)
@anchor{library/email headerregistry email headerregistry Group addresses}@anchor{29ae}
@deffn {属性} addresses

一个可能为空的表示组中地址的包含 @ref{2995,,Address} 对象的元组。
@end deffn

@geindex __str__() (email.headerregistry.Group 方法)
@anchor{library/email headerregistry email headerregistry Group __str__}@anchor{29af}
@deffn {方法} __str__ ()

@code{Group} 的 @code{str} 值会根据 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 进行格式化，但不带任何非 ASCII 字符的 Content Transfer Encoding。 如果 @code{display_name} 为空值且只有一个单独 @code{Address} 在 @code{addresses} 列表中，则 @code{str} 值将与该单独 @code{Address} 的 @code{str} 相同。
@end deffn
@end deffn

@node email contentmanager 管理 MIME 内容,email 示例,email headerregistry 自定义标头对象,email --- 电子邮件与 MIME 处理包
@anchor{library/email contentmanager doc}@anchor{29b0}@anchor{library/email contentmanager email-contentmanager-managing-mime-content}@anchor{29b1}@anchor{library/email contentmanager module-email contentmanager}@anchor{69}
@subsubsection @code{email.contentmanager}: 管理 MIME 内容


@geindex email.contentmanager (模块)

@strong{源代码:} Lib/email/contentmanager.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/contentmanager.py}


__________________________________________________________________



3.6 新版功能: @footnote{@w{(1)} 
最初在 3.4 中作为 @ref{a6a,,暂定模块} 添加
}


@geindex ContentManager (email.contentmanager 中的类)
@anchor{library/email contentmanager email contentmanager ContentManager}@anchor{29b2}
@deffn {类} email.contentmanager.ContentManager

内容管理器的基类。 提供注册 MIME 内容和其他表示形式间转换器的标准注册机制，以及 @code{get_content} 和 @code{set_content} 发送方法。

@geindex get_content() (email.contentmanager.ContentManager 方法)
@anchor{library/email contentmanager email contentmanager ContentManager get_content}@anchor{293a}
@deffn {方法} get_content (msg, *args, **kw)

基于 @emph{msg} 的 @code{mimetype} 查找处理函数（参见下一段），调用该函数，传递所有参数，并返回调用的结果。 预期的效果是处理程序将从 @emph{msg} 中提取有效载荷并返回编码了有关被提取数据信息的对象。

要找到处理程序，将在注册表中查找以下键，找到第一个键即停止:

@quotation


@itemize *

@item 
表示完整 MIME 类型的字符串 (@code{maintype/subtype})

@item 
表示 @code{maintype} 的字符串

@item 
空字符串
@end itemize
@end quotation

如果这些键都没有产生处理程序，则为完整 MIME 类型引发一个 @ref{3f1,,KeyError}。
@end deffn

@geindex set_content() (email.contentmanager.ContentManager 方法)
@anchor{library/email contentmanager email contentmanager ContentManager set_content}@anchor{293b}
@deffn {方法} set_content (msg, obj, *args, **kw)

如果 @code{maintype} 为 @code{multipart}，则引发 @ref{1ff,,TypeError}；否则基于 @emph{obj} 的类型（参见下一段）查找处理函数，在 @emph{msg} 上调用 @ref{2944,,clear_content()}，并调用处理函数，传递所有参数。 预期的效果是处理程序将转换 @emph{obj} 并存入 @emph{msg}，并可能对 @emph{msg} 进行其他更改，例如添加各种 MIME 标头来编码需要用来解释所存储数据的信息。

要找到处理程序，将获取 @emph{obj} 的类型 (@code{typ = type(obj)})，并在注册表中查找以下键，找到第一个键即停止:

@quotation


@itemize *

@item 
类型本身 (@code{typ})

@item 
类型的完整限定名称 (@code{typ.__module__ + '.' + typ.__qualname__})。

@item 
类型的 qualname (@code{typ.__qualname__})

@item 
类型的 name (@code{typ.__name__})。
@end itemize
@end quotation

如果未匹配到上述的任何一项，则在 @ref{29b3,,MRO} (@code{typ.__mro__}) 中为每个类型重复上述的所有检测。 最后，如果没有其他键产生处理程序，则为 @code{None} 键检测处理程序。 如果也没有 @code{None} 的处理程序，则为该类型的完整限定名称引发 @ref{3f1,,KeyError}。

并会添加一个 @code{MIME-Version} 标头，如果没有的话 (另请参见 @ref{93a,,MIMEPart})。
@end deffn

@geindex add_get_handler() (email.contentmanager.ContentManager 方法)
@anchor{library/email contentmanager email contentmanager ContentManager add_get_handler}@anchor{29b4}
@deffn {方法} add_get_handler (key, handler)

将 @emph{handler} 函数记录为 @emph{key} 的处理程序。 对于可能的 @emph{key} 键，请参阅 @ref{29b5,,get_content()}。
@end deffn

@geindex add_set_handler() (email.contentmanager.ContentManager 方法)
@anchor{library/email contentmanager email contentmanager ContentManager add_set_handler}@anchor{29b6}
@deffn {方法} add_set_handler (typekey, handler)

将 @emph{handler} 记录为当一个匹配 @emph{typekey} 的类型对象被传递给 @ref{29b7,,set_content()} 时所要调用的函数。 对于可能的 @emph{typekey} 值，请参阅 @ref{29b7,,set_content()}。
@end deffn
@end deffn

@menu
* 内容管理器实例:: 

@end menu

@node 内容管理器实例,,,email contentmanager 管理 MIME 内容
@anchor{library/email contentmanager content-manager-instances}@anchor{29b8}
@subsubsection 内容管理器实例


目前 email 包只提供了一个实体内容管理器 @ref{296e,,raw_data_manager}，不过在未来可能会添加更多。 @ref{296e,,raw_data_manager} 是由 @ref{ae0,,EmailPolicy} 及其衍生工具所提供的 @ref{93b,,content_manager}。

@geindex raw_data_manager() (在 email.contentmanager 模块中)
@anchor{library/email contentmanager email contentmanager raw_data_manager}@anchor{296e}
@deffn {数据} email.contentmanager.raw_data_manager

这个内容管理器仅提供了超出 @ref{644,,Message} 本身提供内容的最小接口：它只处理文本、原始字节串和 @ref{644,,Message} 对象。 不过相比基础 API，它具有显著的优势：在文本部分上执行 @code{get_content} 将返回一个 unicode 字符串而无需由应用程序来手动解码，@code{set_content} 为控制添加到一个部分的标头和控制内容传输编码格式提供了丰富的选项集合，并且它还启用了多种 @code{add_} 方法，从而简化了多部分消息的创建过程。

@geindex get_content() (在 email.contentmanager 模块中)
@anchor{library/email contentmanager email contentmanager get_content}@anchor{29b5}
@deffn {方法} email.contentmanager.get_content (msg, errors='replace')

将指定部分的有效载荷作为字符串（对于 @code{text} 部分）, @ref{645,,EmailMessage} 对象（对于 @code{message/rfc822} 部分）或 @code{bytes} 对象（对于所有其他非多部分类型）返回。 如果是在 @code{multipart} 上调用则会引发 @ref{3f1,,KeyError}。 如果指定部分是一个 @code{text} 部分并且指明了 @emph{errors}，则会在将载荷解码为 unicode 时将其用作错误处理程序。 默认的错误处理程序是 @code{replace}。
@end deffn

@geindex set_content() (在 email.contentmanager 模块中)
@anchor{library/email contentmanager email contentmanager set_content}@anchor{29b7}
@deffn {方法} email.contentmanager.set_content (msg, <'str'>, subtype="plain", charset='utf-8', cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

@deffnx {方法} email.contentmanager.set_content (msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None)

@deffnx {方法} email.contentmanager.set_content (msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

向 @emph{msg} 添加标头和有效载荷:

添加一个带有 @code{maintype/subtype} 值的 @code{Content-Type} 标头。

@quotation


@itemize *

@item 
对于 @code{str}，将 MIME @code{maintype} 设为 @code{text}，如果指定了子类型 @emph{subtype} 则设为指定值，否则设为 @code{plain}。

@item 
对于 @code{bytes}，将使用指定的 @emph{maintype} 和 @emph{subtype}，如果未指定则会引发 @ref{1ff,,TypeError}。

@item 
对于 @ref{645,,EmailMessage} 对象，将 maintype 设为 @code{message}，并将指定的 subtype 设为 @emph{subtype}，如果未指定则设为 @code{rfc822}。 如果 @emph{subtype} 为 @code{partial}，则引发一个错误（必须使用 @code{bytes} 对象来构造 @code{message/partial} 部分）。
@end itemize
@end quotation

如果提供了 @emph{charset} (这只对 @code{str} 适用)，则使用指定的字符集将字符串编码为字节串。 默认值为 @code{utf-8}。 如果指定的 @emph{charset} 是某个标准 MIME 字符集名称的已知别名，则会改用该标准字符集。

如果设置了 @emph{cte}，则使用指定的内容传输编码格式对有效载荷进行编码，并将 @code{Content-Transfer-Encoding} 标头设为该值。 可能的 @emph{cte} 值有 @code{quoted-printable}, @code{base64}, @code{7bit}, @code{8bit} 和 @code{binary}。 如果输入无法以指定的编码格式被编码 (例如，对于包含非 ASCII 值的输入指定 @emph{cte} 值为 @code{7bit})，则会引发 @ref{16d,,ValueError}。

@quotation


@itemize *

@item 
对于 @code{str} 对象，如果 @emph{cte} 未设置则会使用启发方式来确定最紧凑的编码格式。

@item 
对于 @ref{645,,EmailMessage}，按照 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://tools.ietf.org/html/rfc2046.html}，如果为 @emph{subtype} @code{rfc822} 请求的 @emph{cte} 为 @code{quoted-printable} 或 @code{base64} ，而为 @code{7bit} 以外的任何 @emph{cte} 为 @emph{subtype} @code{external-body} 则会引发一个错误。 对于 @code{message/rfc822}，如果 @emph{cte} 未指定则会使用 @code{8bit}。 对于所有其他 @emph{subtype} 值，都会使用 @code{7bit}。
@end itemize
@end quotation

@cartouche
@quotation 注解 
@emph{cte} 值为 @code{binary} 实际上还不能正确工作。 由 @code{set_content} 所修改的 @code{EmailMessage} 对象是正确的，但 @ref{c28,,BytesGenerator} 不会正确地将其序列化。
@end quotation
@end cartouche

如果设置了 @emph{disposition}，它会被用作 @code{Content-Disposition} 标头的值。 如果未设置，并且指定了 @emph{filename}，则添加值为 @code{attachment} 的标头。 如果未设置 @emph{disposition} 并且也未指定 @emph{filename}，则不添加标头。 @emph{disposition} 的有效值仅有 @code{attachment} 和 @code{inline}。

如果设置了 @emph{filename}，则将其用作 @code{Content-Disposition} 标头的 @code{filename} 参数的值。

如果设置了 @emph{cid}，则添加一个 @code{Content-ID} 标头并将其值设为 @emph{cid}。

如果设置了 @emph{params}，则迭代其 @code{items} 方法并使用输出的 @code{(key, value)} 结果对在 @code{Content-Type} 标头上设置附加参数。

如果设置了 @emph{headers} 并且为 @code{headername: headervalue} 形式的字符串的列表或为 @code{header} 对象的列表（通过一个 @code{name} 属性与字符串相区分），则将标头添加到 @emph{msg}。
@end deffn
@end deffn

@node email 示例,email message Message 使用 compat32 API 来表示电子邮件消息,email contentmanager 管理 MIME 内容,email --- 电子邮件与 MIME 处理包
@anchor{library/email examples doc}@anchor{29b9}@anchor{library/email examples email-examples}@anchor{93c}@anchor{library/email examples id1}@anchor{29ba}
@subsubsection @code{email}: 示例


以下是一些如何使用 @ref{67,,email} 包来读取、写入和发送简单电子邮件以及更复杂的MIME邮件的示例。

首先，让我们看看如何创建和发送简单的文本消息（文本内容和地址都可能包含unicode字符）：

@example
# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of @{textfile@}'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
@end example

解析 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 标题可以通过使用 @ref{72,,parser} 模块中的类来轻松完成：

@example
# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@@example.com>\n'
        'To: <someone_else@@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: @{@}'.format(headers['to']))
print('From: @{@}'.format(headers['from']))
print('Subject: @{@}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: @{@}'.format(headers['to'].addresses[0].username))
print('Sender name: @{@}'.format(headers['from'].addresses[0].display_name))
@end example

以下是如何发送包含可能在目录中的一系列家庭照片的MIME消息示例：

@example
# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
@end example

以下是如何将目录的全部内容作为电子邮件消息发送的示例： @footnote{@w{(1)} 
感谢 Matthew Dixon Cowles 提供最初的灵感和示例。
}

@example
#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = f'Contents of directory @{os.path.abspath(directory)@}'
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
@end example

以下是如何将上述MIME消息解压缩到文件目录中的示例：

@example
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = f'part-@{counter:03d@}@{ext@}'
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()
@end example

以下是如何使用备用纯文本版本创建 HTML 消息的示例。 为了让事情变得更有趣，我们在 html 部分中包含了一个相关的图像，我们保存了一份我们要发送的内容到硬盘中，然后发送它。

@example
#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:@{asparagus_cid@}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
@end example

如果我们发送最后一个示例中的消息，这是我们可以处理它的一种方法：

@example
import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print('@w{'}.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = @{@}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display @{@}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display @{@}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.
@end example

直到输出提示，上面的输出是：

@example
To: Penelope Pussycat <penelope@@example.com>, Fabrette Pussycat <fabrette@@example.com>
From: Pepé Le Pew <pepe@@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.
@end example

旧式 API:

@node email message Message 使用 compat32 API 来表示电子邮件消息,email mime 从头创建电子邮件和 MIME 对象,email 示例,email --- 电子邮件与 MIME 处理包
@anchor{library/email compat32-message doc}@anchor{29bb}@anchor{library/email compat32-message compat32-message}@anchor{290d}@anchor{library/email compat32-message email-message-message-representing-an-email-message-using-the-compat32-api}@anchor{29bc}
@subsubsection @code{email.message.Message}: 使用 @code{compat32} API 来表示电子邮件消息


@ref{644,,Message} 类与 @ref{645,,EmailMessage} 类非常相似，但没有该类所添加的方法，并且某些方法的默认行为也略有不同。 我们还在这里记录了一些虽然被 @ref{645,,EmailMessage} 类所支持但并不推荐的方法，除非你是在处理旧有代码。

在其他情况下这两个类的理念和结构都是相同的。

本文档描述了默认 (对于 @ref{644,,Message}) 策略 @ref{add,,Compat32} 之下的行为。 如果你要使用其他策略，你应当改用 @ref{645,,EmailMessage} 类。

电子邮件消息由多个 @emph{标头} 和一个 @emph{载荷} 组成。 标头必须为 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html} 风格的名称和值，其中字典名和值由冒号分隔。 冒号不是字段名或字段值的组成部分。 载荷可以是简单的文本消息，或是二进制对象，或是多个子消息的结构化序列，每个子消息都有自己的标头集合和自己的载荷。 后一种类型的载荷是由具有 @code{multipart/*} 或 @code{message/rfc822} 等 MIME 类型的消息来指明的。

@ref{644,,Message} 对象所提供了概念化模型是由标头组成的有序字典，加上用于访问标头中的特殊信息以及访问载荷的额外方法，以便能生成消息的序列化版本，并递归地遍历对象树。 请注意重复的标头是受支持的，但必须使用特殊的方法来访问它们。

@ref{644,,Message} 伪字典以标头名作为索引，标头名必须为 ASCII 值。 字典的值为应当只包含 ASCII 字符的字符串；对于非 ASCII 输入有一些特殊处理，但这并不总能产生正确的结果。 标头以保留原大小写的形式存储和返回，但字段名称匹配对大小写不敏感。 还可能会有一个单独的封包标头，也称 @emph{Unix-From} 标头或 @code{From_} 标头。 @emph{载荷} 对于简单消息对象的情况是一个字符串或字节串，对于 MIME 容器文档的情况 (例如 @code{multipart/*} 和 @code{message/rfc822}) 则是一个 @ref{644,,Message} 对象。

以下是 @ref{644,,Message} 类的方法:

@geindex Message (email.message 中的类)
@anchor{library/email compat32-message email message Message}@anchor{644}
@deffn {类} email.message.Message (policy=compat32)

如果指定了 @emph{policy} (它必须为 @ref{73,,policy} 类的实例) 则使用它所设置的规则来更新和序列化消息的表示形式。 如果未设置 @emph{policy}，则使用 @ref{add,,compat32} 策略，该策略会保持对 Python 3.2 版 email 包的向下兼容性。 更多信息请参阅 @ref{73,,policy} 文档。


在 3.3 版更改: 增加了 @emph{policy} 关键字参数。


@geindex as_string() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message as_string}@anchor{936}
@deffn {方法} as_string (unixfrom=False, maxheaderlen=0, policy=None)

以展平的字符串形式返回整个消息对象。 或可选的 @emph{unixfrom} 为真值，返回的字符串会包括封包标头。 @emph{unixfrom} 的默认值是 @code{False}。 出于保持向下兼容性的原因，@emph{maxheaderlen} 的默认值是 @code{0}，因此如果你想要不同的值你必须显式地重载它（在策略中为 @emph{max_line_length} 指定的值将被此方法忽略）。 @emph{policy} 参数可被用于覆盖从消息实例获取的默认策略。 这可以用来对该方法所输出的格式进行一些控制，因为指定的 @emph{policy} 将被传递给 @code{Generator}。

如果需要填充默认值以完成对字符串的转换则展平消息可能触发对 @ref{644,,Message} 的修改（例如，MIME 边界可能会被生成或被修改）。

请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以 @code{From} 打头的行执行调整。 为了获得更高灵活性，请实例化一个 @ref{c27,,Generator} 实例并直接使用其 @ref{295c,,flatten()} 方法。 例如:

@example
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
@end example

如果消息对象包含未按照 RFC 标准进行编码的二进制数据，则这些不合规数据将被 unicode "unknown character" 码位值所替代。 （另请参阅 @ref{937,,as_bytes()} 和 @ref{c28,,BytesGenerator}。）


在 3.4 版更改: 增加了 @emph{policy} 关键字参数。

@end deffn

@geindex __str__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __str__}@anchor{29bd}
@deffn {方法} __str__ ()

与 @ref{936,,as_string()} 等价。 这将让 @code{str(msg)} 产生一个包含已格式化消息的字符号。
@end deffn

@geindex as_bytes() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message as_bytes}@anchor{937}
@deffn {方法} as_bytes (unixfrom=False, policy=None)

以字节串对象的形式返回整个扁平化后的消息。 当可选的 @emph{unixfrom} 为真值时，返回的字符串会包括封包标头。 @emph{unixfrom} 的默认值为 @code{False}。 @emph{policy} 参数可被用于重载从消息实例获取的默认策略。 这可被用来控制该方法所产生的部分格式化效果，因为指定的 @emph{policy} 将被传递给 @code{BytesGenerator}。

如果需要填充默认值以完成对字符串的转换则展平消息可能触发对 @ref{644,,Message} 的修改（例如，MIME 边界可能会被生成或被修改）。

请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以 @code{From} 打头的行执行调整。 为了获得更高灵活性，请实例化一个 @ref{c28,,BytesGenerator} 实例并直接使用其 @ref{2958,,flatten()} 方法。 例如:

@example
from io import BytesIO
from email.generator import BytesGenerator
fp = BytesIO()
g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
@end example


3.4 新版功能.

@end deffn

@geindex __bytes__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __bytes__}@anchor{938}
@deffn {方法} __bytes__ ()

与 @ref{937,,as_bytes()} 等价。 这将让 @code{bytes(msg)} 产生一个包含已格式化消息的字节串对象。


3.4 新版功能.

@end deffn

@geindex is_multipart() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message is_multipart}@anchor{2933}
@deffn {方法} is_multipart ()

如果该消息的载荷是一个子 @ref{644,,Message} 对象列表则返回 @code{True}，否则返回 @code{False}。 当 @ref{2933,,is_multipart()} 返回 @code{False} 时，载荷应当是一个字符串对象（有可能是一个 CTE 编码的二进制载荷）。 （请注意 @ref{2933,,is_multipart()} 返回 @code{True} 并不意味着 "msg.get_content_maintype() == 'multipart'" 将返回 @code{True}。 例如，@code{is_multipart} 在 @ref{644,,Message} 类型为 @code{message/rfc822} 时也将返回 @code{True}。）
@end deffn

@geindex set_unixfrom() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_unixfrom}@anchor{29be}
@deffn {方法} set_unixfrom (unixfrom)

将消息的封包标头设为 @emph{unixfrom}，这应当是一个字符串。
@end deffn

@geindex get_unixfrom() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_unixfrom}@anchor{29bf}
@deffn {方法} get_unixfrom ()

返回消息的信封头。如果信封头从未被设置过，默认返回 @code{None} 。
@end deffn

@geindex attach() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message attach}@anchor{2940}
@deffn {方法} attach (payload)

将给定的 @emph{payload} 添加到当前载荷中，当前载荷在该调用之前必须为 @code{None} 或是一个 @ref{644,,Message} 对象列表。 在调用之后，此载荷将总是一个 @ref{644,,Message} 对象列表。 如果你想将此载荷设为一个标量对象（如字符串），请改用 @ref{29c0,,set_payload()}。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被 @ref{fcc,,set_content()} 及相应的 @code{make} 和 @code{add} 方法所替代。
@end deffn

@geindex get_payload() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_payload}@anchor{c26}
@deffn {方法} get_payload (i=None, decode=False)

返回当前的载荷，它在 @ref{2933,,is_multipart()} 为 @code{True} 时将是一个 @ref{644,,Message} 对象列表，在 @ref{2933,,is_multipart()} 为 @code{False} 时则是一个字符串。 如果该载荷是一个列表且你修改了这个列表对象，那么你就是原地修改了消息的载荷。

传入可选参数 @emph{i} 时，如果 @ref{2933,,is_multipart()} 为 @code{True}，@ref{c26,,get_payload()} 将返回载荷从零开始计数的第 @emph{i} 个元素。 如果 @emph{i} 小于 0 或大于等于载荷中的条目数则将引发 @ref{f3d,,IndexError}。 如果载荷是一个字符串 (即 @ref{2933,,is_multipart()} 为 @code{False}) 且给出了 @emph{i}，则会引发 @ref{1ff,,TypeError}。

可选的 @emph{decode} 是一个指明载荷是否应根据 @code{Content-Transfer-Encoding} 标头被解码的旗标。 当其值为 @code{True} 且消息没有多个部分时，如果此标头值为 @code{quoted-printable} 或 @code{base64} 则载荷将被解码。 如果使用了其他编码格式，或者找不到 @code{Content-Transfer-Encoding} 标头时，载荷将被原样返回（不编码）。 在所有情况下返回值都是二进制数据。 如果消息有多个部分且 @emph{decode} 旗标为 @code{True}，则将返回 @code{None}。 如果载荷为 base64 但内容不完全正确（如缺少填充符、存在 base64 字母表以外的字符等），则将在消息的缺陷属性中添加适当的缺陷值 (分别为 @code{InvalidBase64PaddingDefect} 或 @code{InvalidBase64CharactersDefect})。

当 @emph{decode} 为 @code{False} (默认值) 时消息体会作为字符串返回而不解码 @code{Content-Transfer-Encoding}。 但是，对于 @code{Content-Transfer-Encoding} 为 8bit 的情况，会尝试使用 @code{Content-Type} 标头指定的 @code{charset} 来解码原始字节串，并使用 @code{replace} 错误处理程序。  如果未指定 @code{charset}，或者如果指定的 @code{charset} 未被 email 包所识别，则会使用默认的 ASCII 字符集来解码消息体。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被 @ref{2939,,get_content()} 和 @ref{2938,,iter_parts()} 方法所替代。
@end deffn

@geindex set_payload() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_payload}@anchor{29c0}
@deffn {方法} set_payload (payload, charset=None)

将整个消息对象的载荷设为 @emph{payload}。 客户端要负责确保载荷的不变性。 可选的 @emph{charset} 用于设置消息的默认字符集；详情请参阅 @ref{29c1,,set_charset()}。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被 @ref{fcc,,set_content()} 方法所替代。
@end deffn

@geindex set_charset() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_charset}@anchor{29c1}
@deffn {方法} set_charset (charset)

将载荷的字符集设为 @emph{charset}，它可以是 @ref{7d1,,Charset} 实例 (参见 @ref{68,,email.charset})、字符集名称字符串或 @code{None}。 如果是字符串，它将被转换为一个 @ref{7d1,,Charset} 实例。 如果 @emph{charset} 是 @code{None}，@code{charset} 形参将从 @code{Content-Type} 标头中被删除（消息将不会进行其他修改）。 任何其他值都将导致 @ref{1ff,,TypeError}。

如果 @code{MIME-Version} 标头不存在则将被添加。 如果 @code{Content-Type} 标头不存在，则将添加一个值为 @code{text/plain} 的该标头。 无论 @code{Content-Type} 标头是否已存在，其 @code{charset} 形参都将被设为 @emph{charset.output_charset}。 如果 @emph{charset.input_charset} 和 @emph{charset.output_charset} 不同，则载荷将被重编码为 @emph{output_charset}。 如果 @code{Content-Transfer-Encoding} 标头不存在，则载荷将在必要时使用指定的 @ref{7d1,,Charset} 来转换编码，并将添加一个具有相应值的标头。 如果 @code{Content-Transfer-Encoding} 标头已存在，则会假定载荷已使用该 @code{Content-Transfer-Encoding} 进行正确编码并不会再被修改。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被 @code{email.emailmessage.EmailMessage.set_content()} 方法的 @emph{charset} 形参所替代。
@end deffn

@geindex get_charset() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_charset}@anchor{29c2}
@deffn {方法} get_charset ()

返回与消息的载荷相关联的 @ref{7d1,,Charset} 实例。

这是一个过时的方法。 在 @code{EmailMessage} 类上它将总是返回 @code{None}。
@end deffn

以下方法实现了用于访问消息的 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 标头的类映射接口。  请注意这些方法和普通映射（例如字典）接口之间存在一些语义上的不同。 举例来说，在一个字典中不能有重复的键，但消息标头则可能有重复。 并且，在字典中由 @ref{29c3,,keys()} 返回的键的顺序是没有保证的，但在 @ref{644,,Message} 对象中，标头总是会按它们在原始消息中的出现或后继加入顺序返回。 任何已删除再重新加入的标头总是会添加到标头列表的末尾。

这些语义上的差异是有意为之且其目的是为了提供最大的便利性。

请注意在任何情况下，消息当中的任何封包标头都不会包含在映射接口当中。

在由字节串生成的模型中，任何包含非 ASCII 字节数据（违反 RFC）的标头值当通过此接口来获取时，将被表示为使用 @cite{unknown-8bit} 字符集的 @ref{fce,,Header} 对象。

@geindex __len__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __len__}@anchor{29c4}
@deffn {方法} __len__ ()

返回标头的总数，包括重复项。
@end deffn

@geindex __contains__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __contains__}@anchor{29c5}
@deffn {方法} __contains__ (name)

如果消息对象中有一个名为 @emph{name} 的字段则返回 @code{True}。 匹配操作对大小写不敏感并且 @emph{name} 不应包括末尾的冒号。 用于 @code{in} 运算符，例如:

@example
if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])
@end example
@end deffn

@geindex __getitem__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __getitem__}@anchor{29c6}
@deffn {方法} __getitem__ (name)

返回指定名称标头字段的值。 @emph{name} 不应包括作为字段分隔符的冒号。 如果标头未找到，则返回 @code{None}；@ref{3f1,,KeyError} 永远不会被引发。

请注意如果指定名称的字段在消息标头中多次出现，具体将返回哪个字段值是未定义的。 请使用 @ref{29c7,,get_all()} 方法来获取所有指定名称标头的值。
@end deffn

@geindex __setitem__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __setitem__}@anchor{29c8}
@deffn {方法} __setitem__ (name, val)

将具有字段名 @emph{name} 和值 @emph{val} 的标头添加到消息中。 字段会被添加到消息的现有字段的末尾。

请注意，这个方法 @emph{既不会} 覆盖 @emph{也不会} 删除任何字段名重名的已有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 @emph{name} 字段名的字段，你需要先把旧字段删除。例如：

@example
del msg['subject']
msg['subject'] = 'Python roolz!'
@end example
@end deffn

@geindex __delitem__() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message __delitem__}@anchor{29c9}
@deffn {方法} __delitem__ (name)

删除信息头当中字段名匹配 @emph{name} 的所有字段。如果匹配指定名称的字段没有找到，也不会抛出任何异常。
@end deffn

@geindex keys() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message keys}@anchor{29c3}
@deffn {方法} keys ()

以列表形式返回消息头中所有的字段名。
@end deffn

@geindex values() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message values}@anchor{29ca}
@deffn {方法} values ()

以列表形式返回消息头中所有的字段值。
@end deffn

@geindex items() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message items}@anchor{29cb}
@deffn {方法} items ()

以二元元组的列表形式返回消息头中所有的字段名和字段值。
@end deffn

@geindex get() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get}@anchor{29cc}
@deffn {方法} get (name, failobj=None)

返回指定名称标头字段的值。 这与 @ref{29c6,,__getitem__()} 是一样的，不同之处在于如果指定名称标头未找到则会返回可选的 @emph{failobj} (默认为 @code{None})。
@end deffn

以下是一些有用的附加方法:

@geindex get_all() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_all}@anchor{29c7}
@deffn {方法} get_all (name, failobj=None)

返回字段名为 @emph{name} 的所有字段值的列表。如果信息内不存在匹配的字段，返回 @emph{failobj} （其默认值为 @code{None} ）。
@end deffn

@geindex add_header() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message add_header}@anchor{29cd}
@deffn {方法} add_header (_name, _value, **_params)

高级头字段设定。这个方法与 @ref{29c8,,__setitem__()} 类似，不过你可以使用关键字参数为字段提供附加参数。 @emph{_name} 是字段名， @emph{_value} 是字段 @emph{主} 值。

对于关键字参数字典 @emph{_params} 中的每一项，其键会被当作形参名，并执行下划线和连字符间的转换（因为连字符不是合法的 Python 标识符）。 通常，形参将以 @code{key="value"} 的形式添加，除非值为 @code{None}，在这种情况下将只添加键。 如果值包含非 ASCII 字符，可将其指定为格式为 @code{(CHARSET, LANGUAGE, VALUE)} 的三元组，其中 @code{CHARSET} 为要用来编码值的字符集名称字符串，@code{LANGUAGE} 通常可设为 @code{None} 或空字符串（请参阅 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 了解其他可能的取值），而 @code{VALUE} 为包含非 ASCII 码位的字符串值。 如果不是传入一个三元组且值包含非 ASCII 字符，则会自动以 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 格式使用 @code{CHARSET} 为 @code{utf-8} 和 @code{LANGUAGE} 为 @code{None} 对其进行编码。

以下是为示例代码:

@example
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
@end example

会添加一个形如下文的头字段：

@example
Content-Disposition: attachment; filename="bud.gif"
@end example

使用非 ASCII 字符的示例代码:

@example
msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '@w{'}, 'Fußballer.ppt'))
@end example

它的输出结果为

@example
Content-Disposition: attachment; filename*="iso-8859-1'@w{'}Fu%DFballer.ppt"
@end example
@end deffn

@geindex replace_header() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message replace_header}@anchor{29ce}
@deffn {方法} replace_header (_name, _value)

替换一个标头。 将替换在匹配 @emph{_name} 的消息中找到的第一个标头，标头顺序和字段名大小写保持不变。 如果未找到匹配的标头，则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex get_content_type() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_content_type}@anchor{29cf}
@deffn {方法} get_content_type ()

返回消息的内容类型。 返回的字符串会强制转换为 @code{maintype/subtype} 的全小写形式。 如果消息中没有 @code{Content-Type} 标头则将返回由 @ref{29d0,,get_default_type()} 给出的默认类型。 因为根据 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html}，消息总是要有一个默认类型，所以 @ref{29cf,,get_content_type()} 将总是返回一个值。

@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 将消息的默认类型定义为 @code{text/plain}，除非它是出现在 @code{multipart/digest} 容器内，在这种情况下其类型应为 @code{message/rfc822}。 如果 @code{Content-Type} 标头指定了无效的类型，
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 规定其默认类型应为 @code{text/plain}。
@end deffn

@geindex get_content_maintype() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_content_maintype}@anchor{29d1}
@deffn {方法} get_content_maintype ()

返回信息的主要内容类型。准确来说，此方法返回的是 @ref{29cf,,get_content_type()} 方法所返回的形如 @code{maintype/subtype} 的字符串当中的 @code{maintype} 部分。
@end deffn

@geindex get_content_subtype() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_content_subtype}@anchor{29d2}
@deffn {方法} get_content_subtype ()

返回信息的子内容类型。准确来说，此方法返回的是 @ref{29cf,,get_content_type()} 方法所返回的形如 @code{maintype/subtype} 的字符串当中的 @code{subtype} 部分。
@end deffn

@geindex get_default_type() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_default_type}@anchor{29d0}
@deffn {方法} get_default_type ()

返回默认的内容类型。绝大多数的信息，其默认内容类型都是 @code{text/plain} 。作为 @code{multipart/digest} 容器内子部分的信息除外，它们的默认内容类型是 @code{message/rfc822} 。
@end deffn

@geindex set_default_type() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_default_type}@anchor{29d3}
@deffn {方法} set_default_type (ctype)

设置默认的内容类型。 @emph{ctype} 应当为 @code{text/plain} 或者 @code{message/rfc822}，尽管这并非强制。 默认的内容类型不会存储在 @code{Content-Type} 标头中。
@end deffn

@geindex get_params() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_params}@anchor{29d4}
@deffn {方法} get_params (failobj=None, header='content-type', unquote=True)

将消息的 @code{Content-Type} 形参作为列表返回。 所返回列表的元素为以 @code{'='} 号拆分出的键/值对 2 元组。 @code{'='} 左侧的为键，右侧的为值。 如果形参值中没有 @code{'='} 号，否则该将值如 @ref{29d5,,get_param()} 描述并且在可选 @emph{unquote} 为 @code{True} (默认值) 时会被取消转义。

可选的 @emph{failobj} 是在没有 @code{Content-Type} 标头时要返回的对象。 可选的 @emph{header} 是要替代 @code{Content-Type} 被搜索的标头。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被标头访问方法所返回的单独标头对象的 @emph{params} 特征属性所替代。
@end deffn

@geindex get_param() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_param}@anchor{29d5}
@deffn {方法} get_param (param, failobj=None, header='content-type', unquote=True)

将 @code{Content-Type} 标头的形参 @emph{param} 作为字符串返回。 如果消息没有 @code{Content-Type} 标头或者没有这样的形参，则返回 @emph{failobj} (默认为 @code{None})。

如果给出可选的 @emph{header}，它会指定要替代 @code{Content-Type} 来使用的消息标头。

形参的键总是以大小写不敏感的方式来比较的。 返回值可以是一个字符串，或者如果形参以 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 编码则是一个 3 元组。 当为 3 元组时，值中的元素采用 @code{(CHARSET, LANGUAGE, VALUE)} 的形式。 请注意 @code{CHARSET} 和 @code{LANGUAGE} 都可以为 @code{None}，在此情况下你应当将 @code{VALUE} 当作以 @code{us-ascii} 字符集来编码。 你可以总是忽略 @code{LANGUAGE}。

如果你的应用不关心形参是否以 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 来编码，你可以通过调用 @ref{29d6,,email.utils.collapse_rfc2231_value()} 来展平形参值，传入来自 @ref{29d5,,get_param()} 的返回值。 当值为元组时这将返回一个经适当编码的 Unicode 字符串，否则返回未经转换的原字符串。 例如:

@example
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
@end example

无论在哪种情况下，形参值（或为返回的字符串，或为 3 元组形式的 @code{VALUE} 条目）总是未经转换的，除非 @emph{unquote} 被设为 @code{False}。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被标头访问方法所返回的单独标头对象的 @emph{params} 特征属性所替代。
@end deffn

@geindex set_param() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_param}@anchor{939}
@deffn {方法} set_param (param, value, header='Content-Type', requote=True, charset=None, language='@w{'}, replace=False)

在 @code{Content-Type} 标头中设置一个形参。 如果该形参已存在于标头中，它的值将被替换为 @emph{value}。 如果此消息还未定义 @code{Content-Type} 标头，它将被设为 @code{text/plain} 且新的形参值将按 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 的要求添加。

可选的 @emph{header} 指定一个 @code{Content-Type} 的替代标头，并且所有形参将根据需要被转换，除非可选的 @emph{requote} 为 @code{False} (默认为 @code{True})。

如果指定了可选的 @emph{charset}，形参将按照 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 来编码。 可选的 @emph{language} 指定了 RFC 2231 的语言，默认为空字符串。 @emph{charset} 和 @emph{language} 都应为字符串。

如果 @emph{replace} 为 @code{False} （默认值），该头字段会被移动到所有头字段的末尾。如果 @emph{replace} 为 @code{True} ，字段会被原地更新。


在 3.4 版更改: 添加了 @code{replace} 关键字。

@end deffn

@geindex del_param() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message del_param}@anchor{29d7}
@deffn {方法} del_param (param, header='content-type', requote=True)

从 @code{Content-Type} 标头中完全移除给定的形参。 标头将被原地重写并不带该形参或它的值。  所有的值将根据需要被转换，除非 @emph{requote} 为 @code{False} (默认为 @code{True})。 可选的 @emph{header} 指定 @code{Content-Type} 的一个替代项。
@end deffn

@geindex set_type() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_type}@anchor{29d8}
@deffn {方法} set_type (type, header='Content-Type', requote=True)

设置 @code{Content-Type} 标头的主类型和子类型。 @emph{type} 必须为 @code{maintype/subtype} 形式的字符串，否则会引发 @ref{16d,,ValueError}。

此方法可替换 @code{Content-Type} 标头，并保持所有形参不变。 如果 @emph{requote} 为 @code{False}，这会保持原有标头引用转换不变，否则形参将被引用转换（默认行为）。

可以在 @emph{header} 参数中指定一个替代标头。 当 @code{Content-Type} 标头被设置时也会添加一个 @code{MIME-Version} 标头。

这是一个过时的方法。 在 @code{EmailMessage} 类上它的功能已被 @code{make_} 和 @code{add_} 方法所替代。
@end deffn

@geindex get_filename() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_filename}@anchor{29d9}
@deffn {方法} get_filename (failobj=None)

返回信息头当中 @code{Content-Disposition} 字段当中名为 @code{filename} 的参数值。如果该字段当中没有此参数，该方法会退而寻找 @code{Content-Type} 字段当中的 @code{name} 参数值。如果这个也没有找到，或者这些个字段压根就不存在，返回 @emph{failobj} 。返回的字符串永远按照 @ref{292c,,email.utils.unquote()} 方法去除引号。
@end deffn

@geindex get_boundary() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_boundary}@anchor{29da}
@deffn {方法} get_boundary (failobj=None)

返回信息头当中 @code{Content-Type} 字段当中名为 @code{boundary} 的参数值。如果字段当中没有此参数，或者这些个字段压根就不存在，返回 @emph{failobj} 。返回的字符串永远按照 @ref{292c,,email.utils.unquote()} 方法去除引号。
@end deffn

@geindex set_boundary() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message set_boundary}@anchor{29db}
@deffn {方法} set_boundary (boundary)

将 @code{Content-Type} 头字段的 @code{boundary} 参数设置为 @emph{boundary} 。 @ref{29db,,set_boundary()} 方法永远都会在必要的时候为 @emph{boundary} 添加引号。如果信息对象中没有 @code{Content-Type} 头字段，抛出 @ref{292f,,HeaderParseError} 异常。

请注意使用这个方法与删除旧的 @code{Content-Type} 标头并通过 @ref{29cd,,add_header()} 添加一个带有新边界的新标头有细微的差异，因为 @ref{29db,,set_boundary()} 会保留 @code{Content-Type} 标头在原标头列表中的顺序。 但是，它 @emph{不会} 保留原 @code{Content-Type} 标头中可能存在的任何连续的行。
@end deffn

@geindex get_content_charset() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_content_charset}@anchor{29dc}
@deffn {方法} get_content_charset (failobj=None)

返回 @code{Content-Type} 头字段中的 @code{charset} 参数，强制小写。如果字段当中没有此参数，或者这个字段压根不存在，返回 @emph{failobj} 。

请注意此方法不同于 @ref{29c2,,get_charset()}，后者会返回 @ref{7d1,,Charset} 实例作为消息体的默认编码格式。
@end deffn

@geindex get_charsets() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_charsets}@anchor{29dd}
@deffn {方法} get_charsets (failobj=None)

返回一个包含了信息内所有字符集名字的列表。如果信息是 @code{multipart} 类型的，那么列表当中的每一项都对应其负载的子部分的字符集名字。否则，该列表是一个长度为1的列表。

列表中的每一项都是字符串，它们是其所表示的子部分的 @code{Content-Type} 标头中 @code{charset} 形参的值。 但是，如果该子部分没有 @code{Content-Type} 标头，或没有 @code{charset} 形参，或者主 MIME 类型不是 @code{text}，则所返回列表中的对应项将为 @emph{failobj}。
@end deffn

@geindex get_content_disposition() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message get_content_disposition}@anchor{7ce}
@deffn {方法} get_content_disposition ()

如果信息的 @code{Content-Disposition} 头字段存在，返回其字段值；否则返回 @code{None} 。返回的值均为小写，不包含参数。如果信息遵循 
@geindex RFC; RFC 2183
RFC 2183@footnote{https://tools.ietf.org/html/rfc2183.html} 标准，则返回值只可能在 @emph{inline} 、 @emph{attachment} 和 @code{None} 之间选择。


3.5 新版功能.

@end deffn

@geindex walk() (email.message.Message 方法)
@anchor{library/email compat32-message email message Message walk}@anchor{29de}
@deffn {方法} walk ()

@ref{29de,,walk()} 方法是一个多功能生成器。它可以被用来以深度优先顺序遍历信息对象树的所有部分和子部分。一般而言， @ref{29de,,walk()} 会被用作 @code{for} 循环的迭代器，每一次迭代都返回其下一个子部分。

以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型。

@c import email
@c from email import message_from_binary_file
@c from os.path import join, dirname
@c lib_dir = dirname(dirname(email.__file__))
@c file_path = join(lib_dir, 'test/test_email/data/msg_16.txt')
@c with open(file_path, 'rb') as f:
@c     msg = message_from_binary_file(f)
@c from email.iterators import _structure

@example
>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain
@end example

@code{walk} 会遍历所有 @ref{2933,,is_multipart()} 方法返回 @code{True} 的部分之子部分，哪怕 @code{msg.get_content_maintype() == 'multipart'} 返回的是 @code{False} 。使用 @code{_structure} 除错帮助函数可以帮助我们在下面这个例子当中看清楚这一点：

@example
>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain
@end example

在这里， @code{message} 的部分并非 @code{multiparts} ，但是它们真的包含子部分！ @code{is_multipart()} 返回 @code{True} ， @code{walk} 也深入进这些子部分中。
@end deffn

@ref{644,,Message} 对象也可以包含两个可选的实例属性，它们可被用于生成纯文本的 MIME 消息。

@geindex preamble (email.message.Message 属性)
@anchor{library/email compat32-message email message Message preamble}@anchor{29df}
@deffn {属性} preamble

MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永远不可见，因为它处在标准 MIME 防护范围之外。 但是，当查看消息的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变得可见。

@emph{preamble} 属性包含 MIME 文档开头部分的这些处于保护范围之外的文本。 当 @ref{bf4,,Parser} 在标头之后及第一个分界字符串之前发现一些文本时，它会将这些文本赋值给消息的 @emph{preamble} 属性。 当 @ref{c27,,Generator} 写出 MIME 消息的纯文本表示形式时，如果它发现消息具有 @emph{preamble} 属性，它将在标头及第一个分界之间区域写出这些文本。 请参阅 @ref{72,,email.parser} 和 @ref{6c,,email.generator} 了解更多细节。

请注意如果消息对象没有前导文本，则 @emph{preamble} 属性将为 @code{None}。
@end deffn

@geindex epilogue (email.message.Message 属性)
@anchor{library/email compat32-message email message Message epilogue}@anchor{29e0}
@deffn {属性} epilogue

@emph{epilogue} 属性的作用方式与 @emph{preamble} 属性相同，区别在于它包含出现于最后一个分界与消息结尾之间的文本。

你不需要将 epilogue 设为空字符串以便让 @ref{c27,,Generator} 在文件末尾打印一个换行符。
@end deffn

@geindex defects (email.message.Message 属性)
@anchor{library/email compat32-message email message Message defects}@anchor{29e1}
@deffn {属性} defects

@emph{defects} 属性包含在解析消息时发现的所有问题的列表。 请参阅 @ref{6b,,email.errors} 了解可能的解析缺陷的详细描述。
@end deffn
@end deffn

@node email mime 从头创建电子邮件和 MIME 对象,email header 国际化标头,email message Message 使用 compat32 API 来表示电子邮件消息,email --- 电子邮件与 MIME 处理包
@anchor{library/email mime doc}@anchor{29e2}@anchor{library/email mime email-mime-creating-email-and-mime-objects-from-scratch}@anchor{29e3}@anchor{library/email mime module-email mime}@anchor{71}
@subsubsection @code{email.mime}: 从头创建电子邮件和 MIME 对象


@geindex email.mime (模块)

@strong{源代码:} Lib/email/mime/@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/mime/}


__________________________________________________________________


此模块是旧版 (@code{Compat32}) 电子邮件 API 的组成部分。 它的功能在新版 API 中被 @ref{69,,contentmanager} 部分替代，但在某些应用中这些类仍可能有用，即使是在非旧版代码中。

通常，你是通过传递一个文件或一些文本到解析器来获得消息对象结构体的，解析器会解析文本并返回根消息对象。 不过你也可以从头开始构建一个完整的消息结构体，甚至是手动构建单独的 @ref{644,,Message} 对象。 实际上，你也可以接受一个现有的结构体并添加新的 @ref{644,,Message} 对象并移动它们。 这为切片和分割 MIME 消息提供了非常方便的接口。

你可以通过创建 @ref{644,,Message} 实例并手动添加附件和所有适当的标头来创建一个新的对象结构体。  不过对于 MIME 消息来说，@ref{67,,email} 包提供了一些便捷子类来让事情变得更容易。

这些类列示如下:

@geindex MIMEBase (email.mime.base 中的类)
@anchor{library/email mime email mime base MIMEBase}@anchor{29e4}
@deffn {类} email.mime.base.MIMEBase (_maintype, _subtype, *, policy=compat32, **_params)

模块: @code{email.mime.base}

这是 @ref{644,,Message} 的所有 MIME 专属子类。 通常你不会创建专门的 @ref{29e4,,MIMEBase} 实例，尽管你可以这样做。 @ref{29e4,,MIMEBase} 主要被提供用来作为更具体的 MIME 感知子类的便捷基类。

@emph{_maintype} 是 @code{Content-Type} 的主类型 (例如 @code{text} 或 @code{image})，而 @emph{_subtype} 是 @code{Content-Type} 的次类型 (例如 @code{plain} 或 @code{gif})。 @emph{_params} 是一个形参键/值字典并会被直接传递给 @ref{29cd,,Message.add_header}。

如果指定了 @emph{policy} (默认为 @ref{add,,compat32} 策略)，它将被传递给 @ref{644,,Message}。

@ref{29e4,,MIMEBase} 类总是会添加一个 @code{Content-Type} 标头 (基于 @emph{_maintype}, @emph{_subtype} 和 @emph{_params})，以及一个 @code{MIME-Version} 标头 (总是设为 @code{1.0})。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMENonMultipart (email.mime.nonmultipart 中的类)
@anchor{library/email mime email mime nonmultipart MIMENonMultipart}@anchor{fa5}
@deffn {类} email.mime.nonmultipart.MIMENonMultipart

模块: @code{email.mime.nonmultipart}

@ref{29e4,,MIMEBase} 的子类，这是用于非 @code{multipart} MIME 消息的中间基类。 这个类的主要目标是避免使用 @ref{2940,,attach()} 方法，该方法仅对 @code{multipart} 消息有意义。 如果 @ref{2940,,attach()} 被调用，则会引发 @ref{2985,,MultipartConversionError} 异常。
@end deffn

@geindex MIMEMultipart (email.mime.multipart 中的类)
@anchor{library/email mime email mime multipart MIMEMultipart}@anchor{29e5}
@deffn {类} email.mime.multipart.MIMEMultipart (_subtype='mixed', boundary=None, _subparts=None, *, policy=compat32, **_params)

模块: @code{email.mime.multipart}

@ref{29e4,,MIMEBase} 的子类，这是用于 @code{multipart} MIME 消息的中间基类。 可选的 @emph{_subtype} 默认为 @code{mixed}，但可被用来指定消息的子类型。 将会在消息对象中添加一个:mimetype:@cite{multipart/_subtype} 的 @code{Content-Type} 标头。 并还将添加一个 @code{MIME-Version} 标头。

可选的 @emph{boundary} 是多部分边界字符串。 当为 @code{None} (默认值) 时，则会在必要时（例如当消息被序列化时）计算边界。

@emph{_subparts} 是载荷初始子部分的序列。 此序列必须可以被转换为列表。 你总是可以使用 @ref{2940,,Message.attach} 方法将新的子部分附加到消息中。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。

用于 @code{Content-Type} 标头的附加形参会从关键字参数中获取，或者传入到 @emph{_params} 参数，该参数是一个关键字的字典。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMEApplication (email.mime.application 中的类)
@anchor{library/email mime email mime application MIMEApplication}@anchor{29e6}
@deffn {类} email.mime.application.MIMEApplication (_data, _subtype='octet-stream', _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

模块: @code{email.mime.application}

@ref{fa5,,MIMENonMultipart} 的子类，@ref{29e6,,MIMEApplication} 类被用来表示主类型为 @code{application} 的 MIME 消息。 @emph{_data} 是包含原始字节数据的字符串。 可选的 @emph{_subtype} 指定 MIME 子类型并默认为 @code{octet-stream}。

可选的 @emph{_encoder} 是一个可调用对象（即函数），它将执行实际的数据编码以便传输。 这个可调用对象接受一个参数，该参数是 @ref{29e6,,MIMEApplication} 的实例。 它应当使用 @ref{c26,,get_payload()} 和 @ref{29c0,,set_payload()} 来将载荷改为已编码形式。 它还应根据需要将任何 @code{Content-Transfer-Encoding} 或其他标头添加到消息对象中。 默认编码格式为 base64。 请参阅 @ref{6a,,email.encoders} 模块来查看内置编码器列表。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。

@emph{_params} 会被直接传递给基类的构造器。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMEAudio (email.mime.audio 中的类)
@anchor{library/email mime email mime audio MIMEAudio}@anchor{29e7}
@deffn {类} email.mime.audio.MIMEAudio (_audiodata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

模块: @code{email.mime.audio}

@ref{fa5,,MIMENonMultipart} 的子类，@ref{29e7,,MIMEAudio} 类被用来创建主类型为 @code{audio} 的 MIME 消息。 @emph{_audiodata} 是包含原始音频数据的字符串。 如果此数据可由标准 Python 模块 @ref{ee,,sndhdr} 来解码，则其子类型将被自动包括在 @code{Content-Type} 标头中。 在其他情况下你可以通过 @emph{_subtype} 参数显式地指定音频子类型 。 如果无法猜测出主类型并且未给出 @emph{_subtype}，则会引发 @ref{1ff,,TypeError}。

可选的 @emph{_encoder} 是一个可调用对象（即函数），它将执行实际的音频数据编码以便传输。  这个可调用对象接受一个参数，该参数是 @ref{29e7,,MIMEAudio} 的实例。 它应当使用 @ref{c26,,get_payload()} 和 @ref{29c0,,set_payload()} 来将载荷改为已编码形式。 它还应根据需要将任何 @code{Content-Transfer-Encoding} 或其他标头添加到消息对象中。 默认编码格式为 base64。 请参阅 @ref{6a,,email.encoders} 模块来查看内置编码器列表。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。

@emph{_params} 会被直接传递给基类的构造器。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMEImage (email.mime.image 中的类)
@anchor{library/email mime email mime image MIMEImage}@anchor{2986}
@deffn {类} email.mime.image.MIMEImage (_imagedata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

模块: @code{email.mime.image}

@ref{fa5,,MIMENonMultipart} 的子类，@ref{2986,,MIMEImage} 类被用来创建主类型为 @code{image} 的 MIME 消息对象。 @emph{_imagedata} 是包含原始图像数据的字符串。 如果此数据可由标准 Python 模块 @ref{98,,imghdr} 来解码，则其子类型将被自动包括在 @code{Content-Type} 标头中。 在其他情况下你可以通过 @emph{_subtype} 参数显式地指定图像子类型。 如果无法猜测出主类型并且未给出 @emph{_subtype}，则会引发 @ref{1ff,,TypeError}。

可选的 @emph{_encoder} 是一个可调用对象（即函数），它将执行实际的图像数据编码以便传输。 这个可调用对象接受一个参数，该参数是 @ref{2986,,MIMEImage} 的实例。 它应当使用 @ref{c26,,get_payload()} 和 @ref{29c0,,set_payload()} 来将载荷改为已编码形式。 它还应根据需要将任何 @code{Content-Transfer-Encoding} 或其他标头添加到消息对象中。 默认编码格式为 base64。 请参阅 @ref{6a,,email.encoders} 模块来查看内置编码器列表。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。

@emph{_params} 会被直接传递给 @ref{29e4,,MIMEBase} 构造器。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMEMessage (email.mime.message 中的类)
@anchor{library/email mime email mime message MIMEMessage}@anchor{29e8}
@deffn {类} email.mime.message.MIMEMessage (_msg, _subtype='rfc822', *, policy=compat32)

模块: @code{email.mime.message}

@ref{fa5,,MIMENonMultipart} 的子类，@ref{29e8,,MIMEMessage} 类被用来创建主类型为 @code{message} 的 MIME 对象。 @emph{_msg} 将被用作载荷，并且必须为 @ref{644,,Message} 类（或其子类）的实例，否则会引发 @ref{1ff,,TypeError}。

可选的 @emph{_subtype} 设置消息的子类型；它的默认值为 @code{rfc822}。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。


在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@geindex MIMEText (email.mime.text 中的类)
@anchor{library/email mime email mime text MIMEText}@anchor{7d0}
@deffn {类} email.mime.text.MIMEText (_text, _subtype='plain', _charset=None, *, policy=compat32)

模块: @code{email.mime.text}

@ref{fa5,,MIMENonMultipart} 的子类，@ref{7d0,,MIMEText} 类被用来创建主类型为 @code{text} 的 MIME 对象。 @emph{_text} 是用作载荷的字符串。  @emph{_subtype} 指定子类型并且默认为 @code{plain}。 @emph{_charset} 是文本的字符集并会作为参数传递给 @ref{fa5,,MIMENonMultipart} 构造器；如果该字符串仅包含 @code{ascii} 码位则其默认值为 @code{us-ascii}，否则为 @code{utf-8}。 @emph{_charset} 形参接受一个字符串或是一个 @ref{7d1,,Charset} 实例。

除非 @emph{_charset} 参数被显式地设为 @code{None}，否则所创建的 MIMEText 对象将同时具有附带 @code{charset} 形参的 @code{Content-Type} 标头，以及 @code{Content-Transfer-Encoding} 标头。 这意味着后续的 @code{set_payload} 调用将不再产生已编码的载荷，即使它在 @code{set_payload} 命令中被传入。 你可以通过删除 @code{Content-Transfer-Encoding} 标头来“重置”此行为，在此之后的 @code{set_payload} 调用将自动编码新的载荷（并添加新的 @code{Content-Transfer-Encoding} 标头）。

可选的 @emph{policy} 参数默认为 @ref{add,,compat32}。


在 3.5 版更改: @emph{_charset} 也可接受 @ref{7d1,,Charset} 实例。



在 3.6 版更改: 添加了 @emph{policy} 仅限关键字形参。

@end deffn

@node email header 国际化标头,email charset 表示字符集,email mime 从头创建电子邮件和 MIME 对象,email --- 电子邮件与 MIME 处理包
@anchor{library/email header doc}@anchor{29e9}@anchor{library/email header email-header-internationalized-headers}@anchor{29ea}@anchor{library/email header module-email header}@anchor{6d}
@subsubsection @code{email.header}: 国际化标头


@geindex email.header (模块)

@strong{源代码:} Lib/email/header.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/header.py}


__________________________________________________________________


此模块是旧式 (@code{Compat32}) email API 的一部分。 在当前的 API 中标头的编码和解码是由 @ref{645,,EmailMessage} 类的字典型 API 来透明地处理的。 除了在旧有代码中使用，此模块在需要完全控制当编码标头时所使用的字符集时也很有用处。

本节中的其余文本是此模块的原始文档。

@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 是描述电子邮件消息格式的基础标准。 它派生自更早的 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 标准，该标准在大多数电子邮件仅由 ASCII 字符组成时已被广泛使用。 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 所描述的规范假定电子邮件都只包含 7 位 ASCII 字符。

当然，随着电子邮件在全球部署，它已经变得国际化了，例如电子邮件消息中现在可以使用特定语言的专属字符集。 这个基础标准仍然要求电子邮件消息只使用 7 位 ASCII 字符来进行传输，为此编写了大量 RFC 来描述如何将包含非 ASCII 字符的电子邮件编码为符合 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的格式。 这些 RFC 包括 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html}, 
@geindex RFC; RFC 2046
RFC 2046@footnote{https://tools.ietf.org/html/rfc2046.html}, 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 和 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html}。 @ref{67,,email} 包在其 @ref{6d,,email.header} 和 @ref{68,,email.charset} 模块中支持了这些标准。

如果你想在你的电子邮件标头中包括非 ASCII 字符，比如说是在 @code{Subject} 或 @code{To} 字段中，你应当使用 @ref{fce,,Header} 类并将 @ref{644,,Message} 对象中的字段赋值为 @ref{fce,,Header} 的实例而不是使用字符串作为字段值。 请从 @ref{6d,,email.header} 模块导入 @ref{fce,,Header} 类。 例如:

@example
>>> from email.message import Message
>>> from email.header import Header
>>> msg = Message()
>>> h = Header('p\xf6stal', 'iso-8859-1')
>>> msg['Subject'] = h
>>> msg.as_string()
'Subject: =?iso-8859-1?q?p=F6stal?=\n\n'
@end example

是否注意到这里我们是如何希望 @code{Subject} 字段包含非 ASCII 字符的？  我们通过创建一个 @ref{fce,,Header} 实例并传入字节串编码所用的字符集来做到这一点。 当后续的 @ref{644,,Message} 实例被展平时，@code{Subject} 字段会正确地按 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 来编码。 可感知 MIME 的电子邮件阅读器将会使用嵌入的 ISO-8859-1 字符来显示此标头。

以下是 @ref{fce,,Header} 类描述:

@geindex Header (email.header 中的类)
@anchor{library/email header email header Header}@anchor{fce}
@deffn {类} email.header.Header (s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict')

创建符合 MIME 要求的标头，其中可包含不同字符集的字符串。

可选的 @emph{s} 是初始标头值。 如果为 @code{None} (默认值)，则表示初始标头值未设置。 你可以在稍后使用 @ref{29eb,,append()} 方法调用向标头添加新值。  @emph{s} 可以是 @ref{172,,bytes} 或 @ref{206,,str} 的实例，注意参阅 @ref{29eb,,append()} 文档了解相关语义。

可选的 @emph{charset} 用于两种目的：它的含义与 @ref{29eb,,append()} 方法的 @emph{charset} 参数相同。  它还会为所有省略了 @emph{charset} 参数的后续 @ref{29eb,,append()} 调用设置默认字符集。 如果 @emph{charset} 在构造器中未提供（默认设置），则会将 @code{us-ascii} 字符集用作 @emph{s} 的初始字符集以及后续 @ref{29eb,,append()} 调用的默认字符集。

通过 @emph{maxlinelen} 可以显式指定最大行长度。 要将第一行拆分为更短的值  (以适应未被包括在to account for the field header which isn't included in @emph{s} 中的字段标头，例如 @code{Subject})，则将字段名称作为 @emph{header_name} 传入。 @emph{maxlinelen} 默认值为 76，而 @emph{header_name} 默认值为 @code{None}，表示不考虑拆分超长标头的第一行。

可选的 @emph{continuation_ws} 必须为符合 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的折叠用空白符，通常是空格符或硬制表符。 这个字符将被加缀至连续行的开头。 @emph{continuation_ws} 默认为一个空格符。

可选的 @emph{errors} 会被直接传递给 @ref{29eb,,append()} 方法。

@geindex append() (email.header.Header 方法)
@anchor{library/email header email header Header append}@anchor{29eb}
@deffn {方法} append (s, charset=None, errors='strict')

将字符串 @emph{s} 添加到 MIME 标头。

如果给出可选的 @emph{charset}，它应当是一个 @ref{7d1,,Charset} 实例 (参见 @ref{68,,email.charset}) 或字符集名称，该参数将被转换为一个 @ref{7d1,,Charset} 实例。  如果为 @code{None} (默认值) 则表示会使用构造器中给出的 @emph{charset}。

@emph{s} 可以是 @ref{172,,bytes} 或 @ref{206,,str} 的实例。 如果它是 @ref{172,,bytes} 的实例，则 @emph{charset} 为该字节串的编码格式，如果字节串无法用该字符集来解码则将引发 @ref{d0b,,UnicodeError}。

如果 @emph{s} 是 @ref{206,,str} 的实例，则 @emph{charset} 是用来指定字符串中字符字符集的提示。

在这两种情况下，当使用 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 规则产生符合 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的标头时，将使用指定字符集的输出编解码器来编码字符串。 如果字符串无法使用该输出编解码器来编码，则将引发 UnicodeError。

可选的 @emph{errors} 会在 @emph{s} 为字节串时被作为 errors 参数传递给 decode 调用。
@end deffn

@geindex encode() (email.header.Header 方法)
@anchor{library/email header email header Header encode}@anchor{29ec}
@deffn {方法} encode (splitchars=';, \t', maxlinelen=None, linesep='\n')

将消息标头编码为符合 RFC 的格式，可能会对过长的行采取折行并将非 ASCII 部分以 base64 或 quoted-printable 编码格式进行封装。

可选的 @emph{splitchars} 是一个字符串，其中包含应在正常的标头折行处理期间由拆分算法赋予额外权重的字符。 这是对于 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 中 '更高层级语法拆分' 的很粗略的支持：在拆分期间会首选在 splitchar 之前的拆分点，字符的优先级是基于它们在字符串中的出现顺序。 字符串中可包含空格和制表符以指明当其他拆分字符未在被拆分行中出现时是否要将某个字符作为优先于另一个字符的首选拆分点。 拆分字符不会影响以 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 编码的行。

如果给出 @emph{maxlinelen}，它将覆盖实例的最大行长度值。

@emph{linesep} 指定用来分隔已折叠标头行的字符。 它默认为 Python 应用程序代码中最常用的值 (@code{\n})，但也可以指定为 @code{\r\n} 以便产生带有符合 RFC 的行分隔符的标头。


在 3.2 版更改: 增加了 @emph{linesep} 参数。

@end deffn

@ref{fce,,Header} 类还提供了一些方法以支持标准运算符和内置函数。

@geindex __str__() (email.header.Header 方法)
@anchor{library/email header email header Header __str__}@anchor{29ed}
@deffn {方法} __str__ ()

以字符串形式返回 @ref{fce,,Header} 的近似表示，使用不受限制的行长度。 所有部分都会使用指定编码格式转换为 unicode 并适当地连接起来。 任何带有 @code{'unknown-8bit'} 字符集的部分都会使用 @code{'replace'} 错误处理程序解码为 ASCII。


在 3.2 版更改: 增加对 @code{'unknown-8bit'} 字符集的处理。

@end deffn

@geindex __eq__() (email.header.Header 方法)
@anchor{library/email header email header Header __eq__}@anchor{29ee}
@deffn {方法} __eq__ (other)

这个方法允许你对两个 @ref{fce,,Header} 实例进行相等比较。
@end deffn

@geindex __ne__() (email.header.Header 方法)
@anchor{library/email header email header Header __ne__}@anchor{29ef}
@deffn {方法} __ne__ (other)

这个方法允许你对两个 @ref{fce,,Header} 实例进行不等比较。
@end deffn
@end deffn

@ref{6d,,email.header} 模块还提供了下列便捷函数。

@geindex decode_header() (在 email.header 模块中)
@anchor{library/email header email header decode_header}@anchor{ae1}
@deffn {函数} email.header.decode_header (header)

在不转换字符集的情况下对消息标头值进行解码。  @emph{header} 为标头值。

这个函数返回一个 @code{(decoded_string, charset)} 对的列表，其中包含标头的每个已解码部分。 对于标头的未编码部分 @emph{charset} 为 @code{None}，在其他情况下则为一个包含已编码字符串中所指定字符集名称的小写字符串。

以下是为示例代码:

@example
>>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')]
@end example
@end deffn

@geindex make_header() (在 email.header 模块中)
@anchor{library/email header email header make_header}@anchor{ae2}
@deffn {函数} email.header.make_header (decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')

基于 @ref{ae1,,decode_header()} 所返回的数据对序列创建一个 @ref{fce,,Header} 实例。

@ref{ae1,,decode_header()} 接受一个标头值字符串并返回格式为 @code{(decoded_string, charset)} 的数据对序列，其中 @emph{charset} 是字符集名称。

这个函数接受这样的数据对序列并返回一个 @ref{fce,,Header} 实例。 可选的 @emph{maxlinelen}, @emph{header_name} 和 @emph{continuation_ws} 与 @ref{fce,,Header} 构造器中的含义相同。
@end deffn

@node email charset 表示字符集,email encoders 编码器,email header 国际化标头,email --- 电子邮件与 MIME 处理包
@anchor{library/email charset doc}@anchor{29f0}@anchor{library/email charset email-charset-representing-character-sets}@anchor{29f1}@anchor{library/email charset module-email charset}@anchor{68}
@subsubsection @code{email.charset}: 表示字符集


@geindex email.charset (模块)

@strong{源代码:} Lib/email/charset.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/charset.py}


__________________________________________________________________


此模块是旧版 (@code{Compat32}) email API 的组成部分。 在新版 API 中只会使用其中的别名表。

本段落中的剩余文本是该模块的原始文档。

此模块提供了一个 @ref{7d1,,Charset} 类用来表示电子邮件消息中的字符集和字符集转换操作，以及一个字符集注册表和几个用于操作此注册表的便捷方法。 @ref{7d1,,Charset} 的实例在 @ref{67,,email} 包的其他几个模块中也有使用。

请从 @ref{68,,email.charset} 模块导入这个类。

@geindex Charset (email.charset 中的类)
@anchor{library/email charset email charset Charset}@anchor{7d1}
@deffn {类} email.charset.Charset (input_charset=DEFAULT_CHARSET)

将字符集映射到其 email 特征属性。

这个类提供了特定字符集对于电子邮件的要求的相关信息。 考虑到适用编解码器的可用性，它还为字符集之间的转换提供了一些便捷例程。 在给定字符集的情况下，它将尽可能地以符合 RFC 的方式在电子邮件消息中提供有关如何使用该字符集的信息。

特定字符集当在电子邮件标头或消息体中使用时必须以 quoted-printable 或 base64 来编码。 某些字符集则必须被立即转换，不允许在电子邮件中使用。

可选的 @emph{input_charset} 说明如下；它总是会被强制转为小写。 在进行别名正规化后它还会被用来查询字符集注册表以找出用于该字符集的标头编码格式、消息体编码格式和输出转换编解码器。 举例来说，如果 @emph{input_charset} 为 @code{iso-8859-1}，则标头和消息体将会使用 quoted-printable 来编码并且不需要输出转换编解码器。 如果 @emph{input_charset} 为 @code{euc-jp}，则标头将使用 base64 来编码，消息体将不会被编码，但输出文本将从 @code{euc-jp} 字符集转换为 @code{iso-2022-jp} 字符集。

@ref{7d1,,Charset} 实例具有下列数据属性:

@geindex input_charset (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset input_charset}@anchor{29f2}
@deffn {属性} input_charset

指定的初始字符集。 通用别名会被转换为它们的 @emph{官方} 电子邮件名称 (例如 @code{latin_1} 会被转换为 @code{iso-8859-1})。 默认值为 7 位 @code{us-ascii}。
@end deffn

@geindex header_encoding (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset header_encoding}@anchor{29f3}
@deffn {属性} header_encoding

如果字符集在用于电子邮件标头之前必须被编码，此属性将被设为 @code{charset.QP} (表示 quoted-printable 编码格式), @code{charset.BASE64} (表示 base64 编码格式) 或 @code{charset.SHORTEST} 表示 QP 或 BASE64 编码格式中最简短的一个。 在其他情况下，该属性将为 @code{None}。
@end deffn

@geindex body_encoding (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset body_encoding}@anchor{29f4}
@deffn {属性} body_encoding

与 @emph{header_encoding} 一样，但是用来描述电子邮件消息体的编码格式，它实际上可以与标头编码格式不同。 @code{charset.SHORTEST} 不允许被用作 @emph{body_encoding}。
@end deffn

@geindex output_charset (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset output_charset}@anchor{29f5}
@deffn {属性} output_charset

某些字符集在用于电子邮件标头或消息体之前必须被转换。 如果 @emph{input_charset} 是这些字符集之一，该属性将包含输出将要转换的字符集名称。 在其他情况下，该属性将为 @code{None}。
@end deffn

@geindex input_codec (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset input_codec}@anchor{29f6}
@deffn {属性} input_codec

用于将 @emph{input_charset} 转换为 Unicode 的 Python 编解码器名称。 如果不需要任何转换编解码器，该属性将为 @code{None}。
@end deffn

@geindex output_codec (email.charset.Charset 属性)
@anchor{library/email charset email charset Charset output_codec}@anchor{29f7}
@deffn {属性} output_codec

用于将 Unicode 转换为 @emph{output_charset} 的 Python 编解码器名称。 如果不需要任何转换编解码器，该属性将具有与 @emph{input_codec} 相同的值。
@end deffn

@ref{7d1,,Charset} 实例还有下列方法:

@geindex get_body_encoding() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset get_body_encoding}@anchor{29f8}
@deffn {方法} get_body_encoding ()

返回用于消息体编码的内容转换编码格式。

根据所使用的编码格式返回 @code{quoted-printable} 或 @code{base64}，或是返回一个函数，在这种情况下你应当调用该函数并附带一个参数，即被编码的消息对象。 该函数应当自行将 @code{Content-Transfer-Encoding} 标头设为适当的值。

如果 @emph{body_encoding} 为 @code{QP} 则返回字符串 @code{quoted-printable}，如果 @emph{body_encoding} 为 @code{BASE64} 则返回字符串 @code{base64}，并在其他情况下返回字符串 @code{7bit}。
@end deffn

@geindex get_output_charset() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset get_output_charset}@anchor{29f9}
@deffn {方法} get_output_charset ()

返回输出字符集。

如果 @emph{output_charset} 属性不为 @code{None} 则返回该属性，否则返回 @emph{input_charset}。
@end deffn

@geindex header_encode() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset header_encode}@anchor{29fa}
@deffn {方法} header_encode (string)

对字符串 @emph{string} 执行标头编码。

编码格式的类型 (base64 或 quoted-printable) 将取决于 @emph{header_encoding} 属性。
@end deffn

@geindex header_encode_lines() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset header_encode_lines}@anchor{29fb}
@deffn {方法} header_encode_lines (string, maxlengths)

通过先将 @emph{string} 转换为字节串来对其执行标头编码。

这类似于 @ref{29fa,,header_encode()}，区别是字符串会被调整至参数 @emph{maxlengths} 所给出的最大行长度，它应当是一个迭代器：该迭代器返回的每个元素将提供下一个最大行长度。
@end deffn

@geindex body_encode() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset body_encode}@anchor{29fc}
@deffn {方法} body_encode (string)

对字符串 @emph{string} 执行消息体编码。

编码格式的类型 (base64 或 quoted-printable) 将取决于 @emph{body_encoding} 属性。
@end deffn

@ref{7d1,,Charset} 类还提供了一些方法以支持标准运算和内置函数。

@geindex __str__() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset __str__}@anchor{29fd}
@deffn {方法} __str__ ()

将 @emph{input_charset} 以强制转为小写的字符串形式返回。 @ref{453,,__repr__()} 是 @ref{29fd,,__str__()} 的别名。
@end deffn

@geindex __eq__() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset __eq__}@anchor{29fe}
@deffn {方法} __eq__ (other)

这个方法允许你对两个 @ref{7d1,,Charset} 实例进行相等比较。
@end deffn

@geindex __ne__() (email.charset.Charset 方法)
@anchor{library/email charset email charset Charset __ne__}@anchor{29ff}
@deffn {方法} __ne__ (other)

这个方法允许你对两个 @ref{7d1,,Charset} 实例进行相等比较。
@end deffn
@end deffn

@ref{68,,email.charset} 模块还提供了下列函数用于向全局字符集、别名以及编解码器注册表添加新条目:

@geindex add_charset() (在 email.charset 模块中)
@anchor{library/email charset email charset add_charset}@anchor{2a00}
@deffn {函数} email.charset.add_charset (charset, header_enc=None, body_enc=None, output_charset=None)

向全局注册表添加字符特征属性。

@emph{charset} 是输入字符集，它必须为某个字符集的正规名称。

可选的 @emph{header_enc} 和 @emph{body_enc} 可以是 @code{charset.QP} 表示 quoted-printable 编码格式, @code{charset.BASE64} 表示 base64 编码格式, @code{charset.SHORTEST} 表示 quoted-printable 或 base64 编码格式中较短的一个，或者为 @code{None} 表示没有编码格式。 @code{SHORTEST} 仅对 @emph{header_enc} 有效。 默认值为 @code{None} 表示没有编码格式。

可选的 @emph{output_charset} 是输出所应当采用的字符集。 当 @code{Charset.convert()} 方法被调用时将会执行从输入字符集到输出字符集的转换。 默认情况下输出字符集将与输入字符集相同。

@emph{input_charset} 和 @emph{output_charset} 都必须在模块的字符集-编解码器映射中具有 Unicode 编解码器条目；使用 @ref{2a01,,add_codec()} 可添加本模块还不知道的编解码器。 请参阅 @ref{1b,,codecs} 模块的文档来了解更多信息。

全局字符集注册表保存在模块全局字典 @code{CHARSETS} 中。
@end deffn

@geindex add_alias() (在 email.charset 模块中)
@anchor{library/email charset email charset add_alias}@anchor{2a02}
@deffn {函数} email.charset.add_alias (alias, canonical)

添加一个字符集别名。 @emph{alias} 为特定的别名，例如 @code{latin-1}。 @emph{canonical} 是字符集的正规名称，例如 @code{iso-8859-1}。

全局字符集注册表保存在模块全局字典 @code{ALIASES} 中。
@end deffn

@geindex add_codec() (在 email.charset 模块中)
@anchor{library/email charset email charset add_codec}@anchor{2a01}
@deffn {函数} email.charset.add_codec (charset, codecname)

添加在给定字符集的字符和 Unicode 之间建立映射的编解码器。

@emph{charset} 是某个字符集的正规名称。 @emph{codecname} 是某个 Python 编解码器的名称，可以被用来作为 @ref{206,,str} 的 @ref{170,,encode()} 方法的第二个参数。
@end deffn

@node email encoders 编码器,email utils 其他工具,email charset 表示字符集,email --- 电子邮件与 MIME 处理包
@anchor{library/email encoders doc}@anchor{2a03}@anchor{library/email encoders email-encoders-encoders}@anchor{2a04}@anchor{library/email encoders module-email encoders}@anchor{6a}
@subsubsection @code{email.encoders}: 编码器


@geindex email.encoders (模块)

@strong{源代码:} Lib/email/encoders.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/encoders.py}


__________________________________________________________________


此模块是旧版 (@code{Compat32}) email API 的组成部分。 在新版 API 中将由 @ref{fcc,,set_content()} 方法的 @emph{cte} 形参提供该功能。

此模块在 Python 3 中已弃用。 这里提供的函数不应被显式地调用，因为 @ref{7d0,,MIMEText} 类会在类实例化期间使用 @emph{_subtype} 和 @emph{_charset} 值来设置内容类型和 CTE 标头。

本段落中的剩余文本是该模块的原始文档。

当创建全新的 @ref{644,,Message} 对象时，你经常需要对载荷编码以便通过兼容的邮件服务器进行传输。 对于包含二进制数据的 @code{image/*} 和 @code{text/*} 类型的消息来说尤其如此。

@ref{67,,email} 包在其 @code{encoders} 模块中提供了一些方便的编码器。 这些编码器实际上由 @ref{29e7,,MIMEAudio} 和 @ref{2986,,MIMEImage} 类构造器所使用以提供默认编码格式。 所有编码器函数都只接受一个参数，即要编码的消息对象。 它们通常会提取有效载荷，对其进行编码，并将载荷重置为这种新编码的值。  它们还应当相应地设置 @code{Content-Transfer-Encoding} 标头。

请注意，这些函数对于多段消息没有意义。 它们必须应用到各个单独的段上面，而不是整体。如果直接传递一个多段类型的消息，会产生一个 @ref{1ff,,TypeError} 错误。

下面是提供的编码函数：

@geindex encode_quopri() (在 email.encoders 模块中)
@anchor{library/email encoders email encoders encode_quopri}@anchor{2a05}
@deffn {函数} email.encoders.encode_quopri (msg)

将有效数据编码为经转换的可打印形式，并将 @code{Content-Transfer-Encoding} 标头设置为 @code{quoted-printable} @footnote{@w{(1)} 
请注意使用 @ref{2a05,,encode_quopri()} 编码格式还会对数据中的所有制表符和空格符进行编码。
}。 当大多数实际的数据是普通的可打印数据但包含少量不可打印的字符时，这是一个很好的编码。
@end deffn

@geindex encode_base64() (在 email.encoders 模块中)
@anchor{library/email encoders email encoders encode_base64}@anchor{2a06}
@deffn {函数} email.encoders.encode_base64 (msg)

将有效载荷编码为 base64 形式，并将 @code{Content-Transfer-Encoding} 标头设为 @code{base64}。 当你的载荷主要包含不可打印数据时这是一种很好用的编码格式，因为它比 quoted-printable 更紧凑。 base64 编码格式的缺点是它会使文本变成人类不可读的形式。
@end deffn

@geindex encode_7or8bit() (在 email.encoders 模块中)
@anchor{library/email encoders email encoders encode_7or8bit}@anchor{2a07}
@deffn {函数} email.encoders.encode_7or8bit (msg)

此函数并不实际改变消息的有效载荷，但它会基于载荷数据将 @code{Content-Transfer-Encoding} 标头相应地设为 @code{7bit} 或 @code{8bit}。
@end deffn

@geindex encode_noop() (在 email.encoders 模块中)
@anchor{library/email encoders email encoders encode_noop}@anchor{2a08}
@deffn {函数} email.encoders.encode_noop (msg)

此函数什么都不会做；它甚至不会设置 @code{Content-Transfer-Encoding} 标头。
@end deffn

@node email utils 其他工具,email iterators 迭代器,email encoders 编码器,email --- 电子邮件与 MIME 处理包
@anchor{library/email utils doc}@anchor{2a09}@anchor{library/email utils email-utils-miscellaneous-utilities}@anchor{2a0a}@anchor{library/email utils module-email utils}@anchor{74}
@subsubsection @code{email.utils}: 其他工具


@geindex email.utils (模块)

@strong{源代码:} Lib/email/utils.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/utils.py}


__________________________________________________________________


@ref{74,,email.utils} 模块提供如下几个工具

@geindex localtime() (在 email.utils 模块中)
@anchor{library/email utils email utils localtime}@anchor{ae8}
@deffn {函数} email.utils.localtime (dt=None)

以感知型 datetime 对象返回当地时间。 如果调用时参数为空，则返回当前时间。 否则 @emph{dt} 参数应该是一个 @ref{19f,,datetime} 实例，并根据系统时区数据库转换为当地时区。 如果 @emph{dt} 是简单型的 (即 @code{dt.tzinfo} 是 @code{None} )，则假定为当地时间。 在这种情况下，为正值或零的 @emph{isdst} 会使 @code{localtime} 假定夏季时间（例如，夏令时）对指定时间生效或不生效。 负值 @emph{isdst} 会使 @code{localtime} 预测夏季时间对指定时间是否生效。


3.3 新版功能.

@end deffn

@geindex make_msgid() (在 email.utils 模块中)
@anchor{library/email utils email utils make_msgid}@anchor{2a0b}
@deffn {函数} email.utils.make_msgid (idstring=None, domain=None)

返回一个适合作为兼容 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的 @code{Message-ID} 标头的字符串。可选参数 @emph{idstring} 可传入一字符串以增强该消息 ID 的唯一性。可选参数 @emph{domain} 可用于提供消息 ID 中字符 '@@' 之后的部分，其默认值是本机的主机名。正常情况下无需覆盖此默认值，但在特定情况下覆盖默认值可能会有用，比如构建一个分布式系统，在多台主机上采用一致的域名。


在 3.2 版更改: 增加了关键字 @emph{domain}

@end deffn

下列函数是旧（@code{Compat32}）电子邮件 API 的一部分。新 API 提供的解析和格式化在标头解析机制中已经被自动完成，故在使用新 API 时没有必要直接使用它们函数。

@geindex quote() (在 email.utils 模块中)
@anchor{library/email utils email utils quote}@anchor{2a0c}
@deffn {函数} email.utils.quote (str)

返回一个新的字符串， @emph{str} 中的反斜杠被替换为两个反斜杠，并且双引号被替换为反斜杠加双引号。
@end deffn

@geindex unquote() (在 email.utils 模块中)
@anchor{library/email utils email utils unquote}@anchor{292c}
@deffn {函数} email.utils.unquote (str)

返回 @emph{str} 被去除引用后的字符串。如果 @emph{str} 开头和结尾均是双引号，则这对双引号被去除。类似地，如果 @emph{str} 开头和结尾都是尖角括号，这对尖角括号会被去除。
@end deffn

@geindex parseaddr() (在 email.utils 模块中)
@anchor{library/email utils email utils parseaddr}@anchor{2a0d}
@deffn {函数} email.utils.parseaddr (address)

将地址（应为诸如 @code{To} 或者 @code{Cc} 之类包含地址的字段值）解析为构成之的 @emph{真实名字} 和 @emph{电子邮件地址} 部分。返回包含这两个信息的一个元组；如若解析失败，则返回一个二元组 @code{('@w{'}, '@w{'})} 。
@end deffn

@geindex formataddr() (在 email.utils 模块中)
@anchor{library/email utils email utils formataddr}@anchor{bf1}
@deffn {函数} email.utils.formataddr (pair, charset='utf-8')

是 @ref{2a0d,,parseaddr()} 的逆操作，接受一个 @code{(真实名字, 电子邮件地址)} 的二元组，并返回适合于 @code{To} or @code{Cc} 标头的字符串。如果第一个元素为假性值，则第二个元素将被原样返回。

可选地，如果指定 @emph{charset}，则被视为一符合 
@geindex RFC; RFC 2047
RFC 2047@footnote{https://tools.ietf.org/html/rfc2047.html} 的编码字符集，用于编码 @code{真实名字} 中的非 ASCII 字符。可以是一个 @ref{206,,str} 类的实例，或者一个 @ref{7d1,,Charset} 类。默认为  @code{utf-8} 。


在 3.3 版更改: 添加了 @emph{charset} 选项。

@end deffn

@geindex getaddresses() (在 email.utils 模块中)
@anchor{library/email utils email utils getaddresses}@anchor{fcd}
@deffn {函数} email.utils.getaddresses (fieldvalues)

该方法返回一个形似 @code{parseaddr()} 返回的二元组的列表。 @emph{fieldvalues} 是一个序列，包含了形似 @ref{29c7,,Message.get_all} 返回值的标头字段值。获取了一消息的所有收件人的简单示例如下：

@example
from email.utils import getaddresses

tos = msg.get_all('to', [])
ccs = msg.get_all('cc', [])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
@end example
@end deffn

@geindex parsedate() (在 email.utils 模块中)
@anchor{library/email utils email utils parsedate}@anchor{2a0e}
@deffn {函数} email.utils.parsedate (date)

尝试根据 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的规则解析一个日期。然而，有些寄信人不严格遵守这一格式，所以这种情况下 @ref{2a0e,,parsedate()} 会尝试猜测其形式。@emph{date} 是一个字符串包含了一个形如 @code{"Mon, 20 Nov 1995 19:12:08 -0500"} 的 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 格式日期。如果日期解析成功， @ref{2a0e,,parsedate()} 将返回一个九元组，可直接传递给 @ref{c3f,,time.mktime()}；否则返回 @code{None}。注意返回的元组中下标为 6、7、8 的部分是无用的。
@end deffn

@geindex parsedate_tz() (在 email.utils 模块中)
@anchor{library/email utils email utils parsedate_tz}@anchor{fb6}
@deffn {函数} email.utils.parsedate_tz (date)

执行与 @ref{2a0e,,parsedate()} 相同的功能，但会返回 @code{None} 或是一个 10 元组；前 9 个元素构成一个可以直接传给 @ref{c3f,,time.mktime()} 的元组，而第十个元素则是该日期的时区与 UTC (格林威治平均时 GMT 的正式名称) @footnote{@w{(1)} 
请注意时区时差的符号与同一时区的 @code{time.timezone} 变量的符号相反；后者遵循 POSIX 标准而此模块遵循 
@geindex RFC; RFC 2822
@uref{https://tools.ietf.org/html/rfc2822.html,RFC 2822}。
} 的时差。 如果输入字符串不带时区，则所返回元组的最后一个元素将为 @code{0}，这表示 UTC。 请注意结果元组的索引号 6, 7 和 8 是不可用的。
@end deffn

@geindex parsedate_to_datetime() (在 email.utils 模块中)
@anchor{library/email utils email utils parsedate_to_datetime}@anchor{ae7}
@deffn {函数} email.utils.parsedate_to_datetime (date)

@ref{ae6,,format_datetime()} 的逆操作。 执行与 @ref{2a0e,,parsedate()} 相同的功能，但会在成功时返回一个 @ref{19f,,datetime}。 如果输入日期的时区值为 @code{-0000}，则 @code{datetime} 将为一个简单型 @code{datetime}，而如果日期符合 RFC 标准则它将代表一个 UTC 时间，但是并不指明日期所在消息的实际源时区。 如果输入日期具有任何其他有效的时区差值，则 @code{datetime} 将为一个感知型 @code{datetime} 并与 @ref{ae9,,timezone} @ref{180,,tzinfo} 相对应。


3.3 新版功能.

@end deffn

@geindex mktime_tz() (在 email.utils 模块中)
@anchor{library/email utils email utils mktime_tz}@anchor{2a0f}
@deffn {函数} email.utils.mktime_tz (tuple)

将 @ref{fb6,,parsedate_tz()} 所返回的 10 元组转换为一个 UTC 时间戳（相距 Epoch 纪元初始的秒数）。 如果元组中的时区项为 @code{None}，则视为当地时间。
@end deffn

@geindex formatdate() (在 email.utils 模块中)
@anchor{library/email utils email utils formatdate}@anchor{2a10}
@deffn {函数} email.utils.formatdate (timeval=None, localtime=False, usegmt=False)

返回 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 标准的日期字符串，例如:

@example
Fri, 09 Nov 2001 01:08:47 -0000
@end example

可选的 @emph{timeval} 如果给出，则是一个可被 @ref{c1a,,time.gmtime()} 和 @ref{10c9,,time.localtime()} 接受的浮点数时间值，否则会使得当前时间。

可选的 @emph{localtime} 是一个旗标，当为 @code{True} 时，将会解析 @emph{timeval}，并返回一个相对于当地时区而非 UTC 的日期值，并会适当地考虑夏令时。 默认值 @code{False} 表示使用 UTC。

可选的 @emph{usegmt} 是一个旗标，当为 @code{True} 时，将会输出一个日期字符串，其中时区表示为 ascii 字符串 @code{GMT} 而非数字形式的 @code{-0000}。 这对某些协议（例如 HTTP）来说是必要的。 这仅在 @emph{localtime} 为 @code{False} 时应用。 默认值为 @code{False}。
@end deffn

@geindex format_datetime() (在 email.utils 模块中)
@anchor{library/email utils email utils format_datetime}@anchor{ae6}
@deffn {函数} email.utils.format_datetime (dt, usegmt=False)

类似于 @code{formatdate}，但输入的是一个 @ref{30,,datetime} 实例。 如果实例是一个简单型 datetime，它会被视为 "不带源时区信息的 UTC"，并且使用传统的 @code{-0000} 作为时区。 如果实例是一个感知型 @code{datetime}，则会使用数字形式的时区时差。 如果实例是感知型且时区时差为零，则 @emph{usegmt} 可能会被设为 @code{True}，在这种情况下将使用字符串 @code{GMT} 而非数字形式的时区时差。 这提供了一种生成符合标准 HTTP 日期标头的方式。


3.3 新版功能.

@end deffn

@geindex decode_rfc2231() (在 email.utils 模块中)
@anchor{library/email utils email utils decode_rfc2231}@anchor{2a11}
@deffn {函数} email.utils.decode_rfc2231 (s)

根据 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 解码字符串 @emph{s}。
@end deffn

@geindex encode_rfc2231() (在 email.utils 模块中)
@anchor{library/email utils email utils encode_rfc2231}@anchor{2a12}
@deffn {函数} email.utils.encode_rfc2231 (s, charset=None, language=None)

根据 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 对字符串 @emph{s} 进行编码。 可选的 @emph{charset} 和 @emph{language} 如果给出，则为指明要使用的字符集名称和语言名称。 如果两者均未给出，则会原样返回 @emph{s}。 如果给出 @emph{charset} 但未给出 @emph{language}，则会使用空字符串作为 @emph{language} 值来对字符串进行编码。
@end deffn

@geindex collapse_rfc2231_value() (在 email.utils 模块中)
@anchor{library/email utils email utils collapse_rfc2231_value}@anchor{29d6}
@deffn {函数} email.utils.collapse_rfc2231_value (value, errors='replace', fallback_charset='us-ascii')

当以 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 格式来编码标头形参时，@ref{29d5,,Message.get_param} 可能返回一个包含字符集、语言和值的 3 元组。 @ref{29d6,,collapse_rfc2231_value()} 会将此返回为一个 unicode 字符串。 可选的 @emph{errors} 会被传递给 @ref{206,,str} 的 @ref{170,,encode()} 方法的 @emph{errors} 参数；它的默认值为 @code{'replace'}。 可选的 @emph{fallback_charset} 指定当 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 标头中的字符集无法被 Python 识别时要使用的字符集；它的默认值为 @code{'us-ascii'}。

为方便起见，如果传给 @ref{29d6,,collapse_rfc2231_value()} 的 @emph{value} 不是一个元组，则应为一个字符串并会将其原样返回。
@end deffn

@geindex decode_params() (在 email.utils 模块中)
@anchor{library/email utils email utils decode_params}@anchor{2a13}
@deffn {函数} email.utils.decode_params (params)

根据 
@geindex RFC; RFC 2231
RFC 2231@footnote{https://tools.ietf.org/html/rfc2231.html} 解码参数列表。 @emph{params} 是一个包含 @code{(content-type, string-value)} 形式的元素的 2 元组的序列。
@end deffn

@subsubheading 备注


@node email iterators 迭代器,,email utils 其他工具,email --- 电子邮件与 MIME 处理包
@anchor{library/email iterators doc}@anchor{2a14}@anchor{library/email iterators email-iterators-iterators}@anchor{2a15}@anchor{library/email iterators module-email iterators}@anchor{6f}
@subsubsection @code{email.iterators}: 迭代器


@geindex email.iterators (模块)

@strong{源代码:} Lib/email/iterators.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/email/iterators.py}


__________________________________________________________________


通过 @ref{29de,,Message.walk} 方法来迭代消息对象树是相当容易的。 @ref{6f,,email.iterators} 模块提供了一些适用于消息对象树的高层级迭代器。

@geindex body_line_iterator() (在 email.iterators 模块中)
@anchor{library/email iterators email iterators body_line_iterator}@anchor{2a16}
@deffn {函数} email.iterators.body_line_iterator (msg, decode=False)

此函数会迭代 @emph{msg} 的所有子部分中的所有载荷，逐行返回字符串载荷。 它会跳过所有子部分的标头，并且它也会跳过任何包含不为 Python 字符串的载荷的子部分。 这基本上等价于使用 @ref{1da3,,readline()} 从一个文件读取消息的纯文本表示形式，并跳过所有中间的标头。

可选的 @emph{decode} 会被传递给 @ref{c26,,Message.get_payload}。
@end deffn

@geindex typed_subpart_iterator() (在 email.iterators 模块中)
@anchor{library/email iterators email iterators typed_subpart_iterator}@anchor{2a17}
@deffn {函数} email.iterators.typed_subpart_iterator (msg, maintype='text', subtype=None)

此函数会迭代 @emph{msg} 的所有子部分，只返回其中与 @emph{maintype} 和 @emph{subtype} 所指定的 MIME 类型相匹配的子部分。

请注意 @emph{subtype} 是可选项；如果省略，则仅使用主类型来进行子部分 MIME 类型的匹配。 @emph{maintype} 也是可选项；它的默认值为 @code{text}。

因此，在默认情况下 @ref{2a17,,typed_subpart_iterator()} 会返回每一个 MIME 类型为 @code{text/*} 的子部分。
@end deffn

增加了以下函数作为有用的调试工具。 它 @emph{不应当} 被视为该包所支持的公共接口的组成部分。

@geindex _structure() (在 email.iterators 模块中)
@anchor{library/email iterators email iterators _structure}@anchor{2a18}
@deffn {函数} email.iterators._structure (msg, fp=None, level=0, include_default=False)

打印消息对象结构的内容类型的缩进表示形式。 例如:

@c import email
@c from email.iterators import _structure
@c somefile = open('../Lib/test/test_email/data/msg_02.txt')

@example
>>> msg = email.message_from_file(somefile)
>>> _structure(msg)
multipart/mixed
    text/plain
    text/plain
    multipart/digest
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
    text/plain
@end example

@c somefile.close()

可选项 @emph{fp} 是一个作为打印输出目标的文件类对象。 它必须适用于 Python 的 @ref{97a,,print()} 函数。 @emph{level} 是供内部使用的。 @emph{include_default} 如果为真值，则会同时打印默认类型。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{ed,,smtplib} 模块

SMTP (简单邮件传输协议) 客户端

@item @ref{d0,,poplib} 模块

POP (邮局协议) 客户端

@item @ref{97,,imaplib} 模块

IMAP (互联网消息访问协议) 客户端

@item @ref{c0,,nntplib} 模块

NNTP (网络新闻传输协议) 客户端

@item @ref{ae,,mailbox} 模块

创建、读取和管理使用保存在磁盘中的多种标准格式的消息集的工具。

@item @ref{ec,,smtpd} 模块

SMTP 服务器框架 (主要适用于测试)
@end table


@node json --- JSON 编码和解码器,mailbox --- 操作多种格式的邮箱,email --- 电子邮件与 MIME 处理包,互联网数据处理
@anchor{library/json doc}@anchor{2a19}@anchor{library/json json-json-encoder-and-decoder}@anchor{2a1a}@anchor{library/json module-json}@anchor{a4}
@subsection @code{json} --- JSON 编码和解码器


@geindex json (模块)

@strong{源代码:} Lib/json/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/json/__init__.py}


__________________________________________________________________


JSON (JavaScript Object Notation)@footnote{http://json.org}，由 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://tools.ietf.org/html/rfc7159.html}  (它取代了 
@geindex RFC; RFC 4627
RFC 4627@footnote{https://tools.ietf.org/html/rfc4627.html}) 和 ECMA-404@footnote{http://www.ecma-international.org/publications/standards/Ecma-404.htm} 指定，是一个受 JavaScript@footnote{https://en.wikipedia.org/wiki/JavaScript} 的对象字面值句法启发的轻量级数据交换格式，尽管它不仅仅是一个严格意义上的 JavaScript 的子集 @footnote{@w{(1)} 
正如 @uref{https://www.rfc-editor.org/errata_search.php?rfc=7159,RFC 7159 的勘误表} 所说明的，JSON 允许以字符串表示字面值字符 U+2028 (LINE SEPARATOR) 和 U+2029 (PARAGRAPH SEPARATOR)，而 JavaScript (在 ECMAScript 5.1 版中) 不允许。
}。

@cartouche
@quotation 警告 
Be cautious when parsing JSON data from untrusted sources. A malicious
JSON string may cause the decoder to consume considerable CPU and memory
resources. Limiting the size of data to be parsed is recommended.
@end quotation
@end cartouche

@ref{a4,,json} 提供了与标准库 @ref{b0,,marshal} 和 @ref{ca,,pickle} 相似的API接口。

对基本的 Python 对象层次结构进行编码：

@example
>>> import json
>>> json.dumps(['foo', @{'bar': ('baz', None, 1.0, 2)@}])
'["foo", @{"bar": ["baz", null, 1.0, 2]@}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps(@{"c": 0, "b": 0, "a": 0@}, sort_keys=True))
@{"a": 0, "b": 0, "c": 0@}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
@end example

紧凑编码:

@example
>>> import json
>>> json.dumps([1, 2, 3, @{'4': 5, '6': 7@}], separators=(',', ':'))
'[1,2,3,@{"4":5,"6":7@}]'
@end example

美化输出:

@example
>>> import json
>>> print(json.dumps(@{'4': 5, '6': 7@}, sort_keys=True, indent=4))
@{
    "4": 5,
    "6": 7
@}
@end example

JSON解码:

@example
>>> import json
>>> json.loads('["foo", @{"bar":["baz", null, 1.0, 2]@}]')
['foo', @{'bar': ['baz', None, 1.0, 2]@}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']
@end example

特殊JSON对象解码:

@example
>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('@{"__complex__": true, "real": 1, "imag": 2@}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')
@end example

扩展 @ref{707,,JSONEncoder}:

@example
>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']
@end example

从命令行使用 @ref{a5,,json.tool} 来验证并美化输出：

@example
$ echo '@{"json":"obj"@}' | python -m json.tool
@{
    "json": "obj"
@}
$ echo '@{1.2:3.4@}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
@end example

详细文档请参见 @ref{2a1b,,命令行界面}。

@cartouche
@quotation 注解 
JSON 是 YAML@footnote{http://yaml.org/} 1.2 的一个子集。由该模块的默认设置生成的 JSON （尤其是默认的 “分隔符” 设置值）也是 YAML 1.0 and 1.1 的一个子集。因此该模块也能够用于序列化为 YAML。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
这个模块的编码器和解码器默认保护输入和输出的顺序。仅当底层的容器未排序时才会失去顺序。
@end quotation
@end cartouche

@menu
* 基本使用:: 
* 编码器和解码器:: 
* 异常: 异常<13>. 
* 标准符合性和互操作性:: 
* 命令行界面: 命令行界面<4>. 

@end menu

@node 基本使用,编码器和解码器,,json --- JSON 编码和解码器
@anchor{library/json basic-usage}@anchor{2a1c}
@subsubsection 基本使用


@geindex dump() (在 json 模块中)
@anchor{library/json json dump}@anchor{705}
@deffn {函数} json.dump (obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

使用这个 @ref{2a1d,,转换表} 将 @emph{obj} 序列化为 JSON 格式化流形式的 @emph{fp} (支持 @code{.write()} 的 @ref{1e0e,,file-like object})。

如果 @emph{skipkeys} 是 true （默认为 @code{False}），那么那些不是基本对象（包括 @ref{206,,str}, @ref{205,,int}、@ref{1fe,,float}、@ref{2c4,,bool}、@code{None}）的字典的键会被跳过；否则引发一个 @ref{1ff,,TypeError}。

@ref{a4,,json} 模块始终产生 @ref{206,,str} 对象而非 @ref{172,,bytes} 对象。因此，@code{fp.write()} 必须支持 @ref{206,,str} 输入。

如果 @emph{ensure_ascii} 是 true （即默认值），输出保证将所有输入的非 ASCII 字符转义。如果 @emph{ensure_ascii} 是 false，这些字符会原样输出。

如果 @emph{check_circular} 是为假值 (默认为 @code{True})，那么容器类型的循环引用检验会被跳过并且循环引用会引发一个 @ref{731,,RecursionError} (或者更糟的情况)。

如果 @emph{allow_nan} 是 false（默认为 @code{True}），那么在对严格 JSON 规格范围外的 @ref{1fe,,float} 类型值（@code{nan}、@code{inf} 和 @code{-inf}）进行序列化时会引发一个 @ref{16d,,ValueError}。如果 @emph{allow_nan} 是 true，则使用它们的 JavaScript 等价形式（@code{NaN}、@code{Infinity} 和 @code{-Infinity}）。

如果 @emph{indent} 是一个非负整数或者字符串，那么 JSON 数组元素和对象成员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者 @code{""}，则只会添加换行符。 @code{None} (默认值) 选择最紧凑的表达。 使用一个正整数会让每一层缩进同样数量的空格。 如果 @emph{indent} 是一个字符串 (比如 @code{"\t"})，那个字符串会被用于缩进每一层。


在 3.2 版更改: 允许使用字符串作为 @emph{indent} 而不再仅仅是整数。


当指定时，@emph{separators} 应当是一个 @code{(item_separator, key_separator)} 元组。当 @emph{indent} 为 @code{None} 时，默认值取 @code{(', ', ': ')}，否则取 @code{(',', ': ')}。为了得到最紧凑的 JSON 表达式，你应该指定其为 @code{(',', ':')} 以消除空白字符。


在 3.4 版更改: 现当 @emph{indent} 不是 @code{None} 时，采用 @code{(',', ': ')} 作为默认值。


当 @emph{default} 被指定时，其应该是一个函数，每当某个对象无法被序列化时它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一个 @ref{1ff,,TypeError}。如果没有被指定，则会直接引发 @ref{1ff,,TypeError}。

如果 @emph{sort_keys} 是 true（默认为 @code{False}），那么字典的输出会以键的顺序排序。

为了使用一个自定义的 @ref{707,,JSONEncoder} 子类（比如：覆盖了 @code{default()} 方法来序列化额外的类型）， 通过 @emph{cls} 关键字参数来指定；否则将使用 @ref{707,,JSONEncoder}。


在 3.6 版更改: 所有的可选参数现在是 @ref{3d6,,keyword-only} 的了。


@cartouche
@quotation 注解 
与 @ref{ca,,pickle} 和 @ref{b0,,marshal} 不同，JSON 不是一个具有框架的协议，所以尝试多次使用同一个 @emph{fp} 调用 @ref{705,,dump()} 来序列化多个对象会产生一个不合规的 JSON 文件。
@end quotation
@end cartouche
@end deffn

@geindex dumps() (在 json 模块中)
@anchor{library/json json dumps}@anchor{706}
@deffn {函数} json.dumps (obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

使用这个 @ref{2a1d,,转换表} 将 @emph{obj} 序列化为 JSON 格式的 @ref{206,,str}。 其参数的含义与 @ref{705,,dump()} 中的相同。

@cartouche
@quotation 注解 
JSON 中的键-值对中的键永远是 @ref{206,,str} 类型的。当一个对象被转化为 JSON 时，字典中所有的键都会被强制转换为字符串。这所造成的结果是字典被转换为 JSON 然后转换回字典时可能和原来的不相等。换句话说，如果 x 具有非字符串的键，则有 @code{loads(dumps(x)) != x}。
@end quotation
@end cartouche
@end deffn

@geindex load() (在 json 模块中)
@anchor{library/json json load}@anchor{662}
@deffn {函数} json.load (fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

使用这个 @ref{2a1e,,转换表} 将 @emph{fp} (一个支持 @code{.read()} 并包含一个 JSON 文档的 @ref{1409,,text file} 或者 @ref{140a,,binary file}) 反序列化为一个 Python 对象。

@emph{object_hook} 是一个可选的函数，它会被调用于每一个解码出的对象字面量（即一个 @ref{164,,dict}）。@emph{object_hook} 的返回值会取代原本的 @ref{164,,dict}。这一特性能够被用于实现自定义解码器（如 JSON-RPC@footnote{http://www.jsonrpc.org} 的类型提示)。

@emph{object_pairs_hook} 是一个可选的函数，它会被调用于每一个有序列表对解码出的对象字面量。 @emph{object_pairs_hook} 的返回值将会取代原本的 @ref{164,,dict} 。这一特性能够被用于实现自定义解码器。如果 @emph{object_hook} 也被定义， @emph{object_pairs_hook} 优先。


在 3.1 版更改: 添加了对 @emph{object_pairs_hook} 的支持。


@emph{parse_float} ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调用。默认状态下，相当于 @code{float(num_str)} 。可以用于对 JSON 浮点数使用其它数据类型和语法分析程序 （比如 @ref{2c7,,decimal.Decimal} ）。

@emph{parse_int} ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。默认状态下，相当于 @code{int(num_str)} 。可以用于对 JSON 整数使用其它数据类型和语法分析程序 （比如 @ref{1fe,,float} ）。


在 3.9.14 版更改: The default @emph{parse_int} of @ref{205,,int()} now limits the maximum length of
the integer string via the interpreter's @ref{288,,integer string conversion length limitation} to help avoid denial
of service attacks.


@emph{parse_constant} ，如果指定，将要与以下字符串中的一个一同调用： @code{'-Infinity'} ， @code{'Infinity'} ， @code{'NaN'} 。如果遇到无效的 JSON 数字则可以使用它引发异常。


在 3.1 版更改: @emph{parse_constant} 不再调用 'null' ， 'true' ， 'false' 。


要使用自定义的 @ref{708,,JSONDecoder} 子类，用 @code{cls} 指定他；否则使用 @ref{708,,JSONDecoder} 。额外的关键词参数会通过类的构造函数传递。

如果反序列化的数据不是有效 JSON 文档，引发 @ref{801,,JSONDecodeError} 错误。


在 3.6 版更改: 所有的可选参数现在是 @ref{3d6,,keyword-only} 的了。



在 3.6 版更改: @emph{fp} 现在可以是 @ref{140a,,binary file} 。输入编码应当是 UTF-8 ， UTF-16 或者 UTF-32 。

@end deffn

@geindex loads() (在 json 模块中)
@anchor{library/json json loads}@anchor{226}
@deffn {函数} json.loads (s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

使用这个 @ref{2a1e,,转换表} 将 @emph{s} (一个包含 JSON 文档的 @ref{206,,str}, @ref{172,,bytes} 或 @ref{173,,bytearray} 实例) 反序列化为 Python 对象。

其他参数的含义与 @ref{662,,load()} 中的相同。

如果反序列化的数据不是有效 JSON 文档，引发 @ref{801,,JSONDecodeError} 错误。


在 3.6 版更改: @emph{s} 现在可以为 @ref{172,,bytes} 或 @ref{173,,bytearray} 类型。 输入编码应为 UTF-8, UTF-16 或 UTF-32。



在 3.9 版更改: 关键字参数 @emph{encoding} 已被移除。

@end deffn

@node 编码器和解码器,异常<13>,基本使用,json --- JSON 编码和解码器
@anchor{library/json encoders-and-decoders}@anchor{2a1f}
@subsubsection 编码器和解码器


@geindex JSONDecoder (json 中的类)
@anchor{library/json json JSONDecoder}@anchor{708}
@deffn {类} json.JSONDecoder (*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)

简单的JSON解码器。

默认情况下，解码执行以下翻译:
@anchor{library/json json-to-py-table}@anchor{2a1e}

@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} 
@headitem

JSON

@tab

Python

@item

object

@tab

dict

@item

array

@tab

list

@item

string

@tab

str

@item

number (int)

@tab

int

@item

number (real)

@tab

float

@item

true

@tab

True

@item

false

@tab

False

@item

null

@tab

None

@end multitable


它还将“NaN”、“Infinity”和“-Infinity”理解为它们对应的“float”值，这超出了JSON规范。

如果指定了 @emph{object_hook}，它将被调用并传入每个已解码 JSON 对象的结果，并且其返回值将被用来替代给定的 @ref{164,,dict}。 它可被用于提供自定义的反序列化操作（例如支持 JSON-RPC@footnote{http://www.jsonrpc.org} 类提示）。

如果指定了 @emph{object_pairs_hook} 则它将被调用并传入以对照值有序列表进行解码的每个 JSON 对象的结果。 @emph{object_pairs_hook} 的结果值将被用来替代 @ref{164,,dict}。 这一特性可被用于实现自定义解码器。 如果还定义了 @emph{object_hook}，则 @emph{object_pairs_hook} 的优先级更高。


在 3.1 版更改: 添加了对 @emph{object_pairs_hook} 的支持。


@emph{parse_float} ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调用。默认状态下，相当于 @code{float(num_str)} 。可以用于对 JSON 浮点数使用其它数据类型和语法分析程序 （比如 @ref{2c7,,decimal.Decimal} ）。

@emph{parse_int} ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。默认状态下，相当于 @code{int(num_str)} 。可以用于对 JSON 整数使用其它数据类型和语法分析程序 （比如 @ref{1fe,,float} ）。

@emph{parse_constant} ，如果指定，将要与以下字符串中的一个一同调用： @code{'-Infinity'} ， @code{'Infinity'} ， @code{'NaN'} 。如果遇到无效的 JSON 数字则可以使用它引发异常。

如果 @emph{strict} 为 false （默认为 @code{True} ），那么控制字符将被允许在字符串内。在此上下文中的控制字符编码在范围 0--31 内的字符，包括 @code{'\t'} (制表符）， @code{'\n'} ， @code{'\r'} 和 @code{'\0'} 。

如果反序列化的数据不是有效 JSON 文档，引发 @ref{801,,JSONDecodeError} 错误。


在 3.6 版更改: 所有形参现在都是 @ref{3d6,,仅限关键字参数}。


@geindex decode() (json.JSONDecoder 方法)
@anchor{library/json json JSONDecoder decode}@anchor{2a20}
@deffn {方法} decode (s)

返回 @emph{s} 的 Python 表示形式（包含一个 JSON 文档的 @ref{206,,str} 实例）。

如果给定的 JSON 文档无效则将引发 @ref{801,,JSONDecodeError}。
@end deffn

@geindex raw_decode() (json.JSONDecoder 方法)
@anchor{library/json json JSONDecoder raw_decode}@anchor{2a21}
@deffn {方法} raw_decode (s)

从 @emph{s} 中解码出 JSON 文档（以 JSON 文档开头的一个 @ref{206,,str} 对象）并返回一个 Python 表示形式为 2 元组以及指明该文档在 @emph{s} 中结束位置的序号。

这可以用于从一个字符串解码JSON文档，该字符串的末尾可能有无关的数据。
@end deffn
@end deffn

@geindex JSONEncoder (json 中的类)
@anchor{library/json json JSONEncoder}@anchor{707}
@deffn {类} json.JSONEncoder (*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

用于Python数据结构的可扩展JSON编码器。

默认支持以下对象和类型：
@anchor{library/json py-to-json-table}@anchor{2a1d}

@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

Python

@tab

JSON

@item

dict

@tab

object

@item

list, tuple

@tab

array

@item

str

@tab

string

@item

int, float, int 和 float 派生的枚举

@tab

number

@item

True

@tab

true

@item

False

@tab

false

@item

None

@tab

null

@end multitable



在 3.4 版更改: 添加了对 int 和 float 派生的枚举类的支持


为了将其拓展至识别其他对象，需要子类化并实现 @ref{2a22,,default()} 方法于另一种返回 @code{o} 的可序列化对象的方法如果可行，否则它应该调用超类实现（来引发 @ref{1ff,,TypeError} ）。

如果 @emph{skipkeys} 为假值（默认），则当尝试对非 @ref{206,,str}, @ref{205,,int}, @ref{1fe,,float} 或 @code{None} 的键进行编码时将会引发 @ref{1ff,,TypeError}。 如果 @emph{skipkeys} 为真值，这些条目将被直接跳过。

如果 @emph{ensure_ascii} 是 true （即默认值），输出保证将所有输入的非 ASCII 字符转义。如果 @emph{ensure_ascii} 是 false，这些字符会原样输出。

如果 @emph{check_circular} 为 true （默认），那么列表，字典，和自定义编码的对象在编码期间会被检查重复循环引用防止无限递归（无限递归将导致 @ref{731,,RecursionError} ）。否则，这样进行检查。

如果 @emph{allow_nan} 为 true （默认），那么 @code{NaN} ， @code{Infinity} ，和 @code{-Infinity} 进行编码。此行为不符合 JSON 规范，但与大多数的基于 Javascript 的编码器和解码器一致。否则，它将是一个 @ref{16d,,ValueError} 来编码这些浮点数。

如果 @emph{sort_keys} 为 true （默认为： @code{False} ），那么字典的输出是按照键排序；这对回归测试很有用，以确保可以每天比较 JSON 序列化。

如果 @emph{indent} 是一个非负整数或者字符串，那么 JSON 数组元素和对象成员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者 @code{""}，则只会添加换行符。 @code{None} (默认值) 选择最紧凑的表达。 使用一个正整数会让每一层缩进同样数量的空格。 如果 @emph{indent} 是一个字符串 (比如 @code{"\t"})，那个字符串会被用于缩进每一层。


在 3.2 版更改: 允许使用字符串作为 @emph{indent} 而不再仅仅是整数。


当指定时，@emph{separators} 应当是一个 @code{(item_separator, key_separator)} 元组。当 @emph{indent} 为 @code{None} 时，默认值取 @code{(', ', ': ')}，否则取 @code{(',', ': ')}。为了得到最紧凑的 JSON 表达式，你应该指定其为 @code{(',', ':')} 以消除空白字符。


在 3.4 版更改: 现当 @emph{indent} 不是 @code{None} 时，采用 @code{(',', ': ')} 作为默认值。


当 @emph{default} 被指定时，其应该是一个函数，每当某个对象无法被序列化时它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一个 @ref{1ff,,TypeError}。如果没有被指定，则会直接引发 @ref{1ff,,TypeError}。


在 3.6 版更改: 所有形参现在都是 @ref{3d6,,仅限关键字参数}。


@geindex default() (json.JSONEncoder 方法)
@anchor{library/json json JSONEncoder default}@anchor{2a22}
@deffn {方法} default (o)

在子类中实现这种方法使其返回 @emph{o} 的可序列化对象，或者调用基础实现（引发 @ref{1ff,,TypeError} ）。

例如，为了支持任意的迭代器，你可以这样来实现 @ref{2a22,,default()}:

@example
def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)
@end example
@end deffn

@geindex encode() (json.JSONEncoder 方法)
@anchor{library/json json JSONEncoder encode}@anchor{2a23}
@deffn {方法} encode (o)

返回 Python @emph{o} 数据结构的 JSON 字符串表达方式。例如:

@example
>>> json.JSONEncoder().encode(@{"foo": ["bar", "baz"]@})
'@{"foo": ["bar", "baz"]@}'
@end example
@end deffn

@geindex iterencode() (json.JSONEncoder 方法)
@anchor{library/json json JSONEncoder iterencode}@anchor{2a24}
@deffn {方法} iterencode (o)

编码给定对象 @emph{o} ，并且让每个可用的字符串表达方式。例如:

@example
for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
@end example
@end deffn
@end deffn

@node 异常<13>,标准符合性和互操作性,编码器和解码器,json --- JSON 编码和解码器
@anchor{library/json exceptions}@anchor{2a25}
@subsubsection 异常


@geindex JSONDecodeError
@anchor{library/json json JSONDecodeError}@anchor{801}
@deffn {例外} json.JSONDecodeError (msg, doc, pos)

拥有以下附加属性的 @ref{16d,,ValueError} 的子类：

@geindex msg (json.JSONDecodeError 属性)
@anchor{library/json json JSONDecodeError msg}@anchor{2a26}
@deffn {属性} msg

未格式化的错误消息。
@end deffn

@geindex doc (json.JSONDecodeError 属性)
@anchor{library/json json JSONDecodeError doc}@anchor{2a27}
@deffn {属性} doc

正在解析的 JSON 文档。
@end deffn

@geindex pos (json.JSONDecodeError 属性)
@anchor{library/json json JSONDecodeError pos}@anchor{2a28}
@deffn {属性} pos

The start index of @emph{doc} where parsing failed.
@end deffn

@geindex lineno (json.JSONDecodeError 属性)
@anchor{library/json json JSONDecodeError lineno}@anchor{2a29}
@deffn {属性} lineno

The line corresponding to @emph{pos}.
@end deffn

@geindex colno (json.JSONDecodeError 属性)
@anchor{library/json json JSONDecodeError colno}@anchor{2a2a}
@deffn {属性} colno

The column corresponding to @emph{pos}.
@end deffn


3.5 新版功能.

@end deffn

@node 标准符合性和互操作性,命令行界面<4>,异常<13>,json --- JSON 编码和解码器
@anchor{library/json standard-compliance-and-interoperability}@anchor{2a2b}
@subsubsection 标准符合性和互操作性


JSON 格式由 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://tools.ietf.org/html/rfc7159.html} 和 ECMA-404@footnote{http://www.ecma-international.org/publications/standards/Ecma-404.htm} 指定。此段落详细讲了这个模块符合 RFC 的级别。简单来说， @ref{707,,JSONEncoder} 和 @ref{708,,JSONDecoder} 子类，和明确提到的参数以外的参数，不作考虑。

此模块不严格遵循于 RFC ，它实现了一些扩展是有效的 Javascript 但不是有效的 JSON。尤其是：


@itemize -

@item 
无限和 NaN 数值是被接受并输出；

@item 
对象内的重复名称是接受的，并且仅使用最后一对属性-值对的值。
@end itemize

自从 RFC 允许符合 RFC 的语法分析程序接收 不符合 RFC 的输入文本以来，这个模块的解串器在默认状态下默认符合 RFC 。

@menu
* 字符编码:: 
* Infinite 和 NaN 数值:: 
* 对象中的重复名称:: 
* 顶级非对象，非数组值:: 
* 实现限制:: 

@end menu

@node 字符编码,Infinite 和 NaN 数值,,标准符合性和互操作性
@anchor{library/json character-encodings}@anchor{2a2c}
@subsubsection 字符编码


RFC 要求使用 UTF-8 ， UTF-16 ，或 UTF-32 之一来表示 JSON ，为了最大互通性推荐使用 UTF-8 。

RFC允许，尽管不是必须的，这个模块的序列化默认设置为 @emph{ensure_ascii=True} ，这样消除输出以便结果字符串至容纳 ASCII 字符。

@emph{ensure_ascii} 参数以外，此模块是严格的按照在 Python 对象和 @ref{206,,Unicode strings} 间的转换定义的，并且因此不能直接解决字符编码的问题。

RFC 禁止添加字符顺序标记（ BOM ）在 JSON 文本的开头，这个模块的序列化器不添加 BOM 标记在它的输出上。 RFC，准许 JSON 反序列化器忽略它们输入中的初始 BOM 标记，但不要求。此模块的反序列化器引发 @ref{16d,,ValueError} 当存在初始 BOM 标记。

RFC 不会明确禁止包含字节序列的 JSON 字符串这不对应有效的 Unicode 字符（比如 不成对的 UTF-16 的替代物），但是它确实指出它们可能会导致互操作性问题。默认下，模块对这样的序列接受和输出（当在原始 @ref{206,,str} 存在时）代码点。

@node Infinite 和 NaN 数值,对象中的重复名称,字符编码,标准符合性和互操作性
@anchor{library/json infinite-and-nan-number-values}@anchor{2a2d}
@subsubsection Infinite 和 NaN 数值


RFC 不允许 infinite 或者 NaN 数值的表达方式。尽管这样，默认情况下，此模块接受并且输出 @code{Infinity} ， @code{-Infinity}，和 @code{NaN} 好像它们是有效的JSON数字字面值

@example
>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan
@end example

序列化器中， @emph{allow_nan} 参数可用于替代这个行为。反序列化器中， @emph{parse_constant} 参数，可用于替代这个行为。

@node 对象中的重复名称,顶级非对象，非数组值,Infinite 和 NaN 数值,标准符合性和互操作性
@anchor{library/json repeated-names-within-an-object}@anchor{2a2e}
@subsubsection 对象中的重复名称


RFC 具体说明了 在 JSON对象里的名字应该是唯一的，但没有规定如何处理JSON对象中的重复名称。默认下，此模块不引发异常；作为替代，对于给定名它将忽略除姓-值对之外的所有对:

@example
>>> weird_json = '@{"x": 1, "x": 2, "x": 3@}'
>>> json.loads(weird_json)
@{'x': 3@}
@end example

The @emph{object_pairs_hook} parameter can be used to alter this behavior.

@node 顶级非对象，非数组值,实现限制,对象中的重复名称,标准符合性和互操作性
@anchor{library/json top-level-non-object-non-array-values}@anchor{2a2f}
@subsubsection 顶级非对象，非数组值


过时的 
@geindex RFC; RFC 4627
RFC 4627@footnote{https://tools.ietf.org/html/rfc4627.html} 指定的旧版本 JSON 要求 JSON 文本顶级值必须是 JSON 对象或数组（ Python @ref{164,,dict} 或 @ref{1f9,,list} ），并且不能是 JSON null 值，布尔值，数值或者字符串值。 
@geindex RFC; RFC 7159
RFC 7159@footnote{https://tools.ietf.org/html/rfc7159.html} 移除这个限制，此模块没有并且从未在序列化器和反序列化器中实现这个限制。

无论如何，为了最大化地获取互操作性，你可能希望自己遵守该原则。

@node 实现限制,,顶级非对象，非数组值,标准符合性和互操作性
@anchor{library/json implementation-limitations}@anchor{2a30}
@subsubsection 实现限制


一些 JSON 反序列化器的实现应该在以下方面做出限制：


@itemize *

@item 
可接受的 JSON 文本大小

@item 
嵌套 JSON 对象和数组的最高水平

@item 
JSON 数字的范围和精度

@item 
JSON 字符串的内容和最大长度
@end itemize

此模块不强制执行任何上述限制，除了相关的 Python 数据类型本身或者 Python 解释器本身的限制以外。

当序列化为 JSON ，在应用中当心此类限制这可能破坏你的 JSON 。特别是，通常将 JSON 数字反序列化为 IEEE 754 双精度数字，从而受到该表示方式的范围和精度限制。这是特别相关的，当序列化非常大的 Python @ref{205,,int} 值时，或者当序列化 "exotic" 数值类型的实例时比如 @ref{2c7,,decimal.Decimal} 。

@node 命令行界面<4>,,标准符合性和互操作性,json --- JSON 编码和解码器
@anchor{library/json command-line-interface}@anchor{2a31}@anchor{library/json json-commandline}@anchor{2a1b}@anchor{library/json module-json tool}@anchor{a5}
@subsubsection 命令行界面


@geindex json.tool (模块)

@strong{源代码：} Lib/json/tool.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/json/tool.py}


__________________________________________________________________


The @ref{a5,,json.tool} module provides a simple command line interface to validate
and pretty-print JSON objects.

如果未指定可选的 @code{infile} 和 @code{outfile} 参数，则将分别使用 @ref{427,,sys.stdin} 和 @ref{428,,sys.stdout}:

@example
$ echo '@{"json": "obj"@}' | python -m json.tool
@{
    "json": "obj"
@}
$ echo '@{1.2:3.4@}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
@end example


在 3.5 版更改: 输出现在将与输入顺序保持一致。 请使用 @ref{2a32,,--sort-keys} 选项来将输出按照键的字母顺序排序。


@menu
* 命令行选项: 命令行选项<4>. 

@end menu

@node 命令行选项<4>,,,命令行界面<4>
@anchor{library/json command-line-options}@anchor{2a33}
@subsubsection 命令行选项


@geindex json.tool command line option; infile
@anchor{library/json cmdoption-json-tool-arg-infile}@anchor{2a34}
@deffn {程序选项} infile

要被验证或美化打印的 JSON 文件：

@example
$ python -m json.tool mp_films.json
[
    @{
        "title": "And Now for Something Completely Different",
        "year": 1971
    @},
    @{
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    @}
]
@end example

如果 @emph{infile} 未指定，则从 @ref{427,,sys.stdin} 读取。
@end deffn

@geindex json.tool command line option; outfile
@anchor{library/json cmdoption-json-tool-arg-outfile}@anchor{2a35}
@deffn {程序选项} outfile

将 @emph{infile} 输出写入到给定的 @emph{outfile}。 在其他情况下写入到 @ref{428,,sys.stdout}。
@end deffn

@geindex json.tool command line option; --sort-keys
@anchor{library/json cmdoption-json-tool-sort-keys}@anchor{2a32}
@deffn {程序选项} @w{-}@w{-}sort@w{-}keys

将字典输出按照键的字母顺序排序。


3.5 新版功能.

@end deffn

@geindex json.tool command line option; --no-ensure-ascii
@anchor{library/json cmdoption-json-tool-no-ensure-ascii}@anchor{2a36}
@deffn {程序选项} @w{-}@w{-}no@w{-}ensure@w{-}ascii

禁用非 ASCII 字符的转义，详情参见 @ref{706,,json.dumps()}。


3.9 新版功能.

@end deffn

@geindex json.tool command line option; --json-lines
@anchor{library/json cmdoption-json-tool-json-lines}@anchor{2a37}
@deffn {程序选项} @w{-}@w{-}json@w{-}lines

将每个输入行解析为单独的 JSON 对象。


3.8 新版功能.

@end deffn

@geindex json.tool command line option; --indent
@geindex json.tool command line option; --tab
@geindex json.tool command line option; --no-indent
@geindex json.tool command line option; --compact
@anchor{library/json cmdoption-json-tool-indent}@anchor{2a38}
@deffn {程序选项} @w{-}@w{-}indent, @w{-}@w{-}tab, @w{-}@w{-}no@w{-}indent, @w{-}@w{-}compact

用于空白符控制的互斥选项。


3.9 新版功能.

@end deffn

@geindex json.tool command line option; -h
@geindex json.tool command line option; --help
@anchor{library/json cmdoption-json-tool-h}@anchor{2a39}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

显示帮助消息。
@end deffn

@node mailbox --- 操作多种格式的邮箱,mimetypes --- 映射文件名到 MIME 类型,json --- JSON 编码和解码器,互联网数据处理
@anchor{library/mailbox doc}@anchor{2a3a}@anchor{library/mailbox mailbox-manipulate-mailboxes-in-various-formats}@anchor{2a3b}@anchor{library/mailbox module-mailbox}@anchor{ae}
@subsection @code{mailbox} --- 操作多种格式的邮箱


@geindex mailbox (模块)

@strong{源代码：} Lib/mailbox.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/mailbox.py}


__________________________________________________________________


本模块定义了两个类，@ref{cb9,,Mailbox} 和 @ref{cbd,,Message}，用于访问和操作磁盘中的邮箱及其所包含的电子邮件。 @ref{cb9,,Mailbox} 提供了类似字典的从键到消息的映射。 @ref{cbd,,Message} 为 @ref{70,,email.message} 模块的 @ref{644,,Message} 类增加了特定格式专属的状态和行为。 支持的邮箱格式有 Maildir, mbox, MH, Babyl 以及 MMDF。


@subsubheading 参见



@table @asis

@item 模块 @ref{67,,email}

表示和操作邮件消息。
@end table


@menu
* Mailbox 对象:: 
* Message 对象:: 
* 异常: 异常<14>. 
* 示例: 示例<27>. 

@end menu

@node Mailbox 对象,Message 对象,,mailbox --- 操作多种格式的邮箱
@anchor{library/mailbox id1}@anchor{2a3c}@anchor{library/mailbox mailbox-objects}@anchor{2a3d}
@subsubsection @code{Mailbox} 对象


@geindex Mailbox (mailbox 中的类)
@anchor{library/mailbox mailbox Mailbox}@anchor{cb9}
@deffn {类} mailbox.Mailbox

一个邮箱，它可以被检视和修改。

@ref{cb9,,Mailbox} 类定义了一个接口并且它不应被实例化。 而是应该让格式专属的子类继承 @ref{cb9,,Mailbox} 并且你的代码应当实例化一个特定的子类。

@ref{cb9,,Mailbox} 接口类似于字典，其中每个小键都有对应的消息。 键是由 @ref{cb9,,Mailbox} 实例发出的，它们将由实例来使用并且只对该 @ref{cb9,,Mailbox} 实例有意义。 键会持续标识一条消息，即使对应的消息已被修改，例如被另一条消息所替代。

可以使用 set 型方法 @ref{cb8,,add()} 将消息添加到 @ref{cb9,,Mailbox} 并可以使用 @code{del} 语句或 set 型方法 @ref{2a3e,,remove()} 和 @ref{2a3f,,discard()} 将其移除。

@ref{cb9,,Mailbox} 接口语义在某些值得注意的方面与字典语义有所不同。 每次请求消息时，都会基于邮箱的当前状态生成一个新的表示形式（通常为 @ref{cbd,,Message} 实例）。 类似地，当向 @ref{cb9,,Mailbox} 实例添加消息时，所提供的消息表示形式的内容将被复制。 无论在哪种情况下 @ref{cb9,,Mailbox} 实例都不会保留对消息表示形式的引用。

默认的 @ref{cb9,,Mailbox} 迭代器会迭代消息表示形式，而不像默认的字典迭代器那样迭代键。 此外，在迭代期间修改邮箱是安全且有明确定义的。 在创建迭代器之后被添加到邮箱的消息将对该迭代不可见。 在迭代器产出消息之前被从邮箱移除的消息将被静默地跳过，但是使用来自迭代器的键也有可能导致 @ref{3f1,,KeyError} 异常，如果对应的消息后来被移除的话。

@cartouche
@quotation 警告 
在修改可能同时被其他某个进程修改的邮箱时要非常小心。 用于此种任务的最安全邮箱格式是 Maildir；请尽量避免使用 mbox 之类的单文件格式进行并发写入。 如果你正在修改一个邮箱，你 @emph{必须} 在读取文件中的任何消息或者执行添加或删除消息等修改操作 @emph{之前} 通过调用 @ref{2a40,,lock()} 以及 @ref{2a41,,unlock()} 方法来锁定它。 如果未锁定邮箱则将导致丢失消息或损坏整个邮箱的风险。
@end quotation
@end cartouche

@ref{cb9,,Mailbox} 实例具有下列方法:

@geindex add() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox add}@anchor{cb8}
@deffn {方法} add (message)

将 @emph{message} 添加到邮箱并返回分配给它的键。

形参 @emph{message} 可以是 @ref{cbd,,Message} 实例、@ref{644,,email.message.Message} 实例、字符串、字节串或文件类对象（应当以二进制模式打开）。 如果 @emph{message} 是适当的格式专属 @ref{cbd,,Message} 子类的实例（举例来说，如果它是一个 @ref{2915,,mboxMessage} 实例而这是一个 @ref{2a42,,mbox} 实例），将使用其格式专属的信息。 在其他情况下，则会使用合理的默认值作为格式专属的信息。


在 3.2 版更改: 增加了对二进制输入的支持。

@end deffn

@geindex remove() (mailbox.Mailbox 方法)
@geindex __delitem__() (mailbox.Mailbox 方法)
@geindex discard() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox remove}@anchor{2a3e}
@deffn {方法} remove (key)
@anchor{library/mailbox mailbox Mailbox __delitem__}@anchor{2a43}
@deffnx {方法} __delitem__ (key)
@anchor{library/mailbox mailbox Mailbox discard}@anchor{2a3f}
@deffnx {方法} discard (key)

从邮箱中删除对应于 @emph{key} 的消息。

当消息不存在时，如果此方法是作为 @ref{2a3e,,remove()} 或 @ref{2a43,,__delitem__()} 调用则会引发 @ref{3f1,,KeyError} 异常，而如果此方法是作为 @ref{2a3f,,discard()} 调用则不会引发异常。 如果下层邮箱格式支持来自其他进程的并发修改则 @ref{2a3f,,discard()} 的行为可能是更为适合的。
@end deffn

@geindex __setitem__() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox __setitem__}@anchor{2a44}
@deffn {方法} __setitem__ (key, message)

将 @emph{key} 所对应的消息替换为 @emph{message}。 如果没有与 @emph{key} 所对应的消息则会引发 @ref{3f1,,KeyError} 异常。

与 @ref{cb8,,add()} 一样，形参 @emph{message} 可以是 @ref{cbd,,Message} 实例、@ref{644,,email.message.Message} 实例、字符串、字节串或文件类对象（应当以二进制模式打开）。 如果 @emph{message} 是适当的格式专属 @ref{cbd,,Message} 子类的实例（举例来说，如果它是一个 @ref{2915,,mboxMessage} 实例而这是一个 @ref{2a42,,mbox} 实例），将使用其格式专属的信息。 在其他情况下，当前与 @emph{key} 所对应的消息的格式专属信息则会保持不变。
@end deffn

@geindex iterkeys() (mailbox.Mailbox 方法)
@geindex keys() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox iterkeys}@anchor{2a45}
@deffn {方法} iterkeys ()
@anchor{library/mailbox mailbox Mailbox keys}@anchor{2a46}
@deffnx {方法} keys ()

如果通过 @ref{2a45,,iterkeys()} 调用则返回一个迭代所有键的迭代器，或者如果通过 @ref{2a46,,keys()} 调用则返回一个键列表。
@end deffn

@geindex itervalues() (mailbox.Mailbox 方法)
@geindex __iter__() (mailbox.Mailbox 方法)
@geindex values() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox itervalues}@anchor{2a47}
@deffn {方法} itervalues ()
@anchor{library/mailbox mailbox Mailbox __iter__}@anchor{2a48}
@deffnx {方法} __iter__ ()
@anchor{library/mailbox mailbox Mailbox values}@anchor{2a49}
@deffnx {方法} values ()

如果通过 @ref{2a47,,itervalues()} 或 @ref{2a48,,__iter__()} 调用则返回一个迭代所有消息的表示形式的迭代器，或者如果通过 @ref{2a49,,values()} 调用则返回一个由这些表示形式组成的列表。 消息会被表示为适当的格式专属 @ref{cbd,,Message} 子类的实例，除非当 @ref{cb9,,Mailbox} 实例被初始化时指定了自定义的消息工厂函数。

@cartouche
@quotation 注解 
@ref{2a48,,__iter__()} 的行为与字典不同，后者是对键进行迭代。
@end quotation
@end cartouche
@end deffn

@geindex iteritems() (mailbox.Mailbox 方法)
@geindex items() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox iteritems}@anchor{2a4a}
@deffn {方法} iteritems ()
@anchor{library/mailbox mailbox Mailbox items}@anchor{2a4b}
@deffnx {方法} items ()

如果通过 @ref{2a4a,,iteritems()} 调用则返回一个迭代 (@emph{key}, @emph{message}) 对的迭代器，其中 @emph{key} 为键而 @emph{message} 为消息的表示形式，或者如果通过 @ref{2a4b,,items()} 调用则返回一个由这种键值对组成的列表。 消息会被表示为适当的格式专属 @ref{cbd,,Message} 子类的实例，除非当 @ref{cb9,,Mailbox} 实例被初始化时指定了自定义的消息工厂函数。
@end deffn

@geindex get() (mailbox.Mailbox 方法)
@geindex __getitem__() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox get}@anchor{2a4c}
@deffn {方法} get (key, default=None)
@anchor{library/mailbox mailbox Mailbox __getitem__}@anchor{2a4d}
@deffnx {方法} __getitem__ (key)

返回对应于 @emph{key} 的消息的表示形式。 当对应的消息不存在时，如果通过 @ref{2a4c,,get()} 调用则返回 @emph{default} 而如果通过 @ref{2a4d,,__getitem__()} 调用此方法则会引发 @ref{3f1,,KeyError} 异常。 消息会被表示为适当的格式专属 @ref{cbd,,Message} 子类的实例，除非当 @ref{cb9,,Mailbox} 实例被初始化时指定了自定义的消息工厂函数。
@end deffn

@geindex get_message() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox get_message}@anchor{2a4e}
@deffn {方法} get_message (key)

将对应于 @emph{key} 的消息的表示形式作为适当的格式专属 @ref{cbd,,Message} 子类的实例返回，或者如果对应的消息不存在则会引发 @ref{3f1,,KeyError} 异常。
@end deffn

@geindex get_bytes() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox get_bytes}@anchor{cbb}
@deffn {方法} get_bytes (key)

返回对应于 @emph{key} 的消息的字节表示形式，或者如果对应的消息不存在则会引发 @ref{3f1,,KeyError} 异常。


3.2 新版功能.

@end deffn

@geindex get_string() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox get_string}@anchor{cbc}
@deffn {方法} get_string (key)

返回对应于 @emph{key} 的消息的字符串表示形式，或者如果对应的消息不存在则会引发 @ref{3f1,,KeyError} 异常。 消息是通过 @ref{644,,email.message.Message} 处理来将其转换为纯 7bit 表示形式的。
@end deffn

@geindex get_file() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox get_file}@anchor{cba}
@deffn {方法} get_file (key)

返回对应于 @emph{key} 的消息的文件类表示形式，或者如果对应的消息不存在则会引发 @ref{3f1,,KeyError} 异常。 文件类对象的行为相当于以二进制模式打开。 当不再需要此文件时应当将其关闭。


在 3.2 版更改: 此文件对象实际上是二进制文件；之前它被不正确地以文本模式返回。 并且，此文件类对象现在还支持上下文管理协议：你可以使用 @ref{7e4,,with} 语句来自动关闭它。


@cartouche
@quotation 注解 
不同于其他消息表示形式，文件类表示形式并不一定独立于创建它们的 @ref{cb9,,Mailbox} 实例或下层的邮箱。 每个子类都会提供更具体的文档。
@end quotation
@end cartouche
@end deffn

@geindex __contains__() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox __contains__}@anchor{2a4f}
@deffn {方法} __contains__ (key)

如果 @emph{key} 有对应的消息则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex __len__() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox __len__}@anchor{2a50}
@deffn {方法} __len__ ()

返回邮箱中消息的数量。
@end deffn

@geindex clear() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox clear}@anchor{2a51}
@deffn {方法} clear ()

从邮箱中删除所有消息。
@end deffn

@geindex pop() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox pop}@anchor{2a52}
@deffn {方法} pop (key, default=None)

返回对应于 @emph{key} 的消息的表示形式并删除该消息。 如果对应的消息不存在则返回 @emph{default}。 消息会被表示为适当的格式专属 @ref{cbd,,Message} 子类的实例，除非当 @ref{cb9,,Mailbox} 实例被初始化时指定了自定义的消息工厂函数。
@end deffn

@geindex popitem() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox popitem}@anchor{2a53}
@deffn {方法} popitem ()

返回一个任意的 (@emph{key}, @emph{message}) 对，其中 @emph{key} 为键而 @emph{message} 为消息的表示形式，并删除对应的消息。 如果邮箱为空，则会引发 @ref{3f1,,KeyError} 异常。 消息会被表示为适当的格式专属 @ref{cbd,,Message} 子类的实例，除非当 @ref{cb9,,Mailbox} 实例被初始化时指定了自定义的消息工厂函数。
@end deffn

@geindex update() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox update}@anchor{2a54}
@deffn {方法} update (arg)

形参 @emph{arg} 应当是 @emph{key} 到 @emph{message} 的映射或 (@emph{key}, @emph{message}) 对的可迭代对象。 用来更新邮箱以使得对于每个给定的 @emph{key} 和 @emph{message}，与 @emph{key} 相对应的消息会被设为 @emph{message}，就像通过使用 @ref{2a44,,__setitem__()} 一样。 类似于 @ref{2a44,,__setitem__()}，每个 @emph{key} 都必须在邮箱中有一个对应的消息否则将会引发 @ref{3f1,,KeyError} 异常，因此在通常情况下将 @emph{arg} 设为 @ref{cb9,,Mailbox} 实例是不正确的。

@cartouche
@quotation 注解 
与字典不同，关键字参数是不受支持的。
@end quotation
@end cartouche
@end deffn

@geindex flush() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox flush}@anchor{2a55}
@deffn {方法} flush ()

将所有待定的更改写入到文件系统。 对于某些 @ref{cb9,,Mailbox} 子类来说，更改总是被立即写入因而 @ref{2a55,,flush()} 并不会做任何事，但您仍然应当养成调用此方法的习惯。
@end deffn

@geindex lock() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox lock}@anchor{2a40}
@deffn {方法} lock ()

在邮箱上获取一个独占式咨询锁以使其他进程知道不能修改它。 如果锁无法被获取则会引发 @ref{2a56,,ExternalClashError}。 所使用的具体锁机制取决于邮箱的格式。 在对邮箱内容进行任何修改之前你应当 @emph{总是} 锁定它。
@end deffn

@geindex unlock() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox unlock}@anchor{2a41}
@deffn {方法} unlock ()

释放邮箱上的锁，如果存在的话。
@end deffn

@geindex close() (mailbox.Mailbox 方法)
@anchor{library/mailbox mailbox Mailbox close}@anchor{2a57}
@deffn {方法} close ()

刷新邮箱，如果必要则将其解锁。 并关闭所有打开的文件。 对于某些 @ref{cb9,,Mailbox} 子类来说，此方法并不会做任何事。
@end deffn
@end deffn

@menu
* Maildir:: 
* mbox:: 
* MH:: 
* Babyl:: 
* MMDF:: 

@end menu

@node Maildir,mbox,,Mailbox 对象
@anchor{library/mailbox mailbox-maildir}@anchor{2a58}@anchor{library/mailbox maildir}@anchor{2a59}
@subsubsection @code{Maildir}


@geindex Maildir (mailbox 中的类)
@anchor{library/mailbox mailbox Maildir}@anchor{d78}
@deffn {类} mailbox.Maildir (dirname, factory=None, create=True)

@ref{cb9,,Mailbox} 的一个子类，用于 Maildir 格式的邮箱。 形参 @emph{factory} 是一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制模式打开）并返回一个自定义的表示形式。 如果 @emph{factory} 为 @code{None}，则会使用 @ref{2a5a,,MaildirMessage} 作为默认的消息表示形式。 如果 @emph{create} 为 @code{True}，则当邮箱不存在时会创建它。

如果 @emph{create} 为 @code{True} 且 @emph{dirname} 路径存在，它将被视为已有的 maildir 而无需尝试验证其目录布局。

使用 @emph{dirname} 这个名称而不使用 @emph{path} 是出于历史原因。

Maildir 是一种基于目录的邮箱格式，它是针对 qmail 邮件传输代理而发明的，现在也得到了其他程序的广泛支持。 Maildir 邮箱中的消息存储在一个公共目录结构中的单独文件内。 这样的设计允许 Maildir 邮箱被多个彼此无关的程序访问和修改而不会导致数据损坏，因此文件锁定操作是不必要的。

Maildir 邮箱包含三个子目录，分别是: @code{tmp}, @code{new} 和 @code{cur}。 消息会不时地在 @code{tmp} 子目录中创建然后移至 @code{new} 子目录来结束投递。 后续电子邮件客户端可能将消息移至 @code{cur} 子目录并将有关消息状态的信息存储在附带到其文件名的特殊 "info" 小节中。

Courier 电子邮件传输代理所引入的文件夹风格也是受支持的。 主邮箱中任何子目录只要其名称的第一个字符是 @code{'.'} 就会被视为文件夹。 文件夹名称会被 @ref{d78,,Maildir} 表示为不带前缀 @code{'.'} 的形式。 每个文件夹自身都是一个 Maildir 邮箱但不应包含其他文件夹。 逻辑嵌套关系是使用 @code{'.'} 来划定层级，例如 "Archived.2005.07"。

@cartouche
@quotation 注解 
Maildir 规范要求使用在特定消息文件名中使用冒号 (@code{':'})。 但是，某些操作系统不允许将此字符用于文件名，如果你希望在这些操作系统上使用类似 Maildir 的格式，你应当指定改用另一个字符。 叹号 (@code{'!'}) 是一个受欢迎的选择。 例如:

@example
import mailbox
mailbox.Maildir.colon = '!'
@end example

@code{colon} 属性也可以在每个实例上分别设置。
@end quotation
@end cartouche

@ref{d78,,Maildir} 实例具有 @ref{cb9,,Mailbox} 的所有方法及下列附加方法:

@geindex list_folders() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir list_folders}@anchor{2a5b}
@deffn {方法} list_folders ()

返回所有文件夹名称的列表。
@end deffn

@geindex get_folder() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir get_folder}@anchor{2a5c}
@deffn {方法} get_folder (folder)

返回表示名称为 @emph{folder} 的文件夹的 @ref{d78,,Maildir} 实例。 如果文件夹不存在则会引发 @ref{2a5d,,NoSuchMailboxError} 异常。
@end deffn

@geindex add_folder() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir add_folder}@anchor{2a5e}
@deffn {方法} add_folder (folder)

创建名称为 @emph{folder} 的文件夹并返回表示它的 @ref{d78,,Maildir} 实例。
@end deffn

@geindex remove_folder() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir remove_folder}@anchor{2a5f}
@deffn {方法} remove_folder (folder)

删除名称为 @emph{folder} 的文件夹。 如果文件夹包含任何消息，则将引发 @ref{2a60,,NotEmptyError} 异常且该文件夹将不会被删除。
@end deffn

@geindex clean() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir clean}@anchor{2a61}
@deffn {方法} clean ()

从邮箱中删除最近 36 小时内未被访问过的临时文件。 Maildir 规范要求邮件阅读程序应当时常进行此操作。
@end deffn

@ref{d78,,Maildir} 所实现的某些 @ref{cb9,,Mailbox} 方法值得进行特别的说明:

@geindex add() (mailbox.Maildir 方法)
@geindex __setitem__() (mailbox.Maildir 方法)
@geindex update() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir add}@anchor{2a62}
@deffn {方法} add (message)
@anchor{library/mailbox mailbox Maildir __setitem__}@anchor{2a63}
@deffnx {方法} __setitem__ (key, message)
@anchor{library/mailbox mailbox Maildir update}@anchor{2a64}
@deffnx {方法} update (arg)

@cartouche
@quotation 警告 
这些方法会基于当前进程 ID 来生成唯一文件名。 当使用多线程时，可能发生未被检测到的名称冲突并导致邮箱损坏，除非是对线程进行协调以避免使用这些方法同时操作同一个邮箱。
@end quotation
@end cartouche
@end deffn

@geindex flush() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir flush}@anchor{2a65}
@deffn {方法} flush ()

对 Maildir 邮箱的所有更改都会立即被应用，所以此方法并不会做任何事情。
@end deffn

@geindex lock() (mailbox.Maildir 方法)
@geindex unlock() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir lock}@anchor{2a66}
@deffn {方法} lock ()
@anchor{library/mailbox mailbox Maildir unlock}@anchor{2a67}
@deffnx {方法} unlock ()

Maildir 邮箱不支持（或要求）锁定操作，所以此方法并不会做任何事情。
@end deffn

@geindex close() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir close}@anchor{2a68}
@deffn {方法} close ()

@ref{d78,,Maildir} 实例不保留任何打开的文件并且下层的邮箱不支持锁定操作，所以此方法不会做任何事情。
@end deffn

@geindex get_file() (mailbox.Maildir 方法)
@anchor{library/mailbox mailbox Maildir get_file}@anchor{2a69}
@deffn {方法} get_file (key)

根据主机平台的不同，当返回的文件保持打开状态时可能无法修改或移除下层的消息。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item Courier 上的 maildir 指南页面@footnote{http://www.courier-mta.org/maildir.html}

该格式的规格说明。 描述了用于支持文件夹的通用扩展。

@item 使用 maildir 格式@footnote{https://cr.yp.to/proto/maildir.html}

Maildir 发明者对它的说明。 包括已更新的名称创建方案和 "info" 语义的相关细节。
@end table


@node mbox,MH,Maildir,Mailbox 对象
@anchor{library/mailbox mailbox-mbox}@anchor{2a6a}@anchor{library/mailbox mbox}@anchor{2a6b}
@subsubsection @code{mbox}


@geindex mbox (mailbox 中的类)
@anchor{library/mailbox mailbox mbox}@anchor{2a42}
@deffn {类} mailbox.mbox (path, factory=None, create=True)

@ref{cb9,,Mailbox} 的子类，用于 mbox 格式的邮箱。 形参 @emph{factory} 是一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制模式打开）并返回一个自定义的表示形式。 如果 @emph{factory} 为 @code{None}，则会使用 @ref{2915,,mboxMessage} 作为默认的消息表示形式。 如果 @emph{create} 为 @code{True}，则当邮箱不存在时会创建它。

mbox 格式是在 Unix 系统上存储电子邮件的经典格式。 mbox 邮箱中的所有消息都存储在一个单独文件中，每条消息的开头由前五个字符为 "From " 的行来指明。

还有一些 mbox 格式变种对原始格式中发现的缺点做了改进，@ref{2a42,,mbox} 只实现原始格式，有时被称为 @emph{mboxo}。 这意味着当存储消息时 @code{Content-Length} 标头如果存在则会被忽略并且消息体中出现于行开头的任何 "From " 会被转换为 ">From "，但是当读取消息时 ">From " 则不会被转换为 "From "。

@ref{2a42,,mbox} 所实现的某些 @ref{cb9,,Mailbox} 方法值得进行特别的说明:

@geindex get_file() (mailbox.mbox 方法)
@anchor{library/mailbox mailbox mbox get_file}@anchor{2a6c}
@deffn {方法} get_file (key)

在 @ref{2a42,,mbox} 实例上调用 @code{flush()} 或 @code{close()} 之后再使用文件可能产生无法预料的结果或者引发异常。
@end deffn

@geindex lock() (mailbox.mbox 方法)
@geindex unlock() (mailbox.mbox 方法)
@anchor{library/mailbox mailbox mbox lock}@anchor{2a6d}
@deffn {方法} lock ()
@anchor{library/mailbox mailbox mbox unlock}@anchor{2a6e}
@deffnx {方法} unlock ()

使用三种锁机制 --- dot 锁，以及可能情况下的 @code{flock()} 和 @code{lockf()} 系统调用。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item tin 上的 mbox 指南页面@footnote{http://www.tin.org/bin/man.cgi?section=5&topic=mbox}

该格式的规格说明，包括有关锁的详情。

@item 在 Unix 上配置 Netscape Mail: 为何 Content-Length 格式是不好的@footnote{https://www.jwz.org/doc/content-length.html}

使用原始 mbox 格式而非其变种的一些理由。

@item "mbox" 是由多个彼此不兼容的邮箱格式构成的家族@footnote{https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml}

有关 mbox 变种的历史。
@end table


@node MH,Babyl,mbox,Mailbox 对象
@anchor{library/mailbox mailbox-mh}@anchor{2a6f}@anchor{library/mailbox mh}@anchor{2a70}
@subsubsection @code{MH}


@geindex MH (mailbox 中的类)
@anchor{library/mailbox mailbox MH}@anchor{2a71}
@deffn {类} mailbox.MH (path, factory=None, create=True)

@ref{cb9,,Mailbox} 的子类，用于 MH 格式的邮箱。 形参 @emph{factory} 是一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制模式打开）并返回一个自定义的表示形式。 如果 @emph{factory} 为 @code{None}，则会使用 @ref{2a72,,MHMessage} 作为默认的消息表示形式。 如果 @emph{create} 为 @code{True}，则当邮箱不存在时会创建它。

MH 是一种基于目录的邮箱格式，它是针对 MH Message Handling System 电子邮件用户代理而发明的。 在 MH 邮箱的每条消息都放在单独文件中。 MH 邮箱中除了邮件消息还可以包含其他 MH 邮箱 (称为 @emph{文件夹})。 文件夹可以无限嵌套。 MH 邮箱还支持 @emph{序列}，这是一种命名列表，用来对消息进行逻辑分组而不必将其移入子文件夹。 序列是在每个文件夹中名为 @code{.mh_sequences} 的文件内定义的。

@ref{2a71,,MH} 类可以操作 MH 邮箱，但它并不试图模拟 @code{mh} 的所有行为。 特别地，它并不会修改 @code{context} 或 @code{.mh_profile} 文件也不会受其影响，这两个文件是 @code{mh} 用来存储状态和配置数据的。

@ref{2a71,,MH} 实例具有 @ref{cb9,,Mailbox} 的所有方法及下列附加方法:

@geindex list_folders() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH list_folders}@anchor{2a73}
@deffn {方法} list_folders ()

返回所有文件夹名称的列表。
@end deffn

@geindex get_folder() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH get_folder}@anchor{2a74}
@deffn {方法} get_folder (folder)

返回表示名称为 @emph{folder} 的文件夹的 @ref{2a71,,MH} 实例。 如果文件夹不存在则会引发 @ref{2a5d,,NoSuchMailboxError} 异常。
@end deffn

@geindex add_folder() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH add_folder}@anchor{2a75}
@deffn {方法} add_folder (folder)

创建名称为 @emph{folder} 的文件夹并返回表示它的 @ref{2a71,,MH} 实例。
@end deffn

@geindex remove_folder() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH remove_folder}@anchor{2a76}
@deffn {方法} remove_folder (folder)

删除名称为 @emph{folder} 的文件夹。 如果文件夹包含任何消息，则将引发 @ref{2a60,,NotEmptyError} 异常且该文件夹将不会被删除。
@end deffn

@geindex get_sequences() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH get_sequences}@anchor{2a77}
@deffn {方法} get_sequences ()

返回映射到键列表的序列名称字典。 如果不存在任何序列，则返回空字典。
@end deffn

@geindex set_sequences() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH set_sequences}@anchor{2a78}
@deffn {方法} set_sequences (sequences)

根据由映射到键列表的名称组成的字典 @emph{sequences} 来重新定义邮箱中的序列，该字典与 @ref{2a77,,get_sequences()} 返回值的形式一样。
@end deffn

@geindex pack() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH pack}@anchor{2a79}
@deffn {方法} pack ()

根据需要重命名邮箱中的消息以消除序号中的空缺。 序列列表中的条目会做相应的修改。

@cartouche
@quotation 注解 
已发送的键会因此操作而失效并且不应当被继续使用。
@end quotation
@end cartouche
@end deffn

@ref{2a71,,MH} 所实现的某些 @ref{cb9,,Mailbox} 方法值得进行特别的说明:

@geindex remove() (mailbox.MH 方法)
@geindex __delitem__() (mailbox.MH 方法)
@geindex discard() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH remove}@anchor{2a7a}
@deffn {方法} remove (key)
@anchor{library/mailbox mailbox MH __delitem__}@anchor{2a7b}
@deffnx {方法} __delitem__ (key)
@anchor{library/mailbox mailbox MH discard}@anchor{2a7c}
@deffnx {方法} discard (key)

这些方法会立即删除消息。 通过在名称前加缀一个冒号作为消息删除标记的 MH 惯例不会被使用。
@end deffn

@geindex lock() (mailbox.MH 方法)
@geindex unlock() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH lock}@anchor{2a7d}
@deffn {方法} lock ()
@anchor{library/mailbox mailbox MH unlock}@anchor{2a7e}
@deffnx {方法} unlock ()

使用三种锁机制 --- dot 锁，以及可能情况下下 @code{flock()} 和 @code{lockf()} 系统调用。 对于 MH 邮箱来说，锁定邮箱意味着锁定 @code{.mh_sequences} 文件，并且仅在执行会影响单独消息文件的操作期间锁定单独消息文件。
@end deffn

@geindex get_file() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH get_file}@anchor{2a7f}
@deffn {方法} get_file (key)

根据主机平台的不同，当返回的文件保持打开状态时可能无法移除下层的消息。
@end deffn

@geindex flush() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH flush}@anchor{2a80}
@deffn {方法} flush ()

对 MH 邮箱的所有更改都会立即被应用，所以此方法并不会做任何事情。
@end deffn

@geindex close() (mailbox.MH 方法)
@anchor{library/mailbox mailbox MH close}@anchor{2a81}
@deffn {方法} close ()

@ref{2a71,,MH} 实例不保留任何打开的文件，所以此方法等价于 @ref{2a7e,,unlock()}。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item nmh - Message Handling System@footnote{http://www.nongnu.org/nmh/}

@code{nmh} 的主页，这是原始 @code{mh} 的更新版本。

@item MH & nmh: Email for Users & Programmers@footnote{https://rand-mh.sourceforge.io/book/}

使用 GPL 许可证的介绍 @code{mh} 与 @code{nmh} 的图书，包含有关该邮箱格式的各种信息。
@end table


@node Babyl,MMDF,MH,Mailbox 对象
@anchor{library/mailbox babyl}@anchor{2a82}@anchor{library/mailbox mailbox-babyl}@anchor{2a83}
@subsubsection @code{Babyl}


@geindex Babyl (mailbox 中的类)
@anchor{library/mailbox mailbox Babyl}@anchor{2a84}
@deffn {类} mailbox.Babyl (path, factory=None, create=True)

@ref{cb9,,Mailbox} 的子类，用于 Babyl 格式的邮箱。 形参 @emph{factory} 是一个可调用对象，它接受一个文件类表示形式（其行为相当于以二进制模式打开）并返回一个自定义的表示形式。 如果 @emph{factory} 为 @code{None}，则会使用 @ref{2a85,,BabylMessage} 作为默认的消息表示形式。 如果 @emph{create} 为 @code{True}，则当邮箱不存在时会创建它。

Babyl 是 Rmail 电子邮箱用户代理所使用单文件邮箱格式，包括在 Emacs 中。 每条消息的开头由一个包含 Control-Underscore (@code{'\037'}) 和 Control-L (@code{'\014'}) 这两个字符的行来指明。 消息的结束由下一条消息的开头来指明，或者当为最后一条消息时则由一个包含 Control-Underscore (@code{'\037'}) 字符的行来指明。

Babyl 邮箱中的消息带有两组标头：原始标头和所谓的可见标头。 可见标头通常为原始标头经过重格式化和删减以更易读的子集。 Babyl 邮箱中的每条消息都附带了一个 @emph{标签} 列表，即记录消息相关额外信息的短字符串，邮箱中所有的用户定义标签列表会存储于 Babyl 的选项部分。

@ref{2a84,,Babyl} 实例具有 @ref{cb9,,Mailbox} 的所有方法及下列附加方法:

@geindex get_labels() (mailbox.Babyl 方法)
@anchor{library/mailbox mailbox Babyl get_labels}@anchor{2a86}
@deffn {方法} get_labels ()

返回邮箱中使用的所有用户定义标签名称的列表。

@cartouche
@quotation 注解 
邮箱中存在哪些标签会通过检查实际的消息而非查询 Babyl 选项部分的标签列表，但 Babyl 选项部分会在邮箱被修改时更新。
@end quotation
@end cartouche
@end deffn

@ref{2a84,,Babyl} 所实现的某些 @ref{cb9,,Mailbox} 方法使得进行特别的说明:

@geindex get_file() (mailbox.Babyl 方法)
@anchor{library/mailbox mailbox Babyl get_file}@anchor{2a87}
@deffn {方法} get_file (key)

在 Babyl 邮箱中，消息的标头并不是与消息体存储在一起的。 要生成文件类表示形式，标头和消息体会被一起拷贝到一个 @ref{894,,io.BytesIO} 实例中，它具有与文件相似的 API。 因此，文件类对象实际上独立于下层邮箱，但与字符串表达形式相比并不会更节省内存。
@end deffn

@geindex lock() (mailbox.Babyl 方法)
@geindex unlock() (mailbox.Babyl 方法)
@anchor{library/mailbox mailbox Babyl lock}@anchor{2a88}
@deffn {方法} lock ()
@anchor{library/mailbox mailbox Babyl unlock}@anchor{2a89}
@deffnx {方法} unlock ()

使用三种锁机制 --- dot 锁，以及可能情况下的 @code{flock()} 和 @code{lockf()} 系统调用。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item Format of Version 5 Babyl Files@footnote{https://quimby.gnus.org/notes/BABYL}

Babyl 格式的规格说明。

@item Reading Mail with Rmail@footnote{https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html}

Rmail 的帮助手册，包含了有关 Babyl 语义的一些信息。
@end table


@node MMDF,,Babyl,Mailbox 对象
@anchor{library/mailbox mailbox-mmdf}@anchor{2a8a}@anchor{library/mailbox mmdf}@anchor{2a8b}
@subsubsection @code{MMDF}


@geindex MMDF (mailbox 中的类)
@anchor{library/mailbox mailbox MMDF}@anchor{2a8c}
@deffn {类} mailbox.MMDF (path, factory=None, create=True)

@ref{cb9,,Mailbox} 的子类，用于 MMDF 格式的邮箱。 形参 @emph{factory} 是一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制模式打开）并返回一个自定义的表示形式。 如果 @emph{factory} 为 @code{None}，则会使用 @ref{2a8d,,MMDFMessage} 作为默认的消息表示形式。 如果 @emph{create} 为 @code{True}，则当邮箱不存在时会创建它。

MMDF 是一种专用于电子邮件传输代理 Multichannel Memorandum Distribution Facility 的单文件邮箱格式。 每条消息使用与 mbox 消息相同的形式，但其前后各有包含四个 Control-A (@code{'\001'}) 字符的行。 与 mbox 格式一样，每条消息的开头由一个前五个字符为 "From " 的行来指明，但当存储消息时额外出现的 "From " 不会被转换为 ">From "  因为附加的消息分隔符可防止将这些内容误认为是后续消息的开头。

@ref{2a8c,,MMDF} 所实现的某些 @ref{cb9,,Mailbox} 方法值得进行特别的说明:

@geindex get_file() (mailbox.MMDF 方法)
@anchor{library/mailbox mailbox MMDF get_file}@anchor{2a8e}
@deffn {方法} get_file (key)

在 @ref{2a8c,,MMDF} 实例上调用 @code{flush()} 或 @code{close()} 之后再使用文件可能产生无法预料的结果或者引发异常。
@end deffn

@geindex lock() (mailbox.MMDF 方法)
@geindex unlock() (mailbox.MMDF 方法)
@anchor{library/mailbox mailbox MMDF lock}@anchor{2a8f}
@deffn {方法} lock ()
@anchor{library/mailbox mailbox MMDF unlock}@anchor{2a90}
@deffnx {方法} unlock ()

使用三种锁机制 --- dot 锁，以及可能情况下的 @code{flock()} 和 @code{lockf()} 系统调用。
@end deffn
@end deffn


@subsubheading 参见



@table @asis

@item tin 上的 mmdf 指南页面@footnote{http://www.tin.org/bin/man.cgi?section=5&topic=mmdf}

MMDF 格式的规格说明，来自新闻阅读器 tin 的文档。

@item MMDF@footnote{https://en.wikipedia.org/wiki/MMDF}

一篇描述 Multichannel Memorandum Distribution Facility 的维基百科文章。
@end table


@node Message 对象,异常<14>,Mailbox 对象,mailbox --- 操作多种格式的邮箱
@anchor{library/mailbox mailbox-message-objects}@anchor{2a91}@anchor{library/mailbox message-objects}@anchor{2a92}
@subsubsection @code{Message} 对象


@geindex Message (mailbox 中的类)
@anchor{library/mailbox mailbox Message}@anchor{cbd}
@deffn {类} mailbox.Message (message=None)

@ref{70,,email.message} 模块的 @ref{644,,Message} 的子类。 @ref{cbd,,mailbox.Message} 的子类添加了特定邮箱格式专属的状态和行为。

如果省略了 @emph{message}，则新实例会以默认的空状态被创建。 如果 @emph{message} 是一个 @ref{644,,email.message.Message} 实例，其内容会被拷贝；此外，如果 @emph{message} 是一个 @ref{cbd,,Message} 实例，则任何格式专属信息会尽可能地被拷贝。 如果 @emph{message} 是一个字符串、字节串或文件，则它应当包含兼容 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 的消息，该消息会被读取和解析。 文档应当以二进制模式打开，但文本模式的文件也会被接受以向下兼容。

各个子类所提供的格式专属状态和行为各有不同，但总的来说只有那些不仅限于特定邮箱的特性才会被支持（虽然这些特性可能专属于特定邮箱格式）。 例如，例如，单文件邮箱格式的文件偏移量和基于目录的邮箱格式的文件名都不会被保留，因为它们都仅适用于对应的原始邮箱。 但消息是否已被用户读取或标记为重要等状态则会被保留，因为它们适用于消息本身。

不要求用 @ref{cbd,,Message} 实例来表示使用 @ref{cb9,,Mailbox} 实例所提取到的消息。 在某些情况下，生成 @ref{cbd,,Message} 表示形式所需的时间和内存空间可能是不可接受的。 对于此类情况，@ref{cb9,,Mailbox} 实例还提供了字符串和文件类表示形式，并可在初始化 @ref{cb9,,Mailbox} 实例时指定自定义的消息工厂函数。
@end deffn

@menu
* MaildirMessage:: 
* mboxMessage:: 
* MHMessage:: 
* BabylMessage:: 
* MMDFMessage:: 

@end menu

@node MaildirMessage,mboxMessage,,Message 对象
@anchor{library/mailbox mailbox-maildirmessage}@anchor{2a93}@anchor{library/mailbox maildirmessage}@anchor{2a94}
@subsubsection @code{MaildirMessage}


@geindex MaildirMessage (mailbox 中的类)
@anchor{library/mailbox mailbox MaildirMessage}@anchor{2a5a}
@deffn {类} mailbox.MaildirMessage (message=None)

具有 Maildir 专属行为的消息。 形参 @emph{message} 的含义与 @ref{cbd,,Message} 构造器一致。

通常，邮件用户代理应用程序会在用户第一次打开并关闭邮箱之后将 @code{new} 子目录中的所有消息移至 @code{cur} 子目录，将这些消息记录为旧消息，无论它们是否真的已被阅读。 @code{cur} 下的每条消息都有一个 "info" 部分被添加到其文件名中以存储有关其状态的信息。 （某些邮件阅读器还会把 "info" 部分也添加到 @code{new} 下的消息中。） "info" 部分可以采用两种形式之一：它可能包含 "2," 后面跟一个经标准化的旗标列表（例如 "2,FR"）或者它可能包含 "1," 后面跟所谓的实验性信息。 Maildir 消息的标准旗标如下:


@multitable {xxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

旗标

@tab

意义

@tab

解释

@item

D

@tab

草稿

@tab

正在撰写中

@item

F

@tab

已标记

@tab

已被标记为重要

@item

P

@tab

已检视

@tab

转发，重新发送或退回

@item

R

@tab

已回复

@tab

回复给

@item

S

@tab

已查看

@tab

已阅读

@item

T

@tab

已删除

@tab

标记为可被删除

@end multitable


@ref{2a5a,,MaildirMessage} 实例提供以下方法：

@geindex get_subdir() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage get_subdir}@anchor{2a95}
@deffn {方法} get_subdir ()

返回 "new" (如果消息应当被存储在 @code{new} 子目录下) 或者 "cur" (如果消息应当被存储在 @code{cur} 子目录下)。

@cartouche
@quotation 注解 
消息通常会在其邮箱被访问后被从 @code{new} 移至 @code{cur}，无论该消息是否已被阅读。  如果 msg.get_flags()`@w{`} 中的 @code{"S" 为 `@w{`}True} 则说明消息 @code{msg} 已被阅读。
@end quotation
@end cartouche
@end deffn

@geindex set_subdir() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage set_subdir}@anchor{2a96}
@deffn {方法} set_subdir (subdir)

设置消息应当被存储到的子目录。 形参 @emph{subdir} 必须为 "new" 或 "cur"。
@end deffn

@geindex get_flags() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage get_flags}@anchor{2a97}
@deffn {方法} get_flags ()

返回一个指明当前所设旗标的字符串。 如果消息符合标准的 Maildir 格式，则结果为零或按字母顺序各自出现一次的 @code{'D'}, @code{'F'}, @code{'P'}, @code{'R'}, @code{'S'} 和 @code{'T'} 的拼接。 如果未设任何旗标或者如果 "info" 包含实验性语义则返回空字符串。
@end deffn

@geindex set_flags() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage set_flags}@anchor{2a98}
@deffn {方法} set_flags (flags)

设置由 @emph{flags} 所指定的旗标并重置所有其它旗标。
@end deffn

@geindex add_flag() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage add_flag}@anchor{2a99}
@deffn {方法} add_flag (flag)

设置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性添加一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。 当前 "info" 会被覆盖，无论它是否只包含实验性信息而非旗标。
@end deffn

@geindex remove_flag() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage remove_flag}@anchor{2a9a}
@deffn {方法} remove_flag (flag)

重置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性移除一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。 如果 "info" 包含实验性信息而非旗标，则当前的 "info" 不会被修改。
@end deffn

@geindex get_date() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage get_date}@anchor{2a9b}
@deffn {方法} get_date ()

以表示 Unix 纪元秒数的浮点数形式返回消息的发送日期。
@end deffn

@geindex set_date() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage set_date}@anchor{2a9c}
@deffn {方法} set_date (date)

将消息的发送日期设为 @emph{date}，一个表示 Unix 纪元秒数的浮点数。
@end deffn

@geindex get_info() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage get_info}@anchor{2a9d}
@deffn {方法} get_info ()

返回一个包含消息的 "info" 的字符串。 这适用于访问和修改实验性的 "info" (即不是由旗标组成的列表)。
@end deffn

@geindex set_info() (mailbox.MaildirMessage 方法)
@anchor{library/mailbox mailbox MaildirMessage set_info}@anchor{2a9e}
@deffn {方法} set_info (info)

将 "info" 设为 @emph{info}，这应当是一个字符串。
@end deffn
@end deffn

当一个 @ref{2a5a,,MaildirMessage} 实例基于 @ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 实例被创建时，将会忽略 @code{Status} 和 @code{X-Status} 标头并进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 状态

@item

"cur" 子目录

@tab

O 旗标

@item

F 旗标

@tab

F 旗标

@item

R 旗标

@tab

A 旗标

@item

S 旗标

@tab

R 旗标

@item

T 旗标

@tab

D 旗标

@end multitable


当一个 @ref{2a5a,,MaildirMessage} 实例基于 @ref{2a72,,MHMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a72,,MHMessage} 状态

@item

"cur" 子目录

@tab

"unseen" 序列

@item

"cur" 子目录和 S 旗标

@tab

非 "unseen" 序列

@item

F 旗标

@tab

"flagged" 序列

@item

R 旗标

@tab

"replied" 序列

@end multitable


当一个 @ref{2a5a,,MaildirMessage} 实例基于 @ref{2a85,,BabylMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a85,,BabylMessage} 状态

@item

"cur" 子目录

@tab

"unseen" 标签

@item

"cur" 子目录和 S 旗标

@tab

非 "unseen" 标签

@item

P 旗标

@tab

"forwarded" 或 "resent" 标签

@item

R 旗标

@tab

"answered" 标签

@item

T 旗标

@tab

"deleted" 标签

@end multitable


@node mboxMessage,MHMessage,MaildirMessage,Message 对象
@anchor{library/mailbox mailbox-mboxmessage}@anchor{2a9f}@anchor{library/mailbox mboxmessage}@anchor{2aa0}
@subsubsection @code{mboxMessage}


@geindex mboxMessage (mailbox 中的类)
@anchor{library/mailbox mailbox mboxMessage}@anchor{2915}
@deffn {类} mailbox.mboxMessage (message=None)

具有 mbox 专属行为的消息。 形参 @emph{message} 的含义与 @ref{cbd,,Message} 构造器一致。

mbox 邮箱中的消息会一起存储在单个文件中。  发件人的信封地址和发送时间通常存储在指明每条消息的起始的以 "From " 打头的行中，不过在 mbox 的各种实现之间此数据的确切格式具有相当大的差异。 指明消息状态的各种旗标，例如是否已读或标记为重要等等通常存储在 @code{Status} 和 @code{X-Status} 标头中。

传统的 mbox 消息旗标如下:


@multitable {xxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

旗标

@tab

意义

@tab

解释

@item

R

@tab

已阅读

@tab

已阅读

@item

O

@tab

旧消息

@tab

之前已经过 MUA 检测

@item

D

@tab

已删除

@tab

标记为可被删除

@item

F

@tab

已标记

@tab

已被标记为重要

@item

A

@tab

已回复

@tab

回复给

@end multitable


"R" 和 "O" 旗标存储在 @code{Status} 标头中，而 "D", "F" 和 "A" 旗标存储在 @code{X-Status} 标头中。 旗标和标头通常会按上述顺序显示。

@ref{2915,,mboxMessage} 实例提供了下列方法:

@geindex get_from() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage get_from}@anchor{2aa1}
@deffn {方法} get_from ()

返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。 开头的 "From " 和末尾的换行符会被去除。
@end deffn

@geindex set_from() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage set_from}@anchor{2aa2}
@deffn {方法} set_from (from_, time_=None)

将 "From " 行设为 @emph{from_}，这应当被指定为不带开头的 "From " 或末尾的换行符。 为方便起见，可以指定 @emph{time_} 并将经过适当的格式化再添加到 @emph{from_}。 如果指定了 @emph{time_}，它应当是一个 @ref{69a,,time.struct_time} 实例，适合传入 @ref{c40,,time.strftime()} 的元组或者 @code{True} (以使用 @ref{c1a,,time.gmtime()})。
@end deffn

@geindex get_flags() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage get_flags}@anchor{2aa3}
@deffn {方法} get_flags ()

返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结果为零或各自出现一次的 @code{'R'}, @code{'O'}, @code{'D'}, @code{'F'} 和 @code{'A'} 按上述顺序的拼接。
@end deffn

@geindex set_flags() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage set_flags}@anchor{2aa4}
@deffn {方法} set_flags (flags)

设置由 @emph{flags} 所指明的旗标并重启所有其他旗标。 形参 @emph{flags} 应当为零或各自出现多次的 @code{'R'}, @code{'O'}, @code{'D'}, @code{'F'} 和 @code{'A'} 按任意顺序的拼接。
@end deffn

@geindex add_flag() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage add_flag}@anchor{2aa5}
@deffn {方法} add_flag (flag)

设置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性添加一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。
@end deffn

@geindex remove_flag() (mailbox.mboxMessage 方法)
@anchor{library/mailbox mailbox mboxMessage remove_flag}@anchor{2aa6}
@deffn {方法} remove_flag (flag)

重置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性移除一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。
@end deffn
@end deffn

当一个 @ref{2915,,mboxMessage} 实例基于 @ref{2a5a,,MaildirMessage} 实例被创建时，"From " 行会基于 @ref{2a5a,,MaildirMessage} 实例的发送时间被生成，并进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a5a,,MaildirMessage} 状态

@item

R 旗标

@tab

S 旗标

@item

O 旗标

@tab

"cur" 子目录

@item

D 旗标

@tab

T 旗标

@item

F 旗标

@tab

F 旗标

@item

A 旗标

@tab

R 旗标

@end multitable


当一个 @ref{2915,,mboxMessage} 实例基于 @ref{2a72,,MHMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a72,,MHMessage} 状态

@item

R 旗标 和 O 旗标

@tab

非 "unseen" 序列

@item

O 旗标

@tab

"unseen" 序列

@item

F 旗标

@tab

"flagged" 序列

@item

A 旗标

@tab

"replied" 序列

@end multitable


当一个 @ref{2915,,mboxMessage} 实例基于 @ref{2a85,,BabylMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a85,,BabylMessage} 状态

@item

R 旗标 和 O 旗标

@tab

非 "unseen" 标签

@item

O 旗标

@tab

"unseen" 标签

@item

D 旗标

@tab

"deleted" 标签

@item

A 旗标

@tab

"answered" 标签

@end multitable


当一个 @ref{cbd,,Message} 实例基于 @ref{2a8d,,MMDFMessage} 实例被创建时，"From " 行会被拷贝并直接对应所有旗标。


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a8d,,MMDFMessage} 状态

@item

R 旗标

@tab

R 旗标

@item

O 旗标

@tab

O 旗标

@item

D 旗标

@tab

D 旗标

@item

F 旗标

@tab

F 旗标

@item

A 旗标

@tab

A 旗标

@end multitable


@node MHMessage,BabylMessage,mboxMessage,Message 对象
@anchor{library/mailbox mailbox-mhmessage}@anchor{2aa7}@anchor{library/mailbox mhmessage}@anchor{2aa8}
@subsubsection @code{MHMessage}


@geindex MHMessage (mailbox 中的类)
@anchor{library/mailbox mailbox MHMessage}@anchor{2a72}
@deffn {类} mailbox.MHMessage (message=None)

具有 MH 专属行为的消息。 形参 @emph{message} 的含义与 @ref{cbd,,Message} 构造器一致。

MH 消息不支持传统意义上的标记或旗标，但它们支持序列，即对任意消息的逻辑分组。 某些邮件阅读程序 (但不包括标准 @code{mh} 和 @code{nmh}) 以与其他格式使用旗标类似的方式来使用序列，如下所示:


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

序列

@tab

解释

@item

unseen

@tab

未阅读，但之前已经过 MUA 检测

@item

已回复

@tab

回复给

@item

已标记

@tab

已被标记为重要

@end multitable


@ref{2a72,,MHMessage} 实例提供了下列方法:

@geindex get_sequences() (mailbox.MHMessage 方法)
@anchor{library/mailbox mailbox MHMessage get_sequences}@anchor{2aa9}
@deffn {方法} get_sequences ()

返回一个包含此消息的序列的名称的列表。
@end deffn

@geindex set_sequences() (mailbox.MHMessage 方法)
@anchor{library/mailbox mailbox MHMessage set_sequences}@anchor{2aaa}
@deffn {方法} set_sequences (sequences)

设置包含此消息的序列的列表。
@end deffn

@geindex add_sequence() (mailbox.MHMessage 方法)
@anchor{library/mailbox mailbox MHMessage add_sequence}@anchor{2aab}
@deffn {方法} add_sequence (sequence)

将 @emph{sequence} 添加到包含此消息的序列的列表。
@end deffn

@geindex remove_sequence() (mailbox.MHMessage 方法)
@anchor{library/mailbox mailbox MHMessage remove_sequence}@anchor{2aac}
@deffn {方法} remove_sequence (sequence)

将 @emph{sequence} 从包含此消息的序列的列表中移除。
@end deffn
@end deffn

当一个 @ref{2a72,,MHMessage} 实例基于 @ref{2a5a,,MaildirMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a5a,,MaildirMessage} 状态

@item

"unseen" 序列

@tab

非 S 旗标

@item

"replied" 序列

@tab

R 旗标

@item

"flagged" 序列

@tab

F 旗标

@end multitable


当一个 @ref{2a72,,MHMessage} 实例基于 @ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 实例被创建时，将会忽略 @code{Status} 和 @code{X-Status} 标头并进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 状态

@item

"unseen" 序列

@tab

非 R 旗标

@item

"replied" 序列

@tab

A 旗标

@item

"flagged" 序列

@tab

F 旗标

@end multitable


当一个 @ref{2a72,,MHMessage} 实例基于 @ref{2a85,,BabylMessage} 实例被创建时，将进入下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a85,,BabylMessage} 状态

@item

"unseen" 序列

@tab

"unseen" 标签

@item

"replied" 序列

@tab

"answered" 标签

@end multitable


@node BabylMessage,MMDFMessage,MHMessage,Message 对象
@anchor{library/mailbox babylmessage}@anchor{2aad}@anchor{library/mailbox mailbox-babylmessage}@anchor{2aae}
@subsubsection @code{BabylMessage}


@geindex BabylMessage (mailbox 中的类)
@anchor{library/mailbox mailbox BabylMessage}@anchor{2a85}
@deffn {类} mailbox.BabylMessage (message=None)

具有 Babyl 专属行为的消息。 形参 @emph{message} 的含义与 @ref{cbd,,Message} 构造器一致。

某些消息标签被称为 @emph{属性}，根据惯例被定义为具有特殊的含义。 这些属性如下所示:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标签

@tab

解释

@item

unseen

@tab

未阅读，但之前已经过 MUA 检测

@item

deleted

@tab

标记为可被删除

@item

filed

@tab

复制到另一个文件或邮箱

@item

answered

@tab

回复给

@item

forwarded

@tab

已转发

@item

edited

@tab

已被用户修改

@item

resent

@tab

已重发

@end multitable


默认情况下，Rmail 只显示可见标头。 不过 @ref{2a85,,BabylMessage} 类会使用原始标头因为它们更完整。 如果需要可以显式地访问可见标头。

@ref{2a85,,BabylMessage} 实例提供了下列方法:

@geindex get_labels() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage get_labels}@anchor{2aaf}
@deffn {方法} get_labels ()

返回邮件上的标签列表。
@end deffn

@geindex set_labels() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage set_labels}@anchor{2ab0}
@deffn {方法} set_labels (labels)

将消息上的标签列表设置为 @emph{labels} 。
@end deffn

@geindex add_label() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage add_label}@anchor{2ab1}
@deffn {方法} add_label (label)

将 @emph{label} 添加到消息上的标签列表中。
@end deffn

@geindex remove_label() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage remove_label}@anchor{2ab2}
@deffn {方法} remove_label (label)

从消息上的标签列表中删除 @emph{label} 。
@end deffn

@geindex get_visible() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage get_visible}@anchor{2ab3}
@deffn {方法} get_visible ()

返回一个 @ref{cbd,,Message} 实例，其标头为消息的可见标头而其消息体为空。
@end deffn

@geindex set_visible() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage set_visible}@anchor{2ab4}
@deffn {方法} set_visible (visible)

将消息的可见标头设为与 @emph{message} 中的标头一致。 形参 @emph{visible} 应当是一个 @ref{cbd,,Message} 实例，@ref{644,,email.message.Message} 实例，字符串或文件类对象（且应当以文本模式打开）。
@end deffn

@geindex update_visible() (mailbox.BabylMessage 方法)
@anchor{library/mailbox mailbox BabylMessage update_visible}@anchor{2ab5}
@deffn {方法} update_visible ()

当一个 @ref{2a85,,BabylMessage} 实例的原始标头被修改时，可见标头不会自动进行对应修改。 此方法将按以下方式更新可见标头：每个具有对应原始标头的可见标头会被设为原始标头的值，每个没有对应原始标头的可见标头会被移除，而任何存在于原始标头但不存在于可见标头中的 @code{Date}, @code{From}, @code{Reply-To}, @code{To}, @code{CC} 和 @code{Subject} 会被添加至可见标头。
@end deffn
@end deffn

当一个 @ref{2a85,,BabylMessage} 实例基于 @ref{2a5a,,MaildirMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a5a,,MaildirMessage} 状态

@item

"unseen" 标签

@tab

非 S 旗标

@item

"deleted" 标签

@tab

T 旗标

@item

"answered" 标签

@tab

R 旗标

@item

"forwarded" 标签

@tab

P 旗标

@end multitable


当一个 @ref{2a85,,BabylMessage} 实例基于 @ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 实例被创建时，将会忽略 @code{Status} 和 @code{X-Status} 标头并进入下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2915,,mboxMessage} 或 @ref{2a8d,,MMDFMessage} 状态

@item

"unseen" 标签

@tab

非 R 旗标

@item

"deleted" 标签

@tab

D 旗标

@item

"answered" 标签

@tab

A 旗标

@end multitable


当一个 @ref{2a85,,BabylMessage} 实例基于 @ref{2a72,,MHMessage} 实例被创建时，将进入下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a72,,MHMessage} 状态

@item

"unseen" 标签

@tab

"unseen" 序列

@item

"answered" 标签

@tab

"replied" 序列

@end multitable


@node MMDFMessage,,BabylMessage,Message 对象
@anchor{library/mailbox mailbox-mmdfmessage}@anchor{2ab6}@anchor{library/mailbox mmdfmessage}@anchor{2ab7}
@subsubsection @code{MMDFMessage}


@geindex MMDFMessage (mailbox 中的类)
@anchor{library/mailbox mailbox MMDFMessage}@anchor{2a8d}
@deffn {类} mailbox.MMDFMessage (message=None)

具有 MMDF 专属行为的消息。 形参 @emph{message} 的含义与 @ref{cbd,,Message} 构造器一致。

与 mbox 邮箱中的消息类似，MMDF 消息会与将发件人的地址和发送日期作为以 "From " 打头的初始行一起存储。 同样地，指明消息状态的旗标通常存储在 @code{Status} 和 @code{X-Status} 标头中。

传统的 MMDF 消息旗标与 mbox 消息的类似，如下所示:


@multitable {xxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

旗标

@tab

意义

@tab

解释

@item

R

@tab

已阅读

@tab

已阅读

@item

O

@tab

旧消息

@tab

之前已经过 MUA 检测

@item

D

@tab

已删除

@tab

标记为可被删除

@item

F

@tab

已标记

@tab

已被标记为重要

@item

A

@tab

已回复

@tab

回复给

@end multitable


"R" 和 "O" 旗标存储在 @code{Status} 标头中，而 "D", "F" 和 "A" 旗标存储在 @code{X-Status} 标头中。 旗标和标头通常会按上述顺序显示。

@ref{2a8d,,MMDFMessage} 实例提供了下列方法，与 @ref{2915,,mboxMessage} 所提供的类似:

@geindex get_from() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage get_from}@anchor{2ab8}
@deffn {方法} get_from ()

返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。 开头的 "From " 和末尾的换行符会被去除。
@end deffn

@geindex set_from() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage set_from}@anchor{2ab9}
@deffn {方法} set_from (from_, time_=None)

将 "From " 行设为 @emph{from_}，这应当被指定为不带开头的 "From " 或末尾的换行符。 为方便起见，可以指定 @emph{time_} 并将经过适当的格式化再添加到 @emph{from_}。 如果指定了 @emph{time_}，它应当是一个 @ref{69a,,time.struct_time} 实例，适合传入 @ref{c40,,time.strftime()} 的元组或者 @code{True} (以使用 @ref{c1a,,time.gmtime()})。
@end deffn

@geindex get_flags() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage get_flags}@anchor{2aba}
@deffn {方法} get_flags ()

返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结果为零或各自出现一次的 @code{'R'}, @code{'O'}, @code{'D'}, @code{'F'} 和 @code{'A'} 按上述顺序的拼接。
@end deffn

@geindex set_flags() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage set_flags}@anchor{2abb}
@deffn {方法} set_flags (flags)

设置由 @emph{flags} 所指明的旗标并重启所有其他旗标。 形参 @emph{flags} 应当为零或各自出现多次的 @code{'R'}, @code{'O'}, @code{'D'}, @code{'F'} 和 @code{'A'} 按任意顺序的拼接。
@end deffn

@geindex add_flag() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage add_flag}@anchor{2abc}
@deffn {方法} add_flag (flag)

设置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性添加一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。
@end deffn

@geindex remove_flag() (mailbox.MMDFMessage 方法)
@anchor{library/mailbox mailbox MMDFMessage remove_flag}@anchor{2abd}
@deffn {方法} remove_flag (flag)

重置由 @emph{flag} 所指明的旗标而不改变其他旗标。 要一次性移除一个以上的旗标，@emph{flag} 可以为包含一个以上字符的字符串。
@end deffn
@end deffn

当一个 @ref{2a8d,,MMDFMessage} 实例基于 @ref{2a5a,,MaildirMessage} 实例被创建时，"From " 行会基于 @ref{2a5a,,MaildirMessage} 实例的发送日期被生成，并进入下列转换:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a5a,,MaildirMessage} 状态

@item

R 旗标

@tab

S 旗标

@item

O 旗标

@tab

"cur" 子目录

@item

D 旗标

@tab

T 旗标

@item

F 旗标

@tab

F 旗标

@item

A 旗标

@tab

R 旗标

@end multitable


当一个 @ref{2a8d,,MMDFMessage} 实例基于 @ref{2a72,,MHMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a72,,MHMessage} 状态

@item

R 旗标 和 O 旗标

@tab

非 "unseen" 序列

@item

O 旗标

@tab

"unseen" 序列

@item

F 旗标

@tab

"flagged" 序列

@item

A 旗标

@tab

"replied" 序列

@end multitable


当一个 @ref{2a8d,,MMDFMessage} 实例基于 @ref{2a85,,BabylMessage} 实例被创建时，将进行下列转换:


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2a85,,BabylMessage} 状态

@item

R 旗标 和 O 旗标

@tab

非 "unseen" 标签

@item

O 旗标

@tab

"unseen" 标签

@item

D 旗标

@tab

"deleted" 标签

@item

A 旗标

@tab

"answered" 标签

@end multitable


当一个 @ref{2a8d,,MMDFMessage} 实例基于 @ref{2915,,mboxMessage} 实例被创建时，"From " 行会被拷贝并直接对应所有旗标:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

结果状态

@tab

@ref{2915,,mboxMessage} 状态

@item

R 旗标

@tab

R 旗标

@item

O 旗标

@tab

O 旗标

@item

D 旗标

@tab

D 旗标

@item

F 旗标

@tab

F 旗标

@item

A 旗标

@tab

A 旗标

@end multitable


@node 异常<14>,示例<27>,Message 对象,mailbox --- 操作多种格式的邮箱
@anchor{library/mailbox exceptions}@anchor{2abe}
@subsubsection 异常


@ref{ae,,mailbox} 模块中定义了下列异常类:

@geindex Error
@anchor{library/mailbox mailbox Error}@anchor{2abf}
@deffn {例外} mailbox.Error

所有其他模块专属异常的基类。
@end deffn

@geindex NoSuchMailboxError
@anchor{library/mailbox mailbox NoSuchMailboxError}@anchor{2a5d}
@deffn {例外} mailbox.NoSuchMailboxError

在期望获得一个邮箱但未找到时被引发，例如当使用不存在的路径来实例化一个 @ref{cb9,,Mailbox} 子类时 (且将 @emph{create} 形参设为 @code{False})，或是当打开一个不存在的路径时。
@end deffn

@geindex NotEmptyError
@anchor{library/mailbox mailbox NotEmptyError}@anchor{2a60}
@deffn {例外} mailbox.NotEmptyError

在期望一个邮箱为空但不为空时被引发，例如当删除一个包含消息的文件夹时。
@end deffn

@geindex ExternalClashError
@anchor{library/mailbox mailbox ExternalClashError}@anchor{2a56}
@deffn {例外} mailbox.ExternalClashError

在某些邮箱相关条件超出了程序控制范围导致其无法继续运行时被引发，例如当要获取的锁已被另一个程序获取时，或是当要生成的唯一性文件名已存在时。
@end deffn

@geindex FormatError
@anchor{library/mailbox mailbox FormatError}@anchor{2ac0}
@deffn {例外} mailbox.FormatError

在某个文件中的数据无法被解析时被引发，例如当一个 @ref{2a71,,MH} 实例尝试读取已损坏的 @code{.mh_sequences} 文件时。
@end deffn

@node 示例<27>,,异常<14>,mailbox --- 操作多种格式的邮箱
@anchor{library/mailbox examples}@anchor{2ac1}@anchor{library/mailbox mailbox-examples}@anchor{2ac2}
@subsubsection 示例


一个打印指定邮箱中所有消息的主题的简单示例:

@example
import mailbox
for message in mailbox.mbox('~/mbox'):
    subject = message['subject']       # Could possibly be None.
    if subject and 'python' in subject.lower():
        print(subject)
@end example

要将所有邮件从 Babyl 邮箱拷贝到 MH 邮箱，请转换所有可转换的格式专属信息:

@example
import mailbox
destination = mailbox.MH('~/Mail')
destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
    destination.add(mailbox.MHMessage(message))
destination.flush()
destination.unlock()
@end example

这个示例将来自多个邮件列表的邮件分类放入不同的邮箱，小心避免由于其他程序的并发修改导致的邮件损坏，由于程序中断导致的邮件丢失，或是由于邮箱中消息格式错误导致的意外终止:

@example
import mailbox
import email.errors

list_names = ('python-list', 'python-dev', 'python-bugs')

boxes = @{name: mailbox.mbox('~/email/%s' % name) for name in list_names@}
inbox = mailbox.Maildir('~/Maildir', factory=None)

for key in inbox.iterkeys():
    try:
        message = inbox[key]
    except email.errors.MessageParseError:
        continue                # The message is malformed. Just leave it.

    for name in list_names:
        list_id = message['list-id']
        if list_id and name in list_id:
            # Get mailbox to use
            box = boxes[name]

            # Write copy to disk before removing original.
            # If there's a crash, you might duplicate a message, but
            # that's better than losing a message completely.
            box.lock()
            box.add(message)
            box.flush()
            box.unlock()

            # Remove original message
            inbox.lock()
            inbox.discard(key)
            inbox.flush()
            inbox.unlock()
            break               # Found destination, so stop looking.

for box in boxes.itervalues():
    box.close()
@end example

@node mimetypes --- 映射文件名到 MIME 类型,base64 --- Base16 Base32 Base64 Base85 数据编码,mailbox --- 操作多种格式的邮箱,互联网数据处理
@anchor{library/mimetypes doc}@anchor{2ac3}@anchor{library/mimetypes mimetypes-map-filenames-to-mime-types}@anchor{2ac4}@anchor{library/mimetypes module-mimetypes}@anchor{b2}
@subsection @code{mimetypes} --- 映射文件名到 MIME 类型


@geindex mimetypes (模块)

@strong{源代码:} Lib/mimetypes.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/mimetypes.py}

@geindex MIME; content type


__________________________________________________________________


@ref{b2,,mimetypes} 模块可以在文件名或 URL 和关联到文件扩展名的 MIME 类型之间执行转换。 所提供的转换包括从文件名到 MIME 类型和从 MIME 类型到文件扩展名；后一种转换不支持编码格式。

该模块提供了一个类和一些便捷函数。 这些函数是该模块通常的接口，但某些应用程序可能也会希望使用类。

下列函数提供了此模块的主要接口。 如果此模块尚未被初始化，它们将会调用 @ref{10eb,,init()}，如果它们依赖于 @ref{10eb,,init()} 所设置的信息的话。

@geindex guess_type() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes guess_type}@anchor{10ea}
@deffn {函数} mimetypes.guess_type (url, strict=True)

@geindex MIME; headers

根据 @emph{url} 给出的文件名、路径或 URL 来猜测文件的类型，URL 可以为字符串或 @ref{47b,,path-like object}。

返回值是一个元组 @code{(type, encoding)} 其中 @emph{type} 在无法猜测（后缀不存在或者未知）时为 @code{None}，或者为 @code{'type/subtype'} 形式的字符串，可以作为 MIME @code{content-type} 标头。

@emph{encoding} 在无编码格式时为 @code{None}，或者为程序所用的编码格式 (例如 @code{compress} 或 @code{gzip})。 它可以作为 @code{Content-Encoding} 标头，但 @strong{不可} 作为 @code{Content-Transfer-Encoding} 标头。 映射是表格驱动的。 编码格式前缀对大小写敏感；类型前缀会先以大小写敏感方式检测再以大小写不敏感方式检测。

可选的 @emph{strict} 参数是一个旗标，指明要将已知 MIME 类型限制在 IANA 已注册@footnote{https://www.iana.org/assignments/media-types/media-types.xhtml} 的官方类型之内。 当 @emph{strict} 为 @code{True} 时（默认值），则仅支持 IANA 类型；当 @emph{strict} 为 @code{False} 时，则还支持某些附加的非标准但常用的 MIME 类型。


在 3.8 版更改: 增加了 @ref{47b,,path-like object} 作为 url 的支持。

@end deffn

@geindex guess_all_extensions() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes guess_all_extensions}@anchor{fbb}
@deffn {函数} mimetypes.guess_all_extensions (type, strict=True)

根据由 @emph{type} 给出的文件 MIME 类型猜测其扩展名。 返回值是由所有可能的文件扩展名组成的字符串列表，包括开头的点号 (@code{'.'})。 这些扩展名不保证能关联到任何特定的数据流，但是将会由  @ref{10ea,,guess_type()} 映射到 MIME 类型 @emph{type}。

可选的 @emph{strict} 参数具有与 @ref{10ea,,guess_type()} 函数一致的含义。
@end deffn

@geindex guess_extension() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes guess_extension}@anchor{2ac5}
@deffn {函数} mimetypes.guess_extension (type, strict=True)

根据由 @emph{type} 给出的文件 MIME 类型猜测其扩展名。 返回值是一个表示文件扩展名的字符串，包括开头的点号 (@code{'.'})。 该扩展名不保证能关联到任何特定的数据流，但是将会由 @ref{10ea,,guess_type()} 映射到 MIME 类型 @emph{type}。 如果不能猜测出 @emph{type} 的扩展名，则将返回 @code{None}。

可选的 @emph{strict} 参数具有与 @ref{10ea,,guess_type()} 函数一致的含义。
@end deffn

有一些附加函数和数据项可被用于控制此模块的行为。

@geindex init() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes init}@anchor{10eb}
@deffn {函数} mimetypes.init (files=None)

初始化内部数据结构。 @emph{files} 如果给出则必须是一个文件名序列，它应当被用于协助默认的类型映射。 如果省略则要使用的文件名会从 @ref{2ac6,,knownfiles} 中获取； 在 Windows 上，将会载入当前注册表设置。  在 @emph{files} 或 @ref{2ac6,,knownfiles} 中指定的每个文件名的优先级将高于在它之前的文件名。 @ref{10eb,,init()} 允许被重复调用。

为 @emph{files} 指定一个空列表将防止应用系统默认选项：将只保留来自内置列表的常用值。

如果 @emph{files} 为 @code{None} 则内部数据结构会完全重建为其初始默认值。 这是一个稳定操作并将在多次调用时产生相同的结果。


在 3.2 版更改: 在之前版本中，Windows 注册表设置会被忽略。

@end deffn

@geindex read_mime_types() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes read_mime_types}@anchor{1063}
@deffn {函数} mimetypes.read_mime_types (filename)

载入在文件 @emph{filename} 中给定的类型映射，如果文件存在的话。 返回的类型映射会是一个字典，其中的键值对为文件扩展名包括开头的点号 (@code{'.'}) 与 @code{'type/subtype'} 形式的字符串。 如果文件 @emph{filename} 不存在或无法被读取，则返回 @code{None}。
@end deffn

@geindex add_type() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes add_type}@anchor{2ac7}
@deffn {函数} mimetypes.add_type (type, ext, strict=True)

添加一个从 MIME 类型 @emph{type} 到扩展名 @emph{ext} 的映射。 当扩展名已知时，新类型将替代旧类型。 当类型已知时，扩展名将被添加到已知扩展名列表。

当 @emph{strict} 为 @code{True} 时（默认值），映射将被添加到官方 MIME 类型，否则添加到非标准类型。
@end deffn

@geindex inited() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes inited}@anchor{2ac8}
@deffn {数据} mimetypes.inited

指明全局数据结构是否已被初始化的旗标。 这会由 @ref{10eb,,init()} 设为 @code{True}。
@end deffn

@geindex knownfiles() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes knownfiles}@anchor{2ac6}
@deffn {数据} mimetypes.knownfiles

@geindex file; mime.types

通常安装的类型映射文件名列表。 这些文件一般被命名为 @code{mime.types} 并会由不同的包安装在不同的位置。
@end deffn

@geindex suffix_map() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes suffix_map}@anchor{2ac9}
@deffn {数据} mimetypes.suffix_map

将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其编码格式和类型是由相同的扩展名来指明的。 例如，@code{.tgz} 扩展名被映射到 @code{.tar.gz} 以允许编码格式和类型被分别识别。
@end deffn

@geindex encodings_map() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes encodings_map}@anchor{2aca}
@deffn {数据} mimetypes.encodings_map

映射文件扩展名到编码格式类型的字典。
@end deffn

@geindex types_map() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes types_map}@anchor{2acb}
@deffn {数据} mimetypes.types_map

映射文件扩展名到 MIME 类型的字典。
@end deffn

@geindex common_types() (在 mimetypes 模块中)
@anchor{library/mimetypes mimetypes common_types}@anchor{2acc}
@deffn {数据} mimetypes.common_types

映射文件扩展名到非标准但常见的 MIME 类型的字典。
@end deffn

此模块一个使用示例:

@example
>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'
@end example

@menu
* MimeTypes 对象:: 

@end menu

@node MimeTypes 对象,,,mimetypes --- 映射文件名到 MIME 类型
@anchor{library/mimetypes id1}@anchor{2acd}@anchor{library/mimetypes mimetypes-objects}@anchor{2ace}
@subsubsection MimeTypes 对象


@ref{2acf,,MimeTypes} 类可以被用于那些需要多个 MIME 类型数据库的应用程序；它提供了与 @ref{b2,,mimetypes} 模块所提供的类似接口。

@geindex MimeTypes (mimetypes 中的类)
@anchor{library/mimetypes mimetypes MimeTypes}@anchor{2acf}
@deffn {类} mimetypes.MimeTypes (filenames=(), strict=True)

这个类表示 MIME 类型数据库。  默认情况下，它提供了对与此模块其余部分一致的数据库的访问权限。 这个初始数据库是此模块所提供数据库的一个副本，并可以通过使用 @ref{2ad0,,read()} 或 @ref{2ad1,,readfp()} 方法将附加的 @code{mime.types} 样式文载入到数据库中来进行扩展。 如果不需要默认数据的话这个映射字典也可以在载入附加数据之前先被清空。

可选的 @emph{filenames} 形参可被用来让附加文件被载入到默认数据库“之上”。

@geindex suffix_map (mimetypes.MimeTypes 属性)
@anchor{library/mimetypes mimetypes MimeTypes suffix_map}@anchor{2ad2}
@deffn {属性} suffix_map

将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其编码格式和类型是由相同的扩展名来指明的。 例如，@code{.tgz} 扩展名被映射到 @code{.tar.gz} 以允许编码格式和类型被分别识别。 这是在模块中定义的全局 @ref{2ac9,,suffix_map} 的一个副本。
@end deffn

@geindex encodings_map (mimetypes.MimeTypes 属性)
@anchor{library/mimetypes mimetypes MimeTypes encodings_map}@anchor{2ad3}
@deffn {属性} encodings_map

映射文件扩展名到编码格式类型的字典。 这是在模块中定义的全局 @ref{2aca,,encodings_map} 的一个副本。
@end deffn

@geindex types_map (mimetypes.MimeTypes 属性)
@anchor{library/mimetypes mimetypes MimeTypes types_map}@anchor{2ad4}
@deffn {属性} types_map

包含两个字典的元组，将文件扩展名映射到 MIME 类型：第一个字典针对非标准类型而第二个字典针对标准类型。 它们会由 @ref{2acc,,common_types} 和 @ref{2acb,,types_map} 来初始化。
@end deffn

@geindex types_map_inv (mimetypes.MimeTypes 属性)
@anchor{library/mimetypes mimetypes MimeTypes types_map_inv}@anchor{2ad5}
@deffn {属性} types_map_inv

包含两个字典的元组，将 MIME 类型映射到文件扩展名列表：第一个字典针对非标准类型而第二个字典针对标准类型。 它们会由 @ref{2acc,,common_types} 和 @ref{2acb,,types_map} 来初始化。
@end deffn

@geindex guess_extension() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes guess_extension}@anchor{2ad6}
@deffn {方法} guess_extension (type, strict=True)

类似于 @ref{2ac5,,guess_extension()} 函数，使用存储的表作为对象的一部分。
@end deffn

@geindex guess_type() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes guess_type}@anchor{11a5}
@deffn {方法} guess_type (url, strict=True)

类似于 @ref{10ea,,guess_type()} 函数，使用存储的表作为对象的一部分。
@end deffn

@geindex guess_all_extensions() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes guess_all_extensions}@anchor{2ad7}
@deffn {方法} guess_all_extensions (type, strict=True)

类似于 @ref{fbb,,guess_all_extensions()} 函数，使用存储的表作为对象的一部分。
@end deffn

@geindex read() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes read}@anchor{2ad0}
@deffn {方法} read (filename, strict=True)

从名称为 @emph{filename} 的文件载入 MIME 信息。 此方法使用 @ref{2ad1,,readfp()} 来解析文件。

如果 @emph{strict} 为 @code{True}，信息将被添加到标准类型列表，否则添加到非标准类型列表。
@end deffn

@geindex readfp() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes readfp}@anchor{2ad1}
@deffn {方法} readfp (fp, strict=True)

从打开的文件 @emph{fp} 载入 MIME 类型信息。  文件必须具有标准 @code{mime.types} 文件的格式。

如果 @emph{strict} 为 @code{True}，信息将被添加到标准类型列表，否则添加到非标准类型列表。
@end deffn

@geindex read_windows_registry() (mimetypes.MimeTypes 方法)
@anchor{library/mimetypes mimetypes MimeTypes read_windows_registry}@anchor{2ad8}
@deffn {方法} read_windows_registry (strict=True)

从 Windows 注册表载入 MIME 类型信息。

@ref{14c1,,可用性}: Windows。

如果 @emph{strict} 为 @code{True}，信息将被添加到标准类型列表，否则添加到非标准类型列表。


3.2 新版功能.

@end deffn
@end deffn

@node base64 --- Base16 Base32 Base64 Base85 数据编码,binhex --- 对binhex4文件进行编码和解码,mimetypes --- 映射文件名到 MIME 类型,互联网数据处理
@anchor{library/base64 doc}@anchor{2ad9}@anchor{library/base64 base64-base16-base32-base64-base85-data-encodings}@anchor{2ada}@anchor{library/base64 module-base64}@anchor{d}
@subsection @code{base64} --- Base16, Base32, Base64, Base85 数据编码


@geindex base64 (模块)

@strong{源代码：} Lib/base64.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/base64.py}

@geindex base64; encoding
@geindex MIME; base64 encoding


__________________________________________________________________


此模块提供了将二进制数据编码为可打印的 ASCII 字符以及将这些编码解码回二进制数据的函数。它为 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://tools.ietf.org/html/rfc3548.html} 指定的 Base16, Base32 和 Base64 编码以及已被广泛接受的 Ascii85 和 Base85 编码提供了编码和解码函数。

@geindex RFC; RFC 3548
RFC 3548@footnote{https://tools.ietf.org/html/rfc3548.html} 编码的目的是使得二进制数据可以作为电子邮件的内容正确地发送，用作 URL 的一部分，或者作为 HTTP POST 请求的一部分。其中的编码算法和 @code{uuencode} 程序是不同的。

此模块提供了两个接口。新的接口提供了从 @ref{6e9,,类字节对象} 到 ASCII 字节 @ref{172,,bytes} 的编码，以及将 ASCII 的 @ref{6e9,,类字节对象} 或字符串解码到 @ref{172,,bytes} 的操作。此模块支持定义在 
@geindex RFC; RFC 3548
RFC 3548@footnote{https://tools.ietf.org/html/rfc3548.html} 中的所有 base-64 字母表 （普通的、URL 安全的和文件系统安全的）。

旧的接口不提供从字符串的解码操作，但提供了操作 @ref{c1d,,文件对象} 的编码和解码函数。旧接口只支持标准的 Base64 字母表，并且按照 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} 的规范每 76 个字符增加一个换行符。注意：如果你需要支持 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html}，那么使用 @ref{67,,email} 模块可能更加合适。


在 3.3 版更改: 新的接口提供的解码函数现在已经支持只包含 ASCII 的 Unicode 字符串。



在 3.4 版更改: 所有 @ref{6e9,,类字节对象} 现在已经被所有编码和解码函数接受。添加了对 Ascii85/Base85 的支持。


新的接口提供：

@geindex b64encode() (在 base64 模块中)
@anchor{library/base64 base64 b64encode}@anchor{2adb}
@deffn {函数} base64.b64encode (s, altchars=None)

对 @ref{6e9,,bytes-like object} @emph{s} 进行 Base64 编码，并返回编码后的 @ref{172,,bytes}。

可选项 @emph{altchars} 必须是一个长 2 字节的 @ref{6e9,,bytes-like object}，它指定了用于替换 @code{+} 和 @code{/} 的字符。这允许应用程序生成 URL 或文件系统安全的 Base64 字符串。默认值是 @code{None}，使用标准 Base64 字母表。
@end deffn

@geindex b64decode() (在 base64 模块中)
@anchor{library/base64 base64 b64decode}@anchor{10ec}
@deffn {函数} base64.b64decode (s, altchars=None, validate=False)

解码 Base64 编码过的 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s} 并返回解码过的 @ref{172,,bytes}。

可选项 @emph{altchars} 必须是一个长 2 字节的 @ref{6e9,,bytes-like object}，它指定了用于替换 @code{+} 和 @code{/} 的字符。

如果 @emph{s} 被不正确地填写，一个 @ref{a48,,binascii.Error} 错误将被抛出。

如果 @emph{validate} 值为 @code{False} （默认情况），则在填充检查前，将丢弃既不在标准 base-64 字母表之中也不在备用字母表中的字符。如果 @emph{validate} 为 @code{True}，这些非 base64 字符将导致 @ref{a48,,binascii.Error}。
@end deffn

@geindex standard_b64encode() (在 base64 模块中)
@anchor{library/base64 base64 standard_b64encode}@anchor{2adc}
@deffn {函数} base64.standard_b64encode (s)

编码 @ref{6e9,,bytes-like object} @emph{s}，使用标准 Base64 字母表并返回编码过的 @ref{172,,bytes}。
@end deffn

@geindex standard_b64decode() (在 base64 模块中)
@anchor{library/base64 base64 standard_b64decode}@anchor{2add}
@deffn {函数} base64.standard_b64decode (s)

解码 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s}，使用标准 Base64 字母表并返回编码过的 @ref{172,,bytes}。
@end deffn

@geindex urlsafe_b64encode() (在 base64 模块中)
@anchor{library/base64 base64 urlsafe_b64encode}@anchor{2ade}
@deffn {函数} base64.urlsafe_b64encode (s)

编码 @ref{6e9,,bytes-like object} @emph{s}，使用 URL 与文件系统安全的字母表，使用 @code{-} 以及 @code{_} 代替标准 Base64 字母表中的 @code{+} 和 @code{/}。返回编码过的 @ref{172,,bytes}。结果中可能包含 @code{=}。
@end deffn

@geindex urlsafe_b64decode() (在 base64 模块中)
@anchor{library/base64 base64 urlsafe_b64decode}@anchor{2adf}
@deffn {函数} base64.urlsafe_b64decode (s)

解码 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s}，使用 URL 与文件系统安全的字母表，使用 @code{-} 以及 @code{_} 代替标准 Base64 字母表中的 @code{+} 和 @code{/}。返回解码过的 @ref{172,,bytes}
@end deffn

@geindex b32encode() (在 base64 模块中)
@anchor{library/base64 base64 b32encode}@anchor{2ae0}
@deffn {函数} base64.b32encode (s)

用 Base32 编码 @ref{6e9,,bytes-like object} @emph{s} 并返回编码过的 @ref{172,,bytes}
@end deffn

@geindex b32decode() (在 base64 模块中)
@anchor{library/base64 base64 b32decode}@anchor{a47}
@deffn {函数} base64.b32decode (s, casefold=False, map01=None)

解码 Base32 编码过的 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s} 并返回解码过的 @ref{172,,bytes}。

可选的 @emph{casefold} 是一个指定小写字幕是否可接受为输入的标志。为了安全考虑，默认值为 @code{False}。

@geindex RFC; RFC 3548
RFC 3548@footnote{https://tools.ietf.org/html/rfc3548.html} 允许将字母 0(zero) 映射为字母 O(oh)，并可以选择是否将字母 1(one) 映射为 I(eye) 或 L(el)。可选参数 @emph{map01} 不是 @code{None} 时，它的值指定 1 的映射目标 (I 或 l)，当 @emph{map01} 非 @code{None} 时， 0 总是被映射为 O。为了安全考虑，默认值被设为 @code{None}，如果是这样， 0 和 1 不允许被作为输入。

如果 @emph{s} 被错误地填写或输入中存在字母表之外的字符，将抛出 @ref{a48,,binascii.Error}。
@end deffn

@geindex b16encode() (在 base64 模块中)
@anchor{library/base64 base64 b16encode}@anchor{2ae1}
@deffn {函数} base64.b16encode (s)

用 Base16 编码 @ref{6e9,,bytes-like object} @emph{s} 并返回编码过的 @ref{172,,bytes}
@end deffn

@geindex b16decode() (在 base64 模块中)
@anchor{library/base64 base64 b16decode}@anchor{2ae2}
@deffn {函数} base64.b16decode (s, casefold=False)

解码 Base16 编码过的 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s} 并返回解码过的 @ref{172,,bytes}。

可选的 @emph{casefold} 是一个指定小写字幕是否可接受为输入的标志。为了安全考虑，默认值为 @code{False}。

如果 @emph{s} 被错误地填写或输入中存在字母表之外的字符，将抛出 @ref{a48,,binascii.Error}。
@end deffn

@geindex a85encode() (在 base64 模块中)
@anchor{library/base64 base64 a85encode}@anchor{91b}
@deffn {函数} base64.a85encode (b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

用 Ascii85 编码 @ref{6e9,,bytes-like object} @emph{s} 并返回编码过的 @ref{172,,bytes}

@emph{foldspaces} 是一个可选的标志，使用特殊的短序列 'y' 代替 'btoa' 提供的 4 个连续空格 (ASCII 0x20)。这个特性不被 "标准" Ascii85 编码支持。

@emph{wrapcol} 控制了输出是否包含换行符 (@code{b'\n'}). 如果该值非零, 则每一行只有该值所限制的字符长度.

@emph{pad} 控制在编码之前输入是否填充为4的倍数。请注意，@code{btoa} 实现总是填充。

@emph{adobe} 控制编码后的字节序列是否要加上 @code{<~} 和 @code{~>}，这是 Adobe 实现所使用的。


3.4 新版功能.

@end deffn

@geindex a85decode() (在 base64 模块中)
@anchor{library/base64 base64 a85decode}@anchor{91c}
@deffn {函数} base64.a85decode (b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')

解码 Ascii85 编码过的 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{s} 并返回解码过的 @ref{172,,bytes}。

@emph{foldspaces} 旗标指明是否应接受 'y' 短序列作为 4 个连续空格 (ASCII 0x20) 的快捷方式。 此特性不被 "标准" Ascii85 编码格式所支持。

@emph{adobe} 控制输入序列是否为 Adobe Ascii85 格式 (即附加 <~ 和 ~>)。

@emph{ignorechars} 应当是一个 @ref{6e9,,bytes-like object} 或 ASCII 字符串，其中包含要从输入中忽略的字符。 这应当只包含空白字符，并且默认包含 ASCII 中所有的空白字符。


3.4 新版功能.

@end deffn

@geindex b85encode() (在 base64 模块中)
@anchor{library/base64 base64 b85encode}@anchor{91d}
@deffn {函数} base64.b85encode (b, pad=False)

用 base85（如 git 风格的二进制 diff 数据所用格式）编码 @ref{6e9,,bytes-like object} @emph{b} 并返回编码后的 @ref{172,,bytes}。

如果 @emph{pad} 为真值，输入将以 @code{b'\0'} 填充以使其编码前长度为 4 字节的倍数。


3.4 新版功能.

@end deffn

@geindex b85decode() (在 base64 模块中)
@anchor{library/base64 base64 b85decode}@anchor{91e}
@deffn {函数} base64.b85decode (b)

解码 base85 编码过的 @ref{6e9,,bytes-like object} 或 ASCII 字符串 @emph{b} 并返回解码过的 @ref{172,,bytes}。 如有必要，填充会被隐式地移除。


3.4 新版功能.

@end deffn

旧式接口:

@geindex decode() (在 base64 模块中)
@anchor{library/base64 base64 decode}@anchor{2ae3}
@deffn {函数} base64.decode (input, output)

解码二进制 @emph{input} 文件的内容并将结果二进制数据写入 @emph{output} 文件。 @emph{input} 和 @emph{output} 必须为 @ref{c1d,,文件对象}. @emph{input} 将被读取直至 @code{input.readline()} 返回空字节串对象。
@end deffn

@geindex decodebytes() (在 base64 模块中)
@anchor{library/base64 base64 decodebytes}@anchor{224}
@deffn {函数} base64.decodebytes (s)

解码 @ref{6e9,,bytes-like object} @emph{s}，该对象必须包含一行或多行 base64 编码的数据，并返回已解码的 @ref{172,,bytes}。


3.1 新版功能.

@end deffn

@geindex encode() (在 base64 模块中)
@anchor{library/base64 base64 encode}@anchor{2ae4}
@deffn {函数} base64.encode (input, output)

编码二进制 @emph{input} 文件的内容并将经 base64 编码的数据写入 @emph{output} 文件。 @emph{input} 和 @emph{output} 必须为 @ref{c1d,,文件对象}。 @emph{input} 将被读取直到 @code{input.read()} 返回空字节串对象。 @ref{2ae4,,encode()} 会在每输出 76 个字节之后插入一个换行符 (@code{b'\n'})，并会确保输出总是以换行符来结束，如 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} (MIME) 所规定的那样。
@end deffn

@geindex encodebytes() (在 base64 模块中)
@anchor{library/base64 base64 encodebytes}@anchor{223}
@deffn {函数} base64.encodebytes (s)

编码 @ref{6e9,,bytes-like object} @emph{s}，其中可以包含任意二进制数据，并返回包含经 base64 编码数据的 @ref{172,,bytes}，每输出 76 个字节之后将带一个换行符 (@code{b'\n'})，并会确保在末尾也有一个换行符，如 
@geindex RFC; RFC 2045
RFC 2045@footnote{https://tools.ietf.org/html/rfc2045.html} (MIME) 所规定的那样。


3.1 新版功能.

@end deffn

此模块的一个使用示例:

@example
>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{f,,binascii}

支持模块，包含ASCII到二进制和二进制到ASCII转换。

@geindex RFC; RFC 1521

@item RFC 1521@footnote{https://tools.ietf.org/html/rfc1521.html} - MIME (Multipurpose Internet Mail Extensions) 第一部分：规定并描述因特网消息体的格式的机制。

第 5.2 节，“Base64 内容转换编码格式” 提供了 base64 编码格式的定义。
@end table


@node binhex --- 对binhex4文件进行编码和解码,binascii --- 二进制和 ASCII 码互转,base64 --- Base16 Base32 Base64 Base85 数据编码,互联网数据处理
@anchor{library/binhex doc}@anchor{2ae5}@anchor{library/binhex binhex-encode-and-decode-binhex4-files}@anchor{2ae6}@anchor{library/binhex module-binhex}@anchor{10}
@subsection @code{binhex} --- 对binhex4文件进行编码和解码


@geindex binhex (模块)

@strong{源代码:} Lib/binhex.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/binhex.py}


3.9 版后已移除.



__________________________________________________________________


此模块以binhe4格式对文件进行编码和解码，该格式允许Macintosh文件以ASCII格式表示。仅处理数据分支。

@ref{10,,binhex} 模块定义了以下功能：

@geindex binhex() (在 binhex 模块中)
@anchor{library/binhex binhex binhex}@anchor{2ae7}
@deffn {函数} binhex.binhex (input, output)

将带有文件名 @emph{输入} 的二进制文件转换为binhex文件 @emph{输出} 。输出参数可以是文件名或类文件对象（ @code{write()} 和 @code{close()} 方法的任何对象）。
@end deffn

@geindex hexbin() (在 binhex 模块中)
@anchor{library/binhex binhex hexbin}@anchor{2ae8}
@deffn {函数} binhex.hexbin (input, output)

解码binhex文件输入。  @emph{输入} 可以是支持 @code{read()} 和 @code{close()} 方法的文件名或类文件对象。生成的文件将写入名为 @emph{output} 的文件，除非参数为 @code{None} ，在这种情况下，从binhex文件中读取输出文件名。
@end deffn

还定义了以下异常：

@geindex Error
@anchor{library/binhex binhex Error}@anchor{2ae9}
@deffn {例外} binhex.Error

当无法使用binhex格式编码某些内容时（例如，文件名太长而无法放入文件名字段中），或者输入未正确编码的binhex数据时，会引发异常。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{f,,binascii}

支持模块，包含ASCII到二进制和二进制到ASCII转换。
@end table


@menu
* 注释: 注释<3>. 

@end menu

@node 注释<3>,,,binhex --- 对binhex4文件进行编码和解码
@anchor{library/binhex binhex-notes}@anchor{2aea}@anchor{library/binhex notes}@anchor{2aeb}
@subsubsection 注释


还有一个替代的、功能更强大的编码器和解码器接口，详细信息请参见源代码。

如果您在非Macintosh平台上编码或解码文本文件，它们仍将使用旧的Macintosh换行符约定（回车符作为行尾）。

@node binascii --- 二进制和 ASCII 码互转,quopri --- 编码与解码经过 MIME 转码的可打印数据,binhex --- 对binhex4文件进行编码和解码,互联网数据处理
@anchor{library/binascii doc}@anchor{2aec}@anchor{library/binascii binascii-convert-between-binary-and-ascii}@anchor{2aed}@anchor{library/binascii module-binascii}@anchor{f}
@subsection @code{binascii} --- 二进制和 ASCII 码互转


@geindex binascii (模块)

@geindex 模块; uu
@geindex 模块; base64
@geindex 模块; binhex


__________________________________________________________________


@ref{f,,binascii} 模块包含很多在二进制和二进制表示的各种ASCII码之间转换的方法。 通常情况不会直接使用这些函数，而是使用像  @ref{12c,,uu} ， @ref{d,,base64} ，或 @ref{10,,binhex} 这样的封装模块。 为了执行效率高，@ref{f,,binascii} 模块含有许多用 C 写的低级函数，这些底层函数被一些高级模块所使用。

@cartouche
@quotation 注解 
@code{a2b_*} 函数接受只含有 ASCII 码的Unicode 字符串。其他函数只接受 @ref{6e9,,字节类对象} （例如 @ref{172,,bytes}，@ref{173,,bytearray} 和其他支持缓冲区协议的对象）。


在 3.3 版更改: ASCII-only unicode strings are now accepted by the @code{a2b_*} functions.

@end quotation
@end cartouche

@ref{f,,binascii} 模块定义了以下函数：

@geindex a2b_uu() (在 binascii 模块中)
@anchor{library/binascii binascii a2b_uu}@anchor{2aee}
@deffn {函数} binascii.a2b_uu (string)

将单行 uu 编码数据转换成二进制数据并返回。uu 编码每行的数据通常包含45 个（二进制）字节，最后一行除外。每行数据后面可能跟有空格。
@end deffn

@geindex b2a_uu() (在 binascii 模块中)
@anchor{library/binascii binascii b2a_uu}@anchor{47e}
@deffn {函数} binascii.b2a_uu (data, *, backtick=False)

将二进制数据转换为 ASCII 编码字符，返回值是转换后的行数据，包括换行符。 @emph{data} 的长度最多为45。如果 @emph{backtick} 为ture，则零由 @code{'`'} 而不是空格表示。


在 3.7 版更改: 增加 @emph{backtick} 形参。

@end deffn

@geindex a2b_base64() (在 binascii 模块中)
@anchor{library/binascii binascii a2b_base64}@anchor{1123}
@deffn {函数} binascii.a2b_base64 (string)

将 base64 数据块转换成二进制并以二进制数据形式返回。一次可以传递多行数据。
@end deffn

@geindex b2a_base64() (在 binascii 模块中)
@anchor{library/binascii binascii b2a_base64}@anchor{625}
@deffn {函数} binascii.b2a_base64 (data, *, newline=True)

将二进制数据转换为一行用 base64 编码的ASCII字符串。返回值是转换后的行数据，如果 @emph{newline} 为true，则返回值包括换行符。该函数的输出符合：rfc：@cite{3548}。


在 3.6 版更改: 增加 @emph{newline} 形参。

@end deffn

@geindex a2b_qp() (在 binascii 模块中)
@anchor{library/binascii binascii a2b_qp}@anchor{2aef}
@deffn {函数} binascii.a2b_qp (data, header=False)

将一个引号可打印的数据块转换成二进制数据并返回。一次可以转换多行。如果可选参数 @emph{header} 存在且为true，则数据中的下划线将被解码成空格。
@end deffn

@geindex b2a_qp() (在 binascii 模块中)
@anchor{library/binascii binascii b2a_qp}@anchor{2af0}
@deffn {函数} binascii.b2a_qp (data, quotetabs=False, istext=True, header=False)

将二进制数据转换为一行或多行带引号可打印编码的ASCII字符串。返回值是转换后的行数据。如果可选参数 @emph{quotetabs} 存在且为真值，则对所有制表符和空格进行编码。如果可选参数 @emph{istext} 存在且为真值，则不对新行进行编码，但将对尾随空格进行编码。如果可选参数 @emph{header} 存在且为true，则空格将被编码为下划线 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://tools.ietf.org/html/rfc1522.html}。如果可选参数 @emph{header} 存在且为假值，则也会对换行符进行编码;不进行换行转换编码可能会破坏二进制数据流。
@end deffn

@geindex a2b_hqx() (在 binascii 模块中)
@anchor{library/binascii binascii a2b_hqx}@anchor{20a}
@deffn {函数} binascii.a2b_hqx (string)

将 binhex4 格式的 ASCII 数据不进行 RLE 解压缩直接转换为二进制数据。该字符串应包含完整数量的二进制字节，或者（在binhex4 数据最后部分）剩余位为零。


3.9 版后已移除.

@end deffn

@geindex rledecode_hqx() (在 binascii 模块中)
@anchor{library/binascii binascii rledecode_hqx}@anchor{20c}
@deffn {函数} binascii.rledecode_hqx (data)

根据 binhex4 标准对数据执行 RLE 解压缩。该算法在一个字节的数据后使用 @code{0x90} 作为重复指示符，然后计数。计数 @code{0} 指定字节值 @code{0x90} 。该例程返回解压缩的数据，输入数据以孤立的重复指示符结束的情况下，将引发 @ref{2af1,,Incomplete} 异常。


在 3.2 版更改: 仅接受 bytestring 或 bytearray 对象作为输入。



3.9 版后已移除.

@end deffn

@geindex rlecode_hqx() (在 binascii 模块中)
@anchor{library/binascii binascii rlecode_hqx}@anchor{20b}
@deffn {函数} binascii.rlecode_hqx (data)

在 @emph{data} 上执行 binhex4 游程编码压缩并返回结果。


3.9 版后已移除.

@end deffn

@geindex b2a_hqx() (在 binascii 模块中)
@anchor{library/binascii binascii b2a_hqx}@anchor{209}
@deffn {函数} binascii.b2a_hqx (data)

执行 hexbin4 类型二进制到 ASCII 码的转换并返回结果字符串。输入数据应经过 RLE 编码，且数据长度可被3整除（除了最后一个片段）。


3.9 版后已移除.

@end deffn

@geindex crc_hqx() (在 binascii 模块中)
@anchor{library/binascii binascii crc_hqx}@anchor{10cf}
@deffn {函数} binascii.crc_hqx (data, value)

以 @emph{value} 作为初始 CRC 计算 @emph{data} 的16位 CRC 值，返回其结果。这里使用 CRC-CCITT 生成多项式 @emph{x}@w{^16} + @emph{x}@w{^12} + @emph{x}@w{^5} + 1 ，通常表示为0x1021。该 CRC 被用于 binhex4 格式。
@end deffn

@geindex crc32() (在 binascii 模块中)
@anchor{library/binascii binascii crc32}@anchor{f88}
@deffn {函数} binascii.crc32 (data[, value])

计算 CRC-32，即 @emph{data} 的无符号 32 位校验和，初始 CRC 值为 @emph{value}。 默认的初始 CRC 值为零。 该算法与 ZIP 文件校验和算法一致。 由于该算法被设计用作校验和算法，因此不适合用作通用哈希算法。 使用方式如下:

@example
print(binascii.crc32(b"hello world"))
# Or, in two pieces:
crc = binascii.crc32(b"hello")
crc = binascii.crc32(b" world", crc)
print('crc32 = @{:#010x@}'.format(crc))
@end example


在 3.0 版更改: 结果值将始终为无符号类型。 要在使用 Python 2 或更早版本时生成同样的数值，请使用 @code{crc32(data) & 0xffffffff}。

@end deffn

@geindex b2a_hex() (在 binascii 模块中)
@geindex hexlify() (在 binascii 模块中)
@anchor{library/binascii binascii b2a_hex}@anchor{1a02}
@deffn {函数} binascii.b2a_hex (data[, sep[, bytes_per_sep=1]])
@anchor{library/binascii binascii hexlify}@anchor{1141}
@deffnx {函数} binascii.hexlify (data[, sep[, bytes_per_sep=1]])

返回二进制数据 @emph{data} 的十六进制表示形式。 @emph{data} 的每个字节都被转换为相应的2位十六进制表示形式。因此返回的字节对象的长度是 @emph{data} 的两倍。

使用：@ref{72e,,bytes.hex()} 方法也可以方便地实现相似的功能（但仅返回文本字符串）。

如果指定了 @emph{sep}，它必须为单字符 str 或 bytes 对象。 它将被插入每个 @emph{bytes_per_sep} 输入字节之后。 分隔符位置默认从输出的右端开始计数，如果你希望从左端开始计数，请提供一个负的 @emph{bytes_per_sep} 值。

@example
>>> import binascii
>>> binascii.b2a_hex(b'\xb9\x01\xef')
b'b901ef'
>>> binascii.hexlify(b'\xb9\x01\xef', '-')
b'b9-01-ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
b'b9_01ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
b'b901 ef'
@end example


在 3.8 版更改: 添加了 @emph{sep} 和 @emph{bytes_per_sep} 形参。

@end deffn

@geindex a2b_hex() (在 binascii 模块中)
@geindex unhexlify() (在 binascii 模块中)
@anchor{library/binascii binascii a2b_hex}@anchor{1a03}
@deffn {函数} binascii.a2b_hex (hexstr)
@anchor{library/binascii binascii unhexlify}@anchor{11bd}
@deffnx {函数} binascii.unhexlify (hexstr)

返回由十六进制字符串  @emph{hexstr} 表示的二进制数据。此函数功能与 @ref{1a02,,b2a_hex()} 相反。 @emph{hexstr} 必须包含偶数个十六进制数字（可以是大写或小写），否则会引发  @ref{a48,,Error} 异常。

使用：@ref{447,,bytes.fromhex()}  类方法也实现相似的功能（仅接受文本字符串参数，不限制其中的空白字符）。
@end deffn

@geindex Error
@anchor{library/binascii binascii Error}@anchor{a48}
@deffn {例外} binascii.Error

通常是因为编程错误引发的异常。
@end deffn

@geindex Incomplete
@anchor{library/binascii binascii Incomplete}@anchor{2af1}
@deffn {例外} binascii.Incomplete

数据不完整引发的异常。通常不是编程错误导致的，可以通过读取更多的数据并再次尝试来处理该异常。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{d,,base64}

支持在16，32，64，85进制中进行符合 RFC 协议的 base64 样式编码。

@item 模块 @ref{10,,binhex}

支持在 Macintosh 上使用的 binhex 格式。

@item 模块 @ref{12c,,uu}

支持在 Unix 上使用的 UU 编码。

@item 模块 @ref{db,,quopri}

支持在 MIME 版本电子邮件中使用引号可打印编码。
@end table


@node quopri --- 编码与解码经过 MIME 转码的可打印数据,,binascii --- 二进制和 ASCII 码互转,互联网数据处理
@anchor{library/quopri doc}@anchor{2af2}@anchor{library/quopri module-quopri}@anchor{db}@anchor{library/quopri quopri-encode-and-decode-mime-quoted-printable-data}@anchor{2af3}
@subsection @code{quopri} --- 编码与解码经过 MIME 转码的可打印数据


@geindex quopri (模块)

@strong{源代码:} Lib/quopri.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/quopri.py}

@geindex quoted-printable; encoding
@geindex MIME; quoted-printable encoding


__________________________________________________________________


此模块会执行转换后可打印的传输编码与解码，具体定义见 
@geindex RFC; RFC 1521
RFC 1521@footnote{https://tools.ietf.org/html/rfc1521.html}: "MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies"。 转换后可打印的编码格式被设计用于只包含相对较少的不可打印字符的数据；如果存在大量这样的字符，通过 @ref{d,,base64} 模块所提供的 base64 编码方案会更为紧凑，例如当发送图片文件时。

@geindex decode() (在 quopri 模块中)
@anchor{library/quopri quopri decode}@anchor{1a05}
@deffn {函数} quopri.decode (input, output, header=False)

解码 @emph{input} 文件的内容并将已解码二进制数据结果写入 @emph{output} 文件。 @emph{input} 和 @emph{output} 必须为 @ref{c1d,,二进制文件对象}。 如果提供了可选参数 @emph{header} 且为真值，下划线将被解码为空格。 此函数可用于解码“Q”编码的头数据，具体描述见 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://tools.ietf.org/html/rfc1522.html}: "MIME (Multipurpose Internet Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text"。
@end deffn

@geindex encode() (在 quopri 模块中)
@anchor{library/quopri quopri encode}@anchor{1a04}
@deffn {函数} quopri.encode (input, output, quotetabs, header=False)

编码 @emph{input} 文件的内容并将转换后可打印的数据结果写入 @emph{output} 文件。 @emph{input} 和 @emph{output} 必须为 @ref{c1d,,二进制文件对象}. @emph{quotetabs} 是一个非可选的旗标，它控制是否要编码内嵌的空格与制表符；当为真值时将编码此类内嵌空白符，当为假值时则保持原样不进行编码。 请注意出现在行尾的空格与制表符总是会被编码，具体描述见 
@geindex RFC; RFC 1521
RFC 1521@footnote{https://tools.ietf.org/html/rfc1521.html}。 @emph{header} 旗标控制空格符是否要编码为下划线，具体描述见 
@geindex RFC; RFC 1522
RFC 1522@footnote{https://tools.ietf.org/html/rfc1522.html}。
@end deffn

@geindex decodestring() (在 quopri 模块中)
@anchor{library/quopri quopri decodestring}@anchor{2af4}
@deffn {函数} quopri.decodestring (s, header=False)

类似 @ref{1a05,,decode()}，区别在于它接受一个源 @ref{172,,bytes} 并返回对应的已解码 @ref{172,,bytes}。
@end deffn

@geindex encodestring() (在 quopri 模块中)
@anchor{library/quopri quopri encodestring}@anchor{2af5}
@deffn {函数} quopri.encodestring (s, quotetabs=False, header=False)

类型 @ref{1a04,,encode()}，区别在于它接受一个源 @ref{172,,bytes} 并返回对应的已编码 @ref{172,,bytes}。 在默认情况下，它会发送 @code{False} 值给 @ref{1a04,,encode()} 函数的 @emph{quotetabs} 形参。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{d,,base64}

编码与解码 MIME base64 数据
@end table


@node 结构化标记处理工具,互联网协议和支持,互联网数据处理,Python 标准库
@anchor{library/markup doc}@anchor{2af6}@anchor{library/markup markup}@anchor{2af7}@anchor{library/markup structured-markup-processing-tools}@anchor{2af8}
@section 结构化标记处理工具


Python 支持各种模块，以处理各种形式的结构化数据标记。 这包括使用标准通用标记语言（SGML）和超文本标记语言（HTML）的模块，以及使用可扩展标记语言（XML）的几个接口。

@menu
* html: html --- 超文本标记语言支持. 超文本标记语言支持
* html.parser: html parser --- 简单的 HTML 和 XHTML 解析器. 简单的 HTML 和 XHTML 解析器
* html.entities: html entities --- HTML 一般实体的定义. HTML 一般实体的定义
* XML处理模块:: 
* xml.etree.ElementTree: xml etree ElementTree --- ElementTree XML API. ElementTree XML API
* xml.dom: xml dom --- 文档对象模型 API. 文档对象模型 API
* xml.dom.minidom: xml dom minidom --- 最小化的 DOM 实现. 最小化的 DOM 实现
* xml.dom.pulldom: xml dom pulldom --- 支持构建部分 DOM 树. 支持构建部分 DOM 树
* xml.sax: xml sax --- 支持 SAX2 解析器. 支持 SAX2 解析器
* xml.sax.handler: xml sax handler --- SAX 处理句柄的基类. SAX 处理句柄的基类
* xml.sax.saxutils: xml sax saxutils --- SAX 工具集. SAX 工具集
* xml.sax.xmlreader: xml sax xmlreader --- 用于 XML 解析器的接口. 用于 XML 解析器的接口
* xml.parsers.expat: xml parsers expat --- 使用 Expat 的快速 XML 解析. 使用 Expat 的快速 XML 解析

@end menu

@node html --- 超文本标记语言支持,html parser --- 简单的 HTML 和 XHTML 解析器,,结构化标记处理工具
@anchor{library/html doc}@anchor{2af9}@anchor{library/html html-hypertext-markup-language-support}@anchor{2afa}@anchor{library/html module-html}@anchor{8f}
@subsection @code{html} --- 超文本标记语言支持


@geindex html (模块)

@strong{源码：} Lib/html/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/html/__init__.py}


__________________________________________________________________


该模块定义了操作HTML的工具。

@geindex escape() (在 html 模块中)
@anchor{library/html html escape}@anchor{a21}
@deffn {函数} html.escape (s, quote=True)

将字符串 @emph{s} 中的字符`@w{`}&`@w{`} 、 @code{<} 和 @code{>} 转换为安全的HTML序列。 如果需要在 HTML 中显示可能包含此类字符的文本，请使用此选项。 如果可选的标志 @emph{quote} 为真值，则字符 (@code{"}) 和 (@code{'}) 也被转换；这有助于包含在由引号分隔的 HTML 属性中，如 @code{<a href="...">}。


3.2 新版功能.

@end deffn

@geindex unescape() (在 html 模块中)
@anchor{library/html html unescape}@anchor{22c}
@deffn {函数} html.unescape (s)

将字符串 @emph{s} 中的所有命名和数字字符引用 (例如 @code{&gt;}, @code{&#62;}, @code{&#x3e;}) 转换为相应的Unicode字符。 此函数使用HTML 5标准为有效和无效字符引用定义的规则，以及 @ref{afc,,HTML 5 命名字符引用列表}。


3.4 新版功能.

@end deffn


__________________________________________________________________


@code{html} 包中的子模块是：


@itemize *

@item 
@ref{91,,html.parser} —— 具有宽松解析模式的HTML / XHTML解析器

@item 
@ref{90,,html.entities} -- HTML 实体定义
@end itemize

@node html parser --- 简单的 HTML 和 XHTML 解析器,html entities --- HTML 一般实体的定义,html --- 超文本标记语言支持,结构化标记处理工具
@anchor{library/html parser doc}@anchor{2afb}@anchor{library/html parser html-parser-simple-html-and-xhtml-parser}@anchor{2afc}@anchor{library/html parser module-html parser}@anchor{91}
@subsection @code{html.parser} --- 简单的 HTML 和 XHTML 解析器


@geindex html.parser (模块)

@strong{源代码：} Lib/html/parser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/html/parser.py}

@geindex HTML
@geindex XHTML


__________________________________________________________________


这个模块定义了一个 @ref{22b,,HTMLParser} 类，为 HTML（超文本标记语言）和 XHTML 文本文件解析提供基础。

@geindex HTMLParser (html.parser 中的类)
@anchor{library/html parser html parser HTMLParser}@anchor{22b}
@deffn {类} html.parser.HTMLParser (*, convert_charrefs=True)

创建一个能解析无效标记的解析器实例。

如果 @emph{convert_charrefs} 为 @code{True} (默认值)，则所有字符引用( @code{script}/@code{style}   元素中的除外)都会自动转换为相应的 Unicode 字符。

一个 @ref{22b,,HTMLParser} 类的实例用来接受 HTML 数据，并在标记开始、标记结束、文本、注释和其他元素标记出现的时候调用对应的方法。要实现具体的行为，请使用 @ref{22b,,HTMLParser} 的子类并重载其方法。

这个解析器不检查结束标记是否与开始标记匹配，也不会因外层元素完毕而隐式关闭了的元素引发结束标记处理。


在 3.4 版更改: @emph{convert_charrefs} 关键字参数被添加。



在 3.5 版更改: @emph{convert_charrefs} 参数的默认值现在为 @code{True}。

@end deffn

@menu
* HTML 解析器的示例程序:: 
* HTMLParser 方法:: 
* 示例: 示例<28>. 

@end menu

@node HTML 解析器的示例程序,HTMLParser 方法,,html parser --- 简单的 HTML 和 XHTML 解析器
@anchor{library/html parser example-html-parser-application}@anchor{2afd}
@subsubsection HTML 解析器的示例程序


下面是简单的 HTML 解析器的一个基本示例，使用 @ref{22b,,HTMLParser} 类，当遇到开始标记、结束标记以及数据的时候将内容打印出来。

@example
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')
@end example

输出是:

@example
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data  : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
@end example

@node HTMLParser 方法,示例<28>,HTML 解析器的示例程序,html parser --- 简单的 HTML 和 XHTML 解析器
@anchor{library/html parser htmlparser-methods}@anchor{2afe}
@subsubsection @code{HTMLParser} 方法


@ref{22b,,HTMLParser} 实例有下列方法：

@geindex feed() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser feed}@anchor{2aff}
@deffn {方法} HTMLParser.feed (data)

填充一些文本到解析器中。如果包含完整的元素，则被处理；如果数据不完整，将被缓冲直到更多的数据被填充，或者 @ref{2b00,,close()} 被调用。@emph{data} 必须为 @ref{206,,str} 类型。
@end deffn

@geindex close() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser close}@anchor{2b00}
@deffn {方法} HTMLParser.close ()

如同后面跟着一个文件结束标记一样，强制处理所有缓冲数据。这个方法能被派生类重新定义，用于在输入的末尾定义附加处理，但是重定义的版本应当始终调用基类 @ref{22b,,HTMLParser} 的 @ref{2b00,,close()} 方法。
@end deffn

@geindex reset() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser reset}@anchor{2b01}
@deffn {方法} HTMLParser.reset ()

重置实例。丢失所有未处理的数据。在实例化阶段被隐式调用。
@end deffn

@geindex getpos() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser getpos}@anchor{2b02}
@deffn {方法} HTMLParser.getpos ()

返回当前行号和偏移值。
@end deffn

@geindex get_starttag_text() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser get_starttag_text}@anchor{2b03}
@deffn {方法} HTMLParser.get_starttag_text ()

返回最近打开的开始标记中的文本。 结构化处理时通常应该不需要这个，但在处理“已部署”的 HTML 或是在以最小改变来重新生成输入时可能会有用处（例如可以保留属性间的空格等）。
@end deffn

下列方法将在遇到数据或者标记元素的时候被调用。他们需要在子类中重载。基类的实现中没有任何实际操作（除了 @ref{2b04,,handle_startendtag()} ）：

@geindex handle_starttag() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_starttag}@anchor{2b05}
@deffn {方法} HTMLParser.handle_starttag (tag, attrs)

调用此方法来处理一个元素的开始标记 (例如 @code{<div id="main">})。

@emph{tag} 参数是小写的标记名。@emph{attrs} 参数是一个 @code{(name, value)} 形式的列表，包含了所有在标记的 @code{<>}  括号中找到的属性。@emph{name} 转换为小写，@emph{value} 的引号被去除，字符和实体引用都会被替换。

实例中，对于标签 @code{<A HREF="https://www.cwi.nl/">}，这个方法将以下列形式被调用 @code{handle_starttag('a', [('href', 'https://www.cwi.nl/')])} 。

@ref{90,,html.entities} 中的所有实体引用，会被替换为属性值。
@end deffn

@geindex handle_endtag() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_endtag}@anchor{2b06}
@deffn {方法} HTMLParser.handle_endtag (tag)

此方法被用来处理元素的结束标记（例如： @code{</div>} ）。

@emph{tag} 参数是小写的标签名。
@end deffn

@geindex handle_startendtag() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_startendtag}@anchor{2b04}
@deffn {方法} HTMLParser.handle_startendtag (tag, attrs)

类似于 @ref{2b05,,handle_starttag()}, 只是在解析器遇到 XHTML 样式的空标记时被调用（ @code{<img ... />}）。这个方法能被需要这种特殊词法信息的子类重载；默认实现仅简单调用 @ref{2b05,,handle_starttag()} 和 @ref{2b06,,handle_endtag()} 。
@end deffn

@geindex handle_data() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_data}@anchor{2b07}
@deffn {方法} HTMLParser.handle_data (data)

这个方法被用来处理任意数据（例如：文本节点和 @code{<script>...</script>} 以及 @code{<style>...</style>} 中的内容）。
@end deffn

@geindex handle_entityref() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_entityref}@anchor{2b08}
@deffn {方法} HTMLParser.handle_entityref (name)

这个方法被用于处理 @code{&name;} 形式的命名字符引用（例如 @code{&gt;}），其中 @emph{name} 是通用的实体引用（例如： @code{'gt'}）。如果 @emph{convert_charrefs} 为 @code{True}，该方法永远不会被调用。
@end deffn

@geindex handle_charref() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_charref}@anchor{2b09}
@deffn {方法} HTMLParser.handle_charref (name)

这个方法被用来处理 @code{&#NNN;} 和 @code{&#xNNN;} 形式的十进制和十六进制字符引用。例如，@code{&gt;} 等效的十进制形式为 @code{&#62;} ，而十六进制形式为 @code{&#x3E;} ；在这种情况下，方法将收到  @code{'62'} 或 @code{'x3E'} 。如果 @emph{convert_charrefs} 为 @code{True} ，则该方法永远不会被调用。
@end deffn

@geindex handle_comment() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_comment}@anchor{2b0a}
@deffn {方法} HTMLParser.handle_comment (data)

这个方法在遇到注释的时候被调用（例如： @code{<!--comment-->} ）。

例如， @code{<!-- comment -->} 这个注释会用 @code{' comment '} 作为参数调用此方法。

Internet Explorer 条件注释（condcoms）的内容也被发送到这个方法，因此，对于 @code{<!--[if IE 9]>IE9-specific content<![endif]-->} ，这个方法将接收到 @code{'[if IE 9]>IE9-specific content<![endif]'} 。
@end deffn

@geindex handle_decl() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_decl}@anchor{2b0b}
@deffn {方法} HTMLParser.handle_decl (decl)

这个方法用来处理 HTML doctype 申明（例如 @code{<!DOCTYPE html>} ）。

@emph{decl} 形参为 @code{<!...>} 标记中的所有内容（例如： @code{'DOCTYPE html'} ）。
@end deffn

@geindex handle_pi() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser handle_pi}@anchor{2b0c}
@deffn {方法} HTMLParser.handle_pi (data)

此方法在遇到处理指令的时候被调用。@emph{data} 形参将包含整个处理指令。例如，对于处理指令 @code{<?proc color='red'>} ，这个方法将以 @code{handle_pi("proc color='red'")} 形式被调用。它旨在被派生类重载；基类实现中无任何实际操作。

@cartouche
@quotation 注解 
@ref{22b,,HTMLParser} 类使用 SGML 语法规则处理指令。使用 @code{'?'} 结尾的 XHTML 处理指令将导致 @code{'?'} 包含在 @emph{data} 中。
@end quotation
@end cartouche
@end deffn

@geindex unknown_decl() (html.parser.HTMLParser 方法)
@anchor{library/html parser html parser HTMLParser unknown_decl}@anchor{2b0d}
@deffn {方法} HTMLParser.unknown_decl (data)

当解析器读到无法识别的声明时，此方法被调用。

@emph{data} 形参为 @code{<![...]>} 标记中的所有内容。某些时候对派生类的重载很有用。基类实现中无任何实际操作。
@end deffn

@node 示例<28>,,HTMLParser 方法,html parser --- 简单的 HTML 和 XHTML 解析器
@anchor{library/html parser examples}@anchor{2b0e}@anchor{library/html parser htmlparser-examples}@anchor{2b0f}
@subsubsection 示例


下面的类实现了一个解析器，用于更多示例的演示:

@example
from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
@end example

解析一个文档类型声明:

@example
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
@end example

解析一个具有一些属性和标题的元素:

@example
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h1>Python</h1>')
Start tag: h1
Data     : Python
End tag  : h1
@end example

@code{script} 和 @code{style} 元素中的内容原样返回，无需进一步解析:

@example
>>> parser.feed('<style type="text/css">#python @{ color: green @}</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python @{ color: green @}
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
@end example

解析注释:

@example
>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
@end example

解析命名或数字形式的字符引用，并把他们转换到正确的字符（注意：这 3 种转义都是 @code{'>'} ）:

@example
>>> parser.feed('&gt;&#62;&#x3E;')
Named ent: >
Num ent  : >
Num ent  : >
@end example

填充不完整的块给 @ref{2aff,,feed()} 执行，@ref{2b07,,handle_data()} 可能会多次调用（除非 @emph{convert_charrefs} 被设置为 @code{True} ）:

@example
>>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
...     parser.feed(chunk)
...
Start tag: span
Data     : buff
Data     : ered
Data     : text
End tag  : span
@end example

解析无效的 HTML (例如：未引用的属性）也能正常运行:

@example
>>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
     attr: ('class', 'link')
     attr: ('href', '#main')
Data     : tag soup
End tag  : p
End tag  : a
@end example

@node html entities --- HTML 一般实体的定义,XML处理模块,html parser --- 简单的 HTML 和 XHTML 解析器,结构化标记处理工具
@anchor{library/html entities doc}@anchor{2b10}@anchor{library/html entities html-entities-definitions-of-html-general-entities}@anchor{2b11}@anchor{library/html entities module-html entities}@anchor{90}
@subsection @code{html.entities} --- HTML 一般实体的定义


@geindex html.entities (模块)

@strong{源码：} Lib/html/entities.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/html/entities.py}


__________________________________________________________________


该模块定义了四个词典， @ref{afc,,html5}、 @ref{2b12,,name2codepoint}、 @ref{2b13,,codepoint2name}、以及 @ref{2b14,,entitydefs}。

@geindex html5() (在 html.entities 模块中)
@anchor{library/html entities html entities html5}@anchor{afc}
@deffn {数据} html.entities.html5

将 HTML5 命名字符引用 @footnote{@w{(1)} 
参见 @indicateurl{https://html.spec.whatwg.org/multipage/syntax.html#named-character-references}
} 映射到等效的 Unicode 字符的字典，例如 @code{html5['gt;'] == '>'}。 请注意，尾随的分号包含在名称中（例如 @code{'gt;'} ），但是即使没有分号，一些名称也会被标准接受，在这种情况下，名称出现时带有和不带有 @code{';'}。另见 @ref{22c,,html.unescape()}。


3.3 新版功能.

@end deffn

@geindex entitydefs() (在 html.entities 模块中)
@anchor{library/html entities html entities entitydefs}@anchor{2b14}
@deffn {数据} html.entities.entitydefs

将 XHTML 1.0 实体定义映射到 ISO Latin-1 中的替换文本的字典。
@end deffn

@geindex name2codepoint() (在 html.entities 模块中)
@anchor{library/html entities html entities name2codepoint}@anchor{2b12}
@deffn {数据} html.entities.name2codepoint

将 HTML 实体名称映射到 Unicode 代码点的字典。
@end deffn

@geindex codepoint2name() (在 html.entities 模块中)
@anchor{library/html entities html entities codepoint2name}@anchor{2b13}
@deffn {数据} html.entities.codepoint2name

将 Unicode 代码点映射到 HTML 实体名称的字典。
@end deffn

@node XML处理模块,xml etree ElementTree --- ElementTree XML API,html entities --- HTML 一般实体的定义,结构化标记处理工具
@anchor{library/xml doc}@anchor{2b15}@anchor{library/xml module-xml}@anchor{13c}@anchor{library/xml xml}@anchor{2b16}@anchor{library/xml xml-processing-modules}@anchor{2b17}
@subsection XML处理模块


@geindex xml (模块)

@strong{源码：} Lib/xml/@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/}


__________________________________________________________________


用于处理XML的Python接口分组在 @code{xml} 包中。

@cartouche
@quotation 警告 
XML 模块对于错误或恶意构造的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞} 和 @ref{2b19,,defusedxml 包} 部分。
@end quotation
@end cartouche

值得注意的是 @ref{13c,,xml} 包中的模块要求至少有一个 SAX 兼容的 XML 解析器可用。Expat 解析器包含在 Python 中，因此 @ref{141,,xml.parsers.expat} 模块将始终可用。

@ref{13d,,xml.dom} 和 @ref{144,,xml.sax} 包的文档是 DOM 和 SAX 接口的 Python 绑定的定义。

XML 处理子模块包括:


@itemize *

@item 
@ref{140,,xml.etree.ElementTree}： ElementTree API，一个简单而轻量级的XML处理器
@end itemize



@itemize *

@item 
@ref{13d,,xml.dom}：DOM API 定义

@item 
@ref{13e,,xml.dom.minidom}：最小的 DOM 实现

@item 
@ref{13f,,xml.dom.pulldom}：支持构建部分 DOM 树
@end itemize



@itemize *

@item 
@ref{144,,xml.sax}：SAX2 基类和便利函数

@item 
@ref{141,,xml.parsers.expat}：Expat解析器绑定
@end itemize

@menu
* XML 漏洞:: 
* defusedxml 包:: 

@end menu

@node XML 漏洞,defusedxml 包,,XML处理模块
@anchor{library/xml id1}@anchor{2b1a}@anchor{library/xml xml-vulnerabilities}@anchor{2b18}
@subsubsection XML 漏洞


XML 处理模块对于恶意构造的数据是不安全的。 攻击者可能滥用 XML 功能来执行拒绝服务攻击、访问本地文件、生成与其它计算机的网络连接或绕过防火墙。

下表概述了已知的攻击以及各种模块是否容易受到攻击。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

种类

@tab

sax

@tab

etree

@tab

minidom

@tab

pulldom

@tab

xmlrpc

@item

billion laughs

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@item

quadratic blowup

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@tab

@strong{易受攻击} (1)

@item

external entity expansion

@tab

安全 (5)

@tab

安全 (2)

@tab

安全 (3)

@tab

安全 (5)

@tab

安全 (4)

@item

DTD@footnote{https://en.wikipedia.org/wiki/Document_type_definition} retrieval

@tab

安全 (5)

@tab

安全

@tab

安全

@tab

安全 (5)

@tab

安全

@item

decompression bomb

@tab

安全

@tab

安全

@tab

安全

@tab

安全

@tab

@strong{易受攻击}

@end multitable



@enumerate 

@item 
Expat 2.4.1 及更新的版本不易受 "billion laughs" 和 "quadratic blowup" 漏洞的攻击。 因为可能要依赖系统提供的库而仍被列为易受攻击的项目。 请检查 @code{pyexpat.EXPAT_VERSION}。

@item 
@ref{140,,xml.etree.ElementTree} 不会扩展外部实体并在实体发生时引发 @code{ParserError}。

@item 
@ref{13e,,xml.dom.minidom} 不会扩展外部实体，只是简单地返回未扩展的实体。

@item 
@code{xmlrpclib} 不扩展外部实体并省略它们。

@item 
从 Python 3.7.1 开始，默认情况下不再处理外部通用实体。
@end enumerate


@table @asis

@item billion laughs / exponential entity expansion （狂笑/递归实体扩展）

Billion Laughs@footnote{https://en.wikipedia.org/wiki/Billion_laughs} 攻击 -- 也称为递归实体扩展 -- 使用多级嵌套实体。 每个实体多次引用另一个实体，最终实体定义包含一个小字符串。 指数级扩展导致几千 GB 的文本，并消耗大量内存和 CPU 时间。

@item quadratic blowup entity expansion（二次爆炸实体扩展）

二次爆炸攻击类似于 Billion Laughs@footnote{https://en.wikipedia.org/wiki/Billion_laughs} 攻击，它也滥用实体扩展。 它不是嵌套实体，而是一遍又一遍地重复一个具有几千个字符的大型实体。攻击不如递归情况有效，但它避免触发禁止深度嵌套实体的解析器对策。

@item external entity expansion

实体声明可以包含的不仅仅是替换文本。 它们还可以指向外部资源或本地文件。 XML 解析器访问资源并将内容嵌入到 XML 文档中。

@item DTD@footnote{https://en.wikipedia.org/wiki/Document_type_definition} retrieval

Python 的一些 XML 库 @ref{13f,,xml.dom.pulldom} 从远程或本地位置检索文档类型定义。 该功能与外部实体扩展问题具有相似的含义。

@item decompression bomb

Decompression bombs（解压炸弹，又名 ZIP bomb@footnote{https://en.wikipedia.org/wiki/Zip_bomb}）适用于所有可以解析压缩 XML 流（例如 gzip 压缩的 HTTP 流或 LZMA 压缩的文件）的 XML 库。 对于攻击者来说，它可以将传输的数据量减少三个量级或更多。
@end table

PyPI上 defusedxml@footnote{https://pypi.org/project/defusedxml/} 的文档包含有关所有已知攻击向量的更多信息以及示例和参考。

@node defusedxml 包,,XML 漏洞,XML处理模块
@anchor{library/xml defusedxml-package}@anchor{2b19}@anchor{library/xml the-defusedxml-package}@anchor{2b1b}
@subsubsection @code{defusedxml} 包


defusedxml@footnote{https://pypi.org/project/defusedxml/} 是一个纯 Python 软件包，它修改了所有标准库 XML 解析器的子类，可以防止任何潜在的恶意操作。 对于解析不受信任的XML数据的任何服务器代码，建议使用此程序包。 该软件包还提供了有关更多 XML 漏洞（如 XPath 注入）的示例漏洞和扩展文档。

@node xml etree ElementTree --- ElementTree XML API,xml dom --- 文档对象模型 API,XML处理模块,结构化标记处理工具
@anchor{library/xml etree elementtree doc}@anchor{2b1c}@anchor{library/xml etree elementtree dtd}@anchor{2b1d}@anchor{library/xml etree elementtree module-xml etree ElementTree}@anchor{140}@anchor{library/xml etree elementtree xml-etree-elementtree-the-elementtree-xml-api}@anchor{2b1e}
@subsection @code{xml.etree.ElementTree} ---  ElementTree XML API


@geindex xml.etree.ElementTree (模块)

@strong{源代码：} Lib/xml/etree/ElementTree.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/etree/ElementTree.py}


__________________________________________________________________


@ref{140,,xml.etree.ElementTree} 模块实现了一个简单高效的API，用于解析和创建XML数据。


在 3.3 版更改: 此模块将在可能的情况下使用快速实现。



3.3 版后已移除: @code{xml.etree.cElementTree} 模块已被弃用。


@cartouche
@quotation 警告 
@ref{140,,xml.etree.ElementTree} 模块对于恶意构建的数据是不安全的。如果需要解析不可信或未经身份验证的数据，请参见 @ref{2b18,,XML 漏洞} 。
@end quotation
@end cartouche

@menu
* 教程:: 
* XPath支持:: 
* 参考引用:: 
* XInclude 支持:: 
* 参考引用: 参考引用<2>. 

@end menu

@node 教程,XPath支持,,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree tutorial}@anchor{2b1f}
@subsubsection 教程


这是一个使用 @ref{140,,xml.etree.ElementTree} （简称 @code{ET} ）的简短教程。目标是演示模块的一些构建块和基本概念。

@menu
* XML 树和元素:: 
* 解析 XML:: 
* 用于非阻塞解析的拉取 API:: 
* 查找感兴趣的元素:: 
* 修改XML文件:: 
* 构建 XML 文档:: 
* 解析带有命名空间的 XML:: 

@end menu

@node XML 树和元素,解析 XML,,教程
@anchor{library/xml etree elementtree xml-tree-and-elements}@anchor{2b20}
@subsubsection XML 树和元素


XML 是一种继承性的分层数据格式，最自然的表示方法是使用树。 为此， @code{ET} 有两个类 -- @ref{21d,,ElementTree} 将整个XML文档表示为一个树， @ref{21e,,Element} 表示该树中的单个节点。 与整个文档的交互（读写文件）通常在 @ref{21d,,ElementTree} 级别完成。 与单个 XML 元素及其子元素的交互是在 @ref{21e,,Element} 级别完成的。

@node 解析 XML,用于非阻塞解析的拉取 API,XML 树和元素,教程
@anchor{library/xml etree elementtree elementtree-parsing-xml}@anchor{2b21}@anchor{library/xml etree elementtree parsing-xml}@anchor{2b22}
@subsubsection 解析 XML


我们将使用以下 XML 文档作为本节的示例数据：

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
@end example

可以通过从文件中读取来导入此数据：

@example
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
@end example

或直接从字符串中解析：

@example
root = ET.fromstring(country_data_as_string)
@end example

@ref{2b23,,fromstring()} 将 XML 从字符串直接解析为 @ref{21e,,Element} ，该元素是已解析树的根元素。 其他解析函数可能会创建一个 @ref{21d,,ElementTree} 。 确切信息请查阅文档。

作为 @ref{21e,,Element} ， @code{root} 具有标签和属性字典:

@example
>>> root.tag
'data'
>>> root.attrib
@{@}
@end example

还有可以迭代的子节点：

@example
>>> for child in root:
...     print(child.tag, child.attrib)
...
country @{'name': 'Liechtenstein'@}
country @{'name': 'Singapore'@}
country @{'name': 'Panama'@}
@end example

子级是可以嵌套的，我们可以通过索引访问特定的子级节点：

@example
>>> root[0][1].text
'2008'
@end example

@cartouche
@quotation 注解 
并非 XML 输入的所有元素都将作为解析树的元素结束。 目前，此模块跳过输入中的任何 XML 注释、处理指令和文档类型声明。 然而，使用这个模块的 API 而不是从 XML 文本解析构建的树可以包含注释和处理指令，生成 XML 输出时同样包含这些注释和处理指令。 可以通过将自定义 @ref{384,,TreeBuilder} 实例传递给 @ref{383,,XMLParser} 构造器来访问文档类型声明。
@end quotation
@end cartouche

@node 用于非阻塞解析的拉取 API,查找感兴趣的元素,解析 XML,教程
@anchor{library/xml etree elementtree elementtree-pull-parsing}@anchor{a03}@anchor{library/xml etree elementtree pull-api-for-non-blocking-parsing}@anchor{2b24}
@subsubsection 用于非阻塞解析的拉取 API


此模块所提供了大多数解析函数都要求在返回任何结果之前一次性读取整个文档。 可以使用 @ref{383,,XMLParser} 并以增量方式添加数据，但这是在回调目标上调用方法的推送式 API。 有时用户真正想要的是能够以增量方式解析 XML 而无需阻塞操作，同时享受完整的已构造 @ref{21e,,Element} 对象。

针对此需求的最强大工具是 @ref{a02,,XMLPullParser}。 它不要求通过阻塞式读取来获得 XML 数据，而是通过执行 @ref{2b25,,XMLPullParser.feed()} 调用来增量式地添加数据。  要获得已解析的 XML 元素，应调用 @ref{2b26,,XMLPullParser.read_events()}。 下面是一个示例:

@example
>>> parser = ET.XMLPullParser(['start', 'end'])
>>> parser.feed('<mytag>sometext')
>>> list(parser.read_events())
[('start', <Element 'mytag' at 0x7fa66db2be58>)]
>>> parser.feed(' more text</mytag>')
>>> for event, elem in parser.read_events():
...     print(event)
...     print(elem.tag, 'text=', elem.text)
...
end
@end example

常见的用例是针对以非阻塞方式进行的应用程序，其中 XML 是从套接字接收或从某些存储设备增量式读取的。 在这些用例中，阻塞式读取是不可接受的。

因为其非常灵活，@ref{a02,,XMLPullParser} 在更简单的用例中使用起来可能并不方便。 如果你不介意你的应用程序在读取 XML 数据时造成阻塞但仍希望具有增量解析能力，可以考虑 @ref{a32,,iterparse()}。 它在你读取大型 XML 文档并且不希望将它完全放去内存时会很适用。

@node 查找感兴趣的元素,修改XML文件,用于非阻塞解析的拉取 API,教程
@anchor{library/xml etree elementtree finding-interesting-elements}@anchor{2b27}
@subsubsection 查找感兴趣的元素


@ref{21e,,Element} 有一些很有效的方法，可帮助递归遍历其下的所有子树（包括子级，子级的子级，等等）。例如 @ref{db7,,Element.iter()}:

@example
>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
@{'name': 'Austria', 'direction': 'E'@}
@{'name': 'Switzerland', 'direction': 'W'@}
@{'name': 'Malaysia', 'direction': 'N'@}
@{'name': 'Costa Rica', 'direction': 'W'@}
@{'name': 'Colombia', 'direction': 'E'@}
@end example

@ref{2b28,,Element.findall()} 仅查找当前元素的直接子元素中带有指定标签的元素。 @ref{2b29,,Element.find()} 找带有特定标签的 @emph{第一个} 子级，然后可以用 @ref{2b2a,,Element.text} 访问元素的文本内容。 @ref{2b2b,,Element.get} 访问元素的属性:

@example
>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68
@end example

通过使用 @ref{526,,XPath} ，可以更精确地指定要查找的元素。

@node 修改XML文件,构建 XML 文档,查找感兴趣的元素,教程
@anchor{library/xml etree elementtree modifying-an-xml-file}@anchor{2b2c}
@subsubsection 修改XML文件


@ref{21d,,ElementTree} 提供了一种构建XML文档并将其写入文件的简单方法。调用 @ref{a06,,ElementTree.write()} 方法就可以实现。

创建后可以直接操作 @ref{21e,,Element} 对象。例如：使用 @ref{2b2a,,Element.text} 修改文本字段，使用 @ref{2b2d,,Element.set()} 方法添加和修改属性，以及使用  @ref{2b2e,,Element.append()} 添加新的子元素。

假设我们要为每个国家/地区的中添加一个排名，并在排名元素中添加一个 @code{updated} 属性：

@example
>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')
@end example

生成的XML现在看起来像这样：

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
@end example

可以使用 @ref{2b2f,,Element.remove()} 删除元素。假设我们要删除排名高于50的所有国家/地区:

@example
>>> for country in root.findall('country'):
...     # using root.findall() to avoid removal during traversal
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')
@end example

请注意在迭代时进行并发修改可能会导致问题，就像在迭代并修改 Python 列表或字典时那样。 因此，这个示例先通过 @code{root.findall()} 收集了所有匹配的元素，在此之后再对匹配项列表进行迭代。

生成的XML现在看起来像这样：

@example
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>
@end example

@node 构建 XML 文档,解析带有命名空间的 XML,修改XML文件,教程
@anchor{library/xml etree elementtree building-xml-documents}@anchor{2b30}
@subsubsection 构建 XML 文档


@ref{2b31,,SubElement()} 函数还提供了一种便捷方法来为给定元素创建新的子元素:

@example
>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>
@end example

@node 解析带有命名空间的 XML,,构建 XML 文档,教程
@anchor{library/xml etree elementtree parsing-xml-with-namespaces}@anchor{2b32}
@subsubsection 解析带有命名空间的 XML


如果 XML 输入带有 命名空间@footnote{https://en.wikipedia.org/wiki/XML_namespace}，则具有前缀的 @code{prefix:sometag} 形式的标记和属性将被扩展为 @code{@{uri@}sometag}，其中 @emph{prefix} 会被完整 @emph{URI} 所替换。 并且，如果存在 默认命名空间@footnote{https://www.w3.org/TR/xml-names/#defaulting}，则完整 URI 会被添加到所有未加前缀的标记之前。

下面的 XML 示例包含两个命名空间，一个具有前缀 "fictional" 而另一个则作为默认命名空间:

@example
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>
@end example

搜索和探查这个 XML 示例的一种方式是手动为 @ref{2b29,,find()} 或 @ref{2b28,,findall()} 的 xpath 中的每个标记或属性添加 URI:

@example
root = fromstring(xml_text)
for actor in root.findall('@{http://people.example.com@}actor'):
    name = actor.find('@{http://people.example.com@}name')
    print(name.text)
    for char in actor.findall('@{http://characters.example.com@}character'):
        print(' |-->', char.text)
@end example

一种更好的方式是搜索带命名空间的 XML 示例创建一个字典来存放你自己的前缀并在搜索函数中使用它们:

@example
ns = @{'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'@}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)
@end example

这两种方式都会输出:

@example
John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement
@end example

@node XPath支持,参考引用,教程,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree elementtree-xpath}@anchor{526}@anchor{library/xml etree elementtree xpath-support}@anchor{2b33}
@subsubsection XPath支持


此模块提供了对 XPath 表达式@footnote{https://www.w3.org/TR/xpath} 的有限支持用于在树中定位元素。 其目标是支持一个简化语法的较小子集；完整的 XPath 引擎超出了此模块的适用范围。

@menu
* 示例: 示例<29>. 
* 支持的XPath语法:: 

@end menu

@node 示例<29>,支持的XPath语法,,XPath支持
@anchor{library/xml etree elementtree example}@anchor{2b34}
@subsubsection 示例


下面是一个演示此模块的部分 XPath 功能的例子。 我们将使用来自 @ref{2b21,,解析 XML} 小节的 @code{countrydata} XML 文档:

@example
import xml.etree.ElementTree as ET

root = ET.fromstring(countrydata)

# Top-level elements
root.findall(".")

# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@@name='Singapore']")

# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@@name='Singapore']/year")

# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")
@end example

对于带有命名空间的 XML，应使用通常的限定 @code{@{namespace@}tag} 标记法:

@example
# All dublin-core "title" tags in the document
root.findall(".//@{http://purl.org/dc/elements/1.1/@}title")
@end example

@node 支持的XPath语法,,示例<29>,XPath支持
@anchor{library/xml etree elementtree supported-xpath-syntax}@anchor{2b35}
@subsubsection 支持的XPath语法



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

语法

@tab

含义

@item

@code{tag}

@tab

选择具有给定标记的所有子元素。 例如，@code{spam} 是选择名为 @code{spam} 的所有子元素，而 @code{spam/egg} 是在名为 @code{spam} 的子元素中选择所有名为 @code{egg} 的孙元素，@code{@{*@}spam} 是在任意（或无）命名空间中选择名为 @code{spam} 的标记，而 @code{@{@}*} 是只选择不在一个命名空间中的标记。


在 3.8 版更改: 增加了对星号通配符的支持。


@item

@code{*}

@tab

选择所有子元素，包括注释和处理说明。例如 @code{*/egg} 选择所有名为 @code{egg} 的孙元素。

@item

@code{.}

@tab

选择当前节点。这在路径的开头非常有用，用于指示它是相对路径。

@item

@code{//}

@tab

选择所有子元素 在当前元素的所有下级中选择所有下级元素。 例如，@code{.//egg} 是在整个树中选择所有 @code{egg} 元素。

@item

@code{..}

@tab

选择父元素。 如果路径试图前往起始元素的上级（元素的 @code{find} 被调用）则返回 @code{None}。

@item

@code{[@@attrib]}

@tab

选择具有给定属性的所有元素。

@item

@code{[@@attrib='value']}

@tab

选择给定属性具有给定值的所有元素。该值不能包含引号。

@item

@code{[tag]}

@tab

选择所有包含 @code{tag} 子元素的元素。只支持直系子元素。

@item

@code{[.='text']}

@tab

选择完整文本内容等于 @code{text} 的所有元素（包括后代）。


3.7 新版功能.


@item

@code{[tag='text']}

@tab

选择所有包含名为 @code{tag} 的子元素的元素，这些子元素（包括后代）的完整文本内容等于给定的 @code{text} 。

@item

@code{[position]}

@tab

选择位于给定位置的所有元素。 位置可以是一个整数 (1 表示首位)，表达式 @code{last()} (表示末位)，或者相对于末位的位置 (例如 @code{last()-1})。

@end multitable


谓词（方括号内的表达式）之前必须带有标签名称，星号或其他谓词。@code{position} 谓词前必须有标签名称。

@node 参考引用,XInclude 支持,XPath支持,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree reference}@anchor{2b36}
@subsubsection 参考引用


@menu
* 函数: 函数<7>. 

@end menu

@node 函数<7>,,,参考引用
@anchor{library/xml etree elementtree elementtree-functions}@anchor{2b37}@anchor{library/xml etree elementtree functions}@anchor{2b38}
@subsubsection 函数


@geindex canonicalize() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree canonicalize}@anchor{2b39}
@deffn {函数} xml.etree.ElementTree.canonicalize (xml_data=None, *, out=None, from_file=None, **options)

C14N 2.0@footnote{https://www.w3.org/TR/xml-c14n2/}  转换功能。.

规整化是标准化 XML 输出的一种方式，该方式允许按字节比较和数字签名。 它降低了 XML 序列化器所具有的自由度并改为生成更受约束的 XML 表示形式。 主要限制涉及命名空间声明的位置、属性的顺序和可忽略的空白符等。

此函数接受一个 XML 数字字符串 (@emph{xml_data}) 或文件路径或者文件类对象 (@emph{from_file}) 作为输入，将其转换为规整形式，并在提供了 @emph{out} 文件（类）对象的情况下将其写到该对象的话，或者如果未提供则将其作为文本字符串返回。 输出文件接受文本而非字节数据。  因此它应当以使用 @code{utf-8} 编码格式的文本模式来打开。

典型使用:

@example
xml_data = "<root>...</root>"
print(canonicalize(xml_data))

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(xml_data, out=out_file)

with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
    canonicalize(from_file="inputfile.xml", out=out_file)
@end example

配置选项 @emph{options} 如下:


@itemize -

@item 
@emph{with_comments}: 设为真值以包括注释 (默认为假值)

@item 

@table @asis

@item @emph{strip_text}: 设为真值以去除文本内容前后的空白符

（默认值：否）
@end table

@item 

@table @asis

@item @emph{rewrite_prefixes}: 设为真值以替换带有 "n@{number@}" 前缀的命名空间

（默认值：否）
@end table

@item 

@table @asis

@item @emph{qname_aware_tags}: 一组可感知限定名称的标记名称，其中的前缀

应当在文本内容中被替换 (默认为空值)
@end table

@item 

@table @asis

@item @emph{qname_aware_attrs}: 一组可感知限定名称的属性名称，其中的前缀

应当在文本内容中被替换 (默认为空值)
@end table

@item 
@emph{exclude_attrs}: 一组不应当被序列化的属性名称

@item 
@emph{exclude_tags}: 一组不应当被序列化的标记名称
@end itemize

在上面的选项列表中，"一组" 是指任意多项集或包含字符串的可迭代对象，排序是不必要的。


3.8 新版功能.

@end deffn

@geindex Comment() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree Comment}@anchor{2b3a}
@deffn {函数} xml.etree.ElementTree.Comment (text=None)

注释元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被标准序列化器当作 XML 注释来进行序列化。 注释字串可以是字节串或是 Unicode 字符串。 @emph{text} 是包含注释字串的字符串。 返回一个表示注释的元素实例。

请注意 @ref{383,,XMLParser} 会跳过输入中的注释而不会为其创建注释对象。 @ref{21d,,ElementTree} 将只在当使用某个 @ref{21e,,Element} 方法向树插入了注释节点时才会包含注释节点。
@end deffn

@geindex dump() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree dump}@anchor{2b3b}
@deffn {函数} xml.etree.ElementTree.dump (elem)

将一个元素树或元素结构体写入到 sys.stdout。 此函数应当只被用于调试。

实际输出格式是依赖于具体实现的。 在这个版本中，它将以普通 XML 文件的格式写入。

@emph{elem} 是一个元素树或单独元素。


在 3.8 版更改: @ref{2b3b,,dump()} 函数现在会保留用户指定的属性顺序。

@end deffn

@geindex fromstring() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree fromstring}@anchor{2b23}
@deffn {函数} xml.etree.ElementTree.fromstring (text, parser=None)

根据一个字符串常量解析 XML 的节。 与 @ref{2b3c,,XML()} 类似。 @emph{text} 是包含 XML 数据的字符串。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准 @ref{383,,XMLParser} 解析器。 返回一个 @ref{21e,,Element} 实例。
@end deffn

@geindex fromstringlist() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree fromstringlist}@anchor{c2a}
@deffn {函数} xml.etree.ElementTree.fromstringlist (sequence, parser=None)

根据一个字符串片段序列解析 XML 文档。 @emph{sequence} 是包含 XML 数据片段的列表或其他序列对象。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 返回一个 @ref{21e,,Element} 实例。


3.2 新版功能.

@end deffn

@geindex indent() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree indent}@anchor{2b3d}
@deffn {函数} xml.etree.ElementTree.indent (tree, space="  ", level=0)

添加空格到子树来实现树的缩进效果。 这可以被用来生成美化打印的 XML 输出。 @emph{tree} 可以为 Element 或 ElementTree。 @emph{space} 是对应将被插入的每个缩进层级的空格字符串，默认为两个空格符。 要对已缩进的树的部分子树进行缩进，请传入初始缩进层级作为 @emph{level}。


3.9 新版功能.

@end deffn

@geindex iselement() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree iselement}@anchor{2b3e}
@deffn {函数} xml.etree.ElementTree.iselement (element)

检测一个对象是否为有效的元素对象。 @emph{element} 是一个元素实例。 如果对象是一个元素对象则返回 @code{True}。
@end deffn

@geindex iterparse() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree iterparse}@anchor{a32}
@deffn {函数} xml.etree.ElementTree.iterparse (source, events=None, parser=None)

以增量方式将一个 XML 节解析为元素树，并向用户报告执行情况。 @emph{source} 是包含 XML 数据的文件名或 @ref{c1d,,file object}。 @emph{events} 是要报告的事件序列。 所支持的事件字符串有 @code{"start"}, @code{"end"}, @code{"comment"}, @code{"pi"}, @code{"start-ns"} 和 @code{"end-ns"} ("ns" 事件用于获取详细的命名空间信息)。 如果 @emph{events} 被省略，则只有 @code{"end"} 事件会被报告。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 @emph{parser} 必须为 @ref{383,,XMLParser} 的子类并且只能使用默认的 @ref{384,,TreeBuilder} 作为目标。 返回一个提供 @code{(event, elem)} 对的 @ref{11ba,,iterator}。

请注意虽然 @ref{a32,,iterparse()} 是以增量方式构建树，但它会对 @emph{source} (或其所指定的文件) 发出阻塞式读取。 因此，它不适用于不可执行阻塞式读取的应用。 对于完全非阻塞式的解析，请参看 @ref{a02,,XMLPullParser}。

@cartouche
@quotation 注解 
@ref{a32,,iterparse()} 只会确保当发出 "start" 事件时看到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本容和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存在也可能不存在。

如果你需要已完全填充的元素，请改为查找 "end" 事件。
@end quotation
@end cartouche


3.4 版后已移除: @emph{parser} 参数。



在 3.8 版更改: 增加了 @code{comment} 和 @code{pi} 事件。

@end deffn

@geindex parse() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree parse}@anchor{2b3f}
@deffn {函数} xml.etree.ElementTree.parse (source, parser=None)

将一个 XML 的节解析为元素树。 @emph{source} 是包含 XML 数据的文件名或文件对象。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 返回一个 @ref{21d,,ElementTree} 实例。
@end deffn

@geindex ProcessingInstruction() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree ProcessingInstruction}@anchor{2b40}
@deffn {函数} xml.etree.ElementTree.ProcessingInstruction (target, text=None)

PI 元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被当作 XML 处理指令来进行序列化。 @emph{target} 是包含 PI 目标的字符串。 @emph{text} 如果给出则是包含 PI 内容的字符串。 返回一个表示处理指令的元素实例。

请注意 @ref{383,,XMLParser} 会跳过输入中的处理指令而不会为其创建注释对象。 @ref{21d,,ElementTree} 将只在当使用某个 @ref{21e,,Element} 方法向树插入了处理指令节点时才会包含处理指令节点。
@end deffn

@geindex register_namespace() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree register_namespace}@anchor{c2b}
@deffn {函数} xml.etree.ElementTree.register_namespace (prefix, uri)

注册一个命名空间前缀。 这个注册表是全局的，并且任何对应给定前缀或命名空间 URI 的现有映射都会被移除。 @emph{prefix} 是命名空间前缀。 @emph{uri} 是命名空间 URI。 如果可能的话，这个命名空间中的标记和属性将附带给定的前缀来进行序列化。


3.2 新版功能.

@end deffn

@geindex SubElement() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree SubElement}@anchor{2b31}
@deffn {函数} xml.etree.ElementTree.SubElement (parent, tag, attrib=@{@}, **extra)

子元素工厂函数。 这个函数会创建一个元素实例，并将其添加到现有的元素。

元素名、属性名和属性值可以是字节串或 Unicode 字符串。 @emph{parent} 是父元素。 @emph{tag} 是子元素名。 @emph{attrib} 是一个可选的字典，其中包含元素属性。  @emph{extra} 包含额外的属性，以关键字参数形式给出。 返回一个元素实例。
@end deffn

@geindex tostring() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree tostring}@anchor{a04}
@deffn {函数} xml.etree.ElementTree.tostring (element, encoding="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

生成一个 XML 元素的字符串表示形式，包括所有子元素。 @emph{element} 是一个 @ref{21e,,Element} 实例。 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如 "UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} 是输出编码格式（默认为 US-ASCII）。 请使用 @code{encoding="unicode"} 来生成 Unicode 字符串（否则生成字节串）。 @emph{method} 是 @code{"xml"}, @code{"html"} 或 @code{"text"} (默认为 @code{"xml"})。 @emph{xml_declaration}, @emph{default_namespace} 和 @emph{short_empty_elements} 具有与 @ref{a06,,ElementTree.write()} 中一致的含义。 返回一个包含 XML 数据（可选）已编码的字符串。


3.4 新版功能: @emph{short_empty_elements} 形参。



3.8 新版功能: @emph{xml_declaration} 和 @emph{default_namespace} 形参。



在 3.8 版更改: @ref{a04,,tostring()} 函数现在会保留用户指定的属性顺序。

@end deffn

@geindex tostringlist() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree tostringlist}@anchor{a05}
@deffn {函数} xml.etree.ElementTree.tostringlist (element, encoding="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True)

生成一个 XML 元素的字符串表示形式，包括所有子元素。 @emph{element} 是一个 @ref{21e,,Element} 实例。 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如 "UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} 是输出编码格式（默认为 US-ASCII）。 请使用 @code{encoding="unicode"} 来生成 Unicode 字符串（否则生成字节串）。 @emph{method} 是 @code{"xml"}, @code{"html"} 或 @code{"text"} (默认为 @code{"xml"})。 @emph{xml_declaration}, @emph{default_namespace} 和 @emph{short_empty_elements} 具有与 @ref{a06,,ElementTree.write()} 中一致的含义。 返回一个包含 XML 数据（可选）已编码字符串的列表。 它并不保证任何特定的序列，除了 @code{b"".join(tostringlist(element)) == tostring(element)}。


3.2 新版功能.



3.4 新版功能: @emph{short_empty_elements} 形参。



3.8 新版功能: @emph{xml_declaration} 和 @emph{default_namespace} 形参。



在 3.8 版更改: @ref{a05,,tostringlist()} 函数现在会保留用户指定的属性顺序。

@end deffn

@geindex XML() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree XML}@anchor{2b3c}
@deffn {函数} xml.etree.ElementTree.XML (text, parser=None)

根据一个字符串常量解析 XML 的节。 此函数可被用于在 Python 代码中嵌入“XML 字面值”。 @emph{text} 是包含 XML 数据的字符串。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 返回一个 @ref{21e,,Element} 实例。
@end deffn

@geindex XMLID() (在 xml.etree.ElementTree 模块中)
@anchor{library/xml etree elementtree xml etree ElementTree XMLID}@anchor{2b41}
@deffn {函数} xml.etree.ElementTree.XMLID (text, parser=None)

根据一个字符串常量解析 XML 的节，并且还将返回一个将元素的 id:s 映射到元素的字典。 @emph{text} 是包含 XML 数据的字符串。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 返回一个包含 @ref{21e,,Element} 实例和字典的元组。
@end deffn

@node XInclude 支持,参考引用<2>,参考引用,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree elementtree-xinclude}@anchor{2b42}@anchor{library/xml etree elementtree xinclude-support}@anchor{2b43}
@subsubsection XInclude 支持


此模块通过 @code{xml.etree.ElementInclude} 辅助模块提供了对 XInclude 指令@footnote{https://www.w3.org/TR/xinclude/} 的有限支持，这个模块可被用来根据元素树的信息在其中插入子树和文本字符串。

@menu
* 示例: 示例<30>. 

@end menu

@node 示例<30>,,,XInclude 支持
@anchor{library/xml etree elementtree id3}@anchor{2b44}
@subsubsection 示例


以下是一个演示 XInclude 模块用法的例子。 要在当前文本中包括一个 XML 文档，请使用 @code{@{http://www.w3.org/2001/XInclude@}include} 元素并将 @strong{parse} 属性设为 @code{"xml"}，并使用 @strong{href} 属性来指定要包括的文档。

@example
<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="source.xml" parse="xml" />
</document>
@end example

默认情况下，@strong{href} 属性会被当作文件名来处理。 你可以使用自定义加载器来重载此行为。 还要注意标准辅助器不支持 XPointer 语法。

要处理这个文件，请正常加载它，并将根元素传给 @ref{140,,xml.etree.ElementTree} 模块:

@example
from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()

ElementInclude.include(root)
@end example

ElementInclude 模块使用来自 @strong{source.xml} 文档的根元素替代 @code{@{http://www.w3.org/2001/XInclude@}include} 元素。 结果看起来大概是这样:

@example
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <para>This is a paragraph.</para>
</document>
@end example

如果省略了 @strong{parse} 属性，它会取默认的 "xml"。 要求有 href 属性。

要包括文本文档，请使用 @code{@{http://www.w3.org/2001/XInclude@}include} 元素，并将 @strong{parse} 属性设为 "text":

@example
<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) <xi:include href="year.txt" parse="text" />.
</document>
@end example

结果可能如下所示：

@example
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) 2003.
</document>
@end example

@node 参考引用<2>,,XInclude 支持,xml etree ElementTree --- ElementTree XML API
@anchor{library/xml etree elementtree id4}@anchor{2b45}
@subsubsection 参考引用


@menu
* 函数: 函数<8>. 
* 元素对象:: 
* ElementTree 对象:: 
* QName 对象:: 
* TreeBuilder 对象:: 
* XMLParser对象:: 
* XMLPullParser对象:: 
* 异常: 异常<15>. 

@end menu

@node 函数<8>,元素对象,,参考引用<2>
@anchor{library/xml etree elementtree elementinclude-functions}@anchor{2b46}@anchor{library/xml etree elementtree id5}@anchor{2b47}
@subsubsection 函数


@geindex xml.etree.ElementInclude.default_loader() (內置函数)
@anchor{library/xml etree elementtree xml etree ElementInclude default_loader}@anchor{2b48}
@deffn {函数} xml.etree.ElementInclude.default_loader (href, parse, encoding=None)

默认的加载器。 这个默认的加载器会从磁盘读取所包括的资源。 @emph{href} 是一个 URL。 @emph{parse} 是 "xml" 或 "text" 表示解析模式。 @emph{encoding} 是可选的文本编码格式。 如果未给出，则编码格式为 @code{utf-8}。 返回已扩展的资源。 如果解析模式为 @code{"xml"}，则它是一个 ElementTree 实例。 如果解析模式为 "text"，则它是一个 Unicode 字符串。 如果加载器失败，它可以返回 None 或者引发异常。
@end deffn

@geindex xml.etree.ElementInclude.include() (內置函数)
@anchor{library/xml etree elementtree xml etree ElementInclude include}@anchor{2b49}
@deffn {函数} xml.etree.ElementInclude.include (elem, loader=None, base_url=None, max_depth=6)

这个函数会扩展 XInclude 指令。 @emph{elem} 是根元素。 @emph{loader} 是可选的资源加载器。 如果省略，则它默认为 @ref{2b48,,default_loader()}。 如果给出，则它应当是一个实现了与 @ref{2b48,,default_loader()} 相同的接口的可调用对象。 @emph{base_url} 是原文件的基准 URL，用于求解相对的包括文件引用。 @emph{max_depth} 是递归包括的最大数量。  此限制是为了降低恶意内容爆破的风险。 传入一个负值可禁用此限制。

返回已扩展的资源。 如果解析模式为 @code{"xml"}，则它是一个 ElementTree 实例。 如果解析模式为 "text"，则它是一个 Unicode 字符串。 如果加载器失败，它可以返回 None 或者引发异常。


3.9 新版功能: @emph{base_url} 和 @emph{max_depth} 形参。

@end deffn

@node 元素对象,ElementTree 对象,函数<8>,参考引用<2>
@anchor{library/xml etree elementtree element-objects}@anchor{2b4a}@anchor{library/xml etree elementtree elementtree-element-objects}@anchor{2b4b}
@subsubsection 元素对象


@geindex Element (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree Element}@anchor{21e}
@deffn {类} xml.etree.ElementTree.Element (tag, attrib=@{@}, **extra)

元素类。 这个类定义了 Element 接口，并提供了这个接口的引用实现。

元素名、属性名和属性值可以是字节串或 Unicode 字符串。 @emph{tag} 是元素名。 @emph{attrib} 是一个可选的字典，其中包含元素属性。 @emph{extra} 包含额外的属性，以关键字参数形式给出。

@geindex tag (xml.etree.ElementTree.Element 属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element tag}@anchor{2b4c}
@deffn {属性} tag

一个标识此元素意味着何种数据的字符串(换句话说，元素类型)。
@end deffn

@geindex text (xml.etree.ElementTree.Element 属性)
@geindex tail (xml.etree.ElementTree.Element 属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element text}@anchor{2b2a}
@deffn {属性} text
@anchor{library/xml etree elementtree xml etree ElementTree Element tail}@anchor{2b4d}
@deffnx {属性} tail

这些属性可被用于存放与元素相关联的额外数据。 它们的值通常为字符串但也可以是任何应用专属的对象。 如果元素是基于 XML 文件创建的，@emph{text} 属性会存放元素的开始标记及其第一个子元素或结束标记之间的文本，或者为 @code{None}，而 @emph{tail} 属性会存放元素的结束标记及下一个标记之间的文本，或者为 @code{None}。 对于 XML 数据

@example
<a><b>1<c>2<d/>3</c></b>4</a>
@end example

@emph{a} 元素的 @emph{text} 和 @emph{tail} 属性均为 @code{None}，@emph{b} 元素的 @emph{text} 为 @code{"1"} 而 @emph{tail} 为 @code{"4"}，@emph{c} 元素的 @emph{text} 为 @code{"2"} 而 @emph{tail} 为 @code{None}，@emph{d} 元素的 @emph{text} 为 @code{None} 而 @emph{tail} 为 @code{"3"}。

要获取一个元素的内部文本，请参阅 @ref{c2e,,itertext()}，例如 @code{"".join(element.itertext())}。

应用程序可以将任意对象存入这些属性。
@end deffn

@geindex attrib (xml.etree.ElementTree.Element 属性)
@anchor{library/xml etree elementtree xml etree ElementTree Element attrib}@anchor{2b4e}
@deffn {属性} attrib

一个包含元素属性的字典。 请注意虽然 @emph{attrib} 值总是一个真正可变的 Python 字典，但 ElementTree 实现可以选择其他内部表示形式，并只在有需要时才创建字典。 为了发挥这种实现的优势，请在任何可能情况下使用下列字典方法。
@end deffn

以下字典类方法作用于元素属性。

@geindex clear() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element clear}@anchor{2b4f}
@deffn {方法} clear ()

重设一个元素。 此方法会移除所有子元素，清空所有属性，并将 text 和 tail 属性设为 @code{None}。
@end deffn

@geindex get() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element get}@anchor{2b2b}
@deffn {方法} get (key, default=None)

获取名为 @emph{key} 的元素属性。

返回属性的值，或者如果属性未找到则返回 @emph{default}。
@end deffn

@geindex items() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element items}@anchor{2b50}
@deffn {方法} items ()

将元素属性以 (name, value) 对序列的形式返回。 所返回属性的顺序任意。
@end deffn

@geindex keys() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element keys}@anchor{2b51}
@deffn {方法} keys ()

将元素属性名称以列表的形式返回。 所返回名称的顺序任意。
@end deffn

@geindex set() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element set}@anchor{2b2d}
@deffn {方法} set (key, value)

将元素的 @emph{key} 属性设为 @emph{value}。
@end deffn

以下方法作用于元素的下级（子元素）。

@geindex append() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element append}@anchor{2b2e}
@deffn {方法} append (subelement)

将元素 @emph{subelement} 添加到此元素的子元素内部列表。 如果 @emph{subelement} 不是一个 @ref{21e,,Element} 则会引发 @ref{1ff,,TypeError}。
@end deffn

@geindex extend() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element extend}@anchor{c2c}
@deffn {方法} extend (subelements)

使用具有零个或多个元素的序列对象添加 @emph{subelements}。 如果某个子元素不是 @ref{21e,,Element} 则会引发 @ref{1ff,,TypeError}。


3.2 新版功能.

@end deffn

@geindex find() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element find}@anchor{2b29}
@deffn {方法} find (match, namespaces=None)

查找第一个匹配 @emph{match} 的子元素。 @emph{match} 可以是一个标记名称或者 @ref{526,,路径}。 返回一个元素实例或 @code{None}。 @emph{namespaces} 是可选的从命名空间前缀到完整名称的映射。 传入 @code{'@w{'}} 作为前缀可将表达式中所有无前缀的标记名称移动到给定的命名空间。
@end deffn

@geindex findall() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element findall}@anchor{2b28}
@deffn {方法} findall (match, namespaces=None)

根据标记名称或者 @ref{526,,路径} 查找所有匹配的子元素。 返回一个包含所有匹配元素按文档顺序排序的列表。 @emph{namespaces} 是可选的从命名空间前缀到完整名称的映射。 传入 @code{'@w{'}} 作为前缀可将表达式中所有无前缀的标记名称移动到给定的命名空间。
@end deffn

@geindex findtext() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element findtext}@anchor{2b52}
@deffn {方法} findtext (match, default=None, namespaces=None)

查找第一个匹配 @emph{match} 的子元素的文本。 @emph{match} 可以是一个标记名称或者 @ref{526,,路径}。 反回第一个匹配的元素的文本内容，或者如果元素未找到则返回 @emph{default}。 请注意如果匹配的元素没有文本内容则会返回一个空字符串。 @emph{namespaces} 是可选的从命名空间前缀到完整名称的映射。 传入 @code{'@w{'}} 作为前缀可将表达式中所有无前缀的标记名称移动到给定的命名空间。
@end deffn

@geindex insert() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element insert}@anchor{2b53}
@deffn {方法} insert (index, subelement)

将 @emph{subelement} 插入到此元素的给定位置中。 如果 @emph{subelement} 不是一个 @ref{21e,,Element} 则会引发 @ref{1ff,,TypeError}。
@end deffn

@geindex iter() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element iter}@anchor{db7}
@deffn {方法} iter (tag=None)

创建一个以当前元素为根元素的树的 @ref{11ba,,iterator}。 该迭代器将以文档（深度优先）顺序迭代此元素及其所有下级元素。 如果 @emph{tag} 不为 @code{None} 或 @code{'*'}，则迭代器只返回标记为 @emph{tag} 的元素。 如果树结构在迭代期间被修改，则结果是未定义的。


3.2 新版功能.

@end deffn

@geindex iterfind() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element iterfind}@anchor{c2d}
@deffn {方法} iterfind (match, namespaces=None)

根据标记名称或者 @ref{526,,路径} 查找所有匹配的子元素。 返回一个按文档顺序产生所有匹配元素的可迭代对象。 @emph{namespaces} 是可选的从命名空间前缀到完整名称的映射。


3.2 新版功能.

@end deffn

@geindex itertext() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element itertext}@anchor{c2e}
@deffn {方法} itertext ()

创建一个文本迭代器。 该迭代器将按文档顺序遍历此元素及其所有子元素，并返回所有内部文本。


3.2 新版功能.

@end deffn

@geindex makeelement() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element makeelement}@anchor{2b54}
@deffn {方法} makeelement (tag, attrib)

创建一个与此元素类型相同的新元素对象。 请不要调用此方法，而应改用 @ref{2b31,,SubElement()} 工厂函数。
@end deffn

@geindex remove() (xml.etree.ElementTree.Element 方法)
@anchor{library/xml etree elementtree xml etree ElementTree Element remove}@anchor{2b2f}
@deffn {方法} remove (subelement)

从元素中移除 @emph{subelement}。 与 find* 方法不同的是此方法会基于实例的标识来比较元素，而不是基于标记的值或内容。
@end deffn

@ref{21e,,Element} 对象还支持下列序列类型方法以配合子元素使用: @ref{d33,,__delitem__()}, @ref{3ad,,__getitem__()}, @ref{d32,,__setitem__()}, @ref{e98,,__len__()}。

注意：不带子元素的元素将被检测为 @code{False}。 此行为将在未来的版本中发生变化。 请改用 @code{len(elem)} 或 @code{elem is None} 进行检测。

@example
element = root.find('foo')

if not element:  # careful!
    print("element not found, or element has no subelements")

if element is None:
    print("element not found")
@end example

在 Python 3.8 之前，元素的 XML 属性的序列化顺序会通过按其名称排序来强制使其可被预期。 由于现在字典已保证是有序的，这个强制重排序在 Python 3.8 中已被移除以保留原本由用户代码解析或创建的属性顺序。

通常，用户代码应当尽量不依赖于特定的属性顺序，因为 XML 信息设定@footnote{https://www.w3.org/TR/xml-infoset/} 明确地排除了用属性顺序转递信息的做法。 代码应当准备好处理任何输入顺序。 对于要求确定性的 XML 输出的情况，例如加密签名或检测数据集等，可以通过规范化 @ref{2b39,,canonicalize()} 函数来进行传统的序列化。

对于规范化输出不可用但仍然要求输出特定属性顺序的情况，代码应当设法直接按要求的顺序来创建属性，以避免代码阅读者产生不匹配的感觉。 如果这一点是难以做到的，可以在序列化之前应用以下写法来强制实现顺序不依赖于元素的创建:

@example
def reorder_attributes(root):
    for el in root.iter():
        attrib = el.attrib
        if len(attrib) > 1:
            # adjust attribute order, e.g. by sorting
            attribs = sorted(attrib.items())
            attrib.clear()
            attrib.update(attribs)
@end example
@end deffn

@node ElementTree 对象,QName 对象,元素对象,参考引用<2>
@anchor{library/xml etree elementtree elementtree-elementtree-objects}@anchor{2b55}@anchor{library/xml etree elementtree elementtree-objects}@anchor{2b56}
@subsubsection ElementTree 对象


@geindex ElementTree (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree}@anchor{21d}
@deffn {类} xml.etree.ElementTree.ElementTree (element=None, file=None)

ElementTree 包装器类。 这个类表示一个完整的元素层级结构，并添加了一些对于标准 XML 序列化的额外支持。

@emph{element} 是根元素。 如果给出 XML @emph{file} 则将使用其内容来初始化树结构。

@geindex _setroot() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree _setroot}@anchor{2b57}
@deffn {方法} _setroot (element)

替换该树结构的根元素。 这将丢弃该树结构的当前内容，并将其替换为给定的元素。 请小心使用。  @emph{element} 是一个元素实例。
@end deffn

@geindex find() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree find}@anchor{2b58}
@deffn {方法} find (match, namespaces=None)

与 @ref{2b29,,Element.find()} 类似，从树的根节点开始。
@end deffn

@geindex findall() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree findall}@anchor{2b59}
@deffn {方法} findall (match, namespaces=None)

与 @ref{2b28,,Element.findall()} 类似，从树的根节点开始。
@end deffn

@geindex findtext() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree findtext}@anchor{2b5a}
@deffn {方法} findtext (match, default=None, namespaces=None)

与 @ref{2b52,,Element.findtext()} 类似，从树的根节点开始。
@end deffn

@geindex getroot() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree getroot}@anchor{2b5b}
@deffn {方法} getroot ()

返回这个树的根元素。
@end deffn

@geindex iter() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree iter}@anchor{2b5c}
@deffn {方法} iter (tag=None)

创建并返回根元素的树结构迭代器。 该迭代器会以节顺序遍历这个树的所有元素。 @emph{tag} 是要查找的标记（默认返回所有元素）。
@end deffn

@geindex iterfind() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree iterfind}@anchor{2b5d}
@deffn {方法} iterfind (match, namespaces=None)

与 @ref{c2d,,Element.iterfind()} 类似，从树的根节点开始。


3.2 新版功能.

@end deffn

@geindex parse() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree parse}@anchor{2b5e}
@deffn {方法} parse (source, parser=None)

将一个外部 XML 节载入到此元素树。 @emph{source} 是一个文件名或 @ref{c1d,,file object}。 @emph{parser} 是可选的解析器实例。 如果未给出，则会使用标准的 @ref{383,,XMLParser} 解析器。 返回该节的根元素。
@end deffn

@geindex write() (xml.etree.ElementTree.ElementTree 方法)
@anchor{library/xml etree elementtree xml etree ElementTree ElementTree write}@anchor{a06}
@deffn {方法} write (file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml", *, short_empty_elements=True)

将元素树以 XML 格式写入到文件。 @emph{file} 为文件名，或是以写入模式打开的 @ref{c1d,,file object}。 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如 "UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} 为输出编码格式 (默认为 US-ASCII)。 @emph{xml_declaration} 控制是否要将 XML 声明添加到文件中。 使用 @code{False} 表示从不添加，@code{True} 表示总是添加，@code{None} 表示仅在非 US-ASCII 或 UTF-8 或 Unicode 时添加 (默认为 @code{None})。 @emph{default_namespace} 设置默认 XML 命名空间 (用于 "xmlns")。 @emph{method} 为 @code{"xml"}, @code{"html"} 或 @code{"text"} (默认为 @code{"xml"})。 仅限关键字形参 @emph{short_empty_elements} 控制不包含内容的元素的格式。 如为 @code{True} (默认值)，它们会被输出为单个自结束标记，否则它们会被输出为一对开始/结束标记。

输出是一个字符串 (@ref{206,,str}) 或字节串 (@ref{172,,bytes})。 由*encoding* 参数来控制。 如果 @emph{encoding} 为 @code{"unicode"}，则输出是一个字符串；否则为字节串；请注意这可能与 @emph{file} 的类型相冲突，如果它是一个打开的 @ref{c1d,,file object} 的话；请确保你不会试图写入字符串到二进制流或者反向操作。


3.4 新版功能: @emph{short_empty_elements} 形参。



在 3.8 版更改: @ref{a06,,write()} 方法现在会保留用户指定的属性顺序。

@end deffn
@end deffn

这是将要被操作的 XML 文件:

@example
<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>
@end example

修改第一段中的每个链接的 "target"  属性的示例:

@example
>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a"))   # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
>>> tree.write("output.xhtml")
@end example

@node QName 对象,TreeBuilder 对象,ElementTree 对象,参考引用<2>
@anchor{library/xml etree elementtree elementtree-qname-objects}@anchor{2b5f}@anchor{library/xml etree elementtree qname-objects}@anchor{2b60}
@subsubsection QName 对象


@geindex QName (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree QName}@anchor{2b61}
@deffn {类} xml.etree.ElementTree.QName (text_or_uri, tag=None)

QName 包装器。 这可被用来包装 QName 属性值，以便在输出中获得适当的命名空间处理。 @emph{text_or_uri} 是一个包含 QName 值的字符串，其形式为 @{uri@}local，或者如果给出了 tag 参数，则为 QName 的 URI 部分。 如果给出了 @emph{tag}，则第一个参数会被解读为 URI，而这个参数会被解读为本地名称。 @ref{2b61,,QName} 实例是不透明的。
@end deffn

@node TreeBuilder 对象,XMLParser对象,QName 对象,参考引用<2>
@anchor{library/xml etree elementtree elementtree-treebuilder-objects}@anchor{2b62}@anchor{library/xml etree elementtree treebuilder-objects}@anchor{2b63}
@subsubsection TreeBuilder 对象


@geindex TreeBuilder (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder}@anchor{384}
@deffn {类} xml.etree.ElementTree.TreeBuilder (element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)

通用元素结构构建器。  此构建器会将包含 start, data, end, comment 和 pi 方法调用的序列转换为格式良好的元素结构。 你可以通过这个类使用一个自定义 XML 解析器或其他 XML 类格式的解析器来构建元素结构。

如果给出 @emph{element_factory}，它必须为接受两个位置参数的可调用对象：一个标记和一个属性字典。  它预期会返回一个新的元素实例。

如果给出 @emph{comment_factory} 和 @emph{pi_factory} 函数，它们的行为应当像 @ref{2b3a,,Comment()} 和 @ref{2b40,,ProcessingInstruction()} 函数一样创建注释和处理指令。 如果未给出，则将使用默认工厂函数。 当 @emph{insert_comments} 和/或 @emph{insert_pis} 为真值时，如果 comments/pis 在根元素之中（但不在其之外）出现则它们将被插入到树中。

@geindex close() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder close}@anchor{2b64}
@deffn {方法} close ()

刷新构建器缓存，并返回最高层级的文档元素。 返回一个 @ref{21e,,Element} 实例。
@end deffn

@geindex data() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder data}@anchor{2b65}
@deffn {方法} data (data)

将文本添加到当前元素。 @emph{data} 为要添加的文本。 这应当是一个字节串或 Unicode 字符串。
@end deffn

@geindex end() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder end}@anchor{c2f}
@deffn {方法} end (tag)

关闭当前元素。 @emph{tag} 是元素名称。 返回已关闭的元素。
@end deffn

@geindex start() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder start}@anchor{10b6}
@deffn {方法} start (tag, attrs)

打开一个新元素。 @emph{tag} 是元素名称。 @emph{attrs} 是包含元素属性的字典。 返回打开的元素。
@end deffn

@geindex comment() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder comment}@anchor{2b66}
@deffn {方法} comment (text)

使用给定的 @emph{text} 创建一条注释。 如果 @code{insert_comments} 为真值，这还会将其添加到树结构中。


3.8 新版功能.

@end deffn

@geindex pi() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder pi}@anchor{2b67}
@deffn {方法} pi (target, text)

使用给定的 @emph{target} 名称和 @emph{text} 创建一条注释。 如果 @code{insert_pis} 为真值，这还会将其添加到树结构中。


3.8 新版功能.

@end deffn

此外，自定义的 @ref{384,,TreeBuilder} 对象还提供了以下方法:

@geindex doctype() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder doctype}@anchor{3eb}
@deffn {方法} doctype (name, pubid, system)

处理一条 doctype 声明。 @emph{name} 为 doctype 名称。 @emph{pubid} 为公有标识。 @emph{system} 为系统标识。 此方法不存在于默认的 @ref{384,,TreeBuilder} 类中。


3.2 新版功能.

@end deffn

@geindex start_ns() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder start_ns}@anchor{2b68}
@deffn {方法} start_ns (prefix, uri)

在定义了 @code{start()} 回调的打开元素的该回调被调用之前，当解析器遇到新的命名空间声明时都会被调用。 @emph{prefix} 对于默认命名空间为 @code{'@w{'}} 或者在其他情况下为被声明的命名空间前缀名称。 @emph{uri} 是命名空间 URI。


3.8 新版功能.

@end deffn

@geindex end_ns() (xml.etree.ElementTree.TreeBuilder 方法)
@anchor{library/xml etree elementtree xml etree ElementTree TreeBuilder end_ns}@anchor{2b69}
@deffn {方法} end_ns (prefix)

在声明了命名空间前缀映射的元素的 @code{end()} 回调之后被调用，附带超出作用域的 @emph{prefix} 的名称。


3.8 新版功能.

@end deffn
@end deffn

@geindex C14NWriterTarget (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree C14NWriterTarget}@anchor{2b6a}
@deffn {类} xml.etree.ElementTree.C14NWriterTarget (write, *, with_comments=False, strip_text=False, rewrite_prefixes=False, qname_aware_tags=None, qname_aware_attrs=None, exclude_attrs=None, exclude_tags=None)

C14N 2.0@footnote{https://www.w3.org/TR/xml-c14n2/} 写入器。 其参数与 @ref{2b39,,canonicalize()} 函数的相同。 这个类并不会构建树结构而是使用 @emph{write} 函数将回调事件直接转换为序列化形式。


3.8 新版功能.

@end deffn

@node XMLParser对象,XMLPullParser对象,TreeBuilder 对象,参考引用<2>
@anchor{library/xml etree elementtree elementtree-xmlparser-objects}@anchor{2b6b}@anchor{library/xml etree elementtree xmlparser-objects}@anchor{2b6c}
@subsubsection XMLParser对象


@geindex XMLParser (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser}@anchor{383}
@deffn {类} xml.etree.ElementTree.XMLParser (*, target=None, encoding=None)

这个类是此模块的低层级构建单元。 它使用 @ref{141,,xml.parsers.expat} 来实现高效、基于事件的 XML 解析。  它可以通过 @ref{2b6d,,feed()} 方法增量式地收受 XML 数据，并且解析事件会被转换为推送式 API —— 通过在 @emph{target} 对象上发起对回调的调用。 如果省略 @emph{target}，则会使用标准的 @ref{384,,TreeBuilder}。 如果给出了 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如 "UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} ，该值将覆盖在 XML 文件中指定的编码格式。


在 3.8 版更改: 所有形参现在都是 @ref{3d6,,仅限关键字形参}。 @emph{html} 参数不再受支持。


@geindex close() (xml.etree.ElementTree.XMLParser 方法)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser close}@anchor{2b6e}
@deffn {方法} close ()

结束向解析器提供数据。 返回调用在构造期间传入的 @emph{target} 的 @code{close()} 方法的结果；在默认情况下，这是最高层级的文档元素。
@end deffn

@geindex feed() (xml.etree.ElementTree.XMLParser 方法)
@anchor{library/xml etree elementtree xml etree ElementTree XMLParser feed}@anchor{2b6d}
@deffn {方法} feed (data)

将数据送入解析器。 @emph{data} 是编码后的数据。
@end deffn

@ref{2b6d,,XMLParser.feed()} 会为每个打开的标记调用 @emph{target} 的 @code{start(tag, attrs_dict)} 方法，为每个关闭的标记调用它的 @code{end(tag)} 方法，并通过 @code{data(data)} 方法来处理数据。 有关更多受支持的回调方法，请参阅 @ref{384,,TreeBuilder} 类。  @ref{2b6e,,XMLParser.close()} 会调用 @emph{target} 的 @code{close()} 方法。 @ref{383,,XMLParser} 不仅仅可被用来构建树结构。 下面是一个统计 XML 文件最大深度的示例:

@example
>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4
@end example
@end deffn

@node XMLPullParser对象,异常<15>,XMLParser对象,参考引用<2>
@anchor{library/xml etree elementtree elementtree-xmlpullparser-objects}@anchor{2b6f}@anchor{library/xml etree elementtree xmlpullparser-objects}@anchor{2b70}
@subsubsection XMLPullParser对象


@geindex XMLPullParser (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser}@anchor{a02}
@deffn {类} xml.etree.ElementTree.XMLPullParser (events=None)

适用于非阻塞应用程序的拉取式解析器。 它的输入侧 API 与 @ref{383,,XMLParser} 的类似，但不是向回调目标推送调用，@ref{a02,,XMLPullParser} 会收集一个解析事件的内部列表并让用户来读取它。 @emph{events} 是要报告的事件序列。 受支持的事件字符串有 @code{"start"}, @code{"end"}, @code{"comment"}, @code{"pi"}, @code{"start-ns"} 和 @code{"end-ns"} ("ns" 事件被用于获取详细的命名空间信息)。 如果 @emph{events} 被省略，则只报告 @code{"end"} 事件。

@geindex feed() (xml.etree.ElementTree.XMLPullParser 方法)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser feed}@anchor{2b25}
@deffn {方法} feed (data)

将给定的字节数据送入解析器。
@end deffn

@geindex close() (xml.etree.ElementTree.XMLPullParser 方法)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser close}@anchor{2b71}
@deffn {方法} close ()

通知解析器数据流已终结。 不同于 @ref{2b6e,,XMLParser.close()}，此方法总是返回 @ref{204,,None}。 当解析器被关闭时任何还未被获取的事件仍可通过 @ref{2b26,,read_events()} 被读取。
@end deffn

@geindex read_events() (xml.etree.ElementTree.XMLPullParser 方法)
@anchor{library/xml etree elementtree xml etree ElementTree XMLPullParser read_events}@anchor{2b26}
@deffn {方法} read_events ()

返回包含在送入解析器的数据中遇到的事件的迭代器。 此迭代器会产生 @code{(event, elem)} 对，其中 @emph{event} 是代表事件类型的字符串 (例如 @code{"end"}) 而 @emph{elem} 是遇到的 @ref{21e,,Element} 对象，或者以下的其他上下文值。


@itemize *

@item 
@code{start}, @code{end}: 当前元素。

@item 
@code{comment}, @code{pi}: 当前注释 / 处理指令

@item 
@code{start-ns}: 一个指定所声明命名空间映射的元组 @code{(prefix, uri)}。

@item 
@code{end-ns}: @ref{204,,None} (这可能在未来版本中改变)
@end itemize

在之前对 @ref{2b26,,read_events()} 的调用中提供的事件将不会被再次产生。 事件仅当它们从迭代器中被取出时才会在内部队列中被消费，因此多个读取方对获取自 @ref{2b26,,read_events()} 的迭代器进行平行迭代将产生无法预料的结果。
@end deffn

@cartouche
@quotation 注解 
@ref{a02,,XMLPullParser} 只会确保当发出 "start" 事件时看到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本内容和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存在也可能不存在。

如果你需要已完全填充的元素，请改为查找 "end" 事件。
@end quotation
@end cartouche


3.4 新版功能.



在 3.8 版更改: 增加了 @code{comment} 和 @code{pi} 事件。

@end deffn

@node 异常<15>,,XMLPullParser对象,参考引用<2>
@anchor{library/xml etree elementtree exceptions}@anchor{2b72}
@subsubsection 异常


@geindex ParseError (xml.etree.ElementTree 中的类)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError}@anchor{cdf}
@deffn {类} xml.etree.ElementTree.ParseError

XML 解析器错误，由此模块中的多个解析方法在解析失败时引发。 此异常的实例的字符串表示将包含用户友好的错误消息。 此外，它将具有下列可用属性:

@geindex code (xml.etree.ElementTree.ParseError 属性)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError code}@anchor{2b73}
@deffn {属性} code

来自外部解析器的数字错误代码。 请参阅 @ref{141,,xml.parsers.expat} 的文档查看错误代码列表及它们的含义。
@end deffn

@geindex position (xml.etree.ElementTree.ParseError 属性)
@anchor{library/xml etree elementtree xml etree ElementTree ParseError position}@anchor{2b74}
@deffn {属性} position

一个包含 @emph{line}, @emph{column} 数值的元组，指明错误发生的位置。
@end deffn
@end deffn

@node xml dom --- 文档对象模型 API,xml dom minidom --- 最小化的 DOM 实现,xml etree ElementTree --- ElementTree XML API,结构化标记处理工具
@anchor{library/xml dom doc}@anchor{2b75}@anchor{library/xml dom module-xml dom}@anchor{13d}@anchor{library/xml dom xml-dom-the-document-object-model-api}@anchor{2b76}
@subsection @code{xml.dom} --- 文档对象模型 API


@geindex xml.dom (模块)

@strong{源代码:} Lib/xml/dom/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/dom/__init__.py}


__________________________________________________________________


文档对象模型“DOM”是一个来自万维网联盟（W3C）的跨语言 API，用于访问和修改 XML 文档。 DOM 的实现将 XML 文档以树结构表示，或者允许客户端代码从头构建这样的结构。 然后它会通过一组提供通用接口的对象赋予对结构的访问权。

DOM 特别适用于进行随机访问的应用。 SAX 仅允许你每次查看文档的一小部分。 如果你正在查看一个 SAX 元素，你将不能访问其他元素。 如果你正在查看一个文本节点，你将不能访问包含它的元素。 当你编写一个 SAX 应用时，你需要在你自己的代码的某个地方记住你的程序在文档中的位置。 SAX 不会帮你做这件事。 并且，如果你想要在 XML 文档中向前查看，你是绝对办不到的。

有些应用程序在不能访问树的事件驱动模型中是根本无法编写的。 当然你可以在 SAX 事件中自行构建某种树，但是 DOM 可以使你避免编写这样的代码。 DOM 是针对 XML 数据的标准树表示形式。

文档对象模型是由 W3C 分阶段定义的，在其术语中称为“层级”。 Python 中该 API 的映射大致是基于 DOM 第 2 层级的建议。

@c What if your needs are somewhere between SAX and the DOM?  Perhaps
@c you cannot afford to load the entire tree in memory but you find the
@c SAX model somewhat cumbersome and low-level.  There is also a module
@c called xml.dom.pulldom that allows you to build trees of only the
@c parts of a document that you need structured access to.  It also has
@c features that allow you to find your way around the DOM.
@c See http://www.prescod.net/python/pulldom

DOM 应用程序通常从将某些 XML 解析为 DOM 开始。 此操作如何实现完全未被 DOM 第 1 层级所涉及，而第 2 层级也只提供了有限的改进：有一个 @code{DOMImplementation} 对象类，它提供对 @code{Document} 创建方法的访问，但却没有办法以不依赖具体实现的方式访问 XML 读取器/解析器/文档创建器。 也没有当不存在 @code{Document} 对象的情况下访问这些方法的定义良好的方式。 在 Python 中，每个 DOM 实现将提供一个函数 @ref{2b77,,getDOMImplementation()}。 DOM 第 3 层级增加了一个载入/存储规格说明，它定义了与读取器的接口，但这在 Python 标准库中尚不可用。

一旦你得到了 DOM 文档对象，你就可以通过 XML 文档的属性和方法访问它的各个部分。 这些属性定义在 DOM 规格说明当中；参考指南的这一部分描述了 Python 对此规格说明的解读。

W3C 提供的规格说明定义了适用于 Java, ECMAScript 和 OMG IDL 的 DOM API。 这里定义的 Python 映射很大程度上是基于此规格说明的 IDL 版本，但并不要求严格映射（但具体实现可以自由地支持对 IDL 的严格映射）。 请参阅 @ref{2b78,,一致性} 一节查看有关映射要求的详细讨论。


@subsubheading 参见



@table @asis

@item 文档对象模型 (DOM) 第 2 层级规格说明@footnote{https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/}

被 Python DOM API 作为基础的 W3C 建议。

@item 文档对象模型 (DOM) 第 1 层级规格说明@footnote{https://www.w3.org/TR/REC-DOM-Level-1/}

被 @ref{13e,,xml.dom.minidom} 所支持的 W3C 针对 DOM 的建议。

@item Python 语言映射规格说明@footnote{https://www.omg.org/spec/PYTH/1.2/PDF}

此文档指明了从 OMG IDL 到 Python 的映射。
@end table


@menu
* 模块内容: 模块内容<6>. 
* DOM 中的对象:: 
* 一致性:: 

@end menu

@node 模块内容<6>,DOM 中的对象,,xml dom --- 文档对象模型 API
@anchor{library/xml dom module-contents}@anchor{2b79}
@subsubsection 模块内容


@ref{13d,,xml.dom} 包含下列函数:

@geindex registerDOMImplementation() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom registerDOMImplementation}@anchor{2b7a}
@deffn {函数} xml.dom.registerDOMImplementation (name, factory)

注册 @emph{factory} 函数并使用名称 @emph{name}。 该工厂函数应当返回一个实现了 @code{DOMImplementation} 接口的对象。 该工厂函数可每次都返回相同对象，或每次调用都返回新的对象，视具体实现的要求而定（例如该实现是否支持某些定制功能）。
@end deffn

@geindex getDOMImplementation() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom getDOMImplementation}@anchor{2b77}
@deffn {函数} xml.dom.getDOMImplementation (name=None, features=())

返回一个适当的 DOM 实现。 @emph{name} 是通用名称、DOM 实现的模块名称或者 @code{None}。 如果它不为 @code{None}，则会导入相应模块并在导入成功时返回一个 @code{DOMImplementation} 对象。 如果没有给出名称，并且如果设置了 
@geindex PYTHON_DOM
@geindex 环境变量; PYTHON_DOM
@code{PYTHON_DOM} 环境变量，此变量会被用来查找相应的实现。

如果未给出 name，此函数会检查可用的实现来查找具有所需特性集的一个。 如果找不到任何实现，则会引发 @ref{16c,,ImportError}。 features 集必须是包含 @code{(feature, version)} 对的序列，它会被传给可用的 @code{DOMImplementation} 对象上的 @code{hasFeature()} 方法。
@end deffn

还提供了一些便捷常量:

@geindex EMPTY_NAMESPACE() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom EMPTY_NAMESPACE}@anchor{2b7b}
@deffn {数据} xml.dom.EMPTY_NAMESPACE

该值用于指明没有命名空间被关联到 DOM 中的某个节点。 它通常被作为某个节点的 @code{namespaceURI}，或者被用作某个命名空间专属方法的 @emph{namespaceURI} 参数。
@end deffn

@geindex XML_NAMESPACE() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom XML_NAMESPACE}@anchor{2b7c}
@deffn {数据} xml.dom.XML_NAMESPACE

关联到保留前缀 @code{xml} 的命名空间 URI，如 XML 中的命名空间@footnote{https://www.w3.org/TR/REC-xml-names/} （第 4 节） 所定义的。
@end deffn

@geindex XMLNS_NAMESPACE() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom XMLNS_NAMESPACE}@anchor{2b7d}
@deffn {数据} xml.dom.XMLNS_NAMESPACE

命名空间声明的命名空间 URI，如 文档对象模型 (DOM) 第 2 层级核心规格说明@footnote{https://www.w3.org/TR/DOM-Level-2-Core/core.html} (第 1.1.8节) 所定义的。
@end deffn

@geindex XHTML_NAMESPACE() (在 xml.dom 模块中)
@anchor{library/xml dom xml dom XHTML_NAMESPACE}@anchor{2b7e}
@deffn {数据} xml.dom.XHTML_NAMESPACE

XHTML 命名空间的 URI，如 XHTML 1.0: 扩展超文本标记语言@footnote{https://www.w3.org/TR/xhtml1/} (第 3.1.1 节) 所定义的。
@end deffn

此外，@ref{13d,,xml.dom} 还包含一个基本 @code{Node} 类和一些 DOM 异常类。 此模块提供的 @code{Node} 类未实现 DOM 规格描述所定义的任何方法和属性；实际的 DOM 实现必须提供它们。 提供 @code{Node} 类作为此模块的一部分并没有提供用于实际的 @code{Node} 对象的 @code{nodeType} 属性的常量；它们是位于类内而不是位于模块层级以符合 DOM 规格描述。

@c Should the Node documentation go here?

@node DOM 中的对象,一致性,模块内容<6>,xml dom --- 文档对象模型 API
@anchor{library/xml dom dom-objects}@anchor{2b7f}@anchor{library/xml dom objects-in-the-dom}@anchor{2b80}
@subsubsection DOM 中的对象


DOM 的权威文档是来自 W3C 的 DOM 规格描述。

请注意，DOM 属性也可以作为节点而不是简单的字符串进行操作。 然而，必须这样做的情况相当少见，所以这种用法还没有被写入文档。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

接口

@tab

部件

@tab

目的

@item

@code{DOMImplementation}

@tab

@ref{2b81,,DOMImplementation 对象}

@tab

底层实现的接口。

@item

@code{Node}

@tab

@ref{2b82,,节点对象}

@tab

文档中大多数对象的基本接口。

@item

@code{NodeList}

@tab

@ref{2b83,,节点列表对象}

@tab

节点序列的接口。

@item

@code{DocumentType}

@tab

@ref{2b84,,文档类型对象}

@tab

有关处理文档所需声明的信息。

@item

@code{Document}

@tab

@ref{2b85,,Document 对象}

@tab

表示整个文档的对象。

@item

@code{Element}

@tab

@ref{2b86,,元素对象}

@tab

文档层次结构中的元素节点。

@item

@code{Attr}

@tab

@ref{2b87,,Attr 对象}

@tab

元素节点上的属性值节点。

@item

@code{Comment}

@tab

@ref{2b88,,注释对象}

@tab

源文档中注释的表示形式。

@item

@code{Text}

@tab

@ref{2b89,,Text 和 CDATASection 对象}

@tab

包含文档中文本内容的节点。

@item

@code{ProcessingInstruction}

@tab

@ref{2b8a,,ProcessingInstruction 对象}

@tab

处理指令表示形式。

@end multitable


描述在 Python 中使用 DOM 定义的异常的小节。

@menu
* DOMImplementation 对象:: 
* 节点对象:: 
* 节点列表对象:: 
* 文档类型对象:: 
* Document 对象:: 
* 元素对象: 元素对象<2>. 
* Attr 对象:: 
* NamedNodeMap 对象:: 
* 注释对象:: 
* Text 和 CDATASection 对象:: 
* ProcessingInstruction 对象:: 
* 异常: 异常<16>. 

@end menu

@node DOMImplementation 对象,节点对象,,DOM 中的对象
@anchor{library/xml dom dom-implementation-objects}@anchor{2b81}@anchor{library/xml dom domimplementation-objects}@anchor{2b8b}
@subsubsection DOMImplementation 对象


@code{DOMImplementation} 接口提供了一种让应用程序确定他们所使用的 DOM 中某一特性可用性的方式。 DOM 第 2 级还添加了使用 @code{DOMImplementation} 来创建新的 @code{Document} 和 @code{DocumentType} 对象的能力。

@geindex hasFeature() (xml.dom.DOMImplementation 方法)
@anchor{library/xml dom xml dom DOMImplementation hasFeature}@anchor{2b8c}
@deffn {方法} DOMImplementation.hasFeature (feature, version)

如果字符串对 @emph{feature} 和 @emph{version} 所标识的特性已被实现则返回 @code{True}。
@end deffn

@geindex createDocument() (xml.dom.DOMImplementation 方法)
@anchor{library/xml dom xml dom DOMImplementation createDocument}@anchor{2b8d}
@deffn {方法} DOMImplementation.createDocument (namespaceUri, qualifiedName, doctype)

返回一个新的 @code{Document} 对象 (DOM 的根节点)，包含一个具有给定 @emph{namespaceUri} 和 @emph{qualifiedName} 的下级 @code{Element} 对象。 @emph{doctype} 必须为由 @ref{2b8e,,createDocumentType()} 创建的 @code{DocumentType} 对象，或者为 @code{None}。 在 Python DOM API 中，前两个参数也可为 @code{None} 以表示不要创建任何下级 @code{Element}。
@end deffn

@geindex createDocumentType() (xml.dom.DOMImplementation 方法)
@anchor{library/xml dom xml dom DOMImplementation createDocumentType}@anchor{2b8e}
@deffn {方法} DOMImplementation.createDocumentType (qualifiedName, publicId, systemId)

返回一个新的封装了给定 @emph{qualifiedName}, @emph{publicId} 和 @emph{systemId} 字符串的 @code{DocumentType} 对象，它表示包含在 XML 文档类型声明中的信息。
@end deffn

@node 节点对象,节点列表对象,DOMImplementation 对象,DOM 中的对象
@anchor{library/xml dom dom-node-objects}@anchor{2b82}@anchor{library/xml dom node-objects}@anchor{2b8f}
@subsubsection 节点对象


XML 文档的所有组成部分都是 @code{Node} 的子类。

@geindex nodeType (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node nodeType}@anchor{2b90}
@deffn {属性} Node.nodeType

一个代表节点类型的整数。 类型符号常量在 @code{Node} 对象上: @code{ELEMENT_NODE}, @code{ATTRIBUTE_NODE}, @code{TEXT_NODE}, @code{CDATA_SECTION_NODE}, @code{ENTITY_NODE}, @code{PROCESSING_INSTRUCTION_NODE}, @code{COMMENT_NODE}, @code{DOCUMENT_NODE}, @code{DOCUMENT_TYPE_NODE}, @code{NOTATION_NODE}。 这是个只读属性。
@end deffn

@geindex parentNode (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node parentNode}@anchor{2b91}
@deffn {属性} Node.parentNode

当前节点的上级，或者对于文档节点则为 @code{None}。 该值总是一个 @code{Node} 对象或者 @code{None}。 对于 @code{Element} 节点，这将为上级元素，但对于根元素例外，在此情况下它将为 @code{Document} 对象。 对于 @code{Attr} 节点，它将总是为 @code{None}。 这是个只读属性。
@end deffn

@geindex attributes (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node attributes}@anchor{2b92}
@deffn {属性} Node.attributes

属性对象的 @code{NamedNodeMap}。 这仅对元素才有实际值；其它对象会为该属性提供 @code{None} 值。 这是个只读属性。
@end deffn

@geindex previousSibling (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node previousSibling}@anchor{2b93}
@deffn {属性} Node.previousSibling

在此节点之前具有相同上级的相邻节点。 例如结束标记紧接在在 @emph{self} 元素的开始标记之前的元素。 当然，XML 文档并非只是由元素组成，因此之前相邻节点可以是文本、注释或者其他内容。 如果此节点是上级的第一个子节点，则该属性将为 @code{None}。 这是一个只读属性。
@end deffn

@geindex nextSibling (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node nextSibling}@anchor{2b94}
@deffn {属性} Node.nextSibling

在此节点之后具有相同上级的相邻节点。 另请参见 @ref{2b93,,previousSibling}。 如果此节点是上级的最后一个子节点，则该属性将为 @code{None}。 这是一个只读属性。
@end deffn

@geindex childNodes (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node childNodes}@anchor{2b95}
@deffn {属性} Node.childNodes

包含在此节点中的节点列表。 这是一个只读属性。
@end deffn

@geindex firstChild (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node firstChild}@anchor{2b96}
@deffn {属性} Node.firstChild

节点的第一个下级，如果有的话，否则为 @code{None}。 这是个只读属性。
@end deffn

@geindex lastChild (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node lastChild}@anchor{2b97}
@deffn {属性} Node.lastChild

节点的最后一个下级，如果有的话，否则为 @code{None}。 这是个只读属性。
@end deffn

@geindex localName (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node localName}@anchor{2b98}
@deffn {属性} Node.localName

@code{tagName} 在冒号之后的部分，如果有冒号的话，否则为整个 @code{tagName}。 该值为一个字符串。
@end deffn

@geindex prefix (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node prefix}@anchor{2b99}
@deffn {属性} Node.prefix

@code{tagName} 在冒号之前的部分，如果有冒号的话，否则为空字符串。 该值为一个字符串或者为 @code{None}。
@end deffn

@geindex namespaceURI (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node namespaceURI}@anchor{2b9a}
@deffn {属性} Node.namespaceURI

关联到元素名称的命名空间。 这将是一个字符串或为 @code{None}。 这是个只读属性。
@end deffn

@geindex nodeName (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node nodeName}@anchor{2b9b}
@deffn {属性} Node.nodeName

这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 你总是可以从其他特征属性例如元素的 @code{tagName} 特征属性或属性的 @code{name} 特征属性获取你能从这里获取的信息。 对于所有节点类型，这个属性的值都将是一个字符串或为 @code{None}。 这是一个只读属性。
@end deffn

@geindex nodeValue (xml.dom.Node 属性)
@anchor{library/xml dom xml dom Node nodeValue}@anchor{2b9c}
@deffn {属性} Node.nodeValue

这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 具体情况与 @ref{2b9b,,nodeName} 的类似。 该值是一个字符串或为 @code{None}。
@end deffn

@geindex hasAttributes() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node hasAttributes}@anchor{2b9d}
@deffn {方法} Node.hasAttributes ()

如果该节点具有任何属性则返回 @code{True}。
@end deffn

@geindex hasChildNodes() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node hasChildNodes}@anchor{2b9e}
@deffn {方法} Node.hasChildNodes ()

如果该节点具有任何子节点则返回 @code{True}。
@end deffn

@geindex isSameNode() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node isSameNode}@anchor{2b9f}
@deffn {方法} Node.isSameNode (other)

如果 @emph{other} 指向的节点就是此节点则返回 @code{True}。 这对于使用了任何代理架构的 DOM 实现来说特别有用（因为多个对象可能指向相同节点）。

@cartouche
@quotation 注解 
这是基于已提议的 DOM 第 3 等级 API，目前尚处于“起草”阶段，但这个特定接口看来并不存在争议。 来自 W3C 的修改将不会影响 Python DOM 接口中的这个方法（不过针对它的任何新 W3C API 也将受到支持）。
@end quotation
@end cartouche
@end deffn

@geindex appendChild() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node appendChild}@anchor{2ba0}
@deffn {方法} Node.appendChild (newChild)

在子节点列表末尾添加一个新的子节点，返回 @emph{newChild}。 如果节点已存在于树结构中，它将先被移除。
@end deffn

@geindex insertBefore() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node insertBefore}@anchor{2ba1}
@deffn {方法} Node.insertBefore (newChild, refChild)

在现有的子节点之前插入一个新的子节点。 它必须属于 @emph{refChild} 是这个节点的子节点的情况；如果不是，则会引发 @ref{16d,,ValueError}。@emph{newChild} 会被返回。 如果 @emph{refChild} 为 @code{None}，它会将 @emph{newChild} 插入到子节点列表的末尾。
@end deffn

@geindex removeChild() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node removeChild}@anchor{2ba2}
@deffn {方法} Node.removeChild (oldChild)

移除一个子节点。 @emph{oldChild} 必须是这个节点的子节点；如果不是，则会引发 @ref{16d,,ValueError}。 成功时 @emph{oldChild} 会被返回。 如果 @emph{oldChild} 将不再被继续使用，则将调用它的 @code{unlink()} 方法。
@end deffn

@geindex replaceChild() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node replaceChild}@anchor{2ba3}
@deffn {方法} Node.replaceChild (newChild, oldChild)

将一个现有节点替换为新的节点。 这必须属于 @emph{oldChild} 是该节点的子节点的情况；如果不是，则会引发 @ref{16d,,ValueError}。
@end deffn

@geindex normalize() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node normalize}@anchor{2ba4}
@deffn {方法} Node.normalize ()

合并相邻的文本节点以便将所有文本段存储为单个 @code{Text} 实例。 这可以简化许多应用程序处理来自 DOM 树文本的操作。
@end deffn

@geindex cloneNode() (xml.dom.Node 方法)
@anchor{library/xml dom xml dom Node cloneNode}@anchor{2ba5}
@deffn {方法} Node.cloneNode (deep)

克隆此节点。 设置 @emph{deep} 表示也克隆所有子节点。 此方法将返回克隆的节点。
@end deffn

@node 节点列表对象,文档类型对象,节点对象,DOM 中的对象
@anchor{library/xml dom dom-nodelist-objects}@anchor{2b83}@anchor{library/xml dom nodelist-objects}@anchor{2ba6}
@subsubsection 节点列表对象


@code{NodeList} 代表一个节点列表。 在 DOM 核心建议中这些对象有两种使用方式: 由 @code{Element} 对象提供作为其子节点列表，以及由 @code{Node} 的 @code{getElementsByTagName()} 和 @code{getElementsByTagNameNS()} 方法通过此接口返回对象来表示查询结果。

DOM 第 2 层级建议为这些对象定义一个方法和一个属性:

@geindex item() (xml.dom.NodeList 方法)
@anchor{library/xml dom xml dom NodeList item}@anchor{2ba7}
@deffn {方法} NodeList.item (i)

从序列中返回第 @emph{i} 项，如果序列不为空的话，否则返回 @code{None}。 索引号 @emph{i} 不允许小于零或大于等于序列的长度。
@end deffn

@geindex length (xml.dom.NodeList 属性)
@anchor{library/xml dom xml dom NodeList length}@anchor{2ba8}
@deffn {属性} NodeList.length

序列中的节点数量。
@end deffn

此外，Python DOM 接口还要求提供一些额外支持来允许将 @code{NodeList} 对象用作 Python 序列。 所有 @code{NodeList} 实现都必须包括对 @ref{e98,,__len__()} 和 @ref{3ad,,__getitem__()} 的支持；这样 @code{NodeList} 就允许使用 @ref{d02,,for} 语句进行迭代并能正确地支持 @ref{292,,len()} 内置函数。

如果一个 DOM 实现支持文档的修改，则 @code{NodeList} 实现还必须支持 @ref{d32,,__setitem__()} 和 @ref{d33,,__delitem__()} 方法。

@node 文档类型对象,Document 对象,节点列表对象,DOM 中的对象
@anchor{library/xml dom documenttype-objects}@anchor{2ba9}@anchor{library/xml dom dom-documenttype-objects}@anchor{2b84}
@subsubsection 文档类型对象


有关一个文档所声明的标注和实体的信息（包括解析器所使用并能提供信息的外部子集）可以从 @code{DocumentType} 对象获取。 文档的 @code{DocumentType} 可从 @code{Document} 对象的 @code{doctype} 属性中获取；如果一个文档没有 @code{DOCTYPE} 声明，则该文档的 @code{doctype} 属性将被设为 @code{None} 而非此接口的一个实例。

@code{DocumentType} 是 @code{Node} 是专门化，并增加了下列属性:

@geindex publicId (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType publicId}@anchor{2baa}
@deffn {属性} DocumentType.publicId

文档类型定义的外部子集的公有标识。 这将为一个字符串或者为 @code{None}。
@end deffn

@geindex systemId (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType systemId}@anchor{2bab}
@deffn {属性} DocumentType.systemId

文档类型定义的外部子集的系统标识。 这将为一个字符串形式的 URI，或者为 @code{None}。
@end deffn

@geindex internalSubset (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType internalSubset}@anchor{2bac}
@deffn {属性} DocumentType.internalSubset

一个给出来自文档的完整内部子集的字符串。 这不包括子集外面的圆括号。 如果文档没有内部子集，则应为 @code{None}。
@end deffn

@geindex name (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType name}@anchor{2bad}
@deffn {属性} DocumentType.name

@code{DOCTYPE} 声明中给出的根元素名称，如果有的话。
@end deffn

@geindex entities (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType entities}@anchor{2bae}
@deffn {属性} DocumentType.entities

这是给出外部实体定义的 @code{NamedNodeMap}。 对于多次定义的实体名称，则只提供第一次的定义（其他的会按照 XML 建议被忽略）。 这可能为 @code{None}，如果解析器未提供此信息，或者如果未定义任何实体的话。
@end deffn

@geindex notations (xml.dom.DocumentType 属性)
@anchor{library/xml dom xml dom DocumentType notations}@anchor{2baf}
@deffn {属性} DocumentType.notations

这是给出标注定义的 @code{NamedNodeMap}。 对于多次定义的标注，则只提供第一次的定义（其他的会按照 XML 建议被忽略）。 这可能为 @code{None}，如果解析器未提供此信息，或者如果未定义任何标注的话。
@end deffn

@node Document 对象,元素对象<2>,文档类型对象,DOM 中的对象
@anchor{library/xml dom document-objects}@anchor{2bb0}@anchor{library/xml dom dom-document-objects}@anchor{2b85}
@subsubsection Document 对象


@code{Document} 代表一个完整的 XML 文档，包括其组成元素、属性、处理指令和注释等。 请记住它会继承来自 @code{Node} 的属性。

@geindex documentElement (xml.dom.Document 属性)
@anchor{library/xml dom xml dom Document documentElement}@anchor{2bb1}
@deffn {属性} Document.documentElement

文档唯一的根元素。
@end deffn

@geindex createElement() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createElement}@anchor{2bb2}
@deffn {方法} Document.createElement (tagName)

创建并返回一个新的元素节点。 当元素被创建时不会被插入到文档中。 你需要通过某个其他方法例如 @code{insertBefore()} 或 @code{appendChild()} 来显示地插入它。
@end deffn

@geindex createElementNS() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createElementNS}@anchor{2bb3}
@deffn {方法} Document.createElementNS (namespaceURI, tagName)

创建并返回一个新的带有命名空间的元素。 @emph{tagName} 可以带有前缀。 当元素被创建时不会被插入到文档中。 你需要通过某个其他方法例如 @code{insertBefore()} 或 @code{appendChild()} 来显式地插入它。
@end deffn

@geindex createTextNode() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createTextNode}@anchor{2bb4}
@deffn {方法} Document.createTextNode (data)

创建并返回一个包含作为形参被传入的数据的文本节点。 与其他创建方法一样，此方法不会将节点插入到树中。
@end deffn

@geindex createComment() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createComment}@anchor{2bb5}
@deffn {方法} Document.createComment (data)

创建并返回一个包含作为形参被传入的数据的注释节点。 与其他创建方法一样，此方法不会将节点插入到树中。
@end deffn

@geindex createProcessingInstruction() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createProcessingInstruction}@anchor{2bb6}
@deffn {方法} Document.createProcessingInstruction (target, data)

创建并返回一个包含作为形参被传入的 @emph{target} 和 @emph{data} 的处理指令节点。 与其他创建方法一样，此方法不会将节点插入到树中。
@end deffn

@geindex createAttribute() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createAttribute}@anchor{2bb7}
@deffn {方法} Document.createAttribute (name)

创建并返回一个属性节点。 此方法不会将属性节点关联到任何特定的元素。 你必须在正确的 @code{Element} 对象上使用 @code{setAttributeNode()} 来使用新创建的属性实例。
@end deffn

@geindex createAttributeNS() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document createAttributeNS}@anchor{2bb8}
@deffn {方法} Document.createAttributeNS (namespaceURI, qualifiedName)

创建并返回一个带有命名空间的属性节点。 @emph{tagName} 可以带有前缀。 此方法不会将属性节点关联到任何特定的元素。 你必须在正确的 @code{Element} 对象上使用 @code{setAttributeNode()} 来使用新创建的属性实例。
@end deffn

@geindex getElementsByTagName() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document getElementsByTagName}@anchor{2bb9}
@deffn {方法} Document.getElementsByTagName (tagName)

搜索全部具有特定元素类型名称的后继元素（直接下级、下级的下级等等）。
@end deffn

@geindex getElementsByTagNameNS() (xml.dom.Document 方法)
@anchor{library/xml dom xml dom Document getElementsByTagNameNS}@anchor{2bba}
@deffn {方法} Document.getElementsByTagNameNS (namespaceURI, localName)

搜索全部具有特定命名空间 URI 和 localname 的后继元素（直接下级、下级的下级等等）。 localname 是命名空间在前缀之后的部分。
@end deffn

@node 元素对象<2>,Attr 对象,Document 对象,DOM 中的对象
@anchor{library/xml dom dom-element-objects}@anchor{2b86}@anchor{library/xml dom element-objects}@anchor{2bbb}
@subsubsection 元素对象


@code{Element} 是 @code{Node} 的子类，因此会继承该类的全部属性。

@geindex tagName (xml.dom.Element 属性)
@anchor{library/xml dom xml dom Element tagName}@anchor{2bbc}
@deffn {属性} Element.tagName

元素类型名称。 在使用命名空间的文档中它可能包含冒号。 该值是一个字符串。
@end deffn

@geindex getElementsByTagName() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getElementsByTagName}@anchor{2bbd}
@deffn {方法} Element.getElementsByTagName (tagName)

与 @code{Document} 类中的对应方法相同。
@end deffn

@geindex getElementsByTagNameNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getElementsByTagNameNS}@anchor{2bbe}
@deffn {方法} Element.getElementsByTagNameNS (namespaceURI, localName)

与 @code{Document} 类中的对应方法相同。
@end deffn

@geindex hasAttribute() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element hasAttribute}@anchor{2bbf}
@deffn {方法} Element.hasAttribute (name)

如果元素带有名称为 @emph{name} 的属性则返回 @code{True}。
@end deffn

@geindex hasAttributeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element hasAttributeNS}@anchor{2bc0}
@deffn {方法} Element.hasAttributeNS (namespaceURI, localName)

如果元素带有名称为 @emph{namespaceURI} 加 @emph{localName} 的属性则返回 @code{True}。
@end deffn

@geindex getAttribute() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getAttribute}@anchor{2bc1}
@deffn {方法} Element.getAttribute (name)

将名称为 @emph{name} 的属性的值作为字符串返回。 如果指定属性不存在，则返回空字符串，就像该属性没有对应的值一样。
@end deffn

@geindex getAttributeNode() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getAttributeNode}@anchor{2bc2}
@deffn {方法} Element.getAttributeNode (attrname)

返回名称为 @emph{attrname} 的属性对应的 @code{Attr} 节点。
@end deffn

@geindex getAttributeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getAttributeNS}@anchor{2bc3}
@deffn {方法} Element.getAttributeNS (namespaceURI, localName)

将名称为 @emph{namespaceURI} 加 @emph{localName} 的属性的值作为字符串返回。 如果指定属性不存在，则返回空字符串，就像该属性没有对应的值一样。
@end deffn

@geindex getAttributeNodeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element getAttributeNodeNS}@anchor{2bc4}
@deffn {方法} Element.getAttributeNodeNS (namespaceURI, localName)

将给定 @emph{namespaceURI} 加 @emph{localName} 的属性的值作为节点返回。
@end deffn

@geindex removeAttribute() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element removeAttribute}@anchor{2bc5}
@deffn {方法} Element.removeAttribute (name)

移除指定名称的节点。 如果没有匹配的属性，则会引发 @ref{2bc6,,NotFoundErr}。
@end deffn

@geindex removeAttributeNode() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element removeAttributeNode}@anchor{2bc7}
@deffn {方法} Element.removeAttributeNode (oldAttr)

从属性列表中移除并返回 @emph{oldAttr}，如果该属性存在的话。 如果 @emph{oldAttr} 不存在，则会引发 @ref{2bc6,,NotFoundErr}。
@end deffn

@geindex removeAttributeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element removeAttributeNS}@anchor{2bc8}
@deffn {方法} Element.removeAttributeNS (namespaceURI, localName)

移除指定名称的属性。 请注意它是使用 localName 而不是 qname。 如果没有匹配的属性也不会引发异常。
@end deffn

@geindex setAttribute() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element setAttribute}@anchor{2bc9}
@deffn {方法} Element.setAttribute (name, value)

将属性值设为指定的字符串。
@end deffn

@geindex setAttributeNode() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element setAttributeNode}@anchor{2bca}
@deffn {方法} Element.setAttributeNode (newAttr)

将一个新的属性节点添加到元素，当匹配到 @code{name} 属性时如有必要会替换现有的属性。 如果发生了替换，将返回原有属性节点。 如果 @emph{newAttr} 已经被使用，则会引发 @ref{2bcb,,InuseAttributeErr}。
@end deffn

@geindex setAttributeNodeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element setAttributeNodeNS}@anchor{2bcc}
@deffn {方法} Element.setAttributeNodeNS (newAttr)

将一个新的属性节点添加到元素，当匹配到 @code{namespaceURI} 和 @code{localName} 属性时如有必要会替换现有的属性。 如果发生了替换，将返回原有属性节点。 如果 @emph{newAttr} 已经被使用，则会引发 @ref{2bcb,,InuseAttributeErr}。
@end deffn

@geindex setAttributeNS() (xml.dom.Element 方法)
@anchor{library/xml dom xml dom Element setAttributeNS}@anchor{2bcd}
@deffn {方法} Element.setAttributeNS (namespaceURI, qname, value)

将属性值设为 @emph{namespaceURI} 和 @emph{qname} 所给出的字符串。 请注意 qname 是整个属性名称。  这与上面的方法不同。
@end deffn

@node Attr 对象,NamedNodeMap 对象,元素对象<2>,DOM 中的对象
@anchor{library/xml dom attr-objects}@anchor{2bce}@anchor{library/xml dom dom-attr-objects}@anchor{2b87}
@subsubsection Attr 对象


@code{Attr} 继承自 @code{Node}，因此会继承其全部属性。

@geindex name (xml.dom.Attr 属性)
@anchor{library/xml dom xml dom Attr name}@anchor{2bcf}
@deffn {属性} Attr.name

属性名称。 在使用命名空间的文档中可能会包括冒号。
@end deffn

@geindex localName (xml.dom.Attr 属性)
@anchor{library/xml dom xml dom Attr localName}@anchor{2bd0}
@deffn {属性} Attr.localName

名称在冒号之后的部分，如果有的话，否则为完整名称。 这是个只读属性。
@end deffn

@geindex prefix (xml.dom.Attr 属性)
@anchor{library/xml dom xml dom Attr prefix}@anchor{2bd1}
@deffn {属性} Attr.prefix

名称在冒号之前的部分，如果有冒号的话，否则为空字符串。
@end deffn

@geindex value (xml.dom.Attr 属性)
@anchor{library/xml dom xml dom Attr value}@anchor{2bd2}
@deffn {属性} Attr.value

属性的文本值。 这与 @code{nodeValue} 属性同义。
@end deffn

@node NamedNodeMap 对象,注释对象,Attr 对象,DOM 中的对象
@anchor{library/xml dom dom-attributelist-objects}@anchor{2bd3}@anchor{library/xml dom namednodemap-objects}@anchor{2bd4}
@subsubsection NamedNodeMap 对象


@code{NamedNodeMap} @emph{不是} 继承自 @code{Node}。

@geindex length (xml.dom.NamedNodeMap 属性)
@anchor{library/xml dom xml dom NamedNodeMap length}@anchor{2bd5}
@deffn {属性} NamedNodeMap.length

属性列表的长度。
@end deffn

@geindex item() (xml.dom.NamedNodeMap 方法)
@anchor{library/xml dom xml dom NamedNodeMap item}@anchor{2bd6}
@deffn {方法} NamedNodeMap.item (index)

返回特定带有索引号的属性。 获取属性的顺序是强制规定的，但在 DOM 的生命期内会保持一致。 其中每一项均为属性节点。 可使用 @code{value} 属性获取其值。
@end deffn

还有一些试验性方法给予这个类更多的映射行为。 你可以使用这些方法或者使用 @code{Element} 对象上标准化的 @code{getAttribute*()} 方法族。

@node 注释对象,Text 和 CDATASection 对象,NamedNodeMap 对象,DOM 中的对象
@anchor{library/xml dom comment-objects}@anchor{2bd7}@anchor{library/xml dom dom-comment-objects}@anchor{2b88}
@subsubsection 注释对象


@code{Comment} 代表 XML 文档中的注释。 它是 @code{Node} 的子类，但不能拥有下级节点。

@geindex data (xml.dom.Comment 属性)
@anchor{library/xml dom xml dom Comment data}@anchor{2bd8}
@deffn {属性} Comment.data

注释的内容是一个字符串。 该属性包含在开头 @code{<!-}@code{-} 和末尾 @code{-}@code{->} 之间的所有字符，但不包括这两个符号。
@end deffn

@node Text 和 CDATASection 对象,ProcessingInstruction 对象,注释对象,DOM 中的对象
@anchor{library/xml dom dom-text-objects}@anchor{2b89}@anchor{library/xml dom text-and-cdatasection-objects}@anchor{2bd9}
@subsubsection Text 和 CDATASection 对象


@code{Text} 接口代表 XML 文档中的文本。 如果解析器和 DOM 实现支持 DOM 的 XML 扩展，则包裹在 CDATA 标记的节中的部分会被存储到 @code{CDATASection} 对象中。 这两个接口很相似，但是提供了不同的 @code{nodeType} 属性值。

这些接口扩展了 @code{Node} 接口。 它们不能拥有下级节点。

@geindex data (xml.dom.Text 属性)
@anchor{library/xml dom xml dom Text data}@anchor{2bda}
@deffn {属性} Text.data

字符串形式的文本节点内容。
@end deffn

@cartouche
@quotation 注解 
@code{CDATASection} 节点的使用并不表示该节点代表一个完整的 CDATA 标记节，只是表示该节点的内容是 CDATA 节的一部分。 单个 CDATA 节可以由文档树中的多个节点来表示。 没有什么办法能确定两个相邻的 @code{CDATASection} 节点是否代表不同的 CDATA 标记节。
@end quotation
@end cartouche

@node ProcessingInstruction 对象,异常<16>,Text 和 CDATASection 对象,DOM 中的对象
@anchor{library/xml dom dom-pi-objects}@anchor{2b8a}@anchor{library/xml dom processinginstruction-objects}@anchor{2bdb}
@subsubsection ProcessingInstruction 对象


代表 XML 文档中的处理指令。 它继承自 @code{Node} 接口并且不能拥有下级节点。

@geindex target (xml.dom.ProcessingInstruction 属性)
@anchor{library/xml dom xml dom ProcessingInstruction target}@anchor{2bdc}
@deffn {属性} ProcessingInstruction.target

到第一个空格符为止的处理指令内容。 这是个只读属性。
@end deffn

@geindex data (xml.dom.ProcessingInstruction 属性)
@anchor{library/xml dom xml dom ProcessingInstruction data}@anchor{2bdd}
@deffn {属性} ProcessingInstruction.data

在第一个空格符之后的处理指令内容。
@end deffn

@node 异常<16>,,ProcessingInstruction 对象,DOM 中的对象
@anchor{library/xml dom dom-exceptions}@anchor{2bde}@anchor{library/xml dom exceptions}@anchor{2bdf}
@subsubsection 异常


DOM 第 2 层级推荐定义一个异常 @ref{2be0,,DOMException}，以及多个变量用来允许应用程序确定发生了何种错误。 @ref{2be0,,DOMException} 实例带有 @ref{1a,,code} 属性用来提供特定异常所对应的值。

Python DOM 接口提供了一些常量，但还扩展了异常集以使 DOM 所定义的每个异常代码都存在特定的异常。 接口的具体实现必须引发正确的特定异常，它们各自带有正确的 @ref{1a,,code} 属性值。

@geindex DOMException
@anchor{library/xml dom xml dom DOMException}@anchor{2be0}
@deffn {例外} xml.dom.DOMException

所有特定 DOM 异常所使用的异常基类。 该异常类不可被直接实例化。
@end deffn

@geindex DomstringSizeErr
@anchor{library/xml dom xml dom DomstringSizeErr}@anchor{2be1}
@deffn {例外} xml.dom.DomstringSizeErr

当指定范围的文本不能适配一个字符串时被引发。 此异常在 Python DOM 实现中尚不可用，但可从不是以 Python 编写的 DOM 实现中接收。
@end deffn

@geindex HierarchyRequestErr
@anchor{library/xml dom xml dom HierarchyRequestErr}@anchor{2be2}
@deffn {例外} xml.dom.HierarchyRequestErr

当尝试插入一个节点但该节点类型不被允许时被引发。
@end deffn

@geindex IndexSizeErr
@anchor{library/xml dom xml dom IndexSizeErr}@anchor{2be3}
@deffn {例外} xml.dom.IndexSizeErr

当一个方法的索引或大小参数为负值或超出允许的值范围时被引发。
@end deffn

@geindex InuseAttributeErr
@anchor{library/xml dom xml dom InuseAttributeErr}@anchor{2bcb}
@deffn {例外} xml.dom.InuseAttributeErr

当尝试插入一个 @code{Attr} 节点但该节点已存在于文档中的某处时被引发。
@end deffn

@geindex InvalidAccessErr
@anchor{library/xml dom xml dom InvalidAccessErr}@anchor{2be4}
@deffn {例外} xml.dom.InvalidAccessErr

当某个参数或操作在底层对象中不受支持时被引发。
@end deffn

@geindex InvalidCharacterErr
@anchor{library/xml dom xml dom InvalidCharacterErr}@anchor{2be5}
@deffn {例外} xml.dom.InvalidCharacterErr

当某个字符串参数包含的字符在使用它的上下文中不被 XML 1.0 标准建议所允许时引发。 例如，尝试创建一个元素类型名称中带有空格的 @code{Element} 节点将导致此错误被引发。
@end deffn

@geindex InvalidModificationErr
@anchor{library/xml dom xml dom InvalidModificationErr}@anchor{2be6}
@deffn {例外} xml.dom.InvalidModificationErr

当尝试修改某个节点的类型时被引发。
@end deffn

@geindex InvalidStateErr
@anchor{library/xml dom xml dom InvalidStateErr}@anchor{2be7}
@deffn {例外} xml.dom.InvalidStateErr

当尝试使用未定义或不再可用的的对象时被引发。
@end deffn

@geindex NamespaceErr
@anchor{library/xml dom xml dom NamespaceErr}@anchor{2be8}
@deffn {例外} xml.dom.NamespaceErr

如果试图以 XML 中的命名空间@footnote{https://www.w3.org/TR/REC-xml-names/} 建议所不允许的方式修改任何对象，则会引发此异常。
@end deffn

@geindex NotFoundErr
@anchor{library/xml dom xml dom NotFoundErr}@anchor{2bc6}
@deffn {例外} xml.dom.NotFoundErr

当某个节点不存在于被引用的上下文中时引发的异常。 例如，@code{NamedNodeMap.removeNamedItem()} 将在所传入的节点不在于于映射中时引发此异常。
@end deffn

@geindex NotSupportedErr
@anchor{library/xml dom xml dom NotSupportedErr}@anchor{2be9}
@deffn {例外} xml.dom.NotSupportedErr

当具体实现不支持所请求的对象类型或操作时被引发。
@end deffn

@geindex NoDataAllowedErr
@anchor{library/xml dom xml dom NoDataAllowedErr}@anchor{2bea}
@deffn {例外} xml.dom.NoDataAllowedErr

当为某个不支持数据 的节点指定数据时被引发。

@c XXX  a better explanation is needed!
@end deffn

@geindex NoModificationAllowedErr
@anchor{library/xml dom xml dom NoModificationAllowedErr}@anchor{2beb}
@deffn {例外} xml.dom.NoModificationAllowedErr

当尝试修改某个不允许修改的对象（例如只读节点）时被引发。
@end deffn

@geindex SyntaxErr
@anchor{library/xml dom xml dom SyntaxErr}@anchor{2bec}
@deffn {例外} xml.dom.SyntaxErr

当指定了无效或非法的字符串时被引发。

@c XXX  how is this different from InvalidCharacterErr?
@end deffn

@geindex WrongDocumentErr
@anchor{library/xml dom xml dom WrongDocumentErr}@anchor{2bed}
@deffn {例外} xml.dom.WrongDocumentErr

当将某个节点插入非其当前所属的另一个文档，并且具体实现不支持从一个文档向一个文档迁移节点时被引发。
@end deffn

DOM 建议映射中针对上述异常而定义的异常代码如下表所示:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常量

@tab

异常

@item

@code{DOMSTRING_SIZE_ERR}

@tab

@ref{2be1,,DomstringSizeErr}

@item

@code{HIERARCHY_REQUEST_ERR}

@tab

@ref{2be2,,HierarchyRequestErr}

@item

@code{INDEX_SIZE_ERR}

@tab

@ref{2be3,,IndexSizeErr}

@item

@code{INUSE_ATTRIBUTE_ERR}

@tab

@ref{2bcb,,InuseAttributeErr}

@item

@code{INVALID_ACCESS_ERR}

@tab

@ref{2be4,,InvalidAccessErr}

@item

@code{INVALID_CHARACTER_ERR}

@tab

@ref{2be5,,InvalidCharacterErr}

@item

@code{INVALID_MODIFICATION_ERR}

@tab

@ref{2be6,,InvalidModificationErr}

@item

@code{INVALID_STATE_ERR}

@tab

@ref{2be7,,InvalidStateErr}

@item

@code{NAMESPACE_ERR}

@tab

@ref{2be8,,NamespaceErr}

@item

@code{NOT_FOUND_ERR}

@tab

@ref{2bc6,,NotFoundErr}

@item

@code{NOT_SUPPORTED_ERR}

@tab

@ref{2be9,,NotSupportedErr}

@item

@code{NO_DATA_ALLOWED_ERR}

@tab

@ref{2bea,,NoDataAllowedErr}

@item

@code{NO_MODIFICATION_ALLOWED_ERR}

@tab

@ref{2beb,,NoModificationAllowedErr}

@item

@code{SYNTAX_ERR}

@tab

@ref{2bec,,SyntaxErr}

@item

@code{WRONG_DOCUMENT_ERR}

@tab

@ref{2bed,,WrongDocumentErr}

@end multitable


@node 一致性,,DOM 中的对象,xml dom --- 文档对象模型 API
@anchor{library/xml dom conformance}@anchor{2bee}@anchor{library/xml dom dom-conformance}@anchor{2b78}
@subsubsection 一致性


本节描述了 Python DOM API、W3C DOM 建议以及 Python 的 OMG IDL 映射之间的一致性要求和关系。

@menu
* 类型映射:: 
* 访问器方法:: 

@end menu

@node 类型映射,访问器方法,,一致性
@anchor{library/xml dom dom-type-mapping}@anchor{2bef}@anchor{library/xml dom type-mapping}@anchor{2bf0}
@subsubsection 类型映射


将根据下表，将DOM规范中使用的IDL类型映射为Python类型。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

IDL  类型

@tab

Python 类型

@item

@code{boolean}

@tab

@code{bool} 或 @code{int}

@item

@code{int}

@tab

@code{int}

@item

@code{long int}

@tab

@code{int}

@item

@code{unsigned int}

@tab

@code{int}

@item

@code{DOMString}

@tab

@code{str} 或 @code{bytes}

@item

@code{null}

@tab

@code{None}

@end multitable


@node 访问器方法,,类型映射,一致性
@anchor{library/xml dom accessor-methods}@anchor{2bf1}@anchor{library/xml dom dom-accessor-methods}@anchor{2bf2}
@subsubsection 访问器方法


从 OMG IDL 到 Python 的映射以类似于 Java 映射的方式定义了针对 IDL @code{attribute} 声明的访问器函数。 映射以下 IDL 声明

@example
readonly attribute string someValue;
         attribute string anotherValue;
@end example

会产生三个访问器函数:  @code{someValue} 的 "get" 方法 (@code{_get_someValue()})，以及 @code{anotherValue} 的 "get" 和 "set" 方法 (@code{_get_anotherValue()} 和 @code{_set_anotherValue()})。 特别地，该映射不要求 IDL 属性像普通 Python 属性那样可访问:  @code{object.someValue} @emph{并非} 必须可用，并可能引发 @ref{4aa,,AttributeError}。

但是，Python DOM API 则 @emph{确实} 要求普通属性访问可用。 这意味着由 Python IDL 解译器生成的典型代理有可能会不可用，如果 DOM 对象是通过 CORBA 来访问则在客户端可能需要有包装对象。 虽然这确实要求为 CORBA DOM 客户端进行额外的考虑，但具有从 Python 通过 CORBA 使用 DOM 经验的实现并不会认为这是个问题。 已经声明了 @code{readonly} 的属性不必在所有 DOM 实现中限制写入访问。

在 Python DOM API 中，访问器函数不是必须的。 如果提供，则它们应当采用由 Python IDL 映射所定义的形式，但这些方法会被认为不必要，因为这些属性可以从 Python 直接访问。 永远都不要为 @code{readonly} 属性提供 "set" 访问器。

IDL 定义没有完全体现 W3C DOM API 的要求，如特定对象的概念，又如 @code{getElementsByTagName()} 的返回值为 "live" 等。 Python DOM API 并不强制具体实现执行这些要求。

@node xml dom minidom --- 最小化的 DOM 实现,xml dom pulldom --- 支持构建部分 DOM 树,xml dom --- 文档对象模型 API,结构化标记处理工具
@anchor{library/xml dom minidom doc}@anchor{2bf3}@anchor{library/xml dom minidom module-xml dom minidom}@anchor{13e}@anchor{library/xml dom minidom xml-dom-minidom-minimal-dom-implementation}@anchor{2bf4}
@subsection @code{xml.dom.minidom} --- 最小化的 DOM 实现


@geindex xml.dom.minidom (模块)

@strong{源代码:} Lib/xml/dom/minidom.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/dom/minidom.py}


__________________________________________________________________


@ref{13e,,xml.dom.minidom} 是文档对象模型接口的最小化实现，具有与其他语言类似的 API。 它的目标是比完整 DOM 更简单并且更为小巧。 对于 DOM 还不十分熟悉的用户则应当考虑改用 @ref{140,,xml.etree.ElementTree} 模块来进行 XML 处理。

@cartouche
@quotation 警告 
@ref{13e,,xml.dom.minidom} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche

DOM 应用程序通常会从将某个 XML 解析为 DOM 开始。 使用 @ref{13e,,xml.dom.minidom} 时，这是通过各种解析函数来完成的:

@example
from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name

datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource)  # parse an open file

dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
@end example

@ref{2bf5,,parse()} 函数可接受一个文件名或者打开的文件对象。

@geindex parse() (在 xml.dom.minidom 模块中)
@anchor{library/xml dom minidom xml dom minidom parse}@anchor{2bf5}
@deffn {函数} xml.dom.minidom.parse (filename_or_file, parser=None, bufsize=None)

根据给定的输入返回一个 @code{Document}。 @emph{filename_or_file} 可以是一个文件名，或是一个文件类对象。 如果给定 @emph{parser} 则它必须是一个 SAX2 解析器对象。 此函数将修改解析器的处理程序并激活命名空间支持；其他解析器配置（例如设置一个实体求解器）必须已经提前完成。
@end deffn

如果你将 XML 存放为字符串形式，则可以改用 @ref{2bf6,,parseString()} 函数:

@geindex parseString() (在 xml.dom.minidom 模块中)
@anchor{library/xml dom minidom xml dom minidom parseString}@anchor{2bf6}
@deffn {函数} xml.dom.minidom.parseString (string, parser=None)

返回一个代表 @emph{string} 的 @code{Document}。 此方法会为指定字符串创建一个 @ref{924,,io.StringIO} 对象并将其传递给 @ref{2bf5,,parse()}。
@end deffn

两个函数均返回一个代表文档内容的 @code{Document} 对象。object representing the content of the document.

@ref{2bf5,,parse()} 和 @ref{2bf6,,parseString()} 函数所做的是将 XML 解析器连接到一个 "DOM 构建器"，它可以从任意 SAX 解析器接收解析事件并将其转换为 DOM 树结构。 这两个函数的名称可能有些误导性，但在学习此接口时是很容易掌握的。 文档解析操作将在这两个函数返回之前完成；简单地说这两个函数本身并不提供解析器实现。

你也可以通过在一个 "DOM 实现" 对象上调用方法来创建 @code{Document}。 此对象可通过调用 @ref{13d,,xml.dom} 包或者 @ref{13e,,xml.dom.minidom} 模块中的 @code{getDOMImplementation()} 函数来获取。 一旦你获得了一个 @code{Document}，你就可以向它添加子节点来填充 DOM:

@example
from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)
@end example

一旦你得到了 DOM 文档对象，你就可以通过其属性和方法访问对应 XML 文档的各个部分。 这些属性定义在 DOM 规格说明当中；文档对象的主要特征属性是 @code{documentElement}。 它给出了 XML 文档中的主元素：即包含了所有其他元素的元素。 以下是一个示例程序:

@example
dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"
@end example

当你完成对一个 DOM 树的处理时，你可以选择调用 @code{unlink()} 方法以鼓励尽早清除不再需要的对象。 @code{unlink()} 是 @ref{13e,,xml.dom.minidom} 针对 DOM API 的专属扩展，它会将特定节点及其下级标记为不再有用。 在其他情况下，Python 的垃圾回收器将负责最终处理树结构中的对象。


@subsubheading 参见



@table @asis

@item 文档对象模型 (DOM) 第 1 层级规格说明@footnote{https://www.w3.org/TR/REC-DOM-Level-1/}

被 @ref{13e,,xml.dom.minidom} 所支持的 W3C 针对 DOM 的建议。
@end table


@menu
* DOM 对象:: 
* DOM 示例:: 
* minidom 和 DOM 标准:: 

@end menu

@node DOM 对象,DOM 示例,,xml dom minidom --- 最小化的 DOM 实现
@anchor{library/xml dom minidom dom-objects}@anchor{2bf7}@anchor{library/xml dom minidom minidom-objects}@anchor{2bf8}
@subsubsection DOM 对象


Python 的 DOM API 定义被作为 @ref{13d,,xml.dom} 模块文档的一部分给出。  这一节列出了该 API 和 @ref{13e,,xml.dom.minidom} 之间的差异。

@geindex unlink() (xml.dom.minidom.Node 方法)
@anchor{library/xml dom minidom xml dom minidom Node unlink}@anchor{2bf9}
@deffn {方法} Node.unlink ()

破坏 DOM 的内部引用以便它能在没有循环 GC 的 Python 版本上垃圾回收器回收。 即使在循环 GC 可用的时候，使用此方法也可让大量内存更快变为可用，因此当 DOM 对象不再被需要时尽早调用它们的这个方法是很好的做法。 此方法只须在 @code{Document} 对象上调用，但也可以在下级节点上调用以丢弃该节点的下级节点。

你可以通过使用 @ref{7e4,,with} 语句来避免显式调用此方法。 以下代码会在 @code{with} 代码块退出时自动取消链接 @emph{dom}:

@example
with xml.dom.minidom.parse(datasource) as dom:
    ... # Work with dom.
@end example
@end deffn

@geindex writexml() (xml.dom.minidom.Node 方法)
@anchor{library/xml dom minidom xml dom minidom Node writexml}@anchor{2bfa}
@deffn {方法} Node.writexml (writer, indent="", addindent="", newl="", encoding=None, standalone=None)

将 XML 写入到写入器对象。 写入器接受文本而非字节串作为输入，它应当具有与文件对象接口相匹配的 @code{write()} 方法。 @emph{indent} 形参是当前节点的缩进层级。 @emph{addindent} 形参是用于当前节点的下级节点的缩进量。 @emph{newl} 形参指定用于一行结束的字符串。

对于 @code{Document} 节点，可以使用附加的关键字参数 @emph{encoding} 来指定 XML 标头的编码格式字段。

类似地，显式指明 @emph{standalone} 参数将会使单独的文档声明被添加到 XML 文档的开头部分。 如果将该值设为 @cite{True}，则会添加 @cite{standalone="yes"}，否则将为 @cite{"no"}。 未指明该参数将使文档声明被省略。


在 3.8 版更改: @ref{2bfa,,writexml()} 方法现在会保留用户指定的属性顺序。



在 3.9 版更改: 增加了 @emph{standalone} 形参。

@end deffn

@geindex toxml() (xml.dom.minidom.Node 方法)
@anchor{library/xml dom minidom xml dom minidom Node toxml}@anchor{2bfb}
@deffn {方法} Node.toxml (encoding=None, standalone=None)

返回一个包含 XML DOM 节点所代表的 XML 的字符串或字节串。

带有显式的 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式名称应当遵循适当的标准。 例如，"UTF-8" 是有效的，但 "UTF8" 在 XML 文档的声明中是无效的，即使 Python 接受其作为编码格式名称。 详情参见 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} 参数时，结果为使用指定编码格式的字节串。 没有 @emph{encoding} 参数时，结果为 Unicode 字符串，并且结果字符串中的 XML 声明将不指定编码格式。 使用 UTF-8 以外的编码格式对此字符串进行编码通常是不正确的，因为 UTF-8 是 XML 的默认编码格式。

@emph{standalone} 参数的行为与 @ref{2bfa,,writexml()} 中的完全一致。


在 3.8 版更改: @ref{2bfb,,toxml()} 方法现在会保留用户指定的属性顺序。



在 3.9 版更改: 增加了 @emph{standalone} 形参。

@end deffn

@geindex toprettyxml() (xml.dom.minidom.Node 方法)
@anchor{library/xml dom minidom xml dom minidom Node toprettyxml}@anchor{2bfc}
@deffn {方法} Node.toprettyxml (indent="\t", newl="\n", encoding=None, standalone=None)

返回文档的美化打印版本。 @emph{indent} 指定缩进字符串并默认为制表符；@emph{newl} 指定标示每行结束的字符串并默认为 @code{\n}。

@emph{encoding} 参数的行为类似于 @ref{2bfb,,toxml()} 的对应参数。

@emph{standalone} 参数的行为与 @ref{2bfa,,writexml()} 中的完全一致。


在 3.8 版更改: @ref{2bfc,,toprettyxml()} 方法现在会保留用户指定的属性顺序。



在 3.9 版更改: 增加了 @emph{standalone} 形参。

@end deffn

@node DOM 示例,minidom 和 DOM 标准,DOM 对象,xml dom minidom --- 最小化的 DOM 实现
@anchor{library/xml dom minidom dom-example}@anchor{2bfd}@anchor{library/xml dom minidom id2}@anchor{2bfe}
@subsubsection DOM 示例


此示例程序是个相当实际的简单程序示例。 在这个特定情况中，我们没有过多地利用 DOM 的灵活性。

@example
import xml.dom.minidom

document = """\
<slideshow>
<title>Demo slideshow</title>
<slide><title>Slide title</title>
<point>This is a demo</point>
<point>Of a program for processing slides</point>
</slide>

<slide><title>Another demo slide</title>
<point>It is important</point>
<point>To have more than</point>
<point>one slide</point>
</slide>
</slideshow>
"""

dom = xml.dom.minidom.parseString(document)

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return '@w{'}.join(rc)

def handleSlideshow(slideshow):
    print("<html>")
    handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
    slides = slideshow.getElementsByTagName("slide")
    handleToc(slides)
    handleSlides(slides)
    print("</html>")

def handleSlides(slides):
    for slide in slides:
        handleSlide(slide)

def handleSlide(slide):
    handleSlideTitle(slide.getElementsByTagName("title")[0])
    handlePoints(slide.getElementsByTagName("point"))

def handleSlideshowTitle(title):
    print("<title>%s</title>" % getText(title.childNodes))

def handleSlideTitle(title):
    print("<h2>%s</h2>" % getText(title.childNodes))

def handlePoints(points):
    print("<ul>")
    for point in points:
        handlePoint(point)
    print("</ul>")

def handlePoint(point):
    print("<li>%s</li>" % getText(point.childNodes))

def handleToc(slides):
    for slide in slides:
        title = slide.getElementsByTagName("title")[0]
        print("<p>%s</p>" % getText(title.childNodes))

handleSlideshow(dom)
@end example

@node minidom 和 DOM 标准,,DOM 示例,xml dom minidom --- 最小化的 DOM 实现
@anchor{library/xml dom minidom minidom-and-dom}@anchor{2bff}@anchor{library/xml dom minidom minidom-and-the-dom-standard}@anchor{2c00}
@subsubsection minidom 和 DOM 标准


@ref{13e,,xml.dom.minidom} 模块实际上是兼容 DOM 1.0 的 DOM 并带有部分 DOM 2 特性（主要是命名空间特性）。

Python 中 DOM 接口的用法十分直观。 会应用下列映射规则:


@itemize *

@item 
接口是通过实例对象来访问的。 应用程序不应实例化这些类本身；它们应当使用 @code{Document} 对象提供的创建器函数。 派生的接口支持上级接口的所有操作（和属性），并添加了新的操作。

@item 
操作以方法的形式使用。 因由 DOM 只使用 @ref{179,,in} 形参，参数是以正常顺序传入的（从左至右）。 不存在可选参数。 @code{void} 操作返回 @code{None}。

@item 
IDL 属性会映射到实例属性。 为了兼容针对 Python 的 OMG IDL 语言映射，属性 @code{foo} 也可通过访问器方法 @code{_get_foo()} 和 @code{_set_foo()} 来访问。 @code{readonly} 属性不可被修改；运行时并不强制要求这一点。

@item 
@code{short int}, @code{unsigned int}, @code{unsigned long long} 和 @code{boolean} 类型都会映射为 Python 整数类型。

@item 
@code{DOMString} 类型会映射为 Python 字符串。 @ref{13e,,xml.dom.minidom} 支持字节串或字符串，但通常是产生字符串。 @code{DOMString} 类型的值也可以为 @code{None}，W3C 的 DOM 规格说明允许其具有 IDL @code{null} 值。

@item 
@code{const} 声明会映射为它们各自的作用域内的变量 (例如 @code{xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE})；它们不可被修改。

@item 
@code{DOMException} 目前不被 @ref{13e,,xml.dom.minidom} 所支持。 @ref{13e,,xml.dom.minidom} 会改为使用标准 Python 异常例如 @ref{1ff,,TypeError} 和 @ref{4aa,,AttributeError}。

@item 
@code{NodeList} 对象是使用 Python 内置列表类型来实现的。 这些对象提供了 DOM 规格说明中定义的接口，但在较早版本的 Python 中它们不支持官方 API。 相比在 W3C 建议中定义的接口，它们要更加的 "Pythonic"。
@end itemize

下列接口未在 @ref{13e,,xml.dom.minidom} 中实现:


@itemize *

@item 
@code{DOMTimeStamp}

@item 
@code{EntityReference}
@end itemize

这些接口所反映的 XML 文档信息对于大多数 DOM 用户来说没有什么帮助。

@node xml dom pulldom --- 支持构建部分 DOM 树,xml sax --- 支持 SAX2 解析器,xml dom minidom --- 最小化的 DOM 实现,结构化标记处理工具
@anchor{library/xml dom pulldom doc}@anchor{2c01}@anchor{library/xml dom pulldom module-xml dom pulldom}@anchor{13f}@anchor{library/xml dom pulldom xml-dom-pulldom-support-for-building-partial-dom-trees}@anchor{2c02}
@subsection @code{xml.dom.pulldom} --- 支持构建部分 DOM 树


@geindex xml.dom.pulldom (模块)

@strong{源代码:} Lib/xml/dom/pulldom.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/dom/pulldom.py}


__________________________________________________________________


@ref{13f,,xml.dom.pulldom} 模块提供了一个“拉取解析器”，它能在必要时被用于产生文件的可访问 DOM 的片段。 其基本概念包括从输入的 XML 流拉取“事件”并处理它们。 与同样地同时应用了事件驱动处理模型加回调函数的 SAX 不同，拉取解析器的用户要负责显式地从流拉取事件，并循环遍历这些事件直到处理结束或者发生了错误条件。

@cartouche
@quotation 警告 
@ref{13f,,xml.dom.pulldom} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche


在 3.7.1 版更改: SAX 解析器默认不再处理一般外部实体以提升在默认情况下的安全性。 要启用外部实体处理，请传入一个自定义的解析器实例:

@example
from xml.dom.pulldom import parse
from xml.sax import make_parser
from xml.sax.handler import feature_external_ges

parser = make_parser()
parser.setFeature(feature_external_ges, True)
parse(filename, parser=parser)
@end example


示例:

@example
from xml.dom import pulldom

doc = pulldom.parse('sales_items.xml')
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'item':
        if int(node.getAttribute('price')) > 50:
            doc.expandNode(node)
            print(node.toxml())
@end example

@code{event} 是一个常量，可以取下列值之一:


@itemize *

@item 
@code{START_ELEMENT}

@item 
@code{END_ELEMENT}

@item 
@code{COMMENT}

@item 
@code{START_DOCUMENT}

@item 
@code{END_DOCUMENT}

@item 
@code{CHARACTERS}

@item 
@code{PROCESSING_INSTRUCTION}

@item 
@code{IGNORABLE_WHITESPACE}
@end itemize

@code{node} 是一个 @code{xml.dom.minidom.Document}, @code{xml.dom.minidom.Element} 或 @code{xml.dom.minidom.Text} 类型的对象。

由于文档是被当作“展平”的事件流来处理的，文档“树”会被隐式地遍历并且无论所需元素在树中的深度如何都会被找到。 换句话说，不需要考虑层级问题，例如文档节点的递归搜索等，但是如果元素的内容很重要，则有必要保留一些上下文相关的状态（例如记住任意给定点在文档中的位置）或者使用 @ref{2c03,,DOMEventStream.expandNode()} 方法并切换到 DOM 相关的处理过程。

@geindex PullDom (xml.dom.pulldom 中的类)
@anchor{library/xml dom pulldom xml dom pulldom PullDom}@anchor{2c04}
@deffn {类} xml.dom.pulldom.PullDom (documentFactory=None)

@ref{2c05,,xml.sax.handler.ContentHandler} 的子类。
@end deffn

@geindex SAX2DOM (xml.dom.pulldom 中的类)
@anchor{library/xml dom pulldom xml dom pulldom SAX2DOM}@anchor{2c06}
@deffn {类} xml.dom.pulldom.SAX2DOM (documentFactory=None)

@ref{2c05,,xml.sax.handler.ContentHandler} 的子类。
@end deffn

@geindex parse() (在 xml.dom.pulldom 模块中)
@anchor{library/xml dom pulldom xml dom pulldom parse}@anchor{2c07}
@deffn {函数} xml.dom.pulldom.parse (stream_or_string, parser=None, bufsize=None)

基于给定的输入返回一个 @ref{3aa,,DOMEventStream}。 @emph{stream_or_string} 可以是一个文件名，或是一个文件类对象。 @emph{parser} 如果给出，则必须是一个 @ref{2c08,,XMLReader} 对象。 此函数将改变解析器的文档处理程序并激活命名空间支持；其他解析器配置（例如设置实体解析器）必须在之前已完成。
@end deffn

如果你将 XML 存放为字符串，则可以改用 @ref{2c09,,parseString()} 函数:

@geindex parseString() (在 xml.dom.pulldom 模块中)
@anchor{library/xml dom pulldom xml dom pulldom parseString}@anchor{2c09}
@deffn {函数} xml.dom.pulldom.parseString (string, parser=None)

返回一个 @ref{3aa,,DOMEventStream} 来表示 (Unicode) @emph{string}。
@end deffn

@geindex default_bufsize() (在 xml.dom.pulldom 模块中)
@anchor{library/xml dom pulldom xml dom pulldom default_bufsize}@anchor{2c0a}
@deffn {数据} xml.dom.pulldom.default_bufsize

将 @emph{bufsize} 形参的默认值设为 @ref{2c07,,parse()}。

此变量的值可在调用 @ref{2c07,,parse()} 之前修改并使新值生效。
@end deffn

@menu
* DOMEventStream 对象:: 

@end menu

@node DOMEventStream 对象,,,xml dom pulldom --- 支持构建部分 DOM 树
@anchor{library/xml dom pulldom domeventstream-objects}@anchor{2c0b}@anchor{library/xml dom pulldom id1}@anchor{2c0c}
@subsubsection DOMEventStream 对象


@geindex DOMEventStream (xml.dom.pulldom 中的类)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream}@anchor{3aa}
@deffn {类} xml.dom.pulldom.DOMEventStream (stream, parser, bufsize)


3.8 版后已移除: 对 @ref{3ad,,序列协议} 的支持已被弃用。


@geindex getEvent() (xml.dom.pulldom.DOMEventStream 方法)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream getEvent}@anchor{2c0d}
@deffn {方法} getEvent ()

返回一个元组，其中包含 @emph{event} 和 @code{xml.dom.minidom.Document} 形式的当前 @emph{node} 如果 event 等于 @code{START_DOCUMENT}，包含 @code{xml.dom.minidom.Element} 如果 event 等于 @code{START_ELEMENT} 或 @code{END_ELEMENT} 或者 @code{xml.dom.minidom.Text} 如果 event 等于 @code{CHARACTERS}。 当前 node 不包含有关其子节点的信息，除非 @ref{2c03,,expandNode()} 被调用。
@end deffn

@geindex expandNode() (xml.dom.pulldom.DOMEventStream 方法)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream expandNode}@anchor{2c03}
@deffn {方法} expandNode (node)

将 @emph{node} 的所有子节点扩展到 @emph{node} 中。 例如:

@example
from xml.dom import pulldom

xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>'
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '<p/>'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '<p>Some text <div>and more</div></p>'
        print(node.toxml())
@end example
@end deffn

@geindex reset() (xml.dom.pulldom.DOMEventStream 方法)
@anchor{library/xml dom pulldom xml dom pulldom DOMEventStream reset}@anchor{2c0e}
@deffn {方法} reset ()
@end deffn
@end deffn

@node xml sax --- 支持 SAX2 解析器,xml sax handler --- SAX 处理句柄的基类,xml dom pulldom --- 支持构建部分 DOM 树,结构化标记处理工具
@anchor{library/xml sax doc}@anchor{2c0f}@anchor{library/xml sax module-xml sax}@anchor{144}@anchor{library/xml sax xml-sax-support-for-sax2-parsers}@anchor{2c10}
@subsection @code{xml.sax} --- 支持 SAX2 解析器


@geindex xml.sax (模块)

@strong{源代码:} Lib/xml/sax/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/sax/__init__.py}


__________________________________________________________________


@ref{144,,xml.sax} 包提供多个模块，它们在 Python 上实现了用于 XML (SAX)  接口的简单 API。 这个包本身为  SAX API 用户提供了一些最常用的 SAX 异常和便捷函数。

@cartouche
@quotation 警告 
@ref{144,,xml.sax} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche


在 3.7.1 版更改: SAX 解析器默认不会再处理通用外部实体以便提升安全性。 在此之前，解析器会创建网络连接来获取远程文件或是从 DTD 和实体文件系统中加载本地文件。 此特性可通过在解析器对象上调用 @ref{2c11,,setFeature()} 对象并传入参数 @ref{2c12,,feature_external_ges} 来重新启用。


可用的便捷函数如下所列:

@geindex make_parser() (在 xml.sax 模块中)
@anchor{library/xml sax xml sax make_parser}@anchor{11a8}
@deffn {函数} xml.sax.make_parser (parser_list=[])

创建并返回一个 SAX @ref{2c08,,XMLReader} 对象。 将返回第一个被找到的解析器。 如果提供了 @emph{parser_list}，它必须为一个包含字符串的可迭代对象，这些字符串指定了具有名为 @code{create_parser()} 函数的模块。 在 @emph{parser_list} 中列出的模块将在默认解析器列表中的模块之前被使用。


在 3.8 版更改: @emph{parser_list} 参数可以是任意可迭代对象，而不一定是列表。

@end deffn

@geindex parse() (在 xml.sax 模块中)
@anchor{library/xml sax xml sax parse}@anchor{1165}
@deffn {函数} xml.sax.parse (filename_or_stream, handler, error_handler=handler.ErrorHandler())

创建一个 SAX 解析器并用它来解析文档。 用于传入文档的 @emph{filename_or_stream} 可以是一个文件名或文件对象。 @emph{handler} 形参必须是一个 SAX @ref{2c05,,ContentHandler} 实例。 如果给出了 @emph{error_handler}，则它必须是一个 SAX @ref{2c13,,ErrorHandler} 实例；如果省略，则对于任何错误都将引发  @ref{2c14,,SAXParseException}。 此函数没有返回值；所有操作必须由传入的 @emph{handler} 来完成。
@end deffn

@geindex parseString() (在 xml.sax 模块中)
@anchor{library/xml sax xml sax parseString}@anchor{88c}
@deffn {函数} xml.sax.parseString (string, handler, error_handler=handler.ErrorHandler())

类似于 @ref{1165,,parse()}，但解析对象是作为形参传入的缓冲区 @emph{string}。 @emph{string} 必须为 @ref{206,,str} 实例或者 @ref{6e9,,bytes-like object}。


在 3.5 版更改: 增加了对 @ref{206,,str} 实例的支持。

@end deffn

典型的 SAX 应用程序会使用三种对象：读取器、处理句柄和输入源。 “读取器”在此上下文中与解析器同义，即某个从输入源读取字节或字符，并产生事件序列的代码段。 事件随后将被分发给处理句柄对象，即由读取器发起调用处理句柄上的某个方法。 因此 SAX 应用程序必须获取一个读取器对象，创建或打开输入源，创建处理句柄，并一起连接到这些对象。 作为准备工作的最后一步，将调用读取器来解析输入内容。 在解析过程中，会根据来自输入数据的结构化和语义化事件来调用处理句柄对象上的方法。

就这些对象而言，只有接口部分是需要关注的；它们通常不是由应用程序本身来实例化。 由于 Python 没有显式的接口标记法，它们的正式引入形式是类，但应用程序可能会使用并非从已提供的类继承而来的实现。 @ref{88b,,InputSource}, @ref{2c15,,Locator}, @code{Attributes}, @code{AttributesNS} 以及 @ref{2c08,,XMLReader} 接口是在 @ref{147,,xml.sax.xmlreader} 模块中定义的。 处理句柄接口是在 @ref{145,,xml.sax.handler} 中定义的。 为了方便起见，@ref{88b,,InputSource} (它往往会被直接实例化) 和处理句柄类也可以从 @ref{144,,xml.sax} 获得。 这些接口的描述见下文。

除了这些类，@ref{144,,xml.sax} 还提供了如下异常类。

@geindex SAXException
@anchor{library/xml sax xml sax SAXException}@anchor{2c16}
@deffn {例外} xml.sax.SAXException (msg, exception=None)

封装某个 XML 错误或警告。 这个类可以包含来自 XML 解析器或应用程序的基本错误或警告信息：它可以被子类化以提供额外的功能或是添加本地化信息。 请注意虽然在 @ref{2c13,,ErrorHandler} 接口中定义的处理句柄可以接收该异常的实例，但是并不要求实际引发该异常 --- 它也可以被用作信息的容器。

当实例化时，@emph{msg} 应当是适合人类阅读的错误描述。 如果给出了可选的 @emph{exception} 形参，它应当为 @code{None} 或者解析代码所捕获的异常并会被作为信息传递出去。

这是其他 SAX 异常类的基类。
@end deffn

@geindex SAXParseException
@anchor{library/xml sax xml sax SAXParseException}@anchor{2c14}
@deffn {例外} xml.sax.SAXParseException (msg, exception, locator)

@ref{2c16,,SAXException} 的子类，针对解析错误引发。 这个类的实例会被传递给 SAX @ref{2c13,,ErrorHandler} 接口的方法来提供关于解析错误的信息。 这个类支持 SAX @ref{2c15,,Locator} 接口以及 @ref{2c16,,SAXException} 接口。
@end deffn

@geindex SAXNotRecognizedException
@anchor{library/xml sax xml sax SAXNotRecognizedException}@anchor{2c17}
@deffn {例外} xml.sax.SAXNotRecognizedException (msg, exception=None)

@ref{2c16,,SAXException} 的子类，当 SAX @ref{2c08,,XMLReader} 遇到不可识别的特性或属性时引发。 SAX 应用程序和扩展可能会出于类似目的而使用这个类。
@end deffn

@geindex SAXNotSupportedException
@anchor{library/xml sax xml sax SAXNotSupportedException}@anchor{2c18}
@deffn {例外} xml.sax.SAXNotSupportedException (msg, exception=None)

@ref{2c16,,SAXException} 的子类，当 SAX @ref{2c08,,XMLReader} 被要求启用某个不受支持的特性，或者将某个属性设为具体实现不支持的值时引发。 SAX 应用程序和扩展可能会出于类似目的而使用这个类。
@end deffn


@subsubheading 参见



@table @asis

@item SAX: The Simple API for XML@footnote{http://www.saxproject.org/}

这个网站是 SAX API 定义的焦点。 它提供了一个 Java 实现以及在线文档。 还包括其他实现的链接和历史信息。

@item @ref{145,,xml.sax.handler} 模块

应用程序所提供对象的接口定义。

@item @ref{146,,xml.sax.saxutils} 模块

可在 SAX 应用程序中使用的便捷函数。

@item @ref{147,,xml.sax.xmlreader} 模块

解析器所提供对象的接口定义。
@end table


@menu
* SAXException 对象:: 

@end menu

@node SAXException 对象,,,xml sax --- 支持 SAX2 解析器
@anchor{library/xml sax sax-exception-objects}@anchor{2c19}@anchor{library/xml sax saxexception-objects}@anchor{2c1a}
@subsubsection SAXException 对象


@ref{2c16,,SAXException} 异常类支持下列方法:

@geindex getMessage() (xml.sax.SAXException 方法)
@anchor{library/xml sax xml sax SAXException getMessage}@anchor{2c1b}
@deffn {方法} SAXException.getMessage ()

返回描述错误条件的适合人类阅读的消息。
@end deffn

@geindex getException() (xml.sax.SAXException 方法)
@anchor{library/xml sax xml sax SAXException getException}@anchor{2c1c}
@deffn {方法} SAXException.getException ()

返回一个封装的异常对象或者 @code{None}。
@end deffn

@node xml sax handler --- SAX 处理句柄的基类,xml sax saxutils --- SAX 工具集,xml sax --- 支持 SAX2 解析器,结构化标记处理工具
@anchor{library/xml sax handler doc}@anchor{2c1d}@anchor{library/xml sax handler module-xml sax handler}@anchor{145}@anchor{library/xml sax handler xml-sax-handler-base-classes-for-sax-handlers}@anchor{2c1e}
@subsection @code{xml.sax.handler} --- SAX 处理句柄的基类


@geindex xml.sax.handler (模块)

@strong{源代码:} Lib/xml/sax/handler.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/sax/handler.py}


__________________________________________________________________


SAX API 定类了四种处理句柄：内容句柄、DTD 句柄、错误句柄以及实体解析器。 应用程序通常只需要实现他们感兴趣的事件对应的接口；他们可以在单个对象或多个对象中实现这些接口。 处理句柄的实现应当继承自在 @ref{145,,xml.sax.handler} 模块中提供的基类，以便所有方法都能获得默认的实现。

@geindex ContentHandler (xml.sax.handler 中的类)
@anchor{library/xml sax handler xml sax handler ContentHandler}@anchor{2c05}
@deffn {类} xml.sax.handler.ContentHandler

这是 SAX 中的主回调接口，也是对应用程序来说最重要的一个接口。 此接口中事件的顺序反映了文档中信息的顺序。
@end deffn

@geindex DTDHandler (xml.sax.handler 中的类)
@anchor{library/xml sax handler xml sax handler DTDHandler}@anchor{2c1f}
@deffn {类} xml.sax.handler.DTDHandler

处理 DTD 事件。

这个接口仅指定了基本解析（未解析的实体和属性）所需的那些 DTD 事件。
@end deffn

@geindex EntityResolver (xml.sax.handler 中的类)
@anchor{library/xml sax handler xml sax handler EntityResolver}@anchor{2c20}
@deffn {类} xml.sax.handler.EntityResolver

用于解析实体的基本接口。 如果你创建了实现此接口的对象，然后用你的解析器注册该对象，该解析器将调用你的对象中的方法来解析所有外部实体。
@end deffn

@geindex ErrorHandler (xml.sax.handler 中的类)
@anchor{library/xml sax handler xml sax handler ErrorHandler}@anchor{2c13}
@deffn {类} xml.sax.handler.ErrorHandler

解析器用来向应用程序表示错误和警告的接口。 这个对象的方法控制错误是要立即转换为异常还是以某种其他该来来处理。
@end deffn

除了这些类，@ref{145,,xml.sax.handler} 还提供了表示特性和属性名称的符号常量。

@geindex feature_namespaces() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_namespaces}@anchor{2c21}
@deffn {数据} xml.sax.handler.feature_namespaces


@display
值: @code{"http://xml.org/sax/features/namespaces"}@w{ }
true: 执行命名空间处理。@w{ }
false: 可选择不执行命名空间处理 (这意味着 namespace-prefixes; default)。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex feature_namespace_prefixes() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_namespace_prefixes}@anchor{2c22}
@deffn {数据} xml.sax.handler.feature_namespace_prefixes


@display
值: @code{"http://xml.org/sax/features/namespace-prefixes"}@w{ }
true: 报告原始的带前缀名称和用于命名空间声明的属性。@w{ }
false: 不报告用于命名空间声明的属性，可选择不报告原始的带前缀名称（默认）。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex feature_string_interning() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_string_interning}@anchor{2c23}
@deffn {数据} xml.sax.handler.feature_string_interning


@display
值: @code{"http://xml.org/sax/features/string-interning"}@w{ }
true: 所有元素名称、前缀、属性名称、命名空间 URI 以及本地名称都使用内置的 intern 函数进行内化。@w{ }
false: 名称不要求被内化，但也可以被内化（默认）。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex feature_validation() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_validation}@anchor{2c24}
@deffn {数据} xml.sax.handler.feature_validation


@display
值: @code{"http://xml.org/sax/features/validation"}@w{ }
true: 报告所有的验证错误（包括 external-general-entities 和 external-parameter-entities）。@w{ }
false: 不报告验证错误。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex feature_external_ges() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_external_ges}@anchor{2c12}
@deffn {数据} xml.sax.handler.feature_external_ges


@display
值: @code{"http://xml.org/sax/features/external-general-entities"}@w{ }
true: 包括所有的外部通用（文本）实体。@w{ }
false: 不包括外部通用实体。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex feature_external_pes() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler feature_external_pes}@anchor{2c25}
@deffn {数据} xml.sax.handler.feature_external_pes


@display
值: @code{"http://xml.org/sax/features/external-parameter-entities"}@w{ }
true: 包括所有的外部参数实体，也包括外部 DTD 子集。@w{ }
false: 不包括任何外部参数实体，也不包括外部 DTD 子集。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex all_features() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler all_features}@anchor{2c26}
@deffn {数据} xml.sax.handler.all_features

全部特性列表。
@end deffn

@geindex property_lexical_handler() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler property_lexical_handler}@anchor{2c27}
@deffn {数据} xml.sax.handler.property_lexical_handler


@display
值: @code{"http://xml.org/sax/properties/lexical-handler"}@w{ }
数据类型: xml.sax.sax2lib.LexicalHandler (在 Python 2 中不受支持)@w{ }
描述: 可选的扩展处理句柄，用于注释等词法事件。@w{ }
访问: 读/写@w{ }
@end display


@end deffn

@geindex property_declaration_handler() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler property_declaration_handler}@anchor{2c28}
@deffn {数据} xml.sax.handler.property_declaration_handler


@display
值: @code{"http://xml.org/sax/properties/declaration-handler"}@w{ }
数据类型: xml.sax.sax2lib.DeclHandler (在 Python 2 中不受支持)@w{ }
描述: 可选的扩展处理句柄，用于标注和未解析实体以外的 DTD 相关事件。@w{ }
访问: 读/写@w{ }
@end display


@end deffn

@geindex property_dom_node() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler property_dom_node}@anchor{2c29}
@deffn {数据} xml.sax.handler.property_dom_node


@display
值: @code{"http://xml.org/sax/properties/dom-node"}@w{ }
数据类型: org.w3c.dom.Node (在 Python 2 中不受支持)@w{ }
描述: 在解析时，如果这是一个 DOM 迭代器则为当前被访问的 DOM 节点；不在解析时，则将根 DOM 节点用于迭代。@w{ }
access: (解析) 只读; (不解析) 读/写@w{ }
@end display


@end deffn

@geindex property_xml_string() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler property_xml_string}@anchor{2c2a}
@deffn {数据} xml.sax.handler.property_xml_string


@display
值: @code{"http://xml.org/sax/properties/xml-string"}@w{ }
数据类型: Bytes@w{ }
描述: 作为当前事件来源的字符串字面值。@w{ }
访问: 只读@w{ }
@end display


@end deffn

@geindex all_properties() (在 xml.sax.handler 模块中)
@anchor{library/xml sax handler xml sax handler all_properties}@anchor{2c2b}
@deffn {数据} xml.sax.handler.all_properties

已知属性名称列表。
@end deffn

@menu
* ContentHandler 对象:: 
* DTDHandler 对象:: 
* EntityResolver 对象:: 
* ErrorHandler 对象:: 

@end menu

@node ContentHandler 对象,DTDHandler 对象,,xml sax handler --- SAX 处理句柄的基类
@anchor{library/xml sax handler content-handler-objects}@anchor{2c2c}@anchor{library/xml sax handler contenthandler-objects}@anchor{2c2d}
@subsubsection ContentHandler 对象


用户应当子类化 @ref{2c05,,ContentHandler} 来支持他们的应用程序。 以下方法会由解析器在输入文档的适当事件上调用:

@geindex setDocumentLocator() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler setDocumentLocator}@anchor{2c2e}
@deffn {方法} ContentHandler.setDocumentLocator (locator)

由解析器调用来给予应用程序一个定位器以确定文档事件来自何处。

强烈建议（虽然不是绝对的要求） SAX 解析器提供一个定位器：如果提供的话，它必须在发起调用 DocumentHandler 接口的任何其他方法之前通过发起调用此方法来提供定位器。

定位器允许应用程序确定任何文档相关事件的结束位置，即使解析器没有报告错误。 通常，应用程序将使用这些信息来报告它自己的错误（例如未匹配到应用程序业务规则的字符内容）。 定位器所返回的信息可能不足以与搜索引擎配合使用。

请注意定位器只有在发起调用此接口中的事件时才会返回正确的信息。 应用程序不应试图在其他任何时刻使用它。
@end deffn

@geindex startDocument() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler startDocument}@anchor{2c2f}
@deffn {方法} ContentHandler.startDocument ()

接收一个文档开始的通知。

SAX 解析器将只发起调用这个方法一次，并且会在调用这个接口或 DTDHandler 中的任何其他方法之前 (@ref{2c2e,,setDocumentLocator()} 除外)。
@end deffn

@geindex endDocument() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler endDocument}@anchor{2c30}
@deffn {方法} ContentHandler.endDocument ()

接收一个文档结束的通知。

SAX 解析器将只发起调用这个方法一次，并且它将是在解析过程中最后发起调用的方法。 解析器在（因不可恢复的错误）放弃解析或到达输入的终点之前不应发起调用这个方法。
@end deffn

@geindex startPrefixMapping() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler startPrefixMapping}@anchor{2c31}
@deffn {方法} ContentHandler.startPrefixMapping (prefix, uri)

开始一个前缀 URI 命名空间映射的范围。

来自此事件的信息对于一般命名空间处理来说是不必要的：当 @code{feature_namespaces} 特性被启用时（默认）SAX XML 读取器将自动为元素和属性名称替换前缀。

但是也存在一些情况，当应用程序需要在字符数据或属性值中使用前缀，而它们无法被安全地自动扩展；@ref{2c31,,startPrefixMapping()} 和 @ref{2c32,,endPrefixMapping()} 事件会向应用程序提供信息以便在这些上下文内部扩展前缀，如果有必要的话。

@c XXX This is not really the default, is it? MvL

请注意 @ref{2c31,,startPrefixMapping()} 和 @ref{2c32,,endPrefixMapping()} 事件并不保证能够相对彼此被正确地嵌套：所有 @ref{2c31,,startPrefixMapping()} 事件都将在对应的 @ref{2c33,,startElement()} 事件之前发生，而所有 @ref{2c32,,endPrefixMapping()} 事件都将在对应的 @ref{2c34,,endElement()} 事件之后发生，但它们的并不保证一致。
@end deffn

@geindex endPrefixMapping() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler endPrefixMapping}@anchor{2c32}
@deffn {方法} ContentHandler.endPrefixMapping (prefix)

结束一个前缀 URI 映射的范围。

请参看 @ref{2c31,,startPrefixMapping()} 了解详情。 此事件将总是会在对应的 @ref{2c34,,endElement()} 事件之后发生，但 @ref{2c32,,endPrefixMapping()} 事件的顺序则并没有保证。
@end deffn

@geindex startElement() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler startElement}@anchor{2c33}
@deffn {方法} ContentHandler.startElement (name, attrs)

在非命令空间模式下指示一个元素的开始。

@emph{name} 形参包含字符串形式的元素类型原始 XML 1.0 名称而 @emph{attrs} 形参存放包含元素属性的 @code{Attributes} 接口对象 (参见 @ref{2c35,,Attributes 接口})。 作为 @emph{attrs} 传入的对象可能被解析器所重用；维持一个对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请使用 @emph{attrs} 对象的 @ref{25,,copy()} 方法。
@end deffn

@geindex endElement() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler endElement}@anchor{2c34}
@deffn {方法} ContentHandler.endElement (name)

在非命名空间模式下指示一个元素的结束。

@emph{name} 形参包含元素类型的名称，与 @ref{2c33,,startElement()} 事件的一样。
@end deffn

@geindex startElementNS() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler startElementNS}@anchor{2c36}
@deffn {方法} ContentHandler.startElementNS (name, qname, attrs)

在命名空间模式下指示一个元素的开始。

@emph{name} 形参包含以 @code{(uri, localname)} 元组表示的元素类型名称，@emph{qname} 形参包含源文档中使用的原始 XML 1.0 名称，而 @emph{attrs} 形参存放包含元素属性的 @code{AttributesNS} 接口实例 (参见 @ref{2c37,,AttributesNS 接口})。 如果没有命名空间被关联到元素，则 @emph{name} 的 @emph{uri} 部分将为 @code{None}。 作为 @emph{attrs} 传入的对象可能被解析器所重用；维持一个对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请使用 @emph{attrs} 对象的 @ref{25,,copy()} 方法。

解析器可将 @emph{qname} 形参设为 @code{None}，除非 @code{feature_namespace_prefixes} 特性已被激活。
@end deffn

@geindex endElementNS() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler endElementNS}@anchor{2c38}
@deffn {方法} ContentHandler.endElementNS (name, qname)

在命名空间模式下指示一个元素的结束。

@emph{name} 形参包含元素类型的名称，与 @ref{2c36,,startElementNS()} 方法的一样，@emph{qname} 形参也是类似的。
@end deffn

@geindex characters() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler characters}@anchor{2c39}
@deffn {方法} ContentHandler.characters (content)

接收字符数据的通知。

解析器将调用此方法来报告每一个字符数据分块。 SAX 解析器可以将所有连续字符数据返回为一个单独分块，或者将其拆成几个分块；但是，在任意单个事件中的所有字符都必须来自同一个外部实体以便定位器提供有用的信息。

@emph{content} 可以是一个字符串或字节串实例；@code{expat} 读取器模块总是会产生字符串。

@cartouche
@quotation 注解 
Python XML 特别关注小组所提供的早期 SAX 1 接口针对此方法使用了一个更类似于 Java 的接口。 由于 Python 所使用的大多数解析器都没有利用老式的接口，因而选择了更简单的签名来替代它。 要将旧代码转换为新接口，请使用 @emph{content} 而不要通过旧的 @emph{offset} 和 @emph{length} 形参来对内容进行切片。
@end quotation
@end cartouche
@end deffn

@geindex ignorableWhitespace() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler ignorableWhitespace}@anchor{2c3a}
@deffn {方法} ContentHandler.ignorableWhitespace (whitespace)

接收元素内容中可忽略空白符的通知。

验证解析器必须使用此方法来报告每个可忽略的空白符分块（参见 W3C XML 1.0 建议第 2.10 节）：非验证解析器如果能够解析并使用内容模型的话也可以使用此方法。

SAX 解析器可以将所有连续字符数据返回为一个单独分块，或者将其拆成几个分块；但是，在任意单个事件中的所有字符都必须来自同一个外部实体以便定位器提供有用的信息。
@end deffn

@geindex processingInstruction() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler processingInstruction}@anchor{2c3b}
@deffn {方法} ContentHandler.processingInstruction (target, data)

接受一条处理指令的通知。

解析器将为已找到的每条处理指令发起调用该方法一次：请注意处理指令可能出现在主文档元素之前或之后。

SAX 解析器绝不应当使用此方法来报告 XML 声明（XML 1.0 第 2.8 节）或文本声明（XML 1.0 第 4.3.1 节）。
@end deffn

@geindex skippedEntity() (xml.sax.handler.ContentHandler 方法)
@anchor{library/xml sax handler xml sax handler ContentHandler skippedEntity}@anchor{2c3c}
@deffn {方法} ContentHandler.skippedEntity (name)

接收一个已跳过实体的通知。

解析器将为每个已跳过实体发起调用此方法一次。 非验证处理程序可能会跳过未看到声明的实体（例如，由于实体是在一个外部because, for example, the entity was declared in an external DTD 子集中声明的）。 所有处理程序都可以跳过外部实体，具体取决于 @code{feature_external_ges} 和 @code{feature_external_pes} 属性的值。
@end deffn

@node DTDHandler 对象,EntityResolver 对象,ContentHandler 对象,xml sax handler --- SAX 处理句柄的基类
@anchor{library/xml sax handler dtd-handler-objects}@anchor{2c3d}@anchor{library/xml sax handler dtdhandler-objects}@anchor{2c3e}
@subsubsection DTDHandler 对象


@ref{2c1f,,DTDHandler} 实例提供了下列方法:

@geindex notationDecl() (xml.sax.handler.DTDHandler 方法)
@anchor{library/xml sax handler xml sax handler DTDHandler notationDecl}@anchor{2c3f}
@deffn {方法} DTDHandler.notationDecl (name, publicId, systemId)

处理标注声明事件。
@end deffn

@geindex unparsedEntityDecl() (xml.sax.handler.DTDHandler 方法)
@anchor{library/xml sax handler xml sax handler DTDHandler unparsedEntityDecl}@anchor{2c40}
@deffn {方法} DTDHandler.unparsedEntityDecl (name, publicId, systemId, ndata)

处理未解析的实体声明事件。
@end deffn

@node EntityResolver 对象,ErrorHandler 对象,DTDHandler 对象,xml sax handler --- SAX 处理句柄的基类
@anchor{library/xml sax handler entity-resolver-objects}@anchor{2c41}@anchor{library/xml sax handler entityresolver-objects}@anchor{2c42}
@subsubsection EntityResolver 对象


@geindex resolveEntity() (xml.sax.handler.EntityResolver 方法)
@anchor{library/xml sax handler xml sax handler EntityResolver resolveEntity}@anchor{2c43}
@deffn {方法} EntityResolver.resolveEntity (publicId, systemId)

求解一个实体的系统标识符并返回一个字符串形式的系统标识符作为读取源，或是一个 InputSource 作为读取源。  默认的实现会返回 @emph{systemId}。
@end deffn

@node ErrorHandler 对象,,EntityResolver 对象,xml sax handler --- SAX 处理句柄的基类
@anchor{library/xml sax handler errorhandler-objects}@anchor{2c44}@anchor{library/xml sax handler sax-error-handler}@anchor{2c45}
@subsubsection ErrorHandler 对象


带有这个接口的对象被用于接收来自 @ref{2c08,,XMLReader} 的错误和警告信息。 如果你创建了一个实现这个接口的对象，然后用你的 @ref{2c08,,XMLReader} 注册这个对象，则解析器将调用你的对象中的这个方法来报告所有的警告和错误。 有三个可用的错误级别：警告、（或许）可恢复的错误和不可恢复的错误。 所有方法都接受 @code{SAXParseException} 作为唯一的形参。 错误和警告可以通过引发所传入的异常对象来转换为异常。

@geindex error() (xml.sax.handler.ErrorHandler 方法)
@anchor{library/xml sax handler xml sax handler ErrorHandler error}@anchor{2c46}
@deffn {方法} ErrorHandler.error (exception)

当解析器遇到一个可恢复的错误时调用。 如果此方法没有引发异常，则解析可能会继续，但是应用程序不能预期获得更多的文档信息。 允许解析器继续可能会允许在输入文档中发现额外的错误。
@end deffn

@geindex fatalError() (xml.sax.handler.ErrorHandler 方法)
@anchor{library/xml sax handler xml sax handler ErrorHandler fatalError}@anchor{2c47}
@deffn {方法} ErrorHandler.fatalError (exception)

当解析器遇到一个不可恢复的错误时调用；在此方法返回时解析应当终止。
@end deffn

@geindex warning() (xml.sax.handler.ErrorHandler 方法)
@anchor{library/xml sax handler xml sax handler ErrorHandler warning}@anchor{2c48}
@deffn {方法} ErrorHandler.warning (exception)

当解析器向应用程序提供次要警告信息时调用。 在此方法返回时解析应当继续，并且文档信息将继续被传递给应用程序。 在此方法中引发异常将导致解析结束。
@end deffn

@node xml sax saxutils --- SAX 工具集,xml sax xmlreader --- 用于 XML 解析器的接口,xml sax handler --- SAX 处理句柄的基类,结构化标记处理工具
@anchor{library/xml sax utils doc}@anchor{2c49}@anchor{library/xml sax utils module-xml sax saxutils}@anchor{146}@anchor{library/xml sax utils xml-sax-saxutils-sax-utilities}@anchor{2c4a}
@subsection @code{xml.sax.saxutils} --- SAX 工具集


@geindex xml.sax.saxutils (模块)

@strong{源代码:} Lib/xml/sax/saxutils.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/sax/saxutils.py}


__________________________________________________________________


@ref{146,,xml.sax.saxutils} 模块包含一些在创建 SAX 应用程序时十分有用的类和函数，它们可以被直接使用，或者是作为基类使用。

@geindex escape() (在 xml.sax.saxutils 模块中)
@anchor{library/xml sax utils xml sax saxutils escape}@anchor{2c4b}
@deffn {函数} xml.sax.saxutils.escape (data, entities=@{@})

对数据字符串中的 @code{'&'}, @code{'<'} 和 @code{'>'} 进行转义。

你可以通过传入一个字典作为可选的 @emph{entities} 形参来对其他字符串数据进行转义。 字典的键和值必须为字符串；每个键将被替换为其所对应的值。 字符 @code{'&'}, @code{'<'} 和 @code{'>'} 总是会被转义，即使提供了 @emph{entities}。
@end deffn

@geindex unescape() (在 xml.sax.saxutils 模块中)
@anchor{library/xml sax utils xml sax saxutils unescape}@anchor{2c4c}
@deffn {函数} xml.sax.saxutils.unescape (data, entities=@{@})

对字符串数据中的 @code{'&amp;'}, @code{'&lt;'} 和 @code{'&gt;'} 进行反转义。

你可以通过传入一个字典作为可选的 @emph{entities} 形参来对其他数据字符串进行转义。 字典的键和值必须都为字符串；每个键将被替换为所对应的值。 @code{'&amp'}, @code{'&lt;'} 和 @code{'&gt;'} 将总是保持不被转义，即使提供了 @emph{entities}。
@end deffn

@geindex quoteattr() (在 xml.sax.saxutils 模块中)
@anchor{library/xml sax utils xml sax saxutils quoteattr}@anchor{2c4d}
@deffn {函数} xml.sax.saxutils.quoteattr (data, entities=@{@})

类似于 @ref{2c4b,,escape()}，但还会对 @emph{data} 进行处理以将其用作属性值。 返回值是 @emph{data} 加上任何额外要求的替换的带引号版本。@ref{2c4d,,quoteattr()} 将基于 @emph{data} 的内容选择一个引号字符，以尽量避免在字符串中编码任何引号字符。 如果单双引号字符在 @emph{data} 中都存在，则双引号字符将被编码并且 @emph{data} 将使用双引号来标记。 结果字符串可被直接用作属性值:

@example
>>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef">
@end example

此函数适用于为 HTML 或任何使用引用实体语法的 SGML 生成属性值。
@end deffn

@geindex XMLGenerator (xml.sax.saxutils 中的类)
@anchor{library/xml sax utils xml sax saxutils XMLGenerator}@anchor{2c4e}
@deffn {类} xml.sax.saxutils.XMLGenerator (out=None, encoding='iso-8859-1', short_empty_elements=False)

这个类通过将 SAX 事件写回到 XML 文档来实现 @ref{2c05,,ContentHandler} 接口。 换句话说，使用 @ref{2c4e,,XMLGenerator} 作为内容处理程序将重新产生所解析的原始文档。 @emph{out} 应当为一个文件类对象，它默认将为 @emph{sys.stdout}。 @emph{encoding} 为输出流的编码格式，它默认将为 @code{'iso-8859-1'}。 @emph{short_empty_elements} 控制不包含内容的元素的格式化：如为 @code{False} (默认值) 则它们会以开始/结束标记对的形式被发送，如果设为 @code{True} 则它们会以单个自结束标记的形式被发送。


3.2 新版功能: @emph{short_empty_elements} 形参。

@end deffn

@geindex XMLFilterBase (xml.sax.saxutils 中的类)
@anchor{library/xml sax utils xml sax saxutils XMLFilterBase}@anchor{2c4f}
@deffn {类} xml.sax.saxutils.XMLFilterBase (base)

这个类被设计用来分隔 @ref{2c08,,XMLReader} 和客户端应用的事件处理程序。 在默认情况下，它除了将请求传送给读取器并将事件传送给处理程序之外什么都不做，但其子类可以重载特定的方法以在传送它们的时候修改事件流或配置请求。
@end deffn

@geindex prepare_input_source() (在 xml.sax.saxutils 模块中)
@anchor{library/xml sax utils xml sax saxutils prepare_input_source}@anchor{2c50}
@deffn {函数} xml.sax.saxutils.prepare_input_source (source, base='@w{'})

此函数接受一个输入源和一个可选的基准 URL 并返回一个经过完整解析可供读取的 @ref{88b,,InputSource}。 输入源的给出形式可以为字符串、文件类对象或 @ref{88b,,InputSource} 对象；解析器将使用此函数来针对它们的 @code{parse()} 方法实现多态 @emph{source} 参数。
@end deffn

@node xml sax xmlreader --- 用于 XML 解析器的接口,xml parsers expat --- 使用 Expat 的快速 XML 解析,xml sax saxutils --- SAX 工具集,结构化标记处理工具
@anchor{library/xml sax reader doc}@anchor{2c51}@anchor{library/xml sax reader module-xml sax xmlreader}@anchor{147}@anchor{library/xml sax reader xml-sax-xmlreader-interface-for-xml-parsers}@anchor{2c52}
@subsection @code{xml.sax.xmlreader} --- 用于 XML 解析器的接口


@geindex xml.sax.xmlreader (模块)

@strong{源代码:} Lib/xml/sax/xmlreader.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xml/sax/xmlreader.py}


__________________________________________________________________


SAX 解析器实现了 @ref{2c08,,XMLReader} 接口。 它们是在一个 Python 模块中实现的，该模块必须提供一个 @code{create_parser()} 函数。 该函数由  @ref{11a8,,xml.sax.make_parser()} 不带参数地发起调用来创建新的解析器对象。

@geindex XMLReader (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader XMLReader}@anchor{2c08}
@deffn {类} xml.sax.xmlreader.XMLReader

可由 SAX 解析器继承的基类。
@end deffn

@geindex IncrementalParser (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser}@anchor{2c53}
@deffn {类} xml.sax.xmlreader.IncrementalParser

在某些情况下，最好不要一次性地解析输入源，而是在可用的时候分块送入。 请注意读取器通常不会读取整个文件，它同样也是分块读取的； 并且 @code{parse()} 在处理完整个文档之前不会返回。 所以如果不希望 @code{parse()} 出现阻塞行为则应当使用这些接口。

当解析器被实例化时它已准备好立即开始接受来自 feed 方法的数据。 在通过调用 close 方法结束解析时 reset 方法也必须被调用以使解析器准备好接受新的数据，无论它是来自于 feed 还是使用 parse 方法。

请注意这些方法 @emph{不可} 在解析期间被调用，即在 parse 被调用之后及其返回之前。

默认情况下，该类还使用 IncrementalParser 接口的 feed, close 和 reset 方法来实现 XMLReader 接口的 parse 方法以方便 SAX 2.0 驱动的编写者。
@end deffn

@geindex Locator (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader Locator}@anchor{2c15}
@deffn {类} xml.sax.xmlreader.Locator

用于关联一个 SAX 事件与一个文档位置的接口。 定位器对象只有在调用 DocumentHandler 的方法期间才会返回有效的结果；在其他任何时候，结果都是不可预测的。 如果信息不可用，这些方法可能返回 @code{None}。
@end deffn

@geindex InputSource (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader InputSource}@anchor{88b}
@deffn {类} xml.sax.xmlreader.InputSource (system_id=None)

@ref{2c08,,XMLReader} 读取实体所需信息的封装。

这个类可能包括了关于公有标识符、系统标识符、字节流（可能带有字符编码格式信息）和/或一个实体的字符流的信息。

应用程序将创建这个类的对象以便在 @ref{2c54,,XMLReader.parse()} 方法中使用或是用于从 EntityResolver.resolveEntity 返回值。

@ref{88b,,InputSource} 属于应用程序，@ref{2c08,,XMLReader} 不能修改从应用程序传递给它的 @ref{88b,,InputSource} 对象，但它可以创建副本并进行修改。
@end deffn

@geindex AttributesImpl (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader AttributesImpl}@anchor{2c55}
@deffn {类} xml.sax.xmlreader.AttributesImpl (attrs)

这是 @code{Attributes} 接口（参见 @ref{2c35,,Attributes 接口} 一节）的具体实现。 这是一个 @code{startElement()} 调用中的元素属性的字典类对象。 除了最有用处的字典操作，它还支持接口所描述的一些其他方法。 该类的对象应当由读取器来实例化；@emph{attrs} 必须为包含从属性名到属性值的映射的字典类对象。
@end deffn

@geindex AttributesNSImpl (xml.sax.xmlreader 中的类)
@anchor{library/xml sax reader xml sax xmlreader AttributesNSImpl}@anchor{2c56}
@deffn {类} xml.sax.xmlreader.AttributesNSImpl (attrs, qnames)

可感知命名空间的 @ref{2c55,,AttributesImpl} 变体形式，它将被传递给 @code{startElementNS()}。 它派生自 @ref{2c55,,AttributesImpl}，但会将属性名称解读为 @emph{namespaceURI} 和 @emph{localname} 二元组。 此外，它还提供了一些期望接收在原始文档中出现的限定名称的方法。 这个类实现了 @code{AttributesNS} 接口（参见 @ref{2c37,,AttributesNS 接口} 一节）。
@end deffn

@menu
* XMLReader 对象:: 
* IncrementalParser 对象:: 
* Locator 对象:: 
* InputSource 对象:: 
* Attributes 接口:: 
* AttributesNS 接口:: 

@end menu

@node XMLReader 对象,IncrementalParser 对象,,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader id1}@anchor{2c57}@anchor{library/xml sax reader xmlreader-objects}@anchor{2c58}
@subsubsection XMLReader 对象


@ref{2c08,,XMLReader} 接口支持下列方法:

@geindex parse() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader parse}@anchor{2c54}
@deffn {方法} XMLReader.parse (source)

处理输入源，产生 SAX 事件。 @emph{source} 对象可以是一个系统标识符（标识输入源的字符串 -- 通常为文件名或 URL）, @ref{336,,pathlib.Path} 或 @ref{47b,,路径类} 对象，或者是 @ref{88b,,InputSource} 对象。 当 @ref{2c54,,parse()} 返回时，输入会被全部处理完成，解析器对象可以被丢弃或重置。


在 3.5 版更改: 增加了对字符流的支持。



在 3.8 版更改: 增加了对路径类对象的支持。

@end deffn

@geindex getContentHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getContentHandler}@anchor{2c59}
@deffn {方法} XMLReader.getContentHandler ()

返回当前的 @ref{2c05,,ContentHandler}。
@end deffn

@geindex setContentHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setContentHandler}@anchor{2c5a}
@deffn {方法} XMLReader.setContentHandler (handler)

设置当前的 @ref{2c05,,ContentHandler}。 如果没有设置 @ref{2c05,,ContentHandler}，内容事件将被丢弃。
@end deffn

@geindex getDTDHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getDTDHandler}@anchor{2c5b}
@deffn {方法} XMLReader.getDTDHandler ()

返回当前的 @ref{2c1f,,DTDHandler}。
@end deffn

@geindex setDTDHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setDTDHandler}@anchor{2c5c}
@deffn {方法} XMLReader.setDTDHandler (handler)

设置当前的 @ref{2c1f,,DTDHandler}。 如果没有设置 @ref{2c1f,,DTDHandler}，DTD 事件将被德育。
@end deffn

@geindex getEntityResolver() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getEntityResolver}@anchor{2c5d}
@deffn {方法} XMLReader.getEntityResolver ()

返回当前的 @ref{2c20,,EntityResolver}。
@end deffn

@geindex setEntityResolver() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setEntityResolver}@anchor{2c5e}
@deffn {方法} XMLReader.setEntityResolver (handler)

设置当前的 @ref{2c20,,EntityResolver}。 如果没有设置 @ref{2c20,,EntityResolver}，尝试解析一个外部实体将导致打开该实体的系统标识符，并且如果它不可用则操作将失败。
@end deffn

@geindex getErrorHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getErrorHandler}@anchor{2c5f}
@deffn {方法} XMLReader.getErrorHandler ()

返回当前的 @ref{2c13,,ErrorHandler}。
@end deffn

@geindex setErrorHandler() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setErrorHandler}@anchor{2c60}
@deffn {方法} XMLReader.setErrorHandler (handler)

设置当前的错误处理句柄。 如果没有设置 @ref{2c13,,ErrorHandler}，错误将作为异常被引发，并将打印警告信息。
@end deffn

@geindex setLocale() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setLocale}@anchor{2c61}
@deffn {方法} XMLReader.setLocale (locale)

允许应用程序为错误和警告设置语言区域。

SAX 解析器不要求为错误和警告提供本地化信息；但是如果它们无法支持所请求的语言区域，则必须引发一个 SAX 异常。 应用程序可以在解析的中途请求更改语言区域。
@end deffn

@geindex getFeature() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getFeature}@anchor{2c62}
@deffn {方法} XMLReader.getFeature (featurename)

返回 @emph{featurename} 特性的当前设置。 如果特性无法被识别，则会引发 @code{SAXNotRecognizedException}。 在 @ref{145,,xml.sax.handler} 模块中列出了常见的特性名称。
@end deffn

@geindex setFeature() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setFeature}@anchor{2c11}
@deffn {方法} XMLReader.setFeature (featurename, value)

将 @emph{featurename} 设为 @emph{value}。 如果特性无法被识别，则会引发 @code{SAXNotRecognizedException}。 如果特性或其设置不被解析器所支持，则会引发 @emph{SAXNotSupportedException}。
@end deffn

@geindex getProperty() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader getProperty}@anchor{2c63}
@deffn {方法} XMLReader.getProperty (propertyname)

返回 @emph{propertyname} 属性的当前设置。 如果属性无法被识别，则会引发 @code{SAXNotRecognizedException}。 在 @ref{145,,xml.sax.handler} 模块中列出了常见的属性名称。
@end deffn

@geindex setProperty() (xml.sax.xmlreader.XMLReader 方法)
@anchor{library/xml sax reader xml sax xmlreader XMLReader setProperty}@anchor{2c64}
@deffn {方法} XMLReader.setProperty (propertyname, value)

将 @emph{propertyname} 设为 @emph{value}。 如果属性无法被识别，则会引发 @code{SAXNotRecognizedException}。 如果属性或其设置不被解析器所支持，则会引发 @emph{SAXNotSupportedException}。
@end deffn

@node IncrementalParser 对象,Locator 对象,XMLReader 对象,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader incremental-parser-objects}@anchor{2c65}@anchor{library/xml sax reader incrementalparser-objects}@anchor{2c66}
@subsubsection IncrementalParser 对象


@ref{2c53,,IncrementalParser} 的实例额外提供了下列方法:

@geindex feed() (xml.sax.xmlreader.IncrementalParser 方法)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser feed}@anchor{2c67}
@deffn {方法} IncrementalParser.feed (data)

处理 @emph{data} 的一个分块。
@end deffn

@geindex close() (xml.sax.xmlreader.IncrementalParser 方法)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser close}@anchor{2c68}
@deffn {方法} IncrementalParser.close ()

确定文档的结尾。 这将检查只能在结尾处检查的格式是否良好的条件，发起调用处理程序，并可能会清理在解析期间分配的资源。
@end deffn

@geindex reset() (xml.sax.xmlreader.IncrementalParser 方法)
@anchor{library/xml sax reader xml sax xmlreader IncrementalParser reset}@anchor{2c69}
@deffn {方法} IncrementalParser.reset ()

此方法会在调用 close 来重置解析器以便其准备好解析新的文档之后被调用。 在 close 之后未调用 reset 即调用 parse 或 feed 的结果是未定义的。
@end deffn

@node Locator 对象,InputSource 对象,IncrementalParser 对象,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader id2}@anchor{2c6a}@anchor{library/xml sax reader locator-objects}@anchor{2c6b}
@subsubsection Locator 对象


@ref{2c15,,Locator} 的实例提供了下列方法:

@geindex getColumnNumber() (xml.sax.xmlreader.Locator 方法)
@anchor{library/xml sax reader xml sax xmlreader Locator getColumnNumber}@anchor{2c6c}
@deffn {方法} Locator.getColumnNumber ()

返回当前事件开始位置的列号。
@end deffn

@geindex getLineNumber() (xml.sax.xmlreader.Locator 方法)
@anchor{library/xml sax reader xml sax xmlreader Locator getLineNumber}@anchor{2c6d}
@deffn {方法} Locator.getLineNumber ()

返回当前事件开始位置的行号。
@end deffn

@geindex getPublicId() (xml.sax.xmlreader.Locator 方法)
@anchor{library/xml sax reader xml sax xmlreader Locator getPublicId}@anchor{2c6e}
@deffn {方法} Locator.getPublicId ()

返回当前事件的公有标识符。
@end deffn

@geindex getSystemId() (xml.sax.xmlreader.Locator 方法)
@anchor{library/xml sax reader xml sax xmlreader Locator getSystemId}@anchor{2c6f}
@deffn {方法} Locator.getSystemId ()

返回当前事件的系统标识符。
@end deffn

@node InputSource 对象,Attributes 接口,Locator 对象,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader input-source-objects}@anchor{2c70}@anchor{library/xml sax reader inputsource-objects}@anchor{2c71}
@subsubsection InputSource 对象


@geindex setPublicId() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource setPublicId}@anchor{2c72}
@deffn {方法} InputSource.setPublicId (id)

设置该 @ref{88b,,InputSource} 的公有标识符。
@end deffn

@geindex getPublicId() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource getPublicId}@anchor{2c73}
@deffn {方法} InputSource.getPublicId ()

返回此 @ref{88b,,InputSource} 的公有标识符。
@end deffn

@geindex setSystemId() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource setSystemId}@anchor{2c74}
@deffn {方法} InputSource.setSystemId (id)

设置此 @ref{88b,,InputSource} 的系统标识符。
@end deffn

@geindex getSystemId() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource getSystemId}@anchor{2c75}
@deffn {方法} InputSource.getSystemId ()

返回此 @ref{88b,,InputSource} 的系统标识符。
@end deffn

@geindex setEncoding() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource setEncoding}@anchor{2c76}
@deffn {方法} InputSource.setEncoding (encoding)

设置此 @ref{88b,,InputSource} 的字符编码格式。

编码格式必须是 XML 编码声明可接受的字符串（参见 XML 建议规范第 4.3.3 节）。

如果 @ref{88b,,InputSource} 还包含一个字符流则 @ref{88b,,InputSource} 的 encoding 属性会被忽略。
@end deffn

@geindex getEncoding() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource getEncoding}@anchor{2c77}
@deffn {方法} InputSource.getEncoding ()

获取此 InputSource 的字符编码格式。
@end deffn

@geindex setByteStream() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource setByteStream}@anchor{2c78}
@deffn {方法} InputSource.setByteStream (bytefile)

设置此输入源的字节流（为 @ref{140a,,binary file} 对象）。

如果还指定了一个字符流被则 SAX 解析器会忽略此设置，但它将优先使用字节流而不是自己打开一个 URI 连接。

如果应用程序知道字节流的字符编码格式，它应当使用 setEncoding 方法来设置它。
@end deffn

@geindex getByteStream() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource getByteStream}@anchor{2c79}
@deffn {方法} InputSource.getByteStream ()

获取此输入源的字节流。

getEncoding 方法将返回该字节流的字符编码格式，如果未知则返回 @code{None}。
@end deffn

@geindex setCharacterStream() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource setCharacterStream}@anchor{2c7a}
@deffn {方法} InputSource.setCharacterStream (charfile)

设置此输入源的字符流 (为 @ref{1409,,text file} 对象)。

如果指定了一个字符流，SAX 解析器将忽略任何字节流并且不会尝试打开一个指向系统标识符的 URI 连接。
@end deffn

@geindex getCharacterStream() (xml.sax.xmlreader.InputSource 方法)
@anchor{library/xml sax reader xml sax xmlreader InputSource getCharacterStream}@anchor{2c7b}
@deffn {方法} InputSource.getCharacterStream ()

获取此输入源的字符流。
@end deffn

@node Attributes 接口,AttributesNS 接口,InputSource 对象,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader attributes-objects}@anchor{2c35}@anchor{library/xml sax reader the-attributes-interface}@anchor{2c7c}
@subsubsection @code{Attributes} 接口


@code{Attributes} 对象实现了一部分 @ref{c14,,映射协议}，包括 @code{copy()}, @code{get()}, @ref{df6,,__contains__()}, @code{items()}, @code{keys()} 和 @code{values()} 等方法。 还提供了下列方法:

@geindex getLength() (xml.sax.xmlreader.Attributes 方法)
@anchor{library/xml sax reader xml sax xmlreader Attributes getLength}@anchor{2c7d}
@deffn {方法} Attributes.getLength ()

返回属性的数量。
@end deffn

@geindex getNames() (xml.sax.xmlreader.Attributes 方法)
@anchor{library/xml sax reader xml sax xmlreader Attributes getNames}@anchor{2c7e}
@deffn {方法} Attributes.getNames ()

返回属性的名称。
@end deffn

@geindex getType() (xml.sax.xmlreader.Attributes 方法)
@anchor{library/xml sax reader xml sax xmlreader Attributes getType}@anchor{2c7f}
@deffn {方法} Attributes.getType (name)

返回属性 @emph{name} 的类型，通常为 @code{'CDATA'}。
@end deffn

@geindex getValue() (xml.sax.xmlreader.Attributes 方法)
@anchor{library/xml sax reader xml sax xmlreader Attributes getValue}@anchor{2c80}
@deffn {方法} Attributes.getValue (name)

返回属性 @emph{name} 的值。
@end deffn

@c getValueByQName, getNameByQName, getQNameByName, getQNames available

@c here already, but documented only for derived class.

@node AttributesNS 接口,,Attributes 接口,xml sax xmlreader --- 用于 XML 解析器的接口
@anchor{library/xml sax reader attributes-ns-objects}@anchor{2c37}@anchor{library/xml sax reader the-attributesns-interface}@anchor{2c81}
@subsubsection @code{AttributesNS} 接口


此接口是 @code{Attributes} 接口（参见 @ref{2c35,,Attributes 接口} 章节）的一个子类型。 那个接口所支持的所有方法在 @code{AttributesNS} 对象上也都可用。

下列方法也是可用的:

@geindex getValueByQName() (xml.sax.xmlreader.AttributesNS 方法)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getValueByQName}@anchor{2c82}
@deffn {方法} AttributesNS.getValueByQName (name)

返回一个限定名称的值。
@end deffn

@geindex getNameByQName() (xml.sax.xmlreader.AttributesNS 方法)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getNameByQName}@anchor{2c83}
@deffn {方法} AttributesNS.getNameByQName (name)

返回限定名称 @emph{name} 的 @code{(namespace, localname)} 对。
@end deffn

@geindex getQNameByName() (xml.sax.xmlreader.AttributesNS 方法)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getQNameByName}@anchor{2c84}
@deffn {方法} AttributesNS.getQNameByName (name)

返回 @code{(namespace, localname)} 对的限定名称。
@end deffn

@geindex getQNames() (xml.sax.xmlreader.AttributesNS 方法)
@anchor{library/xml sax reader xml sax xmlreader AttributesNS getQNames}@anchor{2c85}
@deffn {方法} AttributesNS.getQNames ()

返回所有属性的限定名称。
@end deffn

@node xml parsers expat --- 使用 Expat 的快速 XML 解析,,xml sax xmlreader --- 用于 XML 解析器的接口,结构化标记处理工具
@anchor{library/pyexpat doc}@anchor{2c86}@anchor{library/pyexpat module-xml parsers expat}@anchor{141}@anchor{library/pyexpat xml-parsers-expat-fast-xml-parsing-using-expat}@anchor{2c87}
@subsection @code{xml.parsers.expat} ---  使用 Expat 的快速 XML 解析


@geindex xml.parsers.expat (模块)


__________________________________________________________________


@c Markup notes:
@c 
@c Many of the attributes of the XMLParser objects are callbacks.  Since
@c signature information must be presented, these are described using the method
@c directive.  Since they are attributes which are set by client code, in-text
@c references to these attributes should be marked using the :member: role.

@cartouche
@quotation 警告 
@code{pyexpat} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche

@geindex Expat

@ref{141,,xml.parsers.expat} 模块是针对 Expat 非验证 XML 解析器的 Python 接口。 此模块提供了一个扩展类型 @code{xmlparser}，它代表一个 XML 解析器的当前状态。 在创建一个 @code{xmlparser} 对象之后，该对象的各个属性可被设置为相应的处理句柄函数。 随后当将一个 XML 文档送入解析器时，就会为该 XML 文档中的字符数据和标记调用处理句柄函数。

@geindex 模块; pyexpat

此模块使用 @code{pyexpat} 模块来提供对 Expat 解析器的访问。 直接使用 @code{pyexpat} 模块的方式已被弃用。

此模块提供了一个异常和一个类型对象:

@geindex ExpatError
@anchor{library/pyexpat xml parsers expat ExpatError}@anchor{ce0}
@deffn {例外} xml.parsers.expat.ExpatError

此异常会在 Expat 报错时被引发。 请参阅 @ref{2c88,,ExpatError 异常} 一节了解有关解读 Expat 错误的更多信息。
@end deffn

@geindex error
@anchor{library/pyexpat xml parsers expat error}@anchor{2c89}
@deffn {例外} xml.parsers.expat.error

@ref{ce0,,ExpatError} 的别名。
@end deffn

@geindex XMLParserType() (在 xml.parsers.expat 模块中)
@anchor{library/pyexpat xml parsers expat XMLParserType}@anchor{2c8a}
@deffn {数据} xml.parsers.expat.XMLParserType

来自 @ref{2c8b,,ParserCreate()} 函数的返回值的类型。
@end deffn

@ref{141,,xml.parsers.expat} 模块包含两个函数:

@geindex ErrorString() (在 xml.parsers.expat 模块中)
@anchor{library/pyexpat xml parsers expat ErrorString}@anchor{2c8c}
@deffn {函数} xml.parsers.expat.ErrorString (errno)

返回给定错误号 @emph{errno} 的解释性字符串。
@end deffn

@geindex ParserCreate() (在 xml.parsers.expat 模块中)
@anchor{library/pyexpat xml parsers expat ParserCreate}@anchor{2c8b}
@deffn {函数} xml.parsers.expat.ParserCreate (encoding=None, namespace_separator=None)

创建并返回一个新的 @code{xmlparser} 对象。 如果指定了 @emph{encoding}，它必须为指定 XML 数据所使用的编码格式名称的字符串。 Expat 支持的编码格式没有 Python 那样多，而且它的编码格式库也不能被扩展；它支持 UTF-8, UTF-16, ISO-8859-1 (Latin1) 和 ASCII。 如果给出了 @emph{encoding} @footnote{@w{(1)} 
包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如 "UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅 @indicateurl{https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl} 和 @indicateurl{https://www.iana.org/assignments/character-sets/character-sets.xhtml}。
} 则它将覆盖隐式或显式指定的文档编码格式。

可以选择让 Expat 为你做 XML 命名空间处理，这是通过提供 @emph{namespace_separator} 值来启用的。 该值必须是一个单字符的字符串；如果字符串的长度不合法则将引发 @ref{16d,,ValueError} (@code{None} 被视为等同于省略)。 当命名空间处理被启用时，属于特定命名空间的元素类型名称和属性名称将被展开。 传递给The element name passed to the 元素处理句柄 @code{StartElementHandler} 和 @code{EndElementHandler} 的元素名称将为命名空间 URI，命名空间分隔符和名称的本地部分的拼接。 如果命名空间分隔符是一个零字节 (@code{chr(0)}) 则命名空间 URI 和本地部分将被直接拼接而不带任何分隔符。

举例来说，如果 @emph{namespace_separator} 被设为空格符 (@code{' '}) 并对以下文档进行解析:

@example
<?xml version="1.0"?>
<root xmlns    = "http://default-namespace.org/"
      xmlns:py = "http://www.python.org/ns/">
  <py:elem1 />
  <elem2 xmlns="" />
</root>
@end example

@code{StartElementHandler} 将为每个元素获取以下字符串:

@example
http://default-namespace.org/ root
http://www.python.org/ns/ elem1
elem2
@end example

由于 @code{pyexpat} 所使用的 @code{Expat} 库的限制，被返回的 @code{xmlparser} 实例只能被用来解析单个 XML 文档。 请为每个文档调用 @code{ParserCreate} 来提供单独的解析器实例。
@end deffn


@subsubheading 参见



@table @asis

@item The Expat XML Parser@footnote{http://www.libexpat.org/}

Expat 项目的主页。
@end table


@menu
* XMLParser对象: XMLParser对象<2>. 
* ExpatError 异常:: 
* 示例: 示例<31>. 
* 内容模型描述:: 
* Expat 错误常量:: 

@end menu

@node XMLParser对象<2>,ExpatError 异常,,xml parsers expat --- 使用 Expat 的快速 XML 解析
@anchor{library/pyexpat id2}@anchor{2c8d}@anchor{library/pyexpat xmlparser-objects}@anchor{2c8e}
@subsubsection XMLParser对象


@code{xmlparser} 对象具有以下方法:

@geindex Parse() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser Parse}@anchor{2c8f}
@deffn {方法} xmlparser.Parse (data[, isfinal])

解析字符串 @emph{data} 的内容，调用适当的处理函数来处理解析后的数据。 在对此方法的最后一次调用时 @emph{isfinal} 必须为真值；它允许以片段形式解析单个文件，而不是提交多个文件。 @emph{data} 在任何时候都可以为空字符串。
@end deffn

@geindex ParseFile() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser ParseFile}@anchor{2c90}
@deffn {方法} xmlparser.ParseFile (file)

解析从对象 @emph{file} 读取的 XML 数据。 @emph{file} 仅需提供 @code{read(nbytes)} 方法，当没有更多数据可读时将返回空字符串。
@end deffn

@geindex SetBase() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser SetBase}@anchor{2c91}
@deffn {方法} xmlparser.SetBase (base)

设置要用于解析声明中的系统标识符的相对 URI 的基准。 解析相对标识符的任务会留给应用程序进行：这个值将作为 @emph{base} 参数传递给 @ref{2c92,,ExternalEntityRefHandler()}, @ref{2c93,,NotationDeclHandler()} 和 @ref{2c94,,UnparsedEntityDeclHandler()} 函数。
@end deffn

@geindex GetBase() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser GetBase}@anchor{2c95}
@deffn {方法} xmlparser.GetBase ()

返回包含之前调用 @ref{2c91,,SetBase()} 所设置的基准位置的字符串，或者如果未调用 @ref{2c91,,SetBase()} 则返回 @code{None}。
@end deffn

@geindex GetInputContext() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser GetInputContext}@anchor{2c96}
@deffn {方法} xmlparser.GetInputContext ()

将生成当前事件的输入数据以字符串形式返回。 数据为包含文本的实体的编码格式。 如果被调用时未激活事件处理句柄，则返回值将为 @code{None}。
@end deffn

@geindex ExternalEntityParserCreate() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser ExternalEntityParserCreate}@anchor{2c97}
@deffn {方法} xmlparser.ExternalEntityParserCreate (context[, encoding])

创建一个“子”解析器，可被用来解析由父解析器解析的内容所引用的外部解析实体。 @emph{context} 形参应当是传递给 @ref{2c92,,ExternalEntityRefHandler()} 处理函数的字符串，具体如下所述。 子解析器创建时 @ref{2c98,,ordered_attributes} 和 @ref{2c99,,specified_attributes} 会被设为此解析器的值。
@end deffn

@geindex SetParamEntityParsing() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser SetParamEntityParsing}@anchor{2c9a}
@deffn {方法} xmlparser.SetParamEntityParsing (flag)

控制参数实体（包括外部 DTD 子集）的解析。 可能的 @emph{flag} 值有 @code{XML_PARAM_ENTITY_PARSING_NEVER}, @code{XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE} 和 @code{XML_PARAM_ENTITY_PARSING_ALWAYS}。 如果该旗标设置成功则返回真值。
@end deffn

@geindex UseForeignDTD() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser UseForeignDTD}@anchor{2c9b}
@deffn {方法} xmlparser.UseForeignDTD ([flag])

调用时将 @emph{flag} 设为真值（默认）将导致 Expat 调用 @ref{2c92,,ExternalEntityRefHandler} 时将所有参数设为 @ref{204,,None} 以允许加载替代的 DTD。 如果文档不包含文档类型声明，@ref{2c92,,ExternalEntityRefHandler} 仍然会被调用，但 @ref{2c9c,,StartDoctypeDeclHandler} 和 @ref{2c9d,,EndDoctypeDeclHandler} 将不会被调用。

为 @emph{flag} 传入假值将将撤消之前传入真值的调用，除此之外没有其他影响。

此方法只能在调用 @ref{2c8f,,Parse()} 或 @ref{2c90,,ParseFile()} 方法之前被调用；在已调用过这两个方法之后调用它会导致引发 @ref{ce0,,ExpatError} 且 @ref{1a,,code} 属性被设为 @code{errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]}。
@end deffn

@code{xmlparser} 对象具有下列属性:

@geindex buffer_size (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_size}@anchor{2c9e}
@deffn {属性} xmlparser.buffer_size

当 @ref{2c9f,,buffer_text} 为真值时所使用的缓冲区大小。 可以通过将此属性赋一个新的整数值来设置一个新的缓冲区大小。 当大小发生改变时，缓冲区将被刷新。
@end deffn

@geindex buffer_text (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_text}@anchor{2c9f}
@deffn {属性} xmlparser.buffer_text

将此属性设为真值会使得 @code{xmlparser} 对象缓冲 Expat 所返回的文本内容以尽可能地避免多次调用 @ref{2ca0,,CharacterDataHandler()} 回调。 这可以显著地提升性能，因为 Expat 通常会将字符数据在每个行结束的位置上进行分块。 此属性默认为假值，但可以在任何时候被更改。
@end deffn

@geindex buffer_used (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser buffer_used}@anchor{2ca1}
@deffn {属性} xmlparser.buffer_used

当 @ref{2c9f,,buffer_text} 被启用时，缓冲区中存储的字节数。 这些字节数据表示以 UTF-8 编码的文本。  当 @ref{2c9f,,buffer_text} 为假值时此属性没有任何实际意义。
@end deffn

@geindex ordered_attributes (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser ordered_attributes}@anchor{2c98}
@deffn {属性} xmlparser.ordered_attributes

将该属性设为非零整数会使得各个属性被报告为列表而非字典。 各个属性会按照在文档文本中的出现顺序显示。 对于每个属性，将显示两个列表条目：属性名和属性值。 （该模块的较旧版本也使用了此格式。） 默认情况下，该属性为假值；它可以在任何时候被更改。
@end deffn

@geindex specified_attributes (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser specified_attributes}@anchor{2c99}
@deffn {属性} xmlparser.specified_attributes

如果设为非零整数，解析器将只报告在文档实例中指明的属性而不报告来自属性声明的属性。 设置此属性的应用程序需要特别小心地使用从声明中获得的附加信息以符合 XML 处理程序的行为标准。 默认情况下，该属性为假值；它可以在任何时候被更改。
@end deffn

下列属性包含与 @code{xmlparser} 对象遇到的最近发生的错误有关联的值，并且一旦对 @code{Parse()} 或 @code{ParseFile()} 的调用引发了 @ref{ce0,,xml.parsers.expat.ExpatError} 异常就将只包含正确的值。

@geindex ErrorByteIndex (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorByteIndex}@anchor{2ca2}
@deffn {属性} xmlparser.ErrorByteIndex

错误发生位置的字节索引号。
@end deffn

@geindex ErrorCode (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorCode}@anchor{2ca3}
@deffn {属性} xmlparser.ErrorCode

指明问题的的数字代码。 该值可被传给 @ref{2c8c,,ErrorString()} 函数，或是与在 @code{errors} 对象中定义的常量之一进行比较。
@end deffn

@geindex ErrorColumnNumber (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorColumnNumber}@anchor{2ca4}
@deffn {属性} xmlparser.ErrorColumnNumber

错误发生位置的列号。
@end deffn

@geindex ErrorLineNumber (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser ErrorLineNumber}@anchor{2ca5}
@deffn {属性} xmlparser.ErrorLineNumber

错误发生位置的行号。
@end deffn

下列属性包含 @code{xmlparser} 对象中关联到当前解析位置的值。 在回调报告解析事件期间它们将指示生成事件的字符序列的第一个字符的位置。 当在回调的外部被调用时，所指示的位置将恰好位于最后的解析事件之后（无论是否存在关联的回调）。

@geindex CurrentByteIndex (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentByteIndex}@anchor{2ca6}
@deffn {属性} xmlparser.CurrentByteIndex

解析器输入的当前字节索引号。
@end deffn

@geindex CurrentColumnNumber (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentColumnNumber}@anchor{2ca7}
@deffn {属性} xmlparser.CurrentColumnNumber

解析器输入的当前列号。
@end deffn

@geindex CurrentLineNumber (xml.parsers.expat.xmlparser 属性)
@anchor{library/pyexpat xml parsers expat xmlparser CurrentLineNumber}@anchor{2ca8}
@deffn {属性} xmlparser.CurrentLineNumber

解析器输入的当前行号。
@end deffn

可被设置的处理句柄列表。 要在一个 @code{xmlparser} 对象 @emph{o} 上设置处理句柄，请使用 @code{o.handlername = func}。 @emph{handlername} 必须从下面的列表中获取，而 @emph{func} 必须为接受正确数量参数的可调用对象。 所有参数均为字符串，除非另外指明。

@geindex XmlDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser XmlDeclHandler}@anchor{2ca9}
@deffn {方法} xmlparser.XmlDeclHandler (version, encoding, standalone)

当解析 XML 声明时被调用。 XML 声明是 XML 建议适用版本、文档文本的编码格式，以及可选的“独立”声明的（可选）声明。 @emph{version} 和 @emph{encoding} 将为字符串，而 @emph{standalone} 在文档被声明为独立时将为 @code{1}，在文档被声明为非独立时将为 @code{0}，或者在 standalone 短语被省略时则为 @code{-1}。 这仅适用于 Expat 的 1.95.0 或更新版本。
@end deffn

@geindex StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser StartDoctypeDeclHandler}@anchor{2c9c}
@deffn {方法} xmlparser.StartDoctypeDeclHandler (doctypeName, systemId, publicId, has_internal_subset)

当 Expat 开始解析文档类型声明 (@code{<!DOCTYPE ...}) 时被调用。 @emph{doctypeName} 会完全按所显示的被提供。 @emph{systemId} 和 @emph{publicId} 形参给出所指定的系统和公有标识符，如果被省略则为 @code{None}。 如果文档包含内部文档声明子集则 @emph{has_internal_subset} 将为真值。 这要求 Expat 1.2 或更新的版本。
@end deffn

@geindex EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser EndDoctypeDeclHandler}@anchor{2c9d}
@deffn {方法} xmlparser.EndDoctypeDeclHandler ()

当 Expat 完成解析文档类型声明时被调用。 这要求 Expat 1.2 或更新版本。
@end deffn

@geindex ElementDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser ElementDeclHandler}@anchor{2caa}
@deffn {方法} xmlparser.ElementDeclHandler (name, model)

为每个元素类型声明调用一次。 @emph{name} 为元素类型名称，而 @emph{model} 为内容模型的表示形式。
@end deffn

@geindex AttlistDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser AttlistDeclHandler}@anchor{2cab}
@deffn {方法} xmlparser.AttlistDeclHandler (elname, attname, type, default, required)

为一个元素类型的每个已声明属性执行调用。 如果一个属性列表声明声明了三个属性，这个处理句柄会被调用三次，每个属性一次。 @emph{elname} 是声明所适用的元素的名称而 @emph{attname} 是已声明的属性的名称。 属性类型是作为 @emph{type} 传入的字符串；可能的值有 @code{'CDATA'}, @code{'ID'}, @code{'IDREF'}, ... @emph{default} 给出了当属性未被文档实例所指明时该属性的默认值，或是为 @code{None}，如果没有默认值 (@code{#IMPLIED} 值) 的话。 如果属性必须在文档实例中给出，则 @emph{required} 将为真值。 这要求 Expat 1.95.0 或更新的版本。
@end deffn

@geindex StartElementHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser StartElementHandler}@anchor{2cac}
@deffn {方法} xmlparser.StartElementHandler (name, attributes)

在每个元素开始时被调用。 @emph{name} 是包含元素名称的字符串，而 @emph{attributes} 是元素的属性。 如果 @ref{2c98,,ordered_attributes} 为真值，则属性为列表形式 (完整描述参见 @ref{2c98,,ordered_attributes})。 否则为将名称映射到值的字典。
@end deffn

@geindex EndElementHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser EndElementHandler}@anchor{2cad}
@deffn {方法} xmlparser.EndElementHandler (name)

在每个元素结束时被调用。
@end deffn

@geindex ProcessingInstructionHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser ProcessingInstructionHandler}@anchor{2cae}
@deffn {方法} xmlparser.ProcessingInstructionHandler (target, data)

在每次处理指令时调用。
@end deffn

@geindex CharacterDataHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser CharacterDataHandler}@anchor{2ca0}
@deffn {方法} xmlparser.CharacterDataHandler (data)

针对字符数据调用。 此方法将被用于普通字符数据、CDATA 标记内容以及可忽略的空白符。 需要区分这几种情况的应用程序可以使用 @ref{2caf,,StartCdataSectionHandler}, @ref{2cb0,,EndCdataSectionHandler} 和 @ref{2caa,,ElementDeclHandler} 回调来收集必要的信息。
@end deffn

@geindex UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser UnparsedEntityDeclHandler}@anchor{2c94}
@deffn {方法} xmlparser.UnparsedEntityDeclHandler (entityName, base, systemId, publicId, notationName)

针对未解析（NDATA）实体声明调用。 此方法仅存在于 Expat 库的 1. 2 版；对于更新的版本，请改用 @ref{2cb1,,EntityDeclHandler}。 （下层 Expat 库中的对应函数已被声明为过时。）
@end deffn

@geindex EntityDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser EntityDeclHandler}@anchor{2cb1}
@deffn {方法} xmlparser.EntityDeclHandler (entityName, is_parameter_entity, value, base, systemId, publicId, notationName)

针对所有实体声明被调用。 对于形参和内部实体，@emph{value} 将为给出实体的声明内容的字符串；对于外部实体将为 @code{None}。 @emph{notationName} 形参对于已解析实体将为 @code{None}，对于未解析实体则为标注的名称。 如果实体为形参实体则 @emph{is_parameter_entity} 将为真值而如果为普通实体则为假值（大多数应用程序只需要关注普通实体）。 此方法仅从 1.95.0 版 Expat 库开始才可用。
@end deffn

@geindex NotationDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser NotationDeclHandler}@anchor{2c93}
@deffn {方法} xmlparser.NotationDeclHandler (notationName, base, systemId, publicId)

针对标注声明被调用。 @emph{notationName}, @emph{base}, @emph{systemId} 和 @emph{publicId} 如果给出则均应为字符串。 如果省略公有标识符，则 @emph{publicId} 将为 @code{None}。
@end deffn

@geindex StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser StartNamespaceDeclHandler}@anchor{2cb2}
@deffn {方法} xmlparser.StartNamespaceDeclHandler (prefix, uri)

当一个元素包含命名空间声明时被调用。 命名空间声明会在为声明所在的元素调用 @ref{2cac,,StartElementHandler} 之前被处理。
@end deffn

@geindex EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser EndNamespaceDeclHandler}@anchor{2cb3}
@deffn {方法} xmlparser.EndNamespaceDeclHandler (prefix)

当到达包含命名空间声明的元素的关闭标记时被调用。 此方法会按照调用 @ref{2cb2,,StartNamespaceDeclHandler} 以指明每个命名空间作用域的开始的逆顺序为元素上的每个命名空间声明调用一次。 对这个处理句柄的调用是在相应的 @ref{2cad,,EndElementHandler} 之后针对元素的结束而进行的。
@end deffn

@geindex CommentHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser CommentHandler}@anchor{2cb4}
@deffn {方法} xmlparser.CommentHandler (data)

针对注释被调用。 @emph{data} 是注释的文本，不包括开头的 @code{'<!-}@code{-'} 和末尾的 @code{'-}@code{->'}。
@end deffn

@geindex StartCdataSectionHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser StartCdataSectionHandler}@anchor{2caf}
@deffn {方法} xmlparser.StartCdataSectionHandler ()

在一个 CDATA 节的开头被调用。 需要此方法和 @ref{2cb0,,EndCdataSectionHandler} 以便能够标识 CDATA 节的语法开始和结束。
@end deffn

@geindex EndCdataSectionHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser EndCdataSectionHandler}@anchor{2cb0}
@deffn {方法} xmlparser.EndCdataSectionHandler ()

在一个 CDATA 节的末尾被调用。
@end deffn

@geindex DefaultHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser DefaultHandler}@anchor{2cb5}
@deffn {方法} xmlparser.DefaultHandler (data)

针对 XML 文档中没有指定适用处理句柄的任何字符被调用。 这包括了所有属于可被报告的结构的一部分，但未提供处理句柄的字符。
@end deffn

@geindex DefaultHandlerExpand() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser DefaultHandlerExpand}@anchor{2cb6}
@deffn {方法} xmlparser.DefaultHandlerExpand (data)

这与 @ref{2cb5,,DefaultHandler()} 相同，但不会抑制内部实体的扩展。 实体引用将不会被传递给默认处理句柄。
@end deffn

@geindex NotStandaloneHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser NotStandaloneHandler}@anchor{2cb7}
@deffn {方法} xmlparser.NotStandaloneHandler ()

当 XML 文档未被声明为独立文档时被调用。 这种情况发生在出现外部子集或对参数实体的引用，但 XML 声明没有在 XML 声明中将 standalone 设为 @code{yes} 的时候。 如果这个处理句柄返回 @code{0}，那么解析器将引发 @code{XML_ERROR_NOT_STANDALONE} 错误。 如果这个处理句柄没有被设置，那么解析器就不会为这个条件引发任何异常。
@end deffn

@geindex ExternalEntityRefHandler() (xml.parsers.expat.xmlparser 方法)
@anchor{library/pyexpat xml parsers expat xmlparser ExternalEntityRefHandler}@anchor{2c92}
@deffn {方法} xmlparser.ExternalEntityRefHandler (context, base, systemId, publicId)

为对外部实体的引用执行调用。 @emph{base} 为当前的基准，由之前对 @ref{2c91,,SetBase()} 的调用设置。 公有和系统标识符 @emph{systemId} 和 @emph{publicId} 如果给出则圴为字符串；如果公有标识符未给出，则 @emph{publicId} 将为 @code{None}。 @emph{context} 是仅根据以下说明来使用的不透明值。

对于要解析的外部实体，这个处理句柄必须被实现。 它负责使用 @code{ExternalEntityParserCreate(context)} 来创建子解析器，通过适当的回调将其初始化，并对实体进行解析。 这个处理句柄应当返回一个整数；如果它返回 @code{0}，则解析器将引发 @code{XML_ERROR_EXTERNAL_ENTITY_HANDLING} 错误，否则解析将会继续。

如果未提供这个处理句柄，外部实体会由 @ref{2cb5,,DefaultHandler} 回调来报告，如果提供了该回调的话。
@end deffn

@node ExpatError 异常,示例<31>,XMLParser对象<2>,xml parsers expat --- 使用 Expat 的快速 XML 解析
@anchor{library/pyexpat expaterror-exceptions}@anchor{2cb8}@anchor{library/pyexpat expaterror-objects}@anchor{2c88}
@subsubsection ExpatError 异常


@ref{ce0,,ExpatError} 异常包含几个有趣的属性:

@geindex code (xml.parsers.expat.ExpatError 属性)
@anchor{library/pyexpat xml parsers expat ExpatError code}@anchor{2cb9}
@deffn {属性} ExpatError.code

Expat 对于指定错误的内部错误号。 @ref{2cba,,errors.messages} 字典会将这些错误号映射到 Expat 的错误消息。 例如:

@example
from xml.parsers.expat import ParserCreate, ExpatError, errors

p = ParserCreate()
try:
    p.Parse(some_xml_document)
except ExpatError as err:
    print("Error:", errors.messages[err.code])
@end example

@ref{142,,errors} 模块也提供了一些错误消息常量和一个将这些消息映射回错误码的字典 @ref{2cbb,,codes}，参见下文。
@end deffn

@geindex lineno (xml.parsers.expat.ExpatError 属性)
@anchor{library/pyexpat xml parsers expat ExpatError lineno}@anchor{2cbc}
@deffn {属性} ExpatError.lineno

检测到错误所在的行号。 首行的行号为 @code{1}。
@end deffn

@geindex offset (xml.parsers.expat.ExpatError 属性)
@anchor{library/pyexpat xml parsers expat ExpatError offset}@anchor{2cbd}
@deffn {属性} ExpatError.offset

错误发生在行中的字符偏移量。 首列的列号为 @code{0}。
@end deffn

@node 示例<31>,内容模型描述,ExpatError 异常,xml parsers expat --- 使用 Expat 的快速 XML 解析
@anchor{library/pyexpat example}@anchor{2cbe}@anchor{library/pyexpat expat-example}@anchor{2cbf}
@subsubsection 示例


以下程序定义了三个处理句柄，会简单地打印出它们的参数。:

@example
import xml.parsers.expat

# 3 handler functions
def start_element(name, attrs):
    print('Start element:', name, attrs)
def end_element(name):
    print('End element:', name)
def char_data(data):
    print('Character data:', repr(data))

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.Parse("""<?xml version="1.0"?>
<parent id="top"><child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""", 1)
@end example

来自这个程序的输出是:

@example
Start element: parent @{'id': 'top'@}
Start element: child1 @{'name': 'paul'@}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 @{'name': 'fred'@}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
@end example

@node 内容模型描述,Expat 错误常量,示例<31>,xml parsers expat --- 使用 Expat 的快速 XML 解析
@anchor{library/pyexpat content-model-descriptions}@anchor{2cc0}@anchor{library/pyexpat expat-content-models}@anchor{2cc1}@anchor{library/pyexpat module-xml parsers expat model}@anchor{143}
@subsubsection 内容模型描述


@geindex xml.parsers.expat.model (模块)

内容模型是使用嵌套的元组来描述的。 每个元素包含四个值：类型、限定符、名称和一个子元组。 子元组就是附加的内容模型描述。

前两个字段的值是在 @ref{143,,xml.parsers.expat.model} 模块中定义的常量。 这些常量可分为两组：模型类型组和限定符组。

模型类型组中的常量有:


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_ANY

模型名称所指定的元素被声明为具有 @code{ANY} 内容模型。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_CHOICE

命名元素允许从几个选项中选择；这被用于内容模型例如 @code{(A | B | C)}。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_EMPTY

被声明为 @code{EMPTY} 的元素具有此模型类型。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_MIXED
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_NAME
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CTYPE_SEQ

代表彼此相连的一系列模型的模型用此模型类型来指明。 这被用于 @code{(A, B, C)} 这样的模型。
@end deffn

限定符组中的常量有:


@deffn {数据} xml.parsers.expat.model.XML_CQUANT_NONE

未给出限定符，这样它可以只出现一次，例如 @code{A}。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CQUANT_OPT

可选的模型：它可以出现一次或完全不出现，例如 @code{A?}。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CQUANT_PLUS

模型必须出现一次或多次 (例如 @code{A+})。
@end deffn


@deffn {数据} xml.parsers.expat.model.XML_CQUANT_REP

模型必须出现零次或多次，例如 @code{A*}。
@end deffn

@node Expat 错误常量,,内容模型描述,xml parsers expat --- 使用 Expat 的快速 XML 解析
@anchor{library/pyexpat expat-error-constants}@anchor{2cc2}@anchor{library/pyexpat expat-errors}@anchor{2cc3}@anchor{library/pyexpat module-xml parsers expat errors}@anchor{142}
@subsubsection Expat 错误常量


@geindex xml.parsers.expat.errors (模块)

下列常量是在 @ref{142,,xml.parsers.expat.errors} 模块中提供的。 这些常量在有错误发生时解读被引发的 @code{ExpatError} 异常对象的某些属性时很有用处。 出于保持向下兼容性的理由，这些常量的值是错误 @emph{消息} 而不是数字形式的错误 @emph{代码}，为此你可以将它的 @ref{1a,,code} 属性和 @code{errors.codes[errors.XML_ERROR_@emph{CONSTANT_NAME}]} 进行比较。

@code{errors} 模块具有以下属性:

@geindex codes() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors codes}@anchor{2cbb}
@deffn {数据} xml.parsers.expat.errors.codes

将字符串描述映射到其错误代码的字典。


3.2 新版功能.

@end deffn

@geindex messages() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors messages}@anchor{2cba}
@deffn {数据} xml.parsers.expat.errors.messages

将数字形式的错误代码映射到其字符串描述的字典。


3.2 新版功能.

@end deffn

@geindex XML_ERROR_ASYNC_ENTITY() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ASYNC_ENTITY}@anchor{2cc4}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY
@end deffn

@geindex XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF}@anchor{2cc5}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

属性值中指向一个外部实体而非内部实体的实体引用。
@end deffn

@geindex XML_ERROR_BAD_CHAR_REF() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_BAD_CHAR_REF}@anchor{2cc6}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF

指向一个在 XML 不合法的字符的字符引用 (例如，字符 @code{0} 或 '@code{&#0;}')。
@end deffn

@geindex XML_ERROR_BINARY_ENTITY_REF() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_BINARY_ENTITY_REF}@anchor{2cc7}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF

指向一个使用标注声明，因而无法被解析的实体的实体引用。
@end deffn

@geindex XML_ERROR_DUPLICATE_ATTRIBUTE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_DUPLICATE_ATTRIBUTE}@anchor{2cc8}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE

一个属性在一个开始标记中被使用超过一次。
@end deffn

@geindex XML_ERROR_INCORRECT_ENCODING() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INCORRECT_ENCODING}@anchor{2cc9}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING
@end deffn

@geindex XML_ERROR_INVALID_TOKEN() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INVALID_TOKEN}@anchor{2cca}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN

当一个输入字节无法被正确分配给一个字符时引发；例如，在 UTF-8 输入流中的 NUL 字节 (值为 @code{0}).
@end deffn

@geindex XML_ERROR_JUNK_AFTER_DOC_ELEMENT() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_JUNK_AFTER_DOC_ELEMENT}@anchor{2ccb}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT

在文档元素之后出现空白符以外的内容。
@end deffn

@geindex XML_ERROR_MISPLACED_XML_PI() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_MISPLACED_XML_PI}@anchor{2ccc}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI

在输入数据开始位置以外的地方发现 XML 声明。
@end deffn

@geindex XML_ERROR_NO_ELEMENTS() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NO_ELEMENTS}@anchor{2ccd}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS

文档不包含任何元素（XML 要求所有文档都包含恰好一个最高层级元素）。
@end deffn

@geindex XML_ERROR_NO_MEMORY() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NO_MEMORY}@anchor{2cce}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_NO_MEMORY

Expat 无法在内部分配内存。
@end deffn

@geindex XML_ERROR_PARAM_ENTITY_REF() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PARAM_ENTITY_REF}@anchor{2ccf}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF

在不被允许的位置发现一个参数实体引用。
@end deffn

@geindex XML_ERROR_PARTIAL_CHAR() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PARTIAL_CHAR}@anchor{2cd0}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR

在输入中发出一个不完整的字符。
@end deffn

@geindex XML_ERROR_RECURSIVE_ENTITY_REF() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_RECURSIVE_ENTITY_REF}@anchor{2cd1}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF

一个实体引用包含了对同一实体的另一个引用；可能是通过不同的名称，并可能是间接的引用。
@end deffn

@geindex XML_ERROR_SYNTAX() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SYNTAX}@anchor{2cd2}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_SYNTAX

遇到了某个未指明的语法错误。
@end deffn

@geindex XML_ERROR_TAG_MISMATCH() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_TAG_MISMATCH}@anchor{2cd3}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH

一个结束标记不能匹配到最内层的未关闭开始标记。
@end deffn

@geindex XML_ERROR_UNCLOSED_TOKEN() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_TOKEN}@anchor{2cd4}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN

某些记号（例如开始标记）在流结束或遇到下一个记号之前还未关闭。
@end deffn

@geindex XML_ERROR_UNDEFINED_ENTITY() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNDEFINED_ENTITY}@anchor{2cd5}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY

对一个未定义的实体进行了引用。
@end deffn

@geindex XML_ERROR_UNKNOWN_ENCODING() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNKNOWN_ENCODING}@anchor{2cd6}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING

文档编码格式不被 Expat 所支持。
@end deffn

@geindex XML_ERROR_UNCLOSED_CDATA_SECTION() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_CDATA_SECTION}@anchor{2cd7}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION

一个 CDATA 标记节还未关闭。
@end deffn

@geindex XML_ERROR_EXTERNAL_ENTITY_HANDLING() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_EXTERNAL_ENTITY_HANDLING}@anchor{2cd8}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING
@end deffn

@geindex XML_ERROR_NOT_STANDALONE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NOT_STANDALONE}@anchor{2cd9}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE

解析器确定文档不是“独立的”但它却在 XML 声明中声明自己是独立的，并且 @code{NotStandaloneHandler} 被设置为返回 @code{0}。
@end deffn

@geindex XML_ERROR_UNEXPECTED_STATE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNEXPECTED_STATE}@anchor{2cda}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE
@end deffn

@geindex XML_ERROR_ENTITY_DECLARED_IN_PE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ENTITY_DECLARED_IN_PE}@anchor{2cdb}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE
@end deffn

@geindex XML_ERROR_FEATURE_REQUIRES_XML_DTD() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_FEATURE_REQUIRES_XML_DTD}@anchor{2cdc}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD

请求了一个需要已编译 DTD 支持的操作，但 Expat 被配置为不带 DTD 支持。 此错误应当绝对不会被 @ref{141,,xml.parsers.expat} 模块的标准构建版本所报告。
@end deffn

@geindex XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING}@anchor{2cdd}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

在解析开始之后请求一个只能在解析开始之前执行的行为改变。 此错误（目前）只能由 @code{UseForeignDTD()} 所引发。
@end deffn

@geindex XML_ERROR_UNBOUND_PREFIX() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNBOUND_PREFIX}@anchor{2cde}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX

当命名空间处理被启用时发现一个未声明的前缀。
@end deffn

@geindex XML_ERROR_UNDECLARING_PREFIX() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_UNDECLARING_PREFIX}@anchor{2cdf}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX

文档试图移除与某个前缀相关联的命名空间声明。
@end deffn

@geindex XML_ERROR_INCOMPLETE_PE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_INCOMPLETE_PE}@anchor{2ce0}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE

一个参数实体包含不完整的标记。
@end deffn

@geindex XML_ERROR_XML_DECL() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_XML_DECL}@anchor{2ce1}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_XML_DECL

文档完全未包含任何文档元素。
@end deffn

@geindex XML_ERROR_TEXT_DECL() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_TEXT_DECL}@anchor{2ce2}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_TEXT_DECL

解析一个外部实体中的文本声明时出现错误。
@end deffn

@geindex XML_ERROR_PUBLICID() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_PUBLICID}@anchor{2ce3}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_PUBLICID

在公有 id 中发现不被允许的字符。
@end deffn

@geindex XML_ERROR_SUSPENDED() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SUSPENDED}@anchor{2ce4}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_SUSPENDED

在挂起的解析器上请求执行操作，但未获得允许。 这包括提供额外输入或停止解析器的尝试。
@end deffn

@geindex XML_ERROR_NOT_SUSPENDED() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_NOT_SUSPENDED}@anchor{2ce5}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED

在解析器未被挂起的时候执行恢复解析器的尝试。
@end deffn

@geindex XML_ERROR_ABORTED() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_ABORTED}@anchor{2ce6}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_ABORTED

此错误不应当被报告给 Python 应用程序。
@end deffn

@geindex XML_ERROR_FINISHED() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_FINISHED}@anchor{2ce7}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_FINISHED

在一个已经完成解析输入的解析器上请求执行操作，但未获得允许。 这包括提供额外输入或停止解析器的尝试。
@end deffn

@geindex XML_ERROR_SUSPEND_PE() (在 xml.parsers.expat.errors 模块中)
@anchor{library/pyexpat xml parsers expat errors XML_ERROR_SUSPEND_PE}@anchor{2ce8}
@deffn {数据} xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE
@end deffn

@node 互联网协议和支持,多媒体服务,结构化标记处理工具,Python 标准库
@anchor{library/internet doc}@anchor{2ce9}@anchor{library/internet internet}@anchor{2cea}@anchor{library/internet internet-protocols-and-support}@anchor{2ceb}
@section 互联网协议和支持


@geindex WWW
@geindex Internet
@geindex World Wide Web

@geindex 模块; socket

本章介绍的模块实现了互联网协议并支持相关技术。 它们都是用 Python 实现的。 这些模块中的大多数都需要存在依赖于系统的模块 @ref{ef,,socket} ，目前大多数流行平台都支持它。 这是一个概述：

@menu
* webbrowser: webbrowser --- 方便的Web浏览器控制器. 方便的Web浏览器控制器
* wsgiref: wsgiref --- WSGI 工具和引用的实现. WSGI 工具和引用的实现
* urllib: urllib --- URL 处理模块. URL 处理模块
* urllib.request: urllib request --- 用于打开 URL 的可扩展库. 用于打开 URL 的可扩展库
* urllib.response: urllib response --- urllib 使用的 Response 类. urllib 使用的 Response 类
* urllib.parse 用于解析 URL: urllib parse 用于解析 URL. 
* urllib.error: urllib error --- urllib request 引发的异常类. urllib.request 引发的异常类
* urllib.robotparser: urllib robotparser --- robots txt 语法分析程序. robots.txt 语法分析程序
* http: http --- HTTP 模块. HTTP 模块
* http.client: http client --- HTTP 协议客户端. HTTP 协议客户端
* ftplib: ftplib --- FTP 协议客户端. FTP 协议客户端
* poplib: poplib --- POP3 协议客户端. POP3 协议客户端
* imaplib: imaplib --- IMAP4 协议客户端. IMAP4 协议客户端
* smtplib ---SMTP协议客户端:: 
* uuid: uuid --- RFC 4122 定义的UUID对象. RFC 4122 定义的UUID对象
* socketserver: socketserver --- 用于网络服务器的框架. 用于网络服务器的框架
* http.server: http server --- HTTP 服务器. HTTP 服务器
* http.cookies: http cookies --- HTTP状态管理. HTTP状态管理
* http.cookiejar —— HTTP 客户端的 Cookie 处理: http cookiejar —— HTTP 客户端的 Cookie 处理. 
* xmlrpc: xmlrpc --- XMLRPC 服务端与客户端模块. XMLRPC 服务端与客户端模块
* xmlrpc.client: xmlrpc client --- XML-RPC 客户端访问. XML-RPC 客户端访问
* xmlrpc.server: xmlrpc server --- 基本 XML-RPC 服务器. 基本 XML-RPC 服务器
* ipaddress: ipaddress --- IPv4/IPv6 操作库. IPv4/IPv6 操作库

@end menu

@node webbrowser --- 方便的Web浏览器控制器,wsgiref --- WSGI 工具和引用的实现,,互联网协议和支持
@anchor{library/webbrowser doc}@anchor{2cec}@anchor{library/webbrowser module-webbrowser}@anchor{132}@anchor{library/webbrowser webbrowser-convenient-web-browser-controller}@anchor{2ced}
@subsection @code{webbrowser} --- 方便的Web浏览器控制器


@geindex webbrowser (模块)

@strong{源码：} Lib/webbrowser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/webbrowser.py}


__________________________________________________________________


@ref{132,,webbrowser} 模块提供了一个高级接口，允许向用户显示基于Web的文档。 在大多数情况下，只需从该模块调用 @ref{2cee,,open()} 函数就可以了。

在 Unix 下，图形浏览器在 X11 下是首选，但如果图形浏览器不可用或 X11 显示不可用，则将使用文本模式浏览器。 如果使用文本模式浏览器，则调用进程将阻塞，直到用户退出浏览器。

如果存在环境变量 
@geindex BROWSER
@geindex 环境变量; BROWSER
@code{BROWSER} ，则将其解释为 @ref{14b6,,os.pathsep} 分隔的浏览器列表，以便在平台默认值之前尝试。 当列表部分的值包含字符串 @code{％s} 时，它被解释为一个文字浏览器命令行，用于替换 @code{％s} 的参数 URL ；如果该部分不包含 @code{％s}，则它只被解释为要启动的浏览器的名称。 @footnote{@w{(1)} 
这里命名的不带完整路径的可执行文件将在 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量给出的目录中搜索。
}

对于非 Unix 平台，或者当 Unix 上有远程浏览器时，控制过程不会等待用户完成浏览器，而是允许远程浏览器在显示界面上维护自己的窗口。 如果 Unix 上没有远程浏览器，控制进程将启动一个新的浏览器并等待。

脚本 @code{webbrowser} 可以用作模块的命令行界面。它接受一个 URL 作为参数。还接受以下可选参数：@code{-n} 如果可能，在新的浏览器窗口中打开 URL ； @code{-t} 在新的浏览器页面（“标签”）中打开 URL。这些选择当然是相互排斥的。用法示例:

@example
python -m webbrowser -t "https://www.python.org"
@end example

定义了以下异常：

@geindex Error
@anchor{library/webbrowser webbrowser Error}@anchor{2cef}
@deffn {例外} webbrowser.Error

发生浏览器控件错误时引发异常。
@end deffn

定义了以下函数：

@geindex open() (在 webbrowser 模块中)
@anchor{library/webbrowser webbrowser open}@anchor{2cee}
@deffn {函数} webbrowser.open (url, new=0, autoraise=True)

使用默认浏览器显示 @emph{url}。 如果 @emph{new} 为 0，则尽可能在同一浏览器窗口中打开 @emph{url}。 如果 @emph{new} 为 1，则尽可能打开新的浏览器窗口。 如果 @emph{new} 为 2，则尽可能打开新的浏览器页面（“标签”）。 如果 @emph{autoraise} 为 “True”，则会尽可能置前窗口（请注意，在许多窗口管理器下，无论此变量的设置如何，都会置前窗口）。

请注意，在某些平台上，尝试使用此函数打开文件名，可能会起作用并启动操作系统的关联程序。 但是，这种方式不被支持也不可移植。

使用 @code{url} 参数会引发  @ref{fec,,auditing event} @code{webbrowser.open} 。
@end deffn

@geindex open_new() (在 webbrowser 模块中)
@anchor{library/webbrowser webbrowser open_new}@anchor{2cf0}
@deffn {函数} webbrowser.open_new (url)

如果可能，在默认浏览器的新窗口中打开 @emph{url}，否则，在唯一的浏览器窗口中打开 @emph{url}。
@end deffn

@geindex open_new_tab() (在 webbrowser 模块中)
@anchor{library/webbrowser webbrowser open_new_tab}@anchor{2cf1}
@deffn {函数} webbrowser.open_new_tab (url)

如果可能，在默认浏览器的新页面（“标签”）中打开 @emph{url}，否则等效于 @ref{2cf0,,open_new()}。
@end deffn

@geindex get() (在 webbrowser 模块中)
@anchor{library/webbrowser webbrowser get}@anchor{2cf2}
@deffn {函数} webbrowser.get (using=None)

返回浏览器类型为 @emph{using} 指定的控制器对象。 如果 @emph{using} 为 @code{None}，则返回适用于调用者环境的默认浏览器的控制器。
@end deffn

@geindex register() (在 webbrowser 模块中)
@anchor{library/webbrowser webbrowser register}@anchor{2cf3}
@deffn {函数} webbrowser.register (name, constructor, instance=None, *, preferred=False)

注册 @emph{name} 浏览器类型。 注册浏览器类型后， @ref{2cf2,,get()} 函数可以返回该浏览器类型的控制器。 如果没有提供 @emph{instance}，或者为 @code{None}，@emph{constructor} 将在没有参数的情况下被调用，以在需要时创建实例。 如果提供了 @emph{instance}，则永远不会调用 @emph{constructor}，并且可能是 @code{None}。

将 @emph{preferred} 设置为 @code{True} 使得这个浏览器成为 @ref{2cf2,,get()} 不带参数调用的首选结果。 否则，只有在您计划设置 
@geindex BROWSER
@geindex 环境变量; BROWSER
@code{BROWSER} 变量，或使用与您声明的处理程序的名称相匹配的非空参数调用 @ref{2cf2,,get()} 时，此入口点才有用。


在 3.7 版更改: 添加了仅关键字参数 @emph{preferred}。

@end deffn

预定义了许多浏览器类型。 此表给出了可以传递给 @ref{2cf2,,get()} 函数的类型名称以及控制器类的相应实例化，这些都在此模块中定义。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

类型名

@tab

类名

@tab

注释

@item

@code{'mozilla'}

@tab

@code{Mozilla('mozilla')}

@tab

@item

@code{'firefox'}

@tab

@code{Mozilla('mozilla')}

@tab

@item

@code{'netscape'}

@tab

@code{Mozilla('netscape')}

@tab

@item

@code{'galeon'}

@tab

@code{Galeon('galeon')}

@tab

@item

@code{'epiphany'}

@tab

@code{Galeon('epiphany')}

@tab

@item

@code{'skipstone'}

@tab

@code{BackgroundBrowser('skipstone')}

@tab

@item

@code{'kfmclient'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'konqueror'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'kfm'}

@tab

@code{Konqueror()}

@tab

(1)

@item

@code{'mosaic'}

@tab

@code{BackgroundBrowser('mosaic')}

@tab

@item

@code{'opera'}

@tab

@code{Opera()}

@tab

@item

@code{'grail'}

@tab

@code{Grail()}

@tab

@item

@code{'links'}

@tab

@code{GenericBrowser('links')}

@tab

@item

@code{'elinks'}

@tab

@code{Elinks('elinks')}

@tab

@item

@code{'lynx'}

@tab

@code{GenericBrowser('lynx')}

@tab

@item

@code{'w3m'}

@tab

@code{GenericBrowser('w3m')}

@tab

@item

@code{'windows-default'}

@tab

@code{WindowsDefault}

@tab

(2)

@item

@code{'macosx'}

@tab

@code{MacOSXOSAScript('default')}

@tab

(3)

@item

@code{'safari'}

@tab

@code{MacOSXOSAScript('safari')}

@tab

(3)

@item

@code{'google-chrome'}

@tab

@code{Chrome('google-chrome')}

@tab

@item

@code{'chrome'}

@tab

@code{Chrome('chrome')}

@tab

@item

@code{'chromium'}

@tab

@code{Chromium('chromium')}

@tab

@item

@code{'chromium-browser'}

@tab

@code{Chromium('chromium-browser')}

@tab

@end multitable


注释:


@enumerate 

@item 
“Konqueror” 是 Unix 的 KDE 桌面环境的文件管理器，只有在 KDE 运行时才有意义。 一些可靠地检测 KDE 的方法会很好；仅检查 
@geindex KDEDIR
@geindex 环境变量; KDEDIR
@code{KDEDIR} 变量是不够的。 另请注意，KDE 2的 @code{konqueror} 命令，会使用名称 “kfm”---此实现选择运行的 Konqueror 的最佳策略。

@item 
仅限 Windows 平台。

@item 
仅限 macOS 平台。
@end enumerate


3.3 新版功能: 添加了对 Chrome/Chromium 的支持。


以下是一些简单的例子:

@example
url = 'https://docs.python.org/'

# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)

# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
@end example

@menu
* 浏览器控制器对象:: 

@end menu

@node 浏览器控制器对象,,,webbrowser --- 方便的Web浏览器控制器
@anchor{library/webbrowser browser-controller-objects}@anchor{2cf4}@anchor{library/webbrowser browser-controllers}@anchor{2cf5}
@subsubsection 浏览器控制器对象


浏览器控制器提供三个与模块级便捷函数相同的方法：

@geindex open() (webbrowser.controller 方法)
@anchor{library/webbrowser webbrowser controller open}@anchor{2cf6}
@deffn {方法} controller.open (url, new=0, autoraise=True)

使用此控制器处理的浏览器显示 @emph{url}。 如果 @emph{new} 为 1，则尽可能打开新的浏览器窗口。 如果 @emph{new} 为 2，则尽可能打开新的浏览器页面（“标签”）。
@end deffn

@geindex open_new() (webbrowser.controller 方法)
@anchor{library/webbrowser webbrowser controller open_new}@anchor{2cf7}
@deffn {方法} controller.open_new (url)

如果可能，在此控制器处理的浏览器的新窗口中打开 @emph{url} ，否则，在唯一的浏览器窗口中打开 @emph{url} 。 别名 @ref{2cf0,,open_new()}。
@end deffn

@geindex open_new_tab() (webbrowser.controller 方法)
@anchor{library/webbrowser webbrowser controller open_new_tab}@anchor{2cf8}
@deffn {方法} controller.open_new_tab (url)

如果可能，在此控制器处理的浏览器的新页面（“标签”）中打开 @emph{url}，否则等效于 @ref{2cf0,,open_new()}。
@end deffn

@node wsgiref --- WSGI 工具和引用的实现,urllib --- URL 处理模块,webbrowser --- 方便的Web浏览器控制器,互联网协议和支持
@anchor{library/wsgiref doc}@anchor{2cf9}@anchor{library/wsgiref module-wsgiref}@anchor{135}@anchor{library/wsgiref wsgiref-wsgi-utilities-and-reference-implementation}@anchor{2cfa}
@subsection @code{wsgiref} --- WSGI 工具和引用的实现


@geindex wsgiref (模块)


__________________________________________________________________


Web 服务器网关接口（WSGI）是 Web 服务器软件和用 Python 编写的 Web 应用程序之间的标准接口。 具有标准接口能够让支持 WSGI 的应用程序与多种不同的 Web 服务器配合使用。

只有 Web 服务器和编程框架的开发者才需要了解 WSGI 设计的每个细节和边界情况。 你不需要了解 WSGI 的每个细节而只需要安装一个 WSGI 应用程序或编写使用现有框架的 Web 应用程序。

@ref{135,,wsgiref} 是一个 WSGI 规范的参考实现，可被用于将 WSGI 支持添加到 Web 服务器或框架中。 它提供了操作 WSGI 环境变量和响应标头的工具，实现 WSGI 服务器的基类，一个可部署 WSGI 应用程序的演示性 HTTP 服务器，以及一个用于检查 WSGI 服务器和应用程序是否符合 WSGI 规范的验证工具 (
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333})。

参看 wsgi.readthedocs.io@footnote{https://wsgi.readthedocs.io/} 获取有关 WSGI 的更多信息，以及教程和其他资源的链接。

@c XXX If you're just trying to write a web application...

@menu
* wsgiref.util: wsgiref util -- WSGI 环境工具. WSGI 环境工具
* wsgiref.headers: wsgiref headers -- WSGI 响应标头工具. WSGI 响应标头工具
* wsgiref.simple_server: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器. 一个简单的 WSGI HTTP 服务器
* wsgiref.validate: wsgiref validate --- WSGI 一致性检查器. WSGI 一致性检查器
* wsgiref.handlers: wsgiref handlers -- 服务器/网关基类. 服务器/网关基类
* 示例: 示例<32>. 

@end menu

@node wsgiref util -- WSGI 环境工具,wsgiref headers -- WSGI 响应标头工具,,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref module-wsgiref util}@anchor{139}@anchor{library/wsgiref wsgiref-util-wsgi-environment-utilities}@anchor{2cfb}
@subsubsection @code{wsgiref.util} -- WSGI 环境工具


@geindex wsgiref.util (模块)

本模块提供了多种工具配合 WSGI 环境使用。 WSGI 环境就是一个包含 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所描述的 HTTP 请求变量的目录。  所有接受 @emph{environ} 形参的函数都会预期被得到一个符合 WSGI 规范的目录；请参阅 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 来了解相关规范的细节。

@geindex guess_scheme() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util guess_scheme}@anchor{2cfc}
@deffn {函数} wsgiref.util.guess_scheme (environ)

返回对于 @code{wsgi.url_scheme} 应为 "http" 还是 "https" 的猜测，具体方式是在 @emph{environ} 中检查 @code{HTTPS} 环境变量。 返回值是一个字符串。

此函数适用于创建一个包装了 CGI 或 CGI 类协议例如 FastCGI 的网关。 通常，提供这种协议的服务器将包括一个 @code{HTTPS} 变量并会在通过 SSL 接收请求时将其值设为 "1", "yes" 或 "on"。 这样，此函数会在找到上述值时返回 "https"，否则返回 "http"。
@end deffn

@geindex request_uri() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util request_uri}@anchor{2cfd}
@deffn {函数} wsgiref.util.request_uri (environ, include_query=True)

使用 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 的 "URL Reconstruction" 一节中的算法返回完整的请求 URL，可能包括查询字符串。 如果 @emph{include_query} 为假值，则结果 URI 中将不包括查询字符串。
@end deffn

@geindex application_uri() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util application_uri}@anchor{2cfe}
@deffn {函数} wsgiref.util.application_uri (environ)

类似于 @ref{2cfd,,request_uri()}，区别在于 @code{PATH_INFO} 和 @code{QUERY_STRING} 变量会被忽略。 结果为请求所指定的应用程序对象的基准 URI。
@end deffn

@geindex shift_path_info() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util shift_path_info}@anchor{2cff}
@deffn {函数} wsgiref.util.shift_path_info (environ)

将单个名称从 @code{PATH_INFO} 变换为 @code{SCRIPT_NAME} 并返回该名称。 @emph{environ} 目录将被原地 @emph{修改}；如果你需要保留原始 @code{PATH_INFO} 或 @code{SCRIPT_NAME} 不变请使用一个副本。

如果 @code{PATH_INFO} 中没有剩余的路径节，则返回 @code{None}。

通常，此例程被用来处理请求 URI 路径的每个部分，比如说将路径当作是一系列字典键。 此例程会修改传入的环境以使其适合发起调用位于目标 URI 上的其他 WSGI 应用程序，如果有一个 WSGI 应用程序位于 @code{/foo}，而请求 URI 路径为 @code{/foo/bar/baz}，且位于 @code{/foo} 的 WSGI 应用程序调用了 @ref{2cff,,shift_path_info()}，它将获得字符串 "bar"，而环境将被更新以适合传递给位于 @code{/foo/bar} 的 WSGI 应用程序。 也就是说，@code{SCRIPT_NAME} 将由 @code{/foo} 变为 @code{/foo/bar}，而 @code{PATH_INFO} 将由 @code{/bar/baz} 变为 @code{/baz}。

当 @code{PATH_INFO} 只是 "/" 时，此例程会返回一个空字符串并在 @code{SCRIPT_NAME} 末尾添加一个斜杠，虽然空的路径节通常会被忽略，并且 @code{SCRIPT_NAME} 通常也不以斜杠作为结束。 此行为是有意为之的，用来确保应用程序在使用此例程执行对象遍历时能区分以 @code{/x} 结束的和以 @code{/x/} 结束的 URI。
@end deffn

@geindex setup_testing_defaults() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util setup_testing_defaults}@anchor{2d00}
@deffn {函数} wsgiref.util.setup_testing_defaults (environ)

以简短的默认值更新 @emph{environ} 用于测试目的。

此全程会添加 WSGI 所需要的各种参数，包括 @code{HTTP_HOST}, @code{SERVER_NAME}, @code{SERVER_PORT}, @code{REQUEST_METHOD}, @code{SCRIPT_NAME}, @code{PATH_INFO} 以及 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 中定义的所有 @code{wsgi.*} 变量。 它只提供默认值，而不会替换这些变量的现有设置。

此例程的目的是让 WSGI 服务器的单元测试以及应用程序设置测试环境更为容易。 它不应该被实际的 WSGI 服务器或应用程序所使用，因为它用的是假数据！

用法示例：

@example
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret

with make_server('@w{'}, 8000, simple_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()
@end example
@end deffn

除了上述的环境函数，@ref{139,,wsgiref.util} 模块还提供了以下辅助工具:

@geindex is_hop_by_hop() (在 wsgiref.util 模块中)
@anchor{library/wsgiref wsgiref util is_hop_by_hop}@anchor{2d01}
@deffn {函数} wsgiref.util.is_hop_by_hop (header_name)

如果 'header_name' 是 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 所定义的 HTTP/1.1 "Hop-by-Hop" 标头则返回 @code{True}。
@end deffn

@geindex FileWrapper (wsgiref.util 中的类)
@anchor{library/wsgiref wsgiref util FileWrapper}@anchor{3ab}
@deffn {类} wsgiref.util.FileWrapper (filelike, blksize=8192)

一个将文件类对象转换为 @ref{11ba,,iterator} 的包装器。 结果对象同时支持 @ref{3ad,,__getitem__()} 和 @ref{611,,__iter__()} 迭代形式，以便兼容 Python 2.1 和 Jython。 当对象被迭代时，可选的 @emph{blksize} 形参将被反复地传给 @emph{文件类对象} 的 @code{read()} 方法以获取字节串并输出。 当 @code{read()} 返回空字节串时，迭代将结束并不可再恢复。

如果 @emph{filelike} 具有 @code{close()} 方法，返回的对象也将具有 @code{close()} 方法，并且它将在被调用时发起调用 @emph{filelike} 对象的 @code{close()} 方法。

用法示例：

@example
from io import StringIO
from wsgiref.util import FileWrapper

# We're using a StringIO-buffer for as the file-like object
filelike = StringIO("This is an example file-like object"*10)
wrapper = FileWrapper(filelike, blksize=5)

for chunk in wrapper:
    print(chunk)
@end example


3.8 版后已移除: 对 @ref{3ad,,序列协议} 的支持已被弃用。

@end deffn

@node wsgiref headers -- WSGI 响应标头工具,wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,wsgiref util -- WSGI 环境工具,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref module-wsgiref headers}@anchor{137}@anchor{library/wsgiref wsgiref-headers-wsgi-response-header-tools}@anchor{2d02}
@subsubsection @code{wsgiref.headers} -- WSGI 响应标头工具


@geindex wsgiref.headers (模块)

此模块提供了一个单独的类 @ref{888,,Headers}，可以方便地使用一个映射类接口操作 WSGI 响应标头。

@geindex Headers (wsgiref.headers 中的类)
@anchor{library/wsgiref wsgiref headers Headers}@anchor{888}
@deffn {类} wsgiref.headers.Headers ([headers])

创建一个包装了 @emph{headers} 的映射类对象，它必须为如 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所描述的由标头名称/值元组构成的列表。 @emph{headers} 的默认值为一个空列表。

@ref{888,,Headers} 对象支持典型的映射操作包括 @ref{3ad,,__getitem__()}, @code{get()}, @ref{d32,,__setitem__()}, @code{setdefault()}, @ref{d33,,__delitem__()} 和 @ref{df6,,__contains__()}。 对于以上各个方法，映射的键是标头名称（大小写不敏感），而值是关联到该标头名称的第一个值。 设置一个标头会移除该标头的任何现有值，再将一个新值添加到所包装的标头列表末尾。 标头的现有顺序通常会保持不变，只在所包装的列表末尾添加新的标头。

与字典不同，当你试图获取或删除所包装的标头列表中不存在的键时 @ref{888,,Headers} 对象不会引发错误。 获取一个不存在的标头只是返回 @code{None}，而删除一个不存在的标头则没有任何影响。

@ref{888,,Headers} 对象还支持 @code{keys()}, @code{values()} 以及 @code{items()} 方法。 如果存在具有多个值的键则 @code{keys()} 和 @code{items()} 所返回的列表可能包括多个相同的键。 对 @ref{888,,Headers} 对象执行 @code{len()} 的结果与 @code{items()} 的长度相同，也与所包装的标头列表的长度相同。 实际上，@code{items()} 方法只是返回所包装的标头列表的一个副本。

在 @ref{888,,Headers} 对象上调用 @code{bytes()} 将返回适用于作为 HTTP 响应标头来传输的已格式化字节串。 每个标头附带以逗号加空格分隔的值放置在一行中。 每一行都以回车符加换行符结束，且该字节串会以一个空行作为结束。

除了映射接口和格式化特性，@ref{888,,Headers} 对象还具有下列方法用来查询和添加多值标头，以及添加具有 MIME 参数的标头:

@geindex get_all() (wsgiref.headers.Headers 方法)
@anchor{library/wsgiref wsgiref headers Headers get_all}@anchor{2d03}
@deffn {方法} get_all (name)

返回包含指定标头的所有值的列表。

返回的列表项将按它们在原始标头列表中的出现或被添加到实例中的顺序排序，并可能包含重复项。 任何被删除并重新插入的字段总是会被添加到标头列表末尾。 如果给定名称的字段不存在，则返回一个空列表。
@end deffn

@geindex add_header() (wsgiref.headers.Headers 方法)
@anchor{library/wsgiref wsgiref headers Headers add_header}@anchor{2d04}
@deffn {方法} add_header (name, value, **_params)

添加一个（可能有多个值）标头，带有通过关键字参数指明的可选的 MIME 参数。

@emph{name} 是要添加的标头字段。 可以使用关键字参数来为标头字段设置 MIME 参数。 每个参数必须为字符串或 @code{None}。 参数名中的下划线会被转换为连字符，因为连字符不可在 Python 标识符中出现，但许多 MIME 参数名都包括连字符。 如果参数值为字符串，它会以 @code{name="value"} 的形式被添加到标头值参数中。 如果为 @code{None}，则只会添加参数名。 （这适用于没有值的 MIME 参数。） 示例用法:

@example
h.add_header('content-disposition', 'attachment', filename='bud.gif')
@end example

以上代码将添加一个这样的标头:

@example
Content-Disposition: attachment; filename="bud.gif"
@end example
@end deffn


在 3.5 版更改: @emph{headers} 形参是可选的。

@end deffn

@node wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,wsgiref validate --- WSGI 一致性检查器,wsgiref headers -- WSGI 响应标头工具,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref module-wsgiref simple_server}@anchor{138}@anchor{library/wsgiref wsgiref-simple-server-a-simple-wsgi-http-server}@anchor{2d05}
@subsubsection @code{wsgiref.simple_server} -- 一个简单的 WSGI HTTP 服务器


@geindex wsgiref.simple_server (模块)

此模块实现了一个简单的 HTTP 服务器 (基于 @ref{96,,http.server}) 来发布 WSGI 应用程序。 每个服务器实例会在给定的主机名和端口号上发布一个 WSGI 应用程序。 如果你想在一个主机名和端口号上发布多个应用程序，你应当创建一个通过解析 @code{PATH_INFO} 来选择每个请求要发起调用哪个应用程序的 WSGI 应用程序。 (例如，使用 @ref{139,,wsgiref.util} 中的  @code{shift_path_info()} 函数。)

@geindex make_server() (在 wsgiref.simple_server 模块中)
@anchor{library/wsgiref wsgiref simple_server make_server}@anchor{2d06}
@deffn {函数} wsgiref.simple_server.make_server (host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)

创建一个新的 WSGI 服务器并在 @emph{host} 和 @emph{port} 上进行监听，接受对 @emph{app} 的连接。 返回值是所提供的 @emph{server_class} 的实例，并将使用指定的 @emph{handler_class} 来处理请求。 @emph{app} 必须是一个如 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所定义的 WSGI 应用程序对象。

用法示例：

@example
from wsgiref.simple_server import make_server, demo_app

with make_server('@w{'}, 8000, demo_app) as httpd:
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

    # Alternative: serve one request, then exit
    httpd.handle_request()
@end example
@end deffn

@geindex demo_app() (在 wsgiref.simple_server 模块中)
@anchor{library/wsgiref wsgiref simple_server demo_app}@anchor{2d07}
@deffn {函数} wsgiref.simple_server.demo_app (environ, start_response)

此函数是一个小巧但完整的 WSGI 应用程序，它返回一个包含消息 "Hello world!" 以及 @emph{environ} 形参中提供的键/值对的文本页面。 它适用于验证 WSGI 服务器 (例如 @ref{138,,wsgiref.simple_server}) 是否能够正确地运行一个简单的 WSGI 应用程序。
@end deffn

@geindex WSGIServer (wsgiref.simple_server 中的类)
@anchor{library/wsgiref wsgiref simple_server WSGIServer}@anchor{2d08}
@deffn {类} wsgiref.simple_server.WSGIServer (server_address, RequestHandlerClass)

创建一个 @ref{2d08,,WSGIServer} 实例。 @emph{server_address} 应当是一个 @code{(host,port)} 元组，而 @emph{RequestHandlerClass} 应当是 @ref{af5,,http.server.BaseHTTPRequestHandler} 的子类，它将被用来处理请求。

你通常不需要调用此构造器，因为 @ref{2d06,,make_server()} 函数能为你处理所有的细节。

@ref{2d08,,WSGIServer} 是 @ref{2d09,,http.server.HTTPServer} 的子类，因此它所有的方法 (例如 @code{serve_forever()} 和 @code{handle_request()}) 都是可用的。 @ref{2d08,,WSGIServer} 还提供了以下 WSGI 专属的方法:

@geindex set_app() (wsgiref.simple_server.WSGIServer 方法)
@anchor{library/wsgiref wsgiref simple_server WSGIServer set_app}@anchor{2d0a}
@deffn {方法} set_app (application)

将可调用对象 @emph{application} 设为将要接受请求的 WSGI 应用程序。
@end deffn

@geindex get_app() (wsgiref.simple_server.WSGIServer 方法)
@anchor{library/wsgiref wsgiref simple_server WSGIServer get_app}@anchor{2d0b}
@deffn {方法} get_app ()

返回当前设置的应用程序可调用对象。
@end deffn

但是，你通常不需要使用这些附加的方法，因为 @ref{2d0a,,set_app()} 通常会由 @ref{2d06,,make_server()} 来调用，而 @ref{2d0b,,get_app()} 主要是针对请求处理句柄实例的。
@end deffn

@geindex WSGIRequestHandler (wsgiref.simple_server 中的类)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler}@anchor{2d0c}
@deffn {类} wsgiref.simple_server.WSGIRequestHandler (request, client_address, server)

为给定的 @emph{request} 创建一个 HTTP 处理句柄 (例如套接字)，@emph{client_address} (一个 @code{(host,port)} 元组)，以及 @emph{server} (@ref{2d08,,WSGIServer} 实例)。

你不需要直接创建该类的实例；它们会根据 @ref{2d08,,WSGIServer} 对象的需要自动创建。 但是，你可以子类化该类并将其作为 @emph{handler_class} 提供给 @ref{2d06,,make_server()} 函数。 一些可能在子类中重载的相关方法:

@geindex get_environ() (wsgiref.simple_server.WSGIRequestHandler 方法)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler get_environ}@anchor{2d0d}
@deffn {方法} get_environ ()

返回包含针对一个请求的 WSGI 环境的字典。  默认实现会拷贝 @ref{2d08,,WSGIServer} 对象的 @code{base_environ} 字典属性的内容并添加从 HTTP 请求获取的各种标头。 对此方法的每个调用应当返回一个 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所指明的包含所有相关 CGI 环境变量的新字典。
@end deffn

@geindex get_stderr() (wsgiref.simple_server.WSGIRequestHandler 方法)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler get_stderr}@anchor{2d0e}
@deffn {方法} get_stderr ()

返回应被用作 @code{wsgi.errors} 流的对象。 默认实现将只返回 @code{sys.stderr}。
@end deffn

@geindex handle() (wsgiref.simple_server.WSGIRequestHandler 方法)
@anchor{library/wsgiref wsgiref simple_server WSGIRequestHandler handle}@anchor{2d0f}
@deffn {方法} handle ()

处理 HTTP 请求。 默认的实现会使用 @ref{136,,wsgiref.handlers} 类创建一个处理句柄实例来实现实际的 WSGI 应用程序接口。
@end deffn
@end deffn

@node wsgiref validate --- WSGI 一致性检查器,wsgiref handlers -- 服务器/网关基类,wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref module-wsgiref validate}@anchor{13a}@anchor{library/wsgiref wsgiref-validate-wsgi-conformance-checker}@anchor{2d10}
@subsubsection @code{wsgiref.validate} --- WSGI 一致性检查器


@geindex wsgiref.validate (模块)

当创建新的 WSGI 应用程序对象、框架、服务器或中间件时，使用 @ref{13a,,wsgiref.validate} 来验证新代码的一致性是很有用的。 此模块提供了一个创建 WSGI 应用程序对象的函数来验证 WSGI 服务器或网关与 WSGI 应用程序对象之间的通信，以便检查双方的协议一致性。

请注意这个工具并不保证完全符合 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333}；此模块没有报告错误并不一定表示不存在错误。 但是，如果此模块确实报告了错误，那么几乎可以肯定服务器或应用程序不是 100% 符合要求的。

此模块是基于 Ian Bicking 的 "Python Paste" 库的 @code{paste.lint} 模块。

@geindex validator() (在 wsgiref.validate 模块中)
@anchor{library/wsgiref wsgiref validate validator}@anchor{2d11}
@deffn {函数} wsgiref.validate.validator (application)

包装 @emph{application} 并返回一个新的 WSGI 应用程序对象。  返回的应用程序将转发所有请求到原始的 @emph{application}，并将检查 @emph{application} 和发起调用它的服务器是否都符合 WSGI 规范和 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html}。

任何被检测到的不一致性都会导致引发 @ref{241,,AssertionError}；但是请注意，如何对待这些错误取决于具体服务器。 例如，@ref{138,,wsgiref.simple_server} 和其他基于 @ref{136,,wsgiref.handlers} 的服务器（它们没有重载错误处理方法来做其他操作）将简单地输出一条消息报告发生了错误，并将回溯转给 @code{sys.stderr} 或者其他错误数据流。

这个包装器也可能会使用 @ref{12f,,warnings} 模块生成输出来指明存在问题但实际上未被 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所禁止的行为。 除非它们被 Python 命令行选项或 @ref{12f,,warnings} API 所屏蔽，否则任何此类警告都将被写入到 @code{sys.stderr} (@emph{不是} @code{wsgi.errors}，除非它们恰好是同一个对象)。

用法示例：

@example
from wsgiref.validate import validator
from wsgiref.simple_server import make_server

# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)

    # This is going to break because we need to return a list, and
    # the validator is going to inform us
    return b"Hello World"

# This is the application wrapped in a validator
validator_app = validator(simple_app)

with make_server('@w{'}, 8000, validator_app) as httpd:
    print("Listening on port 8000....")
    httpd.serve_forever()
@end example
@end deffn

@node wsgiref handlers -- 服务器/网关基类,示例<32>,wsgiref validate --- WSGI 一致性检查器,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref module-wsgiref handlers}@anchor{136}@anchor{library/wsgiref wsgiref-handlers-server-gateway-base-classes}@anchor{2d12}
@subsubsection @code{wsgiref.handlers} -- 服务器/网关基类


@geindex wsgiref.handlers (模块)

此模块提供了用于实现 WSGI 服务器和网关的处理句柄基类。 这些基类可处理大部分与 WSGI 应用程序通信的工作，只要给予它们一个带有输入、输出和错误流的 CGI 类环境。

@geindex CGIHandler (wsgiref.handlers 中的类)
@anchor{library/wsgiref wsgiref handlers CGIHandler}@anchor{2d13}
@deffn {类} wsgiref.handlers.CGIHandler

通过 @code{sys.stdin}, @code{sys.stdout}, @code{sys.stderr} 和 @code{os.environ} 发起基于 CGI 的调用。 这在当你有一个 WSGI 应用程序并想将其作为 CGI 脚本运行时很有用处。 只需发起调用 @code{CGIHandler().run(app)}，其中 @code{app} 是你想要发起调用的 WSGI 应用程序。

该类是 @ref{2d14,,BaseCGIHandler} 的子类，它将设置 @code{wsgi.run_once} 为真值，@code{wsgi.multithread} 为假值，@code{wsgi.multiprocess} 为真值，并总是使用 @ref{fd,,sys} 和 @ref{c4,,os} 来获取所需的 CGI 流和环境。
@end deffn

@geindex IISCGIHandler (wsgiref.handlers 中的类)
@anchor{library/wsgiref wsgiref handlers IISCGIHandler}@anchor{2d15}
@deffn {类} wsgiref.handlers.IISCGIHandler

@ref{2d13,,CGIHandler} 的一个专门化替代，用于在 Microsoft 的 IIS Web 服务器上部署，无需设置 config allowPathInfo 选项 (IIS>=7) 或 metabase allowPathInfoForScriptMappings (IIS<7)。

默认情况下，IIS 给出的 @code{PATH_INFO} 会与前面的 @code{SCRIPT_NAME} 重复，导致想要实现路由的 WSGI 应用程序出现问题。 这个处理句柄会去除任何这样的重复路径。

IIS 可被配置为传递正确的 @code{PATH_INFO}，但这会导致另一个 @code{PATH_TRANSLATED} 出错的问题。 幸运的是这个变量很少被使用并且不被 WSGI 所保证。 但是在 IIS<7 上，这个设置只能在 vhost 层级上进行，影响到所有其他脚本映射，其中许多在受 @code{PATH_TRANSLATED} 问题影响时都会中断运行。 因此 IIS<7 的部署几乎从不附带这样的修正（即使 IIS7 也很少使用它，因为它仍然不带 UI）。

CGI 代码没有办法确定该选项是否已设置，因此提供了一个单独的处理句柄类。 它的用法与 @ref{2d13,,CGIHandler} 相同，即通过调用 @code{IISCGIHandler().run(app)}，其中 @code{app} 是你想要发起调用的 WSGI 应用程序。


3.2 新版功能.

@end deffn

@geindex BaseCGIHandler (wsgiref.handlers 中的类)
@anchor{library/wsgiref wsgiref handlers BaseCGIHandler}@anchor{2d14}
@deffn {类} wsgiref.handlers.BaseCGIHandler (stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

类似于 @ref{2d13,,CGIHandler}，但是改用 @ref{fd,,sys} 和 @ref{c4,,os} 模块，CGI 环境和 I/O 流会被显式地指定。 @emph{multithread} 和 @emph{multiprocess} 值被用来为处理句柄实例所运行的任何应用程序设置 @code{wsgi.multithread} 和 @code{wsgi.multiprocess} 旗标。

该类是 @ref{2d16,,SimpleHandler} 的子类，旨在用于 HTTP "origin servers" 以外的软件。 如果你在编写一个网关协议实现（例如 CGI, FastCGI, SCGI 等等），它使用 @code{Status:} 标头来发布 HTTP 状态，你可能会想要子类化该类而不是 @ref{2d16,,SimpleHandler}。
@end deffn

@geindex SimpleHandler (wsgiref.handlers 中的类)
@anchor{library/wsgiref wsgiref handlers SimpleHandler}@anchor{2d16}
@deffn {类} wsgiref.handlers.SimpleHandler (stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

类似于 @ref{2d14,,BaseCGIHandler}，但被设计用于 HTTP 原始服务器。 如果你在编写一个 HTTP 服务器实现，你可能会想要子类化该类而不是 @ref{2d14,,BaseCGIHandler}。

该类是 @ref{1150,,BaseHandler} 的子类。 它重载了 @ref{e2b,,__init__()}, @code{get_stdin()}, @code{get_stderr()}, @code{add_cgi_vars()}, @code{_write()} 和 @code{_flush()} 方法以支持通过构造器显式地设置环境和流。 所提供的环境和流存储在 @code{stdin}, @code{stdout}, @code{stderr} 和 @code{environ} 属性中。

@emph{stdout} 的 @ref{68a,,write()} 方法应该完整写入每个数据块，与 @ref{689,,io.BufferedIOBase} 一样。
@end deffn

@geindex BaseHandler (wsgiref.handlers 中的类)
@anchor{library/wsgiref wsgiref handlers BaseHandler}@anchor{1150}
@deffn {类} wsgiref.handlers.BaseHandler

这是适用于运行 WSGI 应用程序的抽象基类。 每个实例将处理一个单独的 HTTP 请求，不过在原则上你也可以创建一个可针对多个请求重用的子类。

@ref{1150,,BaseHandler} 实例只有一个方法提供给外部使用:

@geindex run() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler run}@anchor{2d17}
@deffn {方法} run (app)

运行指定的 WSGI 应用程序 @emph{app}。
@end deffn

所有的 @ref{1150,,BaseHandler} 其他方法都是在运行应用程序过程中由该方法发起调用的，因此主要是为了允许定制运行过程。

以下方法必须在子类中被重载:

@geindex _write() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler _write}@anchor{2d18}
@deffn {方法} _write (data)

缓冲字节数据 @emph{data} 以便传输给客户端。 如果此方法真的传输了数据也是可以的；@ref{1150,,BaseHandler} 只有在底层系统真有这样的区分时才会区分写入和刷新操作以提高效率。
@end deffn

@geindex _flush() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler _flush}@anchor{2d19}
@deffn {方法} _flush ()

强制将缓冲的数据传输给客户端。 如果此方法无任何操作也是可以的（例如，@ref{2d18,,_write()} 实际上已发送了数据）。
@end deffn

@geindex get_stdin() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_stdin}@anchor{2d1a}
@deffn {方法} get_stdin ()

返回一个适合被用作当前被处理的请求的 @code{wsgi.input} 的输入流对象。
@end deffn

@geindex get_stderr() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_stderr}@anchor{2d1b}
@deffn {方法} get_stderr ()

返回一个适合被用作当前所处理请求的 @code{wsgi.errors} 的输出流对象。
@end deffn

@geindex add_cgi_vars() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler add_cgi_vars}@anchor{2d1c}
@deffn {方法} add_cgi_vars ()

将当前请求的 CGI 变量插入到 @code{environ} 属性。
@end deffn

以下是一些你可能会想要重载的其他方法。 但这只是个简略的列表，它不包括每个可被重载的方法。 你应当在在尝试创建自定义的 @ref{1150,,BaseHandler} 子类之前参阅文档字符串和源代码来了解更多信息。

用于自定义 WSGI 环境的属性和方法:

@geindex wsgi_multithread (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_multithread}@anchor{2d1d}
@deffn {属性} wsgi_multithread

用于 @code{wsgi.multithread} 环境变量的值。 它在 @ref{1150,,BaseHandler} 中默认为真值，但在其他子类中可能有不同的默认值（或是由构造器来设置）。
@end deffn

@geindex wsgi_multiprocess (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_multiprocess}@anchor{2d1e}
@deffn {属性} wsgi_multiprocess

用于 @code{wsgi.multiprocess} 环境变量的值。 它在 @ref{1150,,BaseHandler} 中默认为真值，但在其他子类中可能有不同的默认值（或是由构造器来设置）。
@end deffn

@geindex wsgi_run_once (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_run_once}@anchor{2d1f}
@deffn {属性} wsgi_run_once

用于 @code{wsgi.run_once} 环境变量的值。 它在 @ref{1150,,BaseHandler} 中默认为假值，但在 @ref{2d13,,CGIHandler} 中默认为真值。
@end deffn

@geindex os_environ (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler os_environ}@anchor{2d20}
@deffn {属性} os_environ

要包括在每个请求的 WSGI 环境中的默认环境变量。 在默认情况下，这是当 @ref{136,,wsgiref.handlers} 被导入时的 @code{os.environ} 的一个副本，但也可以在类或实例层级上创建它们自己的子类。 请注意该字典应当被当作是只读的，因为默认值会在多个类和实际之间共享。
@end deffn

@geindex server_software (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler server_software}@anchor{2d21}
@deffn {属性} server_software

如果设置了 @ref{2d22,,origin_server} 属性，该属性的值会被用来设置默认的 @code{SERVER_SOFTWARE} WSGI 环境变量，并且还会被用来设置 HTTP 响应中默认的 @code{Server:} 标头。 它会被不是 It is ignored for handlers (such as @ref{2d14,,BaseCGIHandler} and @ref{2d13,,CGIHandler}) that are not HTTP origin servers.


在 3.3 版更改: 名称 "Python" 会被替换为实现专属的名称如 "CPython", "Jython" 等等。

@end deffn

@geindex get_scheme() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler get_scheme}@anchor{2d23}
@deffn {方法} get_scheme ()

返回当前请求所使用的 URL 方案。 默认的实现会使用来自 @ref{139,,wsgiref.util} 的 @code{guess_scheme()} 函数根据当前请求的 @code{environ} 变量来猜测方案应该是 "http" 还是 "https"。
@end deffn

@geindex setup_environ() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler setup_environ}@anchor{2d24}
@deffn {方法} setup_environ ()

将 @code{environ} 属性设为填充了完整内容的 WSGI 环境。 默认的实现会使用上述的所有方法和属性，加上 @ref{2d1a,,get_stdin()}, @ref{2d1b,,get_stderr()} 和 @ref{2d1c,,add_cgi_vars()} 方法以及 @ref{2d25,,wsgi_file_wrapper} 属性。 它还会插入一个 @code{SERVER_SOFTWARE} 键，如果该键还不存在的话，只要 @ref{2d22,,origin_server} 属性为真值并且设置了 @ref{2d21,,server_software} 属性。
@end deffn

用于自定义异常处理的方法和属性:

@geindex log_exception() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler log_exception}@anchor{2d26}
@deffn {方法} log_exception (exc_info)

将 @emph{exc_info} 元素记录到服务器日志。 @emph{exc_info} 是一个 @code{(type, value, traceback)} 元组。 默认的实现会简单地将回溯信息写入请求的 @code{wsgi.errors} 流并刷新它。 子类可以重载此方法来修改格式或重设输出目标，通过邮件将回溯信息发给管理员，或执行任何其他符合要求的动作。
@end deffn

@geindex traceback_limit (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler traceback_limit}@anchor{2d27}
@deffn {属性} traceback_limit

要包括在默认 @ref{2d26,,log_exception()} 方法的回溯信息输出中的最大帧数。 如果为 @code{None}，则会包括所有的帧。
@end deffn

@geindex error_output() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_output}@anchor{2d28}
@deffn {方法} error_output (environ, start_response)

此方法是一个为用户生成错误页面的 WSGI 应用程序。 它仅当将标头发送给客户端之前发生错误时会被发起调用。

此方法可使用 @code{sys.exc_info()} 来访问当前错误信息，并应当在调用 @emph{start_response} 时将该信息传递给它（如 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 的 "Error Handling" 部分所描述的）。

默认的实现只是使用 @ref{2d29,,error_status}, @ref{2d2a,,error_headers}, 和 @ref{2d2b,,error_body} 属性来生成一个输出页面。 子类可以重载此方法来产生更动态化的错误输出。

但是请注意，从安全角度看来是不建议将诊断信息暴露给任何用户的；理想的做法是你应当通过特别处理来启用诊断输出，因此默认的实现并不包括这样的内容。
@end deffn

@geindex error_status (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_status}@anchor{2d29}
@deffn {属性} error_status

用于错误响应的 HTTP 状态。 这应当是一个在 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 中定义的字符串；它默认为代码 500 以相应的消息。
@end deffn

@geindex error_headers (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_headers}@anchor{2d2a}
@deffn {属性} error_headers

用于错误响应的 HTTP 标头。 这应当是由 WSGI 响应标头 (@code{(name, value)} 元组) 构成的列表，如 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 所定义的。 默认的列表只是将内容类型设为 @code{text/plain}。
@end deffn

@geindex error_body (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler error_body}@anchor{2d2b}
@deffn {属性} error_body

错误响应体。  这应当是一个 HTTP 响应体字节串。 它默认为纯文本 "A server error occurred.  Please contact the administrator."
@end deffn

用于 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} 的 "可选的平台专属文件处理" 特性的方法和属性:

@geindex wsgi_file_wrapper (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler wsgi_file_wrapper}@anchor{2d25}
@deffn {属性} wsgi_file_wrapper

一个 @code{wsgi.file_wrapper} 工厂对象，或为 @code{None}。 该属性的默认值是 @ref{3ab,,wsgiref.util.FileWrapper} 类。
@end deffn

@geindex sendfile() (wsgiref.handlers.BaseHandler 方法)
@anchor{library/wsgiref wsgiref handlers BaseHandler sendfile}@anchor{2d2c}
@deffn {方法} sendfile ()

重载以实现平台专属的文件传输。 此方法仅在应用程序的返回值是由 @ref{2d25,,wsgi_file_wrapper} 属性指定的类的实例时会被调用。 如果它能够成功地传输文件则应当返回真值，以使得默认的传输代码将不会被执行。 此方法的默认实现只会返回假值。
@end deffn

杂项方法和属性:

@geindex origin_server (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler origin_server}@anchor{2d22}
@deffn {属性} origin_server

该属性在处理句柄的 @ref{2d18,,_write()} 和 @ref{2d19,,_flush()} 被用于同客户端直接通信而不是通过需要 HTTP 状态为某种特殊 @code{Status:} 标头的 CGI 类网关协议时应当被设为真值

该属性在 @ref{1150,,BaseHandler} 中默认为真值，但在 @ref{2d14,,BaseCGIHandler} 和 @ref{2d13,,CGIHandler} 中则为假值。
@end deffn

@geindex http_version (wsgiref.handlers.BaseHandler 属性)
@anchor{library/wsgiref wsgiref handlers BaseHandler http_version}@anchor{2d2d}
@deffn {属性} http_version

如果 @ref{2d22,,origin_server} 为真值，则该字符串属性会被用来设置给客户端的响应的 HTTP 版本。 它的默认值为 @code{"1.0"}。
@end deffn
@end deffn

@geindex read_environ() (在 wsgiref.handlers 模块中)
@anchor{library/wsgiref wsgiref handlers read_environ}@anchor{c11}
@deffn {函数} wsgiref.handlers.read_environ ()

将来自 @code{os.environ} 的 CGI 变量转码为 
@geindex Python 提高建议; PEP 3333
PEP 3333@footnote{https://www.python.org/dev/peps/pep-3333} "bytes in unicode" 字符串，返回一个新的字典。 此函数被 @ref{2d13,,CGIHandler} 和 @ref{2d15,,IISCGIHandler} 用来替代直接使用 @code{os.environ}，后者不一定在所有使用 Python 3 的平台和 Web 服务器上都符合 WSGI 标准 -- 特别是当 OS 的实际环境为 Unicode 时 (例如 Windows)，或者当环境为字节数据，但被 Python 用来解码它的系统编码格式不是 ISO-8859-1 时 (例如使用 UTF-8 的 Unix 系统)。

如果你要实现自己的基于 CGI 的处理句柄，你可能会想要使用此例程而不是简单地从 @code{os.environ} 直接拷贝值。


3.2 新版功能.

@end deffn

@node 示例<32>,,wsgiref handlers -- 服务器/网关基类,wsgiref --- WSGI 工具和引用的实现
@anchor{library/wsgiref examples}@anchor{2d2e}
@subsubsection 示例


这是一个可运行的 "Hello World" WSGI 应用程序:

@example
from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object.
def hello_world_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    return [b"Hello World"]

with make_server('@w{'}, 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()
@end example

一个发布当前目录的 WSGI 应用程序示例，接受通过命令行指定可选的目录和端口号 (默认值: 8000):

@example
#!/usr/bin/env python3
'@w{'}'
Small wsgiref based web server. Takes a path to serve from and an
optional port number (defaults to 8000), then tries to serve files.
Mime types are guessed from the file names, 404 errors are raised
if the file is not found. Used for the make serve target in Doc.
'@w{'}'
import sys
import os
import mimetypes
from wsgiref import simple_server, util

def app(environ, respond):

    fn = os.path.join(path, environ['PATH_INFO'][1:])
    if '.' not in fn.split(os.path.sep)[-1]:
        fn = os.path.join(fn, 'index.html')
    type = mimetypes.guess_type(fn)[0]

    if os.path.exists(fn):
        respond('200 OK', [('Content-Type', type)])
        return util.FileWrapper(open(fn, "rb"))
    else:
        respond('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'not found']

if __name__ == '__main__':
    path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
    httpd = simple_server.make_server('@w{'}, port, app)
    print("Serving @{@} on port @{@}, control-C to stop".format(path, port))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Shutting down.")
        httpd.server_close()
@end example

@node urllib --- URL 处理模块,urllib request --- 用于打开 URL 的可扩展库,wsgiref --- WSGI 工具和引用的实现,互联网协议和支持
@anchor{library/urllib doc}@anchor{2d2f}@anchor{library/urllib module-urllib}@anchor{126}@anchor{library/urllib urllib-url-handling-modules}@anchor{2d30}
@subsection @code{urllib} --- URL 处理模块


@geindex urllib (模块)

@strong{源代码:} Lib/urllib/@footnote{https://github.com/python/cpython/tree/3.9/Lib/urllib/}


__________________________________________________________________


@code{urllib} 是一个收集了多个涉及 URL 的模块的包：


@itemize *

@item 
@ref{129,,urllib.request} 打开和读取 URL

@item 
@ref{127,,urllib.error} 包含 @ref{129,,urllib.request} 抛出的异常

@item 
@ref{128,,urllib.parse}  用于解析 URL

@item 
@ref{12b,,urllib.robotparser} 用于解析 @code{robots.txt} 文件
@end itemize

@node urllib request --- 用于打开 URL 的可扩展库,urllib response --- urllib 使用的 Response 类,urllib --- URL 处理模块,互联网协议和支持
@anchor{library/urllib request doc}@anchor{2d31}@anchor{library/urllib request module-urllib request}@anchor{129}@anchor{library/urllib request urllib-request-extensible-library-for-opening-urls}@anchor{2d32}
@subsection @code{urllib.request} --- 用于打开 URL 的可扩展库


@geindex urllib.request (模块)

@strong{源码：} Lib/urllib/request.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/urllib/request.py}


__________________________________________________________________


@ref{129,,urllib.request} 模块定义了适用于在各种复杂情况下打开 URL（主要为 HTTP）的函数和类 --- 例如基本认证、摘要认证、重定向、cookies 及其它。


@subsubheading 参见


对于更高级别的 HTTP 客户端接口，建议使用 Requests@footnote{https://requests.readthedocs.io/en/master/}  。


@ref{129,,urllib.request} 模块定义了以下函数：

@geindex urlopen() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request urlopen}@anchor{885}
@deffn {函数} urllib.request.urlopen (url, data=None[, timeout], *, cafile=None, capath=None, cadefault=False, context=None)

打开统一资源定位符 @emph{url}，可以是一个字符串或一个 @ref{9e5,,Request} 对象。

@emph{data} 必须是一个对象，用于给出要发送到服务器的附加数据，若不需要发送数据则为 @code{None}。详情请参阅 @ref{9e5,,Request} 。

urllib.request 模块采用 HTTP/1.1 协议，并且在其 HTTP 请求中包含 @code{Connection:close} 头部信息。

@emph{timeout} 为可选参数，用于指定阻塞操作（如连接尝试）的超时时间，单位为秒。如未指定，将使用全局默认超时参数）。本参数实际仅对 HTTP、HTTPS 和 FTP 连接有效。

如果给定了 @emph{context} 参数，则必须是一个 @ref{4f2,,ssl.SSLContext} 实例，用于描述各种 SSL 参数。更多详情请参阅 @ref{4a2,,HTTPSConnection} 。

@emph{cafile} 和 @emph{capath} 为可选参数，用于为 HTTPS 请求指定一组受信 CA 证书。@emph{cafile} 应指向包含CA 证书的单个文件， @emph{capath} 则应指向哈希证书文件的目录。更多信息可参阅 @ref{8e2,,ssl.SSLContext.load_verify_locations()} 。

参数 @emph{cadefault} 将被忽略。

本函数总会返回一个对象，该对象可作为 @ref{66b,,context manager} 使用，带有 @emph{url}、@emph{headers} 和 @emph{status} 属性。有关这些属性的更多详细信息，请参阅 @ref{2d33,,urllib.response.addinfourl} 。

对于 HTTP 和 HTTPS 的 URL 而言，本函数将返回一个稍经修改的 @ref{af8,,http.client.HTTPResponse} 对象。除了上述 3 个新的方法之外，还有 msg 属性包含了与 @ref{2d34,,reason} 属性相同的信息---服务器返回的原因描述文字，而不是  @ref{af8,,HTTPResponse} 的文档所述的响应头部信息。

对于 FTP、文件、数据的URL，以及由传统的 @ref{2d35,,URLopener}  和 @ref{2d36,,FancyURLopener} 类处理的请求，本函数将返回一个 @ref{2d33,,urllib.response.addinfourl} 对象。

协议发生错误时，将会引发 @ref{2d37,,URLError} 。

请注意，如果没有处理函数对请求进行处理，则有可能会返回 @code{None}  。尽管默认安装的全局 @ref{2d38,,OpenerDirector} 会用 @ref{2d39,,UnknownHandler} 来确保不会发生这种情况。

此外，如果检测到设置了代理（比如设置了 
@geindex http_proxy
@geindex 环境变量; http_proxy
@code{http_proxy} 之类的环境变量），默认会安装 @ref{1121,,ProxyHandler} 并确保通过代理处理请求。

Python 2.6 以下版本中留存的 @code{urllib.urlopen} 函数已停止使用了； @ref{885,,urllib.request.urlopen()} 对应于传统的 @code{urllib2.urlopen} 。对代理服务的处理是通过将字典参数传给 @code{urllib.urlopen} 来完成的，可以用 @ref{1121,,ProxyHandler} 对象获取到代理处理函数。

默认会触发一条 @ref{fec,,审计事件} @code{urllib.Request} ，参数 @code{fullurl} 、 @code{data} 、@code{headers} 、@code{method} 均取自请求对象。


在 3.2 版更改: 增加了 @emph{cafile} 与 @emph{capath}。



在 3.2 版更改: 只要条件允许（指 @ref{2839,,ssl.HAS_SNI} 为真），现在能够支持 HTTPS 虚拟主机。



3.2 新版功能: @emph{data} 可以是一个可迭代对象。



在 3.3 版更改: 增加了 @emph{cadefault}。



在 3.4.3 版更改: 增加了 @emph{context}。



3.6 版后已移除: @emph{cafile} 、 @emph{capath} 和 @emph{cadefault} 已废弃，转而推荐使用 @emph{context}。请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 选取系统信任的 CA 证书。

@end deffn

@geindex install_opener() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request install_opener}@anchor{2d3a}
@deffn {函数} urllib.request.install_opener (opener)

安装一个 @ref{2d38,,OpenerDirector} 实例，作为默认的全局打开函数。仅当 urlopen 用到该打开函数时才需要安装；否则，只需调用 @ref{9e9,,OpenerDirector.open()} 而不是 @ref{885,,urlopen()}。代码不会检查是否真的属于 @ref{2d38,,OpenerDirector} 类，所有具备适当接口的类都能适用。
@end deffn

@geindex build_opener() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request build_opener}@anchor{2d3b}
@deffn {函数} urllib.request.build_opener ([handler, ...])

返回一个 @ref{2d38,,OpenerDirector} 实例，以给定顺序把处理函数串联起来。处理函数可以是 @ref{2d3c,,BaseHandler} 的实例，也可以是 @ref{2d3c,,BaseHandler} 的子类（这时构造函数必须允许不带任何参数的调用）。以下类的实例将位于 @emph{处理函数} 之前，除非 @emph{处理函数} 已包含这些类、其实例或其子类： @ref{1121,,ProxyHandler} （如果检测到代理设置）、@ref{2d39,,UnknownHandler} 、@ref{2d3d,,HTTPHandler} 、@ref{2d3e,,HTTPDefaultErrorHandler} 、@ref{2d3f,,HTTPRedirectHandler} 、 @ref{2d40,,FTPHandler} 、 @ref{2d41,,FileHandler} 、@ref{2d42,,HTTPErrorProcessor} 。

若 Python 安装时已带了 SSL 支持（指可以导入 @ref{f3,,ssl} 模块），则还会加入 @ref{c80,,HTTPSHandler} 。

A @ref{2d3c,,BaseHandler} subclass may also change its @code{handler_order}
attribute to modify its position in the handlers list.
@end deffn

@geindex pathname2url() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request pathname2url}@anchor{2d43}
@deffn {函数} urllib.request.pathname2url (path)

将路径名 @emph{path} 从路径本地写法转换为 URL 路径部分所采用的格式。本函数不会生成完整的 URL。返回值将会用 @ref{51a,,quote()} 函数加以编码。
@end deffn

@geindex url2pathname() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request url2pathname}@anchor{2d44}
@deffn {函数} urllib.request.url2pathname (path)

从百分号编码的 URL 中将 @emph{path} 部分转换为本地路径的写法。本函数不接受完整的 URL，并利用 @ref{1124,,unquote()} 函数对 @emph{path} 进行解码。
@end deffn

@geindex getproxies() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request getproxies}@anchor{2d45}
@deffn {函数} urllib.request.getproxies ()

此辅助函数将返回一个将各个方案映射到代理服务器 URL 的字典。 它会先为所有操作系统以大小写不敏感的方式扫描名为 @code{<scheme>_proxy} 的环境变量，当无法找到时，则会在 macOS 上从系统配置中而在 Windows 上从 Windows 系统注册表中查找代理信息。 如果同时存在小写和大写形式的环境变量（且内容不一致），则会首先小写形式。

@cartouche
@quotation 注解 
如果存在环境变量 @code{REQUEST_METHOD} ，通常表示脚本运行于 CGI 环境中，则环境变量 @code{HTTP_PROXY} （大写的 @code{_PROXY}）将会被忽略。这是因其可以由客户端用 HTTP 头部信息 “Proxy:”注入。若要在 CGI 环境中使用 HTTP 代理，请显式使用 @code{`ProxyHandler} ，或确保变量名称为小写（或至少是 @code{_proxy} 后缀）。
@end quotation
@end cartouche
@end deffn

提供了以下类：

@geindex Request (urllib.request 中的类)
@anchor{library/urllib request urllib request Request}@anchor{9e5}
@deffn {类} urllib.request.Request (url, data=None, headers=@{@}, origin_req_host=None, unverifiable=False, method=None)

URL 请求对象的抽象类。

@emph{url} 应为包含合法 URL 的字符串。

@emph{data} 必须是一个对象，用于给定发往服务器的附加数据，若无需此类数据则为 @code{None} 。 目前 唯一用到 @emph{data} 的只有 HTTP 请求。支持的对象类型包括字节串、类文件对象和可遍历的类字节串对象。如果没有提供 @code{Content-Length} 和  @code{Transfer-Encoding} 头部字段， @ref{2d3d,,HTTPHandler} 会根据 @emph{data} 的类型设置这些头部字段。@code{Content-Length} 将用于发送字节对象，而 
@geindex RFC; RFC 7230
RFC 7230@footnote{https://tools.ietf.org/html/rfc7230.html} 第 3.3.1 节中定义的 @code{Transfer-Encoding: chunked} 将用于发送文件和其他可遍历对象。

对于 HTTP POST 请求方法而言，@emph{data} 应该是标准 @code{application/x-www-form-urlencoded} 格式的缓冲区。 @ref{884,,urllib.parse.urlencode()} 函数的参数为映射对象或二元组序列，并返回一个该编码格式的 ASCII 字符串。在用作 @emph{data} 参数之前，应将其编码为字节串。

@emph{headers} 应当是一个字典，并将被视同附带了每个键和值作为参数去调用 @ref{2d46,,add_header()}。 这通常被用于 "伪装" @code{User-Agent} 标头值，浏览器会使用标头值来标识自己 -- 某些 HTTP 服务器只允许来自普通浏览器的请求而不允许来自脚本的请求。 例如，Mozilla Firefox 可能将自己标识为 @code{"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}，而 @ref{126,,urllib} 的默认用户代理字符串则是 @code{"Python-urllib/2.6"} (在 Python 2.6 中)。 所有发送的标头键都使用驼峰命名法。

如果给出了 @emph{data} 参数，则应当包含合适的 @code{Content-Type} 头部信息。若未提供且 @emph{data} 不是 None，则会把 @code{Content-Type: application/x-www-form-urlencoded} 加入作为默认值。

接下来的两个参数，只对第三方 HTTP cookie 的处理才有用：

@emph{origin_req_host} 应为发起初始会话的请求主机，定义参见 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 。默认指为`@w{`}http.cookiejar.request_host(self)`@w{`} 。这是用户发起初始请求的主机名或 IP 地址。假设请求是针对 HTML 文档中的图片数据发起的，则本属性应为对包含图像的页面发起请求的主机。

@emph{unverifiable} 应该标示出请求是否无法验证，定义参见 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 。默认值为 @code{False} 。所谓无法验证的请求，是指用户没有机会对请求的 URL 做验证。例如，如果请求是针对 HTML 文档中的图像，用户没有机会去许可能自动读取图像，则本参数应为 True。

@emph{method} 应为字符串，标示要采用的 HTTP 请求方法（例如 @code{'HEAD'} ）。如果给出本参数，其值会存储在 @ref{9e6,,method} 属性中，并由 @ref{ba2,,get_method()} 使用。如果 @emph{data} 为`@w{`}None`@w{`} 则默认值为 @code{'GET'} ，否则为 @code{'POST'}。子类可以设置 @ref{9e6,,method} 属性来标示不同的默认请求方法。

@cartouche
@quotation 注解 
如果 data 对象无法分多次传递其内容（比如文件或只能生成一次内容的可迭代对象）并且由于 HTTP 重定向或身份验证而发生请求重试行为，则该请求不会正常工作。 @emph{data} 是紧挨着头部信息发送给 HTTP 服务器的。现有库不支持 HTTP 100-continue 的征询。
@end quotation
@end cartouche


在 3.3 版更改: Request 类增加了 @ref{9e6,,Request.method} 参数。



在 3.4 版更改: 默认 @ref{9e6,,Request.method} 可以在类中标明。



在 3.6 版更改: 如果给出了 @code{Content-Length} ，且 @emph{data} 既不为 @code{None} 也不是字节串对象，则不会触发错误。而会退而求其次采用分块传输的编码格式。

@end deffn

@geindex OpenerDirector (urllib.request 中的类)
@anchor{library/urllib request urllib request OpenerDirector}@anchor{2d38}
@deffn {类} urllib.request.OpenerDirector

@ref{2d38,,OpenerDirector} 类通过串接在一起的 @ref{2d3c,,BaseHandler} 打开 URL，并负责管理 handler 链及从错误中恢复。
@end deffn

@geindex BaseHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request BaseHandler}@anchor{2d3c}
@deffn {类} urllib.request.BaseHandler

这是所有已注册 handler 的基类，只做了简单的注册机制。
@end deffn

@geindex HTTPDefaultErrorHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPDefaultErrorHandler}@anchor{2d3e}
@deffn {类} urllib.request.HTTPDefaultErrorHandler

为 HTTP 错误响应定义的默认 handler，所有出错响应都会转为 @ref{9eb,,HTTPError} 异常。
@end deffn

@geindex HTTPRedirectHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPRedirectHandler}@anchor{2d3f}
@deffn {类} urllib.request.HTTPRedirectHandler

一个用于处理重定向的类。
@end deffn

@geindex HTTPCookieProcessor (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPCookieProcessor}@anchor{2d47}
@deffn {类} urllib.request.HTTPCookieProcessor (cookiejar=None)

一个用于处理 HTTP Cookies 的类。
@end deffn

@geindex ProxyHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request ProxyHandler}@anchor{1121}
@deffn {类} urllib.request.ProxyHandler (proxies=None)

让请求转往代理服务。 如果给出了 @emph{proxies}，则它必须是一个将协议名称映射到代理 URL 的字典。 默认是从环境变量 @code{<protocol>_proxy} 中读取代理列表。 如果没有设置代理服务的环境变量，则在 Windows 环境下代理设置会从注册表的 Internet Settings 部分获取，而在 macOS 环境下代理信息会从 System Configuration Framework 获取。

若要禁用自动检测出来的代理，请传入空的字典对象。

环境变量 
@geindex no_proxy
@geindex 环境变量; no_proxy
@code{no_proxy} 可用于指定不必通过代理访问的主机；应为逗号分隔的主机名后缀列表，可加上 @code{:port} ，例如 @code{cern.ch,ncsa.uiuc.edu,some.host:8080} 。

@quotation

@cartouche
@quotation 注解 
如果设置了 @code{REQUEST_METHOD} 变量，则会忽略 @code{HTTP_PROXY} ；参阅 @ref{2d45,,getproxies()} 文档。
@end quotation
@end cartouche
@end quotation
@end deffn

@geindex HTTPPasswordMgr (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPPasswordMgr}@anchor{2d48}
@deffn {类} urllib.request.HTTPPasswordMgr

维护 @code{(realm, uri) -> (user, password)} 映射数据库。
@end deffn

@geindex HTTPPasswordMgrWithDefaultRealm (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithDefaultRealm}@anchor{2d49}
@deffn {类} urllib.request.HTTPPasswordMgrWithDefaultRealm

维护 @code{(realm, uri) -> (user, password)} 映射数据库。realm 为 @code{None} 视作全匹配，若没有其他合适的安全区域就会检索它。
@end deffn

@geindex HTTPPasswordMgrWithPriorAuth (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth}@anchor{883}
@deffn {类} urllib.request.HTTPPasswordMgrWithPriorAuth

@ref{2d49,,HTTPPasswordMgrWithDefaultRealm} 的一个变体，也带有 @code{uri -> is_authenticated} 映射数据库。可被 BasicAuth 处理函数用于确定立即发送身份认证凭据的时机，而不是先等待 @code{401} 响应。


3.5 新版功能.

@end deffn

@geindex AbstractBasicAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request AbstractBasicAuthHandler}@anchor{fed}
@deffn {类} urllib.request.AbstractBasicAuthHandler (password_mgr=None)

这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参数 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；关于必须支持哪些接口，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 对象的章节。如果 @emph{password_mgr} 还提供 @code{is_authenticated} 和 @code{update_authenticated} 方法（请参阅 @ref{2d4b,,HTTPPasswordMgrWithPriorAuth 对象} 对象），则 handler 将对给定 URI 用到 @code{is_authenticated} 的结果，来确定是否随请求发送身份认证凭据。如果该 URI 的 @code{is_authenticated}  返回 @code{True}，则发送凭据。如果 @code{is_authenticated} 为 @code{False} ，则不发送凭据，然后若收到 @code{401} 响应，则使用身份认证凭据重新发送请求。如果身份认证成功，则调用 @code{update_authenticated} 设置该 URI 的 @code{is_authenticated} 为 @code{True}，这样后续对该 URI 或其所有父 URI 的请求将自动包含该身份认证凭据。


3.5 新版功能: 增加了对 @code{is_authenticated} 的支持。

@end deffn

@geindex HTTPBasicAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPBasicAuthHandler}@anchor{2d4c}
@deffn {类} urllib.request.HTTPBasicAuthHandler (password_mgr=None)

处理远程主机的身份认证。 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；有关哪些接口是必须支持的，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 章节。如果给出错误的身份认证方式， HTTPBasicAuthHandler 将会触发 @ref{16d,,ValueError} 。
@end deffn

@geindex ProxyBasicAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request ProxyBasicAuthHandler}@anchor{2d4d}
@deffn {类} urllib.request.ProxyBasicAuthHandler (password_mgr=None)

处理有代理服务时的身份认证。 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；有关哪些接口是必须支持的，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 章节。
@end deffn

@geindex AbstractDigestAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request AbstractDigestAuthHandler}@anchor{10b5}
@deffn {类} urllib.request.AbstractDigestAuthHandler (password_mgr=None)

这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参数 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；关于必须支持哪些接口，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 的章节。
@end deffn

@geindex HTTPDigestAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPDigestAuthHandler}@anchor{2d4e}
@deffn {类} urllib.request.HTTPDigestAuthHandler (password_mgr=None)

处理远程主机的身份认证。 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；有关哪些接口是必须支持的，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 章节。如果同时添加了 digest 身份认证 handler 和basic 身份认证 handler，则会首先尝试 digest 身份认证。如果 digest 身份认证再返回 40x 响应，会再发送到 basic 身份验证 handler 进行处理。如果给出 Digest 和 Basic 之外的身份认证方式， 本 handler 方法将会触发 @ref{16d,,ValueError} 。


在 3.3 版更改: 碰到不支持的认证方式时，将会触发 @ref{16d,,ValueError} 。

@end deffn

@geindex ProxyDigestAuthHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request ProxyDigestAuthHandler}@anchor{2d4f}
@deffn {类} urllib.request.ProxyDigestAuthHandler (password_mgr=None)

处理有代理服务时的身份认证。 @emph{password_mgr} 应与 @ref{2d48,,HTTPPasswordMgr} 兼容；有关哪些接口是必须支持的，请参阅 @ref{2d4a,,HTTPPasswordMgr 对象} 章节。
@end deffn

@geindex HTTPHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPHandler}@anchor{2d3d}
@deffn {类} urllib.request.HTTPHandler

用于打开 HTTP URL 的 handler 类。
@end deffn

@geindex HTTPSHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPSHandler}@anchor{c80}
@deffn {类} urllib.request.HTTPSHandler (debuglevel=0, context=None, check_hostname=None)

用于打开 HTTPS URL 的 handler 类。@emph{context} 和 @emph{check_hostname} 的含义与  @ref{4a2,,http.client.HTTPSConnection} 的一样。


在 3.2 版更改: 添加 @emph{context} 和 @emph{check_hostname} 参数。

@end deffn

@geindex FileHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request FileHandler}@anchor{2d41}
@deffn {类} urllib.request.FileHandler

打开本地文件。
@end deffn

@geindex DataHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request DataHandler}@anchor{9e4}
@deffn {类} urllib.request.DataHandler

打开数据 URL。


3.4 新版功能.

@end deffn

@geindex FTPHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request FTPHandler}@anchor{2d40}
@deffn {类} urllib.request.FTPHandler

打开 FTP URL。
@end deffn

@geindex CacheFTPHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request CacheFTPHandler}@anchor{2d50}
@deffn {类} urllib.request.CacheFTPHandler

打开 FTP URL，并将打开的 FTP 连接存入缓存，以便最大程度减少延迟。
@end deffn

@geindex UnknownHandler (urllib.request 中的类)
@anchor{library/urllib request urllib request UnknownHandler}@anchor{2d39}
@deffn {类} urllib.request.UnknownHandler

处理所有未知类型 URL 的兜底类。
@end deffn

@geindex HTTPErrorProcessor (urllib.request 中的类)
@anchor{library/urllib request urllib request HTTPErrorProcessor}@anchor{2d42}
@deffn {类} urllib.request.HTTPErrorProcessor

处理出错的 HTTP 响应。
@end deffn

@menu
* Request 对象:: 
* OpenerDirector 对象:: 
* BaseHandler 对象:: 
* HTTPRedirectHandler 对象:: 
* HTTPCookieProcessor 对象:: 
* ProxyHandler 对象:: 
* HTTPPasswordMgr 对象:: 
* HTTPPasswordMgrWithPriorAuth 对象:: 
* AbstractBasicAuthHandler 对象:: 
* HTTPBasicAuthHandler 对象:: 
* ProxyBasicAuthHandler 对象:: 
* AbstractDigestAuthHandler 对象:: 
* HTTPDigestAuthHandler 对象:: 
* ProxyDigestAuthHandler 对象:: 
* HTTPHandler 对象:: 
* HTTPSHandler 对象:: 
* FileHandler 对象:: 
* DataHandler 对象:: 
* FTPHandler 对象:: 
* CacheFTPHandler 对象:: 
* UnknownHandler 对象:: 
* HTTPErrorProcessor 对象:: 
* 示例: 示例<33>. 
* 沿袭的接口:: 
* urllib.request 的限制: urllib request 的限制. 

@end menu

@node Request 对象,OpenerDirector 对象,,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request id1}@anchor{2d51}@anchor{library/urllib request request-objects}@anchor{2d52}
@subsubsection Request 对象


以下方法介绍了 @ref{9e5,,Request} 的公开接口，因此子类可以覆盖所有这些方法。这里还定义了几个公开属性，客户端可以利用这些属性了解经过解析的请求。

@geindex full_url (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request full_url}@anchor{9e7}
@deffn {属性} Request.full_url

传给构造函数的原始 URL。


在 3.4 版更改.


Request.full_url 是一个带有 setter、getter 和 deleter 的属性。读取 @ref{9e7,,full_url} 属性将会返回附带片段（fragment）的初始请求 URL。
@end deffn

@geindex type (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request type}@anchor{2d53}
@deffn {属性} Request.type

URI 方式。
@end deffn

@geindex host (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request host}@anchor{2d54}
@deffn {属性} Request.host

URI 权限，通常是整个主机，但也有可能带有冒号分隔的端口号。
@end deffn

@geindex origin_req_host (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request origin_req_host}@anchor{2d55}
@deffn {属性} Request.origin_req_host

请求的原始主机，不含端口。
@end deffn

@geindex selector (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request selector}@anchor{2d56}
@deffn {属性} Request.selector

URI 路径。若 @ref{9e5,,Request} 使用代理，selector 将会是传给代理的完整 URL。
@end deffn

@geindex data (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request data}@anchor{9e8}
@deffn {属性} Request.data

请求的数据体，未给出则为 @code{None} 。


在 3.4 版更改: 现在如果修改 @ref{9e8,,Request.data} 的值，则会删除之前设置或计算过的“Content-Length”头部信息。

@end deffn

@geindex unverifiable (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request unverifiable}@anchor{2d57}
@deffn {属性} Request.unverifiable

布尔值，标识本请求是否属于 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 中定义的无法验证的情况。
@end deffn

@geindex method (urllib.request.Request 属性)
@anchor{library/urllib request urllib request Request method}@anchor{9e6}
@deffn {属性} Request.method

要采用的 HTTP 请求方法。默认为 @ref{204,,None}，表示 @ref{ba2,,get_method()} 将对方法进行正常处理。设置本值可以覆盖 @ref{ba2,,get_method()} 中的默认处理过程，设置方式可以是在 @ref{9e5,,Request} 的子类中给出默认值，也可以通过 @emph{method} 参数给 @ref{9e5,,Request} 构造函数传入一个值。


3.3 新版功能.



在 3.4 版更改: 现在可以在子类中设置默认值；而之前只能通过构造函数的实参进行设置。

@end deffn

@geindex get_method() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request get_method}@anchor{ba2}
@deffn {方法} Request.get_method ()

返回表示 HTTP  请求方法的字符串。如果 @ref{9e6,,Request.method} 不为  @code{None} ，则返回其值。否则若  @ref{9e8,,Request.data} 为  则返回 @code{'GET'}，不为 @code{None} 则返回 @code{'POST'} 。只对 HTTP 请求有效。


在 3.3 版更改: 现在 get_method 会兼顾 @ref{9e6,,Request.method} 的值。

@end deffn

@geindex add_header() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request add_header}@anchor{2d46}
@deffn {方法} Request.add_header (key, val)

向请求添加一个标头。 标头目前会被所有处理句柄忽略但只有 HTTP 处理句柄是例外，该处理句柄会将它们加入发给服务器的标头列表中。 请注意同名的标头只能有一个，当 @emph{key} 发生冲突时后续的调用将会覆盖之前的调用。 目前，这并不会造成 HTTP 功能的损失，因为所有可多次使用而仍有意义的标头都有（特定标头专属的）方式来获得与仅使用一个标头时相同的功能。 请注意使用此方法添加的标头也会被添加到重定向的请求中。
@end deffn

@geindex add_unredirected_header() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request add_unredirected_header}@anchor{2d58}
@deffn {方法} Request.add_unredirected_header (key, header)

添加一项不会被加入重定向请求的头部信息。
@end deffn

@geindex has_header() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request has_header}@anchor{2d59}
@deffn {方法} Request.has_header (header)

返回本实例是否带有命名头部信息（对常规数据和非重定向数据都会检测）。
@end deffn

@geindex remove_header() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request remove_header}@anchor{9ea}
@deffn {方法} Request.remove_header (header)

从本请求实例中移除指定命名的头部信息（对常规数据和非重定向数据都会检测）。


3.4 新版功能.

@end deffn

@geindex get_full_url() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request get_full_url}@anchor{2d5a}
@deffn {方法} Request.get_full_url ()

返回构造器中给定的 URL。


在 3.4 版更改.


返回 @ref{9e7,,Request.full_url}
@end deffn

@geindex set_proxy() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request set_proxy}@anchor{2d5b}
@deffn {方法} Request.set_proxy (host, type)

连接代理服务器，为当前请求做准备。 @emph{host} 和 @emph{type} 将会取代本实例中的对应值，selector 将会是构造函数中给出的初始 URL。
@end deffn

@geindex get_header() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request get_header}@anchor{2d5c}
@deffn {方法} Request.get_header (header_name, default=None)

返回给定头部信息的数据。如果该头部信息不存在，返回默认值。
@end deffn

@geindex header_items() (urllib.request.Request 方法)
@anchor{library/urllib request urllib request Request header_items}@anchor{2d5d}
@deffn {方法} Request.header_items ()

返回头部信息，形式为（名称, 数据）的元组列表。
@end deffn


在 3.4 版更改: 自 3.3 起已弃用的下列方法已被删除：add_data、has_data、get_data、get_type、get_host、get_selector、get_origin_req_host 和 is_unverifiable 。


@node OpenerDirector 对象,BaseHandler 对象,Request 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request opener-director-objects}@anchor{2d5e}@anchor{library/urllib request openerdirector-objects}@anchor{2d5f}
@subsubsection OpenerDirector 对象


@ref{2d38,,OpenerDirector} 实例有以下方法：

@geindex add_handler() (urllib.request.OpenerDirector 方法)
@anchor{library/urllib request urllib request OpenerDirector add_handler}@anchor{2d60}
@deffn {方法} OpenerDirector.add_handler (handler)

@emph{handler} 应为 @ref{2d3c,,BaseHandler} 的实例。将检索以下类型的方法，并将其添加到对应的处理链中（注意 HTTP 错误是特殊情况）。请注意，下文中的 @emph{protocol} 应替换为要处理的实际协议，例如 @code{http_response()} 将是 HTTP 协议响应处理函数。并且 @emph{type} 也应替换为实际的 HTTP 代码，例如 @code{http_error_404()} 将处理 HTTP 404 错误。


@itemize *

@item 
@code{<protocol>_open()} — 表明该  handler 知道如何打开 @emph{protocol} 协议的URL。

更多信息请参阅 @ref{2d61,,BaseHandler.<protocol>_open()} 。

@item 
@code{http_error_<type>()} — 表明该  handler 知道如何处理代码为 @emph{type} 的 HTTP 错误。

更多信息请参阅 @ref{2d62,,BaseHandler.http_error_<nnn>()} 。

@item 
@code{<protocol>_error()} — 表明该 handler 知道如何处理来自协议为 @emph{protocol} （非@code{http}）的错误。

@item 
@code{<protocol>_request()} — 表明该 handler 知道如何预处理协议为 @emph{protocol} 的请求。

更多信息请参阅 @ref{2d63,,BaseHandler.<protocol>_request()} 。

@item 
@code{<protocol>_response()} — 表明该 handler 知道如何后处理协议为 @emph{protocol} 的响应。

更多信息请参阅 @ref{2d64,,BaseHandler.<protocol>_response()} 。
@end itemize
@end deffn

@geindex open() (urllib.request.OpenerDirector 方法)
@anchor{library/urllib request urllib request OpenerDirector open}@anchor{9e9}
@deffn {方法} OpenerDirector.open (url, data=None[, timeout])

打开给定的 @emph{url} (可以是一个请求对象或一个字符串），可以选择传入给定的 @emph{data}。 参数、返回值和被引发的异常均与 @ref{885,,urlopen()} 的相同 (它只是简单地在当前安装的全局 @ref{2d38,,OpenerDirector} 上调用 @ref{16f,,open()} 方法)。 可选的 @emph{timeout} 形参指定了针对阻塞操作例如连接尝试的超时值 (如果未指明，则将使用全局默认的超时设置)。 超时特性仅适用于 HTTP, HTTPS 和 FTP 连接。
@end deffn

@geindex error() (urllib.request.OpenerDirector 方法)
@anchor{library/urllib request urllib request OpenerDirector error}@anchor{2d65}
@deffn {方法} OpenerDirector.error (proto, *args)

处理给定协议的错误。将用给定的参数（协议相关）调用已注册的给定协议的错误处理程序。HTTP 协议是特殊情况，采用 HTTP 响应码来确定具体的错误处理程序；请参考 handler 类的 @code{http_error_<type>()} 方法。

返回值和异常均与 @ref{885,,urlopen()} 相同。
@end deffn

OpenerDirector 对象分 3 个阶段打开 URL：

每个阶段中调用这些方法的次序取决于 handler 实例的顺序。


@enumerate 

@item 
每个具有 @code{_request()} 这类方法的 handler 都会调用本方法对请求进行预处理。

@item 
调用具有 @code{_open()} 这类方法的 handler 来处理请求。当 handler 返回非@ref{204,,None} 值（即响应）或引发异常（通常是 @ref{2d37,,URLError}）时，本阶段结束。本阶段能够传播异常。

事实上，以上算法首先会尝试名为 @code{default_open()} 的。如果这些方法全都返回 @ref{204,,None}，则会对名为 @code{_open()} 的这类方法重复过程。如果又都返回 @ref{204,,None}，则再对名为 @code{unknown_open()} 的方法重复过程。

请注意，这些方法的代码可能会调用 @ref{2d38,,OpenerDirector} 父实例的 @ref{9e9,,open()} 和 @ref{2d65,,error()} 方法。

@item 
每个具有 @code{_response()} 这类方法的 handler 都会调用这些方法，以对响应进行后处理。
@end enumerate

@node BaseHandler 对象,HTTPRedirectHandler 对象,OpenerDirector 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request base-handler-objects}@anchor{2d66}@anchor{library/urllib request basehandler-objects}@anchor{2d67}
@subsubsection BaseHandler 对象


@ref{2d3c,,BaseHandler} 对象提供了一些直接可用的方法，以及其他一些可供派生类使用的方法。以下是可供直接使用的方法：

@geindex add_parent() (urllib.request.BaseHandler 方法)
@anchor{library/urllib request urllib request BaseHandler add_parent}@anchor{2d68}
@deffn {方法} BaseHandler.add_parent (director)

将 director 加为父 OpenerDirector。
@end deffn

@geindex close() (urllib.request.BaseHandler 方法)
@anchor{library/urllib request urllib request BaseHandler close}@anchor{2d69}
@deffn {方法} BaseHandler.close ()

移除所有父 OpenerDirector。
@end deffn

以下属性和方法仅供 @ref{2d3c,,BaseHandler} 的子类使用：

@cartouche
@quotation 注解 
以下约定已被采纳：定义 @code{<protocol>_request()} 或 @code{<protocol>_response()} 方法的子类应命名为 @code{*Processor}；所有其他子类都应命名为 @code{*Handler} 。
@end quotation
@end cartouche

@geindex parent (urllib.request.BaseHandler 属性)
@anchor{library/urllib request urllib request BaseHandler parent}@anchor{2d6a}
@deffn {属性} BaseHandler.parent

一个可用的 @ref{2d38,,OpenerDirector}，可用于以其他协议打开 URI，或处理错误。
@end deffn

@geindex default_open() (urllib.request.BaseHandler 方法)
@anchor{library/urllib request urllib request BaseHandler default_open}@anchor{2d6b}
@deffn {方法} BaseHandler.default_open (req)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要捕获所有 URL 则应进行定义。

如果实现了本方法，则它将被父类 @ref{2d38,,OpenerDirector} 所调用。 它应当返回一个如 @ref{2d38,,OpenerDirector} 的 @ref{9e9,,open()} 方法的返回值所描述的文件类对象，或是返回 @code{None}。 它应当引发 @ref{2d37,,URLError}，除非发生真正的异常 (例如，@ref{fb5,,MemoryError} 就不应被映射为 @code{URLError})。

本方法将会在所有协议的 open 方法之前被调用。
@end deffn
@anchor{library/urllib request protocol-open}@anchor{2d61}

@deffn {方法} BaseHandler.<protocol>_open(req)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要处理给定协议的 URL 则应进行定义。

若定义了本方法，将会被父 @ref{2d38,,OpenerDirector} 对象调用。返回值和 @code{default_open()} 的一样。
@end deffn

@geindex unknown_open() (urllib.request.BaseHandler 方法)
@anchor{library/urllib request urllib request BaseHandler unknown_open}@anchor{2d6c}
@deffn {方法} BaseHandler.unknown_open (req)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要捕获并打开所有未注册 handler 的 URL，则应进行定义。

若实现了本方法，将会被 @ref{2d6a,,parent} 属性指向的父 @ref{2d38,,OpenerDirector} 调用。返回值和 @ref{2d6b,,default_open()} 的一样。
@end deffn

@geindex http_error_default() (urllib.request.BaseHandler 方法)
@anchor{library/urllib request urllib request BaseHandler http_error_default}@anchor{2d6d}
@deffn {方法} BaseHandler.http_error_default (req, fp, code, msg, hdrs)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要为所有未定义 handler 的 HTTP 错误提供一个兜底方法，则应进行重写。@ref{2d38,,OpenerDirector} 会自动调用本方法，获取错误信息，而通常在其他时候不应去调用。

@emph{req} 会是一个 @ref{9e5,,Request} 对象，@emph{fp} 是一个带有 HTTP 错误体的文件类对象，@emph{code} 是三位数的错误码，@emph{msg} 是供用户阅读的解释信息，@emph{hdrs} 则是一个包含出错头部信息的字典对象。

返回值和触发的异常应与 @ref{885,,urlopen()} 的相同。
@end deffn
@anchor{library/urllib request http-error-nnn}@anchor{2d62}

@deffn {方法} BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)

@emph{nnn} 应为三位数的 HTTP 错误码。本方法在 @ref{2d3c,,BaseHandler} 中也未予定义，但当子类的实例发生代码为 @emph{nnn} 的 HTTP 错误时，若方法存在则会被调用。

子类应该重写本方法，以便能处理相应的 HTTP 错误。

参数、返回值和触发的异常应与 @code{http_error_default()} 相同。
@end deffn
@anchor{library/urllib request protocol-request}@anchor{2d63}

@deffn {方法} BaseHandler.<protocol>_request(req)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要对给定协议的请求进行预处理，则应进行定义。

若实现了本方法，将会被父 @ref{2d38,,OpenerDirector} 调用。@emph{req} 将为 @ref{9e5,,Request} 对象。返回值应为 @ref{9e5,,Request} 对象。
@end deffn
@anchor{library/urllib request protocol-response}@anchor{2d64}

@deffn {方法} BaseHandler.<protocol>_response(req, response)

本方法在 @ref{2d3c,,BaseHandler} 中 @emph{未} 予定义，但其子类若要对给定协议的请求进行后处理，则应进行定义。

若实现了本方法，将会被父 @ref{2d38,,OpenerDirector} 调用。@emph{req} 将为 @ref{9e5,,Request} 对象。@emph{response} 应实现与  @ref{885,,urlopen()} 返回值相同的接口。返回值应实现与 @ref{885,,urlopen()} 返回值相同的接口。
@end deffn

@node HTTPRedirectHandler 对象,HTTPCookieProcessor 对象,BaseHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-redirect-handler}@anchor{2d6e}@anchor{library/urllib request httpredirecthandler-objects}@anchor{2d6f}
@subsubsection HTTPRedirectHandler 对象


@cartouche
@quotation 注解 
某些 HTTP 重定向操作需要本模块的客户端代码提供的功能。这时会触发 @ref{9eb,,HTTPError}。有关各种重定向代码的确切含义，请参阅 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 。

如果给到 HTTPRedirectHandler 的重定向 URL 不是 HTTP、HTTPS 或 FTP URL，则出于安全考虑将触发 @code{HTTPError} 异常。
@end quotation
@end cartouche

@geindex redirect_request() (urllib.request.HTTPRedirectHandler 方法)
@anchor{library/urllib request urllib request HTTPRedirectHandler redirect_request}@anchor{2d70}
@deffn {方法} HTTPRedirectHandler.redirect_request (req, fp, code, msg, hdrs, newurl)

返回 @ref{9e5,,Request} 或 @code{None} 对象作为重定向行为的响应。当服务器接收到重定向请求时， @code{http_error_30*()} 方法的默认实现代码将会调用本方法。如果确实应该发生重定向，则返回一个新的 @ref{9e5,,Request} 对象，使得 @code{http_error_30*()} 能重定向至 @emph{newurl}。否则，若没有 handler 会处理此 URL，则会引发 @ref{9eb,,HTTPError}；或者本方法不能处理但或许会有其他 handler 会处理，则返回 @code{None} 。

@cartouche
@quotation 注解 
本方法的默认实现代码并未严格遵循 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html}，即 @code{POST} 请求的 301 和 302 响应不得在未经用户确认的情况下自动进行重定向。现实情况下，浏览器确实允许自动重定向这些响应，将 POST 更改为 @code{GET} ，于是默认实现代码就复现了这种处理方式。
@end quotation
@end cartouche
@end deffn

@geindex http_error_301() (urllib.request.HTTPRedirectHandler 方法)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_301}@anchor{2d71}
@deffn {方法} HTTPRedirectHandler.http_error_301 (req, fp, code, msg, hdrs)

重定向到 @code{Location:} 或 @code{URI:} URL。 这个方法会在得到 HTTP 'moved permanently' 响应时由上级 @ref{2d38,,OpenerDirector} 来调用。
@end deffn

@geindex http_error_302() (urllib.request.HTTPRedirectHandler 方法)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_302}@anchor{2d72}
@deffn {方法} HTTPRedirectHandler.http_error_302 (req, fp, code, msg, hdrs)

与  @ref{2d71,,http_error_301()} 相同，不过是发生“found”响应时的调用。
@end deffn

@geindex http_error_303() (urllib.request.HTTPRedirectHandler 方法)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_303}@anchor{2d73}
@deffn {方法} HTTPRedirectHandler.http_error_303 (req, fp, code, msg, hdrs)

与  @ref{2d71,,http_error_301()} 相同，不过是发生“see other”响应时的调用。
@end deffn

@geindex http_error_307() (urllib.request.HTTPRedirectHandler 方法)
@anchor{library/urllib request urllib request HTTPRedirectHandler http_error_307}@anchor{2d74}
@deffn {方法} HTTPRedirectHandler.http_error_307 (req, fp, code, msg, hdrs)

与  @ref{2d71,,http_error_301()} 相同，不过是发生“temporary redirect”响应时的调用。
@end deffn

@node HTTPCookieProcessor 对象,ProxyHandler 对象,HTTPRedirectHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-cookie-processor}@anchor{2d75}@anchor{library/urllib request httpcookieprocessor-objects}@anchor{2d76}
@subsubsection HTTPCookieProcessor 对象


@ref{2d47,,HTTPCookieProcessor} 的实例具备一个属性：

@geindex cookiejar (urllib.request.HTTPCookieProcessor 属性)
@anchor{library/urllib request urllib request HTTPCookieProcessor cookiejar}@anchor{2d77}
@deffn {属性} HTTPCookieProcessor.cookiejar

cookie 存放在 @ref{2d78,,http.cookiejar.CookieJar} 中。
@end deffn

@node ProxyHandler 对象,HTTPPasswordMgr 对象,HTTPCookieProcessor 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request proxy-handler}@anchor{2d79}@anchor{library/urllib request proxyhandler-objects}@anchor{2d7a}
@subsubsection ProxyHandler 对象



@deffn {方法} ProxyHandler.<protocol>_open(request)

@ref{1121,,ProxyHandler} 将为每种 @emph{protocol} 准备一个 @code{_open()} 方法，在构造函数给出的 @emph{proxies} 字典中包含对应的代理服务器信息。通过调用 @code{request.set_proxy()}，本方法将把请求转为通过代理服务器，并会调用 handler 链中的下一个 handler 来完成对应的协议处理。
@end deffn

@node HTTPPasswordMgr 对象,HTTPPasswordMgrWithPriorAuth 对象,ProxyHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-password-mgr}@anchor{2d4a}@anchor{library/urllib request httppasswordmgr-objects}@anchor{2d7b}
@subsubsection HTTPPasswordMgr 对象


以下方法 @ref{2d48,,HTTPPasswordMgr} 和 @ref{2d49,,HTTPPasswordMgrWithDefaultRealm} 对象均有提供。

@geindex add_password() (urllib.request.HTTPPasswordMgr 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgr add_password}@anchor{2d7c}
@deffn {方法} HTTPPasswordMgr.add_password (realm, uri, user, passwd)

@emph{uri} 可以是单个 URI，也可以是 URI 列表。@emph{realm}、@emph{user} 和 @emph{passwd} 必须是字符串。这使得在为 @emph{realm} 和超级 URI 进行身份认证时，@code{(user, passwd)} 可用作认证令牌。
@end deffn

@geindex find_user_password() (urllib.request.HTTPPasswordMgr 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgr find_user_password}@anchor{f8e}
@deffn {方法} HTTPPasswordMgr.find_user_password (realm, authuri)

为给定 realm 和 URI 获取用户名和密码。如果没有匹配的用户名和密码，本方法将会返回 @code{(None, None)} 。

对于 @ref{2d49,,HTTPPasswordMgrWithDefaultRealm} 对象，如果给定 @emph{realm} 没有匹配的用户名和密码，将搜索 realm  @code{None}。
@end deffn

@node HTTPPasswordMgrWithPriorAuth 对象,AbstractBasicAuthHandler 对象,HTTPPasswordMgr 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-password-mgr-with-prior-auth}@anchor{2d4b}@anchor{library/urllib request httppasswordmgrwithpriorauth-objects}@anchor{2d7d}
@subsubsection HTTPPasswordMgrWithPriorAuth 对象


这是 @ref{2d49,,HTTPPasswordMgrWithDefaultRealm} 的扩展，以便对那些需要一直发送认证凭证的 URI 进行跟踪。

@geindex add_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth add_password}@anchor{2d7e}
@deffn {方法} HTTPPasswordMgrWithPriorAuth.add_password (realm, uri, user, passwd, is_authenticated=False)

@emph{realm}、@emph{uri}、@emph{user}、@emph{passwd} 的含义与 @ref{2d7c,,HTTPPasswordMgr.add_password()} 的相同。@emph{is_authenticated} 为给定 URI 或 URI 列表设置 @code{is_authenticated} 标志的初始值。如果 @emph{is_authenticated} 设为 @code{True} ，则会忽略 @emph{realm}。
@end deffn

@geindex find_user_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth find_user_password}@anchor{2d7f}
@deffn {方法} HTTPPasswordMgrWithPriorAuth.find_user_password (realm, authuri)

与 @ref{2d49,,HTTPPasswordMgrWithDefaultRealm} 对象的相同。
@end deffn

@geindex update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth update_authenticated}@anchor{2d80}
@deffn {方法} HTTPPasswordMgrWithPriorAuth.update_authenticated (self, uri, is_authenticated=False)

更新给定 @emph{uri} 或 URI 列表的 @code{is_authenticated} 标志。
@end deffn

@geindex is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 方法)
@anchor{library/urllib request urllib request HTTPPasswordMgrWithPriorAuth is_authenticated}@anchor{f8f}
@deffn {方法} HTTPPasswordMgrWithPriorAuth.is_authenticated (self, authuri)

返回给定 URI @code{is_authenticated} 标志的当前状态。
@end deffn

@node AbstractBasicAuthHandler 对象,HTTPBasicAuthHandler 对象,HTTPPasswordMgrWithPriorAuth 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request abstract-basic-auth-handler}@anchor{2d81}@anchor{library/urllib request abstractbasicauthhandler-objects}@anchor{2d82}
@subsubsection AbstractBasicAuthHandler 对象


@geindex http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler 方法)
@anchor{library/urllib request urllib request AbstractBasicAuthHandler http_error_auth_reqed}@anchor{2d83}
@deffn {方法} AbstractBasicAuthHandler.http_error_auth_reqed (authreq, host, req, headers)

通过获取用户名和密码并重新尝试请求，以处理身份认证请求。 @emph{authreq} 应该是请求中包含 realm 的头部信息名称，@emph{host} 指定了需要进行身份认证的 URL 和路径，@emph{req} 应为 (已失败的) @ref{9e5,,Request} 对象 ,  @emph{headers} 应该是出错的头部信息。

@emph{host} 要么是一个认证信息（例如 @code{"python.org"} ），要么是一个包含认证信息的 URL（如`@w{`}"@indicateurl{http://python.org/}"`@w{`} ）。 不论是哪种格式，认证信息中都不能包含用户信息（因此，@code{"python.org"} 和 @code{"python.org:80"} 没问题，而 @code{"joe:password@@python.org"} 则不行）。
@end deffn

@node HTTPBasicAuthHandler 对象,ProxyBasicAuthHandler 对象,AbstractBasicAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-basic-auth-handler}@anchor{2d84}@anchor{library/urllib request httpbasicauthhandler-objects}@anchor{2d85}
@subsubsection HTTPBasicAuthHandler 对象


@geindex http_error_401() (urllib.request.HTTPBasicAuthHandler 方法)
@anchor{library/urllib request urllib request HTTPBasicAuthHandler http_error_401}@anchor{2d86}
@deffn {方法} HTTPBasicAuthHandler.http_error_401 (req, fp, code, msg, hdrs)

如果可用的话，请用身份认证信息重试请求。
@end deffn

@node ProxyBasicAuthHandler 对象,AbstractDigestAuthHandler 对象,HTTPBasicAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request proxy-basic-auth-handler}@anchor{2d87}@anchor{library/urllib request proxybasicauthhandler-objects}@anchor{2d88}
@subsubsection ProxyBasicAuthHandler 对象


@geindex http_error_407() (urllib.request.ProxyBasicAuthHandler 方法)
@anchor{library/urllib request urllib request ProxyBasicAuthHandler http_error_407}@anchor{2d89}
@deffn {方法} ProxyBasicAuthHandler.http_error_407 (req, fp, code, msg, hdrs)

如果可用的话，请用身份认证信息重试请求。
@end deffn

@node AbstractDigestAuthHandler 对象,HTTPDigestAuthHandler 对象,ProxyBasicAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request abstract-digest-auth-handler}@anchor{2d8a}@anchor{library/urllib request abstractdigestauthhandler-objects}@anchor{2d8b}
@subsubsection AbstractDigestAuthHandler 对象


@geindex http_error_auth_reqed() (urllib.request.AbstractDigestAuthHandler 方法)
@anchor{library/urllib request urllib request AbstractDigestAuthHandler http_error_auth_reqed}@anchor{2d8c}
@deffn {方法} AbstractDigestAuthHandler.http_error_auth_reqed (authreq, host, req, headers)

@emph{authreq} 应为请求中有关 realm 的头部信息名称，@emph{host} 应为需要进行身份认证的主机，@emph{req} 应为（已失败的） @ref{9e5,,Request} 对象， @emph{headers} 则应为出错的头部信息。
@end deffn

@node HTTPDigestAuthHandler 对象,ProxyDigestAuthHandler 对象,AbstractDigestAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-digest-auth-handler}@anchor{2d8d}@anchor{library/urllib request httpdigestauthhandler-objects}@anchor{2d8e}
@subsubsection HTTPDigestAuthHandler 对象


@geindex http_error_401() (urllib.request.HTTPDigestAuthHandler 方法)
@anchor{library/urllib request urllib request HTTPDigestAuthHandler http_error_401}@anchor{2d8f}
@deffn {方法} HTTPDigestAuthHandler.http_error_401 (req, fp, code, msg, hdrs)

如果可用的话，请用身份认证信息重试请求。
@end deffn

@node ProxyDigestAuthHandler 对象,HTTPHandler 对象,HTTPDigestAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request proxy-digest-auth-handler}@anchor{2d90}@anchor{library/urllib request proxydigestauthhandler-objects}@anchor{2d91}
@subsubsection ProxyDigestAuthHandler 对象


@geindex http_error_407() (urllib.request.ProxyDigestAuthHandler 方法)
@anchor{library/urllib request urllib request ProxyDigestAuthHandler http_error_407}@anchor{2d92}
@deffn {方法} ProxyDigestAuthHandler.http_error_407 (req, fp, code, msg, hdrs)

如果可用的话，请用身份认证信息重试请求。
@end deffn

@node HTTPHandler 对象,HTTPSHandler 对象,ProxyDigestAuthHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-handler-objects}@anchor{2d93}@anchor{library/urllib request httphandler-objects}@anchor{2d94}
@subsubsection HTTPHandler 对象


@geindex http_open() (urllib.request.HTTPHandler 方法)
@anchor{library/urllib request urllib request HTTPHandler http_open}@anchor{2d95}
@deffn {方法} HTTPHandler.http_open (req)

发送 HTTP 请求，根据 @code{req.has_data()} 的结果，可能是 GET 或 POST 格式。
@end deffn

@node HTTPSHandler 对象,FileHandler 对象,HTTPHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request https-handler-objects}@anchor{2d96}@anchor{library/urllib request httpshandler-objects}@anchor{2d97}
@subsubsection HTTPSHandler 对象


@geindex https_open() (urllib.request.HTTPSHandler 方法)
@anchor{library/urllib request urllib request HTTPSHandler https_open}@anchor{2d98}
@deffn {方法} HTTPSHandler.https_open (req)

发送 HTTPS 请求，根据 @code{req.has_data()} 的结果，可能是 GET 或 POST 格式。
@end deffn

@node FileHandler 对象,DataHandler 对象,HTTPSHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request file-handler-objects}@anchor{2d99}@anchor{library/urllib request filehandler-objects}@anchor{2d9a}
@subsubsection FileHandler 对象


@geindex file_open() (urllib.request.FileHandler 方法)
@anchor{library/urllib request urllib request FileHandler file_open}@anchor{2d9b}
@deffn {方法} FileHandler.file_open (req)

若无主机名或主机名为 @code{'localhost'} ，则打开本地文件。


在 3.2 版更改: 本方法仅适用于本地主机名。如果给出的是远程主机名，将会触发 @ref{2d37,,URLError} 。

@end deffn

@node DataHandler 对象,FTPHandler 对象,FileHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request data-handler-objects}@anchor{2d9c}@anchor{library/urllib request datahandler-objects}@anchor{2d9d}
@subsubsection DataHandler 对象


@geindex data_open() (urllib.request.DataHandler 方法)
@anchor{library/urllib request urllib request DataHandler data_open}@anchor{2d9e}
@deffn {方法} DataHandler.data_open (req)

读取内含数据的 URL。这种 URL 本身包含了经过编码的数据。 
@geindex RFC; RFC 2397
RFC 2397@footnote{https://tools.ietf.org/html/rfc2397.html} 中给出了数据 URL 的语法定义。目前的代码库将忽略经过 base64 编码的数据 URL 中的空白符，因此 URL 可以放入任何源码文件中。如果数据 URL 的 base64 编码尾部缺少填充，即使某些浏览器不介意，但目前的代码库仍会引发 @ref{16d,,ValueError}。
@end deffn

@node FTPHandler 对象,CacheFTPHandler 对象,DataHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request ftp-handler-objects}@anchor{2d9f}@anchor{library/urllib request ftphandler-objects}@anchor{2da0}
@subsubsection FTPHandler 对象


@geindex ftp_open() (urllib.request.FTPHandler 方法)
@anchor{library/urllib request urllib request FTPHandler ftp_open}@anchor{2da1}
@deffn {方法} FTPHandler.ftp_open (req)

打开由 @emph{req} 给出的 FTP 文件。登录时的用户名和密码总是为空。
@end deffn

@node CacheFTPHandler 对象,UnknownHandler 对象,FTPHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request cacheftp-handler-objects}@anchor{2da2}@anchor{library/urllib request cacheftphandler-objects}@anchor{2da3}
@subsubsection CacheFTPHandler 对象


@ref{2d50,,CacheFTPHandler} 对象即为加入以下方法的 @ref{2d40,,FTPHandler} 对象：

@geindex setTimeout() (urllib.request.CacheFTPHandler 方法)
@anchor{library/urllib request urllib request CacheFTPHandler setTimeout}@anchor{2da4}
@deffn {方法} CacheFTPHandler.setTimeout (t)

设置连接超时为 @emph{t} 秒。
@end deffn

@geindex setMaxConns() (urllib.request.CacheFTPHandler 方法)
@anchor{library/urllib request urllib request CacheFTPHandler setMaxConns}@anchor{2da5}
@deffn {方法} CacheFTPHandler.setMaxConns (m)

设置已缓存的最大连接数为 @emph{m} 。
@end deffn

@node UnknownHandler 对象,HTTPErrorProcessor 对象,CacheFTPHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request unknown-handler-objects}@anchor{2da6}@anchor{library/urllib request unknownhandler-objects}@anchor{2da7}
@subsubsection UnknownHandler 对象


@geindex unknown_open() (urllib.request.UnknownHandler 方法)
@anchor{library/urllib request urllib request UnknownHandler unknown_open}@anchor{2da8}
@deffn {方法} UnknownHandler.unknown_open ()

触发 @ref{2d37,,URLError} 异常。
@end deffn

@node HTTPErrorProcessor 对象,示例<33>,UnknownHandler 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request http-error-processor-objects}@anchor{2da9}@anchor{library/urllib request httperrorprocessor-objects}@anchor{2daa}
@subsubsection HTTPErrorProcessor 对象


@geindex http_response() (urllib.request.HTTPErrorProcessor 方法)
@anchor{library/urllib request urllib request HTTPErrorProcessor http_response}@anchor{2dab}
@deffn {方法} HTTPErrorProcessor.http_response (request, response)

处理出错的 HTTP 响应。

对于 200 错误码，响应对象将立即返回。

对于 200 以外的错误码，只通过 @ref{2d65,,OpenerDirector.error()} 将任务传给 handler 的 @code{http_error_<type>()} 方法。如果最终没有 handler 处理错误， @ref{2d3e,,HTTPDefaultErrorHandler} 将触发 @ref{9eb,,HTTPError}。
@end deffn

@geindex https_response() (urllib.request.HTTPErrorProcessor 方法)
@anchor{library/urllib request urllib request HTTPErrorProcessor https_response}@anchor{2dac}
@deffn {方法} HTTPErrorProcessor.https_response (request, response)

HTTPS 出错响应的处理。

与 @ref{2dab,,http_response()} 方法相同。
@end deffn

@node 示例<33>,沿袭的接口,HTTPErrorProcessor 对象,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request examples}@anchor{2dad}@anchor{library/urllib request urllib-request-examples}@anchor{2dae}
@subsubsection 示例


@ref{2daf,,如何利用 urllib 包获取网络资源} 中给出了更多的示例。

以下示例将读取 python.org 主页并显示前 300 个字节的内容：

@example
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))
...
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
<title>Python Programming '
@end example

请注意，urlopen 将返回字节串对象。这是因为 urlopen 无法自动确定由 HTTP 服务器收到的字节流的编码。通常，只要能确定或猜出编码格式，就应将返回的字节串解码为字符串。

下述 W3C 文档 @indicateurl{https://www.w3.org/International/O-charset}列出了可用于指明（X）HTML 或 XML 文档编码信息的多种方案。

python.org 网站已在 meta 标签中指明，采用的是 @emph{utf-8} 编码，因此这里将用同样的格式对字节串进行解码。

@example
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(100).decode('utf-8'))
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm
@end example

不用 @ref{66b,,context manager} 方法也能获得同样的结果：

@example
>>> import urllib.request
>>> f = urllib.request.urlopen('http://www.python.org/')
>>> print(f.read(100).decode('utf-8'))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm
@end example

以下示例将会把数据流发送给某 CGI 的 stdin，并读取返回数据。请注意，该示例只能工作于 Python 装有 SSL 支持的环境。

@example
>>> import urllib.request
>>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
...                       data=b'This data is passed to stdin of the CGI')
>>> with urllib.request.urlopen(req) as f:
...     print(f.read().decode('utf-8'))
...
Got Data: "This data is passed to stdin of the CGI"
@end example

上述示例中的 CGI 代码如下所示：

@example
#!/usr/bin/env python
import sys
data = sys.stdin.read()
print('Content-type: text/plain\n\nGot Data: "%s"' % data)
@end example

下面是利用 @ref{9e5,,Request} 发送`@w{`}PUT`@w{`} 请求的示例：

@example
import urllib.request
DATA = b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
with urllib.request.urlopen(req) as f:
    pass
print(f.status)
print(f.reason)
@end example

基本 HTTP 认证示例：

@example
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')
@end example

@ref{2d3b,,build_opener()} 默认提供了很多现成的 handler，包括 @ref{1121,,ProxyHandler}。 默认情况下，@ref{1121,,ProxyHandler} 会使用名为 @code{<scheme>_proxy} 的环境变量，其中的 @code{<scheme>} 是相关的 URL 协议。 例如，可以读取 
@geindex http_proxy
@geindex 环境变量; http_proxy
@code{http_proxy} 环境变量来获取 HTTP 代理的 URL。

以下示例将默认的 @ref{1121,,ProxyHandler} 替换为自己的 handler，由程序提供代理 URL，并利用 @ref{2d4d,,ProxyBasicAuthHandler} 加入代理认证的支持：

@example
proxy_handler = urllib.request.ProxyHandler(@{'http': 'http://www.example.com:3128/'@})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')
@end example

添加 HTTP 头部信息：

可利用 @ref{9e5,,Request} 构造函数的 @emph{headers} 参数，或者是：

@example
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
r = urllib.request.urlopen(req)
@end example

@ref{2d38,,OpenerDirector} 自动会在每个 @ref{9e5,,Request} 中加入一项 @code{User-Agent} 头部信息。若要修改，请参见以下语句：

@example
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
@end example

另请记得，当 @ref{9e5,,Request} 传给  @ref{885,,urlopen()}  （或 @ref{9e9,,OpenerDirector.open()}）时，会加入一些标准的头部信息（ @code{Content-Length} 、 @code{Content-Type} 和 @code{Host}）。
@anchor{library/urllib request urllib-examples}@anchor{2db0}
以下会话示例用 @code{GET} 方法读取包含参数的 URL。

@example
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode(@{'spam': 1, 'eggs': 2, 'bacon': 0@})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
...     print(f.read().decode('utf-8'))
...
@end example

以下示例换用 @code{POST} 方法。请注意 urlencode 输出结果先被编码为字节串 data，再送入 urlopen。

@example
>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode(@{'spam': 1, 'eggs': 2, 'bacon': 0@})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
...     print(f.read().decode('utf-8'))
...
@end example

以下示例显式指定了 HTTP 代理，以覆盖环境变量中的设置：

@example
>>> import urllib.request
>>> proxies = @{'http': 'http://proxy.example.com:8080/'@}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> with opener.open("http://www.python.org") as f:
...     f.read().decode('utf-8')
...
@end example

以下示例根本不用代理，也覆盖了环境变量中的设置：

@example
>>> import urllib.request
>>> opener = urllib.request.FancyURLopener(@{@})
>>> with opener.open("http://www.python.org/") as f:
...     f.read().decode('utf-8')
...
@end example

@node 沿袭的接口,urllib request 的限制,示例<33>,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request legacy-interface}@anchor{2db1}
@subsubsection 沿袭的接口


以下函数和类是由 Python 2 模块 @code{urllib`@w{`}（相对早于 `@w{`}urllib2} ）移植过来的。将来某个时候可能会停用。

@geindex urlretrieve() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request urlretrieve}@anchor{2db2}
@deffn {函数} urllib.request.urlretrieve (url, filename=None, reporthook=None, data=None)

将 URL 形式的网络对象复制为本地文件。如果 URL 指向本地文件，则必须提供文件名才会执行复制。返回值为元组 @code{(filename, headers)} ，其中 @emph{filename} 是保存网络对象的本地文件名， @emph{headers} 是由 @ref{885,,urlopen()} 返回的远程对象 @code{info()} 方法的调用结果。可能触发的异常与 @ref{885,,urlopen()} 相同。

第二个参数指定文件的保存位置（若未给出，则会是名称随机生成的临时文件）。第三个参数是个可调用对象，在建立网络连接时将会调用一次，之后每次读完数据块后会调用一次。该可调用对象将会传入 3 个参数：已传输的块数、块的大小（以字节为单位）和文件总的大小。如果面对的是老旧 FTP 服务器，文件大小参数可能会是 @code{-1} ，这些服务器响应读取请求时不会返回文件大小。

以下例子演示了大部分常用场景：

@example
>>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()
@end example

如果 @emph{url} 使用 @code{http:} 方式的标识符，则可能给出可选的 @emph{data} 参数来指定一个 @code{POST} 请求 (通常的请求类型为 @code{GET})。 @emph{data} 参数必须是标准 @code{application/x-www-form-urlencoded} 格式的字节串对象；参见 @ref{884,,urllib.parse.urlencode()} 函数。

@ref{2db2,,urlretrieve()} 在检测到可用数据少于预期的大小（即由 @emph{Content-Length} 标头所报告的大小）时将引发 @code{ContentTooShortError}。 例如，这可能会在下载中断时发生。

@emph{Content-Length} 会被视为大小的下限：如果存在更多的可用数据，urlretrieve 会读取更多的数据，但是如果可用数据少于该值，则会引发异常。

在这种情况下你仍然能够获取已下载的数据，它会存放在异常实例的 @code{content} 属性中。

如果未提供 @emph{Content-Length} 标头，urlretrieve 就无法检查它所下载的数据大小，只是简单地返回它。 在这种情况下你只能假定下载是成功的。
@end deffn

@geindex urlcleanup() (在 urllib.request 模块中)
@anchor{library/urllib request urllib request urlcleanup}@anchor{112c}
@deffn {函数} urllib.request.urlcleanup ()

清理之前调用 @ref{2db2,,urlretrieve()} 时可能留下的临时文件。
@end deffn

@geindex URLopener (urllib.request 中的类)
@anchor{library/urllib request urllib request URLopener}@anchor{2d35}
@deffn {类} urllib.request.URLopener (proxies=None, **x509)


3.3 版后已移除.


用于打开和读取 URL 的基类。 除非你需要支持使用 @code{http:}, @code{ftp:} 或 @code{file:} 以外的方式来打开对象，那你也许可以使用 @ref{2d36,,FancyURLopener}。

在默认情况下，@ref{2d35,,URLopener} 类会发送一个内容为 @code{urllib/VVV} 的 @code{User-Agent} 标头，其中 @emph{VVV} 是 @ref{126,,urllib} 的版本号。 应用程序可以通过子类化 @ref{2d35,,URLopener} 或 @ref{2d36,,FancyURLopener} 并在子类定义中将类属性 @ref{2db3,,version} 设为适当的字符串值来定义自己的 @code{User-Agent} 标头。

可选的 @emph{proxies} 形参应当是一个将方式名称映射到代理 URL 的字典，如为空字典则会完全关闭代理。 它的默认值为 @code{None}，在这种情况下如果存在环境代理设置则将使用它，正如上文 @ref{885,,urlopen()} 的定义中所描述的。

一些归属于 @emph{x509} 的额外关键字形参可在使用 @code{https:} 方式时被用于客户端的验证。 支持通过关键字 @emph{key_file} 和 @emph{cert_file} 来提供 SSL 密钥和证书；对客户端验证的支持需要提供这两个形参。

如果服务器返回错误代码则 @ref{2d35,,URLopener} 对象将引发 @ref{30b,,OSError} 异常。

@geindex open() (urllib.request.URLopener 方法)
@anchor{library/urllib request urllib request URLopener open}@anchor{2db4}
@deffn {方法} open (fullurl, data=None)

使用适当的协议打开 @emph{fullurl}。 此方法会设置缓存和代理信息，然后调用适当的打开方法并附带其输入参数。 如果方式无法被识别，则会调用 @ref{2db5,,open_unknown()}。 @emph{data} 参数的含义与 @ref{885,,urlopen()} 中的 @emph{data} 参数相同。

此方法总是会使用 @ref{51a,,quote()} 来对 @emph{fullurl} 进行转码。
@end deffn

@geindex open_unknown() (urllib.request.URLopener 方法)
@anchor{library/urllib request urllib request URLopener open_unknown}@anchor{2db5}
@deffn {方法} open_unknown (fullurl, data=None)

用于打开未知 URL 类型的可重载接口。
@end deffn

@geindex retrieve() (urllib.request.URLopener 方法)
@anchor{library/urllib request urllib request URLopener retrieve}@anchor{114c}
@deffn {方法} retrieve (url, filename=None, reporthook=None, data=None)

提取 @emph{url} 的内容并将其存放到 @emph{filename} 中。 返回值为元组，由一个本地文件名和一个包含响应标头 (对于远程 URL) 的 @ref{644,,email.message.Message} 对象或者 @code{None}  (对于本地 URL)。 之后调用方必须打开并读取 @emph{filename} 的内容。 如果 @emph{filename} 未给出并且 URL 指向一个本地文件，则会返回输入文件名。 如果 URL 非本地并且 @emph{filename} 未给出，则文件名为带有与输入 URL 的路径末尾部分后缀相匹配的后缀的 @ref{fc8,,tempfile.mktemp()} 的输出。 如果给出了 @emph{reporthook}，它必须为接受三个数字形参的函数：数据分块编号、读入分块的最大数据量和下载的总数据量 (未知则为 -1)。 它将在开始时和从网络读取每个数据分块之后被调用。 对于本地 URL @emph{reporthook} 会被忽略。

如果 @emph{url} 使用 @code{http:} 方式的标识符，则可能给出可选的 @emph{data} 参数来指定一个 @code{POST} 请求 (通常的请求类型为 @code{GET})。 @emph{data} 参数必须为标准的 @code{application/x-www-form-urlencoded} 格式 ；参见 @ref{884,,urllib.parse.urlencode()} 函数。
@end deffn

@geindex version (urllib.request.URLopener 属性)
@anchor{library/urllib request urllib request URLopener version}@anchor{2db3}
@deffn {属性} version

指明打开器对象的用户代理名称的变量。  以便让 @ref{126,,urllib} 告诉服务器它是某个特定的用户代理，请在子类中将其作为类变量来设置或是在调用基类构造器之前在构造器中设置。
@end deffn
@end deffn

@geindex FancyURLopener (urllib.request 中的类)
@anchor{library/urllib request urllib request FancyURLopener}@anchor{2d36}
@deffn {类} urllib.request.FancyURLopener (...)


3.3 版后已移除.


@ref{2d36,,FancyURLopener} 子类化了 @ref{2d35,,URLopener} 以提供对以下 HTTP 响应代码的默认处理: 301, 302, 303, 307 和 401。 对于上述的 30x 响应代码，会使用 @code{Location} 标头来获取实际 URL。 对于 401 响应代码 (authentication required)，则会执行基本 HTTP 验证。 对于 30x 响应代码，递归层数会受 @emph{maxtries} 属性值的限制，该值默认为 10。

对于所有其他响应代码，会调用 @code{http_error_default()} 方法，你可以在子类中重载此方法来正确地处理错误。

@cartouche
@quotation 注解 
根据 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 的说明，对 POST 请求的 301 和 302 响应不可在未经用户确认的情况下自动进行重定向。 在现实情况下，浏览器确实允许自动重定义这些响应，将 POST 更改为 GET，于是 @ref{126,,urllib} 就会复现这种行为。
@end quotation
@end cartouche

传给此构造器的形参与 @ref{2d35,,URLopener} 的相同。

@cartouche
@quotation 注解 
当执行基本验证时，@ref{2d36,,FancyURLopener} 实例会调用其 @ref{2db6,,prompt_user_passwd()} 方法。 默认的实现将向用户询问控制终端所要求的信息。 如有必要子类可以重载此方法来支持更适当的行为。
@end quotation
@end cartouche

@ref{2d36,,FancyURLopener} 类附带了一个额外方法，它应当被重载以提供适当的行为:

@geindex prompt_user_passwd() (urllib.request.FancyURLopener 方法)
@anchor{library/urllib request urllib request FancyURLopener prompt_user_passwd}@anchor{2db6}
@deffn {方法} prompt_user_passwd (host, realm)

返回指定的安全体系下在给定的主机上验证用户所需的信息。 返回的值应当是一个元组 @code{(user, password)}，它可被用于基本验证。

该实现会在终端上提示此信息；应用程序应当重载此方法以使用本地环境下适当的交互模型。
@end deffn
@end deffn

@node urllib request 的限制,,沿袭的接口,urllib request --- 用于打开 URL 的可扩展库
@anchor{library/urllib request urllib-request-restrictions}@anchor{2db7}
@subsubsection @code{urllib.request} 的限制


@quotation

@geindex HTTP; protocol
@geindex FTP; protocol
@end quotation


@itemize *

@item 
目前，仅支持下列协议: HTTP (0.9 和 1.0 版), FTP, 本地文件, 以及数据 URL。


在 3.4 版更改: 增加了对数据URL 的支持。


@item 
@ref{2db2,,urlretrieve()} 的缓存特性已被禁用，等待有人有时间去正确地解决过期时间标头的处理问题。

@item 
应当有一个函数来查询特定 URL 是否在缓存中。

@item 
为了保持向下兼容性，如果某个 URL 看起来是指向本地文件但该文件无法被打开，则该 URL 会使用 FTP 协议来重新解读。 这有时可能会导致令人迷惑的错误消息。

@item 
@ref{885,,urlopen()} 和 @ref{2db2,,urlretrieve()} 方法在等待网络连接建立时会导致任意长的延迟。这意味着在不使用线程的情况下，搭建一个可交互的网络客户端是非常困难的。

@geindex HTML
@geindex HTTP; protocol

@item 
由 @ref{885,,urlopen()} 或 @ref{2db2,,urlretrieve()} 返回的数据就是服务器所返回的原始数据。 这可以是二进制数据（如图片）、纯文本或 HTML 代码等。 HTTP 协议在响应标头中提供了类型信息，这可以通过读取 @code{Content-Type} 标头来查看。 如果返回的数据是 HTML，你可以使用 @ref{91,,html.parser} 模块来解析它。

@geindex FTP

@item 
处理 FTP 协议的代码无法区分文件和目录。 这在尝试读取指向不可访问的 URL 时可能导致意外的行为。 如果 URL 以一个 @code{/} 结束，它会被认为指向一个目录并将作相应的处理。 但是如果读取一个文件的尝试导致了 550 错误（表示 URL 无法找到或不可访问，这常常是由于权限原因），则该路径会被视为一个目录以便处理 URL 是指定一个目录但略去了末尾 @code{/} 的情况。 这在你尝试获取一个因其设置了读取权限因而无法访问的文件时会造成误导性的结果；FTP 代码将尝试读取它，因 550 错误而失败，然后又为这个不可读取的文件执行目录列表操作。 如果需要细粒度的控制，请考虑使用 @ref{82,,ftplib} 模块，子类化 @ref{2d36,,FancyURLopener}，或是修改 @emph{_urlopener} 来满足你的需求。
@end itemize

@node urllib response --- urllib 使用的 Response 类,urllib parse 用于解析 URL,urllib request --- 用于打开 URL 的可扩展库,互联网协议和支持
@anchor{library/urllib request module-urllib response}@anchor{12a}@anchor{library/urllib request urllib-response-response-classes-used-by-urllib}@anchor{2db8}
@subsection @code{urllib.response} --- urllib 使用的 Response 类


@geindex urllib.response (模块)

@ref{12a,,urllib.response} 模块定义了一些函数和提供最小化文件类接口包括 @code{read()} 和 @code{readline()} 等的类。 此模块定义的函数会由 @ref{129,,urllib.request} 模块在内部使用。 典型的响应对象是一个 @ref{2d33,,urllib.response.addinfourl} 实例:

@geindex addinfourl (urllib.response 中的类)
@anchor{library/urllib request urllib response addinfourl}@anchor{2d33}
@deffn {类} urllib.response.addinfourl

@geindex url (urllib.response.addinfourl 属性)
@anchor{library/urllib request urllib response addinfourl url}@anchor{2db9}
@deffn {属性} url

已读取资源的 URL，通常用于确定是否进行了重定向。
@end deffn

@geindex headers (urllib.response.addinfourl 属性)
@anchor{library/urllib request urllib response addinfourl headers}@anchor{2dba}
@deffn {属性} headers

以 @ref{645,,EmailMessage} 实例的形式返回响应的标头。
@end deffn

@geindex status (urllib.response.addinfourl 属性)
@anchor{library/urllib request urllib response addinfourl status}@anchor{2dbb}
@deffn {属性} status


3.9 新版功能.


由服务器返回的状态码。
@end deffn

@geindex geturl() (urllib.response.addinfourl 方法)
@anchor{library/urllib request urllib response addinfourl geturl}@anchor{2dbc}
@deffn {方法} geturl ()


3.9 版后已移除: 已弃用，建议改用 @ref{2db9,,url}。

@end deffn

@geindex info() (urllib.response.addinfourl 方法)
@anchor{library/urllib request urllib response addinfourl info}@anchor{2dbd}
@deffn {方法} info ()


3.9 版后已移除: 已弃用，建议改用 @ref{2dba,,headers}。

@end deffn

@geindex code (urllib.response.addinfourl 属性)
@anchor{library/urllib request urllib response addinfourl code}@anchor{2dbe}
@deffn {属性} code


3.9 版后已移除: 已弃用，建议改用 @ref{2dbb,,status}。

@end deffn

@geindex getstatus() (urllib.response.addinfourl 方法)
@anchor{library/urllib request urllib response addinfourl getstatus}@anchor{2dbf}
@deffn {方法} getstatus ()


3.9 版后已移除: 已弃用，建议改用 @ref{2dbb,,status}。

@end deffn
@end deffn

@node urllib parse 用于解析 URL,urllib error --- urllib request 引发的异常类,urllib response --- urllib 使用的 Response 类,互联网协议和支持
@anchor{library/urllib parse doc}@anchor{2dc0}@anchor{library/urllib parse module-urllib parse}@anchor{128}@anchor{library/urllib parse urllib-parse-parse-urls-into-components}@anchor{2dc1}
@subsection @code{urllib.parse}  用于解析 URL


@geindex urllib.parse (模块)

@strong{源代码:} Lib/urllib/parse.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/urllib/parse.py}

@geindex WWW
@geindex World Wide Web
@geindex URL
@geindex URL; parsing
@geindex relative; URL


__________________________________________________________________


该模块定义了一个标准接口，用于URL字符串按组件(协议、网络位置、路径等)分解，或将组件组合回URL字符串，并将 "相对URL "转换为给定 "基础URL "的绝对URL。

The module has been designed to match the Internet RFC on Relative Uniform
Resource Locators. It supports the following URL schemes: @code{file}, @code{ftp},
@code{gopher}, @code{hdl}, @code{http}, @code{https}, @code{imap}, @code{mailto}, @code{mms},
@code{news}, @code{nntp}, @code{prospero}, @code{rsync}, @code{rtsp}, @code{rtspu}, @code{sftp},
@code{shttp}, @code{sip}, @code{sips}, @code{snews}, @code{svn}, @code{svn+ssh}, @code{telnet},
@code{wais}, @code{ws}, @code{wss}.

@ref{128,,urllib.parse} 模块定义的函数可分为两个主要门类: URL 解析和 URL 转码。 这些函数将在以下各节中详细说明。

@menu
* URL 解析:: 
* URL parsing security:: 
* 解析ASCII编码字节:: 
* 结构化解析结果:: 
* URL 转码:: 

@end menu

@node URL 解析,URL parsing security,,urllib parse 用于解析 URL
@anchor{library/urllib parse url-parsing}@anchor{2dc2}
@subsubsection URL 解析


URL解析功能可以将一个URL字符串分割成其组件，或者将URL组件组合成一个URL字符串。

@geindex urlparse() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urlparse}@anchor{6fb}
@deffn {函数} urllib.parse.urlparse (urlstring, scheme='@w{'}, allow_fragments=True)

将一个 URL 解析为六个部分，返回一个包含 6 项的 @ref{b84,,named tuple}。 这对应于 URL 的主要结构: @code{scheme://netloc/path;parameters?query#fragment}。 每个元组项均为字符串，可能为空字符串。 这些部分不会再被拆分为更小的部分（例如，netloc 将为单个字符串），并且 % 转义不会被扩展。 上面显示的分隔符不会出现在结果中，只有 @emph{path} 部分的开头斜杠例外，它如果存在则会被保留。 例如:

@example
>>> from urllib.parse import urlparse
>>> urlparse("scheme://netloc/path;parameters?query#fragment")
ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', params='@w{'},
            query='query', fragment='fragment')
>>> o = urlparse("http://docs.python.org:80/3/library/urllib.parse.html?"
...              "highlight=params#url-parsing")
>>> o
ParseResult(scheme='http', netloc='docs.python.org:80',
            path='/3/library/urllib.parse.html', params='@w{'},
            query='highlight=params', fragment='url-parsing')
>>> o.scheme
'http'
>>> o.netloc
'docs.python.org:80'
>>> o.hostname
'docs.python.org'
>>> o.port
80
>>> o._replace(fragment="").geturl()
'http://docs.python.org:80/3/library/urllib.parse.html?highlight=params'
@end example

根据 
@geindex RFC; RFC 1808
RFC 1808@footnote{https://tools.ietf.org/html/rfc1808.html} 中的语法规范，urlparse 仅在 netloc 前面正确地附带了 '//' 的情况下才会识别它。 否则输入会被当作是一个相对 URL 因而以路径的组成部分开头。

@example
>>> from urllib.parse import urlparse
>>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
ParseResult(scheme='@w{'}, netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='@w{'}, query='@w{'}, fragment='@w{'})
>>> urlparse('www.cwi.nl/%7Eguido/Python.html')
ParseResult(scheme='@w{'}, netloc='@w{'}, path='www.cwi.nl/%7Eguido/Python.html',
            params='@w{'}, query='@w{'}, fragment='@w{'})
>>> urlparse('help/Python.html')
ParseResult(scheme='@w{'}, netloc='@w{'}, path='help/Python.html', params='@w{'},
            query='@w{'}, fragment='@w{'})
@end example

@emph{scheme} 参数给出了默认的协议，只有在 URL 未指定协议的情况下才会被使用。 它应该是与 @emph{urlstring} 相同的类型（文本或字节串），除此之外默认值 @code{'@w{'}} 也总是被允许，并会在适当情况下自动转换为 @code{b'@w{'}}。

如果 @emph{allow_fragments} 参数为假值，则片段标识符不会被识别。 它们会被解析为路径、参数或查询部分，在返回值中 @code{fragment} 会被设为空字符串。

返回值是一个 @ref{b84,,named tuple}，这意味着它的条目可以通过索引或作为命名属性来访问，这些属性是：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

索引

@tab

值

@tab

值（如果不存在）

@item

@code{scheme}

@tab

0

@tab

URL协议

@tab

@emph{scheme} 参数

@item

@code{netloc}

@tab

1

@tab

网络位置部分

@tab

空字符串

@item

@code{path}

@tab

2

@tab

分层路径

@tab

空字符串

@item

@code{params}

@tab

3

@tab

最后路径元素的参数

@tab

空字符串

@item

@code{query}

@tab

4

@tab

查询组件

@tab

空字符串

@item

@code{fragment}

@tab

5

@tab

片段识别

@tab

空字符串

@item

@code{username}

@tab

@tab

用户名

@tab

@ref{204,,None}

@item

@code{password}

@tab

@tab

密码

@tab

@ref{204,,None}

@item

@code{hostname}

@tab

@tab

主机名（小写）

@tab

@ref{204,,None}

@item

@code{port}

@tab

@tab

端口号为整数（如果存在）

@tab

@ref{204,,None}

@end multitable


如果在 URL 中指定了无效的端口，读取 @code{port} 属性将引发 @ref{16d,,ValueError}。 有关结果对象的更多信息请参阅 @ref{2dc3,,结构化解析结果} 一节。

在 @code{netloc} 属性中不匹配的方括号将引发 @ref{16d,,ValueError}。

如果 @code{netloc} 属性中的字符在 NFKC 规范化下（如 IDNA 编码格式所使用的）被分解成 @code{/}, @code{?}, @code{#}, @code{@@} 或 @code{:} 则将引发 @ref{16d,,ValueError}。 如果在解析之前 URL 就被分解，则不会引发错误。

与所有具名元组的情况一样，该子类还有一些特别有用的附加方法和属性。 其中一个方法是 @code{_replace()}。 @code{_replace()} 方法将返回一个新的 ParseResult 对象来将指定字段替换为新的值。

@example
>>> from urllib.parse import urlparse
>>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
>>> u
ParseResult(scheme='@w{'}, netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='@w{'}, query='@w{'}, fragment='@w{'})
>>> u._replace(scheme='http')
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='@w{'}, query='@w{'}, fragment='@w{'})
@end example

@cartouche
@quotation 警告 
@ref{6fb,,urlparse()} does not perform validation.  See @ref{2dc4,,URL parsing security} for details.
@end quotation
@end cartouche


在 3.2 版更改: 添加了IPv6 URL解析功能。



在 3.3 版更改: The fragment is now parsed for all URL schemes (unless @emph{allow_fragment} is
false), in accordance with 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html}.  Previously, a whitelist of
schemes that support fragments existed.



在 3.6 版更改: 超范围的端口号现在会引发 @ref{16d,,ValueError}，而不是返回 @ref{204,,None}。



在 3.8 版更改: 在 NFKC 规范化下会影响 netloc 解析的字符现在将引发 @ref{16d,,ValueError}。

@end deffn

@geindex parse_qs() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse parse_qs}@anchor{280}
@deffn {函数} urllib.parse.parse_qs (qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

解析以字符串参数形式（类型为 @code{application/x-www-form-urlencoded} 的数据）给出的查询字符串。 返回字典形式的数据。 结果字典的键为唯一的查询变量名而值为每个变量名对应的值列表。

可选参数 @emph{keep_blank_values} 是一个旗标，指明是否要将以百分号转码的空值作为空字符串处理。 真值表示空值应当被保留作为空字符串。 默认的假值表示空值会被忽略并将其视作未包括的值。

可选参数 @emph{strict_parsing} 是一个旗标，指明要如何处理解析错误。 如为假值（默认），错误会被静默地忽略。 如为真值，错误会引发 @ref{16d,,ValueError} 异常。

可选的 @emph{encoding} 和 @emph{errors} 形参指定如何将以百分号编码的序列解码为 Unicode 字符，即作为 @ref{171,,bytes.decode()} 方法所接受的数据。

可选参数 @emph{max_num_fields} 是要读取的最大字段数量的。 如果设置，则如果读取的字段超过 @emph{max_num_fields} 会引发 @ref{16d,,ValueError}。

可选参数 @emph{separator} 是用来分隔查询参数的符号。 默认为 @code{&}。

使用 @ref{884,,urllib.parse.urlencode()} 函数 (并将 @code{doseq} 形参设为 @code{True}) 将这样的字典转换为查询字符串。.


在 3.2 版更改: 增加了 @emph{encoding} 和 @emph{errors} 形参。



在 3.8 版更改: 增加了 @emph{max_num_fields} 形参。



在 3.9.2 版更改: Added @emph{separator} parameter with the default value of @code{&}. Python
versions earlier than Python 3.9.2 allowed using both @code{;} and @code{&} as
query parameter separator. This has been changed to allow only a single
separator key, with @code{&} as the default separator.

@end deffn

@geindex parse_qsl() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse parse_qsl}@anchor{281}
@deffn {函数} urllib.parse.parse_qsl (qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

解析以字符串参数形式（类型为 @code{application/x-www-form-urlencoded} 的数据）给出的查询字符串。 数据以字段名和字段值对列表的形式返回。

可选参数 @emph{keep_blank_values} 是一个旗标，指明是否要将以百分号转码的空值作为空字符串处理。 真值表示空值应当被保留作为空字符串。 默认的假值表示空值会被忽略并将其视作未包括的值。

可选参数 @emph{strict_parsing} 是一个旗标，指明要如何处理解析错误。 如为假值（默认），错误会被静默地忽略。 如为真值，错误会引发 @ref{16d,,ValueError} 异常。

可选的 @emph{encoding} 和 @emph{errors} 形参指定如何将以百分号编码的序列解码为 Unicode 字符，即作为 @ref{171,,bytes.decode()} 方法所接受的数据。

可选参数 @emph{max_num_fields} 是要读取的最大字段数量的。 如果设置，则如果读取的字段超过 @emph{max_num_fields} 会引发 @ref{16d,,ValueError}。

可选参数 @emph{separator} 是用来分隔查询参数的符号。 默认为 @code{&}。

使用 @ref{884,,urllib.parse.urlencode()} 函数将这样的名值对列表转换为查询字符串。


在 3.2 版更改: 增加了 @emph{encoding} 和 @emph{errors} 形参。



在 3.8 版更改: 增加了 @emph{max_num_fields} 形参。



在 3.9.2 版更改: Added @emph{separator} parameter with the default value of @code{&}. Python
versions earlier than Python 3.9.2 allowed using both @code{;} and @code{&} as
query parameter separator. This has been changed to allow only a single
separator key, with @code{&} as the default separator.

@end deffn

@geindex urlunparse() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urlunparse}@anchor{2dc5}
@deffn {函数} urllib.parse.urlunparse (parts)

根据 @code{urlparse()} 所返回的元组来构造一个 URL。 @emph{parts} 参数可以是任何包含六个条目的可迭代对象。 构造的结果可能是略有不同但保持等价的 URL，如果被解析的 URL 原本包含不必要的分隔符（例如，带有空查询的 @code{?}；RFC 已声明这是等价的）。
@end deffn

@geindex urlsplit() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urlsplit}@anchor{6fa}
@deffn {函数} urllib.parse.urlsplit (urlstring, scheme='@w{'}, allow_fragments=True)

此函数类似于 @ref{6fb,,urlparse()}，但不会拆分来自 URL 的参数。 此函数通常应当在需要允许将参数应用到 URL 的 @emph{path} 部分的每个分节的较新的 URL 语法的情况下 (参见 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://tools.ietf.org/html/rfc2396.html}) 被用来代替 @ref{6fb,,urlparse()}。 需要使用一个拆分函数来拆分路径分节和参数。 此函数将返回包含 5 个条目的 @ref{b84,,named tuple}:

@example
(addressing scheme, network location, path, query, fragment identifier).
@end example

返回值是一个 @ref{b84,,named tuple}，它的条目可以通过索引或作为命名属性来访问:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

索引

@tab

值

@tab

值（如果不存在）

@item

@code{scheme}

@tab

0

@tab

URL协议

@tab

@emph{scheme} 参数

@item

@code{netloc}

@tab

1

@tab

网络位置部分

@tab

空字符串

@item

@code{path}

@tab

2

@tab

分层路径

@tab

空字符串

@item

@code{query}

@tab

3

@tab

查询组件

@tab

空字符串

@item

@code{fragment}

@tab

4

@tab

片段识别

@tab

空字符串

@item

@code{username}

@tab

@tab

用户名

@tab

@ref{204,,None}

@item

@code{password}

@tab

@tab

密码

@tab

@ref{204,,None}

@item

@code{hostname}

@tab

@tab

主机名（小写）

@tab

@ref{204,,None}

@item

@code{port}

@tab

@tab

端口号为整数（如果存在）

@tab

@ref{204,,None}

@end multitable


如果在 URL 中指定了无效的端口，读取 @code{port} 属性将引发 @ref{16d,,ValueError}。 有关结果对象的更多信息请参阅 @ref{2dc3,,结构化解析结果} 一节。

在 @code{netloc} 属性中不匹配的方括号将引发 @ref{16d,,ValueError}。

如果 @code{netloc} 属性中的字符在 NFKC 规范化下（如 IDNA 编码格式所使用的）被分解成 @code{/}, @code{?}, @code{#}, @code{@@} 或 @code{:} 则将引发 @ref{16d,,ValueError}。 如果在解析之前 URL 就被分解，则不会引发错误。

Following some of the WHATWG spec@footnote{https://url.spec.whatwg.org/#concept-basic-url-parser} that updates RFC 3986, leading C0
control and space characters are stripped from the URL. @code{\n},
@code{\r} and tab @code{\t} characters are removed from the URL at any position.

@cartouche
@quotation 警告 
@ref{6fa,,urlsplit()} does not perform validation.  See @ref{2dc4,,URL parsing security} for details.
@end quotation
@end cartouche


在 3.6 版更改: 超范围的端口号现在会引发 @ref{16d,,ValueError}，而不是返回 @ref{204,,None}。



在 3.8 版更改: 在 NFKC 规范化下会影响 netloc 解析的字符现在将引发 @ref{16d,,ValueError}。



在 3.9.5 版更改: ASCII 换行符和制表符会从 URL 中被去除。



在 3.9.17 版更改: Leading WHATWG C0 control and space characters are stripped from the URL.

@end deffn

@geindex urlunsplit() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urlunsplit}@anchor{2dc6}
@deffn {函数} urllib.parse.urlunsplit (parts)

将 @ref{6fa,,urlsplit()} 所返回的元组中的元素合并为一个字符串形式的完整 URL。 @emph{parts} 参数可以是任何包含五个条目的可迭代对象。 其结果可能是略有不同但保持等价的 URL，如果被解析的 URL 原本包含不必要的分隔符（例如，带有空查询的 ?；RFC 已声明这是等价的）。
@end deffn

@geindex urljoin() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urljoin}@anchor{886}
@deffn {函数} urllib.parse.urljoin (base, url, allow_fragments=True)

通过合并一个 "基准 URL" (@emph{base}) 和另一个 URL (@emph{url}) 来构造一个完整 ("absolute") URL。 在非正式情况下，这将使用基准 URL 的各部分，特别是地址协议、网络位置和 (一部分) 路径来提供相对 URL 中缺失的部分。 例如:

@example
>>> from urllib.parse import urljoin
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
'http://www.cwi.nl/%7Eguido/FAQ.html'
@end example

@emph{allow_fragments} 参数具有与 @ref{6fb,,urlparse()} 中的对应参数一致的含义与默认值。

@cartouche
@quotation 注解 
如果 @emph{url} 为绝对 URL (即以 @code{//} 或 @code{scheme://} 打头)，则 @emph{url} 的主机名和/或协议将出现在结果中。 例如:

@example
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
...         '//www.python.org/%7Eguido')
'http://www.python.org/%7Eguido'
@end example

如果你不想要那样的行为，请使用 @ref{6fa,,urlsplit()} 和 @ref{2dc6,,urlunsplit()} 对 @emph{url} 进行预处理，移除可能存在的 @emph{scheme} 和 @emph{netloc} 部分。
@end quotation
@end cartouche


在 3.5 版更改: 更新行为以匹配 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html} 中定义的语义。

@end deffn

@geindex urldefrag() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urldefrag}@anchor{cb4}
@deffn {函数} urllib.parse.urldefrag (url)

如果 @emph{url} 包含片段标识符，则返回不带片段标识符的 @emph{url} 修改版本。 如果 @emph{url} 中没有片段标识符，则返回未经修改的 @emph{url} 和一个空字符串。

返回值是一个 @ref{b84,,named tuple}，它的条目可以通过索引或作为命名属性来访问:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

索引

@tab

值

@tab

值（如果不存在）

@item

@code{url}

@tab

0

@tab

不带片段的 URL

@tab

空字符串

@item

@code{fragment}

@tab

1

@tab

片段识别

@tab

空字符串

@end multitable


请参阅 @ref{2dc3,,结构化解析结果} 一节了解有关结果对象的更多信息。


在 3.2 版更改: 结果为已构造好的对象而不是一个简单的 2 元组。-tuple.

@end deffn

@geindex unwrap() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse unwrap}@anchor{2dc7}
@deffn {函数} urllib.parse.unwrap (url)

从已包装的 URL (即被格式化为 @code{<URL:scheme://host/path>}, @code{<scheme://host/path>}, @code{URL:scheme://host/path} 或 @code{scheme://host/path} 的字符串) 中提取 URL。 如果 @emph{url} 不是一个已包装的 URL，它将被原样返回。
@end deffn

@node URL parsing security,解析ASCII编码字节,URL 解析,urllib parse 用于解析 URL
@anchor{library/urllib parse id1}@anchor{2dc8}@anchor{library/urllib parse url-parsing-security}@anchor{2dc4}
@subsubsection URL parsing security


The @ref{6fa,,urlsplit()} and @ref{6fb,,urlparse()} APIs do not perform @strong{validation} of
inputs.  They may not raise errors on inputs that other applications consider
invalid.  They may also succeed on some inputs that might not be considered
URLs elsewhere.  Their purpose is for practical functionality rather than
purity.

Instead of raising an exception on unusual input, they may instead return some
component parts as empty strings. Or components may contain more than perhaps
they should.

We recommend that users of these APIs where the values may be used anywhere
with security implications code defensively. Do some verification within your
code before trusting a returned component part.  Does that @code{scheme} make
sense?  Is that a sensible @code{path}?  Is there anything strange about that
@code{hostname}?  etc.

@node 解析ASCII编码字节,结构化解析结果,URL parsing security,urllib parse 用于解析 URL
@anchor{library/urllib parse id2}@anchor{2dc9}@anchor{library/urllib parse parsing-ascii-encoded-bytes}@anchor{cb6}
@subsubsection 解析ASCII编码字节


这些 URL 解析函数最初设计只用于操作字符串。 但在实践中，它也能够操作经过正确转码和编码的 ASCII 字节序列形式的 URL。 相应地，此模块中的 URL 解析函数既可以操作 @ref{206,,str} 对象也可以操作 @ref{172,,bytes} 和 @ref{173,,bytearray} 对象。

如果传入 @ref{206,,str} 数据，结果将只包含 @ref{206,,str} 数据。 如果传入 @ref{172,,bytes} 或 @ref{173,,bytearray} 数据，则结果也将只包含 @ref{172,,bytes} 数据。

试图在单个函数调用中混用 @ref{206,,str} 数据和 @ref{172,,bytes} 或 @ref{173,,bytearray} 数据将导致引发 @ref{1ff,,TypeError}，而试图传入非 ASCII 字节值则将引发 @ref{332,,UnicodeDecodeError}。

为了支持结果对象在 @ref{206,,str} 和 @ref{172,,bytes} 之间方便地转换，所有来自 URL 解析函数的返回值都会提供 @code{encode()} 方法 (当结果包含 @ref{206,,str} 数据) 或 @code{decode()} 方法 (当结果包含 @ref{172,,bytes} 数据)。 这些方法的签名与 @ref{206,,str} 和 @ref{172,,bytes} 的对应方法相匹配 (不同之处在于其默认编码格式是 @code{'ascii'} 而非 @code{'utf-8'})。 每个方法会输出包含相应类型的 @ref{172,,bytes} 数据 (对于 @code{encode()} 方法) 或 @ref{206,,str} 数据 (对于 @code{decode()} 方法) 的值。

对于某些需要在有可能不正确地转码的包含非 ASCII 数据的 URL 上进行操作的应用程序来说，在发起调用 URL 解析方法之前必须自行将字节串解码为字符。

在本节中描述的行为仅适用于 URL 解析函数。 URL 转码函数在产生和消耗字节序列时使用它们自己的规则，详情参见单独 URL 转码函数的文档。


在 3.2 版更改: URL 解析函数现在接受 ASCII 编码的字节序列


@node 结构化解析结果,URL 转码,解析ASCII编码字节,urllib parse 用于解析 URL
@anchor{library/urllib parse structured-parse-results}@anchor{2dca}@anchor{library/urllib parse urlparse-result-object}@anchor{2dc3}
@subsubsection 结构化解析结果


@ref{6fb,,urlparse()}, @ref{6fa,,urlsplit()} 和 @ref{cb4,,urldefrag()} 函数的结果对象是 @ref{1a2,,tuple} 类型的子类。 这些子类中增加了在那些函数的文档中列出的属性，之前小节中描述的编码和解码支持，以及一个附加方法:

@geindex geturl() (urllib.parse.urllib.parse.SplitResult 方法)
@anchor{library/urllib parse urllib parse urllib parse SplitResult geturl}@anchor{2dcb}
@deffn {方法} urllib.parse.SplitResult.geturl ()

以字符串形式返回原始 URL 的重合并版本。 这可能与原始 URL 有所不同，例如协议的名称可能被正规化为小写字母、空的组成部分可能被丢弃。 特别地，空的参数、查询和片段标识符将会被移除。

对于 @ref{cb4,,urldefrag()} 的结果，只有空的片段标识符会被移除。 对于 @ref{6fa,,urlsplit()} 和 @ref{6fb,,urlparse()} 的结果，所有被记录的改变都会被应用到此方法所返回的 URL 上。

如果是通过原始的解析方法传回则此方法的结果会保持不变:

@example
>>> from urllib.parse import urlsplit
>>> url = 'HTTP://www.Python.org/doc/#'
>>> r1 = urlsplit(url)
>>> r1.geturl()
'http://www.Python.org/doc/'
>>> r2 = urlsplit(r1.geturl())
>>> r2.geturl()
'http://www.Python.org/doc/'
@end example
@end deffn

下面的类提供了当在 @ref{206,,str} 对象上操作时对结构化解析结果的实现:

@geindex DefragResult (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse DefragResult}@anchor{2dcc}
@deffn {类} urllib.parse.DefragResult (url, fragment)

用于 @ref{cb4,,urldefrag()} 结果的实体类，包含有 @ref{206,,str} 数据。 @code{encode()} 方法会返回一个 @ref{2dcd,,DefragResultBytes} 实例。


3.2 新版功能.

@end deffn

@geindex ParseResult (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse ParseResult}@anchor{2dce}
@deffn {类} urllib.parse.ParseResult (scheme, netloc, path, params, query, fragment)

用于 @ref{6fb,,urlparse()} 结果的实体类，包含有 @ref{206,,str} 数据。 @code{encode()} 方法会返回一个 @ref{2dcf,,ParseResultBytes} 实例。
@end deffn

@geindex SplitResult (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse SplitResult}@anchor{2dd0}
@deffn {类} urllib.parse.SplitResult (scheme, netloc, path, query, fragment)

用于 @ref{6fa,,urlsplit()} 结果的实体类，包含有 @ref{206,,str} 数据。 @code{encode()} 方法会返回一个 @ref{2dd1,,SplitResultBytes} 实例。
@end deffn

下面的类提供了当在 @ref{172,,bytes} 或 @ref{173,,bytearray} 对象上操作时对解析结果的实现:

@geindex DefragResultBytes (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse DefragResultBytes}@anchor{2dcd}
@deffn {类} urllib.parse.DefragResultBytes (url, fragment)

用于 @ref{cb4,,urldefrag()} 结果的实体类，包含有 @ref{172,,bytes} 数据。 @code{decode()} 方法会返回一个 @ref{2dcc,,DefragResult} 实例。


3.2 新版功能.

@end deffn

@geindex ParseResultBytes (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse ParseResultBytes}@anchor{2dcf}
@deffn {类} urllib.parse.ParseResultBytes (scheme, netloc, path, params, query, fragment)

用于 @ref{6fb,,urlparse()} 结果的实体类，包含有 @ref{172,,bytes} 数据。 @code{decode()} 方法会返回一个 @ref{2dce,,ParseResult} 实例。


3.2 新版功能.

@end deffn

@geindex SplitResultBytes (urllib.parse 中的类)
@anchor{library/urllib parse urllib parse SplitResultBytes}@anchor{2dd1}
@deffn {类} urllib.parse.SplitResultBytes (scheme, netloc, path, query, fragment)

用于 @ref{6fa,,urlsplit()} 结果的实体类，包含有 @ref{172,,bytes} 数据。 @code{decode()} 方法会返回一个 @ref{2dd0,,SplitResult} 实例。


3.2 新版功能.

@end deffn

@node URL 转码,,结构化解析结果,urllib parse 用于解析 URL
@anchor{library/urllib parse url-quoting}@anchor{2dd2}
@subsubsection URL 转码


URL 转码函数的功能是接收程序数据并通过对特殊字符进行转码并正确编码非 ASCII 文本来将其转为可以安全地用作 URL 组成部分的形式。 它们还支持逆转此操作以便从作为 URL 组成部分的内容中重建原始数据，如果上述的 URL 解析函数还未覆盖此功能的话。

@geindex quote() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse quote}@anchor{51a}
@deffn {函数} urllib.parse.quote (string, safe='/', encoding=None, errors=None)

使用 @code{%xx} 转义符替换 @emph{string} 中的特殊字符。 字母、数字和 @code{'_.-~'} 等字符一定不会被转码。 在默认情况下，此函数只对 URL 的路径部分进行转码。 可选的 @emph{safe} 形参额外指定不应被转码的 ASCII 字符 --- 其默认值为 @code{'/'}。

@emph{string} 可以是 @ref{206,,str} 或 @ref{172,,bytes} 对象。


在 3.7 版更改: 从 
@geindex RFC; RFC 2396
RFC 2396@footnote{https://tools.ietf.org/html/rfc2396.html} 迁移到 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html} 以转码 URL 字符串。 "~" 现在已被包括在非保留字符集中。


可选的 @emph{encoding} 和 @emph{errors} 形参指明如何处理非 ASCII 字符，与 @ref{170,,str.encode()} 方法所接受的值一样。 @emph{encoding} 默认为 @code{'utf-8'}。 @emph{errors} 默认为 @code{'strict'}，表示不受支持的字符将引发 @ref{331,,UnicodeEncodeError}。 如果 @emph{string} 为 @ref{172,,bytes} 则不可提供 @emph{encoding} 和 @emph{errors}，否则将引发 @ref{1ff,,TypeError}。

请注意 @code{quote(string, safe, encoding, errors)} 等价于 @code{quote_from_bytes(string.encode(encoding, errors), safe)}。

例如: @code{quote('/El Niño/')} 将产生 @code{'/El%20Ni%C3%B1o/'}.
@end deffn

@geindex quote_plus() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse quote_plus}@anchor{cb5}
@deffn {函数} urllib.parse.quote_plus (string, safe='@w{'}, encoding=None, errors=None)

类似于 @ref{51a,,quote()}，但还会使用加号来替换空格，如在构建放入 URL 的查询字符串时对于转码 HTML 表单值时所要求的那样。 原始字符串中的加号会被转义，除非它们已包括在 @emph{safe} 中。 它也不会将 @emph{safe} 的默认值设为 @code{'/'}。

例如: @code{quote_plus('/El Niño/')} 将产生 @code{'%2FEl+Ni%C3%B1o%2F'}。
@end deffn

@geindex quote_from_bytes() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse quote_from_bytes}@anchor{2dd3}
@deffn {函数} urllib.parse.quote_from_bytes (bytes, safe='/')

类似于 @ref{51a,,quote()}，但是接受 @ref{172,,bytes} 对象而非 @ref{206,,str}，并且不执行从字符串到字节串的编码。

例如: @code{quote_from_bytes(b'a&\xef')} 产生 @code{'a%26%EF'}。
@end deffn

@geindex unquote() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse unquote}@anchor{1124}
@deffn {函数} urllib.parse.unquote (string, encoding='utf-8', errors='replace')

将 @code{%xx} 转义符替换为其单字符等价物。 可选的 @emph{encoding} 和 @emph{errors} 形参指定如何将以百分号编码的序列解码为 Unicode 字符，即 @ref{171,,bytes.decode()} 方法所接受的数据。

@emph{string} 可以是 @ref{206,,str} 或 @ref{172,,bytes} 对象。

@emph{encoding} 默认为 @code{'utf-8'}。 @emph{errors} 默认为 @code{'replace'}，表示无效的序列将被替换为占位字符。

例如: @code{unquote('/El%20Ni%C3%B1o/')} 将产生 @code{'/El Niño/'}。


在 3.9 版更改: @emph{string} 形参支持 bytes 和 str 对象（之前仅支持 str）。

@end deffn

@geindex unquote_plus() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse unquote_plus}@anchor{2dd4}
@deffn {函数} urllib.parse.unquote_plus (string, encoding='utf-8', errors='replace')

类似于 @ref{1124,,unquote()}，但还会将加号替换为空格，如反转码表单值所要求的。

@emph{string} 必须为 @ref{206,,str}。

例如: @code{unquote_plus('/El+Ni%C3%B1o/')} 将产生 @code{'/El Niño/'}。
@end deffn

@geindex unquote_to_bytes() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse unquote_to_bytes}@anchor{2dd5}
@deffn {函数} urllib.parse.unquote_to_bytes (string)

将 @code{%xx} 转义符替换为其单八位等价物，并返回一个 @ref{172,,bytes} 对象。

@emph{string} 可以是 @ref{206,,str} 或 @ref{172,,bytes} 对象。

如果它是 @ref{206,,str}，则 @emph{string} 中未转义的非 ASCII 字符会被编码为 UTF-8 字节串。

例如: @code{unquote_to_bytes('a%26%EF')} y将产生 @code{b'a&\xef'}。
@end deffn

@geindex urlencode() (在 urllib.parse 模块中)
@anchor{library/urllib parse urllib parse urlencode}@anchor{884}
@deffn {函数} urllib.parse.urlencode (query, doseq=False, safe='@w{'}, encoding=None, errors=None, quote_via=quote_plus)

将一个包含有 @ref{206,,str} 或 @ref{172,,bytes} 对象的映射对象或二元组序列转换为以百分号编码的 ASCII 文本字符串。 如果所产生的字符串要被用作 @ref{885,,urlopen()} 函数的 POST 操作的 @emph{data}，则它应当被编码为字节串，否则它将导致 @ref{1ff,,TypeError}。

结果字符串是一系列 @code{key=value} 对，由 @code{'&'} 字符进行分隔，其中 @emph{key} 和 @emph{value} 都已使用 @emph{quote_via} 函数转码。 在默认情况下，会使用 @ref{cb5,,quote_plus()} 来转码值，这意味着空格会被转码为 @code{'+'} 字符而 '/' 字符会被转码为 @code{%2F}，即遵循 GET 请求的标准 (@code{application/x-www-form-urlencoded})。 另一个可以作为 @emph{quote_via} 传入的替代函数是 @ref{51a,,quote()}，它将把空格转码为 @code{%20} 并且不编码 '/' 字符。 为了最大程度地控制要转码的内容，请使用 @code{quote} 并指定 @emph{safe} 的值。

当使用二元组序列作为 @emph{query} 参数时，每个元组的第一个元素为键而第二个元素为值。 值元素本身也可以为一个序列，在那种情况下，如果可选的形参 @emph{doseq} 的值为 @code{True}，则每个键的值序列元素生成单个 @code{key=value} 对（以 @code{'&'} 分隔）。 被编码的字符串中的参数顺序将与序列中的形参元素顺序相匹配。

@emph{safe}, @emph{encoding} 和 @emph{errors} 形参会被传递给 @emph{quote_via} (@emph{encoding} 和 @emph{errors} 形参仅在查询元素为 @ref{206,,str} 时会被传递)。

为了反向执行这个编码过程，此模块提供了 @ref{280,,parse_qs()} 和 @ref{281,,parse_qsl()} 来将查询字符串解析为 Python 数据结构。

请参考 @ref{2db0,,urllib 示例} 来了解如何使用 @ref{884,,urllib.parse.urlencode()} 方法来生成 URL 的查询字符串或 POST 请求的数据。


在 3.2 版更改: 查询支持字节和字符串对象。



3.5 新版功能: @emph{quote_via} 参数.

@end deffn


@subsubheading 参见



@table @asis

@item WHATWG@footnote{https://url.spec.whatwg.org/} -  URL 现有标准

定义 URL、域名、IP 地址、application/x-www-form-urlencoded 格式及其 API 的工作组。

@geindex RFC; RFC 3986

@item RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html} - 统一资源标识符

这是当前的标准 (STD66)。 任何对于 urllib.parse 模块的修改都必须遵循该标准。 某些偏离也可能会出现，这大都是出于向下兼容的目的以及特定的经常存在于各主要浏览器上的实际解析需求。

@geindex RFC; RFC 2732

@item RFC 2732@footnote{https://tools.ietf.org/html/rfc2732.html} - URL 中的 IPv6 Addresses 地址显示格式。

这指明了 IPv6 URL 的解析要求。

@geindex RFC; RFC 2396

@item RFC 2396@footnote{https://tools.ietf.org/html/rfc2396.html} - 统一资源标识符（URI）：通用语法

描述统一资源名称 (URN) 和统一资源定位符 (URL) 通用语义要求的文档。

@geindex RFC; RFC 2368

@item RFC 2368@footnote{https://tools.ietf.org/html/rfc2368.html} - mailto URL 模式。

mailto URL 模式的解析要求。

@geindex RFC; RFC 1808

@item RFC 1808@footnote{https://tools.ietf.org/html/rfc1808.html} - 相对统一资源定位符

这个请求注释包括联结绝对和相对 URL 的规则，其中包括大量控制边界情况处理的 "异常示例"。

@geindex RFC; RFC 1738

@item RFC 1738@footnote{https://tools.ietf.org/html/rfc1738.html} - 统一资源定位符 (URL)

这指明了绝对 URL 的正式语义和句法。
@end table


@node urllib error --- urllib request 引发的异常类,urllib robotparser --- robots txt 语法分析程序,urllib parse 用于解析 URL,互联网协议和支持
@anchor{library/urllib error doc}@anchor{2dd6}@anchor{library/urllib error module-urllib error}@anchor{127}@anchor{library/urllib error urllib-error-exception-classes-raised-by-urllib-request}@anchor{2dd7}@anchor{library/urllib error whatwg}@anchor{2dd8}
@subsection @code{urllib.error} --- urllib.request 引发的异常类


@geindex urllib.error (模块)

@strong{源代码：} Lib/urllib/error.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/urllib/error.py}


__________________________________________________________________


@ref{127,,urllib.error} 模块为 @ref{129,,urllib.request} 所引发的异常定义了异常类。 基础异常类是 @ref{2d37,,URLError}。

下列异常会被 @ref{127,,urllib.error} 按需引发：

@geindex URLError
@anchor{library/urllib error urllib error URLError}@anchor{2d37}
@deffn {例外} urllib.error.URLError

处理程序在遇到问题时会引发此异常（或其派生的异常）。 它是 @ref{30b,,OSError} 的一个子类。

@geindex reason (urllib.error.URLError 属性)
@anchor{library/urllib error urllib error URLError reason}@anchor{2dd9}
@deffn {属性} reason

此错误的原因。 它可以是一个消息字符串或另一个异常实例。
@end deffn


在 3.3 版更改: @ref{2d37,,URLError} 已被设为 @ref{30b,,OSError} 而不是 @ref{a7c,,IOError} 的子类。

@end deffn

@geindex HTTPError
@anchor{library/urllib error urllib error HTTPError}@anchor{9eb}
@deffn {例外} urllib.error.HTTPError

虽然是一个异常（@ref{2d37,,URLError} 的一个子类），@ref{9eb,,HTTPError} 也可以作为一个非异常的文件类返回值（与 @ref{885,,urlopen()} 返所回的对象相同）。 这适用于处理特殊 HTTP 错误例如作为认证请求的时候。

@geindex code (urllib.error.HTTPError 属性)
@anchor{library/urllib error urllib error HTTPError code}@anchor{2dda}
@deffn {属性} code

一个 HTTP 状态码，具体定义见 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html}。 这个数字的值对应于存放在 @ref{2ddb,,http.server.BaseHTTPRequestHandler.responses} 代码字典中的某个值。
@end deffn

@geindex reason (urllib.error.HTTPError 属性)
@anchor{library/urllib error urllib error HTTPError reason}@anchor{2ddc}
@deffn {属性} reason

这通常是一个解释本次错误原因的字符串。
@end deffn

@geindex headers (urllib.error.HTTPError 属性)
@anchor{library/urllib error urllib error HTTPError headers}@anchor{9ec}
@deffn {属性} headers

导致 @ref{9eb,,HTTPError} 的特定 HTTP 请求的 HTTP 响应头。


3.4 新版功能.

@end deffn
@end deffn

@geindex ContentTooShortError
@anchor{library/urllib error urllib error ContentTooShortError}@anchor{2ddd}
@deffn {例外} urllib.error.ContentTooShortError (msg, content)

此异常会在 @ref{2db2,,urlretrieve()} 函数检测到已下载的数据量小于期待的数据量（由 @emph{Content-Length} 头给定）时被引发。 @code{content} 属性中将存放已下载（可能被截断）的数据。
@end deffn

@node urllib robotparser --- robots txt 语法分析程序,http --- HTTP 模块,urllib error --- urllib request 引发的异常类,互联网协议和支持
@anchor{library/urllib robotparser doc}@anchor{2dde}@anchor{library/urllib robotparser module-urllib robotparser}@anchor{12b}@anchor{library/urllib robotparser urllib-robotparser-parser-for-robots-txt}@anchor{2ddf}
@subsection @code{urllib.robotparser} --- robots.txt 语法分析程序


@geindex urllib.robotparser (模块)

@strong{源代码：} Lib/urllib/robotparser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/urllib/robotparser.py}

@geindex WWW
@geindex World Wide Web
@geindex URL
@geindex robots.txt


__________________________________________________________________


此模块提供了一个单独的类 @ref{6ae,,RobotFileParser}，它可以回答关于某个特定用户代理是否能在 Web 站点获取发布 @code{robots.txt} 文件的 URL 的问题。 有关 @code{robots.txt} 文件结构的更多细节请参阅 @indicateurl{http://www.robotstxt.org/orig.html}。

@geindex RobotFileParser (urllib.robotparser 中的类)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser}@anchor{6ae}
@deffn {类} urllib.robotparser.RobotFileParser (url='@w{'})

这个类提供了一些可以读取、解析和回答关于 @emph{url} 上的 @code{robots.txt} 文件的问题的方法。

@geindex set_url() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser set_url}@anchor{2de0}
@deffn {方法} set_url (url)

设置指向 @code{robots.txt} 文件的 URL。
@end deffn

@geindex read() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser read}@anchor{2de1}
@deffn {方法} read ()

读取 @code{robots.txt} URL 并将其输入解析器。
@end deffn

@geindex parse() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser parse}@anchor{121e}
@deffn {方法} parse (lines)

解析行参数。
@end deffn

@geindex can_fetch() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser can_fetch}@anchor{2de2}
@deffn {方法} can_fetch (useragent, url)

如果允许 @emph{useragent} 按照被解析 @code{robots.txt} 文件中的规则来获取 @emph{url} 则返回 @code{True}。
@end deffn

@geindex mtime() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser mtime}@anchor{2de3}
@deffn {方法} mtime ()

返回最近一次获取 @code{robots.txt} 文件的时间。 这适用于需要定期检查 @code{robots.txt} 文件更新情况的长时间运行的网页爬虫。
@end deffn

@geindex modified() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser modified}@anchor{2de4}
@deffn {方法} modified ()

将最近一次获取 @code{robots.txt} 文件的时间设置为当前时间。
@end deffn

@geindex crawl_delay() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser crawl_delay}@anchor{2de5}
@deffn {方法} crawl_delay (useragent)

为指定的 @emph{useragent} 从 @code{robots.txt} 返回 @code{Crawl-delay} 形参。 如果此形参不存在或不适用于指定的 @emph{useragent} 或者此形参的 @code{robots.txt} 条目存在语法错误，则返回 @code{None}。


3.6 新版功能.

@end deffn

@geindex request_rate() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser request_rate}@anchor{2de6}
@deffn {方法} request_rate (useragent)

以 @ref{b84,,named tuple} @code{RequestRate(requests, seconds)} 的形式从 @code{robots.txt} 返回 @code{Request-rate} 形参的内容。 如果此形参不存在或不适用于指定的 @emph{useragent} 或者此形参的 @code{robots.txt} 条目存在语法错误，则返回 @code{None}。


3.6 新版功能.

@end deffn

@geindex site_maps() (urllib.robotparser.RobotFileParser 方法)
@anchor{library/urllib robotparser urllib robotparser RobotFileParser site_maps}@anchor{11b5}
@deffn {方法} site_maps ()

以 @ref{1f9,,list()} 的形式从 @code{robots.txt} 返回 @code{Sitemap} 形参的内容。 如果此形参不存在或者此形参的 @code{robots.txt} 条目存在语法错误，则返回 @code{None}。


3.8 新版功能.

@end deffn
@end deffn

下面的例子演示了 @ref{6ae,,RobotFileParser} 类的基本用法:

@example
>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
3
>>> rrate.seconds
20
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True
@end example

@node http --- HTTP 模块,http client --- HTTP 协议客户端,urllib robotparser --- robots txt 语法分析程序,互联网协议和支持
@anchor{library/http doc}@anchor{2de7}@anchor{library/http http-http-modules}@anchor{2de8}@anchor{library/http module-http}@anchor{92}
@subsection @code{http} --- HTTP 模块


@geindex http (模块)

@strong{源代码:} Lib/http/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/http/__init__.py}

@geindex HTTP; protocol
@geindex HTTP; http (standard module)


__________________________________________________________________


@ref{92,,http} 是一个包，它收集了多个用于处理超文本传输协议的模块:


@itemize *

@item 
@ref{93,,http.client} 是一个低层级的 HTTP 协议客户端；对于高层级的 URL 访问请使用 @ref{129,,urllib.request}

@item 
@ref{96,,http.server} 包含基于 @ref{f0,,socketserver} 的基本 HTTP 服务类

@item 
@ref{95,,http.cookies} 包含一些有用来实现通过 cookies 进行状态管理的工具

@item 
@ref{94,,http.cookiejar} 提供了 cookies 的持久化
@end itemize

@ref{92,,http} 也是一个通过 @ref{1ac,,http.HTTPStatus} 枚举定义了一些 HTTP 状态码以及相关联消息的模块

@geindex HTTPStatus (http 中的类)
@anchor{library/http http HTTPStatus}@anchor{1ac}
@deffn {类} http.HTTPStatus


3.5 新版功能.


@ref{68e,,enum.IntEnum} 的子类，它定义了组 HTTP 状态码，原理短语以及用英语书写的长描述文本。

用法:

@example
>>> from http import HTTPStatus
>>> HTTPStatus.OK
<HTTPStatus.OK: 200>
>>> HTTPStatus.OK == 200
True
>>> HTTPStatus.OK.value
200
>>> HTTPStatus.OK.phrase
'OK'
>>> HTTPStatus.OK.description
'Request fulfilled, document follows'
>>> list(HTTPStatus)
[<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...]
@end example
@end deffn

@menu
* HTTP 状态码:: 

@end menu

@node HTTP 状态码,,,http --- HTTP 模块
@anchor{library/http http-status-codes}@anchor{2de9}@anchor{library/http id1}@anchor{2dea}
@subsubsection HTTP 状态码


已支持并且已在 @ref{1ac,,http.HTTPStatus} IANA 注册@footnote{https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml} 的状态码有：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

状态码

@tab

映射名

@tab

详情

@item

@code{100}

@tab

@code{CONTINUE}

@tab

HTTP/1.1 
@geindex RFC; RFC 7231
RFC 7231@footnote{https://tools.ietf.org/html/rfc7231.html},  6.2.1 节

@item

@code{101}

@tab

@code{SWITCHING_PROTOCOLS}

@tab

HTTP/1.1 RFC 7231,  6.2.2 节

@item

@code{102}

@tab

@code{PROCESSING}

@tab

WebDAV RFC 2518,  10.1 节

@item

@code{103}

@tab

@code{EARLY_HINTS}

@tab

用于指定提示 
@geindex RFC; RFC 8297
RFC 8297@footnote{https://tools.ietf.org/html/rfc8297.html} 的 HTTP 状态码

@item

@code{200}

@tab

@code{OK}

@tab

HTTP/1.1 RFC 7231,  6.3.1 节

@item

@code{201}

@tab

@code{CREATED}

@tab

HTTP/1.1 RFC 7231,  6.3.2 节

@item

@code{202}

@tab

@code{ACCEPTED}

@tab

HTTP/1.1 RFC 7231,  6.3.3 节

@item

@code{203}

@tab

@code{NON_AUTHORITATIVE_INFORMATION}

@tab

HTTP/1.1 RFC 7231,  6.3.4 节

@item

@code{204}

@tab

@code{NO_CONTENT}

@tab

HTTP/1.1 RFC 7231,  6.3.5 节

@item

@code{205}

@tab

@code{RESET_CONTENT}

@tab

HTTP/1.1 RFC 7231,  6.3.6 节

@item

@code{206}

@tab

@code{PARTIAL_CONTENT}

@tab

HTTP/1.1 RFC 7233,  4.1 节

@item

@code{207}

@tab

@code{MULTI_STATUS}

@tab

WebDAV RFC 4918,  11.1 节

@item

@code{208}

@tab

@code{ALREADY_REPORTED}

@tab

WebDAV Binding Extensions RFC 5842, 7.1 节（实验性）

@item

@code{226}

@tab

@code{IM_USED}

@tab

Delta Encoding in HTTP RFC 3229,  10.4.1 节

@item

@code{300}

@tab

@code{MULTIPLE_CHOICES}：有多种资源可选择

@tab

HTTP/1.1 RFC 7231,  6.4.1 节

@item

@code{301}

@tab

@code{MOVED_PERMANENTLY}：永久移动

@tab

HTTP/1.1 RFC 7231,  6.4.2 节

@item

@code{302}

@tab

@code{FOUND}：临时移动

@tab

HTTP/1.1 RFC 7231,  6.4.3 节

@item

@code{303}

@tab

@code{SEE_OTHER}：已经移动

@tab

HTTP/1.1 RFC 7231, 6.4.4 节

@item

@code{304}

@tab

@code{NOT_MODIFIED}：没有修改

@tab

HTTP/1.1 RFC 7232, 4.1 节

@item

@code{305}

@tab

@code{USE_PROXY}：使用代理

@tab

HTTP/1.1 RFC 7231, 6.4.5 节

@item

@code{307}

@tab

@code{TEMPORARY_REDIRECT}：临时重定向

@tab

HTTP/1.1 
@geindex RFC; RFC 7231
RFC 7231@footnote{https://tools.ietf.org/html/rfc7231.html}, 6.4.7 节

@item

@code{308}

@tab

@code{PERMANENT_REDIRECT}：永久重定向

@tab

Permanent Redirect 
@geindex RFC; RFC 7238
RFC 7238@footnote{https://tools.ietf.org/html/rfc7238.html}, Section 3 (Experimental)

@item

@code{400}

@tab

@code{BAD_REQUEST}：错误请求

@tab

HTTP/1.1 RFC 7231, 6.5.1 节

@item

@code{401}

@tab

@code{UNAUTHORIZED}：未授权

@tab

HTTP/1.1 Authentication RFC 7235, 3.1 节

@item

@code{402}

@tab

@code{PAYMENT_REQUIRED}：保留，将来使用

@tab

HTTP/1.1 RFC 7231, 6.5.2 节

@item

@code{403}

@tab

@code{FORBIDDEN}：禁止

@tab

HTTP/1.1 RFC 7231, 6.5.3 节

@item

@code{404}

@tab

@code{NOT_FOUND}：没有找到

@tab

HTTP/1.1 RFC 7231, 6.5.4 节

@item

@code{405}

@tab

@code{METHOD_NOT_ALLOWED}：该请求方法不允许

@tab

HTTP/1.1 RFC 7231, 6.5.5 节

@item

@code{406}

@tab

@code{NOT_ACCEPTABLE}：不可接受

@tab

HTTP/1.1 RFC 7231, 6.5.6 节

@item

@code{407}

@tab

@code{PROXY_AUTHENTICATION_REQUIRED}：要求使用代理验证身份

@tab

HTTP/1.1 Authentication RFC 7235, 3.1 节

@item

@code{408}

@tab

@code{REQUEST_TIMEOUT}：请求超时

@tab

HTTP/1.1 
@geindex RFC; RFC 7231
RFC 7231@footnote{https://tools.ietf.org/html/rfc7231.html}, 6.5.7 节

@item

@code{409}

@tab

@code{CONFLICT}：冲突

@tab

HTTP/1.1 RFC 7231, 6.5.8 节

@item

@code{410}

@tab

@code{GONE}：已经不在了

@tab

HTTP/1.1 RFC 7231, 6.5.9 节

@item

@code{411}

@tab

@code{LENGTH_REQUIRED}：长度要求

@tab

HTTP/1.1 RFC 7231, 6.5.10 节

@item

@code{412}

@tab

@code{PRECONDITION_FAILED}：前提条件错误

@tab

HTTP/1.1 RFC 7232, 4.2 节

@item

@code{413}

@tab

@code{REQUEST_ENTITY_TOO_LARGE}：请求体太大了

@tab

HTTP/1.1 RFC 7231, 6.5.11 节

@item

@code{414}

@tab

@code{REQUEST_URI_TOO_LONG}：请求URI太长了

@tab

HTTP/1.1 RFC 7231, 6.5.12 节

@item

@code{415}

@tab

@code{UNSUPPORTED_MEDIA_TYPE}：不支持的媒体格式

@tab

HTTP/1.1 RFC 7231,  6.5.13 节

@item

@code{416}

@tab

@code{REQUESTED_RANGE_NOT_SATISFIABLE}

@tab

HTTP/1.1 Range Requests RFC 7233, 4.4 节

@item

@code{417}

@tab

@code{EXPECTATION_FAILED}：期望失败

@tab

HTTP/1.1 RFC 7231,  6.5.14 节

@item

@code{418}

@tab

@code{IM_A_TEAPOT}

@tab

HTCPCP/1.0 
@geindex RFC; RFC 2324
RFC 2324@footnote{https://tools.ietf.org/html/rfc2324.html}, Section 2.3.2

@item

@code{421}

@tab

@code{MISDIRECTED_REQUEST}

@tab

HTTP/2 
@geindex RFC; RFC 7540
RFC 7540@footnote{https://tools.ietf.org/html/rfc7540.html}, 9.1.2 节

@item

@code{422}

@tab

@code{UNPROCESSABLE_ENTITY}：可加工实体

@tab

WebDAV RFC 4918, 11.2 节

@item

@code{423}

@tab

@code{LOCKED}：锁着

@tab

WebDAV RFC 4918, 11.3 节

@item

@code{424}

@tab

@code{FAILED_DEPENDENCY}：失败的依赖

@tab

WebDAV RFC 4918, 11.4 节

@item

@code{425}

@tab

@code{TOO_EARLY}

@tab

使用 HTTP 
@geindex RFC; RFC 8470
RFC 8470@footnote{https://tools.ietf.org/html/rfc8470.html} 中的早期数据

@item

@code{426}

@tab

@code{UPGRADE_REQUIRED}：升级需要

@tab

HTTP/1.1 RFC 7231, 6.5.15 节

@item

@code{428}

@tab

@code{PRECONDITION_REQUIRED}：先决条件要求

@tab

Additional HTTP Status Codes RFC 6585

@item

@code{429}

@tab

@code{TOO_MANY_REQUESTS}：太多的请求

@tab

Additional HTTP Status Codes RFC 6585

@item

@code{431}

@tab

@code{REQUEST_HEADER_FIELDS_TOO_LARGE}：请求头太大

@tab

Additional HTTP Status Codes RFC 6585

@item

@code{451}

@tab

@code{UNAVAILABLE_FOR_LEGAL_REASONS}

@tab

HTTP 状态码用于报告法律障碍 
@geindex RFC; RFC 7725
RFC 7725@footnote{https://tools.ietf.org/html/rfc7725.html}

@item

@code{500}

@tab

@code{INTERNAL_SERVER_ERROR}：内部服务错误

@tab

HTTP/1.1 RFC 7231, 6.6.1 节

@item

@code{501}

@tab

@code{NOT_IMPLEMENTED}：不可执行

@tab

HTTP/1.1 RFC 7231, 6.6.2 节

@item

@code{502}

@tab

@code{BAD_GATEWAY}：无效网关

@tab

HTTP/1.1 RFC 7231, 6.6.3 节

@item

@code{503}

@tab

@code{SERVICE_UNAVAILABLE}：服务不可用

@tab

HTTP/1.1 RFC 7231, 6.6.4 节

@item

@code{504}

@tab

@code{GATEWAY_TIMEOUT}：网关超时

@tab

HTTP/1.1 RFC 7231, 6.6.5 节

@item

@code{505}

@tab

@code{HTTP_VERSION_NOT_SUPPORTED}：HTTP版本不支持

@tab

HTTP/1.1 RFC 7231, 6.6.6 节

@item

@code{506}

@tab

@code{VARIANT_ALSO_NEGOTIATES}：服务器存在内部配置错误

@tab

透明内容协商在： HTTP 
@geindex RFC; RFC 2295
RFC 2295@footnote{https://tools.ietf.org/html/rfc2295.html},  8.1 节（实验性）

@item

@code{507}

@tab

@code{INSUFFICIENT_STORAGE}：存储不足

@tab

WebDAV RFC 4918, 11.5 节

@item

@code{508}

@tab

@code{LOOP_DETECTED}：循环检测

@tab

WebDAV Binding Extensions RFC 5842,  7.2 节（实验性）

@item

@code{510}

@tab

@code{NOT_EXTENDED}：不扩展

@tab

WebDAV Binding Extensions RFC 5842, 7.2 节（实验性）

@item

@code{511}

@tab

@code{NETWORK_AUTHENTICATION_REQUIRED}：要求网络身份验证

@tab

Additional HTTP Status Codes 
@geindex RFC; RFC 6585
RFC 6585@footnote{https://tools.ietf.org/html/rfc6585.html},  6 节

@end multitable


为了保持向后兼容性，枚举值也以常量形式出现在 @ref{93,,http.client} 模块中，。 枚举名等于常量名 (例如 @code{http.HTTPStatus.OK} 也可以是 @code{http.client.OK})。


在 3.7 版更改: 添加了 @code{421 MISDIRECTED_REQUEST} 状态码。



3.8 新版功能: 添加了 @code{451 UNAVAILABLE_FOR_LEGAL_REASONS} 状态码。



3.9 新版功能: 增加了 @code{103 EARLY_HINTS}, @code{418 IM_A_TEAPOT} 和 @code{425 TOO_EARLY} 状态码


@node http client --- HTTP 协议客户端,ftplib --- FTP 协议客户端,http --- HTTP 模块,互联网协议和支持
@anchor{library/http client doc}@anchor{2deb}@anchor{library/http client http-client-http-protocol-client}@anchor{2dec}@anchor{library/http client module-http client}@anchor{93}
@subsection @code{http.client} --- HTTP 协议客户端


@geindex http.client (模块)

@strong{源代码：} Lib/http/client.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/http/client.py}

@geindex HTTP; protocol
@geindex HTTP; http.client (standard module)

@geindex 模块; urllib.request


__________________________________________________________________


这个模块定义了实现 HTTP 和 HTTPS 协议客户端的类。 它通常不直接使用 --- 模块 @ref{129,,urllib.request} 用它来处理使用 HTTP 和 HTTPS 的 URL。


@subsubheading 参见


对于更高级别的 HTTP 客户端接口，建议使用 Requests@footnote{https://requests.readthedocs.io/en/master/}  。


@cartouche
@quotation 注解 
HTTPS 支持仅在编译 Python 时启用了 SSL 支持的情况下（通过 @ref{f3,,ssl} 模块）可用。
@end quotation
@end cartouche

该模块支持以下类：

@geindex HTTPConnection (http.client 中的类)
@anchor{library/http client http client HTTPConnection}@anchor{4a1}
@deffn {类} http.client.HTTPConnection (host, port=None[, timeout], source_address=None, blocksize=8192)

@ref{4a1,,HTTPConnection} 的实例代表与 HTTP 的一个连接事务。 它的实例化应当传入一个主机和可选的端口号。 如果没有传入端口号，如果主机字符串的形式为 @code{主机:端口} 则会从中提取端口，否则将使用默认的 HTTP 端口（80）。 如果给出了可选的 @emph{timeout} 参数，则阻塞操作（例如连接尝试）将在指定的秒数之后超时（如果未给出，则使用全局默认超时设置）。 可选的 @emph{source_address} 参数可以为一个 (主机, 端口) 元组，用作进行 HTTP 连接的源地址。 可选的 @emph{blocksize} 参数可以字节为单位设置缓冲区的大小，用来发送文件类消息体。

举个例子，以下调用都是创建连接到同一主机和端口的服务器的实例：

@example
>>> h1 = http.client.HTTPConnection('www.python.org')
>>> h2 = http.client.HTTPConnection('www.python.org:80')
>>> h3 = http.client.HTTPConnection('www.python.org', 80)
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
@end example


在 3.2 版更改: 添加了 @emph{source_address}。



在 3.4 版更改: 删除了 @emph{strict} 参数，不再支持 HTTP 0.9 风格的“简单响应”。



在 3.7 版更改: 添加了 @emph{blocksize} 参数。

@end deffn

@geindex HTTPSConnection (http.client 中的类)
@anchor{library/http client http client HTTPSConnection}@anchor{4a2}
@deffn {类} http.client.HTTPSConnection (host, port=None, key_file=None, cert_file=None[, timeout], source_address=None, *, context=None, check_hostname=None, blocksize=8192)

@ref{4a1,,HTTPConnection} 的子类，使用 SSL 与安全服务器进行通信。 默认端口为 @code{443}。 如果指定了 @emph{context}，它必须为一个描述 SSL 各选项的 @ref{4f2,,ssl.SSLContext} 实例。

请参阅 @ref{2711,,安全考量} 了解有关最佳实践的更多信息。


在 3.2 版更改: 添加了 @emph{source_address}, @emph{context} 和 @emph{check_hostname}。



在 3.2 版更改: 这个类目前会在可能的情况下（即如果 @ref{2839,,ssl.HAS_SNI} 为真值）支持 HTTPS 虚拟主机。



在 3.4 版更改: 删除了 @emph{strict} 参数，不再支持 HTTP 0.9 风格的“简单响应”。



在 3.4.3 版更改: 目前这个类在默认情况下会执行所有必要的证书和主机检查。 要回复到先前的非验证行为，可以将 @code{ssl._create_unverified_context()} 传递给 @emph{context} 参数。



在 3.8 版更改: 该类现在对于默认的 @emph{context} 或在传入 @emph{cert_file} 并附带自定义 @emph{context} 时会启用 TLS 1.3 @ref{358,,ssl.SSLContext.post_handshake_auth}。



3.6 版后已移除: @emph{key_file} 和 @emph{cert_file} 已弃用并转而推荐 @emph{context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。

@emph{check_hostname} 参数也已弃用；应当改用 @emph{context} 的 @ref{2824,,ssl.SSLContext.check_hostname} 属性。

@end deffn

@geindex HTTPResponse (http.client 中的类)
@anchor{library/http client http client HTTPResponse}@anchor{af8}
@deffn {类} http.client.HTTPResponse (sock, debuglevel=0, method=None, url=None)

在成功连接后返回类的实例，而不是由用户直接实例化。


在 3.4 版更改: 删除了 @emph{strict} 参数，不再支持HTTP 0.9 风格的“简单响应”。

@end deffn

这个模块定义了以下函数：

@geindex parse_headers() (在 http.client 模块中)
@anchor{library/http client http client parse_headers}@anchor{11bf}
@deffn {函数} http.client.parse_headers (fp)

从文件指针 @emph{fp} 中解析头部信息，该文件代表 HTTP 请求/响应。该文件必须是 @code{BufferedIOBase}  reader 对象（即不是文本），并且必须提供符合 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 格式的头部。

该函数返回 @code{http.client.HTTPMessage} 的实例，带有头部各个字段，但不带正文数据（与 @ref{2ded,,HTTPResponse.msg} 和 @ref{2dee,,http.server.BaseHTTPRequestHandler.headers} 一样）。返回之后，文件指针 @emph{fp} 已为读取 HTTP 正文做好准备了。

@cartouche
@quotation 注解 
@ref{11bf,,parse_headers()} 不会解析 HTTP 消息的开始行；只会解析各 @code{Name: value} 行。文件必须为读取这些字段做好准备，所以在调用该函数之前，第一行应该已经被读取过了。
@end quotation
@end cartouche
@end deffn

下列异常可以适当地被引发:

@geindex HTTPException
@anchor{library/http client http client HTTPException}@anchor{2def}
@deffn {例外} http.client.HTTPException

此模块中其他异常的基类。 它是 @ref{2e3,,Exception} 的一个子类。
@end deffn

@geindex NotConnected
@anchor{library/http client http client NotConnected}@anchor{2df0}
@deffn {例外} http.client.NotConnected

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex InvalidURL
@anchor{library/http client http client InvalidURL}@anchor{2df1}
@deffn {例外} http.client.InvalidURL

@ref{2def,,HTTPException} 的一个子类，如果给出了一个非数字或为空值的端口就会被引发。
@end deffn

@geindex UnknownProtocol
@anchor{library/http client http client UnknownProtocol}@anchor{2df2}
@deffn {例外} http.client.UnknownProtocol

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex UnknownTransferEncoding
@anchor{library/http client http client UnknownTransferEncoding}@anchor{2df3}
@deffn {例外} http.client.UnknownTransferEncoding

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex UnimplementedFileMode
@anchor{library/http client http client UnimplementedFileMode}@anchor{2df4}
@deffn {例外} http.client.UnimplementedFileMode

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex IncompleteRead
@anchor{library/http client http client IncompleteRead}@anchor{2df5}
@deffn {例外} http.client.IncompleteRead

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex ImproperConnectionState
@anchor{library/http client http client ImproperConnectionState}@anchor{2df6}
@deffn {例外} http.client.ImproperConnectionState

@ref{2def,,HTTPException} 的一个子类。
@end deffn

@geindex CannotSendRequest
@anchor{library/http client http client CannotSendRequest}@anchor{2df7}
@deffn {例外} http.client.CannotSendRequest

@ref{2df6,,ImproperConnectionState} 的一个子类。
@end deffn

@geindex CannotSendHeader
@anchor{library/http client http client CannotSendHeader}@anchor{2df8}
@deffn {例外} http.client.CannotSendHeader

@ref{2df6,,ImproperConnectionState} 的一个子类。
@end deffn

@geindex ResponseNotReady
@anchor{library/http client http client ResponseNotReady}@anchor{2df9}
@deffn {例外} http.client.ResponseNotReady

@ref{2df6,,ImproperConnectionState} 的一个子类。
@end deffn

@geindex BadStatusLine
@anchor{library/http client http client BadStatusLine}@anchor{2dfa}
@deffn {例外} http.client.BadStatusLine

@ref{2def,,HTTPException} 的一个子类。 如果服务器反馈了一个我们不理解的 HTTP 状态码就会被引发。
@end deffn

@geindex LineTooLong
@anchor{library/http client http client LineTooLong}@anchor{2dfb}
@deffn {例外} http.client.LineTooLong

@ref{2def,,HTTPException} 的一个子类。 如果在 HTTP 协议中从服务器接收到过长的行就会被引发。
@end deffn

@geindex RemoteDisconnected
@anchor{library/http client http client RemoteDisconnected}@anchor{7e0}
@deffn {例外} http.client.RemoteDisconnected

@ref{a8a,,ConnectionResetError} 和 @ref{2dfa,,BadStatusLine} 的一个子类。 当尝试读取响应时的结果是未从连接读取到数据时由 @ref{7df,,HTTPConnection.getresponse()} 引发，表明远端已关闭连接。


3.5 新版功能: 在此之前引发的异常为 @ref{2dfa,,BadStatusLine}@code{('@w{'})}。

@end deffn

此模块中定义的常量为：

@geindex HTTP_PORT() (在 http.client 模块中)
@anchor{library/http client http client HTTP_PORT}@anchor{2dfc}
@deffn {数据} http.client.HTTP_PORT

HTTP 协议默认的端口号 (总是 @code{80})。
@end deffn

@geindex HTTPS_PORT() (在 http.client 模块中)
@anchor{library/http client http client HTTPS_PORT}@anchor{2dfd}
@deffn {数据} http.client.HTTPS_PORT

HTTPS 协议默认的端口号 (总是 @code{443})。
@end deffn

@geindex responses() (在 http.client 模块中)
@anchor{library/http client http client responses}@anchor{2dfe}
@deffn {数据} http.client.responses

这个字典把 HTTP 1.1 状态码映射到 W3C 名称。

例如：@code{http.client.responses[http.client.NOT_FOUND]} 是 @code{'NOT FOUND} （未发现）。
@end deffn

本模块中可用的 HTTP 状态码常量可以参见 @ref{2de9,,HTTP 状态码} 。

@menu
* HTTPConnection 对象:: 
* HTTPResponse 对象:: 
* 示例: 示例<34>. 
* HTTPMessage 对象:: 

@end menu

@node HTTPConnection 对象,HTTPResponse 对象,,http client --- HTTP 协议客户端
@anchor{library/http client httpconnection-objects}@anchor{2dff}@anchor{library/http client id1}@anchor{2e00}
@subsubsection HTTPConnection 对象


@ref{4a1,,HTTPConnection} 实例拥有以下方法：

@geindex request() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection request}@anchor{652}
@deffn {方法} HTTPConnection.request (method, url, body=None, headers=@{@}, *, encode_chunked=False)

这会使用 HTTP 请求方法 @emph{method} 和选择器 @emph{url} 向服务器发送请求。

如果给定 @emph{body}，那么给定的数据会在信息头完成之后发送。它可能是一个 @ref{206,,str} 、一个 @ref{6e9,,bytes-like object} 、一个打开的 @ref{c1d,,file object}，或者 @ref{172,,bytes} 迭代器。如果 @emph{body} 是字符串，它会按 HTTP 默认的 ISO-8859-1 编码；如果是一个字节类对象，它会按原样发送；如果是 @ref{c1d,,file object} ，文件的内容会被发送，这个文件对象应该支持 @code{read()} 方法。如果这个文件对象是一个 @ref{d09,,io.TextIOBase} 实例， @code{read()} 方法返回的数据会按 ISO-8859-1 编码，否则 @code{read()} 方法返回的数据会按原样发送；如果 @emph{body} 是一个迭代器，迭代器中的元素会被发送，直到迭代器耗尽。

@emph{headers} 参数应是额外的随请求发送的 HTTP 信息头的字典。

如果 @emph{headers} 既不包含 Content-Length 也没有 Transfer-Encoding，但存在请求正文，那么这些头字段中的一个会自动设定。如果 @emph{body} 是 @code{None}，那么对于要求正文的方法 (@code{PUT}，@code{POST}，和 @code{PATCH})，Content-Length 头会被设为 @code{0}。如果 @emph{body} 是字符串或者类似字节的对象，并且也不是 @ref{c1d,,文件}，Content-Length 头会设为正文的长度。任何其他类型的 @emph{body} （一般是文件或迭代器）会按块编码，这时会自动设定 Transfer-Encoding 头以代替 Content-Length。

在 @emph{headers} 中指定 Transfer-Encoding 时， @emph{encode_chunked} 是唯一相关的参数。如果 @emph{encode_chunked} 为 @code{False}，HTTPConnection 对象会假定所有的编码都由调用代码处理。如果为 @code{True}，正文会按块编码。

@cartouche
@quotation 注解 
HTTP 协议在 1.1 版中添加了块传输编码。除非明确知道 HTTP 服务器可以处理 HTTP 1.1，调用者要么必须指定 Content-Length，要么必须传入 @ref{206,,str} 或字节类对象，注意该对象不能是表达 body 的文件。
@end quotation
@end cartouche


3.2 新版功能: @emph{body} 现在可以是可迭代对象了。



在 3.6 版更改: 如果 Content-Length 和 Transfer-Encoding 都没有在 @emph{headers} 中设置，文件和可迭代的 @emph{body} 对象现在会按块编码。添加了 @emph{encode_chunked} 参数。不会尝试去确定文件对象的 Content-Length。

@end deffn

@geindex getresponse() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection getresponse}@anchor{7df}
@deffn {方法} HTTPConnection.getresponse ()

应当在发送一个请求从服务器获取响应时被调用。 返回一个 @ref{af8,,HTTPResponse} 的实例。

@cartouche
@quotation 注解 
请注意你必须在读取了整个响应之后才能向服务器发送新的请求。
@end quotation
@end cartouche


在 3.5 版更改: 如果引发了 @ref{7e1,,ConnectionError} 或其子类， @ref{4a1,,HTTPConnection} 对象将在发送新的请求时准备好重新连接。

@end deffn

@geindex set_debuglevel() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection set_debuglevel}@anchor{2e01}
@deffn {方法} HTTPConnection.set_debuglevel (level)

设置调试等级。 默认的调试等级为 @code{0}，意味着不会打印调试输出。 任何大于 @code{0} 的值将使得所有当前定义的调试输出被打印到 stdout。 @code{debuglevel} 会被传给任何新创建的 @ref{af8,,HTTPResponse} 对象。


3.1 新版功能.

@end deffn

@geindex set_tunnel() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection set_tunnel}@anchor{c85}
@deffn {方法} HTTPConnection.set_tunnel (host, port=None, headers=None)

为 HTTP 连接隧道设置主机和端口。 这将允许通过代理服务器运行连接。

host 和 port 参数指明隧道连接的位置（即 CONNECT 请求所包含的地址，而 @emph{不是} 代理服务器的地址）。

headers 参数应为一个随 CONNECT 请求发送的额外 HTTP 标头的映射。

例如，要通过一个运行于本机 8080 端口的 HTTPS 代理服务器隧道，我们应当向 @ref{4a2,,HTTPSConnection} 构造器传入代理的地址，并将我们最终想要访问的主机地址传给 @ref{c85,,set_tunnel()} 方法:

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")
@end example


3.2 新版功能.

@end deffn

@geindex connect() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection connect}@anchor{2e02}
@deffn {方法} HTTPConnection.connect ()

当对象被创建后连接到指定的服务器。 默认情况下，如果客户端还未建立连接，此函数会在发送请求时自动被调用。
@end deffn

@geindex close() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection close}@anchor{2e03}
@deffn {方法} HTTPConnection.close ()

关闭到服务器的连接。
@end deffn

@geindex blocksize (http.client.HTTPConnection 属性)
@anchor{library/http client http client HTTPConnection blocksize}@anchor{2e04}
@deffn {属性} HTTPConnection.blocksize

用于发送文件类消息体的缓冲区大小。


3.7 新版功能.

@end deffn

作为对使用上述 @code{request()} 方法的替代同，你也可以通过使用下面的四个函数，分步骤发送请的请求。

@geindex putrequest() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection putrequest}@anchor{2e05}
@deffn {方法} HTTPConnection.putrequest (method, url, skip_host=False, skip_accept_encoding=False)

应为连接服务器之后首先调用的函数。将向服务器发送一行数据，包含 @emph{method} 字符串、@emph{url} 字符串和 HTTP 版本（@code{HTTP/1.1}）。若要禁止自动发送 @code{Host:} 或 @code{Accept-Encoding:} 头部信息（比如需要接受其他编码格式的内容），请将 @emph{skip_host} 或 @emph{skip_accept_encoding} 设为非 False 值。
@end deffn

@geindex putheader() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection putheader}@anchor{2e06}
@deffn {方法} HTTPConnection.putheader (header, argument[, ...])

向服务器发送一个 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 格式的头部。将向服务器发送一行由头、冒号和空格以及第一个参数组成的数据。 如果还给出了其他参数，将在后续行中发送，每行由一个制表符和一个参数组成。
@end deffn

@geindex endheaders() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection endheaders}@anchor{653}
@deffn {方法} HTTPConnection.endheaders (message_body=None, *, encode_chunked=False)

向服务器发送一个空行，表示头部文件结束。可选的 @emph{message_body} 参数可用于传入一个与请求相关的消息体。

如果 @emph{encode_chunked} 为 @code{True}，则对 @emph{message_body} 的每次迭代结果将依照 
@geindex RFC; RFC 7230
RFC 7230@footnote{https://tools.ietf.org/html/rfc7230.html} 3.3.1 节的规范进行分块编码。数据如何编码取决于 @emph{message_body} 的类型。 如果 @emph{message_body} 实现了 @ref{174c,,buffer 接口}，编码将生成一个数据块。如果 @emph{message_body} 是  @ref{1849,,collections.abc.Iterable}，则 @emph{message_body} 的每次迭代都会产生一个块。 如果 @emph{message_body} 为  @ref{c1d,,file object}，那么每次调用 @code{.read()} 都会产生一个数据块。在 @emph{message_body} 结束后，本方法立即会自动标记块编码数据的结束。

@cartouche
@quotation 注解 
由于分块编码的规范要求，迭代器本身产生的空块将被分块编码器忽略。这是为了避免目标服务器因错误编码而过早终止对请求的读取。
@end quotation
@end cartouche


3.6 新版功能: 支持分块编码。加入了 @emph{encode_chunked} 参数。

@end deffn

@geindex send() (http.client.HTTPConnection 方法)
@anchor{library/http client http client HTTPConnection send}@anchor{2e07}
@deffn {方法} HTTPConnection.send (data)

发送数据到服务器。本函数只应在调用 @ref{653,,endheaders()} 方法之后且调用  @ref{7df,,getresponse()} 之前直接调用。
@end deffn

@node HTTPResponse 对象,示例<34>,HTTPConnection 对象,http client --- HTTP 协议客户端
@anchor{library/http client httpresponse-objects}@anchor{2e08}@anchor{library/http client id2}@anchor{2e09}
@subsubsection HTTPResponse 对象


@ref{af8,,HTTPResponse} 实例封装了来自服务器的 HTTP 响应。通过它可以访问请求头和响应体。响应是可迭代对象，可在 with 语句中使用。


在 3.5 版更改: 现在已实现了 @ref{689,,io.BufferedIOBase} 接口，并且支持所有的读取操作。


@geindex read() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse read}@anchor{2e0a}
@deffn {方法} HTTPResponse.read ([amt])

读取并返回响应体，或后续 @emph{amt} 个字节。
@end deffn

@geindex readinto() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse readinto}@anchor{af9}
@deffn {方法} HTTPResponse.readinto (b)

读取响应体的后续 len(b) 个字节到缓冲区 @emph{b}。返回读取的字节数。


3.3 新版功能.

@end deffn

@geindex getheader() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse getheader}@anchor{2e0b}
@deffn {方法} HTTPResponse.getheader (name, default=None)

返回头部信息中的 @emph{name} 值，如果没有与 @emph{name} 匹配的字段，则返回*default*。如果名为 @emph{name} 的字段不止一个，则返回所有字段，中间用 ', ' 连接。 如果 'default' 不是单个字符串，而是其他可迭代对象，则其元素同样以逗号连接并返回。
@end deffn

@geindex getheaders() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse getheaders}@anchor{2e0c}
@deffn {方法} HTTPResponse.getheaders ()

返回  (header, value) 元组构成的列表。
@end deffn

@geindex fileno() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse fileno}@anchor{2e0d}
@deffn {方法} HTTPResponse.fileno ()

返回底层套接字的 @code{fileno}。
@end deffn

@geindex msg (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse msg}@anchor{2ded}
@deffn {属性} HTTPResponse.msg

包含响应头的 @code{http.client.HTTPMessage} 实例。@code{http.client.HTTPMessage} 是 @ref{70,,email.message} 的子类。
@end deffn

@geindex version (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse version}@anchor{2e0e}
@deffn {属性} HTTPResponse.version

服务器使用的 HTTP 协议版本。10 代表 HTTP/1.0，11 代表 HTTP/1.1。
@end deffn

@geindex url (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse url}@anchor{2e0f}
@deffn {属性} HTTPResponse.url

已读取资源的 URL，通常用于确定是否进行了重定向。
@end deffn

@geindex headers (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse headers}@anchor{2e10}
@deffn {属性} HTTPResponse.headers

响应的头部信息，形式为 @ref{645,,email.message.EmailMessage} 的实例。
@end deffn

@geindex status (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse status}@anchor{2e11}
@deffn {属性} HTTPResponse.status

由服务器返回的状态码。
@end deffn

@geindex reason (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse reason}@anchor{2d34}
@deffn {属性} HTTPResponse.reason

服务器返回的原因短语。
@end deffn

@geindex debuglevel (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse debuglevel}@anchor{2e12}
@deffn {属性} HTTPResponse.debuglevel

一个调试钩子。如果 @ref{2e12,,debuglevel} 大于零，状态信息将在读取和解析响应数据时打印输出到 stdout。
@end deffn

@geindex closed (http.client.HTTPResponse 属性)
@anchor{library/http client http client HTTPResponse closed}@anchor{2e13}
@deffn {属性} HTTPResponse.closed

如果流被关闭，则为`@w{`}True`@w{`}。
@end deffn

@geindex geturl() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse geturl}@anchor{2e14}
@deffn {方法} HTTPResponse.geturl ()


3.9 版后已移除: 已弃用，建议用 @ref{2e0f,,url}。

@end deffn

@geindex info() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse info}@anchor{2e15}
@deffn {方法} HTTPResponse.info ()


3.9 版后已移除: 已弃用，建议用 @ref{2e10,,headers}。

@end deffn

@geindex getstatus() (http.client.HTTPResponse 方法)
@anchor{library/http client http client HTTPResponse getstatus}@anchor{2e16}
@deffn {方法} HTTPResponse.getstatus ()


3.9 版后已移除: 已弃用，建议用 @ref{2e11,,status} 。

@end deffn

@node 示例<34>,HTTPMessage 对象,HTTPResponse 对象,http client --- HTTP 协议客户端
@anchor{library/http client examples}@anchor{2e17}
@subsubsection 示例


下面是使用 @code{GET} 方法的会话示例：

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read()  # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while chunk := r1.read(200):
...     print(repr(chunk))
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn = http.client.HTTPSConnection("docs.python.org")
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
@end example

以下是使用 @code{HEAD} 方法的会话示例。 请注意，@code{HEAD} 方法从不返回任何数据。

@example
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("HEAD", "/")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b'@w{'}
True
@end example

下面是用 @code{POST} 发送请求的会话示例：

@example
>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode(@{'@@number': 12524, '@@type': 'issue', '@@action': 'show'@})
>>> headers = @{"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"@}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
>>> data = response.read()
>>> data
b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()
@end example

在客户端， @code{HTTP PUT} 请求与 @code{POST} 请求非常相似。区别只在于服务器端，HTTP 服务器将允许通过 @code{PUT} 请求创建资源。应该注意的是，自定义的 HTTP 方法也可以在 @ref{9e5,,urllib.request.Request} 中通过设置适当的方法属性来进行处理。下面是一个会话示例，演示了如何利用 http.client 发送 @code{PUT} 请求。

@example
>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK
@end example

@node HTTPMessage 对象,,示例<34>,http client --- HTTP 协议客户端
@anchor{library/http client httpmessage-objects}@anchor{2e18}@anchor{library/http client id3}@anchor{2e19}
@subsubsection HTTPMessage 对象


@code{http.client.HTTPMessage} 的实例存有 HTTP 响应的头部信息。利用 @ref{644,,email.message.Message} 类实现。

@c XXX Define the methods that clients can depend upon between versions.

@node ftplib --- FTP 协议客户端,poplib --- POP3 协议客户端,http client --- HTTP 协议客户端,互联网协议和支持
@anchor{library/ftplib doc}@anchor{2e1a}@anchor{library/ftplib ftplib-ftp-protocol-client}@anchor{2e1b}@anchor{library/ftplib module-ftplib}@anchor{82}
@subsection @code{ftplib} --- FTP 协议客户端


@geindex ftplib (模块)

@strong{源代码：} Lib/ftplib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/ftplib.py}

@geindex FTP; protocol
@geindex FTP; ftplib (standard module)


__________________________________________________________________


本模块定义了 @ref{1a6,,FTP} 类和一些相关项目。@ref{1a6,,FTP} 类实现了 FTP 协议的客户端。可以用该类编写 Python 程序，执行各种自动化的 FTP 任务，如镜像其他 FTP 服务器。@ref{129,,urllib.request} 模块也用它来处理使用了 FTP 的 URL。关于 FTP（文件传输协议）的详情请参阅 Internet 
@geindex RFC; RFC 959
RFC 959@footnote{https://tools.ietf.org/html/rfc959.html}。

默认编码为 UTF-8，遵循 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://tools.ietf.org/html/rfc2640.html}。

以下是使用 @ref{82,,ftplib} 模块的会话示例:

@example
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org')  # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd anonymous@@
'230 Login successful.'
>>> ftp.cwd('debian')               # change into "debian" directory
'250 Directory successfully changed.'
>>> ftp.retrlines('LIST')           # list directory contents
-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
...
drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>>     ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
@end example

这个模块定义了以下内容：

@geindex FTP (ftplib 中的类)
@anchor{library/ftplib ftplib FTP}@anchor{1a6}
@deffn {类} ftplib.FTP (host='@w{'}, user='@w{'}, passwd='@w{'}, acct='@w{'}, timeout=None, source_address=None, *, encoding='utf-8')

返回一个 @ref{1a6,,FTP} 类的新实例。当传入 @emph{host} 时，将调用 @code{connect(host)} 方法。当传入 @emph{user} 时，将额外调用 @code{login(user, passwd, acct)} 方法（其中 @emph{passwd} 和 @emph{acct} 若没有传入则默认为空字符串）。可选参数 @emph{timeout} 指定阻塞操作（如连接尝试）的超时（以秒为单位，如果未指定超时，将使用全局默认超时设置）。@emph{source_address} 是一个 2 元组 @code{(host, port)}，套接字在连接前绑定它，作为其源地址。@emph{encoding} 参数指定目录和文件名的编码。

@ref{1a6,,FTP} 类支持 @ref{7e4,,with} 语句，例如：

@example
>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
...     ftp.login()
...     ftp.dir()
... 
'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
>>>
@end example


在 3.2 版更改: 支持了 @ref{7e4,,with} 语句。



在 3.3 版更改: 添加了 @emph{source_address} 参数。



在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。添加了 @emph{encoding} 参数，且为了遵循 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://tools.ietf.org/html/rfc2640.html}，该参数默认值从 Latin-1 改为了 UTF-8。

@end deffn

@geindex FTP_TLS (ftplib 中的类)
@anchor{library/ftplib ftplib FTP_TLS}@anchor{1a7}
@deffn {类} ftplib.FTP_TLS (host='@w{'}, user='@w{'}, passwd='@w{'}, acct='@w{'}, keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8')

一个 @ref{1a6,,FTP} 的子类，它为 FTP 添加了 TLS 支持，如 
@geindex RFC; RFC 4217
RFC 4217@footnote{https://tools.ietf.org/html/rfc4217.html} 所述。它将像通常一样连接到 21 端口，暗中保护在身份验证前的 FTP 控制连接。而保护数据连接需要用户明确调用 @ref{2e1c,,prot_p()} 方法。@emph{context} 是一个 @ref{4f2,,ssl.SSLContext} 对象，该对象可以将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构中。请阅读 @ref{2711,,安全考量} 以获取最佳实践。

@emph{keyfile} 和 @emph{certfile} 是可以代替 @emph{context} 的传统方案，它们可以分别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。


3.2 新版功能.



在 3.3 版更改: 添加了 @emph{source_address} 参数。



在 3.4 版更改: 本类现在支持通过 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称提示} （参阅 @ref{2839,,ssl.HAS_SNI}）进行主机名检查。



3.6 版后已移除: @emph{keyfile} 和 @emph{certfile} 已弃用并转而推荐 @emph{context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。



在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。添加了 @emph{encoding} 参数，且为了遵循 
@geindex RFC; RFC 2640
RFC 2640@footnote{https://tools.ietf.org/html/rfc2640.html}，该参数默认值从 Latin-1 改为了 UTF-8。


以下是使用 @ref{1a7,,FTP_TLS} 类的会话示例:

@example
>>> ftps = FTP_TLS('ftp.pureftpd.org')
>>> ftps.login()
'230 Anonymous user logged in'
>>> ftps.prot_p()
'200 Data protection level set to "private"'
>>> ftps.nlst()
['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']
@end example
@end deffn

@geindex error_reply
@anchor{library/ftplib ftplib error_reply}@anchor{2e1d}
@deffn {例外} ftplib.error_reply

从服务器收到意外答复时，将引发本异常。
@end deffn

@geindex error_temp
@anchor{library/ftplib ftplib error_temp}@anchor{2e1e}
@deffn {例外} ftplib.error_temp

收到表示临时错误的错误代码（响应代码在 400--499 范围内）时，将引发本异常。
@end deffn

@geindex error_perm
@anchor{library/ftplib ftplib error_perm}@anchor{2e1f}
@deffn {例外} ftplib.error_perm

收到表示永久性错误的错误代码（响应代码在 500--599 范围内）时，将引发本异常。
@end deffn

@geindex error_proto
@anchor{library/ftplib ftplib error_proto}@anchor{2e20}
@deffn {例外} ftplib.error_proto

从服务器收到不符合 FTP 响应规范的答复，比如以数字 1--5 开头时，将引发本异常。
@end deffn

@geindex all_errors() (在 ftplib 模块中)
@anchor{library/ftplib ftplib all_errors}@anchor{2e21}
@deffn {数据} ftplib.all_errors

所有异常的集合（一个元组），由于 FTP 连接出现问题（并非调用者的编码错误），@ref{1a6,,FTP} 实例的方法可能会引发这些异常。该集合包括上面列出的四个异常以及 @ref{30b,,OSError} 和 @ref{d3c,,EOFError}。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{be,,netrc} 模块

@code{.netrc} 文件格式解析器。FTP 客户端在响应用户之前，通常使用 @code{.netrc} 文件来加载用户认证信息。
@end table


@menu
* FTP 对象:: 
* FTP_TLS 对象:: 

@end menu

@node FTP 对象,FTP_TLS 对象,,ftplib --- FTP 协议客户端
@anchor{library/ftplib ftp-objects}@anchor{2e22}@anchor{library/ftplib id1}@anchor{2e23}
@subsubsection FTP 对象


一些方法可以按照两种方式来使用：一种处理文本文件，另一种处理二进制文件。方法名称与相应的命令相同，文本版中命令后面跟着 @code{lines}，二进制版中命令后面跟着 @code{binary}。

@ref{1a6,,FTP} 实例具有下列方法:

@geindex set_debuglevel() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP set_debuglevel}@anchor{2e24}
@deffn {方法} FTP.set_debuglevel (level)

设置实例的调试级别，它控制着调试信息的数量。默认值 @code{0} 不产生调试信息。值 @code{1} 产生中等数量的调试信息，通常每个请求产生一行。大于或等于 @code{2} 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被记录下来。
@end deffn

@geindex connect() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP connect}@anchor{2e25}
@deffn {方法} FTP.connect (host='@w{'}, port=0, timeout=None, source_address=None)

连接到给定的主机和端口。默认端口号由 FTP 协议规范规定，为 @code{21}。偶尔才需要指定其他端口号。每个实例只应调用一次本函数，如果在创建实例时就传入了 host，则根本不应调用它。所有其他方法只能在建立连接后使用。可选参数 @emph{timeout} 指定连接尝试的超时（以秒为单位）。如果没有传入 @emph{timeout}，将使用全局默认超时设置。@emph{source_address} 是一个 2 元组 @code{(host, port)}，套接字在连接前绑定它，作为其源地址。

引发一个 @ref{fec,,审计事件} @code{ftplib.connect}，附带参数 @code{self}, @code{host}, @code{port}。


在 3.3 版更改: 添加了 @emph{source_address} 参数。

@end deffn

@geindex getwelcome() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP getwelcome}@anchor{2e26}
@deffn {方法} FTP.getwelcome ()

返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用户有关的免责声明或帮助信息。）
@end deffn

@geindex login() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP login}@anchor{2e27}
@deffn {方法} FTP.login (user='anonymous', passwd='@w{'}, acct='@w{'})

以 @emph{user} 的身份登录。@emph{passwd} 和 @emph{acct} 是可选参数，默认为空字符串。如果没有指定 @emph{user}，则默认为 @code{'anonymous'}。如果 @emph{user} 为 @code{'anonymous'}，那么默认的 @emph{passwd} 是 @code{'anonymous@@'}。连接建立后，每个实例只应调用一次本函数；如果在创建实例时传入了 host 和 user，则完全不应该调用本函数。在客户端登录后，才允许执行大多数 FTP 命令。@emph{acct} 参数提供记账信息 ("accounting information")；仅少数系统实现了该特性。
@end deffn

@geindex abort() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP abort}@anchor{2e28}
@deffn {方法} FTP.abort ()

中止正在进行的文件传输。本方法并不总是有效，但值得一试。
@end deffn

@geindex sendcmd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP sendcmd}@anchor{2e29}
@deffn {方法} FTP.sendcmd (cmd)

将一条简单的命令字符串发送到服务器，返回响应的字符串。

引发一个 @ref{fec,,审计事件} @code{ftplib.sendcmd}，附带参数 @code{self}, @code{cmd}。
@end deffn

@geindex voidcmd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP voidcmd}@anchor{2e2a}
@deffn {方法} FTP.voidcmd (cmd)

将一条简单的命令字符串发送到服务器，并处理响应内容。如果收到的响应代码表示的是成功（代码范围 200--299），则不返回任何内容。否则将引发 @ref{2e1d,,error_reply}。

引发一个 @ref{fec,,审计事件} @code{ftplib.sendcmd}，附带参数 @code{self}, @code{cmd}。
@end deffn

@geindex retrbinary() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP retrbinary}@anchor{2e2b}
@deffn {方法} FTP.retrbinary (cmd, callback, blocksize=8192, rest=None)

以二进制传输模式下载文件。@emph{cmd} 应为恰当的 @code{RETR} 命令：@code{'RETR 文件名'}。@emph{callback} 函数会在收到每个数据块时调用，传入的参数是表示数据块的一个字节。为执行实际传输，创建了底层套接字对象，可选参数 @emph{blocksize} 指定了读取该对象时的最大块大小（这也是传入 @emph{callback} 的数据块的最大大小）。已经选择了合理的默认值。@emph{rest} 的含义与 @ref{2e2c,,transfercmd()} 方法中的含义相同。
@end deffn

@geindex retrlines() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP retrlines}@anchor{2e2d}
@deffn {方法} FTP.retrlines (cmd, callback=None)

按照初始化时的 @emph{encoding} 参数指定的编码，获取文件或目录列表。@emph{cmd} 应是恰当的 @code{RETR} 命令（参阅 @ref{2e2b,,retrbinary()}），也可以是诸如 @code{LIST} 或 @code{NLST} 之类的命令（通常就只是字符串 @code{'LIST'}）。@code{LIST} 获取文件列表以及那些文件的信息。@code{NLST} 获取文件名称列表。@emph{callback} 函数会在每一行都调用，参数就是包含一行的字符串，删除了尾部的 CRLF。默认的 @emph{callback} 会把行打印到 @code{sys.stdout}。
@end deffn

@geindex set_pasv() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP set_pasv}@anchor{2e2e}
@deffn {方法} FTP.set_pasv (val)

如果 @emph{val} 为 true，则打开“被动”模式，否则禁用被动模式。默认下被动模式是打开的。
@end deffn

@geindex storbinary() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP storbinary}@anchor{d6f}
@deffn {方法} FTP.storbinary (cmd, fp, blocksize=8192, callback=None, rest=None)

以二进制传输模式存储文件。 @emph{cmd} 应为恰当的 @code{STOR} 命令: @code{"STOR filename"}。@emph{fp} 是一个 @ref{c1d,,文件对象} (以二进制模式打开)，将使用它的 @code{read()} 方法读取它，用于提供要存储的数据，直到遇到 EOF，读取时的块大小为 @emph{blocksize}。 参数 @emph{blocksize} 的默认值为 8192。 可选参数 @emph{callback} 是单参数函数，在每个数据块发送后都会以该数据块作为参数来调用它。@emph{rest} 的含义与 @ref{2e2c,,transfercmd()} 方法中的含义相同。


在 3.2 版更改: 添加了 @emph{rest} 参数。

@end deffn

@geindex storlines() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP storlines}@anchor{2e2f}
@deffn {方法} FTP.storlines (cmd, fp, callback=None)

以文本行模式存储文件。@emph{cmd} 应为恰当的 @code{STOR} 命令 (请参阅 @ref{d6f,,storbinary()})。 @emph{fp} 是一个 @ref{c1d,,文件对象} (以二进制模式打开)，将使用它的 @ref{1883,,readline()} 方法读取它的每一行，用于提供要存储的数据，直到遇到 EOF。 可选参数 @emph{callback} 是单参数函数，在每行发送后都会以该行作为参数来调用它。
@end deffn

@geindex transfercmd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP transfercmd}@anchor{2e2c}
@deffn {方法} FTP.transfercmd (cmd, rest=None)

在 FTP 数据连接上开始传输数据。如果传输处于活动状态，传输命令由 @emph{cmd} 指定，需发送 @code{EPRT} 或 @code{PORT} 命令，然后接受连接 (accept)。如果服务器是被动服务器，需发送 @code{EPSV} 或 @code{PASV} 命令，连接到服务器 (connect)，然后启动传输命令。两种方式都将返回用于连接的套接字。

如果传入了可选参数 @emph{rest}，则一条 @code{REST} 命令会被发送到服务器，并以 @emph{rest} 作为参数。@emph{rest} 通常表示请求文件中的字节偏移量，它告诉服务器重新开始发送文件的字节，从请求的偏移量处开始，跳过起始字节。但是请注意，@ref{2e2c,,transfercmd()} 方法会将 @emph{rest} 转换为字符串，但是不检查字符串的内容，转换用的编码是在初始化时指定的 @emph{encoding} 参数。如果服务器无法识别 @code{REST} 命令，将引发 @ref{2e1d,,error_reply} 异常。如果发生这种情况，只需不带 @emph{rest} 参数调用 @ref{2e2c,,transfercmd()}。
@end deffn

@geindex ntransfercmd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP ntransfercmd}@anchor{2e30}
@deffn {方法} FTP.ntransfercmd (cmd, rest=None)

类似于 @ref{2e2c,,transfercmd()}，但返回一个元组，包括数据连接和数据的预计大小。如果预计大小无法计算，则返回的预计大小为 @code{None}。@emph{cmd} 和 @emph{rest} 的含义与 @ref{2e2c,,transfercmd()} 中的相同。
@end deffn

@geindex mlsd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP mlsd}@anchor{aec}
@deffn {方法} FTP.mlsd (path="", facts=[])

使用 @code{MLSD} 命令以标准格式列出目录内容 (
@geindex RFC; RFC 3659
RFC 3659@footnote{https://tools.ietf.org/html/rfc3659.html})。如果省略 @emph{path} 则使用当前目录。@emph{facts} 是字符串列表，表示所需的信息类型（如 @code{["type", "size", "perm"]}）。返回一个生成器对象，每个在 path 中找到的文件都将在该对象中生成两个元素的元组。第一个元素是文件名，第二个元素是该文件的 facts 的字典。该字典的内容受 @emph{facts} 参数限制，但不能保证服务器会返回所有请求的 facts。


3.3 新版功能.

@end deffn

@geindex nlst() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP nlst}@anchor{aed}
@deffn {方法} FTP.nlst (argument[, ...])

返回一个文件名列表，文件名由 @code{NLST} 命令返回。可选参数 @emph{argument} 是待列出的目录（默认为当前服务器目录）。可以使用多个参数，将非标准选项传递给 @code{NLST} 命令。

@cartouche
@quotation 注解 
如果目标服务器支持相关命令，那么 @ref{aec,,mlsd()} 提供的 API 更好。
@end quotation
@end cartouche
@end deffn

@geindex dir() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP dir}@anchor{aee}
@deffn {方法} FTP.dir (argument[, ...])

生成目录列表，即 @code{LIST} 命令所返回的结果，并将其打印到标准输出。可选参数 @emph{argument} 是待列出的目录（默认为当前服务器目录）。可以使用多个参数，将非标准选项传递给 @code{LIST} 命令。如果最后一个参数是一个函数，它将被用作 @emph{callback} 函数，与 @ref{2e2d,,retrlines()} 中的相同，默认将打印到 @code{sys.stdout}。本方法返回 @code{None}。

@cartouche
@quotation 注解 
如果目标服务器支持相关命令，那么 @ref{aec,,mlsd()} 提供的 API 更好。
@end quotation
@end cartouche
@end deffn

@geindex rename() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP rename}@anchor{2e31}
@deffn {方法} FTP.rename (fromname, toname)

将服务器上的文件 @emph{fromname} 重命名为 @emph{toname}。
@end deffn

@geindex delete() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP delete}@anchor{2e32}
@deffn {方法} FTP.delete (filename)

将服务器上名为 @emph{filename} 的文件删除。如果删除成功，返回响应文本，如果删除失败，在权限错误时引发 @ref{2e1f,,error_perm}，在其他错误时引发 @ref{2e1d,,error_reply}。
@end deffn

@geindex cwd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP cwd}@anchor{2e33}
@deffn {方法} FTP.cwd (pathname)

设置服务器端的当前目录。
@end deffn

@geindex mkd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP mkd}@anchor{2e34}
@deffn {方法} FTP.mkd (pathname)

在服务器上创建一个新目录。
@end deffn

@geindex pwd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP pwd}@anchor{2e35}
@deffn {方法} FTP.pwd ()

返回服务器上当前目录的路径。
@end deffn

@geindex rmd() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP rmd}@anchor{2e36}
@deffn {方法} FTP.rmd (dirname)

将服务器上名为 @emph{dirname} 的目录删除。
@end deffn

@geindex size() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP size}@anchor{2e37}
@deffn {方法} FTP.size (filename)

请求服务器上名为 @emph{filename} 的文件大小。成功后以整数返回文件大小，未成功则返回 @code{None}。注意，@code{SIZE} 不是标准命令，但通常许多服务器的实现都支持该命令。
@end deffn

@geindex quit() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP quit}@anchor{2e38}
@deffn {方法} FTP.quit ()

向服务器发送 @code{QUIT} 命令并关闭连接。 这是关闭一个连接的“礼貌”方式，但是如果服务器对 @code{QUIT} 命令的响应带有错误消息则这会引发一个异常。 这意味着对 @ref{2e39,,close()} 方法的调用，它将使得 @ref{1a6,,FTP} 实例对后继调用无效（见下文）。
@end deffn

@geindex close() (ftplib.FTP 方法)
@anchor{library/ftplib ftplib FTP close}@anchor{2e39}
@deffn {方法} FTP.close ()

单方面关闭连接。 这不该被应用于已经关闭的连接，例如成功调用 @ref{2e38,,quit()} 之后的连接。 在此调用之后 @ref{1a6,,FTP} 实例不应被继续使用（在调用 @ref{2e39,,close()} 或 @ref{2e38,,quit()} 之后你不能通过再次发起调用 @ref{2e27,,login()} 方法重新打开连接）。
@end deffn

@node FTP_TLS 对象,,FTP 对象,ftplib --- FTP 协议客户端
@anchor{library/ftplib ftp-tls-objects}@anchor{2e3a}
@subsubsection FTP_TLS 对象


@ref{1a7,,FTP_TLS} 类继承自 @ref{1a6,,FTP}，它定义了下述其他对象：

@geindex ssl_version (ftplib.FTP_TLS 属性)
@anchor{library/ftplib ftplib FTP_TLS ssl_version}@anchor{2e3b}
@deffn {属性} FTP_TLS.ssl_version

欲采用的 SSL 版本（默认为 @ref{2829,,ssl.PROTOCOL_SSLv23}）。
@end deffn

@geindex auth() (ftplib.FTP_TLS 方法)
@anchor{library/ftplib ftplib FTP_TLS auth}@anchor{2e3c}
@deffn {方法} FTP_TLS.auth ()

通过使用 TLS 或 SSL 来设置一个安全控制连接，具体取决于 @ref{2e3b,,ssl_version} 属性是如何设置的。


在 3.4 版更改: 此方法现在支持使用 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称指示} (参见 @ref{2839,,ssl.HAS_SNI}) 进行主机名检查。

@end deffn

@geindex ccc() (ftplib.FTP_TLS 方法)
@anchor{library/ftplib ftplib FTP_TLS ccc}@anchor{aeb}
@deffn {方法} FTP_TLS.ccc ()

将控制通道回复为纯文本。 这适用于发挥知道如何使用非安全 FTP 处理 NAT 而无需打开固定端口的防火墙的优势。


3.3 新版功能.

@end deffn

@geindex prot_p() (ftplib.FTP_TLS 方法)
@anchor{library/ftplib ftplib FTP_TLS prot_p}@anchor{2e1c}
@deffn {方法} FTP_TLS.prot_p ()

设置加密数据连接。
@end deffn

@geindex prot_c() (ftplib.FTP_TLS 方法)
@anchor{library/ftplib ftplib FTP_TLS prot_c}@anchor{2e3d}
@deffn {方法} FTP_TLS.prot_c ()

设置明文数据连接。
@end deffn

@node poplib --- POP3 协议客户端,imaplib --- IMAP4 协议客户端,ftplib --- FTP 协议客户端,互联网协议和支持
@anchor{library/poplib doc}@anchor{2e3e}@anchor{library/poplib module-poplib}@anchor{d0}@anchor{library/poplib poplib-pop3-protocol-client}@anchor{2e3f}
@subsection @code{poplib} --- POP3 协议客户端


@geindex poplib (模块)

@c revised by ESR, January 2000

@strong{源代码：} Lib/poplib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/poplib.py}

@geindex POP3; protocol


__________________________________________________________________


本模块定义了一个 @ref{1d6,,POP3} 类，该类封装了到 POP3 服务器的连接过程，并实现了 
@geindex RFC; RFC 1939
RFC 1939@footnote{https://tools.ietf.org/html/rfc1939.html} 中定义的协议。@ref{1d6,,POP3} 类同时支持 
@geindex RFC; RFC 1939
RFC 1939@footnote{https://tools.ietf.org/html/rfc1939.html} 中最小的和可选的命令集。@ref{1d6,,POP3} 类还支持在 
@geindex RFC; RFC 2595
RFC 2595@footnote{https://tools.ietf.org/html/rfc2595.html} 中引入的 @code{STLS} 命令，用于在已建立的连接上启用加密通信。

本模块额外提供一个 @ref{1d7,,POP3_SSL} 类，在连接到 POP3 服务器时，该类为使用 SSL 作为底层协议层提供了支持。

注意，尽管 POP3 具有广泛的支持，但它已经过时。POP3 服务器的实现质量差异很大，而且大多很糟糕。如果邮件服务器支持 IMAP，则最好使用 @ref{1b0,,imaplib.IMAP4} 类，因为 IMAP 服务器一般实现得更好。

@ref{d0,,poplib} 模块提供了两个类：

@geindex POP3 (poplib 中的类)
@anchor{library/poplib poplib POP3}@anchor{1d6}
@deffn {类} poplib.POP3 (host, port=POP3_PORT[, timeout])

本类实现实际的 POP3 协议。实例初始化时，连接就会建立。如果省略 @emph{port}，则使用标准 POP3 端口（110）。可选参数 @emph{timeout} 指定连接尝试的超时时间（以秒为单位，如果未指定超时，将使用全局默认超时设置）。

引发一个 @ref{fec,,审计事件} @code{poplib.connect}，附带参数 @code{self}, @code{host}, @code{port}。

引发一个 @ref{fec,,审计事件} @code{poplib.putline}，附带参数 @code{self}, @code{line}。


在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。

@end deffn

@geindex POP3_SSL (poplib 中的类)
@anchor{library/poplib poplib POP3_SSL}@anchor{1d7}
@deffn {类} poplib.POP3_SSL (host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None)

一个 @ref{1d6,,POP3} 的子类，它使用经 SSL 加密的套接字连接到服务器。如果端口 @emph{port} 未指定，则使用 995，它是标准的 POP3-over-SSL 端口。@emph{timeout} 的作用与 @ref{1d6,,POP3} 构造函数中的相同。@emph{context} 是一个可选的 @ref{4f2,,ssl.SSLContext} 对象，该对象可以将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构中。请阅读 @ref{2711,,安全考量} 以获取最佳实践。

@emph{keyfile} 和 @emph{certfile} 是可以代替 @emph{context} 的传统方案，它们可以分别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。

引发一个 @ref{fec,,审计事件} @code{poplib.connect}，附带参数 @code{self}, @code{host}, @code{port}。

引发一个 @ref{fec,,审计事件} @code{poplib.putline}，附带参数 @code{self}, @code{line}。


在 3.2 版更改: 添加了 @emph{context} 参数。



在 3.4 版更改: 本类现在支持使用 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称指示} （参阅 @ref{2839,,ssl.HAS_SNI}）进行主机名检查。



3.6 版后已移除: @emph{keyfile} 和 @emph{certfile} 已弃用并转而推荐 @emph{context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。



在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。

@end deffn

定义了一个异常，它是作为 @ref{d0,,poplib} 模块的属性定义的：

@geindex error_proto
@anchor{library/poplib poplib error_proto}@anchor{bf3}
@deffn {例外} poplib.error_proto

此模块的所有错误都将引发本异常（来自 @ref{ef,,socket} 模块的错误不会被捕获）。异常的原因将以字符串的形式传递给构造函数。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{97,,imaplib} 模块

标准的 Python IMAP 模块。

@item 有关 Fetchmail 的常见问题@footnote{http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html}

@code{fetchmail} POP/IMAP 客户端的“常见问题”收集了 POP3 服务器之间的差异和 RFC 不兼容的信息，如果要编写基于 POP 协议的应用程序，这可能会很有用。
@end table


@menu
* POP3 对象:: 
* POP3 示例:: 

@end menu

@node POP3 对象,POP3 示例,,poplib --- POP3 协议客户端
@anchor{library/poplib id1}@anchor{2e40}@anchor{library/poplib pop3-objects}@anchor{2e41}
@subsubsection POP3 对象


所有 POP3 命令均以同名的方法表示，小写，大多数方法返回的是服务器发送的响应文本。

@ref{1d6,,POP3} 实例具有下列方法：

@geindex set_debuglevel() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 set_debuglevel}@anchor{2e42}
@deffn {方法} POP3.set_debuglevel (level)

设置实例的调试级别，它控制着调试信息的数量。默认值 @code{0} 不产生调试信息。值 @code{1} 产生中等数量的调试信息，通常每个请求产生一行。大于或等于 @code{2} 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被记录下来。
@end deffn

@geindex getwelcome() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 getwelcome}@anchor{2e43}
@deffn {方法} POP3.getwelcome ()

返回 POP3 服务器发送的问候语字符串。
@end deffn

@geindex capa() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 capa}@anchor{982}
@deffn {方法} POP3.capa ()

查询服务器支持的功能，这些功能在 
@geindex RFC; RFC 2449
RFC 2449@footnote{https://tools.ietf.org/html/rfc2449.html} 中有说明。返回一个 @code{@{'name': ['param'...]@}} 形式的字典。


3.4 新版功能.

@end deffn

@geindex user() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 user}@anchor{2e44}
@deffn {方法} POP3.user (username)

发送 user 命令，返回的响应应该指示需要一个密码。
@end deffn

@geindex pass_() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 pass_}@anchor{2e45}
@deffn {方法} POP3.pass_ (password)

发送密码，响应包括邮件数和邮箱大小。注意：在调用 @code{quit()} 前，服务器上的邮箱都是锁定的。
@end deffn

@geindex apop() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 apop}@anchor{2e46}
@deffn {方法} POP3.apop (user, secret)

使用更安全的 APOP 身份验证登录到 POP3 服务器。
@end deffn

@geindex rpop() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 rpop}@anchor{2e47}
@deffn {方法} POP3.rpop (user)

使用 RPOP 身份验证（类似于 Unix r-命令）登录到 POP3 服务器。
@end deffn

@geindex stat() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 stat}@anchor{2e48}
@deffn {方法} POP3.stat ()

获取邮箱状态。结果为 2 个整数组成的元组：@code{(message count, mailbox size)}。
@end deffn

@geindex list() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 list}@anchor{2e49}
@deffn {方法} POP3.list ([which])

请求消息列表，结果的形式为 @code{(response, ['mesg_num octets', ...], octets)}。如果设置了 @emph{which}，它表示需要列出的消息。
@end deffn

@geindex retr() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 retr}@anchor{2e4a}
@deffn {方法} POP3.retr (which)

检索编号为 @emph{which} 的整条消息，并设置其已读标志位。结果的形式为 @code{(response, ['line', ...], octets)}。
@end deffn

@geindex dele() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 dele}@anchor{2e4b}
@deffn {方法} POP3.dele (which)

将编号为 @emph{which} 的消息标记为待删除。在多数服务器上，删除操作直到 QUIT 才会实际执行（主要例外是 Eudora QPOP，它在断开连接时执行删除，故意违反了 RFC）。
@end deffn

@geindex rset() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 rset}@anchor{2e4c}
@deffn {方法} POP3.rset ()

移除邮箱中的所有待删除标记。
@end deffn

@geindex noop() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 noop}@anchor{2e4d}
@deffn {方法} POP3.noop ()

什么都不做。可以用于保持活动状态。
@end deffn

@geindex quit() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 quit}@anchor{bf2}
@deffn {方法} POP3.quit ()

登出：提交更改，解除邮箱锁定，断开连接。
@end deffn

@geindex top() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 top}@anchor{2e4e}
@deffn {方法} POP3.top (which, howmuch)

检索编号为 @emph{which} 的消息，范围是消息头加上消息头往后数 @emph{howmuch} 行。结果的形式为 @code{(response, ['line', ...], octets)}。

本方法使用 POP3 TOP 命令，不同于 RETR 命令，它不设置邮件的已读标志位。不幸的是，TOP 在 RFC 中说明不清晰，且在小众的服务器软件中往往不可用。信任并使用它之前，请先手动对目标 POP3 服务器测试本方法。
@end deffn

@geindex uidl() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 uidl}@anchor{2e4f}
@deffn {方法} POP3.uidl (which=None)

返回消息摘要（唯一 ID）列表。如果指定了 @emph{which}，那么结果将包含那条消息的唯一 ID，形式为 @code{'response mesgnum uid}，如果未指定，那么结果为列表 @code{(response, ['mesgnum uid', ...], octets)}。
@end deffn

@geindex utf8() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 utf8}@anchor{82b}
@deffn {方法} POP3.utf8 ()

尝试切换至 UTF-8 模式。成功则返回服务器的响应，失败则引发 @ref{bf3,,error_proto} 异常。在 
@geindex RFC; RFC 6856
RFC 6856@footnote{https://tools.ietf.org/html/rfc6856.html} 中有说明。


3.5 新版功能.

@end deffn

@geindex stls() (poplib.POP3 方法)
@anchor{library/poplib poplib POP3 stls}@anchor{983}
@deffn {方法} POP3.stls (context=None)

在活动连接上开启 TLS 会话，在 
@geindex RFC; RFC 2595
RFC 2595@footnote{https://tools.ietf.org/html/rfc2595.html} 中有说明。仅在用户身份验证前允许这样做。

@emph{context} 参数是一个 @ref{4f2,,ssl.SSLContext} 对象，该对象可以将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构中。请阅读 @ref{2711,,安全考量} 以获取最佳实践。

此方法支持通过 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称指示} (参见 @ref{2839,,ssl.HAS_SNI}) 进行主机名检查。


3.4 新版功能.

@end deffn

@ref{1d7,,POP3_SSL} 实例没有额外方法。该子类的接口与其父类的相同。

@node POP3 示例,,POP3 对象,poplib --- POP3 协议客户端
@anchor{library/poplib id2}@anchor{2e50}@anchor{library/poplib pop3-example}@anchor{2e51}
@subsubsection POP3 示例


以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息:

@example
import getpass, poplib

M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print(j)
@end example

模块的最后有一段测试，其中包含的用法示例更加广泛。

@node imaplib --- IMAP4 协议客户端,smtplib ---SMTP协议客户端,poplib --- POP3 协议客户端,互联网协议和支持
@anchor{library/imaplib doc}@anchor{2e52}@anchor{library/imaplib imaplib-imap4-protocol-client}@anchor{2e53}@anchor{library/imaplib module-imaplib}@anchor{97}
@subsection @code{imaplib} --- IMAP4 协议客户端


@geindex imaplib (模块)

@c revised by ESR, January 2000

@c changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002

@c changes for IMAP4_stream by Piers Lauder <piers@communitysolutions.com.au>,
@c November 2002

@strong{源代码：} Lib/imaplib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/imaplib.py}

@geindex IMAP4; protocol
@geindex IMAP4_SSL; protocol
@geindex IMAP4_stream; protocol


__________________________________________________________________


本模块定义了三个类： @ref{1b0,,IMAP4} 、 @ref{1b1,,IMAP4_SSL} 和 @ref{1b3,,IMAP4_stream} 。这三个类封装了与IMAP4服务器的连接并实现了 
@geindex RFC; RFC 2060
RFC 2060@footnote{https://tools.ietf.org/html/rfc2060.html} 当中定义的大多数IMAP4rev1客户端协议。其与IMAP4（ 
@geindex RFC; RFC 1730
RFC 1730@footnote{https://tools.ietf.org/html/rfc1730.html} ）服务器后向兼容，但是 @code{STATUS}  指令在IMAP4中不支持。

@ref{97,,imaplib} 模块提供了三个类，其中 @ref{1b0,,IMAP4} 是基类：

@geindex IMAP4 (imaplib 中的类)
@anchor{library/imaplib imaplib IMAP4}@anchor{1b0}
@deffn {类} imaplib.IMAP4 (host='@w{'}, port=IMAP4_PORT, timeout=None)

这个类实现了实际的 IMAP4 协议。 当其实例被实例化时会创建连接并确定协议版本 (IMAP4 或 IMAP4rev1)。 如果未指明 @emph{host}，则会使用 @code{'@w{'}} (本地主机)。 如果省略 @emph{port}，则会使用标准 IMAP4 端口 (143)。 可选的 @emph{timeout} 形参指定连接尝试的超时秒数。 如果未指定超时或为 None，则会使用全局默认的套接字超时。

@ref{1b0,,IMAP4} 类支持 @ref{7e4,,with} 语句。 当这样使用时，IMAP4 @code{LOGOUT} 命令会在 @code{with} 语句退出时自动发出。 例如:

@example
>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
...     M.noop()
...
('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])
@end example


在 3.5 版更改: 支持了 @ref{7e4,,with} 语句。



在 3.9 版更改: 添加了可选的 @emph{timeout} 形参。

@end deffn

有三个异常被定义为 @ref{1b0,,IMAP4} 类的属性:

@geindex IMAP4.error
@anchor{library/imaplib imaplib IMAP4 error}@anchor{2e54}
@deffn {例外} IMAP4.error

任何错误都将引发该异常。 异常的原因会以字符串的形式传递给构造器。
@end deffn

@geindex IMAP4.abort
@anchor{library/imaplib imaplib IMAP4 abort}@anchor{2e55}
@deffn {例外} IMAP4.abort

IMAP4 服务器错误会导致引发该异常。 这是 @ref{2e54,,IMAP4.error} 的子类。 请注意关闭此实例并实例化一个新实例通常将会允许从该异常中恢复。
@end deffn

@geindex IMAP4.readonly
@anchor{library/imaplib imaplib IMAP4 readonly}@anchor{2e56}
@deffn {例外} IMAP4.readonly

当一个可写邮箱的状态被服务器修改时会引发此异常。  此异常是 @ref{2e54,,IMAP4.error} 的子类。 某个其他客户端现在会具有写入权限，将需要重新打开该邮箱以重新获得写入权限。
@end deffn

另外还有一个针对安全连接的子类:

@geindex IMAP4_SSL (imaplib 中的类)
@anchor{library/imaplib imaplib IMAP4_SSL}@anchor{1b1}
@deffn {类} imaplib.IMAP4_SSL (host='@w{'}, port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None, timeout=None)

这是一个派生自 @ref{1b0,,IMAP4} 的子类，它使用经 SSL 加密的套接字进行连接 (为了使用这个类你需要编译时附带 SSL 支持的 socket 模块)。 如果未指定 @emph{host}，则会使用 @code{'@w{'}} (本地主机)。 如果省略了 @emph{port}，则会使用标准的 IMAP4-over-SSL 端口 (993)。 @emph{ssl_context} 是一个 @ref{4f2,,ssl.SSLContext} 对象，它允许将 SSL 配置选项、证书和私钥打包放入一个单独的 (可以长久存在的) 结构体中。 请阅读 @ref{2711,,安全考量} 以获取最佳实践。

@emph{keyfile} 和 @emph{certfile} 是 @emph{ssl_context} 的旧式替代品 —— 它们可以指向 PEM 格式的私钥和证书链文件用于 SSL 连接。 请注意 @emph{keyfile}/@emph{certfile} 形参不能与 @emph{ssl_context} 共存，如果 @emph{keyfile}/@emph{certfile} 与 @emph{ssl_context} 一同被提供则会引发 @ref{16d,,ValueError}。

可选的 @emph{timeout} 形参指明连接尝试的超时秒数。 如果参数未给出或为 None，则会使用全局默认的套接字超时设置。


在 3.3 版更改: 增加了 @emph{ssl_context} 形参。



在 3.4 版更改: 本类现在支持通过 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称提示} （参阅 @ref{2839,,ssl.HAS_SNI}）进行主机名检查。



3.6 版后已移除: @emph{keyfile} 和 @emph{certfile} 已弃用并转而推荐 @emph{ssl_context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()}，或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。



在 3.9 版更改: 添加了可选的 @emph{timeout} 形参。

@end deffn

第二个子类允许由子进程所创建的连接:

@geindex IMAP4_stream (imaplib 中的类)
@anchor{library/imaplib imaplib IMAP4_stream}@anchor{1b3}
@deffn {类} imaplib.IMAP4_stream (command)

这是一个派生自 @ref{1b0,,IMAP4} 的子类，它可以连接 @code{stdin/stdout} 文件描述符，此种文件是通过向 @code{subprocess.Popen()} 传入 @emph{command} 来创建的。
@end deffn

定义了下列工具函数:

@geindex Internaldate2tuple() (在 imaplib 模块中)
@anchor{library/imaplib imaplib Internaldate2tuple}@anchor{2e57}
@deffn {函数} imaplib.Internaldate2tuple (datestr)

解析一个 IMAP4 @code{INTERNALDATE} 字符串并返回对应的本地时间。 返回值是一个 @ref{69a,,time.struct_time} 元组或者如果字符串格式错误则为 @code{None}。
@end deffn

@geindex Int2AP() (在 imaplib 模块中)
@anchor{library/imaplib imaplib Int2AP}@anchor{2e58}
@deffn {函数} imaplib.Int2AP (num)

将一个整数转换为使用字符集 [@code{A} .. @code{P}] 的字节串表示形式。
@end deffn

@geindex ParseFlags() (在 imaplib 模块中)
@anchor{library/imaplib imaplib ParseFlags}@anchor{2e59}
@deffn {函数} imaplib.ParseFlags (flagstr)

将一个 IMAP4 @code{FLAGS} 响应转换为包含单独旗标的元组。
@end deffn

@geindex Time2Internaldate() (在 imaplib 模块中)
@anchor{library/imaplib imaplib Time2Internaldate}@anchor{2e5a}
@deffn {函数} imaplib.Time2Internaldate (date_time)

将 @emph{date_time} 转换为 IMAP4 @code{INTERNALDATE} 表示形式。 返回值是以下形式的字符串: @code{"DD-Mmm-YYYY HH:MM:SS +HHMM"} (包括双引号)。 @emph{date_time} 参数可以是一个代表距离纪元起始的秒数 (如 @ref{436,,time.time()} 的返回值) 的数字 (整数或浮点数)，一个代表本地时间的 9 元组，一个 @ref{69a,,time.struct_time} 实例 (如 @ref{10c9,,time.localtime()} 的返回值)，一个感知型的 @ref{19f,,datetime.datetime} 实例，或一个双引号字符串。 在最后一种情况下，它会被假定已经具有正确的格式。
@end deffn

请注意 IMAP4 消息编号会随邮箱的改变而改变；特别是在使用 @code{EXPUNGE} 命令执行删除后剩余的消息会被重新编号。 因此高度建议通过 UID 命令来改用 UID。

模块的最后有一段测试，其中包含的用法示例更加广泛。


@subsubheading 参见


描述该协议的文档，实现该协议的服务器源代码，由华盛顿大学 IMAP 信息中心提供 (@strong{源代码}) @indicateurl{https://github.com/uw-imap/imap} (@strong{不再维护})。


@menu
* IMAP4 对象:: 
* IMAP4 示例:: 

@end menu

@node IMAP4 对象,IMAP4 示例,,imaplib --- IMAP4 协议客户端
@anchor{library/imaplib id1}@anchor{2e5b}@anchor{library/imaplib imap4-objects}@anchor{2e5c}
@subsubsection IMAP4 对象


所有 IMAP4rev1 命令都表示为同名的方法，可以为大写或小写形式。

命令的所有参数都会被转换为字符串，只有 @code{AUTHENTICATE} 例外，而, and the last argument to @code{APPEND} 的最后一个参数会被作为 IMAP4 字面值传入。 如有必要 (字符串包含 IMAP4 协议中的敏感字符并且未加圆括号或双引号) 每个字符串都会被转码。 但是，@code{LOGIN} 命令的 @emph{password} 参数总是会被转码。 如果你想让某个参数字符串免于被转码 (例如: @code{STORE} 的 @emph{flags} 参数) 则要为该字符串加上圆括号 (例如: @code{r'(\Deleted)'})。

每条命令均返回一个元组: @code{(type, [data, ...])} 其中 @emph{type} 通常为 @code{'OK'} 或 @code{'NO'}，而 @emph{data} 为来自命令响应的文本，或为来自命令的规定结果。 每个 @emph{data} 均为 @code{bytes} 或者元组。 如果为元组，则其第一部分是响应的标头，而第二部分将包含数据 (例如: 'literal' 值)。

以下命令的 @emph{message_set} 选项为指定要操作的一条或多条消息的字符串。 它可以是一个简单的消息编号 (@code{'1'})，一段消息编号区间 (@code{'2:4'})，或者一组以逗号分隔的非连续区间 (@code{'1:3,6:9'})。 区间可以包含一个星号来表示无限的上界 (@code{'3:*'})。

@ref{1b0,,IMAP4} 实例具有下列方法:

@geindex append() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 append}@anchor{2e5d}
@deffn {方法} IMAP4.append (mailbox, flags, date_time, message)

将 @emph{message} 添加到指定的邮箱。
@end deffn

@geindex authenticate() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 authenticate}@anchor{2e5e}
@deffn {方法} IMAP4.authenticate (mechanism, authobject)

认证命令 --- 要求对响应进行处理。

@emph{mechanism} 指明要使用哪种认证机制 —— 它应当在实例变量 @code{capabilities} 中以 @code{AUTH=mechanism} 的形式出现。

@emph{authobject} 必须是一个可调用对象:

@example
data = authobject(response)
@end example

它将被调用以便处理服务器连续响应；传给它的 @emph{response} 参数将为 @code{bytes} 类型。 它应当返回 base64 编码的 @code{bytes} @emph{数据} 并发送给服务器。 或者在客户端中止响应时返回 @code{None} 并应改为发送 @code{*}。


在 3.5 版更改: 字符串形式的用户名和密码现在会被执行 @code{utf-8} 编码而不限于 ASCII 字符。

@end deffn

@geindex check() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 check}@anchor{2e5f}
@deffn {方法} IMAP4.check ()

为服务器上的邮箱设置检查点。
@end deffn

@geindex close() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 close}@anchor{1b5}
@deffn {方法} IMAP4.close ()

关闭当前选定的邮箱。 已删除的消息会从可写邮箱中被移除。 在 @code{LOGOUT} 之前建议执行此命令。
@end deffn

@geindex copy() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 copy}@anchor{2e60}
@deffn {方法} IMAP4.copy (message_set, new_mailbox)

将 @emph{message_set} 消息拷贝到 @emph{new_mailbox} 的末尾。
@end deffn

@geindex create() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 create}@anchor{2e61}
@deffn {方法} IMAP4.create (mailbox)

新建名为 @emph{mailbox} 新邮箱。
@end deffn

@geindex delete() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 delete}@anchor{2e62}
@deffn {方法} IMAP4.delete (mailbox)

删除名为 @emph{mailbox} 的旧邮箱。
@end deffn

@geindex deleteacl() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 deleteacl}@anchor{2e63}
@deffn {方法} IMAP4.deleteacl (mailbox, who)

删除邮箱上某人的 ACL (移除任何权限)。
@end deffn

@geindex enable() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 enable}@anchor{7e5}
@deffn {方法} IMAP4.enable (capability)

启用 @emph{capability} (参见 
@geindex RFC; RFC 5161
RFC 5161@footnote{https://tools.ietf.org/html/rfc5161.html})。 大多数功能都不需要被启用。 目前只有 @code{UTF8=ACCEPT} 功能受到支持 (参见 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://tools.ietf.org/html/rfc6855.html})。


3.5 新版功能: @ref{7e5,,enable()} 方法本身，以及 
@geindex RFC; RFC 6855
RFC 6855@footnote{https://tools.ietf.org/html/rfc6855.html} 支持。

@end deffn

@geindex expunge() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 expunge}@anchor{2e64}
@deffn {方法} IMAP4.expunge ()

从选定的邮箱中永久移除被删除的条目。 为每条被删除的消息各生成一个 @code{EXPUNGE} 响应。 返回包含按接收时间排序的 @code{EXPUNGE} 消息编号的列表。
@end deffn

@geindex fetch() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 fetch}@anchor{2e65}
@deffn {方法} IMAP4.fetch (message_set, message_parts)

获取消息（的各个部分）。 @emph{message_parts} 应为加圆标号的消息部分名称字符串，例如: @code{"(UID BODY[TEXT])"}。 返回的数据是由消息部分封包和数据组成的元组。
@end deffn

@geindex getacl() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 getacl}@anchor{2e66}
@deffn {方法} IMAP4.getacl (mailbox)

获取 @emph{mailbox} 的 @code{ACL}。 此方法是非标准的，但是被 @code{Cyrus} 服务器所支持。
@end deffn

@geindex getannotation() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 getannotation}@anchor{2e67}
@deffn {方法} IMAP4.getannotation (mailbox, entry, attribute)

提取 @emph{mailbox} 的特定 @code{ANNOTATION}。 此方法是非标准的，但是被 @code{Cyrus} 服务器所支持。
@end deffn

@geindex getquota() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 getquota}@anchor{2e68}
@deffn {方法} IMAP4.getquota (root)

获取 @code{quota} @emph{root} 的资源使用和限制。 此方法是 rfc2087 定义的 IMAP4 QUOTA 扩展的组成部分。
@end deffn

@geindex getquotaroot() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 getquotaroot}@anchor{2e69}
@deffn {方法} IMAP4.getquotaroot (mailbox)

获取指定 @emph{mailbox} 的 @code{quota} @code{roots} 列表。 此方法是 rfc2087 定义的 IMAP4 QUOTA 扩展的组成部分。
@end deffn

@geindex list() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 list}@anchor{2e6a}
@deffn {方法} IMAP4.list ([directory[, pattern]])

列出 @emph{directory} 中与 @emph{pattern} 相匹配的邮箱名称。 @emph{directory} 默认为最高层级的电邮文件夹，而 @emph{pattern} 默认为匹配任何文本。 返回的数据包含 @code{LIST} 响应列表。
@end deffn

@geindex login() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 login}@anchor{2e6b}
@deffn {方法} IMAP4.login (user, password)

使用纯文本密码标识客户。 @emph{password} 将被转码。
@end deffn

@geindex login_cram_md5() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 login_cram_md5}@anchor{2e6c}
@deffn {方法} IMAP4.login_cram_md5 (user, password)

在标识用户以保护密码时强制使用 @code{CRAM-MD5} 认证。 将只在服务器 @code{CAPABILITY} 响应包含 @code{AUTH=CRAM-MD5} 阶段时才有效。
@end deffn

@geindex logout() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 logout}@anchor{2e6d}
@deffn {方法} IMAP4.logout ()

关闭对服务器的连接。 返回服务器 @code{BYE} 响应。


在 3.8 版更改: 此方法不会再忽略静默的任意异常。

@end deffn

@geindex lsub() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 lsub}@anchor{2e6e}
@deffn {方法} IMAP4.lsub (directory='""', pattern='*')

列出 directory 中抽取的与 pattern 相匹配的邮箱。 @emph{directory} 默认为最高层级目录而 @emph{pattern} 默认为匹配任何邮箱。 返回的数据为消息部分封包和数据的元组。
@end deffn

@geindex myrights() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 myrights}@anchor{2e6f}
@deffn {方法} IMAP4.myrights (mailbox)

显示某个邮箱的本人 ACL (即本人在邮箱中的权限)。
@end deffn

@geindex namespace() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 namespace}@anchor{2e70}
@deffn {方法} IMAP4.namespace ()

返回 
@geindex RFC; RFC 2342
RFC 2342@footnote{https://tools.ietf.org/html/rfc2342.html} 中定义的 IMAP 命名空间。
@end deffn

@geindex noop() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 noop}@anchor{2e71}
@deffn {方法} IMAP4.noop ()

将 @code{NOOP} 发送给服务器。
@end deffn

@geindex open() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 open}@anchor{1b2}
@deffn {方法} IMAP4.open (host, port, timeout=None)

打开连接 @emph{host} 上 @emph{port} 的套接字。 可选的 @emph{timeout} 形参指定连接尝试的超时秒数。 如果 timeout 未给出或为 None，则会使用全局默认的套接字超时。 另外请注意如果 @emph{timeout} 形参被设为零，它将引发 @ref{16d,,ValueError} 以拒绝创建非阻塞套接字。 此方法会由 @ref{1b0,,IMAP4} 构造器隐式地调用。 此方法所建立的连接对象将在 @ref{2e72,,IMAP4.read()}, @ref{2e73,,IMAP4.readline()}, @ref{2e74,,IMAP4.send()} 和 @ref{2e75,,IMAP4.shutdown()} 等方法中被使用。 你可以重载此方法。

引发一个 @ref{fec,,审计事件} @code{imaplib.open}，附带参数 @code{self}, @code{host}, @code{port}。


在 3.9 版更改: 加入 @emph{timeout} 参数。

@end deffn

@geindex partial() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 partial}@anchor{2e76}
@deffn {方法} IMAP4.partial (message_num, message_part, start, length)

获取消息被截断的部分。 返回的数据是由消息部分封包和数据组成的元组。
@end deffn

@geindex proxyauth() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 proxyauth}@anchor{2e77}
@deffn {方法} IMAP4.proxyauth (user)

作为 @emph{user} 进行认证。 允许经权限的管理员通过代理进入任意用户的邮箱。
@end deffn

@geindex read() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 read}@anchor{2e72}
@deffn {方法} IMAP4.read (size)

从远程服务器读取 @emph{size} 字节。 你可以重载此方法。
@end deffn

@geindex readline() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 readline}@anchor{2e73}
@deffn {方法} IMAP4.readline ()

从远程服务器读取一行。 你可以重载此方法。
@end deffn

@geindex recent() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 recent}@anchor{2e78}
@deffn {方法} IMAP4.recent ()

提示服务器进行更新。 如果没有新消息则返回的数据为 @code{None}，否则为 @code{RECENT} 响应的值。
@end deffn

@geindex rename() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 rename}@anchor{2e79}
@deffn {方法} IMAP4.rename (oldmailbox, newmailbox)

将名为 @emph{oldmailbox} 的邮箱重命名为 @emph{newmailbox}。
@end deffn

@geindex response() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 response}@anchor{2e7a}
@deffn {方法} IMAP4.response (code)

如果收到响应 @emph{code} 则返回其数据，否则返回 @code{None}。 返回给定的代码，而不是普通的类型。
@end deffn

@geindex search() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 search}@anchor{2e7b}
@deffn {方法} IMAP4.search (charset, criterion[, ...])

在邮箱中搜索匹配的消息。 @emph{charset} 可以为 @code{None}，在这种情况下在发给服务器的请求中将不指定 @code{CHARSET}。 IMAP 协议要求至少指定一个标准；当服务器返回错误时将会引发异常。 @emph{charset} 为 @code{None} 对应使用 @ref{7e5,,enable()} 命令启用了 @code{UTF8=ACCEPT} 功能的情况。

示例:

@example
# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')

# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')
@end example
@end deffn

@geindex select() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 select}@anchor{2e7c}
@deffn {方法} IMAP4.select (mailbox='INBOX', readonly=False)

选择一个邮箱。 返回的数据是 @emph{mailbox} 中消息的数量 (@code{EXISTS} 响应)。 默认的 @emph{mailbox} 为 @code{'INBOX'}。 如果设置了 @emph{readonly} 旗标，则不允许修改该邮箱。
@end deffn

@geindex send() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 send}@anchor{2e74}
@deffn {方法} IMAP4.send (data)

将 @code{data} 发送给远程服务器。 请可以重载此方法。

引发一个 @ref{fec,,审计事件} @code{imaplib.send}，附带参数 @code{self}, @code{data}。
@end deffn

@geindex setacl() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 setacl}@anchor{2e7d}
@deffn {方法} IMAP4.setacl (mailbox, who, what)

发送 @emph{mailbox} 的 @code{ACL}。 此方法是非标准的，但是被 @code{Cyrus} 服务器所支持。
@end deffn

@geindex setannotation() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 setannotation}@anchor{2e7e}
@deffn {方法} IMAP4.setannotation (mailbox, entry, attribute[, ...])

设置 @emph{mailbox} 的 @code{ANNOTATION}。 此方法是非标准的，但是被 @code{Cyrus} 服务器所支持。
@end deffn

@geindex setquota() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 setquota}@anchor{2e7f}
@deffn {方法} IMAP4.setquota (root, limits)

设置 @code{quota} @emph{root} 的资源限制为 @emph{limits}。 此方法是 rfc2087 定义的 IMAP4 QUOTA 扩展的组成部分。
@end deffn

@geindex shutdown() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 shutdown}@anchor{2e75}
@deffn {方法} IMAP4.shutdown ()

关闭在 @code{open} 中建立的连接。 此方法会由 @ref{2e6d,,IMAP4.logout()} 隐式地调用。 你可以重载此方法。
@end deffn

@geindex socket() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 socket}@anchor{2e80}
@deffn {方法} IMAP4.socket ()

返回用于连接服务器的套接字实例。
@end deffn

@geindex sort() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 sort}@anchor{2e81}
@deffn {方法} IMAP4.sort (sort_criteria, charset, search_criterion[, ...])

@code{sort} 命令是 @code{search} 的变化形式，带有结果排序语句。 返回的数据包含以空格分隔的匹配消息编号列表。

排序命令在 @emph{search_criterion} 参数之前还有两个参数；一个带圆括号的 @emph{sort_criteria} 列表，和搜索的 @emph{charset}。 请注意不同于 @code{search}，搜索的 @emph{charset} 参数是强制性的。 还有一个 @code{uid sort} 命令与 @code{sort} 对应，如同 @code{uid search} 与 @code{search} 对应一样。 @code{sort} 命令首先在邮箱中搜索匹配给定搜索条件的消息，使用 charset 参数来解读搜索条件中的字符串。 然后它将返回所匹配消息的编号。

这是一个 @code{IMAP4rev1} 扩展命令。
@end deffn

@geindex starttls() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 starttls}@anchor{c82}
@deffn {方法} IMAP4.starttls (ssl_context=None)

发送一个 @code{STARTTLS} 命令。 @emph{ssl_context} 参数是可选的并且应为一个 @ref{4f2,,ssl.SSLContext} 对象。 这将在 IMAP 连接上启用加密。 请阅读 @ref{2711,,安全考量} 来了解最佳实践。


3.2 新版功能.



在 3.4 版更改: 此方法现在支持使用 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称指示} (参见 @ref{2839,,ssl.HAS_SNI}) 进行主机名检查。

@end deffn

@geindex status() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 status}@anchor{2e82}
@deffn {方法} IMAP4.status (mailbox, names)

针对 @emph{mailbox} 请求指定的状态条件。
@end deffn

@geindex store() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 store}@anchor{2e83}
@deffn {方法} IMAP4.store (message_set, command, flag_list)

改变邮箱中消息的旗标处理。 @emph{command} 由 
@geindex RFC; RFC 2060
RFC 2060@footnote{https://tools.ietf.org/html/rfc2060.html} 的 6.4.6 小节指明，应为 "FLAGS", "+FLAGS" 或 "-FLAGS" 之一，并可选择附带 ".SILENT" 后缀。

例如，要在所有消息上设置删除旗标:

@example
typ, data = M.search(None, 'ALL')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
@end example

@cartouche
@quotation 注解 
创建包含 ']' 的旗标 (例如: "[test]") 会违反 
@geindex RFC; RFC 3501
RFC 3501@footnote{https://tools.ietf.org/html/rfc3501.html} (IMAP 协议)。 但是，imaplib 在历史上曾经允许创建这样的标签，并且流行的 IMAP 服务器如 Gmail 都会接受并生成这样的旗标。 有些非 Python 程序也会创建这样的旗标。 虽然它违反 RFC 并且 IMAP 客户端和服务器应当严格遵守规范，但是 imaplib 出于向下兼容的理由仍然继续允许创建这样的标签，并且在 Python 3.6 中会在其被服务器所发送时处理它们，因为这能提升实际的兼容性。
@end quotation
@end cartouche
@end deffn

@geindex subscribe() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 subscribe}@anchor{2e84}
@deffn {方法} IMAP4.subscribe (mailbox)

订阅新邮箱。
@end deffn

@geindex thread() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 thread}@anchor{2e85}
@deffn {方法} IMAP4.thread (threading_algorithm, charset, search_criterion[, ...])

@code{thread} 命令是 @code{search} 的变化形式，带有针对结果的消息串句法。 返回的数据包含以空格分隔的消息串成员列表。

消息串成员由零个或多个消息编号组成，以空格分隔，标示了连续的上下级关系。

thread 命令在 @emph{search_criterion} 参数之前还有两个参数；一个 @emph{threading_algorithm}，以及搜索使用的 @emph{charset}。 请注意不同于 @code{search}，搜索使用的 @emph{charset} 参数是强制性的。 还有一个 @code{uid thread} 命令与 @code{thread} 对应，如同 @code{uid search} 与 @code{search} 对应一个。 @code{thread} 命令首先在邮箱中搜索匹配给定搜索条件的消息，使用 charset 参数来解读搜索条件中的字符串。 然后它将按照指定的消息串算法返回所匹配的消息串。

这是一个 @code{IMAP4rev1} 扩展命令。
@end deffn

@geindex uid() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 uid}@anchor{2e86}
@deffn {方法} IMAP4.uid (command, arg[, ...])

执行 command arg 并附带用 UID 所标识的消息，而不是用消息编号。 返回与命令对应的响应。 必须至少提供一个参数；如果不提供任何参数，服务器将返回错误并引发异常。
@end deffn

@geindex unsubscribe() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 unsubscribe}@anchor{2e87}
@deffn {方法} IMAP4.unsubscribe (mailbox)

取消订阅原有邮箱。
@end deffn

@geindex unselect() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 unselect}@anchor{1b4}
@deffn {方法} IMAP4.unselect ()

@ref{1b4,,imaplib.IMAP4.unselect()} 会释放关联到选定邮箱的服务器资源并将服务器返回到已认证状态。 此命令会执行与 @ref{1b5,,imaplib.IMAP4.close()} 相同的动作，区别在于它不会从当前选定邮箱中永久性地移除消息。


3.9 新版功能.

@end deffn

@geindex xatom() (imaplib.IMAP4 方法)
@anchor{library/imaplib imaplib IMAP4 xatom}@anchor{2e88}
@deffn {方法} IMAP4.xatom (name[, ...])

允许服务器在 @code{CAPABILITY} 响应中通知简单的扩展命令。
@end deffn

在 @ref{1b0,,IMAP4} 的实例上定义了下列属性:

@geindex PROTOCOL_VERSION (imaplib.IMAP4 属性)
@anchor{library/imaplib imaplib IMAP4 PROTOCOL_VERSION}@anchor{2e89}
@deffn {属性} IMAP4.PROTOCOL_VERSION

在服务器的 @code{CAPABILITY} 响应中最新的受支持协议。
@end deffn

@geindex debug (imaplib.IMAP4 属性)
@anchor{library/imaplib imaplib IMAP4 debug}@anchor{2e8a}
@deffn {属性} IMAP4.debug

控制调试输出的整数值。 初始值会从模块变量 @code{Debug} 中获取。 大于三的值表示将追踪每一条命令。
@end deffn

@geindex utf8_enabled (imaplib.IMAP4 属性)
@anchor{library/imaplib imaplib IMAP4 utf8_enabled}@anchor{7e6}
@deffn {属性} IMAP4.utf8_enabled

通常为 @code{False} 的布尔值，但也可以被设为 @code{True}，如果成功地为 @code{UTF8=ACCEPT} 功能发送了 @ref{7e5,,enable()} 命令的话。


3.5 新版功能.

@end deffn

@node IMAP4 示例,,IMAP4 对象,imaplib --- IMAP4 协议客户端
@anchor{library/imaplib id2}@anchor{2e8b}@anchor{library/imaplib imap4-example}@anchor{2e8c}
@subsubsection IMAP4 示例


以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息:

@example
import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()
@end example

@node smtplib ---SMTP协议客户端,uuid --- RFC 4122 定义的UUID对象,imaplib --- IMAP4 协议客户端,互联网协议和支持
@anchor{library/smtplib doc}@anchor{2e8d}@anchor{library/smtplib module-smtplib}@anchor{ed}@anchor{library/smtplib smtplib-smtp-protocol-client}@anchor{2e8e}
@subsection @code{smtplib} ---SMTP协议客户端


@geindex smtplib (模块)

@strong{源代码：} Lib/smtplib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/smtplib.py}

@geindex SMTP; protocol
@geindex Simple Mail Transfer Protocol


__________________________________________________________________


@ref{ed,,smtplib} 模块定义了一个 SMTP 客户端会话对象，该对象可将邮件发送到 Internet 上带有 SMTP 或 ESMTP 接收程序的计算机。 关于 SMTP 和 ESMTP 操作的详情请参阅 
@geindex RFC; RFC 821
RFC 821@footnote{https://tools.ietf.org/html/rfc821.html} (简单邮件传输协议) 和 
@geindex RFC; RFC 1869
RFC 1869@footnote{https://tools.ietf.org/html/rfc1869.html} (SMTP 服务扩展)。

@geindex SMTP (smtplib 中的类)
@anchor{library/smtplib smtplib SMTP}@anchor{1df}
@deffn {类} smtplib.SMTP (host='@w{'}, port=0, local_hostname=None[, timeout], source_address=None)

一个 @ref{1df,,SMTP} 实例就是一个封装好的 SMTP 连接。该实例具有的方法支持所有 SMTP 和 ESMTP 操作。如果传入了可选参数 host 和 port，那么将在初始化时使用这些参数调用 SMTP @ref{1116,,connect()} 方法。如果传入了 @emph{local_hostname}，它将在 HELO/EHLO 命令中被用作本地主机的 FQDN。否则将使用 @ref{27eb,,socket.getfqdn()} 找到本地主机名。如果 @ref{1116,,connect()} 返回了成功码以外的内容，则引发 @ref{2e8f,,SMTPConnectError} 异常。可选参数 @emph{timeout} 指定阻塞操作（如连接尝试）的超时（以秒为单位，如果未指定超时，将使用全局默认超时设置）。到达超时时长后会引发 @ref{ce1,,socket.timeout} 异常。可选参数 source_address 允许在有多张网卡的计算机中绑定到某些特定的源地址，和/或绑定到某些特定的源 TCP 端口。在连接前，套接字需要绑定一个 2 元组 (host, port) 作为其源地址。如果省略，或者是主机为 @code{'@w{'}} 和/或端口为 0，则将使用操作系统默认行为。

正常使用时，只需要初始化或 connect 方法，@ref{83d,,sendmail()} 方法，再加上 @ref{2e90,,SMTP.quit()} 方法即可。下文包括了一个示例。

@ref{1df,,SMTP} 类支持 @ref{7e4,,with} 语句。当这样使用时，@code{with} 语句一退出就会自动发出 SMTP @code{QUIT} 命令。例如:

@example
>>> from smtplib import SMTP
>>> with SMTP("domain.org") as smtp:
...     smtp.noop()
...
(250, b'Ok')
>>>
@end example

引发一个 @ref{fec,,审计事件} @code{smtplib.send}，附带参数 @code{self}, @code{data}。


在 3.3 版更改: 支持了 @ref{7e4,,with} 语句。



在 3.3 版更改: 添加了 source_address 参数。



3.5 新版功能: 现在已支持 SMTPUTF8 扩展 (
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html})。



在 3.9 版更改: 如果 @emph{timeout} 形参被设为零，则它将引发 @ref{16d,,ValueError} 来阻止创建非阻塞的套接字

@end deffn

@geindex SMTP_SSL (smtplib 中的类)
@anchor{library/smtplib smtplib SMTP_SSL}@anchor{1e0}
@deffn {类} smtplib.SMTP_SSL (host='@w{'}, port=0, local_hostname=None, keyfile=None, certfile=None[, timeout], context=None, source_address=None)

@ref{1e0,,SMTP_SSL} 实例与 @ref{1df,,SMTP} 实例的行为完全相同。在开始连接就需要 SSL，且 @code{starttls()} 不适合的情况下，应该使用 @ref{1e0,,SMTP_SSL}。如果未指定 @emph{host}，则使用 localhost。如果 @emph{port} 为 0，则使用标准 SMTP-over-SSL 端口（465）。可选参数 @emph{local_hostname}、@emph{timeout} 和 @emph{source_address} 的含义与 @ref{1df,,SMTP} 类中的相同。可选参数 @emph{context} 是一个 @ref{4f2,,SSLContext} 对象，可以从多个方面配置安全连接。请阅读 @ref{2711,,安全考量} 以获取最佳实践。

@emph{keyfile} 和 @emph{certfile} 是 @emph{context} 的传统替代物，它们可以指向 PEM 格式的私钥和证书链文件用于 SSL 连接。


在 3.3 版更改: 增加了 @emph{context}。



在 3.3 版更改: 添加了 source_address 参数。



在 3.4 版更改: 本类现在支持通过 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称提示} （参阅 @ref{2839,,ssl.HAS_SNI}）进行主机名检查。



3.6 版后已移除: @emph{keyfile} 和 @emph{certfile} 已弃用并转而推荐 @emph{context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。



在 3.9 版更改: 如果 @emph{timeout} 形参被设为零，则它将引发 @ref{16d,,ValueError} 来阻止创建非阻塞的套接字

@end deffn

@geindex LMTP (smtplib 中的类)
@anchor{library/smtplib smtplib LMTP}@anchor{1e1}
@deffn {类} smtplib.LMTP (host='@w{'}, port=LMTP_PORT, local_hostname=None, source_address=None[, timeout])

LMTP 协议与 ESMTP 非常相似，它很大程度上基于标准的 SMTP 客户端。将 Unix 套接字用于 LMTP 是很常见的，因此 @code{connect()} 方法支持 Unix 套接字，也支持常规的 host:port 服务器。可选参数 local_hostname 和 source_address 的含义与 @ref{1df,,SMTP} 类中的相同。要指定 Unix 套接字，@emph{host} 必须使用绝对路径，以 '/' 开头。

支持使用常规的 SMTP 机制来进行认证。 当使用 Unix 套接字时，LMTP 通常不支持或要求任何认证，但你的情况可能会有所不同。


在 3.9 版更改: 添加了可选的 @emph{timeout} 形参。

@end deffn

同样地定义了一组精心选择的异常:

@geindex SMTPException
@anchor{library/smtplib smtplib SMTPException}@anchor{9a7}
@deffn {例外} smtplib.SMTPException

@ref{30b,,OSError} 的子类，它是本模块提供的所有其他异常的基类。


在 3.4 版更改: SMTPException 已成为 @ref{30b,,OSError} 的子类

@end deffn

@geindex SMTPServerDisconnected
@anchor{library/smtplib smtplib SMTPServerDisconnected}@anchor{2e91}
@deffn {例外} smtplib.SMTPServerDisconnected

当服务器意外断开连接，或在 @ref{1df,,SMTP} 实例连接到服务器之前尝试使用它时将引发此异常。
@end deffn

@geindex SMTPResponseException
@anchor{library/smtplib smtplib SMTPResponseException}@anchor{2e92}
@deffn {例外} smtplib.SMTPResponseException

包括 SMTP 错误代码的所有异常的基类。 这些异常会在 SMTP 服务器返回错误代码时在实例中生成。 错误代码存放在错误的 @code{smtp_code} 属性中，并且 @code{smtp_error} 属性会被设为错误消息。
@end deffn

@geindex SMTPSenderRefused
@anchor{library/smtplib smtplib SMTPSenderRefused}@anchor{2e93}
@deffn {例外} smtplib.SMTPSenderRefused

发送方地址被拒绝。  除了在所有 @ref{2e92,,SMTPResponseException} 异常上设置的属性，还会将 'sender' 设为代表拒绝方 SMTP 服务器的字符串。
@end deffn

@geindex SMTPRecipientsRefused
@anchor{library/smtplib smtplib SMTPRecipientsRefused}@anchor{2e94}
@deffn {例外} smtplib.SMTPRecipientsRefused

所有接收方地址被拒绝。 每个接收方的错误可通过属性 @code{recipients} 来访问，该属性是一个字典，其元素顺序与 @ref{83d,,SMTP.sendmail()} 所返回的一致。
@end deffn

@geindex SMTPDataError
@anchor{library/smtplib smtplib SMTPDataError}@anchor{2e95}
@deffn {例外} smtplib.SMTPDataError

SMTP 服务器拒绝接收消息数据。
@end deffn

@geindex SMTPConnectError
@anchor{library/smtplib smtplib SMTPConnectError}@anchor{2e8f}
@deffn {例外} smtplib.SMTPConnectError

在建立与服务器的连接期间发生了错误。
@end deffn

@geindex SMTPHeloError
@anchor{library/smtplib smtplib SMTPHeloError}@anchor{2e96}
@deffn {例外} smtplib.SMTPHeloError

服务器拒绝了我们的 @code{HELO} 消息。
@end deffn

@geindex SMTPNotSupportedError
@anchor{library/smtplib smtplib SMTPNotSupportedError}@anchor{1114}
@deffn {例外} smtplib.SMTPNotSupportedError

尝试的命令或选项不被服务器所支持。


3.5 新版功能.

@end deffn

@geindex SMTPAuthenticationError
@anchor{library/smtplib smtplib SMTPAuthenticationError}@anchor{2e97}
@deffn {例外} smtplib.SMTPAuthenticationError

SMTP 认证出现问题。 最大的可能是服务器不接受所提供的用户名/密码组合。
@end deffn


@subsubheading 参见



@table @asis

@geindex RFC; RFC 821

@item RFC 821@footnote{https://tools.ietf.org/html/rfc821.html} - 简单邮件传输协议

SMTP 的协议定义。 该文件涵盖了 SMTP 的模型、操作程序和协议细节。

@geindex RFC; RFC 1869

@item RFC 1869@footnote{https://tools.ietf.org/html/rfc1869.html} - SMTP 服务扩展

定义了 SMTP 的 ESMTP 扩展。 这描述了一个用新命令扩展 SMTP 的框架，支持动态发现服务器所提供的命令，并定义了一些额外的命令。
@end table


@menu
* SMTP 对象:: 
* SMTP 示例:: 

@end menu

@node SMTP 对象,SMTP 示例,,smtplib ---SMTP协议客户端
@anchor{library/smtplib id1}@anchor{2e98}@anchor{library/smtplib smtp-objects}@anchor{2e99}
@subsubsection SMTP 对象


一个 @ref{1df,,SMTP} 实例拥有以下方法：

@geindex set_debuglevel() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP set_debuglevel}@anchor{83c}
@deffn {方法} SMTP.set_debuglevel (level)

设置调试输出级别。 如果 @emph{level} 的值为 1 或 @code{True} ，就会产生连接的调试信息，以及所有发送和接收服务器的信息。 如果 @emph{level} 的值为 2 ，则这些信息会被加上时间戳。


在 3.5 版更改: 添调试级别 2 。

@end deffn

@geindex docmd() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP docmd}@anchor{2e9a}
@deffn {方法} SMTP.docmd (cmd, args='@w{'})

向服务器发送一条命令 @emph{cmd} 。 可选的参数 @emph{args} 被简单地串联到命令中，用一个空格隔开。

这将返回一个由数字响应代码和实际响应行组成的2元组（多行响应被连接成一个长行）。

在正常操作中，应该没有必要明确地调用这个方法。它被用来实现其他方法，对于测试私有扩展可能很有用。

如果在等待回复的过程中，与服务器的连接丢失， @ref{2e91,,SMTPServerDisconnected} 将被触发。
@end deffn

@geindex connect() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP connect}@anchor{1116}
@deffn {方法} SMTP.connect (host='localhost', port=0)

连接到某个主机的某个端口。默认是连接到 localhost 的标准 SMTP 端口（25）上。如果主机名以冒号 (@code{':'}) 结尾，后跟数字，则该后缀将被删除，且数字将视作要使用的端口号。如果在实例化时指定了 host，则构造函数会自动调用本方法。返回包含响应码和响应消息的 2 元组，它们由服务器在其连接响应中发送。

触发一个 @ref{fec,,auditing event} @code{smtplib.connect}，其参数为 @code{self} ， @code{host} ， @code{port} 。
@end deffn

@geindex helo() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP helo}@anchor{2e9b}
@deffn {方法} SMTP.helo (name='@w{'})

使用 @code{HELO} 向 SMTP 服务器表明自己的身份。 hostname 参数默认为本地主机的完全合格域名。服务器返回的消息被存储为对象的 @code{helo_resp} 属性。

在正常操作中，应该没有必要明确调用这个方法。它将在必要时被 @ref{83d,,sendmail()} 隐式调用。
@end deffn

@geindex ehlo() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP ehlo}@anchor{2e9c}
@deffn {方法} SMTP.ehlo (name='@w{'})

使用 @code{EHLO} 向 ESMTP 服务器标识自身。hostname 参数默认为 localhost 的标准域名。使用 @ref{2e9d,,has_extn()} 来检查响应中的 ESMTP 选项，并将它们保存起来。还给一些信息性的属性赋值：服务器返回的消息存储为 @code{ehlo_resp} 属性；根据服务器是否支持 ESMTP，将 @code{does_esmtp} 设置为 true 或 false；而 @code{esmtp_features} 是一个字典，包含该服务器支持的 SMTP 服务扩展的名称及参数（如果有参数）。

除非你想在发送邮件前使用 @ref{2e9d,,has_extn()} ，否则应该没有必要明确调用这个方法。 它将在必要时被 @ref{83d,,sendmail()} 隐式调用。
@end deffn

@geindex ehlo_or_helo_if_needed() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP ehlo_or_helo_if_needed}@anchor{2e9e}
@deffn {方法} SMTP.ehlo_or_helo_if_needed ()

如果这个会话中没有先前的 @code{EHLO} 或 @code{HELO} 命令，该方法会调用 @ref{2e9c,,ehlo()} 和/或 @ref{2e9b,,helo()} 。它首先尝试 ESMTP @code{EHLO} 。


@table @asis

@item @ref{2e96,,SMTPHeloError}

服务器没有正确回复 @code{HELO} 问候。
@end table
@end deffn

@geindex has_extn() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP has_extn}@anchor{2e9d}
@deffn {方法} SMTP.has_extn (name)

如果 @emph{name} 在服务器返回的 SMTP 服务扩展集合中，返回 @ref{59c,,True} ，否则为 @ref{497,,False} 。大小写被忽略。
@end deffn

@geindex verify() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP verify}@anchor{2e9f}
@deffn {方法} SMTP.verify (address)

使用 SMTP @code{VRFY} 检查此服务器上的某个地址是否有效。 如果用户地址有效则返回一个由代码 250 和完整 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 地址（包括人名）组成的元组。 否则返回 400 或更大的 SMTP 错误代码以及一个错误字符串。

@cartouche
@quotation 注解 
许多网站都禁用 SMTP @code{VRFY} 以阻止垃圾邮件。
@end quotation
@end cartouche
@end deffn

@geindex login() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP login}@anchor{2ea0}
@deffn {方法} SMTP.login (user, password, *, initial_response_ok=True)

登录到一个需要认证的 SMTP 服务器。 参数是用于认证的用户名和密码。 如果会话在之前没有执行过 @code{EHLO} 或 @code{HELO} 命令，此方法会先尝试 ESMTP @code{EHLO}。 如果认证成功则此方法将正常返回，否则可能引发以下异常:


@table @asis

@item @ref{2e96,,SMTPHeloError}

服务器没有正确回复 @code{HELO} 问候。

@item @ref{2e97,,SMTPAuthenticationError}

服务器不接受所提供的用户名/密码组合。

@item @ref{1114,,SMTPNotSupportedError}

服务器不支持 @code{AUTH} 命令。

@item @ref{9a7,,SMTPException}

未找到适当的认证方法。
@end table

@ref{ed,,smtplib} 所支持的每种认证方法只要被服务器声明支持就会被依次尝试。 请参阅 @ref{83b,,auth()} 获取受支持的认证方法列表。 @emph{initial_response_ok} 会被传递给 @ref{83b,,auth()}。

可选的关键字参数 @emph{initial_response_ok} 对于支持它的认证方法，是否可以与 @code{AUTH} 命令一起发送 
@geindex RFC; RFC 4954
RFC 4954@footnote{https://tools.ietf.org/html/rfc4954.html} 中所规定的“初始响应”，而不是要求回复/响应。


在 3.5 版更改: 可能会引发 @ref{1114,,SMTPNotSupportedError}，并添加 @emph{initial_response_ok} 形参。

@end deffn

@geindex auth() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP auth}@anchor{83b}
@deffn {方法} SMTP.auth (mechanism, authobject, *, initial_response_ok=True)

为指定的认证机制 @emph{mechanism} 发送 @code{SMTP} @code{AUTH} 命令，并通过 @emph{authobject} 处理回复响应。

@emph{mechanism} 指定要使用何种认证机制作为 @code{AUTH} 命令的参数；可用的值是在 @code{esmtp_features} 的 @code{auth} 元素中列出的内容。

@emph{authobject} 必须是接受一个可选的单独参数的可调用对象:

@quotation

data = authobject(challenge=None)
@end quotation

如果可选的关键字参数 @emph{initial_response_ok} 为真值，则将先不带参数地调用 @code{authobject()}。 它可以返回 
@geindex RFC; RFC 4954
RFC 4954@footnote{https://tools.ietf.org/html/rfc4954.html} "初始响应" ASCII @code{str}，其内容将被编码并使用下述的 @code{AUTH} 命令来发送。 如果 @code{authobject()} 不支持初始响应（例如由于要求一个回复），它应当将 @code{None} 作为附带 @code{challenge=None} 调用的返回值。 如果 @emph{initial_response_ok} 为假值，则 @code{authobject()} 将不会附带 @code{None} 被首先调用。

如果初始响应检测返回了 @code{None}，或者如果 @emph{initial_response_ok} 为假值，则将调用 @code{authobject()} 来处理服务器的回复响应；它所传递的 @emph{challenge} 参数将为一个 @code{bytes}。 它应当返回用 base64 进行编码的 ASCII @code{str} @emph{data} 并发送给服务器。

@code{SMTP} 类提供的 @code{authobjects} 针对 @code{CRAM-MD5}, @code{PLAIN} 和 @code{LOGIN} 等机制；它们的名称分别是 @code{SMTP.auth_cram_md5}, @code{SMTP.auth_plain} 和 @code{SMTP.auth_login}。 它们都要求将 @code{user} 和 @code{password} 这两个 @code{SMTP} 实例属性设为适当的值。

用户代码通常不需要直接调用 @code{auth}，而是调用 @ref{2ea0,,login()} 方法，它将按上述顺序依次尝试上述每一种机制。 @code{auth} 被公开以便辅助实现 @ref{ed,,smtplib} 没有（或尚未）直接支持的认证方法。


3.5 新版功能.

@end deffn

@geindex starttls() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP starttls}@anchor{b65}
@deffn {方法} SMTP.starttls (keyfile=None, certfile=None, context=None)

将 SMTP 连接设为 TLS (传输层安全) 模式。 后续的所有 SMTP 命令都将被加密。 你应当随即再次调用 @ref{2e9c,,ehlo()}。

如果提供了 @emph{keyfile} 和 @emph{certfile}，它们会被用来创建 @ref{4f2,,ssl.SSLContext}。

可选的 @emph{context} 形参是一个 @ref{4f2,,ssl.SSLContext} 对象；它是使用密钥文件和证书的替代方式，如果指定了该形参则 @emph{keyfile} 和 @emph{certfile} 都应为 @code{None}。

如果这个会话中没有先前的 @code{EHLO} or @code{HELO} 命令，该方法会首先尝试 ESMTP @code{EHLO}。


3.6 版后已移除: @emph{keyfile} 和 @emph{certfile} 已弃用并转而推荐 @emph{context}。 请改用 @ref{b72,,ssl.SSLContext.load_cert_chain()} 或让 @ref{9b0,,ssl.create_default_context()} 为你选择系统所信任的 CA 证书。



@table @asis

@item @ref{2e96,,SMTPHeloError}

服务器没有正确回复 @code{HELO} 问候。

@item @ref{1114,,SMTPNotSupportedError}

服务器不支持 STARTTLS 扩展。

@item @ref{3e4,,RuntimeError}

SSL/TLS 支持在你的 Python 解释器上不可用。
@end table


在 3.3 版更改: 增加了 @emph{context}。



在 3.4 版更改: 此方法现在支持使用 @code{SSLContext.check_hostname} 和 @emph{服务器名称指示符} (参见 @ref{2839,,HAS_SNI}) 进行主机名检查。



在 3.5 版更改: 因缺少 STARTTLS 支持而引发的错误现在是 @ref{1114,,SMTPNotSupportedError} 子类而不是 @ref{9a7,,SMTPException} 基类。

@end deffn

@geindex sendmail() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP sendmail}@anchor{83d}
@deffn {方法} SMTP.sendmail (from_addr, to_addrs, msg, mail_options=(), rcpt_options=())

发送邮件。必要参数是一个 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 发件地址字符串，一个 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 收件地址字符串列表（裸字符串将被视为含有 1 个地址的列表），以及一个消息字符串。调用者可以将 ESMTP 选项列表（如 @code{8bitmime}）作为 @emph{mail_options} 传入，用于 @code{MAIL FROM} 命令。需要与所有 @code{RCPT} 命令一起使用的 ESMTP 选项（如 @code{DSN} 命令）可以作为 @emph{rcpt_options} 传入。（如果需要对不同的收件人使用不同的 ESMTP 选项，则必须使用底层的方法来发送消息，如 @code{mail()}, @code{rcpt()} 和 @code{data()}。）

@cartouche
@quotation 注解 
@emph{from_addr} 和 @emph{to_addrs} 形参被用来构造传输代理所使用的消息封包。 @code{sendmail} 不会以任何方式修改消息标头。
@end quotation
@end cartouche

@emph{msg} 可以是一个包含 ASCII 范围内字符的字符串，或是一个字节串。 字符串会使用 ascii 编解码器编码为字节串，并且单独的 @code{\r} 和 @code{\n} 字符会被转换为 @code{\r\n} 字符序列。 字节串则不会被修改。

如果在此之前本会话没有执行过 @code{EHLO} 或 @code{HELO} 命令，此方法会先尝试 ESMTP @code{EHLO}。 如果服务器执行了 ESMTP，消息大小和每个指定的选项将被传递给它（如果指定的选项属于服务器声明的特性集）。 如果 @code{EHLO} 失败，则将尝试 @code{HELO} 并屏蔽 ESMTP 选项。

如果邮件被至少一个接收方接受则此方法将正常返回。 在其他情况下它将引发异常。 也就是说，如果此方法没有引发异常，则应当会有人收到你的邮件。 如果此方法没有引发异常，它将返回一个字典，其中的条目对应每个拒绝的接收方。 每个条目均包含由服务器发送的 SMTP 错误代码和相应错误消息所组成的元组。

如果 @code{SMTPUTF8} 包括在 @emph{mail_options} 中，并且被服务器所支持，则 @emph{from_addr} 和 @emph{to_addrs} 可能包含非 ASCII 字符。

此方法可能引发以下异常:


@table @asis

@item @ref{2e94,,SMTPRecipientsRefused}

所有收件人都被拒绝。 无人收到邮件。 该异常的 @code{recipients} 属性是一个字典，其中有被拒绝收件人的信息（类似于至少有一个收件人接受邮件时所返回的信息）。

@item @ref{2e96,,SMTPHeloError}

服务器没有正确回复 @code{HELO} 问候。

@item @ref{2e93,,SMTPSenderRefused}

服务器不接受 @emph{from_addr}。

@item @ref{2e95,,SMTPDataError}

服务器回复了一个意外的错误代码（而不是拒绝收件人）。

@item @ref{1114,,SMTPNotSupportedError}

在 @emph{mail_options} 中给出了 @code{SMTPUTF8} 但是不被服务器所支持。
@end table

除非另有说明，即使在引发异常之后连接仍将被打开。


在 3.2 版更改: @emph{msg} 可以为字节串。



在 3.5 版更改: 增加了 @code{SMTPUTF8} 支持，并且如果指定了 @code{SMTPUTF8} 但是不被服务器所支持则可能会引发 @ref{1114,,SMTPNotSupportedError}。

@end deffn

@geindex send_message() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP send_message}@anchor{83e}
@deffn {方法} SMTP.send_message (msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())

本方法是一种快捷方法，用于带着消息调用 @ref{83d,,sendmail()}，消息由 @ref{644,,email.message.Message} 对象表示。参数的含义与 @ref{83d,,sendmail()} 中的相同，除了 @emph{msg}，它是一个 @code{Message} 对象。

如果 @emph{from_addr} 为 @code{None} 或 @emph{to_addrs} 为 @code{None}，那么`@w{`}send_message`@w{`}将根据 
@geindex RFC; RFC 5322
RFC 5322@footnote{https://tools.ietf.org/html/rfc5322.html}，从 @emph{msg} 头部提取地址填充下列参数：如果头部存在 @code{Sender} 字段，则用它填充 @emph{from_addr}，不存在则用 @code{From} 字段填充 @emph{from_addr}。@emph{to_addrs} 组合了 @emph{msg} 中的 @code{To}, @code{Cc} 和 @code{Bcc} 字段的值（字段存在的情况下）。如果一组 @code{Resent-*} 头部恰好出现在 message 中，那么就忽略常规的头部，改用 @code{Resent-*} 头部。如果 message 包含多组 @code{Resent-*} 头部，则引发 @ref{16d,,ValueError}，因为无法明确检测出哪一组 @code{Resent-} 头部是最新的。

@code{send_message} 使用 @ref{c28,,BytesGenerator} 来序列化 @emph{msg}，且将 @code{\r\n} 作为 @emph{linesep}，并调用 @ref{83d,,sendmail()} 来传输序列化后的结果。无论 @emph{from_addr} 和 @emph{to_addrs} 的值为何，@code{send_message} 都不会传输 @emph{msg} 中可能出现的 @code{Bcc} 或 @code{Resent-Bcc} 头部。如果 @emph{from_addr} 和 @emph{to_addrs} 中的某个地址包含非 ASCII 字符，且服务器没有声明支持 @code{SMTPUTF8}，则引发 @code{SMTPNotSupported} 错误。如果服务器支持，则 @code{Message} 将按新克隆的 @ref{73,,policy} 进行序列化，其中的 @ref{7cf,,utf8} 属性被设置为 @code{True}，且 @code{SMTPUTF8} 和 @code{BODY=8BITMIME} 被添加到 @emph{mail_options} 中。


3.2 新版功能.



3.5 新版功能: 支持国际化地址 (@code{SMTPUTF8})。

@end deffn

@geindex quit() (smtplib.SMTP 方法)
@anchor{library/smtplib smtplib SMTP quit}@anchor{2e90}
@deffn {方法} SMTP.quit ()

终结 SMTP 会话并关闭连接。 返回 SMTP @code{QUIT} 命令的结果。
@end deffn

与标准 SMTP/ESMTP 命令 @code{HELP}, @code{RSET}, @code{NOOP}, @code{MAIL}, @code{RCPT} 和 @code{DATA} 对应的低层级方法也是受支持的。 通常不需要直接调用这些方法，因此它们没有被写入本文档。 相关细节请参看模块代码。

@node SMTP 示例,,SMTP 对象,smtplib ---SMTP协议客户端
@anchor{library/smtplib id2}@anchor{2ea1}@anchor{library/smtplib smtp-example}@anchor{2ea2}
@subsubsection SMTP 示例


这个例子提示用户输入消息封包所需的地址 ('To' 和 'From' 地址)，以及所要封包的消息。 请注意包括在消息中的标头必须包括在输入的消息中；这个例子不对 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 标头进行任何处理。 特别地，'To' 和 'From' 地址必须显式地包括在消息标头中。

@example
import smtplib

def prompt(prompt):
    return input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print("Message length is", len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
@end example

@cartouche
@quotation 注解 
通常，你将需要使用 @ref{67,,email} 包的特性来构造电子邮件消息，然后你可以通过 @ref{83e,,send_message()} 来发送它，参见 @ref{93c,,email; 示例}。
@end quotation
@end cartouche

@node uuid --- RFC 4122 定义的UUID对象,socketserver --- 用于网络服务器的框架,smtplib ---SMTP协议客户端,互联网协议和支持
@anchor{library/uuid doc}@anchor{2ea3}@anchor{library/uuid module-uuid}@anchor{12d}@anchor{library/uuid uuid-uuid-objects-according-to-rfc-4122}@anchor{2ea4}
@subsection @code{uuid} --- @strong{RFC 4122} 定义的UUID对象


@geindex RFC; RFC 4122

@geindex uuid (模块)

@strong{Source code:} Lib/uuid.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/uuid.py}


__________________________________________________________________


这个模块提供了不可变的 @ref{392,,UUID} 对象 (@ref{392,,UUID} 类) 和 @ref{520,,uuid1()}, @ref{2ea5,,uuid3()}, @ref{2ea6,,uuid4()}, @ref{2ea7,,uuid5()} 等函数用于生成 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} 所定义的第 1, 3, 4 和 5 版 UUID。

如果你想要的只是一个唯一的ID，你可能应该调用 @ref{520,,uuid1()} 或 @ref{2ea6,,uuid4()}。 注意 @ref{520,,uuid1()} 可能会损害隐私，因为它创建了一个包含计算机网络地址的UUID。 @ref{2ea6,,uuid4()} 可以创建一个随机UUID。

根据底层平台的支持，@ref{520,,uuid1()} 可能会也可能不会返回一个 "安全的" UUID。 安全的 UUID 是使用同步方法生成的，确保没有两个进程可以获得相同的 UUID。 所有 @ref{392,,UUID} 的实例都有一个 @code{is_safe} 属性，使用这个枚举来传递关于 UUID 安全的任何信息:

@geindex SafeUUID (uuid 中的类)
@anchor{library/uuid uuid SafeUUID}@anchor{2ea8}
@deffn {类} uuid.SafeUUID


3.7 新版功能.


@geindex safe (uuid.SafeUUID 属性)
@anchor{library/uuid uuid SafeUUID safe}@anchor{2ea9}
@deffn {属性} safe

该UUID是由平台以多进程安全的方式生成的。
@end deffn

@geindex unsafe (uuid.SafeUUID 属性)
@anchor{library/uuid uuid SafeUUID unsafe}@anchor{2eaa}
@deffn {属性} unsafe

UUID不是以多进程安全的方式生成的。
@end deffn

@geindex unknown (uuid.SafeUUID 属性)
@anchor{library/uuid uuid SafeUUID unknown}@anchor{2eab}
@deffn {属性} unknown

该平台不提供UUID是否安全生成的信息。
@end deffn
@end deffn

@geindex UUID (uuid 中的类)
@anchor{library/uuid uuid UUID}@anchor{392}
@deffn {类} uuid.UUID (hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)

用一串32位十六进制数字、一串大端序16个字节作为*bytes*参数、一串16个小端序字节作为*bytes_le*参数、一个由六个整数组成的元组（32位*time_low*，16位*time_mid*，16位*time_hi_version*，8位*clock_seq_hi_variant*，8位*clock_seq_low*，48位*node*）作为*fields*参数，或者一个128位整数作为*int*参数创建一个UUID。当给出一串十六进制数字时，大括号、连字符和URN前缀都是可选的。 例如，这些表达式都产生相同的UUID:

@example
UUID('@{12345678-1234-5678-1234-567812345678@}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes=b'\x12\x34\x56\x78'*4)
UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
              b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
@end example

必须给出 @emph{hex}、@emph{bytes}、@emph{bytes_le}、@emph{fields} 或 @emph{int} 中的唯一一个。 @emph{version} 参数是可选的；如果给定，产生的UUID将根据 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} 设置其变体和版本号，覆盖给定的 @emph{hex}、@emph{bytes}、@emph{bytes_le}、@emph{fields} 或 @emph{int} 中的位。

UUID 对象的比较是通过比较它们的 @ref{2eac,,UUID.int} 属性进行的。 与非 UUID 对象的比较会引发 @ref{1ff,,TypeError}。

@code{str(uuid)} 返回一个 @code{12345678-1234-5678-1234-567812345678} 形式的字符串，其中 32 位十六进制数字代表 UUID。
@end deffn

@ref{392,,UUID} 实例有这些只读的属性:

@geindex bytes (uuid.UUID 属性)
@anchor{library/uuid uuid UUID bytes}@anchor{2ead}
@deffn {属性} UUID.bytes

UUID 是一个 16 字节的字符串（包含 6 个整数字段，大端字节顺序）。
@end deffn

@geindex bytes_le (uuid.UUID 属性)
@anchor{library/uuid uuid UUID bytes_le}@anchor{2eae}
@deffn {属性} UUID.bytes_le

UUID 是一个 16 字节的字符串（其中 @emph{time_low}、@emph{time_mid} 和 @emph{time_hi_version} 为小端字节顺序）。
@end deffn

@geindex fields (uuid.UUID 属性)
@anchor{library/uuid uuid UUID fields}@anchor{2eaf}
@deffn {属性} UUID.fields

以元组形式存放的UUID的6个整数域，有六个单独的属性和两个派生属性：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

意义

@item

@code{time_low}

@tab

UUID的前32位

@item

@code{time_mid}

@tab

接前一域的16位

@item

@code{time_hi_version}

@tab

接前一域的16位

@item

@code{clock_seq_hi_variant}

@tab

接前一域的8位

@item

@code{clock_seq_low}

@tab

接前一域的8位

@item

@code{node}

@tab

UUID的最后48位

@item

@ref{10c,,time}

@tab

UUID的总长60位的时间戳

@item

@code{clock_seq}

@tab

14位的序列号

@end multitable

@end deffn

@geindex hex (uuid.UUID 属性)
@anchor{library/uuid uuid UUID hex}@anchor{2eb0}
@deffn {属性} UUID.hex

UUID 是一个 32 字符的小写十六进制数码字符串。
@end deffn

@geindex int (uuid.UUID 属性)
@anchor{library/uuid uuid UUID int}@anchor{2eac}
@deffn {属性} UUID.int

UUID是一个128位的整数。
@end deffn

@geindex urn (uuid.UUID 属性)
@anchor{library/uuid uuid UUID urn}@anchor{2eb1}
@deffn {属性} UUID.urn

在 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} 中定义的 URN 形式的 UUID。
@end deffn

@geindex variant (uuid.UUID 属性)
@anchor{library/uuid uuid UUID variant}@anchor{2eb2}
@deffn {属性} UUID.variant

UUID 的变体，它决定了 UUID 的内部布局。 这将是 @ref{2eb3,,RESERVED_NCS}, @ref{2eb4,,RFC_4122}, @ref{2eb5,,RESERVED_MICROSOFT} 或 @ref{2eb6,,RESERVED_FUTURE} 中的一个。
@end deffn

@geindex version (uuid.UUID 属性)
@anchor{library/uuid uuid UUID version}@anchor{2eb7}
@deffn {属性} UUID.version

UUID 版本号（1 到 5，只有当变体为 @ref{2eb4,,RFC_4122} 时才有意义）。
@end deffn

@geindex is_safe (uuid.UUID 属性)
@anchor{library/uuid uuid UUID is_safe}@anchor{51e}
@deffn {属性} UUID.is_safe

一个 @ref{2ea8,,SafeUUID} 的枚举，表示平台是否以多进程安全的方式生成 UUID。


3.7 新版功能.

@end deffn

@ref{12d,,uuid} 模块定义了以下函数：

@geindex getnode() (在 uuid 模块中)
@anchor{library/uuid uuid getnode}@anchor{51f}
@deffn {函数} uuid.getnode ()

获取 48 位正整数形式的硬件地址。 第一次运行时，它可能会启动一个单独的程序，这可能会相当慢。 如果所有获取硬件地址的尝试都失败了，我们会按照 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} 中的建议，选择一个随机的 48 位数字，其多播位 (第一个八进制数的最小有效位) 设置为 1。 “硬件地址”是指一个网络接口的 MAC 地址。 在一台有多个网络接口的机器上，普遍管理的 MAC 地址 (即第一个八位数的第二个最小有效位是 @emph{未设置的}) 将比本地管理的 MAC 地址优先，但没有其他排序保证。


在 3.7 版更改: 普遍管理的MAC地址优于本地管理的MAC地址，因为前者保证是全球唯一的，而后者则不是。

@end deffn

@geindex getnode

@geindex uuid1() (在 uuid 模块中)
@anchor{library/uuid uuid uuid1}@anchor{520}
@deffn {函数} uuid.uuid1 (node=None, clock_seq=None)

根据主机 ID、序列号和当前时间生成一个 UUID。 如果没有给出 @emph{node}，则使用 @ref{51f,,getnode()} 来获取硬件地址。 如果给出了 @emph{clock_seq}，它将被用作序列号；否则将选择一个随机的 14 比特位序列号。
@end deffn

@geindex uuid1

@geindex uuid3() (在 uuid 模块中)
@anchor{library/uuid uuid uuid3}@anchor{2ea5}
@deffn {函数} uuid.uuid3 (namespace, name)

根据命名空间标识符（这是一个UUID）和名称（这是一个字符串）的MD5哈希值，生成一个UUID。
@end deffn

@geindex uuid3

@geindex uuid4() (在 uuid 模块中)
@anchor{library/uuid uuid uuid4}@anchor{2ea6}
@deffn {函数} uuid.uuid4 ()

生成一个随机的UUID。
@end deffn

@geindex uuid4

@geindex uuid5() (在 uuid 模块中)
@anchor{library/uuid uuid uuid5}@anchor{2ea7}
@deffn {函数} uuid.uuid5 (namespace, name)

根据命名空间标识符（这是一个UUID）和名称（这是一个字符串）的SHA-1哈希值生成一个UUID。
@end deffn

@geindex uuid5

@ref{12d,,uuid} 模块定义了以下命名空间标识符，供 @ref{2ea5,,uuid3()} 或 @ref{2ea7,,uuid5()} 使用。

@geindex NAMESPACE_DNS() (在 uuid 模块中)
@anchor{library/uuid uuid NAMESPACE_DNS}@anchor{2eb8}
@deffn {数据} uuid.NAMESPACE_DNS

当指定这个命名空间时，@emph{name} 字符串是一个完全限定的域名。
@end deffn

@geindex NAMESPACE_URL() (在 uuid 模块中)
@anchor{library/uuid uuid NAMESPACE_URL}@anchor{2eb9}
@deffn {数据} uuid.NAMESPACE_URL

当指定这个命名空间时，@emph{name} 字符串是一个 URL。
@end deffn

@geindex NAMESPACE_OID() (在 uuid 模块中)
@anchor{library/uuid uuid NAMESPACE_OID}@anchor{2eba}
@deffn {数据} uuid.NAMESPACE_OID

当指定这个命名空间时，@emph{name} 字符串是一个 ISO OID。
@end deffn

@geindex NAMESPACE_X500() (在 uuid 模块中)
@anchor{library/uuid uuid NAMESPACE_X500}@anchor{2ebb}
@deffn {数据} uuid.NAMESPACE_X500

当指定这个命名空间时，@emph{name} 字符串是 DER 或文本输出格式的 X.500 DN。
@end deffn

@ref{12d,,uuid} 模块为 @code{variant} 属性的可能值定义了以下常量:

@geindex RESERVED_NCS() (在 uuid 模块中)
@anchor{library/uuid uuid RESERVED_NCS}@anchor{2eb3}
@deffn {数据} uuid.RESERVED_NCS

为NCS兼容性保留。
@end deffn

@geindex RFC_4122() (在 uuid 模块中)
@anchor{library/uuid uuid RFC_4122}@anchor{2eb4}
@deffn {数据} uuid.RFC_4122

指定 
@geindex RFC; RFC 4122
RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} 中给出的 UUID 布局。
@end deffn

@geindex RESERVED_MICROSOFT() (在 uuid 模块中)
@anchor{library/uuid uuid RESERVED_MICROSOFT}@anchor{2eb5}
@deffn {数据} uuid.RESERVED_MICROSOFT

为微软的兼容性保留。
@end deffn

@geindex RESERVED_FUTURE() (在 uuid 模块中)
@anchor{library/uuid uuid RESERVED_FUTURE}@anchor{2eb6}
@deffn {数据} uuid.RESERVED_FUTURE

保留给未来的定义。
@end deffn


@subsubheading 参见



@table @asis

@geindex RFC; RFC 4122

@item RFC 4122@footnote{https://tools.ietf.org/html/rfc4122.html} - 通用唯一标识符（UUID）URN命名空间

本规范定义了UUID的统一资源名称空间，UUID的内部格式，以及生成UUID的方法。
@end table


@menu
* 示例: 示例<35>. 

@end menu

@node 示例<35>,,,uuid --- RFC 4122 定义的UUID对象
@anchor{library/uuid example}@anchor{2ebc}@anchor{library/uuid uuid-example}@anchor{2ebd}
@subsubsection 示例


下面是一些 @ref{12d,,uuid} 模块的典型使用例子:

@example
>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('@{00010203-0405-0607-0809-0a0b0c0d0e0f@}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
@end example

@node socketserver --- 用于网络服务器的框架,http server --- HTTP 服务器,uuid --- RFC 4122 定义的UUID对象,互联网协议和支持
@anchor{library/socketserver doc}@anchor{2ebe}@anchor{library/socketserver module-socketserver}@anchor{f0}@anchor{library/socketserver socketserver-a-framework-for-network-servers}@anchor{2ebf}
@subsection @code{socketserver} --- 用于网络服务器的框架


@geindex socketserver (模块)

@strong{源代码:} Lib/socketserver.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/socketserver.py}


__________________________________________________________________


@ref{f0,,socketserver} 模块简化了编写网络服务器的任务。

该模块具有四个基础实体服务器类:

@geindex TCPServer (socketserver 中的类)
@anchor{library/socketserver socketserver TCPServer}@anchor{2ec0}
@deffn {类} socketserver.TCPServer (server_address, RequestHandlerClass, bind_and_activate=True)

This uses the Internet TCP protocol, which provides for
continuous streams of data between the client and server.
If @emph{bind_and_activate} is true, the constructor automatically attempts to
invoke @ref{2ec1,,server_bind()} and
@ref{2ec2,,server_activate()}.  The other parameters are passed to
the @ref{b6a,,BaseServer} base class.
@end deffn

@geindex UDPServer (socketserver 中的类)
@anchor{library/socketserver socketserver UDPServer}@anchor{2ec3}
@deffn {类} socketserver.UDPServer (server_address, RequestHandlerClass, bind_and_activate=True)

该类使用数据包，即一系列离散的信息分包，它们可能会无序地到达或在传输中丢失。 该类的形参与 @ref{2ec0,,TCPServer} 的相同。
@end deffn

@geindex UnixStreamServer (socketserver 中的类)
@geindex UnixDatagramServer (socketserver 中的类)
@anchor{library/socketserver socketserver UnixStreamServer}@anchor{2ec4}
@deffn {类} socketserver.UnixStreamServer (server_address, RequestHandlerClass, bind_and_activate=True)
@anchor{library/socketserver socketserver UnixDatagramServer}@anchor{2ec5}
@deffnx {类} socketserver.UnixDatagramServer (server_address, RequestHandlerClass, bind_and_activate=True)

这两个更常用的类与 TCP 和 UDP 类相似，但使用 Unix 域套接字；它们在非 Unix 系统平台上不可用。 它们的形参与 @ref{2ec0,,TCPServer} 的相同。
@end deffn

这四个类会 @emph{同步地} 处理请求；每个请求必须完成才能开始下一个请求。 这就不适用于每个请求要耗费很长时间来完成的情况，或者因为它需要大量的计算，又或者它返回了大量的数据而客户端处理起来很缓慢。 解决方案是创建单独的进程或线程来处理每个请求；@ref{4e4,,ForkingMixIn} 和 @ref{4e5,,ThreadingMixIn} 混合类可以被用于支持异步行为。

创建一个服务器需要分几个步骤进行。 首先，你必须通过子类化 @ref{2ec6,,BaseRequestHandler} 类并重载其 @ref{2ec7,,handle()} 方法来创建一个请求处理句柄类；这个方法将处理传入的请求。 其次，你必须实例化某个服务器类，将服务器地址和请求处理句柄类传给它。 建议在 @ref{7e4,,with} 语句中使用该服务器。 然后再调用服务器对象的 @ref{2ec8,,handle_request()} 或 @ref{b6c,,serve_forever()} 方法来处理一个或多个请求。 最后，调用 @ref{2ec9,,server_close()} 来关闭套接字（除非你使用了 @code{with} 语句）。

当从 @ref{4e5,,ThreadingMixIn} 继承线程连接行为时，你应当显式地声明你希望在突然关机时你的线程采取何种行为。 @ref{4e5,,ThreadingMixIn} 类定义了一个属性 @emph{daemon_threads}，它指明服务器是否应当等待线程终止。 如果你希望线程能自主行动你应当显式地设置这个旗标；默认值为 @ref{497,,False}，表示 Python 将不会在 @ref{4e5,,ThreadingMixIn} 所创建的所有线程都退出之前退出。

服务器类具有同样的外部方法和属性，无论它们使用哪种网络协议。

@menu
* 服务器创建的说明:: 
* Server 对象: Server 对象<2>. 
* 请求处理句柄对象:: 
* 示例: 示例<36>. 

@end menu

@node 服务器创建的说明,Server 对象<2>,,socketserver --- 用于网络服务器的框架
@anchor{library/socketserver server-creation-notes}@anchor{2eca}
@subsubsection 服务器创建的说明


在继承图中有五个类，其中四个代表四种类型的同步服务器:

@example
+------------+
| BaseServer |
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+
@end example

请注意 @ref{2ec5,,UnixDatagramServer} 派生自 @ref{2ec3,,UDPServer}，而不是 @ref{2ec4,,UnixStreamServer} --- IP 和 Unix 流服务器的唯一区别是地址族，它会在两种 Unix 服务器类中简单地重复。

@geindex ForkingMixIn (socketserver 中的类)
@geindex ThreadingMixIn (socketserver 中的类)
@anchor{library/socketserver socketserver ForkingMixIn}@anchor{4e4}
@deffn {类} socketserver.ForkingMixIn
@anchor{library/socketserver socketserver ThreadingMixIn}@anchor{4e5}
@deffnx {类} socketserver.ThreadingMixIn

每种服务器类型的分叉和线程版本都可以使用这些混合类来创建。 例如，@ref{2ecb,,ThreadingUDPServer} 的创建方式如下:

@example
class ThreadingUDPServer(ThreadingMixIn, UDPServer):
    pass
@end example

混合类先出现，因为它重载了 @ref{2ec3,,UDPServer} 中定义的一个方法。 设置各种属性也会改变下层服务器机制的行为。

@ref{4e4,,ForkingMixIn} 和下文提及的分叉类仅在支持 @ref{a4b,,fork()} 的 POSIX 系统平台上可用。

@code{socketserver.ForkingMixIn.server_close()} 会等待直到所有子进程完成，除非 @code{socketserver.ForkingMixIn.block_on_close} 属性为假值。

@code{socketserver.ThreadingMixIn.server_close()} 会等待直到所有非守护类线程完成，除非 @code{socketserver.ThreadingMixIn.block_on_close} 属性为假值。 请将 @code{ThreadingMixIn.daemon_threads} 设为 @code{True} 来使用守护类线程以便不等待线完成。


在 3.7 版更改: @code{socketserver.ForkingMixIn.server_close()} 和 @code{socketserver.ThreadingMixIn.server_close()} 现在会等待直到所有子进程和非守护类线程完成。 请新增一个 @code{socketserver.ForkingMixIn.block_on_close} 类属性来选择 3.7 版之前的行为。

@end deffn

@geindex ForkingTCPServer (socketserver 中的类)
@geindex ForkingUDPServer (socketserver 中的类)
@geindex ThreadingTCPServer (socketserver 中的类)
@geindex ThreadingUDPServer (socketserver 中的类)
@anchor{library/socketserver socketserver ForkingTCPServer}@anchor{2ecc}
@deffn {类} socketserver.ForkingTCPServer
@anchor{library/socketserver socketserver ForkingUDPServer}@anchor{2ecd}
@deffnx {类} socketserver.ForkingUDPServer
@anchor{library/socketserver socketserver ThreadingTCPServer}@anchor{2ece}
@deffnx {类} socketserver.ThreadingTCPServer
@anchor{library/socketserver socketserver ThreadingUDPServer}@anchor{2ecb}
@deffnx {类} socketserver.ThreadingUDPServer

这些类都是使用混合类来预定义的。
@end deffn

要实现一个服务，你必须从 @ref{2ec6,,BaseRequestHandler} 派生一个类并重定义其 @ref{2ec7,,handle()} 方法。 然后你可以通过组合某种服务器类型与你的请求处理句柄类来运行各种版本的服务。 请求处理句柄类对于数据报和流服务必须是不相同的。 这可以通过使用处理句柄子类 @ref{688,,StreamRequestHandler} 或 @ref{2ecf,,DatagramRequestHandler} 来隐藏。

当然，你仍然需要动点脑筋！ 举例来说，如果服务包含可能被不同请求所修改的内存状态则使用分叉服务器是没有意义的，因为在子进程中的修改将永远不会触及保存在父进程中的初始状态并传递到各个子进程。 在这种情况下，你可以使用线程服务器，但你可能必须使用锁来保护共享数据的一致性。

另一方面，如果你是在编写一个所有数据保存在外部（例如文件系统）的 HTTP 服务器，同步类实际上将在正在处理某个请求的时候“失聪” -- 如果某个客户端在接收它所请求的所有数据时很缓慢这可能会是非常长的时间。 这时线程或分叉服务器会更为适用。

在某些情况下，合适的做法是同步地处理请求的一部分，但根据请求数据在分叉的子进程中完成处理。 这可以通过使用一个同步服务器并在请求处理句柄类 @ref{2ec7,,handle()} 中进行显式分叉来实现。

还有一种可以在既不支持线程也不支持 @ref{a4b,,fork()} 的环境（或者对于本服务来说这两者开销过大或是不适用）中处理多个同时请求的方式是维护一个显式的部分完成的请求表并使用 @ref{e6,,selectors} 来决定接下来要处理哪个请求（或者是否要处理一个新传入的请求）。 这对于流服务来说特别重要，因为每个客户端可能会连接很长的时间（如果不能使用线程或子进程）。 请参阅 @ref{a,,asyncore} 来了解另一种管理方式。

@c XXX should data and methods be intermingled, or separate?
@c how should the distinction between class and instance variables be drawn?

@node Server 对象<2>,请求处理句柄对象,服务器创建的说明,socketserver --- 用于网络服务器的框架
@anchor{library/socketserver server-objects}@anchor{2ed0}
@subsubsection Server 对象


@geindex BaseServer (socketserver 中的类)
@anchor{library/socketserver socketserver BaseServer}@anchor{b6a}
@deffn {类} socketserver.BaseServer (server_address, RequestHandlerClass)

这是本模块中所有 Server 对象的超类。 它定义了下文给出的接口，但没有实现大部分的方法，它们应在子类中实现。 两个形参存储在对应的 @ref{2ed1,,server_address} 和 @ref{2ed2,,RequestHandlerClass} 属性中。

@geindex fileno() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer fileno}@anchor{2ed3}
@deffn {方法} fileno ()

返回服务器正在监听的套接字的以整数表示的文件描述符。 此函数最常被传递给 @ref{e6,,selectors}，以允许在同一进程中监控多个服务器。
@end deffn

@geindex handle_request() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer handle_request}@anchor{2ec8}
@deffn {方法} handle_request ()

处理单个请求。 此函数会依次调用下列方法: @ref{2ed4,,get_request()}, @ref{2ed5,,verify_request()} 和 @ref{2ed6,,process_request()}。 如果用户提供的处理句柄类的 @ref{2ec7,,handle()} 方法引发了异常，则将调用服务器的 @ref{6fe,,handle_error()} 方法。 如果在 @ref{2ed7,,timeout} 秒内未接收到请求，将会调用 @ref{2ed8,,handle_timeout()} 并将返回 @ref{2ec8,,handle_request()}。
@end deffn

@geindex serve_forever() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer serve_forever}@anchor{b6c}
@deffn {方法} serve_forever (poll_interval=0.5)

对请求进行处理直至收到显式的 @ref{119e,,shutdown()} 请求。 每隔 @emph{poll_interval} 秒对 shutdown 进行轮询。 忽略 @ref{2ed7,,timeout} 属性。 它还会调用 @ref{b6b,,service_actions()}，这可被子类或混合类用来提供某个给定服务的专属操作。 例如，@ref{4e4,,ForkingMixIn} 类使用 @ref{b6b,,service_actions()} 来清理僵尸子进程。


在 3.3 版更改: 将 @code{service_actions} 调用添加到 @code{serve_forever} 方法。

@end deffn

@geindex service_actions() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer service_actions}@anchor{b6b}
@deffn {方法} service_actions ()

此方法会在 the @ref{b6c,,serve_forever()} 循环中被调用。 此方法可被子类或混合类所重载以执行某个给定服务的专属操作，例如清理操作。


3.3 新版功能.

@end deffn

@geindex shutdown() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer shutdown}@anchor{119e}
@deffn {方法} shutdown ()

通知 @ref{b6c,,serve_forever()} 循环停止并等待它完成。 @ref{119e,,shutdown()} 必须在 @ref{b6c,,serve_forever()} 运行于不同线程时被调用否则它将发生死锁。
@end deffn

@geindex server_close() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer server_close}@anchor{2ec9}
@deffn {方法} server_close ()

清理服务器。 可以被重载。
@end deffn

@geindex address_family (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer address_family}@anchor{2ed9}
@deffn {属性} address_family

服务器套接字所属的协议族。 常见的例子有 @ref{f76,,socket.AF_INET} 和 @ref{f78,,socket.AF_UNIX}。
@end deffn

@geindex RequestHandlerClass (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer RequestHandlerClass}@anchor{2ed2}
@deffn {属性} RequestHandlerClass

用户提供的请求处理句柄类；将为每个请求创建该类的实例。
@end deffn

@geindex server_address (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer server_address}@anchor{2ed1}
@deffn {属性} server_address

The address on which the server is listening.  The format of addresses varies
depending on the protocol family;
see the documentation for the @ref{ef,,socket} module
for details.  For Internet protocols, this is a tuple containing a string giving
the address, and an integer port number: @code{('127.0.0.1', 80)}, for example.
@end deffn

@geindex socket (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer socket}@anchor{2eda}
@deffn {属性} socket

将由服务器用于监听入站请求的套接字对象。
@end deffn

服务器类支持下列类变量:

@c XXX should class variables be covered before instance variables, or vice versa?

@geindex allow_reuse_address (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer allow_reuse_address}@anchor{2edb}
@deffn {属性} allow_reuse_address

服务器是否要允许地址的重用。 默认值为 @ref{497,,False}，并可在子类中设置以改变策略。
@end deffn

@geindex request_queue_size (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer request_queue_size}@anchor{2edc}
@deffn {属性} request_queue_size

请求队列的长度。 如果处理单个请求要花费很长的时间，则当服务器正忙时到达的任何请求都会被加入队列，最多加入 @ref{2edc,,request_queue_size} 个请求。 一旦队列被加满，来自客户端的更多请求将收到 "Connection denied" 错误。 默认值为 5，但可在子类中重载。
@end deffn

@geindex socket_type (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer socket_type}@anchor{2edd}
@deffn {属性} socket_type

服务器使用的套接字类型；常见的有 @ref{d5a,,socket.SOCK_STREAM} 和 @ref{d59,,socket.SOCK_DGRAM} 这两个值。
@end deffn

@geindex timeout (socketserver.BaseServer 属性)
@anchor{library/socketserver socketserver BaseServer timeout}@anchor{2ed7}
@deffn {属性} timeout

超时限制，以秒数表示，或者如果不限制超时则为 @ref{204,,None}。 如果在超时限制期间没有收到 @ref{2ec8,,handle_request()}，则会调用 @ref{2ed8,,handle_timeout()} 方法。
@end deffn

有多个服务器方法可被服务器基类的子类例如 @ref{2ec0,,TCPServer} 所重载；这些方法对服务器对象的外部用户来说并无用处。

@c XXX should the default implementations of these be documented, or should
@c it be assumed that the user will look at socketserver.py?

@geindex finish_request() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer finish_request}@anchor{2ede}
@deffn {方法} finish_request (request, client_address)

通过实例化 @ref{2ed2,,RequestHandlerClass} 并调用其 @ref{2ec7,,handle()} 方法来实际处理请求。
@end deffn

@geindex get_request() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer get_request}@anchor{2ed4}
@deffn {方法} get_request ()

必须接受来自套接字的请求，并返回一个 2 元组，其中包含用来与客户端通信的 @emph{new} 套接字对象，以及客户端的地址。
@end deffn

@geindex handle_error() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer handle_error}@anchor{6fe}
@deffn {方法} handle_error (request, client_address)

此函数会在 @ref{2ed2,,RequestHandlerClass} 实例的 @ref{2ec7,,handle()} 方法引发异常时被调用。 默认行为是将回溯信息打印到标准错误并继续处理其他请求。


在 3.6 版更改: 现在只针对派生自 @ref{2e3,,Exception} 类的异常调用此方法。

@end deffn

@geindex handle_timeout() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer handle_timeout}@anchor{2ed8}
@deffn {方法} handle_timeout ()

此函数会在 @ref{2ed7,,timeout} 属性被设为 @ref{204,,None} 以外的值并且在超出时限之后仍未收到请求时被调用。 分叉服务器的默认行为是收集任何已退出的子进程状态，而在线程服务器中此方法则不做任何操作。
@end deffn

@geindex process_request() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer process_request}@anchor{2ed6}
@deffn {方法} process_request (request, client_address)

调用 @ref{2ede,,finish_request()} 来创建 @ref{2ed2,,RequestHandlerClass} 的实例。 如果需要，此函数可创建一个新的进程或线程来处理请求；@ref{4e4,,ForkingMixIn} 和 @ref{4e5,,ThreadingMixIn} 类能完成此任务。
@end deffn

@c Is there any point in documenting the following two functions?
@c What would the purpose of overriding them be: initializing server
@c instance variables, adding new network families?

@geindex server_activate() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer server_activate}@anchor{2ec2}
@deffn {方法} server_activate ()

由服务器的构造器调用以激活服务器。 TCP 服务器的默认行为只是在服务器的套接字上发起调用 @ref{844,,listen()}。 可以被重载。
@end deffn

@geindex server_bind() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer server_bind}@anchor{2ec1}
@deffn {方法} server_bind ()

由服务器的构造器调用以将套接字绑定到所需的地址。 可以被重载。
@end deffn

@geindex verify_request() (socketserver.BaseServer 方法)
@anchor{library/socketserver socketserver BaseServer verify_request}@anchor{2ed5}
@deffn {方法} verify_request (request, client_address)

必须返回一个布尔值；如果值为 @ref{59c,,True}，请求将被处理。 而如果值为 @ref{497,,False}，请求将被拒绝。 此函数可被重载以实现服务器的访问控制。 默认实现总是返回 @ref{59c,,True}。
@end deffn


在 3.6 版更改: 添加了对 @ref{66b,,context manager} 协议的支持。 退出上下文管理器与调用 @ref{2ec9,,server_close()} 等效。

@end deffn

@node 请求处理句柄对象,示例<36>,Server 对象<2>,socketserver --- 用于网络服务器的框架
@anchor{library/socketserver request-handler-objects}@anchor{2edf}
@subsubsection 请求处理句柄对象


@geindex BaseRequestHandler (socketserver 中的类)
@anchor{library/socketserver socketserver BaseRequestHandler}@anchor{2ec6}
@deffn {类} socketserver.BaseRequestHandler

这是所有请求处理句柄对象的超类。 它定义了下文列出的接口。 一个实体请求处理句柄子类必须定义新的 @ref{2ec7,,handle()} 方法，并可重载任何其他方法。 对于每个请求都会创建一个新的子类的实例。

@geindex setup() (socketserver.BaseRequestHandler 方法)
@anchor{library/socketserver socketserver BaseRequestHandler setup}@anchor{2ee0}
@deffn {方法} setup ()

会在 @ref{2ec7,,handle()} 方法之前被调用以执行任何必要的初始化操作。 默认实现不执行任何操作。
@end deffn

@geindex handle() (socketserver.BaseRequestHandler 方法)
@anchor{library/socketserver socketserver BaseRequestHandler handle}@anchor{2ec7}
@deffn {方法} handle ()

此函数必须执行为请求提供服务所需的全部操作。 默认实现不执行任何操作。 它有几个可用的实例属性；请求为 @code{self.request}；客户端地址为 @code{self.client_address}；服务器实例为 @code{self.server}，如果它需要访问特定服务器信息的话。

针对数据报或流服务的 @code{self.request} 类型是不同的。 对于流服务，@code{self.request} 是一个套接字对象；对于数据报服务，@code{self.request} 是一对字符串与套接字。
@end deffn

@geindex finish() (socketserver.BaseRequestHandler 方法)
@anchor{library/socketserver socketserver BaseRequestHandler finish}@anchor{2ee1}
@deffn {方法} finish ()

在 @ref{2ec7,,handle()} 方法之后调用以执行任何需要的清理操作。 默认实现不执行任何操作。 如果 @ref{2ee0,,setup()} 引发了异常，此函数将不会被调用。
@end deffn
@end deffn

@geindex StreamRequestHandler (socketserver 中的类)
@geindex DatagramRequestHandler (socketserver 中的类)
@anchor{library/socketserver socketserver StreamRequestHandler}@anchor{688}
@deffn {类} socketserver.StreamRequestHandler
@anchor{library/socketserver socketserver DatagramRequestHandler}@anchor{2ecf}
@deffnx {类} socketserver.DatagramRequestHandler

@ref{2ec6,,BaseRequestHandler} 子类重载了 @ref{2ee0,,setup()} 和 @ref{2ee1,,finish()} 方法，并提供了 @code{self.rfile} 和 @code{self.wfile} 属性。 @code{self.rfile} 和 @code{self.wfile} 属性可以被分别读取或写入，以获取请求数据或将数据返回给客户端。

这两个类的 @code{rfile} 属性都支持 @ref{689,,io.BufferedIOBase} 可读接口，并且 @code{DatagramRequestHandler.wfile} 还支持 @ref{689,,io.BufferedIOBase} 可写接口。


在 3.6 版更改: @code{StreamRequestHandler.wfile} 也支持 @ref{689,,io.BufferedIOBase} 可写接口。

@end deffn

@node 示例<36>,,请求处理句柄对象,socketserver --- 用于网络服务器的框架
@anchor{library/socketserver examples}@anchor{2ee2}
@subsubsection 示例


@menu
* socketserver.TCPServer 示例: socketserver TCPServer 示例. 
* socketserver.UDPServer 示例: socketserver UDPServer 示例. 
* 异步混合类:: 

@end menu

@node socketserver TCPServer 示例,socketserver UDPServer 示例,,示例<36>
@anchor{library/socketserver socketserver-tcpserver-example}@anchor{2ee3}
@subsubsection @code{socketserver.TCPServer} 示例


以下是服务端:

@example
import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("@{@} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
@end example

一个使用流（通过提供标准文件接口来简化通信的文件类对象）的替代请求处理句柄类:

@example
class MyTCPHandler(socketserver.StreamRequestHandler):

    def handle(self):
        # self.rfile is a file-like object created by the handler;
        # we can now use e.g. readline() instead of raw recv() calls
        self.data = self.rfile.readline().strip()
        print("@{@} wrote:".format(self.client_address[0]))
        print(self.data)
        # Likewise, self.wfile is a file-like object used to write back
        # to the client
        self.wfile.write(self.data.upper())
@end example

区别在于第二个处理句柄的 @code{readline()} 调用将多次调用 @code{recv()} 直至遇到一个换行符，而第一个处理句柄的单次 @code{recv()} 调用只是返回在一次 @code{sendall()} 调用中由客户端发送的内容。

以下是客户端:

@example
import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     @{@}".format(data))
print("Received: @{@}".format(received))
@end example

这个示例程序的输出应该是像这样的:

服务器:

@example
$ python TCPServer.py
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'
@end example

客户端:

@example
$ python TCPClient.py hello world with TCP
Sent:     hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent:     python is nice
Received: PYTHON IS NICE
@end example

@node socketserver UDPServer 示例,异步混合类,socketserver TCPServer 示例,示例<36>
@anchor{library/socketserver socketserver-udpserver-example}@anchor{2ee4}
@subsubsection @code{socketserver.UDPServer} 示例


以下是服务端:

@example
import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    """
    This class works similar to the TCP handler class, except that
    self.request consists of a pair of data and client socket, and since
    there is no connection the client address must be given explicitly
    when sending data back via sendto().
    """

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print("@{@} wrote:".format(self.client_address[0]))
        print(data)
        socket.sendto(data.upper(), self.client_address)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
        server.serve_forever()
@end example

以下是客户端:

@example
import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")

print("Sent:     @{@}".format(data))
print("Received: @{@}".format(received))
@end example

这个示例程序的输出应该是与 TCP 服务器示例相一致的。

@node 异步混合类,,socketserver UDPServer 示例,示例<36>
@anchor{library/socketserver asynchronous-mixins}@anchor{2ee5}
@subsubsection 异步混合类


要构建异步处理句柄，请使用 @ref{4e5,,ThreadingMixIn} 和 @ref{4e4,,ForkingMixIn} 类。

@ref{4e5,,ThreadingMixIn} 类的示例:

@example
import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("@{@}: @{@}".format(cur_thread.name, data), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((ip, port))
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: @{@}".format(response))

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    with server:
        ip, port = server.server_address

        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        print("Server loop running in thread:", server_thread.name)

        client(ip, port, "Hello World 1")
        client(ip, port, "Hello World 2")
        client(ip, port, "Hello World 3")

        server.shutdown()
@end example

这个示例程序的输出应该是像这样的:

@example
$ python ThreadedTCPServer.py
Server loop running in thread: Thread-1
Received: Thread-2: Hello World 1
Received: Thread-3: Hello World 2
Received: Thread-4: Hello World 3
@end example

@ref{4e4,,ForkingMixIn} 类的使用方式是相同的，区别在于服务器将为每个请求产生一个新的进程。 仅在支持 @ref{a4b,,fork()} 的 POSIX 系统平台上可用。

@node http server --- HTTP 服务器,http cookies --- HTTP状态管理,socketserver --- 用于网络服务器的框架,互联网协议和支持
@anchor{library/http server doc}@anchor{2ee6}@anchor{library/http server http-server-http-servers}@anchor{2ee7}@anchor{library/http server module-http server}@anchor{96}
@subsection @code{http.server} --- HTTP 服务器


@geindex http.server (模块)

@strong{源代码：} Lib/http/server.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/http/server.py}

@geindex WWW; server
@geindex HTTP; protocol
@geindex URL
@geindex httpd


__________________________________________________________________


这个模块定义了实现 HTTP 服务器（ Web 服务器）的类。

@cartouche
@quotation 警告 
@ref{96,,http.server} is not recommended for production. It only implements
@ref{2ee8,,basic security checks}.
@end quotation
@end cartouche

@ref{2d09,,HTTPServer} 是 @ref{2ec0,,socketserver.TCPServer} 的一个子类。它会创建和侦听 HTTP 套接字，并将请求调度给处理程序。用于创建和运行服务器的代码看起来像这样：

@example
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('@w{'}, 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()
@end example

@geindex HTTPServer (http.server 中的类)
@anchor{library/http server http server HTTPServer}@anchor{2d09}
@deffn {类} http.server.HTTPServer (server_address, RequestHandlerClass)

该类基于 @ref{2ec0,,TCPServer} 类，并会将服务器地址存入名为 @code{server_name} 和 @code{server_port} 的实例变量中。服务器可被处理程序通过 @code{server} 实例变量访问。
@end deffn

@geindex ThreadingHTTPServer (http.server 中的类)
@anchor{library/http server http server ThreadingHTTPServer}@anchor{4a5}
@deffn {类} http.server.ThreadingHTTPServer (server_address, RequestHandlerClass)

这个类与 HTTPServer 相似，但会通过使用 @ref{4e5,,ThreadingMixIn} 来以线程处理请求。 这适用于处理 Web 浏览器预开启套接字，以便 @ref{2d09,,HTTPServer} 无限期地执行等待。


3.7 新版功能.

@end deffn

@ref{2d09,,HTTPServer} 和 @ref{4a5,,ThreadingHTTPServer} 必须在实例化时给定一个 @emph{RequestHandlerClass}，此模块提供了该对象的三种不同形式:

@geindex BaseHTTPRequestHandler (http.server 中的类)
@anchor{library/http server http server BaseHTTPRequestHandler}@anchor{af5}
@deffn {类} http.server.BaseHTTPRequestHandler (request, client_address, server)

这个类用于处理到达服务器的 HTTP 请求。 它本身无法响应任何实际的 HTTP 请求；它必须被子类化以处理每个请求方法（例如 GET 或 POST）。 @ref{af5,,BaseHTTPRequestHandler} 提供了许多供子类使用的类和实例变量以及方法。

这个处理程序将解析请求和标头，然后调用特定请求类型对应的方法。 方法名称将根据请求来构造。 例如，对于请求方法 @code{SPAM}，将不带参数地调用 @code{do_SPAM()} 方法。 所有相关信息会被保存在该处理程序的实际变量中。 子类不需要重载或扩展 @ref{e2b,,__init__()} 方法。

@ref{af5,,BaseHTTPRequestHandler} 具有下列实例变量:

@geindex client_address (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler client_address}@anchor{2ee9}
@deffn {属性} client_address

包含 @code{(host, port)} 形式的指向客户端地址的元组。
@end deffn

@geindex server (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler server}@anchor{2eea}
@deffn {属性} server

包含服务器实例。
@end deffn

@geindex close_connection (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler close_connection}@anchor{2eeb}
@deffn {属性} close_connection

应当在 @ref{2eec,,handle_one_request()} 返回之前设定的布尔值，指明是否要期待另一个请求，还是应当关闭连接。
@end deffn

@geindex requestline (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler requestline}@anchor{2eed}
@deffn {属性} requestline

包含 HTTP 请求行的字符串表示。 末尾的 CRLF 会被去除。 该属性应当由 @ref{2eec,,handle_one_request()} 来设定。 如果无有效请求行被处理，则它应当被设为空字符串。
@end deffn

@geindex command (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler command}@anchor{2eee}
@deffn {属性} command

包含具体的命令（请求类型）。 例如 @code{'GET'}。
@end deffn

@geindex path (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler path}@anchor{2eef}
@deffn {属性} path

包含请求路径。如果URL的查询部分存在， @code{path} 会包含这个查询部分。使用 
@geindex RFC; RFC 3986
RFC 3986@footnote{https://tools.ietf.org/html/rfc3986.html} 的术语来说，在这里， @code{path} 包含 @code{hier-part} 和 @code{query} 。
@end deffn

@geindex request_version (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler request_version}@anchor{2ef0}
@deffn {属性} request_version

包含请求的版本字符串。 例如 @code{'HTTP/1.0'}。
@end deffn

@geindex headers (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler headers}@anchor{2dee}
@deffn {属性} headers

存放由 @ref{2ef1,,MessageClass} 类变量所指定的类的实例。 该实例会解析并管理 HTTP 请求中的标头。 @ref{93,,http.client} 中的 @ref{11bf,,parse_headers()} 函数将被用来解析标头并且它需要 HTTP 请求提供一个有效的 
@geindex RFC; RFC 2822
RFC 2822@footnote{https://tools.ietf.org/html/rfc2822.html} 风格的标头。
@end deffn

@geindex rfile (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler rfile}@anchor{2ef2}
@deffn {属性} rfile

一个 @ref{689,,io.BufferedIOBase} 输入流，准备从可选的输入数据的开头进行读取。
@end deffn

@geindex wfile (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler wfile}@anchor{2ef3}
@deffn {属性} wfile

包含用于写入响应并发回给客户端的输出流。 在写入流时必须正确遵守 HTTP 协议以便成功地实现与 HTTP 客户端的互操作。


在 3.6 版更改: 这是一个 @ref{689,,io.BufferedIOBase} 流。

@end deffn

@ref{af5,,BaseHTTPRequestHandler} 具有下列属性：

@geindex server_version (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler server_version}@anchor{2ef4}
@deffn {属性} server_version

指定服务器软件版本。 你可能会想要重载该属性。 该属性的格式为多个以空格分隔的字符串，其中每个字符串的形式为 name[/version]。 例如 @code{'BaseHTTP/0.2'}。
@end deffn

@geindex sys_version (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler sys_version}@anchor{2ef5}
@deffn {属性} sys_version

包含 Python 系统版本，采用 @ref{2ef6,,version_string} 方法和 @ref{2ef4,,server_version} 类变量所支持的形式。 例如 @code{'Python/1.4'}。
@end deffn

@geindex error_message_format (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler error_message_format}@anchor{2ef7}
@deffn {属性} error_message_format

指定应当被 @ref{950,,send_error()} 方法用来构建发给客户端的错误响应的格式字符串。 该字符串应使用来自 @ref{2ddb,,responses} 的变量根据传给 @ref{950,,send_error()} 的状态码来填充默认值。
@end deffn

@geindex error_content_type (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler error_content_type}@anchor{2ef8}
@deffn {属性} error_content_type

指定发送给客户端的错误响应的 Content-Type HTTP 标头。 默认值为 @code{'text/html'}。
@end deffn

@geindex protocol_version (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler protocol_version}@anchor{2ef9}
@deffn {属性} protocol_version

该属性指定在响应中使用的 HTTP 协议版本。 如果设为 @code{'HTTP/1.1'}，服务器将允许 HTTP 永久连接；但是，这样你的服务器 @emph{必须} 在发给客户端的所有响应中包括一个准确的 @code{Content-Length} 标头 (使用 @ref{2efa,,send_header()})。 为了向下兼容，该设置默认为 @code{'HTTP/1.0'}。
@end deffn

@geindex MessageClass (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler MessageClass}@anchor{2ef1}
@deffn {属性} MessageClass

指定一个 @ref{644,,email.message.Message} 这样的类来解析 HTTP 标头。 通常该属性不会被重载，其默认值为 @code{http.client.HTTPMessage}。
@end deffn

@geindex responses (http.server.BaseHTTPRequestHandler 属性)
@anchor{library/http server http server BaseHTTPRequestHandler responses}@anchor{2ddb}
@deffn {属性} responses

该属性包含一个整数错误代码与由短消息和长消息组成的二元组的映射。 例如，@code{@{code: (shortmessage, longmessage)@}}。 @emph{shortmessage} 通常是作为消息响应中的 @emph{message} 键，而 @emph{longmessage} 则是作为 @emph{explain} 键。 该属性会被 @ref{2efb,,send_response_only()} 和 @ref{950,,send_error()} 方法所使用。
@end deffn

@ref{af5,,BaseHTTPRequestHandler} 实例具有下列方法:

@geindex handle() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler handle}@anchor{2efc}
@deffn {方法} handle ()

调用 @ref{2eec,,handle_one_request()} 一次（或者如果启用了永久连接则为多次）来处理传入的 HTTP 请求。 你应该完全不需要重载它；而是要实现适当的 @code{do_*()} 方法。
@end deffn

@geindex handle_one_request() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler handle_one_request}@anchor{2eec}
@deffn {方法} handle_one_request ()

此方法将解析并将请求分配给适当的 @code{do_*()} 方法。 你应该完全不需要重载它。
@end deffn

@geindex handle_expect_100() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler handle_expect_100}@anchor{2efd}
@deffn {方法} handle_expect_100 ()

当一个符合 HTTP/1.1 标准的服务器收到 @code{Expect: 100-continue} 请求标头时它会以 @code{100 Continue} 加 @code{200 OK} 的标头作为响应。 如果服务器不希望客户端继续则可以重载此方法引发一个错误。 例如服务器可以选择发送 @code{417 Expectation Failed} 作为响应标头并 @code{return False}。


3.2 新版功能.

@end deffn

@geindex send_error() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler send_error}@anchor{950}
@deffn {方法} send_error (code, message=None, explain=None)

发送并记录回复给客户端的完整错误信息。 数字形式的 @emph{code} 指明 HTTP 错误代码，可选的 @emph{message} 为简短的易于人类阅读的错误描述。 @emph{explain} 参数可被用于提供更详细的错误信息；它将使用 @ref{2ef7,,error_message_format} 属性来进行格式化并在一组完整的标头之后作为响应体被发送。 @ref{2ddb,,responses} 属性存放了 @emph{message} 和 @emph{explain} 的默认值，它们将在未提供时被使用；对于未知代码两者的默认值均为字符串 @code{???}。 如果方法为 HEAD 或响应代码是下列值之一则响应体将为空: @code{1xx}, @code{204 No Content}, @code{205 Reset Content}, @code{304 Not Modified}。


在 3.4 版更改: 错误响应包括一个 Content-Length 标头。 增加了 @emph{explain} 参数。

@end deffn

@geindex send_response() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler send_response}@anchor{2efe}
@deffn {方法} send_response (code, message=None)

将一个响应标头添加到标头缓冲区并记录被接受的请求。 HTTP 响应行会被写入到内部缓冲区，后面是 @emph{Server} 和 @emph{Date} 标头。 这两个标头的值将分别通过 @ref{2ef6,,version_string()} 和 @ref{2eff,,date_time_string()} 方法获取。 如果服务器不打算使用 @ref{2efa,,send_header()} 方法发送任何其他标头，则 @ref{2efe,,send_response()} 后面应该跟一个 @ref{af6,,end_headers()} 调用。


在 3.3 版更改: 标头会被存储到内部缓冲区并且需要显式地调用 @ref{af6,,end_headers()}。

@end deffn

@geindex send_header() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler send_header}@anchor{2efa}
@deffn {方法} send_header (keyword, value)

将 HTTP 标头添加到内部缓冲区，它将在 @ref{af6,,end_headers()} 或 @ref{af7,,flush_headers()} 被发起调用时写入输出流。 @emph{keyword} 应当指定标头关键字，并以 @emph{value} 指定其值。 请注意，在 send_header 调用结束之后，必须调用 @ref{af6,,end_headers()} 以便完成操作。


在 3.2 版更改: 标头将被存入内部缓冲区。

@end deffn

@geindex send_response_only() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler send_response_only}@anchor{2efb}
@deffn {方法} send_response_only (code, message=None)

只发送响应标头，用于当 @code{100 Continue} 响应被服务器发送给客户端的场合。 标头不会被缓冲而是直接发送到输出流。 如果未指定 @emph{message}，则会发送与响应 @emph{code}  相对应的 HTTP 消息。


3.2 新版功能.

@end deffn

@geindex end_headers() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler end_headers}@anchor{af6}
@deffn {方法} end_headers ()

将一个空行（指明响应中 HTTP 标头的结束）添加到标头缓冲区并调用 @ref{af7,,flush_headers()}。


在 3.2 版更改: 已缓冲的标头会被写入到输出流。

@end deffn

@geindex flush_headers() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler flush_headers}@anchor{af7}
@deffn {方法} flush_headers ()

最终将标头发送到输出流并清空内部标头缓冲区。


3.3 新版功能.

@end deffn

@geindex log_request() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler log_request}@anchor{2f00}
@deffn {方法} log_request (code='-', size='-')

记录一次被接受（成功）的请求。 @emph{code} 应当指定与请求相关联的 HTTP 代码。 如果请求的大小可用，则它应当作为 @emph{size} 形参传入。
@end deffn

@geindex log_error() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler log_error}@anchor{2f01}
@deffn {方法} log_error (...)

当请求无法完成时记录一次错误。 默认情况下，它会将消息传给 @ref{2f02,,log_message()}，因此它接受同样的参数 (@emph{format} 和一些额外的值)。
@end deffn

@geindex log_message() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler log_message}@anchor{2f02}
@deffn {方法} log_message (format, ...)

将任意一条消息记录到 @code{sys.stderr}。 此方法通常会被重载以创建自定义的错误日志记录机制。 @emph{format} 参数是标准 printf 风格的格式字符串，其中会将传给 @ref{2f02,,log_message()} 的额外参数用作格式化操作的输入。 每条消息日志记录的开头都会加上客户端 IP 地址和当前日期时间。
@end deffn

@geindex version_string() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler version_string}@anchor{2ef6}
@deffn {方法} version_string ()

返回服务器软件的版本字符串。 该值为 @ref{2ef4,,server_version} 与 @ref{2ef5,,sys_version} 属性的组合。
@end deffn

@geindex date_time_string() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler date_time_string}@anchor{2eff}
@deffn {方法} date_time_string (timestamp=None)

返回由 @emph{timestamp} 所给定的日期和时间（参数应为 @code{None} 或为 @ref{436,,time.time()} 所返回的格式），格式化为一个消息标头。 如果省略 @emph{timestamp}，则会使用当前日期和时间。

结果看起来像 @code{'Sun, 06 Nov 1994 08:49:37 GMT'}。
@end deffn

@geindex log_date_time_string() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler log_date_time_string}@anchor{2f03}
@deffn {方法} log_date_time_string ()

返回当前的日期和时间，为日志格式化
@end deffn

@geindex address_string() (http.server.BaseHTTPRequestHandler 方法)
@anchor{library/http server http server BaseHTTPRequestHandler address_string}@anchor{2f04}
@deffn {方法} address_string ()

返回客户端的地址


在 3.3 版更改: 在之前版本中，会执行一次名称查找。 为了避免名称解析的时延，现在将总是返回 IP 地址。

@end deffn
@end deffn

@geindex SimpleHTTPRequestHandler (http.server 中的类)
@anchor{library/http server http server SimpleHTTPRequestHandler}@anchor{4a4}
@deffn {类} http.server.SimpleHTTPRequestHandler (request, client_address, server, directory=None)

这个类会为目录 @emph{directory} 及以下的文件提供发布服务，或者如果未提供 @emph{directory} 则为当前目录，直接将目录结构映射到 HTTP 请求。


3.7 新版功能: @emph{directory} 形参。



在 3.9 版更改: @emph{directory} 形参接受一个 @ref{47b,,path-like object}。


诸如解析请求之类的大量工作都是由基类 @ref{af5,,BaseHTTPRequestHandler} 完成的。本类实现了 @ref{2f05,,do_GET()} 和 @ref{2f06,,do_HEAD()} 函数。

以下是 @ref{4a4,,SimpleHTTPRequestHandler} 的类属性。

@geindex server_version (http.server.SimpleHTTPRequestHandler 属性)
@anchor{library/http server http server SimpleHTTPRequestHandler server_version}@anchor{2f07}
@deffn {属性} server_version

这会是 @code{"SimpleHTTP/" + __version__}，其中 @code{__version__} 定义于模块级别。
@end deffn

@geindex extensions_map (http.server.SimpleHTTPRequestHandler 属性)
@anchor{library/http server http server SimpleHTTPRequestHandler extensions_map}@anchor{2f08}
@deffn {属性} extensions_map

将后缀映射为 MIME 类型的字典，其中包含了覆盖系统默认值的自定义映射关系。不区分大小写，因此字典键只应为小写值。


在 3.9 版更改: 此字典不再填充默认的系统映射，而只包含覆盖值。

@end deffn

@ref{4a4,,SimpleHTTPRequestHandler} 类定义了以下方法：

@geindex do_HEAD() (http.server.SimpleHTTPRequestHandler 方法)
@anchor{library/http server http server SimpleHTTPRequestHandler do_HEAD}@anchor{2f06}
@deffn {方法} do_HEAD ()

本方法为 @code{'HEAD'} 请求提供服务：它将发送等同于 @code{GET} 请求的头文件。关于合法头部信息的更完整解释，请参阅 @ref{2f05,,do_GET()} 方法。
@end deffn

@geindex do_GET() (http.server.SimpleHTTPRequestHandler 方法)
@anchor{library/http server http server SimpleHTTPRequestHandler do_GET}@anchor{2f05}
@deffn {方法} do_GET ()

这一请求通过把其解释为当前工作目录的相对路径来映射到本地文件

如果请求被映射到目录，则会依次检查该目录是否存在 @code{index.html} 或 @code{index.htm} 文件。若存在则返回文件内容；否则会调用  @code{list_directory()} 方法生成目录列表。本方法将利用 @ref{b25,,os.listdir()} 扫描目录，如果 @ref{b25,,listdir()} 失败，则返回 @code{404} 出错应答。

如果请求被映射到文件，则会打开该文件。 打开文件时的任何 @ref{30b,,OSError} 异常都会被映射为 @code{404}, @code{'File not found'} 错误。 如果请求中带有 @code{'If-Modified-Since'} 标头，而在此时间点之后文件未作修改，则会发送 @code{304}, @code{'Not Modified'} 的响应。 否则会调用 @code{guess_type()} 方法猜测内容的类型，该方法会反过来用到 @emph{extensions_map} 变量，并返回文件内容。

将会输出 @code{'Content-type:'} 头部信息，带上猜出的内容类型，然后是 @code{'Content-Length:'} 头部信息，带有文件的大小，以及 @code{'Last-Modified:'} 头部信息，带有文件的修改时间。

后面是一个空行，标志着头部信息的结束，然后输出文件的内容。如果文件的 MIME 类型以 @code{text/} 开头，文件将以文本模式打开；否则将使用二进制模式。

用法示例请参阅 @ref{96,,http.server} 模块中的 @ref{105,,test()} 函数的实现。


在 3.7 版更改: 为 @code{'If-Modified-Since'} 头部信息提供支持。

@end deffn
@end deffn

@ref{4a4,,SimpleHTTPRequestHandler} 类的用法可如下所示，以便创建一个非常简单的 Web 服务，为相对于当前目录的文件提供服务：

@example
import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
@end example
@anchor{library/http server http-server-cli}@anchor{951}
@ref{96,,http.server} 也可以使用解释器的 @ref{44c,,-m} 参数直接调用。 与前面的例子类似，这将提供相对于当前目录的文件:

@example
python -m http.server
@end example

服务器默认监听端口为8000。可以通过传递所需的端口号作为参数来覆盖默认值:

@example
python -m http.server 9000
@end example

默认情况下，服务器将自己绑定到所有接口。 选项 @cite{-b/--bind} 指定了一个特定的地址，它应该与之绑定。 IPv4 和 IPv6 地址都被支持。例如，下面的命令使服务器只绑定到 localhost:

@example
python -m http.server --bind 127.0.0.1
@end example


3.4 新版功能: 引入了 @code{--bind} 参数。



3.8 新版功能: 为了支持 IPv6 改进了 @code{--bind} 参数。


默认情况下，服务器使用当前目录。选项 @code{-d/--directory} 指定了一个它应该提供文件的目录。例如，下面的命令使用一个特定的目录:

@example
python -m http.server --directory /tmp/
@end example


3.7 新版功能: @code{--directory} 参数被引入。


@geindex CGIHTTPRequestHandler (http.server 中的类)
@anchor{library/http server http server CGIHTTPRequestHandler}@anchor{2f09}
@deffn {类} http.server.CGIHTTPRequestHandler (request, client_address, server)

该类可为当前及以下目录中的文件或输出 CGI 脚本提供服务。注意，把 HTTP 分层结构映射到本地目录结构，这与 @ref{4a4,,SimpleHTTPRequestHandler} 完全一样。

@cartouche
@quotation 注解 
由 @ref{2f09,,CGIHTTPRequestHandler} 类运行的 CGI 脚本不能进行重定向操作（HTTP 代码302），因为在执行 CGI 脚本之前会发送代码 200（接下来就输出脚本）。这样状态码就冲突了。
@end quotation
@end cartouche

然而，如果这个类猜测它是一个 CGI 脚本，那么就会运行该 CGI 脚本，而不是作为文件提供出去。 只会识别基于目录的 CGI —— 另有一种常用的服务器设置，即标识 CGI 脚本是通过特殊的扩展名。

如果请求指向 @code{cgi_directories} 以下的路径，@code{do_GET()} 和 @code{do_HEAD()} 函数已作修改，不是给出文件，而是运行 CGI 脚本并输出结果。

@ref{2f09,,CGIHTTPRequestHandler} 定义了以下数据成员：

@geindex cgi_directories (http.server.CGIHTTPRequestHandler 属性)
@anchor{library/http server http server CGIHTTPRequestHandler cgi_directories}@anchor{2f0a}
@deffn {属性} cgi_directories

默认为 @code{['/cgi-bin', '/htbin']}，视作 CGI 脚本所在目录。
@end deffn

@ref{2f09,,CGIHTTPRequestHandler} 定义了以下方法：

@geindex do_POST() (http.server.CGIHTTPRequestHandler 方法)
@anchor{library/http server http server CGIHTTPRequestHandler do_POST}@anchor{2f0b}
@deffn {方法} do_POST ()

本方法服务于  @code{'POST'} 请求，仅用于 CGI 脚本。如果试图向非 CGI 网址发送 POST 请求，则会输出错误 501：Can only POST to CGI scripts"。
@end deffn

请注意，为了保证安全性，CGI 脚本将以用户 nobody 的 UID 运行。CGI 脚本运行错误将被转换为错误 403。
@end deffn

通过在命令行传入 @code{--cgi} 参数，可以启用  @ref{2f09,,CGIHTTPRequestHandler} ：

@example
python -m http.server --cgi
@end example

@menu
* 安全考量: 安全考量<4>. 

@end menu

@node 安全考量<4>,,,http server --- HTTP 服务器
@anchor{library/http server http-server-security}@anchor{2ee8}@anchor{library/http server security-considerations}@anchor{2f0c}
@subsubsection 安全考量


@geindex http.server; security

@ref{4a4,,SimpleHTTPRequestHandler} will follow symbolic links when handling
requests, this makes it possible for files outside of the specified directory
to be served.

Earlier versions of Python did not scrub control characters from the
log messages emitted to stderr from @code{python -m http.server} or the
default @ref{af5,,BaseHTTPRequestHandler} @code{.log_message}
implementation. This could allow remote clients connecting to your
server to send nefarious control codes to your terminal.


3.9.16 新版功能: scrubbing control characters from log messages


@node http cookies --- HTTP状态管理,http cookiejar —— HTTP 客户端的 Cookie 处理,http server --- HTTP 服务器,互联网协议和支持
@anchor{library/http cookies doc}@anchor{2f0d}@anchor{library/http cookies http-cookies-http-state-management}@anchor{2f0e}@anchor{library/http cookies module-http cookies}@anchor{95}
@subsection @code{http.cookies} --- HTTP状态管理


@geindex http.cookies (模块)

@strong{源代码:} Lib/http/cookies.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/http/cookies.py}


__________________________________________________________________


@ref{95,,http.cookies} 模块定义的类将 cookie 的概念抽象了出来，这是一种 HTTP 状态的管理机制。它既支持简单的纯字符串形式的 cookie，也为任何可序列化数据类型的 cookie 提供抽象。

以前，该模块严格套用 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 和 
@geindex RFC; RFC 2068
RFC 2068@footnote{https://tools.ietf.org/html/rfc2068.html} 规范中描述的解析规则。后来人们发现，MSIE 3.0 并不遵循这些规范中的字符规则，而且目前许多浏览器和服务器在处理 cookie 时也放宽了解析规则。 因此，这里用到的解析规则没有那么严格。

字符集 @ref{d2c,,string.ascii_letters} 、 @ref{18b8,,string.digits} 和 @code{!#$%&'*+-.^_`|~:}  给出了本模块允许出现在 cookie 名称中的有效字符集（如 @ref{591,,key}）。


在 3.3 版更改: “:”字符可用于有效的 cookie 名称。


@cartouche
@quotation 注解 
当遇到无效 cookie 时会触发 @ref{2f0f,,CookieError}，所以若 cookie 数据来自浏览器，一定要做好应对无效数据的准备，并在解析时捕获 @ref{2f0f,,CookieError}。
@end quotation
@end cartouche

@geindex CookieError
@anchor{library/http cookies http cookies CookieError}@anchor{2f0f}
@deffn {例外} http.cookies.CookieError

出现异常的原因，可能是不符合 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} ：属性不正确、@code{Set-Cookie} 头部信息不正确等等。
@end deffn

@geindex BaseCookie (http.cookies 中的类)
@anchor{library/http cookies http cookies BaseCookie}@anchor{2f10}
@deffn {类} http.cookies.BaseCookie ([input])

类似字典的对象，字典键为字符串，字典值是 @ref{590,,Morsel} 实例。请注意，在将键值关联时，首先会把值转换为包含键和值的 @ref{590,,Morsel} 对象。

若给出 @emph{input} ，将会传给 @ref{2f11,,load()} 方法。
@end deffn

@geindex SimpleCookie (http.cookies 中的类)
@anchor{library/http cookies http cookies SimpleCookie}@anchor{11b7}
@deffn {类} http.cookies.SimpleCookie ([input])

该类派生于 @ref{2f10,,BaseCookie}，并覆盖了 @code{value_decode()} 和 @code{value_encode()} 方法。SimpleCookie 允许用字符串作为 cookie 值。在设置值时，SimpleCookie 将调用内置的 @ref{206,,str()} 将其转换为字符串。从 HTTP 接收到的值将作为字符串保存。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{94,,http.cookiejar} 模块

处理网络 @emph{客户端} 的 HTTP cookie。 @ref{94,,http.cookiejar} 和 @ref{95,,http.cookies} 模块相互没有依赖关系。

@geindex RFC; RFC 2109

@item RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} - HTTP状态管理机制

这是本模块实现的状态管理规范。
@end table


@menu
* Cookie 对象:: 
* Morsel 对象:: 
* 示例: 示例<37>. 

@end menu

@node Cookie 对象,Morsel 对象,,http cookies --- HTTP状态管理
@anchor{library/http cookies cookie-objects}@anchor{2f12}@anchor{library/http cookies id1}@anchor{2f13}
@subsubsection Cookie 对象


@geindex value_decode() (http.cookies.BaseCookie 方法)
@anchor{library/http cookies http cookies BaseCookie value_decode}@anchor{2f14}
@deffn {方法} BaseCookie.value_decode (val)

由字符串返回元组 @code{(real_value, coded_value)}。@code{real_value} 可为任意类型。@ref{2f10,,BaseCookie} 中的此方法未实现任何解码工作——只为能被子类重写。
@end deffn

@geindex value_encode() (http.cookies.BaseCookie 方法)
@anchor{library/http cookies http cookies BaseCookie value_encode}@anchor{2f15}
@deffn {方法} BaseCookie.value_encode (val)

返回元组 @code{(real_value, coded_value)}。@emph{val} 可为任意类型，@code{coded_value} 则会转换为字符串。 @ref{2f10,,BaseCookie} 中的此方法未实现任何编码工作——只为能被子类重写。

通常在 @emph{value_decode} 的取值范围内，@ref{2f15,,value_encode()} 和 @ref{2f14,,value_decode()} 应为可互逆操作。
@end deffn

@geindex output() (http.cookies.BaseCookie 方法)
@anchor{library/http cookies http cookies BaseCookie output}@anchor{2f16}
@deffn {方法} BaseCookie.output (attrs=None, header='Set-Cookie:', sep='\r\n')

返回可作为 HTTP 标头信息发送的字符串表示。 @emph{attrs} 和 @emph{header} 会传给每个 @ref{590,,Morsel} 的 @ref{2f16,,output()} 方法。 @emph{sep} 用来将标头连接在一起，默认为 @code{'\r\n'} (CRLF) 组合。
@end deffn

@geindex js_output() (http.cookies.BaseCookie 方法)
@anchor{library/http cookies http cookies BaseCookie js_output}@anchor{2f17}
@deffn {方法} BaseCookie.js_output (attrs=None)

返回一段可供嵌入的 JavaScript 代码，若在支持 JavaScript 的浏览器上运行，其作用如同发送 HTTP 头部信息一样。

@emph{attrs} 的含义与 @ref{2f16,,output()} 的相同。
@end deffn

@geindex load() (http.cookies.BaseCookie 方法)
@anchor{library/http cookies http cookies BaseCookie load}@anchor{2f11}
@deffn {方法} BaseCookie.load (rawdata)

若 @emph{rawdata} 为字符串，则会作为 @code{HTTP_COOKIE} 进行解析，并将找到的值添加为 @ref{590,,Morsel}。 如果是字典值，则等价于:

@example
for k, v in rawdata.items():
    cookie[k] = v
@end example
@end deffn

@node Morsel 对象,示例<37>,Cookie 对象,http cookies --- HTTP状态管理
@anchor{library/http cookies id2}@anchor{2f18}@anchor{library/http cookies morsel-objects}@anchor{2f19}
@subsubsection Morsel 对象


@geindex Morsel (http.cookies 中的类)
@anchor{library/http cookies http cookies Morsel}@anchor{590}
@deffn {类} http.cookies.Morsel

对键/值对的抽象，带有 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 的部分属性。

morsel 对象类似于字典，键的组成是常量——均为有效的 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 属性，包括：


@itemize *

@item 
@code{expires}

@item 
@code{path}

@item 
@code{comment}

@item 
@code{domain}

@item 
@code{max-age}

@item 
@code{secure}

@item 
@code{version}

@item 
@code{httponly}

@item 
@code{samesite}
@end itemize

@code{httponly} 属性指明了该 cookie 仅在 HTTP 请求中传输，且不能通过 JavaScript 访问。这是为了减轻某些跨站脚本攻击的危害。

@code{samesite} 属性指明了浏览器不得与跨站请求一起发送该 cookie。这有助于减轻 CSRF 攻击的危害。此属性的有效值为 “Strict”和“Lax”。

键不区分大小写，默认值为 @code{'@w{'}}。


在 3.5 版更改: 现在，@code{__eq__()} 会同时考虑 @ref{591,,key} 和 @ref{592,,value} 。



在 3.7 版更改: Attributes @ref{591,,key}, @ref{592,,value} and
@ref{593,,coded_value} are read-only.  Use @ref{594,,set()} for
setting them.



在 3.8 版更改: 增加对 @code{samesite} 属性的支持。

@end deffn

@geindex value (http.cookies.Morsel 属性)
@anchor{library/http cookies http cookies Morsel value}@anchor{592}
@deffn {属性} Morsel.value

Cookie的值。
@end deffn

@geindex coded_value (http.cookies.Morsel 属性)
@anchor{library/http cookies http cookies Morsel coded_value}@anchor{593}
@deffn {属性} Morsel.coded_value

编码后的 cookie 值——也即要发送的内容。
@end deffn

@geindex key (http.cookies.Morsel 属性)
@anchor{library/http cookies http cookies Morsel key}@anchor{591}
@deffn {属性} Morsel.key

cookie 名称
@end deffn

@geindex set() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel set}@anchor{594}
@deffn {方法} Morsel.set (key, value, coded_value)

设置 @emph{key}、@emph{value} 和 @emph{coded_value} 属性。
@end deffn

@geindex isReservedKey() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel isReservedKey}@anchor{2f1a}
@deffn {方法} Morsel.isReservedKey (K)

@emph{K} 是否属于 @ref{590,,Morsel} 的键。
@end deffn

@geindex output() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel output}@anchor{2f1b}
@deffn {方法} Morsel.output (attrs=None, header='Set-Cookie:')

返回 morsel 的字符串形式，适用于作为 HTTP 头部信息进行发送。默认包含所有属性，除非给出 @emph{attrs} 属性列表。@emph{header} 默认为 @code{"Set-Cookie:"}。
@end deffn

@geindex js_output() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel js_output}@anchor{2f1c}
@deffn {方法} Morsel.js_output (attrs=None)

返回一段可供嵌入的 JavaScript 代码，若在支持 JavaScript 的浏览器上运行，其作用如同发送 HTTP 头部信息一样。

@emph{attrs} 的含义与 @ref{2f1b,,output()} 的相同。
@end deffn

@geindex OutputString() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel OutputString}@anchor{2f1d}
@deffn {方法} Morsel.OutputString (attrs=None)

返回 morsel 的字符串形式，不含 HTTP 或 JavaScript 数据。

@emph{attrs} 的含义与 @ref{2f1b,,output()} 的相同。
@end deffn

@geindex update() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel update}@anchor{8bb}
@deffn {方法} Morsel.update (values)

用字典 @emph{values} 中的值更新  morsel 字典中的值。若有 @emph{values} 字典中的键不是有效的 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 属性，则会触发错误。


在 3.5 版更改: 无效键会触发错误。

@end deffn

@geindex copy() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel copy}@anchor{8ba}
@deffn {方法} Morsel.copy (value)

返回 morsel 对象的浅表复制副本。


在 3.5 版更改: 返回一个 morsel 对象，而非字典。

@end deffn

@geindex setdefault() (http.cookies.Morsel 方法)
@anchor{library/http cookies http cookies Morsel setdefault}@anchor{2f1e}
@deffn {方法} Morsel.setdefault (key, value=None)

若 key 不是有效的 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 属性则触发错误，否则与 @ref{aa7,,dict.setdefault()} 相同。
@end deffn

@node 示例<37>,,Morsel 对象,http cookies --- HTTP状态管理
@anchor{library/http cookies cookie-example}@anchor{2f1f}@anchor{library/http cookies example}@anchor{2f20}
@subsubsection 示例


以下例子演示了 @ref{95,,http.cookies} 模块的用法。

@example
>>> from http import cookies
>>> C = cookies.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = cookies.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
>>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
>>> C = cookies.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
>>> C = cookies.SimpleCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = cookies.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven
@end example

@node http cookiejar —— HTTP 客户端的 Cookie 处理,xmlrpc --- XMLRPC 服务端与客户端模块,http cookies --- HTTP状态管理,互联网协议和支持
@anchor{library/http cookiejar doc}@anchor{2f21}@anchor{library/http cookiejar http-cookiejar-cookie-handling-for-http-clients}@anchor{2f22}@anchor{library/http cookiejar module-http cookiejar}@anchor{94}
@subsection @code{http.cookiejar} —— HTTP 客户端的 Cookie 处理


@geindex http.cookiejar (模块)

@strong{源代码：} Lib/http/cookiejar.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/http/cookiejar.py}


__________________________________________________________________


@ref{94,,http.cookiejar} 模块定义了用于自动处理 HTTP cookie 的类。这对访问需要小段数据 —— @emph{cookies} 的网站很有用，这些数据由 Web 服务器的 HTTP 响应在客户端计算机上设置，然后在以后的 HTTP 请求中返回给服务器。

常规的 Netscape Cookie 协议和 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 定义的协议都可以处理。RFC 2965 处理默认情况下处于关闭状态。 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookie 被解析为 Netscape cookie，随后根据有效的 'policy' 被视为 Netscape 或 RFC 2965 cookie。 请注意，Internet 上的大多数 cookie 是 Netscape cookie。 @ref{94,,http.cookiejar} 尝试遵循事实上的 Netscape cookie 协议（与原始 Netscape 规范中所设定的协议大不相同），包括注意 @code{max-age} 和 @code{port} RFC 2965 引入的 cookie 属性。

@cartouche
@quotation 注解 
在 @code{Set-Cookie} 和 @code{Set-Cookie2} 头中找到的各种命名参数通常指 @emph{attributes}。为了不与 Python 属性相混淆，模块文档使用 @emph{cookie-attribute} 代替。
@end quotation
@end cartouche

此模块定义了以下异常：

@geindex LoadError
@anchor{library/http cookiejar http cookiejar LoadError}@anchor{2f23}
@deffn {例外} http.cookiejar.LoadError

@ref{2f24,,FileCookieJar} 实例在从文件加载 cookies 出错时抛出这个异常。 @ref{2f23,,LoadError} 是 @ref{30b,,OSError} 的一个子类。


在 3.3 版更改: LoadError 成为 @ref{30b,,OSError} 的子类而不是 @ref{a7c,,IOError}。

@end deffn

提供了以下类：

@geindex CookieJar (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar CookieJar}@anchor{2d78}
@deffn {类} http.cookiejar.CookieJar (policy=None)

@emph{policy} 是实现了 @ref{2f25,,CookiePolicy} 接口的一个对象。

@ref{2d78,,CookieJar} 类储存 HTTP cookies。它从 HTTP 请求提取 cookies，并在 HTTP 响应中返回它们。 @ref{2d78,,CookieJar} 实例在必要时自动处理包含 cookie 的到期情况。子类还负责储存和从文件或数据库中查找 cookies。
@end deffn

@geindex FileCookieJar (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar FileCookieJar}@anchor{2f24}
@deffn {类} http.cookiejar.FileCookieJar (filename, delayload=None, policy=None)

@emph{policy} 是实现了 @ref{2f25,,CookiePolicy} 接口的一个对象。对于其他参数，参考相应属性的文档。

一个可以从硬盘中文件加载或保存 cookie 的 @ref{2d78,,CookieJar}。 Cookies @strong{不} 会在 @ref{2f26,,load()} 或 @ref{2f27,,revert()} 方法调用前从命名的文件中加载。子类的文档位于段落 @ref{2f28,,FileCookieJar 的子类及其与 Web 浏览器的协同}。


在 3.8 版更改: 文件名形参支持 @ref{47b,,path-like object}。

@end deffn

@geindex CookiePolicy (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar CookiePolicy}@anchor{2f25}
@deffn {类} http.cookiejar.CookiePolicy

此类负责确定是否应从服务器接受每个 cookie 或将其返回给服务器。
@end deffn

@geindex DefaultCookiePolicy (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy}@anchor{1172}
@deffn {类} http.cookiejar.DefaultCookiePolicy (blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=("https", "wss"))

构造参数只能以关键字参数传递，@emph{blocked_domains} 是一个我们既不会接受也不会返回 cookie 的域名序列。@emph{allowed_domains} 如果不是 @ref{204,,None}，则是仅有的我们会接受或返回的域名序列。@emph{secure_protocols} 是可以添加安全 cookies 的协议序列。默认将 @emph{https} 和 @emph{wss} （安全 WebSocket）考虑为安全协议。对于其他参数，参考 @ref{2f25,,CookiePolicy} 和 @ref{1172,,DefaultCookiePolicy} 对象的文档。

@ref{1172,,DefaultCookiePolicy} 实现了 Netscape 和 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} cookies 的标准接受 / 拒绝规则。 默认情况下，
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookies（即在 @code{Set-Cookie} 头中收到的 cookie-attribute 版本为 1 的 cookies ）将按照 RFC 2965 规则处理。 然而，如果 RFC 2965 的处理被关闭，或者  @ref{2f29,,rfc2109_as_netscape} 为 @code{True}，@ref{2f2a,,Cookie} 实例的 @code{version} 属性设置将被为 0， RFC 2109 cookies @ref{2d78,,CookieJar} 实例将 "降级" 为 Netscape cookies。 @ref{1172,,DefaultCookiePolicy} 也提供一些参数以允许一些策略微调。
@end deffn

@geindex Cookie (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar Cookie}@anchor{2f2a}
@deffn {类} http.cookiejar.Cookie

这个类代表 Netscape、
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} 和 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 的 cookie 。 我们不希望 @ref{94,,http.cookiejar} 的用户构建他们自己的 @ref{2f2a,,Cookie} 实例。 相反，如果有必要，请在一个  @ref{2d78,,CookieJar} 实例上调用 @code{make_cookies()} 。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{129,,urllib.request}

URL 打开带有自动的 cookie 处理。

@item 模块 @ref{95,,http.cookies}

HTTP cookie类，主要是对服务端代码有用。  @ref{94,,http.cookiejar} 和 @ref{95,,http.cookies} 模块不相互依赖。

@item @indicateurl{https://curl.se/rfc/cookie_spec.html}

原始 Netscape cookie 协议的规范。 虽然这仍然是主流协议，但所有主要浏览器（以及 @ref{94,,http.cookiejar} ）实现的 "Netscape cookie协议" 与`@w{`}cookie_spec.html`@w{`}中描述的协议仅有几分相似之处。

@geindex RFC; RFC 2109

@item RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} - HTTP状态管理机制

被 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 所取代。使用 @code{Set-Cookie} version=1 。

@geindex RFC; RFC 2965

@item RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} - HTTP状态管理机制

修正了错误的 Netscape 协议。 使用 @code{Set-Cookie2} 来代替 @code{Set-Cookie} 。 没有广泛被使用。

@item @indicateurl{http://kristol.org/cookie/errata.html}

未完成的:rfc:@cite{2965} 勘误表。
@end table

HTTP状态管理使用方法


@menu
* CookieJar 和 FileCookieJar 对象:: 
* FileCookieJar 的子类及其与 Web 浏览器的协同:: 
* CookiePolicy 对象:: 
* DefaultCookiePolicy 对象:: 
* Cookie 对象: Cookie 对象<2>. 
* 示例: 示例<38>. 

@end menu

@node CookieJar 和 FileCookieJar 对象,FileCookieJar 的子类及其与 Web 浏览器的协同,,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar cookie-jar-objects}@anchor{2f2b}@anchor{library/http cookiejar cookiejar-and-filecookiejar-objects}@anchor{2f2c}
@subsubsection CookieJar 和 FileCookieJar 对象


@ref{2d78,,CookieJar} 对象支持 @ref{11ba,,iterator} 协议，用于迭代包含的 @ref{2f2a,,Cookie} 对象。

@ref{2d78,,CookieJar} 有以下方法：

@geindex add_cookie_header() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar add_cookie_header}@anchor{2f2d}
@deffn {方法} CookieJar.add_cookie_header (request)

在 @emph{request} 中添加正确的 @code{Cookie} 头。

如果策略允许（即 @code{rfc2965} 和 @code{hide_cookie2} 属性在 @ref{2d78,,CookieJar} 的 @ref{2f25,,CookiePolicy} 实例中分别为 True 和 False ）， @code{Cookie2} 标头也会在适当时候添加。

如 @ref{129,,urllib.request} 所记载的， @emph{request} 对象（通常是一个 @ref{9e5,,urllib.request.Request} 实例）必须支持 @code{get_full_url()} , @code{get_host()}, @code{get_type()}, @code{unverifiable()}, @code{has_header()}, @code{get_header()}, @code{header_items()}, @code{add_unredirected_header()} 和 @code{origin_req_host} 属性。


在 3.3 版更改: @emph{request} 对象需要 @code{origin_req_host} 属性。对已废弃的方法 @code{get_origin_req_host()} 的依赖已被移除。

@end deffn

@geindex extract_cookies() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar extract_cookies}@anchor{2f2e}
@deffn {方法} CookieJar.extract_cookies (response, request)

从HTTP @emph{response} 中提取 cookie，并在政策允许的情况下，将它们存储在 @ref{2d78,,CookieJar} 中。

@ref{2d78,,CookieJar} 将 在*response* 参数中寻找允许的 @code{Set-Cookie} 和 @code{Set-Cookie2} 头信息，并适当地存储cookies（须经 @ref{2f2f,,CookiePolicy.set_ok()} 方法批准）。

@emph{response} 对象（通常是调用 @ref{885,,urllib.request.urlopen()} 或类似方法的结果）应该支持 @code{info()} 方法，它返回 @ref{644,,email.message.Message} 实例。

如 @ref{129,,urllib.request} 的文档所说，@emph{request} 对象（通常是一个 @ref{9e5,,urllib.request.Request} 实例）必须支持 @code{get_full_url()}, @code{get_host()}, @code{unverifiable()} 和 @code{origin_req_host} 属性。 该请求用于设置 cookie-attributes 的默认值，以及检查 cookie 是否允许被设置。


在 3.3 版更改: @emph{request} 对象需要 @code{origin_req_host} 属性。对已废弃的方法 @code{get_origin_req_host()} 的依赖已被移除。

@end deffn

@geindex set_policy() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar set_policy}@anchor{2f30}
@deffn {方法} CookieJar.set_policy (policy)

设置要使用的 @ref{2f25,,CookiePolicy} 实例。
@end deffn

@geindex make_cookies() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar make_cookies}@anchor{2f31}
@deffn {方法} CookieJar.make_cookies (response, request)

返回从 @emph{response} 对象中提取的 @ref{2f2a,,Cookie} 对象的序列。

关于 @emph{response} 和 @emph{request} 参数所需的接口，请参见 @ref{2f2e,,extract_cookies()} 的文档。
@end deffn

@geindex set_cookie_if_ok() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar set_cookie_if_ok}@anchor{2f32}
@deffn {方法} CookieJar.set_cookie_if_ok (cookie, request)

如果策略规定可以这样做，就设置一个 @ref{2f2a,,Cookie} 。
@end deffn

@geindex set_cookie() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar set_cookie}@anchor{2f33}
@deffn {方法} CookieJar.set_cookie (cookie)

设置一个 @ref{2f2a,,Cookie}，不需要检查策略是否应该被设置。
@end deffn

@geindex clear() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar clear}@anchor{2f34}
@deffn {方法} CookieJar.clear ([domain[, path[, name]]])

清除一些cookie。

如果调用时没有参数，则清除所有的cookie。 如果给定一个参数，只有属于该 @emph{domain} 的cookies将被删除。如果给定两个参数，那么属于指定的 @emph{domain} 和 URL @emph{path} 的cookie将被删除。 如果给定三个参数，那么属于指定的 @emph{domain} 、@emph{path} 和 @emph{name} 的cookie将被删除

如果不存在匹配的 cookie，则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex clear_session_cookies() (http.cookiejar.CookieJar 方法)
@anchor{library/http cookiejar http cookiejar CookieJar clear_session_cookies}@anchor{2f35}
@deffn {方法} CookieJar.clear_session_cookies ()

丢弃所有session cookie。

丢弃所有 @code{discard} 属性为真值的已包含 cookie（通常是因为它们没有 @code{max-age} 或 @code{expires} cookie 属性，或者显式的 @code{discard} cookie 属性）。 对于交互式浏览器，会话的结束通常对应于关闭浏览器窗口。

请注意 @code{save()} 方法并不会保存会话的 cookie，除非你通过传入一个真值给 @emph{ignore_discard} 参数来提出明确的要求。
@end deffn

@ref{2f24,,FileCookieJar} 实现了下列附加方法:

@geindex save() (http.cookiejar.FileCookieJar 方法)
@anchor{library/http cookiejar http cookiejar FileCookieJar save}@anchor{2f36}
@deffn {方法} FileCookieJar.save (filename=None, ignore_discard=False, ignore_expires=False)

将 cookie 保存到文件。

基类会引发 @ref{70e,,NotImplementedError}。 子类可以继续不实现该方法。

@emph{filename} 为要用来保存 cookie 的文件名称。 如果未指定 @emph{filename}，则会使用 @code{self.filename} (该属性默认为传给构造器的值，如果有传入的话)；如果 @code{self.filename} 为 @ref{204,,None}，则会引发 @ref{16d,,ValueError}。

@emph{ignore_discard}: 即使设定了丢弃 cookie 仍然保存它们。 @emph{ignore_expires}: 即使 cookie 已超期仍然保存它们

文件如果已存在则会被覆盖，这将清除其所包含的全部 cookie。 已保存的 cookie 可以使用 @ref{2f26,,load()} 或 @ref{2f27,,revert()} 方法来恢复。
@end deffn

@geindex load() (http.cookiejar.FileCookieJar 方法)
@anchor{library/http cookiejar http cookiejar FileCookieJar load}@anchor{2f26}
@deffn {方法} FileCookieJar.load (filename=None, ignore_discard=False, ignore_expires=False)

从文件加载 cookie。

旧的 cookie 将被保留，除非是被新加载的 cookie 所覆盖。

其参数与 @ref{2f36,,save()} 的相同。

指定的文件必须为该类所能理解的格式，否则将引发 @ref{2f23,,LoadError}。 也可能会引发 @ref{30b,,OSError}，例如当文件不存在的时候。


在 3.3 版更改: 过去触发的 @ref{a7c,,IOError}，现在是 @ref{30b,,OSError} 的别名。

@end deffn

@geindex revert() (http.cookiejar.FileCookieJar 方法)
@anchor{library/http cookiejar http cookiejar FileCookieJar revert}@anchor{2f27}
@deffn {方法} FileCookieJar.revert (filename=None, ignore_discard=False, ignore_expires=False)

清除所有 cookie 并从保存的文件重新加载 cookie。

@ref{2f27,,revert()} 可以引发与 @ref{2f26,,load()} 相同的异常。 如果执行失败，对象的状态将不会被改变。
@end deffn

@ref{2f24,,FileCookieJar} 实例具有下列公有属性:

@geindex filename (http.cookiejar.FileCookieJar 属性)
@anchor{library/http cookiejar http cookiejar FileCookieJar filename}@anchor{2f37}
@deffn {属性} FileCookieJar.filename

默认的保存 cookie 的文件的文件名。 该属性可以被赋值。
@end deffn

@geindex delayload (http.cookiejar.FileCookieJar 属性)
@anchor{library/http cookiejar http cookiejar FileCookieJar delayload}@anchor{2f38}
@deffn {属性} FileCookieJar.delayload

如为真值，则惰性地从磁盘加载 cookie。 该属性不应当被赋值。 这只是一个提示，因为它只会影响性能，而不会影响行为（除非磁盘中的 cookie 被改变了）。 @ref{2d78,,CookieJar} 对象可能会忽略它。 任何包括在标准库中的 @ref{2f24,,FileCookieJar} 类都不会惰性地加载 cookie。
@end deffn

@node FileCookieJar 的子类及其与 Web 浏览器的协同,CookiePolicy 对象,CookieJar 和 FileCookieJar 对象,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar file-cookie-jar-classes}@anchor{2f28}@anchor{library/http cookiejar filecookiejar-subclasses-and-co-operation-with-web-browsers}@anchor{2f39}
@subsubsection FileCookieJar 的子类及其与 Web 浏览器的协同


提供了以下 @ref{2d78,,CookieJar} 子类用于读取和写入。

@geindex MozillaCookieJar (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar MozillaCookieJar}@anchor{2f3a}
@deffn {类} http.cookiejar.MozillaCookieJar (filename, delayload=None, policy=None)

一个能够以 Mozilla @code{cookies.txt} 文件格式（该格式也被 Lynx 和 Netscape 浏览器所使用）从磁盘加载和存储 cookie 的 @ref{2f24,,FileCookieJar}。

@cartouche
@quotation 注解 
这会丢失有关 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} cookie 的信息，以及有关较新或非标准的 cookie 属性例如 @code{port}。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
在存储之前备份你的 cookie，如果你的 cookie 丢失/损坏会造成麻烦的话（有一些微妙的因素可能导致文件在加载/保存的往返过程中发生细微的变化）。
@end quotation
@end cartouche

还要注意在 Mozilla 运行期间保存的 cookie 将可能被 Mozilla 清除。
@end deffn

@geindex LWPCookieJar (http.cookiejar 中的类)
@anchor{library/http cookiejar http cookiejar LWPCookieJar}@anchor{2f3b}
@deffn {类} http.cookiejar.LWPCookieJar (filename, delayload=None, policy=None)

一个能够以 libwww-perl 库的 @code{Set-Cookie3} 文件格式从磁盘加载和存储 cookie 的 @ref{2f24,,FileCookieJar}。 这适用于当你想以人类可读的文件来保存 cookie 的情况。


在 3.8 版更改: 文件名形参支持 @ref{47b,,path-like object}。

@end deffn

@node CookiePolicy 对象,DefaultCookiePolicy 对象,FileCookieJar 的子类及其与 Web 浏览器的协同,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar cookie-policy-objects}@anchor{2f3c}@anchor{library/http cookiejar cookiepolicy-objects}@anchor{2f3d}
@subsubsection CookiePolicy 对象


实现了 @ref{2f25,,CookiePolicy} 接口的对象具有下列方法:

@geindex set_ok() (http.cookiejar.CookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar CookiePolicy set_ok}@anchor{2f2f}
@deffn {方法} CookiePolicy.set_ok (cookie, request)

返回指明是否应当从服务器接受 cookie 的布尔值。

@emph{cookie} 是一个 @ref{2f2a,,Cookie} 实例。 @emph{request} 是一个实现了由 @ref{2f2e,,CookieJar.extract_cookies()} 的文档所定义的接口的对象。
@end deffn

@geindex return_ok() (http.cookiejar.CookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar CookiePolicy return_ok}@anchor{2f3e}
@deffn {方法} CookiePolicy.return_ok (cookie, request)

返回指明是否应当将 cookie 返回给服务器的布尔值。

@emph{cookie} 是一个 @ref{2f2a,,Cookie} 实例。 @emph{request} 是一个实现了 @ref{2f2d,,CookieJar.add_cookie_header()} 的文档所定义的接口的对象。
@end deffn

@geindex domain_return_ok() (http.cookiejar.CookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar CookiePolicy domain_return_ok}@anchor{2f3f}
@deffn {方法} CookiePolicy.domain_return_ok (domain, request)

对于给定的 cookie 域如果不应当返回 cookie 则返回 @code{False}。

此方法是一种优化操作。 它消除了检查每个具有特定域的 cookie 的必要性（这可能会涉及读取许多文件）。 从 @ref{2f3f,,domain_return_ok()} 和 @ref{2f40,,path_return_ok()} 返回真值并将所有工作留给 @ref{2f3e,,return_ok()}。

如果 @ref{2f3f,,domain_return_ok()} 为 cookie 域返回真值，则会为 cookie 路径调用 @ref{2f40,,path_return_ok()}。 在其他情况下，则不会为该 cookie 域调用 @ref{2f40,,path_return_ok()} 和 @ref{2f3e,,return_ok()}。 如果 @ref{2f40,,path_return_ok()} 返回真值，则会调用 @ref{2f3e,,return_ok()} 并附带 @ref{2f2a,,Cookie} 对象本身以进行全面检查。 在其他情况下，都永远不会为该 cookie 路径调用 @ref{2f3e,,return_ok()}。

请注意 @ref{2f3f,,domain_return_ok()} 会针对每个 @emph{cookie} 域被调用，而非只针对 @emph{request} 域。 例如，该函数会针对 @code{".example.com"} 和 @code{"www.example.com"} 被调用，如果 request 域为 @code{"www.example.com"} 的话。 对于 @ref{2f40,,path_return_ok()} 也是如此。

@emph{request} 参数与 @ref{2f3e,,return_ok()} 的文档所说明的一致。
@end deffn

@geindex path_return_ok() (http.cookiejar.CookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar CookiePolicy path_return_ok}@anchor{2f40}
@deffn {方法} CookiePolicy.path_return_ok (path, request)

对于给定的 cookie 路径如果不应当返回 cookie 返回 @code{False}。

请参阅 @ref{2f3f,,domain_return_ok()} 的文档。
@end deffn

除了实现上述方法，@ref{2f25,,CookiePolicy} 接口的实现还必须提供下列属性，指明应当使用哪种协议以及如何使用。 所有这些属性都可以被赋值。

@geindex netscape (http.cookiejar.CookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy netscape}@anchor{2f41}
@deffn {属性} CookiePolicy.netscape

实现 Netscape 协议。
@end deffn

@geindex rfc2965 (http.cookiejar.CookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy rfc2965}@anchor{2f42}
@deffn {属性} CookiePolicy.rfc2965

实现 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 协议。
@end deffn

@geindex hide_cookie2 (http.cookiejar.CookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar CookiePolicy hide_cookie2}@anchor{2f43}
@deffn {属性} CookiePolicy.hide_cookie2

不要向请求添加 @code{Cookie2} 标头（此标头是提示服务器请求方能识别 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} cookie）。
@end deffn

定义 @ref{2f25,,CookiePolicy} 类的最适用方式是通过子类化 @ref{1172,,DefaultCookiePolicy} 并重载部分或全部上述的方法。 @ref{2f25,,CookiePolicy} 本身可被用作 '空策略' 以允许设置和接收所有的 cookie（但这没有什么用处）。

@node DefaultCookiePolicy 对象,Cookie 对象<2>,CookiePolicy 对象,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar default-cookie-policy-objects}@anchor{2f44}@anchor{library/http cookiejar defaultcookiepolicy-objects}@anchor{2f45}
@subsubsection DefaultCookiePolicy 对象


实现接收和返回 cookie 的标准规则。

@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 和 Netscape cookie 均被涵盖。 RFC 2965 处理默认关闭。

提供自定义策略的最容易方式是重载此类并在你重载的实现中添加你自己的额外检查之前调用其方法:

@example
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
            return False
        if i_dont_want_to_store_this_cookie(cookie):
            return False
        return True
@end example

在实现 @ref{2f25,,CookiePolicy} 接口所要求的特性之外，该类还允许你阻止和允许特定的域设置和接收 cookie。 还有一些严格性开关允许你将相当宽松的 Netscape 协议规则收紧一点（代价是可能会阻止某些无害的 cookie）。

A domain blacklist and whitelist is provided (both off by default). Only domains
not in the blacklist and present in the whitelist (if the whitelist is active)
participate in cookie setting and returning.  Use the @emph{blocked_domains}
constructor argument, and @code{blocked_domains()} and
@code{set_blocked_domains()} methods (and the corresponding argument and methods
for @emph{allowed_domains}).  If you set a whitelist, you can turn it off again by
setting it to @ref{204,,None}.

Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched.  For example, @code{"example.com"} matches a blacklist
entry of @code{"example.com"}, but @code{"www.example.com"} does not.  Domains that do
start with a dot are matched by more specific domains too. For example, both
@code{"www.example.com"} and @code{"www.coyote.example.com"} match @code{".example.com"}
(but @code{"example.com"} itself does not).  IP addresses are an exception, and
must match exactly.  For example, if blocked_domains contains @code{"192.168.1.2"}
and @code{".168.1.2"}, 192.168.1.2 is blocked, but 193.168.1.2 is not.

@ref{1172,,DefaultCookiePolicy} 实现了下列附加方法:

@geindex blocked_domains() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy blocked_domains}@anchor{2f46}
@deffn {方法} DefaultCookiePolicy.blocked_domains ()

返回被阻止域的序列（元组类型）。
@end deffn

@geindex set_blocked_domains() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy set_blocked_domains}@anchor{2f47}
@deffn {方法} DefaultCookiePolicy.set_blocked_domains (blocked_domains)

设置被阻止域的序列。
@end deffn

@geindex is_blocked() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy is_blocked}@anchor{2f48}
@deffn {方法} DefaultCookiePolicy.is_blocked (domain)

Return whether @emph{domain} is on the blacklist for setting or receiving cookies.
@end deffn

@geindex allowed_domains() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy allowed_domains}@anchor{2f49}
@deffn {方法} DefaultCookiePolicy.allowed_domains ()

返回 @ref{204,,None}，或者被允许域的序列（元组类型）。
@end deffn

@geindex set_allowed_domains() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy set_allowed_domains}@anchor{2f4a}
@deffn {方法} DefaultCookiePolicy.set_allowed_domains (allowed_domains)

设置被允许域的序列，或者为 @ref{204,,None}。
@end deffn

@geindex is_not_allowed() (http.cookiejar.DefaultCookiePolicy 方法)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy is_not_allowed}@anchor{2f4b}
@deffn {方法} DefaultCookiePolicy.is_not_allowed (domain)

Return whether @emph{domain} is not on the whitelist for setting or receiving
cookies.
@end deffn

@ref{1172,,DefaultCookiePolicy} 实例具有下列属性，它们都是基于同名的构造器参数来初始化的，并且都可以被赋值。

@geindex rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy rfc2109_as_netscape}@anchor{2f29}
@deffn {属性} DefaultCookiePolicy.rfc2109_as_netscape

如为真值，则请求 @ref{2d78,,CookieJar} 实例将 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookie (即在带有 version 值为 1 的 cookie 属性的 @code{Set-Cookie} 标头中接收到的 cookie) 降级为 Netscape cookie: 即将 @ref{2f2a,,Cookie} 实例的 version 属性设为 0。 默认值为 @ref{204,,None}，在此情况下 RFC 2109 cookie 仅在s are downgraded if and only if 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 处理被关闭时才会被降级。 因此，RFC 2109 cookie 默认会被降级。
@end deffn

通用严格性开关:

@geindex strict_domain (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_domain}@anchor{2f4c}
@deffn {属性} DefaultCookiePolicy.strict_domain

不允许网站设置带国家码顶级域的包含两部分的域名例如 @code{.co.uk}, @code{.gov.uk}, @code{.co.nz} 等。 此开关尚未十分完善，并不保证有效！
@end deffn

@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 协议严格性开关:

@geindex strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_rfc2965_unverifiable}@anchor{2f4d}
@deffn {属性} DefaultCookiePolicy.strict_rfc2965_unverifiable

遵循针对不可验证事务的 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 规则（不可验证事务通常是由重定向或请求发布在其它网站的图片导致的）。 如果该属性为假值，则 @emph{永远不会} 基于可验证性而阻止 cookie。
@end deffn

Netscape 协议严格性开关:

@geindex strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_unverifiable}@anchor{2f4e}
@deffn {属性} DefaultCookiePolicy.strict_ns_unverifiable

即便是对 Netscape cookie 也要应用 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 规则。
@end deffn

@geindex strict_ns_domain (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_domain}@anchor{2f4f}
@deffn {属性} DefaultCookiePolicy.strict_ns_domain

指明针对 Netscape cookie 的域匹配规则的严格程度。 可接受的值见下文。
@end deffn

@geindex strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_initial_dollar}@anchor{2f50}
@deffn {属性} DefaultCookiePolicy.strict_ns_set_initial_dollar

忽略 Set-Cookie 中的 cookie: 即名称前缀为 @code{'@{TX-PL-LABEL@}#x27;} 的标头。
@end deffn

@geindex strict_ns_set_path (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_path}@anchor{2f51}
@deffn {属性} DefaultCookiePolicy.strict_ns_set_path

不允许设置路径与请求 URL 路径不匹配的 cookie。
@end deffn

@code{strict_ns_domain} 是一组旗标。 其值是通过或运算来构造的（例如，@code{DomainStrictNoDots|DomainStrictNonDomain} 表示同时设置两个旗标）。

@geindex DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNoDots}@anchor{2f52}
@deffn {属性} DefaultCookiePolicy.DomainStrictNoDots

当设置 cookie 是，'host prefix' 不可包含点号（例如 @code{www.foo.bar.com} 不能为 @code{.bar.com} 设置 cookie，因为 @code{www.foo} 包含了一个点号）。
@end deffn

@geindex DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNonDomain}@anchor{2f53}
@deffn {属性} DefaultCookiePolicy.DomainStrictNonDomain

没有显式指明Cookies that did not explicitly specify a @code{domain} cookie 属性的 cookie 只能被返回给与设置 cookie 的域相同的域（例如 @code{spam.example.com} 不会是来自 @code{example.com} 的返回 cookie，如果该域名没有 @code{domain} cookie 属性的话）。
@end deffn

@geindex DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainRFC2965Match}@anchor{2f54}
@deffn {属性} DefaultCookiePolicy.DomainRFC2965Match

当设置 cookie 时，要求完整的 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 域匹配。
@end deffn

下列属性是为方便使用而提供的，是上述旗标的几种最常用组合:

@geindex DomainLiberal (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainLiberal}@anchor{2f55}
@deffn {属性} DefaultCookiePolicy.DomainLiberal

等价于 0 (即所有上述 Netscape 域严格性旗标均停用)。
@end deffn

@geindex DomainStrict (http.cookiejar.DefaultCookiePolicy 属性)
@anchor{library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrict}@anchor{2f56}
@deffn {属性} DefaultCookiePolicy.DomainStrict

等价于 @code{DomainStrictNoDots|DomainStrictNonDomain}。
@end deffn

@node Cookie 对象<2>,示例<38>,DefaultCookiePolicy 对象,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar cookie-objects}@anchor{2f57}
@subsubsection Cookie 对象


@ref{2f2a,,Cookie} 实例具有与各种 cookie 标准中定义的标准 cookie 属性大致对应的 Python 属性。 这并非一一对应，因为存在复杂的赋默认值的规则，因为 @code{max-age} 和 @code{expires} cookie 属性包含相同信息，也因为 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookie 可以被 @ref{94,,http.cookiejar} 从第 1 版 '降级为' 第 0 版 (Netscape) cookie。

对这些属性的赋值在 @ref{2f25,,CookiePolicy} 方法的极少数情况以外应该都是不必要的。 该类不会强制内部一致性，因此如果这样做则你应当清楚自己在做什么。

@geindex version (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie version}@anchor{2f58}
@deffn {属性} Cookie.version

整数或 @ref{204,,None}。 Netscape cookie 的 @ref{2f58,,version} 值为 0。 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} 和 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookie 的 @code{version} cookie 属性值为 1。 但是，请注意 @ref{94,,http.cookiejar} 可以将 RFC 2109 cookie '降级' 为 Netscape cookie，在此情况下 @ref{2f58,,version} 值也为 0。
@end deffn

@geindex name (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie name}@anchor{2f59}
@deffn {属性} Cookie.name

Cookie 名称（一个字符串）。
@end deffn

@geindex value (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie value}@anchor{2f5a}
@deffn {属性} Cookie.value

Cookie 值（一个字符串），或为 @ref{204,,None}。
@end deffn

@geindex port (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie port}@anchor{2f5b}
@deffn {属性} Cookie.port

代表一个端口或一组端口（例如 '80' 或 '80,8080'）的字符串，或为 @ref{204,,None}。
@end deffn

@geindex path (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie path}@anchor{2f5c}
@deffn {属性} Cookie.path

Cookie 路径 (字符串类型，例如 @code{'/acme/rocket_launchers'})。
@end deffn

@geindex secure (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie secure}@anchor{2f5d}
@deffn {属性} Cookie.secure

如果 cookie 应当只能通过安全连接返回则为 @code{True}。
@end deffn

@geindex expires (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie expires}@anchor{2f5e}
@deffn {属性} Cookie.expires

整数类型的过期时间，以距离 Unix 纪元的秒数表示，或者为 @ref{204,,None}。 另请参阅 @ref{2f5f,,is_expired()} 方法。
@end deffn

@geindex discard (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie discard}@anchor{2f60}
@deffn {属性} Cookie.discard

如果是会话 cookie 则为 @code{True}。
@end deffn

@geindex comment (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie comment}@anchor{2f61}
@deffn {属性} Cookie.comment

来自服务器的解释此 cookie 功能的字符串形式的注释，或者为 @ref{204,,None}。
@end deffn

@geindex comment_url (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie comment_url}@anchor{2f62}
@deffn {属性} Cookie.comment_url

链接到来自服务器的解释此 cookie 功能的注释的 URL，或者为 @ref{204,,None}。
@end deffn

@geindex rfc2109 (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie rfc2109}@anchor{2f63}
@deffn {属性} Cookie.rfc2109

如果 cookie 是作为 
@geindex RFC; RFC 2109
RFC 2109@footnote{https://tools.ietf.org/html/rfc2109.html} cookie 被接收（即该 cookie 是在 @code{Set-Cookie} 标头中送达，且该标头的 Version cookie 属性的值为 1）则为 @code{True}。 之所以要提供该属性是因为 @ref{94,,http.cookiejar} 可能会从 RFC 2109 cookies '降级' 为 Netscape cookie，在此情况下 @ref{2f58,,version} 值为 0。
@end deffn

@geindex port_specified (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie port_specified}@anchor{2f64}
@deffn {属性} Cookie.port_specified

如果服务器显式地指定了一个端口或一组端口（在 @code{Set-Cookie} / @code{Set-Cookie2} 标头中）则为 @code{True}。
@end deffn

@geindex domain_specified (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie domain_specified}@anchor{2f65}
@deffn {属性} Cookie.domain_specified

如果服务器显式地指定了一个域则为 @code{True}。
@end deffn

@geindex domain_initial_dot (http.cookiejar.Cookie 属性)
@anchor{library/http cookiejar http cookiejar Cookie domain_initial_dot}@anchor{2f66}
@deffn {属性} Cookie.domain_initial_dot

该属性为 @code{True} 表示服务器显式地指定了以一个点号 (@code{'.'}) 打头的域。
@end deffn

Cookie 可能还有额外的非标准 cookie 属性。 这些属性可以通过下列方法来访问:

@geindex has_nonstandard_attr() (http.cookiejar.Cookie 方法)
@anchor{library/http cookiejar http cookiejar Cookie has_nonstandard_attr}@anchor{2f67}
@deffn {方法} Cookie.has_nonstandard_attr (name)

如果 cookie 具有相应名称的 cookie 属性则返回 @code{True}。
@end deffn

@geindex get_nonstandard_attr() (http.cookiejar.Cookie 方法)
@anchor{library/http cookiejar http cookiejar Cookie get_nonstandard_attr}@anchor{2f68}
@deffn {方法} Cookie.get_nonstandard_attr (name, default=None)

如果 cookie 具有相应名称的 cookie 属性，则返回其值。 否则，返回 @emph{default}。
@end deffn

@geindex set_nonstandard_attr() (http.cookiejar.Cookie 方法)
@anchor{library/http cookiejar http cookiejar Cookie set_nonstandard_attr}@anchor{2f69}
@deffn {方法} Cookie.set_nonstandard_attr (name, value)

设置指定名称的 cookie 属性的值。
@end deffn

@ref{2f2a,,Cookie} 类还定义了下列方法:

@geindex is_expired() (http.cookiejar.Cookie 方法)
@anchor{library/http cookiejar http cookiejar Cookie is_expired}@anchor{2f5f}
@deffn {方法} Cookie.is_expired (now=None)

如果 cookie 传入了服务器请求其所应过期的时间则为 @code{True}。 如果给出 @emph{now} 值（距离 Unix 纪元的秒数），则返回在指定的时间 cookie 是否已过期。
@end deffn

@node 示例<38>,,Cookie 对象<2>,http cookiejar —— HTTP 客户端的 Cookie 处理
@anchor{library/http cookiejar examples}@anchor{2f6a}
@subsubsection 示例


第一个例子显示了 @ref{94,,http.cookiejar} 的最常见用法:

@example
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

这个例子演示了如何使用你的 Netscape, Mozilla 或 Lynx cookie 打开一个 URL (假定 cookie 文件位置采用 Unix/Netscape 惯例):

@example
import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

下一个例子演示了 @ref{1172,,DefaultCookiePolicy} 的使用。 启用 
@geindex RFC; RFC 2965
RFC 2965@footnote{https://tools.ietf.org/html/rfc2965.html} cookie，在设置和返回 Netscape cookie 时更严格地限制域，以及阻止某些域设置 cookie 或返回它们:

@example
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
    rfc2965=True, strict_ns_domain=Policy.DomainStrict,
    blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
@end example

@node xmlrpc --- XMLRPC 服务端与客户端模块,xmlrpc client --- XML-RPC 客户端访问,http cookiejar —— HTTP 客户端的 Cookie 处理,互联网协议和支持
@anchor{library/xmlrpc doc}@anchor{2f6b}@anchor{library/xmlrpc xmlrpc-xmlrpc-server-and-client-modules}@anchor{2f6c}
@subsection @code{xmlrpc} --- XMLRPC 服务端与客户端模块


XML-RPC 是一种远程过程调用方法，它使用通过 HTTP 传递的 XML 作为载体。 有了它，客户端可以在远程服务器上调用带参数的方法（服务器以 URI 命名）并获取结构化的数据。

@code{xmlrpc} 是一个集合了 XML-RPC 服务端与客户端实现模块的包。 这些模块是:


@itemize *

@item 
@ref{148,,xmlrpc.client}

@item 
@ref{149,,xmlrpc.server}
@end itemize

@node xmlrpc client --- XML-RPC 客户端访问,xmlrpc server --- 基本 XML-RPC 服务器,xmlrpc --- XMLRPC 服务端与客户端模块,互联网协议和支持
@anchor{library/xmlrpc client doc}@anchor{2f6d}@anchor{library/xmlrpc client module-xmlrpc client}@anchor{148}@anchor{library/xmlrpc client xmlrpc-client-xml-rpc-client-access}@anchor{2f6e}
@subsection @code{xmlrpc.client} --- XML-RPC 客户端访问


@geindex xmlrpc.client (模块)

@strong{源代码:} Lib/xmlrpc/client.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xmlrpc/client.py}

@c XXX Not everything is documented yet.  It might be good to describe
@c Marshaller, Unmarshaller, getparser and Transport.


__________________________________________________________________


XML-RPC 是一种远程过程调用方法，它以使用 HTTP(S) 传递的 XML 作为载体。 通过它，客户端可以在远程服务器（服务器以 URI 指明）上调用带参数的方法并获取结构化的数据。 本模块支持编写 XML-RPC 客户端代码；它会处理在通用 Python 对象和 XML 之间进行在线翻译的所有细节。

@cartouche
@quotation 警告 
@ref{148,,xmlrpc.client} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche


在 3.5 版更改: 对于 HTTPS URI，现在 @ref{148,,xmlrpc.client} 默认会执行所有必要的证书和主机名检查。


@geindex ServerProxy (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client ServerProxy}@anchor{386}
@deffn {类} xmlrpc.client.ServerProxy (uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)

@ref{386,,ServerProxy} 实例是管理与远程 XML-RPC 服务器通信的对象。 要求的第一个参数为 URI (统一资源定位符)，通常就是服务器的 URL。 可选的第二个参数为传输工厂实例；在默认情况下对于 https: URL 是一个内部 @code{SafeTransport} 实例，在其他情况下则是一个内部 HTTP @code{Transport} 实例。 可选的第三个参数为编码格式，默认为 UTF-8。 可选的第四个参数为调试旗标。

下列形参控制所返回代理实例的使用。 如果 @emph{allow_none} 为真值，则 Python 常量 @code{None} 将被转写为 XML；默认行为是针对 @code{None} 引发 @ref{1ff,,TypeError}。 这是对 XML-RPC 规格的一个常用扩展，但并不被所有客户端和服务器所支持；请参阅 http://ontosys.com/xml-rpc/extensions.php@footnote{https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php} 了解详情。 @emph{use_builtin_types} 旗标可被用来将日期/时间值表示为 @ref{19f,,datetime.datetime} 对象而将二进制数据表示为 @ref{172,,bytes} 对象；此旗标默认为假值。 @ref{19f,,datetime.datetime}, @ref{172,,bytes} 和 @ref{173,,bytearray} 对象可以被传给调用操作。 @emph{headers} 形参为可选的随每次请求发送的 HTTP 标头序列，其形式为包含代表标头名称和值的 2 元组的序列 (例如 @cite{[('Header-Name'@comma{} 'value')]})。 已不再适用的 @emph{use_datetime} 旗标与 @emph{use_builtin_types} 类似但它只针对日期/时间值。
@end deffn


在 3.3 版更改: 增加了 @emph{use_builtin_types} 旗标。



在 3.8 版更改: 增加了 @emph{headers} 形参。

HTTP 和 HTTPS 传输均支持用于 HTTP 基本身份验证的 URL 语法扩展: @code{http://user:pass@@host:port/path}。 @code{user:pass} 部分将以 base64 编码为 HTTP 'Authorization' 标头，并在发起调用 XML-RPC 方法时作为连接过程的一部分发送给远程服务器。 你只需要在远程服务器要求基本身份验证账号和密码时使用此语法。 如果提供了 HTTPS URL，@emph{context} 可以为 @ref{4f2,,ssl.SSLContext} 并配置有下层 HTTPS 连接的 SSL 设置。

返回的实例是一个代理对象，具有可被用来在远程服务器上发起相应 RPC 调用的方法。 如果远程服务器支持内省 API，则也可使用该代理对象在远程服务器上查询它所支持的方法（服务发现）并获取其他服务器相关的元数据

适用的类型（即可通过 XML 生成 marshall 对象），包括如下类型（除了已说明的例外，它们会被反 marshall 为同样的 Python 类型）:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

XML-RPC类型

@tab

Python数据类型

@item

@code{boolean}

@tab

@ref{2c4,,bool}

@item

@code{int}, @code{i1}, @code{i2},  @code{i4}, @code{i8} 或者 @code{biginteger}

@tab

@ref{205,,int} 的范围从 -2147483648 到 2147483647。值将获得 @code{<int>} 标志。

@item

@code{double} 或 @code{float}

@tab

@ref{1fe,,float}。值将获得 @code{<double>} 标志。

@item

@code{string}

@tab

@ref{206,,str}

@item

@code{array}

@tab

@ref{1f9,,list} 或 @ref{1a2,,tuple} 包含整合元素。数组以 @ref{1f9,,lists} 形式返回。

@item

@code{struct}

@tab

@ref{164,,dict}。 键必须为字符串，值可以为任何适用的类型。 可以传入用户自定义类的对象；只有其 @ref{5fe,,__dict__} 属性会被传输。

@item

@code{dateTime.iso8601}

@tab

@ref{2f6f,,DateTime} 或 @ref{19f,,datetime.datetime}。返回的类型取决于 @emph{use_builtin_types} 和 @emph{use_datetime} 标志的值。

@item

@code{base64}

@tab

@ref{2f70,,Binary}, @ref{172,,bytes} 或 @ref{173,,bytearray}。返回的类型取决于 @emph{use_builtin_types} 标志的值。

@item

@code{nil}

@tab

@code{None} 常量。仅当 @emph{allow_none} 为true时才允许传递。

@item

@code{bigdecimal}

@tab

@ref{2c7,,decimal.Decimal}.  仅返回类型。

@end multitable


这是This is the full set of data types supported by XML-RPC 所支持数据类型的完整集合。 方法调用也可能引发一个特殊的 @ref{2f71,,Fault} 实例，用来提示 XML-RPC 服务器错误，或是用 @ref{2f72,,ProtocolError} 来提示 HTTP/HTTPS 传输层中的错误。 @ref{2f71,,Fault} 和 @ref{2f72,,ProtocolError} 都派生自名为 @code{Error} 的基类。 请注意 xmlrpc client 模块目前不可 marshal 内置类型的子类的实例。

当传入字符串时，XML 中的特殊字符如 @code{<}, @code{>} 和 @code{&} 将被自动转义。 但是，调用方有责任确保字符串中没有 XML 中不允许的字符，例如 ASCII 值在 0 和 31 之间的控制字符（当然，制表、换行和回车除外）；不这样做将导致 XML-RPC 请求的 XML 格式不正确。 如果你必须通过 XML-RPC 传入任意字节数据，请使用 @ref{172,,bytes} 或 @ref{173,,bytearray} 类或者下文描述的 @ref{2f70,,Binary} 包装器类。

@code{Server} 被保留作为 @ref{386,,ServerProxy} 的别名用于向下兼容。 新的代码应当使用 @ref{386,,ServerProxy}。


在 3.5 版更改: 增加了 @emph{context} 参数。



在 3.6 版更改: 增加了对带有前缀的类型标签的支持 (例如 @code{ex:nil})。 增加了对反 marshall 被 Apache XML-RPC 实现用于表示数值的附加类型的支持: @code{i1}, @code{i2}, @code{i8}, @code{biginteger}, @code{float} 和 @code{bigdecimal}。 请参阅 @indicateurl{http://ws.apache.org/xmlrpc/types.html} 了解详情。




@subsubheading 参见



@table @asis

@item XML-RPC HOWTO@footnote{http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html}

以多种语言对 XML-RPC 操作和客户端软件进行了很好的说明。 包含 XML-RPC 客户端开发者所需知道的几乎任何事情。

@item XML-RPC Introspection@footnote{http://xmlrpc-c.sourceforge.net/introspection.html}

描述了用于内省的 XML-RPC 协议扩展。

@item XML-RPC Specification@footnote{http://xmlrpc.scripting.com/spec.html}

官方规范说明。
@end table


@menu
* ServerProxy 对象:: 
* DateTime 对象:: 
* Binary 对象:: 
* Fault 对象:: 
* ProtocolError 对象:: 
* MultiCall 对象:: 
* 便捷函数:: 
* 客户端用法的示例:: 
* 客户端与服务器用法的示例:: 

@end menu

@node ServerProxy 对象,DateTime 对象,,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client id1}@anchor{2f73}@anchor{library/xmlrpc client serverproxy-objects}@anchor{2f74}
@subsubsection ServerProxy 对象


@ref{386,,ServerProxy} 实例有一个方法与 XML-RPC 服务器所接受的每个远程过程调用相对应。 调用该方法会执行一个 RPC，通过名称和参数签名来调度（例如同一个方法名可通过多个参数签名来重载）。 RPC 结束时返回一个值，它可以是适用类型的返回数据或是表示错误的 @ref{2f71,,Fault} 或 @ref{2f72,,ProtocolError} 对象。

支持 XML 内省 API 的服务器还支持一些以保留的 @code{system} 属性分组的通用方法:

@geindex listMethods() (xmlrpc.client.ServerProxy.system 方法)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system listMethods}@anchor{2f75}
@deffn {方法} ServerProxy.system.listMethods ()

此方法返回一个字符串列表，每个字符串都各自对应 XML-RPC 服务器所支持的（非系统）方法。
@end deffn

@geindex methodSignature() (xmlrpc.client.ServerProxy.system 方法)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system methodSignature}@anchor{2f76}
@deffn {方法} ServerProxy.system.methodSignature (name)

此方法接受一个形参，即某个由 XML-RPC 服务器所实现的方法名称。 它返回一个由此方法可能的签名组成的数组。 一个签名就是一个类型数组。 这些类型中的第一个是方法的的返回类型，其余的均为形参。

由于允许多个签名（即重载），此方法是返回一个签名列表而非一个单例。

签名本身被限制为一个方法所期望的最高层级形参。 举例来说如果一个方法期望有一个结构体数组作为形参，并返回一个字符串，则其签名就是 "string, array"。 如果它期望有三个整数并返回一个字符串，则其签名是 "string, int, int, int"。

如果方法没有定义任何签名，则将返回一个非数组值。 在 Python 中这意味着返回值的类型为列表以外的类型。
@end deffn

@geindex methodHelp() (xmlrpc.client.ServerProxy.system 方法)
@anchor{library/xmlrpc client xmlrpc client ServerProxy system methodHelp}@anchor{2f77}
@deffn {方法} ServerProxy.system.methodHelp (name)

此方法接受一个形参，即 XML-RPC 服务器所实现的某个方法的名称。 它返回描述相应方法用法的文档字符串。 如果没有可用的文档字符串，则返回空字符串。 文档字符串可以包含 HTML 标记。
@end deffn


在 3.5 版更改: @ref{386,,ServerProxy} 的实例支持 @ref{66b,,context manager} 协议用于关闭下层传输。


以下是一个可运行的示例。 服务器端代码:

@example
from xmlrpc.server import SimpleXMLRPCServer

def is_even(n):
    return n % 2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
@end example

前述服务器的客户端代码:

@example
import xmlrpc.client

with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
    print("3 is even: %s" % str(proxy.is_even(3)))
    print("100 is even: %s" % str(proxy.is_even(100)))
@end example

@node DateTime 对象,Binary 对象,ServerProxy 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client datetime-objects}@anchor{2f78}@anchor{library/xmlrpc client id2}@anchor{2f79}
@subsubsection DateTime 对象


@geindex DateTime (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client DateTime}@anchor{2f6f}
@deffn {类} xmlrpc.client.DateTime

该类的初始化可以使用距离 Unix 纪元的秒数、时间元组、ISO 8601 时间/日期字符串或 @ref{19f,,datetime.datetime} 实例。 它具有下列方法，主要是为 marshall 和反 marshall 代码的内部使用提供支持:

@geindex decode() (xmlrpc.client.DateTime 方法)
@anchor{library/xmlrpc client xmlrpc client DateTime decode}@anchor{2f7a}
@deffn {方法} decode (string)

接受一个字符串作为实例的新时间值。
@end deffn

@geindex encode() (xmlrpc.client.DateTime 方法)
@anchor{library/xmlrpc client xmlrpc client DateTime encode}@anchor{2f7b}
@deffn {方法} encode (out)

将此 @ref{2f6f,,DateTime} 条目的 XML-RPC 编码格式写入到 @emph{out} 流对象。
@end deffn

它还通过富比较和 @ref{453,,__repr__()} 方法来支持某些 Python 内置操作。
@end deffn

以下是一个可运行的示例。 服务器端代码:

@example
import datetime
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def today():
    today = datetime.datetime.today()
    return xmlrpc.client.DateTime(today)

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(today, "today")
server.serve_forever()
@end example

前述服务器的客户端代码:

@example
import xmlrpc.client
import datetime

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")

today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
@end example

@node Binary 对象,Fault 对象,DateTime 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client binary-objects}@anchor{2f7c}@anchor{library/xmlrpc client id3}@anchor{2f7d}
@subsubsection Binary 对象


@geindex Binary (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client Binary}@anchor{2f70}
@deffn {类} xmlrpc.client.Binary

该类的初始化可以使用字节数据（可包括 NUL）。 对 @ref{2f70,,Binary} 对象的初始访问是由一个属性来提供的:

@geindex data (xmlrpc.client.Binary 属性)
@anchor{library/xmlrpc client xmlrpc client Binary data}@anchor{2f7e}
@deffn {属性} data

被 @ref{2f70,,Binary} 实例封装的二进制数据。 该数据以 @ref{172,,bytes} 对象的形式提供。
@end deffn

@ref{2f70,,Binary} 对象具有下列方法，支持这些方法主要是供 marshall 和反 marshall 代码在内部使用:

@geindex decode() (xmlrpc.client.Binary 方法)
@anchor{library/xmlrpc client xmlrpc client Binary decode}@anchor{2f7f}
@deffn {方法} decode (bytes)

接受一个 base64 @ref{172,,bytes} 对象并将其解码为实例的新数据。
@end deffn

@geindex encode() (xmlrpc.client.Binary 方法)
@anchor{library/xmlrpc client xmlrpc client Binary encode}@anchor{2f80}
@deffn {方法} encode (out)

将此二进制条目的 XML-RPC base 64 编码格式写入到 @emph{out} 流对象。

被编码数据将依据 
@geindex RFC; RFC 2045#section-6.8
RFC 2045 第 6.8 节@footnote{https://tools.ietf.org/html/rfc2045.html#section-6.8} 每 76 个字符换行一次，这是撰写 XML-RPC 规范说明时 base64 规范的事实标准。
@end deffn

它还通过 @ref{454,,__eq__()} 和 @ref{f20,,__ne__()} 方法来支持某些 Python 内置运算符。
@end deffn

该二进制对象的示例用法。 我们将通过 XMLRPC 来传输一张图片:

@example
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def python_logo():
    with open("python_logo.jpg", "rb") as handle:
        return xmlrpc.client.Binary(handle.read())

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(python_logo, 'python_logo')

server.serve_forever()
@end example

客户端会获取图片并将其保存为一个文件:

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
with open("fetched_python_logo.jpg", "wb") as handle:
    handle.write(proxy.python_logo().data)
@end example

@node Fault 对象,ProtocolError 对象,Binary 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client fault-objects}@anchor{2f81}@anchor{library/xmlrpc client id4}@anchor{2f82}
@subsubsection Fault 对象


@geindex Fault (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client Fault}@anchor{2f71}
@deffn {类} xmlrpc.client.Fault

@ref{2f71,,Fault} 对象封装了 XML-RPC fault 标签的内容。 Fault 对象具有下列属性:

@geindex faultCode (xmlrpc.client.Fault 属性)
@anchor{library/xmlrpc client xmlrpc client Fault faultCode}@anchor{2f83}
@deffn {属性} faultCode

A string indicating the fault type.
@end deffn

@geindex faultString (xmlrpc.client.Fault 属性)
@anchor{library/xmlrpc client xmlrpc client Fault faultString}@anchor{2f84}
@deffn {属性} faultString

一个包含与 fault 相关联的诊断消息的字符串。
@end deffn
@end deffn

在接下来的示例中我们将通过返回一个复数类型的值来故意引发一个 @ref{2f71,,Fault}。 服务器端代码:

@example
from xmlrpc.server import SimpleXMLRPCServer

# A marshalling error is going to occur because we're returning a
# complex number
def add(x, y):
    return x+y+0j

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(add, 'add')

server.serve_forever()
@end example

前述服务器的客户端代码:

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
try:
    proxy.add(2, 5)
except xmlrpc.client.Fault as err:
    print("A fault occurred")
    print("Fault code: %d" % err.faultCode)
    print("Fault string: %s" % err.faultString)
@end example

@node ProtocolError 对象,MultiCall 对象,Fault 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client protocol-error-objects}@anchor{2f85}@anchor{library/xmlrpc client protocolerror-objects}@anchor{2f86}
@subsubsection ProtocolError 对象


@geindex ProtocolError (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client ProtocolError}@anchor{2f72}
@deffn {类} xmlrpc.client.ProtocolError

@ref{2f72,,ProtocolError} 对象描述了下层传输层中的协议错误（例如当 URI 所指定的服务器不存在时的 404 'not found' 错误）。 它具有下列属性:

@geindex url (xmlrpc.client.ProtocolError 属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError url}@anchor{2f87}
@deffn {属性} url

触发错误的 URI 或 URL。
@end deffn

@geindex errcode (xmlrpc.client.ProtocolError 属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError errcode}@anchor{2f88}
@deffn {属性} errcode

错误代码。
@end deffn

@geindex errmsg (xmlrpc.client.ProtocolError 属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError errmsg}@anchor{2f89}
@deffn {属性} errmsg

错误消息或诊断字符串。
@end deffn

@geindex headers (xmlrpc.client.ProtocolError 属性)
@anchor{library/xmlrpc client xmlrpc client ProtocolError headers}@anchor{2f8a}
@deffn {属性} headers

一个包含触发错误的 HTTP/HTTPS 请求的标头的字典。
@end deffn
@end deffn

在接下来的示例中我们将通过提供一个无效的 URI 来故意引发一个 @ref{2f72,,ProtocolError}:

@example
import xmlrpc.client

# create a ServerProxy with a URI that doesn't respond to XMLRPC requests
proxy = xmlrpc.client.ServerProxy("http://google.com/")

try:
    proxy.some_method()
except xmlrpc.client.ProtocolError as err:
    print("A protocol error occurred")
    print("URL: %s" % err.url)
    print("HTTP/HTTPS headers: %s" % err.headers)
    print("Error code: %d" % err.errcode)
    print("Error message: %s" % err.errmsg)
@end example

@node MultiCall 对象,便捷函数,ProtocolError 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client multicall-objects}@anchor{2f8b}
@subsubsection MultiCall 对象


@ref{2f8c,,MultiCall} 对象提供了一种将对远程服务器的多个调用封装为一个单独请求的方式 @footnote{@w{(1)} 
此做法被首次提及是在 @uref{https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic,a discussion on xmlrpc.com}。
}。

@geindex MultiCall (xmlrpc.client 中的类)
@anchor{library/xmlrpc client xmlrpc client MultiCall}@anchor{2f8c}
@deffn {类} xmlrpc.client.MultiCall (server)

创建一个用于盒式方法调用的对象。 @emph{server} 是调用的最终目标。 可以对结果对象发起调用，但它们将立即返回 @code{None}，并只在 @ref{2f8c,,MultiCall} 对象中存储调用名称和形参。 调用该对象本身会导致所有已存储的调用作为一个单独的 @code{system.multicall} 请求被发送。 此调用的结果是一个 @ref{a8c,,generator}；迭代这个生成器会产生各个结果。
@end deffn

以下是该类的用法示例。 服务器端代码:

@example
from xmlrpc.server import SimpleXMLRPCServer

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x // y

# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
@end example

前述服务器的客户端代码:

@example
import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
multicall = xmlrpc.client.MultiCall(proxy)
multicall.add(7, 3)
multicall.subtract(7, 3)
multicall.multiply(7, 3)
multicall.divide(7, 3)
result = multicall()

print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
@end example

@node 便捷函数,客户端用法的示例,MultiCall 对象,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client convenience-functions}@anchor{2f8d}
@subsubsection 便捷函数


@geindex dumps() (在 xmlrpc.client 模块中)
@anchor{library/xmlrpc client xmlrpc client dumps}@anchor{2f8e}
@deffn {函数} xmlrpc.client.dumps (params, methodname=None, methodresponse=None, encoding=None, allow_none=False)

请 @emph{params} 转换为一个 XML-RPC 请求。 或者当 @emph{methodresponse} 为真值时则转换为一个请求。 @emph{params} 可以是一个参数元组或是一个 @ref{2f71,,Fault} 异常类的实例。 如果 @emph{methodresponse} 为真值，只有单独的值可以被返回，这意味着 @emph{params} 的长度必须为 1。 如果提供了 @emph{encoding}，则在生成的 XML 会使用该编码格式；默认的编码格式为 UTF-8。 Python 的 @ref{204,,None} 值不可在标准 XML-RPC 中使用；要通过扩展来允许使用它，请为 @emph{allow_none} 提供一个真值。
@end deffn

@geindex loads() (在 xmlrpc.client 模块中)
@anchor{library/xmlrpc client xmlrpc client loads}@anchor{2f8f}
@deffn {函数} xmlrpc.client.loads (data, use_datetime=False, use_builtin_types=False)

将一个 XML-RPC 请求或响应转换为 Python 对象 @code{(params, methodname)}。 @emph{params} 是一个参数元组；@emph{methodname} 是一个字符串，或者如果数据包没有提供方法名则为 @code{None}。 如果 XML-RPC 数据包是代表一个故障条件，则此函数将引发一个 @ref{2f71,,Fault} 异常。 @emph{use_builtin_types} 旗标可被用于将日期/时间值表示为 @ref{19f,,datetime.datetime} 对象并将二进制数据表示为 @ref{172,,bytes} 对象；此旗标默认为假值。

已过时的 @emph{use_datetime} 旗标与 @emph{use_builtin_types} 类似但只作用于日期/时间值。


在 3.3 版更改: 增加了 @emph{use_builtin_types} 旗标。

@end deffn

@node 客户端用法的示例,客户端与服务器用法的示例,便捷函数,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client example-of-client-usage}@anchor{2f90}@anchor{library/xmlrpc client xmlrpc-client-example}@anchor{2f91}
@subsubsection 客户端用法的示例


@example
# simple test program (from the XML-RPC specification)
from xmlrpc.client import ServerProxy, Error

# server = ServerProxy("http://localhost:8000") # local server
with ServerProxy("http://betty.userland.com") as proxy:

    print(proxy)

    try:
        print(proxy.examples.getStateName(41))
    except Error as v:
        print("ERROR", v)
@end example

要通过 HTTP 代理访问一个 XML-RPC 服务器，你必须自行定义一个传输。 下面的例子演示了具体做法:

@example
import http.client
import xmlrpc.client

class ProxiedTransport(xmlrpc.client.Transport):

    def set_proxy(self, host, port=None, headers=None):
        self.proxy = host, port
        self.proxy_headers = headers

    def make_connection(self, host):
        connection = http.client.HTTPConnection(*self.proxy)
        connection.set_tunnel(host, headers=self.proxy_headers)
        self._connection = host, connection
        return connection

transport = ProxiedTransport()
transport.set_proxy('proxy-server', 8080)
server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
print(server.examples.getStateName(41))
@end example

@node 客户端与服务器用法的示例,,客户端用法的示例,xmlrpc client --- XML-RPC 客户端访问
@anchor{library/xmlrpc client example-of-client-and-server-usage}@anchor{2f92}
@subsubsection 客户端与服务器用法的示例


参见 @ref{2f93,,SimpleXMLRPCServer 示例}。

@c the link now points to webarchive since the one at

@c http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin

@c doesn't reply)

@node xmlrpc server --- 基本 XML-RPC 服务器,ipaddress --- IPv4/IPv6 操作库,xmlrpc client --- XML-RPC 客户端访问,互联网协议和支持
@anchor{library/xmlrpc server doc}@anchor{2f94}@anchor{library/xmlrpc server module-xmlrpc server}@anchor{149}@anchor{library/xmlrpc server xmlrpc-server-basic-xml-rpc-servers}@anchor{2f95}
@subsection @code{xmlrpc.server} --- 基本 XML-RPC 服务器


@geindex xmlrpc.server (模块)

@strong{源代码:} Lib/xmlrpc/server.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xmlrpc/server.py}


__________________________________________________________________


@ref{149,,xmlrpc.server} 模块为以 Python 编写 XML-RPC 服务器提供了一个基本服务器框架。 服务器可以是独立的，使用 @ref{2f96,,SimpleXMLRPCServer}，或是嵌入某个 CGI 环境中，使用 @ref{2f97,,CGIXMLRPCRequestHandler}。

@cartouche
@quotation 警告 
@ref{149,,xmlrpc.server} 模块对于恶意构建的数据是不安全的。 如果你需要解析不受信任或未经身份验证的数据，请参阅 @ref{2b18,,XML 漏洞}。
@end quotation
@end cartouche

@geindex SimpleXMLRPCServer (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer}@anchor{2f96}
@deffn {类} xmlrpc.server.SimpleXMLRPCServer (addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)

创建一个新的服务器实例。 这个类提供了一些用来注册可以被 XML-RPC 协议所调用的函数的方法。 @emph{requestHandler} 形参应该是一个用于请求处理句柄实例的工厂函数；它默认为 @ref{2f98,,SimpleXMLRPCRequestHandler}。 @emph{addr} 和 @emph{requestHandler} 形参会被传给 @ref{2ec0,,socketserver.TCPServer} 构造器。 如果 @emph{logRequests} 为真值（默认），请求将被记录到日志；将此形参设为假值将关闭日志记录。 @emph{allow_none} 和 @emph{encoding} 形参会被传给 @ref{148,,xmlrpc.client} 并控制将从服务器返回的 XML-RPC 响应。 @emph{bind_and_activate} 形参控制 @code{server_bind()} 和 @code{server_activate()} 是否会被构造器立即调用；它默认为真值。 将其设为假值将允许代码在地址被绑定之前操作 @emph{allow_reuse_address} 类变量。 @emph{use_builtin_types} 形参会被传给 @ref{2f8f,,loads()} 函数并控制当收到日期/时间值或二进制数据时将处理哪些类型；它默认为假值。


在 3.3 版更改: 增加了 @emph{use_builtin_types} 旗标。

@end deffn

@geindex CGIXMLRPCRequestHandler (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler}@anchor{2f97}
@deffn {类} xmlrpc.server.CGIXMLRPCRequestHandler (allow_none=False, encoding=None, use_builtin_types=False)

创建一个新的实例来处理 CGI 环境中的 XML-RPC 请求。 @emph{allow_none} 和 @emph{encoding} 形参会被传递给 @ref{148,,xmlrpc.client} 并控制将要从服务器返回的 XML-RPC 响应。 @emph{use_builtin_types} 形参会被传递给 @ref{2f8f,,loads()} 函数并控制当接收到日期/时间值或二进制数据时要处理哪种类型；该形参默认为假值。


在 3.3 版更改: 增加了 @emph{use_builtin_types} 旗标。

@end deffn

@geindex SimpleXMLRPCRequestHandler (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler}@anchor{2f98}
@deffn {类} xmlrpc.server.SimpleXMLRPCRequestHandler

创建一个新的请求处理句柄实例。 该请求处理句柄支持 @code{POST} 请求并会修改日志记录操作以便使用传递给 @ref{2f96,,SimpleXMLRPCServer} 形参的 @emph{logRequests} 形参。
@end deffn

@menu
* SimpleXMLRPCServer 对象:: 
* CGIXMLRPCRequestHandler:: 
* XMLRPC 服务器文档:: 
* DocXMLRPCServer 对象:: 
* DocCGIXMLRPCRequestHandler:: 

@end menu

@node SimpleXMLRPCServer 对象,CGIXMLRPCRequestHandler,,xmlrpc server --- 基本 XML-RPC 服务器
@anchor{library/xmlrpc server simple-xmlrpc-servers}@anchor{2f99}@anchor{library/xmlrpc server simplexmlrpcserver-objects}@anchor{2f9a}
@subsubsection SimpleXMLRPCServer 对象


@ref{2f96,,SimpleXMLRPCServer} 类是基于 @ref{2ec0,,socketserver.TCPServer} 并提供了一个创建简单、独立的 XML-RPC 服务器的方式。

@geindex register_function() (xmlrpc.server.SimpleXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_function}@anchor{2f9b}
@deffn {方法} SimpleXMLRPCServer.register_function (function=None, name=None)

注册一个可以响应 XML-RPC 请求的函数。 如果给出了 @emph{name}，则它将成为与 @emph{function} 相关联的方法名，否则将使用 @code{function.__name__}。 @emph{name} 是一个字符串，并可能包含不可在 Python 标识符中出现的字符，包括句点符。

此方法也可被用作装饰器。 当被用作装饰器时，@emph{name} 只能被指定为以 @emph{name} 注册的 @emph{function} 的一个关键字参数。 如果没有指定 @emph{name}，则将使用 @code{function.__name__}。


在 3.7 版更改: @ref{2f9b,,register_function()} 可被用作装饰器。

@end deffn

@geindex register_instance() (xmlrpc.server.SimpleXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_instance}@anchor{2f9c}
@deffn {方法} SimpleXMLRPCServer.register_instance (instance, allow_dotted_names=False)

注册一个被用来公开未使用 @ref{2f9b,,register_function()} 注册的方法名的对象。 如果 @emph{instance} 包含 @code{_dispatch()} 方法，它将被调用并附带被请求的方法名和来自请求的形参。 它的 API 是 @code{def _dispatch(self, method, params)} (请注意 @emph{params} 并不表示变量参数列表)。 如果它调用了一个下层函数来执行任务，该函数将以 @code{func(*params)} 的形式被调用，即扩展了形参列表。 来自 @code{_dispatch()} 的返回值将作为结果被返回给客户端。 如果 @emph{instance} 不包含 @code{_dispatch()} 方法，则会在其中搜索与被请求的方法名相匹配的属性。

如果可选的 @emph{allow_dotted_names} 参数为真值且该实例没有 @code{_dispatch()} 方法，则如果被请求的方法名包含句点符，会单独搜索该方法名的每个组成部分，其效果就是执行了简单的分层级搜索。 通过搜索找到的值将随即附带来自请求的形参被调用，并且返回值会被回传给客户端。

@cartouche
@quotation 警告 
启用 @emph{allow_dotted_names} 选项将允许入侵者访问你的模块的全局变量并可能允许入侵者在你的机器上执行任意代码。 仅可在安全、封闭的网络中使用此选项。
@end quotation
@end cartouche
@end deffn

@geindex register_introspection_functions() (xmlrpc.server.SimpleXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_introspection_functions}@anchor{2f9d}
@deffn {方法} SimpleXMLRPCServer.register_introspection_functions ()

注册 XML-RPC 内省函数 @code{system.listMethods}, @code{system.methodHelp} 和 @code{system.methodSignature}。
@end deffn

@geindex register_multicall_functions() (xmlrpc.server.SimpleXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_multicall_functions}@anchor{2f9e}
@deffn {方法} SimpleXMLRPCServer.register_multicall_functions ()

注册 XML-RPC 多调用函数 system.multicall。
@end deffn

@geindex rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler 属性)
@anchor{library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler rpc_paths}@anchor{2f9f}
@deffn {属性} SimpleXMLRPCRequestHandler.rpc_paths

一个必须为元组类型的属性值，其中列出所接收 XML-RPC 请求的有效路径部分。 发送到其他路径的请求将导致 404 "no such page" HTTP 错误。 如果此元组为空，则所有路径都将被视为有效。 默认值为 @code{('/', '/RPC2')}。
@end deffn

@menu
* SimpleXMLRPCServer 示例:: 

@end menu

@node SimpleXMLRPCServer 示例,,,SimpleXMLRPCServer 对象
@anchor{library/xmlrpc server id1}@anchor{2fa0}@anchor{library/xmlrpc server simplexmlrpcserver-example}@anchor{2f93}
@subsubsection SimpleXMLRPCServer 示例


服务器端代码:

@example
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name
    def adder_function(x, y):
        return x + y
    server.register_function(adder_function, 'add')

    # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'mul').
    class MyFuncs:
        def mul(self, x, y):
            return x * y

    server.register_instance(MyFuncs())

    # Run the server's main loop
    server.serve_forever()
@end example

以下客户端代码将调用上述服务器所提供的方法:

@example
import xmlrpc.client

s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3))  # Returns 2**3 = 8
print(s.add(2,3))  # Returns 5
print(s.mul(5,2))  # Returns 5*2 = 10

# Print list of available methods
print(s.system.listMethods())
@end example

@code{register_function()} 也可被用作装饰器。 上述服务器端示例可以通过装饰器方式来注册函数:

@example
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name, using
    # register_function as a decorator. *name* can only be given
    # as a keyword argument.
    @@server.register_function(name='add')
    def adder_function(x, y):
        return x + y

    # Register a function under function.__name__.
    @@server.register_function
    def mul(x, y):
        return x * y

    server.serve_forever()
@end example

以下包括在 @code{Lib/xmlrpc/server.py} 模块中的例子演示了一个允许带点号名称并注册有多调用函数的服务器。

@cartouche
@quotation 警告 
启用 @emph{allow_dotted_names} 选项将允许入侵者访问你的模块的全局变量并可能允许入侵者在你的机器上执行任意代码。 仅可在安全、封闭的网络中使用此示例。
@end quotation
@end cartouche

@example
import datetime

class ExampleService:
    def getData(self):
        return '42'

    class currentTime:
        @@staticmethod
        def getCurrentTime():
            return datetime.datetime.now()

with SimpleXMLRPCServer(("localhost", 8000)) as server:
    server.register_function(pow)
    server.register_function(lambda x,y: x+y, 'add')
    server.register_instance(ExampleService(), allow_dotted_names=True)
    server.register_multicall_functions()
    print('Serving XML-RPC on localhost port 8000')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nKeyboard interrupt received, exiting.")
        sys.exit(0)
@end example

这个 ExampleService 演示程序可通过命令行发起调用:

@example
python -m xmlrpc.server
@end example

可与上述服务器进行交互的客户端包括在 @cite{Lib/xmlrpc/client.py} 中:

@example
server = ServerProxy("http://localhost:8000")

try:
    print(server.currentTime.getCurrentTime())
except Error as v:
    print("ERROR", v)

multi = MultiCall(server)
multi.getData()
multi.pow(2,9)
multi.add(1,2)
try:
    for response in multi():
        print(response)
except Error as v:
    print("ERROR", v)
@end example

这个可与示例 XMLRPC 服务器进行交互的客户端的启动方式如下:

@example
python -m xmlrpc.client
@end example

@node CGIXMLRPCRequestHandler,XMLRPC 服务器文档,SimpleXMLRPCServer 对象,xmlrpc server --- 基本 XML-RPC 服务器
@anchor{library/xmlrpc server cgixmlrpcrequesthandler}@anchor{2fa1}
@subsubsection CGIXMLRPCRequestHandler


@ref{2f97,,CGIXMLRPCRequestHandler} 类可被用来处理发送给 Python CGI 脚本的 XML-RPC 请求。

@geindex register_function() (xmlrpc.server.CGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_function}@anchor{2fa2}
@deffn {方法} CGIXMLRPCRequestHandler.register_function (function=None, name=None)

注册一个可以响应 XML-RPC 请求的函数。 如果给出了 @emph{name}，则它将成为与 @emph{function} 相关联的方法名，否则将使用 @code{function.__name__}。 @emph{name} 是一个字符串，并可能包含不可在 Python 标识符中出现的字符，包括句点符。

此方法也可被用作装饰器。 当被用作装饰器时，@emph{name} 只能被指定为以 @emph{name} 注册的 @emph{function} 的一个关键字参数。 如果没有指定 @emph{name}，则将使用 @code{function.__name__}。


在 3.7 版更改: @ref{2fa2,,register_function()} 可被用作装饰器。

@end deffn

@geindex register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_instance}@anchor{2fa3}
@deffn {方法} CGIXMLRPCRequestHandler.register_instance (instance)

注册一个对象用来公开未使用 @ref{2fa2,,register_function()} 进行注册的方法名。 如果实例包含 @code{_dispatch()} 方法，它会附带所请求的方法名和来自请求的形参被调用；返回值会作为结果被返回给客户端。 如果实例不包含 @code{_dispatch()} 方法，则在其中搜索与所请求方法名相匹配的属性；如果所请求方法名包含句点，则会分别搜索方法名的每个部分，其效果就是执行了简单的层级搜索。 搜索找到的值将附带来自请求的形参被调用，其返回值会被返回给客户端。
@end deffn

@geindex register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_introspection_functions}@anchor{2fa4}
@deffn {方法} CGIXMLRPCRequestHandler.register_introspection_functions ()

注册 XML-RPC 内海函数 @code{system.listMethods}, @code{system.methodHelp} 和  @code{system.methodSignature}。
@end deffn

@geindex register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_multicall_functions}@anchor{2fa5}
@deffn {方法} CGIXMLRPCRequestHandler.register_multicall_functions ()

注册 XML-RPC 多调用函数 @code{system.multicall}。
@end deffn

@geindex handle_request() (xmlrpc.server.CGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler handle_request}@anchor{2fa6}
@deffn {方法} CGIXMLRPCRequestHandler.handle_request (request_text=None)

处理一个 XML-RPC 请求。 如果给出了 @emph{request_text}，它应当是 HTTP 服务器所提供的 POST 数据，否则将使用 stdin 的内容。
@end deffn

示例:

@example
class MyFuncs:
    def mul(self, x, y):
        return x * y


handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()
@end example

@node XMLRPC 服务器文档,DocXMLRPCServer 对象,CGIXMLRPCRequestHandler,xmlrpc server --- 基本 XML-RPC 服务器
@anchor{library/xmlrpc server documenting-xmlrpc-server}@anchor{2fa7}
@subsubsection XMLRPC 服务器文档


这些类扩展了上面的类以发布响应 HTTP GET 请求的 HTML 文档。 服务器可以是独立的，使用 @ref{1105,,DocXMLRPCServer}，或是嵌入某个 CGI 环境中，使用 @ref{2fa8,,DocCGIXMLRPCRequestHandler}。

@geindex DocXMLRPCServer (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer}@anchor{1105}
@deffn {类} xmlrpc.server.DocXMLRPCServer (addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)

创建一个新的服务器实例。 所有形参的含义与 @ref{2f96,,SimpleXMLRPCServer} 的相同；@emph{requestHandler} 默认为 @ref{2fa9,,DocXMLRPCRequestHandler}。


在 3.3 版更改: 增加了 @emph{use_builtin_types} 旗标。

@end deffn

@geindex DocCGIXMLRPCRequestHandler (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler}@anchor{2fa8}
@deffn {类} xmlrpc.server.DocCGIXMLRPCRequestHandler

创建一个新的实例来处理 CGI 环境中的 XML-RPC 请求。
@end deffn

@geindex DocXMLRPCRequestHandler (xmlrpc.server 中的类)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCRequestHandler}@anchor{2fa9}
@deffn {类} xmlrpc.server.DocXMLRPCRequestHandler

创建一个新的请求处理句柄实例。 该请求处理句柄支持 XML-RPC POST 请求、文档 GET 请求并会修改日志记录操作以便使用传递给 @ref{1105,,DocXMLRPCServer} 构造器形参的 @emph{logRequests} 形参。
@end deffn

@node DocXMLRPCServer 对象,DocCGIXMLRPCRequestHandler,XMLRPC 服务器文档,xmlrpc server --- 基本 XML-RPC 服务器
@anchor{library/xmlrpc server doc-xmlrpc-servers}@anchor{2faa}@anchor{library/xmlrpc server docxmlrpcserver-objects}@anchor{2fab}
@subsubsection DocXMLRPCServer 对象


@ref{1105,,DocXMLRPCServer} 类派生自 @ref{2f96,,SimpleXMLRPCServer} 并提供了一种创建自动记录文档的、独立的 XML-RPC 服务器的方式。 HTTP POST 请求将作为 XML-RPC 方法调用来处理。 HTTP GET 请求将通过生成 pydoc 风格的 HTML 文档来处理。 这将允许服务器自己提供基于 Web 的文档。

@geindex set_server_title() (xmlrpc.server.DocXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_title}@anchor{2fac}
@deffn {方法} DocXMLRPCServer.set_server_title (server_title)

设置所生成 HTML 文档要使用的标题。 此标题将在 HTML "title" 元素中使用。
@end deffn

@geindex set_server_name() (xmlrpc.server.DocXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_name}@anchor{2fad}
@deffn {方法} DocXMLRPCServer.set_server_name (server_name)

设置所生成 HTML 文档要使用的名称。 此名称将出现在所生成文档顶部的 "h1" 元素中。
@end deffn

@geindex set_server_documentation() (xmlrpc.server.DocXMLRPCServer 方法)
@anchor{library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_documentation}@anchor{2fae}
@deffn {方法} DocXMLRPCServer.set_server_documentation (server_documentation)

设置所生成Set the description used in the generated HTML 文档要使用的描述。 此描述将显示为文档中的一个段落，位于服务器名称之下。
@end deffn

@node DocCGIXMLRPCRequestHandler,,DocXMLRPCServer 对象,xmlrpc server --- 基本 XML-RPC 服务器
@anchor{library/xmlrpc server doccgixmlrpcrequesthandler}@anchor{2faf}
@subsubsection DocCGIXMLRPCRequestHandler


@ref{2fa8,,DocCGIXMLRPCRequestHandler} 类派生自 @ref{2f97,,CGIXMLRPCRequestHandler} 并提供了一种创建自动记录文档的 XML-RPC CGI 脚本的方式。 HTTP POST 请求将作为 XML-RPC 方法调用来处理。 HTTP GET 请求将通过生成 pydoc 风格的 HTML 文档来处理。 这将允许服务器自己提供基于 Web 的文档。

@geindex set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_title}@anchor{2fb0}
@deffn {方法} DocCGIXMLRPCRequestHandler.set_server_title (server_title)

设置所生成 HTML 文档要使用的标题。 此标题将在 HTML "title" 元素中使用。
@end deffn

@geindex set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_name}@anchor{2fb1}
@deffn {方法} DocCGIXMLRPCRequestHandler.set_server_name (server_name)

设置所生成 HTML 文档要使用的名称。 此名称将出现在所生成文档顶部的 "h1" 元素中。
@end deffn

@geindex set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler 方法)
@anchor{library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_documentation}@anchor{2fb2}
@deffn {方法} DocCGIXMLRPCRequestHandler.set_server_documentation (server_documentation)

设置所生成Set the description used in the generated HTML 文档要使用的描述。 此描述将显示为文档中的一个段落，位于服务器名称之下。
@end deffn

@node ipaddress --- IPv4/IPv6 操作库,,xmlrpc server --- 基本 XML-RPC 服务器,互联网协议和支持
@anchor{library/ipaddress doc}@anchor{2fb3}@anchor{library/ipaddress ipaddress-ipv4-ipv6-manipulation-library}@anchor{2fb4}@anchor{library/ipaddress module-ipaddress}@anchor{a2}
@subsection @code{ipaddress} --- IPv4/IPv6 操作库


@geindex ipaddress (模块)

@strong{源代码：} Lib/ipaddress.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/ipaddress.py}


__________________________________________________________________


@ref{a2,,ipaddress} 提供了创建、处理和操作 IPv4 和 IPv6 地址和网络的功能。

该模块中的函数和类可以直接处理与IP地址相关的各种任务，包括检查两个主机是否在同一个子网中，遍历某个子网中的所有主机，检查一个字符串是否是一个有效的IP地址或网络定义等等。

这是完整的模块 API 参考—若要查看概述，请见 @ref{2fb5,,ipaddress模块介绍}.


3.3 新版功能.


@c import ipaddress
@c from ipaddress import (
@c     ip_network, IPv4Address, IPv4Interface, IPv4Network,
@c )

@menu
* 方便的工厂函数:: 
* IP 地址:: 
* IP网络的定义:: 
* 接口对象:: 
* 其他模块级别函数:: 
* 自定义异常:: 

@end menu

@node 方便的工厂函数,IP 地址,,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress convenience-factory-functions}@anchor{2fb6}
@subsubsection 方便的工厂函数


@ref{a2,,ipaddress} 模块提供来工厂函数来方便地创建 IP 地址，网络和接口：

@geindex ip_address() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress ip_address}@anchor{2fb7}
@deffn {函数} ipaddress.ip_address (address)

返回一个 @ref{2fb8,,IPv4Address} 或 @ref{1bc,,IPv6Address} 对象，取决于作为参数传递的 IP 地址。可以提供IPv4或IPv6地址，小于 @code{2**32} 的整数默认被认为是 IPv4。如果 @emph{address} 不是有效的 IPv4 或 IPv6 地址，则会抛出 @ref{16d,,ValueError}。

@example
>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')
@end example
@end deffn

@geindex ip_network() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress ip_network}@anchor{2fb9}
@deffn {函数} ipaddress.ip_network (address, strict=True)

返回一个 @ref{4af,,IPv4Network} 或 @ref{4ae,,IPv6Network} 对象，具体取决于作为参数传入的 IP 地址。 @emph{address} 是表示 IP 网址的字符串或整数。 可以提供 IPv4 或 IPv6 网址；小于 @code{2**32} 的整数默认被视为 IPv4。 @emph{strict} 会被传给 @ref{4af,,IPv4Network} 或 @ref{4ae,,IPv6Network} 构造器。 如果 @emph{address} 不表示有效的 IPv4 或 IPv6 网址，或者网络设置了 host 比特位，则会引发 @ref{16d,,ValueError}。

@example
>>> ipaddress.ip_network('192.168.0.0/28')
IPv4Network('192.168.0.0/28')
@end example
@end deffn

@geindex ip_interface() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress ip_interface}@anchor{2fba}
@deffn {函数} ipaddress.ip_interface (address)

返回一个 @ref{f7f,,IPv4Interface} 或 @ref{f80,,IPv6Interface} 对象，取决于作为参数传递的 IP 地址。 @emph{address} 是代表 IP 地址的字符串或整数。 可以提供 IPv4 或 IPv6 地址，小于 @code{2**32} 的整数默认认为是 IPv4。 如果 @emph{address} 不是有效的IPv4 或 IPv6 地址，则会抛出一个 @ref{16d,,ValueError}。
@end deffn

这些方便的函数的一个缺点是需要同时处理IPv4和IPv6格式，这意味着提供的错误信息并不精准，因为函数不知道是打算采用IPv4还是IPv6格式。更详细的错误报告可以通过直接调用相应版本的类构造函数来获得。

@node IP 地址,IP网络的定义,方便的工厂函数,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress ip-addresses}@anchor{2fbb}
@subsubsection IP 地址


@menu
* 地址对象:: 
* 转换字符串和整数:: 
* 运算符: 运算符<3>. 

@end menu

@node 地址对象,转换字符串和整数,,IP 地址
@anchor{library/ipaddress address-objects}@anchor{2fbc}
@subsubsection 地址对象


@ref{2fb8,,IPv4Address} 和 @ref{1bc,,IPv6Address} 对象有很多共同的属性。一些只对IPv6 地址有意义的属性也在 @ref{2fb8,,IPv4Address} 对象实现，以便更容易编写正确处理两种 IP 版本的代码。地址对象是可哈希的 @ref{277,,hashable}，所以它们可以作为字典中的键来使用。

@geindex IPv4Address (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv4Address}@anchor{2fb8}
@deffn {类} ipaddress.IPv4Address (address)

构造一个 IPv4 地址。 如果 @emph{address} 不是一个有效的 IPv4 地址，会抛出 @ref{2fbd,,AddressValueError} 。

以下是有效的 IPv4 地址：


@enumerate 

@item 
以十进制小数点表示的字符串，由四个十进制整数组成，范围为0--255，用点隔开(例如 @code{192.168.0.1} )。每个整数代表地址中的八位（一个字节）。不允许使用前导零，以免与八进制表示产生歧义。

@item 
一个32位可容纳的整数。

@item 
一个长度为 4 的封装在 @ref{172,,bytes} 对象中的整数(高位优先)。
@end enumerate

@example
>>> ipaddress.IPv4Address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(3232235521)
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
IPv4Address('192.168.0.1')
@end example


在 3.8 版更改: 前导零可被接受，即使是在可能与八进制表示混淆的情况下也会被接受。



在 3.10 版更改: 前导零不再被接受，并且会被视作错误。IPv4地址字符串现在严格按照glibc的 @ref{238,,inet_pton()} 函数进行解析。



在 3.9.5 版更改: 上述变更也在自3.9.5版本起的Python 3.9当中被包含。



在 3.8.12 版更改: 从3.8.12版本开始，Python 3.8中也包含了上述变化。


@geindex version (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address version}@anchor{2fbe}
@deffn {属性} version

合适的版本号：IPv4为 @code{4} ，IPv6为 @code{6} 。
@end deffn

@geindex max_prefixlen (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address max_prefixlen}@anchor{2fbf}
@deffn {属性} max_prefixlen

在该版本的地址表示中，比特数的总数：IPv4为 @code{32} ；IPv6为 @code{128} 。

前缀定义了地址中的前导位数量，通过比较来确定一个地址是否是网络的一部分。
@end deffn

@geindex compressed (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address compressed}@anchor{2fc0}
@deffn {属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address exploded}@anchor{2fc1}
@deffn {属性} exploded

以点符号分割十进制表示的字符串。表示中不包括前导零。

由于IPv4没有为八位数设为零的地址定义速记符号，这两个属性始终与IPv4地址的`@w{`}str(addr)`@w{`}相同。暴露这些属性使得编写能够处理IPv4和IPv6地址的显示代码变得更加容易。
@end deffn

@geindex packed (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address packed}@anchor{2fc2}
@deffn {属性} packed

这个地址的二进制表示——一个适当长度的 @ref{172,,bytes} 对象（最高的八位在最前）。  对于 IPv4 来说是 4 字节，对于 IPv6 来说是 16 字节。
@end deffn

@geindex reverse_pointer (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address reverse_pointer}@anchor{2fc3}
@deffn {属性} reverse_pointer

IP地址的反向DNS PTR记录的名称，例如:

@example
>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
@end example

这是可用于执行PTR查询的名称，而不是已解析的主机名本身。


3.5 新版功能.

@end deffn

@geindex is_multicast (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_multicast}@anchor{2fc4}
@deffn {属性} is_multicast

如果该地址被保留用作多播用途，返回 @code{True} 。关于多播地址，请参见 
@geindex RFC; RFC 3171
RFC 3171@footnote{https://tools.ietf.org/html/rfc3171.html} （IPv4）和 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://tools.ietf.org/html/rfc2373.html} （IPv6）。
@end deffn

@geindex is_private (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_private}@anchor{2fc5}
@deffn {属性} is_private

如果该地址被分配至私有网络，返回 @code{True} 。关于公共网络，请参见 iana-ipv4-special-registry@footnote{https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml} （针对IPv4）和 iana-ipv6-special-registry@footnote{https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml} （针对IPv6）。
@end deffn

@geindex is_global (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_global}@anchor{960}
@deffn {属性} is_global

如果该地址被分配至公共网络，返回 @code{True} 。关于公共网络，请参见 iana-ipv4-special-registry@footnote{https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml} （针对IPv4）和 iana-ipv6-special-registry@footnote{https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml} （针对IPv6）。


3.4 新版功能.

@end deffn

@geindex is_unspecified (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_unspecified}@anchor{2fc6}
@deffn {属性} is_unspecified

当地址未指定时为`@w{`}True`@w{`} 。  参见 
@geindex RFC; RFC 5735
RFC 5735@footnote{https://tools.ietf.org/html/rfc5735.html} (IPv4) 或 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://tools.ietf.org/html/rfc2373.html} (IPv6).
@end deffn

@geindex is_reserved (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_reserved}@anchor{2fc7}
@deffn {属性} is_reserved

如果该地址属于互联网工程任务组（IETF）所规定的其他保留地址，返回 @code{True} 。
@end deffn

@geindex is_loopback (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_loopback}@anchor{2fc8}
@deffn {属性} is_loopback

如果该地址为一个回环地址，返回 @code{True} 。关于回环地址，请见 
@geindex RFC; RFC 3330
RFC 3330@footnote{https://tools.ietf.org/html/rfc3330.html} （IPv4）和 
@geindex RFC; RFC 2373
RFC 2373@footnote{https://tools.ietf.org/html/rfc2373.html} （IPv6）。
@end deffn

@geindex is_link_local (ipaddress.IPv4Address 属性)
@anchor{library/ipaddress ipaddress IPv4Address is_link_local}@anchor{2fc9}
@deffn {属性} is_link_local

如果该地址被保留用于本地链接则为 @code{True}。 参见 
@geindex RFC; RFC 3927
RFC 3927@footnote{https://tools.ietf.org/html/rfc3927.html}。
@end deffn
@end deffn

@geindex __format__() (ipaddress.IPv4Address 方法)
@anchor{library/ipaddress ipaddress IPv4Address __format__}@anchor{2fca}
@deffn {方法} IPv4Address.__format__ (fmt)

返回一个IP地址的字符串表示，由一个明确的格式字符串控制。@emph{fmt} 可以是以下之一: @code{'s'}，默认选项，相当于 @ref{206,,str()}，@code{'b'} 用于零填充的二进制字符串，@code{'X'} 或者 @code{'x'} 用于大写或小写的十六进制表示，或者 @code{'n'} 相当于 @code{'b'} 用于 IPv4 地址和 @code{'x'} 用于 IPv6 地址。 对于二进制和十六进制表示法，可以使用形式指定器 @code{'#'} 和分组选项 @code{'_'}。 @code{__format__} 被 @code{format}、 @code{str.format} 和 f 字符串使用。

@example
>>> format(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> '@{:#b@}'.format(ipaddress.IPv4Address('192.168.0.1'))
'0b11000000101010000000000000000001'
>>> f'@{ipaddress.IPv6Address("2001:db8::1000"):s@}'
'2001:db8::1000'
>>> format(ipaddress.IPv6Address('2001:db8::1000'), '_X')
'2001_0DB8_0000_0000_0000_0000_0000_1000'
>>> '@{:#_n@}'.format(ipaddress.IPv6Address('2001:db8::1000'))
'0x2001_0db8_0000_0000_0000_0000_0000_1000'
@end example


3.9 新版功能.

@end deffn

@geindex IPv6Address (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv6Address}@anchor{1bc}
@deffn {类} ipaddress.IPv6Address (address)

构造一个 IPv6 地址。 如果 @emph{address} 不是一个有效的 IPv6 地址，会抛出 @ref{2fbd,,AddressValueError} 。

以下是有效的 IPv6 地址：


@enumerate 

@item 
一个由八组四个16进制数字组成的字符串, 每组展示为16位. 以冒号分隔. 这可以描述为 @emph{分解} (普通书写).  此字符可以被 @emph{压缩} (速记书写) .  详见:RFC:@cite{4291} .  例如, @code{"0000:0000:0000:0000:0000:0abc:0007:0def"} 可以被精简为 @code{"::abc:7:def"}.

可选择的是，该字符串也可以有一个范围区ID，用后缀`@w{`}%scope_id`@w{`}表示。如果存在，范围ID必须是非空的，并且不能包含`@w{`}%`@w{`}。详见:RFC:@cite{4007}。例如，@code{fe80::1234%1`@w{`}可以识别节点第一条链路上的地址`@w{`}fe80::1234}

@item 
适合 128 位的整数.

@item 
一个打包在长度为 16 字节的大端序 @ref{172,,bytes} 对象中的整数。
@end enumerate

@example
>>> ipaddress.IPv6Address('2001:db8::1000')
IPv6Address('2001:db8::1000')
>>> ipaddress.IPv6Address('ff02::5678%1')
IPv6Address('ff02::5678%1')
@end example

@geindex compressed (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address compressed}@anchor{2fcb}
@deffn {属性} compressed
@end deffn

地址表示的简短形式，省略了组中的前导零，完全由零组成的最长的组序列被折叠成一个空组。

这也是`@w{`}str(addr)`@w{`}对IPv6地址返回的值。

@geindex exploded (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address exploded}@anchor{2fcc}
@deffn {属性} exploded
@end deffn

地址的长形式表示，包括所有前导零和完全由零组成的组。

关于以下属性和方法，请参见 @ref{2fb8,,IPv4Address} 类的相应文档。

@geindex packed (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address packed}@anchor{2fcd}
@deffn {属性} packed
@end deffn

@geindex reverse_pointer (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address reverse_pointer}@anchor{2fce}
@deffn {属性} reverse_pointer
@end deffn

@geindex version (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address version}@anchor{2fcf}
@deffn {属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address max_prefixlen}@anchor{2fd0}
@deffn {属性} max_prefixlen
@end deffn

@geindex is_multicast (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_multicast}@anchor{2fd1}
@deffn {属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_private}@anchor{2fd2}
@deffn {属性} is_private
@end deffn

@geindex is_global (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_global}@anchor{2fd3}
@deffn {属性} is_global
@end deffn

@geindex is_unspecified (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_unspecified}@anchor{2fd4}
@deffn {属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_reserved}@anchor{2fd5}
@deffn {属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_loopback}@anchor{2fd6}
@deffn {属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_link_local}@anchor{2fd7}
@deffn {属性} is_link_local


3.4 新版功能: is_global

@end deffn

@geindex is_site_local (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address is_site_local}@anchor{2fd8}
@deffn {属性} is_site_local

如果地址被保留用于本地站点则为 @code{True}。 请注意本地站点地址空间已被 
@geindex RFC; RFC 3879
RFC 3879@footnote{https://tools.ietf.org/html/rfc3879.html} 弃用。 请使用 @ref{2fc5,,is_private} 来检测此地址是否位于 
@geindex RFC; RFC 4193
RFC 4193@footnote{https://tools.ietf.org/html/rfc4193.html} 所定义的本地唯一地址空间中。
@end deffn

@geindex ipv4_mapped (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address ipv4_mapped}@anchor{2fd9}
@deffn {属性} ipv4_mapped

映射IPv4的地址 (起始为 @code{::FFFF/96}), 这一属性记录为嵌入IPv4地址. 其他的任何地址, 这一属性为 @code{None}.
@end deffn

@geindex scope_id (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address scope_id}@anchor{1bd}
@deffn {属性} scope_id

对于:RFC:@cite{4007`定义的作用域地址，此属性以字符串的形式确定地址所属的作用域的特定区域。当没有指定作用域时，该属性将是`@w{`}None`}。
@end deffn

@geindex sixtofour (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address sixtofour}@anchor{2fda}
@deffn {属性} sixtofour

对于看起来是6to4的地址（以`@w{`}2002::/16`@w{`}开头），如 
@geindex RFC; RFC 3056
RFC 3056@footnote{https://tools.ietf.org/html/rfc3056.html} 所定义的，此属性将返回嵌入的IPv4地址。 对于任何其他地址，该属性将是`@w{`}None`@w{`}。
@end deffn

@geindex teredo (ipaddress.IPv6Address 属性)
@anchor{library/ipaddress ipaddress IPv6Address teredo}@anchor{2fdb}
@deffn {属性} teredo

对于看起来是:RFC:@cite{4380`定义的Teredo地址（以`@w{`}2001::/32`@w{`}开头）的地址，此属性将返回嵌入式IP地址对`@w{`}(server@comma{} client)`}。 对于任何其他地址，该属性将是`@w{`}None`@w{`}。
@end deffn
@end deffn

@geindex __format__() (ipaddress.IPv6Address 方法)
@anchor{library/ipaddress ipaddress IPv6Address __format__}@anchor{2fdc}
@deffn {方法} IPv6Address.__format__ (fmt)

请参考 @ref{2fb8,,IPv4Address} 中对应的方法文档。


3.9 新版功能.

@end deffn

@node 转换字符串和整数,运算符<3>,地址对象,IP 地址
@anchor{library/ipaddress conversion-to-strings-and-integers}@anchor{2fdd}
@subsubsection 转换字符串和整数


与网络模块互操作像套接字模块, 地址必须转换为字符串或整数. 这是使用 @ref{206,,str()} 和 @ref{205,,int()} 内置函数:

@example
>>> str(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> int(ipaddress.IPv4Address('192.168.0.1'))
3232235521
>>> str(ipaddress.IPv6Address('::1'))
'::1'
>>> int(ipaddress.IPv6Address('::1'))
1
@end example

请注意，IPv6范围内的地址被转换为没有范围区域ID的整数。

@node 运算符<3>,,转换字符串和整数,IP 地址
@anchor{library/ipaddress operators}@anchor{2fde}
@subsubsection 运算符


地址对象支持一些运算符。 除非另有说明，运算符只能在兼容对象之间应用（即IPv4与IPv4，IPv6与IPv6）。

@menu
* 比较运算符:: 
* 算术运算符:: 

@end menu

@node 比较运算符,算术运算符,,运算符<3>
@anchor{library/ipaddress comparison-operators}@anchor{2fdf}
@subsubsection 比较运算符


地址对象可以用通常的一组比较运算符进行比较。具有不同范围区域ID的相同IPv6地址是不平等的。一些例子:

@example
>>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
True
>>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
False
>>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
True
>>> IPv6Address('fe80::1234') == IPv6Address('fe80::1234%1')
False
>>> IPv6Address('fe80::1234%1') != IPv6Address('fe80::1234%2')
True
@end example

@node 算术运算符,,比较运算符,运算符<3>
@anchor{library/ipaddress arithmetic-operators}@anchor{2fe0}
@subsubsection 算术运算符


整数可以被添加到地址对象或从地址对象中减去。 一些例子:

@example
>>> IPv4Address('127.0.0.2') + 3
IPv4Address('127.0.0.5')
>>> IPv4Address('127.0.0.2') - 3
IPv4Address('126.255.255.255')
>>> IPv4Address('255.255.255.255') + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
@end example

@node IP网络的定义,接口对象,IP 地址,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress ip-network-definitions}@anchor{2fe1}
@subsubsection IP网络的定义


@ref{4af,,IPv4Network} 和 @ref{4ae,,IPv6Network} 对象提供了一个定义和检查IP网络定义的机制。一个网络定义由一个 @emph{掩码} 和一个 @emph{网络地址} 组成，因此定义了一个IP地址的范围，当用掩码屏蔽（二进制AND）时，等于网络地址。 例如，一个带有掩码`@w{`}255.255.255.0`@w{`}和网络地址`@w{`}192.168.1.0`@w{`}的网络定义由包括`@w{`}192.168.1.0`@w{`}到`@w{`}192.168.1.255`@w{`}的IP地址组成。

@menu
* 前缀、网络掩码和主机掩码:: 
* 网络对象:: 
* 运算符: 运算符<4>. 

@end menu

@node 前缀、网络掩码和主机掩码,网络对象,,IP网络的定义
@anchor{library/ipaddress prefix-net-mask-and-host-mask}@anchor{2fe2}
@subsubsection 前缀、网络掩码和主机掩码


有几种相等的方法来指定IP网络掩码。 @emph{前缀} @code{/<nbits>`@w{`}是一个符号，表示在网络掩码中设置了多少个高阶位。 一个 *网络掩码* 是一个设置了一定数量高阶位的IP地址。 因此，前缀}/24`@w{`}等同于IPv4中的网络掩码`@w{`}255.255.255.0`@w{`}或IPv6中的网络掩码`@w{`}ffff:ff00::@code{。 此外，*主机掩码* 是 *网络掩码* 的逻辑取反，有时被用来表示网络掩码（例如在Cisco访问控制列表中）。 在IPv4中，相当于主机掩码`@w{`}0.0.0.255`@w{`}的是}/24`@w{`} 。

@node 网络对象,运算符<4>,前缀、网络掩码和主机掩码,IP网络的定义
@anchor{library/ipaddress network-objects}@anchor{2fe3}
@subsubsection 网络对象


所有由地址对象实现的属性也由网络对象实现。 此外，网络对象还实现了额外的属性。所有这些在 @ref{4af,,IPv4Network} 和 @ref{4ae,,IPv6Network} 之间是共同的，所以为了避免重复，它们只在 @ref{4af,,IPv4Network} 中记录。网络对象是 @ref{277,,hashable}，所以它们可以作为字典中的键使用。

@geindex IPv4Network (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv4Network}@anchor{4af}
@deffn {类} ipaddress.IPv4Network (address, strict=True)

构建一个 IPv4 网络定义。 @emph{address} 可以是以下之一：


@enumerate 

@item 
一个由 IP 地址和可选掩码组成的字符串，用斜线  (@code{/}) 分开。 IP 地址是网络地址，掩码可以是一个单一的数字，这意味着它是一个 @emph{前缀}，或者是一个 IPv4 地址的字符串表示。 如果是后者，如果掩码以非零字段开始，则被解释为 @emph{网络掩码}，如果以零字段开始，则被解释为 @emph{主机掩码}，唯一的例外是全零的掩码被视为 @emph{网络掩码}。 如果没有提供掩码，它就被认为是 @code{/32}。

例如，以下的*地址*描述是等同的：@code{192.168.1.0/24}，@code{192.168.1.0/255.255.255.0`@w{`}和`@w{`}192.168.1.0/0.0.0.255}

@item 
一个可转化为32位的整数。 这相当于一个单地址的网络，网络地址是*address*，掩码是`@w{`}/32`@w{`}。

@item 
一个整数被打包成一个长度为 4 的大端序 @ref{172,,bytes} 对象。 其解释类似于一个整数 @emph{address}。

@item 
一个地址描述和一个网络掩码的双元组，其中地址描述是一个字符串，一个 32 位的整数，一个 4 字节的打包整数，或一个现有的 IPv4Address 对象；而网络掩码是一个代表前缀长度的整数 (例如 @code{24}) 或一个代表前缀掩码的字符串 (例如 @code{255.255.255.0})。
@end enumerate

如果 @emph{address} 不是一个有效的 IPv4 地址则会引发 @ref{2fbd,,AddressValueError}。 如果掩码不是有效的 IPv4 地址则会引发 @ref{2fe4,,NetmaskValueError}。

如果 @emph{strict} 是 @code{True}，并且在提供的地址中设置了主机位，那么 @ref{16d,,ValueError} 将被触发。 否则，主机位将被屏蔽掉，以确定适当的网络地址。

除非另有说明，如果参数的 IP 版本与 @code{self} 不兼容，所有接受其他网络/地址对象的网络方法都将引发 @ref{1ff,,TypeError}。


在 3.5 版更改: 为*address*构造函数参数添加了双元组形式。


@geindex version (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network version}@anchor{2fe5}
@deffn {属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network max_prefixlen}@anchor{2fe6}
@deffn {属性} max_prefixlen

请参考 @ref{2fb8,,IPv4Address} 中的相应属性文档。
@end deffn

@geindex is_multicast (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_multicast}@anchor{2fe7}
@deffn {属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_private}@anchor{2fe8}
@deffn {属性} is_private
@end deffn

@geindex is_unspecified (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_unspecified}@anchor{2fe9}
@deffn {属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_reserved}@anchor{2fea}
@deffn {属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_loopback}@anchor{2feb}
@deffn {属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network is_link_local}@anchor{2fec}
@deffn {属性} is_link_local

如果这些属性对网络地址和广播地址都是真实的，那么它们对整个网络来说就是真实的。
@end deffn

@geindex network_address (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network network_address}@anchor{2fed}
@deffn {属性} network_address

网络的网络地址。网络地址和前缀长度一起唯一地定义了一个网络。
@end deffn

@geindex broadcast_address (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network broadcast_address}@anchor{2fee}
@deffn {属性} broadcast_address

网络的广播地址。发送到广播地址的数据包应该被网络上的每台主机所接收。
@end deffn

@geindex hostmask (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network hostmask}@anchor{2fef}
@deffn {属性} hostmask

主机掩码，作为一个 @ref{2fb8,,IPv4Address} 对象。
@end deffn

@geindex netmask (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network netmask}@anchor{2ff0}
@deffn {属性} netmask

网络掩码，作为一个 @ref{2fb8,,IPv4Address} 对象。
@end deffn

@geindex with_prefixlen (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network with_prefixlen}@anchor{2ff1}
@deffn {属性} with_prefixlen
@end deffn

@geindex compressed (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network compressed}@anchor{2ff2}
@deffn {属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network exploded}@anchor{2ff3}
@deffn {属性} exploded

网络的字符串表示，其中掩码为前缀符号。

@code{with_prefixlen} 和 @code{compressed} 总是与 @code{str(network)} 相同，@code{exploded} 使用分解形式的网络地址。
@end deffn

@geindex with_netmask (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network with_netmask}@anchor{2ff4}
@deffn {属性} with_netmask

网络的字符串表示，掩码用net mask符号表示。
@end deffn

@geindex with_hostmask (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network with_hostmask}@anchor{2ff5}
@deffn {属性} with_hostmask

网络的字符串表示，其中的掩码为主机掩码符号。
@end deffn

@geindex num_addresses (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network num_addresses}@anchor{2ff6}
@deffn {属性} num_addresses

网络中的地址总数。
@end deffn

@geindex prefixlen (ipaddress.IPv4Network 属性)
@anchor{library/ipaddress ipaddress IPv4Network prefixlen}@anchor{2ff7}
@deffn {属性} prefixlen

网络前缀的长度，以比特为单位。
@end deffn

@geindex hosts() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network hosts}@anchor{2ff8}
@deffn {方法} hosts ()

返回一个网络中可用主机的迭代器。 可用的主机是属于该网络的所有IP地址，除了网络地址本身和网络广播地址。 对于掩码长度为31的网络，网络地址和网络广播地址也包括在结果中。掩码为32的网络将返回一个包含单一主机地址的列表。

@example
>>> list(ip_network('192.0.2.0/29').hosts())  
[IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'),
 IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'),
 IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')]
>>> list(ip_network('192.0.2.0/31').hosts())
[IPv4Address('192.0.2.0'), IPv4Address('192.0.2.1')]
>>> list(ip_network('192.0.2.1/32').hosts())
[IPv4Address('192.0.2.1')]
@end example
@end deffn

@geindex overlaps() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network overlaps}@anchor{2ff9}
@deffn {方法} overlaps (other)

如果这个网络部分或全部包含在*other*中，或者*other*全部包含在这个网络中，则为`@w{`}True`@w{`}。
@end deffn

@geindex address_exclude() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network address_exclude}@anchor{2ffa}
@deffn {方法} address_exclude (network)

计算从这个网络中移除给定的 @emph{network} 后产生的网络定义。 返回一个网络对象的迭代器。 如果 @emph{network} 不完全包含在这个网络中则会引发 @ref{16d,,ValueError}。

@example
>>> n1 = ip_network('192.0.2.0/28')
>>> n2 = ip_network('192.0.2.1/32')
>>> list(n1.address_exclude(n2))  
[IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
 IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]
@end example
@end deffn

@geindex subnets() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network subnets}@anchor{890}
@deffn {方法} subnets (prefixlen_diff=1, new_prefix=None)

根据参数值，加入的子网构成当前的网络定义。 @emph{prefixlen_diff} 是我们的前缀长度应该增加的数量。 @emph{new_prefix} 是所需的子网的新前缀；它必须大于我们的前缀。 必须设置 @emph{prefixlen_diff} 和 @emph{new_prefix} 中的一个，且只有一个。 返回一个网络对象的迭代器。

@example
>>> list(ip_network('192.0.2.0/24').subnets())
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
>>> list(ip_network('192.0.2.0/24').subnets(prefixlen_diff=2))  
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=26))  
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=23))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise ValueError('new prefix must be longer')
ValueError: new prefix must be longer
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=25))
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
@end example
@end deffn

@geindex supernet() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network supernet}@anchor{891}
@deffn {方法} supernet (prefixlen_diff=1, new_prefix=None)

包含这个网络定义的超级网，取决于参数值。 @emph{prefixlen_diff} 是我们的前缀长度应该减少的数量。 @emph{new_prefix} 是超级网的新前缀；它必须比我们的前缀小。 必须设置 @emph{prefixlen_diff} 和 @emph{new_prefix} 中的一个，而且只有一个。 返回一个单一的网络对象。

@example
>>> ip_network('192.0.2.0/24').supernet()
IPv4Network('192.0.2.0/23')
>>> ip_network('192.0.2.0/24').supernet(prefixlen_diff=2)
IPv4Network('192.0.0.0/22')
>>> ip_network('192.0.2.0/24').supernet(new_prefix=20)
IPv4Network('192.0.0.0/20')
@end example
@end deffn

@geindex subnet_of() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network subnet_of}@anchor{2ffb}
@deffn {方法} subnet_of (other)

如果这个网络是*other*的子网，则返回`@w{`}True`@w{`}。

@example
>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> b.subnet_of(a)
True
@end example


3.7 新版功能.

@end deffn

@geindex supernet_of() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network supernet_of}@anchor{2ffc}
@deffn {方法} supernet_of (other)

如果这个网络是*other*的超网，则返回`@w{`}True`@w{`}。

@example
>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> a.supernet_of(b)
True
@end example


3.7 新版功能.

@end deffn

@geindex compare_networks() (ipaddress.IPv4Network 方法)
@anchor{library/ipaddress ipaddress IPv4Network compare_networks}@anchor{2ffd}
@deffn {方法} compare_networks (other)

将这个网络与*ohter*网络进行比较。 在这个比较中，只考虑网络地址；不考虑主机位。 返回是`@w{`}-1`@w{`} 、 @code{0`@w{`}或`@w{`}1}。

@example
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.2/32'))
-1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.0/32'))
1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.1/32'))
0
@end example


3.7 版后已移除: 它使用与"<"、"=="和">"相同的排序和比较算法。

@end deffn
@end deffn

@geindex IPv6Network (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv6Network}@anchor{4ae}
@deffn {类} ipaddress.IPv6Network (address, strict=True)

构建一个 IPv6 网络定义。 @emph{address} 可以是以下之一：


@enumerate 

@item 
一个由IP地址和可选前缀长度组成的字符串，用斜线（@code{/}）分开。 IP地址是网络地址，前缀长度必须是一个数字，即*prefix*。 如果没有提供前缀长度，就认为是`@w{`}/128`@w{`}。

请注意，目前不支持扩展的网络掩码。 这意味着 @code{2001:db00::0/24} 是一个有效的参数，而 @code{2001:db00::0/ffff:ff00::} 不是。

@item 
一个适合128位的整数。 这相当于一个单地址网络，网络地址是*address*，掩码是`@w{`}/128`@w{`}。

@item 
一个整数被打包成一个长度为 16 的大端序 @ref{172,,bytes} 对象。 其解释类似于一个整数的 @emph{address}。

@item 
一个地址描述和一个网络掩码的双元组，其中地址描述是一个字符串，一个 128 位的整数，一个 16 字节的打包整数，或者一个现有的 IPv6Address 对象；而网络掩码是一个代表前缀长度的整数。
@end enumerate

如果 @emph{address} 不是一个有效的 IPv6 地址则会引发 @ref{2fbd,,AddressValueError}。 如果掩码对 IPv6 地址无效则会引发 @ref{2fe4,,NetmaskValueError}。

如果 @emph{strict} 是 @code{True}，并且在提供的地址中设置了主机位，那么 @ref{16d,,ValueError} 将被触发。 否则，主机位将被屏蔽掉，以确定适当的网络地址。


在 3.5 版更改: 为*address*构造函数参数添加了双元组形式。


@geindex version (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network version}@anchor{2ffe}
@deffn {属性} version
@end deffn

@geindex max_prefixlen (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network max_prefixlen}@anchor{2fff}
@deffn {属性} max_prefixlen
@end deffn

@geindex is_multicast (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_multicast}@anchor{3000}
@deffn {属性} is_multicast
@end deffn

@geindex is_private (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_private}@anchor{3001}
@deffn {属性} is_private
@end deffn

@geindex is_unspecified (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_unspecified}@anchor{3002}
@deffn {属性} is_unspecified
@end deffn

@geindex is_reserved (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_reserved}@anchor{3003}
@deffn {属性} is_reserved
@end deffn

@geindex is_loopback (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_loopback}@anchor{3004}
@deffn {属性} is_loopback
@end deffn

@geindex is_link_local (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_link_local}@anchor{3005}
@deffn {属性} is_link_local
@end deffn

@geindex network_address (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network network_address}@anchor{3006}
@deffn {属性} network_address
@end deffn

@geindex broadcast_address (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network broadcast_address}@anchor{3007}
@deffn {属性} broadcast_address
@end deffn

@geindex hostmask (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network hostmask}@anchor{3008}
@deffn {属性} hostmask
@end deffn

@geindex netmask (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network netmask}@anchor{3009}
@deffn {属性} netmask
@end deffn

@geindex with_prefixlen (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network with_prefixlen}@anchor{300a}
@deffn {属性} with_prefixlen
@end deffn

@geindex compressed (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network compressed}@anchor{300b}
@deffn {属性} compressed
@end deffn

@geindex exploded (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network exploded}@anchor{300c}
@deffn {属性} exploded
@end deffn

@geindex with_netmask (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network with_netmask}@anchor{300d}
@deffn {属性} with_netmask
@end deffn

@geindex with_hostmask (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network with_hostmask}@anchor{300e}
@deffn {属性} with_hostmask
@end deffn

@geindex num_addresses (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network num_addresses}@anchor{300f}
@deffn {属性} num_addresses
@end deffn

@geindex prefixlen (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network prefixlen}@anchor{3010}
@deffn {属性} prefixlen
@end deffn

@geindex hosts() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network hosts}@anchor{3011}
@deffn {方法} hosts ()

返回一个网络中可用主机的迭代器。 可用的主机是属于该网络的所有IP地址，除了Subnet-Router任播的地址。 对于掩码长度为127的网络，子网-路由器任播地址也包括在结果中。掩码为128的网络将返回一个包含单一主机地址的列表。
@end deffn

@geindex overlaps() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network overlaps}@anchor{3012}
@deffn {方法} overlaps (other)
@end deffn

@geindex address_exclude() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network address_exclude}@anchor{3013}
@deffn {方法} address_exclude (network)
@end deffn

@geindex subnets() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network subnets}@anchor{3014}
@deffn {方法} subnets (prefixlen_diff=1, new_prefix=None)
@end deffn

@geindex supernet() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network supernet}@anchor{3015}
@deffn {方法} supernet (prefixlen_diff=1, new_prefix=None)
@end deffn

@geindex subnet_of() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network subnet_of}@anchor{3016}
@deffn {方法} subnet_of (other)
@end deffn

@geindex supernet_of() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network supernet_of}@anchor{3017}
@deffn {方法} supernet_of (other)
@end deffn

@geindex compare_networks() (ipaddress.IPv6Network 方法)
@anchor{library/ipaddress ipaddress IPv6Network compare_networks}@anchor{3018}
@deffn {方法} compare_networks (other)

请参考 @ref{4af,,IPv4Network} 中的相应属性文档。
@end deffn

@geindex is_site_local (ipaddress.IPv6Network 属性)
@anchor{library/ipaddress ipaddress IPv6Network is_site_local}@anchor{3019}
@deffn {属性} is_site_local

如果这些属性对网络地址和广播地址都是真的，那么对整个网络来说就是真的。
@end deffn
@end deffn

@node 运算符<4>,,网络对象,IP网络的定义
@anchor{library/ipaddress id1}@anchor{301a}
@subsubsection 运算符


网络对象支持一些操作符。 除非另有说明，操作符只能在兼容的对象之间应用（例如，IPv4与IPv4，IPv6与IPv6）。

@menu
* 逻辑操作符:: 
* 迭代: 迭代<2>. 
* 作为地址容器的网络:: 

@end menu

@node 逻辑操作符,迭代<2>,,运算符<4>
@anchor{library/ipaddress logical-operators}@anchor{301b}
@subsubsection 逻辑操作符


网络对象可以用常规的逻辑运算符集进行比较。网络对象首先按网络地址排序，然后按网络掩码排序。

@node 迭代<2>,作为地址容器的网络,逻辑操作符,运算符<4>
@anchor{library/ipaddress iteration}@anchor{301c}
@subsubsection 迭代


网络对象可以被迭代，以列出属于该网络的所有地址。 对于迭代，@emph{所有} 主机都会被返回，包括不可用的主机（对于可用的主机，使用 @ref{2ff8,,hosts()} 方法）。 一个例子:

@example
>>> for addr in IPv4Network('192.0.2.0/28'):
...     addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
IPv4Address('192.0.2.7')
IPv4Address('192.0.2.8')
IPv4Address('192.0.2.9')
IPv4Address('192.0.2.10')
IPv4Address('192.0.2.11')
IPv4Address('192.0.2.12')
IPv4Address('192.0.2.13')
IPv4Address('192.0.2.14')
IPv4Address('192.0.2.15')
@end example

@node 作为地址容器的网络,,迭代<2>,运算符<4>
@anchor{library/ipaddress networks-as-containers-of-addresses}@anchor{301d}
@subsubsection 作为地址容器的网络


网络对象可以作为地址的容器。 一些例子:

@example
>>> IPv4Network('192.0.2.0/28')[0]
IPv4Address('192.0.2.0')
>>> IPv4Network('192.0.2.0/28')[15]
IPv4Address('192.0.2.15')
>>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
True
>>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
False
@end example

@node 接口对象,其他模块级别函数,IP网络的定义,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress interface-objects}@anchor{301e}
@subsubsection 接口对象


接口对象是 @ref{277,,hashable} 的，所以它们可以作为字典中的键使用。

@geindex IPv4Interface (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv4Interface}@anchor{f7f}
@deffn {类} ipaddress.IPv4Interface (address)

构建一个 IPv4 接口。 @emph{address} 的含义与 @ref{4af,,IPv4Network} 构造器中的一样，不同之处在于任意主机地址总是会被接受。

@ref{f7f,,IPv4Interface} 是 @ref{2fb8,,IPv4Address} 的一个子类，所以它继承了该类的所有属性。 此外，还有以下属性可用：

@geindex ip (ipaddress.IPv4Interface 属性)
@anchor{library/ipaddress ipaddress IPv4Interface ip}@anchor{301f}
@deffn {属性} ip

地址（@ref{2fb8,,IPv4Address}）没有网络信息。

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.ip
IPv4Address('192.0.2.5')
@end example
@end deffn

@geindex network (ipaddress.IPv4Interface 属性)
@anchor{library/ipaddress ipaddress IPv4Interface network}@anchor{3020}
@deffn {属性} network

该接口所属的网络（@ref{4af,,IPv4Network}）。

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.network
IPv4Network('192.0.2.0/24')
@end example
@end deffn

@geindex with_prefixlen (ipaddress.IPv4Interface 属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_prefixlen}@anchor{3021}
@deffn {属性} with_prefixlen

用前缀符号表示的接口与掩码的字符串。

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_prefixlen
'192.0.2.5/24'
@end example
@end deffn

@geindex with_netmask (ipaddress.IPv4Interface 属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_netmask}@anchor{3022}
@deffn {属性} with_netmask

以网络为掩码的接口的字符串表示。

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_netmask
'192.0.2.5/255.255.255.0'
@end example
@end deffn

@geindex with_hostmask (ipaddress.IPv4Interface 属性)
@anchor{library/ipaddress ipaddress IPv4Interface with_hostmask}@anchor{3023}
@deffn {属性} with_hostmask

以主机为掩码的接口的字符串表示。

@example
>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_hostmask
'192.0.2.5/0.0.0.255'
@end example
@end deffn
@end deffn

@geindex IPv6Interface (ipaddress 中的类)
@anchor{library/ipaddress ipaddress IPv6Interface}@anchor{f80}
@deffn {类} ipaddress.IPv6Interface (address)

构建一个 IPv6 接口。 @emph{address} 的含义与 @ref{4ae,,IPv6Network} 构造器中的一样，不同之处在于任意主机地址总是会被接受。

@ref{f80,,IPv6Interface} 是 @ref{1bc,,IPv6Address} 的一个子类，所以它继承了该类的所有属性。 此外，还有以下属性可用：

@geindex ip (ipaddress.IPv6Interface 属性)
@anchor{library/ipaddress ipaddress IPv6Interface ip}@anchor{3024}
@deffn {属性} ip
@end deffn

@geindex network (ipaddress.IPv6Interface 属性)
@anchor{library/ipaddress ipaddress IPv6Interface network}@anchor{3025}
@deffn {属性} network
@end deffn

@geindex with_prefixlen (ipaddress.IPv6Interface 属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_prefixlen}@anchor{3026}
@deffn {属性} with_prefixlen
@end deffn

@geindex with_netmask (ipaddress.IPv6Interface 属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_netmask}@anchor{3027}
@deffn {属性} with_netmask
@end deffn

@geindex with_hostmask (ipaddress.IPv6Interface 属性)
@anchor{library/ipaddress ipaddress IPv6Interface with_hostmask}@anchor{3028}
@deffn {属性} with_hostmask

请参考 @ref{f7f,,IPv4Interface} 中的相应属性文档。
@end deffn
@end deffn

@menu
* 运算符: 运算符<5>. 

@end menu

@node 运算符<5>,,,接口对象
@anchor{library/ipaddress id2}@anchor{3029}
@subsubsection 运算符


接口对象支持一些运算符。 除非另有说明，运算符只能在兼容的对象之间应用（即IPv4与IPv4，IPv6与IPv6）。

@menu
* 逻辑操作符: 逻辑操作符<2>. 

@end menu

@node 逻辑操作符<2>,,,运算符<5>
@anchor{library/ipaddress id3}@anchor{302a}
@subsubsection 逻辑操作符


接口对象可以用通常的逻辑运算符集进行比较。

对于相等比较（@code{==`@w{`}和}!=`@w{`}），IP地址和网络都必须是相同的对象才会相等。 一个接口不会与任何地址或网络对象相等。

对于排序 (@code{<}、@code{>} 等)，规则是不同的。 具有相同 IP 版本的接口和地址对象可以被比较，而地址对象总是在接口对象之前排序。 两个接口对象首先通过它们的网络进行比较，如果它们是相同的，则通过它们的 IP 地址进行比较。

@node 其他模块级别函数,自定义异常,接口对象,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress other-module-level-functions}@anchor{302b}
@subsubsection 其他模块级别函数


该模块还提供以下模块级函数：

@geindex v4_int_to_packed() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress v4_int_to_packed}@anchor{302c}
@deffn {函数} ipaddress.v4_int_to_packed (address)

以网络（大端序）顺序将一个地址表示为 4 个打包的字节。@emph{address} 是一个 IPv4 IP 地址的整数表示。 如果整数是负数或太大而不满足 IPv4 IP 地址要求，会触发一个 @ref{16d,,ValueError}。

@example
>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.v4_int_to_packed(3221225985)
b'\xc0\x00\x02\x01'
@end example
@end deffn

@geindex v6_int_to_packed() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress v6_int_to_packed}@anchor{302d}
@deffn {函数} ipaddress.v6_int_to_packed (address)

以网络（大端序）顺序将一个地址表示为 4 个打包的字节。@emph{address} 是一个IPv6 IP地址的整数表示。 如果整数是负数或太大而不满足 IPv6 IP 地址要求，会触发一个 @ref{16d,,ValueError}。
@end deffn

@geindex summarize_address_range() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress summarize_address_range}@anchor{892}
@deffn {函数} ipaddress.summarize_address_range (first, last)

给出第一个和最后一个 IP 地址，返回总结的网络范围的迭代器。 @emph{first} 是范围内的第一个 @ref{2fb8,,IPv4Address} 或 @ref{1bc,,IPv6Address}，@emph{last} 是范围内的最后一个 @ref{2fb8,,IPv4Address} 或 @ref{1bc,,IPv6Address}。 如果 @emph{first} 或 @emph{last} 不是IP地址或不是同一版本则会引发 @ref{1ff,,TypeError}。 如果 @emph{last} 不大于 @emph{first}，或者 @emph{first} 的地址版本不是 4 或 6 则会引发 @ref{16d,,ValueError}。

@example
>>> [ipaddr for ipaddr in ipaddress.summarize_address_range(
...    ipaddress.IPv4Address('192.0.2.0'),
...    ipaddress.IPv4Address('192.0.2.130'))]
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')]
@end example
@end deffn

@geindex collapse_addresses() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress collapse_addresses}@anchor{893}
@deffn {函数} ipaddress.collapse_addresses (addresses)

返回一个 @ref{4af,,IPv4Network} 或 @ref{4ae,,IPv6Network} 对象的迭代器。 @emph{addresses} 是一个 @ref{4af,,IPv4Network} 或 @ref{4ae,,IPv6Network} 对象的迭代器。 如果 @emph{addresses} 包含混合版本的对象则会引发 @ref{1ff,,TypeError}。

@example
>>> [ipaddr for ipaddr in
... ipaddress.collapse_addresses([ipaddress.IPv4Network('192.0.2.0/25'),
... ipaddress.IPv4Network('192.0.2.128/25')])]
[IPv4Network('192.0.2.0/24')]
@end example
@end deffn

@geindex get_mixed_type_key() (在 ipaddress 模块中)
@anchor{library/ipaddress ipaddress get_mixed_type_key}@anchor{302e}
@deffn {函数} ipaddress.get_mixed_type_key (obj)

返回一个适合在网络和地址之间进行排序的键。 地址和网络对象在默认情况下是不可排序的；它们在本质上是不同的，所以表达式:

@example
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
@end example

是没有意义的。 然而，有些时候，你可能希望让 @ref{a2,,ipaddress} 对这些进行排序。 如果你需要这样做，你可以使用这个函数作为 @ref{54f,,sorted()} 的 @emph{key} 参数。

@emph{obj} 是一个网络或地址对象。
@end deffn

@node 自定义异常,,其他模块级别函数,ipaddress --- IPv4/IPv6 操作库
@anchor{library/ipaddress custom-exceptions}@anchor{302f}
@subsubsection 自定义异常


为了支持来自类构造函数的更具体的错误报告，模块定义了以下异常：

@geindex AddressValueError
@anchor{library/ipaddress ipaddress AddressValueError}@anchor{2fbd}
@deffn {例外} ipaddress.AddressValueError (ValueError)

与地址有关的任何数值错误。
@end deffn

@geindex NetmaskValueError
@anchor{library/ipaddress ipaddress NetmaskValueError}@anchor{2fe4}
@deffn {例外} ipaddress.NetmaskValueError (ValueError)

与网络掩码有关的任何数值错误
@end deffn

@node 多媒体服务,国际化,互联网协议和支持,Python 标准库
@anchor{library/mm doc}@anchor{3030}@anchor{library/mm mmedia}@anchor{3031}@anchor{library/mm multimedia-services}@anchor{3032}
@section 多媒体服务


本章描述的模块实现了主要用于多媒体应用的各种算法或接口。 它们可在安装时自行决定。 这是一个概述：

@menu
* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换

@end menu

@node wave --- 读写WAV格式文件,colorsys --- 颜色系统间的转换,,多媒体服务
@anchor{library/wave doc}@anchor{3033}@anchor{library/wave module-wave}@anchor{130}@anchor{library/wave wave-read-and-write-wav-files}@anchor{3034}
@subsection @code{wave} --- 读写WAV格式文件


@geindex wave (模块)

@c Documentations stolen from comments in file.

@strong{源代码:} Lib/wave.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/wave.py}


__________________________________________________________________


@ref{130,,wave} 模块提供了一个处理 WAV 声音格式的便利接口。它不支持压缩/解压，但是支持单声道/立体声。

@ref{130,,wave} 模块定义了以下函数和异常:

@geindex open() (在 wave 模块中)
@anchor{library/wave wave open}@anchor{21a}
@deffn {函数} wave.open (file, mode=None)

如果 @emph{file} 是一个字符串，打开对应文件名的文件。否则就把它作为文件类对象来处理。@emph{mode} 可以为以下值：


@table @asis

@item @code{'rb'}

只读模式。

@item @code{'wb'}

只写模式。
@end table

注意不支持同时读写WAV文件。

@emph{mode} 设为 @code{'rb'} 时返回一个 @code{Wave_read} 对象，而 @emph{mode} 设为 @code{'wb'} 时返回一个 @code{Wave_write} 对象。如果省略 @emph{mode} 并指定 @emph{file} 来传入一个文件类对象，则 @code{file.mode} 会被用作 @emph{mode} 的默认值。

如果操作的是文件对象，当使用 wave 对象的 @code{close()} 方法时，并不会真正关闭文件对象，这需要调用者负责来关闭文件对象。

@ref{21a,,open()} 函数可以在 @ref{7e4,,with} 语句中使用。 当 @code{with} 阻塞结束时，@ref{3035,,Wave_read.close()} 或 @ref{3036,,Wave_write.close()} 方法会被调用。


在 3.4 版更改: 添加了对不可搜索文件的支持。

@end deffn

@geindex Error
@anchor{library/wave wave Error}@anchor{3037}
@deffn {例外} wave.Error

当不符合WAV格式或无法操作时引发的错误。
@end deffn

@menu
* Wave_read对象:: 
* Wave_write 对象:: 

@end menu

@node Wave_read对象,Wave_write 对象,,wave --- 读写WAV格式文件
@anchor{library/wave id1}@anchor{3038}@anchor{library/wave wave-read-objects}@anchor{3039}
@subsubsection Wave_read对象


由 @ref{21a,,open()} 返回的 Wave_read 对象，有以下几种方法:

@geindex close() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read close}@anchor{3035}
@deffn {方法} Wave_read.close ()

关闭 @ref{130,,wave} 打开的数据流并使对象不可用。当对象销毁时会自动调用。
@end deffn

@geindex getnchannels() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getnchannels}@anchor{303a}
@deffn {方法} Wave_read.getnchannels ()

返回声道数量（@code{1} 为单声道，@code{2} 为立体声）
@end deffn

@geindex getsampwidth() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getsampwidth}@anchor{303b}
@deffn {方法} Wave_read.getsampwidth ()

返回采样字节长度。
@end deffn

@geindex getframerate() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getframerate}@anchor{303c}
@deffn {方法} Wave_read.getframerate ()

返回采样频率。
@end deffn

@geindex getnframes() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getnframes}@anchor{303d}
@deffn {方法} Wave_read.getnframes ()

返回音频总帧数。
@end deffn

@geindex getcomptype() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getcomptype}@anchor{303e}
@deffn {方法} Wave_read.getcomptype ()

返回压缩类型（只支持 @code{'NONE'} 类型）
@end deffn

@geindex getcompname() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getcompname}@anchor{303f}
@deffn {方法} Wave_read.getcompname ()

@ref{303e,,getcomptype()} 的通俗版本。使用 @code{'not compressed'} 代替 @code{'NONE'}。
@end deffn

@geindex getparams() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getparams}@anchor{3040}
@deffn {方法} Wave_read.getparams ()

返回一个 @ref{1a1,,namedtuple()} @code{(nchannels, sampwidth, framerate, nframes, comptype, compname)}，与 @code{get*()} 方法的输出相同。
@end deffn

@geindex readframes() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read readframes}@anchor{3041}
@deffn {方法} Wave_read.readframes (n)

读取并返回以 @ref{172,,bytes} 对象表示的最多 @emph{n} 帧音频。
@end deffn

@geindex rewind() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read rewind}@anchor{3042}
@deffn {方法} Wave_read.rewind ()

设置当前文件指针位置。
@end deffn

后面两个方法是为了和 @ref{4,,aifc} 保持兼容，实际不做任何事情。

@geindex getmarkers() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getmarkers}@anchor{3043}
@deffn {方法} Wave_read.getmarkers ()

返回 @code{None}。
@end deffn

@geindex getmark() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read getmark}@anchor{3044}
@deffn {方法} Wave_read.getmark (id)

引发错误异常。
@end deffn

以下两个方法都使用指针，具体实现由其底层决定。

@geindex setpos() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read setpos}@anchor{3045}
@deffn {方法} Wave_read.setpos (pos)

设置文件指针到指定位置。
@end deffn

@geindex tell() (wave.Wave_read 方法)
@anchor{library/wave wave Wave_read tell}@anchor{3046}
@deffn {方法} Wave_read.tell ()

返回当前文件指针位置。
@end deffn

@node Wave_write 对象,,Wave_read对象,wave --- 读写WAV格式文件
@anchor{library/wave id2}@anchor{3047}@anchor{library/wave wave-write-objects}@anchor{9fa}
@subsubsection Wave_write 对象


对于可查找的输出流，@code{wave} 头将自动更新以反映实际写入的帧数。 对于不可查找的流，当写入第一帧时 @emph{nframes} 值必须准确。 获取准确的 @emph{nframes} 值可以通过调用 @ref{3048,,setnframes()} 或 @ref{3049,,setparams()} 并附带 @ref{3036,,close()} 被调用之前将要写入的帧数，然后使用 @ref{9fb,,writeframesraw()} 来写入帧数据，或者通过调用 @ref{9fc,,writeframes()} 并附带所有要写入的帧。 在后一种情况下 @ref{9fc,,writeframes()} 将计算数据中的帧数并在写入帧数据之前相应地设置 @emph{nframes}。

由 @ref{21a,,open()} 返回的 Wave_write 对象，有以下几种方法:


在 3.4 版更改: 添加了对不可搜索文件的支持。


@geindex close() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write close}@anchor{3036}
@deffn {方法} Wave_write.close ()

确保 @emph{nframes} 是正确的，并在文件被 @ref{130,,wave} 打开时关闭它。 此方法会在对象收集时被调用。 如果输出流不可查找且 @emph{nframes} 与实际写入的帧数不匹配时引发异常。
@end deffn

@geindex setnchannels() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setnchannels}@anchor{304a}
@deffn {方法} Wave_write.setnchannels (n)

设置声道数。
@end deffn

@geindex setsampwidth() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setsampwidth}@anchor{304b}
@deffn {方法} Wave_write.setsampwidth (n)

设置采样字节长度为 @emph{n}。
@end deffn

@geindex setframerate() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setframerate}@anchor{304c}
@deffn {方法} Wave_write.setframerate (n)

设置采样频率为 @emph{n}。


在 3.2 版更改: 对此方法的非整数输入会被舍入到最接近的整数。

@end deffn

@geindex setnframes() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setnframes}@anchor{3048}
@deffn {方法} Wave_write.setnframes (n)

设置总帧数为 @emph{n}。 如果与之后实际写入的帧数不一致此值将会被更改（ 如果输出流不可查找则此更改尝试将引发错误）。
@end deffn

@geindex setcomptype() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setcomptype}@anchor{304d}
@deffn {方法} Wave_write.setcomptype (type, name)

设置压缩格式。目前只支持 @code{NONE} 即无压缩格式。
@end deffn

@geindex setparams() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write setparams}@anchor{3049}
@deffn {方法} Wave_write.setparams (tuple)

@emph{tuple} 应该是 @code{(nchannels, sampwidth, framerate, nframes, comptype, compname)}，每项的值应可用于 @code{set*()} 方法。设置所有形参。
@end deffn

@geindex tell() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write tell}@anchor{304e}
@deffn {方法} Wave_write.tell ()

返回当前文件指针，其指针含义和 @ref{3046,,Wave_read.tell()} 以及 @ref{3045,,Wave_read.setpos()} 是一致的。
@end deffn

@geindex writeframesraw() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write writeframesraw}@anchor{9fb}
@deffn {方法} Wave_write.writeframesraw (data)

写入音频数据但不更新 @emph{nframes}。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn

@geindex writeframes() (wave.Wave_write 方法)
@anchor{library/wave wave Wave_write writeframes}@anchor{9fc}
@deffn {方法} Wave_write.writeframes (data)

写入音频帧并确保 @emph{nframes} 是正确的。 如果输出流不可查找且在 @emph{data} 被写入之后写入的总帧数与之前设定的has been written does not match the previously set value for @emph{nframes} 值不匹配将会引发错误。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn

注意在调用 @code{writeframes()} 或 @code{writeframesraw()} 之后再设置任何格式参数是无效的，而且任何这样的尝试将引发 @ref{3037,,wave.Error}。

@node colorsys --- 颜色系统间的转换,,wave --- 读写WAV格式文件,多媒体服务
@anchor{library/colorsys doc}@anchor{304f}@anchor{library/colorsys colorsys-conversions-between-color-systems}@anchor{3050}@anchor{library/colorsys module-colorsys}@anchor{1f}
@subsection @code{colorsys} --- 颜色系统间的转换


@geindex colorsys (模块)

@strong{源代码：} Lib/colorsys.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/colorsys.py}


__________________________________________________________________


@ref{1f,,colorsys} 模块定义了计算机显示器所用的 RGB (Red Green Blue) 色彩空间与三种其他色彩坐标系统 YIQ, HLS (Hue Lightness Saturation) 和 HSV (Hue Saturation Value) 表示的颜色值之间的双向转换。 所有这些色彩空间的坐标都使用浮点数值来表示。 在 YIQ 空间中，Y 坐标取值为 0 和 1 之间，而 I 和 Q 坐标均可以为正数或负数。 在所有其他空间中，坐标取值均为 0 和 1 之间。


@subsubheading 参见


有关色彩空间的更多信息可访问 @indicateurl{https://poynton.ca/ColorFAQ.html} 和 @indicateurl{https://www.cambridgeincolour.com/tutorials/color-spaces.htm}。


@ref{1f,,colorsys} 模块定义了如下函数：

@geindex rgb_to_yiq() (在 colorsys 模块中)
@anchor{library/colorsys colorsys rgb_to_yiq}@anchor{3051}
@deffn {函数} colorsys.rgb_to_yiq (r, g, b)

把颜色从RGB值转为YIQ值。
@end deffn

@geindex yiq_to_rgb() (在 colorsys 模块中)
@anchor{library/colorsys colorsys yiq_to_rgb}@anchor{3052}
@deffn {函数} colorsys.yiq_to_rgb (y, i, q)

把颜色从YIQ值转为RGB值。
@end deffn

@geindex rgb_to_hls() (在 colorsys 模块中)
@anchor{library/colorsys colorsys rgb_to_hls}@anchor{3053}
@deffn {函数} colorsys.rgb_to_hls (r, g, b)

把颜色从RGB值转为HLS值。
@end deffn

@geindex hls_to_rgb() (在 colorsys 模块中)
@anchor{library/colorsys colorsys hls_to_rgb}@anchor{3054}
@deffn {函数} colorsys.hls_to_rgb (h, l, s)

把颜色从HLS值转为RGB值。
@end deffn

@geindex rgb_to_hsv() (在 colorsys 模块中)
@anchor{library/colorsys colorsys rgb_to_hsv}@anchor{3055}
@deffn {函数} colorsys.rgb_to_hsv (r, g, b)

把颜色从RGB值转为HSV值。
@end deffn

@geindex hsv_to_rgb() (在 colorsys 模块中)
@anchor{library/colorsys colorsys hsv_to_rgb}@anchor{3056}
@deffn {函数} colorsys.hsv_to_rgb (h, s, v)

把颜色从HSV值转为RGB值。
@end deffn

示例:

@example
>>> import colorsys
>>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)
(0.5, 0.5, 0.4)
>>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
(0.2, 0.4, 0.4)
@end example

@node 国际化,程序框架,多媒体服务,Python 标准库
@anchor{library/i18n doc}@anchor{3057}@anchor{library/i18n i18n}@anchor{3058}@anchor{library/i18n internationalization}@anchor{3059}
@section 国际化


本章中介绍的模块通过提供选择要在程序信息中使用的语言的机制或通过定制输出以匹配本地约定来帮助你编写不依赖于语言和区域设置的软件。

本章中描述的模块列表是：

@menu
* gettext: gettext --- 多语种国际化服务. 多语种国际化服务
* locale: locale --- 国际化服务. 国际化服务

@end menu

@node gettext --- 多语种国际化服务,locale --- 国际化服务,,国际化
@anchor{library/gettext doc}@anchor{305a}@anchor{library/gettext gettext-multilingual-internationalization-services}@anchor{305b}@anchor{library/gettext module-gettext}@anchor{87}
@subsection @code{gettext} --- 多语种国际化服务


@geindex gettext (模块)

@strong{源代码：} Lib/gettext.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/gettext.py}


__________________________________________________________________


@ref{87,,gettext} 模块为 Python 模块和应用程序提供国际化 (Internationalization, I18N) 和本地化 (Localization, L10N) 服务。它同时支持 GNU @code{gettext} 消息编目 API 和更高级的、基于类的 API，后者可能更适合于 Python 文件。下方描述的接口允许用户使用一种自然语言编写模块和应用程序消息，并提供翻译后的消息编目，以便在不同的自然语言下运行。

同时还给出一些本地化 Python 模块及应用程序的小技巧。

@menu
* GNU gettext API:: 
* 基于类的 API:: 
* 国际化 (I18N) 你的程序和模块: 国际化 I18N 你的程序和模块. 
* 致谢: 致谢<9>. 

@end menu

@node GNU gettext API,基于类的 API,,gettext --- 多语种国际化服务
@anchor{library/gettext gnu-gettext-api}@anchor{305c}
@subsubsection GNU @code{gettext} API


模块 @ref{87,,gettext} 定义了下列  API，这与 @code{gettext} API 类似。如果你使用该 API，将会对整个应用程序产生全局的影响。如果你的应用程序支持多语种，而语言选择取决于用户的语言环境设置，这通常正是你所想要的。而如果你正在本地化某个 Python 模块，或者你的应用程序需要在运行时切换语言，相反你或许想用基于类的API。

@geindex bindtextdomain() (在 gettext 模块中)
@anchor{library/gettext gettext bindtextdomain}@anchor{305d}
@deffn {函数} gettext.bindtextdomain (domain, localedir=None)

将 @emph{domain} 绑定到本地目录 @emph{localedir}。 更具体地来说，模块 @ref{87,,gettext} 将使用路径 (在 Unix 系统中):  @code{@emph{localedir}/@emph{language}/LC_MESSAGES/@emph{domain}.mo} 查找二进制 @code{.mo} 文件，此处对应地查找 @emph{language} 的位置是环境变量 
@geindex LANGUAGE
@geindex 环境变量; LANGUAGE
@code{LANGUAGE}, 
@geindex LC_ALL
@geindex 环境变量; LC_ALL
@code{LC_ALL}, 
@geindex LC_MESSAGES
@geindex 环境变量; LC_MESSAGES
@code{LC_MESSAGES} 和 
@geindex LANG
@geindex 环境变量; LANG
@code{LANG} 中。

如果遗漏了 @emph{localedir} 或者设置为 @code{None}，那么将返回当前 @emph{domain} 所绑定的值 @footnote{@w{(1)} 
不同系统的默认语言环境目录是不同的；比如在 RedHat Linux 上是 @code{/usr/share/locale}，在 Solaris 上是 @code{/usr/lib/locale}。@ref{87,,gettext} 模块不会支持这些基于不同系统的默认值；而它的默认值为 @code{@emph{sys.base_prefix}/share/locale} （请参阅 @ref{305e,,sys.base_prefix}）。基于上述原因，最好每次都在应用程序的开头使用明确的绝对路径来调用 @ref{305d,,bindtextdomain()}。
}
@end deffn

@geindex bind_textdomain_codeset() (在 gettext 模块中)
@anchor{library/gettext gettext bind_textdomain_codeset}@anchor{3c2}
@deffn {函数} gettext.bind_textdomain_codeset (domain, codeset=None)

将 @emph{domain} 绑定到 @emph{codeset}，修改 @ref{3be,,lgettext()}, @ref{3bf,,ldgettext()}, @ref{3c0,,lngettext()} 和 @ref{3c1,,ldngettext()} 函数返回的字节串的字符编码。如果省略了 @emph{codeset}，则返回当前绑定的编码集。


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn

@geindex textdomain() (在 gettext 模块中)
@anchor{library/gettext gettext textdomain}@anchor{305f}
@deffn {函数} gettext.textdomain (domain=None)

修改或查询当前的全局域。如果 @emph{domain} 为 @code{None}，则返回当前的全局域，不为 @code{None} 则将全局域设置为 @emph{domain}，并返回它。
@end deffn

@geindex _ (underscore); gettext

@geindex gettext() (在 gettext 模块中)
@anchor{library/gettext gettext gettext}@anchor{e9a}
@deffn {函数} gettext.gettext (message)

返回 @emph{message} 的本地化翻译，依据包括当前的全局域、语言和语言环境目录。本函数在本地命名空间中通常有别名 @code{_()} （参考下面的示例）。
@end deffn

@geindex dgettext() (在 gettext 模块中)
@anchor{library/gettext gettext dgettext}@anchor{3060}
@deffn {函数} gettext.dgettext (domain, message)

与 @ref{e9a,,gettext()} 类似，但在指定的 @emph{domain} 中查找 message。
@end deffn

@geindex ngettext() (在 gettext 模块中)
@anchor{library/gettext gettext ngettext}@anchor{3061}
@deffn {函数} gettext.ngettext (singular, plural, n)

与 @ref{e9a,,gettext()} 类似，但考虑了复数形式。如果找到了翻译，则将 @emph{n} 代入复数公式，然后返回得出的消息（某些语言具有两种以上的复数形式）。如果未找到翻译，则 @emph{n} 为 1 时返回 @emph{singular}，为其他数时返回 @emph{plural}。

复数公式取自编目头文件。它是 C 或 Python 表达式，有一个自变量 @emph{n}，该表达式计算的是所需复数形式在编目中的索引号。关于在 @code{.po} 文件中使用的确切语法和各种语言的公式，请参阅 GNU gettext 文档@footnote{https://www.gnu.org/software/gettext/manual/gettext.html} 。
@end deffn

@geindex dngettext() (在 gettext 模块中)
@anchor{library/gettext gettext dngettext}@anchor{3062}
@deffn {函数} gettext.dngettext (domain, singular, plural, n)

与 @ref{3061,,ngettext()} 类似，但在指定的 @emph{domain} 中查找 message。
@end deffn

@geindex pgettext() (在 gettext 模块中)
@anchor{library/gettext gettext pgettext}@anchor{307}
@deffn {函数} gettext.pgettext (context, message)
@end deffn

@geindex dpgettext() (在 gettext 模块中)
@anchor{library/gettext gettext dpgettext}@anchor{3063}
@deffn {函数} gettext.dpgettext (domain, context, message)
@end deffn

@geindex npgettext() (在 gettext 模块中)
@anchor{library/gettext gettext npgettext}@anchor{3064}
@deffn {函数} gettext.npgettext (context, singular, plural, n)
@end deffn

@geindex dnpgettext() (在 gettext 模块中)
@anchor{library/gettext gettext dnpgettext}@anchor{3065}
@deffn {函数} gettext.dnpgettext (domain, context, singular, plural, n)

与前缀中没有 @code{p} 的相应函数类似（即 @ref{87,,gettext()}, @ref{3060,,dgettext()}, @ref{3061,,ngettext()}, @ref{3062,,dngettext()} ），但是仅翻译给定的 message @emph{context}。


3.8 新版功能.

@end deffn

@geindex lgettext() (在 gettext 模块中)
@anchor{library/gettext gettext lgettext}@anchor{3be}
@deffn {函数} gettext.lgettext (message)
@end deffn

@geindex ldgettext() (在 gettext 模块中)
@anchor{library/gettext gettext ldgettext}@anchor{3bf}
@deffn {函数} gettext.ldgettext (domain, message)
@end deffn

@geindex lngettext() (在 gettext 模块中)
@anchor{library/gettext gettext lngettext}@anchor{3c0}
@deffn {函数} gettext.lngettext (singular, plural, n)
@end deffn

@geindex ldngettext() (在 gettext 模块中)
@anchor{library/gettext gettext ldngettext}@anchor{3c1}
@deffn {函数} gettext.ldngettext (domain, singular, plural, n)

与前缀中没有 @code{l} 的相应函数等效（ @ref{e9a,,gettext()}, @ref{3060,,dgettext()}, @ref{3061,,ngettext()} 和 @ref{3062,,dngettext()} ），但是如果没有用 @ref{3c2,,bind_textdomain_codeset()} 显式设置其他编码，则返回的翻译将以首选系统编码来编码字节串。

@cartouche
@quotation 警告 
在 Python 3 中应避免使用这些函数，因为它们返回的是编码后的字节串。最好使用返回 Unicode 字符串的其他方法，因为大多数 Python 应用程序都希望将人类可读的文本作为字符串而不是字节来处理。此外，如果翻译后的字符串存在编码问题，则可能会意外出现与 Unicode 相关的异常。
@end quotation
@end cartouche


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn

注意，GNU @code{gettext} 还定义了 @code{dcgettext()} 方法，但它被认为不实用，因此目前没有实现它。

这是该 API 的典型用法示例:

@example
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print(_('This is a translatable string.'))
@end example

@node 基于类的 API,国际化 I18N 你的程序和模块,GNU gettext API,gettext --- 多语种国际化服务
@anchor{library/gettext class-based-api}@anchor{3066}
@subsubsection 基于类的 API


与 GNU @code{gettext} API 相比，@ref{87,,gettext} 模块的基于类的 API 提供了更多的灵活性和更强的便利性。这是本地化 Python 应用程序和模块的推荐方法。@code{gettext} 定义了一个 @ref{3067,,GNUTranslations} 类，该类实现了 GNU @code{.mo} 格式文件的解析，并且具有用于返回字符串的方法。本类的实例也可以将自身作为函数 @code{_()} 安装到内建命名空间中。

@geindex find() (在 gettext 模块中)
@anchor{library/gettext gettext find}@anchor{3068}
@deffn {函数} gettext.find (domain, localedir=None, languages=None, all=False)

本函数实现了标准的 @code{.mo} 文件搜索算法。它接受一个 @emph{domain}，它与 @ref{305f,,textdomain()} 接受的域相同。可选参数 @emph{localedir} 与 @ref{305d,,bindtextdomain()} 中的相同。可选参数 @emph{languages} 是多条字符串的列表，其中每条字符串都是一种语言代码。

如果没有传入 @emph{localedir}，则使用默认的系统语言环境目录。 @footnote{@w{(2)} 
参阅上方 @ref{305d,,bindtextdomain()} 的脚注。
} 如果没有传入 @emph{languages}，则搜索以下环境变量：
@geindex LANGUAGE
@geindex 环境变量; LANGUAGE
@code{LANGUAGE}、
@geindex LC_ALL
@geindex 环境变量; LC_ALL
@code{LC_ALL}、
@geindex LC_MESSAGES
@geindex 环境变量; LC_MESSAGES
@code{LC_MESSAGES} 和 
@geindex LANG
@geindex 环境变量; LANG
@code{LANG}。从这些变量返回的第一个非空值将用作 @emph{languages} 变量。环境变量应包含一个语言列表，由冒号分隔，该列表会被按冒号拆分，以产生所需的语言代码字符串列表。

@ref{3068,,find()} 将扩展并规范化 language，然后遍历它们，搜索由这些组件构建的现有文件:

@code{@emph{localedir}/@emph{language}/LC_MESSAGES/@emph{domain}.mo}

@ref{3068,,find()} 返回找到类似的第一个文件名。如果找不到这样的文件，则返回 @code{None}。如果传入了 @emph{all}，它将返回一个列表，包含所有文件名，并按它们在语言列表或环境变量中出现的顺序排列。
@end deffn

@geindex translation() (在 gettext 模块中)
@anchor{library/gettext gettext translation}@anchor{3c5}
@deffn {函数} gettext.translation (domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None)

根据 @emph{domain}、@emph{localedir} 和 @emph{languages}，返回 @code{*Translations} 实例，首先应将前述参数传入 @ref{3068,,find()} 以获取关联的 @code{.mo} 文件路径的列表。名字与 @code{.mo} 文件名相同的实例将被缓存。如果传入 @emph{class_}，它将是实际被实例化的类，否则实例化 @ref{3067,,GNUTranslations}。类的构造函数必须只接受一个 @ref{c1d,,文件对象} 参数。如果传入 @emph{codeset}，那么在 @ref{3069,,lgettext()} 和 @ref{306a,,lngettext()} 方法中，对翻译后的字符串进行编码的字符集将被改变。

如果找到多个文件，后找到的文件将用作先前文件的替补。为了设置替补，将使用 @ref{4da,,copy.copy()} 从缓存中克隆每个 translation 对象。实际的实例数据仍在缓存中共享。

如果 @code{.mo} 文件未找到，且 @emph{fallback} 为 false（默认值），则本函数引发 @ref{30b,,OSError} 异常，如果 @emph{fallback} 为 true，则返回一个 @ref{306b,,NullTranslations} 实例。


在 3.3 版更改: @ref{a7c,,IOError} 代替 @ref{30b,,OSError} 被引发。



Deprecated since version 3.8, will be removed in version 3.10: @emph{codeset} 参数。

@end deffn

@geindex install() (在 gettext 模块中)
@anchor{library/gettext gettext install}@anchor{3c6}
@deffn {函数} gettext.install (domain, localedir=None, codeset=None, names=None)

根据传入 @ref{3c5,,translation()} 函数的 @emph{domain}、@emph{localedir} 和 @emph{codeset}，在 Python 内建命名空间中安装 @code{_()} 函数。

@emph{names} 参数的信息请参阅 translation 对象的 @ref{306c,,install()} 方法的描述。

如下所示，通常将字符串包括在 @code{_()} 函数的调用中，以标记应用程序中待翻译的字符串，就像这样:

@example
print(_('This string will be translated.'))
@end example

为了方便，一般将 @code{_()} 函数安装在 Python 内建命名空间中，以便在应用程序的所有模块中轻松访问它。


Deprecated since version 3.8, will be removed in version 3.10: @emph{codeset} 参数。

@end deffn

@menu
* NullTranslations 类:: 
* GNUTranslations 类:: 
* Solaris 消息编目支持:: 
* 编目构造器:: 

@end menu

@node NullTranslations 类,GNUTranslations 类,,基于类的 API
@anchor{library/gettext the-nulltranslations-class}@anchor{306d}
@subsubsection @code{NullTranslations} 类


translation 类实际实现的是，将原始源文件消息字符串转换为已翻译的消息字符串。所有 translation 类使用的基类为 @ref{306b,,NullTranslations}，它提供了基本的接口，可用于编写自己定制的 translation 类。以下是 @code{NullTranslations} 的方法：

@geindex NullTranslations (gettext 中的类)
@anchor{library/gettext gettext NullTranslations}@anchor{306b}
@deffn {类} gettext.NullTranslations (fp=None)

接受一个可选参数 @ref{c1d,,文件对象} @emph{fp}，该参数会被基类忽略。初始化由派生类设置的 "protected" （受保护的）实例变量 @emph{_info} 和 @emph{_charset}，与 @emph{_fallback} 类似，但它是通过 @ref{306e,,add_fallback()} 来设置的。如果 @emph{fp} 不为 @code{None}，就会调用 @code{self._parse(fp)}。

@geindex _parse() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations _parse}@anchor{306f}
@deffn {方法} _parse (fp)

在基类中没有操作，本方法接受文件对象 @emph{fp}，从该文件读取数据，用来初始化消息编目。如果你手头的消息编目文件的格式不受支持，则应重写本方法来解析你的格式。
@end deffn

@geindex add_fallback() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations add_fallback}@anchor{306e}
@deffn {方法} add_fallback (fallback)

添加 @emph{fallback} 为当前 translation 对象的替补对象。如果 translation 对象无法为指定消息提供翻译，则应向替补查询。
@end deffn

@geindex gettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations gettext}@anchor{3070}
@deffn {方法} gettext (message)

如果设置了替补，则转发 @code{gettext()} 给替补。否则返回 @emph{message}。在派生类中被重写。
@end deffn

@geindex ngettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations ngettext}@anchor{3071}
@deffn {方法} ngettext (singular, plural, n)

如果设置了替补，则转发 @code{ngettext()} 给替补。否则，@emph{n} 为 1 时返回 @emph{singular}，为其他时返回 @emph{plural}。在派生类中被重写。
@end deffn

@geindex pgettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations pgettext}@anchor{3072}
@deffn {方法} pgettext (context, message)

如果设置了替补，则转发 @ref{307,,pgettext()} 给替补。否则返回已翻译的消息。在派生类中被重写。


3.8 新版功能.

@end deffn

@geindex npgettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations npgettext}@anchor{3073}
@deffn {方法} npgettext (context, singular, plural, n)

如果设置了替补，则转发 @ref{3064,,npgettext()} 给替补。否则返回已翻译的消息。在派生类中被重写。


3.8 新版功能.

@end deffn

@geindex lgettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations lgettext}@anchor{3069}
@deffn {方法} lgettext (message)
@end deffn

@geindex lngettext() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations lngettext}@anchor{306a}
@deffn {方法} lngettext (singular, plural, n)

与 @ref{3070,,gettext()} 和 @ref{3071,,ngettext()} 等效，但是如果没有用 @ref{3c4,,set_output_charset()} 显式设置编码，则返回的翻译将以首选系统编码来编码字节串。在派生类中被重写。

@cartouche
@quotation 警告 
应避免在 Python 3 中使用这些方法。请参阅 @ref{3be,,lgettext()} 函数的警告。
@end quotation
@end cartouche


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn

@geindex info() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations info}@anchor{3074}
@deffn {方法} info ()

返回 "protected"（受保护的） @code{_info} 变量，它是一个字典，包含在消息编目文件中找到的元数据。
@end deffn

@geindex charset() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations charset}@anchor{3075}
@deffn {方法} charset ()

返回消息编目文件的编码。
@end deffn

@geindex output_charset() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations output_charset}@anchor{3c3}
@deffn {方法} output_charset ()

返回由 @ref{3069,,lgettext()} 和 @ref{306a,,lngettext()} 翻译出的消息的编码。


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn

@geindex set_output_charset() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations set_output_charset}@anchor{3c4}
@deffn {方法} set_output_charset (charset)

更改翻译出的消息的编码。


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn

@geindex install() (gettext.NullTranslations 方法)
@anchor{library/gettext gettext NullTranslations install}@anchor{306c}
@deffn {方法} install (names=None)

本方法将 @ref{3070,,gettext()} 安装至内建命名空间，并绑定为 @code{_}。

如果传入 @emph{names} 参数，该参数必须是一个序列，包含除 @code{_()} 外其他要安装在内建命名空间中的函数的名称。支持的名称有 @code{'gettext'}, @code{'ngettext'}, @code{'pgettext'}, @code{'npgettext'}, @code{'lgettext'} 和 @code{'lngettext'}。

注意，这仅仅是使 @code{_()} 函数在应用程序中生效的一种方法，尽管也是最方便的方法。由于它会影响整个应用程序全局，特别是内建命名空间，因此已经本地化的模块不应该安装 @code{_()}，而是应该用下列代码使 @code{_()} 在各自模块中生效:

@example
import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext
@end example

这只将 @code{_()} 放在其模块的全局命名空间中，所以只影响其模块内的调用。


在 3.8 版更改: 添加了 @code{'pgettext'} 和 @code{'npgettext'}。

@end deffn
@end deffn

@node GNUTranslations 类,Solaris 消息编目支持,NullTranslations 类,基于类的 API
@anchor{library/gettext the-gnutranslations-class}@anchor{3076}
@subsubsection @code{GNUTranslations} 类


@ref{87,,gettext} 模块提供了一个派生自 @ref{306b,,NullTranslations} 的其他类：@ref{3067,,GNUTranslations}。该类重写了 @code{_parse()}，同时能以大端序和小端序格式读取 GNU @code{gettext} 格式的 @code{.mo} 文件。

@ref{3067,,GNUTranslations} 从翻译编目中解析出可选的元数据。GNU @code{gettext} 约定，将元数据包括在空字符串的翻译中。该元数据采用 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} 样式的 @code{key: value} 键值对，且应该包含 @code{Project-Id-Version} 键。如果找到 @code{Content-Type} 键，那么将用 @code{charset} 属性去初始化 "protected"（受保护的） @code{_charset} 实例变量，而该变量在未找到键的情况下默认为 @code{None}。如果指定了字符编码，那么从编目中读取的所有消息 ID 和消息字符串都将使用此编码转换为 Unicode，若未指定编码，则假定编码为 ASCII。

由于消息 ID 也是作为 Unicode 字符串读取的，因此所有 @code{*gettext()} 方法都假定消息 ID 为 Unicode 字符串，而不是字节串。

整个键/值对集合将被放入一个字典，并设置为 "protected"（受保护的） @code{_info} 实例变量。

如果 @code{.mo} 文件的魔法值 (magic number) 无效，或遇到意外的主版本号，或在读取文件时发生其他问题，则实例化 @ref{3067,,GNUTranslations} 类会引发 @ref{30b,,OSError}。

@geindex GNUTranslations (gettext 中的类)
@anchor{library/gettext gettext GNUTranslations}@anchor{3067}
@deffn {类} gettext.GNUTranslations

下列方法是根据基类实现重写的：

@geindex gettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations gettext}@anchor{3077}
@deffn {方法} gettext (message)

在编目中查找 @emph{message} ID，并以 Unicode 字符串形式返回相应的消息字符串。如果在编目中没有 @emph{message} ID 条目，且配置了替补，则查找请求将被转发到替补的 @ref{3070,,gettext()} 方法。否则，返回 @emph{message} ID。
@end deffn

@geindex ngettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations ngettext}@anchor{3078}
@deffn {方法} ngettext (singular, plural, n)

查找消息 ID 的复数形式。@emph{singular} 用作消息 ID，用于在编目中查找，同时 @emph{n} 用于确定使用哪种复数形式。返回的消息字符串是 Unicode 字符串。

如果在编目中没有找到消息 ID，且配置了替补，则查找请求将被转发到替补的 @ref{3071,,ngettext()} 方法。否则，当 @emph{n} 为 1 时返回 @emph{singular}，其他情况返回 @emph{plural}。

例如：

@example
n = len(os.listdir('.'))
cat = GNUTranslations(somefile)
message = cat.ngettext(
    'There is %(num)d file in this directory',
    'There are %(num)d files in this directory',
    n) % @{'num': n@}
@end example
@end deffn

@geindex pgettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations pgettext}@anchor{3079}
@deffn {方法} pgettext (context, message)

在编目中查找 @emph{context} 和 @emph{message} ID，并以 Unicode 字符串形式返回相应的消息字符串。如果在编目中没有 @emph{message} ID 和 @emph{context} 条目，且配置了替补，则查找请求将被转发到替补的 @ref{307,,pgettext()} 方法。否则，返回 @emph{message} ID。


3.8 新版功能.

@end deffn

@geindex npgettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations npgettext}@anchor{307a}
@deffn {方法} npgettext (context, singular, plural, n)

查找消息 ID 的复数形式。@emph{singular} 用作消息 ID，用于在编目中查找，同时 @emph{n} 用于确定使用哪种复数形式。

如果在编目中没有找到 @emph{context} 对应的消息 ID，且配置了替补，则查找请求将被转发到替补的 @ref{3064,,npgettext()} 方法。否则，当 @emph{n} 为 1 时返回 @emph{singular}，其他情况返回 @emph{plural}。


3.8 新版功能.

@end deffn

@geindex lgettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations lgettext}@anchor{307b}
@deffn {方法} lgettext (message)
@end deffn

@geindex lngettext() (gettext.GNUTranslations 方法)
@anchor{library/gettext gettext GNUTranslations lngettext}@anchor{307c}
@deffn {方法} lngettext (singular, plural, n)

与 @ref{3077,,gettext()} 和 @ref{3078,,ngettext()} 等效，但是如果没有用 @ref{3c4,,set_output_charset()} 显式设置编码，则返回的翻译将以首选系统编码来编码字节串。

@cartouche
@quotation 警告 
应避免在 Python 3 中使用这些方法。请参阅 @ref{3be,,lgettext()} 函数的警告。
@end quotation
@end cartouche


Deprecated since version 3.8, will be removed in version 3.10.

@end deffn
@end deffn

@node Solaris 消息编目支持,编目构造器,GNUTranslations 类,基于类的 API
@anchor{library/gettext solaris-message-catalog-support}@anchor{307d}
@subsubsection Solaris 消息编目支持


Solaris 操作系统定义了自己的二进制 @code{.mo} 文件格式，但由于找不到该格式的文档，因此目前不支持该格式。

@node 编目构造器,,Solaris 消息编目支持,基于类的 API
@anchor{library/gettext the-catalog-constructor}@anchor{307e}
@subsubsection 编目构造器


@geindex GNOME

GNOME 用的 @ref{87,,gettext} 模块是 James Henstridge 写的版本，但该版本的 API 略有不同。它文档中的用法是:

@example
import gettext
cat = gettext.Catalog(domain, localedir)
_ = cat.gettext
print(_('hello world'))
@end example

为了与本模块的旧版本兼容，@code{Catalog()} 函数是上述 @ref{3c5,,translation()} 函数的别名。

本模块与 Henstridge 的模块有一个区别：他的编目对象支持通过映射 API 进行访问，但是该特性似乎从未使用过，因此目前不支持该特性。

@node 国际化 I18N 你的程序和模块,致谢<9>,基于类的 API,gettext --- 多语种国际化服务
@anchor{library/gettext internationalizing-your-programs-and-modules}@anchor{307f}
@subsubsection 国际化 (I18N) 你的程序和模块


国际化 (I18N) 是指使程序可切换多种语言的操作。本地化 (L10N) 是指程序的适配能力，一旦程序被国际化，就能适配当地的语言和文化习惯。为了向 Python 程序提供不同语言的消息，需要执行以下步骤：


@enumerate 

@item 
准备程序或模块，将可翻译的字符串特别标记起来

@item 
在已标记的文件上运行一套工具，用来生成原始消息编目

@item 
创建消息编目的不同语言的翻译

@item 
使用 @ref{87,,gettext} 模块，以便正确翻译消息字符串
@end enumerate

为了准备代码以达成 I18N，需要巡视文件中的所有字符串。所有要翻译的字符串都应包括在 @code{_('...')} 内，以此打上标记——也就是调用 @code{_()} 函数。例如:

@example
filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)
@end example

在这个例子中，字符串 @code{'writing a log message'} 被标记为待翻译，而字符串 @code{'mylog.txt'} 和 @code{'w'} 没有被标记。

有一些工具可以将待翻译的字符串提取出来。原版的 GNU @code{gettext} 仅支持 C 或 C++ 源代码，但其扩展版 @code{xgettext} 可以扫描多种语言的代码（包括 Python），来找出标记为可翻译的字符串。Babel@footnote{http://babel.pocoo.org/} 是一个 Python 国际化库，其中包含一个 @code{pybabel} 脚本，用于提取并编译消息编目。François Pinard 写的称为 @code{xpot} 的程序也能完成类似的工作，可从他的 po-utils 软件包@footnote{https://github.com/pinard/po-utils} 中获取。

（Python 还包括了这些程序的纯 Python 版本，称为 @code{pygettext.py} 和 @code{msgfmt.py}，某些 Python 发行版已经安装了它们。@code{pygettext.py} 类似于 @code{xgettext}，但只能理解 Python 源代码，无法处理诸如 C 或 C++ 的其他编程语言。@code{pygettext.py} 支持的命令行界面类似于 @code{xgettext}，查看其详细用法请运行 @code{pygettext.py --help}。@code{msgfmt.py} 与 GNU @code{msgfmt} 是二进制兼容的。有了这两个程序，可以不需要 GNU @code{gettext} 包来国际化 Python 应用程序。）

@code{xgettext}、@code{pygettext} 或类似工具生成的 @code{.po} 文件就是消息编目。它们是结构化的人类可读文件，包含源代码中所有被标记的字符串，以及这些字符串的翻译的占位符。

然后把这些 @code{.po} 文件的副本交给各个人工译者，他们为所支持的每种自然语言编写翻译。译者以 @code{<语言名称>.po} 文件的形式发送回翻译完的某个语言的版本，将该文件用 @code{msgfmt} 程序编译为机器可读的 @code{.mo} 二进制编目文件。@ref{87,,gettext} 模块使用 @code{.mo} 文件在运行时进行实际的翻译处理。

如何在代码中使用 @ref{87,,gettext} 模块取决于国际化单个模块还是整个应用程序。接下来的两节将讨论每种情况。

@menu
* 本地化你的模块:: 
* 本地化你的应用程序:: 
* 即时更改语言:: 
* 延迟翻译:: 

@end menu

@node 本地化你的模块,本地化你的应用程序,,国际化 I18N 你的程序和模块
@anchor{library/gettext localizing-your-module}@anchor{3080}
@subsubsection 本地化你的模块


如果要本地化模块，则切忌进行全局性的更改，如更改内建命名空间。不应使用 GNU @code{gettext} API，而应使用基于类的 API。

假设你的模块叫做 "spam"，并且该模块的各种自然语言翻译 @code{.mo} 文件存放于 @code{/usr/share/locale}，为 GNU @code{gettext} 格式。以下内容应放在模块顶部:

@example
import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.gettext
@end example

@node 本地化你的应用程序,即时更改语言,本地化你的模块,国际化 I18N 你的程序和模块
@anchor{library/gettext localizing-your-application}@anchor{3081}
@subsubsection 本地化你的应用程序


如果正在本地化应用程序，可以将 @code{_()} 函数全局安装到内建命名空间中，通常在应用程序的主文件中安装。这将使某个应用程序的所有文件都能使用 @code{_('...')}，而不必在每个文件中显式安装它。

最简单的情况，就只需将以下代码添加到应用程序的主程序文件中:

@example
import gettext
gettext.install('myapplication')
@end example

如果需要设置语言环境目录，可以将其传递给 @ref{3c6,,install()} 函数:

@example
import gettext
gettext.install('myapplication', '/usr/share/locale')
@end example

@node 即时更改语言,延迟翻译,本地化你的应用程序,国际化 I18N 你的程序和模块
@anchor{library/gettext changing-languages-on-the-fly}@anchor{3082}
@subsubsection 即时更改语言


如果程序需要同时支持多种语言，则可能需要创建多个翻译实例，然后在它们之间进行显式切换，如下所示:

@example
import gettext

lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])

# start by using language1
lang1.install()

# ... time goes by, user selects language 2
lang2.install()

# ... more time goes by, user selects language 3
lang3.install()
@end example

@node 延迟翻译,,即时更改语言,国际化 I18N 你的程序和模块
@anchor{library/gettext deferred-translations}@anchor{3083}
@subsubsection 延迟翻译


在大多数代码中，字符串会在编写位置进行翻译。但偶尔需要将字符串标记为待翻译，实际翻译却推迟到后面。一个典型的例子是:

@example
animals = ['mollusk',
           'albatross',
           'rat',
           'penguin',
           'python', ]
# ...
for a in animals:
    print(a)
@end example

此处希望将 @code{animals} 列表中的字符串标记为可翻译，但不希望在打印之前对它们进行翻译。

这是处理该情况的一种方式:

@example
def _(message): return message

animals = [_('mollusk'),
           _('albatross'),
           _('rat'),
           _('penguin'),
           _('python'), ]

del _

# ...
for a in animals:
    print(_(a))
@end example

该方法之所以可行，是因为 @code{_()} 的虚定义只是简单地返回了原本的字符串。并且该虚定义将临时覆盖内建命名空间中 @code{_()} 的定义（直到 @ref{13d1,,del} 命令）。即使先前在本地命名空间中已经有了 @code{_()} 的定义也请注意。

注意，第二次使用 @code{_()} 不会认为 "a" 可以传递给 @code{gettext} 程序去翻译，因为该参数不是字符串文字。

解决该问题的另一种方法是下面这个例子:

@example
def N_(message): return message

animals = [N_('mollusk'),
           N_('albatross'),
           N_('rat'),
           N_('penguin'),
           N_('python'), ]

# ...
for a in animals:
    print(_(a))
@end example

这种情况下标记可翻译的字符串使用的是函数 @code{N_()}，该函数不会与 @code{_()} 的任何定义冲突。但是，需要教会消息提取程序去寻找用 @code{N_()} 标记的可翻译字符串。@code{xgettext}, @code{pygettext}, @code{pybabel extract} 和 @code{xpot} 都支持此功能，使用 @code{-k} 命令行开关即可。这里选择 @code{N_()} 为名称完全是任意的，它也能轻易改为 @code{MarkThisStringForTranslation()}。

@node 致谢<9>,,国际化 I18N 你的程序和模块,gettext --- 多语种国际化服务
@anchor{library/gettext acknowledgements}@anchor{3084}
@subsubsection 致谢


以下人员为创建此模块贡献了代码、反馈、设计建议、早期实现和宝贵的经验：


@itemize *

@item 
Peter Funk

@item 
James Henstridge

@item 
Juan David Ibáñez Palomar

@item 
Marc-André Lemburg

@item 
Martin von Löwis

@item 
François Pinard

@item 
Barry Warsaw

@item 
Gustavo Niemeyer
@end itemize

@node locale --- 国际化服务,,gettext --- 多语种国际化服务,国际化
@anchor{library/locale doc}@anchor{3085}@anchor{library/locale locale-internationalization-services}@anchor{3086}@anchor{library/locale module-locale}@anchor{a9}
@subsection @code{locale} --- 国际化服务


@geindex locale (模块)

@strong{源代码：} Lib/locale.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/locale.py}


__________________________________________________________________


@ref{a9,,locale} 模块开通了 POSIX 本地化数据库和功能的访问。POSIX 本地化机制让程序员能够为应用程序处理某些本地化的问题，而不需要去了解运行软件的每个国家的全部文化特点。

@geindex 模块; _locale

@ref{a9,,locale} 模块是在 @code{_locale} 模块的基础上实现的，而 _locale 则又用到了 ANSI C 语言实现的本地化功能。

@ref{a9,,locale} 模块定义了以下异常和函数：

@geindex Error
@anchor{library/locale locale Error}@anchor{3087}
@deffn {例外} locale.Error

当传给 @ref{2196,,setlocale()} 的 locale 无法识别时，会触发异常。
@end deffn

@geindex setlocale() (在 locale 模块中)
@anchor{library/locale locale setlocale}@anchor{2196}
@deffn {函数} locale.setlocale (category, locale=None)

如果给定了 @emph{locale} 而不是 @code{None}，@ref{2196,,setlocale()} 会修改 @emph{category} 的 locale 设置。可用的类别会在下面的数据描述中列出。@emph{locale} 可以是一个字符串，也可以是两个字符串（语言代码和编码）组成的可迭代对象。若为可迭代对象，则会用地区别名引擎转换为一个地区名称。若为空字符串则指明采用用户的默认设置。如果 locale 设置修改失败，会触发 @ref{3087,,Error} 异常。如果成功则返回新的 locale 设置。

如果省略 @emph{locale} 或为 @code{None}，将返回 @emph{category} 但当前设置。

@ref{2196,,setlocale()} 在大多数系统上都不是线程安全的。应用程序通常会如下调用：

@example
import locale
locale.setlocale(locale.LC_ALL, '@w{'})
@end example

这会把所有类别的 locale 都设为用户的默认设置（通常在 
@geindex LANG
@geindex 环境变量; LANG
@code{LANG} 环境变量中指定）。如果后续 locale 没有改动，则使用多线程应该不会产生问题。
@end deffn

@geindex localeconv() (在 locale 模块中)
@anchor{library/locale locale localeconv}@anchor{58d}
@deffn {函数} locale.localeconv ()

以字典的形式返回本地约定的数据库。此字典具有以下字符串作为键：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类别

@tab

键

@tab

含义

@item

@ref{3088,,LC_NUMERIC}

@tab

@code{'decimal_point'}

@tab

小数点字符。

@item

@tab

@code{'grouping'}

@tab

数字列表，指定 @code{'thousands_sep'} 应该出现的位置。 如果列表以 @ref{3089,,CHAR_MAX} 结束，则不会作分组。如果列表以 @code{0} 结束，则重复使用最后的分组大小。

@item

@tab

@code{'thousands_sep'}

@tab

组之间使用的字符。

@item

@ref{308a,,LC_MONETARY}

@tab

@code{'int_curr_symbol'}

@tab

国际货币符号。

@item

@tab

@code{'currency_symbol'}

@tab

当地货币符号。

@item

@tab

@code{'p_cs_precedes/n_cs_precedes'}

@tab

货币符号是否在值之前（对于正值或负值）。

@item

@tab

@code{'p_sep_by_space/n_sep_by_space'}

@tab

货币符号是否通过空格与值分隔（对于正值或负值）。

@item

@tab

@code{'mon_decimal_point'}

@tab

用于货币金额的小数点。

@item

@tab

@code{'frac_digits'}

@tab

货币值的本地格式中使用的小数位数。

@item

@tab

@code{'int_frac_digits'}

@tab

货币价值的国际格式中使用的小数位数。

@item

@tab

@code{'mon_thousands_sep'}

@tab

用于货币值的组分隔符。

@item

@tab

@code{'mon_grouping'}

@tab

相当于 @code{'grouping'} ，用于货币价值。

@item

@tab

@code{'positive_sign'}

@tab

用于标注正货币价值的符号。

@item

@tab

@code{'negative_sign'}

@tab

用于注释负货币价值的符号。

@item

@tab

@code{'p_sign_posn/n_sign_posn'}

@tab

符号的位置（对于正值或负值），见下文。

@end multitable


可以将所有数值设置为 @ref{3089,,CHAR_MAX} ，以指示此语言环境中未指定任何值。

下面给出了 @code{'p_sign_posn'} 和 @code{'n_sign_posn'} 的可能值。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

解释

@item

@code{0}

@tab

被括号括起来的货币和金额。

@item

@code{1}

@tab

该标志应位于值和货币符号之前。

@item

@code{2}

@tab

该标志应位于值和货币符号之后。

@item

@code{3}

@tab

标志应该紧跟在值之前。

@item

@code{4}

@tab

标志应该紧跟值项。

@item

@code{CHAR_MAX}

@tab

此语言环境中未指定任何内容。

@end multitable


该函数将 @code{LC_CTYPE} 地区设为 @code{LC_NUMERIC} 地区，若地区不同且数字或货币字符为非 ASCII，则设置为 @code{LC_MONETARY} 地区。这个临时的改变会影响到其他线程。


在 3.7 版更改: 现在在某些情况下，该函数会将 @code{LC_CTYPE} 地区设为 @code{LC_NUMERIC} 地区。

@end deffn

@geindex nl_langinfo() (在 locale 模块中)
@anchor{library/locale locale nl_langinfo}@anchor{308b}
@deffn {函数} locale.nl_langinfo (option)

以字符串形式返回一些地区相关的信息。本函数并非在所有系统都可用，而且可用的 option 在不同平台上也可能不同。可填的参数值为数值，在 locale 模块中提供了对应的符号常量。

@ref{308b,,nl_langinfo()} 函数可接受以下值。大部分含义都取自 GNU C 库。

@geindex CODESET() (在 locale 模块中)
@anchor{library/locale locale CODESET}@anchor{308c}
@deffn {数据} locale.CODESET

获取一个字符串，代表所选地区采用的字符编码名称。
@end deffn

@geindex D_T_FMT() (在 locale 模块中)
@anchor{library/locale locale D_T_FMT}@anchor{308d}
@deffn {数据} locale.D_T_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示日期和时间。
@end deffn

@geindex D_FMT() (在 locale 模块中)
@anchor{library/locale locale D_FMT}@anchor{308e}
@deffn {数据} locale.D_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示日期。
@end deffn

@geindex T_FMT() (在 locale 模块中)
@anchor{library/locale locale T_FMT}@anchor{308f}
@deffn {数据} locale.T_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示时间。
@end deffn

@geindex T_FMT_AMPM() (在 locale 模块中)
@anchor{library/locale locale T_FMT_AMPM}@anchor{3090}
@deffn {数据} locale.T_FMT_AMPM

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以 am/pm 的格式表示时间。
@end deffn


@deffn {数据} DAY_1 ... DAY_7

获取一周中第 n 天的名称。

@cartouche
@quotation 注解 
这里遵循美国惯例，即 @code{DAY_1} 是星期天，而不是国际惯例（ISO 8601），即星期一是一周的第一天。
@end quotation
@end cartouche
@end deffn


@deffn {数据} ABDAY_1 ... ABDAY_7

获取一周中第 n 天的缩写名称。
@end deffn


@deffn {数据} MON_1 ... MON_12

获取第 n 个月的名称。
@end deffn


@deffn {数据} ABMON_1 ... ABMON_12

获取第 n 个月的缩写名称。
@end deffn

@geindex RADIXCHAR() (在 locale 模块中)
@anchor{library/locale locale RADIXCHAR}@anchor{3091}
@deffn {数据} locale.RADIXCHAR

获取小数点字符（小数点、小数逗号等）。
@end deffn

@geindex THOUSEP() (在 locale 模块中)
@anchor{library/locale locale THOUSEP}@anchor{3092}
@deffn {数据} locale.THOUSEP

获取千位数（三位数一组）的分隔符。
@end deffn

@geindex YESEXPR() (在 locale 模块中)
@anchor{library/locale locale YESEXPR}@anchor{3093}
@deffn {数据} locale.YESEXPR

获取一个可供 regex 函数使用的正则表达式，用于识别需要回答是或否的问题的肯定回答。

@cartouche
@quotation 注解 
该表达式的语法适用于 C 库的 @code{regex()} 函数，可能与 @ref{dd,,re} 中的语法不一样。
@end quotation
@end cartouche
@end deffn

@geindex NOEXPR() (在 locale 模块中)
@anchor{library/locale locale NOEXPR}@anchor{3094}
@deffn {数据} locale.NOEXPR

获取一个可供 regex(3) 函数使用的正则表达式，用于识别需要回答是或否的问题的否定回答。
@end deffn

@geindex CRNCYSTR() (在 locale 模块中)
@anchor{library/locale locale CRNCYSTR}@anchor{3095}
@deffn {数据} locale.CRNCYSTR

获取货币符号，如果符号应位于数字之前，则在其前面加上“-”；如果符号应位于数字之后，则前面加“+”；如果符号应取代小数点字符，则前面加“.”。
@end deffn

@geindex ERA() (在 locale 模块中)
@anchor{library/locale locale ERA}@anchor{3096}
@deffn {数据} locale.ERA

获取一个字符串，代表当前地区使用的纪元。

大多数地区都没有定义该值。定义了该值的一个案例日本。日本传统的日期表示方法中，包含了当时天皇统治朝代的名称。

通常没有必要直接使用该值。在格式串中指定 @code{E} 符号，会让  @ref{c40,,time.strftime()} 函数启用此信息。返回字符串的格式并没有定义，因此不得假定各个系统都能理解。
@end deffn

@geindex ERA_D_T_FMT() (在 locale 模块中)
@anchor{library/locale locale ERA_D_T_FMT}@anchor{3097}
@deffn {数据} locale.ERA_D_T_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示带纪元的日期和时间。
@end deffn

@geindex ERA_D_FMT() (在 locale 模块中)
@anchor{library/locale locale ERA_D_FMT}@anchor{3098}
@deffn {数据} locale.ERA_D_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示带纪元的日期。
@end deffn

@geindex ERA_T_FMT() (在 locale 模块中)
@anchor{library/locale locale ERA_T_FMT}@anchor{3099}
@deffn {数据} locale.ERA_T_FMT

获取一个字符串，可用作 @ref{c40,,time.strftime()} 的格式串，以便以地区特定格式表示带纪元的时间。
@end deffn

@geindex ALT_DIGITS() (在 locale 模块中)
@anchor{library/locale locale ALT_DIGITS}@anchor{309a}
@deffn {数据} locale.ALT_DIGITS

获取 0 到 99 的表示法，最多不超过 100 个值。
@end deffn
@end deffn

@geindex getdefaultlocale() (在 locale 模块中)
@anchor{library/locale locale getdefaultlocale}@anchor{14c2}
@deffn {函数} locale.getdefaultlocale ([envvars])

尝试确定默认的地区设置，并以 @code{(language code, encoding)} 元组的形式返回。

根据 POSIX 的规范，未调用 @code{setlocale(LC_ALL, '@w{'})} 的程序采用可移植的 @code{'C'} 区域设置运行。 调用 @code{setlocale(LC_ALL, '@w{'})} 则可采用 
@geindex LANG
@geindex 环境变量; LANG
@code{LANG} 变量定义的默认区域。 由于不想干扰当前的区域设置，因此就以上述方式进行了模拟。

为了维持与其他平台的兼容性，不仅需要检测 
@geindex LANG
@geindex 环境变量; LANG
@code{LANG} 变量，还需要检测 envvars 参数给出的变量列表。首先发现的定义将被采用。 @emph{envvars} 默认为 GNU gettext 采用的搜索路径；必须包含 @code{'LANG'} 变量。 GNU gettext 的搜索路径依次包含了 @code{'LC_ALL'}、@code{'LC_CTYPE'}、@code{'LANG'} 和 @code{'LANGUAGE'}。

除了 @code{'C'} 之外，语言代码对应 
@geindex RFC; RFC 1766
RFC 1766@footnote{https://tools.ietf.org/html/rfc1766.html} 标准。如果 @emph{语言代码} 和 @emph{编码}  不能确定，可为 @code{None}。
@end deffn

@geindex getlocale() (在 locale 模块中)
@anchor{library/locale locale getlocale}@anchor{1a7a}
@deffn {函数} locale.getlocale (category=LC_CTYPE)

以列表的形式返回指定地区类别的当前设置，结果包括 @emph{语言代码} 、@emph{编码}。@emph{category} 可以是 @code{LC_*}  之一， @ref{309b,,LC_ALL} 除外。默认为 @ref{309c,,LC_CTYPE}。

除了 @code{'C'} 之外，语言代码对应 
@geindex RFC; RFC 1766
RFC 1766@footnote{https://tools.ietf.org/html/rfc1766.html} 标准。如果 @emph{语言代码} 和 @emph{编码}  不能确定，可为 @code{None}。
@end deffn

@geindex getpreferredencoding() (在 locale 模块中)
@anchor{library/locale locale getpreferredencoding}@anchor{4b4}
@deffn {函数} locale.getpreferredencoding (do_setlocale=True)

Return the encoding used for text data, according to user preferences.  User
preferences are expressed differently on different systems, and might not be
available programmatically on some systems, so this function only returns a
guess.

某些系统必须调用 @ref{2196,,setlocale()} 才能获取用户偏好，所以本函数不是线程安全的。如果不需要或不希望调用 setlocale，@emph{do_setlocale} 应设为 @code{False}。

On Android or in the UTF-8 mode (@ref{297,,-X} @code{utf8} option), always
return @code{'UTF-8'}, the locale and the @emph{do_setlocale} argument are ignored.


在 3.7 版更改: The function now always returns @code{UTF-8} on Android or if the UTF-8 mode
is enabled.

@end deffn

@geindex normalize() (在 locale 模块中)
@anchor{library/locale locale normalize}@anchor{309d}
@deffn {函数} locale.normalize (localename)

为给定的区域名称返回标准代码。返回的区域代码已经格式化，可供 @ref{2196,,setlocale()} 使用。 如果标准化操作失败，则返回原名称。

如果给出的编码无法识别，则本函数默认采用区域代码的默认编码，这正类似于 @ref{2196,,setlocale()}。
@end deffn

@geindex resetlocale() (在 locale 模块中)
@anchor{library/locale locale resetlocale}@anchor{309e}
@deffn {函数} locale.resetlocale (category=LC_ALL)

将 @emph{category} 的区域设为默认值。

默认设置通过调用 @ref{14c2,,getdefaultlocale()} 确定。@emph{category} 默认为 @ref{309b,,LC_ALL}。
@end deffn

@geindex strcoll() (在 locale 模块中)
@anchor{library/locale locale strcoll}@anchor{309f}
@deffn {函数} locale.strcoll (string1, string2)

根据当前的 @ref{30a0,,LC_COLLATE} 设置，对两个字符串进行比较。与其他比较函数一样，根据 @emph{string1} 位于 @emph{string2} 之前、之后或是相同，返回负值、、正值或者 @code{0}。
@end deffn

@geindex strxfrm() (在 locale 模块中)
@anchor{library/locale locale strxfrm}@anchor{30a1}
@deffn {函数} locale.strxfrm (string)

将字符串转换为可用于本地化比较的字符串。例如 @code{strxfrm(s1) < strxfrm(s2)} 相当于 @code{strcoll(s1, s2) < 0}。在重复比较同一个字符串时，可能会用到本函数，比如整理字符串列表时。
@end deffn

@geindex format_string() (在 locale 模块中)
@anchor{library/locale locale format_string}@anchor{4b3}
@deffn {函数} locale.format_string (format, val, grouping=False, monetary=False)

根据当前的 @ref{3088,,LC_NUMERIC} 设置，对数字 @emph{val} 进行格式化。格式将遵循 @code{%} 运算符的约定。浮点值的小数点会按需修改。若 @emph{grouping} 为 True，则还会考虑分组。

若 @emph{monetary} 为 True，则会用到货币千位分隔符和分组字符串。

格式化符的处理类似 @code{format % val} ，但会考虑到当前的区域设置。


在 3.7 版更改: 增加了关键字参数 @emph{monetary} 。

@end deffn

@geindex format() (在 locale 模块中)
@anchor{library/locale locale format}@anchor{572}
@deffn {函数} locale.format (format, val, grouping=False, monetary=False)

请注意，本函数的工作原理与 @ref{4b3,,format_string()} 类似，但只对 @code{%char} 格式符起作用。 比如 @code{'%f'} 和 @code{'%.0f'} 都是有效的格式符，但 @code{'%f KiB'} 则不是。

若想用到全部的格式化串，请采用 @ref{4b3,,format_string()}。


3.7 版后已移除: 请改用 @ref{4b3,,format_string()} 。

@end deffn

@geindex currency() (在 locale 模块中)
@anchor{library/locale locale currency}@anchor{30a2}
@deffn {函数} locale.currency (val, symbol=True, grouping=False, international=False)

根据当前的 @ref{308a,,LC_MONETARY} 设置，对数字 @emph{val} 进行格式化。

如果 @emph{symbol} 为 True（默认值），则返回的字符串将包含货币符号。如果 @emph{grouping} 为 True（非默认值），则会进行分组。如果 @emph{international} 为 True（非默认值），将采用国际货币符号。

请注意，本函数对区域 “C” 无效，所以必须先通过 @ref{2196,,setlocale()} 设置一个区域。
@end deffn

@geindex str() (在 locale 模块中)
@anchor{library/locale locale str}@anchor{30a3}
@deffn {函数} locale.str (float)

对浮点数进行格式化，格式要求与内置函数 @code{str(float)} 相同，但会考虑小数点。
@end deffn

@geindex delocalize() (在 locale 模块中)
@anchor{library/locale locale delocalize}@anchor{806}
@deffn {函数} locale.delocalize (string)

根据 @ref{3088,,LC_NUMERIC} 的设置，将字符串转换为格式化后的数字字符串。


3.5 新版功能.

@end deffn

@geindex atof() (在 locale 模块中)
@anchor{library/locale locale atof}@anchor{30a4}
@deffn {函数} locale.atof (string, func=float)

将一个字符串转换为数字，遵循 @ref{3088,,LC_NUMERIC} 设置，通过在 @emph{string} 上调用 @ref{806,,delocalize()} 的结果上调用 @emph{func} 来实现。
@end deffn

@geindex atoi() (在 locale 模块中)
@anchor{library/locale locale atoi}@anchor{30a5}
@deffn {函数} locale.atoi (string)

按照 @ref{3088,,LC_NUMERIC} 的约定，将字符串转换为整数。
@end deffn

@geindex LC_CTYPE() (在 locale 模块中)
@anchor{library/locale locale LC_CTYPE}@anchor{309c}
@deffn {数据} locale.LC_CTYPE

@geindex 模块; string

字符型函数的区域类别。根据该类别的设置，模块 @ref{f6,,string} 中处理大小写的函数会改变操作方式。
@end deffn

@geindex LC_COLLATE() (在 locale 模块中)
@anchor{library/locale locale LC_COLLATE}@anchor{30a0}
@deffn {数据} locale.LC_COLLATE

字符串排序会用到的区域类别。 将会影响 @ref{a9,,locale} 模块的 @ref{309f,,strcoll()} 和 @ref{30a1,,strxfrm()} 函数。
@end deffn

@geindex LC_TIME() (在 locale 模块中)
@anchor{library/locale locale LC_TIME}@anchor{30a6}
@deffn {数据} locale.LC_TIME

格式化时间时会用到的区域类别。 @ref{c40,,time.strftime()} 函数会参考这些约定。
@end deffn

@geindex LC_MONETARY() (在 locale 模块中)
@anchor{library/locale locale LC_MONETARY}@anchor{308a}
@deffn {数据} locale.LC_MONETARY

格式化货币值时会用到的区域类别。可用值可由 @ref{58d,,localeconv()} 函数获取。
@end deffn

@geindex LC_MESSAGES() (在 locale 模块中)
@anchor{library/locale locale LC_MESSAGES}@anchor{30a7}
@deffn {数据} locale.LC_MESSAGES

显示消息时用到的区域类别。目前 Python 不支持应用定制的本地化消息。 由操作系统显示的消息，比如由 @ref{2093,,os.strerror()} 返回的消息可能会受到该类别的影响。
@end deffn

@geindex LC_NUMERIC() (在 locale 模块中)
@anchor{library/locale locale LC_NUMERIC}@anchor{3088}
@deffn {数据} locale.LC_NUMERIC

格式化数字时用到的区域类别。 @ref{a9,,locale} 模块的 @ref{572,,format()} 、 @ref{30a5,,atoi()} 、 @ref{30a4,,atof()} 和 @ref{30a3,,str()} 函数会受到该类别的影响。其他所有数字格式化操作不受影响。
@end deffn

@geindex LC_ALL() (在 locale 模块中)
@anchor{library/locale locale LC_ALL}@anchor{309b}
@deffn {数据} locale.LC_ALL

混合所有的区域设置。如果在区域改动时使用该标志，将尝试设置所有类别的区域参数。只要有任何一个类别设置失败，就不会修改任何类别。在使用此标志获取区域设置时，会返回一个代表所有类别设置的字符串。之后可用此字符串恢复设置。
@end deffn

@geindex CHAR_MAX() (在 locale 模块中)
@anchor{library/locale locale CHAR_MAX}@anchor{3089}
@deffn {数据} locale.CHAR_MAX

一个符号常量， @ref{58d,,localeconv()} 返回多个值时将会用到。
@end deffn

示例:

@example
>>> import locale
>>> loc = locale.getlocale()  # get current locale
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '@w{'})   # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale
@end example

@menu
* 背景、细节、提示、技巧和注意事项:: 
* 针对扩展程序编写人员和嵌入Python 运行的程序:: 
* 访问信息目录:: 

@end menu

@node 背景、细节、提示、技巧和注意事项,针对扩展程序编写人员和嵌入Python 运行的程序,,locale --- 国际化服务
@anchor{library/locale background-details-hints-tips-and-caveats}@anchor{30a8}
@subsubsection 背景、细节、提示、技巧和注意事项


The C standard defines the locale as a program-wide property that may be
relatively expensive to change.  On top of that, some implementation are broken
in such a way that frequent locale changes may cause core dumps.  This makes the
locale somewhat painful to use correctly.

当程序第一次启动时，无论用户偏好定义成什么，区域值都是 @code{C}。不过有一个例外，就是在启动时修改 @ref{309c,,LC_CTYPE} 类别，设置当前区域编码为用户偏好编码。程序必须调用 @code{setlocale(LC_ALL, '@w{'})} 明确表示用户偏好区域将设为其他类别。

若要从库程序中调用 @ref{2196,,setlocale()} ，通常这不是个好主意，因为副作用是会影响整个程序。保存和恢复区域设置也几乎一样糟糕：不仅代价高昂，而且会影响到恢复之前运行的其他线程。

如果是要编写通用模块，需要有一种不受区域设置影响的操作方式（比如某些用到 @ref{c40,,time.strftime()} 的格式），将不得不寻找一种不用标准库的方案。更好的办法是说服自己，可以采纳区域设置。只有在万不得已的情况下，才能用文档标注出模块与非 @code{C} 区域设置不兼容。

根据区域设置进行数字运算的唯一方法，就是采用本模块定义的函数：@ref{30a4,,atof()} 、 @ref{30a5,,atoi()} 、 @ref{572,,format()} 、 @ref{30a3,,str()}。

无法根据区域设置进行大小写转换和字符分类。对于（Unicode）文本字符串来说，这些操作都是根据字符值进行的；而对于字节符串来说，转换和分类则是根据字节的 ASCII 值进行的，高位被置位的字节（即非 ASCII 字节）永远不会被转换或被视作字母或空白符之类。

@node 针对扩展程序编写人员和嵌入Python 运行的程序,访问信息目录,背景、细节、提示、技巧和注意事项,locale --- 国际化服务
@anchor{library/locale embedding-locale}@anchor{30a9}@anchor{library/locale for-extension-writers-and-programs-that-embed-python}@anchor{30aa}
@subsubsection 针对扩展程序编写人员和嵌入Python 运行的程序


除了要查询当前区域，扩展模块不应去调用 @ref{2196,,setlocale()}。但由于返回值只能用于恢复设置，所以也没什么用（也许只能用于确认是否为 @code{C}）。

当 Python 代码利用 @ref{a9,,locale} 模块修改区域设置时，也会影响到嵌入 Python 运行的应用程序。如果嵌入运行的程序不希望发生这种情况，则应从  @code{config.c} 文件的内置模块表中删除 @code{_locale} 扩展模块（所有操作均是由它完成的），并确保 @code{_locale} 模块不能成为一个共享库。

@node 访问信息目录,,针对扩展程序编写人员和嵌入Python 运行的程序,locale --- 国际化服务
@anchor{library/locale access-to-message-catalogs}@anchor{30ab}@anchor{library/locale locale-gettext}@anchor{30ac}
@subsubsection 访问信息目录


@geindex gettext() (在 locale 模块中)
@anchor{library/locale locale gettext}@anchor{30ad}
@deffn {函数} locale.gettext (msg)
@end deffn

@geindex dgettext() (在 locale 模块中)
@anchor{library/locale locale dgettext}@anchor{30ae}
@deffn {函数} locale.dgettext (domain, msg)
@end deffn

@geindex dcgettext() (在 locale 模块中)
@anchor{library/locale locale dcgettext}@anchor{30af}
@deffn {函数} locale.dcgettext (domain, msg, category)
@end deffn

@geindex textdomain() (在 locale 模块中)
@anchor{library/locale locale textdomain}@anchor{30b0}
@deffn {函数} locale.textdomain (domain)
@end deffn

@geindex bindtextdomain() (在 locale 模块中)
@anchor{library/locale locale bindtextdomain}@anchor{30b1}
@deffn {函数} locale.bindtextdomain (domain, dir)
@end deffn

在提供 gettext 接口的系统中，locale 模块暴露出了 C 库的接口。它由 @code{gettext()} 、@code{dgettext()} 、@code{dcgettext()} 、 @code{textdomain()} 、@code{bindtextdomain()} 和 @code{bind_textdomain_codeset()} 等函数组成。 他们与 @ref{87,,gettext} 模块中的同名函数类似，但采用了 C 库二进制格式的消息目录，以及 C 库的搜索算法来查找消息目录。

Python 应用程序通常不需要调用这些函数，而应改用 @ref{87,,gettext}。这条规则的一个已知例外，是与附加 C 库链接的应用程序，他们在内部调用了 @code{gettext()} 或 @code{dcgettext()}。对于这些应用程序，可能有必要绑定文本域，以便库可以准确找到他们的信息目录。

@node 程序框架,Tk图形用户界面 GUI,国际化,Python 标准库
@anchor{library/frameworks doc}@anchor{30b2}@anchor{library/frameworks frameworks}@anchor{30b3}@anchor{library/frameworks program-frameworks}@anchor{30b4}
@section 程序框架


本章中描述的模块是很大程度上决定程序结构的框架。 目前，这里描述的模块都面向编写命令行接口。

本章描述的完整模块列表如下：

@menu
* turtle: turtle --- 海龟绘图. 海龟绘图
* cmd: cmd --- 支持面向行的命令解释器. 支持面向行的命令解释器
* shlex —— 简单的词义分析:: 

@end menu

@node turtle --- 海龟绘图,cmd --- 支持面向行的命令解释器,,程序框架
@anchor{library/turtle doc}@anchor{30b5}@anchor{library/turtle module-turtle}@anchor{11f}@anchor{library/turtle turtle-turtle-graphics}@anchor{30b6}
@subsection @code{turtle} --- 海龟绘图


@geindex turtle (模块)

@strong{源码：} Lib/turtle.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/turtle.py}

@c from turtle import *
@c turtle = Turtle()


__________________________________________________________________


@menu
* 概述: 概述<11>. 
* 可用的 Turtle 和 Screen 方法概览:: 
* RawTurtle/Turtle 方法和对应函数:: 
* TurtleScreen/Screen 方法及对应函数:: 
* 公共类:: 
* 帮助与配置:: 
* turtledemo: turtledemo --- 演示脚本集. 演示脚本集
* Python 2.6 之后的变化: Python 2 6 之后的变化. 
* Python 3.0 之后的变化: Python 3 0 之后的变化. 

@end menu

@node 概述<11>,可用的 Turtle 和 Screen 方法概览,,turtle --- 海龟绘图
@anchor{library/turtle introduction}@anchor{30b7}
@subsubsection 概述


海龟绘图很适合用来引导孩子学习编程。 最初来自于 Wally Feurzeig, Seymour Papert 和 Cynthia Solomon 于 1967 年所创造的 Logo 编程语言。

请想象绘图区有一只机器海龟，起始位置在 x-y 平面的 (0, 0) 点。先执行 @code{import turtle}，再执行 @code{turtle.forward(15)}，它将(在屏幕上)朝所面对的 x 轴正方向前进 15 像素，随着它的移动画出一条线段。再执行 @code{turtle.right(25)}，它将原地右转 25 度。

@subsubheading Turtle star



使用海龟绘图可以编写重复执行简单动作的程序画出精细复杂的形状。

@image{python-figures/turtle-star,,,,png}

@example
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()
@end example

通过组合使用此类命令，可以轻松地绘制出精美的形状和图案。

@ref{11f,,turtle} 模块是基于 Python 标准发行版 2.5 以来的同名模块重新编写并进行了功能扩展。

新模块尽量保持了原模块的特点，并且(几乎)100%与其兼容。这就意味着初学编程者能够以交互方式使用模块的所有命令、类和方法——运行 IDLE 时注意加 @code{-n} 参数。

turtle 模块提供面向对象和面向过程两种形式的海龟绘图基本组件。由于它使用 @ref{10e,,tkinter} 实现基本图形界面，因此需要安装了 Tk 支持的 Python 版本。

面向对象的接口主要使用“2+2”个类：


@enumerate 

@item 
@ref{30b8,,TurtleScreen} 类定义图形窗口作为绘图海龟的运动场。它的构造器需要一个 @code{tkinter.Canvas} 或 @ref{30b9,,ScrolledCanvas} 作为参数。应在 @ref{11f,,turtle} 作为某个程序的一部分的时候使用。

@ref{30ba,,Screen()} 函数返回一个 @ref{30b8,,TurtleScreen} 子类的单例对象。此函数应在 @ref{11f,,turtle} 作为独立绘图工具时使用。作为一个单例对象，其所属的类是不可被继承的。

TurtleScreen/Screen 的所有方法还存在对应的函数，即作为面向过程的接口组成部分。

@item 
@ref{30bb,,RawTurtle} (别名: @ref{30bc,,RawPen}) 类定义海龟对象在 @ref{30b8,,TurtleScreen} 上绘图。它的构造器需要一个 Canvas, ScrolledCanvas 或 TurtleScreen 作为参数，以指定 RawTurtle 对象在哪里绘图。

从 RawTurtle 派生出子类 @ref{30bd,,Turtle} (别名: @code{Pen})，该类对象在 @ref{30ba,,Screen} 实例上绘图，如果实例不存在则会自动创建。

RawTurtle/Turtle 的所有方法也存在对应的函数，即作为面向过程的接口组成部分。
@end enumerate

过程式接口提供与 @ref{30ba,,Screen} 和 @ref{30bd,,Turtle} 类的方法相对应的函数。函数名与对应的方法名相同。当 Screen 类的方法对应函数被调用时会自动创建一个 Screen 对象。当 Turtle 类的方法对应函数被调用时会自动创建一个 (匿名的) Turtle 对象。

如果屏幕上需要有多个海龟，就必须使用面向对象的接口。

@cartouche
@quotation 注解 
以下文档给出了函数的参数列表。对于方法来说当然还有额外的第一个参数 @emph{self}，这里省略了。
@end quotation
@end cartouche

@node 可用的 Turtle 和 Screen 方法概览,RawTurtle/Turtle 方法和对应函数,概述<11>,turtle --- 海龟绘图
@anchor{library/turtle overview-of-available-turtle-and-screen-methods}@anchor{30be}
@subsubsection 可用的 Turtle 和 Screen 方法概览


@menu
* Turtle 方法:: 
* TurtleScreen/Screen 方法:: 

@end menu

@node Turtle 方法,TurtleScreen/Screen 方法,,可用的 Turtle 和 Screen 方法概览
@anchor{library/turtle turtle-methods}@anchor{30bf}
@subsubsection Turtle 方法



@table @asis

@item 海龟动作


@table @asis

@item 移动和绘制


@display
@ref{30c0,,forward()} | @ref{30c1,,fd()} 前进@w{ }
@ref{30c2,,backward()} | @ref{30c3,,bk()} | @ref{30c4,,back()} 后退@w{ }
@ref{30c5,,right()} | @ref{30c6,,rt()} 右转@w{ }
@ref{30c7,,left()} | @ref{30c8,,lt()} 左转@w{ }
@ref{30c9,,goto()} | @ref{30ca,,setpos()} | @ref{30cb,,setposition()} 前往/定位@w{ }
@ref{30cc,,setx()} 设置x坐标@w{ }
@ref{30cd,,sety()} 设置y坐标@w{ }
@ref{30ce,,setheading()} | @ref{30cf,,seth()} 设置朝向@w{ }
@ref{30d0,,home()} 返回原点@w{ }
@ref{30d1,,circle()} 画圆@w{ }
@ref{30d2,,dot()} 画点@w{ }
@ref{30d3,,stamp()} 印章@w{ }
@ref{30d4,,clearstamp()} 清除印章@w{ }
@ref{30d5,,clearstamps()} 清除多个印章@w{ }
@ref{30d6,,undo()} 撤消@w{ }
@ref{30d7,,speed()} 速度@w{ }
@end display



@item 获取海龟的状态


@display
@ref{30d8,,position()} | @ref{30d9,,pos()} 位置@w{ }
@ref{30da,,towards()} 目标方向@w{ }
@ref{30db,,xcor()} x坐标@w{ }
@ref{30dc,,ycor()} y坐标@w{ }
@ref{30dd,,heading()} 朝向@w{ }
@ref{30de,,distance()} 距离@w{ }
@end display



@item 设置与度量单位


@display
@ref{30df,,degrees()} 角度@w{ }
@ref{30e0,,radians()} 弧度@w{ }
@end display


@end table

@item 画笔控制


@table @asis

@item 绘图状态


@display
@ref{30e1,,pendown()} | @ref{30e2,,pd()} | @ref{30e3,,down()} 画笔落下@w{ }
@ref{30e4,,penup()} | @ref{30e5,,pu()} | @ref{30e6,,up()} 画笔抬起@w{ }
@ref{30e7,,pensize()} | @ref{30e8,,width()} 画笔粗细@w{ }
@ref{30e9,,pen()} 画笔@w{ }
@ref{30ea,,isdown()} 画笔是否落下@w{ }
@end display



@item 颜色控制


@display
@ref{30eb,,color()} 颜色@w{ }
@ref{30ec,,pencolor()} 画笔颜色@w{ }
@ref{30ed,,fillcolor()} 填充颜色@w{ }
@end display



@item 填充


@display
@ref{30ee,,filling()} 是否填充@w{ }
@ref{30ef,,begin_fill()} 开始填充@w{ }
@ref{30f0,,end_fill()} 结束填充@w{ }
@end display



@item 更多绘图控制


@display
@ref{30f1,,reset()} 重置@w{ }
@ref{30f2,,clear()} 清空@w{ }
@ref{30f3,,write()} 书写@w{ }
@end display


@end table

@item 海龟状态


@table @asis

@item 可见性


@display
@ref{30f4,,showturtle()} | @ref{30f5,,st()} 显示海龟@w{ }
@ref{30f6,,hideturtle()} | @ref{30f7,,ht()} 隐藏海龟@w{ }
@ref{30f8,,isvisible()} 是否可见@w{ }
@end display



@item 外观


@display
@ref{30f9,,shape()} 形状@w{ }
@ref{30fa,,resizemode()} 大小调整模式@w{ }
@ref{30fb,,shapesize()} | @ref{30fc,,turtlesize()} 形状大小@w{ }
@ref{30fd,,shearfactor()} 剪切因子@w{ }
@ref{30fe,,settiltangle()} 设置倾角@w{ }
@ref{30ff,,tiltangle()} 倾角@w{ }
@ref{3100,,tilt()} 倾斜@w{ }
@ref{3101,,shapetransform()} 变形@w{ }
@ref{3102,,get_shapepoly()} 获取形状多边形@w{ }
@end display


@end table

@item 使用事件


@display
@ref{3103,,onclick()} 当鼠标点击@w{ }
@ref{3104,,onrelease()} 当鼠标释放@w{ }
@ref{3105,,ondrag()} 当鼠标拖动@w{ }
@end display



@item 特殊海龟方法


@display
@ref{3106,,begin_poly()} 开始记录多边形@w{ }
@ref{3107,,end_poly()} 结束记录多边形@w{ }
@ref{3108,,get_poly()} 获取多边形@w{ }
@ref{3109,,clone()} 克隆@w{ }
@ref{310a,,getturtle()} | @ref{310b,,getpen()} 获取海龟画笔@w{ }
@ref{310c,,getscreen()} 获取屏幕@w{ }
@ref{310d,,setundobuffer()} 设置撤消缓冲区@w{ }
@ref{310e,,undobufferentries()} 撤消缓冲区条目数@w{ }
@end display


@end table

@node TurtleScreen/Screen 方法,,Turtle 方法,可用的 Turtle 和 Screen 方法概览
@anchor{library/turtle methods-of-turtlescreen-screen}@anchor{310f}
@subsubsection TurtleScreen/Screen 方法



@table @asis

@item 窗口控制


@display
@ref{3110,,bgcolor()} 背景颜色@w{ }
@ref{3111,,bgpic()} 背景图片@w{ }
@ref{3112,,clearscreen()}@w{ }
@ref{3113,,resetscreen()}@w{ }
@ref{3114,,screensize()} 屏幕大小@w{ }
@ref{3115,,setworldcoordinates()} 设置世界坐标系@w{ }
@end display



@item 动画控制


@display
@ref{3116,,delay()} 延迟@w{ }
@ref{3117,,tracer()} 追踪@w{ }
@ref{3118,,update()} 更新@w{ }
@end display



@item 使用屏幕事件


@display
@ref{3119,,listen()} 监听@w{ }
@ref{311a,,onkey()} | @ref{311b,,onkeyrelease()} 当键盘按下并释放@w{ }
@ref{311c,,onkeypress()} 当键盘按下@w{ }
@ref{3103,,onclick()} | @ref{311d,,onscreenclick()} 当点击屏幕@w{ }
@ref{311e,,ontimer()} 当达到定时@w{ }
@ref{311f,,mainloop()} | @ref{3120,,done()} 主循环@w{ }
@end display



@item 设置与特殊方法


@display
@ref{3121,,mode()} 模式@w{ }
@ref{3122,,colormode()} 颜色模式@w{ }
@ref{3123,,getcanvas()} 获取画布@w{ }
@ref{3124,,getshapes()} 获取形状@w{ }
@ref{3125,,register_shape()} | @ref{3126,,addshape()} 添加形状@w{ }
@ref{3127,,turtles()} 所有海龟@w{ }
@ref{3128,,window_height()} 窗口高度@w{ }
@ref{3129,,window_width()} 窗口宽度@w{ }
@end display



@item 输入方法


@display
@ref{ff1,,textinput()} 文本输入@w{ }
@ref{ff2,,numinput()} 数字输入@w{ }
@end display



@item Screen 专有方法


@display
@ref{312a,,bye()} 退出@w{ }
@ref{312b,,exitonclick()} 当点击时退出@w{ }
@ref{312c,,setup()} 设置@w{ }
@ref{312d,,title()} 标题@w{ }
@end display


@end table

@node RawTurtle/Turtle 方法和对应函数,TurtleScreen/Screen 方法及对应函数,可用的 Turtle 和 Screen 方法概览,turtle --- 海龟绘图
@anchor{library/turtle methods-of-rawturtle-turtle-and-corresponding-functions}@anchor{312e}
@subsubsection RawTurtle/Turtle 方法和对应函数


本节中的大部分示例都使用 Turtle 类的一个实例，命名为 @code{turtle}。

@menu
* 海龟动作:: 
* 获取海龟的状态:: 
* 度量单位设置:: 
* 画笔控制:: 
* 海龟状态:: 
* 使用事件:: 
* 特殊海龟方法:: 
* 复合形状:: 

@end menu

@node 海龟动作,获取海龟的状态,,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle turtle-motion}@anchor{312f}
@subsubsection 海龟动作


@geindex forward() (在 turtle 模块中)
@geindex fd() (在 turtle 模块中)
@anchor{library/turtle turtle forward}@anchor{30c0}
@deffn {函数} turtle.forward (distance)
@anchor{library/turtle turtle fd}@anchor{30c1}
@deffnx {函数} turtle.fd (distance)

@*参数: 
@code{distance} -- 一个数值 (整型或浮点型)


海龟前进 @emph{distance} 指定的距离，方向为海龟的朝向。

@example
>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)
@end example
@end deffn

@geindex back() (在 turtle 模块中)
@geindex bk() (在 turtle 模块中)
@geindex backward() (在 turtle 模块中)
@anchor{library/turtle turtle back}@anchor{30c4}
@deffn {函数} turtle.back (distance)
@anchor{library/turtle turtle bk}@anchor{30c3}
@deffnx {函数} turtle.bk (distance)
@anchor{library/turtle turtle backward}@anchor{30c2}
@deffnx {函数} turtle.backward (distance)

@*参数: 
@code{distance} -- 一个数值


海龟后退 @emph{distance} 指定的距离，方向与海龟的朝向相反。不改变海龟的朝向。

@c >>> turtle.goto(0, 0)

@example
>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
@end example
@end deffn

@geindex right() (在 turtle 模块中)
@geindex rt() (在 turtle 模块中)
@anchor{library/turtle turtle right}@anchor{30c5}
@deffn {函数} turtle.right (angle)
@anchor{library/turtle turtle rt}@anchor{30c6}
@deffnx {函数} turtle.rt (angle)

@*参数: 
@code{angle} -- 一个数值 (整型或浮点型)


海龟右转 @emph{angle} 个单位。(单位默认为角度，但可通过 @ref{30df,,degrees()} 和 @ref{30e0,,radians()} 函数改变设置。) 角度的正负由海龟模式确定，参见 @ref{3121,,mode()}。

@c >>> turtle.setheading(22)

@example
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
@end example
@end deffn

@geindex left() (在 turtle 模块中)
@geindex lt() (在 turtle 模块中)
@anchor{library/turtle turtle left}@anchor{30c7}
@deffn {函数} turtle.left (angle)
@anchor{library/turtle turtle lt}@anchor{30c8}
@deffnx {函数} turtle.lt (angle)

@*参数: 
@code{angle} -- 一个数值 (整型或浮点型)


海龟左转 @emph{angle} 个单位。(单位默认为角度，但可通过 @ref{30df,,degrees()} 和 @ref{30e0,,radians()} 函数改变设置。) 角度的正负由海龟模式确定，参见 @ref{3121,,mode()}。

@c >>> turtle.setheading(22)

@example
>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0
@end example
@end deffn

@geindex goto() (在 turtle 模块中)
@geindex setpos() (在 turtle 模块中)
@geindex setposition() (在 turtle 模块中)
@anchor{library/turtle turtle goto}@anchor{30c9}
@deffn {函数} turtle.goto (x, y=None)
@anchor{library/turtle turtle setpos}@anchor{30ca}
@deffnx {函数} turtle.setpos (x, y=None)
@anchor{library/turtle turtle setposition}@anchor{30cb}
@deffnx {函数} turtle.setposition (x, y=None)

@*参数: 

@itemize *

@item 
@code{x} -- 一个数值或数值对/向量

@item 
@code{y} -- 一个数值或 @code{None}
@end itemize


如果 @emph{y} 为 @code{None}，@emph{x} 应为一个表示坐标的数值对或 @ref{3130,,Vec2D} 类对象 (例如 @ref{30d9,,pos()} 返回的对象).

海龟移动到一个绝对坐标。如果画笔已落下将会画线。不改变海龟的朝向。

@c >>> turtle.goto(0, 0)

@example
 >>> tp = turtle.pos()
 >>> tp
 (0.00,0.00)
 >>> turtle.setpos(60,30)
 >>> turtle.pos()
 (60.00,30.00)
 >>> turtle.setpos((20,80))
 >>> turtle.pos()
 (20.00,80.00)
 >>> turtle.setpos(tp)
 >>> turtle.pos()
 (0.00,0.00)
@end example
@end deffn

@geindex setx() (在 turtle 模块中)
@anchor{library/turtle turtle setx}@anchor{30cc}
@deffn {函数} turtle.setx (x)

@*参数: 
@code{x} -- 一个数值 (整型或浮点型)


设置海龟的横坐标为 @emph{x}，纵坐标保持不变。

@c >>> turtle.goto(0, 240)

@example
>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
@end example
@end deffn

@geindex sety() (在 turtle 模块中)
@anchor{library/turtle turtle sety}@anchor{30cd}
@deffn {函数} turtle.sety (y)

@*参数: 
@code{y} -- 一个数值 (整型或浮点型)


设置海龟的纵坐标为 @emph{y}，横坐标保持不变。

@c >>> turtle.goto(0, 40)

@example
>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
@end example
@end deffn

@geindex setheading() (在 turtle 模块中)
@geindex seth() (在 turtle 模块中)
@anchor{library/turtle turtle setheading}@anchor{30ce}
@deffn {函数} turtle.setheading (to_angle)
@anchor{library/turtle turtle seth}@anchor{30cf}
@deffnx {函数} turtle.seth (to_angle)

@*参数: 
@code{to_angle} -- 一个数值 (整型或浮点型)


设置海龟的朝向为 @emph{to_angle}。以下是以角度表示的几个常用方向：


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标准模式

@tab

logo 模式

@item

0 - 东

@tab

0 - 北

@item

90 - 北

@tab

90 - 东

@item

180 - 西

@tab

180 - 南

@item

270 - 南

@tab

270 - 西

@end multitable


@example
>>> turtle.setheading(90)
>>> turtle.heading()
90.0
@end example
@end deffn

@geindex home() (在 turtle 模块中)
@anchor{library/turtle turtle home}@anchor{30d0}
@deffn {函数} turtle.home ()

海龟移至初始坐标 (0,0)，并设置朝向为初始方向 (由海龟模式确定，参见 @ref{3121,,mode()})。

@c >>> turtle.setheading(90)
@c >>> turtle.goto(0, -10)

@example
>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex circle() (在 turtle 模块中)
@anchor{library/turtle turtle circle}@anchor{30d1}
@deffn {函数} turtle.circle (radius, extent=None, steps=None)

@*参数: 

@itemize *

@item 
@code{radius} -- 一个数值

@item 
@code{extent} -- 一个数值 (或 @code{None})

@item 
@code{steps} -- 一个整型数 (或 @code{None})
@end itemize


绘制一个 @emph{radius} 指定半径的圆。圆心在海龟左边 @emph{radius} 个单位；@emph{extent} 为一个夹角，用来决定绘制圆的一部分。如未指定 @emph{extent*则绘制整个圆。如果 *extent} 不是完整圆周，则以当前画笔位置为一个端点绘制圆弧。如果 @emph{radius} 为正值则朝逆时针方向绘制圆弧，否则朝顺时针方向。最终海龟的朝向会依据 @emph{extent} 的值而改变。

圆实际是以其内切正多边形来近似表示的，其边的数量由 @emph{steps} 指定。如果未指定边数则会自动确定。此方法也可用来绘制正多边形。

@example
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
@end example
@end deffn

@geindex dot() (在 turtle 模块中)
@anchor{library/turtle turtle dot}@anchor{30d2}
@deffn {函数} turtle.dot (size=None, *color)

@*参数: 

@itemize *

@item 
@code{size} -- 一个整型数 >= 1 (如果指定)

@item 
@code{color} -- 一个颜色字符串或颜色数值元组
@end itemize


绘制一个直径为 @emph{size}，颜色为 @emph{color} 的圆点。如果 @emph{size} 未指定，则直径取 pensize+4 和 2*pensize 中的较大值。

@example
>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex stamp() (在 turtle 模块中)
@anchor{library/turtle turtle stamp}@anchor{30d3}
@deffn {函数} turtle.stamp ()

在海龟当前位置印制一个海龟形状。返回该印章的 stamp_id，印章可以通过调用 @code{clearstamp(stamp_id)} 来删除。

@example
>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)
@end example
@end deffn

@geindex clearstamp() (在 turtle 模块中)
@anchor{library/turtle turtle clearstamp}@anchor{30d4}
@deffn {函数} turtle.clearstamp (stampid)

@*参数: 
@code{stampid} -- 一个整型数，必须是之前 @ref{30d3,,stamp()} 调用的返回值


删除 @emph{stampid} 指定的印章。

@example
>>> turtle.position()
(150.00,-0.00)
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.position()
(200.00,-0.00)
>>> turtle.clearstamp(astamp)
>>> turtle.position()
(200.00,-0.00)
@end example
@end deffn

@geindex clearstamps() (在 turtle 模块中)
@anchor{library/turtle turtle clearstamps}@anchor{30d5}
@deffn {函数} turtle.clearstamps (n=None)

@*参数: 
@code{n} -- 一个整型数 (或 @code{None})


删除全部或前/后 @emph{n} 个海龟印章。如果 @emph{n} 为 @code{None} 则删除全部印章，如果 @emph{n} > 0 则删除前 @emph{n} 个印章，否则如果 @emph{n} < 0 则删除后 @emph{n} 个印章。

@example
>>> for i in range(8):
...     turtle.stamp(); turtle.fd(30)
13
14
15
16
17
18
19
20
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
@end example
@end deffn

@geindex undo() (在 turtle 模块中)
@anchor{library/turtle turtle undo}@anchor{30d6}
@deffn {函数} turtle.undo ()

撤消 (或连续撤消) 最近的一个 (或多个) 海龟动作。可撤消的次数由撤消缓冲区的大小决定。

@example
>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()
@end example
@end deffn

@geindex speed() (在 turtle 模块中)
@anchor{library/turtle turtle speed}@anchor{30d7}
@deffn {函数} turtle.speed (speed=None)

@*参数: 
@code{speed} -- 一个 0..10 范围内的整型数或速度字符串 (见下)


设置海龟移动的速度为 0..10 表示的整型数值。如未指定参数则返回当前速度。

如果输入数值大于 10 或小于 0.5 则速度设为 0。速度字符串与速度值的对应关系如下:


@itemize *

@item 
"fastest":  0 最快

@item 
"fast":  10 快

@item 
"normal":  6 正常

@item 
"slow":  3 慢

@item 
"slowest":  1 最慢
@end itemize

速度值从 1 到 10，画线和海龟转向的动画效果逐级加快。

注意: @emph{speed} = 0 表示 @emph{没有} 动画效果。forward/back 将使海龟向前/向后跳跃，同样的 left/right 将使海龟立即改变朝向。

@example
>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9
@end example
@end deffn

@node 获取海龟的状态,度量单位设置,海龟动作,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle tell-turtle-s-state}@anchor{3131}
@subsubsection 获取海龟的状态


@geindex position() (在 turtle 模块中)
@geindex pos() (在 turtle 模块中)
@anchor{library/turtle turtle position}@anchor{30d8}
@deffn {函数} turtle.position ()
@anchor{library/turtle turtle pos}@anchor{30d9}
@deffnx {函数} turtle.pos ()

返回海龟当前的坐标 (x,y) (为 @ref{3130,,Vec2D} 矢量类对象)。

@example
>>> turtle.pos()
(440.00,-0.00)
@end example
@end deffn

@geindex towards() (在 turtle 模块中)
@anchor{library/turtle turtle towards}@anchor{30da}
@deffn {函数} turtle.towards (x, y=None)

@*参数: 

@itemize *

@item 
@code{x} -- 一个数值或数值对/矢量，或一个海龟实例

@item 
@code{y} -- 一个数值——如果 @emph{x} 是一个数值，否则为 @code{None}
@end itemize


返回从海龟位置到由 (x,y)、矢量或另一海龟所确定位置的连线的夹角。 此数值依赖于海龟的初始朝向，这又取决于 "standard"/"world" 或 "logo" 模式设置。

@example
>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
@end example
@end deffn

@geindex xcor() (在 turtle 模块中)
@anchor{library/turtle turtle xcor}@anchor{30db}
@deffn {函数} turtle.xcor ()

返回海龟的 x 坐标。

@example
>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876
@end example
@end deffn

@geindex ycor() (在 turtle 模块中)
@anchor{library/turtle turtle ycor}@anchor{30dc}
@deffn {函数} turtle.ycor ()

返回海龟的 y 坐标。

@example
>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(turtle.pos())
(50.00,86.60)
>>> print(round(turtle.ycor(), 5))
86.60254
@end example
@end deffn

@geindex heading() (在 turtle 模块中)
@anchor{library/turtle turtle heading}@anchor{30dd}
@deffn {函数} turtle.heading ()

返回海龟当前的朝向 (数值依赖于海龟模式参见 @ref{3121,,mode()})。

@example
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
@end example
@end deffn

@geindex distance() (在 turtle 模块中)
@anchor{library/turtle turtle distance}@anchor{30de}
@deffn {函数} turtle.distance (x, y=None)

@*参数: 

@itemize *

@item 
@code{x} -- 一个数值或数值对/矢量，或一个海龟实例

@item 
@code{y} -- 一个数值——如果 @emph{x} 是一个数值，否则为 @code{None}
@end itemize


返回从海龟位置到由 (x,y)，适量或另一海龟对应位置的单位距离。

@example
>>> turtle.home()
>>> turtle.distance(30,40)
50.0
>>> turtle.distance((30,40))
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0
@end example
@end deffn

@node 度量单位设置,画笔控制,获取海龟的状态,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle settings-for-measurement}@anchor{3132}
@subsubsection 度量单位设置


@geindex degrees() (在 turtle 模块中)
@anchor{library/turtle turtle degrees}@anchor{30df}
@deffn {函数} turtle.degrees (fullcircle=360.0)

@*参数: 
@code{fullcircle} -- 一个数值


设置角度的度量单位，即设置一个圆周为多少 "度"。默认值为 360 度。

@example
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0
@end example
@end deffn

@geindex radians() (在 turtle 模块中)
@anchor{library/turtle turtle radians}@anchor{30e0}
@deffn {函数} turtle.radians ()

设置角度的度量单位为弧度。其值等于 @code{degrees(2*math.pi)}。

@example
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966
@end example

@c >>> turtle.degrees(360)
@end deffn

@node 画笔控制,海龟状态,度量单位设置,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle pen-control}@anchor{3133}
@subsubsection 画笔控制


@menu
* 绘图状态:: 
* 颜色控制:: 
* 填充:: 
* 更多绘图控制:: 

@end menu

@node 绘图状态,颜色控制,,画笔控制
@anchor{library/turtle drawing-state}@anchor{3134}
@subsubsection 绘图状态


@geindex pendown() (在 turtle 模块中)
@geindex pd() (在 turtle 模块中)
@geindex down() (在 turtle 模块中)
@anchor{library/turtle turtle pendown}@anchor{30e1}
@deffn {函数} turtle.pendown ()
@anchor{library/turtle turtle pd}@anchor{30e2}
@deffnx {函数} turtle.pd ()
@anchor{library/turtle turtle down}@anchor{30e3}
@deffnx {函数} turtle.down ()

画笔落下 -- 移动时将画线。
@end deffn

@geindex penup() (在 turtle 模块中)
@geindex pu() (在 turtle 模块中)
@geindex up() (在 turtle 模块中)
@anchor{library/turtle turtle penup}@anchor{30e4}
@deffn {函数} turtle.penup ()
@anchor{library/turtle turtle pu}@anchor{30e5}
@deffnx {函数} turtle.pu ()
@anchor{library/turtle turtle up}@anchor{30e6}
@deffnx {函数} turtle.up ()

画笔抬起 -- 移动时不画线。
@end deffn

@geindex pensize() (在 turtle 模块中)
@geindex width() (在 turtle 模块中)
@anchor{library/turtle turtle pensize}@anchor{30e7}
@deffn {函数} turtle.pensize (width=None)
@anchor{library/turtle turtle width}@anchor{30e8}
@deffnx {函数} turtle.width (width=None)

@*参数: 
@code{width} -- 一个正数值


设置线条的粗细为 @emph{width} 或返回该值。如果 resizemode 设为 "auto" 并且 turtleshape 为多边形，该多边形也以同样组细的线条绘制。如未指定参数，则返回当前的 pensize。

@example
>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn
@end example
@end deffn

@geindex pen() (在 turtle 模块中)
@anchor{library/turtle turtle pen}@anchor{30e9}
@deffn {函数} turtle.pen (pen=None, **pendict)

@*参数: 

@itemize *

@item 
@code{pen} -- 一个包含部分或全部下列键的字典

@item 
@code{pendict} -- 一个或多个以下列键为关键字的关键字参数
@end itemize


返回或设置画笔的属性，以一个包含以下键值对的 "画笔字典" 表示:


@itemize *

@item 
"shown": True/False

@item 
"pendown": True/False

@item 
"pencolor": 颜色字符串或颜色元组

@item 
"fillcolor": 颜色字符串或颜色元组

@item 
"pensize": 正数值

@item 
"speed": 0..10 范围内的数值

@item 
"resizemode": "auto" 或 "user" 或 "noresize"

@item 
"stretchfactor": (正数值, 正数值)

@item 
"outline": 正数值

@item 
"tilt": 数值
@end itemize

此字典可作为后续调用 @ref{30e9,,pen()} 时的参数，以恢复之前的画笔状态。另外还可将这些属性作为关键词参数提交。使用此方式可以用一条语句设置画笔的多个属性。

@example
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
 ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
 ('shearfactor', 0.0), ('shown', True), ('speed', 9),
 ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', '@w{'}), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
@end example
@end deffn

@geindex isdown() (在 turtle 模块中)
@anchor{library/turtle turtle isdown}@anchor{30ea}
@deffn {函数} turtle.isdown ()

如果画笔落下返回 @code{True}，如果画笔抬起返回 @code{False}。

@example
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
@end example
@end deffn

@node 颜色控制,填充,绘图状态,画笔控制
@anchor{library/turtle color-control}@anchor{3135}
@subsubsection 颜色控制


@geindex pencolor() (在 turtle 模块中)
@anchor{library/turtle turtle pencolor}@anchor{30ec}
@deffn {函数} turtle.pencolor (*args)

返回或设置画笔颜色。

允许以下四种输入格式:


@table @asis

@item @code{pencolor()}

返回以颜色描述字符串或元组 (见示例) 表示的当前画笔颜色。可用作其他 color/pencolor/fillcolor 调用的输入。

@item @code{pencolor(colorstring)}

设置画笔颜色为 @emph{colorstring} 指定的 Tk 颜色描述字符串，例如 @code{"red"}、@code{"yellow"} 或 @code{"#33cc8c"}。

@item @code{pencolor((r, g, b))}

设置画笔颜色为以 @emph{r}, @emph{g}, @emph{b} 元组表示的 RGB 颜色。@emph{r}, @emph{g}, @emph{b} 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255 (参见 @ref{3122,,colormode()})。

@item @code{pencolor(r, g, b)}

设置画笔颜色为以 @emph{r}, @emph{g}, @emph{b} 表示的 RGB 颜色。@emph{r}, @emph{g}, @emph{b} 的取值范围应为 0..colormode。
@end table

如果 turtleshape 为多边形，该多边形轮廓也以新设置的画笔颜色绘制。

@example
 >>> colormode()
 1.0
 >>> turtle.pencolor()
 'red'
 >>> turtle.pencolor("brown")
 >>> turtle.pencolor()
 'brown'
 >>> tup = (0.2, 0.8, 0.55)
 >>> turtle.pencolor(tup)
 >>> turtle.pencolor()
 (0.2, 0.8, 0.5490196078431373)
 >>> colormode(255)
 >>> turtle.pencolor()
 (51.0, 204.0, 140.0)
 >>> turtle.pencolor('#32c18f')
 >>> turtle.pencolor()
 (50.0, 193.0, 143.0)
@end example
@end deffn

@geindex fillcolor() (在 turtle 模块中)
@anchor{library/turtle turtle fillcolor}@anchor{30ed}
@deffn {函数} turtle.fillcolor (*args)

返回或设置填充颜色。

允许以下四种输入格式:


@table @asis

@item @code{fillcolor()}

返回以颜色描述字符串或元组 (见示例) 表示的当前填充颜色。可用作其他 color/pencolor/fillcolor 调用的输入。

@item @code{fillcolor(colorstring)}

设置填充颜色为 @emph{colorstring} 指定的 Tk 颜色描述字符串，例如 @code{"red"}、@code{"yellow"} 或 @code{"#33cc8c"}。

@item @code{fillcolor((r, g, b))}

设置填充颜色为以 @emph{r}, @emph{g}, @emph{b} 元组表示的 RGB 颜色。@emph{r}, @emph{g}, @emph{b} 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255 (参见 @ref{3122,,colormode()})。

@item @code{fillcolor(r, g, b)}

设置填充颜色为 @emph{r}, @emph{g}, @emph{b} 表示的 RGB 颜色。@emph{r}, @emph{g}, @emph{b} 的取值范围应为 0..colormode。
@end table

如果 turtleshape 为多边形，该多边形内部也以新设置的填充颜色填充。

@example
 >>> turtle.fillcolor("violet")
 >>> turtle.fillcolor()
 'violet'
 >>> turtle.pencolor()
 (50.0, 193.0, 143.0)
 >>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
 >>> turtle.fillcolor()
 (50.0, 193.0, 143.0)
 >>> turtle.fillcolor('#ffffff')
 >>> turtle.fillcolor()
 (255.0, 255.0, 255.0)
@end example
@end deffn

@geindex color() (在 turtle 模块中)
@anchor{library/turtle turtle color}@anchor{30eb}
@deffn {函数} turtle.color (*args)

返回或设置画笔颜色和填充颜色。

允许多种输入格式。使用如下 0 至 3 个参数:


@table @asis

@item @code{color()}

返回以一对颜色描述字符串或元组表示的当前画笔颜色和填充颜色，两者可分别由 @ref{30ec,,pencolor()} 和 @ref{30ed,,fillcolor()} 返回。

@item @code{color(colorstring)}, @code{color((r,g,b))}, @code{color(r,g,b)}

输入格式与 @ref{30ec,,pencolor()} 相同，同时设置填充颜色和画笔颜色为指定的值。

@item @code{color(colorstring1, colorstring2)}, @code{color((r1,g1,b1), (r2,g2,b2))}

相当于 @code{pencolor(colorstring1)} 加 @code{fillcolor(colorstring2)}，使用其他输入格式的方法也与之类似。
@end table

如果 turtleshape 为多边形，该多边形轮廓与填充也使用新设置的颜色。

@example
 >>> turtle.color("red", "green")
 >>> turtle.color()
 ('red', 'green')
 >>> color("#285078", "#a0c8f0")
 >>> color()
 ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
@end example
@end deffn

另参见: Screen 方法 @ref{3122,,colormode()}。

@node 填充,更多绘图控制,颜色控制,画笔控制
@anchor{library/turtle filling}@anchor{3136}
@subsubsection 填充


@c >>> turtle.home()

@geindex filling() (在 turtle 模块中)
@anchor{library/turtle turtle filling}@anchor{30ee}
@deffn {函数} turtle.filling ()

返回填充状态 (填充为 @code{True}，否则为 @code{False})。

@example
 >>> turtle.begin_fill()
 >>> if turtle.filling():
 ...    turtle.pensize(5)
 ... else:
 ...    turtle.pensize(3)
@end example
@end deffn

@geindex begin_fill() (在 turtle 模块中)
@anchor{library/turtle turtle begin_fill}@anchor{30ef}
@deffn {函数} turtle.begin_fill ()

在绘制要填充的形状之前调用。
@end deffn

@geindex end_fill() (在 turtle 模块中)
@anchor{library/turtle turtle end_fill}@anchor{30f0}
@deffn {函数} turtle.end_fill ()

填充上次调用 @ref{30ef,,begin_fill()} 之后绘制的形状。

自相交多边形或多个形状间的重叠区域是否填充取决于操作系统的图形引擎、重叠的类型以及重叠的层数。 例如上面的 Turtle 多芒星可能会全部填充为黄色，也可能会有一些白色区域。

@example
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()
@end example
@end deffn

@node 更多绘图控制,,填充,画笔控制
@anchor{library/turtle more-drawing-control}@anchor{3137}
@subsubsection 更多绘图控制


@geindex reset() (在 turtle 模块中)
@anchor{library/turtle turtle reset}@anchor{30f1}
@deffn {函数} turtle.reset ()

从屏幕中删除海龟的绘图，海龟回到原点并设置所有变量为默认值。

@example
>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
@end example
@end deffn

@geindex clear() (在 turtle 模块中)
@anchor{library/turtle turtle clear}@anchor{30f2}
@deffn {函数} turtle.clear ()

从屏幕中删除指定海龟的绘图。不移动海龟。海龟的状态和位置以及其他海龟的绘图不受影响。
@end deffn

@geindex write() (在 turtle 模块中)
@anchor{library/turtle turtle write}@anchor{30f3}
@deffn {函数} turtle.write (arg, move=False, align="left", font=("Arial", 8, "normal"))

@*参数: 

@itemize *

@item 
@code{arg} -- 要书写到 TurtleScreen 的对象

@item 
@code{move} -- True/False

@item 
@code{align} -- 字符串 "left", "center" 或 "right"

@item 
@code{font} -- 一个三元组 (fontname, fontsize, fonttype)
@end itemize


基于 @emph{align} ("left", "center" 或 "right") 并使用给定的字体将文本 —— @emph{arg} 的字符串表示形式 —— 写到当前海龟位置。 如果 @emph{move} 为真值，画笔会移至文本的右下角。 默认情况下 @emph{move} 为 @code{False}。

@example
>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)
@end example
@end deffn

@node 海龟状态,使用事件,画笔控制,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle turtle-state}@anchor{3138}
@subsubsection 海龟状态


@menu
* 可见性:: 
* 外观:: 

@end menu

@node 可见性,外观,,海龟状态
@anchor{library/turtle visibility}@anchor{3139}
@subsubsection 可见性


@geindex hideturtle() (在 turtle 模块中)
@geindex ht() (在 turtle 模块中)
@anchor{library/turtle turtle hideturtle}@anchor{30f6}
@deffn {函数} turtle.hideturtle ()
@anchor{library/turtle turtle ht}@anchor{30f7}
@deffnx {函数} turtle.ht ()

使海龟不可见。当你绘制复杂图形时这是个好主意，因为隐藏海龟可显著加快绘制速度。

@example
>>> turtle.hideturtle()
@end example
@end deffn

@geindex showturtle() (在 turtle 模块中)
@geindex st() (在 turtle 模块中)
@anchor{library/turtle turtle showturtle}@anchor{30f4}
@deffn {函数} turtle.showturtle ()
@anchor{library/turtle turtle st}@anchor{30f5}
@deffnx {函数} turtle.st ()

使海龟可见。

@example
>>> turtle.showturtle()
@end example
@end deffn

@geindex isvisible() (在 turtle 模块中)
@anchor{library/turtle turtle isvisible}@anchor{30f8}
@deffn {函数} turtle.isvisible ()

如果海龟显示返回 @code{True}，如果海龟隐藏返回 @code{False}。

@example
>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True
@end example
@end deffn

@node 外观,,可见性,海龟状态
@anchor{library/turtle appearance}@anchor{313a}
@subsubsection 外观


@geindex shape() (在 turtle 模块中)
@anchor{library/turtle turtle shape}@anchor{30f9}
@deffn {函数} turtle.shape (name=None)

@*参数: 
@code{name} -- 一个有效的形状名字符串


设置海龟形状为 @emph{name} 指定的形状名，如未指定形状名则返回当前的形状名。@emph{name} 指定的形状名应存在于 TurtleScreen 的 shape 字典中。多边形的形状初始时有以下几种: "arrow", "turtle", "circle", "square", "triangle", "classic"。要了解如何处理形状请参看 Screen 方法 @ref{3125,,register_shape()}。

@example
>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
@end example
@end deffn

@geindex resizemode() (在 turtle 模块中)
@anchor{library/turtle turtle resizemode}@anchor{30fa}
@deffn {函数} turtle.resizemode (rmode=None)

@*参数: 
@code{rmode} -- 字符串 "auto", "user", "noresize" 其中之一


设置大小调整模式为以下值之一: "auto", "user", "noresize"。如未指定 @emph{rmode} 则返回当前的大小调整模式。不同的大小调整模式的效果如下:


@itemize -

@item 
"auto": 根据画笔粗细值调整海龟的外观。

@item 
"user": 根据拉伸因子和轮廓宽度 (outline) 值调整海龟的外观，两者是由 @ref{30fb,,shapesize()} 设置的。

@item 
"noresize": 不调整海龟的外观大小。
@end itemize

@code{resizemode("user")} 会由 @ref{30fb,,shapesize()} 带参数使用时被调用。

@example
>>> turtle.resizemode()
'noresize'
>>> turtle.resizemode("auto")
>>> turtle.resizemode()
'auto'
@end example
@end deffn

@geindex shapesize() (在 turtle 模块中)
@geindex turtlesize() (在 turtle 模块中)
@anchor{library/turtle turtle shapesize}@anchor{30fb}
@deffn {函数} turtle.shapesize (stretch_wid=None, stretch_len=None, outline=None)
@anchor{library/turtle turtle turtlesize}@anchor{30fc}
@deffnx {函数} turtle.turtlesize (stretch_wid=None, stretch_len=None, outline=None)

@*参数: 

@itemize *

@item 
@code{stretch_wid} -- 正数值

@item 
@code{stretch_len} -- 正数值

@item 
@code{outline} -- 正数值
@end itemize


返回或设置画笔的属性 x/y-拉伸因子和/或轮廓。设置大小调整模式为 "user"。当且仅当大小调整模式设为 "user" 时海龟会基于其拉伸因子调整外观: @emph{stretch_wid} 为垂直于其朝向的宽度拉伸因子，@emph{stretch_len} 为平等于其朝向的长度拉伸因子，决定形状轮廓线的粗细。

@example
>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)
@end example
@end deffn

@geindex shearfactor() (在 turtle 模块中)
@anchor{library/turtle turtle shearfactor}@anchor{30fd}
@deffn {函数} turtle.shearfactor (shear=None)

@*参数: 
@code{shear} -- 数值 (可选)


设置或返回当前的剪切因子。根据 share 指定的剪切因子即剪切角度的切线来剪切海龟形状。@emph{不} 改变海龟的朝向 (移动方向)。如未指定 shear 参数: 返回当前的剪切因子即剪切角度的切线，与海龟朝向平行的线条将被剪切。

@example
 >>> turtle.shape("circle")
 >>> turtle.shapesize(5,2)
 >>> turtle.shearfactor(0.5)
 >>> turtle.shearfactor()
 0.5
@end example
@end deffn

@geindex tilt() (在 turtle 模块中)
@anchor{library/turtle turtle tilt}@anchor{3100}
@deffn {函数} turtle.tilt (angle)

@*参数: 
@code{angle} -- 一个数值


海龟形状自其当前的倾角转动 @emph{angle} 指定的角度，但 @emph{不} 改变海龟的朝向 (移动方向)。

@example
>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
@end example
@end deffn

@geindex settiltangle() (在 turtle 模块中)
@anchor{library/turtle turtle settiltangle}@anchor{30fe}
@deffn {函数} turtle.settiltangle (angle)

@*参数: 
@code{angle} -- 一个数值


旋转海龟形状使其指向 @emph{angle} 指定的方向，忽略其当前的倾角，@emph{不} 改变海龟的朝向 (移动方向)。

@example
>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> turtle.fd(50)
@end example


3.1 版后已移除.

@end deffn

@geindex tiltangle() (在 turtle 模块中)
@anchor{library/turtle turtle tiltangle}@anchor{30ff}
@deffn {函数} turtle.tiltangle (angle=None)

@*参数: 
@code{angle} -- 一个数值 (可选)


设置或返回当前的倾角。如果指定 angle 则旋转海龟形状使其指向 angle 指定的方向，忽略其当前的倾角。@emph{不} 改变海龟的朝向 (移动方向)。如果未指定 angle: 返回当前的倾角，即海龟形状的方向和海龟朝向 (移动方向) 之间的夹角。

@example
>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45.0
@end example
@end deffn

@geindex shapetransform() (在 turtle 模块中)
@anchor{library/turtle turtle shapetransform}@anchor{3101}
@deffn {函数} turtle.shapetransform (t11=None, t12=None, t21=None, t22=None)

@*参数: 

@itemize *

@item 
@code{t11} -- 一个数值 (可选)

@item 
@code{t12} -- 一个数值 (可选)

@item 
@code{t21} -- 一个数值 (可选)

@item 
@code{t12} -- 一个数值 (可选)
@end itemize


设置或返回海龟形状的当前变形矩阵。

如未指定任何矩阵元素，则返回以 4 元素元组表示的变形矩阵。 否则就根据设置指定元素的矩阵来改变海龟形状，矩阵第一排的值为 t11, t12 而第二排的值为 t21, t22。 行列式 t11 * t22 - t12 * t21 必须不为零，否则会引发错误。 根据指定矩阵修改拉伸因子 stretchfactor, 剪切因子 shearfactor 和倾角 tiltangle。

@example
>>> turtle = Turtle()
>>> turtle.shape("square")
>>> turtle.shapesize(4,2)
>>> turtle.shearfactor(-0.5)
>>> turtle.shapetransform()
(4.0, -1.0, -0.0, 2.0)
@end example
@end deffn

@geindex get_shapepoly() (在 turtle 模块中)
@anchor{library/turtle turtle get_shapepoly}@anchor{3102}
@deffn {函数} turtle.get_shapepoly ()

返回以坐标值对元组表示的当前形状多边形。这可以用于定义一个新形状或一个复合形状的多个组成部分。

@example
>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))
@end example
@end deffn

@node 使用事件,特殊海龟方法,海龟状态,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle using-events}@anchor{313b}
@subsubsection 使用事件



@deffn {函数} turtle.onclick (fun, btn=1, add=None)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

@item 
@code{btn} -- 鼠标按钮编号，默认值为 1 (鼠标左键)

@item 
@code{add} -- @code{True} 或 @code{False} -- 如为 @code{True} 则将添加一个新绑定，否则将取代先前的绑定
@end itemize


将 @emph{fun} 指定的函数绑定到鼠标点击此海龟事件。如果 @emph{fun} 值为 @code{None}，则移除现有的绑定。以下为使用匿名海龟即过程式的示例:

@example
>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed
@end example
@end deffn

@geindex onrelease() (在 turtle 模块中)
@anchor{library/turtle turtle onrelease}@anchor{3104}
@deffn {函数} turtle.onrelease (fun, btn=1, add=None)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

@item 
@code{btn} -- 鼠标按钮编号，默认值为 1 (鼠标左键)

@item 
@code{add} -- @code{True} 或 @code{False} -- 如为 @code{True} 则将添加一个新绑定，否则将取代先前的绑定
@end itemize


将 @emph{fun} 指定的函数绑定到在此海龟上释放鼠标按键事件。如果 @emph{fun} 值为 @code{None}，则移除现有的绑定。

@example
>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
@end example
@end deffn

@geindex ondrag() (在 turtle 模块中)
@anchor{library/turtle turtle ondrag}@anchor{3105}
@deffn {函数} turtle.ondrag (fun, btn=1, add=None)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

@item 
@code{btn} -- 鼠标按钮编号，默认值为 1 (鼠标左键)

@item 
@code{add} -- @code{True} 或 @code{False} -- 如为 @code{True} 则将添加一个新绑定，否则将取代先前的绑定
@end itemize


将 @emph{fun} 指定的函数绑定到在此海龟上移动鼠标事件。如果 @emph{fun} 值为 @code{None}，则移除现有的绑定。

注: 在海龟上移动鼠标事件之前应先发生在此海龟上点击鼠标事件。

@example
>>> turtle.ondrag(turtle.goto)
@end example

在此之后点击并拖动海龟可在屏幕上手绘线条 (如果画笔为落下)。
@end deffn

@node 特殊海龟方法,复合形状,使用事件,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle special-turtle-methods}@anchor{313c}
@subsubsection 特殊海龟方法


@geindex begin_poly() (在 turtle 模块中)
@anchor{library/turtle turtle begin_poly}@anchor{3106}
@deffn {函数} turtle.begin_poly ()

开始记录多边形的顶点。当前海龟位置为多边形的第一个顶点。
@end deffn

@geindex end_poly() (在 turtle 模块中)
@anchor{library/turtle turtle end_poly}@anchor{3107}
@deffn {函数} turtle.end_poly ()

停止记录多边形的顶点。当前海龟位置为多边形的最后一个顶点。它将连线到第一个顶点。
@end deffn

@geindex get_poly() (在 turtle 模块中)
@anchor{library/turtle turtle get_poly}@anchor{3108}
@deffn {函数} turtle.get_poly ()

返回最新记录的多边形。

@example
>>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p)
@end example
@end deffn

@geindex clone() (在 turtle 模块中)
@anchor{library/turtle turtle clone}@anchor{3109}
@deffn {函数} turtle.clone ()

创建并返回海龟的克隆体，具有相同的位置、朝向和海龟属性。

@example
>>> mick = Turtle()
>>> joe = mick.clone()
@end example
@end deffn

@geindex getturtle() (在 turtle 模块中)
@geindex getpen() (在 turtle 模块中)
@anchor{library/turtle turtle getturtle}@anchor{310a}
@deffn {函数} turtle.getturtle ()
@anchor{library/turtle turtle getpen}@anchor{310b}
@deffnx {函数} turtle.getpen ()

返回海龟对象自身。唯一合理的用法: 作为一个函数来返回 "匿名海龟":

@example
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>
@end example
@end deffn

@geindex getscreen() (在 turtle 模块中)
@anchor{library/turtle turtle getscreen}@anchor{310c}
@deffn {函数} turtle.getscreen ()

返回作为海龟绘图场所的 @ref{30b8,,TurtleScreen} 类对象。该对象将可调用 TurtleScreen 方法。

@example
>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
@end example
@end deffn

@geindex setundobuffer() (在 turtle 模块中)
@anchor{library/turtle turtle setundobuffer}@anchor{310d}
@deffn {函数} turtle.setundobuffer (size)

@*参数: 
@code{size} -- 一个整型数值或 @code{None}


设置或禁用撤销缓冲区。 如果 @emph{size} 为整数，则开辟一个给定大小的空撤销缓冲区。 @emph{size} 给出了可以通过 @ref{30d6,,undo()} 方法/函数撤销海龟动作的最大次数。  如果 @emph{size} 为 @code{None}，则禁用撤销缓冲区。

@example
>>> turtle.setundobuffer(42)
@end example
@end deffn

@geindex undobufferentries() (在 turtle 模块中)
@anchor{library/turtle turtle undobufferentries}@anchor{310e}
@deffn {函数} turtle.undobufferentries ()

返回撤销缓冲区里的条目数。

@example
>>> while undobufferentries():
...     undo()
@end example
@end deffn

@node 复合形状,,特殊海龟方法,RawTurtle/Turtle 方法和对应函数
@anchor{library/turtle compound-shapes}@anchor{313d}@anchor{library/turtle compoundshapes}@anchor{313e}
@subsubsection 复合形状


要使用由多个不同颜色多边形构成的复合海龟形状，你必须明确地使用辅助类 @ref{313f,,Shape}，具体步骤如下:


@enumerate 

@item 
创建一个空 Shape 对象，类型为 "compound"。

@item 
按照需要使用 @code{addcomponent()} 方法向此对象添加多个部件。

例如:

@example
>>> s = Shape("compound")
>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s.addcomponent(poly1, "red", "blue")
>>> poly2 = ((0,0),(10,-5),(-10,-5))
>>> s.addcomponent(poly2, "blue", "red")
@end example

@item 
接下来将 Shape 对象添加到 Screen 对象的形状列表并使用它:

@example
>>> register_shape("myshape", s)
>>> shape("myshape")
@end example
@end enumerate

@cartouche
@quotation 注解 
@ref{313f,,Shape} 类在 @ref{3125,,register_shape()} 方法的内部以多种方式使用。应用程序编写者 @emph{只有} 在使用上述的复合形状时才需要处理 Shape 类。
@end quotation
@end cartouche

@node TurtleScreen/Screen 方法及对应函数,公共类,RawTurtle/Turtle 方法和对应函数,turtle --- 海龟绘图
@anchor{library/turtle methods-of-turtlescreen-screen-and-corresponding-functions}@anchor{3140}
@subsubsection TurtleScreen/Screen 方法及对应函数


本节中的大部分示例都使用 TurtleScreen 类的一个实例，命名为 @code{screen}。

@c >>> screen = Screen()

@menu
* 窗口控制:: 
* 动画控制:: 
* 使用屏幕事件:: 
* 输入方法:: 
* 设置与特殊方法:: 
* Screen 专有方法@comma{} 而非继承自 TurtleScreen: Screen 专有方法 而非继承自 TurtleScreen. 

@end menu

@node 窗口控制,动画控制,,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle window-control}@anchor{3141}
@subsubsection 窗口控制


@geindex bgcolor() (在 turtle 模块中)
@anchor{library/turtle turtle bgcolor}@anchor{3110}
@deffn {函数} turtle.bgcolor (*args)

@*参数: 
@code{args} -- 一个颜色字符串或三个取值范围 0..colormode 内的数值或一个取值范围相同的数值3元组


设置或返回 TurtleScreen 的背景颜色。

@example
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
@end example
@end deffn

@geindex bgpic() (在 turtle 模块中)
@anchor{library/turtle turtle bgpic}@anchor{3111}
@deffn {函数} turtle.bgpic (picname=None)

@*参数: 
@code{picname} -- 一个字符串, gif-文件名, @code{"nopic"}, 或 @code{None}


设置背景图片或返回当前背景图片名称。如果 @emph{picname} 为一个文件名，则将相应图片设为背景。如果 @emph{picname} 为 @code{"nopic"}，则删除当前背景图片。如果 @emph{picname} 为 @code{None}，则返回当前背景图片文件名。:

@example
>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"
@end example
@end deffn


@deffn {函数} turtle.clear ()

@cartouche
@quotation 注解 
此 TurtleScreen 方法作为全局函数时只有一个名字 @code{clearscreen}。全局函数 @code{clear} 所对应的是 Turtle 方法 @code{clear}。
@end quotation
@end cartouche
@end deffn

@geindex clearscreen() (在 turtle 模块中)
@anchor{library/turtle turtle clearscreen}@anchor{3112}
@deffn {函数} turtle.clearscreen ()

从中删除所有海龟的全部绘图。将已清空的 TurtleScreen 重置为初始状态: 白色背景，无背景片，无事件绑定并启用追踪。
@end deffn


@deffn {函数} turtle.reset ()

@cartouche
@quotation 注解 
此 TurtleScreen 方法作为全局函数时只有一个名字 @code{resetscreen}。全局函数 @code{reset} 所对应的是 Turtle 方法 @code{reset}。
@end quotation
@end cartouche
@end deffn

@geindex resetscreen() (在 turtle 模块中)
@anchor{library/turtle turtle resetscreen}@anchor{3113}
@deffn {函数} turtle.resetscreen ()

重置屏幕上的所有海龟为其初始状态。
@end deffn

@geindex screensize() (在 turtle 模块中)
@anchor{library/turtle turtle screensize}@anchor{3114}
@deffn {函数} turtle.screensize (canvwidth=None, canvheight=None, bg=None)

@*参数: 

@itemize *

@item 
@code{canvwidth} -- 正整型数，以像素表示画布的新宽度值

@item 
@code{canvheight} -- 正整型数，以像素表示画面的新高度值

@item 
@code{bg} -- 颜色字符串或颜色元组，新的背景颜色
@end itemize


如未指定任何参数，则返回当前的 (canvaswidth, canvasheight)。否则改变作为海龟绘图场所的画布大小。不改变绘图窗口。要观察画布的隐藏区域，可以使用滚动条。通过此方法可以令之前绘制于画布之外的图形变为可见。

@example
>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)
@end example

也可以用来寻找意外逃走的海龟 ;-)
@end deffn

@geindex setworldcoordinates() (在 turtle 模块中)
@anchor{library/turtle turtle setworldcoordinates}@anchor{3115}
@deffn {函数} turtle.setworldcoordinates (llx, lly, urx, ury)

@*参数: 

@itemize *

@item 
@code{llx} -- 一个数值, 画布左下角的 x-坐标

@item 
@code{lly} -- 一个数值, 画布左下角的 y-坐标

@item 
@code{urx} -- 一个数值, 画面右上角的 x-坐标

@item 
@code{ury} -- 一个数值, 画布右上角的 y-坐标
@end itemize


设置用户自定义坐标系并在必要时切换模式为 "world"。这会执行一次 @code{screen.reset()}。如果 "world" 模式已激活，则所有图形将根据新的坐标系重绘。

@strong{注意}: 在用户自定义坐标系中，角度可能显得扭曲。

@example
>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon
@end example

@c >>> screen.reset()
@c >>> for t in turtles():
@c ...      t.reset()
@end deffn

@node 动画控制,使用屏幕事件,窗口控制,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle animation-control}@anchor{3142}
@subsubsection 动画控制


@geindex delay() (在 turtle 模块中)
@anchor{library/turtle turtle delay}@anchor{3116}
@deffn {函数} turtle.delay (delay=None)

@*参数: 
@code{delay} -- 正整型数


设置或返回以毫秒数表示的延迟值 @emph{delay}。(这约等于连续两次画布刷新的间隔时间。) 绘图延迟越长，动画速度越慢。

可选参数:

@example
>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
@end example
@end deffn

@geindex tracer() (在 turtle 模块中)
@anchor{library/turtle turtle tracer}@anchor{3117}
@deffn {函数} turtle.tracer (n=None, delay=None)

@*参数: 

@itemize *

@item 
@code{n} -- 非负整型数

@item 
@code{delay} -- 非负整型数
@end itemize


启用/禁用海龟动画并设置刷新图形的延迟时间。如果指定 @emph{n} 值，则只有每第 n 次屏幕刷新会实际执行。(可被用来加速复杂图形的绘制。) 如果调用时不带参数，则返回当前保存的 n 值。第二个参数设置延迟值 (参见 @ref{3116,,delay()})。

@example
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
...     fd(dist)
...     rt(90)
...     dist += 2
@end example
@end deffn

@geindex update() (在 turtle 模块中)
@anchor{library/turtle turtle update}@anchor{3118}
@deffn {函数} turtle.update ()

执行一次 TurtleScreen 刷新。在禁用追踪时使用。
@end deffn

另参见 RawTurtle/Turtle 方法 @ref{30d7,,speed()}。

@node 使用屏幕事件,输入方法,动画控制,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle using-screen-events}@anchor{3143}
@subsubsection 使用屏幕事件


@geindex listen() (在 turtle 模块中)
@anchor{library/turtle turtle listen}@anchor{3119}
@deffn {函数} turtle.listen (xdummy=None, ydummy=None)

设置焦点到 TurtleScreen (以便接收按键事件)。使用两个 Dummy 参数以便能够传递 @ref{3119,,listen()} 给 onclick 方法。
@end deffn

@geindex onkey() (在 turtle 模块中)
@geindex onkeyrelease() (在 turtle 模块中)
@anchor{library/turtle turtle onkey}@anchor{311a}
@deffn {函数} turtle.onkey (fun, key)
@anchor{library/turtle turtle onkeyrelease}@anchor{311b}
@deffnx {函数} turtle.onkeyrelease (fun, key)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个无参数的函数或 @code{None}

@item 
@code{key} -- 一个字符串: 键 (例如 "a") 或键标 (例如 "space")
@end itemize


绑定 @emph{fun} 指定的函数到按键释放事件。如果 @emph{fun} 值为 @code{None}，则移除事件绑定。注: 为了能够注册按键事件，TurtleScreen 必须得到焦点。(参见 method @ref{3119,,listen()} 方法。)

@example
>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
@end example
@end deffn

@geindex onkeypress() (在 turtle 模块中)
@anchor{library/turtle turtle onkeypress}@anchor{311c}
@deffn {函数} turtle.onkeypress (fun, key=None)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个无参数的函数或 @code{None}

@item 
@code{key} -- 一个字符串: 键 (例如 "a") 或键标 (例如 "space")
@end itemize


绑定 @emph{fun} 指定的函数到指定键的按下事件。如未指定键则绑定到任意键的按下事件。注: 为了能够注册按键事件，必须得到焦点。(参见 @ref{3119,,listen()} 方法。)

@example
>>> def f():
...     fd(50)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
@end example
@end deffn

@geindex onclick() (在 turtle 模块中)
@geindex onscreenclick() (在 turtle 模块中)
@anchor{library/turtle turtle onclick}@anchor{3103}
@deffn {函数} turtle.onclick (fun, btn=1, add=None)
@anchor{library/turtle turtle onscreenclick}@anchor{311d}
@deffnx {函数} turtle.onscreenclick (fun, btn=1, add=None)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

@item 
@code{btn} -- 鼠标按钮编号，默认值为 1 (鼠标左键)

@item 
@code{add} -- @code{True} 或 @code{False} -- 如为 @code{True} 则将添加一个新绑定，否则将取代先前的绑定
@end itemize


绑定 @emph{fun} 指定的函数到鼠标点击屏幕事件。如果 @emph{fun} 值为 @code{None}，则移除现有的绑定。

以下示例使用一个 TurtleScreen 实例 @code{screen} 和一个 Turtle 实例 @code{turtle}:

@example
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again
@end example

@cartouche
@quotation 注解 
此 TurtleScreen 方法作为全局函数时只有一个名字 @code{onscreenclick}。全局函数 @code{onclick} 所对应的是 Turtle 方法 @code{onclick}。
@end quotation
@end cartouche
@end deffn

@geindex ontimer() (在 turtle 模块中)
@anchor{library/turtle turtle ontimer}@anchor{311e}
@deffn {函数} turtle.ontimer (fun, t=0)

@*参数: 

@itemize *

@item 
@code{fun} -- 一个无参数的函数

@item 
@code{t} -- 一个数值 >= 0
@end itemize


安装一个计时器，在 @emph{t} 毫秒后调用 @emph{fun} 函数。

@example
>>> running = True
>>> def f():
...     if running:
...         fd(50)
...         lt(60)
...         screen.ontimer(f, 250)
>>> f()   ### makes the turtle march around
>>> running = False
@end example
@end deffn

@geindex mainloop() (在 turtle 模块中)
@geindex done() (在 turtle 模块中)
@anchor{library/turtle turtle mainloop}@anchor{311f}
@deffn {函数} turtle.mainloop ()
@anchor{library/turtle turtle done}@anchor{3120}
@deffnx {函数} turtle.done ()

开始事件循环 - 调用 Tkinter 的 mainloop 函数。必须作为一个海龟绘图程序的结束语句。如果一个脚本是在以 -n 模式 (无子进程) 启动的 IDLE 中运行时 @emph{不可} 使用 - 用于实现海龟绘图的交互功能。:

@example
>>> screen.mainloop()
@end example
@end deffn

@node 输入方法,设置与特殊方法,使用屏幕事件,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle input-methods}@anchor{3144}
@subsubsection 输入方法


@geindex textinput() (在 turtle 模块中)
@anchor{library/turtle turtle textinput}@anchor{ff1}
@deffn {函数} turtle.textinput (title, prompt)

@*参数: 

@itemize *

@item 
@code{title} -- 字符串

@item 
@code{prompt} -- 字符串
@end itemize


弹出一个对话框窗口用来输入一个字符串。形参 title 为对话框窗口的标题，prompt 为一条文本，通常用来提示要输入什么信息。返回输入的字符串。如果对话框被取消则返回 @code{None}。:

@example
>>> screen.textinput("NIM", "Name of first player:")
@end example
@end deffn

@geindex numinput() (在 turtle 模块中)
@anchor{library/turtle turtle numinput}@anchor{ff2}
@deffn {函数} turtle.numinput (title, prompt, default=None, minval=None, maxval=None)

@*参数: 

@itemize *

@item 
@code{title} -- 字符串

@item 
@code{prompt} -- 字符串

@item 
@code{default} -- 数值 (可选)

@item 
@code{minval} -- 数值 (可选)

@item 
@code{maxval} -- 数值 (可选)
@end itemize


弹出一个对话框窗口用来输入一个数值。title 为对话框窗口的标题，prompt 为一条文本，通常用来描述要输入的数值信息。default: 默认值, minval: 可输入的最小值, maxval: 可输入的最大值。输入数值的必须在指定的 minval .. maxval 范围之内，否则将给出一条提示，对话框保持打开等待修改。返回输入的数值。如果对话框被取消则返回 @code{None}。:

@example
>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
@end example
@end deffn

@node 设置与特殊方法,Screen 专有方法 而非继承自 TurtleScreen,输入方法,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle settings-and-special-methods}@anchor{3145}
@subsubsection 设置与特殊方法


@geindex mode() (在 turtle 模块中)
@anchor{library/turtle turtle mode}@anchor{3121}
@deffn {函数} turtle.mode (mode=None)

@*参数: 
@code{mode} -- 字符串 "standard", "logo" 或 "world" 其中之一


设置海龟模式 ("standard", "logo" 或 "world") 并执行重置。如未指定模式则返回当前的模式。

"standard" 模式与旧的 @ref{11f,,turtle} 兼容。"logo" 模式与大部分 Logo 海龟绘图兼容。"world" 模式使用用户自定义的 "世界坐标系"。@strong{注意}: 在此模式下，如果 @code{x/y} 单位比率不等于 1 则角度会显得扭曲。


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} 
@headitem

模式

@tab

初始海龟朝向

@tab

正数角度

@item

"standard"

@tab

朝右 (东)

@tab

逆时针

@item

"logo"

@tab

朝上 (北)

@tab

顺时针

@end multitable


@example
>>> mode("logo")   # resets turtle heading to north
>>> mode()
'logo'
@end example
@end deffn

@geindex colormode() (在 turtle 模块中)
@anchor{library/turtle turtle colormode}@anchor{3122}
@deffn {函数} turtle.colormode (cmode=None)

@*参数: 
@code{cmode} -- 数值 1.0 或 255 其中之一


返回颜色模式或将其设为 1.0 或 255。构成颜色三元组的 @emph{r}, @emph{g}, @emph{b} 数值必须在 0..@emph{cmode} 范围之内。

@example
>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
     ...
TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> screen.colormode()
255
>>> turtle.pencolor(240,160,80)
@end example
@end deffn

@geindex getcanvas() (在 turtle 模块中)
@anchor{library/turtle turtle getcanvas}@anchor{3123}
@deffn {函数} turtle.getcanvas ()

返回此 TurtleScreen 的 Canvas 对象。供了解 Tkinter 的 Canvas 对象内部机理的人士使用。

@example
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>
@end example
@end deffn

@geindex getshapes() (在 turtle 模块中)
@anchor{library/turtle turtle getshapes}@anchor{3124}
@deffn {函数} turtle.getshapes ()

返回所有当前可用海龟形状的列表。

@example
>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
@end example
@end deffn

@geindex register_shape() (在 turtle 模块中)
@geindex addshape() (在 turtle 模块中)
@anchor{library/turtle turtle register_shape}@anchor{3125}
@deffn {函数} turtle.register_shape (name, shape=None)
@anchor{library/turtle turtle addshape}@anchor{3126}
@deffnx {函数} turtle.addshape (name, shape=None)

调用此函数有三种不同方式:


@enumerate 

@item 
@emph{name} 为一个 gif 文件的文件名， @emph{shape} 为 @code{None}: 安装相应的图像形状。:

@example
>>> screen.register_shape("turtle.gif")
@end example

@cartouche
@quotation 注解 
当海龟转向时图像形状 @emph{不会} 转动，因此无法显示海龟的朝向!
@end quotation
@end cartouche

@item 
@emph{name} 为指定的字符串，@emph{shape} 为由坐标值对构成的元组: 安装相应的多边形形状。

@example
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
@end example

@item 
@emph{name} 为指定的字符串， 为一个 (复合) @ref{313f,,Shape} 类对象: 安装相应的复合形状。
@end enumerate

将一个海龟形状加入 TurtleScreen 的形状列表。只有这样注册过的形状才能通过执行 @code{shape(shapename)} 命令来使用。
@end deffn

@geindex turtles() (在 turtle 模块中)
@anchor{library/turtle turtle turtles}@anchor{3127}
@deffn {函数} turtle.turtles ()

返回屏幕上的海龟列表。

@example
>>> for turtle in screen.turtles():
...     turtle.color("red")
@end example
@end deffn

@geindex window_height() (在 turtle 模块中)
@anchor{library/turtle turtle window_height}@anchor{3128}
@deffn {函数} turtle.window_height ()

返回海龟窗口的高度。:

@example
>>> screen.window_height()
480
@end example
@end deffn

@geindex window_width() (在 turtle 模块中)
@anchor{library/turtle turtle window_width}@anchor{3129}
@deffn {函数} turtle.window_width ()

返回海龟窗口的宽度。:

@example
>>> screen.window_width()
640
@end example
@end deffn

@node Screen 专有方法 而非继承自 TurtleScreen,,设置与特殊方法,TurtleScreen/Screen 方法及对应函数
@anchor{library/turtle methods-specific-to-screen-not-inherited-from-turtlescreen}@anchor{3146}@anchor{library/turtle screenspecific}@anchor{3147}
@subsubsection Screen 专有方法, 而非继承自 TurtleScreen


@geindex bye() (在 turtle 模块中)
@anchor{library/turtle turtle bye}@anchor{312a}
@deffn {函数} turtle.bye ()

关闭海龟绘图窗口。
@end deffn

@geindex exitonclick() (在 turtle 模块中)
@anchor{library/turtle turtle exitonclick}@anchor{312b}
@deffn {函数} turtle.exitonclick ()

将 @code{bye()} 方法绑定到 Screen 上的鼠标点击事件。

如果配置字典中 "using_IDLE" 的值为 @code{False} (默认值) 则同时进入主事件循环。注: 如果启动 IDLE 时使用了 @code{-n} 开关 (无子进程)，@code{turtle.cfg} 中此数值应设为 @code{True}。在此情况下 IDLE 本身的主事件循环同样会作用于客户脚本。
@end deffn

@geindex setup() (在 turtle 模块中)
@anchor{library/turtle turtle setup}@anchor{312c}
@deffn {函数} turtle.setup (width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])

设置主窗口的大小和位置。默认参数值保存在配置字典中，可通过 @code{turtle.cfg} 文件进行修改。

@*参数: 

@itemize *

@item 
@code{width} -- 如为一个整型数值，表示大小为多少像素，如为一个浮点数值，则表示屏幕的占比；默认为屏幕的 50%

@item 
@code{height} -- 如为一个整型数值，表示高度为多少像素，如为一个浮点数值，则表示屏幕的占比；默认为屏幕的 75%

@item 
@code{startx} -- 如为正值，表示初始位置距离屏幕左边缘多少像素，负值表示距离右边缘，@code{None} 表示窗口水平居中

@item 
@code{starty} -- 如为正值，表示初始位置距离屏幕上边缘多少像素，负值表示距离下边缘，@code{None} 表示窗口垂直居中
@end itemize


@example
>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers
@end example
@end deffn

@geindex title() (在 turtle 模块中)
@anchor{library/turtle turtle title}@anchor{312d}
@deffn {函数} turtle.title (titlestring)

@*参数: 
@code{titlestring} -- 一个字符串，显示为海龟绘图窗口的标题栏文本


设置海龟窗口标题为 @emph{titlestring} 指定的文本。

@example
>>> screen.title("Welcome to the turtle zoo!")
@end example
@end deffn

@node 公共类,帮助与配置,TurtleScreen/Screen 方法及对应函数,turtle --- 海龟绘图
@anchor{library/turtle public-classes}@anchor{3148}
@subsubsection 公共类


@geindex RawTurtle (turtle 中的类)
@geindex RawPen (turtle 中的类)
@anchor{library/turtle turtle RawTurtle}@anchor{30bb}
@deffn {类} turtle.RawTurtle (canvas)
@anchor{library/turtle turtle RawPen}@anchor{30bc}
@deffnx {类} turtle.RawPen (canvas)

@*参数: 
@code{canvas} -- 一个 @code{tkinter.Canvas} , @ref{30b9,,ScrolledCanvas} 或 @ref{30b8,,TurtleScreen} 类对象


创建一个海龟。海龟对象具有 "Turtle/RawTurtle 方法" 一节所述的全部方法。
@end deffn

@geindex Turtle (turtle 中的类)
@anchor{library/turtle turtle Turtle}@anchor{30bd}
@deffn {类} turtle.Turtle

RawTurtle 的子类，具有相同的接口，但其绘图场所为默认的 @ref{30ba,,Screen} 类对象，在首次使用时自动创建。
@end deffn

@geindex TurtleScreen (turtle 中的类)
@anchor{library/turtle turtle TurtleScreen}@anchor{30b8}
@deffn {类} turtle.TurtleScreen (cv)

@*参数: 
@code{cv} -- 一个 @code{tkinter.Canvas} 类对象


提供面向屏幕的方法例如 @code{setbg()} 等。说明见上文。
@end deffn

@geindex Screen (turtle 中的类)
@anchor{library/turtle turtle Screen}@anchor{30ba}
@deffn {类} turtle.Screen

TurtleScreen 的子类，@ref{3147,,增加了四个方法}.
@end deffn

@geindex ScrolledCanvas (turtle 中的类)
@anchor{library/turtle turtle ScrolledCanvas}@anchor{30b9}
@deffn {类} turtle.ScrolledCanvas (master)

@*参数: 
@code{master} -- 可容纳 ScrolledCanvas 的 Tkinter 部件，即添加了滚动条的 Tkinter-canvas


由 Screen 类使用，使其能够自动提供一个 ScrolledCanvas 作为海龟的绘图场所。
@end deffn

@geindex Shape (turtle 中的类)
@anchor{library/turtle turtle Shape}@anchor{313f}
@deffn {类} turtle.Shape (type_, data)

@*参数: 
@code{type_} -- 字符串 "polygon", "image", "compound" 其中之一


实现形状的数据结构。@code{(type_, data)} 必须遵循以下定义:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@emph{type_}

@tab

@emph{data}

@item

"polygon"

@tab

一个多边形元组，即由坐标值对构成的元组

@item

"image"

@tab

一个图片  (此形式仅限内部使用!)

@item

"compound"

@tab

@code{None} (复合形状必须使用 @ref{3149,,addcomponent()} 方法来构建)

@end multitable


@geindex addcomponent() (turtle.Shape 方法)
@anchor{library/turtle turtle Shape addcomponent}@anchor{3149}
@deffn {方法} addcomponent (poly, fill, outline=None)

@*参数: 

@itemize *

@item 
@code{poly} -- 一个多边形，即由数值对构成的元组

@item 
@code{fill} -- 一种颜色，将用来填充 @emph{poly} 指定的多边形

@item 
@code{outline} -- 一种颜色，用于多边形的轮廓 (如有指定)
@end itemize


示例:

@example
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # ... add more components and then use register_shape()
@end example

参见 @ref{313e,,复合形状}。
@end deffn
@end deffn

@geindex Vec2D (turtle 中的类)
@anchor{library/turtle turtle Vec2D}@anchor{3130}
@deffn {类} turtle.Vec2D (x, y)

一个二维矢量类，用来作为实现海龟绘图的辅助类。也可能在海龟绘图程序中使用。派生自元组，因此矢量也属于元组!

提供的运算 (@emph{a}, @emph{b} 为矢量, @emph{k} 为数值):


@itemize *

@item 
@code{a + b} 矢量加法

@item 
@code{a - b} 矢量减法

@item 
@code{a * b} 内积

@item 
@code{k * a} 和 @code{a * k} 与标量相乘

@item 
@code{abs(a)} a 的绝对值

@item 
@code{a.rotate(angle)} 旋转
@end itemize
@end deffn

@node 帮助与配置,turtledemo --- 演示脚本集,公共类,turtle --- 海龟绘图
@anchor{library/turtle help-and-configuration}@anchor{314a}
@subsubsection 帮助与配置


@menu
* 如何使用帮助:: 
* 文档字符串翻译为不同的语言:: 
* 如何配置 Screen 和 Turtle:: 

@end menu

@node 如何使用帮助,文档字符串翻译为不同的语言,,帮助与配置
@anchor{library/turtle how-to-use-help}@anchor{314b}
@subsubsection 如何使用帮助


Screen 和 Turtle 类的公用方法以文档字符串提供了详细的文档。因此可以利用 Python 帮助工具获取这些在线帮助信息:


@itemize -

@item 
当使用 IDLE 时，输入函数/方法调用将弹出工具提示显示其签名和文档字符串的头几行。

@item 
对文法或函数调用 @ref{175,,help()} 将显示其文档字符串:

@example
>>> help(Screen.bgcolor)
Help on method bgcolor in module turtle:

bgcolor(self, *args) unbound turtle.Screen method
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.


      >>> screen.bgcolor("orange")
      >>> screen.bgcolor()
      "orange"
      >>> screen.bgcolor(0.5,0,0.5)
      >>> screen.bgcolor()
      "#800080"

>>> help(Turtle.penup)
Help on method penup in module turtle:

penup(self) unbound turtle.Turtle method
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    >>> turtle.penup()
@end example

@item 
方法对应函数的文档字符串的形式会有一些修改:

@example
>>> help(bgcolor)
Help on function bgcolor in module turtle:

bgcolor(*args)
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.

    Example::

      >>> bgcolor("orange")
      >>> bgcolor()
      "orange"
      >>> bgcolor(0.5,0,0.5)
      >>> bgcolor()
      "#800080"

>>> help(penup)
Help on function penup in module turtle:

penup()
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    Example:
    >>> penup()
@end example
@end itemize

这些修改版文档字符串是在导入时与方法对应函数的定义一起自动生成的。

@node 文档字符串翻译为不同的语言,如何配置 Screen 和 Turtle,如何使用帮助,帮助与配置
@anchor{library/turtle translation-of-docstrings-into-different-languages}@anchor{314c}
@subsubsection 文档字符串翻译为不同的语言


可使用工具创建一个字典，键为方法名，值为 Screen 和 Turtle 类公共方法的文档字符串。

@geindex write_docstringdict() (在 turtle 模块中)
@anchor{library/turtle turtle write_docstringdict}@anchor{314d}
@deffn {函数} turtle.write_docstringdict (filename="turtle_docstringdict")

@*参数: 
@code{filename} -- 一个字符串，表示文件名


创建文档字符串字典并将其写入 filename 指定的 Python 脚本文件。此函数必须显示地调用 (海龟绘图类并不使用此函数)。文档字符串字典将被写入到 Python 脚本文件 @code{@emph{filename}.py}。该文件可作为模板用来将文档字符串翻译为不同语言。
@end deffn

如果你 (或你的学生) 想使用本国语言版本的 @ref{11f,,turtle} 在线帮助，你必须翻译文档字符串并保存结果文件，例如 @code{turtle_docstringdict_german.py}.

如果你在 @code{turtle.cfg} 文件中加入了相应的条目，此字典将在导入模块时被读取并替代原有的英文版文档字符串。

在撰写本文档时已经有了德语和意大利语版的文档字符串字典。(更多需求请联系 @email{glingl@@aon.at})

@node 如何配置 Screen 和 Turtle,,文档字符串翻译为不同的语言,帮助与配置
@anchor{library/turtle how-to-configure-screen-and-turtles}@anchor{314e}
@subsubsection 如何配置 Screen 和 Turtle


内置的默认配置是模仿旧 turtle 模块的外观和行为，以便尽可能地与其保持兼容。

如果你想使用不同的配置，以便更好地反映此模块的特性或是更适合你的需求，例如在课堂中使用，你可以准备一个配置文件 @code{turtle.cfg}，该文件将在导入模块时被读取并根据其中的设定修改模块配置。

内置的配置对应以下的 turtle.cfg:

@example
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
@end example

选定条目的简短说明:


@itemize -

@item 
开头的四行对应 @code{Screen.setup()} 方法的参数。

@item 
第 5 和 6 行对应 @code{Screen.screensize()} 方法的参数。

@item 
@emph{shape} 可以是任何内置形状，即: arrow, turtle 等。更多信息可用 @code{help(shape)} 查看。

@item 
如果你想使用无填充色 (即令海龟变透明)，你必须写 @code{fillcolor = ""} (但 cfg 文件中所有非空字符串都不可加引号)。

@item 
如果你想令海龟反映其状态，你必须使用 @code{resizemode = auto}。

@item 
如果你设置语言例如 @code{language = italian} 则文档字符串字典 @code{turtle_docstringdict_italian.py} 将在导入模块时被加载 (如果导入路径即 @ref{11f,,turtle} 的目录中存在此文件。

@item 
@emph{exampleturtle} 和 @emph{examplescreen} 条目定义了相应对象在文档字符串中显示的名称。方法文档字符串转换为函数文档字符串时将从文档字符串中删去这些名称。

@item 
@emph{using_IDLE}: 如果你经常使用 IDLE 并启用其 -n 开关 ("无子进程") 则应将此项设为 @code{True}，这将阻止 @ref{312b,,exitonclick()} 进入主事件循环。
@end itemize

@code{turtle.cfg} 文件可以保存于 @ref{11f,,turtle} 所在目录，当前工作目录也可以有一个同名文件。后者会重载覆盖前者的设置。

@code{Lib/turtledemo} 目录中也有一个 @code{turtle.cfg} 文件。你可以将其作为示例进行研究，并在运行演示时查看其作用效果 (但最好不要在演示查看器中运行)。

@node turtledemo --- 演示脚本集,Python 2 6 之后的变化,帮助与配置,turtle --- 海龟绘图
@anchor{library/turtle module-turtledemo}@anchor{120}@anchor{library/turtle turtledemo-demo-scripts}@anchor{314f}
@subsubsection @code{turtledemo} --- 演示脚本集


@geindex turtledemo (模块)

@ref{120,,turtledemo} 包汇集了一组演示脚本。这些脚本可以通过以下命令打开所提供的演示查看器运行和查看:

@example
python -m turtledemo
@end example

此外，你也可以单独运行其中的演示脚本。例如，:

@example
python -m turtledemo.bytedesign
@end example

@ref{120,,turtledemo} 包目录中的内容:


@itemize -

@item 
一个演示查看器 @code{__main__.py}，可用来查看脚本的源码并即时运行。

@item 
多个脚本文件，演示 @ref{11f,,turtle} 模块的不同特性。所有示例可通过 Examples 菜单打开。也可以单独运行每个脚本。

@item 
一个 @code{turtle.cfg} 文件，作为说明如何编写并使用模块配置文件的示例模板。
@end itemize

演示脚本清单如下:


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名称

@tab

描述

@tab

相关特性

@item

bytedesign

@tab

复杂的传统海龟绘图模式

@tab

@code{tracer()}, delay,
@code{update()}

@item

chaos

@tab

绘制 Verhulst 动态模型，演示通过计算机的运算可能会生成令人惊叹的结果

@tab

世界坐标系

@item

clock

@tab

绘制模拟时钟显示本机的当前时间

@tab

海龟作为表针, ontimer

@item

colormixer

@tab

试验 r, g, b 颜色模式

@tab

@code{ondrag()} 当鼠标拖动

@item

forest

@tab

绘制 3 棵广度优先树

@tab

随机化

@item

fractalcurves

@tab

绘制 Hilbert & Koch 曲线

@tab

递归

@item

lindenmayer

@tab

文化数学 (印度装饰艺术)

@tab

L-系统

@item

minimal_hanoi

@tab

汉诺塔

@tab

矩形海龟作为汉诺盘 (shape, shapesize)

@item

nim

@tab

玩经典的“尼姆”游戏，开始时有三堆小棒，与电脑对战。

@tab

海龟作为小棒，事件驱动 (鼠标, 键盘)

@item

paint

@tab

超极简主义绘画程序

@tab

@code{onclick()} 当鼠标点击

@item

peace

@tab

初级技巧

@tab

海龟: 外观与动画

@item

penrose

@tab

非周期性地使用风筝和飞镖形状铺满平面

@tab

@code{stamp()} 印章

@item

planet_and_moon

@tab

模拟引力系统

@tab

复合开关, @code{Vec2D} 类

@item

round_dance

@tab

两两相对并不断旋转舞蹈的海龟

@tab

复合形状, clone shapesize, tilt, get_shapepoly, update

@item

sorting_animate

@tab

动态演示不同的排序方法

@tab

简单对齐, 随机化

@item

tree

@tab

一棵 (图形化的) 广度优先树 (使用生成器)

@tab

@code{clone()} 克隆

@item

two_canvases

@tab

简单设计

@tab

两块画布上的海龟

@item

wikipedia

@tab

一个来自介绍海龟绘图的维基百科文章的图案

@tab

@code{clone()},
@code{undo()}

@item

yinyang

@tab

另一个初级示例

@tab

@code{circle()} 画圆

@end multitable


祝你玩得开心！

@node Python 2 6 之后的变化,Python 3 0 之后的变化,turtledemo --- 演示脚本集,turtle --- 海龟绘图
@anchor{library/turtle changes-since-python-2-6}@anchor{3150}
@subsubsection Python 2.6 之后的变化



@itemize -

@item 
@code{Turtle.tracer()}, @code{Turtle.window_width()} 和 @code{Turtle.window_height()} 方法已被去除。具有这些名称和功能的方法现在只限于 @code{Screen} 类的方法。但其对应的函数仍然可用。(实际上在 Python 2.6 中这些方法就已经只是从对应的 @code{TurtleScreen}/@code{Screen} 类的方法复制而来。)

@item 
@code{Turtle.fill()} 方法已被去除。@code{begin_fill()} 和 @code{end_fill()} 的行为则有细微改变: 现在每个填充过程必须以一个 @code{end_fill()} 调用来结束。

@item 
新增了一个 @code{Turtle.filling()} 方法。该方法返回一个布尔值: 如果填充过程正在进行为 @code{True}，否则为 @code{False}。此行为相当于 Python 2.6 中不带参数的 @code{fill()} 调用。
@end itemize

@node Python 3 0 之后的变化,,Python 2 6 之后的变化,turtle --- 海龟绘图
@anchor{library/turtle changes-since-python-3-0}@anchor{3151}
@subsubsection Python 3.0 之后的变化



@itemize -

@item 
新增了 @code{Turtle.shearfactor()}, @code{Turtle.shapetransform()} 和 @code{Turtle.get_shapepoly()} 方法。这样就可以使用所有标准线性变换来调整海龟形状。@code{Turtle.tiltangle()} 的功能已被加强: 现在可被用来获取或设置倾角。@code{Turtle.settiltangle()} 已弃用。

@item 
新增了 @code{Screen.onkeypress()} 方法作为对 @code{Screen.onkey()} 的补充，实际就是将行为绑定到 keyrelease 事件。后者相应增加了一个别名: @code{Screen.onkeyrelease()}。

@item 
新增了  @code{Screen.mainloop()} 方法。这样当仅需使用 Screen 和 Turtle 对象时不需要再额外导入 @code{mainloop()}。

@item 
新增了两个方法 @code{Screen.textinput()} 和 @code{Screen.numinput()}。用来弹出对话框接受输入并分别返回字符串和数值。

@item 
两个新的示例脚本 @code{tdemo_nim.py} 和 @code{tdemo_round_dance.py} 被加入到 @code{Lib/turtledemo} 目录中。
@end itemize

@c >>> for turtle in turtles():
@c ...      turtle.reset()
@c >>> turtle.penup()
@c >>> turtle.goto(-200,25)
@c >>> turtle.pendown()
@c >>> turtle.write("No one expects the Spanish Inquisition!",
@c ...      font=("Arial", 20, "normal"))
@c >>> turtle.penup()
@c >>> turtle.goto(-100,-50)
@c >>> turtle.pendown()
@c >>> turtle.write("Our two chief Turtles are...",
@c ...      font=("Arial", 16, "normal"))
@c >>> turtle.penup()
@c >>> turtle.goto(-450,-75)
@c >>> turtle.write(str(turtles()))

@node cmd --- 支持面向行的命令解释器,shlex —— 简单的词义分析,turtle --- 海龟绘图,程序框架
@anchor{library/cmd doc}@anchor{3152}@anchor{library/cmd cmd-support-for-line-oriented-command-interpreters}@anchor{3153}@anchor{library/cmd module-cmd}@anchor{19}
@subsection @code{cmd} --- 支持面向行的命令解释器


@geindex cmd (模块)

@strong{源代码:} Lib/cmd.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/cmd.py}


__________________________________________________________________


@ref{3154,,Cmd} 类提供简单框架用于编写面向行的命令解释器。  这些通常对测试工具，管理工具和原型有用，这些工具随后将被包含在更复杂的接口中。

@geindex Cmd (cmd 中的类)
@anchor{library/cmd cmd Cmd}@anchor{3154}
@deffn {类} cmd.Cmd (completekey='tab', stdin=None, stdout=None)

一个 @ref{3154,,Cmd} 实例或子类实例是面向行的解释器框架结构。 实例化 @ref{3154,,Cmd} 本身是没有充分理由的， 它作为自定义解释器类的超类是非常有用的为了继承 @ref{3154,,Cmd} 的方法并且封装动作方法。

可选参数 @emph{completekey} 是完成键的 @ref{de,,readline} 名称；默认是 @code{Tab} 。如果 @emph{completekey} 不是 @ref{204,,None} 并且 @ref{de,,readline} 是可用的， 命令完成会自动完成。

可选参数 @emph{stdin} 和 @emph{stdout} 指定了Cmd实例或子类实例将用于输入和输出的输入和输出文件对象。如果没有指定，他们将默认为 @ref{427,,sys.stdin} 和 @ref{428,,sys.stdout} 。

如果你想要使用一个给定的 @emph{stdin} ，确保将实例的 @ref{3155,,use_rawinput} 属性设置为 @code{False} ，否则 @emph{stdin} 将被忽略。
@end deffn

@menu
* Cmd 对象:: 
* Cmd 例子:: 

@end menu

@node Cmd 对象,Cmd 例子,,cmd --- 支持面向行的命令解释器
@anchor{library/cmd cmd-objects}@anchor{3156}@anchor{library/cmd id1}@anchor{3157}
@subsubsection Cmd 对象


@ref{3154,,Cmd} 实例有下列方法：

@geindex cmdloop() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd cmdloop}@anchor{3158}
@deffn {方法} Cmd.cmdloop (intro=None)

反复发出提示，接受输入，从收到的输入中解析出一个初始前缀，并分派给操作方法，将其余的行作为参数传递给它们。

可选参数是在第一个提示之前发布的横幅或介绍字符串（这将覆盖 @ref{3159,,intro} 类属性）。

如果 @ref{de,,readline} 继承模块被加载，输入将自动继承类似 @code{bash}的历史列表编辑（例如， @code{Control-P} 滚动回到最后一个命令， @code{Control-N} 转到下一个命令，以 @code{Control-F} 非破坏性的方式向右 @code{Control-B} 移动光标，破坏性地等）。

输入的文件结束符被作为字符串传回 @code{'EOF'} 。

@geindex ? (question mark); in a command interpreter
@geindex ! (exclamation); in a command interpreter

解释器实例将会识别命令名称 @code{foo} 当且仅当它有方法 @code{do_foo()} 。有一个特殊情况，分派始于字符 @code{'?'} 的行到方法 @code{do_help()} 。另一种特殊情况，分派始于字符 @code{'!'} 的行到方法 @code{do_shell()} （如果定义了这个方法）

这个方法将返回当 @ref{315a,,postcmd()} 方法返回一个真值 。参数 @emph{stop} 到 @ref{315a,,postcmd()} 是命令对应的返回值 @code{do_*()} 的方法。

如果激活了完成，全部命令将会自动完成，并且通过调用 @code{complete_foo()} 参数 @emph{text} , @emph{line}, @emph{begidx} ,和 @emph{endidx} 完成全部命令参数。 @emph{text} 是我们试图匹配的字符串前缀，所有返回的匹配项必须以它为开头。 @emph{line} 是删除了前导空格的当前的输入行， @emph{begidx} 和 @emph{endidx} 是前缀文本的开始和结束索引。，可以用于根据参数位置提供不同的完成。

所有 @ref{3154,,Cmd} 的子类继承一个预定义 @code{do_help()} 。 这个方法使用参数 @code{'bar'} 调用， 调用对应的方法 @code{help_bar()} ，如果不存在，打印 @code{do_bar()} 的文档字符串，如果可用。没有参数的情况下， @code{do_help()} 方法会列出所有可用的帮助主题 （即所有具有相应的 @code{help_*()} 方法或命令的 文档字符串），也会列举所有未被记录的命令。
@end deffn

@geindex onecmd() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd onecmd}@anchor{315b}
@deffn {方法} Cmd.onecmd (str)

解释该参数，就好像它是为响应提示而键入的一样。 这可能会被覆盖，但通常不应该被覆盖; 请参阅： @ref{315c,,precmd()} 和 @ref{315a,,postcmd()} 方法，用于执行有用的挂钩。 返回值是一个标志，指示解释器对命令的解释是否应该停止。 如果命令 @emph{str} 有一个 @code{do_*()} 方法，则返回该方法的返回值，否则返回 @ref{315d,,default()} 方法的返回值。
@end deffn

@geindex emptyline() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd emptyline}@anchor{315e}
@deffn {方法} Cmd.emptyline ()

在响应提示输入空行时调用的方法。如果此方法未被覆盖，则重复输入的最后一个非空命令。
@end deffn

@geindex default() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd default}@anchor{315d}
@deffn {方法} Cmd.default (line)

当命令前缀不能被识别的时候在输入行调用的方法。如果此方法未被覆盖，它将输出一个错误信息并返回。
@end deffn

@geindex completedefault() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd completedefault}@anchor{315f}
@deffn {方法} Cmd.completedefault (text, line, begidx, endidx)

当没有特定于命令的 @code{complete_*()} 方法可用时，调用此方法完成输入行。默认情况下，它返回一个空列表。
@end deffn

@geindex precmd() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd precmd}@anchor{315c}
@deffn {方法} Cmd.precmd (line)

钩方法在命令行 @emph{line} 被解释之前执行，但是在输入提示被生成和发出后。这个方法是一个在 @ref{3154,,Cmd} 中的存根；它的存在是为了被子类覆盖。返回值被用作  @ref{315b,,onecmd()} 方法执行的命令； @ref{315c,,precmd()} 的实现或许会重写命令或者简单的返回 @emph{line} 不变。
@end deffn

@geindex postcmd() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd postcmd}@anchor{315a}
@deffn {方法} Cmd.postcmd (stop, line)

钩方法只在命令调度完成后执行。这个方法是一个在 @ref{3154,,Cmd} 中的存根；它的存在是为了子类被覆盖。 @emph{line} 是被执行的命令行， @emph{stop} 是一个表示在调用 @ref{315a,,postcmd()} 之后是否终止执行的标志；这将作为 @ref{315b,,onecmd()} 方法的返回值。这个方法的返回值被用作与 @emph{stop} 相关联的内部标志的新值；返回 false 将导致解释继续。
@end deffn

@geindex preloop() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd preloop}@anchor{3160}
@deffn {方法} Cmd.preloop ()

钩方法当 @ref{3158,,cmdloop()} 被调用时执行一次。方法是一个在 @ref{3154,,Cmd} 中的存根；它的存在是为了被子类覆盖。
@end deffn

@geindex postloop() (cmd.Cmd 方法)
@anchor{library/cmd cmd Cmd postloop}@anchor{3161}
@deffn {方法} Cmd.postloop ()

钩方法在 @ref{3158,,cmdloop()} 即将返回时执行一次。这个方法是一个在 @ref{3154,,Cmd} 中的存根；它的存在是为了被子类覆盖。
@end deffn

Instances of @ref{3154,,Cmd} subclasses have some public instance variables:

@geindex prompt (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd prompt}@anchor{3162}
@deffn {属性} Cmd.prompt

发出提示以请求输入。
@end deffn

@geindex identchars (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd identchars}@anchor{3163}
@deffn {属性} Cmd.identchars

接受命令前缀的字符串。
@end deffn

@geindex lastcmd (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd lastcmd}@anchor{3164}
@deffn {属性} Cmd.lastcmd

看到最后一个非空命令前缀。
@end deffn

@geindex cmdqueue (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd cmdqueue}@anchor{3165}
@deffn {属性} Cmd.cmdqueue

排队的输入行列表。当需要新的输入时，在 @ref{3158,,cmdloop()} 中检查 cmdqueue 列表；如果它不是空的，它的元素将被按顺序处理，就像在提示符处输入一样。
@end deffn

@geindex intro (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd intro}@anchor{3159}
@deffn {属性} Cmd.intro

要作为简介或横幅发出的字符串。 可以通过给 @ref{3158,,cmdloop()} 方法一个参数来覆盖它。
@end deffn

@geindex doc_header (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd doc_header}@anchor{3166}
@deffn {属性} Cmd.doc_header

如果帮助输出具有记录命令的段落，则发出头文件。
@end deffn

@geindex misc_header (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd misc_header}@anchor{3167}
@deffn {属性} Cmd.misc_header

如果帮助输出其他帮助主题的部分（即与 @code{do_*()} 方法没有关联的 @code{help_*()} 方法），则发出头文件。
@end deffn

@geindex undoc_header (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd undoc_header}@anchor{3168}
@deffn {属性} Cmd.undoc_header

如果帮助输出未被记录命令的部分（即与 @code{help_*()} 方法没有关联的 @code{do_*()} 方法），则发出头文件。
@end deffn

@geindex ruler (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd ruler}@anchor{3169}
@deffn {属性} Cmd.ruler

用于在帮助信息标题的下方绘制分隔符的字符，如果为空，则不绘制标尺线。 这个字符默认是 @code{'='} 。
@end deffn

@geindex use_rawinput (cmd.Cmd 属性)
@anchor{library/cmd cmd Cmd use_rawinput}@anchor{3155}
@deffn {属性} Cmd.use_rawinput

这是一个标志，默认为 true 。如果为 true ，, @ref{3158,,cmdloop()} 使用 @ref{d3b,,input()} 先是提示并且阅读下一个命令；如果为 false ， @code{sys.stdout.write()} 和 @code{sys.stdin.readline()} 被使用。（这意味着解释器将会自动支持类似于 @code{Emacs}的行编辑和命令历史记录按键操作，通过导入 @ref{de,,readline} 在支持它的系统上。）
@end deffn

@node Cmd 例子,,Cmd 对象,cmd --- 支持面向行的命令解释器
@anchor{library/cmd cmd-example}@anchor{316a}@anchor{library/cmd id2}@anchor{316b}
@subsubsection Cmd 例子


The @ref{19,,cmd} module is mainly useful for building custom shells that let a
user work with a program interactively.

这部分提供了一个简单的例子来介绍如何使用一部分在 @ref{11f,,turtle} 模块中的命令构建一个 shell 。

基础的 turtle 命令比如 @ref{30c0,,forward()} 被添加进一个 @ref{3154,,Cmd} 子类，方法名为  @code{do_forward()} 。参数被转换成数字并且分发至 turtle 模组中。 docstring 是 shell 提供的帮助实用程序。

例子也包含使用 @ref{315c,,precmd()} 方法实现基础的记录和回放的功能，这个方法负责将输入转换为小写并且将命令写入文件。 @code{do_playback()} 方法读取文件并添加记录命令至 @code{cmdqueue} 用于即时回放:

@example
import cmd, sys
from turtle import *

class TurtleShell(cmd.Cmd):
    intro = 'Welcome to the turtle shell.   Type help or ? to list commands.\n'
    prompt = '(turtle) '
    file = None

    # ----- basic turtle commands -----
    def do_forward(self, arg):
        'Move the turtle forward by the specified distance:  FORWARD 10'
        forward(*parse(arg))
    def do_right(self, arg):
        'Turn turtle right by given number of degrees:  RIGHT 20'
        right(*parse(arg))
    def do_left(self, arg):
        'Turn turtle left by given number of degrees:  LEFT 90'
        left(*parse(arg))
    def do_goto(self, arg):
        'Move turtle to an absolute position with changing orientation.  GOTO 100 200'
        goto(*parse(arg))
    def do_home(self, arg):
        'Return turtle to the home position:  HOME'
        home()
    def do_circle(self, arg):
        'Draw circle with given radius an options extent and steps:  CIRCLE 50'
        circle(*parse(arg))
    def do_position(self, arg):
        'Print the current turtle position:  POSITION'
        print('Current position is %d %d\n' % position())
    def do_heading(self, arg):
        'Print the current turtle heading in degrees:  HEADING'
        print('Current heading is %d\n' % (heading(),))
    def do_color(self, arg):
        'Set the color:  COLOR BLUE'
        color(arg.lower())
    def do_undo(self, arg):
        'Undo (repeatedly) the last turtle action(s):  UNDO'
    def do_reset(self, arg):
        'Clear the screen and return turtle to center:  RESET'
        reset()
    def do_bye(self, arg):
        'Stop recording, close the turtle window, and exit:  BYE'
        print('Thank you for using Turtle')
        self.close()
        bye()
        return True

    # ----- record and playback -----
    def do_record(self, arg):
        'Save future commands to filename:  RECORD rose.cmd'
        self.file = open(arg, 'w')
    def do_playback(self, arg):
        'Playback commands from a file:  PLAYBACK rose.cmd'
        self.close()
        with open(arg) as f:
            self.cmdqueue.extend(f.read().splitlines())
    def precmd(self, line):
        line = line.lower()
        if self.file and 'playback' not in line:
            print(line, file=self.file)
        return line
    def close(self):
        if self.file:
            self.file.close()
            self.file = None

def parse(arg):
    'Convert a series of zero or more numbers to an argument tuple'
    return tuple(map(int, arg.split()))

if __name__ == '__main__':
    TurtleShell().cmdloop()
@end example

这是一个示例会话，其中 turtle shell 显示帮助功能，使用空行重复命令，以及简单的记录和回放功能：

@example
Welcome to the turtle shell.   Type help or ? to list commands.

(turtle) ?

Documented commands (type help <topic>):
========================================
bye     color    goto     home  playback  record  right
circle  forward  heading  left  position  reset   undo

(turtle) help forward
Move the turtle forward by the specified distance:  FORWARD 10
(turtle) record spiral.cmd
(turtle) position
Current position is 0 0

(turtle) heading
Current heading is 0

(turtle) reset
(turtle) circle 20
(turtle) right 30
(turtle) circle 40
(turtle) right 30
(turtle) circle 60
(turtle) right 30
(turtle) circle 80
(turtle) right 30
(turtle) circle 100
(turtle) right 30
(turtle) circle 120
(turtle) right 30
(turtle) circle 120
(turtle) heading
Current heading is 180

(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 500
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 300
(turtle) playback spiral.cmd
Current position is 0 0

Current heading is 0

Current heading is 180

(turtle) bye
Thank you for using Turtle
@end example

@node shlex —— 简单的词义分析,,cmd --- 支持面向行的命令解释器,程序框架
@anchor{library/shlex doc}@anchor{316c}@anchor{library/shlex module-shlex}@anchor{e8}@anchor{library/shlex shlex-simple-lexical-analysis}@anchor{316d}
@subsection @code{shlex} —— 简单的词义分析


@geindex shlex (模块)

@strong{源代码：} Lib/shlex.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/shlex.py}


__________________________________________________________________


@ref{67b,,shlex} 类可用于编写类似 Unix shell 的简单词义分析程序。通常可用于编写“迷你语言”（如 Python 应用程序的运行控制文件）或解析带引号的字符串。

@ref{e8,,shlex} 模块中定义了以下函数：

@geindex split() (在 shlex 模块中)
@anchor{library/shlex shlex split}@anchor{211}
@deffn {函数} shlex.split (s, comments=False, posix=True)

用类似 shell 的语法拆分字符串 @emph{s}。如果 @emph{comments} 为 @ref{497,,False} (默认值)，则不会解析给定字符串中的注释 (@ref{316e,,commenters} 属性的 @ref{67b,,shlex} 实例设为空字符串)。 本函数默认工作于 POSIX 模式下，但若 @emph{posix} 参数为 False，则采用非 POSIX 模式。

@cartouche
@quotation 注解 
Since the @ref{211,,split()} function instantiates a @ref{67b,,shlex}
instance, passing @code{None} for @emph{s} will read the string to split from
standard input.
@end quotation
@end cartouche


3.9 版后已移除: 在以后的 Python 版本中，给 @emph{s} 传入 @code{None} 将触发异常。

@end deffn

@geindex join() (在 shlex 模块中)
@anchor{library/shlex shlex join}@anchor{34c}
@deffn {函数} shlex.join (split_command)

将列表 @emph{split_command} 中的单词串联起来，返回一个字符串。本函数是 @ref{211,,split()} 的逆运算。

@example
>>> from shlex import join
>>> print(join(['echo', '-n', 'Multiple words']))
echo -n 'Multiple words'
@end example

为防止注入漏洞，返回值是经过 shell 转义的（参见 @ref{b57,,quote()} ）。


3.8 新版功能.

@end deffn

@geindex quote() (在 shlex 模块中)
@anchor{library/shlex shlex quote}@anchor{b57}
@deffn {函数} shlex.quote (s)

返回经过  shell 转义的字符串 @emph{s} 。返回值为字符串，可以安全地作为 shell 命令行中的单词使用，可用于不能使用列表的场合。

以下用法是不安全的：

@example
>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l @{@}'.format(filename)
>>> print(command)  # executed by a shell: boom!
ls -l somefile; rm -rf ~
@end example

用 @ref{b57,,quote()} 可以堵住这种安全漏洞：

@example
>>> from shlex import quote
>>> command = 'ls -l @{@}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home @{@}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"'@w{'}
@end example

这种包装方式兼容于 UNIX shell 和 @ref{211,,split()} 。

@example
>>> from shlex import split
>>> remote_command = split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']
@end example


3.3 新版功能.

@end deffn

@ref{e8,,shlex} 模块中定义了以下类：

@geindex shlex (shlex 中的类)
@anchor{library/shlex shlex shlex}@anchor{67b}
@deffn {类} shlex.shlex (instream=None, infile=None, posix=False, punctuation_chars=False)

@ref{67b,,shlex} 及其子类的实例是一种词义分析器对象。 利用初始化参数可指定从哪里读取字符。 初始化参数必须是具备 @ref{2192,,read()} 和 @ref{1da3,,readline()} 方法的文件/流对象，或者是一个字符串。 如果没有给出初始化参数，则会从 @code{sys.stdin} 获取输入。 第二个可选参数是个文件名字符串，用于设置 @ref{316f,,infile} 属性的初始值。 如果 @emph{instream} 参数被省略或等于 @code{sys.stdin}，则第二个参数默认为 "stdin"。 @emph{posix} 参数定义了操作的模式：若 @emph{posix} 不为真值（默认），则 @ref{67b,,shlex} 实例将工作于兼容模式。 若运行于 POSIX 模式下，则 @ref{67b,,shlex} 会尽可能地应用 POSIX shell 解析规则。 @emph{punctuation_chars} 参数提供了一种使行为更接近于真正的 shell 解析的方式。 该参数可接受多种值：默认值、@code{False}、保持 Python 3.5 及更早版本的行为。 如果设为 @code{True}，则会改变对字符 @code{();<>|&} 的解析方式：这些字符将作为独立的形符被返回（视作标点符号）。 如果设为非空字符串，则这些字符将被用作标点符号。 出现在 @emph{punctuation_chars} 中的 @ref{3170,,wordchars} 属性中的任何字符都会从 @ref{3170,,wordchars} 中被删除。 请参阅 @ref{67c,,改进的 shell 兼容性} 了解详情。 @emph{punctuation_chars} 只能在创建 @ref{67b,,shlex} 实例时设置，以后不能再作修改。


在 3.6 版更改: 加入 @emph{punctuation_chars} 参数。

@end deffn


@subsubheading 参见



@table @asis

@item @ref{22,,configparser} 模块

配置文件解析器，类似于 Windows 的 @code{.ini} 文件。
@end table


@menu
* shlex 对象:: 
* 解析规则:: 
* 改进的 shell 兼容性:: 

@end menu

@node shlex 对象,解析规则,,shlex —— 简单的词义分析
@anchor{library/shlex id1}@anchor{3171}@anchor{library/shlex shlex-objects}@anchor{3172}
@subsubsection shlex 对象


@ref{67b,,shlex} 实例具备以下方法：

@geindex get_token() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex get_token}@anchor{3173}
@deffn {方法} shlex.get_token ()

返回一个单词。如果所有单词已用 @ref{3174,,push_token()} 堆叠在一起了，则从堆中弹出一个单词。否则就从输入流中读取一个。如果读取时遇到文件结束符，则会返回 @code{eof`（在非 POSIX 模式下为空字符串 `}'@w{'}@code{，在 POSIX 模式下为 `@w{`}None}）。
@end deffn

@geindex push_token() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex push_token}@anchor{3174}
@deffn {方法} shlex.push_token (str)

将参数值压入单词堆栈。
@end deffn

@geindex read_token() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex read_token}@anchor{3175}
@deffn {方法} shlex.read_token ()

读取一个原单词。忽略堆栈，且不解释源请求。（通常没什么用，只是为了完整起见。）
@end deffn

@geindex sourcehook() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex sourcehook}@anchor{3176}
@deffn {方法} shlex.sourcehook (filename)

当 @ref{67b,,shlex} 检测到源请求（见下面的 @ref{3177,,source}），本方法被赋予以下单词作为参数，并应返回一个由文件名和打开的文件对象组成的元组。

通常本方法会先移除参数中的引号。如果结果为绝对路径名，或者之前没有有效的源请求，或者之前的源请求是一个流对象（比如 @code{sys.stdin}），那么结果将不做处理。否则，如果结果是相对路径名，那么前面将会加上目录部分，目录名来自于源堆栈中前一个文件名（类似于 C 预处理器对 @code{#include "file.h"} 的处理方式）。

结果被视为一个文件名，并作为元组的第一部分返回，元组的第二部分以此为基础调用 @ref{16f,,open()} 获得。（注意：这与实例初始化中的参数顺序相反！)

此钩子函数是公开的，可用于实现路径搜索、添加文件扩展名或黑入其他命名空间。没有对应的“关闭”钩子函数，但 shlex 实例在返回 EOF 时会调用源输入流的 @ref{1190,,close()} 方法。

若要更明确地控制源堆栈，请采用 @ref{3178,,push_source()} 和 @ref{3179,,pop_source()} 方法。
@end deffn

@geindex push_source() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex push_source}@anchor{3178}
@deffn {方法} shlex.push_source (newstream, newfile=None)

将输入源流压入输入堆栈。如果指定了文件名参数，以后错误信息中将会用到。这与 @ref{3176,,sourcehook()} 内部使用的方法相同。
@end deffn

@geindex pop_source() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex pop_source}@anchor{3179}
@deffn {方法} shlex.pop_source ()

从输入堆栈中弹出最后一条输入源。当遇到输入流的 EOF 时，内部也使用同一方法。
@end deffn

@geindex error_leader() (shlex.shlex 方法)
@anchor{library/shlex shlex shlex error_leader}@anchor{317a}
@deffn {方法} shlex.error_leader (infile=None, lineno=None)

本方法生成一条错误信息的首部，以 Unix C 编译器错误标签的形式；格式为`@w{`}'"%s", line %d: '@code{，其中 `@w{`}%s} 被替换为当前源文件的名称，@code{%d} 被替换为当前输入行号（可用可选参数覆盖）。

这是个快捷函数，旨在鼓励 @ref{e8,,shlex} 用户以标准的、可解析的格式生成错误信息，以便 Emacs 和其他 Unix 工具理解。
@end deffn

@ref{67b,,shlex} 子类的实例有一些公共实例变量，这些变量可以控制词义分析，也可用于调试。

@geindex commenters (shlex.shlex 属性)
@anchor{library/shlex shlex shlex commenters}@anchor{316e}
@deffn {属性} shlex.commenters

将被视为注释起始字符串。从注释起始字符串到行尾的所有字符都将被忽略。默认情况下只包括 @code{'#'}。
@end deffn

@geindex wordchars (shlex.shlex 属性)
@anchor{library/shlex shlex shlex wordchars}@anchor{3170}
@deffn {属性} shlex.wordchars

可连成多字符单词的字符串。默认包含所有 ASCII 字母数字和下划线。在 POSIX 模式下，Latin-1 字符集的重音字符也被包括在内。如果  @ref{1122,,punctuation_chars} 不为空，则可出现在文件名规范和命令行参数中的 @code{~-./*?=} 字符也将包含在内，任何 @code{punctuation_chars} 中的字符将从 @code{wordchars} 中移除。如果 @ref{317b,,whitespace_split} 设为 @code{True}，则本规则无效。
@end deffn

@geindex whitespace (shlex.shlex 属性)
@anchor{library/shlex shlex shlex whitespace}@anchor{317c}
@deffn {属性} shlex.whitespace

将被视为空白符并跳过的字符。空白符是单词的边界。默认包含空格、制表符、换行符和回车符。
@end deffn

@geindex escape (shlex.shlex 属性)
@anchor{library/shlex shlex shlex escape}@anchor{317d}
@deffn {属性} shlex.escape

将视为转义字符。仅适用于 POSIX 模式，默认只包含 @code{'\'}。
@end deffn

@geindex quotes (shlex.shlex 属性)
@anchor{library/shlex shlex shlex quotes}@anchor{317e}
@deffn {属性} shlex.quotes

将视为引号的字符。单词中的字符将会累至再次遇到同样的引号（因此，不同的引号会像在 shell 中一样相互包含。）默认包含 ASCII 单引号和双引号。
@end deffn

@geindex escapedquotes (shlex.shlex 属性)
@anchor{library/shlex shlex shlex escapedquotes}@anchor{317f}
@deffn {属性} shlex.escapedquotes

@ref{317e,,quotes} 中的字符将会解析 @ref{317d,,escape} 定义的转义字符。这只在 POSIX 模式下使用，默认只包含 @code{'"'}。
@end deffn

@geindex whitespace_split (shlex.shlex 属性)
@anchor{library/shlex shlex shlex whitespace_split}@anchor{317b}
@deffn {属性} shlex.whitespace_split

若为 @code{True}，则只根据空白符拆分单词。这很有用，比如用 @ref{67b,,shlex} 解析命令行，用类似 shell 参数的方式读取各个单词。当与 @ref{1122,,punctuation_chars} 一起使用时，将根据空白符和这些字符拆分单词。


在 3.8 版更改: @ref{1122,,punctuation_chars} 属性已与 @ref{317b,,whitespace_split} 属性兼容。

@end deffn

@geindex infile (shlex.shlex 属性)
@anchor{library/shlex shlex shlex infile}@anchor{316f}
@deffn {属性} shlex.infile

当前输入的文件名，可能是在类实例化时设置的，或者是由后来的源请求堆栈生成的。在构建错误信息时可能会用到本属性。
@end deffn

@geindex instream (shlex.shlex 属性)
@anchor{library/shlex shlex shlex instream}@anchor{3180}
@deffn {属性} shlex.instream

@ref{67b,,shlex} 实例正从中读取字符的输入流。
@end deffn

@geindex source (shlex.shlex 属性)
@anchor{library/shlex shlex shlex source}@anchor{3177}
@deffn {属性} shlex.source

本属性默认值为 @code{None}。 如果给定一个字符串，则会识别为包含请求，类似于各种 shell 中的 @code{source} 关键字。 也就是说，紧随其后的单词将作为文件名打开，作为输入流，直至遇到 EOF 后调用流的 @ref{1190,,close()} 方法，然后原输入流仍变回输入源。Source 请求可以在词义堆栈中嵌套任意深度。
@end deffn

@geindex debug (shlex.shlex 属性)
@anchor{library/shlex shlex shlex debug}@anchor{3181}
@deffn {属性} shlex.debug

如果本属性为大于 @code{1} 的数字，则 @ref{67b,,shlex} 实例会把动作进度详细地输出出来。若需用到本属性，可阅读源代码来了解细节。
@end deffn

@geindex lineno (shlex.shlex 属性)
@anchor{library/shlex shlex shlex lineno}@anchor{3182}
@deffn {属性} shlex.lineno

源的行数（到目前为止读到的换行符数量加 1）。
@end deffn

@geindex token (shlex.shlex 属性)
@anchor{library/shlex shlex shlex token}@anchor{3183}
@deffn {属性} shlex.token

单词缓冲区。在捕获异常时可能会用到。
@end deffn

@geindex eof (shlex.shlex 属性)
@anchor{library/shlex shlex shlex eof}@anchor{3184}
@deffn {属性} shlex.eof

用于确定文件结束的单词。在非 POSIX 模式下，将设为空字符串 @code{'@w{'}}，在 POSIX 模式下被设为 @code{None}。
@end deffn

@geindex punctuation_chars (shlex.shlex 属性)
@anchor{library/shlex shlex shlex punctuation_chars}@anchor{1122}
@deffn {属性} shlex.punctuation_chars

只读属性。表示应视作标点符号的字符。标点符号将作为单个单词返回。然而，请注意不会进行语义有效性检查：比如 “>>>” 可能会作为一个单词返回，虽然 shell 可能无法识别。


3.6 新版功能.

@end deffn

@node 解析规则,改进的 shell 兼容性,shlex 对象,shlex —— 简单的词义分析
@anchor{library/shlex parsing-rules}@anchor{3185}@anchor{library/shlex shlex-parsing-rules}@anchor{3186}
@subsubsection 解析规则


在非 POSIX 模式下时，@ref{67b,,shlex} 会试图遵守以下规则：


@itemize *

@item 
不识别单词中的引号（@code{Do"Not"Separate} 解析为一个单词 @code{Do"Not"Separate}）。

@item 
不识别转义字符；

@item 
引号包裹的字符保留字面意思。

@item 
成对的引号会将单词分离（@code{"Do"Separate} 解析为 @code{"Do"} 和 @code{Separate}）。

@item 
如果 @ref{317b,,whitespace_split} 为 @code{False}，则未声明为单词字符、空白或引号的字符将作为单字符标记返回。若为 @code{True}， 则 @ref{67b,,shlex} 只根据空白符拆分单词。

@item 
EOF 用空字符串（@code{'@w{'}}）表示；

@item 
空字符串无法解析，即便是加了引号。
@end itemize

在 POSIX 模式时，@ref{67b,,shlex} 将尝试遵守以下解析规则：


@itemize *

@item 
引号会被剔除，且不会拆分单词（ @code{"Do"Not"Separate"} 将解析为单个单词 @code{DoNotSeparate}）。

@item 
未加引号包裹的转义字符（如 @code{'\'} ）保留后一个字符的字面意思；

@item 
引号中的字符不属于 @ref{317f,,escapedquotes} （例如，@code{"'"}），则保留引号中所有字符的字面值。

@item 
若引号包裹的字符属于 @ref{317f,,escapedquotes} （例如 @code{'"'}），则保留引号中所有字符的字面意思，属于 @ref{317d,,escape} 中的字符除外。仅当后跟后半个引号或转义字符本身时，转义字符才保留其特殊含义。否则，转义字符将视作普通字符。

@item 
EOF 用 @ref{204,,None} 表示。

@item 
允许出现引号包裹的空字符串（@code{'@w{'}}）。
@end itemize

@node 改进的 shell 兼容性,,解析规则,shlex —— 简单的词义分析
@anchor{library/shlex improved-compatibility-with-shells}@anchor{3187}@anchor{library/shlex improved-shell-compatibility}@anchor{67c}
@subsubsection 改进的 shell 兼容性



3.6 新版功能.


@ref{e8,,shlex} 类提供了与常见 Unix shell（如 @code{bash}、@code{dash} 和`@w{`}sh`@w{`}）的解析兼容性。为了充分利用这种兼容性，请在构造函数中设定 @code{punctuation_chars} 参数。该参数默认为 @code{False}，维持 3.6 以下版本的行为。如果设为 @code{True}，则会改变对 @code{();<>|&} 字符的解析方式：这些字符都将视为单个标记返回。虽然不算是完整的 shell 解析程序（考虑到 shell 的多样性，超出了标准库的范围），但确实能比其他方式更容易进行命令行的处理。以下代码段演示了两者的差异：

@example
 >>> import shlex
 >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")"
 >>> s = shlex.shlex(text, posix=True)
 >>> s.whitespace_split = True
 >>> list(s)
 ['a', '&&', 'b;', 'c', '&&', 'd', '||', 'e;', 'f', '>abc;', '(def', 'ghi)']
 >>> s = shlex.shlex(text, posix=True, punctuation_chars=True)
 >>> s.whitespace_split = True
 >>> list(s)
 ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', 'abc', ';',
 '(', 'def', 'ghi', ')']
@end example

当然，返回的词法单元对 shell 无效，需要对返回的词法单元自行进行错误检查。

punctuation_chars 参数可以不传入 @code{True} ，而是传入包含特定字符的字符串，用于确定由哪些字符构成标点符号。例如：

@example
>>> import shlex
>>> s = shlex.shlex("a && b || c", punctuation_chars="|")
>>> list(s)
['a', '&', '&', 'b', '||', 'c']
@end example

@cartouche
@quotation 注解 
如果指定了 @code{punctuation_chars}，则 @ref{3170,,wordchars} 属性的参数会是 @code{~-./*?=}。因为这些字符可以出现在文件名（包括通配符）和命令行参数中（如 @code{--color=auto}）。因此：

@example
>>> import shlex
>>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
...                 punctuation_chars=True)
>>> list(s)
['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']
@end example

不过为了尽可能接近于 shell ，建议在使用  @ref{1122,,punctuation_chars}  时始终使用 @code{posix} 和 @ref{317b,,whitespace_split} ，这将完全否定 @ref{3170,,wordchars} 。
@end quotation
@end cartouche

为了达到最佳效果，@code{punctuation_chars} 应与 @code{posix=True} 一起设置。（注意 @code{posix=False} 是 @ref{67b,,shlex} 的默认设置)。

@node Tk图形用户界面 GUI,开发工具,程序框架,Python 标准库
@anchor{library/tk doc}@anchor{3188}@anchor{library/tk graphical-user-interfaces-with-tk}@anchor{3189}@anchor{library/tk tkinter}@anchor{318a}
@section Tk图形用户界面(GUI)


@geindex GUI
@geindex Graphical User Interface
@geindex Tkinter
@geindex Tk

Tcl/Tk集成到Python中已经有一些年头了。Python程序员可以通过 @ref{10e,,tkinter} 包和它的扩展， @ref{117,,tkinter.tix} 模块和 @ref{118,,tkinter.ttk} 模块，来使用这套鲁棒的、平台无关的窗口工具集。

@ref{10e,,tkinter} 包是使用面向对象方式对 Tcl/Tk 进行的一层薄包装。 使用 @ref{10e,,tkinter}，你不需要写 Tcl 代码，但你将需要参阅 Tk 文档，有时还需要参阅 Tcl 文档。 @ref{10e,,tkinter} 是一组包装器，它将 Tk 的可视化部件实现为相应的 Python 类。

@ref{10e,,tkinter} 的主要特点是速度很快，并且通常直接附带在 Python 中。 虽然它的官方文档做得不好，但还是有许多可用的资源，包括：在线参考、教程、入门书等等。 @ref{10e,,tkinter} 还有众所周知的较过时的外观界面，这在 Tk 8.5 中已得到很大改进。 无论如何，你还可以考虑许多其他的 GUI 库。 Python wiki 例出了一些替代性的 GUI 框架和工具@footnote{https://wiki.python.org/moin/GuiProgramming}。

@menu
* tkinter: tkinter --- Tcl/Tk的Python接口. Tcl/Tk的Python接口
* tkinter.colorchooser: tkinter colorchooser --- 颜色选择对话框. 颜色选择对话框
* tkinter.font: tkinter font --- Tkinter 字体封装. Tkinter 字体封装
* Tkinter 对话框:: 
* tkinter.messagebox: tkinter messagebox --- Tkinter 消息提示. Tkinter 消息提示
* tkinter.scrolledtext: tkinter scrolledtext --- 滚动文字控件. 滚动文字控件
* tkinter.dnd: tkinter dnd --- 拖放操作支持. 拖放操作支持
* tkinter.ttk: tkinter ttk --- Tk主题部件. Tk主题部件
* tkinter.tix: tkinter tix --- TK扩展包. TK扩展包
* IDLE: IDLE<52>. 

@end menu

@node tkinter --- Tcl/Tk的Python接口,tkinter colorchooser --- 颜色选择对话框,,Tk图形用户界面 GUI
@anchor{library/tkinter doc}@anchor{318b}@anchor{library/tkinter module-tkinter}@anchor{10e}@anchor{library/tkinter tkinter-python-interface-to-tcl-tk}@anchor{318c}
@subsection @code{tkinter} --- Tcl/Tk的Python接口


@geindex tkinter (模块)

@strong{源代码:} Lib/tkinter/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/__init__.py}


__________________________________________________________________


@ref{10e,,tkinter} 包 ("Tk 接口") 是针对 Tcl/Tk GUI 工具包的标准 Python 接口。 Tk 和 @ref{10e,,tkinter} 在大多数 Unix 平台，包括 macOS，以及 Windows 系统上均可使用。

在命令行中运行 @code{python -m tkinter}，应该会弹出一个Tk界面的窗口，表明 @ref{10e,,tkinter} 包已经正确安装，而且告诉你 Tcl/Tk 的版本号，通过这个版本号，你就可以参考对应的 Tcl/Tk 文档了。


@subsubheading 参见



@itemize *

@item 

@table @asis

@item TkDocs@footnote{http://tkdocs.com/}

关于使用 Tkinter 创建用户界面的详细教程。 讲解了关键概念，并介绍了使用现代 API 的推荐方式。
@end table

@item 

@table @asis

@item Tkinter 8.5 参考：一个Python图形用户界面@footnote{https://www.tkdocs.com/shipman/}

详细讲解可用的类、方法和选项的 Tkinter 8.5 参考文档。
@end table
@end itemize

Tcl/Tk 资源:


@itemize *

@item 

@table @asis

@item Tk 命令@footnote{https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm}

有关 Tkinter 所使用的每个底层 Tcl/Tk 命令的完整参考文档。
@end table

@item 

@table @asis

@item Tcl/Tk 主页@footnote{https://www.tcl.tk}

额外的文档，以及 Tcl/Tk 核心开发相关链接。
@end table
@end itemize

书籍:


@itemize *

@item 

@table @asis

@item Modern Tkinter for Busy Python Developers@footnote{https://tkdocs.com/book.html}

Mark Roseman 著。 (ISBN 978-1999149567)
@end table

@item 

@table @asis

@item Python and Tkinter Programming@footnote{https://www.packtpub.com/product/python-gui-programming-with-tkinter/9781788835886}

Alan Moore 著。 (ISBN 978-1788835886)
@end table

@item 

@table @asis

@item 使用 Python 编程@footnote{http://learning-python.com/about-pp4e.html}

Mark Lutz 著；对 Tkinter 进行了精彩的讲解。 (ISBN 978-0596158101)
@end table

@item 

@table @asis

@item Tcl and the Tk Toolkit (2nd edition)@footnote{https://www.amazon.com/exec/obidos/ASIN/032133633X}

John Ousterhout ，Tcl/Tk 的创造者，与 Ken Jones 合著；未涉及 Tkinter。 (ISBN 978-0321336330)
@end table
@end itemize


@menu
* Tkinter 模块:: 
* Tkinter 拾遗:: 
* Tcl/Tk 速览:: 
* 将简单的 Tk 映射到 Tkinter:: 
* Tk 和 Tkinter 如何关联:: 
* 快速参考:: 
* 文件句柄:: 

@end menu

@node Tkinter 模块,Tkinter 拾遗,,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter tkinter-modules}@anchor{318d}
@subsubsection Tkinter 模块


对 Tkinter 的支持分布在多个模块中。 大多数应用程序将需要主模块 @ref{10e,,tkinter}，以及 @ref{118,,tkinter.ttk} 模块，后者提供了带主题的现代部件集及相应的 API:

@example
from tkinter import *
from tkinter import ttk
@end example

@geindex Tk (tkinter 中的类)
@anchor{library/tkinter tkinter Tk}@anchor{318e}
@deffn {类} tkinter.Tk (screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)

构造一个最高层级的 Tk 部件，这通常是一个应用程序的主窗口，并为这个部件初始化 Tcl 解释器。 每个实例都有其各自所关联的 Tcl 解释器。

@ref{318e,,Tk} 类通常全部使用默认值来初始化。 不过，目前还可识别下列关键字参数:


@table @asis

@item @emph{screenName}

当（作为字符串）给出时，设置 
@geindex DISPLAY
@geindex 环境变量; DISPLAY
@code{DISPLAY} 环境变量。 （仅限 X11）

@item @emph{baseName}

预置文件的名称。 在默认情况下，@emph{baseName} 是来自于程序名称 (@code{sys.argv[0]})。

@item @emph{className}

控件类的名称。 会被用作预置文件同时也作为 Tcl 发起调用的名称 (@emph{interp} 中的 @emph{argv0})。

@item @emph{useTk}

如果为 @code{True}，则初始化 Tk 子系统。 @ref{318f,,tkinter.Tcl()} 函数会将其设为 @code{False}。

@item @emph{sync}

如果为 @code{True}，则同步执行所有 X 服务器命令，以便立即报告错误。 可被用于调试。 （仅限 X11）

@item @emph{use}

指定嵌入应用程序的窗口 @emph{id}，而不是将其创建为独立的顶层窗口。 @emph{id} 必须以与顶层控件的 -use 选项值相同的方式来指定（也就是说，它具有与 @code{winfo_id()} 的返回值相同的形式）。

请注意在某些平台上只有当 @emph{id} 是指向一个启用了 -container 选项的 Tk 框架或顶层窗口时此参数才能正确生效。
@end table

@ref{318e,,Tk} 读取并解释预置文件，其名称为 @code{.@emph{className}.tcl} 和 @code{.@emph{baseName}.tcl}，进入 Tcl 解释器并基于 @code{.@emph{className}.py} 在 @code{.@emph{baseName}.py} 的内容调用 @ref{d14,,exec()}。 预置文件的路径为 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} 环境变量，或者如果它未被设置，则为 @ref{1d97,,os.curdir}。

@geindex tk (tkinter.Tk 属性)
@anchor{library/tkinter tkinter Tk tk}@anchor{3190}
@deffn {属性} tk

通过实例化 @ref{318e,,Tk} 创建的 Tk 应用程序对象。 这提供了对 Tcl 解释器的访问。 每个被附加到相同 @ref{318e,,Tk} 实例的控件都具有相同的 @ref{3190,,tk} 属性值。
@end deffn

@geindex master (tkinter.Tk 属性)
@anchor{library/tkinter tkinter Tk master}@anchor{3191}
@deffn {属性} master

包含此控件的控件对象。 对于 @ref{318e,,Tk}，@emph{master} 将为 @ref{204,,None} 因为它是主窗口。 术语 @emph{master} 和 @emph{parent} 是类似的且有时作为参数名称被交替使用；但是，调用 @code{winfo_parent()} 将返回控件名称字符串而 @ref{3191,,master} 将返回控件对象。 @emph{parent}/@emph{child} 反映了树型关系而 @emph{master}/@emph{slave} 反映了容器结构。
@end deffn

@geindex children (tkinter.Tk 属性)
@anchor{library/tkinter tkinter Tk children}@anchor{3192}
@deffn {属性} children

以 @ref{164,,dict} 表示的此控件的直接下级其中的键为子控件名称而值为子实例对象。
@end deffn
@end deffn

@geindex Tcl() (在 tkinter 模块中)
@anchor{library/tkinter tkinter Tcl}@anchor{318f}
@deffn {函数} tkinter.Tcl (screenName=None, baseName=None, className='Tk', useTk=False)

@ref{318f,,Tcl()} 函数是一个工厂函数，它创建的对象与 @ref{318e,,Tk} 类创建的对象非常相似，只是它不初始化 Tk 子系统。 在不想创建或无法创建（如没有 X Server 的 Unix/Linux 系统）额外的顶层窗口的环境中驱动 Tcl 解释器时，这一点非常有用。 由 @ref{318f,,Tcl()} 对象创建的对象可以通过调用其 @code{loadtk()} 方法来创建顶层窗口（并初始化 Tk 子系统）。
@end deffn

提供 Tk 支持的模块包括:


@table @asis

@item @ref{10e,,tkinter}

主 Tkinter 模块。

@item @ref{10f,,tkinter.colorchooser}

让用户选择颜色的对话框。

@item @ref{110,,tkinter.commondialog}

在此处列出的其他模块中定义的对话框的基类。

@item @ref{112,,tkinter.filedialog}

允许用户指定文件的通用对话框，用于打开或保存文件。

@item @ref{113,,tkinter.font}

帮助操作字体的工具。

@item @ref{114,,tkinter.messagebox}

访问标准的 Tk 对话框。

@item @ref{115,,tkinter.scrolledtext}

内置纵向滚动条的文本组件。

@item @ref{116,,tkinter.simpledialog}

基础对话框和便捷功能。

@item @ref{118,,tkinter.ttk}

在 Tk 8.5 中引入的带主题的控件集，提供了对应于 @ref{10e,,tkinter} 模块中许多经典控件的现代替代。
@end table

附加模块:


@table @asis

@item @code{_tkinter}

一个包含低层级 Tcl/Tk 接口的二进制模块。 它会被主 @ref{10e,,tkinter} 模块自动导入，且永远不应被应用程序员所直接使用。 它通常是一个共享库（或 DLL），但在某些情况下可能被动态链接到 Python 解释器。

@item @code{idlelib}

Python 的集成开发与学习环境（IDLE）。 基于 @ref{10e,,tkinter}。

@item @code{tkinter.constants}

当向 Tkinter 调用传入各种形参时可被用来代替字符串的符号常量。 由主 @ref{10e,,tkinter} 模块自动导入。

@item @ref{111,,tkinter.dnd}

针对 @ref{10e,,tkinter} 的（实验性的）拖放支持。 当以 Tk DND 代替时它将会被弃用。

@item @ref{117,,tkinter.tix}

（已弃用）一个增加了部分新控件的较老的第三方 Tcl/Tk 包。 对多数人来说可以在 @ref{118,,tkinter.ttk} 中找到更好的替代品。

@item @ref{11f,,turtle}

Tk 窗口中的海龟绘图库。
@end table

@node Tkinter 拾遗,Tcl/Tk 速览,Tkinter 模块,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter tkinter-life-preserver}@anchor{3193}
@subsubsection Tkinter 拾遗


本节不应作为 Tk 或 Tkinter 的详尽教程。而只是一个补充，提供一些系统指南。

致谢：


@itemize *

@item 
Tk 是 John Ousterhout 在伯克利大学时写的。

@item 
Tkinter 是由 Steen Lumholt 和 Guido van Rossum 编写的。

@item 
本拾遗由弗吉尼亚大学的 Matt Conway 撰写。

@item 
HTML 渲染和一些自由编辑功能，是由 Ken Manheimer 根据 FrameMaker 创建的。

@item 
Fredrik Lundh 认真研究并修改了类的接口描述，使其与 Tk 4.2 保持一致。

@item 
Mike Clarkson 将文档转换为 LaTeX 格式，并编写了参考手册的用户界面章节。
@end itemize

@menu
* 本节内容的用法:: 
* 简单的 Hello World 程序:: 

@end menu

@node 本节内容的用法,简单的 Hello World 程序,,Tkinter 拾遗
@anchor{library/tkinter how-to-use-this-section}@anchor{3194}
@subsubsection 本节内容的用法


本节分为两部分：前半部分（大致）涵盖了背景材料，后半部分可以作为手头的参考手册。

当试图回答“如何才能怎么怎么”这种问题时，通常最好是弄清楚如何直接在 Tk 中实现，然后转换回相应的 @ref{10e,,tkinter} 调用。Python 程序员通常可查看 Tk 文档来猜测正确的 Python 命令。这意味着要用好 Tkinter，必须对 Tk 有一定的了解。本文无法完成这个任务，所以最好的做法就是给出目前最好的文档。下面给出一些小提示：


@itemize *

@item 
作者强烈建议用户先拿到一份 Tk 手册。具体来说，@code{manN} 目录下的 man 文档是最有用的。@code{man3} 的 man 文档描述了 Tk 库的 C 接口，因此对脚本编写人员没有什么特别的帮助。

@item 
Addison-Wesley 出版了一本名为《Tcl 和 Tk 工具包》的书，作者是 John Ousterhout（ISBN 0-201-63337-X），对于新手来说，这是一本很好的 Tcl 和Tk 介绍书籍。该书不算详尽，很多细节还是要看 man 手册。

@item 
对大多数人而言，@code{tkinter/__init__.py} 是最后一招，但其他手段都无效时也不失为一个好去处。
@end itemize

@node 简单的 Hello World 程序,,本节内容的用法,Tkinter 拾遗
@anchor{library/tkinter a-simple-hello-world-program}@anchor{3195}
@subsubsection 简单的 Hello World 程序


@example
import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()
@end example

@node Tcl/Tk 速览,将简单的 Tk 映射到 Tkinter,Tkinter 拾遗,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter a-very-quick-look-at-tcl-tk}@anchor{3196}
@subsubsection Tcl/Tk 速览


类的层次结构看起来很复杂，但在实际操作中，应用程序编写人员几乎总是查看最底层的类。

注释:


@itemize *

@item 
提供这些类，是为了能在同一个命名空间下将某些功能组织在一起。并不意味着可以独立对其进行实例化。

@item 
@ref{318e,,Tk} 类在同一个应用程序中仅需作一次实例化。应用程序编程人员不需要显式进行实例化，只要有其他任何类被实例化，系统就会创建一个。

@item 
@code{Widget} 类不是用来实例化的，它仅用于继承以便生成“真正”的部件（ C++ 中称为“抽象类”）。
@end itemize

若要充分利用这些参考资料，有时需要知道如何阅读 Tk 的短文，以及如何识别 Tk 命令的各个部分。（参见 @ref{3197,,将简单的 Tk 映射到 Tkinter} 一节，了解以下内容在 @ref{10e,,tkinter} 中的对应部分）。

Tk 脚本就是 Tcl 程序。像所有其他的 Tcl 程序一样，Tk 脚本只是由空格分隔的单词列表。一个Tk 部件只是它的 @emph{class}，@emph{options} 用于进行配置，@emph{actions} 让它执行有用的动作。

要在 Tk 中制作一个部件，总是采用如下格式的命令：

@example
classCommand newPathname options
@end example


@table @asis

@item @emph{classCommand}

表示要制作何种部件（按钮、标签、菜单......）。
@end table

@geindex . (dot); in Tkinter


@table @asis

@item @emph{newPathname}

该组件的新名字。Tk 中的所有名字都必须唯一。为了帮助实现这一点，Tk 中的部件都用 @emph{路径} 命名，就像文件系统中的文件一样。顶层的部件，即 @emph{根}，名为 @code{.`@w{`}（句点），而子部件则由更多的句点分隔。比如部件名可能会是 `@w{`}.myApp.controlPanel.okButton} 。

@item @emph{options}

配置部件的外观，有时也能配置行为。这些选项以标志和值的列表形式出现。标志前带一个“-”，就像 Unix shell 命令的标志一样，如果值超过一个单词，就用引号括起来。
@end table

例如:

@example
button   .fred   -fg red -text "hi there"
   ^       ^     \______________________/
   |       |                |
 class    new            options
command  widget  (-opt val -opt val ...)
@end example

一旦创建成功，部件的路径名就成了一条新的命令。这个新的 @emph{部件命令} 是程序员让新部件执行某些 @emph{action} 的句柄。在 C 语言中可表示为someAction(fred, someOptions)，在 C++ 中可表示为fred.someAction(someOptions)，而在 Tk 中写作：

@example
.fred someAction someOptions
@end example

请注意，对象名 @code{.fred} 是以句点开头的。

如您所料，@emph{someAction} 的可用值取决于部件的类别。如果 fred 为按钮，则 @cite{.fred disable} 有效（fred 会变灰），而当 fred 为标签时则无效（Tk 不支持标签的禁用）。

@emph{someOptions} 的合法值取决于动作。有些动作不需要参数，比如 @code{disable}，其他动作如文本输入框的 @code{delete} 命令则需用参数指定要删除的文本范围。

@node 将简单的 Tk 映射到 Tkinter,Tk 和 Tkinter 如何关联,Tcl/Tk 速览,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter mapping-basic-tk-into-tkinter}@anchor{3198}@anchor{library/tkinter tkinter-basic-mapping}@anchor{3197}
@subsubsection 将简单的 Tk 映射到 Tkinter


Tk 中的类命令对应于 Tkinter 中的类构造函数：

@example
button .fred                =====>  fred = Button()
@end example

父对象是隐含在创建时给定的新名字中的。在 Tkinter 中，父对象是显式指定的：

@example
button .panel.fred          =====>  fred = Button(panel)
@end example

Tk 中的配置项是以连字符标签列表的形式给出的，后跟着参数值。在 Tkinter 中，选项指定为实例构造函数中的关键字参数，在配置调用时指定为关键字 args，或在已有实例中指定为实例索引，以字典的形式。参见 @ref{3199,,可选配置项} 一节的选项设置部分。

@example
button .fred -fg red        =====>  fred = Button(panel, fg="red")
.fred configure -fg red     =====>  fred["fg"] = red
                            OR ==>  fred.config(fg="red")
@end example

在 Tk 中, 要在某个部件上执行动作, 要用部件名作为命令, 并后面附上动作名称, 可能还会带有参数（option）。在 Tkinter 中，则调用类实例的方法来执行部件的动作。部件能够执行的动作（方法）列在 @code{tkinter/__init__.py} 中。

@example
.fred invoke                =====>  fred.invoke()
@end example

若要将部件交给打包器（geometry manager），需带上可选参数去调用 pack。在 Tkinter 中，Pack 类拥有全部这些功能，pack 命令的各种形式都以方法的形式实现。 @ref{10e,,tkinter} 中的所有部件都是从 Packer 继承而来的，因此继承了所有打包方法。关于Form geometry manager 的更多信息，请参见 @ref{117,,tkinter.tix} 模块的文档。

@example
pack .fred -side left       =====>  fred.pack(side="left")
@end example

@node Tk 和 Tkinter 如何关联,快速参考,将简单的 Tk 映射到 Tkinter,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter how-tk-and-tkinter-are-related}@anchor{319a}
@subsubsection Tk 和 Tkinter 如何关联


自上而下：


@table @asis

@item （Python）应用程序位于这里

Python 应用程序进行了 @ref{10e,,tkinter} 调用。

@item tkinter （Python 包）

此调用（比如创建一个按钮部件）在 @ref{10e,,tkinter} 包中实现，它是用 Python 编写的。该 Python 函数将解析命令和参数，并转换为貌似 Tk 脚本的格式，而不像是 Python 脚本。

@item _tkinter（C 语言）

这些命令及参数将被传给 @code{_tkinter} 扩展模块中的 C 函数——注意下划线。

@item Tk 部件（C 和 Tcl）

该 C 函数能调用其他的 C 模块，包括构成 Tk 库的 C 函数。Tk 是用 C 和一些 Tcl 实现的。Tk 部件的 Tcl 部分用于将某些默认行为绑定到部件上，并在导入 Python @ref{10e,,tkinter} 包时执行一次。（该阶段对用户而言永不可见）。

@item Tk（C 语言）

Tk 部件的 Tk 语言部分实现了最终的映射

@item Xlib（C 语言）

Xlib 库在屏幕上绘制图形。
@end table

@node 快速参考,文件句柄,Tk 和 Tkinter 如何关联,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter handy-reference}@anchor{319b}
@subsubsection 快速参考


@menu
* 可选配置项:: 
* 包装器:: 
* 包装器的参数:: 
* 部件与变量的关联:: 
* 窗口管理器:: 
* Tk 参数的数据类型:: 
* 绑定和事件:: 
* index 参数:: 
* 图片:: 

@end menu

@node 可选配置项,包装器,,快速参考
@anchor{library/tkinter setting-options}@anchor{319c}@anchor{library/tkinter tkinter-setting-options}@anchor{3199}
@subsubsection 可选配置项


配置参数可以控制组件颜色和边框宽度等。可通过三种方式进行设置：


@table @asis

@item 在对象创建时，使用关键字参数

@example
fred = Button(self, fg="red", bg="blue")
@end example

@item 在对象创建后，将参数名用作字典索引

@example
fred["fg"] = "red"
fred["bg"] = "blue"
@end example

@item 利用 config() 方法修改对象的属性

@example
fred.config(fg="red", bg="blue")
@end example
@end table

关于这些参数及其表现的完整解释，请参阅 Tk 手册中有关组件的 man 帮助页。

请注意，man 手册页列出了每个部件的“标准选项”和“组件特有选项”。前者是很多组件通用的选项列表，后者是该组件特有的选项。标准选项在  @code{options(3)} man 手册中有文档。

本文没有区分标准选项和部件特有选项。有些选项不适用于某类组件。组件是否对某选项做出响应，取决于组件的类别；按钮组件有一个 @code{command} 选项，而标签组件就没有。

组件支持的选项在其手册中有列出，也可在运行时调用 @code{config()} 方法（不带参数）查看，或者通过调用组件的 @code{keys()} 方法进行查询。这些调用的返回值为字典，字典的键是字符串格式的选项名（比如 @code{'relief'}），字典的值为五元组。

有些选项，比如 @code{bg} 是全名通用选项的同义词（@code{bg} 是 “background”的简写）。向 @code{config()} 方法传入选项的简称将返回一个二元组，而不是五元组。传回的二元组将包含同义词的全名和“真正的”选项（比如 @code{('bg', 'background')}）。


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

意义

@tab

示例

@item

0

@tab

选项名称

@tab

@code{'relief'}

@item

1

@tab

数据库查找的选项名称

@tab

@code{'relief'}

@item

2

@tab

数据库查找的选项类

@tab

@code{'Relief'}

@item

3

@tab

默认值

@tab

@code{'raised'}

@item

4

@tab

当前值

@tab

@code{'groove'}

@end multitable


示例:

@example
>>> print(fred.config())
@{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')@}
@end example

当然，输出的字典将包含所有可用选项及其值。这里只是举个例子。

@node 包装器,包装器的参数,可选配置项,快速参考
@anchor{library/tkinter the-packer}@anchor{319d}
@subsubsection 包装器


@geindex packing (widgets)

包装器是 Tk 的形状管理机制之一。 形状管理器用于指定部件在容器内的相对位置——彼此的 @emph{宿主} 关系。与更为麻烦的 @emph{定位器} 相比（不太常用，这里不做介绍），包装器可接受定性的相对关系—— @emph{上面} 、@emph{左边} 、@emph{填充} 等，并确定精确的放置坐标。

@emph{主} 部件的大小都由其内部的 “从属部件” 的大小决定。包装器用于控制从属部件在主部件中出现的位置。可以把部件包入框架，再把框架包入其他框架中，搭建出所需的布局。此外，只要完成了包装，组件的布局就会进行动态调整，以适应布局参数的变化。

请注意，只有用形状管理器指定几何形状后，部件才会显示出来。忘记设置形状参数是新手常犯的错误，惊讶于创建完部件却啥都没出现。部件只有在应用了类似于打包器的 @code{pack()} 方法之后才会显示在屏幕上。

调用 pack() 方法时可以给出由关键字/参数值组成的键值对，以便控制组件在其容器中出现的位置，以及主程序窗口大小变动时的行为。下面是一些例子：

@example
fred.pack()                     # defaults to side = "top"
fred.pack(side="left")
fred.pack(expand=1)
@end example

@node 包装器的参数,部件与变量的关联,包装器,快速参考
@anchor{library/tkinter packer-options}@anchor{319e}
@subsubsection 包装器的参数


关于包装器及其可接受的参数，更多信息请参阅 man 手册和 John Ousterhout 书中的第 183 页。


@table @asis

@item anchor

锚点类型。 表示包装器要放置的每个从属组件的位置。

@item expand

布尔型，@code{0} 或 @code{1} 。

@item fill

合法值为：@code{'x'} 、@code{'y'} 、@code{'both'} 、@code{'none'}。

@item ipadx 和 ipady

距离值，指定从属部件每一侧的内边距。

@item padx 和 pady

距离值，指定从属部件的外边距。

@item side

合法值为：@code{'left'}、 @code{'right'} 、 @code{'top'}、 @code{'bottom'}。
@end table

@node 部件与变量的关联,窗口管理器,包装器的参数,快速参考
@anchor{library/tkinter coupling-widget-variables}@anchor{319f}
@subsubsection 部件与变量的关联


通过一些特定参数，某些组件（如文本输入组件）的当前设置可直接与应用程序的变量关联。这些参数包括 @code{variable} 、 @code{textvariable} 、 @code{onvalue} 、 @code{offvalue}  、 @code{value}。这种关联是双向的：只要这些变量因任何原因发生变化，其关联的部件就会更新以反映新的参数值。

不幸的是，在目前 @ref{10e,,tkinter} 的实现代码中，不可能通过 @code{variable} 或 @code{textvariable} 参数将任意 Python 变量移交给组件。变量只有是 @ref{10e,,tkinter} 中定义的 Variable 类的子类，才能生效。

已经定义了很多有用的 Variable 子类： @code{StringVar} 、 @code{IntVar} 、@code{DoubleVar} 和 @code{BooleanVar}。调用 @code{get()} 方法可以读取这些变量的当前值；调用 @code{set()} 方法则可改变变量值。只要遵循这种用法，组件就会保持跟踪变量的值，而不需要更多的干预。

例如:

@example
import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pack()

        self.entrythingy = tk.Entry()
        self.entrythingy.pack()

        # Create the application variable.
        self.contents = tk.StringVar()
        # Set it to some value.
        self.contents.set("this is a variable")
        # Tell the entry widget to watch this variable.
        self.entrythingy["textvariable"] = self.contents

        # Define a callback for when the user hits return.
        # It prints the current value of the variable.
        self.entrythingy.bind('<Key-Return>',
                             self.print_contents)

    def print_contents(self, event):
        print("Hi. The current entry content is:",
              self.contents.get())

root = tk.Tk()
myapp = App(root)
myapp.mainloop()
@end example

@node 窗口管理器,Tk 参数的数据类型,部件与变量的关联,快速参考
@anchor{library/tkinter the-window-manager}@anchor{31a0}
@subsubsection 窗口管理器


@geindex window manager (widgets)

Tk 有个实用命令 @code{wm}，用于与窗口管理器进行交互。@code{wm} 命令的参数可用于控制标题、位置、图标之类的东西。在 @ref{10e,,tkinter} 中，这些命令已被实现为 @code{Wm} 类的方法。顶层部件是 @code{Wm} 类的子类，所以可以直接调用 @code{Wm} 的这些方法。

要获得指定部件所在的顶层窗口，通常只要引用该部件的主窗口即可。当然，如果该部件是包装在框架内的，那么主窗口不代表就是顶层窗口。为了获得任意组件所在的顶层窗口，可以调用 @code{_root()} 方法。该方法以下划线开头，表明其为 Python 实现的代码，而非 Tk 提供的某个接口。

以下是一些典型用法：

@example
import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

# create the application
myapp = App()

#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)

# start the program
myapp.mainloop()
@end example

@node Tk 参数的数据类型,绑定和事件,窗口管理器,快速参考
@anchor{library/tkinter tk-option-data-types}@anchor{31a1}
@subsubsection Tk 参数的数据类型


@geindex Tk Option Data Types


@table @asis

@item anchor

合法值是罗盘的方位点：@code{"n"} 、@code{"ne"} 、@code{"e"} 、@code{"se"} 、@code{"s"} 、@code{"sw"} 、@code{"w"} 、@code{"nw"}  和 @code{"center"}

@item 位图

内置已命名的位图有八个：@code{'error'}、 @code{'gray25'} 、@code{'gray50'} 、@code{'hourglass'}、 @code{'info'} 、@code{'questhead'} 、@code{'question'} 、@code{'warning'} 。若要指定位图的文件名，请给出完整路径，前面加一个 @code{@@}，比如 @code{"@@/usr/contrib/bitmap/gumby.bit"}。

@item 布尔值

可以传入整数 0 或 1，或是字符串 @code{"yes"} 或 @code{"no"}。

@item callback -- 回调

指任何无需调用参数的 Python 函数。 例如：

@example
def print_it():
    print("hi there")
fred["command"] = print_it
@end example

@item color

可在 rgb.txt 文件中以颜色名的形式给出，或是 RGB 字符串的形式，4 位 ：@code{"#RGB"} ，8 位 ：@code{"#RRGGBB"}，12 位：@code{"#RRRGGGBBB"}，16 位：@code{"#RRRRGGGGBBBB"}，其中R、G、B 为合法的十六进制数值。 详见 Ousterhout 书中的第 160 页。

@item cursor

可采用 @code{cursorfont.h} 中的标准光标名称，去掉 @code{XC_} 前缀。 比如要获取一个手形光标（@code{XC_hand2}），可以用字符串 @code{"hand2"}。也可以指定自己的位图和掩码文件作为光标。参见 Ousterhout 书中的第 179 页。

@item distance

屏幕距离可以用像素或绝对距离来指定。像素是数字，绝对距离是字符串，后面的字符表示单位：@code{c} 是厘米，@code{i} 是英寸，@code{m} 是毫米，@code{p} 则表示打印机的点数。例如，3.5 英寸可表示为 @code{"3.5i"}。

@item font

Tk 采用一串名称的格式表示字体，例如 @code{@{courier 10 bold@}}。正数的字体大小以点为单位，负数的大小以像素为单位。

@item geometry

这是一个 @code{widthxheight} 形式的字符串，其中宽度和高度对于大多数部件来说是以像素为单位的（对于显示文本的部件来说是以字符为单位的）。例如：fred["geometry"] = "200x100"。

@item justify

合法的值为字符串： @code{"left"} 、 @code{"center"} 、 @code{"right"} 和 @code{"fill"} 。

@item region

这是包含四个元素的字符串，以空格分隔，每个元素是表示一个合法的距离值（见上文）。例如：@code{"2 3 4 5"} 、 @code{"3i 2i 4.5i 2i"} 和 @code{"3c 2c 4c 10.43c"} 都是合法的区域值。

@item relief

决定了组件的边框样式。 合法值包括：@code{"raised"}、 @code{"sunken"} 、@code{"flat"} 、@code{"groove"}  和 @code{"ridge"} 。

@item scrollcommand

这几乎就是带滚动条部件的 @code{set()} 方法，但也可是任一只有一个参数的部件方法。

@item wrap

只能是以下值之一：@code{"none"} 、 @code{"char"} 、 @code{"word"}。
@end table

@node 绑定和事件,index 参数,Tk 参数的数据类型,快速参考
@anchor{library/tkinter bindings-and-events}@anchor{31a2}@anchor{library/tkinter id1}@anchor{31a3}
@subsubsection 绑定和事件


@geindex bind (widgets)
@geindex events (widgets)

部件命令中的 bind 方法可觉察某些事件，并在事件发生时触发一个回调函数。bind  方法的形式是：

@example
def bind(self, sequence, func, add='@w{'}):
@end example

这里：


@table @asis

@item 序列

是一个表示事件的目标种类的字符串。（详情请看 bind 的手册页和 John Outsterhout 的书的第 201 页。）

@item func

是带有一个参数的 Python 函数，发生事件时将会调用。传入的参数为一个 Event 实例。（以这种方式部署的函数通常称为 @emph{回调函数}。）

@item add

可选项， @code{'@w{'}} 或 @code{'+'} 。传入空字符串表示本次绑定将替换与此事件关联的其他所有绑定。传递 @code{'+'} 则意味着加入此事件类型已绑定函数的列表中。
@end table

例如:

@example
def turn_red(self, event):
    event.widget["activeforeground"] = "red"

self.button.bind("<Enter>", self.turn_red)
@end example

请注意，在 @code{turn_red()} 回调函数中如何访问事件的 widget 字段。该字段包含了捕获 X 事件的控件。下表列出了事件可供访问的其他字段，及其在 Tk 中的表示方式，这在查看 Tk 手册时很有用处。


@multitable {xxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Tk

@tab

Tkinter 事件字段

@tab

Tk

@tab

Tkinter 事件字段

@item

%f

@tab

焦点

@tab

%A

@tab

字符

@item

%h

@tab

height

@tab

%E

@tab

send_event

@item

%k

@tab

keycode

@tab

%K

@tab

keysym

@item

%s

@tab

状况

@tab

%N

@tab

keysym_num

@item

%t

@tab

time

@tab

%T

@tab

类型

@item

%w

@tab

宽度

@tab

%W

@tab

widget

@item

%x

@tab

x

@tab

%X

@tab

x_root

@item

%y

@tab

y

@tab

%Y

@tab

y_root

@end multitable


@node index 参数,图片,绑定和事件,快速参考
@anchor{library/tkinter the-index-parameter}@anchor{31a4}
@subsubsection index 参数


很多控件都需要传入 index 参数。该参数用于指明 Text 控件中的位置，或指明 Entry 控件中的字符，或指明 Menu 控件中的菜单项。


@table @asis

@item Entry 控件的索引（index、view index 等）

Entry 控件带有 index 属性，指向显示文本中的字符位置。这些 @ref{10e,,tkinter}  函数可用于访问文本控件中的这些特定位置：

@item Text 控件的索引

Text 控件的索引语法非常复杂，最好还是在 Tk 手册中查看。

@item Menu 索引（menu.invoke()、menu.entryconfig() 等）

菜单的某些属性和方法可以操纵特定的菜单项。只要属性或参数需要用到菜单索引，就可用以下方式传入：


@itemize *

@item 
一个整数，指的是控件项的数字位置，从顶部开始计数，从 0 开始；

@item 
字符串 @code{"active"}，指的是当前光标所在的菜单；

@item 
字符串 @code{"last"}，指的是上一个菜单项；

@item 
带有 @code{@@} 前缀的整数，比如 @code{@@6}，这里的整数解释为菜单坐标系中的 y 像素坐标。

@item 
表示没有任何菜单条目的字符串 @code{"none"} 经常与 menu.activate() 一同被用来停用所有条目，以及

@item 
与菜单项的文本标签进行模式匹配的文本串，从菜单顶部扫描到底部。请注意，此索引类型是在其他所有索引类型之后才会考虑的，这意味着文本标签为 @code{last}、@code{active} 或 @code{none}  的菜单项匹配成功后，可能会视为这些单词文字本身。
@end itemize
@end table

@node 图片,,index 参数,快速参考
@anchor{library/tkinter images}@anchor{31a5}
@subsubsection 图片


通过 @code{tkinter.Image} 的各种子类可以创建相应格式的图片：


@itemize *

@item 
@code{BitmapImage} 对应 XBM 格式的图片。

@item 
@code{PhotoImage} 对应 PGM、PPM、GIF 和 PNG 格式的图片。后者自 Tk 8.6 开始支持。
@end itemize

这两种图片可通过 @code{file} 或 @code{data} 属性创建的（也可能由其他属性创建）。

然后可在某些支持 @code{image} 属性的控件中（如标签、按钮、菜单）使用图片对象。这时，Tk 不会保留对图片对象的引用。当图片对象的最后一个 Python 引用被删除时，图片数据也会删除，并且 Tk 会在用到图片对象的地方显示一个空白框。


@subsubheading 参见


Pillow@footnote{http://python-pillow.org/} 包增加了对 BMP、JPEG、TIFF 和 WebP 等格式的支持。


@node 文件句柄,,快速参考,tkinter --- Tcl/Tk的Python接口
@anchor{library/tkinter file-handlers}@anchor{31a6}@anchor{library/tkinter tkinter-file-handlers}@anchor{31a7}
@subsubsection 文件句柄


Tk 允许为文件操作注册和注销一个回调函数，当对文件描述符进行 I/O 时，Tk 的主循环会调用该回调函数。每个文件描述符只能注册一个处理程序。示例代码如下：

@example
import tkinter
widget = tkinter.Tk()
mask = tkinter.READABLE | tkinter.WRITABLE
widget.tk.createfilehandler(file, mask, callback)
...
widget.tk.deletefilehandler(file)
@end example

在 Windows 系统中不可用。

由于不知道可读取多少字节，你可能不希望使用 @ref{689,,BufferedIOBase} 或 @ref{d09,,TextIOBase} 的 @ref{1eff,,read()} 或 @ref{1883,,readline()} 方法，因为这些方法必须读取预定数量的字节。 对于套接字，可使用 @ref{774,,recv()} 或 @ref{775,,recvfrom()} 方法；对于其他文件，可使用原始读取方法或 @code{os.read(file.fileno(), maxbytecount)}。

@geindex createfilehandler() (tkinter.Widget.tk 方法)
@anchor{library/tkinter tkinter Widget tk createfilehandler}@anchor{31a8}
@deffn {方法} Widget.tk.createfilehandler (file, mask, func)

注册文件处理程序的回调函数 @emph{func}。 @emph{file} 参数可以是具备 @ref{209a,,fileno()} 方法的对象（例如文件或套接字对象），也可以是整数文件描述符。 @emph{mask} 参数是下述三个常量的逻辑“或”组合。回调函数将用以下格式调用：

@example
callback(file, mask)
@end example
@end deffn

@geindex deletefilehandler() (tkinter.Widget.tk 方法)
@anchor{library/tkinter tkinter Widget tk deletefilehandler}@anchor{31a9}
@deffn {方法} Widget.tk.deletefilehandler (file)

注销文件处理函数。
@end deffn

@geindex READABLE() (在 tkinter 模块中)
@geindex WRITABLE() (在 tkinter 模块中)
@geindex EXCEPTION() (在 tkinter 模块中)
@anchor{library/tkinter tkinter READABLE}@anchor{31aa}
@deffn {数据} tkinter.READABLE
@anchor{library/tkinter tkinter WRITABLE}@anchor{31ab}
@deffnx {数据} tkinter.WRITABLE
@anchor{library/tkinter tkinter EXCEPTION}@anchor{31ac}
@deffnx {数据} tkinter.EXCEPTION

Constants used in the @emph{mask} arguments.
@end deffn

@node tkinter colorchooser --- 颜色选择对话框,tkinter font --- Tkinter 字体封装,tkinter --- Tcl/Tk的Python接口,Tk图形用户界面 GUI
@anchor{library/tkinter colorchooser doc}@anchor{31ad}@anchor{library/tkinter colorchooser module-tkinter colorchooser}@anchor{10f}@anchor{library/tkinter colorchooser tkinter-colorchooser-color-choosing-dialog}@anchor{31ae}
@subsection @code{tkinter.colorchooser} --- 颜色选择对话框


@geindex tkinter.colorchooser (模块)

@strong{源代码:} Lib/tkinter/colorchooser.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/colorchooser.py}


__________________________________________________________________


@ref{10f,,tkinter.colorchooser} 模块提供了 @ref{31af,,Chooser} 类作为原生颜色选择对话框的接口。 @code{Chooser} 实现了一个模式颜色选择对话框窗口。 @code{Chooser} 类继承自 @ref{31b0,,Dialog} 类。

@geindex Chooser (tkinter.colorchooser 中的类)
@anchor{library/tkinter colorchooser tkinter colorchooser Chooser}@anchor{31af}
@deffn {类} tkinter.colorchooser.Chooser (master=None, **options)
@end deffn

@geindex askcolor() (在 tkinter.colorchooser 模块中)
@anchor{library/tkinter colorchooser tkinter colorchooser askcolor}@anchor{31b1}
@deffn {函数} tkinter.colorchooser.askcolor (color=None, **options)

创建一个颜色选择对话框。 调用此方法将显示相应窗口，等待用户进行选择，并将选择的颜色 (或 @code{None}) 返回给调用者。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{110,,tkinter.commondialog}

Tkinter 标准对话框模块
@end table


@node tkinter font --- Tkinter 字体封装,Tkinter 对话框,tkinter colorchooser --- 颜色选择对话框,Tk图形用户界面 GUI
@anchor{library/tkinter font doc}@anchor{31b2}@anchor{library/tkinter font module-tkinter font}@anchor{113}@anchor{library/tkinter font tkinter-font-tkinter-font-wrapper}@anchor{31b3}
@subsection @code{tkinter.font} --- Tkinter 字体封装


@geindex tkinter.font (模块)

@strong{源代码:} Lib/tkinter/font.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/font.py}


__________________________________________________________________


@ref{113,,tkinter.font} 模块提供用于创建和使用命名字体的 @ref{1016,,Font} 类。

不同的字体粗细和倾斜是：

@geindex NORMAL() (在 tkinter.font 模块中)
@geindex BOLD() (在 tkinter.font 模块中)
@geindex ITALIC() (在 tkinter.font 模块中)
@geindex ROMAN() (在 tkinter.font 模块中)
@anchor{library/tkinter font tkinter font NORMAL}@anchor{31b4}
@deffn {数据} tkinter.font.NORMAL
@anchor{library/tkinter font tkinter font BOLD}@anchor{31b5}
@deffnx {数据} tkinter.font.BOLD
@anchor{library/tkinter font tkinter font ITALIC}@anchor{31b6}
@deffnx {数据} tkinter.font.ITALIC
@anchor{library/tkinter font tkinter font ROMAN}@anchor{31b7}
@deffnx {数据} tkinter.font.ROMAN
@end deffn

@geindex Font (tkinter.font 中的类)
@anchor{library/tkinter font tkinter font Font}@anchor{1016}
@deffn {类} tkinter.font.Font (root=None, font=None, name=None, exists=False, **options)

@ref{1016,,Font} 类表示命名字体。@emph{Font} 实例具有唯一的名称，可以通过其族、大小和样式配置进行指定。命名字体是 Tk 将字体创建和标识为单个对象的方法，而不是通过每次出现时的属性来指定字体。

@quotation

参数：

@quotation


@display
@emph{font} - 字体指示符元组 (family, size, options)@w{ }
@emph{name} - 唯一的字体名@w{ }
@emph{exists} - 指向现有命名字体（如果有）@w{ }
@end display


@end quotation

其他关键字选项（如果指定了 @emph{font}，则忽略）：

@quotation


@display
@emph{family} - 字体系列，例如 Courier，Times@w{ }
@emph{size} - 字体大小@w{ }
@display
如果 @emph{size} 为正数，则解释为以磅为单位的大小。@w{ }
如果 @emph{size} 是负数，则将其绝对值@w{ }
解释为以像素为单位的大小。@w{ }
@end display
@emph{weight} - 字体强调 (NORMAL, BOLD)（普通，加粗）@w{ }
@emph{slant} - ROMAN, ITALIC（正体，斜体）@w{ }
@emph{underline} - 字体下划线（0 - 无下划线，1 - 有下划线）@w{ }
@emph{overstrike} - 字体删除线（0 - 无删除线，1 - 有删除线）@w{ }
@end display


@end quotation
@end quotation

@geindex actual() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font actual}@anchor{31b8}
@deffn {方法} actual (option=None, displayof=None)

返回字体的属性。
@end deffn

@geindex cget() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font cget}@anchor{31b9}
@deffn {方法} cget (option)

检索字体的某一个属性值。
@end deffn

@geindex config() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font config}@anchor{31ba}
@deffn {方法} config (**options)

修改字体的某一个属性值。
@end deffn

@geindex copy() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font copy}@anchor{31bb}
@deffn {方法} copy ()

返回当前字体的新实例。
@end deffn

@geindex measure() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font measure}@anchor{31bc}
@deffn {方法} measure (text, displayof=None)

返回以当前字体格式化时文本将在指定显示上占用的空间量。如果未指定显示，则假定为主应用程序窗口。
@end deffn

@geindex metrics() (tkinter.font.Font 方法)
@anchor{library/tkinter font tkinter font Font metrics}@anchor{31bd}
@deffn {方法} metrics (*options, **kw)

返回特定字体的数据。选项包括：


@table @asis

@item @emph{ascent} - 基线和最高点之间的距离

（在该字体中的一个字符可以占用的空间中）

@item @emph{descent} - 基线和最低点之间的距离

（在该字体中的一个字符可以占用的空间中）

@item @emph{linespace} - 所需最小垂直间距（在两个

该字体的字符间，使得这两个字符在垂直方向上不重叠）。
@end table

@emph{fixed} - 如果该字体宽度被固定则为1，否则为0。
@end deffn
@end deffn

@geindex families() (在 tkinter.font 模块中)
@anchor{library/tkinter font tkinter font families}@anchor{31be}
@deffn {函数} tkinter.font.families (root=None, displayof=None)

返回不同的字体系列。
@end deffn

@geindex names() (在 tkinter.font 模块中)
@anchor{library/tkinter font tkinter font names}@anchor{31bf}
@deffn {函数} tkinter.font.names (root=None)

返回定义字体的名字。
@end deffn

@geindex nametofont() (在 tkinter.font 模块中)
@anchor{library/tkinter font tkinter font nametofont}@anchor{31c0}
@deffn {函数} tkinter.font.nametofont (name)

返回一个 @ref{1016,,Font} 类，代表一个 tk 命名的字体。
@end deffn

@node Tkinter 对话框,tkinter messagebox --- Tkinter 消息提示,tkinter font --- Tkinter 字体封装,Tk图形用户界面 GUI
@anchor{library/dialog doc}@anchor{31c1}@anchor{library/dialog tkinter-dialogs}@anchor{31c2}
@subsection Tkinter 对话框


@menu
* tkinter.simpledialog: tkinter simpledialog --- 标准 Tkinter 输入对话框. 标准 Tkinter 输入对话框
* tkinter.filedialog: tkinter filedialog --- 文件选择对话框. 文件选择对话框.
* tkinter.commondialog: tkinter commondialog --- 对话窗口模板. 对话窗口模板

@end menu

@node tkinter simpledialog --- 标准 Tkinter 输入对话框,tkinter filedialog --- 文件选择对话框,,Tkinter 对话框
@anchor{library/dialog module-tkinter simpledialog}@anchor{116}@anchor{library/dialog tkinter-simpledialog-standard-tkinter-input-dialogs}@anchor{31c3}
@subsubsection @code{tkinter.simpledialog} --- 标准 Tkinter 输入对话框


@geindex tkinter.simpledialog (模块)

@strong{源码:} Lib/tkinter/simpledialog.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/simpledialog.py}


__________________________________________________________________


@ref{116,,tkinter.simpledialog} 模块包含了一些便捷类和函数，用于创建简单的模态对话框，从用户那里读取一个值。

@geindex askfloat() (在 tkinter.simpledialog 模块中)
@geindex askinteger() (在 tkinter.simpledialog 模块中)
@geindex askstring() (在 tkinter.simpledialog 模块中)
@anchor{library/dialog tkinter simpledialog askfloat}@anchor{31c4}
@deffn {函数} tkinter.simpledialog.askfloat (title, prompt, **kw)
@anchor{library/dialog tkinter simpledialog askinteger}@anchor{31c5}
@deffnx {函数} tkinter.simpledialog.askinteger (title, prompt, **kw)
@anchor{library/dialog tkinter simpledialog askstring}@anchor{31c6}
@deffnx {函数} tkinter.simpledialog.askstring (title, prompt, **kw)

以上三个函数提供给用户输入期望值的类型的对话框.
@end deffn

@geindex Dialog (tkinter.simpledialog 中的类)
@anchor{library/dialog tkinter simpledialog Dialog}@anchor{31c7}
@deffn {类} tkinter.simpledialog.Dialog (parent, title=None)

自定义对话框的基类.

@quotation

@geindex body() (tkinter.simpledialog.Dialog 方法)
@anchor{library/dialog tkinter simpledialog Dialog body}@anchor{31c8}
@deffn {方法} body (master)

可以覆盖，用于构建对话框的界面，并返回初始焦点所在的部件。
@end deffn

@geindex buttonbox() (tkinter.simpledialog.Dialog 方法)
@anchor{library/dialog tkinter simpledialog Dialog buttonbox}@anchor{31c9}
@deffn {方法} buttonbox ()

加入 OK 和 Cancel 按钮的默认行为. 重写自定义按钮布局.
@end deffn
@end quotation
@end deffn

@node tkinter filedialog --- 文件选择对话框,tkinter commondialog --- 对话窗口模板,tkinter simpledialog --- 标准 Tkinter 输入对话框,Tkinter 对话框
@anchor{library/dialog module-tkinter filedialog}@anchor{112}@anchor{library/dialog tkinter-filedialog-file-selection-dialogs}@anchor{31ca}
@subsubsection @code{tkinter.filedialog} --- 文件选择对话框.


@geindex tkinter.filedialog (模块)

@strong{源码:} Lib/tkinter/filedialog.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/filedialog.py}


__________________________________________________________________


@ref{112,,tkinter.filedialog} 模块提供了用于创建文件/目录选择窗口的类和工厂函数。

@menu
* 原生 加载/保存 对话框.: 原生 加载/保存 对话框. 

@end menu

@node 原生 加载/保存 对话框,,,tkinter filedialog --- 文件选择对话框
@anchor{library/dialog native-load-save-dialogs}@anchor{31cb}
@subsubsection 原生 加载/保存 对话框.


以下类和函数提供了文件对话窗口，这些窗口带有原生外观，具备可定制行为的配置项。这些关键字参数适用于以下类和函数：

@quotation


@display
@emph{parent} —— 对话框下方的窗口@w{ }
@end display




@display
@emph{title} —— 窗口的标题@w{ }
@end display




@display
@emph{initialdir} —— 对话框的启动目录@w{ }
@end display




@display
@emph{initialfile} —— 打开对话框时选中的文件@w{ }
@end display




@display
@emph{filetypes} —— （标签，匹配模式）元组构成的列表，允许使用 “*” 通配符@w{ }
@end display




@display
@emph{defaultextension} —— 默认的扩展名，用于加到文件名后面（保存对话框）。@w{ }
@end display




@display
@emph{multiple} —— 为 True 则允许多选@w{ }
@end display


@end quotation

** 静态工厂函数 **

调用以下函数时，会创建一个模态的、原生外观的对话框，等待用户选取，然后将选中值或 @code{None} 返回给调用者。

@geindex askopenfile() (在 tkinter.filedialog 模块中)
@geindex askopenfiles() (在 tkinter.filedialog 模块中)
@anchor{library/dialog tkinter filedialog askopenfile}@anchor{31cc}
@deffn {函数} tkinter.filedialog.askopenfile (mode="r", **options)
@anchor{library/dialog tkinter filedialog askopenfiles}@anchor{31cd}
@deffnx {函数} tkinter.filedialog.askopenfiles (mode="r", **options)

上述两个函数创建了 @ref{31ce,,Open} 对话框，并以只读模式返回打开的文件对象。
@end deffn

@geindex asksaveasfile() (在 tkinter.filedialog 模块中)
@anchor{library/dialog tkinter filedialog asksaveasfile}@anchor{31cf}
@deffn {函数} tkinter.filedialog.asksaveasfile (mode="w", **options)

创建 @ref{31d0,,SaveAs} 对话框并返回一个写入模式打开的文件对象。
@end deffn

@geindex askopenfilename() (在 tkinter.filedialog 模块中)
@geindex askopenfilenames() (在 tkinter.filedialog 模块中)
@anchor{library/dialog tkinter filedialog askopenfilename}@anchor{31d1}
@deffn {函数} tkinter.filedialog.askopenfilename (**options)
@anchor{library/dialog tkinter filedialog askopenfilenames}@anchor{31d2}
@deffnx {函数} tkinter.filedialog.askopenfilenames (**options)

以上两个函数创建了 @ref{31ce,,Open} 对话框，并返回选中的文件名，对应着已存在的文件。
@end deffn

@geindex asksaveasfilename() (在 tkinter.filedialog 模块中)
@anchor{library/dialog tkinter filedialog asksaveasfilename}@anchor{31d3}
@deffn {函数} tkinter.filedialog.asksaveasfilename (**options)

创建 @ref{31d0,,SaveAs} 对话框，并返回选中的文件名。
@end deffn

@geindex askdirectory() (在 tkinter.filedialog 模块中)
@anchor{library/dialog tkinter filedialog askdirectory}@anchor{31d4}
@deffn {函数} tkinter.filedialog.askdirectory (**options)


@display
提示用户选择一个目录.@w{ }
其他关键字参数：@w{ }
@display
@emph{mustexist} —— 确定是否必须为已存在的目录。@w{ }
@end display
@end display


@end deffn

@geindex Open (tkinter.filedialog 中的类)
@geindex SaveAs (tkinter.filedialog 中的类)
@anchor{library/dialog tkinter filedialog Open}@anchor{31ce}
@deffn {类} tkinter.filedialog.Open (master=None, **options)
@anchor{library/dialog tkinter filedialog SaveAs}@anchor{31d0}
@deffnx {类} tkinter.filedialog.SaveAs (master=None, **options)

上述两个类提供了用于保存和加载文件的原生对话窗口。
@end deffn

** 便捷类 **

以下类用于从头开始创建文件/目录窗口。不会模仿当前系统的原生外观。

@geindex Directory (tkinter.filedialog 中的类)
@anchor{library/dialog tkinter filedialog Directory}@anchor{31d5}
@deffn {类} tkinter.filedialog.Directory (master=None, **options)

创建对话框，提示用户选择一个目录。
@end deffn

@cartouche
@quotation 注解 
为了实现自定义的事件处理和行为，应继承 @emph{FileDialog} 类。
@end quotation
@end cartouche

@geindex FileDialog (tkinter.filedialog 中的类)
@anchor{library/dialog tkinter filedialog FileDialog}@anchor{31d6}
@deffn {类} tkinter.filedialog.FileDialog (master, title=None)

创建一个简单的文件选择对话框。

@geindex cancel_command() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog cancel_command}@anchor{31d7}
@deffn {方法} cancel_command (event=None)

触发对话窗口的终止。
@end deffn

@geindex dirs_double_event() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog dirs_double_event}@anchor{31d8}
@deffn {方法} dirs_double_event (event)

目录双击事件的处理程序。
@end deffn

@geindex dirs_select_event() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog dirs_select_event}@anchor{31d9}
@deffn {方法} dirs_select_event (event)

目录单击事件的处理程序。
@end deffn

@geindex files_double_event() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog files_double_event}@anchor{31da}
@deffn {方法} files_double_event (event)

文件双击事件的处理程序。
@end deffn

@geindex files_select_event() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog files_select_event}@anchor{31db}
@deffn {方法} files_select_event (event)

文件单击事件的处理程序。
@end deffn

@geindex filter_command() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog filter_command}@anchor{31dc}
@deffn {方法} filter_command (event=None)

以目录过滤文件.
@end deffn

@geindex get_filter() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog get_filter}@anchor{31dd}
@deffn {方法} get_filter ()

获取当前使用的文件过滤器.
@end deffn

@geindex get_selection() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog get_selection}@anchor{31de}
@deffn {方法} get_selection ()

获取当前选择的项目.
@end deffn

@geindex go() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog go}@anchor{31df}
@deffn {方法} go (dir_or_file=os.curdir, pattern="*", default="", key=None)

渲染对话和启动事件循环,
@end deffn

@geindex ok_event() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog ok_event}@anchor{31e0}
@deffn {方法} ok_event (event)

退出对话回到当前选择.
@end deffn

@geindex quit() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog quit}@anchor{31e1}
@deffn {方法} quit (how=None)

退出对话回到文件名, 如果有的话.
@end deffn

@geindex set_filter() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog set_filter}@anchor{31e2}
@deffn {方法} set_filter (dir, pat)

设置文件过滤器.
@end deffn

@geindex set_selection() (tkinter.filedialog.FileDialog 方法)
@anchor{library/dialog tkinter filedialog FileDialog set_selection}@anchor{31e3}
@deffn {方法} set_selection (file)

将当前选中文件更新为 @emph{file}。
@end deffn
@end deffn

@geindex LoadFileDialog (tkinter.filedialog 中的类)
@anchor{library/dialog tkinter filedialog LoadFileDialog}@anchor{31e4}
@deffn {类} tkinter.filedialog.LoadFileDialog (master, title=None)

FileDialog 的一个子类，为选择已有文件创建对话窗口。

@geindex ok_command() (tkinter.filedialog.LoadFileDialog 方法)
@anchor{library/dialog tkinter filedialog LoadFileDialog ok_command}@anchor{31e5}
@deffn {方法} ok_command ()

检测有否给出文件，以及选中的文件是否存在。
@end deffn
@end deffn

@geindex SaveFileDialog (tkinter.filedialog 中的类)
@anchor{library/dialog tkinter filedialog SaveFileDialog}@anchor{31e6}
@deffn {类} tkinter.filedialog.SaveFileDialog (master, title=None)

FileDialog 的一个子类，创建用于选择目标文件的对话窗口。

@geindex ok_command() (tkinter.filedialog.SaveFileDialog 方法)
@anchor{library/dialog tkinter filedialog SaveFileDialog ok_command}@anchor{31e7}
@deffn {方法} ok_command ()

检测选中文件是否为目录。如果选中已存在文件，则需要进行确认。
@end deffn
@end deffn

@node tkinter commondialog --- 对话窗口模板,,tkinter filedialog --- 文件选择对话框,Tkinter 对话框
@anchor{library/dialog module-tkinter commondialog}@anchor{110}@anchor{library/dialog tkinter-commondialog-dialog-window-templates}@anchor{31e8}
@subsubsection @code{tkinter.commondialog} --- 对话窗口模板


@geindex tkinter.commondialog (模块)

@strong{源码:} Lib/tkinter/commondialog.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/commondialog.py}


__________________________________________________________________


@ref{110,,tkinter.commondialog} 模块提供了 @ref{31b0,,Dialog} 类，是其他模块定义的对话框的基类。

@geindex Dialog (tkinter.commondialog 中的类)
@anchor{library/dialog tkinter commondialog Dialog}@anchor{31b0}
@deffn {类} tkinter.commondialog.Dialog (master=None, **options)

@geindex show() (tkinter.commondialog.Dialog 方法)
@anchor{library/dialog tkinter commondialog Dialog show}@anchor{31e9}
@deffn {方法} show (color=None, **options)

渲染对话窗口.
@end deffn
@end deffn


@subsubheading 参见


模块 @ref{114,,tkinter.messagebox}, @ref{1404,,读写文件}


@node tkinter messagebox --- Tkinter 消息提示,tkinter scrolledtext --- 滚动文字控件,Tkinter 对话框,Tk图形用户界面 GUI
@anchor{library/tkinter messagebox doc}@anchor{31ea}@anchor{library/tkinter messagebox module-tkinter messagebox}@anchor{114}@anchor{library/tkinter messagebox tkinter-messagebox-tkinter-message-prompts}@anchor{31eb}
@subsection @code{tkinter.messagebox} --- Tkinter 消息提示


@geindex tkinter.messagebox (模块)

@strong{源代码:} Lib/tkinter/messagebox.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/messagebox.py}


__________________________________________________________________


@ref{114,,tkinter.messagebox} 模块提供了一个模板基类以及多个常用配置的便捷方法。 消息框为模式窗口并将基于用户的选择返回 (True, False, OK, None, Yes, No) 的一个子集。 常用消息框风格和布局包括但不限于:


@float Figure

@image{python-figures/tk_msg,,,,png}

@end float


@geindex Message (tkinter.messagebox 中的类)
@anchor{library/tkinter messagebox tkinter messagebox Message}@anchor{31ec}
@deffn {类} tkinter.messagebox.Message (master=None, **options)

创建一个默认信息消息框。
@end deffn

@strong{信息消息框}

@geindex showinfo() (在 tkinter.messagebox 模块中)
@anchor{library/tkinter messagebox tkinter messagebox showinfo}@anchor{31ed}
@deffn {方法} tkinter.messagebox.showinfo (title=None, message=None, **options)
@end deffn

@strong{警告消息框}

@geindex showwarning() (在 tkinter.messagebox 模块中)
@geindex showerror() (在 tkinter.messagebox 模块中)
@anchor{library/tkinter messagebox tkinter messagebox showwarning}@anchor{31ee}
@deffn {方法} tkinter.messagebox.showwarning (title=None, message=None, **options)
@anchor{library/tkinter messagebox tkinter messagebox showerror}@anchor{31ef}
@deffnx {方法} tkinter.messagebox.showerror (title=None, message=None, **options)
@end deffn

@strong{疑问消息框}

@geindex askquestion() (在 tkinter.messagebox 模块中)
@geindex askokcancel() (在 tkinter.messagebox 模块中)
@geindex askretrycancel() (在 tkinter.messagebox 模块中)
@geindex askyesno() (在 tkinter.messagebox 模块中)
@geindex askyesnocancel() (在 tkinter.messagebox 模块中)
@anchor{library/tkinter messagebox tkinter messagebox askquestion}@anchor{31f0}
@deffn {方法} tkinter.messagebox.askquestion (title=None, message=None, **options)
@anchor{library/tkinter messagebox tkinter messagebox askokcancel}@anchor{31f1}
@deffnx {方法} tkinter.messagebox.askokcancel (title=None, message=None, **options)
@anchor{library/tkinter messagebox tkinter messagebox askretrycancel}@anchor{31f2}
@deffnx {方法} tkinter.messagebox.askretrycancel (title=None, message=None, **options)
@anchor{library/tkinter messagebox tkinter messagebox askyesno}@anchor{31f3}
@deffnx {方法} tkinter.messagebox.askyesno (title=None, message=None, **options)
@anchor{library/tkinter messagebox tkinter messagebox askyesnocancel}@anchor{31f4}
@deffnx {方法} tkinter.messagebox.askyesnocancel (title=None, message=None, **options)
@end deffn

@node tkinter scrolledtext --- 滚动文字控件,tkinter dnd --- 拖放操作支持,tkinter messagebox --- Tkinter 消息提示,Tk图形用户界面 GUI
@anchor{library/tkinter scrolledtext doc}@anchor{31f5}@anchor{library/tkinter scrolledtext module-tkinter scrolledtext}@anchor{115}@anchor{library/tkinter scrolledtext tkinter-scrolledtext-scrolled-text-widget}@anchor{31f6}
@subsection @code{tkinter.scrolledtext} --- 滚动文字控件


@geindex tkinter.scrolledtext (模块)

@strong{源代码：} Lib/tkinter/scrolledtext.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/scrolledtext.py}


__________________________________________________________________


@ref{115,,tkinter.scrolledtext} 模块提供了一个同名的类，实现了带有垂直滚动条并被配置为可以“正常运作”的文本控件 。 使用 @ref{31f7,,ScrolledText} 类会比直接配置一个文本控件附加滚动条要简单得多。

文本控件与滚动条打包在一个 @code{Frame} 中， @code{Grid} 方法和 @code{Pack} 方法的布局管理器从 @code{Frame} 对象中获得。这允许 @ref{31f7,,ScrolledText} 控件可以直接用于实现大多数正常的布局管理行为。

如果需要更具体的控制，可以使用以下属性：

@geindex ScrolledText (tkinter.scrolledtext 中的类)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText}@anchor{31f7}
@deffn {类} tkinter.scrolledtext.ScrolledText (master=None, **kw)

@geindex frame (tkinter.scrolledtext.ScrolledText 属性)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText frame}@anchor{31f8}
@deffn {属性} frame

围绕文本和滚动条控件的框架。
@end deffn

@geindex vbar (tkinter.scrolledtext.ScrolledText 属性)
@anchor{library/tkinter scrolledtext tkinter scrolledtext ScrolledText vbar}@anchor{31f9}
@deffn {属性} vbar

滚动条控件。
@end deffn
@end deffn

@node tkinter dnd --- 拖放操作支持,tkinter ttk --- Tk主题部件,tkinter scrolledtext --- 滚动文字控件,Tk图形用户界面 GUI
@anchor{library/tkinter dnd doc}@anchor{31fa}@anchor{library/tkinter dnd module-tkinter dnd}@anchor{111}@anchor{library/tkinter dnd tkinter-dnd-drag-and-drop-support}@anchor{31fb}
@subsection @code{tkinter.dnd} --- 拖放操作支持


@geindex tkinter.dnd (模块)

@strong{源代码:} Lib/tkinter/dnd.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/dnd.py}


__________________________________________________________________


@cartouche
@quotation 注解 
此模块是实验性的且在为 Tk DND 所替代后将被弃用。
@end quotation
@end cartouche

@ref{111,,tkinter.dnd} 模块为单个应用内部的对象提供了在同一窗口中或多个窗口间的拖放操作支持。 要将对象设为可拖放，你必须为其创建启动拖放进程的事件绑定。 通常，你要将 ButtonPress 事件绑定到你所编写的回调函数 (参见 @ref{31a2,,绑定和事件})。 该函数应当调用 @ref{31fc,,dnd_start()}，其中 'source' 为要拖动的对象，而 'event' 为发起调用的事件（你的回调函数的参数）。

目标对象的选择方式如下:


@enumerate 

@item 
从顶至底地在鼠标之下的区域中搜索目标控件
@end enumerate

@quotation


@itemize *

@item 
目标控件应当具有一个指向可调用对象的 @emph{dnd_accept} 属性

@item 
如果 @emph{dnd_accept} 不存在或是返回 None，则将转至父控件中搜索

@item 
如果目标控件未找到，则目标对象为 None
@end itemize
@end quotation


@enumerate 2

@item 
调用 @emph{<old_target>.dnd_leave(source, event)}

@item 
调用 @emph{<new_target>.dnd_enter(source, event)}

@item 
调用 @emph{<target>.dnd_commit(source, event)} 来通知释放

@item 
调用 @emph{<source>.dnd_end(target, event)} 来表明拖放的结束
@end enumerate

@geindex DndHandler (tkinter.dnd 中的类)
@anchor{library/tkinter dnd tkinter dnd DndHandler}@anchor{31fd}
@deffn {类} tkinter.dnd.DndHandler (source, event)

@emph{DndHandler} 类处理拖放事件，在事件控件的根对象上跟踪 Motion 和 ButtonRelease 事件。

@geindex cancel() (tkinter.dnd.DndHandler 方法)
@anchor{library/tkinter dnd tkinter dnd DndHandler cancel}@anchor{31fe}
@deffn {方法} cancel (event=None)

取消拖放进程。
@end deffn

@geindex finish() (tkinter.dnd.DndHandler 方法)
@anchor{library/tkinter dnd tkinter dnd DndHandler finish}@anchor{31ff}
@deffn {方法} finish (event, commit=0)

执行结束播放函数。
@end deffn

@geindex on_motion() (tkinter.dnd.DndHandler 方法)
@anchor{library/tkinter dnd tkinter dnd DndHandler on_motion}@anchor{3200}
@deffn {方法} on_motion (event)

在执行拖动期间为目标对象检查鼠标之下的区域。
@end deffn

@geindex on_release() (tkinter.dnd.DndHandler 方法)
@anchor{library/tkinter dnd tkinter dnd DndHandler on_release}@anchor{3201}
@deffn {方法} on_release (event)

当释放模式被触发时表明拖动的结束。
@end deffn
@end deffn

@geindex dnd_start() (在 tkinter.dnd 模块中)
@anchor{library/tkinter dnd tkinter dnd dnd_start}@anchor{31fc}
@deffn {函数} tkinter.dnd.dnd_start (source, event)

用于拖放进程的工厂函数。
@end deffn


@subsubheading 参见


@ref{31a2,,绑定和事件}


@node tkinter ttk --- Tk主题部件,tkinter tix --- TK扩展包,tkinter dnd --- 拖放操作支持,Tk图形用户界面 GUI
@anchor{library/tkinter ttk doc}@anchor{3202}@anchor{library/tkinter ttk module-tkinter ttk}@anchor{118}@anchor{library/tkinter ttk tkinter-ttk-tk-themed-widgets}@anchor{3203}
@subsection @code{tkinter.ttk} --- Tk主题部件


@geindex tkinter.ttk (模块)

@strong{源代码:} Lib/tkinter/ttk.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/ttk.py}

@geindex ttk


__________________________________________________________________


@ref{118,,tkinter.ttk} 模块自 Tk 8.5 开始引入，可用于访问 Tk 风格的控件包。如果 Python 未基于 Tk 8.5 编译，只要安装了 @emph{Tile} 仍可访问本模块。前一种采用 Tk 8.5 的方式带有更多好处，比如在 X11 系统下支持反锯齿字体渲染和透明窗口（需要 X11 中的窗口组管理器）。

@ref{118,,tkinter.ttk} 的基本设计思路，就是尽可能地把控件的行为代码与实现其外观的代码分离开来。


@subsubheading 参见



@table @asis

@item Tk 控件风格@footnote{https://core.tcl.tk/tips/doc/trunk/tip/48.md}

一份文档介绍Tk支持的主题
@end table


@menu
* 使用 Ttk:: 
* Ttk 控件:: 
* 控件:: 
* 组合框:: 
* Spinbox:: 
* 笔记本:: 
* Progressbar:: 
* Separator:: 
* Sizegrip:: 
* Treeview:: 
* Ttk 风格:: 

@end menu

@node 使用 Ttk,Ttk 控件,,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk using-ttk}@anchor{3204}
@subsubsection 使用 Ttk


开始使用 Ttk, 导入模块:

@example
from tkinter import ttk
@end example

重写基础Tk控件,导入应跟随Tk导入:

@example
from tkinter import *
from tkinter.ttk import *
@end example

这段代码会让以下几个 @code{tkinter. ttk} 控件（@code{Button}, @code{Checkbutton}, @code{Entry}, @code{Frame}, @code{Label}, @code{LabelFrame}, @code{Menubutton}, @code{PanedWindow}, @code{Radiobutton}, @code{Scale} 和 @code{Scrollbar}）自动替换掉 Tk 的对应控件。

使用新控件的直接好处，是拥有更好的跨平台的外观，但新旧控件并不完全兼容。主要区别在于，Ttk 组件不再包含“fg”、“bg”等与样式相关的参数 。而是用 @code{ttk.Style}  类来定义更美观的样式效果。


@subsubheading 参见



@table @asis

@item 将现有的应用程序转换为 Tile 控件，可参考 Converting existing applications to use Tile widgets@footnote{http://tktable.sourceforge.net/tile/doc/converting.txt} 。

此文介绍使用新控件时的常见差别（使用 Tcl ）。
@end table


@node Ttk 控件,控件,使用 Ttk,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk ttk-widgets}@anchor{3205}
@subsubsection Ttk 控件


ttk 中有 18 种部件 ，其中十二种已存在于 tkinter 中: @code{Button}, @code{Checkbutton}, @code{Entry}, @code{Frame}, @code{Label}, @code{LabelFrame}, @code{Menubutton}, @code{PanedWindow}, @code{Radiobutton}, @code{Scale}, @code{Scrollbar} 以及 @ref{50a,,Spinbox}。 另外六种是新增的: @ref{3206,,Combobox}, @ref{3207,,Notebook}, @ref{3208,,Progressbar}, @code{Separator}, @code{Sizegrip} 以及 @ref{3e6,,Treeview}。 它们全都是 @ref{3209,,Widget} 的子类。

ttk 控件可以改善应用程序的外观。如上所述，修改样式的代码与 tk 控件存在差异。

Tk 代码:

@example
l1 = tkinter.Label(text="Test", fg="black", bg="white")
l2 = tkinter.Label(text="Test", fg="black", bg="white")
@end example

Ttk 代码:

@example
style = ttk.Style()
style.configure("BW.TLabel", foreground="black", background="white")

l1 = ttk.Label(text="Test", style="BW.TLabel")
l2 = ttk.Label(text="Test", style="BW.TLabel")
@end example

有关 @ref{320a,,TtkStyling} 的更多信息，请参阅 @ref{320b,,Style} 类文档。

@node 控件,组合框,Ttk 控件,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk widget}@anchor{320c}
@subsubsection 控件


@code{ttk.Widget} 定义了由 Tk 带主题部件所支持的标准选项和方法，它们不应该被直接实例化。

@menu
* 标准选项:: 
* 可滚动控件选项:: 
* 标签选项:: 
* 兼容性选项:: 
* 控件状态:: 
* ttk.Widget: ttk Widget. 

@end menu

@node 标准选项,可滚动控件选项,,控件
@anchor{library/tkinter ttk standard-options}@anchor{320d}
@subsubsection 标准选项


所有 @code{ttk} 小部件接受以下选项：

@quotation


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

类

@tab

指定窗口类。在查询选项数据库中窗口的其他选项时，使用该类，确定窗口的默认绑定标签，以及选择控件的默认布局和样式。此选项仅为只读，并且只能在创建窗口时指定。

@item

光标

@tab

指定要用于控件的鼠标光标。如果设置为空字符串（默认值），则为父控件继承光标.

@item

takefocus

@tab

确定窗口是否在键盘遍历期间接受焦点。返回0或1，返回空字符串。如果返回0，则表示在键盘遍历期间应该跳过该窗口。如果为1，则表示只要可以查看窗口就应该接收输入焦点。并且空字符串意味着遍历脚本决定是否关注窗口。

@item

风格

@tab

可用于指定自定义控件样式。

@end multitable

@end quotation

@node 可滚动控件选项,标签选项,标准选项,控件
@anchor{library/tkinter ttk scrollable-widget-options}@anchor{320e}
@subsubsection 可滚动控件选项


控件支持以下选项使用滚动条控制.

@quotation


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

xscroll命令

@tab

用于与水平滚动条通讯.

当视图在控件的窗口改变,控件将会基于scroll命令生成Tcl命令.

通常该参数由滚动条的 @code{Scrollbar.set()} 方法组成。当窗口中的可见内容发生变化时，将会刷新滚动条的状态。

@item

yscroll命令

@tab

用于与垂直滚动条通讯.更多信息请参考上面的信息.

@end multitable

@end quotation

@node 标签选项,兼容性选项,可滚动控件选项,控件
@anchor{library/tkinter ttk label-options}@anchor{320f}
@subsubsection 标签选项


以下选项支持标签,按钮已及其他类按钮的控件.

@quotation


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

文本

@tab

指定显示在控件内的文本。

@item

文本变量

@tab

指定一个变量名，其值将用于设置 text 参数。

@item

下划线

@tab

设置文本字符串中带下划线字符的索引（基于0）。下划线字符用于激活快捷键。

@item

图片

@tab

指定一个用于显示的图像。这是一个由1个或多个元素组成的列表。第一个元素是默认的图像名称。列表的其余部分是由 @ref{102f,,Style.map()} 定义的“状态/值对”的序列，指定控件在某状态或状态组合时要采用的图像。列表中的所有图像应具备相同的尺寸。

@item

compound

@tab

指定同时存在 text 和 image 参数时，应如何显示文本和对应的图片。合法的值包括：


@itemize *

@item 
text: 只显示文本

@item 
image: 只显示图片

@item 
top, bottom, left, right: 分别显示图片的上,下,左,右的文本.

@item 
none: 默认. 如果设置显示图片, 否则文本.
@end itemize

@item

宽度

@tab

如果值大于零，指定文本标签留下多少空间，单位是字符数；如果值小于零，则指定最小宽度。如果等于零或未指定，则使用文本标签本身的宽度。

@end multitable

@end quotation

@node 兼容性选项,控件状态,标签选项,控件
@anchor{library/tkinter ttk compatibility-options}@anchor{3210}
@subsubsection 兼容性选项


@quotation


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

状况

@tab

可以设为“normal”或“disabled”，以便控制“禁用”状态标志位。本参数只允许写入：用以改变控件的状态，但 @ref{3211,,Widget.state()} 方法不影响本参数。

@end multitable

@end quotation

@node 控件状态,ttk Widget,兼容性选项,控件
@anchor{library/tkinter ttk widget-states}@anchor{3212}
@subsubsection 控件状态


控件状态是无关状态标志的位图.

@quotation


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标志

@tab

描述

@item

活动

@tab

鼠标光标经过控件并按下鼠标按钮，将引发动作。

@item

禁用

@tab

在程序控制下控件是禁用的

@item

焦点

@tab

控件有键盘焦点

@item

按压

@tab

控件已被按下。

@item

选择

@tab

勾选或单选框之类的控件，表示启用、选中状态。

@item

背景

@tab

Windows 和 Mac 系统的窗口具有“激活”或后台的概念。后台窗口的控件会设置 @emph{foreground} 参数，而前台窗口的控件则会清除此状态。

@item

只读

@tab

控件不允许用户修改。

@item

alternate

@tab

控件的备选显式格式。

@item

无效的

@tab

控件的值是无效的

@end multitable

@end quotation

所谓的控件状态，就是一串状态名称的组合，可在某个名称前加上感叹号，表示该状态位是关闭的。

@node ttk Widget,,控件状态,控件
@anchor{library/tkinter ttk ttk-widget}@anchor{3213}
@subsubsection ttk.Widget


除了以下方法之外，@code{ttk.Widget} 还支持 @code{tkinter.Widget.cget()} 和 @code{tkinter.Widget.configure()} 方法。

@geindex Widget (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Widget}@anchor{3209}
@deffn {类} tkinter.ttk.Widget

@geindex identify() (tkinter.ttk.Widget 方法)
@anchor{library/tkinter ttk tkinter ttk Widget identify}@anchor{3214}
@deffn {方法} identify (x, y)

返回位于 @emph{x} @emph{y} 的控件名称，如果该坐标点不属于任何控件，则返回空字符串。

@emph{x} 和 @emph{y} 是控件内的相对坐标，单位是像素。
@end deffn

@geindex instate() (tkinter.ttk.Widget 方法)
@anchor{library/tkinter ttk tkinter ttk Widget instate}@anchor{3215}
@deffn {方法} instate (statespec, callback=None, *args, **kw)

检测控件的状态。如果没有设置回调函数，那么当控件状态符合 @emph{statespec} 时返回 @code{True}，否则返回 @code{False}。如果指定了回调函数，那么当控件状态匹配 @emph{statespec} 时将会调用回调函数，且带上参数 args。
@end deffn

@geindex state() (tkinter.ttk.Widget 方法)
@anchor{library/tkinter ttk tkinter ttk Widget state}@anchor{3211}
@deffn {方法} state (statespec=None)

修改或查询控件的状态。如果给出了 @emph{statespec}，则会设置控件的状态，并返回一个新的*statespec*，表明哪些标志做过改动。如果未给出 @emph{statespec}，则返回当前启用的状态标志。
@end deffn

@emph{statespec} 通常是列表或元组类型。
@end deffn

@node 组合框,Spinbox,控件,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk combobox}@anchor{3216}
@subsubsection 组合框


@code{ttk.Combobox} 控件是文本框和下拉列表的组合体。该控件是 @code{Entry} 的子类。

除了从 @ref{3209,,Widget} 继承的 @code{Widget.cget()} 、 @code{Widget.configure()} 、@ref{3214,,Widget.identify()} 、@ref{3215,,Widget.instate()} 和 @ref{3211,,Widget.state()} 方法，以及从  @code{Entry} 继承的 @code{Entry.bbox()} 、 @code{Entry.delete()} 、 @code{Entry.icursor()} 、@code{Entry.index()} 、 @code{Entry.insert()} 、 @code{Entry.selection()} 、 @code{Entry.xview()} 方法，@code{ttk.Combobox} 还自带了其他几个方法。

@menu
* 选项:: 
* 虚拟事件:: 
* ttk.Combobox: ttk Combobox. 

@end menu

@node 选项,虚拟事件,,组合框
@anchor{library/tkinter ttk options}@anchor{3217}
@subsubsection 选项


控件可设置以下参数：

@quotation


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

exportselection

@tab

布尔值，如果设为 True，则控件的选中文字将关联为窗口管理器的选中文字（可由 Misc.selection_get 返回）。

@item

justify

@tab

指定文本在控件中的对齐方式。可为 left、center、right 之一。

@item

height

@tab

设置下拉列表框的高度。

@item

postcommand

@tab

一条代码，（可用 Misc.register 进行注册），在显示之前将被调用。可用于选取要显示的值。

@item

状况

@tab

normal 、readonly 或 disabled。在 readonly  状态下，数据不能直接编辑，用户只能从下拉列表中选取。在 normal  状态下，可直接编辑文本框。在 disabled 状态下，无法做任何交互。

@item

文本变量

@tab

设置一个变量名，其值与控件的值关联。每当该变量对应的值发生变动时，控件值就会更新，反之亦然。参见 @code{tkinter.StringVar} 。

@item

值

@tab

设置显示于下拉列表中的值。

@item

宽度

@tab

设置为整数值，表示输入窗口的应有宽度，单位是字符单位（控件字体的平均字符宽度）。

@end multitable

@end quotation

@node 虚拟事件,ttk Combobox,选项,组合框
@anchor{library/tkinter ttk virtual-events}@anchor{3218}
@subsubsection 虚拟事件


当用户从下拉列表中选择某个元素时，控件会生成一条 @strong{<<ComboboxSelected>>} 虚拟事件。

@node ttk Combobox,,虚拟事件,组合框
@anchor{library/tkinter ttk ttk-combobox}@anchor{3219}
@subsubsection ttk.Combobox


@geindex Combobox (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Combobox}@anchor{3206}
@deffn {类} tkinter.ttk.Combobox

@geindex current() (tkinter.ttk.Combobox 方法)
@anchor{library/tkinter ttk tkinter ttk Combobox current}@anchor{321a}
@deffn {方法} current (newindex=None)

如果给出了 @emph{newindex}，则把控件值设为 @emph{newindex} 位置的元素值。否则，返回当前值的索引，当前值未在列表中则返回 -1。
@end deffn

@geindex get() (tkinter.ttk.Combobox 方法)
@anchor{library/tkinter ttk tkinter ttk Combobox get}@anchor{321b}
@deffn {方法} get ()

返回控件的当前值。
@end deffn

@geindex set() (tkinter.ttk.Combobox 方法)
@anchor{library/tkinter ttk tkinter ttk Combobox set}@anchor{321c}
@deffn {方法} set (value)

设置控件的值为 @emph{value} 。
@end deffn
@end deffn

@node Spinbox,笔记本,组合框,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk spinbox}@anchor{321d}
@subsubsection Spinbox


@code{ttk.Spinbox} 控件是 @code{ttk.Entry} 的扩展，带有增减箭头。可用于数字或字符串列表。这是 @code{Entry} 的子类。

除了从 @ref{3209,,Widget} 继承的 @code{Widget.cget()} 、 @code{Widget.configure()} 、@code{Widget.identified()} 、 @ref{3215,,Widget.instate()} 和 @ref{3211,,Widget.state()} 方法，以及从 @code{Entry} 继承的 @code{Entry. bbox()} 、 @code{Entry.delete()} 、 @code{Entry.icursor()} 、@code{Entry.index()} 、 @code{Entry.insert()} 、 @code{Entry.xview()} 方法，控件还自带了其他一些方法，在 @code{ttk.Spinbox} 中都有介绍。

@menu
* 选项: 选项<2>. 
* 虚拟事件: 虚拟事件<2>. 
* ttk.Spinbox: ttk Spinbox. 

@end menu

@node 选项<2>,虚拟事件<2>,,Spinbox
@anchor{library/tkinter ttk id1}@anchor{321e}
@subsubsection 选项


控件可设置以下参数：

@quotation
@end quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

从

@tab

浮点值。即递减按钮要递减的最小值。作为参数使用时必须写成 @code{from_}，因为 @code{from} 是 Python 关键字。

@item

到

@tab

浮点值。即递增按钮能够到达的最大值。

@item

增加

@tab

浮点值。指定递增/递减按钮每次的修改量。默认值为 1.0。

@item

值

@tab

字符串或浮点值构成的序列。如若给出，则递增/递减会在此序列元素间循环，而不是增减数值。

@item

wrap

@tab

布尔值。若为 @code{True} ，则递增和递减按钮会由 @code{to} 值循环至 @code{from} 值，或由  @code{from} 值循环至 @code{to} 值。

@item

格式

@tab

字符串。指定递增/递减按钮的数字格式。必须以“%W.Pf”的格式给出，W 是填充的宽度，P 是小数精度，% 和 f 就是本身的含义。

@item

命令

@tab

Python 回调函数。只要递增或递减按钮按下之后，就会进行不带参数的调用。

@end multitable


@node 虚拟事件<2>,ttk Spinbox,选项<2>,Spinbox
@anchor{library/tkinter ttk id2}@anchor{321f}
@subsubsection 虚拟事件


用户若按下 <Up> ，则控件会生成 @strong{<<Increment>>} 虚拟事件，若按下 <Down> 则会生成 @strong{<<Decrement>>} 事件。

@node ttk Spinbox,,虚拟事件<2>,Spinbox
@anchor{library/tkinter ttk ttk-spinbox}@anchor{3220}
@subsubsection ttk.Spinbox


@geindex Spinbox (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Spinbox}@anchor{50a}
@deffn {类} tkinter.ttk.Spinbox

@geindex get() (tkinter.ttk.Spinbox 方法)
@anchor{library/tkinter ttk tkinter ttk Spinbox get}@anchor{3221}
@deffn {方法} get ()

返回spinbox当前值
@end deffn

@geindex set() (tkinter.ttk.Spinbox 方法)
@anchor{library/tkinter ttk tkinter ttk Spinbox set}@anchor{3222}
@deffn {方法} set (value)

设置spinbox的值为*值*.
@end deffn
@end deffn

@node 笔记本,Progressbar,Spinbox,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk notebook}@anchor{3223}
@subsubsection 笔记本


Ttk Notebook 控件管理着多个窗口的集合，每次显示其中的一个。每个子窗口都与某个 tab 关联，可供用户选中以改变当前显示的窗口。

@menu
* 选项: 选项<3>. 
* Tab 选项:: 
* Tab 标识:: 
* 虚拟事件: 虚拟事件<3>. 
* ttk.Notebook: ttk Notebook. 

@end menu

@node 选项<3>,Tab 选项,,笔记本
@anchor{library/tkinter ttk id3}@anchor{3224}
@subsubsection 选项


控件可设置以下参数：

@quotation


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

height

@tab

如若给出且大于 0，则指定子窗口面板的应有高度（不含内部缩进）。否则会采用所有子窗口面板的最大高度。

@item

padding

@tab

指定在控件外部添加的留白。padding 是最多包含四个值的列表，指定左顶右底的空间。如果给出的元素少于四个，底部值默认为顶部值，右侧值默认为左侧值，顶部值默认为左侧值。

@item

宽度

@tab

若给出且大于 0，则设置面板的应有宽度（不含内部 padding）。否则将采用所有子窗口面板的最大宽度。

@end multitable

@end quotation

@node Tab 选项,Tab 标识,选项<3>,笔记本
@anchor{library/tkinter ttk tab-options}@anchor{3225}
@subsubsection Tab 选项


Tab 特有属性如下：

@quotation


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

状况

@tab

可为 normal、disabled 或 disabled 之一。若为 disabled 则不能选中。若为 hidden 则不会显示。

@item

sticky

@tab

指定子窗口在面板内的定位方式。应为包含零个或多个 n、s、e 、w 字符的字符串。每个字母表示子窗口应紧靠的方向（北、南、东或西），正如 @code{grid()} 位置管理器所述。

@item

padding

@tab

指定控件和面板之间的留白空间。格式与本控件的 padding 属性相同。

@item

文本

@tab

指定显示在 tab 上的文本。

@item

图片

@tab

指定显示在 tab 上的图片。参见 @ref{3209,,Widget} 的 image 属性。

@item

compound

@tab

当文本和图片同时存在时，指定图片相对于文本的显示位置。合法的属性值参见 @ref{320f,,Label Options} 。

@item

下划线

@tab

指定下划线在文本字符串中的索引（基于0）。如果调用过了 @ref{3226,,Notebook.enable_traversal()}，带下划线的字符将用于激活快捷键。

@end multitable

@end quotation

@node Tab 标识,虚拟事件<3>,Tab 选项,笔记本
@anchor{library/tkinter ttk tab-identifiers}@anchor{3227}
@subsubsection Tab 标识


The tab_id present in several methods of @code{ttk.Notebook} may take any
of the following forms:


@itemize *

@item 
位于 0 和 tab 总数之间的整数值。

@item 
子窗口的名称

@item 
以“@@x,y”形式给出的位置，唯一标识了 tab 页。

@item 
字符串“current”，标识当前选中的 Tab。

@item 
字符串字面值 "end"，它返回标签页的数量 (仅适用于 @ref{3228,,Notebook.index()})
@end itemize

@node 虚拟事件<3>,ttk Notebook,Tab 标识,笔记本
@anchor{library/tkinter ttk id4}@anchor{3229}
@subsubsection 虚拟事件


当选中一个新 tab 页之后，控件会生成一条 @strong{<<NotebookTabChanged>>} 虚拟事件。

@node ttk Notebook,,虚拟事件<3>,笔记本
@anchor{library/tkinter ttk ttk-notebook}@anchor{322a}
@subsubsection ttk.Notebook


@geindex Notebook (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Notebook}@anchor{3207}
@deffn {类} tkinter.ttk.Notebook

@geindex add() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook add}@anchor{322b}
@deffn {方法} add (child, **kw)

添加一个新 tab 页。

如果窗口是由 Notebook 管理但处于隐藏状态，则会恢复到之前的位置。

可用属性请参见 @ref{3225,,Tab Options} 。
@end deffn

@geindex forget() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook forget}@anchor{322c}
@deffn {方法} forget (tab_id)

删除 @emph{tab_id} 指定的 tab 页，移除与其窗口的关联。
@end deffn

@geindex hide() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook hide}@anchor{322d}
@deffn {方法} hide (tab_id)

隐藏 @emph{tab_id} 指定的 tab 页。

tab 页不会显示出来，但关联的窗口仍接受 Notebook 的管理，其配置属性会继续保留。隐藏的 tab 页可由 @ref{322b,,add()} 恢复。
@end deffn

@geindex identify() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook identify}@anchor{322e}
@deffn {方法} identify (x, y)

返回 tab 页内位置为  @emph{x}、@emph{y} 的控件名称，若不存在则返回空字符串。
@end deffn

@geindex index() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook index}@anchor{3228}
@deffn {方法} index (tab_id)

返回 @emph{tab_id} 指定 tab 页的索引值，如果 @emph{tab_id} 为 end 则返回 tab 页的总数。
@end deffn

@geindex insert() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook insert}@anchor{322f}
@deffn {方法} insert (pos, child, **kw)

在指定位置插入一个面板控件。

@emph{pos} 可为字符串“end” 、整数索引值或子窗口名称。如果 @emph{child} 已由 Notebook 管理，则移至指定位置。

可用属性请参见 @ref{3225,,Tab Options} 。
@end deffn

@geindex select() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook select}@anchor{3230}
@deffn {方法} select (tab_id=None)

选中 @emph{tab_id} 指定 tab。

显示关联的子窗口，之前选中的窗口将取消映射关系。如果省略 @emph{tab_id} ，则返回当前选中面板的控件名称。
@end deffn

@geindex tab() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook tab}@anchor{3231}
@deffn {方法} tab (tab_id, option=None, **kw)

查询或修改 @emph{tab_id} 指定 tab 的属性。

如果未给出 @emph{kw} ，则返回由 tab 属性组成的字典。如果指定了 @emph{option}，则返回其值。否则，设置属性值。
@end deffn

@geindex tabs() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook tabs}@anchor{3232}
@deffn {方法} tabs ()

返回 Notebook 管理的窗口列表。
@end deffn

@geindex enable_traversal() (tkinter.ttk.Notebook 方法)
@anchor{library/tkinter ttk tkinter ttk Notebook enable_traversal}@anchor{3226}
@deffn {方法} enable_traversal ()

为包含 Notebook 的顶层窗口启用键盘遍历。

这将为包含 Notebook 的顶层窗口增加如下键盘绑定关系：


@itemize *

@item 
@code{Control-Tab} ：将当前 tab 加入选中列表。

@item 
@code{Shift-Control-Tab} ：选中当前 tab 之前的页。

@item 
@code{Alt-K} ：这里 @emph{K} 是任意 tab 页的快捷键（带下划线）字符，将会直接选中该 tab。
@end itemize

一个顶层窗口中可为多个 Notebook 启用键盘遍历，包括嵌套的 Notebook 。但仅当所有面板都将所在 Notebook 作为父控件时，键盘遍历才会生效。
@end deffn
@end deffn

@node Progressbar,Separator,笔记本,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk progressbar}@anchor{3233}
@subsubsection Progressbar


@code{ttk.Progressbar} 控件可为长时间操作显示状态。可工作于两种模式：1）确定模式，显示相对完成进度；2）不确定模式，显示动画让用户知道工作正在进行中。

@menu
* 选项: 选项<4>. 
* ttk.Progressbar: ttk Progressbar. 

@end menu

@node 选项<4>,ttk Progressbar,,Progressbar
@anchor{library/tkinter ttk id5}@anchor{3234}
@subsubsection 选项


控件可设置以下参数：

@quotation


@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

orient

@tab

horizontal 或 vertical。指定进度条的显示方向。

@item

length

@tab

指定进度条长轴的长度（横向为宽度，纵向则为高度）。

@item

模式

@tab

determinate 或 indeterminate。

@item

maximum

@tab

设定最大值。默认为 100。

@item

值

@tab

进度条的当前值。在 determinate 模式下代表已完成的工作量。在 indeterminate 模式下，解释为 @emph{maximum} 的模；也就是说，当本值增至 @emph{maximum} 时，进度条完成了一个“周期”。

@item

variable

@tab

与属性值关联的变量名。若给出，则当变量值变化时会自动设为进度条的值。

@item

phase

@tab

只读属性。只要值大于 0 且在 determinate 模式下小于最大值，控件就会定期增大该属性值。当前主题可利用本属性提供额外的动画效果。

@end multitable

@end quotation

@node ttk Progressbar,,选项<4>,Progressbar
@anchor{library/tkinter ttk ttk-progressbar}@anchor{3235}
@subsubsection ttk.Progressbar


@geindex Progressbar (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Progressbar}@anchor{3208}
@deffn {类} tkinter.ttk.Progressbar

@geindex start() (tkinter.ttk.Progressbar 方法)
@anchor{library/tkinter ttk tkinter ttk Progressbar start}@anchor{3236}
@deffn {方法} start (interval=None)

启动自动递增模式：安排一个循环的定时器事件，每隔 @emph{interval} 毫秒调用一次 @ref{3237,,Progressbar.step()}。@emph{interval} 可省略，默认为 50毫秒。
@end deffn

@geindex step() (tkinter.ttk.Progressbar 方法)
@anchor{library/tkinter ttk tkinter ttk Progressbar step}@anchor{3237}
@deffn {方法} step (amount=None)

将进度条的值增加 @emph{amount}。

@emph{amount} 可省略，默认为 1.0。
@end deffn

@geindex stop() (tkinter.ttk.Progressbar 方法)
@anchor{library/tkinter ttk tkinter ttk Progressbar stop}@anchor{3238}
@deffn {方法} stop ()

停止自增模式：取消所有由 @ref{3236,,Progressbar.start()} 启动的循环定时器事件。
@end deffn
@end deffn

@node Separator,Sizegrip,Progressbar,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk separator}@anchor{3239}
@subsubsection Separator


@code{ttk.Separator} 控件用于显示横向或纵向的分隔条。

除由 @code{ttk.Widget} 继承而来的方法外，没有定义其他方法。

@menu
* 选项: 选项<5>. 

@end menu

@node 选项<5>,,,Separator
@anchor{library/tkinter ttk id6}@anchor{323a}
@subsubsection 选项


属性如下：

@quotation


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

orient

@tab

horizontal 或 vertical。指定分隔条的方向。

@end multitable

@end quotation

@node Sizegrip,Treeview,Separator,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk sizegrip}@anchor{323b}
@subsubsection Sizegrip


@code{ttk.Sizegrip} 控件允许用户通过按下并拖动控制柄来调整内部顶层窗口的大小。

除由 @code{ttk.Widget} 继承的之外，没有其他属性和方法。

@menu
* 与平台相关的注意事项:: 
* Bug:: 

@end menu

@node 与平台相关的注意事项,Bug,,Sizegrip
@anchor{library/tkinter ttk platform-specific-notes}@anchor{323c}
@subsubsection 与平台相关的注意事项



@itemize *

@item 
在 macOS 上，顶层窗口默认自动包括了一个内置的大小控制柄。 再加一个 @code{Sizegrip} 也没什么坏处，因为内置的控制柄会盖住该控件。
@end itemize

@node Bug,,与平台相关的注意事项,Sizegrip
@anchor{library/tkinter ttk bugs}@anchor{323d}
@subsubsection Bug



@itemize *

@item 
假如内部的顶层窗口位置是相对于屏幕的右侧或底部进行设置的，那么 @code{Sizegrip} 控件将不会改变窗口的大小。

@item 
仅支持东南方向的缩放。
@end itemize

@node Treeview,Ttk 风格,Sizegrip,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk treeview}@anchor{323e}
@subsubsection Treeview


@code{ttk.Treeview} 控件可将多项内容分层级显示。每个数据项抖带有一个文本标签、一张图片（可选）和一个数据列表（可选）。这些数据值将在树标签后面分列显示。

数据值的显示顺序可用属性 @code{displaycolumns} 进行控制。树控件还可以显示列标题。数据列可通过数字或名称进行访问，各列的名称在属性 columns 中列出。参阅 @ref{323f,,Column Identifiers}。

每个数据项都由唯一名称进行标识。如果调用者未提供数据项的 ID，树控件会自动生成。根有且只有一个，名为 @code{@{@}}。根本身不会显示出来；其子项将显示在顶层。

每个数据项均带有 tag 列表，可用于绑定事件及控制外观。

Treeview 组件支持水平和垂直滚动，滚动时会依据 @ref{320e,,Scrollable Widget Options}  描述的属性和 @ref{3240,,Treeview.xview()} 和 @ref{3241,,Treeview.yview()} 方法。

@menu
* 选项: 选项<6>. 
* 数据项的属性:: 
* tag 属性:: 
* 列标识:: 
* 虚拟事件: 虚拟事件<4>. 
* ttk.Treeview: ttk Treeview. 

@end menu

@node 选项<6>,数据项的属性,,Treeview
@anchor{library/tkinter ttk id7}@anchor{3242}
@subsubsection 选项


控件可设置以下参数：

@quotation


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

columns

@tab

列标识的列表，指定列的数量和名称。

@item

displaycolumns

@tab

列标识的列表（索引可为符号或整数），指定要显示的数据列及显示顺序，或者字符串 “#all”。

@item

height

@tab

指定可见的行数。注意：所需宽度由各列宽度之和决定。

@item

padding

@tab

指定控件内部的留白。为不超过四个元素的长度列表。

@item

selectmode

@tab

控制内部类如何进行选中项的管理。可为 extended、browse 或 none。若设为 extended（默认），则可选中多个项。若为 browse ，则每次只能选中一项。若为 none，则无法修改选中项。

请注意，代码和 tag 绑定可自由进行选中操作，不受本属性的限制。

@item

show

@tab

由0个或下列值组成的列表，指定要显示树的哪些元素。


@itemize *

@item 
tree ：在 #0 列显示树的文本标签。

@item 
headings ：显示标题行。
@end itemize

默认为“tree headings”，显示所有元素。

** 注意** ：第 #0 列一定是指 tree 列，即便未设置 show="tree" 也一样。

@end multitable

@end quotation

@node 数据项的属性,tag 属性,选项<6>,Treeview
@anchor{library/tkinter ttk item-options}@anchor{3243}
@subsubsection 数据项的属性


可在插入和数据项操作时设置以下属性。

@quotation


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

文本

@tab

用于显示的文本标签。

@item

图片

@tab

Tk 图片对象，显示在文本标签左侧。

@item

值

@tab

关联的数据值列表。

每个数据项关联的数据数量应与 columns 属性相同。如果比 columns 属性的少，剩下的值将视为空。如果多于 columns 属性的，多余数据将被忽略。

@item

open

@tab

@code{True} 或 @code{False}，表明是否显示数据项的子树。

@item

tags

@tab

与该数据项关联的 tag 列表。

@end multitable

@end quotation

@node tag 属性,列标识,数据项的属性,Treeview
@anchor{library/tkinter ttk tag-options}@anchor{3244}
@subsubsection tag 属性


tag 可定义以下属性：

@quotation


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

选项

@tab

描述

@item

foreground

@tab

定义文本前景色。

@item

背景

@tab

定义单元格或数据项的背景色。

@item

font

@tab

定义文本的字体。

@item

图片

@tab

定义数据项的图片，当 image 属性为空时使用。

@end multitable

@end quotation

@node 列标识,虚拟事件<4>,tag 属性,Treeview
@anchor{library/tkinter ttk column-identifiers}@anchor{323f}
@subsubsection 列标识


列标识可用以下格式给出：


@itemize *

@item 
由 columns 属性给出的符号名。

@item 
整数值 n，指定第 n 列。

@item 
#n 的字符串格式，n 是整数，指定第 n 个显示列。
@end itemize

注释:


@itemize *

@item 
数据项属性的显示顺序可能与存储顺序不一样。

@item 
#0 列一定是指 tree 列，即便未指定 show="tree" 也是一样。
@end itemize

数据列号是指属性值列表中的索引值，显示列号是指显示在树控件中的列号。树的文本标签将显示在 #0 列。如果未设置 displaycolumns 属性，则数据列 n 将显示在第 #n+1 列。再次强调一下，@strong{#0 列一定是指 tree 列} 。

@node 虚拟事件<4>,ttk Treeview,列标识,Treeview
@anchor{library/tkinter ttk id8}@anchor{3245}
@subsubsection 虚拟事件


Treeview 控件会生成以下虚拟事件。

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Event

@tab

描述

@item

<<TreeviewSelect>>

@tab

当选中项发生变化时生成。

@item

<<TreeviewOpen>>

@tab

当焦点所在项的 open= True 时立即生成。

@item

<<TreeviewClose>>

@tab

当焦点所在项的 open= True 之后立即生成。

@end multitable

@end quotation

@ref{3246,,Treeview.focus()} 和 @ref{3e7,,Treeview.selection()} 方法可用于确认涉及的数据项。

@node ttk Treeview,,虚拟事件<4>,Treeview
@anchor{library/tkinter ttk ttk-treeview}@anchor{3247}
@subsubsection ttk.Treeview


@geindex Treeview (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Treeview}@anchor{3e6}
@deffn {类} tkinter.ttk.Treeview

@geindex bbox() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview bbox}@anchor{3248}
@deffn {方法} bbox (item, column=None)

返回某 @emph{数据项} 的边界（相对于控件窗口的坐标），形式为 (x, y, width, height) 。

若给出了 @emph{column}，则返回该单元格的边界。若该 @emph{数据项} 不可见（即从属于已关闭项或滚动至屏幕外），则返回空字符串。
@end deffn

@geindex get_children() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview get_children}@anchor{3249}
@deffn {方法} get_children (item=None)

返回从属于 @emph{item} 的下级数据项列表。

若未给出 @emph{item} ，则返回根的下级。
@end deffn

@geindex set_children() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview set_children}@anchor{324a}
@deffn {方法} set_children (item, *newchildren)

用 @emph{newchildren} 替换 @emph{item} 的下级数据。

对于 @emph{item} 中存在而 @emph{newchildren} 中不存在的数据项，会从树中移除。@emph{newchildren} 中的数据不能是 @emph{item} 的上级。注意，未给出 @emph{newchildren} 会导致 @emph{item} 的子项被移除。
@end deffn

@geindex column() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview column}@anchor{324b}
@deffn {方法} column (column, option=None, **kw)

查询或修改 @emph{column} 的属性。

如果未给出 @emph{kw}，则返回属性值的字典。若指定了 @emph{option}，则会返回该属性值。否则将设置属性值。

合法的 属性/值 可为：


@itemize *

@item 

@table @asis

@item id

返回列名。这是只读属性。
@end table

@item 

@table @asis

@item anchor：标准的 Tk 锚点值。

指定该列的文本在单元格内的对齐方式。
@end table

@item 

@table @asis

@item minwidth：宽度。

列的最小宽度，单位是像素。在缩放控件或用户拖动某一列时，Treeview 会保证列宽不小于此值。
@end table

@item 

@table @asis

@item stretch: @code{True}/@code{False}

指明列宽度是否应该在部件大小被改变时进行相应的调整。
@end table

@item 

@table @asis

@item width: width

以像素表示的列宽度。
@end table
@end itemize

要配置树的列，则调用此方法并附带参数 column = "#0"
@end deffn

@geindex delete() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview delete}@anchor{324c}
@deffn {方法} delete (*items)

删除所有 @emph{items} 及其下属。

根不能删除。
@end deffn

@geindex detach() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview detach}@anchor{324d}
@deffn {方法} detach (*items)

将所有 @emph{items} 与树解除关联。

数据项及其下属依然存在，后续可以重新插入，目前只是不显示出来。

根不能解除关联。
@end deffn

@geindex exists() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview exists}@anchor{324e}
@deffn {方法} exists (item)

如果给出的 @emph{item} 位于树中，则返回 @code{True}。
@end deffn

@geindex focus() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview focus}@anchor{3246}
@deffn {方法} focus (item=None)

如果给出 @emph{item} 则设为当前焦点。否则返回当前焦点所在数据项，若无则返回 '@w{'}。
@end deffn

@geindex heading() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview heading}@anchor{324f}
@deffn {方法} heading (column, option=None, **kw)

查询或修改某 @emph{column} 的标题。

若未给出 @emph{kw}，则返回列标题组成的列表。若给出了 @emph{option} 则返回对应属性值。否则，设置属性值。

合法的 属性/值 可为：


@itemize *

@item 

@table @asis

@item text：文本。

显示为列标题的文本。
@end table

@item 

@table @asis

@item image：图片名称

指定显示在列标题右侧的图片。
@end table

@item 

@table @asis

@item anchor：锚点

指定列标题文本的对齐方式。应为标准的 Tk 锚点值。
@end table

@item 

@table @asis

@item command：回调函数

点击列标题时执行的回调函数。
@end table
@end itemize

若要对 tree 列进行设置，请带上 column = "#0" 进行调用。
@end deffn

@geindex identify() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview identify}@anchor{3250}
@deffn {方法} identify (component, x, y)

返回 @emph{x}、@emph{y} 位置上 @emph{component} 控件的描述信息，如果此处没有这种控件，则返回空字符串。
@end deffn

@geindex identify_row() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_row}@anchor{3251}
@deffn {方法} identify_row (y)

返回 @emph{y} 位置上的数据项 ID。
@end deffn

@geindex identify_column() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_column}@anchor{3252}
@deffn {方法} identify_column (x)

返回 @emph{x} 位置上的单元格所在的数据列 ID。

tree 列的 ID 为 #0 。
@end deffn

@geindex identify_region() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_region}@anchor{3253}
@deffn {方法} identify_region (x, y)

返回以下值之一：


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

region

@tab

区域

@item

标题栏

@tab

树的标题栏区域。

@item

heading

@tab

两个列标题之间的间隔区域。

@item

tree

@tab

树区域。

@item

cell

@tab

数据单元格。

@end multitable


可用性：Tk 8.6。
@end deffn

@geindex identify_element() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview identify_element}@anchor{3254}
@deffn {方法} identify_element (x, y)

返回位于 @emph{x} 、@emph{y} 的数据项。

可用性：Tk 8.6。
@end deffn

@geindex index() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview index}@anchor{3255}
@deffn {方法} index (item)

返回 @emph{item} 在其数据项列表中的整数索引。
@end deffn

@geindex insert() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview insert}@anchor{3256}
@deffn {方法} insert (parent, index, iid=None, **kw)

新建一个数据项并返回其 ID。

@emph{parent} 是父项的 ID，若要新建顶级项则为空字符串。 @emph{index} 是整数或“end”，指明在父项的子项列表中的插入位置。如果 @emph{index} 小于等于0，则在开头插入新节点；如果 @emph{index} 大于或等于当前子节点数，则将其插入末尾。如果给出了 @emph{iid}，则将其用作数据项 ID； @emph{iid} 不得存在于树中。否则会新生成一个唯一 ID。

此处可设置的属性请参阅 @ref{3243,,Item Options} 。
@end deffn

@geindex item() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview item}@anchor{3257}
@deffn {方法} item (item, option=None, **kw)

查询或修改某 @emph{item} 的属性。

如果未给出 option，则返回属性/值构成的字典。如果给出了 @emph{option}，则返回该属性的值。否则，将属性设为 @emph{kw} 给出的值。
@end deffn

@geindex move() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview move}@anchor{3258}
@deffn {方法} move (item, parent, index)

将 @emph{item} 移至指定位置，父项为 @emph{parent} ，子项列表索引为 @emph{index} 。

将数据项移入其子项之下是非法的。如果 @emph{index} 小于等于0，@emph{item} 将被移到开头；如果大于等于子项的总数，则被移至最后。如果 @emph{item} 已解除关联，则会被重新连接。
@end deffn

@geindex next() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview next}@anchor{3259}
@deffn {方法} next (item)

返回 @emph{item} 的下一个相邻项，如果 @emph{item} 是父项的最后一个子项，则返回 '@w{'}。
@end deffn

@geindex parent() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview parent}@anchor{325a}
@deffn {方法} parent (item)

返回 @emph{item} 的父项 ID，如果 @emph{item} 为顶级节点，则返回 '@w{'}。
@end deffn

@geindex prev() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview prev}@anchor{325b}
@deffn {方法} prev (item)

返回 @emph{item} 的前一个相邻项，若 @emph{item} 为父项的第一个子项，则返回 '@w{'}。
@end deffn

@geindex reattach() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview reattach}@anchor{325c}
@deffn {方法} reattach (item, parent, index)

@ref{3258,,Treeview.move()} 的别名。
@end deffn

@geindex see() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview see}@anchor{325d}
@deffn {方法} see (item)

确保 @emph{item} 可见。

将 @emph{item} 所有上级的 open 属性设为 @code{True}，必要时会滚动控件，让 @emph{item} 处于树的可见部分。
@end deffn

@geindex selection() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview selection}@anchor{3e7}
@deffn {方法} selection ()

返回由选中项构成的元组。


在 3.8 版更改: @code{selection()} 不再接受参数了。若要改变选中的状态，请使用以下方法。

@end deffn

@geindex selection_set() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_set}@anchor{3e8}
@deffn {方法} selection_set (*items)

让 @emph{items} 成为新的选中项。


在 3.6 版更改: @emph{items} 可作为多个单独的参数传递，而不是作为一个元组。

@end deffn

@geindex selection_add() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_add}@anchor{325e}
@deffn {方法} selection_add (*items)

将 @emph{items} 加入选中项。


在 3.6 版更改: @emph{items} 可作为多个单独的参数传递，而不是作为一个元组。

@end deffn

@geindex selection_remove() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_remove}@anchor{325f}
@deffn {方法} selection_remove (*items)

从选中项中移除 @emph{items} 。


在 3.6 版更改: @emph{items} 可作为多个单独的参数传递，而不是作为一个元组。

@end deffn

@geindex selection_toggle() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview selection_toggle}@anchor{3260}
@deffn {方法} selection_toggle (*items)

切换 @emph{items} 中各项的选中状态。


在 3.6 版更改: @emph{items} 可作为多个单独的参数传递，而不是作为一个元组。

@end deffn

@geindex set() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview set}@anchor{3261}
@deffn {方法} set (item, column=None, value=None)

若带一个参数，则返回指定 @emph{item} 的列/值字典。若带两个参数，则返回 @emph{column} 的当前值。若带三个参数，则将 @emph{item} 的 @emph{column} 设为 @emph{value}。
@end deffn

@geindex tag_bind() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_bind}@anchor{3262}
@deffn {方法} tag_bind (tagname, sequence=None, callback=None)

为 tag 为 @emph{tagname} 的数据项绑定事件 @emph{sequence} 的回调函数。当事件分发给该数据项时，tag 参数为 @emph{tagname} 的全部数据项的回调都会被调用到。
@end deffn

@geindex tag_configure() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_configure}@anchor{3263}
@deffn {方法} tag_configure (tagname, option=None, **kw)

查询或修改 @emph{tagname} 指定项的参数。

如果给出了 @emph{kw}，则返回 @emph{tagname} 项的属性字典。如果给出了 @emph{option}，则返回 @emph{tagname} 项的 @emph{option} 属性值。否则，设置 @emph{tagname} 项的属性值。
@end deffn

@geindex tag_has() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview tag_has}@anchor{3264}
@deffn {方法} tag_has (tagname, item=None)

如果给出了 @emph{item} ，则依据 @emph{item} 是否具备 @emph{tagname} 而返回 1 或 0。否则，返回 tag 为 @emph{tagname} 的所有数据项构成的列表。

可用性：Tk 8.6。
@end deffn

@geindex xview() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview xview}@anchor{3240}
@deffn {方法} xview (*args)

查询或修改 Treeview 的横向位置。
@end deffn

@geindex yview() (tkinter.ttk.Treeview 方法)
@anchor{library/tkinter ttk tkinter ttk Treeview yview}@anchor{3241}
@deffn {方法} yview (*args)

查询或修改 Treeview 的纵向位置。
@end deffn
@end deffn

@node Ttk 风格,,Treeview,tkinter ttk --- Tk主题部件
@anchor{library/tkinter ttk ttk-styling}@anchor{3265}@anchor{library/tkinter ttk ttkstyling}@anchor{320a}
@subsubsection Ttk 风格


@code{ttk} 的每种控件都赋有一个样式，指定了控件内的元素及其排列方式，以及元素属性的动态和默认设置。默认情况下，样式名与控件的类名相同，但可能会被控件的 style 属性覆盖。如果不知道控件的类名，可用 @code{Misc.winfo_class()} 方法获取（somewidget.winfo_class()）。


@subsubheading 参见



@table @asis

@item Tcl'2004 会议报告@footnote{http://tktable.sourceforge.net/tile/tile-tcl2004.pdf}

文章解释了主题引擎的工作原理。
@end table


@geindex Style (tkinter.ttk 中的类)
@anchor{library/tkinter ttk tkinter ttk Style}@anchor{320b}
@deffn {类} tkinter.ttk.Style

用于操控风格数据库的类。

@geindex configure() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style configure}@anchor{3266}
@deffn {方法} configure (style, query_opt=None, **kw)

查询或设置 @emph{style} 的默认参数。

Each key in @emph{kw} is an option and each value is a string identifying
the value for that option.

例如，要将默认按钮改为扁平样式，并带有留白和各种背景色：

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

ttk.Style().configure("TButton", padding=6, relief="flat",
   background="#ccc")

btn = ttk.Button(text="Sample")
btn.pack()

root.mainloop()
@end example
@end deffn

@geindex map() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style map}@anchor{102f}
@deffn {方法} map (style, query_opt=None, **kw)

查询或设置 @emph{style} 的指定属性的动态值。

@emph{kw} 的每个键都是一个属性，每个值通常应为列表或元组，其中包含以元组、列表或其他形式组合而成的状态标识（statespec）。状态标识是由一个或多个状态组合，加上一个值组成。

举个例子能更清晰些：

@example
import tkinter
from tkinter import ttk

root = tkinter.Tk()

style = ttk.Style()
style.map("C.TButton",
    foreground=[('pressed', 'red'), ('active', 'blue')],
    background=[('pressed', '!disabled', 'black'), ('active', 'white')]
    )

colored_btn = ttk.Button(text="Test", style="C.TButton").pack()

root.mainloop()
@end example

请注意，要点是属性的（状态，值）序列的顺序，如果前景色属性的顺序改为 @code{[('active', 'blue'), ('pressed', 'red')]} ，则控件处于激活或按下状态时的前景色将为蓝色。
@end deffn

@geindex lookup() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style lookup}@anchor{3267}
@deffn {方法} lookup (style, option, state=None, default=None)

返回 @emph{style} 中的 @emph{option} 属性值。

如果给出了 @emph{state} ，则应是一个或多个状态组成的序列。如果设置了 @emph{default} 参数，则在属性值缺失时会用作后备值。

若要检测按钮的默认字体，可以：

@example
from tkinter import ttk

print(ttk.Style().lookup("TButton", "font"))
@end example
@end deffn

@geindex layout() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style layout}@anchor{3268}
@deffn {方法} layout (style, layoutspec=None)

按照 @emph{style} 定义控件布局。如果省略了 @emph{layoutspec}，则返回该样式的布局属性。

若给出了 @emph{layoutspec}，则应为一个列表或其他的序列类型（不包括字符串），其中的数据项应为元组类型，第一项是布局名称，第二项的格式应符合 @ref{3269,,Layouts}  的描述。

以下示例有助于理解这种格式（这里并没有实际意义）：

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.layout("TMenubutton", [
   ("Menubutton.background", None),
   ("Menubutton.button", @{"children":
       [("Menubutton.focus", @{"children":
           [("Menubutton.padding", @{"children":
               [("Menubutton.label", @{"side": "left", "expand": 1@})]
           @})]
       @})]
   @}),
])

mbtn = ttk.Menubutton(text='Text')
mbtn.pack()
root.mainloop()
@end example
@end deffn

@geindex element_create() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style element_create}@anchor{326a}
@deffn {方法} element_create (elementname, etype, *args, **kw)

在当前主题中创建一个新元素 @emph{etype} ，应为 image、from 或 vsapi。后者仅在 Windows XP 和 Vista 版的 Tk 8.6a 中可用，此处不再赘述。

如果用了 image，则 @emph{args} 应包含默认的图片名，后面跟着 状态标识/值（这里是 imagespec），@emph{kw} 可带有以下属性：

@quotation


@itemize *

@item 

@table @asis

@item border=padding

padding 是由不超过四个整数构成的列表，分别定义了左、顶、右、底的边界。
@end table

@item 

@table @asis

@item height=height

定义了元素的最小高度。如果小于零，则默认采用图片本身的高度。
@end table

@item 

@table @asis

@item padding=padding

定义了元素的内部留白。若未指定则默认采用 border 值。
@end table

@item 

@table @asis

@item sticky=spec

定义了图片的对齐方式。spec 包含零个或多个 n、s、w、e 字符。
@end table

@item 

@table @asis

@item width=width

定义了元素的最小宽度。如果小于零，则默认采用图片本身的宽度。
@end table
@end itemize
@end quotation

如果 @emph{etype} 的值用了 from，则 @ref{326a,,element_create()} 将复制一个现有的元素。 @emph{args} 应包含主题名和可选的要复制的元素。若未给出要克隆的元素，则采用空元素。 @emph{kw} 参数将被丢弃。
@end deffn

@geindex element_names() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style element_names}@anchor{326b}
@deffn {方法} element_names ()

返回当前主题已定义的元素列表 。
@end deffn

@geindex element_options() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style element_options}@anchor{326c}
@deffn {方法} element_options (elementname)

返回 @emph{elementname} 的属性列表。
@end deffn

@geindex theme_create() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style theme_create}@anchor{326d}
@deffn {方法} theme_create (themename, parent=None, settings=None)

新建一个主题。

如果 @emph{themename} 已经存在，则会报错。如果给出了 @emph{parent}，则新主题将从父主题继承样式、元素和布局。若给出了 @emph{settings} ，则语法应与 @ref{326e,,theme_settings()} 的相同。
@end deffn

@geindex theme_settings() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style theme_settings}@anchor{326e}
@deffn {方法} theme_settings (themename, settings)

将当前主题临时设为 @emph{themename}，并应用 @emph{settings}，然后恢复之前的主题。

@emph{settings} 中的每个键都是一种样式而每个值可能包含 'configure', 'map', 'layout' 和 'element create' 等键并且它们被预期具有与分别由 @ref{3266,,Style.configure()}, @ref{102f,,Style.map()}, @ref{3268,,Style.layout()} 和 @ref{326a,,Style.element_create()} 方法所指定的相符的格式。

以下例子会对 Combobox 的默认主题稍作修改：

@example
from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.theme_settings("default", @{
   "TCombobox": @{
       "configure": @{"padding": 5@},
       "map": @{
           "background": [("active", "green2"),
                          ("!disabled", "green4")],
           "fieldbackground": [("!disabled", "green3")],
           "foreground": [("focus", "OliveDrab1"),
                          ("!disabled", "OliveDrab2")]
       @}
   @}
@})

combo = ttk.Combobox().pack()

root.mainloop()
@end example
@end deffn

@geindex theme_names() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style theme_names}@anchor{326f}
@deffn {方法} theme_names ()

返回所有已知主题的列表。
@end deffn

@geindex theme_use() (tkinter.ttk.Style 方法)
@anchor{library/tkinter ttk tkinter ttk Style theme_use}@anchor{3270}
@deffn {方法} theme_use (themename=None)

若未给出 @emph{themename}，则返回正在使用的主题。否则，将当前主题设为 @emph{themename}，刷新所有控件并引发 <<ThemeChanged>> 事件。
@end deffn
@end deffn

@menu
* 布局:: 

@end menu

@node 布局,,,Ttk 风格
@anchor{library/tkinter ttk layouts}@anchor{3269}
@subsubsection 布局


布局在没有属性时可以为 @code{None} ，或是定义了元素排列方式的属性字典。布局机制采用了位置管理器的简化版本：给定一个初始容器（cavity），为每个元素都分配一个包装（parcel）。合法的选项/值包括：

@quotation


@itemize *

@item 

@table @asis

@item side: whichside

指定元素置于容器的哪一侧； 顶、右、底或左。如果省略，则该元素将占据整个容器。
@end table

@item 

@table @asis

@item sticky: nswe

指定元素在已分配包装盒内的放置位置。
@end table

@item 

@table @asis

@item unit: 0 或 1

如果设为 1，则将元素及其所有后代均视作单个元素以供 @ref{3214,,Widget.identify()} 等使用。 它被用于滚动条之类带有控制柄的东西。
@end table

@item 

@table @asis

@item children: [sublayout... ]

指定要放置于元素内的元素列表。每个元素都是一个元组（或其他序列类型），其中第一项是布局名称，另一项是个 @ref{3269,,Layout} 。
@end table
@end itemize
@end quotation

@node tkinter tix --- TK扩展包,IDLE<52>,tkinter ttk --- Tk主题部件,Tk图形用户界面 GUI
@anchor{library/tkinter tix doc}@anchor{3271}@anchor{library/tkinter tix layout}@anchor{3272}@anchor{library/tkinter tix layouts}@anchor{3273}@anchor{library/tkinter tix module-tkinter tix}@anchor{117}@anchor{library/tkinter tix tkinter-tix-extension-widgets-for-tk}@anchor{3274}
@subsection @code{tkinter.tix} --- TK扩展包


@geindex tkinter.tix (模块)

@strong{源代码:} Lib/tkinter/tix.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tkinter/tix.py}

@geindex Tix


3.6 版后已移除: 这个 TK 扩展已无人维护所以请不要在新代码中使用。 请改用 @ref{118,,tkinter.ttk}。



__________________________________________________________________


@ref{117,,tkinter.tix} (Tk Interface Extension) 模块提供了更丰富的额外可视化部件集。 虽然标准 Tk 库包含许多有用的部件，但还远不够完备。 @ref{117,,tkinter.tix} 库提供了标准 Tk 所缺少的大量常用部件: @ref{3275,,HList}, @ref{3276,,ComboBox}, @ref{3277,,Control} (即 SpinBox) 以及一系列可滚动的部件。 @ref{117,,tkinter.tix} 还包括了大量在多种不同领域的应用中很常用的部件: @ref{3278,,NoteBook}, @ref{3279,,FileEntry}, @ref{327a,,PanedWindow} 等等；总共有超过 40 种。

使用这些新增部件，你可以为应用程序引入新的交互技术，创建更好用且更直观的用户界面。 你在设计应用程序时可以通过选择最适合的部件来匹配你的应用程序和用户的特殊需求。


@subsubheading 参见



@table @asis

@item Tix 主页@footnote{http://tix.sourceforge.net/}

@code{Tix} 的主页。 其中包括附加文档和下载资源的链接。

@item Tix Man Pages@footnote{http://tix.sourceforge.net/dist/current/man/}

在线版本的指南页面和参考材料。

@item Tix Programming Guide@footnote{http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html}

在线版本的程序员参考材料。

@item Tix Development Applications@footnote{http://tix.sourceforge.net/Tixapps/src/Tide.html}

开发 Tix 和 Tkinter 程序的 Tix 应用。 Tide 应用在 Tk 在 Tkinter 下工作，并包括了 @code{TixInspect}，这是一个可远程修改和调试 Tix/Tk/Tkinter 应用的检查工具。
@end table


@menu
* 使用 Tix:: 
* Tix 部件:: 
* Tix 命令:: 

@end menu

@node 使用 Tix,Tix 部件,,tkinter tix --- TK扩展包
@anchor{library/tkinter tix using-tix}@anchor{327b}
@subsubsection 使用 Tix


@geindex Tk (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Tk}@anchor{327c}
@deffn {类} tkinter.tix.Tk (screenName=None, baseName=None, className='Tix')

最常用于代表应用主窗口的最高层级部件。 它具有一个相关联的 Tcl 解释器。interpreter.

@ref{117,,tkinter.tix} 模块中的类子类化了 @ref{10e,,tkinter} 中的类。 前者会导入后者，因此 @ref{117,,tkinter.tix} 要使用 Tkinter，你所要做的就是导入一个模块。 通常，你可以只导入 @ref{117,,tkinter.tix}，并将最高层级调用由 @ref{318e,,tkinter.Tk} 替换为 @code{tix.Tk}:

@example
from tkinter import tix
from tkinter.constants import *
root = tix.Tk()
@end example
@end deffn

要使用 @ref{117,,tkinter.tix}，你必须安装有 Tix 部件，通常会与你的 Tk 部分一起安装。 要测试你的安装，请尝试以下代码:

@example
from tkinter import tix
root = tix.Tk()
root.tk.eval('package require Tix')
@end example

@node Tix 部件,Tix 命令,使用 Tix,tkinter tix --- TK扩展包
@anchor{library/tkinter tix tix-widgets}@anchor{327d}
@subsubsection Tix 部件


Tix@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm} 将 40 多个部件类引入到 @ref{10e,,tkinter} 工具集中。

@menu
* 基本部件:: 
* 文件选择器:: 
* 层级式列表框:: 
* 表格式列表框:: 
* 管理器部件:: 
* 图像类型:: 
* 其他部件:: 
* 表单布局管理器:: 

@end menu

@node 基本部件,文件选择器,,Tix 部件
@anchor{library/tkinter tix basic-widgets}@anchor{327e}
@subsubsection 基本部件


@geindex Balloon (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Balloon}@anchor{327f}
@deffn {类} tkinter.tix.Balloon

Balloon@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm} 会在部件上弹出以提供帮助信息。 当用户将光标移到一个与 Balloon 部件绑定的部件内时，将在屏幕上弹出一个显示描述性消息的小窗口。
@end deffn

@c Python Demo of:

@c \ulink{Balloon}{http://tix.sourceforge.net/dist/current/demos/samples/Balloon.tcl}

@geindex ButtonBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix ButtonBox}@anchor{3280}
@deffn {类} tkinter.tix.ButtonBox

ButtonBox@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm} 部件会创建一组按钮框，例如常用的 @code{Ok Cancel} 按钮框。
@end deffn

@c Python Demo of:

@c \ulink{ButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/BtnBox.tcl}

@geindex ComboBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix ComboBox}@anchor{3276}
@deffn {类} tkinter.tix.ComboBox

ComboBox@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm} 部件类似于 MS Windows 中的组合框控件。 用户可以通过在输入框子部件中输入或是在列表框子部件中选择来选定一个选项。
@end deffn

@c Python Demo of:

@c \ulink{ComboBox}{http://tix.sourceforge.net/dist/current/demos/samples/ComboBox.tcl}

@geindex Control (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Control}@anchor{3277}
@deffn {类} tkinter.tix.Control

The Control@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm} 控件又名 @code{SpinBox} 控件。 用户可通过点按两个方向键或直接输入内容来调整数值。 更新的数值将被检查是否在用户定义的上下限之内。
@end deffn

@c Python Demo of:

@c \ulink{Control}{http://tix.sourceforge.net/dist/current/demos/samples/Control.tcl}

@geindex LabelEntry (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix LabelEntry}@anchor{3281}
@deffn {类} tkinter.tix.LabelEntry

LabelEntry@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm} 部件将输入框部件和标签打包为一个部件。 它可被用来简化 "输入表单" 类界面的创建。
@end deffn

@c Python Demo of:

@c \ulink{LabelEntry}{http://tix.sourceforge.net/dist/current/demos/samples/LabEntry.tcl}

@geindex LabelFrame (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix LabelFrame}@anchor{3282}
@deffn {类} tkinter.tix.LabelFrame

LabelFrame@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm} 部件将框架部件和标签打包为一个部件。 要在一个 LabelFrame 部件中创建部件，应当创建与 @code{frame} 子部件相关联的新部件并在 @code{frame} 子部件中管理它们。
@end deffn

@c Python Demo of:

@c \ulink{LabelFrame}{http://tix.sourceforge.net/dist/current/demos/samples/LabFrame.tcl}

@geindex Meter (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Meter}@anchor{3283}
@deffn {类} tkinter.tix.Meter

Meter@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm} 部件可用来显示可能会耗费很长时间运行的后台任务的进度。
@end deffn

@c Python Demo of:

@c \ulink{Meter}{http://tix.sourceforge.net/dist/current/demos/samples/Meter.tcl}

@geindex OptionMenu (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix OptionMenu}@anchor{3284}
@deffn {类} tkinter.tix.OptionMenu

OptionMenu@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm} 可创建一个选项按钮菜单。
@end deffn

@c Python Demo of:

@c \ulink{OptionMenu}{http://tix.sourceforge.net/dist/current/demos/samples/OptMenu.tcl}

@geindex PopupMenu (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix PopupMenu}@anchor{3285}
@deffn {类} tkinter.tix.PopupMenu

PopupMenu@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm} 部件可被用来替代 @code{tk_popup} 命令。 @code{Tix} @ref{3285,,PopupMenu} 部件的优势在于它所需要的应用操纵代码较少。
@end deffn

@c Python Demo of:

@c \ulink{PopupMenu}{http://tix.sourceforge.net/dist/current/demos/samples/PopMenu.tcl}

@geindex Select (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Select}@anchor{3286}
@deffn {类} tkinter.tix.Select

Select@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm} 控件是一组按钮子控件的容器。 它可被用来为用户提供单选钮或复选钮形式的选项。
@end deffn

@c Python Demo of:

@c \ulink{Select}{http://tix.sourceforge.net/dist/current/demos/samples/Select.tcl}

@geindex StdButtonBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix StdButtonBox}@anchor{3287}
@deffn {类} tkinter.tix.StdButtonBox

StdButtonBox@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm} 部件是一个用于 Motif 风格对话框的标准按钮组。
@end deffn

@c Python Demo of:

@c \ulink{StdButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/StdBBox.tcl}

@node 文件选择器,层级式列表框,基本部件,Tix 部件
@anchor{library/tkinter tix file-selectors}@anchor{3288}
@subsubsection 文件选择器


@geindex DirList (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix DirList}@anchor{3289}
@deffn {类} tkinter.tix.DirList

DirList@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm} 部件显示一个目录、它的上级目录和子目录的列表视图。 用户可以选择列表中显示的某个目录或切换到另一个目录。
@end deffn

@c Python Demo of:

@c \ulink{DirList}{http://tix.sourceforge.net/dist/current/demos/samples/DirList.tcl}

@geindex DirTree (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix DirTree}@anchor{328a}
@deffn {类} tkinter.tix.DirTree

DirTree@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm} 部件显示一个目录、它的上级目录和子目录的树状视图。 用户可以选择其中显示的某个目录或切换到另一个目录。
@end deffn

@c Python Demo of:

@c \ulink{DirTree}{http://tix.sourceforge.net/dist/current/demos/samples/DirTree.tcl}

@geindex DirSelectDialog (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix DirSelectDialog}@anchor{328b}
@deffn {类} tkinter.tix.DirSelectDialog

DirSelectDialog@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm} 部件以对话框窗口形式表示文件系统中的目录。 用户可以使用该对话框窗口在文件系统中漫游以选择所需的目录。
@end deffn

@c Python Demo of:

@c \ulink{DirSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/DirDlg.tcl}

@geindex DirSelectBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix DirSelectBox}@anchor{328c}
@deffn {类} tkinter.tix.DirSelectBox

@ref{328c,,DirSelectBox} 类似于标准的 Motif(TM) 目录选择框。 它通常用于让用户选择一个目录。 DirSelectBox 会将最近选择的目录存放在一个 ComboBox 部件中以便可以再次快速地选择它们。
@end deffn

@geindex ExFileSelectBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix ExFileSelectBox}@anchor{328d}
@deffn {类} tkinter.tix.ExFileSelectBox

ExFileSelectBox@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm} 部件通常是嵌入在 tixExFileSelectDialog 部件中。 它为用户提供了一种方便的选择文件方法。 @ref{328d,,ExFileSelectBox} 部件的风格非常类似于 MS Windows 3.1 中的标准文件对话框。
@end deffn

@c Python Demo of:

@c \ulink{ExFileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/EFileDlg.tcl}

@geindex FileSelectBox (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix FileSelectBox}@anchor{328e}
@deffn {类} tkinter.tix.FileSelectBox

FileSelectBox@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm} 类似于标准的 Motif(TM) 文件选择框。 它通常用于让用户选择一个文件。 FileSelectBox 会将最近选择的文件存放在一个 @ref{3276,,ComboBox} 部件中以便可以再次快速地选择它们。
@end deffn

@c Python Demo of:

@c \ulink{FileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/FileDlg.tcl}

@geindex FileEntry (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix FileEntry}@anchor{3279}
@deffn {类} tkinter.tix.FileEntry

FileEntry@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm} 部件可被用于输入一个文件名。 用户可以手动输入文件名。 或者用户也可以按输入框旁边的按钮控件，这将打开一个文件选择对话框。
@end deffn

@c Python Demo of:

@c \ulink{FileEntry}{http://tix.sourceforge.net/dist/current/demos/samples/FileEnt.tcl}

@node 层级式列表框,表格式列表框,文件选择器,Tix 部件
@anchor{library/tkinter tix hierarchical-listbox}@anchor{328f}
@subsubsection 层级式列表框


@geindex HList (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix HList}@anchor{3275}
@deffn {类} tkinter.tix.HList

HList@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm} 部件可被用于显示任何具有层级结构的数据，例如文件系统目录树。 其中的列表条目带有缩进并按照它们在层级中的位置以分支线段相连。
@end deffn

@c Python Demo of:

@c \ulink{HList}{http://tix.sourceforge.net/dist/current/demos/samples/HList1.tcl}

@geindex CheckList (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix CheckList}@anchor{3290}
@deffn {类} tkinter.tix.CheckList

CheckList@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm} 部件可显示一个供用户选择的条目列表。 CheckList 的功能类似于 Tk 复选钮或单选钮部件，不同之处在于它能够处理比复选钮或单选钮多得多的条目。
@end deffn

@c Python Demo of:

@c \ulink{ CheckList}{http://tix.sourceforge.net/dist/current/demos/samples/ChkList.tcl}

@c Python Demo of:

@c \ulink{ScrolledHList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList.tcl}

@c Python Demo of:

@c \ulink{ScrolledHList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList2.tcl}

@geindex Tree (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Tree}@anchor{3291}
@deffn {类} tkinter.tix.Tree

Tree@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm} 部件可被用于以树形显示具有层级结构的数据。 用户可以通过打开或关闭部分树枝来调整树形视图。
@end deffn

@c Python Demo of:

@c \ulink{Tree}{http://tix.sourceforge.net/dist/current/demos/samples/Tree.tcl}

@c Python Demo of:

@c \ulink{Tree (Dynamic)}{http://tix.sourceforge.net/dist/current/demos/samples/DynTree.tcl}

@node 表格式列表框,管理器部件,层级式列表框,Tix 部件
@anchor{library/tkinter tix tabular-listbox}@anchor{3292}
@subsubsection 表格式列表框


@geindex TList (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix TList}@anchor{3293}
@deffn {类} tkinter.tix.TList

TList@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm} 部件可被用于以表格形式显示数据。 @ref{3293,,TList} 部件中的列表条目类似于 Tk 列表框部件中的条目。 主要差异在于 (1) @ref{3293,,TList} 部件能以二维格式显示列表条目 (2) 你可以在列表条目中使用图片以及多种颜色和字体。
@end deffn

@c Python Demo of:

@c \ulink{ScrolledTList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/STList1.tcl}

@c Python Demo of:

@c \ulink{ScrolledTList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/STList2.tcl}

@c Grid has yet to be added to Python

@c \subsubsection{Grid Widget}

@c Python Demo of:

@c \ulink{Simple Grid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid0.tcl}

@c Python Demo of:

@c \ulink{ScrolledGrid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid1.tcl}

@c Python Demo of:

@c \ulink{Editable Grid}{http://tix.sourceforge.net/dist/current/demos/samples/EditGrid.tcl}

@node 管理器部件,图像类型,表格式列表框,Tix 部件
@anchor{library/tkinter tix manager-widgets}@anchor{3294}
@subsubsection 管理器部件


@geindex PanedWindow (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix PanedWindow}@anchor{327a}
@deffn {类} tkinter.tix.PanedWindow

PanedWindow@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm} 部件允许用户交互式地控制多个面板的大小。 这些面板可以垂直或水平地排列。 用户通过拖动两个面板间的控制柄来改变面板的大小。
@end deffn

@c Python Demo of:

@c \ulink{PanedWindow}{http://tix.sourceforge.net/dist/current/demos/samples/PanedWin.tcl}

@geindex ListNoteBook (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix ListNoteBook}@anchor{3295}
@deffn {类} tkinter.tix.ListNoteBook

ListNoteBook@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm} 部件非常类似于 @code{TixNoteBook} 部件：它可被用于在有限空间内显示多个窗口，就像是一个“笔记本”。 笔记本可分为许多页面（窗口）。 同一时刻只能显示其中一个页面。 用户可以通过在 @code{hlist} 子部件中选择所需页面的名称来切换这些页面。
@end deffn

@c Python Demo of:

@c \ulink{ListNoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/ListNBK.tcl}

@geindex NoteBook (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix NoteBook}@anchor{3278}
@deffn {类} tkinter.tix.NoteBook

NoteBook@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm} 部件可被用于在有限空间内显示多个窗口，就像是一个“笔记本”。 笔记本可分为许多页面。 同一时刻只能显示其中一个页面。 用户可以通过选择 NoteBook 部件顶端的可视化“选项卡”来切换这些页面。
@end deffn

@c Python Demo of:

@c \ulink{NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/NoteBook.tcl}

@c \subsubsection{Scrolled Widgets}

@c Python Demo of:

@c \ulink{ScrolledListBox}{http://tix.sourceforge.net/dist/current/demos/samples/SListBox.tcl}

@c Python Demo of:

@c \ulink{ScrolledText}{http://tix.sourceforge.net/dist/current/demos/samples/SText.tcl}

@c Python Demo of:

@c \ulink{ScrolledWindow}{http://tix.sourceforge.net/dist/current/demos/samples/SWindow.tcl}

@c Python Demo of:

@c \ulink{Canvas Object View}{http://tix.sourceforge.net/dist/current/demos/samples/CObjView.tcl}

@node 图像类型,其他部件,管理器部件,Tix 部件
@anchor{library/tkinter tix image-types}@anchor{3296}
@subsubsection 图像类型


@ref{117,,tkinter.tix} 模块增加了:


@itemize *

@item 
将 pixmap@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm} 功能提供给所有 @ref{117,,tkinter.tix} 和 @ref{10e,,tkinter} 部件以使用 XPM 文件创建彩色图像。

@c Python Demo of:

@c \ulink{XPM Image In Button}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm.tcl}

@c Python Demo of:

@c \ulink{XPM Image In Menu}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm1.tcl}

@item 
Compound@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm} 图像类型可被用于创建由许多横行构成的图像；每一行都包含从左至右排列的一组条目（文本、位图、图像或空白）。 例如，某个组合图像可被用于在一个 Tk @code{Button} 部件内同时显示一张位图和一个文本字符串。

@c Python Demo of:

@c \ulink{Compound Image In Buttons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg.tcl}

@c Python Demo of:

@c \ulink{Compound Image In NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg2.tcl}

@c Python Demo of:

@c \ulink{Compound Image Notebook Color Tabs}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg4.tcl}

@c Python Demo of:

@c \ulink{Compound Image Icons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg3.tcl}
@end itemize

@node 其他部件,表单布局管理器,图像类型,Tix 部件
@anchor{library/tkinter tix miscellaneous-widgets}@anchor{3297}
@subsubsection 其他部件


@geindex InputOnly (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix InputOnly}@anchor{3298}
@deffn {类} tkinter.tix.InputOnly

InputOnly@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm} 部件可接收来自用户的输入，此功能可通过 @code{bind} 命令实现（仅限 Unix）。
@end deffn

@node 表单布局管理器,,其他部件,Tix 部件
@anchor{library/tkinter tix form-geometry-manager}@anchor{3299}
@subsubsection 表单布局管理器


@ref{117,,tkinter.tix} 还额外提供了以下部件来增强 @ref{10e,,tkinter} 的功能:

@geindex Form (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix Form}@anchor{329a}
@deffn {类} tkinter.tix.Form

Form@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm} 布局管理器是以针对所有 Tk 部件的附加规则为基础的。
@end deffn

@node Tix 命令,,Tix 部件,tkinter tix --- TK扩展包
@anchor{library/tkinter tix tix-commands}@anchor{329b}
@subsubsection Tix 命令


@geindex tixCommand (tkinter.tix 中的类)
@anchor{library/tkinter tix tkinter tix tixCommand}@anchor{329c}
@deffn {类} tkinter.tix.tixCommand

Tix 命令@footnote{http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm} 提供了对 @code{Tix} 内部状态和 @code{Tix} 应用程序上下文等杂项元素的访问。 大部分由这些方法控制的信息作为一个整体被发给应用程序，或是发给一个屏幕或显示区域，而不是某个特定窗口。

要查看当前的设置，通常的用法是:

@example
from tkinter import tix
root = tix.Tk()
print(root.tix_configure())
@end example
@end deffn

@geindex tix_configure() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_configure}@anchor{329d}
@deffn {方法} tixCommand.tix_configure (cnf=None, **kw)

查询或修改 Tix 应用程序上下文的配置选项。 如果未指定任何选项，则返回包含所有选项的字典。 如果指定了不带值的选项，则该方法返回描述指定选项的列表（如果未指定选项则此列表与所返回值对应的子列表相同）。 如果指定了一个或多个选项-值对，则该方法会将指定的选项修改为指定的值；在此情况下该方法将返回一个空字符串。 选项可以是配置选项中的任何一个。
@end deffn

@geindex tix_cget() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_cget}@anchor{329e}
@deffn {方法} tixCommand.tix_cget (option)

返回由 @emph{option} 给出的配置选项的当前值。 选项可以是配置选项中的任何一个。
@end deffn

@geindex tix_getbitmap() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_getbitmap}@anchor{329f}
@deffn {方法} tixCommand.tix_getbitmap (name)

在某个位图目录中定位名称为 @code{name.xpm} 或 @code{name} 的位图文件（位图目录参见 @ref{32a0,,tix_addbitmapdir()} 方法）。 通过使用 @ref{329f,,tix_getbitmap()}，你可以避免在你的应用程序中硬编码位图文件的路径名。 执行成功时，它返回位图文件的完整路径名，并带有前缀字符 @code{@@}。 返回值可被用于配置 Tk 和 Tix 部件的 @code{bitmap} 选项。
@end deffn

@geindex tix_addbitmapdir() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_addbitmapdir}@anchor{32a0}
@deffn {方法} tixCommand.tix_addbitmapdir (directory)

Tix 维护了一个列表以供 @ref{32a1,,tix_getimage()} 和 @ref{329f,,tix_getbitmap()} 方法在其中搜索图像文件。 标准位图目录是 @code{$TIX_LIBRARY/bitmaps}。 @ref{32a0,,tix_addbitmapdir()} 方法向该列表添加了 @emph{directory}。 通过使用此方法，应用程序的图像文件也可使用 @ref{32a1,,tix_getimage()} 或 @ref{329f,,tix_getbitmap()} 方法来定位。
@end deffn

@geindex tix_filedialog() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_filedialog}@anchor{32a2}
@deffn {方法} tixCommand.tix_filedialog ([dlgclass])

返回可在来自该应用程序的同不调用之间共享的选择对话框。 此方法将在首次被调用时创建一个选择对话框部件。 此后对 @ref{32a2,,tix_filedialog()} 的所有调用都将返回该对话框。 可以传入一个字符串形式的可选形参 dlgclass 来指明所需的选择对话框类型。 可用的选项有 @code{tix}, @code{FileSelectDialog} 或 @code{tixExFileSelectDialog}。
@end deffn

@geindex tix_getimage() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_getimage}@anchor{32a1}
@deffn {方法} tixCommand.tix_getimage (self, name)

在某个位图目录（参见上文的 @ref{32a0,,tix_addbitmapdir()} 方法）中定位名为 @code{name.xpm}, @code{name.xbm} 或 @code{name.ppm} 的图像文件。 如果存在多个同名文件（但扩展名不同），则会按照 X 显示的深度选择图像类型：单色显示选择 xbm 图像而彩色显示则选择彩色图像。 通过使用 @ref{32a1,,tix_getimage()}，你可以避免在你的应用程序中硬编码图像文件的路径名。 当执行成功时，此方法将返回新创建图像的名称，它可被用于配置 Tk 和 Tix 部件的 @code{image} 选项。
@end deffn

@geindex tix_option_get() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_option_get}@anchor{32a3}
@deffn {方法} tixCommand.tix_option_get (name)

获取由 Tix 规格机制维护的选项。
@end deffn

@geindex tix_resetoptions() (tkinter.tix.tixCommand 方法)
@anchor{library/tkinter tix tkinter tix tixCommand tix_resetoptions}@anchor{32a4}
@deffn {方法} tixCommand.tix_resetoptions (newScheme, newFontSet[, newScmPrio])

将 Tix 应用程序的规格设置与字体设置分别重置为 @emph{newScheme} 和 @emph{newFontSet}。 这只会影响调用此方法之后创建的部件。 因此，最好是在 Tix 应用程序的任何部件被创建之前调用 resetoptions 方法。

可以给出可选的形参 @emph{newScmPrio} 来重置由 Tix 规格所设置的 Tk 选项的优先级。

由于 Tk 处理 X 选项数据库的特别方式，在 Tix 被导入并初始化之后，将无法再使用 @code{tix_config()} 方法来重置颜色方案和字体集。 而必须要使用 @ref{32a4,,tix_resetoptions()} 方法。
@end deffn

@node IDLE<52>,,tkinter tix --- TK扩展包,Tk图形用户界面 GUI
@anchor{library/idle doc}@anchor{32a5}@anchor{library/idle id1}@anchor{32a6}@anchor{library/idle idle}@anchor{a34}
@subsection IDLE


@strong{源代码：} Lib/idlelib/@footnote{https://github.com/python/cpython/tree/3.9/Lib/idlelib/}

@geindex IDLE
@geindex Python Editor
@geindex Integrated Development Environment


__________________________________________________________________


IDLE 是 Python 所内置的开发与学习环境。

IDLE 具有以下特性：


@itemize *

@item 
编码于 100% 纯正的 Python，使用名为 @ref{10e,,tkinter} 的图形用户界面工具

@item 
跨平台：在 Windows、Unix 和 macOS 上工作近似。

@item 
提供输入输出高亮和错误信息的 Python 命令行窗口 （交互解释器）

@item 
提供多次撤销操作、Python 语法高亮、智能缩进、函数调用提示、自动补全等功能的多窗口文本编辑器

@item 
在多个窗口中检索，在编辑器中替换文本，以及在多个文件中检索（通过 grep）

@item 
提供持久保存的断点调试、单步调试、查看本地和全局命名空间功能的调试器

@item 
配置、浏览以及其它对话框
@end itemize

@menu
* 目录:: 
* 编辑和导航:: 
* 启动和代码执行:: 
* 帮助和偏好:: 

@end menu

@node 目录,编辑和导航,,IDLE<52>
@anchor{library/idle menus}@anchor{32a7}
@subsubsection 目录


IDEL 有两种主要的窗口类型：Shell窗口和编辑器窗口。其中编辑器窗口可以同时打开多个。并且对于 Windows 和 Linux 平台，窗口顶部主菜单各不相同。以下每个菜单说明项，都标识了与之关联的平台类型。

导出窗口，例如使用 编辑=>在文件中查找 是编辑器窗口的的一个子类型。它们目前有着相同的主菜单，但是默认标题和上下文菜单不同。

在macOS上，只有一个应用程序菜单。它会根据当前选择的窗口动态变化。它具有一个IDLE菜单，并且下面描述的某些条目已移动到符合Apple准则的位置。

@menu
* 文件菜单 （命令行和编辑器）:: 
* 编辑菜单（命令行和编辑器）:: 
* 格式菜单（仅 window 编辑器）:: 
* 运行菜单（仅 window 编辑器）:: 
* Shell 菜单（仅 window 编辑器）:: 
* 调试菜单（仅 window 编辑器）:: 
* 选项菜单（命令行和编辑器）:: 
* Window 菜单（命令行和编辑器）:: 
* 帮助菜单（命令行和编辑器）:: 
* 上下文菜单:: 

@end menu

@node 文件菜单 （命令行和编辑器）,编辑菜单（命令行和编辑器）,,目录
@anchor{library/idle file-menu-shell-and-editor}@anchor{32a8}
@subsubsection 文件菜单 （命令行和编辑器）



@table @asis

@item 新建文件

创建一个文件编辑器窗口。

@item 打开...

使用打开窗口以打开一个已存在的文件。

@item 近期文件

打开一个近期文件列表，选取一个以打开它。

@item 打开模块...

打开一个已存在的模块 （搜索 sys.path）
@end table

@geindex Class browser
@geindex Path browser


@table @asis

@item 类浏览器

于当前所编辑的文件中使用树形结构展示函数、类以及方法。在命令行中，首先打开一个模块。

@item 路径浏览

在树状结构中展示 sys.path 目录、模块、函数、类和方法。

@item 保存

如果文件已经存在，则将当前窗口保存至对应的文件。自打开或上次保存之后经过修改的文件的窗口标题栏首尾将出现星号 * 。如果没有对应的文件，则使用“另存为”代替。

@item 保存为...

使用“保存为”对话框保存当前窗口。被保存的文件将作为当前窗口新的对应文件。

@item 另存为副本...

保存当前窗口至另一个文件，而不修改当前对应文件。

@item 打印窗口

通过默认打印机打印当前窗口。

@item 关闭窗口

关闭当前窗口（如果是未保存的编辑器窗口，则会提示保存；如果是未保存的 Shell 窗口，则会提示退出执行）。 在Shell 窗口中调用 @code{exit()} 或 @code{close()} 也会关闭 Shell 窗口。 如果这是唯一的窗口，则还会退出 IDLE。

@item 退出 IDLE

关闭所有窗口并退出 IDLE (将提示保存未保存的编辑窗口）。
@end table

@node 编辑菜单（命令行和编辑器）,格式菜单（仅 window 编辑器）,文件菜单 （命令行和编辑器）,目录
@anchor{library/idle edit-menu-shell-and-editor}@anchor{32a9}
@subsubsection 编辑菜单（命令行和编辑器）



@table @asis

@item 撤销操作

撤销当前窗口的最近一次操作。最高可以撤回 1000 条操作记录。

@item 重做

重做当前窗口最近一次所撤销的操作。

@item 剪切

复制选区至系统剪贴板，然后删除选区。

@item 复制

复制选区至系统剪贴板。

@item 粘贴

插入系统剪贴板的内容至当前窗口。
@end table

剪贴板功能也可用于上下文目录。


@table @asis

@item 全选

选择当前窗口的全部内容。

@item 查找...

打开一个提供多选项的查找窗口。

@item 再次查找

重复上一次搜索（如果有的话）。

@item 查找选区

查找当前选中的字符串，如果存在

@item 在文件中查找...

打开文件查找对话框。将结果输出至新的输出窗口。

@item 替换...

打开 查找并替换 对话框。

@item 前往行

将光标移到所请求行的开头并使该行可见。 对于超过文件尾的请求将会移到文件尾。 清除所有选区并更新行列状态。

@item 提示完成

打开一个可滚动列表以允许选择现有的名称。 请参阅下面编辑与导航一节中的 @ref{32aa,,自动补全}。

@item 展开文本

展开键入的前缀以匹配同一窗口中的完整单词；重复以获得不同的扩展。

@item 显示调用贴士

在函数的右括号后，打开一个带有函数参数提示的小窗口。请参阅下面的“编辑和导航”部分中的 @ref{32ab,,Calltips} 。

@item 显示周围括号

突出显示周围的括号。
@end table

@node 格式菜单（仅 window 编辑器）,运行菜单（仅 window 编辑器）,编辑菜单（命令行和编辑器）,目录
@anchor{library/idle format-menu}@anchor{32ac}@anchor{library/idle format-menu-editor-window-only}@anchor{32ad}
@subsubsection 格式菜单（仅 window 编辑器）



@table @asis

@item 增加缩进

将选定的行右缩进（默认为4个空格）。

@item 减少缩进

将选定的行左缩进（默认为4个空格）。

@item 注释

在所选行的前面插入 ##。

@item 取消注释

从所选行中删除开头的 ＃ 或 ##。

@item 制表符化

将 @emph{前导} 空格变成制表符。 （注意：我们建议使用4个空格来缩进Python代码。）

@item 取消制表符化

将 @emph{所有} 制表符转换为正确的空格数。

@item 缩进方式切换

打开一个对话框，以在制表符和空格之间切换。

@item 缩进宽度调整

打开一个对话框以更改缩进宽度。 Python社区接受的默认值为4个空格。

@item 格式段落

在注释块或多行字符串或字符串中的选定行中，重新格式化当前以空行分隔的段落。段落中的所有行的格式都将少于N列，其中N默认为72。

@item 删除尾随空格

通过将 str.rstrip 应用于每行（包括多行字符串中的行），删除行尾非空白字符之后的尾随空格和其他空白字符。除Shell窗口外，在文件末尾删除多余的换行符。
@end table

@geindex Run script

@node 运行菜单（仅 window 编辑器）,Shell 菜单（仅 window 编辑器）,格式菜单（仅 window 编辑器）,目录
@anchor{library/idle run-menu-editor-window-only}@anchor{32ae}
@subsubsection 运行菜单（仅 window 编辑器）

@anchor{library/idle run-module}@anchor{32af}

@table @asis

@item 运行模块

执行 @ref{32b0,,检查模块} 。如果没有错误，重新启动 shell 以清理环境，然后执行模块。输出显示在 shell 窗口中。请注意，输出需要使用 “打印” 或 “写入”。执行完成后，Shell 将保留焦点并显示提示。此时，可以交互地探索执行的结果。这类似于在命令行执行带有 @code{python -i file} 的文件。
@end table
@anchor{library/idle run-custom}@anchor{32b1}

@table @asis

@item 运行... 定制

与 @ref{32af,,运行模块} 相同，但使用自定义设置运行该模块。@emph{命令行参数} 扩展 @ref{cce,,sys.argv} ，就像在命令行上传递一样。该模块可以在命令行管理程序中运行，而无需重新启动。
@end table
@anchor{library/idle check-module}@anchor{32b0}

@table @asis

@item 检查模块

检查 “编辑器” 窗口中当前打开的模块的语法。如果尚未保存该模块，则 IDLE会提示用户保存或自动保存，如在 “空闲设置” 对话框的 “常规” 选项卡中所选择的那样。如果存在语法错误，则会在 “编辑器” 窗口中指示大概位置。
@end table
@anchor{library/idle python-shell}@anchor{32b2}

@table @asis

@item Python Shell

打开或唤醒Python Shell窗口。
@end table

@node Shell 菜单（仅 window 编辑器）,调试菜单（仅 window 编辑器）,运行菜单（仅 window 编辑器）,目录
@anchor{library/idle shell-menu-shell-window-only}@anchor{32b3}
@subsubsection Shell 菜单（仅 window 编辑器）



@table @asis

@item 查看最近重启

将Shell窗口滚动到上一次Shell重启。

@item 重启Shell

重启 shell 以清理环境，重置显示和异常处理。

@item 上一条历史记录

循环浏览历史记录中与当前条目匹配的早期命令。

@item 下一条历史记录

循环浏览历史记录中与当前条目匹配的后续命令。

@item 中断执行

停止正在运行的程序。
@end table

@node 调试菜单（仅 window 编辑器）,选项菜单（命令行和编辑器）,Shell 菜单（仅 window 编辑器）,目录
@anchor{library/idle debug-menu-shell-window-only}@anchor{32b4}
@subsubsection 调试菜单（仅 window 编辑器）



@table @asis

@item 跳转到文件/行

查看当前行。 以光标提示，且上一行为文件名和行号。 如果找到目标，如果文件尚未打开则打开该文件，并显示目标行。 使用此菜单项来查看异常回溯中引用的源代码行以及用文件中查找功能找到的行。 也可在 Shell 窗口和 Output 窗口的上下文菜单中使用。
@end table

@geindex debugger
@geindex stack viewer


@table @asis

@item 调试器（切换）

激活后，在Shell中输入的代码或从编辑器中运行的代码将在调试器下运行。在编辑器中，可以使用上下文菜单设置断点。此功能不完整，具有实验性。

@item 堆栈查看器

在树状目录中显示最后一个异常的堆栈回溯，可以访问本地和全局。

@item 自动打开堆栈查看器

在未处理的异常上切换自动打开堆栈查看器。
@end table

@node 选项菜单（命令行和编辑器）,Window 菜单（命令行和编辑器）,调试菜单（仅 window 编辑器）,目录
@anchor{library/idle options-menu-shell-and-editor}@anchor{32b5}
@subsubsection 选项菜单（命令行和编辑器）



@table @asis

@item 配置 IDLE

打开配置对话框并更改以下各项的首选项：字体、缩进、键绑定、文本颜色主题、启动窗口和大小、其他帮助源和扩展名。在MacOS上，通过在应用程序菜单中选择首选项来打开配置对话框。有关详细信息，请参阅：帮助和首选项下的 @ref{32b6,,首选项设置}。
@end table

大多数配置选项适用于所有窗口或将来的所有窗口。以下选项仅适用于活动窗口。


@table @asis

@item 显示/隐藏代码上下文（仅 window 编辑器）

在编辑窗口顶部打开一个面板来显示在窗口顶部滚动的代码块上下文。 请参阅下文“编辑与导航”章节中的 @ref{32b7,,代码上下文}。

@item 显示/隐藏行号（仅 window 编辑器）

在编辑窗口左侧打开一个显示代码文本行编号的列。 默认为关闭显示，这可以在首选项中修改 (参见 @ref{32b6,,设置首选项})。

@item 缩放/还原高度

在窗口的正常尺寸和最大高度之间进行切换。 初始尺寸默认为 40 行每行 80 字符，除非在配置 IDLE 对话框的通用选项卡中做了修改。 屏幕的最大高度由首次在屏幕上将缩小的窗口最大化的操作来确定。 改变屏幕设置可能使保存的高度失效。 此切换操作在窗口最大化状态下无效。
@end table

@node Window 菜单（命令行和编辑器）,帮助菜单（命令行和编辑器）,选项菜单（命令行和编辑器）,目录
@anchor{library/idle window-menu-shell-and-editor}@anchor{32b8}
@subsubsection Window 菜单（命令行和编辑器）


列出所有打开的窗口的名称；选择一个将其带到前台（必要时对其进行去符号化）。

@node 帮助菜单（命令行和编辑器）,上下文菜单,Window 菜单（命令行和编辑器）,目录
@anchor{library/idle help-menu-shell-and-editor}@anchor{32b9}
@subsubsection 帮助菜单（命令行和编辑器）



@table @asis

@item 关于 IDLE

显示版本，版权，许可证，荣誉等。

@item IDLE 帮助

显示此 IDLE 文档，详细介绍菜单选项，基本编辑和导航以及其他技巧。

@item Python 文档

访问本地Python文档（如果已安装），或启动Web浏览器并打开docs.python.org显示最新的Python文档。

@item 海龟演示

使用示例 Python 代码运行 turtledemo 模块和海龟绘图
@end table

可以在 “常规” 选项卡下的 “配置IDLE” 对话框中添加其他帮助源。有关“帮助”菜单选项的更多信息，请参见下面的 @ref{32ba,,帮助源} 小节。

@geindex Cut
@geindex Copy
@geindex Paste
@geindex Set Breakpoint
@geindex Clear Breakpoint
@geindex breakpoints

@node 上下文菜单,,帮助菜单（命令行和编辑器）,目录
@anchor{library/idle context-menus}@anchor{32bb}
@subsubsection 上下文菜单


通过在窗口中右击（在 macOS 上则为按住 Control 键点击）来打开一个上下文菜单。 上下文菜单也具有编辑菜单中的标准剪贴板功能。


@table @asis

@item 剪切

复制选区至系统剪贴板，然后删除选区。

@item 复制

复制选区至系统剪贴板。

@item 粘贴

插入系统剪贴板的内容至当前窗口。
@end table

编辑器窗口也具有断点功能。 设置了断点的行会被特别标记。 断点仅在启用调试器运行时有效。 文件的断点会被保存在用户的 @code{.idlerc} 目录中。


@table @asis

@item 设置断点

在当前行设置断点

@item 清除断点

清除当前行断点
@end table

shell 和输出窗口还具有以下内容。


@table @asis

@item 跳转到文件/行

与调试菜单相同。
@end table

Shell 窗口也有一个输出折叠功能，参见下文的 @emph{Python Shell 窗口} 小节。


@table @asis

@item 压缩

如果将光标位于输出行上，则会折叠在上方代码和下方提示直到 'Squeezed text' 标签之间的所有输出。
@end table

@node 编辑和导航,启动和代码执行,目录,IDLE<52>
@anchor{library/idle editing-and-navigation}@anchor{32bc}@anchor{library/idle id2}@anchor{32bd}
@subsubsection 编辑和导航


@menu
* 编辑窗口:: 
* 按键绑定:: 
* 自动缩进:: 
* 完成:: 
* 提示:: 
* 代码上下文:: 
* Python Shell 窗口:: 
* 文本颜色:: 

@end menu

@node 编辑窗口,按键绑定,,编辑和导航
@anchor{library/idle editor-windows}@anchor{32be}
@subsubsection 编辑窗口


IDLE 可以在启动时打开编辑器窗口，这取决于选项设置和你启动 IDLE 的方式。 在此之后，请使用 File 菜单。 对于给定的文件只能打开一个编辑器窗口。

标题栏包含文件名称、完整路径，以及运行该窗口的 Python 和 IDLE 版本。 状态栏包含行号 ('Ln') 和列号 ('Col')。 行号从 1 开始；列号则从 0 开始。

IDE 会定扩展名为 .py* 的文件包含 Python 代码而其他文件不包含。 可使用 Run 菜单来运行 Python 代码。

@node 按键绑定,自动缩进,编辑窗口,编辑和导航
@anchor{library/idle key-bindings}@anchor{32bf}
@subsubsection 按键绑定


在本节中，'C' 是指 Windows 和 Unix 上的 @code{Control} 键，以及 macOS 上的 @code{Command} 键。


@itemize *

@item 
@code{Backspace} 向左删除; @code{Del} 向右删除

@item 
@code{C-Backspace} 向左删除单词; @code{C-Del} 向右删除单词

@item 
方向键和 @code{Page Up}/@code{Page Down} 移动

@item 
@code{C-LeftArrow} 和 @code{C-RightArrow} 按单词移动

@item 
@code{Home}/@code{End} 跳转到行首/尾

@item 
@code{C-Home}/@code{C-End} 跳转到文档首/尾

@item 
一些有用的Emacs绑定是从Tcl / Tk继承的：

@quotation


@itemize *

@item 
@code{C-a} 行首

@item 
@code{C-e} 行尾

@item 
@code{C-k} 删除行（但未将其放入剪贴板）

@item 
@code{C-l} 将插入点设为窗口中心

@item 
@code{C-b} 后退一个字符而不删除该字符（通常你也可以用方向键进行此操作）

@item 
@code{C-f} 前进一个字符而不删除该字符（通常你也可以用方向键进行此操作）

@item 
@code{C-p} 向上一行（通常你也可以用方向键进行此操作）

@item 
@code{C-d} 删除下一个字符
@end itemize
@end quotation
@end itemize

标准的键绑定（例如 @code{C-c} 复制和 @code{C-v} 粘贴）仍会有效。 键绑定可在配置 IDLE 对话框中选择。

@node 自动缩进,完成,按键绑定,编辑和导航
@anchor{library/idle automatic-indentation}@anchor{32c0}
@subsubsection 自动缩进


在一个代码块开头的语句之后，下一行会缩进 4 个空格符（在 Python Shell 窗口中是一个制表符）。 在特定关键字之后（break, return 等），下一行将不再缩进。 在开头的缩进中，按 @code{Backspace} 将会删除 4 个空格符。 @code{Tab} 则会插入空格符（在 Python Shell 窗口中是一个制表符），具体数量取决于缩进宽度。 目前，Tab 键按照 Tcl/Tk 的规定设置为四个空格符。

另请参阅 @ref{32ac,,Format 菜单} 的缩进/取消缩进区的命令。

@node 完成,提示,自动缩进,编辑和导航
@anchor{library/idle completions}@anchor{32aa}@anchor{library/idle id3}@anchor{32c1}
@subsubsection 完成


当被请求并且可用时，将为模块名、类属性、函数或文件名提供补全。 每次请求方法将显示包含现有名称的补全提示框。 （例外情况参见下文的 Tab 补全。） 对于任意提示框，要改变被补全的名称和提示框中被高亮的条目，可以通过输入和删除字符、按 @code{Up}, @code{Down}, @code{PageUp}, @code{PageDown}, @code{Home} 和 @code{End} 键；或是在提示框中单击。 要关闭补全提示框可以通过 @code{Escape}, @code{Enter} 或按两次 @code{Tab} 键或是在提示框外单击。 在提示框内双击则将执行选择并关闭。

有一种打开提示框的方式是输入一个关键字符并等待预设的一段间隔。 此间隔默认为 2 秒；这可以在设置对话框中定制。 （要防止自动弹出，可将时延设为一个很大的豪秒数值，例如 100000000。） 对于导入的模块名或者类和函数属性，请输入 '.'。 对于根目录下的文件名，请在开头引号之后立即输入 @ref{1e1c,,os.sep} 或 @ref{1e1d,,os.altsep}。 （在 Windows 下，可以先指定一个驱动器。） 可通过输入目录名和分隔符来进入子目录。

除了等待，或是在提示框关闭之后，可以使用 Edit 菜单的 Show Completions 来立即打开一个补全提示框。 默认的热键是 @code{C-space}。 如果在打开提示框之前输入一某个名称的前缀，则将显示第一个匹配项或最接近的项。 结果将与在提示框已显示之后输入前缀时相同。 在一个引号之后执行 Show Completions 将会实例当前目录下的文件名而不是根目录下的。

在输入前缀后按 @code{Tab} 键的效果通常与 Show Completions 相同。 （如果未输入前缀则为缩进。） 但是，如果输入的前缀只有一个匹配项，则该匹配项会立即被添加到编辑器文本中而不打开补全提示框。

在字符串以外且开头不带 '.' 地输入前缀并执行 'Show Completions' 或按 @code{Tab} 键将打开一个包含关键字、内置名称和现有模块级名称的补全提示框。

当在编辑器（而非 Shell）中编辑代码时，可以通过运行你的代码并在此后不重启 Shell 来增加可用的模块级名称。 这在文件顶部添加了导入语句之后会特别有用。 这还会增加可用的属性补全。

补全提示框在初始时会排除以 '_' 打头的名称，对于模块还会排除未包括在 '__all__' 中的名称。 这些隐藏名称可通过在 '.' 之后输入 '_' 来访问，这在提示框打开之前或之后都是有效的。

@node 提示,代码上下文,完成,编辑和导航
@anchor{library/idle calltips}@anchor{32ab}@anchor{library/idle id4}@anchor{32c2}
@subsubsection 提示


当在一个 @emph{可用的} 函数名称之后输入 @code{(} 时将自动显示一个调用提示。 函数名称表达式可以包括点号和方括号索引操作。 调用提示将保持打开直到它被点击、光标移出参数区、或是输入了 @code{)}。 当光标位于某个定义的参数区时，可以在菜单中选择 Edit 的 "Show Call Tip" 或是输入其快捷键来显示调用提示。

调用提示是由函数的签名和文档字符串到第一个空行或第五个非空行为止的内容组成的。 （某些内置函数没有可访问的签名。） 签名中的 '/' 或 '*' 指明其前面或后面的参数仅限以位置或名称（关键字）方式传入。 具体细节可能会改变。

在 Shell 中，可访问的函数取决于有哪些模块已被导入用户进程，包括由 IDLE 本身导入的模块，以及哪些定义已被运行，以上均从最近的重启动开始算起。

例如，重启动 Shell 并输入 @code{itertools.count(}。 将显示调用提示，因为 IDLE 出于自身需要已将 itertools 导入了用户进程。 （此行为可能会改变。） 输入 @code{turtle.write(} 则不显示任何提示。 因为 IDLE 本身不会导入 turtle。 菜单项和快捷键同样不会有任何反应。 输入 @code{import turtle}。 则在此之后，@code{turtle.write(} 将显示调用提示。

在编辑器中，import 语句在文件运行之前是没有效果的。 在输入 import 语句之后、添加函数定义之后，或是打开一个现有文件之后可以先运行一下文件。

@node 代码上下文,Python Shell 窗口,提示,编辑和导航
@anchor{library/idle code-context}@anchor{32b7}@anchor{library/idle id5}@anchor{32c3}
@subsubsection 代码上下文


在一个包含 Python 代码的编辑器窗口内部，可以切换代码上下文以便显示或隐藏窗口顶部的面板。 当显示时，此面板可以冻结代码块的开头行，例如以 @code{class}, @code{def} 或 @code{if} 关键字开头的行，这样的行在不显示时面板时可能离开视野。 此面板的大小将根据需要扩展和收缩以显示当前层级的全部上下文，直至达到配置 IDLE 对话框中所定义的最大行数（默认为 15）。 如果如果没有当前上下文行而此功能被启用，则将显示一个空行。 点击上下文面板中的某一行将把该行移至编辑器顶部。

上下文面板的文本和背景颜色可在配置 IDLE 对话框的 Highlights 选项卡中进行配置。

@node Python Shell 窗口,文本颜色,代码上下文,编辑和导航
@anchor{library/idle python-shell-window}@anchor{32c4}
@subsubsection Python Shell 窗口


通过 IDLE 的 Shell 可以输入、编辑和召回整条语句。 大部分控制台和终端在同一时刻只能处理单个物理行。

当向 Shell 粘贴代码时，它并不会被编译和执行，直到按下 @code{Return} 键。 在此之前可以先编辑所粘贴的代码。 如果向 Shell 粘贴了多行代码，多条语句会被当作一条语句来编译，结果将引发 @ref{562,,SyntaxError}。

之前小节中描述的编辑功能在交互式地输入代码时也可使用。 IDLE 的 Shell 窗口还会响应以下按键。


@itemize *

@item 
@code{C-c} 中断执行命令

@item 
@code{C-d} 发送文件结束命令；如果在 @code{>>>} 提示符后按下会关闭窗口。

@item 
@code{Alt-/} (扩展单词) 也有助于减少输入量

历史命令


@itemize *

@item 
@code{Alt-p} 提取与你所输入键匹配的前一条命令。 在 macOS 上请使用 @code{C-p}。

@item 
@code{Alt-n} 提取下一条命令。 在 macOS 上请使用 @code{C-n}。

@item 
在任意的前一条命令上按 @code{Return} 将提取该命令
@end itemize
@end itemize

@node 文本颜色,,Python Shell 窗口,编辑和导航
@anchor{library/idle text-colors}@anchor{32c5}
@subsubsection 文本颜色


IDLE 文本默认为白底黑字，但有特殊含义的文本将以彩色显示。 对于 Shell 来说包括 Shell 输出，Shell 错误，用户输出和用户错误。 对于 Shell 提示符下或编辑器中的 Python 代码来说则包括关键字，内置类和函数名称，@code{class} 和 @code{def} 之后的名称，字符串和注释等。 对于任意文本窗口来说则包括光标（如果存在）、找到的文本（如果可能）和选定的文本。

广西着色是在背景上完成的，因此有时会看到非着色的文本。 要改变颜色方案，请使用配置 IDLE 对话框的高亮选项卡。 编辑器中的调试器断点行标记和弹出面板和对话框中的文本则是用户不可配置的。

@node 启动和代码执行,帮助和偏好,编辑和导航,IDLE<52>
@anchor{library/idle startup-and-code-execution}@anchor{32c6}
@subsubsection 启动和代码执行


在附带 @code{-s} 选项启用的情况下，IDLE 将会执行环境变量 
@geindex IDLESTARTUP
@geindex 环境变量; IDLESTARTUP
@code{IDLESTARTUP} 或 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 所引用的文件。 IDLE 会先检查 @code{IDLESTARTUP}；如果 @code{IDLESTARTUP} 存在则会运行被引用的文件。 如果 @code{IDLESTARTUP} 不存在，则 IDLE 会检查 @code{PYTHONSTARTUP}。 这些环境变量所引用的文件是存放经常被 IDLE Shell 所使用的函数，或者执行导入常用模块的 import 语句的便捷场所。

此外，@code{Tk} 也会在存在启动文件时加载它。 请注意 Tk 文件会被无条件地加载。 此附加文件名为 @code{.Idle.py} 并且会在用户的家目录下查找。 此文件中的语句将在 Tk 的命名空间中执行，所以此文件不适用于导入要在 IDLE 的 Python Shell 中使用的函数。

@menu
* 命令行语法:: 
* 启动失败:: 
* 运行用户代码:: 
* Shell中的用户输出:: 
* 开发 tkinter 应用程序:: 
* 在没有子进程的情况下运行:: 

@end menu

@node 命令行语法,启动失败,,启动和代码执行
@anchor{library/idle command-line-usage}@anchor{32c7}
@subsubsection 命令行语法


@example
idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

-c command  run command in the shell window
-d          enable debugger and open shell window
-e          open editor window
-h          print help message with legal combinations and exit
-i          open shell window
-r file     run file in shell window
-s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
-t title    set title of shell window
-           run stdin in shell (- must be last option before args)
@end example

如果有参数：


@itemize *

@item 
如果使用了 @code{-}, @code{-c} 或 @code{r}，则放在 @code{sys.argv[1:...]} 和 @code{sys.argv[0]} 中的所有参数都会被设为 @code{'@w{'}}, @code{'-c'} 或 @code{'-r'}。 不会打开任何编辑器窗口，即使是在选项对话框中的默认设置。

@item 
在其他情况下，参数为要打开编辑的文件而 @code{sys.argv} 反映的是传给 IDLE 本身的参数。
@end itemize

@node 启动失败,运行用户代码,命令行语法,启动和代码执行
@anchor{library/idle startup-failure}@anchor{32c8}
@subsubsection 启动失败


IDLE 使用一个套接字在 IDLE GUI 进程和用户代码执行进程之间通信。 当 Shell 启动或重启动时必须建立一个连接。 （重启动会以一个内容为 'RESTART' 的分隔行来标示）。 如果用户进程无法连接到 GUI 进程，它通常会显示一个包含 'cannot connect' 消息的  @code{Tk} 错误提示框来引导用户。 随后将会退出程序。

有一个 Unix 系统专属的连接失败是由系统网络设置中错误配置的掩码规则导致的。 当从一个终端启动 IDLE 时，用户将看到一条以 @code{** Invalid host:} 开头的消息。 有效的值为 @code{127.0.0.1 (idlelib.rpc.LOCALHOST)}。 用户可以在一个终端窗口输入 @code{tcpconnect -irv 127.0.0.1 6543} 并在另一个终端窗口中输入 @code{tcplisten <same args>} 来进行诊断。

导致连接失败的一个常见原因是用户创建的文件与标准库模块同名，例如 @emph{random.py} 和 @emph{tkinter.py}。 当这样的文件与要运行的文件位于同一目录中时，IDLE 将无法导入标准库模块。 可用的解决办法是重命名用户文件。

虽然现在已不太常见，但杀毒软件或防火墙程序也有可能会阻止连接。 如果无法将此类程序设为允许连接，那么为了运行 IDLE 就必须将其关闭。 允许这样的内部连接是安全的，因为数据在外部端口上不可见。 一个类似的问题是错误的网络配置阻止了连接。

Python 的安装问题有时会使 IDLE 退出：存在多个版本时可能导致程序崩溃，或者单独安装时可能需要管理员权限。 如果想要避免程序崩溃，或是不想以管理员身份运行，最简单的做法是完全卸载 Python 并重新安装。

有时会出现 pythonw.exe 僵尸进程问题。 在 Windows 上，可以使用任务管理员来检查并停止该进程。 有时由程序崩溃或键盘中断（control-C）所发起的重启动可能会出现连接失败。 关闭错误提示框或使用 Shell 菜单中的 Restart Shell 可能会修复此类临时性错误。

当 IDLE 首次启动时，它会尝试读取 @code{~/.idlerc/} 中的用户配置文件（~ 是用户的家目录）。 如果配置有问题，则应当显示一条错误消息。 除随机磁盘错误之外，此类错误均可通过不手动编辑这些文件来避免。 请使用 Options 菜单来打开配置对话框。 一旦用户配置文件出现错误，最好的解决办法就是删除它并使用配置对话框重新设置。

如果 IDLE 退出时没有发出任何错误消息，并且它不是通过控制台启动的，请尝试通过控制台或终端 (@code{python -m idlelib}) 来启动它以查看是否会出现错误消息。

在基于 Unix 的系统上使用 tcl/tk 低于 @code{8.6.11} 的版本 (查看 @code{About IDLE}) 时特定字体的特定字符可能导致终端提示 tk 错误消息。 这可能发生在启动 IDLE 编辑包此种字符的文件或是在之后输入此种字符的时候。 如果无法升级 tcl/tk，可以重新配置 IDLE 来使用其他的字体。

@node 运行用户代码,Shell中的用户输出,启动失败,启动和代码执行
@anchor{library/idle running-user-code}@anchor{32c9}
@subsubsection 运行用户代码


除了少量例外，使用 IDLE 执行 Python 代码的结果应当与使用默认方法，即在文本模式的系统控制台或终端窗口中直接通过 Python 解释器执行同样的代码相同。 但是，不同的界面和操作有时会影响显示的结果。 例如，@code{sys.modules} 初始时具有更多条目，而 @code{threading.active_count()} 将返回 2 而不是 1。

在默认情况下，IDLE 会在单独的 OS 进程中运行用户代码而不是在运行 Shell 和编辑器的用户界面进程中运行。 在执行进程中，它会将 @code{sys.stdin}, @code{sys.stdout} 和 @code{sys.stderr} 替换为从 Shell 窗口获取输入并向其发送输出的对象。 保存在 @code{sys.__stdin__}, @code{sys.__stdout__} 和 @code{sys.__stderr__} 中的原始值不会被改变，但可能会为 @code{None}。

将打印输出从一个进程发送到另一个进程中的文本部件要比打印到同一个进程中的系统终端慢。 这在打印多个参数时将有更明显的影响，因为每个参数、每个分隔符和换行符对应的字符串都要单独发送。 在开发中，这通常不算是问题，但如果希望能在 IDLE 中更快地打印，可以将想要显示的所有内容先格式化并拼接到一起然后打印单个字符串。 格式字符串和 @ref{1796,,str.join()} 都可以被用于合并字段和文本行。

IDLE 的标准流替换不会被执行进程中创建的子进程所继承，不论它是由用户代码直接创建还是由 multiprocessing 之类的模块创建的。 如果这样的子进程使用了 @code{input} 获取 sys.stdin 或者使用了 @code{print} 或 @code{write} 输出到 sys.stdout 或 sys.stderr，则应当在命令行窗口中启动 IDLE。 这样二级子进程将会被附加到该窗口进行输出和输出。

如果 @code{sys} 被用户代码重置，例如使用了 @code{importlib.reload(sys)}，则 IDLE 的修改将丢失，来自键盘的输入和向屏幕的输出将无法正确运作。

当 Shell 获得焦点时，它将控制键盘与屏幕。 这通常会保持透明，但一些直接访问键盘和屏幕的函数将会不起作用。 这也包括那些确定是否有键被按下以及是哪个键被按下的系统专属函数。

在执行进程中运行的 IDLE 代码会向调用栈添加在其他情况下不存在的帧。 IDLE 包装了 @code{sys.getrecursionlimit} 和 @code{sys.setrecursionlimit} 以减少额外栈帧的影响。

当用户代码直接或者通过调用 sys.exit 引发 SystemExit 时，IDLE 将返回 Shell 提示符而非完全退出。

@node Shell中的用户输出,开发 tkinter 应用程序,运行用户代码,启动和代码执行
@anchor{library/idle user-output-in-shell}@anchor{32ca}
@subsubsection Shell中的用户输出


当一个程序输出文本时，结果将由相应的输出设备来确定。 当 IDLE 执行用户代码时，@code{sys.stdout} 和 @code{sys.stderr} 会被连接到 IDLE Shell 的显示区。 它的某些特性是从底层的 Tk Text 部件继承而来。 其他特性则是程序所添加的。 总之，Shell 被设计用于开发环境而非生产环境运行。

例如，Shell 绝不会丢弃输出。 一个向 Shell 发送无限输出的程序将最终占满内存，导致内存错误。 作为对比，某些系统文本模式窗口只会保留输出的最后 n 行。 例如，Windows 控制台可由用户设置保留 1 至 9999 行，默认为 300 行。

A Tk Text widget, and hence IDLE's Shell, displays characters (codepoints) in
the BMP (Basic Multilingual Plane) subset of Unicode.  Which characters are
displayed with a proper glyph and which with a replacement box depends on the
operating system and installed fonts.  Tab characters cause the following text
to begin after the next tab stop. (They occur every 8 'characters').  Newline
characters cause following text to appear on a new line.  Other control
characters are ignored or displayed as a space, box, or something else,
depending on the operating system and font.  (Moving the text cursor through
such output with arrow keys may exhibit some surprising spacing behavior.)

@example
>>> s = 'a\tb\a<\x02><\r>\bc\nd'  # Enter 22 chars.
>>> len(s)
14
>>> s  # Display repr(s)
'a\tb\x07<\x02><\r>\x08c\nd'
>>> print(s, end='@w{'})  # Display s as is.
# Result varies by OS and font.  Try it.
@end example

@code{repr} 函数会被用于表达式值的交互式回显。 它将返回输入字符串的一个修改版本，其中的控制代码、部分 BMP 码位以及所有非 BMP 码位都将被替换为转义代码。 如上面所演示的，它使用户可以辨识字符串中的字符，无论它们会如何显示。

普通的与错误的输出通常会在与代码输入和彼此之间保持区分 (显示于不同的行)。 它们也会分别使用不同的高亮颜色。

对于 SyntaxError 回溯信息，表示检测到错误位置的正常 '^' 标记被替换为带有代表错误的文本颜色高亮。 当从文件运行的代码导致了其他异常时，用户可以右击回溯信息行在 IDLE 编辑器中跳转到相应的行。 如有必要将打开相应的文件。

Shell 具有将输出行折叠为一个 'Squeezed text' 标签的特殊功能。 此功能将自动应用于超过 N 行的输出 (默认 N = 50)。 N 可以在设置对话框中 General 页的 PyShell 区域中修改。 行数更少的输出也可通过在输出上右击来折叠。 此功能适用于过多的输出行数导致滚动操作变慢的情况。

已折叠的输出可通过双击该标签来原地展开。 也可通过右击该标签将其发送到剪贴板或单独的查看窗口。

@node 开发 tkinter 应用程序,在没有子进程的情况下运行,Shell中的用户输出,启动和代码执行
@anchor{library/idle developing-tkinter-applications}@anchor{32cb}
@subsubsection 开发 tkinter 应用程序


IDLE 有意与标准 Python 保持区别以方便 tkinter 程序的开发。 在标准 Python 中输入 @code{import tkinter as tk; root = tk.Tk()} 不会显示任何东西。 在 IDLE 中输入同样的代码则会显示一个 tk 窗口。 在标准 Python 中，还必须输入 @code{root.update()} 才会将窗口显示出来。 IDLE 会在幕后执行同样的方法，每秒大约 20 次，即每隔大约 50 毫秒。 下面输入 @code{b = tk.Button(root, text='button'); b.pack()}。 在标准 Python 中仍然不会有任何可见的变化，直到输入 @code{root.update()}。

大多数 tkinter 程序都会运行 @code{root.mainloop()}，它通常直到 tk 应用被销毁时才会返回。 如果程序是通过 @code{python -i} 或 IDLE 编辑器运行的，则 @code{>>>} Shell 提示符将直到 @code{mainloop()} 返回时才会出现，这时将结束程序的交互。

当通过 IDLE 编辑器运行 tkinter 程序时，可以注释掉 mainloop 调用。 这样将立即回到 Shell 提示符并可与正在运行的应用程序交互。 请记得当在标准 Python 中运行时重新启用 mainloop 调用。

@node 在没有子进程的情况下运行,,开发 tkinter 应用程序,启动和代码执行
@anchor{library/idle running-without-a-subprocess}@anchor{32cc}
@subsubsection 在没有子进程的情况下运行


By default, IDLE executes user code in a separate subprocess via a socket,
which uses the internal loopback interface.  This connection is not
externally visible and no data is sent to or received from the Internet.
If firewall software complains anyway, you can ignore it.

如果创建套接字连接的尝试失败，IDLE 将会通知你。 这样的失败可能是暂时性的，但是如果持续存在，问题可能是防火墙阻止了连接或某个系统配置错误。 在问题得到解决之前，可以使用 -n 命令行开关来运行 IDLE。

如果 IDLE 启动时使用了 -n 命令行开关则它将在单个进程中运行并且将不再创建运行 RPC Python 执行服务器的子进程。 这适用于 Python 无法在你的系统平台上创建子进程或 RPC 套接字接口的情况。 但是，在这种模式下用户代码没有与 IDLE 本身相隔离。 而且，当选择 Run/Run Module (F5) 时运行环境也不会重启。 如果你的代码已被修改，你必须为受影响的模块执行 reload() 并重新导入特定的条目 (例如 from foo import baz) 才能让修改生效。 出于这些原因，在可能的情况下最好还是使用默认的子进程来运行 IDLE。


3.4 版后已移除.


@node 帮助和偏好,,启动和代码执行,IDLE<52>
@anchor{library/idle help-and-preferences}@anchor{32cd}
@subsubsection 帮助和偏好


@menu
* 帮助源:: 
* 首选项设置:: 
* macOS 上的IDLE:: 
* 扩展:: 

@end menu

@node 帮助源,首选项设置,,帮助和偏好
@anchor{library/idle help-sources}@anchor{32ba}@anchor{library/idle id6}@anchor{32ce}
@subsubsection 帮助源


Help 菜单项 "IDLE Help" 会显示标准库参考中 IDLE 一章的带格式 HTML 版本。 这些内容放在只读的 tkinter 文本窗口中，与在浏览器中看到的内容类似。 可使用鼠标滚轮、滚动条或上下方向键来浏览文本。 或是点击 TOC (Table of Contents) 按钮并在打开的选项框中选择一个节标题。

Help 菜单项 "Python Docs" 会打开更丰富的帮助源，包括教程，通过 @code{docs.python.org/x.y} 来访问，其中 'x.y' 是当前运行的 Python 版本。 如果你的系统有此文档的离线副本 (这可能是一个安装选项)，则将打开这个副本。

选定的 URL 可以使用配置 IDLE 对话框的 General 选项卡随时在帮助菜单中添加或移除。

@node 首选项设置,macOS 上的IDLE,帮助源,帮助和偏好
@anchor{library/idle preferences}@anchor{32b6}@anchor{library/idle setting-preferences}@anchor{32cf}
@subsubsection 首选项设置


字体首选项、高亮、按键和通用首选项可通过 Option 菜单的配置 IDLE 项来修改。 非默认的用户设置将保存在用户家目录下的 @code{.idlerc} 目录中。 用户配置文件错误导致的问题可通过编辑或删除 @code{.idlerc} 中的一个或多个文件来解决。

在 Font 选项卡中，可以查看使用多种语言的多个字符的示例文本来了解字体或字号效果。 可以编辑示例文本来添加想要的其他字符。 请使用示例文本选择等宽字体。 如果某些字符在 Shell 或编辑器中的显示有问题，可以将它们添加到示例文本的开头并尝试改变字号和字体。

在 Highlights 和 Keys 选项卡中，可以选择内置或自定义的颜色主题和按键集合。 要将更新的内置颜色主题或按键集合与旧版 IDLE 一起使用，可以将其保存为新的自定义主题或按键集合就将可在旧版 IDLE 中使用。

@node macOS 上的IDLE,扩展,首选项设置,帮助和偏好
@anchor{library/idle idle-on-macos}@anchor{32d0}
@subsubsection macOS 上的IDLE


在 System Preferences: Dock 中，可以将 "Prefer tabs when opening documents" 设为 "Always"。 但是该设置不能兼容 IDLE 所使用的 tk/tkinter GUI 框架，并会使得部分 IDLE 特性失效。

@node 扩展,,macOS 上的IDLE,帮助和偏好
@anchor{library/idle extensions}@anchor{32d1}
@subsubsection 扩展


IDLE 可以包含扩展插件。 扩展插件的首选项可通过首选项对话框的 Extensions 选项卡来修改。 请查看 idlelib 目录下 config-extensions.def 的开头来了解详情。 目前唯一的扩展插件是 zzdummy，它也是一个测试用的示例。

@c Other sections I have in mind are
@c Tkinter internals
@c Freezing Tkinter applications

@node 开发工具,调试和分析,Tk图形用户界面 GUI,Python 标准库
@anchor{library/development doc}@anchor{32d2}@anchor{library/development development}@anchor{32d3}@anchor{library/development development-tools}@anchor{32d4}
@section 开发工具


本章中描述的各模块可帮你编写 Python 程序。例如，@ref{d9,,pydoc} 模块接受一个模块并根据该模块的内容来生成文档。@ref{66,,doctest} 和 @ref{124,,unittest} 这两个模块包含了用于编写单元测试的框架，并可用于自动测试所编写的代码，验证预期的输出是否产生。@code{2to3} 程序能够将 Python 2.x 源代码翻译成有效的 Python 3.x 源代码。

本章中描述的模块列表是：

@menu
* typing: typing --- 类型提示支持. 类型提示支持
* pydoc: pydoc --- 文档生成器和在线帮助系统. 文档生成器和在线帮助系统
* Python 开发模式:: 
* Python 开发模式的效果:: 
* ResourceWarning 示例:: 
* 文件描述符错误示例:: 
* doctest: doctest --- 测试交互性的Python示例. 测试交互性的Python示例
* unittest: unittest --- 单元测试框架. 单元测试框架
* unittest.mock: unittest mock --- mock对象库. mock对象库
* unittest.mock 上手指南: unittest mock 上手指南. 
* 2to3 - 自动将 Python 2 代码转为 Python 3 代码:: 
* test: test --- Python回归测试包. Python回归测试包
* test.support: test support --- 针对 Python 测试套件的工具. 针对 Python 测试套件的工具
* test.support.socket_helper: test support socket_helper --- 用于套接字测试的工具. 用于套接字测试的工具
* test.support.script_helper: test support script_helper --- 用于 Python 执行测试工具. 用于 Python 执行测试工具
* test.support.bytecode_helper: test support bytecode_helper --- 用于测试正确字节码生成的支持工具. 用于测试正确字节码生成的支持工具

@end menu

@node typing --- 类型提示支持,pydoc --- 文档生成器和在线帮助系统,,开发工具
@anchor{library/typing doc}@anchor{32d5}@anchor{library/typing module-typing}@anchor{122}@anchor{library/typing typing-support-for-type-hints}@anchor{32d6}
@subsection @code{typing} --- 类型提示支持


@geindex typing (模块)


3.5 新版功能.


@strong{源码：} Lib/typing.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/typing.py}

@cartouche
@quotation 注解 
Python 运行时不强制执行函数和变量类型注解，但这些注解可用于类型检查器、IDE、静态检查器等第三方工具。
@end quotation
@end cartouche


__________________________________________________________________


这个模块提供对类型提示的运行时支持。最基本的支持包括 @ref{74f,,Any} , @ref{11b3,,Union} , @ref{27c,,Callable} , @ref{1098,,TypeVar} , 和 @ref{1055,,Generic} 。关于完整的规范，请参考 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 。关于类型提示的简化介绍，请参考 
@geindex Python 提高建议; PEP 483
PEP 483@footnote{https://www.python.org/dev/peps/pep-0483} 。

下面的函数接收与返回的都是字符串，注解方式如下：

@example
def greeting(name: str) -> str:
    return 'Hello ' + name
@end example

@code{greeting} 函数中，参数 @code{name} 的类型是 @ref{206,,str}，返回类型也是 @ref{206,,str}。子类型也可以当作参数。

新的功能频繁地被添加到 @code{typing} 模块中。typing_extensions@footnote{https://pypi.org/project/typing-extensions/} 包提供了这些新功能对旧版本 Python 的向后移植。

@menu
* 相关的 PEP:: 
* 类型别名:: 
* NewType:: 
* 可调对象（Callable）:: 
* 泛型（Generic）:: 
* 用户定义的泛型类型:: 
* Any 类型:: 
* 名义子类型 vs 结构子类型:: 
* 模块内容: 模块内容<7>. 

@end menu

@node 相关的 PEP,类型别名,,typing --- 类型提示支持
@anchor{library/typing id1}@anchor{32d7}@anchor{library/typing relevant-peps}@anchor{32d8}
@subsubsection 相关的 PEP


自从在 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 483
PEP 483@footnote{https://www.python.org/dev/peps/pep-0483} 中首次引入类型提示以来，一些 PEP 已经修改和增强了 Python 的类型注释框架。包括:


@itemize *

@item 

@table @asis

@geindex Python 提高建议; PEP 526

@item PEP 526@footnote{https://www.python.org/dev/peps/pep-0526}: 变量注解的语法

@emph{引入} 在函数定义之外标注变量的语法，以及 @ref{6a4,,ClassVar} 。
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 544

@item PEP 544@footnote{https://www.python.org/dev/peps/pep-0544}: Protocol：结构子类型（静态鸭子类型）。

@emph{引入} @ref{371,,Protocol} 和 @ref{372,,@@runtime_checkable} 装饰器。
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 585

@item PEP 585@footnote{https://www.python.org/dev/peps/pep-0585}: 标准集合中的类型提示泛型

@emph{引入} @ref{27d,,types.GenericAlias} 和使用标准库类作为 @ref{1030,,通用类型} 的能力。
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 586

@item PEP 586@footnote{https://www.python.org/dev/peps/pep-0586}: 文字类型

@emph{Introducing} @ref{276,,Literal}
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 589

@item PEP 589@footnote{https://www.python.org/dev/peps/pep-0589}: TypedDict: 具有固定键集的字典的类型提示

@emph{引入} @ref{36e,,TypedDict}
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 591

@item PEP 591@footnote{https://www.python.org/dev/peps/pep-0591}: 为 typing 添加最终限定符

@emph{引入} @ref{36f,,Final} 和 @ref{370,,@@final} 装饰器
@end table

@item 

@table @asis

@geindex Python 提高建议; PEP 593

@item PEP 593@footnote{https://www.python.org/dev/peps/pep-0593}: 灵活的函数和变量注解

@emph{Introducing} @ref{1ef,,Annotated}
@end table
@end itemize

@node 类型别名,NewType,相关的 PEP,typing --- 类型提示支持
@anchor{library/typing type-aliases}@anchor{32d9}
@subsubsection 类型别名


把类型赋给别名，就可以定义类型别名。本例中，@code{Vector} 和 @code{list[float]} 相同，可互换：

@example
Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
@end example

类型别名适用于简化复杂的类型签名。例如：

@example
from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...
@end example

注意，@code{None} 是一种类型提示特例，已被 @code{type(None)} 取代。

@node NewType,可调对象（Callable）,类型别名,typing --- 类型提示支持
@anchor{library/typing distinct}@anchor{32da}@anchor{library/typing newtype}@anchor{32db}
@subsubsection NewType


Use the @ref{6a6,,NewType()} helper to create distinct types:

@example
from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
@end example

静态类型检查器把新类型当作原始类型的子类，这种方式适用于捕捉逻辑错误：

@example
def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
@end example

@code{UserId} 类型的变量可执行所有 @code{int} 操作，但返回结果都是 @code{int} 类型。这种方式允许在预期 @code{int} 时传入 @code{UserId}，还能防止意外创建无效的 @code{UserId}：

@example
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
@end example

Note that these checks are enforced only by the static type checker. At runtime,
the statement @code{Derived = NewType('Derived', Base)} will make @code{Derived} a
callable that immediately returns whatever parameter you pass it. That means
the expression @code{Derived(some_value)} does not create a new class or introduce
any overhead beyond that of a regular function call.

更确切地说，在运行时，@code{some_value is Derived(some_value)} 表达式总为 True。

也就是说，不能创建 @code{Derived} 的子类型，因为，在运行时，它是标识函数，不是真正的类型：

@example
from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
@end example

然而，我们可以在 "派生的" @code{NewType} 的基础上创建一个 @ref{6a6,,NewType}。

@example
from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)
@end example

同时，@code{ProUserId} 的类型检查也可以按预期执行。

详见 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484}。

@cartouche
@quotation 注解 
回顾上文，类型别名声明了两种彼此 @emph{等价} 的类型。 @code{Alias = Original} 时，静态类型检查器认为 @code{Alias} 与 @code{Original} @emph{完全等价}。 这种方式适用于简化复杂类型签名。

反之，@code{NewType} 声明把一种类型当作另一种类型的 @emph{子类型}。@code{Derived = NewType('Derived', Original)} 时，静态类型检查器把 @code{Derived} 当作 @code{Original} 的 @emph{子类} ，即，@code{Original} 类型的值不能用在预期 @code{Derived} 类型的位置。这种方式适用于以最小运行时成本防止逻辑错误。
@end quotation
@end cartouche


3.5.2 新版功能.


@node 可调对象（Callable）,泛型（Generic）,NewType,typing --- 类型提示支持
@anchor{library/typing callable}@anchor{32dc}
@subsubsection 可调对象（Callable）


预期特定签名回调函数的框架可以用 @code{Callable[[Arg1Type, Arg2Type], ReturnType]} 实现类型提示。

例如：

@example
from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

async def on_update(value: str) -> None:
    # Body
callback: Callable[[str], Awaitable[None]] = on_update
@end example

无需指定调用签名，用省略号字面量替换类型提示里的参数列表： @code{Callable[..., ReturnType]}，就可以声明可调对象的返回类型。

@node 泛型（Generic）,用户定义的泛型类型,可调对象（Callable）,typing --- 类型提示支持
@anchor{library/typing generics}@anchor{15b7}@anchor{library/typing id2}@anchor{32dd}
@subsubsection 泛型（Generic）


容器中，对象的类型信息不能以泛型方式静态推断，因此，抽象基类扩展支持下标，用于表示容器元素的预期类型。

@example
from collections.abc import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...
@end example

typing 模块中推出的 @ref{1098,,TypeVar} 工厂函数实现泛型参数化。

@example
from collections.abc import Sequence
from typing import TypeVar

T = TypeVar('T')      # Declare type variable

def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]
@end example

@node 用户定义的泛型类型,Any 类型,泛型（Generic）,typing --- 类型提示支持
@anchor{library/typing user-defined-generic-types}@anchor{32de}@anchor{library/typing user-defined-generics}@anchor{15b8}
@subsubsection 用户定义的泛型类型


用户定义的类可以定义为泛型类。

@example
from typing import TypeVar, Generic
from logging import Logger

T = TypeVar('T')

class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)
@end example

@code{Generic[T]} 是定义类 @code{LoggedVar} 的基类，该类使用单类型参数 @code{T}。在该类体内，@code{T} 是有效的类型。

@ref{1055,,Generic} 基类定义了 @ref{440,,__class_getitem__()} ，因此，@code{LoggedVar[t]} 也是有效类型：

@example
from collections.abc import Iterable

def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
    for var in vars:
        var.set(0)
@end example

一个泛型可以有任何数量的类型变量。所有种类的 @ref{1098,,TypeVar} 都可以作为泛型的参数:

@example
from typing import TypeVar, Generic, Sequence

T = TypeVar('T', contravariant=True)
B = TypeVar('B', bound=Sequence[bytes], covariant=True)
S = TypeVar('S', int, str)

class WeirdTrio(Generic[T, B, S]):
    ...
@end example

@ref{1055,,Generic} 类型变量的参数应各不相同。下列代码就是无效的：

@example
from typing import TypeVar, Generic
...

T = TypeVar('T')

class Pair(Generic[T, T]):   # INVALID
    ...
@end example

@ref{1055,,Generic} 支持多重继承：

@example
from collections.abc import Sized
from typing import TypeVar, Generic

T = TypeVar('T')

class LinkedList(Sized, Generic[T]):
    ...
@end example

继承自泛型类时，可以修正某些类型变量：

@example
from collections.abc import Mapping
from typing import TypeVar

T = TypeVar('T')

class MyDict(Mapping[str, T]):
    ...
@end example

比如，本例中 @code{MyDict} 调用的单参数，@code{T}。

未指定泛型类的类型参数时，每个位置的类型都预设为 @ref{74f,,Any}。下例中，@code{MyIterable} 不是泛型，但却隐式继承了 @code{Iterable[Any]}：

@example
from collections.abc import Iterable

class MyIterable(Iterable): # Same as Iterable[Any]
@end example

还支持用户定义的泛型类型别名。例如：

@example
from collections.abc import Iterable
from typing import TypeVar, Union
S = TypeVar('S')
Response = Union[Iterable[S], int]

# Return type here is same as Union[Iterable[str], int]
def response(query: str) -> Response[str]:
    ...

T = TypeVar('T', int, float, complex)
Vec = Iterable[tuple[T, T]]

def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
    return sum(x*y for x, y in v)
@end example


在 3.7 版更改: @ref{1055,,Generic} 不再支持自定义元类。


抽象基类可作为用户定义的泛型类的基类，且不会与元类冲突。现已不再支持泛型元类。参数化泛型的输出结果会被缓存，typing 模块的大多数类型都可哈希、可进行等价对比。

@node Any 类型,名义子类型 vs 结构子类型,用户定义的泛型类型,typing --- 类型提示支持
@anchor{library/typing the-any-type}@anchor{32df}
@subsubsection @code{Any} 类型


@ref{74f,,Any} 是一种特殊的类型。静态类型检查器认为所有类型均与 @ref{74f,,Any} 兼容，同样，@ref{74f,,Any} 也与所有类型兼容。

也就是说，可对 @ref{74f,,Any} 类型的值执行任何操作或方法调用，并赋值给任意变量：

@example
from typing import Any

a: Any = None
a = []          # OK
a = 2           # OK

s: str = '@w{'}
s = a           # OK

def foo(item: Any) -> int:
    # Typechecks; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()
    ...
@end example

注意，@ref{74f,,Any} 类型的值赋给更精确的类型时，不执行类型检查。例如，把 @code{a} 赋给 @code{s}，在运行时，即便 @code{s} 已声明为 @ref{206,,str} 类型，但接收 @ref{205,,int} 值时，静态类型检查器也不会报错。

此外，未指定返回值与参数类型的函数，都隐式地默认使用 @ref{74f,,Any}：

@example
def legacy_parser(text):
    ...
    return data

# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
    ...
    return data
@end example

需要混用动态与静态类型代码时，此操作把 @ref{74f,,Any} 当作 @emph{应急出口}。

@ref{74f,,Any} 和 @ref{3da,,object} 的区别。与 @ref{74f,,Any} 相似，所有类型都是 @ref{3da,,object} 的子类型。然而，与 @ref{74f,,Any} 不同，object 不可逆：@ref{3da,,object} @emph{不是} 其它类型的子类型。

就是说，值的类型是 @ref{3da,,object} 时，类型检查器几乎会拒绝所有对它的操作，并且，把它赋给更精确的类型变量（或返回值）属于类型错误。例如：

@example
def hash_a(item: object) -> int:
    # Fails; an object does not have a 'magic' method.
    item.magic()
    ...

def hash_b(item: Any) -> int:
    # Typechecks
    item.magic()
    ...

# Typechecks, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")

# Typechecks, since Any is compatible with all types
hash_b(42)
hash_b("foo")
@end example

使用 @ref{3da,,object}，说明值能以类型安全的方式转为任何类型。使用 @ref{74f,,Any}，说明值是动态类型。

@node 名义子类型 vs 结构子类型,模块内容<7>,Any 类型,typing --- 类型提示支持
@anchor{library/typing nominal-vs-structural-subtyping}@anchor{32e0}
@subsubsection 名义子类型 vs 结构子类型


最初 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 将 Python 静态类型系统定义为使用 @emph{名义子类型}。这意味着当且仅当类 @code{A} 是 @code{B} 的子类时，才满足有类 @code{B} 预期时使用类 @code{A} 。

此项要求以前也适用于抽象基类，例如，@ref{1849,,Iterable} 。这种方式的问题在于，定义类时必须显式说明，既不 Pythonic，也不是动态类型式 Python 代码的惯用写法。例如，下列代码就遵从了 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 的规范：

@example
from collections.abc import Sized, Iterable, Iterator

class Bucket(Sized, Iterable[int]):
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...
@end example

@geindex Python 提高建议; PEP 544
PEP 544@footnote{https://www.python.org/dev/peps/pep-0544} 允许用户在类定义时不显式说明基类，从而解决了这一问题，静态类型检查器隐式认为 @code{Bucket} 既是 @code{Sized} 的子类型，又是 @code{Iterable[int]} 的子类型。这就是 @emph{结构子类型} （又称为静态鸭子类型）：

@example
from collections.abc import Iterator, Iterable

class Bucket:  # Note: no base classes
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...

def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket())  # Passes type check
@end example

此外，结构子类型的优势在于，通过继承特殊类 @ref{371,,Protocol} ，用户可以定义新的自定义协议（见下文中的例子）。

@node 模块内容<7>,,名义子类型 vs 结构子类型,typing --- 类型提示支持
@anchor{library/typing module-contents}@anchor{32e1}
@subsubsection 模块内容


本模块定义了下列类、函数和修饰器。

@cartouche
@quotation 注解 
本模块定义了一些类型，作为标准库中已有的类的子类，从而可以让 @ref{1055,,Generic} 支持 @code{[]} 中的类型变量。Python 3.9 中，这些标准库的类已支持 @code{[]} ，因此，这些类型就变得冗余了。

Python 3.9 弃用了这些冗余类型，但解释器并未提供相应的弃用警告。标记弃用类型的工作留待支持 Python 3.9 及以上版本的类型检查器实现。

Python 3.9.0 发布五年后的首个 Python 发行版将从 @ref{122,,typing} 模块中移除这些弃用类型。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 《@emph{标准集合的类型提示泛型}》。
@end quotation
@end cartouche

@menu
* 特殊类型原语:: 
* 泛型具象容器:: 
* 抽象基类:: 
* 协议: 协议<3>. 
* 函数与装饰器:: 
* 内省辅助器:: 
* 常量: 常量<4>. 

@end menu

@node 特殊类型原语,泛型具象容器,,模块内容<7>
@anchor{library/typing special-typing-primitives}@anchor{32e2}
@subsubsection 特殊类型原语


@menu
* 特殊类型:: 
* 特殊形式:: 
* 构建泛型类型:: 
* 其他特殊指令:: 

@end menu

@node 特殊类型,特殊形式,,特殊类型原语
@anchor{library/typing special-types}@anchor{32e3}
@subsubsection 特殊类型


这些类型可用于类型注解，但不支持 @code{[]}。

@geindex Any() (在 typing 模块中)
@anchor{library/typing typing Any}@anchor{74f}
@deffn {数据} typing.Any

不受限的特殊类型。


@itemize *

@item 
所有类型都与 @ref{74f,,Any} 兼容。

@item 
@ref{74f,,Any} 与所有类型都兼容。
@end itemize
@end deffn

@geindex NoReturn() (在 typing 模块中)
@anchor{library/typing typing NoReturn}@anchor{32e4}
@deffn {数据} typing.NoReturn

标记没有返回值的函数的特殊类型。例如：

@example
from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError('no way')
@end example


3.5.4 新版功能.



3.6.2 新版功能.

@end deffn

@node 特殊形式,构建泛型类型,特殊类型,特殊类型原语
@anchor{library/typing special-forms}@anchor{32e5}
@subsubsection 特殊形式


可用于类型注解，且支持 @code{[]} ，每种形式都有其独特的句法。

@geindex Tuple() (在 typing 模块中)
@anchor{library/typing typing Tuple}@anchor{32e6}
@deffn {数据} typing.Tuple

元组类型； @code{Tuple[X, Y]} 是二项元组类型，第一个元素的类型是 X，第二个元素的类型是 Y。空元组的类型可写为 @code{Tuple[()]}。

例：@code{Tuple[T1, T2]} 是二项元组，类型变量分别为 T1 和 T2。@code{Tuple[int, float, str]} 是由整数、浮点数、字符串组成的三项元组。

可用省略号字面量指定同质变长元组，例如，@code{Tuple[int, ...]} 。@ref{32e6,,Tuple} 与 @code{Tuple[Any, ...]} 等价，也与 @ref{1a2,,tuple} 等价。


3.9 版后已移除: @ref{1a2,,builtins.tuple} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Union() (在 typing 模块中)
@anchor{library/typing typing Union}@anchor{11b3}
@deffn {数据} typing.Union

联合类型；@code{Union[X, Y]} 的意思是，非 X 即 Y。

可用 @code{Union[int, str]} 等形式定义联合类型。 具体如下：


@itemize *

@item 
参数必须是某种类型，且至少有一个。

@item 
联合类型之联合类型会被展平，例如：

@example
Union[Union[int, str], float] == Union[int, str, float]
@end example

@item 
单参数之联合类型就是该参数自身，例如：

@example
Union[int] == int  # The constructor actually returns int
@end example

@item 
冗余的参数会被跳过，例如：

@example
Union[int, str, int] == Union[int, str]
@end example

@item 
比较联合类型，不涉及参数顺序，例如：

@example
Union[int, str] == Union[str, int]
@end example

@item 
联合类型不能作为子类，也不能实例化。

@item 
不支持 @code{Union[X][Y]} 这种写法。

@item 
@code{Optional[X]} 是 @code{Union[X, None]} 的缩写。
@end itemize


在 3.7 版更改: 在运行时，不要移除联合类型中的显式子类。

@end deffn

@geindex Optional() (在 typing 模块中)
@anchor{library/typing typing Optional}@anchor{32e7}
@deffn {数据} typing.Optional

可选类型。

 @code{Optional[X]} 等价于 @code{Union[X, None]} 。

注意，可选类型与含默认值的可选参数不同。含默认值的可选参数不需要在类型注解上添加 @code{Optional} 限定符，因为它仅是可选的。例如：

@example
def foo(arg: int = 0) -> None:
    ...
@end example

另一方面，显式应用 @code{None} 值时，不管该参数是否可选， @code{Optional} 都适用。例如：

@example
def foo(arg: Optional[int] = None) -> None:
    ...
@end example
@end deffn

@geindex Callable() (在 typing 模块中)
@anchor{library/typing typing Callable}@anchor{27c}
@deffn {数据} typing.Callable

可调类型； @code{Callable[[int], str]} 是把（int）转为 str 的函数。

下标句法必须与参数列表和返回类型这两个值一起使用。参数列表只能是类型列表或省略号；返回类型只能是单一类型。

没有说明可选参数或关键字参数的句法；这类函数类型很少用作回调类型。@code{Callable[..., ReturnType]} （省略号字面量）可用于为接受任意数量参数，并返回 @code{ReturnType} 的可调对象提供类型提示。纯 @ref{27c,,Callable} 等价于 @code{Callable[..., Any]}，进而等价于 @ref{27b,,collections.abc.Callable} 。


3.9 版后已移除: @ref{27b,,collections.abc.Callable} 现已支持 @code{[]}。 详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Type (typing 中的类)
@anchor{library/typing typing Type}@anchor{32e8}
@deffn {类} typing.Type (Generic[CT_co])

用 @code{C} 注解的变量可以接受类型 @code{C} 的值。反之，用 @code{Type[C]} 注解的变量可以接受类自身的值 — 准确地说，是接受 @code{C} 的 @emph{类对象}，例如：

@example
a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'
@end example

注意，@code{Type[C]} 为协变量：

@example
class User: ...
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...

# Accepts User, BasicUser, ProUser, TeamUser, ...
def make_new_user(user_class: Type[User]) -> User:
    # ...
    return user_class()
@end example

@code{Type[C]} 为协变量的意思是指， @code{C} 的所有子类都应使用与 @code{C} 相同的构造器签名及类方法签名。类型检查器应标记违反此项规定的内容，但也应允许符合指定基类构造器调用的子类进行构造器调用。
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484}  修订版将来可能会调整类型检查器对这种特例的处理方式。

 @ref{32e8,,Type} 合法的参数仅有类、@ref{74f,,Any} 、@ref{15b7,,类型变量} 以及上述类型的联合类型。例如：

@example
def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ...
@end example

 @code{Type[Any]} 等价于 @code{Type}，进而等价于 Python 元类架构的根基，@code{type}。


3.5.2 新版功能.



3.9 版后已移除: @ref{709,,builtins.type} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Literal() (在 typing 模块中)
@anchor{library/typing typing Literal}@anchor{276}
@deffn {数据} typing.Literal

表示类型检查器对应变量或函数参数的值等价于给定字面量（或多个字面量之一）的类型。例如：

@example
def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
    ...

open_helper('/some/path', 'r')  # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker
@end example

@code{Literal[...]} 不能创建子类。在运行时，任意值均可作为 @code{Literal[...]} 的类型参数，但类型检查器可以对此加以限制。字面量类型详见 
@geindex Python 提高建议; PEP 586
PEP 586@footnote{https://www.python.org/dev/peps/pep-0586} 。


3.8 新版功能.



在 3.9.1 版更改: @code{Literal} 现在能去除形参的重复。 @code{Literal} 对象的相等性比较不再依赖顺序。 现在如果有某个参数不为 @ref{277,,hashable}，@code{Literal} 对象在相等性比较期间将引发 @ref{1ff,,TypeError}。

@end deffn

@geindex ClassVar() (在 typing 模块中)
@anchor{library/typing typing ClassVar}@anchor{6a4}
@deffn {数据} typing.ClassVar

标记类变量的特殊类型构造器。

如 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 所述，打包在 ClassVar 内的变量注解是指，给定属性应当用作类变量，而不应设置在类实例上。用法如下：

@example
class Starship:
    stats: ClassVar[dict[str, int]] = @{@} # class variable
    damage: int = 10                     # instance variable
@end example

@ref{6a4,,ClassVar} 仅接受类型，也不能使用下标。

@ref{6a4,,ClassVar} 本身不是类，不应用于 @ref{55a,,isinstance()} 或 @ref{55b,,issubclass()}。@ref{6a4,,ClassVar} 不改变 Python 运行时行为，但可以用于第三方类型检查器。例如，类型检查器会认为以下代码有错：

@example
enterprise_d = Starship(3000)
enterprise_d.stats = @{@} # Error, setting class variable on instance
Starship.stats = @{@}     # This is OK
@end example


3.5.3 新版功能.

@end deffn

@geindex Final() (在 typing 模块中)
@anchor{library/typing typing Final}@anchor{36f}
@deffn {数据} typing.Final

告知类型检查器某名称不能再次赋值或在子类中重写的特殊类型构造器。例如：

@example
MAX_SIZE: Final = 9000
MAX_SIZE += 1  # Error reported by type checker

class Connection:
    TIMEOUT: Final[int] = 10

class FastConnector(Connection):
    TIMEOUT = 1  # Error reported by type checker
@end example

这些属性没有运行时检查。详见 
@geindex Python 提高建议; PEP 591
PEP 591@footnote{https://www.python.org/dev/peps/pep-0591}。


3.8 新版功能.

@end deffn

@geindex Annotated() (在 typing 模块中)
@anchor{library/typing typing Annotated}@anchor{1ef}
@deffn {数据} typing.Annotated

@geindex Python 提高建议; PEP 593
PEP 593@footnote{https://www.python.org/dev/peps/pep-0593} （@code{灵活函数和变量注解}）里引入的类型，可以用上下文特定元数据（@code{Annotated} 的参数可变，也可能用它的多个组成部分）装饰现有的类型。具体来说，就是类型提示 @code{Annotated[T, x]} 用元数据 @code{x} 注解类型 @code{T}。静态分析或运行时都能使用该元数据。库（或工具）处理类型提示 @code{Annotated[T, x]} 时，在元数据 @code{x} 不涉及特殊逻辑的情况下，可忽略该类型提示，仅把它当作类型 @code{T}。与 @code{typing} 模块中现有的 @code{no_type_check} 功能不同，该功能完全禁用了函数或类的类型检查注解，而 @code{Annotated} 类型则允许对 @code{T} 进行静态类型检查（可安全地忽略 @code{x}），也可以在特定应用程序中实现 @code{x} 的运行时访问。

毕竟，如何解释注解（如有）由处理 @code{Annotated} 类型的工具/库负责。工具/库处理 @code{Annotated} 类型时，扫描所有注解以确定是否需要进行处理（例如，使用 @code{isinstance()}）。

工具/库不支持注解，或遇到未知注解时，应忽略注解，并把注解类型当作底层类型。

是否允许客户端在一个类型上使用多个注解，以及如何合并这些注解，由处理注解的工具决定。

@code{Annotated} 类型支持把多个相同（或不同）的单个（或多个）类型注解置于任意节点。因此，使用这些注解的工具/库要负责处理潜在的重复项。例如，执行值范围分析时，应允许以下操作：

@example
T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
@end example

传递 @code{include_extras=True} 至 @ref{1f0,,get_type_hints()} ，即可在运行时访问额外的注解。

语义详情：


@itemize *

@item 
@code{Annotated} 的第一个参数必须是有效类型。

@item 
支持多个类型标注（@code{Annotated} 支持可变参数）：

@example
Annotated[int, ValueRange(3, 10), ctype("char")]
@end example

@item 
调用 @code{Annotated} 至少要有两个参数（@code{Annotated[int]} 是无效的）

@item 
注解的顺序会被保留，且影响等价检查：

@example
Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[
    int, ctype("char"), ValueRange(3, 10)
]
@end example

@item 
嵌套 @code{Annotated} 类型会被展平，元数据从最内层注解依序展开：

@example
Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
    int, ValueRange(3, 10), ctype("char")
]
@end example

@item 
不移除注解重复项：

@example
Annotated[int, ValueRange(3, 10)] != Annotated[
    int, ValueRange(3, 10), ValueRange(3, 10)
]
@end example

@item 
@code{Annotated} 可用于嵌套或泛型别名：

@example
T = TypeVar('T')
Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
V = Vec[int]

V == Annotated[list[tuple[int, int]], MaxLen(10)]
@end example
@end itemize


3.9 新版功能.

@end deffn

@node 构建泛型类型,其他特殊指令,特殊形式,特殊类型原语
@anchor{library/typing building-generic-types}@anchor{32e9}
@subsubsection 构建泛型类型


以下内容是创建泛型类型的基石，但不在注解内使用。

@geindex Generic (typing 中的类)
@anchor{library/typing typing Generic}@anchor{1055}
@deffn {类} typing.Generic

用于泛型类型的抽象基类。

泛型类型一般通过继承含一个或多个类型变量的类实例进行声明。例如，泛型映射类型定义如下：

@example
class Mapping(Generic[KT, VT]):
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.
@end example

该类的用法如下：

@example
X = TypeVar('X')
Y = TypeVar('Y')

def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
    try:
        return mapping[key]
    except KeyError:
        return default
@end example
@end deffn

@geindex TypeVar (typing 中的类)
@anchor{library/typing typing TypeVar}@anchor{1098}
@deffn {类} typing.TypeVar

类型变量。

用法：

@example
T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
@end example

类型变量主要是为静态类型检查器提供支持，用于泛型类型与泛型函数定义的参数。有关泛型类型，详见 @ref{1055,,Generic}。泛型函数的写法如下：

@example
def repeat(x: T, n: int) -> Sequence[T]:
    """Return a list containing n references to x."""
    return [x]*n


def print_capitalized(x: S) -> S:
    """Print x capitalized, and return x."""
    print(x.capitalize())
    return x


def concatenate(x: A, y: A) -> A:
    """Add two strings or bytes objects together."""
    return x + y
@end example

请注意，类型变量可以是 @emph{被绑定的} ， @emph{被约束的} ，或者两者都不是，但不能既是被绑定的 @emph{又是} 被约束的。

约束类型变量和绑定类型变量在几个重要方面具有不同的语义。使用 @emph{约束} 类型变量意味着它只能被解析为正好是所给的约束之一:

@example
a = concatenate('one', 'two')  # Ok, variable 'a' has type 'str'
b = concatenate(StringSubclass('one'), StringSubclass('two'))  # Inferred type of variable 'b' is 'str',
                                                               # despite 'StringSubclass' being passed in
c = concatenate('one', b'two')  # error: type variable 'A' can be either 'str' or 'bytes' in a function call, but not both
@end example

然而，使用一个 @emph{绑定} 类型变量，意味着将使用最具体的类型来解析 @code{TypeVar}

@example
print_capitalized('a string')  # Ok, output has type 'str'

class StringSubclass(str):
    pass

print_capitalized(StringSubclass('another string'))  # Ok, output has type 'StringSubclass'
print_capitalized(45)  # error: int is not a subtype of str
@end example

类型变量可以被绑定到具体类型、抽象类型（ ABC 或 protocol ），甚至是类型的联合:

@example
U = TypeVar('U', bound=str|bytes)  # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs)  # Can be anything with an __abs__ method
@end example

绑定类型变量对于注释作为替代构造函数的 @ref{310,,classmethods} 特别有用。在下面的例子中（ ©  Raymond Hettinger@footnote{https://www.youtube.com/watch?v=HTLu2DFOdTg} ），类型变量 @code{C} 通过使用前向引用被绑定到类 @code{Circle} 。使用这个类型变量来注解类方法 @code{with_circumference} ，而不是将返回类型硬编码为 @code{Circle} ，这意味着类型检查器可以正确推断出返回类型，即使该方法是在一个子类上调用的:

@example
import math

C = TypeVar('C', bound='Circle')

class Circle:
    """An abstract circle"""

    def __init__(self, radius: float) -> None:
        self.radius = radius

    # Use a type variable to show that the return type
    # will always be an instance of whatever `@w{`}cls`@w{`} is
    @@classmethod
    def with_circumference(cls: type[C], circumference: float) -> C:
        """Create a circle with the specified circumference"""
        radius = circumference / (math.pi * 2)
        return cls(radius)


class Tire(Circle):
    """A specialised circle (made out of rubber)"""

    MATERIAL = 'rubber'


c = Circle.with_circumference(3)  # Ok, variable 'c' has type 'Circle'
t = Tire.with_circumference(4)  # Ok, variable 't' has type 'Tire' (not 'Circle')
@end example

在运行时，@code{isinstance(x, T)} 会触发 @ref{1ff,,TypeError} 异常。一般而言，@ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 不应与类型搭配使用。

类型变量可以通过传递 @code{covariant=True} 或 @code{contravariant=True} 来标记协变或反变。 更多细节请参见 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 。 默认情况下，类型变量是不变的。
@end deffn

@geindex AnyStr() (在 typing 模块中)
@anchor{library/typing typing AnyStr}@anchor{32ea}
@deffn {数据} typing.AnyStr

@code{AnyStr} 定义为 @code{AnyStr = TypeVar('AnyStr', str, bytes)} 的 @ref{1098,,约束类型变量} 。

这里指的是，它可以接受任意同类字符串，但不支持混用不同类别的字符串。例如：

@example
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

concat(u"foo", u"bar")  # Ok, output has type 'unicode'
concat(b"foo", b"bar")  # Ok, output has type 'bytes'
concat(u"foo", b"bar")  # Error, cannot mix unicode and bytes
@end example
@end deffn

@geindex Protocol (typing 中的类)
@anchor{library/typing typing Protocol}@anchor{371}
@deffn {类} typing.Protocol (Generic)

Protocol 类的基类。Protocol 类的定义如下：

@example
class Proto(Protocol):
    def meth(self) -> int:
        ...
@end example

这些类主要与静态类型检查器搭配使用，用来识别结构子类型（静态鸭子类型），例如：

@example
class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check
@end example

详见 
@geindex Python 提高建议; PEP 544
PEP 544@footnote{https://www.python.org/dev/peps/pep-0544}。Protocol 类用 @ref{372,,runtime_checkable()} （见下文）装饰，忽略类型签名，仅检查给定属性是否存在，充当简要的运行时协议。

Protocol 类可以是泛型，例如：

@example
class GenProto(Protocol[T]):
    def meth(self) -> T:
        ...
@end example


3.8 新版功能.

@end deffn

@geindex runtime_checkable() (在 typing 模块中)
@anchor{library/typing typing runtime_checkable}@anchor{372}
@deffn {函数} @@typing.runtime_checkable

用于把 Protocol 类标记为运行时协议。

该协议可以与 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 一起使用。应用于非协议的类时，会触发 @ref{1ff,,TypeError}。该指令支持简易结构检查，与 @ref{1e,,collections.abc} 的 @ref{1849,,Iterable} 非常类似，只擅长做一件事。  例如：

@example
@@runtime_checkable
class Closable(Protocol):
    def close(self): ...

assert isinstance(open('/some/file'), Closable)
@end example

@cartouche
@quotation 注解 
@ref{372,,runtime_checkable()} 只检查所需方法是否存在，但却不检查类型签名！ 例如，@ref{2c8,,builtins.complex} 支持 @ref{2cb,,__float__()}，因此，它能通过 @ref{32eb,,SupportsFloat}  的 @ref{55b,,issubclass()} 检查。 然而，@code{complex.__float__} 方法其实只是为了触发含更多信息的 @ref{1ff,,TypeError}。
@end quotation
@end cartouche


3.8 新版功能.

@end deffn

@node 其他特殊指令,,构建泛型类型,特殊类型原语
@anchor{library/typing other-special-directives}@anchor{32ec}
@subsubsection 其他特殊指令


这些特殊指令是声明类型的基石，但不在注解内使用。

@geindex NamedTuple (typing 中的类)
@anchor{library/typing typing NamedTuple}@anchor{228}
@deffn {类} typing.NamedTuple

@ref{1a1,,collections.namedtuple()} 的类型版本。

用法：

@example
class Employee(NamedTuple):
    name: str
    id: int
@end example

相当于：

@example
Employee = collections.namedtuple('Employee', ['name', 'id'])
@end example

为字段提供默认值，要在类体内赋值：

@example
class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3
@end example

带默认值的字段必须在不带默认值的字段后面。

由此产生的类有一个额外的属性 @code{__annotations__} ，给出一个 dict ，将字段名映射到字段类型。（字段名在 @code{_fields} 属性中，默认值在 @code{_field_defaults} 属性中，这两者都是 @ref{1a1,,namedtuple()} API 的一部分。）

@code{NamedTuple} 子类也支持文档字符串与方法：

@example
class Employee(NamedTuple):
    """Represents an employee."""
    name: str
    id: int = 3

    def __repr__(self) -> str:
        return f'<Employee @{self.name@}, id=@{self.id@}>'
@end example

反向兼容用法：

@example
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
@end example


在 3.6 版更改: 添加了对 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 中变量注解句法的支持。



在 3.6.1 版更改: 添加了对默认值、方法、文档字符串的支持。



在 3.8 版更改: @code{_field_types} 和 @code{__annotations__} 属性现已使用常规字典，不再使用 @code{OrderedDict} 实例。



在 3.9 版更改: 移除了 @code{_field_types} 属性， 改用具有相同信息，但更标准的  @code{__annotations__} 属性。

@end deffn

@geindex NewType() (在 typing 模块中)
@anchor{library/typing typing NewType}@anchor{6a6}
@deffn {函数} typing.NewType (name, tp)

用于为类型检查器标明不同类型的辅助函数，详见 @ref{32da,,NewType}。在运行时，它返回一个返回其参数的函数。用法如下：

@example
UserId = NewType('UserId', int)
first_user = UserId(1)
@end example


3.5.2 新版功能.

@end deffn

@geindex TypedDict (typing 中的类)
@anchor{library/typing typing TypedDict}@anchor{36e}
@deffn {类} typing.TypedDict (dict)

把类型提示添加至字典的特殊构造器。在运行时，它是纯 @ref{164,,dict}。

@code{TypedDict} 声明一个字典类型，该类型预期所有实例都具有一组键集，其中，每个键都与对应类型的值关联。运行时不检查此预期，而是由类型检查器强制执行。用法如下：

@example
class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = @{'x': 1, 'y': 2, 'label': 'good'@}  # OK
b: Point2D = @{'z': 3, 'label': 'bad'@}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
@end example

To allow using this feature with older versions of Python that do not
support 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526}, @code{TypedDict} supports two additional equivalent
syntactic forms:


@itemize *

@item 
Using a literal @ref{164,,dict} as the second argument:

@example
Point2D = TypedDict('Point2D', @{'x': int, 'y': int, 'label': str@})
@end example

@item 
Using keyword arguments:

@example
Point2D = TypedDict('Point2D', x=int, y=int, label=str)
@end example
@end itemize

当任何一个键不是有效的 @ref{1533,,标识符} 时，例如因为它们是关键字或包含连字符，也应该使用函数式语法。例子:

@example
# raises SyntaxError
class Point2D(TypedDict):
    in: int  # 'in' is a keyword
    x-y: int  # name with hyphens

# OK, functional syntax
Point2D = TypedDict('Point2D', @{'in': int, 'x-y': int@})
@end example

默认情况下，所有的键都必须出现在一个 @code{TypedDict} 中。 可以通过指定总数来重写这一点。用法:

@example
class Point2D(TypedDict, total=False):
    x: int
    y: int

# Alternative syntax
Point2D = TypedDict('Point2D', @{'x': int, 'y': int@}, total=False)
@end example

这意味着一个 @code{Point2D} @code{TypedDict} 可以省略任何一个键。 类型检查器只需要支持一个字面的 @code{False} 或 @code{True} 作为 @code{total} 参数的值。 @code{True} 是默认的，它使类主体中定义的所有项目都是必需的。

一个 @code{TypedDict} 类型有可能使用基于类的语法从一个或多个其他 @code{TypedDict} 类型继承。用法:

@example
class Point3D(Point2D):
    z: int
@end example

@code{Point3D} 有三个项目 : @code{x} , @code{y} 和 @code{z} 。 其等价于定义:

@example
class Point3D(TypedDict):
    x: int
    y: int
    z: int
@end example

@code{TypedDict} 不能继承于一个非 @code{TypedDict} 类，其中特别包括 @ref{1055,,Generic} 。例如：

@example
class X(TypedDict):
    x: int

class Y(TypedDict):
    y: int

class Z(object): pass  # A non-TypedDict class

class XY(X, Y): pass  # OK

class XZ(X, Z): pass  # raises TypeError

T = TypeVar('T')
class XT(X, Generic[T]): pass  # raises TypeError
@end example

A @code{TypedDict} can be introspected via @code{__annotations__},
@ref{32ed,,__total__}, @ref{32ee,,__required_keys__}, and @ref{32ef,,__optional_keys__}.

@geindex __total__ (typing.TypedDict 属性)
@anchor{library/typing typing TypedDict __total__}@anchor{32ed}
@deffn {属性} __total__

@code{Point2D.__total__} gives the value of the @code{total} argument.
Example:

@example
>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True
@end example
@end deffn

@geindex __required_keys__ (typing.TypedDict 属性)
@anchor{library/typing typing TypedDict __required_keys__}@anchor{32ee}
@deffn {属性} __required_keys__
@end deffn

@geindex __optional_keys__ (typing.TypedDict 属性)
@anchor{library/typing typing TypedDict __optional_keys__}@anchor{32ef}
@deffn {属性} __optional_keys__

@code{Point2D.__required_keys__} 和 @code{Point2D.__optional_keys__} 分别返回 @ref{1f8,,frozenset} 对象，其中包含必需和非必需键。目前，在同一个  中声明必需和非必需键的唯一方法是混合继承，用一个 @code{total} 参数值声明一个 @code{TypedDict} ，然后从另一个 @code{total} 参数值不同的 @code{TypedDict} 中继承它。用法：

@example
>>> class Point2D(TypedDict, total=False):
...     x: int
...     y: int
...
>>> class Point3D(Point2D):
...     z: int
...
>>> Point3D.__required_keys__ == frozenset(@{'z'@})
True
>>> Point3D.__optional_keys__ == frozenset(@{'x', 'y'@})
True
@end example
@end deffn

更多示例与 @code{TypedDict} 的详细规则，详见 
@geindex Python 提高建议; PEP 589
PEP 589@footnote{https://www.python.org/dev/peps/pep-0589}。


3.8 新版功能.

@end deffn

@node 泛型具象容器,抽象基类,特殊类型原语,模块内容<7>
@anchor{library/typing generic-concrete-collections}@anchor{32f0}
@subsubsection 泛型具象容器


@menu
* 对应的内置类型:: 
* collections 对应类型:: 
* 其他具象类型:: 

@end menu

@node 对应的内置类型,collections 对应类型,,泛型具象容器
@anchor{library/typing corresponding-to-built-in-types}@anchor{32f1}
@subsubsection 对应的内置类型


@geindex Dict (typing 中的类)
@anchor{library/typing typing Dict}@anchor{32f2}
@deffn {类} typing.Dict (dict, MutableMapping[KT, VT])

@ref{164,,dict} 的泛型版本。适用于注解返回类型。注解参数时，最好使用 @ref{32f3,,Mapping} 等抽象容器类型。

该类型用法如下：

@example
def count_words(text: str) -> Dict[str, int]:
    ...
@end example


3.9 版后已移除: @ref{164,,builtins.dict} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex List (typing 中的类)
@anchor{library/typing typing List}@anchor{32f4}
@deffn {类} typing.List (list, MutableSequence[T])

@ref{1f9,,list} 的泛型版本。适用于注解返回类型。注解参数时，最好使用 @ref{32f5,,Sequence} 或 @ref{32f6,,Iterable} 等抽象容器类型。

该类型用法如下：

@example
T = TypeVar('T', int, float)

def vec2(x: T, y: T) -> List[T]:
    return [x, y]

def keep_positives(vector: Sequence[T]) -> List[T]:
    return [item for item in vector if item > 0]
@end example


3.9 版后已移除: @ref{1f9,,builtins.list} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Set (typing 中的类)
@anchor{library/typing typing Set}@anchor{32f7}
@deffn {类} typing.Set (set, MutableSet[T])

@ref{1f7,,builtins.set} 的泛型版本。适用于注解返回类型。注解参数时，最好使用 @ref{32f8,,AbstractSet} 等抽象容器类型。


3.9 版后已移除: @ref{1f7,,builtins.set} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex FrozenSet (typing 中的类)
@anchor{library/typing typing FrozenSet}@anchor{32f9}
@deffn {类} typing.FrozenSet (frozenset, AbstractSet[T_co])

@ref{1f8,,builtins.frozenset} 的泛型版本。


3.9 版后已移除: @ref{1f8,,builtins.frozenset} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@cartouche
@quotation 注解 
@ref{32e6,,Tuple} 是一种特殊形式。
@end quotation
@end cartouche

@node collections 对应类型,其他具象类型,对应的内置类型,泛型具象容器
@anchor{library/typing corresponding-to-types-in-collections}@anchor{32fa}
@subsubsection @code{collections} 对应类型


@geindex DefaultDict (typing 中的类)
@anchor{library/typing typing DefaultDict}@anchor{32fb}
@deffn {类} typing.DefaultDict (collections.defaultdict, MutableMapping[KT, VT])

@ref{c15,,collections.defaultdict} 的泛型版本。


3.5.2 新版功能.



3.9 版后已移除: @ref{c15,,collections.defaultdict} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex OrderedDict (typing 中的类)
@anchor{library/typing typing OrderedDict}@anchor{32fc}
@deffn {类} typing.OrderedDict (collections.OrderedDict, MutableMapping[KT, VT])

@ref{2f1,,collections.OrderedDict} 的泛型版本。


3.7.2 新版功能.



3.9 版后已移除: @ref{2f1,,collections.OrderedDict} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex ChainMap (typing 中的类)
@anchor{library/typing typing ChainMap}@anchor{32fd}
@deffn {类} typing.ChainMap (collections.ChainMap, MutableMapping[KT, VT])

@ref{5ac,,collections.ChainMap} 的泛型版本。


3.5.4 新版功能.



3.6.1 新版功能.



3.9 版后已移除: @ref{5ac,,collections.ChainMap} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Counter (typing 中的类)
@anchor{library/typing typing Counter}@anchor{32fe}
@deffn {类} typing.Counter (collections.Counter, Dict[T, int])

@ref{ac2,,collections.Counter} 的泛型版本。


3.5.4 新版功能.



3.6.1 新版功能.



3.9 版后已移除: @ref{ac2,,collections.Counter} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Deque (typing 中的类)
@anchor{library/typing typing Deque}@anchor{32ff}
@deffn {类} typing.Deque (deque, MutableSequence[T])

@ref{633,,collections.deque} 的泛型版本。


3.5.4 新版功能.



3.6.1 新版功能.



3.9 版后已移除: @ref{633,,collections.deque} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@node 其他具象类型,,collections 对应类型,泛型具象容器
@anchor{library/typing other-concrete-types}@anchor{3300}
@subsubsection 其他具象类型


@geindex IO (typing 中的类)
@geindex TextIO (typing 中的类)
@geindex BinaryIO (typing 中的类)
@anchor{library/typing typing IO}@anchor{3301}
@deffn {类} typing.IO
@anchor{library/typing typing TextIO}@anchor{3302}
@deffnx {类} typing.TextIO
@anchor{library/typing typing BinaryIO}@anchor{3303}
@deffnx {类} typing.BinaryIO

泛型类型 @code{IO[AnyStr]} 及其子类 @code{TextIO(IO[str])} 与 @code{BinaryIO(IO[bytes])} 表示 I/O 流的类型，例如 @ref{16f,,open()} 所返回的对象。


Deprecated since version 3.8, will be removed in version 3.12: 这些类型也在 @code{typing.io} 命名空间中，它从未得到类型检查器的支持并将被移除。

@end deffn

@geindex Pattern (typing 中的类)
@geindex Match (typing 中的类)
@anchor{library/typing typing Pattern}@anchor{3304}
@deffn {类} typing.Pattern
@anchor{library/typing typing Match}@anchor{3305}
@deffnx {类} typing.Match

这些类型对应的是从 @ref{555,,re.compile()} 和 @ref{c8b,,re.match()} 返回的类型。 这些类型（及相应的函数）是 @code{AnyStr} 中的泛型并可通过编写 @code{Pattern[str]}, @code{Pattern[bytes]}, @code{Match[str]} 或 @code{Match[bytes]} 来具体指定。


Deprecated since version 3.8, will be removed in version 3.12: 这些类型也在 @code{typing.re} 命名空间中，它从未得到类型检查器的支持并将被移除。



3.9 版后已移除: @ref{dd,,re} 模块中的 @code{Pattern} 与 @code{Match} 类现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Text (typing 中的类)
@anchor{library/typing typing Text}@anchor{3306}
@deffn {类} typing.Text

@code{Text} 是 @code{str} 的别名。提供了对 Python 2 代码的向下兼容：Python 2 中，@code{Text} 是 @code{unicode} 的别名。

使用 @code{Text} 时，值中必须包含 unicode 字符串，以兼容 Python 2 和 Python 3：

@example
def add_unicode_checkmark(text: Text) -> Text:
    return text + u' \u2713'
@end example


3.5.2 新版功能.

@end deffn

@node 抽象基类,协议<3>,泛型具象容器,模块内容<7>
@anchor{library/typing abstract-base-classes}@anchor{3307}
@subsubsection 抽象基类


@menu
* collections.abc 对应的容器: collections abc 对应的容器. 
* collections.abc 对应的其他类型: collections abc 对应的其他类型. 
* 异步编程:: 
* 上下文管理器类型: 上下文管理器类型<2>. 

@end menu

@node collections abc 对应的容器,collections abc 对应的其他类型,,抽象基类
@anchor{library/typing corresponding-to-collections-in-collections-abc}@anchor{3308}
@subsubsection @code{collections.abc} 对应的容器


@geindex AbstractSet (typing 中的类)
@anchor{library/typing typing AbstractSet}@anchor{32f8}
@deffn {类} typing.AbstractSet (Sized, Collection[T_co])

@ref{1841,,collections.abc.Set}  的泛型版本。


3.9 版后已移除: @ref{1841,,collections.abc.Set} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex ByteString (typing 中的类)
@anchor{library/typing typing ByteString}@anchor{3309}
@deffn {类} typing.ByteString (Sequence[int])

@ref{184d,,collections.abc.ByteString} 的泛型版本。

该类型代表了 @ref{172,,bytes}、@ref{173,,bytearray}、@ref{38d,,memoryview} 等字节序列类型。

作为该类型的简称，@ref{172,,bytes} 可用于标注上述任意类型的参数。


3.9 版后已移除: @ref{184d,,collections.abc.ByteString} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Collection (typing 中的类)
@anchor{library/typing typing Collection}@anchor{6a3}
@deffn {类} typing.Collection (Sized, Iterable[T_co], Container[T_co])

@ref{62f,,collections.abc.Collection} 的泛型版本。


3.6.0 新版功能.



3.9 版后已移除: @ref{62f,,collections.abc.Collection} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 与 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Container (typing 中的类)
@anchor{library/typing typing Container}@anchor{330a}
@deffn {类} typing.Container (Generic[T_co])

@ref{184b,,collections.abc.Container} 的泛型版本。


3.9 版后已移除: @ref{184b,,collections.abc.Container} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex ItemsView (typing 中的类)
@anchor{library/typing typing ItemsView}@anchor{330b}
@deffn {类} typing.ItemsView (MappingView, Generic[KT_co, VT_co])

@ref{1850,,collections.abc.ItemsView} 的泛型版本。


3.9 版后已移除: @ref{1850,,collections.abc.ItemsView} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex KeysView (typing 中的类)
@anchor{library/typing typing KeysView}@anchor{330c}
@deffn {类} typing.KeysView (MappingView[KT_co], AbstractSet[KT_co])

@ref{184f,,collections.abc.KeysView} 的泛型版本。


3.9 版后已移除: @ref{184f,,collections.abc.KeysView} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Mapping (typing 中的类)
@anchor{library/typing typing Mapping}@anchor{32f3}
@deffn {类} typing.Mapping (Sized, Collection[KT], Generic[VT_co])

@ref{15f,,collections.abc.Mapping} 的泛型版本。用法如下：

@example
def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
    return word_list[word]
@end example


3.9 版后已移除: @ref{15f,,collections.abc.Mapping} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex MappingView (typing 中的类)
@anchor{library/typing typing MappingView}@anchor{330d}
@deffn {类} typing.MappingView (Sized, Iterable[T_co])

@ref{184e,,collections.abc.MappingView} 的泛型版本。


3.9 版后已移除: @ref{184e,,collections.abc.MappingView} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex MutableMapping (typing 中的类)
@anchor{library/typing typing MutableMapping}@anchor{330e}
@deffn {类} typing.MutableMapping (Mapping[KT, VT])

@ref{ad7,,collections.abc.MutableMapping} 的泛型版本。


3.9 版后已移除: @ref{ad7,,collections.abc.MutableMapping} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex MutableSequence (typing 中的类)
@anchor{library/typing typing MutableSequence}@anchor{330f}
@deffn {类} typing.MutableSequence (Sequence[T])

@ref{7a9,,collections.abc.MutableSequence} 的泛型版本。


3.9 版后已移除: @ref{7a9,,collections.abc.MutableSequence} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex MutableSet (typing 中的类)
@anchor{library/typing typing MutableSet}@anchor{3310}
@deffn {类} typing.MutableSet (AbstractSet[T])

@ref{184c,,collections.abc.MutableSet} 的泛型版本。


3.9 版后已移除: @ref{184c,,collections.abc.MutableSet} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Sequence (typing 中的类)
@anchor{library/typing typing Sequence}@anchor{32f5}
@deffn {类} typing.Sequence (Reversible[T_co], Collection[T_co])

@ref{1794,,collections.abc.Sequence} 的泛型版本。


3.9 版后已移除: @ref{1794,,collections.abc.Sequence} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex ValuesView (typing 中的类)
@anchor{library/typing typing ValuesView}@anchor{3311}
@deffn {类} typing.ValuesView (MappingView[VT_co])

@ref{1851,,collections.abc.ValuesView} 的泛型版本。


3.9 版后已移除: @ref{1851,,collections.abc.ValuesView} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@node collections abc 对应的其他类型,异步编程,collections abc 对应的容器,抽象基类
@anchor{library/typing corresponding-to-other-types-in-collections-abc}@anchor{3312}
@subsubsection @code{collections.abc} 对应的其他类型


@geindex Iterable (typing 中的类)
@anchor{library/typing typing Iterable}@anchor{32f6}
@deffn {类} typing.Iterable (Generic[T_co])

@ref{1849,,collections.abc.Iterable} 的泛型版本。


3.9 版后已移除: @ref{1849,,collections.abc.Iterable} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Iterator (typing 中的类)
@anchor{library/typing typing Iterator}@anchor{3313}
@deffn {类} typing.Iterator (Iterable[T_co])

@ref{184a,,collections.abc.Iterator} 的泛型版本。


3.9 版后已移除: @ref{184a,,collections.abc.Iterator} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Generator (typing 中的类)
@anchor{library/typing typing Generator}@anchor{3314}
@deffn {类} typing.Generator (Iterator[T_co], Generic[T_co, T_contra, V_co])

生成器可以由泛型类型 @code{Generator[YieldType, SendType, ReturnType]} 注解。例如：

@example
def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'
@end example

注意，与 typing 模块里的其他泛型不同， @ref{3314,,Generator} 的 @code{SendType} 属于逆变行为，不是协变行为，也是不变行为。

如果生成器只产生值，可将 @code{SendType} 与 @code{ReturnType} 设为 @code{None}：

@example
def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1
@end example

此外，还可以把生成器的返回类型注解为 @code{Iterable[YieldType]} 或 @code{Iterator[YieldType]}：

@example
def infinite_stream(start: int) -> Iterator[int]:
    while True:
        yield start
        start += 1
@end example


3.9 版后已移除: @ref{7b2,,collections.abc.Generator} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Hashable (typing 中的类)
@anchor{library/typing typing Hashable}@anchor{3315}
@deffn {类} typing.Hashable

@ref{1af1,,collections.abc.Hashable} 的别名。
@end deffn

@geindex Reversible (typing 中的类)
@anchor{library/typing typing Reversible}@anchor{3316}
@deffn {类} typing.Reversible (Iterable[T_co])

@ref{630,,collections.abc.Reversible} 的泛型版本。


3.9 版后已移除: @ref{630,,collections.abc.Reversible} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Sized (typing 中的类)
@anchor{library/typing typing Sized}@anchor{3317}
@deffn {类} typing.Sized

@ref{1af2,,collections.abc.Sized} 的别名。
@end deffn

@node 异步编程,上下文管理器类型<2>,collections abc 对应的其他类型,抽象基类
@anchor{library/typing asynchronous-programming}@anchor{3318}
@subsubsection 异步编程


@geindex Coroutine (typing 中的类)
@anchor{library/typing typing Coroutine}@anchor{1045}
@deffn {类} typing.Coroutine (Awaitable[V_co], Generic[T_co, T_contra, V_co])

@ref{7b4,,collections.abc.Coroutine} 的泛型版本。类型变量的差异和顺序与 @ref{3314,,Generator} 的内容相对应，例如：

@example
from collections.abc import Coroutine
c: Coroutine[list[str], str, int]  # Some coroutine defined elsewhere
x = c.send('hi')                   # Inferred type of 'x' is list[str]
async def bar() -> None:
    y = await c                    # Inferred type of 'y' is int
@end example


3.5.3 新版功能.



3.9 版后已移除: @ref{7b4,,collections.abc.Coroutine} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex AsyncGenerator (typing 中的类)
@anchor{library/typing typing AsyncGenerator}@anchor{3319}
@deffn {类} typing.AsyncGenerator (AsyncIterator[T_co], Generic[T_co, T_contra])

异步生成器可由泛型类型 @code{AsyncGenerator[YieldType, SendType]} 注解。例如：

@example
async def echo_round() -> AsyncGenerator[int, float]:
    sent = yield 0
    while sent >= 0.0:
        rounded = await round(sent)
        sent = yield rounded
@end example

与常规生成器不同，异步生成器不能返回值，因此没有 @code{ReturnType} 类型参数。 与 @ref{3314,,Generator} 类似，@code{SendType} 也属于逆变行为。

如果生成器只产生值，可将 @code{SendType} 设置为 @code{None}：

@example
async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
    while True:
        yield start
        start = await increment(start)
@end example

此外，可用 @code{AsyncIterable[YieldType]} 或 @code{AsyncIterator[YieldType]} 注解生成器的返回类型：

@example
async def infinite_stream(start: int) -> AsyncIterator[int]:
    while True:
        yield start
        start = await increment(start)
@end example


3.6.1 新版功能.



3.9 版后已移除: @ref{632,,collections.abc.AsyncGenerator} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex AsyncIterable (typing 中的类)
@anchor{library/typing typing AsyncIterable}@anchor{331a}
@deffn {类} typing.AsyncIterable (Generic[T_co])

@ref{7b6,,collections.abc.AsyncIterable} 的泛型版本。


3.5.2 新版功能.



3.9 版后已移除: @ref{7b6,,collections.abc.AsyncIterable} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex AsyncIterator (typing 中的类)
@anchor{library/typing typing AsyncIterator}@anchor{331b}
@deffn {类} typing.AsyncIterator (AsyncIterable[T_co])

@ref{7b5,,collections.abc.AsyncIterator} 的泛型版本。


3.5.2 新版功能.



3.9 版后已移除: @ref{7b5,,collections.abc.AsyncIterator} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex Awaitable (typing 中的类)
@anchor{library/typing typing Awaitable}@anchor{331c}
@deffn {类} typing.Awaitable (Generic[T_co])

@ref{7b3,,collections.abc.Awaitable} 的泛型版本。


3.5.2 新版功能.



3.9 版后已移除: @ref{7b3,,collections.abc.Awaitable} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@node 上下文管理器类型<2>,,异步编程,抽象基类
@anchor{library/typing context-manager-types}@anchor{331d}
@subsubsection 上下文管理器类型


@geindex ContextManager (typing 中的类)
@anchor{library/typing typing ContextManager}@anchor{637}
@deffn {类} typing.ContextManager (Generic[T_co])

@ref{636,,contextlib.AbstractContextManager} 的泛型版本。


3.5.4 新版功能.



3.6.0 新版功能.



3.9 版后已移除: @ref{636,,contextlib.AbstractContextManager} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@geindex AsyncContextManager (typing 中的类)
@anchor{library/typing typing AsyncContextManager}@anchor{331e}
@deffn {类} typing.AsyncContextManager (Generic[T_co])

@ref{489,,contextlib.AbstractAsyncContextManager} 的泛型版本。


3.5.4 新版功能.



3.6.2 新版功能.



3.9 版后已移除: @ref{489,,contextlib.AbstractAsyncContextManager} 现已支持 @code{[]}。详见 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 和 @ref{1030,,GenericAlias 类型}。

@end deffn

@node 协议<3>,函数与装饰器,抽象基类,模块内容<7>
@anchor{library/typing protocols}@anchor{331f}
@subsubsection 协议


这些协议由 @ref{372,,runtime_checkable()} 装饰。

@geindex SupportsAbs (typing 中的类)
@anchor{library/typing typing SupportsAbs}@anchor{3320}
@deffn {类} typing.SupportsAbs

含抽象方法 @code{__abs__} 的抽象基类，是其返回类型里的协变量。
@end deffn

@geindex SupportsBytes (typing 中的类)
@anchor{library/typing typing SupportsBytes}@anchor{3321}
@deffn {类} typing.SupportsBytes

含抽象方法 @code{__bytes__} 的抽象基类。
@end deffn

@geindex SupportsComplex (typing 中的类)
@anchor{library/typing typing SupportsComplex}@anchor{3322}
@deffn {类} typing.SupportsComplex

含抽象方法 @code{__complex__} 的抽象基类。
@end deffn

@geindex SupportsFloat (typing 中的类)
@anchor{library/typing typing SupportsFloat}@anchor{32eb}
@deffn {类} typing.SupportsFloat

含抽象方法 @code{__float__} 的抽象基类。
@end deffn

@geindex SupportsIndex (typing 中的类)
@anchor{library/typing typing SupportsIndex}@anchor{374}
@deffn {类} typing.SupportsIndex

含抽象方法 @code{__index__} 的抽象基类。


3.8 新版功能.

@end deffn

@geindex SupportsInt (typing 中的类)
@anchor{library/typing typing SupportsInt}@anchor{373}
@deffn {类} typing.SupportsInt

含抽象方法 @code{__int__} 的抽象基类。
@end deffn

@geindex SupportsRound (typing 中的类)
@anchor{library/typing typing SupportsRound}@anchor{3323}
@deffn {类} typing.SupportsRound

含抽象方法 @code{__round__} 的抽象基类，是其返回类型的协变量。
@end deffn

@node 函数与装饰器,内省辅助器,协议<3>,模块内容<7>
@anchor{library/typing functions-and-decorators}@anchor{3324}
@subsubsection 函数与装饰器


@geindex cast() (在 typing 模块中)
@anchor{library/typing typing cast}@anchor{3325}
@deffn {函数} typing.cast (typ, val)

把值强制转换为类型。

不变更返回值。对类型检查器而言，代表了返回值具有指定的类型，但运行时故意不做任何检查（以便让检查速度尽量快）。
@end deffn

@geindex overload() (在 typing 模块中)
@anchor{library/typing typing overload}@anchor{3326}
@deffn {函数} @@typing.overload

@code{@@overload} 装饰器可以修饰支持多个不同参数类型组合的函数或方法。@code{@@overload} - 装饰定义的系列必须紧跟一个非 @code{@@overload}-装饰定义（用于同一个函数/方法）。@code{@@overload}-装饰定义仅是为了协助类型检查器， 因为该装饰器会被非 @code{@@overload}-装饰定义覆盖，后者用于运行时，而且会被类型检查器忽略。在运行时直接调用 @code{@@overload} 装饰的函数会触发 @ref{70e,,NotImplementedError}。下面的重载示例给出了比联合类型或类型变量更精准的类型：

@example
@@overload
def process(response: None) -> None:
    ...
@@overload
def process(response: int) -> tuple[int, str]:
    ...
@@overload
def process(response: bytes) -> str:
    ...
def process(response):
    <actual implementation>
@end example

详见 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484}，与其他类型语义进行对比。
@end deffn

@geindex final() (在 typing 模块中)
@anchor{library/typing typing final}@anchor{370}
@deffn {函数} @@typing.final

告知类型检查器被装饰的方法不能被覆盖，且被装饰的类不能作为子类的装饰器，例如：

@example
class Base:
    @@final
    def done(self) -> None:
        ...
class Sub(Base):
    def done(self) -> None:  # Error reported by type checker
        ...

@@final
class Leaf:
    ...
class Other(Leaf):  # Error reported by type checker
    ...
@end example

这些属性没有运行时检查。详见 
@geindex Python 提高建议; PEP 591
PEP 591@footnote{https://www.python.org/dev/peps/pep-0591}。


3.8 新版功能.

@end deffn

@geindex no_type_check() (在 typing 模块中)
@anchor{library/typing typing no_type_check}@anchor{3327}
@deffn {函数} @@typing.no_type_check

标明注解不是类型提示的装饰器。

用作类或函数的 @ref{174,,decorator}。用于类时，递归地应用于该类中定义的所有方法，（但不影响超类或子类中定义的方法）。

本方法可直接修改函数。
@end deffn

@geindex no_type_check_decorator() (在 typing 模块中)
@anchor{library/typing typing no_type_check_decorator}@anchor{3328}
@deffn {函数} @@typing.no_type_check_decorator

让其他装饰器具有 @ref{3327,,no_type_check()} 效果的装饰器。

本装饰器用 @ref{3327,,no_type_check()} 里的装饰函数打包其他装饰器。
@end deffn

@geindex type_check_only() (在 typing 模块中)
@anchor{library/typing typing type_check_only}@anchor{3329}
@deffn {函数} @@typing.type_check_only

标记类或函数内不可用于运行时的装饰器。

在运行时，该装饰器本身不可用。实现返回的是私有类实例时，它主要是用于标记在类型存根文件中定义的类。

@example
@@type_check_only
class Response:  # private or not available at runtime
    code: int
    def get_header(self, name: str) -> str: ...

def fetch_response() -> Response: ...
@end example

注意，建议不要返回私有类实例，最好将之设为公共类。
@end deffn

@node 内省辅助器,常量<4>,函数与装饰器,模块内容<7>
@anchor{library/typing introspection-helpers}@anchor{332a}
@subsubsection 内省辅助器


@geindex get_type_hints() (在 typing 模块中)
@anchor{library/typing typing get_type_hints}@anchor{1f0}
@deffn {函数} typing.get_type_hints (obj, globalns=None, localns=None, include_extras=False)

返回函数、方法、模块、类对象的类型提示的字典。

一般情况下，与 @code{obj.__annotations__} 相同。此外，可通过在 @code{globals} 与 @code{locals} 命名空间里进行评估，以此来处理编码为字符串字面量的前向引用。如有需要，在默认值设置为 @code{None} 时，可为函数或方法注解添加 @code{Optional[t]}。对于类 @code{C}，则返回由所有 @code{__annotations__} 与 @code{C.__mro__} 逆序合并而成的字典。

本函数以递归地方式用 @code{T} 替换所有 @code{Annotated[T, ...]}， 除非将 @code{include_extras} 的值设置为 @code{True} （详见 @ref{1ef,,Annotated}）。例如：

@example
class Student(NamedTuple):
    name: Annotated[str, 'some marker']

get_type_hints(Student) == @{'name': str@}
get_type_hints(Student, include_extras=False) == @{'name': str@}
get_type_hints(Student, include_extras=True) == @{
    'name': Annotated[str, 'some marker']
@}
@end example


在 3.9 版更改: 
@geindex Python 提高建议; PEP 593
PEP 593@footnote{https://www.python.org/dev/peps/pep-0593} 的组成部分，添加了 @code{include_extras} 参数。

@end deffn

@geindex get_args() (在 typing 模块中)
@anchor{library/typing typing get_args}@anchor{27e}
@deffn {函数} typing.get_args (tp)
@end deffn

@geindex get_origin() (在 typing 模块中)
@anchor{library/typing typing get_origin}@anchor{375}
@deffn {函数} typing.get_origin (tp)

为泛型类型与特殊类型形式提供了基本的内省功能。

对于 @code{X[Y, Z, ...]} 形式的类型对象，这些函数返回 @code{X} 与 @code{(Y, Z, ...)}。如果 @code{X} 是内置对象或 @ref{1d,,collections} class 的泛型别名， 会将其标准化为原始类。如果 @code{X} 是包含在其他泛型类型中的 @ref{11b3,,Union} 或 @ref{276,,Literal}，@code{(Y, Z, ...)} 的顺序会因类型缓存，而与原始参数 @code{[Y, Z, ...]} 的顺序不同。对于不支持的对象会相应地返回 @code{None} 或 @code{()}。例如：

@example
assert get_origin(Dict[str, int]) is dict
assert get_args(Dict[int, str]) == (int, str)

assert get_origin(Union[int, str]) is Union
assert get_args(Union[int, str]) == (int, str)
@end example


3.8 新版功能.

@end deffn

@geindex ForwardRef (typing 中的类)
@anchor{library/typing typing ForwardRef}@anchor{f90}
@deffn {类} typing.ForwardRef

用于字符串前向引用的内部类型表示的类。 例如，@code{List["SomeClass"]} 会被隐式转换为 @code{List[ForwardRef("SomeClass")]}。 这个类不应由用户来实例化，但可以由内省工具使用。

@cartouche
@quotation 注解 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} 泛型类型例如 @code{list["SomeClass"]} 将不会被隐式地转换为 @code{list[ForwardRef("SomeClass")]} 因而将不会自动解析为 @code{list[SomeClass]}。
@end quotation
@end cartouche


3.7.4 新版功能.

@end deffn

@node 常量<4>,,内省辅助器,模块内容<7>
@anchor{library/typing constant}@anchor{332b}
@subsubsection 常量


@geindex TYPE_CHECKING() (在 typing 模块中)
@anchor{library/typing typing TYPE_CHECKING}@anchor{6a5}
@deffn {数据} typing.TYPE_CHECKING

被第三方静态类型检查器假定为 @code{True} 的特殊常量。在运行时为 @code{False}。用法如下：

@example
if TYPE_CHECKING:
    import expensive_mod

def fun(arg: 'expensive_mod.SomeType') -> None:
    local_var: expensive_mod.AnotherType = other_fun()
@end example

第一个类型注解必须用引号标注，才能把它当作“前向引用”，从而在解释器运行时中隐藏 @code{expensive_mod} 引用。局部变量的类型注释不会被评估，因此，第二个注解不需要用引号引起来。

@cartouche
@quotation 注解 
使用 @code{from __future__ import} 时，函数定义时不处理注解， 而是把注解当作字符串存在 @code{__annotations__} 里，这样就不必为注解使用引号。（详见 
@geindex Python 提高建议; PEP 563
PEP 563@footnote{https://www.python.org/dev/peps/pep-0563}）。
@end quotation
@end cartouche


3.5.2 新版功能.

@end deffn

@node pydoc --- 文档生成器和在线帮助系统,Python 开发模式,typing --- 类型提示支持,开发工具
@anchor{library/pydoc doc}@anchor{332c}@anchor{library/pydoc module-pydoc}@anchor{d9}@anchor{library/pydoc pydoc-documentation-generator-and-online-help-system}@anchor{332d}
@subsection @code{pydoc} --- 文档生成器和在线帮助系统


@geindex pydoc (模块)

@strong{源代码:} Lib/pydoc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pydoc.py}

@geindex documentation; generation
@geindex documentation; online
@geindex help; online


__________________________________________________________________


@ref{d9,,pydoc} 模块自动利用 Python 模块生成文档。生成的文档可在控制台中显示为文本页面，还可在 Web 浏览器中查阅，或保存为 HTML 文件。

对于模块、类、函数和方法，显示的文档内容取自文档字符串（即 @code{__doc__} 属性），并会递归地从其带文档的成员中获取。 如果没有文档字符串，@ref{d9,,pydoc} 会尝试从类、函数或方法定义上方，或是模块顶部的注释行段落获取 (参见 @ref{332e,,inspect.getcomments()}).

内置函数 @ref{175,,help()} 会发起调用交互式解释器的在线帮助系统，该系统使用 @ref{d9,,pydoc} 在终端上生成文本形式的文档内容。 同样的文本文档也可以在 Python 解释器以外通过在操作系统的命令提示符下以脚本方式运行 @code{pydoc} 来查看。 例如，运行

@example
pydoc sys
@end example

在终端提示符下将通过 @ref{fd,,sys} 模块显示文档内容，其样式类似于 Unix @code{man} 命令所显示的指南页面。 @code{pydoc} 的参数可以为函数、模块、包，或带点号的对模块中的类、方法或函数以及包中的模块的引用。 如果传给 @code{pydoc} 的参数像是一个路径（即包含所在操作系统的路径分隔符，例如 Unix 的正斜杠），并且其指向一个现有的 Python 源文件，则会为该文件生成文档内容。

@cartouche
@quotation 注解 
为了找到对象及其文档内容，@ref{d9,,pydoc} 会导入文档所在的模块。 因此，任何模块层级的代码都将被执行。 请使用 @code{if __name__ == '__main__':} 语句来确保一个文件的特定代码仅在作为脚本被发起调用时执行而不是在被导入时执行。
@end quotation
@end cartouche

当打印输出到控制台时，@code{pydoc} 会尝试对输出进行分页以方便阅读。 如果设置了 
@geindex PAGER
@geindex 环境变量; PAGER
@code{PAGER} 环境变量，@code{pydoc} 将使用该变量值作为分页程序。

在参数前指定 @code{-w} 旗标将把 HTML 文档写入到当前目录下的一个文件中，而不是在控制台中显示文本。

在参数前指定 @code{-k} 旗标将在全部可用模块的提要行中搜索参数所给定的关键字，具体方式同样类似于 Unix @code{man} 命令。 模块的提要行就是其文档字符串的第一行。

你还可以使用 @code{pydoc} 在本机上启动一个 HTTP 服务，这将向来访的 Web 浏览器提供文档服务。 @code{pydoc -p 1234} 将在 1234 端口上启动 HTTP 服务，允许你在你喜欢的 Web 服务器中通过 @code{http://localhost:1234/} 浏览文档内容。 指定 @code{0} 作为端口号将会任意选择一个未使用的端口。

@code{pydoc -n <hostname>} 将启动在给定主机名上执行监听的服务。 默认主机名为 'localhost' 但如果你希望能从其他机器搜索该服务器，你可能会想要改变服务器所响应的主机名。 在开发阶段此特性会特别有用，因为这样你将能在一个容器中运行 pydoc。

@code{pydoc -b} 将启动服务并额外打开一个 Web 浏览器访问模块索引页。 所发布的每个页面顶端都带有导航栏，你可以点击 @emph{Get} 获取特定条目的帮助，点击 @emph{Search} 在所有模块的提要行中搜索特定关键词，或是点击 @emph{Module index}, @emph{Topics} 和 @emph{Keywords} 前往相应的页面。

当 @code{pydoc} 生成文档内容时，它会使用当前环境和路径来定位模块。 因此，发起调用 @code{pydoc spam} 得到的文档版本会与你启动 Python 解释器并输入 @code{import spam} 时得到的模块版本完全相同。

核心模块的模块文档位置对应于 @code{https://docs.python.org/X.Y/library/} 其中 @code{X} 和 @code{Y} 是 Python 解释器的主要版本号和小版本号。 这可通过设置 
@geindex PYTHONDOCS
@geindex 环境变量; PYTHONDOCS
@code{PYTHONDOCS} 环境变量来重载为指向不同的 URL 或包含 Library Reference Manual 页面的本地目录。


在 3.2 版更改: 添加 @code{-b} 选项。



在 3.3 版更改: 命令行选项 @code{-g} 已经移除。



在 3.4 版更改: @ref{d9,,pydoc} 现在会使用 @ref{65e,,inspect.signature()} 而非 @ref{660,,inspect.getfullargspec()} 来从可调用对象中提取签名信息。



在 3.7 版更改: 添加 @code{-n} 选项。


@node Python 开发模式,Python 开发模式的效果,pydoc --- 文档生成器和在线帮助系统,开发工具
@anchor{library/devmode doc}@anchor{332f}@anchor{library/devmode devmode}@anchor{160}@anchor{library/devmode python-development-mode}@anchor{3330}
@subsection Python 开发模式



3.7 新版功能.


Python 开发模式引入了额外的运行时检查，由于成本太高，所以默认情况下是不启用的。如果代码是正确的，它不应该比默认情况的更加详细；只有在检测到问题的时候才会发出新的警告。

它可以通过 @ref{297,,-X dev} 命令行选项或通过设置 
@geindex PYTHONDEVMODE
@geindex 环境变量; PYTHONDEVMODE
@ref{445,,PYTHONDEVMODE} 环境变量为 @code{1} 来启用。

@node Python 开发模式的效果,ResourceWarning 示例,Python 开发模式,开发工具
@anchor{library/devmode effects-of-the-python-development-mode}@anchor{3331}
@subsection Python 开发模式的效果


启用 Python 开发模式后的效果，与以下命令类似，不过还有下面的额外效果：

@example
PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python3 -W default -X faulthandler
@end example

Python 开发模式的效果：


@itemize *

@item 
加入 @code{default} @ref{14ae,,warning filter} 。下述警告信息将会显示出来：


@itemize *

@item 
@ref{15a,,DeprecationWarning}

@item 
@ref{6d9,,ImportWarning}

@item 
@ref{15c,,PendingDeprecationWarning}

@item 
@ref{5d3,,ResourceWarning}
@end itemize

通常上述警告是由默认的 @ref{14ae,,warning filters} 负责处理的。

其行为相当于使用了 @ref{15b,,-W default} 命令行选项。

使用命令行参数 @ref{15b,,-W error} 或将环境变量 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS} 设为 @code{error}，可将警告视为错误。

@item 
在内存分配程序中安装调试钩子，用以查看：


@itemize *

@item 
缓冲区下溢

@item 
缓冲区上溢

@item 
内存分配 API 冲突

@item 
不安全的 GIL 调用
@end itemize

参见 C 函数 @ref{60c,,PyMem_SetupDebugHooks()} 。

效果类似于将环境变量 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 设为 @code{debug}。

若要启用 Python 开发模式，却又不要在内存分配程序中安装调试钩子，请将 环境变量 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 设为 @code{default}。

@item 
在启动 Python 时调用 @ref{64b,,faulthandler.enable()} ，会安装 @code{SIGSEGV} 、 @code{SIGFPE} 、 @code{SIGABRT} 、 @code{SIGBUS} 和 @code{SIGILL} 信号的处理程序，以便在程序崩溃时将 Python 跟踪信息转储下来。

其行为如同使用了 @ref{297,,-X faulthandler} 命令行选项或将 
@geindex PYTHONFAULTHANDLER
@geindex 环境变量; PYTHONFAULTHANDLER
@ref{ab0,,PYTHONFAULTHANDLER} 环境变量设为 @code{1}。

@item 
启用 @ref{14be,,asyncio debug mode}。比如 @ref{9,,asyncio} 会检查没有等待的协程并记录下来。

效果如同将环境变量 
@geindex PYTHONASYNCIODEBUG
@geindex 环境变量; PYTHONASYNCIODEBUG
@ref{14bd,,PYTHONASYNCIODEBUG} 设为 @code{1}。

@item 
检查字符串编码和解码函数的 @emph{encoding} 和 @emph{errors} 参数。例如： @ref{16f,,open()} 、 @ref{170,,str.encode()} 和 @ref{171,,bytes.decode()}。

为了获得最佳性能，默认只会在第一次编码/解码错误时才会检查  @emph{errors} 参数，有时 @emph{encoding} 参数为空字符串时还会被忽略。

@item 
@ref{313,,io.IOBase} 的析构函数会记录 @code{close()} 触发的异常。

@item 
将 @ref{c17,,sys.flags} 的 @code{dev_mode} 属性设为 @code{True}。
@end itemize

Python 开发模式下，默认不会启用 @ref{11d,,tracemalloc} 模块，因为其性能和内存开销太大。启用 @ref{11d,,tracemalloc} 模块后，能够提供有关错误来源的一些额外信息。例如，@ref{5d3,,ResourceWarning} 记录了资源分配的跟踪信息，而缓冲区溢出错误记录了内存块分配的跟踪信息。

Python 开发模式不会阻止命令行参数 @ref{788,,-O} 删除 @ref{240,,assert} 语句，也不会阻止将 @ref{1180,,__debug__} 设为 @code{False}。


在 3.8 版更改: 现在， @ref{313,,io.IOBase} 的析构函数会记录 @code{close()} 触发的异常。



在 3.9 版更改: 现在，字符串编码和解码操作时会检查 @emph{encoding} 和 @emph{errors} 参数。


@node ResourceWarning 示例,文件描述符错误示例,Python 开发模式的效果,开发工具
@anchor{library/devmode resourcewarning-example}@anchor{3332}
@subsection ResourceWarning 示例


以下示例将统计由命令行指定的文本文件的行数：

@example
import sys

def main():
    fp = open(sys.argv[1])
    nlines = len(fp.readlines())
    print(nlines)
    # The file is closed implicitly

if __name__ == "__main__":
    main()
@end example

上述代码没有显式关闭文件。默认情况下，Python 不会触发任何警告。下面用 README.txt 文件测试下，有 269 行。

@example
$ python3 script.py README.txt
269
@end example

启用 Python 开发模式后，则会显示一条 @ref{5d3,,ResourceWarning} 警告。

@example
$ python3 -X dev script.py README.txt
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
@end example

启用 @ref{11d,,tracemalloc} 后，则还会显示打开文件的那行代码：

@example
$ python3 -X dev -X tracemalloc=5 script.py README.rst
269
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README.rst' mode='r' encoding='UTF-8'>
  main()
Object allocated at (most recent call last):
  File "script.py", lineno 10
    main()
  File "script.py", lineno 4
    fp = open(sys.argv[1])
@end example

修正方案就是显式关闭文件。下面用上下文管理器作为示例：

@example
def main():
    # Close the file explicitly when exiting the with block
    with open(sys.argv[1]) as fp:
        nlines = len(fp.readlines())
    print(nlines)
@end example

未能显式关闭资源，会让资源打开时长远超预期；在退出 Python 时可能会导致严重问题。这在 CPython 中比较糟糕，但在 PyPy 中会更糟。显式关闭资源能让应用程序更加稳定可靠。

@node 文件描述符错误示例,doctest --- 测试交互性的Python示例,ResourceWarning 示例,开发工具
@anchor{library/devmode bad-file-descriptor-error-example}@anchor{3333}
@subsection 文件描述符错误示例


显示自身的第一行代码：

@example
import os

def main():
    fp = open(__file__)
    firstline = fp.readline()
    print(firstline.rstrip())
    os.close(fp.fileno())
    # The file is closed implicitly

main()
@end example

默认情况下，Python 不会触发任何警告：

@example
$ python3 script.py
import os
@end example

在 Python 开发模式下，会在析构文件对象时显示 @ref{5d3,,ResourceWarning} 并记录 “Bad file descriptor” 错误。

@example
$ python3 script.py
import os
script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' encoding='UTF-8'>
Traceback (most recent call last):
  File "script.py", line 10, in <module>
    main()
OSError: [Errno 9] Bad file descriptor
@end example

@code{os.close(fp.fileno())} 会关闭文件描述符。当文件对象析构函数试图再次关闭文件描述符时会失败，并触发 @code{Bad file descriptor} 错误。每个文件描述符只允许关闭一次。在最坏的情况下，关闭两次会导致程序崩溃（示例可参见 bpo-18748@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=18748} ）。

修正方案是删除 @code{os.close(fp.fileno())} 这一行，或者打开文件时带上 @code{closefd=False} 参数。

@node doctest --- 测试交互性的Python示例,unittest --- 单元测试框架,文件描述符错误示例,开发工具
@anchor{library/doctest doc}@anchor{3334}@anchor{library/doctest doctest-test-interactive-python-examples}@anchor{3335}@anchor{library/doctest module-doctest}@anchor{66}
@subsection @code{doctest} --- 测试交互性的Python示例


@geindex doctest (模块)

** 源代码 ** Lib/doctest.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/doctest.py}


__________________________________________________________________


@ref{66,,doctest} 模块寻找像Python交互式代码的文本，然后执行这些代码来确保它们的确就像展示的那样正确运行，有许多方法来使用doctest：


@itemize *

@item 
通过验证所有交互式示例仍然按照记录的方式工作，以此来检查模块的文档字符串是否是最新的。

@item 
通过验证来自一个测试文件或一个测试对象的交互式示例按预期工作，来进行回归测试。

@item 
为一个包写指导性的文档，用输入输出的例子来说明。 取决于是强调例子还是说明性的文字，这有一种 "文本测试 "或 "可执行文档 "的风格。
@end itemize

下面是一个小却完整的示例模块:

@example
"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result


if __name__ == "__main__":
    import doctest
    doctest.testmod()
@end example

如果你直接在命令行里运行 @code{example.py} ， @ref{66,,doctest} 将发挥他的作用。

@example
$ python example.py
$
@end example

没有输出！ 这很正常，这意味着所有的例子都成功了。 把 @code{-v} 传给脚本，@ref{66,,doctest} 会打印出它所尝试的详细日志，并在最后打印出一个总结。

@example
$ python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
@end example

以此类推，最终以：

@example
Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 tests in __main__
   8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
@end example

这就是对于高效地使用 @ref{66,,doctest} 你所需要知道的一切！开始上手吧。 下面的章节提供了完整的细节。 请注意，在标准的 Python 测试套件和库中有许多 doctest 的例子。特别有用的例子可以在标准测试文件 @code{Lib/test/test_doctest.py} 中找到。

@menu
* 简单用法：检查Docstrings中的示例:: 
* 简单的用法：检查文本文件中的例子:: 
* 它是如何工作的:: 
* 基本API:: 
* Unittest API:: 
* 高级 API:: 
* 调试:: 
* 肥皂盒:: 

@end menu

@node 简单用法：检查Docstrings中的示例,简单的用法：检查文本文件中的例子,,doctest --- 测试交互性的Python示例
@anchor{library/doctest doctest-simple-testmod}@anchor{3336}@anchor{library/doctest simple-usage-checking-examples-in-docstrings}@anchor{3337}
@subsubsection 简单用法：检查Docstrings中的示例


开始使用doctest的最简单方法（但不一定是你将继续这样做的方式）是结束每个模块 @code{M} 使用:

@example
if __name__ == "__main__":
    import doctest
    doctest.testmod()
@end example

@ref{66,,doctest} 会随后检查模块 @code{M} 中的文档字符串。

以脚本形式运行该模块会使文档中的例子得到执行和验证:

@example
python M.py
@end example

这不会显示任何东西，除非一个例子失败了，在这种情况下，失败的例子和失败的原因会被打印到stdout，最后一行的输出是`@w{`}***Test Failed*** N failures.`@w{`}，其中*N*是失败的例子的数量。

用`@w{`}-v`@w{`}来运行它来切换，而不是:

@example
python M.py -v
@end example

并将所有尝试过的例子的详细报告打印到标准输出，最后还有各种总结。

你可以通过向 @ref{e9d,,testmod()} 传递 @code{verbose=True} 来强制执行 verbose 模式，或者通过传递 @code{verbose=False} 来禁止它。 在这两种情况下，@code{sys.argv} 都不会被 @ref{e9d,,testmod()} 检查（所以传递 @code{-v} 或不传递都没有影响）。

还有一个命令行快捷方式用于运行 @ref{e9d,,testmod()}。 你可以指示Python解释器直接从标准库中运行doctest模块，并在命令行中传递模块名称:

@example
python -m doctest -v example.py
@end example

这将导入 @code{example.py} 作为一个独立的模块，并对其运行 @ref{e9d,,testmod()}。 注意，如果该文件是一个包的一部分，并且从该包中导入了其他子模块，这可能无法正确工作。

关于 @ref{e9d,,testmod()} 的更多信息，请参见 @ref{3338,,基本API} 部分。

@node 简单的用法：检查文本文件中的例子,它是如何工作的,简单用法：检查Docstrings中的示例,doctest --- 测试交互性的Python示例
@anchor{library/doctest doctest-simple-testfile}@anchor{3339}@anchor{library/doctest simple-usage-checking-examples-in-a-text-file}@anchor{333a}
@subsubsection 简单的用法：检查文本文件中的例子


doctest 的另一个简单应用是测试文本文件中的交互式例子。 这可以用 @ref{333b,,testfile()} 函数来完成;:

@example
import doctest
doctest.testfile("example.txt")
@end example

这个简短的脚本执行并验证文件 @code{example.txt} 中包含的任何交互式 Python 示例。该文件的内容被当作一个巨大的文档串来处理；该文件不需要包含一个Python程序！例如，也许 @code{example.txt} 包含以下内容:

@example
The `@w{`}example`@w{`} module
======================

Using `@w{`}factorial`@w{`}
-------------------

This is an example text file in reStructuredText format.  First import
`@w{`}factorial`@w{`} from the `@w{`}example`@w{`} module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120
@end example

运行`@w{`}doctest.testfile("example.txt")`@w{`}，然后发现这个文档中的错误:

@example
File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720
@end example

与 @ref{e9d,,testmod()} 一样， @ref{333b,,testfile()} 不会显示任何东西，除非一个例子失败。 如果一个例子失败了，那么失败的例子和失败的原因将被打印到stdout，使用的格式与 @ref{e9d,,testmod()} 相同。

默认情况下，@ref{333b,,testfile()} 在调用模块的目录中寻找文件。参见章节 @ref{3338,,基本API}，了解可用于告诉它在其他位置寻找文件的可选参数的描述。

像 @ref{e9d,,testmod()} 一样，@ref{333b,,testfile()} 的详细程度可以通过命令行 @code{-v} 切换或可选的关键字参数 @emph{verbose} 来设置。

还有一个命令行快捷方式用于运行 @ref{333b,,testfile()}。 你可以指示Python解释器直接从标准库中运行doctest模块，并在命令行中传递文件名:

@example
python -m doctest -v example.txt
@end example

因为文件名没有以 @code{.py} 结尾，@ref{66,,doctest} 推断它必须用 @ref{333b,,testfile()} 运行，而不是 @ref{e9d,,testmod()}。

关于 @ref{333b,,testfile()} 的更多信息，请参见 @ref{3338,,基本API} 一节。

@node 它是如何工作的,基本API,简单的用法：检查文本文件中的例子,doctest --- 测试交互性的Python示例
@anchor{library/doctest doctest-how-it-works}@anchor{333c}@anchor{library/doctest how-it-works}@anchor{333d}
@subsubsection 它是如何工作的


这一节详细研究了doctest的工作原理：它查看哪些文档串，它如何找到交互式的用例，它使用什么执行环境，它如何处理异常，以及如何用选项标志来控制其行为。这是你写doctest例子所需要知道的信息；关于在这些例子上实际运行doctest的信息，请看下面的章节。

@menu
* 哪些文件串被检查了？:: 
* 文档串的例子是如何被识别的？:: 
* 什么是执行上下文:: 
* 异常如何处理？:: 
* 选项标记:: 
* 指令:: 
* 警告: 警告<2>. 

@end menu

@node 哪些文件串被检查了？,文档串的例子是如何被识别的？,,它是如何工作的
@anchor{library/doctest doctest-which-docstrings}@anchor{333e}@anchor{library/doctest which-docstrings-are-examined}@anchor{333f}
@subsubsection 哪些文件串被检查了？


模块的文档串以及所有函数、类和方法的文档串都将被搜索。 导入模块的对象不被搜索。

此外，如果 @code{M.__test__} 存在并且 "为真值"，则它必须是一个字典，其中每个条目都将一个（字符串）名称映射到一个函数对象、类对象或字符串。 从 @code{M.__test__} 找到的函数和类对象的文档字符串会被搜索，而字符串会被当作文档字符串来处理。 在输出时，每个键 @code{K} 在 @code{M.__test__} 中都显示为其名称

@example
<name of M>.__test__.K
@end example

任何发现的类都会以类似的方式进行递归搜索，以测试其包含的方法和嵌套类中的文档串。

@strong{CPython implementation detail:} Prior to version 3.4, extension modules written in C were not fully
searched by doctest.

@node 文档串的例子是如何被识别的？,什么是执行上下文,哪些文件串被检查了？,它是如何工作的
@anchor{library/doctest doctest-finding-examples}@anchor{3340}@anchor{library/doctest how-are-docstring-examples-recognized}@anchor{3341}
@subsubsection 文档串的例子是如何被识别的？


在大多数情况下，对交互式控制台会话的复制和粘贴功能工作得很好，但是 doctest 并不试图对任何特定的 Python shell 进行精确的模拟。

@example
>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
...     print("yes")
... else:
...     print("no")
...     print("NO")
...     print("NO!!!")
...
no
NO
NO!!!
>>>
@end example

@geindex >>>; interpreter prompt
@geindex ...; interpreter prompt

任何预期的输出必须紧随包含代码的最后 @code{'>>> '} 或 @code{'... '} 行，预期的输出（如果有的话）延伸到下一 @code{'>>> '} 行或全空白行。

fine输出：


@itemize *

@item 
预期输出不能包含一个全白的行，因为这样的行被认为是预期输出的结束信号。 如果预期的输出包含一个空行，在你的测试例子中，在每一个预期有空行的地方加上`@w{`}<BLANKLINE>`@w{`}。

@item 
所有硬制表符都被扩展为空格，使用 8 列的制表符。由测试代码生成的输出中的制表符不会被修改。 因为样本输出中的任何硬制表符都会被扩展，这意味着如果代码输出包括硬制表符，文档测试通过的唯一方法是 @ref{3342,,NORMALIZE_WHITESPACE} 选项或者 @ref{3343,,指令} 是有效的。 另外，测试可以被重写，以捕获输出并将其与预期值进行比较，作为测试的一部分。这种对源码中标签的处理是通过试错得出的，并被证明是最不容易出错的处理方式。通过编写一个自定义的 @ref{3344,,DocTestParser} 类，可以使用一个不同的算法来处理标签。

@item 
向stdout的输出被捕获，但不向stderr输出（异常回溯通过不同的方式被捕获）。

@item 
如果你在交互式会话中通过反斜线续行，或出于任何其他原因使用反斜线，你应该使用原始文件串，它将完全保留你输入的反斜线:

@example
>>> def f(x):
...     r'@w{'}'Backslashes in a raw docstring: m\n'@w{'}'
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
@end example

否则，反斜杠将被解释为字符串的一部分。例如，上面的`@w{`}n`@w{`}会被解释为一个换行符。 另外，你可以在doctest版本中把每个反斜杠加倍（而不使用原始字符串）:

@example
>>> def f(x):
...     '@w{'}'Backslashes in a raw docstring: m\\n'@w{'}'
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n
@end example

@item 
起始列并不重要:

@example
>>> assert "Easy!"
      >>> import math
          >>> math.floor(1.9)
          1
@end example

并从预期的输出中剥离出与开始该例子的初始 @code{'>>> '} 行中出现的同样多的前导空白字符。
@end itemize

@node 什么是执行上下文,异常如何处理？,文档串的例子是如何被识别的？,它是如何工作的
@anchor{library/doctest doctest-execution-context}@anchor{3345}@anchor{library/doctest what-s-the-execution-context}@anchor{3346}
@subsubsection 什么是执行上下文


默认情况下，每次 @ref{66,,doctest} 找到要测试的文档串时，它都会使用 @code{M} 的*浅层副本*，这样运行测试就不会改变模块的真正全局变量，而且 @code{M} 的一个测试也不会留下临时变量，从而意外地让另一个测试通过。这意味着例子可以自由地使用 @code{M} 中的任何顶级定义的名字，以及正在运行的文档串中早期定义的名字。用例不能看到其他文档串中定义的名字。

你可以通过将`@w{`}globs=your_dict`@w{`}传递给 @ref{e9d,,testmod()} 或 @ref{333b,,testfile()} 来强制使用你自己的dict作为执行环境。

@node 异常如何处理？,选项标记,什么是执行上下文,它是如何工作的
@anchor{library/doctest doctest-exceptions}@anchor{3347}@anchor{library/doctest what-about-exceptions}@anchor{3348}
@subsubsection 异常如何处理？


没问题，只要回溯是这个例子产生的唯一输出：只要粘贴回溯即可。@footnote{@w{(1)} 
不支持同时包含预期输出和异常的用例。试图猜测一个在哪里结束，另一个在哪里开始，太容易出错了，而且这也会使测试变得混乱。
} 由于回溯所包含的细节可能会迅速变化（例如，确切的文件路径和行号），这是doctest努力使其接受的内容具有灵活性的一种情况。

简单实例:

@example
>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
@end example

如果 @ref{16d,,ValueError} 被触发，该测试就会成功，@code{list.remove(x): x not in list} 的细节如图所示。

异常的预期输出必须以回溯头开始，可以是以下两行中的任何一行，缩进程度与例子中的第一行相同:

@example
Traceback (most recent call last):
Traceback (innermost last):
@end example

回溯头的后面是一个可选的回溯堆栈，其内容被doctest忽略。 回溯堆栈通常是省略的，或者从交互式会话中逐字复制的。

回溯堆栈的后面是最有趣的部分：包含异常类型和细节的一行（几行）。 这通常是回溯的最后一行，但如果异常有多行细节，则可以延伸到多行:

@example
>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: multi
    line
detail
@end example

最后三行（以 @ref{16d,,ValueError} 开头）将与异常的类型和细节进行比较，其余的被忽略。

最佳实践是省略回溯栈，除非它为这个例子增加了重要的文档价值。 因此，最后一个例子可能更好，因为:

@example
>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
    ...
ValueError: multi
    line
detail
@end example

请注意，回溯的处理方式非常特别。 特别是，在重写的例子中，@code{...} 的使用与 doctest 的 @ref{e9e,,ELLIPSIS} 选项无关。 该例子中的省略号可以不写，也可以是三个（或三百个）逗号或数字，或者是一个缩进的 Monty Python 短剧的剧本。

有些细节你应该读一遍，但不需要记住：


@itemize *

@item 
Doctest 不能猜测你的预期输出是来自异常回溯还是来自普通打印。 因此，例如，一个期望 @code{ValueError: 42 is prime} 的用例将通过测试，无论 @ref{16d,,ValueError} 是真的被触发，或者该用例只是打印了该回溯文本。 在实践中，普通输出很少以回溯标题行开始，所以这不会产生真正的问题。

@item 
回溯堆栈的每一行（如果有的话）必须比例子的第一行缩进， @emph{或者} 以一个非字母数字的字符开始。 回溯头之后的第一行缩进程度相同，并且以字母数字开始，被认为是异常细节的开始。 当然，这对真正的回溯来说是正确的事情。

@item 
当 @ref{3349,,IGNORE_EXCEPTION_DETAIL} doctest 选项被指定时，最左边的冒号后面的所有内容以及异常名称中的任何模块信息都被忽略。

@item 
交互式 shell 省略了一些 @ref{562,,SyntaxError} 的回溯头行。但 doctest 使用回溯头行来区分异常和非异常。所以在罕见的情况下，如果你需要测试一个省略了回溯头的 @ref{562,,SyntaxError}，你将需要手动添加回溯头行到你的测试用例中。
@end itemize

@geindex ^ (caret); marker


@itemize *

@item 
对于一些 @ref{562,,SyntaxError}，Python 使用 @code{^} 标记显示语法错误的字符位置:

@example
>>> 1 1
  File "<stdin>", line 1
    1 1
      ^
SyntaxError: invalid syntax
@end example

由于显示错误位置的行在异常类型和细节之前，它们不被doctest检查。 例如，下面的测试会通过，尽管它把`@w{`}^`@w{`}标记放在了错误的位置:

@example
>>> 1 1
Traceback (most recent call last):
  File "<stdin>", line 1
    1 1
    ^
SyntaxError: invalid syntax
@end example
@end itemize
@anchor{library/doctest option-flags-and-directives}@anchor{334a}
@node 选项标记,指令,异常如何处理？,它是如何工作的
@anchor{library/doctest doctest-options}@anchor{933}@anchor{library/doctest option-flags}@anchor{334b}
@subsubsection 选项标记


一系列选项旗标控制着 doctest 的各方面行为。 旗标的符号名称以模块常量的形式提供，可以一起 @ref{16a5,,按位或} 并传递给各种函数。 这些名称也可以在 @ref{3343,,doctest 指令} 中使用，并且可以通过 @code{-o} 选项传递给 doctest 命令行接口。


3.4 新版功能: 命令行选项 @code{-o} 。


第一组选项定义了测试语义，控制doctest如何决定实际输出是否与用例的预期输出相匹配方面的问题。

@geindex DONT_ACCEPT_TRUE_FOR_1() (在 doctest 模块中)
@anchor{library/doctest doctest DONT_ACCEPT_TRUE_FOR_1}@anchor{334c}
@deffn {数据} doctest.DONT_ACCEPT_TRUE_FOR_1

默认情况下，如果一个预期的输出块只包含 @code{1}，那么实际的输出块只包含 @code{1} 或只包含 @code{True} 就被认为是匹配的，同样，@code{0} 与 @code{False} 也是如此。 当  @ref{334c,,DONT_ACCEPT_TRUE_FOR_1} 被指定时，两种替换都不允许。 默认行为是为了适应 Python 将许多函数的返回类型从整数改为布尔值；期望 "小整数" 输出的测试在这些情况下仍然有效。 这个选项可能会消失，但不会在几年内消失。
@end deffn

@geindex <BLANKLINE>

@geindex DONT_ACCEPT_BLANKLINE() (在 doctest 模块中)
@anchor{library/doctest doctest DONT_ACCEPT_BLANKLINE}@anchor{334d}
@deffn {数据} doctest.DONT_ACCEPT_BLANKLINE

默认情况下，如果一个预期输出块包含一个只包含字符串 @code{<BLANKLINE>} 的行，那么该行将与实际输出中的一个空行相匹配。 因为一个真正的空行是对预期输出的限定，这是传达预期空行的唯一方法。 当 @ref{334d,,DONT_ACCEPT_BLANKLINE} 被指定时，这种替换是不允许的。
@end deffn

@geindex NORMALIZE_WHITESPACE() (在 doctest 模块中)
@anchor{library/doctest doctest NORMALIZE_WHITESPACE}@anchor{3342}
@deffn {数据} doctest.NORMALIZE_WHITESPACE

当指定时，所有的空白序列（空白和换行）都被视为相等。预期输出中的任何空白序列将与实际输出中的任何空白序列匹配。默认情况下，空白必须完全匹配。 @ref{3342,,NORMALIZE_WHITESPACE} 在预期输出非常长的一行，而你想把它包在源代码的多行中时特别有用。
@end deffn

@geindex ...; in doctests

@geindex ELLIPSIS() (在 doctest 模块中)
@anchor{library/doctest doctest ELLIPSIS}@anchor{e9e}
@deffn {数据} doctest.ELLIPSIS

当指定时，预期输出中的省略号（@code{...}）可以匹配实际输出中的任何子串。这包括跨行的子串和空子串，所以最好保持简单的用法。复杂的用法会导致与`@w{`}.*`@w{`}在正则表达式中容易出现的 "oops, it matched too much!"相同的意外情况。
@end deffn

@geindex IGNORE_EXCEPTION_DETAIL() (在 doctest 模块中)
@anchor{library/doctest doctest IGNORE_EXCEPTION_DETAIL}@anchor{3349}
@deffn {数据} doctest.IGNORE_EXCEPTION_DETAIL

当被指定时，只要有预期类型的异常被引发 doctests 就会预期异常测试通过，即使细节（消息和完整限定异常名称）不匹配。

举例来说，一个例子预期 @code{ValueError: 42} 将通过，如果实际引发的异常是 @code{ValueError: 3*14}，但是如果引发的是 @ref{1ff,,TypeError} 则将失败。 它也将忽略任何包括在异常类前面的完整限定名称，该名称在所使用的不同 Python 版本和代码/库中可能会不同。 因此，以下三种形式对于指定的旗标均有效:

@example
>>> raise Exception('message')
Traceback (most recent call last):
Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
builtins.Exception: message

>>> raise Exception('message')
Traceback (most recent call last):
__main__.Exception: message
@end example

请注意 @ref{e9e,,ELLIPSIS} 也可以被用来忽略异常消息中的细节，但这样的测试仍然可能根据特定模块名称是否存在或是否完全匹配而失败。


在 3.2 版更改: @ref{3349,,IGNORE_EXCEPTION_DETAIL} 现在也忽略了与包含被测异常的模块有关的任何信息。

@end deffn

@geindex SKIP() (在 doctest 模块中)
@anchor{library/doctest doctest SKIP}@anchor{334e}
@deffn {数据} doctest.SKIP

当指定时，完全不运行这个用例。 这在doctest用例既是文档又是测试案例的情况下很有用，一个例子应该包括在文档中，但不应该被检查。例如，这个例子的输出可能是随机的；或者这个例子可能依赖于测试驱动程序所不能使用的资源。

SKIP标志也可用于临时 "注释" 用例。
@end deffn

@geindex COMPARISON_FLAGS() (在 doctest 模块中)
@anchor{library/doctest doctest COMPARISON_FLAGS}@anchor{334f}
@deffn {数据} doctest.COMPARISON_FLAGS

一个比特或运算将上述所有的比较标志放在一起。
@end deffn

第二组选项控制测试失败的报告方式：

@geindex REPORT_UDIFF() (在 doctest 模块中)
@anchor{library/doctest doctest REPORT_UDIFF}@anchor{e9f}
@deffn {数据} doctest.REPORT_UDIFF

当指定时，涉及多行预期和实际输出的故障将使用统一的差异来显示。
@end deffn

@geindex REPORT_CDIFF() (在 doctest 模块中)
@anchor{library/doctest doctest REPORT_CDIFF}@anchor{ea0}
@deffn {数据} doctest.REPORT_CDIFF

当指定时，涉及多行预期和实际输出的故障将使用上下文差异来显示。
@end deffn

@geindex REPORT_NDIFF() (在 doctest 模块中)
@anchor{library/doctest doctest REPORT_NDIFF}@anchor{ea1}
@deffn {数据} doctest.REPORT_NDIFF

当指定时，差异由`@w{`}difflib.Differ`@w{`}来计算，使用与流行的:file:@cite{ndiff.py`工具相同的算法。这是唯一一种标记行内和行间差异的方法。 例如，如果一行预期输出包含数字`@w{`}1`}，而实际输出包含字母`@w{`}l`@w{`}，那么就会插入一行，用圆点标记不匹配的列位置。
@end deffn

@geindex REPORT_ONLY_FIRST_FAILURE() (在 doctest 模块中)
@anchor{library/doctest doctest REPORT_ONLY_FIRST_FAILURE}@anchor{3350}
@deffn {数据} doctest.REPORT_ONLY_FIRST_FAILURE

当指定时，在每个 doctest 中显示第一个失败的用例，但隐藏所有其余用例的输出。 这将防止 doctest 报告由于先前的失败而中断的正确用例；但也可能隐藏独立于第一个失败的不正确用例。 当 @ref{3350,,REPORT_ONLY_FIRST_FAILURE} 被指定时，其余的用例仍然被运行，并且仍然计入报告的失败总数；只是输出被隐藏了。
@end deffn

@geindex FAIL_FAST() (在 doctest 模块中)
@anchor{library/doctest doctest FAIL_FAST}@anchor{934}
@deffn {数据} doctest.FAIL_FAST

当指定时，在第一个失败的用例后退出，不尝试运行其余的用例。因此，报告的失败次数最多为1。这个标志在调试时可能很有用，因为第一个失败后的用例甚至不会产生调试输出。

doctest命令行接受选项`@w{`}-f`@w{`}作为`@w{`}-o FAIL_FAST`@w{`}的简洁形式。


3.4 新版功能.

@end deffn

@geindex REPORTING_FLAGS() (在 doctest 模块中)
@anchor{library/doctest doctest REPORTING_FLAGS}@anchor{3351}
@deffn {数据} doctest.REPORTING_FLAGS

一个比特或操作将上述所有的报告标志组合在一起。
@end deffn

还有一种方法可以注册新的选项标志名称，不过这并不有用，除非你打算通过子类来扩展 @ref{66,,doctest} 内部。

@geindex register_optionflag() (在 doctest 模块中)
@anchor{library/doctest doctest register_optionflag}@anchor{3352}
@deffn {函数} doctest.register_optionflag (name)

用给定的名称创建一个新的选项标志，并返回新标志的整数值。 @ref{3352,,register_optionflag()} 可以在继承 @ref{3353,,OutputChecker} 或 @ref{3354,,DocTestRunner} 时使用，以创建子类支持的新选项。 @ref{3352,,register_optionflag()} 应始终使用以下方式调用:

@example
MY_FLAG = register_optionflag('MY_FLAG')
@end example
@end deffn

@geindex # (hash); in doctests
@geindex + (plus); in doctests
@geindex - (minus); in doctests

@node 指令,警告<2>,选项标记,它是如何工作的
@anchor{library/doctest directives}@anchor{3355}@anchor{library/doctest doctest-directives}@anchor{3343}
@subsubsection 指令


Doctest指令可以用来修改单个例子的 @ref{933,,option flags} 。 Doctest指令是在一个用例的源代码后面的特殊Python注释。

@example
@anchor{library/doctest grammar-token-directive}@anchor{3356}directive             ::= "#" "doctest:" directive_options
@anchor{library/doctest grammar-token-directive-options}@anchor{3357}directive_options     ::= directive_option ("," directive_option)\*
@anchor{library/doctest grammar-token-directive-option}@anchor{3358}directive_option      ::= on_or_off directive_option_name
@anchor{library/doctest grammar-token-on-or-off}@anchor{3359}on_or_off             ::= "+" \| "-"
@anchor{library/doctest grammar-token-directive-option-name}@anchor{335a}directive_option_name ::= "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...
@end example

@code{+} 或 @code{-} 与指令选项名称之间不允许有空格。 指令选项名称可以是上面解释的任何一个选项标志名称。

一个用例的 doctest 指令可以修改 doctest 对该用例的行为。 使用 @code{+} 来启用指定的行为，或者使用 @code{-} 来禁用它。

例如，这个测试将会通过:

@example
>>> print(list(range(20))) 
[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
10,  11, 12, 13, 14, 15, 16, 17, 18, 19]
@end example

如果没有这个指令，它就会失败，这是因为实际的输出在个位数的列表元素前没有两个空格，也因为实际的输出是在单行上。 这个测试也通过了，而且也需要一个指令来完成:

@example
>>> print(list(range(20))) 
[0, 1, ..., 18, 19]
@end example

在一个物理行上可以使用多个指令，用逗号分隔:

@example
>>> print(list(range(20))) 
[0,    1, ...,   18,    19]
@end example

如果在一个用例中使用了多个指令注释，那么它们将被合并:

@example
>>> print(list(range(20))) 
...                        
[0,    1, ...,   18,    19]
@end example

正如前面的例子所示，你可以在你的用例中添加只包含指令的行。 当一个用例太长，指令不能舒适地放在同一行时，这可能很有用:

@example
>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
... 
[0, ..., 4, 10, ..., 19, 30, ..., 39]
@end example

请注意，由于所有的选项都是默认禁用的，而指令只适用于它们出现的用例，所以启用选项 (通过指令中的 @code{+}) 通常是唯一有意义的选择。 然而，选项标志也可以被传递给运行测试的函数，建立不同的默认值。 在这种情况下，通过指令中的 @code{-} 来禁用一个选项可能是有用的。

@node 警告<2>,,指令,它是如何工作的
@anchor{library/doctest doctest-warnings}@anchor{335b}@anchor{library/doctest warnings}@anchor{335c}
@subsubsection 警告


@ref{66,,doctest} 是严格地要求在预期输出中完全匹配。 如果哪怕只有一个字符不匹配，测试就会失败。 这可能会让你吃惊几次，在你确切地了解到 Python 对输出的保证和不保证之前。 例如，当打印一个集合时，Python 不保证元素以任何特定的顺序被打印出来，所以像:

@example
>>> foo()
@{"Hermione", "Harry"@}
@end example

是不可靠的！一个变通方法是做:

@example
>>> foo() == @{"Hermione", "Harry"@}
True
@end example

来取代。另一个是使用

@example
>>> d = sorted(foo())
>>> d
['Harry', 'Hermione']
@end example

@cartouche
@quotation 注解 
在 Python 3.6 之前，当打印一个 dict 时，Python 并不保证键值对以任何特定的顺序被打印。
@end quotation
@end cartouche

还有其他的问题，但你会明白的。

另一个不好的做法是打印嵌入了对象地址的变量，如:

@example
>>> id(1.0) # certain to fail some of the time
7948648
>>> class C: pass
>>> C()   # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>
@end example

@ref{e9e,,ELLIPSIS} 指令为最后一个例子提供了一个不错的方法:

@example
>>> C() 
<__main__.C instance at 0x...>
@end example

浮点数在不同的平台上也会有小的输出变化，因为Python在浮点数的格式化上依赖于平台的C库，而C库在这个问题上的质量差异很大。:

@example
>>> 1./7  # risky
0.14285714285714285
>>> print(1./7) # safer
0.142857142857
>>> print(round(1./7, 6)) # much safer
0.142857
@end example

形式`@w{`}I/2.**J`@w{`}的数字在所有的平台上都是安全的，我经常设计一些测试的用例来产生该形式的数:

@example
>>> 3./4  # utterly safe
0.75
@end example

简单的分数也更容易让人理解，这也使得文件更加完善。

@node 基本API,Unittest API,它是如何工作的,doctest --- 测试交互性的Python示例
@anchor{library/doctest basic-api}@anchor{335d}@anchor{library/doctest doctest-basic-api}@anchor{3338}
@subsubsection 基本API


函数 @ref{e9d,,testmod()} 和 @ref{333b,,testfile()} 为 doctest 提供了一个简单的接口，应该足以满足大多数基本用途。关于这两个函数的不太正式的介绍，请参见 @ref{3336,,简单用法：检查Docstrings中的示例} 和 @ref{3339,,简单的用法：检查文本文件中的例子} 部分。

@geindex testfile() (在 doctest 模块中)
@anchor{library/doctest doctest testfile}@anchor{333b}
@deffn {函数} doctest.testfile (filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None)

除了*filename*，所有的参数都是可选的，而且应该以关键字的形式指定。

测试名为 @emph{filename} 的文件中的用例。 返回`@w{`}(failure_count, test_count)`@w{`}。

可选参数 @emph{module_relative} 指定了文件名的解释方式。


@itemize *

@item 
如果 @emph{module_relative} 是 @code{True} (默认)，那么 @emph{filename} 指定一个独立于操作系统的模块相对路径。 默认情况下，这个路径是相对于调用模块的目录的；但是如果指定了 @emph{package} 参数，那么它就是相对于该包的。 为了保证操作系统的独立性，@emph{filename} 应该使用字符来分隔路径段，并且不能是一个绝对路径 (即不能以 @code{/} 开始)。

@item 
如果 @emph{module_relative} 是 @code{False}，那么 @emph{filename} 指定了一个操作系统特定的路径。路径可以是绝对的，也可以是相对的；相对路径是相对于当前工作目录而言的。
@end itemize

可选参数 @emph{name} 给出了测试的名称；默认情况下，或者如果是`@w{`}None`@w{`}，那么使用`@w{`}os.path.basename(filename)`@w{`}。

可选参数 @emph{package} 是一个 Python 包或一个 Python 包的名字，其目录应被用作模块相关文件名的基础目录。 如果没有指定包，那么调用模块的目录将作为模块相关文件名的基础目录。如果 @emph{module_relative} 是`@w{`}False`@w{`}，那么指定 @emph{package} 是错误的。

可选参数 @emph{globs} 给出了一个在执行示例时用作全局变量的dict。 这个dict的一个新的浅层副本将为doctest创建，因此它的用例将从一个干净的地方开始。默认情况下，或者如果为`@w{`}None`@w{`}，使用一个新的空dict。

可选参数 @emph{extraglobs} 给出了一个合并到用于执行用例全局变量中的dict。 这就像 @ref{e96,,dict.update()} 一样：如果 @emph{globs} 和 @emph{extraglobs} 有一个共同的键，那么 @emph{extraglobs} 中的相关值会出现在合并的dict中。 默认情况下，或者为`@w{`}None`@w{`} ，则不使用额外的全局变量。这是一个高级功能，允许对 doctest 进行参数化。例如，可以为一个基类写一个测试，使用该类的通用名称，然后通过传递一个 @emph{extraglobs} dict，将通用名称映射到要测试的子类，从而重复用于测试任何数量的子类。

可选的参数 @emph{verbose} 如果为真值会打印很多东西，如果为假值则只打印失败信息；默认情况下，或者为 @code{None}，只有当 @code{'-v'} 在 @code{sys.argv} 中时才为真值。

可选参数 @emph{report} 为True时，在结尾处打印一个总结，否则在结尾处什么都不打印。 在verbose模式下，总结是详细的，否则总结是非常简短的（事实上，如果所有的测试都通过了，总结就是空的）。

可选参数 @emph{optionflags} （默认值为0）是选项标志的 @ref{16a5,,bitwise OR} 。参见章节 @ref{933,,选项标记} 。

可选参数 @emph{raise_on_error} 默认为False。 如果是True，在一个用例中第一次出现失败或意外的异常时，会触发一个异常。这允许对失败进行事后调试。默认行为是继续运行例子。

可选参数 @emph{parser} 指定一个 @ref{3344,,DocTestParser} （或子类），它应该被用来从文件中提取测试。它默认为一个普通的解析器（即`@w{`}DocTestParser()`@w{`}）。

可选参数 @emph{encoding} 指定了一个编码，应该用来将文件转换为unicode。
@end deffn

@geindex testmod() (在 doctest 模块中)
@anchor{library/doctest doctest testmod}@anchor{e9d}
@deffn {函数} doctest.testmod (m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)

所有的参数都是可选的，除了 @emph{m} 之外，都应该以关键字的形式指定。

测试从模块 @emph{m} （或模块 @ref{1,,__main__} ，如果 @emph{m} 没有被提供或为`@w{`}None`@w{`}）可达到的函数和类的文档串中的用例，从`@w{`}m.__doc__`@w{`}开始。

也测试从dict @code{m.__test__} 可达到的用例，如果它存在并且不是 @code{None} 。 @code{m.__test__} 将名字（字符串）映射到函数、类和字符串；函数和类的文档串被搜索到的用例；字符串被直接搜索到，就像它们是文档串一样。

只搜索附属于模块 @emph{m} 中的对象的文档串。

返回 @code{(failure_count, test_count)} 。

可选参数 @emph{name} 给出了模块的名称；默认情况下，或者如果为 @code{None} ，则为 @code{m.__name__} 。

可选参数 @emph{exclude_empty} 默认为假值。 如果为真值，没有找到任何 doctest 的对象将被排除在考虑范围之外。 默认情况下是向后兼容，所以仍然使用 @code{doctest.master.summarize()} 和 @ref{e9d,,testmod()} 的代码会继续得到没有测试的对象的输出。 较新的 @ref{335e,,DocTestFinder} 构造器的 @emph{exclude_empty} 参数默认为真值。

可选参数 @emph{extraglobs} 、 @emph{verbose} 、 @emph{report} 、 @emph{optionflags} 、 @emph{raise_on_error} 和 @emph{globs} 与上述函数 @ref{333b,,testfile()} 的参数相同，只是 @emph{globs} 默认为 @code{m.__dict__} 。
@end deffn

@geindex run_docstring_examples() (在 doctest 模块中)
@anchor{library/doctest doctest run_docstring_examples}@anchor{335f}
@deffn {函数} doctest.run_docstring_examples (f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0)

与对象 @emph{f} 相关的测试用例；例如， @emph{f} 可以是一个字符串、一个模块、一个函数或一个类对象。

dict 参数 @emph{globs} 的浅层拷贝被用于执行环境。

可选参数*name*在失败信息中使用，默认为 @code{"NoName"} 。

如果可选参数 @emph{verbose} 为真，即使没有失败也会产生输出。 默认情况下，只有在用例失败的情况下才会产生输出。

可选参数 @emph{compileflags} 给出了Python编译器在运行例子时应该使用的标志集。默认情况下，或者如果为 @code{None} ，标志是根据 @emph{globs} 中发现的未来特征集推导出来的。

可选参数 @emph{optionflags} 的作用与上述 @ref{333b,,testfile()} 函数中的相同。
@end deffn

@node Unittest API,高级 API,基本API,doctest --- 测试交互性的Python示例
@anchor{library/doctest doctest-unittest-api}@anchor{3360}@anchor{library/doctest unittest-api}@anchor{3361}
@subsubsection Unittest API


@ref{66,,doctest} 提供了两个函数，可以用来从模块和包含测试的文本文件中创建 @ref{124,,unittest} 测试套件。 要与 @ref{124,,unittest} 测试发现集成，请在你的测试模块中包含一个 @code{load_tests()} 函数：:

@example
import unittest
import doctest
import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests
@end example

有两个主要函数用于从文本文件和带doctest的模块中创建 @ref{7cb,,unittest.TestSuite} 实例。

@geindex DocFileSuite() (在 doctest 模块中)
@anchor{library/doctest doctest DocFileSuite}@anchor{3362}
@deffn {函数} doctest.DocFileSuite (*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None)

将一个或多个文本文件中的doctest测试转换为一个 @ref{7cb,,unittest.TestSuite} 。

返回的 @ref{7cb,,unittest.TestSuite} 将由 unittest 框架运行，并运行每个文件中的交互式示例。如果任何文件中的用例失败了，那么合成的单元测试就会失败，并触发一个 @code{failureException} 异常，显示包含该测试的文件名和一个（有时是近似的）行号。

传递一个或多个要检查的文本文件的路径（作为字符串）。

选项可以作为关键字参数提供：

可选参数 @emph{module_relative} 指定了 @emph{paths} 中的文件名应该如何解释。


@itemize *

@item 
如果*module_relative*是 @code{True} （默认值），那么 @emph{paths} 中的每个文件名都指定了一个独立于操作系统的模块相对路径。 默认情况下，这个路径是相对于调用模块的目录的；但是如果指定了 @emph{package} 参数，那么它就是相对于该包的。 为了保证操作系统的独立性，每个文件名都应该使用字符来分隔路径段，并且不能是绝对路径（即不能以 @code{/} 开始）。

@item 
如果 @emph{module_relative} 是 @code{False} ，那么 @emph{paths} 中的每个文件名都指定了一个操作系统特定的路径。 路径可以是绝对的，也可以是相对的；相对路径是关于当前工作目录的解析。
@end itemize

可选参数 @emph{package} 是一个Python包或一个Python包的名字，其目录应该被用作 @emph{paths} 中模块相关文件名的基本目录。 如果没有指定包，那么调用模块的目录将作为模块相关文件名的基础目录。 如果 @emph{module_relative} 是 @code{False} ，那么指定 @emph{package} 是错误的。

可选的参数 @emph{setUp} 为测试套件指定了一个设置函数。在运行每个文件中的测试之前，它被调用。 @emph{setUp} 函数将被传递给一个 @ref{3363,,DocTest} 对象。 setUp函数可以通过测试的 @emph{globs} 属性访问测试的全局变量。

可选的参数 @emph{tearDown} 指定了测试套件的卸载函数。 在运行每个文件中的测试后，它会被调用。 @emph{tearDown} 函数将被传递一个 @ref{3363,,DocTest} 对象。 setUp函数可以通过测试的 @emph{globs} 属性访问测试的全局变量。

可选参数 @emph{globs} 是一个包含测试的初始全局变量的字典。 这个字典的一个新副本为每个测试创建。 默认情况下， @emph{globs} 是一个新的空字典。

可选参数 @emph{optionflags} 为测试指定默认的doctest选项，通过将各个选项的标志连接在一起创建。 参见章节 @ref{933,,选项标记} 。参见下面的函数 @ref{3364,,set_unittest_reportflags()} ，以了解设置报告选项的更好方法。

可选参数 @emph{parser} 指定一个 @ref{3344,,DocTestParser} （或子类），它应该被用来从文件中提取测试。它默认为一个普通的解析器（即`@w{`}DocTestParser()`@w{`}）。

可选参数 @emph{encoding} 指定了一个编码，应该用来将文件转换为unicode。

该全局 @code{__file__} 被添加到提供给用 @ref{3362,,DocFileSuite()} 从文本文件加载的doctest的全局变量中。
@end deffn

@geindex DocTestSuite() (在 doctest 模块中)
@anchor{library/doctest doctest DocTestSuite}@anchor{7ca}
@deffn {函数} doctest.DocTestSuite (module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, checker=None)

将一个模块的doctest测试转换为 @ref{7cb,,unittest.TestSuite} 。

返回的 @ref{7cb,,unittest.TestSuite} 将由 unittest 框架运行，并运行模块中的每个 doctest。 如果任何一个测试失败，那么合成的单元测试就会失败，并触发一个 @code{failureException} 异常，显示包含该测试的文件名和一个（有时是近似的）行号。

可选参数 @emph{module} 提供了要测试的模块。 它可以是一个模块对象或一个（可能是带点的）模块名称。 如果没有指定，则使用调用此函数的模块。

可选参数 @emph{globs} 是一个包含测试的初始全局变量的字典。 这个字典的一个新副本为每个测试创建。 默认情况下， @emph{globs} 是一个新的空字典。

可选参数 @emph{extraglobs} 指定了一组额外的全局变量，这些变量被合并到 @emph{globs} 中。 默认情况下，不使用额外的全局变量。

可选参数 @emph{test_finder} 是 @ref{335e,,DocTestFinder} 对象（或一个可替换的对象），用于从模块中提取测试。

可选参数 @emph{setUp} 、 @emph{tearDown} 和 @emph{optionflags} 与上述函数 @ref{3362,,DocFileSuite()} 相同。

这个函数使用与 @ref{e9d,,testmod()} 相同的搜索技术。


在 3.5 版更改: 如果 @emph{module} 不包含任何文件串，则 @ref{7ca,,DocTestSuite()} 返回一个空的 @ref{7cb,,unittest.TestSuite}，而不是触发 @ref{16d,,ValueError}。

@end deffn

@ref{7ca,,DocTestSuite()} 从 @code{doctest.DocTestCase} 实例中创建一个 @ref{7cb,,unittest.TestSuite} ，而 @code{DocTestCase} 是 @ref{9ee,,unittest.TestCase} 的子类。 @code{DocTestCase} 在这里没有记录（这是一个内部细节），但研究其代码可以回答关于 @ref{124,,unittest} 集成的实际细节问题。

同样， @ref{3362,,DocFileSuite()} 从 @code{doctest.DocFileCase} 实例中创建一个 @ref{7cb,,unittest.TestSuite} ，并且 @code{DocFileCase} 是 @code{DocTestCase} 的一个子类。

所以这两种创建 @ref{7cb,,unittest.TestSuite} 的方式都是运行 @code{DocTestCase} 的实例。这一点很重要，因为有一个微妙的原因：当你自己运行 @ref{66,,doctest} 函数时，你可以直接控制使用中的 @ref{66,,doctest} 选项，通过传递选项标志给 @ref{66,,doctest} 函数。 然而，如果你正在编写一个 @ref{124,,unittest} 框架， @ref{124,,unittest} 最终会控制测试的运行时间和方式。 框架作者通常希望控制 @ref{66,,doctest} 的报告选项（也许，例如，由命令行选项指定），但没有办法通过 @ref{124,,unittest} 向 @ref{66,,doctest} 测试运行者传递选项。

出于这个原因， @ref{66,,doctest} 也支持一个概念，即 @ref{66,,doctest} 报告特定于 @ref{124,,unittest} 支持的标志，通过这个函数：

@geindex set_unittest_reportflags() (在 doctest 模块中)
@anchor{library/doctest doctest set_unittest_reportflags}@anchor{3364}
@deffn {函数} doctest.set_unittest_reportflags (flags)

设置要使用的 @ref{66,,doctest} 报告标志。

参数 @emph{flags} 是选项标志的 @ref{16a5,,bitwise OR} 。 参见章节 @ref{933,,选项标记} 。 只有 "报告标志" 可以被使用。

这是一个模块的全局设置，并影响所有未来由模块 @ref{124,,unittest} 运行的测试： @code{DocTestCase} 的 @code{runTest()} 方法会查看 @code{DocTestCase} 实例构建时为测试用例指定的选项标志。 如果没有指定报告标志（这是典型的和预期的情况）， @ref{66,,doctest} 的 @ref{124,,unittest} 报告标志被 @ref{16a5,,bitwise ORed} 到选项标志中，这样增加的选项标志被传递给 @ref{3354,,DocTestRunner} 实例来运行doctest。 如果在构建 @code{DocTestCase} 实例时指定了任何报告标志，那么 @ref{66,,doctest} 的 @ref{124,,unittest} 报告标志会被忽略。

@ref{124,,unittest} 报告标志的值在调用该函数之前是有效的，由该函数返回。
@end deffn

@node 高级 API,调试,Unittest API,doctest --- 测试交互性的Python示例
@anchor{library/doctest advanced-api}@anchor{3365}@anchor{library/doctest doctest-advanced-api}@anchor{3366}
@subsubsection 高级 API


基本 API 是一个简单的封装，旨在使 doctest 易于使用。它相当灵活，应该能满足大多数用户的需求；但是，如果你需要对测试进行更精细的控制，或者希望扩展 doctest 的功能，那么你应该使用高级 API 。

高级API围绕着两个容器类，用于存储从 doctest 案例中提取的交互式用例:


@itemize *

@item 
@ref{3367,,Example}: 一个单一的 Python @ref{1d37,,statement} ，与它的预期输出配对。

@item 
@ref{3363,,DocTest}: 一组 @ref{3367,,Example}s 的集合，通常从一个文档字符串或文本文件中提取。
@end itemize

定义了额外的处理类来寻找、解析和运行，并检查 doctest 的用例。


@itemize *

@item 
@ref{335e,,DocTestFinder} : 查找给定模块中的所有文档串，并使用 @ref{3344,,DocTestParser} 从每个包含交互式用例的文档串中创建一个 @ref{3363,,DocTest} 。

@item 
@ref{3344,,DocTestParser} : 从一个字符串（如一个对象的文档串）创建一个 @ref{3363,,DocTest} 对象。

@item 
@ref{3354,,DocTestRunner} : 执行 @ref{3363,,DocTest} 中的用例，并使用 @ref{3353,,OutputChecker} 来验证其输出。

@item 
@ref{3353,,OutputChecker} : 将一个测试用例的实际输出与预期输出进行比较，并决定它们是否匹配。
@end itemize

这些处理类之间的关系总结在下图中:

@example
                            list of:
+------+                   +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+    |        ^     +---------+     |       ^    (printed)
            |        |     | Example |     |       |
            v        |     |   ...   |     v       |
           DocTestParser   | Example |   OutputChecker
                           +---------+
@end example

@menu
* DocTest 对象:: 
* Example 对象:: 
* DocTestFinder 对象:: 
* DocTestParser 对象:: 
* DocTestRunner 对象:: 
* OutputChecker 对象:: 

@end menu

@node DocTest 对象,Example 对象,,高级 API
@anchor{library/doctest doctest-doctest}@anchor{3368}@anchor{library/doctest doctest-objects}@anchor{3369}
@subsubsection DocTest 对象


@geindex DocTest (doctest 中的类)
@anchor{library/doctest doctest DocTest}@anchor{3363}
@deffn {类} doctest.DocTest (examples, globs, name, filename, lineno, docstring)

应该在单一命名空间中运行的doctest用例的集合。构造函数参数被用来初始化相同名称的属性。

@ref{3363,,DocTest} 定义了以下属性。 它们由构造函数初始化，不应该被直接修改。

@geindex examples (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest examples}@anchor{336a}
@deffn {属性} examples

一个 @ref{3367,,Example} 对象的列表，它编码了应该由该测试运行的单个交互式 Python 用例。
@end deffn

@geindex globs (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest globs}@anchor{336b}
@deffn {属性} globs

例子应该运行的命名空间（又称 globals ）。这是一个将名字映射到数值的字典。例子对名字空间的任何改变（比如绑定新的变量）将在测试运行后反映在 @ref{336b,,globs} 中。
@end deffn

@geindex name (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest name}@anchor{336c}
@deffn {属性} name

识别 @ref{3363,,DocTest} 的字符串名称。 通常情况下，这是从测试中提取的对象或文件的名称。
@end deffn

@geindex filename (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest filename}@anchor{336d}
@deffn {属性} filename

这个 @ref{3363,,DocTest} 被提取的文件名；或者为`@w{`}None`@w{`}，如果文件名未知，或者 @ref{3363,,DocTest} 没有从文件中提取。
@end deffn

@geindex lineno (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest lineno}@anchor{336e}
@deffn {属性} lineno

@ref{336d,,filename} 中的行号，这个 @ref{3363,,DocTest} 开始的地方，或者行号不可用时为`@w{`}None`@w{`}。 这个行号相对于文件的开头来说是零的。
@end deffn

@geindex docstring (doctest.DocTest 属性)
@anchor{library/doctest doctest DocTest docstring}@anchor{336f}
@deffn {属性} docstring

从测试中提取的字符串，或者如果字符串不可用，或者为 @code{None} ，如果测试没有从字符串中提取。
@end deffn
@end deffn

@node Example 对象,DocTestFinder 对象,DocTest 对象,高级 API
@anchor{library/doctest doctest-example}@anchor{3370}@anchor{library/doctest example-objects}@anchor{3371}
@subsubsection Example 对象


@geindex Example (doctest 中的类)
@anchor{library/doctest doctest Example}@anchor{3367}
@deffn {类} doctest.Example (source, want, exc_msg=None, lineno=0, indent=0, options=None)

单个交互式用例，由一个 Python 语句及其预期输出组成。 构造函数参数被用来初始化相同名称的属性。

@ref{3367,,Example} 定义了以下属性。 它们由构造函数初始化，不应该被直接修改。

@geindex source (doctest.Example 属性)
@anchor{library/doctest doctest Example source}@anchor{3372}
@deffn {属性} source

一个包含该用例源码的字符串。 源码由一个 Python 语句组成，并且总是以换行结束；构造函数在必要时添加一个换行。
@end deffn

@geindex want (doctest.Example 属性)
@anchor{library/doctest doctest Example want}@anchor{3373}
@deffn {属性} want

运行这个用例的源码的预期输出（可以是 stdout ，也可以是异常情况下的回溯）。 @ref{3373,,want} 以一个换行符结束，除非没有预期的输出，在这种情况下它是一个空字符串。 构造函数在必要时添加一个换行。
@end deffn

@geindex exc_msg (doctest.Example 属性)
@anchor{library/doctest doctest Example exc_msg}@anchor{3374}
@deffn {属性} exc_msg

用例产生的异常信息，如果这个例子被期望产生一个异常；或者为 @code{None} ，如果它不被期望产生一个异常。 这个异常信息与 @ref{3375,,traceback.format_exception_only()} 的返回值进行比较。 @ref{3374,,exc_msg} 以换行结束，除非是 @code{None} 。
@end deffn

@geindex lineno (doctest.Example 属性)
@anchor{library/doctest doctest Example lineno}@anchor{3376}
@deffn {属性} lineno

包含本例的字符串中的行号，即本例的开始。 这个行号相对于包含字符串的开头来说是以零开始的。
@end deffn

@geindex indent (doctest.Example 属性)
@anchor{library/doctest doctest Example indent}@anchor{3377}
@deffn {属性} indent

用例在包含字符串中的缩进，即在用例的第一个提示前有多少个空格字符。
@end deffn

@geindex options (doctest.Example 属性)
@anchor{library/doctest doctest Example options}@anchor{3378}
@deffn {属性} options

一个从选项标志到 @code{True} 或 @code{False} 的字典映射，用于覆盖这个例子的默认选项。 任何不包含在这个字典中的选项标志都被保留为默认值（由 @ref{3354,,DocTestRunner} 的 @code{optionflags} 指定）。默认情况下，没有选项被设置。
@end deffn
@end deffn

@node DocTestFinder 对象,DocTestParser 对象,Example 对象,高级 API
@anchor{library/doctest doctest-doctestfinder}@anchor{3379}@anchor{library/doctest doctestfinder-objects}@anchor{337a}
@subsubsection DocTestFinder 对象


@geindex DocTestFinder (doctest 中的类)
@anchor{library/doctest doctest DocTestFinder}@anchor{335e}
@deffn {类} doctest.DocTestFinder (verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)

一个处理类，用于从一个给定的对象的 docstring 和其包含的对象的 docstring 中提取与之相关的 @ref{3363,,DocTest} 。 @ref{3363,,DocTest} 可以从模块、类、函数、方法、静态方法、类方法和属性中提取。

可选的参数 @emph{verbose} 可以用来显示查找器搜索到的对象。 它的默认值是 @code{False} （无输出）。

可选的参数 @emph{parser} 指定了 @ref{3344,,DocTestParser} 对象（或一个可替换的对象），用于从文档串中提取 doctest 。

如果可选的参数 @emph{recurse} 是 False ，那么 @ref{337b,,DocTestFinder.find()} 将只检查给定的对象，而不是任何包含的对象。

如果可选参数 @emph{exclude_empty} 为 False ，那么 @ref{337b,,DocTestFinder.find()} 将包括对文档字符串为空的对象的测试。

@ref{335e,,DocTestFinder} 定义了以下方法：

@geindex find() (doctest.DocTestFinder 方法)
@anchor{library/doctest doctest DocTestFinder find}@anchor{337b}
@deffn {方法} find (obj[, name][, module][, globs][, extraglobs])

返回 @ref{3363,,DocTest} 的列表，该列表由 @emph{obj} 的文档串或其包含的任何对象的文档串定义。

可选参数 @emph{name} 指定了对象的名称；这个名称将被用来为返回的 @ref{3363,,DocTest} 构建名称。 如果没有指定*name*，则使用 @code{obj.__name__} 。

可选参数 @emph{module} 是包含给定对象的模块。如果没有指定模块或者是 @code{None} ，那么测试查找器将试图自动确定正确的模块。 该对象被使用的模块：


@itemize *

@item 
作为一个默认的命名空间，如果没有指定 @emph{globs} 。

@item 
为了防止 DocTestFinder 从其他模块导入的对象中提取 DocTest 。 (包含有除 @emph{module} 以外的模块的对象会被忽略)。

@item 
找到包含该对象的文件名。

@item 
找到该对象在其文件中的行号。
@end itemize

如果 @emph{module} 是 @code{False} ，将不会试图找到这个模块。 这是不明确的，主要用于测试 doctest 本身：如果 @emph{module} 是 @code{False} ，或者是 @code{None} 但不能自动找到，那么所有对象都被认为属于（不存在的）模块，所以所有包含的对象将（递归地）被搜索到 doctest 。

每个 @ref{3363,,DocTest} 的 globals 是由 @emph{globs} 和 @emph{extraglobs} 组合而成的（ @emph{extraglobs} 的绑定覆盖 @emph{globs} 的绑定）。 为每个 @ref{3363,,DocTest} 创建一个新的 globals 字典的浅层拷贝。如果没有指定 @emph{globs} ，那么它默认为模块的 @emph{__dict__} ，如果指定了或者为 @code{@{@}} ，则除外。 如果没有指定 @emph{extraglobs} ，那么它默认为 @code{@{@}} 。
@end deffn
@end deffn

@node DocTestParser 对象,DocTestRunner 对象,DocTestFinder 对象,高级 API
@anchor{library/doctest doctest-doctestparser}@anchor{337c}@anchor{library/doctest doctestparser-objects}@anchor{337d}
@subsubsection DocTestParser 对象


@geindex DocTestParser (doctest 中的类)
@anchor{library/doctest doctest DocTestParser}@anchor{3344}
@deffn {类} doctest.DocTestParser

一个处理类，用于从一个字符串中提取交互式的用例，并使用它们来创建一个 @ref{3363,,DocTest} 对象。

@ref{3344,,DocTestParser} 定义了以下方法：

@geindex get_doctest() (doctest.DocTestParser 方法)
@anchor{library/doctest doctest DocTestParser get_doctest}@anchor{337e}
@deffn {方法} get_doctest (string, globs, name, filename, lineno)

从给定的字符串中提取所有的测试用例，并将它们收集到一个 @ref{3363,,DocTest} 对象中。

@emph{globs} 、 @emph{name} 、 @emph{filename} 和 @emph{lineno} 是新的 @ref{3363,,DocTest} 对象的属性。 更多信息请参见 @ref{3363,,DocTest} 的文档。
@end deffn

@geindex get_examples() (doctest.DocTestParser 方法)
@anchor{library/doctest doctest DocTestParser get_examples}@anchor{337f}
@deffn {方法} get_examples (string, name='<string>')

ä»ç»å®çå­ç¬¦ä¸²ä¸­æåææçæµè¯ç¨ä¾ï¼å¹¶ä»¥ @ref{3367,,Example} å¯¹è±¡åè¡¨çå½¢å¼è¿åã è¡æ°ä»¥ 0 ä¸ºåºç¡ã å¯éåæ° @emph{name} æ¯è¯å«è¿ä¸ªå­ç¬¦ä¸²çåç§°ï¼åªç¨äºéè¯¯ä¿¡æ¯ã
@end deffn

@geindex parse() (doctest.DocTestParser 方法)
@anchor{library/doctest doctest DocTestParser parse}@anchor{3380}
@deffn {方法} parse (string, name='<string>')

å°ç»å®çå­ç¬¦ä¸²åæç¨ä¾åä¸­é´ææ¬ï¼å¹¶ä»¥ @ref{3367,,Example} åå­ç¬¦ä¸²äº¤æ¿çåè¡¨å½¢å¼è¿åã @ref{3367,,Example} çè¡å·ä»¥ 0 ä¸ºåºç¡ã å¯éåæ° @emph{name} æ¯è¯å«è¿ä¸ªå­ç¬¦ä¸²çåç§°ï¼åªç¨äºéè¯¯ä¿¡æ¯ã
@end deffn
@end deffn

@node DocTestRunner 对象,OutputChecker 对象,DocTestParser 对象,高级 API
@anchor{library/doctest doctest-doctestrunner}@anchor{3381}@anchor{library/doctest doctestrunner-objects}@anchor{3382}
@subsubsection DocTestRunner 对象


@geindex DocTestRunner (doctest 中的类)
@anchor{library/doctest doctest DocTestRunner}@anchor{3354}
@deffn {类} doctest.DocTestRunner (checker=None, verbose=None, optionflags=0)

ä¸ä¸ªå¤çç±»ï¼ç¨äºæ§è¡åéªè¯ @ref{3363,,DocTest} ä¸­çäº¤äºå¼ç¨ä¾ã

é¢æè¾åºåå®é
è¾åºä¹é´çæ¯è¾æ¯ç±ä¸ä¸ª @ref{3353,,OutputChecker} å®æçã è¿ç§æ¯è¾å¯ä»¥ç¨ä¸äºéé¡¹æ å¿æ¥å®å¶ï¼æ´å¤ä¿¡æ¯è¯·ç @ref{933,,选项标记} é¨åã å¦æéé¡¹æ å¿ä¸å¤ï¼é£ä¹ä¹å¯ä»¥éè¿åæé å½æ°ä¼ é @ref{3353,,OutputChecker} çå­ç±»æ¥å®å¶æ¯è¾ã

æµè¯è¿è¡å¨çæ¾ç¤ºè¾åºå¯ä»¥éè¿ä¸¤ç§æ¹å¼æ§å¶ãé¦å
ï¼ä¸ä¸ªè¾åºå½æ°å¯ä»¥è¢«ä¼ éç» @code{TestRunner.run()} ï¼è¿ä¸ªå½æ°å°è¢«è°ç¨ï¼å¹¶æ¾ç¤ºåºåºè¯¥æ¾ç¤ºçå­ç¬¦ä¸²ã å®çé»è®¤å¼æ¯ @code{sys.stdout.write} ã å¦æåªæè·è¾åºæ¯ä¸å¤çï¼é£ä¹ä¹å¯ä»¥éè¿å­ç±»å DocTestRunner ï¼å¹¶éå @ref{3383,,report_start()} , @ref{3384,,report_success()} ,  @ref{3385,,report_unexpected_exception()} , å @ref{3386,,report_failure()} æ¹æ³æ¥å®å¶æ¾ç¤ºè¾åºã

å¯éçå
³é®å­åæ° @emph{checker} æå®äº @ref{3353,,OutputChecker} å¯¹è±¡ï¼ææ¿æ¢ï¼ï¼å®åºè¯¥è¢«ç¨æ¥æ¯è¾é¢æè¾åºå doctest ç¨ä¾çå®é
è¾åºã

å¯éçå
³é®å­åæ° @emph{verbose} æ§å¶ @ref{3354,,DocTestRunner} çè¯¦ç»ç¨åº¦ã å¦æ @emph{verbose} æ¯ @code{True} ï¼é£ä¹æ¯ä¸ªç¨ä¾çä¿¡æ¯é½ä¼è¢«æå°åºæ¥ï¼å½å®æ­£å¨è¿è¡æ¶ã å¦æ @emph{verbose*æ¯ `@w{`}False`@w{`} ï¼ååªæå°å¤±è´¥çä¿¡æ¯ã å¦æ *verbose} æ²¡ææå®ï¼æè
ä¸º @code{None} ï¼å¦æå½ä½¿ç¨äºå½ä»¤è¡å¼å
³ @code{-v} ï¼åä½¿ç¨verboseè¾åºã

å¯éçå
³é®å­åæ° @emph{optionflags} å¯ä»¥ç¨æ¥æ§å¶æµè¯è¿è¡å¨å¦ä½æ¯è¾é¢æè¾åºåå®é
è¾åºï¼ä»¥åå¦ä½æ¾ç¤ºå¤±è´¥ãæ´å¤ä¿¡æ¯ï¼è¯·åè§ç« è @ref{933,,选项标记} ã

@ref{3344,,DocTestParser} 定义了以下方法：

@geindex report_start() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner report_start}@anchor{3383}
@deffn {方法} report_start (out, test, example)

报告测试运行器即将处理给定的用例。提供这个方法是为了让 @ref{3354,,DocTestRunner} 的子类能够定制他们的输出；它不应该被直接调用。

@emph{example} 是即将被处理的用。 @emph{test} 是 @emph{包含用例} 的测试。  @emph{out} 是传递给 @ref{3387,,DocTestRunner.run()} 的输出函数。
@end deffn

@geindex report_success() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner report_success}@anchor{3384}
@deffn {方法} report_success (out, test, example, got)

报告给定的例子运行成功。 提供这个方法是为了让 @ref{3354,,DocTestRunner} 的子类能够定制他们的输出；它不应该被直接调用。

@emph{example} 是即将被处理的用例。 @emph{got} 是这个例子的实际输出。 @emph{test} 是包含 @emph{example} 的测试。 @emph{out} 是传递给 @ref{3387,,DocTestRunner.run()} 的输出函数。
@end deffn

@geindex report_failure() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner report_failure}@anchor{3386}
@deffn {方法} report_failure (out, test, example, got)

报告给定的用例运行失败。 提供这个方法是为了让 @ref{3354,,DocTestRunner} 的子类能够定制他们的输出；它不应该被直接调用。

@emph{example} 是即将被处理的用例。 @emph{got} 是这个例子的实际输出。 @emph{test} 是包含 @emph{example} 的测试。 @emph{out} 是传递给 @ref{3387,,DocTestRunner.run()} 的输出函数。
@end deffn

@geindex report_unexpected_exception() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner report_unexpected_exception}@anchor{3385}
@deffn {方法} report_unexpected_exception (out, test, example, exc_info)

报告给定的用例触发了一个异常。 提供这个方法是为了让 @ref{3354,,DocTestRunner} 的子类能够定制他们的输出；它不应该被直接调用。

@emph{example} 是将要被处理的用例。 @emph{exc_info} 是一个元组，包含关于异常的信息（如由 @ref{d2f,,sys.exc_info()} 返回）。 @emph{test} 是包含 @emph{example} 的测试。 @emph{out} 是传递给 @ref{3387,,DocTestRunner.run()} 的输出函数。
@end deffn

@geindex run() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner run}@anchor{3387}
@deffn {方法} run (test, compileflags=None, out=None, clear_globs=True)

在 @emph{test} （一个 @ref{3363,,DocTest} 对象）中运行这些用例，并使用写入函数 @emph{out} 显示结果。

这些用例都是在命名空间 @code{test.globs} 中运行的。 如果 @emph{clear_globs} 为 True （默认），那么这个命名空间将在测试运行后被清除，以帮助进行垃圾回收。如果你想在测试完成后检查命名空间，那么使用 @emph{clear_globs=False} 。

@emph{compileflags} 给出了 Python 编译器在运行例子时应该使用的标志集。如果没有指定，那么它将默认为适用于 @emph{globs} 的 future-import 标志集。

每个用例的输出都使用 @ref{3354,,DocTestRunner} 的输出检查器进行检查，结果由 @code{DocTestRunner.report_*()} 方法进行格式化。
@end deffn

@geindex summarize() (doctest.DocTestRunner 方法)
@anchor{library/doctest doctest DocTestRunner summarize}@anchor{3388}
@deffn {方法} summarize (verbose=None)

打印这个 DocTestRunner 运行过的所有测试用例的摘要，并返回一个 @ref{b84,,named tuple} @code{TestResults(failed, attempted)} 。

可选的 @emph{verbose} 参数控制摘要的详细程度。 如果没有指定 verbose ，那么将使用 @ref{3354,,DocTestRunner} 的 verbose 。
@end deffn
@end deffn

@node OutputChecker 对象,,DocTestRunner 对象,高级 API
@anchor{library/doctest doctest-outputchecker}@anchor{3389}@anchor{library/doctest outputchecker-objects}@anchor{338a}
@subsubsection OutputChecker 对象


@geindex OutputChecker (doctest 中的类)
@anchor{library/doctest doctest OutputChecker}@anchor{3353}
@deffn {类} doctest.OutputChecker

一个用于检查测试用例的实际输出是否与预期输出相匹配的类。 @ref{3353,,OutputChecker} 定义了两个方法： @ref{338b,,check_output()} ，比较给定的一对输出，如果它们匹配则返回 @code{True} ； @ref{338c,,output_difference()} ，返回一个描述两个输出之间差异的字符串。

@ref{3353,,OutputChecker} 定义了以下方法：

@geindex check_output() (doctest.OutputChecker 方法)
@anchor{library/doctest doctest OutputChecker check_output}@anchor{338b}
@deffn {方法} check_output (want, got, optionflags)

如果一个用例的实际输出（ @emph{got} ）与预期输出（ @emph{want} ）匹配，则返回 @code{True} 。 如果这些字符串是相同的，总是被认为是匹配的；但是根据测试运行器使用的选项标志，也可能有几种非精确的匹配类型。 参见章节 @ref{933,,选项标记} 了解更多关于选项标志的信息。
@end deffn

@geindex output_difference() (doctest.OutputChecker 方法)
@anchor{library/doctest doctest OutputChecker output_difference}@anchor{338c}
@deffn {方法} output_difference (example, got, optionflags)

返回一个字符串，描述给定用例（ @emph{example} ）的预期输出和实际输出（ @emph{got} ）之间的差异。  @emph{optionflags} 是用于比较 @emph{want} 和 @emph{got} 的选项标志集。
@end deffn
@end deffn

@node 调试,肥皂盒,高级 API,doctest --- 测试交互性的Python示例
@anchor{library/doctest debugging}@anchor{338d}@anchor{library/doctest doctest-debugging}@anchor{338e}
@subsubsection 调试


Doctest 提供了几种调试 doctest 用例的机制：


@itemize *

@item 
有几个函数将测试转换为可执行的 Python 程序，这些程序可以在 Python 调试器， @ref{c9,,pdb} 下运行。

@item 
@ref{338f,,DebugRunner} 类是 @ref{3354,,DocTestRunner} 的一个子类，它为第一个失败的用例触发一个异常，包含关于这个用例的信息。这些信息可以用来对这个用例进行事后调试。

@item 
由 @ref{7ca,,DocTestSuite()} 生成的 @ref{124,,unittest} 用例支持由 @ref{9ee,,unittest.TestCase} 定义的 @ref{3390,,debug()} 方法，。

@item 
你可以在 doctest 的用例中加入对 @ref{4d1,,pdb.set_trace()} 的调用，当这一行被执行时，你会进入 Python 调试器。 然后你可以检查变量的当前值，等等。 例如，假设 @code{a.py} 只包含这个模块 docstring

@example
"""
>>> def f(x):
...     g(x*2)
>>> def g(x):
...     print(x+3)
...     import pdb; pdb.set_trace()
>>> f(3)
9
"""
@end example

那么一个交互式Python会话可能是这样的:

@example
>>> import a, doctest
>>> doctest.testmod(a)
--Return--
> <doctest a[1]>(3)g()->None
-> import pdb; pdb.set_trace()
(Pdb) list
  1     def g(x):
  2         print(x+3)
  3  ->     import pdb; pdb.set_trace()
[EOF]
(Pdb) p x
6
(Pdb) step
--Return--
> <doctest a[0]>(2)f()->None
-> g(x*2)
(Pdb) list
  1     def f(x):
  2  ->     g(x*2)
[EOF]
(Pdb) p x
3
(Pdb) step
--Return--
> <doctest a[2]>(1)?()->None
-> f(3)
(Pdb) cont
(0, 3)
>>>
@end example
@end itemize

将测试转换为 Python 代码的函数，并可能在调试器下运行合成的代码:

@geindex script_from_examples() (在 doctest 模块中)
@anchor{library/doctest doctest script_from_examples}@anchor{3391}
@deffn {函数} doctest.script_from_examples (s)

将带有用例的文本转换为脚本。

参数 @emph{s} 是一个包含测试用例的字符串。 该字符串被转换为 Python 脚本，其中 @emph{s} 中的 doctest 用例被转换为常规代码，其他的都被转换为 Python 注释。 生成的脚本将以字符串的形式返回。例如，

@example
import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))
@end example

显示:

@example
# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3
@end example

这个函数在内部被其他函数使用（见下文），但当你想把一个交互式 Python 会话转化为 Python 脚本时，也会很有用。
@end deffn

@geindex testsource() (在 doctest 模块中)
@anchor{library/doctest doctest testsource}@anchor{3392}
@deffn {函数} doctest.testsource (module, name)

将一个对象的 doctest 转换为一个脚本。

参数 @emph{module} 是一个模块对象，或者一个模块带点的名称，包含对其 doctest 感兴趣的对象。 参数 @emph{name} 是具有感兴趣的测试的对象的名称（在模块中）。 结果是一个字符串，包含该对象的文本串转换为 Python 脚本，如上面 @ref{3391,,script_from_examples()} 所述。 例如，如果模块 @code{a.py} 包含一个顶级函数 @code{f()} ，那么

@example
import a, doctest
print(doctest.testsource(a, "a.f"))
@end example

打印函数 @code{f()} 的文档串的脚本版本，将测试转换为代码，其余部分放在注释中。
@end deffn

@geindex debug() (在 doctest 模块中)
@anchor{library/doctest doctest debug}@anchor{3390}
@deffn {函数} doctest.debug (module, name, pm=False)

对一个对象的 doctest 进行调试。

@emph{module} 和 @emph{name} 参数与上面函数 @ref{3392,,testsource()} 的参数相同。 被命名对象的文本串的合成 Python 脚本被写入一个临时文件，然后该文件在 Python 调试器 @ref{c9,,pdb} 的控制下运行。

@code{module.__dict__} 的一个浅层拷贝被用于本地和全局的执行环境。

可选参数 @emph{pm} 控制是否使用事后调试。 如果 @emph{pm} 为 True ，则直接运行脚本文件，只有当脚本通过引发一个未处理的异常而终止时，调试器才会介入。如果是这样，就会通过 @ref{e12,,pdb.post_mortem()} 调用事后调试，并传递未处理异常的跟踪对象。如果没有指定 @emph{pm} ，或者是 False ，脚本将从一开始就在调试器下运行，通过传递一个适当的 @ref{d14,,exec()} 调用给 @ref{3393,,pdb.run()} 。
@end deffn

@geindex debug_src() (在 doctest 模块中)
@anchor{library/doctest doctest debug_src}@anchor{3394}
@deffn {函数} doctest.debug_src (src, pm=False, globs=None)

在一个字符串中调试 doctest 。

这就像上面的函数 @ref{3390,,debug()} ，只是通过 @emph{src} 参数，直接指定一个包含测试用例的字符串。

可选参数 @emph{pm} 的含义与上述函数 @ref{3390,,debug()} 的含义相同。

可选的参数 @emph{globs} 给出了一个字典，作为本地和全局的执行环境。 如果没有指定，或者为 @code{None} ，则使用一个空的字典。如果指定，则使用字典的浅层拷贝。
@end deffn

@ref{338f,,DebugRunner} 类，以及它可能触发的特殊异常，是测试框架作者最感兴趣的，在此仅作简要介绍。请看源代码，特别是 @ref{338f,,DebugRunner} 的文档串（这是一个测试！）以了解更多细节。

@geindex DebugRunner (doctest 中的类)
@anchor{library/doctest doctest DebugRunner}@anchor{338f}
@deffn {类} doctest.DebugRunner (checker=None, verbose=None, optionflags=0)

@ref{3354,,DocTestRunner} 的一个子类，一旦遇到失败，就会触发一个异常。 如果一个意外的异常发生，就会引发一个 @ref{3395,,UnexpectedException} 异常，包含测试、用例和原始异常。 如果输出不匹配，那么就会引发一个 @ref{3396,,DocTestFailure} 异常，包含测试、用例和实际输出。

关于构造函数参数和方法的信息，请参见 @ref{3354,,DocTestRunner} 部分的文档 @ref{3366,,高级 API} 。
@end deffn

@ref{338f,,DebugRunner} 实例可能会触发两种异常。

@geindex DocTestFailure
@anchor{library/doctest doctest DocTestFailure}@anchor{3396}
@deffn {例外} doctest.DocTestFailure (test, example, got)

@ref{3354,,DocTestRunner} 触发的异常，表示一个 doctest 用例的实际输出与预期输出不一致。构造函数参数被用来初始化相同名称的属性。
@end deffn

@ref{3396,,DocTestFailure} 定义了以下属性:

@geindex test (doctest.DocTestFailure 属性)
@anchor{library/doctest doctest DocTestFailure test}@anchor{3397}
@deffn {属性} DocTestFailure.test

当该用例失败时正在运行的 @ref{3363,,DocTest} 对象。
@end deffn

@geindex example (doctest.DocTestFailure 属性)
@anchor{library/doctest doctest DocTestFailure example}@anchor{3398}
@deffn {属性} DocTestFailure.example

失败的 @ref{3367,,Example} 。
@end deffn

@geindex got (doctest.DocTestFailure 属性)
@anchor{library/doctest doctest DocTestFailure got}@anchor{3399}
@deffn {属性} DocTestFailure.got

用例的实际输出。
@end deffn

@geindex UnexpectedException
@anchor{library/doctest doctest UnexpectedException}@anchor{3395}
@deffn {例外} doctest.UnexpectedException (test, example, exc_info)

一个由 @ref{3354,,DocTestRunner} 触发的异常，以提示一个 doctest 用例引发了一个意外的异常。 构造函数参数被用来初始化相同名称的属性。
@end deffn

@ref{3395,,UnexpectedException} 定义了以下属性:

@geindex test (doctest.UnexpectedException 属性)
@anchor{library/doctest doctest UnexpectedException test}@anchor{339a}
@deffn {属性} UnexpectedException.test

当该用例失败时正在运行的 @ref{3363,,DocTest} 对象。
@end deffn

@geindex example (doctest.UnexpectedException 属性)
@anchor{library/doctest doctest UnexpectedException example}@anchor{339b}
@deffn {属性} UnexpectedException.example

失败的 @ref{3367,,Example} 。
@end deffn

@geindex exc_info (doctest.UnexpectedException 属性)
@anchor{library/doctest doctest UnexpectedException exc_info}@anchor{339c}
@deffn {属性} UnexpectedException.exc_info

一个包含意外异常信息的元组，由 @code{sys.ex_info()} 返回。
@end deffn

@node 肥皂盒,,调试,doctest --- 测试交互性的Python示例
@anchor{library/doctest doctest-soapbox}@anchor{339d}@anchor{library/doctest soapbox}@anchor{339e}
@subsubsection 肥皂盒


正如介绍中提到的， @ref{66,,doctest} 已经发展到有三个主要用途:


@enumerate 

@item 
检查 docstring 中的用例。

@item 
回归测试

@item 
可执行的文档/文字测试。
@end enumerate

这些用途有不同的要求，区分它们是很重要的。特别是，用晦涩难懂的测试用例来填充你的文档字符串会使文档变得很糟糕。

在编写文档串时，要谨慎地选择文档串的用例。这是一门需要学习的艺术——一开始可能并不自然。用例应该为文档增加真正的价值。 一个好的用例往往可以抵得上许多文字。如果用心去做，这些用例对你的用户来说是非常有价值的，而且随着时间的推移和事情的变化，收集这些用例所花费的时间也会得到很多倍的回报。 我仍然惊讶于我的 @ref{66,,doctest} 用例在一个“无害”的变化后停止工作。

Doctest 也是回归测试的一个很好的工具，特别是如果你不吝啬解释的文字。 通过交错的文本和用例，可以更容易地跟踪真正的测试，以及为什么。当测试失败时，好的文本可以使你更容易弄清问题所在，以及如何解决。 的确，你可以在基于代码的测试中写大量的注释，但很少有程序员这样做。许多人发现，使用 doctest 方法反而能使测试更加清晰。 也许这只是因为 doctest 使写散文比写代码容易一些，而在代码中写注释则有点困难。 我认为它比这更深入：当写一个基于 doctest 的测试时，自然的态度是你想解释你的软件的细微之处，并用例子来说明它们。这反过来又自然地导致了测试文件从最简单的功能开始，然后逻辑地发展到复杂和边缘案例。 一个连贯的叙述是结果，而不是一个孤立的函数集合，似乎是随机的测试孤立的功能位。 这是一种不同的态度，产生不同的结果，模糊了测试和解释之间的区别。

回归测试最好限制在专用对象或文件中。 有几种组织测试的选择：


@itemize *

@item 
编写包含测试案例的文本文件作为交互式例子，并使用 @ref{333b,,testfile()} 或 @ref{3362,,DocFileSuite()} 来测试这些文件。 建议这样做，尽管对于新的项目来说是最容易做到的，从一开始就设计成使用 doctest 。

@item 
定义命名为 @code{_regrtest_topic} 的函数，由单个文档串组成，包含命名主题的测试用例。 这些函数可以包含在与模块相同的文件中，或分离出来成为一个单独的测试文件。

@item 
定义一个从回归测试主题到包含测试用例的文档串的 @code{__test__} 字典映射。
@end itemize

当你把你的测试放在一个模块中时，这个模块本身就可以成为测试运行器。 当一个测试失败时，你可以安排你的测试运行器只重新运行失败的测试，同时调试问题。 下面是这样一个测试运行器的最小例子:

@example
if __name__ == '__main__':
    import doctest
    flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
    if len(sys.argv) > 1:
        name = sys.argv[1]
        if name in globals():
            obj = globals()[name]
        else:
            obj = __test__[name]
        doctest.run_docstring_examples(obj, globals(), name=name,
                                       optionflags=flags)
    else:
        fail, total = doctest.testmod(optionflags=flags)
        print("@{@} failures out of @{@} tests".format(fail, total))
@end example

@node unittest --- 单元测试框架,unittest mock --- mock对象库,doctest --- 测试交互性的Python示例,开发工具
@anchor{library/unittest doc}@anchor{339f}@anchor{library/unittest module-unittest}@anchor{124}@anchor{library/unittest unittest-unit-testing-framework}@anchor{33a0}
@subsection @code{unittest} --- 单元测试框架


@geindex unittest (模块)

@strong{源代码：} Lib/unittest/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/unittest/__init__.py}


__________________________________________________________________


（如果你已经对测试的概念比较熟悉了，你可能想直接跳转到这一部分 @ref{33a1,,断言方法}。）

@ref{124,,unittest} 单元测试框架是受到 JUnit 的启发，与其他语言中的主流单元测试框架有着相似的风格。其支持测试自动化，配置共享和关机代码测试。支持将测试样例聚合到测试集中，并将测试与报告框架独立。

为了实现这些，@ref{124,,unittest} 通过面向对象的方式支持了一些重要的概念。


@table @asis

@item 测试脚手架

@emph{test fixture} 表示为了开展一项或多项测试所需要进行的准备工作，以及所有相关的清理操作。举个例子，这可能包含创建临时或代理的数据库、目录，再或者启动一个服务器进程。

@item 测试用例

一个测试用例是一个独立的测试单元。它检查输入特定的数据时的响应。 @ref{124,,unittest} 提供一个基类： @ref{9ee,,TestCase} ，用于新建测试用例。

@item 测试套件

@emph{test suite} 是一系列的测试用例，或测试套件，或两者皆有。它用于归档需要一起执行的测试。

@item 测试运行器（test runner）

@emph{test runner} 是一个用于执行和输出测试结果的组件。这个运行器可能使用图形接口、文本接口，或返回一个特定的值表示运行测试的结果。
@end table


@subsubheading 参见



@table @asis

@item @ref{66,,doctest} --- 文档测试模块

另一个风格完全不同的测试模块。

@item 简单 Smalltalk 测试：便用模式@footnote{https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm}

Kent Beck 有关使用 @ref{124,,unittest} 所共享的模式的测试框架的原创论文。

@item pytest@footnote{https://docs.pytest.org/}

第三方单元测试框架，提供轻量化的语法来编写测试，例如：@code{assert func(10) == 42}。

@item Python 测试工具分类@footnote{https://wiki.python.org/moin/PythonTestingToolsTaxonomy}

一个 Python 测试工具的详细列表，包含测试框架和模拟对象库。

@item Python 中的测试 邮件列表

一个讨论 Python 中的测试和测试工具的特别兴趣小组。
@end table

随 Python 源代码分发的脚本 @code{Tools/unittestgui/unittestgui.py} 是一个一个用于发现和执行测试的用户图形界面工具。这主要是为了方便新手使用单元测试制作的。在生产环境中，测试应由一个持续集成（CI）系统运行，如  Buildbot@footnote{https://buildbot.net/}, Jenkins@footnote{https://jenkins.io/} ，Travis-CI@footnote{https://travis-ci.com}, 或 AppVeyor@footnote{https://www.appveyor.com/}。


@menu
* 基本实例:: 
* 命令行界面: 命令行界面<5>. 
* 探索性测试:: 
* 组织你的测试代码:: 
* 复用已有的测试代码:: 
* 跳过测试与预计的失败:: 
* 使用子测试区分测试迭代:: 
* 类与函数:: 
* 类与模块设定:: 
* 信号处理:: 

@end menu

@node 基本实例,命令行界面<5>,,unittest --- 单元测试框架
@anchor{library/unittest basic-example}@anchor{33a2}@anchor{library/unittest unittest-minimal-example}@anchor{33a3}
@subsubsection 基本实例


@ref{124,,unittest} 模块提供了一系列创建和运行测试的工具。这一段落演示了这些工具的一小部分，但也足以满足大部分用户的需求。

这是一段简短的代码，来测试三种字符串方法:

@example
import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()
@end example

继承 @ref{9ee,,unittest.TestCase} 就创建了一个测试样例。上述三个独立的测试是三个类的方法，这些方法的命名都以 @code{test} 开头。 这个命名约定告诉测试运行者类的哪些方法表示测试。

每个测试的关键是：调用 @ref{c8d,,assertEqual()} 来检查预期的输出； 调用 @ref{c8c,,assertTrue()} 或 @ref{d97,,assertFalse()} 来验证一个条件；调用 @ref{b9b,,assertRaises()} 来验证抛出了一个特定的异常。使用这些方法而不是 @ref{240,,assert} 语句是为了让测试运行者能聚合所有的测试结果并产生结果报告。

通过 @ref{d9b,,setUp()} 和 @ref{d9c,,tearDown()} 方法，可以设置测试开始前与完成后需要执行的指令。 在  @ref{33a4,,组织你的测试代码} 中，对此有更为详细的描述。

最后的代码块中，演示了运行测试的一个简单的方法。 @ref{9f1,,unittest.main()} 提供了一个测试脚本的命令行接口。当在命令行运行该测试脚本，上文的脚本生成如以下格式的输出:

@example
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
@end example

在调用测试脚本时添加 @code{-v} 参数使 @ref{9f1,,unittest.main()} 显示更为详细的信息，生成如以下形式的输出:

@example
test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK
@end example

以上例子演示了 @ref{124,,unittest} 中最常用的、足够满足许多日常测试需求的特性。文档的剩余部分详述该框架的完整特性。

@node 命令行界面<5>,探索性测试,基本实例,unittest --- 单元测试框架
@anchor{library/unittest command-line-interface}@anchor{33a5}@anchor{library/unittest unittest-command-line-interface}@anchor{33a6}
@subsubsection 命令行界面


unittest 模块可以通过命令行运行模块、类和独立测试方法的测试:

@example
python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method
@end example

你可以传入模块名、类或方法名或他们的任意组合。

同样的，测试模块可以通过文件路径指定:

@example
python -m unittest tests/test_something.py
@end example

这样就可以使用 shell 的文件名补全指定测试模块。所指定的文件仍需要可以被作为模块导入。路径通过去除 '.py' 、把分隔符转换为 '.' 转换为模块名。若你需要执行不能被作为模块导入的测试文件，你需要直接执行该测试文件。

在运行测试时，你可以通过添加 -v 参数获取更详细（更多的冗余）的信息。

@example
python -m unittest -v test_module
@end example

当运行时不包含参数，开始 @ref{33a7,,探索性测试}

@example
python -m unittest
@end example

用于获取命令行选项列表：

@example
python -m unittest -h
@end example


在 3.2 版更改: 在早期版本中，只支持运行独立的测试方法，而不支持模块和类。


@menu
* 命令行选项: 命令行选项<5>. 

@end menu

@node 命令行选项<5>,,,命令行界面<5>
@anchor{library/unittest command-line-options}@anchor{33a8}
@subsubsection 命令行选项


@code{unittest} supports these command-line options:

@geindex unittest command line option; -b
@geindex unittest command line option; --buffer
@anchor{library/unittest cmdoption-unittest-b}@anchor{d93}
@deffn {程序选项} @w{-}b, @w{-}@w{-}buffer

在测试运行时，标准输出流与标准错误流会被放入缓冲区。成功的测试的运行时输出会被丢弃；测试不通过时，测试运行中的输出会正常显示，错误会被加入到测试失败信息。
@end deffn

@geindex unittest command line option; -c
@geindex unittest command line option; --catch
@anchor{library/unittest cmdoption-unittest-c}@anchor{d94}
@deffn {程序选项} @w{-}c, @w{-}@w{-}catch

当测试正在运行时， @code{Control-C} 会等待当前测试完成，并在完成后报告已执行的测试的结果。当再次按下 @code{Control-C} 时，引发平常的 @ref{2d3,,KeyboardInterrupt} 异常。

See @ref{33a9,,Signal Handling} for the functions that provide this functionality.
@end deffn

@geindex unittest command line option; -f
@geindex unittest command line option; --failfast
@anchor{library/unittest cmdoption-unittest-f}@anchor{d96}
@deffn {程序选项} @w{-}f, @w{-}@w{-}failfast

当出现第一个错误或者失败时，停止运行测试。
@end deffn

@geindex unittest command line option; -k
@anchor{library/unittest cmdoption-unittest-k}@anchor{33aa}
@deffn {程序选项} @w{-}k

只运行匹配模式或子字符串的测试方法和类。 此选项可以被多次使用，在此情况下将会包括匹配任何给定模式的所有测试用例。

包含通配符（*）的模式使用 @ref{1e21,,fnmatch.fnmatchcase()} 对测试名称进行匹配。另外，该匹配是大小写敏感的。

模式对测试加载器导入的测试方法全名进行匹配。

例如，@code{-k foo} 可以匹配到 @code{foo_tests.SomeTest.test_something}  和 @code{bar_tests.SomeTest.test_foo} ，但是不能匹配到 @code{bar_tests.FooTest.test_something} 。
@end deffn

@geindex unittest command line option; --locals
@anchor{library/unittest cmdoption-unittest-locals}@anchor{33ab}
@deffn {程序选项} @w{-}@w{-}locals

在回溯中显示局部变量。
@end deffn


3.2 新版功能: 添加命令行选项 @code{-b}, @code{-c} 和 @code{-f} 。



3.5 新版功能: 命令行选项 @code{--locals} 。



3.7 新版功能: 命令行选项 @code{-k} 。


命令行亦可用于探索性测试，以运行一个项目的所有测试或其子集。

@node 探索性测试,组织你的测试代码,命令行界面<5>,unittest --- 单元测试框架
@anchor{library/unittest test-discovery}@anchor{33ac}@anchor{library/unittest unittest-test-discovery}@anchor{33a7}
@subsubsection 探索性测试



3.2 新版功能.


Unittest支持简单的测试搜索。若需要使用探索性测试，所有的测试文件必须是 @ref{13e0,,modules} 或 @ref{13ee,,packages} （包括 @ref{161d,,namespace packages} )并可从项目根目录导入（即它们的文件名必须是有效的 @ref{1533,,identifiers} ）。

探索性测试在 @ref{9f3,,TestLoader.discover()} 中实现，但也可以通过命令行使用。它在命令行中的基本用法如下：

@example
cd project_directory
python -m unittest discover
@end example

@cartouche
@quotation 注解 
方便起见， @code{python -m unittest} 与 @code{python -m unittest discover} 等价。如果你需要向探索性测试传入参数，必须显式地使用 @code{discover} 子命令。
@end quotation
@end cartouche

@code{discover} 有以下选项：

@geindex unittest-discover command line option; -v
@geindex unittest-discover command line option; --verbose
@anchor{library/unittest cmdoption-unittest-discover-v}@anchor{33ad}
@deffn {程序选项} @w{-}v, @w{-}@w{-}verbose

更详细地输出结果。
@end deffn

@geindex unittest-discover command line option; -s
@geindex unittest-discover command line option; --start-directory directory
@anchor{library/unittest cmdoption-unittest-discover-s}@anchor{33ae}
@deffn {程序选项} @w{-}s, @w{-}@w{-}start@w{-}directory directory

开始进行搜索的目录(默认值为当前目录 @code{.} )。
@end deffn

@geindex unittest-discover command line option; -p
@geindex unittest-discover command line option; --pattern pattern
@anchor{library/unittest cmdoption-unittest-discover-p}@anchor{33af}
@deffn {程序选项} @w{-}p, @w{-}@w{-}pattern pattern

用于匹配测试文件的模式（默认为 @code{test*.py} ）。
@end deffn

@geindex unittest-discover command line option; -t
@geindex unittest-discover command line option; --top-level-directory directory
@anchor{library/unittest cmdoption-unittest-discover-t}@anchor{33b0}
@deffn {程序选项} @w{-}t, @w{-}@w{-}top@w{-}level@w{-}directory directory

指定项目的最上层目录（通常为开始时所在目录）。
@end deffn

@ref{33ae,,-s} ，@ref{33af,,-p} 和 @ref{33b0,,-t} 选项可以按顺序作为位置参数传入。以下两条命令是等价的：

@example
python -m unittest discover -s project_directory -p "*_test.py"
python -m unittest discover project_directory "*_test.py"
@end example

正如可以传入路径那样，传入一个包名作为起始目录也是可行的，如 @code{myproject.subpackage.test} 。你提供的包名会被导入，它在文件系统中的位置会被作为起始目录。

@cartouche
@quotation 警告 
探索性测试通过导入测试对测试进行加载。在找到所有你指定的开始目录下的所有测试文件后，它把路径转换为包名并进行导入。如 @code{foo/bar/baz.py} 会被导入为 @code{foo.bar.baz} 。

如果你有一个全局安装的包，并尝试对这个包的副本进行探索性测试，可能会从错误的地方开始导入。如果出现这种情况，测试会输出警告并退出。

如果你使用包名而不是路径作为开始目录，搜索时会假定它导入的是你想要的目录，所以你不会收到警告。
@end quotation
@end cartouche

测试模块和包可以通过 @ref{33b1,,load_tests protocol} 自定义测试的加载和搜索。


在 3.4 版更改: 测试发现支持初始目录下的 @ref{161d,,命名空间包}。注意你也需要指定顶层目录（例如：@code{python -m unittest discover -s root/namespace -t root}）。


@node 组织你的测试代码,复用已有的测试代码,探索性测试,unittest --- 单元测试框架
@anchor{library/unittest organizing-test-code}@anchor{33b2}@anchor{library/unittest organizing-tests}@anchor{33a4}
@subsubsection 组织你的测试代码


单元测试的构建单位是 @emph{test cases} ：独立的、包含执行条件与正确性检查的方案。在 @ref{124,,unittest} 中，测试用例表示为 @ref{9ee,,unittest.TestCase} 的实例。通过编写 @ref{9ee,,TestCase} 的子类或使用 @ref{33b3,,FunctionTestCase} 编写你自己的测试用例。

一个 @ref{9ee,,TestCase} 实例的测试代码必须是完全自含的，因此它可以独立运行，或与其它任意组合任意数量的测试用例一起运行。

@ref{9ee,,TestCase} 的最简单的子类需要实现一个测试方法（例如一个命名以 @code{test} 开头的方法）以执行特定的测试代码：

@example
import unittest

class DefaultWidgetSizeTestCase(unittest.TestCase):
    def test_default_widget_size(self):
        widget = Widget('The widget')
        self.assertEqual(widget.size(), (50, 50))
@end example

可以看到，为了进行测试，我们使用了基类 @ref{9ee,,TestCase} 提供的其中一个 @code{assert*()} 方法。若测试不通过，将会引发一个带有说明信息的异常，并且 @ref{124,,unittest} 会将这个测试用例标记为测试不通过。任何其它类型的异常将会被当做错误处理。

可能同时存在多个前置操作相同的测试，我们可以把测试的前置操作从测试代码中拆解出来，并实现测试前置方法 @ref{d9b,,setUp()} 。在运行测试时，测试框架会自动地为每个单独测试调用前置方法。

@example
import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def test_default_widget_size(self):
        self.assertEqual(self.widget.size(), (50,50),
                         'incorrect default size')

    def test_widget_resize(self):
        self.widget.resize(100,150)
        self.assertEqual(self.widget.size(), (100,150),
                         'wrong size after resize')
@end example

@cartouche
@quotation 注解 
多个测试运行的顺序由内置字符串排序方法对测试名进行排序的结果决定。
@end quotation
@end cartouche

在测试运行时，若 @ref{d9b,,setUp()} 方法引发异常，测试框架会认为测试发生了错误，因此测试方法不会被运行。

相似的，我们提供了一个 @ref{d9c,,tearDown()} 方法在测试方法运行后进行清理工作。

@example
import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):
        self.widget.dispose()
@end example

若 @ref{d9b,,setUp()} 成功运行，无论测试方法是否成功，都会运行 @ref{d9c,,tearDown()} 。

这样的一个测试代码运行的环境被称为 @emph{test fixture} 。一个新的 TestCase 实例作为一个测试脚手架，用于运行各个独立的测试方法。在运行每个测试时，@ref{d9b,,setUp()} 、@ref{d9c,,tearDown()} 和 @code{__init__()} 会被调用一次。

推荐你根据用例所测试的功能将测试用 TestCase 分组。@ref{124,,unittest} 为此提供了 @emph{test suite}：@ref{124,,unittest} 的 @ref{7cb,,TestSuite} 类是一个代表。通常情况下，调用 @ref{9f1,,unittest.main()} 就能正确地找到并执行这个模块下所有用 TestCase 分组的测试。

然而，如果你需要自定义你的测试套件的话，你可以参考以下方法组织你的测试：

@example
def suite():
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase('test_default_widget_size'))
    suite.addTest(WidgetTestCase('test_widget_resize'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())
@end example

你可以把测试用例和测试套件放在与被测试代码相同的模块中（比如 @code{widget.py}），但将测试代码放在单独的模块中（比如 @code{test_widget.py}）有几个优势。


@itemize *

@item 
测试模块可以从命令行被独立调用。

@item 
更容易在分发的代码中剥离测试代码。

@item 
降低没有好理由的情况下修改测试代码以通过测试的诱惑。

@item 
测试代码应比被测试代码更少地被修改。

@item 
被测试代码可以更容易地被重构。

@item 
对用 C 语言写成的模块无论如何都得单独写成一个模块，为什么不保持一致呢？

@item 
如果测试策略发生了改变，没有必要修改源代码。
@end itemize

@node 复用已有的测试代码,跳过测试与预计的失败,组织你的测试代码,unittest --- 单元测试框架
@anchor{library/unittest legacy-unit-tests}@anchor{33b4}@anchor{library/unittest re-using-old-test-code}@anchor{33b5}
@subsubsection 复用已有的测试代码


一些用户希望直接使用 @ref{124,,unittest} 运行已有的测试代码，而不需要把已有的每个测试函数转化为一个 @ref{9ee,,TestCase} 的子类。

因此， @ref{124,,unittest} 提供 @ref{33b3,,FunctionTestCase} 类。这个 @ref{9ee,,TestCase} 的子类可用于打包已有的测试函数，并支持设置前置与后置函数。

假定有一个测试函数：

@example
def testSomething():
    something = makeSomething()
    assert something.name is not None
    # ...
@end example

可以创建等价的测试用例如下，其中前置和后置方法是可选的。

@example
testcase = unittest.FunctionTestCase(testSomething,
                                     setUp=makeSomethingDB,
                                     tearDown=deleteSomethingDB)
@end example

@cartouche
@quotation 注解 
用 @ref{33b3,,FunctionTestCase} 可以快速将现有的测试转换成基于 @ref{124,,unittest} 的测试，但不推荐你这样做。花点时间继承 @ref{9ee,,TestCase} 会让以后重构测试无比轻松。
@end quotation
@end cartouche

在某些情况下，现有的测试可能是用 @ref{66,,doctest} 模块编写的。 如果是这样， @ref{66,,doctest} 提供了一个 @code{DocTestSuite} 类，可以从现有基于 @ref{66,,doctest} 的测试中自动构建 @ref{7cb,,unittest.TestSuite} 用例。

@node 跳过测试与预计的失败,使用子测试区分测试迭代,复用已有的测试代码,unittest --- 单元测试框架
@anchor{library/unittest skipping-tests-and-expected-failures}@anchor{33b6}@anchor{library/unittest unittest-skipping}@anchor{33b7}
@subsubsection 跳过测试与预计的失败



3.1 新版功能.


Unittest 支持跳过单个或整组的测试用例。它还支持把测试标注成“预期失败”的测试，这些坏测试会失败，但不会算进 @ref{ba0,,TestResult} 的失败里。

要跳过测试只需使用 @ref{112e,,skip()} @ref{174,,decorator} 或其附带条件的版本，在 @ref{d9b,,setUp()} 内部使用 @ref{33b8,,TestCase.skipTest()}，或是直接引发 @ref{9f2,,SkipTest}。

跳过测试的基本用法如下:

@example
class MyTestCase(unittest.TestCase):

    @@unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @@unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("external resource not available")
        # test code that depends on the external resource
        pass
@end example

在啰嗦模式下运行以上测试例子时，程序输出如下：

@example
test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)
@end example

跳过测试类的写法跟跳过测试方法的写法相似:

@example
@@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass
@end example

@ref{d9b,,TestCase.setUp()}  也可以跳过测试。可以用于所需资源不可用的情况下跳过接下来的测试。

使用 @ref{33b9,,expectedFailure()} 装饰器表明这个测试预计失败。:

@example
class ExpectedFailureTestCase(unittest.TestCase):
    @@unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")
@end example

你可以很容易地编写在测试时调用 @ref{112e,,skip()} 的装饰器作为自定义的跳过测试装饰器。 下面这个装饰器会跳过测试，除非所传入的对象具有特定的属性:

@example
def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("@{!r@} doesn't have @{!r@}".format(obj, attr))
@end example

以下的装饰器和异常实现了跳过测试和预期失败两种功能：

@geindex skip() (在 unittest 模块中)
@anchor{library/unittest unittest skip}@anchor{112e}
@deffn {函数} @@unittest.skip (reason)

跳过被此装饰器装饰的测试。 @emph{reason}  为测试被跳过的原因。
@end deffn

@geindex skipIf() (在 unittest 模块中)
@anchor{library/unittest unittest skipIf}@anchor{33ba}
@deffn {函数} @@unittest.skipIf (condition, reason)

当 @emph{condition} 为真时，跳过被装饰的测试。
@end deffn

@geindex skipUnless() (在 unittest 模块中)
@anchor{library/unittest unittest skipUnless}@anchor{33bb}
@deffn {函数} @@unittest.skipUnless (condition, reason)

跳过被装饰的测试，除非 @emph{condition} 为真。
@end deffn

@geindex expectedFailure() (在 unittest 模块中)
@anchor{library/unittest unittest expectedFailure}@anchor{33b9}
@deffn {函数} @@unittest.expectedFailure

将测试标记为预期的失败或错误。 如果测试失败或在测试函数自身（而非在某个 @emph{test fixture} 方法）中出现错误则将认为是测试成功。 如果测试通过，则将认为是测试失败。
@end deffn

@geindex SkipTest
@anchor{library/unittest unittest SkipTest}@anchor{9f2}
@deffn {例外} unittest.SkipTest (reason)

引发此异常以跳过一个测试。

通常来说，你可以使用 @ref{33b8,,TestCase.skipTest()} 或其中一个跳过测试的装饰器实现跳过测试的功能，而不是直接引发此异常。
@end deffn

被跳过的测试的 @ref{d9b,,setUp()}  和 @ref{d9c,,tearDown()} 不会被运行。被跳过的类的 @ref{37d,,setUpClass()} 和 @ref{d99,,tearDownClass()} 不会被运行。被跳过的模组的 @code{setUpModule()} 和 @code{tearDownModule()} 不会被运行。

@node 使用子测试区分测试迭代,类与函数,跳过测试与预计的失败,unittest --- 单元测试框架
@anchor{library/unittest distinguishing-test-iterations-using-subtests}@anchor{33bc}@anchor{library/unittest subtests}@anchor{9f0}
@subsubsection 使用子测试区分测试迭代



3.4 新版功能.


当你的几个测试之间的差异非常小，例如只有某些形参不同时，unittest 允许你使用 @ref{9ef,,subTest()} 上下文管理器在一个测试方法体的内部区分它们。

例如，以下测试:

@example
class NumbersTest(unittest.TestCase):

    def test_even(self):
        """
        Test that numbers between 0 and 5 are all even.
        """
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
@end example

可以得到以下输出:

@example
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
@end example

如果不使用子测试，程序遇到第一次错误之后就会停止。而且因为`@w{`}i`@w{`}的值不显示，错误也更难找。

@example
======================================================================
FAIL: test_even (__main__.NumbersTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
@end example

@node 类与函数,类与模块设定,使用子测试区分测试迭代,unittest --- 单元测试框架
@anchor{library/unittest classes-and-functions}@anchor{33bd}@anchor{library/unittest unittest-contents}@anchor{33be}
@subsubsection 类与函数


本节深入介绍了 @ref{124,,unittest} 的 API。

@menu
* 测试用例:: 
* 分组测试:: 
* 加载和运行测试:: 

@end menu

@node 测试用例,分组测试,,类与函数
@anchor{library/unittest test-cases}@anchor{33bf}@anchor{library/unittest testcase-objects}@anchor{33c0}
@subsubsection 测试用例


@geindex TestCase (unittest 中的类)
@anchor{library/unittest unittest TestCase}@anchor{9ee}
@deffn {类} unittest.TestCase (methodName='runTest')

@ref{9ee,,TestCase} 类的实例代表了 @ref{124,,unittest} 宇宙中的逻辑测试单元。 该类旨在被当作基类使用，特定的测试将由其实体子类来实现。 该类实现了测试运行器所需的接口以允许它驱动测试，并实现了可被测试代码用来检测和报告各种类型的失败的方法。

每个 @ref{9ee,,TestCase} 实例将运行一个单位的基础方法：即名为 @emph{methodName} 的方法。 在使用 @ref{9ee,,TestCase} 的大多数场景中，你都不需要修改 @emph{methodName} 或重新实现默认的 @code{runTest()} 方法。


在 3.2 版更改: @ref{9ee,,TestCase} 不需要提供 @emph{methodName} 即可成功初始化。 这使得从交互式解释器试验 @ref{9ee,,TestCase} 更为容易。


@ref{9ee,,TestCase} 的实例提供了三组方法：一组用来运行测试，另一组被测试实现用来检查条件和报告失败，还有一些查询方法用来收集有关测试本身的信息。

第一组（用于运行测试的）方法是：

@geindex setUp() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase setUp}@anchor{d9b}
@deffn {方法} setUp ()

为测试预备而调用的方法。 此方法会在调用测试方法之前被调用；除了 @ref{241,,AssertionError} 或 @ref{9f2,,SkipTest}，此方法所引发的任何异常都将被视为错误而非测试失败。 默认的实现将不做任何事情。
@end deffn

@geindex tearDown() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase tearDown}@anchor{d9c}
@deffn {方法} tearDown ()

在测试方法被调用并记录结果之后立即被调用的方法。 此方法即使在测试方法引发异常时仍会被调用，因此子类中的实现将需要特别注意检查内部状态。 除 @ref{241,,AssertionError} 或 @ref{9f2,,SkipTest} 外，此方法所引发的任何异常都将被视为额外的错误而非测试失败（因而会增加总计错误报告数）。 此方法将只在 @ref{d9b,,setUp()} 成功执行时被调用，无论测试方法的结果如何。 默认的实现将不做任何事情。
@end deffn

@geindex setUpClass() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase setUpClass}@anchor{37d}
@deffn {方法} setUpClass ()

在一个单独类中的测试运行之前被调用的类方法。 @code{setUpClass} 会被作为唯一的参数在类上调用且必须使用 @ref{310,,classmethod()} 装饰器:

@example
@@classmethod
def setUpClass(cls):
    ...
@end example

查看 @ref{33c1,,Class and Module Fixtures} 获取更详细的说明。


3.2 新版功能.

@end deffn

@geindex tearDownClass() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase tearDownClass}@anchor{d99}
@deffn {方法} tearDownClass ()

在一个单独类的测试完成运行之后被调用的类方法。 @code{tearDownClass} 会被作为唯一的参数在类上调用且必须使用 @ref{310,,classmethod()} 装饰器:

@example
@@classmethod
def tearDownClass(cls):
    ...
@end example

查看 @ref{33c1,,Class and Module Fixtures} 获取更详细的说明。


3.2 新版功能.

@end deffn

@geindex run() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase run}@anchor{b9f}
@deffn {方法} run (result=None)

运行测试，将结果收集至作为 @emph{result} 传入的 @ref{ba0,,TestResult}。 如果 @emph{result} 被省略或为 @code{None}，则会创建一个临时的结果对象（通过调用 @ref{33c2,,defaultTestResult()} 方法）并使用它。 结果对象会被返回给 @ref{b9f,,run()} 的调用方。

同样的效果也可通过简单地调用 @ref{9ee,,TestCase} 实例来达成。


在 3.3 版更改: 之前版本的 @code{run} 不会返回结果。 也不会调用实例。

@end deffn

@geindex skipTest() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase skipTest}@anchor{33b8}
@deffn {方法} skipTest (reason)

在测试方法或 @ref{d9b,,setUp()} 执行期间调用此方法将跳过当前测试。 详情参见 @ref{33b7,,跳过测试与预计的失败}。


3.1 新版功能.

@end deffn

@geindex subTest() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase subTest}@anchor{9ef}
@deffn {方法} subTest (msg=None, **params)

返回一个上下文管理器以将其中的代码块作为子测试来执行。 可选的 @emph{msg} 和 @emph{params} 是将在子测试失败时显示的任意值，以便让你能清楚地标识它们。

一个测试用例可以包含任意数量的子测试声明，并且它们可以任意地嵌套。

查看 @ref{9f0,,使用子测试区分测试迭代} 获取更详细的信息。


3.4 新版功能.

@end deffn

@geindex debug() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase debug}@anchor{fba}
@deffn {方法} debug ()

运行测试而不收集结果。 这允许测试所引发的异常被传递给调用方，并可被用于支持在调试器中运行测试。
@end deffn
@anchor{library/unittest assert-methods}@anchor{33a1}
@ref{9ee,,TestCase} 类提供了一些断言方法用于检查并报告失败。 下表列出了最常用的方法（请查看下文的其他表来了解更多的断言方法）:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

方法

@tab

检查对象

@tab

引入版本

@item

@ref{c8d,,assertEqual(a@comma{} b)}

@tab

@code{a == b}

@tab

@item

@ref{c8e,,assertNotEqual(a@comma{} b)}

@tab

@code{a != b}

@tab

@item

@ref{c8c,,assertTrue(x)}

@tab

@code{bool(x) is True}

@tab

@item

@ref{d97,,assertFalse(x)}

@tab

@code{bool(x) is False}

@tab

@item

@ref{d9f,,assertIs(a@comma{} b)}

@tab

@code{a is b}

@tab

3.1

@item

@ref{da0,,assertIsNot(a@comma{} b)}

@tab

@code{a is not b}

@tab

3.1

@item

@ref{d9d,,assertIsNone(x)}

@tab

@code{x is None}

@tab

3.1

@item

@ref{d9e,,assertIsNotNone(x)}

@tab

@code{x is not None}

@tab

3.1

@item

@ref{da8,,assertIn(a@comma{} b)}

@tab

@code{a in b}

@tab

3.1

@item

@ref{da9,,assertNotIn(a@comma{} b)}

@tab

@code{a not in b}

@tab

3.1

@item

@ref{da1,,assertIsInstance(a@comma{} b)}

@tab

@code{isinstance(a, b)}

@tab

3.2

@item

@ref{da2,,assertNotIsInstance(a@comma{} b)}

@tab

@code{not isinstance(a, b)}

@tab

3.2

@end multitable


这些断言方法都支持 @emph{msg} 参数，如果指定了该参数，它将被用作测试失败时的错误消息 (另请参阅 @ref{d98,,longMessage})。 请注意将 @emph{msg} 关键字参数传给 @ref{b9b,,assertRaises()}, @ref{b9c,,assertRaisesRegex()}, @ref{b9d,,assertWarns()}, @ref{b9e,,assertWarnsRegex()} 的前提是它们必须被用作上下文管理器。

@geindex assertEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertEqual}@anchor{c8d}
@deffn {方法} assertEqual (first, second, msg=None)

测试 @emph{first} 和 @emph{second} 是否相等。 如果两个值的比较结果是不相等，则测试将失败。

此外，如果 @emph{first} 和 @emph{second} 的类型完全相同且属于 list, tuple, dict, set, frozenset 或 str 或者属于通过 @ref{db1,,addTypeEqualityFunc()} 注册子类的类型则将会调用类型专属的相等判断函数以便生成更有用的默认错误消息 (另请参阅 @ref{33c3,,类型专属方法列表})。


在 3.1 版更改: 增加了对类型专属的相等判断函数的自动调用。



在 3.2 版更改: 增加了 @ref{da7,,assertMultiLineEqual()} 作为用于比较字符串的默认类型相等判断函数。

@end deffn

@geindex assertNotEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertNotEqual}@anchor{c8e}
@deffn {方法} assertNotEqual (first, second, msg=None)

测试 @emph{first} 和 @emph{second} 是否不等。 如果两个值的比较结果是相等，则测试将失败。
@end deffn

@geindex assertTrue() (unittest.TestCase 方法)
@geindex assertFalse() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertTrue}@anchor{c8c}
@deffn {方法} assertTrue (expr, msg=None)
@anchor{library/unittest unittest TestCase assertFalse}@anchor{d97}
@deffnx {方法} assertFalse (expr, msg=None)

测试 @emph{expr} 是否为真值（或假值）。

请注意这等价于 @code{bool(expr) is True} 而不等价于 @code{expr is True} (后者要使用 @code{assertIs(expr, True)})。 当存在更专门的方法时也应避免使用此方法 (例如应使用 @code{assertEqual(a, b)} 而不是 @code{assertTrue(a == b)})，因为它们在测试失败时会提供更有用的错误消息。
@end deffn

@geindex assertIs() (unittest.TestCase 方法)
@geindex assertIsNot() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertIs}@anchor{d9f}
@deffn {方法} assertIs (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertIsNot}@anchor{da0}
@deffnx {方法} assertIsNot (first, second, msg=None)

测试 @emph{first} 和 @emph{second} 是（或不是）同一个对象。


3.1 新版功能.

@end deffn

@geindex assertIsNone() (unittest.TestCase 方法)
@geindex assertIsNotNone() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertIsNone}@anchor{d9d}
@deffn {方法} assertIsNone (expr, msg=None)
@anchor{library/unittest unittest TestCase assertIsNotNone}@anchor{d9e}
@deffnx {方法} assertIsNotNone (expr, msg=None)

测试 @emph{expr} 是 (或不是) @code{None}。


3.1 新版功能.

@end deffn

@geindex assertIn() (unittest.TestCase 方法)
@geindex assertNotIn() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertIn}@anchor{da8}
@deffn {方法} assertIn (member, container, msg=None)
@anchor{library/unittest unittest TestCase assertNotIn}@anchor{da9}
@deffnx {方法} assertNotIn (member, container, msg=None)

测试 @emph{member} 是 (或不是) @emph{container} 的成员。


3.1 新版功能.

@end deffn

@geindex assertIsInstance() (unittest.TestCase 方法)
@geindex assertNotIsInstance() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertIsInstance}@anchor{da1}
@deffn {方法} assertIsInstance (obj, cls, msg=None)
@anchor{library/unittest unittest TestCase assertNotIsInstance}@anchor{da2}
@deffnx {方法} assertNotIsInstance (obj, cls, msg=None)

测试 @emph{obj} 是 (或不是) @emph{cls} (此参数可以为一个类或包含类的元组，即 @ref{55a,,isinstance()} 所接受的参数) 的实例。 要检测是否为指定类型，请使用 @ref{d9f,,assertIs(type(obj)@comma{} cls)}。


3.2 新版功能.

@end deffn

还可以使用下列方法来检查异常、警告和日志消息的产生:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

方法

@tab

检查对象

@tab

引入版本

@item

@ref{b9b,,assertRaises(exc@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} 引发 @emph{exc}

@tab

@item

@ref{b9c,,assertRaisesRegex(exc@comma{} r@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} 引发了 @emph{exc} 并且消息可与正则表达式 @emph{r} 相匹配

@tab

3.1

@item

@ref{b9d,,assertWarns(warn@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} 引发了 @emph{warn}

@tab

3.2

@item

@ref{b9e,,assertWarnsRegex(warn@comma{} r@comma{} fun@comma{} *args@comma{} **kwds)}

@tab

@code{fun(*args, **kwds)} 引发了 @emph{warn} 并且消息可与正则表达式 @emph{r} 相匹配

@tab

3.2

@item

@ref{9f4,,assertLogs(logger@comma{} level)}

@tab

@code{with} 代码块在 @emph{logger} 上使用最小的 @emph{level} 级别写入了日志

@tab

3.4

@end multitable


@geindex assertRaises() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertRaises}@anchor{b9b}
@deffn {方法} assertRaises (exception, callable, *args, **kwds)

@deffnx {方法} assertRaises (exception, *, msg=None)

测试当 @emph{callable} 附带任何同时被传给 @ref{b9b,,assertRaises()} 的位置或关键字参数被调用时是否引发了异常。 如果引发了 @emph{exception} 则测试通过，如果引发了另一个异常则报错，或者如果未引发任何异常则测试失败。 要捕获一组异常中的任何一个，可以将包含多个异常类的元组作为 @emph{exception} 传入。

如果只给出了 @emph{exception} 和可能的 @emph{msg} 参数，则返回一个上下文管理器以便被测试的代码可以被写成内联形式而不是被写成函数:

@example
with self.assertRaises(SomeException):
    do_something()
@end example

当被作为上下文管理器使用时，@ref{b9b,,assertRaises()} 接受额外的关键字参数 @emph{msg}。

上下文管理器将把捕获的异常对象存入在其 @code{exception} 属性中。 这适用于需要对所引发异常执行额外检查的场合:

@example
with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
@end example


在 3.1 版更改: 添加了将 @ref{b9b,,assertRaises()} 用作上下文管理器的功能。



在 3.2 版更改: 增加了 @code{exception} 属性。



在 3.3 版更改: 增加了 @emph{msg} 关键字参数在作为上下文管理器时使用。

@end deffn

@geindex assertRaisesRegex() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertRaisesRegex}@anchor{b9c}
@deffn {方法} assertRaisesRegex (exception, regex, callable, *args, **kwds)

@deffnx {方法} assertRaisesRegex (exception, regex, *, msg=None)

与 @ref{b9b,,assertRaises()} 类似但还会测试 @emph{regex} 是否匹配被引发异常的字符串表示形式。 @emph{regex} 可以是一个正则表达式对象或包含正则表达式的字符串以提供给 @ref{c8a,,re.search()} 使用。 例如:

@example
self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
                       int, 'XYZ')
@end example

或者：

@example
with self.assertRaisesRegex(ValueError, 'literal'):
   int('XYZ')
@end example


3.1 新版功能: 以方法名`@w{`}assertRaisesRegexp`@w{`}添加。



在 3.2 版更改: 重命名为 @ref{b9c,,assertRaisesRegex()}。



在 3.3 版更改: 增加了 @emph{msg} 关键字参数在作为上下文管理器时使用。

@end deffn

@geindex assertWarns() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertWarns}@anchor{b9d}
@deffn {方法} assertWarns (warning, callable, *args, **kwds)

@deffnx {方法} assertWarns (warning, *, msg=None)

测试当 @emph{callable} 附带任何同时被传给 @ref{b9d,,assertWarns()} 的位置或关键字参数被调用时是否触发了警告。 如果触发了 @emph{warning} 则测试通过，否则测试失败。 引发任何异常则报错。 要捕获一组警告中的任何一个，可将包含多个警告类的元组作为 @emph{warnings} 传入。

如果只给出了 @emph{warning} 和可能的 @emph{msg} 参数，则返回一个上下文管理器以便被测试的代码可以被写成内联形式而不是被写成函数:

@example
with self.assertWarns(SomeWarning):
    do_something()
@end example

当被作为上下文管理器使用时，@ref{b9d,,assertWarns()} 接受额外的关键字参数 @emph{msg}。

上下文管理器将把捕获的警告对象保存在其 @code{warning} 属性中，并把触发警告的源代码行保存在 @code{filename} 和 @code{lineno} 属性中。 这适用于需要对捕获的警告执行额外检查的场合:

@example
with self.assertWarns(SomeWarning) as cm:
    do_something()

self.assertIn('myfile.py', cm.filename)
self.assertEqual(320, cm.lineno)
@end example

无论被调用时警告过滤器是否就位此方法均可工作。


3.2 新版功能.



在 3.3 版更改: 增加了 @emph{msg} 关键字参数在作为上下文管理器时使用。

@end deffn

@geindex assertWarnsRegex() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertWarnsRegex}@anchor{b9e}
@deffn {方法} assertWarnsRegex (warning, regex, callable, *args, **kwds)

@deffnx {方法} assertWarnsRegex (warning, regex, *, msg=None)

与 @ref{b9d,,assertWarns()} 类似但还会测试 @emph{regex} 是否匹配被触发警告的消息文本。 @emph{regex} 可以是一个正则表达式对象或包含正则表达式的字符串以提供给 @ref{c8a,,re.search()} 使用。 例如:

@example
self.assertWarnsRegex(DeprecationWarning,
                      r'legacy_function\(\) is deprecated',
                      legacy_function, 'XYZ')
@end example

或者：

@example
with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
    frobnicate('/etc/passwd')
@end example


3.2 新版功能.



在 3.3 版更改: 增加了 @emph{msg} 关键字参数在作为上下文管理器时使用。

@end deffn

@geindex assertLogs() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertLogs}@anchor{9f4}
@deffn {方法} assertLogs (logger=None, level=None)

一个上下文管理器，它测试在 @emph{logger} 或其子对象上是否至少记录了一条至少为指定 @emph{level} 以上级别的消息。

如果给出了 @emph{logger} 则它应为一个 @ref{4b6,,logging.Logger} 对象或为一个指定日志记录器名称的 @ref{206,,str}。 默认为根日志记录器，它将捕获未被非传播型后继日志记录器所拦阻的所有消息。

如果给出了 @emph{level} 则它应为一个用数字表示的日志记录级别或其字符串形式 (例如 @code{"ERROR"} 或 @code{logging.ERROR})。 默认为 @code{logging.INFO}。

如果在 @code{with} 代码块内部发出了至少一条与 @emph{logger} 和 @emph{level} 条件相匹配的消息则测试通过，否则测试失败。

上下文管理器返回的对象是一个记录辅助器，它会记录所匹配的日志消息。 它有两个属性:

@geindex records (unittest.TestCase 属性)
@anchor{library/unittest unittest TestCase records}@anchor{33c4}
@deffn {属性} records

所匹配的日志消息 @ref{9f5,,logging.LogRecord} 对象组成的列表。
@end deffn

@geindex output (unittest.TestCase 属性)
@anchor{library/unittest unittest TestCase output}@anchor{33c5}
@deffn {属性} output

由 @ref{206,,str} 对象组成的列表，内容为所匹配消息经格式化后的输出。
@end deffn

示例:

@example
with self.assertLogs('foo', level='INFO') as cm:
   logging.getLogger('foo').info('first message')
   logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
@end example


3.4 新版功能.

@end deffn

还有其他一些方法可用于执行更专门的检查，例如:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

方法

@tab

检查对象

@tab

引入版本

@item

@ref{c8f,,assertAlmostEqual(a@comma{} b)}

@tab

@code{round(a-b, 7) == 0}

@tab

@item

@ref{c90,,assertNotAlmostEqual(a@comma{} b)}

@tab

@code{round(a-b, 7) != 0}

@tab

@item

@ref{da3,,assertGreater(a@comma{} b)}

@tab

@code{a > b}

@tab

3.1

@item

@ref{da4,,assertGreaterEqual(a@comma{} b)}

@tab

@code{a >= b}

@tab

3.1

@item

@ref{da5,,assertLess(a@comma{} b)}

@tab

@code{a < b}

@tab

3.1

@item

@ref{da6,,assertLessEqual(a@comma{} b)}

@tab

@code{a <= b}

@tab

3.1

@item

@ref{c89,,assertRegex(s@comma{} r)}

@tab

@code{r.search(s)}

@tab

3.1

@item

@ref{33c6,,assertNotRegex(s@comma{} r)}

@tab

@code{not r.search(s)}

@tab

3.2

@item

@ref{c87,,assertCountEqual(a@comma{} b)}

@tab

@emph{a} 和 @emph{b} 具有同样数量的相同元素，无论其顺序如何。

@tab

3.2

@end multitable


@geindex assertAlmostEqual() (unittest.TestCase 方法)
@geindex assertNotAlmostEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertAlmostEqual}@anchor{c8f}
@deffn {方法} assertAlmostEqual (first, second, places=7, msg=None, delta=None)
@anchor{library/unittest unittest TestCase assertNotAlmostEqual}@anchor{c90}
@deffnx {方法} assertNotAlmostEqual (first, second, places=7, msg=None, delta=None)

测试 @emph{first} 是否约等于 @emph{second}，比较的标准是计算差值并舍入到 @emph{places} 所指定的十进制位数 (默认为 7 位)，再与零相比较。 请注意此方法是将结果值舍入到指定的 @emph{十进制位数} (即相当于 @ref{d3d,,round()} 函数) 而非 @emph{有效位数}。

如果提供了 @emph{delta} 而非 @emph{places} 则 @emph{first} 和 @emph{second} 之间的差值必须小于等于 (或大于) @emph{delta}。

同时提供 @emph{delta} 和 @emph{places} 将引发 @ref{1ff,,TypeError}。


在 3.2 版更改: @ref{c8f,,assertAlmostEqual()} 会自动将几乎相等的对象视为相等。 而如果对象相等则 @ref{c90,,assertNotAlmostEqual()} 会自动测试失败。 增加了 @emph{delta} 关键字参数。

@end deffn

@geindex assertGreater() (unittest.TestCase 方法)
@geindex assertGreaterEqual() (unittest.TestCase 方法)
@geindex assertLess() (unittest.TestCase 方法)
@geindex assertLessEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertGreater}@anchor{da3}
@deffn {方法} assertGreater (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertGreaterEqual}@anchor{da4}
@deffnx {方法} assertGreaterEqual (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertLess}@anchor{da5}
@deffnx {方法} assertLess (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertLessEqual}@anchor{da6}
@deffnx {方法} assertLessEqual (first, second, msg=None)

根据方法名分别测试 @emph{first} 是否 >, >=, < 或 <= @emph{second}。 如果不是，则测试失败:

@example
>>> self.assertGreaterEqual(3, 4)
AssertionError: "3" unexpectedly not greater than or equal to "4"
@end example


3.1 新版功能.

@end deffn

@geindex assertRegex() (unittest.TestCase 方法)
@geindex assertNotRegex() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertRegex}@anchor{c89}
@deffn {方法} assertRegex (text, regex, msg=None)
@anchor{library/unittest unittest TestCase assertNotRegex}@anchor{33c6}
@deffnx {方法} assertNotRegex (text, regex, msg=None)

测试一个 @emph{regex} 是否匹配 @emph{文本}。如果不匹配，错误信息中将包含匹配模式和 @emph{文本*（或部分匹配失败的 *文本}）。@emph{regex} 可以是正则表达式对象或能够用于 @ref{c8a,,re.search()} 的包含正则表达式的字符串。


3.1 新版功能: 以方法名`@w{`}assertRegexpMatches`@w{`}添加。



在 3.2 版更改: 方法 @code{assertRegexpMatches()} 已被改名为 @ref{c89,,assertRegex()}。



3.2 新版功能: @ref{33c6,,assertNotRegex()}



3.5 新版功能: @code{assertNotRegexpMatches} 这个名字是 @ref{33c6,,assertNotRegex()} 的已被弃用的别名。

@end deffn

@geindex assertCountEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertCountEqual}@anchor{c87}
@deffn {方法} assertCountEqual (first, second, msg=None)

测试序列 @emph{first} 与 @emph{second} 是否包含同样的元素，无论其顺序如何。 当存在差异时，将生成一条错误消息来列出两个序列之间的差异。

重复的元素 @emph{不会} 在 @emph{first} 和 @emph{second} 的比较中被忽略。 它会检查每个元素在两个序列中的出现次数是否相同。 等价于: @code{assertEqual(Counter(list(first)), Counter(list(second)))} 但还适用于包含不可哈希对象的序列。


3.2 新版功能.

@end deffn
@anchor{library/unittest type-specific-methods}@anchor{33c3}
@ref{c8d,,assertEqual()} 方法会将相同类型对象的相等性检查分派给不同的类型专属方法。 这些方法已被大多数内置类型所实现，但也可以使用 @ref{db1,,addTypeEqualityFunc()} 来注册新的方法:

@geindex addTypeEqualityFunc() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase addTypeEqualityFunc}@anchor{db1}
@deffn {方法} addTypeEqualityFunc (typeobj, function)

注册一个由 @ref{c8d,,assertEqual()} 调用的特定类型专属方法来检查恰好为相同 @emph{typeobj} (而非子类) 的两个对象是否相等。 @emph{function} 必须接受两个位置参数和第三个 msg=None 关键字参数，就像 @ref{c8d,,assertEqual()} 那样。 当检测到前两个形参之间不相等时它必须引发 @ref{33c7,,self.failureException(msg)} -- 可能还会提供有用的信息并在错误消息中详细解释不相等的原因。


3.1 新版功能.

@end deffn

以下是 @ref{c8d,,assertEqual()} 自动选用的不同类型的比较方法。一般情况下不需要直接在测试中调用这些方法。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
@headitem

方法

@tab

用作比较

@tab

引入版本

@item

@ref{da7,,assertMultiLineEqual(a@comma{} b)}

@tab

字符串

@tab

3.1

@item

@ref{dad,,assertSequenceEqual(a@comma{} b)}

@tab

序列

@tab

3.1

@item

@ref{dab,,assertListEqual(a@comma{} b)}

@tab

列表

@tab

3.1

@item

@ref{dac,,assertTupleEqual(a@comma{} b)}

@tab

元组

@tab

3.1

@item

@ref{daa,,assertSetEqual(a@comma{} b)}

@tab

集合

@tab

3.1

@item

@ref{dae,,assertDictEqual(a@comma{} b)}

@tab

字典

@tab

3.1

@end multitable


@geindex assertMultiLineEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertMultiLineEqual}@anchor{da7}
@deffn {方法} assertMultiLineEqual (first, second, msg=None)

测试多行字符串 @emph{first} 是否与字符串 @emph{second} 相等。 当不相等时将在错误消息中包括两个字符串之间差异的高亮显示。 此方法会在通过 @ref{c8d,,assertEqual()} 进行字符串比较时默认被使用。


3.1 新版功能.

@end deffn

@geindex assertSequenceEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertSequenceEqual}@anchor{dad}
@deffn {方法} assertSequenceEqual (first, second, msg=None, seq_type=None)

测试两个序列是否相等。 如果提供了 @emph{seq_type}，则 @emph{first} 和 @emph{second} 都必须为 @emph{seq_type} 的实例否则将引发失败。 如果两个序列不相等则会构造一个错误消息来显示两者之间的差异。

此方法不会被 @ref{c8d,,assertEqual()} 直接调用，但它会被用于实现 @ref{dab,,assertListEqual()} 和 @ref{dac,,assertTupleEqual()}。


3.1 新版功能.

@end deffn

@geindex assertListEqual() (unittest.TestCase 方法)
@geindex assertTupleEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertListEqual}@anchor{dab}
@deffn {方法} assertListEqual (first, second, msg=None)
@anchor{library/unittest unittest TestCase assertTupleEqual}@anchor{dac}
@deffnx {方法} assertTupleEqual (first, second, msg=None)

测试两个列表或元组是否相等。 如果不相等，则会构造一个错误消息来显示两者之间的差异。 如果某个形参的类型不正确也会引发错误。 这些方法会在通过 @ref{c8d,,assertEqual()} 进行列表或元组比较时默认被使用。


3.1 新版功能.

@end deffn

@geindex assertSetEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertSetEqual}@anchor{daa}
@deffn {方法} assertSetEqual (first, second, msg=None)

测试两个集合是否相等。 如果不相等，则会构造一个错误消息来列出两者之间的差异。 此方法会在通过 @ref{c8d,,assertEqual()} 进行集合或冻结集合比较时默认被使用。

如果 @emph{first} 或 @emph{second} 没有 @code{set.difference()} 方法则测试失败。


3.1 新版功能.

@end deffn

@geindex assertDictEqual() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase assertDictEqual}@anchor{dae}
@deffn {方法} assertDictEqual (first, second, msg=None)

测试两个字典是否相等。 如果不相等，则会构造一个错误消息来显示两个字典的差异。 此方法会在对 @ref{c8d,,assertEqual()} 的调用中默认被用来进行字典的比较。


3.1 新版功能.

@end deffn
@anchor{library/unittest other-methods-and-attrs}@anchor{33c8}
最后 @ref{9ee,,TestCase} 还提供了以下的方法和属性:

@geindex fail() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase fail}@anchor{33c9}
@deffn {方法} fail (msg=None)

无条件地发出测试失败消息，附带错误消息 @emph{msg} 或 @code{None}。
@end deffn

@geindex failureException (unittest.TestCase 属性)
@anchor{library/unittest unittest TestCase failureException}@anchor{33c7}
@deffn {属性} failureException

这个类属性给出测试方法所引发的异常。 如果某个测试框架需要使用专门的异常，并可能附带额外的信息，则必须子类化该类以便与框架“正常互动”。 这个属性的初始值为 @ref{241,,AssertionError}。
@end deffn

@geindex longMessage (unittest.TestCase 属性)
@anchor{library/unittest unittest TestCase longMessage}@anchor{d98}
@deffn {属性} longMessage

这个类属性决定当将一个自定义失败消息作为 msg 参数传给一个失败的 assertXYY 调用时会发生什么。默认值为 @code{True}。 在此情况下，自定义消息会被添加到标准失败消息的末尾。 当设为 @code{False} 时，自定义消息会替换标准消息。

类设置可以通过在调用断言方法之前将一个实例属性 self.longMessage 赋值为 @code{True} 或 @code{False} 在单个测试方法中进行重载。

类设置会在每个测试调用之前被重置。


3.1 新版功能.

@end deffn

@geindex maxDiff (unittest.TestCase 属性)
@anchor{library/unittest unittest TestCase maxDiff}@anchor{c88}
@deffn {属性} maxDiff

这个属性控制来自在测试失败时报告 diffs 的断言方法的 diffs 输出的最大长度。 它默认为 80*8 个字符。 这个属性所影响的断言方法有 @ref{dad,,assertSequenceEqual()} (包括所有委托给它的序列比较方法), @ref{dae,,assertDictEqual()} 以及 @ref{da7,,assertMultiLineEqual()}。

将 @code{maxDiff} 设为 @code{None} 表示不限制 diffs 的最大长度。


3.2 新版功能.

@end deffn

测试框架可使用下列方法在测试时收集信息:

@geindex countTestCases() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase countTestCases}@anchor{33ca}
@deffn {方法} countTestCases ()

返回此测试对象所提供的测试数量。 对于 @ref{9ee,,TestCase} 实例，该数量将总是为 @code{1}。
@end deffn

@geindex defaultTestResult() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase defaultTestResult}@anchor{33c2}
@deffn {方法} defaultTestResult ()

返回此测试类所要使用的测试结果类的实例（如果未向 @ref{b9f,,run()} 方法提供其他结果实例）。

对于 @ref{9ee,,TestCase} 实例，该返回值将总是为 @ref{ba0,,TestResult} 的实例；@ref{9ee,,TestCase} 的子类应当在有必要时重载此方法。
@end deffn

@geindex id() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase id}@anchor{33cb}
@deffn {方法} id ()

返回一个标识指定测试用例的字符串。 该返回值通常为测试方法的完整名称，包括模块名和类名。
@end deffn

@geindex shortDescription() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase shortDescription}@anchor{33cc}
@deffn {方法} shortDescription ()

返回测试的描述，如果未提供描述则返回 @code{None}。 此方法的默认实现将在可用的情况下返回测试方法的文档字符串的第一行，或者返回 @code{None}。


在 3.1 版更改: 在 3.1 中已修改此方法将测试名称添加到简短描述中，即使存在文档字符串。 这导致了与单元测试扩展的兼容性问题因而在 Python 3.2 中将添加测试名称操作改到 @ref{f9d,,TextTestResult} 中。

@end deffn

@geindex addCleanup() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase addCleanup}@anchor{3cd}
@deffn {方法} addCleanup (function, /, *args, **kwargs)

在 @ref{d9c,,tearDown()} 之后添加了一个要调用的函数来清理测试期间所使用的资源。 函数将按它们被添加的相反顺序被调用 (@abbr{LIFO})。 它们在调用时将附带它们被添加时传给 @ref{3cd,,addCleanup()} 的任何参数和关键字参数。

如果 @ref{d9b,,setUp()} 失败，即意味着 @ref{d9c,,tearDown()} 未被调用，则已添加的任何清理函数仍将被调用。


3.1 新版功能.

@end deffn

@geindex doCleanups() (unittest.TestCase 方法)
@anchor{library/unittest unittest TestCase doCleanups}@anchor{d9a}
@deffn {方法} doCleanups ()

此方法会在 @ref{d9c,,tearDown()} 之后无条件地被调用，或者如果 @ref{d9b,,setUp()} 引发了异常则会在 @ref{d9b,,setUp()} 之后被调用。

它将负责调用由 @ref{3cd,,addCleanup()} 添加的所有清理函数。 如果你需要在 @ref{d9c,,tearDown()} @emph{之前} 调用清理函数则可以自行调用 @ref{d9a,,doCleanups()}。

@ref{d9a,,doCleanups()} 每次会弹出清理函数栈中的一个方法，因此它可以在任何时候被调用。


3.1 新版功能.

@end deffn

@geindex addClassCleanup() (unittest.TestCase 类方法)
@anchor{library/unittest unittest TestCase addClassCleanup}@anchor{37c}
@deffn {方法} classmethod addClassCleanup (function, /, *args, **kwargs)

在Add a function to be called after @ref{d99,,tearDownClass()} 之后添加了一个要调用的函数来清理测试类运行期间所使用的资源。 函数将按它们被添加的相反顺序被调用 (@abbr{LIFO})。 它们在调用时将附带它们被添加时传给 @ref{37c,,addClassCleanup()} 的任何参数和关键字参数。

如果 @ref{37d,,setUpClass()} 失败，即意味着 @ref{d99,,tearDownClass()} 未被调用，则已添加的任何清理函数仍将被调用。


3.8 新版功能.

@end deffn

@geindex doClassCleanups() (unittest.TestCase 类方法)
@anchor{library/unittest unittest TestCase doClassCleanups}@anchor{33cd}
@deffn {方法} classmethod doClassCleanups ()

此方法会在 @ref{d99,,tearDownClass()} 之后无条件地被调用，或者如果 @ref{37d,,setUpClass()} 引发了异常则会在 @ref{37d,,setUpClass()} 之后被调用。

它将负责访问由 @ref{37c,,addClassCleanup()} 添加的所有清理函数。 如果你需要在 @ref{d99,,tearDownClass()} @emph{之前} 调用清理函数则可以自行调用 @ref{33cd,,doClassCleanups()}。

@ref{33cd,,doClassCleanups()} 每次会弹出清理函数栈中的一个方法，因此它在任何时候被调用。


3.8 新版功能.

@end deffn
@end deffn

@geindex IsolatedAsyncioTestCase (unittest 中的类)
@anchor{library/unittest unittest IsolatedAsyncioTestCase}@anchor{37e}
@deffn {类} unittest.IsolatedAsyncioTestCase (methodName='runTest')

这个类提供了与 @ref{9ee,,TestCase} 类似的 API 并也接受协程作为测试函数。


3.8 新版功能.


@geindex asyncSetUp() (unittest.IsolatedAsyncioTestCase 方法)
@anchor{library/unittest unittest IsolatedAsyncioTestCase asyncSetUp}@anchor{33ce}
@deffn {方法} coroutine asyncSetUp ()

为测试预备而调用的方法。 此方法会在 @code{setUp()} 之后被调用。 此方法将在调用测试方法之前立即被调用；除了 @ref{241,,AssertionError} 或 @ref{9f2,,SkipTest}，此方法所引发的任何异常都将被视为错误而非测试失败。 默认的实现将不做任何事情。
@end deffn

@geindex asyncTearDown() (unittest.IsolatedAsyncioTestCase 方法)
@anchor{library/unittest unittest IsolatedAsyncioTestCase asyncTearDown}@anchor{33cf}
@deffn {方法} coroutine asyncTearDown ()

在测试方法被调用并记录结果之后立即被调用的方法。 此方法会在 @code{tearDown()} 之前被调用。 此方法即使在测试方法引发异常时仍会被调用，因此子类中的实现将需要特别注意检查内部状态。 除 @ref{241,,AssertionError} 或 @ref{9f2,,SkipTest} 外，此方法所引发的任何异常都将被视为额外的错误而非测试失败（因而会增加总计错误报告数）。 此方法将只在 @ref{33ce,,asyncSetUp()} 成功执行时被调用，无论测试方法的结果如何。 默认的实现将不做任何事情。
@end deffn

@geindex addAsyncCleanup() (unittest.IsolatedAsyncioTestCase 方法)
@anchor{library/unittest unittest IsolatedAsyncioTestCase addAsyncCleanup}@anchor{33d0}
@deffn {方法} addAsyncCleanup (function, /, *args, **kwargs)

此方法接受一个可被用作清理函数的协程。
@end deffn

@geindex run() (unittest.IsolatedAsyncioTestCase 方法)
@anchor{library/unittest unittest IsolatedAsyncioTestCase run}@anchor{33d1}
@deffn {方法} run (result=None)

设置一个新的事件循环来运行测试，将结果收集至作为 @emph{result} 传入的 @ref{ba0,,TestResult}。 如果 @emph{result} 被省略或为 @code{None}，则会创建一个临时的结果对象（通过调用 @code{defaultTestResult()} 方法）并使用它。 结果对象会被返回给 @ref{33d1,,run()} 的调用方。 在测试结束时事件循环中的所有任务都将被取消。
@end deffn

一个显示先后顺序的例子:

@example
from unittest import IsolatedAsyncioTestCase

events = []


class Test(IsolatedAsyncioTestCase):


    def setUp(self):
        events.append("setUp")

    async def asyncSetUp(self):
        self._async_connection = await AsyncConnection()
        events.append("asyncSetUp")

    async def test_response(self):
        events.append("test_response")
        response = await self._async_connection.get("https://example.com")
        self.assertEqual(response.status_code, 200)
        self.addAsyncCleanup(self.on_cleanup)

    def tearDown(self):
        events.append("tearDown")

    async def asyncTearDown(self):
        await self._async_connection.close()
        events.append("asyncTearDown")

    async def on_cleanup(self):
        events.append("cleanup")

if __name__ == "__main__":
    unittest.main()
@end example

在运行测试之后，@code{events} 将会包含 @code{["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"]}。
@end deffn

@geindex FunctionTestCase (unittest 中的类)
@anchor{library/unittest unittest FunctionTestCase}@anchor{33b3}
@deffn {类} unittest.FunctionTestCase (testFunc, setUp=None, tearDown=None, description=None)

这个类实现了 @ref{9ee,,TestCase} 的部分接口，允许测试运行方驱动测试，但不提供可被测试代码用来检查和报告错误的方法。 这个类被用于创建使用传统测试代码的测试用例，允许它被集成到基于 @ref{124,,unittest} 的测试框架中。
@end deffn

@menu
* 已弃用的别名:: 

@end menu

@node 已弃用的别名,,,测试用例
@anchor{library/unittest deprecated-aliases}@anchor{c91}@anchor{library/unittest id1}@anchor{33d2}
@subsubsection 已弃用的别名


由于历史原因，某些 @ref{9ee,,TestCase} 方法具有一个或几个已目前已弃用的别名。 下表列出了它们的正确名称和已弃用的别名:

@quotation


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

方法名

@tab

已弃用的别名

@tab

已弃用的别名

@item

@ref{c8d,,assertEqual()}

@tab

failUnlessEqual

@tab

assertEquals

@item

@ref{c8e,,assertNotEqual()}

@tab

failIfEqual

@tab

assertNotEquals

@item

@ref{c8c,,assertTrue()}

@tab

failUnless

@tab

assert_

@item

@ref{d97,,assertFalse()}

@tab

failIf

@tab

@item

@ref{b9b,,assertRaises()}

@tab

failUnlessRaises

@tab

@item

@ref{c8f,,assertAlmostEqual()}

@tab

failUnlessAlmostEqual

@tab

assertAlmostEquals

@item

@ref{c90,,assertNotAlmostEqual()}

@tab

failIfAlmostEqual

@tab

assertNotAlmostEquals

@item

@ref{c89,,assertRegex()}

@tab

@tab

assertRegexpMatches

@item

@ref{33c6,,assertNotRegex()}

@tab

@tab

assertNotRegexpMatches

@item

@ref{b9c,,assertRaisesRegex()}

@tab

@tab

assertRaisesRegexp

@end multitable



3.1 版后已移除: 在第二列中列出的 fail* 别名已经被弃用。



3.2 版后已移除: 在第三列中列出的 assert* 别名已经被弃用。



3.2 版后已移除: @code{assertRegexpMatches} 和 @code{assertRaisesRegexp} 已经被重命名为 @ref{c89,,assertRegex()} 和 @ref{b9c,,assertRaisesRegex()}。



3.5 版后已移除: @code{assertNotRegexpMatches} 这个名称已被弃用并应改用 @ref{33c6,,assertNotRegex()}。

@end quotation

@node 分组测试,加载和运行测试,测试用例,类与函数
@anchor{library/unittest grouping-tests}@anchor{33d3}@anchor{library/unittest testsuite-objects}@anchor{33d4}
@subsubsection 分组测试


@geindex TestSuite (unittest 中的类)
@anchor{library/unittest unittest TestSuite}@anchor{7cb}
@deffn {类} unittest.TestSuite (tests=())

这个类代表对单独测试用例和测试套件的聚合。 这个类提供给测试运行方所需的接口以允许其像任何其他测试用例一样运行。 运行一个 @ref{7cb,,TestSuite} 实例与对套件执行迭代来逐一运行每个测试的效果相同。

如果给出了 @emph{tests}，则它必须是一个包含单独测试用例的可迭代对象或是将被用于初始构建测试套件的其他测试套件。 额外的方法被提供用来在随后向测试集添加测试用例和测试套件。

@ref{7cb,,TestSuite} 对象的行为与 @ref{9ee,,TestCase} 对象很相似，区别在于它们并不会真正实现一个测试。 它们会被用来将测试聚合为多个要同时运行的测试分组。 还有一些额外的方法会被用来向 @ref{7cb,,TestSuite} 实例添加测试:

@geindex addTest() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite addTest}@anchor{33d5}
@deffn {方法} addTest (test)

向测试套件添加 @ref{9ee,,TestCase} 或 @ref{7cb,,TestSuite}。
@end deffn

@geindex addTests() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite addTests}@anchor{33d6}
@deffn {方法} addTests (tests)

将来自包含 @ref{9ee,,TestCase} 和 @ref{7cb,,TestSuite} 实例的可迭代对象的所有测试添加到这个测试套件。

这等价于对 @emph{tests} 进行迭代，并为其中的每个元素调用 @ref{33d5,,addTest()}。
@end deffn

@ref{7cb,,TestSuite} 与 @ref{9ee,,TestCase} 共享下列方法:

@geindex run() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite run}@anchor{33d7}
@deffn {方法} run (result)

运行与这个套件相关联的测试，将结果收集到作为 @emph{result} 传入的测试结果对象中。 请注意与 @ref{b9f,,TestCase.run()} 的区别，@ref{33d7,,TestSuite.run()} 必须传入结果对象。
@end deffn

@geindex debug() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite debug}@anchor{33d8}
@deffn {方法} debug ()

运行与这个套件相关联的测试而不收集结果。 这允许测试所引发的异常被传递给调用方并可被用于支持在调试器中运行测试。
@end deffn

@geindex countTestCases() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite countTestCases}@anchor{33d9}
@deffn {方法} countTestCases ()

返回此测试对象所提供的测试数量，包括单独的测试和子套件。
@end deffn

@geindex __iter__() (unittest.TestSuite 方法)
@anchor{library/unittest unittest TestSuite __iter__}@anchor{a4c}
@deffn {方法} __iter__ ()

由 @ref{7cb,,TestSuite} 分组的测试总是可以通过迭代来访问。 其子类可以通过重载 @ref{a4c,,__iter__()} 来惰性地提供测试。 请注意此方法可在单个套件上多次被调用（例如在计数测试或相等性比较时），为此在 @ref{33d7,,TestSuite.run()} 之前重复迭代所返回的测试对于每次调用迭代都必须相同。 在 @ref{33d7,,TestSuite.run()} 之后，调用方不应继续访问此方法所返回的测试，除非调用方使用重载了 @code{TestSuite._removeTestAtIndex()} 的子类来保留对测试的引用。


在 3.2 版更改: 在较早的版本中 @ref{7cb,,TestSuite} 会直接访问测试而不是通过迭代，因此只重载 @ref{a4c,,__iter__()} 并不足以提供所有测试。



在 3.4 版更改: 在较早的版本中 @ref{7cb,,TestSuite} 会在 @ref{33d7,,TestSuite.run()} 之后保留对每个 @ref{9ee,,TestCase} 的引用。 其子类可以通过重载 @code{TestSuite._removeTestAtIndex()} 来恢复此行为。

@end deffn

在 @ref{7cb,,TestSuite} 对象的典型应用中，@ref{33d7,,run()} 方法是由 @code{TestRunner} 发起调用而不是由最终用户测试来控制。
@end deffn

@node 加载和运行测试,,分组测试,类与函数
@anchor{library/unittest loading-and-running-tests}@anchor{33da}
@subsubsection 加载和运行测试


@geindex TestLoader (unittest 中的类)
@anchor{library/unittest unittest TestLoader}@anchor{87b}
@deffn {类} unittest.TestLoader

@ref{87b,,TestLoader} 类可被用来基于类和模块创建测试套件。 通常，没有必要创建该类的实例；@ref{124,,unittest} 模块提供了一个可作为 @ref{33db,,unittest.defaultTestLoader} 共享的实例。 但是，使用子类或实例允许对某些配置属性进行定制。

@ref{87b,,TestLoader} 对象具有下列属性:

@geindex errors (unittest.TestLoader 属性)
@anchor{library/unittest unittest TestLoader errors}@anchor{87a}
@deffn {属性} errors

包含在加载测试期间遇到的非致命错误的列表。 在任何时候都不会被加载方重置。 致命错误是通过相关方法引发一个异常来向调用方发出信号的。 非致命错误也是由一个将在运行时引发原始错误的合成测试来提示的。


3.5 新版功能.

@end deffn

@ref{87b,,TestLoader} 对象具有下列方法:

@geindex loadTestsFromTestCase() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader loadTestsFromTestCase}@anchor{33dc}
@deffn {方法} loadTestsFromTestCase (testCaseClass)

返回一个包含在 @ref{9ee,,TestCase} 所派生的 @code{testCaseClass} 中的所有测试用例的测试套件。

会为每个由 @ref{33dd,,getTestCaseNames()} 指明的方法创建一个测试用例实例。 在默认情况下这些都是以 @code{test} 开头的方法名称。 如果 @ref{33dd,,getTestCaseNames()} 不返回任何方法，但 @code{runTest()} 方法已被实现，则会为该方法创建一个单独的测试用例。
@end deffn

@geindex loadTestsFromModule() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader loadTestsFromModule}@anchor{879}
@deffn {方法} loadTestsFromModule (module, pattern=None)

返回包含在给定模块中的所有测试用例的测试套件。 此方法会在 @emph{module} 中搜索从派生自 @ref{9ee,,TestCase} 的类并为该类定义的每个测试方法创建一个类实例。

@cartouche
@quotation 注解 
虽然使用 @ref{9ee,,TestCase} 所派生的类的层级结构可以方便地共享配置和辅助函数，但在不打算直接实例化的基类上定义测试方法并不能很好地配合此方法使用。 不过，当配置有差异并且定义在子类当中时这样做还是有用处的。
@end quotation
@end cartouche

如果一个模块提供了 @code{load_tests} 函数则它将被调用以加载测试。 这允许模块自行定制测试加载过程。 这就称为 @ref{33b1,,load_tests protocol}。 @emph{pattern} 参数会被作为传给 @code{load_tests} 的第三个参数。


在 3.2 版更改: 添加了对 @code{load_tests} 的支持。



在 3.5 版更改: 未写入文档的非官方 @emph{use_load_tests} 默认参数已被弃用并忽略，但是它仍然被接受以便向下兼容。 此方法现在还接受一个仅限关键字参数 @emph{pattern}，它会被作为传给 @code{load_tests} 的第三个参数。

@end deffn

@geindex loadTestsFromName() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader loadTestsFromName}@anchor{daf}
@deffn {方法} loadTestsFromName (name, module=None)

返回由给出了字符串形式规格描述的所有测试用例组成的测试套件。

描述名称 @emph{name} 是一个“带点号的名称”，它可以被解析为一个模块、一个测试用例类、一个测试用例类内部的测试方法、一个 @ref{7cb,,TestSuite} 实例，或者一个返回 @ref{9ee,,TestCase} 或 @ref{7cb,,TestSuite} 实例的可调用对象。 这些检查将按在此列出的顺序执行；也就是说，一个可能的测试用例类上的方法将作为“一个测试用例内部的测试方法”而非作为“一个可调用对象”被选定。

举例来说，如果你有一个模块 @code{SampleTests}，其中包含一个派生自 @ref{9ee,,TestCase} 的类 @code{SampleTestCase}，其中包含三个测试方法 (@code{test_one()}, @code{test_two()} 和 @code{test_three()})。 则描述名称 @code{'SampleTests.SampleTestCase'} 将使此方法返回一个测试套件，它将运行全部三个测试方法。 使用描述名称 @code{'SampleTests.SampleTestCase.test_two'} 将使它返回一个测试套件，它将仅运行 @code{test_two()} 测试方法。 描述名称可以指向尚未被导入的模块和包；它们将作为附带影响被导入。

本模块可以选择相对于给定的 @emph{module} 来解析 @emph{name}。


在 3.5 版更改: 如果在遍历 @emph{name} 时发生了 @ref{16c,,ImportError} 或 @ref{4aa,,AttributeError} 则在运行时引发该错误的合成测试将被返回。 这些错误被包括在由 self.errors 所积累的错误中。

@end deffn

@geindex loadTestsFromNames() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader loadTestsFromNames}@anchor{33de}
@deffn {方法} loadTestsFromNames (names, module=None)

类似于 @ref{daf,,loadTestsFromName()}，但是接受一个名称序列而不是单个名称。 返回值是一个测试套件，它支持为每个名称所定义的所有测试。
@end deffn

@geindex getTestCaseNames() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader getTestCaseNames}@anchor{33dd}
@deffn {方法} getTestCaseNames (testCaseClass)

返回由 @emph{testCaseClass} 中找到的方法名称组成的已排序的序列；这应当是 @ref{9ee,,TestCase} 的一个子类。
@end deffn

@geindex discover() (unittest.TestLoader 方法)
@anchor{library/unittest unittest TestLoader discover}@anchor{9f3}
@deffn {方法} discover (start_dir, pattern='test*.py', top_level_dir=None)

通过从指定的开始目录向其子目录递归来找出所有测试模块，并返回一个包含该结果的 TestSuite 对象。 只有与 @emph{pattern} 匹配的测试文件才会被加载。 （使用 shell 风格的模式匹配。） 只有可导入的模块名称（即有效的 Python 标识符）将会被加载。

所有测试模块都必须可以从项目的最高层级上导入。 如果起始目录不是最高层级目录则必须单独指明最高层级目录。

如果导入某个模块失败，比如因为存在语法错误，则会将其记录为单独的错误并将继续查找模块。 如果导入失败是因为引发了 @ref{9f2,,SkipTest}，则会将其记录为跳过而不是错误。

如果找到了一个包（即包含名为 @code{__init__.py} 的文件的目录），则将在包中查找 @code{load_tests} 函数。 如果存在此函数则将对其执行调用 @code{package.load_tests(loader, tests, pattern)}。 测试发现操作会确保在执行期间仅检查测试一次，即使 load_tests 函数本身调用了 @code{loader.discover} 也是如此。.

如果 @code{load_tests} 存在则发现操作 @emph{不会} 对包执行递归处理，@code{load_tests} 将负责加载包中的所有测试。is responsible for loading all tests in the package.

模式特意地不被当作 loader 属性来保存以使包能够自己继续执行发现操作。 @emph{top_level_dir} 则会被保存以使 @code{load_tests} 不需要将此参数传入到 @code{loader.discover()}。

@emph{start_dir} 可以是一个带点号的名称或是一个目录。


3.2 新版功能.



在 3.4 版更改: 在导入时引发 @ref{9f2,,SkipTest} 的模块会被记录为跳过，而不是错误。



在 3.4 版更改: @emph{start_dir} 可以是一个 @ref{161d,,命名空间包}。



在 3.4 版更改: 路径在被导入之前会先被排序以使得执行顺序保持一致，即使下层文件系统的顺序不是取决于文件名的。



在 3.5 版更改: 现在 @code{load_tests} 会检查已找到的包，无论它们的路径是否与 @emph{pattern} 匹配，因为包名称是无法与默认的模式匹配的。

@end deffn

@ref{87b,,TestLoader} 的下列属性可通过子类化或在实例上赋值来配置:

@geindex testMethodPrefix (unittest.TestLoader 属性)
@anchor{library/unittest unittest TestLoader testMethodPrefix}@anchor{33df}
@deffn {属性} testMethodPrefix

给出将被解读为测试方法的方法名称的前缀的字符串。 默认值为 @code{'test'}。

这会影响 @ref{33dd,,getTestCaseNames()} 以及所有 @code{loadTestsFrom*()} 方法。
@end deffn

@geindex sortTestMethodsUsing (unittest.TestLoader 属性)
@anchor{library/unittest unittest TestLoader sortTestMethodsUsing}@anchor{33e0}
@deffn {属性} sortTestMethodsUsing

将被用来在 @ref{33dd,,getTestCaseNames()} 以及所有 @code{loadTestsFrom*()} 方法中比较方法名称以便对它们进行排序。
@end deffn

@geindex suiteClass (unittest.TestLoader 属性)
@anchor{library/unittest unittest TestLoader suiteClass}@anchor{db0}
@deffn {属性} suiteClass

根据一个测试列表来构造测试套件的可调用对象。 不需要结果对象上的任何方法。 默认值为 @ref{7cb,,TestSuite} 类。

这会影响所有 @code{loadTestsFrom*()} 方法。
@end deffn

@geindex testNamePatterns (unittest.TestLoader 属性)
@anchor{library/unittest unittest TestLoader testNamePatterns}@anchor{33e1}
@deffn {属性} testNamePatterns

由 Unix shell 风格通配符的测试名称模式组成的列表，供测试方法进行匹配以包括在测试套件中（参见 @code{-v} 选项）。

如果该属性不为 @code{None} (默认值)，则将要包括在测试套件中的所有测试方法都必须匹配该列表中的某个模式。 请注意匹配总是使用 @ref{1e21,,fnmatch.fnmatchcase()} 来执行，因此不同于传给 @code{-v} 选项的模式，简单的子字符串模式将必须使用 @code{*} 通配符来进行转换。

这会影响所有 @code{loadTestsFrom*()} 方法。


3.7 新版功能.

@end deffn
@end deffn

@geindex TestResult (unittest 中的类)
@anchor{library/unittest unittest TestResult}@anchor{ba0}
@deffn {类} unittest.TestResult

这个类被用于编译有关哪些测试执行成功而哪些失败的信息。

存放一组测试的结果的 @ref{ba0,,TestResult} 对象。 @ref{9ee,,TestCase} 和 @ref{7cb,,TestSuite} 类将确保结果被正确地记录；测试创建者无须担心如何记录测试的结果。

建立在 @ref{124,,unittest} 之上的测试框架可能会想要访问通过运行一组测试所产生的 @ref{ba0,,TestResult} 对象用来报告信息；@code{TestRunner.run()} 方法是出于这个目的而返回 @ref{ba0,,TestResult} 实例的。

@ref{ba0,,TestResult} 实例具有下列属性，在检查运行一组测试的结果的时候很有用处。

@geindex errors (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult errors}@anchor{33e2}
@deffn {属性} errors

一个包含 @ref{9ee,,TestCase} 实例和保存了格式化回溯信息的字符串 2 元组的列表。 每个元组代表一个引发了非预期的异常的测试。
@end deffn

@geindex failures (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult failures}@anchor{33e3}
@deffn {属性} failures

一个包含 @ref{9ee,,TestCase} 实例和保存了格式化回溯信息的字符串 2 元组的列表。 每个元组代表一个使用 @code{TestCase.assert*()} 方法显式地发出失败信号的测试。
@end deffn

@geindex skipped (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult skipped}@anchor{33e4}
@deffn {属性} skipped

一个包含 2-tuples of @ref{9ee,,TestCase} 实例和保存了跳过测试原因的字符串 2 元组的列表。


3.1 新版功能.

@end deffn

@geindex expectedFailures (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult expectedFailures}@anchor{33e5}
@deffn {属性} expectedFailures

一个包含 @ref{9ee,,TestCase} 实例和保存了格式化回溯信息的 2 元组的列表。 每个元组代表测试用例的一个已预期的失败或错误。
@end deffn

@geindex unexpectedSuccesses (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult unexpectedSuccesses}@anchor{33e6}
@deffn {属性} unexpectedSuccesses

一个包含被标记为已预期失败，但却测试成功的 @ref{9ee,,TestCase} 实例的列表。
@end deffn

@geindex shouldStop (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult shouldStop}@anchor{33e7}
@deffn {属性} shouldStop

当测试的执行应当被 @ref{33e8,,stop()} 停止时则设为 @code{True}。
@end deffn

@geindex testsRun (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult testsRun}@anchor{33e9}
@deffn {属性} testsRun

目前已运行的测试的总数量。
@end deffn

@geindex buffer (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult buffer}@anchor{33ea}
@deffn {属性} buffer

如果设为真值，@code{sys.stdout} 和 @code{sys.stderr} 将在 @ref{33eb,,startTest()} 和 @ref{33ec,,stopTest()} 被调用之间被缓冲。 被收集的输出将仅在测试失败或发生错误时才会被回显到真正的 @code{sys.stdout} 和 @code{sys.stderr}。 任何输出还会被附加到失败/错误消息中。


3.2 新版功能.

@end deffn

@geindex failfast (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult failfast}@anchor{33ed}
@deffn {属性} failfast

如果设为真值则 @ref{33e8,,stop()} 将在首次失败或错误时被调用，停止测试运行。


3.2 新版功能.

@end deffn

@geindex tb_locals (unittest.TestResult 属性)
@anchor{library/unittest unittest TestResult tb_locals}@anchor{33ee}
@deffn {属性} tb_locals

如果设为真值则局部变量将被显示在回溯信息中。


3.5 新版功能.

@end deffn

@geindex wasSuccessful() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult wasSuccessful}@anchor{33ef}
@deffn {方法} wasSuccessful ()

如果当前所有测试都已通过则返回 @code{True}，否则返回 @code{False}。


在 3.4 版更改: 如果有任何来自测试的 @ref{33e6,,unexpectedSuccesses} 被 @ref{33b9,,expectedFailure()} 装饰器所标记则返回 @code{False}。

@end deffn

@geindex stop() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult stop}@anchor{33e8}
@deffn {方法} stop ()

此方法可被调用以提示正在运行的测试集要将 @ref{33e7,,shouldStop} 属性设为 @code{True} 来表示其应当被中止。 @code{TestRunner} 对象应当认同此旗标并返回而不再运行任何额外的测试。

例如，该特性会被 @ref{f9e,,TextTestRunner} 类用来在当用户从键盘发出一个中断信号时停止测试框架。 提供了 @code{TestRunner} 实现的交互式工具也可通过类似方式来使用该特性。
@end deffn

@ref{ba0,,TestResult} 类的下列方法被用于维护内部数据结构，并可在子类中被扩展以支持额外的报告需求。 这特别适用于构建支持在运行测试时提供交互式报告的工具。

@geindex startTest() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult startTest}@anchor{33eb}
@deffn {方法} startTest (test)

当测试用例 @emph{test} 即将被运行时被调用。
@end deffn

@geindex stopTest() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult stopTest}@anchor{33ec}
@deffn {方法} stopTest (test)

在测试用例 @emph{test} 已经执行后被调用，无论其结果如何。
@end deffn

@geindex startTestRun() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult startTestRun}@anchor{db3}
@deffn {方法} startTestRun ()

在任何测试被执行之前被调用一次。


3.1 新版功能.

@end deffn

@geindex stopTestRun() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult stopTestRun}@anchor{db4}
@deffn {方法} stopTestRun ()

在所有测试被执行之后被调用一次。


3.1 新版功能.

@end deffn

@geindex addError() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addError}@anchor{33f0}
@deffn {方法} addError (test, err)

当测试用例 @emph{test} 引发了非预期的异常时被调用。 @emph{err} 是一个元组，其形式与 @ref{d2f,,sys.exc_info()} 的返回值相同: @code{(type, value, traceback)}。

默认实现会将一个元组 @code{(test, formatted_err)} 添加到实例的 @ref{33e2,,errors} 属性，其中 @emph{formatted_err} 是派生自 @emph{err} 的已格式化回溯信息。
@end deffn

@geindex addFailure() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addFailure}@anchor{33f1}
@deffn {方法} addFailure (test, err)

当测试用例 @emph{test} 发出了失败信号时将被调用。 @emph{err} 是一个元组，其形式与 @ref{d2f,,sys.exc_info()} 的返回值相同: @code{(type, value, traceback)}。

默认实现会将一个元组 @code{(test, formatted_err)} 添加到实例的 @ref{33e3,,failures} 属性，其中 @emph{formatted_err} 是派生自 @emph{err} 的已格式化回溯信息。
@end deffn

@geindex addSuccess() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addSuccess}@anchor{33f2}
@deffn {方法} addSuccess (test)

当测试用例 @emph{test} 成功时被调用。

默认实现将不做任何操作。
@end deffn

@geindex addSkip() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addSkip}@anchor{33f3}
@deffn {方法} addSkip (test, reason)

当测试用例 @emph{test} 被跳过时将被调用。 @emph{reason} 是给出的跳过测试的理由。

默认实现会将一个元组 @code{(test, reason)} 添加到实例的 @ref{33e4,,skipped} 属性。
@end deffn

@geindex addExpectedFailure() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addExpectedFailure}@anchor{33f4}
@deffn {方法} addExpectedFailure (test, err)

当测试用例 @emph{test} 失败或发生错误，但是使用了 @ref{33b9,,expectedFailure()} 装饰器来标记时将被调用。

默认实现会将一个元组 @code{(test, formatted_err)} 添加到实例的 @ref{33e5,,expectedFailures} 属性，其中 @emph{formatted_err} 是派生自 @emph{err} 的已格式化回溯信息。
@end deffn

@geindex addUnexpectedSuccess() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addUnexpectedSuccess}@anchor{33f5}
@deffn {方法} addUnexpectedSuccess (test)

当测试用例 @emph{test} 使用了was marked with the @ref{33b9,,expectedFailure()} 装饰器来标记，但是却执行成功时将被调用。

默认实现会将该测试添加到实例的 @ref{33e6,,unexpectedSuccesses} 属性。
@end deffn

@geindex addSubTest() (unittest.TestResult 方法)
@anchor{library/unittest unittest TestResult addSubTest}@anchor{33f6}
@deffn {方法} addSubTest (test, subtest, outcome)

当一个子测试结束时将被调用。 @emph{test} 是对应于该测试方法的测试用例。 @emph{subtest} 是一个描述该子测试的 @ref{9ee,,TestCase} 实例。

如果 @emph{outcome} 为 @ref{204,,None}，则该子测试执行成功。 否则，它将失败并引发一个异常，@emph{outcome} 是一个元组，其形式与 @ref{d2f,,sys.exc_info()} 的返回值相同: @code{(type, value, traceback)}。

默认实现在测试结果为成功时将不做任何事，并会将子测试的失败记录为普通的失败。


3.4 新版功能.

@end deffn
@end deffn

@geindex TextTestResult (unittest 中的类)
@anchor{library/unittest unittest TextTestResult}@anchor{f9d}
@deffn {类} unittest.TextTestResult (stream, descriptions, verbosity)

@ref{ba0,,TestResult} 的一个具体实现，由 @ref{f9e,,TextTestRunner} 使用。


3.2 新版功能: 这个类在之前被命名为 @code{_TextTestResult}。 这个旧名字仍然作为别名存在，但已被弃用。

@end deffn

@geindex defaultTestLoader() (在 unittest 模块中)
@anchor{library/unittest unittest defaultTestLoader}@anchor{33db}
@deffn {数据} unittest.defaultTestLoader

用于分享的 @ref{87b,,TestLoader} 类实例。 如果不需要自制 @ref{87b,,TestLoader}，则可以使用该实例而不必重复创建新的实例。
@end deffn

@geindex TextTestRunner (unittest 中的类)
@anchor{library/unittest unittest TextTestRunner}@anchor{f9e}
@deffn {类} unittest.TextTestRunner (stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False)

一个将结果输出到流的基本测试运行器。 如果 @emph{stream} 为默认的 @code{None}，则会使用 @ref{1eb,,sys.stderr} 作为输出流。 这个类具有一些配置形参，但实际上都非常简单。 运行测试套件的图形化应用程序应当提供替代实现。 这样的实现应当在添加新特性到 unittest 时接受 @code{**kwargs} 作为修改构造运行器的接口。

在默认情况下这个运行器会显示 @ref{15a,,DeprecationWarning}, @ref{15c,,PendingDeprecationWarning}, @ref{5d3,,ResourceWarning} 和 @ref{6d9,,ImportWarning}，即使它们 @ref{33f7,,被默认忽略}。 由 @ref{c91,,deprecated unittest methods} 所导致的弃用警告也会被作为特例，并且当警告过滤器为 @code{'default'} 或 @code{'always'} 时，对于每个模块它们将仅显示一次，以避免过多的警告消息。 此种行为可使用 Python 的 @code{-Wd} 或 @code{-Wa} 选项 (参见 @ref{14ad,,警告控制}) 并让 @emph{warnings} 保持为 @code{None} 来覆盖。


在 3.2 版更改: 增加了 @code{warnings} 参数。



在 3.2 版更改: 默认流会在实例化而不是在导入时被设为 @ref{1eb,,sys.stderr}。



在 3.5 版更改: 增加了 tb_locals 形参。


@geindex _makeResult() (unittest.TextTestRunner 方法)
@anchor{library/unittest unittest TextTestRunner _makeResult}@anchor{33f8}
@deffn {方法} _makeResult ()

此方法将返回由 @ref{33f9,,run()} 使用的 @code{TestResult} 实例。 它不应当被直接调用，但可在子类中被重载以提供自定义的 @code{TestResult}。

@code{_makeResult()} 会实例化传给 @code{TextTestRunner} 构造器的 @code{resultclass} 参数所指定的类或可迭代对象。 如果没有提供 @code{resultclass} 则默认为 @ref{f9d,,TextTestResult}。 结果类会使用以下参数来实例化:

@example
stream, descriptions, verbosity
@end example
@end deffn

@geindex run() (unittest.TextTestRunner 方法)
@anchor{library/unittest unittest TextTestRunner run}@anchor{33f9}
@deffn {方法} run (test)

此方法是 @code{TextTestRunner} 的主要公共接口。 此方法接受一个 @ref{7cb,,TestSuite} 或 @ref{9ee,,TestCase} 实例。 通过调用 @ref{33f8,,_makeResult()} 创建 @ref{ba0,,TestResult} 来运行测试并将结果打印到标准输出。
@end deffn
@end deffn

@geindex main() (在 unittest 模块中)
@anchor{library/unittest unittest main}@anchor{9f1}
@deffn {函数} unittest.main (module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)

从 @emph{module} 加载一组测试并运行它们的命令行程序；这主要是为了让测试模块能方便地执行。 此函数的最简单用法是在测试脚本末尾包括下列行:

@example
if __name__ == '__main__':
    unittest.main()
@end example

你可以通过传入冗余参数运行测试以获得更详细的信息:

@example
if __name__ == '__main__':
    unittest.main(verbosity=2)
@end example

@emph{defaultTest} 参数是要运行的单个测试名称，或者如果未通过 @emph{argv} 指定任何测试名称则是包含多个测试名称的可迭代对象。 如果未指定或为 @code{None} 且未通过 @emph{argv} 指定任何测试名称，则会运行在 @emph{module} 中找到的所有测试。

@emph{argv} 参数可以是传给程序的选项列表，其中第一个元素是程序名。 如未指定或为 @code{None}，则会使用 @ref{cce,,sys.argv} 的值。

@emph{testRunner} 参数可以是测试运行器类或是其已创建的实例。 在默认情况下 @code{main} 会调用 @ref{db2,,sys.exit()} 并附带一个退出码来指明测试运行是成功还是失败。

@emph{testLoader} 参数必须是一个 @ref{87b,,TestLoader} 实例，其默认值为 @ref{33db,,defaultTestLoader}。

@code{main} 支持通过传入 @code{exit=False} 参数以便在交互式解释器中使用。 这将在标准输出中显示结果而不调用 @ref{db2,,sys.exit()}:

@example
>>> from unittest import main
>>> main(module='test_module', exit=False)
@end example

@emph{failfast}, @emph{catchbreak} 和 @emph{buffer} 形参的效果与同名的 @ref{33a8,,command-line options} 一致。

@emph{warnings} 参数指定在运行测试时所应使用的 @ref{15d,,警告过滤器}。 如果未指定，则默认的 @code{None} 会在将 @code{-W} 选项传给 @code{python} 命令时被保留 (参见 @ref{14ad,,警告控制})，而在其他情况下将被设为 @code{'default'}。

调用 @code{main} 实际上将返回一个 @code{TestProgram} 类的实例。 这会把测试运行结果保存为 @code{result} 属性。


在 3.1 版更改: 增加了 @emph{exit} 形参。



在 3.2 版更改: 增加了 @emph{verbosity}, @emph{failfast}, @emph{catchbreak}, @emph{buffer} 和 @emph{warnings} 形参。



在 3.4 版更改: @emph{defaultTest} 形参被修改为也接受一个由测试名称组成的迭代器。

@end deffn

@menu
* load_tests 协议:: 

@end menu

@node load_tests 协议,,,加载和运行测试
@anchor{library/unittest load-tests-protocol}@anchor{33b1}
@subsubsection load_tests 协议



3.2 新版功能.


模块或包可以通过实现一个名为 @code{load_tests} 的函数来定制在正常测试运行或测试发现期间要如何从中加载测试。

如果一个测试模块定义了 @code{load_tests} 则它将被 @ref{879,,TestLoader.loadTestsFromModule()} 调用并传入下列参数:

@example
load_tests(loader, standard_tests, pattern)
@end example

其中 @emph{pattern} 会通过 @code{loadTestsFromModule} 传入。 它的默认值为 @code{None}。

它应当返回一个 @ref{7cb,,TestSuite}。

@emph{loader} 是执行载入操作的 @ref{87b,,TestLoader} 实例。 @emph{standard_tests} 是默认要从该模块载入的测试。 测试模块通常只需从标准测试集中添加或移除测试。 第三个参数是在作为测试发现的一部分载入包时使用的。

一个从指定 @ref{9ee,,TestCase} 类集合中载入测试的 @code{load_tests} 函数看起来可能是这样的:

@example
test_cases = (TestCase1, TestCase2, TestCase3)

def load_tests(loader, tests, pattern):
    suite = TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
        suite.addTests(tests)
    return suite
@end example

如果发现操作是在一个包含包的目录中开始的，不论是通过命令行还是通过调用 @ref{9f3,,TestLoader.discover()}，则将在包 @code{__init__.py} 中检查 @code{load_tests}。 如果不存在此函数，则发现将在包内部执行递归，就像它是另一个目录一样。 在其他情况下，包中测试的发现操作将留给 @code{load_tests} 执行，它将附带下列参数被调用:

@example
load_tests(loader, standard_tests, pattern)
@end example

这应当返回代表包中所有测试的 @ref{7cb,,TestSuite}。 (@code{standard_tests} 将只包含从 @code{__init__.py} 获取的测试。)

因为模式已被传入 @code{load_tests} 所以包可以自由地继续（还可能修改）测试发现操作。 针对一个测试包的 '无操作' @code{load_tests} 函数看起来是这样的:

@example
def load_tests(loader, standard_tests, pattern):
    # top level directory cached on loader instance
    this_dir = os.path.dirname(__file__)
    package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
    standard_tests.addTests(package_tests)
    return standard_tests
@end example


在 3.5 版更改: 发现操作不会再检查包名称是否匹配 @emph{pattern}，因为包名称不可能匹配默认的模式。


@node 类与模块设定,信号处理,类与函数,unittest --- 单元测试框架
@anchor{library/unittest class-and-module-fixtures}@anchor{33c1}
@subsubsection 类与模块设定


类与模块设定是在 @ref{7cb,,TestSuite} 中实现的。 当测试套件遇到来自新类的测试时则来自之前的类（如果存在）的 @code{tearDownClass()} 会被调用，然后再调用来自新类的 @code{setUpClass()}。

类似地如果测试是来自之前的测试的另一个模块则来自之前模块的 @code{tearDownModule} 将被运行，然后再运行来自新模块的 @code{setUpModule}。

在所有测试运行完毕后最终的 @code{tearDownClass} 和 @code{tearDownModule} 将被运行。

请注意共享设定不适用于一些 [潜在的] 特性例如测试并行化并且它们会破坏测试隔离。 它们应当被谨慎地使用。

由 unittest 测试加载器创建的测试的默认顺序是将所有来自相同模块和类的测试归入相同分组。 这将导致 @code{setUpClass} / @code{setUpModule} (等) 对于每个类和模块都恰好被调用一次。 如果你将顺序随机化，以便使得来自不同模块和类的测试彼此相邻，那么这些共享的设定函数就可能会在一次测试运行中被多次调用。

共享的设定不适用与非标准顺序的套件。 对于不想支持共享设定的框架来说 @code{BaseTestSuite} 仍然可用。

如果在共享的设定函数中引发了任何异常则测试将被报告错误。 因为没有对应的测试实例，所以会创建一个 @code{_ErrorHolder} 对象（它具有与 @ref{9ee,,TestCase} 相同的接口）来代表该错误。 如果你只是使用标准 unittest 测试运行器那么这个细节并不重要，但是如果你是一个框架开发者那么这可能会有关系。

@menu
* setUpClass 和 tearDownClass:: 
* setUpModule 和 tearDownModule:: 

@end menu

@node setUpClass 和 tearDownClass,setUpModule 和 tearDownModule,,类与模块设定
@anchor{library/unittest setupclass-and-teardownclass}@anchor{33fa}
@subsubsection setUpClass 和 tearDownClass


这些必须被实现为类方法:

@example
import unittest

class Test(unittest.TestCase):
    @@classmethod
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    @@classmethod
    def tearDownClass(cls):
        cls._connection.destroy()
@end example

如果你希望在基类上的 @code{setUpClass} 和 @code{tearDownClass} 被调用则你必须自己云调用它们。 在 @ref{9ee,,TestCase} 中的实现是空的。

如果在 @code{setUpClass} 中引发了异常则类中的测试将不会被运行并且 @code{tearDownClass} 也不会被运行。 跳过的类中的 @code{setUpClass} 或 @code{tearDownClass} 将不会被运行。 如果引发的异常是 @ref{9f2,,SkipTest} 异常则类将被报告为已跳过而非发生错误。

@node setUpModule 和 tearDownModule,,setUpClass 和 tearDownClass,类与模块设定
@anchor{library/unittest setupmodule-and-teardownmodule}@anchor{33fb}
@subsubsection setUpModule 和 tearDownModule


这些应当被实现为函数:

@example
def setUpModule():
    createConnection()

def tearDownModule():
    closeConnection()
@end example

如果在 @code{setUpModule} 中引发了异常则模块中的任何测试都将不会被运行并且 @code{tearDownModule} 也不会被运行。 如果引发的异常是 @ref{9f2,,SkipTest} 异常则模块将被报告为已跳过而非发生错误。

要添加即使在发生异常时也必须运行的清理代码，请使用 @code{addModuleCleanup}:

@geindex addModuleCleanup() (在 unittest 模块中)
@anchor{library/unittest unittest addModuleCleanup}@anchor{37b}
@deffn {函数} unittest.addModuleCleanup (function, /, *args, **kwargs)

在 @code{tearDownModule()} 之后添加一个要调用的函数来清理测试类运行期间所使用的资源。 函数将按它们被添加的相反顺序被调用 (@abbr{LIFO})。 它们在调用时将附带它们被添加时传给 @ref{37b,,addModuleCleanup()} 的任何参数和关键字参数。

如果 @code{setUpModule()} 失败，即意味着 @code{tearDownModule()} 未被调用，则已添加的任何清理函数仍将被调用。


3.8 新版功能.

@end deffn

@geindex doModuleCleanups() (在 unittest 模块中)
@anchor{library/unittest unittest doModuleCleanups}@anchor{33fc}
@deffn {函数} unittest.doModuleCleanups ()

此函数会在 @code{tearDownModule()} 之后无条件地被调用，或者如果 @code{setUpModule()} 引发了异常则会在 @code{setUpModule()} 之后被调用。

它将负责调用由It is responsible for calling all the cleanup functions added by @ref{37b,,addModuleCleanup()} 添加的所有清理函数。 如果你需要在 @code{tearDownModule()} @emph{之前} 调用清理函数则可以自行调用 @ref{33fc,,doModuleCleanups()}。

@ref{33fc,,doModuleCleanups()} 每次会弹出清理函数栈中的一个方法，因此它可以在任何时候被调用。


3.8 新版功能.

@end deffn

@node 信号处理,,类与模块设定,unittest --- 单元测试框架
@anchor{library/unittest signal-handling}@anchor{33a9}
@subsubsection 信号处理



3.2 新版功能.


unittest 的 @ref{d94,,-c/--catch} 命令行选项，加上 @ref{9f1,,unittest.main()} 的 @code{catchbreak} 形参，提供了在测试运行期间处理 control-C 的更友好方式。 在捕获中断行为被启用时 control-C 将允许当前运行的测试能够完成，而测试运行将随后结束并报告已有的全部结果。 第二个 control-C 将会正常地引发 @ref{2d3,,KeyboardInterrupt}。

处理 control-C 信号的句柄会尝试与安装了自定义 @ref{263c,,signal.SIGINT} 处理句柄的测试代码保持兼容。 如果是 @code{unittest} 处理句柄而 @emph{不是} 已安装的 @ref{263c,,signal.SIGINT} 处理句柄被调用，即它被系统在测试的下层替换并委托处理，则它会调用默认的处理句柄。 这通常会是替换了已安装处理句柄并委托处理的代码所预期的行为。 对于需要禁用 @code{unittest} control-C 处理的单个测试则可以使用 @ref{d95,,removeHandler()} 装饰器。

还有一些工具函数让框架开发者可以在测试框架内部启用 control-C 处理功能。

@geindex installHandler() (在 unittest 模块中)
@anchor{library/unittest unittest installHandler}@anchor{33fd}
@deffn {函数} unittest.installHandler ()

安装 control-C 处理句柄。 当接收到 @ref{263c,,signal.SIGINT} 时（通常是响应用户按下 control-C）所有已注册的结果都会执行 @ref{33e8,,stop()} 调用。
@end deffn

@geindex registerResult() (在 unittest 模块中)
@anchor{library/unittest unittest registerResult}@anchor{33fe}
@deffn {函数} unittest.registerResult (result)

注册一个 @ref{ba0,,TestResult} 对象用于 control-C 的处理。 注册一个结果将保存指向它的弱引用，因此这并不能防止结果被作为垃圾回收。

如果 control-C 未被启用则注册 @ref{ba0,,TestResult} 对象将没有任何附带影响，因此不论是否启用了该项处理测试框架都可以无条件地注册他们独立创建的所有结果。
@end deffn

@geindex removeResult() (在 unittest 模块中)
@anchor{library/unittest unittest removeResult}@anchor{33ff}
@deffn {函数} unittest.removeResult (result)

移除一个已注册的结果。 一旦结果被移除则 @ref{33e8,,stop()} 将不再会作为针对 control-C 的响应在结果对象上被调用。
@end deffn

@geindex removeHandler() (在 unittest 模块中)
@anchor{library/unittest unittest removeHandler}@anchor{d95}
@deffn {函数} unittest.removeHandler (function=None)

当不附带任何参数被调用时此函数将移除已被安装的 control-C 处理句柄。 此函数还可被用作测试装饰器以在测试被执行时临时性地移除处理句柄:

@example
@@unittest.removeHandler
def test_signal_handling(self):
    ...
@end example
@end deffn

@node unittest mock --- mock对象库,unittest mock 上手指南,unittest --- 单元测试框架,开发工具
@anchor{library/unittest mock doc}@anchor{3400}@anchor{library/unittest mock module-unittest mock}@anchor{125}@anchor{library/unittest mock unittest-mock-mock-object-library}@anchor{3401}
@subsection @code{unittest.mock} --- mock对象库


@geindex unittest.mock (模块)


3.3 新版功能.


@strong{源代码：} Lib/unittest/mock.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/unittest/mock.py}


__________________________________________________________________


@ref{125,,unittest.mock} 是一个用于测试的Python库。它允许使用mock对象替换受测试系统的部分，并对它们如何已经被使用进行断言。

@ref{125,,unittest.mock} 提供的 @ref{37a,,Mock} 类，能在整个测试套件中模拟大量的方法。创建后，就可以断言调用了哪些方法/属性及其参数。还可以以常规方式指定返回值并设置所需的属性。

此外，mock 提供了用于修补测试范围内模块和类级别属性的 @ref{881,,patch()} 装饰器，和用于创建独特对象的 @ref{517,,sentinel} 。 阅读 @ref{3402,,quick guide} 中的案例了解如何使用 @ref{37a,,Mock} ，@ref{87e,,MagicMock} 和 @ref{881,,patch()} 。

mock 被设计为配合 @ref{124,,unittest} 使用且它是基于 'action -> assertion' 模式而非许多模拟框架所使用的 'record -> replay' 模式。

在 Python 的早期版本要单独使用 @ref{125,,unittest.mock} ，在 PyPI 获取 mock@footnote{https://pypi.org/project/mock} 。

@menu
* 快速上手:: 
* Mock 类:: 
* patch 装饰器:: 
* MagicMock 与魔术方法支持:: 
* 辅助对象:: 

@end menu

@node 快速上手,Mock 类,,unittest mock --- mock对象库
@anchor{library/unittest mock quick-guide}@anchor{3402}
@subsubsection 快速上手


@c class ProductionClass:
@c     def method(self, a, b, c):
@c         pass
@c 
@c class SomeClass:
@c     @staticmethod
@c     def static_method(args):
@c         return args
@c 
@c     @classmethod
@c     def class_method(cls, args):
@c         return args

当您访问对象时， @ref{37a,,Mock} 和 @ref{87e,,MagicMock} 将创建所有属性和方法，并保存他们在使用时的细节。你可以通过配置，指定返回值或者限制可访问属性，然后断言他们如何被调用：

@example
>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')
@end example

通过 @code{side_effect} 设置副作用(side effects) ，可以是一个 mock 被调用是抛出的异常：

@example
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
 ...
KeyError: 'foo'
@end example

@example
>>> values = @{'a': 1, 'b': 2, 'c': 3@}
>>> def side_effect(arg):
...     return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
@end example

Mock 还可以通过其他方法配置和控制其行为。例如 mock 可以通过设置 @emph{spec} 参数来从一个对象中获取其规格(specification)。如果访问 mock 的属性或方法不在 spec 中，会报 @ref{4aa,,AttributeError} 错误。

使用 @ref{881,,patch()} 装饰去/上下文管理器，可以更方便地测试一个模块下的类或对象。你指定的对象会在测试过程中替换成 mock （或者其他对象），测试结束后恢复。

@example
>>> from unittest.mock import patch
>>> @@patch('module.ClassName2')
... @@patch('module.ClassName1')
... def test(MockClass1, MockClass2):
...     module.ClassName1()
...     module.ClassName2()
...     assert MockClass1 is module.ClassName1
...     assert MockClass2 is module.ClassName2
...     assert MockClass1.called
...     assert MockClass2.called
...
>>> test()
@end example

@cartouche
@quotation 注解 
当你嵌套 patch 装饰器时，mock 将以执行顺序传递给装饰器函数（@emph{Python} 装饰器正常顺序）。由于从下至上，因此在上面的示例中，首先 mock 传入的 @code{module.ClassName1} 。

在查找对象的名称空间中修补对象使用 @ref{881,,patch()} 。使用起来很简单，阅读 @ref{3403,,在哪里打补丁} 来快速上手。
@end quotation
@end cartouche

@ref{881,,patch()} 也可以 with 语句中使用上下文管理。

@example
>>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
...     thing = ProductionClass()
...     thing.method(1, 2, 3)
...
>>> mock_method.assert_called_once_with(1, 2, 3)
@end example

还有一个 @ref{1153,,patch.dict()} 用于在一定范围内设置字典中的值，并在测试结束时将字典恢复为其原始状态：

@example
>>> foo = @{'key': 'value'@}
>>> original = foo.copy()
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}, clear=True):
...     assert foo == @{'newkey': 'newvalue'@}
...
>>> assert foo == original
@end example

Mock支持 Python @ref{3404,,魔术方法} 。使用模式方法最简单的方式是使用 @ref{87e,,MagicMock} class. 。它可以做如下事情：

@example
>>> mock = MagicMock()
>>> mock.__str__.return_value = 'foobarbaz'
>>> str(mock)
'foobarbaz'
>>> mock.__str__.assert_called_with()
@end example

Mock 能指定函数（或其他 Mock 实例）为魔术方法，它们将被适当地调用。  @ref{87e,,MagicMock} 是预先创建了所有魔术方法（所有有用的方法） 的 Mock 。

下面是一个使用了普通 Mock 类的魔术方法的例子

@example
>>> mock = Mock()
>>> mock.__str__ = Mock(return_value='wheeeeee')
>>> str(mock)
'wheeeeee'
@end example

使用 @ref{3405,,auto-speccing} 可以保证测试中的模拟对象与要替换的对象具有相同的api 。在 patch  中可以通过 @emph{autospec} 参数实现自动推断，或者使用 @ref{10d0,,create_autospec()} 函数。自动推断会创建一个与要替换对象相同的属相和方法的模拟对象，并且任何函数和方法（包括构造函数）都具有与真实对象相同的调用签名。

这么做是为了因确保不当地使用 mock 导致与生产代码相同的失败：

@example
>>> from unittest.mock import create_autospec
>>> def function(a, b, c):
...     pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
 ...
TypeError: <lambda>() takes exactly 3 arguments (1 given)
@end example

在类中使用 @ref{10d0,,create_autospec()} 时，会复制 @code{__init__} 方法的签名，另外在可调用对象上使用时，会复制 @code{__call__} 方法的签名。

@node Mock 类,patch 装饰器,快速上手,unittest mock --- mock对象库
@anchor{library/unittest mock the-mock-class}@anchor{3406}
@subsubsection Mock 类


@c import asyncio
@c import inspect
@c import unittest
@c from unittest.mock import sentinel, DEFAULT, ANY
@c from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock
@c from unittest.mock import mock_open

@ref{37a,,Mock} 是一个可以灵活的替换存根 (stubs) 的对象，可以测试所有代码。 Mock 是可调用的，在访问其属性时创建一个新的 mock @footnote{@w{(1)} 
仅有的例外是魔术方法和属性（其名称前后都带有双下划线）。 Mock 不会创建它们而是将引发 @ref{4aa,,AttributeError}。 这是因为解释器将会经常隐式地请求这些方法，并且在它准备接受一个魔术方法却得到一个新的 Mock 对象时会 @emph{相当} 困惑。 如果你需要魔术方法支持请参阅 @ref{3404,,魔术方法}。
} 。访问相同的属性只会返回相同的 mock 。 Mock 会保存调用记录，可以通过断言获悉代码的调用。

@ref{87e,,MagicMock} 是  @ref{37a,,Mock} 的子类，它有所有预创建且可使用的魔术方法。在需要模拟不可调用对象时，可以使用 @ref{3407,,NonCallableMock}  和 @ref{3408,,NonCallableMagicMock}

@ref{881,,patch()} 装饰器便于 @ref{37a,,Mock} 对象临时替换特定模块中的类。 @ref{881,,patch()}  默认创建 @ref{87e,,MagicMock} 。可以使用 @ref{881,,patch()} 方法的 @emph{new_callable} 参数指定 @ref{37a,,Mock} 的替代类。

@geindex Mock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock Mock}@anchor{37a}
@deffn {类} unittest.mock.Mock (spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)

创建一个新的  @ref{37a,,Mock} 对象。通过可选参数指定 @ref{37a,,Mock} 对象的行为：


@itemize *

@item 
@emph{spec}: 可以是要给字符串列表，也可以是充当模拟对象规范的现有对象（类或实例）。如果传入一个对象，则通过在该对象上调用 dir 来生成字符串列表（不支持的魔法属性和方法除外）。访问不在此列表中的任何属性都将触发 @ref{4aa,,AttributeError} 。

如果 @emph{spec} 是一个对象（而不是字符串列表），则 @ref{ed4,,__class__} 返回 @emph{spec} 对象的类。 这允许模拟程序通过 @ref{55a,,isinstance()}  测试。

@item 
@emph{spec_set} ：@emph{spec} 的更严格的变体。如果使用了该属性，尝试模拟 @emph{set} 或 @emph{get} 的属性不在 @emph{spec_set} 所包含的对象中时，会抛出 @ref{4aa,,AttributeError} 。

@item 
@emph{side_effect} ：每当调用 Mock 时都会调用的函数。 参见  @ref{3409,,side_effect}  属性。 对于引发异常或动态更改返回值很有用。 该函数使用与 mock 函数相同的参数调用，并且除非返回 @ref{340a,,DEFAULT} ，否则该函数的返回值将用作返回值。

另外， @emph{side_effect} 可以是异常类或实例。 此时，调用模拟程序时将引发异常。

如果 @emph{side_effect} 是可迭代对象，则每次调用 mock 都将返回可迭代对象的下一个值。

设置 @emph{side_effect} 为 @code{None} 即可清空。

@item 
@emph{return_value} ：调用 mock 的返回值。 默认情况下，是一个新的Mock（在首次访问时创建）。 参见 @ref{340b,,return_value} 属性 。

@item 
@emph{unsafe} ：默认情况下，如果任何以 @emph{assert} 或 @emph{assret} 开头的属性都将引发  @ref{4aa,,AttributeError} 。 当 @code{unsafe=True} 时可以访问。


3.5 新版功能.


@item 
@emph{wraps} ：要包装的 mock 对象。 如果 @emph{wraps} 不是 @code{None} ，那么调用 Mock 会将调用传递给 @emph{wraps} 的对象（返回实际结果）。 对模拟的属性访问将返回一个 Mock 对象，该对象包装了 @emph{wraps} 对象的相应属性（因此，尝试访问不存在的属性将引发  @ref{4aa,,AttributeError} ）。

如果明确指定 @emph{return_value} ，调用是，不会返回包装对象，而是返回 @emph{return_value} 。

@item 
@emph{name} ：mock 的名称。 在调试时很有用。 名称会传递到子 mock 。
@end itemize

还可以使用任意关键字参数来调用 mock 。 创建模拟后，将使用这些属性来设置 mock 的属性。 有关详细信息，请参见 @ref{340c,,configure_mock()}  方法。

@geindex assert_called() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_called}@anchor{6a9}
@deffn {方法} assert_called ()

断言至少被调用过一次。

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called()
@end example


3.6 新版功能.

@end deffn

@geindex assert_called_once() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_called_once}@anchor{6aa}
@deffn {方法} assert_called_once ()

断言仅被调用一次。

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
...
AssertionError: Expected 'method' to have been called once. Called 2 times.
@end example


3.6 新版功能.

@end deffn

@geindex assert_called_with() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_called_with}@anchor{1183}
@deffn {方法} assert_called_with (*args, **kwargs)

此方法是断言上次调用已以特定方式进行的一种便捷方法：

@example
>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')
@end example
@end deffn

@geindex assert_called_once_with() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_called_once_with}@anchor{340d}
@deffn {方法} assert_called_once_with (*args, **kwargs)

断言 mock 仅被调用一次，并且向该调用传入了指定的参数。

@example
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recent call last):
  ...
AssertionError: Expected 'mock' to be called once. Called 2 times.
@end example
@end deffn

@geindex assert_any_call() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_any_call}@anchor{340e}
@deffn {方法} assert_any_call (*args, **kwargs)

断言使用指定的参数调用。

如果 mock @emph{曾经} 被调用过则断言通过，不同于 @ref{1183,,assert_called_with()} 和 @ref{340d,,assert_called_once_with()} 那样只有在调用是最近的一次时才会通过，而对于 @ref{340d,,assert_called_once_with()} 则它还必须是唯一的一次调用。

@example
>>> mock = Mock(return_value=None)
>>> mock(1, 2, arg='thing')
>>> mock('some', 'thing', 'else')
>>> mock.assert_any_call(1, 2, arg='thing')
@end example
@end deffn

@geindex assert_has_calls() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_has_calls}@anchor{340f}
@deffn {方法} assert_has_calls (calls, any_order=False)

断言 mock 已附带指定的参数被调用。 将针对这些调用检查 @ref{3410,,mock_calls} 列表。

如果 @emph{any_order} 为假值则调用必须是顺序进行的。 在指定的调用之前或之后还可以有额外的调用。

如果 @emph{any_order} 为真值则调用可以是任意顺序的，但它们都必须在 @ref{3410,,mock_calls} 中出现。

@example
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
@end example
@end deffn

@geindex assert_not_called() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock assert_not_called}@anchor{87d}
@deffn {方法} assert_not_called ()

断言 mock 从未被调用过。

@example
>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
  ...
AssertionError: Expected 'hello' to not have been called. Called 1 times.
@end example


3.5 新版功能.

@end deffn

@geindex reset_mock() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock reset_mock}@anchor{6ab}
@deffn {方法} reset_mock (*, return_value=False, side_effect=False)

reset_mock 方法将在 mock 对象上重围所有的调用属性:

@example
>>> mock = Mock(return_value=None)
>>> mock('hello')
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False
@end example


在 3.6 版更改: 向 reset_mock 函数添加了两个仅限关键字参数。


这在你想要创建一系列重用相同对象的断言时会很有用处。 请注意 @ref{6ab,,reset_mock()} @emph{不会} 清除返回值、@ref{3409,,side_effect} 或任何你使用普通赋值所默认设置的子属性。 如果你想要重置 @emph{return_value} 或 @ref{3409,,side_effect}，则要为相应的形参传入 @code{True}。 子 mock 和返回值 mock (如果有的话) 也会被重置。

@cartouche
@quotation 注解 
@emph{return_value} 和 @ref{3409,,side_effect} 均为仅限关键字参数。
@end quotation
@end cartouche
@end deffn

@geindex mock_add_spec() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock mock_add_spec}@anchor{3411}
@deffn {方法} mock_add_spec (spec, spec_set=False)

为 mock 添加规格说明。 @emph{spec} 可以是一个对象或字符串列表。 只有 @emph{spec} 上的属性可以作为来自 mock 的属性被获取。

如果 @emph{spec_set} 为真值则只有 spec 上的属性可以被设置。
@end deffn

@geindex attach_mock() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock attach_mock}@anchor{3412}
@deffn {方法} attach_mock (mock, attribute)

附加一个 mock 作为这一个的属性，替换它的名称和上级。 对附加 mock 的调用将记录在这一个的 @ref{3413,,method_calls} 和 @ref{3410,,mock_calls} 属性中。
@end deffn

@geindex configure_mock() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock configure_mock}@anchor{340c}
@deffn {方法} configure_mock (**kwargs)

通过关键字参数在 mock 上设置属性。

属性加返回值和附带影响可以使用标准点号标记在子 mock 上设置并在方法调用中解包一个字典:

@example
>>> mock = Mock()
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock.configure_mock(**attrs)
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

同样的操作可在对 mock 的构造器调用中达成:

@example
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

@ref{340c,,configure_mock()} 的存在是使得 mock 被创建之后的配置更为容易。
@end deffn

@geindex __dir__() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock __dir__}@anchor{3414}
@deffn {方法} __dir__ ()

@ref{37a,,Mock} 对象会将 @code{dir(some_mock)} 的结果限制为有用结果。 对于带有 @emph{spec} 的 mock 这还包括 mock 的所有被允许的属性。

请查看 @ref{3415,,FILTER_DIR} 了解此过滤做了什么，以及如何停用它。
@end deffn

@geindex _get_child_mock() (unittest.mock.Mock 方法)
@anchor{library/unittest mock unittest mock Mock _get_child_mock}@anchor{3416}
@deffn {方法} _get_child_mock (**kw)

创建针对属性和返回值的子 mock。 默认情况下子 mock 将为与其上级相同的类型。 Mock 的子类可能需要重载它来定制子 mock 的创建方式。

对于非可调用的 mock 将会使用可调用的变化形式（而非不是任意的自定义子类）。
@end deffn

@geindex called (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock called}@anchor{3417}
@deffn {属性} called

一个表示 mock 对象是否已被调用的布尔值:

@example
>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True
@end example
@end deffn

@geindex call_count (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock call_count}@anchor{3418}
@deffn {属性} call_count

一个告诉你 mock object 对象已被调用多少次的整数值:

@example
>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2
@end example
@end deffn

@geindex return_value (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock return_value}@anchor{340b}
@deffn {属性} return_value

设置这个来配置通过调用该 mock 所返回的值:

@example
>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'
@end example

默认的返回值是一个 mock 对象并且你可以通过正常方式来配置它:

@example
>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<Mock name='mock()()' id='...'>
>>> mock.return_value.assert_called_with()
@end example

@ref{340b,,return_value} 也可以在构造器中设置:

@example
>>> mock = Mock(return_value=3)
>>> mock.return_value
3
>>> mock()
3
@end example
@end deffn

@geindex side_effect (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock side_effect}@anchor{3409}
@deffn {属性} side_effect

这可以是当该This can either be a function to be called when the mock 被调用时将被调用的一个函数，可调用对象或者要被引发的异常（类或实例）。

如果你传入一个函数则它将附带与该 mock 相同的参数被调用并且除了该函数返回 @ref{340a,,DEFAULT} 单例的情况以外对该 mock 的调用都将随后返回该函数所返回的任何东西。 如果该函数返回 @ref{340a,,DEFAULT} 则该 mock 将返回其正常值 (来自 @ref{340b,,return_value})。

如果你传入一个可迭代对象，它会被用来获取一个在每次调用时必须产生一个值的迭代器。 这个值可以是一个要被引发的异常实例，或是一个要从该调用返回给 mock 的值 (@ref{340a,,DEFAULT} 处理与函数的情况一致)。

一个引发异常（来测试 API 的异常处理）的 mock 的示例:

@example
>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!
@end example

使用 @ref{3409,,side_effect} 来返回包含多个值的序列:

@example
>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)
@end example

使用一个可调用对象:

@example
>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
@end example

@ref{3409,,side_effect} 可以在构造器中设置。 下面是在 mock 被调用时增加一个该属性值并返回它的例子:

@example
>>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7
@end example

将 @ref{3409,,side_effect} 设为 @code{None} 可以清除它:

@example
>>> m = Mock(side_effect=KeyError, return_value=3)
>>> m()
Traceback (most recent call last):
 ...
KeyError
>>> m.side_effect = None
>>> m()
3
@end example
@end deffn

@geindex call_args (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock call_args}@anchor{10b3}
@deffn {属性} call_args

这可以是 @code{None} (如果 mock 没有被调用)，或是 mock 最近一次被调用时附带的参数。 这将采用元组的形式：第一个成员也可以通过 @code{args} 特征属性来访问，它是 mock 被调用时所附带的任何位置参数 (或为空元组)，而第二个成员也可以通过 @code{kwargs} 特征属性来访问，它则是任何关键字参数 (或为空字典)。

@example
>>> mock = Mock(return_value=None)
>>> print(mock.call_args)
None
>>> mock()
>>> mock.call_args
call()
>>> mock.call_args == ()
True
>>> mock(3, 4)
>>> mock.call_args
call(3, 4)
>>> mock.call_args == ((3, 4),)
True
>>> mock.call_args.args
(3, 4)
>>> mock.call_args.kwargs
@{@}
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
call(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args.args
(3, 4, 5)
>>> mock.call_args.kwargs
@{'key': 'fish', 'next': 'w00t!'@}
@end example

@ref{10b3,,call_args}，以及列表 @ref{3419,,call_args_list}, @ref{3413,,method_calls} 和 @ref{3410,,mock_calls} 的成员都是 @ref{1115,,call} 对象。 这些对象属性元组，因此它们可被解包以获得单独的参数并创建更复杂的断言。 参见 @ref{341a,,作为元组的 call}。


在 3.8 版更改: 增加了 @code{args} 和 @code{kwargs} 特征属性。properties.

@end deffn

@geindex call_args_list (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock call_args_list}@anchor{3419}
@deffn {属性} call_args_list

这是一个已排序的对 mock 对象的所有调用的列表（因此该列表的长度就是它已被调用的次数）。 在执行任何调用之前它将是一个空列表。 @ref{1115,,call} 对象可以被用来方便地构造调用列表以与 @ref{3419,,call_args_list} 相比较。

@example
>>> mock = Mock(return_value=None)
>>> mock()
>>> mock(3, 4)
>>> mock(key='fish', next='w00t!')
>>> mock.call_args_list
[call(), call(3, 4), call(key='fish', next='w00t!')]
>>> expected = [(), ((3, 4),), (@{'key': 'fish', 'next': 'w00t!'@},)]
>>> mock.call_args_list == expected
True
@end example

@ref{3419,,call_args_list} 的成员均为 @ref{1115,,call} 对象。 它们可作为元组被解包以获得单个参数。 参见 @ref{341a,,作为元组的 call}。
@end deffn

@geindex method_calls (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock method_calls}@anchor{3413}
@deffn {属性} method_calls

除了会追踪对其自身的调用，mock 还会追踪对方法和属性，以及 @emph{它们的} 方法和属性的访问:

@example
>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.property.method.attribute()
<Mock name='mock.property.method.attribute()' id='...'>
>>> mock.method_calls
[call.method(), call.property.method.attribute()]
@end example

@ref{3413,,method_calls} 的成员均为 @ref{1115,,call} 对象。 它们可以作为元组被解包以获得单个参数。 参见 @ref{341a,,作为元组的 call}.
@end deffn

@geindex mock_calls (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock mock_calls}@anchor{3410}
@deffn {属性} mock_calls

@ref{3410,,mock_calls} 会记录 @emph{所有} 对 mock 对象、它的方法、魔术方法的调用 @emph{以及} 返回值的 mock。

@example
>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='...'>
>>> mock.second()
<MagicMock name='mock.second()' id='...'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='...'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
... call.__int__(), call()(1)]
>>> mock.mock_calls == expected
True
@end example

@ref{3410,,mock_calls} 的成员均为 @ref{1115,,call} 对象。 它们可以作为元组被解包以获得单个参数。 参见 @ref{341a,,作为元组的 call}。

@cartouche
@quotation 注解 
@ref{3410,,mock_calls} 的记录方式意味着在进行嵌套调用时，之前调用的形参不会被记录因而这样的比较将总是相等:

@example
>>> mock = MagicMock()
>>> mock.top(a=3).bottom()
<MagicMock name='mock.top().bottom()' id='...'>
>>> mock.mock_calls
[call.top(a=3), call.top().bottom()]
>>> mock.mock_calls[-1] == call.top(a=-1).bottom()
True
@end example
@end quotation
@end cartouche
@end deffn

@geindex __class__ (unittest.mock.Mock 属性)
@anchor{library/unittest mock unittest mock Mock __class__}@anchor{341b}
@deffn {属性} __class__

通常一个对象的 @ref{341b,,__class__} 属性将返回其类型。 对于具有 @code{spec} 的 mock 对象来说，@code{__class__} 将改为返回 spec 类。  这将允许 mock 对象为它们所替换 / 屏蔽的对象跳过 @ref{55a,,isinstance()} 测试:

@example
>>> mock = Mock(spec=3)
>>> isinstance(mock, int)
True
@end example

@ref{341b,,__class__} 是可以被赋值的，这将允许 mock 跳过 @ref{55a,,isinstance()} 检测而不强制要求你使用 spec:

@example
>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True
@end example
@end deffn
@end deffn

@geindex NonCallableMock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock NonCallableMock}@anchor{3407}
@deffn {类} unittest.mock.NonCallableMock (spec=None, wraps=None, name=None, spec_set=None, **kwargs)

不可调用的 @ref{37a,,Mock} 版本。 其构造器的形参具有与 @ref{37a,,Mock} 相同的含义，区别在于 @emph{return_value} 和 @emph{side_effect} 在不可调用的 mock 上没有意义。
@end deffn

使用类或实例作为 @code{spec} 或 @code{spec_set} 的 mock 对象能够跳过 @ref{55a,,isinstance()} 测试:

@example
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
@end example

@ref{37a,,Mock} 类具有对模拟魔术方法的支持。 请参阅 @ref{3404,,魔术方法} 了解完整细节。

mock 操作类和 @ref{881,,patch()} 装饰器都接受任意关键字参数用于配置。 对于 @ref{881,,patch()} 装饰器来说关键字参数会被传给所创建 mock 的构造器。 这些关键字被用于配置  mock 的属性:

@example
>>> m = MagicMock(attribute=3, other='fish')
>>> m.attribute
3
>>> m.other
'fish'
@end example

子 mock 的返回值和附带效果也可使用带点号的标记通过相同的方式来设置。 由于你无法直接在调用中使用带点号的名称因此你需要创建一个字典并使用 @code{**} 来解包它:

@example
>>> attrs = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError
@end example

使用 @emph{spec} (或 @emph{spec_set}) 创建的可调用 mock 将在匹配调用与 mock 时内省规格说明对象的签名。 因此，它可以匹配实际调用的参数而不必关心它们是按位置还是按名称传入的:

@example
>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, c=3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(1, 2, 3)
>>> mock.assert_called_with(a=1, b=2, c=3)
@end example

这适用于 @ref{1183,,assert_called_with()}, @ref{340d,,assert_called_once_with()}, @ref{340f,,assert_has_calls()} 和 @ref{340e,,assert_any_call()}。 当执行 @ref{3405,,自动 spec} 时，它还将应用于 mock 对象的方法调用。

@quotation


在 3.4 版更改: 添加了在附带规格说明和自动规格说明的 mock 对象上的签名内省

@end quotation

@geindex PropertyMock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock PropertyMock}@anchor{341c}
@deffn {类} unittest.mock.PropertyMock (*args, **kwargs)

旨在作为类的特征属性或其他描述器使用的 mock。 @ref{341c,,PropertyMock} 提供了 @ref{159d,,__get__()} 和 @ref{15a1,,__set__()} 方法以便你可以在它被提取时指定一个返回值。

当从一个对象提取 @ref{341c,,PropertyMock} 实例时将不附带任何参数地调用该 mock。 如果设置它则调用该 mock 时将附带被设置的值。

@example
>>> class Foo:
...     @@property
...     def foo(self):
...         return 'something'
...     @@foo.setter
...     def foo(self, value):
...         pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
...     mock_foo.return_value = 'mockity-mock'
...     this_foo = Foo()
...     print(this_foo.foo)
...     this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]
@end example
@end deffn

由于 mock 属性的存储方式你无法直接将 @ref{341c,,PropertyMock} 附加到一个 mock 对象。 但是你可以将它附加到 mock 类型对象:

@example
>>> m = MagicMock()
>>> p = PropertyMock(return_value=3)
>>> type(m).foo = p
>>> m.foo
3
>>> p.assert_called_once_with()
@end example

@geindex AsyncMock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock AsyncMock}@anchor{379}
@deffn {类} unittest.mock.AsyncMock (spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)

@ref{87e,,MagicMock} 的异步版本。 @ref{379,,AsyncMock} 对象的行为方式将使该对象被识别为异步函数，其调用的结果将为可等待对象。

@example
>>> mock = AsyncMock()
>>> asyncio.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock())  
True
@end example

调用 @code{mock()} 的结果是一个异步函数，它在被等待之后将具有 @code{side_effect} 或 @code{return_value} 的结果:


@itemize -

@item 
如果 @code{side_effect} 是一个函数，则异步函数将返回该函数的结果,

@item 
如果 @code{side_effect} 是一个异常，则异步函数将引发该异常,

@item 
如果 @code{side_effect} 是一个可迭代对象，则异步函数将返回该可迭代对象的下一个值，但是，如果结果序列被耗尽，则会立即引发 @code{StopAsyncIteration},

@item 
如果 @code{side_effect} 未被定义，则异步函数将返回is not defined, the async function will return the value defined by @code{return_value} 所定义的值，因而，在默认情况下，异步函数会返回一个新的 @ref{379,,AsyncMock} 对象。
@end itemize

将 @ref{37a,,Mock} 或 @ref{87e,,MagicMock} 的 @emph{spec} 设为异步函数将导致在调用后返回一个协程对象。

@example
>>> async def async_func(): pass
...
>>> mock = MagicMock(async_func)
>>> mock
<MagicMock spec='function' id='...'>
>>> mock()  
<coroutine object AsyncMockMixin._mock_call at ...>
@end example

将 @ref{37a,,Mock}, @ref{87e,,MagicMock} 或 @ref{379,,AsyncMock} 的 @emph{spec} 设为带有异步和同步函数的类将自动删除其中的同步函数并将它们设为 @ref{87e,,MagicMock} (如果上级 mock 是 @ref{379,,AsyncMock} 或 @ref{87e,,MagicMock}) 或者 @ref{37a,,Mock} (如果上级 mock 是 @ref{37a,,Mock})。 所有异步函数都将为 @ref{379,,AsyncMock}。

@example
>>> class ExampleClass:
...     def sync_foo():
...         pass
...     async def async_foo():
...         pass
...
>>> a_mock = AsyncMock(ExampleClass)
>>> a_mock.sync_foo
<MagicMock name='mock.sync_foo' id='...'>
>>> a_mock.async_foo
<AsyncMock name='mock.async_foo' id='...'>
>>> mock = Mock(ExampleClass)
>>> mock.sync_foo
<Mock name='mock.sync_foo' id='...'>
>>> mock.async_foo
<AsyncMock name='mock.async_foo' id='...'>
@end example


3.8 新版功能.


@geindex assert_awaited() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited}@anchor{341d}
@deffn {方法} assert_awaited ()

断言 mock 已被等待至少一次。 请注意这是从被调用的对象中分离出来的，必须要使用 @code{await} 关键字:

@example
>>> mock = AsyncMock()
>>> async def main(coroutine_mock):
...     await coroutine_mock
...
>>> coroutine_mock = mock()
>>> mock.called
True
>>> mock.assert_awaited()
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited.
>>> asyncio.run(main(coroutine_mock))
>>> mock.assert_awaited()
@end example
@end deffn

@geindex assert_awaited_once() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_once}@anchor{341e}
@deffn {方法} assert_awaited_once ()

断言 mock 已被等待恰好一次。

@example
>>> mock = AsyncMock()
>>> async def main():
...     await mock()
...
>>> asyncio.run(main())
>>> mock.assert_awaited_once()
>>> asyncio.run(main())
>>> mock.method.assert_awaited_once()
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 2 times.
@end example
@end deffn

@geindex assert_awaited_with() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_with}@anchor{341f}
@deffn {方法} assert_awaited_with (*args, **kwargs)

断言上一次等待传入了指定的参数。

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_with('foo', bar='bar')
>>> mock.assert_awaited_with('other')
Traceback (most recent call last):
...
AssertionError: expected call not found.
Expected: mock('other')
Actual: mock('foo', bar='bar')
@end example
@end deffn

@geindex assert_awaited_once_with() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_awaited_once_with}@anchor{3420}
@deffn {方法} assert_awaited_once_with (*args, **kwargs)

断言 mock 被等待恰好一次并且附带了指定的参数。

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_once_with('foo', bar='bar')
>>> asyncio.run(main('foo', bar='bar'))
>>> mock.assert_awaited_once_with('foo', bar='bar')
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 2 times.
@end example
@end deffn

@geindex assert_any_await() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_any_await}@anchor{3421}
@deffn {方法} assert_any_await (*args, **kwargs)

断言 mock 已被等待并附带了指定的参数。

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> asyncio.run(main('foo', bar='bar'))
>>> asyncio.run(main('hello'))
>>> mock.assert_any_await('foo', bar='bar')
>>> mock.assert_any_await('other')
Traceback (most recent call last):
...
AssertionError: mock('other') await not found
@end example
@end deffn

@geindex assert_has_awaits() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_has_awaits}@anchor{3422}
@deffn {方法} assert_has_awaits (calls, any_order=False)

断言 mock 已附带了指定的调用被等待。 将针对这些等待检查 @ref{10b2,,await_args_list} 列表。

如果 @emph{any_order} 为假值则等待必须是顺序进行的。 在指定的等待之前或之后还可以有额外的调用。

如果 @emph{any_order} 为真值则等待可以是任意顺序的，但它们都必须在 @ref{10b2,,await_args_list} 中出现。

@example
>>> mock = AsyncMock()
>>> async def main(*args, **kwargs):
...     await mock(*args, **kwargs)
...
>>> calls = [call("foo"), call("bar")]
>>> mock.assert_has_awaits(calls)
Traceback (most recent call last):
...
AssertionError: Awaits not found.
Expected: [call('foo'), call('bar')]
Actual: []
>>> asyncio.run(main('foo'))
>>> asyncio.run(main('bar'))
>>> mock.assert_has_awaits(calls)
@end example
@end deffn

@geindex assert_not_awaited() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock assert_not_awaited}@anchor{3423}
@deffn {方法} assert_not_awaited ()

断言 mock 从未被等待过。

@example
>>> mock = AsyncMock()
>>> mock.assert_not_awaited()
@end example
@end deffn

@geindex reset_mock() (unittest.mock.AsyncMock 方法)
@anchor{library/unittest mock unittest mock AsyncMock reset_mock}@anchor{3424}
@deffn {方法} reset_mock (*args, **kwargs)

参见 @ref{6ab,,Mock.reset_mock()}。 还会将 @ref{3425,,await_count} 设为 0，将 @ref{3426,,await_args} 设为 None，并清空 @ref{10b2,,await_args_list}。
@end deffn

@geindex await_count (unittest.mock.AsyncMock 属性)
@anchor{library/unittest mock unittest mock AsyncMock await_count}@anchor{3425}
@deffn {属性} await_count

一个追踪 mock 对象已被等待多少次的整数值。

@example
>>> mock = AsyncMock()
>>> async def main():
...     await mock()
...
>>> asyncio.run(main())
>>> mock.await_count
1
>>> asyncio.run(main())
>>> mock.await_count
2
@end example
@end deffn

@geindex await_args (unittest.mock.AsyncMock 属性)
@anchor{library/unittest mock unittest mock AsyncMock await_args}@anchor{3426}
@deffn {属性} await_args

这可能为 @code{None} (如果 mock 从未被等待)，或为该 mock 上一次被等待所附带的参数。 其功能与 @ref{10b3,,Mock.call_args} 相同。

@example
>>> mock = AsyncMock()
>>> async def main(*args):
...     await mock(*args)
...
>>> mock.await_args
>>> asyncio.run(main('foo'))
>>> mock.await_args
call('foo')
>>> asyncio.run(main('bar'))
>>> mock.await_args
call('bar')
@end example
@end deffn

@geindex await_args_list (unittest.mock.AsyncMock 属性)
@anchor{library/unittest mock unittest mock AsyncMock await_args_list}@anchor{10b2}
@deffn {属性} await_args_list

这是由对 mock 对象按顺序执行的所有等待组成的列表（因此该列表的长度即它被等待的次数）。 在有任何等待被执行之前它将为一个空列表。Before any awaits have been made it is an empty list.

@example
>>> mock = AsyncMock()
>>> async def main(*args):
...     await mock(*args)
...
>>> mock.await_args_list
[]
>>> asyncio.run(main('foo'))
>>> mock.await_args_list
[call('foo')]
>>> asyncio.run(main('bar'))
>>> mock.await_args_list
[call('foo'), call('bar')]
@end example
@end deffn
@end deffn

@menu
* 调用: 调用<2>. 
* 删除属性:: 
* Mock 的名称与 name 属性:: 
* 附加 Mock 作为属性:: 

@end menu

@node 调用<2>,删除属性,,Mock 类
@anchor{library/unittest mock calling}@anchor{3427}
@subsubsection 调用


Mock 对象是可调用对象。 调用将把值集合作为 @ref{340b,,return_value} 属性返回。 默认的返回值是一个新的 Mock 对象；它会在对返回值的首次访问（不论是显式访问还是通过调用 Mock）时被创建 —— 但它会被保存并且每次都返回相同的对象。

对该对象的调用将被记录在 @ref{10b3,,call_args} 和 @ref{3419,,call_args_list} 等属性中。

如果设置了 @ref{3409,,side_effect} 则它将在调用被记录之后被调用，因此如果 @code{side_effect} 引发了异常该调用仍然会被记录。

让一个 mock 在被调用时引发异常的最简单方式是将 @ref{3409,,side_effect} 设为一个异常类或实例:

@example
>>> m = MagicMock(side_effect=IndexError)
>>> m(1, 2, 3)
Traceback (most recent call last):
  ...
IndexError
>>> m.mock_calls
[call(1, 2, 3)]
>>> m.side_effect = KeyError('Bang!')
>>> m('two', 'three', 'four')
Traceback (most recent call last):
  ...
KeyError: 'Bang!'
>>> m.mock_calls
[call(1, 2, 3), call('two', 'three', 'four')]
@end example

如果 @code{side_effect} 为函数则该函数所返回的对象就是调用该 mock 所返回的对象。 @code{side_effect} 函数在被调用时将附带与该 mock 相同的参数。 这允许你根据输入动态地改变返回值:

@example
>>> def side_effect(value):
...     return value + 1
...
>>> m = MagicMock(side_effect=side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]
@end example

如果你想让该 mock 仍然返回默认的返回值（一个新的 mock对象），或是任何设定的返回值，那么有两种方式可以做到这一点。 从 @code{side_effect} 内部返回 @code{mock.return_value}，或者返回 @ref{340a,,DEFAULT}:

@example
>>> m = MagicMock()
>>> def side_effect(*args, **kwargs):
...     return m.return_value
...
>>> m.side_effect = side_effect
>>> m.return_value = 3
>>> m()
3
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> m.side_effect = side_effect
>>> m()
3
@end example

要移除一个 @code{side_effect}，并返回到默认的行为，请将 @code{side_effect} 设为 @code{None}:

@example
>>> m = MagicMock(return_value=6)
>>> def side_effect(*args, **kwargs):
...     return 3
...
>>> m.side_effect = side_effect
>>> m()
3
>>> m.side_effect = None
>>> m()
6
@end example

@code{side_effect} 也可以是任意可迭代对象。 对该 mock 的重复调用将返回来自该可迭代对象的值（直到该可迭代对象被耗尽并导致 @ref{58a,,StopIteration} 被引发）:

@example
>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
  ...
StopIteration
@end example

如果该可迭代对象有任何成员属于异常则它们将被引发而不是被返回:

@example
>>> iterable = (33, ValueError, 66)
>>> m = MagicMock(side_effect=iterable)
>>> m()
33
>>> m()
Traceback (most recent call last):
 ...
ValueError
>>> m()
66
@end example

@node 删除属性,Mock 的名称与 name 属性,调用<2>,Mock 类
@anchor{library/unittest mock deleting-attributes}@anchor{3428}@anchor{library/unittest mock id2}@anchor{3429}
@subsubsection 删除属性


Mock 对象会根据需要创建属性。 这允许它们可以假装成任意类型的对象。

你可能想要一个 mock 对象在调用 @ref{553,,hasattr()} 时返回 @code{False}，或者在获取某个属性时引发 @ref{4aa,,AttributeError}。 你可以通过提供一个对象作为 mock 的 @code{spec} 属性来做到这点，但这并不总是很方便。

你可以通过删除属性来“屏蔽”它们。 属性一旦被删除，访问它将引发 @ref{4aa,,AttributeError}。

@example
>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
    ...
AttributeError: f
@end example

@node Mock 的名称与 name 属性,附加 Mock 作为属性,删除属性,Mock 类
@anchor{library/unittest mock mock-names-and-the-name-attribute}@anchor{342a}
@subsubsection Mock 的名称与 name 属性


由于 "name" 是 @ref{37a,,Mock} 构造器的参数之一，如果你想让你的 mock 对象具有 "name" 属性你不可以在创建时传入该参数。 有两个替代方式。 一个选项是使用 @ref{340c,,configure_mock()}:

@example
>>> mock = MagicMock()
>>> mock.configure_mock(name='my_name')
>>> mock.name
'my_name'
@end example

一个更简单的选项是在 mock 创建之后简单地设置 "name" 属性:

@example
>>> mock = MagicMock()
>>> mock.name = "foo"
@end example

@node 附加 Mock 作为属性,,Mock 的名称与 name 属性,Mock 类
@anchor{library/unittest mock attaching-mocks-as-attributes}@anchor{342b}
@subsubsection 附加 Mock 作为属性


当你附加一个 mock 作为另一个 mock 的属性（或作为返回值）时它会成为该 mock 的 "子对象"。 对子对象的调用会被记录在父对象的 @ref{3413,,method_calls} 和 @ref{3410,,mock_calls} 属性中。 这适用于配置子 mock 然后将它们附加到父对象，或是将 mock 附加到将记录所有对子对象的调用的父对象上并允许你创建有关 mock 之间的调用顺序的断言:

@example
>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(1)
>>> child2(2)
>>> parent.mock_calls
[call.child1(1), call.child2(2)]
@end example

这里有一个例外情况是如果 mock 设置了名称。 这允许你在出于某些理由不希望其发生时避免 "父对象" 的影响。

@example
>>> mock = MagicMock()
>>> not_a_child = MagicMock(name='not-a-child')
>>> mock.attribute = not_a_child
>>> mock.attribute()
<MagicMock name='not-a-child()' id='...'>
>>> mock.mock_calls
[]
@end example

通过 @ref{881,,patch()} 创建的 mock 会被自动赋予名称。 要将具有名称的 mock 附加到父对象上你应当使用 @ref{3412,,attach_mock()} 方法:

@example
>>> thing1 = object()
>>> thing2 = object()
>>> parent = MagicMock()
>>> with patch('__main__.thing1', return_value=None) as child1:
...     with patch('__main__.thing2', return_value=None) as child2:
...         parent.attach_mock(child1, 'child1')
...         parent.attach_mock(child2, 'child2')
...         child1('one')
...         child2('two')
...
>>> parent.mock_calls
[call.child1('one'), call.child2('two')]
@end example

@node patch 装饰器,MagicMock 与魔术方法支持,Mock 类,unittest mock --- mock对象库
@anchor{library/unittest mock the-patchers}@anchor{342c}
@subsubsection patch 装饰器


patch 装饰器仅被用于在它们所装饰的函数作用域内部为对象添加补丁。 它们会自动为你执行去除补丁的处理，即使是在引发了异常的情况下。 所有这些函数都还可在 with 语句中使用或是作为类装饰器。

@menu
* patch:: 
* patch.object: patch object. 
* patch.dict: patch dict. 
* patch.multiple: patch multiple. 
* 补丁方法; start 和 stop: 补丁方法 start 和 stop. 
* 为内置对象打补丁:: 
* TEST_PREFIX:: 
* 嵌套补丁装饰器:: 
* 补丁的位置:: 
* 对描述器和代理对象打补丁:: 

@end menu

@node patch,patch object,,patch 装饰器
@anchor{library/unittest mock patch}@anchor{342d}
@subsubsection patch


@cartouche
@quotation 注解 
问题的关键是要在正确的命名空间中打补丁。 参见 @ref{342e,,where to patch} 一节。
@end quotation
@end cartouche

@geindex patch() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock patch}@anchor{881}
@deffn {函数} unittest.mock.patch (target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

@ref{881,,patch()} 可以作为函数装饰器、类装饰器或上下文管理器。 在函数或 with 语句的内部，@emph{target} 会打上一个 @emph{new} 对象补丁。 当函数/with 语句退出时补丁将被撤销。

如果 @emph{new} 被省略，那么如果被打补丁的对象是一个异步函数则 target 将被替换为 @ref{379,,AsyncMock} 否则替换为 @ref{87e,,MagicMock}。 如果 @ref{881,,patch()} 被用作装饰器并且 @emph{new} 被省略，那么已创建的 mock 将作为一个附加参数传入被装饰的函数。 如果 @ref{881,,patch()} 被用作上下文管理器那么已创建的 mock 将被该上下文管理器所返回。is returned by the context manager.

@emph{target} 应当为 @code{'package.module.ClassName'} 形式的字符串。 @emph{target} 将被导入并且该指定对象会被替换为 @emph{new} 对象，因此 @emph{target} 必须是可以从你调用 @ref{881,,patch()} 的环境中导入的。 target 会在被装饰的函数被执行的时候被导入，而非在装饰的时候。

@emph{spec} 和 @emph{spec_set} 关键字参数会被传递给 @ref{87e,,MagicMock}，如果 patch 为你创建了此对象的话。

此外你还可以传入 @code{spec=True} 或 @code{spec_set=True}，这将使 patch 将被模拟的对象作为 spec/spec_set 对象传入。

@emph{new_callable} 允许你指定一个不同的类，或者可调用对象，它将被调用以创建 @emph{新的} 对象。 在默认情况下将指定 @ref{379,,AsyncMock} 用于异步函数，@ref{87e,,MagicMock} 用于其他函数。

另一种更强形式的 @emph{spec} 是 @emph{autospec}。 如果你设置了 @code{autospec=True} 则将以来自被替换对象的 spec 来创建 mock。 mock 的所有属性也将具有被替换对象相应属性的 spec。 被模拟的方法和函数将检查它们的参数并且如果使用了错误的签名调用它们则将引发 @ref{1ff,,TypeError}。 对于替换了一个类的 mock，它们的返回值（即‘实例’）将具有与该类相同的 spec。 请参阅 @ref{10d0,,create_autospec()} 函数以及 @ref{3405,,自动 spec}。

除了 @code{autospec=True} 你还可以传入 @code{autospec=some_object} 以使用任意对象而不是被替换的对象作为 spec。

在默认情况下 @ref{881,,patch()} 将无法替换不存在的属性。 如果你传入 @code{create=True}，且该属性并不存在，则 patch 将在调用被打补丁的函数时为你创建该属性，并在退出被打补丁的函数时再次删除它。 这适用于编写针对生产代码在运行时创建的属性的测试。 它默认是被关闭的因为这具有危险性。 当它被开启时你将能够针对实际上并不存在的 API 编写通过测试！

@cartouche
@quotation 注解 

在 3.5 版更改: 如果你要给某个模块的内置函数打补丁则不必传入 @code{create=True}，它默认就会被添加。

@end quotation
@end cartouche

Patch 可以被用作 @code{TestCase} 类装饰器。 其作用是装饰类中的每个测试方法。 当你的测试方法共享同一个补丁集时这将减少模板代码。 @ref{881,,patch()} 会通过查找以 @code{patch.TEST_PREFIX} 打头的名称来找到测试。 其默认值为 @code{'test'}，这与 @ref{124,,unittest} 打到测试的方式一致。 你可以通过设置 @code{patch.TEST_PREFIX} 来指定其他的前缀。

Patch 可以通过 with 语句作为上下文管理器使用。 这时补丁将应用于 with 语句的缩进代码块。 如果你使用了 "as" 则打补丁的对象将被绑定到 "as" 之后的名称；这非常适用于当 @ref{881,,patch()} 为你创建 mock 对象的情况。

@ref{881,,patch()} 可接受任意关键字参数。 如果打补丁的对象是异步的则这些参数将被传给 @ref{379,,AsyncMock}，否则传给 @ref{87e,,MagicMock}，或者是指定的 @emph{new_callable}。

@code{patch.dict(...)}, @code{patch.multiple(...)} 和 @code{patch.object(...)} 可用于其他使用场景。
@end deffn

@ref{881,,patch()} 作为函数装饰器，为你创建 mock 并将其传入被装饰的函数:

@example
>>> @@patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
...     print(mock_class is SomeClass)
...
>>> function(None)
True
@end example

为类打补丁将把该类替换为 @ref{87e,,MagicMock} 的 @emph{实例}。 如果该类是在受测试的代码中被实例化的则它将为所要使用的 mock 的 @ref{340b,,return_value}。

如果该类被多次实例化则你可以使用 @ref{3409,,side_effect} 来每次返回一个新 mock。 或者你也可以将 @emph{return_value} 设为你希望的任何对象。

要在被打补丁的类的 @emph{实例} 的方法上配置返回值你必须在 @code{return_value} 操作。 例如:

@example
>>> class Class:
...     def method(self):
...         pass
...
>>> with patch('__main__.Class') as MockClass:
...     instance = MockClass.return_value
...     instance.method.return_value = 'foo'
...     assert Class() is instance
...     assert Class().method() == 'foo'
...
@end example

如果你使用 @emph{spec} 或 @emph{spec_set} 并且 @ref{881,,patch()} 替换的是 @emph{class}，那么所创建的 mock 的返回值将具有同样的 spec。

@example
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()
@end example

@emph{new_callable} 参数适用于当你想要使用其他类来替代所创建的 mock 默认的 @ref{87e,,MagicMock} 的场合。 例如，如果你想要使用 @ref{3407,,NonCallableMock}:

@example
>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
...     assert thing is mock_thing
...     thing()
...
Traceback (most recent call last):
  ...
TypeError: 'NonCallableMock' object is not callable
@end example

另一个使用场景是用 @ref{924,,io.StringIO} 实例来替换某个对象:

@example
>>> from io import StringIO
>>> def foo():
...     print('Something')
...
>>> @@patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
...     foo()
...     assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()
@end example

当 @ref{881,,patch()} 为你创建 mock 时，通常你需要做的第一件事就是配置该 mock。 某些配置可以在对 patch 的调用中完成。 你在调用时传入的任何关键字参数都将被用来在所创建的 mock 上设置属性:

@example
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two'
@end example

除了所创建的 mock 的属性上的属性，例如 @ref{340b,,return_value} 和 @ref{3409,,side_effect}，还可以配置子 mock 的属性。 将这些属性直接作为关键字参数传入在语义上是无效的，但是仍然能够使用 @code{**} 将以这些属性为键的字典扩展至一个 @ref{881,,patch()} 调用中

@example
>>> config = @{'method.return_value': 3, 'other.side_effect': KeyError@}
>>> patcher = patch('__main__.thing', **config)
>>> mock_thing = patcher.start()
>>> mock_thing.method()
3
>>> mock_thing.other()
Traceback (most recent call last):
  ...
KeyError
@end example

在默认情况下，尝试给某个模块中并不存在的函数（或者某个类中的方法或属性）打补丁将会失败并引发 @ref{4aa,,AttributeError}:

@example
>>> @@patch('sys.non_existing_attribute', 42)
... def test():
...     assert sys.non_existing_attribute == 42
...
>>> test()
Traceback (most recent call last):
  ...
AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing_attribute'
@end example

但在对 @ref{881,,patch()} 的调用中添加 @code{create=True} 将使之前示例的效果符合预期:

@example
>>> @@patch('sys.non_existing_attribute', 42, create=True)
... def test(mock_stdout):
...     assert sys.non_existing_attribute == 42
...
>>> test()
@end example


在 3.8 版更改: 如果目标为异步函数那么 @ref{881,,patch()} 现在将返回一个 @ref{379,,AsyncMock}。


@node patch object,patch dict,patch,patch 装饰器
@anchor{library/unittest mock patch-object}@anchor{342f}
@subsubsection patch.object


@geindex patch.object() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock patch object}@anchor{10fd}
@deffn {函数} patch.object (target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

用一个 mock 对象为对象 (@emph{target}) 中指定名称的成员 (@emph{attribute}) 打补丁。

@ref{10fd,,patch.object()} 可以被用作装饰器、类装饰器或上下文管理器。 @emph{new}, @emph{spec}, @emph{create}, @emph{spec_set}, @emph{autospec} 和 @emph{new_callable} 等参数的含义与 @ref{881,,patch()} 的相同。 与 @ref{881,,patch()} 类似，@ref{10fd,,patch.object()} 接受任意关键字参数用于配置它所创建的 mock 对象。

当用作类装饰器时 @ref{10fd,,patch.object()} 将认可 @code{patch.TEST_PREFIX} 作为选择所要包装方法的标准。
@end deffn

你可以附带三个参数或两个参数来调用 @ref{10fd,,patch.object()}。 三个参数的形式将接受要打补丁的对象、属性的名称以及将要替换该属性的对象。

将附带两个参数的形式调用时你将省略替换对象，还会为你创建一个 mock 并作为附加参数传入被装饰的函数:

@example
>>> @@patch.object(SomeClass, 'class_method')
... def test(mock_method):
...     SomeClass.class_method(3)
...     mock_method.assert_called_with(3)
...
>>> test()
@end example

传给 @ref{10fd,,patch.object()} 的 @emph{spec}, @emph{create} 和其他参数的含义与 @ref{881,,patch()} 的同名参数相同。

@node patch dict,patch multiple,patch object,patch 装饰器
@anchor{library/unittest mock patch-dict}@anchor{3430}
@subsubsection patch.dict


@geindex patch.dict() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock patch dict}@anchor{1153}
@deffn {函数} patch.dict (in_dict, values=(), clear=False, **kwargs)

为一个目录或目录类对象打补丁，并在测试之后将该目录恢复到其初始状态。

@emph{in_dict} 可以是一个字典或映射类容器。 如果它是一个映射则它必须至少支持获取、设置和删除条目以及对键执行迭代。

@emph{in_dict} 也可以是一个指定字典名称的字符串，然后将通过导入操作来获取该字典。

@emph{values} 可以是一个要在字典中设置的值的字典。 @emph{values} 也可以是一个包含 @code{(key, value)} 对的可迭代对象。

如果 @emph{clear} 为真值则该字典将在设置新值之前先被清空。

@ref{1153,,patch.dict()} 也可以附带任意关键字参数调用以设置字典中的值。


在 3.8 版更改: 现在当 @ref{1153,,patch.dict()} 被用作上下文管理器时将返回被打补丁的字典。now returns the patched dictionary when used as a context manager.

@end deffn

@ref{1153,,patch.dict()} 可被用作上下文管理器、装饰器或类装饰器:

@example
>>> foo = @{@}
>>> @@patch.dict(foo, @{'newkey': 'newvalue'@})
... def test():
...     assert foo == @{'newkey': 'newvalue'@}
>>> test()
>>> assert foo == @{@}
@end example

当被用作类装饰器时 @ref{1153,,patch.dict()} 将认可 @code{patch.TEST_PREFIX} (默认值为 @code{'test'}) 作为选择所在包装方法的标准:

@example
>>> import os
>>> import unittest
>>> from unittest.mock import patch
>>> @@patch.dict('os.environ', @{'newkey': 'newvalue'@})
... class TestSample(unittest.TestCase):
...     def test_sample(self):
...         self.assertEqual(os.environ['newkey'], 'newvalue')
@end example

如果你在为你的测试使用不同的前缀，你可以通过设置 @code{patch.TEST_PREFIX} 来将不同的前缀告知打补丁方。 有关如何修改该值的详情请参阅 @ref{3431,,TEST_PREFIX}。

@ref{1153,,patch.dict()} 可被用来向一个字典添加成员，或者简单地让测试修改一个字典，并确保当测试结束时恢复该字典。

@example
>>> foo = @{@}
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}) as patched_foo:
...     assert foo == @{'newkey': 'newvalue'@}
...     assert patched_foo == @{'newkey': 'newvalue'@}
...     # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
...     patched_foo['spam'] = 'eggs'
...
>>> assert foo == @{@}
>>> assert patched_foo == @{@}
@end example

@example
>>> import os
>>> with patch.dict('os.environ', @{'newkey': 'newvalue'@}):
...     print(os.environ['newkey'])
...
newvalue
>>> assert 'newkey' not in os.environ
@end example

可以在 @ref{1153,,patch.dict()} 调用中使用关键字来设置字典的值:

@example
>>> mymodule = MagicMock()
>>> mymodule.function.return_value = 'fish'
>>> with patch.dict('sys.modules', mymodule=mymodule):
...     import mymodule
...     mymodule.function('some', 'args')
...
'fish'
@end example

@ref{1153,,patch.dict()} 可以用于实际上不是字典的字典类对象。 它们最少必须支持条目获取、设置、删除以及迭代或成员检测两者中的一个。 这对应于魔术方法 @ref{3ad,,__getitem__()}, @ref{d32,,__setitem__()}, @ref{d33,,__delitem__()} 以及 @ref{611,,__iter__()} 或 @ref{df6,,__contains__()}。

@example
>>> class Container:
...     def __init__(self):
...         self.values = @{@}
...     def __getitem__(self, name):
...         return self.values[name]
...     def __setitem__(self, name, value):
...         self.values[name] = value
...     def __delitem__(self, name):
...         del self.values[name]
...     def __iter__(self):
...         return iter(self.values)
...
>>> thing = Container()
>>> thing['one'] = 1
>>> with patch.dict(thing, one=2, two=3):
...     assert thing['one'] == 2
...     assert thing['two'] == 3
...
>>> assert thing['one'] == 1
>>> assert list(thing) == ['one']
@end example

@node patch multiple,补丁方法 start 和 stop,patch dict,patch 装饰器
@anchor{library/unittest mock patch-multiple}@anchor{3432}
@subsubsection patch.multiple


@geindex patch.multiple() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock patch multiple}@anchor{3433}
@deffn {函数} patch.multiple (target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

在单个调用中执行多重补丁。 它接受要打补丁的对象（一个对象或一个通过导入来获取对象的字符串）以及用于补丁的关键字参数:

@example
with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
    ...
@end example

如果你希望 @ref{3433,,patch.multiple()} 为你创建 mock 则要使用 @ref{340a,,DEFAULT} 作为值。 在此情况下所创建的 mock 会通过关键字参数传入被装饰的函数，而当 @ref{3433,,patch.multiple()} 被用作上下文管理器时则将返回一个字典。

@ref{3433,,patch.multiple()} 可以被用作装饰器、类装饰器或上下文管理器。 @emph{spec}, @emph{spec_set}, @emph{create}, @emph{autospec} 和 @emph{new_callable} 等参数的含义与 @ref{881,,patch()} 的相同。 这些参数将被应用到 @ref{3433,,patch.multiple()} 所打的 @emph{所有} 补丁。

当被用作类装饰器时 @ref{3433,,patch.multiple()} 将认可 @code{patch.TEST_PREFIX} 作为选择所要包装方法的标准。
@end deffn

如果你希望 @ref{3433,,patch.multiple()} 为你创建 mock，那么你可以使用 @ref{340a,,DEFAULT} 作为值。 如果你使用 @ref{3433,,patch.multiple()} 作为装饰器则所创建的 mock 会作为关键字参数传入被装饰的函数。

@example
>>> thing = object()
>>> other = object()

>>> @@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(thing, other):
...     assert isinstance(thing, MagicMock)
...     assert isinstance(other, MagicMock)
...
>>> test_function()
@end example

@ref{3433,,patch.multiple()} 可以与其他 @code{patch} 装饰器嵌套使用，但要将作为关键字传入的参数要放在 @ref{881,,patch()} 所创建的标准参数 @emph{之后}:

@example
>>> @@patch('sys.exit')
... @@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
...     assert 'other' in repr(other)
...     assert 'thing' in repr(thing)
...     assert 'exit' in repr(mock_exit)
...
>>> test_function()
@end example

如果 @ref{3433,,patch.multiple()} 被用作上下文管理器，则上下文管理器的返回值将是一个以所创建的 mock 的名称为键的字典:

@example
>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
...     assert 'other' in repr(values['other'])
...     assert 'thing' in repr(values['thing'])
...     assert values['thing'] is thing
...     assert values['other'] is other
...
@end example

@node 补丁方法 start 和 stop,为内置对象打补丁,patch multiple,patch 装饰器
@anchor{library/unittest mock patch-methods-start-and-stop}@anchor{3434}@anchor{library/unittest mock start-and-stop}@anchor{3435}
@subsubsection 补丁方法: start 和 stop


所有补丁对象都具有 @code{start()} 和 @code{stop()} 方法。 使用这些方法可以更简单地在 @code{setUp} 方法上打补丁，还可以让你不必嵌套使用装饰器或 with 语句就能打多重补丁。

要使用这些方法请按正常方式调用 @ref{881,,patch()}, @ref{10fd,,patch.object()} 或 @ref{1153,,patch.dict()} 并保留一个指向所返回 @code{patcher} 对象的引用。 然后你可以调用 @code{start()} 来原地打补丁并调用 @code{stop()} 来恢复它。

如果你使用 @ref{881,,patch()} 来创建自己的 mock 那么将可通过调用 @code{patcher.start} 来返回它。

@example
>>> patcher = patch('package.module.ClassName')
>>> from package import module
>>> original = module.ClassName
>>> new_mock = patcher.start()
>>> assert module.ClassName is not original
>>> assert module.ClassName is new_mock
>>> patcher.stop()
>>> assert module.ClassName is original
>>> assert module.ClassName is not new_mock
@end example

此操作的一个典型应用场景是在一个 @code{TestCase} 的 @code{setUp} 方法中执行多重补丁:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         self.patcher1 = patch('package.module.Class1')
...         self.patcher2 = patch('package.module.Class2')
...         self.MockClass1 = self.patcher1.start()
...         self.MockClass2 = self.patcher2.start()
...
...     def tearDown(self):
...         self.patcher1.stop()
...         self.patcher2.stop()
...
...     def test_something(self):
...         assert package.module.Class1 is self.MockClass1
...         assert package.module.Class2 is self.MockClass2
...
>>> MyTest('test_something').run()
@end example

@cartouche
@quotation 警告 
如果你要使用这个技巧则你必须通过调用 @code{stop} 来确保补丁被“恢复”。 这可能要比你想像的更麻烦，因为如果在 @code{setUp} 中引发了异常那么 @code{tearDown} 将不会被调用。 @ref{3cd,,unittest.TestCase.addCleanup()} 可以简化此操作:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         patcher = patch('package.module.Class')
...         self.MockClass = patcher.start()
...         self.addCleanup(patcher.stop)
...
...     def test_something(self):
...         assert package.module.Class is self.MockClass
...
@end example

一项额外的好处是你不再需要保留指向 @code{patcher} 对象的引用。
@end quotation
@end cartouche

还可以通过使用 @ref{3436,,patch.stopall()} 来停止已启动的所有补丁。

@geindex patch.stopall() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock patch stopall}@anchor{3436}
@deffn {函数} patch.stopall ()

停止所有激活的补丁。 仅会停止通过 @code{start} 启动的补丁。
@end deffn

@node 为内置对象打补丁,TEST_PREFIX,补丁方法 start 和 stop,patch 装饰器
@anchor{library/unittest mock id4}@anchor{3437}@anchor{library/unittest mock patch-builtins}@anchor{3438}
@subsubsection 为内置对象打补丁


你可以为一个模块中的任何内置函数打补丁。 以以示例是为内置函数 @ref{1588,,ord()} 打补丁:

@example
>>> @@patch('__main__.ord')
... def test(mock_ord):
...     mock_ord.return_value = 101
...     print(ord('c'))
...
>>> test()
101
@end example

@node TEST_PREFIX,嵌套补丁装饰器,为内置对象打补丁,patch 装饰器
@anchor{library/unittest mock id5}@anchor{3439}@anchor{library/unittest mock test-prefix}@anchor{3431}
@subsubsection TEST_PREFIX


所有补丁都可被用作类装饰器。 当以这种方式使用时它们将会包装类中的每个测试方法。 补丁会将以名字以 @code{'test'} 开头的方法识别为测试方法。 这与 @ref{87b,,unittest.TestLoader} 查找测试方法的默认方式相同。

你可能会想要为你的测试使用不同的前缀。 你可以通过设置 @code{patch.TEST_PREFIX} 来告知打补丁方不同的前缀:

@example
>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>>
>>> @@patch('__main__.value', 'not three')
... class Thing:
...     def foo_one(self):
...         print(value)
...     def foo_two(self):
...         print(value)
...
>>>
>>> Thing().foo_one()
not three
>>> Thing().foo_two()
not three
>>> value
3
@end example

@node 嵌套补丁装饰器,补丁的位置,TEST_PREFIX,patch 装饰器
@anchor{library/unittest mock nesting-patch-decorators}@anchor{343a}
@subsubsection 嵌套补丁装饰器


如果你想要应用多重补丁那么你可以简单地堆叠多个装饰器。

你可以使用以下模式来堆叠多个补丁装饰器:

@example
>>> @@patch.object(SomeClass, 'class_method')
... @@patch.object(SomeClass, 'static_method')
... def test(mock1, mock2):
...     assert SomeClass.static_method is mock1
...     assert SomeClass.class_method is mock2
...     SomeClass.static_method('foo')
...     SomeClass.class_method('bar')
...     return mock1, mock2
...
>>> mock1, mock2 = test()
>>> mock1.assert_called_once_with('foo')
>>> mock2.assert_called_once_with('bar')
@end example

请注意装饰器是从下往上被应用的。 这是 Python 应用装饰器的标准方式。 被创建并传入你的测试函数的 mock 的顺序也将匹配这个顺序。

@node 补丁的位置,对描述器和代理对象打补丁,嵌套补丁装饰器,patch 装饰器
@anchor{library/unittest mock id6}@anchor{342e}@anchor{library/unittest mock where-to-patch}@anchor{3403}
@subsubsection 补丁的位置


@ref{881,,patch()} 通过（临时性地）修改某一个对象的 @emph{名称} 指向另一个对象来发挥作用。 可以有多个名称指向任意单独对象，因此要让补丁起作用你必须确保已为被测试的系统所使用的名称打上补丁。

基本原则是你要在对象 @emph{被查找} 的地方打补丁，这不一定就是它被定义的地方。 一组示例将有助于厘清这一点。

想像我们有一个想要测试的具有如下结构的项目:

@example
a.py
    -> Defines SomeClass

b.py
    -> from a import SomeClass
    -> some_function instantiates SomeClass
@end example

现在我们要测试 @code{some_function} 但我们想使用 @ref{881,,patch()} 来模拟 @code{SomeClass}。 问题在于当我们导入模块 b 时，我们将必须让它从模块 a 导入 @code{SomeClass}。 如果我们使用 @ref{881,,patch()} 来模拟 @code{a.SomeClass} 那么它将不会对我们的测试造成影响；模块 b 已经拥有对 @emph{真正的} @code{SomeClass} 的引用因此看上去我们的补丁不会有任何影响。

关键在于对 @code{SomeClass} 打补丁操作是在它被使用（或它被查找）的地方。 在此情况下实际上 @code{some_function} 将在模块 b 中查找 @code{SomeClass}，而我们已经在那里导入了它。 补丁看上去应该是这样:

@example
@@patch('b.SomeClass')
@end example

但是，再考虑另一个场景，其中不是 @code{from a import SomeClass} 而是模块 b 执行了 @code{import a} 并且 @code{some_function} 使用了 @code{a.SomeClass}。 这两个导入形式都很常见。 在这种情况下我们要打补丁的类将在该模块中被查找因而我们必须改为对 @code{a.SomeClass} 打补丁:

@example
@@patch('a.SomeClass')
@end example

@node 对描述器和代理对象打补丁,,补丁的位置,patch 装饰器
@anchor{library/unittest mock patching-descriptors-and-proxy-objects}@anchor{343b}
@subsubsection 对描述器和代理对象打补丁


@ref{342d,,patch} 和 @ref{342f,,patch.object} 都能正确地对描述器打补丁并恢复：包括类方法、静态方法和特征属性。 你应当在 @emph{类} 而不是在实例上为它们打补丁。 它们还适用于代理属性访问的 @emph{某些} 对象，例如 django 设置对象@footnote{http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198}。

@node MagicMock 与魔术方法支持,辅助对象,patch 装饰器,unittest mock --- mock对象库
@anchor{library/unittest mock magicmock-and-magic-method-support}@anchor{343c}
@subsubsection MagicMock 与魔术方法支持


@menu
* 模拟魔术方法:: 
* MagicMock:: 

@end menu

@node 模拟魔术方法,MagicMock,,MagicMock 与魔术方法支持
@anchor{library/unittest mock magic-methods}@anchor{3404}@anchor{library/unittest mock mocking-magic-methods}@anchor{343d}
@subsubsection 模拟魔术方法


@ref{37a,,Mock} 支持模拟 Python 协议方法，或称“魔术方法”。 这允许 mock 对象替代容器或其他实现了 Python 协议的对象。

因为查找魔术方法的方式不同于普通方法 @footnote{@w{(2)} 
魔术方法 @emph{应当} 是在类中而不是在实例中查找。 不同的 Python 版本对这个规则的应用并不一致。 受支持的协议方法应当适用于所有受支持的 Python 版本。
}，这种支持采用了特别的实现。 这意味着只有特定的魔术方法受到支持。 受支持的是 @emph{几乎} 所有魔术方法。 如果有你需要但被遗漏的请告知我们。

你可以通过在某个函数或 mock 实例中设置魔术方法来模拟它们。 如果你是使用函数则它 @emph{必须} 接受 @code{self} 作为第一个参数 @footnote{@w{(3)} 
该函数基本上是与类挂钩的，但每个 @code{Mock} 实例都会与其他实例保持隔离。
}。

@example
>>> def __str__(self):
...     return 'fooble'
...
>>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble'
@end example

@example
>>> mock = Mock()
>>> mock.__str__ = Mock()
>>> mock.__str__.return_value = 'fooble'
>>> str(mock)
'fooble'
@end example

@example
>>> mock = Mock()
>>> mock.__iter__ = Mock(return_value=iter([]))
>>> list(mock)
[]
@end example

一个这样的应用场景是在 @ref{7e4,,with} 语句中模拟作为上下文管理器的对象:

@example
>>> mock = Mock()
>>> mock.__enter__ = Mock(return_value='foo')
>>> mock.__exit__ = Mock(return_value=False)
>>> with mock as m:
...     assert m == 'foo'
...
>>> mock.__enter__.assert_called_with()
>>> mock.__exit__.assert_called_with(None, None, None)
@end example

对魔术方法的调用不会在 @ref{3413,,method_calls} 中出现，但它们会被记录在 @ref{3410,,mock_calls} 中。

@cartouche
@quotation 注解 
如果你使用 @emph{spec} 关键字参数来创建 mock 那么尝试设置不包含在 spec 中的魔术方法将引发 @ref{4aa,,AttributeError}。
@end quotation
@end cartouche

受支持魔术方法的完整列表如下:


@itemize *

@item 
@code{__hash__}, @code{__sizeof__}, @code{__repr__} 和 @code{__str__}

@item 
@code{__dir__}, @code{__format__} 和 @code{__subclasses__}

@item 
@code{__round__}, @code{__floor__}, @code{__trunc__} 和 @code{__ceil__}

@item 
比较运算: @code{__lt__}, @code{__gt__}, @code{__le__}, @code{__ge__}, @code{__eq__} 和 @code{__ne__}

@item 
容器方法: @code{__getitem__}, @code{__setitem__}, @code{__delitem__}, @code{__contains__}, @code{__len__}, @code{__iter__}, @code{__reversed__} 和 @code{__missing__}

@item 
上下文管理器: @code{__enter__}, @code{__exit__}, @code{__aenter__} 和 @code{__aexit__}

@item 
单目数值运算方法: @code{__neg__}, @code{__pos__} 和 @code{__invert__}

@item 
数值运算方法 (包括右手和原地形式): @code{__add__}, @code{__sub__}, @code{__mul__}, @code{__matmul__}, @code{__div__}, @code{__truediv__}, @code{__floordiv__}, @code{__mod__}, @code{__divmod__}, @code{__lshift__}, @code{__rshift__}, @code{__and__}, @code{__xor__}, @code{__or__} 和 @code{__pow__}

@item 
数值转换方法: @code{__complex__}, @code{__int__}, @code{__float__} 和 @code{__index__}

@item 
描述器方法: @code{__get__}, @code{__set__} and @code{__delete__}

@item 
封存方法: @code{__reduce__}, @code{__reduce_ex__}, @code{__getinitargs__}, @code{__getnewargs__}, @code{__getstate__} 和 @code{__setstate__}

@item 
文件系统路径表示: @code{__fspath__}

@item 
异步迭代方法: @code{__aiter__} and @code{__anext__}
@end itemize


在 3.8 版更改: 增加了对 @ref{5ef,,os.PathLike.__fspath__()} 的支持。



在 3.8 版更改: 增加了对 @code{__aenter__}, @code{__aexit__}, @code{__aiter__} 和 @code{__anext__} 的支持。


下列方法均存在但是 @emph{不受} 支持，因为它们或者被 mock 所使用，或者无法动态设置，或者可能导致问题:


@itemize *

@item 
@code{__getattr__}, @code{__setattr__}, @code{__init__} 和 @code{__new__}

@item 
@code{__prepare__}, @code{__instancecheck__}, @code{__subclasscheck__}, @code{__del__}
@end itemize

@node MagicMock,,模拟魔术方法,MagicMock 与魔术方法支持
@anchor{library/unittest mock magic-mock}@anchor{343e}
@subsubsection MagicMock


存在两个版本的 @code{MagicMock}: @ref{87e,,MagicMock} 和 @ref{3408,,NonCallableMagicMock}.

@geindex MagicMock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock MagicMock}@anchor{87e}
@deffn {类} unittest.mock.MagicMock (*args, **kw)

@code{MagicMock} 是包含了大部分魔术方法的默认实现的 @ref{37a,,Mock} 的子类。 你可以使用 @code{MagicMock} 而无须自行配置魔术方法。without having to configure the magic methods yourself.

构造器形参的含义与 @ref{37a,,Mock} 的相同。

如果你使用了 @emph{spec} 或 @emph{spec_set} 参数则将 @emph{只有} 存在于 spec 中的魔术方法会被创建。
@end deffn

@geindex NonCallableMagicMock (unittest.mock 中的类)
@anchor{library/unittest mock unittest mock NonCallableMagicMock}@anchor{3408}
@deffn {类} unittest.mock.NonCallableMagicMock (*args, **kw)

@ref{87e,,MagicMock} 的不可调用对象版本。

其构造器的形参具有与 @ref{87e,,MagicMock} 相同的含义，区别在于 @emph{return_value} 和 @emph{side_effect} 在不可调用的 mock 上没有意义。
@end deffn

魔术方法是通过 @ref{87e,,MagicMock} 对象来设置的，因此你可以用通常的方式来配置它们并使用它们:

@example
>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result'
@end example

在默认情况下许多协议方法都需要返回特定类型的对象。 这些方法都预先配置了默认的返回值，以便它们在你对返回值不感兴趣时可以不做任何事就能被使用。 如果你想要修改默认值则你仍然可以手动 @emph{设置} 返回值。

方法及其默认返回值:


@itemize *

@item 
@code{__lt__}: @code{NotImplemented}

@item 
@code{__gt__}: @code{NotImplemented}

@item 
@code{__le__}: @code{NotImplemented}

@item 
@code{__ge__}: @code{NotImplemented}

@item 
@code{__int__}: @code{1}

@item 
@code{__contains__}: @code{False}

@item 
@code{__len__}: @code{0}

@item 
@code{__iter__}: @code{iter([])}

@item 
@code{__exit__}: @code{False}

@item 
@code{__aexit__}: @code{False}

@item 
@code{__complex__}: @code{1j}

@item 
@code{__float__}: @code{1.0}

@item 
@code{__bool__}: @code{True}

@item 
@code{__index__}: @code{1}

@item 
@code{__hash__}: mock 的默认 hash

@item 
@code{__str__}: mock 的默认 str

@item 
@code{__sizeof__}: mock 的默认 sizeof
@end itemize

例如:

@example
>>> mock = MagicMock()
>>> int(mock)
1
>>> len(mock)
0
>>> list(mock)
[]
>>> object() in mock
False
@end example

两个相等性方法 @ref{454,,__eq__()} 和 @ref{f20,,__ne__()} 是特殊的。 它们基于标识号进行默认的相等性比较，使用 @ref{3409,,side_effect} 属性，除非你修改它们的返回值以返回其他内容:

@example
>>> MagicMock() == 3
False
>>> MagicMock() != 3
True
>>> mock = MagicMock()
>>> mock.__eq__.return_value = True
>>> mock == 3
True
@end example

@code{MagicMock.__iter__()} 的返回值可以是任意可迭代对象而不要求必须是迭代器:

@example
>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
@end example

如果返回值 @emph{是} 迭代器，则对其执行一次迭代就会将它耗尽因而后续执行的迭代将会输出空列表:

@example
>>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
[]
@end example

@code{MagicMock} 已配置了所有受支持的魔术方法，只有某些晦涩和过时的魔术方法是例外。 如果你需要仍然可以设置它们。

在 @code{MagicMock} 中受到支持但默认未被设置的魔术方法有:


@itemize *

@item 
@code{__subclasses__}

@item 
@code{__dir__}

@item 
@code{__format__}

@item 
@code{__get__}, @code{__set__} 和 @code{__delete__}

@item 
@code{__reversed__} 和 @code{__missing__}

@item 
@code{__reduce__}, @code{__reduce_ex__}, @code{__getinitargs__}, @code{__getnewargs__}, @code{__getstate__} 和 @code{__setstate__}

@item 
@code{__getformat__} 和 @code{__setformat__}
@end itemize

@node 辅助对象,,MagicMock 与魔术方法支持,unittest mock --- mock对象库
@anchor{library/unittest mock helpers}@anchor{343f}
@subsubsection 辅助对象


@menu
* sentinel:: 
* DEFAULT:: 
* call:: 
* create_autospec:: 
* ANY:: 
* FILTER_DIR:: 
* mock_open:: 
* 自动 spec:: 
* 将 mock 封包:: 

@end menu

@node sentinel,DEFAULT,,辅助对象
@anchor{library/unittest mock sentinel}@anchor{3440}
@subsubsection sentinel


@geindex sentinel() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock sentinel}@anchor{517}
@deffn {数据} unittest.mock.sentinel

@code{sentinel} 对象提供了一种为你的测试提供独特对象的便捷方式。

属性是在你通过名称访问它们时按需创建的。 访问相同的属性将始终返回相同的对象。 返回的对象会有一个合理的 repr 以使测试失败消息易于理解。


在 3.7 版更改: 现在 @code{sentinel} 属性会在它们被 @ref{25,,copy} 或 @ref{ca,,pickle} 时保存其标识。

@end deffn

在测试时你可能需要测试是否有一个特定的对象作为参数被传给了另一个方法，或是被其返回。 通常的做法是创建一个指定名称的 sentinel 对象来执行这种测试。 @ref{517,,sentinel} 提供了一种创建和测试此类对象的标识的便捷方式。

在这个示例中我们为 @code{method} 打上便捷补丁以返回 @code{sentinel.some_object}:

@example
>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> result
sentinel.some_object
@end example

@node DEFAULT,call,sentinel,辅助对象
@anchor{library/unittest mock default}@anchor{3441}
@subsubsection DEFAULT


@geindex DEFAULT() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock DEFAULT}@anchor{340a}
@deffn {数据} unittest.mock.DEFAULT

@ref{340a,,DEFAULT} 对象是一个预先创建的 sentinel (实际为 @code{sentinel.DEFAULT})。 它可被 @ref{3409,,side_effect} 函数用来指明其应当使用正常的返回值。
@end deffn

@node call,create_autospec,DEFAULT,辅助对象
@anchor{library/unittest mock call}@anchor{3442}
@subsubsection call


@geindex call() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock call}@anchor{1115}
@deffn {函数} unittest.mock.call (*args, **kwargs)

@ref{1115,,call()} 是一个可创建更简单断言的辅助对象，用于同 @ref{10b3,,call_args}, @ref{3419,,call_args_list}, @ref{3410,,mock_calls} 和 @ref{3413,,method_calls} 进行比较。 @ref{1115,,call()} 也可配合 @ref{340f,,assert_has_calls()} 使用。

@example
>>> m = MagicMock(return_value=None)
>>> m(1, 2, a='foo', b='bar')
>>> m()
>>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
True
@end example
@end deffn

@geindex call_list() (unittest.mock.call 方法)
@anchor{library/unittest mock unittest mock call call_list}@anchor{3443}
@deffn {方法} call.call_list ()

对于代表多个调用的 call 对象，@ref{3443,,call_list()} 将返回一个包含所有中间调用以及最终调用的列表。
@end deffn

@code{call_list} 特别适用于创建针对“链式调用”的断言。 链式调用是指在一行代码中执行的多个调用。 这将使得一个 mock 的中存在多个条目 @ref{3410,,mock_calls}。 手动构造调用的序列将会很烦琐。

@ref{3443,,call_list()} 可以根据同一个链式调用构造包含多个调用的序列:

@example
>>> m = MagicMock()
>>> m(1).method(arg='foo').other('bar')(2.0)
<MagicMock name='mock().method().other()()' id='...'>
>>> kall = call(1).method(arg='foo').other('bar')(2.0)
>>> kall.call_list()
[call(1),
 call().method(arg='foo'),
 call().method().other('bar'),
 call().method().other()(2.0)]
>>> m.mock_calls == kall.call_list()
True
@end example
@anchor{library/unittest mock calls-as-tuples}@anchor{341a}
根据构造方式的不同，@code{call} 对象可以是一个 (位置参数, 关键字参数) 或 (名称, 位置参数, 关键字参数) 元组。 当你自行构造它们时这没有什么关系，但是 @ref{10b3,,Mock.call_args}, @ref{3419,,Mock.call_args_list} 和 @ref{3410,,Mock.mock_calls} 属性当中的 @code{call} 对象可以被反查以获取它们所包含的单个参数。

@ref{10b3,,Mock.call_args} 和 @ref{3419,,Mock.call_args_list} 中的 @code{call} 对象是 (位置参数, 关键字参数) 二元组而 @ref{3410,,Mock.mock_calls} 中以及你自行构造的 @code{call} 对象则是 (名称, 位置参数, 关键字参数) 三元组。

你可以使用它们作为“元组”的特性来为更复杂的内省和断言功能获取单个参数。 位置参数是一个元组（如无位置参数则为空元组）而关键字参数是一个字典:

@example
>>> m = MagicMock(return_value=None)
>>> m(1, 2, 3, arg='one', arg2='two')
>>> kall = m.call_args
>>> kall.args
(1, 2, 3)
>>> kall.kwargs
@{'arg': 'one', 'arg2': 'two'@}
>>> kall.args is kall[0]
True
>>> kall.kwargs is kall[1]
True
@end example

@example
>>> m = MagicMock()
>>> m.foo(4, 5, 6, arg='two', arg2='three')
<MagicMock name='mock.foo()' id='...'>
>>> kall = m.mock_calls[0]
>>> name, args, kwargs = kall
>>> name
'foo'
>>> args
(4, 5, 6)
>>> kwargs
@{'arg': 'two', 'arg2': 'three'@}
>>> name is m.mock_calls[0][0]
True
@end example

@node create_autospec,ANY,call,辅助对象
@anchor{library/unittest mock create-autospec}@anchor{3444}
@subsubsection create_autospec


@geindex create_autospec() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock create_autospec}@anchor{10d0}
@deffn {函数} unittest.mock.create_autospec (spec, spec_set=False, instance=False, **kwargs)

使用另一对象作为 spec 来创建 mock 对象。 mock 的属性将使用 @emph{spec} 对象上的对应属性作为其 spec。

被模拟的函数或方法的参数将会被检查以确保它们是附带了正确的签名被调用的。

如果 @emph{spec_set} 为 @code{True} 则尝试设置不存在于 spec 对象中的属性将引发 @ref{4aa,,AttributeError}。

如果将类用作 spec 则 mock（该类的实例）的返回值将为这个 spec。 你可以通过传入 @code{instance=True} 来将某个类用作一个实例对象的 spec。 被返回的 mock 将仅在该 mock 的实例为可调用对象时才会是可调用对象。

@ref{10d0,,create_autospec()} 也接受被传入所创建 mock 的构造器的任意关键字参数。
@end deffn

请参阅 @ref{3405,,自动 spec} 来了解如何通过 @ref{10d0,,create_autospec()} 以及 @ref{881,,patch()} 的 @emph{autospec} 参数来自动设置 spec。


在 3.8 版更改: 如果目标为异步函数那么 @ref{10d0,,create_autospec()} 现在将返回一个 @ref{379,,AsyncMock}。


@node ANY,FILTER_DIR,create_autospec,辅助对象
@anchor{library/unittest mock any}@anchor{3445}
@subsubsection ANY


@geindex ANY() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock ANY}@anchor{111a}
@deffn {数据} unittest.mock.ANY
@end deffn

有时你可能需要设置关于要模拟的调用中的 @emph{某些} 参数的断言，但是又不想理会其他参数或者想要从 @ref{10b3,,call_args} 中单独拿出它们并针对它们设置更复杂的断言。

为了忽略某些参数你可以传入与 @emph{任意对象} 相等的对象。 这样再调用 @ref{1183,,assert_called_with()} 和 @ref{340d,,assert_called_once_with()} 时无论传入什么参数都将执行成功。

@example
>>> mock = Mock(return_value=None)
>>> mock('foo', bar=object())
>>> mock.assert_called_once_with('foo', bar=ANY)
@end example

@ref{111a,,ANY} 也可被用在与 @ref{3410,,mock_calls} 这样的调用列表相比较的场合:

@example
>>> m = MagicMock(return_value=None)
>>> m(1)
>>> m(1, 2)
>>> m(object())
>>> m.mock_calls == [call(1), call(1, 2), ANY]
True
@end example

@node FILTER_DIR,mock_open,ANY,辅助对象
@anchor{library/unittest mock filter-dir}@anchor{3446}
@subsubsection FILTER_DIR


@geindex FILTER_DIR() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock FILTER_DIR}@anchor{3415}
@deffn {数据} unittest.mock.FILTER_DIR
@end deffn

@ref{3415,,FILTER_DIR} 是一个控制 mock 对象响应 @ref{e01,,dir()} 的方式的模块级变量（只适用于 Python 2.6 之后的版本）。 默认值为 @code{True}，这将使用下文描述的过滤操作，以便只显示有用的成员。 如果你不想要这样的过滤，或是出于诊断目的需要将其关闭，则应设置 @code{mock.FILTER_DIR = False}。

当启用过滤时，@code{dir(some_mock)} 将只显示有用的属性并将包括正常情况下不会被显示的任何动态创建的属性。 如果 mock 是使用 @emph{spec} (当然也可以是 @emph{autospec}) 创建的则原有的所有属性都将被显示，即使它们还未被访问过:

@example
>>> dir(Mock())
['assert_any_call',
 'assert_called',
 'assert_called_once',
 'assert_called_once_with',
 'assert_called_with',
 'assert_has_calls',
 'assert_not_called',
 'attach_mock',
 ...
>>> from urllib import request
>>> dir(Mock(spec=request))
['AbstractBasicAuthHandler',
 'AbstractDigestAuthHandler',
 'AbstractHTTPHandler',
 'BaseHandler',
 ...
@end example

许多不太有用的（是 @ref{37a,,Mock} 的而不是被模拟对象的私有成员）开头带有下划线和双下划线的属性已从在 @ref{37a,,Mock} 上对 @ref{e01,,dir()} 的调用的结果中被过滤。 如果你不喜欢此行为你可以通过设置模块级开关 @ref{3415,,FILTER_DIR} 来将其关闭:

@example
>>> from unittest import mock
>>> mock.FILTER_DIR = False
>>> dir(mock.Mock())
['_NonCallableMock__get_return_value',
 '_NonCallableMock__get_side_effect',
 '_NonCallableMock__return_value_doc',
 '_NonCallableMock__set_return_value',
 '_NonCallableMock__set_side_effect',
 '__call__',
 '__class__',
 ...
@end example

或者你也可以直接使用 @code{vars(my_mock)} (实例成员) 和 @code{dir(type(my_mock))} (类型成员) 来忽略 @code{mock.FILTER_DIR} 设置绕过过滤。

@node mock_open,自动 spec,FILTER_DIR,辅助对象
@anchor{library/unittest mock mock-open}@anchor{3447}
@subsubsection mock_open


@geindex mock_open() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock mock_open}@anchor{114b}
@deffn {函数} unittest.mock.mock_open (mock=None, read_data=None)

创建 mock 来代替使用 @ref{16f,,open()} 的辅助函数。 它对于 @ref{16f,,open()} 被直接调用或被用作上下文管理器的情况都适用。

@emph{mock} 参数是要配置的 mock 对象。 如为 @code{None} (默认值) 则将为你创建一个 @ref{87e,,MagicMock}，其 API 会被限制为可用于标准文件处理的方法或属性。

@emph{read_data} 是供文件处理的 @code{read()}, @ref{1883,,readline()} 和 @ref{1921,,readlines()} 方法返回的字符串。 调用这些方法将会从 @emph{read_data} 获取数据直到它被耗尽。 对这些方法的模拟是相当简化的：每次 @emph{mock} 被调用时，@emph{read_data} 都将从头开始。 如果你需要对你提供给测试代码的数据有更多控制那么你将需要自行定制这个 mock。 如果这还不够用，那么通过一些 PyPI@footnote{https://pypi.org} 上的内存文件系统包可以提供更真实的测试文件系统。


在 3.4 版更改: 增加了对 @ref{1883,,readline()} 和 @ref{1921,,readlines()} 的支持。 对 @code{read()} 的模拟被改为消耗 @emph{read_data} 而不是每次调用时返回它。



在 3.5 版更改: @emph{read_data} 现在会在每次 @emph{mock} 的调用时重置。



在 3.8 版更改: 为实现增加了 @ref{611,,__iter__()} 以使迭代操作（例如在 for 循环中）能正确地消耗 @emph{read_data}。

@end deffn

将 @ref{16f,,open()} 用作上下文管理器一确保你的文件处理被正确关闭的最佳方式因而十分常用:

@example
with open('/some/path', 'w') as f:
    f.write('something')
@end example

这里的问题在于即使你模拟了对 @ref{16f,,open()} 的调用但被用作上下文管理器（并调用其 @ref{d65,,__enter__()} 和 @ref{d66,,__exit__()} 方法）的也是 @emph{被返回的对象}。

通过 @ref{87e,,MagicMock} 来模拟上下文管理器是十分常见且十分麻烦的因此需要使用一个辅助函数。

@example
>>> m = mock_open()
>>> with patch('__main__.open', m):
...     with open('foo', 'w') as h:
...         h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
 call().__enter__(),
 call().write('some stuff'),
 call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
@end example

以及针对读取文件:

@example
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h:
...         result = h.read()
...
>>> m.assert_called_once_with('foo')
>>> assert result == 'bibble'
@end example

@node 自动 spec,将 mock 封包,mock_open,辅助对象
@anchor{library/unittest mock auto-speccing}@anchor{3405}@anchor{library/unittest mock autospeccing}@anchor{3448}
@subsubsection 自动 spec


自动 spec 是基于现有 mock 的 @code{spec} 特性。 它将 mock 的 api 限制为原始对象 (spec) 的 api，但它是递归（惰性实现）的因而 mock 的属性只有与 spec 的属性相同的 api。 除此之外被模块的函数 / 方法具有与原对应物相同的调用签名因此如果它们被不正确地调用时会引发 @ref{1ff,,TypeError}。

在我开始解释自动 spec 如何运作之前，先说明一下它的必要性。

@ref{37a,,Mock} 是一个非常强大而灵活的对象，但当它被用来模拟来自被测试系统的对象时有两个缺陷。 其中一个缺陷是 @ref{37a,,Mock} 的 api 特有的而另一个则是使用 mock 对象时普遍存在的问题。

第一个问题为 @ref{37a,,Mock} 所专属。 @ref{37a,,Mock} 具有两个特别好用的断言方法: @ref{1183,,assert_called_with()} 和 @ref{340d,,assert_called_once_with()}。

@example
>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
Traceback (most recent call last):
 ...
AssertionError: Expected 'mock' to be called once. Called 2 times.
@end example

因为 mock 会根据需要自动创建属性，并允许你附带任意参数调用它们，所以如果你写错了这两个断言方法则你的断言将会失效:

@example
>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assret_called_once_with(4, 5, 6)  # Intentional typo!
@end example

你的测试将因这个拼写错误而静默并且错误地通过。

第二个问题是 mock 操作中普遍存在的。 如果你重构了你的部分代码，例如修改了一些成员的名称等等，则代码中任何仍在使用 @emph{旧 api} 但其使用的是 mock 而非真实对象的测试仍将通过。 这意味着即使你的代码已被破坏你的测试却仍可能全部通过。

请注意这是为什么你在单元测试之外还需要集成测试的原因之一。 孤立地测试每个部分时全都正常而顺滑，但是如果你没有测试你的各个单元“联成一体”的情况如何那么就仍然存在测试可以发现大量错误的空间。

@code{mock} 已经提供了一个对此有帮助的特性，称为 spec 控制。 如果你使用类或实例作为一个 mock 的 @code{spec} 那么你将仅能访问 mock 中只存在于实际的类中的属性。

@example
>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.assret_called_with  # Intentional typo!
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'
@end example

这个 spec 仅会应用于 mock 本身，因此对于 mock 中的任意方法我们仍然面临相同的问题:

@example
>>> mock.has_data()
<mock.Mock object at 0x...>
>>> mock.has_data.assret_called_with()  # Intentional typo!
@end example

自动 spec 解决了这个问题。 你可以将 @code{autospec=True} 传给 @ref{881,,patch()} / @ref{10fd,,patch.object()} 或是使用 @ref{10d0,,create_autospec()} 函数来创建带有 spec 的 mock。 如果你是将 @code{autospec=True} 参数传给 @ref{881,,patch()} 那么被替代的那个对象将被用作 spec 对象。 因为 spec 控制是“惰性地”执行的（spec 在 mock 中的属性被访问时才会被创建）所以即使是非常复杂或深度嵌套的对象（例如需要导入本身已导入了多个模块的模块）你也可以使用它而不会有太大的性能损失。

以下是一个实际应用的示例:

@example
>>> from urllib import request
>>> patcher = patch('__main__.request', autospec=True)
>>> mock_request = patcher.start()
>>> request is mock_request
True
>>> mock_request.Request
<MagicMock name='request.Request' spec='Request' id='...'>
@end example

你可以看到 @code{request.Request} 有一个 spec。 @code{request.Request} 的构造器接受两个参数 (其中一个是 @emph{self})。 如果我们尝试不正确地调用它则将导致:

@example
>>> req = request.Request()
Traceback (most recent call last):
 ...
TypeError: <lambda>() takes at least 2 arguments (1 given)
@end example

该 spec 也将应用于被实例化的类（即附带i.e. the return value of spec 的 mock 的返回值）:

@example
>>> req = request.Request('foo')
>>> req
<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
@end example

@code{Request} 对象是不可调用对象，因此实例化我们的被模拟 @code{request.Request} 的返回值是一个不可调用的 mock。 有了这个 spec 我们的断言中出现任何拼写问题都将引发正确的错误:

@example
>>> req.add_header('spam', 'eggs')
<MagicMock name='request.Request().add_header()' id='...'>
>>> req.add_header.assret_called_with  # Intentional typo!
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'
>>> req.add_header.assert_called_with('spam', 'eggs')
@end example

在许多情况下你将只需将In many cases you will just be able to add @code{autospec=True} 添加到你现有的 @ref{881,,patch()} 调用中即可防止拼写错误和 api 变化所导致的问题。

除了通过 @ref{881,,patch()} 来使用 @emph{autospec}  还有一个 @ref{10d0,,create_autospec()} 可以直接创建带有自动 spec 的 mock:

@example
>>> from urllib import request
>>> mock_request = create_autospec(request)
>>> mock_request.Request('foo', 'bar')
<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
@end example

不过这并非没有缺点和限制，这也就是为什么它不是默认行为。 为了知道在 spec 对象上有哪些属性是可用的，autospec 必须对 spec 进行自省（访问其属性）。 当你遍历 mock 上的属性时在原始对象上的对应遍历也将在底层进行。 如果你的任何带 spec 的对象具有可触发代码执行的特征属性或描述器则你可能会无法使用 autospec。 在另一方面更好的的做法是将你的对象设计为可以安全地执行自省 @footnote{@w{(4)} 
这仅适用于类或已实例化的对象。 调用一个被模拟的类来创建一个 mock 实例 @emph{不会} 创建真的实例。 只有属性查找 —— 以及对 @ref{e01,,dir()} 的调用 —— 会被执行。
}。

一个更严重的问题在于实例属性往往是在 @ref{e2b,,__init__()} 方法中被创建而在类中完全不存在。 @emph{autospec} 无法获取动态创建的属性而使得 api 被限制于可见的属性。

@example
>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a
...
Traceback (most recent call last):
  ...
AttributeError: Mock object has no attribute 'a'
@end example

要解决这个问题有几种不同的方式。 最容易但多少有些烦扰的方式是简单地在 mock 创建完成后再设置所需的属性。 Just because @emph{autospec} 只是不允许你获取不存在于 spec 上的属性但并不会阻止你设置它们:

@example
>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a = 33
...
@end example

@emph{spec} 和 @emph{autospec} 都有更严格的版本 @emph{确实能} 阻止你设置不存在的属性。 这在你希望确保你的代码只能 @emph{设置} 有效的属性时也很有用，但显然它会阻止下面这个特定的应用场景:

@example
>>> with patch('__main__.Something', autospec=True, spec_set=True):
...   thing = Something()
...   thing.a = 33
...
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'a'
@end example

解决此问题的最好方式可能是添加类属性作为在 @ref{e2b,,__init__()} 中初始化的实例属性的默认值。 请注意如果你只在 @ref{e2b,,__init__()} 中设置默认属性那么通过类属性来提供它们（当然会在实例之间共享）也将有更快的速度。 例如

@example
class Something:
    a = 33
@end example

这带来了另一个问题。 为今后将变为不同类型对象的那些成员提供默认值 @code{None} 是比较常见的做法。 @code{None} 作为 spec 是没有用处的，因为它会使你无法访问 @emph{any} 任何属性或方法。 由于 @code{None} 作为 spec 将 @emph{永远不会} 有任何用处，并且有可能要指定某个通常为其他类型的成员，因此 autospec 不会为被设为 @code{None} 的成员使用 spec。 它们将为普通的 mock (嗯 —— 应为 MagicMocks):

@example
>>> class Something:
...     member = None
...
>>> mock = create_autospec(Something)
>>> mock.member.foo.bar.baz()
<MagicMock name='mock.member.foo.bar.baz()' id='...'>
@end example

如果你不喜欢修改你的生产类来添加默认值那么还有其他的选项。 其中之一是简单地使用一个实例而非类作为 spec。 另一选项则是创建一个生产类的子类并向该子类添加默认值而不影响到生产类。 这两个选项都需要你使用一个替代对象作为 spec。 值得庆幸的是 @ref{881,,patch()} 支持这样做 —— 你可以简单地传入替代对象作为 @emph{autospec} 参数:

@example
>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> class SomethingForTest(Something):
...   a = 33
...
>>> p = patch('__main__.Something', autospec=SomethingForTest)
>>> mock = p.start()
>>> mock.a
<NonCallableMagicMock name='Something.a' spec='int' id='...'>
@end example

@node 将 mock 封包,,自动 spec,辅助对象
@anchor{library/unittest mock sealing-mocks}@anchor{3449}
@subsubsection 将 mock 封包


@c from unittest.mock import seal

@geindex seal() (在 unittest.mock 模块中)
@anchor{library/unittest mock unittest mock seal}@anchor{518}
@deffn {函数} unittest.mock.seal (mock)

封包将在访问被封包的 mock 的属性或其任何已经被递归地模拟的属性时禁止自动创建 mock。

如果一个带有名称或 spec 的 mock 实例被分配给一个属性则将不会在封包链中处理它。 这可以防止人们对 mock 对象的固定部分执行封包。

@example
>>> mock = Mock()
>>> mock.submock.attribute1 = 2
>>> mock.not_submock = mock.Mock(name="sample_name")
>>> seal(mock)
>>> mock.new_attribute  # This will raise AttributeError.
>>> mock.submock.attribute2  # This will raise AttributeError.
>>> mock.not_submock.attribute2  # This won't raise.
@end example


3.7 新版功能.

@end deffn

@node unittest mock 上手指南,2to3 - 自动将 Python 2 代码转为 Python 3 代码,unittest mock --- mock对象库,开发工具
@anchor{library/unittest mock-examples doc}@anchor{344a}@anchor{library/unittest mock-examples unittest-mock-getting-started}@anchor{344b}
@subsection @code{unittest.mock} 上手指南



3.3 新版功能.

@anchor{library/unittest mock-examples getting-started}@anchor{344c}
@c import asyncio
@c import unittest
@c from unittest.mock import Mock, MagicMock, AsyncMock, patch, call, sentinel
@c 
@c class SomeClass:
@c     attribute = 'this is a doctest'
@c 
@c     @staticmethod
@c     def static_method():
@c         pass

@menu
* 使用 mock:: 
* 补丁装饰器:: 
* 更多示例:: 

@end menu

@node 使用 mock,补丁装饰器,,unittest mock 上手指南
@anchor{library/unittest mock-examples using-mock}@anchor{344d}
@subsubsection 使用 mock


@menu
* 模拟方法调用:: 
* 对象上的方法调用的 mock:: 
* 模拟类:: 
* 命名你的 mock:: 
* 追踪所有的调用:: 
* 设置返回值和属性:: 
* 通过 mock 引发异常:: 
* 附带影响函数和可迭代对象:: 
* 模拟异步迭代器:: 
* 模拟异步上下文管理器:: 
* 基于现有对象创建模拟对象:: 

@end menu

@node 模拟方法调用,对象上的方法调用的 mock,,使用 mock
@anchor{library/unittest mock-examples mock-patching-methods}@anchor{344e}
@subsubsection 模拟方法调用


使用 @ref{37a,,Mock} 的常见场景：


@itemize *

@item 
模拟函数调用

@item 
记录“对象上的方法调用”
@end itemize

你可能需要替换一个对象上的方法，用于确认此方法被系统中的其他部分调用过，并且调用时使用了正确的参数。

@example
>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')
<MagicMock name='method()' id='...'>
@end example

使用了 mock（本例中的 @code{real.method}）之后，它有方法和属性可以让你针对它是被如何使用的下断言。

@cartouche
@quotation 注解 
在多数示例中，@ref{37a,,Mock} 与 @ref{87e,,MagicMock} 两个类可以相互替换，而 @code{MagicMock} 是一个更适用的类，通常情况下，使用它就可以了。
@end quotation
@end cartouche

如果 mock 被调用，它的 @ref{3417,,called} 属性就会变成 @code{True}，更重要的是，我们可以使用 @ref{1183,,assert_called_with()} 或者 @ref{340d,,assert_called_once_with()} 方法来确认它在被调用时使用了正确的参数。

在如下的测试示例中，验证对于 @code{ProductionClass().method} 的调用会导致 @code{something} 的调用。

@example
>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
@end example

@node 对象上的方法调用的 mock,模拟类,模拟方法调用,使用 mock
@anchor{library/unittest mock-examples mock-for-method-calls-on-an-object}@anchor{344f}
@subsubsection 对象上的方法调用的 mock


上一个例子中我们直接在对象上给方法打补丁以检查它是否被正确地调用。 另一个常见的用例是将一个对象传给一个方法（或被测试系统的某个部分）然后检查它是否以正确的方式被使用。

下面这个简单的 @code{ProductionClass} 具有一个 @code{closer} 方法。 如果它附带一个对象被调用那么它就会调用其中的 @code{close}。

@example
>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...
@end example

所以为了测试它我们需要传入一个带有 @code{close} 方法的对象并检查它是否被正确地调用。

@example
>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()
@end example

我们不需要做任何事来在我们的 mock 上提供 'close' 方法。 访问 close 的操作就会创建它。 因此，如果 'close' 还未被调用那么在测试时访问它就将创建它，但是 @ref{1183,,assert_called_with()} 则会引发一个失败的异常。

@node 模拟类,命名你的 mock,对象上的方法调用的 mock,使用 mock
@anchor{library/unittest mock-examples mocking-classes}@anchor{3450}
@subsubsection 模拟类


一个常见的用例是模拟被测试的代码所实例化的类。 当你给一个类打上补丁，该类就会被替换为一个 mock。 实例是通过 @emph{该用该类} 来创建的。 这意味着你要通过查看被模拟类的返回值来访问 "mock 实例"。

在下面的例子中我们有一个函数 @code{some_function} 实例化了 @code{Foo} 并调用该实例中的一个方法。 对 @ref{881,,patch()} 的调用会将类 @code{Foo} 替换为一个 mock。 @code{Foo} 实例是调用该 mock 的结果，所以它是通过修改 @ref{340b,,return_value} 来配置的。

@example
>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'
@end example

@node 命名你的 mock,追踪所有的调用,模拟类,使用 mock
@anchor{library/unittest mock-examples naming-your-mocks}@anchor{3451}
@subsubsection 命名你的 mock


给你的 mock 起个名字可能会很有用。 名字会显示在 mock 的 repr 中并在 mock 出现于测试失败消息中时可以帮助理解。 这个名字也会被传播给 mock 的属性或方法:

@example
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'>
@end example

@node 追踪所有的调用,设置返回值和属性,命名你的 mock,使用 mock
@anchor{library/unittest mock-examples tracking-all-calls}@anchor{3452}
@subsubsection 追踪所有的调用


通常你会想要追踪对某个方法的多次调用。 @ref{3410,,mock_calls} 属性记录了所有对 mock 的子属性的调用 —— 并且还包括对它们的子属性的调用。

@example
>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='...'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='...'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]
@end example

如果你做了一个有关 @code{mock_calls} 的断言并且有任何非预期的方法被调用，则断言将失败。 这很有用处，因为除了断言你所预期的调用已被执行，你还会检查它们是否以正确的顺序被执行并且没有额外的调用:

你使用 @ref{1115,,call} 对象来构造列表以便与 @code{mock_calls} 进行比较:

@example
>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True
@end example

然而，返回 mock 的调用的形参不会被记录，这意味着不可能追踪附带了重要形参的创建上级对象的嵌套调用:

@example
>>> m = Mock()
>>> m.factory(important=True).deliver()
<Mock name='mock.factory().deliver()' id='...'>
>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True
@end example

@node 设置返回值和属性,通过 mock 引发异常,追踪所有的调用,使用 mock
@anchor{library/unittest mock-examples setting-return-values-and-attributes}@anchor{3453}
@subsubsection 设置返回值和属性


在 mock 对象上设置返回值是非常容易的:

@example
>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3
@end example

当然你也可以对 mock 上的方法做同样的操作:

@example
>>> mock = Mock()
>>> mock.method.return_value = 3
>>> mock.method()
3
@end example

返回值也可以在构造器中设置:

@example
>>> mock = Mock(return_value=3)
>>> mock()
3
@end example

如果你需要在你的 mock 上设置一个属性，只需这样做:

@example
>>> mock = Mock()
>>> mock.x = 3
>>> mock.x
3
@end example

有时你会想要模拟更复杂的情况，例如这个例子 @code{mock.connection.cursor().execute("SELECT 1")}。 如果我们希望这个调用返回一个列表，那么我们还必须配置嵌套调用的结果。

我们可以像这样使用 @ref{1115,,call} 在一个“链式调用”中构造调用集合以便随后方便地设置断言:

@example
>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cursor().execute("SELECT 1").call_list()
>>> mock.mock_calls
[call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
>>> mock.mock_calls == expected
True
@end example

对 @code{.call_list()} 的调用会将我们的调用对象转成一个代表链式调用的调用列表。

@node 通过 mock 引发异常,附带影响函数和可迭代对象,设置返回值和属性,使用 mock
@anchor{library/unittest mock-examples raising-exceptions-with-mocks}@anchor{3454}
@subsubsection 通过 mock 引发异常


一个很有用的属性是 @ref{3409,,side_effect}。 如果你将该属性设为一个异常类或者实例那么当 mock 被调用时该异常将会被引发。

@example
>>> mock = Mock(side_effect=Exception('Boom!'))
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!
@end example

@node 附带影响函数和可迭代对象,模拟异步迭代器,通过 mock 引发异常,使用 mock
@anchor{library/unittest mock-examples side-effect-functions-and-iterables}@anchor{3455}
@subsubsection 附带影响函数和可迭代对象


@code{side_effect} 也可以被设为一个函数或可迭代对象。 @code{side_effect} 作为可迭代对象的应用场景适用于你的 mock 将要被多次调用，并且你希望每次调用都返回不同的值的情况。 当你将 @code{side_effect} 设为一个可迭代对象时每次对 mock 的调用将返回可迭代对象的下一个值。

@example
>>> mock = MagicMock(side_effect=[4, 5, 6])
>>> mock()
4
>>> mock()
5
>>> mock()
6
@end example

对于更高级的用例，例如根据 mock 调用时附带的参数动态改变返回值，@code{side_effect} 可以指定一个函数。 该函数将附带与 mock 相同的参数被调用。 该函数所返回的就是调用所返回的对象:

@example
>>> vals = @{(1, 2): 1, (2, 3): 2@}
>>> def side_effect(*args):
...     return vals[args]
...
>>> mock = MagicMock(side_effect=side_effect)
>>> mock(1, 2)
1
>>> mock(2, 3)
2
@end example

@node 模拟异步迭代器,模拟异步上下文管理器,附带影响函数和可迭代对象,使用 mock
@anchor{library/unittest mock-examples mocking-asynchronous-iterators}@anchor{3456}
@subsubsection 模拟异步迭代器


从 Python 3.8 起，@code{AsyncMock} 和 @code{MagicMock} 支持通过 @code{__aiter__} 来模拟 @ref{743,,异步迭代器}。 @code{__aiter__} 的 @ref{340b,,return_value} 属性可以被用来设置要用于迭代的返回值。

@example
>>> mock = MagicMock()  # AsyncMock also works here
>>> mock.__aiter__.return_value = [1, 2, 3]
>>> async def main():
...     return [i async for i in mock]
...
>>> asyncio.run(main())
[1, 2, 3]
@end example

@node 模拟异步上下文管理器,基于现有对象创建模拟对象,模拟异步迭代器,使用 mock
@anchor{library/unittest mock-examples mocking-asynchronous-context-manager}@anchor{3457}
@subsubsection 模拟异步上下文管理器


从 Python 3.8 起，@code{AsyncMock} 和 @code{MagicMock} 支持通过 @code{__aenter__} 和 @code{__aexit__} 来模拟 @ref{1601,,异步上下文管理器}。 在默认情况下，@code{__aenter__} 和 @code{__aexit__} 将为返回异步函数的 @code{AsyncMock} 实例。

@example
>>> class AsyncContextManager:
...     async def __aenter__(self):
...         return self
...     async def __aexit__(self, exc_type, exc, tb):
...         pass
...
>>> mock_instance = MagicMock(AsyncContextManager())  # AsyncMock also works here
>>> async def main():
...     async with mock_instance as result:
...         pass
...
>>> asyncio.run(main())
>>> mock_instance.__aenter__.assert_awaited_once()
>>> mock_instance.__aexit__.assert_awaited_once()
@end example

@node 基于现有对象创建模拟对象,,模拟异步上下文管理器,使用 mock
@anchor{library/unittest mock-examples creating-a-mock-from-an-existing-object}@anchor{3458}
@subsubsection 基于现有对象创建模拟对象


使用模拟操作的一个问题是它会将你的测试与你的 mock 实现相关联而不是与你的真实代码相关联。 假设你有一个实现了 @code{some_method} 的类。 在对另一个类的测试中，你提供了一个 @emph{同样} 提供了 @code{some_method} 的模拟该对象的 mock 对象。 如果后来你重构了第一个类，使得它不再具有 @code{some_method} —— 那么你的测试将继续保持通过，尽管现在你的代码已经被破坏了！

@ref{37a,,Mock} 允许你使用allows you to provide an object as a specification for the mock, using the @emph{spec} 关键字参数来提供一个对象作为 mock 的规格说明。 在 mock 上访问不存在于你的规格说明对象中的方法 / 属性将立即引发一个属性错误。 如果你修改你的规格说明的实现，，那么使用了该类的测试将立即开始失败而不需要你在这些测试中实例化该类。

@example
>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
   ...
AttributeError: object has no attribute 'old_method'
@end example

使用规格说明还可以启用对 mock 的调用的更聪明的匹配操作，无论是否有将某些形参作为位置或关键字参数传入:

@example
>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, 3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(a=1, b=2, c=3)
@end example

如果你想要让这些更聪明的匹配操作也适用于 mock 上的方法调用，你可以使用 @ref{3405,,auto-speccing}。

如果你想要更强形式的规格说明以防止设置任意属性并获取它们那么你可以使用 @emph{spec_set} 来代替 @emph{spec}。

@node 补丁装饰器,更多示例,使用 mock,unittest mock 上手指南
@anchor{library/unittest mock-examples patch-decorators}@anchor{3459}
@subsubsection 补丁装饰器


@cartouche
@quotation 注解 
在查找对象的名称空间中修补对象使用 @ref{881,,patch()} 。使用起来很简单，阅读 @ref{3403,,在哪里打补丁} 来快速上手。
@end quotation
@end cartouche

测试中的一个常见需求是为类属性或模块属性打补丁，例如修补内置对象或修补某个模块中的类来测试其是否被实例化。 模块和类都可算是全局对象，因此对它们打补丁的操作必须在测试完成之后被还原否则补丁将持续影响其他测试并导致难以诊断的问题。

为此 mock 提供了三个便捷的装饰器: @ref{881,,patch()}, @ref{10fd,,patch.object()} 和 @ref{1153,,patch.dict()}。 @code{patch} 接受单个字符串，其形式 @code{package.module.Class.attribute} 指明你要修补的属性。 它还可选择接受一个值用来替换指定的属性（或者类对象等等）。 'patch.object' 接受一个对象和你想要修补的属性名称，并可选择接受要用作补丁的值。

@code{patch.object}:

@example
>>> original = SomeClass.attribute
>>> @@patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test():
...     assert SomeClass.attribute == sentinel.attribute
...
>>> test()
>>> assert SomeClass.attribute == original

>>> @@patch('package.module.attribute', sentinel.attribute)
... def test():
...     from package.module import attribute
...     assert attribute is sentinel.attribute
...
>>> test()
@end example

如果你要给一个模块 (包括 @ref{12,,builtins}) 打补丁则可使用 @ref{881,,patch()} 来代替 @ref{10fd,,patch.object()}:

@example
>>> mock = MagicMock(return_value=sentinel.file_handle)
>>> with patch('builtins.open', mock):
...     handle = open('filename', 'r')
...
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"
@end example

如有必要模块名可以是“带点号”的，其形式如 @code{package.module}:

@example
>>> @@patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
...     from package.module import ClassName
...     assert ClassName.attribute == sentinel.attribute
...
>>> test()
@end example

一个良好的模式是实际地装饰测试方法本身:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch.object(SomeClass, 'attribute', sentinel.attribute)
...     def test_something(self):
...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
...
>>> original = SomeClass.attribute
>>> MyTest('test_something').test_something()
>>> assert SomeClass.attribute == original
@end example

如果你想要通过 Mock 来打补丁，你可以只附带一个参数使用 @ref{881,,patch()} (或附带两个参数使用 @ref{10fd,,patch.object()})。 这将为你创建 mock 并传递给测试函数 / 方法:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch.object(SomeClass, 'static_method')
...     def test_something(self, mock_method):
...         SomeClass.static_method()
...         mock_method.assert_called_with()
...
>>> MyTest('test_something').test_something()
@end example

你可以使用以下模式来堆叠多个补丁装饰器:

@example
>>> class MyTest(unittest.TestCase):
...     @@patch('package.module.ClassName1')
...     @@patch('package.module.ClassName2')
...     def test_something(self, MockClass2, MockClass1):
...         self.assertIs(package.module.ClassName1, MockClass1)
...         self.assertIs(package.module.ClassName2, MockClass2)
...
>>> MyTest('test_something').test_something()
@end example

当你嵌套 patch 装饰器时将以它们被应用的相同顺序（即 @emph{Python} 应用装饰器的正常顺序）将 mock 传入被装饰的函数。 也就是说从下往上，因此在上面的示例中 @code{test_module.ClassName2} 的 mock 会被最先传入。

还有一个 @ref{1153,,patch.dict()} 用于在一定范围内设置字典中的值，并在测试结束时将字典恢复为其原始状态：

@example
>>> foo = @{'key': 'value'@}
>>> original = foo.copy()
>>> with patch.dict(foo, @{'newkey': 'newvalue'@}, clear=True):
...     assert foo == @{'newkey': 'newvalue'@}
...
>>> assert foo == original
@end example

@code{patch}, @code{patch.object} 和 @code{patch.dict} 都可被用作上下文管理器。

在你使用 @ref{881,,patch()} 为你创建 mock 时，你可以使用 with 语句的 "as" 形式来获得对 mock 的引用:

@example
>>> class ProductionClass:
...     def method(self):
...         pass
...
>>> with patch.object(ProductionClass, 'method') as mock_method:
...     mock_method.return_value = None
...     real = ProductionClass()
...     real.method(1, 2, 3)
...
>>> mock_method.assert_called_with(1, 2, 3)
@end example

作为替代 @code{patch}, @code{patch.object} 和 @code{patch.dict} 可以被用作类装饰器。 当以此方式使用时其效果与将装饰器单独应用到每个以 "test" 打头的方法上相同。

@node 更多示例,,补丁装饰器,unittest mock 上手指南
@anchor{library/unittest mock-examples further-examples}@anchor{345a}@anchor{library/unittest mock-examples id1}@anchor{345b}
@subsubsection 更多示例


下面是一些针对更为高级应用场景的补充示例。

@menu
* 模拟链式调用:: 
* 部分模拟:: 
* 模拟生成器方法:: 
* 对每个测试方法应用相同的补丁:: 
* 模拟未绑定方法:: 
* 通过 mock 检查多次调用:: 
* 处理可变参数:: 
* 嵌套补丁:: 
* 使用 MagicMock 模拟字典:: 
* 模拟子类及其属性:: 
* 通过 patch.dict 模拟导入: 通过 patch dict 模拟导入. 
* 追踪调用顺序和不太冗长的调用断言:: 
* 更复杂的参数匹配:: 

@end menu

@node 模拟链式调用,部分模拟,,更多示例
@anchor{library/unittest mock-examples mocking-chained-calls}@anchor{345c}
@subsubsection 模拟链式调用


实际上一旦你理解了 @ref{340b,,return_value} 属性那么使用 mock 模拟链式调用就会相当直观。 当一个 mock 首次被调用，或者当你在它被调用前获取其 @code{return_value} 时，将会创建一个新的 @ref{37a,,Mock}。

这意味着你可以通过检视 @code{return_value} mock 来了解从调用被模拟对象返回的对象是如何被使用的:

@example
>>> mock = Mock()
>>> mock().foo(a=2, b=3)
<Mock name='mock().foo()' id='...'>
>>> mock.return_value.foo.assert_called_with(a=2, b=3)
@end example

从这里开始只需一个步骤即可配置并创建有关链式调用的断言。 当然还有另一种选择是首先以更易于测试的方式来编写你的代码...

因此，如果我们有这样一些代码:

@example
>>> class Something:
...     def __init__(self):
...         self.backend = BackendProvider()
...     def method(self):
...         response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
...         # more code
@end example

假定 @code{BackendProvider} 已经过良好测试，我们要如何测试 @code{method()}？ 特别地，我们希望测试代码段 @code{# more code} 是否以正确的方式使用了响应对象。

由于这个链式调用来自一个实例属性我们可以对 @code{backend} 属性在 @code{Something} 实例上进行猴子式修补。 在这个特定情况下我们只对最后调用 @code{start_call} 的返回值感兴趣所以我们不需要进行太多的配置。 让我们假定它返回的是“文件类”对象，因此我们将确保我们的响应对象使用内置的 @ref{16f,,open()} 作为其 @code{spec}。

为了做到这一点我们创建一个 mock 实例作为我们的 mock 后端并为它创建一个 mock 响应对象。 要将该响应对象设为最后的 @code{start_call} 的返回值我们可以这样做:

@example
mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
@end example

我们可以通过更好一些的方式做到这一点，即使用 @ref{340c,,configure_mock()} 方法直接为我们设置返回值:

@example
>>> something = Something()
>>> mock_response = Mock(spec=open)
>>> mock_backend = Mock()
>>> config = @{'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response@}
>>> mock_backend.configure_mock(**config)
@end example

有了这些我们就能准备好给“mock 后端”打上猴子补丁并可以执行真正的调用:

@example
>>> something.backend = mock_backend
>>> something.method()
@end example

使用 @ref{3410,,mock_calls} 我们可以通过一个断言来检查链式调用。 一个链式调用就是在一行代码中连续执行多个调用，所以在 @code{mock_calls} 中将会有多个条目。 我们可以使用 @ref{3443,,call.call_list()} 来为我们创建这个调用列表:

@example
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list
@end example

@node 部分模拟,模拟生成器方法,模拟链式调用,更多示例
@anchor{library/unittest mock-examples partial-mocking}@anchor{345d}
@subsubsection 部分模拟


在某些测试中我希望模拟对 @ref{1a32,,datetime.date.today()} 的调用以返回一个已知的日期，但我又不想阻止被测试的代码创建新的日期对象。 很不幸 @ref{19d,,datetime.date} 是用 C 语言编写的，因此我不能简单地给静态的 @code{date.today()} 方法打上猴子补丁。

我找到了实现这一点的简单方式即通过一个 mock 来实际包装日期类，但通过对构造器的调用传递给真实的类（并返回真实的实例）。

这里使用 @ref{881,,patch 装饰器} 来模拟被测试模块中的 @code{date} 类。 模拟 date 类中的 @code{side_effect} 属性随后被设为一个返回真实日期的 lambda 函数。 当模拟 date 类被调用时将由 @code{side_effect} 构造并返回一个真实日期。

@example
>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
@end example

请注意我们没有在全局范围上修补 @ref{19d,,datetime.date}，我们只是在 @emph{使用} 它的模块中给 @code{date} 打补丁。 参见 @ref{3403,,补丁的位置}。

当 @code{date.today()} 被调用时将返回一个已知的日期，但对 @code{date(...)} 构造器的调用仍会返回普通的日期。 如果不是这样你会发现你必须使用与被测试的代码完全相同的算法来计算出预期的结果，这是测试工作中的一个经典的反模式。

对 date 构造器的调用会被记录在 @code{mock_date} 属性中 (@code{call_count} 等)，它们也可能对你的测试有用处。

有关处理模块日期或其他内置类的一种替代方式的讨论请参见 这篇博客文章@footnote{https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/}。

@node 模拟生成器方法,对每个测试方法应用相同的补丁,部分模拟,更多示例
@anchor{library/unittest mock-examples mocking-a-generator-method}@anchor{345e}
@subsubsection 模拟生成器方法


Python 生成器是指在被迭代时使用 @ref{2ce,,yield} 语句来返回一系列值的函数或方法 @footnote{@w{(1)} 
此外还有生成器表达式和更多的生成器 @uref{http://www.dabeaz.com/coroutines/index.html,进阶用法}，但在这里我们不去关心它们。 有关生成器及其强大功能的一个很好的介绍请参阅: @uref{http://www.dabeaz.com/generators/,针对系统程序员的生成器妙招}。
}。

调用生成器方法 / 函数将返回生成器对象。 生成器对象随后会被迭代。 迭代操作对应的协议方法是 @ref{178d,,__iter__()}，因此我们可以使用 @ref{87e,,MagicMock} 来模拟它。

以下是一个使用 "iter" 方法模拟为生成器的示例类:

@example
>>> class Foo:
...     def iter(self):
...         for i in [1, 2, 3]:
...             yield i
...
>>> foo = Foo()
>>> list(foo.iter())
[1, 2, 3]
@end example

我们要如何模拟这个类，特别是它的 "iter" 方法呢？

为了配置从迭代操作（隐含在对 @ref{1f9,,list} 的调用中）返回的值，我们需要配置调用 @code{foo.iter()} 所返回的对象。

@example
>>> mock_foo = MagicMock()
>>> mock_foo.iter.return_value = iter([1, 2, 3])
>>> list(mock_foo.iter())
[1, 2, 3]
@end example

@node 对每个测试方法应用相同的补丁,模拟未绑定方法,模拟生成器方法,更多示例
@anchor{library/unittest mock-examples applying-the-same-patch-to-every-test-method}@anchor{345f}
@subsubsection 对每个测试方法应用相同的补丁


如果你想要为多个测试方法准备好一些补丁那么最简单的方式就是将 patch 装饰器应用到每个方法。 这在感觉上会造成不必要的重复。 对于 Python 2.6 或更新的版本你可以使用 @ref{881,,patch()} (其所有不同的形式) 作为类装饰器。 这将把补丁应用于类中的所有测试方法。 测试方法是通过名称前缀为 @code{test} 来标识的:

@example
>>> @@patch('mymodule.SomeClass')
... class MyTest(unittest.TestCase):
...
...     def test_one(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def test_two(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def not_a_test(self):
...         return 'something'
...
>>> MyTest('test_one').test_one()
>>> MyTest('test_two').test_two()
>>> MyTest('test_two').not_a_test()
'something'
@end example

另一种管理补丁的方式是使用 @ref{3435,,补丁方法; start 和 stop}。 它允许你将打补丁操作移至你的 @code{setUp} 和 @code{tearDown} 方法中。

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         self.patcher = patch('mymodule.foo')
...         self.mock_foo = self.patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
...     def tearDown(self):
...         self.patcher.stop()
...
>>> MyTest('test_foo').run()
@end example

如果你要使用这个技巧则你必须通过调用 @code{stop} 来确保补丁被“恢复”。 这可能要比你想像的更麻烦，因为如果在 setUp 中引发了异常那么 tearDown 将不会被调用。 @ref{3cd,,unittest.TestCase.addCleanup()} 可以做到更方便:

@example
>>> class MyTest(unittest.TestCase):
...     def setUp(self):
...         patcher = patch('mymodule.foo')
...         self.addCleanup(patcher.stop)
...         self.mock_foo = patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
>>> MyTest('test_foo').run()
@end example

@node 模拟未绑定方法,通过 mock 检查多次调用,对每个测试方法应用相同的补丁,更多示例
@anchor{library/unittest mock-examples mocking-unbound-methods}@anchor{3460}
@subsubsection 模拟未绑定方法


当前在编写测试时我需要修补一个 @emph{未绑定方法} (在类上而不是在实例上为方法打补丁)。 我需要将 self 作为第一个参数传入因为我想对哪些对象在调用这个特定方法进行断言。 问题是这里你不能用 mock 来打补丁，因为如果你用 mock 来替换一个未绑定方法那么当从实例中获取时它就不会成为一个已绑定方法，因而它不会获得传入的 self。 绕过此问题的办法是改用一个真正的函数来修补未绑定方法。 @ref{881,,patch()} 装饰器让使用 mock 来给方法打补丁变得如此简单以至于创建一个真正的函数成为一件麻烦事。

如果将 @code{autospec=True} 传给 patch 那么它就会用一个 @emph{真正的} 函数对象来打补丁。 这个函数对象具有与它所替换的函数相同的签名，但会在内部将操作委托给一个 mock。 你仍然可以通过与以前完全相同的方式来自动创建你的 mock。 但是这将意味着一件事，就是如果你用它来修补一个类上的非绑定方法那么如果它是从一个实例中获取则被模拟的函数将被转为已绑定方法。 传给它的第一个参数将为 @code{self}，而这真是我想要的:

@example
>>> class Foo:
...   def foo(self):
...     pass
...
>>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
...   mock_foo.return_value = 'foo'
...   foo = Foo()
...   foo.foo()
...
'foo'
>>> mock_foo.assert_called_once_with(foo)
@end example

如果我们不使用 @code{autospec=True} 那么这个未绑定方法会改为通过一个 Mock 补丁来修补，而不是附带 @code{self} 来调用。

@node 通过 mock 检查多次调用,处理可变参数,模拟未绑定方法,更多示例
@anchor{library/unittest mock-examples checking-multiple-calls-with-mock}@anchor{3461}
@subsubsection 通过 mock 检查多次调用


mock 有一个很好的 API 用于针对你的 mock 对象如何被使用来下断言。

@example
>>> mock = Mock()
>>> mock.foo_bar.return_value = None
>>> mock.foo_bar('baz', spam='eggs')
>>> mock.foo_bar.assert_called_with('baz', spam='eggs')
@end example

如果你的 mock 只会被调用一次你可以使用 @code{assert_called_once_with()} 方法，这也将断言 @code{call_count} 为一。

@example
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most recent call last):
    ...
AssertionError: Expected to be called once. Called 2 times.
@end example

@code{assert_called_with} 和 @code{assert_called_once_with} 都是有关 @emph{最近} 调用的断言。 如果你的 mock 将被多次调用，并且你想要针对 @emph{所有} 这些调用下断言你可以使用 @ref{3419,,call_args_list}:

@example
>>> mock = Mock(return_value=None)
>>> mock(1, 2, 3)
>>> mock(4, 5, 6)
>>> mock()
>>> mock.call_args_list
[call(1, 2, 3), call(4, 5, 6), call()]
@end example

使用 @ref{1115,,call} 辅助对象可以方便地针对这些调用下断言。 你可以创建一个预期调用的列表并将其与 @code{call_args_list} 比较。 这看起来与 @code{call_args_list} 的 repr 非常相似:

@example
>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True
@end example

@node 处理可变参数,嵌套补丁,通过 mock 检查多次调用,更多示例
@anchor{library/unittest mock-examples coping-with-mutable-arguments}@anchor{3462}
@subsubsection 处理可变参数


另一种很少见，但可能给你带来麻烦的情况会在你的 mock 附带可变参数被调用的时候发生。 @code{call_args} 和 @code{call_args_list} 将保存对这些参数的 @emph{引用}。 如果这些参数被受测试的代码所改变那么你将无法再针对当该 mock 被调用时附带的参数值下断言。

下面是一些演示此问题的示例代码。 设想在 'mymodule' 中定义了下列函数:

@example
def frob(val):
    pass

def grob(val):
    "First frob and then clear val"
    frob(val)
    val.clear()
@end example

当我们想要测试 @code{grob} 调用 @code{frob} 并附带了正确的参数时将可看到发生了什么:

@example
>>> with patch('mymodule.frob') as mock_frob:
...     val = @{6@}
...     mymodule.grob(val)
...
>>> val
set()
>>> mock_frob.assert_called_with(@{6@})
Traceback (most recent call last):
    ...
AssertionError: Expected: ((@{6@},), @{@})
Called with: ((set(),), @{@})
@end example

对于 mock 的一个可能性是复制你传入的参数。 如果你创建依赖于对象标识号相等性的断言那么这可能会在后面导致问题。

下面是一个使用 @code{side_effect} 功能的解决方案。 如果你为 mock 提供了 @code{side_effect} 函数那么 @code{side_effect} 将附带与该 mock 相同的参数被调用。 这使我们有机会拷贝这些参数并保存它们用于之后进行断言。 在这个例子中我使用了 @emph{另一个} mock 来保存参数以便我可以使用该 mock 的方法来进行断言。 在这里辅助函数再次为我设置好了所需的功能。

@example
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
...     new_mock = Mock()
...     def side_effect(*args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         new_mock(*args, **kwargs)
...         return DEFAULT
...     mock.side_effect = side_effect
...     return new_mock
...
>>> with patch('mymodule.frob') as mock_frob:
...     new_mock = copy_call_args(mock_frob)
...     val = @{6@}
...     mymodule.grob(val)
...
>>> new_mock.assert_called_with(@{6@})
>>> new_mock.call_args
call(@{6@})
@end example

调用 @code{copy_call_args} 时会传入将被调用的 mock。 它将返回一个新的 mock 供我们进行断言。 @code{side_effect} 函数会拷贝这些参数并附带该副本来调用我们的 @code{new_mock}。

@cartouche
@quotation 注解 
如果你的 mock 只会被使用一次那么有更容易的方式可以在它们被调用时检查参数。 你可以简单地在 @code{side_effect} 函数中执行检查。

@example
>>> def side_effect(arg):
...     assert arg == @{6@}
...
>>> mock = Mock(side_effect=side_effect)
>>> mock(@{6@})
>>> mock(set())
Traceback (most recent call last):
    ...
AssertionError
@end example
@end quotation
@end cartouche

一个替代方式是创建一个 @ref{37a,,Mock} 或 @ref{87e,,MagicMock}  的子类来拷贝 (使用 @ref{4db,,copy.deepcopy()}) 参数。 下面是一个示例实现:

@example
>>> from copy import deepcopy
>>> class CopyingMock(MagicMock):
...     def __call__(self, /, *args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         return super().__call__(*args, **kwargs)
...
>>> c = CopyingMock(return_value=None)
>>> arg = set()
>>> c(arg)
>>> arg.add(1)
>>> c.assert_called_with(set())
>>> c.assert_called_with(arg)
Traceback (most recent call last):
    ...
AssertionError: Expected call: mock(@{1@})
Actual call: mock(set())
>>> c.foo
<CopyingMock name='mock.foo' id='...'>
@end example

当你子类化 @code{Mock} 或 @code{MagicMock} 时所有动态创建的属性以及 @code{return_value} 都将自动使用你的子类。 这意味着 @code{CopyingMock} 的所有子类也都将为 @code{CopyingMock} 类型。

@node 嵌套补丁,使用 MagicMock 模拟字典,处理可变参数,更多示例
@anchor{library/unittest mock-examples nesting-patches}@anchor{3463}
@subsubsection 嵌套补丁


使用 patch 作为上下文管理器很不错，但是如果你要执行多个补丁你将不断嵌套 with 语句使得代码越来越深地向右缩进:

@example
>>> class MyTest(unittest.TestCase):
...
...     def test_foo(self):
...         with patch('mymodule.Foo') as mock_foo:
...             with patch('mymodule.Bar') as mock_bar:
...                 with patch('mymodule.Spam') as mock_spam:
...                     assert mymodule.Foo is mock_foo
...                     assert mymodule.Bar is mock_bar
...                     assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').test_foo()
>>> assert mymodule.Foo is original
@end example

使用 unittest @code{cleanup} 函数和 @ref{3435,,补丁方法; start 和 stop} 我们可以达成同样的效果而无须嵌套缩进。 一个简单的辅助方法 @code{create_patch} 会为我们执行打补丁操作并返回所创建的 mock:

@example
>>> class MyTest(unittest.TestCase):
...
...     def create_patch(self, name):
...         patcher = patch(name)
...         thing = patcher.start()
...         self.addCleanup(patcher.stop)
...         return thing
...
...     def test_foo(self):
...         mock_foo = self.create_patch('mymodule.Foo')
...         mock_bar = self.create_patch('mymodule.Bar')
...         mock_spam = self.create_patch('mymodule.Spam')
...
...         assert mymodule.Foo is mock_foo
...         assert mymodule.Bar is mock_bar
...         assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').run()
>>> assert mymodule.Foo is original
@end example

@node 使用 MagicMock 模拟字典,模拟子类及其属性,嵌套补丁,更多示例
@anchor{library/unittest mock-examples mocking-a-dictionary-with-magicmock}@anchor{3464}
@subsubsection 使用 MagicMock 模拟字典


你可能会想要模拟一个字典或其他容器对象，记录所有对它的访问并让它的行为仍然像是一个字典。

要做到这点我们可以用 @ref{87e,,MagicMock}，它的行为类似于字典，并会使用 @ref{3409,,side_effect} 将字典访问委托给下层的在我们控制之下的一个真正的字典。

当我们的 @code{MagicMock} 的 @ref{3ad,,__getitem__()} 和 @ref{d32,,__setitem__()} 方法被调用（即普通的字典访问操作）时 @code{side_effect} 将附带键（对于 @code{__setitem__} 则还将附带值）被调用。 我们也可以控制返回的对象。

在 @code{MagicMock} 被使用之后我们可以使用 @ref{3419,,call_args_list} 等属性来针对该字典是如何被使用的下断言。

@example
>>> my_dict = @{'a': 1, 'b': 2, 'c': 3@}
>>> def getitem(name):
...      return my_dict[name]
...
>>> def setitem(name, val):
...     my_dict[name] = val
...
>>> mock = MagicMock()
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem
@end example

@cartouche
@quotation 注解 
@code{MagicMock} 的一个可用替代是使用 @code{Mock} 并 @emph{仅仅} 提供你明确需要的魔术方法:

@example
>>> mock = Mock()
>>> mock.__getitem__ = Mock(side_effect=getitem)
>>> mock.__setitem__ = Mock(side_effect=setitem)
@end example

@emph{第三个} 选项是使用 @code{MagicMock} 但传入 @code{dict} 作为 @emph{spec} (或 @emph{spec_set}) 参数以使得所创建的 @code{MagicMock} 只有字典魔术方法是可用的:

@example
>>> mock = MagicMock(spec_set=dict)
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem
@end example
@end quotation
@end cartouche

通过提供这些附带影响函数，@code{mock} 的行为将类似于普通字典但又会记录所有访问。 如果你尝试访问一个不存在的键它甚至会引发 @ref{3f1,,KeyError}。

@example
>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
    ...
KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
>>> mock['d']
'eggs'
@end example

在它被使用之后你可以使用普通的 mock 方法和属性进行有关访问操作的断言:

@example
>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
@{'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'@}
@end example

@node 模拟子类及其属性,通过 patch dict 模拟导入,使用 MagicMock 模拟字典,更多示例
@anchor{library/unittest mock-examples mock-subclasses-and-their-attributes}@anchor{3465}
@subsubsection 模拟子类及其属性


你可能出于各种原因想要子类化 @ref{37a,,Mock}。 其中一个可能的原因是为了添加辅助方法。 下面是一个笨兮兮的示例:

@example
>>> class MyMock(MagicMock):
...     def has_been_called(self):
...         return self.called
...
>>> mymock = MyMock(return_value=None)
>>> mymock
<MyMock id='...'>
>>> mymock.has_been_called()
False
>>> mymock()
>>> mymock.has_been_called()
True
@end example

The standard behaviour for @code{Mock} 实例的标准行为是属性和返回值 mock 具有与它们所访问的 mock 相同的类型。 这将确保 @code{Mock} 的属性均为 @code{Mocks} 而 @code{MagicMock} 的属性均为 @code{MagicMocks} @footnote{@w{(2)} 
此规则的一个例外涉及不可调用 mock。 属性会使用可调用对象版本是因为如非如此则不可调用 mock 将无法拥有可调用的方法。
}。 因此如果你通过子类化来添加辅助方法那么它们也将在你的子类的实例的属性和返回值 mock 上可用。

@example
>>> mymock.foo
<MyMock name='mock.foo' id='...'>
>>> mymock.foo.has_been_called()
False
>>> mymock.foo()
<MyMock name='mock.foo()' id='...'>
>>> mymock.foo.has_been_called()
True
@end example

有时这很不方便。 例如，有一位用户@footnote{https://code.google.com/archive/p/mock/issues/105} 子类化 mock 来创建一个 Twisted 适配器@footnote{https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html}。 将它也应用到属性实际上会导致出错。

@code{Mock} (它的所有形式) 使用一个名为 @code{_get_child_mock} 的方法来创建这些用于属性和返回值的“子 mock”。 你可以通过重载此方法来防止你的子类被用于属性。 其签名被设为接受任意关键字参数 (@code{**kwargs}) 并且它们会被传递给 mock 构造器:

@example
>>> class Subclass(MagicMock):
...     def _get_child_mock(self, /, **kwargs):
...         return MagicMock(**kwargs)
...
>>> mymock = Subclass()
>>> mymock.foo
<MagicMock name='mock.foo' id='...'>
>>> assert isinstance(mymock, Subclass)
>>> assert not isinstance(mymock.foo, Subclass)
>>> assert not isinstance(mymock(), Subclass)
@end example

@node 通过 patch dict 模拟导入,追踪调用顺序和不太冗长的调用断言,模拟子类及其属性,更多示例
@anchor{library/unittest mock-examples mocking-imports-with-patch-dict}@anchor{3466}
@subsubsection 通过 patch.dict 模拟导入


有一种会令模拟变困难的情况是当你在函数内部有局部导入。 这更难模拟的原因是它们不是使用来自我们能打补丁的模拟命名空间中的对象。

一般来说局部导入是应当避免的。 局部导入有时是为了防止循环依赖，而这个问题 @emph{通常} 都有更好的解决办法（重构代码）或者通过延迟导入来防止“前期成本”。 这也可以通过比无条件地局部导入更好的方式来解决（将模块保存为一个类或模块属性并且只在首次使用时执行导入）。

除此之外还有一个办法可以使用 @code{mock} 来影响导入的结果。 导入操作会从 @ref{109a,,sys.modules} 字典提取一个 @emph{对象}。 请注意是提取一个 @emph{对象}，不是必须为模块。 首次导入一个模块将使一个模块对象被放入 @cite{sys.modules}，因此通常当你执行导入时你将得到一个模块。 然而这并不是必然的。

这意味着你可以使用 @ref{1153,,patch.dict()} 来 @emph{临时性地} 将一个 mock 放入 @ref{109a,,sys.modules}。 在补丁激活期间的任何导入操作都将得到该 mock。 当补丁完成时（被装饰的函数退出，with 语句代码块结束或者 @code{patcher.stop()} 被调用）则之前存在的任何东西都将被安全地恢复。

下面是一个模拟 'fooble' 模拟的示例。

@example
>>> import sys
>>> mock = Mock()
>>> with patch.dict('sys.modules', @{'fooble': mock@}):
...    import fooble
...    fooble.blob()
...
<Mock name='mock.blob()' id='...'>
>>> assert 'fooble' not in sys.modules
>>> mock.blob.assert_called_once_with()
@end example

你可以看到 @code{import fooble} 成功执行，而当退出时 @ref{109a,,sys.modules} 中将不再有 'fooble'。

这同样适用于 @code{from module import name} 形式:

@example
>>> mock = Mock()
>>> with patch.dict('sys.modules', @{'fooble': mock@}):
...    from fooble import blob
...    blob.blip()
...
<Mock name='mock.blob.blip()' id='...'>
>>> mock.blob.blip.assert_called_once_with()
@end example

稍微多做一点工作你还可以模拟包的导入:

@example
>>> mock = Mock()
>>> modules = @{'package': mock, 'package.module': mock.module@}
>>> with patch.dict('sys.modules', modules):
...    from package.module import fooble
...    fooble()
...
<Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_called_once_with()
@end example

@node 追踪调用顺序和不太冗长的调用断言,更复杂的参数匹配,通过 patch dict 模拟导入,更多示例
@anchor{library/unittest mock-examples tracking-order-of-calls-and-less-verbose-call-assertions}@anchor{3467}
@subsubsection 追踪调用顺序和不太冗长的调用断言


@ref{37a,,Mock} 类允许你通过 @ref{3413,,method_calls} 属性来追踪在你的 mock 对象上的方法调用的 @emph{顺序}。 这并不允许你追踪单独 mock 对象之间的调用顺序，但是我们可以使用 @ref{3410,,mock_calls} 来达到同样的效果。

因为 mock 会追踪 @code{mock_calls} 中对子 mock 的调用，并且访问 mock 的任意属性都会创建一个子 mock，所以我们可以基于父 mock 创建单独的子 mock。 随后对这些子 mock 的调用将按顺序被记录在父 mock 的 @code{mock_calls} 中:

@example
>>> manager = Mock()
>>> mock_foo = manager.foo
>>> mock_bar = manager.bar
@end example

@example
>>> mock_foo.something()
<Mock name='mock.foo.something()' id='...'>
>>> mock_bar.other.thing()
<Mock name='mock.bar.other.thing()' id='...'>
@end example

@example
>>> manager.mock_calls
[call.foo.something(), call.bar.other.thing()]
@end example

我们可以随后通过与管理 mock 上的 @code{mock_calls} 属性进行比较来进行有关这些调用，包括调用顺序的断言:

@example
>>> expected_calls = [call.foo.something(), call.bar.other.thing()]
>>> manager.mock_calls == expected_calls
True
@end example

如果 @code{patch} 创建并准备好了你的 mock 那么你可以使用 @ref{3412,,attach_mock()} 方法将它们附加到管理 mock 上。 在附加之后所有调用都将被记录在管理器的 @code{mock_calls} 中。

@example
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
...     with patch('mymodule.Class2') as MockClass2:
...         manager.attach_mock(MockClass1, 'MockClass1')
...         manager.attach_mock(MockClass2, 'MockClass2')
...         MockClass1().foo()
...         MockClass2().bar()
<MagicMock name='mock.MockClass1().foo()' id='...'>
<MagicMock name='mock.MockClass2().bar()' id='...'>
>>> manager.mock_calls
[call.MockClass1(),
call.MockClass1().foo(),
call.MockClass2(),
call.MockClass2().bar()]
@end example

如果已经进行了许多调用，但是你只对它们的一个特定序列感兴趣则有一种替代方式是使用 @ref{340f,,assert_has_calls()} 方法。 这需要一个调用的列表（使用 @ref{1115,,call} 对象来构建）。 如果该调用序列在 @ref{3410,,mock_calls} 中则断言将成功。

@example
>>> m = MagicMock()
>>> m().foo().bar().baz()
<MagicMock name='mock().foo().bar().baz()' id='...'>
>>> m.one().two().three()
<MagicMock name='mock.one().two().three()' id='...'>
>>> calls = call.one().two().three().call_list()
>>> m.assert_has_calls(calls)
@end example

即使链式调用 @code{m.one().two().three()} 不是对 mock 的唯一调用，该断言仍将成功。

有时可能会对一个 mock 进行多次调用，而你只对断言其中的 @emph{某些} 调用感兴趣。 你甚至可能对顺序也不关心。 在这种情况下你可以将 @code{any_order=True} 传给 @code{assert_has_calls}:

@example
>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(calls, any_order=True)
@end example

@node 更复杂的参数匹配,,追踪调用顺序和不太冗长的调用断言,更多示例
@anchor{library/unittest mock-examples more-complex-argument-matching}@anchor{3468}
@subsubsection 更复杂的参数匹配


使用与 @ref{111a,,ANY} 一样的基本概念我们可以实现匹配器以便在用作 mock 的参数的对象上执行更复杂的断言。

假设我们准备将某个对象传给一个在默认情况下基于对象标识相等（这是 Python 中用户自定义类的默认行为）的 mock。 要使用 @ref{1183,,assert_called_with()} 我们就将必须传入完全相同的对象。 如果我们只对该对象的某些属性感兴趣那么我们可以创建一个能为我们检查这些属性的匹配器。

在这个示例中你可以看到为何执行对 @code{assert_called_with} 的‘标准’调用并不足够:

@example
>>> class Foo:
...     def __init__(self, a, b):
...         self.a, self.b = a, b
...
>>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
    ...
AssertionError: Expected: call(<__main__.Foo object at 0x...>)
Actual call: call(<__main__.Foo object at 0x...>)
@end example

一个针对我们的 @code{Foo} 类的比较函数看上去会是这样的:

@example
>>> def compare(self, other):
...     if not type(self) == type(other):
...         return False
...     if self.a != other.a:
...         return False
...     if self.b != other.b:
...         return False
...     return True
...
@end example

而一个可以使用这样的比较函数进行相等性比较运算的匹配器对象看上去会是这样的:

@example
>>> class Matcher:
...     def __init__(self, compare, some_obj):
...         self.compare = compare
...         self.some_obj = some_obj
...     def __eq__(self, other):
...         return self.compare(self.some_obj, other)
...
@end example

将所有这些放在一起:

@example
>>> match_foo = Matcher(compare, Foo(1, 2))
>>> mock.assert_called_with(match_foo)
@end example

@code{Matcher} 是用我们的比较函数和我们想要比较的 @code{Foo} 对象来实例化的。 在 @code{assert_called_with} 中将会调用 @code{Matcher} 的相等性方法，它会将调用 mock 时附带的对象与我们创建我们的匹配器时附带的对象进行比较。 如果它们匹配则 @code{assert_called_with} 通过，而如果不匹配则会引发 @ref{241,,AssertionError}:

@example
>>> match_wrong = Matcher(compare, Foo(3, 4))
>>> mock.assert_called_with(match_wrong)
Traceback (most recent call last):
    ...
AssertionError: Expected: ((<Matcher object at 0x...>,), @{@})
Called with: ((<Foo object at 0x...>,), @{@})
@end example

通过一些调整你可以让比较函数直接引发 @ref{241,,AssertionError} 并提供更有用的失败消息。

从 1.5 版开始，Python 测试库 PyHamcrest@footnote{https://pyhamcrest.readthedocs.io/} 提供了类似的功能，在这里可能会很有用，它采用的形式是相等性匹配器 (hamcrest.library.integration.match_equality@footnote{https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality})。

@node 2to3 - 自动将 Python 2 代码转为 Python 3 代码,test --- Python回归测试包,unittest mock 上手指南,开发工具
@anchor{library/2to3 doc}@anchor{3469}@anchor{library/2to3 to3-automated-python-2-to-3-code-translation}@anchor{346a}@anchor{library/2to3 to3-reference}@anchor{d46}
@subsection 2to3 - 自动将 Python 2 代码转为 Python 3 代码


2to3 是一个 Python 程序，它可以读取 Python 2.x 的源代码并使用一系列的 @emph{修复器} 来将其转换为合法的 Python 3.x 代码。 标准库已包含了丰富的修复器，这足以处理几乎所有代码。 不过 2to3 的支持库 @ref{a7,,lib2to3} 是一个很灵活通用的库，所以还可以编写你自己的 2to3 修复器。

@menu
* 使用 2to3:: 
* 修复器:: 
* lib2to3 —— 2to3 支持库:: 

@end menu

@node 使用 2to3,修复器,,2to3 - 自动将 Python 2 代码转为 Python 3 代码
@anchor{library/2to3 to3-using}@anchor{346b}@anchor{library/2to3 using-2to3}@anchor{346c}
@subsubsection 使用 2to3


2to3 通常会作为脚本和 Python 解释器一起安装，你可以在 Python 根目录的 @code{Tools/scripts} 文件夹下找到它。

2to3 的基本调用参数是一个需要转换的文件或目录列表。对于目录，会递归地寻找其中的 Python 源码。

这里有一个 Python 2.x 的源码文件，@code{example.py}：

@example
def greet(name):
    print "Hello, @{0@}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)
@end example

它可以在命令行中使用 2to3 转换成 Python 3.x 版本的代码：

@example
$ 2to3 example.py
@end example

这个命令会打印出和源文件的区别。通过传入 @code{-w} 参数，2to3 也可以把需要的修改写回到原文件中（除非传入了 @code{-n} 参数，否则会为原始文件创建一个副本）：

@example
$ 2to3 -w example.py
@end example

在转换完成后，@code{example.py} 看起来像是这样：

@example
def greet(name):
    print("Hello, @{0@}!".format(name))
print("What's your name?")
name = input()
greet(name)
@end example

注释和缩进都会在转换过程中保持不变。

默认情况下，2to3 会执行 @ref{346d,,预定义修复器} 的集合。使用 @code{-l} 参数可以列出所有可用的修复器。使用 @code{-f} 参数可以明确指定需要使用的修复器集合。而使用 @code{-x} 参数则可以明确指定不使用的修复器。下面的例子会只使用 @code{imports} 和 @code{has_key} 修复器运行：

@example
$ 2to3 -f imports -f has_key example.py
@end example

这个命令会执行除了 @code{apply} 之外的所有修复器：

@example
$ 2to3 -x apply example.py
@end example

有一些修复器是需要 @emph{显式指定} 的，它们默认不会执行，必须在命令行中列出才会执行。比如下面的例子，除了默认的修复器以外，还会执行 @code{idioms} 修复器：

@example
$ 2to3 -f all -f idioms example.py
@end example

注意这里使用 @code{all} 来启用所有默认的修复器。

有些情况下 2to3 会找到源码中有一些需要修改，但是无法自动处理的代码。在这种情况下，2to3 会在差异处下面打印一个警告信息。你应该定位到相应的代码并对其进行修改，以使其兼容 Python 3.x。

2to3 也可以重构 doctests。使用 @code{-d} 开启这个模式。需要注意*只有* doctests 会被重构。这种模式下不需要文件是合法的 Python 代码。举例来说，reST 文档中类似 doctests 的示例也可以使用这个选项进行重构。

@code{-v} 选项可以输出更多转换程序的详细信息。

由于某些 print 语句可被解读为函数调用或是语句，2to3 并不总能读取包含 print 函数的文件。 当 2to3 检测到存在 @code{from __future__ import print_function} 编译器指令时，会修改其内部语法将 @ref{97a,,print()} 解读为函数。 这一变动也可以使用 @code{-p} 旗标手动开启。 使用 @code{-p} 来为已转换过 print 语句的代码运行修复器。 也可以使用 @code{-e} 将 @ref{d14,,exec()} 解读为函数。

@code{-o} 或 @code{--output-dir} 选项可以指定将转换后的文件写入其他目录中。由于这种情况下不会覆写原始文件，所以创建副本文件毫无意义，因此也需要使用 @code{-n} 选项来禁用创建副本。


3.2.3 新版功能: 增加了 @code{-o} 选项。


@code{-W} 或 @code{--write-unchanged-files} 选项用来告诉 2to3 始终需要输出文件，即使没有任何改动。这在使用 @code{-o} 参数时十分有用，这样就可以将整个 Python 源码包完整地转换到另一个目录。这个选项隐含了 @code{-w} 选项，否则等于没有作用。


3.2.3 新版功能: 增加了 @code{-W} 选项。


@code{--add-suffix} 选项接受一个字符串，用来作为后缀附加在输出文件名后面的后面。由于写入的文件名与原始文件不同，所以没有必要创建副本，因此 @code{-n} 选项也是必要的。举个例子：

@example
$ 2to3 -n -W --add-suffix=3 example.py
@end example

这样会把转换后的文件写入 @code{example.py3} 文件。


3.2.3 新版功能: 增加了 @code{--add-suffix} 选项。


将整个项目从一个目录转换到另一个目录可以用这样的命令：

@example
$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode
@end example

@node 修复器,lib2to3 —— 2to3 支持库,使用 2to3,2to3 - 自动将 Python 2 代码转为 Python 3 代码
@anchor{library/2to3 fixers}@anchor{346e}@anchor{library/2to3 to3-fixers}@anchor{346d}
@subsubsection 修复器


转换代码的每一个步骤都封装在修复器中。可以使用 @code{2to3 -l} 来列出可用的修复器。@ref{346b,,之前已经提到}，每个修复器都可以独立地打开或是关闭。下面会对各个修复器做更详细的描述。

@geindex apply (2to3 fixer)
@anchor{library/2to3 2to3fixer-apply}@anchor{346f}
@deffn {2to3fixer} apply

移除对 @code{apply()} 的使用，举例来说，@code{apply(function, *args, **kwargs)} 会被转换成 @code{function(*args, **kwargs)}。
@end deffn

@geindex asserts (2to3 fixer)
@anchor{library/2to3 2to3fixer-asserts}@anchor{3470}
@deffn {2to3fixer} asserts

将已弃用的 @ref{124,,unittest} 方法替换为正确的。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Python 2.x

@tab

Python 3.x

@item

@code{failUnlessEqual(a, b)}

@tab

@ref{c8d,,assertEqual(a@comma{} b)}

@item

@code{assertEquals(a, b)}

@tab

@ref{c8d,,assertEqual(a@comma{} b)}

@item

@code{failIfEqual(a, b)}

@tab

@ref{c8e,,assertNotEqual(a@comma{} b)}

@item

@code{assertNotEquals(a, b)}

@tab

@ref{c8e,,assertNotEqual(a@comma{} b)}

@item

@code{failUnless(a)}

@tab

@ref{c8c,,assertTrue(a)}

@item

@code{assert_(a)}

@tab

@ref{c8c,,assertTrue(a)}

@item

@code{failIf(a)}

@tab

@ref{d97,,assertFalse(a)}

@item

@code{failUnlessRaises(exc, cal)}

@tab

@ref{b9b,,assertRaises(exc@comma{} cal)}

@item

@code{failUnlessAlmostEqual(a, b)}

@tab

@ref{c8f,,assertAlmostEqual(a@comma{} b)}

@item

@code{assertAlmostEquals(a, b)}

@tab

@ref{c8f,,assertAlmostEqual(a@comma{} b)}

@item

@code{failIfAlmostEqual(a, b)}

@tab

@ref{c90,,assertNotAlmostEqual(a@comma{} b)}

@item

@code{assertNotAlmostEquals(a, b)}

@tab

@ref{c90,,assertNotAlmostEqual(a@comma{} b)}

@end multitable

@end deffn

@geindex basestring (2to3 fixer)
@anchor{library/2to3 2to3fixer-basestring}@anchor{3471}
@deffn {2to3fixer} basestring

将 @code{basestring} 转换为 @ref{206,,str}。
@end deffn

@geindex buffer (2to3 fixer)
@anchor{library/2to3 2to3fixer-buffer}@anchor{3472}
@deffn {2to3fixer} buffer

将 @code{buffer} 转换为 @ref{38d,,memoryview}。这个修复器是可选的，因为 @ref{38d,,memoryview} API 和 @code{buffer} 很相似，但不完全一样。
@end deffn

@geindex dict (2to3 fixer)
@anchor{library/2to3 2to3fixer-dict}@anchor{3473}
@deffn {2to3fixer} dict

修复字典迭代方法。@code{dict.iteritems()} 会转换成 @ref{cfd,,dict.items()}，@code{dict.iterkeys()} 会转换成 @ref{cfc,,dict.keys()}，@code{dict.itervalues()} 会转换成 @ref{cfe,,dict.values()}。类似的，@code{dict.viewitems()}，@code{dict.viewkeys()} 和 @code{dict.viewvalues()} 会分别转换成 @ref{cfd,,dict.items()}，@ref{cfc,,dict.keys()} 和 @ref{cfe,,dict.values()}。另外也会将原有的 @ref{cfd,,dict.items()}，@ref{cfc,,dict.keys()} 和  @ref{cfe,,dict.values()} 方法调用用 @ref{1f9,,list} 包装一层。
@end deffn

@geindex except (2to3 fixer)
@anchor{library/2to3 2to3fixer-except}@anchor{3474}
@deffn {2to3fixer} except

将 @code{except X, T} 转换为 @code{except X as T}。
@end deffn

@geindex exec (2to3 fixer)
@anchor{library/2to3 2to3fixer-exec}@anchor{3475}
@deffn {2to3fixer} exec

将 @code{exec} 语句转换为 @ref{d14,,exec()} 函数调用。
@end deffn

@geindex execfile (2to3 fixer)
@anchor{library/2to3 2to3fixer-execfile}@anchor{11a4}
@deffn {2to3fixer} execfile

移除 @code{execfile()} 的使用。@code{execfile()} 的实参会使用 @ref{16f,,open()}，@ref{2ee,,compile()} 和 @ref{d14,,exec()} 包装。
@end deffn

@geindex exitfunc (2to3 fixer)
@anchor{library/2to3 2to3fixer-exitfunc}@anchor{3476}
@deffn {2to3fixer} exitfunc

将对 @code{sys.exitfunc} 的赋值改为使用 @ref{b,,atexit} 模块代替。
@end deffn

@geindex filter (2to3 fixer)
@anchor{library/2to3 2to3fixer-filter}@anchor{3477}
@deffn {2to3fixer} filter

将 @ref{d00,,filter()} 函数用 @ref{1f9,,list} 包装一层。
@end deffn

@geindex funcattrs (2to3 fixer)
@anchor{library/2to3 2to3fixer-funcattrs}@anchor{3478}
@deffn {2to3fixer} funcattrs

修复已经重命名的函数属性。比如 @code{my_function.func_closure} 会被转换为 @code{my_function.__closure__}。
@end deffn

@geindex future (2to3 fixer)
@anchor{library/2to3 2to3fixer-future}@anchor{3479}
@deffn {2to3fixer} future

移除 @code{from __future__ import new_feature} 语句。
@end deffn

@geindex getcwdu (2to3 fixer)
@anchor{library/2to3 2to3fixer-getcwdu}@anchor{347a}
@deffn {2to3fixer} getcwdu

将 @code{os.getcwdu()} 重命名为 @ref{1162,,os.getcwd()}。
@end deffn

@geindex has_key (2to3 fixer)
@anchor{library/2to3 2to3fixer-has_key}@anchor{347b}
@deffn {2to3fixer} has_key

将 @code{dict.has_key(key)} 转换为 @code{key in dict}。
@end deffn

@geindex idioms (2to3 fixer)
@anchor{library/2to3 2to3fixer-idioms}@anchor{347c}
@deffn {2to3fixer} idioms

这是一个可选的修复器，会进行多种转换，将 Python 代码变成更加常见的写法。类似 @code{type(x) is SomeClass} 和 @code{type(x) == SomeClass} 的类型对比会被转换成 @code{isinstance(x, SomeClass)}。@code{while 1} 转换成 @code{while True}。这个修复器还会在合适的地方使用 @ref{54f,,sorted()} 函数。举个例子，这样的代码块：

@example
L = list(some_iterable)
L.sort()
@end example

会被转换为：

@example
L = sorted(some_iterable)
@end example
@end deffn

@geindex import (2to3 fixer)
@anchor{library/2to3 2to3fixer-import}@anchor{347d}
@deffn {2to3fixer} import

检测 sibling imports，并将其转换成相对 import。
@end deffn

@geindex imports (2to3 fixer)
@anchor{library/2to3 2to3fixer-imports}@anchor{347e}
@deffn {2to3fixer} imports

处理标准库模块的重命名。
@end deffn

@geindex imports2 (2to3 fixer)
@anchor{library/2to3 2to3fixer-imports2}@anchor{347f}
@deffn {2to3fixer} imports2

处理标准库中其他模块的重命名。这个修复器由于一些技术上的限制，因此和 @ref{347e,,imports} 拆分开了。
@end deffn

@geindex input (2to3 fixer)
@anchor{library/2to3 2to3fixer-input}@anchor{3480}
@deffn {2to3fixer} input

将 @code{input(prompt)} 转换为 @code{eval(input(prompt))}。
@end deffn

@geindex intern (2to3 fixer)
@anchor{library/2to3 2to3fixer-intern}@anchor{3481}
@deffn {2to3fixer} intern

将 @code{intern()} 转换为 @ref{d3e,,sys.intern()}。
@end deffn

@geindex isinstance (2to3 fixer)
@anchor{library/2to3 2to3fixer-isinstance}@anchor{3482}
@deffn {2to3fixer} isinstance

修复 @ref{55a,,isinstance()} 函数第二个实参中重复的类型。举例来说，@code{isinstance(x, (int, int))} 会转换为 @code{isinstance(x, int)}, @code{isinstance(x, (int, float, int))} 会转换为 @code{isinstance(x, (int, float))}。
@end deffn

@geindex itertools_imports (2to3 fixer)
@anchor{library/2to3 2to3fixer-itertools_imports}@anchor{3483}
@deffn {2to3fixer} itertools_imports

移除 @code{itertools.ifilter()}，@code{itertools.izip()} 以及 @code{itertools.imap()} 的 import。对 @code{itertools.ifilterfalse()} 的 import 也会替换成 @ref{1752,,itertools.filterfalse()}。
@end deffn

@geindex itertools (2to3 fixer)
@anchor{library/2to3 2to3fixer-itertools}@anchor{3484}
@deffn {2to3fixer} itertools

修改 @code{itertools.ifilter()}，@code{itertools.izip()} 和 @code{itertools.imap()} 的调用为对应的内建实现。@code{itertools.ifilterfalse()} 会替换成 @ref{1752,,itertools.filterfalse()}。
@end deffn

@geindex long (2to3 fixer)
@anchor{library/2to3 2to3fixer-long}@anchor{3485}
@deffn {2to3fixer} long

将 @code{long} 重命名为 @ref{205,,int}。
@end deffn

@geindex map (2to3 fixer)
@anchor{library/2to3 2to3fixer-map}@anchor{3486}
@deffn {2to3fixer} map

用 @ref{1f9,,list} 包装 @ref{cff,,map()}。同时也会将 @code{map(None, x)} 替换为 @code{list(x)}。使用 @code{from future_builtins import map} 禁用这个修复器。
@end deffn

@geindex metaclass (2to3 fixer)
@anchor{library/2to3 2to3fixer-metaclass}@anchor{3487}
@deffn {2to3fixer} metaclass

将老的元类语法（类体中的 @code{__metaclass__ = Meta}）替换为新的（@code{class X(metaclass=Meta)}）。
@end deffn

@geindex methodattrs (2to3 fixer)
@anchor{library/2to3 2to3fixer-methodattrs}@anchor{3488}
@deffn {2to3fixer} methodattrs

修复老的方法属性名。例如 @code{meth.im_func} 会被转换为 @code{meth.__func__}。
@end deffn

@geindex ne (2to3 fixer)
@anchor{library/2to3 2to3fixer-ne}@anchor{3489}
@deffn {2to3fixer} ne

转换老的不等语法，将 @code{<>} 转为 @code{!=}。
@end deffn

@geindex next (2to3 fixer)
@anchor{library/2to3 2to3fixer-next}@anchor{348a}
@deffn {2to3fixer} next

将迭代器的 @code{next()} 方法调用转为 @ref{77f,,next()} 函数。也会将 @ref{77f,,next()} 方法重命名为 @ref{d34,,__next__()}。
@end deffn

@geindex nonzero (2to3 fixer)
@anchor{library/2to3 2to3fixer-nonzero}@anchor{348b}
@deffn {2to3fixer} nonzero

将被调用的方法定义 @code{__nonzero__()} 改名为 @ref{d38,,__bool__()}。
@end deffn

@geindex numliterals (2to3 fixer)
@anchor{library/2to3 2to3fixer-numliterals}@anchor{348c}
@deffn {2to3fixer} numliterals

将八进制字面量转为新的语法。
@end deffn

@geindex operator (2to3 fixer)
@anchor{library/2to3 2to3fixer-operator}@anchor{348d}
@deffn {2to3fixer} operator

将 @ref{c2,,operator} 模块中的许多方法调用转为其他的等效函数调用。如果有需要，会添加适当的 @code{import} 语句，比如 @code{import collections.abc}。有以下转换映射：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Python 2.x

@tab

Python 3.x

@item

@code{operator.isCallable(obj)}

@tab

@code{callable(obj)}

@item

@code{operator.sequenceIncludes(obj)}

@tab

@code{operator.contains(obj)}

@item

@code{operator.isSequenceType(obj)}

@tab

@code{isinstance(obj, collections.abc.Sequence)}

@item

@code{operator.isMappingType(obj)}

@tab

@code{isinstance(obj, collections.abc.Mapping)}

@item

@code{operator.isNumberType(obj)}

@tab

@code{isinstance(obj, numbers.Number)}

@item

@code{operator.repeat(obj, n)}

@tab

@code{operator.mul(obj, n)}

@item

@code{operator.irepeat(obj, n)}

@tab

@code{operator.imul(obj, n)}

@end multitable

@end deffn

@geindex paren (2to3 fixer)
@anchor{library/2to3 2to3fixer-paren}@anchor{348e}
@deffn {2to3fixer} paren

在列表生成式中增加必须的括号。例如将 @code{[x for x in 1, 2]} 转换为 @code{[x for x in (1, 2)]}。
@end deffn

@geindex print (2to3 fixer)
@anchor{library/2to3 2to3fixer-print}@anchor{348f}
@deffn {2to3fixer} print

将 @code{print} 语句转换为 @ref{97a,,print()} 函数。
@end deffn

@geindex raise (2to3 fixer)
@anchor{library/2to3 2to3fixer-raise}@anchor{3490}
@deffn {2to3fixer} raise

将 @code{raise E, V} 转换为 @code{raise E(V)}，将 @code{raise E, V, T} 转换为 @code{raise E(V).with_traceback(T)}。如果 @code{E} 是元组，这样的转换是不正确的，因为用元组代替异常的做法在 3.0 中已经移除了。
@end deffn

@geindex raw_input (2to3 fixer)
@anchor{library/2to3 2to3fixer-raw_input}@anchor{3491}
@deffn {2to3fixer} raw_input

将 @code{raw_input()} 转换为 @ref{d3b,,input()}。
@end deffn

@geindex reduce (2to3 fixer)
@anchor{library/2to3 2to3fixer-reduce}@anchor{3492}
@deffn {2to3fixer} reduce

将 @code{reduce()} 转换为 @ref{d3f,,functools.reduce()}。
@end deffn

@geindex reload (2to3 fixer)
@anchor{library/2to3 2to3fixer-reload}@anchor{11b2}
@deffn {2to3fixer} reload

将 @code{reload()} 转换为 @ref{4a8,,importlib.reload()}。
@end deffn

@geindex renames (2to3 fixer)
@anchor{library/2to3 2to3fixer-renames}@anchor{3493}
@deffn {2to3fixer} renames

将 @code{sys.maxint} 转换为 @ref{c1e,,sys.maxsize}。
@end deffn

@geindex repr (2to3 fixer)
@anchor{library/2to3 2to3fixer-repr}@anchor{3494}
@deffn {2to3fixer} repr

将反引号 repr 表达式替换为 @ref{8c3,,repr()} 函数。
@end deffn

@geindex set_literal (2to3 fixer)
@anchor{library/2to3 2to3fixer-set_literal}@anchor{3495}
@deffn {2to3fixer} set_literal

将 @ref{1f7,,set} 构造函数替换为 set literals 写法。这个修复器是可选的。
@end deffn

@geindex standarderror (2to3 fixer)
@anchor{library/2to3 2to3fixer-standarderror}@anchor{3496}
@deffn {2to3fixer} standarderror

将 @code{StandardError} 重命名为 @ref{2e3,,Exception}。
@end deffn

@geindex sys_exc (2to3 fixer)
@anchor{library/2to3 2to3fixer-sys_exc}@anchor{3497}
@deffn {2to3fixer} sys_exc

将弃用的 @code{sys.exc_value}，@code{sys.exc_type}，@code{sys.exc_traceback} 替换为 @ref{d2f,,sys.exc_info()} 的用法。
@end deffn

@geindex throw (2to3 fixer)
@anchor{library/2to3 2to3fixer-throw}@anchor{3498}
@deffn {2to3fixer} throw

修复生成器的 @code{throw()} 方法的 API 变更。
@end deffn

@geindex tuple_params (2to3 fixer)
@anchor{library/2to3 2to3fixer-tuple_params}@anchor{3499}
@deffn {2to3fixer} tuple_params

移除隐式的元组参数解包。这个修复器会插入临时变量。
@end deffn

@geindex types (2to3 fixer)
@anchor{library/2to3 2to3fixer-types}@anchor{349a}
@deffn {2to3fixer} types

修复 @ref{709,,type} 模块中一些成员的移除引起的代码问题。
@end deffn

@geindex unicode (2to3 fixer)
@anchor{library/2to3 2to3fixer-unicode}@anchor{349b}
@deffn {2to3fixer} unicode

将 @code{unicode} 重命名为 @ref{206,,str}。
@end deffn

@geindex urllib (2to3 fixer)
@anchor{library/2to3 2to3fixer-urllib}@anchor{349c}
@deffn {2to3fixer} urllib

将 @ref{126,,urllib} 和 @code{urllib2} 重命名为 @ref{126,,urllib} 包。
@end deffn

@geindex ws_comma (2to3 fixer)
@anchor{library/2to3 2to3fixer-ws_comma}@anchor{349d}
@deffn {2to3fixer} ws_comma

移除逗号分隔的元素之间多余的空白。这个修复器是可选的。
@end deffn

@geindex xrange (2to3 fixer)
@anchor{library/2to3 2to3fixer-xrange}@anchor{349e}
@deffn {2to3fixer} xrange

将 @code{xrange()} 重命名为 @ref{1f6,,range()}，并用 @ref{1f9,,list} 包装原有的 @ref{1f6,,range()}。
@end deffn

@geindex xreadlines (2to3 fixer)
@anchor{library/2to3 2to3fixer-xreadlines}@anchor{349f}
@deffn {2to3fixer} xreadlines

将 @code{for x in file.xreadlines()} 转换为 @code{for x in file}。
@end deffn

@geindex zip (2to3 fixer)
@anchor{library/2to3 2to3fixer-zip}@anchor{34a0}
@deffn {2to3fixer} zip

用 @ref{1f9,,list} 包装 @ref{d04,,zip()}。如果使用了 @code{from future_builtins import zip} 的话会禁用。
@end deffn

@node lib2to3 —— 2to3 支持库,,修复器,2to3 - 自动将 Python 2 代码转为 Python 3 代码
@anchor{library/2to3 lib2to3-2to3-s-library}@anchor{34a1}@anchor{library/2to3 module-lib2to3}@anchor{a7}
@subsubsection @code{lib2to3} —— 2to3 支持库


@geindex lib2to3 (模块)

@strong{源代码：} Lib/lib2to3/@footnote{https://github.com/python/cpython/tree/3.9/Lib/lib2to3/}


__________________________________________________________________



3.10 版后已移除: Python 3.9 将切换到 PEG 解析器 (参见 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617})，Python 3.10 可能会包含 lib2to3 的 LL(1) 解析器所不能解析的新语法。 @code{lib2to3} 模块可能会在未来的 Python 版本中被移出标准库。 请考虑使用第三方替代例如 LibCST@footnote{https://libcst.readthedocs.io/} 或 parso@footnote{https://parso.readthedocs.io/}。


@cartouche
@quotation 注解 
@ref{a7,,lib2to3} API 并不稳定，并可能在未来大幅修改。
@end quotation
@end cartouche

@node test --- Python回归测试包,test support --- 针对 Python 测试套件的工具,2to3 - 自动将 Python 2 代码转为 Python 3 代码,开发工具
@anchor{library/test doc}@anchor{34a2}@anchor{library/test module-test}@anchor{105}@anchor{library/test parso}@anchor{34a3}@anchor{library/test test-regression-tests-package-for-python}@anchor{34a4}
@subsection @code{test} ---  Python回归测试包


@geindex test (模块)

@cartouche
@quotation 注解 
@ref{105,,test} 包只供 Python 内部使用。它的记录是为了让 Python 的核心开发者受益。我们不鼓励在 Python 标准库之外使用这个包，因为这里提到的代码在 Python 的不同版本之间可能会改变或被删除而不另行通知。
@end quotation
@end cartouche


__________________________________________________________________


@ref{105,,test} 包包含了 Python 的所有回归测试，以及 @ref{106,,test.support} 和 @code{test.regrtest} 模块。  @ref{106,,test.support} 用于增强你的测试，而 @code{test.regrtest} 驱动测试套件。

@code{test`包中每个名字以 `@w{`}test_`} 开头的模块都是一个特定模块或功能的测试套件。所有新的测试应该使用 @ref{124,,unittest} 或 @ref{66,,doctest} 模块编写。一些旧的测试是使用“传统”的测试风格编写的，即比较打印出来的输出到`@w{`}sys.stdout`@w{`}；这种测试风格被认为是过时的。


@subsubheading 参见



@table @asis

@item 模块 @ref{124,,unittest}

编写 PyUnit 回归测试.

@item @ref{124,,unittest} --- 文档测试

嵌入到文档字符串的测试。
@end table


@menu
* 为 test 包编写单元测试:: 
* 使用命令行界面运行测试:: 

@end menu

@node 为 test 包编写单元测试,使用命令行界面运行测试,,test --- Python回归测试包
@anchor{library/test writing-tests}@anchor{34a5}@anchor{library/test writing-unit-tests-for-the-test-package}@anchor{34a6}
@subsubsection 为 @code{test} 包编写单元测试


使用 @ref{124,,unittest} 模块的测试最好是遵循一些准则。 其中一条是测试模块的名称要以 @code{test_} 打头并以被测试模块的名称结尾。 测试模块中的测试方法应当以 @code{test_} 打头并以该方法所测试的内容的说明结尾。 这很有必要因为这样测试驱动程序就会将这些方法识别为测试方法。 此外，该方法不应当包括任何文档字符串。 应当使用注释 (例如 @code{# Tests function returns only True or False}) 来为测试方法提供文档说明。 这样做是因为文档字符串如果存在则会被打印出来因此无法指明正在运行哪个测试。

有一个基本模板经常会被使用:

@example
import unittest
from test import support

class MyTestCase1(unittest.TestCase):

    # Only use setUp() and tearDown() if necessary

    def setUp(self):
        ... code to execute in preparation for tests ...

    def tearDown(self):
        ... code to execute to clean up after tests ...

    def test_feature_one(self):
        # Test feature one.
        ... testing code ...

    def test_feature_two(self):
        # Test feature two.
        ... testing code ...

    ... more test methods ...

class MyTestCase2(unittest.TestCase):
    ... same structure as MyTestCase1 ...

... more test classes ...

if __name__ == '__main__':
    unittest.main()
@end example

这种代码模式允许测试套件由 @code{test.regrtest} 运行，作为支持 @ref{124,,unittest} CLI 的脚本单独运行，或者通过 @code{python -m unittest} CLI 来运行。

回归测试的目标是尝试破坏代码。 这引出了一些需要遵循的准则:


@itemize *

@item 
测试套件应当测试所有的类、函数和常量。 这不仅包括要向外界展示的外部 API 也包括“私有”的代码。

@item 
白盒测试（在编写测试时检查被测试的代码）是最推荐的。 黑盒测试（只测试已发布的用户接口）因不够完整而不能确保所有边界和边缘情况都被测试到。

@item 
确保所有可能的值包括无效的值都被测试到。 这能确保不仅全部的有效值都可被接受而且不适当的值也能被正确地处理。

@item 
消耗尽可能多的代码路径。 测试发生分支的地方从而调整输入以确保通过代码采取尽可能多的不同路径。

@item 
为受测试的代码所发现的任何代码缺陷添加明确的测试。 这将确保如果代码在将来被改变错误也不会再次出现。

@item 
确保在你的测试完成后执行清理（例如关闭并删除所有临时文件）。

@item 
如果某个测试依赖于操作系统上的特定条件那么要在尝试测试之前先验证该条件是否已存在。

@item 
尽可能少地导入模块并尽可能快地完成操作。 这可以最大限度地减少测试的外部依赖性并且还可以最大限度地减少导入模块带来的附带影响所导致的异常行为。

@item 
尝试最大限度地重用代码。 在某些情况下，测试结果会因使用不同类型的输入这样的小细节而变化。 可通过一个指定输入的类来子类化一个基本测试类来最大限度地减少重复代码:

@example
class TestFuncAcceptsSequencesMixin:

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)
@end example

当使用这种模式时，请记住所有继承自 @ref{9ee,,unittest.TestCase} 的类都会作为测试来运行。 上面例子中的 @code{Mixin} 类没有任何数据所以其本身是无法运行的，因此它不是继承自 @ref{9ee,,unittest.TestCase}。
@end itemize


@subsubheading 参见



@table @asis

@item 测试驱动的开发

Kent Beck 所著的阐述在实现代码之前编写驱动的书。
@end table


@node 使用命令行界面运行测试,,为 test 包编写单元测试,test --- Python回归测试包
@anchor{library/test regrtest}@anchor{a1b}@anchor{library/test running-tests-using-the-command-line-interface}@anchor{34a7}
@subsubsection 使用命令行界面运行测试


通过使用 @ref{44c,,-m} 选项 @ref{105,,test} 包可以作为脚本运行以驱动 Python 的回归测试套件: @code{python -m test}。 在内部，它使用 @code{test.regrtest}；之前 Python 版本所使用的 @code{python -m test.regrtest} 调用仍然有效。 运行该脚本自身会自动开始运行 @ref{105,,test} 包中的所有回归测试。 它通过在包中查找所有名称以 @code{test_} 打头的模块，导入它们，并在有 @code{test_main()} 函数时执行它或是在没有 @code{test_main} 时通过 unittest.TestLoader.loadTestsFromModule 载入测试。 要执行的测试的名称也可以被传递给脚本。 指定一个单独的回归测试 (@code{python -m test test_spam}) 将使输出最小化并且只打印测试通过或失败的消息。

直接运行 @ref{105,,test} 将允许设置哪些资源可供测试使用。 你可以通过使用 @code{-u} 命令行选项来做到这一点。 指定 @code{all} 作为 @code{-u} 选项的值将启用所有可能的资源: @code{python -m test -uall}。 如果只需要一项资源（这是更为常见的情况），可以在 @code{all} 之后加一个以逗号分隔的列表来指明不需要的资源。 命令 @code{python -m test -uall,-audio,-largefile} 将运行 @ref{105,,test} 并使用除 @code{audio} 和 @code{largefile} 资源之外的所有资源。 要查看所有资源的列表和更多的命令行选项，请运行 @code{python -m test -h}。

另外一些执行回归测试的方式依赖于执行测试所在的系统平台。 在 Unix 上，你可以在构建 Python 的最高层级目录中运行 @code{make test}。 在 Windows 上，在你的 @code{PCbuild} 目录中执行 @code{rt.bat} 将运行所有的回归测试。

@node test support --- 针对 Python 测试套件的工具,test support socket_helper --- 用于套接字测试的工具,test --- Python回归测试包,开发工具
@anchor{library/test module-test support}@anchor{106}@anchor{library/test test-support-utilities-for-the-python-test-suite}@anchor{34a8}
@subsection @code{test.support} --- 针对 Python 测试套件的工具


@geindex test.support (模块)

@ref{106,,test.support} 模块提供了对 Python 的回归测试套件的支持。

@cartouche
@quotation 注解 
@ref{106,,test.support} 不是一个公用模块。 这篇文档是为了帮助 Python 开发者编写测试。 此模块的 API 可能被改变而不顾及发行版本之间的向下兼容性问题。
@end quotation
@end cartouche

此模块定义了以下异常:

@geindex TestFailed
@anchor{library/test test support TestFailed}@anchor{34a9}
@deffn {例外} test.support.TestFailed

当一个测试失败时将引发的异常。 此异常已被弃用而应改用基于 @ref{124,,unittest} 的测试以及 @ref{9ee,,unittest.TestCase} 的断言方法。
@end deffn

@geindex ResourceDenied
@anchor{library/test test support ResourceDenied}@anchor{34aa}
@deffn {例外} test.support.ResourceDenied

@ref{9f2,,unittest.SkipTest} 的子类。 当一个资源（例如网络连接）不可用时将被引发。 由 @ref{34ab,,requires()} 函数所引发。
@end deffn

@ref{106,,test.support} 模块定义了以下常量:

@geindex verbose() (在 test.support 模块中)
@anchor{library/test test support verbose}@anchor{34ac}
@deffn {数据} test.support.verbose

当启用详细输出时为 @code{True}。 当需要有关运行中的测试的更详细信息时应当被选择。 @emph{verbose} 是由 @code{test.regrtest} 来设置的。
@end deffn

@geindex is_jython() (在 test.support 模块中)
@anchor{library/test test support is_jython}@anchor{34ad}
@deffn {数据} test.support.is_jython

如果所运行的解释器是 Jython 时为 @code{True}。
@end deffn

@geindex is_android() (在 test.support 模块中)
@anchor{library/test test support is_android}@anchor{34ae}
@deffn {数据} test.support.is_android

如果系统是 Android 时为 @code{True}。
@end deffn

@geindex unix_shell() (在 test.support 模块中)
@anchor{library/test test support unix_shell}@anchor{34af}
@deffn {数据} test.support.unix_shell

如果系统不是 Windows 时则为 shell 的路径；否则为 @code{None}。
@end deffn

@geindex FS_NONASCII() (在 test.support 模块中)
@anchor{library/test test support FS_NONASCII}@anchor{34b0}
@deffn {数据} test.support.FS_NONASCII

一个可通过 @ref{5f2,,os.fsencode()} 编码的非 ASCII 字符。
@end deffn

@geindex TESTFN() (在 test.support 模块中)
@anchor{library/test test support TESTFN}@anchor{1067}
@deffn {数据} test.support.TESTFN

设置为一个可以安全地用作临时文件名的名称。 任何被创建的临时文件都应当被关闭和撤销链接（移除）。
@end deffn

@geindex TESTFN_UNICODE() (在 test.support 模块中)
@anchor{library/test test support TESTFN_UNICODE}@anchor{34b1}
@deffn {数据} test.support.TESTFN_UNICODE

设置为用于临时文件的非 ASCII 名称。
@end deffn

@geindex TESTFN_ENCODING() (在 test.support 模块中)
@anchor{library/test test support TESTFN_ENCODING}@anchor{34b2}
@deffn {数据} test.support.TESTFN_ENCODING

Set to @ref{5f8,,sys.getfilesystemencoding()}.
@end deffn

@geindex TESTFN_UNENCODABLE() (在 test.support 模块中)
@anchor{library/test test support TESTFN_UNENCODABLE}@anchor{34b3}
@deffn {数据} test.support.TESTFN_UNENCODABLE

设置为一个应当在严格模式下不可使用文件系统编码格式来编码的文件名（str 类型）。 如果无法生成这样的文件名则可以为 @code{None}。
@end deffn

@geindex TESTFN_UNDECODABLE() (在 test.support 模块中)
@anchor{library/test test support TESTFN_UNDECODABLE}@anchor{34b4}
@deffn {数据} test.support.TESTFN_UNDECODABLE

设置为一个应当在严格模式下不可使用文件系统编码格式来编码的文件名（bytes 类型）。 如果无法生成这样的文件名则可以为 @code{None}。
@end deffn

@geindex TESTFN_NONASCII() (在 test.support 模块中)
@anchor{library/test test support TESTFN_NONASCII}@anchor{34b5}
@deffn {数据} test.support.TESTFN_NONASCII

Set to a filename containing the @ref{34b0,,FS_NONASCII} character.
@end deffn

@geindex LOOPBACK_TIMEOUT() (在 test.support 模块中)
@anchor{library/test test support LOOPBACK_TIMEOUT}@anchor{10fa}
@deffn {数据} test.support.LOOPBACK_TIMEOUT

使用网络服务器监听网络本地环回接口如 @code{127.0.0.1} 的测试的以秒为单位的超时值。

该超时长到足以防止测试失败：它要考虑客户端和服务器可能会在不同线程甚至不同进程中运行。

该超时应当对于 @ref{771,,socket.socket} 的 @ref{773,,connect()}, @ref{774,,recv()} 和 @ref{777,,send()} 方法都足够长。

其默认值为5秒。

参见 @ref{10fb,,INTERNET_TIMEOUT}。
@end deffn

@geindex INTERNET_TIMEOUT() (在 test.support 模块中)
@anchor{library/test test support INTERNET_TIMEOUT}@anchor{10fb}
@deffn {数据} test.support.INTERNET_TIMEOUT

Timeout in seconds for network requests going to the Internet.

The timeout is short enough to prevent a test to wait for too long if the
Internet request is blocked for whatever reason.

通常使用 @ref{10fb,,INTERNET_TIMEOUT} 的超时不应该将测试标记为失败，而是跳过测试：参见 @ref{34b6,,transient_internet()}。

其默认值是1分钟。

参见 @ref{10fa,,LOOPBACK_TIMEOUT}。
@end deffn

@geindex SHORT_TIMEOUT() (在 test.support 模块中)
@anchor{library/test test support SHORT_TIMEOUT}@anchor{fdf}
@deffn {数据} test.support.SHORT_TIMEOUT

如果测试耗时“太长”而要将测试标记为失败的以秒为单位的超时值。

该超时值取决于 regrtest @code{--timeout} 命令行选项。

如果一个使用 @ref{fdf,,SHORT_TIMEOUT} 的测试在慢速 buildbots 上开始随机失败，请使用 @ref{10fc,,LONG_TIMEOUT} 来代替。

其默认值为30秒。
@end deffn

@geindex LONG_TIMEOUT() (在 test.support 模块中)
@anchor{library/test test support LONG_TIMEOUT}@anchor{10fc}
@deffn {数据} test.support.LONG_TIMEOUT

用于检测测试何时挂起的以秒为单位的超时值。

它的长度足够在最慢的 Python buildbot 上降低测试失败的风险。 如果测试耗时“过长”也不应当用它将该测试标记为失败。 此超时值依赖于 regrtest @code{--timeout} 命令行选项。

其默认值为5分钟。

另请参见 @ref{10fa,,LOOPBACK_TIMEOUT}, @ref{10fb,,INTERNET_TIMEOUT} 和 @ref{fdf,,SHORT_TIMEOUT}。
@end deffn

@geindex SAVEDCWD() (在 test.support 模块中)
@anchor{library/test test support SAVEDCWD}@anchor{34b7}
@deffn {数据} test.support.SAVEDCWD

设置为 @ref{1162,,os.getcwd()}。
@end deffn

@geindex PGO() (在 test.support 模块中)
@anchor{library/test test support PGO}@anchor{34b8}
@deffn {数据} test.support.PGO

当测试对 PGO 没有用处时设置是否要跳过测试。
@end deffn

@geindex PIPE_MAX_SIZE() (在 test.support 模块中)
@anchor{library/test test support PIPE_MAX_SIZE}@anchor{34b9}
@deffn {数据} test.support.PIPE_MAX_SIZE

一个通常大于下层 OS 管道缓冲区大小的常量，以产生写入阻塞。
@end deffn

@geindex SOCK_MAX_SIZE() (在 test.support 模块中)
@anchor{library/test test support SOCK_MAX_SIZE}@anchor{34ba}
@deffn {数据} test.support.SOCK_MAX_SIZE

一个通常大于下层 OS 套接字缓冲区大小的常量，以产生写入阻塞。
@end deffn

@geindex TEST_SUPPORT_DIR() (在 test.support 模块中)
@anchor{library/test test support TEST_SUPPORT_DIR}@anchor{34bb}
@deffn {数据} test.support.TEST_SUPPORT_DIR

设为包含 @ref{106,,test.support} 的最高层级目录。
@end deffn

@geindex TEST_HOME_DIR() (在 test.support 模块中)
@anchor{library/test test support TEST_HOME_DIR}@anchor{34bc}
@deffn {数据} test.support.TEST_HOME_DIR

设为 test 包的最高层级目录。
@end deffn

@geindex TEST_DATA_DIR() (在 test.support 模块中)
@anchor{library/test test support TEST_DATA_DIR}@anchor{34bd}
@deffn {数据} test.support.TEST_DATA_DIR

设为 test 包中的 @code{data} 目录。
@end deffn

@geindex MAX_Py_ssize_t() (在 test.support 模块中)
@anchor{library/test test support MAX_Py_ssize_t}@anchor{34be}
@deffn {数据} test.support.MAX_Py_ssize_t

设为大内存测试的 @ref{c1e,,sys.maxsize}。
@end deffn

@geindex max_memuse() (在 test.support 模块中)
@anchor{library/test test support max_memuse}@anchor{34bf}
@deffn {数据} test.support.max_memuse

通过 @ref{34c0,,set_memlimit()} 设为针对大内存测试的内存限制。 由 @ref{34be,,MAX_Py_ssize_t} 来限制。
@end deffn

@geindex real_max_memuse() (在 test.support 模块中)
@anchor{library/test test support real_max_memuse}@anchor{34c1}
@deffn {数据} test.support.real_max_memuse

通过 @ref{34c0,,set_memlimit()} 设为针对大内存测试的内存限制。 不受 @ref{34be,,MAX_Py_ssize_t} 的限制。
@end deffn

@geindex MISSING_C_DOCSTRINGS() (在 test.support 模块中)
@anchor{library/test test support MISSING_C_DOCSTRINGS}@anchor{34c2}
@deffn {数据} test.support.MISSING_C_DOCSTRINGS

Return @code{True} if running on CPython, not on Windows, and configuration
not set with @code{WITH_DOC_STRINGS}.
@end deffn

@geindex HAVE_DOCSTRINGS() (在 test.support 模块中)
@anchor{library/test test support HAVE_DOCSTRINGS}@anchor{34c3}
@deffn {数据} test.support.HAVE_DOCSTRINGS

Check for presence of docstrings.
@end deffn

@geindex TEST_HTTP_URL() (在 test.support 模块中)
@anchor{library/test test support TEST_HTTP_URL}@anchor{34c4}
@deffn {数据} test.support.TEST_HTTP_URL

定义用于网络测试的韧性 HTTP 服务器的 URL。
@end deffn

@geindex ALWAYS_EQ() (在 test.support 模块中)
@anchor{library/test test support ALWAYS_EQ}@anchor{34c5}
@deffn {数据} test.support.ALWAYS_EQ

等于任何对象的对象。 用于测试混合类型比较。
@end deffn

@geindex NEVER_EQ() (在 test.support 模块中)
@anchor{library/test test support NEVER_EQ}@anchor{34c6}
@deffn {数据} test.support.NEVER_EQ

不等于任何对象的对象 (即使是 @ref{34c5,,ALWAYS_EQ})。 用于测试混合类型比较。
@end deffn

@geindex LARGEST() (在 test.support 模块中)
@anchor{library/test test support LARGEST}@anchor{34c7}
@deffn {数据} test.support.LARGEST

大于任何对象的对象（除了其自身）。 用于测试混合类型比较。
@end deffn

@geindex SMALLEST() (在 test.support 模块中)
@anchor{library/test test support SMALLEST}@anchor{34c8}
@deffn {数据} test.support.SMALLEST

小于任何对象的对象（除了其自身）。 用于测试混合类型比较。Used to test mixed type comparison.
@end deffn

@ref{106,,test.support} 模块定义了以下函数:

@geindex forget() (在 test.support 模块中)
@anchor{library/test test support forget}@anchor{34c9}
@deffn {函数} test.support.forget (module_name)

从 @code{sys.modules} 移除名为 @emph{module_name} 的模块并删除该模块的已编译字节码文件。
@end deffn

@geindex unload() (在 test.support 模块中)
@anchor{library/test test support unload}@anchor{34ca}
@deffn {函数} test.support.unload (name)

从 @code{sys.modules} 中删除 @emph{name}。
@end deffn

@geindex unlink() (在 test.support 模块中)
@anchor{library/test test support unlink}@anchor{34cb}
@deffn {函数} test.support.unlink (filename)

Call @ref{b21,,os.unlink()} on @emph{filename}.  On Windows platforms, this is
wrapped with a wait loop that checks for the existence of the file.
@end deffn

@geindex rmdir() (在 test.support 模块中)
@anchor{library/test test support rmdir}@anchor{34cc}
@deffn {函数} test.support.rmdir (filename)

Call @ref{b1f,,os.rmdir()} on @emph{filename}.  On Windows platforms, this is
wrapped with a wait loop that checks for the existence of the file.
@end deffn

@geindex rmtree() (在 test.support 模块中)
@anchor{library/test test support rmtree}@anchor{34cd}
@deffn {函数} test.support.rmtree (path)

Call @ref{350,,shutil.rmtree()} on @emph{path} or call @ref{329,,os.lstat()} and
@ref{b1f,,os.rmdir()} to remove a path and its contents.  On Windows platforms,
this is wrapped with a wait loop that checks for the existence of the files.
@end deffn

@geindex make_legacy_pyc() (在 test.support 模块中)
@anchor{library/test test support make_legacy_pyc}@anchor{34ce}
@deffn {函数} test.support.make_legacy_pyc (source)

将 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}/
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} pyc 文件移至旧版 pyc 位置并返回该旧版 pyc 文件的文件系统路径。 @emph{source} 的值是源文件的文件系统路径。 它不必真实存在，但是 PEP 3147/488 pyc 文件必须存在。
@end deffn

@geindex is_resource_enabled() (在 test.support 模块中)
@anchor{library/test test support is_resource_enabled}@anchor{34cf}
@deffn {函数} test.support.is_resource_enabled (resource)

如果 @emph{resource} 已启用并可用则返回 @code{True}。 可用资源列表只有当 @code{test.regrtest} 正在执行测试时才会被设置。
@end deffn

@geindex python_is_optimized() (在 test.support 模块中)
@anchor{library/test test support python_is_optimized}@anchor{34d0}
@deffn {函数} test.support.python_is_optimized ()

如果 Python 编译未使用 @code{-O0} 或 @code{-Og} 则返回 @code{True}。
@end deffn

@geindex with_pymalloc() (在 test.support 模块中)
@anchor{library/test test support with_pymalloc}@anchor{34d1}
@deffn {函数} test.support.with_pymalloc ()

返回 @code{_testcapi.WITH_PYMALLOC}。
@end deffn

@geindex requires() (在 test.support 模块中)
@anchor{library/test test support requires}@anchor{34ab}
@deffn {函数} test.support.requires (resource, msg=None)

如果 @emph{resource} 不可用则引发 @ref{34aa,,ResourceDenied}。 如果该异常被引发则 @emph{msg} 为传给 @ref{34aa,,ResourceDenied} 的参数。 如果被 @code{__name__} 为 @code{'__main__'} 的函数调用则总是返回 @code{True}。 在测试由 @code{test.regrtest} 执行时使用。
@end deffn

@geindex system_must_validate_cert() (在 test.support 模块中)
@anchor{library/test test support system_must_validate_cert}@anchor{34d2}
@deffn {函数} test.support.system_must_validate_cert (f)

Raise @ref{9f2,,unittest.SkipTest} on TLS certification validation failures.
@end deffn

@geindex sortdict() (在 test.support 模块中)
@anchor{library/test test support sortdict}@anchor{34d3}
@deffn {函数} test.support.sortdict (dict)

返回 @emph{dict} 按键排序的 repr。
@end deffn

@geindex findfile() (在 test.support 模块中)
@anchor{library/test test support findfile}@anchor{34d4}
@deffn {函数} test.support.findfile (filename, subdir=None)

返回名为 @emph{filename} 的文件的路径。 如果未找到匹配结果则返回 @emph{filename}。 这并不等于失败因为它也算是该文件的路径。

设置 @emph{subdir} 指明要用来查找文件的相对路径而不是直接在路径目录中查找。
@end deffn

@geindex create_empty_file() (在 test.support 模块中)
@anchor{library/test test support create_empty_file}@anchor{34d5}
@deffn {函数} test.support.create_empty_file (filename)

创建一个名为 @emph{filename} 的空文件。 如果文件已存在，则清空其内容。
@end deffn

@geindex fd_count() (在 test.support 模块中)
@anchor{library/test test support fd_count}@anchor{34d6}
@deffn {函数} test.support.fd_count ()

统计打开的文件描述符数量。
@end deffn

@geindex match_test() (在 test.support 模块中)
@anchor{library/test test support match_test}@anchor{34d7}
@deffn {函数} test.support.match_test (test)

Match @emph{test} to patterns set in @ref{34d8,,set_match_tests()}.
@end deffn

@geindex set_match_tests() (在 test.support 模块中)
@anchor{library/test test support set_match_tests}@anchor{34d8}
@deffn {函数} test.support.set_match_tests (patterns)

Define match test with regular expression @emph{patterns}.
@end deffn

@geindex run_unittest() (在 test.support 模块中)
@anchor{library/test test support run_unittest}@anchor{11c1}
@deffn {函数} test.support.run_unittest (*classes)

执行传给函数的 @ref{9ee,,unittest.TestCase} 子类。 此函数会扫描类中带有 @code{test_} 前缀的方法并单独执行这些测试。

将字符串作为形参传递也是合法的；这些形参应为 @code{sys.modules} 中的键。 每个被关联的模块将由 @code{unittest.TestLoader.loadTestsFromModule()} 执行扫描。 这通常出现在以下 @code{test_main()} 函数中:

@example
def test_main():
    support.run_unittest(__name__)
@end example

这将运行在指定模块中定义的所有测试。
@end deffn

@geindex run_doctest() (在 test.support 模块中)
@anchor{library/test test support run_doctest}@anchor{34d9}
@deffn {函数} test.support.run_doctest (module, verbosity=None, optionflags=0)

在给定的 @emph{module} 上运行 @ref{e9d,,doctest.testmod()}。 返回 @code{(failure_count, test_count)}。

如果 @emph{verbosity} 为 @code{None}，@ref{e9d,,doctest.testmod()} 运行时的消息详细程度将设为 @ref{34ac,,verbose}。 否则，运行时的消息详细程度将设为 @code{None}。 @emph{optionflags} 将作为 @code{optionflags} 传给 @ref{e9d,,doctest.testmod()}。
@end deffn

@geindex setswitchinterval() (在 test.support 模块中)
@anchor{library/test test support setswitchinterval}@anchor{34da}
@deffn {函数} test.support.setswitchinterval (interval)

将 @ref{219,,sys.setswitchinterval()} 设为给定的 @emph{interval}。 请为 Android 系统定义一个最小间隔以防止系统挂起。
@end deffn

@geindex check_impl_detail() (在 test.support 模块中)
@anchor{library/test test support check_impl_detail}@anchor{34db}
@deffn {函数} test.support.check_impl_detail (**guards)

Use this check to guard CPython's implementation-specific tests or to
run them only on the implementations guarded by the arguments:

@example
check_impl_detail()               # Only on CPython (default).
check_impl_detail(jython=True)    # Only on Jython.
check_impl_detail(cpython=False)  # Everywhere except CPython.
@end example
@end deffn

@geindex check_warnings() (在 test.support 模块中)
@anchor{library/test test support check_warnings}@anchor{34dc}
@deffn {函数} test.support.check_warnings (*filters, quiet=True)

一个用于 @ref{34dd,,warnings.catch_warnings()} 以更容易地测试特定警告是否被正确引发的便捷包装器。 它大致等价于调用 @code{warnings.catch_warnings(record=True)} 并将 @ref{34de,,warnings.simplefilter()} 设为 @code{always} 并附带自动验证已记录结果的选项。

@code{check_warnings} 接受 @code{("message regexp", WarningCategory)} 形式的 2 元组作为位置参数。 如果提供了一个或多个 @emph{filters}，或者如果可选的关键字参数 @emph{quiet} 为 @code{False}，则它会检查确认警告是符合预期的：每个已指定的过滤器必须匹配至少一个被包围的代码或测试失败时引发的警告，并且如果有任何未能匹配已指定过滤器的警告被引发则测试将失败。 要禁用这些检查中的第一项，请将 @emph{quiet} 设为 @code{True}。

如果未指定任何参数，则默认为:

@example
check_warnings(("", Warning), quiet=True)
@end example

在此情况下所有警告都会被捕获而不会引发任何错误。

在进入该上下文管理器时，将返回一个 @code{WarningRecorder} 实例。 来自 @ref{34dd,,catch_warnings()} 的下层警告列表可通过该记录器对象的 @ref{12f,,warnings} 属性来访问。 作为一个便捷方式，该对象中代表最近的警告的属性也可通过该记录器对象来直接访问（参见以下示例）。 如果未引发任何警告，则在其他情况下预期代表一个警告的任何对象属性都将返回 @code{None}。

该记录器对象还有一个 @code{reset()} 方法，该方法会清空警告列表。

该上下文管理器被设计为像这样来使用:

@example
with check_warnings(("assertion is always true", SyntaxWarning),
                    ("", UserWarning)):
    exec('assert(False, "Hey!")')
    warnings.warn(UserWarning("Hide me!"))
@end example

在此情况下如果两个警告都未被引发，或是引发了其他的警告，则 @ref{34dc,,check_warnings()} 将会引发一个错误。

当一个测试需要更深入地查看这些警告，而不是仅仅检查它们是否发生时，可以使用这样的代码:

@example
with check_warnings(quiet=True) as w:
    warnings.warn("foo")
    assert str(w.args[0]) == "foo"
    warnings.warn("bar")
    assert str(w.args[0]) == "bar"
    assert str(w.warnings[0].args[0]) == "foo"
    assert str(w.warnings[1].args[0]) == "bar"
    w.reset()
    assert len(w.warnings) == 0
@end example

在这里所有的警告都将被捕获，而测试代码会直接测试被捕获的警告。


在 3.2 版更改: 新增可选参数 @emph{filters} 和 @emph{quiet}。

@end deffn

@geindex check_no_resource_warning() (在 test.support 模块中)
@anchor{library/test test support check_no_resource_warning}@anchor{34df}
@deffn {函数} test.support.check_no_resource_warning (testcase)

检测是否没有任何 @ref{5d3,,ResourceWarning} 被引发的上下文管理器。 你必须在该上下文管理器结束之前移除可能发出 @ref{5d3,,ResourceWarning} 的对象。
@end deffn

@geindex set_memlimit() (在 test.support 模块中)
@anchor{library/test test support set_memlimit}@anchor{34c0}
@deffn {函数} test.support.set_memlimit (limit)

针对大内存测试设置 @ref{34bf,,max_memuse} 和 @ref{34c1,,real_max_memuse} 的值。
@end deffn

@geindex record_original_stdout() (在 test.support 模块中)
@anchor{library/test test support record_original_stdout}@anchor{34e0}
@deffn {函数} test.support.record_original_stdout (stdout)

存放来自 @emph{stdout} 的值。 它会在回归测试开始时处理 stdout。
@end deffn

@geindex get_original_stdout() (在 test.support 模块中)
@anchor{library/test test support get_original_stdout}@anchor{34e1}
@deffn {函数} test.support.get_original_stdout ()

返回 @ref{34e0,,record_original_stdout()} 所设置的原始 stdout 或者如果未设置则为 @code{sys.stdout}。
@end deffn

@geindex args_from_interpreter_flags() (在 test.support 模块中)
@anchor{library/test test support args_from_interpreter_flags}@anchor{34e2}
@deffn {函数} test.support.args_from_interpreter_flags ()

返回在 @code{sys.flags} 和 @code{sys.warnoptions} 中重新产生当前设置的命令行参数列表。
@end deffn

@geindex optim_args_from_interpreter_flags() (在 test.support 模块中)
@anchor{library/test test support optim_args_from_interpreter_flags}@anchor{34e3}
@deffn {函数} test.support.optim_args_from_interpreter_flags ()

返回在 @code{sys.flags} 中重新产生当前优化设置的命令行参数列表。
@end deffn

@geindex captured_stdin() (在 test.support 模块中)
@geindex captured_stdout() (在 test.support 模块中)
@geindex captured_stderr() (在 test.support 模块中)
@anchor{library/test test support captured_stdin}@anchor{34e4}
@deffn {函数} test.support.captured_stdin ()
@anchor{library/test test support captured_stdout}@anchor{34e5}
@deffnx {函数} test.support.captured_stdout ()
@anchor{library/test test support captured_stderr}@anchor{1156}
@deffnx {函数} test.support.captured_stderr ()

使用 @ref{924,,io.StringIO} 对象临时替换指定流的上下文管理器。

使用输出流的示例:

@example
with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"
@end example

使用输入流的示例:

@example
with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")
@end example
@end deffn

@geindex temp_dir() (在 test.support 模块中)
@anchor{library/test test support temp_dir}@anchor{34e6}
@deffn {函数} test.support.temp_dir (path=None, quiet=False)

一个在 @emph{path} 上创建临时目录并输出该目录的上下文管理器。

如果 @emph{path} 为 @code{None}，则会使用 @ref{1e0d,,tempfile.mkdtemp()} 来创建临时目录。 如果 @emph{quiet} 为 @code{False}，则该上下文管理器在发生错误时会引发一个异常。 在其他情况下，如果 @emph{path} 已被指定并且无法创建，则只会发出一个警告。
@end deffn

@geindex change_cwd() (在 test.support 模块中)
@anchor{library/test test support change_cwd}@anchor{34e7}
@deffn {函数} test.support.change_cwd (path, quiet=False)

一个临时性地将当前工作目录改为 @emph{path} 并输出该目录的上下文管理器。

如果 @emph{quiet} 为 @code{False}，此上下文管理器将在发生错误时引发一个异常。 在其他情况下，它将只发出一个警告并将当前工作目录保持原状。
@end deffn

@geindex temp_cwd() (在 test.support 模块中)
@anchor{library/test test support temp_cwd}@anchor{34e8}
@deffn {函数} test.support.temp_cwd (name='tempcwd', quiet=False)

一个临时性地创建新目录并改变当前工作目录（CWD）的上下文管理器。

临时性地改变当前工作目录之前此上下文管理器会在当前目录下创建一个名为 @emph{name} 的临时目录。 如果 @emph{name} 为 @code{None}，则会使用 @ref{1e0d,,tempfile.mkdtemp()} 创建临时目录。

如果 @emph{quiet} 为 @code{False} 并且无法创建或修改 CWD，则会引发一个错误。 在其他情况下，只会引发一个警告并使用原始 CWD。
@end deffn

@geindex temp_umask() (在 test.support 模块中)
@anchor{library/test test support temp_umask}@anchor{34e9}
@deffn {函数} test.support.temp_umask (umask)

一个临时性地设置进程掩码的上下文管理器。
@end deffn

@geindex disable_faulthandler() (在 test.support 模块中)
@anchor{library/test test support disable_faulthandler}@anchor{34ea}
@deffn {函数} test.support.disable_faulthandler ()

A context manager that replaces @code{sys.stderr} with @code{sys.__stderr__}.
@end deffn

@geindex gc_collect() (在 test.support 模块中)
@anchor{library/test test support gc_collect}@anchor{34eb}
@deffn {函数} test.support.gc_collect ()

强制收集尽可能多的对象。 这是有必要的因为垃圾回收器并不能保证及时回收资源。 这意味着 @code{__del__} 方法的调用可能会晚于预期而弱引用的存活长于预期。
@end deffn

@geindex disable_gc() (在 test.support 模块中)
@anchor{library/test test support disable_gc}@anchor{34ec}
@deffn {函数} test.support.disable_gc ()

A context manager that disables the garbage collector upon entry and
reenables it upon exit.
@end deffn

@geindex swap_attr() (在 test.support 模块中)
@anchor{library/test test support swap_attr}@anchor{34ed}
@deffn {函数} test.support.swap_attr (obj, attr, new_val)

上下文管理器用一个新对象来交换一个属性。

用法:

@example
with swap_attr(obj, "attr", 5):
    ...
@end example

这把 @code{obj.attr} 设为 5 并在 @code{with} 语句块内保持，在语句块结束时恢复原值。 如果 @code{attr} 不存在于 @code{obj} 中，它将被创建并在语句块结束时被删除。

旧值 (或者如果不存在旧值则为 @code{None}) 将被赋给 "as" 子句的目标，如果存在子句的话。
@end deffn

@geindex swap_item() (在 test.support 模块中)
@anchor{library/test test support swap_item}@anchor{34ee}
@deffn {函数} test.support.swap_item (obj, attr, new_val)

上下文件管理器用一个新对象来交换一个条目。

用法:

@example
with swap_item(obj, "item", 5):
    ...
@end example

这将把 @code{obj["item"]} 设为 5 并在 @code{with} 语句块内保持，在语句块结束时恢复旧值。 如果 @code{item} 不存在于 @code{obj} 中，它将被创建并在语句块结束时被删除。

旧值 (或者如果不存在旧值则为 @code{None}) 将被赋给 "as" 子句的目标，如果存在子句的话。
@end deffn

@geindex print_warning() (在 test.support 模块中)
@anchor{library/test test support print_warning}@anchor{34ef}
@deffn {函数} test.support.print_warning (msg)

打印一个警告到 @ref{34f0,,sys.__stderr__}。 将消息格式化为: @code{f"Warning -- @{msg@}"}。 如果 @emph{msg} 包含多行，则为每行添加 @code{"Warning -- "} 前缀。


3.9 新版功能.

@end deffn

@geindex wait_process() (在 test.support 模块中)
@anchor{library/test test support wait_process}@anchor{10a5}
@deffn {函数} test.support.wait_process (pid, *, exitcode, timeout=None)

等待直到进程 @emph{pid} 结束并检查进程退出代码是否为 @emph{exitcode}。

如果进程退出代码不等于 @emph{exitcode} 则引发 @ref{241,,AssertionError}。

如果进程运行时长超过 @emph{timeout} 秒 (默认为 @ref{fdf,,SHORT_TIMEOUT})，则杀死进程并引发 @ref{241,,AssertionError}。 超时特性在 Windows 上不可用。


3.9 新版功能.

@end deffn

@geindex wait_threads_exit() (在 test.support 模块中)
@anchor{library/test test support wait_threads_exit}@anchor{34f1}
@deffn {函数} test.support.wait_threads_exit (timeout=60.0)

等待直到 @code{with} 语句中所有已创建线程退出的上下文管理器。
@end deffn

@geindex start_threads() (在 test.support 模块中)
@anchor{library/test test support start_threads}@anchor{34f2}
@deffn {函数} test.support.start_threads (threads, unlock=None)

Context manager to start @emph{threads}.  It attempts to join the threads upon
exit.
@end deffn

@geindex calcobjsize() (在 test.support 模块中)
@anchor{library/test test support calcobjsize}@anchor{34f3}
@deffn {函数} test.support.calcobjsize (fmt)

Return @ref{110e,,struct.calcsize()} for @code{nP@{fmt@}0n} or, if @code{gettotalrefcount}
exists, @code{2PnP@{fmt@}0P}.
@end deffn

@geindex calcvobjsize() (在 test.support 模块中)
@anchor{library/test test support calcvobjsize}@anchor{34f4}
@deffn {函数} test.support.calcvobjsize (fmt)

Return @ref{110e,,struct.calcsize()} for @code{nPn@{fmt@}0n} or, if @code{gettotalrefcount}
exists, @code{2PnPn@{fmt@}0P}.
@end deffn

@geindex checksizeof() (在 test.support 模块中)
@anchor{library/test test support checksizeof}@anchor{34f5}
@deffn {函数} test.support.checksizeof (test, o, size)

对于测试用例 @emph{test}，断言 @emph{o} 的 @code{sys.getsizeof} 加 GC 头的大小等于 @emph{size}。
@end deffn

@geindex can_symlink() (在 test.support 模块中)
@anchor{library/test test support can_symlink}@anchor{34f6}
@deffn {函数} test.support.can_symlink ()

如果操作系统支持符号链接则返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex can_xattr() (在 test.support 模块中)
@anchor{library/test test support can_xattr}@anchor{34f7}
@deffn {函数} test.support.can_xattr ()

如果操作系统支持 xattr 支返回 @code{True}，否则返回 @code{False}。
@end deffn

@geindex skip_unless_symlink() (在 test.support 模块中)
@anchor{library/test test support skip_unless_symlink}@anchor{34f8}
@deffn {函数} @@test.support.skip_unless_symlink

一个用于运行需要符号链接支持的测试的装饰器。
@end deffn

@geindex skip_unless_xattr() (在 test.support 模块中)
@anchor{library/test test support skip_unless_xattr}@anchor{34f9}
@deffn {函数} @@test.support.skip_unless_xattr

一个用于运行需要 xattr 支持的测试的装饰器。
@end deffn

@geindex anticipate_failure() (在 test.support 模块中)
@anchor{library/test test support anticipate_failure}@anchor{34fa}
@deffn {函数} @@test.support.anticipate_failure (condition)

一个有条件地用 @ref{33b9,,unittest.expectedFailure()} 来标记测试的装饰器。 任何对此装饰器的使用都应当具有标识相应追踪事项的有关联注释。
@end deffn

@geindex run_with_locale() (在 test.support 模块中)
@anchor{library/test test support run_with_locale}@anchor{34fb}
@deffn {函数} @@test.support.run_with_locale (catstr, *locales)

一个在不同语言区域下运行函数的装饰器，并在其结束后正确地重置语言区域。 @emph{catstr} 是字符串形式的语言区域类别 (例如 @code{"LC_ALL"})。 传入的 @emph{locales} 将依次被尝试，并将使用第一个有效的语言区域。
@end deffn

@geindex run_with_tz() (在 test.support 模块中)
@anchor{library/test test support run_with_tz}@anchor{34fc}
@deffn {函数} @@test.support.run_with_tz (tz)

一个在指定时区下运行函数的装饰器，并在其结束后正确地重置时区。
@end deffn

@geindex requires_freebsd_version() (在 test.support 模块中)
@anchor{library/test test support requires_freebsd_version}@anchor{34fd}
@deffn {函数} @@test.support.requires_freebsd_version (*min_version)

Decorator for the minimum version when running test on FreeBSD.  If the
FreeBSD version is less than the minimum, raise @ref{9f2,,unittest.SkipTest}.
@end deffn

@geindex requires_linux_version() (在 test.support 模块中)
@anchor{library/test test support requires_linux_version}@anchor{34fe}
@deffn {函数} @@test.support.requires_linux_version (*min_version)

Decorator for the minimum version when running test on Linux.  If the
Linux version is less than the minimum, raise @ref{9f2,,unittest.SkipTest}.
@end deffn

@geindex requires_mac_version() (在 test.support 模块中)
@anchor{library/test test support requires_mac_version}@anchor{34ff}
@deffn {函数} @@test.support.requires_mac_version (*min_version)

Decorator for the minimum version when running test on macOS.  If the
macOS version is less than the minimum, raise @ref{9f2,,unittest.SkipTest}.
@end deffn

@geindex requires_IEEE_754() (在 test.support 模块中)
@anchor{library/test test support requires_IEEE_754}@anchor{3500}
@deffn {函数} @@test.support.requires_IEEE_754

用于在非 non-IEEE 754 平台上跳过测试的装饰器。
@end deffn

@geindex requires_zlib() (在 test.support 模块中)
@anchor{library/test test support requires_zlib}@anchor{3501}
@deffn {函数} @@test.support.requires_zlib

用于当 @ref{14d,,zlib} 不存在时跳过测试的装饰器。
@end deffn

@geindex requires_gzip() (在 test.support 模块中)
@anchor{library/test test support requires_gzip}@anchor{3502}
@deffn {函数} @@test.support.requires_gzip

用于当 @ref{8b,,gzip} 不存在时跳过测试的装饰器。
@end deffn

@geindex requires_bz2() (在 test.support 模块中)
@anchor{library/test test support requires_bz2}@anchor{3503}
@deffn {函数} @@test.support.requires_bz2

用于当 @ref{13,,bz2} 不存在时跳过测试的装饰器。
@end deffn

@geindex requires_lzma() (在 test.support 模块中)
@anchor{library/test test support requires_lzma}@anchor{3504}
@deffn {函数} @@test.support.requires_lzma

用于当 @ref{ad,,lzma} 不存在时跳过测试的装饰器。
@end deffn

@geindex requires_resource() (在 test.support 模块中)
@anchor{library/test test support requires_resource}@anchor{3505}
@deffn {函数} @@test.support.requires_resource (resource)

用于当 @emph{resource} 不可用时跳过测试的装饰器。
@end deffn

@geindex requires_docstrings() (在 test.support 模块中)
@anchor{library/test test support requires_docstrings}@anchor{3506}
@deffn {函数} @@test.support.requires_docstrings

用于仅当 @ref{34c3,,HAVE_DOCSTRINGS} 时才运行测试的装饰器。
@end deffn

@geindex cpython_only() (在 test.support 模块中)
@anchor{library/test test support cpython_only}@anchor{3507}
@deffn {函数} @@test.support.cpython_only (test)

表示仅适用于 CPython 的测试的装饰器。
@end deffn

@geindex impl_detail() (在 test.support 模块中)
@anchor{library/test test support impl_detail}@anchor{3508}
@deffn {函数} @@test.support.impl_detail (msg=None, **guards)

用于在 @emph{guards} 上发起调用 @ref{34db,,check_impl_detail()} 的装饰器。 如果调用返回 @code{False}，则使用 @emph{msg} 作为跳过测试的原因。
@end deffn

@geindex no_tracing() (在 test.support 模块中)
@anchor{library/test test support no_tracing}@anchor{3509}
@deffn {函数} @@test.support.no_tracing (func)

用于在测试期间临时关闭追踪的装饰器。
@end deffn

@geindex refcount_test() (在 test.support 模块中)
@anchor{library/test test support refcount_test}@anchor{350a}
@deffn {函数} @@test.support.refcount_test (test)

用于涉及引用计数的测试的装饰器。 如果测试不是由 CPython 运行则该装饰器不会运行测试。 在测试期间会取消设置任何追踪函数以由追踪函数导致的意外引用计数。
@end deffn

@geindex reap_threads() (在 test.support 模块中)
@anchor{library/test test support reap_threads}@anchor{350b}
@deffn {函数} @@test.support.reap_threads (func)

用于确保即使测试失败线程仍然会被清理的装饰器。
@end deffn

@geindex bigmemtest() (在 test.support 模块中)
@anchor{library/test test support bigmemtest}@anchor{350c}
@deffn {函数} @@test.support.bigmemtest (size, memuse, dry_run=True)

用于大内存测试的装饰器。

@emph{size} 是测试所请求的大小（以任意的，由测试解读的单位。）  @emph{memuse} 是测试的每单元字节数，或是对它的良好估计。 例如，一个需要两个字节缓冲区，每个缓冲区 4 GiB，则可以用 @code{@@bigmemtest(size=_4G, memuse=2)} 来装饰。

@emph{size} 参数通常作为额外参数传递给被测试的方法。 如果 @emph{dry_run} 为 @code{True}，则传给测试方法的值可能少于所请求的值。 如果 @emph{dry_run} 为 @code{False}，则意味着当当未指定 @code{-M} 时测试将不支持虚拟运行。
@end deffn

@geindex bigaddrspacetest() (在 test.support 模块中)
@anchor{library/test test support bigaddrspacetest}@anchor{350d}
@deffn {函数} @@test.support.bigaddrspacetest (f)

Decorator for tests that fill the address space.  @emph{f} is the function to
wrap.
@end deffn

@geindex make_bad_fd() (在 test.support 模块中)
@anchor{library/test test support make_bad_fd}@anchor{350e}
@deffn {函数} test.support.make_bad_fd ()

通过打开并关闭临时文件来创建一个无效的文件描述符，并返回其描述器。
@end deffn

@geindex check_syntax_error() (在 test.support 模块中)
@anchor{library/test test support check_syntax_error}@anchor{350f}
@deffn {函数} test.support.check_syntax_error (testcase, statement, errtext='@w{'}, *, lineno=None, offset=None)

用于通过尝试编译 @emph{statement} 来测试 @emph{statement} 中的语法错误。 @emph{testcase} 是测试的 @ref{124,,unittest} 实例。 @emph{errtext} 是应当匹配所引发的 @ref{562,,SyntaxError} 的字符串表示形式的正则表达式。 如果 @emph{lineno} 不为 @code{None}，则与异常所在的行进行比较。 如果 @emph{offset} 不为 @code{None}，则与异常的偏移量进行比较。
@end deffn

@geindex check_syntax_warning() (在 test.support 模块中)
@anchor{library/test test support check_syntax_warning}@anchor{1187}
@deffn {函数} test.support.check_syntax_warning (testcase, statement, errtext='@w{'}, *, lineno=1, offset=None)

用于通过尝试编译 @emph{statement} 来测试 @emph{statement} 中的语法警告。 还会测试 @ref{2d0,,SyntaxWarning} 是否只发出了一次，以及它在转成错误时是否将被转换为 @ref{562,,SyntaxError}。 @emph{testcase} 是用于测试的 @ref{124,,unittest} 实例。  @emph{errtext} 是应当匹配所发出的 @ref{2d0,,SyntaxWarning} 以及所引发的 @ref{562,,SyntaxError} 的字符串表示形式的正则表达式。 如果 @emph{lineno} 不为 @code{None}，则与警告和异常所在的行进行比较。 如果 @emph{offset} 不为 @code{None}，则与异常的偏移量进行比较。


3.8 新版功能.

@end deffn

@geindex open_urlresource() (在 test.support 模块中)
@anchor{library/test test support open_urlresource}@anchor{3510}
@deffn {函数} test.support.open_urlresource (url, *args, **kw)

打开 @emph{url}。 如果打开失败，则引发 @ref{34a9,,TestFailed}。
@end deffn

@geindex import_module() (在 test.support 模块中)
@anchor{library/test test support import_module}@anchor{3511}
@deffn {函数} test.support.import_module (name, deprecated=False, *, required_on())

此函数会导入并返回指定名称的模块。 不同于正常的导入，如果模块无法被导入则此函数将引发 @ref{9f2,,unittest.SkipTest}。

如果 @emph{deprecated} 为 @code{True} 则在此导入操作期间模块和包的弃用消息会被屏蔽。 如果某个模块在特定平台上是必需的而在其他平台上是可选的，请为包含平台前缀的可迭代对象设置 @emph{required_on}，此对象将与 @ref{3db,,sys.platform} 进行比对。


3.1 新版功能.

@end deffn

@geindex import_fresh_module() (在 test.support 模块中)
@anchor{library/test test support import_fresh_module}@anchor{3512}
@deffn {函数} test.support.import_fresh_module (name, fresh=(), blocked=(), deprecated=False)

此函数会在执行导入之前通过从 @code{sys.modules} 移除指定模块来导入并返回指定 Python 模块的新副本。 请注意这不同于 @code{reload()}，原来的模块不会受到此操作的影响。

@emph{fresh} 是包含在执行导入之前还要从 @code{sys.modules} 缓存中移除的附加模块名称的可迭代对象。

@emph{blocked} 是包含模块名称的可迭代对象，导入期间在模块缓存中它会被替换为 @code{None} 以确保尝试导入将引发 @ref{16c,,ImportError}。

指定名称的模块以及任何在 @emph{fresh} 和 @emph{blocked} 形参中指明的模块会在开始导入之前被保存并在全新导入完成时被重新插入到 @code{sys.modules} 中。

如果 @emph{deprecated} 为 @code{True} 则在此导入操作期间模块和包的弃用消息会被屏蔽。

如果指定名称的模块无法被导入则此函数将引发 @ref{16c,,ImportError}.

用法示例:

@example
# Get copies of the warnings module for testing without affecting the
# version being used by the rest of the test suite. One copy uses the
# C implementation, the other is forced to use the pure Python fallback
# implementation
py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
@end example


3.1 新版功能.

@end deffn

@geindex modules_setup() (在 test.support 模块中)
@anchor{library/test test support modules_setup}@anchor{3513}
@deffn {函数} test.support.modules_setup ()

返回 @ref{109a,,sys.modules} 的副本。
@end deffn

@geindex modules_cleanup() (在 test.support 模块中)
@anchor{library/test test support modules_cleanup}@anchor{3514}
@deffn {函数} test.support.modules_cleanup (oldmodules)

移除 @emph{oldmodules} 和 @code{encodings} 以外的模块以保留内部缓冲区。
@end deffn

@geindex threading_setup() (在 test.support 模块中)
@anchor{library/test test support threading_setup}@anchor{3515}
@deffn {函数} test.support.threading_setup ()

返回当前线程计数和悬空线程的副本。
@end deffn

@geindex threading_cleanup() (在 test.support 模块中)
@anchor{library/test test support threading_cleanup}@anchor{3516}
@deffn {函数} test.support.threading_cleanup (*original_values)

清理未在 @emph{original_values} 中指定的线程。 被设计为如果有一个测试在后台离开正在运行的线程时会发出警告。
@end deffn

@geindex join_thread() (在 test.support 模块中)
@anchor{library/test test support join_thread}@anchor{3517}
@deffn {函数} test.support.join_thread (thread, timeout=30.0)

在 @emph{timeout} 秒之内合并一个 @emph{thread}。 如果线程在 @emph{timeout} 秒后仍然存活则引发 @ref{241,,AssertionError}。
@end deffn

@geindex reap_children() (在 test.support 模块中)
@anchor{library/test test support reap_children}@anchor{3518}
@deffn {函数} test.support.reap_children ()

只要有子进程启动就在 @code{test_main} 的末尾使用此函数。 这将有助于确保没有多余的子进程（僵尸）存在占用资源并在查找引用泄漏时造成问题。
@end deffn

@geindex get_attribute() (在 test.support 模块中)
@anchor{library/test test support get_attribute}@anchor{3519}
@deffn {函数} test.support.get_attribute (obj, name)

获取一个属性，如果引发了 @ref{4aa,,AttributeError} 则会引发 @ref{9f2,,unittest.SkipTest}。
@end deffn

@geindex catch_threading_exception() (在 test.support 模块中)
@anchor{library/test test support catch_threading_exception}@anchor{112b}
@deffn {函数} test.support.catch_threading_exception ()

使用 @ref{365,,threading.excepthook()} 来捕获 @ref{21b,,threading.Thread} 异常的上下文管理器。

当异常被捕获时要设置的属性:


@itemize *

@item 
@code{exc_type}

@item 
@code{exc_value}

@item 
@code{exc_traceback}

@item 
@code{thread}
@end itemize

参见 @ref{365,,threading.excepthook()} 文档。

这些属性在上下文管理器退出时将被删除。

用法:

@example
with support.catch_threading_exception() as cm:
    # code spawning a thread which raises an exception
    ...

    # check the thread exception, use cm attributes:
    # exc_type, exc_value, exc_traceback, thread
    ...

# exc_type, exc_value, exc_traceback, thread attributes of cm no longer
# exists at this point
# (to avoid reference cycles)
@end example


3.8 新版功能.

@end deffn

@geindex catch_unraisable_exception() (在 test.support 模块中)
@anchor{library/test test support catch_unraisable_exception}@anchor{112d}
@deffn {函数} test.support.catch_unraisable_exception ()

使用 @ref{361,,sys.unraisablehook()} 来捕获不可引发的异常的上下文管理器。

存储异常值 (@code{cm.unraisable.exc_value}) 会创建一个引用循环。 引用循环将在上下文管理器退出时被显式地打破。

存储对象 (@code{cm.unraisable.object}) 如果被设置为一个正在最终化的对象则可以恢复它。 退出上下文管理器将清除已存在对象。

用法:

@example
with support.catch_unraisable_exception() as cm:
    # code creating an "unraisable exception"
    ...

    # check the unraisable exception: use cm.unraisable
    ...

# cm.unraisable attribute no longer exists at this point
# (to break a reference cycle)
@end example


3.8 新版功能.

@end deffn

@geindex load_package_tests() (在 test.support 模块中)
@anchor{library/test test support load_package_tests}@anchor{351a}
@deffn {函数} test.support.load_package_tests (pkg_dir, loader, standard_tests, pattern)

在测试包中使用的 @ref{124,,unittest} @code{load_tests} 协议的通用实现。 @emph{pkg_dir} 是包的根目录；@emph{loader}, @emph{standard_tests} 和 @emph{pattern} 是 @code{load_tests} 所期望的参数。 在简单的情况下，测试包的 @code{__init__.py} 可以是下面这样的:

@example
import os
from test.support import load_package_tests

def load_tests(*args):
    return load_package_tests(os.path.dirname(__file__), *args)
@end example
@end deffn

@geindex fs_is_case_insensitive() (在 test.support 模块中)
@anchor{library/test test support fs_is_case_insensitive}@anchor{351b}
@deffn {函数} test.support.fs_is_case_insensitive (directory)

如果 @emph{directory} 的文件系统对大小写敏感则返回 @code{True}。
@end deffn

@geindex detect_api_mismatch() (在 test.support 模块中)
@anchor{library/test test support detect_api_mismatch}@anchor{351c}
@deffn {函数} test.support.detect_api_mismatch (ref_api, other_api, *, ignore=())

返回未在 @emph{other_api} 中找到的 @emph{ref_api} 的属性、函数或方法的集合，除去在 @emph{ignore} 中指明的要在这个检查中忽略的已定义条目列表。

在默认情况下这将跳过以 '_' 打头的私有属性但包括所有魔术方法，即以 '__' 打头和结尾的方法。


3.5 新版功能.

@end deffn

@geindex patch() (在 test.support 模块中)
@anchor{library/test test support patch}@anchor{351d}
@deffn {函数} test.support.patch (test_instance, object_to_patch, attr_name, new_value)

用 @emph{new_value} 重载 @emph{object_to_patch.attr_name}。并向 @emph{test_instance} 添加清理过程以便为 @emph{attr_name} 恢复 @emph{object_to_patch}。 @emph{attr_name} 应当是 @emph{object_to_patch} 的一个有效属性。
@end deffn

@geindex run_in_subinterp() (在 test.support 模块中)
@anchor{library/test test support run_in_subinterp}@anchor{351e}
@deffn {函数} test.support.run_in_subinterp (code)

在子解释器中运行 @emph{code}。 如果启用了 @ref{11d,,tracemalloc} 则会引发 @ref{9f2,,unittest.SkipTest}。
@end deffn

@geindex check_free_after_iterating() (在 test.support 模块中)
@anchor{library/test test support check_free_after_iterating}@anchor{351f}
@deffn {函数} test.support.check_free_after_iterating (test, iter, cls, args=())

Assert that @emph{iter} is deallocated after iterating.
@end deffn

@geindex missing_compiler_executable() (在 test.support 模块中)
@anchor{library/test test support missing_compiler_executable}@anchor{3520}
@deffn {函数} test.support.missing_compiler_executable (cmd_names=[])

检查在 @emph{cmd_names} 中列出名称的或者当 @emph{cmd_names} 为空时所有的编译器可执行文件是否存在并返回第一个丢失的可执行文件或者如果未发现任何丢失则返回 @code{None}。
@end deffn

@geindex check__all__() (在 test.support 模块中)
@anchor{library/test test support check__all__}@anchor{3521}
@deffn {函数} test.support.check__all__ (test_case, module, name_of_module=None, extra=(), blacklist=())

断言 @emph{module} 的 @code{__all__} 变量包含全部公有名称。

模块的公有名称（它的 API）是根据它们是否符合公有名称惯例并在 @emph{module} 中被定义来自动检测的。

@emph{name_of_module} 参数可以（用字符串或元组的形式）指定一个 API 可以被定义为什么模块以便被检测为一个公共 API。 一种这样的情况会在 @emph{module} 从其他模块，可能是一个 C 后端 (如 @code{csv} 和它的 @code{_csv}) 导入其公共 API 的某一组成部分时发生。

@emph{extra} 参数可以是一个在其他情况下不会被自动检测为 "public" 的名称集合，例如没有适当 @code{__module__} 属性的对象。 如果提供该参数，它将被添加到自动检测到的对象中。

The @emph{blacklist} argument can be a set of names that must not be treated as part of
the public API even though their names indicate otherwise.

用法示例:

@example
import bar
import foo
import unittest
from test import support

class MiscTestCase(unittest.TestCase):
    def test__all__(self):
        support.check__all__(self, foo)

class OtherTestCase(unittest.TestCase):
    def test__all__(self):
        extra = @{'BAR_CONST', 'FOO_CONST'@}
        blacklist = @{'baz'@}  # Undocumented name.
        # bar imports part of its API from _bar.
        support.check__all__(self, bar, ('bar', '_bar'),
                             extra=extra, blacklist=blacklist)
@end example


3.6 新版功能.

@end deffn

@geindex adjust_int_max_str_digits() (在 test.support 模块中)
@anchor{library/test test support adjust_int_max_str_digits}@anchor{3522}
@deffn {函数} test.support.adjust_int_max_str_digits (max_digits)

This function returns a context manager that will change the global
@ref{f62,,sys.set_int_max_str_digits()} setting for the duration of the
context to allow execution of test code that needs a different limit
on the number of digits when converting between an integer and string.


3.9.14 新版功能.

@end deffn

@ref{106,,test.support} 模块定义了以下的类:

@geindex TransientResource (test.support 中的类)
@anchor{library/test test support TransientResource}@anchor{3523}
@deffn {类} test.support.TransientResource (exc, **kwargs)

Instances are a context manager that raises @ref{34aa,,ResourceDenied} if the
specified exception type is raised.  Any keyword arguments are treated as
attribute/value pairs to be compared against any exception raised within the
@ref{7e4,,with} statement.  Only if all pairs match properly against
attributes on the exception is @ref{34aa,,ResourceDenied} raised.
@end deffn

@geindex EnvironmentVarGuard (test.support 中的类)
@anchor{library/test test support EnvironmentVarGuard}@anchor{3524}
@deffn {类} test.support.EnvironmentVarGuard

用于临时性地设置或取消设置环境变量的类。 其实例可被用作上下文管理器并具有完整的字典接口用来查询/修改下层的 @code{os.environ}。 在从上下文管理器退出之后所有通过此实例对环境变量进行的修改都将被回滚。


在 3.1 版更改: 增加了字典接口。

@end deffn

@geindex set() (test.support.EnvironmentVarGuard 方法)
@anchor{library/test test support EnvironmentVarGuard set}@anchor{3525}
@deffn {方法} EnvironmentVarGuard.set (envvar, value)

临时性地将环境变量 @code{envvar} 的值设为 @code{value}。
@end deffn

@geindex unset() (test.support.EnvironmentVarGuard 方法)
@anchor{library/test test support EnvironmentVarGuard unset}@anchor{3526}
@deffn {方法} EnvironmentVarGuard.unset (envvar)

临时性地取消设置环境变量 @code{envvar}。
@end deffn

@geindex SuppressCrashReport (test.support 中的类)
@anchor{library/test test support SuppressCrashReport}@anchor{3527}
@deffn {类} test.support.SuppressCrashReport

一个用于在预期会使子进程崩溃的测试时尽量防止弹出崩溃对话框的上下文管理器。

在 Windows 上，它会使用 SetErrorMode@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx} 来禁用 Windows 错误报告对话框。

在 UNIX 上，会使用 @ref{3528,,resource.setrlimit()} 来将 @ref{3529,,resource.RLIMIT_CORE} 的软限制设为 0 以防止创建核心转储文件。

在这两个平台上，旧值都将被 @ref{d66,,__exit__()} 恢复。
@end deffn

@geindex CleanImport (test.support 中的类)
@anchor{library/test test support CleanImport}@anchor{352a}
@deffn {类} test.support.CleanImport (*module_names)

A context manager to force import to return a new module reference.  This
is useful for testing module-level behaviors, such as the emission of a
DeprecationWarning on import.  Example usage:

@example
with CleanImport('foo'):
    importlib.import_module('foo')  # New reference.
@end example
@end deffn

@geindex DirsOnSysPath (test.support 中的类)
@anchor{library/test test support DirsOnSysPath}@anchor{352b}
@deffn {类} test.support.DirsOnSysPath (*paths)

A context manager to temporarily add directories to sys.path.

这将创建 @ref{262,,sys.path} 的一个副本，添加作为位置参数传入的任何目录，然后在上下文结束时将 @ref{262,,sys.path} 还原到副本的设置。

请注意该上下文管理器代码块中 @emph{所有} 对 @ref{262,,sys.path} 的修改，包括对象的替换，都将在代码块结束时被还原。
@end deffn

@geindex SaveSignals (test.support 中的类)
@anchor{library/test test support SaveSignals}@anchor{352c}
@deffn {类} test.support.SaveSignals

用于保存和恢复由 Python 句柄的所注册的信号处理句柄。
@end deffn

@geindex Matcher (test.support 中的类)
@anchor{library/test test support Matcher}@anchor{352d}
@deffn {类} test.support.Matcher

@geindex matches() (test.support.Matcher 方法)
@anchor{library/test test support Matcher matches}@anchor{352e}
@deffn {方法} matches (self, d, **kwargs)

尝试对单个字典与所提供的参数进行匹配。
@end deffn

@geindex match_value() (test.support.Matcher 方法)
@anchor{library/test test support Matcher match_value}@anchor{352f}
@deffn {方法} match_value (self, k, dv, v)

尝试对单个已存储值 (@emph{dv}) 与所提供的值 (@emph{v}) 进行匹配。
@end deffn
@end deffn

@geindex WarningsRecorder (test.support 中的类)
@anchor{library/test test support WarningsRecorder}@anchor{3530}
@deffn {类} test.support.WarningsRecorder

用于为单元测试记录警告的类。 请参阅以上 @ref{34dc,,check_warnings()} 的文档来了解详情。
@end deffn

@geindex BasicTestRunner (test.support 中的类)
@anchor{library/test test support BasicTestRunner}@anchor{3531}
@deffn {类} test.support.BasicTestRunner

@geindex run() (test.support.BasicTestRunner 方法)
@anchor{library/test test support BasicTestRunner run}@anchor{3532}
@deffn {方法} run (test)

运行 @emph{test} 并返回结果。
@end deffn
@end deffn

@geindex FakePath (test.support 中的类)
@anchor{library/test test support FakePath}@anchor{3533}
@deffn {类} test.support.FakePath (path)

简单的 @ref{47b,,path-like object}。 它实现了 @code{__fspath__()} 方法，该方法将返回 @emph{path} 参数。 如果 @emph{path} 为一个异常，它将在 @code{__fspath__()} 中被引发。
@end deffn

@node test support socket_helper --- 用于套接字测试的工具,test support script_helper --- 用于 Python 执行测试工具,test support --- 针对 Python 测试套件的工具,开发工具
@anchor{library/test module-test support socket_helper}@anchor{109}@anchor{library/test test-support-socket-helper-utilities-for-socket-tests}@anchor{3534}
@subsection @code{test.support.socket_helper} --- 用于套接字测试的工具


@geindex test.support.socket_helper (模块)

@ref{109,,test.support.socket_helper} 模块提供了对套接字测试的支持。


3.9 新版功能.


@geindex IPV6_ENABLED() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper IPV6_ENABLED}@anchor{3535}
@deffn {数据} test.support.socket_helper.IPV6_ENABLED

设置为 @code{True} 如果主机打开IPv6, 否则 @code{False} .
@end deffn

@geindex find_unused_port() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper find_unused_port}@anchor{3536}
@deffn {函数} test.support.socket_helper.find_unused_port (family=socket.AF_INET, socktype=socket.SOCK_STREAM)

返回一个应当适合绑定的未使用端口。 这是通过创建一个与 @code{sock} 形参相同协议族和类型的临时套接字来达成的 (默认为 @ref{f76,,AF_INET}, @ref{d5a,,SOCK_STREAM})，并将其绑定到指定的主机地址 (默认为 @code{0.0.0.0}) 并将端口设为 0，以从 OS 引出一个未使用的瞬时端口。 这个临时套接字随后将被关闭并删除，然后返回该瞬时端口。

这个方法或 @ref{3537,,bind_port()} 应当被用于任何在测试期间需要绑定到特定端口的测试。 具体使用哪个取决于调用方代码是否会创建 Python 套接字，或者是否需要在构造器中提供或向外部程序提供未使用的端口（例如传给 openssl 的 s_server 模式的 @code{-accept} 参数）。 在可能的情况下将总是优先使用 @ref{3537,,bind_port()} 而非 @ref{3536,,find_unused_port()}。 不建议使用硬编码的端口因为将使测试的多个实例无法同时运行，这对 buildbot 来说是个问题。
@end deffn

@geindex bind_port() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper bind_port}@anchor{3537}
@deffn {函数} test.support.socket_helper.bind_port (sock, host=HOST)

将套接字绑定到一个空闲端口并返回端口号。 这依赖于瞬时端口以确保我们能使用一个未绑定端口。 这很重要因为可能会有许多测试同时运行，特别是在 buildbot 环境中。 如果 @code{sock.family} 为 @ref{f76,,AF_INET} 而 @code{sock.type} 为 @ref{d5a,,SOCK_STREAM}，并且套接字上设置了 @code{SO_REUSEADDR} 或 @code{SO_REUSEPORT} 则此方法将引发异常。 测试绝不应该为 TCP/IP 套接字设置这些套接字选项。 唯一需要设置这些选项的情况是通过多个 UDP 套接字来测试组播。

此外，如果 @code{SO_EXCLUSIVEADDRUSE} 套接字选项是可用的（例如在 Windows 上），它将在套接字上被设置。 这将阻止其他任何人在测试期间绑定到我们的主机/端口。
@end deffn

@geindex bind_unix_socket() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper bind_unix_socket}@anchor{3538}
@deffn {函数} test.support.socket_helper.bind_unix_socket (sock, addr)

绑定一个 unix 套接字，如果 @ref{700,,PermissionError} 被引发则会引发 @ref{9f2,,unittest.SkipTest}。
@end deffn

@geindex skip_unless_bind_unix_socket() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper skip_unless_bind_unix_socket}@anchor{3539}
@deffn {函数} @@test.support.socket_helper.skip_unless_bind_unix_socket

一个用于运行需要 Unix 套接字 @code{bind()} 功能的测试的装饰器。
@end deffn

@geindex transient_internet() (在 test.support.socket_helper 模块中)
@anchor{library/test test support socket_helper transient_internet}@anchor{34b6}
@deffn {函数} test.support.socket_helper.transient_internet (resource_name, *, timeout=30.0, errnos=())

一个在互联网连接的各种问题以异常的形式表现出来时会引发 @ref{34aa,,ResourceDenied} 的上下文管理器。
@end deffn

@node test support script_helper --- 用于 Python 执行测试工具,test support bytecode_helper --- 用于测试正确字节码生成的支持工具,test support socket_helper --- 用于套接字测试的工具,开发工具
@anchor{library/test module-test support script_helper}@anchor{108}@anchor{library/test test-support-script-helper-utilities-for-the-python-execution-tests}@anchor{353a}
@subsection @code{test.support.script_helper} --- 用于 Python 执行测试工具


@geindex test.support.script_helper (模块)

@ref{108,,test.support.script_helper} 模块提供了对 Python 的脚本执行测试的支持。

@geindex interpreter_requires_environment() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper interpreter_requires_environment}@anchor{353b}
@deffn {函数} test.support.script_helper.interpreter_requires_environment ()

如果 @code{sys.executable interpreter} 需要环境变量才能运行则返回 @code{True}。

这被设计用来配合 @code{@@unittest.skipIf()} 以便标注需要使用to annotate tests that need to use an @code{assert_python*()} 函数来启动隔离模式 (@code{-I}) 或无环境模式 (@code{-E}) 子解释器的测试。

正常的编译和测试运行不会进入这种状况但它在尝试从一个使用 Python 的当前家目录查找逻辑找不到明确的家目录的解释器运行标准库测试套件时有可能发生。

设置 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 是一种能让大多数测试套件在这种情况下运行的办法。 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 或 
@geindex PYTHONUSERSITE
@geindex 环境变量; PYTHONUSERSITE
@code{PYTHONUSERSITE} 是另外两个可影响解释器是否能启动的常见环境变量。
@end deffn

@geindex run_python_until_end() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper run_python_until_end}@anchor{353c}
@deffn {函数} test.support.script_helper.run_python_until_end (*args, **env_vars)

基于 @emph{env_vars} 设置环境以便在子进程中运行解释器。 它的值可以包括 @code{__isolated}, @code{__cleanenv}, @code{__cwd}, and @code{TERM}。


在 3.9 版更改: 此函数不会再从 @emph{stderr} 去除空格符。

@end deffn

@geindex assert_python_ok() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper assert_python_ok}@anchor{353d}
@deffn {函数} test.support.script_helper.assert_python_ok (*args, **env_vars)

断言附带 @emph{args} 和可选的环境变量 @emph{env_vars} 运行解释器会成功 (@code{rc == 0}) 并返回一个 @code{(return code, stdout, stderr)} 元组。

If the @code{__cleanenv} keyword is set, @emph{env_vars} is used as a fresh
environment.

Python is started in isolated mode (command line option @code{-I}),
except if the @code{__isolated} keyword is set to @code{False}.


在 3.9 版更改: 此函数不会再从 @emph{stderr} 去除空格符。

@end deffn

@geindex assert_python_failure() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper assert_python_failure}@anchor{353e}
@deffn {函数} test.support.script_helper.assert_python_failure (*args, **env_vars)

断言附带 @emph{args} 和可选的环境变量 @emph{env_vars} 运行解释器会失败 (@code{rc != 0}) 并返回一个 @code{(return code, stdout, stderr)} 元组。

更多选项请参阅 @ref{353d,,assert_python_ok()}。


在 3.9 版更改: 此函数不会再从 @emph{stderr} 去除空格符。

@end deffn

@geindex spawn_python() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper spawn_python}@anchor{353f}
@deffn {函数} test.support.script_helper.spawn_python (*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)

使用给定的参数运行一个 Python 子进程。

@emph{kw} 是要传给 @ref{3e3,,subprocess.Popen()} 的额外关键字参数。 返回一个 @ref{3e3,,subprocess.Popen} 对象。
@end deffn

@geindex kill_python() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper kill_python}@anchor{3540}
@deffn {函数} test.support.script_helper.kill_python (p)

运行给定的 @ref{3e3,,subprocess.Popen} 进程直至完成并返回 stdout.
@end deffn

@geindex make_script() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper make_script}@anchor{3541}
@deffn {函数} test.support.script_helper.make_script (script_dir, script_basename, source, omit_suffix=False)

在路径 @emph{script_dir} 和 @emph{script_basename} 中创建包含 @emph{source} 的脚本。 如果 @emph{omit_suffix} 为 @code{False}，则为名称添加 @code{.py}。 返回完整的脚本路径。
@end deffn

@geindex make_zip_script() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper make_zip_script}@anchor{3542}
@deffn {函数} test.support.script_helper.make_zip_script (zip_dir, zip_basename, script_name, name_in_zip=None)

使用 @emph{zip_dir} 和 @emph{zip_basename} 创建扩展名为 @code{zip} 的 zip 文件，其中包含 @emph{script_name} 中的文件。 @emph{name_in_zip} 为归档名。 返回一个包含 @code{(full path, full path of archive name)} 的元组。
@end deffn

@geindex make_pkg() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper make_pkg}@anchor{3543}
@deffn {函数} test.support.script_helper.make_pkg (pkg_dir, init_source='@w{'})

创建一个名为 @emph{pkg_dir} 的目录，其中包含一个 @code{__init__} 文件并以 @emph{init_source} 作为其内容。
@end deffn

@geindex make_zip_pkg() (在 test.support.script_helper 模块中)
@anchor{library/test test support script_helper make_zip_pkg}@anchor{3544}
@deffn {函数} test.support.script_helper.make_zip_pkg (zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False)

使用 @emph{zip_dir} 和 @emph{zip_basename} 创建一个 zip 包目录，其中包含一个空的 @code{__init__} 文件和一个包含 @emph{source} 的文件 @emph{script_basename}。 如果 @emph{compiled} 为 @code{True}，则两个源文件将被编译并添加到 zip 包中。 返回一个以完整 zip 路径和 zip 文件归档名为元素的元组。
@end deffn

@node test support bytecode_helper --- 用于测试正确字节码生成的支持工具,,test support script_helper --- 用于 Python 执行测试工具,开发工具
@anchor{library/test module-test support bytecode_helper}@anchor{107}@anchor{library/test test-support-bytecode-helper-support-tools-for-testing-correct-bytecode-generation}@anchor{3545}
@subsection @code{test.support.bytecode_helper} --- 用于测试正确字节码生成的支持工具


@geindex test.support.bytecode_helper (模块)

@ref{107,,test.support.bytecode_helper} 模块提供了对测试和检查字节码生成的支持。


3.9 新版功能.


The module defines the following class:

@geindex BytecodeTestCase (test.support.bytecode_helper 中的类)
@anchor{library/test test support bytecode_helper BytecodeTestCase}@anchor{3546}
@deffn {类} test.support.bytecode_helper.BytecodeTestCase (unittest.TestCase)

这个类具有用于检查字节码的自定义断言。
@end deffn

@geindex get_disassembly_as_string() (test.support.bytecode_helper.BytecodeTestCase 方法)
@anchor{library/test test support bytecode_helper BytecodeTestCase get_disassembly_as_string}@anchor{3547}
@deffn {方法} BytecodeTestCase.get_disassembly_as_string (co)

以字符串形式返回 @emph{co} 的汇编码。
@end deffn

@geindex assertInBytecode() (test.support.bytecode_helper.BytecodeTestCase 方法)
@anchor{library/test test support bytecode_helper BytecodeTestCase assertInBytecode}@anchor{3548}
@deffn {方法} BytecodeTestCase.assertInBytecode (x, opname, argval=_UNSPECIFIED)

如果找到 @emph{opname} 则返回 instr，否则抛出 @ref{241,,AssertionError}。
@end deffn

@geindex assertNotInBytecode() (test.support.bytecode_helper.BytecodeTestCase 方法)
@anchor{library/test test support bytecode_helper BytecodeTestCase assertNotInBytecode}@anchor{3549}
@deffn {方法} BytecodeTestCase.assertNotInBytecode (x, opname, argval=_UNSPECIFIED)

如果找到 @emph{opname} 则抛出 @ref{241,,AssertionError}。
@end deffn

@node 调试和分析,软件打包和分发,开发工具,Python 标准库
@anchor{library/debug doc}@anchor{354a}@anchor{library/debug debugging-and-profiling}@anchor{354b}
@section 调试和分析


这些库可以帮助你进行 Python 开发：调试器使你能够逐步执行代码，分析堆栈帧并设置中断点等等，性能分析器可以运行代码并为你提供执行时间的详细数据，使你能够找出你的程序中的瓶颈。 审计事件提供运行时行为的可见性，如果没有此工具则需要进行侵入式调试或修补。
@anchor{library/audit_events audit-events}@anchor{354c}
@geindex audit events

@menu
* 审计事件表:: 
* bdb: bdb --- 调试器框架. 调试器框架
* faulthandler —— 转储 Python 的跟踪信息:: 
* pdb: pdb --- Python 的调试器. Python 的调试器
* Python Profilers 分析器:: 
* timeit: timeit --- 测量小代码片段的执行时间. 测量小代码片段的执行时间
* trace: trace --- 跟踪Python语句执行. 跟踪Python语句执行
* tracemalloc: tracemalloc --- 跟踪内存分配. 跟踪内存分配

@end menu

@node 审计事件表,bdb --- 调试器框架,,调试和分析
@anchor{library/audit_events doc}@anchor{354d}@anchor{library/audit_events audit-events-table}@anchor{354e}
@subsection 审计事件表


下表包含了在整个 CPython 运行时和标准库中由 @ref{109f,,sys.audit()} 或 @ref{10b1,,PySys_Audit()} 调用所引发的全部事件。 这些调用是在 3.8.0 或更高版本中添加了 (参见 
@geindex Python 提高建议; PEP 578
PEP 578@footnote{https://www.python.org/dev/peps/pep-0578})。

请参阅 @ref{354f,,sys.addaudithook()} 和 @ref{3550,,PySys_AddAuditHook()} 了解有关处理这些事件的详细信息。

@strong{CPython implementation detail:} 此表是根据 CPython 文档生成的，可能无法表示其他实现所引发的事件。 请参阅你的运行时专属的文档了解实际引发的事件。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

Audit event

@tab

Arguments

@tab

References

@item

array.__new__

@tab

@code{typecode}, @code{initializer}

@tab

@ref{217,,[1]}

@item

builtins.breakpoint

@tab

@code{breakpointhook}

@tab

@ref{414,,[1]}

@item

builtins.id

@tab

@code{id}

@tab

@ref{e53,,[1]}

@item

builtins.input

@tab

@code{prompt}

@tab

@ref{d3b,,[1]}

@item

builtins.input/result

@tab

@code{result}

@tab

@ref{d3b,,[1]}

@item

code.__new__

@tab

@code{code}, @code{filename}, @code{name}, @code{argcount}, @code{posonlyargcount}, @code{kwonlyargcount}, @code{nlocals}, @code{stacksize}, @code{flags}

@tab

@ref{2d4,,[1]}

@item

compile

@tab

@code{source}, @code{filename}

@tab

@ref{2ee,,[1]}

@item

cpython.PyInterpreterState_Clear

@tab



@tab

@ref{3551,,[1]}

@item

cpython.PyInterpreterState_New

@tab



@tab

@ref{3552,,[1]}

@item

cpython._PySys_ClearAuditHooks

@tab



@tab

@ref{6ca,,[1]}

@item

cpython.run_command

@tab

@code{command}

@tab

@ref{136f,,[1]}

@item

cpython.run_file

@tab

@code{filename}

@tab

@ref{3553,,[1]}

@item

cpython.run_interactivehook

@tab

@code{hook}

@tab

@ref{9d3,,[1]}

@item

cpython.run_module

@tab

@code{module-name}

@tab

@ref{44c,,[1]}

@item

cpython.run_startup

@tab

@code{filename}

@tab

@ref{9d4,,[1]}

@item

cpython.run_stdin

@tab



@tab

@ref{3554,,[1]}

@item

ctypes.addressof

@tab

@code{obj}

@tab

@ref{2492,,[1]}

@item

ctypes.call_function

@tab

@code{func_pointer}, @code{arguments}

@tab

@ref{2487,,[1]}

@item

ctypes.cdata

@tab

@code{address}

@tab

@ref{24a3,,[1]}

@item

ctypes.cdata/buffer

@tab

@code{pointer}, @code{size}, @code{offset}

@tab

@ref{24a1,,[1]}@ref{24a2,,[2]}

@item

ctypes.create_string_buffer

@tab

@code{init}, @code{size}

@tab

@ref{2445,,[1]}

@item

ctypes.create_unicode_buffer

@tab

@code{init}, @code{size}

@tab

@ref{1120,,[1]}

@item

ctypes.dlopen

@tab

@code{name}

@tab

@ref{2484,,[1]}

@item

ctypes.dlsym

@tab

@code{library}, @code{name}

@tab

@ref{2484,,[1]}

@item

ctypes.dlsym/handle

@tab

@code{handle}, @code{name}

@tab

@ref{2484,,[1]}

@item

ctypes.get_errno

@tab



@tab

@ref{247e,,[1]}

@item

ctypes.get_last_error

@tab



@tab

@ref{2480,,[1]}

@item

ctypes.seh_exception

@tab

@code{code}

@tab

@ref{2487,,[1]}

@item

ctypes.set_errno

@tab

@code{errno}

@tab

@ref{247f,,[1]}

@item

ctypes.set_last_error

@tab

@code{error}

@tab

@ref{2481,,[1]}

@item

ctypes.string_at

@tab

@code{address}, @code{size}

@tab

@ref{249b,,[1]}

@item

ctypes.wstring_at

@tab

@code{address}, @code{size}

@tab

@ref{249d,,[1]}

@item

ensurepip.bootstrap

@tab

@code{root}

@tab

@ref{3555,,[1]}

@item

exec

@tab

@code{code_object}

@tab

@ref{c6a,,[1]}@ref{d14,,[2]}

@item

fcntl.fcntl

@tab

@code{fd}, @code{cmd}, @code{arg}

@tab

@ref{27fa,,[1]}

@item

fcntl.flock

@tab

@code{fd}, @code{operation}

@tab

@ref{3556,,[1]}

@item

fcntl.ioctl

@tab

@code{fd}, @code{request}, @code{arg}

@tab

@ref{eaa,,[1]}

@item

fcntl.lockf

@tab

@code{fd}, @code{cmd}, @code{len}, @code{start}, @code{whence}

@tab

@ref{e1f,,[1]}

@item

ftplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{2e25,,[1]}

@item

ftplib.sendcmd

@tab

@code{self}, @code{cmd}

@tab

@ref{2e29,,[1]}@ref{2e2a,,[2]}

@item

function.__new__

@tab

@code{code}

@tab

@ref{1b3b,,[1]}

@item

gc.get_objects

@tab

@code{generation}

@tab

@ref{305,,[1]}

@item

gc.get_referents

@tab

@code{objs}

@tab

@ref{1002,,[1]}

@item

gc.get_referrers

@tab

@code{objs}

@tab

@ref{1001,,[1]}

@item

glob.glob

@tab

@code{pathname}, @code{recursive}

@tab

@ref{6c7,,[1]}@ref{6c8,,[2]}

@item

imaplib.open

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{1b2,,[1]}

@item

imaplib.send

@tab

@code{self}, @code{data}

@tab

@ref{2e74,,[1]}

@item

import

@tab

@code{module}, @code{filename}, @code{sys.path}, @code{sys.meta_path}, @code{sys.path_hooks}

@tab

@ref{cef,,[1]}

@item

marshal.dumps

@tab

@code{value}, @code{version}

@tab

@ref{1e86,,[1]}

@item

marshal.load

@tab



@tab

@ref{1174,,[1]}

@item

marshal.loads

@tab

@code{bytes}

@tab

@ref{1174,,[1]}

@item

mmap.__new__

@tab

@code{fileno}, @code{length}, @code{access}, @code{offset}

@tab

@ref{323,,[1]}

@item

msvcrt.get_osfhandle

@tab

@code{fd}

@tab

@ref{3557,,[1]}

@item

msvcrt.locking

@tab

@code{fd}, @code{mode}, @code{nbytes}

@tab

@ref{3558,,[1]}

@item

msvcrt.open_osfhandle

@tab

@code{handle}, @code{flags}

@tab

@ref{3559,,[1]}

@item

nntplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{1c7,,[1]}@ref{1c8,,[2]}

@item

nntplib.putline

@tab

@code{self}, @code{line}

@tab

@ref{1c7,,[1]}@ref{1c8,,[2]}

@item

object.__delattr__

@tab

@code{obj}, @code{name}

@tab

@ref{1592,,[1]}

@item

object.__getattr__

@tab

@code{obj}, @code{name}

@tab

@ref{552,,[1]}

@item

object.__setattr__

@tab

@code{obj}, @code{name}, @code{value}

@tab

@ref{ef6,,[1]}

@item

open

@tab

@code{file}, @code{mode}, @code{flags}

@tab

@ref{16f,,[1]}@ref{757,,[2]}@ref{762,,[3]}

@item

os.add_dll_directory

@tab

@code{path}

@tab

@ref{2fa,,[1]}

@item

os.chdir

@tab

@code{path}

@tab

@ref{16e,,[1]}@ref{758,,[2]}

@item

os.chflags

@tab

@code{path}, @code{flags}

@tab

@ref{b17,,[1]}@ref{20da,,[2]}

@item

os.chmod

@tab

@code{path}, @code{mode}, @code{dir_fd}

@tab

@ref{b18,,[1]}@ref{759,,[2]}@ref{11a9,,[3]}

@item

os.chown

@tab

@code{path}, @code{uid}, @code{gid}, @code{dir_fd}

@tab

@ref{b19,,[1]}@ref{75a,,[2]}@ref{20db,,[3]}

@item

os.exec

@tab

@code{path}, @code{args}, @code{env}

@tab

@ref{2117,,[1]}

@item

os.fork

@tab



@tab

@ref{a4b,,[1]}

@item

os.forkpty

@tab



@tab

@ref{212f,,[1]}

@item

os.fwalk

@tab

@code{top}, @code{topdown}, @code{onerror}, @code{follow_symlinks}, @code{dir_fd}

@tab

@ref{4c3,,[1]}

@item

os.getxattr

@tab

@code{path}, @code{attribute}

@tab

@ref{b2f,,[1]}

@item

os.kill

@tab

@code{pid}, @code{sig}

@tab

@ref{dc1,,[1]}

@item

os.killpg

@tab

@code{pgid}, @code{sig}

@tab

@ref{112a,,[1]}

@item

os.link

@tab

@code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd}

@tab

@ref{b1a,,[1]}

@item

os.listdir

@tab

@code{path}

@tab

@ref{b25,,[1]}

@item

os.listxattr

@tab

@code{path}

@tab

@ref{b30,,[1]}

@item

os.lockf

@tab

@code{fd}, @code{cmd}, @code{len}

@tab

@ref{b3e,,[1]}

@item

os.mkdir

@tab

@code{path}, @code{mode}, @code{dir_fd}

@tab

@ref{4cc,,[1]}@ref{b1b,,[2]}

@item

os.posix_spawn

@tab

@code{path}, @code{argv}, @code{env}

@tab

@ref{388,,[1]}@ref{1196,,[2]}

@item

os.putenv

@tab

@code{key}, @code{value}

@tab

@ref{1ce,,[1]}

@item

os.remove

@tab

@code{path}, @code{dir_fd}

@tab

@ref{b1c,,[1]}@ref{20e2,,[2]}@ref{b21,,[3]}

@item

os.removexattr

@tab

@code{path}, @code{attribute}

@tab

@ref{b31,,[1]}

@item

os.rename

@tab

@code{src}, @code{dst}, @code{src_dir_fd}, @code{dst_dir_fd}

@tab

@ref{b1d,,[1]}@ref{20e3,,[2]}@ref{b1e,,[3]}

@item

os.rmdir

@tab

@code{path}, @code{dir_fd}

@tab

@ref{b1f,,[1]}

@item

os.scandir

@tab

@code{path}

@tab

@ref{390,,[1]}

@item

os.setxattr

@tab

@code{path}, @code{attribute}, @code{value}, @code{flags}

@tab

@ref{b32,,[1]}

@item

os.spawn

@tab

@code{mode}, @code{path}, @code{args}, @code{env}

@tab

@ref{20d3,,[1]}

@item

os.startfile

@tab

@code{path}, @code{operation}

@tab

@ref{2143,,[1]}

@item

os.symlink

@tab

@code{src}, @code{dst}, @code{dir_fd}

@tab

@ref{b20,,[1]}

@item

os.system

@tab

@code{command}

@tab

@ref{e8e,,[1]}

@item

os.truncate

@tab

@code{fd}, @code{length}

@tab

@ref{75f,,[1]}@ref{81d,,[2]}

@item

os.unsetenv

@tab

@code{key}

@tab

@ref{1cd,,[1]}

@item

os.utime

@tab

@code{path}, @code{times}, @code{ns}, @code{dir_fd}

@tab

@ref{b22,,[1]}

@item

os.walk

@tab

@code{top}, @code{topdown}, @code{onerror}, @code{followlinks}

@tab

@ref{751,,[1]}

@item

pathlib.Path.glob

@tab

@code{self}, @code{pattern}

@tab

@ref{10cd,,[1]}

@item

pathlib.Path.rglob

@tab

@code{self}, @code{pattern}

@tab

@ref{10ce,,[1]}

@item

pdb.Pdb

@tab



@tab

@ref{1d4,,[1]}

@item

pickle.find_class

@tab

@code{module}, @code{name}

@tab

@ref{1e63,,[1]}

@item

poplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{1d6,,[1]}@ref{1d7,,[2]}

@item

poplib.putline

@tab

@code{self}, @code{line}

@tab

@ref{1d6,,[1]}@ref{1d7,,[2]}

@item

pty.spawn

@tab

@code{argv}

@tab

@ref{988,,[1]}

@item

resource.prlimit

@tab

@code{pid}, @code{resource}, @code{limits}

@tab

@ref{98f,,[1]}

@item

resource.setrlimit

@tab

@code{resource}, @code{limits}

@tab

@ref{3528,,[1]}

@item

setopencodehook

@tab



@tab

@ref{2174,,[1]}

@item

shutil.chown

@tab

@code{path}, @code{user}, @code{group}

@tab

@ref{b5a,,[1]}

@item

shutil.copyfile

@tab

@code{src}, @code{dst}

@tab

@ref{38a,,[1]}@ref{38b,,[2]}@ref{389,,[3]}

@item

shutil.copymode

@tab

@code{src}, @code{dst}

@tab

@ref{38a,,[1]}@ref{1e2c,,[2]}

@item

shutil.copystat

@tab

@code{src}, @code{dst}

@tab

@ref{38b,,[1]}@ref{b5b,,[2]}

@item

shutil.copytree

@tab

@code{src}, @code{dst}

@tab

@ref{34e,,[1]}

@item

shutil.make_archive

@tab

@code{base_name}, @code{format}, @code{root_dir}, @code{base_dir}

@tab

@ref{34f,,[1]}

@item

shutil.move

@tab

@code{src}, @code{dst}

@tab

@ref{38c,,[1]}

@item

shutil.rmtree

@tab

@code{path}

@tab

@ref{350,,[1]}

@item

shutil.unpack_archive

@tab

@code{filename}, @code{extract_dir}, @code{format}

@tab

@ref{28b,,[1]}

@item

signal.pthread_kill

@tab

@code{thread_id}, @code{signalnum}

@tab

@ref{b5e,,[1]}

@item

smtplib.connect

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{1116,,[1]}

@item

smtplib.send

@tab

@code{self}, @code{data}

@tab

@ref{1df,,[1]}

@item

socket.__new__

@tab

@code{self}, @code{family}, @code{type}, @code{protocol}

@tab

@ref{771,,[1]}

@item

socket.bind

@tab

@code{self}, @code{address}

@tab

@ref{27f4,,[1]}

@item

socket.connect

@tab

@code{self}, @code{address}

@tab

@ref{773,,[1]}@ref{27f6,,[2]}

@item

socket.getaddrinfo

@tab

@code{host}, @code{port}, @code{family}, @code{type}, @code{protocol}

@tab

@ref{271f,,[1]}

@item

socket.gethostbyaddr

@tab

@code{ip_address}

@tab

@ref{ff8,,[1]}

@item

socket.gethostbyname

@tab

@code{hostname}

@tab

@ref{27ec,,[1]}@ref{ff9,,[2]}

@item

socket.gethostname

@tab



@tab

@ref{2095,,[1]}

@item

socket.getnameinfo

@tab

@code{sockaddr}

@tab

@ref{2720,,[1]}

@item

socket.getservbyname

@tab

@code{servicename}, @code{protocolname}

@tab

@ref{27ee,,[1]}

@item

socket.getservbyport

@tab

@code{port}, @code{protocolname}

@tab

@ref{27ef,,[1]}

@item

socket.sendmsg

@tab

@code{self}, @code{address}

@tab

@ref{779,,[1]}

@item

socket.sendto

@tab

@code{self}, @code{address}

@tab

@ref{77a,,[1]}

@item

socket.sethostname

@tab

@code{name}

@tab

@ref{b68,,[1]}

@item

sqlite3.connect

@tab

@code{database}

@tab

@ref{4e9,,[1]}

@item

subprocess.Popen

@tab

@code{executable}, @code{args}, @code{cwd}, @code{env}

@tab

@ref{3e3,,[1]}

@item

sys._current_frames

@tab



@tab

@ref{e68,,[1]}

@item

sys._getframe

@tab



@tab

@ref{f2c,,[1]}

@item

sys.addaudithook

@tab



@tab

@ref{3550,,[1]}@ref{354f,,[2]}

@item

sys.excepthook

@tab

@code{hook}, @code{type}, @code{value}, @code{traceback}

@tab

@ref{1ae,,[1]}

@item

sys.set_asyncgen_hooks_finalizer

@tab



@tab

@ref{10a0,,[1]}

@item

sys.set_asyncgen_hooks_firstiter

@tab



@tab

@ref{10a0,,[1]}

@item

sys.setprofile

@tab



@tab

@ref{f07,,[1]}

@item

sys.settrace

@tab



@tab

@ref{f08,,[1]}

@item

sys.unraisablehook

@tab

@code{hook}, @code{unraisable}

@tab

@ref{361,,[1]}

@item

syslog.closelog

@tab



@tab

@ref{355a,,[1]}

@item

syslog.openlog

@tab

@code{ident}, @code{logoption}, @code{facility}

@tab

@ref{10ef,,[1]}

@item

syslog.setlogmask

@tab

@code{maskpri}

@tab

@ref{355b,,[1]}

@item

syslog.syslog

@tab

@code{priority}, @code{message}

@tab

@ref{355c,,[1]}

@item

telnetlib.Telnet.open

@tab

@code{self}, @code{host}, @code{port}

@tab

@ref{355d,,[1]}

@item

telnetlib.Telnet.write

@tab

@code{self}, @code{buffer}

@tab

@ref{355e,,[1]}

@item

tempfile.mkdtemp

@tab

@code{fullpath}

@tab

@ref{c9e,,[1]}@ref{1e0d,,[2]}

@item

tempfile.mkstemp

@tab

@code{fullpath}

@tab

@ref{e16,,[1]}@ref{1e0b,,[2]}@ref{1e0c,,[3]}

@item

urllib.Request

@tab

@code{fullurl}, @code{data}, @code{headers}, @code{method}

@tab

@ref{885,,[1]}

@item

webbrowser.open

@tab

@code{url}

@tab

@ref{2cee,,[1]}

@item

winreg.ConnectRegistry

@tab

@code{computer_name}, @code{key}

@tab

@ref{355f,,[1]}

@item

winreg.CreateKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{3560,,[1]}@ref{3561,,[2]}

@item

winreg.DeleteKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{3562,,[1]}@ref{3563,,[2]}

@item

winreg.DeleteValue

@tab

@code{key}, @code{value}

@tab

@ref{3564,,[1]}

@item

winreg.DisableReflectionKey

@tab

@code{key}

@tab

@ref{3565,,[1]}

@item

winreg.EnableReflectionKey

@tab

@code{key}

@tab

@ref{3566,,[1]}

@item

winreg.EnumKey

@tab

@code{key}, @code{index}

@tab

@ref{3567,,[1]}

@item

winreg.EnumValue

@tab

@code{key}, @code{index}

@tab

@ref{3568,,[1]}

@item

winreg.ExpandEnvironmentStrings

@tab

@code{str}

@tab

@ref{3569,,[1]}

@item

winreg.LoadKey

@tab

@code{key}, @code{sub_key}, @code{file_name}

@tab

@ref{356a,,[1]}

@item

winreg.OpenKey

@tab

@code{key}, @code{sub_key}, @code{access}

@tab

@ref{356b,,[1]}

@item

winreg.OpenKey/result

@tab

@code{key}

@tab

@ref{3560,,[1]}@ref{3561,,[2]}@ref{356b,,[3]}

@item

winreg.PyHKEY.Detach

@tab

@code{key}

@tab

@ref{356c,,[1]}

@item

winreg.QueryInfoKey

@tab

@code{key}

@tab

@ref{356d,,[1]}

@item

winreg.QueryReflectionKey

@tab

@code{key}

@tab

@ref{356e,,[1]}

@item

winreg.QueryValue

@tab

@code{key}, @code{sub_key}, @code{value_name}

@tab

@ref{356f,,[1]}@ref{3570,,[2]}

@item

winreg.SaveKey

@tab

@code{key}, @code{file_name}

@tab

@ref{3571,,[1]}

@item

winreg.SetValue

@tab

@code{key}, @code{sub_key}, @code{type}, @code{value}

@tab

@ref{3572,,[1]}@ref{3573,,[2]}

@end multitable


下列事件只在内部被引发，而不会回应任何 CPython 公共 API:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

审计事件

@tab

实参

@item

_winapi.CreateFile

@tab

@code{file_name}, @code{desired_access},
@code{share_mode}, @code{creation_disposition},
@code{flags_and_attributes}

@item

_winapi.CreateJunction

@tab

@code{src_path}, @code{dst_path}

@item

_winapi.CreateNamedPipe

@tab

@code{name}, @code{open_mode}, @code{pipe_mode}

@item

_winapi.CreatePipe

@tab

@item

_winapi.CreateProcess

@tab

@code{application_name}, @code{command_line},
@code{current_directory}

@item

_winapi.OpenProcess

@tab

@code{process_id}, @code{desired_access}

@item

_winapi.TerminateProcess

@tab

@code{handle}, @code{exit_code}

@item

ctypes.PyObj_FromPtr

@tab

@code{obj}

@end multitable


@node bdb --- 调试器框架,faulthandler —— 转储 Python 的跟踪信息,审计事件表,调试和分析
@anchor{library/bdb doc}@anchor{3574}@anchor{library/bdb bdb-debugger-framework}@anchor{3575}@anchor{library/bdb module-bdb}@anchor{e}
@subsection @code{bdb} --- 调试器框架


@geindex bdb (模块)

@strong{源代码:} Lib/bdb.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/bdb.py}


__________________________________________________________________


@ref{e,,bdb} 模块处理基本的调试器函数，例如设置中断点或通过调试器来管理执行。

定义了以下异常：

@geindex BdbQuit
@anchor{library/bdb bdb BdbQuit}@anchor{3576}
@deffn {例外} bdb.BdbQuit

由 @ref{d68,,Bdb} 类引发用于退出调试器的异常。
@end deffn

@ref{e,,bdb} 模块还定义了两个类:

@geindex Breakpoint (bdb 中的类)
@anchor{library/bdb bdb Breakpoint}@anchor{3577}
@deffn {类} bdb.Breakpoint (self, file, line, temporary=0, cond=None, funcname=None)

这个类实现了临时性中断点、忽略计数、禁用与（重新）启用，以及条件设置等。

中断点通过一个名为 @code{bpbynumber} 的列表基于数字并通过 @code{bplist} 基于 @code{(file, line)} 对进行索引。 前者指向一个 @ref{3577,,Breakpoint} 类的单独实例。 后者指向一个由这种实例组成的列表，因为在每一行中可能存在多个中断点。

当创建一个中断点时，它所关联的文件名应当为规范的形式。 如果定义了 @emph{funcname}，则当该函数的第一行被执行时将增加一次中断点命中计数。 带条件的中断点将总被增加一次计数。

@ref{3577,,Breakpoint} 的实例具有下列方法:

@geindex deleteMe() (bdb.Breakpoint 方法)
@anchor{library/bdb bdb Breakpoint deleteMe}@anchor{3578}
@deffn {方法} deleteMe ()

从关联到文件/行的列表中删除此中断点。 如果它是该位置上的最后一个中断点，还将删除相应的文件/行条目。
@end deffn

@geindex enable() (bdb.Breakpoint 方法)
@anchor{library/bdb bdb Breakpoint enable}@anchor{3579}
@deffn {方法} enable ()

将此中断点标记为启用。
@end deffn

@geindex disable() (bdb.Breakpoint 方法)
@anchor{library/bdb bdb Breakpoint disable}@anchor{357a}
@deffn {方法} disable ()

将此中断点标记为禁用。
@end deffn

@geindex bpformat() (bdb.Breakpoint 方法)
@anchor{library/bdb bdb Breakpoint bpformat}@anchor{357b}
@deffn {方法} bpformat ()

返回一个带有关于此中断点的所有信息的，格式良好的字符串:


@itemize *

@item 
此中断点的编号。

@item 
它是否为临时性的。

@item 
它的 file,line 位置。

@item 
导致中断的条件。

@item 
它是否必须在此后被忽略 N 次。

@item 
此中断点的命中计数。
@end itemize


3.2 新版功能.

@end deffn

@geindex bpprint() (bdb.Breakpoint 方法)
@anchor{library/bdb bdb Breakpoint bpprint}@anchor{357c}
@deffn {方法} bpprint (out=None)

将 @ref{357b,,bpformat()} 的输出打印到文件 @emph{out}，或者如果为 @code{None} 则打印到标准输出。, to standard output.
@end deffn
@end deffn

@geindex Bdb (bdb 中的类)
@anchor{library/bdb bdb Bdb}@anchor{d68}
@deffn {类} bdb.Bdb (skip=None)

@ref{d68,,Bdb} 类是作为通用的 Python 调试器基类。

这个类负责追踪工具的细节；所派生的类应当实现用户交互。 标准调试器类 (@ref{1d4,,pdb.Pdb}) 就是一个例子。

如果给出了 @emph{skip} 参数，它必须是一个包含 glob 风格的模块名称模式的可迭代对象。 调试器将不会步进到来自与这些模式相匹配的模块的帧。 一个帧是否会被视为来自特定的模块是由帧的 @code{__name__} 全局变量来确定的。


3.1 新版功能: @emph{skip} 参数。


@ref{d68,,Bdb} 的以下方法通常不需要被重载。

@geindex canonic() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb canonic}@anchor{357d}
@deffn {方法} canonic (filename)

用于获取规范形式文件名的辅助方法，也就是大小写规范的（在大小写不敏感文件系统上）绝对路径，并去除两边的尖括号。
@end deffn

@geindex reset() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb reset}@anchor{357e}
@deffn {方法} reset ()

将 @code{botframe}, @code{stopframe}, @code{returnframe} 和 @code{quitting} 属性设置为准备开始调试的值。
@end deffn

@geindex trace_dispatch() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb trace_dispatch}@anchor{357f}
@deffn {方法} trace_dispatch (frame, event, arg)

此函数被安装为被调试帧的追踪函数。 它的返回值是新的追踪函数（在大多数情况下就是它自身）。

默认实现会决定如何分派帧，这取决于即将被执行的事件的类型（作为字符串传入）。 @emph{event} 可以是下列值之一:


@itemize *

@item 
@code{"line"}: 一个新的代码行即将被执行。

@item 
@code{"call"}: 一个函数即将被调用，或者进入了另一个代码块。

@item 
@code{"return"}: 一个即将返回的函数或其他代码块。

@item 
@code{"exception"}: 一个异常已发生。

@item 
@code{"c_call"}: 一个 C 函数即将被调用。

@item 
@code{"c_return"}: 一个 C 函数已返回。

@item 
@code{"c_exception"}: 一个 C 函数引发了异常。
@end itemize

对于 Python 事件，调用了专门的函数（见下文）。 对于 C 事件，不执行任何操作。

@emph{arg} 形参取决于之前的事件。

请参阅 @ref{f08,,sys.settrace()} 的文档了解追踪函数的更多信息。 对于代码和帧对象的详情，请参考 @ref{1582,,标准类型层级结构}。
@end deffn

@geindex dispatch_line() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb dispatch_line}@anchor{3580}
@deffn {方法} dispatch_line (frame)

如果调试器应当在当前行上停止，则发起调用 @ref{3581,,user_line()} 方法（该方法应当在子类中被重载）。 如果设置了 @code{Bdb.quitting} 旗标（可以通过 @ref{3581,,user_line()} 设置）则将引发 @ref{3576,,BdbQuit} 异常。 返回一个对 @ref{357f,,trace_dispatch()} 方法的引用以便在该作用域内进一步地追踪。
@end deffn

@geindex dispatch_call() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb dispatch_call}@anchor{3582}
@deffn {方法} dispatch_call (frame, arg)

如果调试器应当在此函数调用上停止，则发起调用 @ref{3583,,user_call()} 方法（该方法应当在子类中被重载）。 如果设置了 @code{Bdb.quitting} 旗标（可以通过 @ref{3583,,user_call()} 设置）则将引发 @ref{3576,,BdbQuit} 异常。 返回一个对 @ref{357f,,trace_dispatch()} 方法的引用以便在该作用域内进一步地追踪。
@end deffn

@geindex dispatch_return() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb dispatch_return}@anchor{3584}
@deffn {方法} dispatch_return (frame, arg)

如果调试器应当在此函数返回时停止，则发起调用 @ref{3585,,user_return()} 方法（该方法应当在子类中被重载）。 如果设置了 @code{Bdb.quitting} 旗标（可以通过 @ref{3585,,user_return()} 设置）则将引发 @ref{3576,,BdbQuit} 异常。 返回一个对 @ref{357f,,trace_dispatch()} 方法的引用以便在该作用域内进一步地追踪。
@end deffn

@geindex dispatch_exception() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb dispatch_exception}@anchor{3586}
@deffn {方法} dispatch_exception (frame, arg)

如果调试器应当在此异常上停止，则发起调用 @ref{3587,,user_exception()} 方法（该方法应当在子类中被重载）。 如果设置了 @code{Bdb.quitting} 旗标（可以通过 @ref{3587,,user_exception()} 设置）则将引发 @ref{3576,,BdbQuit} 异常。 返回一个对 @ref{357f,,trace_dispatch()} 方法的引用以便在该作用域内进一步地追踪。
@end deffn

通常情况下派生的类不会重载下列方法，但是如果想要重新定义停止和中断点的定义则可能会重载它们。

@geindex stop_here() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb stop_here}@anchor{3588}
@deffn {方法} stop_here (frame)

此方法将检查调用栈中 @emph{frame} 是否位于 @code{botframe} 的下方。 @code{botframe} 是调试开始所在的帧。
@end deffn

@geindex break_here() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb break_here}@anchor{3589}
@deffn {方法} break_here (frame)

此方法将检查 @emph{frame} 所属的文件名和行，或者至少当前函数中是否存在中断点。 如果中断点是临时性的，此方法将删除它。
@end deffn

@geindex break_anywhere() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb break_anywhere}@anchor{358a}
@deffn {方法} break_anywhere (frame)

此方法将检查当前帧的文件名中是否存在中断点。
@end deffn

派生的类应当重载这些方法以获取调试器操作的控制权。

@geindex user_call() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb user_call}@anchor{3583}
@deffn {方法} user_call (frame, argument_list)

当有可能在被调用函数内部的任何地方需要一个中断时此方法将从 @ref{3582,,dispatch_call()} 被调用。
@end deffn

@geindex user_line() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb user_line}@anchor{3581}
@deffn {方法} user_line (frame)

当 @ref{3588,,stop_here()} 或 @ref{3589,,break_here()} 产生 @code{True} 时此方法将从 @ref{3580,,dispatch_line()} 被调用。
@end deffn

@geindex user_return() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb user_return}@anchor{3585}
@deffn {方法} user_return (frame, return_value)

当 @ref{3588,,stop_here()} 产生 @code{True} 时此方法将从 @ref{3584,,dispatch_return()} 被调用。
@end deffn

@geindex user_exception() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb user_exception}@anchor{3587}
@deffn {方法} user_exception (frame, exc_info)

当 @ref{3588,,stop_here()} 产生 @code{True} 时此方法将从 @ref{3586,,dispatch_exception()} 被调用。
@end deffn

@geindex do_clear() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb do_clear}@anchor{358b}
@deffn {方法} do_clear (arg)

处理当一个中断点属于临时性中断点时是否必须要移除它。

此方法必须由派生类来实现。
@end deffn

派生类与客户端可以调用以下方法来影响步进状态。

@geindex set_step() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_step}@anchor{358c}
@deffn {方法} set_step ()

在一行代码之后停止。Stop after one line of code.
@end deffn

@geindex set_next() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_next}@anchor{358d}
@deffn {方法} set_next (frame)

在给定帧以内或以下的下一行停止。
@end deffn

@geindex set_return() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_return}@anchor{358e}
@deffn {方法} set_return (frame)

当从给定的帧返回时停止。
@end deffn

@geindex set_until() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_until}@anchor{358f}
@deffn {方法} set_until (frame)

当到达不大于当前行的行或当从当前帧返回时停止。
@end deffn

@geindex set_trace() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_trace}@anchor{3590}
@deffn {方法} set_trace ([frame])

从 @emph{frame} 开始调试。 如果未指定 @emph{frame}，则从调用者的帧开始调试。
@end deffn

@geindex set_continue() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_continue}@anchor{3591}
@deffn {方法} set_continue ()

仅在中断点上或是当结束时停止。 如果不存在中断点，则将系统追踪函数设为 @code{None}。
@end deffn

@geindex set_quit() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_quit}@anchor{3592}
@deffn {方法} set_quit ()

将 @code{quitting} 属性设为 @code{True}。 这将在对某个 @code{dispatch_*()} 方法的下一次调用中引发 @ref{3576,,BdbQuit}。
@end deffn

派生的类和客户端可以调用下列方法来操纵中断点。 如果出现错误则这些方法将返回一个包含错误消息的字符串，或者如果一切正常则返回 @code{None}。

@geindex set_break() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb set_break}@anchor{3593}
@deffn {方法} set_break (filename, lineno, temporary=0, cond, funcname)

设置一个新的中断点。 如果对于作为参数传入的 @emph{filename} 不存在 @emph{lineno}，则返回一条错误消息。 @emph{filename} 应为规范的形式，如在 @ref{357d,,canonic()} 方法中描述的。
@end deffn

@geindex clear_break() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb clear_break}@anchor{3594}
@deffn {方法} clear_break (filename, lineno)

删除位于 @emph{filename} 中 @emph{lineno} 上的中断点。 如果未设置过中断点。 则将返回一条错误消息。
@end deffn

@geindex clear_bpbynumber() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb clear_bpbynumber}@anchor{3595}
@deffn {方法} clear_bpbynumber (arg)

删除 @code{Breakpoint.bpbynumber} 中索引号为 @emph{arg} 的中断点。 如果 @emph{arg} 不是数字或超出范围，则返回一条错误消息。
@end deffn

@geindex clear_all_file_breaks() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb clear_all_file_breaks}@anchor{3596}
@deffn {方法} clear_all_file_breaks (filename)

删除 @emph{filename} 中的所有中断点。 如果未设置任何中断点，则返回一条错误消息。
@end deffn

@geindex clear_all_breaks() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb clear_all_breaks}@anchor{3597}
@deffn {方法} clear_all_breaks ()

删除全部现有的中断点。
@end deffn

@geindex get_bpbynumber() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_bpbynumber}@anchor{3598}
@deffn {方法} get_bpbynumber (arg)

返回由指定数字所指明的中断点。 如果 @emph{arg} 是一个字符串，它将被转换为一个数字。 如果 @emph{arg} 不是一个表示数字的字符串，如果给定的中断点不存在或者已被删除，则会引发 @ref{16d,,ValueError}。


3.2 新版功能.

@end deffn

@geindex get_break() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_break}@anchor{3599}
@deffn {方法} get_break (filename, lineno)

检查 @emph{filename} 中在 @emph{lineno} 上是否有中断点。
@end deffn

@geindex get_breaks() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_breaks}@anchor{359a}
@deffn {方法} get_breaks (filename, lineno)

返回 @emph{filename} 中在 @emph{lineno} 上的所有中断点，或者如果未设置任何中断点则返回一个空列表。
@end deffn

@geindex get_file_breaks() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_file_breaks}@anchor{359b}
@deffn {方法} get_file_breaks (filename)

返回 @emph{filename} 中在 @emph{lineno} 上的所有中断点，或者如果未设置任何中断点则返回一个空列表。
@end deffn

@geindex get_all_breaks() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_all_breaks}@anchor{359c}
@deffn {方法} get_all_breaks ()

返回已设置的所有中断点。
@end deffn

派生类与客户端可以调用以下方法来获取一个代表栈回溯信息的数组结构。

@geindex get_stack() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb get_stack}@anchor{359d}
@deffn {方法} get_stack (f, t)

获取一个帧及其所有上级（调用方）和下级帧的记录列表，以及上级部分的大小。
@end deffn

@geindex format_stack_entry() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb format_stack_entry}@anchor{359e}
@deffn {方法} format_stack_entry (frame_lineno, lprefix=': ')

返回一个包含有关栈条目信息的字符串，由一个 @code{(frame, lineno)} 元组来标识:


@itemize *

@item 
包含帧的规范形式的文件名。

@item 
函数名称，或者 @code{"<lambda>"}。

@item 
输入参数。

@item 
返回值。

@item 
代码的行（如果存在）。
@end itemize
@end deffn

以下两个方法可由客户端调用以使用一个调试器来调试一条以字符串形式给出的 @ref{1d37,,statement}。

@geindex run() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb run}@anchor{359f}
@deffn {方法} run (cmd, globals=None, locals=None)

调试一条通过 @ref{d14,,exec()} 函数执行的语句。 @emph{globals} 默认为 @code{__main__.__dict__}，@emph{locals} 默认为 @emph{globals}。
@end deffn

@geindex runeval() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb runeval}@anchor{35a0}
@deffn {方法} runeval (expr, globals=None, locals=None)

调试一条通过 @ref{c6a,,eval()} 函数执行的表达式。 @emph{globals} 和 @emph{locals} 的含义与在 @ref{359f,,run()} 中的相同。
@end deffn

@geindex runctx() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb runctx}@anchor{35a1}
@deffn {方法} runctx (cmd, globals, locals)

为了向下兼容。 调用 @ref{359f,,run()} 方法。
@end deffn

@geindex runcall() (bdb.Bdb 方法)
@anchor{library/bdb bdb Bdb runcall}@anchor{3ca}
@deffn {方法} runcall (func, /, *args, **kwds)

调试一个单独的函数调用，并返回其结果。
@end deffn
@end deffn

最后，这个模块定义了以下函数:

@geindex checkfuncname() (在 bdb 模块中)
@anchor{library/bdb bdb checkfuncname}@anchor{35a2}
@deffn {函数} bdb.checkfuncname (b, frame)

检查是否应当在此中断，根据中断点 @emph{b} 的设置方式。

如果是通过行号设置的，它将检查 @code{b.line} 是否与同样作为参数传入的帧中的行号一致。 如果中断点是通过函数名称设置的，则必须检查是否位于正确的帧（正确的函数）以及是否位于其中第一个可执行的行。
@end deffn

@geindex effective() (在 bdb 模块中)
@anchor{library/bdb bdb effective}@anchor{35a3}
@deffn {函数} bdb.effective (file, line, frame)

确定在这一行代码中是否存在有效的（激活的）中断点。 返回一个包含中断点和表示是否可以删除临时中断点的布尔值的元组。 如果没有匹配的中断点则返回 @code{(None, None)}。
@end deffn

@geindex set_trace() (在 bdb 模块中)
@anchor{library/bdb bdb set_trace}@anchor{35a4}
@deffn {函数} bdb.set_trace ()

使用一个来自调用方的帧的 @ref{d68,,Bdb} 实例开始调试。
@end deffn

@node faulthandler —— 转储 Python 的跟踪信息,pdb --- Python 的调试器,bdb --- 调试器框架,调试和分析
@anchor{library/faulthandler doc}@anchor{35a5}@anchor{library/faulthandler faulthandler-dump-the-python-traceback}@anchor{35a6}@anchor{library/faulthandler module-faulthandler}@anchor{7b}
@subsection @code{faulthandler} —— 转储 Python 的跟踪信息


@geindex faulthandler (模块)


3.3 新版功能.



__________________________________________________________________


当故障、超时或收到用户信号时，利用本模块内的函数可转储 Python 跟踪信息。调用 @ref{64b,,faulthandler.enable()} 可安装 @code{SIGSEGV} 、 @code{SIGFPE} 、 @code{SIGABRT} 、 @code{SIGBUS}  和 @code{SIGILL} 信号的故障处理程序。通过设置 
@geindex PYTHONFAULTHANDLER
@geindex 环境变量; PYTHONFAULTHANDLER
@ref{ab0,,PYTHONFAULTHANDLER} 环境变量或 @ref{297,,-X}  @code{faulthandler} 命令行参数，还可以在启动时开启这些设置。

故障处理程序与操作系统的故障处理程序兼容，比如 Apport 或 Windows 故障处理程序等。如果 @code{sigaltstack()} 函数可用，本模块将为信号处理程序使用备用堆栈。这样即便堆栈溢出也能转储跟踪信息。

故障处理程序将在灾难性场合调用，因此只能使用信号安全的函数（比如不能在堆上分配内存）。由于这一限制，与正常的 Python 跟踪相比，转储量是最小的。


@itemize *

@item 
只支持 ASCII 码。编码时会用到  @code{backslashreplace} 错误处理程序。

@item 
每个字符串限制在 500 个字符以内。

@item 
只会显式文件名、函数名和行号。（不显示源代码）

@item 
上限是 100 页内存帧和 100 个线程。

@item 
反序排列：最近的调用最先显示。
@end itemize

默认情况下，Python 的跟踪信息会写入 @ref{1eb,,sys.stderr}。为了能看到跟踪信息，应用程序必须运行于终端中。日志文件也可以传给 @ref{64b,,faulthandler.enable()}。

本模块是用 C 语言实现的，所以才能在崩溃或 Python 死锁时转储跟踪信息。

在 Python 启动时， @ref{160,,Python 开发模式} 会调用 @ref{64b,,faulthandler.enable()}。

@menu
* 转储跟踪信息:: 
* 错误处理程序的状态:: 
* 一定时间后转储跟踪数据。:: 
* 转储用户信号的跟踪信息。:: 
* 文件描述符相关话题:: 
* 示例: 示例<39>. 

@end menu

@node 转储跟踪信息,错误处理程序的状态,,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler dumping-the-traceback}@anchor{35a7}
@subsubsection 转储跟踪信息


@geindex dump_traceback() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler dump_traceback}@anchor{7d5}
@deffn {函数} faulthandler.dump_traceback (file=sys.stderr, all_threads=True)

将所有线程的跟踪数据转储到 @emph{file} 中。如果 @emph{all_threads} 为 @code{False}，则只转储当前线程。


在 3.5 版更改: 增加了向本函数传入文件描述符的支持。

@end deffn

@node 错误处理程序的状态,一定时间后转储跟踪数据。,转储跟踪信息,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler fault-handler-state}@anchor{35a8}
@subsubsection 错误处理程序的状态


@geindex enable() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler enable}@anchor{64b}
@deffn {函数} faulthandler.enable (file=sys.stderr, all_threads=True)

启用故障处理程序：为 @code{SIGSEGV} 、 @code{SIGFPE} 、 @code{SIGABRT} 、 @code{SIGBUS} 和 @code{SIGILL} 信号安装处理程序，以转储 Python 跟踪信息。如果 @emph{all_threads} 为 @code{True}，则会为每个运行中的线程生成跟踪信息。否则只转储当前线程。

该 @emph{文件} 必须保持打开状态，直至禁用故障处理程序为止：参见 @ref{35a9,,文件描述符相关话题}。


在 3.5 版更改: 增加了向本函数传入文件描述符的支持。



在 3.6 版更改: 在 Windows 系统中，同时会安装一个 Windows 异常处理程序。

@end deffn

@geindex disable() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler disable}@anchor{35aa}
@deffn {函数} faulthandler.disable ()

停用故障处理程序：卸载由 @ref{64b,,enable()} 安装的信号处理程序。
@end deffn

@geindex is_enabled() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler is_enabled}@anchor{35ab}
@deffn {函数} faulthandler.is_enabled ()

检查故障处理程序是否被启用。
@end deffn

@node 一定时间后转储跟踪数据。,转储用户信号的跟踪信息。,错误处理程序的状态,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler dumping-the-tracebacks-after-a-timeout}@anchor{35ac}
@subsubsection 一定时间后转储跟踪数据。


@geindex dump_traceback_later() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler dump_traceback_later}@anchor{7d6}
@deffn {函数} faulthandler.dump_traceback_later (timeout, repeat=False, file=sys.stderr, exit=False)

在 @emph{timeout} 秒超时后，转储所有线程的跟踪信息，如果 @emph{repeat} 为 @code{True}，则每隔 @emph{timeout} 秒转储一次。如果 @emph{exit} 为 @code{True}，则在转储跟踪信息后调用 @code{_exit()}，参数 status=1。请注意， @code{_exit()} 会立即关闭进程，这意味着不做任何清理工作，如刷新文件缓冲区等。如果调用两次函数，则新的调用将取代之前的参数，超时时间也会重置。计时器的精度为亚秒级。

@emph{file} 必须保持打开状态，直至跟踪信息转储完毕，或调用了 @ref{35ad,,cancel_dump_traceback_later()}  ：参见 @ref{35a9,,文件描述符相关话题}。

本函数用一个看门狗线程实现。


在 3.7 版更改: 该函数现在总是可用。



在 3.5 版更改: 增加了向本函数传入文件描述符的支持。

@end deffn

@geindex cancel_dump_traceback_later() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler cancel_dump_traceback_later}@anchor{35ad}
@deffn {函数} faulthandler.cancel_dump_traceback_later ()

取消 @ref{7d6,,dump_traceback_later()} 的最后一次调用。
@end deffn

@node 转储用户信号的跟踪信息。,文件描述符相关话题,一定时间后转储跟踪数据。,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler dumping-the-traceback-on-a-user-signal}@anchor{35ae}
@subsubsection 转储用户信号的跟踪信息。


@geindex register() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler register}@anchor{7d4}
@deffn {函数} faulthandler.register (signum, file=sys.stderr, all_threads=True, chain=False)

注册一个用户信号：为 @emph{signum} 信号安装一个处理程序，将所有线程或当前线程（@emph{all_threads} 为 @code{False} 时）的跟踪信息转储到 @emph{file} 中。如果 chain 为 @code{True}，则调用前一个处理程序。

@emph{file} 必须保持打开状态，直至信号被 @ref{35af,,unregister()} 注销：参见 @ref{35a9,,文件描述符相关话题}。

Windows 中不可用。


在 3.5 版更改: 增加了向本函数传入文件描述符的支持。

@end deffn

@geindex unregister() (在 faulthandler 模块中)
@anchor{library/faulthandler faulthandler unregister}@anchor{35af}
@deffn {函数} faulthandler.unregister (signum)

注销一个用户信号：卸载由 @ref{7d4,,register()} 安装的 @emph{signum} 信号处理程序。如果信号已注册，返回 @code{True}，否则返回 @code{False}。

Windows 中不可用。
@end deffn

@node 文件描述符相关话题,示例<39>,转储用户信号的跟踪信息。,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler faulthandler-fd}@anchor{35a9}@anchor{library/faulthandler issue-with-file-descriptors}@anchor{35b0}
@subsubsection 文件描述符相关话题


@ref{64b,,enable()} 、 @ref{7d6,,dump_traceback_later()} 和 @ref{7d4,,register()} 保留其 @emph{file} 参数给出的文件描述符。 如果文件关闭，文件描述符将被一个新文件重新使用；或者用 @ref{4cd,,os.dup2()} 替换了文件描述符，则跟踪信息将被写入另一个文件。 每次文件被替换时，都会再次调用这些函数。

@node 示例<39>,,文件描述符相关话题,faulthandler —— 转储 Python 的跟踪信息
@anchor{library/faulthandler example}@anchor{35b1}
@subsubsection 示例


在 Linux 中启用和停用内存段故障的默认处理程序：

@example
$ python3 -c "import ctypes; ctypes.string_at(0)"
Segmentation fault

$ python3 -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700 (most recent call first):
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault
@end example

@node pdb --- Python 的调试器,Python Profilers 分析器,faulthandler —— 转储 Python 的跟踪信息,调试和分析
@anchor{library/pdb doc}@anchor{35b2}@anchor{library/pdb debugger}@anchor{35b3}@anchor{library/pdb module-pdb}@anchor{c9}@anchor{library/pdb pdb-the-python-debugger}@anchor{35b4}
@subsection @code{pdb} --- Python 的调试器


@geindex pdb (模块)

@strong{源代码：} Lib/pdb.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pdb.py}

@geindex debugging


__________________________________________________________________


@ref{c9,,pdb} 模块定义了一个交互式源代码调试器，用于 Python 程序。它支持在源码行间设置（有条件的）断点和单步执行，检视堆栈帧，列出源码列表，以及在任何堆栈帧的上下文中运行任意 Python 代码。它还支持事后调试，可以在程序控制下调用。

@geindex Pdb (class in pdb)
@geindex 模块; bdb
@geindex 模块; cmd

调试器是可扩展的——调试器实际被定义为 @ref{1d4,,Pdb} 类。该类目前没有文档，但通过阅读源码很容易理解它。扩展接口使用了 @ref{e,,bdb} 和 @ref{19,,cmd} 模块。

调试器的提示符是 @code{(Pdb)}。在调试器的控制下运行程序的典型用法是:

@example
>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)
@end example


在 3.3 版更改: 由 @ref{de,,readline} 模块实现的 Tab 补全可用于补全本模块的命令和命令的参数，例如，Tab 补全会提供当前的全局变量和局部变量，用作 @code{p} 命令的参数。


也可以将 @code{pdb.py} 作为脚本调用，来调试其他脚本。例如:

@example
python3 -m pdb myscript.py
@end example

当作为脚本调用时，如果要调试的程序异常退出，pdb 调试将自动进入事后调试。事后调试之后（或程序正常退出之后），pdb 将重新启动程序。自动重启会保留 pdb 的状态（如断点），在大多数情况下，这比在退出程序的同时退出调试器更加实用。


3.2 新版功能: @code{pdb.py} 现在接受 @code{-c} 选项，可以执行命令，这与将该命令写入 @code{.pdbrc} 文件相同，请参阅 @ref{35b5,,调试器命令}。



3.7 新版功能: @code{pdb.py} 现在接受 @code{-m} 选项，该选项用于执行一个模块，类似于 @code{python3 -m}。与脚本相同，调试器将暂停在待执行模块第一行前。


中断进入调试器的典型用法是插入:

@example
import pdb; pdb.set_trace()
@end example

到你想进入调试器的位置，再运行程序。 然后你可以单步执行这条语句之后的代码，并使用 @ref{35b6,,continue} 命令来关闭调试器继续运行。


3.7 新版功能: 内置函数 @ref{414,,breakpoint()}，当以默认参数调用它时，可以用来代替 @code{import pdb; pdb.set_trace()}。


检查已崩溃程序的典型用法是:

@example
>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./mymodule.py", line 4, in test
    test2()
  File "./mymodule.py", line 3, in test2
    print(spam)
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print(spam)
(Pdb)
@end example

本模块定义了下列函数，每个函数进入调试器的方式略有不同：

@geindex run() (在 pdb 模块中)
@anchor{library/pdb pdb run}@anchor{3393}
@deffn {函数} pdb.run (statement, globals=None, locals=None)

在调试器控制范围内执行 @emph{statement} （以字符串或代码对象的形式提供）。调试器提示符会在执行代码前出现，你可以设置断点并键入 @ref{35b6,,continue}，也可以使用 @ref{35b7,,step} 或 @ref{35b8,,next} 逐步执行语句（上述所有命令在后文有说明）。可选参数 @emph{globals} 和 @emph{locals} 指定代码执行环境，默认时使用 @ref{1,,__main__} 模块的字典。（请参阅内置函数 @ref{d14,,exec()} 或 @ref{c6a,,eval()} 的说明。）
@end deffn

@geindex runeval() (在 pdb 模块中)
@anchor{library/pdb pdb runeval}@anchor{35b9}
@deffn {函数} pdb.runeval (expression, globals=None, locals=None)

在调试器控制范围内执行 @emph{expression} （以字符串或代码对象的形式提供）。@ref{35b9,,runeval()} 返回时将返回表达式的值。本函数在其他方面与 @ref{3393,,run()} 类似。
@end deffn

@geindex runcall() (在 pdb 模块中)
@anchor{library/pdb pdb runcall}@anchor{35ba}
@deffn {函数} pdb.runcall (function, *args, **kwds)

使用给定的参数调用 @emph{function} （以函数或方法对象的形式提供，不能是字符串）。@ref{35ba,,runcall()} 返回的是所调用函数的返回值。调试器提示符将在进入函数后立即出现。
@end deffn

@geindex set_trace() (在 pdb 模块中)
@anchor{library/pdb pdb set_trace}@anchor{4d1}
@deffn {函数} pdb.set_trace (*, header=None)

在调用本函数的堆栈帧处进入调试器。用于硬编码一个断点到程序中的固定点处，即使该代码不在调试状态（如断言失败时）。如果传入 @emph{header}，它将在调试开始前被打印到控制台。


在 3.7 版更改: 仅关键字参数 @emph{header}。

@end deffn

@geindex post_mortem() (在 pdb 模块中)
@anchor{library/pdb pdb post_mortem}@anchor{e12}
@deffn {函数} pdb.post_mortem (traceback=None)

进入 @emph{traceback} 对象的事后调试。如果没有给定 @emph{traceback}，默认使用当前正在处理的异常之一（默认时，必须存在正在处理的异常）。
@end deffn

@geindex pm() (在 pdb 模块中)
@anchor{library/pdb pdb pm}@anchor{35bb}
@deffn {函数} pdb.pm ()

在 @ref{35bc,,sys.last_traceback} 中查找 traceback，并进入其事后调试。
@end deffn

@code{run*} 函数和 @ref{4d1,,set_trace()} 都是别名，用于实例化 @ref{1d4,,Pdb} 类和调用同名方法。如果要使用其他功能，则必须自己执行以下操作：

@geindex Pdb (pdb 中的类)
@anchor{library/pdb pdb Pdb}@anchor{1d4}
@deffn {类} pdb.Pdb (completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)

@ref{1d4,,Pdb} 是调试器类。

@emph{completekey}、@emph{stdin} 和 @emph{stdout} 参数都会传递给底层的 @ref{3154,,cmd.Cmd} 类，请参考相应的描述。

如果给出 @emph{skip} 参数，则它必须是一个迭代器，可以迭代出 glob-style 样式的模块名称。如果遇到匹配上述样式的模块，调试器将不会进入来自该模块的堆栈帧。 @footnote{@w{(1)} 
一个帧是否会被认为源自特定模块是由帧全局变量 @code{__name__} 来决定的。
}

默认情况下，当发出 @code{continue} 命令时，Pdb 将为 SIGINT 信号设置一个处理程序（SIGINT 信号是用户在控制台按 @code{Ctrl-C} 时发出的）。这使用户可以按 @code{Ctrl-C} 再次进入调试器。如果希望 Pdb 不要修改 SIGINT 处理程序，请将 @emph{nosigint} 设置为 true。

@emph{readrc} 参数默认为 true，它控制 Pdb 是否从文件系统加载 .pdbrc 文件。

启用跟踪且带有 @emph{skip} 参数的调用示范:

@example
import pdb; pdb.Pdb(skip=['django.*']).set_trace()
@end example

引发一个 @ref{fec,,审计事件} @code{pdb.Pdb}，没有附带参数。


3.1 新版功能: @emph{skip} 参数。



3.2 新版功能: @emph{nosigint} 参数。在这之前，Pdb 不为 SIGINT 设置处理程序。



在 3.6 版更改: @emph{readrc} 参数。


@geindex run() (pdb.Pdb 方法)
@geindex runeval() (pdb.Pdb 方法)
@geindex runcall() (pdb.Pdb 方法)
@geindex set_trace() (pdb.Pdb 方法)
@anchor{library/pdb pdb Pdb run}@anchor{35bd}
@deffn {方法} run (statement, globals=None, locals=None)
@anchor{library/pdb pdb Pdb runeval}@anchor{35be}
@deffnx {方法} runeval (expression, globals=None, locals=None)
@anchor{library/pdb pdb Pdb runcall}@anchor{35bf}
@deffnx {方法} runcall (function, *args, **kwds)
@anchor{library/pdb pdb Pdb set_trace}@anchor{35c0}
@deffnx {方法} set_trace ()

请参阅上文解释同名函数的文档。
@end deffn
@end deffn

@menu
* 调试器命令:: 

@end menu

@node 调试器命令,,,pdb --- Python 的调试器
@anchor{library/pdb debugger-commands}@anchor{35b5}@anchor{library/pdb id2}@anchor{35c1}
@subsubsection 调试器命令


下方列出的是调试器可接受的命令。如下所示，大多数命令可以缩写为一个或两个字母。如 @code{h(elp)} 表示可以输入 @code{h} 或 @code{help} 来输入帮助命令（但不能输入 @code{he} 或 @code{hel}，也不能是 @code{H} 或 @code{Help} 或 @code{HELP}）。命令的参数必须用空格（空格符或制表符）分隔。在命令语法中，可选参数括在方括号 (@code{[]}) 中，使用时请勿输入方括号。命令语法中的选择项由竖线 (@code{|}) 分隔。

输入一个空白行将重复最后输入的命令。例外：如果最后一个命令是 @ref{35c2,,list} 命令，则会列出接下来的 11 行。

调试器无法识别的命令将被认为是 Python 语句，并在正在调试的程序的上下文中执行。Python 语句也可以用感叹号 (@code{!}) 作为前缀。这是检查正在调试的程序的强大方法，甚至可以修改变量或调用函数。当此类语句发生异常，将打印异常名称，但调试器的状态不会改变。

调试器支持 @ref{35c3,,别名}。别名可以有参数，使得调试器对被检查的上下文有一定程度的适应性。

在一行中可以输入多条命令，以 @code{;;} 分隔。 （不能使用单个 @code{;}，因为它已被用作传给 Python 解析器的一行中的多条命令的分隔符。） 命令切分所用的方式没有任何智能可言；输入总是会在第一个 @code{;;} 对上被切分，即使它位于带引号的字符串中。 对于带有双分号的字符串可以使用隐式字符串拼接 @code{';'@w{'};'} 或 @code{";"";"} 来变通处理。

@geindex .pdbrc; file
@geindex debugger; configuration; file

如果文件 @code{.pdbrc} 存在于用户主目录或当前目录中，则将其读入并执行，等同于在调试器提示符下键入该文件。这对于别名很有用。若两个文件都存在则首先读取主目录中的文件，且本地文件可以覆盖其中定义的别名。


在 3.2 版更改: @code{.pdbrc} 现在可以包含继续调试的命令，如 @ref{35b6,,continue} 或 @ref{35b8,,next}。文件中的这些命令以前是无效的。


@geindex help (pdb command)
@anchor{library/pdb pdbcommand-help}@anchor{35c4}
@deffn {Pdbcommand} h(elp) [command]

不带参数时，显示可用的命令列表。参数为 @emph{command} 时，打印有关该命令的帮助。@code{help pdb} 显示完整文档（即 @ref{c9,,pdb} 模块的文档字符串）。由于 @emph{command} 参数必须是标识符，因此要获取 @code{!} 的帮助必须输入 @code{help exec}。
@end deffn

@geindex where (pdb command)
@anchor{library/pdb pdbcommand-where}@anchor{35c5}
@deffn {Pdbcommand} w(here)

打印堆栈回溯，最新一帧在底部。有一个箭头指向当前帧，该帧决定了大多数命令的上下文。
@end deffn

@geindex down (pdb command)
@anchor{library/pdb pdbcommand-down}@anchor{35c6}
@deffn {Pdbcommand} d(own) [count]

在堆栈回溯中，将当前帧向下移动 @emph{count} 级（默认为 1 级，移向更新的帧）。
@end deffn

@geindex up (pdb command)
@anchor{library/pdb pdbcommand-up}@anchor{35c7}
@deffn {Pdbcommand} u(p) [count]

在堆栈回溯中，将当前帧向上移动 @emph{count} 级（默认为 1 级，移向更老的帧）。
@end deffn

@geindex break (pdb command)
@anchor{library/pdb pdbcommand-break}@anchor{35c8}
@deffn {Pdbcommand} b(reak) [([filename:]lineno | function) [, condition]]

如果带有 @emph{lineno} 参数，则在当前文件相应行处设置一个断点。如果带有 @emph{function} 参数，则在该函数的第一条可执行语句处设置一个断点。行号可以加上文件名和冒号作为前缀，以在另一个文件（可能是尚未加载的文件）中设置一个断点。另一个文件将在 @ref{262,,sys.path} 范围内搜索。请注意，每个断点都分配有一个编号，其他所有断点命令都引用该编号。

如果第二个参数存在，它应该是一个表达式，且它的计算值为 true 时断点才起作用。

如果不带参数执行，将列出所有中断，包括每个断点、命中该断点的次数、当前的忽略次数以及关联的条件（如果有）。
@end deffn

@geindex tbreak (pdb command)
@anchor{library/pdb pdbcommand-tbreak}@anchor{35c9}
@deffn {Pdbcommand} tbreak [([filename:]lineno | function) [, condition]]

临时断点，在第一次命中时会自动删除。它的参数与 @ref{35c8,,break} 相同。
@end deffn

@geindex clear (pdb command)
@anchor{library/pdb pdbcommand-clear}@anchor{35ca}
@deffn {Pdbcommand} cl(ear) [filename:lineno | bpnumber ...]

如果参数是 @emph{filename:lineno}，则清除此行上的所有断点。如果参数是空格分隔的断点编号列表，则清除这些断点。如果不带参数，则清除所有断点（但会先提示确认）。
@end deffn

@geindex disable (pdb command)
@anchor{library/pdb pdbcommand-disable}@anchor{35cb}
@deffn {Pdbcommand} disable [bpnumber ...]

禁用断点，断点以空格分隔的断点编号列表给出。禁用断点表示它不会导致程序停止执行，但是与清除断点不同，禁用的断点将保留在断点列表中并且可以（重新）启用。
@end deffn

@geindex enable (pdb command)
@anchor{library/pdb pdbcommand-enable}@anchor{35cc}
@deffn {Pdbcommand} enable [bpnumber ...]

启用指定的断点。
@end deffn

@geindex ignore (pdb command)
@anchor{library/pdb pdbcommand-ignore}@anchor{35cd}
@deffn {Pdbcommand} ignore bpnumber [count]

为指定的断点编号设置忽略次数。如果省略 count，则忽略次数将设置为 0。忽略次数为 0 时断点将变为活动状态。如果为非零值，在每次达到断点，且断点未禁用，且关联条件计算值为 true 的情况下，该忽略次数会递减。
@end deffn

@geindex condition (pdb command)
@anchor{library/pdb pdbcommand-condition}@anchor{35ce}
@deffn {Pdbcommand} condition bpnumber [condition]

为断点设置一个新 @emph{condition}，它是一个表达式，且它的计算值为 true 时断点才起作用。如果没有给出 @emph{condition}，则删除现有条件，也就是将断点设为无条件。
@end deffn

@geindex commands (pdb command)
@anchor{library/pdb pdbcommand-commands}@anchor{35cf}
@deffn {Pdbcommand} commands [bpnumber]

为编号是 @emph{bpnumber} 的断点指定一系列命令。命令内容将显示在后续的几行中。输入仅包含 @code{end} 的行来结束命令列表。举个例子:

@example
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
@end example

要删除断点上的所有命令，请输入 @code{commands} 并立即以 @code{end} 结尾，也就是不指定任何命令。

如果不带 @emph{bpnumber} 参数，@code{commands} 作用于最后一个被设置的断点。

可以为断点指定命令来重新启动程序。只需使用 @ref{35b6,,continue} 或 @ref{35b7,,step} 命令或其他可以继续运行程序的命令。

如果指定了某个继续运行程序的命令（目前包括 @ref{35b6,,continue}, @ref{35b7,,step}, @ref{35b8,,next}, @ref{35d0,,return}, @ref{35d1,,jump}, @ref{35d2,,quit} 及它们的缩写）将终止命令列表（就像该命令后紧跟着 end）。因为在任何时候继续运行下去（即使是简单的 next 或 step），都可能会遇到另一个断点，该断点可能具有自己的命令列表，这导致要执行的列表含糊不清。

如果在命令列表中加入 'silent' 命令，那么在该断点处停下时就不会打印常规信息。如果希望断点打印特定信息后继续运行，这可能是理想的。如果没有其他命令来打印一些信息，则看不到已达到断点的迹象。
@end deffn

@geindex step (pdb command)
@anchor{library/pdb pdbcommand-step}@anchor{35b7}
@deffn {Pdbcommand} s(tep)

运行当前行，在第一个可以停止的位置（在被调用的函数内部或在当前函数的下一行）停下。
@end deffn

@geindex next (pdb command)
@anchor{library/pdb pdbcommand-next}@anchor{35b8}
@deffn {Pdbcommand} n(ext)

继续运行，直到运行到当前函数的下一行，或当前函数返回为止。（ @ref{35b8,,next} 和 @ref{35b7,,step} 之间的区别在于，@ref{35b7,,step} 进入被调用函数内部并停止，而 @ref{35b8,,next} （几乎）全速运行被调用函数，仅在当前函数的下一行停止。）
@end deffn

@geindex until (pdb command)
@anchor{library/pdb pdbcommand-until}@anchor{35d3}
@deffn {Pdbcommand} unt(il) [lineno]

如果不带参数，则继续运行，直到行号比当前行大时停止。

如果带有行号，则继续运行，直到行号大于或等于该行号时停止。在这两种情况下，当前帧返回时也将停止。


在 3.2 版更改: 允许明确给定行号。

@end deffn

@geindex return (pdb command)
@anchor{library/pdb pdbcommand-return}@anchor{35d0}
@deffn {Pdbcommand} r(eturn)

继续运行，直到当前函数返回。
@end deffn

@geindex continue (pdb command)
@anchor{library/pdb pdbcommand-continue}@anchor{35b6}
@deffn {Pdbcommand} c(ont(inue))

继续运行，仅在遇到断点时停止。
@end deffn

@geindex jump (pdb command)
@anchor{library/pdb pdbcommand-jump}@anchor{35d1}
@deffn {Pdbcommand} j(ump) lineno

设置即将运行的下一行。仅可用于堆栈最底部的帧。它可以往回跳来再次运行代码，也可以往前跳来跳过不想运行的代码。

需要注意的是，不是所有的跳转都是允许的 -- 例如，不能跳转到 @ref{d02,,for} 循环的中间或跳出 @ref{2c3,,finally} 子句。
@end deffn

@geindex list (pdb command)
@anchor{library/pdb pdbcommand-list}@anchor{35c2}
@deffn {Pdbcommand} l(ist) [first[, last]]

列出当前文件的源代码。如果不带参数，则列出当前行周围的 11 行，或继续前一个列表。如果用 @code{.} 作为参数，则列出当前行周围的 11 行。如果带有一个参数，则列出那一行周围的 11 行。如果带有两个参数，则列出所给的范围中的代码；如果第二个参数小于第一个参数，则将其解释为列出行数的计数。

当前帧中的当前行用 @code{->} 标记。如果正在调试异常，且最早抛出或传递该异常的行不是当前行，则那一行用 @code{>>} 标记。


3.2 新版功能: @code{>>} 标记。

@end deffn

@geindex ll (pdb command)
@anchor{library/pdb pdbcommand-ll}@anchor{35d4}
@deffn {Pdbcommand} ll | longlist

列出当前函数或帧的所有源代码。相关行的标记与 @ref{35c2,,list} 相同。


3.2 新版功能.

@end deffn

@geindex args (pdb command)
@anchor{library/pdb pdbcommand-args}@anchor{35d5}
@deffn {Pdbcommand} a(rgs)

打印当前函数的参数列表。
@end deffn

@geindex p (pdb command)
@anchor{library/pdb pdbcommand-p}@anchor{97b}
@deffn {Pdbcommand} p expression

在当前上下文中运行 @emph{expression} 并打印它的值。

@cartouche
@quotation 注解 
@code{print()} 也可以使用，但它不是一个调试器命令 --- 它执行 Python @ref{97a,,print()} 函数。
@end quotation
@end cartouche
@end deffn

@geindex pp (pdb command)
@anchor{library/pdb pdbcommand-pp}@anchor{35d6}
@deffn {Pdbcommand} pp expression

与 @ref{97b,,p} 命令类似，但表达式的值使用 @ref{d2,,pprint} 模块美观地打印。
@end deffn

@geindex whatis (pdb command)
@anchor{library/pdb pdbcommand-whatis}@anchor{35d7}
@deffn {Pdbcommand} whatis expression

打印 @emph{expression} 的类型。
@end deffn

@geindex source (pdb command)
@anchor{library/pdb pdbcommand-source}@anchor{35d8}
@deffn {Pdbcommand} source expression

尝试获取给定对象的源代码并显示出来。


3.2 新版功能.

@end deffn

@geindex display (pdb command)
@anchor{library/pdb pdbcommand-display}@anchor{35d9}
@deffn {Pdbcommand} display [expression]

如果表达式的值发生改变则显示它的值，每次将停止执行当前帧。

不带表达式则列出当前帧的所有显示表达式。


3.2 新版功能.

@end deffn

@geindex undisplay (pdb command)
@anchor{library/pdb pdbcommand-undisplay}@anchor{35da}
@deffn {Pdbcommand} undisplay [expression]

不再显示当前帧中的表达式。 不带表达式则清除当前帧的所有显示表达式。


3.2 新版功能.

@end deffn

@geindex interact (pdb command)
@anchor{library/pdb pdbcommand-interact}@anchor{35db}
@deffn {Pdbcommand} interact

启动一个交互式解释器（使用 @ref{1a,,code} 模块），它的全局命名空间将包含当前作用域中的所有（全局和局部）名称。


3.2 新版功能.

@end deffn
@anchor{library/pdb debugger-aliases}@anchor{35c3}
@geindex alias (pdb command)
@anchor{library/pdb pdbcommand-alias}@anchor{35dc}
@deffn {Pdbcommand} alias [name [command]]

创建一个标识为 @emph{name} 的别名来执行 @emph{command}。 执行的命令 @emph{不可} 加上引号。 可替换形参可通过 @code{%1}, @code{%2} 等来标示，而 @code{%*} 会被所有形参所替换。 如果没有给出命令，则会显示 @emph{name} 的当前别名。 如果没有给出参数，则会列出所有别名。

别名允许嵌套并可包含能在 pdb 提示符下合法输入的任何内容。 请注意内部 pdb 命令 @emph{可以} 被别名所覆盖。 这样的命令将被隐藏直到别名被移除。 别名会递归地应用到命令行的第一个单词；行内的其他单词不会受影响。

作为示例，这里列出了两个有用的别名（特别适合放在 @code{.pdbrc} 文件中）:

@example
# Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
# Print instance variables in self
alias ps pi self
@end example
@end deffn

@geindex unalias (pdb command)
@anchor{library/pdb pdbcommand-unalias}@anchor{35dd}
@deffn {Pdbcommand} unalias name

删除指定的别名。
@end deffn

@geindex ! (pdb command)
@anchor{library/pdb pdbcommand-!}@anchor{35de}
@deffn {Pdbcommand} ! statement

在当前堆栈帧的上下文中执行 (单行) @emph{statement}。 感叹号可以被省略，除非语句的第一个单词与调试器命令重名。 要设置全局变量，你可以在同一行上为赋值命令添加前缀的 @ref{13a7,,global} 语句，例如:

@example
(Pdb) global list_options; list_options = ['-l']
(Pdb)
@end example
@end deffn

@geindex run (pdb command)
@geindex restart (pdb command)
@anchor{library/pdb pdbcommand-run}@anchor{35df}
@deffn {Pdbcommand} run [args ...]
@anchor{library/pdb pdbcommand-restart}@anchor{35e0}
@deffnx {Pdbcommand} restart [args ...]

重启被调试的 Python 程序。 如果提供了参数，它会用 @ref{e8,,shlex} 来拆分且拆分结果将被用作新的 @ref{cce,,sys.argv}。 历史、中断点、动作和调试器选项将被保留。 @ref{35e0,,restart} 是 @ref{35df,,run} 的一个别名。
@end deffn

@geindex quit (pdb command)
@anchor{library/pdb pdbcommand-quit}@anchor{35d2}
@deffn {Pdbcommand} q(uit)

退出调试器。 被执行的程序将被中止。
@end deffn

@geindex debug (pdb command)
@anchor{library/pdb pdbcommand-debug}@anchor{35e1}
@deffn {Pdbcommand} debug code

进入一个对代码参数执行步进的递归调试器（该参数是在当前环境中执行的任意表达式或语句）。
@end deffn

@geindex retval (pdb command)
@anchor{library/pdb pdbcommand-retval}@anchor{35e2}
@deffn {Pdbcommand} retval

打印函数最后一次返回的返回值。
@end deffn

@node Python Profilers 分析器,timeit --- 测量小代码片段的执行时间,pdb --- Python 的调试器,调试和分析
@anchor{library/profile doc}@anchor{35e3}@anchor{library/profile profile}@anchor{35e4}@anchor{library/profile the-python-profilers}@anchor{35e5}
@subsection Python Profilers 分析器


@strong{源代码：} Lib/profile.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/profile.py} 和 Lib/pstats.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pstats.py}


__________________________________________________________________


@menu
* profile分析器简介:: 
* 实时用户手册:: 
* profile 和 cProfile 模块参考:: 
* Stats 类:: 
* 什么是确定性性能分析？:: 
* 局限性:: 
* 准确估量:: 
* 使用自定义计时器:: 

@end menu

@node profile分析器简介,实时用户手册,,Python Profilers 分析器
@anchor{library/profile introduction-to-the-profilers}@anchor{35e6}@anchor{library/profile profiler-introduction}@anchor{35e7}
@subsubsection profile分析器简介


@geindex deterministic profiling
@geindex profiling@comma{} deterministic

@ref{27,,cProfile} 和 @ref{d3,,profile} 提供了 Python 程序的 @emph{确定性性能分析} 。 @emph{profile} 是一组统计数据，描述程序的各个部分执行的频率和时间。这些统计数据可以通过 @ref{d4,,pstats} 模块格式化为报表。

Python 标准库提供了同一分析接口的两种不同实现：


@enumerate 

@item 
对于大多数用户，建议使用 @ref{27,,cProfile} ；这是一个 C 扩展插件，因为其合理的运行开销，所以适合于分析长时间运行的程序。该插件基于 @code{lsprof} ，由 Brett Rosen 和 Ted Chaotter 贡献。

@item 
@ref{d3,,profile} 是一个纯 Python 模块（@ref{27,,cProfile} 就是模拟其接口的 C 语言实现），但它会显著增加配置程序的开销。如果你正在尝试以某种方式扩展分析器，则使用此模块可能会更容易完成任务。该模块最初由 Jim Roskind  设计和编写。
@end enumerate

@cartouche
@quotation 注解 
profiler 分析器模块被设计为给指定的程序提供执行概要文件，而不是用于基准测试目的（ @ref{10d,,timeit} 才是用于此目标的，它能获得合理准确的结果）。这特别适用于将 Python 代码与 C 代码进行基准测试：分析器为Python 代码引入开销，但不会为 C级别的函数引入开销，因此 C 代码似乎比任何Python 代码都更快。
@end quotation
@end cartouche

@node 实时用户手册,profile 和 cProfile 模块参考,profile分析器简介,Python Profilers 分析器
@anchor{library/profile instant-user-s-manual}@anchor{35e8}@anchor{library/profile profile-instant}@anchor{35e9}
@subsubsection 实时用户手册


本节是为 “不想阅读手册” 的用户提供的。它提供了非常简短的概述，并允许用户快速对现有应用程序执行评测。

要分析采用单个参数的函数，可以执行以下操作：

@example
import cProfile
import re
cProfile.run('re.compile("foo|bar")')
@end example

（如果 @ref{27,,cProfile} 在您的系统上不可用，请使用 @ref{d3,,profile} 。）

上述操作将运行 @ref{555,,re.compile()} 并打印分析结果，如下所示：

@example
      197 function calls (192 primitive calls) in 0.002 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 re.py:212(compile)
     1    0.000    0.000    0.001    0.001 re.py:268(_compile)
     1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
     1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
     4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
   3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)
@end example

第一行显示监听了197个调用。在这些调用中，有192个是 @emph{原始的} ，这意味着调用不是通过递归引发的。下一行: @code{Ordered by: standard name} ，表示最右边列中的文本字符串用于对输出进行排序。列标题包括：


@table @asis

@item ncalls

调用次数

@item tottime

在指定函数中消耗的总时间（不包括调用子函数的时间）

@item percall

是 @code{tottime} 除以 @code{ncalls} 的商

@item cumtime

指定的函数及其所有子函数（从调用到退出）消耗的累积时间。这个数字对于递归函数来说是准确的。

@item percall

是 @code{cumtime} 除以原始调用（次数）的商（即：函数运行一次的平均时间）

@item filename:lineno(function)

提供相应数据的每个函数
@end table

如果第一列中有两个数字（例如3/1），则表示函数递归。第二个值是原始调用次数，第一个是调用的总次数。请注意，当函数不递归时，这两个值是相同的，并且只打印单个数字。

profile 运行结束时，打印输出不是必须的。也可以通过为 @code{run()} 函数指定文件名，将结果保存到文件中：

@example
import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')
@end example

@ref{35ea,,pstats.Stats} 类从文件中读取 profile 结果，并以各种方式对其进行格式化。

@ref{27,,cProfile} 和 @ref{d3,,profile} 文件也可以作为脚本调用，以分析另一个脚本。例如：

@example
python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
@end example

@code{-o} 将profile 结果写入文件而不是标准输出

@code{-s} 指定 @ref{35eb,,sort_stats()} 排序值之一以对输出进行排序。这仅适用于未提供 @code{-o} 的情况

@code{-m} 指定要分析的是模块而不是脚本。

@quotation


3.7 新版功能: @ref{27,,cProfile} 添加 @code{-m} 选项



3.8 新版功能: @ref{d3,,profile} 添加 @code{-m} 选项

@end quotation

@ref{d4,,pstats} 模块的 @ref{35ea,,Stats} 类具有各种方法用来操纵和打印保存到性能分析结果文件的数据。

@example
import pstats
from pstats import SortKey
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()
@end example

@ref{35ec,,strip_dirs()} 方法移除了所有模块名称中的多余路径。 @ref{35eb,,sort_stats()} 方法按照打印出来的标准模块/行/名称对所有条目进行排序。 @ref{35ed,,print_stats()} 方法打印出所有的统计数据。 你可以尝试下列排序调用:

@example
p.sort_stats(SortKey.NAME)
p.print_stats()
@end example

第一个调用实际上将按函数名称对列表进行排序，而第二个调用将打印出统计数据。 下面是一些可以尝试的有趣调用:

@example
p.sort_stats(SortKey.CUMULATIVE).print_stats(10)
@end example

这将按一个函数中的累计时间对性能分析数据进行排序，然后只打印出最重要的十行。 如果你了解哪些算法在耗费时间，上面这一行就是你应该使用的。

如果你想要看看哪些函数的循环次数多，且耗费时间长，你应当这样做:

@example
p.sort_stats(SortKey.TIME).print_stats(10)
@end example

以按照每个函数耗费的时间进行排序，然后打印前十个函数的统计数据。

你也可以尝试：

@example
p.sort_stats(SortKey.FILENAME).print_stats('__init__')
@end example

这将按照文件名对所有统计数据进行排序，然后只打印出类初始化方法的统计数据 (因为它们的名称中都有 @code{__init__})。 作为最后一个例子，你可以尝试:

@example
p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')
@end example

这一行以时间为主键，并以累计时间为次键进行排序，然后打印出部分统计数据。 具体来说，该列表首先被缩减至原始大小的 50% (即: @code{.5})，然后只保留包含 @code{init} 的行，并打印该子列表。

如果你想知道有哪些函数调用了上述函数，你现在就可以做 (@code{p} 仍然会按照最后一个标准进行排序):

@example
p.print_callers(.5, 'init')
@end example

这样你将得到每个被列出的函数的调用方列表。

如果你想要更多的功能，你就必须阅读手册，或者自行猜测下列函数的作用:

@example
p.print_callees()
p.add('restats')
@end example

作为脚本发起调用，@ref{d4,,pstats} 模块是一个用于读取和性能分析转储文件的统计数据浏览器。 它有一个简单的面向行的界面（使用 @ref{19,,cmd} 实现）和交互式的帮助。

@node profile 和 cProfile 模块参考,Stats 类,实时用户手册,Python Profilers 分析器
@anchor{library/profile module-cProfile}@anchor{27}@anchor{library/profile profile-and-cprofile-module-reference}@anchor{35ee}
@subsubsection @code{profile} 和 @code{cProfile} 模块参考


@geindex cProfile (模块)
@anchor{library/profile module-profile}@anchor{d3}
@geindex profile (模块)

@ref{d3,,profile} 和 @ref{27,,cProfile} 模块都提供下列函数：

@geindex run() (在 profile 模块中)
@anchor{library/profile profile run}@anchor{35ef}
@deffn {函数} profile.run (command, filename=None, sort=-1)

此函数接受一个可被传递给 @ref{d14,,exec()} 函数的单独参数，以及一个可选的文件名。 在所有情况下这个例程都会执行:

@example
exec(command, __main__.__dict__, __main__.__dict__)
@end example

并收集执行过程中的性能分析统计数据。 如果未提供文件名，则此函数会自动创建一个 @ref{35ea,,Stats} 实例并打印一个简单的性能分析报告。 如果指定了 sort 值，则它会被传递给这个 @ref{35ea,,Stats} 实例以控制结果的排序方式。
@end deffn

@geindex runctx() (在 profile 模块中)
@anchor{library/profile profile runctx}@anchor{35f0}
@deffn {函数} profile.runctx (command, globals, locals, filename=None, sort=-1)

此函数类似于 @ref{35ef,,run()}，带有为 @emph{command} 字符串提供全局和局部字典的附加参数。 这个例程会执行:

@example
exec(command, globals, locals)
@end example

并像在上述的 @ref{35ef,,run()} 函数中一样收集性能分析数据。
@end deffn

@geindex Profile (profile 中的类)
@anchor{library/profile profile Profile}@anchor{2f3}
@deffn {类} profile.Profile (timer=None, timeunit=0.0, subcalls=True, builtins=True)

这个类通常只在需要比 @code{cProfile.run()} 函数所能提供的更精确的性能分析控制时被使用。

可以通过 @emph{timer} 参数提供一个自定义计时器来测量代码运行花费了多长时间。 它必须是一个返回代表当前时间的单个数字的函数。 如果该数字为整数，则 @emph{timeunit} 指定一个表示每个时间单位持续时间的乘数。 例如，如果定时器返回以千秒为计量单位的时间值，则时间单位将为 @code{.001}。

直接使用 @ref{2f3,,Profile} 类将允许格式化性能分析结果而无需将性能分析数据写入到文件:

@example
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
@end example

@ref{2f3,,Profile} 类也可作为上下文管理器使用 (仅在 @ref{27,,cProfile} 模块中支持。 参见 @ref{15f5,,上下文管理器类型}):

@example
import cProfile

with cProfile.Profile() as pr:
    # ... do something ...

pr.print_stats()
@end example


在 3.8 版更改: 添加了上下文管理器支持。


@geindex enable() (profile.Profile 方法)
@anchor{library/profile profile Profile enable}@anchor{35f1}
@deffn {方法} enable ()

开始收集分析数据。仅在 @ref{27,,cProfile} 可用。
@end deffn

@geindex disable() (profile.Profile 方法)
@anchor{library/profile profile Profile disable}@anchor{35f2}
@deffn {方法} disable ()

停止收集分析数据。仅在 @ref{27,,cProfile} 可用。
@end deffn

@geindex create_stats() (profile.Profile 方法)
@anchor{library/profile profile Profile create_stats}@anchor{35f3}
@deffn {方法} create_stats ()

停止收集分析数据，并在内部将结果记录为当前 profile。
@end deffn

@geindex print_stats() (profile.Profile 方法)
@anchor{library/profile profile Profile print_stats}@anchor{35f4}
@deffn {方法} print_stats (sort=-1)

根据当前性能分析数据创建一个 @ref{35ea,,Stats} 对象并将结果打印到 stdout。
@end deffn

@geindex dump_stats() (profile.Profile 方法)
@anchor{library/profile profile Profile dump_stats}@anchor{35f5}
@deffn {方法} dump_stats (filename)

将当前profile 的结果写入 @emph{filename} 。
@end deffn

@geindex run() (profile.Profile 方法)
@anchor{library/profile profile Profile run}@anchor{35f6}
@deffn {方法} run (cmd)

通过 @ref{d14,,exec()} 对该命令进行性能分析。
@end deffn

@geindex runctx() (profile.Profile 方法)
@anchor{library/profile profile Profile runctx}@anchor{35f7}
@deffn {方法} runctx (cmd, globals, locals)

通过 @ref{d14,,exec()} 并附带指定的全局和局部环境对该命令进行性能分析。
@end deffn

@geindex runcall() (profile.Profile 方法)
@anchor{library/profile profile Profile runcall}@anchor{3c9}
@deffn {方法} runcall (func, /, *args, **kwargs)

对 @code{func(*args, **kwargs)} 进行性能分析
@end deffn
@end deffn

请注意性能分析只有在被调用的命令/函数确实能返回时才可用。 如果解释器被终结（例如在被调用的命令/函数执行期间通过 @ref{db2,,sys.exit()} 调用）则将不会打印性能分析结果。

@node Stats 类,什么是确定性性能分析？,profile 和 cProfile 模块参考,Python Profilers 分析器
@anchor{library/profile profile-stats}@anchor{35f8}@anchor{library/profile the-stats-class}@anchor{35f9}
@subsubsection @code{Stats} 类


性能数据的分析是使用 @ref{35ea,,Stats} 类来完成的。
@anchor{library/profile module-pstats}@anchor{d4}
@geindex pstats (模块)

@geindex Stats (pstats 中的类)
@anchor{library/profile pstats Stats}@anchor{35ea}
@deffn {类} pstats.Stats (*filenames or profile, stream=sys.stdout)

这个类构造器会基于 @emph{filename} (或文件名列表) 或者 @code{Profile} 实例创建一个“统计对象”。 输出将被打印到由 @emph{stream} 所指定的流。

上述构造器所选择的文件必须由相应版本的 @ref{d3,,profile} 或 @ref{27,,cProfile} 来创建。 具体来说，@emph{不会} 保证文件与此性能分析器的未来版本兼容，也不会保证与其他性能分析器，或运行于不同操作系统的同一性能分析器所产生的文件兼容。 如果提供了几个文件，则相同函数的所有统计数据将被聚合在一起，这样就可以在单个报告中同时考虑几个进程的总体情况。 如果额外的文件需要与现有 @ref{35ea,,Stats} 对象中的数据相结合，则可以使用 @ref{35fa,,add()} 方法。

作为从一个文件读取性能分析数据的替代，可以使用 @code{cProfile.Profile} 或 @ref{2f3,,profile.Profile} 对象作为性能分析数据源。

@ref{35ea,,Stats} 对象有以下方法:

@geindex strip_dirs() (pstats.Stats 方法)
@anchor{library/profile pstats Stats strip_dirs}@anchor{35ec}
@deffn {方法} strip_dirs ()

这个用于 @ref{35ea,,Stats} 类的方法会从文件名中去除所有前导路径信息。 它对于减少打印输出的大小以适应（接近） 80 列限制。 这个方法会修改对象，被去除的信息将会丢失。 在执行去除操作后，可以认为对象拥有的条目将使用“随机”顺序，就像它刚在对象初始化并加载之后一样。 如果 @ref{35ec,,strip_dirs()} 导致两个函数名变得无法区分（它们位于相同文件名的相同行，并且具有相同的函数名），那么这两个条目的统计数据将被累积到单个条目中。
@end deffn

@geindex add() (pstats.Stats 方法)
@anchor{library/profile pstats Stats add}@anchor{35fa}
@deffn {方法} add (*filenames)

@ref{35ea,,Stats} 类的这个方法会将额外的性能分析信息累积到当前的性能分析对象中。 它的参数应当指向由相应版本的 @ref{35ef,,profile.run()} 或 @code{cProfile.run()} 所创建的文件名。 相同名称（包括 file, line, name）函数的统计信息会自动累积到单个函数的统计信息。
@end deffn

@geindex dump_stats() (pstats.Stats 方法)
@anchor{library/profile pstats Stats dump_stats}@anchor{35fb}
@deffn {方法} dump_stats (filename)

Save the data loaded into the @ref{35ea,,Stats} object to a file named
@emph{filename}.  The file is created if it does not exist, and is overwritten
if it already exists.  This is equivalent to the method of the same name
on the @ref{2f3,,profile.Profile} and @code{cProfile.Profile} classes.
@end deffn

@geindex sort_stats() (pstats.Stats 方法)
@anchor{library/profile pstats Stats sort_stats}@anchor{35eb}
@deffn {方法} sort_stats (*keys)

This method modifies the @ref{35ea,,Stats} object by sorting it according to
the supplied criteria.  The argument can be either a string or a SortKey
enum identifying the basis of a sort (example: @code{'time'}, @code{'name'},
@code{SortKey.TIME} or @code{SortKey.NAME}). The SortKey enums argument have
advantage over the string argument in that it is more robust and less
error prone.

When more than one key is provided, then additional keys are used as
secondary criteria when there is equality in all keys selected before
them.  For example, @code{sort_stats(SortKey.NAME, SortKey.FILE)} will sort
all the entries according to their function name, and resolve all ties
(identical function names) by sorting by file name.

For the string argument, abbreviations can be used for any key names, as
long as the abbreviation is unambiguous.

The following are the valid string and SortKey:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

有效字符串参数

@tab

有效枚举参数

@tab

含义

@item

@code{'calls'}

@tab

SortKey.CALLS

@tab

调用次数

@item

@code{'cumulative'}

@tab

SortKey.CUMULATIVE

@tab

累积时间

@item

@code{'cumtime'}

@tab

N/A

@tab

累积时间

@item

@code{'file'}

@tab

N/A

@tab

文件名

@item

@code{'filename'}

@tab

SortKey.FILENAME

@tab

文件名

@item

@code{'module'}

@tab

N/A

@tab

文件名

@item

@code{'ncalls'}

@tab

N/A

@tab

调用次数

@item

@code{'pcalls'}

@tab

SortKey.PCALLS

@tab

原始调用计数

@item

@code{'line'}

@tab

SortKey.LINE

@tab

行号

@item

@code{'name'}

@tab

SortKey.NAME

@tab

函数名称

@item

@code{'nfl'}

@tab

SortKey.NFL

@tab

名称/文件/行

@item

@code{'stdname'}

@tab

SortKey.STDNAME

@tab

标准名称

@item

@code{'time'}

@tab

SortKey.TIME

@tab

内部时间

@item

@code{'tottime'}

@tab

N/A

@tab

内部时间

@end multitable


Note that all sorts on statistics are in descending order (placing most
time consuming items first), where as name, file, and line number searches
are in ascending order (alphabetical). The subtle distinction between
@code{SortKey.NFL} and @code{SortKey.STDNAME} is that the standard name is a
sort of the name as printed, which means that the embedded line numbers
get compared in an odd way.  For example, lines 3, 20, and 40 would (if
the file names were the same) appear in the string order 20, 3 and 40.
In contrast, @code{SortKey.NFL} does a numeric compare of the line numbers.
In fact, @code{sort_stats(SortKey.NFL)} is the same as
@code{sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)}.

For backward-compatibility reasons, the numeric arguments @code{-1}, @code{0},
@code{1}, and @code{2} are permitted.  They are interpreted as @code{'stdname'},
@code{'calls'}, @code{'time'}, and @code{'cumulative'} respectively.  If this old
style format (numeric) is used, only one sort key (the numeric key) will
be used, and additional arguments will be silently ignored.

@c For compatibility with the old profiler.


3.7 新版功能: Added the SortKey enum.

@end deffn

@geindex reverse_order() (pstats.Stats 方法)
@anchor{library/profile pstats Stats reverse_order}@anchor{35fc}
@deffn {方法} reverse_order ()

This method for the @ref{35ea,,Stats} class reverses the ordering of the
basic list within the object.  Note that by default ascending vs
descending order is properly selected based on the sort key of choice.

@c This method is provided primarily for compatibility with the old
@c profiler.
@end deffn

@geindex print_stats() (pstats.Stats 方法)
@anchor{library/profile pstats Stats print_stats}@anchor{35ed}
@deffn {方法} print_stats (*restrictions)

This method for the @ref{35ea,,Stats} class prints out a report as described
in the @ref{35ef,,profile.run()} definition.

The order of the printing is based on the last
@ref{35eb,,sort_stats()} operation done on the object (subject to
caveats in @ref{35fa,,add()} and
@ref{35ec,,strip_dirs()}).

The arguments provided (if any) can be used to limit the list down to the
significant entries.  Initially, the list is taken to be the complete set
of profiled functions.  Each restriction is either an integer (to select a
count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to
select a percentage of lines), or a string that will interpreted as a
regular expression (to pattern match the standard name that is printed).
If several restrictions are provided, then they are applied sequentially.
For example:

@example
print_stats(.1, 'foo:')
@end example

would first limit the printing to first 10% of list, and then only print
functions that were part of filename @code{.*foo:}.  In contrast, the
command:

@example
print_stats('foo:', .1)
@end example

would limit the list to all functions having file names @code{.*foo:},
and then proceed to only print the first 10% of them.
@end deffn

@geindex print_callers() (pstats.Stats 方法)
@anchor{library/profile pstats Stats print_callers}@anchor{35fd}
@deffn {方法} print_callers (*restrictions)

This method for the @ref{35ea,,Stats} class prints a list of all functions
that called each function in the profiled database.  The ordering is
identical to that provided by @ref{35ed,,print_stats()}, and the
definition of the restricting argument is also identical.  Each caller is
reported on its own line.  The format differs slightly depending on the
profiler that produced the stats:


@itemize *

@item 
With @ref{d3,,profile}, a number is shown in parentheses after each caller
to show how many times this specific call was made.  For convenience, a
second non-parenthesized number repeats the cumulative time spent in the
function at the right.

@item 
With @ref{27,,cProfile}, each caller is preceded by three numbers: the
number of times this specific call was made, and the total and
cumulative times spent in the current function while it was invoked by
this specific caller.
@end itemize
@end deffn

@geindex print_callees() (pstats.Stats 方法)
@anchor{library/profile pstats Stats print_callees}@anchor{35fe}
@deffn {方法} print_callees (*restrictions)

This method for the @ref{35ea,,Stats} class prints a list of all function
that were called by the indicated function.  Aside from this reversal of
direction of calls (re: called vs was called by), the arguments and
ordering are identical to the @ref{35fd,,print_callers()} method.
@end deffn

@geindex get_stats_profile() (pstats.Stats 方法)
@anchor{library/profile pstats Stats get_stats_profile}@anchor{35ff}
@deffn {方法} get_stats_profile ()

This method returns an instance of StatsProfile, which contains a mapping
of function names to instances of FunctionProfile. Each FunctionProfile
instance holds information related to the function's profile such as how
long the function took to run, how many times it was called, etc...


3.9 新版功能: Added the following dataclasses: StatsProfile, FunctionProfile.
Added the following function: get_stats_profile.

@end deffn
@end deffn

@node 什么是确定性性能分析？,局限性,Stats 类,Python Profilers 分析器
@anchor{library/profile deterministic-profiling}@anchor{3600}@anchor{library/profile what-is-deterministic-profiling}@anchor{3601}
@subsubsection 什么是确定性性能分析？


@emph{确定性性能分析} 旨在反映这样一个事实：即所有 @emph{函数调用} 、 @emph{函数返回} 和 @emph{异常} 事件都被监控，并且对这些事件之间的间隔（在此期间用户的代码正在执行）进行精确计时。相反，统计分析（不是由该模块完成）随机采样有效指令指针，并推断时间花费在哪里。后一种技术传统上涉及较少的开销（因为代码不需要检测），但只提供了时间花在哪里的相对指示。

在Python中，由于在执行过程中总有一个活动的解释器，因此执行确定性评测不需要插入指令的代码。Python 自动为每个事件提供一个:dfn:@cite{钩子} （可选回调）。此外，Python 的解释特性往往会给执行增加太多开销，以至于在典型的应用程序中，确定性分析往往只会增加很小的处理开销。结果是，确定性分析并没有那么代价高昂，但是它提供了有关 Python 程序执行的大量运行时统计信息。

调用计数统计信息可用于识别代码中的错误（意外计数），并识别可能的内联扩展点（高频调用）。内部时间统计可用于识别应仔细优化的 "热循环" 。累积时间统计可用于识别算法选择上的高级别错误。请注意，该分析器中对累积时间的异常处理，允许直接比较算法的递归实现与迭代实现的统计信息。

@node 局限性,准确估量,什么是确定性性能分析？,Python Profilers 分析器
@anchor{library/profile limitations}@anchor{3602}@anchor{library/profile profile-limitations}@anchor{3603}
@subsubsection 局限性


一个限制是关于时间信息的准确性。确定性性能分析存在一个涉及精度的基本问题。最明显的限制是，底层的 "时钟" 周期大约为0.001秒（通常）。因此，没有什么测量会比底层时钟更精确。如果进行了足够的测量，那么 "误差" 将趋于平均。不幸的是，删除第一个错误会导致第二个错误来源。

第二个问题是，从调度事件到分析器调用获取时间函数实际 @emph{获取} 时钟状态，这需要 "一段时间" 。类似地，从获取时钟值（然后保存）开始，直到再次执行用户代码为止，退出分析器事件句柄时也存在一定的延迟。因此，多次调用单个函数或调用多个函数通常会累积此错误。尽管这种方式的误差通常小于时钟的精度（小于一个时钟周期），但它 @emph{可以} 累积并变得非常可观。

与开销较低的 @ref{27,,cProfile} 相比， @ref{d3,,profile} 的问题更为严重。出于这个原因， @ref{d3,,profile} 提供了一种针对指定平台的自我校准方法，以便可以在很大程度上（平均地）消除此误差。  校准后，结果将更准确（在最小二乘意义上），但它有时会产生负数（当调用计数异常低，且概率之神对您不利时：-）。因此 @emph{不要} 对产生的负数感到惊慌。它们应该只在你手工校准分析器的情况下才会出现，实际上结果比没有校准的情况要好。

@node 准确估量,使用自定义计时器,局限性,Python Profilers 分析器
@anchor{library/profile calibration}@anchor{3604}@anchor{library/profile profile-calibration}@anchor{3605}
@subsubsection 准确估量


@ref{d3,,profile} 模块的 profiler 会从每个事件处理时间中减去一个常量，以补偿调用 time 函数和存储结果的开销。默认情况下，常数为0。对于特定的平台，可用以下程序获得更好修正常数（ @ref{3603,,局限性} ）。

@example
import profile
pr = profile.Profile()
for i in range(5):
    print(pr.calibrate(10000))
@end example

The method executes the number of Python calls given by the argument, directly
and again under the profiler, measuring the time for both. It then computes the
hidden overhead per profiler event, and returns that as a float.  For example,
on a 1.8Ghz Intel Core i5 running macOS, and using Python's time.process_time() as
the timer, the magical number is about 4.04e-6.

The object of this exercise is to get a fairly consistent result. If your
computer is @emph{very} fast, or your timer function has poor resolution, you might
have to pass 100000, or even 1000000, to get consistent results.

当你有一个一致的答案时，有三种方法可以使用：

@example
import profile

# 1. Apply computed bias to all Profile instances created hereafter.
profile.Profile.bias = your_computed_bias

# 2. Apply computed bias to a specific Profile instance.
pr = profile.Profile()
pr.bias = your_computed_bias

# 3. Specify computed bias in instance constructor.
pr = profile.Profile(bias=your_computed_bias)
@end example

If you have a choice, you are better off choosing a smaller constant, and then
your results will "less often" show up as negative in profile statistics.

@node 使用自定义计时器,,准确估量,Python Profilers 分析器
@anchor{library/profile profile-timers}@anchor{3606}@anchor{library/profile using-a-custom-timer}@anchor{3607}
@subsubsection 使用自定义计时器


If you want to change how current time is determined (for example, to force use
of wall-clock time or elapsed process time), pass the timing function you want
to the @code{Profile} class constructor:

@example
pr = profile.Profile(your_time_func)
@end example

The resulting profiler will then call @code{your_time_func}. Depending on whether
you are using @ref{2f3,,profile.Profile} or @code{cProfile.Profile},
@code{your_time_func}'s return value will be interpreted differently:


@table @asis

@item @ref{2f3,,profile.Profile}

@code{your_time_func} should return a single number, or a list of numbers whose
sum is the current time (like what @ref{b40,,os.times()} returns).  If the
function returns a single time number, or the list of returned numbers has
length 2, then you will get an especially fast version of the dispatch
routine.

Be warned that you should calibrate the profiler class for the timer function
that you choose (see @ref{3605,,准确估量}).  For most machines, a timer
that returns a lone integer value will provide the best results in terms of
low overhead during profiling.  (@ref{b40,,os.times()} is @emph{pretty} bad, as it
returns a tuple of floating point values).  If you want to substitute a
better timer in the cleanest fashion, derive a class and hardwire a
replacement dispatch method that best handles your timer call, along with the
appropriate calibration constant.

@item @code{cProfile.Profile}

@code{your_time_func} should return a single number.  If it returns integers,
you can also invoke the class constructor with a second argument specifying
the real duration of one unit of time.  For example, if
@code{your_integer_time_func} returns times measured in thousands of seconds,
you would construct the @code{Profile} instance as follows:

@example
pr = cProfile.Profile(your_integer_time_func, 0.001)
@end example

As the @code{cProfile.Profile} class cannot be calibrated, custom timer
functions should be used with care and should be as fast as possible.  For
the best results with a custom timer, it might be necessary to hard-code it
in the C source of the internal @code{_lsprof} module.
@end table

Python 3.3 adds several new functions in @ref{10c,,time} that can be used to make
precise measurements of process or wall-clock time. For example, see
@ref{3d4,,time.perf_counter()}.

@node timeit --- 测量小代码片段的执行时间,trace --- 跟踪Python语句执行,Python Profilers 分析器,调试和分析
@anchor{library/timeit doc}@anchor{3608}@anchor{library/timeit module-timeit}@anchor{10d}@anchor{library/timeit timeit-measure-execution-time-of-small-code-snippets}@anchor{3609}
@subsection @code{timeit} --- 测量小代码片段的执行时间


@geindex timeit (模块)

@strong{源码：} Lib/timeit.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/timeit.py}

@geindex Benchmarking
@geindex Performance


__________________________________________________________________


此模块提供了一种简单的方法来计算一小段 Python 代码的耗时。 它有 @ref{360a,,命令行界面} 以及一个 @ref{360b,,可调用} 方法。 它避免了许多测量时间的常见陷阱。 另见 Tim Peter 在 O'Reilly 出版的 @emph{Python Cookbook} 第二版中“算法”章节的概述。

@menu
* 基本示例: 基本示例<2>. 
* Python 接口:: 
* 命令行界面: 命令行界面<6>. 
* 示例: 示例<40>. 

@end menu

@node 基本示例<2>,Python 接口,,timeit --- 测量小代码片段的执行时间
@anchor{library/timeit basic-examples}@anchor{360c}
@subsubsection 基本示例


以下示例显示了如何使用 @ref{360a,,命令行界面} 来比较三个不同的表达式：

@example
$ python3 -m timeit '"-".join(str(n) for n in range(100))'
10000 loops, best of 5: 30.2 usec per loop
$ python3 -m timeit '"-".join([str(n) for n in range(100)])'
10000 loops, best of 5: 27.5 usec per loop
$ python3 -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 5: 23.2 usec per loop
@end example

这可以通过 @ref{360b,,Python 接口} 实现

@example
>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237
@end example

从 @ref{360b,,Python 接口} 还可以传出一个可调用对象:

@example
>>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
0.19665591977536678
@end example

但请注意 @ref{86a,,timeit()} 仅在使用命令行界面时会自动确定重复次数。 在 @ref{360d,,示例} 一节你可以找到更多的进阶示例。

@node Python 接口,命令行界面<6>,基本示例<2>,timeit --- 测量小代码片段的执行时间
@anchor{library/timeit id1}@anchor{360e}@anchor{library/timeit python-interface}@anchor{360b}
@subsubsection Python 接口


该模块定义了三个便利函数和一个公共类：

@geindex timeit() (在 timeit 模块中)
@anchor{library/timeit timeit timeit}@anchor{86a}
@deffn {函数} timeit.timeit (stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)

使用给定语句、 @emph{setup} 代码和 @emph{timer} 函数创建一个 @ref{360f,,Timer} 实例，并执行 @emph{number} 次其 @ref{69d,,timeit()} 方法。可选的 @emph{globals} 参数指定用于执行代码的命名空间。


在 3.5 版更改: 添加可选参数 @emph{globals} 。

@end deffn

@geindex repeat() (在 timeit 模块中)
@anchor{library/timeit timeit repeat}@anchor{3610}
@deffn {函数} timeit.repeat (stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None)

使用给定语句、 @emph{setup} 代码和 @emph{timer} 函数创建一个 @ref{360f,,Timer} 实例，并使用给定的 @emph{repeat} 计数和 @emph{number} 执行运行其 @ref{3611,,repeat()} 方法。可选的 @emph{globals} 参数指定用于执行代码的命名空间。


在 3.5 版更改: 添加可选参数 @emph{globals} 。



在 3.7 版更改: @emph{repeat} 的默认值由 3 更改为 5 。

@end deffn

@geindex default_timer() (在 timeit 模块中)
@anchor{library/timeit timeit default_timer}@anchor{3612}
@deffn {函数} timeit.default_timer ()

默认的计时器，总是 @ref{3d4,,time.perf_counter()} 。


在 3.3 版更改: @ref{3d4,,time.perf_counter()} 现在是默认计时器。

@end deffn

@geindex Timer (timeit 中的类)
@anchor{library/timeit timeit Timer}@anchor{360f}
@deffn {类} timeit.Timer (stmt='pass', setup='pass', timer=<timer function>, globals=None)

用于小代码片段的计数执行速度的类。

构造函数接受一个将计时的语句、一个用于设置的附加语句和一个定时器函数。两个语句都默认为 @code{'pass'} ；计时器函数与平台有关（请参阅模块文档字符串）。 @emph{stmt} 和 @emph{setup} 也可能包含多个以 @code{;} 或换行符分隔的语句，只要它们不包含多行字符串文字即可。该语句默认在 timeit 的命名空间内执行；可以通过将命名空间传递给 @emph{globals} 来控制此行为。

要测量第一个语句的执行时间，请使用 @ref{69d,,timeit()} 方法。 @ref{3611,,repeat()} 和 @ref{69c,,autorange()} 方法是方便的方法来调用 @ref{69d,,timeit()} 多次。

@emph{setup} 的执行时间从总体计时执行中排除。

@emph{stmt} 和 @emph{setup} 参数也可以使用不带参数的可调用对象。这将在一个计时器函数中嵌入对它们的调用，然后由 @ref{69d,,timeit()} 执行。请注意，由于额外的函数调用，在这种情况下，计时开销会略大一些。


在 3.5 版更改: 添加可选参数 @emph{globals} 。


@geindex timeit() (timeit.Timer 方法)
@anchor{library/timeit timeit Timer timeit}@anchor{69d}
@deffn {方法} timeit (number=1000000)

执行 @emph{number} 次主要语句。这将执行一次 setup 语句，然后返回执行主语句多次所需的时间，以秒为单位测量为浮点数。参数是通过循环的次数，默认为一百万。要使用的主语句、 setup 语句和 timer 函数将传递给构造函数。

@cartouche
@quotation 注解 
默认情况下， @ref{69d,,timeit()} 暂时关闭 @ref{1013,,garbage collection} 。这种方法的优点在于它使独立时序更具可比性。缺点是GC可能是所测量功能性能的重要组成部分。如果是这样，可以在 @emph{setup} 字符串中的第一个语句重新启用GC。例如:

@example
timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
@end example
@end quotation
@end cartouche
@end deffn

@geindex autorange() (timeit.Timer 方法)
@anchor{library/timeit timeit Timer autorange}@anchor{69c}
@deffn {方法} autorange (callback=None)

自动决定调用多少次 @ref{69d,,timeit()} 。

这是一个便利函数，它反复调用 @ref{69d,,timeit()} ，以便总时间 >= 0.2 秒，返回最终（循环次数，循环所用的时间）。它调用 @ref{69d,,timeit()} 的次数以序列 1, 2, 5, 10, 20, 50, ... 递增，直到所用的时间至少为0.2秒。

如果给出 @emph{callback} 并且不是 @code{None} ，则在每次试验后将使用两个参数调用它： @code{callback(number, time_taken)} 。


3.6 新版功能.

@end deffn

@geindex repeat() (timeit.Timer 方法)
@anchor{library/timeit timeit Timer repeat}@anchor{3611}
@deffn {方法} repeat (repeat=5, number=1000000)

调用 @ref{69d,,timeit()} 几次。

这是一个方便的函数，它反复调用 @ref{69d,,timeit()} ，返回结果列表。第一个参数指定调用 @ref{69d,,timeit()} 的次数。第二个参数指定 @ref{69d,,timeit()} 的 @emph{number} 参数。

@cartouche
@quotation 注解 
从结果向量计算并报告平均值和标准差这些是很诱人的。但是，这不是很有用。在典型情况下，最低值给出了机器运行给定代码段的速度的下限；结果向量中较高的值通常不是由Python的速度变化引起的，而是由于其他过程干扰你的计时准确性。所以结果的 @ref{900,,min()} 可能是你应该感兴趣的唯一数字。之后，你应该看看整个向量并应用常识而不是统计。
@end quotation
@end cartouche


在 3.7 版更改: @emph{repeat} 的默认值由 3 更改为 5 。

@end deffn

@geindex print_exc() (timeit.Timer 方法)
@anchor{library/timeit timeit Timer print_exc}@anchor{3613}
@deffn {方法} print_exc (file=None)

帮助程序从计时代码中打印回溯。

典型使用:

@example
t = Timer(...)       # outside the try/except
try:
    t.timeit(...)    # or t.repeat(...)
except Exception:
    t.print_exc()
@end example

与标准回溯相比，优势在于将显示已编译模板中的源行。可选的 @emph{file} 参数指向发送回溯的位置；它默认为 @ref{1eb,,sys.stderr} 。
@end deffn
@end deffn

@node 命令行界面<6>,示例<40>,Python 接口,timeit --- 测量小代码片段的执行时间
@anchor{library/timeit command-line-interface}@anchor{3614}@anchor{library/timeit timeit-command-line-interface}@anchor{360a}
@subsubsection 命令行界面


从命令行调用程序时，使用以下表单:

@example
python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...]
@end example

如果了解以下选项：

@geindex timeit command line option; -n N
@geindex timeit command line option; --number=N
@anchor{library/timeit cmdoption-timeit-n}@anchor{3615}
@deffn {程序选项} @w{-}n N, @w{-}@w{-}number=N

执行 '语句' 多少次
@end deffn

@geindex timeit command line option; -r N
@geindex timeit command line option; --repeat=N
@anchor{library/timeit cmdoption-timeit-r}@anchor{3616}
@deffn {程序选项} @w{-}r N, @w{-}@w{-}repeat=N

重复计时器的次数（默认为5）
@end deffn

@geindex timeit command line option; -s S
@geindex timeit command line option; --setup=S
@anchor{library/timeit cmdoption-timeit-s}@anchor{3617}
@deffn {程序选项} @w{-}s S, @w{-}@w{-}setup=S

最初要执行一次的语句（默认为 @code{pass} ）
@end deffn

@geindex timeit command line option; -p
@geindex timeit command line option; --process
@anchor{library/timeit cmdoption-timeit-p}@anchor{3618}
@deffn {程序选项} @w{-}p, @w{-}@w{-}process

测量进程时间，而不是 wallclock 时间，使用 @ref{3d5,,time.process_time()} 而不是 @ref{3d4,,time.perf_counter()} ，这是默认值


3.3 新版功能.

@end deffn

@geindex timeit command line option; -u
@geindex timeit command line option; --unit=U
@anchor{library/timeit cmdoption-timeit-u}@anchor{3619}
@deffn {程序选项} @w{-}u, @w{-}@w{-}unit=U

指定定时器输出的时间单位；可以选择 nsec，usec，msec或sec


3.5 新版功能.

@end deffn

@geindex timeit command line option; -v
@geindex timeit command line option; --verbose
@anchor{library/timeit cmdoption-timeit-v}@anchor{361a}
@deffn {程序选项} @w{-}v, @w{-}@w{-}verbose

打印原始计时结果；重复更多位数精度
@end deffn

@geindex timeit command line option; -h
@geindex timeit command line option; --help
@anchor{library/timeit cmdoption-timeit-h}@anchor{361b}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

打印一条简短的使用信息并退出
@end deffn

可以通过将每一行指定为单独的语句参数来给出多行语句；通过在引号中包含参数并使用前导空格可以缩进行。多个 @ref{3617,,-s} 选项的处理方式相似。

如果未给出 @ref{3615,,-n}，则会通过尝试按序列 1, 2, 5, 10, 20, 50, ... 递增的数值来计算合适的循环次数，直到总计时间至少为 0.2 秒。

@ref{3612,,default_timer()} 测量可能受到在同一台机器上运行的其他程序的影响，因此在需要精确计时时最好的做法是重复几次计时并使用最佳时间。 @ref{3616,,-r} 选项对此有利；在大多数情况下，默认的 5 次重复可能就足够了。 你可以使用 @ref{3d5,,time.process_time()} 来测量CPU时间。

@cartouche
@quotation 注解 
执行 pass 语句会产生一定的基线开销。这里的代码不会试图隐藏它，但你应该知道它。可以通过不带参数调用程序来测量基线开销，并且Python版本之间可能会有所不同。
@end quotation
@end cartouche

@node 示例<40>,,命令行界面<6>,timeit --- 测量小代码片段的执行时间
@anchor{library/timeit examples}@anchor{361c}@anchor{library/timeit timeit-examples}@anchor{360d}
@subsubsection 示例


可以提供一个在开头只执行一次的 setup 语句：

@example
$ python -m timeit -s 'text = "sample string"; char = "g"'  'char in text'
5000000 loops, best of 5: 0.0877 usec per loop
$ python -m timeit -s 'text = "sample string"; char = "g"'  'text.find(char)'
1000000 loops, best of 5: 0.342 usec per loop
@end example

在输出信息中，共有三个字段。 首先是 loop count，它告诉你每个计时循环重复运行了多少次语句体。 然后是 repetition count ('best of 5')，它告诉你计时循环重复了多少次，最后是语句体在计时循环重复中最好的平均耗时。 即最快一次重复的耗时除以循环计数。

@example
>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.41440500499993504
>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
1.7246671520006203
@end example

使用 @ref{360f,,Timer} 类及其方法可以完成同样的操作:

@example
>>> import timeit
>>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
>>> t.timeit()
0.3955516149999312
>>> t.repeat()
[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]
@end example

以下示例显示如何计算包含多行的表达式。 在这里我们对比使用 @ref{553,,hasattr()} 与 @ref{e3f,,try}/@ref{c19,,except} 的开销来测试缺失与提供对象属性:

@example
$ python -m timeit 'try:' '  str.__bool__' 'except AttributeError:' '  pass'
20000 loops, best of 5: 15.7 usec per loop
$ python -m timeit 'if hasattr(str, "__bool__"): pass'
50000 loops, best of 5: 4.26 usec per loop

$ python -m timeit 'try:' '  int.__bool__' 'except AttributeError:' '  pass'
200000 loops, best of 5: 1.43 usec per loop
$ python -m timeit 'if hasattr(int, "__bool__"): pass'
100000 loops, best of 5: 2.23 usec per loop
@end example

@example
>>> import timeit
>>> # attribute is missing
>>> s = """\
... try:
...     str.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.9138244460009446
>>> s = "if hasattr(str, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.5829014980008651
>>>
>>> # attribute is present
>>> s = """\
... try:
...     int.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.04215312199994514
>>> s = "if hasattr(int, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.08588060699912603
@end example

要让 @ref{10d,,timeit} 模块访问你定义的函数，你可以传递一个包含 import 语句的 @emph{setup} 参数:

@example
def test():
    """Stupid test function"""
    L = [i for i in range(100)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))
@end example

另一种选择是将 @ref{fa1,,globals()} 传递给 @emph{globals} 参数，这将导致代码在当前的全局命名空间中执行。这比单独指定 import 更方便

@example
def f(x):
    return x**2
def g(x):
    return x**4
def h(x):
    return x**8

import timeit
print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))
@end example

@node trace --- 跟踪Python语句执行,tracemalloc --- 跟踪内存分配,timeit --- 测量小代码片段的执行时间,调试和分析
@anchor{library/trace doc}@anchor{361d}@anchor{library/trace module-trace}@anchor{11b}@anchor{library/trace trace-trace-or-track-python-statement-execution}@anchor{361e}
@subsection @code{trace} --- 跟踪Python语句执行


@geindex trace (模块)

@strong{源代码:} Lib/trace.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/trace.py}


__________________________________________________________________


模块 @ref{11b,,trace} module 允许你跟踪程序的执行过程，生成带注释的语句覆盖率列表，打印调用/被调用关系以及列出在程序运行期间执行过的函数。可以在其他程序或者命令行中使用它


@subsubheading 参见



@table @asis

@item Coverage.py@footnote{https://coverage.readthedocs.io/}

流行的第三方代码覆盖工具，可输出 HTML ，并提供分支覆盖等高级功能。
@end table


@menu
* 命令行用法:: 
* 编程接口:: 

@end menu

@node 命令行用法,编程接口,,trace --- 跟踪Python语句执行
@anchor{library/trace command-line-usage}@anchor{361f}@anchor{library/trace trace-cli}@anchor{3620}
@subsubsection 命令行用法


@ref{11b,,trace} 模块可由命令行调用。用法如此简单：

@example
python -m trace --count -C . somefile.py ...
@end example

上述命令将执行 @code{somefile.py} ，并在当前目录生成执行期间所有已导入 Python 模块的带注释列表。

@geindex trace command line option; --help
@anchor{library/trace cmdoption-trace-help}@anchor{3621}
@deffn {程序选项} @w{-}@w{-}help

显示用法并退出。
@end deffn

@geindex trace command line option; --version
@anchor{library/trace cmdoption-trace-version}@anchor{3622}
@deffn {程序选项} @w{-}@w{-}version

显示模块版本并退出。
@end deffn


3.8 新版功能: 加入了 @code{--module} 选项，允许运行可执行模块。


@menu
* 主要的可选参数:: 
* 修饰器:: 
* 过滤器:: 

@end menu

@node 主要的可选参数,修饰器,,命令行用法
@anchor{library/trace main-options}@anchor{3623}
@subsubsection 主要的可选参数


在调用 @ref{11b,,trace} 时，至少须指定以下可选参数之一。 @ref{3624,,-listfuncs} 与 @ref{3625,,-trace} 、 @ref{3626,,-count} 相互排斥。如果给出 @ref{3624,,--listfuncs}，就再不会接受 @ref{3626,,--count} 和 @ref{3625,,--trace} ，反之亦然。

@geindex trace command line option; -c
@geindex trace command line option; --count
@anchor{library/trace cmdoption-trace-c}@anchor{3626}
@deffn {程序选项} @w{-}c, @w{-}@w{-}count

在程序完成时生成一组带有注解的列表文件，显示每个语句被执行的次数。 参见下面的 @ref{3627,,-coverdir} 、@ref{3628,,-file} 和 @ref{3629,,-no-report}。
@end deffn

@geindex trace command line option; -t
@geindex trace command line option; --trace
@anchor{library/trace cmdoption-trace-t}@anchor{3625}
@deffn {程序选项} @w{-}t, @w{-}@w{-}trace

执行时显示行。
@end deffn

@geindex trace command line option; -l
@geindex trace command line option; --listfuncs
@anchor{library/trace cmdoption-trace-l}@anchor{3624}
@deffn {程序选项} @w{-}l, @w{-}@w{-}listfuncs

显示程序运行时执行到的函数。
@end deffn

@geindex trace command line option; -r
@geindex trace command line option; --report
@anchor{library/trace cmdoption-trace-r}@anchor{362a}
@deffn {程序选项} @w{-}r, @w{-}@w{-}report

由之前用了 @ref{3626,,--count} 和 @ref{3628,,--file} 运行的程序产生一个带有注解的报表。 不会执行代码。
@end deffn

@geindex trace command line option; -T
@geindex trace command line option; --trackcalls
@anchor{library/trace cmdoption-trace-trackcalls}@anchor{362b}
@deffn {程序选项} @w{-}T, @w{-}@w{-}trackcalls

显示程序运行时暴露出来的调用关系。
@end deffn

@node 修饰器,过滤器,主要的可选参数,命令行用法
@anchor{library/trace modifiers}@anchor{362c}
@subsubsection 修饰器


@geindex trace command line option; -f
@geindex trace command line option; --file=<file>
@anchor{library/trace cmdoption-trace-f}@anchor{3628}
@deffn {程序选项} @w{-}f, @w{-}@w{-}file=<file>

用于累计多次跟踪运行计数的文件名。应与 @ref{3626,,--count} 一起使用。
@end deffn

@geindex trace command line option; -C
@geindex trace command line option; --coverdir=<dir>
@anchor{library/trace cmdoption-trace-coverdir}@anchor{3627}
@deffn {程序选项} @w{-}C, @w{-}@w{-}coverdir=<dir>

报表文件的所在目录。@code{package.module} 的覆盖率报表将被写入文件 @code{@emph{dir}/@emph{package}/@emph{module}.cover}。
@end deffn

@geindex trace command line option; -m
@geindex trace command line option; --missing
@anchor{library/trace cmdoption-trace-m}@anchor{362d}
@deffn {程序选项} @w{-}m, @w{-}@w{-}missing

生成带注解的报表时，用 @code{>>>>>>} 标记未执行的行。
@end deffn

@geindex trace command line option; -s
@geindex trace command line option; --summary
@anchor{library/trace cmdoption-trace-s}@anchor{362e}
@deffn {程序选项} @w{-}s, @w{-}@w{-}summary

在用到 @ref{3626,,--count} 或 @ref{362a,,--report} 时，将每个文件的简短摘要写到 stdout。
@end deffn

@geindex trace command line option; -R
@geindex trace command line option; --no-report
@anchor{library/trace cmdoption-trace-no-report}@anchor{3629}
@deffn {程序选项} @w{-}R, @w{-}@w{-}no@w{-}report

不生成带注解的报表。如果打算用 @ref{3626,,--count} 执行多次运行，然后在最后产生一组带注解的报表，该选项就很有用。
@end deffn

@geindex trace command line option; -g
@geindex trace command line option; --timing
@anchor{library/trace cmdoption-trace-g}@anchor{362f}
@deffn {程序选项} @w{-}g, @w{-}@w{-}timing

在每一行前面加上时间，自程序运行算起。只在跟踪时有用。
@end deffn

@node 过滤器,,修饰器,命令行用法
@anchor{library/trace filters}@anchor{3630}
@subsubsection 过滤器


以下参数可重复多次。

@geindex trace command line option; --ignore-module=<mod>
@anchor{library/trace cmdoption-trace-ignore-module}@anchor{3631}
@deffn {程序选项} @w{-}@w{-}ignore@w{-}module=<mod>

忽略给出的模块名及其子模块（若为包）。参数可为逗号分隔的名称列表。
@end deffn

@geindex trace command line option; --ignore-dir=<dir>
@anchor{library/trace cmdoption-trace-ignore-dir}@anchor{3632}
@deffn {程序选项} @w{-}@w{-}ignore@w{-}dir=<dir>

忽略指定目录及其子目录下的所有模块和包。参数可为 @ref{14b6,,os.pathsep} 分隔的目录列表。
@end deffn

@node 编程接口,,命令行用法,trace --- 跟踪Python语句执行
@anchor{library/trace programmatic-interface}@anchor{3633}@anchor{library/trace trace-api}@anchor{3634}
@subsubsection 编程接口


@geindex Trace (trace 中的类)
@anchor{library/trace trace Trace}@anchor{3635}
@deffn {类} trace.Trace (count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)

创建一个对象来跟踪单个语句或表达式的执行。所有参数均为选填。 @emph{count} 可对行号计数。 @emph{trace} 启用单行执行跟踪。 @emph{countfuncs} 可列出运行过程中调用的函数。 @emph{countcallers} 可跟踪调用关系。 @emph{ignoremods} 是要忽略的模块或包的列表。@emph{ignoredirs} 是要忽略的模块或包的目录列表。 @emph{infile} 是个文件名，从该文件中读取存储的计数信息。 @emph{outfile} 是用来写入最新计数信息的文件名。 @emph{timing} 可以显示相对于跟踪开始时间的时间戳。

@geindex run() (trace.Trace 方法)
@anchor{library/trace trace Trace run}@anchor{3636}
@deffn {方法} run (cmd)

执行命令，并根据当前跟踪参数从执行过程中收集统计数据。 @emph{cmd} 必须为字符串或 code 对象，可供传入 @ref{d14,,exec()}。
@end deffn

@geindex runctx() (trace.Trace 方法)
@anchor{library/trace trace Trace runctx}@anchor{3637}
@deffn {方法} runctx (cmd, globals=None, locals=None)

在定义的全局和局部环境中，执行命令并收集当前跟踪参数下的执行统计数据。若没有定义 @emph{globals} 和 @emph{locals} ，则默认为空字典。
@end deffn

@geindex runfunc() (trace.Trace 方法)
@anchor{library/trace trace Trace runfunc}@anchor{3cb}
@deffn {方法} runfunc (func, /, *args, **kwds)

在 @ref{3635,,Trace} 对象的控制下，用给定的参数调用 @emph{func}，并采用当前的跟踪参数。
@end deffn

@geindex results() (trace.Trace 方法)
@anchor{library/trace trace Trace results}@anchor{3638}
@deffn {方法} results ()

返回一个 @ref{3639,,CoverageResults} 对象，包含之前对指定 @ref{3635,,Trace} 实例调用 @code{run}、@code{runctx} 和 @code{runfunc} 的累积结果。 累积的跟踪结果不会重置。
@end deffn
@end deffn

@geindex CoverageResults (trace 中的类)
@anchor{library/trace trace CoverageResults}@anchor{3639}
@deffn {类} trace.CoverageResults

用于覆盖跟踪结果的容器，由 @ref{3638,,Trace.results()} 创建。用户不应直接去创建。

@geindex update() (trace.CoverageResults 方法)
@anchor{library/trace trace CoverageResults update}@anchor{363a}
@deffn {方法} update (other)

从另一个 @ref{3639,,CoverageResults} 对象中合并跟踪数据。
@end deffn

@geindex write_results() (trace.CoverageResults 方法)
@anchor{library/trace trace CoverageResults write_results}@anchor{363b}
@deffn {方法} write_results (show_missing=True, summary=False, coverdir=None)

写入代码覆盖结果。设置 @emph{show_missing} 可显示未命中的行。设置*summary* 可在输出中包含每个模块的覆盖率摘要信息。 @emph{coverdir} 可指定覆盖率结果文件的输出目录，为  @code{None} 则结果将置于源文件所在目录中。
@end deffn
@end deffn

以下例子简单演示了编程接口的用法：

@example
import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")
@end example

@node tracemalloc --- 跟踪内存分配,,trace --- 跟踪Python语句执行,调试和分析
@anchor{library/tracemalloc doc}@anchor{363c}@anchor{library/tracemalloc module-tracemalloc}@anchor{11d}@anchor{library/tracemalloc tracemalloc-trace-memory-allocations}@anchor{363d}
@subsection @code{tracemalloc} --- 跟踪内存分配


@geindex tracemalloc (模块)


3.4 新版功能.


@strong{源代码：} Lib/tracemalloc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tracemalloc.py}


__________________________________________________________________


tracemalloc 模块是一个用于对 python 已申请的内存块进行debug的工具。它能提供以下信息:


@itemize *

@item 
定位对象分配内存的位置

@item 
按文件、按行统计python的内存块分配情况: 总大小、块的数量以及块平均大小。

@item 
对比两个内存快照的差异，以便排查内存泄漏
@end itemize

To trace most memory blocks allocated by Python, the module should be started
as early as possible by setting the 
@geindex PYTHONTRACEMALLOC
@geindex 环境变量; PYTHONTRACEMALLOC
@ref{14bc,,PYTHONTRACEMALLOC} environment
variable to @code{1}, or by using @ref{297,,-X} @code{tracemalloc} command line
option. The @ref{14b1,,tracemalloc.start()} function can be called at runtime to
start tracing Python memory allocations.

By default, a trace of an allocated memory block only stores the most recent
frame (1 frame). To store 25 frames at startup: set the
@geindex PYTHONTRACEMALLOC
@geindex 环境变量; PYTHONTRACEMALLOC
@ref{14bc,,PYTHONTRACEMALLOC} environment variable to @code{25}, or use the
@ref{297,,-X} @code{tracemalloc=25} command line option.

@menu
* 示例: 示例<41>. 
* API:: 

@end menu

@node 示例<41>,API,,tracemalloc --- 跟踪内存分配
@anchor{library/tracemalloc examples}@anchor{363e}
@subsubsection 示例


@menu
* 显示前10项:: 
* 计算差异:: 
* 获取一个内存块的溯源:: 
* Pretty top:: 

@end menu

@node 显示前10项,计算差异,,示例<41>
@anchor{library/tracemalloc display-the-top-10}@anchor{363f}
@subsubsection 显示前10项


显示内存分配最多的10个文件：

@example
import tracemalloc

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

print("[ Top 10 ]")
for stat in top_stats[:10]:
    print(stat)
@end example

Python测试套件的输出示例：

@example
[ Top 10 ]
<frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
<frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
/usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
/usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
/usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
/usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
<frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
<frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
<string>:5: size=49.7 KiB, count=148, average=344 B
/usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB
@end example

We can see that Python loaded @code{4855 KiB} data (bytecode and constants) from
modules and that the @ref{1d,,collections} module allocated @code{244 KiB} to build
@ref{1a1,,namedtuple} types.

更多选项，请参见 @ref{3640,,Snapshot.statistics()}

@node 计算差异,获取一个内存块的溯源,显示前10项,示例<41>
@anchor{library/tracemalloc compute-differences}@anchor{3641}
@subsubsection 计算差异


获取两个快照并显示差异：

@example
import tracemalloc
tracemalloc.start()
# ... start your application ...

snapshot1 = tracemalloc.take_snapshot()
# ... call the function leaking memory ...
snapshot2 = tracemalloc.take_snapshot()

top_stats = snapshot2.compare_to(snapshot1, 'lineno')

print("[ Top 10 differences ]")
for stat in top_stats[:10]:
    print(stat)
@end example

Example of output before/after running some tests of the Python test suite:

@example
[ Top 10 differences ]
<frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
/usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
/usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
<frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
/usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
/usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
/usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
/usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
/usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
/usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B
@end example

We can see that Python has loaded @code{8173 KiB} of module data (bytecode and
constants), and that this is @code{4428 KiB} more than had been loaded before the
tests, when the previous snapshot was taken. Similarly, the @ref{a8,,linecache}
module has cached @code{940 KiB} of Python source code to format tracebacks, all
of it since the previous snapshot.

If the system has little free memory, snapshots can be written on disk using
the @ref{3642,,Snapshot.dump()} method to analyze the snapshot offline. Then use the
@ref{3643,,Snapshot.load()} method reload the snapshot.

@node 获取一个内存块的溯源,Pretty top,计算差异,示例<41>
@anchor{library/tracemalloc get-the-traceback-of-a-memory-block}@anchor{3644}
@subsubsection 获取一个内存块的溯源


一段找出程序中最大内存块溯源的代码:

@example
import tracemalloc

# Store 25 frames
tracemalloc.start(25)

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('traceback')

# pick the biggest memory block
stat = top_stats[0]
print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
for line in stat.traceback.format():
    print(line)
@end example

一段Python单元测试的输出案例(限制最大25层堆栈)

@example
903 memory blocks: 870.1 KiB
  File "<frozen importlib._bootstrap>", line 716
  File "<frozen importlib._bootstrap>", line 1036
  File "<frozen importlib._bootstrap>", line 934
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/doctest.py", line 101
    import pdb
  File "<frozen importlib._bootstrap>", line 284
  File "<frozen importlib._bootstrap>", line 938
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/test/support/__init__.py", line 1728
    import doctest
  File "/usr/lib/python3.4/test/test_pickletools.py", line 21
    support.run_doctest(pickletools)
  File "/usr/lib/python3.4/test/regrtest.py", line 1276
    test_runner()
  File "/usr/lib/python3.4/test/regrtest.py", line 976
    display_failure=not verbose)
  File "/usr/lib/python3.4/test/regrtest.py", line 761
    match_tests=ns.match_tests)
  File "/usr/lib/python3.4/test/regrtest.py", line 1563
    main()
  File "/usr/lib/python3.4/test/__main__.py", line 3
    regrtest.main_in_temp_cwd()
  File "/usr/lib/python3.4/runpy.py", line 73
    exec(code, run_globals)
  File "/usr/lib/python3.4/runpy.py", line 160
    "__main__", fname, loader, pkg_name)
@end example

We can see that the most memory was allocated in the @ref{9a,,importlib} module to
load data (bytecode and constants) from modules: @code{870.1 KiB}. The traceback is
where the @ref{9a,,importlib} loaded data most recently: on the @code{import pdb}
line of the @ref{66,,doctest} module. The traceback may change if a new module is
loaded.

@node Pretty top,,获取一个内存块的溯源,示例<41>
@anchor{library/tracemalloc pretty-top}@anchor{3645}
@subsubsection Pretty top


Code to display the 10 lines allocating the most memory with a pretty output,
ignoring @code{<frozen importlib._bootstrap>} and @code{<unknown>} files:

@example
import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=10):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        print("#%s: %s:%s: %.1f KiB"
              % (index, frame.filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)
@end example

Python测试套件的输出示例：

@example
Top 10 lines
#1: Lib/base64.py:414: 419.8 KiB
    _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
#2: Lib/base64.py:306: 419.8 KiB
    _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
#3: collections/__init__.py:368: 293.6 KiB
    exec(class_definition, namespace)
#4: Lib/abc.py:133: 115.2 KiB
    cls = super().__new__(mcls, name, bases, namespace)
#5: unittest/case.py:574: 103.1 KiB
    testMethod()
#6: Lib/linecache.py:127: 95.4 KiB
    lines = fp.readlines()
#7: urllib/parse.py:476: 71.8 KiB
    for a in _hexdig for b in _hexdig@}
#8: <string>:5: 62.0 KiB
#9: Lib/_weakrefset.py:37: 60.0 KiB
    self.data = set()
#10: Lib/base64.py:142: 59.8 KiB
    _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
6220 other: 3602.8 KiB
Total allocated size: 5303.1 KiB
@end example

更多选项，请参见 @ref{3640,,Snapshot.statistics()}

@menu
* Record the current and peak size of all traced memory blocks:: 

@end menu

@node Record the current and peak size of all traced memory blocks,,,Pretty top
@anchor{library/tracemalloc record-the-current-and-peak-size-of-all-traced-memory-blocks}@anchor{3646}
@subsubsection Record the current and peak size of all traced memory blocks


The following code computes two sums like @code{0 + 1 + 2 + ...} inefficiently, by
creating a list of those numbers. This list consumes a lot of memory
temporarily. We can use @ref{3647,,get_traced_memory()} and @ref{1ed,,reset_peak()} to
observe the small memory usage after the sum is computed as well as the peak
memory usage during the computations:

@example
import tracemalloc

tracemalloc.start()

# Example code: compute a sum with a large temporary list
large_sum = sum(list(range(100000)))

first_size, first_peak = tracemalloc.get_traced_memory()

tracemalloc.reset_peak()

# Example code: compute a sum with a small temporary list
small_sum = sum(list(range(1000)))

second_size, second_peak = tracemalloc.get_traced_memory()

print(f"@{first_size=@}, @{first_peak=@}")
print(f"@{second_size=@}, @{second_peak=@}")
@end example

输出:

@example
first_size=664, first_peak=3592984
second_size=804, second_peak=29704
@end example

Using @ref{1ed,,reset_peak()} ensured we could accurately record the peak during the
computation of @code{small_sum}, even though it is much smaller than the overall
peak size of memory blocks since the @ref{14b1,,start()} call. Without the call to
@ref{1ed,,reset_peak()}, @code{second_peak} would still be the peak from the
computation @code{large_sum} (that is, equal to @code{first_peak}). In this case,
both peaks are much higher than the final memory usage, and which suggests we
could optimise (by removing the unnecessary call to @ref{1f9,,list}, and writing
@code{sum(range(...))}).

@node API,,示例<41>,tracemalloc --- 跟踪内存分配
@anchor{library/tracemalloc api}@anchor{3648}
@subsubsection API


@menu
* 函数: 函数<9>. 
* 域过滤器:: 
* 过滤器: 过滤器<2>. 
* Frame:: 
* 快照:: 
* 统计:: 
* StatisticDiff:: 
* 跟踪:: 
* 回溯:: 

@end menu

@node 函数<9>,域过滤器,,API
@anchor{library/tracemalloc functions}@anchor{3649}
@subsubsection 函数


@geindex clear_traces() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc clear_traces}@anchor{364a}
@deffn {函数} tracemalloc.clear_traces ()

清空 Python 所分配的内存块的追踪数据。

另见 @ref{364b,,stop()}.
@end deffn

@geindex get_object_traceback() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc get_object_traceback}@anchor{12da}
@deffn {函数} tracemalloc.get_object_traceback (obj)

Get the traceback where the Python object @emph{obj} was allocated.
Return a @ref{50c,,Traceback} instance, or @code{None} if the @ref{11d,,tracemalloc}
module is not tracing memory allocations or did not trace the allocation of
the object.

See also @ref{1001,,gc.get_referrers()} and @ref{364c,,sys.getsizeof()} functions.
@end deffn

@geindex get_traceback_limit() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc get_traceback_limit}@anchor{364d}
@deffn {函数} tracemalloc.get_traceback_limit ()

Get the maximum number of frames stored in the traceback of a trace.

The @ref{11d,,tracemalloc} module must be tracing memory allocations to
get the limit, otherwise an exception is raised.

The limit is set by the @ref{14b1,,start()} function.
@end deffn

@geindex get_traced_memory() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc get_traced_memory}@anchor{3647}
@deffn {函数} tracemalloc.get_traced_memory ()

Get the current size and peak size of memory blocks traced by the
@ref{11d,,tracemalloc} module as a tuple: @code{(current: int, peak: int)}.
@end deffn

@geindex reset_peak() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc reset_peak}@anchor{1ed}
@deffn {函数} tracemalloc.reset_peak ()

Set the peak size of memory blocks traced by the @ref{11d,,tracemalloc} module
to the current size.

Do nothing if the @ref{11d,,tracemalloc} module is not tracing memory
allocations.

This function only modifies the recorded peak size, and does not modify or
clear any traces, unlike @ref{364a,,clear_traces()}. Snapshots taken with
@ref{364e,,take_snapshot()} before a call to @ref{1ed,,reset_peak()} can be
meaningfully compared to snapshots taken after the call.

See also @ref{3647,,get_traced_memory()}.


3.9 新版功能.

@end deffn

@geindex get_tracemalloc_memory() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc get_tracemalloc_memory}@anchor{364f}
@deffn {函数} tracemalloc.get_tracemalloc_memory ()

Get the memory usage in bytes of the @ref{11d,,tracemalloc} module used to store
traces of memory blocks.
Return an @ref{205,,int}.
@end deffn

@geindex is_tracing() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc is_tracing}@anchor{3650}
@deffn {函数} tracemalloc.is_tracing ()

@code{True} if the @ref{11d,,tracemalloc} module is tracing Python memory
allocations, @code{False} otherwise.

See also @ref{14b1,,start()} and @ref{364b,,stop()} functions.
@end deffn

@geindex start() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc start}@anchor{14b1}
@deffn {函数} tracemalloc.start (nframe: int=1)

Start tracing Python memory allocations: install hooks on Python memory
allocators. Collected tracebacks of traces will be limited to @emph{nframe}
frames. By default, a trace of a memory block only stores the most recent
frame: the limit is @code{1}. @emph{nframe} must be greater or equal to @code{1}.

You can still read the original number of total frames that composed the
traceback by looking at the @ref{3651,,Traceback.total_nframe} attribute.

Storing more than @code{1} frame is only useful to compute statistics grouped
by @code{'traceback'} or to compute cumulative statistics: see the
@ref{3652,,Snapshot.compare_to()} and @ref{3640,,Snapshot.statistics()} methods.

Storing more frames increases the memory and CPU overhead of the
@ref{11d,,tracemalloc} module. Use the @ref{364f,,get_tracemalloc_memory()} function
to measure how much memory is used by the @ref{11d,,tracemalloc} module.

The 
@geindex PYTHONTRACEMALLOC
@geindex 环境变量; PYTHONTRACEMALLOC
@ref{14bc,,PYTHONTRACEMALLOC} environment variable
(@code{PYTHONTRACEMALLOC=NFRAME}) and the @ref{297,,-X} @code{tracemalloc=NFRAME}
command line option can be used to start tracing at startup.

See also @ref{364b,,stop()}, @ref{3650,,is_tracing()} and @ref{364d,,get_traceback_limit()}
functions.
@end deffn

@geindex stop() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc stop}@anchor{364b}
@deffn {函数} tracemalloc.stop ()

Stop tracing Python memory allocations: uninstall hooks on Python memory
allocators. Also clears all previously collected traces of memory blocks
allocated by Python.

Call @ref{364e,,take_snapshot()} function to take a snapshot of traces before
clearing them.

See also @ref{14b1,,start()}, @ref{3650,,is_tracing()} and @ref{364a,,clear_traces()}
functions.
@end deffn

@geindex take_snapshot() (在 tracemalloc 模块中)
@anchor{library/tracemalloc tracemalloc take_snapshot}@anchor{364e}
@deffn {函数} tracemalloc.take_snapshot ()

Take a snapshot of traces of memory blocks allocated by Python. Return a new
@ref{3653,,Snapshot} instance.

The snapshot does not include memory blocks allocated before the
@ref{11d,,tracemalloc} module started to trace memory allocations.

Tracebacks of traces are limited to @ref{364d,,get_traceback_limit()} frames. Use
the @emph{nframe} parameter of the @ref{14b1,,start()} function to store more frames.

The @ref{11d,,tracemalloc} module must be tracing memory allocations to take a
snapshot, see the @ref{14b1,,start()} function.

See also the @ref{12da,,get_object_traceback()} function.
@end deffn

@node 域过滤器,过滤器<2>,函数<9>,API
@anchor{library/tracemalloc domainfilter}@anchor{3654}
@subsubsection 域过滤器


@geindex DomainFilter (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc DomainFilter}@anchor{6a1}
@deffn {类} tracemalloc.DomainFilter (inclusive: bool, domain: int)

Filter traces of memory blocks by their address space (domain).


3.6 新版功能.


@geindex inclusive (tracemalloc.DomainFilter 属性)
@anchor{library/tracemalloc tracemalloc DomainFilter inclusive}@anchor{3655}
@deffn {属性} inclusive

If @emph{inclusive} is @code{True} (include), match memory blocks allocated
in the address space @ref{3656,,domain}.

If @emph{inclusive} is @code{False} (exclude), match memory blocks not allocated
in the address space @ref{3656,,domain}.
@end deffn

@geindex domain (tracemalloc.DomainFilter 属性)
@anchor{library/tracemalloc tracemalloc DomainFilter domain}@anchor{3656}
@deffn {属性} domain

Address space of a memory block (@code{int}). Read-only property.
@end deffn
@end deffn

@node 过滤器<2>,Frame,域过滤器,API
@anchor{library/tracemalloc filter}@anchor{3657}
@subsubsection 过滤器


@geindex Filter (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Filter}@anchor{3658}
@deffn {类} tracemalloc.Filter (inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)

对内存块的跟踪进行筛选。

See the @ref{1e1b,,fnmatch.fnmatch()} function for the syntax of
@emph{filename_pattern}. The @code{'.pyc'} file extension is
replaced with @code{'.py'}.

示例：


@itemize *

@item 
@code{Filter(True, subprocess.__file__)} 只包括 @ref{f9,,subprocess} 模块的追踪数据

@item 
@code{Filter(False, tracemalloc.__file__)} 排除了 @ref{11d,,tracemalloc} 模块的追踪数据

@item 
@code{Filter(False, "<unknown>")} 排除了空的回溯信息
@end itemize


在 3.5 版更改: @code{'.pyo'} 文件扩展名不会再被替换为 @code{'.py'}。



在 3.6 版更改: 增加了 @ref{3659,,domain} 属性。


@geindex domain (tracemalloc.Filter 属性)
@anchor{library/tracemalloc tracemalloc Filter domain}@anchor{3659}
@deffn {属性} domain

Address space of a memory block (@code{int} or @code{None}).

tracemalloc uses the domain @code{0} to trace memory allocations made by
Python. C extensions can use other domains to trace other resources.
@end deffn

@geindex inclusive (tracemalloc.Filter 属性)
@anchor{library/tracemalloc tracemalloc Filter inclusive}@anchor{365a}
@deffn {属性} inclusive

If @emph{inclusive} is @code{True} (include), only match memory blocks allocated
in a file with a name matching @ref{365b,,filename_pattern} at line number
@ref{365c,,lineno}.

If @emph{inclusive} is @code{False} (exclude), ignore memory blocks allocated in
a file with a name matching @ref{365b,,filename_pattern} at line number
@ref{365c,,lineno}.
@end deffn

@geindex lineno (tracemalloc.Filter 属性)
@anchor{library/tracemalloc tracemalloc Filter lineno}@anchor{365c}
@deffn {属性} lineno

Line number (@code{int}) of the filter. If @emph{lineno} is @code{None}, the filter
matches any line number.
@end deffn

@geindex filename_pattern (tracemalloc.Filter 属性)
@anchor{library/tracemalloc tracemalloc Filter filename_pattern}@anchor{365b}
@deffn {属性} filename_pattern

Filename pattern of the filter (@code{str}). Read-only property.
@end deffn

@geindex all_frames (tracemalloc.Filter 属性)
@anchor{library/tracemalloc tracemalloc Filter all_frames}@anchor{365d}
@deffn {属性} all_frames

If @emph{all_frames} is @code{True}, all frames of the traceback are checked. If
@emph{all_frames} is @code{False}, only the most recent frame is checked.

This attribute has no effect if the traceback limit is @code{1}.  See the
@ref{364d,,get_traceback_limit()} function and @ref{365e,,Snapshot.traceback_limit}
attribute.
@end deffn
@end deffn

@node Frame,快照,过滤器<2>,API
@anchor{library/tracemalloc frame}@anchor{365f}
@subsubsection Frame


@geindex Frame (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Frame}@anchor{3660}
@deffn {类} tracemalloc.Frame

Frame of a traceback.

The @ref{50c,,Traceback} class is a sequence of @ref{3660,,Frame} instances.

@geindex filename (tracemalloc.Frame 属性)
@anchor{library/tracemalloc tracemalloc Frame filename}@anchor{3661}
@deffn {属性} filename

文件名（@code{字符串}）
@end deffn

@geindex lineno (tracemalloc.Frame 属性)
@anchor{library/tracemalloc tracemalloc Frame lineno}@anchor{3662}
@deffn {属性} lineno

行号（@code{整形}）
@end deffn
@end deffn

@node 快照,统计,Frame,API
@anchor{library/tracemalloc snapshot}@anchor{3663}
@subsubsection 快照


@geindex Snapshot (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Snapshot}@anchor{3653}
@deffn {类} tracemalloc.Snapshot

Snapshot of traces of memory blocks allocated by Python.

The @ref{364e,,take_snapshot()} function creates a snapshot instance.

@geindex compare_to() (tracemalloc.Snapshot 方法)
@anchor{library/tracemalloc tracemalloc Snapshot compare_to}@anchor{3652}
@deffn {方法} compare_to (old_snapshot: Snapshot, key_type: str, cumulative: bool=False)

Compute the differences with an old snapshot. Get statistics as a sorted
list of @ref{3664,,StatisticDiff} instances grouped by @emph{key_type}.

See the @ref{3640,,Snapshot.statistics()} method for @emph{key_type} and @emph{cumulative}
parameters.

The result is sorted from the biggest to the smallest by: absolute value
of @ref{3665,,StatisticDiff.size_diff}, @ref{3666,,StatisticDiff.size}, absolute
value of @ref{3667,,StatisticDiff.count_diff}, @ref{3668,,Statistic.count} and
then by @ref{3669,,StatisticDiff.traceback}.
@end deffn

@geindex dump() (tracemalloc.Snapshot 方法)
@anchor{library/tracemalloc tracemalloc Snapshot dump}@anchor{3642}
@deffn {方法} dump (filename)

将快照写入文件

使用 @ref{3643,,load()} 重载快照。
@end deffn

@geindex filter_traces() (tracemalloc.Snapshot 方法)
@anchor{library/tracemalloc tracemalloc Snapshot filter_traces}@anchor{366a}
@deffn {方法} filter_traces (filters)

Create a new @ref{3653,,Snapshot} instance with a filtered @ref{366b,,traces}
sequence, @emph{filters} is a list of @ref{6a1,,DomainFilter} and
@ref{3658,,Filter} instances.  If @emph{filters} is an empty list, return a new
@ref{3653,,Snapshot} instance with a copy of the traces.

All inclusive filters are applied at once, a trace is ignored if no
inclusive filters match it. A trace is ignored if at least one exclusive
filter matches it.


在 3.6 版更改: @ref{6a1,,DomainFilter} instances are now also accepted in @emph{filters}.

@end deffn

@geindex load() (tracemalloc.Snapshot 类方法)
@anchor{library/tracemalloc tracemalloc Snapshot load}@anchor{3643}
@deffn {方法} classmethod load (filename)

从文件载入快照。

另见 @ref{3642,,dump()}.
@end deffn

@geindex statistics() (tracemalloc.Snapshot 方法)
@anchor{library/tracemalloc tracemalloc Snapshot statistics}@anchor{3640}
@deffn {方法} statistics (key_type: str, cumulative: bool=False)

获取 @ref{366c,,Statistic} 信息列表，按 @emph{key_type} 分组排序：


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

key_type

@tab

描述

@item

@code{'filename'}

@tab

文件名

@item

@code{'lineno'}

@tab

文件名和行号

@item

@code{'traceback'}

@tab

回溯

@end multitable


If @emph{cumulative} is @code{True}, cumulate size and count of memory blocks of
all frames of the traceback of a trace, not only the most recent frame.
The cumulative mode can only be used with @emph{key_type} equals to
@code{'filename'} and @code{'lineno'}.

The result is sorted from the biggest to the smallest by:
@ref{366d,,Statistic.size}, @ref{3668,,Statistic.count} and then by
@ref{366e,,Statistic.traceback}.
@end deffn

@geindex traceback_limit (tracemalloc.Snapshot 属性)
@anchor{library/tracemalloc tracemalloc Snapshot traceback_limit}@anchor{365e}
@deffn {属性} traceback_limit

Maximum number of frames stored in the traceback of @ref{366b,,traces}:
result of the @ref{364d,,get_traceback_limit()} when the snapshot was taken.
@end deffn

@geindex traces (tracemalloc.Snapshot 属性)
@anchor{library/tracemalloc tracemalloc Snapshot traces}@anchor{366b}
@deffn {属性} traces

Traces of all memory blocks allocated by Python: sequence of
@ref{366f,,Trace} instances.

The sequence has an undefined order. Use the @ref{3640,,Snapshot.statistics()}
method to get a sorted list of statistics.
@end deffn
@end deffn

@node 统计,StatisticDiff,快照,API
@anchor{library/tracemalloc statistic}@anchor{3670}
@subsubsection 统计


@geindex Statistic (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Statistic}@anchor{366c}
@deffn {类} tracemalloc.Statistic

统计内存分配

@ref{3640,,Snapshot.statistics()} 返回 @ref{366c,,Statistic} 实例的列表。.

参见 @ref{3664,,StatisticDiff} 类。

@geindex count (tracemalloc.Statistic 属性)
@anchor{library/tracemalloc tracemalloc Statistic count}@anchor{3668}
@deffn {属性} count

内存块数（@code{整形}）。
@end deffn

@geindex size (tracemalloc.Statistic 属性)
@anchor{library/tracemalloc tracemalloc Statistic size}@anchor{366d}
@deffn {属性} size

Total size of memory blocks in bytes (@code{int}).
@end deffn

@geindex traceback (tracemalloc.Statistic 属性)
@anchor{library/tracemalloc tracemalloc Statistic traceback}@anchor{366e}
@deffn {属性} traceback

Traceback where the memory block was allocated, @ref{50c,,Traceback}
instance.
@end deffn
@end deffn

@node StatisticDiff,跟踪,统计,API
@anchor{library/tracemalloc statisticdiff}@anchor{3671}
@subsubsection StatisticDiff


@geindex StatisticDiff (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc StatisticDiff}@anchor{3664}
@deffn {类} tracemalloc.StatisticDiff

Statistic difference on memory allocations between an old and a new
@ref{3653,,Snapshot} instance.

@ref{3652,,Snapshot.compare_to()} returns a list of @ref{3664,,StatisticDiff}
instances. See also the @ref{366c,,Statistic} class.

@geindex count (tracemalloc.StatisticDiff 属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff count}@anchor{3672}
@deffn {属性} count

Number of memory blocks in the new snapshot (@code{int}): @code{0} if
the memory blocks have been released in the new snapshot.
@end deffn

@geindex count_diff (tracemalloc.StatisticDiff 属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff count_diff}@anchor{3667}
@deffn {属性} count_diff

Difference of number of memory blocks between the old and the new
snapshots (@code{int}): @code{0} if the memory blocks have been allocated in
the new snapshot.
@end deffn

@geindex size (tracemalloc.StatisticDiff 属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff size}@anchor{3666}
@deffn {属性} size

Total size of memory blocks in bytes in the new snapshot (@code{int}):
@code{0} if the memory blocks have been released in the new snapshot.
@end deffn

@geindex size_diff (tracemalloc.StatisticDiff 属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff size_diff}@anchor{3665}
@deffn {属性} size_diff

Difference of total size of memory blocks in bytes between the old and
the new snapshots (@code{int}): @code{0} if the memory blocks have been
allocated in the new snapshot.
@end deffn

@geindex traceback (tracemalloc.StatisticDiff 属性)
@anchor{library/tracemalloc tracemalloc StatisticDiff traceback}@anchor{3669}
@deffn {属性} traceback

Traceback where the memory blocks were allocated, @ref{50c,,Traceback}
instance.
@end deffn
@end deffn

@node 跟踪,回溯,StatisticDiff,API
@anchor{library/tracemalloc trace}@anchor{3673}
@subsubsection 跟踪


@geindex Trace (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Trace}@anchor{366f}
@deffn {类} tracemalloc.Trace

Trace of a memory block.

The @ref{366b,,Snapshot.traces} attribute is a sequence of @ref{366f,,Trace}
instances.


在 3.6 版更改: 增加了 @ref{3674,,domain} 属性。


@geindex domain (tracemalloc.Trace 属性)
@anchor{library/tracemalloc tracemalloc Trace domain}@anchor{3674}
@deffn {属性} domain

Address space of a memory block (@code{int}). Read-only property.

tracemalloc uses the domain @code{0} to trace memory allocations made by
Python. C extensions can use other domains to trace other resources.
@end deffn

@geindex size (tracemalloc.Trace 属性)
@anchor{library/tracemalloc tracemalloc Trace size}@anchor{3675}
@deffn {属性} size

Size of the memory block in bytes (@code{int}).
@end deffn

@geindex traceback (tracemalloc.Trace 属性)
@anchor{library/tracemalloc tracemalloc Trace traceback}@anchor{3676}
@deffn {属性} traceback

Traceback where the memory block was allocated, @ref{50c,,Traceback}
instance.
@end deffn
@end deffn

@node 回溯,,跟踪,API
@anchor{library/tracemalloc traceback}@anchor{3677}
@subsubsection 回溯


@geindex Traceback (tracemalloc 中的类)
@anchor{library/tracemalloc tracemalloc Traceback}@anchor{50c}
@deffn {类} tracemalloc.Traceback

Sequence of @ref{3660,,Frame} instances sorted from the oldest frame to the
most recent frame.

A traceback contains at least @code{1} frame. If the @code{tracemalloc} module
failed to get a frame, the filename @code{"<unknown>"} at line number @code{0} is
used.

When a snapshot is taken, tracebacks of traces are limited to
@ref{364d,,get_traceback_limit()} frames. See the @ref{364e,,take_snapshot()} function.
The original number of frames of the traceback is stored in the
@ref{3651,,Traceback.total_nframe} attribute. That allows to know if a traceback
has been truncated by the traceback limit.

The @ref{3676,,Trace.traceback} attribute is an instance of @ref{50c,,Traceback}
instance.


在 3.7 版更改: Frames are now sorted from the oldest to the most recent, instead of most recent to oldest.


@geindex total_nframe (tracemalloc.Traceback 属性)
@anchor{library/tracemalloc tracemalloc Traceback total_nframe}@anchor{3651}
@deffn {属性} total_nframe

Total number of frames that composed the traceback before truncation.
This attribute can be set to @code{None} if the information is not
available.
@end deffn


在 3.9 版更改: The @ref{3651,,Traceback.total_nframe} attribute was added.


@geindex format() (tracemalloc.Traceback 方法)
@anchor{library/tracemalloc tracemalloc Traceback format}@anchor{50d}
@deffn {方法} format (limit=None, most_recent_first=False)

Format the traceback as a list of lines. Use the @ref{a8,,linecache} module to
retrieve lines from the source code. If @emph{limit} is set, format the @emph{limit}
most recent frames if @emph{limit} is positive. Otherwise, format the
@code{abs(limit)} oldest frames. If @emph{most_recent_first} is @code{True}, the order
of the formatted frames is reversed, returning the most recent frame first
instead of last.

Similar to the @ref{3678,,traceback.format_tb()} function, except that
@ref{50d,,format()} does not include newlines.

示例:

@example
print("Traceback (most recent call first):")
for line in traceback:
    print(line)
@end example

输出:

@example
Traceback (most recent call first):
  File "test.py", line 9
    obj = Object()
  File "test.py", line 12
    tb = tracemalloc.get_object_traceback(f())
@end example
@end deffn
@end deffn

@node 软件打包和分发,Python运行时服务,调试和分析,Python 标准库
@anchor{library/distribution doc}@anchor{3679}@anchor{library/distribution software-packaging-and-distribution}@anchor{367a}
@section 软件打包和分发


这些库可帮助你发布和安装 Python 软件。 虽然这些模块设计为与`Python 包索引 <@indicateurl{https://pypi.org}>`__结合使用，但它们也可以与本地索引服务器一起使用，或者根本不使用任何索引服务器。

@menu
* distutils: distutils --- 构建和安装 Python 模块. 构建和安装 Python 模块
* ensurepip: ensurepip --- 引导 pip 安装器. 引导 pip 安装器
* venv: venv --- 创建虚拟环境. 创建虚拟环境
* zipapp —— 管理可执行的 Python zip 打包文件:: 

@end menu

@node distutils --- 构建和安装 Python 模块,ensurepip --- 引导 pip 安装器,,软件打包和分发
@anchor{library/distutils doc}@anchor{367b}@anchor{library/distutils distutils-building-and-installing-python-modules}@anchor{367c}@anchor{library/distutils module-distutils}@anchor{38}
@subsection @code{distutils} --- 构建和安装 Python 模块


@geindex distutils (模块)


__________________________________________________________________


@ref{38,,distutils} 包为将待构建和安装的额外的模块，打包成 Python 安装包提供支持。新模块既可以是百分百的纯 Python，也可以是用 C 写的扩展模块，或者可以是一组包含了同时用 Python 和 C 编码的 Python 包。

大多数 Python 用户 @emph{不会} 想要直接使用这个包，而是使用 Python 包官方维护的跨版本工具。特别地， setuptools@footnote{https://setuptools.readthedocs.io/en/latest/} 是一个对于 @ref{38,,distutils} 的增强选项，它能提供：


@itemize *

@item 
对声明项目依赖的支持

@item 
额外的用于配置哪些文件包含在源代码发布中的机制（包括与版本控制系统集成需要的插件）

@item 
生成项目“进入点”的能力，进入点可用作应用插件系统的基础

@item 
自动在安装时间生成 Windows 命令行可执行文件的能力，而不是需要预编译它们

@item 
跨所有受支持的 Python 版本上的一致的表现
@end itemize

推荐的  pip@footnote{https://pip.pypa.io/} 安装器用 @code{setuptools} 运行所有的 @code{setup.py} 脚本，即使脚本本身只引了 @code{distutils} 包。参考 Python Packaging User Guide@footnote{https://packaging.python.org}  获得更多信息。

为了打包工具的作者和用户能更好理解当前的打包和分发系统，遗留的基于 @ref{38,,distutils} 的用户文档和 API 参考保持可用：


@itemize *

@item 
@ref{8ee,,安装Python模块（旧版）}

@item 
@ref{8ef,,分发 Python 模块（遗留版本）}
@end itemize

@node ensurepip --- 引导 pip 安装器,venv --- 创建虚拟环境,distutils --- 构建和安装 Python 模块,软件打包和分发
@anchor{library/ensurepip doc}@anchor{367d}@anchor{library/ensurepip ensurepip-bootstrapping-the-pip-installer}@anchor{367e}@anchor{library/ensurepip module-ensurepip}@anchor{78}
@subsection @code{ensurepip} --- 引导 @code{pip} 安装器


@geindex ensurepip (模块)


3.4 新版功能.



__________________________________________________________________


@ref{78,,ensurepip} 包为在已有的Python安装实例或虚拟环境中引导 @code{pip} 安装器提供了支持。需要使用引导才能使用pip的这一事实也正好反映了 @code{pip} 是一个独立的项目，有其自己的发布周期，其最新版本随CPython解释器的维护版本和新特性版本一同捆绑。

在大多数情况下，Python的终端使用者不需要直接调用这个模块（ @code{pip} 默认应该已被引导），不过，如果在安装Python（或创建虚拟环境）之时跳过了安装 @code{pip} 步骤，或者日后特意卸载了 @code{pip} ，则需要使用这个模块。

@cartouche
@quotation 注解 
这个模块 @emph{无需} 访问互联网。引导启动 @code{pip} 所需的全部组件均包含在包的内部。
@end quotation
@end cartouche


@subsubheading 参见



@table @asis

@item @ref{8ec,,安装 Python 模块}

安装Python包的终端使用者教程

@geindex Python 提高建议; PEP 453

@item PEP 453@footnote{https://www.python.org/dev/peps/pep-0453}: 在Python安装实例中显式引导启动pip

这个模块的原始缘由以及规范文档
@end table


@menu
* 命令行界面: 命令行界面<7>. 
* 模块 API:: 

@end menu

@node 命令行界面<7>,模块 API,,ensurepip --- 引导 pip 安装器
@anchor{library/ensurepip command-line-interface}@anchor{367f}
@subsubsection 命令行界面


使用解释器的 @code{-m} 参数调用命令行接口。

最简单的调用方式为：

@example
python -m ensurepip
@end example

This invocation will install @code{pip} if it is not already installed,
but otherwise does nothing. To ensure the installed version of @code{pip}
is at least as recent as the one bundled with @code{ensurepip}, pass the
@code{--upgrade} option:

@example
python -m ensurepip --upgrade
@end example

在默认情况下，@code{pip} 会被安装到当前虚拟环境（如果激活了虚拟环境）或系统的包目录（如果未激活虚拟环境）。 安装位置可通过两个额外的命令行选项来控制。


@itemize *

@item 
@code{--root 1}: 相对于给定的根目录而不是当前已激活虚拟环境（如果存在）的根目录或当前 Python 安装版的默认根目录来安装 @code{pip}。

@item 
@code{--user}: 将 @code{pip} 安装到用户包目录而不是全局安装到当前 Python 安装版（此选项不允许在已激活虚拟环境中使用）。
@end itemize

在默认情况下，脚本 @code{pipX} 和 @code{pipX.Y} 将被安装（其中 X.Y 表示被用来发起调用 @code{ensurepip} 的 Python 的版本）。 所安装的脚本可通过两个额外的命令行选项来控制:


@itemize *

@item 
@code{--altinstall}: 如果请求了一个替代安装版，则 @code{pipX} 脚本将 @emph{不会} 被安装。

@item 
@code{--default-pip}: 如果请求了一个 "默认的 pip" 安装版，则除了两个常规脚本之外还将安装 @code{pip} 脚本。
@end itemize

同时提供这两个脚本选择选项将会触发异常。

@node 模块 API,,命令行界面<7>,ensurepip --- 引导 pip 安装器
@anchor{library/ensurepip module-api}@anchor{3680}
@subsubsection 模块 API


@ref{78,,ensurepip} 暴露了两个函数用于编程:

@geindex version() (在 ensurepip 模块中)
@anchor{library/ensurepip ensurepip version}@anchor{3681}
@deffn {函数} ensurepip.version ()

Returns a string specifying the bundled version of pip that will be
installed when bootstrapping an environment.
@end deffn

@geindex bootstrap() (在 ensurepip 模块中)
@anchor{library/ensurepip ensurepip bootstrap}@anchor{3555}
@deffn {函数} ensurepip.bootstrap (root=None, upgrade=False, user=False, altinstall=False, default_pip=False, verbosity=0)

初始创建 @code{pip} 到当前的或指定的环境中。

@emph{root} 指明要作为相对安装路径的替代根目录。 如果 @emph{root} 为 @code{None}，则安装会使用当前环境的默认安装位置。

@emph{upgrade} indicates whether or not to upgrade an existing installation
of an earlier version of @code{pip} to the bundled version.

@emph{user} 指明是否使用针对用户的安装方案而不是全局安装。

在默认情况下，将会安装 @code{pipX} 和 @code{pipX.Y} 脚本（其中 X.Y 表示 Python 的当前版本）。

如果设置了 @emph{altinstall}，则 @code{pipX} 将 @emph{不会} 被安装。

如果设置了 @emph{default_pip}，则除了两个常规脚本外还将安装 @code{pip}。

同时设置 @emph{altinstall} 和 @emph{default_pip} 将触发 @ref{16d,,ValueError}。

@emph{verbosity} 控制初始创建操作对 @ref{428,,sys.stdout} 的输出信息级别。

引发一个 @ref{fec,,审计事件} @code{ensurepip.bootstrap} 附带参数 @code{root}。

@cartouche
@quotation 注解 
创建创建过程对于 @code{sys.path} 和 @code{os.environ} 都会有附带影响。 改为在子进程中发起调用命令行接口可以避免这些附带影响。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
初始创建过程可能会安装 @code{pip} 所需的额外模块，但其他软件不应假定这些依赖将总是会默认存在（因为这些依赖可能会在未来的 @code{pip} 版本中被移除）。
@end quotation
@end cartouche
@end deffn

@node venv --- 创建虚拟环境,zipapp —— 管理可执行的 Python zip 打包文件,ensurepip --- 引导 pip 安装器,软件打包和分发
@anchor{library/venv doc}@anchor{3682}@anchor{library/venv module-venv}@anchor{12e}@anchor{library/venv venv-creation-of-virtual-environments}@anchor{3683}
@subsection @code{venv} --- 创建虚拟环境


@geindex venv (模块)


3.3 新版功能.


@strong{源码：} Lib/venv/@footnote{https://github.com/python/cpython/tree/3.9/Lib/venv/}

@geindex Environments; virtual


__________________________________________________________________


@ref{12e,,venv} 模块支持使用自己的站点目录创建轻量级“虚拟环境”，可选择与系统站点目录隔离。每个虚拟环境都有自己的 Python 二进制文件（与用于创建此环境的二进制文件的版本相匹配），并且可以在其站点目录中拥有自己独立的已安装 Python 软件包集。

有关 Python 虚拟环境的更多信息，请参阅 
@geindex Python 提高建议; PEP 405
PEP 405@footnote{https://www.python.org/dev/peps/pep-0405} 。


@subsubheading 参见


Python 打包用户指南：创建和使用虚拟环境@footnote{https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment}


@menu
* 创建虚拟环境: 创建虚拟环境<2>. 
* API: API<2>. 
* 一个扩展 EnvBuilder 的例子:: 

@end menu

@node 创建虚拟环境<2>,API<2>,,venv --- 创建虚拟环境
@anchor{library/venv creating-virtual-environments}@anchor{3684}
@subsubsection 创建虚拟环境


通过执行 @code{venv} 指令来创建一个 @ref{3685,,虚拟环境}:

@example
python3 -m venv /path/to/new/virtual/environment
@end example

运行此命令将创建目标目录（父目录若不存在也将创建），并放置一个 @code{pyvenv.cfg} 文件在其中，文件中有一个 @code{home} 键，它的值指向运行此命令的 Python 安装（目标目录的常用名称是 @code{.venv}）。它还会创建一个 @code{bin} 子目录（在 Windows 上是 @code{Scripts}），其中包含 Python 二进制文件的副本或符号链接（视创建环境时使用的平台或参数而定）。它还会创建一个（初始为空的） @code{lib/pythonX.Y/site-packages} 子目录（在 Windows 上是 @code{Lib\site-packages}）。如果指定了一个现有的目录，这个目录就将被重新使用。


3.6 版后已移除: @code{pyvenv} 是 Python 3.3 和 3.4 中创建虚拟环境的推荐工具，不过 在 Python 3.6 中已弃用@footnote{https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features}。



在 3.5 版更改: 现在推荐使用 @code{venv} 来创建虚拟环境。


在 Windows 上，调用 @code{venv} 命令如下:

@example
c:\>c:\Python35\python -m venv c:\path\to\myenv
@end example

或者，如果已经为 @ref{401,,Python 安装} 配置好 @code{PATH} 和 @code{PATHEXT} 变量:

@example
c:\>python -m venv c:\path\to\myenv
@end example

本命令如果以 @code{-h} 参数运行，将显示可用的选项:

@example
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR               A directory to create the environment in.

optional arguments:
  -h, --help            show this help message and exit
  --system-site-packages
                        Give the virtual environment access to the system
                        site-packages dir.
  --symlinks            Try to use symlinks rather than copies, when symlinks
                        are not the default for the platform.
  --copies              Try to use copies rather than symlinks, even when
                        symlinks are the default for the platform.
  --clear               Delete the contents of the environment directory if it
                        already exists, before environment creation.
  --upgrade             Upgrade the environment directory to use this version
                        of Python, assuming Python has been upgraded in-place.
  --without-pip         Skips installing or upgrading pip in the virtual
                        environment (pip is bootstrapped by default)
  --prompt PROMPT       Provides an alternative prompt prefix for this
                        environment.
  --upgrade-deps        Upgrade core dependencies: pip setuptools to the
                        latest version in PyPI

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.
@end example


在 3.9 版更改: 添加 @code{--upgrade-deps} 选项，用于将 pip + setuptools 升级到 PyPI 上的最新版本



在 3.4 版更改: 默认安装 pip，并添加 @code{--without-pip} 和 @code{--copies} 选项



在 3.4 版更改: 在早期版本中，如果目标目录已存在，将引发错误，除非使用了 @code{--clear} 或 @code{--upgrade} 选项。


@cartouche
@quotation 注解 
虽然 Windows 支持符号链接，但不推荐使用它们。特别注意，在文件资源管理器中双击 @code{python.exe} 将立即解析符号链接，并忽略虚拟环境。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
在 Microsoft Windows 上，为了启用 @code{Activate.ps1} 脚本，可能需要修改用户的执行策略。可以运行以下 PowerShell 命令来执行此操作：

PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

参阅 About Execution Policies@footnote{https://go.microsoft.com/fwlink/?LinkID=135170} 以获取更多信息。
@end quotation
@end cartouche

生成的 @code{pyvenv.cfg} 文件还包括 @code{include-system-site-packages} 键，如果运行 @code{venv} 时带有 @code{--system-site-packages} 选项，则键值为 @code{true}，否则为 @code{false}。

除非采用 @code{--without-pip} 选项，否则将会调用 @ref{78,,ensurepip} 将 @code{pip} 引导到虚拟环境中。

可以向 @code{venv} 传入多个路径，此时将根据给定的选项，在所给的每个路径上创建相同的虚拟环境。

创建虚拟环境后，可以使用虚拟环境的二进制目录中的脚本来“激活”该环境。不同平台调用的脚本是不同的（须将 @cite{<venv>} 替换为包含虚拟环境的目录路径）：


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

平台

@tab

Shell

@tab

用于激活虚拟环境的命令

@item

POSIX

@tab

bash/zsh

@tab

$ source <venv>/bin/activate

@item

@tab

fish

@tab

$ source <venv>/bin/activate.fish

@item

@tab

csh/tcsh

@tab

$ source <venv>/bin/activate.csh

@item

@tab

PowerShell Core

@tab

$ <venv>/bin/Activate.ps1

@item

Windows

@tab

cmd.exe

@tab

C:\> <venv>\Scripts\activate.bat

@item

@tab

PowerShell

@tab

PS C:\> <venv>\Scripts\Activate.ps1

@end multitable


当一个虚拟环境被激活时，
@geindex VIRTUAL_ENV
@geindex 环境变量; VIRTUAL_ENV
@code{VIRTUAL_ENV} 环境变量会被设为该虚拟环境的路径。 这可被用来检测程序是否运行在虚拟环境中。

激活环境不是 @emph{必须} 的，激活只是将虚拟环境的二进制目录添加到搜索路径中，这样 "python" 命令将调用虚拟环境的 Python 解释器，可以运行其中已安装的脚本，而不必输入其完整路径。但是，安装在虚拟环境中的所有脚本都应在不激活的情况下可运行，并自动与虚拟环境的 Python 一起运行。

在 shell 中输入 "deactivate" 可以退出虚拟环境。具体机制取决于不同平台，并且是内部实现（通常使用脚本或 shell 函数）。


3.4 新版功能: @code{fish} 和 @code{csh} 激活脚本。



3.8 新版功能: 在 POSIX 上安装 PowerShell 激活脚本，以支持 PowerShell Core。

@anchor{library/venv venv-def}@anchor{3685}
@cartouche
@quotation 注解 
虚拟环境是一个 Python 环境，安装到其中的 Python 解释器、库和脚本与其他虚拟环境中的内容是隔离的，且（默认）与“系统级” Python（操作系统的一部分）中安装的库是隔离的。

虚拟环境是一个目录树，其中包含 Python 可执行文件和其他文件，其他文件指示了这是一个是虚拟环境。

常用安装工具如 setuptools@footnote{https://pypi.org/project/setuptools/} 和 pip@footnote{https://pypi.org/project/pip/} 可以在虚拟环境中按预期工作。换句话说，当虚拟环境被激活，它们就会将 Python 软件包安装到虚拟环境中，无需明确指示。

当虚拟环境被激活（即虚拟环境的 Python 解释器正在运行），属性 @ref{3686,,sys.prefix} 和 @ref{3687,,sys.exec_prefix} 指向的是虚拟环境的基础目录，而 @ref{305e,,sys.base_prefix} 和 @ref{3688,,sys.base_exec_prefix} 指向非虚拟环境的 Python 安装，即曾用于创建虚拟环境的那个 Python 安装。如果虚拟环境没有被激活，则 @ref{3686,,sys.prefix} 与 @ref{305e,,sys.base_prefix} 相同，且 @ref{3687,,sys.exec_prefix} 与 @ref{3688,,sys.base_exec_prefix} 相同（它们均指向非虚拟环境的 Python 安装）。

当虚拟环境被激活，所有 @ref{38,,distutils} 配置文件中更改安装路径的选项都会被忽略，以防止无意中将项目安装在虚拟环境之外。

在命令行 shell 中工作时，用户可以运行虚拟环境可执行文件目录中的 @code{activate} 脚本来激活虚拟环境（调用该文件的确切文件名和命令取决于 shell），这会将虚拟环境的可执行文件目录添加到当前 shell 的 @code{PATH} 环境变量。在其他情况下，无需激活虚拟环境。安装到虚拟环境中的脚本有 "shebang" 行，指向虚拟环境的 Python 解释器。这意味着无论 @code{PATH} 的值如何，脚本都将与该解释器一起运行。在 Windows 上，如果已安装 Python Launcher for Windows，则支持处理 "shebang" 行（此功能在 Python 3.3 中添加，详情请参阅 
@geindex Python 提高建议; PEP 397
PEP 397@footnote{https://www.python.org/dev/peps/pep-0397}）。这样，在 Windows 资源管理器中双击已安装的脚本，应该会使用正确的解释器运行该脚本，而在 @code{PATH} 中无需指向其虚拟环境。
@end quotation
@end cartouche

@node API<2>,一个扩展 EnvBuilder 的例子,创建虚拟环境<2>,venv --- 创建虚拟环境
@anchor{library/venv api}@anchor{3689}@anchor{library/venv venv-api}@anchor{8e9}
@subsubsection API


上述的高级方法使用了一个简单的 API，该 API 提供了一种机制，第三方虚拟环境创建者可以根据其需求自定义环境创建过程，该 API 为 @ref{9f7,,EnvBuilder} 类。

@geindex EnvBuilder (venv 中的类)
@anchor{library/venv venv EnvBuilder}@anchor{9f7}
@deffn {类} venv.EnvBuilder (system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False)

@ref{9f7,,EnvBuilder} 类在实例化时接受以下关键字参数：


@itemize *

@item 
@code{system_site_packages} -- 一个布尔值，要求系统 Python 的 site-packages 对环境可用（默认为 @code{False}）。

@item 
@code{clear} -- 一个布尔值，如果为 true，则在创建环境前将删除目标目录的现有内容。

@item 
@code{symlinks} -- 一个布尔值，指示是否尝试符号链接 Python 二进制文件，而不是进行复制。

@item 
@code{upgrade} -- 一个布尔值，如果为 true，则将使用当前运行的 Python 去升级一个现有的环境，这主要在原位置的 Python 更新后使用（默认为 @code{False}）。

@item 
@code{with_pip} -- 一个布尔值，如果为 true，则确保在虚拟环境中已安装 pip。这使用的是带有 @code{--default-pip} 选项的 @ref{78,,ensurepip}。

@item 
@code{prompt} -- 激活虚拟环境后显示的提示符（默认为 @code{None}，表示使用环境所在的目录名称）。如果使用了 @code{"."} 这一特殊字符串，则使用当前目录的基本名称作为提示符。

@item 
@code{upgrade_deps} -- 将基本 venv 模块更新为 PyPI 上的最新版本。
@end itemize


在 3.4 版更改: 添加 @code{with_pip} 参数



3.6 新版功能: 添加 @code{prompt} 参数



3.9 新版功能: 添加 @code{upgrade_deps} 参数


第三方虚拟环境工具的创建者可以自由地将此处提供的 @ref{9f7,,EnvBuilder} 类作为基类。

返回的 env-builder 是一个对象，包含一个 @code{create} 方法：

@geindex create() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder create}@anchor{368a}
@deffn {方法} create (env_dir)

指定要建立虚拟环境的目标目录（绝对路径或相对于当前路径）来创建虚拟环境。@code{create} 方法将在指定目录中创建环境，或者引发对应的异常。

@ref{9f7,,EnvBuilder} 类的 @code{create} 方法定义了可用于定制子类的钩子:

@example
def create(self, env_dir):
    """
    Create a virtualized Python environment in a directory.
    env_dir is the target directory to create an environment in.
    """
    env_dir = os.path.abspath(env_dir)
    context = self.ensure_directories(env_dir)
    self.create_configuration(context)
    self.setup_python(context)
    self.setup_scripts(context)
    self.post_setup(context)
@end example

每个方法 @ref{368b,,ensure_directories()}, @ref{368c,,create_configuration()}, @ref{368d,,setup_python()}, @ref{368e,,setup_scripts()} 和 @ref{368f,,post_setup()} 都可以被重写。
@end deffn

@geindex ensure_directories() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder ensure_directories}@anchor{368b}
@deffn {方法} ensure_directories (env_dir)

创建环境目录和所有必需的目录，并返回一个上下文对象。该对象只是一个容器，保存属性（如路径），供其他方法使用。允许目录已经存在，如果指定了 @code{clear} 或 @code{upgrade} 就允许在现有环境目录上进行操作。
@end deffn

@geindex create_configuration() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder create_configuration}@anchor{368c}
@deffn {方法} create_configuration (context)

在环境中创建 @code{pyvenv.cfg} 配置文件。
@end deffn

@geindex setup_python() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder setup_python}@anchor{368d}
@deffn {方法} setup_python (context)

在环境中创建 Python 可执行文件的拷贝或符号链接。在 POSIX 系统上，如果给定了可执行文件 @code{python3.x}，将创建指向该可执行文件的 @code{python} 和 @code{python3} 符号链接，除非相同名称的文件已经存在。
@end deffn

@geindex setup_scripts() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder setup_scripts}@anchor{368e}
@deffn {方法} setup_scripts (context)

将适用于平台的激活脚本安装到虚拟环境中。
@end deffn

@geindex upgrade_dependencies() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder upgrade_dependencies}@anchor{3690}
@deffn {方法} upgrade_dependencies (context)

升级环境中 venv 依赖的核心软件包（当前为 @code{pip} 和 @code{setuptools}）。通过在环境中使用 @code{pip} 可执行文件来完成。


3.9 新版功能.

@end deffn

@geindex post_setup() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder post_setup}@anchor{368f}
@deffn {方法} post_setup (context)

占位方法，可以在第三方实现中重写，用于在虚拟环境中预安装软件包，或是其他创建后要执行的步骤。
@end deffn


在 3.7.2 版更改: Windows 现在为 @code{python[w].exe} 使用重定向脚本，而不是复制实际的二进制文件。仅在 3.7.2 中，除非运行的是源码树中的构建，否则 @ref{368d,,setup_python()} 不会执行任何操作。



在 3.7.3 版更改: Windows 将重定向脚本复制为 @ref{368d,,setup_python()} 的一部分而非 @ref{368e,,setup_scripts()}。在 3.7.2 中不是这种情况。使用符号链接时，将链接至原始可执行文件。


此外，@ref{9f7,,EnvBuilder} 提供了如下实用方法，可以从子类的 @ref{368e,,setup_scripts()} 或 @ref{368f,,post_setup()} 调用，用来将自定义脚本安装到虚拟环境中。

@geindex install_scripts() (venv.EnvBuilder 方法)
@anchor{library/venv venv EnvBuilder install_scripts}@anchor{3691}
@deffn {方法} install_scripts (context, path)

@emph{path} 是一个目录的路径，该目录应包含子目录 "common", "posix", "nt"，每个子目录存有发往对应环境中 bin 目录的脚本。在下列占位符替换完毕后，将复制 "common" 的内容和与 @ref{2071,,os.name} 对应的子目录：


@itemize *

@item 
@code{__VENV_DIR__} 会被替换为环境目录的绝对路径。

@item 
@code{__VENV_NAME__} 会被替换为环境名称（环境目录的最后一个字段）。

@item 
@code{__VENV_PROMPT__} 会被替换为提示符（用括号括起来的环境名称紧跟着一个空格）。

@item 
@code{__VENV_BIN_NAME__} 会被替换为 bin 目录的名称（ @code{bin} 或 @code{Scripts} ）。

@item 
@code{__VENV_PYTHON__} 会被替换为环境可执行文件的绝对路径。
@end itemize

允许目录已存在（用于升级现有环境时）。
@end deffn
@end deffn

有一个方便实用的模块级别的函数:

@geindex create() (在 venv 模块中)
@anchor{library/venv venv create}@anchor{9f8}
@deffn {函数} venv.create (env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)

通过关键词参数来创建一个 @ref{9f7,,EnvBuilder}，并且使用 @emph{env_dir} 参数来调用它的 @ref{368a,,create()} 方法。


3.3 新版功能.



在 3.4 版更改: 添加 @code{with_pip} 参数



在 3.6 版更改: 添加 @code{prompt} 参数

@end deffn

@node 一个扩展 EnvBuilder 的例子,,API<2>,venv --- 创建虚拟环境
@anchor{library/venv an-example-of-extending-envbuilder}@anchor{3692}
@subsubsection 一个扩展 @code{EnvBuilder} 的例子


下面的脚本展示了如何通过实现一个子类来扩展 @ref{9f7,,EnvBuilder}。这个子类会安装 setuptools 和 pip 到被创建的虚拟环境中。

@example
import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve
import venv

class ExtendedEnvBuilder(venv.EnvBuilder):
    """
    This builder installs setuptools and pip so that you can pip or
    easy_install other packages into the created virtual environment.

    :param nodist: If true, setuptools and pip are not installed into the
                   created virtual environment.
    :param nopip: If true, pip is not installed into the created
                  virtual environment.
    :param progress: If setuptools or pip are installed, the progress of the
                     installation can be monitored by passing a progress
                     callable. If specified, it is called with two
                     arguments: a string indicating some progress, and a
                     context indicating where the string is coming from.
                     The context argument can have one of three values:
                     'main', indicating that it is called from virtualize()
                     itself, and 'stdout' and 'stderr', which are obtained
                     by reading lines from the output streams of a subprocess
                     which is used to install the app.

                     If a callable is not specified, default progress
                     information is output to sys.stderr.
    """

    def __init__(self, *args, **kwargs):
        self.nodist = kwargs.pop('nodist', False)
        self.nopip = kwargs.pop('nopip', False)
        self.progress = kwargs.pop('progress', None)
        self.verbose = kwargs.pop('verbose', False)
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        """
        Set up any packages which need to be pre-installed into the
        virtual environment being created.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        os.environ['VIRTUAL_ENV'] = context.env_dir
        if not self.nodist:
            self.install_setuptools(context)
        # Can't install pip without setuptools
        if not self.nopip and not self.nodist:
            self.install_pip(context)

    def reader(self, stream, context):
        """
        Read lines from a subprocess' output stream and either pass to a progress
        callable (if specified) or write progress information to sys.stderr.
        """
        progress = self.progress
        while True:
            s = stream.readline()
            if not s:
                break
            if progress is not None:
                progress(s, context)
            else:
                if not self.verbose:
                    sys.stderr.write('.')
                else:
                    sys.stderr.write(s.decode('utf-8'))
                sys.stderr.flush()
        stream.close()

    def install_script(self, context, name, url):
        _, _, path, _, _, _ = urlparse(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the virtual environment's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = '@w{'}
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the virtual environment
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
        self.install_script(context, 'setuptools', url)
        # clear up the setuptools archive which gets downloaded
        pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
        files = filter(pred, os.listdir(context.bin_path))
        for f in files:
            f = os.path.join(context.bin_path, f)
            os.unlink(f)

    def install_pip(self, context):
        """
        Install pip in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bootstrap.pypa.io/get-pip.py'
        self.install_script(context, 'pip', url)

def main(args=None):
    compatible = True
    if sys.version_info < (3, 3):
        compatible = False
    elif not hasattr(sys, 'base_prefix'):
        compatible = False
    if not compatible:
        raise ValueError('This script is only for use with '
                         'Python 3.3 or later')
    else:
        import argparse

        parser = argparse.ArgumentParser(prog=__name__,
                                         description='Creates virtual Python '
                                                     'environments in one or '
                                                     'more target '
                                                     'directories.')
        parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                            help='A directory in which to create the '
                                 'virtual environment.')
        parser.add_argument('--no-setuptools', default=False,
                            action='store_true', dest='nodist',
                            help="Don't install setuptools or pip in the "
                                 "virtual environment.")
        parser.add_argument('--no-pip', default=False,
                            action='store_true', dest='nopip',
                            help="Don't install pip in the virtual "
                                 "environment.")
        parser.add_argument('--system-site-packages', default=False,
                            action='store_true', dest='system_site',
                            help='Give the virtual environment access to the '
                                 'system site-packages dir.')
        if os.name == 'nt':
            use_symlinks = False
        else:
            use_symlinks = True
        parser.add_argument('--symlinks', default=use_symlinks,
                            action='store_true', dest='symlinks',
                            help='Try to use symlinks rather than copies, '
                                 'when symlinks are not the default for '
                                 'the platform.')
        parser.add_argument('--clear', default=False, action='store_true',
                            dest='clear', help='Delete the contents of the '
                                               'virtual environment '
                                               'directory if it already '
                                               'exists, before virtual '
                                               'environment creation.')
        parser.add_argument('--upgrade', default=False, action='store_true',
                            dest='upgrade', help='Upgrade the virtual '
                                                 'environment directory to '
                                                 'use this version of '
                                                 'Python, assuming Python '
                                                 'has been upgraded '
                                                 'in-place.')
        parser.add_argument('--verbose', default=False, action='store_true',
                            dest='verbose', help='Display the output '
                                               'from the scripts which '
                                               'install setuptools and pip.')
        options = parser.parse_args(args)
        if options.upgrade and options.clear:
            raise ValueError('you cannot supply --upgrade and --clear together.')
        builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                       clear=options.clear,
                                       symlinks=options.symlinks,
                                       upgrade=options.upgrade,
                                       nodist=options.nodist,
                                       nopip=options.nopip,
                                       verbose=options.verbose)
        for d in options.dirs:
            builder.create(d)

if __name__ == '__main__':
    rc = 1
    try:
        main()
        rc = 0
    except Exception as e:
        print('Error: %s' % e, file=sys.stderr)
    sys.exit(rc)
@end example

这个脚本同样可以 在线下载@footnote{https://gist.github.com/vsajip/4673395}。

@node zipapp —— 管理可执行的 Python zip 打包文件,,venv --- 创建虚拟环境,软件打包和分发
@anchor{library/zipapp doc}@anchor{3693}@anchor{library/zipapp module-zipapp}@anchor{14a}@anchor{library/zipapp pip}@anchor{3694}@anchor{library/zipapp zipapp-manage-executable-python-zip-archives}@anchor{3695}
@subsection @code{zipapp} —— 管理可执行的 Python zip 打包文件


@geindex zipapp (模块)


3.5 新版功能.


@strong{源代码：} Lib/zipapp.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/zipapp.py}

@geindex Executable Zip Files


__________________________________________________________________


本模块提供了一套管理工具，用于创建包含 Python 代码的压缩文件，这些文件可以 @ref{149f,,直接由 Python 解释器执行}。 本模块提供 @ref{3696,,命令行接口} 和 @ref{3697,,Python API}。

@menu
* 简单示例:: 
* 命令行接口:: 
* Python API:: 
* 示例: 示例<42>. 
* 指定解释器程序:: 
* 用 zipapp 创建独立运行的应用程序:: 
* Python 打包应用程序的格式:: 

@end menu

@node 简单示例,命令行接口,,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp basic-example}@anchor{3698}
@subsubsection 简单示例


下述例子展示了用 @ref{3696,,命令行接口} 根据含有 Python 代码的目录创建一个可执行的打包文件。 运行后该打包文件时，将会执行 @code{myapp} 模块中的 @code{main} 函数。

@example
$ python -m zipapp myapp -m "myapp:main"
$ python myapp.pyz
<output from myapp>
@end example

@node 命令行接口,Python API,简单示例,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp command-line-interface}@anchor{3699}@anchor{library/zipapp zipapp-command-line-interface}@anchor{3696}
@subsubsection 命令行接口


若要从命令行调用，则采用以下形式：

@example
$ python -m zipapp source [options]
@end example

如果 @emph{source} 是个目录，将根据 @emph{source} 的内容创建一个打包文件。如果 @emph{source} 是个文件，则应为一个打包文件，将会复制到目标打包文件中（如果指定了 -info 选项，将会显示 shebang 行的内容）。

可以接受以下参数：

@geindex zipapp command line option; -o <output>
@geindex zipapp command line option; --output=<output>
@anchor{library/zipapp cmdoption-zipapp-o}@anchor{369a}
@deffn {程序选项} @w{-}o <output>, @w{-}@w{-}output=<output>

将程序的输出写入名为 @emph{output} 的文件中。若未指定此参数，输出的文件名将与输入的 @emph{source} 相同，并添加扩展名 @code{.pyz}。如果显式给出了文件名，将会原样使用（因此必要时应包含扩展名 @code{.pyz}）。

如果 @emph{source} 是个打包文件，必须指定一个输出文件名（这时 @emph{output} 必须与 @emph{source} 不同）。
@end deffn

@geindex zipapp command line option; -p <interpreter>
@geindex zipapp command line option; --python=<interpreter>
@anchor{library/zipapp cmdoption-zipapp-p}@anchor{369b}
@deffn {程序选项} @w{-}p <interpreter>, @w{-}@w{-}python=<interpreter>

给打包文件加入 @code{#!} 行，以便指定 @emph{解释器} 作为运行的命令行。另外，还让打包文件在 POSIX 平台上可执行。默认不会写入  @code{#!} 行，也不让文件可执行。
@end deffn

@geindex zipapp command line option; -m <mainfn>
@geindex zipapp command line option; --main=<mainfn>
@anchor{library/zipapp cmdoption-zipapp-m}@anchor{369c}
@deffn {程序选项} @w{-}m <mainfn>, @w{-}@w{-}main=<mainfn>

在打包文件中写入一个 @code{__main__.py} 文件，用于执行 @emph{mainfn}。@emph{mainfn} 参数的形式应为 “pkg.mod:fn”，其中 “pkg.mod”是打包文件中的某个包/模块，“fn”是该模块中的一个可调用对象。@code{__main__.py} 文件将会执行该可调用对象。

在复制打包文件时，不能设置 @ref{369c,,--main}  参数。
@end deffn

@geindex zipapp command line option; -c
@geindex zipapp command line option; --compress
@anchor{library/zipapp cmdoption-zipapp-c}@anchor{369d}
@deffn {程序选项} @w{-}c, @w{-}@w{-}compress

利用 deflate 方法压缩文件，减少输出文件的大小。默认情况下，打包文件中的文件是不压缩的。

在复制打包文件时，@ref{369d,,--compress} 无效。


3.7 新版功能.

@end deffn

@geindex zipapp command line option; --info
@anchor{library/zipapp cmdoption-zipapp-info}@anchor{369e}
@deffn {程序选项} @w{-}@w{-}info

显示嵌入在打包文件中的解释器程序，以便诊断问题。这时会忽略其他所有参数，SOURCE 必须是个打包文件，而不是目录。
@end deffn

@geindex zipapp command line option; -h
@geindex zipapp command line option; --help
@anchor{library/zipapp cmdoption-zipapp-h}@anchor{369f}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

打印简短的用法信息并退出。
@end deffn

@node Python API,示例<42>,命令行接口,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp python-api}@anchor{36a0}@anchor{library/zipapp zipapp-python-api}@anchor{3697}
@subsubsection Python API


该模块定义了两个快捷函数：

@geindex create_archive() (在 zipapp 模块中)
@anchor{library/zipapp zipapp create_archive}@anchor{529}
@deffn {函数} zipapp.create_archive (source, target=None, interpreter=None, main=None, filter=None, compressed=False)

由 @emph{source} 创建一个应用程序打包文件。source 可以是以下形式之一：


@itemize *

@item 
一个目录名，或指向目录的 @ref{47b,,path-like object} ，这时将根据目录内容新建一个应用程序打包文件。

@item 
一个已存在的应用程序打包文件名，或指向这类文件的 @ref{47b,,path-like object}，这时会将该文件复制为目标文件（会稍作修改以反映出 @emph{interpreter} 参数的值）。必要时文件名中应包括 @code{.pyz} 扩展名。

@item 
一个以字节串模式打开的文件对象。该文件的内容应为应用程序打包文件，且假定文件对象定位于打包文件的初始位置。
@end itemize

@emph{target} 参数定义了打包文件的写入位置：


@itemize *

@item 
若是个文件名，或是 @ref{47b,,path-like object}，打包文件将写入该文件中。

@item 
若是个打开的文件对象，打包文件将写入该对象，该文件对象必须在字节串写入模式下打开。

@item 
如果省略了 target （或为 @code{None}），则 source 必须为一个目录，target  将是与 source 同名的文件，并加上 @code{.pyz} 扩展名。
@end itemize

参数 @emph{interpreter} 指定了 Python 解释器程序名，用于执行打包文件。这将以 “释伴（shebang）”行的形式写入打包文件的头部。在 POSIX 平台上，操作系统会进行解释，而在 Windows 平台则会由 Python 启动器进行处理。省略 @emph{interpreter} 参数则不会写入释伴行。如果指定了解释器，且目标为文件名，则会设置目标文件的可执行属性位。

参数 @emph{main} 指定某个可调用程序的名称，用作打包文件的主程序。仅当 source 为目录且不含 @code{__main__.py} 文件时，才能指定该参数。@emph{main} 参数应采用 “pkg.module:callable”的形式，通过导入“pkg.module”并不带参数地执行给出的可调用对象，即可执行打包文件。如果 source 是目录且不含`@w{`}__main__.py`@w{`} 文件，省略 @emph{main} 将会出错，生成的打包文件将无法执行。

可选参数 @emph{filter} 指定了回调函数，将传给代表被添加文件路径的 Path 对象（相对于源目录）。在文件添加完成后，应返回 @code{True}。

可选参数 @emph{compressed} 指定是否要压缩打包文件。若设为 @code{True}，则打包中的文件将用 deflate 方法进行压缩；否则就不会压缩。本参数在复制现有打包文件时无效。

若 @emph{source} 或 @emph{target} 指定的是文件对象，则调用者有责任在调用 create_archive 之后关闭文件。

当复制已有的打包文件时，提供的文件对象只需 @code{read} 和 @code{readline} 方法，或 @code{write} 方法。当由目录创建打包文件时，若目标为文件对象，将会将其传给  类，且必须提供 @code{zipfile.ZipFile} 类所需的方法。


3.7 新版功能: 加入了 @emph{filter} 和 @emph{compressed} 参数。

@end deffn

@geindex get_interpreter() (在 zipapp 模块中)
@anchor{library/zipapp zipapp get_interpreter}@anchor{36a1}
@deffn {函数} zipapp.get_interpreter (archive)

返回打包文件开头的  行指定的解释器程序。如果没有 @code{#!} 行，则返回 @ref{204,,None}。参数 @emph{archive} 可为文件名或在字节串模式下打开以供读取的文件类对象。@code{#!} 行假定是在打包文件的开头。
@end deffn

@node 示例<42>,指定解释器程序,Python API,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp examples}@anchor{36a2}@anchor{library/zipapp zipapp-examples}@anchor{36a3}
@subsubsection 示例


将目录打包成一个文件并运行它。

@example
$ python -m zipapp myapp
$ python myapp.pyz
<output from myapp>
@end example

同样还可用 @ref{529,,create_archive()} 函数完成：

@example
>>> import zipapp
>>> zipapp.create_archive('myapp', 'myapp.pyz')
@end example

要让应用程序能在 POSIX 平台上直接执行，需要指定所用的解释器。

@example
$ python -m zipapp myapp -p "/usr/bin/env python"
$ ./myapp.pyz
<output from myapp>
@end example

若要替换已有打包文件中的释伴行，请用 @ref{529,,create_archive()} 函数另建一个修改好的打包文件：

@example
>>> import zipapp
>>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')
@end example

若要原地更新打包文件，可用 @code{BytesIO} 对象在内存中进行替换，然后再覆盖源文件。注意，原地覆盖文件会有风险，出错时会丢失原文件。这里没有考虑出错情况，但生产代码则应进行处理。另外，这种方案仅当内存足以容纳打包文件时才有意义：

@example
>>> import zipapp
>>> import io
>>> temp = io.BytesIO()
>>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')
>>> with open('myapp.pyz', 'wb') as f:
>>>     f.write(temp.getvalue())
@end example

@node 指定解释器程序,用 zipapp 创建独立运行的应用程序,示例<42>,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp specifying-the-interpreter}@anchor{36a4}@anchor{library/zipapp zipapp-specifying-the-interpreter}@anchor{36a5}
@subsubsection 指定解释器程序


注意，如果指定了解释器程序再发布应用程序打包文件，需要确保所用到的解释器是可移植的。Windows 的 Python 启动器支持大多数常见的 POSIX @code{#!} 行，但还需要考虑一些其他问题。


@itemize *

@item 
如果采用“/usr/bin/env python”（或其他格式的 python 调用命令，比如“/usr/bin/python”)，需要考虑默认版本既可能是 Python 2 又可能是 Python 3，应让代码在两个版本下均能正常运行。

@item 
如果用到的 Python 版本明确，如“/usr/bin/env python3”，则没有该版本的用户将无法运行应用程序。（如果代码不兼容 Python 2，可能正该如此）。

@item 
因为无法指定“python X.Y以上版本”，所以应小心“/usr/bin/env python3.4”这种精确版本的指定方式，因为对于 Python 3.5 的用户就得修改释伴行，比如：
@end itemize

通常应该用“/usr/bin/env python2”或“/usr/bin/env python3”的格式，具体根据代码适用于 Python 2 还是 3 而定。

@node 用 zipapp 创建独立运行的应用程序,Python 打包应用程序的格式,指定解释器程序,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp creating-standalone-applications-with-zipapp}@anchor{36a6}
@subsubsection 用 zipapp 创建独立运行的应用程序


利用 @ref{14a,,zipapp} 模块可以创建独立运行的 Python 程序，以便向最终用户发布，仅需在系统中装有合适版本的 Python 即可运行。操作的关键就是把应用程序代码和所有依赖项一起放入打包文件中。

创建独立运行打包文件的步骤如下：


@enumerate 

@item 
照常在某个目录中创建应用程序，于是会有一个 @code{myapp} 目录，里面有个`@w{`}__main__.py`@w{`} 文件，以及所有支持性代码。

@item 
用 pip 将应用程序的所有依赖项装入 @code{myapp} 目录。

@example
$ python -m pip install -r requirements.txt --target myapp
@end example

（这里假定在 @code{requirements.txt} 文件中列出了项目所需的依赖项，也可以在 pip 命令行中列出依赖项）。

@item 
pip 在 @code{myapp} 中创建的 @code{.dist-info} 目录，是可以删除的。这些目录保存了 pip 用于管理包的元数据，由于接下来不会再用到 pip，所以不是必须存在，当然留下来也不会有什么坏处。

@item 
用以下命令打包：

@example
$ python -m zipapp -p "interpreter" myapp
@end example
@end enumerate

这会生成一个独立的可执行文件，可在任何装有合适解释器的机器上运行。详情参见 @ref{36a5,,指定解释器程序}。可以单个文件的形式分发给用户。

在 Unix 系统中，@code{myapp.pyz} 文件将以原有文件名执行。如果喜欢 “普通”的命令名，可以重命名该文件，去掉扩展名 @code{.pyz} 。在 Windows 系统中，@code{myapp.pyz[w]} 是可执行文件，因为 Python 解释器在安装时注册了扩展名`@w{`}.pyz`@w{`} 和 @code{.pyzw} 。

@menu
* 制作 Windows 可执行文件:: 
* 注意事项:: 

@end menu

@node 制作 Windows 可执行文件,注意事项,,用 zipapp 创建独立运行的应用程序
@anchor{library/zipapp making-a-windows-executable}@anchor{36a7}
@subsubsection 制作 Windows 可执行文件


在 Windows 系统中，可能没有注册扩展名 @code{.pyz}，另外有些场合无法“透明”地识别已注册的扩展（最简单的例子是，@code{subprocess.run(['myapp'])} 就找不到——需要明确指定扩展名）。

因此，在 Windows 系统中，通常最好 由zipapp 创建一个可执行文件。虽然需要用到 C 编译器，但还是相对容易做到的。基本做法有赖于以下事实，即 zip 文件内可预置任意数据，Windows 的 exe 文件也可以附带任意数据。因此，创建一个合适的启动程序并将 @code{.pyz} 文件附在后面，最后就能得到一个单文件的可执行文件，可运行 Python 应用程序。

合适的启动程序可以简单如下：

@example
#define Py_LIMITED_API 1
#include "Python.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#ifdef WINDOWS
int WINAPI wWinMain(
    HINSTANCE hInstance,      /* handle to current instance */
    HINSTANCE hPrevInstance,  /* handle to previous instance */
    LPWSTR lpCmdLine,         /* pointer to command line */
    int nCmdShow              /* show state of window */
)
#else
int wmain()
#endif
@{
    wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*));
    myargv[0] = __wargv[0];
    memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *));
    return Py_Main(__argc+1, myargv);
@}
@end example

若已定义了预处理器符号 @code{WINDOWS}，上述代码将会生成一个 GUI 可执行文件。若未定义则生成一个可执行的控制台文件。

直接使用标准的 MSVC 命令行工具，或利用 distutils 知道如何编译 Python 源代码，即可编译可执行文件：

@example
>>> from distutils.ccompiler import new_compiler
>>> import distutils.sysconfig
>>> import sys
>>> import os
>>> from pathlib import Path

>>> def compile(src):
>>>     src = Path(src)
>>>     cc = new_compiler()
>>>     exe = src.stem
>>>     cc.add_include_dir(distutils.sysconfig.get_python_inc())
>>>     cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs'))
>>>     # First the CLI executable
>>>     objs = cc.compile([str(src)])
>>>     cc.link_executable(objs, exe)
>>>     # Now the GUI executable
>>>     cc.define_macro('WINDOWS')
>>>     objs = cc.compile([str(src)])
>>>     cc.link_executable(objs, exe + 'w')

>>> if __name__ == "__main__":
>>>     compile("zastub.c")
@end example

生成的启动程序用到了 “受限 ABI”，所以可在任意版本的 Python 3.x 中运行。只要用户的 @code{PATH} 中包含了 Python（@code{python3.dll}）路径即可。

若要得到完全独立运行的发行版程序，可将附有应用程序的启动程序，与“内嵌版” Python 打包在一起即可。这样在架构匹配（32位或64位）的任一 PC 上都能运行。

@node 注意事项,,制作 Windows 可执行文件,用 zipapp 创建独立运行的应用程序
@anchor{library/zipapp caveats}@anchor{36a8}
@subsubsection 注意事项


要将应用程序打包为单个文件，存在一些限制。大多数情况下，无需对应用程序进行重大修改即可解决。


@enumerate 

@item 
如果应用程序依赖某个带有 C 扩展的包，则此程序包无法由打包文件运行（这是操作系统的限制，因为可执行代码必须存在于文件系统中，操作系统才能加载）。这时可去除打包文件中的依赖关系，然后要求用户事先安装好该程序包，或者与打包文件一起发布并在 @code{__main__.py} 中增加代码，将未打包模块的目录加入 @code{sys.path} 中。采用增加代码方式时，一定要为目标架构提供合适的二进制文件（可能还需在运行时根据用户的机器选择正确的版本加入 @code{sys.path}）。

@item 
若要如上所述发布一个 Windows 可执行文件，就得确保用户在 PATH 中包含`@w{`}python3.dll`@w{`} 的路径（安装程序默认不会如此），或者应把应用程序与内嵌版 Python 一起打包。

@item 
上述给出的启动程序采用了 Python 嵌入 API。 这意味着应用程序将会是 @code{sys.executable} ，而*不是*传统的 Python 解释器。代码及依赖项需做好准备。例如，如果应用程序用到了 @ref{b7,,multiprocessing} 模块，就需要调用 @ref{2539,,multiprocessing.set_executable()} 来让模块知道标准 Python 解释器的位置。
@end enumerate

@node Python 打包应用程序的格式,,用 zipapp 创建独立运行的应用程序,zipapp —— 管理可执行的 Python zip 打包文件
@anchor{library/zipapp the-python-zip-application-archive-format}@anchor{36a9}
@subsubsection Python 打包应用程序的格式


自 2.6 版开始，Python 即能够执行包含  文件的打包文件了。为了能被 Python 执行，应用程序的打包文件必须为包含 @code{__main__.py} 文件的标准 zip 文件，@code{__main__.py} 文件将作为应用程序的入口运行。类似于常规的 Python 脚本，父级（这里指打包文件）将放入 @ref{262,,sys.path} ，因此可从打包文件中导入更多的模块。

zip 文件格式允许在文件中预置任意数据。利用这种能力，zip 应用程序格式在文件中预置了一个标准的 POSIX “释伴”行（@code{#!/path/to/interpreter}）。

因此，Python zip 应用程序的格式会如下所示：


@enumerate 

@item 
可选的释伴行，包含字符 @code{b'#!'}，后面是解释器名，然后是换行符 （@code{b'\n'}）。 解释器名可为操作系统 “释伴”处理所能接受的任意值，或为 Windows 系统中的 Python 启动程序。解释器名在 Windows 中应用 UTF-8 编码，在 POSIX 中则用 @ref{5f8,,sys.getfilesystemencoding()}。

@item 
标准的打包文件由 @ref{14b,,zipfile} 模块生成。其中 @emph{必须} 包含一个名为`@w{`}__main__.py`@w{`} 的文件（必须位于打包文件的“根”目录——不能位于某个子目录中）。打包文件中的数据可以是压缩或未压缩的。
@end enumerate

如果应用程序的打包文件带有释伴行，则在 POSIX 系统中可能需要启用可执行属性，以允许直接执行。

不一定非要用本模块中的工具创建应用程序打包文件，本模块只是提供了便捷方案，上述格式的打包文件可用任何方式创建，均可被 Python 接受。

@node Python运行时服务,自定义 Python 解释器,软件打包和分发,Python 标准库
@anchor{library/python doc}@anchor{36aa}@anchor{library/python python}@anchor{36ab}@anchor{library/python python-runtime-services}@anchor{36ac}
@section Python运行时服务


本章里描述的模块提供了和Python解释器及其环境交互相关的广泛服务。以下是综述：

@menu
* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig —— 提供对 Python 配置信息的访问支持:: 
* builtins: builtins --- 内建对象. 内建对象
* __main__: __main__ --- 顶层脚本环境. 顶层脚本环境
* warnings —— 警告信息的控制:: 
* dataclasses: dataclasses --- 数据类. 数据类
* contextlib: contextlib --- 为 with语句上下文提供的工具. 为 with语句上下文提供的工具
* abc: abc --- 抽象基类. 抽象基类
* atexit: atexit --- 退出处理器. 退出处理器
* traceback: traceback --- 打印或检索堆栈回溯. 打印或检索堆栈回溯
* __future__: __future__ --- Future 语句定义. Future 语句定义
* gc: gc --- 垃圾回收器接口. 垃圾回收器接口
* inspect: inspect --- 检查对象. 检查对象
* site —— 指定域的配置钩子:: 

@end menu

@node sys --- 系统相关的参数和函数,sysconfig —— 提供对 Python 配置信息的访问支持,,Python运行时服务
@anchor{library/sys doc}@anchor{36ad}@anchor{library/sys module-sys}@anchor{fd}@anchor{library/sys sys-system-specific-parameters-and-functions}@anchor{36ae}
@subsection @code{sys} --- 系统相关的参数和函数


@geindex sys (模块)


__________________________________________________________________


该模块提供了一些变量和函数。这些变量可能被解释器使用，也可能由解释器提供。这些函数会影响解释器。本模块总是可用的。

@geindex abiflags() (在 sys 模块中)
@anchor{library/sys sys abiflags}@anchor{395}
@deffn {数据} sys.abiflags

在POSIX系统上，以标准的 @code{configure} 脚本构建的 Python 中，这个变量会包含 
@geindex Python 提高建议; PEP 3149
PEP 3149@footnote{https://www.python.org/dev/peps/pep-3149} 中定义的ABI标签。


在 3.8 版更改: 默认的 flags 变为了空字符串（用于 pymalloc 的 @code{m} 旗标已经移除）



3.2 新版功能.

@end deffn

@geindex addaudithook() (在 sys 模块中)
@anchor{library/sys sys addaudithook}@anchor{354f}
@deffn {函数} sys.addaudithook (hook)

将可调用对象 @emph{hook} 附加到当前（子）解释器的活动的审计钩子列表中。

当通过 @ref{109f,,sys.audit()} 函数引发审计事件时，每个钩子将按照其被加入的先后顺序被调用，调用时会传入事件名称和参数元组。 由 @ref{3550,,PySys_AddAuditHook()} 添加的原生钩子会先被调用，然后是当前（子）解释器中添加的钩子。 接下来这些钩子会记录事件，引发异常来中止操作，或是完全终止进程。

调用 @ref{354f,,sys.addaudithook()} 时它自身将引发一个名为 @code{sys.addaudithook} 的审计事件且不附带参数。 如果任何现有的钩子引发了派生自 @ref{3e4,,RuntimeError} 的异常，则新的钩子不会被添加并且该异常会被抑制。 其结果就是，调用者无法确保他们的钩子已经被添加，除非他们控制了全部现有的钩子。

请参阅 @ref{354c,,审计事件表} 以获取由 CPython 引发的所有事件，并参阅 
@geindex Python 提高建议; PEP 578
PEP 578@footnote{https://www.python.org/dev/peps/pep-0578} 了解最初的设计讨论。


3.8 新版功能.



在 3.8.1 版更改: 派生自 @ref{2e3,,Exception} （而非 @ref{3e4,,RuntimeError} ）的异常不会被抑制。


@strong{CPython implementation detail:} 启用跟踪时（参阅 @ref{f08,,settrace()} ），仅当可调用对象（钩子）的 @code{__cantrace__} 成员设置为 true 时，才会跟踪该钩子。否则，跟踪功能将跳过该钩子。
@end deffn

@geindex argv() (在 sys 模块中)
@anchor{library/sys sys argv}@anchor{cce}
@deffn {数据} sys.argv

一个列表，其中包含了被传递给 Python 脚本的命令行参数。 @code{argv[0]} 为脚本的名称（是否是完整的路径名取决于操作系统）。如果是通过 Python 解释器的命令行参数 @ref{136f,,-c} 来执行的， @code{argv[0]} 会被设置成字符串 @code{'-c'} 。如果没有脚本名被传递给 Python 解释器， @code{argv[0]} 为空字符串。

为了遍历标准输入，或者通过命令行传递的文件列表，参照 @ref{7e,,fileinput} 模块

@cartouche
@quotation 注解 
在 Unix 上，系统传递的命令行参数是字节类型的。Python 使用文件系统编码和 "surrogateescape" 错误处理方案对它们进行解码。当需要原始字节时，可以通过 @code{[os.fsencode(arg) for arg in sys.argv]} 来获取。
@end quotation
@end cartouche
@end deffn
@anchor{library/sys auditing}@anchor{fec}
@geindex audit() (在 sys 模块中)
@anchor{library/sys sys audit}@anchor{109f}
@deffn {函数} sys.audit (event, *args)

@geindex auditing

引发一个审计事件并触发任何激活的审计钩子。 @emph{event} 是一个用于标识事件的字符串，@emph{args} 会包含有关事件的更多信息的可选参数。 特定事件的参数的数量和类型会被视为是公有的稳定 API 且不应当在版本之间进行修改。

例如，有一个审计事件的名称为 @code{os.chdir}。 此事件具有一个名为 @emph{path} 的参数，该参数将包含所请求的新工作目录。

@ref{109f,,sys.audit()} 将调用现有的审计钩子，传入事件名称和参数，并将重新引发来自任何钩子的第一个异常。 通常来说，如果有一个异常被引发，则它不应当被处理且其进程应当被尽可能快地终止。 这将允许钩子实现来决定对特定事件要如何反应：它们可以只是将事件写入日志或是通过引发异常来中止操作。

钩子程序由 @ref{354f,,sys.addaudithook()} 或 @ref{3550,,PySys_AddAuditHook()} 函数添加。

与本函数相等效的原生函数是 @ref{10b1,,PySys_Audit()}，应尽量使用原生函数。

参阅 @ref{354c,,审计事件表} 以获取 CPython 定义的所有审计事件。


3.8 新版功能.

@end deffn

@geindex base_exec_prefix() (在 sys 模块中)
@anchor{library/sys sys base_exec_prefix}@anchor{3688}
@deffn {数据} sys.base_exec_prefix

在 @code{site.py} 运行之前， Python 启动的时候被设置为跟 @ref{3687,,exec_prefix} 同样的值。如果不是运行在 @ref{3685,,虚拟环境} 中，两个值会保持相同；如果 @code{site.py} 发现处于一个虚拟环境中， @ref{3686,,prefix} 和 @ref{3687,,exec_prefix} 将会指向虚拟环境。然而 @ref{305e,,base_prefix} 和 @ref{3688,,base_exec_prefix} 将仍然会指向基础的 Python 环境（用来创建虚拟环境的 Python 环境）


3.3 新版功能.

@end deffn

@geindex base_prefix() (在 sys 模块中)
@anchor{library/sys sys base_prefix}@anchor{305e}
@deffn {数据} sys.base_prefix

在 @code{site.py} 运行之前， Python 启动的时候被设置为跟 @ref{3686,,prefix} 同样的值。如果不是运行在 @ref{3685,,虚拟环境} 中, 两个值会保持相同；如果 @code{site.py} 发现处于一个虚拟环境中， @ref{3686,,prefix} 和 @ref{3687,,exec_prefix} 将会指向虚拟环境。然而 @ref{305e,,base_prefix} 和 @ref{3688,,base_exec_prefix} 将仍然会指向基础的 Python 环境（用来创建虚拟环境的 Python 环境）


3.3 新版功能.

@end deffn

@geindex byteorder() (在 sys 模块中)
@anchor{library/sys sys byteorder}@anchor{1785}
@deffn {数据} sys.byteorder

本地字节顺序的指示符。在大端序（最高有效位优先）操作系统上值为 @code{'big'} ，在小端序（最低有效位优先）操作系统上为 @code{'little'} 。
@end deffn

@geindex builtin_module_names() (在 sys 模块中)
@anchor{library/sys sys builtin_module_names}@anchor{13e7}
@deffn {数据} sys.builtin_module_names

一个元素为字符串的元组。包含了所有的被编译进 Python 解释器的模块。（这个信息无法通过其他的办法获取， @code{modules.keys()} 只包括被导入过的模块。）
@end deffn

@geindex call_tracing() (在 sys 模块中)
@anchor{library/sys sys call_tracing}@anchor{36af}
@deffn {函数} sys.call_tracing (func, args)

在启用跟踪时调用 @code{func(*args)}  来保存跟踪状态，然后恢复跟踪状态。这将从检查点的调试器调用，以便递归地调试其他的一些代码。
@end deffn

@geindex copyright() (在 sys 模块中)
@anchor{library/sys sys copyright}@anchor{36b0}
@deffn {数据} sys.copyright

一个字符串，包含了 Python 解释器有关的版权信息
@end deffn

@geindex _clear_type_cache() (在 sys 模块中)
@anchor{library/sys sys _clear_type_cache}@anchor{36b1}
@deffn {函数} sys._clear_type_cache ()

清除内部的类型缓存。类型缓存是为了加速查找方法和属性的。在调试引用泄漏的时候调用这个函数 @emph{只会} 清除不必要的引用。

这个函数应该只在内部为了一些特定的目的使用。
@end deffn

@geindex _current_frames() (在 sys 模块中)
@anchor{library/sys sys _current_frames}@anchor{e68}
@deffn {函数} sys._current_frames ()

返回一个字典，存放着每个线程的标识符与（调用本函数时）该线程栈顶的帧（当前活动的帧）之间的映射。注意 @ref{11c,,traceback} 模块中的函数可以在给定某一帧的情况下构建调用堆栈。

这对于调试死锁最有用：本函数不需要死锁线程的配合，并且只要这些线程的调用栈保持死锁，它们就是冻结的。在调用本代码来检查栈顶的帧的那一刻，非死锁线程返回的帧可能与该线程当前活动的帧没有任何关系。

这个函数应该只在内部为了一些特定的目的使用。

引发一个 @ref{fec,,审计事件} @code{sys._current_frames}，没有附带参数。
@end deffn

@geindex breakpointhook() (在 sys 模块中)
@anchor{library/sys sys breakpointhook}@anchor{42c}
@deffn {函数} sys.breakpointhook ()

本钩子函数由内建函数 @ref{414,,breakpoint()} 调用。默认情况下，它将进入 @ref{c9,,pdb} 调试器，但可以将其改为任何其他函数，以选择使用哪个调试器。

该函数的特征取决于其调用的函数。例如，默认绑定（即 @code{pdb.set_trace()} ）不要求提供参数，但可以将绑定换成要求提供附加参数（位置参数/关键字参数）的函数。内建函数 @code{breakpoint()} 直接将其 @code{*args} 和 @code{**kws} 传入。@code{breakpointhooks()} 返回的所有内容都会从 @code{breakpoint()} 返回。

默认的实现首先会查询环境变量 
@geindex PYTHONBREAKPOINT
@geindex 环境变量; PYTHONBREAKPOINT
@ref{42d,,PYTHONBREAKPOINT}。如果将该变量设置为 @code{"0"}，则本函数立即返回，表示在断点处无操作。如果未设置该环境变量或将其设置为空字符串，则调用 @code{pdb.set_trace()}。否则，此变量应指定要运行的函数，指定函数时应使用 Python 的点导入命名法，如 @code{package.subpackage.module.function}。这种情况下将导入 @code{package.subpackage.module}，且导入的模块必须有一个名为 @code{function()} 的可调用对象。该可调用对象会运行，@code{*args} 和 @code{**kws} 会传入，且无论 @code{function()} 返回什么，@code{sys.breakpointhook()} 都将返回到內建函数 @ref{414,,breakpoint()}。

请注意，如果在导入 
@geindex PYTHONBREAKPOINT
@geindex 环境变量; PYTHONBREAKPOINT
@ref{42d,,PYTHONBREAKPOINT} 指定的可调用对象时出错，则将报告一个 @ref{3ea,,RuntimeWarning} 并忽略断点。

另请注意，如果以编程方式覆盖 @code{sys.breakpointhook()}，则 @emph{不会} 查询 
@geindex PYTHONBREAKPOINT
@geindex 环境变量; PYTHONBREAKPOINT
@ref{42d,,PYTHONBREAKPOINT}。


3.7 新版功能.

@end deffn

@geindex _debugmallocstats() (在 sys 模块中)
@anchor{library/sys sys _debugmallocstats}@anchor{36b2}
@deffn {函数} sys._debugmallocstats ()

将有关 CPython 内存分配器状态的底层的信息打印至 stderr。

如果 Python 被配置为 --with-pydebug，本方法还将执行一些开销较大的内部一致性检查。


3.3 新版功能.


@strong{CPython implementation detail:} 本函数仅限 CPython。此处没有定义确切的输出格式，且可能会更改。
@end deffn

@geindex dllhandle() (在 sys 模块中)
@anchor{library/sys sys dllhandle}@anchor{36b3}
@deffn {数据} sys.dllhandle

指向 Python DLL 句柄的整数。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex displayhook() (在 sys 模块中)
@anchor{library/sys sys displayhook}@anchor{f28}
@deffn {函数} sys.displayhook (value)

如果 @emph{value} 不是 @code{None}，则本函数会将 @code{repr(value)} 打印至 @code{sys.stdout}，并将 @emph{value} 保存在 @code{builtins._} 中。如果 @code{repr(value)} 无法用 @code{sys.stdout.errors} 错误处理方案（可能为 @code{'strict'} ）编码为 @code{sys.stdout.encoding}，则用 @code{'backslashreplace'} 错误处理方案将其编码为 @code{sys.stdout.encoding}。

在交互式 Python 会话中运行 @ref{15be,,expression} 产生结果后，将在结果上调用 @code{sys.displayhook}。若要自定义这些 value 的显示，可以将 @code{sys.displayhook} 指定为另一个单参数函数。

伪代码:

@example
def displayhook(value):
    if value is None:
        return
    # Set '_' to None to avoid recursion
    builtins._ = None
    text = repr(value)
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            text = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value
@end example


在 3.2 版更改: 在发生 @ref{331,,UnicodeEncodeError} 时使用 @code{'backslashreplace'} 错误处理方案。

@end deffn

@geindex dont_write_bytecode() (在 sys 模块中)
@anchor{library/sys sys dont_write_bytecode}@anchor{36b4}
@deffn {数据} sys.dont_write_bytecode

如果该值为 true，则 Python 在导入源码模块时将不会尝试写入 @code{.pyc} 文件。该值会被初始化为 @code{True} 或 @code{False}，依据是 @ref{e06,,-B} 命令行选项和 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE} 环境变量，可以自行设置该值，来控制是否生成字节码文件。
@end deffn

@geindex pycache_prefix() (在 sys 模块中)
@anchor{library/sys sys pycache_prefix}@anchor{298}
@deffn {数据} sys.pycache_prefix

如果将该值设为某个目录（不是 @code{None} ），Python 会将字节码缓存文件 @code{.pyc} 写入到以该目录为根的并行目录树中（并从中读取），而不是在源码树中的 @code{__pycache__} 目录下读写。源码树中所有的 @code{__pycache__} 目录都将被忽略，并将在 pycache prefix 内写入新的 @cite{.pyc} 文件。因此，如果使用 @ref{20,,compileall} 作为预构建步骤，则必须确保预构建时使用的 pycache prefix （如果有）与将来运行的时候相同。

相对路径将解释为相对于当前工作目录。

该值的初值设置，依据 @ref{297,,-X} @code{pycache_prefix=PATH} 命令行选项或 
@geindex PYTHONPYCACHEPREFIX
@geindex 环境变量; PYTHONPYCACHEPREFIX
@ref{296,,PYTHONPYCACHEPREFIX} 环境变量的值（命令行优先）。如果两者均未设置，则为 @code{None}。


3.8 新版功能.

@end deffn

@geindex excepthook() (在 sys 模块中)
@anchor{library/sys sys excepthook}@anchor{1ae}
@deffn {函数} sys.excepthook (type, value, traceback)

本函数会将所给的回溯和异常输出到 @code{sys.stderr} 中。

当抛出一个异常，且未被捕获时，解释器将调用 @code{sys.excepthook} 并带有三个参数：异常类、异常实例和一个回溯对象。在交互式会话中，这会在控制权返回到提示符之前发生。在 Python 程序中，这会在程序退出之前发生。如果要自定义此类顶级异常的处理过程，可以将另一个 3 个参数的函数赋给 @code{sys.excepthook}。

引发一个 @ref{fec,,审计事件} @code{sys.excepthook}，附带参数 @code{hook}, @code{type}, @code{value}, @code{traceback}。


@subsubheading 参见


@ref{361,,sys.unraisablehook()} 函数处理无法抛出的异常，@ref{365,,threading.excepthook()} 函数处理 @ref{366,,threading.Thread.run()} 抛出的异常。

@end deffn

@geindex __breakpointhook__() (在 sys 模块中)
@geindex __displayhook__() (在 sys 模块中)
@geindex __excepthook__() (在 sys 模块中)
@geindex __unraisablehook__() (在 sys 模块中)
@anchor{library/sys sys __breakpointhook__}@anchor{36b5}
@deffn {数据} sys.__breakpointhook__
@anchor{library/sys sys __displayhook__}@anchor{36b6}
@deffnx {数据} sys.__displayhook__
@anchor{library/sys sys __excepthook__}@anchor{36b7}
@deffnx {数据} sys.__excepthook__
@anchor{library/sys sys __unraisablehook__}@anchor{36b8}
@deffnx {数据} sys.__unraisablehook__

程序开始时，这些对象存有 @code{breakpointhook}、@code{displayhook}、@code{excepthook} 和 @code{unraisablehook} 的初始值。保存它们是为了可以在 @code{breakpointhook}、@code{displayhook} 和 @code{excepthook}、@code{unraisablehook} 被破坏或被替换时恢复它们。


3.7 新版功能: __breakpointhook__



3.8 新版功能: __unraisablehook__

@end deffn

@geindex exc_info() (在 sys 模块中)
@anchor{library/sys sys exc_info}@anchor{d2f}
@deffn {函数} sys.exc_info ()

本函数返回的元组包含三个值，它们给出当前正在处理的异常的信息。返回的信息仅限于当前线程和当前堆栈帧。如果当前堆栈帧没有正在处理的异常，则信息将从下级被调用的堆栈帧或上级调用者等位置获取，依此类推，直到找到正在处理异常的堆栈帧为止。此处的“处理异常”指的是“执行 except 子句”。任何堆栈帧都只能访问当前正在处理的异常的信息。

@geindex 对象; traceback

如果整个堆栈都没有正在处理的异常，则返回包含三个 @code{None} 值的元组。否则返回值为 @code{(type, value, traceback)}。它们的含义是：@emph{type} 是正在处理的异常类型（它是 @ref{2e2,,BaseException} 的子类）；@emph{value} 是异常实例（异常类型的实例）；@emph{traceback} 是一个 @ref{44b,,回溯对象}，该对象封装了最初发生异常时的调用堆栈。
@end deffn

@geindex exec_prefix() (在 sys 模块中)
@anchor{library/sys sys exec_prefix}@anchor{3687}
@deffn {数据} sys.exec_prefix

一个字符串，提供特定域的目录前缀，该目录中安装了与平台相关的 Python 文件，默认也是 @code{'/usr/local'}。该目录前缀可以在构建时使用 @code{configure} 脚本的 @code{--exec-prefix} 参数进行设置。具体而言，所有配置文件（如 @code{pyconfig.h} 头文件）都安装在目录 @code{@emph{exec_prefix}/lib/python@emph{X.Y}/config} 中，共享库模块安装在 @code{@emph{exec_prefix}/lib/python@emph{X.Y}/lib-dynload} 中，其中 @emph{X.Y} 是 Python 的版本号，如 @code{3.2}。

@cartouche
@quotation 注解 
如果在一个 @ref{3685,,虚拟环境} 中，那么该值将在 @code{site.py} 中被修改，指向虚拟环境。Python 安装位置仍然可以用 @ref{3688,,base_exec_prefix} 来获取。
@end quotation
@end cartouche
@end deffn

@geindex executable() (在 sys 模块中)
@anchor{library/sys sys executable}@anchor{3a5}
@deffn {数据} sys.executable

一个字符串，提供 Python 解释器的可执行二进制文件的绝对路径，仅在部分系统中此值有意义。如果 Python 无法获取其可执行文件的真实路径，则 @ref{3a5,,sys.executable} 将为空字符串或 @code{None}。
@end deffn

@geindex exit() (在 sys 模块中)
@anchor{library/sys sys exit}@anchor{db2}
@deffn {函数} sys.exit ([arg])

引发一个 @ref{6fd,,SystemExit} 异常，表示打算退出解释器。

可选参数 @emph{arg} 可以是表示退出状态的整数（默认为 0），也可以是其他类型的对象。如果它是整数，则 shell 等将 0 视为“成功终止”，非零值视为“异常终止”。大多数系统要求该值的范围是 0--127，否则会产生不确定的结果。某些系统为退出代码约定了特定的含义，但通常尚不完善；Unix 程序通常用 2 表示命令行语法错误，用 1 表示所有其他类型的错误。传入其他类型的对象，如果传入 @code{None} 等同于传入 0，如果传入其他对象则将其打印至 @ref{1eb,,stderr}，且退出代码为 1。特别地，@code{sys.exit("some error message")} 可以在发生错误时快速退出程序。

由于 @ref{1773,,exit()} 最终 "只" 引发了一个异常，它只在从主线程调用时退出进程，而异常不会被拦截。 @ref{e3f,,try} 语句的 finally 子句所指定的清理动作会被遵守，并且有可能在外层拦截退出的尝试。


在 3.6 版更改: 在 Python 解释器捕获 @ref{6fd,,SystemExit} 后，如果在清理中发生错误（如清除标准流中的缓冲数据时出错），则退出状态码将变为 120。

@end deffn

@geindex flags() (在 sys 模块中)
@anchor{library/sys sys flags}@anchor{c17}
@deffn {数据} sys.flags

@ref{b84,,具名元组} @emph{flags} 含有命令行标志的状态。这些属性是只读的。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

标志

@item

@code{debug}

@tab

@ref{14a6,,-d}

@item

@ref{a0,,inspect}

@tab

@ref{ee9,,-i}

@item

@code{interactive}

@tab

@ref{ee9,,-i}

@item

@code{isolated}

@tab

@ref{232,,-I}

@item

@code{optimize}

@tab

@ref{788,,-O} 或 @ref{789,,-OO}

@item

@ref{36b4,,dont_write_bytecode}

@tab

@ref{e06,,-B}

@item

@code{no_user_site}

@tab

@ref{de3,,-s}

@item

@code{no_site}

@tab

@ref{c00,,-S}

@item

@code{ignore_environment}

@tab

@ref{231,,-E}

@item

@code{verbose}

@tab

@ref{e55,,-v}

@item

@code{bytes_warning}

@tab

@ref{522,,-b}

@item

@code{quiet}

@tab

@ref{14a9,,-q}

@item

@code{hash_randomization}

@tab

@ref{1211,,-R}

@item

@code{dev_mode}

@tab

@ref{297,,-X dev} (@ref{160,,Python 开发模式})

@item

@code{utf8_mode}

@tab

@ref{297,,-X utf8}

@item

@code{int_max_str_digits}

@tab

@ref{297,,-X int_max_str_digits} (@ref{288,,integer string conversion length limitation})

@end multitable



在 3.2 版更改: 为新的 @ref{14a9,,-q} 标志添加了 @code{quiet} 属性



3.2.3 新版功能: @code{hash_randomization} 属性



在 3.3 版更改: 删除了过时的 @code{division_warning} 属性



在 3.4 版更改: 为 @ref{232,,-I} @code{isolated} 标志添加了 @code{isolated} 属性。



在 3.7 版更改: 为新的 @ref{160,,Python 开发模式} 添加了 @code{dev_mode} 属性，为新的 @ref{297,,-X} @code{utf8} 标志添加了 @code{utf8_mode} 属性。



在 3.9.14 版更改: Added the @code{int_max_str_digits} attribute.

@end deffn

@geindex float_info() (在 sys 模块中)
@anchor{library/sys sys float_info}@anchor{1145}
@deffn {数据} sys.float_info

一个 @ref{b84,,具名元组}，存有浮点型的相关信息。它包含的是关于精度和内部表示的底层信息。这些值与标准头文件 @code{float.h} 中为 C 语言定义的各种浮点常量对应，详情请参阅 1999 ISO/IEC C 标准 @ref{36b9,,[C99]} 的 5.2.4.2.2 节，'Characteristics of floating types（浮点型的特性）'。


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

float.h 宏

@tab

说明

@item

@code{epsilon}

@tab

DBL_EPSILON

@tab

大于 1.0 的最小值和 1.0 之间的差，表示为浮点数

另请参阅 @ref{1c2,,math.ulp()}。

@item

@code{dig}

@tab

DBL_DIG

@tab

浮点数可以真实表示的最大十进制数字；见下文

@item

@code{mant_dig}

@tab

DBL_MANT_DIG

@tab

浮点数精度：@code{radix} 基数下的浮点数有效位数

@item

@ref{901,,max}

@tab

DBL_MAX

@tab

可表示的最大正浮点数（非无穷）

@item

@code{max_exp}

@tab

DBL_MAX_EXP

@tab

使得 @code{radix**(e-1)} 是可表示的浮点数（非无穷）的最大整数 @emph{e}

@item

@code{max_10_exp}

@tab

DBL_MAX_10_EXP

@tab

使得 @code{10**e} 在可表示的浮点数（非无穷）范围内的最大整数 @emph{e}

@item

@ref{900,,min}

@tab

DBL_MIN

@tab

可表示的最小正 @emph{规格化} 浮点数

使用 @ref{1c2,,math.ulp(0.0)} 获取可表示的最小正 @emph{非规格化} 浮点数

@item

@code{min_exp}

@tab

DBL_MIN_EXP

@tab

使得 @code{radix**(e-1)} 是规格化浮点数的最小整数 @emph{e}

@item

@code{min_10_exp}

@tab

DBL_MIN_10_EXP

@tab

使得 @code{10**e} 是规格化浮点数的最小整数 @emph{e}

@item

@code{radix}

@tab

FLT_RADIX

@tab

指数表示法中采用的基数

@item

@code{rounds}

@tab

FLT_ROUNDS

@tab

整数常数，表示算术运算中的舍入方式。它反映了解释器启动时系统的 FLT_ROUNDS 宏的值。关于可能的值及其含义的说明，请参阅 C99 标准 5.2.4.2.2 节。

@end multitable


关于 @code{sys.float_info.dig} 属性的进一步说明。如果 @code{s} 是表示十进制数的字符串，而该数最多有 @code{sys.float_info.dig} 位有效数字，则将 @code{s} 转换为 float 再转回去将恢复原先相同十进制值的字符串:

@example
>>> import sys
>>> sys.float_info.dig
15
>>> s = '3.14159265358979'    # decimal string with 15 significant digits
>>> format(float(s), '.15g')  # convert to float and back -> same value
'3.14159265358979'
@end example

但是对于超过 @code{sys.float_info.dig} 位有效数字的字符串，转换前后并非总是相同:

@example
>>> s = '9876543211234567'    # 16 significant digits is too many!
>>> format(float(s), '.16g')  # conversion changes value
'9876543211234568'
@end example
@end deffn

@geindex float_repr_style() (在 sys 模块中)
@anchor{library/sys sys float_repr_style}@anchor{d60}
@deffn {数据} sys.float_repr_style

一个字符串，反映 @ref{8c3,,repr()} 函数在浮点数上的行为。如果该字符串是 @code{'short'}，那么对于（非无穷的）浮点数 @code{x}，@code{repr(x)} 将会生成一个短字符串，满足 @code{float(repr(x)) == x} 的特性。这是 Python 3.1 及更高版本中的常见行为。否则 @code{float_repr_style} 的值将是 @code{'legacy'}，此时 @code{repr(x)} 的行为方式将与 Python 3.1 之前的版本相同。


3.1 新版功能.

@end deffn

@geindex getallocatedblocks() (在 sys 模块中)
@anchor{library/sys sys getallocatedblocks}@anchor{9d1}
@deffn {函数} sys.getallocatedblocks ()

返回解释器当前已分配的内存块数，无论它们大小如何。本函数主要用于跟踪和调试内存泄漏。因为解释器有内部缓存，所以不同调用之间结果会变化。可能需要调用 @ref{36b1,,_clear_type_cache()} 和 @ref{362,,gc.collect()} 使结果更容易预测。

如果当前 Python 构建或实现无法合理地计算此信息，允许 @ref{9d1,,getallocatedblocks()} 返回 0。


3.4 新版功能.

@end deffn

@geindex getandroidapilevel() (在 sys 模块中)
@anchor{library/sys sys getandroidapilevel}@anchor{4ff}
@deffn {函数} sys.getandroidapilevel ()

返回一个整数，表示 Android 构建时 API 版本。

@ref{14c1,,可用性}：Android。


3.7 新版功能.

@end deffn

@geindex getdefaultencoding() (在 sys 模块中)
@anchor{library/sys sys getdefaultencoding}@anchor{36ba}
@deffn {函数} sys.getdefaultencoding ()

返回当前 Unicode 实现所使用的默认字符串编码名称。
@end deffn

@geindex getdlopenflags() (在 sys 模块中)
@anchor{library/sys sys getdlopenflags}@anchor{f18}
@deffn {函数} sys.getdlopenflags ()

返回当前 @code{dlopen()} 调用所使用的标志位的值。标志值对应的符号名称可以在 @ref{c4,,os} 模块中找到（形如 @code{RTLD_xxx} 的常量，如 @ref{b43,,os.RTLD_LAZY} ）。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex getfilesystemencoding() (在 sys 模块中)
@anchor{library/sys sys getfilesystemencoding}@anchor{5f8}
@deffn {函数} sys.getfilesystemencoding ()

返回编码名称，该编码用于在 Unicode 文件名和 bytes 文件名之间转换。为获得最佳兼容性，任何时候都应使用 str 表示文件名，尽管用字节来表示文件名也是支持的。函数如果需要接受或返回文件名，它应支持 str 或 bytes，并在内部将其转换为系统首选的表示形式。

该编码始终是 ASCII 兼容的。

应使用 @ref{5f2,,os.fsencode()} 和 @ref{5f1,,os.fsdecode()} 来保证所采用的编码和错误处理方案都是正确的。


@itemize *

@item 
在 UTF-8 模式下，任何平台上的编码均为 @code{utf-8}。

@item 
在 macOS 上，编码为 @code{'utf-8'}。

@item 
在 Unix 上，编码是语言环境编码。

@item 
在 Windows 上取决于用户配置，编码可能是 @code{'utf-8'} 或 @code{'mbcs'}。

@item 
在 Android 上，编码为 @code{'utf-8'}。

@item 
在 VxWorks 上，编码为 @code{'utf-8'}。
@end itemize


在 3.2 版更改: @ref{5f8,,getfilesystemencoding()} 的结果将不再有可能是 @code{None}。



在 3.6 版更改: Windows 不再保证会返回 @code{'mbcs'}。详情请参阅 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529} 和 @ref{5fa,,_enablelegacywindowsfsencoding()}。



在 3.7 版更改: 在 UTF-8 模式下返回 'utf-8' 。

@end deffn

@geindex getfilesystemencodeerrors() (在 sys 模块中)
@anchor{library/sys sys getfilesystemencodeerrors}@anchor{695}
@deffn {函数} sys.getfilesystemencodeerrors ()

返回错误处理方案的名称，该错误处理方案将在 Unicode 文件名和 bytes 文件名转换时生效。编码的名称是由 @ref{5f8,,getfilesystemencoding()} 返回的。

应使用 @ref{5f2,,os.fsencode()} 和 @ref{5f1,,os.fsdecode()} 来保证所采用的编码和错误处理方案都是正确的。


3.6 新版功能.

@end deffn

@geindex get_int_max_str_digits() (在 sys 模块中)
@anchor{library/sys sys get_int_max_str_digits}@anchor{1877}
@deffn {函数} sys.get_int_max_str_digits ()

Returns the current value for the @ref{288,,integer string conversion length limitation}. See also @ref{f62,,set_int_max_str_digits()}.


3.9.14 新版功能.

@end deffn

@geindex getrefcount() (在 sys 模块中)
@anchor{library/sys sys getrefcount}@anchor{36bb}
@deffn {函数} sys.getrefcount (object)

返回 @emph{object} 的引用计数。返回的计数通常比预期的多一，因为它包括了作为 @ref{36bb,,getrefcount()} 参数的这一次（临时）引用。
@end deffn

@geindex getrecursionlimit() (在 sys 模块中)
@anchor{library/sys sys getrecursionlimit}@anchor{f42}
@deffn {函数} sys.getrecursionlimit ()

返回当前的递归限制值，即 Python 解释器堆栈的最大深度。此限制可防止无限递归导致的 C 堆栈溢出和 Python 崩溃。该值可以通过 @ref{f43,,setrecursionlimit()} 设置。
@end deffn

@geindex getsizeof() (在 sys 模块中)
@anchor{library/sys sys getsizeof}@anchor{364c}
@deffn {函数} sys.getsizeof (object[, default])

返回对象的大小（以字节为单位）。该对象可以是任何类型。所有内建对象返回的结果都是正确的，但对于第三方扩展不一定正确，因为这与具体实现有关。

只计算直接分配给对象的内存消耗，不计算它所引用的对象的内存消耗。

对象不提供计算大小的方法时，如果传入过 @emph{default} 则返回它，否则抛出 @ref{1ff,,TypeError} 异常。

如果对象由垃圾回收器管理，则 @ref{364c,,getsizeof()} 将调用对象的 @code{__sizeof__} 方法，并在上层添加额外的垃圾回收器。

可以参考 recursive sizeof recipe@footnote{https://code.activestate.com/recipes/577504} 中的示例，关于递归调用 @ref{364c,,getsizeof()} 来得到各个容器及其所有内容物的大小。
@end deffn

@geindex getswitchinterval() (在 sys 模块中)
@anchor{library/sys sys getswitchinterval}@anchor{218}
@deffn {函数} sys.getswitchinterval ()

返回解释器的“线程切换间隔时间”，请参阅 @ref{219,,setswitchinterval()}。


3.2 新版功能.

@end deffn

@geindex _getframe() (在 sys 模块中)
@anchor{library/sys sys _getframe}@anchor{f2c}
@deffn {函数} sys._getframe ([depth])

返回来自调用栈的一个帧对象。如果传入可选整数 @emph{depth}，则返回从栈顶往下相应调用层数的帧对象。如果该数比调用栈更深，则抛出 @ref{16d,,ValueError}。@emph{depth} 的默认值是 0，返回调用栈顶部的帧。

引发一个 @ref{fec,,审计事件} @code{sys._getframe}，没有附带参数。

@strong{CPython implementation detail:} 这个函数应该只在内部为了一些特定的目的使用。不保证它在所有 Python 实现中都存在。
@end deffn

@geindex getprofile() (在 sys 模块中)
@anchor{library/sys sys getprofile}@anchor{e14}
@deffn {函数} sys.getprofile ()

@geindex profile function
@geindex profiler

返回由 @ref{f07,,setprofile()} 设置的性能分析函数。
@end deffn

@geindex gettrace() (在 sys 模块中)
@anchor{library/sys sys gettrace}@anchor{e15}
@deffn {函数} sys.gettrace ()

@geindex trace function
@geindex debugger

返回由 @ref{f08,,settrace()} 设置的跟踪函数。

@strong{CPython implementation detail:} @ref{e15,,gettrace()} 函数仅用于实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而不是语言定义的一部分，因此并非在所有 Python 实现中都可用。
@end deffn

@geindex getwindowsversion() (在 sys 模块中)
@anchor{library/sys sys getwindowsversion}@anchor{696}
@deffn {函数} sys.getwindowsversion ()

返回一个具名元组，描述当前正在运行的 Windows 版本。元素名称包括 @emph{major}, @emph{minor}, @emph{build}, @emph{platform}, @emph{service_pack}, @emph{service_pack_minor}, @emph{service_pack_major}, @emph{suite_mask}, @emph{product_type} 和 @emph{platform_version}。@emph{service_pack} 包含一个字符串，@emph{platform_version} 包含一个三元组，其他所有值都是整数。元素也可以通过名称来访问，所以 @code{sys.getwindowsversion()[0]} 与 @code{sys.getwindowsversion().major} 是等效的。为保持与旧版本的兼容性，只有前 5 个元素可以用索引检索。

@emph{platform} 将会是 @code{2 (VER_PLATFORM_WIN32_NT)}。

@emph{product_type} 可能是以下值之一：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

含义

@item

@code{1 (VER_NT_WORKSTATION)}

@tab

系统是工作站。

@item

@code{2 (VER_NT_DOMAIN_CONTROLLER)}

@tab

系统是域控制器。

@item

@code{3 (VER_NT_SERVER)}

@tab

系统是服务器，但不是域控制器。

@end multitable


本函数包装了 Win32 @code{GetVersionEx()} 函数，参阅 Microsoft 文档有关 @code{OSVERSIONINFOEX()} 的内容可获取这些字段的更多信息。

@emph{platform_version} 返回当前操作系统的主要版本、次要版本和编译版本号，而不是为该进程所模拟的版本。 它旨在用于日志记录而非特性检测。

@cartouche
@quotation 注解 
@emph{platform_version} 会从 kernel32.dll 获取版本号，这个版本可能与 OS 版本不同。 请使用 @ref{ce,,platform} 模块来获取准确的 OS 版本号。
@end quotation
@end cartouche

@ref{14c1,,可用性}: Windows。


在 3.2 版更改: 更改为具名元组，添加 @emph{service_pack_minor}, @emph{service_pack_major}, @emph{suite_mask} 和 @emph{product_type}。



在 3.6 版更改: 添加了 @emph{platform_version}

@end deffn

@geindex get_asyncgen_hooks() (在 sys 模块中)
@anchor{library/sys sys get_asyncgen_hooks}@anchor{36bc}
@deffn {函数} sys.get_asyncgen_hooks ()

返回一个 @emph{asyncgen_hooks} 对象，该对象类似于 @ref{1a1,,namedtuple}，形式为 @cite{(firstiter@comma{} finalizer)}，其中 @emph{firstiter} 和 @emph{finalizer} 为 @code{None} 或函数，函数以 @ref{36bd,,异步生成器迭代器} 作为参数，并用于在事件循环中干预异步生成器的终结。


3.6 新版功能: 详情请参阅 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525}。


@cartouche
@quotation 注解 
本函数已添加至暂定软件包（详情请参阅 
@geindex Python 提高建议; PEP 411
PEP 411@footnote{https://www.python.org/dev/peps/pep-0411} ）。
@end quotation
@end cartouche
@end deffn

@geindex get_coroutine_origin_tracking_depth() (在 sys 模块中)
@anchor{library/sys sys get_coroutine_origin_tracking_depth}@anchor{500}
@deffn {函数} sys.get_coroutine_origin_tracking_depth ()

获取由 @ref{501,,set_coroutine_origin_tracking_depth()} 设置的协程来源的追踪深度。


3.7 新版功能.


@cartouche
@quotation 注解 
本函数已添加至暂定软件包（详情请参阅 
@geindex Python 提高建议; PEP 411
PEP 411@footnote{https://www.python.org/dev/peps/pep-0411} ）。仅将其用于调试目的。
@end quotation
@end cartouche
@end deffn

@geindex hash_info() (在 sys 模块中)
@anchor{library/sys sys hash_info}@anchor{a0f}
@deffn {数据} sys.hash_info

一个 @ref{b84,,具名元组}，给出数字类型的哈希的实现参数。关于数字类型的哈希的详情请参阅 @ref{178b,,数字类型的哈希运算}。


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

说明

@item

@code{width}

@tab

用于哈希值的位宽度

@item

@code{modulus}

@tab

用于数字散列方案的素数模数P。

@item

@code{inf}

@tab

为正无穷大返回的哈希值

@item

@code{nan}

@tab

为nan返回的哈希值

@item

@code{imag}

@tab

用于复数虚部的乘数

@item

@code{algorithm}

@tab

字符串、字节和内存视图的哈希算法的名称

@item

@code{hash_bits}

@tab

哈希算法的内部输出大小。

@item

@code{seed_bits}

@tab

散列算法的种子密钥的大小

@end multitable



3.2 新版功能.



在 3.4 版更改: 添加了 @emph{algorithm}, @emph{hash_bits} 和 @emph{seed_bits}

@end deffn

@geindex hexversion() (在 sys 模块中)
@anchor{library/sys sys hexversion}@anchor{36be}
@deffn {数据} sys.hexversion

编码为单个整数的版本号。该整数会确保每个版本都自增，其中适当包括了未发布版本。举例来说，要测试 Python 解释器的版本不低于 1.5.2，请使用:

@example
if sys.hexversion >= 0x010502F0:
    # use some advanced feature
    ...
else:
    # use an alternative implementation or warn the user
    ...
@end example

之所以称它为 @code{hexversion}，是因为只有将它传入内置函数 @ref{d36,,hex()} 后，其结果才看起来有意义。也可以使用 @ref{b84,,具名元组} @ref{bf6,,sys.version_info}，它对相同信息有着更人性化的编码。

关于 @code{hexversion} 的更多信息可以在 @ref{36bf,,API 和 ABI 版本管理} 中找到。
@end deffn

@geindex implementation() (在 sys 模块中)
@anchor{library/sys sys implementation}@anchor{a94}
@deffn {数据} sys.implementation

一个对象，该对象包含当前运行的 Python 解释器的实现信息。所有 Python 实现中都必须存在下列属性。

@emph{name} 是当前实现的标识符，如 @code{'cpython'}。实际的字符串由 Python 实现定义，但保证是小写字母。

@emph{version} 是一个具名元组，格式与 @ref{bf6,,sys.version_info} 相同。它表示 Python @emph{实现} 的版本。 另一个（由 @code{sys.version_info} 表示）是当前解释器遵循的相应 Python @emph{语言} 的版本，两者具有不同的含义。 例如，对于 PyPy 1.8，@code{sys.implementation.version} 可能是 @code{sys.version_info(1, 8, 0, 'final', 0)}，而 @code{sys.version_info} 则是 @code{sys.version_info(2, 7, 2, 'final', 0)}。对于 CPython 而言两个值是相同的，因为它是参考实现。

@emph{hexversion} 是十六进制的实现版本，类似于 @ref{36be,,sys.hexversion}。

@emph{cache_tag} 是导入机制使用的标记，用于已缓存模块的文件名。按照惯例，它将由实现的名称和版本组成，如 @code{'cpython-33'}。但如果合适，Python 实现可以使用其他值。如果 @code{cache_tag} 被置为 @code{None}，表示模块缓存已禁用。

@ref{a94,,sys.implementation} 可能包含相应 Python 实现的其他属性。这些非标准属性必须以下划线开头，此处不详细阐述。无论其内容如何，@ref{a94,,sys.implementation} 在解释器运行期间或不同实现版本之间都不会更改。（但是不同 Python 语言版本间可能会不同。）详情请参阅 
@geindex Python 提高建议; PEP 421
PEP 421@footnote{https://www.python.org/dev/peps/pep-0421}。


3.3 新版功能.


@cartouche
@quotation 注解 
新的必要属性的添加必须经过常规的 PEP 过程。详情请参阅 
@geindex Python 提高建议; PEP 421
PEP 421@footnote{https://www.python.org/dev/peps/pep-0421}。
@end quotation
@end cartouche
@end deffn

@geindex int_info() (在 sys 模块中)
@anchor{library/sys sys int_info}@anchor{cf3}
@deffn {数据} sys.int_info

一个 @ref{b84,,具名元组}，包含 Python 内部整数表示形式的信息。这些属性是只读的。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

说明

@item

@code{bits_per_digit}

@tab

每个数字占有的位数。Python 内部将整数存储在基底 @code{2**int_info.bits_per_digit}

@item

@code{sizeof_digit}

@tab

用于表示数字的C类型的字节大小

@item

@code{default_max_str_digits}

@tab

default value for
@ref{1877,,sys.get_int_max_str_digits()} when it
is not otherwise explicitly configured.

@item

@code{str_digits_check_threshold}

@tab

minimum non-zero value for
@ref{f62,,sys.set_int_max_str_digits()},
@geindex PYTHONINTMAXSTRDIGITS
@geindex 环境变量; PYTHONINTMAXSTRDIGITS
@ref{f61,,PYTHONINTMAXSTRDIGITS}, or
@ref{297,,-X int_max_str_digits}.

@end multitable



3.1 新版功能.



在 3.9.14 版更改: Added @code{default_max_str_digits} and @code{str_digits_check_threshold}.

@end deffn

@geindex __interactivehook__() (在 sys 模块中)
@anchor{library/sys sys __interactivehook__}@anchor{9d3}
@deffn {数据} sys.__interactivehook__

当本属性存在，则以 @ref{9d2,,交互模式} 启动解释器时，将自动（不带参数地）调用本属性的值。该过程是在读取 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 文件之后完成的，所以可以在该文件中设置这一钩子。@ref{eb,,site} 模块 @ref{9d5,,设置了这一属性}。

引发一个 @ref{fec,,审计事件} @code{cpython.run_interactivehook}，附带参数 @code{hook}。


3.4 新版功能.

@end deffn

@geindex intern() (在 sys 模块中)
@anchor{library/sys sys intern}@anchor{d3e}
@deffn {函数} sys.intern (string)

将 @emph{string} 插入 "interned" （驻留）字符串表，返回被插入的字符串 -- 它是 @emph{string} 本身或副本。驻留字符串对提高字典查找的性能很有用 -- 如果字典中的键已驻留，且所查找的键也已驻留，则键（取散列后）的比较可以用指针代替字符串来比较。通常，Python 程序使用到的名称会被自动驻留，且用于保存模块、类或实例属性的字典的键也已驻留。

驻留字符串不是永久存在的，对 @ref{d3e,,intern()} 返回值的引用必须保留下来，才能发挥驻留字符串的优势。
@end deffn

@geindex is_finalizing() (在 sys 模块中)
@anchor{library/sys sys is_finalizing}@anchor{85b}
@deffn {函数} sys.is_finalizing ()

如果 Python 解释器 @ref{85c,,正在关闭} 则返回 @ref{59c,,True}，否则返回 @ref{497,,False}。


3.5 新版功能.

@end deffn

@geindex last_type() (在 sys 模块中)
@geindex last_value() (在 sys 模块中)
@geindex last_traceback() (在 sys 模块中)
@anchor{library/sys sys last_type}@anchor{d2a}
@deffn {数据} sys.last_type
@anchor{library/sys sys last_value}@anchor{36c0}
@deffnx {数据} sys.last_value
@anchor{library/sys sys last_traceback}@anchor{35bc}
@deffnx {数据} sys.last_traceback

这三个变量并非总是有定义，仅当有异常未处理，且解释器打印了错误消息和堆栈回溯时，才会给它们赋值。它们的预期用途，是允许交互中的用户导入调试器模块，进行事后调试，而不必重新运行导致错误的命令。（通常使用 @code{import pdb; pdb.pm()} 进入事后调试器，详情请参阅 @ref{c9,,pdb} 模块。）

这些变量的含义与上述 @ref{d2f,,exc_info()} 返回值的含义相同。
@end deffn

@geindex maxsize() (在 sys 模块中)
@anchor{library/sys sys maxsize}@anchor{c1e}
@deffn {数据} sys.maxsize

一个整数，表示 @ref{391,,Py_ssize_t} 类型的变量可以取到的最大值。在 32 位平台上通常为 @code{2**31 - 1}，在 64 位平台上通常为 @code{2**63 - 1}。
@end deffn

@geindex maxunicode() (在 sys 模块中)
@anchor{library/sys sys maxunicode}@anchor{a75}
@deffn {数据} sys.maxunicode

一个整数，表示最大的 Unicode 码点值，如 @code{1114111} （十六进制为 @code{0x10FFFF} ）。


在 3.3 版更改: 在 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 之前，@code{sys.maxunicode} 曾是 @code{0xFFFF} 或 @code{0x10FFFF}，具体取决于配置选项，该选项指定将 Unicode 字符存储为 UCS-2 还是 UCS-4。

@end deffn

@geindex meta_path() (在 sys 模块中)
@anchor{library/sys sys meta_path}@anchor{6e7}
@deffn {数据} sys.meta_path

一个由 @ref{a9a,,元路径查找器} 对象组成的列表，当查找需要导入的模块时，会调用这些对象的 @ref{56d,,find_spec()} 方法，观察这些对象是否能找到所需模块。调用 @ref{56d,,find_spec()} 方法最少需要传入待导入模块的绝对名称。如果待导入模块包含在一个包中，则父包的 @ref{13f3,,__path__} 属性将作为第二个参数被传入。该方法返回 @ref{36c1,,模块规格}，找不到模块则返回 @code{None}。


@subsubheading 参见



@table @asis

@item @ref{a9c,,importlib.abc.MetaPathFinder}

抽象基类，定义了 @ref{6e7,,meta_path} 内的查找器对象的接口。

@item @ref{1630,,importlib.machinery.ModuleSpec}

@ref{56d,,find_spec()} 返回的实例所对应的具体类。
@end table



在 3.4 版更改: 在 Python 3.4 中通过 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} 引入了 @ref{36c1,,模块规格}。早期版本的 Python 会寻找一个称为 @ref{56c,,find_module()} 的方法。如果某个 @ref{6e7,,meta_path} 条目没有 @ref{56d,,find_spec()} 方法，就会回退去调用前一种方法。

@end deffn

@geindex modules() (在 sys 模块中)
@anchor{library/sys sys modules}@anchor{109a}
@deffn {数据} sys.modules

一个字典，将模块名称映射到已加载的模块。可以操作该字典来强制重新加载模块，或是实现其他技巧。但是，替换的字典不一定会按预期工作，并且从字典中删除必要的项目可能会导致 Python 崩溃。
@end deffn

@geindex path() (在 sys 模块中)
@anchor{library/sys sys path}@anchor{262}
@deffn {数据} sys.path

@geindex module; search; path

一个由字符串组成的列表，用于指定模块的搜索路径。初始化自环境变量 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH}，再加上一条与安装有关的默认路径。

程序启动时将初始化本列表，列表的第一项 @code{path[0]} 目录含有调用 Python 解释器的脚本。如果脚本目录不可用（比如以交互方式调用了解释器，或脚本是从标准输入中读取的），则 @code{path[0]} 为空字符串，这将导致 Python 优先搜索当前目录中的模块。注意，脚本目录将插入在 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 的条目*之前*。

程序可以随意修改本列表用于自己的目的。只能向 @ref{262,,sys.path} 中添加 string 和 bytes 类型，其他数据类型将在导入期间被忽略。


@subsubheading 参见


@ref{eb,,site} 模块，该模块描述了如何使用 .pth 文件来扩展 @ref{262,,sys.path}。

@end deffn

@geindex path_hooks() (在 sys 模块中)
@anchor{library/sys sys path_hooks}@anchor{a46}
@deffn {数据} sys.path_hooks

一个由可调用对象组成的列表，这些对象接受一个路径作为参数，并尝试为该路径创建一个 @ref{1624,,查找器}。如果成功创建查找器，则可调用对象将返回它，否则将引发 @ref{16c,,ImportError} 异常。

本特性最早在 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 中被提及。
@end deffn

@geindex path_importer_cache() (在 sys 模块中)
@anchor{library/sys sys path_importer_cache}@anchor{5a0}
@deffn {数据} sys.path_importer_cache

一个字典，作为 @ref{1624,,查找器} 对象的缓存。key 是传入 @ref{a46,,sys.path_hooks} 的路径，value 是相应已找到的查找器。如果路径是有效的文件系统路径，但在 @ref{a46,,sys.path_hooks} 中未找到查找器，则存入 @code{None}。

本特性最早在 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 中被提及。


在 3.3 版更改: 未找到查找器时，改为存储 @code{None}，而不是 @ref{aa4,,imp.NullImporter}。

@end deffn

@geindex platform() (在 sys 模块中)
@anchor{library/sys sys platform}@anchor{3db}
@deffn {数据} sys.platform

本字符串是一个平台标识符，举例而言，该标识符可用于将特定平台的组件追加到 @ref{262,,sys.path} 中。

对于 Unix 系统（除 Linux 和 AIX 外），该字符串是 @emph{Python 构建时的} @code{uname -s} 返回的小写操作系统名称，并附加了 @code{uname -r} 返回的系统版本的第一部分，如 @code{'sunos5'} 或 @code{'freebsd8'}。除非需要检测特定版本的系统，否则建议使用以下习惯用法:

@example
if sys.platform.startswith('freebsd'):
    # FreeBSD-specific code here...
elif sys.platform.startswith('linux'):
    # Linux-specific code here...
elif sys.platform.startswith('aix'):
    # AIX-specific code here...
@end example

对于其他系统，值是：


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

系统

@tab

@code{平台} 值

@item

AIX

@tab

@code{'aix'}

@item

Linux

@tab

@code{'linux'}

@item

Windows

@tab

@code{'win32'}

@item

Windows/Cygwin

@tab

@code{'cygwin'}

@item

macOS

@tab

@code{'darwin'}

@end multitable



在 3.3 版更改: 在 Linux 上，@ref{3db,,sys.platform} 将不再包含副版本号。它将总是 @code{'linux'} 而不是 @code{'linux2'} 或 @code{'linux3'}。由于旧版本的 Python 会包含该版本号，因此推荐总是使用上述 @code{startswith} 习惯用法。



在 3.8 版更改: 在 AIX 上，@ref{3db,,sys.platform} 将不再包含副版本号。它将总是 @code{'aix'} 而不是 @code{'aix5'} 或 @code{'aix7'}。由于旧版本的 Python 会包含该版本号，因此推荐总是使用上述 @code{startswith} 习惯用法。



@subsubheading 参见


@ref{2071,,os.name} 更加简略。@ref{b41,,os.uname()} 提供系统的版本信息。

@ref{ce,,platform} 模块提供了对系统标识更详细的检查。

@end deffn

@geindex platlibdir() (在 sys 模块中)
@anchor{library/sys sys platlibdir}@anchor{1ea}
@deffn {数据} sys.platlibdir

平台专用库目录。用于构建标准库的路径和已安装扩展模块的路径。

在大多数平台上，它等同于 @code{"lib"} 。在 Fedora 和 SuSE 上，它等同于给出了以下 @code{sys.path} 路径的 64 位平台上的 @code{"lib64"} （其中 @code{X.Y} 是 Python 的 @code{major.minor} 版本）。


@itemize *

@item 
@code{/usr/lib64/pythonX.Y/}：标准库（如 @ref{c4,,os} 模块的 @code{os.py} ）

@item 
@code{/usr/lib64/pythonX.Y/lib-dynload/}：标准库的 C 扩展模块（如 @ref{7a,,errno} 模块，确切的文件名取决于平台）

@item 
@code{/usr/lib/pythonX.Y/site-packages/} (请使用 @code{lib}, 而非 @ref{1ea,,sys.platlibdir}): 第三方模块

@item 
@code{/usr/lib64/pythonX.Y/site-packages/}: 第三方包的 C 扩展模块
@end itemize


3.9 新版功能.

@end deffn

@geindex prefix() (在 sys 模块中)
@anchor{library/sys sys prefix}@anchor{3686}
@deffn {数据} sys.prefix

一个字符串，给出特定站点的目录前缀，用于安装与平台无关的 Python 文件；在 Unix 上，默认是 @code{'/usr/local'} 。这可以在构建时通过 @code{configure} 脚本的 @cite{--prefix} 参数来设置。 参见 @ref{36c2,,安装路径} 以了解衍生路径。

@cartouche
@quotation 注解 
如果在一个 @ref{3685,,虚拟环境} 中，那么该值将在 @code{site.py} 中被修改，指向虚拟环境。Python 安装位置仍然可以用 @ref{305e,,base_prefix} 来获取。
@end quotation
@end cartouche
@end deffn

@geindex ps1() (在 sys 模块中)
@geindex ps2() (在 sys 模块中)
@anchor{library/sys sys ps1}@anchor{14b7}
@deffn {数据} sys.ps1
@anchor{library/sys sys ps2}@anchor{14b8}
@deffnx {数据} sys.ps2

@geindex interpreter prompts
@geindex prompts@comma{} interpreter
@geindex >>>; interpreter prompt
@geindex ...; interpreter prompt

字符串，指定解释器的首要和次要提示符。仅当解释器处于交互模式时，它们才有定义。这种情况下，它们的初值为 @code{'>>> '} 和 @code{'... '}。如果赋给其中某个变量的是非字符串对象，则每次解释器准备读取新的交互式命令时，都会重新运行该对象的 @ref{206,,str()}，这可以用来实现动态的提示符。
@end deffn

@geindex setdlopenflags() (在 sys 模块中)
@anchor{library/sys sys setdlopenflags}@anchor{b4a}
@deffn {函数} sys.setdlopenflags (n)

设置解释器在调用 @code{dlopen()} 时用到的标志，例如解释器在加载扩展模块时。首先，调用 @code{sys.setdlopenflags(0)} 将在导入模块时对符号启用惰性解析。要在扩展模块之间共享符号，请调用 @code{sys.setdlopenflags(os.RTLD_GLOBAL)}。标志值的符号名称可以在 @ref{c4,,os} 模块中找到（即 @code{RTLD_xxx} 常量，如 @ref{b43,,os.RTLD_LAZY} ）。

@ref{14c1,,可用性}: Unix。
@end deffn

@geindex set_int_max_str_digits() (在 sys 模块中)
@anchor{library/sys sys set_int_max_str_digits}@anchor{f62}
@deffn {函数} sys.set_int_max_str_digits (n)

Set the @ref{288,,integer string conversion length limitation} used by this interpreter. See also
@ref{1877,,get_int_max_str_digits()}.


3.9.14 新版功能.

@end deffn

@geindex setprofile() (在 sys 模块中)
@anchor{library/sys sys setprofile}@anchor{f07}
@deffn {函数} sys.setprofile (profilefunc)

@geindex profile function
@geindex profiler

设置系统的性能分析函数，该函数使得在 Py​​thon 中能够实现一个 Python 源代码性能分析器。关于 Python Profiler 的更多信息请参阅 @ref{35e4,,Python Profilers 分析器} 章节。性能分析函数的调用方式类似于系统的跟踪函数（参阅 @ref{f08,,settrace()} ），但它是通过不同的事件调用的，例如，不是每执行一行代码就调用它一次（仅在调用某函数和从某函数返回时才会调用性能分析函数，但即使某函数发生异常也会算作返回事件）。该函数是特定于单个线程的，但是性能分析器无法得知线程之间的上下文切换，因此在存在多个线程的情况下使用它是没有意义的。另外，因为它的返回值不会被用到，所以可以简单地返回 @code{None}。性能分析函数中的错误将导致其自身被解除设置。

性能分析函数应接收三个参数：@emph{frame}、@emph{event} 和 @emph{arg}。@emph{frame} 是当前的堆栈帧。@emph{event} 是一个字符串：@code{'call'}、@code{'return'}、@code{'c_call'}、@code{'c_return'} 或 @code{'c_exception'}。@emph{arg} 取决于事件类型。

引发一个 @ref{fec,,审计事件} @code{sys.setprofile}，不附带任何参数。

这些事件具有以下含义：


@table @asis

@item @code{'call'}

表示调用了某个函数（或进入了其他的代码块）。性能分析函数将被调用，@emph{arg} 为 @code{None}。

@item @code{'return'}

表示某个函数（或别的代码块）即将返回。性能分析函数将被调用，@emph{arg} 是即将返回的值，如果此次返回事件是由于抛出异常，@emph{arg} 为 @code{None}。

@item @code{'c_call'}

表示即将调用某个 C 函数。它可能是扩展函数或是内建函数。@emph{arg} 是 C 函数对象。

@item @code{'c_return'}

表示返回了某个 C 函数。@emph{arg} 是 C 函数对象。

@item @code{'c_exception'}

表示某个 C 函数抛出了异常。@emph{arg} 是 C 函数对象。
@end table
@end deffn

@geindex setrecursionlimit() (在 sys 模块中)
@anchor{library/sys sys setrecursionlimit}@anchor{f43}
@deffn {函数} sys.setrecursionlimit (limit)

将 Python 解释器堆栈的最大深度设置为 @emph{limit}。此限制可防止无限递归导致的 C 堆栈溢出和 Python 崩溃。

不同平台所允许的最高限值不同。当用户有需要深度递归的程序且平台支持更高的限值，可能就需要调高限值。进行该操作需要谨慎，因为过高的限值可能会导致崩溃。

如果新的限值低于当前的递归深度，将抛出 @ref{731,,RecursionError} 异常。


在 3.5.1 版更改: 如果新的限值低于当前的递归深度，现在将抛出 @ref{731,,RecursionError} 异常。

@end deffn

@geindex setswitchinterval() (在 sys 模块中)
@anchor{library/sys sys setswitchinterval}@anchor{219}
@deffn {函数} sys.setswitchinterval (interval)

设置解释器的线程切换间隔时间（单位为秒）。该浮点数决定了“时间片”的理想持续时间，时间片将分配给同时运行的 Python 线程。请注意，实际值可能更高，尤其是使用了运行时间长的内部函数或方法时。同时，在时间间隔末尾调度哪个线程是操作系统的决定。解释器没有自己的调度程序。


3.2 新版功能.

@end deffn

@geindex settrace() (在 sys 模块中)
@anchor{library/sys sys settrace}@anchor{f08}
@deffn {函数} sys.settrace (tracefunc)

@geindex trace function
@geindex debugger

设置系统的跟踪函数，使得用户在 Python 中就可以实现 Python 源代码调试器。该函数是特定于单个线程的，所以要让调试器支持多线程，必须为正在调试的每个线程都用 @ref{f08,,settrace()} 注册一个跟踪函数，或使用 @ref{24c7,,threading.settrace()}。

跟踪函数应接收三个参数：@emph{frame}、@emph{event} 和 @emph{arg}。@emph{frame} 是当前的堆栈帧。@emph{event} 是一个字符串：@code{'call'}、@code{'line'}、@code{'return'}、@code{'exception'} 或 @code{'opcode'}。@emph{arg} 取决于事件类型。

每次进入 trace 函数的新的局部作用范围，都会调用 trace 函数（ @emph{event} 会被设置为 @code{'call'} ），它应该返回一个引用，指向即将用在新作用范围上的局部跟踪函数；如果不需要跟踪当前的作用范围，则返回 @code{None}。

局部跟踪函数应返回对自身的引用（或对另一个函数的引用，用来在其作用范围内进行进一步的跟踪），或者返回 @code{None} 来停止跟踪其作用范围。

如果跟踪函数出错，则该跟踪函数将被取消设置，类似于调用 @code{settrace(None)}。

这些事件具有以下含义：


@table @asis

@item @code{'call'}

表示调用了某个函数（或进入了其他的代码块）。全局跟踪函数将被调用，@emph{arg} 为 @code{None}。返回值将指定局部跟踪函数。

@item @code{'line'}

表示解释器即将执行新一行代码或重新执行循环条件。局部跟踪函数将被调用，@emph{arg} 为 @code{None}，其返回值将指定新的局部跟踪函数。关于其工作原理的详细说明，请参见 @code{Objects/lnotab_notes.txt}。要在该堆栈帧禁用每行触发事件，可以在堆栈帧上将 @code{f_trace_lines} 设置为 @ref{497,,False}。

@item @code{'return'}

表示某个函数（或别的代码块）即将返回。局部跟踪函数将被调用，@emph{arg} 是即将返回的值，如果此次返回事件是由于抛出异常，@emph{arg} 为 @code{None}。跟踪函数的返回值将被忽略。

@item @code{'exception'}

表示发生了某个异常。局部跟踪函数将被调用，@emph{arg} 是一个 @code{(exception, value, traceback)} 元组，返回值将指定新的局部跟踪函数。

@item @code{'opcode'}

表示解释器即将执行一个新的操作码（操作码的详情请参阅 @ref{37,,dis} ）。局部跟踪函数将被调用，@emph{arg} 为 @code{None}，其返回值将指定新的局部跟踪函数。每操作码触发事件默认情况下都不发出：必须在堆栈帧上将 @code{f_trace_opcodes} 显式地设置为 @ref{59c,,True} 来请求这些事件。
@end table

注意，由于异常是在链式调用中传播的，所以每一级都会产生一个 @code{'exception'} 事件。

更细微的用法是，可以显式地通过赋值 @code{frame.f_trace = tracefunc} 来设置跟踪函数，而不是用现有跟踪函数的返回值去间接设置它。当前帧上的跟踪函数必须激活，而 @ref{f08,,settrace()} 还没有做这件事。注意，为了使上述设置起效，必须使用 @ref{f08,,settrace()} 来安装全局跟踪函数才能启用运行时跟踪机制，但是它不必与上述是同一个跟踪函数（它可以是一个开销很低的跟踪函数，只返回 @code{None}，即在各个帧上立即将其自身禁用）。

关于代码对象和帧对象的更多信息请参考 @ref{1582,,标准类型层级结构}。

引发一个 @ref{fec,,审计事件} @code{sys.settrace}，不附带任何参数。

@strong{CPython implementation detail:} @ref{f08,,settrace()} 函数仅用于实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而不是语言定义的一部分，因此并非在所有 Python 实现中都可用。


在 3.7 版更改: 添加了 @code{'opcode'} 事件类型；为帧对象添加了 @code{f_trace_lines} 和 @code{f_trace_opcodes} 属性

@end deffn

@geindex set_asyncgen_hooks() (在 sys 模块中)
@anchor{library/sys sys set_asyncgen_hooks}@anchor{10a0}
@deffn {函数} sys.set_asyncgen_hooks (firstiter, finalizer)

接受两个可选的关键字参数，要求它们是可调用对象，且接受一个 @ref{36bd,,异步生成器迭代器} 作为参数。@emph{firstiter} 对象将在异步生成器第一次迭代时调用。@emph{finalizer} 将在异步生成器即将被销毁时调用。

引发一个 @ref{fec,,审计事件} @code{sys.set_asyncgen_hooks_firstiter}，不附带任何参数。

引发一个 @ref{fec,,审计事件} @code{sys.set_asyncgen_hooks_finalizer}，不附带任何参数。

之所以会引发两个审计事件，是因为底层的 API 由两个调用组成，每个调用都须要引发自己的事件。


3.6 新版功能: 更多详情请参阅 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525}，@emph{finalizer} 方法的参考示例可参阅 Lib/asyncio/base_events.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py} 中 @code{asyncio.Loop.shutdown_asyncgens} 的实现。


@cartouche
@quotation 注解 
本函数已添加至暂定软件包（详情请参阅 
@geindex Python 提高建议; PEP 411
PEP 411@footnote{https://www.python.org/dev/peps/pep-0411} ）。
@end quotation
@end cartouche
@end deffn

@geindex set_coroutine_origin_tracking_depth() (在 sys 模块中)
@anchor{library/sys sys set_coroutine_origin_tracking_depth}@anchor{501}
@deffn {函数} sys.set_coroutine_origin_tracking_depth (depth)

用于启用或禁用协程溯源。启用后，协程对象上的 @code{cr_origin} 属性将包含一个元组，它由多个（文件名 filename，行号 line number，函数名 function name）元组组成，整个元组描述出了协程对象创建过程的回溯，元组首端是最近一次的调用。禁用后，@code{cr_origin} 将为 None。

要启用，请向 @emph{depth} 传递一个大于零的值，它指定了有多少帧将被捕获信息。要禁用，请将 @emph{depth} 置为零。

该设置是特定于单个线程的。


3.7 新版功能.


@cartouche
@quotation 注解 
本函数已添加至暂定软件包（详情请参阅 
@geindex Python 提高建议; PEP 411
PEP 411@footnote{https://www.python.org/dev/peps/pep-0411} ）。仅将其用于调试目的。
@end quotation
@end cartouche
@end deffn

@geindex _enablelegacywindowsfsencoding() (在 sys 模块中)
@anchor{library/sys sys _enablelegacywindowsfsencoding}@anchor{5fa}
@deffn {函数} sys._enablelegacywindowsfsencoding ()

将默认文件系统编码和错误处理方案分别更改为 'mbcs' 和 'replace'，这是为了与 Python 3.6 前的版本保持一致。

这等同于在启动 Python 前先定义好 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 环境变量; PYTHONLEGACYWINDOWSFSENCODING
@ref{5f9,,PYTHONLEGACYWINDOWSFSENCODING} 环境变量。

@ref{14c1,,可用性}: Windows。


3.6 新版功能: 更多详情请参阅 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529}。

@end deffn

@geindex stdin() (在 sys 模块中)
@geindex stdout() (在 sys 模块中)
@geindex stderr() (在 sys 模块中)
@anchor{library/sys sys stdin}@anchor{427}
@deffn {数据} sys.stdin
@anchor{library/sys sys stdout}@anchor{428}
@deffnx {数据} sys.stdout
@anchor{library/sys sys stderr}@anchor{1eb}
@deffnx {数据} sys.stderr

解释器用于标准输入、标准输出和标准错误的 @ref{c1d,,文件对象}：


@itemize *

@item 
@code{stdin} 用于所有交互式输入（包括对 @ref{d3b,,input()} 的调用）；

@item 
@code{stdout} 用于 @ref{97a,,print()} 和 @ref{15be,,expression} 语句的输出，以及用于 @ref{d3b,,input()} 的提示符；

@item 
解释器自身的提示符和它的错误消息都发往 @code{stderr}。
@end itemize

这些流都是常规 @ref{1409,,文本文件}，与 @ref{16f,,open()} 函数返回的对象一致。它们的参数选择如下：


@itemize *

@item 
字符编码取决于各个平台。在非 Windows 平台上使用的是语言环境 (locale) 编码（可参阅 @ref{4b4,,locale.getpreferredencoding()} ）。

在 Windows 上，控制台设备使用 UTF-8 编码。非字符设备（如磁盘文件和管道）使用系统语言环境编码（即 ANSI 代码页）。非控制台字符设备（即 @code{isatty()} 返回的是 @code{True}，如 NUL）在启动时，会把控制台输入代码页和输出代码页的值分别用于 stdin 和 stdout/stderr。如果进程原本没有附加到控制台，则默认为系统语言环境编码。

要重写控制台的特殊行为，可以在启动 Python 前设置 PYTHONLEGACYWINDOWSSTDIO 环境变量。此时，控制台代码页将用于其他字符设备。

在所有平台上，都可以通过在 Python 启动前设置 
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} 环境变量来重写字符编码，或通过新的 @ref{297,,-X} @code{utf8} 命令行选项和 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} 环境变量来设置。但是，对 Windows 控制台来说，上述方法仅在设置了 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 环境变量; PYTHONLEGACYWINDOWSSTDIO
@ref{5fc,,PYTHONLEGACYWINDOWSSTDIO} 后才起效。

@item 
交互模式下，@code{stdout} 流是行缓冲的。其他情况下，它像常规文本文件一样是块缓冲的。两种情况下的 @code{stderr} 流都是行缓冲的。要使得两个流都变成无缓冲，可以传入 @ref{10e6,,-u} 命令行选项或设置 
@geindex PYTHONUNBUFFERED
@geindex 环境变量; PYTHONUNBUFFERED
@ref{10e7,,PYTHONUNBUFFERED} 环境变量。
@end itemize


在 3.9 版更改: 非交互模式下，@code{stderr} 现在是行缓冲的，而不是全缓冲的。


@cartouche
@quotation 注解 
要从标准流写入或读取二进制数据，请使用底层二进制 @ref{d0a,,buffer} 对象。例如，要将字节写入 @ref{428,,stdout}，请使用 @code{sys.stdout.buffer.write(b'abc')}。

但是，如果你在写一个库（并且不限制执行库代码时的上下文），那么请注意，标准流可能会被替换为文件类对象，如 @ref{924,,io.StringIO}，它们是不支持 @code{buffer} 属性的。
@end quotation
@end cartouche
@end deffn

@geindex __stdin__() (在 sys 模块中)
@geindex __stdout__() (在 sys 模块中)
@geindex __stderr__() (在 sys 模块中)
@anchor{library/sys sys __stdin__}@anchor{36c3}
@deffn {数据} sys.__stdin__
@anchor{library/sys sys __stdout__}@anchor{1e41}
@deffnx {数据} sys.__stdout__
@anchor{library/sys sys __stderr__}@anchor{34f0}
@deffnx {数据} sys.__stderr__

程序开始时，这些对象存有 @code{stdin}、@code{stderr} 和 @code{stdout} 的初始值。它们在程序结束前都可以使用，且在需要向实际的标准流打印内容时很有用，无论 @code{sys.std*} 对象是否已重定向。

如果实际文件已经被覆盖成一个损坏的对象了，那它也可用于将实际文件还原成能正常工作的文件对象。但是，本过程的最佳方法应该是，在原来的流被替换之前就显式地保存它，并使用这一保存的对象来还原。

@cartouche
@quotation 注解 
某些情况下的 @code{stdin}、@code{stdout} 和 @code{stderr} 以及初始值 @code{__stdin__}、@code{__stdout__} 和 @code{__stderr__} 可以是 @code{None}。通常发生在未连接到控制台的 Windows GUI app 中，以及在用 @code{pythonw} 启动的 Python app 中。
@end quotation
@end cartouche
@end deffn

@geindex thread_info() (在 sys 模块中)
@anchor{library/sys sys thread_info}@anchor{b83}
@deffn {数据} sys.thread_info

一个 @ref{b84,,具名元组}，包含线程实现的信息。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

说明

@item

@code{name}

@tab

线程实现的名称：

@quotation


@itemize *

@item 
@code{'nt'}: Windows 线程

@item 
@code{'pthread'}: POSIX 线程

@item 
@code{'solaris'}: Solaris 线程
@end itemize
@end quotation

@item

@code{lock}

@tab

锁实现的名称：

@quotation


@itemize *

@item 
@code{'semaphore'}: 锁使用信号量

@item 
@code{'mutex+cond'}: 锁使用互斥和条件变量

@item 
@code{None} 如果此信息未知
@end itemize
@end quotation

@item

@ref{6d4,,version}

@tab

线程库的名称和版本。它是一个字符串，如果此信息未知，则为 @code{None} 。

@end multitable



3.3 新版功能.

@end deffn

@geindex tracebacklimit() (在 sys 模块中)
@anchor{library/sys sys tracebacklimit}@anchor{36c4}
@deffn {数据} sys.tracebacklimit

当该变量值设置为整数，在发生未处理的异常时，它将决定打印的回溯信息的最大层级数。默认为 @code{1000}。当将其设置为 @code{0} 或小于 0，将关闭所有回溯信息，并且只打印异常类型和异常值。
@end deffn

@geindex unraisablehook() (在 sys 模块中)
@anchor{library/sys sys unraisablehook}@anchor{361}
@deffn {函数} sys.unraisablehook (unraisable, /)

处理一个无法抛出的异常。

它会在发生了一个异常但 Python 没有办法处理时被调用。例如，当一个析构器引发了异常，或在垃圾回收 (@ref{362,,gc.collect()}) 期间引发了异常。

@emph{unraisable} 参数具有以下属性:


@itemize *

@item 
@emph{exc_type}: 异常类型

@item 
@emph{exc_value}: 异常值，可以是 @code{None}.

@item 
@emph{exc_traceback}: 异常回溯，可以是 @code{None}.

@item 
@emph{err_msg}: 错误信息，可以是 @code{None}.

@item 
@emph{object}: 导致异常的对象，可以为 @code{None}.
@end itemize

默认的钩子程序会将 @emph{err_msg} 和 @emph{object} 格式化为： @code{f'@{err_msg@}: @{object!r@}'}；如果 @emph{err_msg} 为 @code{None} 则采用 "Exception ignored in" 错误信息。

要改变无法抛出的异常的处理过程，可以重写 @ref{361,,sys.unraisablehook()}。

使用定制钩子存放 @emph{exc_value} 可能会创建引用循环。 它应当在不再需要异常时被显式地清空以打破引用循环。

如果一个 @emph{object} 正在被销毁，那么使用自定义的钩子储存该对象可能会将其复活。请在自定义钩子生效后避免储存 @emph{object}，以避免对象的复活。

另请参阅 @ref{1ae,,excepthook()}，它处理未捕获的异常。

引发一个审计事件 @code{sys.unraisablehook} 并附带参数 @code{hook}, @code{unraisable}。


3.8 新版功能.

@end deffn

@geindex version() (在 sys 模块中)
@anchor{library/sys sys version}@anchor{6d4}
@deffn {数据} sys.version

一个包含 Python 解释器版本号加编译版本号以及所用编译器等额外信息的字符串。 此字符串会在交互式解释器启动时显示。 请不要从中提取版本信息，而应当使用 @ref{bf6,,version_info} 以及 @ref{ce,,platform} 模块所提供的函数。
@end deffn

@geindex api_version() (在 sys 模块中)
@anchor{library/sys sys api_version}@anchor{36c5}
@deffn {数据} sys.api_version

这个解释器的 C API 版本。当你在调试 Python及期扩展模板的版本冲突这个功能非常有用。
@end deffn

@geindex version_info() (在 sys 模块中)
@anchor{library/sys sys version_info}@anchor{bf6}
@deffn {数据} sys.version_info

一个包含版本号五部分的元组: @emph{major}, @emph{minor}, @emph{micro}, @emph{releaselevel} 和 @emph{serial}。 除 @emph{releaselevel} 外的所有值均为整数；发布级别值则为 @code{'alpha'}, @code{'beta'}, @code{'candidate'} 或 @code{'final'}。 对应于 Python 版本 2.0 的 @code{version_info} 值为 @code{(2, 0, 0, 'final', 0)}。 这些部分也可按名称访问，因此 @code{sys.version_info[0]} 就等价于 @code{sys.version_info.major}，依此类推。


在 3.1 版更改: 增加了以名称表示的各部分属性。

@end deffn

@geindex warnoptions() (在 sys 模块中)
@anchor{library/sys sys warnoptions}@anchor{523}
@deffn {数据} sys.warnoptions

这是警告框架的一个实现细节；请不要修改此值。 有关警告框架的更多信息请参阅 @ref{12f,,warnings} 模块。
@end deffn

@geindex winver() (在 sys 模块中)
@anchor{library/sys sys winver}@anchor{36c6}
@deffn {数据} sys.winver

用于在 Windows 平台上组成注册表键的版本号。 这在 Python DLL 中存储为 1000 号字符串资源。 其值通常是 @ref{6d4,,version} 的头三个字符。 它在 @ref{fd,,sys} 模块中提供是为了信息展示目的；修改此值不会影响 Python 所使用的注册表键。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex _xoptions() (在 sys 模块中)
@anchor{library/sys sys _xoptions}@anchor{14b2}
@deffn {数据} sys._xoptions

一个字典，包含通过 @ref{297,,-X} 命令行选项传递的旗标，这些旗标专属于各种具体实现。选项名称将会映射到对应的值（如果显式指定）或者 @ref{59c,,True}。例如:

@example
$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._xoptions
@{'a': 'b', 'c': True@}
@end example

@strong{CPython implementation detail:} 这是 CPython 专属的访问通过 @ref{297,,-X} 传递的选项的方式。 其他实现可能会通过其他方式导出它们，或者完全不导出。


3.2 新版功能.

@end deffn

@subsubheading 引用


@anchor{library/sys c99}@anchor{36b9}@w{(C99)} 
ISO/IEC 9899:1999.  "Programming languages -- C." 该标准的公开草案可从 @indicateurl{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf}获得。

@node sysconfig —— 提供对 Python 配置信息的访问支持,builtins --- 内建对象,sys --- 系统相关的参数和函数,Python运行时服务
@anchor{library/sysconfig doc}@anchor{36c7}@anchor{library/sysconfig module-sysconfig}@anchor{fe}@anchor{library/sysconfig sysconfig-provide-access-to-python-s-configuration-information}@anchor{36c8}
@subsection @code{sysconfig} —— 提供对 Python 配置信息的访问支持


@geindex sysconfig (模块)


3.2 新版功能.


@strong{源代码：} Lib/sysconfig.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/sysconfig.py}

@geindex configuration information


__________________________________________________________________


@ref{fe,,sysconfig} 模块提供了对 Python 配置信息的访问支持，比如安装路径列表和有关当前平台的配置变量。

@menu
* 配置变量:: 
* 安装路径:: 
* 其他功能: 其他功能<3>. 
* 使用 sysconfig 作为脚本as a script:: 

@end menu

@node 配置变量,安装路径,,sysconfig —— 提供对 Python 配置信息的访问支持
@anchor{library/sysconfig configuration-variables}@anchor{36c9}
@subsubsection 配置变量


Python 的发行版中包含一个 @code{Makefile} 和一个 @code{pyconfig.h} 头文件，这是构建 Python 二进制文件本身和用 @ref{38,,distutils} 编译的第三方 C 语言扩展所必需的。

@ref{fe,,sysconfig} 将这些文件中的所有变量放在一个字典对象中，可用 @ref{a4f,,get_config_vars()} 或 @ref{a4e,,get_config_var()} 访问。

请注意在 Windows 上，这是一个小得多的集合。

@geindex get_config_vars() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_config_vars}@anchor{a4f}
@deffn {函数} sysconfig.get_config_vars (*args)

不带参数时，返回一个与当前平台相关的所有配置变量的字典。

带参数时，返回一个由在配置变量字典中查找每个参数的结果的值组成的列表。

对于每个参数，如果未找到值，则返回 @code{None}。
@end deffn

@geindex get_config_var() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_config_var}@anchor{a4e}
@deffn {函数} sysconfig.get_config_var (name)

返回单个变量 @emph{name} 的值。 等价于 @code{get_config_vars().get(name)}。

如果未找到 @emph{name}，则返回 @code{None}。
@end deffn

用法示例:

@example
>>> import sysconfig
>>> sysconfig.get_config_var('Py_ENABLE_SHARED')
0
>>> sysconfig.get_config_var('LIBDIR')
'/usr/local/lib'
>>> sysconfig.get_config_vars('AR', 'CXX')
['ar', 'g++']
@end example

@node 安装路径,其他功能<3>,配置变量,sysconfig —— 提供对 Python 配置信息的访问支持
@anchor{library/sysconfig id1}@anchor{36ca}@anchor{library/sysconfig installation-paths}@anchor{36c2}
@subsubsection 安装路径


Python 会使用根据平台和安装选项区别处理的安装方案。 这些方案保存在 @ref{fe,,sysconfig} 中基于 @ref{2071,,os.name} 的返回值来确定的唯一标识符下。

每个使用 @ref{38,,distutils} 或基于 Distutils 的系统安装的新组件都将遵循同样的方案将其文件拷贝到正确的位置。

Python 目前支持六种方案:


@itemize -

@item 
@emph{posix_prefix}: 针对 POSIX 平台如 Linux 或 macOS 的方案。 这是在安装 Python 或者组件时的默认方案。

@item 
@emph{posix_home}: 当在安装时使用了 @emph{home} 选项时针对 POSIX 平台所使用的方案。 此方案会在通过 Distutils 附带指定的前缀安装组件时被使用。

@item 
@emph{posix_user}: 当通过 Distutils 安装组件并且使用了 @emph{user} 选项时针对 POSIX 平台所使用的方案。 此方案会在用户家目录下定义路径位置。

@item 
@emph{nt}: 针对 NT 平台如 Windows 的方案。

@item 
@emph{nt_user}: 针对 NT 平台，当使用了 @emph{user} 选项时的方案。

@item 
@emph{osx_framework_user}: 针对 macOS，当使用了 @emph{user} 选项时的方案。
@end itemize

每个方案本身由一系列路径组成并且每个路径都有唯一的标识符。 Python 目前使用了八个路径:


@itemize -

@item 
@emph{stdlib}: 包含非平台专属的标准 Python 库文件的目录。

@item 
@emph{platstdlib}: 包含平台专属的标准 Python 库文件的目录。

@item 
@emph{platlib}: 用于站点专属、平台专属的文件的目录。

@item 
@emph{purelib}: 用于站点专属、非平台专属的文件的目录。

@item 
@emph{include}: 用于非平台专属的头文件的目录。

@item 
@emph{platinclude}: 用于平台专属的头文件的目录。

@item 
@emph{scripts}: 用于脚本文件的目录。

@item 
@emph{data}: 用于数据文件的目录。
@end itemize

@ref{fe,,sysconfig} 提供了一些函数来确定这些路径。

@geindex get_scheme_names() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_scheme_names}@anchor{36cb}
@deffn {函数} sysconfig.get_scheme_names ()

返回一个包含 @ref{fe,,sysconfig} 目前支持的所有方案的元组。
@end deffn

@geindex get_path_names() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_path_names}@anchor{36cc}
@deffn {函数} sysconfig.get_path_names ()

返回一个包含在 @ref{fe,,sysconfig} 中目前支持的所有路径名称的元组。
@end deffn

@geindex get_path() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_path}@anchor{d8e}
@deffn {函数} sysconfig.get_path (name[, scheme[, vars[, expand]]])

返回一个对应于路径 @emph{name}，来自名为 @emph{scheme} 的安装方案的安装路径。

@emph{name} 必须是一个来自 @ref{36cc,,get_path_names()} 所返回的列表的值。

@ref{fe,,sysconfig} 会针对每个平台保存与每个路径名称相对应的安装路径，并带有可扩展的变量。 例如针对 @emph{nt} 方案的 @emph{stdlib} 路径是: @code{@{base@}/Lib}。

@ref{d8e,,get_path()} 将使用 @ref{a4f,,get_config_vars()} 所返回的变量来扩展路径。 所有变量对于每种平台都有相应的默认值因此使用者可以调用此函数来获取默认值。

如果提供了 @emph{scheme}，则它必须是一个来自 @ref{36cb,,get_scheme_names()} 所返回的列表的值。 在其他情况下，将会使用针对当前平台的默认方案。

如果提供了 @emph{vars}，则它必须是一个将要更新 @ref{a4f,,get_config_vars()} 所返回的字典的字典。

如果 @emph{expand} 被设为 @code{False}，则将不使用这些变量来扩展路径。

如果 @emph{name} 未找到，则会引发 @ref{3f1,,KeyError}。
@end deffn

@geindex get_paths() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_paths}@anchor{caf}
@deffn {函数} sysconfig.get_paths ([scheme[, vars[, expand]]])

返回一个包含与特定安装方案对应的安装路径的字典。 请参阅 @ref{d8e,,get_path()} 了解详情。

如果未提供 @emph{scheme}，则将使用针对当前平台的默认方案。

如果提供了 @emph{vars}，则它必须是一个将要更新用于扩展的字典的变量字典。

如果 @emph{expand} 被设为假值，则路径将不会被扩展。

如果 @emph{scheme} 不是一个现有的方案，则 @ref{caf,,get_paths()} 将引发 @ref{3f1,,KeyError}。
@end deffn

@node 其他功能<3>,使用 sysconfig 作为脚本as a script,安装路径,sysconfig —— 提供对 Python 配置信息的访问支持
@anchor{library/sysconfig other-functions}@anchor{36cd}
@subsubsection 其他功能


@geindex get_python_version() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_python_version}@anchor{cae}
@deffn {函数} sysconfig.get_python_version ()

以字符串形式 @code{MAJOR.MINOR} 返回 Python 版本号。 类似于 @code{'%d.%d' % sys.version_info[:2]}。
@end deffn

@geindex get_platform() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_platform}@anchor{cad}
@deffn {函数} sysconfig.get_platform ()

返回一个标识当前平台的字符串。

这主要被用来区分平台专属的构建目录和平台专属的构建分发版。 通常包括 OS 名称和版本以及架构（即 'os.uname()' 所提供的信息)，但是实际包括的信息取决于具体 OS；例如，在 Linux 上，内核版本号并不是特别重要。

返回值的示例：


@itemize -

@item 
linux-i586

@item 
linux-alpha (?)

@item 
solaris-2.6-sun4u
@end itemize

Windows将返回以下之一：


@itemize -

@item 
win-amd64 (在 AMD64, aka x86_64, Intel64, 和 EM64T上的64位 Windows )

@item 
win32（所有其他的 —— 确切地说，返回 sys.platform）
@end itemize

macOS 可以返回:


@itemize -

@item 
macosx-10.6-ppc

@item 
macosx-10.4-ppc64

@item 
macosx-10.3-i386

@item 
macosx-10.4-fat
@end itemize

对于其他非-POSIX 平台， 目前只是返回 @ref{3db,,sys.platform} 。
@end deffn

@geindex is_python_build() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig is_python_build}@anchor{d8f}
@deffn {函数} sysconfig.is_python_build ()

如果正在运行的 Python 解释器是使用源代码构建的并在其构建位置上运行，而不是在其他位置例如通过运行 @code{make install} 或通过二进制机器码安装程序安装则返回 @code{True}。
@end deffn

@geindex parse_config_h() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig parse_config_h}@anchor{36ce}
@deffn {函数} sysconfig.parse_config_h (fp[, vars])

解析一个 @code{config.h} 风格的文件。

@emph{fp} 是一个指向 @code{config.h} 风格的文件的文件类对象。

返回一个包含名称/值对的字典。 如果传入一个可选的字典作为第二个参数，则将使用它而不是新的字典，并使用从文件中读取的值更新它。
@end deffn

@geindex get_config_h_filename() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_config_h_filename}@anchor{36cf}
@deffn {函数} sysconfig.get_config_h_filename ()

返回  @code{pyconfig.h} 的目录
@end deffn

@geindex get_makefile_filename() (在 sysconfig 模块中)
@anchor{library/sysconfig sysconfig get_makefile_filename}@anchor{36d0}
@deffn {函数} sysconfig.get_makefile_filename ()

返回 @code{Makefile} 的目录
@end deffn

@node 使用 sysconfig 作为脚本as a script,,其他功能<3>,sysconfig —— 提供对 Python 配置信息的访问支持
@anchor{library/sysconfig using-sysconfig-as-a-script}@anchor{36d1}
@subsubsection 使用 @code{sysconfig} 作为脚本as a script


使用通过 Python 的 @emph{-m} 将 @ref{fe,,sysconfig} 作为脚本使用:

@example
$ python -m sysconfig
Platform: "macosx-10.4-i386"
Python version: "3.2"
Current installation scheme: "posix_prefix"

Paths:
        data = "/usr/local"
        include = "/Users/tarek/Dev/svn.python.org/py3k/Include"
        platinclude = "."
        platlib = "/usr/local/lib/python3.2/site-packages"
        platstdlib = "/usr/local/lib/python3.2"
        purelib = "/usr/local/lib/python3.2/site-packages"
        scripts = "/usr/local/bin"
        stdlib = "/usr/local/lib/python3.2"

Variables:
        AC_APPLE_UNIVERSAL_BUILD = "0"
        AIX_GENUINE_CPLUSPLUS = "0"
        AR = "ar"
        ARFLAGS = "rc"
        ...
@end example

此调用将把 @ref{cad,,get_platform()}, @ref{cae,,get_python_version()}, @ref{d8e,,get_path()} 和 @ref{a4f,,get_config_vars()} 所返回的信息打印至标准输出。

@node builtins --- 内建对象,__main__ --- 顶层脚本环境,sysconfig —— 提供对 Python 配置信息的访问支持,Python运行时服务
@anchor{library/builtins doc}@anchor{36d2}@anchor{library/builtins builtins-built-in-objects}@anchor{36d3}@anchor{library/builtins module-builtins}@anchor{12}
@subsection @code{builtins} --- 内建对象


@geindex builtins (模块)


__________________________________________________________________


该模块提供对Python的所有“内置”标识符的直接访问；例如，@code{builtins.open} 是内置函数的全名 @ref{16f,,open()} 。请参阅 @ref{cc6,,内置函数} 和 @ref{176f,,内置常量} 的文档。

大多数应用程序通常不会显式访问此模块，但在提供与内置值同名的对象的模块中可能很有用，但其中还需要内置该名称。例如，在一个想要实现 @ref{16f,,open()} 函数的模块中，它包装了内置的 @ref{16f,,open()} ，这个模块可以直接使用:

@example
import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '@w{'}'Wrapper around a file that converts output to upper-case.'@w{'}'

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...
@end example

作为一个实现细节，大多数模块都将名称 @code{__builtins__} 作为其全局变量的一部分提供。 @code{__builtins__} 的值通常是这个模块或者这个模块的值 @ref{5fe,,__dict__} 属性。由于这是一个实现细节，因此 Python 的替代实现可能不会使用它。

@node __main__ --- 顶层脚本环境,warnings —— 警告信息的控制,builtins --- 内建对象,Python运行时服务
@anchor{library/__main__ doc}@anchor{36d4}@anchor{library/__main__ main-top-level-script-environment}@anchor{36d5}@anchor{library/__main__ module-__main__}@anchor{1}
@subsection @code{__main__} --- 顶层脚本环境


@geindex __main__ (模块)


__________________________________________________________________


@code{'__main__'} 是顶层代码执行的作用域的名称。模块的 __name__ 在通过标准输入、脚本文件或是交互式命令读入的时候会等于 @code{'__main__'}。

模块可以通过检查自己的 @code{__name__} 来得知是否运行在 main 作用域中，这使得模块可以在作为脚本或是通过 @code{python -m} 运行时条件性地执行一些代码，而在被 import 时不会执行。

@example
if __name__ == "__main__":
    # execute only if run as a script
    main()
@end example

对软件包来说，通过加入 @code{__main__.py} 模块可以达到同样的效果，当使用 @code{-m} 运行模块时，其中的代码会被执行。

@node warnings —— 警告信息的控制,dataclasses --- 数据类,__main__ --- 顶层脚本环境,Python运行时服务
@anchor{library/warnings doc}@anchor{36d6}@anchor{library/warnings module-warnings}@anchor{12f}@anchor{library/warnings warnings-warning-control}@anchor{36d7}
@subsection @code{warnings} —— 警告信息的控制


@geindex warnings (模块)

@strong{源代码：} Lib/warnings.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/warnings.py}

@geindex warnings


__________________________________________________________________


通常以下情况会引发警告：提醒用户注意程序中的某些情况，而这些情况（通常）还不值得触发异常并终止程序。例如，当程序用到了某个过时的模块时，就可能需要发出一条警告。

Python 程序员可调用本模块中定义的 @ref{f22,,warn()} 函数来发布警告。（C 语言程序员则用 @ref{e7e,,PyErr_WarnEx()} ； 详见 @ref{36d8,,异常处理} ）。

警告信息通常会写入 @ref{1eb,,sys.stderr} ，但可以灵活改变，从忽略所有警告到变成异常都可以。警告的处理方式可以依据 @ref{18ac,,警告类型} 、警告信息的文本和发出警告的源位置而进行变化。同一源位置重复出现的警告通常会被抑制。

控制警告信息有两个阶段：首先，每次引发警告时，决定信息是否要发出；然后，如果要发出信息，就用可由用户设置的钩子进行格式化并打印输出。

@ref{15d,,警告过滤器} 控制着是否发出警告信息，也即一系列的匹配规则和动作。调用 @ref{ed2,,filterwarnings()} 可将规则加入过滤器，调用  @ref{36d9,,resetwarnings()} 则可重置为默认状态。

警告信息的打印输出是通过调用 @ref{36da,,showwarning()} 完成的，该函数可被重写；默认的实现代码是调用 @ref{1176,,formatwarning()} 进行格式化，自己编写的代码也可以调用此格式化函数。


@subsubheading 参见


利用 @ref{2256,,logging.captureWarnings()} 可以采用标准的日志部件处理所有警告。


@menu
* 警告类别:: 
* 警告过滤器:: 
* 暂时禁止警告:: 
* 测试警告:: 
* 为新版本的依赖关系更新代码:: 
* 可用的函数:: 
* 可用的上下文管理器:: 

@end menu

@node 警告类别,警告过滤器,,warnings —— 警告信息的控制
@anchor{library/warnings id1}@anchor{36db}@anchor{library/warnings warning-categories}@anchor{18ac}
@subsubsection 警告类别


警告的类别由一些内置的异常表示。这种分类有助于对警告信息进行分组过滤。

虽然在技术上警告类别属于 @ref{18aa,,内置异常}，但也只是在此记录一下而已，因为在概念上他们属于警告机制的一部分。

通过对某个标准的警告类别进行派生，用户代码可以定义其他的警告类别。 警告类别必须是 @ref{18ad,,Warning} 类的子类。

目前已定义了以下警告类别的类：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类

@tab

描述

@item

@ref{18ad,,Warning}

@tab

这是所有警告类别的基类。它是 @ref{2e3,,Exception} 的子类。

@item

@ref{18ae,,UserWarning}

@tab

The default category for @ref{f22,,warn()}.

@item

@ref{15a,,DeprecationWarning}

@tab

已废弃特性警告的基类，这些警告是为其他 Python 开发者准备的（默认会忽略，除非在 @code{__main__} 中用代码触发）。

@item

@ref{2d0,,SyntaxWarning}

@tab

用于警告可疑语法的基类。

@item

@ref{3ea,,RuntimeWarning}

@tab

用于警告可疑运行时特性的基类

@item

@ref{43e,,FutureWarning}

@tab

用于警告已废弃特性的基类，这些警告是为 Python 应用程序的最终用户准备的。

@item

@ref{15c,,PendingDeprecationWarning}

@tab

用于警告即将废弃功能的基类（默认忽略）。

@item

@ref{6d9,,ImportWarning}

@tab

导入模块时触发的警告的基类（默认忽略）。

@item

@ref{e54,,UnicodeWarning}

@tab

用于 Unicode 相关警告的基类。

@item

@ref{5b8,,BytesWarning}

@tab

@ref{172,,bytes} 和 @ref{173,,bytearray} 相关警告的基类

@item

@ref{5d3,,ResourceWarning}

@tab

资源使用相关警告的基础类别（默认会被忽略）。ignored by default).

@end multitable



在 3.7 版更改: 以前 @ref{15a,,DeprecationWarning} 和 @ref{43e,,FutureWarning} 是根据某个功能是否完全删除或改变其行为来区分的。现在是根据受众和默认警告过滤器的处理方式来区分的。


@node 警告过滤器,暂时禁止警告,警告类别,warnings —— 警告信息的控制
@anchor{library/warnings the-warnings-filter}@anchor{36dc}@anchor{library/warnings warning-filter}@anchor{15d}
@subsubsection 警告过滤器


警告过滤器控制着警告是否被忽略、显示或转为错误（触发异常）。

从概念上讲，警告过滤器维护着一个经过排序的过滤器类别列表；任何具体的警告都会依次与列表中的每种过滤器进行匹配，直到找到一个匹配项；过滤器决定了匹配项的处理方式。每个列表项均为 ( @emph{action} ,  @emph{message} ,  @emph{category} ,  @emph{module} ,  @emph{lineno} ) 格式的元组，其中：


@itemize *

@item 
@emph{action} 是以下字符串之一：


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

处置

@item

@code{"default"}

@tab

为发出警告的每个位置（模块+行号）打印第一个匹配警告

@item

@code{"error"}

@tab

将匹配警告转换为异常

@item

@code{"ignore"}

@tab

从不打印匹配的警告

@item

@code{"always"}

@tab

总是打印匹配的警告

@item

@code{"module"}

@tab

为发出警告的每个模块打印第一次匹配警告（无论行号如何）

@item

@code{"once"}

@tab

无论位置如何，仅打印第一次出现的匹配警告

@end multitable


@item 
@emph{message} 是包含正则表达式的字符串，警告信息的开头必须与之匹配。该表达式编译时不区分大小写。

@item 
@emph{category} 是警告类别的类（@ref{18ad,,Warning} 的子类），警告类别必须是其子类，才能匹配。

@item 
@emph{module} 是个字符串，包含了模块名称必须匹配的正则表达式。该表达式编译时大小写敏感。

@item 
@emph{lineno} 是个整数，发生警告的行号必须与之匹配，或与所有行号匹配。
@end itemize

由于 @ref{18ad,,Warning} 类是由内置类 @ref{2e3,,Exception} 派生出来的，要把某个警告变成错误，只要触发`@w{`}category(message)`@w{`} 即可。

如果警告不匹配所有已注册的过滤器，那就会应用 “default” 动作（正如其名）。

@menu
* 警告过滤器的介绍:: 
* 默认警告过滤器:: 
* 重写默认的过滤器:: 

@end menu

@node 警告过滤器的介绍,默认警告过滤器,,警告过滤器
@anchor{library/warnings describing-warning-filters}@anchor{14ae}@anchor{library/warnings id2}@anchor{36dd}
@subsubsection 警告过滤器的介绍


警告过滤器由传给 Python 解释器的命令行 @ref{15b,,-W} 选项和 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS} 环境变量初始化。解释器在  @code{sys.warningoptions} 中保存了所有给出的参数，但不作解释；@ref{12f,,warnings} 模块在第一次导入时会解析这些参数（无效的选项被忽略，并会先向 @ref{1eb,,sys.stderr} 打印一条信息）。

每个警告过滤器的设定格式为冒号分隔的字段序列：

@example
action:message:category:module:line
@end example

这些字段的含义在 @ref{15d,,警告过滤器} 中描述。当一行中列出多个过滤器时（如 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS}），过滤器间用逗号隔开，后面的优先于前面的（因为是从左到右应用的，最近应用的过滤器优先于前面的）。

常用的警告过滤器适用于所有的警告、特定类别的警告、由特定模块和包引发的警告。下面是一些例子：

@example
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule[.*]         # Convert warnings to errors in "mymodule"
                             # and any subpackages of "mymodule"
@end example

@node 默认警告过滤器,重写默认的过滤器,警告过滤器的介绍,警告过滤器
@anchor{library/warnings default-warning-filter}@anchor{36de}@anchor{library/warnings id3}@anchor{36df}
@subsubsection 默认警告过滤器


Python 默认安装了几个警告过滤器，可以通过 @ref{15b,,-W} 命令行参数、 
@geindex PYTHONWARNINGS
@geindex 环境变量; PYTHONWARNINGS
@ref{524,,PYTHONWARNINGS} 环境变量及调用 @ref{ed2,,filterwarnings()} 进行覆盖。

在常规发布的版本中，默认的警告过滤器包括（按优先顺序排列）：

@example
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
@end example

在调试版本中，默认警告过滤器的列表是空的。


在 3.2 版更改: 除了 @ref{15c,,PendingDeprecationWarning} 之外，@ref{15a,,DeprecationWarning} 现在默认会被忽略。



在 3.7 版更改: @ref{15a,,DeprecationWarning} 在被 @code{__main__} 中的代码直接触发时，默认会再次显示。



在 3.7 版更改: 如果指定两次 @ref{522,,-b}，则 @ref{5b8,,BytesWarning} 不再出现在默认的过滤器列表中，而是通过 @code{sys.warningoptions} 进行配置。


@node 重写默认的过滤器,,默认警告过滤器,警告过滤器
@anchor{library/warnings overriding-the-default-filter}@anchor{36e0}@anchor{library/warnings warning-disable}@anchor{36e1}
@subsubsection 重写默认的过滤器


Python 应用程序的开发人员可能希望在默认情况下向用户隐藏 @emph{所有} Python级别的警告，而只在运行测试或其他调试时显示这些警告。用于向解释器传递过滤器配置的 @code{sys.warningoptions} 属性可以作为一个标记，表示是否应该禁用警告：

@example
import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
@end example

建议 Python 代码测试的开发者使用如下代码，以确保被测代码默认显示 @emph{所有} 警告：

@example
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
@end example

最后，建议在 @code{__main__} 以外的命名空间运行用户代码的交互式开发者，请确保 @ref{15a,,DeprecationWarning} 在默认情况下是可见的，可采用如下代码（这里 @code{user_ns} 是用于执行交互式输入代码的模块）：

@example
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
@end example

@node 暂时禁止警告,测试警告,警告过滤器,warnings —— 警告信息的控制
@anchor{library/warnings temporarily-suppressing-warnings}@anchor{36e2}@anchor{library/warnings warning-suppress}@anchor{36e3}
@subsubsection 暂时禁止警告


如果明知正在使用会引起警告的代码，比如某个废弃函数，但不想看到警告（即便警告已经通过命令行作了显式配置），那么可以使用 @ref{34dd,,catch_warnings} 上下文管理器来抑制警告。

@example
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
@end example

在上下文管理器中，所有的警告将被简单地忽略。这样就能使用已知的过时代码而又不必看到警告，同时也不会限制警告其他可能不知过时的代码。注意：只能保证在单线程应用程序中生效。如果两个以上的线程同时使用 @ref{34dd,,catch_warnings} 上下文管理器，行为不可预知。

@node 测试警告,为新版本的依赖关系更新代码,暂时禁止警告,warnings —— 警告信息的控制
@anchor{library/warnings testing-warnings}@anchor{36e4}@anchor{library/warnings warning-testing}@anchor{36e5}
@subsubsection 测试警告


要测试由代码引发的警告，请采用 @ref{34dd,,catch_warnings} 上下文管理器。有了它，就可以临时改变警告过滤器以方便测试。例如，以下代码可捕获所有的警告以便查看：

@example
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)
@end example

也可以用 @code{error} 取代 @code{always} ，让所有的警告都成为异常。需要注意的是，如果某条警告已经因为 @code{once} / @code{default} 规则而被引发，那么无论设置什么过滤器，该条警告都不会再出现，除非该警告有关的注册数据被清除。

一旦上下文管理器退出，警告过滤器将恢复到刚进此上下文时的状态。这样在多次测试时可防止意外改变警告过滤器，从而导致不确定的测试结果。模块中的 @ref{36da,,showwarning()} 函数也被恢复到初始值。注意：这只能在单线程应用程序中得到保证。如果两个以上的线程同时使用 @ref{34dd,,catch_warnings} 上下文管理器，行为未定义。

当测试多项操作会引发同类警告时，重点是要确保每次操作都会触发新的警告（比如，将警告设置为异常并检查操作是否触发异常，检查每次操作后警告列表的长度是否有增加，否则就在每次新操作前将以前的警告列表项删除）。

@node 为新版本的依赖关系更新代码,可用的函数,测试警告,warnings —— 警告信息的控制
@anchor{library/warnings updating-code-for-new-versions-of-dependencies}@anchor{36e6}@anchor{library/warnings warning-ignored}@anchor{33f7}
@subsubsection 为新版本的依赖关系更新代码


在默认情况下，主要针对 Python 开发者（而不是 Python 应用程序的最终用户）的警告类别，会被忽略。

值得注意的是，这个“默认忽略”的列表包含 @ref{15a,,DeprecationWarning} （适用于每个模块，除了 @code{__main__}），这意味着开发人员应该确保在测试代码时应将通常忽略的警告显示出来，以便未来破坏性 API 变化时及时收到通知（无论是在标准库还是第三方包）。

理想情况下，代码会有一个合适的测试套件，在运行测试时会隐含地启用所有警告（由 @ref{124,,unittest} 模块提供的测试运行程序就是如此）。

在不太理想的情况下，可以通过向 Python 解释器传入 @ref{15b,,-Wd}  (这是 @code{-W default} 的简写) 或设置环境变量 @code{PYTHONWARNINGS=default} 来检查应用程序是否用到了已弃用的接口。 这样可以启用对所有警告的默认处理操作，包括那些默认忽略的警告。 要改变遇到警告后执行的动作，可以改变传给 @ref{15b,,-W} 的参数 (例如 @code{-W error})。 请参阅 @ref{15b,,-W} 旗标来了解更多的细节。

@node 可用的函数,可用的上下文管理器,为新版本的依赖关系更新代码,warnings —— 警告信息的控制
@anchor{library/warnings available-functions}@anchor{36e7}@anchor{library/warnings warning-functions}@anchor{36e8}
@subsubsection 可用的函数


@geindex warn() (在 warnings 模块中)
@anchor{library/warnings warnings warn}@anchor{f22}
@deffn {函数} warnings.warn (message, category=None, stacklevel=1, source=None)

引发警告、忽略或者触发异常。 如果给出 @emph{category} 参数，则必须是  @ref{18ac,,警告类别类} ；默认为 @ref{18ae,,UserWarning}。 或者 @emph{message} 可为 @ref{18ad,,Warning} 的实例，这时 @emph{category} 将被忽略，转而采用 @code{message.__class__}。 在这种情况下，错误信息文本将是 @code{str(message)}。 如果某条警告被 @ref{15d,,警告过滤器} 改成了错误，本函数将触发一条异常。 参数 @emph{stacklevel} 可供 Python 包装函数使用，比如:

@example
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
@end example

这会让警告指向 @code{deprecation()} 的调用者，而不是 @code{deprecation()} 本身的来源（因为后者会破坏引发警告的目的）。

@emph{source} 是发出 @ref{5d3,,ResourceWarning} 的被销毁对象。


在 3.6 版更改: 加入  @emph{source}  参数。

@end deffn

@geindex warn_explicit() (在 warnings 模块中)
@anchor{library/warnings warnings warn_explicit}@anchor{6b1}
@deffn {函数} warnings.warn_explicit (message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)

这是 @ref{f22,,warn()} 函数的底层接口，显式传入消息、类别、文件名和行号，以及可选的模块名和注册表（应为模块的 @code{__warningregistry__} 字典）。 模块名称默认为去除了 @code{.py} 的文件名；如果未传递注册表，警告就不会被抑制。 @emph{message} 必须是个字符串，@emph{category} 是 @ref{18ad,,Warning} 的子类；或者*message* 可为 @ref{18ad,,Warning} 的实例，且 @emph{category} 将被忽略。

@emph{module_globals} 应为发出警告的代码所用的全局命名空间。（该参数用于从 zip 文件或其他非文件系统导入模块时显式源码）。

@emph{source} 是发出 @ref{5d3,,ResourceWarning} 的被销毁对象。


在 3.6 版更改: 加入  @emph{source} 参数。

@end deffn

@geindex showwarning() (在 warnings 模块中)
@anchor{library/warnings warnings showwarning}@anchor{36da}
@deffn {函数} warnings.showwarning (message, category, filename, lineno, file=None, line=None)

将警告信息写入文件。默认的实现代码是调用`@w{`}formatwarning(message, category, filename, lineno, line)`@w{`} 并将结果字符串写入 @emph{file} ，默认文件为 @ref{1eb,,sys.stderr}。通过将任何可调用对象赋给 @code{warnings.showwarning} 可替换掉该函数。@emph{line} 是要包含在警告信息中的一行源代码；如果未提供 @emph{line}，@ref{36da,,showwarning()} 将尝试读取由*filename* 和 @emph{lineno} 指定的行。
@end deffn

@geindex formatwarning() (在 warnings 模块中)
@anchor{library/warnings warnings formatwarning}@anchor{1176}
@deffn {函数} warnings.formatwarning (message, category, filename, lineno, line=None)

以标准方式格式化一条警告信息。将返回一个字符串，可能包含内嵌的换行符，并以换行符结束。如果未提供 @emph{line}，@ref{1176,,formatwarning()} 将尝试读取由 @emph{filename} 和 @emph{lineno} 指定的行。
@end deffn

@geindex filterwarnings() (在 warnings 模块中)
@anchor{library/warnings warnings filterwarnings}@anchor{ed2}
@deffn {函数} warnings.filterwarnings (action, message='@w{'}, category=Warning, module='@w{'}, lineno=0, append=False)

在 @ref{15d,,警告过滤器种类} 列表中插入一条数据项。默认情况下，该数据项将被插到前面；如果 @emph{append} 为 True，则会插到后面。这里会检查参数的类型，编译 @emph{message} 和 @emph{module} 正则表达式，并将他们作为一个元组插入警告过滤器的列表中。如果两者都与某种警告匹配，那么靠近列表前面的数据项就会覆盖后面的项。省略的参数默认匹配任意值。
@end deffn

@geindex simplefilter() (在 warnings 模块中)
@anchor{library/warnings warnings simplefilter}@anchor{34de}
@deffn {函数} warnings.simplefilter (action, category=Warning, lineno=0, append=False)

在 @ref{15d,,警告过滤器种类} 列表中插入一条简单数据项。函数参数的含义与 @ref{ed2,,filterwarnings()} 相同，但不需要正则表达式，因为插入的过滤器总是匹配任何模块中的任何信息，只要类别和行号匹配即可。
@end deffn

@geindex resetwarnings() (在 warnings 模块中)
@anchor{library/warnings warnings resetwarnings}@anchor{36d9}
@deffn {函数} warnings.resetwarnings ()

重置警告过滤器。这将丢弃之前对 @ref{ed2,,filterwarnings()} 的所有调用，包括 @ref{15b,,-W} 命令行选项和对 @ref{34de,,simplefilter()} 的调用效果。
@end deffn

@node 可用的上下文管理器,,可用的函数,warnings —— 警告信息的控制
@anchor{library/warnings available-context-managers}@anchor{36e9}
@subsubsection 可用的上下文管理器


@geindex catch_warnings (warnings 中的类)
@anchor{library/warnings warnings catch_warnings}@anchor{34dd}
@deffn {类} warnings.catch_warnings (*, record=False, module=None)

该上下文管理器会复制警告过滤器和 @ref{36da,,showwarning()} 函数，并在退出时恢复。 如果 @emph{record} 参数是 @ref{497,,False} (默认)，则在进入时会返回 @ref{204,,None}。 如果 @emph{record} 为 @ref{59c,,True}，则返回一个列表，列表由自定义 @ref{36da,,showwarning()} 函数所用对象逐步填充（该函数还会抑制 @code{sys.stdout} 的输出）。 列表中每个对象的属性与 @ref{36da,,showwarning()} 的参数名称相同。

@emph{module} 参数代表一个模块，当导入 @ref{12f,,warnings} 时，将被用于代替返回的模块，其过滤器将被保护。该参数主要是为了测试 @ref{12f,,warnings} 模块自身。

@cartouche
@quotation 注解 
@ref{34dd,,catch_warnings} 管理器的工作方式，是替换并随后恢复模块的 @ref{36da,,showwarning()} 函数和内部的过滤器种类列表。这意味着上下文管理器将会修改全局状态，因此不是线程安全的。
@end quotation
@end cartouche
@end deffn

@node dataclasses --- 数据类,contextlib --- 为 with语句上下文提供的工具,warnings —— 警告信息的控制,Python运行时服务
@anchor{library/dataclasses doc}@anchor{36ea}@anchor{library/dataclasses dataclasses-data-classes}@anchor{36eb}@anchor{library/dataclasses module-dataclasses}@anchor{2f}
@subsection @code{dataclasses} --- 数据类


@geindex dataclasses (模块)

@strong{源码：} Lib/dataclasses.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dataclasses.py}


__________________________________________________________________


这个模块提供了一个装饰器和一些函数，用于自动添加生成的 @ref{36ec,,special method}，例如 @ref{e2b,,__init__()} 和 @ref{453,,__repr__()} 到用户定义的类。 它最初描述于 
@geindex Python 提高建议; PEP 557
PEP 557@footnote{https://www.python.org/dev/peps/pep-0557} 。

在这些生成的方法中使用的成员变量是使用 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 类型标注来定义的。 例如以下代码:

@example
from dataclasses import dataclass

@@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand
@end example

将在添加的内容中包括如下所示的 @ref{e2b,,__init__()}:

@example
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand
@end example

请注意，此方法会自动添加到类中：它不会在上面显示的 @code{InventoryItem} 定义中直接指定。


3.7 新版功能.


@menu
* 模块级装饰器、类和函数:: 
* 初始化后处理:: 
* 类变量:: 
* 仅初始化变量:: 
* 冻结的实例:: 
* 继承: 继承<2>. 
* 默认工厂函数:: 
* 可变的默认值:: 
* 异常: 异常<17>. 

@end menu

@node 模块级装饰器、类和函数,初始化后处理,,dataclasses --- 数据类
@anchor{library/dataclasses module-level-decorators-classes-and-functions}@anchor{36ed}
@subsubsection 模块级装饰器、类和函数


@geindex dataclass() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses dataclass}@anchor{452}
@deffn {函数} @@dataclasses.dataclass (*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

这个函数是 @ref{174,,decorator} ，用于将生成的 @ref{36ec,,special method} 添加到类中，如下所述。

@ref{452,,dataclass()} 装饰器会检查类以查找 @code{field}。 @code{field} 被定义为具有 @ref{71c,,类型标注} 的类变量。 除了下面描述的两个例外，在 @ref{452,,dataclass()} 中没有什么东西会去检查在变量标注中所指定的类型。

所有生成的方法中的字段顺序是它们在类定义中出现的顺序。

@ref{452,,dataclass()} 装饰器将向类中添加各种“dunder”方法，如下所述。 如果所添加的方法已存在于类中，则行为将取决于下面所列出的参数。 装饰器会返回调用它的类本身；不会创建新的类。

如果 @ref{452,,dataclass()} 仅用作没有参数的简单装饰器，它就像它具有此签名中记录的默认值一样。也就是说，这三种 @ref{452,,dataclass()} 用法是等价的:

@example
@@dataclass
class C:
    ...

@@dataclass()
class C:
    ...

@@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class C:
   ...
@end example

@ref{452,,dataclass()} 的参数有：


@itemize -

@item 
@code{init}: 如果为真值（默认），将生成一个 @ref{e2b,,__init__()} 方法。

如果类已定义 @ref{e2b,,__init__()} ，则忽略此参数。

@item 
@code{repr} ：如果为真值（默认），将生成一个 @ref{453,,__repr__()} 方法。 生成的 repr 字符串将具有类名以及每个字段的名称和 repr ，按照它们在类中定义的顺序。不包括标记为从 repr 中排除的字段。 例如：@code{InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)}。

如果类已定义 @ref{453,,__repr__()} ，则忽略此参数。

@item 
@code{eq} ：如果为true（默认值），将生成 @ref{454,,__eq__()} 方法。此方法将类作为其字段的元组按顺序比较。比较中的两个实例必须是相同的类型。

如果类已定义 @ref{454,,__eq__()} ，则忽略此参数。

@item 
@code{order} ：如果为真值（默认为 @code{False} ），则 @ref{d06,,__lt__()} 、 @ref{d70,,__le__()} 、 @ref{d71,,__gt__()} 和 @ref{d72,,__ge__()} 方法将生成。 这将类作为其字段的元组按顺序比较。比较中的两个实例必须是相同的类型。如果 @code{order} 为真值并且 @code{eq} 为假值 ，则引发 @ref{16d,,ValueError} 。

如果类已经定义了 @ref{d06,,__lt__()} 、 @ref{d70,,__le__()} 、 @ref{d71,,__gt__()} 或者 @ref{d72,,__ge__()} 中的任意一个，将引发 @ref{1ff,,TypeError} 。

@item 
@code{unsafe_hash} ：如果为 @code{False} （默认值），则根据 @code{eq} 和 @code{frozen} 的设置方式生成 @ref{455,,__hash__()} 方法。

@ref{455,,__hash__()} 由内置的 @ref{aac,,hash()} 使用，当对象被添加到散列集合（如字典和集合）时。有一个 @ref{455,,__hash__()} 意味着类的实例是不可变的。可变性是一个复杂的属性，取决于程序员的意图， @ref{454,,__eq__()} 的存在性和行为，以及 @ref{452,,dataclass()} 装饰器中 @code{eq} 和 @code{frozen} 标志的值。

默认情况下， @ref{452,,dataclass()} 不会隐式添加 @ref{455,,__hash__()} 方法，除非这样做是安全的。 它也不会添加或更改现有的明确定义的 @ref{455,,__hash__()} 方法。 设置类属性 @code{__hash__ = None} 对 Python 具有特定含义，如 @ref{455,,__hash__()} 文档中所述。

如果 @ref{455,,__hash__()} 没有显式定义，或者它被设为 @code{None}，则 @ref{452,,dataclass()} @emph{可能} 会添加一个隐式 @ref{455,,__hash__()} 方法。 虽然并不推荐，但你可以用 @code{unsafe_hash=True} 来强制 @ref{452,,dataclass()} 创建一个 @ref{455,,__hash__()} 方法。 如果你的类在逻辑上不可变但却仍然可被修改那么可能就是这种情况。 这是一个特殊用例并且应当被仔细地考虑。

以下是隐式创建 @ref{455,,__hash__()} 方法的规则。请注意，你不能在数据类中都使用显式的 @ref{455,,__hash__()} 方法并设置 @code{unsafe_hash=True} ；这将导致 @ref{1ff,,TypeError} 。

如果 @code{eq} 和 @code{frozen} 都是 true，默认情况下 @ref{452,,dataclass()} 将为你生成一个 @ref{455,,__hash__()} 方法。如果 @code{eq} 为 true 且 @code{frozen} 为 false ，则 @ref{455,,__hash__()} 将被设置为 @code{None} ，标记它不可用（因为它是可变的）。如果 @code{eq} 为 false ，则 @ref{455,,__hash__()} 将保持不变，这意味着将使用超类的 @ref{455,,__hash__()} 方法（如果超类是 @ref{3da,,object} ，这意味着它将回到基于id的hash）。

@item 
@code{frozen}: 如为真值 (默认值为 @code{False})，则对字段赋值将会产生异常。 这模拟了只读的冻结实例。 如果在类中定义了 @ref{ef6,,__setattr__()} 或 @ref{1592,,__delattr__()} 则将会引发 @ref{1ff,,TypeError}。 参见下文的讨论。
@end itemize

@code{field}s 可以选择使用普通的 Python 语法指定默认值:

@example
@@dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'
@end example

在这个例子中， @code{a} 和 @code{b} 都将包含在添加的 @ref{e2b,,__init__()} 方法中，它们将被定义为:

@example
def __init__(self, a: int, b: int = 0):
@end example

如果具有默认值的字段之后存在没有默认值的字段，将会引发 @ref{1ff,,TypeError}。 无论此情况是发生在单个类中还是作为类继承的结果，都是如此。
@end deffn

@geindex field() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses field}@anchor{1182}
@deffn {函数} dataclasses.field (*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)

对于常见和简单的用例，不需要其他功能。但是，有些数据类功能需要额外的每字段信息。为了满足这种对附加信息的需求，你可以通过调用提供的 @ref{1182,,field()} 函数来替换默认字段值。例如:

@example
@@dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]
@end example

如上所示， @code{MISSING} 值是一个 sentinel 对象，用于检测是否提供了 @code{default} 和 @code{default_factory} 参数。 使用此 sentinel 是因为 @code{None} 是 @code{default} 的有效值。没有代码应该直接使用 @code{MISSING} 值。

@ref{1182,,field()} 参数有：


@itemize -

@item 
@code{default} ：如果提供，这将是该字段的默认值。这是必需的，因为 @ref{1182,,field()} 调用本身会替换一般的默认值。

@item 
@code{default_factory} ：如果提供，它必须是一个零参数可调用对象，当该字段需要一个默认值时，它将被调用。除了其他目的之外，这可以用于指定具有可变默认值的字段，如下所述。 同时指定 @code{default} 和 @code{default_factory} 将产生错误。

@item 
@code{init} ：如果为true（默认值），则该字段作为参数包含在生成的 @ref{e2b,,__init__()} 方法中。

@item 
@code{repr} ：如果为true（默认值），则该字段包含在生成的 @ref{453,,__repr__()} 方法返回的字符串中。

@item 
@code{compare} ：如果为true（默认值），则该字段包含在生成的相等性和比较方法中（ @ref{454,,__eq__()} ， @ref{d71,,__gt__()} 等等）。

@item 
@code{hash} ：这可以是布尔值或 @code{None} 。如果为true，则此字段包含在生成的 @ref{455,,__hash__()} 方法中。如果为 @code{None} （默认值），请使用 @code{compare} 的值，这通常是预期的行为。如果字段用于比较，则应在 hash 中考虑该字段。不鼓励将此值设置为 @code{None} 以外的任何值。

设置 @code{hash=False} 但 @code{compare=True} 的一个可能原因是，如果一个计算 hash 的代价很高的字段是检验等价性需要的，但还有其他字段可以计算类型的 hash 。 即使从 hash 中排除某个字段，它仍将用于比较。

@item 
@code{metadata} ：这可以是映射或 None 。 None 被视为一个空的字典。这个值包含在 @code{MappingProxyType()} 中，使其成为只读，并暴露在 @ref{1852,,Field} 对象上。数据类根本不使用它，它是作为第三方扩展机制提供的。多个第三方可以各自拥有自己的键值，以用作元数据中的命名空间。
@end itemize

如果通过调用 @ref{1182,,field()} 指定字段的默认值，则该字段的类属性将替换为指定的 @code{default} 值。如果没有提供 @code{default} ，那么将删除类属性。目的是在 @ref{452,,dataclass()} 装饰器运行之后，类属性将包含字段的默认值，就像指定了默认值一样。例如，之后:

@example
@@dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20
@end example

类属性 @code{C.z} 将是 @code{10} ，类属性 @code{C.t} 将是 @code{20}，类属性 @code{C.x} 和 @code{C.y} 将不设置。
@end deffn

@geindex Field (dataclasses 中的类)
@anchor{library/dataclasses dataclasses Field}@anchor{1852}
@deffn {类} dataclasses.Field

@ref{1852,,Field} 对象描述每个定义的字段。这些对象在内部创建，并由 @ref{36ee,,fields()} 模块级方法返回（见下文）。用户永远不应该直接实例化 @ref{1852,,Field} 对象。 其有文档的属性是：

@quotation


@itemize -

@item 
@code{name} ：字段的名字。

@item 
@code{type} ：字段的类型。

@item 
@code{default} 、 @code{default_factory} 、 @code{init} 、 @code{repr} 、 @code{hash} 、 @code{compare} 以及 @code{metadata} 与具有和 @ref{1182,,field()} 声明中相同的意义和值。
@end itemize
@end quotation

可能存在其他属性，但它们是私有的，不能被审查或依赖。
@end deffn

@geindex fields() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses fields}@anchor{36ee}
@deffn {函数} dataclasses.fields (class_or_instance)

返回 @ref{1852,,Field} 对象的元组，用于定义此数据类的字段。 接受数据类或数据类的实例。如果没有传递一个数据类或实例将引发 @ref{1ff,,TypeError} 。 不返回 @code{ClassVar} 或 @code{InitVar} 的伪字段。
@end deffn

@geindex asdict() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses asdict}@anchor{fa3}
@deffn {函数} dataclasses.asdict (obj, *, dict_factory=dict)

将数据类`@w{`}obj`@w{`}转换为一个字典（通过使用工厂函数`@w{`}dict_factory`@w{`}）。 每个数据类被转换为其字段的字典，作为`@w{`}name: value`@w{`}键值对。数据类、字典、列表和元组被递归到。 其他对象用 @ref{4db,,copy.deepcopy()} 来复制。

在嵌套的数据类上使用 @ref{fa3,,asdict()} 的例子:

@example
@@dataclass
class Point:
     x: int
     y: int

@@dataclass
class C:
     mylist: list[Point]

p = Point(10, 20)
assert asdict(p) == @{'x': 10, 'y': 20@}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == @{'mylist': [@{'x': 0, 'y': 0@}, @{'x': 10, 'y': 4@}]@}
@end example

要创建一个浅拷贝，可以使用以下方法:

@example
dict((field.name, getattr(obj, field.name)) for field in fields(obj))
@end example

如果 @code{obj} 不是一个数据类实例, @ref{fa3,,asdict()} 引发 @ref{1ff,,TypeError} 。
@end deffn

@geindex astuple() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses astuple}@anchor{fa2}
@deffn {函数} dataclasses.astuple (obj, *, tuple_factory=tuple)

将数据类`@w{`}obj`@w{`}转换为一个元组（通过使用工厂函数`@w{`}tuple_factory`@w{`}）。 每个数据类被转换为其字段值的元组。数据类、字典、列表和元组被递归到。其他对象用 @ref{4db,,copy.deepcopy()} 来复制。

继续前一个例子:

@example
assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)
@end example

要创建一个浅拷贝，可以使用以下方法:

@example
tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))
@end example

如果`@w{`}obj`@w{`}不是一个数据类实例， @ref{fa2,,astuple()} 引发 @ref{1ff,,TypeError} 。
@end deffn

@geindex make_dataclass() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses make_dataclass}@anchor{36ef}
@deffn {函数} dataclasses.make_dataclass (cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

创建一个名为 @code{cls_name} 的新数据类，字段为 @code{fields} 中定义的字段，基类为 @code{bases} 中给出的基类，并使用 @code{namespace} 中给出的命名空间进行初始化。 @code{fields} 是一个可迭代的元素，每个元素都是 @code{name} 、 @code{(name, type)} 或 @code{(name, type, Field)} 。 如果只提供`@w{`}name`@w{`} ， @code{type} 为 @code{typing.Any} 。 @code{init} 、 @code{repr} 、 @code{eq} 、 @code{order} 、 @code{unsafe_hash} 和 @code{frozen} 的值与它们在  @ref{452,,dataclass()} 中的含义相同。

此函数不是严格要求的，因为用于任何创建带有 @code{__annotations__} 的新类的 Python 机制都可以应用 @ref{452,,dataclass()} 函数将该类转换为数据类。提供此功能是为了方便。例如:

@example
C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace=@{'add_one': lambda self: self.x + 1@})
@end example

等价于

@example
@@dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1
@end example
@end deffn

@geindex replace() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses replace}@anchor{ff3}
@deffn {函数} dataclasses.replace (obj, /, **changes)

创建一个与`@w{`}obj`@w{`}类型相同的新对象，将字段替换为来自`@w{`}changes`@w{`}的值。如果`@w{`}obj`@w{`}不是数据类，则引发 @ref{1ff,,TypeError} 。如果`@w{`}changes`@w{`}里面的值没有指定字段，引发 @ref{1ff,,TypeError} 。

新返回的对象通过调用数据类的 @ref{e2b,,__init__()} 方法创建。这确保了如果存在 @code{__post_init__()} ，其也被调用。

如果存在没有默认值的仅初始化变量，必须在调用 @ref{ff3,,replace()} 时指定，以便它们可以传递给 @ref{e2b,,__init__()} 和 @code{__post_init__()} 。

@code{changes} 包含任何定义为 @code{init=False} 的字段是错误的。在这种情况下会引发 @ref{16d,,ValueError} 。

提前提醒 @code{init=False} 字段在调用 @ref{ff3,,replace()} 时的工作方式。如果它们完全被初始化的话，它们不是从源对象复制的，而是在 @code{__post_init__()} 中初始化。估计 @code{init=False} 字段很少能被正确地使用。如果使用它们，那么使用备用类构造函数或者可能是处理实例复制的自定义 @code{replace()} （或类似命名的）方法可能是明智的。
@end deffn

@geindex is_dataclass() (在 dataclasses 模块中)
@anchor{library/dataclasses dataclasses is_dataclass}@anchor{f9f}
@deffn {函数} dataclasses.is_dataclass (obj)

如果其形参为 dataclass 或其实例则返回 @code{True}，否则返回 @code{False}。

如果你需要知道一个类是否是一个数据类的实例（而不是一个数据类本身），那么再添加一个 @code{not isinstance(obj, type)} 检查:

@example
def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)
@end example
@end deffn

@node 初始化后处理,类变量,模块级装饰器、类和函数,dataclasses --- 数据类
@anchor{library/dataclasses post-init-processing}@anchor{36f0}
@subsubsection 初始化后处理


生成的 @ref{e2b,,__init__()} 代码将调用一个名为 @code{__post_init__()} 的方法，如果在类上已经定义了 @code{__post_init__()} 。它通常被称为 @code{self.__post_init__()} 。但是，如果定义了任何 @code{InitVar} 字段，它们也将按照它们在类中定义的顺序传递给 @code{__post_init__()} 。 如果没有 @code{__ init__()} 方法生成，那么 @code{__post_init__()} 将不会被自动调用。

在其他用途中，这允许初始化依赖于一个或多个其他字段的字段值。例如:

@example
@@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b
@end example

由 @ref{452,,dataclass()} 所生成的 @ref{e2b,,__init__()} 方法不会调用基类的 @ref{e2b,,__init__()} 方法。 如果基类有需要被调用的 @ref{e2b,,__init__()} 方法，通常是在 @code{__post_init__()} 方法中调用此方法:

@example
@@dataclass
class Rectangle:
    height: float
    width: float

@@dataclass
class Square(Rectangle):
    side: float

    def __post_init__(self):
        super().__init__(self.side, self.side)
@end example

但是请注意，一般来说 dataclass 生成的 @ref{e2b,,__init__()} 方法不需要被调用，因为派生的 dataclass 将负责初始化任何自身为 dataclass 的基类的所有字段。

有关将参数传递给 @code{__post_init__()} 的方法，请参阅下面有关仅初始化变量的段落。另请参阅关于 @ref{ff3,,replace()} 处理 @code{init=False} 字段的警告。

@node 类变量,仅初始化变量,初始化后处理,dataclasses --- 数据类
@anchor{library/dataclasses class-variables}@anchor{36f1}
@subsubsection 类变量


两个地方 @ref{452,,dataclass()} 实际检查字段类型的之一是确定字段是否是如 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 所定义的类变量。它通过检查字段的类型是否为 @code{typing.ClassVar} 来完成此操作。如果一个字段是一个 @code{ClassVar} ，它将被排除在考虑范围之外，并被数据类机制忽略。这样的 @code{ClassVar} 伪字段不会由模块级的 @ref{36ee,,fields()} 函数返回。

@node 仅初始化变量,冻结的实例,类变量,dataclasses --- 数据类
@anchor{library/dataclasses init-only-variables}@anchor{36f2}
@subsubsection 仅初始化变量


另一个 @ref{452,,dataclass()} 检查类型注解地方是为了确定一个字段是否是一个仅初始化变量。它通过查看字段的类型是否为 @code{dataclasses.InitVar} 类型来实现。如果一个字段是一个 @code{InitVar} ，它被认为是一个称为仅初始化字段的伪字段。因为它不是一个真正的字段，所以它不会被模块级的 @ref{36ee,,fields()} 函数返回。仅初始化字段作为参数添加到生成的 @ref{e2b,,__init__()} 方法中，并传递给可选的 @code{__post_init__()} 方法。数据类不会使用它们。

例如，假设一个字段将从数据库初始化，如果在创建类时未提供其值:

@example
@@dataclass
class C:
    i: int
    j: int = None
    database: InitVar[DatabaseType] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)
@end example

在这种情况下， @ref{36ee,,fields()} 将返回 @code{i} 和 @code{j} 的 @ref{1852,,Field} 对象，但不包括 @code{database} 。

@node 冻结的实例,继承<2>,仅初始化变量,dataclasses --- 数据类
@anchor{library/dataclasses frozen-instances}@anchor{36f3}
@subsubsection 冻结的实例


无法创建真正不可变的 Python 对象。但是，通过将 @code{frozen=True} 传递给 @ref{452,,dataclass()} 装饰器，你可以模拟不变性。在这种情况下，数据类将向类添加 @ref{ef6,,__setattr__()} 和 @ref{1592,,__delattr__()} 方法。 些方法在调用时会引发 @ref{36f4,,FrozenInstanceError} 。

使用 @code{frozen=True} 时会有很小的性能损失： @code{__ init__()} 不能使用简单的赋值来初始化字段，并必须使用 @ref{ef6,,object.__setattr__()} 。

@node 继承<2>,默认工厂函数,冻结的实例,dataclasses --- 数据类
@anchor{library/dataclasses inheritance}@anchor{36f5}
@subsubsection 继承


当数组由 @ref{452,,dataclass()} 装饰器创建时，它会查看反向 MRO 中的所有类的基类（即从 @ref{3da,,object} 开始 ），并且对于它找到的每个数据类， 将该基类中的字段添加到字段的有序映射中。添加完所有基类字段后，它会将自己的字段添加到有序映射中。所有生成的方法都将使用这种组合的，计算的有序字段映射。由于字段是按插入顺序排列的，因此派生类会重载基类。一个例子:

@example
@@dataclass
class Base:
    x: Any = 15.0
    y: int = 0

@@dataclass
class C(Base):
    z: int = 10
    x: int = 15
@end example

最后的字段列表依次是 @code{x} 、 @code{y} 、 @code{z} 。 @code{x} 的最终类型是 @code{int} ，如类 @code{C} 中所指定的那样。

为 @code{C} 生成的 @ref{e2b,,__init__()} 方法看起来像:

@example
def __init__(self, x: int = 15, y: int = 0, z: int = 10):
@end example

@node 默认工厂函数,可变的默认值,继承<2>,dataclasses --- 数据类
@anchor{library/dataclasses default-factory-functions}@anchor{36f6}
@subsubsection 默认工厂函数


@quotation

如果一个 @ref{1182,,field()} 指定了一个 @code{default_factory} ，当需要该字段的默认值时，将使用零参数调用它。例如，要创建列表的新实例，请使用:

@example
mylist: list = field(default_factory=list)
@end example

如果一个字段被排除在 @ref{e2b,,__init__()} 之外（使用 @code{init=False} ）并且字段也指定 @code{default_factory} ，则默认的工厂函数将始终从生成的 @ref{e2b,,__init__()} 函数调用。发生这种情况是因为没有其他方法可以为字段提供初始值。
@end quotation

@node 可变的默认值,异常<17>,默认工厂函数,dataclasses --- 数据类
@anchor{library/dataclasses mutable-default-values}@anchor{36f7}
@subsubsection 可变的默认值


@quotation

Python 在类属性中存储默认成员变量值。思考这个例子，不使用数据类:

@example
class C:
    x = []
    def add(self, element):
        self.x.append(element)

o1 = C()
o2 = C()
o1.add(1)
o2.add(2)
assert o1.x == [1, 2]
assert o1.x is o2.x
@end example

请注意，类 @code{C} 的两个实例共享相同的类变量 @code{x} ，如预期的那样。

使用数据类， @emph{如果} 此代码有效:

@example
@@dataclass
class D:
    x: List = []
    def add(self, element):
        self.x += element
@end example

它生成的代码类似于:

@example
class D:
    x = []
    def __init__(self, x=x):
        self.x = x
    def add(self, element):
        self.x += element

assert D().x is D().x
@end example

这与使用类 @code{C} 的原始示例具有相同的问题。也就是说，在创建类实例时没有为 @code{x} 指定值的类 @code{D} 的两个实例将共享相同的 @code{x} 副本。由于数据类只使用普通的 Python 类创建，因此它们也会共享此行为。数据类没有通用的方法来检测这种情况。相反，如果数据类检测到类型为 @code{list} 、 @code{dict} 或 @code{set} 的默认参数，则会引发 @ref{1ff,,TypeError} 。这是一个部分解决方案，但它可以防止许多常见错误。

使用默认工厂函数是一种创建可变类型新实例的方法，并将其作为字段的默认值:

@example
@@dataclass
class D:
    x: list = field(default_factory=list)

assert D().x is not D().x
@end example
@end quotation

@node 异常<17>,,可变的默认值,dataclasses --- 数据类
@anchor{library/dataclasses exceptions}@anchor{36f8}
@subsubsection 异常


@geindex FrozenInstanceError
@anchor{library/dataclasses dataclasses FrozenInstanceError}@anchor{36f4}
@deffn {例外} dataclasses.FrozenInstanceError

在使用 @code{frozen=True} 定义的数据类上调用隐式定义的 @ref{ef6,,__setattr__()} 或 @ref{1592,,__delattr__()} 时引发。 这是 @ref{4aa,,AttributeError} 的一个子类。
@end deffn

@node contextlib --- 为 with语句上下文提供的工具,abc --- 抽象基类,dataclasses --- 数据类,Python运行时服务
@anchor{library/contextlib doc}@anchor{36f9}@anchor{library/contextlib contextlib-utilities-for-with-statement-contexts}@anchor{36fa}@anchor{library/contextlib module-contextlib}@anchor{23}
@subsection @code{contextlib} --- 为 @code{with}语句上下文提供的工具


@geindex contextlib (模块)

@strong{源代码} Lib/contextlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/contextlib.py}


__________________________________________________________________


此模块为涉及 @ref{7e4,,with} 语句的常见任务提供了实用的工具。更多信息请参见 @ref{15f5,,上下文管理器类型} 和 @ref{15f3,,with 语句上下文管理器}。

@menu
* 工具:: 
* 例子和配方:: 
* 单独使用，可重用并可重进入的上下文管理器:: 

@end menu

@node 工具,例子和配方,,contextlib --- 为 with语句上下文提供的工具
@anchor{library/contextlib utilities}@anchor{36fb}
@subsubsection 工具


提供的函数和类：

@geindex AbstractContextManager (contextlib 中的类)
@anchor{library/contextlib contextlib AbstractContextManager}@anchor{636}
@deffn {类} contextlib.AbstractContextManager

一个为实现了 @ref{d65,,object.__enter__()} 与 @ref{d66,,object.__exit__()} 的类提供的 @ref{c0e,,abstract base class}。为 @ref{d65,,object.__enter__()} 提供的一个默认实现是返回 @code{self} 而 @ref{d66,,object.__exit__()} 是一个默认返回 @code{None} 的抽象方法。 参见 @ref{15f5,,上下文管理器类型} 的定义。


3.6 新版功能.

@end deffn

@geindex AbstractAsyncContextManager (contextlib 中的类)
@anchor{library/contextlib contextlib AbstractAsyncContextManager}@anchor{489}
@deffn {类} contextlib.AbstractAsyncContextManager

一个为实现了 @ref{10e3,,object.__aenter__()} 与 @ref{10e4,,object.__aexit__()} 的类提供的 @ref{c0e,,abstract base class}。 为 @ref{10e3,,object.__aenter__()} 提供的一个默认实现是返回 @code{self} 而 @ref{10e4,,object.__aexit__()} 是一个默认返回 @code{None} 的抽象方法。 参见 @ref{1601,,异步上下文管理器} 的定义。


3.7 新版功能.

@end deffn

@geindex contextmanager() (在 contextlib 模块中)
@anchor{library/contextlib contextlib contextmanager}@anchor{c58}
@deffn {函数} @@contextlib.contextmanager

这个函数是一个 @ref{174,,decorator} ，它可以定义一个支持 @ref{7e4,,with} 语句上下文管理器的工厂函数， 而不需要创建一个类或区 @ref{d65,,__enter__()} 与 @ref{d66,,__exit__()} 方法。

尽管许多对象原生支持使用 with 语句，但有些需要被管理的资源并不是上下文管理器，并且没有实现 @code{close()} 方法而不能使用 @code{contextlib.closing} 。

下面是一个抽象的示例，展示如何确保正确的资源管理:

@example
from contextlib import contextmanager

@@contextmanager
def managed_resource(*args, **kwds):
    # Code to acquire resource, e.g.:
    resource = acquire_resource(*args, **kwds)
    try:
        yield resource
    finally:
        # Code to release resource, e.g.:
        release_resource(resource)

>>> with managed_resource(timeout=3600) as resource:
...     # Resource is released at the end of this block,
...     # even if code in the block raises an exception
@end example

被装饰的函数在被调用时，必须返回一个 @ref{a8c,,generator} 迭代器。 这个迭代器必须只 yield 一个值出来，这个值会被用在 @ref{7e4,,with} 语句中，绑定到 @code{as} 后面的变量，如果给定了的话。

当生成器发生 yield 时，嵌套在 @ref{7e4,,with} 语句中的语句体会被执行。 语句体执行完毕离开之后，该生成器将被恢复执行。 如果在该语句体中发生了未处理的异常，则该异常会在生成器发生 yield 时重新被引发。 因此，你可以使用 @ref{e3f,,try}...@ref{c19,,except}...@ref{2c3,,finally} 语句来捕获该异常（如果有的话），或确保进行了一些清理。 如果仅出于记录日志或执行某些操作（而非完全抑制异常）的目的捕获了异常，生成器必须重新引发该异常。 否则生成器的上下文管理器将向 @code{with} 语句指示该异常已经被处理，程序将立即在 @code{with} 语句之后恢复并继续执行。

@ref{c58,,contextmanager()} 使用 @ref{c57,,ContextDecorator} 因此它创建的上下文管理器不仅可以用在 @ref{7e4,,with} 语句中，还可以用作一个装饰器。当它用作一个装饰器时，每一次函数调用时都会隐式创建一个新的生成器实例（这使得 @ref{c58,,contextmanager()} 创建的上下文管理器满足了支持多次调用以用作装饰器的需求，而非“一次性”的上下文管理器）。


在 3.2 版更改: @ref{c57,,ContextDecorator} 的使用。

@end deffn

@geindex asynccontextmanager() (在 contextlib 模块中)
@anchor{library/contextlib contextlib asynccontextmanager}@anchor{488}
@deffn {函数} @@contextlib.asynccontextmanager

与 @ref{c58,,contextmanager()} 类似，但创建的是 @ref{1601,,asynchronous context manager} 。

这个函数是一个 @ref{174,,decorator} ，它可以定义一个支持 @ref{740,,async with} 语句的异步上下文管理器的工厂函数， 而不需要创建一个类或区分 @ref{10e3,,__aenter__()} 与 @ref{10e4,,__aexit__()} 方法。它必须被作用在一个 @ref{166f,,asynchronous generator} 函数上

一个简单的示例：

@example
from contextlib import asynccontextmanager

@@asynccontextmanager
async def get_connection():
    conn = await acquire_db_connection()
    try:
        yield conn
    finally:
        await release_db_connection(conn)

async def get_all_users():
    async with get_connection() as conn:
        return conn.query('SELECT ...')
@end example


3.7 新版功能.

@end deffn

@geindex closing() (在 contextlib 模块中)
@anchor{library/contextlib contextlib closing}@anchor{36fc}
@deffn {函数} contextlib.closing (thing)

返回一个在语句块执行完成时关闭 @emph{things} 的上下文管理器。这基本上等价于：

@example
from contextlib import contextmanager

@@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()
@end example

并允许你编写这样的代码：

@example
from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)
@end example

而无需显式地关闭 @code{page} 。 即使发生错误，在退出 @ref{7e4,,with} 语句块时， @code{page.close()} 也同样会被调用。
@end deffn
@anchor{library/contextlib simplifying-support-for-single-optional-context-managers}@anchor{36fd}
@geindex nullcontext() (在 contextlib 模块中)
@anchor{library/contextlib contextlib nullcontext}@anchor{486}
@deffn {函数} contextlib.nullcontext (enter_result=None)

返回一个从 @code{__enter__} 返回 @emph{enter_result} 的上下文管理器，除此之外不执行任何操作。它旨在用于可选上下文管理器的一种替代，例如：

@example
def myfunction(arg, ignore_exceptions=False):
    if ignore_exceptions:
        # Use suppress to ignore all exceptions.
        cm = contextlib.suppress(Exception)
    else:
        # Do not ignore any exceptions, cm has no effect.
        cm = contextlib.nullcontext()
    with cm:
        # Do something
@end example

一个使用 @emph{enter_result} 的例子：

@example
def process_file(file_or_path):
    if isinstance(file_or_path, str):
        # If string, open file
        cm = open(file_or_path)
    else:
        # Caller is responsible for closing file
        cm = nullcontext(file_or_path)

    with cm as file:
        # Perform processing on the file
@end example


3.7 新版功能.

@end deffn

@geindex suppress() (在 contextlib 模块中)
@anchor{library/contextlib contextlib suppress}@anchor{923}
@deffn {函数} contextlib.suppress (*exceptions)

返回一个当指定的异常在 @code{with} 语句体中发生时会屏蔽它们然后从 @code{with} 语句结束后的第一条语言开始恢复执行的上下文管理器。

与完全抑制异常的任何其他机制一样，该上下文管理器应当只用来抑制非常具体的错误，并确保该场景下静默地继续执行程序是通用的正确做法。

例如:

@example
from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

with suppress(FileNotFoundError):
    os.remove('someotherfile.tmp')
@end example

这段代码等价于：

@example
try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass

try:
    os.remove('someotherfile.tmp')
except FileNotFoundError:
    pass
@end example

该上下文管理器是 @ref{36fe,,reentrant} 。


3.4 新版功能.

@end deffn

@geindex redirect_stdout() (在 contextlib 模块中)
@anchor{library/contextlib contextlib redirect_stdout}@anchor{7bf}
@deffn {函数} contextlib.redirect_stdout (new_target)

用于将 @ref{428,,sys.stdout} 临时重定向到一个文件或类文件对象的上下文管理器。

该工具给已有的将输出硬编码写到 stdout 的函数或类提供了额外的灵活性。

例如， @ref{175,,help()} 的输出通常会被发送到 @emph{sys.stdout}。 你可以通过将输出重定向到一个 @ref{924,,io.StringIO} 对象来将该输出捕获到字符串。 替换的流是由 @code{__enter__} 返回的因此可以被用作 @ref{7e4,,with} 语句的目标:

@example
with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()
@end example

如果要把 @ref{175,,help()} 的输出写到磁盘上的一个文件，重定向该输出到一个常规文件：

@example
with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)
@end example

如果要把 @ref{175,,help()} 的输出写到 @emph{sys.stderr} ：

@example
with redirect_stdout(sys.stderr):
    help(pow)
@end example

需要注意的点在于， @ref{428,,sys.stdout} 的全局副作用意味着此上下文管理器不适合在库代码和大多数多线程应用程序中使用。它对子进程的输出没有影响。不过对于许多工具脚本而言，它仍然是一个有用的方法。

该上下文管理器是 @ref{36fe,,reentrant} 。


3.4 新版功能.

@end deffn

@geindex redirect_stderr() (在 contextlib 模块中)
@anchor{library/contextlib contextlib redirect_stderr}@anchor{7be}
@deffn {函数} contextlib.redirect_stderr (new_target)

与 @ref{7bf,,redirect_stdout()} 类似，不过是将 @ref{1eb,,sys.stderr} 重定向到一个文件或类文件对象。

该上下文管理器是 @ref{36fe,,reentrant} 。


3.5 新版功能.

@end deffn

@geindex ContextDecorator (contextlib 中的类)
@anchor{library/contextlib contextlib ContextDecorator}@anchor{c57}
@deffn {类} contextlib.ContextDecorator

一个使上下文管理器能用作装饰器的基类。

与往常一样，继承自 @code{ContextDecorator}  的上下文管理器必须实现 @code{__enter__} 与 @code{__exit__} 。即使用作装饰器， @code{__exit__} 依旧会保持可能的异常处理。

@code{ContextDecorator} 被用在 @ref{c58,,contextmanager()} 中，因此你自然获得了这项功能。

@code{ContextDecorator} 的示例:

@example
from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False

>>> @@mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing
@end example

这个改动只是针对如下形式的一个语法糖：

@example
def f():
    with cm():
        # Do stuff
@end example

@code{ContextDecorator} 使得你可以这样改写：

@example
@@cm()
def f():
    # Do stuff
@end example

这能清楚地表明， @code{cm} 作用于整个函数，而不仅仅是函数的一部分（同时也能保持不错的缩进层级）。

现有的上下文管理器即使已经有基类，也可以使用 @code{ContextDecorator} 作为混合类进行扩展：

@example
from contextlib import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False
@end example

@cartouche
@quotation 注解 
由于被装饰的函数必须能够被多次调用，因此对应的上下文管理器必须支持在多个 @ref{7e4,,with} 语句中使用。如果不是这样，则应当使用原来的具有显式 @code{with} 语句的形式使用该上下文管理器。
@end quotation
@end cartouche


3.2 新版功能.

@end deffn

@geindex ExitStack (contextlib 中的类)
@anchor{library/contextlib contextlib ExitStack}@anchor{487}
@deffn {类} contextlib.ExitStack

该上下文管理器的设计目标是使得在编码中组合其他上下文管理器和清理函数更加容易，尤其是那些可选的或由输入数据驱动的上下文管理器。

例如，通过一个如下的 with 语句可以很容易处理一组文件：

@example
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception
@end example

@ref{d65,,__enter__()} 方法返回 @ref{487,,ExitStack} 实例，并且不会执行额外的操作。

每个实例维护一个注册了一组回调的栈，这些回调在实例关闭时以相反的顺序被调用（显式或隐式地在 @ref{7e4,,with} 语句的末尾）。请注意，当一个栈实例被垃圾回收时，这些回调将 @emph{不会} 被隐式调用。

通过使用这个基于栈的模型，那些通过 @code{__init__} 方法获取资源的上下文管理器（如文件对象）能够被正确处理。

由于注册的回调函数是按照与注册相反的顺序调用的，因此最终的行为就像多个嵌套的 @ref{7e4,,with} 语句用在这些注册的回调函数上。这个行为甚至扩展到了异常处理：如果内部的回调函数抑制或替换了异常，则外部回调收到的参数是基于该更新后的状态得到的。

这是一个相对底层的 API，它负责正确处理栈里回调退出时依次展开的细节。它为相对高层的上下文管理器提供了一个合适的基础，使得它能根据应用程序的需求使用特定方式操作栈。


3.3 新版功能.


@geindex enter_context() (contextlib.ExitStack 方法)
@anchor{library/contextlib contextlib ExitStack enter_context}@anchor{36ff}
@deffn {方法} enter_context (cm)

进入一个新的上下文管理器并将其 @ref{d66,,__exit__()} 方法添加到回调栈中。 返回值是该上下文管理器自己的 @ref{d65,,__enter__()} 方法的输出结果。

这些上下文管理器可能会屏蔽异常就如当它们作为 @ref{7e4,,with} 语句的一部分直接使用时通常表现的行为一样。
@end deffn

@geindex push() (contextlib.ExitStack 方法)
@anchor{library/contextlib contextlib ExitStack push}@anchor{3700}
@deffn {方法} push (exit)

将一个上下文管理器的 @ref{d66,,__exit__()} 方法添加到回调栈。

由于 @code{__enter__} @emph{没有} 被发起调用，此方法可以被用来通过一个上下文管理器自己的 @ref{d66,,__exit__()} 覆盖 @ref{d65,,__enter__()} 的部分实现。

如果传递了一个不是上下文管理器的对象，此方法将假定它是一个回调 具有与上下文管理器的 @ref{d66,,__exit__()} 方法相同的签名的回调并会直接将其添加到回调栈中。

通过返回真值，这些回调可以通过与上下文管理器 @ref{d66,,__exit__()} 方法相同的方式屏蔽异常。

传入的对象将被该函数返回，允许此方法作为函数装饰器使用。
@end deffn

@geindex callback() (contextlib.ExitStack 方法)
@anchor{library/contextlib contextlib ExitStack callback}@anchor{3cf}
@deffn {方法} callback (callback, /, *args, **kwds)

接受一个任意的回调函数和参数并将其添加到回调栈。

与其他方法不同，通过此方式添加的回调无法屏蔽异常（因为异常的细节不会被传递给它们）。

传入的回调将被该函数返回，允许此方法作为函数装饰器使用。
@end deffn

@geindex pop_all() (contextlib.ExitStack 方法)
@anchor{library/contextlib contextlib ExitStack pop_all}@anchor{3701}
@deffn {方法} pop_all ()

将回调栈传输到一个新的 @ref{487,,ExitStack} 实例并返回它。 此操作不会发起调用任何回调 —— 作为替代，现在当新栈被关闭时它们将（显式地或是在一条 @ref{7e4,,with} 语句结束时隐式地）被发起调用。

例如，一组文件可以像下面这样以“一个都不能少”的操作方式被打开:

@example
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
    # If opening any file fails, all previously opened files will be
    # closed automatically. If all files are opened successfully,
    # they will remain open even after the with statement ends.
    # close_files() can then be invoked explicitly to close them all.
@end example
@end deffn

@geindex close() (contextlib.ExitStack 方法)
@anchor{library/contextlib contextlib ExitStack close}@anchor{3702}
@deffn {方法} close ()

立即展开回调栈，按注册时的相反顺序发起调用其中的回调。 对于任何已注册的上下文管理器和退出回调，传入的参数将表明没有发生异常。
@end deffn
@end deffn

@geindex AsyncExitStack (contextlib 中的类)
@anchor{library/contextlib contextlib AsyncExitStack}@anchor{48a}
@deffn {类} contextlib.AsyncExitStack

一个 @ref{1601,,异步上下文管理器}，类似于 @ref{487,,ExitStack}，它支持组合同步和异步上下文管理器，并拥有针对清理逻辑的协程。

@code{close()} 方法没有被实现，使用 @ref{3703,,aclose()} 替代。

@geindex enter_async_context() (contextlib.AsyncExitStack 方法)
@anchor{library/contextlib contextlib AsyncExitStack enter_async_context}@anchor{3704}
@deffn {方法} coroutine enter_async_context (cm)

与 @code{enter_context()} 相近，但是需要一个异步上下文管理器。
@end deffn

@geindex push_async_exit() (contextlib.AsyncExitStack 方法)
@anchor{library/contextlib contextlib AsyncExitStack push_async_exit}@anchor{3705}
@deffn {方法} push_async_exit (exit)

与 @code{push()} 相近，但是需要一个异步上下文管理器或协程函数。
@end deffn

@geindex push_async_callback() (contextlib.AsyncExitStack 方法)
@anchor{library/contextlib contextlib AsyncExitStack push_async_callback}@anchor{3d0}
@deffn {方法} push_async_callback (callback, /, *args, **kwds)

与 @code{callback()} 相近，但是需要一个协程函数。
@end deffn

@geindex aclose() (contextlib.AsyncExitStack 方法)
@anchor{library/contextlib contextlib AsyncExitStack aclose}@anchor{3703}
@deffn {方法} coroutine aclose ()

和 @code{close()} 相近，但是它正确处理了可等待对象。
@end deffn

从 @ref{488,,asynccontextmanager()} 的例子继续：

@example
async with AsyncExitStack() as stack:
    connections = [await stack.enter_async_context(get_connection())
        for i in range(5)]
    # All opened connections will automatically be released at the end of
    # the async with statement, even if attempts to open a connection
    # later in the list raise an exception.
@end example


3.7 新版功能.

@end deffn

@node 例子和配方,单独使用，可重用并可重进入的上下文管理器,工具,contextlib --- 为 with语句上下文提供的工具
@anchor{library/contextlib examples-and-recipes}@anchor{3706}
@subsubsection 例子和配方


本节描述了一些用于有效利用 @ref{23,,contextlib} 所提供的工具的示例和步骤。

@menu
* 支持可变数量的上下文管理器:: 
* 捕获 __enter__ 方法产生的异常:: 
* 在一个 __enter__ 方法的实现中进行清理:: 
* 替换任何对 try-finally 和旗标变量的使用:: 
* 将上下文管理器作为函数装饰器使用:: 

@end menu

@node 支持可变数量的上下文管理器,捕获 __enter__ 方法产生的异常,,例子和配方
@anchor{library/contextlib supporting-a-variable-number-of-context-managers}@anchor{3707}
@subsubsection 支持可变数量的上下文管理器


@ref{487,,ExitStack} 的主要应用场景已在该类的文档中给出：在单个 @ref{7e4,,with} 语句中支持可变数量的上下文管理器和其他清理操作。 这个可变性可以来自通过用户输入驱动所需的上下文管理器数量（例如打开用户所指定的文件集），或者来自将某些上下文管理器作为可选项。

@example
with ExitStack() as stack:
    for resource in resources:
        stack.enter_context(resource)
    if need_special_resource():
        special = acquire_special_resource()
        stack.callback(release_special_resource, special)
    # Perform operations that use the acquired resources
@end example

如上所示，@ref{487,,ExitStack} 还让使用 @ref{7e4,,with} 语句来管理任意非原生支持上下文管理器协议的资源变得相当容易。

@node 捕获 __enter__ 方法产生的异常,在一个 __enter__ 方法的实现中进行清理,支持可变数量的上下文管理器,例子和配方
@anchor{library/contextlib catching-exceptions-from-enter-methods}@anchor{3708}
@subsubsection 捕获 @code{__enter__} 方法产生的异常


有时人们会想要从 @code{__enter__} 方法的实现中捕获异常，而 @emph{不会} 无意中捕获来自 @ref{7e4,,with} 语句体或上下文管理器的 @code{__exit__} 方法的异常。 通过使用 @ref{487,,ExitStack} 可以将上下文管理协议中的步骤稍微分开以允许这样做:

@example
stack = ExitStack()
try:
    x = stack.enter_context(cm)
except Exception:
    # handle __enter__ exception
else:
    with stack:
        # Handle normal case
@end example

实际上需要这样做很可能表明下层的 API 应该提供一个直接的资源管理接口以便与 @ref{e3f,,try}/@ref{c19,,except}/@ref{2c3,,finally} 语句配合使用，但并不是所有的 API 在这方面都设计得很好。 当上下文管理器是所提供的唯一资源管理 API 时，则 @ref{487,,ExitStack} 可以让处理各种无法在 @ref{7e4,,with} 语句中直接处理的情况变得更为容易。

@node 在一个 __enter__ 方法的实现中进行清理,替换任何对 try-finally 和旗标变量的使用,捕获 __enter__ 方法产生的异常,例子和配方
@anchor{library/contextlib cleaning-up-in-an-enter-implementation}@anchor{3709}
@subsubsection 在一个 @code{__enter__} 方法的实现中进行清理


正如 @ref{3700,,ExitStack.push()} 的文档中所指出，如果在 @ref{d65,,__enter__()} 实现中的后续步骤失败则此方法在清理已分配的资源时将很有用处。

下面是为一个上下文管理器做这件事的例子，该上下文管理器可接受资源获取和释放函数，以及可选的验证函数，并将它们映射到上下文管理协议:

@example
from contextlib import contextmanager, AbstractContextManager, ExitStack

class ResourceManager(AbstractContextManager):

    def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
        self.acquire_resource = acquire_resource
        self.release_resource = release_resource
        if check_resource_ok is None:
            def check_resource_ok(resource):
                return True
        self.check_resource_ok = check_resource_ok

    @@contextmanager
    def _cleanup_on_error(self):
        with ExitStack() as stack:
            stack.push(self)
            yield
            # The validation check passed and didn't raise an exception
            # Accordingly, we want to keep the resource, and pass it
            # back to our caller
            stack.pop_all()

    def __enter__(self):
        resource = self.acquire_resource()
        with self._cleanup_on_error():
            if not self.check_resource_ok(resource):
                msg = "Failed validation for @{!r@}"
                raise RuntimeError(msg.format(resource))
        return resource

    def __exit__(self, *exc_details):
        # We don't need to duplicate any of our resource release logic
        self.release_resource()
@end example

@node 替换任何对 try-finally 和旗标变量的使用,将上下文管理器作为函数装饰器使用,在一个 __enter__ 方法的实现中进行清理,例子和配方
@anchor{library/contextlib replacing-any-use-of-try-finally-and-flag-variables}@anchor{370a}
@subsubsection 替换任何对 @code{try-finally} 和旗标变量的使用


一种你有时将看到的模式是 @code{try-finally} 语句附带一个变量来指明 @code{finally} 子句体是否要被执行。 在其最简单的形式中（它无法仅仅通过改用一条 @code{except} 子句来预先处理），看起来会是这样:

@example
cleanup_needed = True
try:
    result = perform_operation()
    if result:
        cleanup_needed = False
finally:
    if cleanup_needed:
        cleanup_resources()
@end example

就如任何基于 @code{try} 语句的代码一样，这可能会导致开发和审查方面的问题，因为设置代码和清理代码最终可能会被任意长的代码部分所分隔。

@ref{487,,ExitStack} 将允许选择在一条 @code{with} 语句末尾注册一个用于执行的回调的替代方式，等以后再决定是否跳过该回调的执行:

@example
from contextlib import ExitStack

with ExitStack() as stack:
    stack.callback(cleanup_resources)
    result = perform_operation()
    if result:
        stack.pop_all()
@end example

这允许在事先显式地指明预期的清理行为，而不需要一个单独的旗标变量。

如果某个应用程序大量使用此模式，则可以通过使用一个较小的辅助类来进一步地简化它:

@example
from contextlib import ExitStack

class Callback(ExitStack):
    def __init__(self, callback, /, *args, **kwds):
        super().__init__()
        self.callback(callback, *args, **kwds)

    def cancel(self):
        self.pop_all()

with Callback(cleanup_resources) as cb:
    result = perform_operation()
    if result:
        cb.cancel()
@end example

如果资源清理操作尚未完善地捆绑到一个独立的函数中，则仍然可以使用 @ref{3cf,,ExitStack.callback()} 的装饰器形式来提前声明资源清理:

@example
from contextlib import ExitStack

with ExitStack() as stack:
    @@stack.callback
    def cleanup_resources():
        ...
    result = perform_operation()
    if result:
        stack.pop_all()
@end example

受装饰器协议工作方式的影响，以此方式声明的回调函数无法接受任何形参。 作为替代，任何要释放的资源必须作为闭包变量来访问。

@node 将上下文管理器作为函数装饰器使用,,替换任何对 try-finally 和旗标变量的使用,例子和配方
@anchor{library/contextlib using-a-context-manager-as-a-function-decorator}@anchor{370b}
@subsubsection 将上下文管理器作为函数装饰器使用


@ref{c57,,ContextDecorator} 类允许将上下文管理器作为函数装饰器使用，而不仅在 @code{with} 语句块中使用。

例如，有时将函数或语句组包装在一个可以跟踪进入和退出时间的记录器中是很有用的。 与其为任务同时编写函数装饰器和上下文管理器，不如继承 @ref{c57,,ContextDecorator} 在一个定义中同时提供这两种能力:

@example
from contextlib import ContextDecorator
import logging

logging.basicConfig(level=logging.INFO)

class track_entry_and_exit(ContextDecorator):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        logging.info('Entering: %s', self.name)

    def __exit__(self, exc_type, exc, exc_tb):
        logging.info('Exiting: %s', self.name)
@end example

这个类的实例既可以被用作上下文管理器：

@example
with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()
@end example

也可以被用作函数装饰器：

@example
@@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()
@end example

使用上下文管理器作为函数装饰器时，有一个额外限制：没有办法得到 @ref{d65,,__enter__()} 的返回值。如果需要返回值，你仍然需要显式使用 @code{with} 语句。


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 343

@item PEP 343@footnote{https://www.python.org/dev/peps/pep-0343} - "with" 语句

Python @ref{7e4,,with} 语句的规范描述、背景和示例。
@end table


@node 单独使用，可重用并可重进入的上下文管理器,,例子和配方,contextlib --- 为 with语句上下文提供的工具
@anchor{library/contextlib single-use-reusable-and-reentrant-cms}@anchor{925}@anchor{library/contextlib single-use-reusable-and-reentrant-context-managers}@anchor{370c}
@subsubsection 单独使用，可重用并可重进入的上下文管理器


大多数上下文管理器的编写方式意味着它们只能在一个 @ref{7e4,,with} 语句中被有效使用一次。 这些一次性使用的上下文管理器必须在每次被使用时重新创建 —— 试图第二次使用它们将会触发异常或是不能正确工作。

这个常见的限制意味着通常来说都建议在 @ref{7e4,,with} 语句开头上下文管理器被使用的位置直接创建它们（如下面所有的使用示例所显示的）。

文件是一个高效的单独使用上下文管理器的例子，因为第一个 @ref{7e4,,with} 语句将关闭文件，防止任何后续的使用该文件对象的 IO 操作。

使用 @ref{c58,,contextmanager()} 创建的上下文管理器也是单次使用的上下文管理器，并会在试图第二次使用它们时报告下层生成器无法执行产生操作:

@example
>>> from contextlib import contextmanager
>>> @@contextmanager
... def singleuse():
...     print("Before")
...     yield
...     print("After")
...
>>> cm = singleuse()
>>> with cm:
...     pass
...
Before
After
>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield
@end example

@menu
* 重进入上下文管理器:: 
* 可重用的上下文管理器:: 

@end menu

@node 重进入上下文管理器,可重用的上下文管理器,,单独使用，可重用并可重进入的上下文管理器
@anchor{library/contextlib reentrant-cms}@anchor{36fe}@anchor{library/contextlib reentrant-context-managers}@anchor{370d}
@subsubsection 重进入上下文管理器


更复杂的上下文管理器可以“重进入”。 这些上下文管理器不但可以被用于多个 @ref{7e4,,with} 语句中，还可以被用于已经在使用同一个上下文管理器的 @code{with} 语句 @emph{内部}。

@ref{cc2,,threading.RLock} 是一个可重入上下管理器的例子，@ref{923,,suppress()} 和 @ref{7bf,,redirect_stdout()} 也是如此。 下面是一个非常简单的可重入使用的示例:

@example
>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
...     print("This is written to the stream rather than stdout")
...     with write_to_stream:
...         print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream
@end example

现实世界的可重入例子更可能涉及到多个函数的相互调用因此会比这个例子要复杂得多。

还要注意可重入与线程安全 @emph{不是} 一回事。 举例来说，@ref{7bf,,redirect_stdout()} 肯定不是线程安全的，因为它会通过将 @ref{428,,sys.stdout} 绑定到一个不同的流对系统状态做了全局性的修改。

@node 可重用的上下文管理器,,重进入上下文管理器,单独使用，可重用并可重进入的上下文管理器
@anchor{library/contextlib reusable-cms}@anchor{370e}@anchor{library/contextlib reusable-context-managers}@anchor{370f}
@subsubsection 可重用的上下文管理器


与单次使用和可重入上下文管理器都不同的还有“可重用”上下文管理器（或者，使用完全显式的表达应为“可重用，但不可重入”上下文管理器，因为可重入上下文管理器也会是可重用的）。 这些上下文管理器支持多次使用，但如果特定的上下文管理器实例已经在包含它的 with 语句中被使用过则将失败（或者不能正确工作）。

@ref{24d8,,threading.Lock} 是一个可重用，但是不可重入的上下文管理器的例子（对于可重入锁，则有必要使用 @ref{cc2,,threading.RLock} 来代替）。

另一个可重用，但不可重入的上下文管理器的例子是 @ref{487,,ExitStack}，因为它在离开任何 with 语句时会发起调用 @emph{所有} 当前已注册的回调，不论回调是在哪里添加的:

@example
>>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
...     stack.callback(print, "Callback: from first context")
...     print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
...     stack.callback(print, "Callback: from second context")
...     print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
...     stack.callback(print, "Callback: from outer context")
...     with stack:
...         stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context
@end example

正如这个例子的输出所显示的，在多个 with 语句中重用一个单独的栈对象可以正确工作，但调试嵌套它们就将导致栈在最内层的 with 语句结束时被清空，这不大可能是符合期望的行为。

使用单独的 @ref{487,,ExitStack} 实例而不是重复使用一个实例可以避免此问题:

@example
>>> from contextlib import ExitStack
>>> with ExitStack() as outer_stack:
...     outer_stack.callback(print, "Callback: from outer context")
...     with ExitStack() as inner_stack:
...         inner_stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Leaving outer context
Callback: from outer context
@end example

@node abc --- 抽象基类,atexit --- 退出处理器,contextlib --- 为 with语句上下文提供的工具,Python运行时服务
@anchor{library/abc doc}@anchor{3710}@anchor{library/abc abc-abstract-base-classes}@anchor{3711}@anchor{library/abc module-abc}@anchor{3}
@subsection @code{abc} --- 抽象基类


@geindex abc (模块)

@c much of the content adapted from docstrings

@strong{源代码：} Lib/abc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/abc.py}


__________________________________________________________________


该模块提供了在 Python 中定义 @ref{c0e,,抽象基类} (ABC) 的组件，在 
@geindex Python 提高建议; PEP 3119
PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119} 中已有概述。查看 PEP 文档了解为什么需要在 Python 中增加这个模块。（也可查看 
@geindex Python 提高建议; PEP 3141
PEP 3141@footnote{https://www.python.org/dev/peps/pep-3141} 以及 @ref{c1,,numbers} 模块了解基于 ABC 的数字类型继承关系。）

@ref{1d,,collections} 模块中有一些派生自 ABC 的具体类；当然这些类还可以进一步被派生。此外，@ref{1e,,collections.abc} 子模块中有一些 ABC 可被用于测试一个类或实例是否提供特定的接口，例如它是否可哈希或它是否为映射等。

该模块提供了一个元类 @ref{910,,ABCMeta}，可以用来定义抽象类，另外还提供一个工具类 @ref{90f,,ABC}，可以用它以继承的方式定义抽象基类。

@geindex ABC (abc 中的类)
@anchor{library/abc abc ABC}@anchor{90f}
@deffn {类} abc.ABC

一个使用 @ref{910,,ABCMeta} 作为元类的工具类。抽象基类可以通过从 @ref{90f,,ABC} 派生来简单地创建，这就避免了在某些情况下会令人混淆的元类用法，例如：

@example
from abc import ABC

class MyABC(ABC):
    pass
@end example

注意 @ref{90f,,ABC} 的类型仍然是 @ref{910,,ABCMeta}，因此继承 @ref{90f,,ABC} 仍然需要关注元类使用中的注意事项，比如可能会导致元类冲突的多重继承。当然你也可以直接使用 @ref{910,,ABCMeta} 作为元类来定义抽象基类，例如：

@example
from abc import ABCMeta

class MyABC(metaclass=ABCMeta):
    pass
@end example


3.4 新版功能.

@end deffn

@geindex ABCMeta (abc 中的类)
@anchor{library/abc abc ABCMeta}@anchor{910}
@deffn {类} abc.ABCMeta

用于定义抽象基类（ABC）的元类。

使用该元类以创建抽象基类。抽象基类可以像 mix-in 类一样直接被子类继承。你也可以将不相关的具体类（包括内建类）和抽象基类注册为“抽象子类” —— 这些类以及它们的子类会被内建函数 @ref{55b,,issubclass()} 识别为对应的抽象基类的子类，但是该抽象基类不会出现在其 MRO（Method Resolution Order，方法解析顺序）中，抽象基类中实现的方法也不可调用（即使通过 @ref{5e6,,super()} 调用也不行）。@footnote{@w{(1)} 
C++ 程序员需要注意：Python 中虚基类的概念和 C++ 中的并不相同。
}

使用 @ref{910,,ABCMeta} 作为元类创建的类含有如下方法：

@geindex register() (abc.ABCMeta 方法)
@anchor{library/abc abc ABCMeta register}@anchor{ab9}
@deffn {方法} register (subclass)

将“子类”注册为该抽象基类的“抽象子类”，例如：

@example
from abc import ABC

class MyABC(ABC):
    pass

MyABC.register(tuple)

assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
@end example


在 3.3 版更改: 返回注册的子类，使其能够作为类装饰器。



在 3.4 版更改: 你可以使用 @ref{90e,,get_cache_token()} 函数来检测对 @ref{ab9,,register()} 的调用。

@end deffn

你也可以在虚基类中重载这个方法。

@geindex __subclasshook__() (abc.ABCMeta 方法)
@anchor{library/abc abc ABCMeta __subclasshook__}@anchor{3712}
@deffn {方法} __subclasshook__ (subclass)

（必须定义为类方法。）

检查 @emph{subclass} 是否是该抽象基类的子类。也就是说对于那些你希望定义为该抽象基类的子类的类，你不用对每个类都调用 @ref{ab9,,register()} 方法了，而是可以直接自定义 @code{issubclass} 的行为。（这个类方法是在抽象基类的 @code{__subclasscheck__()} 方法中调用的。）

该方法必须返回 @code{True}, @code{False} 或是 @code{NotImplemented}。如果返回 @code{True}，@emph{subclass} 就会被认为是这个抽象基类的子类。如果返回 @code{False}，无论正常情况是否应该认为是其子类，统一视为不是。如果返回 @code{NotImplemented}，子类检查会按照正常机制继续执行。

@c XXX explain the "usual mechanism"
@end deffn

为了对这些概念做一演示，请看以下定义 ABC 的示例：

@example
class Foo:
    def __getitem__(self, index):
        ...
    def __len__(self):
        ...
    def get_iterator(self):
        return iter(self)

class MyIterable(ABC):

    @@abstractmethod
    def __iter__(self):
        while False:
            yield None

    def get_iterator(self):
        return self.__iter__()

    @@classmethod
    def __subclasshook__(cls, C):
        if cls is MyIterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

MyIterable.register(Foo)
@end example

ABC @code{MyIterable} 定义了标准的迭代方法 @ref{178e,,__iter__()} 作为一个抽象方法。这里给出的实现仍可在子类中被调用。@code{get_iterator()} 方法也是 @code{MyIterable} 抽象基类的一部分，但它并非必须被非抽象派生类所重载。

这里定义的 @ref{3712,,__subclasshook__()} 类方法指明了任何在其 @ref{5fe,,__dict__} (或在其通过 @ref{176a,,__mro__} 列表访问的基类) 中具有 @ref{178e,,__iter__()} 方法的类也都会被视为 @code{MyIterable}。

最后，末尾行使得 @code{Foo} 成为 @code{MyIterable} 的一个虚子类，即使它没有定义 @ref{178e,,__iter__()} 方法（它使用了以 @ref{e98,,__len__()} 和 @ref{3ad,,__getitem__()} 术语定义的旧式可迭代对象协议）。 请注意这将不会使 @code{get_iterator} 成为 @code{Foo} 的一个可用方法，它是被另外提供的。
@end deffn

此外，@ref{3,,abc} 模块还提供了这些装饰器：

@geindex abstractmethod() (在 abc 模块中)
@anchor{library/abc abc abstractmethod}@anchor{ab6}
@deffn {函数} @@abc.abstractmethod

用于声明抽象方法的装饰器。

使用此装饰器要求类的元类是 @ref{910,,ABCMeta} 或是从该类派生。一个具有派生自 @ref{910,,ABCMeta} 的元类的类不可以被实例化，除非它全部的抽象方法和特征属性均已被重载。抽象方法可通过任何普通的“super”调用机制来调用。 @ref{ab6,,abstractmethod()} 可被用于声明特性属性和描述器的抽象方法。

不支持动态添加抽象方法到一个类，或试图在方法或类被创建后修改其抽象状态等操作。 @ref{ab6,,abstractmethod()} 只会影响使用常规继承所派生的子类；通过 ABC 的 @code{register()} 方法注册的“虚子类”不会受到影响。

当 @ref{ab6,,abstractmethod()} 与其他方法描述符配合应用时，它应当被应用为最内层的装饰器，如以下用法示例所示:

@example
class C(ABC):
    @@abstractmethod
    def my_abstract_method(self, arg1):
        ...
    @@classmethod
    @@abstractmethod
    def my_abstract_classmethod(cls, arg2):
        ...
    @@staticmethod
    @@abstractmethod
    def my_abstract_staticmethod(arg3):
        ...

    @@property
    @@abstractmethod
    def my_abstract_property(self):
        ...
    @@my_abstract_property.setter
    @@abstractmethod
    def my_abstract_property(self, val):
        ...

    @@abstractmethod
    def _get_x(self):
        ...
    @@abstractmethod
    def _set_x(self, val):
        ...
    x = property(_get_x, _set_x)
@end example

为了能正确地与抽象基类机制实现互操作，描述符必须使用 @code{__isabstractmethod__} 将自身标识为抽象的。 通常，如果被用于组成描述符的任何方法都是抽象的则此属性应当为 @code{True}。 例如，Python 的内置 @ref{30f,,property} 所做的就等价于:

@example
class Descriptor:
    ...
    @@property
    def __isabstractmethod__(self):
        return any(getattr(f, '__isabstractmethod__', False) for
                   f in (self._fget, self._fset, self._fdel))
@end example

@cartouche
@quotation 注解 
不同于 Java 抽象方法，这些抽象方法可能具有一个实现。 这个实现可在重载它的类上通过 @ref{5e6,,super()} 机制来调用。 这在使用协作多重继承的框架中可以被用作超调用的一个端点。
@end quotation
@end cartouche
@end deffn

@ref{3,,abc} 模块还支持下列旧式装饰器:

@geindex abstractclassmethod() (在 abc 模块中)
@anchor{library/abc abc abstractclassmethod}@anchor{ab7}
@deffn {函数} @@abc.abstractclassmethod


3.2 新版功能.



3.3 版后已移除: 现在可以让 @ref{310,,classmethod} 配合 @ref{ab6,,abstractmethod()} 使用，使得此装饰器变得冗余。


内置 @ref{310,,classmethod()} 的子类，指明一个抽象类方法。 在其他方面它都类似于 @ref{ab6,,abstractmethod()}。

这个特例已被弃用，因为现在当 @ref{310,,classmethod()} 装饰器应用于抽象方法时它会被正确地标识为抽象的:

@example
class C(ABC):
    @@classmethod
    @@abstractmethod
    def my_abstract_classmethod(cls, arg):
        ...
@end example
@end deffn

@geindex abstractstaticmethod() (在 abc 模块中)
@anchor{library/abc abc abstractstaticmethod}@anchor{ab8}
@deffn {函数} @@abc.abstractstaticmethod


3.2 新版功能.



3.3 版后已移除: 现在可以让 @ref{311,,staticmethod} 配合 @ref{ab6,,abstractmethod()} 使用，使得此装饰器变得冗余。


内置 @ref{311,,staticmethod()} 的子类，指明一个抽象静态方法。 在其他方面它都类似于 @ref{ab6,,abstractmethod()}。

这个特例已被弃用，因为现在当 @ref{311,,staticmethod()} 装饰器应用于抽象方法时它会被正确地标识为抽象的:

@example
class C(ABC):
    @@staticmethod
    @@abstractmethod
    def my_abstract_staticmethod(arg):
        ...
@end example
@end deffn

@geindex abstractproperty() (在 abc 模块中)
@anchor{library/abc abc abstractproperty}@anchor{ab5}
@deffn {函数} @@abc.abstractproperty


3.3 版后已移除: 现在可以让 @ref{30f,,property}, @code{property.getter()}, @code{property.setter()} 和 @code{property.deleter()} 配合 @ref{ab6,,abstractmethod()} 使用，使得此装饰器变得冗余。


内置 @ref{30f,,property()} 的子类，指明一个抽象特性属性。

这个特例已被弃用，因为现在当 @ref{30f,,property()} 装饰器应用于抽象方法时它会被正确地标识为抽象的:

@example
class C(ABC):
    @@property
    @@abstractmethod
    def my_abstract_property(self):
        ...
@end example

上面的例子定义了一个只读特征属性；你也可以通过适当地将一个或多个下层方法标记为抽象的来定义可读写的抽象特征属性:

@example
class C(ABC):
    @@property
    def x(self):
        ...

    @@x.setter
    @@abstractmethod
    def x(self, val):
        ...
@end example

如果只有某些组件是抽象的，则只需更新那些组件即可在子类中创建具体的特征属性:

@example
class D(C):
    @@C.x.setter
    def x(self, val):
        ...
@end example
@end deffn

@ref{3,,abc} 模块还提供了这些函数：

@geindex get_cache_token() (在 abc 模块中)
@anchor{library/abc abc get_cache_token}@anchor{90e}
@deffn {函数} abc.get_cache_token ()

返回当前抽象基类的缓存令牌

此令牌是一个不透明对象（支持相等性测试），用于为虚子类标识抽象基类缓存的当前版本。 此令牌会在任何 ABC 上每次调用 @ref{ab9,,ABCMeta.register()} 时发生更改。


3.4 新版功能.

@end deffn

@node atexit --- 退出处理器,traceback --- 打印或检索堆栈回溯,abc --- 抽象基类,Python运行时服务
@anchor{library/atexit doc}@anchor{3713}@anchor{library/atexit atexit-exit-handlers}@anchor{3714}@anchor{library/atexit module-atexit}@anchor{b}
@subsection @code{atexit} --- 退出处理器


@geindex atexit (模块)


__________________________________________________________________


@ref{b,,atexit} 模块定义了清理函数的注册和反注册函数. 被注册的函数会在解释器正常终止时执行. @ref{b,,atexit} 会按照注册顺序的*逆序*执行; 如果你注册了 @code{A}, @code{B} 和 @code{C}, 那么在解释器终止时会依序执行 @code{C}, @code{B}, @code{A}.

@strong{注意:} 通过该模块注册的函数, 在程序被未被 Python 捕获的信号杀死时并不会执行, 在检测到 Python 内部致命错误以及调用了 @ref{188f,,os._exit()} 时也不会执行.


在 3.7 版更改: 当配合 C-API 子解释器使用时，已注册函数是它们所注册解释器中的局部对象。


@geindex register() (在 atexit 模块中)
@anchor{library/atexit atexit register}@anchor{f4d}
@deffn {函数} atexit.register (func, *args, **kwargs)

将 @emph{func} 注册为终止时执行的函数.  任何传给 @emph{func} 的可选的参数都应当作为参数传给 @ref{f4d,,register()}.  可以多次注册同样的函数及参数.

在正常的程序终止时 (举例来说, 当调用了 @ref{db2,,sys.exit()} 或是主模块的执行完成时), 所有注册过的函数都会以后进先出的顺序执行. 这样做是假定更底层的模块通常会比高层模块更早引入, 因此需要更晚清理.

如果在 exit 处理句柄执行期间引发了异常，将会打印回溯信息 (除非引发的是 @ref{6fd,,SystemExit}) 并且异常信息会被保存。 在所有 exit 处理句柄都获得运行机会之后，所引发的最后一个异常会被重新引发。

这个函数返回 @emph{func} 对象，可以把它当作装饰器使用。
@end deffn

@geindex unregister() (在 atexit 模块中)
@anchor{library/atexit atexit unregister}@anchor{3715}
@deffn {函数} atexit.unregister (func)

将 @emph{func} 移出当解释器关闭时要运行的函数列表。 如果 @emph{func} 之前未被注册则 @ref{3715,,unregister()} 将静默地不做任何事。 如果 @emph{func} 已被注册一次以上，则该函数每次在 @ref{b,,atexit} 调用栈中的出现都将被移除。 当取消注册时会在内部使用相等性比较 (@code{==})，因而函数引用不需要具有匹配的标识号。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{de,,readline}

使用 @ref{b,,atexit} 读写 @ref{de,,readline} 历史文件的有用的例子。
@end table


@menu
* atexit 示例:: 

@end menu

@node atexit 示例,,,atexit --- 退出处理器
@anchor{library/atexit atexit-example}@anchor{3716}@anchor{library/atexit id1}@anchor{3717}
@subsubsection @code{atexit} 示例


以下简单例子演示了一个模块在被导入时如何从文件初始化一个计数器，并在程序终结时自动保存计数器的更新值，此操作不依赖于应用在终结时对此模块进行显式调用。:

@example
try:
    with open('counterfile') as infile:
        _count = int(infile.read())
except FileNotFoundError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    with open('counterfile', 'w') as outfile:
        outfile.write('%d' % _count)

import atexit

atexit.register(savecounter)
@end example

位置和关键字参数也可传入 @ref{f4d,,register()} 以便传递给被调用的已注册函数:

@example
def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
@end example

作为 @ref{174,,decorator}: 使用:

@example
import atexit

@@atexit.register
def goodbye():
    print('You are now leaving the Python sector.')
@end example

只有在函数不需要任何参数调用时才能工作.

@node traceback --- 打印或检索堆栈回溯,__future__ --- Future 语句定义,atexit --- 退出处理器,Python运行时服务
@anchor{library/traceback doc}@anchor{3718}@anchor{library/traceback module-traceback}@anchor{11c}@anchor{library/traceback traceback-print-or-retrieve-a-stack-traceback}@anchor{3719}
@subsection @code{traceback} --- 打印或检索堆栈回溯


@geindex traceback (模块)

@strong{源代码：} Lib/traceback.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/traceback.py}


__________________________________________________________________


该模块提供了一个标准接口来提取、格式化和打印 Python 程序的堆栈跟踪结果。它完全模仿Python 解释器在打印堆栈跟踪结果时的行为。当您想要在程序控制下打印堆栈跟踪结果时，例如在“封装”解释器时，这是非常有用的。

@geindex 对象; traceback

这个模块使用 traceback 对象 —— 这是存储在 @ref{35bc,,sys.last_traceback} 中的对象类型变量，并作为 @ref{d2f,,sys.exc_info()} 的第三项被返回。

这个模块定义了以下函数：

@geindex print_tb() (在 traceback 模块中)
@anchor{library/traceback traceback print_tb}@anchor{872}
@deffn {函数} traceback.print_tb (tb, limit=None, file=None)

如果*limit*是正整数，那么从 traceback 对象 "tb" 输出最高 @emph{limit} 个（从调用函数开始的）栈的堆栈回溯‎条目‎；如果 @emph{limit} 是负数就输出 @code{abs(limit)} 个回溯条目；又如果 @emph{limit} 被省略或者为 @code{None}，那么就会输出所有回溯条目。如果 @emph{file} 被省略或为 @code{None} 那么就会输出至标准输出`@w{`}sys.stderr`@w{`}否则它应该是一个打开的文件或者文件类对象来接收输出


在 3.5 版更改: 添加了对负数值 @emph{limit} 的支持

@end deffn

@geindex print_exception() (在 traceback 模块中)
@anchor{library/traceback traceback print_exception}@anchor{2236}
@deffn {函数} traceback.print_exception (etype, value, tb, limit=None, file=None, chain=True)

打印回溯对象 @emph{tb} 到 @emph{file} 的异常信息和整个堆栈回溯。这和 @ref{872,,print_tb()} 比有以下方面不同：


@itemize *

@item 
如果 @emph{tb} 不为 @code{None}，它将打印头部 @code{Traceback (most recent call last):}

@item 
它将在输出完堆栈回溯后，输出异常中的  @emph{etype} 和 @emph{value} 信息
@end itemize

@geindex ^ (caret); marker


@itemize *

@item 
如果 @emph{type(value)} 为 @ref{562,,SyntaxError} 且 @emph{value} 具有适当的格式，它会打印发生语法错误的行并用一个圆点来指明错误的大致位置。
@end itemize

可选的 @emph{limit} 参数具有与 @ref{872,,print_tb()} 的相同含义。 如果 @emph{chain} 为真值（默认），则链式异常（异常的 @code{__cause__} 或 @code{__context__} 属性）也将被打印出来，就像解释器本身在打印未处理的异常时一样。


在 3.5 版更改: @emph{etype} 参数会被忽略并根据 @emph{value} 推断出来。

@end deffn

@geindex print_exc() (在 traceback 模块中)
@anchor{library/traceback traceback print_exc}@anchor{371a}
@deffn {函数} traceback.print_exc (limit=None, file=None, chain=True)

这是 @code{print_exception(*sys.exc_info(), limit, file, chain)} 的简写。
@end deffn

@geindex print_last() (在 traceback 模块中)
@anchor{library/traceback traceback print_last}@anchor{371b}
@deffn {函数} traceback.print_last (limit=None, file=None, chain=True)

这是 @code{print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)} 的简写。 通常它将只在异常到达交互提示之后才会起作用 (参见 @ref{d2a,,sys.last_type})。
@end deffn

@geindex print_stack() (在 traceback 模块中)
@anchor{library/traceback traceback print_stack}@anchor{873}
@deffn {函数} traceback.print_stack (f=None, limit=None, file=None)

如果 @emph{limit} 为正数则打印至多 @emph{limit} 个栈回溯条目（从发起调用点开始）。 在其他情况下，则打印最后 @code{abs(limit)} 个条目。 如果 @emph{limit} 被省略或为 @code{None}，则会打印所有条目。 可选的 @emph{f} 参数可被用来指明一个用于开始的替代栈。 可选的 @emph{file} 参数具有与 @ref{872,,print_tb()} 的相同含义。


在 3.5 版更改: 添加了对负数值 @emph{limit} 的支持

@end deffn

@geindex extract_tb() (在 traceback 模块中)
@anchor{library/traceback traceback extract_tb}@anchor{371c}
@deffn {函数} traceback.extract_tb (tb, limit=None)

返回一个 @ref{870,,StackSummary} 对象来代表从回溯对象 @emph{tb} 提取的 "预处理" 栈回溯条目列表。 它适用于栈回溯的替代格式化。 可选的 @emph{limit} 参数具有与 @ref{872,,print_tb()} 的相同含义。 "预处理" 栈回溯条目是一个 @ref{871,,FrameSummary} 对象，其中包含代表通常为栈回溯打印的信息的 @code{filename}, @code{lineno}, @code{name} 和 @code{line} 等属性。 @code{line} 是一个去除了前导和末尾空白符的字符串；如果源代码不可用则它将为 @code{None}。
@end deffn

@geindex extract_stack() (在 traceback 模块中)
@anchor{library/traceback traceback extract_stack}@anchor{371d}
@deffn {函数} traceback.extract_stack (f=None, limit=None)

从当前的栈帧提取原始回溯信息。 返回值具有与 @ref{371c,,extract_tb()} 的相同格式。 可选的 @emph{f} 和 @emph{limit} 参数具有与 @ref{873,,print_stack()} 的相同含义。
@end deffn

@geindex format_list() (在 traceback 模块中)
@anchor{library/traceback traceback format_list}@anchor{371e}
@deffn {函数} traceback.format_list (extracted_list)

给定一个由元组或如 @ref{371c,,extract_tb()} 或 @ref{371d,,extract_stack()} 所返回的 @ref{871,,FrameSummary} 对象组成的列表，返回一个可打印的字符串列表。 结果列表中的每个字符串都对应于参数列表中具有相同索引号的条目。 每个字符串以一个换行符结束；对于那些源文本行不为 @code{None} 的条目，字符串也可能包含内部换行符。
@end deffn

@geindex format_exception_only() (在 traceback 模块中)
@anchor{library/traceback traceback format_exception_only}@anchor{3375}
@deffn {函数} traceback.format_exception_only (etype, value)

Format the exception part of a traceback.  The arguments are the exception
type and value such as given by @code{sys.last_type} and @code{sys.last_value}.
The return value is a list of strings, each ending in a newline.  Normally,
the list contains a single string; however, for @ref{562,,SyntaxError}
exceptions, it contains several lines that (when printed) display detailed
information about where the syntax error occurred.  The message indicating
which exception occurred is the always last string in the list.
@end deffn

@geindex format_exception() (在 traceback 模块中)
@anchor{library/traceback traceback format_exception}@anchor{371f}
@deffn {函数} traceback.format_exception (etype, value, tb, limit=None, chain=True)

格式化一个栈跟踪和异常信息。 参数的含义与传给 @ref{2236,,print_exception()} 的相应参数相同。 返回值是一个字符串列表，每个字符串都以一个换行符结束且有些还包含内部换行符。 当这些行被拼接并打印时，打印的文本与 @ref{2236,,print_exception()} 的完全相同。


在 3.5 版更改: @emph{etype} 参数会被忽略并根据 @emph{value} 推断出来。

@end deffn

@geindex format_exc() (在 traceback 模块中)
@anchor{library/traceback traceback format_exc}@anchor{3720}
@deffn {函数} traceback.format_exc (limit=None, chain=True)

这类似于 @code{print_exc(limit)} 但会返回一个字符串而不是打印到一个文件。
@end deffn

@geindex format_tb() (在 traceback 模块中)
@anchor{library/traceback traceback format_tb}@anchor{3678}
@deffn {函数} traceback.format_tb (tb, limit=None)

是 @code{format_list(extract_tb(tb, limit))} 的简写形式。
@end deffn

@geindex format_stack() (在 traceback 模块中)
@anchor{library/traceback traceback format_stack}@anchor{3721}
@deffn {函数} traceback.format_stack (f=None, limit=None)

是 @code{format_list(extract_stack(f, limit))} 的简写形式。
@end deffn

@geindex clear_frames() (在 traceback 模块中)
@anchor{library/traceback traceback clear_frames}@anchor{9e0}
@deffn {函数} traceback.clear_frames (tb)

通过调用每个帧对象的 @code{clear()} 方法来清除回溯 @emph{tb} 中所有栈帧的局部变量。


3.4 新版功能.

@end deffn

@geindex walk_stack() (在 traceback 模块中)
@anchor{library/traceback traceback walk_stack}@anchor{86d}
@deffn {函数} traceback.walk_stack (f)

从给定的帧开始访问 @code{f.f_back} 之后的栈，产生每一帧的帧和行号。 如果 @emph{f} 为 @code{None}，则会使用当前栈。 这个辅助函数要与 @ref{3722,,StackSummary.extract()} 一起使用。


3.5 新版功能.

@end deffn

@geindex walk_tb() (在 traceback 模块中)
@anchor{library/traceback traceback walk_tb}@anchor{86e}
@deffn {函数} traceback.walk_tb (tb)

访问 @code{tb_next} 之后的回溯并产生每一帧的帧和行号。 这个辅助函数要与 @ref{3722,,StackSummary.extract()} 一起使用。


3.5 新版功能.

@end deffn

此模块还定义了以下的类:

@menu
* TracebackException 对象:: 
* StackSummary 对象:: 
* FrameSummary 对象:: 
* 回溯示例:: 

@end menu

@node TracebackException 对象,StackSummary 对象,,traceback --- 打印或检索堆栈回溯
@anchor{library/traceback tracebackexception-objects}@anchor{3723}
@subsubsection @code{TracebackException} 对象



3.5 新版功能.


@ref{86f,,TracebackException} 对象基于实际的异常创建通过轻量的方式捕获数据以便随后打印。

@geindex TracebackException (traceback 中的类)
@anchor{library/traceback traceback TracebackException}@anchor{86f}
@deffn {类} traceback.TracebackException (exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False)

捕获一个异常以便随后渲染。 @emph{limit}, @emph{lookup_lines} 和 @emph{capture_locals} 的含义与 @ref{870,,StackSummary} 类的相同。

请注意当局部变量被捕获时，它们也会被显示在回溯中。

@geindex __cause__ (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException __cause__}@anchor{3724}
@deffn {属性} __cause__

原始 @code{__cause__} 的 @ref{86f,,TracebackException}。
@end deffn

@geindex __context__ (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException __context__}@anchor{3725}
@deffn {属性} __context__

原始 @code{__context__} 的 @ref{86f,,TracebackException}。
@end deffn

@geindex __suppress_context__ (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException __suppress_context__}@anchor{3726}
@deffn {属性} __suppress_context__

来自原始异常的 @code{__suppress_context__}。
@end deffn

@geindex stack (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException stack}@anchor{3727}
@deffn {属性} stack

代表回溯的 @ref{870,,StackSummary}。
@end deffn

@geindex exc_type (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException exc_type}@anchor{3728}
@deffn {属性} exc_type

原始回溯的类。
@end deffn

@geindex filename (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException filename}@anchor{3729}
@deffn {属性} filename

针对语法错误 —— 错误发生所在的文件名。
@end deffn

@geindex lineno (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException lineno}@anchor{372a}
@deffn {属性} lineno

针对语法错误 —— 错误发生所在的行号。
@end deffn

@geindex text (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException text}@anchor{372b}
@deffn {属性} text

针对语法错误 —— 错误发生所在的文本。
@end deffn

@geindex offset (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException offset}@anchor{372c}
@deffn {属性} offset

针对语法错误 —— 错误发生所在的文本内部的偏移量。
@end deffn

@geindex msg (traceback.TracebackException 属性)
@anchor{library/traceback traceback TracebackException msg}@anchor{372d}
@deffn {属性} msg

针对语法错误 —— 编译器错误消息。
@end deffn

@geindex from_exception() (traceback.TracebackException 类方法)
@anchor{library/traceback traceback TracebackException from_exception}@anchor{372e}
@deffn {方法} classmethod from_exception (exc, *, limit=None, lookup_lines=True, capture_locals=False)

捕获一个异常以便随后渲染。 @emph{limit}, @emph{lookup_lines} 和 @emph{capture_locals} 的含义与 @ref{870,,StackSummary} 类的相同。

请注意当局部变量被捕获时，它们也会被显示在回溯中。
@end deffn

@geindex format() (traceback.TracebackException 方法)
@anchor{library/traceback traceback TracebackException format}@anchor{372f}
@deffn {方法} format (*, chain=True)

格式化异常。

如果 @emph{chain} 不为 @code{True}，则 @code{__cause__} 和 @code{__context__} 将不会被格式化。

返回值是一个字符串的生成器，其中每个字符串都以换行符结束并且有些还会包含内部换行符。 @ref{2236,,print_exception()} 是此方法的一个包装器，它只是将这些行打印到一个文件。

指明发生了哪种异常的消息总会是输出中的最后一个字符串。
@end deffn

@geindex format_exception_only() (traceback.TracebackException 方法)
@anchor{library/traceback traceback TracebackException format_exception_only}@anchor{3730}
@deffn {方法} format_exception_only ()

格式化回溯的异常部分。

返回值是一个字符串的生成器，每个字符串都以一个换行符结束。

通常，生成器会发出单个字符串；不过，对于 @ref{562,,SyntaxError} 异常，它会发出（当打印时）显示有关语法错误发生在何处的详细信息的多个行。

指明发生了哪种异常的消息总会是输出中的最后一个字符串。
@end deffn
@end deffn

@node StackSummary 对象,FrameSummary 对象,TracebackException 对象,traceback --- 打印或检索堆栈回溯
@anchor{library/traceback stacksummary-objects}@anchor{3731}
@subsubsection @code{StackSummary} 对象



3.5 新版功能.


代表一个可被格式化的调用栈的 @ref{870,,StackSummary} 对象。

@geindex StackSummary (traceback 中的类)
@anchor{library/traceback traceback StackSummary}@anchor{870}
@deffn {类} traceback.StackSummary

@geindex extract() (traceback.StackSummary 类方法)
@anchor{library/traceback traceback StackSummary extract}@anchor{3722}
@deffn {方法} classmethod extract (frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)

构造一个来自帧生成器的 @ref{870,,StackSummary} 对象（如 @ref{86d,,walk_stack()} 或 @ref{86e,,walk_tb()} 所返回的一样）。

如果提供了 @emph{limit}，则只从 @emph{frame_gen} 提取指定数量的帧。 如果 @emph{lookup_lines} 为 @code{False}，则返回的 @ref{871,,FrameSummary} 对象将不会读入它们的行，这使得创建 @ref{870,,StackSummary} 的开销更低（如果它不会被实际格式化这就会很有价值）。 如果 @emph{capture_locals} 为 @code{True} 则每个 @ref{871,,FrameSummary} 中的局部变量会被捕获为对象表示形式。
@end deffn

@geindex from_list() (traceback.StackSummary 类方法)
@anchor{library/traceback traceback StackSummary from_list}@anchor{3732}
@deffn {方法} classmethod from_list (a_list)

从所提供的 @ref{871,,FrameSummary} 对象列表或旧式的元组列表构造一个 @ref{870,,StackSummary} 对象。 每个元组都应当是以文件、行号、名称和行为元素的 4 元组。
@end deffn

@geindex format() (traceback.StackSummary 方法)
@anchor{library/traceback traceback StackSummary format}@anchor{3733}
@deffn {方法} format ()

返回一个可打印的字符串列表。 结果列表中的每个字符串各自对应来自于栈的单独帧。 每个字符串都以一个换行符结束；对于带有源文本行的条目来说，字符串还可能包含内部换行符。

对于同一帧与行的长序列，将显示前几个重复项，后面跟一个指明之后的实际重复次数的总结行。


在 3.6 版更改: 重复帧的长序列现在将被缩减。

@end deffn
@end deffn

@node FrameSummary 对象,回溯示例,StackSummary 对象,traceback --- 打印或检索堆栈回溯
@anchor{library/traceback framesummary-objects}@anchor{3734}
@subsubsection @code{FrameSummary} 对象



3.5 新版功能.


@ref{871,,FrameSummary} 对象代表回溯中的一个单独帧。

@geindex FrameSummary (traceback 中的类)
@anchor{library/traceback traceback FrameSummary}@anchor{871}
@deffn {类} traceback.FrameSummary (filename, lineno, name, lookup_line=True, locals=None, line=None)

代表回溯或栈中被格式化或打印的一个单独帧。 它有时可能还带有包括在其中的帧局部变量的字符串化版本。 如果 @emph{lookup_line} 为 @code{False}，则不会查找源代码直到 @ref{871,,FrameSummary} 已经访问了 @code{line} 属性（这还将发生在将其转换为元组时）。 @code{line} 可能会被直接提供，并将完全阻止行查找的发生。 @emph{locals} 是一个可选的局部变量字典，如果有提供的话这些变量的表示形式将被存储在摘要中以便随后显示。
@end deffn

@node 回溯示例,,FrameSummary 对象,traceback --- 打印或检索堆栈回溯
@anchor{library/traceback traceback-example}@anchor{3735}@anchor{library/traceback traceback-examples}@anchor{3736}
@subsubsection 回溯示例


这个简单示例是一个基本的读取-求值-打印循环，类似于（但实用性小于）标准 Python 交互式解释器循环。 对于解释器循环的更完整实现，请参阅 @ref{1a,,code} 模块。

@example
import sys, traceback

def run_user_code(envdir):
    source = input(">>> ")
    try:
        exec(source, envdir)
    except Exception:
        print("Exception in user code:")
        print("-"*60)
        traceback.print_exc(file=sys.stdout)
        print("-"*60)

envdir = @{@}
while True:
    run_user_code(envdir)
@end example

下面的例子演示了打印和格式化异常与回溯的不同方式:

@example
import sys, traceback

def lumberjack():
    bright_side_of_death()

def bright_side_of_death():
    return tuple()[0]

try:
    lumberjack()
except IndexError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print("*** print_exception:")
    # exc_type below is ignored on 3.5 and later
    traceback.print_exception(exc_type, exc_value, exc_traceback,
                              limit=2, file=sys.stdout)
    print("*** print_exc:")
    traceback.print_exc(limit=2, file=sys.stdout)
    print("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print(formatted_lines[0])
    print(formatted_lines[-1])
    print("*** format_exception:")
    # exc_type below is ignored on 3.5 and later
    print(repr(traceback.format_exception(exc_type, exc_value,
                                          exc_traceback)))
    print("*** extract_tb:")
    print(repr(traceback.extract_tb(exc_traceback)))
    print("*** format_tb:")
    print(repr(traceback.format_tb(exc_traceback)))
    print("*** tb_lineno:", exc_traceback.tb_lineno)
@end example

该示例的输出看起来像上这样:

@example
*** print_tb:
  File "<doctest...>", line 10, in <module>
    lumberjack()
*** print_exception:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** print_exc:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range
*** format_exception:
['Traceback (most recent call last):\n',
 '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
 'IndexError: tuple index out of range\n']
*** extract_tb:
[<FrameSummary file <doctest...>, line 10 in <module>>,
 <FrameSummary file <doctest...>, line 4 in lumberjack>,
 <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
*** format_tb:
['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
*** tb_lineno: 10
@end example

下面的例子演示了打印和格式化栈的不同方式:

@example
>>> import traceback
>>> def another_function():
...     lumberstack()
...
>>> def lumberstack():
...     traceback.print_stack()
...     print(repr(traceback.extract_stack()))
...     print(repr(traceback.format_stack()))
...
>>> another_function()
  File "<doctest>", line 10, in <module>
    another_function()
  File "<doctest>", line 3, in another_function
    lumberstack()
  File "<doctest>", line 6, in lumberstack
    traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
 ('<doctest>', 3, 'another_function', 'lumberstack()'),
 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
['  File "<doctest>", line 10, in <module>\n    another_function()\n',
 '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
 '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']
@end example

最后这个例子演示了最后几个格式化函数:

@example
>>> import traceback
>>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
 '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
>>> an_error = IndexError('tuple index out of range')
>>> traceback.format_exception_only(type(an_error), an_error)
['IndexError: tuple index out of range\n']
@end example

@node __future__ --- Future 语句定义,gc --- 垃圾回收器接口,traceback --- 打印或检索堆栈回溯,Python运行时服务
@anchor{library/__future__ doc}@anchor{3737}@anchor{library/__future__ future-future-statement-definitions}@anchor{3738}@anchor{library/__future__ module-__future__}@anchor{0}
@subsection @code{__future__} --- Future 语句定义


@geindex __future__ (模块)

@strong{源代码：} Lib/__future__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/__future__.py}


__________________________________________________________________


@ref{0,,__future__} 是一个真正的模块，这主要有 3 个原因：


@itemize *

@item 
避免混淆已有的分析 import 语句并查找 import 的模块的工具。

@item 
确保 @ref{16f4,,future 语句} 在 2.1 之前的版本运行时至少能抛出 runtime 异常（import @ref{0,,__future__} 会失败，因为 2.1 版本之前没有这个模块）。

@item 
当引入不兼容的修改时，可以记录其引入的时间以及强制使用的时间。这是一种可执行的文档，并且可以通过 import @ref{0,,__future__} 来做程序性的检查。
@end itemize

@code{__future__.py} 中的每一条语句都是以下格式的：

@example
FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)
@end example

通常 @emph{OptionalRelease} 要比 @emph{MandatoryRelease} 小，并且都是和 @ref{bf6,,sys.version_info} 格式一致的 5 元素元组。

@example
(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)
@end example

@emph{OptionalRelease} 记录了一个特性首次发布时的 Python 版本。

在 @emph{MandatoryRelases} 还没有发布时，@emph{MandatoryRelease} 表示该特性会变成语言的一部分的预测时间。

其他情况下，@emph{MandatoryRelease} 用来记录这个特性是何时成为语言的一部分的。从该版本往后，使用该特性将不需要 future 语句，不过很多人还是会加上对应的 import。

@emph{MandatoryRelease} 也可能是 @code{None}, 表示这个特性已经被撤销。

@code{_Feature} 类的实例有两个对应的方法，@code{getOptionalRelease()} 和 @code{getMandatoryRelease()}。

@emph{CompilerFlag} 是一个（位）标记，对于动态编译的代码，需要将这个标记作为第四个参数传入内建函数 @ref{2ee,,compile()} 中以开启对应的特性。这个标记存储在 @code{_Feature} 类实例的 @code{compiler_flag} 属性中。

@ref{0,,__future__} 中不会删除特性的描述。从 Python 2.1 中首次加入以来，通过这种方式引入了以下特性：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

特性

@tab

可选版本

@tab

强制加入版本

@tab

效果

@item

nested_scopes

@tab

2.1.0b1

@tab

2.2

@tab

@geindex Python 提高建议; PEP 227
PEP 227@footnote{https://www.python.org/dev/peps/pep-0227}:
@emph{Statically Nested Scopes}

@item

generators

@tab

2.2.0a1

@tab

2.3

@tab

@geindex Python 提高建议; PEP 255
PEP 255@footnote{https://www.python.org/dev/peps/pep-0255}:
@emph{Simple Generators}

@item

division

@tab

2.2.0a2

@tab

3.0

@tab

@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238}:
@emph{Changing the Division Operator}

@item

absolute_import

@tab

2.5.0a1

@tab

3.0

@tab

@geindex Python 提高建议; PEP 328
PEP 328@footnote{https://www.python.org/dev/peps/pep-0328}:
@emph{Imports: Multi-Line and Absolute/Relative}

@item

with_statement

@tab

2.5.0a1

@tab

2.6

@tab

@geindex Python 提高建议; PEP 343
PEP 343@footnote{https://www.python.org/dev/peps/pep-0343}:
@emph{The "with" Statement}

@item

print_function

@tab

2.6.0a2

@tab

3.0

@tab

@geindex Python 提高建议; PEP 3105
PEP 3105@footnote{https://www.python.org/dev/peps/pep-3105}:
@emph{Make print a function}

@item

unicode_literals

@tab

2.6.0a2

@tab

3.0

@tab

@geindex Python 提高建议; PEP 3112
PEP 3112@footnote{https://www.python.org/dev/peps/pep-3112}:
@emph{Bytes literals in Python 3000}

@item

generator_stop

@tab

3.5.0b1

@tab

3.7

@tab

@geindex Python 提高建议; PEP 479
PEP 479@footnote{https://www.python.org/dev/peps/pep-0479}:
@emph{StopIteration handling inside generators}

@item

annotations

@tab

3.7.0b1

@tab

TBD @footnote{@w{(1)} 
先前计划在 Python 3.10 中强制使用 @code{from __future__ import annotations} ，但Python指导委员会两次决定推迟这一改变（ @uref{https://mail.python.org/archives/list/python-dev@@python.org/message/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/,Python 3.10 的公告} ； @uref{https://mail.python.org/archives/list/python-dev@@python.org/message/VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/,Python 3.11 的公告} ）。目前还没有做出最终决定。参见 
@geindex Python 提高建议; PEP 563
@uref{https://www.python.org/dev/peps/pep-0563,PEP 563} 和 
@geindex Python 提高建议; PEP 649
@uref{https://www.python.org/dev/peps/pep-0649,PEP 649} 。
}

@tab

@geindex Python 提高建议; PEP 563
PEP 563@footnote{https://www.python.org/dev/peps/pep-0563}:
@emph{Postponed evaluation of annotations}

@end multitable


@c XXX Adding a new entry?  Remember to update simple_stmts.rst, too.


@subsubheading 参见



@table @asis

@item @ref{16f4,,future 语句}

编译器怎样处理 future import。
@end table


@node gc --- 垃圾回收器接口,inspect --- 检查对象,__future__ --- Future 语句定义,Python运行时服务
@anchor{library/gc doc}@anchor{3739}@anchor{library/gc gc-garbage-collector-interface}@anchor{373a}@anchor{library/gc module-gc}@anchor{84}
@subsection @code{gc} --- 垃圾回收器接口


@geindex gc (模块)


__________________________________________________________________


此模块提供可选的垃圾回收器的接口，提供的功能包括：关闭收集器、调整收集频率、设置调试选项。它同时提供对回收器找到但是无法释放的不可达对象的访问。由于 Python 使用了带有引用计数的回收器，如果你确定你的程序不会产生循环引用，你可以关闭回收器。可以通过调用 @code{gc.disable()} 关闭自动垃圾回收。若要调试一个存在内存泄漏的程序，调用 @code{gc.set_debug(gc.DEBUG_LEAK)} ；需要注意的是，它包含 @code{gc.DEBUG_SAVEALL} ，使得被垃圾回收的对象会被存放在 gc.garbage 中以待检查。

@ref{84,,gc} 模块提供下列函数：

@geindex enable() (在 gc 模块中)
@anchor{library/gc gc enable}@anchor{373b}
@deffn {函数} gc.enable ()

启用自动垃圾回收
@end deffn

@geindex disable() (在 gc 模块中)
@anchor{library/gc gc disable}@anchor{373c}
@deffn {函数} gc.disable ()

停用自动垃圾回收
@end deffn

@geindex isenabled() (在 gc 模块中)
@anchor{library/gc gc isenabled}@anchor{373d}
@deffn {函数} gc.isenabled ()

如果启用了自动回收则返回 @code{True}。
@end deffn

@geindex collect() (在 gc 模块中)
@anchor{library/gc gc collect}@anchor{362}
@deffn {函数} gc.collect (generation=2)

若被调用时不包含参数，则启动完全的垃圾回收。可选的参数 @emph{generation} 可以是一个整数，指明需要回收哪一代（从 0 到 2 ）的垃圾。当参数 @emph{generation} 无效时，会引发 @ref{16d,,ValueError} 异常。返回发现的不可达对象的数目。

每当运行完整收集或最高代 (2) 收集时，为多个内置类型所维护的空闲列表会被清空。 由于特定类型特别是 @ref{1fe,,float} 的实现，在某些空闲列表中并非所有项都会被释放。
@end deffn

@geindex set_debug() (在 gc 模块中)
@anchor{library/gc gc set_debug}@anchor{373e}
@deffn {函数} gc.set_debug (flags)

设置垃圾回收器的调试标识位。调试信息会被写入 @code{sys.stderr} 。此文档末尾列出了各个标志位及其含义；可以使用位操作对多个标志位进行设置以控制调试器。
@end deffn

@geindex get_debug() (在 gc 模块中)
@anchor{library/gc gc get_debug}@anchor{373f}
@deffn {函数} gc.get_debug ()

返回当前调试标识位。
@end deffn

@geindex get_objects() (在 gc 模块中)
@anchor{library/gc gc get_objects}@anchor{305}
@deffn {函数} gc.get_objects (generation=None)

返回一个收集器所跟踪的所有对象的列表，所返回的列表除外。 如果 @emph{generation} 不为 None，则只返回收集器所跟踪的属于该生成的对象。


在 3.8 版更改: 新的 @emph{generation} 形参。


引发一个 @ref{fec,,审计事件} @code{gc.get_objects}，附带参数 @code{generation}。
@end deffn

@geindex get_stats() (在 gc 模块中)
@anchor{library/gc gc get_stats}@anchor{944}
@deffn {函数} gc.get_stats ()

返回一个包含三个字典对象的列表，每个字典分别包含对应代的从解释器开始运行的垃圾回收统计数据。字典的键的数目在将来可能发生改变，目前每个字典包含以下内容：


@itemize *

@item 
@code{collections} 是该代被回收的次数；

@item 
@code{collected} 是该代中被回收的对象总数；

@item 
@code{uncollectable} 是在这一代中被发现无法收集的对象总数 （因此被移动到 @ref{c1b,,garbage} 列表中）。
@end itemize


3.4 新版功能.

@end deffn

@geindex set_threshold() (在 gc 模块中)
@anchor{library/gc gc set_threshold}@anchor{3740}
@deffn {函数} gc.set_threshold (threshold0[, threshold1[, threshold2]])

设置垃圾回收阈值（收集频率）。 将 @emph{threshold0} 设为零会禁用回收。

垃圾回收器把所有对象分类为三代，其依据是对象在多少次垃圾回收后幸存。 新建对象会被放在最年轻代（第 @code{0} 代）。 如果一个对象在一次垃圾回收后幸存，它会被移入下一个较老代。 由于第 @code{2} 代是最老代，这一代的对象在一次垃圾回收后仍会保留原样。 为了确定何时要运行，垃圾回收器会跟踪自上一次回收后对象分配和释放的数量。 当分配数量减去释放数量的结果值大于 @emph{threshold0} 时，垃圾回收就会开始。 初始时只有第 @code{0} 代会被检查。 如果自第 @code{1} 代被检查后第 @code{0} 代已被检查超过 @emph{threshold1} 次，则第 @code{1} 也会被检查。 对于第三代来说情况还会更复杂，请参阅 Collecting the oldest generation@footnote{https://devguide.python.org/garbage_collector/#collecting-the-oldest-generation} 来了解详情。
@end deffn

@geindex get_count() (在 gc 模块中)
@anchor{library/gc gc get_count}@anchor{3741}
@deffn {函数} gc.get_count ()

将当前回收计数以形为 @code{(count0, count1, count2)} 的元组返回。
@end deffn

@geindex get_threshold() (在 gc 模块中)
@anchor{library/gc gc get_threshold}@anchor{3742}
@deffn {函数} gc.get_threshold ()

将当前回收阈值以形为 @code{(threshold0, threshold1, threshold2)} 的元组返回。
@end deffn

@geindex get_referrers() (在 gc 模块中)
@anchor{library/gc gc get_referrers}@anchor{1001}
@deffn {函数} gc.get_referrers (*objs)

返回直接引用任意一个 @emph{objs} 的对象列表。这个函数只定位支持垃圾回收的容器；引用了其它对象但不支持垃圾回收的扩展类型不会被找到。

需要注意的是，已经解除对 @emph{objs} 引用的对象，但仍存在于循环引用中未被回收时，仍然会被作为引用者出现在返回的列表当中。若要获取当前正在引用 @emph{objs} 的对象，需要调用 @ref{362,,collect()} 然后再调用 @ref{1001,,get_referrers()} 。

@cartouche
@quotation 警告 
在使用 @ref{1001,,get_referrers()} 返回的对象时必须要小心，因为其中一些对象可能仍在构造中因此处于暂时的无效状态。不要把 @ref{1001,,get_referrers()} 用于调试以外的其它目的。
@end quotation
@end cartouche

引发一个 @ref{fec,,审计事件} @code{gc.get_referrers}，附带参数 @code{objs}。
@end deffn

@geindex get_referents() (在 gc 模块中)
@anchor{library/gc gc get_referents}@anchor{1002}
@deffn {函数} gc.get_referents (*objs)

返回被任意一个参数中的对象直接引用的对象的列表。返回的被引用对象是被参数中的对象的C语言级别方法（若存在） @ref{23c,,tp_traverse} 访问到的对象，可能不是所有的实际直接可达对象。只有支持垃圾回收的对象支持 @ref{23c,,tp_traverse}  方法，并且此方法只会在需要访问涉及循环引用的对象时使用。因此，可以有以下例子：一个整数对其中一个参数是直接可达的，这个整数有可能出现或不出现在返回的结果列表当中。

引发一个 @ref{fec,,审计事件} @code{gc.get_referents}，附带参数 @code{objs}。
@end deffn

@geindex is_tracked() (在 gc 模块中)
@anchor{library/gc gc is_tracked}@anchor{d73}
@deffn {函数} gc.is_tracked (obj)

当对象正在被垃圾回收器监控时返回 @code{True} ，否则返回 @code{False} 。一般来说，原子类的实例不会被监控，而非原子类（如容器、用户自定义的对象）会被监控。然而，会有一些特定类型的优化以便减少垃圾回收器在简单实例（如只含有原子性的键和值的字典）上的消耗。

@example
>>> gc.is_tracked(0)
False
>>> gc.is_tracked("a")
False
>>> gc.is_tracked([])
True
>>> gc.is_tracked(@{@})
False
>>> gc.is_tracked(@{"a": 1@})
False
>>> gc.is_tracked(@{"a": []@})
True
@end example


3.1 新版功能.

@end deffn

@geindex is_finalized() (在 gc 模块中)
@anchor{library/gc gc is_finalized}@anchor{1a9}
@deffn {函数} gc.is_finalized (obj)

如果给定对象已被垃圾回收器终结则返回 @code{True}，否则返回 @code{False}。

@example
>>> x = None
>>> class Lazarus:
...     def __del__(self):
...         global x
...         x = self
...
>>> lazarus = Lazarus()
>>> gc.is_finalized(lazarus)
False
>>> del lazarus
>>> gc.is_finalized(x)
True
@end example


3.9 新版功能.

@end deffn

@geindex freeze() (在 gc 模块中)
@anchor{library/gc gc freeze}@anchor{49b}
@deffn {函数} gc.freeze ()

冻结 gc 所跟踪的所有对象 —— 将它们移至永久代并忽略所有未来的集合。 这可以在 POSIX fork() 调用之前使用以便令对写入复制保持友好或加速收集。 并且在 POSIX fork() 调用之前的收集也可以释放页面以供未来分配，这也可能导致写入时复制，因此建议在主进程中禁用 gc 并在 fork 之前冻结，而在子进程中启用 gc。


3.7 新版功能.

@end deffn

@geindex unfreeze() (在 gc 模块中)
@anchor{library/gc gc unfreeze}@anchor{49c}
@deffn {函数} gc.unfreeze ()

解冻永久代中的对象，并将它们放回到年老代中。


3.7 新版功能.

@end deffn

@geindex get_freeze_count() (在 gc 模块中)
@anchor{library/gc gc get_freeze_count}@anchor{49d}
@deffn {函数} gc.get_freeze_count ()

返回永久代中的对象数量。


3.7 新版功能.

@end deffn

提供以下变量仅供只读访问（你可以修改但不应该重绑定它们）：

@geindex garbage() (在 gc 模块中)
@anchor{library/gc gc garbage}@anchor{c1b}
@deffn {数据} gc.garbage

一个回收器发现不可达而又无法被释放的对象（不可回收对象）列表。 从 Python 3.4 开始，该列表在大多数时候都应该是空的，除非使用了含有非 @code{NULL} @code{tp_del} 空位的 C 扩展类型的实例。

如果设置了 @ref{3743,,DEBUG_SAVEALL} ，则所有不可访问对象将被添加至该列表而不会被释放。


在 3.2 版更改: 当 @ref{85c,,interpreter shutdown} 即解释器关闭时，若此列表非空，会产生 @ref{5d3,,ResourceWarning} ，即资源警告，在默认情况下此警告不会被提醒。如果设置了 @ref{c1c,,DEBUG_UNCOLLECTABLE} ，所有无法被回收的对象会被打印。



在 3.4 版更改: 根据 
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442} ，带有 @ref{a0d,,__del__()} 方法的对象最终不再会进入 @ref{c1b,,gc.garbage} 。

@end deffn

@geindex callbacks() (在 gc 模块中)
@anchor{library/gc gc callbacks}@anchor{af1}
@deffn {数据} gc.callbacks

在垃圾回收器开始前和完成后会被调用的一系列回调函数。这些回调函数在被调用时使用两个参数： @emph{phase} 和 @emph{info} 。

@emph{phase} 可为以下两值之一：

@quotation

"start": 垃圾回收即将开始。

"stop": 垃圾回收已结束。
@end quotation

@emph{info} is a dict providing more information for the callback.  The following
keys are currently defined:

@quotation

"generation"（代） ：正在被回收的最久远的一代。

"collected"（已回收的 ）: 当*phase* 为 "stop" 时，被成功回收的对象的数目。

"uncollectable"（不可回收的）: 当 @emph{phase} 为 "stop" 时，不能被回收并被放入 @ref{c1b,,garbage} 的对象的数目。
@end quotation

应用程序可以把他们自己的回调函数加入此列表。主要的使用场景有：

@quotation

统计垃圾回收的数据，如：不同代的回收频率、回收所花费的时间。

使应用程序可以识别和清理他们自己的在 @ref{c1b,,garbage} 中的不可回收类型的对象。
@end quotation


3.3 新版功能.

@end deffn

以下常量被用于 @ref{373e,,set_debug()} ：

@geindex DEBUG_STATS() (在 gc 模块中)
@anchor{library/gc gc DEBUG_STATS}@anchor{3744}
@deffn {数据} gc.DEBUG_STATS

在回收完成后打印统计信息。当回收频率设置较高时，这些信息会比较有用。
@end deffn

@geindex DEBUG_COLLECTABLE() (在 gc 模块中)
@anchor{library/gc gc DEBUG_COLLECTABLE}@anchor{3745}
@deffn {数据} gc.DEBUG_COLLECTABLE

当发现可回收对象时打印信息。
@end deffn

@geindex DEBUG_UNCOLLECTABLE() (在 gc 模块中)
@anchor{library/gc gc DEBUG_UNCOLLECTABLE}@anchor{c1c}
@deffn {数据} gc.DEBUG_UNCOLLECTABLE

打印找到的不可回收对象的信息（指不能被回收器回收的不可达对象）。这些对象会被添加到 @code{garbage} 列表中。


在 3.2 版更改: 当 @ref{85c,,interpreter shutdown} 时，即解释器关闭时，若 @ref{c1b,,garbage} 列表中存在对象，这些对象也会被打印输出。

@end deffn

@geindex DEBUG_SAVEALL() (在 gc 模块中)
@anchor{library/gc gc DEBUG_SAVEALL}@anchor{3743}
@deffn {数据} gc.DEBUG_SAVEALL

设置后，所有回收器找到的不可达对象会被添加进 @emph{garbage} 而不是直接被释放。这在调试一个内存泄漏的程序时会很有用。
@end deffn

@geindex DEBUG_LEAK() (在 gc 模块中)
@anchor{library/gc gc DEBUG_LEAK}@anchor{3746}
@deffn {数据} gc.DEBUG_LEAK

调试内存泄漏的程序时，使回收器打印信息的调试标识位。（等价于 @code{DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL} ）。
@end deffn

@node inspect --- 检查对象,site —— 指定域的配置钩子,gc --- 垃圾回收器接口,Python运行时服务
@anchor{library/inspect doc}@anchor{3747}@anchor{library/inspect inspect-inspect-live-objects}@anchor{3748}@anchor{library/inspect module-inspect}@anchor{a0}
@subsection @code{inspect} --- 检查对象


@geindex inspect (模块)

@strong{源代码:} Lib/inspect.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/inspect.py}


__________________________________________________________________


@ref{a0,,inspect} 模块提供了一些有用的函数帮助获取对象的信息，例如模块、类、方法、函数、回溯、帧对象以及代码对象。例如它可以帮助你检查类的内容，获取某个方法的源代码，取得并格式化某个函数的参数列表，或者获取你需要显示的回溯的详细信息。

该模块提供了4种主要的功能：类型检查、获取源代码、检查类与函数、检查解释器的调用堆栈。

@menu
* 类型和成员:: 
* 获取源代码:: 
* 使用 Signature 对象对可调用对象进行内省:: 
* 类与函数: 类与函数<2>. 
* 解释器栈:: 
* 静态地获取属性:: 
* 生成器和协程的当前状态:: 
* 代码对象位标志:: 
* 命令行界面: 命令行界面<8>. 

@end menu

@node 类型和成员,获取源代码,,inspect --- 检查对象
@anchor{library/inspect inspect-types}@anchor{3749}@anchor{library/inspect types-and-members}@anchor{374a}
@subsubsection 类型和成员


@ref{374b,,getmembers()} 函数获取对象的成员，例如类或模块。函数名以"is"开始的函数主要作为 @ref{374b,,getmembers()} 的第2个参数使用。它们也可用于判定某对象是否有如下的特殊属性:

@c this function name is too big to fit in the ascii-art table below


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

类型

@tab

属性

@tab

描述

@item

module 模块

@tab

__doc__

@tab

文档字符串

@item

@tab

__file__

@tab

文件名(内置模块没有文件名)

@item

class 类

@tab

__doc__

@tab

文档字符串

@item

@tab

__name__

@tab

类定义时所使用的名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

__module__

@tab

该类型被定义时所在的模块的名称

@item

method 方法

@tab

__doc__

@tab

文档字符串

@item

@tab

__name__

@tab

该方法定义时所使用的名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

__func__

@tab

实现该方法的函数对象

@item

@tab

__self__

@tab

该方法被绑定的实例，若没有绑定则为 @code{None}

@item

@tab

__module__

@tab

定义此方法的模块的名称

@item

函数

@tab

__doc__

@tab

文档字符串

@item

@tab

__name__

@tab

用于定义此函数的名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

__code__

@tab

包含已编译函数的代码对象 @ref{713,,bytecode}

@item

@tab

__defaults__

@tab

所有位置或关键字参数的默认值的元组

@item

@tab

__kwdefaults__

@tab

保存仅关键字参数的所有默认值的映射

@item

@tab

__globals__

@tab

包含此函数定义的全局命名空间

@item

@tab

__annotations__

@tab

参数名称到注解的映射；保留键 @code{"return"} 用于返回值注解。

@item

@tab

__module__

@tab

此函数定义所在的模块名称

@item

回溯

@tab

tb_frame

@tab

此级别的框架对象

@item

@tab

tb_lasti

@tab

在字节码中最后尝试的指令的索引

@item

@tab

tb_lineno

@tab

当前行在Python源代码中的行号

@item

@tab

tb_next

@tab

下一个内部回溯对象（由本层调用）

@item

框架

@tab

f_back

@tab

下一个外部帧对象（此帧的调用者）

@item

@tab

f_builtins

@tab

此帧所看到的buildins命名空间

@item

@tab

f_code

@tab

在此帧中执行的代码对象

@item

@tab

f_globals

@tab

此帧所看到的全局命名空间

@item

@tab

f_lasti

@tab

在字节码中最后尝试的指令的索引

@item

@tab

f_lineno

@tab

当前行在Python源代码中的行号

@item

@tab

f_locals

@tab

此帧所看到的局部命名空间

@item

@tab

f_trace

@tab

此帧的追踪函数，或`@w{`}None`@w{`}

@item

code

@tab

co_argcount

@tab

参数数量（不包括仅关键字参数、* 或 ** 参数）

@item

@tab

co_code

@tab

原始编译字节码的字符串

@item

@tab

co_cellvars

@tab

单元变量名称的元组(通过包含作用域引用)

@item

@tab

co_consts

@tab

字节码中使用的常量元组

@item

@tab

co_filename

@tab

创建此代码对象的文件的名称

@item

@tab

co_firstlineno

@tab

第一行在Python源码的行号

@item

@tab

co_flags

@tab

@code{CO_*} 标志的位图，详见 @ref{374c,,此处}

@item

@tab

co_lnotab

@tab

编码的行号到字节码索引的映射

@item

@tab

co_freevars

@tab

自由变量的名字组成的元组（通过函数闭包引用）

@item

@tab

co_posonlyargcount

@tab

仅限位置参数的数量

@item

@tab

co_kwonlyargcount

@tab

仅限关键字参数的数量（不包括 ** 参数）

@item

@tab

co_name

@tab

定义此代码对象的名称

@item

@tab

co_names

@tab

局部变量名称的元组

@item

@tab

co_nlocals

@tab

局部变量的数量

@item

@tab

co_stacksize

@tab

需要虚拟机堆栈空间

@item

@tab

co_varnames

@tab

参数名和局部变量的元组

@item

生成器

@tab

__name__

@tab

名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

gi_frame

@tab

框架

@item

@tab

gi_running

@tab

生成器在运行吗？

@item

@tab

gi_code

@tab

code

@item

@tab

gi_yieldfrom

@tab

通过`@w{`}yield from`@w{`}迭代的对象，或`@w{`}None`@w{`}

@item

协程

@tab

__name__

@tab

名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

cr_await

@tab

正在等待的对象，或`@w{`}None`@w{`}

@item

@tab

cr_frame

@tab

框架

@item

@tab

cr_running

@tab

这个协程正在运行吗？

@item

@tab

cr_code

@tab

code

@item

@tab

cr_origin

@tab

协程被创建的位置，或`@w{`}None`@w{`}。参见 @ref{501,,sys.set_coroutine_origin_tracking_depth()}

@item

builtin

@tab

__doc__

@tab

文档字符串

@item

@tab

__name__

@tab

此函数或方法的原始名称

@item

@tab

__qualname__

@tab

qualified name -- 限定名称

@item

@tab

__self__

@tab

方法绑定到的实例，或`@w{`}None`@w{`}

@end multitable



在 3.5 版更改: 为生成器添加`@w{`}__qualname__`@w{`}和`@w{`}gi_yieldfrom`@w{`}属性。

生成器的`@w{`}__name__`@w{`}属性现在由函数名称设置，而不是代码对象名称，并且现在可以被修改。



在 3.7 版更改: 为协程添加`@w{`}cr_origin`@w{`}属性。


@geindex getmembers() (在 inspect 模块中)
@anchor{library/inspect inspect getmembers}@anchor{374b}
@deffn {函数} inspect.getmembers (object[, predicate])

返回一个对象上的所有成员，组成以 @code{(名称, 值)} 对为元素的列表，按名称排序。如果提供了可选的 @emph{predicate} 参数（会对每个成员的 @code{值} 对象进行一次调用），则仅包含该断言为真的成员。

@cartouche
@quotation 注解 
如果要让 @ref{374b,,getmembers()} 返回元类中定义的类属性，那么实参须为一个类且这些属性在元类的自定义方法 @ref{434,,__dir__()} 中列出。
@end quotation
@end cartouche
@end deffn

@geindex getmodulename() (在 inspect 模块中)
@anchor{library/inspect inspect getmodulename}@anchor{6f3}
@deffn {函数} inspect.getmodulename (path)

返回由文件名 @emph{path} 表示的模块名字，但不包括外层的包名。文件扩展名会检查是否在 @ref{374d,,importlib.machinery.all_suffixes()} 列出的条目中。如果符合，则文件路径的最后一个组成部分会去掉后缀名后被返回；否则返回`@w{`}None`@w{`}。

值得注意的是，这个函数 @emph{仅} 返回可以作为 Python 模块的名字，而有可能指向一个 Python 包的路径仍然会返回`@w{`}None`@w{`}。


在 3.3 版更改: 该函数直接基于 @ref{9a,,importlib}。

@end deffn

@geindex ismodule() (在 inspect 模块中)
@anchor{library/inspect inspect ismodule}@anchor{374e}
@deffn {函数} inspect.ismodule (object)

当该对象是一个模块时返回`@w{`}True`@w{`}。
@end deffn

@geindex isclass() (在 inspect 模块中)
@anchor{library/inspect inspect isclass}@anchor{374f}
@deffn {函数} inspect.isclass (object)

当该对象是一个类时返回`@w{`}True`@w{`}，无论是内置类或者 Python 代码中定义的类。
@end deffn

@geindex ismethod() (在 inspect 模块中)
@anchor{library/inspect inspect ismethod}@anchor{3750}
@deffn {函数} inspect.ismethod (object)

当该对象是一个 Python 写成的绑定方法时返回`@w{`}True`@w{`}。
@end deffn

@geindex isfunction() (在 inspect 模块中)
@anchor{library/inspect inspect isfunction}@anchor{3751}
@deffn {函数} inspect.isfunction (object)

当该对象是一个 Python 函数时（包括使用 @ref{1cf0,,lambda} 表达式创造的函数），返回`@w{`}True`@w{`}。
@end deffn

@geindex isgeneratorfunction() (在 inspect 模块中)
@anchor{library/inspect inspect isgeneratorfunction}@anchor{119f}
@deffn {函数} inspect.isgeneratorfunction (object)

当该对象是一个 Python 生成器函数时返回`@w{`}True`@w{`}。


在 3.8 版更改: 对于使用 @ref{8bf,,functools.partial()} 封装的函数，如果被封装的函数是一个 Python 生成器函数，现在也会返回`@w{`}True`@w{`}。

@end deffn

@geindex isgenerator() (在 inspect 模块中)
@anchor{library/inspect inspect isgenerator}@anchor{3752}
@deffn {函数} inspect.isgenerator (object)

当该对象是一个生成器时返回`@w{`}True`@w{`}。
@end deffn

@geindex iscoroutinefunction() (在 inspect 模块中)
@anchor{library/inspect inspect iscoroutinefunction}@anchor{7f3}
@deffn {函数} inspect.iscoroutinefunction (object)

当该对象是一个 @ref{73c,,协程函数} （通过 @ref{3b1,,async def} 语法定义的函数）。


3.5 新版功能.



在 3.8 版更改: 对于使用 @ref{8bf,,functools.partial()} 封装的函数，如果被封装的函数是一个 @ref{73c,,协程函数} ，现在也会返回`@w{`}True`@w{`}。

@end deffn

@geindex iscoroutine() (在 inspect 模块中)
@anchor{library/inspect inspect iscoroutine}@anchor{7f2}
@deffn {函数} inspect.iscoroutine (object)

当该对象是一个由 @ref{3b1,,async def} 函数创建的 @ref{18a,,协程} 时返回`@w{`}True`@w{`}。


3.5 新版功能.

@end deffn

@geindex isawaitable() (在 inspect 模块中)
@anchor{library/inspect inspect isawaitable}@anchor{7f4}
@deffn {函数} inspect.isawaitable (object)

如果该对象可以在 @ref{2df,,await} 表达式中使用时返回`@w{`}True`@w{`}。

也可以用于区分基于生成器的协程和常规的生成器：

@example
def gen():
    yield
@@types.coroutine
def gen_coro():
    yield

assert not isawaitable(gen())
assert isawaitable(gen_coro())
@end example


3.5 新版功能.

@end deffn

@geindex isasyncgenfunction() (在 inspect 模块中)
@anchor{library/inspect inspect isasyncgenfunction}@anchor{11a0}
@deffn {函数} inspect.isasyncgenfunction (object)

如果该对象是一个 @ref{166f,,异步生成器} 函数则返回`@w{`}True`@w{`}，例如：

@example
>>> async def agen():
...     yield 1
...
>>> inspect.isasyncgenfunction(agen)
True
@end example


3.6 新版功能.



在 3.8 版更改: 对于使用 @ref{8bf,,functools.partial()} 封装的函数，如果被封装的函数是一个 @ref{166f,,异步生成器} ，现在也会返回`@w{`}True`@w{`}。

@end deffn

@geindex isasyncgen() (在 inspect 模块中)
@anchor{library/inspect inspect isasyncgen}@anchor{3753}
@deffn {函数} inspect.isasyncgen (object)

如果该对象是一个由 @ref{166f,,异步生成器} 函数创建的 @ref{36bd,,异步生成器迭代器}，则返回 @code{True}。


3.6 新版功能.

@end deffn

@geindex istraceback() (在 inspect 模块中)
@anchor{library/inspect inspect istraceback}@anchor{3754}
@deffn {函数} inspect.istraceback (object)

如果该对象是一个回溯则返回 @code{True}。
@end deffn

@geindex isframe() (在 inspect 模块中)
@anchor{library/inspect inspect isframe}@anchor{3755}
@deffn {函数} inspect.isframe (object)

如果该对象是一个帧则返回 @code{True}。
@end deffn

@geindex iscode() (在 inspect 模块中)
@anchor{library/inspect inspect iscode}@anchor{3756}
@deffn {函数} inspect.iscode (object)

如果该对象是一个代码对象则返回 @code{True}。
@end deffn

@geindex isbuiltin() (在 inspect 模块中)
@anchor{library/inspect inspect isbuiltin}@anchor{3757}
@deffn {函数} inspect.isbuiltin (object)

如果该对象是一个内置函数或一个绑定的内置方法，则返回 @code{True}。
@end deffn

@geindex isroutine() (在 inspect 模块中)
@anchor{library/inspect inspect isroutine}@anchor{3758}
@deffn {函数} inspect.isroutine (object)

如果该对象是一个用户定义的或内置的函数或者方法，则返回 @code{True}。
@end deffn

@geindex isabstract() (在 inspect 模块中)
@anchor{library/inspect inspect isabstract}@anchor{3759}
@deffn {函数} inspect.isabstract (object)

如果该对象是一个抽象基类则返回 @code{True}。
@end deffn

@geindex ismethoddescriptor() (在 inspect 模块中)
@anchor{library/inspect inspect ismethoddescriptor}@anchor{375a}
@deffn {函数} inspect.ismethoddescriptor (object)

如果该对象是一个方法描述器，但 @ref{3750,,ismethod()} 、 @ref{374f,,isclass()} 、 @ref{3751,,isfunction()} 及 @ref{3757,,isbuiltin()} 均不为真。

例如，该函数对于 @code{int.__add__} 为真。一个通过此测试的对象可以有 @ref{159d,,__get__()} 方法，但不能有 @ref{15a1,,__set__()} 方法，除此以外的属性集合是可变的。一个 @ref{d37,,__name__} 属性通常是合理的，而 @code{__doc__} 属性常常也是。

即使是通过描述器实现的函数，如果通过其他某一个测试，则  @ref{375a,,ismethoddescriptor()} 测试则会返回 @code{False}。这单纯是因为其他测试提供了更多保证。比如，当一个对象通过 @ref{3750,,ismethod()} 测试时，你可以使用 @code{__func__} 等属性。
@end deffn

@geindex isdatadescriptor() (在 inspect 模块中)
@anchor{library/inspect inspect isdatadescriptor}@anchor{375b}
@deffn {函数} inspect.isdatadescriptor (object)

如果该对象是一个数据描述器则返回 @code{True}。

数据描述器拥有 @ref{15a1,,__set__} 或 @ref{15a2,,__delete__} 方法。比如属性（通过 Python 定义）、getset 和成员。后二者是通过 C 定义的，并且也有对应的更具体的测试，并且在不同的 Python 实现中也是健壮的。典型地，数据描述器会拥有 @ref{d37,,__name__} 和 @code{__doc__} 属性（属性、getset 和成员都包含这两个属性），但这并无保证。
@end deffn

@geindex isgetsetdescriptor() (在 inspect 模块中)
@anchor{library/inspect inspect isgetsetdescriptor}@anchor{375c}
@deffn {函数} inspect.isgetsetdescriptor (object)

如果该对象是一个 getset 描述器则返回 @code{True}。

@strong{CPython implementation detail:} getset 是在扩展模块中通过 @ref{533,,PyGetSetDef} 结构体定义的属性。对于不包含这种类型的 Python 实现，这个方法将永远返回 @code{False}。
@end deffn

@geindex ismemberdescriptor() (在 inspect 模块中)
@anchor{library/inspect inspect ismemberdescriptor}@anchor{375d}
@deffn {函数} inspect.ismemberdescriptor (object)

如果该对象是一个成员描述器则返回 @code{True}。

@strong{CPython implementation detail:} 成员描述器是在扩展模块中通过 @ref{532,,PyMemberDef} 结构体定义的属性。对于不包含这种类型的 Python 实现，这个方法将永远返回 @code{False}。
@end deffn

@node 获取源代码,使用 Signature 对象对可调用对象进行内省,类型和成员,inspect --- 检查对象
@anchor{library/inspect inspect-source}@anchor{375e}@anchor{library/inspect retrieving-source-code}@anchor{375f}
@subsubsection 获取源代码


@geindex getdoc() (在 inspect 模块中)
@anchor{library/inspect inspect getdoc}@anchor{30e}
@deffn {函数} inspect.getdoc (object)

获取对象的文档字符串并通过 @ref{3760,,cleandoc()} 进行清理。如果对象本身并未提供文档字符串并且这个对象是一个类、一个方法、一个属性或者一个描述器，将通过继承层级结构获取文档字符串。


在 3.5 版更改: 文档字符串没有被重写的话将会被继承。

@end deffn

@geindex getcomments() (在 inspect 模块中)
@anchor{library/inspect inspect getcomments}@anchor{332e}
@deffn {函数} inspect.getcomments (object)

任意多行注释作为单一一个字符串返回。对于类、函数和方法，选取紧贴在该对象的源代码之前的注释；对于模块，选取 Python 源文件顶部的注释。如果对象的源代码不可获得，返回 @code{None}。这可能是因为对象是 C 语言中或者是在交互式命令行中定义的。
@end deffn

@geindex getfile() (在 inspect 模块中)
@anchor{library/inspect inspect getfile}@anchor{1220}
@deffn {函数} inspect.getfile (object)

返回定义了这个对象的文件名（包括文本文件或二进制文件）。如何该对象是一个内置模块、类或函数则会失败并引发一个 @ref{1ff,,TypeError}。
@end deffn

@geindex getmodule() (在 inspect 模块中)
@anchor{library/inspect inspect getmodule}@anchor{fb7}
@deffn {函数} inspect.getmodule (object)

尝试猜测该对象是在哪个模块中定义的。
@end deffn

@geindex getsourcefile() (在 inspect 模块中)
@anchor{library/inspect inspect getsourcefile}@anchor{3761}
@deffn {函数} inspect.getsourcefile (object)

返回定义了这个对象的 Python 源文件名。如果该对象是一个内置模块、类或函数则会失败并引发一个 @ref{1ff,,TypeError}。
@end deffn

@geindex getsourcelines() (在 inspect 模块中)
@anchor{library/inspect inspect getsourcelines}@anchor{3762}
@deffn {函数} inspect.getsourcelines (object)

返回一个源代码行的列表和对象的起始行。实参可以是一个模块、类、方法、函数、回溯、帧或者代码对象。与该对象相关的源代码会按行构成一个列表，并且会有一个行号表示其中第一行代码出现在源文件的第几行。如果源代码不能被获取，则会引发一个 @ref{30b,,OSError}。


在 3.3 版更改: 现在会引发 @ref{30b,,OSError} 而不是 @ref{a7c,,IOError}，后者现在是前者的一个别名。

@end deffn

@geindex getsource() (在 inspect 模块中)
@anchor{library/inspect inspect getsource}@anchor{1025}
@deffn {函数} inspect.getsource (object)

返回对象的源代码文本。实参可以是一个模块、类、方法、函数、回溯、帧或者代码对象。源代码会作为单一一个字符串被返回。如果源代码不能被获取，则会引发一个 @ref{30b,,OSError}。


在 3.3 版更改: 现在会引发 @ref{30b,,OSError} 而不是 @ref{a7c,,IOError}，后者现在是前者的一个别名。

@end deffn

@geindex cleandoc() (在 inspect 模块中)
@anchor{library/inspect inspect cleandoc}@anchor{3760}
@deffn {函数} inspect.cleandoc (doc)

清理文档字符串中为对齐当前代码块进行的缩进

第一行的所有前缀空白符会被移除。从第二行开始所有可以被统一去除的空白符也会被去除。之后，首尾的空白行也会被移除。同时，所有制表符会被展开到空格。
@end deffn

@node 使用 Signature 对象对可调用对象进行内省,类与函数<2>,获取源代码,inspect --- 检查对象
@anchor{library/inspect inspect-signature-object}@anchor{3763}@anchor{library/inspect introspecting-callables-with-the-signature-object}@anchor{3764}
@subsubsection 使用 Signature 对象对可调用对象进行内省



3.3 新版功能.


Signature 对象代表了一个可调用对象的调用签名和返回值标注。要获取一个 Signature 对象，使用 @ref{65e,,signature()} 函数。

@geindex signature() (在 inspect 模块中)
@anchor{library/inspect inspect signature}@anchor{65e}
@deffn {函数} inspect.signature (callable, *, follow_wrapped=True)

返回给定的 @code{callable} 的一个 @ref{7ee,,Signature} 对象：

@example
>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

>>> str(sig.parameters['b'])
'b:int'

>>> sig.parameters['b'].annotation
<class 'int'>
@end example

接受各类的 Python 可调用对象，包括单纯的函数、类，到 @ref{8bf,,functools.partial()} 对象。

Raises @ref{16d,,ValueError} if no signature can be provided, and
@ref{1ff,,TypeError} if that type of object is not supported.

函数签名中的斜杠（/）表示在它之前的参数是仅限位置的。详见 @ref{1759,,编程常见问题中关于仅限位置参数的条目}


3.5 新版功能: @code{follow_wrapped} 形参。传递 @code{False} 来获得特定关于 @code{callable} 的签名（@code{callable.__wrapped__} 将不会用来解包被修饰的可调用对象）。


@cartouche
@quotation 注解 
一些可调用对象可能在特定 Python 实现中无法被内省。例如，在 CPython 中，部分通过 C 语言定义的内置函数不提供关于其参数的元数据。
@end quotation
@end cartouche
@end deffn

@geindex Signature (inspect 中的类)
@anchor{library/inspect inspect Signature}@anchor{7ee}
@deffn {类} inspect.Signature (parameters=None, *, return_annotation=Signature.empty)

一个 Signature 对象代表了一个函数的调用签名和返回值标注。对于函数接受的每个参数，它对应地在自身的 @ref{10d1,,parameters} 容器中存储一个 @ref{7ef,,Parameter} 对象。

可选参数 @emph{parameters} 是一个 @ref{7ef,,Parameter} 对象组成的序列，它会在之后被验证不存在名字重复的参数，并且参数处于正确的顺序，即仅限位置参数最前，之后紧接着可位置可关键字参数，并且有默认值参数在无默认值参数之前。

可选参数 @emph{return_annotation} 可以是任意 Python 对象，是该可调用对象中 "return" 的标注。

 Signature 对象是 @emph{不可变} 的。使用 @ref{3765,,Signature.replace()} 来构造一个修改后的副本。


在 3.5 版更改:  Signature 对象既可封存又可哈希。


@geindex empty (inspect.Signature 属性)
@anchor{library/inspect inspect Signature empty}@anchor{3766}
@deffn {属性} empty

该类的一个特殊标记来明确指出返回值标注缺失。
@end deffn

@geindex parameters (inspect.Signature 属性)
@anchor{library/inspect inspect Signature parameters}@anchor{10d1}
@deffn {属性} parameters

一个参数名字到对应 @ref{7ef,,Parameter} 对象的有序映射。参数以严格的定义顺序出现，包括仅关键字参数。


在 3.7 版更改: Python 从 3.7 版起才显式地保证了它保持仅关键字参数的定义顺序，尽管实践上在 Python 3 中一直保持了这个顺序。

@end deffn

@geindex return_annotation (inspect.Signature 属性)
@anchor{library/inspect inspect Signature return_annotation}@anchor{3767}
@deffn {属性} return_annotation

可调用对象的“返回值”标注。如果可调用对象没有“返回值”标注，这个属性会被设置为 @ref{3766,,Signature.empty}。
@end deffn

@geindex bind() (inspect.Signature 方法)
@anchor{library/inspect inspect Signature bind}@anchor{3768}
@deffn {方法} bind (*args, **kwargs)

构造一个位置和关键字实参到形参的映射。如果 @code{*args} 和 @code{**kwargs} 符合签名，则返回一个 @ref{a92,,BoundArguments}；否则引发一个 @ref{1ff,,TypeError} 。
@end deffn

@geindex bind_partial() (inspect.Signature 方法)
@anchor{library/inspect inspect Signature bind_partial}@anchor{3769}
@deffn {方法} bind_partial (*args, **kwargs)

与 @ref{3768,,Signature.bind()} 作用方式相同，但允许省略部分必要的参数（模仿 @ref{8bf,,functools.partial()} 的行为）。返回 @ref{a92,,BoundArguments}，或者在传入参数不符合签名的情况下，引发一个 @ref{1ff,,TypeError}。
@end deffn

@geindex replace() (inspect.Signature 方法)
@anchor{library/inspect inspect Signature replace}@anchor{3765}
@deffn {方法} replace (*[, parameters][, return_annotation])

基于 replace 函数被调用的目标，创建一个新的 Signature 实例。可以传递不同的 @code{parameters} 和/或 @code{return_annotation} 来覆盖原本签名的对应的属性。要从复制的 Signature 中移除 return_annotation，可以传入 @ref{3766,,Signature.empty} 。

@example
>>> def test(a, b):
...     pass
>>> sig = signature(test)
>>> new_sig = sig.replace(return_annotation="new return anno")
>>> str(new_sig)
"(a, b) -> 'new return anno'"
@end example
@end deffn

@geindex from_callable() (inspect.Signature 类方法)
@anchor{library/inspect inspect Signature from_callable}@anchor{7f1}
@deffn {方法} classmethod from_callable (obj, *, follow_wrapped=True)

Return a @ref{7ee,,Signature} (or its subclass) object for a given callable
@code{obj}.  Pass @code{follow_wrapped=False} to get a signature of @code{obj}
without unwrapping its @code{__wrapped__} chain.

该函数简化了创建 @ref{7ee,,Signature} 的子类的过程：

@example
class MySignature(Signature):
    pass
sig = MySignature.from_callable(min)
assert isinstance(sig, MySignature)
@end example


3.5 新版功能.

@end deffn
@end deffn

@geindex Parameter (inspect 中的类)
@anchor{library/inspect inspect Parameter}@anchor{7ef}
@deffn {类} inspect.Parameter (name, kind, *, default=Parameter.empty, annotation=Parameter.empty)

Parameter 对象是 @emph{不可变} 的。不要直接修改 Parameter 对象，而是通过 @ref{376a,,Parameter.replace()} 来创建一个修改后的副本。


在 3.5 版更改:  Parameter 对象既可封存（pickle）又可哈希。


@geindex empty (inspect.Parameter 属性)
@anchor{library/inspect inspect Parameter empty}@anchor{376b}
@deffn {属性} empty

该类的一个特殊标记来明确指出默认值和标注的缺失。
@end deffn

@geindex name (inspect.Parameter 属性)
@anchor{library/inspect inspect Parameter name}@anchor{376c}
@deffn {属性} name

参数的名字字符串。这个名字必须是一个合法的 Python 标识符。

@strong{CPython implementation detail:} CPython 会为代码对象构造形如 @code{.0} 的隐式形参名，用以实现推导式和生成器表达式。


在 3.6 版更改: 这些形参名会被此模块暴露为形如 @code{implicit0} 一样的名字。

@end deffn

@geindex default (inspect.Parameter 属性)
@anchor{library/inspect inspect Parameter default}@anchor{376d}
@deffn {属性} default

该参数的默认值。如果该参数没有默认值，这个参数会被设置为 @ref{376b,,Parameter.empty} 。
@end deffn

@geindex annotation (inspect.Parameter 属性)
@anchor{library/inspect inspect Parameter annotation}@anchor{376e}
@deffn {属性} annotation

该参数的标注。如果该参数没有标注，该属性会被设置为 @ref{376b,,Parameter.empty} 。
@end deffn

@geindex kind (inspect.Parameter 属性)
@anchor{library/inspect inspect Parameter kind}@anchor{376f}
@deffn {属性} kind

描述实参值会如何绑定到形参。可能的取值（可以通过 @ref{7ef,,Parameter} 获得，比如 @code{Parameter.KEYWORD_ONLY} ）：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

名称

@tab

意义

@item

@emph{POSITIONAL_ONLY}

@tab

值必须以位置参数的方式传递。仅限位置参数是在函数定义中出现在 @code{/} 之前（如果有）的条目。

@item

@emph{POSITIONAL_OR_KEYWORD}

@tab

值既可以以关键字参数的形式提供，也可以以位置参数的形式提供（这是 Python 写成的函数的标准绑定行为的）。

@item

@emph{VAR_POSITIONAL}

@tab

没有绑定到其他形参的位置实参组成的元组。这对应于 Python 函数定义中的 @code{*args} 形参。

@item

@emph{KEYWORD_ONLY}

@tab

值必须以关键字实参的形式提供。仅限关键字参数是在 Python 函数定义中出现在 @code{*} 或 @code{*args} 之后的条目。

@item

@emph{VAR_KEYWORD}

@tab

一个未绑定到其他形参的关键字参数的字典。这对应于 Python 函数定义中的 @code{**kwargs} 形参。

@end multitable


例如，打印所有没有默认值的仅关键字参数：

@example
>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     if (param.kind == param.KEYWORD_ONLY and
...                        param.default is param.empty):
...         print('Parameter:', param)
Parameter: c
@end example
@end deffn

@geindex description (inspect.Parameter.kind 属性)
@anchor{library/inspect inspect Parameter kind description}@anchor{3770}
@deffn {属性} kind.description

描述 Parameter.kind 的枚举值。


3.8 新版功能.


例子：打印所有参数的描述：

@example
>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     print(param.kind.description)
positional or keyword
positional or keyword
keyword-only
keyword-only
@end example
@end deffn

@geindex replace() (inspect.Parameter 方法)
@anchor{library/inspect inspect Parameter replace}@anchor{376a}
@deffn {方法} replace (*[, name][, kind][, default][, annotation])

基于 replace 函数被调用的目标，创建一个新的 Parameter 实例。要覆写 @ref{7ef,,Parameter} 的属性，传递对应的参数。要移除 Parameter 的默认值和/或标注，传递 @ref{376b,,Parameter.empty}。

@example
>>> from inspect import Parameter
>>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
>>> str(param)
'foo=42'

>>> str(param.replace()) # Will create a shallow copy of 'param'
'foo=42'

>>> str(param.replace(default=Parameter.empty, annotation='spam'))
"foo:'spam'"
@end example
@end deffn


在 3.4 版更改: 在 Python 3.3 中， Parameter 对象当 @code{kind} 为 @code{POSITIONAL_ONLY} 时允许 @code{name} 被设置为 @code{None}。这现在已不再被允许。

@end deffn

@geindex BoundArguments (inspect 中的类)
@anchor{library/inspect inspect BoundArguments}@anchor{a92}
@deffn {类} inspect.BoundArguments

调用 @ref{3768,,Signature.bind()} 或 @ref{3769,,Signature.bind_partial()} 的结果。容纳实参到函数的形参的映射。

@geindex arguments (inspect.BoundArguments 属性)
@anchor{library/inspect inspect BoundArguments arguments}@anchor{1ba}
@deffn {属性} arguments

一个形参名到实参值的可变映射。仅包含显式绑定的参数。对 @ref{1ba,,arguments} 的修改会反映到 @ref{3771,,args} 和 @ref{3772,,kwargs} 上。

应当在任何参数处理目的中与 @ref{10d1,,Signature.parameters} 结合使用。

@cartouche
@quotation 注解 
 @ref{3768,,Signature.bind()} 和 @ref{3769,,Signature.bind_partial()} 中采用默认值的参数被跳过。然而，如果有需要的话，可以使用 @ref{7f0,,BoundArguments.apply_defaults()} 来添加它们。
@end quotation
@end cartouche


在 3.9 版更改:  @ref{1ba,,arguments} 现在的类型是 @ref{164,,dict}。之前，它的类型是 @ref{2f1,,collections.OrderedDict}。

@end deffn

@geindex args (inspect.BoundArguments 属性)
@anchor{library/inspect inspect BoundArguments args}@anchor{3771}
@deffn {属性} args

位置参数的值的元组。由 @ref{1ba,,arguments} 属性动态计算。
@end deffn

@geindex kwargs (inspect.BoundArguments 属性)
@anchor{library/inspect inspect BoundArguments kwargs}@anchor{3772}
@deffn {属性} kwargs

关键字参数值的字典。由 @ref{1ba,,arguments} 属性动态计算。
@end deffn

@geindex signature (inspect.BoundArguments 属性)
@anchor{library/inspect inspect BoundArguments signature}@anchor{3773}
@deffn {属性} signature

向父 @ref{7ee,,Signature} 对象的一个引用。
@end deffn

@geindex apply_defaults() (inspect.BoundArguments 方法)
@anchor{library/inspect inspect BoundArguments apply_defaults}@anchor{7f0}
@deffn {方法} apply_defaults ()

设置缺失的参数的默认值。

对于变长位置参数（@code{*args}），默认值是一个空元组。

对于变长关键字参数（@code{**kwargs}）默认值是一个空字典。

@example
>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
@{'a': 'spam', 'b': 'ham', 'args': ()@}
@end example


3.5 新版功能.

@end deffn

 @ref{3771,,args} 和 @ref{3772,,kwargs} 属性可以被用于调用函数：

@example
def test(a, *, b):
    ...

sig = signature(test)
ba = sig.bind(10, b=20)
test(*ba.args, **ba.kwargs)
@end example
@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 362

@item PEP 362@footnote{https://www.python.org/dev/peps/pep-0362} - 函数签名对象。

包含具体的规范，实现细节和样例。
@end table


@node 类与函数<2>,解释器栈,使用 Signature 对象对可调用对象进行内省,inspect --- 检查对象
@anchor{library/inspect classes-and-functions}@anchor{3774}@anchor{library/inspect inspect-classes-functions}@anchor{3775}
@subsubsection 类与函数


@geindex getclasstree() (在 inspect 模块中)
@anchor{library/inspect inspect getclasstree}@anchor{3776}
@deffn {函数} inspect.getclasstree (classes, unique=False)

将给定的类的列表组织成嵌套列表的层级结构。每当一个内层列表出现时，它包含的类均派生自紧接着该列表之前的条目的类。每个条目均是一个二元组，包含一个类和它的基类组成的元组。如果 @emph{unique} 参数为真值，则给定列表中的每个类将恰有一个对应条目。否则，运用了多重继承的类和它们的后代将出现多次。
@end deffn

@geindex getargspec() (在 inspect 模块中)
@anchor{library/inspect inspect getargspec}@anchor{65f}
@deffn {函数} inspect.getargspec (func)

获取一个 Python 函数的形参的名字和默认值。将返回一个 @ref{b84,,具名元组} @code{ArgSpec(args, varargs, keywords, defaults)}。 @emph{args} 是一个形参名字的列表。 @emph{varargs} 和 @emph{keywords} 是 @code{*} 和 @code{**} 形参的名字或 @code{None}。 @emph{defaults} 是一个默认参数值的元组或没有默认值时取 @code{None}。如果该元组有 @emph{n} 个元素，则它们对应 @emph{args} 中的最后 @emph{n} 个元素。


3.0 版后已移除: 通常可以替换为使用更新后的 API @ref{660,,getfullargspec()}，后者还能正确处理函数标注和仅限关键字形参。

又或者，使用 @ref{65e,,signature()} 和 @ref{3763,,Signature 对象}，这提供一个更加结构化的处理可调用对象的内省 API。

@end deffn

@geindex getfullargspec() (在 inspect 模块中)
@anchor{library/inspect inspect getfullargspec}@anchor{660}
@deffn {函数} inspect.getfullargspec (func)

获取一个 Python 函数的形参的名字和默认值。将返回一个 @ref{b84,,具名元组}：

@code{FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
annotations)}

@emph{args} 是一个位置参数的名字的列表。 @emph{varargs} 是 @code{*} 形参的名字或 @code{None} 表示不接受任意长位置参数时。 @emph{varkw} 是 @code{**} 参数的名字，或 @code{None} 表示不接受任意关键字参数。 @emph{defaults} 是一个包含了默认参数值的 @emph{n} 元组分别对应最后 @emph{n} 个位置参数，或 @code{None} 则表示没有默认值。 @emph{kwonlyargs} 是一个仅关键词参数列表，保持定义时的顺序。 @emph{kwonlydefaults} 是一个字典映射自 @emph{kwonlyargs} 中包含的形参名。 @emph{annotations} 是一个字典，包含形参值到标注的映射。其中包含一个特殊的键 @code{"return"} 代表函数返回值的标注（如果有的话）。

注意： @ref{65e,,signature()} 和 @ref{3763,,Signature 对象} 提供可调用对象内省更推荐的 API，并且支持扩展模块 API 中可能出现的额外的行为（比如仅限位置参数）。该函数被保留的主要原因是保持兼容 Python 2 的 @code{inspect} 模块 API。


在 3.4 版更改: 该函数现在基于 @ref{65e,,signature()} 但仍然忽略 @code{__wrapped__} 属性，并且在签名中包含绑定方法中的第一个绑定参数。



在 3.6 版更改: 该方法在 Python 3.5 中曾因 @ref{65e,,signature()} 被文档归为弃用。但该决定已被推翻以恢复一个明确受支持的标准接口，以便运用一份源码通用 Python 2/3 间遗留的 @ref{65f,,getargspec()} API 的迁移。



在 3.7 版更改: Python 从 3.7 版起才显式地保证了它保持仅关键字参数的定义顺序，尽管实践上在 Python 3 中一直保持了这个顺序。

@end deffn

@geindex getargvalues() (在 inspect 模块中)
@anchor{library/inspect inspect getargvalues}@anchor{8b0}
@deffn {函数} inspect.getargvalues (frame)

获取传入特定的帧的实参的信息。将返回一个 @ref{b84,,具名元组} @code{ArgInfo(args, varargs, keywords, locals)}。 @emph{args} 是一个参数名字的列表。 @emph{varargs} 和 @emph{keyword} 是 @code{*} 和 @code{**} 参数的名字或 @code{None}。 @emph{locals} 是给定的帧的局部环境字典。

@cartouche
@quotation 注解 
该函数因疏忽在 Python 3.5 中被错误地标记为弃用。
@end quotation
@end cartouche
@end deffn

@geindex formatargspec() (在 inspect 模块中)
@anchor{library/inspect inspect formatargspec}@anchor{8af}
@deffn {函数} inspect.formatargspec (args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])

将 @ref{660,,getfullargspec()} 的返回值格式化为美观的参数规格。

最初的七个参数是 (@code{args}, @code{varargs}, @code{varkw}, @code{defaults}, @code{kwonlyargs}, @code{kwonlydefaults}, @code{annotations}) 。

其他6个参数分别是会被调用以转化参数名、@code{*} 参数名、@code{**} 参数名、默认值、返回标注和独立标注为字符串的函数。

例如:

@example
>>> from inspect import formatargspec, getfullargspec
>>> def f(a: int, b: float):
...     pass
...
>>> formatargspec(*getfullargspec(f))
'(a: int, b: float)'
@end example


3.5 版后已移除: 使用 @ref{65e,,signature()} 和 @ref{3763,,Signature 对象}，它为可调用对象提供一个更好的内省 API。

@end deffn

@geindex formatargvalues() (在 inspect 模块中)
@anchor{library/inspect inspect formatargvalues}@anchor{8b1}
@deffn {函数} inspect.formatargvalues (args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])

将 @ref{8b0,,getargvalues()} 返回的四个值格式化为美观的参数规格。 format* 的参数是对应的可选格式化函数以转化名字和值为字符串。

@cartouche
@quotation 注解 
该函数因疏忽在 Python 3.5 中被错误地标记为弃用。
@end quotation
@end cartouche
@end deffn

@geindex getmro() (在 inspect 模块中)
@anchor{library/inspect inspect getmro}@anchor{3777}
@deffn {函数} inspect.getmro (cls)

返回由类 cls 的全部基类按方法解析顺序组成的元组，包括 cls 本身。所有类不会在此元组中出现多于一次。注意方法解析顺序取决于 cls 的类型。除非使用一个非常奇怪的用户定义元类型，否则 cls 会是元组的第一个元素。
@end deffn

@geindex getcallargs() (在 inspect 模块中)
@anchor{library/inspect inspect getcallargs}@anchor{8ae}
@deffn {函数} inspect.getcallargs (func, /, *args, **kwds)

仿照调用方式绑定 @emph{args} 和 @emph{kwds} 到 Python 函数或方法 @emph{func} 参数名。对于绑定方法，也绑定第一个参数（通常命名为 @code{self}）到关联的实例。返回一个字典，映射自参数名（包括可能存在的 @code{*} 和 @code{**} 参数）到他们对应于 @emph{args} 和 @emph{kwds} 中的值。假使 @emph{func} 被错误地调用，即是说 @code{func(*args, **kwds)} 会因函数签名不一致引发一个异常，那么也会引发一个相同种类的异常，并附上相同或类似的消息。例如：

@example
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
>>> getcallargs(f, 1, 2, 3) == @{'a': 1, 'named': @{@}, 'b': 2, 'pos': (3,)@}
True
>>> getcallargs(f, a=2, x=4) == @{'a': 2, 'named': @{'x': 4@}, 'b': 1, 'pos': ()@}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'
@end example


3.2 新版功能.



3.5 版后已移除: 改使用 @ref{3768,,Signature.bind()} 和 @ref{3769,,Signature.bind_partial()}。

@end deffn

@geindex getclosurevars() (在 inspect 模块中)
@anchor{library/inspect inspect getclosurevars}@anchor{aff}
@deffn {函数} inspect.getclosurevars (func)

获取自 Python 函数或方法 @emph{func} 引用的外部名字到它们的值的映射。返回一个 @ref{b84,,具名元组} @code{ClosureVars(nonlocals, globals, builtins, unbound)}。 @emph{nonlocals} 映射引用的名字到词法闭包变量，@emph{globals} 映射到函数的模块级全局， @emph{builtins} 映射到函数体内可见的内置变量。 @emph{unbound} 是在函数中引用但不能解析到给定的模块全局和内置变量的名字的集合。

如果 @emph{func} 不是 Python 函数或方法，将引发 @ref{1ff,,TypeError}。


3.3 新版功能.

@end deffn

@geindex unwrap() (在 inspect 模块中)
@anchor{library/inspect inspect unwrap}@anchor{95d}
@deffn {函数} inspect.unwrap (func, *, stop=None)

获取 @emph{func} 所包装的对象。它追踪 @code{__wrapped__} 属性链并返回最后一个对象。

@emph{stop} 是一个可选的回调，接受包装链的一个对象作为唯一参数，以允许通过让回调返回真值使解包装更早中止。如果回调不曾返回一个真值，将如常返回链中的最后一个对象。例如， @ref{65e,,signature()} 使用该参数来在遇到具有 @code{__signature__} 参数的对象时停止解包装。

如果遇到循环，则引发 @ref{16d,,ValueError}。


3.4 新版功能.

@end deffn

@node 解释器栈,静态地获取属性,类与函数<2>,inspect --- 检查对象
@anchor{library/inspect inspect-stack}@anchor{3778}@anchor{library/inspect the-interpreter-stack}@anchor{3779}
@subsubsection 解释器栈


当下列函数返回“帧记录”时，每个记录是一个 @ref{b84,,具名元组} @code{FrameInfo(frame, filename, lineno, function, code_context, index)}。该元组包含帧对象、文件名、当前行的行号、函数名、来源于源代码的若干行上下文组成的列表和当前行在该列表中的索引。


在 3.5 版更改: 不再返回一个元组而是返回一个具名元组。


@cartouche
@quotation 注解 
保留帧对象的引用（可见于这些函数返回的帧记录的第一个元素）会导致你的程序产生循环引用。每当一个循环引用被创建，所有可从产生循环的对象访问的对象的生命周期将会被大幅度延长，即便 Python 的可选的循环检测器被启用。如果这类循环必须被创建，确保它们会被显式地打破以避免对象销毁被延迟从而导致占用内存增加。

尽管循环检测器能够处理这种情况，这些帧（包括其局部变量）的销毁可以通过在 @ref{2c3,,finally} 子句中移除循环来产生确定的行为。对于循环检测器在编译 Python 时被禁用或者使用 @ref{373c,,gc.disable()} 时，这样处理更加尤为重要。比如：

@example
def handle_stackframe_without_leak():
    frame = inspect.currentframe()
    try:
        # do something with the frame
    finally:
        del frame
@end example

如果你希望保持帧更长的时间（比如在之后打印回溯），你也可以通过 @ref{902,,frame.clear()} 方法打破循环引用。
@end quotation
@end cartouche

大部分这些函数支持的可选的 @emph{context} 参数指定返回时包含的上下文的行数，以当前行为中心。

@geindex getframeinfo() (在 inspect 模块中)
@anchor{library/inspect inspect getframeinfo}@anchor{377a}
@deffn {函数} inspect.getframeinfo (frame, context=1)

获取一个帧或者一个回溯对象的信息。返回一个 @ref{b84,,具名元组} @code{Traceback(filename, lineno, function, code_context, index)}。
@end deffn

@geindex getouterframes() (在 inspect 模块中)
@anchor{library/inspect inspect getouterframes}@anchor{7f9}
@deffn {函数} inspect.getouterframes (frame, context=1)

获取某帧及其所有外部帧的帧记录的列表。这些帧表示了导致 @emph{frame} 被创建的一系列调用。返回的列表中的第一个记录代表了 @emph{frame} 本身；最后一个记录代表了 @emph{frame} 的栈上的最外层的调用。


在 3.5 版更改: 返回一个 @ref{b84,,具名元组} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} 的列表。

@end deffn

@geindex getinnerframes() (在 inspect 模块中)
@anchor{library/inspect inspect getinnerframes}@anchor{7fa}
@deffn {函数} inspect.getinnerframes (traceback, context=1)

获取一个回溯所在的帧和它所有的内部的帧的列表。这些帧代表了作为 @emph{frame} 的后续的帧。第一条记录代表了 @emph{traceback} 本身；最后一条记录代表了引发异常的位置。


在 3.5 版更改: 返回一个 @ref{b84,,具名元组} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} 的列表。

@end deffn

@geindex currentframe() (在 inspect 模块中)
@anchor{library/inspect inspect currentframe}@anchor{377b}
@deffn {函数} inspect.currentframe ()

返回调用者的栈帧对应的帧对象。

@strong{CPython implementation detail:} 该函数依赖于 Python 解释器对于栈帧的支持，这并非在 Python 的所有实现中被保证。该函数在不支持Python 栈帧的实现中运行会返回 @code{None}。
@end deffn

@geindex stack() (在 inspect 模块中)
@anchor{library/inspect inspect stack}@anchor{7f7}
@deffn {函数} inspect.stack (context=1)

返回调用者的栈的帧记录列表。第一个记录代表调用者，最后一个记录代表了栈上最外层的调用。


在 3.5 版更改: 返回一个 @ref{b84,,具名元组} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} 的列表。

@end deffn

@geindex trace() (在 inspect 模块中)
@anchor{library/inspect inspect trace}@anchor{7f8}
@deffn {函数} inspect.trace (context=1)

返回介于当前帧和引发了当前正在处理的异常的帧之间的所有帧记录的列表。列表中的第一条记录代表调用者；最后一条记录代表了引发异常的地方。


在 3.5 版更改: 返回一个 @ref{b84,,具名元组} @code{FrameInfo(frame, filename, lineno, function, code_context, index)} 的列表。

@end deffn

@node 静态地获取属性,生成器和协程的当前状态,解释器栈,inspect --- 检查对象
@anchor{library/inspect fetching-attributes-statically}@anchor{377c}
@subsubsection 静态地获取属性


 @ref{554,,getattr()} 和 @ref{553,,hasattr()} 都可能会在获取或者判断属性是否存在时触发代码执行。描述符，就和特性一样，会被调用， @ref{433,,__getattr__()} 和 @ref{552,,__getattribute__()} 可能会被调用。

对于你想要静态地内省的情况，比如文档工具，这会显得不方便。 @ref{ca1,,getattr_static()} 拥有与 @ref{554,,getattr()} 相同的签名，但避免了获取属性时执行代码。

@geindex getattr_static() (在 inspect 模块中)
@anchor{library/inspect inspect getattr_static}@anchor{ca1}
@deffn {函数} inspect.getattr_static (obj, attr, default=None)

获取属性而不触发描述器协议的动态查找能力 @ref{433,,__getattr__()} 或 @ref{552,,__getattribute__()}。

注意：该函数可能无法获取 getattr 能获取的全部的属性（比如动态地创建的属性），并且可能发现一些 getattr 无法找到的属性（比如描述器会引发 AttributeError）。它也能够返回描述器对象本身而非实例成员。

如果实例的 @ref{5fe,,__dict__} 被其他成员遮盖（比如一个特性）则该函数无法找到实例成员。


3.2 新版功能.

@end deffn

 @ref{ca1,,getattr_static()} 不解析描述器。比如槽描述器或 C 语言中实现的 getset 描述器。该描述器对象会被直接返回，而不处理底层属性。

你可以用类似下方的代码的方法处理此事。注意，对于任意 getset 描述符，使用这段代码仍可能触发代码执行。

@example
# example code for resolving the builtin descriptor types
class _foo:
    __slots__ = ['foo']

slot_descriptor = type(_foo.foo)
getset_descriptor = type(type(open(__file__)).name)
wrapper_descriptor = type(str.__dict__['__add__'])
descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)

result = getattr_static(some_object, 'foo')
if type(result) in descriptor_types:
    try:
        result = result.__get__()
    except AttributeError:
        # descriptors can raise AttributeError to
        # indicate there is no underlying value
        # in which case the descriptor itself will
        # have to do
        pass
@end example

@node 生成器和协程的当前状态,代码对象位标志,静态地获取属性,inspect --- 检查对象
@anchor{library/inspect current-state-of-generators-and-coroutines}@anchor{377d}
@subsubsection 生成器和协程的当前状态


当实现协程调度器或其他更高级的生成器用途时，判断一个生成器是正在执行、等待启动或继续或执行，又或者已经被终止是非常有用的。 @ref{ca0,,getgeneratorstate()} 允许方便地判断一个生成器的当前状态。

@geindex getgeneratorstate() (在 inspect 模块中)
@anchor{library/inspect inspect getgeneratorstate}@anchor{ca0}
@deffn {函数} inspect.getgeneratorstate (generator)

获取生成器迭代器的当前状态。


@table @asis

@item 可能的状态是：


@itemize *

@item 
GEN_CREATED：等待开始执行。

@item 
GEN_RUNNING：正在被解释器执行。

@item 
GEN_SUSPENDED：当前挂起于一个 yield 表达式。

@item 
GEN_CLOSED：执行已经完成。
@end itemize
@end table


3.2 新版功能.

@end deffn

@geindex getcoroutinestate() (在 inspect 模块中)
@anchor{library/inspect inspect getcoroutinestate}@anchor{7f6}
@deffn {函数} inspect.getcoroutinestate (coroutine)

获取协程对象的当前状态。该函数设计为用于使用 @ref{3b1,,async def} 函数创建的协程函数，但也能接受任何包括 @code{cr_running} 和 @code{cr_frame} 的类似协程的对象。


@table @asis

@item 可能的状态是：


@itemize *

@item 
CORO_CREATED：等待开始执行。

@item 
CORO_RUNNING：当前正在被解释器执行。

@item 
CORO_SUSPENDED：当前挂起于一个 await 表达式。

@item 
CORO_CLOSED：执行已经完成。
@end itemize
@end table


3.5 新版功能.

@end deffn

生成器当前的内部状态也可以被查询。这通常在测试目的中最为有用，来保证内部状态如预期一样被更新：

@geindex getgeneratorlocals() (在 inspect 模块中)
@anchor{library/inspect inspect getgeneratorlocals}@anchor{b00}
@deffn {函数} inspect.getgeneratorlocals (generator)

获取 @emph{generator} 里的实时局部变量到当前值的映射。返回一个由名字映射到值的字典。这与在生成器的主体内调用 @ref{55f,,locals()} 是等效的，并且相同的警告也适用。

如果 @emph{generator} 是一个没有关联帧的 @ref{a8c,,生成器}，则返回一个空字典。如果 @emph{generator} 不是一个 Python 生成器对象，则引发 @ref{1ff,,TypeError}。

@strong{CPython implementation detail:} 该函数依赖于生成器为内省暴露一个 Python 栈帧，这并非在 Python 的所有实现中被保证。在这种情况下，该函数将永远返回一个空字典。


3.3 新版功能.

@end deffn

@geindex getcoroutinelocals() (在 inspect 模块中)
@anchor{library/inspect inspect getcoroutinelocals}@anchor{7f5}
@deffn {函数} inspect.getcoroutinelocals (coroutine)

该函数可类比于 @ref{b00,,getgeneratorlocals()}，只是作用于由 @ref{3b1,,async def} 函数创建的协程。


3.5 新版功能.

@end deffn

@node 代码对象位标志,命令行界面<8>,生成器和协程的当前状态,inspect --- 检查对象
@anchor{library/inspect code-objects-bit-flags}@anchor{377e}@anchor{library/inspect inspect-module-co-flags}@anchor{374c}
@subsubsection 代码对象位标志


Python 代码对象有一个 @code{co_flags} 属性，它是下列标志的位图。

@geindex CO_OPTIMIZED() (在 inspect 模块中)
@anchor{library/inspect inspect CO_OPTIMIZED}@anchor{377f}
@deffn {数据} inspect.CO_OPTIMIZED

代码对象已经经过优化，会采用快速局部变量。
@end deffn

@geindex CO_NEWLOCALS() (在 inspect 模块中)
@anchor{library/inspect inspect CO_NEWLOCALS}@anchor{3780}
@deffn {数据} inspect.CO_NEWLOCALS

如果被置位，当代码对象被执行时会创建一个新的字典作为帧的 @code{f_locals}。
@end deffn

@geindex CO_VARARGS() (在 inspect 模块中)
@anchor{library/inspect inspect CO_VARARGS}@anchor{3781}
@deffn {数据} inspect.CO_VARARGS

代码对象拥有一个变长位置形参（类似 @code{*args}）。
@end deffn

@geindex CO_VARKEYWORDS() (在 inspect 模块中)
@anchor{library/inspect inspect CO_VARKEYWORDS}@anchor{3782}
@deffn {数据} inspect.CO_VARKEYWORDS

代码对象拥有一个可变关键字形参 (类似 @code{**kwrags})。
@end deffn

@geindex CO_NESTED() (在 inspect 模块中)
@anchor{library/inspect inspect CO_NESTED}@anchor{3783}
@deffn {数据} inspect.CO_NESTED

该标志当代码对象是一个嵌套函数时被置位。
@end deffn

@geindex CO_GENERATOR() (在 inspect 模块中)
@anchor{library/inspect inspect CO_GENERATOR}@anchor{3784}
@deffn {数据} inspect.CO_GENERATOR

当代码对象是一个生成器函数，即调用时会返回一个生成器对象，则该标志被置位。
@end deffn

@geindex CO_NOFREE() (在 inspect 模块中)
@anchor{library/inspect inspect CO_NOFREE}@anchor{3785}
@deffn {数据} inspect.CO_NOFREE

当没有自由或单元变量时，标志被置位。
@end deffn

@geindex CO_COROUTINE() (在 inspect 模块中)
@anchor{library/inspect inspect CO_COROUTINE}@anchor{3786}
@deffn {数据} inspect.CO_COROUTINE

当代码对象是一个协程函数时被置位。当代码对象被执行时它返回一个协程。详见 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492}。


3.5 新版功能.

@end deffn

@geindex CO_ITERABLE_COROUTINE() (在 inspect 模块中)
@anchor{library/inspect inspect CO_ITERABLE_COROUTINE}@anchor{3787}
@deffn {数据} inspect.CO_ITERABLE_COROUTINE

该标志被用于将生成器转变为基于生成器的协程。包含此标志的生成器对象可以被用于 @code{await} 表达式，并可以 @code{yield from} 协程对象。详见 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492}。


3.5 新版功能.

@end deffn

@geindex CO_ASYNC_GENERATOR() (在 inspect 模块中)
@anchor{library/inspect inspect CO_ASYNC_GENERATOR}@anchor{3788}
@deffn {数据} inspect.CO_ASYNC_GENERATOR

当代码对象是一个异步生成器函数时该标志被置位。当代码对象被运行时它将返回一个异步生成器对象。详见 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525}。


3.6 新版功能.

@end deffn

@cartouche
@quotation 注解 
这些标志特指于 CPython，并且在其他 Python 实现中可能从未被定义。更进一步地说，这些标志是一种实现细节，并且可能在将来的 Python 发行中被移除或弃用。推荐使用 @ref{a0,,inspect} 模块的公共 API 来进行任何内省需求。
@end quotation
@end cartouche

@node 命令行界面<8>,,代码对象位标志,inspect --- 检查对象
@anchor{library/inspect command-line-interface}@anchor{3789}@anchor{library/inspect inspect-module-cli}@anchor{95c}
@subsubsection 命令行界面


@ref{a0,,inspect} 模块也提供一个从命令行使用基本的内省能力。

默认地，命令行接受一个模块的名字并打印模块的源代码。也可通过后缀一个冒号和目标对象的限定名称来打印一个类或者一个函数。

@geindex inspect command line option; --details
@anchor{library/inspect cmdoption-inspect-details}@anchor{378a}
@deffn {程序选项} @w{-}@w{-}details

打印特定对象的信息而非源码。
@end deffn

@node site —— 指定域的配置钩子,,inspect --- 检查对象,Python运行时服务
@anchor{library/site doc}@anchor{378b}@anchor{library/site module-site}@anchor{eb}@anchor{library/site site-site-specific-configuration-hook}@anchor{378c}
@subsection @code{site} —— 指定域的配置钩子


@geindex site (模块)

@strong{源代码:} Lib/site.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/site.py}


__________________________________________________________________


@strong{这个模块将在初始化时被自动导入。} 此自动导入可以通过使用解释器的 @ref{c00,,-S} 选项来屏蔽。

@geindex module; search; path

导入此模块将会附加域特定的路径到模块搜索路径并且添加一些内建对象，除非使用了 @ref{c00,,-S} 选项。 那样的话，模块可以被安全地导入，而不会对模块搜索路径和内建对象有自动的修改或添加。要明确地触发通常域特定的添加，调用函数 @ref{14ab,,site.main()}。


在 3.3 版更改: 在之前即便使用了 @ref{c00,,-S}，导入此模块仍然会触发路径操纵。


@geindex site-packages; directory

它会从头部和尾部构建至多四个目录作为起点。 对于头部，它会使用 @code{sys.prefix} 和 @code{sys.exec_prefix}；空的头部会被跳过。 对于尾部，它会使用空字符串然后是 @code{lib/site-packages} (在 Windows 上) 或 @code{lib/python@emph{X.Y}/site-packages} (在 Unix 和 macOS 上)。 对于每个不同的头-尾组合，它会查看其是否指向现有的目录，如果是的话，则将其添加到 @code{sys.path} 并且检查新添加目录中的配置文件。


在 3.5 版更改: 对 "site-python" 目录的支持已被移除。


如果名为 "pyvenv.cfg" 的文件存在于 sys.executable 之上的一个目录中，则 sys.prefix 和 sys.exec_prefix 将被设置为该目录，并且还会检查 site-packages （ sys.base_prefix 和 sys.base_exec_prefix 始终是 Python 安装的 "真实" 前缀）。 如果 "pyvenv.cfg" （引导程序配置文件）包含设置为非 "true"（不区分大小写）的 "include-system-site-packages" 键，则不会在系统级前缀中搜索 site-packages；反之则会。

@geindex # (hash); comment
@geindex 语句; import

一个路径配置文件是具有 @code{@emph{name}.pth} 命名格式的文件，并且存在上面提到的四个目录之一中；它的内容是要添加到 @code{sys.path} 中的额外项目（每行一个）。不存在的项目不会添加到 @code{sys.path}，并且不会检查项目指向的是目录还是文件。项目不会被添加到 @code{sys.path} 超过一次。空行和由 @code{#} 起始的行会被跳过。以 @code{import} 开始的行（跟着空格或 TAB）会被执行。

@cartouche
@quotation 注解 
每次启动 Python，在 @code{.pth} 文件中的可执行行都将会被运行，而不管特定的模块实际上是否需要被使用。 因此，其影响应降至最低。可执行行的主要预期目的是使相关模块可导入（加载第三方导入钩子，调整 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 等）。如果它发生了，任何其他的初始化都应当在模块实际导入之前完成。将代码块限制为一行是一种有意采取的措施，不鼓励在此处放置更复杂的内容。
@end quotation
@end cartouche

@geindex package
@geindex path; configuration; file

例如，假设 @code{sys.prefix} 和 @code{sys.exec_prefix} 已经被设置为 @code{/usr/local}。 Python X.Y 的库之后被安装为 @code{/usr/local/lib/python@emph{X.Y}}。假设有一个拥有三个孙目录 @code{foo}, @code{bar} 和 @code{spam} 的子目录 @code{/usr/local/lib/python@emph{X.Y}/site-packages}，并且有两个路径配置文件 @code{foot.pth} 和 @code{bar.pth}。假定 @code{foo.pth} 内容如下:

@example
# foo package configuration

foo
bar
bletch
@end example

并且 @code{bar.pth} 包含:

@example
# bar package configuration

bar
@end example

则下面特定版目录将以如下顺序被添加到 @code{sys.path}。

@example
/usr/local/lib/pythonX.Y/site-packages/bar
/usr/local/lib/pythonX.Y/site-packages/foo
@end example

请注意 @code{bletch} 已被省略因为它并不存在；@code{bar} 目前在 @code{foo} 目录之前因为 @code{bar.pth} 按字母顺序排在 @code{foo.pth} 之前；而 @code{spam} 已被省略因为它在两个路径配置文件中都未被提及。

@geindex 模块; sitecustomize

在这些路径操作之后，会尝试导入一个名为 @code{sitecustomize} 的模块，它可以执行任意站点专属的定制。 它通常是由系统管理员在 site-packages 目录下创建的。 如果此导入失败并引发 @ref{16c,,ImportError} 或其子类异常，并且异常的 @code{name} 属性等于 @code{'sitecustomize'}，则它会被静默地忽略。 如果 Python 是在没有可用输出流的情况下启动的，例如在 Windows 上使用 @code{pythonw.exe} (它默认被用于启动 start IDLE)，则来自 @code{sitecustomize} 的输出尝试会被忽略。 任何其他异常都会导致静默且可能令人迷惑不解的进程失败。

@geindex 模块; usercustomize

在此之后，会尝试导入一个名为 @code{usercustomize} 的模块，它可以执行任意用户专属的定制，如果 @ref{378d,,ENABLE_USER_SITE} 为真值的话。 这个文件应该在用户的 site-packages 目录中创建（见下文），该目录是 @code{sys.path} 的组成部分，除非被 @ref{de3,,-s} 所禁用。 如果此导入失败并引发 @ref{16c,,ImportError} 或者其子类异常，并且异常的 @code{name} 属性等于 @code{'usercustomize'}，它会被静默地忽略。

请注意对于某些非 Unix 系统来说，@code{sys.prefix} 和 @code{sys.exec_prefix} 均为空值，并且路径操作会被跳过；但是仍然会尝试导入 @code{sitecustomize} 和 @code{usercustomize}。

@menu
* Readline 配置:: 
* 模块内容: 模块内容<8>. 
* 命令行界面: 命令行界面<9>. 

@end menu

@node Readline 配置,模块内容<8>,,site —— 指定域的配置钩子
@anchor{library/site readline-configuration}@anchor{378e}@anchor{library/site rlcompleter-config}@anchor{9d5}
@subsubsection Readline 配置


在支持 @ref{de,,readline} 的系统上，这个模块也将导入并配置 @ref{e1,,rlcompleter} 模块，如果 Python 是以 @ref{9d2,,交互模式} 启动并且不带 @ref{c00,,-S} 选项的话。  默认的行为是启用 tab 键补全并使用 @code{~/.python_history} 作为历史存档文件。 要禁用它，请删除（或重载）你的 @code{sitecustomize} 或 @code{usercustomize} 模块或 
@geindex PYTHONSTARTUP
@geindex 环境变量; PYTHONSTARTUP
@ref{9d4,,PYTHONSTARTUP} 文件中的 @ref{9d3,,sys.__interactivehook__} 属性。


在 3.4 版更改: rlcompleter 和 history 会被自动激活。


@node 模块内容<8>,命令行界面<9>,Readline 配置,site —— 指定域的配置钩子
@anchor{library/site module-contents}@anchor{378f}
@subsubsection 模块内容


@geindex PREFIXES() (在 site 模块中)
@anchor{library/site site PREFIXES}@anchor{3790}
@deffn {数据} site.PREFIXES

site-packages 目录的前缀列表。
@end deffn

@geindex ENABLE_USER_SITE() (在 site 模块中)
@anchor{library/site site ENABLE_USER_SITE}@anchor{378d}
@deffn {数据} site.ENABLE_USER_SITE

显示用户 site-packages 目录状态的旗标。 @code{True} 意味着它被启用并被添加到 @code{sys.path}。 @code{False} 意味着它按照用户请求被禁用 (通过 @ref{de3,,-s} 或 
@geindex PYTHONNOUSERSITE
@geindex 环境变量; PYTHONNOUSERSITE
@ref{de4,,PYTHONNOUSERSITE})。 @code{None} 意味着它因安全理由（user 或 group id 和 effective id 之间不匹配）或是被管理员所禁用。
@end deffn

@geindex USER_SITE() (在 site 模块中)
@anchor{library/site site USER_SITE}@anchor{14aa}
@deffn {数据} site.USER_SITE

正在运行的 Python 的用户级 site-packages 的路径。 它可以为 @code{None}，如果 @ref{cab,,getusersitepackages()} 尚未被调用的话。 默认值在 UNIX 和非框架 macOS 编译版上为 @code{~/.local/lib/python@emph{X.Y}/site-packages}，在 macOS 框架编译版上为  @code{~/Library/Python/@emph{X.Y}/lib/python/site-packages}，而在 Windows 上则为 @code{@emph{%APPDATA%}\Python\Python@emph{XY}\site-packages}。 此目录属于站点目录，这意味着其中的 @code{.pth} 文件将会被处理。
@end deffn

@geindex USER_BASE() (在 site 模块中)
@anchor{library/site site USER_BASE}@anchor{14b9}
@deffn {数据} site.USER_BASE

用户级 site-packages 的基准目录的路径。 它可以为 @code{None}，如果 @ref{caa,,getuserbase()} 尚未被调用的话。 默认值在 UNIX 和 macOS 非框架编译版上为 @code{~/.local}，在 macOS 框架编译版上为 @code{~/Library/Python/@emph{X.Y}}，而在 Windows 上则为 @code{@emph{%APPDATA%}\Python}。 这个值会被 Distutils 用来计算脚本、数据文件和 Python 模块等的安装目录。 对于 @ref{14ba,,用户安装规范}。 另请参阅 
@geindex PYTHONUSERBASE
@geindex 环境变量; PYTHONUSERBASE
@ref{de2,,PYTHONUSERBASE}。
@end deffn

@geindex main() (在 site 模块中)
@anchor{library/site site main}@anchor{14ab}
@deffn {函数} site.main ()

将所有的标准站点专属目录添加到模块搜索路径。 这个函数会在导入此模块时被自动调用，除非 Python 解释器启动时附带了 @ref{c00,,-S} 旗标。


在 3.3 版更改: 这个函数使用无条件调用。

@end deffn

@geindex addsitedir() (在 site 模块中)
@anchor{library/site site addsitedir}@anchor{3791}
@deffn {函数} site.addsitedir (sitedir, known_paths=None)

将一个目录添加到 sys.path 并处理其 @code{.pth} 文件。 通常被用于 @code{sitecustomize} 或 @code{usercustomize} (见下文)。
@end deffn

@geindex getsitepackages() (在 site 模块中)
@anchor{library/site site getsitepackages}@anchor{ca9}
@deffn {函数} site.getsitepackages ()

返回包含所有全局 site-packages 目录的列表。


3.2 新版功能.

@end deffn

@geindex getuserbase() (在 site 模块中)
@anchor{library/site site getuserbase}@anchor{caa}
@deffn {函数} site.getuserbase ()

返回用户基准目录的路径 @ref{14b9,,USER_BASE}。 如果它尚未被初始化，则此函数还将参照 
@geindex PYTHONUSERBASE
@geindex 环境变量; PYTHONUSERBASE
@ref{de2,,PYTHONUSERBASE} 来设置它。


3.2 新版功能.

@end deffn

@geindex getusersitepackages() (在 site 模块中)
@anchor{library/site site getusersitepackages}@anchor{cab}
@deffn {函数} site.getusersitepackages ()

返回用户专属 site-packages 目录的路径 @ref{14aa,,USER_SITE}。 如果它尚未被初始化，则此函数还将参照 @ref{14b9,,USER_BASE} 来设置它。 要确定用户专属 site-packages 是否已被添加到 @code{sys.path} 则应当使用 @ref{378d,,ENABLE_USER_SITE}。


3.2 新版功能.

@end deffn

@node 命令行界面<9>,,模块内容<8>,site —— 指定域的配置钩子
@anchor{library/site command-line-interface}@anchor{3792}@anchor{library/site site-commandline}@anchor{3793}
@subsubsection 命令行界面


@ref{eb,,site} 模块还提供了一个从命令行获取用户目录的方式:

@example
$ python3 -m site --user-site
/home/user/.local/lib/python3.3/site-packages
@end example

如果它被不带参数地调用，它将在标准输出打印 @ref{262,,sys.path} 的内容，再打印 @ref{14b9,,USER_BASE} 的值以及该目录是否存在，然后打印 @ref{14aa,,USER_SITE} 的相应信息，最后打印 @ref{378d,,ENABLE_USER_SITE} 的值。

@geindex site command line option; --user-base
@anchor{library/site cmdoption-site-user-base}@anchor{3794}
@deffn {程序选项} @w{-}@w{-}user@w{-}base

输出用户基本的路径。
@end deffn

@geindex site command line option; --user-site
@anchor{library/site cmdoption-site-user-site}@anchor{3795}
@deffn {程序选项} @w{-}@w{-}user@w{-}site

输出用户site-packages目录的路径。
@end deffn

如果同时给出了两个选项，则将打印用户基准目录和用户站点信息（总是按此顺序），并以 @ref{14b6,,os.pathsep} 分隔。

如果给出了其中一个选项，脚本将退出并返回以下值中的一个：如果用户级 site-packages 目录被启用则为 @code{0}，如果它被用户禁用则为 @code{1}，如果它因安全理由或被管理员禁用则为 @code{2}，如果发生错误则为大于 2 的值。


@subsubheading 参见


@geindex Python 提高建议; PEP 370
PEP 370@footnote{https://www.python.org/dev/peps/pep-0370} -- 分用户的 site-packages 目录


@node 自定义 Python 解释器,导入模块,Python运行时服务,Python 标准库
@anchor{library/custominterp doc}@anchor{3796}@anchor{library/custominterp custom-python-interpreters}@anchor{3797}@anchor{library/custominterp custominterp}@anchor{3798}
@section 自定义 Python 解释器


本章中描述的模块允许编写类似于 Python 的交互式解释器的接口。 如果你想要一个支持附加一些特殊功能到 Python 语言的 Python 解释器，你应该看看 @ref{1a,,code} 模块。 （ @ref{1c,,codeop} 模块是低层级的，用于支持编译可能不完整的 Python 代码块。）

本章描述的完整模块列表如下：

@menu
* code: code --- 解释器基类. 解释器基类
* codeop: codeop --- 编译Python代码. 编译Python代码

@end menu

@node code --- 解释器基类,codeop --- 编译Python代码,,自定义 Python 解释器
@anchor{library/code doc}@anchor{3799}@anchor{library/code code-interpreter-base-classes}@anchor{379a}@anchor{library/code module-code}@anchor{1a}
@subsection @code{code} --- 解释器基类


@geindex code (模块)

@strong{源代码：} Lib/code.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/code.py}


__________________________________________________________________


@code{code} 模块提供了在 Python 中实现 read-eval-print 循环的功能。它包含两个类和一些快捷功能，可用于构建提供交互式解释器的应用程序。

@geindex InteractiveInterpreter (code 中的类)
@anchor{library/code code InteractiveInterpreter}@anchor{379b}
@deffn {类} code.InteractiveInterpreter (locals=None)

这个类处理解析器和解释器状态（用户命名空间的）；它不处理缓冲器、终端提示区或着输入文件名（文件名总是显示地传递）。可选的 @emph{locals} 参数指定一个字典，字典里面包含将在此类执行的代码；它默认创建新的字典，其键 @code{'__name__'} 设置为 @code{'__console__'} ，键 @code{'__doc__'} 设置为 @code{None} 。
@end deffn

@geindex InteractiveConsole (code 中的类)
@anchor{library/code code InteractiveConsole}@anchor{198f}
@deffn {类} code.InteractiveConsole (locals=None, filename="<console>")

尽可能模拟交互式 Python 解释器的行为。此类建立在 @ref{379b,,InteractiveInterpreter} 的基础上，使用熟悉的 @code{sys.ps1} 和 @code{sys.ps2} 作为输入提示符，并有输入缓冲。
@end deffn

@geindex interact() (在 code 模块中)
@anchor{library/code code interact}@anchor{379c}
@deffn {函数} code.interact (banner=None, readfunc=None, local=None, exitmsg=None)

运行一个 read-eval-print 循环的便捷函数。这会创建一个新的 @ref{198f,,InteractiveConsole} 实例。如果提供了 @emph{readfunc} ，会设置为 @ref{379d,,InteractiveConsole.raw_input()} 方法。如果提供了 @emph{local} ，则将其传递给 @ref{198f,,InteractiveConsole} 的构造函数，以用作解释器循环的默认命名空间。然后，如果提供了 @emph{banner} 和 @emph{exitmsg} ，实例的 @ref{379c,,interact()} 方法会以此为标题和退出消息。控制台对象在使用后将被丢弃。


在 3.6 版更改: 加入 @emph{exitmsg} 参数。

@end deffn

@geindex compile_command() (在 code 模块中)
@anchor{library/code code compile_command}@anchor{379e}
@deffn {函数} code.compile_command (source, filename="<input>", symbol="single")

这个函数主要用来模拟 Python 解释器的主循环（即 read-eval-print 循环）。难点的部分是当用户输入不完整命令时，判断能否通过之后的输入来完成（要么成为完整的命令，要么语法错误）。该函数  @emph{几乎} 和实际的解释器主循环的判断是相同的。

@emph{source} 是源字符串；@emph{filename} 是可选的用作读取源的文件名，默认为 @code{'<input>'}；@emph{symbol} 是可选的语法开启符号，应为 @code{'single'} (默认), @code{'eval'} 或 @code{'exec'}。

如果命令完整且有效则返回一个代码对象 (等价于 @code{compile(source, filename, symbol)})；如果命令不完整则返回 @code{None}；如果命令完整但包含语法错误则会引发 @ref{562,,SyntaxError} 或 @ref{a4a,,OverflowError} 而如果命令包含无效字面值则将引发 @ref{16d,,ValueError}。
@end deffn

@menu
* 交互解释器对象:: 
* 交互式控制台对象:: 

@end menu

@node 交互解释器对象,交互式控制台对象,,code --- 解释器基类
@anchor{library/code interactive-interpreter-objects}@anchor{379f}@anchor{library/code interpreter-objects}@anchor{37a0}
@subsubsection 交互解释器对象


@geindex runsource() (code.InteractiveInterpreter 方法)
@anchor{library/code code InteractiveInterpreter runsource}@anchor{37a1}
@deffn {方法} InteractiveInterpreter.runsource (source, filename="<input>", symbol="single")

在解释器中编译并运行一段源码。 所用参数与 @ref{379e,,compile_command()} 一样；@emph{filename} 的默认值为 @code{'<input>'}，@emph{symbol} 则为 @code{'single'}。 可能发生以下情况之一：


@itemize *

@item 
输入不正确；@ref{379e,,compile_command()} 引发了一个异常 (@ref{562,,SyntaxError} 或 @ref{a4a,,OverflowError})。 将通过调用 @ref{37a2,,showsyntaxerror()} 方法打印语法回溯信息。 @ref{37a1,,runsource()} 返回 @code{False}。

@item 
输入不完整，需要更多输入；函数 @ref{379e,,compile_command()} 返回 @code{None} 。方法 @ref{37a1,,runsource()} 返回 @code{True} 。

@item 
输入完整；@ref{379e,,compile_command()} 返回了一个代码对象。 将通过调用 @ref{37a3,,runcode()} 执行代码（该方法也会处理运行时异常，@ref{6fd,,SystemExit} 除外）。 @ref{37a1,,runsource()} 返回 @code{False}。
@end itemize

该返回值用于决定使用 @code{sys.ps1} 还是 @code{sys.ps2} 来作为下一行的输入提示符。
@end deffn

@geindex runcode() (code.InteractiveInterpreter 方法)
@anchor{library/code code InteractiveInterpreter runcode}@anchor{37a3}
@deffn {方法} InteractiveInterpreter.runcode (code)

执行一个代码对象。当发生异常时，调用 @ref{7a4,,showtraceback()} 来显示回溯。除 @ref{6fd,,SystemExit} （允许传播）以外的所有异常都会被捕获。

有关 @ref{2d3,,KeyboardInterrupt} 的说明，该异常可能发生于此代码的其他位置，并且并不总能被捕获。 调用者应当准备好处理它。
@end deffn

@geindex showsyntaxerror() (code.InteractiveInterpreter 方法)
@anchor{library/code code InteractiveInterpreter showsyntaxerror}@anchor{37a2}
@deffn {方法} InteractiveInterpreter.showsyntaxerror (filename=None)

显示刚发生的语法错误。 这不会显示堆栈回溯因为语法错误并无此种信息。 如果给出了 @emph{filename}，它会被放入异常来替代 Python 解析器所提供的默认文件名，因为它在从一个字符串读取时总是会使用 @code{'<string>'}。 输出将由 @ref{37a4,,write()} 方法来写入。
@end deffn

@geindex showtraceback() (code.InteractiveInterpreter 方法)
@anchor{library/code code InteractiveInterpreter showtraceback}@anchor{7a4}
@deffn {方法} InteractiveInterpreter.showtraceback ()

显示刚发生的异常。 我们移除了第一个堆栈条目因为它从属于解释器对象的实现。 输出将由 @ref{37a4,,write()} 方法来写入。


在 3.5 版更改: 将显示完整的链式回溯，而不只是主回溯。

@end deffn

@geindex write() (code.InteractiveInterpreter 方法)
@anchor{library/code code InteractiveInterpreter write}@anchor{37a4}
@deffn {方法} InteractiveInterpreter.write (data)

将一个字符串写入到标准错误流 (@code{sys.stderr})。 所有派生类都应重载此方法以提供必要的正确输出处理。
@end deffn

@node 交互式控制台对象,,交互解释器对象,code --- 解释器基类
@anchor{library/code console-objects}@anchor{37a5}@anchor{library/code interactive-console-objects}@anchor{37a6}
@subsubsection 交互式控制台对象


@ref{198f,,InteractiveConsole} 类是 @ref{379b,,InteractiveInterpreter} 的子类，因此它提供了解释器对象的所有方法，还有以下的额外方法。

@geindex interact() (code.InteractiveConsole 方法)
@anchor{library/code code InteractiveConsole interact}@anchor{37a7}
@deffn {方法} InteractiveConsole.interact (banner=None, exitmsg=None)

近似地模拟交互式 Python 终端。 可选的 @emph{banner} 参数指定要在第一次交互前打印的条幅；默认情况下会类似于标准 Python 解释器所打印的内容，并附上外加圆括号的终端对象类名（这样就不会与真正的解释器混淆 —— 因为确实太像了！）

可选的 @emph{exitmsg} 参数指定要在退出时打印的退出消息。 传入空字符串可以屏蔽退出消息。 如果 @emph{exitmsg} 未给出或为 @code{None}，则将打印默认消息。


在 3.4 版更改: 要禁止打印任何条幅消息，请传递一个空字符串。



在 3.6 版更改: 退出时打印退出消息。

@end deffn

@geindex push() (code.InteractiveConsole 方法)
@anchor{library/code code InteractiveConsole push}@anchor{37a8}
@deffn {方法} InteractiveConsole.push (line)

将一行源文本推入解释器。 行内容不应带有末尾换行符；它可以有内部换行符。 行内容会被添加到一个缓冲区并且会调用解释器的 @code{runsource()} 方法，附带缓冲区内容的拼接结果作为源文本。 如果显示命令已执行或不合法，缓冲区将被重置；否则，则命令尚未结束，缓冲区将在添加行后保持原样。 如果要求更多输入则返回值为 @code{True}，如果行已按某种方式被处理则返回值为 @code{False} (这与 @code{runsource()} 相同)。
@end deffn

@geindex resetbuffer() (code.InteractiveConsole 方法)
@anchor{library/code code InteractiveConsole resetbuffer}@anchor{37a9}
@deffn {方法} InteractiveConsole.resetbuffer ()

从输入缓冲区中删除所有未处理的内容。
@end deffn

@geindex raw_input() (code.InteractiveConsole 方法)
@anchor{library/code code InteractiveConsole raw_input}@anchor{379d}
@deffn {方法} InteractiveConsole.raw_input (prompt="")

输出提示并读取一行。返回的行不包含末尾的换行符。当用户输入 EOF 键序列时，会引发 @ref{d3c,,EOFError} 异常。默认实现是从 @code{sys.stdin} 读取；子类可以用其他实现代替。
@end deffn

@node codeop --- 编译Python代码,,code --- 解释器基类,自定义 Python 解释器
@anchor{library/codeop doc}@anchor{37aa}@anchor{library/codeop codeop-compile-python-code}@anchor{37ab}@anchor{library/codeop module-codeop}@anchor{1c}
@subsection @code{codeop} --- 编译Python代码


@geindex codeop (模块)

@strong{源代码：} Lib/codeop.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/codeop.py}


__________________________________________________________________


@ref{1c,,codeop} 模块提供了可以模拟Python读取-执行-打印循环的实用程序，就像在 @ref{1a,,code} 模块中一样。因此，您可能不希望直接使用该模块；如果你想在程序中包含这样一个循环，你可能需要使用 @ref{1a,,code} 模块。

这个任务有两个部分:


@enumerate 

@item 
能够判断一行输入是否完成了一个Python语句：简而言之，告诉我们是否要打印'">>>"'或'"..."'。

@item 
记住用户已输入了哪些 future 语句，这样后续的输入可以在这些语句被启用的状态下被编译。
@end enumerate

@ref{1c,,codeop} 模块提供了分别以及同时执行这两个部分的方式。

只执行前一部分：

@geindex compile_command() (在 codeop 模块中)
@anchor{library/codeop codeop compile_command}@anchor{1086}
@deffn {函数} codeop.compile_command (source, filename="<input>", symbol="single")

尝试编译 @emph{source}，这应当是一个 Python 代码字符串，并且在 @emph{source} 是有效的 Python 代码时返回一个代码对象。 在此情况下，代码对象的 filename 属性将为 @emph{filename}，其默认值为 @code{'<input>'}。 如果 @emph{source} @emph{不是} 有效的 Python 代码而是有效的 Python 代码的一个前缀时将返回 @code{None}。

如果 @emph{source} 存在问题，将引发异常。 如果存在无效的 Python 语法将引发 @ref{562,,SyntaxError}，而如果存在无效的字面值则将引发 @ref{a4a,,OverflowError} 或 @ref{16d,,ValueError}。

@emph{symbol} 参数确定 @emph{source} 是作为一条语句 (对应默认值 @code{'single'})，作为一系列语句 (@code{'exec'}) 还是作为一个 @ref{15be,,expression} (@code{'eval'}) 进行编译。 任何其他值都将导致引发 @ref{16d,,ValueError}。

@cartouche
@quotation 注解 
解析器有可能（但很不常见）会在到达源码结尾之前停止解析并成功输出结果；在这种情况下，末尾的符号可能会被忽略而不是引发错误。 例如，一个反斜杠加两个换行符之后可以跟随任何无意义的符号。 一旦解析器 API 得到改进将修正这个问题。
@end quotation
@end cartouche
@end deffn

@geindex Compile (codeop 中的类)
@anchor{library/codeop codeop Compile}@anchor{37ac}
@deffn {类} codeop.Compile

这个类的实例具有 @ref{158f,,__call__()} 方法，其签名与内置函数 @ref{2ee,,compile()} 相似，区别在于如果该实例编译了包含 @ref{0,,__future__} 语句的程序文本，则实例会‘记住’并使用已生效的语句编译所有后续程序文本。
@end deffn

@geindex CommandCompiler (codeop 中的类)
@anchor{library/codeop codeop CommandCompiler}@anchor{37ad}
@deffn {类} codeop.CommandCompiler

这个类的实例具有 @ref{158f,,__call__()} 方法，其签名与 @ref{1086,,compile_command()} 相似；区别在于如果该实例编译了包含 @code{__future__} 语句的程序文本，则实例会‘记住’并使用已生效的语句编译编译所有后续程序文本。
@end deffn

@node 导入模块,Python 语言服务,自定义 Python 解释器,Python 标准库
@anchor{library/modules doc}@anchor{37ae}@anchor{library/modules importing-modules}@anchor{37af}@anchor{library/modules modules}@anchor{37b0}
@section 导入模块


本章中介绍的模块提供了导入其他Python模块和挂钩以自定义导入过程的新方法。

本章描述的完整模块列表如下：

@menu
* zipimport: zipimport --- 从 Zip 存档中导入模块. 从 Zip 存档中导入模块
* pkgutil: pkgutil --- 包扩展工具. 包扩展工具
* modulefinder: modulefinder --- 查找脚本使用的模块. 查找脚本使用的模块
* runpy ——查找并执行 Python 模块:: 
* importlib: importlib --- import 的实现. import 的实现
* 使用 importlib.metadata: 使用 importlib metadata. 

@end menu

@node zipimport --- 从 Zip 存档中导入模块,pkgutil --- 包扩展工具,,导入模块
@anchor{library/zipimport doc}@anchor{37b1}@anchor{library/zipimport module-zipimport}@anchor{14c}@anchor{library/zipimport zipimport-import-modules-from-zip-archives}@anchor{37b2}
@subsection @code{zipimport} --- 从 Zip 存档中导入模块


@geindex zipimport (模块)

@strong{源代码：} Lib/zipimport.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/zipimport.py}


__________________________________________________________________


此模块添加了从 ZIP 格式档案中导入 Python 模块（ @code{*.py} ， @code{*.pyc} ）和包的能力。通常不需要明确地使用 @ref{14c,,zipimport} 模块，内置的 @ref{cef,,import} 机制会自动将此模块用于 ZIP 档案路径的 @ref{262,,sys.path} 项目上。

通常， @ref{262,,sys.path} 是字符串的目录名称列表。此模块同样允许 @ref{262,,sys.path} 的一项成为命名 ZIP 文件档案的字符串。 ZIP 档案可以容纳子目录结构去支持包的导入，并且可以将归档文件中的路径指定为仅从子目录导入。比如说，路径 @code{example.zip/lib/} 将只会从档案中的 @code{lib/} 子目录导入。

任何文件都可以放到 ZIP 档案中，但只有 @code{.py} 和 @code{.pyc} 文件会触发导入器操作。 动态模块 (@code{.pyd}, @code{.so}) 的 ZIP 导入是不被允许的。 请注意如果一个档案只包含有 @code{.py} 文件，那么 Python 将不会尝试通过添加对应的 @code{.pyc} 文件来修改档案，这意味着如果一个 ZIP 档案不包含 @code{.pyc} 文件，则导入速度可能会相当慢。


在 3.8 版更改: 以前，不支持带有档案注释的 ZIP 档案。



@subsubheading 参见



@table @asis

@item PKZIP Application Note@footnote{https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT}

Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

@geindex Python 提高建议; PEP 273

@item PEP 273@footnote{https://www.python.org/dev/peps/pep-0273} -  从ZIP压缩包导入模块

由 James C. Ahlstrom 编写，他也提供了实现。 Python 2.3 遵循 
@geindex Python 提高建议; PEP 273
PEP 273@footnote{https://www.python.org/dev/peps/pep-0273} 的规范，但是使用 Just van Rossum 编写的使用了 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 中描述的导入钩的实现。

@geindex Python 提高建议; PEP 302

@item PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} - 新导入钩

PEP 添加导入钩来有助于模块运作。
@end table


此模块定义了一个异常：

@geindex ZipImportError
@anchor{library/zipimport zipimport ZipImportError}@anchor{37b3}
@deffn {例外} zipimport.ZipImportError

异常由 zipimporter 对象引发。这是 @ref{16c,,ImportError} 的子类，因此，也可以捕获为 @ref{16c,,ImportError} 。
@end deffn

@menu
* zipimporter 对象:: 
* 示例: 示例<43>. 

@end menu

@node zipimporter 对象,示例<43>,,zipimport --- 从 Zip 存档中导入模块
@anchor{library/zipimport id1}@anchor{37b4}@anchor{library/zipimport zipimporter-objects}@anchor{37b5}
@subsubsection zipimporter 对象


@ref{37b6,,zipimporter} 是用于导入 ZIP 文件的类。

@geindex zipimporter (zipimport 中的类)
@anchor{library/zipimport zipimport zipimporter}@anchor{37b6}
@deffn {类} zipimport.zipimporter (archivepath)

创建新的 zipimporter 实例。 @emph{archivepath} 必须是指向 ZIP 文件的路径，或者 ZIP 文件中的特定路径。例如， @code{foo/bar.zip/lib} 的 @emph{archivepath} 将在 ZIP 文件 @code{foo/bar.zip} 中的 @code{lib} 目录中查找模块（只要它存在）。

如果 @emph{archivepath} 没有指向一个有效的 ZIP 档案，引发 @ref{37b3,,ZipImportError} 。

@geindex find_module() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter find_module}@anchor{37b7}
@deffn {方法} find_module (fullname[, path])

搜索由 @emph{fullname} 指定的模块。 @emph{fullname} 必须是完全合格的（点分的）模块名。它返回 zipimporter 实例本身如果模块被找到，或者返回 @ref{204,,None} 如果没找到指定模块。可选的 @emph{path} 被忽略，这是为了与导入器协议兼容。
@end deffn

@geindex get_code() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter get_code}@anchor{37b8}
@deffn {方法} get_code (fullname)

返回指定模块的代码对象。如果不能找到模块会引发 @ref{37b3,,ZipImportError} 错误。
@end deffn

@geindex get_data() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter get_data}@anchor{1237}
@deffn {方法} get_data (pathname)

返回与 @emph{pathname} 相关联的数据。如果不能找到文件则引发 @ref{30b,,OSError} 错误。


在 3.3 版更改: 曾经是 @ref{a7c,,IOError} 被引发而不是 @ref{30b,,OSError} 。

@end deffn

@geindex get_filename() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter get_filename}@anchor{37b9}
@deffn {方法} get_filename (fullname)

如果导入了指定的模块 @code{__file__} ，则返回为该模块设置的值。如果未找到模块则引发 @ref{37b3,,ZipImportError} 错误。


3.1 新版功能.

@end deffn

@geindex get_source() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter get_source}@anchor{37ba}
@deffn {方法} get_source (fullname)

返回指定模块的源代码。如果没有找到模块则引发 @ref{37b3,,ZipImportError} ，如果档案包含模块但是没有源代码，返回 @ref{204,,None} 。
@end deffn

@geindex is_package() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter is_package}@anchor{37bb}
@deffn {方法} is_package (fullname)

如果由 @emph{fullname} 指定的模块是一个包则返回 @code{True} 。如果不能找到模块则引发 @ref{37b3,,ZipImportError} 错误。
@end deffn

@geindex load_module() (zipimport.zipimporter 方法)
@anchor{library/zipimport zipimport zipimporter load_module}@anchor{37bc}
@deffn {方法} load_module (fullname)

加载由 @emph{fullname} 指定的模块。 @emph{fullname} 必须是完全限定的（点分的）模块名。它返回已加载模块，或者当找不到模块时引发 @ref{37b3,,ZipImportError} 错误。
@end deffn

@geindex archive (zipimport.zipimporter 属性)
@anchor{library/zipimport zipimport zipimporter archive}@anchor{37bd}
@deffn {属性} archive

导入器关联的 ZIP 文件的文件名，没有可能的子路径。
@end deffn

@geindex prefix (zipimport.zipimporter 属性)
@anchor{library/zipimport zipimport zipimporter prefix}@anchor{37be}
@deffn {属性} prefix

ZIP 文件中搜索的模块的子路径。这是一个指向 ZIP 文件根目录的 zipimporter 对象的空字符串。
@end deffn

当与斜杠结合使用时， @ref{37bd,,archive} 和 @ref{37be,,prefix} 属性等价于赋予 @ref{37b6,,zipimporter} 构造器的原始 @emph{archivepath} 参数。
@end deffn

@node 示例<43>,,zipimporter 对象,zipimport --- 从 Zip 存档中导入模块
@anchor{library/zipimport examples}@anchor{37bf}@anchor{library/zipimport zipimport-examples}@anchor{37c0}
@subsubsection 示例


这是一个从 ZIP 档案中导入模块的例子 - 请注意 @ref{14c,,zipimport} 模块不需要明确地使用。

@example
$ unzip -l example.zip
Archive:  example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'example.zip/jwzthreading.py'
@end example

@node pkgutil --- 包扩展工具,modulefinder --- 查找脚本使用的模块,zipimport --- 从 Zip 存档中导入模块,导入模块
@anchor{library/pkgutil doc}@anchor{37c1}@anchor{library/pkgutil module-pkgutil}@anchor{cd}@anchor{library/pkgutil pkgutil-package-extension-utility}@anchor{37c2}
@subsection @code{pkgutil} --- 包扩展工具


@geindex pkgutil (模块)

@strong{源代码:} Lib/pkgutil.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pkgutil.py}


__________________________________________________________________


该模块为导入系统提供了工具，尤其是在包支持方面。

@geindex ModuleInfo (pkgutil 中的类)
@anchor{library/pkgutil pkgutil ModuleInfo}@anchor{70d}
@deffn {类} pkgutil.ModuleInfo (module_finder, name, ispkg)

一个包含模块信息的简短摘要的命名元组。


3.6 新版功能.

@end deffn

@geindex extend_path() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil extend_path}@anchor{37c3}
@deffn {函数} pkgutil.extend_path (path, name)

扩展组成包的模块的搜索路径。 预期用途是将以下代码放到包的 @code{__init__.py} 中:

@example
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
@end example

这将添加到包的 @code{__path__} 所有在 @ref{262,,sys.path} 上以该包命名的目录的子目录。 这在想把一个逻辑包的不同部分作为多个目录来分发时很有用处。

它还会查找开头部分 @code{*} 与 @emph{name} 参数相匹配的 @code{*.pkg} 文件。 此特性与 @code{*.pth} 文件类似（请参阅 @ref{eb,,site} 模块了解更多信息），区别在于它不会对以 @code{import} 开头的行做特别对待。 将按外在值对 @code{*.pkg} 文件添加信任：除了检查重复项，，所有在 @code{*.pkg} 文件中找到的条目都会被添加到路径中，不管它们是否存在于文件系统中。 （这是特性而非缺陷。）

如果输入路径不是一个列表（已冻结包就是这种情况）则它将被原样返回。 输入路径不会被修改；将返回一个扩展的副本。 条目将被添加到副本的末尾。

@ref{262,,sys.path} 会被假定为一个序列。 @ref{262,,sys.path} 中的条目如果不是指向现有目录的字符串则会被忽略。 @ref{262,,sys.path} 上当用作文件名时会导致错误的 Unicode 条目可以会使得此函数引发异常（与 @ref{32e,,os.path.isdir()} 的行为一致）。
@end deffn

@geindex ImpImporter (pkgutil 中的类)
@anchor{library/pkgutil pkgutil ImpImporter}@anchor{37c4}
@deffn {类} pkgutil.ImpImporter (dirname=None)

包装了 Python 的 "经典" 导入算法的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 查找器

如果 @emph{dirname} 是一个字符串，将创建一个 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 查找器来搜索该目录。 如果 @emph{dirname} 为 @code{None}，则将创建一个 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 来搜索当前 @ref{262,,sys.path}，加上任何已冻结或内置的模块。

请注意 @ref{37c4,,ImpImporter} 目前并不支持放置在 @ref{6e7,,sys.meta_path} 上使用。


3.3 版后已移除: 这种模拟已不再必要，因为标准的导入机制现在完全兼容 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 并且在 @ref{9a,,importlib} 中可用。

@end deffn

@geindex ImpLoader (pkgutil 中的类)
@anchor{library/pkgutil pkgutil ImpLoader}@anchor{37c5}
@deffn {类} pkgutil.ImpLoader (fullname, file, filename, etc)

包装了 Python 的 "经典" 导入算法的 @ref{1625,,加载器}。


3.3 版后已移除: 这种模拟已不再必要，因为标准的导入机制现在完全兼容 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 并且在 @ref{9a,,importlib} 中可用。

@end deffn

@geindex find_loader() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil find_loader}@anchor{37c6}
@deffn {函数} pkgutil.find_loader (fullname)

为给定的 @emph{fullname} 获取一个模块 @ref{1625,,loader}。

这是针对 @ref{a25,,importlib.util.find_spec()} 的向下兼容包装器，它将大多数失败转换为 @ref{16c,,ImportError} 并且只返回加载器而不是完整的 @code{ModuleSpec}。


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。



在 3.4 版更改: 更新为基于 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451}

@end deffn

@geindex get_importer() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil get_importer}@anchor{37c7}
@deffn {函数} pkgutil.get_importer (path_item)

为给定的 @emph{path_item} 获取一个 @ref{1624,,finder}。

返回的查找器如果是由一个路径钩子新建的则会被缓存至 @ref{5a0,,sys.path_importer_cache}。

如果需要重新扫描 @ref{a46,,sys.path_hooks} 则缓存（或其一部分）可以被手动清空。


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。

@end deffn

@geindex get_loader() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil get_loader}@anchor{37c8}
@deffn {函数} pkgutil.get_loader (module_or_name)

为 @emph{module_or_name} 获取一个 @ref{1625,,loader}。

如果模块或包可通过正常导入机制来访问，则会返回该机制相关部分的包装器。 如果模块无法找到或导入则返回 @code{None}。 如果指定的模块尚未被导入，则包含它的包（如果存在）会被导入，以便建立包 @code{__path__}。


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。



在 3.4 版更改: 更新为基于 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451}

@end deffn

@geindex iter_importers() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil iter_importers}@anchor{bf0}
@deffn {函数} pkgutil.iter_importers (fullname='@w{'})

为给定的模块名称产生 @ref{1624,,finder} 对象。

如果完整名称包含一个 @code{'.'}，查找器将针对包含该完整名称的包，否则它们将被注册为最高层级查找器（即同时用于 @ref{6e7,,sys.meta_path} 和 @ref{a46,,sys.path_hooks})。

如果指定的模块位于一个包内，则该包会作为发起调用此函数的附带影响被导入。

如果未指定模块名称，则会产生所有的最高层级查找器。


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。

@end deffn

@geindex iter_modules() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil iter_modules}@anchor{70c}
@deffn {函数} pkgutil.iter_modules (path=None, prefix='@w{'})

为 @emph{path} 上的所有子模块产生 @ref{70d,,ModuleInfo}，或者如果 @emph{path} 为 @code{None}，则为 @ref{262,,sys.path} 上的所有最高层级模块产生。

@emph{path} 应当为 @code{None} 或一个作为查找模块目标的路径的列表。

@emph{prefix} 是要在输出时输出到每个模块名称之前的字符串。

@cartouche
@quotation 注解 
只适用于定义了 @code{iter_modules()} 方法的 @ref{1624,,finder}。 该接口是非标准的，因此本模块还提供了针对 @ref{a9f,,importlib.machinery.FileFinder} 和 @ref{37b6,,zipimport.zipimporter} 的实现。
@end quotation
@end cartouche


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。

@end deffn

@geindex walk_packages() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil walk_packages}@anchor{58e}
@deffn {函数} pkgutil.walk_packages (path=None, prefix='@w{'}, onerror=None)

在 @emph{path} 上递归地为所有模块产生 @ref{70d,,ModuleInfo}，或者如果 @emph{path} 为 @code{None}，则为所有可访问的模块产生。

@emph{path} 应当为 @code{None} 或一个作为查找模块目标的路径的列表。

@emph{prefix} 是要在输出时输出到每个模块名称之前的字符串。

请注意此函数必须导入给定 @emph{path} 上所有的 @emph{packages} (@emph{而不是} 所有的模块！)，以便能访问 @code{__path__} 属性来查找子模块。

@emph{onerror} 是在当试图导入包如果发生任何异常则将附带一个参数（被导入的包的名称）被调用的函数。 如果没有提供 @emph{onerror} 函数，则 @ref{16c,,ImportError} 会被捕获并被忽略，而其他异常则会被传播，导致模块搜索的终结。

例如:

@example
# list all modules python can access
walk_packages()

# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')
@end example

@cartouche
@quotation 注解 
只适用于定义了 @code{iter_modules()} 方法的 @ref{1624,,finder}。 该接口是非标准的，因此本模块还提供了针对 @ref{a9f,,importlib.machinery.FileFinder} 和 @ref{37b6,,zipimport.zipimporter} 的实现。
@end quotation
@end cartouche


在 3.3 版更改: 更新为直接基于 @ref{9a,,importlib} 而不是依赖于包内部的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入模拟。

@end deffn

@geindex get_data() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil get_data}@anchor{1118}
@deffn {函数} pkgutil.get_data (package, resource)

从包中获取一个资源。

这是一个针对 @ref{1625,,loader} @ref{37c9,,get_data} API 的包装器。 @emph{package} 参数应为一个标准模块格式 (@code{foo.bar}) 的包名称。 @emph{resource} 参数应为相对路径文件名的形式，使用 @code{/} 作为路径分隔符。 父目录名 @code{..}，以及根目录名 (以 @code{/} 打头) 均不允许使用。

返回指定资源内容的二进制串。

对于位于文件系统中，已经被导入的包来说，这大致等价于:

@example
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
@end example

如果指定的包无法被定位或加载，或者如果它使用了不支持 @ref{37c9,,get_data} 的 @ref{1625,,loader}，则将返回 @code{None}。 特别地，针对 @ref{161d,,命名空间包} 的 @ref{1625,,loader} 不支持 @ref{37c9,,get_data}。
@end deffn

@geindex resolve_name() (在 pkgutil 模块中)
@anchor{library/pkgutil pkgutil resolve_name}@anchor{37ca}
@deffn {函数} pkgutil.resolve_name (name)

将一个名称解析为对象。

此功能被用在标准库的许多地方 (参见 bpo-12915@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=12915}) —— 并且等价的功能也被广泛用于第三方包例如 setuptools, Django 和 Pyramid。

预期 @emph{name} 将为以下格式之一，其中 W 是一个有效的 Python 标识符的缩写而点号表示这些伪正则表达式中的句点字面值:


@itemize *

@item 
@code{W(.W)*}

@item 
@code{W(.W)*:(W(.W)*)?}
@end itemize

第一种形式只是为了保持向下兼容性。 它假定带点号名称的某一部分是包，而其余部分则是该包内部的一个对象，并可能嵌套在其他对象之内。 因为包和对象层级结构之间的分界点无法通过观察来确定，所以使用这种形式必须重复尝试导入。

在第二种形式中，调用方通过提供一个单独冒号来明确分界点：冒号左边的带点号名称是要导入的包，而冒号右边的带点号名称则是对象层级结构。 使用这种形式只需要导入一次。 如果它以冒号结尾，则将返回一个模块对象。

此函数将返回一个对象（可能为模块），或是引发下列异常之一:

@ref{16d,,ValueError} -- 如果 @emph{name} 不为可识别的格式。

@ref{16c,,ImportError} -- 如果导入本应成功但却失败。

@ref{4aa,,AttributeError} -- 当在遍历所导入包的对象层级结构以获取想要的对象时遭遇失败。


3.9 新版功能.

@end deffn

@node modulefinder --- 查找脚本使用的模块,runpy ——查找并执行 Python 模块,pkgutil --- 包扩展工具,导入模块
@anchor{library/modulefinder doc}@anchor{37cb}@anchor{library/modulefinder module-modulefinder}@anchor{b4}@anchor{library/modulefinder modulefinder-find-modules-used-by-a-script}@anchor{37cc}
@subsection @code{modulefinder} --- 查找脚本使用的模块


@geindex modulefinder (模块)

@strong{源码：} Lib/modulefinder.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/modulefinder.py}


__________________________________________________________________


该模块提供了一个 @ref{1164,,ModuleFinder} 类，可用于确定脚本导入的模块集。 @code{modulefinder.py} 也可以作为脚本运行，给出 Python 脚本的文件名作为参数，之后将打印导入模块的报告。

@geindex AddPackagePath() (在 modulefinder 模块中)
@anchor{library/modulefinder modulefinder AddPackagePath}@anchor{37cd}
@deffn {函数} modulefinder.AddPackagePath (pkg_name, path)

记录名为 @emph{pkg_name} 的包可以在指定的 @emph{path} 中找到。
@end deffn

@geindex ReplacePackage() (在 modulefinder 模块中)
@anchor{library/modulefinder modulefinder ReplacePackage}@anchor{37ce}
@deffn {函数} modulefinder.ReplacePackage (oldname, newname)

允许指定名为 @emph{oldname} 的模块实际上是名为 @emph{newname} 的包。
@end deffn

@geindex ModuleFinder (modulefinder 中的类)
@anchor{library/modulefinder modulefinder ModuleFinder}@anchor{1164}
@deffn {类} modulefinder.ModuleFinder (path=None, debug=0, excludes=[], replace_paths=[])

该类提供 @ref{37cf,,run_script()} 和 @ref{37d0,,report()} 方法，用于确定脚本导入的模块集。 @emph{path} 可以是搜索模块的目录列表；如果没有指定，则使用 @code{sys.path} 。  @emph{debug} 设置调试级别；更高的值使类打印调试消息，关于它正在做什么。 @emph{excludes} 是要从分析中排除的模块名称列表。 @emph{replace_paths} 是将在模块路径中替换的 @code{(oldpath, newpath)} 元组的列表。

@geindex report() (modulefinder.ModuleFinder 方法)
@anchor{library/modulefinder modulefinder ModuleFinder report}@anchor{37d0}
@deffn {方法} report ()

将报告打印到标准输出，列出脚本导入的模块及其路径，以及缺少或似乎缺失的模块。
@end deffn

@geindex run_script() (modulefinder.ModuleFinder 方法)
@anchor{library/modulefinder modulefinder ModuleFinder run_script}@anchor{37cf}
@deffn {方法} run_script (pathname)

分析 @emph{pathname} 文件的内容，该文件必须包含 Python 代码。
@end deffn

@geindex modules (modulefinder.ModuleFinder 属性)
@anchor{library/modulefinder modulefinder ModuleFinder modules}@anchor{37d1}
@deffn {属性} modules

一个将模块名称映射到模块的字典。 请参阅 @ref{37d2,,ModuleFinder 的示例用法}。
@end deffn
@end deffn

@menu
* ModuleFinder 的示例用法:: 

@end menu

@node ModuleFinder 的示例用法,,,modulefinder --- 查找脚本使用的模块
@anchor{library/modulefinder example-usage-of-modulefinder}@anchor{37d3}@anchor{library/modulefinder modulefinder-example}@anchor{37d2}
@subsubsection @code{ModuleFinder} 的示例用法


稍后将分析的脚本（bacon.py）:

@example
import re, itertools

try:
    import baconhameggs
except ImportError:
    pass

try:
    import guido.python.ham
except ImportError:
    pass
@end example

将输出 bacon.py 报告的脚本:

@example
from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('bacon.py')

print('Loaded modules:')
for name, mod in finder.modules.items():
    print('%s: ' % name, end='@w{'})
    print(','.join(list(mod.globalnames.keys())[:3]))

print('-'*50)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))
@end example

输出样例（可能因架构而异）:

@example
Loaded modules:
_types:
copyreg:  _inverted_registry,_slotnames,__all__
sre_compile:  isstring,_sre,_optimize_unicode
_sre:
sre_constants:  REPEAT_ONE,makedict,AT_END_LINE
sys:
re:  __module__,finditer,_expand
itertools:
__main__:  re,itertools,baconhameggs
sre_parse:  _PATTERNENDERS,SRE_FLAG_UNICODE
array:
types:  __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs
@end example

@node runpy ——查找并执行 Python 模块,importlib --- import 的实现,modulefinder --- 查找脚本使用的模块,导入模块
@anchor{library/runpy doc}@anchor{37d4}@anchor{library/runpy module-runpy}@anchor{e2}@anchor{library/runpy runpy-locating-and-executing-python-modules}@anchor{37d5}
@subsection @code{runpy} ——查找并执行 Python  模块


@geindex runpy (模块)

@strong{源代码：} Lib/runpy.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/runpy.py}


__________________________________________________________________


@ref{e2,,runpy} 模块用于找到并运行 Python 的模块，而无需首先导入。主要用于实现 @ref{44c,,-m} 命令行开关，以允许用 Python 模块命名空间而不是文件系统来定位脚本。

请注意，这 @emph{并非} 一个沙盒模块——所有代码都在当前进程中运行，所有副作用（如其他模块对导入操作进行了缓存）在函数返回后都会留存。

此外，在 @ref{e2,,runpy} 函数返回后，任何由已执行代码定义的函数和类都不能保证正确工作。如果某使用场景不能接收此限制，那么选用 @ref{9a,,importlib} 可能更合适些。

@ref{e2,,runpy} 模块提供两个函数：

@geindex run_module() (在 runpy 模块中)
@anchor{library/runpy runpy run_module}@anchor{f7b}
@deffn {函数} runpy.run_module (mod_name, init_globals=None, run_name=None, alter_sys=False)

@geindex 模块; __main__

执行给定模块的代码，并返回结果模块的 globals 字典。 该模块的代码首先会用标准的导入机制去查找定位 (详情请参阅 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302})，然后在全新的模块命名空间中运行。

参数 @emph{mod_name} 应该是一个绝对模块名。如果模块名指向一个包，而不是普通的模块，那么该包会被导入，然后执行包中的 @code{__main__} 子模块，并返回结果模块的 globals 字典。

可选的字典参数 @emph{init_globals} 可用来在代码执行前预填充模块的 globals 字典。给出的字典参数不会被修改。如果字典中定义了以下任意一个特殊全局变量，这些定义都会被 @ref{f7b,,run_module()} 覆盖。

The special global variables @code{__name__}, @code{__spec__}, @code{__file__},
@code{__cached__}, @code{__loader__} and @code{__package__} are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).

若可选参数 @code{__name__} 不为 @ref{204,,None} 则设为 @emph{run_name}，若此名称的模块是一个包则设为 @code{mod_name + '.__main__'}，否则设为 @emph{mod_name} 参数。

@code{__spec__} 将设为合适的 @emph{实际} 导入模块（也就是说，@code{__spec__.name} 一定是 @emph{mod_name} 或  @code{mod_name + '.__main__}，而不是 @emph{run_name}）。

@code{__file__} 、@code{__cached__}、 @code{__loader__} 和 @code{__package__} 根据模块规范进行 @ref{162c,,正常设置}

如果给出了参数 @emph{alter_sys} 并且值为 @ref{59c,,True}，那么 @code{sys.argv[0]} 将被更新为 @code{__file__} 的值，@code{sys.modules[__name__]} 将被更新为临时模块对象。在函数返回前， @code{sys.argv[0]} 和 @code{sys.modules[__name__]} 将会复原。

注意，这种对 @ref{fd,,sys} 的操作不是线程安全的。其他线程可能会看到初始化不完整的模块，以及变动后的参数列表。如果从线程中的代码调用此函数，建议单实例运行 @ref{fd,,sys} 模块。


@subsubheading 参见


@ref{44c,,-m} 选项由命令行提供相同功能。



在 3.1 版更改: 加入了 查找 @code{__main__} 子模块并执行软件包的能力。



在 3.2 版更改: 加入了 @code{__cached__} 全局变量（参见  
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} ）。



在 3.4 版更改: 充分利用 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} 加入的模块规格功能。使得以这种方式运行的模块能够正确设置 @code{__cached__}，并确保真正的模块名称总是可以通过 @code{__spec__.name} 的形式访问。

@end deffn

@geindex run_path() (在 runpy 模块中)
@anchor{library/runpy runpy run_path}@anchor{d81}
@deffn {函数} runpy.run_path (path_name, init_globals=None, run_name=None)

@geindex 模块; __main__

执行指定位置的代码，并返回结果模块的 globals 字典。与提供给 CPython 命令行的脚本名称一样，给出的路径可以指向 Python 源文件、编译过的字节码文件或包含`@w{`}__main__`@w{`} 模块的有效 sys.path 项（例如一个包含顶级`@w{`}__main__.py`@w{`} 文件的 zip 文件）。

对于直接的脚本而言，指定代码将直接在一个新的模块命名空间中运行。对于一个有效的 sys.path 项（通常是一个 zip 文件或目录），其首先会被添加到 @code{sys.path} 的开头。然后，本函数用更新后的路径查找并执行 @ref{1,,__main__}  模块。请注意，即便在指定位置不存在主模块，也没有特别的保护措施来防止调用存在于 @code{sys.path} 其他地方的  @ref{1,,__main__}。

利用可选的字典参数 @emph{init_globals} ，可在代码执行前预填模块的 globals 字典。给出的字典参数不会被修改。如果给出的字典中定义了下列特殊全局变量，这些定义均会被 @ref{f7b,,run_module()} 覆盖。

The special global variables @code{__name__}, @code{__spec__}, @code{__file__},
@code{__cached__}, @code{__loader__} and @code{__package__} are set in the globals
dictionary before the module code is executed (Note that this is a
minimal set of variables - other variables may be set implicitly as an
interpreter implementation detail).

如果该可选参数不为 @ref{204,,None}，则 @code{__name__} 被设为 @emph{run_name}，否则为 @code{'<run_path>'}。

如果提供的路径直接引用了一个脚本文件（无论是源码文件还是预编译的字节码），那么 @code{__file__} 将设为给出的路径，而 @code{__spec__}、@code{__cached__}、@code{__loader__} 和 @code{__package__} 都将设为 @ref{204,,None}。

如果给出的路径是对有效 sys.path 项的引用，那么 @code{__spec__} 将为导入的 @code{__main__} 模块进行正确设置 (也就是说，@code{__spec__.name} 将一定是 @code{__main__})。 @code{__file__}, @code{__cached__}, @code{__loader__} 和 @code{__package__} 将依据模块规格 @ref{162c,,进行常规设置}。

@ref{fd,,sys} 模块也做了一些改动。 首先，@code{sys.path} 可能做上文所述的的修改。 @code{sys.argv[0]} 会被更新为 @code{path_name} 的值而 @code{sys.modules[__name__]} 会被更新为对应于正在被执行的模块的临时模块对象。 在函数返回之前对 @ref{fd,,sys} 中条目的所有修改都会被复原。

注意，与 @ref{f7b,,run_module()} 不同的是，本函数对 @ref{fd,,sys} 的修改不是可有可无的，因为这些调整对于 sys.path 项能够顺利执行至关重要。由于依然存在线程安全的限制，在线程代码中使用本函数时应采用导入锁进行序列运行，或者委托给一个单独的进程。


@subsubheading 参见


@ref{149f,,接口选项} 用于在命令行上实现同等功能（@code{python path/to/script}）。



3.2 新版功能.



在 3.4 版更改: 已作更新，以便充分利用 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} 加入的模块规格功能。使得从有效 sys.path 项导入`@w{`}__main__`@w{`} 而不是直接执行的情况下，能够正确设置 @code{__cached__}。

@end deffn


@subsubheading 参见



@table @asis

@geindex Python 提高建议; PEP 338

@item PEP 338@footnote{https://www.python.org/dev/peps/pep-0338} -- 将模块作为脚本执行

PEP 由 Nick Coghlan 撰写并实现。

@geindex Python 提高建议; PEP 366

@item PEP 366@footnote{https://www.python.org/dev/peps/pep-0366} ——主模块的显式相对导入

PEP 由 Nick Coghlan 撰写并实现。

@geindex Python 提高建议; PEP 451

@item PEP 451@footnote{https://www.python.org/dev/peps/pep-0451} —— 导入系统采用的 ModuleSpec 类型

PEP 由  Eric Snow 撰写并实现。
@end table

@ref{1106,,命令行与环境} —— CPython 命令行详解

@ref{bef,,importlib.import_module()} 函数


@node importlib --- import 的实现,使用 importlib metadata,runpy ——查找并执行 Python 模块,导入模块
@anchor{library/importlib doc}@anchor{37d6}@anchor{library/importlib importlib-the-implementation-of-import}@anchor{37d7}@anchor{library/importlib module-importlib}@anchor{9a}
@subsection @code{importlib} --- @code{import} 的实现


@geindex importlib (模块)


3.1 新版功能.


@strong{源代码} Lib/importlib/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/__init__.py}


__________________________________________________________________


@menu
* 概述: 概述<12>. 
* 函数: 函数<10>. 
* importlib.abc —— 关于导入的抽象基类: importlib abc —— 关于导入的抽象基类. 
* importlib.resources: importlib resources -- 资源. 资源
* importlib.machinery —— 导入器和路径钩子函数。: importlib machinery —— 导入器和路径钩子函数。. 
* importlib.util —— 导入器的工具程序代码: importlib util —— 导入器的工具程序代码. 
* 示例: 示例<44>. 

@end menu

@node 概述<12>,函数<10>,,importlib --- import 的实现
@anchor{library/importlib introduction}@anchor{37d8}
@subsubsection 概述


@ref{9a,,importlib} 包的目的有两个。 第一个目的是在 Python 源代码中提供 @ref{cef,,import} 语句的实现（并且因此而扩展 @ref{16b,,__import__()} 函数）。 这提供了一个可移植到任何 Python 解释器的 @code{import} 实现。 相比使用 Python 以外的编程语言实现方式，这一实现更加易于理解。

第二个目的是实现 @ref{cef,,import} 的部分被公开在这个包中，使得用户更容易创建他们自己的自定义对象 (通常被称为 @ref{1626,,importer}) 来参与到导入过程中。


@subsubheading 参见



@table @asis

@item @ref{cef,,import 语句}

@ref{cef,,import} 语句的语言参考

@item 包规格说明@footnote{https://www.python.org/doc/essays/packages/}

包的初始规范。自从编写这个文档开始，一些语义已经发生改变了（比如基于 @ref{109a,,sys.modules} 中 @code{None} 的重定向）。

@item @ref{a97,,__import__()} 函数

@ref{cef,,import} 语句是这个函数的语法糖。

@geindex Python 提高建议; PEP 235

@item PEP 235@footnote{https://www.python.org/dev/peps/pep-0235}

在忽略大小写的平台上进行导入

@geindex Python 提高建议; PEP 263

@item PEP 263@footnote{https://www.python.org/dev/peps/pep-0263}

定义 Python 源代码编码

@geindex Python 提高建议; PEP 302

@item PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}

新导入钩子

@geindex Python 提高建议; PEP 328

@item PEP 328@footnote{https://www.python.org/dev/peps/pep-0328}

导入：多行和绝对/相对

@geindex Python 提高建议; PEP 366

@item PEP 366@footnote{https://www.python.org/dev/peps/pep-0366}

主模块显式相对导入

@geindex Python 提高建议; PEP 420

@item PEP 420@footnote{https://www.python.org/dev/peps/pep-0420}

隐式命名空间包

@geindex Python 提高建议; PEP 451

@item PEP 451@footnote{https://www.python.org/dev/peps/pep-0451}

导入系统的一个模块规范类型

@geindex Python 提高建议; PEP 488

@item PEP 488@footnote{https://www.python.org/dev/peps/pep-0488}

消除PYO文件

@geindex Python 提高建议; PEP 489

@item PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}

多阶段扩展模块初始化

@geindex Python 提高建议; PEP 552

@item PEP 552@footnote{https://www.python.org/dev/peps/pep-0552}

确定性的 pyc 文件

@geindex Python 提高建议; PEP 3120

@item PEP 3120@footnote{https://www.python.org/dev/peps/pep-3120}

使用 UTF-8 作为默认的源编码

@geindex Python 提高建议; PEP 3147

@item PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}

PYC 仓库目录
@end table


@node 函数<10>,importlib abc —— 关于导入的抽象基类,概述<12>,importlib --- import 的实现
@anchor{library/importlib functions}@anchor{37d9}
@subsubsection 函数


@geindex __import__() (在 importlib 模块中)
@anchor{library/importlib importlib __import__}@anchor{a97}
@deffn {函数} importlib.__import__ (name, globals=None, locals=None, fromlist=(), level=0)

内置 @ref{16b,,__import__()} 函数的实现。

@cartouche
@quotation 注解 
程序式地导入模块应该使用 @ref{bef,,import_module()} 而不是这个函数。
@end quotation
@end cartouche
@end deffn

@geindex import_module() (在 importlib 模块中)
@anchor{library/importlib importlib import_module}@anchor{bef}
@deffn {函数} importlib.import_module (name, package=None)

导入一个模块。 参数 @emph{name} 指定了以绝对或相对导入方式导入什么模块 (比如要么像这样 @code{pkg.mod} 或者这样 @code{..mod})。 如果参数 name 使用相对导入的方式来指定，那么 @emph{package} 参数必须设置为那个包名，这个包名作为解析这个包名的锚点 (比如  @code{import_module('..mod', 'pkg.subpkg')} 将会导入 @code{pkg.mod})。

@ref{bef,,import_module()} 函数是一个对 @ref{a97,,importlib.__import__()} 进行简化的包装器。 这意味着该函数的所有语义都来自于 @ref{a97,,importlib.__import__()}。 这两个函数之间最重要的不同点在于 @ref{bef,,import_module()} 返回指定的包或模块 (例如 @code{pkg.mod})，而 @ref{16b,,__import__()} 返回最高层级的包或模块 (例如 @code{pkg})。

如果动态导入一个自解释器开始执行以来被创建的模块（即创建了一个 Python 源代码文件），为了让导入系统知道这个新模块，可能需要调用 @ref{59f,,invalidate_caches()}。


在 3.3 版更改: 父包会被自动导入。

@end deffn

@geindex find_loader() (在 importlib 模块中)
@anchor{library/importlib importlib find_loader}@anchor{a24}
@deffn {函数} importlib.find_loader (name, path=None)

查找一个模块的加载器，可选择地在指定的 @emph{path} 里面。如果这个模块是在 @ref{109a,,sys.modules}，那么返回 @code{sys.modules[name].__loader__} (除非这个加载器是 @code{None} 或者是没有被设置， 在这样的情况下，会引起 @ref{16d,,ValueError} 异常）。 否则使用 @ref{6e7,,sys.meta_path} 的一次搜索就结束。如果未发现加载器，则返回 @code{None}。

点状的名称没有使得它父包或模块隐式地导入，因为它需要加载它们并且可能不需要。为了适当地导入一个子模块，需要导入子模块的所有父包并且使用正确的参数提供给 @emph{path}。


3.3 新版功能.



在 3.4 版更改: 如果没有设置 @code{__loader__}，会引起 @ref{16d,,ValueError} 异常，就像属性设置为 @code{None} 的时候一样。



3.4 版后已移除: 使用 @ref{a25,,importlib.util.find_spec()} 来代替。

@end deffn

@geindex invalidate_caches() (在 importlib 模块中)
@anchor{library/importlib importlib invalidate_caches}@anchor{59f}
@deffn {函数} importlib.invalidate_caches ()

使查找器存储在 @ref{6e7,,sys.meta_path} 中的内部缓存无效。如果一个查找器实现了 @code{invalidate_caches()}，那么它会被调用来执行那个无效过程。 如果创建/安装任何模块，同时正在运行的程序是为了保证所有的查找器知道新模块的存在，那么应该调用这个函数。


3.3 新版功能.

@end deffn

@geindex reload() (在 importlib 模块中)
@anchor{library/importlib importlib reload}@anchor{4a8}
@deffn {函数} importlib.reload (module)

重新加载之前导入的 @emph{module}。 那个参数必须是一个模块对象，所以它之前必须已经成功导入了。 这在你已经使用外部编辑器编辑过了那个模块的源代码文件并且想在退出 Python 解释器之前试验这个新版本的模块的时候将很适用。 函数的返回值是那个模块对象（如果重新导入导致一个不同的对象放置在 @ref{109a,,sys.modules} 中，那么那个模块对象是有可能会不同）。

当执行 @ref{4a8,,reload()} 的时候：


@itemize *

@item 
Python 模块的代码会被重新编译并且那个模块级的代码被重新执行，通过重新使用一开始加载那个模块的 @ref{1625,,loader}，定义一个新的绑定在那个模块字典中的名称的对象集合。扩展模块的`@w{`}init`@w{`}函数不会被调用第二次。

@item 
与Python中的所有的其它对象一样，旧的对象只有在它们的引用计数为0之后才会被回收。

@item 
模块命名空间中的名称重新指向任何新的或更改后的对象。

@item 
其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新。
@end itemize

有一些其他注意事项：

当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的缓存 —— 使用 @ref{e3f,,try} 语句，就可以测试表的存在并且跳过它的初始化，如果有需要的话:

@example
try:
    cache
except NameError:
    cache = @{@}
@end example

重新加载内置的或者动态加载模块，通常来说不是很有用处。不推荐重新加载"@ref{fd,,sys}，@ref{1,,__main__}，@ref{12,,builtins} 和其它关键模块。在很多例子中，扩展模块并不是设计为不止一次的初始化，并且当重新加载时，可能会以任意方式失败。

如果一个模块使用 @ref{d15,,from} ... @ref{cef,,import} ... 导入的对象来自另外一个模块，给其它模块调用 @ref{4a8,,reload()} 不会重新定义来自这个模块的对象 —— 解决这个问题的一种方式是重新执行 @code{from} 语句，另一种方式是使用 @code{import} 和限定名称(@emph{module.name})来代替。

如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响那些实例的方法定义———它们继续使用旧类中的定义。对于子类来说同样是正确的。


3.4 新版功能.



在 3.7 版更改: 当重新加载的那个模块缺少 @code{ModuleSpec} 的时候，会引起 @ref{4a9,,ModuleNotFoundError} 异常。

@end deffn

@node importlib abc —— 关于导入的抽象基类,importlib resources -- 资源,函数<10>,importlib --- import 的实现
@anchor{library/importlib importlib-abc-abstract-base-classes-related-to-import}@anchor{37da}@anchor{library/importlib module-importlib abc}@anchor{9b}
@subsubsection @code{importlib.abc} —— 关于导入的抽象基类


@geindex importlib.abc (模块)

@strong{源代码：} Lib/importlib/abc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/abc.py}


__________________________________________________________________


The @ref{9b,,importlib.abc} module contains all of the core abstract base classes
used by @ref{cef,,import}. Some subclasses of the core abstract base classes
are also provided to help in implementing the core ABCs.

ABC 类的层次结构：

@example
object
 +-- Finder (deprecated)
 |    +-- MetaPathFinder
 |    +-- PathEntryFinder
 +-- Loader
      +-- ResourceLoader --------+
      +-- InspectLoader          |
           +-- ExecutionLoader --+
                                 +-- FileLoader
                                 +-- SourceLoader
@end example

@geindex Finder (importlib.abc 中的类)
@anchor{library/importlib importlib abc Finder}@anchor{a9e}
@deffn {类} importlib.abc.Finder

代表 @ref{1624,,finder} 的一个抽象基类


3.3 版后已移除: 使用 @ref{a9c,,MetaPathFinder} 或 @ref{a9d,,PathEntryFinder} 来代替。


@geindex find_module() (importlib.abc.Finder 方法)
@anchor{library/importlib importlib abc Finder find_module}@anchor{37db}
@deffn {方法} abstractmethod find_module (fullname, path=None)

为指定的模块查找 @ref{1625,,loader} 定义的抽象方法。本来是在 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 指定的，这个方法是在 @ref{6e7,,sys.meta_path} 和基于路径的导入子系统中使用。


在 3.4 版更改: 当被调用的时候，返回 @code{None} 而不是引发 @ref{70e,,NotImplementedError}。

@end deffn
@end deffn

@geindex MetaPathFinder (importlib.abc 中的类)
@anchor{library/importlib importlib abc MetaPathFinder}@anchor{a9c}
@deffn {类} importlib.abc.MetaPathFinder

代表 @ref{a9a,,meta path finder} 的一个抽象基类。 为了保持兼容性，这是 @ref{a9e,,Finder} 的一个子类。


3.3 新版功能.


@geindex find_spec() (importlib.abc.MetaPathFinder 方法)
@anchor{library/importlib importlib abc MetaPathFinder find_spec}@anchor{56d}
@deffn {方法} find_spec (fullname, path, target=None)

一个抽象方法，用于查找指定模块的 @ref{36c1,,spec} 。若是顶层导入，@emph{path} 将为 @code{None}。 否则就是查找子包或模块，@emph{path} 将是父级包的 @ref{13f3,,__path__} 值。找不到则会返回 @code{None}。传入的 @code{target} 是一个模块对象，查找器可以用来对返回的规格进行更有依据的猜测。在实现具体的 @code{MetaPathFinders} 代码时，可能会用到 @ref{37dc,,importlib.util.spec_from_loader()} 。


3.4 新版功能.

@end deffn

@geindex find_module() (importlib.abc.MetaPathFinder 方法)
@anchor{library/importlib importlib abc MetaPathFinder find_module}@anchor{56c}
@deffn {方法} find_module (fullname, path)

一个用于查找指定的模块中 @ref{1625,,loader} 的遗留方法。如果这是最高层级的导入，@emph{path} 的值将会是 @code{None}。否则，这是一个查找子包或者模块的方法，并且 @emph{path} 的值将会是来自父包的 @ref{13f3,,__path__} 的值。如果未发现加载器，返回 @code{None}。

如果定义了 @ref{56d,,find_spec()} 方法，则提供了向后兼容的功能。


在 3.4 版更改: 当调用这个方法的时候返回 @code{None} 而不是引发 @ref{70e,,NotImplementedError}。 可以使用 @ref{56d,,find_spec()} 来提供功能。



3.4 版后已移除: 使用 @ref{56d,,find_spec()} 来代替。

@end deffn

@geindex invalidate_caches() (importlib.abc.MetaPathFinder 方法)
@anchor{library/importlib importlib abc MetaPathFinder invalidate_caches}@anchor{37dd}
@deffn {方法} invalidate_caches ()

当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进行无效。将在 @ref{6e7,,sys.meta_path} 上的所有查找器的缓存进行无效的时候，这个函数被 @ref{59f,,importlib.invalidate_caches()} 所使用。


在 3.4 版更改: 当方法被调用的时候，方法返回是 @code{None} 而不是 @code{NotImplemented} 。

@end deffn
@end deffn

@geindex PathEntryFinder (importlib.abc 中的类)
@anchor{library/importlib importlib abc PathEntryFinder}@anchor{a9d}
@deffn {类} importlib.abc.PathEntryFinder

@ref{a9b,,path entry finder} 的一个抽象基类。尽管这个基类和 @ref{a9c,,MetaPathFinder} 有一些相似之处，但是 @code{PathEntryFinder} 只在由 @code{PathFinder} 提供的基于路径导入子系统中使用。这个抽象类是 @ref{1624,,Finder} 的一个子类，仅仅是因为兼容性的原因。


3.3 新版功能.


@geindex find_spec() (importlib.abc.PathEntryFinder 方法)
@anchor{library/importlib importlib abc PathEntryFinder find_spec}@anchor{56f}
@deffn {方法} find_spec (fullname, target=None)

一个抽象方法，用于查找指定模块的 @ref{36c1,,spec}。搜索器将只在指定的 @ref{163a,,path entry} 内搜索该模块。找不到则会返回 @code{None}。在实现具体的 @code{PathEntryFinders} 代码时，可能会用到  @ref{37dc,,importlib.util.spec_from_loader()} 。


3.4 新版功能.

@end deffn

@geindex find_loader() (importlib.abc.PathEntryFinder 方法)
@anchor{library/importlib importlib abc PathEntryFinder find_loader}@anchor{56e}
@deffn {方法} find_loader (fullname)

一个用于在模块中查找一个 @ref{1625,,loader} 的遗留方法。 返回一个 @code{(loader, portion)} 的2元组，@code{portion} 是一个贡献给命名空间包部分的文件系统位置的序列。 加载器可能是 @code{None}，同时正在指定的 @code{portion} 表示的是贡献给命名空间包的文件系统位置。@code{portion} 可以使用一个空列表来表示加载器不是命名空间包的一部分。 如果 @code{loader} 是 @code{None} 并且 @code{portion} 是一个空列表，那么命名空间包中无加载器或者文件系统位置可查找到（即在那个模块中未能找到任何东西）。

如果定义了 @ref{56f,,find_spec()} ，则提供了向后兼容的功能。


在 3.4 版更改: 返回 @code{(None, [])} 而不是引发 @ref{70e,,NotImplementedError}。 当可于提供相应的功能的时候，使用 @ref{56f,,find_spec()}。



3.4 版后已移除: 使用 @ref{56f,,find_spec()} 来代替。

@end deffn

@geindex find_module() (importlib.abc.PathEntryFinder 方法)
@anchor{library/importlib importlib abc PathEntryFinder find_module}@anchor{a28}
@deffn {方法} find_module (fullname)

@code{Finder.find_module`的具体实现，该方法等价于`@w{`}self.find_loader(fullname)[0]`()}。


3.4 版后已移除: 使用 @ref{56f,,find_spec()} 来代替。

@end deffn

@geindex invalidate_caches() (importlib.abc.PathEntryFinder 方法)
@anchor{library/importlib importlib abc PathEntryFinder invalidate_caches}@anchor{37de}
@deffn {方法} invalidate_caches ()

当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进行无效。当将所有缓存的查找器的缓存进行无效的时候，该函数被  @code{PathFinder.invalidate_caches()} 使用。
@end deffn
@end deffn

@geindex Loader (importlib.abc 中的类)
@anchor{library/importlib importlib abc Loader}@anchor{8b9}
@deffn {类} importlib.abc.Loader

@ref{1625,,loader} 的抽象基类。 关于一个加载器的实际定义请查看 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}。

加载器想要支持资源读取应该实现一个由 @ref{457,,importlib.abc.ResourceReader} 指定的`@w{`}get_resource_reader(fullname)`@w{`} 方法。


在 3.7 版更改: 引入了可选的 @code{get_resource_reader()} 方法。


@geindex create_module() (importlib.abc.Loader 方法)
@anchor{library/importlib importlib abc Loader create_module}@anchor{657}
@deffn {方法} create_module (spec)

当导入一个模块的时候，一个返回将要使用的那个模块对象的方法。这个方法可能返回 @code{None} ，这暗示着应该发生默认的模块创建语义。"


3.4 新版功能.



在 3.5 版更改: 从 Python 3.6 开始，当定义了 @ref{6e5,,exec_module()} 的时候，这个方法将不会是可选的。

@end deffn

@geindex exec_module() (importlib.abc.Loader 方法)
@anchor{library/importlib importlib abc Loader exec_module}@anchor{6e5}
@deffn {方法} exec_module (module)

当一个模块被导入或重新加载时，一个抽象方法在它自己的命名空间中执行那个模块。当调用 @code{exec_module()} 的时候，那个模块应该已经被初始化 了。当这个方法存在时，必须定义 @ref{657,,create_module()} 。


3.4 新版功能.



在 3.6 版更改: @ref{657,,create_module()} 也必须被定义。

@end deffn

@geindex load_module() (importlib.abc.Loader 方法)
@anchor{library/importlib importlib abc Loader load_module}@anchor{6e4}
@deffn {方法} load_module (fullname)

用于加载一个模块的传统方法。如果这个模块不能被导入，将引起 @ref{16c,,ImportError} 异常，否则返回那个被加载的模块。

如果请求的模块已经存在 @ref{109a,,sys.modules}，应该使用并且重新加载那个模块。 否则加载器应该是创建一个新的模块并且在任何家过程开始之前将这个新模块插入到 @ref{109a,,sys.modules} 中，来阻止递归导入。 如果加载器插入了一个模块并且加载失败了，加载器必须从 @ref{109a,,sys.modules} 中将这个模块移除。在加载器开始执行之前，已经在 @ref{109a,,sys.modules} 中的模块应该被忽略 (查看 @ref{a2f,,importlib.util.module_for_loader()})。

加载器应该在模块上面设置几个属性。（要知道当重新加载一个模块的时候，那些属性某部分可以改变）：


@itemize -

@item 

@table @asis

@item @ref{de0,,__name__}

模块的名字
@end table

@item 

@table @asis

@item @ref{1591,,__file__}

模块数据存储的路径(不是为了内置的模块而设置)
@end table

@item 

@table @asis

@item @ref{c0d,,__cached__}

被存储或应该被存储的模块的编译版本的路径（当这个属性不恰当的时候不设置）。
@end table

@item 

@table @asis

@item @ref{13f3,,__path__}

指定在一个包中搜索路径的一个字符串列表。这个属性不在模块上面进行设置。
@end table

@item 

@table @asis

@item @ref{a3f,,__package__}

当模块作为子模块加载时，其所在包的完全限定名称（顶层模块则为空字符串）。对于包而言，与 @ref{de0,,__name__} 相同。 @ref{a2f,,importlib.util.module_for_loader()} 装饰器能够处理 @ref{a3f,,__package__} 的细节。
@end table

@item 

@table @asis

@item @ref{a40,,__loader__}

用来加载那个模块的加载器。 @ref{a2f,,importlib.util.module_for_loader()} 装饰器可以处理 @ref{a3f,,__package__} 的细节。
@end table
@end itemize

当 @ref{6e5,,exec_module()} 可用的时候，那么则提供了向后兼容的功能。


在 3.4 版更改: 当这个方法被调用的时候，触发 @ref{16c,,ImportError} 异常而不是 @ref{70e,,NotImplementedError}。当 @ref{6e5,,exec_module()} 可用的时候，使用它的功能。



3.4 版后已移除: 加载模块推荐的使用的 API 是 @ref{6e5,,exec_module()} (和 @ref{657,,create_module()})。 加载器应该实现它而不是 load_module()。 当 exec_module() 被实现的时候，导入机制关心的是 load_module() 所有其他的责任。

@end deffn

@geindex module_repr() (importlib.abc.Loader 方法)
@anchor{library/importlib importlib abc Loader module_repr}@anchor{a2e}
@deffn {方法} module_repr (module)

一个遗留方法，在实现时计算并返回给定模块的 repr，作为字符串。 模块类型的默认 repr() 将根据需要使用此方法的结果。


3.3 新版功能.



在 3.4 版更改: 是可选的方法而不是一个抽象方法。



3.4 版后已移除: 现在导入机制会自动地关注这个方法。

@end deffn
@end deffn

@geindex ResourceReader (importlib.abc 中的类)
@anchor{library/importlib importlib abc ResourceReader}@anchor{457}
@deffn {类} importlib.abc.ResourceReader

@emph{被 TraversableResources} 取代

提供读取 @emph{resources} 能力的一个 @ref{c0e,,abstract base class} 。

从这个 ABC 的视角出发，@emph{resource} 指一个包附带的二进制文件。常见的如在包的  @code{__init__.py} 文件旁的数据文件。这个类存在的目的是为了将对数据文件的访问进行抽象，这样包就和其数据文件的存储方式无关了。不论这些文件是存放在一个 zip 文件里还是直接在文件系统内。

对于该类中的任一方法，@emph{resource} 参数的值都需要是一个在概念上表示文件名称的 @ref{47b,,path-like object}。 这意味着任何子目录的路径都不该出现在 @emph{resouce} 参数值内。 因为对于阅读器而言，包的位置就代表着「目录」。 因此目录和文件名就分别对应于包和资源。 这也是该类的实例都需要和一个包直接关联（而不是潜在指代很多包或者一整个模块）的原因。

想支持资源读取的加载器需要提供一个返回实现了此 ABC 的接口的 @code{get_resource_reader(fullname)} 方法。如果通过全名指定的模块不是一个包，这个方法应该返回 @ref{204,,None}。 当指定的模块是一个包时，应该只返回一个与这个抽象类ABC兼容的对象。


3.7 新版功能.


@geindex open_resource() (importlib.abc.ResourceReader 方法)
@anchor{library/importlib importlib abc ResourceReader open_resource}@anchor{37df}
@deffn {方法} abstractmethod open_resource (resource)

返回一个打开的 @ref{1e0e,,file-like object} 用于 @emph{resource} 的二进制读取。

如果无法找到资源，将会引发 @ref{8b7,,FileNotFoundError}。
@end deffn

@geindex resource_path() (importlib.abc.ResourceReader 方法)
@anchor{library/importlib importlib abc ResourceReader resource_path}@anchor{37e0}
@deffn {方法} abstractmethod resource_path (resource)

返回 @emph{resource} 的文件系统路径。

如果资源并不实际存在于文件系统中，将会引发 @ref{8b7,,FileNotFoundError}。
@end deffn

@geindex is_resource() (importlib.abc.ResourceReader 方法)
@anchor{library/importlib importlib abc ResourceReader is_resource}@anchor{37e1}
@deffn {方法} abstractmethod is_resource (name)

如果*name* 被视作资源，则返回True。如果*name*不存在，则引发 @ref{8b7,,FileNotFoundError} 异常。
@end deffn

@geindex contents() (importlib.abc.ResourceReader 方法)
@anchor{library/importlib importlib abc ResourceReader contents}@anchor{11b9}
@deffn {方法} abstractmethod contents ()

反回由字符串组成的 @ref{c84,,iterable}，表示这个包的所有内容。 请注意并不要求迭代器返回的所有名称都是实际的资源，例如返回 @ref{37e1,,is_resource()} 为假值的名称也是可接受的。

允许非资源名字被返回是为了允许存储的一个包和它的资源的方式是已知先验的并且非资源名字会有用的情况。比如，允许返回子目录名字，目的是当得知包和资源存储在文件系统上面的时候，能够直接使用子目录的名字。

这个抽象方法返回了一个不包含任何内容的可迭代对象。
@end deffn
@end deffn

@geindex ResourceLoader (importlib.abc 中的类)
@anchor{library/importlib importlib abc ResourceLoader}@anchor{570}
@deffn {类} importlib.abc.ResourceLoader

一个 @ref{1625,,loader} 的抽象基类，它实现了可选的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 协议用于从存储后端加载任意资源。


3.7 版后已移除: 由于要支持使用 @ref{457,,importlib.abc.ResourceReader}  类来加载资源，这个 ABC 已经被弃用了。


@geindex get_data() (importlib.abc.ResourceLoader 方法)
@anchor{library/importlib importlib abc ResourceLoader get_data}@anchor{37c9}
@deffn {方法} abstractmethod get_data (path)

一个用于返回位于 @emph{path} 的字节数据的抽象方法。有一个允许存储任意数据的类文件存储后端的加载器能够实现这个抽象方法来直接访问这些被存储的数据。如果不能够找到 @emph{path}，则会引发 @ref{30b,,OSError} 异常。@emph{path} 被希望使用一个模块的 @code{__file} 属性或来自一个包的 @ref{13f3,,__path__} 来构建。


在 3.4 版更改: 引发 @ref{30b,,OSError} 异常而不是 @ref{70e,,NotImplementedError} 异常。

@end deffn
@end deffn

@geindex InspectLoader (importlib.abc 中的类)
@anchor{library/importlib importlib abc InspectLoader}@anchor{954}
@deffn {类} importlib.abc.InspectLoader

一个实现加载器检查模块可选的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 协议的 @ref{1625,,loader} 的抽象基类。

@geindex get_code() (importlib.abc.InspectLoader 方法)
@anchor{library/importlib importlib abc InspectLoader get_code}@anchor{955}
@deffn {方法} get_code (fullname)

返回一个模块的代码对象，或如果模块没有一个代码对象（例如，对于内置的模块来说，这会是这种情况），则为 @code{None}。 如果加载器不能找到请求的模块，则引发 @ref{16c,,ImportError} 异常。

@cartouche
@quotation 注解 
当这个方法有一个默认的实现的时候，出于性能方面的考虑，如果有可能的话，建议覆盖它。
@end quotation
@end cartouche

@geindex universal newlines; importlib.abc.InspectLoader.get_source method


在 3.4 版更改: 不再抽象并且提供一个具体的实现。

@end deffn

@geindex get_source() (importlib.abc.InspectLoader 方法)
@anchor{library/importlib importlib abc InspectLoader get_source}@anchor{959}
@deffn {方法} abstractmethod get_source (fullname)

一个返回模块源的抽象方法。使用 @ref{6f5,,universal newlines} 作为文本字符串被返回，将所有可识别行分割符翻译成 @code{'\n'} 字符。 如果没有可用的源（例如，一个内置模块），则返回 @code{None}。 如果加载器不能找到指定的模块，则引发 @ref{16c,,ImportError} 异常。


在 3.4 版更改: 引发 @ref{16c,,ImportError} 而不是 @ref{70e,,NotImplementedError}。

@end deffn

@geindex is_package() (importlib.abc.InspectLoader 方法)
@anchor{library/importlib importlib abc InspectLoader is_package}@anchor{37e2}
@deffn {方法} is_package (fullname)

可选方法，如果模块为包，则返回 True，否则返回 False。 如果 @ref{1625,,loader} 找不到模块，则会触发 @ref{16c,,ImportError}。


在 3.4 版更改: 引发 @ref{16c,,ImportError} 而不是 @ref{70e,,NotImplementedError}。

@end deffn

@geindex source_to_code() (importlib.abc.InspectLoader 静态方法)
@anchor{library/importlib importlib abc InspectLoader source_to_code}@anchor{7ea}
@deffn {方法} static source_to_code (data, path='<string>')

创建一个来自Python源码的代码对象。

参数 @emph{data} 可以是任意 @ref{2ee,,compile()} 函数支持的类型（例如字符串或字节串）。 参数 @emph{path} 应该是源代码来源的路径，这可能是一个抽象概念（例如位于一个 zip 文件中）。

在有后续代码对象的情况下，可以在一个模块中通过运行`@w{`}exec(code, module.__dict__)`@w{`}来执行它。


3.4 新版功能.



在 3.5 版更改: 使得这个方法变成静态的。

@end deffn

@geindex exec_module() (importlib.abc.InspectLoader 方法)
@anchor{library/importlib importlib abc InspectLoader exec_module}@anchor{a2c}
@deffn {方法} exec_module (module)

@ref{6e5,,Loader.exec_module()} 的实现。


3.4 新版功能.

@end deffn

@geindex load_module() (importlib.abc.InspectLoader 方法)
@anchor{library/importlib importlib abc InspectLoader load_module}@anchor{a29}
@deffn {方法} load_module (fullname)

@ref{6e4,,Loader.load_module()} 的实现。


3.4 版后已移除: 使用 @ref{a2c,,exec_module()} 来代替。

@end deffn
@end deffn

@geindex ExecutionLoader (importlib.abc 中的类)
@anchor{library/importlib importlib abc ExecutionLoader}@anchor{37e3}
@deffn {类} importlib.abc.ExecutionLoader

一个继承自 @ref{954,,InspectLoader} 的抽象基类，当被实现时，帮助一个模块作为脚本来执行。 这个抽象基类表示可选的 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 协议。

@geindex get_filename() (importlib.abc.ExecutionLoader 方法)
@anchor{library/importlib importlib abc ExecutionLoader get_filename}@anchor{37e4}
@deffn {方法} abstractmethod get_filename (fullname)

一个用来为指定模块返回 @ref{1591,,__file__} 的值的抽象方法。如果无路径可用，则引发 @ref{16c,,ImportError}。

如果源代码可用，那么这个方法返回源文件的路径，不管是否是用来加载模块的字节码。


在 3.4 版更改: 引发 @ref{16c,,ImportError} 而不是 @ref{70e,,NotImplementedError}。

@end deffn
@end deffn

@geindex FileLoader (importlib.abc 中的类)
@anchor{library/importlib importlib abc FileLoader}@anchor{aa0}
@deffn {类} importlib.abc.FileLoader (fullname, path)

一个继承自 @ref{570,,ResourceLoader} 和 @ref{37e3,,ExecutionLoader}，提供 @ref{37c9,,ResourceLoader.get_data()} 和 @ref{37e4,,ExecutionLoader.get_filename()} 具体实现的抽象基类。

参数*fullname*是加载器要处理的模块的完全解析的名字。参数*path*是模块文件的路径。


3.3 新版功能.


@geindex name (importlib.abc.FileLoader 属性)
@anchor{library/importlib importlib abc FileLoader name}@anchor{37e5}
@deffn {属性} name

加载器可以处理的模块的名字。
@end deffn

@geindex path (importlib.abc.FileLoader 属性)
@anchor{library/importlib importlib abc FileLoader path}@anchor{37e6}
@deffn {属性} path

模块的文件路径
@end deffn

@geindex load_module() (importlib.abc.FileLoader 方法)
@anchor{library/importlib importlib abc FileLoader load_module}@anchor{a2a}
@deffn {方法} load_module (fullname)

调用super的`@w{`}load_module()`@w{`}。


3.4 版后已移除: 使用 @ref{6e5,,Loader.exec_module()} 来代替。

@end deffn

@geindex get_filename() (importlib.abc.FileLoader 方法)
@anchor{library/importlib importlib abc FileLoader get_filename}@anchor{37e7}
@deffn {方法} abstractmethod get_filename (fullname)

返回 @ref{37e6,,path}。
@end deffn

@geindex get_data() (importlib.abc.FileLoader 方法)
@anchor{library/importlib importlib abc FileLoader get_data}@anchor{37e8}
@deffn {方法} abstractmethod get_data (path)

读取 @emph{path} 作为二进制文件并且返回来自它的字节数据。
@end deffn
@end deffn

@geindex SourceLoader (importlib.abc 中的类)
@anchor{library/importlib importlib abc SourceLoader}@anchor{37e9}
@deffn {类} importlib.abc.SourceLoader

一个用于实现源文件（和可选地字节码）加载的抽象基类。这个类继承自 @ref{570,,ResourceLoader} 和 @ref{37e3,,ExecutionLoader}，需要实现：


@itemize *

@item 
@ref{37c9,,ResourceLoader.get_data()}

@item 

@table @asis

@item @ref{37e4,,ExecutionLoader.get_filename()}

应该是只返回源文件的路径；不支持无源加载。
@end table
@end itemize

由这个类定义的抽象方法用来添加可选的字节码文件支持。不实现这些可选的方法（或导致它们引发 @ref{70e,,NotImplementedError} 异常）导致这个加载器只能与源代码一起工作。 实现这些方法允许加载器能与源 @emph{和} 字节码文件一起工作。不允许只提供字节码的 @emph{无源式} 加载。字节码文件是通过移除 Python 编译器的解析步骤来加速加载的优化，并且因此没有开放出字节码专用的 API。

@geindex path_stats() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader path_stats}@anchor{bcc}
@deffn {方法} path_stats (path)

返回一个包含关于指定路径的元数据的 @ref{164,,dict} 的可选的抽象方法。 支持的字典键有：


@itemize -

@item 
@code{'mtime'} (必选项): 一个表示源码修改时间的整数或浮点数；

@item 
@code{'size'} (可选项)：源码的字节大小。
@end itemize

字典中任何其他键会被忽略，以允许将来的扩展。 如果不能处理该路径，则会引发 @ref{30b,,OSError}。


3.3 新版功能.



在 3.4 版更改: 引发 @ref{30b,,OSError} 而不是 @ref{203,,NotImplemented}。

@end deffn

@geindex path_mtime() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader path_mtime}@anchor{bcb}
@deffn {方法} path_mtime (path)

返回指定文件路径修改时间的可选的抽象方法。


3.3 版后已移除: 在有了 @ref{bcc,,path_stats()} 的情况下，这个方法被弃用了。 没必要去实现它了，但是为了兼容性，它依然处于可用状态。 如果文件路径不能被处理，则引发 @ref{30b,,OSError} 异常。



在 3.4 版更改: 引发 @ref{30b,,OSError} 而不是 @ref{203,,NotImplemented}。

@end deffn

@geindex set_data() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader set_data}@anchor{37ea}
@deffn {方法} set_data (path, data)

往一个文件路径写入指定字节的的可选的抽象方法。任何中间不存在的目录不会被自动创建。

由于路径是只读的，当写入的路径产生错误时（@ref{18a6,,errno.EACCES}/@ref{700,,PermissionError}），不会传播异常。


在 3.4 版更改: 当被调用时，不再引起 @ref{70e,,NotImplementedError} 异常。

@end deffn

@geindex get_code() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader get_code}@anchor{37eb}
@deffn {方法} get_code (fullname)

@ref{955,,InspectLoader.get_code()} 的具体实现。
@end deffn

@geindex exec_module() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader exec_module}@anchor{a2d}
@deffn {方法} exec_module (module)

@ref{6e5,,Loader.exec_module()} 的具体实现。


3.4 新版功能.

@end deffn

@geindex load_module() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader load_module}@anchor{a2b}
@deffn {方法} load_module (fullname)

Concrete implementation of @ref{6e4,,Loader.load_module()}.


3.4 版后已移除: 使用 @ref{a2d,,exec_module()} 来代替。

@end deffn

@geindex get_source() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader get_source}@anchor{a43}
@deffn {方法} get_source (fullname)

@ref{959,,InspectLoader.get_source()} 的具体实现。
@end deffn

@geindex is_package() (importlib.abc.SourceLoader 方法)
@anchor{library/importlib importlib abc SourceLoader is_package}@anchor{37ec}
@deffn {方法} is_package (fullname)

@ref{37e2,,InspectLoader.is_package()} 的具体实现。一个模块被确定为一个包的条件是：它的文件路径（由 @ref{37e4,,ExecutionLoader.get_filename()} 提供）当文件扩展名被移除时是一个命名为 @code{__init__} 的文件，@strong{并且} 这个模块名字本身不是以`@w{`}__init__`@w{`}结束。
@end deffn
@end deffn

@geindex Traversable (importlib.abc 中的类)
@anchor{library/importlib importlib abc Traversable}@anchor{fbf}
@deffn {类} importlib.abc.Traversable

拥有部分 pathlib.Path 方法的对象，适用于遍历目录和打开文件。


3.9 新版功能.


@geindex name() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable name}@anchor{37ed}
@deffn {方法} abstractmethod name ()

此对象不带任何父引用的基准名。
@end deffn

@geindex iterdir() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable iterdir}@anchor{37ee}
@deffn {方法} abstractmethod iterdir ()

产出自身内部的可遍历对象。
@end deffn

@geindex is_dir() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable is_dir}@anchor{37ef}
@deffn {方法} abstractmethod is_dir ()

如果自身是一个目录则返回 True。
@end deffn

@geindex is_file() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable is_file}@anchor{37f0}
@deffn {方法} abstractmethod is_file ()

如果自身是一个文件则返回 True。
@end deffn

@geindex joinpath() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable joinpath}@anchor{37f1}
@deffn {方法} abstractmethod joinpath (child)

返回自身中可遍历的子对象。
@end deffn

@geindex __truediv__() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable __truediv__}@anchor{37f2}
@deffn {方法} abstractmethod __truediv__ (child)

返回自身中可遍历的子对象。
@end deffn

@geindex open() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable open}@anchor{37f3}
@deffn {方法} abstractmethod open (mode='r', *args, **kwargs)

@emph{mode} 可以为 'r' 或 'rb' 即以文本或二进制模式打开。 返回一个适用于读取的句柄（与 @ref{1d82,,pathlib.Path.open} 样同）。

当以文本模式打开时，接受与 @ref{6f4,,io.TextIOWrapper} 所接受的相同的编码格式形参。
@end deffn

@geindex read_bytes() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable read_bytes}@anchor{37f4}
@deffn {方法} read_bytes ()

以字节串形式读取自身的内容。
@end deffn

@geindex read_text() (importlib.abc.Traversable 方法)
@anchor{library/importlib importlib abc Traversable read_text}@anchor{37f5}
@deffn {方法} read_text (encoding=None)

以文本形式读取自身的内容。
@end deffn

Note: In Python 3.11 and later, this class is found in @code{importlib.resources.abc}.
@end deffn

@geindex TraversableResources (importlib.abc 中的类)
@anchor{library/importlib importlib abc TraversableResources}@anchor{37f6}
@deffn {类} importlib.abc.TraversableResources

用作资源读取器的抽象基类，能够为 @code{files} 接口提供服务。其为ResourceReader 的子类，并具体实现了 ResourceReader 的抽象方法。因此，任何提供 TraversableReader 的加载器也提供 ResourceReader。


3.9 新版功能.


Note: In Python 3.11 and later, this class is found in @code{importlib.resources.abc}.
@end deffn

@node importlib resources -- 资源,importlib machinery —— 导入器和路径钩子函数。,importlib abc —— 关于导入的抽象基类,importlib --- import 的实现
@anchor{library/importlib importlib-resources-resources}@anchor{37f7}@anchor{library/importlib module-importlib resources}@anchor{9e}
@subsubsection @code{importlib.resources} -- 资源


@geindex importlib.resources (模块)

@strong{源码：} Lib/importlib/resources.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/resources.py}


__________________________________________________________________



3.7 新版功能.


这个模块使得Python的导入系统提供了访问*包*内的*资源*的功能。如果能够导入一个包，那么就能够访问那个包里面的资源。资源可以以二进制或文本模式方式被打开或读取。

资源非常类似于目录内部的文件，要牢记的是这仅仅是一个比喻。资源和包不是与文件系统上的物理文件和目录一样存在着。

@cartouche
@quotation 注解 
本模块提供了类似于 pkg_resources@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html}  Basic Resource Access@footnote{http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access} 的功能，但没有该包的性能开销。这样读取包中的资源就更为容易，语义也更稳定一致。

该模块有独立的向下移植版本， using importlib.resources@footnote{http://importlib-resources.readthedocs.io/en/latest/using.html}  和 migrating from pkg_resources to importlib.resources@footnote{http://importlib-resources.readthedocs.io/en/latest/migration.html}  提供了更多信息。
@end quotation
@end cartouche

加载器想要支持资源读取应该实现一个由 @ref{457,,importlib.abc.ResourceReader} 指定的`@w{`}get_resource_reader(fullname)`@w{`} 方法。

定义了以下类型。

@geindex Package() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources Package}@anchor{37f8}
@deffn {数据} importlib.resources.Package

@code{Package} 类型定义为 @code{Union[str, ModuleType]} 。这意味着只要函数说明接受 @code{Package} 的地方，就可以传入字符串或模块。模块对象必须拥有一个可解析的 @code{__spec__.submodule_search_locations}，不能是 @code{None}。
@end deffn

@geindex Resource() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources Resource}@anchor{37f9}
@deffn {数据} importlib.resources.Resource

此类型描述了传入本包各函数的资源名称。定义为 @code{Union[str, os.PathLike]}。
@end deffn

有以下函数可用：

@geindex files() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources files}@anchor{1b8}
@deffn {函数} importlib.resources.files (package)

Returns an @ref{fbf,,importlib.abc.Traversable} object
representing the resource container for the package (think directory)
and its resources (think files). A Traversable may contain other
containers (think subdirectories).

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。


3.9 新版功能.

@end deffn

@geindex as_file() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources as_file}@anchor{37fa}
@deffn {函数} importlib.resources.as_file (traversable)

Given a @ref{fbf,,importlib.abc.Traversable} object representing
a file, typically from @ref{1b8,,importlib.resources.files()}, return
a context manager for use in a @ref{7e4,,with} statement.
The context manager provides a @ref{336,,pathlib.Path} object.

退出上下文管理程序时，可以清理所有临时文件，比如从压缩文件中提取资源时创建的那些文件。

如果 Traversable 方法（@code{read_text} 等）不够用，需要文件系统中的实际文件时，请使用 @code{as_file}。


3.9 新版功能.

@end deffn

@geindex open_binary() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources open_binary}@anchor{37fb}
@deffn {函数} importlib.resources.open_binary (package, resource)

以二进制读方式打开 @emph{package} 内的 @emph{resource}。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。 @emph{resource} 是要在*package* 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不能为目录）。本函数将返回一个`@w{`}typing.BinaryIO`@w{`} 实例，即一个供读取的已打开的二进制 I/O 流。
@end deffn

@geindex open_text() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources open_text}@anchor{37fc}
@deffn {函数} importlib.resources.open_text (package, resource, encoding='utf-8', errors='strict')

以文本读方式打开 @emph{package} 内的 @emph{resource}。默认情况下，资源将以 UTF-8 格式打开以供读取。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。 @emph{resource} 是要在 @emph{package} 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不能是目录）。@emph{encoding} 和 @emph{errors} 的含义与内置 @ref{16f,,open()} 的一样。

本函数返回一个 @code{typing.TextIO} 实例，即一个打开的文本 I/O  流对象以供读取。
@end deffn

@geindex read_binary() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources read_binary}@anchor{1117}
@deffn {函数} importlib.resources.read_binary (package, resource)

读取并返回 @emph{package} 中的 @emph{resource} 内容，格式为 @code{bytes}。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。 @emph{resource} 是要在 @emph{package} 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不能是目录）。资源内容以 @ref{172,,bytes} 的形式返回。
@end deffn

@geindex read_text() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources read_text}@anchor{37fd}
@deffn {函数} importlib.resources.read_text (package, resource, encoding='utf-8', errors='strict')

读取并返回 @emph{package} 中 @emph{resource} 的内容，格式为 @code{str}。默认情况下，资源内容将以严格的 UTF-8 格式读取。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。 @emph{resource} 是要在 @emph{package} 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不能是目录）。@emph{encoding} 和 @emph{errors} 的含义与内置 @ref{16f,,open()} 的一样。资源内容将以 @ref{206,,str} 的形式返回。
@end deffn

@geindex path() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources path}@anchor{37fe}
@deffn {函数} importlib.resources.path (package, resource)

返回 @emph{resource} 实际的文件系统路径。本函数返回一个上下文管理器，以供 @ref{7e4,,with} 语句中使用。上下文管理器提供一个 @ref{336,,pathlib.Path} 对象。

退出上下文管理程序时，可以清理所有临时文件，比如从压缩文件中提取资源时创建的那些文件。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。 @emph{resource} 是要在 @emph{package} 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不能是目录）。
@end deffn

@geindex is_resource() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources is_resource}@anchor{37ff}
@deffn {函数} importlib.resources.is_resource (package, name)

如果包中存在名为 @emph{name} 的资源，则返回 @code{True}，否则返回 @code{False}。 请记住，目录 @emph{不是} 资源！ @emph{package} 为包名或一个符合 @code{Package} 要求的模块对象。
@end deffn

@geindex contents() (在 importlib.resources 模块中)
@anchor{library/importlib importlib resources contents}@anchor{11b8}
@deffn {函数} importlib.resources.contents (package)

返回一个用于遍历包内各命名项的可迭代对象。该可迭代对象将返回 @ref{206,,str} 资源（如文件）及非资源（如目录）。该迭代器不会递归进入子目录。

@emph{package} 是包名或符合 @code{Package} 要求的模块对象。
@end deffn

@node importlib machinery —— 导入器和路径钩子函数。,importlib util —— 导入器的工具程序代码,importlib resources -- 资源,importlib --- import 的实现
@anchor{library/importlib importlib-machinery-importers-and-path-hooks}@anchor{3800}@anchor{library/importlib module-importlib machinery}@anchor{9c}
@subsubsection @code{importlib.machinery} —— 导入器和路径钩子函数。


@geindex importlib.machinery (模块)

@strong{源代码：} Lib/importlib/machinery.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/machinery.py}


__________________________________________________________________


本模块包含多个对象，以帮助 @ref{cef,,import} 查找并加载模块。

@geindex SOURCE_SUFFIXES() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery SOURCE_SUFFIXES}@anchor{3801}
@deffn {属性} importlib.machinery.SOURCE_SUFFIXES

一个字符串列表，表示源模块的可识别的文件后缀。


3.3 新版功能.

@end deffn

@geindex DEBUG_BYTECODE_SUFFIXES() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery DEBUG_BYTECODE_SUFFIXES}@anchor{3802}
@deffn {属性} importlib.machinery.DEBUG_BYTECODE_SUFFIXES

一个字符串列表，表示未经优化字节码模块的文件后缀。


3.3 新版功能.



3.5 版后已移除: 改用 @ref{3803,,BYTECODE_SUFFIXES} 。

@end deffn

@geindex OPTIMIZED_BYTECODE_SUFFIXES() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery OPTIMIZED_BYTECODE_SUFFIXES}@anchor{3804}
@deffn {属性} importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES

一个字符串列表，表示已优化字节码模块的文件后缀。


3.3 新版功能.



3.5 版后已移除: 改用 @ref{3803,,BYTECODE_SUFFIXES} 。

@end deffn

@geindex BYTECODE_SUFFIXES() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery BYTECODE_SUFFIXES}@anchor{3803}
@deffn {属性} importlib.machinery.BYTECODE_SUFFIXES

一个字符串列表，表示字节码模块的可识别的文件后缀（包含前导的句点符号）。


3.3 新版功能.



在 3.5 版更改: 该值不再依赖于 @code{__debug__} 。

@end deffn

@geindex EXTENSION_SUFFIXES() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery EXTENSION_SUFFIXES}@anchor{3805}
@deffn {属性} importlib.machinery.EXTENSION_SUFFIXES

一个字符串列表，表示扩展模块的可识别的文件后缀。


3.3 新版功能.

@end deffn

@geindex all_suffixes() (在 importlib.machinery 模块中)
@anchor{library/importlib importlib machinery all_suffixes}@anchor{374d}
@deffn {函数} importlib.machinery.all_suffixes ()

返回字符串的组合列表，代表标准导入机制可识别模块的所有文件后缀。这是个助手函数，只需知道某个文件系统路径是否会指向模块，而不需要任何关于模块种类的细节（例如 @ref{6f3,,inspect.getmodulename()}）。


3.3 新版功能.

@end deffn

@geindex BuiltinImporter (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery BuiltinImporter}@anchor{658}
@deffn {类} importlib.machinery.BuiltinImporter

用于导入内置模块的 @ref{1626,,importer}。 所有已知的内置模块都已列入 @ref{13e7,,sys.builtin_module_names}。 此类实现了 @ref{a9c,,importlib.abc.MetaPathFinder} 和 @ref{954,,importlib.abc.InspectLoader} 抽象基类。

此类只定义类的方法，以减轻实例化的开销。


在 3.5 版更改: 作为 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} 的一部分，现在内置模块导入器实现了 @code{Loader.create_module()} 和 @code{Loader.exec_module()}。

@end deffn

@geindex FrozenImporter (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery FrozenImporter}@anchor{a41}
@deffn {类} importlib.machinery.FrozenImporter

用于已冻结模块的 @ref{1626,,importer}。 此类实现了 @ref{a9c,,importlib.abc.MetaPathFinder} 和 @ref{954,,importlib.abc.InspectLoader} 抽象基类。

此类只定义类的方法，以减轻实例化的开销。


在 3.4 版更改: 有了 @code{create_module()} 和 @code{exec_module()} 方法。

@end deffn

@geindex WindowsRegistryFinder (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery WindowsRegistryFinder}@anchor{6e6}
@deffn {类} importlib.machinery.WindowsRegistryFinder

@ref{1624,,Finder} 用于查找在 Windows 注册表中声明的模块。该类实现了基础的 @ref{a9c,,importlib.abc.MetaPathFinder} 。

此类只定义类的方法，以减轻实例化的开销。


3.3 新版功能.



3.6 版后已移除: 改用 @ref{eb,,site} 配置。未来版本的 Python 可能不会默认启用该查找器。

@end deffn

@geindex PathFinder (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery PathFinder}@anchor{a45}
@deffn {类} importlib.machinery.PathFinder

用于 @ref{262,,sys.path} 和包的 @code{__path__} 属性的  @ref{1624,,Finder} 。该类实现了基础的 @ref{a9c,,importlib.abc.MetaPathFinder}。

此类只定义类的方法，以减轻实例化的开销。

@geindex find_spec() (importlib.machinery.PathFinder 类方法)
@anchor{library/importlib importlib machinery PathFinder find_spec}@anchor{a27}
@deffn {方法} classmethod find_spec (fullname, path=None, target=None)

类方法试图在 @ref{262,,sys.path} 或 @emph{path} 上为 @emph{fullname} 指定的模块查找 @ref{36c1,,spec}。对于每个路径条目，都会查看  @ref{5a0,,sys.path_importer_cache} 。如果找到非 False 的对象，则将其用作 @ref{a9b,,path entry finder} 来查找要搜索的模块。如果在 @ref{5a0,,sys.path_importer_cache} 中没有找到条目，那会在 @ref{a46,,sys.path_hooks} 检索该路径条目的查找器，找到了则和查到的模块信息一起存入 @ref{5a0,,sys.path_importer_cache} 。如果查找器没有找到，则缓存中的查找器和模块信息都存为 @code{None} ，并返回。


3.4 新版功能.



在 3.5 版更改: 如果当前工作目录不再有效（用空字符串表示），则返回 @code{None}，但在 @ref{5a0,,sys.path_importer_cache} 中不会有缓存值。

@end deffn

@geindex find_module() (importlib.machinery.PathFinder 类方法)
@anchor{library/importlib importlib machinery PathFinder find_module}@anchor{a26}
@deffn {方法} classmethod find_module (fullname, path=None)

一个过时的 @ref{a27,,find_spec()} 封装对象。


3.4 版后已移除: 使用 @ref{a27,,find_spec()} 来代替。

@end deffn

@geindex invalidate_caches() (importlib.machinery.PathFinder 类方法)
@anchor{library/importlib importlib machinery PathFinder invalidate_caches}@anchor{59e}
@deffn {方法} classmethod invalidate_caches ()

为所有存于 @ref{5a0,,sys.path_importer_cache} 中的查找器，调用其  @ref{37de,,importlib.abc.PathEntryFinder.invalidate_caches()} 方法。 @ref{5a0,,sys.path_importer_cache} 中为 @code{None} 的条目将被删除。


在 3.7 版更改: @ref{5a0,,sys.path_importer_cache} 中的 @code{None} 条目将被删除。

@end deffn


在 3.4 版更改: 调用 @ref{a46,,sys.path_hooks} 中的对象，当前工作目录为 @code{'@w{'}} (即空字符串)。

@end deffn

@geindex FileFinder (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery FileFinder}@anchor{a9f}
@deffn {类} importlib.machinery.FileFinder (path, *loader_details)

@ref{a9d,,importlib.abc.PathEntryFinder} 的一个具体实现，它会缓存来自文件系统的结果。

参数 @emph{path} 是查找器负责搜索的目录。

@emph{loader_details} 参数是数量不定的二元组，每个元组包含加载器及其可识别的文件后缀列表。加载器应为可调用对象，可接受两个参数，即模块的名称和已找到文件的路径。

查找器将按需对目录内容进行缓存，通过对每个模块的检索进行状态统计，验证缓存是否过期。因为缓存的滞后性依赖于操作系统文件系统状态信息的粒度，所以搜索模块、新建文件、然后搜索新文件代表的模块，这会存在竞争状态。如果这些操作的频率太快，甚至小于状态统计的粒度，那么模块搜索将会失败。为了防止这种情况发生，在动态创建模块时，请确保调用 @ref{59f,,importlib.invalidate_caches()}。


3.3 新版功能.


@geindex path (importlib.machinery.FileFinder 属性)
@anchor{library/importlib importlib machinery FileFinder path}@anchor{3806}
@deffn {属性} path

查找器将要搜索的路径。
@end deffn

@geindex find_spec() (importlib.machinery.FileFinder 方法)
@anchor{library/importlib importlib machinery FileFinder find_spec}@anchor{8b8}
@deffn {方法} find_spec (fullname, target=None)

尝试在 @ref{3806,,path} 中找到处理 @emph{fullname} 的规格。


3.4 新版功能.

@end deffn

@geindex find_loader() (importlib.machinery.FileFinder 方法)
@anchor{library/importlib importlib machinery FileFinder find_loader}@anchor{3807}
@deffn {方法} find_loader (fullname)

试图在 @ref{3806,,path} 内找到处理 @emph{fullname} 的加载器。
@end deffn

@geindex invalidate_caches() (importlib.machinery.FileFinder 方法)
@anchor{library/importlib importlib machinery FileFinder invalidate_caches}@anchor{3808}
@deffn {方法} invalidate_caches ()

清理内部缓存。
@end deffn

@geindex path_hook() (importlib.machinery.FileFinder 类方法)
@anchor{library/importlib importlib machinery FileFinder path_hook}@anchor{3809}
@deffn {方法} classmethod path_hook (*loader_details)

一个类方法，返回供 @ref{a46,,sys.path_hooks} 使用的闭包。根据直接给出的路径参数和间接给出的 @emph{loader_details}，闭包会返回一个 @ref{a9f,,FileFinder} 的实例。

如果给闭包的参数不是已存在的目录，将会触发 @ref{16c,,ImportError}。
@end deffn
@end deffn

@geindex SourceFileLoader (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery SourceFileLoader}@anchor{aa1}
@deffn {类} importlib.machinery.SourceFileLoader (fullname, path)

@ref{37e9,,importlib.abc.SourceLoader} 的一个具体实现，该实现子类化了 @ref{aa0,,importlib.abc.FileLoader} 并提供了其他一些方法的具体实现。


3.3 新版功能.


@geindex name (importlib.machinery.SourceFileLoader 属性)
@anchor{library/importlib importlib machinery SourceFileLoader name}@anchor{380a}
@deffn {属性} name

该加载器将要处理的模块名称。
@end deffn

@geindex path (importlib.machinery.SourceFileLoader 属性)
@anchor{library/importlib importlib machinery SourceFileLoader path}@anchor{380b}
@deffn {属性} path

源文件的路径
@end deffn

@geindex is_package() (importlib.machinery.SourceFileLoader 方法)
@anchor{library/importlib importlib machinery SourceFileLoader is_package}@anchor{380c}
@deffn {方法} is_package (fullname)

如果 @ref{380b,,path} 看似包的路径，则返回 @code{True}。
@end deffn

@geindex path_stats() (importlib.machinery.SourceFileLoader 方法)
@anchor{library/importlib importlib machinery SourceFileLoader path_stats}@anchor{380d}
@deffn {方法} path_stats (path)

@ref{bcc,,importlib.abc.SourceLoader.path_stats()} 的具体代码实现。
@end deffn

@geindex set_data() (importlib.machinery.SourceFileLoader 方法)
@anchor{library/importlib importlib machinery SourceFileLoader set_data}@anchor{380e}
@deffn {方法} set_data (path, data)

@ref{37ea,,importlib.abc.SourceLoader.set_data()} 的具体代码实现。
@end deffn

@geindex load_module() (importlib.machinery.SourceFileLoader 方法)
@anchor{library/importlib importlib machinery SourceFileLoader load_module}@anchor{6e2}
@deffn {方法} load_module (name=None)

@ref{6e4,,importlib.abc.Loader.load_module()} 的具体代码实现，这里要加载的模块名是可选的。


3.6 版后已移除: 改用 @ref{6e5,,importlib.abc.Loader.exec_module()} 。

@end deffn
@end deffn

@geindex SourcelessFileLoader (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery SourcelessFileLoader}@anchor{aa2}
@deffn {类} importlib.machinery.SourcelessFileLoader (fullname, path)

@ref{aa0,,importlib.abc.FileLoader} 的具体代码实现，可导入字节码文件（也即源代码文件不存在）。

请注意，直接用字节码文件（而不是源代码文件），会让模块无法应用于所有的 Python 版本或字节码格式有所改动的新版本 Python。


3.3 新版功能.


@geindex name (importlib.machinery.SourcelessFileLoader 属性)
@anchor{library/importlib importlib machinery SourcelessFileLoader name}@anchor{380f}
@deffn {属性} name

加载器将要处理的模块名。
@end deffn

@geindex path (importlib.machinery.SourcelessFileLoader 属性)
@anchor{library/importlib importlib machinery SourcelessFileLoader path}@anchor{3810}
@deffn {属性} path

二进制码文件的路径。
@end deffn

@geindex is_package() (importlib.machinery.SourcelessFileLoader 方法)
@anchor{library/importlib importlib machinery SourcelessFileLoader is_package}@anchor{3811}
@deffn {方法} is_package (fullname)

根据 @ref{3810,,path} 确定该模块是否为包。
@end deffn

@geindex get_code() (importlib.machinery.SourcelessFileLoader 方法)
@anchor{library/importlib importlib machinery SourcelessFileLoader get_code}@anchor{3812}
@deffn {方法} get_code (fullname)

返回由 @ref{3810,,path} 创建的 @ref{380f,,name} 的代码对象。
@end deffn

@geindex get_source() (importlib.machinery.SourcelessFileLoader 方法)
@anchor{library/importlib importlib machinery SourcelessFileLoader get_source}@anchor{3813}
@deffn {方法} get_source (fullname)

因为用此加载器时字节码文件没有源码文件，所以返回 @code{None}。
@end deffn

@geindex load_module() (importlib.machinery.SourcelessFileLoader 方法)
@anchor{library/importlib importlib machinery SourcelessFileLoader load_module}@anchor{6e3}
@deffn {方法} load_module (name=None)
@end deffn

@ref{6e4,,importlib.abc.Loader.load_module()} 的具体代码实现，这里要加载的模块名是可选的。


3.6 版后已移除: 改用 @ref{6e5,,importlib.abc.Loader.exec_module()} 。

@end deffn

@geindex ExtensionFileLoader (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery ExtensionFileLoader}@anchor{659}
@deffn {类} importlib.machinery.ExtensionFileLoader (fullname, path)

@ref{37e3,,importlib.abc.ExecutionLoader} 的具体代码实现，用于扩展模块。

参数 @emph{fullname} 指定了加载器要支持的模块名。参数 @emph{path} 是指向扩展模块文件的路径。


3.3 新版功能.


@geindex name (importlib.machinery.ExtensionFileLoader 属性)
@anchor{library/importlib importlib machinery ExtensionFileLoader name}@anchor{3814}
@deffn {属性} name

装载器支持的模块名。
@end deffn

@geindex path (importlib.machinery.ExtensionFileLoader 属性)
@anchor{library/importlib importlib machinery ExtensionFileLoader path}@anchor{3815}
@deffn {属性} path

扩展模块的路径。
@end deffn

@geindex create_module() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader create_module}@anchor{3816}
@deffn {方法} create_module (spec)

根据 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} ，由给定规范创建模块对象。


3.5 新版功能.

@end deffn

@geindex exec_module() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader exec_module}@anchor{3817}
@deffn {方法} exec_module (module)

根据 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489}，初始化给定的模块对象。


3.5 新版功能.

@end deffn

@geindex is_package() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader is_package}@anchor{3818}
@deffn {方法} is_package (fullname)

根据 @ref{3805,,EXTENSION_SUFFIXES} ，如果文件路径指向某个包的 @code{__init__} 模块，则返回 @code{True}。
@end deffn

@geindex get_code() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_code}@anchor{3819}
@deffn {方法} get_code (fullname)

返回 @code{None}，因为扩展模块缺少代码对象。
@end deffn

@geindex get_source() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_source}@anchor{381a}
@deffn {方法} get_source (fullname)

返回 @code{None}，因为扩展模块没有源代码。
@end deffn

@geindex get_filename() (importlib.machinery.ExtensionFileLoader 方法)
@anchor{library/importlib importlib machinery ExtensionFileLoader get_filename}@anchor{95a}
@deffn {方法} get_filename (fullname)

返回 @ref{3815,,path}。


3.4 新版功能.

@end deffn
@end deffn

@geindex ModuleSpec (importlib.machinery 中的类)
@anchor{library/importlib importlib machinery ModuleSpec}@anchor{1630}
@deffn {类} importlib.machinery.ModuleSpec (name, loader, *, origin=None, loader_state=None, is_package=None)

关于模块导入系统相关状态的规范。通常这是作为模块的 @code{__spec__} 属性暴露出来。 在以下描述中，括号里的名字给出了模块对象中直接可用的属性。比如 @code{module.__spec__.origin == module.__file__}。 但是请注意，虽然 @emph{值} 通常是相等的，但它们可以不同，因为两个对象之间没有进行同步。因此 @code{__path__} 有可能在运行时做过更新，而这不会自动反映在 @code{__spec__.submodule_search_locations} 中。


3.4 新版功能.


@geindex name (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec name}@anchor{1b47}
@deffn {属性} name
@end deffn

（@code{__name__}）

一个字符串，表示模块的完全限定名称。

@geindex loader (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec loader}@anchor{1b45}
@deffn {属性} loader
@end deffn

（@code{__loader__}）

模块加载时应采用的 @ref{1625,,Loader} 。 @ref{1624,,Finders} 应确保设置本属性。

@geindex origin (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec origin}@anchor{381b}
@deffn {属性} origin
@end deffn

（@code{__file__}）

装载模块所在位置的名称，如内置模块为 “buildin”，从源代码加载的模块为文件名。通常应设置 “origin” ，但它可能为 @code{None} (默认值)，表示未指定 (如命名空间包)。

@geindex submodule_search_locations (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec submodule_search_locations}@anchor{381c}
@deffn {属性} submodule_search_locations
@end deffn

（@code{__path__}）

如果是包（否则为 ），子模块所在位置的字符串列表（否则为 @code{None}）。

@geindex loader_state (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec loader_state}@anchor{381d}
@deffn {属性} loader_state
@end deffn

依模块不同的额外数据的容器，以供加载过程中使用（或 @code{None}）。

@geindex cached (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec cached}@anchor{381e}
@deffn {属性} cached
@end deffn

（@code{__cached__}）

字符串，表示编译后的模块所在位置（或 @code{None}）。

@geindex parent (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec parent}@anchor{1b49}
@deffn {属性} parent
@end deffn

（@code{__package__}）

包的完全限定名称（只读），模块应作为其子模块进行加载（对于顶层模块则为空字符串）。对于包而言，其值与 @ref{de0,,__name__} 相同。

@geindex has_location (importlib.machinery.ModuleSpec 属性)
@anchor{library/importlib importlib machinery ModuleSpec has_location}@anchor{381f}
@deffn {属性} has_location
@end deffn

布尔值，表示模块的“origin”属性是否指向可加载的位置。
@end deffn

@node importlib util —— 导入器的工具程序代码,示例<44>,importlib machinery —— 导入器和路径钩子函数。,importlib --- import 的实现
@anchor{library/importlib importlib-util-utility-code-for-importers}@anchor{3820}@anchor{library/importlib module-importlib util}@anchor{9f}
@subsubsection @code{importlib.util} —— 导入器的工具程序代码


@geindex importlib.util (模块)

@strong{源代码：} Lib/importlib/util.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/util.py}


__________________________________________________________________


本模块包含了帮助构建 @ref{1626,,importer} 的多个对象。

@geindex MAGIC_NUMBER() (在 importlib.util 模块中)
@anchor{library/importlib importlib util MAGIC_NUMBER}@anchor{956}
@deffn {属性} importlib.util.MAGIC_NUMBER

代表字节码版本号的字节串。若要有助于加载/写入字节码，可考虑采用  @ref{37e9,,importlib.abc.SourceLoader}。


3.4 新版功能.

@end deffn

@geindex cache_from_source() (在 importlib.util 模块中)
@anchor{library/importlib importlib util cache_from_source}@anchor{65a}
@deffn {函数} importlib.util.cache_from_source (path, debug_override=None, *, optimization=None)

返回 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}/
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} 定义的，与源 @emph{path} 相关联的已编译字节码文件的路径。 例如，如果 @emph{path} 为 @code{/foo/bar/baz.py} 则 Python 3.2 中的返回值将是 @code{/foo/bar/__pycache__/baz.cpython-32.pyc}。 字符串 @code{cpython-32} 来自于当前的魔法标签 (参见 @code{get_tag()}; 如果 @code{sys.implementation.cache_tag} 未定义则将会引发 @ref{70e,,NotImplementedError})。

参数 @emph{optimization} 用于指定字节码文件的优化级别。空字符串代表没有优化，所以 @emph{optimization} 为  的 @code{/foo/bar/baz.py}，将会得到字节码路径为 @code{/foo/bar/__pycache__/baz.cpython-32.pyc}。@code{None} 会导致采用解释器的优化。任何其他字符串都会被采用，所以 @emph{optimization} 为 @code{'@w{'}} 的 @code{/foo/bar/baz.py} 会导致字节码路径为 @code{/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc}。@emph{optimization} 字符串只能是字母数字，否则会触发 @ref{16d,,ValueError}。

@emph{debug_override} 参数已废弃，可用于覆盖系统的 @code{__debug__} 值。@code{True} 值相当于将 @emph{optimization} 设为空字符串。@code{False} 则相当于*optimization* 设为 @code{1}。如果 @emph{debug_override} 和 @emph{optimization} 都不为 @code{None}，则会触发 @ref{1ff,,TypeError}。


3.4 新版功能.



在 3.5 版更改: 增加了 @emph{optimization} 参数，废弃了 @emph{debug_override} 参数。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex source_from_cache() (在 importlib.util 模块中)
@anchor{library/importlib importlib util source_from_cache}@anchor{65b}
@deffn {函数} importlib.util.source_from_cache (path)

根据指向一个 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 文件名的 @emph{path}，返回相关联的源代码文件路径。 举例来说，如果 @emph{path} 为 @code{/foo/bar/__pycache__/baz.cpython-32.pyc} 则返回的路径将是 @code{/foo/bar/baz.py}。 @emph{path} 不需要已存在，但如果它未遵循 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 或 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} 的格式，则会引发 @ref{16d,,ValueError}。 如果未定义 @code{sys.implementation.cache_tag}，则会引发 @ref{70e,,NotImplementedError}。


3.4 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex decode_source() (在 importlib.util 模块中)
@anchor{library/importlib importlib util decode_source}@anchor{958}
@deffn {函数} importlib.util.decode_source (source_bytes)

对代表源代码的字节串进行解码，并将其作为带有通用换行符的字符串返回（符合 @ref{959,,importlib.abc.InspectLoader.get_source()} 要求）。


3.4 新版功能.

@end deffn

@geindex resolve_name() (在 importlib.util 模块中)
@anchor{library/importlib importlib util resolve_name}@anchor{1b7}
@deffn {函数} importlib.util.resolve_name (name, package)

将模块的相对名称解析为绝对名称。

如果 @strong{name} 前面没有句点，那就简单地返回 @strong{name}。这样就能采用`@w{`}importlib.util.resolve_name('sys', __spec__.parent)`@w{`} 之类的写法，而无需检查是否需要 @strong{package} 参数。

如果 @strong{name} 是相对模块名称，但 @strong{package} 为 False 值（如 @code{None} 或空字符串），则会触发 @ref{16c,,ImportError}。 如果相对名称会离开所在的包（如从 @code{spam} 包中请求 @code{..bacon}），则还会触发 @ref{16c,,ImportError}。


3.3 新版功能.



在 3.9 版更改: 为了改善与 import 语句的一致性，对于无效的相对导入尝试会引发 @ref{16c,,ImportError} 而不是 @ref{16d,,ValueError}。

@end deffn

@geindex find_spec() (在 importlib.util 模块中)
@anchor{library/importlib importlib util find_spec}@anchor{a25}
@deffn {函数} importlib.util.find_spec (name, package=None)

查找模块的 @ref{36c1,,spec}，可选相对指定的 @strong{包} 名。如果该模块位于 @ref{109a,,sys.modules} 中，则会返回 @code{sys.modules[name].__spec__} （除非 spec为 @code{None} 或未作设置，这时会触发 @ref{16d,,ValueError})。否则将用  @ref{6e7,,sys.meta_path} 进行搜索。若找不到则返回 @code{None}。

如果 @strong{name} 为一个子模块（带有一个句点），则会自动导入父级模块。

@strong{name} 和 @strong{package} 的用法与 @code{import_module()} 相同。


3.4 新版功能.



在 3.7 版更改: 如果 @strong{package} 实际上不是一个包（即缺少 @ref{13f3,,__path__} 属性）则会引发 @ref{4a9,,ModuleNotFoundError} 而不是 @ref{4aa,,AttributeError}。

@end deffn

@geindex module_from_spec() (在 importlib.util 模块中)
@anchor{library/importlib importlib util module_from_spec}@anchor{7eb}
@deffn {函数} importlib.util.module_from_spec (spec)

基于 @strong{spec} 和 @ref{657,,spec.loader.create_module} 创建一个新模块。

如果 @ref{657,,spec.loader.create_module} 未返回 @code{None}，那么先前已存在的属性不会被重置。另外，如果 @ref{4aa,,AttributeError} 是在访问 @strong{spec} 或设置模块属性时触发的，则不会触发 。

本函数比 @ref{7ec,,types.ModuleType} 创建新模块要好，因为用到 @strong{spec} 模块设置了尽可能多的导入控制属性。


3.5 新版功能.

@end deffn

@geindex module_for_loader() (在 importlib.util 模块中)
@anchor{library/importlib importlib util module_for_loader}@anchor{a2f}
@deffn {函数} @@importlib.util.module_for_loader

@ref{6e4,,importlib.abc.Loader.load_module()} 的一个 @ref{174,,decorator}，用来选取合适的模块对象以供加载。被装饰方法的签名应带有两个位置参数（如：@code{load_module(self, module)}），其中第二个参数将是加载器用到的模块 @strong{对象}。请注意，由于假定有两个参数，所以装饰器对静态方法不起作用。

装饰的方法将接受要加载的模块的 @strong{name}，正如 @ref{1625,,loader} 一样。如果在 @ref{109a,,sys.modules} 中没有找到该模块，那么将构造一个新模块。不管模块来自哪里， @ref{a40,,__loader__} 设置为 @strong{self} ，并且 @ref{a3f,,__package__} 是根据 @ref{37e2,,importlib.abc.InspectLoader.is_package()} 的返回值设置的。这些属性会无条件进行设置以便支持重载。

如果被装饰的方法触发异常，并且已有模块加入 @ref{109a,,sys.modules} 中，那么该模块将被移除，以防 @ref{109a,,sys.modules} 中残留一个部分初始化的模块。如果该模块原先已在 @ref{109a,,sys.modules} 中，则会保留。


在 3.3 版更改: 有可能时自动设置 @ref{a40,,__loader__} 和 @ref{a3f,,__package__} 。



在 3.4 版更改: 无条件设置 @ref{de0,,__name__} 、 @ref{a40,,__loader__} 、 @ref{a3f,,__package__} 以支持再次加载。



3.4 版后已移除: 现在，导入机制直接执行本函数提供的所有功能。

@end deffn

@geindex set_loader() (在 importlib.util 模块中)
@anchor{library/importlib importlib util set_loader}@anchor{a30}
@deffn {函数} @@importlib.util.set_loader

一个 @ref{174,,decorator}，用于 @ref{6e4,,importlib.abc.Loader.load_module()} 在返回的模块上设置 @ref{a40,,__loader__} 属性。如果该属性已被设置，装饰器就什么都不做。这里假定被封装方法的第一个位置参数（即 @code{self}）就是 @ref{a40,,__loader__} 要设置的。


在 3.4 版更改: 如果设为 @code{None} ，则会去设置 @code{__loader__} ，就像该属性不存在一样。



3.4 版后已移除: 现在导入机制会自动用到本方法。

@end deffn

@geindex set_package() (在 importlib.util 模块中)
@anchor{library/importlib importlib util set_package}@anchor{a31}
@deffn {函数} @@importlib.util.set_package

一个用于 @ref{6e4,,importlib.abc.Loader.load_module()} 的 @ref{174,,decorator} ，以便设置返回模块的 @ref{a3f,,__package__} 属性。如果 @ref{a3f,,__package__} 已设置且不为 @code{None}，则不会做改动。


3.4 版后已移除: 现在导入机制会自动用到本方法。

@end deffn

@geindex spec_from_loader() (在 importlib.util 模块中)
@anchor{library/importlib importlib util spec_from_loader}@anchor{37dc}
@deffn {函数} importlib.util.spec_from_loader (name, loader, *, origin=None, is_package=None)

一个工厂函数，用于创建基于加载器的 @code{ModuleSpec} 实例。 形参的含义与 ModuleSpec 的相同。 该函数会利用当前可用的 @ref{1625,,loader} API，比如 @code{InspectLoader.is_package()}，以填充所有缺失的规格信息。


3.4 新版功能.

@end deffn

@geindex spec_from_file_location() (在 importlib.util 模块中)
@anchor{library/importlib importlib util spec_from_file_location}@anchor{65c}
@deffn {函数} importlib.util.spec_from_file_location (name, location, *, loader=None, submodule_search_locations=None)

一个工厂函数，用于创建基于文件路径的 @code{ModuleSpec} 实例。  缺失的信息将通过利用加载器 API 以及模块将基于文件的隐含条件在 spec 上进行填充。


3.4 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex source_hash() (在 importlib.util 模块中)
@anchor{library/importlib importlib util source_hash}@anchor{3821}
@deffn {函数} importlib.util.source_hash (source_bytes)

以字节串的形式返回 @emph{source_bytes} 的哈希值。基于哈希值的 @code{.pyc} 文件在头部嵌入了对应源文件内容的 @ref{3821,,source_hash()}。


3.7 新版功能.

@end deffn

@geindex LazyLoader (importlib.util 中的类)
@anchor{library/importlib importlib util LazyLoader}@anchor{656}
@deffn {类} importlib.util.LazyLoader (loader)

此类会延迟执行模块加载器，直至该模块有一个属性被访问到。

此类 @strong{只} 适用于定义了 @ref{6e5,,exec_module()} 的加载器，因为需要控制模块的类型。 同理，加载器的 @ref{657,,create_module()} 方法必须返回 @code{None} 或 @code{__class__}  属性可被改变且不用  @ref{3822,,slots} 的类型。 最后，用于替换 @ref{109a,,sys.modules} 内容的模块将无法工作，因为无法在整个解释器中安全地替换模块的引用；如果检测到这种替换，将触发 @ref{16d,,ValueError}。

@cartouche
@quotation 注解 
如果项目对启动时间要求很高，只要模块未被用过，此类能够最小化加载模块的开销。对于启动时间并不重要的项目来说，由于加载过程中产生的错误信息会被暂时搁置，因此强烈不建议使用此类。
@end quotation
@end cartouche


3.5 新版功能.



在 3.6 版更改: 开始调用 @ref{657,,create_module()}，移除 @ref{658,,importlib.machinery.BuiltinImporter} 和 @ref{659,,importlib.machinery.ExtensionFileLoader} 的兼容性警告。


@geindex factory() (importlib.util.LazyLoader 类方法)
@anchor{library/importlib importlib util LazyLoader factory}@anchor{3823}
@deffn {方法} classmethod factory (loader)

静态方法，返回创建延迟加载器的可调用对象。就是说用在加载器用类而不是实例传递的场合。

@example
suffixes = importlib.machinery.SOURCE_SUFFIXES
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
@end example
@end deffn
@end deffn

@node 示例<44>,,importlib util —— 导入器的工具程序代码,importlib --- import 的实现
@anchor{library/importlib examples}@anchor{3824}@anchor{library/importlib importlib-examples}@anchor{3825}
@subsubsection 示例


@menu
* 用编程方式导入:: 
* 检查某模块可否导入。:: 
* 直接导入源文件。:: 
* 设置导入器:: 
* importlib.import_module() 的近似实现: importlib import_module 的近似实现. 

@end menu

@node 用编程方式导入,检查某模块可否导入。,,示例<44>
@anchor{library/importlib importing-programmatically}@anchor{3826}
@subsubsection 用编程方式导入


要以编程方式导入一个模块，请使用 @ref{bef,,importlib.import_module()} ：

@example
import importlib

itertools = importlib.import_module('itertools')
@end example

@node 检查某模块可否导入。,直接导入源文件。,用编程方式导入,示例<44>
@anchor{library/importlib checking-if-a-module-can-be-imported}@anchor{3827}
@subsubsection 检查某模块可否导入。


若要查看某个模块是否可导入，但不需要实际执行导入，则应使用  @ref{a25,,importlib.util.find_spec()} ：

@example
import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"@{name!r@} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you chose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"@{name!r@} has been imported")
else:
    print(f"can't find the @{name!r@} module")
@end example

@node 直接导入源文件。,设置导入器,检查某模块可否导入。,示例<44>
@anchor{library/importlib importing-a-source-file-directly}@anchor{3828}
@subsubsection 直接导入源文件。


若要直接导入 Python 源码文件，请使用一下方案（仅 Python 3.5 以上版本有效）：

@example
import importlib.util
import sys

# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
@end example

@node 设置导入器,importlib import_module 的近似实现,直接导入源文件。,示例<44>
@anchor{library/importlib setting-up-an-importer}@anchor{3829}
@subsubsection 设置导入器


对于深度定制的导入，通常需要实现一个 @ref{1626,,importer}。 这意味着得同时管理 @ref{1624,,finder} 和 @ref{1625,,loader}。 根据不同的需求，有两种类型的查找器可供选择： @ref{a9a,,meta path finder} 或 @ref{a9b,,path entry finder}。 前者应位于 @ref{6e7,,sys.meta_path} 之上，而后者是用 @ref{163c,,path entry hook} 在 @ref{a46,,sys.path_hooks} 上创建但与 @ref{262,,sys.path} 一起工作，可能会创建一个查找器。以下例子将演示如何注册自己的导入器，以供导入使用（关于自建导入器请阅读本包内定义的类文档）：

@example
import importlib.machinery
import sys

# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
                  importlib.machinery.SOURCE_SUFFIXES)

# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)

# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
@end example

@node importlib import_module 的近似实现,,设置导入器,示例<44>
@anchor{library/importlib approximating-importlib-import-module}@anchor{382a}
@subsubsection @code{importlib.import_module()} 的近似实现


导入过程本身是用 Python 代码实现的，这样就能通过 importlib 将大多数导入机制暴露出来。以下代码近似实现了 @ref{bef,,importlib.import_module()} ，以帮助说明 importlib 暴露出来的各种 API （importlib 的用法适用于 Python 3.4 以上版本 ，其他代码适用于 Python 3.6 以上版本）。

@example
import importlib.util
import sys

def import_module(name, package=None):
    """An approximate implementation of import."""
    absolute_name = importlib.util.resolve_name(name, package)
    try:
        return sys.modules[absolute_name]
    except KeyError:
        pass

    path = None
    if '.' in absolute_name:
        parent_name, _, child_name = absolute_name.rpartition('.')
        parent_module = import_module(parent_name)
        path = parent_module.__spec__.submodule_search_locations
    for finder in sys.meta_path:
        spec = finder.find_spec(absolute_name, path)
        if spec is not None:
            break
    else:
        msg = f'No module named @{absolute_name!r@}'
        raise ModuleNotFoundError(msg, name=absolute_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[absolute_name] = module
    spec.loader.exec_module(module)
    if path is not None:
        setattr(parent_module, child_name, module)
    return module
@end example

@node 使用 importlib metadata,,importlib --- import 的实现,导入模块
@anchor{library/importlib metadata doc}@anchor{382b}@anchor{library/importlib metadata module-importlib metadata}@anchor{9d}@anchor{library/importlib metadata using}@anchor{382c}@anchor{library/importlib metadata using-importlib-metadata}@anchor{382d}
@subsection 使用 @code{importlib.metadata}


@geindex importlib.metadata (模块)

@strong{源代码：} Lib/importlib/metadata.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/importlib/metadata.py}


3.8 新版功能.


@cartouche
@quotation 注解 
这个功能是暂定的，可能会偏离标准库通常的版本语义。
@end quotation
@end cartouche

@code{importlib.metadata} 是一个提供对已安装包的元数据访问的库。这个库部分建立在 Python 的导入系统上，旨在取代 @code{pkg_resources} 的 entry point API@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points} 和 metadata API@footnote{https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api} 中的类似功能。 通过和 Python 3.7 或更高版本中的 @ref{9e,,importlib.resources} 一同使用（对于旧版本的 Python 则作为 importlib_resources@footnote{https://importlib-resources.readthedocs.io/en/latest/index.html} 向后移植），这可以消除对使用较旧且较为低效的 @code{pkg_resources} 包的需要。

此处所说的 “已安装的包” 通常指通过 pip@footnote{https://pypi.org/project/pip/} 等工具安装在 Python @code{site-packages} 目录下的第三方包。具体来说，它指的是一个具有可发现的 @code{dist-info} 或 @code{egg-info} 目录以及 
@geindex Python 提高建议; PEP 566
PEP 566@footnote{https://www.python.org/dev/peps/pep-0566} 或其更早的规范所定义的元数据的包。默认情况下，包的元数据可以存在于文件系统中或 @ref{262,,sys.path} 上的压缩文件中。 通过扩展机制，元数据几乎可以存在于任何地方。

@menu
* 概述: 概述<13>. 
* 可用 API:: 
* 分发:: 
* 扩展搜索算法:: 

@end menu

@node 概述<13>,可用 API,,使用 importlib metadata
@anchor{library/importlib metadata overview}@anchor{382e}
@subsubsection 概述


假设你想得到你用 @code{pip} 安装的一个包的版本字符串。 我们首先创建一个虚拟环境，并在其中安装一些东西：

@example
$ python3 -m venv example
$ source example/bin/activate
(example) $ pip install wheel
@end example

你可以通过运行以下代码得到`@w{`}wheel`@w{`}的版本字符串：

@example
(example) $ python
>>> from importlib.metadata import version  
>>> version('wheel')  
'0.32.3'
@end example

你也可以获得以组名为关键字的入口点集合，比如 @code{console_scripts} 和 @code{distutils.commands} 。每个组包含一个 @ref{382f,,入口点} 对象的序列。

你可以得到  @ref{3830,,分发的元数据}：

@example
>>> list(metadata('wheel'))  
['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist']
@end example

你也可以获得 @ref{3831,,分发的版本号}，列出它的 @ref{3832,,构成文件}，并且得到分发的 @ref{3833,,分发的依赖} 列表。

@node 可用 API,分发,概述<13>,使用 importlib metadata
@anchor{library/importlib metadata functional-api}@anchor{3834}
@subsubsection 可用 API


这个包通过其公共 API 提供了以下功能。

@menu
* 入口点:: 
* 分发的元数据:: 
* 分发的版本:: 
* 分发的文件:: 
* 分发的依赖:: 

@end menu

@node 入口点,分发的元数据,,可用 API
@anchor{library/importlib metadata entry-points}@anchor{382f}@anchor{library/importlib metadata id1}@anchor{3835}
@subsubsection 入口点


The @code{entry_points()} function returns a dictionary of all entry points,
keyed by group.  Entry points are represented by @code{EntryPoint} instances;
each @code{EntryPoint} has a @code{.name}, @code{.group}, and @code{.value} attributes and
a @code{.load()} method to resolve the value.  There are also @code{.module},
@code{.attr}, and @code{.extras} attributes for getting the components of the
@code{.value} attribute:

@example
>>> eps = entry_points()  
>>> list(eps)  
['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
>>> scripts = eps['console_scripts']  
>>> wheel = [ep for ep in scripts if ep.name == 'wheel'][0]  
>>> wheel  
EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
>>> wheel.module  
'wheel.cli'
>>> wheel.attr  
'main'
>>> wheel.extras  
[]
>>> main = wheel.load()  
>>> main  
<function main at 0x103528488>
@end example

@code{group} 和 @code{name} 是由软件包作者定义的任意值，通常客户端会希望解析某个特定组的所有入口点。阅读 the setuptools docs@footnote{https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins} 以了解更多关于入口点、其定义和用法的信息。

@node 分发的元数据,分发的版本,入口点,可用 API
@anchor{library/importlib metadata distribution-metadata}@anchor{3836}@anchor{library/importlib metadata metadata}@anchor{3830}
@subsubsection 分发的元数据


每个分发都包含某些元数据，你可以通过 @code{metadata()} 函数提取它们：

@example
>>> wheel_metadata = metadata('wheel')  
@end example

The keys of the returned data structure @footnote{@w{(1)} 
Technically, the returned distribution metadata object is an
@ref{645,,email.message.EmailMessage}
instance, but this is an implementation detail, and not part of the
stable API.  You should only use dictionary-like methods and syntax
to access the metadata contents.
} name the metadata keywords, and
their values are returned unparsed from the distribution metadata:

@example
>>> wheel_metadata['Requires-Python']  
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
@end example

@node 分发的版本,分发的文件,分发的元数据,可用 API
@anchor{library/importlib metadata distribution-versions}@anchor{3837}@anchor{library/importlib metadata version}@anchor{3831}
@subsubsection 分发的版本


@code{version()} 函数是以字符串形式获取分发的版本号的最快方式：

@example
>>> version('wheel')  
'0.32.3'
@end example

@node 分发的文件,分发的依赖,分发的版本,可用 API
@anchor{library/importlib metadata distribution-files}@anchor{3838}@anchor{library/importlib metadata files}@anchor{3832}
@subsubsection 分发的文件


你可以获得分发内包含的所有文件的集合。 @code{files()} 函数传入一个分发包的名字并返回所有这个分发安装的文件。每个返回的文件对象都是一个 @ref{236,,pathlib.PurePath} 的具有额外由元数据指定的 @code{dist}， @code{size} 和 @code{hash} 属性的子类 @code{PackagePath} 的实例。例如：

@example
>>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]  
>>> util  
PackagePath('wheel/util.py')
>>> util.size  
859
>>> util.dist  
<importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
>>> util.hash  
<FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>
@end example

当你获得了文件对象，你可以读取其内容：

@example
>>> print(util.read_text())  
import base64
import sys
...
def as_bytes(s):
    if isinstance(s, text_type):
        return s.encode('utf-8')
    return s
@end example

你也可以使用 @code{locate} 方法来获得文件的绝对路径：

@example
>>> util.locate()  
PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py')
@end example

当列出包含文件的元数据文件（RECORD 或 SOURCES.txt）不存在时， @code{files()} 函数将返回 @code{None} 。调用者可能会想要将对 @code{files()} 的调用封装在 always_iterable@footnote{https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable} 中，或者用其他方法来应对目标分发元数据存在性未知的情况。

@node 分发的依赖,,分发的文件,可用 API
@anchor{library/importlib metadata distribution-requirements}@anchor{3839}@anchor{library/importlib metadata requirements}@anchor{3833}
@subsubsection 分发的依赖


使用 @code{requires()} 函数来获得分发的依赖集合：

@example
>>> requires('wheel')  
["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]
@end example

@node 分发,扩展搜索算法,可用 API,使用 importlib metadata
@anchor{library/importlib metadata distributions}@anchor{383a}@anchor{library/importlib metadata id3}@anchor{383b}
@subsubsection 分发


以上的 API 是最常见而方便的用法，但是你也可以通过 @code{Distribution} 类获得以上所有信息。 @code{Distribution} 是一个代表 Python 包的元数据的抽象对象。你可以这样获取 @code{Distribution} 实例：

@example
>>> from importlib.metadata import distribution  
>>> dist = distribution('wheel')  
@end example

因此，可以通过 @code{Distribution} 实例获得版本号：

@example
>>> dist.version  
'0.32.3'
@end example

@code{Distribution} 实例具有所有可用的附加元数据：

@example
>>> dist.metadata['Requires-Python']  
'>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
>>> dist.metadata['License']  
'MIT'
@end example

此处并未描述全部可用的元数据集合。 请参见 
@geindex Python 提高建议; PEP 566
PEP 566@footnote{https://www.python.org/dev/peps/pep-0566} 以了解更多细节。

@node 扩展搜索算法,,分发,使用 importlib metadata
@anchor{library/importlib metadata extending-the-search-algorithm}@anchor{383c}
@subsubsection 扩展搜索算法


因为包的元数据无法通过搜索 @ref{262,,sys.path} 或通过包加载器获得，包的元数据是通过导入系统的 @ref{1622,,查找器} 找到的。 @code{importlib.metadata} 查询在 @ref{6e7,,sys.meta_path} 上的 @ref{a9a,,元数据查找器} 列表以获得分发包的元数据。

Python 默认的 @code{PathFinder} 包含一个调用 @code{importlib.metadata.MetadataPathFinder} 来查找从典型的文件系统路径加载发布的钩子。

抽象基类 @ref{a9c,,importlib.abc.MetaPathFinder} 定义了 Python 导入系统期望的查找器接口。 @code{importlib.metadata} 通过寻找 @ref{6e7,,sys.meta_path} 上查找器可选的 @code{find_distributions} 可调用的属性扩展这个协议，并将这个扩展接口作为 @code{DistributionFinder} 抽象基类提供，它定义了这个抽象方法：

@example
@@abc.abstractmethod
def find_distributions(context=DistributionFinder.Context()):
    """Return an iterable of all Distribution instances capable of
    loading the metadata for packages for the indicated `@w{`}context`@w{`}.
    """
@end example

@code{DistributionFinder.Context} 对象提供了指示搜索路径和匹配名称的属性 @code{.path} 和 @code{.name} ，也可能提供其他相关的上下文。

这在实践中意味着要支持在文件系统外的其他位置查找分发包的元数据，你需要子类化 @code{Distribution} 并实现抽象方法，之后从一个自定义查找器的 @code{find_distributions()} 方法返回这个派生的 @code{Distribution} 实例。

@subsubheading 备注


@node Python 语言服务,杂项服务,导入模块,Python 标准库
@anchor{library/language doc}@anchor{383d}@anchor{library/language language}@anchor{383e}@anchor{library/language python-language-services}@anchor{383f}
@section Python 语言服务


Python 提供了许多模块来帮助使用 Python 语言。 这些模块支持标记化、解析、语法分析、字节码反汇编以及各种其他工具。

这些模块包括：

@menu
* parser: parser --- 访问 Python 解析树. 访问 Python 解析树
* ast: ast --- 抽象语法树. 抽象语法树
* symtable ——访问编译器的符号表:: 
* symbol: symbol --- 与 Python 解析树一起使用的常量. 与 Python 解析树一起使用的常量
* token: token --- 与Python解析树一起使用的常量. 与Python解析树一起使用的常量
* keyword: keyword --- 检验Python关键字. 检验Python关键字
* tokenize: tokenize --- 对 Python 代码使用的标记解析器. 对 Python 代码使用的标记解析器
* tabnanny: tabnanny --- 模糊缩进检测. 模糊缩进检测
* pyclbr: pyclbr --- Python 模块浏览器支持. Python 模块浏览器支持
* py_compile: py_compile --- 编译 Python 源文件. 编译 Python 源文件
* compileall: compileall --- 字节编译 Python 库. 字节编译 Python 库
* dis: dis --- Python 字节码反汇编器. Python 字节码反汇编器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集

@end menu

@node parser --- 访问 Python 解析树,ast --- 抽象语法树,,Python 语言服务
@anchor{library/parser doc}@anchor{3840}@anchor{library/parser module-parser}@anchor{c7}@anchor{library/parser parser-access-python-parse-trees}@anchor{3841}
@subsection @code{parser} --- 访问 Python 解析树


@geindex parser (模块)

@c Copyright 1995 Virginia Polytechnic Institute and State University and Fred
@c L. Drake, Jr.  This copyright notice must be distributed on all copies, but
@c this document otherwise may be distributed as part of the Python
@c distribution.  No fee may be charged for this document in any representation,
@c either on paper or electronically.  This restriction does not affect other
@c elements in a distributed package in any way.

@geindex parsing; Python source code


__________________________________________________________________


The @ref{c7,,parser} module provides an interface to Python's internal parser and
byte-code compiler.  The primary purpose for this interface is to allow Python
code to edit the parse tree of a Python expression and create executable code
from this.  This is better than trying to parse and modify an arbitrary Python
code fragment as a string because parsing is performed in a manner identical to
the code forming the application.  It is also faster.

@cartouche
@quotation 警告 
parser 模块已被弃用并将在未来的 Python 版本中移除。 对于大多数用例你都可以使用 @ref{7,,ast} 模块来控制抽象语法树（AST）的生成和编译阶段。
@end quotation
@end cartouche

There are a few things to note about this module which are important to making
use of the data structures created.  This is not a tutorial on editing the parse
trees for Python code, but some examples of using the @ref{c7,,parser} module are
presented.

Most importantly, a good understanding of the Python grammar processed by the
internal parser is required.  For full information on the language syntax, refer
to @ref{1360,,Python 语言参考手册}.  The parser
itself is created from a grammar specification defined in the file
@code{Grammar/Grammar} in the standard Python distribution.  The parse trees
stored in the ST objects created by this module are the actual output from the
internal parser when created by the @ref{3842,,expr()} or @ref{3843,,suite()} functions,
described below.  The ST objects created by @ref{3844,,sequence2st()} faithfully
simulate those structures.  Be aware that the values of the sequences which are
considered "correct" will vary from one version of Python to another as the
formal grammar for the language is revised.  However, transporting code from one
Python version to another as source text will always allow correct parse trees
to be created in the target version, with the only restriction being that
migrating to an older version of the interpreter will not support more recent
language constructs.  The parse trees are not typically compatible from one
version to another, though source code has usually been forward-compatible within
a major release series.

Each element of the sequences returned by @ref{3845,,st2list()} or @ref{3846,,st2tuple()}
has a simple form.  Sequences representing non-terminal elements in the grammar
always have a length greater than one.  The first element is an integer which
identifies a production in the grammar.  These integers are given symbolic names
in the C header file @code{Include/graminit.h} and the Python module
@ref{fb,,symbol}.  Each additional element of the sequence represents a component
of the production as recognized in the input string: these are always sequences
which have the same form as the parent.  An important aspect of this structure
which should be noted is that keywords used to identify the parent node type,
such as the keyword @ref{eb3,,if} in an @code{if_stmt}, are included in the
node tree without any special treatment.  For example, the @code{if} keyword
is represented by the tuple @code{(1, 'if')}, where @code{1} is the numeric value
associated with all @code{NAME} tokens, including variable and function names
defined by the user.  In an alternate form returned when line number information
is requested, the same token might be represented as @code{(1, 'if', 12)}, where
the @code{12} represents the line number at which the terminal symbol was found.

Terminal elements are represented in much the same way, but without any child
elements and the addition of the source text which was identified.  The example
of the @ref{eb3,,if} keyword above is representative.  The various types of
terminal symbols are defined in the C header file @code{Include/token.h} and
the Python module @ref{119,,token}.

The ST objects are not required to support the functionality of this module,
but are provided for three purposes: to allow an application to amortize the
cost of processing complex parse trees, to provide a parse tree representation
which conserves memory space when compared to the Python list or tuple
representation, and to ease the creation of additional modules in C which
manipulate parse trees.  A simple "wrapper" class may be created in Python to
hide the use of ST objects.

The @ref{c7,,parser} module defines functions for a few distinct purposes.  The
most important purposes are to create ST objects and to convert ST objects to
other representations such as parse trees and compiled code objects, but there
are also functions which serve to query the type of parse tree represented by an
ST object.


@subsubheading 参见



@table @asis

@item 模块 @ref{fb,,symbol}

代表解析树内部节点的有用常量。

@item 模块 @ref{119,,token}

代表解析树叶子节点和测试节点值的函数的有用常量。
@end table


@menu
* 创建 ST 对象:: 
* 转换 ST 对象:: 
* Queries on ST Objects:: 
* 异常和错误处理:: 
* ST 对象:: 
* 示例; compile() 的模拟: 示例 compile 的模拟. 

@end menu

@node 创建 ST 对象,转换 ST 对象,,parser --- 访问 Python 解析树
@anchor{library/parser creating-st-objects}@anchor{3847}@anchor{library/parser creating-sts}@anchor{3848}
@subsubsection 创建 ST 对象


ST objects may be created from source code or from a parse tree. When creating
an ST object from source, different functions are used to create the @code{'eval'}
and @code{'exec'} forms.

@geindex expr() (在 parser 模块中)
@anchor{library/parser parser expr}@anchor{3842}
@deffn {函数} parser.expr (source)

The @ref{3842,,expr()} function parses the parameter @emph{source} as if it were an input
to @code{compile(source, 'file.py', 'eval')}.  If the parse succeeds, an ST object
is created to hold the internal parse tree representation, otherwise an
appropriate exception is raised.
@end deffn

@geindex suite() (在 parser 模块中)
@anchor{library/parser parser suite}@anchor{3843}
@deffn {函数} parser.suite (source)

The @ref{3843,,suite()} function parses the parameter @emph{source} as if it were an input
to @code{compile(source, 'file.py', 'exec')}.  If the parse succeeds, an ST object
is created to hold the internal parse tree representation, otherwise an
appropriate exception is raised.
@end deffn

@geindex sequence2st() (在 parser 模块中)
@anchor{library/parser parser sequence2st}@anchor{3844}
@deffn {函数} parser.sequence2st (sequence)

This function accepts a parse tree represented as a sequence and builds an
internal representation if possible.  If it can validate that the tree conforms
to the Python grammar and all nodes are valid node types in the host version of
Python, an ST object is created from the internal representation and returned
to the called.  If there is a problem creating the internal representation, or
if the tree cannot be validated, a @ref{3849,,ParserError} exception is raised.  An
ST object created this way should not be assumed to compile correctly; normal
exceptions raised by compilation may still be initiated when the ST object is
passed to @ref{384a,,compilest()}.  This may indicate problems not related to syntax
(such as a @ref{fb5,,MemoryError} exception), but may also be due to constructs such
as the result of parsing @code{del f(0)}, which escapes the Python parser but is
checked by the bytecode compiler.

Sequences representing terminal tokens may be represented as either two-element
lists of the form @code{(1, 'name')} or as three-element lists of the form @code{(1,
'name', 56)}.  If the third element is present, it is assumed to be a valid
line number.  The line number may be specified for any subset of the terminal
symbols in the input tree.
@end deffn

@geindex tuple2st() (在 parser 模块中)
@anchor{library/parser parser tuple2st}@anchor{384b}
@deffn {函数} parser.tuple2st (sequence)

This is the same function as @ref{3844,,sequence2st()}.  This entry point is
maintained for backward compatibility.
@end deffn

@node 转换 ST 对象,Queries on ST Objects,创建 ST 对象,parser --- 访问 Python 解析树
@anchor{library/parser converting-st-objects}@anchor{384c}@anchor{library/parser converting-sts}@anchor{384d}
@subsubsection 转换 ST 对象


ST objects, regardless of the input used to create them, may be converted to
parse trees represented as list- or tuple- trees, or may be compiled into
executable code objects.  Parse trees may be extracted with or without line
numbering information.

@geindex st2list() (在 parser 模块中)
@anchor{library/parser parser st2list}@anchor{3845}
@deffn {函数} parser.st2list (st, line_info=False, col_info=False)

This function accepts an ST object from the caller in @emph{st} and returns a
Python list representing the equivalent parse tree.  The resulting list
representation can be used for inspection or the creation of a new parse tree in
list form.  This function does not fail so long as memory is available to build
the list representation.  If the parse tree will only be used for inspection,
@ref{3846,,st2tuple()} should be used instead to reduce memory consumption and
fragmentation.  When the list representation is required, this function is
significantly faster than retrieving a tuple representation and converting that
to nested lists.

If @emph{line_info} is true, line number information will be included for all
terminal tokens as a third element of the list representing the token.  Note
that the line number provided specifies the line on which the token @emph{ends}.
This information is omitted if the flag is false or omitted.
@end deffn

@geindex st2tuple() (在 parser 模块中)
@anchor{library/parser parser st2tuple}@anchor{3846}
@deffn {函数} parser.st2tuple (st, line_info=False, col_info=False)

This function accepts an ST object from the caller in @emph{st} and returns a
Python tuple representing the equivalent parse tree.  Other than returning a
tuple instead of a list, this function is identical to @ref{3845,,st2list()}.

If @emph{line_info} is true, line number information will be included for all
terminal tokens as a third element of the list representing the token.  This
information is omitted if the flag is false or omitted.
@end deffn

@geindex compilest() (在 parser 模块中)
@anchor{library/parser parser compilest}@anchor{384a}
@deffn {函数} parser.compilest (st, filename='<syntax-tree>')

@geindex 內置函数; exec
@geindex 內置函数; eval

The Python byte compiler can be invoked on an ST object to produce code objects
which can be used as part of a call to the built-in @ref{d14,,exec()} or @ref{c6a,,eval()}
functions. This function provides the interface to the compiler, passing the
internal parse tree from @emph{st} to the parser, using the source file name
specified by the @emph{filename} parameter. The default value supplied for @emph{filename}
indicates that the source was an ST object.

Compiling an ST object may result in exceptions related to compilation; an
example would be a @ref{562,,SyntaxError} caused by the parse tree for @code{del f(0)}:
this statement is considered legal within the formal grammar for Python but is
not a legal language construct.  The @ref{562,,SyntaxError} raised for this
condition is actually generated by the Python byte-compiler normally, which is
why it can be raised at this point by the @ref{c7,,parser} module.  Most causes of
compilation failure can be diagnosed programmatically by inspection of the parse
tree.
@end deffn

@node Queries on ST Objects,异常和错误处理,转换 ST 对象,parser --- 访问 Python 解析树
@anchor{library/parser queries-on-st-objects}@anchor{384e}@anchor{library/parser querying-sts}@anchor{384f}
@subsubsection Queries on ST Objects


Two functions are provided which allow an application to determine if an ST was
created as an expression or a suite.  Neither of these functions can be used to
determine if an ST was created from source code via @ref{3842,,expr()} or
@ref{3843,,suite()} or from a parse tree via @ref{3844,,sequence2st()}.

@geindex isexpr() (在 parser 模块中)
@anchor{library/parser parser isexpr}@anchor{3850}
@deffn {函数} parser.isexpr (st)

@geindex 內置函数; compile

When @emph{st} represents an @code{'eval'} form, this function returns @code{True}, otherwise
it returns @code{False}.  This is useful, since code objects normally cannot be queried
for this information using existing built-in functions.  Note that the code
objects created by @ref{384a,,compilest()} cannot be queried like this either, and
are identical to those created by the built-in @ref{2ee,,compile()} function.
@end deffn

@geindex issuite() (在 parser 模块中)
@anchor{library/parser parser issuite}@anchor{3851}
@deffn {函数} parser.issuite (st)

This function mirrors @ref{3850,,isexpr()} in that it reports whether an ST object
represents an @code{'exec'} form, commonly known as a "suite."  It is not safe to
assume that this function is equivalent to @code{not isexpr(st)}, as additional
syntactic fragments may be supported in the future.
@end deffn

@node 异常和错误处理,ST 对象,Queries on ST Objects,parser --- 访问 Python 解析树
@anchor{library/parser exceptions-and-error-handling}@anchor{3852}@anchor{library/parser st-errors}@anchor{3853}
@subsubsection 异常和错误处理


The parser module defines a single exception, but may also pass other built-in
exceptions from other portions of the Python runtime environment.  See each
function for information about the exceptions it can raise.

@geindex ParserError
@anchor{library/parser parser ParserError}@anchor{3849}
@deffn {例外} parser.ParserError

Exception raised when a failure occurs within the parser module.  This is
generally produced for validation failures rather than the built-in
@ref{562,,SyntaxError} raised during normal parsing. The exception argument is
either a string describing the reason of the failure or a tuple containing a
sequence causing the failure from a parse tree passed to @ref{3844,,sequence2st()}
and an explanatory string.  Calls to @ref{3844,,sequence2st()} need to be able to
handle either type of exception, while calls to other functions in the module
will only need to be aware of the simple string values.
@end deffn

Note that the functions @ref{384a,,compilest()}, @ref{3842,,expr()}, and @ref{3843,,suite()} may
raise exceptions which are normally raised by the parsing and compilation
process.  These include the built in exceptions @ref{fb5,,MemoryError},
@ref{a4a,,OverflowError}, @ref{562,,SyntaxError}, and @ref{6fc,,SystemError}.  In these
cases, these exceptions carry all the meaning normally associated with them.
Refer to the descriptions of each function for detailed information.

@node ST 对象,示例 compile 的模拟,异常和错误处理,parser --- 访问 Python 解析树
@anchor{library/parser id1}@anchor{3854}@anchor{library/parser st-objects}@anchor{3855}
@subsubsection ST 对象


Ordered and equality comparisons are supported between ST objects. Pickling of
ST objects (using the @ref{ca,,pickle} module) is also supported.

@geindex STType() (在 parser 模块中)
@anchor{library/parser parser STType}@anchor{3856}
@deffn {数据} parser.STType

The type of the objects returned by @ref{3842,,expr()}, @ref{3843,,suite()} and
@ref{3844,,sequence2st()}.
@end deffn

ST 对象具有以下方法：

@geindex compile() (parser.ST 方法)
@anchor{library/parser parser ST compile}@anchor{3857}
@deffn {方法} ST.compile (filename='<syntax-tree>')

和 @code{compilest(st, filename)} 相同.
@end deffn

@geindex isexpr() (parser.ST 方法)
@anchor{library/parser parser ST isexpr}@anchor{3858}
@deffn {方法} ST.isexpr ()

和  @code{isexpr(st)} 相同。
@end deffn

@geindex issuite() (parser.ST 方法)
@anchor{library/parser parser ST issuite}@anchor{3859}
@deffn {方法} ST.issuite ()

和 @code{issuite(st)} 相同。
@end deffn

@geindex tolist() (parser.ST 方法)
@anchor{library/parser parser ST tolist}@anchor{385a}
@deffn {方法} ST.tolist (line_info=False, col_info=False)

和 @code{st2list(st, line_info, col_info)} 相同。
@end deffn

@geindex totuple() (parser.ST 方法)
@anchor{library/parser parser ST totuple}@anchor{385b}
@deffn {方法} ST.totuple (line_info=False, col_info=False)

和 @code{st2tuple(st, line_info, col_info)} 相同。
@end deffn

@node 示例 compile 的模拟,,ST 对象,parser --- 访问 Python 解析树
@anchor{library/parser example-emulation-of-compile}@anchor{385c}
@subsubsection 示例: @code{compile()} 的模拟


While many useful operations may take place between parsing and bytecode
generation, the simplest operation is to do nothing.  For this purpose, using
the @ref{c7,,parser} module to produce an intermediate data structure is equivalent
to the code

@example
>>> code = compile('a + 5', 'file.py', 'eval')
>>> a = 5
>>> eval(code)
10
@end example

The equivalent operation using the @ref{c7,,parser} module is somewhat longer, and
allows the intermediate internal parse tree to be retained as an ST object:

@example
>>> import parser
>>> st = parser.expr('a + 5')
>>> code = st.compile('file.py')
>>> a = 5
>>> eval(code)
10
@end example

An application which needs both ST and code objects can package this code into
readily available functions:

@example
import parser

def load_suite(source_string):
    st = parser.suite(source_string)
    return st, st.compile()

def load_expression(source_string):
    st = parser.expr(source_string)
    return st, st.compile()
@end example

@node ast --- 抽象语法树,symtable ——访问编译器的符号表,parser --- 访问 Python 解析树,Python 语言服务
@anchor{library/ast doc}@anchor{385d}@anchor{library/ast ast-abstract-syntax-trees}@anchor{385e}@anchor{library/ast module-ast}@anchor{7}
@subsection @code{ast} --- 抽象语法树


@geindex ast (模块)

@c import ast

@strong{源代码：} Lib/ast.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/ast.py}


__________________________________________________________________


@ref{7,,ast} 模块帮助 Python 程序处理 Python 语法的抽象语法树。抽象语法或许会随着 Python 的更新发布而改变；该模块能够帮助理解当前语法在编程层面的样貌。

抽象语法树可通过将 @ref{385f,,ast.PyCF_ONLY_AST} 作为旗标传递给 @ref{2ee,,compile()} 内置函数来生成，或是使用此模块中提供的 @ref{2dd,,parse()} 辅助函数。返回结果将是一个对象树，，其中的类都继承自 @ref{187,,ast.AST}。抽象语法树可被内置的 @ref{2ee,,compile()} 函数编译为一个 Python 代码对象。

@menu
* 抽象文法:: 
* 节点类:: 
* ast 中的辅助函数:: 
* 编译器旗标:: 
* 命令行用法: 命令行用法<2>. 

@end menu

@node 抽象文法,节点类,,ast --- 抽象语法树
@anchor{library/ast abstract-grammar}@anchor{3860}@anchor{library/ast id1}@anchor{3861}
@subsubsection 抽象文法


抽象文法目前定义如下

@example
-- ASDL's 4 builtin types are:
-- identifier, int, string, constant

module Python
@{
    mod = Module(stmt* body, type_ignore* type_ignores)
        | Interactive(stmt* body)
        | Expression(expr body)
        | FunctionType(expr* argtypes, expr returns)

    stmt = FunctionDef(identifier name, arguments args,
                       stmt* body, expr* decorator_list, expr? returns,
                       string? type_comment)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns,
                             string? type_comment)

          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list)
          | Return(expr? value)

          | Delete(expr* targets)
          | Assign(expr* targets, expr value, string? type_comment)
          | AugAssign(expr target, operator op, expr value)
          -- 'simple' indicates that we annotate simple name without parens
          | AnnAssign(expr target, expr annotation, expr? value, int simple)

          -- use 'orelse' because else is a keyword in target languages
          | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
          | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
          | While(expr test, stmt* body, stmt* orelse)
          | If(expr test, stmt* body, stmt* orelse)
          | With(withitem* items, stmt* body, string? type_comment)
          | AsyncWith(withitem* items, stmt* body, string? type_comment)

          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | Assert(expr test, expr? msg)

          | Import(alias* names)
          | ImportFrom(identifier? module, alias* names, int? level)

          | Global(identifier* names)
          | Nonlocal(identifier* names)
          | Expr(expr value)
          | Pass | Break | Continue

          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

          -- BoolOp() can use left & right?
    expr = BoolOp(boolop op, expr* values)
         | NamedExpr(expr target, expr value)
         | BinOp(expr left, operator op, expr right)
         | UnaryOp(unaryop op, expr operand)
         | Lambda(arguments args, expr body)
         | IfExp(expr test, expr body, expr orelse)
         | Dict(expr* keys, expr* values)
         | Set(expr* elts)
         | ListComp(expr elt, comprehension* generators)
         | SetComp(expr elt, comprehension* generators)
         | DictComp(expr key, expr value, comprehension* generators)
         | GeneratorExp(expr elt, comprehension* generators)
         -- the grammar constrains where yield expressions can occur
         | Await(expr value)
         | Yield(expr? value)
         | YieldFrom(expr value)
         -- need sequences for compare to distinguish between
         -- x < 4 < 3 and (x < 4) < 3
         | Compare(expr left, cmpop* ops, expr* comparators)
         | Call(expr func, expr* args, keyword* keywords)
         | FormattedValue(expr value, int? conversion, expr? format_spec)
         | JoinedStr(expr* values)
         | Constant(constant value, string? kind)

         -- the following expression can appear in assignment context
         | Attribute(expr value, identifier attr, expr_context ctx)
         | Subscript(expr value, expr slice, expr_context ctx)
         | Starred(expr value, expr_context ctx)
         | Name(identifier id, expr_context ctx)
         | List(expr* elts, expr_context ctx)
         | Tuple(expr* elts, expr_context ctx)

         -- can appear only in Subscript
         | Slice(expr? lower, expr? upper, expr? step)

          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    expr_context = Load | Store | Del

    boolop = And | Or

    operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
                 | RShift | BitOr | BitXor | BitAnd | FloorDiv

    unaryop = Invert | Not | UAdd | USub

    cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

    comprehension = (expr target, expr iter, expr* ifs, int is_async)

    excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                    attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
                 expr* kw_defaults, arg? kwarg, expr* defaults)

    arg = (identifier arg, expr? annotation, string? type_comment)
           attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    -- keyword arguments supplied to call (NULL identifier for **kwargs)
    keyword = (identifier? arg, expr value)
               attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    -- import name with optional 'as' alias.
    alias = (identifier name, identifier? asname)

    withitem = (expr context_expr, expr? optional_vars)

    type_ignore = TypeIgnore(int lineno, string tag)
@}
@end example

@node 节点类,ast 中的辅助函数,抽象文法,ast --- 抽象语法树
@anchor{library/ast node-classes}@anchor{3862}
@subsubsection 节点类


@geindex AST (ast 中的类)
@anchor{library/ast ast AST}@anchor{187}
@deffn {类} ast.AST

这是所有 AST 节点类的基类。实际上，这些节点类派生自 @code{Parser/Python.asdl} 文件，其中定义的语法树示例 @ref{3860,,如下}。它们在 C 语言模块 @code{_ast} 中定义，并被导出至 @ref{7,,ast} 模块。

抽象语法定义的每个左侧符号(比方说，  @code{ast.stmt} 或者 @code{ast.expr})定义了一个类。另外，在抽象语法定义的右侧，对每一个构造器也定义了一个类；这些类继承自树左侧的类。比如，@ref{111b,,ast.BinOp} 继承自 @code{ast.expr}。对于多分支产生式(也就是"和规则")，树右侧的类是抽象的；只有特定构造器结点的实例能被构造。

@geindex ? (question mark); in AST grammar

@geindex * (asterisk); in AST grammar

@geindex _fields (ast.AST 属性)
@anchor{library/ast ast AST _fields}@anchor{3863}
@deffn {属性} _fields

每个具体类都有个属性 @ref{3863,,_fields}, 用来给出所有子节点的名字。

每个具体类的实例对它每个子节点都有一个属性，对应类型如文法中所定义。比如，@ref{111b,,ast.BinOp} 的实例有个属性 @code{left}，类型是 @code{ast.expr}.

如果这些属性在文法中标记为可选（使用问号），对应值可能会是 @code{None}。如果这些属性有零或多个（用星号标记），对应值会用Python的列表来表示。所有可能的属性必须在用 @ref{2ee,,compile()} 编译得到AST时给出，且是有效的值。
@end deffn

@geindex lineno (ast.AST 属性)
@geindex col_offset (ast.AST 属性)
@geindex end_lineno (ast.AST 属性)
@geindex end_col_offset (ast.AST 属性)
@anchor{library/ast ast AST lineno}@anchor{3864}
@deffn {属性} lineno
@anchor{library/ast ast AST col_offset}@anchor{3865}
@deffnx {属性} col_offset
@anchor{library/ast ast AST end_lineno}@anchor{3866}
@deffnx {属性} end_lineno
@anchor{library/ast ast AST end_col_offset}@anchor{3867}
@deffnx {属性} end_col_offset

Instances of @code{ast.expr} and @code{ast.stmt} subclasses have
@ref{3864,,lineno}, @ref{3865,,col_offset}, @ref{3866,,end_lineno}, and
@ref{3867,,end_col_offset} attributes.  The @ref{3864,,lineno} and
@ref{3866,,end_lineno} are the first and last line numbers of the source
text span (1-indexed so the first line is line 1), and the
@ref{3865,,col_offset} and @ref{3867,,end_col_offset} are the corresponding
UTF-8 byte offsets of the first and last tokens that generated the node.
The UTF-8 offset is recorded because the parser uses UTF-8 internally.

注意编译器不需要结束位置，所以结束位置是可选的。结束偏移在最后一个符号*之后*，例如你可以通过 @code{source_line[node.col_offset : node.end_col_offset]} 获得一个单行表达式节点的源码片段。
@end deffn

一个类的构造器 @code{ast.T} 像下面这样parse它的参数。


@itemize *

@item 
如果有位置参数，它们必须和 @code{T._fields} 中的元素一样多；他们会像这些名字的属性一样被赋值。

@item 
如果有关键字参数，它们必须被设为和给定值同名的属性。
@end itemize

比方说，要创建和填充节点 @ref{3868,,ast.UnaryOp}，你得用

@example
node = ast.UnaryOp()
node.op = ast.USub()
node.operand = ast.Constant()
node.operand.value = 5
node.operand.lineno = 0
node.operand.col_offset = 0
node.lineno = 0
node.col_offset = 0
@end example

或者更紧凑点

@example
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                   lineno=0, col_offset=0)
@end example
@end deffn


在 3.8 版更改: 类 @ref{3ae,,ast.Constant} 现在用于所有常量。



在 3.9 版更改: 简单索引由它们的值表示，扩展切片表示为元组。



3.8 版后已移除: 旧的类 @code{ast.Num},、@code{ast.Str}、 @code{ast.Bytes}、@code{ast.NameConstant} 和 @code{ast.Ellipsis} 仍然有效，但是它们会在未来的 Python 版本中被移除。同时，实例化它们会返回一个不同类的实例。



3.9 版后已移除: 旧的类 @code{ast.Index} 和 @code{ast.ExtSlice} 仍然有效，但是它们会在未来的 Python 版本中被移除。同时，实例化它们会返回一个不同类的实例。


@cartouche
@quotation 注解 
在此显示的特定节点类的描述最初是改编自杰出的 Green Tree Snakes@footnote{https://greentreesnakes.readthedocs.io/en/latest/} 项目及其所有贡献者。
@end quotation
@end cartouche

@menu
* 字面值: 字面值<3>. 
* 变量:: 
* 表达式: 表达式<2>. 
* 语句:: 
* 控制流:: 
* 函数与类定义:: 
* async 与 await:: 

@end menu

@node 字面值<3>,变量,,节点类
@anchor{library/ast literals}@anchor{3869}
@subsubsection 字面值


@geindex Constant (ast 中的类)
@anchor{library/ast ast Constant}@anchor{3ae}
@deffn {类} ast.Constant (value)

一个常量。 @code{Constant} 字面值的 @code{value} 属性即为其代表的 Python 对象。它可以代表简单的数字，字符串或者 @code{None} 对象，但是也可以代表所有元素都是常量的不可变容器，例如元组（tuple）或冻结集合（frozenset）。

@example
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
@end example
@end deffn

@geindex FormattedValue (ast 中的类)
@anchor{library/ast ast FormattedValue}@anchor{386a}
@deffn {类} ast.FormattedValue (value, conversion, format_spec)

节点是以一个 f-字符串形式的格式化字段来代表的。 如果该字符串只包含单个格式化字段而没有任何其他内容则节点可以被隔离，否则它将在 @ref{386b,,JoinedStr} 中出现。


@itemize *

@item 
@code{value} 为任意的表达式节点（如一个字面值、变量或函数调用）。

@item 
@code{conversion} 是一个整数:


@itemize *

@item 
-1: 无格式化

@item 
115: @code{!s} 字符串格式化

@item 
114: @code{!r} repr 格式化

@item 
97: @code{!a} ascii 格式化
@end itemize

@item 
@code{format_spec} 是一个代表值的格式化的 @ref{386b,,JoinedStr} 节点，或者如果未指定格式则为 @code{None}。 @code{conversion} 和 @code{format_spec} 可以被同时设置。
@end itemize
@end deffn

@geindex JoinedStr (ast 中的类)
@anchor{library/ast ast JoinedStr}@anchor{386b}
@deffn {类} ast.JoinedStr (values)

一个 f-字符串，由一系列 @ref{386a,,FormattedValue} 和 @ref{3ae,,Constant} 节点组成。

@example
>>> print(ast.dump(ast.parse('f"sin(@{a@}) is @{sin(a):.3@}"', mode='eval'), indent=4))
Expression(
    body=JoinedStr(
        values=[
            Constant(value='sin('),
            FormattedValue(
                value=Name(id='a', ctx=Load()),
                conversion=-1),
            Constant(value=') is '),
            FormattedValue(
                value=Call(
                    func=Name(id='sin', ctx=Load()),
                    args=[
                        Name(id='a', ctx=Load())],
                    keywords=[]),
                conversion=-1,
                format_spec=JoinedStr(
                    values=[
                        Constant(value='.3')]))]))
@end example
@end deffn

@geindex List (ast 中的类)
@geindex Tuple (ast 中的类)
@anchor{library/ast ast List}@anchor{386c}
@deffn {类} ast.List (elts, ctx)
@anchor{library/ast ast Tuple}@anchor{386d}
@deffnx {类} ast.Tuple (elts, ctx)

一个列表或元组。 @code{elts} 保存一个代表元素的节点的列表。 @code{ctx} 在容器为赋值的目标时 (如 @code{(x,y)=something}) 是 @ref{386e,,Store}，否则是 @ref{386f,,Load}。

@example
>>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
Expression(
    body=List(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
>>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
Expression(
    body=Tuple(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
@end example
@end deffn

@geindex Set (ast 中的类)
@anchor{library/ast ast Set}@anchor{3870}
@deffn {类} ast.Set (elts)

一个集合。 @code{elts} 保存一个代表集合的元组的节点的列表。

@example
>>> print(ast.dump(ast.parse('@{1, 2, 3@}', mode='eval'), indent=4))
Expression(
    body=Set(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)]))
@end example
@end deffn

@geindex Dict (ast 中的类)
@anchor{library/ast ast Dict}@anchor{1089}
@deffn {类} ast.Dict (keys, values)

一个字典。 @code{keys} 和 @code{values} 保存分别代表键和值的节点的列表，按照匹配的顺序（即当调用 @code{dictionary.keys()} 和 @code{dictionary.values()} 时将返回的结果）。

当使用字典字面值进行字典解包操作时要扩展的表达式放入 @code{values} 列表，并将 @code{None} 放入 @code{keys} 的对应位置。

@example
>>> print(ast.dump(ast.parse('@{"a":1, **d@}', mode='eval'), indent=4))
Expression(
    body=Dict(
        keys=[
            Constant(value='a'),
            None],
        values=[
            Constant(value=1),
            Name(id='d', ctx=Load())]))
@end example
@end deffn

@node 变量,表达式<2>,字面值<3>,节点类
@anchor{library/ast variables}@anchor{3871}
@subsubsection 变量


@geindex Name (ast 中的类)
@anchor{library/ast ast Name}@anchor{1075}
@deffn {类} ast.Name (id, ctx)

一个变量名。 @code{id} 将名称保存为字符串，而 @code{ctx} 为下列类型之一。
@end deffn

@geindex Load (ast 中的类)
@geindex Store (ast 中的类)
@geindex Del (ast 中的类)
@anchor{library/ast ast Load}@anchor{386f}
@deffn {类} ast.Load
@anchor{library/ast ast Store}@anchor{386e}
@deffnx {类} ast.Store
@anchor{library/ast ast Del}@anchor{3872}
@deffnx {类} ast.Del

变量引用可被用来载入一个变量的值，为其赋一个新值，或是将其删除。 变量引用会给出一个上下文来区分这几种情况。

@example
>>> print(ast.dump(ast.parse('a'), indent=4))
Module(
    body=[
        Expr(
            value=Name(id='a', ctx=Load()))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('del a'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='a', ctx=Del())])],
    type_ignores=[])
@end example
@end deffn

@geindex Starred (ast 中的类)
@anchor{library/ast ast Starred}@anchor{3873}
@deffn {类} ast.Starred (value, ctx)

一个 @code{*var} 变量引用。 @code{value} 保存变量，通常为一个 @ref{1075,,Name} 节点。 此类型必须在构建 @ref{3874,,Call} 节点并传入 @code{*args} 时被使用。

@example
>>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Starred(
                            value=Name(id='b', ctx=Store()),
                            ctx=Store())],
                    ctx=Store())],
            value=Name(id='it', ctx=Load()))],
    type_ignores=[])
@end example
@end deffn

@node 表达式<2>,语句,变量,节点类
@anchor{library/ast expressions}@anchor{3875}
@subsubsection 表达式


@geindex Expr (ast 中的类)
@anchor{library/ast ast Expr}@anchor{3876}
@deffn {类} ast.Expr (value)

当一个表达式，例如函数调用，本身作为一个语句出现并且其返回值未被使用或存储时，它会被包装在此容器中。 @code{value} 保存本节中的其他节点之一，一个 @ref{3ae,,Constant}, @ref{1075,,Name}, @ref{3877,,Lambda}, @ref{3878,,Yield} 或者 @ref{3879,,YieldFrom} 节点。

@example
>>> print(ast.dump(ast.parse('-a'), indent=4))
Module(
    body=[
        Expr(
            value=UnaryOp(
                op=USub(),
                operand=Name(id='a', ctx=Load())))],
    type_ignores=[])
@end example
@end deffn

@geindex UnaryOp (ast 中的类)
@anchor{library/ast ast UnaryOp}@anchor{3868}
@deffn {类} ast.UnaryOp (op, operand)

一个单目运算。 @code{op} 是运算符，而 @code{operand} 是任意表达式节点。
@end deffn

@geindex UAdd (ast 中的类)
@geindex USub (ast 中的类)
@geindex Not (ast 中的类)
@geindex Invert (ast 中的类)
@anchor{library/ast ast UAdd}@anchor{387a}
@deffn {类} ast.UAdd
@anchor{library/ast ast USub}@anchor{387b}
@deffnx {类} ast.USub
@anchor{library/ast ast Not}@anchor{387c}
@deffnx {类} ast.Not
@anchor{library/ast ast Invert}@anchor{387d}
@deffnx {类} ast.Invert

单目运算符对应的形符。 @ref{387c,,Not} 是 @code{not} 关键字，@ref{387d,,Invert} 是 @code{~} 运算符。

@example
>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
    body=UnaryOp(
        op=Not(),
        operand=Name(id='x', ctx=Load())))
@end example
@end deffn

@geindex BinOp (ast 中的类)
@anchor{library/ast ast BinOp}@anchor{111b}
@deffn {类} ast.BinOp (left, op, right)

一个双目运算（如相加或相减）。 @code{op} 是运算符，而 @code{left} 和 @code{right} 是任意表达式节点。

@example
>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
    body=BinOp(
        left=Name(id='x', ctx=Load()),
        op=Add(),
        right=Name(id='y', ctx=Load())))
@end example
@end deffn

@geindex Add (ast 中的类)
@geindex Sub (ast 中的类)
@geindex Mult (ast 中的类)
@geindex Div (ast 中的类)
@geindex FloorDiv (ast 中的类)
@geindex Mod (ast 中的类)
@geindex Pow (ast 中的类)
@geindex LShift (ast 中的类)
@geindex RShift (ast 中的类)
@geindex BitOr (ast 中的类)
@geindex BitXor (ast 中的类)
@geindex BitAnd (ast 中的类)
@geindex MatMult (ast 中的类)
@anchor{library/ast ast Add}@anchor{387e}
@deffn {类} ast.Add
@anchor{library/ast ast Sub}@anchor{387f}
@deffnx {类} ast.Sub
@anchor{library/ast ast Mult}@anchor{3880}
@deffnx {类} ast.Mult
@anchor{library/ast ast Div}@anchor{3881}
@deffnx {类} ast.Div
@anchor{library/ast ast FloorDiv}@anchor{3882}
@deffnx {类} ast.FloorDiv
@anchor{library/ast ast Mod}@anchor{3883}
@deffnx {类} ast.Mod
@anchor{library/ast ast Pow}@anchor{3884}
@deffnx {类} ast.Pow
@anchor{library/ast ast LShift}@anchor{3885}
@deffnx {类} ast.LShift
@anchor{library/ast ast RShift}@anchor{3886}
@deffnx {类} ast.RShift
@anchor{library/ast ast BitOr}@anchor{3887}
@deffnx {类} ast.BitOr
@anchor{library/ast ast BitXor}@anchor{3888}
@deffnx {类} ast.BitXor
@anchor{library/ast ast BitAnd}@anchor{3889}
@deffnx {类} ast.BitAnd
@anchor{library/ast ast MatMult}@anchor{388a}
@deffnx {类} ast.MatMult

双目运算符对应的形符。
@end deffn

@geindex BoolOp (ast 中的类)
@anchor{library/ast ast BoolOp}@anchor{388b}
@deffn {类} ast.BoolOp (op, values)

一个布尔运算，'or' 或者 'and'。 @code{op} 是 @ref{388c,,Or} 或者 @ref{388d,,And}。 @code{values} 是参与运算的值。 具有相同运算符的连续运算，如 @code{a or b or c}，会被折叠为具有多个值的单个节点。

这不包括 @code{not}，它属于 @ref{3868,,UnaryOp}。

@example
>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
Expression(
    body=BoolOp(
        op=Or(),
        values=[
            Name(id='x', ctx=Load()),
            Name(id='y', ctx=Load())]))
@end example
@end deffn

@geindex And (ast 中的类)
@geindex Or (ast 中的类)
@anchor{library/ast ast And}@anchor{388d}
@deffn {类} ast.And
@anchor{library/ast ast Or}@anchor{388c}
@deffnx {类} ast.Or

布尔运算符对应的形符。
@end deffn

@geindex Compare (ast 中的类)
@anchor{library/ast ast Compare}@anchor{388e}
@deffn {类} ast.Compare (left, ops, comparators)

两个或更多值之间的比较运算。 @code{left} 是参加比较的第一个值，@code{ops} 是由运算符组成的列表，而 @code{comparators} 是由参加比较的第一个元素之后的值组成的列表。

@example
>>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))
Expression(
    body=Compare(
        left=Constant(value=1),
        ops=[
            LtE(),
            Lt()],
        comparators=[
            Name(id='a', ctx=Load()),
            Constant(value=10)]))
@end example
@end deffn

@geindex Eq (ast 中的类)
@geindex NotEq (ast 中的类)
@geindex Lt (ast 中的类)
@geindex LtE (ast 中的类)
@geindex Gt (ast 中的类)
@geindex GtE (ast 中的类)
@geindex Is (ast 中的类)
@geindex IsNot (ast 中的类)
@geindex In (ast 中的类)
@geindex NotIn (ast 中的类)
@anchor{library/ast ast Eq}@anchor{388f}
@deffn {类} ast.Eq
@anchor{library/ast ast NotEq}@anchor{3890}
@deffnx {类} ast.NotEq
@anchor{library/ast ast Lt}@anchor{3891}
@deffnx {类} ast.Lt
@anchor{library/ast ast LtE}@anchor{3892}
@deffnx {类} ast.LtE
@anchor{library/ast ast Gt}@anchor{3893}
@deffnx {类} ast.Gt
@anchor{library/ast ast GtE}@anchor{3894}
@deffnx {类} ast.GtE
@anchor{library/ast ast Is}@anchor{3895}
@deffnx {类} ast.Is
@anchor{library/ast ast IsNot}@anchor{3896}
@deffnx {类} ast.IsNot
@anchor{library/ast ast In}@anchor{3897}
@deffnx {类} ast.In
@anchor{library/ast ast NotIn}@anchor{3898}
@deffnx {类} ast.NotIn

比较运算符对应的形符。
@end deffn

@geindex Call (ast 中的类)
@anchor{library/ast ast Call}@anchor{3874}
@deffn {类} ast.Call (func, args, keywords, starargs, kwargs)

一个函数调用。 @code{func} 是函数，它通常是一个 @ref{1075,,Name} 或 @ref{3899,,Attribute} 对象。 对于其参数:


@itemize *

@item 
@code{args} 保存由按位置传入的参数组成的列表。

@item 
@code{keywords} 保存了一个代表以关键字传入的参数的 @ref{a6,,keyword} 对象的列表。
@end itemize

当创建一个 @code{Call} 节点时，需要有 @code{args} 和 @code{keywords}，但它们可以为空列表。 @code{starargs} 和 @code{kwargs} 是可选的。

@example
>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
    body=Call(
        func=Name(id='func', ctx=Load()),
        args=[
            Name(id='a', ctx=Load()),
            Starred(
                value=Name(id='d', ctx=Load()),
                ctx=Load())],
        keywords=[
            keyword(
                arg='b',
                value=Name(id='c', ctx=Load())),
            keyword(
                value=Name(id='e', ctx=Load()))]))
@end example
@end deffn

@geindex keyword (ast 中的类)
@anchor{library/ast ast keyword}@anchor{389a}
@deffn {类} ast.keyword (arg, value)

传给函数调用或类定义的关键字参数。 @code{arg} 是形参名称对应的原始字符串，@code{value} 是要传入的节点。
@end deffn

@geindex IfExp (ast 中的类)
@anchor{library/ast ast IfExp}@anchor{389b}
@deffn {类} ast.IfExp (test, body, orelse)

一个表达式例如 @code{a if b else c}。 每个字段保存一个单独节点，因而在下面的示例中，三个节点均为 @ref{1075,,Name} 节点。

@example
>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
    body=IfExp(
        test=Name(id='b', ctx=Load()),
        body=Name(id='a', ctx=Load()),
        orelse=Name(id='c', ctx=Load())))
@end example
@end deffn

@geindex Attribute (ast 中的类)
@anchor{library/ast ast Attribute}@anchor{3899}
@deffn {类} ast.Attribute (value, attr, ctx)

属性访问，例如 @code{d.keys}。 @code{value} 是一个节点，通常为 @ref{1075,,Name}。 @code{attr} 是一个给出属性名称的纯字符串，而 @code{ctx} 根据属性操作的方式可以为 @ref{386f,,Load}, @ref{386e,,Store} 或 @ref{3872,,Del}。

@example
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
    body=Attribute(
        value=Name(id='snake', ctx=Load()),
        attr='colour',
        ctx=Load()))
@end example
@end deffn

@geindex NamedExpr (ast 中的类)
@anchor{library/ast ast NamedExpr}@anchor{389c}
@deffn {类} ast.NamedExpr (target, value)

@quotation

一个带名称的表达式。 此 AST 节点是由赋值表达式运算符（或称海象运算符）产生的。 与第一个参数可以有多个节点的 @ref{389d,,Assign} 节点不同，在此情况下 @code{target} 和 @code{value} 都必须为单独节点。
@end quotation

@example
>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
Expression(
    body=NamedExpr(
        target=Name(id='x', ctx=Store()),
        value=Constant(value=4)))
@end example
@end deffn

@menu
* 抽取: 抽取<2>. 
* 推导式:: 

@end menu

@node 抽取<2>,推导式,,表达式<2>
@anchor{library/ast subscripting}@anchor{389e}
@subsubsection 抽取


@geindex Subscript (ast 中的类)
@anchor{library/ast ast Subscript}@anchor{389f}
@deffn {类} ast.Subscript (value, slice, ctx)

抽取操作，如 @code{l[1]}。 @code{value} 是被抽取的对象（通常为序列或映射）。 @code{slice} 是索引号、切片或键。 它可以是一个包含 @ref{38a0,,Slice} 的 @ref{386d,,Tuple}。 @code{ctx} 根据抽取所执行的操作可以为 @ref{386f,,Load}, @ref{386e,,Store} 或 @ref{3872,,Del}。

@example
>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Tuple(
            elts=[
                Slice(
                    lower=Constant(value=1),
                    upper=Constant(value=2)),
                Constant(value=3)],
            ctx=Load()),
        ctx=Load()))
@end example
@end deffn

@geindex Slice (ast 中的类)
@anchor{library/ast ast Slice}@anchor{38a0}
@deffn {类} ast.Slice (lower, upper, step)

常规切片 (形式如 @code{lower:upper} 或 @code{lower:upper:step})。 只能在 @ref{389f,,Subscript} 的 @emph{slice} 字段内部出现，可以是直接切片对象或是作为 @ref{386d,,Tuple} 的元素。

@example
>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Slice(
            lower=Constant(value=1),
            upper=Constant(value=2)),
        ctx=Load()))
@end example
@end deffn

@node 推导式,,抽取<2>,表达式<2>
@anchor{library/ast comprehensions}@anchor{38a1}
@subsubsection 推导式


@geindex ListComp (ast 中的类)
@geindex SetComp (ast 中的类)
@geindex GeneratorExp (ast 中的类)
@geindex DictComp (ast 中的类)
@anchor{library/ast ast ListComp}@anchor{38a2}
@deffn {类} ast.ListComp (elt, generators)
@anchor{library/ast ast SetComp}@anchor{38a3}
@deffnx {类} ast.SetComp (elt, generators)
@anchor{library/ast ast GeneratorExp}@anchor{38a4}
@deffnx {类} ast.GeneratorExp (elt, generators)
@anchor{library/ast ast DictComp}@anchor{38a5}
@deffnx {类} ast.DictComp (key, value, generators)

列表和集合推导式、生成器表达式以及字典推导式。 @code{elt} (或 @code{key} 和 @code{value}) 是一个代表将针对每个条目被求值的部分的单独节点。

@code{generators} 是一个由 @ref{38a6,,comprehension} 节点组成的列表。

@example
>>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
Expression(
    body=ListComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
>>> print(ast.dump(ast.parse('@{x: x**2 for x in numbers@}', mode='eval'), indent=4))
Expression(
    body=DictComp(
        key=Name(id='x', ctx=Load()),
        value=BinOp(
            left=Name(id='x', ctx=Load()),
            op=Pow(),
            right=Constant(value=2)),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
>>> print(ast.dump(ast.parse('@{x for x in numbers@}', mode='eval'), indent=4))
Expression(
    body=SetComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
@end example
@end deffn

@geindex comprehension (ast 中的类)
@anchor{library/ast ast comprehension}@anchor{38a6}
@deffn {类} ast.comprehension (target, iter, ifs, is_async)

推导式中的一个 @code{for} 子句。 @code{target} 是针对每个元素使用的引用 —— 通常为一个 @ref{1075,,Name} 或 @ref{386d,,Tuple} 节点。 @code{iter} 是要执行迭代的对象。 @code{ifs} 是一个由测试表达式组成的列表：每个 @code{for} 子句都可以拥有多个 @code{ifs}。

@code{is_async} 表明推导式是异步的 (使用 @code{async for} 而不是 @code{for})。 它的值是一个整数 (0 或 1)。

@example
>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
...                indent=4)) # Multiple comprehensions in one.
Expression(
    body=ListComp(
        elt=Call(
            func=Name(id='ord', ctx=Load()),
            args=[
                Name(id='c', ctx=Load())],
            keywords=[]),
        generators=[
            comprehension(
                target=Name(id='line', ctx=Store()),
                iter=Name(id='file', ctx=Load()),
                ifs=[],
                is_async=0),
            comprehension(
                target=Name(id='c', ctx=Store()),
                iter=Name(id='line', ctx=Load()),
                ifs=[],
                is_async=0)]))

>>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
...                indent=4)) # generator comprehension
Expression(
    body=GeneratorExp(
        elt=BinOp(
            left=Name(id='n', ctx=Load()),
            op=Pow(),
            right=Constant(value=2)),
        generators=[
            comprehension(
                target=Name(id='n', ctx=Store()),
                iter=Name(id='it', ctx=Load()),
                ifs=[
                    Compare(
                        left=Name(id='n', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=5)]),
                    Compare(
                        left=Name(id='n', ctx=Load()),
                        ops=[
                            Lt()],
                        comparators=[
                            Constant(value=10)])],
                is_async=0)]))

>>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
...                indent=4)) # Async comprehension
Expression(
    body=ListComp(
        elt=Name(id='i', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='i', ctx=Store()),
                iter=Name(id='soc', ctx=Load()),
                ifs=[],
                is_async=1)]))
@end example
@end deffn

@node 语句,控制流,表达式<2>,节点类
@anchor{library/ast statements}@anchor{38a7}
@subsubsection 语句


@geindex Assign (ast 中的类)
@anchor{library/ast ast Assign}@anchor{389d}
@deffn {类} ast.Assign (targets, value, type_comment)

一次赋值。 @code{targets} 是一个由节点组成的列表，而 @code{value} 是一个单独节点。

@code{targets} 中有多个节点表示将同一个值赋给多个目标。 解包操作是通过在 @code{targets} 中放入一个 @ref{386d,,Tuple} 或 @ref{386c,,List} 来表示的。

@geindex type_comment (ast.Assign 属性)
@anchor{library/ast ast Assign type_comment}@anchor{38a8}
@deffn {属性} type_comment

@code{type_comment} 是带有以注释表示的类型标注的可选的字符串。
@end deffn

@example
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store()),
                Name(id='b', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Name(id='b', ctx=Store())],
                    ctx=Store())],
            value=Name(id='c', ctx=Load()))],
    type_ignores=[])
@end example
@end deffn

@geindex AnnAssign (ast 中的类)
@anchor{library/ast ast AnnAssign}@anchor{38a9}
@deffn {类} ast.AnnAssign (target, annotation, value, simple)

一次带有类型标注的赋值。 @code{target} 为单独节点并可以是 @ref{1075,,Name}, @ref{3899,,Attribute} 或 @ref{389f,,Subscript} 之一。 @code{annotation} 为标注，例如一个 @ref{3ae,,Constant} 或 @ref{1075,,Name} 节点。 @code{value} 为可选的单独节点。 @code{simple} 为一个布尔整数，其值对于 @code{target} 中不出现在括号之内因而是纯名称而非表达式的 @ref{1075,,Name} 节点将为 True。

@example
>>> print(ast.dump(ast.parse('c: int'), indent=4))
Module(
    body=[
        AnnAssign(
            target=Name(id='c', ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=1)],
    type_ignores=[])

>>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Module(
    body=[
        AnnAssign(
            target=Name(id='a', ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            value=Constant(value=1),
            simple=0)],
    type_ignores=[])

>>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Module(
    body=[
        AnnAssign(
            target=Attribute(
                value=Name(id='a', ctx=Load()),
                attr='b',
                ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=0)],
    type_ignores=[])

>>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Module(
    body=[
        AnnAssign(
            target=Subscript(
                value=Name(id='a', ctx=Load()),
                slice=Constant(value=1),
                ctx=Store()),
            annotation=Name(id='int', ctx=Load()),
            simple=0)],
    type_ignores=[])
@end example
@end deffn

@geindex AugAssign (ast 中的类)
@anchor{library/ast ast AugAssign}@anchor{38aa}
@deffn {类} ast.AugAssign (target, op, value)

增强赋值，如 @code{a += 1}。 在下面的例子中，@code{target} 是一个针对 @code{x} (带有 @ref{386e,,Store} 上下文) 的 @ref{1075,,Name} 节点，@code{op} 为 @ref{387e,,Add}，而 @code{value} 是一个值为 1 的 @ref{3ae,,Constant}。

The @code{target} attribute connot be of class @ref{386d,,Tuple} or @ref{386c,,List},
unlike the targets of @ref{389d,,Assign}.

@example
>>> print(ast.dump(ast.parse('x += 2'), indent=4))
Module(
    body=[
        AugAssign(
            target=Name(id='x', ctx=Store()),
            op=Add(),
            value=Constant(value=2))],
    type_ignores=[])
@end example
@end deffn

@geindex Raise (ast 中的类)
@anchor{library/ast ast Raise}@anchor{38ab}
@deffn {类} ast.Raise (exc, cause)

一条 @code{raise} 语句。 @code{exc} 是要引发的异常，对于一个单独的 @code{raise} 通常为 @ref{3874,,Call} 或 @ref{1075,,Name}，或者为 @code{None}。 @code{cause} 是针对 @code{raise x from y} 中 @code{y} 的可选部分。

@example
>>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
    body=[
        Raise(
            exc=Name(id='x', ctx=Load()),
            cause=Name(id='y', ctx=Load()))],
    type_ignores=[])
@end example
@end deffn

@geindex Assert (ast 中的类)
@anchor{library/ast ast Assert}@anchor{38ac}
@deffn {类} ast.Assert (test, msg)

一条断言。 @code{test} 保存条件，例如为一个 @ref{388e,,Compare} 节点。 @code{msg} 保存失败消息。

@example
>>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Module(
    body=[
        Assert(
            test=Name(id='x', ctx=Load()),
            msg=Name(id='y', ctx=Load()))],
    type_ignores=[])
@end example
@end deffn

@geindex Delete (ast 中的类)
@anchor{library/ast ast Delete}@anchor{38ad}
@deffn {类} ast.Delete (targets)

代表一条 @code{del} 语句。 @code{targets} 是一个由节点组成的列表，例如 @ref{1075,,Name}, @ref{3899,,Attribute} 或 @ref{389f,,Subscript} 节点。

@example
>>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='x', ctx=Del()),
                Name(id='y', ctx=Del()),
                Name(id='z', ctx=Del())])],
    type_ignores=[])
@end example
@end deffn

@geindex Pass (ast 中的类)
@anchor{library/ast ast Pass}@anchor{38ae}
@deffn {类} ast.Pass

一条 @code{pass} 语句。

@example
>>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
    body=[
        Pass()],
    type_ignores=[])
@end example
@end deffn

其他仅在函数或循环内部可用的语句将在其他小节中描述。

@menu
* 导入:: 

@end menu

@node 导入,,,语句
@anchor{library/ast imports}@anchor{38af}
@subsubsection 导入


@geindex Import (ast 中的类)
@anchor{library/ast ast Import}@anchor{38b0}
@deffn {类} ast.Import (names)

一条导入语句。 @code{names} 是一个由 @ref{38b1,,alias} 节点组成的列表。

@example
>>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Module(
    body=[
        Import(
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')])],
    type_ignores=[])
@end example
@end deffn

@geindex ImportFrom (ast 中的类)
@anchor{library/ast ast ImportFrom}@anchor{38b2}
@deffn {类} ast.ImportFrom (module, names, level)

代表 @code{from x import y}。 @code{module} 是一个 'from' 名称的原始字符串，不带任何前导点号，或者为 @code{None} 表示 @code{from . import foo} 这样的语句。 @code{level} 是一个保存相对导入层级的整数（0 表示绝对导入）。

@example
>>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Module(
    body=[
        ImportFrom(
            module='y',
            names=[
                alias(name='x'),
                alias(name='y'),
                alias(name='z')],
            level=0)],
    type_ignores=[])
@end example
@end deffn

@geindex alias (ast 中的类)
@anchor{library/ast ast alias}@anchor{38b1}
@deffn {类} ast.alias (name, asname)

两个形参均为名称的原始字符串。 如果要使用常规名称则 @code{asname} 可以为 @code{None}。

@example
>>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Module(
    body=[
        ImportFrom(
            module='foo.bar',
            names=[
                alias(name='a', asname='b'),
                alias(name='c')],
            level=2)],
    type_ignores=[])
@end example
@end deffn

@node 控制流,函数与类定义,语句,节点类
@anchor{library/ast control-flow}@anchor{38b3}
@subsubsection 控制流


@cartouche
@quotation 注解 
可选的子句如 @code{else} 如果不存在则会被存储为一个空列表。
@end quotation
@end cartouche

@geindex If (ast 中的类)
@anchor{library/ast ast If}@anchor{38b4}
@deffn {类} ast.If (test, body, orelse)

一条 @code{if} 语句。 @code{test} 保存一个单独节点，如一个 @ref{388e,,Compare} 节点。 @code{body} 和 @code{orelse} 各自保存一个节点列表。

@code{elif} 子句在 AST 中没有特别的表示形式，而是作为上文介绍的 @code{orelse} 部分之内的一个额外 @ref{38b4,,If} 节点出现。

@example
>>> print(ast.dump(ast.parse("""
... if x:
...    ...
... elif y:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        If(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                If(
                    test=Name(id='y', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))],
                    orelse=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])
@end example
@end deffn

@geindex For (ast 中的类)
@anchor{library/ast ast For}@anchor{38b5}
@deffn {类} ast.For (target, iter, body, orelse, type_comment)

一个 @code{for} 循环。 @code{target} 保存循环赋值的变量，是一个单独 @ref{1075,,Name}, @ref{386d,,Tuple} 或 @ref{386c,,List} 节点。 @code{iter} 保存要被循环的条目，同样也是一个单独节点。 @code{body} 和 @code{orelse} 包含要执行的节点列表。 @code{orelse} 中的会在循环正常结束而不是通过 @code{break} 语句结束时被执行。

@geindex type_comment (ast.For 属性)
@anchor{library/ast ast For type_comment}@anchor{38b6}
@deffn {属性} type_comment

@code{type_comment} 是带有以注释表示的类型标注的可选的字符串。
@end deffn

@example
>>> print(ast.dump(ast.parse("""
... for x in y:
...     ...
... else:
...     ...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='x', ctx=Store()),
            iter=Name(id='y', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
@end example
@end deffn

@geindex While (ast 中的类)
@anchor{library/ast ast While}@anchor{38b7}
@deffn {类} ast.While (test, body, orelse)

一个 @code{while} 循环。 @code{test} 保存条件，如一个 @ref{388e,,Compare} 节点。

@example
>> print(ast.dump(ast.parse("""
... while x:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        While(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
@end example
@end deffn

@geindex Break (ast 中的类)
@geindex Continue (ast 中的类)
@anchor{library/ast ast Break}@anchor{38b8}
@deffn {类} ast.Break
@anchor{library/ast ast Continue}@anchor{38b9}
@deffnx {类} ast.Continue

@code{break} 和 @code{continue} 语句。

@example
>>> print(ast.dump(ast.parse("""\
... for a in b:
...     if a > 5:
...         break
...     else:
...         continue
...
... """), indent=4))
Module(
    body=[
        For(
            target=Name(id='a', ctx=Store()),
            iter=Name(id='b', ctx=Load()),
            body=[
                If(
                    test=Compare(
                        left=Name(id='a', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=5)]),
                    body=[
                        Break()],
                    orelse=[
                        Continue()])],
            orelse=[])],
    type_ignores=[])
@end example
@end deffn

@geindex Try (ast 中的类)
@anchor{library/ast ast Try}@anchor{38ba}
@deffn {类} ast.Try (body, handlers, orelse, finalbody)

@code{try} 代码块。 所有属性都是要执行的节点列表，除了 @code{handlers}，它是一个 @ref{38bb,,ExceptHandler} 节点列表。

@example
>>> print(ast.dump(ast.parse("""
... try:
...    ...
... except Exception:
...    ...
... except OtherException as e:
...    ...
... else:
...    ...
... finally:
...    ...
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                ExceptHandler(
                    type=Name(id='OtherException', ctx=Load()),
                    name='e',
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))],
            finalbody=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])
@end example
@end deffn

@geindex ExceptHandler (ast 中的类)
@anchor{library/ast ast ExceptHandler}@anchor{38bb}
@deffn {类} ast.ExceptHandler (type, name, body)

一个单独的 @code{except} 子句。 @code{type} 是它将匹配的异常，通常为一个 @ref{1075,,Name} 节点（或 @code{None} 表示捕获全部的 @code{except:} 子句）。 @code{name} 是一个用于存放异常的别名的原始字符串，或者如果子句没有 @code{as foo} 则为 @code{None}。 @code{body} 为一个节点列表。

@example
>>> print(ast.dump(ast.parse("""\
... try:
...     a + 1
... except TypeError:
...     pass
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=BinOp(
                        left=Name(id='a', ctx=Load()),
                        op=Add(),
                        right=Constant(value=1)))],
            handlers=[
                ExceptHandler(
                    type=Name(id='TypeError', ctx=Load()),
                    body=[
                        Pass()])],
            orelse=[],
            finalbody=[])],
    type_ignores=[])
@end example
@end deffn

@geindex With (ast 中的类)
@anchor{library/ast ast With}@anchor{38bc}
@deffn {类} ast.With (items, body, type_comment)

一个 @code{with} 代码块。 @code{items} 是一个代表上下文管理器的 @ref{38bd,,withitem} 节点列表，而 @code{body} 是该上下文中的缩进代码块。

@geindex type_comment (ast.With 属性)
@anchor{library/ast ast With type_comment}@anchor{38be}
@deffn {属性} type_comment

@code{type_comment} 是带有以注释表示的类型标注的可选的字符串。
@end deffn
@end deffn

@geindex withitem (ast 中的类)
@anchor{library/ast ast withitem}@anchor{38bd}
@deffn {类} ast.withitem (context_expr, optional_vars)

一个 @code{with} 代码块中单独的上下文管理器。 @code{context_expr} 为上下文管理器，通常为一个 @ref{3874,,Call} 节点。 @code{optional_vars} 为一个针对 @code{as foo} 部分的 @ref{1075,,Name}, @ref{386d,,Tuple} 或 @ref{386c,,List}，或者如果未使用别名则为 @code{None}。

@example
>>> print(ast.dump(ast.parse("""\
... with a as b, c as d:
...    something(b, d)
... """), indent=4))
Module(
    body=[
        With(
            items=[
                withitem(
                    context_expr=Name(id='a', ctx=Load()),
                    optional_vars=Name(id='b', ctx=Store())),
                withitem(
                    context_expr=Name(id='c', ctx=Load()),
                    optional_vars=Name(id='d', ctx=Store()))],
            body=[
                Expr(
                    value=Call(
                        func=Name(id='something', ctx=Load()),
                        args=[
                            Name(id='b', ctx=Load()),
                            Name(id='d', ctx=Load())],
                        keywords=[]))])],
    type_ignores=[])
@end example
@end deffn

@node 函数与类定义,async 与 await,控制流,节点类
@anchor{library/ast function-and-class-definitions}@anchor{38bf}
@subsubsection 函数与类定义


@geindex FunctionDef (ast 中的类)
@anchor{library/ast ast FunctionDef}@anchor{38c0}
@deffn {类} ast.FunctionDef (name, args, body, decorator_list, returns, type_comment)

一个函数定义。


@itemize *

@item 
@code{name} 是函数名称的原始字符串。

@item 
@code{args} 是一个 @ref{38c1,,arguments} 节点。

@item 
@code{body} 是函数内部的节点列表。

@item 
@code{decorator_list} 是要应用的装饰器列表，最外层的最先保存（即列表中的第一项将最后被应用）。

@item 
@code{returns} 是返回标注。
@end itemize

@geindex type_comment (ast.FunctionDef 属性)
@anchor{library/ast ast FunctionDef type_comment}@anchor{38c2}
@deffn {属性} type_comment

@code{type_comment} 是带有以注释表示的类型标注的可选的字符串。
@end deffn
@end deffn

@geindex Lambda (ast 中的类)
@anchor{library/ast ast Lambda}@anchor{3877}
@deffn {类} ast.Lambda (args, body)

@code{lambda} 是可在表达式内部使用的最小化函数定义。 不同于 @ref{38c0,,FunctionDef}，@code{body} 是保存一个单独节点。

@example
>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Module(
    body=[
        Expr(
            value=Lambda(
                args=arguments(
                    posonlyargs=[],
                    args=[
                        arg(arg='x'),
                        arg(arg='y')],
                    kwonlyargs=[],
                    kw_defaults=[],
                    defaults=[]),
                body=Constant(value=Ellipsis)))],
    type_ignores=[])
@end example
@end deffn

@geindex arguments (ast 中的类)
@anchor{library/ast ast arguments}@anchor{38c1}
@deffn {类} ast.arguments (posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)

函数的参数。


@itemize *

@item 
@code{posonlyargs}, @code{args} 和 @code{kwonlyargs} 均为 @ref{38c3,,arg} 节点的列表。

@item 
@code{vararg} 和 @code{kwarg} 均为单独的 @ref{38c3,,arg} 节点，指向 @code{*args, **kwargs} 形参。

@item 
@code{kw_defaults} 是一个由仅限关键字参数默认值组成的列表。 如果有一个为 @code{None}，则对应的参数为必须的参数。

@item 
@code{defaults} 是一个由可按位置传入的参数的默认值组成的列表。 如果默认值个数少于参数个数，则它们将对应最后 n 个参数。
@end itemize
@end deffn

@geindex arg (ast 中的类)
@anchor{library/ast ast arg}@anchor{38c3}
@deffn {类} ast.arg (arg, annotation, type_comment)

列表中的一个单独参数。 @code{arg} 为参数名称原始字符串，@code{annotation} 为其标注，如一个 @code{Str} 或 @ref{1075,,Name} 节点。

@geindex type_comment (ast.arg 属性)
@anchor{library/ast ast arg type_comment}@anchor{38c4}
@deffn {属性} type_comment

@code{type_comment} 是一个可选的将注释用作类型标注的字符串。
@end deffn

@example
>>> print(ast.dump(ast.parse("""\
... @@decorator1
... @@decorator2
... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
...     pass
... """), indent=4))
Module(
    body=[
        FunctionDef(
            name='f',
            args=arguments(
                posonlyargs=[],
                args=[
                    arg(
                        arg='a',
                        annotation=Constant(value='annotation')),
                    arg(arg='b'),
                    arg(arg='c')],
                vararg=arg(arg='d'),
                kwonlyargs=[
                    arg(arg='e'),
                    arg(arg='f')],
                kw_defaults=[
                    None,
                    Constant(value=3)],
                kwarg=arg(arg='g'),
                defaults=[
                    Constant(value=1),
                    Constant(value=2)]),
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1', ctx=Load()),
                Name(id='decorator2', ctx=Load())],
            returns=Constant(value='return annotation'))],
    type_ignores=[])
@end example
@end deffn

@geindex Return (ast 中的类)
@anchor{library/ast ast Return}@anchor{38c5}
@deffn {类} ast.Return (value)

A @code{return} 语句。

@example
>>> print(ast.dump(ast.parse('return 4'), indent=4))
Module(
    body=[
        Return(
            value=Constant(value=4))],
    type_ignores=[])
@end example
@end deffn

@geindex Yield (ast 中的类)
@geindex YieldFrom (ast 中的类)
@anchor{library/ast ast Yield}@anchor{3878}
@deffn {类} ast.Yield (value)
@anchor{library/ast ast YieldFrom}@anchor{3879}
@deffnx {类} ast.YieldFrom (value)

一个 @code{yield} 或 @code{yield from} 表达式。 因为这些属于表达式，所以如果发回的值未被使用则必须将它们包装在 @ref{3876,,Expr} 节点中。

@example
>>> print(ast.dump(ast.parse('yield x'), indent=4))
Module(
    body=[
        Expr(
            value=Yield(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
    body=[
        Expr(
            value=YieldFrom(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])
@end example
@end deffn

@geindex Global (ast 中的类)
@geindex Nonlocal (ast 中的类)
@anchor{library/ast ast Global}@anchor{38c6}
@deffn {类} ast.Global (names)
@anchor{library/ast ast Nonlocal}@anchor{38c7}
@deffnx {类} ast.Nonlocal (names)

@code{global} 和 @code{nonlocal} 语句。 @code{names} 为一个由原始字符串组成的列表。

@example
>>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Module(
    body=[
        Global(
            names=[
                'x',
                'y',
                'z'])],
    type_ignores=[])

>>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Module(
    body=[
        Nonlocal(
            names=[
                'x',
                'y',
                'z'])],
    type_ignores=[])
@end example
@end deffn

@geindex ClassDef (ast 中的类)
@anchor{library/ast ast ClassDef}@anchor{38c8}
@deffn {类} ast.ClassDef (name, bases, keywords, starargs, kwargs, body, decorator_list)

一个类定义。


@itemize *

@item 
@code{name} 为类名称的原始字符串。

@item 
@code{bases} 为一个由显式指明的基类节点组成的列表。

@item 
@code{keywords} 为一个由 @ref{a6,,keyword} 节点组成的列表，主要用于‘元类’。 其他关键字将被传给这个元类，参见 PEP-3115@footnote{https://www.python.org/dev/peps/pep-3115/}。

@item 
@code{starargs} 和 @code{kwargs} 各为一个单独的节点，与在函数调用中的一致。 starargs 将被展开加入到基类的列表中，而 kwargs 将被传给元类。

@item 
@code{body} 是一个由代表类定义内部代码的节点组成的列表。

@item 
@code{decorator_list} 是一个节点的列表，与 @ref{38c0,,FunctionDef} 中的一致。
@end itemize

@example
>>> print(ast.dump(ast.parse("""\
... @@decorator1
... @@decorator2
... class Foo(base1, base2, metaclass=meta):
...     pass
... """), indent=4))
Module(
    body=[
        ClassDef(
            name='Foo',
            bases=[
                Name(id='base1', ctx=Load()),
                Name(id='base2', ctx=Load())],
            keywords=[
                keyword(
                    arg='metaclass',
                    value=Name(id='meta', ctx=Load()))],
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1', ctx=Load()),
                Name(id='decorator2', ctx=Load())])],
    type_ignores=[])
@end example
@end deffn

@node async 与 await,,函数与类定义,节点类
@anchor{library/ast async-and-await}@anchor{38c9}
@subsubsection async 与 await


@geindex AsyncFunctionDef (ast 中的类)
@anchor{library/ast ast AsyncFunctionDef}@anchor{38ca}
@deffn {类} ast.AsyncFunctionDef (name, args, body, decorator_list, returns, type_comment)

一个 @code{async def} 函数定义。 具有与 @ref{38c0,,FunctionDef} 相同的字段。
@end deffn

@geindex Await (ast 中的类)
@anchor{library/ast ast Await}@anchor{38cb}
@deffn {类} ast.Await (value)

一个 @code{await} 表达式。 @code{value} 是它所等待的值。 仅在 @ref{38ca,,AsyncFunctionDef} 的函数体内可用。
@end deffn

@example
>>> print(ast.dump(ast.parse("""\
... async def f():
...     await other_func()
... """), indent=4))
Module(
    body=[
        AsyncFunctionDef(
            name='f',
            args=arguments(
                posonlyargs=[],
                args=[],
                kwonlyargs=[],
                kw_defaults=[],
                defaults=[]),
            body=[
                Expr(
                    value=Await(
                        value=Call(
                            func=Name(id='other_func', ctx=Load()),
                            args=[],
                            keywords=[])))],
            decorator_list=[])],
    type_ignores=[])
@end example

@geindex AsyncFor (ast 中的类)
@geindex AsyncWith (ast 中的类)
@anchor{library/ast ast AsyncFor}@anchor{38cc}
@deffn {类} ast.AsyncFor (target, iter, body, orelse, type_comment)
@anchor{library/ast ast AsyncWith}@anchor{38cd}
@deffnx {类} ast.AsyncWith (items, body, type_comment)

@code{async for} 循环和 @code{async with} 上下文管理器。 它们分别具有与 @ref{38b5,,For} 和 @ref{38bc,,With} 相同的字段。 仅在 @ref{38ca,,AsyncFunctionDef} 的函数体内可用。
@end deffn

@cartouche
@quotation 注解 
当一个字符串由 @ref{2dd,,ast.parse()} 来解析时，所返回的树中的运算符节点 (为 @code{ast.operator}, @code{ast.unaryop}, @code{ast.cmpop}, @code{ast.boolop} 和 @code{ast.expr_context} 的子类) 将均为单例对象。 对其中某一个 (例如 @ref{387e,,ast.Add}) 的修改将反映到同一个值所出现的其他位置上。
@end quotation
@end cartouche

@node ast 中的辅助函数,编译器旗标,节点类,ast --- 抽象语法树
@anchor{library/ast ast-helpers}@anchor{38ce}
@subsubsection @code{ast} 中的辅助函数


除了节点类， @ref{7,,ast} 模块里为遍历抽象语法树定义了这些工具函数和类:

@geindex parse() (在 ast 模块中)
@anchor{library/ast ast parse}@anchor{2dd}
@deffn {函数} ast.parse (source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)

把源码解析为AST节点。和 @code{compile(source, filename, mode,ast.PyCF_ONLY_AST)} 等价。

如果给出 @code{type_comments=True}，解析器会被修改以检查并返回 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 所描述的类型注释。 这相当于将 @ref{38cf,,ast.PyCF_TYPE_COMMENTS} 添加到传给 @ref{2ee,,compile()} 的旗标中。 这将报告针对未在正确放置类型注释的语法错误。 没有这个旗标，类型注释将被忽略，而指定 AST 节点上的  @code{type_comment} 字段将总是为 @code{None}。 此外，@code{# type: ignore} 注释的位置将作为 @code{Module} 的 @code{type_ignores} 属性被返回（在其他情况下则总是为空列表）。

并且，如果 @code{mode} 为 @code{'func_type'}，则输入语法会进行与 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} "签名类型注释" 对应的修改，例如 @code{(str, int) -> List[str]}。

此外，将 @code{feature_version} 设为元组 @code{(major, minor)} 将会尝试使用该will attempt to parse using that Python 版本的语法来进行解析。 目前 @code{major} 必须等于 @code{3}。 例如，设置 @code{feature_version=(3, 4)} 将允许使用 @code{async} 和 @code{await} 作为变量名。 最低受支持版本为 @code{(3, 4)}；最高则为 @code{sys.version_info[0:2]}。

如果源包含一个空字符 ('0')，则会引发 @ref{16d,,ValueError}。

@quotation

@cartouche
@quotation 警告 
请注意成功将源代码解析为 AST 对象并不能保证该源代码提供了可被执行的有效 Python 代码，因为编译步骤还可能引发其他的 @ref{562,,SyntaxError} 异常。 例如，对于源代码 @code{return 42} 可以生成一条有效的 return 语句 AST 节点，但它不能被单独编译（它必须位于一个函数节点之内）。

特别地，@ref{2dd,,ast.parse()} 不会执行任何作用域检查，这是由编译步骤来做的。
@end quotation
@end cartouche
@end quotation

@cartouche
@quotation 警告 
足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为Python的AST编译器是有栈深限制的。
@end quotation
@end cartouche


在 3.8 版更改: 增加了 @code{type_comments}, @code{mode='func_type'} 和 @code{feature_version}。

@end deffn

@geindex unparse() (在 ast 模块中)
@anchor{library/ast ast unparse}@anchor{186}
@deffn {函数} ast.unparse (ast_obj)

反向解析一个 @ref{187,,ast.AST} 对象并生成一个包含当再次使用 @ref{2dd,,ast.parse()} 解析时将产生同样的 @ref{187,,ast.AST} 对象的代码的字符串。

@cartouche
@quotation 警告 
所产生的代码字符串将不一定与生成 @ref{187,,ast.AST} 对象的原始代码完全一致（不带任何编译器优化，例如常量元组/冻结集合等）。
@end quotation
@end cartouche

@cartouche
@quotation 警告 
尝试反向解析一个高度复杂的表达式可能会导致 @ref{731,,RecursionError}。
@end quotation
@end cartouche


3.9 新版功能.

@end deffn

@geindex literal_eval() (在 ast 模块中)
@anchor{library/ast ast literal_eval}@anchor{5a8}
@deffn {函数} ast.literal_eval (node_or_string)

对表达式节点以及包含Python字面量或容器的字符串进行安全的求值。传入的字符串或者节点里可能只包含下列的Python字面量结构: 字符串，字节对象(bytes)，数值，元组，列表，字典，集合，布尔值和 @code{None}。

这可被用于安全地对包含不受信任来源的 Python 值的字符串进行求值而不必解析这些值本身。 它并不能对任意的复杂表达式进行求值，例如涉及运算符或索引操作的表达式。

@cartouche
@quotation 警告 
足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为Python的AST编译器是有栈深限制的。
@end quotation
@end cartouche


在 3.2 版更改: 目前支持字节和集合。



在 3.9 版更改: 现在支持通过 @code{'set()'} 创建空集合。

@end deffn

@geindex get_docstring() (在 ast 模块中)
@anchor{library/ast ast get_docstring}@anchor{11d3}
@deffn {函数} ast.get_docstring (node, clean=True)

返回给定 @emph{node} (必须为 @ref{38c0,,FunctionDef}, @ref{38ca,,AsyncFunctionDef}, @ref{38c8,,ClassDef} 或 @code{Module} 节点) 的文档字符串，或者如果没有文档字符串则返回 @code{None}。 如果 @emph{clean} 为真值，则通过 @ref{3760,,inspect.cleandoc()} 清除文档字符串的缩进。


在 3.5 版更改: 目前支持 @ref{38ca,,AsyncFunctionDef}

@end deffn

@geindex get_source_segment() (在 ast 模块中)
@anchor{library/ast ast get_source_segment}@anchor{2dc}
@deffn {函数} ast.get_source_segment (source, node, *, padded=False)

获取生成 @emph{node} 的 @emph{source} 的源代码段。 如果丢失了某些位置信息 (@code{lineno}, @code{end_lineno}, @code{col_offset} 或 @code{end_col_offset})，则返回 @code{None}。

如果 @emph{padded} 为 @code{True}，则多行语句的第一行将以与其初始位置相匹配的空格填充。


3.8 新版功能.

@end deffn

@geindex fix_missing_locations() (在 ast 模块中)
@anchor{library/ast ast fix_missing_locations}@anchor{38d0}
@deffn {函数} ast.fix_missing_locations (node)

当你通过 @ref{2ee,,compile()} 来编译节点树时，编译器会准备接受每个支持 @code{lineno} 和 @code{col_offset} 属性的节点的相应信息。 对已生成节点来说这是相当繁琐的，因此这个辅助工具会递归地为尚未设置这些属性的节点添加它们，具体做法是将其设为父节点的对应值。 它将从 @emph{node} 开始递归地执行。
@end deffn

@geindex increment_lineno() (在 ast 模块中)
@anchor{library/ast ast increment_lineno}@anchor{104d}
@deffn {函数} ast.increment_lineno (node, n=1)

从 @emph{node} 开始按 @emph{n} 递增节点树中每个节点的行号和结束行号。 这在“移动代码”到文件中的不同位置时很有用处。
@end deffn

@geindex copy_location() (在 ast 模块中)
@anchor{library/ast ast copy_location}@anchor{38d1}
@deffn {函数} ast.copy_location (new_node, old_node)

在可能的情况下将源位置 (@code{lineno}, @code{col_offset}, @code{end_lineno} 和 @code{end_col_offset}) 从 @emph{old_node} 拷贝到 @emph{new_node}，并返回 @emph{new_node}。
@end deffn

@geindex iter_fields() (在 ast 模块中)
@anchor{library/ast ast iter_fields}@anchor{38d2}
@deffn {函数} ast.iter_fields (node)

针对于 @emph{node} 上在 @code{node._fields} 中出现的每个字段产生一个 @code{(fieldname, value)} 元组。
@end deffn

@geindex iter_child_nodes() (在 ast 模块中)
@anchor{library/ast ast iter_child_nodes}@anchor{38d3}
@deffn {函数} ast.iter_child_nodes (node)

产生 @emph{node} 所有的直接子节点，也就是说，所有为节点的字段所有为节点列表的字段条目。
@end deffn

@geindex walk() (在 ast 模块中)
@anchor{library/ast ast walk}@anchor{38d4}
@deffn {函数} ast.walk (node)

递归地产生节点树中从 @emph{node} 开始（包括 @emph{node} 本身）的所有下级节点，没有确定的排序方式。 这在你仅想要原地修改节点而不关心具体上下文时很有用处。
@end deffn

@geindex NodeVisitor (ast 中的类)
@anchor{library/ast ast NodeVisitor}@anchor{3af}
@deffn {类} ast.NodeVisitor

一个遍历抽象语法树并针对所找到的每个节点调用访问器函数的节点访问器基类。 该函数可能会返回一个由 @ref{38d5,,visit()} 方法所提供的值。

这个类应当被子类化，并由子类来添加访问器方法。

@geindex visit() (ast.NodeVisitor 方法)
@anchor{library/ast ast NodeVisitor visit}@anchor{38d5}
@deffn {方法} visit (node)

访问一个节点。 默认实现会调用名为 @code{self.visit_@emph{classname}} 的方法其中 @emph{classname} 为节点类的名称，或者如果该方法不存在则为 @ref{38d6,,generic_visit()}。
@end deffn

@geindex generic_visit() (ast.NodeVisitor 方法)
@anchor{library/ast ast NodeVisitor generic_visit}@anchor{38d6}
@deffn {方法} generic_visit (node)

该访问器会在节点的所有子节点上调用 @ref{38d5,,visit()}。

请注意所有包含自定义访问器方法的节点的子节点将不会被访问除非访问器调用了 @ref{38d6,,generic_visit()} 或是自行访问它们。
@end deffn

如果你想在遍历期间应用对节点的修改则请不要使用 @ref{3af,,NodeVisitor}。 对此目的可使用一个允许修改的特殊访问器 (@ref{38d7,,NodeTransformer})。


3.8 版后已移除: @code{visit_Num()}, @code{visit_Str()}, @code{visit_Bytes()}, @code{visit_NameConstant()} 和 @code{visit_Ellipsis()} 等方法现在已被弃用且在未来的 Python 版本中将不会再被调用。 请添加 @code{visit_Constant()} 方法来处理所有常量节点。

@end deffn

@geindex NodeTransformer (ast 中的类)
@anchor{library/ast ast NodeTransformer}@anchor{38d7}
@deffn {类} ast.NodeTransformer

子类 @ref{3af,,NodeVisitor}  用于遍历抽象语法树，并允许修改节点。

@ref{38d7,,NodeTransformer} 将遍历抽象语法树并使用visitor方法的返回值去替换或移除旧节点。如果visitor方法的返回值为 @code{None} , 则该节点将从其位置移除，否则将替换为返回值。当返回值是原始节点时，无需替换。

如下是一个转换器示例，它将所有出现的名称 (@code{foo}) 重写为 @code{data['foo']}:

@example
class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )
@end example

请记住，如果您正在操作的节点具有子节点，则必须先转换其子节点或为该节点调用 @code{generic_visit()} 方法。

对于属于语句集合（适用于所有语句节点）的节点，访问者还可以返回节点列表而不仅仅是单个节点。

如果 @ref{38d7,,NodeTransformer} 引入了新的（不属于原节点树一部分的）节点而没有给出它们的位置信息（如 @code{lineno} 等），则应当调用 @ref{38d0,,fix_missing_locations()} 并传入新的子节点树来重新计算位置信息:

@example
tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
@end example

通常你可以像这样使用转换器:

@example
node = YourTransformer().visit(node)
@end example
@end deffn

@geindex dump() (在 ast 模块中)
@anchor{library/ast ast dump}@anchor{185}
@deffn {函数} ast.dump (node, annotate_fields=True, include_attributes=False, *, indent=None)

返回 @emph{node} 中树结构的格式化转储。 这主要适用于调试目的。 如果 @emph{annotate_fields} 为真值（默认），返回的字符串将显示字段的名称和值。 如果 @emph{annotate_fields} 为假值，结果字符串将通过省略无歧义的字段名称变得更为紧凑。 默认情况下不会转储行号和列偏移等属性。 如果需要，可将 @emph{include_attributes} 设为真值。

如果 @emph{indent} 是一个非负整数或者字符串，那么节点树将被美化输出为指定的缩进级别。 如果缩进级别为 0、负数或者 @code{""} 则将只插入换行符。  @code{None} (默认) 将选择最紧凑的表示形式。 使用一个正整数将让每个级别缩进相应数量的空格。 如果 @emph{indent} 是一个字符串 (如 @code{"\t"})，该字符串会被用于缩进每个级别。


在 3.9 版更改: 添加了 @emph{indent} 选项。

@end deffn

@node 编译器旗标,命令行用法<2>,ast 中的辅助函数,ast --- 抽象语法树
@anchor{library/ast ast-compiler-flags}@anchor{1750}@anchor{library/ast compiler-flags}@anchor{38d8}
@subsubsection 编译器旗标


下列旗标可被传给 @ref{2ee,,compile()} 用来改变程序编译的效果:

@geindex PyCF_ALLOW_TOP_LEVEL_AWAIT() (在 ast 模块中)
@anchor{library/ast ast PyCF_ALLOW_TOP_LEVEL_AWAIT}@anchor{38d9}
@deffn {数据} ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

启用对最高层级 @code{await}, @code{async for}, @code{async with} 以及异步推导式的支持。


3.8 新版功能.

@end deffn

@geindex PyCF_ONLY_AST() (在 ast 模块中)
@anchor{library/ast ast PyCF_ONLY_AST}@anchor{385f}
@deffn {数据} ast.PyCF_ONLY_AST

生成并返回一个抽象语法树而不是返回一个已编译的代码对象。
@end deffn

@geindex PyCF_TYPE_COMMENTS() (在 ast 模块中)
@anchor{library/ast ast PyCF_TYPE_COMMENTS}@anchor{38cf}
@deffn {数据} ast.PyCF_TYPE_COMMENTS

启用对 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526} 风格的类型注释的支持 (@code{# type: <type>}, @code{# type: ignore <stuff>})。


3.8 新版功能.

@end deffn

@node 命令行用法<2>,,编译器旗标,ast --- 抽象语法树
@anchor{library/ast ast-cli}@anchor{38da}@anchor{library/ast command-line-usage}@anchor{38db}
@subsubsection 命令行用法



3.9 新版功能.


@ref{7,,ast} 模块可以在命令行下作为脚本来执行。 具体做法非常简单:

@example
python -m ast [-m <mode>] [-a] [infile]
@end example

可以接受以下选项：

@geindex ast command line option; -h
@geindex ast command line option; --help
@anchor{library/ast cmdoption-ast-h}@anchor{38dc}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

显示帮助信息并退出。
@end deffn

@geindex ast command line option; -m <mode>
@geindex ast command line option; --mode <mode>
@anchor{library/ast cmdoption-ast-m}@anchor{38dd}
@deffn {程序选项} @w{-}m <mode>
@anchor{library/ast cmdoption-ast-mode}@anchor{38de}
@deffnx {程序选项} @w{-}@w{-}mode <mode>

指明哪种代码必须被编译，相当于 @ref{2dd,,parse()} 中的 @emph{mode} 参数。
@end deffn

@geindex ast command line option; --no-type-comments
@anchor{library/ast cmdoption-ast-no-type-comments}@anchor{38df}
@deffn {程序选项} @w{-}@w{-}no@w{-}type@w{-}comments

不要解析类型注释。
@end deffn

@geindex ast command line option; -a
@geindex ast command line option; --include-attributes
@anchor{library/ast cmdoption-ast-a}@anchor{38e0}
@deffn {程序选项} @w{-}a, @w{-}@w{-}include@w{-}attributes

包括属性如行号和列偏移。
@end deffn

@geindex ast command line option; -i <indent>
@geindex ast command line option; --indent <indent>
@anchor{library/ast cmdoption-ast-i}@anchor{38e1}
@deffn {程序选项} @w{-}i <indent>
@anchor{library/ast cmdoption-ast-indent}@anchor{38e2}
@deffnx {程序选项} @w{-}@w{-}indent <indent>

AST 中节点的缩进（空格数）。
@end deffn

如果指定了 @code{infile} 则其内容将被解析为 AST 并转储至 stdout。 在其他情况下，将从 stdin 读取内容。


@subsubheading 参见


Green Tree Snakes@footnote{https://greentreesnakes.readthedocs.io/}，一个外部文档资源，包含处理 Python AST 的完整细节。

ASTTokens@footnote{https://asttokens.readthedocs.io/en/latest/user-guide.html} 会为 Python AST 标注生成它们的源代码中的形符和文本的位置。 这对执行源代码转换的工具很有帮助。

leoAst.py@footnote{http://leoeditor.com/appendices.html#leoast-py} 通过在形符和 ast 节点之间插入双向链接统一了 Python 程序基于形符的和基于解析树的视图。

LibCST@footnote{https://libcst.readthedocs.io/} 将代码解析为一个实体语法树（Concrete Syntax Tree），它看起来像是 ast 树而又保留了所有格式化细节。 它对构建自动化重构（codemod）应用和代码质量检查工具很有用处。

Parso@footnote{https://parso.readthedocs.io} 是一个支持错误恢复和不同 Python 版本的（在多个 Python 版本中）往返解析的 Python 解析器。 Parso 还能列出你的 Python 文件中的许多错误。


@node symtable ——访问编译器的符号表,symbol --- 与 Python 解析树一起使用的常量,ast --- 抽象语法树,Python 语言服务
@anchor{library/symtable doc}@anchor{38e3}@anchor{library/symtable module-symtable}@anchor{fc}@anchor{library/symtable symtable-access-to-the-compiler-s-symbol-tables}@anchor{38e4}
@subsection @code{symtable} ——访问编译器的符号表


@geindex symtable (模块)

@strong{Source code：} Lib/symtable.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/symtable.py}


__________________________________________________________________


符号表由编译器在生成字节码之前根据 AST 生成。符号表负责计算代码中每个标识符的作用域。 @ref{fc,,symtable} 提供了一个查看这些表的接口。

@menu
* 符号表的生成:: 
* 符号表的查看:: 

@end menu

@node 符号表的生成,符号表的查看,,symtable ——访问编译器的符号表
@anchor{library/symtable generating-symbol-tables}@anchor{38e5}
@subsubsection 符号表的生成


@geindex symtable() (在 symtable 模块中)
@anchor{library/symtable symtable symtable}@anchor{114a}
@deffn {函数} symtable.symtable (code, filename, compile_type)

返回 Python 源 @emph{代码} 顶层的 @ref{38e6,,SymbolTable}。@emph{filename} 是代码文件名。 @emph{compile_type} 的含义类似 @ref{2ee,,compile()} 的 @emph{mode} 参数。
@end deffn

@node 符号表的查看,,符号表的生成,symtable ——访问编译器的符号表
@anchor{library/symtable examining-symbol-tables}@anchor{38e7}
@subsubsection 符号表的查看


@geindex SymbolTable (symtable 中的类)
@anchor{library/symtable symtable SymbolTable}@anchor{38e6}
@deffn {类} symtable.SymbolTable

某个代码块的命名空间表。构造函数不公开。

@geindex get_type() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_type}@anchor{38e8}
@deffn {方法} get_type ()

返回符号表的类型。可能是 @code{'class'} 、@code{'module'} 或 @code{'function'}。
@end deffn

@geindex get_id() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_id}@anchor{38e9}
@deffn {方法} get_id ()

返回符号表的标识符
@end deffn

@geindex get_name() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_name}@anchor{38ea}
@deffn {方法} get_name ()

返回符号表的名称。 若为类的符号表则返回类名；若为函数的符号表则为函数名；若是全局符号表则为 @code{'top'} (@ref{38e8,,get_type()} 返回 @code{'module'})。
@end deffn

@geindex get_lineno() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_lineno}@anchor{38eb}
@deffn {方法} get_lineno ()

返回符号表所代表的代码块中第一行的编号。
@end deffn

@geindex is_optimized() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable is_optimized}@anchor{38ec}
@deffn {方法} is_optimized ()

如果符号表中的局部变量可能被优化过，则返回 @code{True}。
@end deffn

@geindex is_nested() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable is_nested}@anchor{38ed}
@deffn {方法} is_nested ()

如果代码块是嵌套类或函数，则返回 @code{True}。
@end deffn

@geindex has_children() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable has_children}@anchor{38ee}
@deffn {方法} has_children ()

如果代码块中有嵌套的命名空间，则返回 @code{True}。可通过  @ref{38ef,,get_children()} 读取。
@end deffn

@geindex get_identifiers() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_identifiers}@anchor{38f0}
@deffn {方法} get_identifiers ()

返回符号表中的符号名列表。
@end deffn

@geindex lookup() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable lookup}@anchor{38f1}
@deffn {方法} lookup (name)

在符号表中查找 @emph{name} 并返回一个 @ref{38f2,,Symbol} 实例。
@end deffn

@geindex get_symbols() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_symbols}@anchor{38f3}
@deffn {方法} get_symbols ()

返回符号表中所有符号的 @ref{38f2,,Symbol} 实例的列表。
@end deffn

@geindex get_children() (symtable.SymbolTable 方法)
@anchor{library/symtable symtable SymbolTable get_children}@anchor{38ef}
@deffn {方法} get_children ()

返回嵌套符号表的列表。
@end deffn
@end deffn

@geindex Function (symtable 中的类)
@anchor{library/symtable symtable Function}@anchor{38f4}
@deffn {类} symtable.Function

函数或方法的命名空间。该类继承自 @ref{38e6,,SymbolTable}。

@geindex get_parameters() (symtable.Function 方法)
@anchor{library/symtable symtable Function get_parameters}@anchor{38f5}
@deffn {方法} get_parameters ()

返回由函数的参数名组成的元组。
@end deffn

@geindex get_locals() (symtable.Function 方法)
@anchor{library/symtable symtable Function get_locals}@anchor{38f6}
@deffn {方法} get_locals ()

返回函数中局部变量名组成的元组。
@end deffn

@geindex get_globals() (symtable.Function 方法)
@anchor{library/symtable symtable Function get_globals}@anchor{38f7}
@deffn {方法} get_globals ()

返回函数中全局变量名组成的元组。
@end deffn

@geindex get_nonlocals() (symtable.Function 方法)
@anchor{library/symtable symtable Function get_nonlocals}@anchor{38f8}
@deffn {方法} get_nonlocals ()

返回函数中非局部变量名组成的元组。
@end deffn

@geindex get_frees() (symtable.Function 方法)
@anchor{library/symtable symtable Function get_frees}@anchor{38f9}
@deffn {方法} get_frees ()

返回函数中自由变量名组成的元组。
@end deffn
@end deffn

@geindex Class (symtable 中的类)
@anchor{library/symtable symtable Class}@anchor{38fa}
@deffn {类} symtable.Class

类的命名空间。继承自 @ref{38e6,,SymbolTable}。

@geindex get_methods() (symtable.Class 方法)
@anchor{library/symtable symtable Class get_methods}@anchor{38fb}
@deffn {方法} get_methods ()

返回类中声明的方法名组成的元组。
@end deffn
@end deffn

@geindex Symbol (symtable 中的类)
@anchor{library/symtable symtable Symbol}@anchor{38f2}
@deffn {类} symtable.Symbol

@ref{38e6,,SymbolTable} 中的数据项，对应于源码中的某个标识符。构造函数不公开。

@geindex get_name() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol get_name}@anchor{38fc}
@deffn {方法} get_name ()

返回符号名
@end deffn

@geindex is_referenced() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_referenced}@anchor{38fd}
@deffn {方法} is_referenced ()

如果符号在代码块中被引用了，则返回 @code{True}。
@end deffn

@geindex is_imported() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_imported}@anchor{38fe}
@deffn {方法} is_imported ()

如果符号是由导入语句创建的，则返回 @code{True}。
@end deffn

@geindex is_parameter() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_parameter}@anchor{38ff}
@deffn {方法} is_parameter ()

如果符号是参数，返回 @code{True}。
@end deffn

@geindex is_global() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_global}@anchor{3900}
@deffn {方法} is_global ()

如果符号是全局变量，则返回 @code{True}。
@end deffn

@geindex is_nonlocal() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_nonlocal}@anchor{118f}
@deffn {方法} is_nonlocal ()

如果符号为非局部变量，则返回 @code{True}。
@end deffn

@geindex is_declared_global() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_declared_global}@anchor{d86}
@deffn {方法} is_declared_global ()

如果符号用 global 声明为全局变量，则返回 @code{True}。
@end deffn

@geindex is_local() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_local}@anchor{3901}
@deffn {方法} is_local ()

如果符号在代码块内是局部变量，则返回 @code{True}。
@end deffn

@geindex is_annotated() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_annotated}@anchor{3902}
@deffn {方法} is_annotated ()

如果符号带有注解，则返回 @code{True}。


3.6 新版功能.

@end deffn

@geindex is_free() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_free}@anchor{3903}
@deffn {方法} is_free ()

如果符号在代码块中被引用，但未赋值，则返回 @code{True}。
@end deffn

@geindex is_assigned() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_assigned}@anchor{3904}
@deffn {方法} is_assigned ()

如果符号在代码块中赋值，则返回 @code{True}。
@end deffn

@geindex is_namespace() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol is_namespace}@anchor{3905}
@deffn {方法} is_namespace ()

如果符号名绑定引入了新的命名空间，则返回 @code{True}。

如果符号名用于 function 或 class 语句，则为 True。

例如:

@example
>>> table = symtable.symtable("def some_func(): pass", "string", "exec")
>>> table.lookup("some_func").is_namespace()
True
@end example

注意，一个符号名可以与多个对象绑定。如果结果为 @code{True}，则该符号名还可以绑定到其他对象上，比如 int 或 list ，且不会引入新的命名空间。
@end deffn

@geindex get_namespaces() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol get_namespaces}@anchor{3906}
@deffn {方法} get_namespaces ()

返回与符号名绑定的命名空间的列表。
@end deffn

@geindex get_namespace() (symtable.Symbol 方法)
@anchor{library/symtable symtable Symbol get_namespace}@anchor{3907}
@deffn {方法} get_namespace ()

返回与符号名绑定的命名空间。如果绑定的命名空间超过一个，则会触发 @ref{16d,,ValueError}。
@end deffn
@end deffn

@node symbol --- 与 Python 解析树一起使用的常量,token --- 与Python解析树一起使用的常量,symtable ——访问编译器的符号表,Python 语言服务
@anchor{library/symbol doc}@anchor{3908}@anchor{library/symbol module-symbol}@anchor{fb}@anchor{library/symbol symbol-constants-used-with-python-parse-trees}@anchor{3909}
@subsection @code{symbol} --- 与 Python 解析树一起使用的常量


@geindex symbol (模块)

@strong{源代码:} Lib/symbol.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/symbol.py}


__________________________________________________________________


此模块提供用于表示解析树内部节点数值的常量。 与大多数 Python 不同，这些常量使用小写字符名称。 请参阅 Python 发行版中的 @code{Grammar/Grammar} 文件来获取该语言语法上下文中对这些名称的定义。 这些名称所映射的特定数字值可能会在 Python 版本之间更改。

@cartouche
@quotation 警告 
symbol 模块已弃用并将在未来的 Python 版本中被移除。
@end quotation
@end cartouche

此模块还提供了一个额外的数据对象:

@geindex sym_name() (在 symbol 模块中)
@anchor{library/symbol symbol sym_name}@anchor{390a}
@deffn {数据} symbol.sym_name

将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类可读的解析树表示。
@end deffn

@node token --- 与Python解析树一起使用的常量,keyword --- 检验Python关键字,symbol --- 与 Python 解析树一起使用的常量,Python 语言服务
@anchor{library/token doc}@anchor{390b}@anchor{library/token module-token}@anchor{119}@anchor{library/token token-constants-used-with-python-parse-trees}@anchor{390c}
@subsection @code{token} --- 与Python解析树一起使用的常量


@geindex token (模块)

@strong{源码：} Lib/token.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/token.py}


__________________________________________________________________


此模块提供表示解析树（终端令牌）的叶节点的数值的常量。 请参阅 Python 发行版中的文件 @code{Grammar/Grammar} ，以获取语言语法上下文中名称的定义。 名称映射到的特定数值可能会在 Python 版本之间更改。

该模块还提供从数字代码到名称和一些函数的映射。 这些函数镜像了 Python C 头文件中的定义。

@geindex tok_name() (在 token 模块中)
@anchor{library/token token tok_name}@anchor{390d}
@deffn {数据} token.tok_name

将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类可读的解析树表示。
@end deffn

@geindex ISTERMINAL() (在 token 模块中)
@anchor{library/token token ISTERMINAL}@anchor{390e}
@deffn {函数} token.ISTERMINAL (x)

对终端标记值返回 @code{True}。
@end deffn

@geindex ISNONTERMINAL() (在 token 模块中)
@anchor{library/token token ISNONTERMINAL}@anchor{390f}
@deffn {函数} token.ISNONTERMINAL (x)

对非终端标记值返回 @code{True}。
@end deffn

@geindex ISEOF() (在 token 模块中)
@anchor{library/token token ISEOF}@anchor{3910}
@deffn {函数} token.ISEOF (x)

如果 @emph{x} 是表示输入结束的标记则返回 @code{True}。
@end deffn

标记常量是：

@c Auto-generated by Tools/scripts/generate_token.py

@geindex ENDMARKER() (在 token 模块中)
@anchor{library/token token ENDMARKER}@anchor{3911}
@deffn {数据} token.ENDMARKER
@end deffn

@geindex NAME() (在 token 模块中)
@anchor{library/token token NAME}@anchor{3912}
@deffn {数据} token.NAME
@end deffn

@geindex NUMBER() (在 token 模块中)
@anchor{library/token token NUMBER}@anchor{3913}
@deffn {数据} token.NUMBER
@end deffn

@geindex STRING() (在 token 模块中)
@anchor{library/token token STRING}@anchor{3914}
@deffn {数据} token.STRING
@end deffn

@geindex NEWLINE() (在 token 模块中)
@anchor{library/token token NEWLINE}@anchor{3915}
@deffn {数据} token.NEWLINE
@end deffn

@geindex INDENT() (在 token 模块中)
@anchor{library/token token INDENT}@anchor{3916}
@deffn {数据} token.INDENT
@end deffn

@geindex DEDENT() (在 token 模块中)
@anchor{library/token token DEDENT}@anchor{3917}
@deffn {数据} token.DEDENT
@end deffn

@geindex LPAR() (在 token 模块中)
@anchor{library/token token LPAR}@anchor{3918}
@deffn {数据} token.LPAR

@code{"("} 的权标值。
@end deffn

@geindex RPAR() (在 token 模块中)
@anchor{library/token token RPAR}@anchor{3919}
@deffn {数据} token.RPAR

@code{")"} 的权标值。
@end deffn

@geindex LSQB() (在 token 模块中)
@anchor{library/token token LSQB}@anchor{391a}
@deffn {数据} token.LSQB

@code{"["} 的权标值。
@end deffn

@geindex RSQB() (在 token 模块中)
@anchor{library/token token RSQB}@anchor{391b}
@deffn {数据} token.RSQB

@code{"]"} 的权标值。
@end deffn

@geindex COLON() (在 token 模块中)
@anchor{library/token token COLON}@anchor{391c}
@deffn {数据} token.COLON

@code{":"} 的权标值。
@end deffn

@geindex COMMA() (在 token 模块中)
@anchor{library/token token COMMA}@anchor{391d}
@deffn {数据} token.COMMA

@code{","} 的权标值。
@end deffn

@geindex SEMI() (在 token 模块中)
@anchor{library/token token SEMI}@anchor{391e}
@deffn {数据} token.SEMI

@code{";"} 的权标值。
@end deffn

@geindex PLUS() (在 token 模块中)
@anchor{library/token token PLUS}@anchor{391f}
@deffn {数据} token.PLUS

@code{"+"} 的权标值。
@end deffn

@geindex MINUS() (在 token 模块中)
@anchor{library/token token MINUS}@anchor{3920}
@deffn {数据} token.MINUS

@code{"-"} 的权标值。
@end deffn

@geindex STAR() (在 token 模块中)
@anchor{library/token token STAR}@anchor{3921}
@deffn {数据} token.STAR

@code{"*"} 的权标值。
@end deffn

@geindex SLASH() (在 token 模块中)
@anchor{library/token token SLASH}@anchor{3922}
@deffn {数据} token.SLASH

@code{"/"} 的权标值。
@end deffn

@geindex VBAR() (在 token 模块中)
@anchor{library/token token VBAR}@anchor{3923}
@deffn {数据} token.VBAR

@code{"|"} 的权标值。
@end deffn

@geindex AMPER() (在 token 模块中)
@anchor{library/token token AMPER}@anchor{3924}
@deffn {数据} token.AMPER

@code{"&"} 的权标值。
@end deffn

@geindex LESS() (在 token 模块中)
@anchor{library/token token LESS}@anchor{3925}
@deffn {数据} token.LESS

@code{"<"} 的权标值。
@end deffn

@geindex GREATER() (在 token 模块中)
@anchor{library/token token GREATER}@anchor{3926}
@deffn {数据} token.GREATER

@code{">"} 的权标值。
@end deffn

@geindex EQUAL() (在 token 模块中)
@anchor{library/token token EQUAL}@anchor{3927}
@deffn {数据} token.EQUAL

@code{"="} 的形符值。
@end deffn

@geindex DOT() (在 token 模块中)
@anchor{library/token token DOT}@anchor{3928}
@deffn {数据} token.DOT

@code{"."} 的形符值。
@end deffn

@geindex PERCENT() (在 token 模块中)
@anchor{library/token token PERCENT}@anchor{3929}
@deffn {数据} token.PERCENT

@code{"%"}
@end deffn

@geindex LBRACE() (在 token 模块中)
@anchor{library/token token LBRACE}@anchor{392a}
@deffn {数据} token.LBRACE

Token value for @code{"@{"}.
@end deffn

@geindex RBRACE() (在 token 模块中)
@anchor{library/token token RBRACE}@anchor{392b}
@deffn {数据} token.RBRACE

@code{"@}"} 的形符值。
@end deffn

@geindex EQEQUAL() (在 token 模块中)
@anchor{library/token token EQEQUAL}@anchor{392c}
@deffn {数据} token.EQEQUAL

@code{"=="} 的形符值。
@end deffn

@geindex NOTEQUAL() (在 token 模块中)
@anchor{library/token token NOTEQUAL}@anchor{392d}
@deffn {数据} token.NOTEQUAL

@code{"!="} 的形符值。
@end deffn

@geindex LESSEQUAL() (在 token 模块中)
@anchor{library/token token LESSEQUAL}@anchor{392e}
@deffn {数据} token.LESSEQUAL

@code{"<="} 的形符值。
@end deffn

@geindex GREATEREQUAL() (在 token 模块中)
@anchor{library/token token GREATEREQUAL}@anchor{392f}
@deffn {数据} token.GREATEREQUAL

@code{">="} 的形符值。
@end deffn

@geindex TILDE() (在 token 模块中)
@anchor{library/token token TILDE}@anchor{3930}
@deffn {数据} token.TILDE

@code{"~"} 的形符值。
@end deffn

@geindex CIRCUMFLEX() (在 token 模块中)
@anchor{library/token token CIRCUMFLEX}@anchor{3931}
@deffn {数据} token.CIRCUMFLEX

@code{"^"} 的形符值。
@end deffn

@geindex LEFTSHIFT() (在 token 模块中)
@anchor{library/token token LEFTSHIFT}@anchor{3932}
@deffn {数据} token.LEFTSHIFT

@code{"<<"} 的形符值。
@end deffn

@geindex RIGHTSHIFT() (在 token 模块中)
@anchor{library/token token RIGHTSHIFT}@anchor{3933}
@deffn {数据} token.RIGHTSHIFT

@code{">>"} 的形符值。
@end deffn

@geindex DOUBLESTAR() (在 token 模块中)
@anchor{library/token token DOUBLESTAR}@anchor{3934}
@deffn {数据} token.DOUBLESTAR

@code{"**"} 的形符值。
@end deffn

@geindex PLUSEQUAL() (在 token 模块中)
@anchor{library/token token PLUSEQUAL}@anchor{3935}
@deffn {数据} token.PLUSEQUAL

@code{"+="} 的形符值。
@end deffn

@geindex MINEQUAL() (在 token 模块中)
@anchor{library/token token MINEQUAL}@anchor{3936}
@deffn {数据} token.MINEQUAL

@code{"-="} 的形符值。
@end deffn

@geindex STAREQUAL() (在 token 模块中)
@anchor{library/token token STAREQUAL}@anchor{3937}
@deffn {数据} token.STAREQUAL

@code{"*="} 的形符值。
@end deffn

@geindex SLASHEQUAL() (在 token 模块中)
@anchor{library/token token SLASHEQUAL}@anchor{3938}
@deffn {数据} token.SLASHEQUAL

@code{"/="} 的形符值。
@end deffn

@geindex PERCENTEQUAL() (在 token 模块中)
@anchor{library/token token PERCENTEQUAL}@anchor{3939}
@deffn {数据} token.PERCENTEQUAL

@code{"%="} 的形符值。
@end deffn

@geindex AMPEREQUAL() (在 token 模块中)
@anchor{library/token token AMPEREQUAL}@anchor{393a}
@deffn {数据} token.AMPEREQUAL

@code{"&="} 的形符值。
@end deffn

@geindex VBAREQUAL() (在 token 模块中)
@anchor{library/token token VBAREQUAL}@anchor{393b}
@deffn {数据} token.VBAREQUAL

@code{"|="} 的形符值。
@end deffn

@geindex CIRCUMFLEXEQUAL() (在 token 模块中)
@anchor{library/token token CIRCUMFLEXEQUAL}@anchor{393c}
@deffn {数据} token.CIRCUMFLEXEQUAL

@code{"^="} 的形符值。
@end deffn

@geindex LEFTSHIFTEQUAL() (在 token 模块中)
@anchor{library/token token LEFTSHIFTEQUAL}@anchor{393d}
@deffn {数据} token.LEFTSHIFTEQUAL

@code{"<<="} 的形符值。
@end deffn

@geindex RIGHTSHIFTEQUAL() (在 token 模块中)
@anchor{library/token token RIGHTSHIFTEQUAL}@anchor{393e}
@deffn {数据} token.RIGHTSHIFTEQUAL

@code{">>="} 的形符值。
@end deffn

@geindex DOUBLESTAREQUAL() (在 token 模块中)
@anchor{library/token token DOUBLESTAREQUAL}@anchor{393f}
@deffn {数据} token.DOUBLESTAREQUAL

@code{"**="} 的形符值。
@end deffn

@geindex DOUBLESLASH() (在 token 模块中)
@anchor{library/token token DOUBLESLASH}@anchor{3940}
@deffn {数据} token.DOUBLESLASH

@code{"//"} 的形符值。
@end deffn

@geindex DOUBLESLASHEQUAL() (在 token 模块中)
@anchor{library/token token DOUBLESLASHEQUAL}@anchor{3941}
@deffn {数据} token.DOUBLESLASHEQUAL

@code{"//="} 的形符值。
@end deffn

@geindex AT() (在 token 模块中)
@anchor{library/token token AT}@anchor{3942}
@deffn {数据} token.AT

@code{"@@"} 的形符值。
@end deffn

@geindex ATEQUAL() (在 token 模块中)
@anchor{library/token token ATEQUAL}@anchor{3943}
@deffn {数据} token.ATEQUAL

@code{"@@="} 的形符值。
@end deffn

@geindex RARROW() (在 token 模块中)
@anchor{library/token token RARROW}@anchor{3944}
@deffn {数据} token.RARROW

@code{"->"} 的形符值。
@end deffn

@geindex ELLIPSIS() (在 token 模块中)
@anchor{library/token token ELLIPSIS}@anchor{3945}
@deffn {数据} token.ELLIPSIS

@code{"..."} 的形符值。
@end deffn

@geindex COLONEQUAL() (在 token 模块中)
@anchor{library/token token COLONEQUAL}@anchor{3946}
@deffn {数据} token.COLONEQUAL

@code{":="} 的形符值。
@end deffn

@geindex OP() (在 token 模块中)
@anchor{library/token token OP}@anchor{3947}
@deffn {数据} token.OP
@end deffn

@geindex AWAIT() (在 token 模块中)
@anchor{library/token token AWAIT}@anchor{3948}
@deffn {数据} token.AWAIT
@end deffn

@geindex ASYNC() (在 token 模块中)
@anchor{library/token token ASYNC}@anchor{3949}
@deffn {数据} token.ASYNC
@end deffn

@geindex TYPE_IGNORE() (在 token 模块中)
@anchor{library/token token TYPE_IGNORE}@anchor{394a}
@deffn {数据} token.TYPE_IGNORE
@end deffn

@geindex TYPE_COMMENT() (在 token 模块中)
@anchor{library/token token TYPE_COMMENT}@anchor{394b}
@deffn {数据} token.TYPE_COMMENT
@end deffn

@geindex ERRORTOKEN() (在 token 模块中)
@anchor{library/token token ERRORTOKEN}@anchor{394c}
@deffn {数据} token.ERRORTOKEN
@end deffn

@geindex N_TOKENS() (在 token 模块中)
@anchor{library/token token N_TOKENS}@anchor{394d}
@deffn {数据} token.N_TOKENS
@end deffn

@geindex NT_OFFSET() (在 token 模块中)
@anchor{library/token token NT_OFFSET}@anchor{394e}
@deffn {数据} token.NT_OFFSET
@end deffn

C 标记生成器不使用以下标记类型值，但 @ref{11a,,tokenize} 模块需要这些标记类型值。

@geindex COMMENT() (在 token 模块中)
@anchor{library/token token COMMENT}@anchor{394f}
@deffn {数据} token.COMMENT

标记值用于表示注释。
@end deffn

@geindex NL() (在 token 模块中)
@anchor{library/token token NL}@anchor{3950}
@deffn {数据} token.NL

标记值用于表示非终止换行符。 @ref{3915,,NEWLINE} 标记表示 Python 代码逻辑行的结束；当在多条物理线路上继续执行逻辑代码行时，会生成 @code{NL} 标记。
@end deffn

@geindex ENCODING() (在 token 模块中)
@anchor{library/token token ENCODING}@anchor{3951}
@deffn {数据} token.ENCODING

指示用于将源字节解码为文本的编码的标记值。 @ref{d2b,,tokenize.tokenize()} 返回的第一个标记将始终是一个 @code{ENCODING} 标记。
@end deffn


@deffn {数据} token.TYPE_COMMENT

表示类型注释被识别的形符值。 此种形符仅在 @ref{2dd,,ast.parse()} 附带 @code{type_comments=True} 被发起调用时才会产生。
@end deffn


在 3.5 版更改: 补充 @ref{3948,,AWAIT} 和 @ref{3949,,ASYNC} 标记。



在 3.7 版更改: 补充 @ref{394f,,COMMENT} 、 @ref{3950,,NL} 和 @ref{3951,,ENCODING} 标记。



在 3.7 版更改: 移除 @ref{3948,,AWAIT} 和 @ref{3949,,ASYNC} 标记。 "async" 和 "await" 现在被标记为 @ref{3912,,NAME} 标记。



在 3.8 版更改: 增加了 @ref{394b,,TYPE_COMMENT}, @ref{394a,,TYPE_IGNORE}, @ref{3946,,COLONEQUAL}. Added @ref{3948,,AWAIT} 和 @ref{3949,,ASYNC} 形符（它们对于支持解析对于 @ref{2dd,,ast.parse()} 的 @code{feature_version} 设为 6 或更低的较老的 Python 版本是必须的）。


@node keyword --- 检验Python关键字,tokenize --- 对 Python 代码使用的标记解析器,token --- 与Python解析树一起使用的常量,Python 语言服务
@anchor{library/keyword doc}@anchor{3952}@anchor{library/keyword keyword-testing-for-python-keywords}@anchor{3953}@anchor{library/keyword module-keyword}@anchor{a6}
@subsection @code{keyword} --- 检验Python关键字


@geindex keyword (模块)

@strong{源码：} Lib/keyword.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/keyword.py}


__________________________________________________________________


此模块允许 Python 程序确定某个字符串是否为 @ref{153b,,关键字}。

@geindex iskeyword() (在 keyword 模块中)
@anchor{library/keyword keyword iskeyword}@anchor{17af}
@deffn {函数} keyword.iskeyword (s)

如果 @emph{s} 是一个 Python @ref{153b,,关键字} 则返回 @code{True}。
@end deffn

@geindex kwlist() (在 keyword 模块中)
@anchor{library/keyword keyword kwlist}@anchor{3954}
@deffn {数据} keyword.kwlist

包含解释器定义的所有 @ref{153b,,关键字} 的序列。 如果所定义的任何关键字仅在特定 @ref{0,,__future__} 语句生效时被激活，它们也将被包含在内。
@end deffn

@geindex issoftkeyword() (在 keyword 模块中)
@anchor{library/keyword keyword issoftkeyword}@anchor{3955}
@deffn {函数} keyword.issoftkeyword (s)

如果 @emph{s} 是一个 Python 的软 @ref{153b,,关键字} 则返回 @code{True}。


3.9 新版功能.

@end deffn

@geindex softkwlist() (在 keyword 模块中)
@anchor{library/keyword keyword softkwlist}@anchor{3956}
@deffn {数据} keyword.softkwlist

包含解释器定义的所有软 @ref{153b,,关键字} 的序列。 如果所定义的任何软关键字仅在特定 @ref{0,,__future__} 语句生效时被激活，它们也将被包含在内。


3.9 新版功能.

@end deffn

@node tokenize --- 对 Python 代码使用的标记解析器,tabnanny --- 模糊缩进检测,keyword --- 检验Python关键字,Python 语言服务
@anchor{library/tokenize doc}@anchor{3957}@anchor{library/tokenize module-tokenize}@anchor{11a}@anchor{library/tokenize tokenize-tokenizer-for-python-source}@anchor{3958}
@subsection @code{tokenize} --- 对 Python 代码使用的标记解析器


@geindex tokenize (模块)

@strong{源码：} Lib/tokenize.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tokenize.py}


__________________________________________________________________


@ref{11a,,tokenize} 模块为 Python 源代码提供了一个词法扫描器，用 Python 实现。该模块中的扫描器也将注释作为标记返回，这使得它对于实现“漂亮的输出器”非常有用，包括用于屏幕显示的着色器。

为了简化标记流的处理，所有的 @ref{1579,,运算符} 和 @ref{157a,,定界符} 以及 @ref{1770,,Ellipsis} 返回时都会打上通用的 @ref{3947,,OP} 标记。 可以通过 @ref{d2b,,tokenize.tokenize()} 返回的 @ref{b84,,named tuple} 对象的 @code{exact_type} 属性来获得确切的标记类型。

@menu
* 对输入进行解析标记:: 
* 命令行用法: 命令行用法<3>. 
* 示例: 示例<45>. 

@end menu

@node 对输入进行解析标记,命令行用法<3>,,tokenize --- 对 Python 代码使用的标记解析器
@anchor{library/tokenize tokenizing-input}@anchor{3959}
@subsubsection 对输入进行解析标记


主要的入口是一个生成器 @ref{a8c,,generator}:

@geindex tokenize() (在 tokenize 模块中)
@anchor{library/tokenize tokenize tokenize}@anchor{d2b}
@deffn {函数} tokenize.tokenize (readline)

生成器 @ref{d2b,,tokenize()} 需要一个 @emph{readline} 参数，这个参数必须是一个可调用对象，且能提供与文件对象的 @ref{1883,,io.IOBase.readline()} 方法相同的接口。每次调用这个函数都要 返回字节类型输入的一行数据。

生成器产生 5 个具有这些成员的元组：令牌类型；令牌字符串；指定令牌在源中开始的行和列的 2 元组 @code{(srow, scol)} ；指定令牌在源中结束的行和列的 2 元组 @code{(erow, ecol)} ；以及发现令牌的行。所传递的行（最后一个元组项）是 @emph{实际的} 行。 5 个元组以 @ref{b84,,named tuple} 的形式返回，字段名是： @code{type string start end line} 。

返回的 @ref{b84,,named tuple} 有一个额外的属性，名为 @code{exact_type} ，包含了 @ref{3947,,OP} 标记的确切操作符类型。 对于所有其他标记类型， @code{exact_type} 等于命名元组的 @code{type} 字段。


在 3.1 版更改: 增加了对 named tuple 的支持。



在 3.3 版更改: 添加了对 @code{exact_type} 的支持。


根据:pep:@cite{263} ， @ref{d2b,,tokenize()} 通过寻找 UTF-8 BOM 或编码 cookie 来确定文件的源编码。
@end deffn

@geindex generate_tokens() (在 tokenize 模块中)
@anchor{library/tokenize tokenize generate_tokens}@anchor{11b4}
@deffn {函数} tokenize.generate_tokens (readline)

对读取 unicode 字符串而不是字节的源进行标记。

和 @ref{d2b,,tokenize()} 一样， @emph{readline} 参数是一个返回单行输入的可调用参数。然而， @ref{11b4,,generate_tokens()} 希望 @emph{readline} 返回一个 str 对象而不是字节。

其结果是一个产生具名元组的的迭代器，与 @ref{d2b,,tokenize()} 完全一样。 它不会产生 @ref{3951,,ENCODING} 标记。
@end deffn

所有来自 @ref{119,,token} 模块的常量也可从 @ref{11a,,tokenize} 导出。

提供了另一个函数来逆转标记化过程。这对于创建对脚本进行标记、修改标记流并写回修改后脚本的工具很有用。

@geindex untokenize() (在 tokenize 模块中)
@anchor{library/tokenize tokenize untokenize}@anchor{395a}
@deffn {函数} tokenize.untokenize (iterable)

将令牌转换为 Python 源代码。 @emph{iterable} 必须返回至少有两个元素的序列，即令牌类型和令牌字符串。任何额外的序列元素都会被忽略。

重构的脚本以单个字符串的形式返回。 结果被保证为标记回与输入相匹配，因此转换是无损的，并保证来回操作。 该保证只适用于标记类型和标记字符串，因为标记之间的间距（列位置）可能会改变。

它返回字节，使用 @ref{3951,,ENCODING} 标记进行编码，这是由 @ref{d2b,,tokenize()} 输出的第一个标记序列。如果输入中没有编码令牌，它将返回一个字符串。
@end deffn

@ref{d2b,,tokenize()} 需要检测它所标记源文件的编码。它用来做这件事的函数是可用的：

@geindex detect_encoding() (在 tokenize 模块中)
@anchor{library/tokenize tokenize detect_encoding}@anchor{1e25}
@deffn {函数} tokenize.detect_encoding (readline)

@ref{1e25,,detect_encoding()} 函数用于检测解码 Python 源文件时应使用的编码。它需要一个参数， readline ，与 @ref{d2b,,tokenize()} 生成器的使用方式相同。

它最多调用 readline 两次，并返回所使用的编码（作为一个字符串）和它所读入的任何行（不是从字节解码的）的 list 。

它从 UTF-8 BOM 或编码 cookie 的存在中检测编码格式，如 
@geindex Python 提高建议; PEP 263
PEP 263@footnote{https://www.python.org/dev/peps/pep-0263} 所指明的。 如果 BOM 和 cookie 都存在，但不一致，将会引发 @ref{562,,SyntaxError}。 请注意，如果找到 BOM ，将返回 @code{'utf-8-sig'} 作为编码格式。

如果没有指定编码，那么将返回默认的 @code{'utf-8'} 编码.

使用 @ref{1e24,,open()} 来打开 Python 源文件：它使用 @ref{1e25,,detect_encoding()} 来检测文件编码。
@end deffn

@geindex open() (在 tokenize 模块中)
@anchor{library/tokenize tokenize open}@anchor{1e24}
@deffn {函数} tokenize.open (filename)

使用由 @ref{1e25,,detect_encoding()} 检测到的编码，以只读模式打开一个文件。


3.2 新版功能.

@end deffn

@geindex TokenError
@anchor{library/tokenize tokenize TokenError}@anchor{395b}
@deffn {例外} tokenize.TokenError

当文件中任何地方没有完成 docstring 或可能被分割成几行的表达式时触发，例如:

@example
"""Beginning of
docstring
@end example

或者：

@example
[1,
 2,
 3
@end example
@end deffn

注意，未封闭的单引号字符串不会导致错误发生。它们被标记为 @ref{394c,,ERRORTOKEN} ，然后是其内容的标记化。

@node 命令行用法<3>,示例<45>,对输入进行解析标记,tokenize --- 对 Python 代码使用的标记解析器
@anchor{library/tokenize command-line-usage}@anchor{395c}@anchor{library/tokenize tokenize-cli}@anchor{395d}
@subsubsection 命令行用法



3.3 新版功能.


@ref{11a,,tokenize} 模块可以作为一个脚本从命令行执行。这很简单。

@example
python -m tokenize [-e] [filename.py]
@end example

可以接受以下选项：

@geindex tokenize command line option; -h
@geindex tokenize command line option; --help
@anchor{library/tokenize cmdoption-tokenize-h}@anchor{395e}
@deffn {程序选项} @w{-}h, @w{-}@w{-}help

显示此帮助信息并退出
@end deffn

@geindex tokenize command line option; -e
@geindex tokenize command line option; --exact
@anchor{library/tokenize cmdoption-tokenize-e}@anchor{395f}
@deffn {程序选项} @w{-}e, @w{-}@w{-}exact

使用确切的类型显示令牌名称
@end deffn

如果 @code{filename.py} 被指定，其内容会被标记到 stdout 。否则，标记化将在 stdin 上执行。

@node 示例<45>,,命令行用法<3>,tokenize --- 对 Python 代码使用的标记解析器
@anchor{library/tokenize examples}@anchor{3960}
@subsubsection 示例


脚本改写器的例子，它将 float 文本转换为 Decimal 对象：。

@example
from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
from io import BytesIO

def decistmt(s):
    """Substitute Decimals for floats in a string of statements.

    >>> from decimal import Decimal
    >>> s = 'print(+21.3e-5*-.1234/81.7)'
    >>> decistmt(s)
    "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"

    The format of the exponent is inherited from the platform C library.
    Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
    we're only showing 12 digits, and the 13th isn't close to 5, the
    rest of the output should be platform-independent.

    >>> exec(s)  #doctest: +ELLIPSIS
    -3.21716034272e-0...7

    Output from calculations with Decimal should be identical across all
    platforms.

    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7
    """
    result = []
    g = tokenize(BytesIO(s.encode('utf-8')).readline)  # tokenize the string
    for toknum, tokval, _, _, _ in g:
        if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result).decode('utf-8')
@end example

从命令行进行标记化的例子。 脚本:

@example
def say_hello():
    print("Hello, World!")

say_hello()
@end example

将被标记为以下输出，其中第一列是发现标记的行 / 列坐标范围，第二列是标记的名称，最后一列是标记的值（如果有）。

@example
$ python -m tokenize hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          OP             '('
1,14-1,15:          OP             ')'
1,15-1,16:          OP             ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           OP             '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          OP             ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         '@w{'}
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           OP             '('
4,10-4,11:          OP             ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      '@w{'}
@end example

可以使用 @ref{395f,,-e} 选项来显示确切的标记类型名称。

@example
$ python -m tokenize -e hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          LPAR           '('
1,14-1,15:          RPAR           ')'
1,15-1,16:          COLON          ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           LPAR           '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          RPAR           ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         '@w{'}
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           LPAR           '('
4,10-4,11:          RPAR           ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      '@w{'}
@end example

以编程方式对文件进行标记的例子，用 @ref{11b4,,generate_tokens()} 读取 unicode 字符串而不是字节:

@example
import tokenize

with tokenize.open('hello.py') as f:
    tokens = tokenize.generate_tokens(f.readline)
    for token in tokens:
        print(token)
@end example

或者通过 @ref{d2b,,tokenize()} 直接读取字节数据:

@example
import tokenize

with open('hello.py', 'rb') as f:
    tokens = tokenize.tokenize(f.readline)
    for token in tokens:
        print(token)
@end example

@node tabnanny --- 模糊缩进检测,pyclbr --- Python 模块浏览器支持,tokenize --- 对 Python 代码使用的标记解析器,Python 语言服务
@anchor{library/tabnanny doc}@anchor{3961}@anchor{library/tabnanny module-tabnanny}@anchor{100}@anchor{library/tabnanny tabnanny-detection-of-ambiguous-indentation}@anchor{3962}
@subsection @code{tabnanny} --- 模糊缩进检测


@geindex tabnanny (模块)

@c rudimentary documentation based on module comments

@strong{源代码:} Lib/tabnanny.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tabnanny.py}


__________________________________________________________________


目前，该模块旨在作为脚本调用。但是可以使用下面描述的 @ref{3963,,check()} 函数将其导入IDE。

@cartouche
@quotation 注解 
此模块提供的API可能会在将来的版本中更改；此类更改可能无法向后兼容。
@end quotation
@end cartouche

@geindex check() (在 tabnanny 模块中)
@anchor{library/tabnanny tabnanny check}@anchor{3963}
@deffn {函数} tabnanny.check (file_or_dir)

如果 @emph{file_or_dir} 是目录而非符号链接，则递归地在名为 @emph{file_or_dir} 的目录树中下行，沿途检查所有 @code{.py} 文件。 如果 @emph{file_or_dir} 是一个普通 Python 源文件，将检查其中的空格相关问题。 诊断消息将使用 @ref{97a,,print()} 函数写入到标准输出。
@end deffn

@geindex verbose() (在 tabnanny 模块中)
@anchor{library/tabnanny tabnanny verbose}@anchor{3964}
@deffn {数据} tabnanny.verbose

此旗标指明是否打印详细消息。 如果作为脚本调用则是通过 @code{-v} 选项来增加。
@end deffn

@geindex filename_only() (在 tabnanny 模块中)
@anchor{library/tabnanny tabnanny filename_only}@anchor{3965}
@deffn {数据} tabnanny.filename_only

此旗标指明是否只打印包含空格相关问题文件的文件名。 如果作为脚本调用则是通过 @code{-q} 选项来设为真值。
@end deffn

@geindex NannyNag
@anchor{library/tabnanny tabnanny NannyNag}@anchor{3966}
@deffn {例外} tabnanny.NannyNag

如果检测到模糊缩进则由 @ref{3967,,process_tokens()} 引发。 在 @ref{3963,,check()} 中捕获并处理。
@end deffn

@geindex process_tokens() (在 tabnanny 模块中)
@anchor{library/tabnanny tabnanny process_tokens}@anchor{3967}
@deffn {函数} tabnanny.process_tokens (tokens)

此函数由 @ref{3963,,check()} 用来处理由 @ref{11a,,tokenize} 模块所生成的标记。
@end deffn

@c XXX document errprint, format_witnesses, Whitespace, check_equal, indents,
@c reset_globals


@subsubheading 参见



@table @asis

@item 模块 @ref{11a,,tokenize}

用于Python源代码的词法扫描程序。
@end table


@node pyclbr --- Python 模块浏览器支持,py_compile --- 编译 Python 源文件,tabnanny --- 模糊缩进检测,Python 语言服务
@anchor{library/pyclbr doc}@anchor{3968}@anchor{library/pyclbr module-pyclbr}@anchor{d8}@anchor{library/pyclbr pyclbr-python-module-browser-support}@anchor{3969}
@subsection @code{pyclbr} --- Python 模块浏览器支持


@geindex pyclbr (模块)

@strong{源代码:} Lib/pyclbr.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pyclbr.py}


__________________________________________________________________


@ref{d8,,pyclbr} 模块提供了对于以 Python 编写的模块中定义的函数、类和方法的受限信息。 这种信息足够用来实现一个模块浏览器。 这种信息是从 Python 源代码中直接提取而非通过导入模块，因此该模块可以安全地用于不受信任的代码。 此限制使得非 Python 实现的模块无法使用此模块，包括所有标准和可选的扩展模块。

@geindex readmodule() (在 pyclbr 模块中)
@anchor{library/pyclbr pyclbr readmodule}@anchor{12db}
@deffn {函数} pyclbr.readmodule (module, path=None)

返回一个将模块层级的类名映射到类描述器的字典。 如果可能，将会包括已导入基类的描述器。 形参 @emph{module} 为要读取模块名称的字符串；它可能是某个包内部的模块名称。 @emph{path} 如果给出则为添加到 @code{sys.path} 开头的目录路径序列，它会被用于定位模块的源代码。

此函数为原始接口，仅保留用于向下兼容。 它会返回以下内容的过滤版本。
@end deffn

@geindex readmodule_ex() (在 pyclbr 模块中)
@anchor{library/pyclbr pyclbr readmodule_ex}@anchor{12dc}
@deffn {函数} pyclbr.readmodule_ex (module, path=None)

返回一个基于字典的树，其中包含与模块中每个用 @code{def} 或 @code{class} 语句定义的函数和类相对应的函数和类描述器。 被返回的字典会将模块层级的函数和类名映射到它们的描述器。 嵌套的对象会被输入到它们的上级子目录中。 与 readmodule 一样，@emph{module} 指明要读取的模块而 @emph{path} 会被添加到 sys.path。 如果被读取的模块是一个包，则返回的字典将具有 @code{'__path__'} 键，其值是一个包含包搜索路径的列表。
@end deffn


3.7 新版功能: 嵌套定义的描述器。 它们通过新的子属性来访问。 每个定义都会有一个新的上级属性。


这些函数所返回的描述器是 Function 和 Class 类的实例。 用户不应自行创建这些类的实例。

@menu
* Function 对象:: 
* Class 对象:: 

@end menu

@node Function 对象,Class 对象,,pyclbr --- Python 模块浏览器支持
@anchor{library/pyclbr function-objects}@anchor{396a}@anchor{library/pyclbr pyclbr-function-objects}@anchor{396b}
@subsubsection Function 对象


@code{Function} 类的实例描述了由  def 语句所定义的函数。 它们具有下列属性:

@geindex file (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function file}@anchor{396c}
@deffn {属性} Function.file

函数定义所在的文件名称。
@end deffn

@geindex module (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function module}@anchor{396d}
@deffn {属性} Function.module

定义了所描述函数的模块名称。
@end deffn

@geindex name (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function name}@anchor{396e}
@deffn {属性} Function.name

函数名称。
@end deffn

@geindex lineno (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function lineno}@anchor{396f}
@deffn {属性} Function.lineno

定义在文件中起始位置的行号。
@end deffn

@geindex parent (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function parent}@anchor{3970}
@deffn {属性} Function.parent

对于最高层级函数为 None。 对于嵌套函数则为上级函数。


3.7 新版功能.

@end deffn

@geindex children (pyclbr.Function 属性)
@anchor{library/pyclbr pyclbr Function children}@anchor{3971}
@deffn {属性} Function.children

将名称映射到嵌套函数和类描述器的字典。


3.7 新版功能.

@end deffn

@node Class 对象,,Function 对象,pyclbr --- Python 模块浏览器支持
@anchor{library/pyclbr class-objects}@anchor{3972}@anchor{library/pyclbr pyclbr-class-objects}@anchor{3973}
@subsubsection Class 对象


@code{Class} 类的实例描述了由 class 语句所定义的类。 它们具有与 Function 对象相同的属性以及两个额外属性。

@geindex file (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class file}@anchor{3974}
@deffn {属性} Class.file

类定义所在的文件名称。
@end deffn

@geindex module (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class module}@anchor{3975}
@deffn {属性} Class.module

定义了所描述类的模块名称。
@end deffn

@geindex name (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class name}@anchor{3976}
@deffn {属性} Class.name

类名称。
@end deffn

@geindex lineno (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class lineno}@anchor{3977}
@deffn {属性} Class.lineno

定义在文件中起始位置的行号。
@end deffn

@geindex parent (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class parent}@anchor{3978}
@deffn {属性} Class.parent

对于最高层级类为 None。 对于嵌套类则为上级类。


3.7 新版功能.

@end deffn

@geindex children (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class children}@anchor{3979}
@deffn {属性} Class.children

将名称映射到嵌套函数和类描述器的字典。


3.7 新版功能.

@end deffn

@geindex super (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class super}@anchor{397a}
@deffn {属性} Class.super

一个 @code{Class} 对象的列表，它们描述了所描述类的直接基类。 被命名为超类但无法被 @ref{12dc,,readmodule_ex()} 发现的类会作为类名字符串而非 @code{Class} 对象列出。
@end deffn

@geindex methods (pyclbr.Class 属性)
@anchor{library/pyclbr pyclbr Class methods}@anchor{397b}
@deffn {属性} Class.methods

一个将方法名映射到行号的字典。 此属性可从更新的子目录中获取，仅保留用于向下兼容。
@end deffn

@node py_compile --- 编译 Python 源文件,compileall --- 字节编译 Python 库,pyclbr --- Python 模块浏览器支持,Python 语言服务
@anchor{library/py_compile doc}@anchor{397c}@anchor{library/py_compile module-py_compile}@anchor{d7}@anchor{library/py_compile py-compile-compile-python-source-files}@anchor{397d}
@subsection @code{py_compile} --- 编译 Python 源文件


@geindex py_compile (模块)

@c documentation based on module docstrings

@strong{源代码:} Lib/py_compile.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/py_compile.py}

@geindex file; byte-code


__________________________________________________________________


@ref{d7,,py_compile} 模块提供了用来从源文件生成字节码的函数和另一个用于当模块源文件作为脚本被调用时的函数。

虽然不太常用，但这个函数在安装共享模块时还是很有用的，特别是当一些用户可能没有权限在包含源代码的目录中写字节码缓存文件时。

@geindex PyCompileError
@anchor{library/py_compile py_compile PyCompileError}@anchor{397e}
@deffn {例外} py_compile.PyCompileError

当编译文件过程中发生错误时，抛出的异常。
@end deffn

@geindex compile() (在 py_compile 模块中)
@anchor{library/py_compile py_compile compile}@anchor{34a}
@deffn {函数} py_compile.compile (file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)

将源文件编译成字节码并写出字节码缓存文件。 源代码从名为 @emph{file} 的文件中加载。 字节码会写入到 @emph{cfile}，默认为 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}/
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488} 路径，以 @code{.pyc} 结尾。 例如，如果 @emph{file} 是 @code{/foo/bar/baz.py} 则对于 Python 3.2 @emph{cfile} 将默认为 @code{/foo/bar/__pycache__/baz.cpython-32.pyc}。 如果指定了 @emph{dfile}，则在错误信息中它将代替 @emph{file} 作为源文件的名称。 如果 @emph{doraise} 为真值，则当编译 @emph{file} 遇到错误时将会引发 @ref{397e,,PyCompileError}。 如果 @emph{doraise} 为假值（默认），则将错误信息写入到 @code{sys.stderr}，但不会引发异常。 此函数返回编译后字节码文件的路径，即 @emph{cfile} 所使用的值。

@emph{doraise} 和 @emph{quiet} 参数确定在编译文件时如何处理错误。 如果 @emph{quiet} 为 0 或 1，并且 @emph{doraise} 为假值，则会启用默认行为：写入错误信息到 @code{sys.stderr}，并且函数将返回 @code{None} 而非一个路径。 如果 @emph{doraise} 为真值，则将改为引发 @ref{397e,,PyCompileError}。 但是如果 @emph{quiet} 为 2，则不会写入消息，并且 @emph{doraise} 也不会有效果。

如果 @emph{cfile} 所表示（显式指定或计算得出）的路径为符号链接或非常规文件，则将引发 @ref{a42,,FileExistsError}。 此行为是用来警告如果允许写入编译后字节码文件到这些路径则导入操作将会把它们转为常规文件。 这是使用文件重命名来将最终编译后字节码文件放置到位以防止并发文件写入问题的导入操作的附带效果。

@emph{optimize} 控制优化级别并会被传给内置的 @ref{2ee,,compile()} 函数。 默认值 @code{-1} 表示选择当前解释器的优化级别。

@emph{invalidation_mode} 应当是 @ref{397f,,PycInvalidationMode} 枚举的成员，它控制在运行时如何让已生成的字节码缓存失效。 如果设置了 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 环境变量则默认值为 @ref{3980,,PycInvalidationMode.CHECKED_HASH}，否则默认值为 @ref{3981,,PycInvalidationMode.TIMESTAMP}。


在 3.2 版更改: 将 @emph{cfile} 的默认值改成与 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 兼容。 之前的默认值是 @emph{file} + @code{'c'} (如果启用优化则为 @code{'o'})。 同时也添加了 @emph{optimize} 形参。



在 3.4 版更改: 将代码更改为使用 @ref{9a,,importlib} 执行字节码缓存文件写入。 这意味着文件创建/写入的语义现在与 @ref{9a,,importlib} 所做的相匹配，例如权限、写入和移动语义等等。 同时也添加了当 @emph{cfile} 为符号链接或非常规文件时引发 @ref{a42,,FileExistsError} 的预警设置。



在 3.7 版更改: @emph{invalidation_mode} 形参是根据 
@geindex Python 提高建议; PEP 552
PEP 552@footnote{https://www.python.org/dev/peps/pep-0552} 的描述添加的。 如果设置了 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 环境变量，@emph{invalidation_mode} 将被强制设为 @ref{3980,,PycInvalidationMode.CHECKED_HASH}。



在 3.7.2 版更改: 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 环境变量不会再覆盖 @emph{invalidation_mode} 参数的值，而改为确定其默认值。



在 3.8 版更改: 增加了 @emph{quiet} 形参。

@end deffn

@geindex PycInvalidationMode (py_compile 中的类)
@anchor{library/py_compile py_compile PycInvalidationMode}@anchor{397f}
@deffn {类} py_compile.PycInvalidationMode

一个由可用方法组成的枚举，解释器可以用来确定字节码文件是否与源文件保持一致。 @code{.pyc} 文件在其标头中指明了所需的失效模式。 请参阅 @ref{442,,已缓存字节码的失效} 了解有关 Python 在运行时如何让 @code{.pyc} 文件失效的更多信息。


3.7 新版功能.


@geindex TIMESTAMP (py_compile.PycInvalidationMode 属性)
@anchor{library/py_compile py_compile PycInvalidationMode TIMESTAMP}@anchor{3981}
@deffn {属性} TIMESTAMP

@code{.pyc} 文件包括时间戳和源文件的大小，Python 将在运行时将其与源文件的元数据进行比较以确定 @code{.pyc} 文件是否需要重新生成。
@end deffn

@geindex CHECKED_HASH (py_compile.PycInvalidationMode 属性)
@anchor{library/py_compile py_compile PycInvalidationMode CHECKED_HASH}@anchor{3980}
@deffn {属性} CHECKED_HASH

@code{.pyc} 文件包括源文件内容的哈希值，Python 将在运行时将其与源文件内容进行比较以确定 @code{.pyc} 文件是否需要重新生成。
@end deffn

@geindex UNCHECKED_HASH (py_compile.PycInvalidationMode 属性)
@anchor{library/py_compile py_compile PycInvalidationMode UNCHECKED_HASH}@anchor{3982}
@deffn {属性} UNCHECKED_HASH

类似于 @ref{3980,,CHECKED_HASH}，@code{.pyc} 文件包括源文件内容的哈希值。 但是，Python 将在运行时假定 @code{.pyc} 文件是最新的而完全不会将 @code{.pyc} 与源文件进行验证。

此选项适用于 @code{.pycs} 由 Python 以外的某个系统例如构建系统来确保最新的情况。
@end deffn
@end deffn

@geindex main() (在 py_compile 模块中)
@anchor{library/py_compile py_compile main}@anchor{3983}
@deffn {函数} py_compile.main (args=None)

编译多个源文件。 在 @emph{args} 中（或者当 @emph{args} 为 @code{None} 时则是在命令行中）指定的文件会被编译并将结果字节码以正常方式来缓存。 此函数不会搜索目录结构来定位源文件；它只编译显式指定的文件。 如果 @code{'-'} 是 args 中唯一的值，则会从标准输入获取文件列表。


在 3.2 版更改: 添加了对 @code{'-'} 的支持。

@end deffn

当此模块作为脚本运行时，会使用 @ref{3983,,main()} 来编译命令行中指定的所有文件。 如果某个文件无法被编译则退出状态将为非零值。


@subsubheading 参见



@table @asis

@item 模块 @ref{20,,compileall}

编译一个目录树中所有 Python 源文件的工具。
@end table


@node compileall --- 字节编译 Python 库,dis --- Python 字节码反汇编器,py_compile --- 编译 Python 源文件,Python 语言服务
@anchor{library/compileall doc}@anchor{3984}@anchor{library/compileall compileall-byte-compile-python-libraries}@anchor{3985}@anchor{library/compileall module-compileall}@anchor{20}
@subsection @code{compileall} --- 字节编译 Python 库


@geindex compileall (模块)

@strong{源代码:} Lib/compileall.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/compileall.py}


__________________________________________________________________


这个模块提供了一些工具函数来支持安装 Python 库。 这些函数可以编译一个目录树中的 Python 源文件。 这个模块可被用来在安装库时创建缓存的字节码文件，这使得它们对于没有库目录写入权限的用户来说也是可用的。

@menu
* 使用命令行:: 
* 公有函数:: 

@end menu

@node 使用命令行,公有函数,,compileall --- 字节编译 Python 库
@anchor{library/compileall command-line-use}@anchor{3986}
@subsubsection 使用命令行


此模块可以作为脚本运行 (使用 @code{python -m compileall}) 来编译 Python 源代码。

@geindex compileall command line option; directory ...
@geindex compileall command line option; file ...
@anchor{library/compileall cmdoption-compileall-arg-directory}@anchor{3987}
@deffn {程序选项} directory ...
@anchor{library/compileall cmdoption-compileall-arg-file}@anchor{3988}
@deffnx {程序选项} file ...

位置参数是要编译的文件或包含源文件的目录，目录将被递归地遍历。 如果没有给出参数，则其行为如同使用了命令行 @code{-l <directories from sys.path>}。
@end deffn

@geindex compileall command line option; -l
@anchor{library/compileall cmdoption-compileall-l}@anchor{3989}
@deffn {程序选项} @w{-}l

不要递归到子目录，只编译直接包含在指明或隐含的目录中的源代码文件。
@end deffn

@geindex compileall command line option; -f
@anchor{library/compileall cmdoption-compileall-f}@anchor{398a}
@deffn {程序选项} @w{-}f

强制重新构建即使时间戳是最新的。
@end deffn

@geindex compileall command line option; -q
@anchor{library/compileall cmdoption-compileall-q}@anchor{398b}
@deffn {程序选项} @w{-}q

不要打印已编译文件的列表。 如果传入一次，则错误消息仍将被打印。 如果传入两次 (@code{-qq})，所有输出都会被屏蔽。
@end deffn

@geindex compileall command line option; -d destdir
@anchor{library/compileall cmdoption-compileall-d}@anchor{398c}
@deffn {程序选项} @w{-}d destdir

要附加到每个被编译文件的路径之前的目录。 这将出现在编译时回溯信息中，并且还会被编译到字节码文件中，届时它将在字节码文件被执行而源文件已不存在的情况下被用于回溯和其他消息。
@end deffn

@geindex compileall command line option; -s strip_prefix
@anchor{library/compileall cmdoption-compileall-s}@anchor{398d}
@deffn {程序选项} @w{-}s strip_prefix
@end deffn

@geindex compileall command line option; -p prepend_prefix
@anchor{library/compileall cmdoption-compileall-p}@anchor{398e}
@deffn {程序选项} @w{-}p prepend_prefix

移除 (@code{-s}) 或添加 (@code{-p}) 记录在 @code{.pyc} 文件中的给定路径前缀。 不可与 @code{-d} 一同使用。
@end deffn

@geindex compileall command line option; -x regex
@anchor{library/compileall cmdoption-compileall-x}@anchor{398f}
@deffn {程序选项} @w{-}x regex

regex 会被用于搜索每个要执行编译的文件的完整路径，而如果 regex 产生了一个匹配，则相应文件会被跳过。
@end deffn

@geindex compileall command line option; -i list
@anchor{library/compileall cmdoption-compileall-i}@anchor{3990}
@deffn {程序选项} @w{-}i list

读取文件 @code{list} 并将其包含的每一行添加到要编译的文件和目录列表中。 如果 @code{list} 为 @code{-}，则从 @code{stdin} 读取行。
@end deffn

@geindex compileall command line option; -b
@anchor{library/compileall cmdoption-compileall-b}@anchor{3991}
@deffn {程序选项} @w{-}b

将字节码写入到它们的传统位置和名称，这可能会覆盖由另一版本的 Python 所创建的字节码文件。 默认是将文件写入到它们的 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 位置和名称，这允许来自多个版本的 Python 字节码文件共存。
@end deffn

@geindex compileall command line option; -r
@anchor{library/compileall cmdoption-compileall-r}@anchor{3992}
@deffn {程序选项} @w{-}r

控制子目录的最大递归层级。 如果给出此选项，则 @code{-l} 选项将不会被考虑。 @code{python -m compileall <directory> -r 0} 等价于 @code{python -m compileall <directory> -l}。
@end deffn

@geindex compileall command line option; -j N
@anchor{library/compileall cmdoption-compileall-j}@anchor{3993}
@deffn {程序选项} @w{-}j N

使用 @emph{N} 个工作者来编译给定目录中的文件。 如果使用 @code{0}，则将使用 @ref{973,,os.cpu_count()} 的结果。
@end deffn

@geindex compileall command line option; --invalidation-mode [timestamp|checked-hash|unchecked-hash]
@anchor{library/compileall cmdoption-compileall-invalidation-mode}@anchor{3994}
@deffn {程序选项} @w{-}@w{-}invalidation@w{-}mode [timestamp|checked@w{-}hash|unchecked@w{-}hash]

控制生成的字节码文件在运行时的失效规则。 值为`@w{`}timestamp`@w{`}，意味着将生成嵌入了源时间戳和大小的 @code{.pyc} 文件。 @code{checked-hash} 和 @code{unchecked-hash} 等值将导致生成基于哈希的 pyc。 基于哈希的 pyc 嵌入了源文件内容的哈希值而不是时间戳。 请参阅 @ref{442,,已缓存字节码的失效} 了解有关 Python 在运行时如何验证字节码缓存文件的更多信息。 如果未设置 
@geindex SOURCE_DATE_EPOCH
@geindex 环境变量; SOURCE_DATE_EPOCH
@code{SOURCE_DATE_EPOCH} 环境变量则默认值为 @code{timestamp}，而如果设置了 @code{SOURCE_DATE_EPOCH} 则为 @code{checked-hash}。
@end deffn

@geindex compileall command line option; -o level
@anchor{library/compileall cmdoption-compileall-o}@anchor{3995}
@deffn {程序选项} @w{-}o level

使用给定的优化级别进行编译。 可以多次使用来一次性地针对多个级别进行编译 (例如，@code{compileall -o 1 -o 2})。
@end deffn

@geindex compileall command line option; -e dir
@anchor{library/compileall cmdoption-compileall-e}@anchor{3996}
@deffn {程序选项} @w{-}e dir

忽略指向给定目录之外的符号链接。
@end deffn

@geindex compileall command line option; --hardlink-dupes
@anchor{library/compileall cmdoption-compileall-hardlink-dupes}@anchor{3997}
@deffn {程序选项} @w{-}@w{-}hardlink@w{-}dupes

如果两个不同优化级别的 @code{.pyc} 文件具有相同的内容，则使用硬链接来合并重复的文件。
@end deffn


在 3.2 版更改: 增加了 @code{-i}, @code{-b} 和 @code{-h} 选项。



在 3.5 版更改: 增加了 @code{-j}, @code{-r} 和 @code{-qq} 选项。 @code{-q} 选项改为多级别值。 @code{-b} 将总是产生以 @code{.pyc} 为后缀的字节码文件，而不是 @code{.pyo}。



在 3.7 版更改: 增加了 @code{--invalidation-mode} 选项。



在 3.9 版更改: 增加了 @code{-s}, @code{-p}, @code{-e} 和 @code{--hardlink-dupes} 选项。 将默认的递归限制从 10 提高到 @ref{f42,,sys.getrecursionlimit()}。 增加允许多次指定 @code{-o} 选项。


没有可以控制 @ref{2ee,,compile()} 函数所使用的优化级别的命令行选项，因为 Python 解释器本身已经提供了该选项: @code{python -O -m compileall}。

类似地，@ref{2ee,,compile()} 函数会遵循 @ref{298,,sys.pycache_prefix} 设置。 所生成的字节码缓存将仅当 @ref{2ee,,compile()} 附带与将在运行时使用的相同 @ref{298,,sys.pycache_prefix} 时可用（如果存在该设置）。

@node 公有函数,,使用命令行,compileall --- 字节编译 Python 库
@anchor{library/compileall public-functions}@anchor{3998}
@subsubsection 公有函数


@geindex compile_dir() (在 compileall 模块中)
@anchor{library/compileall compileall compile_dir}@anchor{483}
@deffn {函数} compileall.compile_dir (dir, maxlevels=sys.getrecursionlimit(), ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)

递归地深入名为 @emph{dir} 的目录树，在途中编译所有 @code{.py} 文件。 如果所有文件都编译成功则返回真值，否则返回假值。

@emph{maxlevels} 形参被用来限制递归深度；它默认为 @code{sys.getrecursionlimit()}。

如果给出了 @emph{ddir}，它会被附加到每个被编译的文件的路径之前以便在编译时回溯中使用，同时还会被编译到字节码文件中，届时它将在字节码文件被执行而源文件已不存在的情况下被用于回溯和其他消息中。

如果 @emph{force} 为真值，则即使时间戳为最新模块也会被重新编译。

如果给出了 @emph{rx}，则它的 @code{search} 方法会在准备编译的每个文件的完整路径上被调用，并且如果它返回真值，则该文件会被跳过。 这可被用来排除与一个正则表达式相匹配的文件，正则表达式将以 @ref{98c,,re.Pattern} 对象的形式给出。

如果 @emph{quiet} 为 @code{False} 或 @code{0} (默认值)，则文件名和其他信息将被打印到标准输出。 如果设为 @code{1}，则只打印错误。 如果设为 @code{2}，则屏蔽所有输出。

如果 @emph{legacy} 为真值，则将字节码文件写入到它们的传统位置和名称，这可能会覆盖由另一版本的 Python 所创建的字节码文件。 默认是将文件写入到它们的 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 位置和名称，这允许来自多个版本的 Python 字节码文件共存。

@emph{optimize} 指明编译器的优化级别。 它会被传给内置 @ref{2ee,,compile()} 函数。 还接受一个优化层别列表这将在单次调用中多次编译一个 @code{.py} 文件。

参数 @emph{workers} 指明要使用多少个工作进程来并行编译文件。 默认设置不使用多个工作进程。 如果平台不能使用多个工作进程而又给出了 @emph{workers} 参数，则将回退为使用顺序编译。 如果 @emph{workers} 为 0，则会使用系统的核心数量。 如果 @emph{workers} 小于 @code{0}，则会引发 @ref{16d,,ValueError}。

@emph{invalidation_mode} 应为 @ref{397f,,py_compile.PycInvalidationMode} 枚举的成员之一并将控制所生成的 pyc 在运行时以何种方式验证是否失效。

@emph{stripdir}, @emph{prependdir} 和 @emph{limit_sl_dest} 参数分别对应上述的 @code{-s}, @code{-p} 和 @code{-e} 选项。 它们可以指定为 @code{str}, @code{bytes} 或 @ref{5ee,,os.PathLike}。

如果 @emph{hardlink_dupes} 为真值且两个使用不同优化级别的 @code{.pyc} 文件具有相同的内容，则会使用硬链接来合并重复的文件。


在 3.2 版更改: 增加了 @emph{legacy} 和 @emph{optimize} 形参。



在 3.5 版更改: 增加了 @emph{workers} 形参。



在 3.5 版更改: @emph{quiet} 形参已改为多级别值。



在 3.5 版更改: @emph{legacy} 形参将只写入 @code{.pyc} 文件而非 @code{.pyo} 文件，无论 @emph{optimize} 的值是什么。



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。



在 3.7 版更改: 增加了 @emph{invalidation_mode} 形参。



在 3.7.2 版更改: @emph{invalidation_mode} 形参的默认值更新为 None。



在 3.8 版更改: 将 @emph{workers} 设为 0 现在将会选择最优核心数量。



在 3.9 版更改: 增加了 @emph{stripdir}, @emph{prependdir}, @emph{limit_sl_dest} 和 @emph{hardlink_dupes} 参数。 @emph{maxlevels} 的默认值从 @code{10} 改为 @code{sys.getrecursionlimit()}

@end deffn

@geindex compile_file() (在 compileall 模块中)
@anchor{library/compileall compileall compile_file}@anchor{7b8}
@deffn {函数} compileall.compile_file (fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)

编译路径为 @emph{fullname} 的文件。 如果文件编译成功则返回真值，否则返回假值。

如果给出了 @emph{ddir}，它会被附加到被编译的文件的路径之前以便在编译时回溯中使用，同时还会被编译到字节码文件中，届时它将在字节码文件被执行而源文件已不存在的情况下被用于回溯和其他消息中。

如果给出了 @emph{rx}，则会向它的 @code{search} 方法传入准备编译的文件的完整路径，并且如果它返回真值，则不编译该文件并返回 @code{True}。 这可被用来排除与一个正则表达式相匹配的文件，正则表达式将以 @ref{98c,,re.Pattern} 对象的形式给出。

如果 @emph{quiet} 为 @code{False} 或 @code{0} (默认值)，则文件名和其他信息将被打印到标准输出。 如果设为 @code{1}，则只打印错误。 如果设为 @code{2}，则屏蔽所有输出。

如果 @emph{legacy} 为真值，则将字节码文件写入到它们的传统位置和名称，这可能会覆盖由另一版本的 Python 所创建的字节码文件。 默认是将文件写入到它们的 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 位置和名称，这允许来自多个版本的 Python 字节码文件共存。

@emph{optimize} 指明编译器的优化级别。 它会被传给内置 @ref{2ee,,compile()} 函数。 还接受一个优化层别列表这将在单次调用中多次编译一个 @code{.py} 文件。

@emph{invalidation_mode} 应为 @ref{397f,,py_compile.PycInvalidationMode} 枚举的成员之一并将控制所生成的 pyc 在运行时以何种方式验证是否失效。

@emph{stripdir}, @emph{prependdir} 和 @emph{limit_sl_dest} 参数分别对应上述的 @code{-s}, @code{-p} 和 @code{-e} 选项。 它们可以指定为 @code{str}, @code{bytes} 或 @ref{5ee,,os.PathLike}。

如果 @emph{hardlink_dupes} 为真值且两个使用不同优化级别的 @code{.pyc} 文件具有相同的内容，则会使用硬链接来合并重复的文件。


3.2 新版功能.



在 3.5 版更改: @emph{quiet} 形参已改为多级别值。



在 3.5 版更改: @emph{legacy} 形参将只写入 @code{.pyc} 文件而非 @code{.pyo} 文件，无论 @emph{optimize} 的值是什么。



在 3.7 版更改: 增加了 @emph{invalidation_mode} 形参。



在 3.7.2 版更改: @emph{invalidation_mode} 形参的默认值更新为 None。



在 3.9 版更改: 增加了 @emph{stripdir}, @emph{prependdir}, @emph{limit_sl_dest} 和 @emph{hardlink_dupes} 参数。

@end deffn

@geindex compile_path() (在 compileall 模块中)
@anchor{library/compileall compileall compile_path}@anchor{7b9}
@deffn {函数} compileall.compile_path (skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1, invalidation_mode=None)

将在 @code{sys.path} 中找到的所有 @code{.py} 文件编译为字节码。 如果所有文件编译成功则返回真值，否则返回假值。

如果 @emph{skip_curdir} 为真值（默认），则当前目录不会被包括在搜索中。 所有其他形参将被传递给 @ref{483,,compile_dir()} 函数。 请注意不同于其他编译函数，@code{maxlevels} 默认为 @code{0}。


在 3.2 版更改: 增加了 @emph{legacy} 和 @emph{optimize} 形参。



在 3.5 版更改: @emph{quiet} 形参已改为多级别值。



在 3.5 版更改: @emph{legacy} 形参将只写入 @code{.pyc} 文件而非 @code{.pyo} 文件，无论 @emph{optimize} 的值是什么。



在 3.7 版更改: 增加了 @emph{invalidation_mode} 形参。



在 3.7.2 版更改: @emph{invalidation_mode} 形参的默认值更新为 None。

@end deffn

强制重新编译 @code{Lib/} 子目录及其所有子目录下的全部 @code{.py} 文件:

@example
import compileall

compileall.compile_dir('Lib/', force=True)

# Perform same compilation, excluding files in .svn directories.
import re
compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)

# pathlib.Path objects can also be used.
import pathlib
compileall.compile_dir(pathlib.Path('Lib/'), force=True)
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{d7,,py_compile}

将单个源文件编译为字节码。
@end table


@node dis --- Python 字节码反汇编器,pickletools --- pickle 开发者工具集,compileall --- 字节编译 Python 库,Python 语言服务
@anchor{library/dis doc}@anchor{3999}@anchor{library/dis dis-disassembler-for-python-bytecode}@anchor{399a}@anchor{library/dis module-dis}@anchor{37}
@subsection @code{dis} --- Python 字节码反汇编器


@geindex dis (模块)

@strong{Source code:} Lib/dis.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/dis.py}


__________________________________________________________________


@ref{37,,dis} 模块通过反汇编支持CPython的 @ref{713,,bytecode} 分析。该模块作为输入的 CPython 字节码在文件 @code{Include/opcode.h} 中定义，并由编译器和解释器使用。

@strong{CPython implementation detail:} 字节码是 CPython 解释器的实现细节。不保证不会在Python版本之间添加、删除或更改字节码。不应考虑将此模块的跨 Python VM 或 Python 版本的使用。


在 3.6 版更改: 每条指令使用2个字节。以前字节数因指令而异。


示例：给出函数 @code{myfunc()}:

@example
def myfunc(alist):
    return len(alist)
@end example

可以使用以下命令显示 @code{myfunc()} 的反汇编

@example
>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              2 LOAD_FAST                0 (alist)
              4 CALL_FUNCTION            1
              6 RETURN_VALUE
@end example

("2" 是行号)。

@menu
* 字节码分析:: 
* 分析函数:: 
* Python字节码说明:: 
* 操作码集合:: 

@end menu

@node 字节码分析,分析函数,,dis --- Python 字节码反汇编器
@anchor{library/dis bytecode-analysis}@anchor{399b}
@subsubsection 字节码分析



3.4 新版功能.


字节码分析 API 允许将 Python 代码片段包装在 @ref{92e,,Bytecode} 对象中，以便轻松访问已编译代码的详细信息。

@geindex Bytecode (dis 中的类)
@anchor{library/dis dis Bytecode}@anchor{92e}
@deffn {类} dis.Bytecode (x, *, first_line=None, current_offset=None)

分析的字节码对应于函数、生成器、异步生成器、协程、方法、源代码字符串或代码对象（由 @ref{2ee,,compile()} 返回）。

这是下面列出的许多函数的便利包装，最值得注意的是 @ref{92d,,get_instructions()} ，迭代于 @ref{92e,,Bytecode} 的实例产生字节码操作 @ref{92c,,Instruction} 的实例。

如果 @emph{first_line} 不是 @code{None} ，则表示应该为反汇编代码中的第一个源代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码对象。

如果 @emph{current_offset} 不是 @code{None} ，则它指的是反汇编代码中的指令偏移量。设置它意味着 @ref{92f,,dis()} 将针对指定的操作码显示“当前指令”标记。

@geindex from_traceback() (dis.Bytecode 类方法)
@anchor{library/dis dis Bytecode from_traceback}@anchor{930}
@deffn {方法} classmethod from_traceback (tb)

从给定回溯构造一个 @ref{92e,,Bytecode} 实例，将设置 @emph{current_offset} 为异常负责的指令。
@end deffn

@geindex Bytecode.codeobj() (在 dis 模块中)
@anchor{library/dis dis Bytecode codeobj}@anchor{399c}
@deffn {数据} codeobj

已编译的代码对象。
@end deffn

@geindex Bytecode.first_line() (在 dis 模块中)
@anchor{library/dis dis Bytecode first_line}@anchor{399d}
@deffn {数据} first_line

代码对象的第一个源代码行（如果可用）
@end deffn

@geindex dis() (dis.Bytecode 方法)
@anchor{library/dis dis Bytecode dis}@anchor{92f}
@deffn {方法} dis ()

返回字节码操作的格式化视图（与 @ref{493,,dis.dis()} 打印相同，但作为多行字符串返回）。
@end deffn

@geindex info() (dis.Bytecode 方法)
@anchor{library/dis dis Bytecode info}@anchor{399e}
@deffn {方法} info ()

返回带有关于代码对象的详细信息的格式化多行字符串，如 @ref{ca4,,code_info()} 。
@end deffn


在 3.7 版更改: 现在可以处理协程和异步生成器对象。

@end deffn

示例:

@example
>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
...     print(instr.opname)
...
LOAD_GLOBAL
LOAD_FAST
CALL_FUNCTION
RETURN_VALUE
@end example

@node 分析函数,Python字节码说明,字节码分析,dis --- Python 字节码反汇编器
@anchor{library/dis analysis-functions}@anchor{399f}
@subsubsection 分析函数


@ref{37,,dis} 模块还定义了以下分析函数，它们将输入直接转换为所需的输出。如果只执行单个操作，它们可能很有用，因此中间分析对象没用：

@geindex code_info() (在 dis 模块中)
@anchor{library/dis dis code_info}@anchor{ca4}
@deffn {函数} dis.code_info (x)

返回格式化的多行字符串，其包含详细代码对象信息的用于被提供的函数、生成器、异步生成器、协程、方法、源代码字符串或代码对象。

请注意，代码信息字符串的确切内容是高度依赖于实现的，它们可能会在Python VM或Python版本中任意更改。


3.2 新版功能.



在 3.7 版更改: 现在可以处理协程和异步生成器对象。

@end deffn

@geindex show_code() (在 dis 模块中)
@anchor{library/dis dis show_code}@anchor{929}
@deffn {函数} dis.show_code (x, *, file=None)

将提供的函数、方法。源代码字符串或代码对象的详细代码对象信息打印到 @emph{file} （如果未指定 @emph{file} ，则为 @code{sys.stdout} ）。

这是 @code{print(code_info(x), file=file)} 的便捷简写，用于在解释器提示符下进行交互式探索。


3.2 新版功能.



在 3.4 版更改: 添加 @emph{file} 形参。

@end deffn

@geindex dis() (在 dis 模块中)
@anchor{library/dis dis dis}@anchor{493}
@deffn {函数} dis.dis (x=None, *, file=None, depth=None)

反汇编 @emph{x} 对象。 @emph{x} 可以表示模块、类、方法、函数、生成器、异步生成器、协程、代码对象、源代码字符串或原始字节码的字节序列。对于模块，它会反汇编所有功能。对于一个类，它反汇编所有方法（包括类和静态方法）。对于代码对象或原始字节码序列，它每字节码指令打印一行。它还递归地反汇编嵌套代码对象（推导式代码，生成器表达式和嵌套函数，以及用于构建嵌套类的代码）。在被反汇编之前，首先使用 @ref{2ee,,compile()} 内置函数将字符串编译为代码对象。如果未提供任何对象，则此函数会反汇编最后一次回溯。

如果提供的话，反汇编将作为文本写入提供的 @emph{file} 参数，否则写入 @code{sys.stdout} 。

递归的最大深度受 @emph{depth} 限制，除非它是 @code{None} 。 @code{depth=0} 表示没有递归。


在 3.4 版更改: 添加 @emph{file} 形参。



在 3.7 版更改: 实现了递归反汇编并添加了 @emph{depth} 参数。



在 3.7 版更改: 现在可以处理协程和异步生成器对象。

@end deffn

@geindex distb() (在 dis 模块中)
@anchor{library/dis dis distb}@anchor{92a}
@deffn {函数} dis.distb (tb=None, *, file=None)

如果没有传递，则使用最后一个回溯来反汇编回溯的堆栈顶部函数。 指示了导致异常的指令。

如果提供的话，反汇编将作为文本写入提供的 @emph{file} 参数，否则写入 @code{sys.stdout} 。


在 3.4 版更改: 添加 @emph{file} 形参。

@end deffn

@geindex disassemble() (在 dis 模块中)
@geindex disco() (在 dis 模块中)
@anchor{library/dis dis disassemble}@anchor{92b}
@deffn {函数} dis.disassemble (code, lasti=-1, *, file=None)
@anchor{library/dis dis disco}@anchor{39a0}
@deffnx {函数} dis.disco (code, lasti=-1, *, file=None)

反汇编代码对象，如果提供了 @emph{lasti} ，则指示最后一条指令。输出分为以下几列：


@enumerate 

@item 
行号，用于每行的第一条指令

@item 
当前指令，表示为 @code{-->} ，

@item 
一个标记的指令，用 @code{>>} 表示，

@item 
指令的地址，

@item 
操作码名称，

@item 
操作参数，和

@item 
括号中参数的解释。
@end enumerate

参数解释识别本地和全局变量名称、常量值、分支目标和比较运算符。

如果提供的话，反汇编将作为文本写入提供的 @emph{file} 参数，否则写入 @code{sys.stdout} 。


在 3.4 版更改: 添加 @emph{file} 形参。

@end deffn

@geindex get_instructions() (在 dis 模块中)
@anchor{library/dis dis get_instructions}@anchor{92d}
@deffn {函数} dis.get_instructions (x, *, first_line=None)

在所提供的函数、方法、源代码字符串或代码对象中的指令上返回一个迭代器。

迭代器生成一系列 @ref{92c,,Instruction} ，命名为元组，提供所提供代码中每个操作的详细信息。

如果 @emph{first_line} 不是 @code{None} ，则表示应该为反汇编代码中的第一个源代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码对象。


3.4 新版功能.

@end deffn

@geindex findlinestarts() (在 dis 模块中)
@anchor{library/dis dis findlinestarts}@anchor{39a1}
@deffn {函数} dis.findlinestarts (code)

此生成器函数使用代码对象 @emph{code} 的 @code{co_firstlineno} 和 @code{co_lnotab} 属性来查找源代码中行开头的偏移量。它们生成为 @code{(offset, lineno)} 对。请参阅 objects/lnotab_notes.txt@footnote{https://github.com/python/cpython/tree/3.9/objects/lnotab_notes.txt} ，了解 @code{co_lnotab} 格式以及如何解码它。


在 3.6 版更改: 行号可能会减少。 以前，他们总是在增加。

@end deffn

@geindex findlabels() (在 dis 模块中)
@anchor{library/dis dis findlabels}@anchor{39a2}
@deffn {函数} dis.findlabels (code)

检测作为跳转目标的原始编译后字节码字符串 @emph{code} 中的所有偏移量，并返回这些偏移量的列表。
@end deffn

@geindex stack_effect() (在 dis 模块中)
@anchor{library/dis dis stack_effect}@anchor{931}
@deffn {函数} dis.stack_effect (opcode, oparg=None, *, jump=None)

使用参数 @emph{oparg} 计算 @emph{opcode} 的堆栈效果。

如果代码有一个跳转目标并且 @emph{jump} 是 @code{True} ，则 @code{drag_effect()} 将返回跳转的堆栈效果。如果 @emph{jump} 是 @code{False} ，它将返回不跳跃的堆栈效果。如果 @emph{jump} 是 @code{None} （默认值），它将返回两种情况的最大堆栈效果。


3.4 新版功能.



在 3.8 版更改: 添加 @emph{jump} 参数。

@end deffn

@node Python字节码说明,操作码集合,分析函数,dis --- Python 字节码反汇编器
@anchor{library/dis bytecodes}@anchor{39a3}@anchor{library/dis python-bytecode-instructions}@anchor{39a4}
@subsubsection Python字节码说明


@ref{92d,,get_instructions()} 函数和 @ref{92e,,Bytecode} 类提供字节码指令的详细信息的 @ref{92c,,Instruction} 实例：

@geindex Instruction (dis 中的类)
@anchor{library/dis dis Instruction}@anchor{92c}
@deffn {类} dis.Instruction

字节码操作的详细信息

@geindex Instruction.opcode() (在 dis 模块中)
@anchor{library/dis dis Instruction opcode}@anchor{39a5}
@deffn {数据} opcode

操作的数字代码，对应于下面列出的操作码值和 @ref{39a6,,操作码集合} 中的字节码值。
@end deffn

@geindex Instruction.opname() (在 dis 模块中)
@anchor{library/dis dis Instruction opname}@anchor{39a7}
@deffn {数据} opname

人类可读的操作名称
@end deffn

@geindex Instruction.arg() (在 dis 模块中)
@anchor{library/dis dis Instruction arg}@anchor{39a8}
@deffn {数据} arg

操作的数字参数（如果有的话），否则为 @code{None}
@end deffn

@geindex Instruction.argval() (在 dis 模块中)
@anchor{library/dis dis Instruction argval}@anchor{39a9}
@deffn {数据} argval

已解析的 arg 值（如果已知），否则与 arg 相同
@end deffn

@geindex Instruction.argrepr() (在 dis 模块中)
@anchor{library/dis dis Instruction argrepr}@anchor{39aa}
@deffn {数据} argrepr

人类可读的操作参数描述
@end deffn

@geindex Instruction.offset() (在 dis 模块中)
@anchor{library/dis dis Instruction offset}@anchor{39ab}
@deffn {数据} offset

在字节码序列中启动操作索引
@end deffn

@geindex Instruction.starts_line() (在 dis 模块中)
@anchor{library/dis dis Instruction starts_line}@anchor{39ac}
@deffn {数据} starts_line

行由此操作码（如果有）启动，否则为 @code{None}
@end deffn

@geindex Instruction.is_jump_target() (在 dis 模块中)
@anchor{library/dis dis Instruction is_jump_target}@anchor{39ad}
@deffn {数据} is_jump_target

如果其他代码跳到这里，则为 @code{True} ，否则为 @code{False}
@end deffn


3.4 新版功能.

@end deffn

Python编译器当前生成以下字节码指令。

@strong{一般指令}

@geindex NOP (opcode)
@anchor{library/dis opcode-NOP}@anchor{39ae}
@deffn {Opcode} NOP

什么都不做。 用作字节码优化器的占位符。
@end deffn

@geindex POP_TOP (opcode)
@anchor{library/dis opcode-POP_TOP}@anchor{39af}
@deffn {Opcode} POP_TOP

删除堆栈顶部（TOS）项。
@end deffn

@geindex ROT_TWO (opcode)
@anchor{library/dis opcode-ROT_TWO}@anchor{39b0}
@deffn {Opcode} ROT_TWO

交换两个最顶层的堆栈项。
@end deffn

@geindex ROT_THREE (opcode)
@anchor{library/dis opcode-ROT_THREE}@anchor{39b1}
@deffn {Opcode} ROT_THREE

将第二个和第三个堆栈项向上提升一个位置，顶项移动到位置三。
@end deffn

@geindex ROT_FOUR (opcode)
@anchor{library/dis opcode-ROT_FOUR}@anchor{404}
@deffn {Opcode} ROT_FOUR

将第二个、第三个和第四个堆栈项向上提升一个位置，将顶项移动到第四个位置。


3.8 新版功能.

@end deffn

@geindex DUP_TOP (opcode)
@anchor{library/dis opcode-DUP_TOP}@anchor{39b2}
@deffn {Opcode} DUP_TOP

复制堆栈顶部的引用。


3.2 新版功能.

@end deffn

@geindex DUP_TOP_TWO (opcode)
@anchor{library/dis opcode-DUP_TOP_TWO}@anchor{39b3}
@deffn {Opcode} DUP_TOP_TWO

复制堆栈顶部的两个引用，使它们保持相同的顺序。


3.2 新版功能.

@end deffn

@strong{一元操作}

一元操作获取堆栈顶部元素，应用操作，并将结果推回堆栈。

@geindex UNARY_POSITIVE (opcode)
@anchor{library/dis opcode-UNARY_POSITIVE}@anchor{39b4}
@deffn {Opcode} UNARY_POSITIVE

实现 @code{TOS = +TOS} 。
@end deffn

@geindex UNARY_NEGATIVE (opcode)
@anchor{library/dis opcode-UNARY_NEGATIVE}@anchor{39b5}
@deffn {Opcode} UNARY_NEGATIVE

实现 @code{TOS = -TOS} 。
@end deffn

@geindex UNARY_NOT (opcode)
@anchor{library/dis opcode-UNARY_NOT}@anchor{39b6}
@deffn {Opcode} UNARY_NOT

实现 @code{TOS = not TOS} 。
@end deffn

@geindex UNARY_INVERT (opcode)
@anchor{library/dis opcode-UNARY_INVERT}@anchor{39b7}
@deffn {Opcode} UNARY_INVERT

实现 @code{TOS = ~TOS} 。
@end deffn

@geindex GET_ITER (opcode)
@anchor{library/dis opcode-GET_ITER}@anchor{39b8}
@deffn {Opcode} GET_ITER

实现 @code{TOS = iter(TOS)} 。
@end deffn

@geindex GET_YIELD_FROM_ITER (opcode)
@anchor{library/dis opcode-GET_YIELD_FROM_ITER}@anchor{39b9}
@deffn {Opcode} GET_YIELD_FROM_ITER

如果 @code{TOS} 是一个 @ref{561,,generator iterator} 或 @ref{18a,,coroutine} 对象则保持原样。否则实现 @code{TOS = iter(TOS)} 。


3.5 新版功能.

@end deffn

@strong{二元操作}

二元操作从堆栈中删除堆栈顶部（TOS）和第二个最顶层堆栈项（TOS1）。 它们执行操作，并将结果放回堆栈。

@geindex BINARY_POWER (opcode)
@anchor{library/dis opcode-BINARY_POWER}@anchor{39ba}
@deffn {Opcode} BINARY_POWER

实现 @code{TOS = TOS1 ** TOS} 。
@end deffn

@geindex BINARY_MULTIPLY (opcode)
@anchor{library/dis opcode-BINARY_MULTIPLY}@anchor{39bb}
@deffn {Opcode} BINARY_MULTIPLY

实现 @code{TOS = TOS1 * TOS} 。
@end deffn

@geindex BINARY_MATRIX_MULTIPLY (opcode)
@anchor{library/dis opcode-BINARY_MATRIX_MULTIPLY}@anchor{39bc}
@deffn {Opcode} BINARY_MATRIX_MULTIPLY

实现 @code{TOS = TOS1 @@ TOS} 。


3.5 新版功能.

@end deffn

@geindex BINARY_FLOOR_DIVIDE (opcode)
@anchor{library/dis opcode-BINARY_FLOOR_DIVIDE}@anchor{39bd}
@deffn {Opcode} BINARY_FLOOR_DIVIDE

实现 @code{TOS = TOS1 // TOS}。
@end deffn

@geindex BINARY_TRUE_DIVIDE (opcode)
@anchor{library/dis opcode-BINARY_TRUE_DIVIDE}@anchor{39be}
@deffn {Opcode} BINARY_TRUE_DIVIDE

实现 @code{TOS = TOS1 / TOS} 。
@end deffn

@geindex BINARY_MODULO (opcode)
@anchor{library/dis opcode-BINARY_MODULO}@anchor{39bf}
@deffn {Opcode} BINARY_MODULO

实现 @code{TOS = TOS1 % TOS} 。
@end deffn

@geindex BINARY_ADD (opcode)
@anchor{library/dis opcode-BINARY_ADD}@anchor{39c0}
@deffn {Opcode} BINARY_ADD

实现 @code{TOS = TOS1 + TOS} 。
@end deffn

@geindex BINARY_SUBTRACT (opcode)
@anchor{library/dis opcode-BINARY_SUBTRACT}@anchor{39c1}
@deffn {Opcode} BINARY_SUBTRACT

实现 @code{TOS = TOS1 - TOS} 。
@end deffn

@geindex BINARY_SUBSCR (opcode)
@anchor{library/dis opcode-BINARY_SUBSCR}@anchor{39c2}
@deffn {Opcode} BINARY_SUBSCR

实现 @code{TOS = TOS1[TOS]} 。
@end deffn

@geindex BINARY_LSHIFT (opcode)
@anchor{library/dis opcode-BINARY_LSHIFT}@anchor{39c3}
@deffn {Opcode} BINARY_LSHIFT

实现 @code{TOS = TOS1 << TOS} 。
@end deffn

@geindex BINARY_RSHIFT (opcode)
@anchor{library/dis opcode-BINARY_RSHIFT}@anchor{39c4}
@deffn {Opcode} BINARY_RSHIFT

实现 @code{TOS = TOS1 >> TOS} 。
@end deffn

@geindex BINARY_AND (opcode)
@anchor{library/dis opcode-BINARY_AND}@anchor{39c5}
@deffn {Opcode} BINARY_AND

实现 @code{TOS = TOS1 & TOS} 。
@end deffn

@geindex BINARY_XOR (opcode)
@anchor{library/dis opcode-BINARY_XOR}@anchor{39c6}
@deffn {Opcode} BINARY_XOR

实现 @code{TOS = TOS1 ^ TOS} 。
@end deffn

@geindex BINARY_OR (opcode)
@anchor{library/dis opcode-BINARY_OR}@anchor{39c7}
@deffn {Opcode} BINARY_OR

实现 @code{TOS = TOS1 | TOS} 。
@end deffn

@strong{就地操作}

就地操作就像二元操作，因为它们删除了TOS和TOS1，并将结果推回到堆栈上，但是当TOS1支持它时，操作就地完成，并且产生的TOS可能是（但不一定） 原来的TOS1。

@geindex INPLACE_POWER (opcode)
@anchor{library/dis opcode-INPLACE_POWER}@anchor{39c8}
@deffn {Opcode} INPLACE_POWER

就地实现 @code{TOS = TOS1 ** TOS} 。
@end deffn

@geindex INPLACE_MULTIPLY (opcode)
@anchor{library/dis opcode-INPLACE_MULTIPLY}@anchor{39c9}
@deffn {Opcode} INPLACE_MULTIPLY

就地实现 @code{TOS = TOS1 * TOS} 。
@end deffn

@geindex INPLACE_MATRIX_MULTIPLY (opcode)
@anchor{library/dis opcode-INPLACE_MATRIX_MULTIPLY}@anchor{39ca}
@deffn {Opcode} INPLACE_MATRIX_MULTIPLY

就地实现 @code{TOS = TOS1 @@ TOS} 。


3.5 新版功能.

@end deffn

@geindex INPLACE_FLOOR_DIVIDE (opcode)
@anchor{library/dis opcode-INPLACE_FLOOR_DIVIDE}@anchor{39cb}
@deffn {Opcode} INPLACE_FLOOR_DIVIDE

就地实现 @code{TOS = TOS1 // TOS} 。
@end deffn

@geindex INPLACE_TRUE_DIVIDE (opcode)
@anchor{library/dis opcode-INPLACE_TRUE_DIVIDE}@anchor{39cc}
@deffn {Opcode} INPLACE_TRUE_DIVIDE

就地实现 @code{TOS = TOS1 / TOS} 。
@end deffn

@geindex INPLACE_MODULO (opcode)
@anchor{library/dis opcode-INPLACE_MODULO}@anchor{39cd}
@deffn {Opcode} INPLACE_MODULO

就地实现 @code{TOS = TOS1 % TOS} 。
@end deffn

@geindex INPLACE_ADD (opcode)
@anchor{library/dis opcode-INPLACE_ADD}@anchor{39ce}
@deffn {Opcode} INPLACE_ADD

就地实现 @code{TOS = TOS1 + TOS} 。
@end deffn

@geindex INPLACE_SUBTRACT (opcode)
@anchor{library/dis opcode-INPLACE_SUBTRACT}@anchor{39cf}
@deffn {Opcode} INPLACE_SUBTRACT

就地实现 @code{TOS = TOS1 - TOS} 。
@end deffn

@geindex INPLACE_LSHIFT (opcode)
@anchor{library/dis opcode-INPLACE_LSHIFT}@anchor{39d0}
@deffn {Opcode} INPLACE_LSHIFT

就地实现 @code{TOS = TOS1 << TOS} 。
@end deffn

@geindex INPLACE_RSHIFT (opcode)
@anchor{library/dis opcode-INPLACE_RSHIFT}@anchor{39d1}
@deffn {Opcode} INPLACE_RSHIFT

就地实现 @code{TOS = TOS1 >> TOS} 。
@end deffn

@geindex INPLACE_AND (opcode)
@anchor{library/dis opcode-INPLACE_AND}@anchor{39d2}
@deffn {Opcode} INPLACE_AND

就地实现 @code{TOS = TOS1 & TOS} 。
@end deffn

@geindex INPLACE_XOR (opcode)
@anchor{library/dis opcode-INPLACE_XOR}@anchor{39d3}
@deffn {Opcode} INPLACE_XOR

就地实现 @code{TOS = TOS1 ^ TOS} 。
@end deffn

@geindex INPLACE_OR (opcode)
@anchor{library/dis opcode-INPLACE_OR}@anchor{39d4}
@deffn {Opcode} INPLACE_OR

就地实现 @code{TOS = TOS1 | TOS} 。
@end deffn

@geindex STORE_SUBSCR (opcode)
@anchor{library/dis opcode-STORE_SUBSCR}@anchor{39d5}
@deffn {Opcode} STORE_SUBSCR

实现 @code{TOS1[TOS] = TOS2} 。
@end deffn

@geindex DELETE_SUBSCR (opcode)
@anchor{library/dis opcode-DELETE_SUBSCR}@anchor{39d6}
@deffn {Opcode} DELETE_SUBSCR

实现 @code{del TOS1[TOS]} 。
@end deffn

@strong{协程操作码}

@geindex GET_AWAITABLE (opcode)
@anchor{library/dis opcode-GET_AWAITABLE}@anchor{39d7}
@deffn {Opcode} GET_AWAITABLE

实现 @code{TOS = get_awaitable(TOS)} ，其中 @code{get_awaitable(o)} 返回 @code{o} 如果 @code{o} 是一个有 CO_ITERABLE_COROUTINE 标志的协程对象或生成器对象，否则解析 @code{o.__await__} 。


3.5 新版功能.

@end deffn

@geindex GET_AITER (opcode)
@anchor{library/dis opcode-GET_AITER}@anchor{39d8}
@deffn {Opcode} GET_AITER

实现 @code{TOS = TOS.__aiter__()} 。


3.5 新版功能.



在 3.7 版更改: 已经不再支持从 @code{__aiter__} 返回可等待对象。

@end deffn

@geindex GET_ANEXT (opcode)
@anchor{library/dis opcode-GET_ANEXT}@anchor{39d9}
@deffn {Opcode} GET_ANEXT

实现 @code{PUSH(get_awaitable(TOS.__anext__()))} 。参见 @code{GET_AWAITABLE} 获取更多 @code{get_awaitable} 的细节


3.5 新版功能.

@end deffn

@geindex END_ASYNC_FOR (opcode)
@anchor{library/dis opcode-END_ASYNC_FOR}@anchor{405}
@deffn {Opcode} END_ASYNC_FOR

终止一个 @ref{406,,async for}  循环。处理等待下一个项目时引发的异常。如果 TOS 是 @ref{1193,,StopAsyncIteration}， 从堆栈弹出7个值，并使用后三个恢复异常状态。否则，使用堆栈中的三个值重新引发异常。从块堆栈中删除异常处理程序块。


3.8 新版功能.

@end deffn

@geindex BEFORE_ASYNC_WITH (opcode)
@anchor{library/dis opcode-BEFORE_ASYNC_WITH}@anchor{39da}
@deffn {Opcode} BEFORE_ASYNC_WITH

从栈顶对象解析 @code{__aenter__} 和 @code{__aexit__} 。将 @code{__aexit__} 和 @code{__aenter__()} 的结果推入堆栈。


3.5 新版功能.

@end deffn

@geindex SETUP_ASYNC_WITH (opcode)
@anchor{library/dis opcode-SETUP_ASYNC_WITH}@anchor{39db}
@deffn {Opcode} SETUP_ASYNC_WITH

创建一个新的帧对象。


3.5 新版功能.

@end deffn

@strong{其他操作码}

@geindex PRINT_EXPR (opcode)
@anchor{library/dis opcode-PRINT_EXPR}@anchor{39dc}
@deffn {Opcode} PRINT_EXPR

实现交互模式的表达式语句。TOS从堆栈中被移除并打印。在非交互模式下，表达式语句以 @ref{39af,,POP_TOP} 终止。
@end deffn

@geindex SET_ADD (opcode)
@anchor{library/dis opcode-SET_ADD}@anchor{39dd}
@deffn {Opcode} SET_ADD (i)

调用 @code{set.add(TOS1[-i], TOS)} 。 用于实现集合推导。
@end deffn

@geindex LIST_APPEND (opcode)
@anchor{library/dis opcode-LIST_APPEND}@anchor{39de}
@deffn {Opcode} LIST_APPEND (i)

调用 @code{list.append(TOS1[-i], TOS)}。 用于实现列表推导式。
@end deffn

@geindex MAP_ADD (opcode)
@anchor{library/dis opcode-MAP_ADD}@anchor{407}
@deffn {Opcode} MAP_ADD (i)

调用 @code{dict.__setitem__(TOS1[-i], TOS1, TOS)} 。 用于实现字典推导。


3.1 新版功能.



在 3.8 版更改: 映射值为 TOS ，映射键为 TOS1 。之前，它们被颠倒了。

@end deffn

对于所有 @ref{39dd,,SET_ADD} 、 @ref{39de,,LIST_APPEND} 和 @ref{407,,MAP_ADD} 指令，当弹出添加的值或键值对时，容器对象保留在堆栈上，以便它可用于循环的进一步迭代。

@geindex RETURN_VALUE (opcode)
@anchor{library/dis opcode-RETURN_VALUE}@anchor{39df}
@deffn {Opcode} RETURN_VALUE

返回 TOS 到函数的调用者。
@end deffn

@geindex YIELD_VALUE (opcode)
@anchor{library/dis opcode-YIELD_VALUE}@anchor{39e0}
@deffn {Opcode} YIELD_VALUE

弹出 TOS 并从一个 @ref{a8c,,generator} 生成它。
@end deffn

@geindex YIELD_FROM (opcode)
@anchor{library/dis opcode-YIELD_FROM}@anchor{39e1}
@deffn {Opcode} YIELD_FROM

弹出 TOS 并将其委托给它作为 @ref{a8c,,generator} 的子迭代器。


3.3 新版功能.

@end deffn

@geindex SETUP_ANNOTATIONS (opcode)
@anchor{library/dis opcode-SETUP_ANNOTATIONS}@anchor{71b}
@deffn {Opcode} SETUP_ANNOTATIONS

检查 @code{__annotations__} 是否在 @code{locals()} 中定义，如果没有，它被设置为空 @code{dict} 。只有在类或模块体静态地包含 @ref{71c,,variable annotations} 时才会发出此操作码。


3.6 新版功能.

@end deffn

@geindex IMPORT_STAR (opcode)
@anchor{library/dis opcode-IMPORT_STAR}@anchor{39e2}
@deffn {Opcode} IMPORT_STAR

将所有不以 @code{'_'} 开头的符号直接从模块 TOS 加载到局部命名空间。加载所有名称后弹出该模块。这个操作码实现了 @code{from module import *} 。
@end deffn

@geindex POP_BLOCK (opcode)
@anchor{library/dis opcode-POP_BLOCK}@anchor{39e3}
@deffn {Opcode} POP_BLOCK

从块堆栈中删除一个块。有一块堆栈，每帧用于表示 @ref{e3f,,try} 语句等。
@end deffn

@geindex POP_EXCEPT (opcode)
@anchor{library/dis opcode-POP_EXCEPT}@anchor{39e4}
@deffn {Opcode} POP_EXCEPT

从块堆栈中删除一个块。 弹出的块必须是异常处理程序块，在进入 except 处理程序时隐式创建。除了从帧堆栈弹出无关值之外，最后三个弹出值还用于恢复异常状态。
@end deffn

@geindex RERAISE (opcode)
@anchor{library/dis opcode-RERAISE}@anchor{39e5}
@deffn {Opcode} RERAISE

重新引发当前位于栈顶的异常。


3.9 新版功能.

@end deffn

@geindex WITH_EXCEPT_START (opcode)
@anchor{library/dis opcode-WITH_EXCEPT_START}@anchor{39e6}
@deffn {Opcode} WITH_EXCEPT_START

调用堆栈中 7 号位置上的函数并附带栈顶位置的三项作为参数。 用来在 @ref{7e4,,with} 语句内发生异常时实现调用 @code{context_manager.__exit__(*exc_info())}。


3.9 新版功能.

@end deffn

@geindex LOAD_ASSERTION_ERROR (opcode)
@anchor{library/dis opcode-LOAD_ASSERTION_ERROR}@anchor{23f}
@deffn {Opcode} LOAD_ASSERTION_ERROR

将 @ref{241,,AssertionError} 推入栈顶。 由 @ref{240,,assert} 语句使用。


3.9 新版功能.

@end deffn

@geindex LOAD_BUILD_CLASS (opcode)
@anchor{library/dis opcode-LOAD_BUILD_CLASS}@anchor{39e7}
@deffn {Opcode} LOAD_BUILD_CLASS

将 @code{builtins .__ build_class__()} 推到堆栈上。它之后被 @ref{718,,CALL_FUNCTION} 调用来构造一个类。
@end deffn

@geindex SETUP_WITH (opcode)
@anchor{library/dis opcode-SETUP_WITH}@anchor{39e8}
@deffn {Opcode} SETUP_WITH (delta)

此操作码会在 with 代码块开始之前执行多个操作。 首先，它从上下文管理器加载 @ref{d66,,__exit__()} 并将其推入栈顶以供 @ref{39e6,,WITH_EXCEPT_START} 后续使用。 然后，调用 @ref{d65,,__enter__()}，并推入一个指向 @emph{delta} 的 finally 代码块。 最后，将调用 @code{__enter__()} 方法的结果推入栈顶。 下一个操作码将忽略它 (@ref{39af,,POP_TOP})，或将其存储在一个或多个变量 (@ref{39e9,,STORE_FAST}, @ref{39ea,,STORE_NAME} 或 @ref{39eb,,UNPACK_SEQUENCE}) 中。


3.2 新版功能.

@end deffn

以下所有操作码均使用其参数。

@geindex STORE_NAME (opcode)
@anchor{library/dis opcode-STORE_NAME}@anchor{39ea}
@deffn {Opcode} STORE_NAME (namei)

实现 @code{name = TOS}。 @emph{namei} 是 @emph{name} 在代码对象的 @code{co_names} 属性中的索引。 在可能的情况下，编译器会尝试使用 @ref{39e9,,STORE_FAST} 或 @ref{39ec,,STORE_GLOBAL}。
@end deffn

@geindex DELETE_NAME (opcode)
@anchor{library/dis opcode-DELETE_NAME}@anchor{39ed}
@deffn {Opcode} DELETE_NAME (namei)

实现 @code{del name} ，其中 @emph{namei} 是代码对象的 @code{co_names} 属性的索引。
@end deffn

@geindex UNPACK_SEQUENCE (opcode)
@anchor{library/dis opcode-UNPACK_SEQUENCE}@anchor{39eb}
@deffn {Opcode} UNPACK_SEQUENCE (count)

将 TOS 解包为 @emph{count} 个单独的值，它们将按从右至左的顺序被放入堆栈。
@end deffn

@geindex UNPACK_EX (opcode)
@anchor{library/dis opcode-UNPACK_EX}@anchor{39ee}
@deffn {Opcode} UNPACK_EX (counts)

实现使用带星号的目标进行赋值：将 TOS 中的可迭代对象解包为单独的值，其中值的总数可以小于可迭代对象中的项数：新值之一将是由所有剩余项构成的列表。

@emph{counts} 的低字节是列表值之前的值的数量，@emph{counts} 中的高字节则是之后的值的数量。 结果值会按从右至左的顺序入栈。
@end deffn

@geindex STORE_ATTR (opcode)
@anchor{library/dis opcode-STORE_ATTR}@anchor{39ef}
@deffn {Opcode} STORE_ATTR (namei)

实现 @code{TOS.name = TOS1}，其中 @emph{namei} 是 name 在 @code{co_names} 中的索引号。
@end deffn

@geindex DELETE_ATTR (opcode)
@anchor{library/dis opcode-DELETE_ATTR}@anchor{39f0}
@deffn {Opcode} DELETE_ATTR (namei)

实现 @code{del TOS.name}，使用 @emph{namei} 作为 @code{co_names} 中的索引号。
@end deffn

@geindex STORE_GLOBAL (opcode)
@anchor{library/dis opcode-STORE_GLOBAL}@anchor{39ec}
@deffn {Opcode} STORE_GLOBAL (namei)

类似于 @ref{39ea,,STORE_NAME} 但会将 name 存储为全局变量。
@end deffn

@geindex DELETE_GLOBAL (opcode)
@anchor{library/dis opcode-DELETE_GLOBAL}@anchor{39f1}
@deffn {Opcode} DELETE_GLOBAL (namei)

类似于 @ref{39ed,,DELETE_NAME} 但会删除一个全局变量。
@end deffn

@geindex LOAD_CONST (opcode)
@anchor{library/dis opcode-LOAD_CONST}@anchor{39f2}
@deffn {Opcode} LOAD_CONST (consti)

将 @code{co_consts[consti]} 推入栈顶。
@end deffn

@geindex LOAD_NAME (opcode)
@anchor{library/dis opcode-LOAD_NAME}@anchor{39f3}
@deffn {Opcode} LOAD_NAME (namei)

将与 @code{co_names[namei]} 相关联的值推入栈顶。
@end deffn

@geindex BUILD_TUPLE (opcode)
@anchor{library/dis opcode-BUILD_TUPLE}@anchor{39f4}
@deffn {Opcode} BUILD_TUPLE (count)

创建一个使用了来自栈的 @emph{count} 个项的元组，并将结果元组推入栈顶。
@end deffn

@geindex BUILD_LIST (opcode)
@anchor{library/dis opcode-BUILD_LIST}@anchor{39f5}
@deffn {Opcode} BUILD_LIST (count)

类似于 @ref{39f4,,BUILD_TUPLE} 但会创建一个列表。
@end deffn

@geindex BUILD_SET (opcode)
@anchor{library/dis opcode-BUILD_SET}@anchor{39f6}
@deffn {Opcode} BUILD_SET (count)

类似于 @ref{39f4,,BUILD_TUPLE} 但会创建一个集合。
@end deffn

@geindex BUILD_MAP (opcode)
@anchor{library/dis opcode-BUILD_MAP}@anchor{39f7}
@deffn {Opcode} BUILD_MAP (count)

将一个新字典对象推入栈顶。 弹出 @code{2 * count} 项使得字典包含 @emph{count} 个条目: @code{@{..., TOS3: TOS2, TOS1: TOS@}}。


在 3.5 版更改: 字典是根据栈中的项创建而不是创建一个预设大小包含 @emph{count} 项的空字典。

@end deffn

@geindex BUILD_CONST_KEY_MAP (opcode)
@anchor{library/dis opcode-BUILD_CONST_KEY_MAP}@anchor{716}
@deffn {Opcode} BUILD_CONST_KEY_MAP (count)

@ref{39f7,,BUILD_MAP} 版本专用于常量键。 弹出的栈顶元素包含一个由键构成的元组，然后从 @code{TOS1} 开始从构建字典的值中弹出 @emph{count} 个值。


3.6 新版功能.

@end deffn

@geindex BUILD_STRING (opcode)
@anchor{library/dis opcode-BUILD_STRING}@anchor{715}
@deffn {Opcode} BUILD_STRING (count)

拼接 @emph{count} 个来自栈的字符串并将结果字符串推入栈顶。


3.6 新版功能.

@end deffn

@geindex LIST_TO_TUPLE (opcode)
@anchor{library/dis opcode-LIST_TO_TUPLE}@anchor{39f8}
@deffn {Opcode} LIST_TO_TUPLE

从堆栈中弹出一个列表并推入一个包含相同值的元组。


3.9 新版功能.

@end deffn

@geindex LIST_EXTEND (opcode)
@anchor{library/dis opcode-LIST_EXTEND}@anchor{39f9}
@deffn {Opcode} LIST_EXTEND (i)

调用 @code{list.extend(TOS1[-i], TOS)}。 用于构建列表。


3.9 新版功能.

@end deffn

@geindex SET_UPDATE (opcode)
@anchor{library/dis opcode-SET_UPDATE}@anchor{39fa}
@deffn {Opcode} SET_UPDATE (i)

调用 @code{set.update(TOS1[-i], TOS)}。 用于构建集合。


3.9 新版功能.

@end deffn

@geindex DICT_UPDATE (opcode)
@anchor{library/dis opcode-DICT_UPDATE}@anchor{39fb}
@deffn {Opcode} DICT_UPDATE (i)

调用 @code{dict.update(TOS1[-i], TOS)}。 用于构建字典。


3.9 新版功能.

@end deffn

@geindex DICT_MERGE (opcode)
@anchor{library/dis opcode-DICT_MERGE}@anchor{39fc}
@deffn {Opcode} DICT_MERGE

类似于 @ref{39fb,,DICT_UPDATE} 但对于重复的键会引发异常。


3.9 新版功能.

@end deffn

@geindex LOAD_ATTR (opcode)
@anchor{library/dis opcode-LOAD_ATTR}@anchor{39fd}
@deffn {Opcode} LOAD_ATTR (namei)

将 TOS 替换为 @code{getattr(TOS, co_names[namei])}。
@end deffn

@geindex COMPARE_OP (opcode)
@anchor{library/dis opcode-COMPARE_OP}@anchor{242}
@deffn {Opcode} COMPARE_OP (opname)

执行布尔运算操作。 操作名称可在 @code{cmp_op[opname]} 中找到。
@end deffn

@geindex IS_OP (opcode)
@anchor{library/dis opcode-IS_OP}@anchor{39fe}
@deffn {Opcode} IS_OP (invert)

执行 @code{is} 比较，或者如果 @code{invert} 为 1 则执行 @code{is not}。


3.9 新版功能.

@end deffn

@geindex CONTAINS_OP (opcode)
@anchor{library/dis opcode-CONTAINS_OP}@anchor{39ff}
@deffn {Opcode} CONTAINS_OP (invert)

执行 @code{in} 比较，或者如果 @code{invert} 为 1 则执行 @code{not in}。


3.9 新版功能.

@end deffn

@geindex IMPORT_NAME (opcode)
@anchor{library/dis opcode-IMPORT_NAME}@anchor{3a00}
@deffn {Opcode} IMPORT_NAME (namei)

导入模块 @code{co_names[namei]}。 会弹出 TOS 和 TOS1 以提供 @emph{fromlist} 和 @emph{level} 参数给 @ref{16b,,__import__()}。 模块对象会被推入栈顶。 当前命名空间不受影响：对于一条标准 import 语句，会执行后续的 @ref{39e9,,STORE_FAST} 指令来修改命名空间。
@end deffn

@geindex IMPORT_FROM (opcode)
@anchor{library/dis opcode-IMPORT_FROM}@anchor{3a01}
@deffn {Opcode} IMPORT_FROM (namei)

从在 TOS 内找到的模块中加载属性 @code{co_names[namei]}。 结果对象会被推入栈顶，以便由后续的 @ref{39e9,,STORE_FAST} 指令来保存。
@end deffn

@geindex JUMP_FORWARD (opcode)
@anchor{library/dis opcode-JUMP_FORWARD}@anchor{3a02}
@deffn {Opcode} JUMP_FORWARD (delta)

将字节码计数器的值增加 @emph{delta}。
@end deffn

@geindex POP_JUMP_IF_TRUE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_TRUE}@anchor{3a03}
@deffn {Opcode} POP_JUMP_IF_TRUE (target)

如果 TOS 为真值，则将字节码计数器的值设为 @emph{target}。 TOS 会被弹出。


3.1 新版功能.

@end deffn

@geindex POP_JUMP_IF_FALSE (opcode)
@anchor{library/dis opcode-POP_JUMP_IF_FALSE}@anchor{3a04}
@deffn {Opcode} POP_JUMP_IF_FALSE (target)

如果 TOS 为假值，则将字节码计数器的值设为 @emph{target}。 TOS 会被弹出。


3.1 新版功能.

@end deffn

@geindex JUMP_IF_NOT_EXC_MATCH (opcode)
@anchor{library/dis opcode-JUMP_IF_NOT_EXC_MATCH}@anchor{3a05}
@deffn {Opcode} JUMP_IF_NOT_EXC_MATCH (target)

检测堆栈中的第二个值是否为匹配 TOS 的异常，如果不是则会跳转。 从堆栈中弹出两个值。


3.9 新版功能.

@end deffn

@geindex JUMP_IF_TRUE_OR_POP (opcode)
@anchor{library/dis opcode-JUMP_IF_TRUE_OR_POP}@anchor{3a06}
@deffn {Opcode} JUMP_IF_TRUE_OR_POP (target)

如果 TOS 为真值，则将字节码计数器的值设为 @emph{target} 并将 TOS 留在栈顶。 否则（如 TOS 为假值），TOS 会被弹出。


3.1 新版功能.

@end deffn

@geindex JUMP_IF_FALSE_OR_POP (opcode)
@anchor{library/dis opcode-JUMP_IF_FALSE_OR_POP}@anchor{3a07}
@deffn {Opcode} JUMP_IF_FALSE_OR_POP (target)

如果 TOS 为假值，则将字节码计数器的值设为 @emph{target} 并将 TOS 留在栈顶。 否则（如 TOS 为真值），TOS 会被弹出。


3.1 新版功能.

@end deffn

@geindex JUMP_ABSOLUTE (opcode)
@anchor{library/dis opcode-JUMP_ABSOLUTE}@anchor{3a08}
@deffn {Opcode} JUMP_ABSOLUTE (target)

将字节码计数器的值设为 @emph{target}。
@end deffn

@geindex FOR_ITER (opcode)
@anchor{library/dis opcode-FOR_ITER}@anchor{3a09}
@deffn {Opcode} FOR_ITER (delta)

TOS 是一个 @ref{11ba,,iterator}。 请调用其 @ref{d34,,__next__()} 方法。 如果此操作产生了一个新值，则将其推入栈顶（将迭代器留在其下方）。 如果迭代器提示已耗尽，TOS 会被弹出，并且字节码计数器将增加 @emph{delta}。
@end deffn

@geindex LOAD_GLOBAL (opcode)
@anchor{library/dis opcode-LOAD_GLOBAL}@anchor{3a0a}
@deffn {Opcode} LOAD_GLOBAL (namei)

加载名称为 @code{co_names[namei]} 的全局对象推入栈顶。
@end deffn

@geindex SETUP_FINALLY (opcode)
@anchor{library/dis opcode-SETUP_FINALLY}@anchor{3a0b}
@deffn {Opcode} SETUP_FINALLY (delta)

将一个来自 try-finally 或 try-except 子句的 try 代码块推入代码块栈顶。 相对 finally 代码块或第一个 except 代码块 @emph{delta} 个点数。
@end deffn

@geindex LOAD_FAST (opcode)
@anchor{library/dis opcode-LOAD_FAST}@anchor{3a0c}
@deffn {Opcode} LOAD_FAST (var_num)

将指向局部对象 @code{co_varnames[var_num]} 的引用推入栈顶。
@end deffn

@geindex STORE_FAST (opcode)
@anchor{library/dis opcode-STORE_FAST}@anchor{39e9}
@deffn {Opcode} STORE_FAST (var_num)

将 TOS 存放到局部对象 @code{co_varnames[var_num]}。
@end deffn

@geindex DELETE_FAST (opcode)
@anchor{library/dis opcode-DELETE_FAST}@anchor{3a0d}
@deffn {Opcode} DELETE_FAST (var_num)

移除局部对象 @code{co_varnames[var_num]}。
@end deffn

@geindex LOAD_CLOSURE (opcode)
@anchor{library/dis opcode-LOAD_CLOSURE}@anchor{3a0e}
@deffn {Opcode} LOAD_CLOSURE (i)

将一个包含在单元的第 @emph{i} 个空位中的对单元的引用推入栈顶并释放可用的存储空间。 如果 @emph{i} 小于 @emph{co_cellvars} 的长度则变量的名称为 @code{co_cellvars[i]}。 否则为 @code{co_freevars[i - len(co_cellvars)]}。
@end deffn

@geindex LOAD_DEREF (opcode)
@anchor{library/dis opcode-LOAD_DEREF}@anchor{3a0f}
@deffn {Opcode} LOAD_DEREF (i)

加载包含在单元的第 @emph{i} 个空位中的单元并释放可用的存储空间。 将一个对单元所包含对象的引用推入栈顶。
@end deffn

@geindex LOAD_CLASSDEREF (opcode)
@anchor{library/dis opcode-LOAD_CLASSDEREF}@anchor{a1c}
@deffn {Opcode} LOAD_CLASSDEREF (i)

类似于 @ref{3a0f,,LOAD_DEREF} 但在查询单元之前会首先检查局部对象字典。 这被用于加载类语句体中的自由变量。


3.4 新版功能.

@end deffn

@geindex STORE_DEREF (opcode)
@anchor{library/dis opcode-STORE_DEREF}@anchor{3a10}
@deffn {Opcode} STORE_DEREF (i)

将 TOS 存放到包含在单元的第 @emph{i} 个空位中的单元内并释放可用存储空间。
@end deffn

@geindex DELETE_DEREF (opcode)
@anchor{library/dis opcode-DELETE_DEREF}@anchor{3a11}
@deffn {Opcode} DELETE_DEREF (i)

清空包含在单元的第 @emph{i} 个空位中的单元并释放可用存储空间。 被用于 @ref{13d1,,del} 语句。


3.2 新版功能.

@end deffn

@geindex RAISE_VARARGS (opcode)
@anchor{library/dis opcode-RAISE_VARARGS}@anchor{3a12}
@deffn {Opcode} RAISE_VARARGS (argc)

使用 @code{raise} 语句的 3 种形式之一引发异常，具体形式取决于 @emph{argc} 的值：


@itemize *

@item 
0: @code{raise} (重新引发之前的异常)

@item 
1: @code{raise TOS} (在 @code{TOS} 上引发异常实例或类型)

@item 
2: @code{raise TOS1 from TOS} (在 @code{TOS1} 上引发异常实例或类型并将 @code{__cause__} 设为 @code{TOS})
@end itemize
@end deffn

@geindex CALL_FUNCTION (opcode)
@anchor{library/dis opcode-CALL_FUNCTION}@anchor{718}
@deffn {Opcode} CALL_FUNCTION (argc)

调用一个可调用对象并传入位置参数。 @emph{argc} 指明位置参数的数量。 栈顶包含位置参数，其中最右边的参数在最顶端。 在参数之下是一个待调用的可调用对象。 @code{CALL_FUNCTION} 会从栈中弹出所有参数以及可调用对象，附带这些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。


在 3.6 版更改: 此操作码仅用于附带位置参数的调用。

@end deffn

@geindex CALL_FUNCTION_KW (opcode)
@anchor{library/dis opcode-CALL_FUNCTION_KW}@anchor{719}
@deffn {Opcode} CALL_FUNCTION_KW (argc)

调用一个可调用对象并传入位置参数（如果有的话）和关键字参数。 @emph{argc} 指明位置参数和关键字参数的总数量。 栈顶元素包含一个关键字参数名称的元组，名称必须为字符串。 在元组之下是与元组顺序相对应的关键字参数值。 在它之下则是位置参数，其中最右边的参数在最顶端。 在参数之下是要调用的可调用对象。 @code{CALL_FUNCTION_KW} 会从栈中弹出所有参数及可调用对象，附带这些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。


在 3.6 版更改: 关键字参数会被打包为一个元组而非字典，@emph{argc} 指明参数的总数量。

@end deffn

@geindex CALL_FUNCTION_EX (opcode)
@anchor{library/dis opcode-CALL_FUNCTION_EX}@anchor{71a}
@deffn {Opcode} CALL_FUNCTION_EX (flags)

调用一个可调用对象并附带位置参数和关键字参数变量集合。 如果设置了 @emph{flags} 的最低位，则栈顶包含一个由额外关键字参数组成的映射对象。 在调用该可调用对象之前，映射对象和可迭代对象会被分别“解包”并将它们的内容分别作为关键字参数和位置参数传入。 @code{CALL_FUNCTION_EX} 会中栈中弹出所有参数及可调用对象，附带这些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。


3.6 新版功能.

@end deffn

@geindex LOAD_METHOD (opcode)
@anchor{library/dis opcode-LOAD_METHOD}@anchor{5b0}
@deffn {Opcode} LOAD_METHOD (namei)

从 TOS 对象加载一个名为 @code{co_names[namei]} 的方法。 TOS 将被弹出。 此字节码可区分两种情况：如果 TOS 有一个名称正确的方法，字节码会将未绑定方法和 TOS 推入栈顶。 TOS 将在调用未绑定方法时被用作 @ref{5b1,,CALL_METHOD} 的第一个参数 (@code{self})。 否则会将 @code{NULL} 和属性查找所返回的对象推入栈顶。


3.7 新版功能.

@end deffn

@geindex CALL_METHOD (opcode)
@anchor{library/dis opcode-CALL_METHOD}@anchor{5b1}
@deffn {Opcode} CALL_METHOD (argc)

调用一个方法。 @emph{argc} 是位置参数的数量。 关键字参数不受支持。 此操作码被设计用于配合 @ref{5b0,,LOAD_METHOD} 使用。 位置参数放在栈顶。 在它们之下放在栈中的是由 @ref{5b0,,LOAD_METHOD} 所描述的两个条目（或者是 @code{self} 和一个未绑定方法对象，或者是 @code{NULL} 和一个任意可调用对象）。 它们会被全部弹出并将返回值推入栈顶。


3.7 新版功能.

@end deffn

@geindex MAKE_FUNCTION (opcode)
@anchor{library/dis opcode-MAKE_FUNCTION}@anchor{717}
@deffn {Opcode} MAKE_FUNCTION (flags)

将一个新函数对象推入栈顶。 从底端到顶端，如果参数带有指定的旗标值则所使用的栈必须由这些值组成。


@itemize *

@item 
@code{0x01} 一个默认值的元组，用于按位置排序的仅限位置形参以及位置或关键字形参

@item 
@code{0x02} 一个仅限关键字形参的默认值的字典

@item 
@code{0x04} 是一个标注字典

@item 
@code{0x08} 一个包含用于自由变量的单元的元组，生成一个闭包

@item 
与函数相关联的代码 (在 TOS1)

@item 
函数的 @ref{158b,,qualified name} (在 TOS)
@end itemize
@end deffn

@geindex BUILD_SLICE (opcode)
@anchor{library/dis opcode-BUILD_SLICE}@anchor{3a13}
@deffn {Opcode} BUILD_SLICE (argc)

@geindex 內置函数; slice

将一个切片对象推入栈顶。 @emph{argc} 必须为 2 或 3。 如果为 2，则推入 @code{slice(TOS1, TOS)}；如果为 3，则推入 @code{slice(TOS2, TOS1, TOS)}。 请参阅 @ref{ed0,,slice()} 内置函数了解详细信息。
@end deffn

@geindex EXTENDED_ARG (opcode)
@anchor{library/dis opcode-EXTENDED_ARG}@anchor{3a14}
@deffn {Opcode} EXTENDED_ARG (ext)

为任意带有大到无法放入默认的单字节的参数的操作码添加前缀。 @emph{ext} 存放一个附加字节作为参数中的高比特位。 对于每个操作码，最多允许三个 @code{EXTENDED_ARG} 前缀，构成两字节到三字节的参数。
@end deffn

@geindex FORMAT_VALUE (opcode)
@anchor{library/dis opcode-FORMAT_VALUE}@anchor{714}
@deffn {Opcode} FORMAT_VALUE (flags)

用于实现格式化字面值字符串（f-字符串）。 从栈中弹出一个可选的 @emph{fmt_spec}，然后是一个必须的 @emph{value}。 @emph{flags} 的解读方式如下：


@itemize *

@item 
@code{(flags & 0x03) == 0x00}: @emph{value} 按原样格式化。

@item 
@code{(flags & 0x03) == 0x01}: 在格式化 @emph{value} 之前调用其 @ref{206,,str()}。

@item 
@code{(flags & 0x03) == 0x02}: 在格式化 @emph{value} 之前调用其 @ref{8c3,,repr()}。

@item 
@code{(flags & 0x03) == 0x03}: 在格式化 @emph{value} 之前调用其 @ref{e19,,ascii()}。

@item 
@code{(flags & 0x04) == 0x04}: 从栈中弹出 @emph{fmt_spec} 并使用它，否则使用空的 @emph{fmt_spec}。
@end itemize

使用 @code{PyObject_Format()} 执行格式化。 结果会被推入栈顶。


3.6 新版功能.

@end deffn

@geindex HAVE_ARGUMENT (opcode)
@anchor{library/dis opcode-HAVE_ARGUMENT}@anchor{3a15}
@deffn {Opcode} HAVE_ARGUMENT

这不是一个真正的操作码。 它用于标明使用参数和不使用参数的操作码 (分别为 @code{< HAVE_ARGUMENT} 和 @code{>= HAVE_ARGUMENT}) 之间的分隔线。


在 3.6 版更改: 现在每条指令都带有参数，但操作码 @code{< HAVE_ARGUMENT} 会忽略它。 之前仅限操作码 @code{>= HAVE_ARGUMENT} 带有参数。

@end deffn

@node 操作码集合,,Python字节码说明,dis --- Python 字节码反汇编器
@anchor{library/dis id1}@anchor{3a16}@anchor{library/dis opcode-collections}@anchor{39a6}
@subsubsection 操作码集合


提供这些集合用于字节码指令的自动内省：

@geindex opname() (在 dis 模块中)
@anchor{library/dis dis opname}@anchor{3a17}
@deffn {数据} dis.opname

操作名称的序列，可使用字节码来索引。
@end deffn

@geindex opmap() (在 dis 模块中)
@anchor{library/dis dis opmap}@anchor{3a18}
@deffn {数据} dis.opmap

映射操作名称到字节码的字典
@end deffn

@geindex cmp_op() (在 dis 模块中)
@anchor{library/dis dis cmp_op}@anchor{3a19}
@deffn {数据} dis.cmp_op

所有比较操作名称的序列。
@end deffn

@geindex hasconst() (在 dis 模块中)
@anchor{library/dis dis hasconst}@anchor{3a1a}
@deffn {数据} dis.hasconst

访问常量的字节码序列。
@end deffn

@geindex hasfree() (在 dis 模块中)
@anchor{library/dis dis hasfree}@anchor{3a1b}
@deffn {数据} dis.hasfree

访问自由变量的字节码序列（请注意这里所说的‘自由’是指在当前作用域中被内部作用域所引用的名称，或在外部作用域中被此作用域所引用的名称。 它 @emph{并不} 包括对全局或内置作用域的引用）。
@end deffn

@geindex hasname() (在 dis 模块中)
@anchor{library/dis dis hasname}@anchor{3a1c}
@deffn {数据} dis.hasname

按名称访问属性的字节码序列。
@end deffn

@geindex hasjrel() (在 dis 模块中)
@anchor{library/dis dis hasjrel}@anchor{3a1d}
@deffn {数据} dis.hasjrel

具有相对跳转目标的字节码序列。
@end deffn

@geindex hasjabs() (在 dis 模块中)
@anchor{library/dis dis hasjabs}@anchor{3a1e}
@deffn {数据} dis.hasjabs

具有绝对跳转目标的字节码序列。
@end deffn

@geindex haslocal() (在 dis 模块中)
@anchor{library/dis dis haslocal}@anchor{3a1f}
@deffn {数据} dis.haslocal

访问局部变量的字节码序列。
@end deffn

@geindex hascompare() (在 dis 模块中)
@anchor{library/dis dis hascompare}@anchor{3a20}
@deffn {数据} dis.hascompare

布尔运算的字节码序列。
@end deffn

@node pickletools --- pickle 开发者工具集,,dis --- Python 字节码反汇编器,Python 语言服务
@anchor{library/pickletools doc}@anchor{3a21}@anchor{library/pickletools module-pickletools}@anchor{cb}@anchor{library/pickletools pickletools-tools-for-pickle-developers}@anchor{3a22}
@subsection @code{pickletools} --- pickle 开发者工具集


@geindex pickletools (模块)

@strong{源代码:} Lib/pickletools.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pickletools.py}


__________________________________________________________________


此模块包含与 @ref{ca,,pickle} 模块内部细节有关的多个常量，一些关于具体实现的详细注释，以及一些能够分析封存数据的有用函数。 此模块的内容对需要操作 @ref{ca,,pickle} 的 Python 核心开发者来说很有用处；@ref{ca,,pickle} 的一般用户则可能会感觉 @ref{cb,,pickletools} 模块与他们无关。

@menu
* 命令行语法: 命令行语法<2>. 
* 编程接口: 编程接口<2>. 

@end menu

@node 命令行语法<2>,编程接口<2>,,pickletools --- pickle 开发者工具集
@anchor{library/pickletools command-line-usage}@anchor{3a23}
@subsubsection 命令行语法



3.2 新版功能.


当从命令行发起调用时，@code{python -m pickletools} 将对一个或更多 pickle 文件的内容进行拆解。 请注意如果你查看 pickle 中保存的 Python 对象而非 pickle 格式的细节，你可能需要改用 @code{-m pickle}。 但是，当你想检查的 pickle 文件来自某个不受信任的源时，@code{-m pickletools} 是更安全的选择，因为它不会执行 pickle 字节码。

例如，对于一个封存在文件 @code{x.pickle} 中的元组 @code{(1, 2)}:

@example
$ python -m pickle x.pickle
(1, 2)

$ python -m pickletools x.pickle
    0: \x80 PROTO      3
    2: K    BININT1    1
    4: K    BININT1    2
    6: \x86 TUPLE2
    7: q    BINPUT     0
    9: .    STOP
highest protocol among opcodes = 2
@end example

@menu
* 命令行选项: 命令行选项<6>. 

@end menu

@node 命令行选项<6>,,,命令行语法<2>
@anchor{library/pickletools command-line-options}@anchor{3a24}
@subsubsection 命令行选项


@geindex pickletools command line option; -a
@geindex pickletools command line option; --annotate
@anchor{library/pickletools cmdoption-pickletools-a}@anchor{3a25}
@deffn {程序选项} @w{-}a, @w{-}@w{-}annotate

使用简短的操作码描述来标注每一行。
@end deffn

@geindex pickletools command line option; -o
@geindex pickletools command line option; --output=<file>
@anchor{library/pickletools cmdoption-pickletools-o}@anchor{3a26}
@deffn {程序选项} @w{-}o, @w{-}@w{-}output=<file>

输出应当写入到的文件名称。
@end deffn

@geindex pickletools command line option; -l
@geindex pickletools command line option; --indentlevel=<num>
@anchor{library/pickletools cmdoption-pickletools-l}@anchor{3a27}
@deffn {程序选项} @w{-}l, @w{-}@w{-}indentlevel=<num>

一个新的 MARK 层级所需缩进的空格数。
@end deffn

@geindex pickletools command line option; -m
@geindex pickletools command line option; --memo
@anchor{library/pickletools cmdoption-pickletools-m}@anchor{3a28}
@deffn {程序选项} @w{-}m, @w{-}@w{-}memo

当反汇编多个对象时，保留各个反汇编的备忘记录。
@end deffn

@geindex pickletools command line option; -p
@geindex pickletools command line option; --preamble=<preamble>
@anchor{library/pickletools cmdoption-pickletools-p}@anchor{3a29}
@deffn {程序选项} @w{-}p, @w{-}@w{-}preamble=<preamble>

当指定一个以上的 pickle 文件时，在每次反汇编之前打印给定的前言。
@end deffn

@node 编程接口<2>,,命令行语法<2>,pickletools --- pickle 开发者工具集
@anchor{library/pickletools programmatic-interface}@anchor{3a2a}
@subsubsection 编程接口


@geindex dis() (在 pickletools 模块中)
@anchor{library/pickletools pickletools dis}@anchor{672}
@deffn {函数} pickletools.dis (pickle, out=None, memo=None, indentlevel=4, annotate=0)

将 pickle 的符号化反汇编数据输出到文件类对象 @emph{out}，默认为 @code{sys.stdout}。 @emph{pickle} 可以是一个字符串或一个文件类对象。 @emph{memo} 可以是一个将被用作 pickle 的备忘记录的 Python 字典；它可被用来对由同一封存器创建的多个封存对象执行反汇编。 由 @code{MARK} 操作码指明的每个连续级别将会缩进 @emph{indentlevel} 个空格。 如果为 @emph{annotate} 指定了一个非零值，则输出中的每个操作码将以一个简短描述来标注。 @emph{annotate} 的值会被用作标注所应开始的列的提示。


3.2 新版功能: @emph{annotate} 参数。

@end deffn

@geindex genops() (在 pickletools 模块中)
@anchor{library/pickletools pickletools genops}@anchor{3a2b}
@deffn {函数} pickletools.genops (pickle)

提供包含 pickle 中所有操作码的 @ref{11ba,,iterator}，返回一个 @code{(opcode, arg, pos)} 三元组的序列。 @emph{opcode} 是 @code{OpcodeInfo} 类的一个实例；@emph{arg} 是 Python 对象形式的 opcode 参数的已解码值；@emph{pos} 是 opcode 所在的位置。 @emph{pickle} 可以是一个字符串或一个文件类对象。
@end deffn

@geindex optimize() (在 pickletools 模块中)
@anchor{library/pickletools pickletools optimize}@anchor{1e61}
@deffn {函数} pickletools.optimize (picklestring)

在消除未使用的 @code{PUT} 操作码之后返回一个新的等效 pickle 字符串。 优化后的 pickle 将更为简短，耗费更为的传输时间，要求更少的存储空间并能更高效地解封。
@end deffn

@node 杂项服务,Windows系统相关模块,Python 语言服务,Python 标准库
@anchor{library/misc doc}@anchor{3a2c}@anchor{library/misc misc}@anchor{3a2d}@anchor{library/misc miscellaneous-services}@anchor{3a2e}
@section 杂项服务


本章中介绍的模块提供了所有 Python 版本中提供的各种杂项服务。 这是一个概述：

@menu
* formatter: formatter --- 通用格式化输出. 通用格式化输出

@end menu

@node formatter --- 通用格式化输出,,,杂项服务
@anchor{library/formatter doc}@anchor{3a2f}@anchor{library/formatter formatter-generic-output-formatting}@anchor{3a30}@anchor{library/formatter module-formatter}@anchor{80}
@subsection @code{formatter} --- 通用格式化输出


@geindex formatter (模块)


3.4 版后已移除: 因为被使用的次数很少，此格式化模块已经被弃用了。



__________________________________________________________________


This module supports two interface definitions, each with multiple
implementations: The @emph{formatter} interface, and the @emph{writer} interface which is
required by the formatter interface.

Formatter objects transform an abstract flow of formatting events into specific
output events on writer objects.  Formatters manage several stack structures to
allow various properties of a writer object to be changed and restored; writers
need not be able to handle relative changes nor any sort of "change back"
operation.  Specific writer properties which may be controlled via formatter
objects are horizontal alignment, font, and left margin indentations.  A
mechanism is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well.  Additional interfaces facilitate formatting
events which are not reversible, such as paragraph separation.

Writer objects encapsulate device interfaces.  Abstract devices, such as file
formats, are supported as well as physical devices.  The provided
implementations all work with abstract devices.  The interface makes available
mechanisms for setting the properties which formatter objects manage and
inserting data into the output.

@menu
* The Formatter Interface:: 
* Formatter Implementations:: 
* The Writer Interface:: 
* Writer Implementations:: 

@end menu

@node The Formatter Interface,Formatter Implementations,,formatter --- 通用格式化输出
@anchor{library/formatter formatter-interface}@anchor{3a31}@anchor{library/formatter the-formatter-interface}@anchor{3a32}
@subsubsection The Formatter Interface


Interfaces to create formatters are dependent on the specific formatter class
being instantiated.  The interfaces described below are the required interfaces
which all formatters must support once initialized.

One data element is defined at the module level:

@geindex AS_IS() (在 formatter 模块中)
@anchor{library/formatter formatter AS_IS}@anchor{3a33}
@deffn {数据} formatter.AS_IS

Value which can be used in the font specification passed to the @code{push_font()}
method described below, or as the new value to any other @code{push_property()}
method.  Pushing the @code{AS_IS} value allows the corresponding @code{pop_property()}
method to be called without having to track whether the property was changed.
@end deffn

The following attributes are defined for formatter instance objects:

@geindex writer (formatter.formatter 属性)
@anchor{library/formatter formatter formatter writer}@anchor{3a34}
@deffn {属性} formatter.writer

The writer instance with which the formatter interacts.
@end deffn

@geindex end_paragraph() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter end_paragraph}@anchor{3a35}
@deffn {方法} formatter.end_paragraph (blanklines)

Close any open paragraphs and insert at least @emph{blanklines} before the next
paragraph.
@end deffn

@geindex add_line_break() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter add_line_break}@anchor{3a36}
@deffn {方法} formatter.add_line_break ()

Add a hard line break if one does not already exist.  This does not break the
logical paragraph.
@end deffn

@geindex add_hor_rule() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter add_hor_rule}@anchor{3a37}
@deffn {方法} formatter.add_hor_rule (*args, **kw)

Insert a horizontal rule in the output.  A hard break is inserted if there is
data in the current paragraph, but the logical paragraph is not broken.  The
arguments and keywords are passed on to the writer's @code{send_line_break()}
method.
@end deffn

@geindex add_flowing_data() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter add_flowing_data}@anchor{3a38}
@deffn {方法} formatter.add_flowing_data (data)

Provide data which should be formatted with collapsed whitespace. Whitespace
from preceding and successive calls to @ref{3a38,,add_flowing_data()} is considered as
well when the whitespace collapse is performed.  The data which is passed to
this method is expected to be word-wrapped by the output device.  Note that any
word-wrapping still must be performed by the writer object due to the need to
rely on device and font information.
@end deffn

@geindex add_literal_data() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter add_literal_data}@anchor{3a39}
@deffn {方法} formatter.add_literal_data (data)

Provide data which should be passed to the writer unchanged. Whitespace,
including newline and tab characters, are considered legal in the value of
@emph{data}.
@end deffn

@geindex add_label_data() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter add_label_data}@anchor{3a3a}
@deffn {方法} formatter.add_label_data (format, counter)

Insert a label which should be placed to the left of the current left margin.
This should be used for constructing bulleted or numbered lists.  If the
@emph{format} value is a string, it is interpreted as a format specification for
@emph{counter}, which should be an integer. The result of this formatting becomes the
value of the label; if @emph{format} is not a string it is used as the label value
directly. The label value is passed as the only argument to the writer's
@code{send_label_data()} method.  Interpretation of non-string label values is
dependent on the associated writer.

Format specifications are strings which, in combination with a counter value,
are used to compute label values.  Each character in the format string is copied
to the label value, with some characters recognized to indicate a transform on
the counter value.  Specifically, the character @code{'1'} represents the counter
value formatter as an Arabic number, the characters @code{'A'} and @code{'a'}
represent alphabetic representations of the counter value in upper and lower
case, respectively, and @code{'I'} and @code{'i'} represent the counter value in Roman
numerals, in upper and lower case.  Note that the alphabetic and roman
transforms require that the counter value be greater than zero.
@end deffn

@geindex flush_softspace() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter flush_softspace}@anchor{3a3b}
@deffn {方法} formatter.flush_softspace ()

Send any pending whitespace buffered from a previous call to
@ref{3a38,,add_flowing_data()} to the associated writer object.  This should be called
before any direct manipulation of the writer object.
@end deffn

@geindex push_alignment() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter push_alignment}@anchor{3a3c}
@deffn {方法} formatter.push_alignment (align)

Push a new alignment setting onto the alignment stack.  This may be
@ref{3a33,,AS_IS} if no change is desired.  If the alignment value is changed from
the previous setting, the writer's @code{new_alignment()} method is called with
the @emph{align} value.
@end deffn

@geindex pop_alignment() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter pop_alignment}@anchor{3a3d}
@deffn {方法} formatter.pop_alignment ()

Restore the previous alignment.
@end deffn

@geindex push_font() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter push_font}@anchor{3a3e}
@deffn {方法} formatter.push_font ((size, italic, bold, teletype))

Change some or all font properties of the writer object.  Properties which are
not set to @ref{3a33,,AS_IS} are set to the values passed in while others are
maintained at their current settings.  The writer's @code{new_font()} method is
called with the fully resolved font specification.
@end deffn

@geindex pop_font() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter pop_font}@anchor{3a3f}
@deffn {方法} formatter.pop_font ()

Restore the previous font.
@end deffn

@geindex push_margin() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter push_margin}@anchor{3a40}
@deffn {方法} formatter.push_margin (margin)

Increase the number of left margin indentations by one, associating the logical
tag @emph{margin} with the new indentation.  The initial margin level is @code{0}.
Changed values of the logical tag must be true values; false values other than
@ref{3a33,,AS_IS} are not sufficient to change the margin.
@end deffn

@geindex pop_margin() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter pop_margin}@anchor{3a41}
@deffn {方法} formatter.pop_margin ()

Restore the previous margin.
@end deffn

@geindex push_style() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter push_style}@anchor{3a42}
@deffn {方法} formatter.push_style (*styles)

Push any number of arbitrary style specifications.  All styles are pushed onto
the styles stack in order.  A tuple representing the entire stack, including
@ref{3a33,,AS_IS} values, is passed to the writer's @code{new_styles()} method.
@end deffn

@geindex pop_style() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter pop_style}@anchor{3a43}
@deffn {方法} formatter.pop_style (n=1)

Pop the last @emph{n} style specifications passed to @ref{3a42,,push_style()}.  A tuple
representing the revised stack, including @ref{3a33,,AS_IS} values, is passed to
the writer's @code{new_styles()} method.
@end deffn

@geindex set_spacing() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter set_spacing}@anchor{3a44}
@deffn {方法} formatter.set_spacing (spacing)

Set the spacing style for the writer.
@end deffn

@geindex assert_line_data() (formatter.formatter 方法)
@anchor{library/formatter formatter formatter assert_line_data}@anchor{3a45}
@deffn {方法} formatter.assert_line_data (flag=1)

Inform the formatter that data has been added to the current paragraph
out-of-band.  This should be used when the writer has been manipulated
directly.  The optional @emph{flag} argument can be set to false if the writer
manipulations produced a hard line break at the end of the output.
@end deffn

@node Formatter Implementations,The Writer Interface,The Formatter Interface,formatter --- 通用格式化输出
@anchor{library/formatter formatter-implementations}@anchor{3a46}@anchor{library/formatter formatter-impls}@anchor{3a47}
@subsubsection Formatter Implementations


Two implementations of formatter objects are provided by this module. Most
applications may use one of these classes without modification or subclassing.

@geindex NullFormatter (formatter 中的类)
@anchor{library/formatter formatter NullFormatter}@anchor{3a48}
@deffn {类} formatter.NullFormatter (writer=None)

A formatter which does nothing.  If @emph{writer} is omitted, a @ref{3a49,,NullWriter}
instance is created.  No methods of the writer are called by
@ref{3a48,,NullFormatter} instances.  Implementations should inherit from this
class if implementing a writer interface but don't need to inherit any
implementation.
@end deffn

@geindex AbstractFormatter (formatter 中的类)
@anchor{library/formatter formatter AbstractFormatter}@anchor{3a4a}
@deffn {类} formatter.AbstractFormatter (writer)

The standard formatter.  This implementation has demonstrated wide applicability
to many writers, and may be used directly in most circumstances.  It has been
used to implement a full-featured World Wide Web browser.
@end deffn

@node The Writer Interface,Writer Implementations,Formatter Implementations,formatter --- 通用格式化输出
@anchor{library/formatter the-writer-interface}@anchor{3a4b}@anchor{library/formatter writer-interface}@anchor{3a4c}
@subsubsection The Writer Interface


Interfaces to create writers are dependent on the specific writer class being
instantiated.  The interfaces described below are the required interfaces which
all writers must support once initialized. Note that while most applications can
use the @ref{3a4a,,AbstractFormatter} class as a formatter, the writer must
typically be provided by the application.

@geindex flush() (formatter.writer 方法)
@anchor{library/formatter formatter writer flush}@anchor{3a4d}
@deffn {方法} writer.flush ()

Flush any buffered output or device control events.
@end deffn

@geindex new_alignment() (formatter.writer 方法)
@anchor{library/formatter formatter writer new_alignment}@anchor{3a4e}
@deffn {方法} writer.new_alignment (align)

Set the alignment style.  The @emph{align} value can be any object, but by convention
is a string or @code{None}, where @code{None} indicates that the writer's "preferred"
alignment should be used. Conventional @emph{align} values are @code{'left'},
@code{'center'}, @code{'right'}, and @code{'justify'}.
@end deffn

@geindex new_font() (formatter.writer 方法)
@anchor{library/formatter formatter writer new_font}@anchor{3a4f}
@deffn {方法} writer.new_font (font)

Set the font style.  The value of @emph{font} will be @code{None}, indicating that the
device's default font should be used, or a tuple of the form @code{(size,
italic, bold, teletype)}.  Size will be a string indicating the size of
font that should be used; specific strings and their interpretation must be
defined by the application.  The @emph{italic}, @emph{bold}, and @emph{teletype} values are
Boolean values specifying which of those font attributes should be used.
@end deffn

@geindex new_margin() (formatter.writer 方法)
@anchor{library/formatter formatter writer new_margin}@anchor{3a50}
@deffn {方法} writer.new_margin (margin, level)

Set the margin level to the integer @emph{level} and the logical tag to @emph{margin}.
Interpretation of the logical tag is at the writer's discretion; the only
restriction on the value of the logical tag is that it not be a false value for
non-zero values of @emph{level}.
@end deffn

@geindex new_spacing() (formatter.writer 方法)
@anchor{library/formatter formatter writer new_spacing}@anchor{3a51}
@deffn {方法} writer.new_spacing (spacing)

Set the spacing style to @emph{spacing}.
@end deffn

@geindex new_styles() (formatter.writer 方法)
@anchor{library/formatter formatter writer new_styles}@anchor{3a52}
@deffn {方法} writer.new_styles (styles)

Set additional styles.  The @emph{styles} value is a tuple of arbitrary values; the
value @ref{3a33,,AS_IS} should be ignored.  The @emph{styles} tuple may be interpreted
either as a set or as a stack depending on the requirements of the application
and writer implementation.
@end deffn

@geindex send_line_break() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_line_break}@anchor{3a53}
@deffn {方法} writer.send_line_break ()

Break the current line.
@end deffn

@geindex send_paragraph() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_paragraph}@anchor{3a54}
@deffn {方法} writer.send_paragraph (blankline)

Produce a paragraph separation of at least @emph{blankline} blank lines, or the
equivalent.  The @emph{blankline} value will be an integer.  Note that the
implementation will receive a call to @ref{3a53,,send_line_break()} before this call
if a line break is needed;  this method should not include ending the last line
of the paragraph. It is only responsible for vertical spacing between
paragraphs.
@end deffn

@geindex send_hor_rule() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_hor_rule}@anchor{3a55}
@deffn {方法} writer.send_hor_rule (*args, **kw)

Display a horizontal rule on the output device.  The arguments to this method
are entirely application- and writer-specific, and should be interpreted with
care.  The method implementation may assume that a line break has already been
issued via @ref{3a53,,send_line_break()}.
@end deffn

@geindex send_flowing_data() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_flowing_data}@anchor{3a56}
@deffn {方法} writer.send_flowing_data (data)

Output character data which may be word-wrapped and re-flowed as needed.  Within
any sequence of calls to this method, the writer may assume that spans of
multiple whitespace characters have been collapsed to single space characters.
@end deffn

@geindex send_literal_data() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_literal_data}@anchor{3a57}
@deffn {方法} writer.send_literal_data (data)

Output character data which has already been formatted for display.  Generally,
this should be interpreted to mean that line breaks indicated by newline
characters should be preserved and no new line breaks should be introduced.  The
data may contain embedded newline and tab characters, unlike data provided to
the @code{send_formatted_data()} interface.
@end deffn

@geindex send_label_data() (formatter.writer 方法)
@anchor{library/formatter formatter writer send_label_data}@anchor{3a58}
@deffn {方法} writer.send_label_data (data)

Set @emph{data} to the left of the current left margin, if possible. The value of
@emph{data} is not restricted; treatment of non-string values is entirely
application- and writer-dependent.  This method will only be called at the
beginning of a line.
@end deffn

@node Writer Implementations,,The Writer Interface,formatter --- 通用格式化输出
@anchor{library/formatter writer-implementations}@anchor{3a59}@anchor{library/formatter writer-impls}@anchor{3a5a}
@subsubsection Writer Implementations


Three implementations of the writer object interface are provided as examples by
this module.  Most applications will need to derive new writer classes from the
@ref{3a49,,NullWriter} class.

@geindex NullWriter (formatter 中的类)
@anchor{library/formatter formatter NullWriter}@anchor{3a49}
@deffn {类} formatter.NullWriter

A writer which only provides the interface definition; no actions are taken on
any methods.  This should be the base class for all writers which do not need to
inherit any implementation methods.
@end deffn

@geindex AbstractWriter (formatter 中的类)
@anchor{library/formatter formatter AbstractWriter}@anchor{3a5b}
@deffn {类} formatter.AbstractWriter

A writer which can be used in debugging formatters, but not much else.  Each
method simply announces itself by printing its name and arguments on standard
output.
@end deffn

@geindex DumbWriter (formatter 中的类)
@anchor{library/formatter formatter DumbWriter}@anchor{3a5c}
@deffn {类} formatter.DumbWriter (file=None, maxcol=72)

Simple writer class which writes output on the @ref{c1d,,file object} passed
in as @emph{file} or, if @emph{file} is omitted, on standard output.  The output is
simply word-wrapped to the number of columns specified by @emph{maxcol}.  This
class is suitable for reflowing a sequence of paragraphs.
@end deffn

@node Windows系统相关模块,Unix 专有服务,杂项服务,Python 标准库
@anchor{library/windows doc}@anchor{3a5d}@anchor{library/windows ms-windows-specific-services}@anchor{3a5e}@anchor{library/windows mswin-specific-services}@anchor{14f6}
@section Windows系统相关模块


本章节叙述的模块只在 Windows 平台上可用。

@menu
* msvcrt: msvcrt --- 来自 MS VC++ 运行时的有用例程. 来自 MS VC++ 运行时的有用例程
* winreg: winreg --- Windows 注册表访问. Windows 注册表访问
* winsound —— Windows 系统的声音播放接口:: 

@end menu

@node msvcrt --- 来自 MS VC++ 运行时的有用例程,winreg --- Windows 注册表访问,,Windows系统相关模块
@anchor{library/msvcrt doc}@anchor{3a5f}@anchor{library/msvcrt module-msvcrt}@anchor{b6}@anchor{library/msvcrt msvcrt-useful-routines-from-the-ms-vc-runtime}@anchor{3a60}
@subsection @code{msvcrt} --- 来自 MS VC++ 运行时的有用例程


@geindex msvcrt (模块)


__________________________________________________________________


这些函数提供了对 Windows 平台上一些有用功能的访问。一些更高级别的模块使用这些函数来构建其服务的 Windows 实现。 例如， @ref{86,,getpass} 模块在实现 @ref{86,,getpass()} 函数时使用了这些函数。

关于这些函数的更多信息可以在平台 API 文档中找到。

该模块实现了控制台 I/O API 的普通和宽字符变体。普通的 API 只处理ASCII字符，国际化应用受限。应该尽可能地使用宽字符 API 。


在 3.3 版更改: 此模块中过去会引发 @ref{a7c,,IOError} 的操作现在将引发 @ref{30b,,OSError}。


@menu
* 文件操作:: 
* 控制台 I/O:: 
* 其他函数:: 

@end menu

@node 文件操作,控制台 I/O,,msvcrt --- 来自 MS VC++ 运行时的有用例程
@anchor{library/msvcrt file-operations}@anchor{3a61}@anchor{library/msvcrt msvcrt-files}@anchor{3a62}
@subsubsection 文件操作


@geindex locking() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt locking}@anchor{3558}
@deffn {函数} msvcrt.locking (fd, mode, nbytes)

基于文件描述符 @emph{fd} 从 C 运行时锁定文件的某一部分。 失败时引发 @ref{30b,,OSError}。 锁定的文件区域从当前文件位置开始扩展 @emph{nbytes} 个字节，并可能持续到超出文件末尾。 @emph{mode} 必须为下面列出的 @code{LK_*} 之一。 一个文件中的多个区域可以被同时锁定，但是不能重叠。 相邻区域不会被合并；它们必须单独被解锁。

引发一个 @ref{fec,,审计事件} @code{msvcrt.locking}，附带参数 @code{fd}, @code{mode}, @code{nbytes}。
@end deffn

@geindex LK_LOCK() (在 msvcrt 模块中)
@geindex LK_RLCK() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt LK_LOCK}@anchor{3a63}
@deffn {数据} msvcrt.LK_LOCK
@anchor{library/msvcrt msvcrt LK_RLCK}@anchor{3a64}
@deffnx {数据} msvcrt.LK_RLCK

锁定指定的字节数据。 如果字节数据无法被锁定，程序会在 1 秒之后立即重试。 如果在 10 次尝试后字节数据仍无法被锁定，则会引发 @ref{30b,,OSError}。
@end deffn

@geindex LK_NBLCK() (在 msvcrt 模块中)
@geindex LK_NBRLCK() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt LK_NBLCK}@anchor{3a65}
@deffn {数据} msvcrt.LK_NBLCK
@anchor{library/msvcrt msvcrt LK_NBRLCK}@anchor{3a66}
@deffnx {数据} msvcrt.LK_NBRLCK

锁定指定的字节数据。 如果字节数据无法被锁定，则会引发 @ref{30b,,OSError}。
@end deffn

@geindex LK_UNLCK() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt LK_UNLCK}@anchor{3a67}
@deffn {数据} msvcrt.LK_UNLCK

解锁指定的字节数据，该对象必须在之前被锁定。
@end deffn

@geindex setmode() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt setmode}@anchor{3a68}
@deffn {函数} msvcrt.setmode (fd, flags)

设置文件描述符 @emph{fd} 的行结束符转写模式。 要将其设为文本模式，则 @emph{flags} 应当为 @ref{20b6,,os.O_TEXT}；设为二进制模式，则应当为 @ref{20a7,,os.O_BINARY}。
@end deffn

@geindex open_osfhandle() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt open_osfhandle}@anchor{3559}
@deffn {函数} msvcrt.open_osfhandle (handle, flags)

基于文件句柄 @emph{handle} 创建一个 C 运行时文件描述符。 @emph{flags} 形参应当 @ref{20a9,,os.O_APPEND}, @ref{20a5,,os.O_RDONLY} 和 @ref{20b6,,os.O_TEXT} 按位 OR 的结果。 返回的文件描述符可以被用作 @ref{1593,,os.fdopen()} 的形参以创建一个文件对象。

引发一个 @ref{fec,,审计事件} @code{msvcrt.open_osfhandle}，附带参数 @code{handle}, @code{flags}。
@end deffn

@geindex get_osfhandle() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt get_osfhandle}@anchor{3557}
@deffn {函数} msvcrt.get_osfhandle (fd)

返回文件描述符 @emph{fd} 的文件句柄。 如果 @emph{fd} 不能被识别则会引发 @ref{30b,,OSError}。

引发一个 @ref{fec,,审计事件} @code{msvcrt.get_osfhandle}，附带参数 @code{fd}。
@end deffn

@node 控制台 I/O,其他函数,文件操作,msvcrt --- 来自 MS VC++ 运行时的有用例程
@anchor{library/msvcrt console-i-o}@anchor{3a69}@anchor{library/msvcrt msvcrt-console}@anchor{3a6a}
@subsubsection 控制台 I/O


@geindex kbhit() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt kbhit}@anchor{3a6b}
@deffn {函数} msvcrt.kbhit ()

如果有某个按键正在等待被读取则返回 @code{True}。
@end deffn

@geindex getch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt getch}@anchor{3a6c}
@deffn {函数} msvcrt.getch ()

读取一个按键并将结果字符返回为一个字节串。 不会有内容回显到缝制台。 如果还没有任何键被按下此调用将会阻塞，但它将不会等待 @code{Enter} 被按下。 如果按下的键是一个特殊功能键，此函数将返回 @code{'\000'} 或 @code{'\xe0'}；下一次调用将返回键代码。 @code{Control-C} 按钮无法使用此函数来读取。
@end deffn

@geindex getwch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt getwch}@anchor{3a6d}
@deffn {函数} msvcrt.getwch ()

@ref{3a6c,,getch()} 的宽字符版本，返回一个 Unicode 值。
@end deffn

@geindex getche() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt getche}@anchor{3a6e}
@deffn {函数} msvcrt.getche ()

类似于 @ref{3a6c,,getch()}，但按键如果表示一个可打印字符则它将被回显。
@end deffn

@geindex getwche() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt getwche}@anchor{3a6f}
@deffn {函数} msvcrt.getwche ()

@ref{3a6e,,getche()} 的宽字符版本，返回一个 Unicode 值。
@end deffn

@geindex putch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt putch}@anchor{3a70}
@deffn {函数} msvcrt.putch (char)

将字符串 @emph{char} 打印到终端，不使用缓冲区。
@end deffn

@geindex putwch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt putwch}@anchor{3a71}
@deffn {函数} msvcrt.putwch (unicode_char)

@ref{3a70,,putch()} 的宽字符版本，接受一个 Unicode 值。
@end deffn

@geindex ungetch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt ungetch}@anchor{3a72}
@deffn {函数} msvcrt.ungetch (char)

使得字节串 @emph{char} 被“推回”终端缓冲区；它将是被 @ref{3a6c,,getch()} 或 @ref{3a6e,,getche()} 读取的下一个字符。
@end deffn

@geindex ungetwch() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt ungetwch}@anchor{3a73}
@deffn {函数} msvcrt.ungetwch (unicode_char)

@ref{3a72,,ungetch()} 的宽字符版本，接受一个 Unicode 值。
@end deffn

@node 其他函数,,控制台 I/O,msvcrt --- 来自 MS VC++ 运行时的有用例程
@anchor{library/msvcrt msvcrt-other}@anchor{3a74}@anchor{library/msvcrt other-functions}@anchor{3a75}
@subsubsection 其他函数


@geindex heapmin() (在 msvcrt 模块中)
@anchor{library/msvcrt msvcrt heapmin}@anchor{3a76}
@deffn {函数} msvcrt.heapmin ()

强制 @code{malloc()} 堆清空自身并将未使用的块返回给操作系统。 失败时，这将引发 @ref{30b,,OSError}。
@end deffn

@node winreg --- Windows 注册表访问,winsound —— Windows 系统的声音播放接口,msvcrt --- 来自 MS VC++ 运行时的有用例程,Windows系统相关模块
@anchor{library/winreg doc}@anchor{3a77}@anchor{library/winreg module-winreg}@anchor{133}@anchor{library/winreg winreg-windows-registry-access}@anchor{3a78}
@subsection @code{winreg} --- Windows 注册表访问


@geindex winreg (模块)


__________________________________________________________________


这些函数将 Windows 注册表 API 暴露给 Python。 为了确保即便程序员忘记显式关闭时也能够正确关闭，这里没有用整数作为注册表句柄，而是采用了 @ref{3a79,,句柄对象}。
@anchor{library/winreg exception-changed}@anchor{3a7a}

在 3.3 版更改: 该模块中的几个函数被用于引发 @ref{a7e,,WindowsError}，该异常现在是 @ref{30b,,OSError} 的别名。


@menu
* 函数: 函数<11>. 
* 常数: 常数<7>. 
* 注册表句柄对象:: 

@end menu

@node 函数<11>,常数<7>,,winreg --- Windows 注册表访问
@anchor{library/winreg functions}@anchor{3a7b}@anchor{library/winreg id1}@anchor{3a7c}
@subsubsection 函数


该模块提供了下列函数：

@geindex CloseKey() (在 winreg 模块中)
@anchor{library/winreg winreg CloseKey}@anchor{3a7d}
@deffn {函数} winreg.CloseKey (hkey)

关闭之前打开的注册表键。参数 @emph{hkey} 指之前打开的键。

@cartouche
@quotation 注解 
如果没有使用该方法关闭 @emph{hkey} (或者通过 @ref{3a7e,,hkey.Close()})，在对象 @emph{hkey} 被 Python 销毁时会将其关闭。
@end quotation
@end cartouche
@end deffn

@geindex ConnectRegistry() (在 winreg 模块中)
@anchor{library/winreg winreg ConnectRegistry}@anchor{355f}
@deffn {函数} winreg.ConnectRegistry (computer_name, key)

建立到另一台计算机上的预定义注册表句柄的连接，并返回一个 @ref{3a79,,句柄对象}。

@emph{computer_name} 是远程计算机的名称，以 @code{r"\\computername"} 的形式。如果是 @code{None} ，将会使用本地计算机。

@emph{key} 是所连接到的预定义句柄。

返回值是所开打键的句柄。如果函数失败，则引发一个 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{winreg.ConnectRegistry}，附带参数 @code{computer_name}, @code{key}。


在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex CreateKey() (在 winreg 模块中)
@anchor{library/winreg winreg CreateKey}@anchor{3560}
@deffn {函数} winreg.CreateKey (key, sub_key)

创建或打开特定的键，返回一个 @ref{3a79,,handle 对象}。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 是用于命名该方法所打开或创建的键的字符串。

如果 @emph{key} 是预定义键之一，@emph{sub_key} 可能会是 @code{None}。该情况下，返回的句柄就是传入函数的句柄。

如果键已经存在，则该函数打开已经存在的该键。

返回值是所开打键的句柄。如果函数失败，则引发一个 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{winreg.CreateKey}，附带参数 @code{key}, @code{sub_key}, @code{access}。

引发一个 @ref{fec,,审计事件} @code{winreg.OpenKey/result}，附带参数 @code{key}。


在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex CreateKeyEx() (在 winreg 模块中)
@anchor{library/winreg winreg CreateKeyEx}@anchor{3561}
@deffn {函数} winreg.CreateKeyEx (key, sub_key, reserved=0, access=KEY_WRITE)

创建或打开特定的键，返回一个 @ref{3a79,,handle 对象}。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 是用于命名该方法所打开或创建的键的字符串。

@emph{reserved} 是一个保留的证书，必须是零。默认值为零。

@emph{access} 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为 @ref{3a80,,KEY_WRITE}。 参阅 @ref{3a81,,Access Rights}  了解其它允许值。

如果 @emph{key} 是预定义键之一，@emph{sub_key} 可能会是 @code{None}。该情况下，返回的句柄就是传入函数的句柄。

如果键已经存在，则该函数打开已经存在的该键。

返回值是所开打键的句柄。如果函数失败，则引发一个 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{winreg.CreateKey}，附带参数 @code{key}, @code{sub_key}, @code{access}。

引发一个 @ref{fec,,审计事件} @code{winreg.OpenKey/result}，附带参数 @code{key}。


3.2 新版功能.



在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex DeleteKey() (在 winreg 模块中)
@anchor{library/winreg winreg DeleteKey}@anchor{3562}
@deffn {函数} winreg.DeleteKey (key, sub_key)

删除指定的键。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 这个字符串必须是由 @emph{key} 参数所指定键的一个子项。该值项不可以是 @code{None}，同时键也不可以有子项。

@emph{该方法不能删除带有子项的键。}

如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则引发一个 @ref{30b,,OSError} 异常。

引发一个 @ref{fec,,审计事件} @code{winreg.DeleteKey}，附带参数 @code{key}, @code{sub_key}, @code{access}。


在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex DeleteKeyEx() (在 winreg 模块中)
@anchor{library/winreg winreg DeleteKeyEx}@anchor{3563}
@deffn {函数} winreg.DeleteKeyEx (key, sub_key, access=KEY_WOW64_64KEY, reserved=0)

删除指定的键。

@cartouche
@quotation 注解 
函数 @ref{3563,,DeleteKeyEx()} 通过 RegDeleteKeyEx 这个 Windows API 函数实现，该函数为 Windows 的64位版本专属。 参阅 RegDeleteKeyEx 文档@footnote{https://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx}。
@end quotation
@end cartouche

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 这个字符串必须是由 @emph{key} 参数所指定键的一个子项。该值项不可以是 @code{None}，同时键也不可以有子项。

@emph{reserved} 是一个保留的证书，必须是零。默认值为零。

@emph{access} 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为常量 @code{_WOW64_64KEY} 。参阅 @ref{3a81,,Access Rights}  了解其它允许值。

@emph{该方法不能删除带有子项的键。}

如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则引发一个 @ref{30b,,OSError} 异常。

在不支持的 Windows 版本之上，将会引发 @ref{70e,,NotImplementedError} 异常。

引发一个 @ref{fec,,审计事件} @code{winreg.DeleteKey}，附带参数 @code{key}, @code{sub_key}, @code{access}。


3.2 新版功能.



在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex DeleteValue() (在 winreg 模块中)
@anchor{library/winreg winreg DeleteValue}@anchor{3564}
@deffn {函数} winreg.DeleteValue (key, value)

从某个注册键中删除一个命名值项。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{value} 为标识所要删除值项的字符串。

引发一个 @ref{fec,,审计事件} @code{winreg.DeleteValue}，附带参数 @code{key}, @code{value}。
@end deffn

@geindex EnumKey() (在 winreg 模块中)
@anchor{library/winreg winreg EnumKey}@anchor{3567}
@deffn {函数} winreg.EnumKey (key, index)

列举某个已经打开注册表键的子项，并返回一个字符串。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{index} 为一个整数，用于标识所获取键的索引。

每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发 @ref{30b,,OSError} 异常，这说明已经没有更多的可用值了。

引发一个 @ref{fec,,审计事件} @code{winreg.EnumKey}，附带参数 @code{key}, @code{index}。


在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex EnumValue() (在 winreg 模块中)
@anchor{library/winreg winreg EnumValue}@anchor{3568}
@deffn {函数} winreg.EnumValue (key, index)

列举某个已经打开注册表键的值项，并返回一个元组。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{index} 为一个整数，用于标识要获取值项的索引。

每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发 @ref{30b,,OSError} 异常，这说明已经没有更多的可用值了。

结果为3元素的元组。


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

意义

@item

@code{0}

@tab

用于标识值项名称的字符串。

@item

@code{1}

@tab

保存值项数据的对象，其类型取决于背后的注册表类型。

@item

@code{2}

@tab

标识值项数据类型的整数。（请查阅 @ref{3573,,SetValueEx()} 文档中的表格）

@end multitable


引发一个 @ref{fec,,审计事件} @code{winreg.EnumValue}，附带参数 @code{key}, @code{index}。


在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex % (percent); environment variables expansion (Windows)

@geindex ExpandEnvironmentStrings() (在 winreg 模块中)
@anchor{library/winreg winreg ExpandEnvironmentStrings}@anchor{3569}
@deffn {函数} winreg.ExpandEnvironmentStrings (str)

Expands environment variable placeholders @code{%NAME%} in strings like
@ref{3a82,,REG_EXPAND_SZ}:

@example
>>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'
@end example

引发一个 @ref{fec,,审计事件} @code{winreg.ExpandEnvironmentStrings}，附带参数 @code{str}。
@end deffn

@geindex FlushKey() (在 winreg 模块中)
@anchor{library/winreg winreg FlushKey}@anchor{3a83}
@deffn {函数} winreg.FlushKey (key)

将某个键的所有属性写入注册表。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

没有必要调用 @ref{3a83,,FlushKey()} 去改动注册表键。注册表的变动是由其延迟刷新机制更新到磁盘的。在系统关机时，也会将注册表的变动写入磁盘。与  @ref{3a7d,,CloseKey()} 不同， @ref{3a83,,FlushKey()} 方法只有等到所有数据都写入注册表后才会返回。只有需要绝对确认注册表变动已写入磁盘时，应用程序才应去调用 @ref{3a83,,FlushKey()}。

@cartouche
@quotation 注解 
如果不知道是否要调用 @ref{3a83,,FlushKey()} ，可能就是不需要。
@end quotation
@end cartouche
@end deffn

@geindex LoadKey() (在 winreg 模块中)
@anchor{library/winreg winreg LoadKey}@anchor{356a}
@deffn {函数} winreg.LoadKey (key, sub_key, file_name)

在指定键之下创建一个子键，并将指定文件中的注册表信息存入该子键中。

@emph{key} 是由 @ref{355f,,ConnectRegistry()} 返回的句柄，或者是常量 @ref{3a84,,HKEY_USERS} 或 @ref{3a85,,HKEY_LOCAL_MACHINE} 之一。

@emph{sub_key} 是个字符串，用于标识需要载入的子键。

@emph{file_name} 是要加载注册表数据的文件名。该文件必须是用 @ref{3571,,SaveKey()} 函数创建的。在文件分配表（FAT）文件系统中，文件名可能不带扩展名。

如果调用 @ref{356a,,LoadKey()} 的进程没有 @code{SE_RESTORE_PRIVILEGE} 权限，则调用会失败。请注意，特权与权限不同 —— 更多细节请参阅 RegLoadKey 文档@footnote{https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx}。

如果 @emph{key} 是由 @ref{355f,,ConnectRegistry()} 返回的句柄，那么 @emph{file_name} 指定的路径是相对于远程计算机而言的。

引发一个 @ref{fec,,审计事件} @code{winreg.LoadKey}，附带参数 @code{key}, @code{sub_key}, @code{file_name}。
@end deffn

@geindex OpenKey() (在 winreg 模块中)
@geindex OpenKeyEx() (在 winreg 模块中)
@anchor{library/winreg winreg OpenKey}@anchor{356b}
@deffn {函数} winreg.OpenKey (key, sub_key, reserved=0, access=KEY_READ)
@anchor{library/winreg winreg OpenKeyEx}@anchor{3a86}
@deffnx {函数} winreg.OpenKeyEx (key, sub_key, reserved=0, access=KEY_READ)

打开指定的注册表键，返回 @ref{3a79,,handle对象}。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 是个字符串，标识了需要打开的子键。

@emph{reserved} 是个保留整数，必须为零。默认值为零。

@emph{access} 是个指定访问掩码的整数，掩码描述了注册表键所需的安全权限。 默认值为 @ref{3a87,,KEY_READ}。 其他合法值参见 @ref{3a81,,访问权限}。

返回结果为一个新句柄，指向指定的注册表键。

如果调用失败，则会触发  @ref{30b,,OSError} 。

引发一个 @ref{fec,,审计事件} @code{winreg.OpenKey}，附带参数 @code{key}, @code{sub_key}, @code{access}。

引发一个 @ref{fec,,审计事件} @code{winreg.OpenKey/result}，附带参数 @code{key}。


在 3.2 版更改: 允许使用命名参数。



在 3.3 版更改: 参考 @ref{3a7a,,上文}。

@end deffn

@geindex QueryInfoKey() (在 winreg 模块中)
@anchor{library/winreg winreg QueryInfoKey}@anchor{356d}
@deffn {函数} winreg.QueryInfoKey (key)

以元组形式返回某注册表键的信息。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

结果为3元素的元组。


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

意义

@item

@code{0}

@tab

表示此注册表键有多少个子键的整数值。

@item

@code{1}

@tab

整数值，给出了此注册表键的值的数量。

@item

@code{2}

@tab

整数值，给出了此注册表键的最后修改时间，单位为自 1601 年 1 月 1 日以来的 100 纳秒。

@end multitable


引发一个 @ref{fec,,审计事件} @code{winreg.QueryInfoKey}，附带参数 @code{key}。
@end deffn

@geindex QueryValue() (在 winreg 模块中)
@anchor{library/winreg winreg QueryValue}@anchor{356f}
@deffn {函数} winreg.QueryValue (key, sub_key)

读取某键的未命名值，形式为字符串。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 是个字符串，用于保存与某个值相关的子键名称。如果本参数为 @code{None} 或空，函数将读取由 @ref{3572,,SetValue()} 方法为 @emph{key} 键设置的值。

注册表中的值包含名称、类型和数据。本方法将读取注册表键值的第一个名称为 @code{NULL} 的数据。可是底层的 API 调用不会返回类型，所以如果可能的话，请一定使用 @ref{3570,,QueryValueEx()}。

引发一个 @ref{fec,,审计事件} @code{winreg.QueryValue}，附带参数 @code{key}, @code{sub_key}, @code{value_name}。
@end deffn

@geindex QueryValueEx() (在 winreg 模块中)
@anchor{library/winreg winreg QueryValueEx}@anchor{3570}
@deffn {函数} winreg.QueryValueEx (key, value_name)

读取已打开注册表键指定值名称的类型和数据。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{value_name} 是字符串，表示要查询的值。

结果为二元组：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

意义

@item

@code{0}

@tab

注册表项的值。

@item

@code{1}

@tab

整数值，给出该值的注册表类型（请查看文档中的表格了解 @ref{3573,,SetValueEx()} ）。

@end multitable


引发一个 @ref{fec,,审计事件} @code{winreg.QueryValue}，附带参数 @code{key}, @code{sub_key}, @code{value_name}。
@end deffn

@geindex SaveKey() (在 winreg 模块中)
@anchor{library/winreg winreg SaveKey}@anchor{3571}
@deffn {函数} winreg.SaveKey (key, file_name)

将指定注册表键及其所有子键存入指定的文件。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{file_name} 是要保存注册表数据的文件名。该文件不能已存在。如果文件名包括扩展名，也不能在文件分配表（FAT）文件系统中用于 @ref{356a,,LoadKey()} 方法。

如果 @emph{key} 代表远程计算机的注册表键，那么 @emph{file_name} 所描述的路径是相对于远程计算机的。本方法的调用者必须拥有 @code{SeBackupPrivilege} 特权。请注意，特权与权限是不同的 —— 更多细节请参见 用户权利和权限之间的冲突文档@footnote{https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx}。

本函数将 @code{NULL} 传给 API 的 @emph{security_attributes}。

引发一个 @ref{fec,,审计事件} @code{winreg.SaveKey}，附带参数 @code{key}, @code{file_name}。
@end deffn

@geindex SetValue() (在 winreg 模块中)
@anchor{library/winreg winreg SetValue}@anchor{3572}
@deffn {函数} winreg.SetValue (key, sub_key, type, value)

将值与指定的注册表键关联。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{sub_key} 是个字符串，用于命名与该值相关的子键。

@emph{type} 是个整数，用于指定数据的类型。目前这必须是 @ref{3a88,,REG_SZ} ，意味着只支持字符串。请用 @ref{3573,,SetValueEx()} 函数支持其他的数据类型。

@emph{value} 是设置新值的字符串。

如果 @emph{sub_key} 参数指定的注册表键不存在，SetValue 函数会创建一个。

值的长度受到可用内存的限制。较长的值（超过 2048 字节）应存为文件，并将文件名存入配置注册表。这有助于提高注册表的使用效率。

由 @emph{key} 参数标识的注册表键，必须已用 @ref{3a89,,KEY_SET_VALUE} 方式打开。

引发一个 @ref{fec,,审计事件} @code{winreg.SetValue}，附带参数 @code{key}, @code{sub_key}, @code{type}, @code{value}。
@end deffn

@geindex SetValueEx() (在 winreg 模块中)
@anchor{library/winreg winreg SetValueEx}@anchor{3573}
@deffn {函数} winreg.SetValueEx (key, value_name, reserved, type, value)

将数据存入已打开的注册表键的值中。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

@emph{value_name} 是个字符串，用于命名与值相关的子键。

@emph{reserved} 可以是任意数据 —— 传给 API 的总是 0。

@emph{type} 是个整数，用于指定数据的类型。请参阅 @ref{3a8a,,Value Types} 了解可用的类型。

@emph{value} 是设置新值的字符串。

本方法也可为指定的注册表键设置额外的值和类型信息。注册表键必须已用 @ref{3a89,,KEY_SET_VALUE} 方式打开。

请用 @ref{3560,,CreateKey()} 或 @ref{356b,,OpenKey()} 方法打开注册表键。

值的长度受到可用内存的限制。较长的值（超过 2048 字节）应存为文件，并将文件名存入配置注册表。这有助于提高注册表的使用效率。

引发一个 @ref{fec,,审计事件} @code{winreg.SetValue}，附带参数 @code{key}, @code{sub_key}, @code{type}, @code{value}。
@end deffn

@geindex DisableReflectionKey() (在 winreg 模块中)
@anchor{library/winreg winreg DisableReflectionKey}@anchor{3565}
@deffn {函数} winreg.DisableReflectionKey (key)

禁用运行于 64 位操作系统的 32 位进程的注册表重定向。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

如果在 32 位操作系统上执行，一般会触发 @ref{70e,,NotImplementedError}。

如果注册表键不在重定向列表中，函数会调用成功，但没有实际效果。禁用注册表键的重定向不会影响任何子键的重定向。

引发一个 @ref{fec,,审计事件} @code{winreg.DisableReflectionKey}，附带参数 @code{key}。
@end deffn

@geindex EnableReflectionKey() (在 winreg 模块中)
@anchor{library/winreg winreg EnableReflectionKey}@anchor{3566}
@deffn {函数} winreg.EnableReflectionKey (key)

恢复已禁用注册表键的重定向。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

如果在 32 位操作系统上执行，一般会触发 @ref{70e,,NotImplementedError}。

恢复注册表键的重定向不会影响任何子键的重定向。

引发一个 @ref{fec,,审计事件} @code{winreg.EnableReflectionKey}，附带参数 @code{key}。
@end deffn

@geindex QueryReflectionKey() (在 winreg 模块中)
@anchor{library/winreg winreg QueryReflectionKey}@anchor{356e}
@deffn {函数} winreg.QueryReflectionKey (key)

确定给定注册表键的重定向状况。

@emph{key} 为某个已经打开的键，或者预定义的 @ref{3a7f,,HKEY_* 常量} 之一。

如果重定向已禁用则返回 @code{True}。

如果在 32 位操作系统上执行，一般会触发 @ref{70e,,NotImplementedError}。

引发一个 @ref{fec,,审计事件} @code{winreg.QueryReflectionKey}，附带参数 @code{key}。
@end deffn

@node 常数<7>,注册表句柄对象,函数<11>,winreg --- Windows 注册表访问
@anchor{library/winreg constants}@anchor{3a8b}@anchor{library/winreg id2}@anchor{3a8c}
@subsubsection 常数


以下常量定义成可供很多 @code{_winreg} 函数使用。

@menu
* HKEY_* 常量:: 
* 访问权限:: 
* 注册表值的类型:: 

@end menu

@node HKEY_* 常量,访问权限,,常数<7>
@anchor{library/winreg hkey-constants}@anchor{3a7f}@anchor{library/winreg id3}@anchor{3a8d}
@subsubsection HKEY_* 常量


@geindex HKEY_CLASSES_ROOT() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_CLASSES_ROOT}@anchor{3a8e}
@deffn {数据} winreg.HKEY_CLASSES_ROOT

本注册表键下的注册表项定义了文件的类型（或类别）及相关属性。Shell 和 COM 应用程序将使用该注册表键下保存的信息。
@end deffn

@geindex HKEY_CURRENT_USER() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_CURRENT_USER}@anchor{3a8f}
@deffn {数据} winreg.HKEY_CURRENT_USER

属于该注册表键的表项定义了当前用户的偏好。这些偏好值包括环境变量设置、程序组数据、颜色、打印机、网络连接和应用程序参数。
@end deffn

@geindex HKEY_LOCAL_MACHINE() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_LOCAL_MACHINE}@anchor{3a85}
@deffn {数据} winreg.HKEY_LOCAL_MACHINE

属于该注册表键的表项定义了计算机的物理状态，包括总线类型、系统内存和已安装软硬件等数据。
@end deffn

@geindex HKEY_USERS() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_USERS}@anchor{3a84}
@deffn {数据} winreg.HKEY_USERS

属于该注册表键的表项定义了当前计算机中新用户的默认配置和当前用户配置。
@end deffn

@geindex HKEY_PERFORMANCE_DATA() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_PERFORMANCE_DATA}@anchor{3a90}
@deffn {数据} winreg.HKEY_PERFORMANCE_DATA

属于该注册表键的表项可用于读取性能数据。这些数据其实并不存放于注册表中；注册表提供功能让系统收集数据。
@end deffn

@geindex HKEY_CURRENT_CONFIG() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_CURRENT_CONFIG}@anchor{3a91}
@deffn {数据} winreg.HKEY_CURRENT_CONFIG

包含有关本地计算机系统当前硬件配置的信息。
@end deffn

@geindex HKEY_DYN_DATA() (在 winreg 模块中)
@anchor{library/winreg winreg HKEY_DYN_DATA}@anchor{3a92}
@deffn {数据} winreg.HKEY_DYN_DATA

Windows 98 以上版本不使用该注册表键。
@end deffn

@node 访问权限,注册表值的类型,HKEY_* 常量,常数<7>
@anchor{library/winreg access-rights}@anchor{3a81}@anchor{library/winreg id4}@anchor{3a93}
@subsubsection 访问权限


更多信息，请参阅 注册表密钥安全和访问@footnote{https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx}。

@geindex KEY_ALL_ACCESS() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_ALL_ACCESS}@anchor{3a94}
@deffn {数据} winreg.KEY_ALL_ACCESS

组合了 STANDARD_RIGHTS_REQUIRED 、@ref{3a95,,KEY_QUERY_VALUE} 、 @ref{3a89,,KEY_SET_VALUE} 、 @ref{3a96,,KEY_CREATE_SUB_KEY} 、 @ref{3a97,,KEY_ENUMERATE_SUB_KEYS} 、 @ref{3a98,,KEY_NOTIFY} 和 @ref{3a99,,KEY_CREATE_LINK} 访问权限。
@end deffn

@geindex KEY_WRITE() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_WRITE}@anchor{3a80}
@deffn {数据} winreg.KEY_WRITE

组合了 STANDARD_RIGHTS_WRITE 、 @ref{3a89,,KEY_SET_VALUE} 和 @ref{3a96,,KEY_CREATE_SUB_KEY} 访问权限。
@end deffn

@geindex KEY_READ() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_READ}@anchor{3a87}
@deffn {数据} winreg.KEY_READ

组合了 STANDARD_RIGHTS_READ 、 @ref{3a95,,KEY_QUERY_VALUE} 、 @ref{3a97,,KEY_ENUMERATE_SUB_KEYS} 和 @ref{3a98,,KEY_NOTIFY} 。
@end deffn

@geindex KEY_EXECUTE() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_EXECUTE}@anchor{3a9a}
@deffn {数据} winreg.KEY_EXECUTE

等价于  @ref{3a87,,KEY_READ}。
@end deffn

@geindex KEY_QUERY_VALUE() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_QUERY_VALUE}@anchor{3a95}
@deffn {数据} winreg.KEY_QUERY_VALUE

查询注册表键值时需要用到。
@end deffn

@geindex KEY_SET_VALUE() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_SET_VALUE}@anchor{3a89}
@deffn {数据} winreg.KEY_SET_VALUE

创建、删除或设置注册表值时需要用到。
@end deffn

@geindex KEY_CREATE_SUB_KEY() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_CREATE_SUB_KEY}@anchor{3a96}
@deffn {数据} winreg.KEY_CREATE_SUB_KEY

创建注册表键的子键时需要用到。
@end deffn

@geindex KEY_ENUMERATE_SUB_KEYS() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_ENUMERATE_SUB_KEYS}@anchor{3a97}
@deffn {数据} winreg.KEY_ENUMERATE_SUB_KEYS

枚举注册表键的子键时需要用到。
@end deffn

@geindex KEY_NOTIFY() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_NOTIFY}@anchor{3a98}
@deffn {数据} winreg.KEY_NOTIFY

为注册表键或子键请求修改通知时需要用到。
@end deffn

@geindex KEY_CREATE_LINK() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_CREATE_LINK}@anchor{3a99}
@deffn {数据} winreg.KEY_CREATE_LINK

保留给系统使用。
@end deffn

@menu
* 64 位系统特有:: 

@end menu

@node 64 位系统特有,,,访问权限
@anchor{library/winreg bit-access-rights}@anchor{3a9b}@anchor{library/winreg bit-specific}@anchor{3a9c}
@subsubsection 64 位系统特有


详情请参阅 Accessing an Alternate Registry View@footnote{https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx}。

@geindex KEY_WOW64_64KEY() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_WOW64_64KEY}@anchor{3a9d}
@deffn {数据} winreg.KEY_WOW64_64KEY

表示 64 位 Windows 中的应用程序应在 64 位注册表视图上操作。
@end deffn

@geindex KEY_WOW64_32KEY() (在 winreg 模块中)
@anchor{library/winreg winreg KEY_WOW64_32KEY}@anchor{3a9e}
@deffn {数据} winreg.KEY_WOW64_32KEY

表示 64 位 Windows 中的应用程序应在 32 位注册表视图上操作。
@end deffn

@node 注册表值的类型,,访问权限,常数<7>
@anchor{library/winreg id5}@anchor{3a9f}@anchor{library/winreg value-types}@anchor{3a8a}
@subsubsection 注册表值的类型


详情请参阅 Registry Value Types@footnote{https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx}。

@geindex REG_BINARY() (在 winreg 模块中)
@anchor{library/winreg winreg REG_BINARY}@anchor{3aa0}
@deffn {数据} winreg.REG_BINARY

任意格式的二进制数据。
@end deffn

@geindex REG_DWORD() (在 winreg 模块中)
@anchor{library/winreg winreg REG_DWORD}@anchor{3aa1}
@deffn {数据} winreg.REG_DWORD

32 位数值。
@end deffn

@geindex REG_DWORD_LITTLE_ENDIAN() (在 winreg 模块中)
@anchor{library/winreg winreg REG_DWORD_LITTLE_ENDIAN}@anchor{3aa2}
@deffn {数据} winreg.REG_DWORD_LITTLE_ENDIAN

32 位低字节序格式的数字。相当于 @ref{3aa1,,REG_DWORD}。
@end deffn

@geindex REG_DWORD_BIG_ENDIAN() (在 winreg 模块中)
@anchor{library/winreg winreg REG_DWORD_BIG_ENDIAN}@anchor{3aa3}
@deffn {数据} winreg.REG_DWORD_BIG_ENDIAN

32 位高字节序格式的数字。
@end deffn

@geindex REG_EXPAND_SZ() (在 winreg 模块中)
@anchor{library/winreg winreg REG_EXPAND_SZ}@anchor{3a82}
@deffn {数据} winreg.REG_EXPAND_SZ

包含环境变量（@code{%PATH%}）的字符串，以空字符结尾。
@end deffn

@geindex REG_LINK() (在 winreg 模块中)
@anchor{library/winreg winreg REG_LINK}@anchor{3aa4}
@deffn {数据} winreg.REG_LINK

Unicode 符号链接。
@end deffn

@geindex REG_MULTI_SZ() (在 winreg 模块中)
@anchor{library/winreg winreg REG_MULTI_SZ}@anchor{1133}
@deffn {数据} winreg.REG_MULTI_SZ

一串以空字符结尾的字符串，最后以两个空字符结尾。Python 会自动处理这种结尾形式。
@end deffn

@geindex REG_NONE() (在 winreg 模块中)
@anchor{library/winreg winreg REG_NONE}@anchor{3aa5}
@deffn {数据} winreg.REG_NONE

未定义的类型。
@end deffn

@geindex REG_QWORD() (在 winreg 模块中)
@anchor{library/winreg winreg REG_QWORD}@anchor{6b3}
@deffn {数据} winreg.REG_QWORD

64 位数字。


3.6 新版功能.

@end deffn

@geindex REG_QWORD_LITTLE_ENDIAN() (在 winreg 模块中)
@anchor{library/winreg winreg REG_QWORD_LITTLE_ENDIAN}@anchor{3aa6}
@deffn {数据} winreg.REG_QWORD_LITTLE_ENDIAN

64 位低字节序格式的数字。相当于 @ref{6b3,,REG_QWORD}。


3.6 新版功能.

@end deffn

@geindex REG_RESOURCE_LIST() (在 winreg 模块中)
@anchor{library/winreg winreg REG_RESOURCE_LIST}@anchor{3aa7}
@deffn {数据} winreg.REG_RESOURCE_LIST

设备驱动程序资源列表。
@end deffn

@geindex REG_FULL_RESOURCE_DESCRIPTOR() (在 winreg 模块中)
@anchor{library/winreg winreg REG_FULL_RESOURCE_DESCRIPTOR}@anchor{3aa8}
@deffn {数据} winreg.REG_FULL_RESOURCE_DESCRIPTOR

硬件设置。
@end deffn

@geindex REG_RESOURCE_REQUIREMENTS_LIST() (在 winreg 模块中)
@anchor{library/winreg winreg REG_RESOURCE_REQUIREMENTS_LIST}@anchor{3aa9}
@deffn {数据} winreg.REG_RESOURCE_REQUIREMENTS_LIST

硬件资源列表。
@end deffn

@geindex REG_SZ() (在 winreg 模块中)
@anchor{library/winreg winreg REG_SZ}@anchor{3a88}
@deffn {数据} winreg.REG_SZ

空字符结尾的字符串。
@end deffn

@node 注册表句柄对象,,常数<7>,winreg --- Windows 注册表访问
@anchor{library/winreg handle-object}@anchor{3a79}@anchor{library/winreg registry-handle-objects}@anchor{3aaa}
@subsubsection 注册表句柄对象


该对象封装了 Windows HKEY 对象，对象销毁时会自动关闭。为确保资源得以清理，可调用 @ref{3a7e,,Close()} 方法或 @ref{3a7d,,CloseKey()} 函数。

本模块中的所有注册表函数都会返回注册表句柄对象。

本模块中所有接受注册表句柄对象的注册表函数，也能接受一个整数，但鼓励大家使用句柄对象。

注册表句柄对象支持 @ref{d38,,__bool__()} 语义 —— 因此：

@example
if handle:
    print("Yes")
@end example

将会打印出 @code{Yes} 。

句柄对象还支持比较语义，因此若多个句柄对象都引用了同一底层 Windows 句柄值，那么比较操作结果将为 True。

句柄对象可转换为整数（如利用内置函数 @ref{205,,int()}），这时会返回底层的 Windows 句柄值。用 @ref{356c,,Detach()} 方法也可返回整数句柄，同时会断开与 Windows 句柄的连接。

@geindex Close() (winreg.PyHKEY 方法)
@anchor{library/winreg winreg PyHKEY Close}@anchor{3a7e}
@deffn {方法} PyHKEY.Close ()

关闭底层的 Windows 句柄。

如果句柄已关闭，不会引发错误。
@end deffn

@geindex Detach() (winreg.PyHKEY 方法)
@anchor{library/winreg winreg PyHKEY Detach}@anchor{356c}
@deffn {方法} PyHKEY.Detach ()

断开与 Windows 句柄的连接。

结果为一个整数，存有被断开连接之前的句柄值。如果该句柄已断开连接或关闭，则返回 0。

调用本函数后，注册表句柄将被迅速禁用，但并没有关闭。当需要底层的 Win32 句柄在句柄对象的生命周期之后仍然存在时，可以调用这个函数。

引发一个 @ref{fec,,审计事件} @code{winreg.PyHKEY.Detach}，附带参数 @code{key}。
@end deffn

@geindex __enter__() (winreg.PyHKEY 方法)
@geindex __exit__() (winreg.PyHKEY 方法)
@anchor{library/winreg winreg PyHKEY __enter__}@anchor{3aab}
@deffn {方法} PyHKEY.__enter__ ()
@anchor{library/winreg winreg PyHKEY __exit__}@anchor{3aac}
@deffnx {方法} PyHKEY.__exit__ (*exc_info)

HKEY 对象实现了 @ref{d65,,__enter__()} 和 @ref{d66,,__exit__()} 方法，因此支持 @ref{7e4,,with} 语句的上下文协议：

@example
with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
    ...  # work with key
@end example

在离开 @ref{7e4,,with} 语句块时，@emph{key} 会自动关闭。
@end deffn

@node winsound —— Windows 系统的声音播放接口,,winreg --- Windows 注册表访问,Windows系统相关模块
@anchor{library/winsound doc}@anchor{3aad}@anchor{library/winsound module-winsound}@anchor{134}@anchor{library/winsound winsound-sound-playing-interface-for-windows}@anchor{3aae}
@subsection @code{winsound} —— Windows 系统的声音播放接口


@geindex winsound (模块)


__________________________________________________________________


通过 @ref{134,,winsound} 模块可访问 Windows 平台的基础音频播放机制。包括一些函数和几个常量。

@geindex Beep() (在 winsound 模块中)
@anchor{library/winsound winsound Beep}@anchor{6b5}
@deffn {函数} winsound.Beep (frequency, duration)

让 PC 的扬声器发出提示音。@emph{frequency} 参数可指定声音的频率，单位是赫兹，必须位于 37 到 32,767 之间。@emph{duration} 参数则指定了声音应持续的毫秒数。若系统无法让扬声器发声，则会触发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex PlaySound() (在 winsound 模块中)
@anchor{library/winsound winsound PlaySound}@anchor{6b7}
@deffn {函数} winsound.PlaySound (sound, flags)

由平台 API 调用底层的 @code{PlaySound()} 函数。 参数 @emph{sound} 可以是文件名、系统音频的别名、@ref{6e9,,bytes-like object} 的音频数据或`@w{`}None`@w{`}。 如何解释取决于 @emph{flags} 的值，可为以下常数的二进制 OR 组合。 如果 @emph{sound} 参数为 @code{None}，则当前播放的波形音频会全部停止。如果系统报错， 则会触发 @ref{3e4,,RuntimeError}。
@end deffn

@geindex MessageBeep() (在 winsound 模块中)
@anchor{library/winsound winsound MessageBeep}@anchor{6b6}
@deffn {函数} winsound.MessageBeep (type=MB_OK)

由平台 API 调用底层的 @code{MessageBeep()} 函数。用于播放注册表中指定的音频。 @emph{type} 参数指定播放的音频；可能的值是 @code{-1}、@code{MB_ICONASTERISK}、@code{MB_ICONEXCLAMATION}、@code{MB_ICONHAND}、@code{MB_ICONQUESTION} 和 @code{MB_OK}，下面会介绍。值 @code{-1} 会生成一个 "简单的嘀声"；若其他的音频无法播放，这是最后的退路。如果系统报错，则会触发 @ref{3e4,,RuntimeError} 。
@end deffn

@geindex SND_FILENAME() (在 winsound 模块中)
@anchor{library/winsound winsound SND_FILENAME}@anchor{3aaf}
@deffn {数据} winsound.SND_FILENAME

参数 @emph{sound} 指明 WAV 文件名。不要与 @ref{3ab0,,SND_ALIAS} 一起使用。
@end deffn

@geindex SND_ALIAS() (在 winsound 模块中)
@anchor{library/winsound winsound SND_ALIAS}@anchor{3ab0}
@deffn {数据} winsound.SND_ALIAS

参数 @emph{sound} 是注册表内关联的音频名称。 如果注册表中无此名称，则播放系统默认的声音，除非同时设定了 @ref{3ab1,,SND_NODEFAULT} 。 如果没有注册默认声音，则会触发 @ref{3e4,,RuntimeError}。 请勿与 @ref{3aaf,,SND_FILENAME} 一起使用。

所有的 Win32 系统至少支持以下音频名称；大多数系统支持的音频都多于这些：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@ref{6b7,,PlaySound()} @emph{name}

@tab

对应的控制面板音频名

@item

@code{'SystemAsterisk'}

@tab

星号

@item

@code{'SystemExclamation'}

@tab

叹息声

@item

@code{'SystemExit'}

@tab

退出 Windows

@item

@code{'SystemHand'}

@tab

关键性停止音

@item

@code{'SystemQuestion'}

@tab

问题

@end multitable


例如:

@example
import winsound
# Play Windows exit sound.
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

# Probably play Windows default sound, if any is registered (because
# "*" probably isn't the registered name of any sound).
winsound.PlaySound("*", winsound.SND_ALIAS)
@end example
@end deffn

@geindex SND_LOOP() (在 winsound 模块中)
@anchor{library/winsound winsound SND_LOOP}@anchor{3ab2}
@deffn {数据} winsound.SND_LOOP

循环播放音频。为避免阻塞，必须同时使用 @ref{3ab3,,SND_ASYNC} 标志。不能与 @ref{3ab4,,SND_MEMORY} 一起使用。
@end deffn

@geindex SND_MEMORY() (在 winsound 模块中)
@anchor{library/winsound winsound SND_MEMORY}@anchor{3ab4}
@deffn {数据} winsound.SND_MEMORY

@ref{6b7,,PlaySound()} 的 @emph{sound} 形参是一个 WAV 文件的内存镜像，作为一个 @ref{6e9,,bytes-like object}。

@cartouche
@quotation 注解 
本模块不支持异步播放音频的内存镜像，所以该标志和 @ref{3ab3,,SND_ASYNC} 的组合将触发 @ref{3e4,,RuntimeError}。
@end quotation
@end cartouche
@end deffn

@geindex SND_PURGE() (在 winsound 模块中)
@anchor{library/winsound winsound SND_PURGE}@anchor{3ab5}
@deffn {数据} winsound.SND_PURGE

停止播放指定声音的所有实例。

@cartouche
@quotation 注解 
新版 Windows 平台不支持本标志。
@end quotation
@end cartouche
@end deffn

@geindex SND_ASYNC() (在 winsound 模块中)
@anchor{library/winsound winsound SND_ASYNC}@anchor{3ab3}
@deffn {数据} winsound.SND_ASYNC

立即返回，允许异步播放音频。
@end deffn

@geindex SND_NODEFAULT() (在 winsound 模块中)
@anchor{library/winsound winsound SND_NODEFAULT}@anchor{3ab1}
@deffn {数据} winsound.SND_NODEFAULT

即便找不到指定的音频，也不播放系统默认音频。
@end deffn

@geindex SND_NOSTOP() (在 winsound 模块中)
@anchor{library/winsound winsound SND_NOSTOP}@anchor{3ab6}
@deffn {数据} winsound.SND_NOSTOP

不打断正在播放的音频。
@end deffn

@geindex SND_NOWAIT() (在 winsound 模块中)
@anchor{library/winsound winsound SND_NOWAIT}@anchor{3ab7}
@deffn {数据} winsound.SND_NOWAIT

如果音频驱动程序忙，则立即返回。

@cartouche
@quotation 注解 
新版 Windows 平台不支持本标志。
@end quotation
@end cartouche
@end deffn

@geindex MB_ICONASTERISK() (在 winsound 模块中)
@anchor{library/winsound winsound MB_ICONASTERISK}@anchor{3ab8}
@deffn {数据} winsound.MB_ICONASTERISK

播放 @code{SystemDefault} 音频。
@end deffn

@geindex MB_ICONEXCLAMATION() (在 winsound 模块中)
@anchor{library/winsound winsound MB_ICONEXCLAMATION}@anchor{3ab9}
@deffn {数据} winsound.MB_ICONEXCLAMATION

播放 @code{SystemExclamation} 音频。
@end deffn

@geindex MB_ICONHAND() (在 winsound 模块中)
@anchor{library/winsound winsound MB_ICONHAND}@anchor{3aba}
@deffn {数据} winsound.MB_ICONHAND

播放 @code{SystemHand} 音频。
@end deffn

@geindex MB_ICONQUESTION() (在 winsound 模块中)
@anchor{library/winsound winsound MB_ICONQUESTION}@anchor{3abb}
@deffn {数据} winsound.MB_ICONQUESTION

播放 @code{SystemQuestion} 音频。
@end deffn

@geindex MB_OK() (在 winsound 模块中)
@anchor{library/winsound winsound MB_OK}@anchor{3abc}
@deffn {数据} winsound.MB_OK

播放 @code{SystemDefault} 音频。
@end deffn

@node Unix 专有服务,被取代的模块,Windows系统相关模块,Python 标准库
@anchor{library/unix doc}@anchor{3abd}@anchor{library/unix unix}@anchor{3abe}@anchor{library/unix unix-specific-services}@anchor{3abf}
@section Unix 专有服务


本章描述的模块提供了 Unix 操作系统独有特性的接口，在某些情况下也适用于它的某些或许多衍生版。 以下为模块概览：

@menu
* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* grp: grp --- 组数据库. 组数据库
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl —— 系统调用 fcntl 和 ioctl:: 
* resource: resource --- 资源使用信息. 资源使用信息
* Unix syslog 库例程:: 

@end menu

@node posix --- 最常见的 POSIX 系统调用,pwd --- 用户密码数据库,,Unix 专有服务
@anchor{library/posix doc}@anchor{3ac0}@anchor{library/posix module-posix}@anchor{d1}@anchor{library/posix posix-the-most-common-posix-system-calls}@anchor{3ac1}
@subsection @code{posix} --- 最常见的 POSIX 系统调用


@geindex posix (模块)


__________________________________________________________________


此模块提供了对基于 C 标准和 POSIX 标准（一种稍加修改的 Unix 接口）进行标准化的系统功能的访问。

@geindex 模块; os

@strong{请勿直接导入此模块。} 而应导入 @ref{c4,,os} 模块，它提供了此接口的 @emph{可移植} 版本。 在 Unix 上，@ref{c4,,os} 模块提供了 @ref{d1,,posix} 接口的一个超集。 在非 Unix 操作系统上 @ref{d1,,posix} 模块将不可用，但会通过 @ref{c4,,os} 接口提供它的一个可用子集。 一旦导入了 @ref{c4,,os}，用它替代 @ref{d1,,posix} 时就 @emph{没有} 性能惩罚。 此外，@ref{c4,,os} 还提供了一些附加功能，例如在 @code{os.environ} 中的某个条目被修改时会自动调用 @ref{1ce,,putenv()}。

错误将作为异常被报告；对于类型错误会给出普通异常，而系统调用所报告的异常则会引发 @ref{30b,,OSError}。

@menu
* 大文件支持:: 
* 重要的模块内容:: 

@end menu

@node 大文件支持,重要的模块内容,,posix --- 最常见的 POSIX 系统调用
@anchor{library/posix large-file-support}@anchor{3ac2}@anchor{library/posix posix-large-files}@anchor{3ac3}
@subsubsection 大文件支持


@geindex large files
@geindex file; large files

某些操作系统（包括 AIX, HP-UX, Irix 和 Solaris）可对 @code{int} 和 @code{long} 为 32 位值的 C 编程模型提供大于 2 GiB 的文件的支持。 这在通常情况下是以将相关数据长度和偏移类型定义为 64 位值的方式来实现的。 这样的文件有时被称为 @emph{大文件}。

Python 中的大文件支持会在 @code{off_t} 的大小超过 @code{long} 且 @code{long long} 至少与 @code{off_t} 一样大时被启用。 要启用此模式可能必须在启用特定编译旗标的情况下执行 Python 配置和编译。 例如，在最近几个版本的 Irix 中默认启用了大文件支持，但在 Solaris 2.6 和 2.7 中你还需要执行这样的操作:

@example
CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
        ./configure
@end example

在支持大文件的 Linux 系统中，可以这样做:

@example
CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
        ./configure
@end example

@node 重要的模块内容,,大文件支持,posix --- 最常见的 POSIX 系统调用
@anchor{library/posix notable-module-contents}@anchor{3ac4}@anchor{library/posix posix-contents}@anchor{3ac5}
@subsubsection 重要的模块内容


除了 @ref{c4,,os} 模块文档已说明的许多函数，@ref{d1,,posix} 还定义了下列数据项:

@geindex environ() (在 posix 模块中)
@anchor{library/posix posix environ}@anchor{3ac6}
@deffn {数据} posix.environ

一个表示解释器启动时间点的字符串环境的字典。 键和值的类型在Unix 上为 bytes 而在 Windows 上为 str。 例如，@code{environ[b'HOME']} (Windows 上的 @code{environ['HOME']}) 是你的家目录的路径名，等价于 C 中的 @code{getenv("HOME")}。

修改此字典不会影响由 @ref{2089,,execv()}, @ref{3d3,,popen()} 或 @ref{e8e,,system()} 所传入的字符串环境；如果你需要修改环境，请将 @code{environ} 传给 @ref{b24,,execve()} 或者为 @ref{e8e,,system()} 或 @ref{3d3,,popen()} 的命令字符串添加变量赋值和 export 语句。


在 3.2 版更改: 在 Unix 上，键和值为 bytes 类型。


@cartouche
@quotation 注解 
@ref{c4,,os} 模块提供了对 @code{environ} 的替代实现，它会在被修改时更新环境。 还要注意更新 @ref{c12,,os.environ} 将导致此字典失效。 推荐使用这个 @ref{c4,,os} 模块版本而不是直接访问 @ref{d1,,posix} 模块。
@end quotation
@end cartouche
@end deffn

@node pwd --- 用户密码数据库,grp --- 组数据库,posix --- 最常见的 POSIX 系统调用,Unix 专有服务
@anchor{library/pwd doc}@anchor{3ac7}@anchor{library/pwd module-pwd}@anchor{d6}@anchor{library/pwd pwd-the-password-database}@anchor{3ac8}
@subsection @code{pwd} --- 用户密码数据库


@geindex pwd (模块)


__________________________________________________________________


此模块可以访问 Unix 用户账户名及密码数据库，在所有 Unix 版本上均可使用。

密码数据库中的条目以元组对象返回，属性对应 @code{passwd} 中的结构（属性如下所示，可参考 @code{<pwd.h>}）：


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

属性

@tab

意义

@item

0

@tab

@code{pw_name}

@tab

登录名

@item

1

@tab

@code{pw_passwd}

@tab

密码，可能已经加密

@item

2

@tab

@code{pw_uid}

@tab

用户 ID 数值

@item

3

@tab

@code{pw_gid}

@tab

组 ID 数值

@item

4

@tab

@code{pw_gecos}

@tab

用户名或备注

@item

5

@tab

@code{pw_dir}

@tab

用户主目录

@item

6

@tab

@code{pw_shell}

@tab

用户的命令解释器

@end multitable


其中 uid 和 gid 是整数，其他是字符串，如果找不到对应的项目，抛出 @ref{3f1,,KeyError} 异常。

@cartouche
@quotation 注解 
@geindex 模块; crypt

传统的 Unix 系统中，@code{pw_passwd} 的值通常使用 DES 导出的算法加密（参阅 @ref{28,,crypt} 模块）。不过现在的 unix 系统使用 @emph{影子密码} 系统。在这些 unix 上，@emph{pw_passwd} 只包含星号（@code{'*'}）或字母（@code{'x'}），而加密的密码存储在文件 @code{/etc/shadow} 中，此文件不是全局可读的。在 @emph{pw_passwd} 中是否包含有用信息是系统相关的。如果可以访问到加密的密码，就需要使用 @ref{f1,,spwd} 模块了。
@end quotation
@end cartouche

本模块定义如下内容：

@geindex getpwuid() (在 pwd 模块中)
@anchor{library/pwd pwd getpwuid}@anchor{1198}
@deffn {函数} pwd.getpwuid (uid)

给定用户的数值 ID，返回密码数据库的对应项目。
@end deffn

@geindex getpwnam() (在 pwd 模块中)
@anchor{library/pwd pwd getpwnam}@anchor{11aa}
@deffn {函数} pwd.getpwnam (name)

给定用户名，返回密码数据库的对应项目。
@end deffn

@geindex getpwall() (在 pwd 模块中)
@anchor{library/pwd pwd getpwall}@anchor{3ac9}
@deffn {函数} pwd.getpwall ()

返回密码数据库中所有项目的列表，顺序不是固定的。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{8a,,grp}

针对用户组数据库的接口，与本模块类似。

@item 模块 @ref{f1,,spwd}

针对影子密码数据库的接口，与本模块类似。
@end table


@node grp --- 组数据库,termios --- POSIX 风格的 tty 控制,pwd --- 用户密码数据库,Unix 专有服务
@anchor{library/grp doc}@anchor{3aca}@anchor{library/grp grp-the-group-database}@anchor{3acb}@anchor{library/grp module-grp}@anchor{8a}
@subsection @code{grp} --- 组数据库


@geindex grp (模块)


__________________________________________________________________


该模块提供对Unix组数据库的访问。 它在所有Unix版本上都可用。

组数据库条目被报告为类似元组的对象，其属性对应于 @code{group} 结构的成员 (下面的属性字段，请参见 @code{<grp.h>}):


@multitable {xxxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

属性

@tab

意义

@item

0

@tab

gr_name

@tab

组名

@item

1

@tab

gr_passwd

@tab

（加密的）组密码； 通常为空

@item

2

@tab

gr_gid

@tab

数字组ID

@item

3

@tab

gr_mem

@tab

组内所有成员的用户名

@end multitable


gid是整数，名称和密码是字符串，成员列表是字符串列表。 （注意，大多数用户未根据密码数据库显式列为所属组的成员。请检查两个数据库以获取完整的成员资格信息。还要注意，以 @code{+} 或 @code{-} 开头的 @code{gr_name} 可能是 YP/NIS 引用，可能无法通过 @ref{11ab,,getgrnam()} 或 @ref{6e0,,getgrgid()} 访问。）

本模块定义如下内容：

@geindex getgrgid() (在 grp 模块中)
@anchor{library/grp grp getgrgid}@anchor{6e0}
@deffn {函数} grp.getgrgid (gid)

返回给定数字组ID的组数据库条目。 如果找不到要求的条目，则会引发 @ref{3f1,,KeyError} 错误。


3.6 版后已移除: 从 Python 3.6 开始，弃用对 @ref{6e0,,getgrgid()} 中的 float 或 string 等非 integer 参数的支持。

@end deffn

@geindex getgrnam() (在 grp 模块中)
@anchor{library/grp grp getgrnam}@anchor{11ab}
@deffn {函数} grp.getgrnam (name)

返回给定组名的组数据库条目。 如果找不到要求的条目，则会引发 @ref{3f1,,KeyError} 错误。
@end deffn

@geindex getgrall() (在 grp 模块中)
@anchor{library/grp grp getgrall}@anchor{3acc}
@deffn {函数} grp.getgrall ()

以任意顺序返回所有可用组条目的列表。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{d6,,pwd}

用户数据库的接口，与此类似。

@item 模块 @ref{f1,,spwd}

针对影子密码数据库的接口，与本模块类似。
@end table


@node termios --- POSIX 风格的 tty 控制,tty --- 终端控制功能,grp --- 组数据库,Unix 专有服务
@anchor{library/termios doc}@anchor{3acd}@anchor{library/termios module-termios}@anchor{104}@anchor{library/termios termios-posix-style-tty-control}@anchor{3ace}
@subsection @code{termios} --- POSIX 风格的 tty 控制


@geindex termios (模块)

@geindex POSIX; I/O control
@geindex tty; I/O control


__________________________________________________________________


此模块提供了针对tty I/O 控制的 POSIX 调用的接口。 有关此类调用的完整描述，请参阅 @code{termios(3)} Unix 指南页。 它仅在当安装时配置了支持 POSIX @emph{termios} 风格的 tty I/O 控制的 Unix 版本上可用。

此模块中的所有函数均接受一个文件描述符 @emph{fd} 作为第一个参数。 这可以是一个整数形式的文件描述符，例如 @code{sys.stdin.fileno()} 所返回的对象，或是一个 @ref{c1d,,file object}，例如 @code{sys.stdin} 本身。

这个模块还定义了与此处所提供的函数一起使用的所有必要的常量；这些常量与它们在 C 中的对应常量同名。 请参考你的系统文档了解有关如何使用这些终端控制接口的更多信息。

这个模块定义了以下函数：

@geindex tcgetattr() (在 termios 模块中)
@anchor{library/termios termios tcgetattr}@anchor{3acf}
@deffn {函数} termios.tcgetattr (fd)

对于文件描述符 @emph{fd} 返回一个包含 tty 属性的列表，形式如下: @code{[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]}，其中 @emph{cc} 为一个包含 tty 特殊字符的列表（每一项都是长度为 1 的字符串，索引号为 @code{VMIN} 和 @code{VTIME} 的项除外，这些字段如有定义则应为整数）。 对旗标和速度以及 @emph{cc} 数组中索引的解读必须使用在 @ref{104,,termios} 模块中定义的符号常量来完成。
@end deffn

@geindex tcsetattr() (在 termios 模块中)
@anchor{library/termios termios tcsetattr}@anchor{3ad0}
@deffn {函数} termios.tcsetattr (fd, when, attributes)

根据 @emph{attributes} 列表设置文件描述符 @emph{fd} 的 tty 属性，该列表即 @ref{3acf,,tcgetattr()} 所返回的对象。 @emph{when} 参数确定何时改变属性: @code{TCSANOW} 表示立即改变，@code{TCSADRAIN} 表示在传输所有队列输出后再改变，或 @code{TCSAFLUSH} 表示在传输所有队列输出并丢失所有队列输入后再改变。
@end deffn

@geindex tcsendbreak() (在 termios 模块中)
@anchor{library/termios termios tcsendbreak}@anchor{3ad1}
@deffn {函数} termios.tcsendbreak (fd, duration)

在文件描述符 @emph{fd} 上发送一个中断。 @emph{duration} 为零表示发送时长为 0.25--0.5 秒的中断；@emph{duration} 非零值的含义取决于具体系统。
@end deffn

@geindex tcdrain() (在 termios 模块中)
@anchor{library/termios termios tcdrain}@anchor{3ad2}
@deffn {函数} termios.tcdrain (fd)

进入等待状态直到写入文件描述符 @emph{fd} 的所有输出都传送完毕。
@end deffn

@geindex tcflush() (在 termios 模块中)
@anchor{library/termios termios tcflush}@anchor{3ad3}
@deffn {函数} termios.tcflush (fd, queue)

在文件描述符 @emph{fd} 上丢弃队列数据。 @emph{queue} 选择器指定哪个队列: @code{TCIFLUSH} 表示输入队列，@code{TCOFLUSH} 表示输出队列，或 @code{TCIOFLUSH} 表示两个队列同时。
@end deffn

@geindex tcflow() (在 termios 模块中)
@anchor{library/termios termios tcflow}@anchor{3ad4}
@deffn {函数} termios.tcflow (fd, action)

在文件描述符 @emph{fd} 上挂起一战恢复输入或输出。 @emph{action} 参数可以为 @code{TCOOFF} 表示挂起输出，@code{TCOON} 表示重启输出，@code{TCIOFF} 表示挂起输入，或 @code{TCION} 表示重启输入。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{11e,,tty}

针对常用终端控制操作的便捷函数。
@end table


@menu
* 示例: 示例<46>. 

@end menu

@node 示例<46>,,,termios --- POSIX 风格的 tty 控制
@anchor{library/termios example}@anchor{3ad5}@anchor{library/termios termios-example}@anchor{3ad6}
@subsubsection 示例


这个函数可提示输入密码并且关闭回显。 请注意其采取的技巧是使用一个单独的 @ref{3acf,,tcgetattr()} 调用和一个 @ref{e3f,,try} ... @ref{2c3,,finally} 语句来确保旧的 tty 属性无论在何种情况下都会被原样保存:

@example
def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd
@end example

@node tty --- 终端控制功能,pty --- 伪终端工具,termios --- POSIX 风格的 tty 控制,Unix 专有服务
@anchor{library/tty doc}@anchor{3ad7}@anchor{library/tty module-tty}@anchor{11e}@anchor{library/tty tty-terminal-control-functions}@anchor{3ad8}
@subsection @code{tty} --- 终端控制功能


@geindex tty (模块)

@strong{Source code:} Lib/tty.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/tty.py}


__________________________________________________________________


@ref{11e,,tty} 模块定义了将 tty 放入 cbreak 和 raw 模式的函数。

因为它需要 @ref{104,,termios} 模块，所以只能在 Unix 上运行。

@ref{11e,,tty} 模块定义了以下函数：

@geindex setraw() (在 tty 模块中)
@anchor{library/tty tty setraw}@anchor{3ad9}
@deffn {函数} tty.setraw (fd, when=termios.TCSAFLUSH)

将文件描述符 @emph{fd} 的模式更改为 raw 。如果 @emph{when} 被省略，则默认为 @code{termios.TCSAFLUSH} ，并传递给 @ref{3ad0,,termios.tcsetattr()} 。
@end deffn

@geindex setcbreak() (在 tty 模块中)
@anchor{library/tty tty setcbreak}@anchor{3ada}
@deffn {函数} tty.setcbreak (fd, when=termios.TCSAFLUSH)

将文件描述符 @emph{fd} 的模式更改为 cbreak 。如果 @emph{when} 被省略，则默认为 @code{termios.TCSAFLUSH} ，并传递给 @ref{3ad0,,termios.tcsetattr()} 。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{104,,termios}

低级终端控制接口。
@end table


@node pty --- 伪终端工具,fcntl —— 系统调用 fcntl 和 ioctl,tty --- 终端控制功能,Unix 专有服务
@anchor{library/pty doc}@anchor{3adb}@anchor{library/pty module-pty}@anchor{d5}@anchor{library/pty pty-pseudo-terminal-utilities}@anchor{3adc}
@subsection @code{pty} --- 伪终端工具


@geindex pty (模块)

@strong{源代码:} Lib/pty.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pty.py}


__________________________________________________________________


@ref{d5,,pty} 模块定义了一些处理“伪终端”概念的操作：启动另一个进程并能以程序方式在其控制终端中进行读写。

由于伪终端处理高度依赖于具体平台，因此此功能只有针对 Linux 的代码。 （Linux 代码也可在其他平台上工作，但是未经测试。）

@ref{d5,,pty} 模块定义了下列函数:

@geindex fork() (在 pty 模块中)
@anchor{library/pty pty fork}@anchor{3add}
@deffn {函数} pty.fork ()

分叉。 将子进程的控制终端连接到一个伪终端。 返回值为 @code{(pid, fd)}。 请注意子进程获得 @emph{pid} 0 而 @emph{fd} 为 @emph{invalid}。 父进程返回值为子进程的 @emph{pid} 而 @emph{fd} 为一个连接到子进程的控制终端（并同时连接到子进程的标准输入和输出）的文件描述符。
@end deffn

@geindex openpty() (在 pty 模块中)
@anchor{library/pty pty openpty}@anchor{3ade}
@deffn {函数} pty.openpty ()

打开一个新的伪终端对，如果可能将使用 @ref{20bc,,os.openpty()}，或是针对通用 Unix 系统的模拟代码。 返回一个文件描述符对 @code{(master, slave)}，分别表示主从两端。
@end deffn

@geindex spawn() (在 pty 模块中)
@anchor{library/pty pty spawn}@anchor{988}
@deffn {函数} pty.spawn (argv[, master_read[, stdin_read]])

生成一个进程，并将其控制终端连接到当前进程的标准 io。 这常被用来应对坚持要从控制终端读取数据的程序。 在 pty 背后生成的进程预期最后将被终止，而且当它被终止时 @emph{spawn} 将会返回。

会向 @emph{master_read} 和 @emph{stdin_read} 函数传入一个文件描述符供它们读取，并且它们总是应当返回一个字节串。 为了强制 spawn 在子进程退出之前返回所以应当抛出 @ref{30b,,OSError}。

两个函数的默认实现在每次函数被调用时将读取并返回至多 1024 个字节。 会向 @emph{master_read} 回调传入伪终端的主文件描述符以从子进程读取输出，而向 @emph{stdin_read} 传入文件描述符 0 以从父进程的标准输入读取数据。

从两个回调返回空字节串会被解读为文件结束 (EOF) 条件，在此之后回调将不再被调用。 如果 @emph{stdin_read} 发出 EOF 信号则控制终端就不能再与父进程或子进程进行通信。 除非子进程将不带任何输入就退出，否则随后 @emph{spawn} 将一直循环下去。 如果 @emph{master_read} 发出 EOF 信号则会有相同的行为结果（至少是在 Linux 上）。

如果两个回调都发出 EOF 信号则 @emph{spawn} 可能将永不返回，除非在你的平台上当传入三个空列表时 @emph{select} 会抛出一个错误。 这是一个程序缺陷，相关文档见 问题 26228@footnote{https://bugs.python.org/issue26228}。

从子进程中的 @ref{76a,,os.waitpid()} 返回退出状态值。

可以使用 @code{waitstatus_to_exitcode()} 来将退出状态转换为退出码。

引发一个 @ref{fec,,审计事件} @code{pty.spawn}，附带参数 @code{argv}。


在 3.4 版更改: @ref{988,,spawn()} 现在会从子进程的 @ref{76a,,os.waitpid()} 返回状态值。

@end deffn

@menu
* 示例: 示例<47>. 

@end menu

@node 示例<47>,,,pty --- 伪终端工具
@anchor{library/pty example}@anchor{3adf}
@subsubsection 示例


以下程序的作用类似于 Unix 命令 @code{script(1)}，它使用一个伪终端来记录一个 "typescript" 里终端进程的所有输入和输出:

@example
import argparse
import os
import pty
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='append', action='store_true')
parser.add_argument('-p', dest='use_python', action='store_true')
parser.add_argument('filename', nargs='?', default='typescript')
options = parser.parse_args()

shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
filename = options.filename
mode = 'ab' if options.append else 'wb'

with open(filename, mode) as script:
    def read(fd):
        data = os.read(fd, 1024)
        script.write(data)
        return data

    print('Script started, file is', filename)
    script.write(('Script started on %s\n' % time.asctime()).encode())

    pty.spawn(shell, read)

    script.write(('Script done on %s\n' % time.asctime()).encode())
    print('Script done, file is', filename)
@end example

@node fcntl —— 系统调用 fcntl 和 ioctl,resource --- 资源使用信息,pty --- 伪终端工具,Unix 专有服务
@anchor{library/fcntl doc}@anchor{3ae0}@anchor{library/fcntl fcntl-the-fcntl-and-ioctl-system-calls}@anchor{3ae1}@anchor{library/fcntl module-fcntl}@anchor{7c}
@subsection @code{fcntl} —— 系统调用 @code{fcntl} 和 @code{ioctl}


@geindex fcntl (模块)

@geindex UNIX; file control
@geindex UNIX; I/O control


__________________________________________________________________


本模块基于文件描述符来进行文件控制和 I/O 控制。它是 Unix 系统调用  @code{fcntl()} 和 @code{ioctl()} 的接口。关于这些调用的完整描述，请参阅 Unix 手册的 @code{fcntl(2)} 和 @code{ioctl(2)} 页面。

本模块的所有函数都接受文件描述符 @emph{fd} 作为第一个参数。可以是一个整数形式的文件描述符，比如 @code{sys.stdin.fileno()} 的返回结果，或为 @ref{313,,io.IOBase} 对象，比如 @code{sys.stdin} 提供一个 @ref{209a,,fileno()}，可返回一个真正的文件描述符。


在 3.3 版更改: 本模块的操作以前触发的是 @ref{a7c,,IOError}，现在则会触发 @ref{30b,,OSError}。



在 3.8 版更改: fcntl 模块现在有了 @code{F_ADD_SEALS} 、@code{F_GET_SEALS}  和 @code{F_SEAL_*} 常量，用于文件描述符 @ref{327,,os.memfd_create()} 的封装。



在 3.9 版更改: 在 macOS 上，fcntl 模块提供了 @code{F_GETPATH} 常量，从文件描述符获取文件的路径。 在 Linux(>=3.15) 上，fcntl 模块提供了 @code{F_OFD_GETLK}, @code{F_OFD_SETLK} 和 @code{F_OFD_SETLKW} 常量，它们将在处理打开文件描述锁时被使用。


这个模块定义了以下函数：

@geindex fcntl() (在 fcntl 模块中)
@anchor{library/fcntl fcntl fcntl}@anchor{27fa}
@deffn {函数} fcntl.fcntl (fd, cmd, arg=0)

对文件描述符 @emph{fd} 执行 @emph{cmd} 操作（能够提供 @ref{209a,,fileno()} 方法的文件对象也可以接受）。 @emph{cmd} 可用的值与操作系统有关，在 @ref{7c,,fcntl} 模块中可作为常量使用，名称与相关 C 语言头文件中的一样。参数 @emph{arg} 可以是整数或 @ref{172,,bytes} 对象。若为整数值，则本函数的返回值是 C 语言  @code{fcntl()} 调用的整数返回值。若为字节串，则其代表一个二进制结构，比如由 @ref{cde,,struct.pack()} 创建的数据。该二进制数据将被复制到一个缓冲区，缓冲区地址传给 C 调用 @code{fcntl()}。调用成功后的返回值位于缓冲区内，转换为一个 @ref{172,,bytes} 对象。返回的对象长度将与 @emph{arg} 参数的长度相同。上限为 1024 字节。如果操作系统在缓冲区中返回的信息大于 1024 字节，很可能导致内存段冲突，或更为不易察觉的数据错误。

如果 @code{fcntl()} 调用失败，会触发 @ref{30b,,OSError}。

引发一条 @ref{fec,,auditing 事件} @code{fcntl.fcntl}，参数为 @code{fd} 、@code{cmd}、@code{arg}。
@end deffn

@geindex ioctl() (在 fcntl 模块中)
@anchor{library/fcntl fcntl ioctl}@anchor{eaa}
@deffn {函数} fcntl.ioctl (fd, request, arg=0, mutate_flag=True)

本函数与 @ref{27fa,,fcntl()} 函数相同，只是参数的处理更加复杂。

@emph{request} 参数的上限是 32位。@ref{104,,termios} 模块中包含了可用作 @emph{request} 参数其他常量，名称与相关 C 头文件中定义的相同。

参数 @emph{arg} 可为整数、支持只读缓冲区接口的对象（如 @ref{172,,bytes} ）或支持读写缓冲区接口的对象（如 @ref{173,,bytearray} ）。

除了最后一种情况，其他情况下的行为都与 @ref{27fa,,fcntl()} 函数一样。

如果传入的是个可变缓冲区，那么行为就由 @emph{mutate_flag} 参数决定。

如果为 False，缓冲区的可变性将被忽略，行为与只读缓冲区一样，只是没有了上述 1024 字节的上限——只要传入的缓冲区能容纳操作系统放入的数据即可。

如果 @emph{mutate_flag} 为 True（默认值），那么缓冲区（实际上）会传给底层的 系统调用 @ref{eaa,,ioctl()} ，其返回代码则会回传给调用它的 Python，而缓冲区的新数据则反映了 @ref{eaa,,ioctl()} 的运行结果。这里做了一点简化，因为若是给出的缓冲区少于 1024 字节，首先会被复制到一个 1024 字节长的静态缓冲区再传给  @ref{eaa,,ioctl()} ，然后把结果复制回给出的缓冲区去。

如果 @code{ioctl()} 调用失败，则会触发 @ref{30b,,OSError} 异常。

举个例子：

@example
>>> import array, fcntl, struct, termios, os
>>> os.getpgrp()
13341
>>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
13341
>>> buf = array.array('h', [0])
>>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
0
>>> buf
array('h', [13341])
@end example

触发一条 @ref{fec,,auditing 事件} @code{fcntl.ioctl}，参数为 @code{fd} 、@code{request} 、@code{arg}。
@end deffn

@geindex flock() (在 fcntl 模块中)
@anchor{library/fcntl fcntl flock}@anchor{3556}
@deffn {函数} fcntl.flock (fd, operation)

在文件描述符 @emph{fd} 上执行加锁操作 @emph{operation} (也接受能提供 @ref{209a,,fileno()} 方法的文件对象)。 详见 Unix 手册  @code{flock(2)}。 (在某些系统中，此函数是用 @code{fcntl()} 模拟出来的。)

如果 @code{flock()} 调用失败，就会触发 @ref{30b,,OSError} 异常。

触发一条 @ref{fec,,审计事件} @code{fcntl.flock}，参数为 @code{fd} 、@code{operation}。
@end deffn

@geindex lockf() (在 fcntl 模块中)
@anchor{library/fcntl fcntl lockf}@anchor{e1f}
@deffn {函数} fcntl.lockf (fd, cmd, len=0, start=0, whence=0)

本质上是对 @ref{27fa,,fcntl()} 加锁调用的封装。@emph{fd} 是要加解锁的文件描述符（也接受能提供 @ref{209a,,fileno()} 方法的文件对象），@emph{cmd} 是以下值之一：


@itemize *

@item 
@code{LOCK_UN} ——解锁

@item 
@code{LOCK_SH} —— 获取一个共享锁

@item 
@code{LOCK_EX} —— 获取一个独占锁
@end itemize

如果 @emph{cmd} 为 @code{LOCK_SH} 或 @code{LOCK_EX}，则还可以与 @code{LOCK_NB} 进行按位或运算，以避免在获取锁时出现阻塞。 如果用了 @code{LOCK_NB}，无法获取锁时将触发 @ref{30b,,OSError}，此异常的 @emph{errno} 属性将被设为 @code{EACCES} 或 @code{EAGAIN} (视操作系统而定；为了保证可移植性，请检查这两个值)。 至少在某些系统上，只有当文件描述符指向需要写入而打开的文件时，才可以使用 @code{LOCK_EX}。

@emph{len} 是要锁定的字节数，@emph{start} 是自 @emph{whence} 开始锁定的字节偏移量，@emph{whence} 与 @ref{1f3f,,io.IOBase.seek()} 的定义一样。


@itemize *

@item 
@code{0} —— 自文件起始位置（@ref{e61,,os.SEEK_SET}）。

@item 
@code{1} —— 自缓冲区当前位置（ @ref{e62,,os.SEEK_CUR} ）

@item 
@code{2}—— 自文件末尾（@ref{e63,,os.SEEK_END})
@end itemize

@emph{start} 的默认值为 0，表示从文件起始位置开始。@emph{len} 的默认值是 0，表示加锁至文件末尾。 @emph{whence} 的默认值也是 0。

触发一条 @ref{fec,,审计事件} @code{fcntl.lockf}，参数为 @code{fd} 、 @code{cmd}、 @code{len}、 @code{start}、 @code{whence}。
@end deffn

示例（都是运行于符合 SVR4 的系统）：

@example
import struct, fcntl, os

f = open(...)
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)

lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)
@end example

注意，在第一个例子中，返回值变量 @emph{rv} 将存有整数；在第二个例子中，该变量中将存有一个 @ref{172,,bytes} 对象。@emph{lockdata} 变量的结构布局视系统而定——因此可能采用 @ref{3556,,flock()} 调用会更好。


@subsubheading 参见



@table @asis

@item 模块 @ref{c4,,os}

如果 @ref{c4,,os} 模块中存在加锁标志 @ref{e64,,O_SHLOCK} 和 @ref{e65,,O_EXLOCK} （仅在BSD上），那么 @ref{762,,os.open()} 函数提供了 @ref{e1f,,lockf()} 和 @ref{3556,,flock()} 函数的替代方案。
@end table


@node resource --- 资源使用信息,Unix syslog 库例程,fcntl —— 系统调用 fcntl 和 ioctl,Unix 专有服务
@anchor{library/resource doc}@anchor{3ae2}@anchor{library/resource module-resource}@anchor{e0}@anchor{library/resource resource-resource-usage-information}@anchor{3ae3}
@subsection @code{resource} --- 资源使用信息


@geindex resource (模块)


__________________________________________________________________


该模块提供了测量和控制程序所利用的系统资源的基本机制。

符号常量被用来指定特定的系统资源，并要求获得关于当前进程或其子进程的使用信息。

当系统调用失败时，会触发一个 @ref{30b,,OSError} 。

@geindex error
@anchor{library/resource resource error}@anchor{3ae4}
@deffn {例外} resource.error

一个被弃用的 @ref{30b,,OSError} 的别名。


在 3.3 版更改: 根据 
@geindex Python 提高建议; PEP 3151
PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151}，这个类是 @ref{30b,,OSError} 的别名。

@end deffn

@menu
* 资源限制: 资源限制<2>. 
* 资源用量:: 

@end menu

@node 资源限制<2>,资源用量,,resource --- 资源使用信息
@anchor{library/resource resource-limits}@anchor{3ae5}
@subsubsection 资源限制


资源的使用可以通过下面描述的 @ref{3528,,setrlimit()} 函数来限制。每个资源都被一对限制所控制：一个软限制和一个硬限制。软限制是当前的限制，并且可以由一个进程随着时间的推移而降低或提高。软限制永远不能超过硬限制。硬限制可以降低到大于软限制的任何数值，但不能提高。（只有拥有超级用户有效UID的进程才能提高硬限制。)

可以被限制的具体资源取决于系统。它们在 man @code{getrlimit(2)} 中描述。 下面列出的资源在底层操作系统支持的情况下被支持；那些不能被操作系统检查或控制的资源在本模块中没有为这些平台定义。

@geindex RLIM_INFINITY() (在 resource 模块中)
@anchor{library/resource resource RLIM_INFINITY}@anchor{3ae6}
@deffn {数据} resource.RLIM_INFINITY

用来表示无限资源的极限的常数。
@end deffn

@geindex getrlimit() (在 resource 模块中)
@anchor{library/resource resource getrlimit}@anchor{3ae7}
@deffn {函数} resource.getrlimit (resource)

返回一个包含 @emph{resource} 当前软限制和硬限制的元组。如果指定了一个无效的资源，则触发 @ref{16d,,ValueError} ，如果底层系统调用意外失败，则引发 @ref{3ae4,,error} 。
@end deffn

@geindex setrlimit() (在 resource 模块中)
@anchor{library/resource resource setrlimit}@anchor{3528}
@deffn {函数} resource.setrlimit (resource, limits)

设置 @emph{resource} 的新的消耗极限。参数 @emph{limits} 必须是一个由两个整数组成的元组 @code{(soft, hard)} ，描述了新的限制。 @ref{3ae6,,RLIM_INFINITY} 的值可以用来请求一个无限的限制。

如果指定了一个无效的资源，如果新的软限制超过了硬限制，或者如果一个进程试图提高它的硬限制，将触发 @ref{16d,,ValueError} 。当资源的硬限制或系统限制不是无限时，指定一个 @ref{3ae6,,RLIM_INFINITY} 的限制将导致 @ref{16d,,ValueError} 。 一个有效 UID 为超级用户的进程可以请求任何有效的限制值，包括无限，但如果请求的限制超过了系统规定的限制，则仍然会产生 @ref{16d,,ValueError} 。

如果底层系统调用失败， @code{setrlimit} 也可能触发 @ref{3ae4,,error} 。

VxWorks只支持设置 @ref{3ae8,,RLIMIT_NOFILE} 。

触发一个 @ref{fec,,auditing event} @code{resource.setrlimit`@w{`}使用参数  `@w{`}resource} ， @code{limits} 。
@end deffn

@geindex prlimit() (在 resource 模块中)
@anchor{library/resource resource prlimit}@anchor{98f}
@deffn {函数} resource.prlimit (pid, resource[, limits])

将 @ref{3528,,setrlimit()} 和 @ref{3ae7,,getrlimit()} 合并为一个函数，支持获取和设置任意进程的资源限制。如果 @emph{pid} 为0，那么该调用适用于当前进程。 @emph{resource} 和 @emph{limits} 的含义与 @ref{3528,,setrlimit()} 相同，只是 @emph{limits} 是可选的。

当 @emph{limits} 没有给出时，该函数返回进程 @emph{pid} 的 @emph{resource} 限制。当 @emph{limits} 被给定时，进程的 @emph{resource} 限制被设置，并返回以前的资源限制。

当 @emph{pid} 找不到时，触发 @ref{a85,,ProcessLookupError} ；当用户没有进程的权限时，触发 @ref{700,,PermissionError} 。

触发一个 @ref{fec,,auditing event} @code{resource.prlimit} 带有参数 @code{pid} ， @code{resource} ， @code{limits} 。

@ref{14c1,,Availability}: Linux 2.6.36 或更新版本带有 glibc 2.13 或更新版本


3.4 新版功能.

@end deffn

这些符号定义了资源的消耗可以通过下面描述的 @ref{3528,,setrlimit()} 和 @ref{3ae7,,getrlimit()} 函数来控制。这些符号的值正是 C 程序所使用的常数。

Unix man 页面 @code{getrlimit(2)} 列出了可用的资源。注意，并非所有系统都使用相同的符号或相同的值来表示相同的资源。本模块并不试图掩盖平台的差异——没有为某一平台定义的符号在该平台上将无法从本模块中获得。

@geindex RLIMIT_CORE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_CORE}@anchor{3529}
@deffn {数据} resource.RLIMIT_CORE

当前进程可以创建的核心文件的最大大小（以字节为单位）。如果需要更大的核心文件来包含整个进程的镜像，这可能会导致创建一个部分核心文件。
@end deffn

@geindex RLIMIT_CPU() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_CPU}@anchor{3ae9}
@deffn {数据} resource.RLIMIT_CPU

一个进程可以使用的最大处理器时间（以秒为单位）。如果超过了这个限制，一个 @code{SIGXCPU} 信号将被发送给进程。（）参见 @ref{ea,,signal} 模块文档，了解如何捕捉这个信号并做一些有用的事情，例如，将打开的文件刷新到磁盘上）。
@end deffn

@geindex RLIMIT_FSIZE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_FSIZE}@anchor{3aea}
@deffn {数据} resource.RLIMIT_FSIZE

进程可能创建的文件的最大大小。
@end deffn

@geindex RLIMIT_DATA() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_DATA}@anchor{3aeb}
@deffn {数据} resource.RLIMIT_DATA

进程的堆的最大大小（以字节为单位）。
@end deffn

@geindex RLIMIT_STACK() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_STACK}@anchor{3aec}
@deffn {数据} resource.RLIMIT_STACK

当前进程的调用堆栈的最大大小（字节）。 这只影响到多线程进程中主线程的堆栈。
@end deffn

@geindex RLIMIT_RSS() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_RSS}@anchor{3aed}
@deffn {数据} resource.RLIMIT_RSS

应该提供给进程的最大常驻内存大小。
@end deffn

@geindex RLIMIT_NPROC() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_NPROC}@anchor{3aee}
@deffn {数据} resource.RLIMIT_NPROC

当前进程可能创建的最大进程数。
@end deffn

@geindex RLIMIT_NOFILE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_NOFILE}@anchor{3ae8}
@deffn {数据} resource.RLIMIT_NOFILE

当前进程打开的文件描述符的最大数量。
@end deffn

@geindex RLIMIT_OFILE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_OFILE}@anchor{3aef}
@deffn {数据} resource.RLIMIT_OFILE

BSD 对 @ref{3ae8,,RLIMIT_NOFILE} 的命名。
@end deffn

@geindex RLIMIT_MEMLOCK() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_MEMLOCK}@anchor{3af0}
@deffn {数据} resource.RLIMIT_MEMLOCK

可能被锁定在内存中的最大地址空间。
@end deffn

@geindex RLIMIT_VMEM() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_VMEM}@anchor{3af1}
@deffn {数据} resource.RLIMIT_VMEM

进程可能占用的最大映射内存区域。
@end deffn

@geindex RLIMIT_AS() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_AS}@anchor{3af2}
@deffn {数据} resource.RLIMIT_AS

进程可能占用的地址空间的最大区域（以字节为单位）。
@end deffn

@geindex RLIMIT_MSGQUEUE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_MSGQUEUE}@anchor{990}
@deffn {数据} resource.RLIMIT_MSGQUEUE

可分配给 POSIX 消息队列的字节数。

@ref{14c1,,Availability}: Linux 2.6.8 或更新版本。


3.4 新版功能.

@end deffn

@geindex RLIMIT_NICE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_NICE}@anchor{991}
@deffn {数据} resource.RLIMIT_NICE

进程的 Nice 级别的上限（计算为 20 - rlim_cur ）。

@ref{14c1,,Availability}: Linux 2.6.12 或更新版本


3.4 新版功能.

@end deffn

@geindex RLIMIT_RTPRIO() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_RTPRIO}@anchor{992}
@deffn {数据} resource.RLIMIT_RTPRIO

实时优先级的上限。

@ref{14c1,,Availability}: Linux 2.6.12 或更新版本


3.4 新版功能.

@end deffn

@geindex RLIMIT_RTTIME() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_RTTIME}@anchor{993}
@deffn {数据} resource.RLIMIT_RTTIME

在实时调度下，一个进程在不进行阻塞性系统调用的情况下，可以花费的 CPU 时间限制（以微秒计）。

@ref{14c1,,Availability}: Linux 2.6.25 或更新版本


3.4 新版功能.

@end deffn

@geindex RLIMIT_SIGPENDING() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_SIGPENDING}@anchor{994}
@deffn {数据} resource.RLIMIT_SIGPENDING

进程可能排队的信号数量。

@ref{14c1,,Availability}: Linux 2.6.8 或更新版本。


3.4 新版功能.

@end deffn

@geindex RLIMIT_SBSIZE() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_SBSIZE}@anchor{995}
@deffn {数据} resource.RLIMIT_SBSIZE

这个用户使用的套接字缓冲区的最大大小（字节数）。这限制了这个用户在任何时候都可以持有的网络内存数量，因此也限制了 mbufs 的数量。

@ref{14c1,,Availability}: FreeBSD 9 或更新版本


3.4 新版功能.

@end deffn

@geindex RLIMIT_SWAP() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_SWAP}@anchor{996}
@deffn {数据} resource.RLIMIT_SWAP

这个用户 ID 的所有进程可能保留或使用的交换空间的最大大小（字节数）。这个限制只有在 vm.overcommit sysctl的第 1 位被置 1 时才会被强制执行。请参阅 tuning(7)@footnote{https://www.freebsd.org/cgi/man.cgi?query=tuning&sektion=7} 以获得关于这个系统检测器的完整介绍。

@ref{14c1,,Availability}: FreeBSD 9 或更新版本


3.4 新版功能.

@end deffn

@geindex RLIMIT_NPTS() (在 resource 模块中)
@anchor{library/resource resource RLIMIT_NPTS}@anchor{997}
@deffn {数据} resource.RLIMIT_NPTS

该用户 ID 创建的伪终端的最大数量。

@ref{14c1,,Availability}: FreeBSD 9 或更新版本


3.4 新版功能.

@end deffn

@node 资源用量,,资源限制<2>,resource --- 资源使用信息
@anchor{library/resource resource-usage}@anchor{3af3}
@subsubsection 资源用量


这些函数被用来检索资源使用信息。

@geindex getrusage() (在 resource 模块中)
@anchor{library/resource resource getrusage}@anchor{e66}
@deffn {函数} resource.getrusage (who)

这个函数返回一个对象，描述当前进程或其子进程所消耗的资源，由 @emph{who} 参数指定。 @emph{who} 参数应该使用下面描述的 @code{RUSAGE_*} 常数之一来指定。

一个简单的示例：

@example
from resource import *
import time

# a non CPU-bound task
time.sleep(3)
print(getrusage(RUSAGE_SELF))

# a CPU-bound task
for i in range(10 ** 8):
   _ = 1 + 1
print(getrusage(RUSAGE_SELF))
@end example

返回值的字段分别描述了某一特定系统资源的使用情况，例如，在用户模式下运行的时间或进程从主内存中换出的次数。有些值取决于内部的时钟周期，例如进程使用的内存量。

为了向后兼容，返回值也可以作为一个 16 个元素的元组来访问。

返回值中的 @code{ru_utime} 和 @code{ru_stime} 字段是浮点值，分别代表在用户模式下执行的时间和在系统模式下执行的时间。其余的值是整数。关于这些值的详细信息，请查阅 @code{getrusage(2)} man page 。这里介绍一个简短的摘要。


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

域

@tab

资源

@item

@code{0}

@tab

@code{ru_utime}

@tab

用户模式下的时间（浮点数秒）

@item

@code{1}

@tab

@code{ru_stime}

@tab

系统模式下的时间（浮点数秒）

@item

@code{2}

@tab

@code{ru_maxrss}

@tab

最大的常驻内存大小

@item

@code{3}

@tab

@code{ru_ixrss}

@tab

共享内存大小

@item

@code{4}

@tab

@code{ru_idrss}

@tab

未共享的内存大小

@item

@code{5}

@tab

@code{ru_isrss}

@tab

未共享的堆栈大小

@item

@code{6}

@tab

@code{ru_minflt}

@tab

不需要 I/O 的页面故障

@item

@code{7}

@tab

@code{ru_majflt}

@tab

需要 I/O 的页面故障数

@item

@code{8}

@tab

@code{ru_nswap}

@tab

swap out 的数量

@item

@code{9}

@tab

@code{ru_inblock}

@tab

块写入操作数

@item

@code{10}

@tab

@code{ru_oublock}

@tab

块输出操作数

@item

@code{11}

@tab

@code{ru_msgsnd}

@tab

发送消息数

@item

@code{12}

@tab

@code{ru_msgrcv}

@tab

收到消息数

@item

@code{13}

@tab

@code{ru_nsignals}

@tab

收到信号数

@item

@code{14}

@tab

@code{ru_nvcsw}

@tab

主动上下文切换

@item

@code{15}

@tab

@code{ru_nivcsw}

@tab

被动上下文切换

@end multitable


如果指定了一个无效的 @emph{who} 参数，这个函数将触发一个 @ref{16d,,ValueError} 。在特殊情况下，它也可能触发 @ref{3ae4,,error} 异常。
@end deffn

@geindex getpagesize() (在 resource 模块中)
@anchor{library/resource resource getpagesize}@anchor{3af4}
@deffn {函数} resource.getpagesize ()

返回一个系统页面的字节数。（这不需要和硬件页的大小相同）。
@end deffn

下面的 @code{RUSAGE_*} 符号被传递给 @ref{e66,,getrusage()} 函数，以指定应该为哪些进程提供信息。

@geindex RUSAGE_SELF() (在 resource 模块中)
@anchor{library/resource resource RUSAGE_SELF}@anchor{3af5}
@deffn {数据} resource.RUSAGE_SELF

传递给 @ref{e66,,getrusage()} 以请求调用进程消耗的资源，这是进程中所有线程使用的资源总和。
@end deffn

@geindex RUSAGE_CHILDREN() (在 resource 模块中)
@anchor{library/resource resource RUSAGE_CHILDREN}@anchor{3af6}
@deffn {数据} resource.RUSAGE_CHILDREN

传递给 @ref{e66,,getrusage()} 以请求被终止和等待的调用进程的子进程所消耗的资源。
@end deffn

@geindex RUSAGE_BOTH() (在 resource 模块中)
@anchor{library/resource resource RUSAGE_BOTH}@anchor{3af7}
@deffn {数据} resource.RUSAGE_BOTH

传递给 @ref{e66,,getrusage()} 以请求当前进程和子进程所消耗的资源。并非所有系统都能使用。
@end deffn

@geindex RUSAGE_THREAD() (在 resource 模块中)
@anchor{library/resource resource RUSAGE_THREAD}@anchor{3af8}
@deffn {数据} resource.RUSAGE_THREAD

传递给 @ref{e66,,getrusage()} 以请求当前线程所消耗的资源。 并非所有系统都能使用。


3.2 新版功能.

@end deffn

@node Unix syslog 库例程,,resource --- 资源使用信息,Unix 专有服务
@anchor{library/syslog doc}@anchor{3af9}@anchor{library/syslog module-syslog}@anchor{ff}@anchor{library/syslog syslog-unix-syslog-library-routines}@anchor{3afa}
@subsection Unix syslog 库例程


@geindex syslog (模块)


__________________________________________________________________


此模块提供一个接口到Unix @code{syslog} 日常库. 参考 Unix 手册页关于 @code{syslog} 设施的详细描述.

此模块包装了系统的 @code{syslog} 例程族。 一个能与 syslog 服务器对话的纯 Python 库则以 @ref{ac,,logging.handlers} 模块中 @code{SysLogHandler} 类的形式提供。

这个模块定义了以下函数：

@geindex syslog() (在 syslog 模块中)
@anchor{library/syslog syslog syslog}@anchor{355c}
@deffn {函数} syslog.syslog (message)

@deffnx {函数} syslog.syslog (priority, message)

将字符串 @emph{message} 发送到系统日志记录器。 如有必要会添加末尾换行符。 每条消息都带有一个由 @emph{facility} 和 @emph{level} 组成的优先级标价签。 可选的 @emph{priority} 参数默认值为 @code{LOG_INFO}，它确定消息的优先级。 如果未在 @emph{priority} 中使用逻辑或 (@code{LOG_INFO | LOG_USER}) 对 facility 进行编码，则会使用在 @ref{10ef,,openlog()} 调用中所给定的值。

如果 @ref{10ef,,openlog()} 未在对 @ref{ff,,syslog()} 的调用之前被调用，则将不带参数地调用 @code{openlog()}。

引发 @ref{fec,,审计事件} @code{syslog.syslog} 使用参数 @code{priority}, @code{message}.
@end deffn

@geindex openlog() (在 syslog 模块中)
@anchor{library/syslog syslog openlog}@anchor{10ef}
@deffn {函数} syslog.openlog ([ident[, logoption[, facility]]])

后续 @ref{ff,,syslog()} 调用的日志选项可以通过调用 @ref{10ef,,openlog()} 来设置。 如果日志当前未打开则 @ref{ff,,syslog()} 将不带参数地调用 @ref{10ef,,openlog()}。

可选的 @emph{ident} 关键字参数是在每条消息前添加的字符串，默认为 @code{sys.argv[0]} 去除打头的路径部分。 可选的 @emph{logoption} 关键字参数（默认为 0）是一个位字段 -- 请参见下文了解可能的组合值。 可选的 @emph{facility} 关键字参数 (默认为 @code{LOG_USER}) 为没有显式编码 facility 的消息设置默认的 facility。

引发 @ref{fec,,审计事件} @code{syslog.openlog} 使用参数 @code{ident}, @code{logoption}, @code{facility}.


在 3.2 版更改: 在之前的版本中，不允许关键字参数，并且要求必须有 @emph{ident}。 @emph{ident} 的默认值依赖于系统库，它往往为 @code{python} 而不是 Python 程序文件的实际名称。

@end deffn

@geindex closelog() (在 syslog 模块中)
@anchor{library/syslog syslog closelog}@anchor{355a}
@deffn {函数} syslog.closelog ()

重置日志模块值并且调用系统库 @code{closelog()}.

这使得此模块在初始导入时行为固定。 例如，@ref{10ef,,openlog()} 将在首次调用 @ref{ff,,syslog()} 时被调用（如果 @ref{10ef,,openlog()} 还未被调用过），并且 @emph{ident} 和其他 @ref{10ef,,openlog()} 形参会被重置为默认值。

引发一个 @ref{fec,,审计事件} @code{syslog.closelog} 不附带任何参数。
@end deffn

@geindex setlogmask() (在 syslog 模块中)
@anchor{library/syslog syslog setlogmask}@anchor{355b}
@deffn {函数} syslog.setlogmask (maskpri)

将优先级掩码设为 @emph{maskpri} 并返回之前的掩码值。 调用 @ref{ff,,syslog()} 并附带未在 @emph{maskpri} 中设置的优先级将会被忽略。 默认设置为记录所有优先级。 函数 @code{LOG_MASK(pri)} 可计算单个优先级 @emph{pri} 的掩码。 函数 @code{LOG_UPTO(pri)} 可计算包括 @emph{pri} 在内的所有优先级的掩码。

引发一个 @ref{fec,,审计事件} @code{syslog.setlogmask} 附带参数 @code{maskpri}。
@end deffn

此模块定义了一下常量:


@table @asis

@item 优先级级别 (高到低):

@code{LOG_EMERG}, @code{LOG_ALERT}, @code{LOG_CRIT}, @code{LOG_ERR},
@code{LOG_WARNING}, @code{LOG_NOTICE}, @code{LOG_INFO},
@code{LOG_DEBUG}.

@item 设施:

@code{LOG_KERN}, @code{LOG_USER}, @code{LOG_MAIL}, @code{LOG_DAEMON}, @code{LOG_AUTH}, @code{LOG_LPR}, @code{LOG_NEWS}, @code{LOG_UUCP}, @code{LOG_CRON}, @code{LOG_SYSLOG}, @code{LOG_LOCAL0} to @code{LOG_LOCAL7}，如果 @code{<syslog.h>} 中有定义则还有 @code{LOG_AUTHPRIV}。

@item 日志选项:

@code{LOG_PID}, @code{LOG_CONS}, @code{LOG_NDELAY}，如果 @code{<syslog.h>} 中有定义则还有 @code{LOG_ODELAY}, @code{LOG_NOWAIT} 以及 @code{LOG_PERROR}。
@end table

@menu
* 示例: 示例<48>. 

@end menu

@node 示例<48>,,,Unix syslog 库例程
@anchor{library/syslog examples}@anchor{3afb}
@subsubsection 示例


@menu
* 简单示例: 简单示例<2>. 

@end menu

@node 简单示例<2>,,,示例<48>
@anchor{library/syslog simple-example}@anchor{3afc}
@subsubsection 简单示例


一个简单的示例集:

@example
import syslog

syslog.syslog('Processing started')
if error:
    syslog.syslog(syslog.LOG_ERR, 'Processing started')
@end example

一个设置多种日志选项的示例，其中有在日志消息中包含进程 ID，以及将消息写入用于邮件日志记录的目标设施等:

@example
syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
syslog.syslog('E-mail processing initiated...')
@end example

@node 被取代的模块,Security Considerations,Unix 专有服务,Python 标准库
@anchor{library/superseded doc}@anchor{3afd}@anchor{library/superseded superseded}@anchor{3afe}@anchor{library/superseded superseded-modules}@anchor{3aff}
@section 被取代的模块


本章中描述的模块均已弃用，仅保留用于向后兼容。 它们已经被其他模块所取代。

@menu
* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* asynchat: asynchat --- 异步套接字指令/响应处理程序. 异步套接字指令/响应处理程序
* asyncore: asyncore --- 异步套接字处理器. 异步套接字处理器
* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* crypt —— 检查 Unix 口令的函数:: 
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* imp —— 由代码内部访问 import 。:: 
* mailcap: mailcap --- Mailcap 文件处理. Mailcap 文件处理
* msilib: msilib --- 读写 Microsoft Installer 文件. 读写 Microsoft Installer 文件
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* nntplib: nntplib --- NNTP 协议客户端. NNTP 协议客户端
* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备
* pipes: pipes --- 终端管道接口. 终端管道接口
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* spwd —— shadow 密码库:: 
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* uu: uu --- 对 uuencode 文件进行编码与解码. 对 uuencode 文件进行编码与解码
* xdrlib: xdrlib --- 编码与解码 XDR 数据. 编码与解码 XDR 数据

@end menu

@node aifc --- 读写 AIFF 和 AIFC 文件,asynchat --- 异步套接字指令/响应处理程序,,被取代的模块
@anchor{library/aifc doc}@anchor{3b00}@anchor{library/aifc aifc-read-and-write-aiff-and-aifc-files}@anchor{3b01}@anchor{library/aifc module-aifc}@anchor{4}
@subsection @code{aifc} --- 读写 AIFF 和 AIFC 文件


@geindex aifc (模块)

@strong{源代码：} Lib/aifc.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/aifc.py}

@geindex Audio Interchange File Format
@geindex AIFF
@geindex AIFF-C


3.11 版后已移除: @ref{4,,aifc} 模块已被弃用（请参阅 (see 
@geindex Python 提高建议; PEP 594#aifc
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#aifc} 了解详情）。



__________________________________________________________________


本模块提供读写 AIFF 和 AIFF-C 文件的支持。AIFF 是音频交换文件格式 (Audio Interchange File Format)，一种用于在文件中存储数字音频采样的格式。AIFF-C 是该格式的更新版本，其中包括压缩音频数据的功能。

音频文件内有许多参数，用于描述音频数据。采样率或帧率是每秒对声音采样的次数。通道数表示音频是单声道，双声道还是四声道。每个通道的每个帧包含一次采样。采样大小是以字节表示的每次采样的大小。因此，一帧由 @code{nchannels * samplesize} （通道数*采样大小）字节组成，而一秒钟的音频包含 @code{nchannels * samplesize * framerate} （通道数*采样大小*帧率）字节。

例如，CD 质量的音频采样大小为 2 字节（16位），使用 2 个声道（立体声），且帧速率为 44,100 帧/秒。这表示帧大小为 4 字节 (2*2)，一秒钟占用 2*2*44100 字节（176,400 字节）。

@ref{4,,aifc} 模块定义了以下函数：

@geindex open() (在 aifc 模块中)
@anchor{library/aifc aifc open}@anchor{565}
@deffn {函数} aifc.open (file, mode=None)

打开一个 AIFF 或 AIFF-C 文件并返回一个对象实例，该实例具有下方描述的方法。参数 @emph{file} 是文件名称字符串或 @ref{c1d,,文件对象}。当打开文件用于读取时，@emph{mode} 必须为 @code{'r'} 或 @code{'rb'}，当打开文件用于写入时，@emph{mode} 必须为 @code{'w'} 或 @code{'wb'}。如果该参数省略，则使用 @code{file.mode} 的值（如果有），否则使用 @code{'rb'}。当文件用于写入时，文件对象应该支持 seek 操作，除非提前获知写入的采样总数，并使用 @code{writeframesraw()} 和 @code{setnframes()}。@ref{565,,open()} 函数可以在 @ref{7e4,,with} 语句中使用。当 @code{with} 块执行完毕，将调用 @ref{913,,close()} 方法。


在 3.4 版更改: 支持了 @ref{7e4,,with} 语句。

@end deffn

当打开文件用于读取时，由 @ref{565,,open()} 返回的对象具有以下几种方法：

@geindex getnchannels() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getnchannels}@anchor{3b02}
@deffn {方法} aifc.getnchannels ()

返回音频的通道数（单声道为 1，立体声为 2）。
@end deffn

@geindex getsampwidth() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getsampwidth}@anchor{3b03}
@deffn {方法} aifc.getsampwidth ()

返回以字节表示的单个采样的大小。
@end deffn

@geindex getframerate() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getframerate}@anchor{3b04}
@deffn {方法} aifc.getframerate ()

返回采样率（每秒的音频帧数）。
@end deffn

@geindex getnframes() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getnframes}@anchor{3b05}
@deffn {方法} aifc.getnframes ()

返回文件中的音频帧总数。
@end deffn

@geindex getcomptype() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getcomptype}@anchor{3b06}
@deffn {方法} aifc.getcomptype ()

返回一个长度为 4 的字节数组，描述了音频文件中使用的压缩类型。对于 AIFF 文件，返回值为 @code{b'NONE'}。
@end deffn

@geindex getcompname() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getcompname}@anchor{3b07}
@deffn {方法} aifc.getcompname ()

返回一个字节数组，可转换为人类可读的描述，描述的是音频文件中使用的压缩类型。对于 AIFF 文件，返回值为 @code{b'not compressed'}。
@end deffn

@geindex getparams() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getparams}@anchor{912}
@deffn {方法} aifc.getparams ()

返回一个 @ref{1a1,,namedtuple()} @code{(nchannels, sampwidth, framerate, nframes, comptype, compname)}，与 @code{get*()} 方法的输出相同。
@end deffn

@geindex getmarkers() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getmarkers}@anchor{3b08}
@deffn {方法} aifc.getmarkers ()

返回一个列表，包含音频文件中的所有标记。标记由一个 3 元素的元组组成。第一个元素是标记 ID（整数），第二个是标记位置，从数据开头算起的帧数（整数），第三个是标记的名称（字符串）。
@end deffn

@geindex getmark() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc getmark}@anchor{3b09}
@deffn {方法} aifc.getmark (id)

根据传入的标记 @emph{id} 返回元组，元组与 @ref{3b08,,getmarkers()} 中描述的一致。
@end deffn

@geindex readframes() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc readframes}@anchor{3b0a}
@deffn {方法} aifc.readframes (nframes)

从音频文件读取并返回后续 @emph{nframes} 个帧。返回的数据是一个字符串，包含每个帧所有通道的未压缩采样值。
@end deffn

@geindex rewind() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc rewind}@anchor{3b0b}
@deffn {方法} aifc.rewind ()

倒回读取指针。下一次 @ref{3b0a,,readframes()} 将从头开始。
@end deffn

@geindex setpos() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setpos}@anchor{3b0c}
@deffn {方法} aifc.setpos (pos)

移动读取指针到指定的帧上。
@end deffn

@geindex tell() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc tell}@anchor{3b0d}
@deffn {方法} aifc.tell ()

返回当前的帧号。
@end deffn

@geindex close() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc close}@anchor{913}
@deffn {方法} aifc.close ()

关闭 AIFF 文件。调用此方法后，对象将无法再使用。
@end deffn

打开文件用于写入时，@ref{565,,open()} 返回的对象具有上述所有方法，但 @code{readframes()} 和 @code{setpos()} 除外，并额外具备了以下方法。只有调用了 @code{set*()} 方法之后，才能调用相应的 @code{get*()} 方法。在首次调用 @code{writeframes()} 或 @code{writeframesraw()} 之前，必须填写除帧数以外的所有参数。

@geindex aiff() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc aiff}@anchor{3b0e}
@deffn {方法} aifc.aiff ()

创建一个 AIFF 文件，默认创建 AIFF-C 文件，除非文件名以 @code{'.aiff'} 为后缀，在此情况下默认创建 AIFF 文件。
@end deffn

@geindex aifc() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc aifc}@anchor{3b0f}
@deffn {方法} aifc.aifc ()

创建一个 AIFF-C 文件。 默认创建 AIFF-C 文件，除非文件名以 @code{'.aiff'} 为后缀，在此情况下默认创建 AIFF 文件。
@end deffn

@geindex setnchannels() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setnchannels}@anchor{3b10}
@deffn {方法} aifc.setnchannels (nchannels)

指明音频文件中的通道数。
@end deffn

@geindex setsampwidth() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setsampwidth}@anchor{3b11}
@deffn {方法} aifc.setsampwidth (width)

指明以字节为单位的音频采样大小。
@end deffn

@geindex setframerate() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setframerate}@anchor{3b12}
@deffn {方法} aifc.setframerate (rate)

指明以每秒帧数表示的采样频率。
@end deffn

@geindex setnframes() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setnframes}@anchor{3b13}
@deffn {方法} aifc.setnframes (nframes)

指明要写入到音频文件的帧数。 如果未设定此形参或者未正确设定，则文件需要支持位置查找。
@end deffn

@geindex setcomptype() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setcomptype}@anchor{3b14}
@deffn {方法} aifc.setcomptype (type, name)

@geindex u-LAW
@geindex A-LAW
@geindex G.722

指明压缩类型。 如果未指明，则音频数据将不会被压缩。 在 AIFF 文件中，压缩是无法实现的。 name 形参应当为以字节数组表示的人类可读的压缩类型描述，type 形参应当为长度为 4 的字节数组。 目前支持的压缩类型如下: @code{b'NONE'}, @code{b'ULAW'}, @code{b'ALAW'}, @code{b'G722'}。
@end deffn

@geindex setparams() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setparams}@anchor{3b15}
@deffn {方法} aifc.setparams (nchannels, sampwidth, framerate, comptype, compname)

一次性设置上述所有参数。 该参数是由多个形参组成的元组。 这意味着可以使用 @ref{912,,getparams()} 调用的结果作为 @ref{3b15,,setparams()} 的参数。
@end deffn

@geindex setmark() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc setmark}@anchor{3b16}
@deffn {方法} aifc.setmark (id, pos, name)

添加具有给定 id (大于 0)，以及在给定位置上给定名称的标记。 此方法可在 @ref{913,,close()} 之前的任何时候被调用。
@end deffn


@deffn {方法} aifc.tell ()

返回输出文件中的当前写入位置。 适用于与 @ref{3b16,,setmark()} 进行协同配合。
@end deffn

@geindex writeframes() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc writeframes}@anchor{915}
@deffn {方法} aifc.writeframes (data)

将数据写入到输出文件。 此方法只能在设置了音频文件形参之后被调用。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn

@geindex writeframesraw() (aifc.aifc 方法)
@anchor{library/aifc aifc aifc writeframesraw}@anchor{914}
@deffn {方法} aifc.writeframesraw (data)

类似于 @ref{915,,writeframes()}，不同之处在于音频文件的标头不会被更新。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn


@deffn {方法} aifc.close ()

关闭 AIFF 文件。 文件的标头会被更新以反映音频数据的实际大小。 在调用此方法之后，对象将无法再被使用。
@end deffn

@node asynchat --- 异步套接字指令/响应处理程序,asyncore --- 异步套接字处理器,aifc --- 读写 AIFF 和 AIFC 文件,被取代的模块
@anchor{library/asynchat doc}@anchor{3b17}@anchor{library/asynchat asynchat-asynchronous-socket-command-response-handler}@anchor{3b18}@anchor{library/asynchat module-asynchat}@anchor{8}
@subsection @code{asynchat} --- 异步套接字指令/响应处理程序


@geindex asynchat (模块)

@strong{源代码:} Lib/asynchat.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asynchat.py}


3.6 版后已移除: @ref{8,,asynchat} 将在 Python 3.12 版被移除（请参阅 
@geindex Python 提高建议; PEP 594#asynchat
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#asynchat} 了解详情）。 请改用 @ref{9,,asyncio}。



__________________________________________________________________


@cartouche
@quotation 注解 
该模块仅为提供向后兼容。我们推荐在新代码中使用 @ref{9,,asyncio} 。
@end quotation
@end cartouche

此模块在 @ref{a,,asyncore} 框架之上构建，简化了异步客户端和服务器并使得处理元素为以任意字符串结束或者为可变长度的协议更加容易。 @ref{8,,asynchat} 定义了一个可以由你来子类化的抽象类 @ref{9a5,,async_chat}，提供了 @code{collect_incoming_data()} 和 @code{found_terminator()} 等方法的实现。 它使用与 @ref{a,,asyncore} 相同的异步循环，并且可以在通道映射中自由地混合 @ref{c99,,asyncore.dispatcher} 和 @ref{9a5,,asynchat.async_chat} 这两种类型的通道。 一般来说 @ref{c99,,asyncore.dispatcher} 服务器通道在接收到传入的连接请求时会生成新的 @ref{9a5,,asynchat.async_chat} 通道对象。

@geindex async_chat (asynchat 中的类)
@anchor{library/asynchat asynchat async_chat}@anchor{9a5}
@deffn {类} asynchat.async_chat

这个类是 @ref{c99,,asyncore.dispatcher} 的抽象子类。 对于实际使用的代码你必须子类化 @ref{9a5,,async_chat}，提供有意义的 @ref{3b19,,collect_incoming_data()} 和 @ref{3b1a,,found_terminator()} 方法。 @ref{c99,,asyncore.dispatcher} 的方法也可以被使用，但它们在消息/响应上下文中并不是全都有意义。

与 @ref{c99,,asyncore.dispatcher} 类似，@ref{9a5,,async_chat} 也定义了一组通过对 @code{select()} 调用之后的套接字条件进行分析所生成的事件。 一旦启动轮询循环 @ref{9a5,,async_chat} 对象的方法就会被事件处理框架调用而无须程序员方面做任何操作。

两个可被修改的类属性，用以提升性能，甚至也可能会节省内存。

@geindex async_chat.ac_in_buffer_size() (在 asynchat 模块中)
@anchor{library/asynchat asynchat async_chat ac_in_buffer_size}@anchor{3b1b}
@deffn {数据} ac_in_buffer_size

异步输入缓冲区大小 (默认为 @code{4096})。
@end deffn

@geindex async_chat.ac_out_buffer_size() (在 asynchat 模块中)
@anchor{library/asynchat asynchat async_chat ac_out_buffer_size}@anchor{3b1c}
@deffn {数据} ac_out_buffer_size

异步输出缓冲区大小 (默认为 @code{4096})。
@end deffn

与 @ref{c99,,asyncore.dispatcher} 不同，@ref{9a5,,async_chat} 允许你定义一个 @abbr{FIFO} 队列 @emph{producers}。 其中的生产者只需要一个方法 @code{more()}，该方法应当返回要在通道上传输的数据。 生产者通过让其 @code{more()} 方法返回空字节串对象来表明其处于耗尽状态 (@emph{意即} 它已不再包含数据)。 此时 @ref{9a5,,async_chat} 对象会将该生产者从队列中移除并开始使用下一个生产者，如果有下一个的话。 当生产者队列为空时 @code{handle_write()} 方法将不执行任何操作。 你要使用通道对象的 @ref{3b1d,,set_terminator()} 方法来描述如何识别来自远程端点的入站传输的结束或是重要的中断点。

要构建一个可用的 @ref{9a5,,async_chat} 子类，你的输入方法 @ref{3b19,,collect_incoming_data()} 和 @ref{3b1a,,found_terminator()} 必须要处理通道异步接收的数据。 这些参数的描述见下文。
@end deffn

@geindex close_when_done() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat close_when_done}@anchor{3b1e}
@deffn {方法} async_chat.close_when_done ()

将 @code{None} 推入生产者队列。 当此生产者被弹出队列时它将导致通道被关闭。
@end deffn

@geindex collect_incoming_data() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat collect_incoming_data}@anchor{3b19}
@deffn {方法} async_chat.collect_incoming_data (data)

调用时附带 @emph{data}，其中包含任意数量的已接收数据。 必须被重载的默认方法将引发一个 @ref{70e,,NotImplementedError} 异常。
@end deffn

@geindex discard_buffers() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat discard_buffers}@anchor{3b1f}
@deffn {方法} async_chat.discard_buffers ()

在紧急情况下此方法将丢弃输入和/或输出缓冲区以及生产者队列中的任何数据。
@end deffn

@geindex found_terminator() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat found_terminator}@anchor{3b1a}
@deffn {方法} async_chat.found_terminator ()

当输入数据流能匹配 @ref{3b1d,,set_terminator()} 所设定的终结条件时会被调用。 必须被重载的默认方法将引发一个 @ref{70e,,NotImplementedError} 异常。 被缓冲的输入数据应当可以通过实例属性来获取。
@end deffn

@geindex get_terminator() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat get_terminator}@anchor{3b20}
@deffn {方法} async_chat.get_terminator ()

返回通道的当前终结器。
@end deffn

@geindex push() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat push}@anchor{3b21}
@deffn {方法} async_chat.push (data)

将数据推入通道的队列以确保其被传输。 要让通道将数据写到网络中你只需要这样做就足够了，虽然以更复杂的方式使用你自己的生产者也是有可能的，例如为了实现加密和分块。
@end deffn

@geindex push_with_producer() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat push_with_producer}@anchor{3b22}
@deffn {方法} async_chat.push_with_producer (producer)

获取一个生产者对象并将其加入到与通道相关联的生产者队列中。 当所有当前已推入的生产者都已被耗尽时通道将通过调用其 @code{more()} 方法来耗用此生产者的数据并将数据发送至远程端点。
@end deffn

@geindex set_terminator() (asynchat.async_chat 方法)
@anchor{library/asynchat asynchat async_chat set_terminator}@anchor{3b1d}
@deffn {方法} async_chat.set_terminator (term)

设置可在通道上被识别的终结条件。 @code{term} 可以是三种类型值中的任意一种 ，对应于处理入站协议数据的三种不同方式。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

term

@tab

描述

@item

@emph{string}

@tab

当在输入流中发现该字符串时将会调用 @ref{3b1a,,found_terminator()}

@item

@emph{integer}

@tab

当接收到指定数量的字符时将会调用 @ref{3b1a,,found_terminator()}

@item

@code{None}

@tab

通道会不断地持续收集数据

@end multitable


请注意终结器之后的任何数据将可在 @ref{3b1a,,found_terminator()} 被调用后由通道来读取。
@end deffn

@menu
* asynchat 示例:: 

@end menu

@node asynchat 示例,,,asynchat --- 异步套接字指令/响应处理程序
@anchor{library/asynchat asynchat-example}@anchor{3b23}@anchor{library/asynchat id1}@anchor{3b24}
@subsubsection asynchat 示例


下面的例子片段显示了如何通过 @ref{9a5,,async_chat} 来读取 HTTP 请求。 Web 服务器可以为每个入站的客户端连接创建 @code{http_request_handler} 对象。 请注意在初始时通道终结器会被设置为匹配 HTTP 标头末尾的空行，并且会用一个旗标来指明标头正在被读取。

一旦完成了标头的读取，如果请求类型为 POST (表明输入流中存在更多的数据) 则会使用 @code{Content-Length:} 标头来设置一个数值终结器以从通道读取适当数量的数据。

一旦完成了对所有相关输入的处理，将会在设置通道终结器为 @code{None} 以确保忽略掉 Web 客户端所发送的任何无关数据之后调用 @code{handle_request()} 方法。

@example
import asynchat

class http_request_handler(asynchat.async_chat):

    def __init__(self, sock, addr, sessions, log):
        asynchat.async_chat.__init__(self, sock=sock)
        self.addr = addr
        self.sessions = sessions
        self.ibuffer = []
        self.obuffer = b""
        self.set_terminator(b"\r\n\r\n")
        self.reading_headers = True
        self.handling = False
        self.cgi_data = None
        self.log = log

    def collect_incoming_data(self, data):
        """Buffer the data"""
        self.ibuffer.append(data)

    def found_terminator(self):
        if self.reading_headers:
            self.reading_headers = False
            self.parse_headers(b"".join(self.ibuffer))
            self.ibuffer = []
            if self.op.upper() == b"POST":
                clen = self.headers.getheader("content-length")
                self.set_terminator(int(clen))
            else:
                self.handling = True
                self.set_terminator(None)
                self.handle_request()
        elif not self.handling:
            self.set_terminator(None)  # browsers sometimes over-send
            self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
            self.handling = True
            self.ibuffer = []
            self.handle_request()
@end example

@node asyncore --- 异步套接字处理器,audioop --- 处理原始音频数据,asynchat --- 异步套接字指令/响应处理程序,被取代的模块
@anchor{library/asyncore doc}@anchor{3b25}@anchor{library/asyncore asyncore-asynchronous-socket-handler}@anchor{3b26}@anchor{library/asyncore module-asyncore}@anchor{a}
@subsection @code{asyncore} --- 异步套接字处理器


@geindex asyncore (模块)

@c heavily adapted from original documentation by Sam Rushing

@strong{源码：} Lib/asyncore.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/asyncore.py}


3.6 版后已移除: @ref{a,,asyncore} 将在 Python 3.12 版被移除（请参阅 
@geindex Python 提高建议; PEP 594#asyncore
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#asyncore} 了解详情）。 请改用 @ref{9,,asyncio}。



__________________________________________________________________


@cartouche
@quotation 注解 
该模块仅为提供向后兼容。我们推荐在新代码中使用 @ref{9,,asyncio} 。
@end quotation
@end cartouche

该模块提供用于编写异步套接字服务客户端与服务端的基础构件。

只有两种方法让单个处理器上的程序“同一时间完成不止一件事”。 多线程编程是最简单和最流行的方法，但是还有另一种非常不同的技术，它可以让你拥有多线程的几乎所有优点，而无需实际使用多线程。 它仅仅在你的程序主要受 I/O 限制时有用，那么。 如果你的程序受处理器限制，那么先发制人的预定线程可能就是你真正需要的。 但是，网络服务器很少受处理器限制。

如果你的操作系统在其 I/O 库中支持 @code{select()} 系统调用（几乎所有操作系统），那么你可以使用它来同时处理多个通信通道；在 I/O 正在“后台”时进行其他工作。 虽然这种策略看起来很奇怪和复杂，特别是起初，它在很多方面比多线程编程更容易理解和控制。 @ref{a,,asyncore} 模块为您解决了许多难题，使得构建复杂的高性能网络服务器和客户端的任务变得轻而易举。 对于“会话”应用程序和协议，伴侣 @ref{8,,asynchat} 模块是非常宝贵的。

这两个模块背后的基本思想是创建一个或多个网络 @emph{通道} ，类的实例 @ref{c99,,asyncore.dispatcher} 和 @ref{9a5,,asynchat.async_chat} 。 创建通道会将它们添加到全局映射中，如果你不为它提供自己的 @emph{映射} ，则由 @ref{3b27,,loop()} 函数使用。

一旦创建了初始通道，调用 @ref{3b27,,loop()} 函数将激活通道服务，该服务将一直持续到最后一个通道（包括在异步服务期间已添加到映射中的任何通道）关闭。

@geindex loop() (在 asyncore 模块中)
@anchor{library/asyncore asyncore loop}@anchor{3b27}
@deffn {函数} asyncore.loop ([timeout[, use_poll[, map[, count]]]])

进入一个轮询循环，其在循环计数超出或所有打开的通道关闭后终止。 所有参数都是可选的。 @emph{count} 形参默认为 @code{None} ，导致循环仅在所有通道关闭时终止。 @emph{timeout} 形参为适当的 @ref{770,,select()} 或 @ref{2866,,poll()} 调用设置超时参数，以秒为单位; 默认值为30秒。 @emph{use_poll} 形参，如果为 True ，则表示 @ref{2866,,poll()} 应优先使用 @ref{770,,select()} (默认为`@w{`}False`@w{`})。

@emph{map} 形参是一个条目为所监视通道的字典。 当通道关闭时它们会被从映射中删除。 如果省略 @emph{map}，则会使用一个全局映射。 通道 (@ref{c99,,asyncore.dispatcher}, @ref{9a5,,asynchat.async_chat} 及其子类的实例) 可以在映射中任意混合。
@end deffn

@geindex dispatcher (asyncore 中的类)
@anchor{library/asyncore asyncore dispatcher}@anchor{c99}
@deffn {类} asyncore.dispatcher

@ref{c99,,dispatcher} 类是对低层级套接字对象的轻量包装器。 要让它更有用处，可以从异步循环调用一些事件处理方法。 在其他方面，它可以被当作是普通的非阻塞型套接字对象。

在特定时间或特定连接状态下触发的低层级事件可通知异步循环发生了特定的高层级事件。 例如，如果我们请求了一个套接字以连接到另一台主机，我们会在套接字首次变得可写时得知连接已建立（在此刻你将知道可以向其写入并预期能够成功）。 包含的高层级事件有:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

事件

@tab

描述

@item

@code{handle_connect()}

@tab

由首个读取或写入事件引起

@item

@code{handle_close()}

@tab

由不带可用数据的读取事件引起

@item

@code{handle_accepted()}

@tab

由在监听套接字上的读取事件引起

@end multitable


在异步处理过程中，每个已映射通道的 @ref{3b28,,readable()} 和 @ref{3b29,,writable()} 方法会被用来确定是否要将通道的套接字添加到已执行 @code{select()} 或 @code{poll()} 用于读取和写入事件的通道列表中。

因此，通道事件的集合要大于基本套接字事件。 可以在你的子类中被重载的全部方法集合如下:

@geindex handle_read() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_read}@anchor{3b2a}
@deffn {方法} handle_read ()

当异步循环检测到通道的套接字上的 @code{read()} 调用将要成功时会被调用。
@end deffn

@geindex handle_write() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_write}@anchor{3b2b}
@deffn {方法} handle_write ()

当异步循环检测到一个可写套接字可以被写入时会被调用。 通常此方法将实现必要的缓冲机制以保证运行效率。 例如:

@example
def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]
@end example
@end deffn

@geindex handle_expt() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_expt}@anchor{3b2c}
@deffn {方法} handle_expt ()

当一个套接字连接存在带外（OOB）数据时会被调用。 这几乎从来不会发生，因为 OOB 虽然受支持但很少被使用。
@end deffn

@geindex handle_connect() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_connect}@anchor{3b2d}
@deffn {方法} handle_connect ()

当活动打开方的套接字实际建立连接时会被调用。 可能会发送一条“欢迎”消息，或者向远程端点发起协议协商等。
@end deffn

@geindex handle_close() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_close}@anchor{3b2e}
@deffn {方法} handle_close ()

当套接字关闭时会被调用。
@end deffn

@geindex handle_error() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_error}@anchor{3b2f}
@deffn {方法} handle_error ()

当一个异常被引发并且未获得其他处理时会被调用。 默认版本将打印精简的回溯信息。
@end deffn

@geindex handle_accept() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_accept}@anchor{c9b}
@deffn {方法} handle_accept ()

当可以与发起对本地端点的 @ref{3b30,,connect()} 调用的新远程端点建立连接时会在侦听通道（被动打开方）上被调用。 在 3.2 版中已被弃用；请改用 @ref{c9a,,handle_accepted()}。


3.2 版后已移除.

@end deffn

@geindex handle_accepted() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher handle_accepted}@anchor{c9a}
@deffn {方法} handle_accepted (sock, addr)

当与发起对本地端点的 @ref{3b30,,connect()} 调用的新远程端点已建立连接时会在侦听通道（被动打开方）上被调用。 @emph{sock} 是可被用于在连接上发送和接收数据的 @emph{新建} 套接字对象，而 @emph{addr} 是绑定到连接另一端的套接字的地址。


3.2 新版功能.

@end deffn

@geindex readable() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher readable}@anchor{3b28}
@deffn {方法} readable ()

每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到可能在其上发生读取事件的列表中。 默认方法会简单地返回 @code{True}，表示在默认情况下，所有通道都希望能读取事件。
@end deffn

@geindex writable() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher writable}@anchor{3b29}
@deffn {方法} writable ()

每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到可能在其上发生写入事件的列表中。 默认方法会简单地返回 @code{True}，表示在默认情况下，所有通道都希望能写入事件。
@end deffn

此外，每个通道都委托或扩展了许多套接字方法。 它们大部分都与其套接字的对应方法几乎一样。

@geindex create_socket() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher create_socket}@anchor{3b31}
@deffn {方法} create_socket (family=socket.AF_INET, type=socket.SOCK_STREAM)

这与普通套接字的创建相同，并会使用同样的创建选项。 请参阅 @ref{ef,,socket} 文档了解有关创建套接字的信息。


在 3.3 版更改: @emph{family} 和 @emph{type} 参数可以被省略。

@end deffn

@geindex connect() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher connect}@anchor{3b30}
@deffn {方法} connect (address)

与普通套接字对象一样，@emph{address} 是一个元组，它的第一个元素是要连接的主机，第二个元素是端口号。
@end deffn

@geindex send() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher send}@anchor{3b32}
@deffn {方法} send (data)

将 @emph{data} 发送到套接字的远程端点。
@end deffn

@geindex recv() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher recv}@anchor{3b33}
@deffn {方法} recv (buffer_size)

从套接字的远程端点读取至多 @emph{buffer_size} 个字节。 读到空字节串表明通道已从另一端被关闭。

请注意 @ref{3b33,,recv()} 可能会引发 @ref{a81,,BlockingIOError}，即使 @ref{770,,select.select()} 或 @ref{2866,,select.poll()} 报告套接字已准备好被读取。
@end deffn

@geindex listen() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher listen}@anchor{3b34}
@deffn {方法} listen (backlog)

侦听与套接字的连接。 @emph{backlog} 参数指明排入连接队列的最大数量且至少应为 1；最大值取决于具体系统（通常为 5）。
@end deffn

@geindex bind() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher bind}@anchor{3b35}
@deffn {方法} bind (address)

将套接字绑定到 @emph{address}。 套接字必须尚未被绑定。  (@emph{address} 的格式取决于具体的地址族 --- 请参阅 @ref{ef,,socket} 文档了解更多信息。) 要将套接字标记为可重用的 (设置 @code{SO_REUSEADDR} 选项)，请调用 @ref{c99,,dispatcher} 对象的 @code{set_reuse_addr()} 方法。
@end deffn

@geindex accept() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher accept}@anchor{c9c}
@deffn {方法} accept ()

接受一个连接。 此套接字必须绑定到一个地址上并且侦听连接。 返回值可以是 @code{None} 或一个 @code{(conn, address)} 对，其中 @emph{conn} 是一个可用来在此连接上发送和接收数据的  @emph{新的} 套接字对象，而 @emph{address} 是绑定到连接另一端套接字的地址。 当返回 @code{None} 时意味着连接没有建立，在此情况下服务器应当忽略此事件并继续侦听后续的入站连接。
@end deffn

@geindex close() (asyncore.dispatcher 方法)
@anchor{library/asyncore asyncore dispatcher close}@anchor{3b36}
@deffn {方法} close ()

关闭套接字。 在此套接字对象上的后续操作都将失败。 远程端点将不再接收任何数据（在排入队列的数据被清空之后）。 当套接字被垃圾回收时会自动关闭。
@end deffn
@end deffn

@geindex dispatcher_with_send (asyncore 中的类)
@anchor{library/asyncore asyncore dispatcher_with_send}@anchor{3b37}
@deffn {类} asyncore.dispatcher_with_send

@ref{c99,,dispatcher} 的一个添加了简单缓冲输出功能的子类，适用于简单客户端。 对于更复杂的用法请使用 @ref{9a5,,asynchat.async_chat}。
@end deffn

@geindex file_dispatcher (asyncore 中的类)
@anchor{library/asyncore asyncore file_dispatcher}@anchor{3b38}
@deffn {类} asyncore.file_dispatcher

file_dispatcher 接受一个文件描述符或 @ref{c1d,,file object} 以及一个可选的 map 参数，并对其进行包装以配合 @code{poll()} 或 @code{loop()} 函数使用。 如果提供一个文件对象或任何具有 @code{fileno()} 方法的对象，其方法将被调用并传递给 @ref{3b39,,file_wrapper} 构造器。

@ref{14c1,,Availability}: Unix.
@end deffn

@geindex file_wrapper (asyncore 中的类)
@anchor{library/asyncore asyncore file_wrapper}@anchor{3b39}
@deffn {类} asyncore.file_wrapper

file_wrapper 接受一个整数形式的文件描述符并调用 @ref{1132,,os.dup()} 来复制其句柄，以便原始句柄可以独立于 file_wrapper 被关闭。 这个类实现了足够的方法来模拟套接字以供 @ref{3b38,,file_dispatcher} 类使用。

@ref{14c1,,Availability}: Unix.
@end deffn

@menu
* asyncore 示例基本 HTTP 客户端:: 
* asyncore 示例基本回显服务器:: 

@end menu

@node asyncore 示例基本 HTTP 客户端,asyncore 示例基本回显服务器,,asyncore --- 异步套接字处理器
@anchor{library/asyncore asyncore-example-1}@anchor{3b3a}@anchor{library/asyncore asyncore-example-basic-http-client}@anchor{3b3b}
@subsubsection asyncore 示例基本 HTTP 客户端


下面是一个非常基本的 HTTP 客户端，它使用了 @ref{c99,,dispatcher} 类来实现套接字处理:

@example
import asyncore

class HTTPClient(asyncore.dispatcher):

    def __init__(self, host, path):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.connect( (host, 80) )
        self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
                            (path, host), 'ascii')

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print(self.recv(8192))

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]


client = HTTPClient('www.python.org', '/')
asyncore.loop()
@end example

@node asyncore 示例基本回显服务器,,asyncore 示例基本 HTTP 客户端,asyncore --- 异步套接字处理器
@anchor{library/asyncore asyncore-example-2}@anchor{3b3c}@anchor{library/asyncore asyncore-example-basic-echo-server}@anchor{3b3d}
@subsubsection asyncore 示例基本回显服务器


下面是一个基本的回显服务器，它使用了 @ref{c99,,dispatcher} 类来接受连接并将入站连接发送给处理程序:

@example
import asyncore

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accepted(self, sock, addr):
        print('Incoming connection from %s' % repr(addr))
        handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()
@end example

@node audioop --- 处理原始音频数据,cgi --- 通用网关接口支持,asyncore --- 异步套接字处理器,被取代的模块
@anchor{library/audioop doc}@anchor{3b3e}@anchor{library/audioop audioop-manipulate-raw-audio-data}@anchor{3b3f}@anchor{library/audioop module-audioop}@anchor{c}
@subsection @code{audioop} --- 处理原始音频数据


@geindex audioop (模块)


3.11 版后已移除: @ref{c,,audioop} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#audioop
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#audioop} 了解详情）。



__________________________________________________________________


@ref{c,,audioop} 模块包含针对声音片段的一些有用操作。它操作的声音片段由 8、16、24 或 32 位宽的有符号整型采样值组成，存储在 @ref{6e9,,类字节串对象} 中。除非特别说明，否则所有标量项目均为整数。


在 3.4 版更改: 增加了对 24 位采样的支持。现在，所有函数都接受任何 @ref{6e9,,类字节串对象}。而传入字符串会立即导致错误。


@geindex Intel/DVI ADPCM
@geindex ADPCM@comma{} Intel/DVI
@geindex a-LAW
@geindex u-LAW

本模块提供对 a-LAW、u-LAW 和 Intel/DVI ADPCM 编码的支持。

@c This para is mostly here to provide an excuse for the index entries...

部分更复杂的操作仅接受 16 位采样，而其他操作始终需要采样大小（以字节为单位）作为该操作的参数。

此模块定义了下列变量和函数：

@geindex error
@anchor{library/audioop audioop error}@anchor{3b40}
@deffn {例外} audioop.error

所有错误都会抛出此异常，比如采样值的字节数未知等等。
@end deffn

@geindex add() (在 audioop 模块中)
@anchor{library/audioop audioop add}@anchor{3b41}
@deffn {函数} audioop.add (fragment1, fragment2, width)

两个采样作为参数传入，返回一个片段，该片段是两个采样的和。@emph{width} 是采样位宽（以字节为单位），可以取 @code{1}, @code{2}, @code{3} 或 @code{4}。两个片段的长度应相同。如果发生溢出，较长的采样将被截断。
@end deffn

@geindex adpcm2lin() (在 audioop 模块中)
@anchor{library/audioop audioop adpcm2lin}@anchor{3b42}
@deffn {函数} audioop.adpcm2lin (adpcmfragment, width, state)

将 Intel/DVI ADPCM 编码的片段解码为线性片段。关于 ADPCM 编码的详情请参阅 @ref{3b43,,lin2adpcm()} 的描述。返回一个元组 @code{(sample, newstate)}，其中 sample 的位宽由 @emph{width} 指定。
@end deffn

@geindex alaw2lin() (在 audioop 模块中)
@anchor{library/audioop audioop alaw2lin}@anchor{3b44}
@deffn {函数} audioop.alaw2lin (fragment, width)

将 a-LAW 编码的声音片段转换为线性编码声音片段。由于 a-LAW 编码采样值始终为 8 位，因此这里的 @emph{width} 仅指输出片段的采样位宽。
@end deffn

@geindex avg() (在 audioop 模块中)
@anchor{library/audioop audioop avg}@anchor{3b45}
@deffn {函数} audioop.avg (fragment, width)

返回片段中所有采样值的平均值。
@end deffn

@geindex avgpp() (在 audioop 模块中)
@anchor{library/audioop audioop avgpp}@anchor{3b46}
@deffn {函数} audioop.avgpp (fragment, width)

返回片段中所有采样值的平均峰峰值。由于没有进行过滤，因此该例程的实用性尚存疑。
@end deffn

@geindex bias() (在 audioop 模块中)
@anchor{library/audioop audioop bias}@anchor{3b47}
@deffn {函数} audioop.bias (fragment, width, bias)

返回一个片段，该片段由原始片段中的每个采样值加上偏差组成。在溢出时采样值会回卷 (wrap around)。
@end deffn

@geindex byteswap() (在 audioop 模块中)
@anchor{library/audioop audioop byteswap}@anchor{919}
@deffn {函数} audioop.byteswap (fragment, width)

“按字节交换”片段中的所有采样值，返回修改后的片段。将大端序采样转换为小端序采样，反之亦然。


3.4 新版功能.

@end deffn

@geindex cross() (在 audioop 模块中)
@anchor{library/audioop audioop cross}@anchor{3b48}
@deffn {函数} audioop.cross (fragment, width)

将片段作为参数传入，返回其中过零点的数量。
@end deffn

@geindex findfactor() (在 audioop 模块中)
@anchor{library/audioop audioop findfactor}@anchor{3b49}
@deffn {函数} audioop.findfactor (fragment, reference)

返回一个系数 @emph{F} 使得 @code{rms(add(fragment, mul(reference, -F)))} 最小，即返回的系数乘以 @emph{reference} 后与 @emph{fragment} 最匹配。两个片段都应包含 2 字节宽的采样。

本例程所需的时间与 @code{len(fragment)} 成正比。
@end deffn

@geindex findfit() (在 audioop 模块中)
@anchor{library/audioop audioop findfit}@anchor{3b4a}
@deffn {函数} audioop.findfit (fragment, reference)

尽可能尝试让 @emph{reference} 匹配 @emph{fragment} 的一部分（@emph{fragment} 应较长）。从概念上讲，完成这些靠从 @emph{fragment} 中取出切片，使用 @ref{3b49,,findfactor()} 计算最佳匹配，并最小化结果。两个片段都应包含 2 字节宽的采样。返回一个元组 @code{(offset, factor)}，其中 @emph{offset} 是在 @emph{fragment} 中的偏移量（整数），表示从此处开始最佳匹配，而 @emph{factor} 是由 @ref{3b49,,findfactor()} 定义的因数（浮点数）。
@end deffn

@geindex findmax() (在 audioop 模块中)
@anchor{library/audioop audioop findmax}@anchor{3b4b}
@deffn {函数} audioop.findmax (fragment, length)

在 @emph{fragment} 中搜索所有长度为 @emph{length} 的采样切片（不是字节！）中，能量最大的那一个切片，即返回 @emph{i} 使得 @code{rms(fragment[i*2:(i+length)*2])} 最大。两个片段都应包含 2 字节宽的采样。

本例程所需的时间与 @code{len(fragment)} 成正比。
@end deffn

@geindex getsample() (在 audioop 模块中)
@anchor{library/audioop audioop getsample}@anchor{3b4c}
@deffn {函数} audioop.getsample (fragment, width, index)

返回片段中采样值索引 @emph{index} 的值。
@end deffn

@geindex lin2adpcm() (在 audioop 模块中)
@anchor{library/audioop audioop lin2adpcm}@anchor{3b43}
@deffn {函数} audioop.lin2adpcm (fragment, width, state)

将采样转换为 4 位 Intel/DVI ADPCM 编码。ADPCM 编码是一种自适应编码方案，其中每个 4 比特数字是一个采样值与下一个采样值之间的差除以（不定的）步长。IMA 已选择使用 Intel/DVI ADPCM 算法，因此它很可能成为标准。

@emph{state} 是一个表示编码器状态的元组。编码器返回一个元组 @code{(adpcmfrag, newstate)}，而 @emph{newstate} 要在下一次调用 @ref{3b43,,lin2adpcm()} 时传入。在初始调用中，可以将 @code{None} 作为 state 传递。@emph{adpcmfrag} 是 ADPCM 编码的片段，每个字节打包了 2 个 4 比特值。
@end deffn

@geindex lin2alaw() (在 audioop 模块中)
@anchor{library/audioop audioop lin2alaw}@anchor{3b4d}
@deffn {函数} audioop.lin2alaw (fragment, width)

将音频片段中的采样值转换为 a-LAW 编码，并将其作为字节对象返回。a-LAW 是一种音频编码格式，仅使用 8 位采样即可获得大约 13 位的动态范围。Sun 音频硬件等使用该编码。
@end deffn

@geindex lin2lin() (在 audioop 模块中)
@anchor{library/audioop audioop lin2lin}@anchor{3b4e}
@deffn {函数} audioop.lin2lin (fragment, width, newwidth)

将采样在 1、2、3 和 4 字节格式之间转换。

@cartouche
@quotation 注解 
在某些音频格式（如 .WAV 文件）中，16、24 和 32 位采样是有符号的，但 8 位采样是无符号的。因此，当将这些格式转换为 8 位宽采样时，还需使结果加上 128:

@example
new_frames = audioop.lin2lin(frames, old_width, 1)
new_frames = audioop.bias(new_frames, 1, 128)
@end example

反之，将 8 位宽的采样转换为 16、24 或 32 位时，必须采用相同的处理。
@end quotation
@end cartouche
@end deffn

@geindex lin2ulaw() (在 audioop 模块中)
@anchor{library/audioop audioop lin2ulaw}@anchor{3b4f}
@deffn {函数} audioop.lin2ulaw (fragment, width)

将音频片段中的采样值转换为 u-LAW 编码，并将其作为字节对象返回。u-LAW 是一种音频编码格式，仅使用 8 位采样即可获得大约 14 位的动态范围。Sun 音频硬件等使用该编码。
@end deffn

@geindex max() (在 audioop 模块中)
@anchor{library/audioop audioop max}@anchor{3b50}
@deffn {函数} audioop.max (fragment, width)

返回片段中所有采样值的最大 @emph{绝对值}。
@end deffn

@geindex maxpp() (在 audioop 模块中)
@anchor{library/audioop audioop maxpp}@anchor{3b51}
@deffn {函数} audioop.maxpp (fragment, width)

返回声音片段中的最大峰峰值。
@end deffn

@geindex minmax() (在 audioop 模块中)
@anchor{library/audioop audioop minmax}@anchor{3b52}
@deffn {函数} audioop.minmax (fragment, width)

返回声音片段中所有采样值的最小值和最大值组成的元组。
@end deffn

@geindex mul() (在 audioop 模块中)
@anchor{library/audioop audioop mul}@anchor{3b53}
@deffn {函数} audioop.mul (fragment, width, factor)

返回一个片段，该片段由原始片段中的每个采样值乘以浮点值 @emph{factor} 组成。如果发生溢出，采样将被截断。
@end deffn

@geindex ratecv() (在 audioop 模块中)
@anchor{library/audioop audioop ratecv}@anchor{3b54}
@deffn {函数} audioop.ratecv (fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])

转换输入片段的帧速率。

@emph{state} 是一个表示转换器状态的元组。转换器返回一个元组 @code{(newfragment, newstate)}，而 @emph{newstate} 要在下一次调用 @ref{3b54,,ratecv()} 时传入。初始调用应传入 @code{None} 作为 state。

参数 @emph{weightA} 和 @emph{weightB} 是简单数字滤波器的参数，默认分别为 @code{1} 和 @code{0}。
@end deffn

@geindex reverse() (在 audioop 模块中)
@anchor{library/audioop audioop reverse}@anchor{3b55}
@deffn {函数} audioop.reverse (fragment, width)

将片段中的采样值反转，返回修改后的片段。
@end deffn

@geindex rms() (在 audioop 模块中)
@anchor{library/audioop audioop rms}@anchor{3b56}
@deffn {函数} audioop.rms (fragment, width)

返回片段的均方根值，即 @code{sqrt(sum(S_i^2)/n)}。

测量音频信号的能量。
@end deffn

@geindex tomono() (在 audioop 模块中)
@anchor{library/audioop audioop tomono}@anchor{3b57}
@deffn {函数} audioop.tomono (fragment, width, lfactor, rfactor)

将立体声片段转换为单声道片段。左通道乘以 @emph{lfactor}，右通道乘以 @emph{rfactor}，然后两个通道相加得到单声道信号。
@end deffn

@geindex tostereo() (在 audioop 模块中)
@anchor{library/audioop audioop tostereo}@anchor{3b58}
@deffn {函数} audioop.tostereo (fragment, width, lfactor, rfactor)

由单声道片段生成立体声片段。立体声片段中的两对采样都是从单声道计算而来的，即左声道是乘以 @emph{lfactor}，右声道是乘以 @emph{rfactor}。
@end deffn

@geindex ulaw2lin() (在 audioop 模块中)
@anchor{library/audioop audioop ulaw2lin}@anchor{3b59}
@deffn {函数} audioop.ulaw2lin (fragment, width)

将 u-LAW 编码的声音片段转换为线性编码声音片段。由于 u-LAW 编码采样值始终为 8 位，因此这里的 @emph{width} 仅指输出片段的采样位宽。
@end deffn

请注意，诸如 @ref{3b53,,mul()} 或 @ref{3b50,,max()} 之类的操作在单声道和立体声间没有区别，即所有采样都作相同处理。如果出现问题，应先将立体声片段拆分为两个单声道片段，之后再重组。以下是如何进行该操作的示例:

@example
def mul_stereo(sample, width, lfactor, rfactor):
    lsample = audioop.tomono(sample, width, 1, 0)
    rsample = audioop.tomono(sample, width, 0, 1)
    lsample = audioop.mul(lsample, width, lfactor)
    rsample = audioop.mul(rsample, width, rfactor)
    lsample = audioop.tostereo(lsample, width, 1, 0)
    rsample = audioop.tostereo(rsample, width, 0, 1)
    return audioop.add(lsample, rsample, width)
@end example

如果使用 ADPCM 编码器构造网络数据包，并且希望协议是无状态的（即能够容忍数据包丢失），则不仅需要传输数据，还应该传输状态。请注意，必须将*初始*状态（传入 @ref{3b43,,lin2adpcm()} 的状态）发送给解码器，不能发送最终状态（编码器返回的状态）。如果要使用 @ref{199b,,struct.Struct} 以二进制保存状态，可以将第一个元素（预测值）用 16 位编码，将第二个元素（增量索引）用 8 位编码。

本 ADPCM 编码器从不与其他 ADPCM 编码器对立，仅针对自身。本开发者可能会误读标准，这种情况下它们将无法与相应标准互操作。

乍看之下 @code{find*()} 例程可能有些可笑。它们主要是用于回声消除，一种快速有效的方法是选取输出样本中能量最高的片段，在输入样本中定位该片段，然后从输入样本中减去整个输出样本:

@example
def echocancel(outputdata, inputdata):
    pos = audioop.findmax(outputdata, 800)    # one tenth second
    out_test = outputdata[pos*2:]
    in_test = inputdata[pos*2:]
    ipos, factor = audioop.findfit(in_test, out_test)
    # Optional (for better cancellation):
    # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
    #              out_test)
    prefill = '\0'*(pos+ipos)*2
    postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
    outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
    return audioop.add(inputdata, outputdata, 2)
@end example

@node cgi --- 通用网关接口支持,cgitb --- 用于 CGI 脚本的回溯管理器,audioop --- 处理原始音频数据,被取代的模块
@anchor{library/cgi doc}@anchor{3b5a}@anchor{library/cgi cgi-common-gateway-interface-support}@anchor{3b5b}@anchor{library/cgi module-cgi}@anchor{15}
@subsection @code{cgi} --- 通用网关接口支持


@geindex cgi (模块)

@strong{源代码：} Lib/cgi.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/cgi.py}

@geindex WWW; server
@geindex CGI; protocol
@geindex HTTP; protocol
@geindex MIME; headers
@geindex URL
@geindex Common Gateway Interface


3.11 版后已移除: @ref{15,,cgi} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#cgi
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#cgi} 了解详情及其替代品）。



__________________________________________________________________


通用网关接口 (CGI) 脚本的支持模块

本模块定义了一些工具供以 Python 编写的 CGI 脚本使用。

@menu
* 概述: 概述<14>. 
* 使用cgi模块。:: 
* 更高层级的接口:: 
* 函数: 函数<12>. 
* 对于安全性的关注:: 
* 在 Unix 系统上安装你的 CGI 脚本:: 
* 测试你的 CGI 脚本:: 
* 调试 CGI 脚本:: 
* 常见问题和解决方案:: 

@end menu

@node 概述<14>,使用cgi模块。,,cgi --- 通用网关接口支持
@anchor{library/cgi introduction}@anchor{3b5c}
@subsubsection 概述

@anchor{library/cgi cgi-intro}@anchor{3b5d}
CGI 脚本是由 HTTP 服务器发起调用，通常用来处理通过 HTML @code{<FORM>} 或 @code{<ISINDEX>} 元素提交的用户输入。

在大多数情况下，CGI 脚本存放在服务器的 @code{cgi-bin} 特殊目录下。 HTTP 服务器将有关请求的各种信息（例如客户端的主机名、所请求的 URL、查询字符串以及许多其他内容）放在脚本的 shell 环境中，然后执行脚本，并将脚本的输出发回到客户端。

脚本的输入也会被连接到客户端，并且有时表单数据也会以此方式来读取；在其他时候表单数据会通过 URL 的“查询字符串”部分来传递。 本模块的目标是处理不同的应用场景并向 Python 脚本提供一个更为简单的接口。 它还提供了一些工具为脚本调试提供帮助，而最近增加的还有对通过表单上传文件的支持（如果你的浏览器支持该功能的话）。

CGI 脚本的输出应当由两部分组成，并由一个空行分隔。 前一部分包含一些标头，它们告诉客户端后面会提供何种数据。 生成一个最小化标头部分的 Python 代码如下所示:

@example
print("Content-Type: text/html")    # HTML is following
print()                             # blank line, end of headers
@end example

后一部分通常为 HTML，提供给客户端软件来显示格式良好包含标题的文本、内联图片等内容。 下面是打印一段简单 HTML 的 Python 代码:

@example
print("<TITLE>CGI script output</TITLE>")
print("<H1>This is my first CGI script</H1>")
print("Hello, world!")
@end example

@node 使用cgi模块。,更高层级的接口,概述<14>,cgi --- 通用网关接口支持
@anchor{library/cgi id1}@anchor{3b5e}@anchor{library/cgi using-the-cgi-module}@anchor{3b5f}
@subsubsection 使用cgi模块。


通过敲下 @code{import cgi} 来开始。

当你在写一个新脚本时，考虑加上这些语句:

@example
import cgitb
cgitb.enable()
@end example

这会激活一个特殊的异常处理句柄，它将在发生任何错误时将详细错误报告显示到 Web 浏览器中。 如果你不希望向你的脚本 的用户显示你的程序的内部细节，你可以改为将报告保存到文件中，使用这样的代码即可:

@example
import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
@end example

在脚本开发期间使用此特性会很有帮助。 @ref{16,,cgitb} 所产生的报告提供了在追踪程序问题时能为你节省大量时间的信息。 你可以在完成测试你的脚本并确信它能正确工作之后再移除 @code{cgitb} 行。

要获取提交的表单数据，请使用 @code{FieldStorage} 类。 如果表单包含非 ASCII 字符，请使用 @emph{encoding} 关键字参数并设置为文档所定义的编码格式值。 它通常包含在 HTML 文档的 HEAD 部分的 META 标记中或者由 @code{Content-Type} 标头所指明。 这会从标准输入或环境读取表单内容（取决于根据 CGI 标准设置的多个环境变量的值）。 由于它可能会消耗标准输入，它应当只被实例化一次。

@code{FieldStorage} 实例可以像 Python 字典一样来检索。 它允许通过 @ref{179,,in} 运算符进行成员检测，也支持标准字典方法 @ref{cfc,,keys()} 和内置函数 @ref{292,,len()}。 包含空字符串的表单字段会被忽略而不会出现在字典中；要保留这样的值，请在创建 @code{FieldStorage} 实例时为可选的 @emph{keep_blank_values} 关键字形参提供一个真值。

举例来说，下面的代码（假定 @code{Content-Type} 标头和空行已经被打印）会检查字段 @code{name} 和 @code{addr} 是否均被设为非空字符串:

@example
form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
    print("<H1>Error</H1>")
    print("Please fill in the name and addr fields.")
    return
print("<p>name:", form["name"].value)
print("<p>addr:", form["addr"].value)
...further form processing here...
@end example

在这里的字段通过 @code{form[key]} 来访问，它们本身就是 @code{FieldStorage} (或 @code{MiniFieldStorage}，取决于表单的编码格式) 的实例。 实例的 @code{value} 属性会产生字段的字符串值。 @code{getvalue()} 方法直接返回这个字符串；它还接受可选的第二个参数作为当请求的键不存在时要返回的默认值。

如果提交的表单数据包含一个以上的同名字段，由 @code{form[key]} 所提取的对象将不是一个 @code{FieldStorage} 或 @code{MiniFieldStorage} 实例而是由这种实例组成的列表。 类似地，在这种情况下，@code{form.getvalue(key)} 将会返回一个字符串列表。 如果你预计到这种可能性（当你的 HTML 表单包含多个同名字段时），请使用 @ref{3b60,,getlist()} 方法，它总是返回一个值的列表（这样你就不需要对只有单个项的情况进行特别处理）。 例如，这段代码拼接了任意数量的 username 字段，以逗号进行分隔:

@example
value = form.getlist("username")
usernames = ",".join(value)
@end example

如果一个字段是代表上传的文件，请通过 @code{value} 属性访问该值或是通过 @code{getvalue()} 方法以字节形式将整个文件读入内存。 这可能不是你想要的结果。 你可以通过测试 @code{filename} 属性或 @code{file} 属性来检测上传的文件。 然后你可以从 @code{file} 属性读取数据，直到它作为 @code{FieldStorage} 实例的垃圾回收的一部分被自动关闭 (@ref{7fd,,read()} 和 @ref{1883,,readline()} 方法将返回字节数据):

@example
fileitem = form["userfile"]
if fileitem.file:
    # It's an uploaded file; count lines
    linecount = 0
    while True:
        line = fileitem.file.readline()
        if not line: break
        linecount = linecount + 1
@end example

@code{FieldStorage} 对象还支持在 @ref{7e4,,with} 语句中使用，该语句结束时将自动关闭它们。

如果在获取上传文件的内容时遇到错误（例如，当用户点击回退或取消按钮中断表单提交时）该字段中对象的 @code{done} 属性值将被设为 -1。

文件上传标准草案考虑到了从一个字段上传多个文件的可能性（使用递归的 @code{multipart/*} 编码格式）。 当这种情况发生时，该条目将是一个类似字典的 @code{FieldStorage} 条目。 这可以通过检测它的 @code{type} 属性来确定，该属性应当是 @code{multipart/form-data} (或者可能是匹配 @code{multipart/*} 的其他 MIME 类型)。 在这种情况下，它可以像最高层级的表单对象一样被递归地迭代处理。

当一个表单按“旧”格式提交时（即以查询字符串或是单个 @code{application/x-www-form-urlencoded} 类型的数据部分的形式），这些条目实际上将是 @code{MiniFieldStorage} 类的实例。 在这种情况下，@code{list}, @code{file} 和 @code{filename} 属性将总是为 @code{None}。

通过 POST 方式提交并且也带有查询字符串的表单将同时包含 @code{FieldStorage} 和 @code{MiniFieldStorage} 条目。


在 3.4 版更改: @code{file} 属性会在创建 @code{FieldStorage} 实例的垃圾回收操作中被自动关闭。



在 3.5 版更改: 为 @code{FieldStorage} 类增加了上下文管理协议支持。


@node 更高层级的接口,函数<12>,使用cgi模块。,cgi --- 通用网关接口支持
@anchor{library/cgi higher-level-interface}@anchor{3b61}
@subsubsection 更高层级的接口


前面的部分解释了如何使用 @code{FieldStorage} 类来读取 CGI 表单数据。 本部分则会描述一个更高层级的接口，它被添加到此类中以允许人们以更为可读和自然的方式行事。 这个接口并不会完全取代前面的部分所描述的技巧 --- 例如它们在高效处理文件上传时仍然很有用处。

@c XXX: Is this true ?

此接口由两个简单的方法组成。 你可以使用这两个方法以通用的方式处理表单数据，而无需担心在一个名称下提交的值是只有一个还是有多个。

在前面的部分中，你已学会当你预期用户在一个名称下提交超过一个值的时候编写以下代码:

@example
item = form.getvalue("item")
if isinstance(item, list):
    # The user is requesting more than one item.
else:
    # The user is requesting only one item.
@end example

这种情况很常见，例如当一个表单包含具有相同名称的一组复选框的时候:

@example
<input type="checkbox" name="item" value="1" />
<input type="checkbox" name="item" value="2" />
@end example

但是在多数情况下，一个表单中的一个特定名称只对应一个表单控件。 因此你可能会编写包含以下代码的脚本:

@example
user = form.getvalue("user").upper()
@end example

这段代码的问题在于你绝不能预期客户端会向你的脚本提供合法的输入。 举例来说，如果一个好奇的用户向查询字符串添加了另一个 @code{user=foo} 对，则该脚本将会崩溃，因为在这种情况下 @code{getvalue("user")} 方法调用将返回一个列表而不是字符串。 在一个列表上调用 @ref{17c2,,upper()} 方法是不合法的（因为列表并没有这个方法）因而会引发 @ref{4aa,,AttributeError} 异常。

因此，读取表单数据值的正确方式应当总是使用检查所获取的值是单一值还是值列表的代码。 这很麻烦并且会使脚本缺乏可读性。

一种更便捷的方式是使用这个更高层级接口所提供的 @ref{3b62,,getfirst()} 和 @ref{3b60,,getlist()} 方法。

@geindex getfirst() (cgi.FieldStorage 方法)
@anchor{library/cgi cgi FieldStorage getfirst}@anchor{3b62}
@deffn {方法} FieldStorage.getfirst (name, default=None)

此方法总是只返回与表单字段 @emph{name} 相关联的单一值。 此方法在同一名称下提交了多个值的情况下将仅返回第一个值。 请注意所接收的值顺序在不同浏览器上可能发生变化因而是不确定的。 @footnote{@w{(1)} 
请注意，新版的 HTML 规范确实注明了请求字段的顺序，但判断请求是否合法非常繁琐和容易出错，可能来自不符合要求的浏览器，甚至不是来自浏览器。
}  如果指定的表单字段或值不存在则此方法将返回可选形参 @emph{default} 所指定的值。 如果未指定此形参则默认值为 @code{None}。
@end deffn

@geindex getlist() (cgi.FieldStorage 方法)
@anchor{library/cgi cgi FieldStorage getlist}@anchor{3b60}
@deffn {方法} FieldStorage.getlist (name)

此方法总是返回与表单字段 @emph{name} 相关联的值列表。 如果 @emph{name} 指定的表单字段或值不存在则此方法将返回一个空列表。 如果指定的表单字段只包含一个值则它将返回只有一项的列表。
@end deffn

使用这两个方法你将能写出优雅简洁的代码:

@example
import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper()    # This way it's safe.
for item in form.getlist("item"):
    do_something(item)
@end example

@node 函数<12>,对于安全性的关注,更高层级的接口,cgi --- 通用网关接口支持
@anchor{library/cgi functions}@anchor{3b63}@anchor{library/cgi functions-in-cgi-module}@anchor{3b64}
@subsubsection 函数


这些函数在你想要更多控制，或者如果你想要应用一些此模块中在其他场景下实现的算法时很有用处。

@geindex parse() (在 cgi 模块中)
@anchor{library/cgi cgi parse}@anchor{282}
@deffn {函数} cgi.parse (fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")

在环境中或从某个文件中解析一个查询 (文件默认为 @code{sys.stdin})。 @emph{keep_blank_values}, @emph{strict_parsing} 和 @emph{separator} 形参会被原样传给 @ref{280,,urllib.parse.parse_qs()}。
@end deffn

@geindex parse_multipart() (在 cgi 模块中)
@anchor{library/cgi cgi parse_multipart}@anchor{283}
@deffn {函数} cgi.parse_multipart (fp, pdict, encoding="utf-8", errors="replace", separator="&")

解析 @code{multipart/form-data} 类型（用于文件上传）的输入。 参数中 @emph{fp} 为输入文件，@emph{pdict} 为包含 @code{Content-Type} 标头中的其他形参的字典，@emph{encoding} 为请求的编码格式。

像 @ref{280,,urllib.parse.parse_qs()} 那样返回一个字典：其中的键为字段名称，值为对应字段的值列表。 对于非文件字段，其值均为字符串列表。

这很容易使用，但如果你预期要上传巨量字节数据时就不太适合了 --- 在这种情况下，请改用更为灵活的 @code{FieldStorage} 类。


在 3.7 版更改: 增加了 @emph{encoding} 和 @emph{errors} 形参。 对于非文件字段，其值现在为字符串列表而非字节串列表。



在 3.9.2 版更改: 增加了 @emph{separator} 形参。

@end deffn

@geindex parse_header() (在 cgi 模块中)
@anchor{library/cgi cgi parse_header}@anchor{3b65}
@deffn {函数} cgi.parse_header (string)

将一个 MIME 标头 (例如 @code{Content-Type}) 解析为一个主值和一个参数字典。
@end deffn

@geindex test() (在 cgi 模块中)
@anchor{library/cgi cgi test}@anchor{3b66}
@deffn {函数} cgi.test ()

对 CGI 执行健壮性检测，适于作为主程序。 写入最小化的 HTTP 标头并以 HTML 格式来格式化提供给脚本的所有信息。
@end deffn

@geindex print_environ() (在 cgi 模块中)
@anchor{library/cgi cgi print_environ}@anchor{3b67}
@deffn {函数} cgi.print_environ ()

以 HTML 格式来格式化 shell 环境。
@end deffn

@geindex print_form() (在 cgi 模块中)
@anchor{library/cgi cgi print_form}@anchor{3b68}
@deffn {函数} cgi.print_form (form)

以 HTML 格式来格式化表单。
@end deffn

@geindex print_directory() (在 cgi 模块中)
@anchor{library/cgi cgi print_directory}@anchor{3b69}
@deffn {函数} cgi.print_directory ()

以 HTML 格式来格式化当前目录。
@end deffn

@geindex print_environ_usage() (在 cgi 模块中)
@anchor{library/cgi cgi print_environ_usage}@anchor{3b6a}
@deffn {函数} cgi.print_environ_usage ()

以 HTML 格式打印有用的环境变量列表（供 CGI 使用）。
@end deffn

@node 对于安全性的关注,在 Unix 系统上安装你的 CGI 脚本,函数<12>,cgi --- 通用网关接口支持
@anchor{library/cgi caring-about-security}@anchor{3b6b}@anchor{library/cgi cgi-security}@anchor{3b6c}
@subsubsection 对于安全性的关注


@geindex CGI; security

有一条重要的规则：如果你发起调用一个外部程序（通过 @ref{e8e,,os.system()}, @ref{3d3,,os.popen()} 或其他具有类似功能的函数），需要非常确定你不会把从客户端接收的任意字符串直接传给 shell。 这是一个著名的安全漏洞，网络中聪明的黑客可以通过它来利用容易上当的 CGI 脚本发起调用任何 shell 命令。 即使 URL 的一部分或字段名称也是不可信任的，因为请求并不一定是来自你的表单！

为了安全起见，如果你必须将从表单获取的字符串传给 shell 命令，你应当确保该字符串仅包含字母数字类字符、连字符、下划线和句点。

@node 在 Unix 系统上安装你的 CGI 脚本,测试你的 CGI 脚本,对于安全性的关注,cgi --- 通用网关接口支持
@anchor{library/cgi installing-your-cgi-script-on-a-unix-system}@anchor{3b6d}
@subsubsection 在 Unix 系统上安装你的 CGI 脚本


请阅读你的 HTTP 服务器的文档并咨询你所用系统的管理员来找到 CGI 脚本应当安装到哪个目录；通常是服务器目录树中的 @code{cgi-bin} 目录。

请确保你的脚本可被“其他人”读取和执行；Unix 文件模式应为八进制数 @code{0o755} (使用 @code{chmod 0755 filename})。 请确保脚本的第一行包含 @code{#!} 且位置是从第 1 列开始，后面带有 Python 解释器的路径名，例如:

@example
#!/usr/local/bin/python
@end example

请确保该 Python 解释器存在并且可被“其他人”执行。

请确保你的脚本需要读取或写入的任何文件都分别是“其他人”可读取或可写入的 --- 它们的模式应为可读取 @code{0o644} 或可写入 @code{0o666}。 这是因为出于安全理由，HTTP 服务器是作为没有任何特殊权限的 "nobody" 用户来运行脚本的。 它只能读取（写入、执行）任何人都能读取（写入、执行）的文件。 执行时的当前目录（通常为服务器的 cgi-bin 目录）和环境变量集合也与你在登录时所得到的不同。 特别地，不可依赖于 shell 的可执行文件搜索路径 (
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}) 或 Python 模块搜索路径 (
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH}) 的任何相关设置。

如果你需要从 Python 的默认模块搜索路径之外的目录载入模块，你可以在导入其他模块之前在你的脚本中改变路径。 例如:

@example
import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
@end example

（在此方式下，最后插入的目录将最先被搜索！）

针对非 Unix 系统的指导会有所变化；请查看你的 HTTP 服务器的文档（通常会有关于 CGI 脚本的部分）。

@node 测试你的 CGI 脚本,调试 CGI 脚本,在 Unix 系统上安装你的 CGI 脚本,cgi --- 通用网关接口支持
@anchor{library/cgi testing-your-cgi-script}@anchor{3b6e}
@subsubsection 测试你的 CGI 脚本


很不幸，当你在命令行中尝试 CGI 脚本时它通常会无法运行，而能在命令行中完美运行的脚本则可能会在运行于服务器时神秘地失败。 但有一个理由使你仍然应当在命令行中测试你的脚本：如果它包含语法错误，Python 解释器将根本不会执行它，而 HTTP 服务器将很可能向客户端发送令人费解的错误信息。

假定你的脚本没有语法错误，但它仍然无法起作用，你将别无选择，只能继续阅读下一节。

@node 调试 CGI 脚本,常见问题和解决方案,测试你的 CGI 脚本,cgi --- 通用网关接口支持
@anchor{library/cgi debugging-cgi-scripts}@anchor{3b6f}
@subsubsection 调试 CGI 脚本


@geindex CGI; debugging

首先，请检查是否有安装上的小错误 --- 仔细阅读上面关于安装 CGI 脚本的部分可以使你节省大量时间。 如果你不确定你是否正确理解了安装过程，请尝试将此模块 (@code{cgi.py}) 的副本作为 CGI 脚本安装。 当作为脚本被发起调用时，该文件将以 HTML 格式转储其环境和表单内容。 请给它赋予正确的模式等，并向它发送一个请求。 如果它是安装在标准的 @code{cgi-bin} 目录下，应该可以通过在你的浏览器中输入表单的 URL 来向它发送请求。

@example
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
@end example

如果此操作给出类型为 404 的错误，说明服务器找不到此脚本 -- 也许你需要将它安装到不同的目录。 如果它给出另一种错误，说明存在安装问题，你应当解决此问题才能继续操作。 如果你得到一个格式良好的环境和表单内容清单（在这个例子中，应当会列出的有字段 "addr" 值为 "At Home" 以及 "name" 值为 "Joe Blow"），则说明 @code{cgi.py} 脚本已正确安装。  如果你为自己的脚本执行了同样的过程，现在你应该能够调试它了。

下一步骤可以是在你的脚本中调用 @ref{15,,cgi} 模块的 @ref{105,,test()} 函数：用这一条语句替换它的主代码

@example
cgi.test()
@end example

这将产生从安装 @code{cgi.py} 文件本身所得到的相同结果。

当某个常规 Python 脚本触发了未处理的异常，（无论出于什么原因：模块名称出错、文件无法打开等)，Python 解释器就会打印出一条完整的跟踪信息并退出。在 CGI 脚本触发异常时，Python 解释器依然会如此，但最有可能的是，跟踪信息只会停留在某个 HTTP 服务日志文件中，或者被完全丢弃。

幸运的是，只要执行 @emph{某些} 代码，就可以利用 @ref{16,,cgitb} 模块将跟踪信息发送给浏览器。 如果你还没有这样做过，只需添加以下几行代码:

@example
import cgitb
cgitb.enable()
@end example

然后再运行一下看；发生问题时应能看到详细的报告，或许能让崩溃的原因更清晰一些。

如果怀疑是 @ref{16,,cgitb} 模块导入的问题，可以采用一个功能更强的方法（只用到内置模块）：

@example
import sys
sys.stderr = sys.stdout
print("Content-Type: text/plain")
print()
...your code here...
@end example

这得靠 Python 解释器来打印跟踪信息。输出的类型为纯文本，不经过任何 HTML 处理。如果代码正常，则客户端会显示原有的 HTML。如果触发了异常，很可能在输出前两行后会显示一条跟踪信息。因为不会继续进行 HTML 解析，所以跟踪信息肯定能被读到。

@node 常见问题和解决方案,,调试 CGI 脚本,cgi --- 通用网关接口支持
@anchor{library/cgi common-problems-and-solutions}@anchor{3b70}
@subsubsection 常见问题和解决方案



@itemize *

@item 
大部分 HTTP 服务器会对 CGI 脚本的输出进行缓存，等脚本执行完毕再行输出。这意味着在脚本运行时，不可能在客户端屏幕上显示出进度情况。

@item 
请查看上述安装说明。

@item 
请查看 HTTP 服务器的日志文件。（在另一个单独窗口中执行 @code{tail -f logfile} 可能会很有用！）

@item 
一定要先检查脚本是否有语法错误，做法类似：@code{python script.py} 。

@item 
如果脚本没有语法错误，试着在脚本的顶部添加 @code{import cgitb; cgitb.enable()}。

@item 
当调用外部程序时，要确保其可被读取。通常这意味着采用绝对路径名------ 在 CGI 脚本中， 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 通常不会设为很有用的值。

@item 
在读写外部文件时，要确保其能被 CGI 脚本归属的用户读写：通常是运行网络服务的用户，或由网络服务的 @code{suexec} 功能明确指定的一些用户。

@item 
不要试图给 CGI 脚本赋予 set-uid 模式。这在大多数系统上这都行不通，出于安全考虑也不应如此。
@end itemize

@node cgitb --- 用于 CGI 脚本的回溯管理器,chunk --- 读取 IFF 分块数据,cgi --- 通用网关接口支持,被取代的模块
@anchor{library/cgitb doc}@anchor{3b71}@anchor{library/cgitb cgitb-traceback-manager-for-cgi-scripts}@anchor{3b72}@anchor{library/cgitb module-cgitb}@anchor{16}
@subsection @code{cgitb} --- 用于 CGI 脚本的回溯管理器


@geindex cgitb (模块)

@strong{源代码:} Lib/cgitb.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/cgitb.py}

@geindex CGI; exceptions
@geindex CGI; tracebacks
@geindex exceptions; in CGI scripts
@geindex tracebacks; in CGI scripts


3.11 版后已移除: @ref{16,,cgitb} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#cgitb
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#cgitb} 了解详情）。



__________________________________________________________________


@ref{16,,cgitb} 模块提供了用于 Python 脚本的特殊异常处理程序。 （这个名称有一点误导性。 它最初是设计用来显示 HTML 格式的 CGI 脚本详细回溯信息。 但后来被一般化为也可显示纯文本格式的回溯信息。） 激活这个模块之后，如果发生了未被捕获的异常，将会显示详细的已格式化的报告。 报告显示内容包括每个层级的源代码摘录，还有当前正在运行的函数的参数和局部变量值，以帮助你调试问题。 你也可以选择将此信息保存至文件而不是将其发送至浏览器。

要启用此特性，只需简单地将此代码添加到你的 CGI 脚本的最顶端:

@example
import cgitb
cgitb.enable()
@end example

@ref{3b73,,enable()} 函数的选项可以控制是将报告显示在浏览器中，还是将报告记录到文件供以后进行分析。

@geindex enable() (在 cgitb 模块中)
@anchor{library/cgitb cgitb enable}@anchor{3b73}
@deffn {函数} cgitb.enable (display=1, logdir=None, context=5, format="html")

@geindex excepthook() (in module sys)

此函数可通过设置 @ref{1ae,,sys.excepthook} 的值以使 @ref{16,,cgitb} 模块接管解释器默认的异常处理机制。

可选参数 @emph{display} 默认为 @code{1} 并可被设为 @code{0} 来停止将回溯发送至浏览器。 如果给出了参数 @emph{logdir}，则回溯会被写入文件。 @emph{logdir} 的值应当是一个用于存放所写入文件的目录。 可选参数 @emph{context} 是要在回溯中的当前源代码行前后显示的上下文行数；默认为 @code{5}。 如果可选参数 @emph{format} 为 @code{"html"}，输出将为 HTML 格式。 任何其它值都会强制启用纯文本输出。 默认取值为 @code{"html"}。
@end deffn

@geindex text() (在 cgitb 模块中)
@anchor{library/cgitb cgitb text}@anchor{3b74}
@deffn {函数} cgitb.text (info, context=5)

此函数用于处理 @emph{info} (一个包含 @ref{d2f,,sys.exc_info()} 返回结果的 3 元组) 所描述的异常，将其回溯格式化为文本并将结果作为字符串返回。 可选参数 @emph{context} 是要在回溯中的当前源码行前后显示的上下文行数；默认为 @code{5}。
@end deffn

@geindex html() (在 cgitb 模块中)
@anchor{library/cgitb cgitb html}@anchor{3b75}
@deffn {函数} cgitb.html (info, context=5)

此函数用于处理 @emph{info} (一个包含 @ref{d2f,,sys.exc_info()} 返回结果的 3 元组) 所描述的异常，将其回溯格式化为 HTML 并将结果作为字符串返回。 可选参数 @emph{context} 是要在回溯中的当前源码行前后显示的上下文行数；默认为 @code{5}。
@end deffn

@geindex handler() (在 cgitb 模块中)
@anchor{library/cgitb cgitb handler}@anchor{3b76}
@deffn {函数} cgitb.handler (info=None)

此函数使用默认设置处理异常（即在浏览器中显示报告，但不记录到文件）。 当你捕获了一个异常并希望使用 @ref{16,,cgitb} 来报告它时可以使用此函数。 可选的 @emph{info} 参数应为一个包含异常类型，异常值和回溯对象的 3 元组，与 @ref{d2f,,sys.exc_info()} 所返回的元组完全一致。 如果未提供 @emph{info} 参数，则会从 @ref{d2f,,sys.exc_info()} 获取当前异常。
@end deffn

@node chunk --- 读取 IFF 分块数据,crypt —— 检查 Unix 口令的函数,cgitb --- 用于 CGI 脚本的回溯管理器,被取代的模块
@anchor{library/chunk doc}@anchor{3b77}@anchor{library/chunk chunk-read-iff-chunked-data}@anchor{3b78}@anchor{library/chunk module-chunk}@anchor{17}
@subsection @code{chunk} --- 读取 IFF 分块数据


@geindex chunk (模块)

@strong{源代码:} Lib/chunk.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/chunk.py}

@geindex Audio Interchange File Format
@geindex AIFF
@geindex AIFF-C
@geindex Real Media File Format
@geindex RMFF


3.11 版后已移除: @ref{17,,chunk} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#chunk
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#chunk} 了解详情）。



__________________________________________________________________


本模块提供了一个读取使用 EA IFF 85 分块的数据的接口chunks. @footnote{@w{(1)} 
"EA IFF 85" 交换格式文件标准, Jerry Morrison, Electronic Arts, 1985 年 1 月。
}  这种格式使用的场合有 Audio Interchange File Format (AIFF/AIFF-C) 和 Real Media File Format (RMFF) 等。 与它们密切相关的 WAVE 音频文件也可使用此模块来读取。

一个分块具有以下结构:


@multitable {xxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

偏移

@tab

长度

@tab

内容

@item

0

@tab

4

@tab

区块ID

@item

4

@tab

4

@tab

大端字节顺序的块大小，不包括头

@item

8

@tab

@emph{n}

@tab

数据字节，其中 @emph{n} 是前一字段中给出的大小

@item

8 + @emph{n}

@tab

0 或 1

@tab

如果 @emph{n} 为奇数且使用块对齐，则需要填充字节

@end multitable


ID是一个4字节的字符串，用于标识块的类型。

大小字段（32 位的值，使用大端字节序编码）给出分块数据的大小，不包括 8 字节的标头。

使用由一个或更多分块组成的 IFF 类型文件。 此处定义的 @ref{3b79,,Chunk} 类的建议使用方式是在每个分块开始时实例化一个实例并从实例读取直到其末尾，在那之后可以再实例化新的实例。 到达文件末尾时，创建新实例将会失败并引发 @ref{d3c,,EOFError} 异常。

@geindex Chunk (chunk 中的类)
@anchor{library/chunk chunk Chunk}@anchor{3b79}
@deffn {类} chunk.Chunk (file, align=True, bigendian=True, inclheader=False)

代表一个分块的类。 @emph{file} 参数预期为一个文件类对象。 特别地也允许该类的实例。 唯一必需的方法是 @code{read()}。 如果存在 @ref{1f3f,,seek()} 和 @ref{1f40,,tell()} 方法并且没有引发异常，它们也会被使用。 如果存在这些方法并且引发了异常，则它们不应改变目标对象。 如果可选参数 @emph{align} 为真值，则分块应当以 2 字节边界对齐。 如果 @emph{align} 为假值，则不使用对齐。 此参数默认为真值。 如果可选参数 @emph{bigendian} 为假值，分块大小应当为小端序。 这对于 WAVE 音频文件是必须的。 此参数默认为真值。 如果可选参数 @emph{inclheader} 为真值，则分块标头中给出的大小将包括标头的大小。 此参数默认为假值。

@ref{3b79,,Chunk} 对象支持下列方法：

@geindex getname() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk getname}@anchor{3b7a}
@deffn {方法} getname ()

返回分块的名称（ID）。 这是分块的头 4 个字节。
@end deffn

@geindex getsize() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk getsize}@anchor{3b7b}
@deffn {方法} getsize ()

返回分块的大小。
@end deffn

@geindex close() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk close}@anchor{3b7c}
@deffn {方法} close ()

关闭并跳转到分块的末尾。 这不会关闭下层的文件。
@end deffn

在 @ref{3b7c,,close()} 方法已被调用后其余方法将会引发 @ref{30b,,OSError}。 在 Python 3.3 之前，它们曾会引发 @ref{a7c,,IOError}，现在这是 @ref{30b,,OSError} 的一个别名。

@geindex isatty() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk isatty}@anchor{3b7d}
@deffn {方法} isatty ()

返回 @code{False}。
@end deffn

@geindex seek() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk seek}@anchor{3b7e}
@deffn {方法} seek (pos, whence=0)

设置分块的当前位置。 @emph{whence} 参数为可选项并且默认为 @code{0} (绝对文件定位)；其他值还有 @code{1} (相对当前位置查找) 和 @code{2} (相对文件末尾查找)。 没有返回值。 如果下层文件不支持查找，则只允许向前查找。
@end deffn

@geindex tell() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk tell}@anchor{3b7f}
@deffn {方法} tell ()

将当前位置返回到分块。
@end deffn

@geindex read() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk read}@anchor{3b80}
@deffn {方法} read (size=-1)

从分块读取至多 @emph{size} 个字节（如果在获得 @emph{size} 个字节之前已到达分块末尾则读取的字节会少于此数量）。 如果 @emph{size} 参数为负值或被省略，则读取所有字节直到分块末尾。 当立即遇到分块末尾则返回空字节串对象。
@end deffn

@geindex skip() (chunk.Chunk 方法)
@anchor{library/chunk chunk Chunk skip}@anchor{3b81}
@deffn {方法} skip ()

跳到分块末尾。此后对分块再次调用 @ref{3b80,,read()} 将返回 @code{b'@w{'}}。 如果你对分块的内容不感兴趣，则应当调用此方法以使文件指向下一分块的开头。
@end deffn
@end deffn

@node crypt —— 检查 Unix 口令的函数,imghdr --- 推测图像类型,chunk --- 读取 IFF 分块数据,被取代的模块
@anchor{library/crypt doc}@anchor{3b82}@anchor{library/crypt crypt-function-to-check-unix-passwords}@anchor{3b83}@anchor{library/crypt module-crypt}@anchor{28}
@subsection @code{crypt} —— 检查 Unix 口令的函数


@geindex crypt (模块)

@strong{源代码：} Lib/struct.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/struct.py}

@geindex crypt(3)
@geindex cipher; DES


3.11 版后已移除: @ref{28,,crypt} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#crypt
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#crypt} 了解详情及其替代品）。 @ref{8c,,hashlib} 模块是针对特定用例的潜在替换选项。



__________________________________________________________________


本模块实现了连接 @code{crypt(3)} 的接口，是一个基于改进 DES 算法的单向散列函数；更多细节请参阅 Unix man 手册。可能的用途包括保存经过哈希的口令，这样就可以在不存储实际口令的情况下对其进行验证，或者尝试用字典来破解 Unix 口令。

@geindex crypt(3)

请注意，本模块的执行取决于当前系统中 @code{crypt(3)} 的实际实现。 因此，当前实现版本可用的扩展均可在本模块使用。

@ref{14c1,,可用性}: Unix。 在 VxWorks 上不可用。

@menu
* 哈希方法:: 
* 模块属性:: 
* 模块函数: 模块函数<2>. 
* 示例: 示例<49>. 

@end menu

@node 哈希方法,模块属性,,crypt —— 检查 Unix 口令的函数
@anchor{library/crypt hashing-methods}@anchor{3b84}
@subsubsection 哈希方法



3.3 新版功能.


@ref{28,,crypt} 模块定义了哈希方法的列表（不是所有的方法在所有平台上都可用）。

@geindex METHOD_SHA512() (在 crypt 模块中)
@anchor{library/crypt crypt METHOD_SHA512}@anchor{3b85}
@deffn {数据} crypt.METHOD_SHA512

基于 SHA-512 哈希函数的模块化加密格式方法，具备 16 个字符的 salt 和 86个字符的哈希算法。这是最强的哈希算法。
@end deffn

@geindex METHOD_SHA256() (在 crypt 模块中)
@anchor{library/crypt crypt METHOD_SHA256}@anchor{3b86}
@deffn {数据} crypt.METHOD_SHA256

另一种基于 SHA-256 哈希函数的模块化加密格式方法，具备 16 个字符的 salt 和 43 个字符的哈希算法。
@end deffn

@geindex METHOD_BLOWFISH() (在 crypt 模块中)
@anchor{library/crypt crypt METHOD_BLOWFISH}@anchor{3b87}
@deffn {数据} crypt.METHOD_BLOWFISH

另一种基于 Blowfish 的模块化加密格式方法，有 22 个字符的 salt 和 31 个字符的哈希算法。


3.7 新版功能.

@end deffn

@geindex METHOD_MD5() (在 crypt 模块中)
@anchor{library/crypt crypt METHOD_MD5}@anchor{3b88}
@deffn {数据} crypt.METHOD_MD5

另一种基于 MD5 哈希函数的模块化加密格式方法，具备 8 个字符的 salt 和 22 个字符的哈希算法。
@end deffn

@geindex METHOD_CRYPT() (在 crypt 模块中)
@anchor{library/crypt crypt METHOD_CRYPT}@anchor{70a}
@deffn {数据} crypt.METHOD_CRYPT

传统的方法，具备 2 个字符的 salt 和 13 个字符的哈希算法。这是最弱的方法。
@end deffn

@node 模块属性,模块函数<2>,哈希方法,crypt —— 检查 Unix 口令的函数
@anchor{library/crypt module-attributes}@anchor{3b89}
@subsubsection 模块属性



3.3 新版功能.


@geindex methods() (在 crypt 模块中)
@anchor{library/crypt crypt methods}@anchor{3b8a}
@deffn {属性} crypt.methods

可用口令哈希算法的列表，形式为 @code{crypt.METHOD_*} 对象。该列表从最强到最弱进行排序。
@end deffn

@node 模块函数<2>,示例<49>,模块属性,crypt —— 检查 Unix 口令的函数
@anchor{library/crypt module-functions}@anchor{3b8b}
@subsubsection 模块函数


@ref{28,,crypt} 模块定义了以下函数：

@geindex crypt() (在 crypt 模块中)
@anchor{library/crypt crypt crypt}@anchor{3b8c}
@deffn {函数} crypt.crypt (word, salt=None)

@emph{word} 通常将是用户在提示符或图形界面上输入的口令。 可选参数 @emph{salt} 要么是 @ref{48d,,mksalt()} 所返回的字符串，即 @code{crypt.METHOD_*} 值之一（尽管不是在所有平台上都可用），要么就是一个包括 salt 的完全加密的口令，与本函数的返回值一样。 如果未给出 @emph{salt}，则将使用 @ref{3b8a,,methods} 中提供的最强方法。

查验口令通常是传入纯文本密码 @emph{word} ，和之前 @ref{28,,crypt()} 调用的结果进行比较，应该与本次调用的结果相同。

@emph{salt} (随机的 2 或 16 个字符的字符串，可能带有 @code{$digit@{TX-PL-LABEL@}#x60;} 前缀以提示相关方法) 将被用来扰乱加密算法。  @emph{salt} 中的字符必须在 @code{[./a-zA-Z0-9]} 集合中，但 Modular Crypt Format 除外，它会带有 @code{$digit@{TX-PL-LABEL@}#x60;} 前缀。

返回哈希后的口令字符串，将由 salt 所在字母表中的字符组成。

@geindex crypt(3)

由于有些 @code{crypt(3)} 扩展允许不同的值， @emph{salt} 大小也可不同，建议在查验口令时采用完整的加密后口令作为 salt。


在 3.3 版更改: 除了字符串之外， @emph{salt} 还可接受 @code{crypt.METHOD_*} 值。

@end deffn

@geindex mksalt() (在 crypt 模块中)
@anchor{library/crypt crypt mksalt}@anchor{48d}
@deffn {函数} crypt.mksalt (method=None, *, rounds=None)

返回用指定方法随机生成的 salt 值。 如果没有给出 @emph{method}，则会使用 @ref{3b8a,,methods} 中提供的最强方法。is used.

返回一个字符串，可用作传入 @ref{28,,crypt()} 的 @emph{salt} 参数。

@emph{rounds} 指定了 @code{METHOD_SHA256}, @code{METHOD_SHA512} 和 @code{METHOD_BLOWFISH} 的循环次数。 对于 @code{METHOD_SHA256} 和 @code{METHOD_SHA512} 而言，必须为介于 @code{1000} 和 @code{999_999_999} 之间的整数，默认值为 @code{5000}。 而对于 @code{METHOD_BLOWFISH}，则必须为 @code{16} (2@w{^4}) 和 @code{2_147_483_648} (2@w{^31}) 之间的二的幂，默认值为 @code{4096} (2@w{^12})。


3.3 新版功能.



在 3.7 版更改: 加入  @emph{rounds} 参数。

@end deffn

@node 示例<49>,,模块函数<2>,crypt —— 检查 Unix 口令的函数
@anchor{library/crypt examples}@anchor{3b8d}
@subsubsection 示例


以下简单示例演示了典型用法（需要一个时间固定的比较操作来限制留给计时攻击的暴露面。 @ref{af3,,hmac.compare_digest()} 即很适用）：

@example
import pwd
import crypt
import getpass
from hmac import compare_digest as compare_hash

def login():
    username = input('Python login: ')
    cryptedpasswd = pwd.getpwnam(username)[1]
    if cryptedpasswd:
        if cryptedpasswd == 'x' or cryptedpasswd == '*':
            raise ValueError('no support for shadow passwords')
        cleartext = getpass.getpass()
        return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
    else:
        return True
@end example

采用当前强度最高的方法生成哈希值，并与原口令进行核对：

@example
import crypt
from hmac import compare_digest as compare_hash

hashed = crypt.crypt(plaintext)
if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
    raise ValueError("hashed version doesn't validate against original")
@end example

@node imghdr --- 推测图像类型,imp —— 由代码内部访问 import 。,crypt —— 检查 Unix 口令的函数,被取代的模块
@anchor{library/imghdr doc}@anchor{3b8e}@anchor{library/imghdr imghdr-determine-the-type-of-an-image}@anchor{3b8f}@anchor{library/imghdr module-imghdr}@anchor{98}
@subsection @code{imghdr} --- 推测图像类型


@geindex imghdr (模块)

@strong{源代码} Lib/imghdr.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/imghdr.py}


3.11 版后已移除: @ref{98,,imghdr} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#imghdr
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#imghdr} 了解详情及其替代品）。



__________________________________________________________________


@ref{98,,imghdr} 模块推测文件或字节流中的图像的类型。

@ref{98,,imghdr} 模块定义了以下类型：

@geindex what() (在 imghdr 模块中)
@anchor{library/imghdr imghdr what}@anchor{7e8}
@deffn {函数} imghdr.what (filename, h=None)

测试包含在命名为 @emph{filename} 的文件中的图像数据，并且返回描述此类图片的字符串。如果可选的 @emph{h} 被提供， @emph{filename} 将被忽略并且 @emph{h} 包含将被测试的二进制流。


在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

接下来的图像类型是可识别的，返回值来自 @ref{7e8,,what()}：


@multitable {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

图像格式

@item

@code{'rgb'}

@tab

SGI 图像库文件

@item

@code{'gif'}

@tab

GIF 87a 和 89a 文件

@item

@code{'pbm'}

@tab

便携式位图文件

@item

@code{'pgm'}

@tab

便携式灰度图文件

@item

@code{'ppm'}

@tab

便携式像素表文件

@item

@code{'tiff'}

@tab

TIFF 文件

@item

@code{'rast'}

@tab

Sun 光栅文件

@item

@code{'xbm'}

@tab

X 位图文件

@item

@code{'jpeg'}

@tab

JFIF 或 Exif 格式的 JPEG 数据

@item

@code{'bmp'}

@tab

BMP 文件

@item

@code{'png'}

@tab

便携式网络图像

@item

@code{'webp'}

@tab

WebP 文件

@item

@code{'exr'}

@tab

OpenEXR 文件

@end multitable



3.5 新版功能: @emph{exr} 和 @emph{webp} 格式被添加。


你可以扩展此 @ref{98,,imghdr} 可以被追加的这个变量识别的文件格式的列表：

@geindex tests() (在 imghdr 模块中)
@anchor{library/imghdr imghdr tests}@anchor{3b90}
@deffn {数据} imghdr.tests

执行单个测试的函数列表。每个函数都有两个参数：字节流和类似开放文件的对象。当 @ref{7e8,,what()} 用字节流调用时，类文件对象将是 @code{None}。

如果测试成功，这个测试函数应当返回一个描述图像类型的字符串，否则返回 @code{None}。
@end deffn

示例:

@example
>>> import imghdr
>>> imghdr.what('bass.gif')
'gif'
@end example

@node imp —— 由代码内部访问 import 。,mailcap --- Mailcap 文件处理,imghdr --- 推测图像类型,被取代的模块
@anchor{library/imp doc}@anchor{3b91}@anchor{library/imp imp-access-the-import-internals}@anchor{3b92}@anchor{library/imp module-imp}@anchor{99}
@subsection @code{imp} —— 由代码内部访问 import 。


@geindex imp (模块)

@strong{源代码：} Lib/imp.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/imp.py}


3.4 版后已移除: @ref{99,,imp} 模块已被废弃，请改用 @ref{9a,,importlib}。


@geindex 语句; import


__________________________________________________________________


本模块提供了一个接口，用于实现 @ref{cef,,import} 语句的机制。这里定义了以下常量和函数：

@geindex get_magic() (在 imp 模块中)
@anchor{library/imp imp get_magic}@anchor{957}
@deffn {函数} imp.get_magic ()

@geindex file; byte-code

返回用于识别字节编译代码文件 (@code{.pyc} files) 的魔术字符串值。 （该值对于各个 Python 版本可能不同。）


3.4 版后已移除: 改用 @ref{956,,importlib.util.MAGIC_NUMBER}。

@end deffn

@geindex get_suffixes() (在 imp 模块中)
@anchor{library/imp imp get_suffixes}@anchor{3b93}
@deffn {函数} imp.get_suffixes ()

返回一个 3 元素元组的列表，每个元组描述了一个特定的模块类型。 每个三元组的形式为 @code{(suffix, mode, type)}，其中 @emph{suffix} 是要附加到模块名称上以组成要搜索的文件名的字符串，@emph{mode} 是要传给内置 @ref{16f,,open()} 函数以打开该文件的模式字符串 (可以为针对文本文件的 @code{'r'} 或针对二进制文件的 @code{'rb'})，而 @emph{type} 是文件类型，它的值为 @ref{3b94,,PY_SOURCE}, @ref{3b95,,PY_COMPILED} 之一 @ref{3b96,,C_EXTENSION}，具体说明如下。


3.3 版后已移除: 改用在 @ref{9c,,importlib.machinery} 上定义的常量。

@end deffn

@geindex find_module() (在 imp 模块中)
@anchor{library/imp imp find_module}@anchor{3b97}
@deffn {函数} imp.find_module (name[, path])

尝试找到模块 @emph{name}。 如果 @emph{path} 被省略或为 @code{None}，则会搜索 @code{sys.path} 给出的目录名列表，但在此前会先搜索几个特殊位置：该函数将尝试找到具有给定名称的内置模块 (@ref{3b98,,C_BUILTIN})，然后是冻结模块 (@ref{3b99,,PY_FROZEN})，并且在某些系统上还会查找其他几个位置（在 Windows 上，它将查看注册表，其中可能指向某一特定文件）。

在其他情况下，@emph{path} 必须是一个目录名列表；将在每个目录中搜索具有上述 @ref{3b93,,get_suffixes()} 所返回的任何后缀的文件。 列表中的无效名称将被静默地忽略（但是所有列表条目都必须为字符串）。

如果搜索成功，返回值将是一个 3 元素元组 @code{(file, pathname, description)}:

@emph{file} 是一个放在最前面的已打开的 @ref{c1d,,file object}，@emph{pathname} 是打到的文件的路径名，而 @emph{description} 是一个描述所找到的模块种类的 3 元素元组，如 @ref{3b93,,get_suffixes()} 所返回的列表中包含的内容。

如果模块为内置或冻结模块则 @emph{file} 和 @emph{pathname} 都将为 @code{None} 并且 @emph{description} 元组将包含空字符串来表示其后缀和模式；模块类型按上述圆括号中所给出的内容来指明。 如果搜索未成功，则会引发 @ref{16c,,ImportError}。 其他异常被用于指示参数或环境问题。

如果模块是一个包，则 @emph{file} 将为 @code{None}，@emph{pathname} 将为包路径而 @emph{description} 元组的最后一项将为 @ref{3b9a,,PKG_DIRECTORY}。

此函数不会处理多层级的模块名称（包含点号的名称）。 为了找到 @emph{P.M}，也就是 @emph{P} 包的的子模块 @emph{M}，请使用 @ref{3b97,,find_module()} 和 @ref{3b9b,,load_module()} 来找到并载入 @emph{P} 包，然后使用 @ref{3b97,,find_module()} 并将 @emph{path} 参数设为 @code{P.__path__}。 当 @emph{P} 本身也具有带点号的名称时，请递归地应用此步骤。


3.3 版后已移除: 请改用 @ref{a25,,importlib.util.find_spec()} 除非需要兼容 Python 3.3，对于后一种情况请使用 @ref{a24,,importlib.find_loader()}。 要查看对于前一种情况的示例用法，请参阅 @ref{9a,,importlib} 文档的 @ref{3825,,示例} 小节。

@end deffn

@geindex load_module() (在 imp 模块中)
@anchor{library/imp imp load_module}@anchor{3b9b}
@deffn {函数} imp.load_module (name, file, pathname, description)

加载之前由 @ref{3b97,,find_module()} 所找到的模块（或由其他方式执行搜索所产生的兼容的结果）。 此函数所做的不只是导入模块：如果模块已经被导入，它将重新加载此模块！ @emph{name} 参数指明完整的模块名称（包括包名，如果它是一个包的子模块的话）。 @emph{file} 参数是一个打开的文件，而 @emph{pathname} 是相应的文件名；当模块是一个包或者不是从文档加载时，它们可以分别为 @code{None} 和 @code{'@w{'}}。 @emph{description} 参数是一个元组，如 @ref{3b93,,get_suffixes()} 将返回的内容一样，描述了必须加载什么样的模块。

如果加载成功，则返回值为相应的模块对象；否则，将引发一个异常 (通常为 @ref{16c,,ImportError})。

@strong{重要:} 调用方需负责关闭 @emph{file} 参数，如果它不为 @code{None} 的话，即使是在有异常被引发时。 这最好是使用 @ref{e3f,,try} ... @ref{2c3,,finally} 语句来实现。


3.3 版后已移除: 如果之前是与 @ref{3b97,,imp.find_module()} 一起使用则可考虑使用 @ref{bef,,importlib.import_module()}，在其他情况下请使用你选择的 @ref{3b97,,imp.find_module()} 替代品所返回的加载器。 如果你直接附带文件路径参数调用 @ref{3b9b,,imp.load_module()} 和相关函数则请使用 @ref{65c,,importlib.util.spec_from_file_location()} 和 @ref{7eb,,importlib.util.module_from_spec()} 的组合。 参见 @ref{9a,,importlib} 文档的 @ref{3825,,示例} 小节来了解各种方式的细节。

@end deffn

@geindex new_module() (在 imp 模块中)
@anchor{library/imp imp new_module}@anchor{3b9c}
@deffn {函数} imp.new_module (name)

返回一个新的名为 @emph{name} 的空模块对象。 此对象 @emph{不会} 被插入到 @code{sys.modules} 中。


3.4 版后已移除: 请改用 @ref{7eb,,importlib.util.module_from_spec()}。

@end deffn

@geindex reload() (在 imp 模块中)
@anchor{library/imp imp reload}@anchor{d40}
@deffn {函数} imp.reload (module)

重新加载之前导入的 @emph{module}。 该参数必须是一个模块对象，因此它之前必须已经被成功导入了。 这在当你已使用外部编辑器编辑过模块源代码文件并想在不退出 Python 解释器的情况下尝试新版本时会很有用处。 返回值为模块对象（与 @emph{module} 参数所指向的相同）。

当 @code{reload(module)} 被执行时:


@itemize *

@item 
Python 模块的代码会被重新编译并且模块层级的代码将重新执行，定义一个新的绑定到模块字典中的名称的对象集合。 扩展模块的 @code{init} 函数不会被重复调用。

@item 
与Python中的所有的其它对象一样，旧的对象只有在引用计数为0之后才会被回收。

@item 
模块命名空间中的名称重新指向任何新的或更改后的对象。

@item 
其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新。
@end itemize

有一些其他注意事项：

当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的缓存 —— 使用 @ref{e3f,,try} 语句，就可以测试表的存在并且跳过它的初始化，如果有需要的话:

@example
try:
    cache
except NameError:
    cache = @{@}
@end example

重新加载内置或动态加载的模块是合法操作但通常不是很有用处，除非是 @ref{fd,,sys}, @ref{1,,__main__} 和 @ref{12,,builtins}。 但是在许多情况下，扩展模块并不是被设计为可被多次初始化的，并可能在重新加载时以任意方式失败。

如果一个模块使用 @ref{d15,,from} ... @ref{cef,,import} ... 导入来自另一个模块的对象，则为另一个模块调用 @ref{d40,,reload()} 并不会重新定义从其中导入的对象 --- 绕过此问题的一种方式是重新执行 @code{from} 语句，另一种方式是使用 @code{import} 和限定名称 (@emph{module}.*name*) 来代替。

如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响这个实例的方法定义———它们继续使用旧类的定义。对于子类，也是一样的。


在 3.3 版更改: 依赖于 @code{__name__} 和 @code{__loader__} 而不仅是 @code{__name__} 同时定义在被重新加载的模块上。



3.4 版后已移除: 使用 @ref{4a8,,importlib.reload()} 来代替。

@end deffn

下列函数可以方便地处理 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 字节编译的文件路径。


3.2 新版功能.


@geindex cache_from_source() (在 imp 模块中)
@anchor{library/imp imp cache_from_source}@anchor{3b9d}
@deffn {函数} imp.cache_from_source (path, debug_override=None)

返回与源 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 定义的 @emph{path} 相关联的已编译字节码文件的路径。 举例来说，如果 @emph{path} 为 @code{/foo/bar/baz.py} 则 Python 3.2 中的返回值将是 @code{/foo/bar/__pycache__/baz.cpython-32.pyc}。 字符串 @code{cpython-32} 来自于当前的魔术标签 (参见 @ref{3b9e,,get_tag()}; 如果 @code{sys.implementation.cache_tag} 未定义则将引发 @ref{70e,,NotImplementedError})。 通过为 @emph{debug_override} 传入 @code{True} 或 @code{False} 你可以覆盖系统设置的 @code{__debug__} 值，以生成优化的字节码。

@emph{path} 不必存在。


在 3.3 版更改: 如果 @code{sys.implementation.cache_tag} 为 @code{None}，则会引发 @ref{70e,,NotImplementedError}。



3.4 版后已移除: 使用 @ref{65a,,importlib.util.cache_from_source()} 来代替。



在 3.5 版更改: @emph{debug_override} 形参不会再创建 @code{.pyo} 文件。

@end deffn

@geindex source_from_cache() (在 imp 模块中)
@anchor{library/imp imp source_from_cache}@anchor{3b9f}
@deffn {函数} imp.source_from_cache (path)

根据给定的 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 文件名的 @emph{path}，返回相关联的源代码文件路径。 举例来说，如果 @emph{path} 为 @code{/foo/bar/__pycache__/baz.cpython-32.pyc} 则返回的路径将是 @code{/foo/bar/baz.py}。 @emph{path} 不必已存在，但是如果它未遵循 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 格式，则会引发 @ref{16d,,ValueError}。 如果未定义 @code{sys.implementation.cache_tag}，则会引发 @ref{70e,,NotImplementedError}。


在 3.3 版更改: 当未定义 @code{sys.implementation.cache_tag} 时将引发 @ref{70e,,NotImplementedError}。



3.4 版后已移除: 使用 @ref{65b,,importlib.util.source_from_cache()} 来代替。

@end deffn

@geindex get_tag() (在 imp 模块中)
@anchor{library/imp imp get_tag}@anchor{3b9e}
@deffn {函数} imp.get_tag ()

返回与此 Python 版本魔数相匹配的 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 魔术标签字符串，如 @ref{957,,get_magic()} 所返回的。


3.4 版后已移除: 从 Python 3.3 开始直接使用 @code{sys.implementation.cache_tag}。

@end deffn

以下函数可以帮助与导入系统的内部锁定机制进行交互。 导入的锁定语义是一个可能在不同发布版之间发生改变的实现细节。 但是，Python 会确保循环导入操作不会出现任何死锁。

@geindex lock_held() (在 imp 模块中)
@anchor{library/imp imp lock_held}@anchor{3ba0}
@deffn {函数} imp.lock_held ()

如果当前持有全局导入锁则返回 @code{True}，否则返回 @code{False}。 在没有线程的系统平台上，将总是返回 @code{False}。

在有线程的平台上，执行导入的线程首先会持有一个全局导入锁，然后为导入其余部分设置模块专属锁。 这将阻止其他线程导入相同的模块直到原始导入完成，防止其他线程看到由原始线程构建的不完整的模块对象。 循环导入是个例外情况，它在构造上就必须在某一时刻暴露不完整的模块对象。


在 3.3 版更改: 锁定方案在大多数情况下都已改为按模块锁定。 对于某些关键任务会保留一个全局导入锁，比如初始化每个模块的锁。



3.4 版后已移除.

@end deffn

@geindex acquire_lock() (在 imp 模块中)
@anchor{library/imp imp acquire_lock}@anchor{3ba1}
@deffn {函数} imp.acquire_lock ()

为当前线程获取解释器的全局导入锁。 这个锁应当由导入钩子来使用以确保导入模块时的线程安全。

一旦某个线程获取了导入锁，同一个线程可以再次获取它而不会阻塞；该线程每次获得它都必须再释放它一次。

在没有线程的平台上，此函数将不做任何操作。


在 3.3 版更改: 锁定方案在大多数情况下都已改为按模块锁定。 对于某些关键任务会保留一个全局导入锁，比如初始化每个模块的锁。



3.4 版后已移除.

@end deffn

@geindex release_lock() (在 imp 模块中)
@anchor{library/imp imp release_lock}@anchor{3ba2}
@deffn {函数} imp.release_lock ()

释放解释器的全局导入锁。 在没有线程的平台上，此函数将不做任何操作。


在 3.3 版更改: 锁定方案在大多数情况下都已改为按模块锁定。 对于某些关键任务会保留一个全局导入锁，比如初始化每个模块的锁。



3.4 版后已移除.

@end deffn

以下是在本模块中定义的具有整数值的常量，用来表示 @ref{3b97,,find_module()} 的搜索结果。

@geindex PY_SOURCE() (在 imp 模块中)
@anchor{library/imp imp PY_SOURCE}@anchor{3b94}
@deffn {数据} imp.PY_SOURCE

模块作为一个源文件被发现。


3.3 版后已移除.

@end deffn

@geindex PY_COMPILED() (在 imp 模块中)
@anchor{library/imp imp PY_COMPILED}@anchor{3b95}
@deffn {数据} imp.PY_COMPILED

模块作为一个已编译代码对象文件被发现。


3.3 版后已移除.

@end deffn

@geindex C_EXTENSION() (在 imp 模块中)
@anchor{library/imp imp C_EXTENSION}@anchor{3b96}
@deffn {数据} imp.C_EXTENSION

模块作为动态可加载共享库被发现。


3.3 版后已移除.

@end deffn

@geindex PKG_DIRECTORY() (在 imp 模块中)
@anchor{library/imp imp PKG_DIRECTORY}@anchor{3b9a}
@deffn {数据} imp.PKG_DIRECTORY

模块作为一个包目录被发现。


3.3 版后已移除.

@end deffn

@geindex C_BUILTIN() (在 imp 模块中)
@anchor{library/imp imp C_BUILTIN}@anchor{3b98}
@deffn {数据} imp.C_BUILTIN

模块作为一个内置模块被发现。


3.3 版后已移除.

@end deffn

@geindex PY_FROZEN() (在 imp 模块中)
@anchor{library/imp imp PY_FROZEN}@anchor{3b99}
@deffn {数据} imp.PY_FROZEN

模块作为一个冻结模块被发现。


3.3 版后已移除.

@end deffn

@geindex NullImporter (imp 中的类)
@anchor{library/imp imp NullImporter}@anchor{aa4}
@deffn {类} imp.NullImporter (path_string)

@ref{aa4,,NullImporter} 类型是一个在无法找到任何模块时处理非目录路径字符串 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302} 导入钩子。 调用此类型时传入一个现有目录或空字符串将引发 @ref{16c,,ImportError}。 在其他情况下，将返回一个 @ref{aa4,,NullImporter} 实例。

这些实例只有一个方法:

@geindex find_module() (imp.NullImporter 方法)
@anchor{library/imp imp NullImporter find_module}@anchor{3ba3}
@deffn {方法} find_module (fullname[, path])

此方法总是返回 @code{None}，表示所请求的模块无法找到。
@end deffn


在 3.3 版更改: 将把 @code{None} 插入到 @code{sys.path_importer_cache} 而不是 @ref{aa4,,NullImporter} 的实例。



3.4 版后已移除: 改为将 @code{None} 插入到 @code{sys.path_importer_cache}。

@end deffn

@menu
* 示例: 示例<50>. 

@end menu

@node 示例<50>,,,imp —— 由代码内部访问 import 。
@anchor{library/imp examples}@anchor{3ba4}@anchor{library/imp examples-imp}@anchor{3ba5}
@subsubsection 示例


以下函数模拟了 Python 1.4 及之前版本的标准导入语句（没有多层级的模块名称）。 （这个 @emph{实现} 不可用于那些版本，因为 @ref{3b97,,find_module()} 已经被扩展而 @ref{3b9b,,load_module()} 在 1.4 中已被添加。）

@example
import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.

    fp, pathname, description = imp.find_module(name)

    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()
@end example

@node mailcap --- Mailcap 文件处理,msilib --- 读写 Microsoft Installer 文件,imp —— 由代码内部访问 import 。,被取代的模块
@anchor{library/mailcap doc}@anchor{3ba6}@anchor{library/mailcap mailcap-mailcap-file-handling}@anchor{3ba7}@anchor{library/mailcap module-mailcap}@anchor{af}
@subsection @code{mailcap} --- Mailcap 文件处理


@geindex mailcap (模块)

@strong{源代码:} Lib/mailcap.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/mailcap.py}


3.11 版后已移除: @ref{af,,mailcap} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#mailcap
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#mailcap} 了解详情）。 @ref{b2,,mimetypes} 模块提供了一个替代品。



__________________________________________________________________


Mailcap 文件可用来配置支持 MIME 的应用例如邮件阅读器和 Web 浏览器如何响应具有不同 MIME 类型的文件。 （"mailcap" 这个名称源自短语"mail capability"。） 例如，一个 mailcap 文件可能包含 @code{video/mpeg; xmpeg %s} 这样的行。 然后，如果用户遇到 MIME 类型为 @code{video/mpeg} 的邮件消息或 Web 文档时，@code{%s} 将被替换为一个文件名（通常是一个临时文件）并且将自动启动 @code{xmpeg} 程序来查看该文件。

mailcap 格式的文档见 
@geindex RFC; RFC 1524
RFC 1524@footnote{https://tools.ietf.org/html/rfc1524.html}, "A User Agent Configuration Mechanism For Multimedia Mail Format Information"，但它并不是一个因特网标准。 不过，mailcap 文件在大多数 Unix 系统上都受到支持。

@geindex findmatch() (在 mailcap 模块中)
@anchor{library/mailcap mailcap findmatch}@anchor{3ba8}
@deffn {函数} mailcap.findmatch (caps, MIMEtype, key='view', filename='/dev/null', plist=[])

返回一个 2 元组；其中第一个元素是包含所要执行命令的字符串 (它可被传递给 @ref{e8e,,os.system()})，第二个元素是对应于给定 MIME 类型的 mailcap 条目。 如果找不到匹配的 MIME 类型，则将返回 @code{(None, None)}。

@emph{key} 是所需字段的名称，它代表要执行的活动类型；默认值是 'view'，因为在最通常的情况下你只是想要查看 MIME 类型数据的正文。 其他可能的值还有 'compose' 和 'edit'，分别用于想要创建给定 MIME 类型正文或修改现有正文数据的情况。 请参阅 
@geindex RFC; RFC 1524
RFC 1524@footnote{https://tools.ietf.org/html/rfc1524.html} 获取这些字段的完整列表。

@emph{filename} 是在命令行中用来替换 @code{%s} 的文件名；默认值 @code{'/dev/null'} 几乎肯定不是你想要的，因此通常你要通过指定一个文件名来重载它。

@emph{plist} 可以是一个包含命名形参的列表；默认值只是一个空列表。 列表中的每个条目必须为包含形参名称的字符串、等于号 (@code{'='}) 以及形参的值。 Mailcap 条目可以包含形如 @code{%@{foo@}} 的命名形参，它将由名为 'foo' 的形参的值所替换。 例如，如果命令行 @code{showpartial %@{id@} %@{number@} %@{total@}} 是在一个 mailcap 文件中，并且 @emph{plist} 被设为 @code{['id=1', 'number=2', 'total=3']}，则结果命令行将为 @code{'showpartial 1 2 3'}。

在 mailcap 文件中，可以指定可选的 "test" 字段来检测某些外部条件（例如所使用的机器架构或窗口系统）来确定是否要应用 mailcap 行。 @ref{3ba8,,findmatch()} 将自动检查此类条件并在检查未通过时跳过条目。


在 3.9.16 版更改: To prevent security issues with shell metacharacters (symbols that have
special effects in a shell command line), @code{findmatch} will refuse
to inject ASCII characters other than alphanumerics and @code{@@+=:,./-_}
into the returned command line.

If a disallowed character appears in @emph{filename}, @code{findmatch} will always
return @code{(None, None)} as if no entry was found.
If such a character appears elsewhere (a value in @emph{plist} or in @emph{MIMEtype}),
@code{findmatch} will ignore all mailcap entries which use that value.
A @ref{12f,,warning} will be raised in either case.

@end deffn

@geindex getcaps() (在 mailcap 模块中)
@anchor{library/mailcap mailcap getcaps}@anchor{3ba9}
@deffn {函数} mailcap.getcaps ()

返回一个将 MIME 类型映射到 mailcap 文件条目列表的字典。 此字典必须被传给 @ref{3ba8,,findmatch()} 函数。 条目会被存储为字典列表，但并不需要了解此表示形式的细节。

此信息来自在系统中找到的所有 mailcap 文件。 用户的 mailcap 文件 @code{$HOME/.mailcap} 中的设置将覆盖系统 mailcap 文件 @code{/etc/mailcap}, @code{/usr/etc/mailcap} 和 @code{/usr/local/etc/mailcap} 中的设置。
@end deffn

一个用法示例:

@example
>>> import mailcap
>>> d = mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
('xmpeg tmp1223', @{'view': 'xmpeg %s'@})
@end example

@node msilib --- 读写 Microsoft Installer 文件,nis --- Sun 的 NIS 黄页 接口,mailcap --- Mailcap 文件处理,被取代的模块
@anchor{library/msilib doc}@anchor{3baa}@anchor{library/msilib module-msilib}@anchor{b5}@anchor{library/msilib msilib-read-and-write-microsoft-installer-files}@anchor{3bab}
@subsection @code{msilib} --- 读写 Microsoft Installer 文件


@geindex msilib (模块)

@strong{源代码:} Lib/msilib/__init__.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/msilib/__init__.py}

@geindex msi


3.11 版后已移除: @ref{b5,,msilib} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#msilib
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#msilib} 了解详情）。



__________________________________________________________________


@ref{b5,,msilib} 支持创建 Microsoft 安装器 (@code{.msi}) 文件。 由于这种文件往往包含一个嵌入的 "cabinet" 文件 (@code{.cab})，它也暴露了一个用于创建 CAB 文件的 API。  目前没有实现对读取 @code{.cab} 文件的支持；对于读取 @code{.msi} 数据库的支持则是可能的。

这个包的目标是提供对 @code{.msi} 文件中的全部表的完整访问，因此，它是一个相当低层级的 API。 这个包的两个主要应用是 @ref{38,,distutils} 命令 @code{bdist_msi}，以及创建 Python 安装程序包本身 (尽管它目前是使用不同版本的 @code{msilib})。

这个包的内容可以大致分为四个部分：低层级 CAB 例程、低层级 MSI 例程、高层级 MSI 例程以及标准表结构。

@geindex FCICreate() (在 msilib 模块中)
@anchor{library/msilib msilib FCICreate}@anchor{3bac}
@deffn {函数} msilib.FCICreate (cabname, files)

新建一个名为 @emph{cabname} 的 CAB 文件。 @emph{files} 必须是一个元组的列表，其中每个元组包含磁盘文件的名称，以及 CAB 文件内文件的名称。

这些文件将按照它们在列表中出现的顺序被添加到 CAB 文件中。 所有文件都会被添加到单个 CAB 文件，使用 MSZIP 压缩算法。

目前没有暴露 MSI 创建的各个步骤对 Python 的回调。
@end deffn

@geindex UuidCreate() (在 msilib 模块中)
@anchor{library/msilib msilib UuidCreate}@anchor{3bad}
@deffn {函数} msilib.UuidCreate ()

返回一个新的唯一标识符的字符串表示形式。 这封装了 Windows API 函数 @code{UuidCreate()} 和 @code{UuidToString()}。
@end deffn

@geindex OpenDatabase() (在 msilib 模块中)
@anchor{library/msilib msilib OpenDatabase}@anchor{106a}
@deffn {函数} msilib.OpenDatabase (path, persist)

通过调用 MsiOpenDatabase 来返回一个新的数据库对象。 @emph{path} 为 MSI 文件的名称；@emph{persist} 可以是常量 @code{MSIDBOPEN_CREATEDIRECT}, @code{MSIDBOPEN_CREATE}, @code{MSIDBOPEN_DIRECT}, @code{MSIDBOPEN_READONLY} 或 @code{MSIDBOPEN_TRANSACT} 中的一个，并可能包括旗标 @code{MSIDBOPEN_PATCHFILE}。 请参阅 Microsoft 文档了解这些旗标的含义；根据这些旗标，将打开一个现有数据库，或者创建一个新数据库。
@end deffn

@geindex CreateRecord() (在 msilib 模块中)
@anchor{library/msilib msilib CreateRecord}@anchor{3bae}
@deffn {函数} msilib.CreateRecord (count)

通过调用 @code{MSICreateRecord()} 来返回一个新的记录对象。 @emph{count} 为记录的字段数量。
@end deffn

@geindex init_database() (在 msilib 模块中)
@anchor{library/msilib msilib init_database}@anchor{106b}
@deffn {函数} msilib.init_database (name, schema, ProductName, ProductCode, ProductVersion, Manufacturer)

创建并返回一个新的数据库 @emph{name}，使用 @emph{schema} 来初始化它，并设置属性 @emph{ProductName}, @emph{ProductCode}, @emph{ProductVersion} 和 @emph{Manufacturer}。

@emph{schema} 必须是一个包含 @code{tables} 和 @code{_Validation_records} 属性的模块对象；在通常情况下，@ref{3baf,,msilib.schema} 应当被使用。

此此函数返回时该数据库将只包含方案和验证记录。
@end deffn

@geindex add_data() (在 msilib 模块中)
@anchor{library/msilib msilib add_data}@anchor{3bb0}
@deffn {函数} msilib.add_data (database, table, records)

将所有 @emph{records} 添加到 @emph{database} 中名为 @emph{table} 的表。

@emph{table} 参数必须为 MSI 方案中预定义的表之一，即 @code{'Feature'}, @code{'File'}, @code{'Component'}, @code{'Dialog'}, @code{'Control'} 等等。

@emph{records} 应当为一个元组的列表，其中的每个元组都包含与表结构对应的记录的所有字段。 对于可选字段，可以传入 @code{None}。

字段值可以为整数、字符串或 Binary 类的实例。
@end deffn

@geindex Binary (msilib 中的类)
@anchor{library/msilib msilib Binary}@anchor{3bb1}
@deffn {类} msilib.Binary (filename)

代表 Binary 表中的条目；使用 @ref{3bb0,,add_data()} 插入这样的对象会将名为 @emph{filename} 文件读入表中。
@end deffn

@geindex add_tables() (在 msilib 模块中)
@anchor{library/msilib msilib add_tables}@anchor{3bb2}
@deffn {函数} msilib.add_tables (database, module)

将来自 @emph{module} 的所有表内容添加到 @emph{database}。 @emph{module} 必须包括一个列出其内容需要被添加的所有表的属性 @emph{tables}，并且每个具有实际内容的表对应一个属性。

这通常被用来安装序列表。
@end deffn

@geindex add_stream() (在 msilib 模块中)
@anchor{library/msilib msilib add_stream}@anchor{3bb3}
@deffn {函数} msilib.add_stream (database, name, path)

将文件 @emph{path} 添加到 @emph{database} 的 @code{_Stream} 表，使用流名称 @emph{name}。
@end deffn

@geindex gen_uuid() (在 msilib 模块中)
@anchor{library/msilib msilib gen_uuid}@anchor{3bb4}
@deffn {函数} msilib.gen_uuid ()

Return a new UUID, in the format that MSI typically requires (i.e. in curly
braces, and with all hexdigits in upper-case).
@end deffn


@subsubheading 参见


FCICreate@footnote{https://msdn.microsoft.com/en-us/library/bb432265.aspx}
UuidCreate@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa379205.aspx}
UuidToString@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa379352.aspx}


@menu
* Database Objects:: 
* View Objects:: 
* Summary Information Objects:: 
* Record Objects:: 
* Errors:: 
* CAB Objects:: 
* Directory Objects:: 
* 相关特性: 相关特性<3>. 
* GUI classes:: 
* Precomputed tables:: 

@end menu

@node Database Objects,View Objects,,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib database-objects}@anchor{3bb5}@anchor{library/msilib id1}@anchor{3bb6}
@subsubsection Database Objects


@geindex OpenView() (msilib.Database 方法)
@anchor{library/msilib msilib Database OpenView}@anchor{106c}
@deffn {方法} Database.OpenView (sql)

Return a view object, by calling @code{MSIDatabaseOpenView()}. @emph{sql} is the SQL
statement to execute.
@end deffn

@geindex Commit() (msilib.Database 方法)
@anchor{library/msilib msilib Database Commit}@anchor{3bb7}
@deffn {方法} Database.Commit ()

Commit the changes pending in the current transaction, by calling
@code{MSIDatabaseCommit()}.
@end deffn

@geindex GetSummaryInformation() (msilib.Database 方法)
@anchor{library/msilib msilib Database GetSummaryInformation}@anchor{3bb8}
@deffn {方法} Database.GetSummaryInformation (count)

Return a new summary information object, by calling
@code{MsiGetSummaryInformation()}.  @emph{count} is the maximum number of updated
values.
@end deffn

@geindex Close() (msilib.Database 方法)
@anchor{library/msilib msilib Database Close}@anchor{4bd}
@deffn {方法} Database.Close ()

Close the database object, through @code{MsiCloseHandle()}.


3.7 新版功能.

@end deffn


@subsubheading 参见


MSIDatabaseOpenView@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370082.aspx}
MSIDatabaseCommit@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370075.aspx}
MSIGetSummaryInformation@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370301.aspx}
MsiCloseHandle@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370067.aspx}


@node View Objects,Summary Information Objects,Database Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib id2}@anchor{3bb9}@anchor{library/msilib view-objects}@anchor{3bba}
@subsubsection View Objects


@geindex Execute() (msilib.View 方法)
@anchor{library/msilib msilib View Execute}@anchor{3bbb}
@deffn {方法} View.Execute (params)

Execute the SQL query of the view, through @code{MSIViewExecute()}. If
@emph{params} is not @code{None}, it is a record describing actual values of the
parameter tokens in the query.
@end deffn

@geindex GetColumnInfo() (msilib.View 方法)
@anchor{library/msilib msilib View GetColumnInfo}@anchor{3bbc}
@deffn {方法} View.GetColumnInfo (kind)

Return a record describing the columns of the view, through calling
@code{MsiViewGetColumnInfo()}. @emph{kind} can be either @code{MSICOLINFO_NAMES} or
@code{MSICOLINFO_TYPES}.
@end deffn

@geindex Fetch() (msilib.View 方法)
@anchor{library/msilib msilib View Fetch}@anchor{3bbd}
@deffn {方法} View.Fetch ()

Return a result record of the query, through calling @code{MsiViewFetch()}.
@end deffn

@geindex Modify() (msilib.View 方法)
@anchor{library/msilib msilib View Modify}@anchor{3bbe}
@deffn {方法} View.Modify (kind, data)

Modify the view, by calling @code{MsiViewModify()}. @emph{kind} can be one of
@code{MSIMODIFY_SEEK}, @code{MSIMODIFY_REFRESH}, @code{MSIMODIFY_INSERT},
@code{MSIMODIFY_UPDATE}, @code{MSIMODIFY_ASSIGN}, @code{MSIMODIFY_REPLACE},
@code{MSIMODIFY_MERGE}, @code{MSIMODIFY_DELETE}, @code{MSIMODIFY_INSERT_TEMPORARY},
@code{MSIMODIFY_VALIDATE}, @code{MSIMODIFY_VALIDATE_NEW},
@code{MSIMODIFY_VALIDATE_FIELD}, or @code{MSIMODIFY_VALIDATE_DELETE}.

@emph{data} must be a record describing the new data.
@end deffn

@geindex Close() (msilib.View 方法)
@anchor{library/msilib msilib View Close}@anchor{3bbf}
@deffn {方法} View.Close ()

Close the view, through @code{MsiViewClose()}.
@end deffn


@subsubheading 参见


MsiViewExecute@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370513.aspx}
MSIViewGetColumnInfo@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370516.aspx}
MsiViewFetch@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370514.aspx}
MsiViewModify@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370519.aspx}
MsiViewClose@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370510.aspx}


@node Summary Information Objects,Record Objects,View Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib summary-information-objects}@anchor{3bc0}@anchor{library/msilib summary-objects}@anchor{3bc1}
@subsubsection Summary Information Objects


@geindex GetProperty() (msilib.SummaryInformation 方法)
@anchor{library/msilib msilib SummaryInformation GetProperty}@anchor{1147}
@deffn {方法} SummaryInformation.GetProperty (field)

Return a property of the summary, through @code{MsiSummaryInfoGetProperty()}.
@emph{field} is the name of the property, and can be one of the constants
@code{PID_CODEPAGE}, @code{PID_TITLE}, @code{PID_SUBJECT}, @code{PID_AUTHOR},
@code{PID_KEYWORDS}, @code{PID_COMMENTS}, @code{PID_TEMPLATE}, @code{PID_LASTAUTHOR},
@code{PID_REVNUMBER}, @code{PID_LASTPRINTED}, @code{PID_CREATE_DTM},
@code{PID_LASTSAVE_DTM}, @code{PID_PAGECOUNT}, @code{PID_WORDCOUNT}, @code{PID_CHARCOUNT},
@code{PID_APPNAME}, or @code{PID_SECURITY}.
@end deffn

@geindex GetPropertyCount() (msilib.SummaryInformation 方法)
@anchor{library/msilib msilib SummaryInformation GetPropertyCount}@anchor{3bc2}
@deffn {方法} SummaryInformation.GetPropertyCount ()

Return the number of summary properties, through
@code{MsiSummaryInfoGetPropertyCount()}.
@end deffn

@geindex SetProperty() (msilib.SummaryInformation 方法)
@anchor{library/msilib msilib SummaryInformation SetProperty}@anchor{3bc3}
@deffn {方法} SummaryInformation.SetProperty (field, value)

Set a property through @code{MsiSummaryInfoSetProperty()}. @emph{field} can have the
same values as in @ref{1147,,GetProperty()}, @emph{value} is the new value of the property.
Possible value types are integer and string.
@end deffn

@geindex Persist() (msilib.SummaryInformation 方法)
@anchor{library/msilib msilib SummaryInformation Persist}@anchor{3bc4}
@deffn {方法} SummaryInformation.Persist ()

Write the modified properties to the summary information stream, using
@code{MsiSummaryInfoPersist()}.
@end deffn


@subsubheading 参见


MsiSummaryInfoGetProperty@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370409.aspx}
MsiSummaryInfoGetPropertyCount@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370488.aspx}
MsiSummaryInfoSetProperty@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370491.aspx}
MsiSummaryInfoPersist@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370490.aspx}


@node Record Objects,Errors,Summary Information Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib id3}@anchor{3bc5}@anchor{library/msilib record-objects}@anchor{3bc6}
@subsubsection Record Objects


@geindex GetFieldCount() (msilib.Record 方法)
@anchor{library/msilib msilib Record GetFieldCount}@anchor{3bc7}
@deffn {方法} Record.GetFieldCount ()

Return the number of fields of the record, through
@code{MsiRecordGetFieldCount()}.
@end deffn

@geindex GetInteger() (msilib.Record 方法)
@anchor{library/msilib msilib Record GetInteger}@anchor{3bc8}
@deffn {方法} Record.GetInteger (field)

Return the value of @emph{field} as an integer where possible.  @emph{field} must
be an integer.
@end deffn

@geindex GetString() (msilib.Record 方法)
@anchor{library/msilib msilib Record GetString}@anchor{3bc9}
@deffn {方法} Record.GetString (field)

Return the value of @emph{field} as a string where possible.  @emph{field} must
be an integer.
@end deffn

@geindex SetString() (msilib.Record 方法)
@anchor{library/msilib msilib Record SetString}@anchor{3bca}
@deffn {方法} Record.SetString (field, value)

Set @emph{field} to @emph{value} through @code{MsiRecordSetString()}. @emph{field} must be an
integer; @emph{value} a string.
@end deffn

@geindex SetStream() (msilib.Record 方法)
@anchor{library/msilib msilib Record SetStream}@anchor{3bcb}
@deffn {方法} Record.SetStream (field, value)

Set @emph{field} to the contents of the file named @emph{value}, through
@code{MsiRecordSetStream()}. @emph{field} must be an integer; @emph{value} a string.
@end deffn

@geindex SetInteger() (msilib.Record 方法)
@anchor{library/msilib msilib Record SetInteger}@anchor{3bcc}
@deffn {方法} Record.SetInteger (field, value)

Set @emph{field} to @emph{value} through @code{MsiRecordSetInteger()}. Both @emph{field} and
@emph{value} must be an integer.
@end deffn

@geindex ClearData() (msilib.Record 方法)
@anchor{library/msilib msilib Record ClearData}@anchor{3bcd}
@deffn {方法} Record.ClearData ()

Set all fields of the record to 0, through @code{MsiRecordClearData()}.
@end deffn


@subsubheading 参见


MsiRecordGetFieldCount@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370366.aspx}
MsiRecordSetString@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370373.aspx}
MsiRecordSetStream@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370372.aspx}
MsiRecordSetInteger@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370371.aspx}
MsiRecordClearData@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370364.aspx}


@node Errors,CAB Objects,Record Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib errors}@anchor{3bce}@anchor{library/msilib msi-errors}@anchor{3bcf}
@subsubsection Errors


All wrappers around MSI functions raise @code{MSIError}; the string inside the
exception will contain more detail.

@node CAB Objects,Directory Objects,Errors,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib cab}@anchor{3bd0}@anchor{library/msilib cab-objects}@anchor{3bd1}
@subsubsection CAB Objects


@geindex CAB (msilib 中的类)
@anchor{library/msilib msilib CAB}@anchor{3bd2}
@deffn {类} msilib.CAB (name)

The class @ref{3bd2,,CAB} represents a CAB file. During MSI construction, files
will be added simultaneously to the @code{Files} table, and to a CAB file. Then,
when all files have been added, the CAB file can be written, then added to the
MSI file.

@emph{name} is the name of the CAB file in the MSI file.

@geindex append() (msilib.CAB 方法)
@anchor{library/msilib msilib CAB append}@anchor{3bd3}
@deffn {方法} append (full, file, logical)

Add the file with the pathname @emph{full} to the CAB file, under the name
@emph{logical}.  If there is already a file named @emph{logical}, a new file name is
created.

Return the index of the file in the CAB file, and the new name of the file
inside the CAB file.
@end deffn

@geindex commit() (msilib.CAB 方法)
@anchor{library/msilib msilib CAB commit}@anchor{3bd4}
@deffn {方法} commit (database)

Generate a CAB file, add it as a stream to the MSI file, put it into the
@code{Media} table, and remove the generated file from the disk.
@end deffn
@end deffn

@node Directory Objects,相关特性<3>,CAB Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib directory-objects}@anchor{3bd5}@anchor{library/msilib msi-directory}@anchor{3bd6}
@subsubsection Directory Objects


@geindex Directory (msilib 中的类)
@anchor{library/msilib msilib Directory}@anchor{3bd7}
@deffn {类} msilib.Directory (database, cab, basedir, physical, logical, default[, componentflags])

Create a new directory in the Directory table. There is a current component at
each point in time for the directory, which is either explicitly created through
@ref{1148,,start_component()}, or implicitly when files are added for the first time.
Files are added into the current component, and into the cab file.  To create a
directory, a base directory object needs to be specified (can be @code{None}), the
path to the physical directory, and a logical directory name.  @emph{default}
specifies the DefaultDir slot in the directory table. @emph{componentflags} specifies
the default flags that new components get.

@geindex start_component() (msilib.Directory 方法)
@anchor{library/msilib msilib Directory start_component}@anchor{1148}
@deffn {方法} start_component (component=None, feature=None, flags=None, keyfile=None, uuid=None)

Add an entry to the Component table, and make this component the current
component for this directory. If no component name is given, the directory
name is used. If no @emph{feature} is given, the current feature is used. If no
@emph{flags} are given, the directory's default flags are used. If no @emph{keyfile}
is given, the KeyPath is left null in the Component table.
@end deffn

@geindex add_file() (msilib.Directory 方法)
@anchor{library/msilib msilib Directory add_file}@anchor{3bd8}
@deffn {方法} add_file (file, src=None, version=None, language=None)

Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the @emph{src} file is specified, it
is interpreted relative to the current directory. Optionally, a @emph{version}
and a @emph{language} can be specified for the entry in the File table.
@end deffn

@geindex glob() (msilib.Directory 方法)
@anchor{library/msilib msilib Directory glob}@anchor{3bd9}
@deffn {方法} glob (pattern, exclude=None)

Add a list of files to the current component as specified in the glob
pattern.  Individual files can be excluded in the @emph{exclude} list.
@end deffn

@geindex remove_pyc() (msilib.Directory 方法)
@anchor{library/msilib msilib Directory remove_pyc}@anchor{3bda}
@deffn {方法} remove_pyc ()

Remove @code{.pyc} files on uninstall.
@end deffn
@end deffn


@subsubheading 参见


Directory Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368295.aspx}
File Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368596.aspx}
Component Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368007.aspx}
FeatureComponents Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368579.aspx}


@node 相关特性<3>,GUI classes,Directory Objects,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib features}@anchor{3bdb}@anchor{library/msilib id4}@anchor{3bdc}
@subsubsection 相关特性


@geindex Feature (msilib 中的类)
@anchor{library/msilib msilib Feature}@anchor{3bdd}
@deffn {类} msilib.Feature (db, id, title, desc, display, level=1, parent=None, directory=None, attributes=0)

Add a new record to the @code{Feature} table, using the values @emph{id}, @emph{parent.id},
@emph{title}, @emph{desc}, @emph{display}, @emph{level}, @emph{directory}, and @emph{attributes}. The
resulting feature object can be passed to the @code{start_component()} method of
@ref{3bd7,,Directory}.

@geindex set_current() (msilib.Feature 方法)
@anchor{library/msilib msilib Feature set_current}@anchor{3bde}
@deffn {方法} set_current ()

Make this feature the current feature of @ref{b5,,msilib}. New components are
automatically added to the default feature, unless a feature is explicitly
specified.
@end deffn
@end deffn


@subsubheading 参见


Feature Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368585.aspx}


@node GUI classes,Precomputed tables,相关特性<3>,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib gui-classes}@anchor{3bdf}@anchor{library/msilib msi-gui}@anchor{3be0}
@subsubsection GUI classes


@ref{b5,,msilib} provides several classes that wrap the GUI tables in an MSI
database. However, no standard user interface is provided; use
@ref{40,,bdist_msi} to create MSI files with a user-interface
for installing Python packages.

@geindex Control (msilib 中的类)
@anchor{library/msilib msilib Control}@anchor{3be1}
@deffn {类} msilib.Control (dlg, name)

Base class of the dialog controls. @emph{dlg} is the dialog object the control
belongs to, and @emph{name} is the control's name.

@geindex event() (msilib.Control 方法)
@anchor{library/msilib msilib Control event}@anchor{3be2}
@deffn {方法} event (event, argument, condition=1, ordering=None)

Make an entry into the @code{ControlEvent} table for this control.
@end deffn

@geindex mapping() (msilib.Control 方法)
@anchor{library/msilib msilib Control mapping}@anchor{3be3}
@deffn {方法} mapping (event, attribute)

Make an entry into the @code{EventMapping} table for this control.
@end deffn

@geindex condition() (msilib.Control 方法)
@anchor{library/msilib msilib Control condition}@anchor{3be4}
@deffn {方法} condition (action, condition)

Make an entry into the @code{ControlCondition} table for this control.
@end deffn
@end deffn

@geindex RadioButtonGroup (msilib 中的类)
@anchor{library/msilib msilib RadioButtonGroup}@anchor{3be5}
@deffn {类} msilib.RadioButtonGroup (dlg, name, property)

Create a radio button control named @emph{name}. @emph{property} is the installer property
that gets set when a radio button is selected.

@geindex add() (msilib.RadioButtonGroup 方法)
@anchor{library/msilib msilib RadioButtonGroup add}@anchor{3be6}
@deffn {方法} add (name, x, y, width, height, text, value=None)

Add a radio button named @emph{name} to the group, at the coordinates @emph{x}, @emph{y},
@emph{width}, @emph{height}, and with the label @emph{text}. If @emph{value} is @code{None}, it
defaults to @emph{name}.
@end deffn
@end deffn

@geindex Dialog (msilib 中的类)
@anchor{library/msilib msilib Dialog}@anchor{3be7}
@deffn {类} msilib.Dialog (db, name, x, y, w, h, attr, title, first, default, cancel)

Return a new @ref{3be7,,Dialog} object. An entry in the @code{Dialog} table is made,
with the specified coordinates, dialog attributes, title, name of the first,
default, and cancel controls.

@geindex control() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog control}@anchor{3be8}
@deffn {方法} control (name, type, x, y, width, height, attributes, property, text, control_next, help)

Return a new @ref{3be1,,Control} object. An entry in the @code{Control} table is
made with the specified parameters.

This is a generic method; for specific types, specialized methods are
provided.
@end deffn

@geindex text() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog text}@anchor{3be9}
@deffn {方法} text (name, x, y, width, height, attributes, text)

Add and return a @code{Text} control.
@end deffn

@geindex bitmap() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog bitmap}@anchor{3bea}
@deffn {方法} bitmap (name, x, y, width, height, text)

Add and return a @code{Bitmap} control.
@end deffn

@geindex line() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog line}@anchor{3beb}
@deffn {方法} line (name, x, y, width, height)

Add and return a @code{Line} control.
@end deffn

@geindex pushbutton() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog pushbutton}@anchor{3bec}
@deffn {方法} pushbutton (name, x, y, width, height, attributes, text, next_control)

Add and return a @code{PushButton} control.
@end deffn

@geindex radiogroup() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog radiogroup}@anchor{3bed}
@deffn {方法} radiogroup (name, x, y, width, height, attributes, property, text, next_control)

Add and return a @code{RadioButtonGroup} control.
@end deffn

@geindex checkbox() (msilib.Dialog 方法)
@anchor{library/msilib msilib Dialog checkbox}@anchor{3bee}
@deffn {方法} checkbox (name, x, y, width, height, attributes, property, text, next_control)

Add and return a @code{CheckBox} control.
@end deffn
@end deffn


@subsubheading 参见


Dialog Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368286.aspx}
Control Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368044.aspx}
Control Types@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368039.aspx}
ControlCondition Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368035.aspx}
ControlEvent Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368037.aspx}
EventMapping Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa368559.aspx}
RadioButton Table@footnote{https://msdn.microsoft.com/en-us/library/windows/desktop/aa370962.aspx}


@node Precomputed tables,,GUI classes,msilib --- 读写 Microsoft Installer 文件
@anchor{library/msilib msi-tables}@anchor{3bef}@anchor{library/msilib precomputed-tables}@anchor{3bf0}
@subsubsection Precomputed tables


@ref{b5,,msilib} provides a few subpackages that contain only schema and table
definitions. Currently, these definitions are based on MSI version 2.0.

@geindex schema() (在 msilib 模块中)
@anchor{library/msilib msilib schema}@anchor{3baf}
@deffn {数据} msilib.schema

This is the standard MSI schema for MSI 2.0, with the @emph{tables} variable
providing a list of table definitions, and @emph{_Validation_records} providing the
data for MSI validation.
@end deffn

@geindex sequence() (在 msilib 模块中)
@anchor{library/msilib msilib sequence}@anchor{3bf1}
@deffn {数据} msilib.sequence

此模块包含针对标准序列表的表内容: @emph{AdminExecuteSequence}, @emph{AdminUISequence}, @emph{AdvtExecuteSequence}, @emph{InstallExecuteSequence} 和 @emph{InstallUISequence}。
@end deffn

@geindex text() (在 msilib 模块中)
@anchor{library/msilib msilib text}@anchor{3bf2}
@deffn {数据} msilib.text

此模块包含 UIText 和 ActionText 表的定义，用于标准安装器动作。
@end deffn

@node nis --- Sun 的 NIS 黄页 接口,nntplib --- NNTP 协议客户端,msilib --- 读写 Microsoft Installer 文件,被取代的模块
@anchor{library/nis doc}@anchor{3bf3}@anchor{library/nis module-nis}@anchor{bf}@anchor{library/nis nis-interface-to-sun-s-nis-yellow-pages}@anchor{3bf4}
@subsection @code{nis} --- Sun 的 NIS (黄页) 接口


@geindex nis (模块)


3.11 版后已移除: @ref{bf,,nis} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#nis
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#nis} 了解详情）。



__________________________________________________________________


@ref{bf,,nis} 模块提供了对 NIS 库的轻量级包装，适用于多个主机的集中管理。

因为 NIS 仅存在于 Unix 系统，此模块仅在 Unix 上可用。

@ref{bf,,nis} 模块定义了以下函数：

@geindex match() (在 nis 模块中)
@anchor{library/nis nis match}@anchor{e5f}
@deffn {函数} nis.match (key, mapname, domain=default_domain)

返回 @emph{key} 在映射 @emph{mapname} 中的匹配结果，如无结果则会引发错误 (@ref{3bf5,,nis.error})。 两个参数都应为字符串，@emph{key} 定长 8 个比特。 返回值为任意字节数组（可包含 @code{NULL} 和其他特殊值）。

请注意如果 @emph{mapname} 是另一名称的别名则会先检查别名。

@emph{domain} 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认 NIS 域中查找。
@end deffn

@geindex cat() (在 nis 模块中)
@anchor{library/nis nis cat}@anchor{3bf6}
@deffn {函数} nis.cat (mapname, domain=default_domain)

返回一个字典，其元素为 @emph{key} 到 @emph{value} 的映射使得 @code{match(key, mapname)==value}。 请注意字典的键和值均为任意字节数组。

请注意如果 @emph{mapname} 是另一名称的别名则会先检查别名。

@emph{domain} 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认 NIS 域中查找。
@end deffn

@geindex maps() (在 nis 模块中)
@anchor{library/nis nis maps}@anchor{e60}
@deffn {函数} nis.maps (domain=default_domain)

返回全部可用映射的列表。

@emph{domain} 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认 NIS 域中查找。
@end deffn

@geindex get_default_domain() (在 nis 模块中)
@anchor{library/nis nis get_default_domain}@anchor{3bf7}
@deffn {函数} nis.get_default_domain ()

返回系统默认的 NIS 域。
@end deffn

@ref{bf,,nis} 模块定义了以下异常：

@geindex error
@anchor{library/nis nis error}@anchor{3bf5}
@deffn {例外} nis.error

当 NIS 函数返回一个错误码时引发的异常。
@end deffn

@node nntplib --- NNTP 协议客户端,optparse --- 解析器的命令行选项,nis --- Sun 的 NIS 黄页 接口,被取代的模块
@anchor{library/nntplib doc}@anchor{3bf8}@anchor{library/nntplib module-nntplib}@anchor{c0}@anchor{library/nntplib nntplib-nntp-protocol-client}@anchor{3bf9}
@subsection @code{nntplib} --- NNTP 协议客户端


@geindex nntplib (模块)

@strong{源代码:} Lib/nntplib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/nntplib.py}

@geindex NNTP; protocol
@geindex Network News Transfer Protocol


3.11 版后已移除: @ref{c0,,nntplib} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594} 了解详情）。



__________________________________________________________________


此模块定义了 @ref{1c7,,NNTP} 类来实现网络新闻传输协议的客户端。 它可被用于实现一个新闻阅读或发布器，或是新闻自动处理程序。 它兼容了 
@geindex RFC; RFC 3977
RFC 3977@footnote{https://tools.ietf.org/html/rfc3977.html} 以及较旧的 
@geindex RFC; RFC 977
RFC 977@footnote{https://tools.ietf.org/html/rfc977.html} 和 
@geindex RFC; RFC 2980
RFC 2980@footnote{https://tools.ietf.org/html/rfc2980.html}。

下面是此模块的两个简单用法示例。 列出某个新闻组的一些统计数据并打印最近 10 篇文章的主题:

@example
>>> s = nntplib.NNTP('news.gmane.io')
>>> resp, count, first, last, name = s.group('gmane.comp.python.committers')
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group gmane.comp.python.committers has 1096 articles, range 1 to 1096
>>> resp, overviews = s.over((last - 9, last))
>>> for id, over in overviews:
...     print(id, nntplib.decode_header(over['subject']))
...
1087 Re: Commit privileges for Łukasz Langa
1088 Re: 3.2 alpha 2 freeze
1089 Re: 3.2 alpha 2 freeze
1090 Re: Commit privileges for Łukasz Langa
1091 Re: Commit privileges for Łukasz Langa
1092 Updated ssh key
1093 Re: Updated ssh key
1094 Re: Updated ssh key
1095 Hello fellow committers!
1096 Re: Hello fellow committers!
>>> s.quit()
'205 Bye!'
@end example

要基于一个二进制文件发布文章 (假定文章包含有效的标头，并且你有在特定新闻组上发布内容的权限):

@example
>>> s = nntplib.NNTP('news.gmane.io')
>>> f = open('article.txt', 'rb')
>>> s.post(f)
'240 Article posted successfully.'
>>> s.quit()
'205 Bye!'
@end example

此模块本身定义了以下的类:

@geindex NNTP (nntplib 中的类)
@anchor{library/nntplib nntplib NNTP}@anchor{1c7}
@deffn {类} nntplib.NNTP (host, port=119, user=None, password=None, readermode=None, usenetrc=False[, timeout])

返回一个新的 @ref{1c7,,NNTP} 对象，代表一个对运行于主机 @emph{host}，在端口 @emph{port} 上监听的 NNTP 服务器的连接。 可以为套接字连接指定可选的 @emph{timeout}。 如果提供了可选的 @emph{user} 和 @emph{password}，或者如果在 @code{/.netrc} 中存在适合的凭证并且可选的旗标 @emph{usenetrc} 为真值，则会使用 @code{AUTHINFO USER} 和 @code{AUTHINFO PASS} 命令在服务器上标识和认证用户。 如果可选的旗标 @emph{readermode} 为真值，则会在执行认证之前发送 @code{mode reader} 命令。 在某些时候如果你是连接本地机器上的 NNTP 服务器并且想要调用读取者专属命令如 @code{group} 那么还必须使用读取者模式。 如果你收到预料之外的 @ref{3bfa,,NNTPPermanentError}，你可能需要设置 @emph{readermode}。 @ref{1c7,,NNTP} 类支持使用 @ref{7e4,,with} 语句来无条件地消费 @ref{30b,,OSError} 异常并在结束时关闭 NNTP 连接，例如:

@example
>>> from nntplib import NNTP
>>> with NNTP('news.gmane.io') as n:
...     n.group('gmane.comp.python.committers')
... 
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>
@end example

引发一个 @ref{fec,,审计事件} @code{nntplib.connect} 附带参数 @code{self}, @code{host}, @code{port}。

引发一个 @ref{fec,,审计事件} @code{nntplib.putline}，附带参数 @code{self}, @code{line}。


在 3.2 版更改: @emph{usenetrc} 现在默认为 @code{False}。



在 3.3 版更改: 支持了 @ref{7e4,,with} 语句。



在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。

@end deffn

@geindex NNTP_SSL (nntplib 中的类)
@anchor{library/nntplib nntplib NNTP_SSL}@anchor{1c8}
@deffn {类} nntplib.NNTP_SSL (host, port=563, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False[, timeout])

返回一个新的 @ref{1c8,,NNTP_SSL} 对象，代表一个对运行于主机 @emph{host}，在端口 @emph{port} 上监听的 NNTP 服务器的连接。 @ref{1c8,,NNTP_SSL} 对象具有与 @ref{1c7,,NNTP} 对象相同的方法。 如果 @emph{port} 被省略，则会使用端口 563 (NNTPS)。 @emph{ssl_context} 也是可选的，且为一个 @ref{4f2,,SSLContext} 对象。 请阅读 @ref{2711,,安全考量} 来了解最佳实践。 所有其他形参的行为都与 @ref{1c7,,NNTP} 的相同。

请注意 
@geindex RFC; RFC 4642
RFC 4642@footnote{https://tools.ietf.org/html/rfc4642.html} 不再推荐使用 563 端口的 SSL，建议改用下文描述的 STARTTLS。 但是，某些服务器只支持前者。

引发一个 @ref{fec,,审计事件} @code{nntplib.connect} 附带参数 @code{self}, @code{host}, @code{port}。

引发一个 @ref{fec,,审计事件} @code{nntplib.putline}，附带参数 @code{self}, @code{line}。


3.2 新版功能.



在 3.4 版更改: 本类现在支持通过 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称提示} （参阅 @ref{2839,,ssl.HAS_SNI}）进行主机名检查。



在 3.9 版更改: 如果 @emph{timeout} 参数设置为 0，创建非阻塞套接字时，它将引发 @ref{16d,,ValueError} 来阻止该操作。

@end deffn

@geindex NNTPError
@anchor{library/nntplib nntplib NNTPError}@anchor{3bfb}
@deffn {例外} nntplib.NNTPError

派生自标准异常 @ref{2e3,,Exception}，这是 @ref{c0,,nntplib} 模块中引发的所有异常的基类。 该类的实例具有以下属性:

@geindex response (nntplib.NNTPError 属性)
@anchor{library/nntplib nntplib NNTPError response}@anchor{3bfc}
@deffn {属性} response

可用的服务器响应，为一 @ref{206,,str} 对象。
@end deffn
@end deffn

@geindex NNTPReplyError
@anchor{library/nntplib nntplib NNTPReplyError}@anchor{3bfd}
@deffn {例外} nntplib.NNTPReplyError

从服务器收到意外答复时，将引发本异常。
@end deffn

@geindex NNTPTemporaryError
@anchor{library/nntplib nntplib NNTPTemporaryError}@anchor{3bfe}
@deffn {例外} nntplib.NNTPTemporaryError

收到 400--499 范围内的响应代码时所引发的异常。
@end deffn

@geindex NNTPPermanentError
@anchor{library/nntplib nntplib NNTPPermanentError}@anchor{3bfa}
@deffn {例外} nntplib.NNTPPermanentError

收到 500--599 范围内的响应代码时所引发的异常。
@end deffn

@geindex NNTPProtocolError
@anchor{library/nntplib nntplib NNTPProtocolError}@anchor{3bff}
@deffn {例外} nntplib.NNTPProtocolError

当从服务器收到不是以数字 1--5 开头的答复时所引发的异常。
@end deffn

@geindex NNTPDataError
@anchor{library/nntplib nntplib NNTPDataError}@anchor{3c00}
@deffn {例外} nntplib.NNTPDataError

当响应数据中存在错误时所引发的异常。
@end deffn

@menu
* NNTP 对象:: 
* 工具函数: 工具函数<2>. 

@end menu

@node NNTP 对象,工具函数<2>,,nntplib --- NNTP 协议客户端
@anchor{library/nntplib id1}@anchor{3c01}@anchor{library/nntplib nntp-objects}@anchor{3c02}
@subsubsection NNTP 对象


当连接时，@ref{1c7,,NNTP} 和 @ref{1c8,,NNTP_SSL} 对象支持以下方法和属性。

@menu
* 属性:: 
* 方法: 方法<3>. 

@end menu

@node 属性,方法<3>,,NNTP 对象
@anchor{library/nntplib attributes}@anchor{3c03}
@subsubsection 属性


@geindex nntp_version (nntplib.NNTP 属性)
@anchor{library/nntplib nntplib NNTP nntp_version}@anchor{3c04}
@deffn {属性} NNTP.nntp_version

代表服务器所支持的 NNTP 协议版本的整数。 在实践中，这对声明遵循 
@geindex RFC; RFC 3977
RFC 3977@footnote{https://tools.ietf.org/html/rfc3977.html} 的服务器应为 @code{2} 而对其他服务器则为 @code{1}。


3.2 新版功能.

@end deffn

@geindex nntp_implementation (nntplib.NNTP 属性)
@anchor{library/nntplib nntplib NNTP nntp_implementation}@anchor{3c05}
@deffn {属性} NNTP.nntp_implementation

描述 NNTP 服务器软件名称和版本的字符串，如果服务器未声明此信息则为 @ref{204,,None}。


3.2 新版功能.

@end deffn

@node 方法<3>,,属性,NNTP 对象
@anchor{library/nntplib methods}@anchor{3c06}
@subsubsection 方法


作为几乎全部方法所返回元组的第一项返回的 @emph{response} 是服务器的响应：以三位数字代码打头的字符串。 如果服务器的响应是提示错误，则方法将引发上述异常之一。

以下方法中许多都接受一个可选的仅限关键字参数 @emph{file}。 当提供了 @emph{file} 参数时，它必须为打开用于二进制写入的 @ref{c1d,,file object}，或要写入的磁盘文件名称。 此类方法随后将把服务器返回的任意数据（除了响应行和表示结束的点号）写入到文件中；此类方法通常返回的任何行列表、元组或对象都将为空值。


在 3.2 版更改: 以下方法中许多都已被重写和修正，这使得它们不再与 3.1 中的同名方法相兼容。


@geindex quit() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP quit}@anchor{3c07}
@deffn {方法} NNTP.quit ()

发送 @code{QUIT} 命令并关闭连接。 一旦此方法被调用，NNTP 对象的其他方法都不应再被调用。
@end deffn

@geindex getwelcome() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP getwelcome}@anchor{3c08}
@deffn {方法} NNTP.getwelcome ()

返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用户有关的免责声明或帮助信息。）
@end deffn

@geindex getcapabilities() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP getcapabilities}@anchor{3c09}
@deffn {方法} NNTP.getcapabilities ()

返回服务器所声明的 
@geindex RFC; RFC 3977
RFC 3977@footnote{https://tools.ietf.org/html/rfc3977.html} 功能，其形式为将功能名称映射到（可能为空的）值列表的 @ref{164,,dict} 实例。 在不能识别 @code{CAPABILITIES} 命令的旧式服务器上，会返回一个空字典。

@example
>>> s = NNTP('news.gmane.io')
>>> 'POST' in s.getcapabilities()
True
@end example


3.2 新版功能.

@end deffn

@geindex login() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP login}@anchor{3c0a}
@deffn {方法} NNTP.login (user=None, password=None, usenetrc=True)

发送 @code{AUTHINFO} 命令并附带用户名和密码。 如果 @emph{user} 和 @emph{password} 为 @code{None} 且 @emph{usenetrc} 为真值，则会在可能的情况下使用来自 @code{~/.netrc} 的凭证。

除非被有意延迟，登录操作通常会在 @ref{1c7,,NNTP} 对象初始化期间被执行因而没有必要单独调用此函数。 要强制延迟验证，你在创建该对象时不能设置 @emph{user} 或 @emph{password}，并必须将 @emph{usenetrc} 设为 False。


3.2 新版功能.

@end deffn

@geindex starttls() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP starttls}@anchor{c7e}
@deffn {方法} NNTP.starttls (context=None)

发送 @code{STARTTLS} 命令。 这将在 NNTP 连接上启用加密。 @emph{context} 参数是可选的且应为 @ref{4f2,,ssl.SSLContext} 对象。 请阅读 @ref{2711,,安全考量} 了解最佳实践。

请注意此操作可能不会在传输验证信息之后立即完成，只要有可能验证默认会在 @ref{1c7,,NNTP} 对象初始化期间发生。 请参阅 @ref{3c0a,,NNTP.login()} 了解有关如何屏蔽此行为的信息。


3.2 新版功能.



在 3.4 版更改: 此方法现在支持使用 @ref{2824,,ssl.SSLContext.check_hostname} 和 @emph{服务器名称指示} (参见 @ref{2839,,ssl.HAS_SNI}) 进行主机名检查。

@end deffn

@geindex newgroups() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP newgroups}@anchor{3c0b}
@deffn {方法} NNTP.newgroups (date, *, file=None)

发送 @code{NEWGROUPS} 命令。 @emph{date} 参数应为 @ref{19d,,datetime.date} 或 @ref{19f,,datetime.datetime} 对象。 返回一个 @code{(response, groups)} 对，其中 @emph{groups} 是代表给定i @emph{date} 以来所新建的分组。 但是如果提供了 @emph{file}，则 @emph{groups} 将为空值。

@example
>>> from datetime import date, timedelta
>>> resp, groups = s.newgroups(date.today() - timedelta(days=3))
>>> len(groups) 
85
>>> groups[0] 
GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m')
@end example
@end deffn

@geindex newnews() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP newnews}@anchor{3c0c}
@deffn {方法} NNTP.newnews (group, date, *, file=None)

发送 @code{NEWNEWS} 命令。 这里，@emph{group} 是新闻组名称或为 @code{'*'}，而 @emph{date} 与 @ref{3c0b,,newgroups()} 中的含义相同。 返回一个 @code{(response, articles)} 对，其中 @emph{articles} 为消息 ID 列表。

此命令经常会被 NNTP 服务器管理员禁用。
@end deffn

@geindex list() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP list}@anchor{3c0d}
@deffn {方法} NNTP.list (group_pattern=None, *, file=None)

发送 @code{LIST} 或 @code{LIST ACTIVE} 命令。 返回一个 @code{(response, list)} 对，其中 @emph{list} 是代表此 NNTP 服务器上所有可用新闻组的元组列表，并可选择匹配模式字符串 @emph{group_pattern}。 每个元组的形式为 @code{(group, last, first, flag)}，其中 @emph{group} 为新闻组名称，@emph{last} 和 @emph{first} 是最后一个和第一个文章的编号，而 @emph{flag} 通常为下列值之一:


@itemize *

@item 
@code{y}: 允许来自对等方的本地发帖和文章。

@item 
@code{m}: 新闻组受到管制因而所有发帖必须经过审核。

@item 
@code{n}: 不允许本地发帖，只允许来自组员的文章。

@item 
@code{j}: 来自组员的文章会被转入垃圾分组。

@item 
@code{x}: 不允许本地发帖，而来自组员的文章会被忽略。

@item 
@code{=foo.bar}: 文章会被转入 @code{foo.bar} 分组。
@end itemize

如果 @emph{flag} 具有其他值，则新闻组的状态应当被视为未知。

此命令可能返回非常庞大的结果，特别是当未指明 @emph{group_pattern} 的时候。 最好是离线缓存其结果，除非你确实需要刷新它们。


在 3.2 版更改: 增加了 @emph{group_pattern}。

@end deffn

@geindex descriptions() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP descriptions}@anchor{215}
@deffn {方法} NNTP.descriptions (grouppattern)

发送 @code{LIST NEWSGROUPS} 命令，其中 @emph{grouppattern} 为 
@geindex RFC; RFC 3977
RFC 3977@footnote{https://tools.ietf.org/html/rfc3977.html} 中规定的 wildmat 字符串（它实际上与 DOS 或 UNIX shell 通配字符串相同）。 返回一个 @code{(response, descriptions)} 对，其中 @emph{descriptions} 是将新闻组名称映射到文本描述的字典。

@example
>>> resp, descs = s.descriptions('gmane.comp.python.*')
>>> len(descs) 
295
>>> descs.popitem() 
('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')
@end example
@end deffn

@geindex description() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP description}@anchor{216}
@deffn {方法} NNTP.description (group)

获取单个新闻组 @emph{group} 的描述。 如果匹配到一个以上的新闻组（如果 'group' 是一个真实的 wildmat 字符串），则返回第一个匹配结果。 如果未匹配到任何新闻组，则返回空字符串。

此方法略去了来自服务器的响应代码。 如果需要响应代码，请使用 @ref{215,,descriptions()}。
@end deffn

@geindex group() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP group}@anchor{3c0e}
@deffn {方法} NNTP.group (name)

发送 @code{GROUP} 命令，其中 @emph{name} 为新闻组名称。 该新闻组如果存在，则会被选定为当前新闻组。 返回一个元组 @code{(response, count, first, last, name)}，其中 @emph{count} 是该新闻组中（估计的）文章数量，@emph{first} 是新闻组中第一篇文章的编号，@emph{last} 是新闻组中最后一篇文章的编号，而 @emph{name} 是新闻组名称。
@end deffn

@geindex over() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP over}@anchor{3c0f}
@deffn {方法} NNTP.over (message_spec, *, file=None)

发送 @code{OVER} 命令，或是旧式服务器上的 @code{XOVER} 命令。 @emph{message_spec} 可以是表示消息 ID 的字符串，或是指明当前新闻组内文章范围的数字元组 @code{(first, last)}，或是指明当前新闻组内从 @code{(first, None)} @emph{first} 到最后一篇文章的元组，或者为 @ref{204,,None} 表示选定当前新闻组内的当前文章。

返回一个 @code{(response, overviews)} 对。 其中 @emph{overviews} 是一个包含 @code{(article_number, overview)} 元组的列表，每个元组对应 @emph{message_spec} 所选定的一篇文章。 每个 @emph{overview} 则是包含同样数量条目的字典，但具体数量取决于服务器。 这些条目或是为消息标头（对应键为小写的标头名称）或是为 metadata 项（对应键为以 @code{":"} 打头的 metadata 名称）。 以下条目会由 NNTP 规范描述来确保提供:


@itemize *

@item 
@code{subject}, @code{from}, @code{date}, @code{message-id} 和 @code{references} 标头

@item 
@code{:bytes} metadata: 整个原始文章数据的字节数（包括标头和消息体）

@item 
@code{:lines} metadata: 文章消息体的行数
@end itemize

每个条目的值或者为字符串，或者在没有值时为 @ref{204,,None}。

建议在标头值可能包含非 ASCII 字符的时候对其使用 @ref{3c10,,decode_header()} 函数:

@example
>>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
>>> resp, overviews = s.over((last, last))
>>> art_num, over = overviews[0]
>>> art_num
117216
>>> list(over.keys())
['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']
>>> over['from']
'=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= <martin@@v.loewis.de>'
>>> nntplib.decode_header(over['from'])
'"Martin v. Löwis" <martin@@v.loewis.de>'
@end example


3.2 新版功能.

@end deffn

@geindex help() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP help}@anchor{3c11}
@deffn {方法} NNTP.help (*, file=None)

发送 @code{HELP} 命令。 返回一个 @code{(response, list)} 对，其中 @emph{list} 为帮助字符串列表。
@end deffn

@geindex stat() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP stat}@anchor{3c12}
@deffn {方法} NNTP.stat (message_spec=None)

发送 @code{STAT} 命令，其中 @emph{message_spec} 为消息 ID (包裹在 @code{'<'} 和 @code{'>'} 中) 或者当前新闻组中的文章编号。 如果 @emph{message_spec} 被省略或为 @ref{204,,None}，则会选择当前新闻组中的当前文章。 反回一个三元组 @code{(response, number, id)}，其中 @emph{number} 为文章编号而 @emph{id} 为消息 ID。

@example
>>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
>>> resp, number, message_id = s.stat(first)
>>> number, message_id
(9099, '<20030112190404.GE29873@@epoch.metaslash.com>')
@end example
@end deffn

@geindex next() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP next}@anchor{3c13}
@deffn {方法} NNTP.next ()

发送 @code{NEXT} 命令。 返回与 @ref{3c12,,stat()} 类似的结果。
@end deffn

@geindex last() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP last}@anchor{3c14}
@deffn {方法} NNTP.last ()

发送 @code{LAST} 命令。 返回与 @ref{3c12,,stat()} 类似的结果。
@end deffn

@geindex article() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP article}@anchor{3c15}
@deffn {方法} NNTP.article (message_spec=None, *, file=None)

发送 @code{ARTICLE} 命令，其中 @emph{message_spec} 的含义与 @ref{3c12,,stat()} 中的相同。 返回一个元组 @code{(response, info)}，其中 @emph{info} 是一个 @ref{1a1,,namedtuple}，包含三个属性 @emph{number}, @emph{message_id} 和 @emph{lines} (按此顺序)。 @emph{number} 是新闻组中的文章数量 (或者如果该信息不可用则为 0)，@emph{message_id} 为字符串形式的消息 ID，而 @emph{lines} 为由包括标头和消息体的原始消息的行组成的列表 (不带末尾换行符)。

@example
>>> resp, info = s.article('<20030112190404.GE29873@@epoch.metaslash.com>')
>>> info.number
0
>>> info.message_id
'<20030112190404.GE29873@@epoch.metaslash.com>'
>>> len(info.lines)
65
>>> info.lines[0]
b'Path: main.gmane.org!not-for-mail'
>>> info.lines[1]
b'From: Neal Norwitz <neal@@metaslash.com>'
>>> info.lines[-3:]
[b'There is a patch for 2.3 as well as 2.2.', b'@w{'}, b'Neal']
@end example
@end deffn

@geindex head() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP head}@anchor{3c16}
@deffn {方法} NNTP.head (message_spec=None, *, file=None)

与 @ref{3c15,,article()} 类似，但会发送 @code{HEAD} 命令。 返回的 @emph{lines} (或写入到 @emph{file}) 将只包含消息标头，不包含消息体。
@end deffn

@geindex body() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP body}@anchor{3c17}
@deffn {方法} NNTP.body (message_spec=None, *, file=None)

与 @ref{3c15,,article()} 类似，但会发送 @code{BODY} 命令。 返回的 @emph{lines} (或写入到 @emph{file}) 将只包含消息体，不包含标头。
@end deffn

@geindex post() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP post}@anchor{3c18}
@deffn {方法} NNTP.post (data)

使用 @code{POST} 命令发布文章。 @emph{data} 参数是以二进制读取模式打开的 @ref{c1d,,file object}，或是任意包含字节串对象的可迭代对象 (表示要发布的文章的原始行数据)。 它应当代表一篇适当格式的新闻组文章，包含所需的标头。 @ref{3c18,,post()} 方法会自动对以 @code{.} 打头的行数据进行转义并添加结束行。

如果此方法执行成功，将返回服务器的响应。 如果服务器拒绝响应，则会引发 @ref{3bfd,,NNTPReplyError}。
@end deffn

@geindex ihave() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP ihave}@anchor{3c19}
@deffn {方法} NNTP.ihave (message_id, data)

发送 @code{IHAVE} 命令。 @emph{message_id} 为要发给服务器的消息 ID (包裹在 @code{'<'} 和 @code{'>'} 中)。 @emph{data} 形参和返回值与 @ref{3c18,,post()} 的一致。
@end deffn

@geindex date() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP date}@anchor{3c1a}
@deffn {方法} NNTP.date ()

返回一个 @code{(response, date)} 对。 @emph{date} 是包含服务器当前日期与时间的 @ref{19f,,datetime} 对象。
@end deffn

@geindex slave() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP slave}@anchor{3c1b}
@deffn {方法} NNTP.slave ()

发送 @code{SLAVE} 命令。 返回服务器的 @emph{响应}。
@end deffn

@geindex set_debuglevel() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP set_debuglevel}@anchor{3c1c}
@deffn {方法} NNTP.set_debuglevel (level)

设置实例的调试级别。 它控制着打印调试输出信息的数量。 默认值 @code{0} 不产生调试输出。 值 @code{1} 产生中等数量的调试输出，通常每个请求或响应各产生一行。 大于等于 @code{2} 的值产生最多的调试输出，在连接上发送和接收的每一行信息都会被记录下来（包括消息文本）。
@end deffn

以下是在 
@geindex RFC; RFC 2980
RFC 2980@footnote{https://tools.ietf.org/html/rfc2980.html} 中定义的可选 NNTP 扩展。 其中一些已被 
@geindex RFC; RFC 3977
RFC 3977@footnote{https://tools.ietf.org/html/rfc3977.html} 中的新命令所取代。

@geindex xhdr() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP xhdr}@anchor{3c1d}
@deffn {方法} NNTP.xhdr (hdr, str, *, file=None)

发送 @code{XHDR} 命令。 @emph{hdr} 参数是标头关键字，例如 @code{'subject'}。 @emph{str} 参数的形式应为 @code{'first-last'}，其中 @emph{first} 和 @emph{last} 是要搜索的首篇和末篇文章编号。 返回一个 @code{(response, list)} 对，其中 @emph{list} 是 @code{(id, text)} 对的列表，其中 @emph{id} 是文章编号（字符串类型）而 @emph{text} 是该文章的请求标头。 如果提供了 @emph{file} 形参，则 @code{XHDR} 命令的输出会保存到文件中。 如果 @emph{file} 为字符串，则此方法将打开指定名称的文件，向其写入内容并将其关闭。 如果 @emph{file} 为 @ref{c1d,,file object}，则将在该文件对象上调用 @code{write()} 方法来保存命令所输出的行信息。 如果提供了 @emph{file}，则返回的 @emph{list} 将为空列表。
@end deffn

@geindex xover() (nntplib.NNTP 方法)
@anchor{library/nntplib nntplib NNTP xover}@anchor{3c1e}
@deffn {方法} NNTP.xover (start, end, *, file=None)

发送 @code{XOVER} 命令。 @emph{start} 和 @emph{end} 是限制所选取文章范围的文章编号。 返回值与 @ref{3c0f,,over()} 的相同。 推荐改用 @ref{3c0f,,over()}，因为它将在可能的情况下自动使用更新的 @code{OVER} 命令。
@end deffn

@node 工具函数<2>,,NNTP 对象,nntplib --- NNTP 协议客户端
@anchor{library/nntplib utility-functions}@anchor{3c1f}
@subsubsection 工具函数


这个模块还定义了下列工具函数:

@geindex decode_header() (在 nntplib 模块中)
@anchor{library/nntplib nntplib decode_header}@anchor{3c10}
@deffn {函数} nntplib.decode_header (header_str)

解码标头值，恢复任何被转义的非 ASCII 字符。 @emph{header_str} 必须为 @ref{206,,str} 对象。 将返回被恢复的值。 推荐使用此函数来以人类可读的形式显示某些标头:

@example
>>> decode_header("Some subject")
'Some subject'
>>> decode_header("=?ISO-8859-15?Q?D=E9buter_en_Python?=")
'Débuter en Python'
>>> decode_header("Re: =?UTF-8?B?cHJvYmzDqG1lIGRlIG1hdHJpY2U=?=")
'Re: problème de matrice'
@end example
@end deffn

@node optparse --- 解析器的命令行选项,ossaudiodev --- 访问兼容OSS的音频设备,nntplib --- NNTP 协议客户端,被取代的模块
@anchor{library/optparse doc}@anchor{3c20}@anchor{library/optparse module-optparse}@anchor{c3}@anchor{library/optparse optparse-parser-for-command-line-options}@anchor{3c21}
@subsection @code{optparse} --- 解析器的命令行选项


@geindex optparse (模块)

@strong{源代码：} Lib/optparse.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/optparse.py}


3.2 版后已移除: @ref{c3,,optparse} 模块已被弃用并且将不再继续开发；开发将转至 @ref{5,,argparse} 模块进行。



__________________________________________________________________


@ref{c3,,optparse} 是一个相比原有 @ref{85,,getopt} 模块更为方便、灵活和强大的命令行选项解析库。 @ref{c3,,optparse} 使用更为显明的命令行解析风格：创建一个 @ref{3c22,,OptionParser} 的实例，向其中填充选项，然后解析命令行。 @ref{c3,,optparse} 允许用户以传统的 GNU/POSIX 语法来指定选项，并为你生成额外的用法和帮助消息。

下面是在一个简单脚本中使用 @ref{c3,,optparse} 的示例:

@example
from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()
@end example

通过这几行代码，你的脚本的用户可以在命令行上完成“常见任务”，例如:

@example
<yourscript> --file=outfile -q
@end example

在它解析命令行时，@ref{c3,,optparse} 会根据用户提供的命令行值设置 @code{parse_args()} 所返回的 @code{options} 对象的属性。 当 @code{parse_args()} 从解析此命令行返回时，@code{options.filename} 将为 @code{"outfile"} 而 @code{options.verbose} 将为 @code{False}。 @ref{c3,,optparse} 支持长短两种形式的选项，允许多个短选项合并到一起，并允许选项以多种方式与其参数相关联。 因此，以下命令行均等价于以上示例:

@example
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile
@end example

此外，用户还可以运行以下命令之一

@example
<yourscript> -h
<yourscript> --help
@end example

这样 @ref{c3,,optparse} 将打印出你的脚本的选项概要:

@example
Usage: <yourscript> [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout
@end example

其中 @emph{yourscript} 的值是在运行时确定的 (通常来自 @code{sys.argv[0]})。

@menu
* 背景:: 
* 教程: 教程<2>. 
* 参考指南:: 
* Option Callbacks:: 
* Extending optparse:: 

@end menu

@node 背景,教程<2>,,optparse --- 解析器的命令行选项
@anchor{library/optparse background}@anchor{3c23}@anchor{library/optparse optparse-background}@anchor{3c24}
@subsubsection 背景


@ref{c3,,optparse} 被显式设计为鼓励创建带有简洁直观、符合惯例的命令行接口的程序。 为了这个目标，它仅支持最常见的命令行语法和在 Unix 下使用的规范语义。 如果你不熟悉这些惯例，请阅读本小节来使自己熟悉它们。

@menu
* 术语:: 
* What are options for?:: 
* 位置位置:: 

@end menu

@node 术语,What are options for?,,背景
@anchor{library/optparse optparse-terminology}@anchor{3c25}@anchor{library/optparse terminology}@anchor{3c26}
@subsubsection 术语



@table @asis

@item 参数

在命令行中输入的字符串，并会被 shell 传给 @code{execl()} 或 @code{execv()}。 在 Python 中，参数将是 @code{sys.argv[1:]} 的元素 (@code{sys.argv[0]} 是被执行的程序的名称)。 Unix shell 也使用术语 "word" 来指代参数。

有时替换 @code{sys.argv[1:]} 以外的参数列表也是必要的，所以你应当将 "参数" 当作是 "@code{sys.argv[1:]} 的一个元素，或者是作为 @code{sys.argv[1:]} 的替代的其他列表"。

@item 选项

一个用来提供额外信息以指导或定制程序的执行的参数。 对于选项有许多不同的语法；传统的 Unix 语法是一个连字符 ("-") 后面跟单个字母，例如 @code{-x} 或 @code{-F}。 此外，传统的 Unix 语法允许将多个选项合并为一个参数，例如 @code{-x -F} 就等价于 @code{-xF}。 GNU 项目引入了 @code{--} 后面跟一串以连字符分隔的单词，例如 @code{--file} 或 @code{--dry-run}。 它们是These are the only two option syntaxes provided by @ref{c3,,optparse} 所提供的仅有的两种选项语法。

存在于世上的其他一些选项语法包括:


@itemize *

@item 
一个连字符后面跟几个字母，例如 @code{-pf} (这与多个选项合并成单个参数 @emph{并不} 一样)

@item 
一个连字符后面跟一个完整单词，例如 @code{-file} (这在技术上等同于前面的语法，但它们通常不在同一个程序中出现)

@item 
一个加号后面跟一个字母，或几个字母，或一个单词，例如 @code{+f}, @code{+rgb}

@item 
一个斜杠后面跟一个字母，或几个字母，或一个单词，例如 @code{/f}, @code{/file}
@end itemize

这些选项语法都不被 @ref{c3,,optparse} 所支持，也永远不会支持。 这是有意为之的：前三种在任何环境下都是非标准的，而最后一种只在你专门针对 Windows 或某些旧平台（例如 VMS, MS-DOS）时才有意义。

@item 可选参数:

一个跟在某个选项之后的参数，与该选项紧密相关，并会在该选项被消耗时从参数列表中被消耗。 使用 @ref{c3,,optparse}，选项参数可以是其对应选项以外的一个单独参数:

@example
-f foo
--file foo
@end example

或是包括在同一个参数中:

@example
-ffoo
--file=foo
@end example

Typically, a given option either takes an argument or it doesn't. Lots of
people want an "optional option arguments" feature, meaning that some options
will take an argument if they see it, and won't if they don't.  This is
somewhat controversial, because it makes parsing ambiguous: if @code{-a} takes
an optional argument and @code{-b} is another option entirely, how do we
interpret @code{-ab}?  Because of this ambiguity, @ref{c3,,optparse} does not
support this feature.

@item positional 参数

something leftover in the argument list after options have been parsed, i.e.
after options and their arguments have been parsed and removed from the
argument list.

@item 必选选项

an option that must be supplied on the command-line; note that the phrase
"required option" is self-contradictory in English.  @ref{c3,,optparse} doesn't
prevent you from implementing required options, but doesn't give you much
help at it either.
@end table

For example, consider this hypothetical command-line:

@example
prog -v --report report.txt foo bar
@end example

@code{-v} and @code{--report} are both options.  Assuming that @code{--report}
takes one argument, @code{report.txt} is an option argument.  @code{foo} and
@code{bar} are positional arguments.

@node What are options for?,位置位置,术语,背景
@anchor{library/optparse optparse-what-options-for}@anchor{3c27}@anchor{library/optparse what-are-options-for}@anchor{3c28}
@subsubsection What are options for?


Options are used to provide extra information to tune or customize the execution
of a program.  In case it wasn't clear, options are usually @emph{optional}.  A
program should be able to run just fine with no options whatsoever.  (Pick a
random program from the Unix or GNU toolsets.  Can it run without any options at
all and still make sense?  The main exceptions are @code{find}, @code{tar}, and
@code{dd}---all of which are mutant oddballs that have been rightly criticized
for their non-standard syntax and confusing interfaces.)

Lots of people want their programs to have "required options".  Think about it.
If it's required, then it's @emph{not optional}!  If there is a piece of information
that your program absolutely requires in order to run successfully, that's what
positional arguments are for.

As an example of good command-line interface design, consider the humble @code{cp}
utility, for copying files.  It doesn't make much sense to try to copy files
without supplying a destination and at least one source. Hence, @code{cp} fails if
you run it with no arguments.  However, it has a flexible, useful syntax that
does not require any options at all:

@example
cp SOURCE DEST
cp SOURCE ... DEST-DIR
@end example

You can get pretty far with just that.  Most @code{cp} implementations provide a
bunch of options to tweak exactly how the files are copied: you can preserve
mode and modification time, avoid following symlinks, ask before clobbering
existing files, etc.  But none of this distracts from the core mission of
@code{cp}, which is to copy either one file to another, or several files to another
directory.

@node 位置位置,,What are options for?,背景
@anchor{library/optparse optparse-what-positional-arguments-for}@anchor{3c29}@anchor{library/optparse what-are-positional-arguments-for}@anchor{3c2a}
@subsubsection 位置位置


Positional arguments are for those pieces of information that your program
absolutely, positively requires to run.

A good user interface should have as few absolute requirements as possible.  If
your program requires 17 distinct pieces of information in order to run
successfully, it doesn't much matter @emph{how} you get that information from the
user---most people will give up and walk away before they successfully run the
program.  This applies whether the user interface is a command-line, a
configuration file, or a GUI: if you make that many demands on your users, most
of them will simply give up.

In short, try to minimize the amount of information that users are absolutely
required to supply---use sensible defaults whenever possible.  Of course, you
also want to make your programs reasonably flexible.  That's what options are
for.  Again, it doesn't matter if they are entries in a config file, widgets in
the "Preferences" dialog of a GUI, or command-line options---the more options
you implement, the more flexible your program is, and the more complicated its
implementation becomes.  Too much flexibility has drawbacks as well, of course;
too many options can overwhelm users and make your code much harder to maintain.

@node 教程<2>,参考指南,背景,optparse --- 解析器的命令行选项
@anchor{library/optparse optparse-tutorial}@anchor{3c2b}@anchor{library/optparse tutorial}@anchor{3c2c}
@subsubsection 教程


While @ref{c3,,optparse} is quite flexible and powerful, it's also straightforward
to use in most cases.  This section covers the code patterns that are common to
any @ref{c3,,optparse}-based program.

First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance:

@example
from optparse import OptionParser
...
parser = OptionParser()
@end example

Then you can start defining options.  The basic syntax is:

@example
parser.add_option(opt_str, ...,
                  attr=value, ...)
@end example

Each option has one or more option strings, such as @code{-f} or @code{--file},
and several option attributes that tell @ref{c3,,optparse} what to expect and what
to do when it encounters that option on the command line.

Typically, each option will have one short option string and one long option
string, e.g.:

@example
parser.add_option("-f", "--file", ...)
@end example

You're free to define as many short option strings and as many long option
strings as you like (including zero), as long as there is at least one option
string overall.

The option strings passed to @ref{21fb,,OptionParser.add_option()} are effectively
labels for the
option defined by that call.  For brevity, we will frequently refer to
@emph{encountering an option} on the command line; in reality, @ref{c3,,optparse}
encounters @emph{option strings} and looks up options from them.

Once all of your options are defined, instruct @ref{c3,,optparse} to parse your
program's command line:

@example
(options, args) = parser.parse_args()
@end example

(If you like, you can pass a custom argument list to @code{parse_args()}, but
that's rarely necessary: by default it uses @code{sys.argv[1:]}.)

@code{parse_args()} 返回两个值：


@itemize *

@item 
@code{options}, an object containing values for all of your options---e.g. if
@code{--file} takes a single string argument, then @code{options.file} will be the
filename supplied by the user, or @code{None} if the user did not supply that
option

@item 
@code{args}, the list of positional arguments leftover after parsing options
@end itemize

This tutorial section only covers the four most important option attributes:
@ref{3c2d,,action}, @ref{3c2e,,type}, @ref{3c2f,,dest}
(destination), and @ref{3c30,,help}. Of these, @ref{3c2d,,action} is the
most fundamental.

@menu
* Understanding option actions:: 
* The store action:: 
* Handling boolean (flag) options: Handling boolean flag options. 
* Other actions:: 
* 默认值:: 
* Generating help:: 
* Printing a version string:: 
* How optparse handles errors:: 
* Putting it all together:: 

@end menu

@node Understanding option actions,The store action,,教程<2>
@anchor{library/optparse optparse-understanding-option-actions}@anchor{3c31}@anchor{library/optparse understanding-option-actions}@anchor{3c32}
@subsubsection Understanding option actions


Actions tell @ref{c3,,optparse} what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into @ref{c3,,optparse};
adding new actions is an advanced topic covered in section
@ref{3c33,,Extending optparse}.  Most actions tell @ref{c3,,optparse} to store
a value in some variable---for example, take a string from the command line and
store it in an attribute of @code{options}.

If you don't specify an option action, @ref{c3,,optparse} defaults to @code{store}.

@node The store action,Handling boolean flag options,Understanding option actions,教程<2>
@anchor{library/optparse optparse-store-action}@anchor{3c34}@anchor{library/optparse the-store-action}@anchor{3c35}
@subsubsection The store action


The most common option action is @code{store}, which tells @ref{c3,,optparse} to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.

例如:

@example
parser.add_option("-f", "--file",
                  action="store", type="string", dest="filename")
@end example

Now let's make up a fake command line and ask @ref{c3,,optparse} to parse it:

@example
args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)
@end example

When @ref{c3,,optparse} sees the option string @code{-f}, it consumes the next
argument, @code{foo.txt}, and stores it in @code{options.filename}.  So, after this
call to @code{parse_args()}, @code{options.filename} is @code{"foo.txt"}.

Some other option types supported by @ref{c3,,optparse} are @code{int} and @code{float}.
Here's an option that expects an integer argument:

@example
parser.add_option("-n", type="int", dest="num")
@end example

Note that this option has no long option string, which is perfectly acceptable.
Also, there's no explicit action, since the default is @code{store}.

Let's parse another fake command-line.  This time, we'll jam the option argument
right up against the option: since @code{-n42} (one argument) is equivalent to
@code{-n 42} (two arguments), the code

@example
(options, args) = parser.parse_args(["-n42"])
print(options.num)
@end example

will print @code{42}.

If you don't specify a type, @ref{c3,,optparse} assumes @code{string}.  Combined with
the fact that the default action is @code{store}, that means our first example can
be a lot shorter:

@example
parser.add_option("-f", "--file", dest="filename")
@end example

If you don't supply a destination, @ref{c3,,optparse} figures out a sensible
default from the option strings: if the first long option string is
@code{--foo-bar}, then the default destination is @code{foo_bar}.  If there are no
long option strings, @ref{c3,,optparse} looks at the first short option string: the
default destination for @code{-f} is @code{f}.

@ref{c3,,optparse} also includes the built-in @code{complex} type.  Adding
types is covered in section @ref{3c33,,Extending optparse}.

@node Handling boolean flag options,Other actions,The store action,教程<2>
@anchor{library/optparse handling-boolean-flag-options}@anchor{3c36}@anchor{library/optparse optparse-handling-boolean-options}@anchor{3c37}
@subsubsection Handling boolean (flag) options


Flag options---set a variable to true or false when a particular option is
seen---are quite common.  @ref{c3,,optparse} supports them with two separate actions,
@code{store_true} and @code{store_false}.  For example, you might have a @code{verbose}
flag that is turned on with @code{-v} and off with @code{-q}:

@example
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")
@end example

Here we have two different options with the same destination, which is perfectly
OK.  (It just means you have to be a bit careful when setting default
values---see below.)

When @ref{c3,,optparse} encounters @code{-v} on the command line, it sets
@code{options.verbose} to @code{True}; when it encounters @code{-q},
@code{options.verbose} is set to @code{False}.

@node Other actions,默认值,Handling boolean flag options,教程<2>
@anchor{library/optparse optparse-other-actions}@anchor{3c38}@anchor{library/optparse other-actions}@anchor{3c39}
@subsubsection Other actions


Some other actions supported by @ref{c3,,optparse} are:


@table @asis

@item @code{"store_const"}

store a constant value

@item @code{"append"}

append this option's argument to a list

@item @code{"count"}

increment a counter by one

@item @code{"callback"}

调用指定函数
@end table

These are covered in section @ref{3c3a,,参考指南},
and section @ref{3c3b,,Option Callbacks}.

@node 默认值,Generating help,Other actions,教程<2>
@anchor{library/optparse default-values}@anchor{3c3c}@anchor{library/optparse optparse-default-values}@anchor{3c3d}
@subsubsection 默认值


All of the above examples involve setting some variable (the "destination") when
certain command-line options are seen.  What happens if those options are never
seen?  Since we didn't supply any defaults, they are all set to @code{None}.  This
is usually fine, but sometimes you want more control.  @ref{c3,,optparse} lets you
supply a default value for each destination, which is assigned before the
command line is parsed.

First, consider the verbose/quiet example.  If we want @ref{c3,,optparse} to set
@code{verbose} to @code{True} unless @code{-q} is seen, then we can do this:

@example
parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option("-q", action="store_false", dest="verbose")
@end example

Since default values apply to the @emph{destination} rather than to any particular
option, and these two options happen to have the same destination, this is
exactly equivalent:

@example
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)
@end example

考虑一下：

@example
parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)
@end example

Again, the default value for @code{verbose} will be @code{True}: the last default
value supplied for any particular destination is the one that counts.

A clearer way to specify default values is the @code{set_defaults()} method of
OptionParser, which you can call at any time before calling @code{parse_args()}:

@example
parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()
@end example

As before, the last value specified for a given option destination is the one
that counts.  For clarity, try to use one method or the other of setting default
values, not both.

@node Generating help,Printing a version string,默认值,教程<2>
@anchor{library/optparse generating-help}@anchor{3c3e}@anchor{library/optparse optparse-generating-help}@anchor{3c3f}
@subsubsection Generating help


@ref{c3,,optparse}'s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you have to do
is supply a @ref{3c30,,help} value for each option, and optionally a short
usage message for your whole program.  Here's an OptionParser populated with
user-friendly (documented) options:

@example
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=True,
                  help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose",
                  help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")
@end example

If @ref{c3,,optparse} encounters either @code{-h} or @code{--help} on the
command-line, or if you just call @code{parser.print_help()}, it prints the
following to standard output:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]
@end example

(If the help output is triggered by a help option, @ref{c3,,optparse} exits after
printing the help text.)

There's a lot going on here to help @ref{c3,,optparse} generate the best possible
help message:


@itemize *

@item 
the script defines its own usage message:

@example
usage = "usage: %prog [options] arg1 arg2"
@end example

@ref{c3,,optparse} expands @code{%prog} in the usage string to the name of the
current program, i.e. @code{os.path.basename(sys.argv[0])}.  The expanded string
is then printed before the detailed option help.

If you don't supply a usage string, @ref{c3,,optparse} uses a bland but sensible
default: @code{"Usage: %prog [options]"}, which is fine if your script doesn't
take any positional arguments.

@item 
every option defines a help string, and doesn't worry about
line-wrapping---@ref{c3,,optparse} takes care of wrapping lines and making
the help output look good.

@item 
options that take a value indicate this fact in their automatically-generated
help message, e.g. for the "mode" option:

@example
-m MODE, --mode=MODE
@end example

Here, "MODE" is called the meta-variable: it stands for the argument that the
user is expected to supply to @code{-m}/@code{--mode}.  By default,
@ref{c3,,optparse} converts the destination variable name to uppercase and uses
that for the meta-variable.  Sometimes, that's not what you want---for
example, the @code{--filename} option explicitly sets @code{metavar="FILE"},
resulting in this automatically-generated option description:

@example
-f FILE, --filename=FILE
@end example

This is important for more than just saving space, though: the manually
written help text uses the meta-variable @code{FILE} to clue the user in that
there's a connection between the semi-formal syntax @code{-f FILE} and the informal
semantic description "write output to FILE". This is a simple but effective
way to make your help text a lot clearer and more useful for end users.

@item 
options that have a default value can include @code{%default} in the help
string---@ref{c3,,optparse} will replace it with @ref{206,,str()} of the option's
default value.  If an option has no default value (or the default value is
@code{None}), @code{%default} expands to @code{none}.
@end itemize

@menu
* Grouping Options:: 

@end menu

@node Grouping Options,,,Generating help
@anchor{library/optparse grouping-options}@anchor{3c40}
@subsubsection Grouping Options


When dealing with many options, it is convenient to group these options for
better help output.  An @ref{3c22,,OptionParser} can contain several option groups,
each of which can contain several options.

An option group is obtained using the class @ref{3c41,,OptionGroup}:

@geindex OptionGroup (optparse 中的类)
@anchor{library/optparse optparse OptionGroup}@anchor{3c41}
@deffn {类} optparse.OptionGroup (parser, title, description=None)

where


@itemize *

@item 
parser is the @ref{3c22,,OptionParser} instance the group will be inserted in
to

@item 
title is the group title

@item 
description, optional, is a long description of the group
@end itemize
@end deffn

@ref{3c41,,OptionGroup} inherits from @code{OptionContainer} (like
@ref{3c22,,OptionParser}) and so the @code{add_option()} method can be used to add
an option to the group.

Once all the options are declared, using the @ref{3c22,,OptionParser} method
@code{add_option_group()} the group is added to the previously defined parser.

Continuing with the parser defined in the previous section, adding an
@ref{3c41,,OptionGroup} to a parser is easy:

@example
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)
@end example

This would result in the following help output:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.
@end example

A bit more complete example might involve using more than one group: still
extending the previous example:

@example
group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

group = OptionGroup(parser, "Debug Options")
group.add_option("-d", "--debug", action="store_true",
                 help="Print debug information")
group.add_option("-s", "--sql", action="store_true",
                 help="Print all SQL statements executed")
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)
@end example

that results in the following output:

@example
Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                        [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

  Debug Options:
    -d, --debug         Print debug information
    -s, --sql           Print all SQL statements executed
    -e                  Print every action done
@end example

Another interesting method, in particular when working programmatically with
option groups is:

@geindex get_option_group() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser get_option_group}@anchor{3c42}
@deffn {方法} OptionParser.get_option_group (opt_str)

Return the @ref{3c41,,OptionGroup} to which the short or long option
string @emph{opt_str} (e.g. @code{'-o'} or @code{'--option'}) belongs. If
there's no such @ref{3c41,,OptionGroup}, return @code{None}.
@end deffn

@node Printing a version string,How optparse handles errors,Generating help,教程<2>
@anchor{library/optparse optparse-printing-version-string}@anchor{3c43}@anchor{library/optparse printing-a-version-string}@anchor{3c44}
@subsubsection Printing a version string


Similar to the brief usage string, @ref{c3,,optparse} can also print a version
string for your program.  You have to supply the string as the @code{version}
argument to OptionParser:

@example
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
@end example

@code{%prog} is expanded just like it is in @code{usage}.  Apart from that,
@code{version} can contain anything you like.  When you supply it, @ref{c3,,optparse}
automatically adds a @code{--version} option to your parser. If it encounters
this option on the command line, it expands your @code{version} string (by
replacing @code{%prog}), prints it to stdout, and exits.

For example, if your script is called @code{/usr/bin/foo}:

@example
$ /usr/bin/foo --version
foo 1.0
@end example

The following two methods can be used to print and get the @code{version} string:

@geindex print_version() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser print_version}@anchor{3c45}
@deffn {方法} OptionParser.print_version (file=None)

Print the version message for the current program (@code{self.version}) to
@emph{file} (default stdout).  As with @ref{3c46,,print_usage()}, any occurrence
of @code{%prog} in @code{self.version} is replaced with the name of the current
program.  Does nothing if @code{self.version} is empty or undefined.
@end deffn

@geindex get_version() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser get_version}@anchor{3c47}
@deffn {方法} OptionParser.get_version ()

Same as @ref{3c45,,print_version()} but returns the version string instead of
printing it.
@end deffn

@node How optparse handles errors,Putting it all together,Printing a version string,教程<2>
@anchor{library/optparse how-optparse-handles-errors}@anchor{3c48}@anchor{library/optparse optparse-how-optparse-handles-errors}@anchor{3c49}
@subsubsection How @code{optparse} handles errors


There are two broad classes of errors that @ref{c3,,optparse} has to worry about:
programmer errors and user errors.  Programmer errors are usually erroneous
calls to @ref{21fb,,OptionParser.add_option()}, e.g. invalid option strings, unknown
option attributes, missing option attributes, etc.  These are dealt with in the
usual way: raise an exception (either @code{optparse.OptionError} or
@ref{1ff,,TypeError}) and let the program crash.

Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is.  @ref{c3,,optparse} can automatically detect
some user errors, such as bad option arguments (passing @code{-n 4x} where
@code{-n} takes an integer argument), missing arguments (@code{-n} at the end
of the command line, where @code{-n} takes an argument of any type).  Also,
you can call @code{OptionParser.error()} to signal an application-defined error
condition:

@example
(options, args) = parser.parse_args()
...
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")
@end example

In either case, @ref{c3,,optparse} handles the error the same way: it prints the
program's usage message and an error message to standard error and exits with
error status 2.

Consider the first example above, where the user passes @code{4x} to an option
that takes an integer:

@example
$ /usr/bin/foo -n 4x
Usage: foo [options]

foo: error: option -n: invalid integer value: '4x'
@end example

Or, where the user fails to pass a value at all:

@example
$ /usr/bin/foo -n
Usage: foo [options]

foo: error: -n option requires an argument
@end example

@ref{c3,,optparse}-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
@code{OptionParser.error()} from your application code.

If @ref{c3,,optparse}'s default error-handling behaviour does not suit your needs,
you'll need to subclass OptionParser and override its @code{exit()}
and/or @code{error()} methods.

@node Putting it all together,,How optparse handles errors,教程<2>
@anchor{library/optparse optparse-putting-it-all-together}@anchor{3c4a}@anchor{library/optparse putting-it-all-together}@anchor{3c4b}
@subsubsection Putting it all together


Here's what @ref{c3,,optparse}-based scripts usually look like:

@example
from optparse import OptionParser
...
def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print("reading %s..." % options.filename)
    ...

if __name__ == "__main__":
    main()
@end example

@node 参考指南,Option Callbacks,教程<2>,optparse --- 解析器的命令行选项
@anchor{library/optparse optparse-reference-guide}@anchor{3c3a}@anchor{library/optparse reference-guide}@anchor{3c4c}
@subsubsection 参考指南


@menu
* 创建解析器:: 
* 填充解析器:: 
* 定义选项:: 
* Option attributes:: 
* Standard option actions:: 
* Standard option types:: 
* 解析参数: 解析参数<2>. 
* Querying and manipulating your option parser:: 
* Conflicts between options:: 
* 清理: 清理<2>. 
* Other methods:: 

@end menu

@node 创建解析器,填充解析器,,参考指南
@anchor{library/optparse creating-the-parser}@anchor{3c4d}@anchor{library/optparse optparse-creating-parser}@anchor{3c4e}
@subsubsection 创建解析器


The first step in using @ref{c3,,optparse} is to create an OptionParser instance.

@geindex OptionParser (optparse 中的类)
@anchor{library/optparse optparse OptionParser}@anchor{3c22}
@deffn {类} optparse.OptionParser (...)

The OptionParser constructor has no required arguments, but a number of
optional keyword arguments.  You should always pass them as keyword
arguments, i.e. do not rely on the order in which the arguments are declared.


@table @asis

@item @code{usage} (默认: @code{"%prog [options]"})

The usage summary to print when your program is run incorrectly or with a
help option.  When @ref{c3,,optparse} prints the usage string, it expands
@code{%prog} to @code{os.path.basename(sys.argv[0])} (or to @code{prog} if you
passed that keyword argument).  To suppress a usage message, pass the
special value @code{optparse.SUPPRESS_USAGE}.

@item @code{option_list} (默认: @code{[]})

A list of Option objects to populate the parser with.  The options in
@code{option_list} are added after any options in @code{standard_option_list} (a
class attribute that may be set by OptionParser subclasses), but before
any version or help options. Deprecated; use @ref{21fb,,add_option()} after
creating the parser instead.

@item @code{option_class} (默认: optparse.Option)

Class to use when adding options to the parser in @ref{21fb,,add_option()}.

@item @code{version} (默认: @code{None})

A version string to print when the user supplies a version option. If you
supply a true value for @code{version}, @ref{c3,,optparse} automatically adds a
version option with the single option string @code{--version}.  The
substring @code{%prog} is expanded the same as for @code{usage}.

@item @code{conflict_handler} (默认: @code{"error"})

Specifies what to do when options with conflicting option strings are
added to the parser; see section
@ref{3c4f,,Conflicts between options}.

@item @code{description} (默认: @code{None})

A paragraph of text giving a brief overview of your program.
@ref{c3,,optparse} reformats this paragraph to fit the current terminal width
and prints it when the user requests help (after @code{usage}, but before the
list of options).

@item @code{formatter} (default: a new @code{IndentedHelpFormatter})

An instance of optparse.HelpFormatter that will be used for printing help
text.  @ref{c3,,optparse} provides two concrete classes for this purpose:
IndentedHelpFormatter and TitledHelpFormatter.

@item @code{add_help_option} (默认: @code{True})

If true, @ref{c3,,optparse} will add a help option (with option strings @code{-h}
and @code{--help}) to the parser.

@item @code{prog}

The string to use when expanding @code{%prog} in @code{usage} and @code{version}
instead of @code{os.path.basename(sys.argv[0])}.

@item @code{epilog} (默认: @code{None})

A paragraph of help text to print after the option help.
@end table
@end deffn

@node 填充解析器,定义选项,创建解析器,参考指南
@anchor{library/optparse optparse-populating-parser}@anchor{3c50}@anchor{library/optparse populating-the-parser}@anchor{3c51}
@subsubsection 填充解析器


There are several ways to populate the parser with options.  The preferred way
is by using @ref{21fb,,OptionParser.add_option()}, as shown in section
@ref{3c2b,,教程}.  @code{add_option()} can be called in one of two ways:


@itemize *

@item 
pass it an Option instance (as returned by @code{make_option()})

@item 
pass it any combination of positional and keyword arguments that are
acceptable to @code{make_option()} (i.e., to the Option constructor), and it
will create the Option instance for you
@end itemize

The other alternative is to pass a list of pre-constructed Option instances to
the OptionParser constructor, as in:

@example
option_list = [
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose"),
    ]
parser = OptionParser(option_list=option_list)
@end example

(@code{make_option()} is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version of
@ref{c3,,optparse} may split Option into several classes, and @code{make_option()}
will pick the right class to instantiate.  Do not instantiate Option directly.)

@node 定义选项,Option attributes,填充解析器,参考指南
@anchor{library/optparse defining-options}@anchor{3c52}@anchor{library/optparse optparse-defining-options}@anchor{3c53}
@subsubsection 定义选项


Each Option instance represents a set of synonymous command-line option strings,
e.g. @code{-f} and @code{--file}.  You can specify any number of short or
long option strings, but you must specify at least one overall option string.

The canonical way to create an @code{Option} instance is with the
@code{add_option()} method of @ref{3c22,,OptionParser}.

@geindex add_option() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser add_option}@anchor{21fb}
@deffn {方法} OptionParser.add_option (option)

@deffnx {方法} OptionParser.add_option (*opt_str, attr=value, ...)

To define an option with only a short option string:

@example
parser.add_option("-f", attr=value, ...)
@end example

And to define an option with only a long option string:

@example
parser.add_option("--foo", attr=value, ...)
@end example

The keyword arguments define attributes of the new Option object.  The most
important option attribute is @ref{3c2d,,action}, and it largely
determines which other attributes are relevant or required.  If you pass
irrelevant option attributes, or fail to pass required ones, @ref{c3,,optparse}
raises an @code{OptionError} exception explaining your mistake.

An option's @emph{action} determines what @ref{c3,,optparse} does when it encounters
this option on the command-line.  The standard option actions hard-coded into
@ref{c3,,optparse} are:


@table @asis

@item @code{"store"}

存储此选项的参数（默认）

@item @code{"store_const"}

store a constant value

@item @code{"store_true"}

store @code{True}

@item @code{"store_false"}

store @code{False}

@item @code{"append"}

append this option's argument to a list

@item @code{"append_const"}

将常量值附加到列表

@item @code{"count"}

increment a counter by one

@item @code{"callback"}

调用指定函数

@item @code{"help"}

打印用法消息，包括所有选项和文档
@end table

(If you don't supply an action, the default is @code{"store"}.  For this action,
you may also supply @ref{3c2e,,type} and @ref{3c2f,,dest} option
attributes; see @ref{3c54,,Standard option actions}.)
@end deffn

As you can see, most actions involve storing or updating a value somewhere.
@ref{c3,,optparse} always creates a special object for this, conventionally called
@code{options} (it happens to be an instance of @code{optparse.Values}).  Option
arguments (and various other values) are stored as attributes of this object,
according to the @ref{3c2f,,dest} (destination) option attribute.

For example, when you call

@example
parser.parse_args()
@end example

one of the first things @ref{c3,,optparse} does is create the @code{options} object:

@example
options = Values()
@end example

If one of the options in this parser is defined with

@example
parser.add_option("-f", "--file", action="store", type="string", dest="filename")
@end example

and the command-line being parsed includes any of the following:

@example
-ffoo
-f foo
--file=foo
--file foo
@end example

then @ref{c3,,optparse}, on seeing this option, will do the equivalent of

@example
options.filename = "foo"
@end example

The @ref{3c2e,,type} and @ref{3c2f,,dest} option attributes are almost
as important as @ref{3c2d,,action}, but @ref{3c2d,,action} is the only
one that makes sense for @emph{all} options.

@node Option attributes,Standard option actions,定义选项,参考指南
@anchor{library/optparse option-attributes}@anchor{3c55}@anchor{library/optparse optparse-option-attributes}@anchor{3c56}
@subsubsection Option attributes


The following option attributes may be passed as keyword arguments to
@ref{21fb,,OptionParser.add_option()}.  If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
@ref{c3,,optparse} raises @code{OptionError}.

@geindex action (optparse.Option 属性)
@anchor{library/optparse optparse Option action}@anchor{3c2d}
@deffn {属性} Option.action

(默认: @code{"store"})

Determines @ref{c3,,optparse}'s behaviour when this option is seen on the
command line; the available options are documented @ref{3c54,,here}.
@end deffn

@geindex type (optparse.Option 属性)
@anchor{library/optparse optparse Option type}@anchor{3c2e}
@deffn {属性} Option.type

(默认: @code{"string"})

The argument type expected by this option (e.g., @code{"string"} or @code{"int"});
the available option types are documented @ref{3c57,,here}.
@end deffn

@geindex dest (optparse.Option 属性)
@anchor{library/optparse optparse Option dest}@anchor{3c2f}
@deffn {属性} Option.dest

(default: derived from option strings)

If the option's action implies writing or modifying a value somewhere, this
tells @ref{c3,,optparse} where to write it: @ref{3c2f,,dest} names an
attribute of the @code{options} object that @ref{c3,,optparse} builds as it parses
the command line.
@end deffn

@geindex default (optparse.Option 属性)
@anchor{library/optparse optparse Option default}@anchor{3c58}
@deffn {属性} Option.default

The value to use for this option's destination if the option is not seen on
the command line.  See also @ref{3c59,,OptionParser.set_defaults()}.
@end deffn

@geindex nargs (optparse.Option 属性)
@anchor{library/optparse optparse Option nargs}@anchor{3c5a}
@deffn {属性} Option.nargs

(默认: 1)

How many arguments of type @ref{3c2e,,type} should be consumed when this
option is seen.  If > 1, @ref{c3,,optparse} will store a tuple of values to
@ref{3c2f,,dest}.
@end deffn

@geindex const (optparse.Option 属性)
@anchor{library/optparse optparse Option const}@anchor{3c5b}
@deffn {属性} Option.const

For actions that store a constant value, the constant value to store.
@end deffn

@geindex choices (optparse.Option 属性)
@anchor{library/optparse optparse Option choices}@anchor{3c5c}
@deffn {属性} Option.choices

For options of type @code{"choice"}, the list of strings the user may choose
from.
@end deffn

@geindex callback (optparse.Option 属性)
@anchor{library/optparse optparse Option callback}@anchor{3c5d}
@deffn {属性} Option.callback

For options with action @code{"callback"}, the callable to call when this option
is seen.  See section @ref{3c3b,,Option Callbacks} for detail on the
arguments passed to the callable.
@end deffn

@geindex callback_args (optparse.Option 属性)
@geindex callback_kwargs (optparse.Option 属性)
@anchor{library/optparse optparse Option callback_args}@anchor{3c5e}
@deffn {属性} Option.callback_args
@anchor{library/optparse optparse Option callback_kwargs}@anchor{3c5f}
@deffnx {属性} Option.callback_kwargs

Additional positional and keyword arguments to pass to @code{callback} after the
four standard callback arguments.
@end deffn

@geindex help (optparse.Option 属性)
@anchor{library/optparse optparse Option help}@anchor{3c30}
@deffn {属性} Option.help

Help text to print for this option when listing all available options after
the user supplies a @ref{3c30,,help} option (such as @code{--help}).  If
no help text is supplied, the option will be listed without help text.  To
hide this option, use the special value @code{optparse.SUPPRESS_HELP}.
@end deffn

@geindex metavar (optparse.Option 属性)
@anchor{library/optparse optparse Option metavar}@anchor{3c60}
@deffn {属性} Option.metavar

(default: derived from option strings)

Stand-in for the option argument(s) to use when printing help text.  See
section @ref{3c2b,,教程} for an example.
@end deffn

@node Standard option actions,Standard option types,Option attributes,参考指南
@anchor{library/optparse optparse-standard-option-actions}@anchor{3c54}@anchor{library/optparse standard-option-actions}@anchor{3c61}
@subsubsection Standard option actions


The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide @ref{c3,,optparse}'s behaviour; a few have required attributes, which you
must specify for any option using that action.


@itemize *

@item 
@code{"store"} [relevant: @ref{3c2e,,type}, @ref{3c2f,,dest},
@ref{3c5a,,nargs}, @ref{3c5c,,choices}]

The option must be followed by an argument, which is converted to a value
according to @ref{3c2e,,type} and stored in @ref{3c2f,,dest}.  If
@ref{3c5a,,nargs} > 1, multiple arguments will be consumed from the
command line; all will be converted according to @ref{3c2e,,type} and
stored to @ref{3c2f,,dest} as a tuple.  See the
@ref{3c57,,Standard option types} section.

If @ref{3c5c,,choices} is supplied (a list or tuple of strings), the type
defaults to @code{"choice"}.

If @ref{3c2e,,type} is not supplied, it defaults to @code{"string"}.

If @ref{3c2f,,dest} is not supplied, @ref{c3,,optparse} derives a destination
from the first long option string (e.g., @code{--foo-bar} implies
@code{foo_bar}). If there are no long option strings, @ref{c3,,optparse} derives a
destination from the first short option string (e.g., @code{-f} implies @code{f}).

示例:

@example
parser.add_option("-f")
parser.add_option("-p", type="float", nargs=3, dest="point")
@end example

As it parses the command line

@example
-f foo.txt -p 1 -3.5 4 -fbar.txt
@end example

@ref{c3,,optparse} will set

@example
options.f = "foo.txt"
options.point = (1.0, -3.5, 4.0)
options.f = "bar.txt"
@end example

@item 
@code{"store_const"} [required: @ref{3c5b,,const}; relevant:
@ref{3c2f,,dest}]

The value @ref{3c5b,,const} is stored in @ref{3c2f,,dest}.

示例:

@example
parser.add_option("-q", "--quiet",
                  action="store_const", const=0, dest="verbose")
parser.add_option("-v", "--verbose",
                  action="store_const", const=1, dest="verbose")
parser.add_option("--noisy",
                  action="store_const", const=2, dest="verbose")
@end example

If @code{--noisy} is seen, @ref{c3,,optparse} will set

@example
options.verbose = 2
@end example

@item 
@code{"store_true"} [relevant: @ref{3c2f,,dest}]

A special case of @code{"store_const"} that stores @code{True} to
@ref{3c2f,,dest}.

@item 
@code{"store_false"} [relevant: @ref{3c2f,,dest}]

Like @code{"store_true"}, but stores @code{False}.

示例:

@example
parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option("--no-clobber", action="store_false", dest="clobber")
@end example

@item 
@code{"append"} [relevant: @ref{3c2e,,type}, @ref{3c2f,,dest},
@ref{3c5a,,nargs}, @ref{3c5c,,choices}]

The option must be followed by an argument, which is appended to the list in
@ref{3c2f,,dest}.  If no default value for @ref{3c2f,,dest} is
supplied, an empty list is automatically created when @ref{c3,,optparse} first
encounters this option on the command-line.  If @ref{3c5a,,nargs} > 1,
multiple arguments are consumed, and a tuple of length @ref{3c5a,,nargs}
is appended to @ref{3c2f,,dest}.

The defaults for @ref{3c2e,,type} and @ref{3c2f,,dest} are the same as
for the @code{"store"} action.

示例:

@example
parser.add_option("-t", "--tracks", action="append", type="int")
@end example

If @code{-t3} is seen on the command-line, @ref{c3,,optparse} does the equivalent
of:

@example
options.tracks = []
options.tracks.append(int("3"))
@end example

If, a little later on, @code{--tracks=4} is seen, it does:

@example
options.tracks.append(int("4"))
@end example

The @code{append} action calls the @code{append} method on the current value of the
option.  This means that any default value specified must have an @code{append}
method.  It also means that if the default value is non-empty, the default
elements will be present in the parsed value for the option, with any values
from the command line appended after those default values:

@example
>>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
>>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
>>> opts.files
['~/.mypkg/defaults', 'overrides.mypkg']
@end example

@item 
@code{"append_const"} [required: @ref{3c5b,,const}; relevant:
@ref{3c2f,,dest}]

Like @code{"store_const"}, but the value @ref{3c5b,,const} is appended to
@ref{3c2f,,dest}; as with @code{"append"}, @ref{3c2f,,dest} defaults to
@code{None}, and an empty list is automatically created the first time the option
is encountered.

@item 
@code{"count"} [relevant: @ref{3c2f,,dest}]

Increment the integer stored at @ref{3c2f,,dest}.  If no default value is
supplied, @ref{3c2f,,dest} is set to zero before being incremented the
first time.

示例:

@example
parser.add_option("-v", action="count", dest="verbosity")
@end example

The first time @code{-v} is seen on the command line, @ref{c3,,optparse} does the
equivalent of:

@example
options.verbosity = 0
options.verbosity += 1
@end example

Every subsequent occurrence of @code{-v} results in

@example
options.verbosity += 1
@end example

@item 
@code{"callback"} [required: @ref{3c5d,,callback}; relevant:
@ref{3c2e,,type}, @ref{3c5a,,nargs}, @ref{3c5e,,callback_args},
@ref{3c5f,,callback_kwargs}]

Call the function specified by @ref{3c5d,,callback}, which is called as

@example
func(option, opt_str, value, parser, *args, **kwargs)
@end example

See section @ref{3c3b,,Option Callbacks} for more detail.

@item 
@code{"help"}

Prints a complete help message for all the options in the current option
parser.  The help message is constructed from the @code{usage} string passed to
OptionParser's constructor and the @ref{3c30,,help} string passed to every
option.

If no @ref{3c30,,help} string is supplied for an option, it will still be
listed in the help message.  To omit an option entirely, use the special value
@code{optparse.SUPPRESS_HELP}.

@ref{c3,,optparse} automatically adds a @ref{3c30,,help} option to all
OptionParsers, so you do not normally need to create one.

示例:

@example
from optparse import OptionParser, SUPPRESS_HELP

# usually, a help option is added automatically, but that can
# be suppressed using the add_help_option argument
parser = OptionParser(add_help_option=False)

parser.add_option("-h", "--help", action="help")
parser.add_option("-v", action="store_true", dest="verbose",
                  help="Be moderately verbose")
parser.add_option("--file", dest="filename",
                  help="Input file to read data from")
parser.add_option("--secret", help=SUPPRESS_HELP)
@end example

If @ref{c3,,optparse} sees either @code{-h} or @code{--help} on the command line,
it will print something like the following help message to stdout (assuming
@code{sys.argv[0]} is @code{"foo.py"}):

@example
Usage: foo.py [options]

Options:
  -h, --help        Show this help message and exit
  -v                Be moderately verbose
  --file=FILENAME   Input file to read data from
@end example

After printing the help message, @ref{c3,,optparse} terminates your process with
@code{sys.exit(0)}.

@item 
@code{"version"}

Prints the version number supplied to the OptionParser to stdout and exits.
The version number is actually formatted and printed by the
@code{print_version()} method of OptionParser.  Generally only relevant if the
@code{version} argument is supplied to the OptionParser constructor.  As with
@ref{3c30,,help} options, you will rarely create @code{version} options,
since @ref{c3,,optparse} automatically adds them when needed.
@end itemize

@node Standard option types,解析参数<2>,Standard option actions,参考指南
@anchor{library/optparse optparse-standard-option-types}@anchor{3c57}@anchor{library/optparse standard-option-types}@anchor{3c62}
@subsubsection Standard option types


@ref{c3,,optparse} has five built-in option types: @code{"string"}, @code{"int"},
@code{"choice"}, @code{"float"} and @code{"complex"}.  If you need to add new
option types, see section @ref{3c33,,Extending optparse}.

Arguments to string options are not checked or converted in any way: the text on
the command line is stored in the destination (or passed to the callback) as-is.

Integer arguments (type @code{"int"}) are parsed as follows:


@itemize *

@item 
if the number starts with @code{0x}, it is parsed as a hexadecimal number

@item 
if the number starts with @code{0}, it is parsed as an octal number

@item 
if the number starts with @code{0b}, it is parsed as a binary number

@item 
otherwise, the number is parsed as a decimal number
@end itemize

The conversion is done by calling @ref{205,,int()} with the appropriate base (2, 8,
10, or 16).  If this fails, so will @ref{c3,,optparse}, although with a more useful
error message.

@code{"float"} and @code{"complex"} option arguments are converted directly with
@ref{1fe,,float()} and @ref{2c8,,complex()}, with similar error-handling.

@code{"choice"} options are a subtype of @code{"string"} options.  The
@ref{3c5c,,choices} option attribute (a sequence of strings) defines the
set of allowed option arguments.  @code{optparse.check_choice()} compares
user-supplied option arguments against this master list and raises
@code{OptionValueError} if an invalid string is given.

@node 解析参数<2>,Querying and manipulating your option parser,Standard option types,参考指南
@anchor{library/optparse optparse-parsing-arguments}@anchor{3c63}@anchor{library/optparse parsing-arguments}@anchor{3c64}
@subsubsection 解析参数


The whole point of creating and populating an OptionParser is to call its
@code{parse_args()} method:

@example
(options, args) = parser.parse_args(args=None, values=None)
@end example

输入参数的位置


@table @asis

@item @code{args}

the list of arguments to process (default: @code{sys.argv[1:]})

@item @code{values}

an @code{optparse.Values} object to store option arguments in (default: a
new instance of @code{Values}) -- if you give an existing object, the
option defaults will not be initialized on it
@end table

and the return values are


@table @asis

@item @code{options}

the same object that was passed in as @code{values}, or the optparse.Values
instance created by @ref{c3,,optparse}

@item @code{args}

the leftover positional arguments after all options have been processed
@end table

The most common usage is to supply neither keyword argument.  If you supply
@code{values}, it will be modified with repeated @ref{1742,,setattr()} calls (roughly one
for every option argument stored to an option destination) and returned by
@code{parse_args()}.

If @code{parse_args()} encounters any errors in the argument list, it calls the
OptionParser's @code{error()} method with an appropriate end-user error message.
This ultimately terminates your process with an exit status of 2 (the
traditional Unix exit status for command-line errors).

@node Querying and manipulating your option parser,Conflicts between options,解析参数<2>,参考指南
@anchor{library/optparse optparse-querying-manipulating-option-parser}@anchor{3c65}@anchor{library/optparse querying-and-manipulating-your-option-parser}@anchor{3c66}
@subsubsection Querying and manipulating your option parser


The default behavior of the option parser can be customized slightly, and you
can also poke around your option parser and see what's there.  OptionParser
provides several methods to help you out:

@geindex disable_interspersed_args() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser disable_interspersed_args}@anchor{21fc}
@deffn {方法} OptionParser.disable_interspersed_args ()

Set parsing to stop on the first non-option.  For example, if @code{-a} and
@code{-b} are both simple options that take no arguments, @ref{c3,,optparse}
normally accepts this syntax:

@example
prog -a arg1 -b arg2
@end example

and treats it as equivalent to

@example
prog -a -b arg1 arg2
@end example

To disable this feature, call @ref{21fc,,disable_interspersed_args()}.  This
restores traditional Unix syntax, where option parsing stops with the first
non-option argument.

Use this if you have a command processor which runs another command which has
options of its own and you want to make sure these options don't get
confused.  For example, each command might have a different set of options.
@end deffn

@geindex enable_interspersed_args() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser enable_interspersed_args}@anchor{3c67}
@deffn {方法} OptionParser.enable_interspersed_args ()

Set parsing to not stop on the first non-option, allowing interspersing
switches with command arguments.  This is the default behavior.
@end deffn

@geindex get_option() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser get_option}@anchor{3c68}
@deffn {方法} OptionParser.get_option (opt_str)

Returns the Option instance with the option string @emph{opt_str}, or @code{None} if
no options have that option string.
@end deffn

@geindex has_option() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser has_option}@anchor{3c69}
@deffn {方法} OptionParser.has_option (opt_str)

Return @code{True} if the OptionParser has an option with option string @emph{opt_str}
(e.g., @code{-q} or @code{--verbose}).
@end deffn

@geindex remove_option() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser remove_option}@anchor{3c6a}
@deffn {方法} OptionParser.remove_option (opt_str)

If the @ref{3c22,,OptionParser} has an option corresponding to @emph{opt_str}, that
option is removed.  If that option provided any other option strings, all of
those option strings become invalid. If @emph{opt_str} does not occur in any
option belonging to this @ref{3c22,,OptionParser}, raises @ref{16d,,ValueError}.
@end deffn

@node Conflicts between options,清理<2>,Querying and manipulating your option parser,参考指南
@anchor{library/optparse conflicts-between-options}@anchor{3c6b}@anchor{library/optparse optparse-conflicts-between-options}@anchor{3c4f}
@subsubsection Conflicts between options


If you're not careful, it's easy to define options with conflicting option
strings:

@example
parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)
@end example

(This is particularly true if you've defined your own OptionParser subclass with
some standard options.)

Every time you add an option, @ref{c3,,optparse} checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor:

@example
parser = OptionParser(..., conflict_handler=handler)
@end example

or with a separate call:

@example
parser.set_conflict_handler(handler)
@end example

The available conflict handlers are:

@quotation


@table @asis

@item @code{"error"} (默认)

assume option conflicts are a programming error and raise
@code{OptionConflictError}

@item @code{"resolve"}

resolve option conflicts intelligently (see below)
@end table
@end quotation

As an example, let's define an @ref{3c22,,OptionParser} that resolves conflicts
intelligently and add conflicting options to it:

@example
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")
@end example

At this point, @ref{c3,,optparse} detects that a previously-added option is already
using the @code{-n} option string.  Since @code{conflict_handler} is @code{"resolve"},
it resolves the situation by removing @code{-n} from the earlier option's list of
option strings.  Now @code{--dry-run} is the only way for the user to activate
that option.  If the user asks for help, the help message will reflect that:

@example
Options:
  --dry-run     do no harm
  ...
  -n, --noisy   be noisy
@end example

It's possible to whittle away the option strings for a previously-added option
until there are none left, and the user has no way of invoking that option from
the command-line.  In that case, @ref{c3,,optparse} removes that option completely,
so it doesn't show up in help text or anywhere else. Carrying on with our
existing OptionParser:

@example
parser.add_option("--dry-run", ..., help="new dry-run option")
@end example

At this point, the original @code{-n}/@code{--dry-run} option is no longer
accessible, so @ref{c3,,optparse} removes it, leaving this help text:

@example
Options:
  ...
  -n, --noisy   be noisy
  --dry-run     new dry-run option
@end example

@node 清理<2>,Other methods,Conflicts between options,参考指南
@anchor{library/optparse cleanup}@anchor{3c6c}@anchor{library/optparse optparse-cleanup}@anchor{3c6d}
@subsubsection 清理


OptionParser instances have several cyclic references.  This should not be a
problem for Python's garbage collector, but you may wish to break the cyclic
references explicitly by calling @code{destroy()} on your
OptionParser once you are done with it.  This is particularly useful in
long-running applications where large object graphs are reachable from your
OptionParser.

@node Other methods,,清理<2>,参考指南
@anchor{library/optparse optparse-other-methods}@anchor{3c6e}@anchor{library/optparse other-methods}@anchor{3c6f}
@subsubsection Other methods


OptionParser supports several other public methods:

@geindex set_usage() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser set_usage}@anchor{3c70}
@deffn {方法} OptionParser.set_usage (usage)

Set the usage string according to the rules described above for the @code{usage}
constructor keyword argument.  Passing @code{None} sets the default usage
string; use @code{optparse.SUPPRESS_USAGE} to suppress a usage message.
@end deffn

@geindex print_usage() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser print_usage}@anchor{3c46}
@deffn {方法} OptionParser.print_usage (file=None)

Print the usage message for the current program (@code{self.usage}) to @emph{file}
(default stdout).  Any occurrence of the string @code{%prog} in @code{self.usage}
is replaced with the name of the current program.  Does nothing if
@code{self.usage} is empty or not defined.
@end deffn

@geindex get_usage() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser get_usage}@anchor{3c71}
@deffn {方法} OptionParser.get_usage ()

Same as @ref{3c46,,print_usage()} but returns the usage string instead of
printing it.
@end deffn

@geindex set_defaults() (optparse.OptionParser 方法)
@anchor{library/optparse optparse OptionParser set_defaults}@anchor{3c59}
@deffn {方法} OptionParser.set_defaults (dest=value, ...)

Set default values for several option destinations at once.  Using
@ref{3c59,,set_defaults()} is the preferred way to set default values for options,
since multiple options can share the same destination.  For example, if
several "mode" options all set the same destination, any one of them can set
the default, and the last one wins:

@example
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced",
                  default="novice")    # overridden below
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice",
                  default="advanced")  # overrides above setting
@end example

To avoid this confusion, use @ref{3c59,,set_defaults()}:

@example
parser.set_defaults(mode="advanced")
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced")
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice")
@end example
@end deffn

@node Option Callbacks,Extending optparse,参考指南,optparse --- 解析器的命令行选项
@anchor{library/optparse option-callbacks}@anchor{3c72}@anchor{library/optparse optparse-option-callbacks}@anchor{3c3b}
@subsubsection Option Callbacks


When @ref{c3,,optparse}'s built-in actions and types aren't quite enough for your
needs, you have two choices: extend @ref{c3,,optparse} or define a callback option.
Extending @ref{c3,,optparse} is more general, but overkill for a lot of simple
cases.  Quite often a simple callback is all you need.

There are two steps to defining a callback option:


@itemize *

@item 
define the option itself using the @code{"callback"} action

@item 
write the callback; this is a function (or method) that takes at least four
arguments, as described below
@end itemize

@menu
* Defining a callback option:: 
* How callbacks are called:: 
* Raising errors in a callback:: 
* Callback example 1; trivial callback: Callback example 1 trivial callback. 
* Callback example 2; check option order: Callback example 2 check option order. 
* Callback example 3; check option order (generalized): Callback example 3 check option order generalized. 
* Callback example 4; check arbitrary condition: Callback example 4 check arbitrary condition. 
* Callback example 5; fixed arguments: Callback example 5 fixed arguments. 
* Callback example 6; variable arguments: Callback example 6 variable arguments. 

@end menu

@node Defining a callback option,How callbacks are called,,Option Callbacks
@anchor{library/optparse defining-a-callback-option}@anchor{3c73}@anchor{library/optparse optparse-defining-callback-option}@anchor{3c74}
@subsubsection Defining a callback option


As always, the easiest way to define a callback option is by using the
@ref{21fb,,OptionParser.add_option()} method.  Apart from @ref{3c2d,,action}, the
only option attribute you must specify is @code{callback}, the function to call:

@example
parser.add_option("-c", action="callback", callback=my_callback)
@end example

@code{callback} is a function (or other callable object), so you must have already
defined @code{my_callback()} when you create this callback option. In this simple
case, @ref{c3,,optparse} doesn't even know if @code{-c} takes any arguments,
which usually means that the option takes no arguments---the mere presence of
@code{-c} on the command-line is all it needs to know.  In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments.  This is where writing callbacks gets tricky;
it's covered later in this section.

@ref{c3,,optparse} always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
@ref{3c5e,,callback_args} and @ref{3c5f,,callback_kwargs}.  Thus, the
minimal callback function signature is:

@example
def my_callback(option, opt, value, parser):
@end example

The four arguments to a callback are described below.

There are several other option attributes that you can supply when you define a
callback option:


@table @asis

@item @ref{3c2e,,type}

has its usual meaning: as with the @code{"store"} or @code{"append"} actions, it
instructs @ref{c3,,optparse} to consume one argument and convert it to
@ref{3c2e,,type}.  Rather than storing the converted value(s) anywhere,
though, @ref{c3,,optparse} passes it to your callback function.

@item @ref{3c5a,,nargs}

also has its usual meaning: if it is supplied and > 1, @ref{c3,,optparse} will
consume @ref{3c5a,,nargs} arguments, each of which must be convertible to
@ref{3c2e,,type}.  It then passes a tuple of converted values to your
callback.

@item @ref{3c5e,,callback_args}

a tuple of extra positional arguments to pass to the callback

@item @ref{3c5f,,callback_kwargs}

a dictionary of extra keyword arguments to pass to the callback
@end table

@node How callbacks are called,Raising errors in a callback,Defining a callback option,Option Callbacks
@anchor{library/optparse how-callbacks-are-called}@anchor{3c75}@anchor{library/optparse optparse-how-callbacks-called}@anchor{3c76}
@subsubsection How callbacks are called


All callbacks are called as follows:

@example
func(option, opt_str, value, parser, *args, **kwargs)
@end example

where


@table @asis

@item @code{option}

is the Option instance that's calling the callback

@item @code{opt_str}

is the option string seen on the command-line that's triggering the callback.
(If an abbreviated long option was used, @code{opt_str} will be the full,
canonical option string---e.g. if the user puts @code{--foo} on the
command-line as an abbreviation for @code{--foobar}, then @code{opt_str} will be
@code{"--foobar"}.)

@item @code{value}

is the argument to this option seen on the command-line.  @ref{c3,,optparse} will
only expect an argument if @ref{3c2e,,type} is set; the type of @code{value} will be
the type implied by the option's type.  If @ref{3c2e,,type} for this option is
@code{None} (no argument expected), then @code{value} will be @code{None}.  If @ref{3c5a,,nargs}
> 1, @code{value} will be a tuple of values of the appropriate type.

@item @code{parser}

is the OptionParser instance driving the whole thing, mainly useful because
you can access some other interesting data through its instance attributes:


@table @asis

@item @code{parser.largs}

the current list of leftover arguments, ie. arguments that have been
consumed but are neither options nor option arguments. Feel free to modify
@code{parser.largs}, e.g. by adding more arguments to it.  (This list will
become @code{args}, the second return value of @code{parse_args()}.)

@item @code{parser.rargs}

the current list of remaining arguments, ie. with @code{opt_str} and
@code{value} (if applicable) removed, and only the arguments following them
still there.  Feel free to modify @code{parser.rargs}, e.g. by consuming more
arguments.

@item @code{parser.values}

the object where option values are by default stored (an instance of
optparse.OptionValues).  This lets callbacks use the same mechanism as the
rest of @ref{c3,,optparse} for storing option values; you don't need to mess
around with globals or closures.  You can also access or modify the
value(s) of any options already encountered on the command-line.
@end table

@item @code{args}

is a tuple of arbitrary positional arguments supplied via the
@ref{3c5e,,callback_args} option attribute.

@item @code{kwargs}

is a dictionary of arbitrary keyword arguments supplied via
@ref{3c5f,,callback_kwargs}.
@end table

@node Raising errors in a callback,Callback example 1 trivial callback,How callbacks are called,Option Callbacks
@anchor{library/optparse optparse-raising-errors-in-callback}@anchor{3c77}@anchor{library/optparse raising-errors-in-a-callback}@anchor{3c78}
@subsubsection Raising errors in a callback


The callback function should raise @code{OptionValueError} if there are any
problems with the option or its argument(s).  @ref{c3,,optparse} catches this and
terminates the program, printing the error message you supply to stderr.  Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.

@node Callback example 1 trivial callback,Callback example 2 check option order,Raising errors in a callback,Option Callbacks
@anchor{library/optparse callback-example-1-trivial-callback}@anchor{3c79}@anchor{library/optparse optparse-callback-example-1}@anchor{3c7a}
@subsubsection Callback example 1: trivial callback


Here's an example of a callback option that takes no arguments, and simply
records that the option was seen:

@example
def record_foo_seen(option, opt_str, value, parser):
    parser.values.saw_foo = True

parser.add_option("--foo", action="callback", callback=record_foo_seen)
@end example

Of course, you could do that with the @code{"store_true"} action.

@node Callback example 2 check option order,Callback example 3 check option order generalized,Callback example 1 trivial callback,Option Callbacks
@anchor{library/optparse callback-example-2-check-option-order}@anchor{3c7b}@anchor{library/optparse optparse-callback-example-2}@anchor{3c7c}
@subsubsection Callback example 2: check option order


Here's a slightly more interesting example: record the fact that @code{-a} is
seen, but blow up if it comes after @code{-b} in the command-line.

@example
def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use -a after -b")
    parser.values.a = 1
...
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b")
@end example

@node Callback example 3 check option order generalized,Callback example 4 check arbitrary condition,Callback example 2 check option order,Option Callbacks
@anchor{library/optparse callback-example-3-check-option-order-generalized}@anchor{3c7d}@anchor{library/optparse optparse-callback-example-3}@anchor{3c7e}
@subsubsection Callback example 3: check option order (generalized)


If you want to re-use this callback for several similar options (set a flag, but
blow up if @code{-b} has already been seen), it needs a bit of work: the error
message and the flag that it sets must be generalized.

@example
def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use %s after -b" % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c')
@end example

@node Callback example 4 check arbitrary condition,Callback example 5 fixed arguments,Callback example 3 check option order generalized,Option Callbacks
@anchor{library/optparse callback-example-4-check-arbitrary-condition}@anchor{3c7f}@anchor{library/optparse optparse-callback-example-4}@anchor{3c80}
@subsubsection Callback example 4: check arbitrary condition


Of course, you could put any condition in there---you're not limited to checking
the values of already-defined options.  For example, if you have options that
should not be called when the moon is full, all you have to do is this:

@example
def check_moon(option, opt_str, value, parser):
    if is_moon_full():
        raise OptionValueError("%s option invalid when moon is full"
                               % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("--foo",
                  action="callback", callback=check_moon, dest="foo")
@end example

(The definition of @code{is_moon_full()} is left as an exercise for the reader.)

@node Callback example 5 fixed arguments,Callback example 6 variable arguments,Callback example 4 check arbitrary condition,Option Callbacks
@anchor{library/optparse callback-example-5-fixed-arguments}@anchor{3c81}@anchor{library/optparse optparse-callback-example-5}@anchor{3c82}
@subsubsection Callback example 5: fixed arguments


Things get slightly more interesting when you define callback options that take
a fixed number of arguments.  Specifying that a callback option takes arguments
is similar to defining a @code{"store"} or @code{"append"} option: if you define
@ref{3c2e,,type}, then the option takes one argument that must be
convertible to that type; if you further define @ref{3c5a,,nargs}, then the
option takes @ref{3c5a,,nargs} arguments.

Here's an example that just emulates the standard @code{"store"} action:

@example
def store_value(option, opt_str, value, parser):
    setattr(parser.values, option.dest, value)
...
parser.add_option("--foo",
                  action="callback", callback=store_value,
                  type="int", nargs=3, dest="foo")
@end example

Note that @ref{c3,,optparse} takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them.  (Or whatever;
obviously you don't need a callback for this example.)

@node Callback example 6 variable arguments,,Callback example 5 fixed arguments,Option Callbacks
@anchor{library/optparse callback-example-6-variable-arguments}@anchor{3c83}@anchor{library/optparse optparse-callback-example-6}@anchor{3c84}
@subsubsection Callback example 6: variable arguments


Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as @ref{c3,,optparse} doesn't provide any
built-in capabilities for it.  And you have to deal with certain intricacies of
conventional Unix command-line parsing that @ref{c3,,optparse} normally handles for
you.  In particular, callbacks should implement the conventional rules for bare
@code{--} and @code{-} arguments:


@itemize *

@item 
either @code{--} or @code{-} can be option arguments

@item 
bare @code{--} (if not the argument to some option): halt command-line
processing and discard the @code{--}

@item 
bare @code{-} (if not the argument to some option): halt command-line
processing but keep the @code{-} (append it to @code{parser.largs})
@end itemize

If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about.  The exact implementation you
choose will be based on which trade-offs you're willing to make for your
application (which is why @ref{c3,,optparse} doesn't support this sort of thing
directly).

Nevertheless, here's a stab at a callback for an option with variable
arguments:

@example
def vararg_callback(option, opt_str, value, parser):
    assert value is None
    value = []

    def floatable(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    for arg in parser.rargs:
        # stop on --foo like options
        if arg[:2] == "--" and len(arg) > 2:
            break
        # stop on -a, but not on -3 or -3.0
        if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
            break
        value.append(arg)

    del parser.rargs[:len(value)]
    setattr(parser.values, option.dest, value)

...
parser.add_option("-c", "--callback", dest="vararg_attr",
                  action="callback", callback=vararg_callback)
@end example

@node Extending optparse,,Option Callbacks,optparse --- 解析器的命令行选项
@anchor{library/optparse extending-optparse}@anchor{3c85}@anchor{library/optparse optparse-extending-optparse}@anchor{3c33}
@subsubsection Extending @code{optparse}


Since the two major controlling factors in how @ref{c3,,optparse} interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.

@menu
* Adding new types:: 
* Adding new actions:: 

@end menu

@node Adding new types,Adding new actions,,Extending optparse
@anchor{library/optparse adding-new-types}@anchor{3c86}@anchor{library/optparse optparse-adding-new-types}@anchor{3c87}
@subsubsection Adding new types


To add new types, you need to define your own subclass of @ref{c3,,optparse}'s
@code{Option} class.  This class has a couple of attributes that define
@ref{c3,,optparse}'s types: @ref{3c88,,TYPES} and @ref{3c89,,TYPE_CHECKER}.

@geindex TYPES (optparse.Option 属性)
@anchor{library/optparse optparse Option TYPES}@anchor{3c88}
@deffn {属性} Option.TYPES

A tuple of type names; in your subclass, simply define a new tuple
@ref{3c88,,TYPES} that builds on the standard one.
@end deffn

@geindex TYPE_CHECKER (optparse.Option 属性)
@anchor{library/optparse optparse Option TYPE_CHECKER}@anchor{3c89}
@deffn {属性} Option.TYPE_CHECKER

A dictionary mapping type names to type-checking functions.  A type-checking
function has the following signature:

@example
def check_mytype(option, opt, value)
@end example

where @code{option} is an @code{Option} instance, @code{opt} is an option string
(e.g., @code{-f}), and @code{value} is the string from the command line that must
be checked and converted to your desired type.  @code{check_mytype()} should
return an object of the hypothetical type @code{mytype}.  The value returned by
a type-checking function will wind up in the OptionValues instance returned
by @code{OptionParser.parse_args()}, or be passed to a callback as the
@code{value} parameter.

Your type-checking function should raise @code{OptionValueError} if it
encounters any problems.  @code{OptionValueError} takes a single string
argument, which is passed as-is to @ref{3c22,,OptionParser}'s @code{error()}
method, which in turn prepends the program name and the string @code{"error:"}
and prints everything to stderr before terminating the process.
@end deffn

Here's a silly example that demonstrates adding a @code{"complex"} option type to
parse Python-style complex numbers on the command line.  (This is even sillier
than it used to be, because @ref{c3,,optparse} 1.3 added built-in support for
complex numbers, but never mind.)

First, the necessary imports:

@example
from copy import copy
from optparse import Option, OptionValueError
@end example

You need to define your type-checker first, since it's referred to later (in the
@ref{3c89,,TYPE_CHECKER} class attribute of your Option subclass):

@example
def check_complex(option, opt, value):
    try:
        return complex(value)
    except ValueError:
        raise OptionValueError(
            "option %s: invalid complex value: %r" % (opt, value))
@end example

Finally, the Option subclass:

@example
class MyOption (Option):
    TYPES = Option.TYPES + ("complex",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["complex"] = check_complex
@end example

(If we didn't make a @ref{25,,copy()} of @ref{3c89,,Option.TYPE_CHECKER}, we would end
up modifying the @ref{3c89,,TYPE_CHECKER} attribute of @ref{c3,,optparse}'s
Option class.  This being Python, nothing stops you from doing that except good
manners and common sense.)

That's it!  Now you can write a script that uses the new option type just like
any other @ref{c3,,optparse}-based script, except you have to instruct your
OptionParser to use MyOption instead of Option:

@example
parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")
@end example

Alternately, you can build your own option list and pass it to OptionParser; if
you don't use @code{add_option()} in the above way, you don't need to tell
OptionParser which option class to use:

@example
option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)
@end example

@node Adding new actions,,Adding new types,Extending optparse
@anchor{library/optparse adding-new-actions}@anchor{3c8a}@anchor{library/optparse optparse-adding-new-actions}@anchor{3c8b}
@subsubsection Adding new actions


Adding new actions is a bit trickier, because you have to understand that
@ref{c3,,optparse} has a couple of classifications for actions:


@table @asis

@item "store" actions

actions that result in @ref{c3,,optparse} storing a value to an attribute of the
current OptionValues instance; these options require a @ref{3c2f,,dest}
attribute to be supplied to the Option constructor.

@item "typed" actions

actions that take a value from the command line and expect it to be of a
certain type; or rather, a string that can be converted to a certain type.
These options require a @ref{3c2e,,type} attribute to the Option
constructor.
@end table

These are overlapping sets: some default "store" actions are @code{"store"},
@code{"store_const"}, @code{"append"}, and @code{"count"}, while the default "typed"
actions are @code{"store"}, @code{"append"}, and @code{"callback"}.

When you add an action, you need to categorize it by listing it in at least one
of the following class attributes of Option (all are lists of strings):

@geindex ACTIONS (optparse.Option 属性)
@anchor{library/optparse optparse Option ACTIONS}@anchor{3c8c}
@deffn {属性} Option.ACTIONS

All actions must be listed in ACTIONS.
@end deffn

@geindex STORE_ACTIONS (optparse.Option 属性)
@anchor{library/optparse optparse Option STORE_ACTIONS}@anchor{3c8d}
@deffn {属性} Option.STORE_ACTIONS

"store" actions are additionally listed here.
@end deffn

@geindex TYPED_ACTIONS (optparse.Option 属性)
@anchor{library/optparse optparse Option TYPED_ACTIONS}@anchor{3c8e}
@deffn {属性} Option.TYPED_ACTIONS

"typed" actions are additionally listed here.
@end deffn

@geindex ALWAYS_TYPED_ACTIONS (optparse.Option 属性)
@anchor{library/optparse optparse Option ALWAYS_TYPED_ACTIONS}@anchor{3c8f}
@deffn {属性} Option.ALWAYS_TYPED_ACTIONS

Actions that always take a type (i.e. whose options always take a value) are
additionally listed here.  The only effect of this is that @ref{c3,,optparse}
assigns the default type, @code{"string"}, to options with no explicit type
whose action is listed in @ref{3c8f,,ALWAYS_TYPED_ACTIONS}.
@end deffn

In order to actually implement your new action, you must override Option's
@code{take_action()} method and add a case that recognizes your action.

For example, let's add an @code{"extend"} action.  This is similar to the standard
@code{"append"} action, but instead of taking a single value from the command-line
and appending it to an existing list, @code{"extend"} will take multiple values in
a single comma-delimited string, and extend an existing list with them.  That
is, if @code{--names} is an @code{"extend"} option of type @code{"string"}, the command
line

@example
--names=foo,bar --names blah --names ding,dong
@end example

would result in a list

@example
["foo", "bar", "blah", "ding", "dong"]
@end example

Again we define a subclass of Option:

@example
class MyOption(Option):

    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)
@end example

Features of note:


@itemize *

@item 
@code{"extend"} both expects a value on the command-line and stores that value
somewhere, so it goes in both @ref{3c8d,,STORE_ACTIONS} and
@ref{3c8e,,TYPED_ACTIONS}.

@item 
to ensure that @ref{c3,,optparse} assigns the default type of @code{"string"} to
@code{"extend"} actions, we put the @code{"extend"} action in
@ref{3c8f,,ALWAYS_TYPED_ACTIONS} as well.

@item 
@code{MyOption.take_action()} implements just this one new action, and passes
control back to @code{Option.take_action()} for the standard @ref{c3,,optparse}
actions.

@item 
@code{values} is an instance of the optparse_parser.Values class, which provides
the very useful @code{ensure_value()} method. @code{ensure_value()} is
essentially @ref{554,,getattr()} with a safety valve; it is called as

@example
values.ensure_value(attr, value)
@end example

If the @code{attr} attribute of @code{values} doesn't exist or is @code{None}, then
ensure_value() first sets it to @code{value}, and then returns 'value. This is
very handy for actions like @code{"extend"}, @code{"append"}, and @code{"count"}, all
of which accumulate data in a variable and expect that variable to be of a
certain type (a list for the first two, an integer for the latter).  Using
@code{ensure_value()} means that scripts using your action don't have to worry
about setting a default value for the option destinations in question; they
can just leave the default as @code{None} and @code{ensure_value()} will take care of
getting it right when it's needed.
@end itemize

@node ossaudiodev --- 访问兼容OSS的音频设备,pipes --- 终端管道接口,optparse --- 解析器的命令行选项,被取代的模块
@anchor{library/ossaudiodev doc}@anchor{3c90}@anchor{library/ossaudiodev module-ossaudiodev}@anchor{c6}@anchor{library/ossaudiodev ossaudiodev-access-to-oss-compatible-audio-devices}@anchor{3c91}
@subsection @code{ossaudiodev}  --- 访问兼容OSS的音频设备


@geindex ossaudiodev (模块)


3.11 版后已移除: @ref{c6,,ossaudiodev} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#ossaudiodev
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#ossaudiodev} 了解详情）。



__________________________________________________________________


该模块允许您访问 OSS（开放式音响系统）音频接口。 OSS 可用于广泛的开源和商业 Unices，并且是 Linux 和最新版本的 FreeBSD 的标准音频接口。

@c Things will get more complicated for future Linux versions, since
@c ALSA is in the standard kernel as of 2.5.x.  Presumably if you
@c use ALSA, you'll have to make sure its OSS compatibility layer
@c is active to use ossaudiodev, but you're going to need it for the vast
@c majority of Linux audio apps anyway.
@c 
@c Sounds like things are also complicated for other BSDs.  In response
@c to my python-dev query, Thomas Wouters said:
@c 
@c > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
@c > OSS installation manual tells you to remove references to OSS/Free from the
@c > kernel :)
@c 
@c but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
@c from its <soundcard.h>:
@c >  * WARNING!  WARNING!
@c >  * This is an OSS (Linux) audio emulator.
@c >  * Use the Native NetBSD API for developing new code, and this
@c >  * only for compiling Linux programs.
@c 
@c There's also an ossaudio manpage on OpenBSD that explains things
@c further.  Presumably NetBSD and OpenBSD have a different standard
@c audio interface.  That's the great thing about standards, there are so
@c many to choose from ... ;-)
@c 
@c This probably all warrants a footnote or two, but I don't understand
@c things well enough right now to write it!   --GPW


在 3.3 版更改: 此模块中过去会引发 @ref{a7c,,IOError} 的操作现在将引发 @ref{30b,,OSError}。



@subsubheading 参见



@table @asis

@item 开放之声系统程序员手册@footnote{http://www.opensound.com/pguide/oss.pdf}

OSS C API 的官方文档
@end table

该模块定义了大量由OSS设备驱动提供的常量； 请参阅`@w{`}<sys/soundcard.h>`@w{`} Linux 或 FreeBSD 上的列表。


@ref{c6,,ossaudiodev} 定义了下列变量和函数:

@geindex OSSAudioError
@anchor{library/ossaudiodev ossaudiodev OSSAudioError}@anchor{3c92}
@deffn {例外} ossaudiodev.OSSAudioError

此异常会针对特定错误被引发。 其参数为一个描述错误信息的字符串。

（如果 @ref{c6,,ossaudiodev} 从系统调用例如 @code{open()}, @code{write()} 或 @code{ioctl()} 接收到错误，它将引发 @ref{30b,,OSError}。 由 @ref{c6,,ossaudiodev} 直接检测到的错误将引发 @ref{3c92,,OSSAudioError}。）

（为了向下兼容，此异常类也可通过 @code{ossaudiodev.error} 访问。）
@end deffn

@geindex open() (在 ossaudiodev 模块中)
@anchor{library/ossaudiodev ossaudiodev open}@anchor{3c93}
@deffn {函数} ossaudiodev.open (mode)

@deffnx {函数} ossaudiodev.open (device, mode)

打开一个音频设备并返回 OSS 音频设备对象。 此对象支持许多文件类方法，例如 @code{read()}, @code{write()} 和 @code{fileno()} (不过传统的 Unix 读/写语义与 OSS 音频设备的存在一些细微的差异)。 它还支持一些音频专属的方法；完整的方法列表见下文。

@emph{device} 是要使用的音频设备文件名。 如果未指定，则此模块会先在环境变量 
@geindex AUDIODEV
@geindex 环境变量; AUDIODEV
@code{AUDIODEV} 中查找要使用的设备。 如果未找到，它将回退为 @code{/dev/dsp}。

@emph{mode} 可以为 @code{'r'} 表示只读（录音）访问，@code{'w'} 表示只写（回放）访问以及 @code{'rw'} 表示同时读写。 由于许多声卡在同一时间只允许单个进程打开录音机或播放器，因此好的做法是只根据活动的需要打开设备。 并且，有些声卡是半双工的：它们可以被打开用于读取或写入，但不能同时读写。

请注意这里特殊的调用语法: @emph{first} 参数是可选的，而第二个参数则是必需的。 这是出于历史原因要与 @ref{c6,,ossaudiodev} 所替代的 @code{linuxaudiodev} 模块保持兼容。

@c XXX it might also be motivated
@c by my unfounded-but-still-possibly-true belief that the default
@c audio device varies unpredictably across operating systems.  -GW
@end deffn

@geindex openmixer() (在 ossaudiodev 模块中)
@anchor{library/ossaudiodev ossaudiodev openmixer}@anchor{3c94}
@deffn {函数} ossaudiodev.openmixer ([device])

打开一个混音设备并返回 OSS 混音设备对象。 @emph{device} 是要使用的混音设备文件名。 如果未指定，则此模块会先在环境变量 
@geindex MIXERDEV
@geindex 环境变量; MIXERDEV
@code{MIXERDEV} 中查找要使用的设备。 如果未找到，它将回退为 @code{/dev/mixer}。
@end deffn

@menu
* 音频设备对象:: 
* 混音器设备对象:: 

@end menu

@node 音频设备对象,混音器设备对象,,ossaudiodev --- 访问兼容OSS的音频设备
@anchor{library/ossaudiodev audio-device-objects}@anchor{3c95}@anchor{library/ossaudiodev ossaudio-device-objects}@anchor{3c96}
@subsubsection 音频设备对象


在你写入或读取音频设备之前，你必须按照正确的顺序调用三个方法:


@enumerate 

@item 
@code{setfmt()} 设置输出格式

@item 
@code{channels()} 设置声道数量

@item 
@code{speed()} 设置采样率
@end enumerate

或者，你也可以使用 @code{setparameters()} 方法一次性地设置全部三个音频参数。 这更为便捷，但可能不会在所有场景下都一样灵活。

@ref{3c93,,open()} 所返回的音频设备对象定义了下列方法和（只读）属性:

@geindex close() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device close}@anchor{3c97}
@deffn {方法} oss_audio_device.close ()

显式地关闭音频设备。 当你完成写入或读取音频设备后，你应当显式地关闭它。 已关闭的设备不可被再次使用。
@end deffn

@geindex fileno() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device fileno}@anchor{3c98}
@deffn {方法} oss_audio_device.fileno ()

返回与设备相关联的文件描述符。
@end deffn

@geindex read() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device read}@anchor{3c99}
@deffn {方法} oss_audio_device.read (size)

从音频输入设备读取 @emph{size} 个字节并返回为 Python 字符串。 与大多数 Unix 设备驱动不同，处于阻塞模式（默认）的 OSS 音频设备将阻塞 @ref{3c99,,read()} 直到所请求大小的数据全部可用。
@end deffn

@geindex write() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device write}@anchor{3c9a}
@deffn {方法} oss_audio_device.write (data)

将一个 @ref{6e9,,bytes-like object} @emph{data} 写入音频设备并返回写入的字节数。 如果音频设备处于阻塞模式（默认），则总是会写入完整数据（这还是不同于通常的 Unix 设备语义）。 如果设备处于非阻塞模式，则可能会有部分数据未被写入 --- 参见 @ref{3c9b,,writeall()}。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn

@geindex writeall() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device writeall}@anchor{3c9b}
@deffn {方法} oss_audio_device.writeall (data)

将一个 @ref{6e9,,bytes-like object} @emph{data} 写入音频设备：等待直到音频设备能够接收数据，将根据其所能接收的数据量尽可能多地写入，并重复操作直至 @emph{data} 被完全写入。 如果设备处于阻塞模式（默认），则其效果与 @ref{3c9a,,write()} 相同；@ref{3c9b,,writeall()} 仅适用于非阻塞模式。 它没有返回值，因为写入的数据量总是等于所提供的数据量。


在 3.5 版更改: 现在支持可写的 @ref{6e9,,字节类对象}。

@end deffn


在 3.2 版更改: 音频设备对象还支持上下文管理协议，就是说它们可以在 @ref{7e4,,with} 语句中使用。


下列方法各自映射一个 @code{ioctl()} 系统调用。 对应关系很明显：例如，@code{setfmt()} 对应 @code{SNDCTL_DSP_SETFMT} ioctl，而 @code{sync()} 对应 @code{SNDCTL_DSP_SYNC} (这在查阅 OSS 文档时很有用)。 如果下层的 @code{ioctl()} 失败，它们将引发 @ref{30b,,OSError}。

@geindex nonblock() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device nonblock}@anchor{3c9c}
@deffn {方法} oss_audio_device.nonblock ()

将设备转为非阻塞模式。 一旦处于非阻塞模式，将无法将其转回阻塞模式。
@end deffn

@geindex getfmts() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device getfmts}@anchor{3c9d}
@deffn {方法} oss_audio_device.getfmts ()

返回声卡所支持的音频输出格式的位掩码。 OSS 支持的一部分格式如下:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件格式

@tab

描述

@item

@code{AFMT_MU_LAW}

@tab

一种对数编码格式（被 Sun @code{.au} 文件和 @code{/dev/audio} 所使用）

@item

@code{AFMT_A_LAW}

@tab

一种对数编码格式

@item

@code{AFMT_IMA_ADPCM}

@tab

一种 4:1 压缩格式，由 Interactive Multimedia Association 定义

@item

@code{AFMT_U8}

@tab

无符号的 8 位音频

@item

@code{AFMT_S16_LE}

@tab

有符号的 16 位音频，采用小端字节序（如 Intel 处理器所用的）

@item

@code{AFMT_S16_BE}

@tab

有符号的 16 位音频，采用大端字节序（如 68k, PowerPC, Sparc 所用的）

@item

@code{AFMT_S8}

@tab

有符号的 8 位音频

@item

@code{AFMT_U16_LE}

@tab

无符号的 16 位小端字节序音频

@item

@code{AFMT_U16_BE}

@tab

无符号的 16 位大端字节序音频

@end multitable


请参阅 OSS 文档获取音频格式的完整列表，还要注意大多数设备都只支持这些列表的一个子集。 某些较旧的设备仅支持 @code{AFMT_U8}；目前最为常用的格式是 @code{AFMT_S16_LE}。
@end deffn

@geindex setfmt() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device setfmt}@anchor{3c9e}
@deffn {方法} oss_audio_device.setfmt (format)

尝试将当前音频格式设为 @emph{format} --- 请参阅 @ref{3c9d,,getfmts()} 获取格式列表。 返回为设备设置的音频格式，这可能并非所请求的格式。 也可被用来返回当前音频格式 --- 这可以通过传入特殊的 "音频格式" @code{AFMT_QUERY} 来实现。
@end deffn

@geindex channels() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device channels}@anchor{3c9f}
@deffn {方法} oss_audio_device.channels (nchannels)

将输出声道数设为 @emph{nchannels}。 值为 1 表示单声道，2 表示立体声。 某些设备可能拥有 2 个以上的声道，并且某些高端设备还可能不支持单声道。 返回为设备设置的声道数。
@end deffn

@geindex speed() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device speed}@anchor{3ca0}
@deffn {方法} oss_audio_device.speed (samplerate)

尝试将音频采样率设为每秒 @emph{samplerate} 次采样。 返回实际设置的采样率。 大多数设备都不支持任意的采样率。 常见的采样率为:


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

采样率

@tab

描述

@item

8000

@tab

@code{/dev/audio} 的默认采样率

@item

11025

@tab

语音录音

@item

22050

@tab

@item

44100

@tab

CD品质的音频（16位采样和2通道）

@item

96000

@tab

DVD品质的音频（24位采样）

@end multitable

@end deffn

@geindex sync() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device sync}@anchor{3ca1}
@deffn {方法} oss_audio_device.sync ()

等待直到音频设备播放完其缓冲区中的所有字节。 （这会在设备被关闭时隐式地发生。） OSS 建议关闭再重新打开设备而不是使用 @ref{3ca1,,sync()}。
@end deffn

@geindex reset() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device reset}@anchor{3ca2}
@deffn {方法} oss_audio_device.reset ()

立即停止播放或录制并使设备返回可接受命令的状态。 OSS 文档建议在调用 @ref{3ca2,,reset()} 之后关闭并重新打开设备。
@end deffn

@geindex post() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device post}@anchor{3ca3}
@deffn {方法} oss_audio_device.post ()

告知设备在输出中可能有暂停，使得设备可以更智能地处理暂停。 你可以在播放一个定点音效之后、等待用户输入之前或执行磁盘 I/O 之前使用此方法。
@end deffn

下列便捷方法合并了多个 ioctl，或是合并了一个 ioctl 与某些简单的运算。

@geindex setparameters() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device setparameters}@anchor{3ca4}
@deffn {方法} oss_audio_device.setparameters (format, nchannels, samplerate[, strict=False])

在一次方法调用中设置关键的音频采样参数 --- 采样格式、声道数和采样率。 @emph{format},  @emph{nchannels} 和 @emph{samplerate} 应当与在 @ref{3c9e,,setfmt()}, @ref{3c9f,,channels()} 和 @ref{3ca0,,speed()}  方法中所指定的一致。 如果 @emph{strict} 为真值，则 @ref{3ca4,,setparameters()} 会检查每个参数是否确实被设置为所请求的值，如果不是则会引发 @ref{3c92,,OSSAudioError}。 返回一个元组 (@emph{format}, @emph{nchannels}, @emph{samplerate}) 指明由设备驱动实际设置的参数值 (即与 @ref{3c9e,,setfmt()}, @ref{3c9f,,channels()} 和 @ref{3ca0,,speed()} 的返回值相同)。

例如，:

@example
(fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
@end example

等价于

@example
fmt = dsp.setfmt(fmt)
channels = dsp.channels(channels)
rate = dsp.rate(rate)
@end example
@end deffn

@geindex bufsize() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device bufsize}@anchor{3ca5}
@deffn {方法} oss_audio_device.bufsize ()

返回硬件缓冲区的大小，以采样数表示。
@end deffn

@geindex obufcount() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device obufcount}@anchor{3ca6}
@deffn {方法} oss_audio_device.obufcount ()

返回硬件缓冲区中待播放的采样数。
@end deffn

@geindex obuffree() (ossaudiodev.oss_audio_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device obuffree}@anchor{3ca7}
@deffn {方法} oss_audio_device.obuffree ()

返回可以被加入硬件缓冲区队列以非阻塞模式播放的采样数。
@end deffn

音频设备对象还支持几个只读属性:

@geindex closed (ossaudiodev.oss_audio_device 属性)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device closed}@anchor{3ca8}
@deffn {属性} oss_audio_device.closed

指明设备是否已被关闭的布尔值。
@end deffn

@geindex name (ossaudiodev.oss_audio_device 属性)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device name}@anchor{3ca9}
@deffn {属性} oss_audio_device.name

包含设备文件名称的字符串。
@end deffn

@geindex mode (ossaudiodev.oss_audio_device 属性)
@anchor{library/ossaudiodev ossaudiodev oss_audio_device mode}@anchor{3caa}
@deffn {属性} oss_audio_device.mode

文件的 I/O 模式，可以为 @code{"r"}, @code{"rw"} 或 @code{"w"}。
@end deffn

@node 混音器设备对象,,音频设备对象,ossaudiodev --- 访问兼容OSS的音频设备
@anchor{library/ossaudiodev id1}@anchor{3cab}@anchor{library/ossaudiodev mixer-device-objects}@anchor{3cac}
@subsubsection 混音器设备对象


混音器对象提供了两个文件类方法:

@geindex close() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device close}@anchor{3cad}
@deffn {方法} oss_mixer_device.close ()

此方法会关闭打开的混音器设备文件。 在文件被关闭后任何继续使用混音器的尝试都将引发 @ref{30b,,OSError}。
@end deffn

@geindex fileno() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device fileno}@anchor{3cae}
@deffn {方法} oss_mixer_device.fileno ()

返回打开的混音器设备文件的文件处理句柄号。
@end deffn


在 3.2 版更改: 混音器设备还支持上下文管理协议。


其余方法都是混音专属的:

@geindex controls() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device controls}@anchor{3caf}
@deffn {方法} oss_mixer_device.controls ()

此方法返回一个表示可用的混音控件的位掩码 ("控件" 是专用的可混合 "声道"，例如 @code{SOUND_MIXER_PCM} 或 @code{SOUND_MIXER_SYNTH})。 该掩码会指定所有可用混音控件的一个子集 --- 它们是在模块层级上定义的 @code{SOUND_MIXER_*} 常量。 举例来说，要确定当前混音器对象是否支持 PCM 混音器，就使用以下 Python 代码:

@example
mixer=ossaudiodev.openmixer()
if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
    # PCM is supported
    ... code ...
@end example

对于大多数目的来说，@code{SOUND_MIXER_VOLUME} (主音量) 和 @code{SOUND_MIXER_PCM} 控件应该足够了 --- 但使用混音器的代码应当在选择混音器控件时保持灵活。 例如在 Gravis Ultrasound 上，@code{SOUND_MIXER_VOLUME} 是不存在的。
@end deffn

@geindex stereocontrols() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device stereocontrols}@anchor{3cb0}
@deffn {方法} oss_mixer_device.stereocontrols ()

返回一个表示立体声混音控件的位掩码。 如果设置了比特位，则对应的控件就是立体声的；如果未设置，则控件为单声道或者不被混音器所支持（请配合 @ref{3caf,,controls()} 使用以确定是哪种情况）。

请查看 @ref{3caf,,controls()} 函数的代码示例了解如何从位掩码获取数据。
@end deffn

@geindex reccontrols() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device reccontrols}@anchor{3cb1}
@deffn {方法} oss_mixer_device.reccontrols ()

返回一个指明可被用于录音的混音器控件的位掩码。 请查看 @ref{3caf,,controls()} 的代码示例了解如何读取位掩码。
@end deffn

@geindex get() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device get}@anchor{3cb2}
@deffn {方法} oss_mixer_device.get (control)

返回给定混音控件的音量。 返回的音量是一个 2 元组 @code{(left_volume,right_volume)}。 音量被表示为从 0 (静音) 到 100 (最大音量) 的数字。 如果控件是单声道的，仍然会返回一个 2 元组，但两个音量必定相同。

如果指定了无效的控件则会引发 @ref{3c92,,OSSAudioError}，或者如果指定了不受支持的控件则会引发 @ref{30b,,OSError}。
@end deffn

@geindex set() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device set}@anchor{3cb3}
@deffn {方法} oss_mixer_device.set (control, (left, right))

将给定混音控件的音量设为 @code{(left,right)}。 @code{left} 和 @code{right} 必须为整数并在 0 (静音) 至 100 (最大音量) 之间。 当执行成功的，新的音量将以 2 元组形式返回。 请注意这可能不完全等于所指定的音量，因为某些声卡的混音器有精度限制。

如果指定了无效的混音控件，或者指定的音量超出限制则会引发 @ref{3c92,,OSSAudioError}。
@end deffn

@geindex get_recsrc() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device get_recsrc}@anchor{3cb4}
@deffn {方法} oss_mixer_device.get_recsrc ()

此方法返回一个表示当前被用作录音源的的控件的位掩码。
@end deffn

@geindex set_recsrc() (ossaudiodev.oss_mixer_device 方法)
@anchor{library/ossaudiodev ossaudiodev oss_mixer_device set_recsrc}@anchor{3cb5}
@deffn {方法} oss_mixer_device.set_recsrc (bitmask)

调用此函数来指定一个录音源。 如果成功则返回一个指明新录音源的位掩码；如果指定了无效的源则会引发 @ref{30b,,OSError}。 如果要将当前录音源设为麦克风输入:

@example
mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
@end example
@end deffn

@node pipes --- 终端管道接口,smtpd --- SMTP 服务器,ossaudiodev --- 访问兼容OSS的音频设备,被取代的模块
@anchor{library/pipes doc}@anchor{3cb6}@anchor{library/pipes module-pipes}@anchor{cc}@anchor{library/pipes pipes-interface-to-shell-pipelines}@anchor{3cb7}
@subsection @code{pipes} --- 终端管道接口


@geindex pipes (模块)

@strong{源代码：} Lib/pipes.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/pipes.py}


3.11 版后已移除: @ref{cc,,pipes} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#pipes
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#pipes} 了解详情）。 请改用 @ref{f9,,subprocess} 模块。



__________________________________________________________________


@ref{cc,,pipes} 定义了一个类用来抽象 @emph{pipeline} 的概念 --- 将数据从一个文件转到另一文件的转换器序列。

由于模块使用了 @code{/bin/sh} 命令行，因此要求有 POSIX 或兼容 @ref{e8e,,os.system()} 和 @ref{3d3,,os.popen()} 的终端程序。

@ref{cc,,pipes} 模块定义了以下的类:

@geindex Template (pipes 中的类)
@anchor{library/pipes pipes Template}@anchor{3cb8}
@deffn {类} pipes.Template

对管道的抽象。
@end deffn

示例:

@example
>>> import pipes
>>> t = pipes.Template()
>>> t.append('tr a-z A-Z', '--')
>>> f = t.open('pipefile', 'w')
>>> f.write('hello world')
>>> f.close()
>>> open('pipefile').read()
'HELLO WORLD'
@end example

@menu
* 模板对象:: 

@end menu

@node 模板对象,,,pipes --- 终端管道接口
@anchor{library/pipes id1}@anchor{3cb9}@anchor{library/pipes template-objects}@anchor{3cba}
@subsubsection 模板对象


模板对象有以下方法:

@geindex reset() (pipes.Template 方法)
@anchor{library/pipes pipes Template reset}@anchor{3cbb}
@deffn {方法} Template.reset ()

将一个管道模板恢复为初始状态。
@end deffn

@geindex clone() (pipes.Template 方法)
@anchor{library/pipes pipes Template clone}@anchor{3cbc}
@deffn {方法} Template.clone ()

返回一个新的等价的管道模板。
@end deffn

@geindex debug() (pipes.Template 方法)
@anchor{library/pipes pipes Template debug}@anchor{3cbd}
@deffn {方法} Template.debug (flag)

如果 @emph{flag} 为真值，则启用调试。 否则禁用调试。 当启用调试时，要执行的命令会被打印出来，并且会给予终端 @code{set -x} 命令以输出更详细的信息。
@end deffn

@geindex append() (pipes.Template 方法)
@anchor{library/pipes pipes Template append}@anchor{3cbe}
@deffn {方法} Template.append (cmd, kind)

在末尾添加一个新的动作。 @emph{cmd} 变量必须为一个有效的 bourne 终端命令。 @emph{kind} 变量由两个字母组成。

第一个字母可以为 @code{'-'} (这表示命令将读取其标准输入), @code{'f'} (这表示命令将读取在命令行中给定的文件) 或 @code{'.'} (这表示命令将不读取输入，因而必须放在前面。)

类似地，第二个字母可以为 @code{'-'} (这表示命令将写入到标准输出), @code{'f'} (这表示命令将写入在命令行中给定的文件) 或 @code{'.'} (这表示命令将不执行写入，因而必须放在末尾。)
@end deffn

@geindex prepend() (pipes.Template 方法)
@anchor{library/pipes pipes Template prepend}@anchor{3cbf}
@deffn {方法} Template.prepend (cmd, kind)

在开头添加一个新的动作。 请参阅 @ref{3cbe,,append()} 获取相应参数的说明。
@end deffn

@geindex open() (pipes.Template 方法)
@anchor{library/pipes pipes Template open}@anchor{3cc0}
@deffn {方法} Template.open (file, mode)

返回一个文件类对象，打开到 @emph{file}，但是将从管道读取或写入。 请注意只能给出 @code{'r'}, @code{'w'} 中的一个。
@end deffn

@geindex copy() (pipes.Template 方法)
@anchor{library/pipes pipes Template copy}@anchor{3cc1}
@deffn {方法} Template.copy (infile, outfile)

通过管道将 @emph{infile} 拷贝到 @emph{outfile}。
@end deffn

@node smtpd --- SMTP 服务器,sndhdr --- 推测声音文件的类型,pipes --- 终端管道接口,被取代的模块
@anchor{library/smtpd doc}@anchor{3cc2}@anchor{library/smtpd module-smtpd}@anchor{ec}@anchor{library/smtpd smtpd-smtp-server}@anchor{3cc3}
@subsection @code{smtpd} --- SMTP 服务器


@geindex smtpd (模块)

@strong{源代码:} Lib/smtpd.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/smtpd.py}


__________________________________________________________________


该模块提供了几个类来实现 SMTP （电子邮件）服务器。


3.6 版后已移除: @ref{ec,,smtpd} 将在 Python 3.12 中移除（请参阅 
@geindex Python 提高建议; PEP 594#smtpd
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#smtpd} 了解详情）。 aiosmtpd@footnote{https://aiosmtpd.readthedocs.io/} 包是这个模块的推荐替代品。 它基于 @ref{9,,asyncio} 并提供了更简洁直观的 API。


有几个服务器的实现；一个是通用的无为实现，可以被重写，而另外两个则提供特定的邮件发送策略。

此外， SMTPChannel 可以被扩展以实现与 SMTP 客户端非常具体的交互行为。

该代码支持 
@geindex RFC; RFC 5321
RFC 5321@footnote{https://tools.ietf.org/html/rfc5321.html} ，加上 
@geindex RFC; RFC 1870
RFC 1870@footnote{https://tools.ietf.org/html/rfc1870.html} SIZE和 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html} SMTPUTF8 扩展。

@menu
* SMTPServer 对象:: 
* DebuggingServer 对象:: 
* PureProxy对象:: 
* MailmanProxy 对象:: 
* SMTPChannel 对象:: 

@end menu

@node SMTPServer 对象,DebuggingServer 对象,,smtpd --- SMTP 服务器
@anchor{library/smtpd smtpserver-objects}@anchor{3cc4}
@subsubsection SMTPServer 对象


@geindex SMTPServer (smtpd 中的类)
@anchor{library/smtpd smtpd SMTPServer}@anchor{703}
@deffn {类} smtpd.SMTPServer (localaddr, remoteaddr, data_size_limit=33554432, map=None, enable_SMTPUTF8=False, decode_data=False)

新建一个 @ref{703,,SMTPServer} 对象，它会绑定到本机地址 @emph{localaddr}。 它将把 @emph{remoteaddr} 当作上游 SMTP 中继器。 @emph{localaddr} 和 @emph{remoteaddr} 都应当是 @ref{27c6,,(host@comma{} port)} 元组。 该对象继承自 @ref{c99,,asyncore.dispatcher}，因而会在实例化时将自己插入到 @ref{a,,asyncore} 的事件循环。

@emph{data_size_limit} 指定将在 @code{DATA} 命令中被接受的最大字节数。 值为 @code{None} 或 @code{0} 表示无限制。

@emph{map} 是用于连接的套接字映射（初始为空的字典是适当的值）。 如果未指定则会使用 @ref{a,,asyncore} 全局套接字映射。

@emph{enable_SMTPUTF8} 决定是否应当启用 @code{SMTPUTF8} 扩展（如 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html} 所定义的。 默认值为 @code{False}。 当设为 @code{True} 时，会接受 @code{SMTPUTF8} 作为 @code{MAIL} 命令的形参并在被提供时将其传给 @code{kwargs['mail_options']} 列表中的 @ref{704,,process_message()}。 @emph{decode_data} 和 @emph{enable_SMTPUTF8} 不可同时被设为 @code{True}。

@emph{decode_data} 指明 SMTP 事务的数据部分是否应当使用 UTF-8 来解码。 当 @emph{decode_data} 为 @code{False} 时（默认值），服务器会声明 @code{8BITMIME} 扩展 (
@geindex RFC; RFC 6152
RFC 6152@footnote{https://tools.ietf.org/html/rfc6152.html})，接受来自 @code{MAIL} 命令的 @code{BODY=8BITMIME} 形参，并在该形参存在时将其传给 @code{kwargs['mail_options']} 列表中的 @ref{704,,process_message()} 方法。 @emph{decode_data} 和 @emph{enable_SMTPUTF8} 不可同时被设为 @code{True}。

@geindex process_message() (smtpd.SMTPServer 方法)
@anchor{library/smtpd smtpd SMTPServer process_message}@anchor{704}
@deffn {方法} process_message (peer, mailfrom, rcpttos, data, **kwargs)

引发 @ref{70e,,NotImplementedError} 异常。 请在子类中重载此方法以实际运用此消息。 在构造器中作为 @emph{remoteaddr} 传入的任何东西都可以 @code{_remoteaddr} 属性的形式来访问。 @emph{peer} 是远程主机的地址，@emph{mailfrom} 是封包的发送方，@emph{rcpttos} 是封包的接收方而 @emph{data} 是包含电子邮件内容的字符串（应该为 
@geindex RFC; RFC 5321
RFC 5321@footnote{https://tools.ietf.org/html/rfc5321.html} 格式）。

如果构造器关键字参数 @emph{decode_data} 被设为 @code{True}，则 @emph{data} 参数将为 Unicode 字符串。 如果被设为 @code{False}，则将为字节串对象。

@emph{kwargs} 是包含附加信息的字典。 如果给出 @code{decode_data=True} 作为初始参数则该字典为空，否则它会包含以下的键:

@quotation


@table @asis

@item @emph{mail_options}:

由 @code{MAIL} 命令所接收的所有参数组成的列表 (其元素为大写形式的字符串；例如: @code{['BODY=8BITMIME', 'SMTPUTF8']})。

@item @emph{rcpt_options}:

与 @emph{mail_options} 类似但是针对 @code{RCPT} 命令。 目前不支持任何 @code{RCPT TO} 选项，因此其值将总是为空列表。
@end table
@end quotation

@code{process_message} 的实现应当使用 @code{**kwargs} 签名来接收任意关键字参数，因为未来的增强特性可能会向 kwargs 字典添加新键。

返回 @code{None} 以请求一个正常的 @code{250 Ok} 响应；在其他情况下则以 
@geindex RFC; RFC 5321
RFC 5321@footnote{https://tools.ietf.org/html/rfc5321.html} 格式返回所需的响应字符串。
@end deffn

@geindex channel_class (smtpd.SMTPServer 属性)
@anchor{library/smtpd smtpd SMTPServer channel_class}@anchor{3cc5}
@deffn {属性} channel_class

重载这个子类以使用自定义的 @ref{702,,SMTPChannel} 来管理 SMTP 客户端。
@end deffn


3.4 新版功能: @emph{map} 构造器参数。



在 3.5 版更改: @emph{localaddr} 和 @emph{remoteaddr} 现在可以包含 IPv6 地址。



3.5 新版功能: @emph{decode_data} 和 @emph{enable_SMTPUTF8} 构造器形参，以及当 @emph{decode_data} 为 @code{False} 时传给 @ref{704,,process_message()} 的 @emph{kwargs} 形参。



在 3.6 版更改: @emph{decode_data} 现在默认为 @code{False}。

@end deffn

@node DebuggingServer 对象,PureProxy对象,SMTPServer 对象,smtpd --- SMTP 服务器
@anchor{library/smtpd debuggingserver-objects}@anchor{3cc6}
@subsubsection DebuggingServer 对象


@geindex DebuggingServer (smtpd 中的类)
@anchor{library/smtpd smtpd DebuggingServer}@anchor{3cc7}
@deffn {类} smtpd.DebuggingServer (localaddr, remoteaddr)

创建一个新的调试服务器。 参数是针对每个 @ref{703,,SMTPServer}。 消息将被丢弃，并在 stdout 上打印出来。
@end deffn

@node PureProxy对象,MailmanProxy 对象,DebuggingServer 对象,smtpd --- SMTP 服务器
@anchor{library/smtpd pureproxy-objects}@anchor{3cc8}
@subsubsection PureProxy对象


@geindex PureProxy (smtpd 中的类)
@anchor{library/smtpd smtpd PureProxy}@anchor{3cc9}
@deffn {类} smtpd.PureProxy (localaddr, remoteaddr)

创建一个新的纯代理服务器。 参数是针对每个 @ref{703,,SMTPServer}。 一切都将被转发到 @emph{remoteaddr}。 请注意运行此对象有很大的机会令你成为一个开放的中继站，所以需要小心。
@end deffn

@node MailmanProxy 对象,SMTPChannel 对象,PureProxy对象,smtpd --- SMTP 服务器
@anchor{library/smtpd mailmanproxy-objects}@anchor{3cca}
@subsubsection MailmanProxy 对象


@geindex MailmanProxy (smtpd 中的类)
@anchor{library/smtpd smtpd MailmanProxy}@anchor{212}
@deffn {类} smtpd.MailmanProxy (localaddr, remoteaddr)


Deprecated since version 3.9, will be removed in version 3.11: @ref{212,,MailmanProxy} 已被弃用，它依赖于一个已不存在的 @code{Mailman} 模块因而本来就不再可用了。


创建一个新的纯代理服务器。 参数是针对每个 @ref{703,,SMTPServer}。 一切都将被转发到 @emph{remoteaddr}，除非本地 mailman 配置知道另一个地址，在那种情况下它将由 mailman 来处理。 请注意运行此对象有很大的机会令你成为一个开放的中继站，所以需要小心。
@end deffn

@node SMTPChannel 对象,,MailmanProxy 对象,smtpd --- SMTP 服务器
@anchor{library/smtpd smtpchannel-objects}@anchor{3ccb}
@subsubsection SMTPChannel 对象


@geindex SMTPChannel (smtpd 中的类)
@anchor{library/smtpd smtpd SMTPChannel}@anchor{702}
@deffn {类} smtpd.SMTPChannel (server, conn, addr, data_size_limit=33554432, map=None, enable_SMTPUTF8=False, decode_data=False)

创建一个新的 @ref{702,,SMTPChannel} 对象，该对象会管理服务器和单个 SMTP 客户端之间的通信。

@emph{conn} 和 @emph{addr} 是针对下述的每个实例变量。

@emph{data_size_limit} 指定将在 @code{DATA} 命令中被接受的最大字节数。 值为 @code{None} 或 @code{0} 表示无限制。

@emph{enable_SMTPUTF8} 确定 @code{SMTPUTF8} 扩展 (如 
@geindex RFC; RFC 6531
RFC 6531@footnote{https://tools.ietf.org/html/rfc6531.html} 所定义的) 是否应当被启用。 默认值为 @code{False}。 @emph{decode_data} 和 @emph{enable_SMTPUTF8} 不能被同时设为 @code{True}。

可以在 @emph{map} 中指定一个字典以避免使用全局套接字映射。

@emph{decode_data} 指明 SMTP 事务的数据部分是否应当使用 UTF-8 来解码。 默认值为 @code{False}。 @emph{decode_data} 和 @emph{enable_SMTPUTF8} 不能被同时设为 @code{True}。

要使用自定义的 SMTPChannel 实现你必须重载你的 @ref{703,,SMTPServer} 的 @ref{3cc5,,SMTPServer.channel_class}。


在 3.5 版更改: 添加了 @emph{decode_data} 和 @emph{enable_SMTPUTF8} 形参。



在 3.6 版更改: @emph{decode_data} 现在默认为 @code{False}。


@ref{702,,SMTPChannel} 具有下列实例变量:

@geindex smtp_server (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel smtp_server}@anchor{3ccc}
@deffn {属性} smtp_server

存放生成此通道的 @ref{703,,SMTPServer}。
@end deffn

@geindex conn (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel conn}@anchor{3ccd}
@deffn {属性} conn

存放连接到客户端的套接字对象。
@end deffn

@geindex addr (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel addr}@anchor{3cce}
@deffn {属性} addr

存放客户端的地址，@ref{772,,socket.accept} 所返回的第二个值。
@end deffn

@geindex received_lines (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel received_lines}@anchor{3ccf}
@deffn {属性} received_lines

存放从客户端接收的行字符串列表 (使用 UTF-8 解码)。 所有行的 @code{"\r\n"} 行结束符都会被转写为 @code{"\n"}。
@end deffn

@geindex smtp_state (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel smtp_state}@anchor{3cd0}
@deffn {属性} smtp_state

存放通道的当前状态。 其初始值将为 @code{COMMAND} 而在客户端发送 "DATA" 行后将为 @code{DATA}。
@end deffn

@geindex seen_greeting (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel seen_greeting}@anchor{3cd1}
@deffn {属性} seen_greeting

存放包含客户端在其 "HELO" 中发送的问候信息的字符串。
@end deffn

@geindex mailfrom (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel mailfrom}@anchor{3cd2}
@deffn {属性} mailfrom

存放包含客户端在 "MAIL FROM:" 中标识的地址的字符串。
@end deffn

@geindex rcpttos (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel rcpttos}@anchor{3cd3}
@deffn {属性} rcpttos

存放包含客户端在 "RCPT TO:" 行中标识的地址的字符串。
@end deffn

@geindex received_data (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel received_data}@anchor{3cd4}
@deffn {属性} received_data

存放客户端在 DATA 状态期间发送的所有数据的字符串，直至但不包括末尾的 @code{"\r\n.\r\n"}。
@end deffn

@geindex fqdn (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel fqdn}@anchor{3cd5}
@deffn {属性} fqdn

存放由 @ref{27eb,,socket.getfqdn()} 所返回的服务器完整限定域名。
@end deffn

@geindex peer (smtpd.SMTPChannel 属性)
@anchor{library/smtpd smtpd SMTPChannel peer}@anchor{3cd6}
@deffn {属性} peer

存放由 @code{conn.getpeername()} 所返回的客户端对等方名称，其中 @code{conn} 为 @ref{3ccd,,conn}。
@end deffn

@ref{702,,SMTPChannel} 在接收到来自客户端的命令行时会通过发起调用名为 @code{smtp_<command>} 的方法来进行操作。 在基类 @ref{702,,SMTPChannel} 中具有用于处理下列命令（并对他们作出适当反应）的方法:


@multitable {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

命令

@tab

所采取的行动

@item

HELO

@tab

接受来自客户端的问候语，并将其存储在 @ref{3cd1,,seen_greeting} 中。将服务器设置为基本命令模式。

@item

EHLO

@tab

接受来自客户的问候并将其存储在 @ref{3cd1,,seen_greeting} 中。将服务器设置为扩展命令模式。

@item

NOOP

@tab

不采取任何措施。

@item

QUIT

@tab

干净地关闭连接。

@item

MAIL

@tab

接受 "MAIL FROM:" 句法并将所提供的地址保存为 @ref{3cd2,,mailfrom}。 在扩展命令模式下，还接受 
@geindex RFC; RFC 1870
RFC 1870@footnote{https://tools.ietf.org/html/rfc1870.html} SIZE 属性并根据 @emph{data_size_limit} 的值作出适当返回。

@item

RCPT

@tab

接受 "RCPT TO:" 句法并将所提供的地址保存在 @ref{3cd3,,rcpttos} 列表中。

@item

RSET

@tab

重置 @ref{3cd2,,mailfrom}, @ref{3cd3,,rcpttos}, 和 @ref{3cd4,,received_data} ，但不重置问候语。

@item

DATA

@tab

将内部状态设为 @code{DATA} 并将来自客户端的剩余行保存在 @ref{3cd4,,received_data} 中直至接收到终止符 @code{"\r\n.\r\n"}。

@item

HELP

@tab

返回有关命令语法的最少信息

@item

VRFY

@tab

返回代码252（服务器不知道该地址是否有效）

@item

EXPN

@tab

报告该命令未实现。

@end multitable

@end deffn

@node sndhdr --- 推测声音文件的类型,spwd —— shadow 密码库,smtpd --- SMTP 服务器,被取代的模块
@anchor{library/sndhdr doc}@anchor{3cd7}@anchor{library/sndhdr module-sndhdr}@anchor{ee}@anchor{library/sndhdr sndhdr-determine-type-of-sound-file}@anchor{3cd8}
@subsection @code{sndhdr} --- 推测声音文件的类型


@geindex sndhdr (模块)

@c Based on comments in the module source file.

@strong{源代码} Lib/sndhdr.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/sndhdr.py}

@geindex A-LAW
@geindex u-LAW


3.11 版后已移除: @ref{ee,,sndhdr} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#sndhdr
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#sndhdr} 了解详情及其替代品）。



__________________________________________________________________


@ref{ee,,sndhdr} 提供了企图猜测文件中的声音数据类型的功能函数。当这些函数可以推测出存储在文件中的声音数据的类型是，它们返回一个 @ref{1a1,,collections.namedtuple()}，包含了五种属性：（@code{filetype}, @code{framerate}, @code{nchannels}, @code{nframes}, @code{sampwidth}）。这些 @emph{type} 的值表示数据的类型，会是以下字符串之一： @code{'aifc'}, @code{'aiff'}, @code{'au'}, @code{'hcom'}, @code{'sndr'}, @code{'sndt'}, @code{'voc'}, @code{'wav'}, @code{'8svx'}, @code{'sb'}, @code{'ub'}, or @code{'ul'} 。 @emph{sampling_rate} 可能是实际值或者当未知或者难以解码时的 @code{0}。类似的， @emph{channels} 也会返回实际值或者在无法推测或者难以解码时返回 @code{0}。 @emph{frames} 则是实际值或 @code{-1}。 元组的最后一项， @emph{bits_per_sample} 将会为比特表示的 sample 大小或者 A-LAW 时为 @code{'A'}， u-LAW 时为 @code{'U'}。

@geindex what() (在 sndhdr 模块中)
@anchor{library/sndhdr sndhdr what}@anchor{840}
@deffn {函数} sndhdr.what (filename)

使用 @ref{841,,whathdr()} 推测存储在 @emph{filename} 文件中的声音数据的类型。如果成功，返回上述的命名元组，否则返回 @code{None}。


在 3.5 版更改: 将结果从元组改为命名元组。

@end deffn

@geindex whathdr() (在 sndhdr 模块中)
@anchor{library/sndhdr sndhdr whathdr}@anchor{841}
@deffn {函数} sndhdr.whathdr (filename)

基于文件头推测存储在文件中的声音数据类型。文件名由 @emph{filename} 给出。这个函数在成功时返回上述命名元组，或者在失败时返回 @code{None}。


在 3.5 版更改: 将结果从元组改为命名元组。

@end deffn

@node spwd —— shadow 密码库,sunau --- 读写 Sun AU 文件,sndhdr --- 推测声音文件的类型,被取代的模块
@anchor{library/spwd doc}@anchor{3cd9}@anchor{library/spwd module-spwd}@anchor{f1}@anchor{library/spwd spwd-the-shadow-password-database}@anchor{3cda}
@subsection @code{spwd} —— shadow 密码库


@geindex spwd (模块)


3.11 版后已移除: @ref{f1,,spwd} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#spwd
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#spwd} 了解详情及其替代品）。



__________________________________________________________________


该模块提供对 Unix shadow 密码库的访问能力。可用于各种 Unix 版本。

访问 shadow 密码数据库须拥有足够的权限（通常意味着必须采用 root 账户）。

shadow 密码库的每条数据均表示为一个类似元组的对象，其属性对应着`@w{`}spwd`@w{`} 结构的成员（下面列出了各属性字段，参见 ` @code{<shadow.h>}）。


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

索引

@tab

属性

@tab

意义

@item

0

@tab

@code{sp_namp}

@tab

登录名

@item

1

@tab

@code{sp_pwdp}

@tab

加密后的密码

@item

2

@tab

@code{sp_lstchg}

@tab

最后修改日期

@item

3

@tab

@code{sp_min}

@tab

两次修改间隔的最小天数

@item

4

@tab

@code{sp_max}

@tab

两次修改间隔的最大天数

@item

5

@tab

@code{sp_warn}

@tab

提前警告用户密码过期的天数

@item

6

@tab

@code{sp_inact}

@tab

密码过期至账户禁用之间的天数

@item

7

@tab

@code{sp_expire}

@tab

账户过期的天数，自 1970-01-01 算起

@item

8

@tab

@code{sp_flag}

@tab

保留字段

@end multitable


sp_namp 和 sp_pwdp 条目是字符串，其他的均为整数。 如果未找到所需条目则会触发 @ref{3f1,,KeyError}。

定义了以下函数：

@geindex getspnam() (在 spwd 模块中)
@anchor{library/spwd spwd getspnam}@anchor{6ff}
@deffn {函数} spwd.getspnam (name)

返回指定用户名的 shadow 密码库记录。


在 3.6 版更改: 如果当前用户权限不足，会触发 @ref{700,,PermissionError}，而非 @ref{3f1,,KeyError}。

@end deffn

@geindex getspall() (在 spwd 模块中)
@anchor{library/spwd spwd getspall}@anchor{3cdb}
@deffn {函数} spwd.getspall ()

返回所有可用的 shadow 密码库记录列表，顺序随机。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{8a,,grp}

针对用户组数据库的接口，与本模块类似。

@item 模块 @ref{d6,,pwd}

访问普通密码库的接口，与本模块类似。
@end table


@node sunau --- 读写 Sun AU 文件,telnetlib -- Telnet 客户端,spwd —— shadow 密码库,被取代的模块
@anchor{library/sunau doc}@anchor{3cdc}@anchor{library/sunau module-sunau}@anchor{fa}@anchor{library/sunau sunau-read-and-write-sun-au-files}@anchor{3cdd}
@subsection @code{sunau} --- 读写 Sun AU 文件


@geindex sunau (模块)

@strong{源代码:} Lib/sunau.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/sunau.py}


3.11 版后已移除: @ref{fa,,sunau} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#sunau
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#sunau} 了解详情）。



__________________________________________________________________


@ref{fa,,sunau} 模拟提供了一个处理 Sun AU 声音格式的便利接口。请注意此模块与 @ref{4,,aifc} 和 @ref{130,,wave} 是兼容接口的。

音频文件由标头和数据组成。标头的字段为：


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

内容

@item

magic word

@tab

四个字节 @code{.snd}

@item

header size

@tab

标头的大小，包括信息，以字节为单位。

@item

data size

@tab

数据的物理大小，以字节为单位。

@item

编码

@tab

指示音频样本的编码方式。

@item

sample rate

@tab

采样率

@item

# of channels

@tab

采样中的通道数。

@item

info

@tab

提供音频文件描述的ASCII字符串（用空字节填充）。

@end multitable


除了 info 字段，所有标头字段的大小都是 4 字节。 它们都是采用大端字节序编码的 32 位无符号整数。

@ref{fa,,sunau} 模块定义了以下函数:

@geindex open() (在 sunau 模块中)
@anchor{library/sunau sunau open}@anchor{57b}
@deffn {函数} sunau.open (file, mode)

如果 @emph{file} 是一个字符串，打开相应名称的文件，否则就把它作为可定位的文件类对象来处理。 @emph{mode} 可以是


@table @asis

@item @code{'r'}

只读模式。

@item @code{'w'}

只写模式。
@end table

注意它不支持同时读/写文件。

@emph{mode} 为 @code{'r'} 时返回一个 @code{AU_read} 对象，而 @emph{mode} 为 @code{'w'} 或 @code{'wb'} 时返回一个 @code{AU_write} 对象。
@end deffn

@ref{fa,,sunau} 模块定义了以下异常:

@geindex Error
@anchor{library/sunau sunau Error}@anchor{3cde}
@deffn {例外} sunau.Error

当 Sun AU 规范或实现的低效导致无法操作时引发的错误。
@end deffn

@ref{fa,,sunau} 模块定义了以下数据条目:

@geindex AUDIO_FILE_MAGIC() (在 sunau 模块中)
@anchor{library/sunau sunau AUDIO_FILE_MAGIC}@anchor{3cdf}
@deffn {数据} sunau.AUDIO_FILE_MAGIC

位于每个有效的 Sun AU 文件开头的整数，以大端序形式存储。 这是一个被当作整数来解读的字符串 @code{.snd}。
@end deffn

@geindex AUDIO_FILE_ENCODING_MULAW_8() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_LINEAR_8() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_LINEAR_16() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_LINEAR_24() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_LINEAR_32() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_ALAW_8() (在 sunau 模块中)
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_MULAW_8}@anchor{3ce0}
@deffn {数据} sunau.AUDIO_FILE_ENCODING_MULAW_8
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_8}@anchor{3ce1}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_LINEAR_8
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_16}@anchor{3ce2}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_LINEAR_16
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_24}@anchor{3ce3}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_LINEAR_24
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_32}@anchor{3ce4}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_LINEAR_32
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_ALAW_8}@anchor{3ce5}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_ALAW_8

AU 标头中被此模块所支持的 encoding 字段值。
@end deffn

@geindex AUDIO_FILE_ENCODING_FLOAT() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_DOUBLE() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_ADPCM_G721() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_ADPCM_G722() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_ADPCM_G723_3() (在 sunau 模块中)
@geindex AUDIO_FILE_ENCODING_ADPCM_G723_5() (在 sunau 模块中)
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_FLOAT}@anchor{3ce6}
@deffn {数据} sunau.AUDIO_FILE_ENCODING_FLOAT
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_DOUBLE}@anchor{3ce7}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_DOUBLE
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G721}@anchor{3ce8}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_ADPCM_G721
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G722}@anchor{3ce9}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_ADPCM_G722
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_3}@anchor{3cea}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3
@anchor{library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_5}@anchor{3ceb}
@deffnx {数据} sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5

AU 标头中附加的已知但不被此模块所支持的 encoding 字段值。
@end deffn

@menu
* AU_read 对象:: 
* AU_write 对象:: 

@end menu

@node AU_read 对象,AU_write 对象,,sunau --- 读写 Sun AU 文件
@anchor{library/sunau au-read-objects}@anchor{3cec}@anchor{library/sunau id1}@anchor{3ced}
@subsubsection AU_read 对象


由上面的 @ref{57b,,open()} 所返回的 AU_read 对象具有以下几种方法:

@geindex close() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read close}@anchor{3cee}
@deffn {方法} AU_read.close ()

关闭流，并使实例不可用。 （此方法会在删除对象时自动调用。）
@end deffn

@geindex getnchannels() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getnchannels}@anchor{3cef}
@deffn {方法} AU_read.getnchannels ()

返回音频的通道数（单声道为 1，立体声为 2）。
@end deffn

@geindex getsampwidth() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getsampwidth}@anchor{3cf0}
@deffn {方法} AU_read.getsampwidth ()

返回采样字节长度。
@end deffn

@geindex getframerate() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getframerate}@anchor{3cf1}
@deffn {方法} AU_read.getframerate ()

返回采样频率。
@end deffn

@geindex getnframes() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getnframes}@anchor{3cf2}
@deffn {方法} AU_read.getnframes ()

返回音频总帧数。
@end deffn

@geindex getcomptype() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getcomptype}@anchor{3cf3}
@deffn {方法} AU_read.getcomptype ()

返回压缩类型。 受支持的压缩类型有 @code{'ULAW'}, @code{'ALAW'} 和 @code{'NONE'}。
@end deffn

@geindex getcompname() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getcompname}@anchor{3cf4}
@deffn {方法} AU_read.getcompname ()

@ref{3cf3,,getcomptype()} 的人类可读的版本。 受支持的类型将为相应的名称 @code{'CCITT G.711 u-law'}, @code{'CCITT G.711 A-law'} 和 @code{'not compressed'}。
@end deffn

@geindex getparams() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getparams}@anchor{3cf5}
@deffn {方法} AU_read.getparams ()

返回一个 @ref{1a1,,namedtuple()} @code{(nchannels, sampwidth, framerate, nframes, comptype, compname)}，与 @code{get*()} 方法的输出相同。
@end deffn

@geindex readframes() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read readframes}@anchor{3cf6}
@deffn {方法} AU_read.readframes (n)

读取至多 @emph{n} 帧音频并作为 @ref{172,,bytes} 对象返回。 数据将以线性格式返回。 如果原始数据为 u-LAW 格式，则它将被转换。
@end deffn

@geindex rewind() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read rewind}@anchor{3cf7}
@deffn {方法} AU_read.rewind ()

设置当前文件指针位置。
@end deffn

以下两个方法都使用指针，具体实现由其底层决定。

@geindex setpos() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read setpos}@anchor{3cf8}
@deffn {方法} AU_read.setpos (pos)

设置文件指针到特定位置。 只有从 @ref{3cf9,,tell()} 返回的值才可被用作 @emph{pos}。
@end deffn

@geindex tell() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read tell}@anchor{3cf9}
@deffn {方法} AU_read.tell ()

返回当前文件指针的位置。 请注意该返回值与文件中的实例位置无关。
@end deffn

以下两个函数是为了与 @ref{4,,aifc} 保持兼容而定义的，实际不做任何事件。

@geindex getmarkers() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getmarkers}@anchor{3cfa}
@deffn {方法} AU_read.getmarkers ()

返回 @code{None}。
@end deffn

@geindex getmark() (sunau.AU_read 方法)
@anchor{library/sunau sunau AU_read getmark}@anchor{3cfb}
@deffn {方法} AU_read.getmark (id)

引发错误异常。
@end deffn

@node AU_write 对象,,AU_read 对象,sunau --- 读写 Sun AU 文件
@anchor{library/sunau au-write-objects}@anchor{3cfc}@anchor{library/sunau id2}@anchor{3cfd}
@subsubsection AU_write 对象


由上面的 @ref{57b,,open()} 所返回的 AU_write 对象具有以下几种方法:

@geindex setnchannels() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setnchannels}@anchor{3cfe}
@deffn {方法} AU_write.setnchannels (n)

设置声道数。
@end deffn

@geindex setsampwidth() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setsampwidth}@anchor{9cd}
@deffn {方法} AU_write.setsampwidth (n)

设置采样宽度（字节长度。）


在 3.4 版更改: 增加了对 24 位采样的支持。

@end deffn

@geindex setframerate() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setframerate}@anchor{3cff}
@deffn {方法} AU_write.setframerate (n)

设置帧速率。
@end deffn

@geindex setnframes() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setnframes}@anchor{3d00}
@deffn {方法} AU_write.setnframes (n)

设置总帧数。 如果写入了更多的帧，此值将会被更改。
@end deffn

@geindex setcomptype() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setcomptype}@anchor{3d01}
@deffn {方法} AU_write.setcomptype (type, name)

设置压缩类型和描述。 对于输出只支持 @code{'NONE'} 和 @code{'ULAW'}。
@end deffn

@geindex setparams() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write setparams}@anchor{3d02}
@deffn {方法} AU_write.setparams (tuple)

@emph{tuple} 应该是 @code{(nchannels, sampwidth, framerate, nframes, comptype, compname)}，每项的值可用于 @code{set*()} 方法。 设置所有形参。
@end deffn

@geindex tell() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write tell}@anchor{3d03}
@deffn {方法} AU_write.tell ()

返回文件中的当前位置，其含义与 @ref{3cf9,,AU_read.tell()} 和 @ref{3cf8,,AU_read.setpos()} 方法的一致。
@end deffn

@geindex writeframesraw() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write writeframesraw}@anchor{9ce}
@deffn {方法} AU_write.writeframesraw (data)

写入音频数据但不更新 @emph{nframes}。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn

@geindex writeframes() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write writeframes}@anchor{9cf}
@deffn {方法} AU_write.writeframes (data)

写入音频数据并更新 @emph{nframes}。


在 3.4 版更改: 现在可接受任意 @ref{6e9,,bytes-like object}。

@end deffn

@geindex close() (sunau.AU_write 方法)
@anchor{library/sunau sunau AU_write close}@anchor{3d04}
@deffn {方法} AU_write.close ()

确保 @emph{nframes} 正确，并关闭文件。

此方法会在删除时被调用。
@end deffn

请注意在调用 @code{writeframes()} 和 @code{writeframesraw()} 之后再设置任何形参都是无效的。

@node telnetlib -- Telnet 客户端,uu --- 对 uuencode 文件进行编码与解码,sunau --- 读写 Sun AU 文件,被取代的模块
@anchor{library/telnetlib doc}@anchor{3d05}@anchor{library/telnetlib module-telnetlib}@anchor{102}@anchor{library/telnetlib telnetlib-telnet-client}@anchor{3d06}
@subsection @code{telnetlib} -- Telnet 客户端


@geindex telnetlib (模块)

@strong{源代码：} Lib/telnetlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/telnetlib.py}

@geindex protocol; Telnet


3.11 版后已移除: @ref{102,,telnetlib} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#telnetlib
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#telnetlib} 了解详情及其替代品）。



__________________________________________________________________


@ref{102,,telnetlib} 模块提供一个实现Telnet协议的类 @ref{698,,Telnet}。关于此协议的细节请参见 
@geindex RFC; RFC 854
RFC 854@footnote{https://tools.ietf.org/html/rfc854.html} 。此外，它还为协议字符（见下文）和 telnet 选项提供了对应的符号常量。telnet选项对应的符号名遵循 @code{arpa/telnet.h} 中的定义，但删除了前缀 @code{TELOPT_}。对于不在 @code{arpa/telnet.h} 的选项的符号常量名，请参考本模块源码。

telnet命令的符号常量名有： IAC, DONT, DO, WONT, WILL, SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP (Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).

@geindex Telnet (telnetlib 中的类)
@anchor{library/telnetlib telnetlib Telnet}@anchor{698}
@deffn {类} telnetlib.Telnet (host=None, port=0[, timeout])

@ref{698,,Telnet} 表示到 Telnet 服务器的连接. 实例初始化后默认不连接；必须使用 @ref{355d,,open()} 方法来建立连接。或者， 可选参数 host 和 port 也可以传递给构造函数，在这种情况下，到服务器的连接将在构造函数返回前建立。可选参数 @emph{timeout} 为阻塞操作（如连接尝试）指定一个以秒为单位的超时时间（如果没有指定，将使用全局默认设置） 。

不要重新打开一个已经连接的实例。

这个类有很多 @code{read_*()} 方法。 请注意，其中一些方法在读取结束时会触发 @ref{d3c,,EOFError} 异常，这是由于连接对象可能出于其它原因返回一个空字符串。 请参阅下面的个别描述。

@ref{698,,Telnet} 对象一个上下文管理器，可以在 @ref{7e4,,with} 语句中使用。当 @code{with} 块结束，@ref{3d07,,close()} 方法会被调用:

@example
>>> from telnetlib import Telnet
>>> with Telnet('localhost', 23) as tn:
...     tn.interact()
...
@end example


在 3.6 版更改: 添加了上下文管理器的支持

@end deffn


@subsubheading 参见



@table @asis

@geindex RFC; RFC 854

@item RFC 854@footnote{https://tools.ietf.org/html/rfc854.html} - Telnet 协议规范

Telnet 协议的定义。
@end table


@menu
* Telnet 对象:: 
* Telnet 示例:: 

@end menu

@node Telnet 对象,Telnet 示例,,telnetlib -- Telnet 客户端
@anchor{library/telnetlib id1}@anchor{3d08}@anchor{library/telnetlib telnet-objects}@anchor{3d09}
@subsubsection Telnet 对象


@ref{698,,Telnet} 实例有以下几种方法：

@geindex read_until() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_until}@anchor{3d0a}
@deffn {方法} Telnet.read_until (expected, timeout=None)

读取直到遇到给定字节串 @emph{expected} 或 @emph{timeout} 秒已经过去。

当没有找到匹配时，返回可用的内容，也可能返回空字节。如果连接已关闭且没有可用的熟数据，将触发 @ref{d3c,,EOFError}。
@end deffn

@geindex read_all() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_all}@anchor{3d0b}
@deffn {方法} Telnet.read_all ()

读取数据，直到遇到 EOF；连接关闭前都会保持阻塞。
@end deffn

@geindex read_some() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_some}@anchor{3d0c}
@deffn {方法} Telnet.read_some ()

在达到 EOF 前，读取至少一个字节的熟数据。如果命中 EOF，返回 @code{b'@w{'}}。如果没有立即可用的数据，则阻塞。
@end deffn

@geindex read_very_eager() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_very_eager}@anchor{3d0d}
@deffn {方法} Telnet.read_very_eager ()

在不阻塞 I/O 的情况下读取所有的内容（eager）。

如果连接已关闭并且没有可用的熟数据，将会触发 @ref{d3c,,EOFError} 。如果没有熟数据可用返回 @code{b'@w{'}}  。除非在一个 IAC 序列的中间，否则不要进行阻塞。
@end deffn

@geindex read_eager() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_eager}@anchor{3d0e}
@deffn {方法} Telnet.read_eager ()

读取现成的数据。

如果连接已关闭并且没有可用的熟数据，将会触发 @ref{d3c,,EOFError} 。如果没有熟数据可用返回 @code{b'@w{'}}  。除非在一个 IAC 序列的中间，否则不要进行阻塞。
@end deffn

@geindex read_lazy() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_lazy}@anchor{3d0f}
@deffn {方法} Telnet.read_lazy ()

处理并返回已经在队列中的数据（lazy）。

如果连接已关闭并且没有可用的数据，将会触发 @ref{d3c,,EOFError} 。如果没有熟数据可用则返回 @code{b'@w{'}} 。除非在一个 IAC 序列的中间，否则不要进行阻塞。
@end deffn

@geindex read_very_lazy() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_very_lazy}@anchor{3d10}
@deffn {方法} Telnet.read_very_lazy ()

返回熟数据队列任何可用的数据（very lazy）。

如果连接已关闭并且没有可用的数据，将会触发 @ref{d3c,,EOFError} 。如果没有熟数据可用则返回 @code{b'@w{'}} 。该方法永远不会阻塞。
@end deffn

@geindex read_sb_data() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet read_sb_data}@anchor{3d11}
@deffn {方法} Telnet.read_sb_data ()

返回在 SB/SE 对之间收集的数据（子选项 begin/end）。当使用 @code{SE} 命令调用回调函数时，该回调函数应该访问这些数据。该方法永远不会阻塞。
@end deffn

@geindex open() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet open}@anchor{355d}
@deffn {方法} Telnet.open (host, port=0[, timeout])

连接主机。第二个可选参数是端口号，默认为标准 Telnet 端口（23）。可选参数 @emph{timeout} 指定一个以秒为单位的超时时间用于像连接尝试这样的阻塞操作（如果没有指定，将使用全局默认超时设置）。

不要尝试重新打开一个已经连接的实例。

触发 @ref{fec,,auditing event} @code{telnetlib.Telnet.open} ，参数为 @code{self}，@code{host}，@code{port}。
@end deffn

@geindex msg() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet msg}@anchor{3d12}
@deffn {方法} Telnet.msg (msg, *args)

当调试级别 @code{>} 0 时打印一条调试信息。如果存在额外参数，则它们会被替换在使用标准字符串格式化操作符的信息中。
@end deffn

@geindex set_debuglevel() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet set_debuglevel}@anchor{3d13}
@deffn {方法} Telnet.set_debuglevel (debuglevel)

设置调试级别。@emph{debuglevel} 的值越高，得到的调试输出越多（在 @code{sys.stdout} ）。
@end deffn

@geindex close() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet close}@anchor{3d07}
@deffn {方法} Telnet.close ()

关闭连接对象。
@end deffn

@geindex get_socket() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet get_socket}@anchor{3d14}
@deffn {方法} Telnet.get_socket ()

返回内部使用的套接字对象。
@end deffn

@geindex fileno() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet fileno}@anchor{3d15}
@deffn {方法} Telnet.fileno ()

返回内部使用的套接字对象的文件描述符。
@end deffn

@geindex write() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet write}@anchor{355e}
@deffn {方法} Telnet.write (buffer)

向套接字写入一个字节字符串，将所有 IAC 字符加倍。如果连接被阻塞，这可能也会阻塞。如果连接关闭可能触发 @ref{30b,,OSError}。

触发 @ref{fec,,auditing event} @code{telnetlib.Telnet.write} ，参数为 @code{self}，@code{buffer}。


在 3.3 版更改: 曾经该函数抛出 @ref{a7f,,socket.error}，现在这是 @ref{30b,,OSError} 的别名。

@end deffn

@geindex interact() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet interact}@anchor{3d16}
@deffn {方法} Telnet.interact ()

交互函数，模拟一个非常笨拙的 Telnet 客户端。
@end deffn

@geindex mt_interact() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet mt_interact}@anchor{3d17}
@deffn {方法} Telnet.mt_interact ()

多线程版的 @ref{3d16,,interact()}.
@end deffn

@geindex expect() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet expect}@anchor{3d18}
@deffn {方法} Telnet.expect (list, timeout=None)

一直读取，直到匹配列表中的某个正则表达式。

第一个参数是一个正则表达式列表，可以是已编译的 (@ref{98c,,正则表达式对象})，也可以是未编译的 (字节串)。 第二个可选参数是超时，单位是秒；默认一直阻塞。

返回一个包含三个元素的元组：列表中的第一个匹配的正则表达式的索引；返回的匹配对象；包括匹配在内的读取过的字节。

如果找到了文件的结尾且没有字节被读取，触发 @ref{d3c,,EOFError}。否则，当没有匹配时,返回 @code{(-1, None, data)}，其中 @emph{data} 是到目前为止接受到的字节（如果发生超时，则可能是空字节）。

如果一个正则表达式以贪婪匹配结束（例如 @code{.*}），或者多个表达式可以匹配同一个输出，则结果是不确定的，可能取决于 I/O 计时。
@end deffn

@geindex set_option_negotiation_callback() (telnetlib.Telnet 方法)
@anchor{library/telnetlib telnetlib Telnet set_option_negotiation_callback}@anchor{3d19}
@deffn {方法} Telnet.set_option_negotiation_callback (callback)

每次在输入流上读取 telnet 选项时，这个带有如下参数的 @emph{callback} （如果设置了）会被调用： callback(telnet socket, command (DO/DONT/WILL/WONT), option)。telnetlib 之后不会再执行其它操作。
@end deffn

@node Telnet 示例,,Telnet 对象,telnetlib -- Telnet 客户端
@anchor{library/telnetlib id2}@anchor{3d1a}@anchor{library/telnetlib telnet-example}@anchor{3d1b}
@subsubsection Telnet 示例


一个简单的说明性典型用法例子:

@example
import getpass
import telnetlib

HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")

tn.write(b"ls\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))
@end example

@node uu --- 对 uuencode 文件进行编码与解码,xdrlib --- 编码与解码 XDR 数据,telnetlib -- Telnet 客户端,被取代的模块
@anchor{library/uu doc}@anchor{3d1c}@anchor{library/uu module-uu}@anchor{12c}@anchor{library/uu uu-encode-and-decode-uuencode-files}@anchor{3d1d}
@subsection @code{uu} --- 对 uuencode 文件进行编码与解码


@geindex uu (模块)

@strong{源代码:} Lib/uu.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/uu.py}


3.11 版后已移除: @ref{12c,,uu} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#uu-and-the-uu-encoding
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#uu-and-the-uu-encoding} 了解详情）。 @ref{d,,base64} 是一个更现代化的替代品。



__________________________________________________________________


此模块使用 uuencode 格式来编码和解码文件，以便任意二进制数据可通过仅限 ASCII 码的连接进行传输。 在任何要求文件参数的地方，这些方法都接受文件类对象。 为了保持向下兼容，也接受包含路径名称的字符串，并且将打开相应的文件进行读写；路径名称 @code{'-'} 被解读为标准输入或输出。 但是，此接口已被弃用；在 Windows 中调用者最好是自行打开文件，并在需要时确保模式为 @code{'rb'} or @code{'wb'}。

@geindex Jansen@comma{} Jack
@geindex Ellinghouse@comma{} Lance

此代码由 Lance Ellinghouse 贡献，并由 Jack Jansen 修改。

@ref{12c,,uu} 模块定义了以下函数：

@geindex encode() (在 uu 模块中)
@anchor{library/uu uu encode}@anchor{51c}
@deffn {函数} uu.encode (in_file, out_file, name=None, mode=None, *, backtick=False)

使用 uuencode 将 @emph{in_file} 文件编码为 @emph{out_file} 文件。 经过 uuencoded 编码的文件将具有指定 @emph{name} 和 @emph{mode} 作为解码该文件默认结果的标头。 默认值会相应地从 @emph{in_file} 或 @code{'-'} 以及 @code{0o666} 中提取。 如果 @emph{backtick} 为真值，零会用 @code{'`'} 而不是空格来表示。


在 3.7 版更改: 增加 @emph{backtick} 参数

@end deffn

@geindex decode() (在 uu 模块中)
@anchor{library/uu uu decode}@anchor{f55}
@deffn {函数} uu.decode (in_file, out_file=None, mode=None, quiet=False)

调用此函数会解码 uuencod 编码的 @emph{in_file} 文件并将结果放入 @emph{out_file} 文件。 如果 @emph{out_file} 是一个路径名称，@emph{mode} 会在必须创建文件时用于设置权限位。 @emph{out_file} 和 @emph{mode} 的默认值会从 uuencode 标头中提取。 但是，如果标头中指定的文件已存在，则会引发 @ref{3d1e,,uu.Error}。

如果输入由不正确的 uuencode 编码器生成，@ref{f55,,decode()} 可能会打印一条警告到标准错误 ，这样 Python 可以从该错误中恢复。 将 @emph{quiet} 设为真值可以屏蔽此警告。
@end deffn

@geindex Error
@anchor{library/uu uu Error}@anchor{3d1e}
@deffn {例外} uu.Error

@ref{2e3,,Exception} 的子类，此异常可由 @ref{f55,,uu.decode()} 在多种情况下引发，如上文所述，此外还包括格式错误的标头或被截断的输入文件等。
@end deffn


@subsubheading 参见



@table @asis

@item 模块 @ref{f,,binascii}

支持模块，包含ASCII到二进制和二进制到ASCII转换。
@end table


@node xdrlib --- 编码与解码 XDR 数据,,uu --- 对 uuencode 文件进行编码与解码,被取代的模块
@anchor{library/xdrlib doc}@anchor{3d1f}@anchor{library/xdrlib module-xdrlib}@anchor{13b}@anchor{library/xdrlib xdrlib-encode-and-decode-xdr-data}@anchor{3d20}
@subsection @code{xdrlib} --- 编码与解码 XDR 数据


@geindex xdrlib (模块)

@strong{源代码:} Lib/xdrlib.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/xdrlib.py}

@geindex XDR
@geindex External Data Representation


3.11 版后已移除: @ref{13b,,xdrlib} 模块已被弃用（请参阅 
@geindex Python 提高建议; PEP 594#xdrlib
PEP 594@footnote{https://www.python.org/dev/peps/pep-0594#xdrlib} 了解详情）。



__________________________________________________________________


@ref{13b,,xdrlib} 模块为外部数据表示标准提供支持，该标准的描述见 
@geindex RFC; RFC 1014
RFC 1014@footnote{https://tools.ietf.org/html/rfc1014.html}，由 Sun Microsystems, Inc. 在 1987 年 6 月撰写。 它支持该 RFC 中描述的大部分数据类型。

@ref{13b,,xdrlib} 模块定义了两个类，一个用于将变量打包为 XDR 表示形式，另一个用于从 XDR 表示形式解包。 此外还有两个异常类。

@geindex Packer (xdrlib 中的类)
@anchor{library/xdrlib xdrlib Packer}@anchor{3d21}
@deffn {类} xdrlib.Packer

@ref{3d21,,Packer} 是用于将数据打包为 XDR 表示形式的类。 @ref{3d21,,Packer} 类的实例化不附带参数。
@end deffn

@geindex Unpacker (xdrlib 中的类)
@anchor{library/xdrlib xdrlib Unpacker}@anchor{3d22}
@deffn {类} xdrlib.Unpacker (data)

@code{Unpacker} 是用于相应地从字符串缓冲区解包 XDR 数据值的类。 输入缓冲区将作为 @emph{data} 给出。
@end deffn


@subsubheading 参见



@table @asis

@geindex RFC; RFC 1014

@item RFC 1014@footnote{https://tools.ietf.org/html/rfc1014.html} - XDR: 外部数据表示标准

这个 RFC 定义了最初编写此模块时 XDR 所用的数据编码格式。 显然它已被 
@geindex RFC; RFC 1832
RFC 1832@footnote{https://tools.ietf.org/html/rfc1832.html} 所淘汰。

@geindex RFC; RFC 1832

@item RFC 1832@footnote{https://tools.ietf.org/html/rfc1832.html} - XDR: 外部数据表示标准

更新的 RFC，它提供了经修订的 XDR 定义。
@end table


@menu
* Packer 对象:: 
* Unpacker 对象:: 
* 异常: 异常<18>. 

@end menu

@node Packer 对象,Unpacker 对象,,xdrlib --- 编码与解码 XDR 数据
@anchor{library/xdrlib packer-objects}@anchor{3d23}@anchor{library/xdrlib xdr-packer-objects}@anchor{3d24}
@subsubsection Packer 对象


@ref{3d21,,Packer} 实例具有下列方法:

@geindex get_buffer() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer get_buffer}@anchor{3d25}
@deffn {方法} Packer.get_buffer ()

将当前打包缓冲区以字符串的形式返回。
@end deffn

@geindex reset() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer reset}@anchor{3d26}
@deffn {方法} Packer.reset ()

将打包缓冲区重置为空字符串。
@end deffn

总体来说，你可以通过调用适当的 @code{pack_type()} 方法来打包任何最常见的 XDR 数据类型。 每个方法都是接受单个参数，即要打包的值。 受支持的简单数据类型打包方法如下: @code{pack_uint()}, @code{pack_int()}, @code{pack_enum()}, @code{pack_bool()}, @code{pack_uhyper()} 以及 @code{pack_hyper()}。

@geindex pack_float() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_float}@anchor{3d27}
@deffn {方法} Packer.pack_float (value)

打包单精度浮点数 @emph{value}。
@end deffn

@geindex pack_double() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_double}@anchor{3d28}
@deffn {方法} Packer.pack_double (value)

打包双精度浮点数 @emph{value}。
@end deffn

以下方法支持打包字符串、字节串以及不透明数据。

@geindex pack_fstring() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_fstring}@anchor{3d29}
@deffn {方法} Packer.pack_fstring (n, s)

打包固定长度字符串 @emph{s}。 @emph{n} 为字符串的长度，但它 @emph{不会} 被打包进数据缓冲区。 如有必要字符串会以空字节串填充以保证 4 字节对齐。
@end deffn

@geindex pack_fopaque() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_fopaque}@anchor{3d2a}
@deffn {方法} Packer.pack_fopaque (n, data)

打包固定长度不透明数据流，类似于 @ref{3d29,,pack_fstring()}。
@end deffn

@geindex pack_string() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_string}@anchor{3d2b}
@deffn {方法} Packer.pack_string (s)

打包可变长度字符串 @emph{s}。 先将字符串的长度打包为无符号整数，再用 @ref{3d29,,pack_fstring()} 来打包字符串数据。
@end deffn

@geindex pack_opaque() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_opaque}@anchor{3d2c}
@deffn {方法} Packer.pack_opaque (data)

打包可变长度不透明数据流，类似于 @ref{3d2b,,pack_string()}。
@end deffn

@geindex pack_bytes() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_bytes}@anchor{3d2d}
@deffn {方法} Packer.pack_bytes (bytes)

打包可变长度字节流，类似于 @ref{3d2b,,pack_string()}。
@end deffn

下列方法支持打包数组和列表:

@geindex pack_list() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_list}@anchor{3d2e}
@deffn {方法} Packer.pack_list (list, pack_item)

打包由同质条目构成的 @emph{list}。 此方法适用于不确定长度的列表；即其长度无法在遍历整个列表之前获知。 对于列表中的每个条目，先打包一个无符号整数 @code{1}，再添加列表中数据的值。 @emph{pack_item} 是在打包单个条目时要调用的函数。 在列表的末尾，会再打包一个无符号整数 @code{0}。

例如，要打包一个整数列表，代码看起来会是这样:

@example
import xdrlib
p = xdrlib.Packer()
p.pack_list([1, 2, 3], p.pack_int)
@end example
@end deffn

@geindex pack_farray() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_farray}@anchor{3d2f}
@deffn {方法} Packer.pack_farray (n, array, pack_item)

打包由同质条目构成的固定长度列表 (@emph{array})。 @emph{n} 为列表长度；它 @emph{不会} 被打包到缓冲区，但是如果 @code{len(array)} 不等于 @emph{n} 则会引发 @ref{16d,,ValueError}。 如上所述，@emph{pack_item} 是在打包每个元素时要使用的函数。
@end deffn

@geindex pack_array() (xdrlib.Packer 方法)
@anchor{library/xdrlib xdrlib Packer pack_array}@anchor{3d30}
@deffn {方法} Packer.pack_array (list, pack_item)

打包由同质条目构成的可变长度 @emph{list}。 先将列表的长度打包为无符号整数，再像上面的 @ref{3d2f,,pack_farray()} 一样打包每个元素。
@end deffn

@node Unpacker 对象,异常<18>,Packer 对象,xdrlib --- 编码与解码 XDR 数据
@anchor{library/xdrlib unpacker-objects}@anchor{3d31}@anchor{library/xdrlib xdr-unpacker-objects}@anchor{3d32}
@subsubsection Unpacker 对象


@ref{3d22,,Unpacker} 类提供以下方法:

@geindex reset() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker reset}@anchor{3d33}
@deffn {方法} Unpacker.reset (data)

使用给定的 @emph{data} 重置字符串缓冲区。
@end deffn

@geindex get_position() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker get_position}@anchor{3d34}
@deffn {方法} Unpacker.get_position ()

返回数据缓冲区中的当前解包位置。
@end deffn

@geindex set_position() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker set_position}@anchor{3d35}
@deffn {方法} Unpacker.set_position (position)

将数据缓冲区的解包位置设为 @emph{position}。 你应当小心使用 @ref{3d34,,get_position()} 和 @ref{3d35,,set_position()}。
@end deffn

@geindex get_buffer() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker get_buffer}@anchor{3d36}
@deffn {方法} Unpacker.get_buffer ()

将当前解包数据缓冲区以字符串的形式返回。
@end deffn

@geindex done() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker done}@anchor{3d37}
@deffn {方法} Unpacker.done ()

表明解包完成。 如果数据没有全部完成解包则会引发 @ref{3d38,,Error} 异常。
@end deffn

此外，每种可通过 @ref{3d21,,Packer} 打包的数据类型都可通过 @ref{3d22,,Unpacker} 来解包。 解包方法的形式为 @code{unpack_type()}，并且不接受任何参数。 该方法将返回解包后的对象。

@geindex unpack_float() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_float}@anchor{3d39}
@deffn {方法} Unpacker.unpack_float ()

解包单精度浮点数。
@end deffn

@geindex unpack_double() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_double}@anchor{3d3a}
@deffn {方法} Unpacker.unpack_double ()

解包双精度浮点数，类似于 @ref{3d39,,unpack_float()}。
@end deffn

此外，以下方法可用来解包字符串、字节串以及不透明数据:

@geindex unpack_fstring() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_fstring}@anchor{3d3b}
@deffn {方法} Unpacker.unpack_fstring (n)

解包并返回固定长度字符串。 @emph{n} 为期望的字符数量。 会预设以空字节串填充以保证 4 字节对齐。
@end deffn

@geindex unpack_fopaque() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_fopaque}@anchor{3d3c}
@deffn {方法} Unpacker.unpack_fopaque (n)

解包并返回固定长度数据流，类似于 @ref{3d3b,,unpack_fstring()}。
@end deffn

@geindex unpack_string() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_string}@anchor{3d3d}
@deffn {方法} Unpacker.unpack_string ()

解包并返回可变长度字符串。 先将字符串的长度解包为无符号整数，再用 @ref{3d3b,,unpack_fstring()} 来解包字符串数据。
@end deffn

@geindex unpack_opaque() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_opaque}@anchor{3d3e}
@deffn {方法} Unpacker.unpack_opaque ()

解包并返回可变长度不透明数据流，类似于 @ref{3d3d,,unpack_string()}。
@end deffn

@geindex unpack_bytes() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_bytes}@anchor{3d3f}
@deffn {方法} Unpacker.unpack_bytes ()

解包并返回可变长度字节流，类似于 @ref{3d3d,,unpack_string()}。
@end deffn

下列方法支持解包数组和列表:

@geindex unpack_list() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_list}@anchor{3d40}
@deffn {方法} Unpacker.unpack_list (unpack_item)

解包并返回同质条目的列表。 该列表每次解包一个元素，先解包一个无符号整数旗标。 如果旗标为 @code{1}，则解包条目并将其添加到列表。 旗标为 @code{0} 表明列表结束。 @emph{unpack_item} 为在解包条目时调用的函数。
@end deffn

@geindex unpack_farray() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_farray}@anchor{3d41}
@deffn {方法} Unpacker.unpack_farray (n, unpack_item)

解包并（以列表形式）返回由同质条目构成的固定长度数组。 @emph{n} 为期望的缓冲区内列表元素数量。 如上所述，@emph{unpack_item} 是解包每个元素时要使用的函数。
@end deffn

@geindex unpack_array() (xdrlib.Unpacker 方法)
@anchor{library/xdrlib xdrlib Unpacker unpack_array}@anchor{3d42}
@deffn {方法} Unpacker.unpack_array (unpack_item)

解包并返回由同质条目构成的可变长度 @emph{list}。 先将列表的长度解包为无符号整数，再像上面的 @ref{3d41,,unpack_farray()} 一样解包每个元素。
@end deffn

@node 异常<18>,,Unpacker 对象,xdrlib --- 编码与解码 XDR 数据
@anchor{library/xdrlib exceptions}@anchor{3d43}@anchor{library/xdrlib xdr-exceptions}@anchor{3d44}
@subsubsection 异常


此模块中的异常会表示为类实例代码:

@geindex Error
@anchor{library/xdrlib xdrlib Error}@anchor{3d38}
@deffn {例外} xdrlib.Error

基本异常类。 @ref{3d38,,Error} 具有一个公共属性 @code{msg}，其中包含对错误的描述。
@end deffn

@geindex ConversionError
@anchor{library/xdrlib xdrlib ConversionError}@anchor{3d45}
@deffn {例外} xdrlib.ConversionError

从 @ref{3d38,,Error} 所派生的类。 不包含额外的实例变量。
@end deffn

以下是一个应该如何捕获这些异常的示例:

@example
import xdrlib
p = xdrlib.Packer()
try:
    p.pack_double(8.01)
except xdrlib.ConversionError as instance:
    print('packing the double failed:', instance.msg)
@end example
@anchor{library/security_warnings security-warnings}@anchor{3d46}
@geindex security considerations

@node Security Considerations,,被取代的模块,Python 标准库
@anchor{library/security_warnings doc}@anchor{3d47}@anchor{library/security_warnings security-considerations}@anchor{3d48}
@section Security Considerations


The following modules have specific security considerations:


@itemize *

@item 
@ref{15,,cgi}: @ref{3b6c,,CGI security considerations}

@item 
@ref{8c,,hashlib}: @ref{203c,,all constructors take a "usedforsecurity" keyword-only argument disabling known insecure and blocked algorithms}

@item 
@ref{96,,http.server} is not suitable for production use, only implementing
basic security checks. See the @ref{2ee8,,security considerations}.

@item 
@ref{aa,,logging}: @ref{225e,,Logging configuration uses eval()}

@item 
@ref{b7,,multiprocessing}: @ref{2544,,Connection.recv() uses pickle}

@item 
@ref{ca,,pickle}: @ref{1e64,,Restricting globals in pickle}

@item 
@ref{dc,,random} shouldn't be used for security purposes, use @ref{e4,,secrets}
instead

@item 
@ref{e7,,shelve}: @ref{1e81,,shelve is based on pickle and thus unsuitable for dealing with untrusted sources}

@item 
@ref{f3,,ssl}: @ref{2711,,SSL/TLS security considerations}

@item 
@ref{f9,,subprocess}: @ref{25e8,,Subprocess security considerations}

@item 
@ref{103,,tempfile}: @ref{1e18,,mktemp is deprecated due to vulnerability to race conditions}

@item 
@ref{13c,,xml}: @ref{2b18,,XML vulnerabilities}

@item 
@ref{14b,,zipfile}: @ref{1f75,,maliciously prepared .zip files can cause disk volume exhaustion}
@end itemize

@node 扩展和嵌入 Python 解释器,Python/C API 参考手册,Python 标准库,Top
@anchor{extending/index doc}@anchor{3d49}@anchor{extending/index extending-and-embedding-the-python-interpreter}@anchor{3d4a}@anchor{extending/index extending-index}@anchor{1361}
@chapter 扩展和嵌入 Python 解释器


本文档描述了如何使用 C 或 C++ 编写模块以使用新模块来扩展 Python 解释器的功能。 这些模块不仅可以定义新的函数，还可以定义新的对象类型及其方法。 该文档还描述了如何将 Python 解释器嵌入到另一个应用程序中，以用作扩展语言。 最后，它展示了如何编译和链接扩展模块，以便它们可以动态地（在运行时）加载到解释器中，如果底层操作系统支持此特性的话。

本文档假设你具备有关 Python 的基本知识。有关该语言的非正式介绍，请参阅 @ref{135e,,Python 教程} 。 @ref{1360,,Python 语言参考手册} 给出了更正式的语言定义。 @ref{135f,,Python 标准库} 包含现有的对象类型、函数和模块（内置和用 Python 编写）的文档，使语言具有广泛的应用范围。

关于整个 Python/C API 的详细介绍，请参阅独立的 @ref{1362,,Python/C API 参考手册} 。

@menu
* 推荐的第三方工具:: 
* 不使用第三方工具创建扩展:: 
* 在更大的应用程序中嵌入 CPython 运行时:: 

@end menu

@node 推荐的第三方工具,不使用第三方工具创建扩展,,扩展和嵌入 Python 解释器
@anchor{extending/index recommended-third-party-tools}@anchor{3d4b}
@section 推荐的第三方工具


本指南仅介绍了作为此 CPython 版本的一部分提供的创建扩展的基本工具。 第三方工具，如 Cython@footnote{http://cython.org/} 、 cffi@footnote{https://cffi.readthedocs.io} 、 SWIG@footnote{http://www.swig.org} 和 Numba@footnote{https://numba.pydata.org/} 提供了更简单和更复杂的方法来为 Python 创建 C 和 C ++ 扩展。


@subsubheading 参见



@table @asis

@item Python Packaging User Guide: Binary Extensions@footnote{https://packaging.python.org/guides/packaging-binary-extensions/}

“ Python Packaging User Guide ”不仅涵盖了几个简化二进制扩展创建的可用工具，还讨论了为什么首先创建扩展模块的各种原因。
@end table


@node 不使用第三方工具创建扩展,在更大的应用程序中嵌入 CPython 运行时,推荐的第三方工具,扩展和嵌入 Python 解释器
@anchor{extending/index creating-extensions-without-third-party-tools}@anchor{3d4c}
@section 不使用第三方工具创建扩展


本指南的这一部分包括在没有第三方工具帮助的情况下创建 C 和 C ++ 扩展。它主要用于这些工具的创建者，而不是建议你创建自己的 C 扩展的方法。

@menu
* 使用 C 或 C++ 扩展 Python:: 
* 自定义扩展类型：教程:: 
* 定义扩展类型：已分类主题:: 
* 构建C/C++扩展:: 
* 在 Windows 上构建 C 和 C++ 扩展:: 

@end menu

@node 使用 C 或 C++ 扩展 Python,自定义扩展类型：教程,,不使用第三方工具创建扩展
@anchor{extending/extending doc}@anchor{3d4d}@anchor{extending/extending extending-intro}@anchor{3d4e}@anchor{extending/extending extending-python-with-c-or-c}@anchor{3d4f}
@subsection 使用 C 或 C++ 扩展 Python


如果你会用 C，添加新的 Python 内置模块会很简单。以下两件不能用 Python 直接做的事，可以通过 @emph{extension modules} 来实现：实现新的内置对象类型；调用 C 的库函数和系统调用。

为了支持扩展，Python API（应用程序编程接口）定义了一系列函数、宏和变量，可以访问 Python 运行时系统的大部分内容。Python 的 API 可以通过在一个 C 源文件中引用 @code{"Python.h"} 头文件来使用。

扩展模块的编写方式取决与你的目的以及系统设置；下面章节会详细介绍。

@cartouche
@quotation 注解 
C扩展接口特指CPython，扩展模块无法在其他Python实现上工作。在大多数情况下，应该避免写C扩展，来保持可移植性。举个例子，如果你的用例调用了C库或系统调用，你应该考虑使用 @ref{2a,,ctypes} 模块或 cffi@footnote{https://cffi.readthedocs.io/} 库，而不是自己写C代码。这些模块允许你写Python代码来接口C代码，而且可移植性更好。不知为何编译失败了。
@end quotation
@end cartouche

@menu
* 一个简单的例子:: 
* 关于错误和异常:: 
* 回到例子:: 
* 模块方法表和初始化函数:: 
* 编译和链接:: 
* 在C中调用Python函数:: 
* 提取扩展函数的参数:: 
* 给扩展函数的关键字参数:: 
* 构造任意值:: 
* 引用计数:: 
* 在C++中编写扩展:: 
* 给扩展模块提供C API:: 

@end menu

@node 一个简单的例子,关于错误和异常,,使用 C 或 C++ 扩展 Python
@anchor{extending/extending a-simple-example}@anchor{3d50}@anchor{extending/extending extending-simpleexample}@anchor{3d51}
@subsubsection 一个简单的例子


让我们创建一个扩展模块 @code{spam} (Monty Python 粉丝最喜欢的食物...) 并且想要创建对应 C 库函数 @code{system()} @footnote{@w{(1)} 
这个函数的接口已经在标准模块 @ref{c4,,os} 里了，这里作为一个简单而直接的例子。
} 的 Python 接口。 这个函数接受一个以 null 结尾的字符串参数并返回一个整数。 我们希望可以在 Python 中以如下方式调用此函数:

@example
>>> import spam
>>> status = spam.system("ls -l")
@end example

首先创建一个 @code{spammodule.c} 文件。（传统上，如果一个模块叫 @code{spam}，则对应实现它的 C 文件叫 @code{spammodule.c}；如果这个模块名字非常长，比如 @code{spammify}，则这个模块的文件可以直接叫 @code{spammify.c}。）

文件中开始的两行是：

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
@end example

这会导入 Python API（如果你喜欢，你可以在这里添加描述模块目标和版权信息的注释)。

@cartouche
@quotation 注解 
由于Python可能会定义一些影响某些系统上标准头文件的预处理器定义，因此在包含任何标准头文件之前，您*必须* include 这个文件：@cite{Python.h}。

推荐总是在 @code{Python.h} 前定义 @code{PY_SSIZE_T_CLEAN} 。查看 @ref{3d52,,提取扩展函数的参数} 来了解这个宏的更多内容。
@end quotation
@end cartouche

所有在 @code{Python.h} 中定义的用户可见的符号都具有 @code{Py} 或 @code{PY} 前缀，已在标准头文件中定义的那些除外。 考虑到便利性，也由于其在 Python 解释器中被广泛使用，@code{"Python.h"} 还包含了一些标准头文件: @code{<stdio.h>}，@code{<string.h>}，@code{<errno.h>} 和 @code{<stdlib.h>}。 如果后面的头文件在你的系统上不存在，它还会直接声明函数 @code{malloc()}，@code{free()} 和 @code{realloc()}。

下面要做的事是将 C 函数添加到我们的扩展模块，当 Python 表达式 @code{spam.system(string)} 被求值时函数将被调用（我们很快就会看到它最终是如何被调用的）:

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
@}
@end example

有个直接翻译参数列表的方法(例如单独的 @code{“ls-l"})到要传递给C函数的参数。C函数总是有两个参数，通常名字是 @emph{self} 和 @emph{args} 。

对模块级函数， @emph{self} 参数指向模块对象；对于方法则指向对象实例。

@emph{args} 参数是指向一个 Python 的 tuple 对象的指针，其中包含参数。 每个 tuple 项对应一个调用参数。 这些参数也全都是 Python 对象 --- 要在我们的 C 函数中使用它们就需要先将其转换为 C 值。 Python API 中的函数 @ref{39b,,PyArg_ParseTuple()} 会检查参数类型并将其转换为 C 值。 它使用模板字符串确定需要的参数类型以及存储被转换的值的 C 变量类型。 细节将稍后说明。

@ref{39b,,PyArg_ParseTuple()} 在所有参数都有正确类型且组成部分按顺序放在传递进来的地址里时，返回真(非零)。其在传入无效参数时返回假(零)。在后续例子里，还会抛出特定异常，使得调用的函数可以理解返回 @code{NULL} (也就是例子里所见)。

@node 关于错误和异常,回到例子,一个简单的例子,使用 C 或 C++ 扩展 Python
@anchor{extending/extending extending-errors}@anchor{3d53}@anchor{extending/extending intermezzo-errors-and-exceptions}@anchor{3d54}
@subsubsection 关于错误和异常


整个 Python 解释器系统有一个如下所述的重要惯例：当一个函数运行失败时，它应当设置一个异常条件并返回一个错误值（通常为 @code{-1} 或 @code{NULL} 指针）。 异常信息保存在解释器线程状态的三个成员中。 如果没有异常则它们的值为 @code{NULL}。 在其他情况下它们是 @ref{d2f,,sys.exc_info()} 所返回的 Python 元组的成员的 C 对应物。 它们分别是异常类型、异常实例和回溯对象。 理解它们对于理解错误是如何被传递的非常重要。

Python API中定义了一些函数来设置这些变量。

最常用的就是 @ref{3d55,,PyErr_SetString()}。 其参数是异常对象和 C 字符串。 异常对象一般是像 @code{PyExc_ZeroDivisionError} 这样的预定义对象。 C 字符串指明异常原因，并被转换为一个 Python 字符串对象存储为异常的“关联值”。

另一个有用的函数是 @ref{3d56,,PyErr_SetFromErrno()} ，仅接受一个异常对象，异常描述包含在全局变量 @code{errno} 中。最通用的函数还是 @ref{3d57,,PyErr_SetObject()} ，包含两个参数，分别为异常对象和异常描述。你不需要使用 @ref{396,,Py_INCREF()} 来增加传递到其他函数的参数对象的引用计数。

你可以通过 @ref{3d58,,PyErr_Occurred()} 在不造成破坏的情况下检测是否设置了异常。 这将返回当前异常对象，或者如果未发生异常则返回 @code{NULL}。 你通常不需要调用 @ref{3d58,,PyErr_Occurred()} 来查看函数调用中是否发生了错误，因为你应该能从返回值中看出来。

当一个函数 @emph{f} 调用另一个函数 @emph{g} 时检测到后者出错了，@emph{f} 应当自己返回一个错误值 (通常为 @code{NULL} 或 @code{-1})。 它 @emph{不应该} 调用某个 @code{PyErr_*()} 函数 --- 这类函数已经被 @emph{g} 调用过了。 @emph{f} 的调用者随后也应当返回一个错误来提示 @emph{它的} 调用者，同样 @emph{不应该} 调用 @code{PyErr_*()}，依此类推 --- 错误的最详细原因已经由首先检测到它的函数报告了。 一旦这个错误到达 Python 解释器的主循环，它会中止当前执行的 Python 代码并尝试找出由 Python 程序员所指定的异常处理程序。

（在某些情况下，当模块确实能够通过调用其它 @code{PyErr_*()} 函数给出更加详细的错误消息，并且在这些情况是可以这样做的。 但是按照一般规则，这是不必要的，并可能导致有关错误原因的信息丢失：大多数操作会由于种种原因而失败。）

想要忽略由一个失败的函数调用所设置的异常，异常条件必须通过调用 @ref{a55,,PyErr_Clear()} 显式地被清除。 C 代码应当调用 @ref{a55,,PyErr_Clear()} 的唯一情况是如果它不想将错误传给解释器而是想完全由自己来处理它（可能是尝试其他方法，或是假装没有出错）。

每次失败的 @code{malloc()} 调用必须转换为一个异常。 @code{malloc()} (或 @code{realloc()} )的直接调用者必须调用 @ref{3d59,,PyErr_NoMemory()} 来返回错误来提示。所有对象创建函数(例如 @ref{3d5a,,PyLong_FromLong()} )已经这么做了，所以这个提示仅用于直接调用 @code{malloc()} 的情况。

还要注意的是，除了 @ref{39b,,PyArg_ParseTuple()} 等重要的例外，返回整数状态码的函数通常都是返回正值或零来表示成功，而以 @code{-1} 表示失败，如同 Unix 系统调用一样。

最后，当你返回一个错误指示器时要注意清理垃圾（通过为你已经创建的对象执行 @ref{399,,Py_XDECREF()} 或 @ref{397,,Py_DECREF()} 调用）！

选择引发哪个异常完全取决于你的喜好。 所有内置的 Python 异常都有对应的预声明 C 对象，例如 @code{PyExc_ZeroDivisionError}，你可以直接使用它们。 当然，你应当明智地选择异常 --- 不要使用 @code{PyExc_TypeError} 来表示一个文件无法被打开 (那大概应该用 @code{PyExc_IOError})。 如果参数列表有问题，@ref{39b,,PyArg_ParseTuple()} 函数通常会引发 @code{PyExc_TypeError}。 如果你想要一个参数的值必须处于特定范围之内或必须满足其他条件，则适宜使用 @code{PyExc_ValueError}。

你也可以为你的模块定义一个唯一的新异常。需要在文件前部声明一个静态对象变量，如:

@example
static PyObject *SpamError;
@end example

并且在你的模块的初始化函数 (@code{PyInit_spam()}) 中使用一个异常对象来初始化:

@example
PyMODINIT_FUNC
PyInit_spam(void)
@{
    PyObject *m;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    Py_XINCREF(SpamError);
    if (PyModule_AddObject(m, "error", SpamError) < 0) @{
        Py_XDECREF(SpamError);
        Py_CLEAR(SpamError);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

注意异常对象的Python名字是 @code{spam.error} 。而 @ref{cd3,,PyErr_NewException()} 函数可以创建一个类，其基类为 @ref{2e3,,Exception} (除非是另一个类传入以替换 @code{NULL} )， 细节参见 @ref{fbe,,内置异常} 。

同样注意的是创建类保存了 @code{SpamError} 的一个引用，这是有意的。为了防止被垃圾回收掉，否则 @code{SpamError} 随时会成为野指针。

一会讨论 @code{PyMODINIT_FUNC} 作为函数返回类型的用法。

@code{spam.error} 异常可以在扩展模块中抛出，通过 @ref{3d55,,PyErr_SetString()} 函数调用，如下：

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    if (sts < 0) @{
        PyErr_SetString(SpamError, "System command failed");
        return NULL;
    @}
    return PyLong_FromLong(sts);
@}
@end example

@node 回到例子,模块方法表和初始化函数,关于错误和异常,使用 C 或 C++ 扩展 Python
@anchor{extending/extending back-to-the-example}@anchor{3d5b}@anchor{extending/extending backtoexample}@anchor{3d5c}
@subsubsection 回到例子


回到前面的例子，你应该明白下面的代码:

@example
if (!PyArg_ParseTuple(args, "s", &command))
    return NULL;
@end example

如果在参数列表中检测到错误，它将返回 @code{NULL} (该值是返回对象指针的函数所使用的错误提示)，这取决于 @ref{39b,,PyArg_ParseTuple()} 设置的异常。 在其他情况下参数的字符串值会被拷贝到局部变量 @code{command}。 这是一个指针赋值并且你不应该修改它所指向的字符串 (因此在标准 C 中，变量 @code{command} 应当被正确地声明为 @code{const char *command})。

下一个语句使用UNIX系统函数 @code{system()} ，传递给他的参数是刚才从 @ref{39b,,PyArg_ParseTuple()} 取出的:

@example
sts = system(command);
@end example

我们的 @code{spam.system()} 函数必须返回 @code{sts} 的值作为Python对象。这通过使用函数 @ref{3d5a,,PyLong_FromLong()} 来实现。

@example
return PyLong_FromLong(sts);
@end example

在这种情况下，会返回一个整数对象，(这个对象会在Python堆里面管理)。

如果你的 C 函数没有有用的返回值 (返回 @code{void} 的函数)，则对应的 Python 函数必须返回 @code{None}。 你必须使用这种写法（可以通过 @ref{ea3,,Py_RETURN_NONE} 宏来实现）:

@example
Py_INCREF(Py_None);
return Py_None;
@end example

@ref{3d5d,,Py_None} 是特殊 Python 对象 @code{None} 所对应的 C 名称。 它是一个真正的 Python 对象而不是 @code{NULL} 指针，如我们所见，后者在大多数上下文中都意味着“错误”。

@node 模块方法表和初始化函数,编译和链接,回到例子,使用 C 或 C++ 扩展 Python
@anchor{extending/extending methodtable}@anchor{3d5e}@anchor{extending/extending the-module-s-method-table-and-initialization-function}@anchor{3d5f}
@subsubsection 模块方法表和初始化函数


为了展示 @code{spam_system()} 如何被Python程序调用。把函数声明为可以被Python调用，需要先定义一个方法表 "method table" 。

@example
static PyMethodDef SpamMethods[] = @{
    ...
    @{"system",  spam_system, METH_VARARGS,
     "Execute a shell command."@},
    ...
    @{NULL, NULL, 0, NULL@}        /* Sentinel */
@};
@end example

注意第三个参数 ( @code{METH_VARARGS} ) ，这个标志指定会使用C的调用惯例。可选值有  @code{METH_VARARGS} 、 @code{METH_VARARGS | METH_KEYWORDS} 。值 @code{0} 代表使用 @ref{39b,,PyArg_ParseTuple()} 的陈旧变量。

如果单独使用 @code{METH_VARARGS} ，函数会等待Python传来tuple格式的参数，并最终使用  @ref{39b,,PyArg_ParseTuple()} 进行解析。

@code{METH_KEYWORDS} 值表示接受关键字参数。这种情况下C函数需要接受第三个 @code{PyObject *}  对象，表示字典参数，使用 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 来解析出参数。

这个方法表必须被模块定义结构所引用。

@example
static struct PyModuleDef spammodule = @{
    PyModuleDef_HEAD_INIT,
    "spam",   /* name of module */
    spam_doc, /* module documentation, may be NULL */
    -1,       /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    SpamMethods
@};
@end example

这个结构体必须传递给解释器的模块初始化函数。初始化函数必须命名为 @code{PyInit_name()} ，其中 @emph{name} 是模块的名字，并应该定义为非 @code{static} ，且在模块文件里：

@example
PyMODINIT_FUNC
PyInit_spam(void)
@{
    return PyModule_Create(&spammodule);
@}
@end example

注意 PyMODINIT_FUNC 将函数声明为 @code{PyObject *} 返回类型，声明了任何平台所要求的特殊链接声明，并针对 C++ 将函数声明为 @code{extern "C"}。

当 Python 程序首次导入 @code{spam} 模块时， @code{PyInit_spam()} 会被调用。 （有关嵌入 Python 的注释参见下文。） 它将调用 @ref{3d60,,PyModule_Create()}，该函数会返回一个模块对象，并基于在模块定义中找到的表将内置函数对象插入到新创建的模块中（该表是一个 @ref{ee5,,PyMethodDef} 结构体的数组）。 @ref{3d60,,PyModule_Create()} 返回一个指向它所创建的模块对象的指针。 它可能会因程度严重的特定错误而中止，或者在模块无法成功初始化时返回 @code{NULL}。 初始化函数必须返回模块对象给其调用者，这样它就可以被插入到 @code{sys.modules} 中。

当嵌入Python时， @code{PyInit_spam()} 函数不会被自动调用，除非放在 @code{PyImport_Inittab} 表里。要添加模块到初始化表，使用 @ref{fe7,,PyImport_AppendInittab()} ，可选的跟着一个模块的导入。

@example
int
main(int argc, char *argv[])
@{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) @{
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    @}

    /* Add a built-in module, before Py_Initialize */
    if (PyImport_AppendInittab("spam", PyInit_spam) == -1) @{
        fprintf(stderr, "Error: could not extend in-built modules table\n");
        exit(1);
    @}

    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(program);

    /* Initialize the Python interpreter.  Required.
       If this step fails, it will be a fatal error. */
    Py_Initialize();

    /* Optionally import the module; alternatively,
       import can be deferred until the embedded script
       imports it. */
    PyObject *pmodule = PyImport_ImportModule("spam");
    if (!pmodule) @{
        PyErr_Print();
        fprintf(stderr, "Error: could not import module 'spam'\n");
    @}

    ...

    PyMem_RawFree(program);
    return 0;
@}
@end example

@cartouche
@quotation 注解 
要从 @code{sys.modules} 删除实体或导入已编译模块到一个进程里的多个解释器(或使用 @code{fork()} 而没用 @code{exec()} )会在一些扩展模块上产生错误。扩展模块作者可以在初始化内部数据结构时给出警告。
@end quotation
@end cartouche

更多关于模块的现实的例子包含在Python源码包的 @code{Modules/xxmodule.c} 中。这些文件可以用作你的代码模板，或者学习。脚本 modulator.py 包含在源码发行版或Windows安装中，提供了一个简单的GUI，用来声明需要实现的函数和对象，并且可以生成供填入的模板。脚本在 Tools/modulator/ 目录。查看README以了解用法。

@cartouche
@quotation 注解 
不像我们的 @code{spam} 例子， @code{xxmodule} 使用了 @emph{多阶段初始化} (Python3.5开始引入)， @code{PyInit_spam} 会返回一个 PyModuleDef 结构体，然后创建的模块放到导入机制。细节参考 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} 的多阶段初始化。
@end quotation
@end cartouche

@node 编译和链接,在C中调用Python函数,模块方法表和初始化函数,使用 C 或 C++ 扩展 Python
@anchor{extending/extending compilation}@anchor{3d61}@anchor{extending/extending compilation-and-linkage}@anchor{3d62}
@subsubsection 编译和链接


在你能使用你的新写的扩展之前，你还需要做两件事情：使用 Python 系统来编译和链接。如果你使用动态加载，这取决于你使用的操作系统的动态加载机制；更多信息请参考编译扩展模块的章节（ @ref{3d63,,构建C/C++扩展} 章节），以及在 Windows 上编译需要的额外信息（ @ref{14fb,,在 Windows 上构建 C 和 C++ 扩展} 章节）。

如果你不使用动态加载，或者想要让模块永久性的作为Python解释器的一部分，就必须修改配置设置，并重新构建解释器。幸运的是在Unix上很简单，只需要把你的文件 ( @code{spammodule.c} 为例) 放在解压缩源码发行包的 @code{Modules/} 目录下，添加一行到 @code{Modules/Setup.local} 来描述你的文件：

@example
spam spammodule.o
@end example

然后在顶层目录运行 @code{make} 来重新构建解释器。你也可以在 @code{Modules/} 子目录使用 @code{make}，但是你必须先重建 @code{Makefile} 文件，然后运行 '@code{make} Makefile' 命令。（你每次修改 @code{Setup} 文件都需要这样操作。）

如果你的模块需要额外的链接，这些内容可以列出在配置文件里，举个实例：

@example
spam spammodule.o -lX11
@end example

@node 在C中调用Python函数,提取扩展函数的参数,编译和链接,使用 C 或 C++ 扩展 Python
@anchor{extending/extending calling-python-functions-from-c}@anchor{3d64}@anchor{extending/extending callingpython}@anchor{3d65}
@subsubsection 在C中调用Python函数


迄今为止，我们一直把注意力集中于让Python调用C函数，其实反过来也很有用，就是用C调用Python函数。这在回调函数中尤其有用。如果一个C接口使用回调，那么就要实现这个回调机制。

幸运的是，Python解释器是比较方便回调的，并给标准Python函数提供了标准接口。(这里就不再详述解析Python代码作为输入的方式，如果有兴趣可以参考 @code{Python/pythonmain.c} 中的 @ref{136f,,-c} 命令代码。)

调用Python函数，首先Python程序要传递Python函数对象。应该提供个函数(或其他接口)来实现。当调用这个函数时，用全局变量保存Python函数对象的指针，还要调用 (@ref{396,,Py_INCREF()}) 来增加引用计数，当然不用全局变量也没什么关系。例如如下:

@example
static PyObject *my_callback = NULL;

static PyObject *
my_set_callback(PyObject *dummy, PyObject *args)
@{
    PyObject *result = NULL;
    PyObject *temp;

    if (PyArg_ParseTuple(args, "O:set_callback", &temp)) @{
        if (!PyCallable_Check(temp)) @{
            PyErr_SetString(PyExc_TypeError, "parameter must be callable");
            return NULL;
        @}
        Py_XINCREF(temp);         /* Add a reference to new callback */
        Py_XDECREF(my_callback);  /* Dispose of previous callback */
        my_callback = temp;       /* Remember new callback */
        /* Boilerplate to return "None" */
        Py_INCREF(Py_None);
        result = Py_None;
    @}
    return result;
@}
@end example

这个函数必须使用 @ref{f12,,METH_VARARGS} 标志注册到解释器，这在 @ref{3d5e,,模块方法表和初始化函数} 章节会描述。 @ref{39b,,PyArg_ParseTuple()} 函数及其参数的文档在 @ref{3d52,,提取扩展函数的参数} 。

@ref{398,,Py_XINCREF()} 和 @ref{399,,Py_XDECREF()} 这两个宏可增加/减少一个对象的引用计数，并且当存在 @code{NULL} 指针时仍可保证安全 (但请注意在这个上下文中 @emph{temp} 将不为  @code{NULL})。 更多相关信息请参考 @ref{3d66,,引用计数} 章节。

@geindex PyObject_CallObject()

随后，当要调用此函数时，你将调用 C 函数 @ref{3d67,,PyObject_CallObject()}。 该函数有两个参数，它们都属于指针，指向任意 Python 对象：即 Python 函数，及其参数列表。 参数列表必须总是一个元组对象，其长度即参数的个数量。 要不带参数地调用 Python 函数，则传入 @code{NULL} 或一个空元组；要带一个参数调用它，则传入一个单元组。 @ref{3f9,,Py_BuildValue()} 会在其格式字符串包含一对圆括号内的零个或多个格式代码时返回一个元组。 例如:

@example
int arg;
PyObject *arglist;
PyObject *result;
...
arg = 123;
...
/* Time to call the callback */
arglist = Py_BuildValue("(i)", arg);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
@end example

@ref{3d67,,PyObject_CallObject()} 返回Python对象指针，这也是Python函数的返回值。 @ref{3d67,,PyObject_CallObject()} 是一个对其参数 "引用计数无关" 的函数。例子中新的元组创建用于参数列表，并且在  @ref{3d67,,PyObject_CallObject()} 之后立即使用了 @ref{397,,Py_DECREF()} 。

@code{PyEval_CallObject()} 的返回值总是“新”的：要么是一个新建的对象；要么是已有对象，但增加了引用计数。所以除非你想把结果保存在全局变量中，你需要对这个值使用 @ref{397,,Py_DECREF()}，即使你对里面的内容（特别！）不感兴趣。

但是在你这么做之前，很重要的一点是检查返回值不是 @code{NULL}。 如果是的话，Python 函数会终止并引发异常。 如果调用 @ref{3d67,,PyObject_CallObject()} 的 C 代码是在 Python 中发起调用的，它应当立即返回一个错误来告知其 Python 调用者，以便解释器能打印栈回溯信息，或者让调用方 Python 代码能处理该异常。 如果这无法做到或不合本意，则应当通过调用 @ref{a55,,PyErr_Clear()} 来清除异常。 例如:

@example
if (result == NULL)
    return NULL; /* Pass error back */
...use result...
Py_DECREF(result);
@end example

依赖于具体的回调函数，你还要提供一个参数列表到 @code{PyEval_CallObject()} 。在某些情况下参数列表是由Python程序提供的，通过接口再传到回调函数。这样就可以不改变形式直接传递。另外一些时候你要构造一个新的tuple来传递参数。最简单的方法就是 @ref{3f9,,Py_BuildValue()} 函数构造tuple。例如，你要传递一个事件对象时可以用:

@example
PyObject *arglist;
...
arglist = Py_BuildValue("(l)", eventcode);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);
@end example

注意 @code{Py_DECREF(arglist)} 所在处会立即调用，在错误检查之前。当然还要注意一些常规的错误，比如 @ref{3f9,,Py_BuildValue()} 可能会遭遇内存不足等等。

你还需要注意，用关键字参数调用 @ref{23d,,PyObject_Call()} ，需要支持普通参数和关键字参数。有如如上例子中，我们使用 @ref{3f9,,Py_BuildValue()} 来构造字典。

@example
PyObject *dict;
...
dict = Py_BuildValue("@{s:i@}", "name", val);
result = PyObject_Call(my_callback, NULL, dict);
Py_DECREF(dict);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);
@end example

@node 提取扩展函数的参数,给扩展函数的关键字参数,在C中调用Python函数,使用 C 或 C++ 扩展 Python
@anchor{extending/extending extracting-parameters-in-extension-functions}@anchor{3d68}@anchor{extending/extending parsetuple}@anchor{3d52}
@subsubsection 提取扩展函数的参数


@geindex PyArg_ParseTuple()

函数 @ref{39b,,PyArg_ParseTuple()} 的声明如下：

@example
int PyArg_ParseTuple(PyObject *arg, const char *format, ...);
@end example

参数 @emph{arg} 必须是一个元组对象，包含从 Python 传递给 C 函数的参数列表。@emph{format} 参数必须是一个格式字符串，语法请参考 Python C/API 手册中的 @ref{3fb,,语句解释及变量编译}。剩余参数是各个变量的地址，类型要与格式字符串对应。

注意 @ref{39b,,PyArg_ParseTuple()} 会检测他需要的Python参数类型，却无法检测传递给他的C变量地址，如果这里出错了，可能会在内存中随机写入东西，小心。

注意任何由调用者提供的Python对象引用是 @emph{借来的} 引用；不要递减它们的引用计数！

一些调用的例子：

@example
#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
#include <Python.h>
@end example

@example
int ok;
int i, j;
long k, l;
const char *s;
Py_ssize_t size;

ok = PyArg_ParseTuple(args, ""); /* No arguments */
    /* Python call: f() */
@end example

@example
ok = PyArg_ParseTuple(args, "s", &s); /* A string */
    /* Possible Python call: f('whoops!') */
@end example

@example
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
    /* Possible Python call: f(1, 2, 'three') */
@end example

@example
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
    /* A pair of ints and a string, whose size is also returned */
    /* Possible Python call: f((1, 2), 'three') */
@end example

@example
@{
    const char *file;
    const char *mode = "r";
    int bufsize = 0;
    ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
    /* A string, and optionally another string and an integer */
    /* Possible Python calls:
       f('spam')
       f('spam', 'w')
       f('spam', 'wb', 100000) */
@}
@end example

@example
@{
    int left, top, right, bottom, h, v;
    ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
             &left, &top, &right, &bottom, &h, &v);
    /* A rectangle and a point */
    /* Possible Python call:
       f(((0, 0), (400, 300)), (10, 10)) */
@}
@end example

@example
@{
    Py_complex c;
    ok = PyArg_ParseTuple(args, "D:myfunction", &c);
    /* a complex, also providing a function name for errors */
    /* Possible Python call: myfunction(1+2j) */
@}
@end example

@node 给扩展函数的关键字参数,构造任意值,提取扩展函数的参数,使用 C 或 C++ 扩展 Python
@anchor{extending/extending keyword-parameters-for-extension-functions}@anchor{3d69}@anchor{extending/extending parsetupleandkeywords}@anchor{3d6a}
@subsubsection 给扩展函数的关键字参数


@geindex PyArg_ParseTupleAndKeywords()

函数 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 声明如下：

@example
int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                const char *format, char *kwlist[], ...);
@end example

@emph{arg} 与 @emph{format} 形参与 @ref{39b,,PyArg_ParseTuple()} 函数所定义的一致。 @emph{kwdict} 形参是作为第三个参数从 Python 运行时接收的关键字字典。 @emph{kwlist} 形参是以 @code{NULL} 结尾的字符串列表，它被用来标识形参；名称从左至右与来自 @emph{format} 的类型信息相匹配。 如果执行成功，@ref{6cb,,PyArg_ParseTupleAndKeywords()} 会返回真值，否则返回假值并引发一个适当的异常。

@cartouche
@quotation 注解 
嵌套的元组在使用关键字参数时无法生效，不在 @emph{kwlist} 中的关键字参数会导致 @ref{1ff,,TypeError} 异常。
@end quotation
@end cartouche

@geindex Philbrick@comma{} Geoff

如下是使用关键字参数的例子模块，作者是 Geoff Philbrick (@email{phibrick@@hks.com}):

@example
#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
#include <Python.h>

static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
@{
    int voltage;
    const char *state = "a stiff";
    const char *action = "voom";
    const char *type = "Norwegian Blue";

    static char *kwlist[] = @{"voltage", "state", "action", "type", NULL@};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                     &voltage, &state, &action, &type))
        return NULL;

    printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

    Py_RETURN_NONE;
@}

static PyMethodDef keywdarg_methods[] = @{
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    @{"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."@},
    @{NULL, NULL, 0, NULL@}   /* sentinel */
@};

static struct PyModuleDef keywdargmodule = @{
    PyModuleDef_HEAD_INIT,
    "keywdarg",
    NULL,
    -1,
    keywdarg_methods
@};

PyMODINIT_FUNC
PyInit_keywdarg(void)
@{
    return PyModule_Create(&keywdargmodule);
@}
@end example

@node 构造任意值,引用计数,给扩展函数的关键字参数,使用 C 或 C++ 扩展 Python
@anchor{extending/extending building-arbitrary-values}@anchor{3d6b}@anchor{extending/extending buildvalue}@anchor{3d6c}
@subsubsection 构造任意值


这个函数与 @ref{39b,,PyArg_ParseTuple()} 很相似，声明如下：

@example
PyObject *Py_BuildValue(const char *format, ...);
@end example

接受一个格式字符串，与 @ref{39b,,PyArg_ParseTuple()} 相同，但是参数必须是原变量的地址指针(输入给函数，而非输出)。最终返回一个Python对象适合于返回C函数调用给Python代码。

一个与 @ref{39b,,PyArg_ParseTuple()} 的不同是，后面可能需要的要求返回一个元组(Python参数里诶包总是在内部描述为元组)，比如用于传递给其他Python函数以参数。 @ref{3f9,,Py_BuildValue()} 并不总是生成元组，在多于1个参数时会生成元组，而如果没有参数则返回 @code{None} ，一个参数则直接返回该参数的对象。如果要求强制生成一个长度为空的元组，或包含一个元素的元组，需要在格式字符串中加上括号。

例子(左侧是调用，右侧是Python值结果)：

@example
Py_BuildValue("")                        None
Py_BuildValue("i", 123)                  123
Py_BuildValue("iii", 123, 456, 789)      (123, 456, 789)
Py_BuildValue("s", "hello")              'hello'
Py_BuildValue("y", "hello")              b'hello'
Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
Py_BuildValue("s#", "hello", 4)          'hell'
Py_BuildValue("y#", "hello", 4)          b'hell'
Py_BuildValue("()")                      ()
Py_BuildValue("(i)", 123)                (123,)
Py_BuildValue("(ii)", 123, 456)          (123, 456)
Py_BuildValue("(i,i)", 123, 456)         (123, 456)
Py_BuildValue("[i,i]", 123, 456)         [123, 456]
Py_BuildValue("@{s:i,s:i@}",
              "abc", 123, "def", 456)    @{'abc': 123, 'def': 456@}
Py_BuildValue("((ii)(ii)) (ii)",
              1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))
@end example

@node 引用计数,在C++中编写扩展,构造任意值,使用 C 或 C++ 扩展 Python
@anchor{extending/extending refcounts}@anchor{3d66}@anchor{extending/extending reference-counts}@anchor{3d6d}
@subsubsection 引用计数


在C/C++语言中，程序员负责动态分配和回收堆(heap)当中的内存。在C里，通过函数 @code{malloc()} 和 @code{free()} 来完成。在C++里是操作 @code{new} 和 @code{delete} 来实现相同的功能。

每个由 @code{malloc()} 分配的内存块，最终都要由 @code{free()} 退回到可用内存池里面去。而调用 @code{free()} 的时机非常重要，如果一个内存块忘了 @code{free()} 则会导致内存泄漏，这块内存在程序结束前将无法重新使用。这叫做 @emph{内存泄漏} 。而如果对同一内存块 @code{free()} 了以后，另外一个指针再次访问，则再次使用 @code{malloc()} 复用这块内存会导致冲突。这叫做 @emph{野指针} 。等同于使用未初始化的数据，core dump，错误结果，神秘的崩溃等。

内存泄露往往发生在一些并不常见的代码流程上面。比如一个函数申请了内存以后，做了些计算，然后释放内存块。现在一些对函数的修改可能增加对计算的测试并检测错误条件，然后过早的从函数返回了。这很容易忘记在退出前释放内存，特别是后期修改的代码。这种内存泄漏，一旦引入，通常很长时间都难以检测到，错误退出被调用的频度较低，而现代电脑又有非常巨大的虚拟内存，所以泄漏仅在长期运行或频繁调用泄漏函数时才会变得明显。因此，有必要避免内存泄漏，通过代码规范会策略来最小化此类错误。

Python通过 @code{malloc()} 和 @code{free()} 包含大量的内存分配和释放，同样需要避免内存泄漏和野指针。他选择的方法就是 @emph{引用计数} 。其原理比较简单：每个对象都包含一个计数器，计数器的增减与对象引用的增减直接相关，当引用计数为0时，表示对象已经没有存在的意义了，对象就可以删除了。

另一个叫法是 @emph{自动垃圾回收} 。(有时引用计数也被看作是垃圾回收策略，于是这里的"自动"用以区分两者)。自动垃圾回收的优点是用户不需要明确的调用 @code{free()} 。(另一个优点是改善速度或内存使用，然而这并不难)。缺点是对C，没有可移植的自动垃圾回收器，而引用计数则可以可移植的实现(只要 @code{malloc()} 和 @code{free()} 函数是可用的，这也是C标准担保的)。也许以后有一天会出现可移植的自动垃圾回收器，但在此前我们必须与引用计数一起工作。

Python使用传统的引用计数实现，也提供了循环监测器，用以检测引用循环。这使得应用无需担心直接或间接的创建了循环引用，这是引用计数垃圾收集的一个弱点。引用循环是对象(可能直接)的引用了本身，所以循环中的每个对象的引用计数都不是0。典型的引用计数实现无法回收处于引用循环中的对象，或者被循环所引用的对象，哪怕没有循环以外的引用了。

循环探测器可以检测垃圾循环并回收。 @ref{84,,gc} 模块提供了方法运行探测器 ( @ref{362,,collect()} 函数) ，而且可以在运行时配置禁用探测器。循环探测器被当作可选组件，默认是包含的，也可以在构建时禁用，在Unix平台(包括Mac OS X)使用 @code{--without-cycle-gc} 选项到 @code{configure} 脚本。如果循环探测器被禁用， @ref{84,,gc} 模块就不可用了。

@menu
* Python中的引用计数:: 
* 拥有规则:: 
* 危险的薄冰:: 
* NULL指针:: 

@end menu

@node Python中的引用计数,拥有规则,,引用计数
@anchor{extending/extending refcountsinpython}@anchor{3d6e}@anchor{extending/extending reference-counting-in-python}@anchor{3d6f}
@subsubsection Python中的引用计数


有两个宏 @code{Py_INCREF(x)} 和 @code{Py_DECREF(x)} ，会处理引用计数的增减。 @ref{397,,Py_DECREF()} 也会在引用计数到达0时释放对象。为了灵活，并不会直接调用 @code{free()} ，而是通过对象的 @emph{类型对象} 的函数指针来调用。为了这个目的(或其他的)，每个对象同时包含一个指向自身类型对象的指针。

最大的问题依旧：何时使用 @code{Py_INCREF(x)} 和 @code{Py_DECREF(x)} ？我们首先引入一些概念。没有人"拥有"一个对象，你可以 @emph{拥有一个引用} 到一个对象。一个对象的引用计数定义为拥有引用的数量。引用的拥有者有责任调用 @ref{397,,Py_DECREF()} ，在引用不再需要时。引用的拥有关系可以被传递。有三种办法来处置拥有的引用：传递、存储、调用 @ref{397,,Py_DECREF()} 。忘记处置一个拥有的引用会导致内存泄漏。

还可以 @emph{借用} @footnote{@w{(2)} 
术语"借用"一个引用是不完全正确的：拥有者仍然有引用的拷贝。
} 一个对象的引用。借用的引用不应该调用 @ref{397,,Py_DECREF()} 。借用者必须确保不能持有对象超过拥有者借出的时间。在拥有者处置对象后使用借用的引用是有风险的，应该完全避免 @footnote{@w{(3)} 
检查引用计数至少为1 @strong{没有用} ，引用计数本身可以在已经释放的内存里，并有可能被其他对象所用。
} 。

借用相对于引用的优点是你无需担心整条路径上代码的引用，或者说，通过借用你无需担心内存泄漏的风险。借用的缺点是一些看起来正确代码上的借用可能会在拥有者处置后使用对象。

借用可以变为拥有引用，通过调用 @ref{396,,Py_INCREF()}。 这不会影响已经借出的拥有者的状态。 这会创建一个新的拥有引用，并给予完全的拥有者责任（新的拥有者必须恰当的处置引用，就像之前的拥有者那样）。

@node 拥有规则,危险的薄冰,Python中的引用计数,引用计数
@anchor{extending/extending ownership-rules}@anchor{3d70}@anchor{extending/extending ownershiprules}@anchor{3d71}
@subsubsection 拥有规则


当一个对象引用传递进出一个函数时，函数的接口应该指定拥有关系的传递是否包含引用。

大多数函数返回一个对象的引用，并传递引用拥有关系。通常，所有创建对象的函数，例如 @ref{3d5a,,PyLong_FromLong()} 和 @ref{3f9,,Py_BuildValue()} ，会传递拥有关系给接收者。即便是对象不是真正新的，你仍然可以获得对象的新引用。一个实例是 @ref{3d5a,,PyLong_FromLong()} 维护了一个流行值的缓存，并可以返回已缓存项目的新引用。

很多另一个对象提取对象的函数，也会传递引用关系，例如 @ref{3d72,,PyObject_GetAttrString()} 。这里的情况不够清晰，一些不太常用的例程是例外的 @ref{3d73,,PyTuple_GetItem()} ， @ref{3d74,,PyList_GetItem()} ， @ref{3d75,,PyDict_GetItem()} ， @ref{3d76,,PyDict_GetItemString()} 都是返回从元组、列表、字典里借用的引用。

函数 @ref{3d77,,PyImport_AddModule()} 也会返回借用的引用，哪怕可能会返回创建的对象：这个可能因为一个拥有的引用对象是存储在 @code{sys.modules} 里。

当你传递一个对象引用到另一个函数时，通常函数是借用出去的。如果需要存储，就使用 @ref{396,,Py_INCREF()} 来变成独立的拥有者。这个规则有两个重要的例外： @ref{3d78,,PyTuple_SetItem()} 和 @ref{3d79,,PyList_SetItem()} 。这些函数接受传递来的引用关系，哪怕会失败！(注意 @ref{3d7a,,PyDict_SetItem()} 及其同类不会接受引用关系，他们是"正常的")。

当一个C函数被Python调用时，会从调用方传来的参数借用引用。调用者拥有对象的引用，所以借用的引用生命周期可以保证到函数返回。只要当借用的引用需要存储或传递时，就必须转换为拥有的引用，通过调用 @ref{396,,Py_INCREF()} 。

Python调用从C函数返回的对象引用时必须是拥有的引用---拥有关系被从函数传递给调用者。

@node 危险的薄冰,NULL指针,拥有规则,引用计数
@anchor{extending/extending thin-ice}@anchor{3d7b}@anchor{extending/extending thinice}@anchor{3d7c}
@subsubsection 危险的薄冰


有少数情况下，借用的引用看起来无害，但却可能导致问题。这通常是因为解释器的隐式调用，并可能导致引用拥有者处置这个引用。

首先需要特别注意的情况是使用 @ref{397,,Py_DECREF()} 到一个无关对象，而这个对象的引用是借用自一个列表的元素。举个实例：

@example
void
bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);

    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0); /* BUG! */
@}
@end example

这个函数首先借用一个引用 @code{list[0]} ，然后替换 @code{list[1]} 为值 @code{0} ，最后打印借用的引用。看起来无害是吧，但却不是。

我们跟着控制流进入 @ref{3d79,,PyList_SetItem()} 。列表拥有者引用了其所有成员，所以当成员1被替换时，就必须处置原来的成员1。现在假设原来的成员1是用户定义类的实例，且假设这个类定义了 @ref{a0d,,__del__()} 方法。如果这个类实例的引用计数是1，那么处置动作就会调用 @ref{a0d,,__del__()} 方法。

既然是Python写的， @ref{a0d,,__del__()} 方法可以执行任意Python代码。是否可能在 @code{bug()} 的 @code{item} 废止引用呢，是的。假设列表传递到 @code{bug()} 会被 @ref{a0d,,__del__()} 方法所访问，就可以执行一个语句来实现 @code{del list[0]} ，然后假设这是最后一个对对象的引用，就需要释放内存，从而使得 @code{item} 无效化。

解决方法是，当你知道了问题的根源，就容易了：临时增加引用计数。正确版本的函数代码如下：

@example
void
no_bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);

    Py_INCREF(item);
    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0);
    Py_DECREF(item);
@}
@end example

这是个真实的故事。一个旧版本的Python包含了这个bug的变种，而一些人花费了大量时间在C调试器上去寻找为什么 @ref{a0d,,__del__()} 方法会失败。

这个问题的第二种情况是借用的引用涉及线程的变种。通常，Python解释器里多个线程无法进入对方的路径，因为有个全局锁保护着Python整个对象空间。但可以使用宏 @ref{3d7d,,Py_BEGIN_ALLOW_THREADS} 来临时释放这个锁，重新获取锁用 @ref{3df,,Py_END_ALLOW_THREADS} 。这通常围绕在阻塞I/O调用外，使得其他线程可以在等待I/O期间使用处理器。显然，如下函数会跟之前那个有一样的问题：

@example
void
bug(PyObject *list)
@{
    PyObject *item = PyList_GetItem(list, 0);
    Py_BEGIN_ALLOW_THREADS
    ...some blocking I/O call...
    Py_END_ALLOW_THREADS
    PyObject_Print(item, stdout, 0); /* BUG! */
@}
@end example

@node NULL指针,,危险的薄冰,引用计数
@anchor{extending/extending null-pointers}@anchor{3d7e}@anchor{extending/extending nullpointers}@anchor{3d7f}
@subsubsection NULL指针


通常，接受对象引用作为参数的函数不希望你传给它们 @code{NULL} 指针，并且当你这样做时将会转储核心（或在以后导致核心转储）。 返回对象引用的函数通常只在要指明发生了异常时才返回 @code{NULL}。 不检测 @code{NULL} 参数的原因在于这些函数经常要将它们所接收的对象传给其他函数 --- 如果每个函数都检测 @code{NULL}，将会导致大量的冗余检测而使代码运行得更缓慢。

更好的做法是仅在“源头”上检测 @code{NULL}，即在接收到一个可能为 @code{NULL} 的指针，例如来自 @code{malloc()} 或是一个可能引发异常的函数的时候。

@ref{396,,Py_INCREF()} 和 @ref{397,,Py_DECREF()} 等宏不会检测 @code{NULL} 指针 --- 但是，它们的变种 @ref{398,,Py_XINCREF()} 和 @ref{399,,Py_XDECREF()} 则会检测。

用于检测特定对象类型的宏 (@code{Pytype_Check()}) 不会检测 @code{NULL} 指针 --- 同样地，有大量代码会连续调用这些宏来测试一个对象是否为几种不同预期类型之一，这将会生成冗余的测试。 不存在带有 @code{NULL} 检测的变体。

C 函数调用机制会保证传给 C 函数的参数列表 (本示例中为 @code{args}) 绝不会为 @code{NULL} --- 实际上它会保证其总是为一个元组 @footnote{@w{(4)} 
当你使用 "旧式" 风格调用约定时，这些保证不成立，尽管这依旧存在于很多旧代码中。
}。

任何时候将 @code{NULL} 指针“泄露”给 Python 用户都会是个严重的错误。

@c Frank Stajano:
@c A pedagogically buggy example, along the lines of the previous listing, would
@c be helpful here -- showing in more concrete terms what sort of actions could
@c cause the problem. I can't very well imagine it from the description.

@node 在C++中编写扩展,给扩展模块提供C API,引用计数,使用 C 或 C++ 扩展 Python
@anchor{extending/extending cplusplus}@anchor{3d80}@anchor{extending/extending writing-extensions-in-c}@anchor{3d81}
@subsubsection 在C++中编写扩展


还可以在C++中编写扩展模块，只是有些限制。如果主程序(Python解释器)是使用C编译器来编译和链接的，全局或静态对象的构造器就不能使用。而如果是C++编译器来链接的就没有这个问题。函数会被Python解释器调用(通常就是模块初始化函数)必须声明为 @code{extern "C"} 。而是否在 @code{extern "C" @{...@}} 里包含Python头文件则不是那么重要，因为如果定义了符号 @code{__cplusplus} 则已经是这么声明的了(所有现代C++编译器都会定义这个符号)。

@node 给扩展模块提供C API,,在C++中编写扩展,使用 C 或 C++ 扩展 Python
@anchor{extending/extending providing-a-c-api-for-an-extension-module}@anchor{3d82}@anchor{extending/extending using-capsules}@anchor{dbf}
@subsubsection 给扩展模块提供C API


很多扩展模块提供了新的函数和类型供Python使用，但有时扩展模块里的代码也可以被其他扩展模块使用。例如，一个扩展模块可以实现一个类型 "collection" 看起来是没有顺序的。就像是Python列表类型，拥有C API允许扩展模块来创建和维护列表，这个新的集合类型可以有一堆C函数用于给其他扩展模块直接使用。

开始看起来很简单：只需要编写函数(无需声明为 @code{static} )，提供恰当的头文件，以及C API的文档。实际上在所有扩展模块都是静态链接到Python解释器时也是可以正常工作的。当模块以共享库链接时，一个模块中的符号定义对另一个模块不可见。可见的细节依赖于操作系统，一些系统的Python解释器使用全局命名空间(例如Windows)，有些则在链接时需要一个严格的已导入符号列表(一个例子是AIX)，或者提供可选的不同策略(如Unix系列)。即便是符号是全局可见的，你要调用的模块也可能尚未加载。

可移植性需要不能对符号可见性做任何假设。这意味着扩展模块里的所有符号都应该声明为 @code{static} ，除了模块的初始化函数，来避免与其他扩展模块的命名冲突(在段落 @ref{3d5e,,模块方法表和初始化函数} 中讨论) 。这意味着符号应该 @emph{必须} 通过其他导出方式来供其他扩展模块访问。

Python提供了一个特别的机制来传递C级别信息(指针)，从一个扩展模块到另一个：Capsules。一个Capsule是一个Python数据类型，会保存指针( @code{void *} )。Capsule只能通过其C API来创建和访问，但可以像其他Python对象一样的传递。通常，我们可以指定一个扩展模块命名空间的名字。其他扩展模块可以导入这个模块，获取这个名字的值，然后从Capsule获取指针。

Capsule可以用多种方式导出C API给扩展模块。每个函数可以用自己的Capsule，或者所有C API指针可以存储在一个数组里，数组地址再发布给Capsule。存储和获取指针也可以用多种方式，供客户端模块使用。

无论你选择哪个方法，正确地为你的 Capsule 命名都很重要。 函数 @ref{3d83,,PyCapsule_New()} 接受一个名称形参 (@code{const char *})；允许你传入一个 @code{NULL} 作为名称，但我们强烈建议你指定一个名称。 正确地命名的 Capsule 提供了一定程序的运行时类型安全；没有可行的方式能区分两个未命名的 Capsule。

通常来说，Capsule用于暴露C API，其名字应该遵循如下规范：

@example
modulename.attributename
@end example

便利函数 @ref{3d84,,PyCapsule_Import()} 可以方便的载入通过Capsule提供的C API，仅在Capsule的名字匹配时。这个行为为C API用户提供了高度的确定性来载入正确的C API。

如下例子展示了将大部分负担交由导出模块作者的方法，适用于常用的库模块。其会存储所有C API指针(例子里只有一个)在 @code{void} 指针的数组里，并使其值变为Capsule。对应的模块头文件提供了宏来管理导入模块和获取C API指针；客户端模块只需要在访问C API前调用这个宏即可。

导出的模块修改自 @code{spam} 模块，来自 @ref{3d51,,一个简单的例子} 段落。函数 @code{spam.system()} 不会直接调用C库函数 @code{system()} ，但一个函数 @code{PySpam_System()} 会负责调用，当然现实中会更复杂些(例如添加 "spam" 到每个命令)。函数 @code{PySpam_System()} 也会导出给其他扩展模块。

函数 @code{PySpam_System()} 是个纯C函数，声明 @code{static} 就像其他地方那样:

@example
static int
PySpam_System(const char *command)
@{
    return system(command);
@}
@end example

函数 @code{spam_system()} 按照如下方式修改:

@example
static PyObject *
spam_system(PyObject *self, PyObject *args)
@{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = PySpam_System(command);
    return PyLong_FromLong(sts);
@}
@end example

在模块开头，在此行后:

@example
#include <Python.h>
@end example

添加另外两行:

@example
#define SPAM_MODULE
#include "spammodule.h"
@end example

@code{#define} 用于告知头文件需要包含给导出的模块，而不是客户端模块。最终，模块的初始化函数必须负责初始化C API指针数组:

@example
PyMODINIT_FUNC
PyInit_spam(void)
@{
    PyObject *m;
    static void *PySpam_API[PySpam_API_pointers];
    PyObject *c_api_object;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    /* Initialize the C API pointer array */
    PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;

    /* Create a Capsule containing the API pointer array's address */
    c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);

    if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) @{
        Py_XDECREF(c_api_object);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

注意 @code{PySpam_API} 声明为 @code{static} ；此外指针数组会在 @code{PyInit_spam()} 结束后消失!

头文件 @code{spammodule.h} 里的一堆工作，看起来如下所示:

@example
#ifndef Py_SPAMMODULE_H
#define Py_SPAMMODULE_H
#ifdef __cplusplus
extern "C" @{
#endif

/* Header file for spammodule */

/* C API functions */
#define PySpam_System_NUM 0
#define PySpam_System_RETURN int
#define PySpam_System_PROTO (const char *command)

/* Total number of C API pointers */
#define PySpam_API_pointers 1


#ifdef SPAM_MODULE
/* This section is used when compiling spammodule.c */

static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

#else
/* This section is used in modules that use spammodule's API */

static void **PySpam_API;

#define PySpam_System \
 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

/* Return -1 on error, 0 on success.
 * PyCapsule_Import will set an exception if there's an error.
 */
static int
import_spam(void)
@{
    PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
    return (PySpam_API != NULL) ? 0 : -1;
@}

#endif

#ifdef __cplusplus
@}
#endif

#endif /* !defined(Py_SPAMMODULE_H) */
@end example

客户端模块必须在其初始化函数里按顺序调用函数 @code{import_spam()} (或其他宏)才能访问函数 @code{PySpam_System()} 。

@example
PyMODINIT_FUNC
PyInit_client(void)
@{
    PyObject *m;

    m = PyModule_Create(&clientmodule);
    if (m == NULL)
        return NULL;
    if (import_spam() < 0)
        return NULL;
    /* additional initialization can happen here */
    return m;
@}
@end example

这种方法的主要缺点是，文件 @code{spammodule.h} 过于复杂。当然，对每个要导出的函数，基本结构是相似的，所以只需要学习一次。

最后需要提醒的是Capsule提供了额外的功能，用于存储在Capsule里的指针的内存分配和释放。细节参考 Python/C API参考手册的章节 @ref{3d85,,Capsule 对象} 和Capsule的实现(在Python源码发行包的 @code{Include/pycapsule.h} 和 @code{Objects/pycapsule.c} )。

@node 自定义扩展类型：教程,定义扩展类型：已分类主题,使用 C 或 C++ 扩展 Python,不使用第三方工具创建扩展
@anchor{extending/newtypes_tutorial doc}@anchor{f7c}@anchor{extending/newtypes_tutorial defining-extension-types-tutorial}@anchor{3d86}@anchor{extending/newtypes_tutorial defining-new-types}@anchor{3d87}
@subsection 自定义扩展类型：教程


Python 允许编写 C 扩展模块定义可以从 Python 代码中操纵的新类型，这很像内置的 @ref{206,,str} 和 @ref{1f9,,list} 类型。所有扩展类型的代码都遵循一个模式，但是在您开始之前，您需要了解一些细节。这份文件是对这个主题介绍。

@menu
* 基础:: 
* Adding data and methods to the Basic example:: 
* Providing finer control over data attributes:: 
* Supporting cyclic garbage collection:: 
* Subclassing other types:: 

@end menu

@node 基础,Adding data and methods to the Basic example,,自定义扩展类型：教程
@anchor{extending/newtypes_tutorial dnt-basics}@anchor{3d88}@anchor{extending/newtypes_tutorial the-basics}@anchor{3d89}
@subsubsection 基础


@ref{1598,,CPython} 运行时将所有 Python 对象都视为类型 @ref{5bd,,PyObject*} 的变量，即所有 Python 对象的"基础类型"。 @ref{5bd,,PyObject} 结构体本身包含了对象的 @ref{3d8a,,reference count} 和对象的"类型对象"。 类型对象确定解释器需要调用哪些 (C) 函数，例如一个属性查询一个对象，一个方法调用，或者与另一个对象相乘。 这些 C 函数被称为“类型方法”。

所以，如果你想要定义新的扩展类型，需要创建新的类型对象。

这类事情只能用例子解释，这里用一个最小化但完整的的模块，定义了新的类型叫做 @code{Custom} 在C扩展模块 @code{custom} 里。

@cartouche
@quotation 注解 
这里展示的方法是定义 @emph{static} 扩展类型的传统方法。可以适合大部分用途。C API也可以定义在堆上分配的扩展类型，使用 @ref{23b,,PyType_FromSpec()} 函数，但不在本入门里讨论。
@end quotation
@end cartouche

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct @{
    PyObject_HEAD
    /* Type-specific fields go here. */
@} CustomObject;

static PyTypeObject CustomType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
@};

static PyModuleDef custommodule = @{
    PyModuleDef_HEAD_INIT,
    .m_name = "custom",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
@};

PyMODINIT_FUNC
PyInit_custom(void)
@{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) @{
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

这部分很容易理解，这是为了跟上一章能对接上。这个文件定义了三件事：


@enumerate 

@item 
@code{Custom} 类的对象 @strong{object} 包含了： @code{CustomObject} 结构，这会为每个 @code{Custom} 实例分配一次。

@item 
@code{Custom} @strong{type} 的行为：这是 @code{CustomType} 结构体，其定义了一堆标识和函数指针，会指向解释器里请求的操作。

@item 
初始化 @code{custom} 模块： @code{PyInit_custom} 函数和对应的 @code{custommodule} 结构体。
@end enumerate

结构的第一块是

@example
typedef struct @{
    PyObject_HEAD
@} CustomObject;
@end example

This is what a Custom object will contain.  @code{PyObject_HEAD} is mandatory
at the start of each object struct and defines a field called @code{ob_base}
of type @ref{5bd,,PyObject}, containing a pointer to a type object and a
reference count (these can be accessed using the macros @ref{3d8b,,Py_TYPE}
and @ref{3d8c,,Py_REFCNT} respectively).  The reason for the macro is to
abstract away the layout and to enable additional fields in debug builds.

@cartouche
@quotation 注解 
注意在宏 @ref{d42,,PyObject_HEAD} 后没有分号。意外添加分号会导致编译器提示出错。
@end quotation
@end cartouche

当然，对象除了在 @code{PyObject_HEAD} 存储数据外，还有额外数据；例如，如下定义了标准的Python浮点数:

@example
typedef struct @{
    PyObject_HEAD
    double ob_fval;
@} PyFloatObject;
@end example

第二个位是类型对象的定义:

@example
static PyTypeObject CustomType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
@};
@end example

@cartouche
@quotation 注解 
推荐使用如上C99风格的初始化，以避免列出所有的 @ref{3fe,,PyTypeObject} 字段，其中很多是你不需要关心的，这样也可以避免关注字段的定义顺序。
@end quotation
@end cartouche

在 @code{object.h} 中实际定义的 @ref{3fe,,PyTypeObject} 具有比如上定义更多的 @ref{272,,字段}。 剩余的字段会由 C 编译器用零来填充，通常的做法是不显式地指定它们，除非你确实需要它们。

我们先挑选一部分，每次一个字段:

@example
PyVarObject_HEAD_INIT(NULL, 0)
@end example

这一行是强制的样板，用以初始化如上提到的 @code{ob_base} 字段:

@example
.tp_name = "custom.Custom",
@end example

我们的类型的名称。 这将出现在我们的对象的默认文本表示形式和某些错误消息中，例如:

@example
>>> "" + custom.Custom()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "custom.Custom") to str
@end example

Note that the name is a dotted name that includes both the module name and the
name of the type within the module. The module in this case is @code{custom} and
the type is @code{Custom}, so we set the type name to @code{custom.Custom}.
Using the real dotted import path is important to make your type compatible
with the @ref{d9,,pydoc} and @ref{ca,,pickle} modules.

@example
.tp_basicsize = sizeof(CustomObject),
.tp_itemsize = 0,
@end example

This is so that Python knows how much memory to allocate when creating
new @code{Custom} instances.  @ref{3d8d,,tp_itemsize} is
only used for variable-sized objects and should otherwise be zero.

@cartouche
@quotation 注解 
If you want your type to be subclassable from Python, and your type has the same
@ref{26b,,tp_basicsize} as its base type, you may have problems with multiple
inheritance.  A Python subclass of your type will have to list your type first
in its @ref{ed3,,__bases__}, or else it will not be able to call your type's
@ref{97d,,__new__()} method without getting an error.  You can avoid this problem by
ensuring that your type has a larger value for @ref{26b,,tp_basicsize} than its
base type does.  Most of the time, this will be true anyway, because either your
base type will be @ref{3da,,object}, or else you will be adding data members to
your base type, and therefore increasing its size.
@end quotation
@end cartouche

我们将类旗标设为 @ref{3d8e,,Py_TPFLAGS_DEFAULT}。

@example
.tp_flags = Py_TPFLAGS_DEFAULT,
@end example

All types should include this constant in their flags.  It enables all of the
members defined until at least Python 3.3.  If you need further members,
you will need to OR the corresponding flags.

We provide a doc string for the type in @ref{3d8f,,tp_doc}.

@example
.tp_doc = PyDoc_STR("Custom objects"),
@end example

To enable object creation, we have to provide a @ref{3d90,,tp_new}
handler.  This is the equivalent of the Python method @ref{97d,,__new__()}, but
has to be specified explicitly.  In this case, we can just use the default
implementation provided by the API function @ref{3d91,,PyType_GenericNew()}.

@example
.tp_new = PyType_GenericNew,
@end example

Everything else in the file should be familiar, except for some code in
@code{PyInit_custom()}:

@example
if (PyType_Ready(&CustomType) < 0)
    return;
@end example

This initializes the @code{Custom} type, filling in a number of members
to the appropriate default values, including @code{ob_type} that we initially
set to @code{NULL}.

@example
Py_INCREF(&CustomType);
if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) @{
    Py_DECREF(&CustomType);
    Py_DECREF(m);
    return NULL;
@}
@end example

This adds the type to the module dictionary.  This allows us to create
@code{Custom} instances by calling the @code{Custom} class:

@example
>>> import custom
>>> mycustom = custom.Custom()
@end example

That's it!  All that remains is to build it; put the above code in a file called
@code{custom.c} and:

@example
from distutils.core import setup, Extension
setup(name="custom", version="1.0",
      ext_modules=[Extension("custom", ["custom.c"])])
@end example

in a file called @code{setup.py}; then typing

@example
$ python setup.py build
@end example

at a shell should produce a file @code{custom.so} in a subdirectory; move to
that directory and fire up Python --- you should be able to @code{import custom} and
play around with Custom objects.

这并不难，对吗？

Of course, the current Custom type is pretty uninteresting. It has no data and
doesn't do anything. It can't even be subclassed.

@cartouche
@quotation 注解 
While this documentation showcases the standard @ref{38,,distutils} module
for building C extensions, it is recommended in real-world use cases to
use the newer and better-maintained @code{setuptools} library.  Documentation
on how to do this is out of scope for this document and can be found in
the Python Packaging User's Guide@footnote{https://packaging.python.org/tutorials/distributing-packages/}.
@end quotation
@end cartouche

@node Adding data and methods to the Basic example,Providing finer control over data attributes,基础,自定义扩展类型：教程
@anchor{extending/newtypes_tutorial adding-data-and-methods-to-the-basic-example}@anchor{3d92}
@subsubsection Adding data and methods to the Basic example


Let's extend the basic example to add some data and methods.  Let's also make
the type usable as a base class. We'll create a new module, @code{custom2} that
adds these capabilities:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static void
Custom_dealloc(CustomObject *self)
@{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
@{
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_XDECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_XDECREF(tmp);
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"@},
    @{"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"@},
    @{"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
@{
    if (self->first == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "first");
        return NULL;
    @}
    if (self->last == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "last");
        return NULL;
    @}
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}

static PyMethodDef Custom_methods[] = @{
    @{"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom2.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
@};

static PyModuleDef custommodule = @{
    PyModuleDef_HEAD_INIT,
    .m_name = "custom2",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
@};

PyMODINIT_FUNC
PyInit_custom2(void)
@{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) @{
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

This version of the module has a number of changes.

We've added an extra include:

@example
#include <structmember.h>
@end example

This include provides declarations that we use to handle attributes, as
described a bit later.

The  @code{Custom} type now has three data attributes in its C struct,
@emph{first}, @emph{last}, and @emph{number}.  The @emph{first} and @emph{last} variables are Python
strings containing first and last names.  The @emph{number} attribute is a C integer.

The object structure is updated accordingly:

@example
typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;
@end example

Because we now have data to manage, we have to be more careful about object
allocation and deallocation.  At a minimum, we need a deallocation method:

@example
static void
Custom_dealloc(CustomObject *self)
@{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}
@end example

which is assigned to the @ref{3d93,,tp_dealloc} member:

@example
.tp_dealloc = (destructor) Custom_dealloc,
@end example

This method first clears the reference counts of the two Python attributes.
@ref{399,,Py_XDECREF()} correctly handles the case where its argument is
@code{NULL} (which might happen here if @code{tp_new} failed midway).  It then
calls the @ref{3d94,,tp_free} member of the object's type
(computed by @code{Py_TYPE(self)}) to free the object's memory.  Note that
the object's type might not be @code{CustomType}, because the object may
be an instance of a subclass.

@cartouche
@quotation 注解 
The explicit cast to @code{destructor} above is needed because we defined
@code{Custom_dealloc} to take a @code{CustomObject *} argument, but the @code{tp_dealloc}
function pointer expects to receive a @code{PyObject *} argument.  Otherwise,
the compiler will emit a warning.  This is object-oriented polymorphism,
in C!
@end quotation
@end cartouche

We want to make sure that the first and last names are initialized to empty
strings, so we provide a @code{tp_new} implementation:

@example
static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}
@end example

and install it in the @ref{3d90,,tp_new} member:

@example
.tp_new = Custom_new,
@end example

The @code{tp_new} handler is responsible for creating (as opposed to initializing)
objects of the type.  It is exposed in Python as the @ref{97d,,__new__()} method.
It is not required to define a @code{tp_new} member, and indeed many extension
types will simply reuse @ref{3d91,,PyType_GenericNew()} as done in the first
version of the @code{Custom} type above.  In this case, we use the @code{tp_new}
handler to initialize the @code{first} and @code{last} attributes to non-@code{NULL}
default values.

@code{tp_new} is passed the type being instantiated (not necessarily @code{CustomType},
if a subclass is instantiated) and any arguments passed when the type was
called, and is expected to return the instance created.  @code{tp_new} handlers
always accept positional and keyword arguments, but they often ignore the
arguments, leaving the argument handling to initializer (a.k.a. @code{tp_init}
in C or @code{__init__} in Python) methods.

@cartouche
@quotation 注解 
@code{tp_new} shouldn't call @code{tp_init} explicitly, as the interpreter
will do it itself.
@end quotation
@end cartouche

The @code{tp_new} implementation calls the @ref{3d95,,tp_alloc}
slot to allocate memory:

@example
self = (CustomObject *) type->tp_alloc(type, 0);
@end example

Since memory allocation may fail, we must check the @ref{3d95,,tp_alloc}
result against @code{NULL} before proceeding.

@cartouche
@quotation 注解 
We didn't fill the @ref{3d95,,tp_alloc} slot ourselves. Rather
@ref{3d96,,PyType_Ready()} fills it for us by inheriting it from our base class,
which is @ref{3da,,object} by default.  Most types use the default allocation
strategy.
@end quotation
@end cartouche

@cartouche
@quotation 注解 
If you are creating a co-operative @ref{3d90,,tp_new} (one
that calls a base type's @ref{3d90,,tp_new} or @ref{97d,,__new__()}),
you must @emph{not} try to determine what method to call using method resolution
order at runtime.  Always statically determine what type you are going to
call, and call its @ref{3d90,,tp_new} directly, or via
@code{type->tp_base->tp_new}.  If you do not do this, Python subclasses of your
type that also inherit from other Python-defined classes may not work correctly.
(Specifically, you may not be able to create instances of such subclasses
without getting a @ref{1ff,,TypeError}.)
@end quotation
@end cartouche

We also define an initialization function which accepts arguments to provide
initial values for our instance:

@example
static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
@{
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_XDECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_XDECREF(tmp);
    @}
    return 0;
@}
@end example

by filling the @ref{3d97,,tp_init} slot.

@example
.tp_init = (initproc) Custom_init,
@end example

The @ref{3d97,,tp_init} slot is exposed in Python as the
@ref{e2b,,__init__()} method.  It is used to initialize an object after it's
created.  Initializers always accept positional and keyword arguments,
and they should return either @code{0} on success or @code{-1} on error.

Unlike the @code{tp_new} handler, there is no guarantee that @code{tp_init}
is called at all (for example, the @ref{ca,,pickle} module by default
doesn't call @ref{e2b,,__init__()} on unpickled instances).  It can also be
called multiple times.  Anyone can call the @ref{e2b,,__init__()} method on
our objects.  For this reason, we have to be extra careful when assigning
the new attribute values.  We might be tempted, for example to assign the
@code{first} member like this:

@example
if (first) @{
    Py_XDECREF(self->first);
    Py_INCREF(first);
    self->first = first;
@}
@end example

But this would be risky.  Our type doesn't restrict the type of the
@code{first} member, so it could be any kind of object.  It could have a
destructor that causes code to be executed that tries to access the
@code{first} member; or that destructor could release the
@ref{20f,,Global interpreter Lock} and let arbitrary code run in other
threads that accesses and modifies our object.

To be paranoid and protect ourselves against this possibility, we almost
always reassign members before decrementing their reference counts.  When
don't we have to do this?


@itemize *

@item 
when we absolutely know that the reference count is greater than 1;

@item 
when we know that deallocation of the object @footnote{@w{(1)} 
This is true when we know that the object is a basic type, like a string or a
float.
} will neither release
the @ref{20f,,GIL} nor cause any calls back into our type's code;

@item 
when decrementing a reference count in a @ref{3d93,,tp_dealloc}
handler on a type which doesn't support cyclic garbage collection @footnote{@w{(2)} 
We relied on this in the @ref{3d93,,tp_dealloc} handler
in this example, because our type doesn't support garbage collection.
}.
@end itemize

We want to expose our instance variables as attributes. There are a
number of ways to do that. The simplest way is to define member definitions:

@example
static PyMemberDef Custom_members[] = @{
    @{"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"@},
    @{"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"@},
    @{"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};
@end example

and put the definitions in the @ref{3d98,,tp_members} slot:

@example
.tp_members = Custom_members,
@end example

Each member definition has a member name, type, offset, access flags and
documentation string.  See the @ref{3d99,,泛型属性管理} section
below for details.

A disadvantage of this approach is that it doesn't provide a way to restrict the
types of objects that can be assigned to the Python attributes.  We expect the
first and last names to be strings, but any Python objects can be assigned.
Further, the attributes can be deleted, setting the C pointers to @code{NULL}.  Even
though we can make sure the members are initialized to non-@code{NULL} values, the
members can be set to @code{NULL} if the attributes are deleted.

We define a single method, @code{Custom.name()}, that outputs the objects name as the
concatenation of the first and last names.

@example
static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
@{
    if (self->first == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "first");
        return NULL;
    @}
    if (self->last == NULL) @{
        PyErr_SetString(PyExc_AttributeError, "last");
        return NULL;
    @}
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}
@end example

The method is implemented as a C function that takes a @code{Custom} (or
@code{Custom} subclass) instance as the first argument.  Methods always take an
instance as the first argument. Methods often take positional and keyword
arguments as well, but in this case we don't take any and don't need to accept
a positional argument tuple or keyword argument dictionary. This method is
equivalent to the Python method:

@example
def name(self):
    return "%s %s" % (self.first, self.last)
@end example

Note that we have to check for the possibility that our @code{first} and
@code{last} members are @code{NULL}.  This is because they can be deleted, in which
case they are set to @code{NULL}.  It would be better to prevent deletion of these
attributes and to restrict the attribute values to be strings.  We'll see how to
do that in the next section.

Now that we've defined the method, we need to create an array of method
definitions:

@example
static PyMethodDef Custom_methods[] = @{
    @{"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};
@end example

(note that we used the @ref{ee2,,METH_NOARGS} flag to indicate that the method
is expecting no arguments other than @emph{self})

and assign it to the @ref{3d9a,,tp_methods} slot:

@example
.tp_methods = Custom_methods,
@end example

Finally, we'll make our type usable as a base class for subclassing.  We've
written our methods carefully so far so that they don't make any assumptions
about the type of the object being created or used, so all we need to do is
to add the @ref{3d9b,,Py_TPFLAGS_BASETYPE} to our class flag definition:

@example
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
@end example

We rename @code{PyInit_custom()} to @code{PyInit_custom2()}, update the
module name in the @ref{259,,PyModuleDef} struct, and update the full class
name in the @ref{3fe,,PyTypeObject} struct.

Finally, we update our @code{setup.py} file to build the new module:

@example
from distutils.core import setup, Extension
setup(name="custom", version="1.0",
      ext_modules=[
         Extension("custom", ["custom.c"]),
         Extension("custom2", ["custom2.c"]),
         ])
@end example

@node Providing finer control over data attributes,Supporting cyclic garbage collection,Adding data and methods to the Basic example,自定义扩展类型：教程
@anchor{extending/newtypes_tutorial providing-finer-control-over-data-attributes}@anchor{3d9c}
@subsubsection Providing finer control over data attributes


In this section, we'll provide finer control over how the @code{first} and
@code{last} attributes are set in the @code{Custom} example. In the previous
version of our module, the instance variables @code{first} and @code{last}
could be set to non-string values or even deleted. We want to make sure that
these attributes always contain strings.

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static void
Custom_dealloc(CustomObject *self)
@{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
@{
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
@{
    Py_INCREF(self->first);
    return self->first;
@}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
@{
    PyObject *tmp;
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    @}
    tmp = self->first;
    Py_INCREF(value);
    self->first = value;
    Py_DECREF(tmp);
    return 0;
@}

static PyObject *
Custom_getlast(CustomObject *self, void *closure)
@{
    Py_INCREF(self->last);
    return self->last;
@}

static int
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
@{
    PyObject *tmp;
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The last attribute value must be a string");
        return -1;
    @}
    tmp = self->last;
    Py_INCREF(value);
    self->last = value;
    Py_DECREF(tmp);
    return 0;
@}

static PyGetSetDef Custom_getsetters[] = @{
    @{"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL@},
    @{"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
@{
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}

static PyMethodDef Custom_methods[] = @{
    @{"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom3.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
@};

static PyModuleDef custommodule = @{
    PyModuleDef_HEAD_INIT,
    .m_name = "custom3",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
@};

PyMODINIT_FUNC
PyInit_custom3(void)
@{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) @{
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

To provide greater control, over the @code{first} and @code{last} attributes,
we'll use custom getter and setter functions.  Here are the functions for
getting and setting the @code{first} attribute:

@example
static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
@{
    Py_INCREF(self->first);
    return self->first;
@}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
@{
    PyObject *tmp;
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    @}
    tmp = self->first;
    Py_INCREF(value);
    self->first = value;
    Py_DECREF(tmp);
    return 0;
@}
@end example

The getter function is passed a @code{Custom} object and a "closure", which is
a void pointer.  In this case, the closure is ignored.  (The closure supports an
advanced usage in which definition data is passed to the getter and setter. This
could, for example, be used to allow a single set of getter and setter functions
that decide the attribute to get or set based on data in the closure.)

The setter function is passed the @code{Custom} object, the new value, and the
closure.  The new value may be @code{NULL}, in which case the attribute is being
deleted.  In our setter, we raise an error if the attribute is deleted or if its
new value is not a string.

We create an array of @ref{533,,PyGetSetDef} structures:

@example
static PyGetSetDef Custom_getsetters[] = @{
    @{"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL@},
    @{"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};
@end example

and register it in the @ref{3d9d,,tp_getset} slot:

@example
.tp_getset = Custom_getsetters,
@end example

The last item in a @ref{533,,PyGetSetDef} structure is the "closure" mentioned
above.  In this case, we aren't using a closure, so we just pass @code{NULL}.

We also remove the member definitions for these attributes:

@example
static PyMemberDef Custom_members[] = @{
    @{"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};
@end example

We also need to update the @ref{3d97,,tp_init} handler to only
allow strings @footnote{@w{(3)} 
We now know that the first and last members are strings, so perhaps we
could be less careful about decrementing their reference counts, however,
we accept instances of string subclasses.  Even though deallocating normal
strings won't call back into our objects, we can't guarantee that deallocating
an instance of a string subclass won't call back into our objects.
} to be passed:

@example
static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
@{
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    @}
    return 0;
@}
@end example

With these changes, we can assure that the @code{first} and @code{last} members are
never @code{NULL} so we can remove checks for @code{NULL} values in almost all cases.
This means that most of the @ref{399,,Py_XDECREF()} calls can be converted to
@ref{397,,Py_DECREF()} calls.  The only place we can't change these calls is in
the @code{tp_dealloc} implementation, where there is the possibility that the
initialization of these members failed in @code{tp_new}.

We also rename the module initialization function and module name in the
initialization function, as we did before, and we add an extra definition to the
@code{setup.py} file.

@node Supporting cyclic garbage collection,Subclassing other types,Providing finer control over data attributes,自定义扩展类型：教程
@anchor{extending/newtypes_tutorial supporting-cyclic-garbage-collection}@anchor{3d9e}
@subsubsection Supporting cyclic garbage collection


Python has a @ref{1013,,cyclic garbage collector (GC)} that
can identify unneeded objects even when their reference counts are not zero.
This can happen when objects are involved in cycles.  For example, consider:

@example
>>> l = []
>>> l.append(l)
>>> del l
@end example

In this example, we create a list that contains itself. When we delete it, it
still has a reference from itself. Its reference count doesn't drop to zero.
Fortunately, Python's cyclic garbage collector will eventually figure out that
the list is garbage and free it.

In the second version of the @code{Custom} example, we allowed any kind of
object to be stored in the @code{first} or @code{last} attributes @footnote{@w{(4)} 
Also, even with our attributes restricted to strings instances, the user
could pass arbitrary @ref{206,,str} subclasses and therefore still create
reference cycles.
}.
Besides, in the second and third versions, we allowed subclassing
@code{Custom}, and subclasses may add arbitrary attributes.  For any of
those two reasons, @code{Custom} objects can participate in cycles:

@example
>>> import custom3
>>> class Derived(custom3.Custom): pass
...
>>> n = Derived()
>>> n.some_attribute = n
@end example

To allow a @code{Custom} instance participating in a reference cycle to
be properly detected and collected by the cyclic GC, our @code{Custom} type
needs to fill two additional slots and to enable a flag that enables these slots:

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct @{
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
@} CustomObject;

static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
@{
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
@}

static int
Custom_clear(CustomObject *self)
@{
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
@}

static void
Custom_dealloc(CustomObject *self)
@{
    PyObject_GC_UnTrack(self);
    Custom_clear(self);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) @{
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) @{
            Py_DECREF(self);
            return NULL;
        @}
        self->number = 0;
    @}
    return (PyObject *) self;
@}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
@{
    static char *kwlist[] = @{"first", "last", "number", NULL@};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) @{
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    @}
    if (last) @{
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    @}
    return 0;
@}

static PyMemberDef Custom_members[] = @{
    @{"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
@{
    Py_INCREF(self->first);
    return self->first;
@}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
@{
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    @}
    Py_INCREF(value);
    Py_CLEAR(self->first);
    self->first = value;
    return 0;
@}

static PyObject *
Custom_getlast(CustomObject *self, void *closure)
@{
    Py_INCREF(self->last);
    return self->last;
@}

static int
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
@{
    if (value == NULL) @{
        PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
        return -1;
    @}
    if (!PyUnicode_Check(value)) @{
        PyErr_SetString(PyExc_TypeError,
                        "The last attribute value must be a string");
        return -1;
    @}
    Py_INCREF(value);
    Py_CLEAR(self->last);
    self->last = value;
    return 0;
@}

static PyGetSetDef Custom_getsetters[] = @{
    @{"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL@},
    @{"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL@},
    @{NULL@}  /* Sentinel */
@};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
@{
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
@}

static PyMethodDef Custom_methods[] = @{
    @{"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    @},
    @{NULL@}  /* Sentinel */
@};

static PyTypeObject CustomType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom4.Custom",
    .tp_doc = PyDoc_STR("Custom objects"),
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_traverse = (traverseproc) Custom_traverse,
    .tp_clear = (inquiry) Custom_clear,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
@};

static PyModuleDef custommodule = @{
    PyModuleDef_HEAD_INIT,
    .m_name = "custom4",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
@};

PyMODINIT_FUNC
PyInit_custom4(void)
@{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) @{
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

First, the traversal method lets the cyclic GC know about subobjects that could
participate in cycles:

@example
static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
@{
    int vret;
    if (self->first) @{
        vret = visit(self->first, arg);
        if (vret != 0)
            return vret;
    @}
    if (self->last) @{
        vret = visit(self->last, arg);
        if (vret != 0)
            return vret;
    @}
    return 0;
@}
@end example

For each subobject that can participate in cycles, we need to call the
@code{visit()} function, which is passed to the traversal method. The
@code{visit()} function takes as arguments the subobject and the extra argument
@emph{arg} passed to the traversal method.  It returns an integer value that must be
returned if it is non-zero.

Python provides a @ref{3d9f,,Py_VISIT()} macro that automates calling visit
functions.  With @ref{3d9f,,Py_VISIT()}, we can minimize the amount of boilerplate
in @code{Custom_traverse}:

@example
static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
@{
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
@}
@end example

@cartouche
@quotation 注解 
The @ref{23c,,tp_traverse} implementation must name its
arguments exactly @emph{visit} and @emph{arg} in order to use @ref{3d9f,,Py_VISIT()}.
@end quotation
@end cartouche

Second, we need to provide a method for clearing any subobjects that can
participate in cycles:

@example
static int
Custom_clear(CustomObject *self)
@{
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
@}
@end example

Notice the use of the @ref{3da0,,Py_CLEAR()} macro.  It is the recommended and safe
way to clear data attributes of arbitrary types while decrementing
their reference counts.  If you were to call @ref{399,,Py_XDECREF()} instead
on the attribute before setting it to @code{NULL}, there is a possibility
that the attribute's destructor would call back into code that reads the
attribute again (@emph{especially} if there is a reference cycle).

@cartouche
@quotation 注解 
You could emulate @ref{3da0,,Py_CLEAR()} by writing:

@example
PyObject *tmp;
tmp = self->first;
self->first = NULL;
Py_XDECREF(tmp);
@end example

Nevertheless, it is much easier and less error-prone to always
use @ref{3da0,,Py_CLEAR()} when deleting an attribute.  Don't
try to micro-optimize at the expense of robustness!
@end quotation
@end cartouche

The deallocator @code{Custom_dealloc} may call arbitrary code when clearing
attributes.  It means the circular GC can be triggered inside the function.
Since the GC assumes reference count is not zero, we need to untrack the object
from the GC by calling @ref{f0f,,PyObject_GC_UnTrack()} before clearing members.
Here is our reimplemented deallocator using @ref{f0f,,PyObject_GC_UnTrack()}
and @code{Custom_clear}:

@example
static void
Custom_dealloc(CustomObject *self)
@{
    PyObject_GC_UnTrack(self);
    Custom_clear(self);
    Py_TYPE(self)->tp_free((PyObject *) self);
@}
@end example

Finally, we add the @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag to the class flags:

@example
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
@end example

That's pretty much it.  If we had written custom @ref{3d95,,tp_alloc} or
@ref{3d94,,tp_free} handlers, we'd need to modify them for cyclic
garbage collection.  Most extensions will use the versions automatically provided.

@node Subclassing other types,,Supporting cyclic garbage collection,自定义扩展类型：教程
@anchor{extending/newtypes_tutorial subclassing-other-types}@anchor{3da2}
@subsubsection Subclassing other types


It is possible to create new extension types that are derived from existing
types. It is easiest to inherit from the built in types, since an extension can
easily use the @ref{3fe,,PyTypeObject} it needs. It can be difficult to share
these @ref{3fe,,PyTypeObject} structures between extension modules.

In this example we will create a @code{SubList} type that inherits from the
built-in @ref{1f9,,list} type. The new type will be completely compatible with
regular lists, but will have an additional @code{increment()} method that
increases an internal counter:

@example
>>> import sublist
>>> s = sublist.SubList(range(3))
>>> s.extend(s)
>>> print(len(s))
6
>>> print(s.increment())
1
>>> print(s.increment())
2
@end example

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct @{
    PyListObject list;
    int state;
@} SubListObject;

static PyObject *
SubList_increment(SubListObject *self, PyObject *unused)
@{
    self->state++;
    return PyLong_FromLong(self->state);
@}

static PyMethodDef SubList_methods[] = @{
    @{"increment", (PyCFunction) SubList_increment, METH_NOARGS,
     PyDoc_STR("increment state counter")@},
    @{NULL@},
@};

static int
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
@{
    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
@}

static PyTypeObject SubListType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "sublist.SubList",
    .tp_doc = PyDoc_STR("SubList objects"),
    .tp_basicsize = sizeof(SubListObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_init = (initproc) SubList_init,
    .tp_methods = SubList_methods,
@};

static PyModuleDef sublistmodule = @{
    PyModuleDef_HEAD_INIT,
    .m_name = "sublist",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
@};

PyMODINIT_FUNC
PyInit_sublist(void)
@{
    PyObject *m;
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0)
        return NULL;

    m = PyModule_Create(&sublistmodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&SubListType);
    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) @{
        Py_DECREF(&SubListType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

As you can see, the source code closely resembles the @code{Custom} examples in
previous sections. We will break down the main differences between them.

@example
typedef struct @{
    PyListObject list;
    int state;
@} SubListObject;
@end example

The primary difference for derived type objects is that the base type's
object structure must be the first value.  The base type will already include
the @ref{d42,,PyObject_HEAD()} at the beginning of its structure.

When a Python object is a @code{SubList} instance, its @code{PyObject *} pointer
can be safely cast to both @code{PyListObject *} and @code{SubListObject *}:

@example
static int
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
@{
    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
@}
@end example

We see above how to call through to the @ref{e2b,,__init__} method of the base
type.

This pattern is important when writing a type with custom
@ref{3d90,,tp_new} and @ref{3d93,,tp_dealloc}
members.  The @ref{3d90,,tp_new} handler should not actually
create the memory for the object with its @ref{3d95,,tp_alloc},
but let the base class handle it by calling its own @ref{3d90,,tp_new}.

The @ref{3fe,,PyTypeObject} struct supports a @ref{3da3,,tp_base}
specifying the type's concrete base class.  Due to cross-platform compiler
issues, you can't fill that field directly with a reference to
@ref{3da4,,PyList_Type}; it should be done later in the module initialization
function:

@example
PyMODINIT_FUNC
PyInit_sublist(void)
@{
    PyObject* m;
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0)
        return NULL;

    m = PyModule_Create(&sublistmodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&SubListType);
    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) @{
        Py_DECREF(&SubListType);
        Py_DECREF(m);
        return NULL;
    @}

    return m;
@}
@end example

Before calling @ref{3d96,,PyType_Ready()}, the type structure must have the
@ref{3da3,,tp_base} slot filled in.  When we are deriving an
existing type, it is not necessary to fill out the @ref{3d95,,tp_alloc}
slot with @ref{3d91,,PyType_GenericNew()} -- the allocation function from the base
type will be inherited.

After that, calling @ref{3d96,,PyType_Ready()} and adding the type object to the
module is the same as with the basic @code{Custom} examples.

@node 定义扩展类型：已分类主题,构建C/C++扩展,自定义扩展类型：教程,不使用第三方工具创建扩展
@anchor{extending/newtypes doc}@anchor{3da5}@anchor{extending/newtypes defining-extension-types-assorted-topics}@anchor{3da6}@anchor{extending/newtypes new-types-topics}@anchor{3da7}
@subsection 定义扩展类型：已分类主题

@anchor{extending/newtypes dnt-type-methods}@anchor{3da8}
本章节目标是提供一个各种你可以实现的类型方法及其功能的简短介绍。

这是C类型 @ref{3fe,,PyTypeObject} 的定义，省略了只用于调试构建的字段:

@example
typedef struct _typeobject @{
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;

@} PyTypeObject;
@end example

这里有 @emph{很多} 方法。但是不要太担心，如果你要定义一个类型，通常只需要实现少量的方法。

正如你猜到的一样，我们正要一步一步详细介绍各种处理程序。因为有大量的历史包袱影响字段的排序，所以我们不会根据它们在结构体里定义的顺序讲解。通常非常容易找到一个包含你需要的字段的例子，然后改变值去适应你新的类型。

@example
const char *tp_name; /* For printing */
@end example

类型的名字 - 上一章提到过的，会出现在很多地方，几乎全部都是为了诊断目的。尝试选择一个好名字，对于诊断很有帮助。

@example
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
@end example

这些字段告诉运行时在创造这个类型的新对象时需要分配多少内存。Python为了可变长度的结构（想下：字符串，元组）有些内置支持，这是 @ref{3d8d,,tp_itemsize} 字段存在的原由。这部分稍后解释。

@example
const char *tp_doc;
@end example

这里你可以放置一段字符串（或者它的地址），当你想在Python脚本引用 @code{obj.__doc__} 时返回这段文档字符串。

现在我们来看一下基本类型方法 - 大多数扩展类型将实现的方法。

@menu
* 终结和内存释放:: 
* 对象展示:: 
* 属性管理:: 
* 对象比较:: 
* 抽象协议支持:: 
* 弱引用支持:: 
* 更多建议:: 

@end menu

@node 终结和内存释放,对象展示,,定义扩展类型：已分类主题
@anchor{extending/newtypes finalization-and-de-allocation}@anchor{3da9}
@subsubsection 终结和内存释放


@geindex object; deallocation
@geindex deallocation@comma{} object
@geindex object; finalization
@geindex finalization@comma{} of objects

@example
destructor tp_dealloc;
@end example

当您的类型实例的引用计数减少为零并且Python解释器想要回收它时，将调用此函数。如果你的类型有内存可供释放或执行其他清理，你可以把它放在这里。 对象本身也需要在这里释放。 以下是此函数的示例：

@example
static void
newdatatype_dealloc(newdatatypeobject *obj)
@{
    free(obj->obj_UnderlyingDatatypePtr);
    Py_TYPE(obj)->tp_free((PyObject *)obj);
@}
@end example

如果你的类型支持垃圾回收，则析构器应当在清理任何成员字段之前调用 @ref{f0f,,PyObject_GC_UnTrack()}:

@example
static void
newdatatype_dealloc(newdatatypeobject *obj)
@{
    PyObject_GC_UnTrack(obj);
    Py_CLEAR(obj->other_obj);
    ...
    Py_TYPE(obj)->tp_free((PyObject *)obj);
@}
@end example

@geindex PyErr_Fetch()
@geindex PyErr_Restore()

一个重要的释放器函数实现要求是把所有未决异常放着不动。这很重要是因为释放器会被解释器频繁的调用，当栈异常退出时(而非正常返回)，不会有任何办法保护释放器看到一个异常尚未被设置。此事释放器的任何行为都会导致额外增加的Python代码来检查异常是否被设置。这可能导致解释器的误导性错误。正确的保护方法是，在任何不安全的操作前，保存未决异常，然后在其完成后恢复。者可以通过 @ref{a54,,PyErr_Fetch()} 和 @ref{3daa,,PyErr_Restore()} 函数来实现:

@example
static void
my_dealloc(PyObject *obj)
@{
    MyObject *self = (MyObject *) obj;
    PyObject *cbresult;

    if (self->my_callback != NULL) @{
        PyObject *err_type, *err_value, *err_traceback;

        /* This saves the current exception state */
        PyErr_Fetch(&err_type, &err_value, &err_traceback);

        cbresult = PyObject_CallNoArgs(self->my_callback);
        if (cbresult == NULL)
            PyErr_WriteUnraisable(self->my_callback);
        else
            Py_DECREF(cbresult);

        /* This restores the saved exception state */
        PyErr_Restore(err_type, err_value, err_traceback);

        Py_DECREF(self->my_callback);
    @}
    Py_TYPE(obj)->tp_free((PyObject*)self);
@}
@end example

@cartouche
@quotation 注解 
你能在释放器函数中安全执行的操作是有限的。 首先，如果你的类型支持垃圾回收 (使用 @ref{23c,,tp_traverse} 和/或 @ref{3dab,,tp_clear})，对象的部分成员可以在调用 @ref{3d93,,tp_dealloc} 时被清空或终结。 其次，在 @ref{3d93,,tp_dealloc} 中，你的对象将处于不稳定状态：它的引用计数等于零。 任何对非琐碎对象或 API 的调用 (如上面的示例所做的) 最终都可能会再次调用 @ref{3d93,,tp_dealloc}，导致双重释放并发生崩溃。

从 Python 3.4 开始，推荐不要在 @ref{3d93,,tp_dealloc} 放复杂的终结代码，而是使用新的 @ref{3ff,,tp_finalize} 类型方法。


@subsubheading 参见


@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442} 解释了新的终结方案。

@end quotation
@end cartouche

@geindex string; object representation
@geindex 內置函数; repr

@node 对象展示,属性管理,终结和内存释放,定义扩展类型：已分类主题
@anchor{extending/newtypes object-presentation}@anchor{3dac}
@subsubsection 对象展示


在 Python 中，有两种方式可以生成对象的文本表示: @ref{8c3,,repr()} 函数和 @ref{206,,str()} 函数。 (@ref{97a,,print()} 函数会直接调用 @ref{206,,str()}。) 这些处理程序都是可选的。

@example
reprfunc tp_repr;
reprfunc tp_str;
@end example

@ref{3dad,,tp_repr} 处理程序应该返回一个字符串对象，其中包含调用它的实例的表示形式。 下面是一个简单的例子:

@example
static PyObject *
newdatatype_repr(newdatatypeobject * obj)
@{
    return PyUnicode_FromFormat("Repr-ified_newdatatype@{@{size:%d@}@}",
                                obj->obj_UnderlyingDatatypePtr->size);
@}
@end example

如果没有指定 @ref{3dad,,tp_repr} 处理程序，解释器将提供一个使用 @ref{3dae,,tp_name} 的表示形式以及对象的惟一标识值。

@ref{3daf,,tp_str} 处理句柄对于 @ref{206,,str()} 就如上述的 @ref{3dad,,tp_repr} 处理句柄对于 @ref{8c3,,repr()} 一样；也就是说，它会在当 Python 代码在你的对象的某个实例上调用 @ref{206,,str()} 时被调用。 它的实现与 @ref{3dad,,tp_repr} 函数非常相似，但其结果字符串是供人类查看的。 如果未指定 @ref{3daf,,tp_str}，则会使用 @ref{3dad,,tp_repr} 重句柄来代替。

下面是一个简单的例子:

@example
static PyObject *
newdatatype_str(newdatatypeobject * obj)
@{
    return PyUnicode_FromFormat("Stringified_newdatatype@{@{size:%d@}@}",
                                obj->obj_UnderlyingDatatypePtr->size);
@}
@end example

@node 属性管理,对象比较,对象展示,定义扩展类型：已分类主题
@anchor{extending/newtypes attribute-management}@anchor{3db0}
@subsubsection 属性管理


对于每个可支持属性操作的对象，相应的类型必须提供用于控制属性获取方式的函数。 需要有一个能够检索属性的函数（如果定义了任何属性）还要有另一个函数负责设置属性（如果允许设置属性）。 移除属性是一种特殊情况，在此情况下要传给处理句柄的新值为 @code{NULL}。

Python 支持两对属性处理句柄；一个支持属性操作的类型只需要实现其中一对的函数。 两者的差别在于一对接受 @code{char*} 作为属性名称，而另一对则接受 @ref{5bd,,PyObject*}。 每种类型都可以选择使用对于实现的便利性来说更有意义的那一对。

@example
getattrfunc  tp_getattr;        /* char * version */
setattrfunc  tp_setattr;
/* ... */
getattrofunc tp_getattro;       /* PyObject * version */
setattrofunc tp_setattro;
@end example

如果访问一个对象的属性总是属于简单操作（这将在下文进行解释），则有一些泛用实现可被用来提供 @ref{5bd,,PyObject*} 版本的属性管理函数。 从 Python 2.2 开始对于类型专属的属性处理句柄的实际需要几乎已完全消失，尽管还存在着许多尚未更新为使用某种新的可选泛用机制的例子。

@menu
* 泛型属性管理:: 
* 类型专属的属性管理:: 

@end menu

@node 泛型属性管理,类型专属的属性管理,,属性管理
@anchor{extending/newtypes generic-attribute-management}@anchor{3d99}@anchor{extending/newtypes id1}@anchor{3db1}
@subsubsection 泛型属性管理


大多数扩展类型只使用 @strong{简单} 属性，那么，是什么让属性变得“简单”呢？只需要满足下面几个条件：


@enumerate 

@item 
当调用 @ref{3d96,,PyType_Ready()} 时，必须知道属性的名称。

@item 
不需要特殊的处理来记录属性是否被查找或设置，也不需要根据值采取操作。
@end enumerate

请注意，此列表不对属性的值、值的计算时间或相关数据的存储方式施加任何限制。

当 @ref{3d96,,PyType_Ready()} 被调用时，它会使用由类型对象所引用的三个表来创建要放置到类型对象的字典中的 @ref{15a8,,descriptor}。 每个描述器控制对实例对象的一个属性的访问。 每个表都是可选的；如果三个表全都为 @code{NULL}，则该类型的实例将只有从它们的基础类型继承来的属性，并且还应当让 @ref{3db2,,tp_getattro} 和 @ref{3db3,,tp_setattro} 字段保持为 @code{NULL}，以允许由基础类型处理这些属性。

表被声明为object::类型的三个字段:

@example
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
@end example

如果 @ref{3d9a,,tp_methods} 不为 @code{NULL}，则它必须指向一个由 @ref{ee5,,PyMethodDef} 结构体组成的数组。 表中的每个条目都是该结构体的一个实例:

@example
typedef struct PyMethodDef @{
    const char  *ml_name;       /* method name */
    PyCFunction  ml_meth;       /* implementation function */
    int          ml_flags;      /* flags */
    const char  *ml_doc;        /* docstring */
@} PyMethodDef;
@end example

应当为该类型所提供的每个方法都定义一个条目；从基础类型继承来的方法不需要条目。 还需要在末尾加一个额外的条目；它是一个标记数组结束的哨兵条目。 该哨兵条目的 @code{ml_name} 字段必须为 @code{NULL}。

第二个表被用来定义要直接映射到实例中的数据的属性。 各种原始 C 类型均受到支持，并且访问方式可以为只读或读写。 表中的结构体被定义为:

@example
typedef struct PyMemberDef @{
    const char *name;
    int         type;
    int         offset;
    int         flags;
    const char *doc;
@} PyMemberDef;
@end example

对于表中的每个条目，将构建一个 @ref{15a8,,descriptor} 并添加到类型中使其能够从实例结构体中提取值。 @ref{709,,type} 字段应当包含在 @code{structmember.h} 头文件中定义的某个类型的代码；该值将被用来确定如何将 Python 值转换为 C 值或者反之。 @code{flags} 字段将被用来储存控制属性可以如何被访问的旗标。

以下标志常量定义在:file: ' structmember.h ';它们可以使用bitwise-OR组合。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

常数

@tab

意义

@item

@code{READONLY}

@tab

没有可写的

@item

@code{READ_RESTRICTED}

@tab

Not readable in restricted mode.

@item

@code{WRITE_RESTRICTED}

@tab

Not writable in restricted mode.

@item

@code{RESTRICTED}

@tab

在受限模式下不可读，也不可写。

@end multitable


@geindex READONLY
@geindex READ_RESTRICTED
@geindex WRITE_RESTRICTED
@geindex RESTRICTED

使用 @ref{3d98,,tp_members} 表来构建用于运行时的描述器还有一个有趣的优点是任何以这种方式定义的属性都可以简单地通过在表中提供文本来设置一个相关联的文档字符串。 一个应用程序可以使用自省 API 从类对象获取描述器，并使用其 @code{__doc__} 属性来获取文档字符串。

与 @ref{3d9a,,tp_methods} 表一样，需要有一个值为 @code{NULL} 的哨兵条目 @code{name}。

@c XXX Descriptors need to be explained in more detail somewhere, but not here.
@c 
@c Descriptor objects have two handler functions which correspond to the
@c \member{tp_getattro} and \member{tp_setattro} handlers.  The
@c \method{__get__()} handler is a function which is passed the descriptor,
@c instance, and type objects, and returns the value of the attribute, or it
@c returns \NULL{} and sets an exception.  The \method{__set__()} handler is
@c passed the descriptor, instance, type, and new value;

@node 类型专属的属性管理,,泛型属性管理,属性管理
@anchor{extending/newtypes type-specific-attribute-management}@anchor{3db4}
@subsubsection 类型专属的属性管理


为了简单起见，这里只演示 @code{char*} 版本；name 形参的类型是 @code{char*} 和 @ref{5bd,,PyObject*} 风格接口之间的唯一区别。 这个示例实际上做了与上面的泛用示例相同的事情，但没有使用在 Python 2.2 中增加的泛用支持。 它解释了处理句柄函数是如何被调用的，因此如果你确实需要扩展它们的功能，你就会明白有什么是需要做的。

@ref{3db5,,tp_getattr} 处理句柄会在对象需要查找属性时被调用。 它被调用的情况与一个类的 @ref{433,,__getattr__()} 方法要被调用的情况相同。

例如：

@example
static PyObject *
newdatatype_getattr(newdatatypeobject *obj, char *name)
@{
    if (strcmp(name, "data") == 0)
    @{
        return PyLong_FromLong(obj->data);
    @}

    PyErr_Format(PyExc_AttributeError,
                 "'%.50s' object has no attribute '%.400s'",
                 tp->tp_name, name);
    return NULL;
@}
@end example

@ref{3db6,,tp_setattr} 处理句柄会在要调用一个类实例的 @ref{ef6,,__setattr__()} 或 @ref{1592,,__delattr__()} 方法时被调用。 当一个属性应当被删除时，第三个形参将为 @code{NULL}。 下面是一个简单地引发异常的例子；如果这确实是你想要的，则 @ref{3db6,,tp_setattr} 处理句柄应当被设为 @code{NULL}。

@example
static int
newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
@{
    PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
    return -1;
@}
@end example

@node 对象比较,抽象协议支持,属性管理,定义扩展类型：已分类主题
@anchor{extending/newtypes object-comparison}@anchor{3db7}
@subsubsection 对象比较


@example
richcmpfunc tp_richcompare;
@end example

@ref{3db8,,tp_richcompare} 处理句柄会在需要进行比较时被调用。 它类似于 @ref{159a,,富比较方法}，例如 @ref{d06,,__lt__()}，并会被 @ref{3db9,,PyObject_RichCompare()} 和 @ref{10e5,,PyObject_RichCompareBool()} 所调用。

此函数被调用时将传入两个 Python 对象和运算符作为参数，其中运算符为 @code{Py_EQ}, @code{Py_NE}, @code{Py_LE}, @code{Py_GE}, @code{Py_LT} 或 @code{Py_GT} 之一。 它应当使用指定的运算符来比较两个对象并在比较操作成功时返回 @code{Py_True} 或 @code{Py_False}，如果比较操作未被实现并应尝试其他对象比较方法时则返回 @code{Py_NotImplemented}，或者如果设置了异常则返回 @code{NULL}。

下面是一个示例实现，该数据类型如果内部指针的大小相等就认为是相等的:

@example
static PyObject *
newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op)
@{
    PyObject *result;
    int c, size1, size2;

    /* code to make sure that both arguments are of type
       newdatatype omitted */

    size1 = obj1->obj_UnderlyingDatatypePtr->size;
    size2 = obj2->obj_UnderlyingDatatypePtr->size;

    switch (op) @{
    case Py_LT: c = size1 <  size2; break;
    case Py_LE: c = size1 <= size2; break;
    case Py_EQ: c = size1 == size2; break;
    case Py_NE: c = size1 != size2; break;
    case Py_GT: c = size1 >  size2; break;
    case Py_GE: c = size1 >= size2; break;
    @}
    result = c ? Py_True : Py_False;
    Py_INCREF(result);
    return result;
 @}
@end example

@node 抽象协议支持,弱引用支持,对象比较,定义扩展类型：已分类主题
@anchor{extending/newtypes abstract-protocol-support}@anchor{3dba}
@subsubsection 抽象协议支持


Python 支持多种 @emph{抽象} '协议'；被提供来使用这些接口的专门接口说明请在 @ref{3dbb,,抽象对象层} 中查看。

这些抽象接口很多都是在 Python 实现开发的早期被定义的。 特别地，数字、映射和序列协议从一开始就已经是 Python 的组成部分。 其他协议则是后来添加的。 对于依赖某些来自类型实现的处理句柄例程的协议来说，较旧的协议被定义为类型对象所引用的处理句柄的可选块。 对于较新的协议来说在主类型对象中还有额外的槽位，并带有一个预设旗标位来指明存在该槽位并应当由解释器来检查。 （此旗标位并不会指明槽位值非 @code{NULL} 的情况，可以设置该旗标来指明一个槽位的存在，但此本位仍可能保持未填充的状态。）

@example
PyNumberMethods   *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods  *tp_as_mapping;
@end example

如果你希望你的对象的行为类似一个数字、序列或映射对象，那么你就要分别放置一个实现了 C 类型 @ref{e4e,,PyNumberMethods}, @ref{3dbc,,PySequenceMethods} 或 @ref{3dbd,,PyMappingMethods}, 的结构体的地址。 你要负责将适当的值填入这些结构体。 你可以在 Python 源代码发布版的 @code{Objects} 目录中找到这些对象各自的用法示例。

@example
hashfunc tp_hash;
@end example

如果你选择提供此函数，则它应当为你的数据类型的实例返回一个哈希数值。 下面是一个简单的示例:

@example
static Py_hash_t
newdatatype_hash(newdatatypeobject *obj)
@{
    Py_hash_t result;
    result = obj->some_size + 32767 * obj->some_number;
    if (result == -1)
       result = -2;
    return result;
@}
@end example

@code{Py_hash_t} 是一个在宽度取决于具体平台的有符号整数类型。 从 @ref{3dbe,,tp_hash} 返回 @code{-1} 表示发生了错误，这就是为什么你应当注意避免在哈希运算成功时返回它，如上面所演示的。

@example
ternaryfunc tp_call;
@end example

此函数会在“调用”你的数据类型实例时被调用，举例来说，如果 @code{obj1} 是你的数据类型的实例而 Python 脚本包含了 @code{obj1('hello')}，则将发起调用 @ref{3dbf,,tp_call} 处理句柄。

此函数接受三个参数:


@enumerate 

@item 
@emph{self} 是作为调用目标的数据类型实例。 如果调用是 @code{obj1('hello')}，则 @emph{self} 为 @code{obj1}。

@item 
@emph{args} 是包含调用参数的元组。 你可以使用 @ref{39b,,PyArg_ParseTuple()} 来提取参数。

@item 
@emph{kwds} 是由传入的关键字参数组成的字典。 如果它不为 @code{NULL} 且你支持关键字参数，则可使用 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 来提取参数。 如果你不想支持关键字参数而它为非 @code{NULL} 值，则会引发 @ref{1ff,,TypeError} 并附带一个提示不支持关键字参数的消息。
@end enumerate

下面是一个演示性的 @code{tp_call} 实现:

@example
static PyObject *
newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds)
@{
    PyObject *result;
    const char *arg1;
    const char *arg2;
    const char *arg3;

    if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) @{
        return NULL;
    @}
    result = PyUnicode_FromFormat(
        "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n",
        obj->obj_UnderlyingDatatypePtr->size,
        arg1, arg2, arg3);
    return result;
@}
@end example

@example
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
@end example

这些函数提供了对迭代器协议的支持。 两个处理句柄都只接受一个形参，即它们被调用时所使用的实例，并返回一个新的引用。 当发生错误时，它们应当设置一个异常并返回 @code{NULL}。  @ref{efa,,tp_iter} 对应于 Python @ref{611,,__iter__()} 方法，而 @ref{efb,,tp_iternext} 对应于 Python @ref{d34,,__next__()} 方法。

任何 @ref{c84,,iterable} 对象都必须实现 @ref{efa,,tp_iter} 处理句柄，该处理句柄必须返回一个 @ref{11ba,,iterator} 对象。 下面是是与 Python 类所应用的同一个指导原则:


@itemize *

@item 
对于可以支持多个独立迭代器的多项集（如列表和元组），则应当在每次调用 @ref{efa,,tp_iter} 时创建并返回一个新的迭代器。

@item 
只能被迭代一次的对象（通常是由于迭代操作的附带影响，例如文件对象）可以通过返回一个指向自身的新引用来实现 @ref{efa,,tp_iter} -- 并且为此还应当实现 @ref{efb,,tp_iternext}  处理句柄。
@end itemize

任何 @ref{11ba,,iterator} 对象都应当同时实现 @ref{efa,,tp_iter} 和 @ref{efb,,tp_iternext}。 一个迭代器的 @ref{efa,,tp_iter} 处理句柄应当返回一个指向该迭代器的新引用。 它的 @ref{efb,,tp_iternext} 处理句柄应当返回一个指向迭代操作的下一个对象的新引用，如果还有下一个对象的话。 如果迭代已到达末尾，则 @ref{efb,,tp_iternext} 可以返回 @code{NULL} 而不设置异常，或者也可以在返回 @code{NULL} 的基础上 @emph{额外} 设置 @ref{58a,,StopIteration}；避免异常可以产生更好的性能。 如果发生了实际的错误，则 @ref{efb,,tp_iternext} 应当总是设置一个异常并返回 @code{NULL}。

@node 弱引用支持,更多建议,抽象协议支持,定义扩展类型：已分类主题
@anchor{extending/newtypes weak-reference-support}@anchor{3dc0}@anchor{extending/newtypes weakref-support}@anchor{1b22}
@subsubsection 弱引用支持


One of the goals of Python 弱引用实现的目标之一是允许任意类型参与弱引用机制而不会在重视性能的对象（例如数字）上产生额外开销。


@subsubheading 参见


@ref{131,,weakref} 模块的文档。


对于可弱引用的对象，扩展类型必须做两件事:


@enumerate 

@item 
在 C 对象结构体中包括一个专门用于弱引用机制的 @ref{5bd,,PyObject*} 字段。 该对象的构造器应当让它保持为 @code{NULL} (当使用默认的 @ref{3d95,,tp_alloc} 时这将会自动设置)。

@item 
将 @ref{26c,,tp_weaklistoffset} 类型成员设置为 C 对象结构体中上述字段的偏移量，这样解释器就能知道如何访问和修改该字段。
@end enumerate

具体来说，下面是一个微小的对象结构体如何被增强为具有所需的字段:

@example
typedef struct @{
    PyObject_HEAD
    PyObject *weakreflist;  /* List of weak references */
@} TrivialObject;
@end example

以及在静态声明的类型对象中的相应成员:

@example
static PyTypeObject TrivialType = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    /* ... other members omitted for brevity ... */
    .tp_weaklistoffset = offsetof(TrivialObject, weakreflist),
@};
@end example

唯一的额外补充是如果字段不为 @code{NULL} 则 @code{tp_dealloc} 需要清除任何弱引用 (通过调用 @code{PyObject_ClearWeakRefs()})。:

@example
static void
Trivial_dealloc(TrivialObject *self)
@{
    /* Clear weakrefs first before calling any destructors */
    if (self->weakreflist != NULL)
        PyObject_ClearWeakRefs((PyObject *) self);
    /* ... remainder of destruction code omitted for brevity ... */
    Py_TYPE(self)->tp_free((PyObject *) self);
@}
@end example

@node 更多建议,,弱引用支持,定义扩展类型：已分类主题
@anchor{extending/newtypes more-suggestions}@anchor{3dc1}
@subsubsection 更多建议


为了学习如何为你的新数据类型实现任何特定方法，请获取 @ref{1598,,CPython} 源代码。 进入 @code{Objects} 目录，然后在 C 源文件中搜索 @code{tp_} 加上你想要的函数 (例如，@code{tp_richcompare})。 你将找到你想要实现的函数的例子。

当你需要验证一个对象是否为你实现的类型的具体实例时，请使用 @ref{3dc2,,PyObject_TypeCheck()} 函数。 它的一个用法示例如下:

@example
if (!PyObject_TypeCheck(some_object, &MyType)) @{
    PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
    return NULL;
@}
@end example


@subsubheading 参见



@table @asis

@item 下载CPython源代码版本。

@indicateurl{https://www.python.org/downloads/source/}

@item GitHub上开发CPython源代码的CPython项目。

@indicateurl{https://github.com/python/cpython}
@end table


@node 构建C/C++扩展,在 Windows 上构建 C 和 C++ 扩展,定义扩展类型：已分类主题,不使用第三方工具创建扩展
@anchor{extending/building doc}@anchor{3dc3}@anchor{extending/building building}@anchor{3d63}@anchor{extending/building building-c-and-c-extensions}@anchor{3dc4}
@subsection 构建C/C++扩展


一个CPython的C扩展是一个共享库(例如一个Linux上的 @code{.so} ，或者Windows上的 @code{.pyd} )，其会导出一个 @emph{初始化函数} 。

为了可导入，共享库必须在 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 中有效，且必须命名遵循模块名字，通过适当的扩展。当使用distutils时，会自动生成正确的文件名。

初始化函数的声明如下：

@geindex PyInit_modulename (C 函数)
@anchor{extending/building c PyInit_modulename}@anchor{3dc5}
@deffn {C 函数} PyObject* PyInit_modulename (void)
@end deffn

该函数返回完整初始化过的模块，或一个 @ref{259,,PyModuleDef} 实例。查看 @ref{3dc6,,初始化 C 模块} 了解更多细节。

对于仅有ASCII编码的模块名，函数必须是 @code{PyInit_<modulename>} ，将 @code{<modulename>} 替换为模块的名字。当使用 @ref{3dc7,,Multi-phase initialization} 时，允许使用非ASCII编码的模块名。此时初始化函数的名字是 @code{PyInitU_<modulename>} ，而 @code{<modulename>} 需要用Python的 @emph{punycode} 编码，连字号需替换为下划线。在Python里:

@example
def initfunc_name(name):
    try:
        suffix = b'_' + name.encode('ascii')
    except UnicodeEncodeError:
        suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
    return b'PyInit' + suffix
@end example

可以在一个动态库里导出多个模块，通过定义多个初始化函数。而导入他们需要符号链接或自定义导入器，因为缺省时只有对应了文件名的函数才会被发现。查看 @emph{"一个库里的多模块"} 章节，在 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} 了解更多细节。

@menu
* 使用distutils构建C和C++扩展:: 
* 发布你的扩展模块:: 

@end menu

@node 使用distutils构建C和C++扩展,发布你的扩展模块,,构建C/C++扩展
@anchor{extending/building building-c-and-c-extensions-with-distutils}@anchor{3dc8}
@subsubsection 使用distutils构建C和C++扩展


扩展模块可以用distutils来构建，这是Python自带的。distutils也支持创建二进制包，用户无需编译器而distutils就能安装扩展。

一个distutils包包含了一个驱动脚本 @code{setup.py} 。这是个纯Python文件，大多数时候也很简单，看起来如下：

@example
from distutils.core import setup, Extension

module1 = Extension('demo',
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])
@end example

通过文件 @code{setup.py} ，和文件 @code{demo.c} ，运行如下

@example
python setup.py build
@end example

这会编译 @code{demo.c} ，然后产生一个扩展模块叫做 @code{demo} 在目录 @code{build} 里。依赖于系统，模块文件会放在某个子目录形如 @code{build/lib.system} ，名字可能是 @code{demo.so} 或 @code{demo.pyd} 。

在文件 @code{setup.py} 里，所有动作的入口通过 @code{setup} 函数。该函数可以接受可变数量个关键字参数，上面的例子只使用了一个子集。特别需要注意的例子指定了构建包的元信息，以及指定了包内容。通常一个包会包括多个模块，就像Python的源码模块、文档、子包等。请参数distutils的文档，在 @ref{8ef,,分发 Python 模块（遗留版本）} 来了解更多distutils的特性；本章节只解释构建扩展模块的部分。

通常预计算参数给 @code{setup()} ，想要更好的结构化驱动脚本。有如如上例子函数 @ref{3dc9,,setup()} 的 @code{ext_modules} 参数是一列扩展模块，每个是一个 @code{Extension} 类的实例。例子中的实例定义了扩展命名为 @code{demo} ，从单一源码文件构建 @code{demo.c} 。

更多时候，构建一个扩展会复杂的多，需要额外的预处理器定义和库。如下例子展示了这些。

@example
from distutils.core import setup, Extension

module1 = Extension('demo',
                    define_macros = [('MAJOR_VERSION', '1'),
                                     ('MINOR_VERSION', '0')],
                    include_dirs = ['/usr/local/include'],
                    libraries = ['tcl83'],
                    library_dirs = ['/usr/local/lib'],
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       author = 'Martin v. Loewis',
       author_email = 'martin@@v.loewis.de',
       url = 'https://docs.python.org/extending/building',
       long_description = '@w{'}'
This is really just a demo package.
'@w{'}',
       ext_modules = [module1])
@end example

例子中函数 @ref{3dc9,,setup()} 在调用时额外传递了元信息，是推荐发布包构建时的内容。对于这个扩展，其指定了预处理器定义，include目录，库目录，库。依赖于编译器，distutils还会用其他方式传递信息给编译器。例如在Unix上，结果是如下编译命令

@example
gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o

gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so
@end example

这些行代码仅用于展示目的；distutils用户应该相信distutils能正确调用。

@node 发布你的扩展模块,,使用distutils构建C和C++扩展,构建C/C++扩展
@anchor{extending/building distributing}@anchor{3dca}@anchor{extending/building distributing-your-extension-modules}@anchor{3dcb}
@subsubsection 发布你的扩展模块


当一个扩展已经成功地被构建时，有三种方式来使用它。

最终用户通常想要安装模块，可以这么运行

@example
python setup.py install
@end example

模块维护者应该制作源码包；要实现可以运行

@example
python setup.py sdist
@end example

有些情况下，需要在源码发布包里包含额外的文件；这通过 @code{MANIFEST.in} 文件实现，查看 @ref{3dcc,,指定要分发的文件} 了解细节。

如果源码发行包被成功地构建，维护者还可以创建二进制发行包。 取决于具体平台，以下命令中的一个可以用来完成此任务

@example
python setup.py bdist_wininst
python setup.py bdist_rpm
python setup.py bdist_dumb
@end example

@node 在 Windows 上构建 C 和 C++ 扩展,,构建C/C++扩展,不使用第三方工具创建扩展
@anchor{extending/windows doc}@anchor{3dcd}@anchor{extending/windows building-c-and-c-extensions-on-windows}@anchor{3dce}@anchor{extending/windows building-on-windows}@anchor{14fb}
@subsection 在 Windows 上构建 C 和 C++ 扩展


这一章简要介绍了如何使用 Microsoft Visual C++ 创建 Python 的 Windows 扩展模块，然后再提供有关其工作机理的详细背景信息。 这些说明材料同时适用于 Windows 程序员学习构建 Python 扩展以及 Unix 程序员学习如何生成在 Unix 和 Windows 上均能成功构建的软件。

鼓励模块作者使用 distutils 方式来构建扩展模块，而不使用本节所描述的方式。 你仍将需要使用 C 编译器来构建 Python；通常为 Microsoft Visual C++。

@cartouche
@quotation 注解 
这一章提及了多个包括已编码 Python 版本号的文件名。 这些文件名以显示为 @code{XY} 的版本号来代表；在实践中，@code{'X'} 将为你所使用的 Python 发布版的主版本号而 @code{'Y'} 将为次版本号。 例如，如果你所使用的是 Python 2.2.1，@code{XY} 将为 @code{22}。
@end quotation
@end cartouche

@menu
* 菜谱式说明:: 
* Unix 和 Windows 之间的差异:: 
* DLL 的实际使用:: 

@end menu

@node 菜谱式说明,Unix 和 Windows 之间的差异,,在 Windows 上构建 C 和 C++ 扩展
@anchor{extending/windows a-cookbook-approach}@anchor{3dcf}@anchor{extending/windows win-cookbook}@anchor{3dd0}
@subsubsection 菜谱式说明


在 Windows 和 Unix 上构建扩展模块都有两种方式：使用 @ref{38,,distutils} 包来控制构建过程，或者全手动操作。 distutils 方式适用于大多数扩展；使用 @ref{38,,distutils} 构建和打包扩展模块的文档见 @ref{8ef,,分发 Python 模块（遗留版本）}。 如果你发现你确实需要手动操作，那么研究一下 winsound@footnote{https://github.com/python/cpython/tree/3.9/PCbuild/winsound.vcxproj} 标准库模块的项目文件可能会很有帮助。

@node Unix 和 Windows 之间的差异,DLL 的实际使用,菜谱式说明,在 Windows 上构建 C 和 C++ 扩展
@anchor{extending/windows differences-between-unix-and-windows}@anchor{3dd1}@anchor{extending/windows dynamic-linking}@anchor{3dd2}
@subsubsection Unix 和 Windows 之间的差异


Unix 和 Windows 对于代码的运行时加载使用了完全不同的范式。 在你尝试构建可动态加载的模块之前，要先了解你所用系统是如何工作的。

在 Unix 中，一个共享对象 (@code{.so}) 文件中包含将由程序来使用的代码，也包含在程序中可被找到的函数名称和数据。 当文件被合并到程序中时，对在文件代码中这些函数和数据的全部引用都会被改为指向程序中函数和数据在内存中所放置的实际位置。 这基本上是一个链接操作。

在 Windows 中，一个动态链接库 (@code{.dll}) 文件中没有悬挂的引用。 而是通过一个查找表执行对函数或数据的访问。 因此在运行时 DLL 代码不必在运行时进行修改；相反地，代码已经使用了 DLL 的查找表，并且在运行时查找表会被修改以指向特定的函数和数据。

在 Unix 中，只存在一种库文件 (@code{.a})，它包含来自多个对象文件 (@code{.o}) 的代码。 在创建共享对象文件 (@code{.so}) 的链接阶段，链接器可能会发现它不知道某个标识符是在哪里定义的。 链接器将在各个库的对象文件中查找它；如果找到了它，链接器将会包括来自该对象文件的所有代码。

在 Windows 中，存在两种库类型，静态库和导入库 (扩展名都是 @code{.lib})。 静态库类似于 Unix 的 @code{.a} 文件；它包含在必要时可被包括的代码。 导入库基本上仅用于让链接器能确保特定标识符是合法的，并且将在 DLL 被加载时出现于程序中。 这样链接器可使用来自导入库的信息构建查找表以便使用未包括在 DLL 中的标识符。 当一个应用程序或  DLL 被链接时，可能会生成一个导入库，它将需要被用于应用程序或 DLL 中未来所有依赖于这些符号的 DLL。

假设你正在编译两个动态加载模块 B 和 C，它们应当共享另一个代码块 A。 在 Unix 上，你 @emph{不应} 将 @code{A.a} 传给链接器作为 @code{B.so} 和 @code{C.so}；那会导致它被包括两次，这样 B 和 C 将分别拥有它们自己的副本。 在 Windows 上，编译 @code{A.dll} 将同时编译 @code{A.lib}。 你 @emph{应当} 将 @code{A.lib} 传给链接器用于 B 和 C。 @code{A.lib} 并不包含代码；它只包含将在运行时被用于访问 A 的代码的信息。

在 Windows 上，使用导入库有点像是使用 @code{import spam}；它让你可以访问 spam 中的名称，但并不会创建一个单独副本。 在 Unix 上，链接到一个库更像是 @code{from spam import *}；它会创建一个单独副本。

@node DLL 的实际使用,,Unix 和 Windows 之间的差异,在 Windows 上构建 C 和 C++ 扩展
@anchor{extending/windows using-dlls-in-practice}@anchor{3dd3}@anchor{extending/windows win-dlls}@anchor{3dd4}
@subsubsection DLL 的实际使用


Windows Python 是在 Microsoft Visual C++ 中构建的；使用其他编译器可能会也可能不会工作。本节的其余部分是针对 MSVC++ 的。

当在 Windows 中创建 DLL 时，你必须将 @code{pythonXY.lib} 传给链接器。 要编译两个 DLL，spam 和 ni (会使用 spam 中找到的 C 函数)，你应当使用以下命令:

@example
cl /LD /I/python/include spam.c ../libs/pythonXY.lib
cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib
@end example

第一条命令创建了三个文件: @code{spam.obj}, @code{spam.dll} 和 @code{spam.lib}。 @code{Spam.dll} 不包含任何 Python 函数 (例如 @ref{39b,,PyArg_ParseTuple()})，但它通过 @code{pythonXY.lib} 可以知道如何找到所需的 Python 代码。

第二条命令创建了 @code{ni.dll} (以及 @code{.obj} 和 @code{.lib})，它知道如何从 spam 以及 Python 可执行文件中找到所需的函数。

不是每个标识符都会被导出到查找表。 如果你想要任何其他模块（包括 Python）都能看到你的标识符，你必须写上 @code{_declspec(dllexport)}，就如在 @code{void _declspec(dllexport) initspam(void)} 或 @code{PyObject _declspec(dllexport) *NiGetSpamData(void)} 中一样。

Developer Studio 将加入大量你并不真正需要的导入库，使你的可执行文件大小增加 100K。 要摆脱它们，请使用项目设置对话框的链接选项卡指定 @emph{忽略默认库}。 将正确的 @code{msvcrtxx.lib} 添加到库列表中。

@node 在更大的应用程序中嵌入 CPython 运行时,,不使用第三方工具创建扩展,扩展和嵌入 Python 解释器
@anchor{extending/index embedding-the-cpython-runtime-in-a-larger-application}@anchor{3dd5}
@section 在更大的应用程序中嵌入 CPython 运行时


有时，不是要创建在 Python 解释器中作为主应用程序运行的扩展，而是希望将 CPython 运行时嵌入到更大的应用程序中。 本节介绍了成功完成此操作所涉及的一些细节。

@menu
* 在其它应用程序嵌入 Python:: 

@end menu

@node 在其它应用程序嵌入 Python,,,在更大的应用程序中嵌入 CPython 运行时
@anchor{extending/embedding doc}@anchor{3dd6}@anchor{extending/embedding embedding}@anchor{3dd7}@anchor{extending/embedding embedding-python-in-another-application}@anchor{3dd8}
@subsection 在其它应用程序嵌入 Python


前几章讨论了如何对 Python 进行扩展，也就是如何用 C 函数库 扩展 Python 的功能。反过来也是可以的：将 Python 嵌入到 C/C++ 应用程序中丰富其功能。这种嵌入可以让应用程序用 Python 来实现某些功能，而不是用 C 或 C++ 。用途会有很多；比如允许用户用 Python 编写一些脚本，以便定制应用程序满足需求。如果某些功能用 Python 编写起来更为容易，那么开发人员自己也能这么干。

Python 的嵌入类似于扩展，但不完全相同。不同之处在于，扩展 Python 时应用程序的主程序仍然是 Python 解释器，而嵌入 Python 时的主程序可能与 Python 完全无关——而是应用程序的某些部分偶尔会调用 Python 解释器来运行一些 Python 代码。

因此，若要嵌入 Python，就要提供自己的主程序。此主程序要做的事情之一就是初始化 Python 解释器。至少得调用函数 @ref{210,,Py_Initialize()}。还有些可选的调用可向 Python 传递命令行参数。之后即可从应用程序的任何地方调用解释器了。

调用解释器的方式有好几种：可向 @ref{3dd9,,PyRun_SimpleString()} 传入一个包含 Python 语句的字符串，也可向 @ref{3dda,,PyRun_SimpleFile()} 传入一个 stdio 文件指针和一个文件名（仅在错误信息中起到识别作用）。还可以调用前面介绍过的底层操作来构造并使用 Python 对象。


@subsubheading 参见



@table @asis

@item @ref{1362,,Python/C API 参考手册}

本文详细介绍了 Python 的 C 接口。这里有大量必要的信息。
@end table


@menu
* 高层次的嵌入:: 
* 突破高层次嵌入的限制：概述:: 
* 纯嵌入:: 
* 对嵌入 Python 功能进行扩展:: 
* 在 C++ 中嵌入 Python:: 
* 在类 Unix 系统中编译和链接:: 

@end menu

@node 高层次的嵌入,突破高层次嵌入的限制：概述,,在其它应用程序嵌入 Python
@anchor{extending/embedding high-level-embedding}@anchor{3ddb}@anchor{extending/embedding very-high-level-embedding}@anchor{3ddc}
@subsubsection 高层次的嵌入


最简单的 Python 嵌入形式就是采用非常高层的接口。该接口的目标是只执行一段 Python 脚本，而无需与应用程序直接交互。比如以下代码可以用来对某个文件进行一些操作。

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
@{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) @{
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    @}
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) @{
        exit(120);
    @}
    PyMem_RawFree(program);
    return 0;
@}
@end example

在 @ref{210,,Py_Initialize()} 之前，应该先调用 @ref{113b,,Py_SetProgramName()} 函数，以便向解释器告知 Python运行库的路径。接下来，@ref{210,,Py_Initialize()}  会初始化 Python 解释器，然后执行硬编码的 Python 脚本，打印出日期和时间。之后，调用 @ref{6ca,,Py_FinalizeEx()} 关闭解释器，程序结束。在真实的程序中，可能需要从其他来源获取 Python 脚本，或许是从文本编辑器例程、文件，或者某个数据库。利用 @ref{3dda,,PyRun_SimpleFile()} 函数可以更好地从文件中获取 Python 代码，可省去分配内存空间和加载文件内容的麻烦。

@node 突破高层次嵌入的限制：概述,纯嵌入,高层次的嵌入,在其它应用程序嵌入 Python
@anchor{extending/embedding beyond-very-high-level-embedding-an-overview}@anchor{3ddd}@anchor{extending/embedding lower-level-embedding}@anchor{3dde}
@subsubsection 突破高层次嵌入的限制：概述


高级接口能从应用程序中执行任何 Python 代码，但至少交换数据可说是相当麻烦的。如若需要交换数据，应使用较低级别的调用。几乎可以实现任何功能，代价是得写更多的 C 代码。

应该注意，尽管意图不同，但扩展 Python 和嵌入 Python 的过程相当类似。前几章中讨论的大多数主题依然有效。为了说明这一点，不妨来看一下从  Python 到 C 的扩展代码到底做了什么：


@enumerate 

@item 
转换 Python 的数据值到 C,

@item 
用转换后的数据执行 C 程序的函数调用，以及

@item 
将调用返回的数据从 C 转换为 Python 格式。
@end enumerate

嵌入 Python 时，接口代码会这样做：


@enumerate 

@item 
转换 C 的数据值到 Python,

@item 
用转换后的数据执行对 Python 接口的函数调用，

@item 
将调用返回的数据从 Python 转换为 C  格式。
@end enumerate

可见只是数据转换的步骤交换了一下顺序，以顺应跨语言的传输方向。唯一的区别是在两次数据转换之间调用的函数不同。在执行扩展时，调用一个 C 函数，而执行嵌入时调用的是个 Python 函数。

本文不会讨论如何将数据从 Python 转换到 C 去，反之亦然。另外还假定读者能够正确使用引用并处理错误。由于这些地方与解释器的扩展没有区别，请参考前面的章节以获得所需的信息。

@node 纯嵌入,对嵌入 Python 功能进行扩展,突破高层次嵌入的限制：概述,在其它应用程序嵌入 Python
@anchor{extending/embedding id1}@anchor{3ddf}@anchor{extending/embedding pure-embedding}@anchor{3de0}
@subsubsection 纯嵌入


第一个程序的目标是执行 Python 脚本中的某个函数。就像高层次接口那样，Python 解释器并不会直接与应用程序进行交互（但下一节将改变这一点）。

要运行 Python 脚本中定义的函数，代码如下：

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
@{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) @{
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    @}

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) @{
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) @{
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) @{
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) @{
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                @}
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            @}
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) @{
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            @}
            else @{
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            @}
        @}
        else @{
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        @}
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    @}
    else @{
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    @}
    if (Py_FinalizeEx() < 0) @{
        return 120;
    @}
    return 0;
@}
@end example

上述代码先利用 @code{argv[1]} 加载 Python 脚本，再调用 @code{argv[2]} 指定的函数。函数的整数参数是 @code{argv} 数组中的其余值。如果 @ref{3de1,,编译并链接} 该程序（此处将最终的可执行程序称作 @code{call}）, 并用它执行一个 Python 脚本，例如：

@example
def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c
@end example

然后结果应该是:

@example
$ call multiply multiply 3 2
Will compute 3 times 2
Result of call: 6
@end example

尽管相对其功能而言，该程序体积相当庞大，但大部分代码是用于 Python 和 C 之间的数据转换，以及报告错误。嵌入 Python 的有趣部分从此开始：

@example
Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
@end example

初始化解释器之后，则用 @ref{e2c,,PyImport_Import()} 加载脚本。此函数的参数需是个 Python 字符串，一个用 @ref{3de2,,PyUnicode_FromString()} 数据转换函数构建的字符串。

@example
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) @{
    ...
@}
Py_XDECREF(pFunc);
@end example

脚本一旦加载完毕，就会用 @ref{3d72,,PyObject_GetAttrString()} 查找属性名称。如果名称存在，并且返回的是可调用对象，即可安全地视其为函数。然后程序继续执行，照常构建由参数组成的元组。然后用以下方式调用 Python 函数：

@example
pValue = PyObject_CallObject(pFunc, pArgs);
@end example

当函数返回时，@code{pValue} 要么为 @code{NULL}，要么包含对函数返回值的引用。请确保用完后释放该引用。

@node 对嵌入 Python 功能进行扩展,在 C++ 中嵌入 Python,纯嵌入,在其它应用程序嵌入 Python
@anchor{extending/embedding extending-embedded-python}@anchor{3de3}@anchor{extending/embedding extending-with-embedding}@anchor{3de4}
@subsubsection 对嵌入 Python 功能进行扩展


到目前为止，嵌入的 Python 解释器还不能访问应用程序本身的功能。Python API 通过扩展嵌入解释器实现了这一点。 也就是说，用应用程序提供的函数对嵌入的解释器进行扩展。虽然听起来有些复杂，但也没那么糟糕。只要暂时忘记是应用程序启动了 Python 解释器。而把应用程序看作是一堆子程序，然后写一些胶水代码让 Python 访问这些子程序，就像编写普通的 Python 扩展程序一样。 例如：

@example
static int numargs=0;

/* Return the number of arguments of the application command line */
static PyObject*
emb_numargs(PyObject *self, PyObject *args)
@{
    if(!PyArg_ParseTuple(args, ":numargs"))
        return NULL;
    return PyLong_FromLong(numargs);
@}

static PyMethodDef EmbMethods[] = @{
    @{"numargs", emb_numargs, METH_VARARGS,
     "Return the number of arguments received by the process."@},
    @{NULL, NULL, 0, NULL@}
@};

static PyModuleDef EmbModule = @{
    PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
    NULL, NULL, NULL, NULL
@};

static PyObject*
PyInit_emb(void)
@{
    return PyModule_Create(&EmbModule);
@}
@end example

在 @code{main()} 函数之前插入上述代码。并在调用 @ref{210,,Py_Initialize()} 之前插入以下两条语句：

@example
numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);
@end example

这两行代码初始化了 @code{numargs} 变量，并让 @code{emb.numargs()} 函数能被嵌入的 Python 解释器访问到。有了这些扩展，Python 脚本可以执行类似以下功能：

@example
import emb
print("Number of arguments", emb.numargs())
@end example

在真实的应用程序中，这种方法将把应用的 API 暴露给 Python 使用。

@c TODO: threads, code examples do not really behave well if errors happen
@c (what to watch out for)

@node 在 C++ 中嵌入 Python,在类 Unix 系统中编译和链接,对嵌入 Python 功能进行扩展,在其它应用程序嵌入 Python
@anchor{extending/embedding embedding-python-in-c}@anchor{3de5}@anchor{extending/embedding embeddingincplusplus}@anchor{3de6}
@subsubsection 在 C++ 中嵌入 Python


还可以将 Python 嵌入到 C++ 程序中去；确切地说，实现方式将取决于 C++ 系统的实现细节；一般需用 C++ 编写主程序，并用 C++ 编译器来编译和链接 程序。不需要用 C++ 重新编译 Python 本身。

@node 在类 Unix 系统中编译和链接,,在 C++ 中嵌入 Python,在其它应用程序嵌入 Python
@anchor{extending/embedding compiling}@anchor{3de1}@anchor{extending/embedding compiling-and-linking-under-unix-like-systems}@anchor{3de7}
@subsubsection 在类 Unix 系统中编译和链接


为了将 Python 解释器嵌入应用程序，找到正确的编译参数传给编译器 (和链接器) 并非易事，特别是因为 Python 加载的库模块是以 C 动态扩展（@code{.so} 文件）的形式实现的。

为了得到所需的编译器和链接器参数，可执行 @code{python@emph{X.Y}-config} 脚本，它是在安装 Python 时生成的（也可能存在 @code{python3-config} 脚本）。该脚本有几个参数，其中以下几个参数会直接有用：


@itemize *

@item 
@code{pythonX.Y-config --cflags} 将给出建议的编译参数。

@example
$ /opt/bin/python3.4-config --cflags
-I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
@end example

@item 
@code{pythonX.Y-config --ldflags} 将给出建议的链接参数。

@example
$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
@end example
@end itemize

@cartouche
@quotation 注解 
为了避免多个 Python 安装版本引发混乱（特别是在系统安装版本和自己编译版本之间），建议用 @code{python@emph{X.Y}-config} 指定绝对路径，如上例所述。
@end quotation
@end cartouche

如果上述方案不起作用（不能保证对所有 Unix 类平台都生效；欢迎提出 @ref{3de8,,bug 报告}），就得阅读系统关于动态链接的文档，并检查 Python 的 @code{Makefile} （用 @ref{36d0,,sysconfig.get_makefile_filename()} 找到所在位置）和编译参数。这时 @ref{fe,,sysconfig} 模块会是个有用的工具，可用编程方式提取需组合在一起的配置值。比如：

@example
>>> import sysconfig
>>> sysconfig.get_config_var('LIBS')
'-lpthread -ldl  -lutil'
>>> sysconfig.get_config_var('LINKFORSHARED')
'-Xlinker -export-dynamic'
@end example

@c XXX similar documentation for Windows missing

@node Python/C API 参考手册,分发 Python 模块,扩展和嵌入 Python 解释器,Top
@anchor{c-api/index doc}@anchor{3de9}@anchor{c-api/index c-api-index}@anchor{1362}@anchor{c-api/index python-c-api-reference-manual}@anchor{3dea}
@chapter Python/C API 参考手册


本手册描述了希望编写扩展模块并将 Python 解释器嵌入其应用程序中的 C 和 C++ 程序员可用的 API。同时可以参阅 @ref{1361,,扩展和嵌入 Python 解释器} ，其中描述了扩展编写的一般原则，但没有详细描述 API 函数。

@menu
* 概述: 概述<15>. 
* 稳定的应用程序二进制接口:: 
* 极高层级:: 
* 引用计数: 引用计数<3>. 
* 异常处理:: 
* 工具: 工具<2>. 
* 抽象对象层:: 
* 具体的对象层:: 
* 初始化，终结和线程:: 
* Python初始化配置:: 
* 内存管理:: 
* 对象实现支持:: 
* API 和 ABI 版本管理:: 

@end menu

@node 概述<15>,稳定的应用程序二进制接口,,Python/C API 参考手册
@anchor{c-api/intro doc}@anchor{3deb}@anchor{c-api/intro api-intro}@anchor{3dec}@anchor{c-api/intro introduction}@anchor{3ded}
@section 概述


Python 的应用编程接口（API）使得 C 和 C++ 程序员可以在多个层级上访问 Python 解释器。该 API 在 C++ 中同样可用，但为简化描述，通常将其称为 Python/C API。使用 Python/C API 有两个基本的理由。第一个理由是为了特定目的而编写 @emph{扩展模块}；它们是扩展 Python 解释器功能的 C 模块。这可能是最常见的使用场景。第二个理由是将 Python 用作更大规模应用的组件；这种技巧通常被称为在一个应用中 @emph{embedding} Python。

编写扩展模块的过程相对来说更易于理解，可以通过“菜谱”的形式分步骤介绍。使用某些工具可在一定程度上自动化这一过程。虽然人们在其他应用中嵌入 Python 的做法早已有之，但嵌入 Python 的过程没有编写扩展模块那样方便直观。

许多 API 函数在你嵌入或是扩展 Python 这两种场景下都能发挥作用；此外，大多数嵌入 Python 的应用程序也需要提供自定义扩展，因此在尝试在实际应用中嵌入 Python 之前先熟悉编写扩展应该会是个好主意。

@menu
* 代码标准:: 
* 包含文件:: 
* 有用的宏:: 
* 对象、类型和引用计数:: 
* 异常: 异常<19>. 
* 嵌入Python: 嵌入Python<2>. 
* 调试构建:: 

@end menu

@node 代码标准,包含文件,,概述<15>
@anchor{c-api/intro coding-standards}@anchor{3dee}
@subsection 代码标准


如果你想要编写可包含于 CPython 的 C 代码，你 @strong{必须} 遵循在 
@geindex Python 提高建议; PEP 7
PEP 7@footnote{https://www.python.org/dev/peps/pep-0007} 中定义的指导原则和标准。这些指导原则适用于任何你所要扩展的 Python 版本。在编写你自己的第三方扩展模块时可以不必遵循这些规范，除非你准备在日后向 Python 贡献这些模块。

@node 包含文件,有用的宏,代码标准,概述<15>
@anchor{c-api/intro api-includes}@anchor{3def}@anchor{c-api/intro include-files}@anchor{3df0}
@subsection 包含文件


使用 Python/C API 所需要的全部函数、类型和宏定义可通过下面这行语句包含到你的代码之中：

@example
#define PY_SSIZE_T_CLEAN
#include <Python.h>
@end example

这意味着包含以下标准头文件：@code{<stdio.h>}，@code{<string.h>}，@code{<errno.h>}，@code{<limits.h>}，@code{<assert.h>} 和 @code{<stdlib.h>}（如果可用）。

@cartouche
@quotation 注解 
由于 Python 可能会定义一些能在某些系统上影响标准头文件的预处理器定义，因此在包含任何标准头文件之前，你 @emph{必须} 先包含 @code{Python.h}。

推荐总是在 @code{Python.h} 前定义 @code{PY_SSIZE_T_CLEAN} 。查看 @ref{3fb,,语句解释及变量编译} 来了解这个宏的更多内容。
@end quotation
@end cartouche

Python.h 所定义的全部用户可见名称（由包含的标准头文件所定义的除外）都带有前缀 @code{Py} 或者 @code{_Py}。以 @code{_Py} 打头的名称是供 Python 实现内部使用的，不应被扩展编写者使用。结构成员名称没有保留前缀。

@cartouche
@quotation 注解 
用户代码永远不应该定义以 @code{Py} 或 @code{_Py} 开头的名称。这会使读者感到困惑，并危及用户代码对未来Python版本的可移植性，这些版本可能会定义以这些前缀之一开头的其他名称。
@end quotation
@end cartouche

头文件通常会与 Python 一起安装。在 Unix 上，它们位于以下目录：@code{@emph{prefix}/include/pythonversion/} 和 @code{@emph{exec_prefix}/include/pythonversion/}，其中 
@geindex prefix
@geindex 环境变量; prefix
@code{prefix} 和 
@geindex exec_prefix
@geindex 环境变量; exec_prefix
@code{exec_prefix} 是由向 Python 的 @code{configure} 脚本传入的对应形参所定义，而 @emph{version} 则为 @code{'%d.%d' % sys.version_info[:2]}。在 Windows 上，头文件安装于 @code{@emph{prefix}/include}，其中 
@geindex prefix
@geindex 环境变量; prefix
@code{prefix} 是向安装程序指定的安装目录。

要包含头文件，请将两个目录（如果不同）都放到你所用编译器的包含搜索路径中。请 @emph{不要} 将父目录放入搜索路径然后使用 @code{#include <pythonX.Y/Python.h>}；这将使得多平台编译不可用，因为 
@geindex prefix
@geindex 环境变量; prefix
@code{prefix} 下平台无关的头文件需要包含来自 
@geindex exec_prefix
@geindex 环境变量; exec_prefix
@code{exec_prefix} 下特定平台的头文件。

C++ 用户应该注意，尽管 API 是完全使用 C 来定义的，但头文件正确地将入口点声明为 @code{extern "C"}，因此 API 在 C++ 中使用此 API 不必再做任何特殊处理。

@node 有用的宏,对象、类型和引用计数,包含文件,概述<15>
@anchor{c-api/intro useful-macros}@anchor{3df1}
@subsection 有用的宏


Python 头文件中定义了一些有用的宏。许多是在靠近它们被使用的地方定义的（例如 @ref{ea3,,Py_RETURN_NONE}）。其他更为通用的则定义在这里。这里所显示的并不是一个完整的列表。

@geindex Py_UNREACHABLE (C 宏)
@anchor{c-api/intro c Py_UNREACHABLE}@anchor{52f}
@deffn {C 宏} Py_UNREACHABLE ()

这个可以在你有一个设计上无法到达的代码路径时使用。例如，当一个 @code{switch} 语句中所有可能的值都已被 @code{case} 子句覆盖了，就可将其用在 @code{default:} 子句中。当你非常想在某个位置放一个 @code{assert(0)} 或 @code{abort()} 调用时也可以用这个。

在 release 模式下，该宏帮助编译器优化代码，并避免发出不可到达代码的警告。例如，在 GCC 的 release 模式下，该宏使用 @code{__builtin_unreachable()} 实现。

@code{Py_UNREACHABLE()} 的一个用法是调用一个不会返回，但却没有声明 @code{_Py_NO_RETURN} 的函数之后。

如果一个代码路径不太可能是正常代码，但在特殊情况下可以到达，就不能使用该宏。例如，在低内存条件下，或者一个系统调用返回超出预期范围值，诸如此类，最好将错误报告给调用者。如果无法将错误报告给调用者，可以使用 @ref{267,,Py_FatalError()} 。


3.7 新版功能.

@end deffn

@geindex Py_ABS (C 宏)
@anchor{c-api/intro c Py_ABS}@anchor{3df2}
@deffn {C 宏} Py_ABS (x)

返回 @code{x} 的绝对值。


3.3 新版功能.

@end deffn

@geindex Py_MIN (C 宏)
@anchor{c-api/intro c Py_MIN}@anchor{3df3}
@deffn {C 宏} Py_MIN (x, y)

返回 @code{x} 和 @code{y} 当中的最小值。


3.3 新版功能.

@end deffn

@geindex Py_MAX (C 宏)
@anchor{c-api/intro c Py_MAX}@anchor{3df4}
@deffn {C 宏} Py_MAX (x, y)

返回 @code{x} 和 @code{y} 当中的最大值。


3.3 新版功能.

@end deffn

@geindex Py_STRINGIFY (C 宏)
@anchor{c-api/intro c Py_STRINGIFY}@anchor{3df5}
@deffn {C 宏} Py_STRINGIFY (x)

将 @code{x} 转换为 C 字符串。例如 @code{Py_STRINGIFY(123)} 返回 @code{"123"}。


3.4 新版功能.

@end deffn

@geindex Py_MEMBER_SIZE (C 宏)
@anchor{c-api/intro c Py_MEMBER_SIZE}@anchor{3df6}
@deffn {C 宏} Py_MEMBER_SIZE (type, member)

返回结构 (@code{type}) @code{member} 的大小，以字节表示。


3.6 新版功能.

@end deffn

@geindex Py_CHARMASK (C 宏)
@anchor{c-api/intro c Py_CHARMASK}@anchor{3df7}
@deffn {C 宏} Py_CHARMASK (c)

参数必须为 [-128, 127] 或 [0, 255] 范围内的字符或整数类型。这个宏将 @code{c} 强制转换为 @code{unsigned char} 返回。
@end deffn

@geindex Py_GETENV (C 宏)
@anchor{c-api/intro c Py_GETENV}@anchor{3df8}
@deffn {C 宏} Py_GETENV (s)

与 @code{getenv(s)} 类似，但是如果命令行上传递了 @ref{231,,-E} ，则返回 @code{NULL} （即如果设置了 @code{Py_IgnoreEnvironmentFlag} ）。
@end deffn

@geindex Py_UNUSED (C 宏)
@anchor{c-api/intro c Py_UNUSED}@anchor{3df9}
@deffn {C 宏} Py_UNUSED (arg)

用于函数定义中未使用的参数，从而消除编译器警告。例如： @code{int func(int a, int Py_UNUSED(b)) @{ return a; @}} 。


3.4 新版功能.

@end deffn

@geindex Py_DEPRECATED (C 宏)
@anchor{c-api/intro c Py_DEPRECATED}@anchor{3dfa}
@deffn {C 宏} Py_DEPRECATED (version)

弃用声明。该宏必须放置在符号名称前。

示例:

@example
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
@end example


在 3.8 版更改: 添加了 MSVC 支持。

@end deffn

@geindex PyDoc_STRVAR (C 宏)
@anchor{c-api/intro c PyDoc_STRVAR}@anchor{10a3}
@deffn {C 宏} PyDoc_STRVAR (name, str)

创建一个可以在文档字符串中使用的，名字为 @code{name} 的变量。如果不和文档字符串一起构建 Python，该值将为空。

如 
@geindex Python 提高建议; PEP 7
PEP 7@footnote{https://www.python.org/dev/peps/pep-0007} 所述，使用 @ref{10a3,,PyDoc_STRVAR} 作为文档字符串，以支持不和文档字符串一起构建 Python 的情况。

示例:

@example
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = @{
    // ...
    @{"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc@},
    // ...
@}
@end example
@end deffn

@geindex PyDoc_STR (C 宏)
@anchor{c-api/intro c PyDoc_STR}@anchor{3dfb}
@deffn {C 宏} PyDoc_STR (str)

为给定的字符串输入创建一个文档字符串，或者当文档字符串被禁用时，创建一个空字符串。

如 
@geindex Python 提高建议; PEP 7
PEP 7@footnote{https://www.python.org/dev/peps/pep-0007} 所述，使用 @ref{3dfb,,PyDoc_STR} 指定文档字符串，以支持不和文档字符串一起构建 Python 的情况。

示例:

@example
static PyMethodDef pysqlite_row_methods[] = @{
    @{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
        PyDoc_STR("Returns the keys of the row.")@},
    @{NULL, NULL@}
@};
@end example
@end deffn

@node 对象、类型和引用计数,异常<19>,有用的宏,概述<15>
@anchor{c-api/intro api-objects}@anchor{3dfc}@anchor{c-api/intro objects-types-and-reference-counts}@anchor{3dfd}
@subsection 对象、类型和引用计数


@geindex 对象; type

多数 Python/C API 有一个或多个参数，以及一个 @ref{5bd,,PyObject*} 类型的返回值。这种类型是指向任意 Python 对象的不透明数据类型的指针。所有 Python 对象类型在大多数情况下都被 Python 语言由相同的方式处理（例如，赋值，作用域规则，和参数传递），因此将它们由单个 C 类型表示才合适。几乎所有 Python 对象存放在堆中：你不能声明一个类型为 @ref{5bd,,PyObject} 的自动或静态的变量，只能声明类型为 @ref{5bd,,PyObject*} 的指针。type 对象是唯一的例外，因为它们永远不能被释放，所以它们通常是静态的 @ref{3fe,,PyTypeObject} 对象。

所有 Python 对象（甚至 Python 整数）都有一个 @emph{type} 和一个 @emph{reference count}。对象的类型确定它是什么类型的对象（例如整数、列表或用户定义函数；还有更多，如 @ref{1582,,标准类型层级结构} 中所述）。对于每个众所周知的类型，都有一个宏来检查对象是否属于该类型；例如，当（且仅当） @emph{a} 所指的对象是 Python 列表时 @code{PyList_Check(a)} 为真。

@menu
* 引用计数: 引用计数<2>. 
* 类型:: 

@end menu

@node 引用计数<2>,类型,,对象、类型和引用计数
@anchor{c-api/intro api-refcounts}@anchor{3dfe}@anchor{c-api/intro reference-counts}@anchor{3dff}
@subsubsection 引用计数


引用计数非常重要，因为现代计算机内存（通常十分）有限；它计算有多少不同的地方引用同一个对象。这样的地方可以是某个对象，或者是某个全局（或静态）C 变量，亦或是某个 C 函数的局部变量。当一个对象的引用计数变为 0，释放该对象。如果这个已释放的对象包含其它对象的引用计数，则递减这些对象的引用计数。如果这些对象的引用计数减少为零，则可以依次释放这些对象，依此类推。（这里有一个很明显的问题——对象之间相互引用；目前，解决方案是“不要那样做”。）

@geindex Py_INCREF()
@geindex Py_DECREF()

总是显式操作引用计数。通常的方法是使用宏 @ref{396,,Py_INCREF()} 来增加一个对象的引用计数，使用宏 @ref{397,,Py_DECREF()} 来减少一个对象的引用计数。宏 @ref{397,,Py_DECREF()} 必须检查引用计数是否为零，然后调用对象的释放器， 因此它比 incref 宏复杂得多。释放器是一个包含在对象类型结构中的函数指针。如果对象是复合对象类型（例如列表），则类型特定的释放器负责递减包含在对象中的其他对象的引用计数，并执行所需的终结。引用计数不会溢出，至少用与虚拟内存中不同内存位置一样多的位用于保存引用计数（即 @code{sizeof(Py_ssize_t) >= sizeof(void*)} ）。因此，引用计数递增是一个简单的操作。

没有必要为每个包含指向对象的指针的局部变量增加对象的引用计数。理论上，当变量指向对象时，对象的引用计数增加 1 ，当变量超出范围时，对象的引用计数减少 1 。但是，这两者相互抵消，所以最后引用计数没有改变。使用引用计数的唯一真正原因是只要我们的变量指向它，就可以防止对象被释放。如果知道至少有一个对该对象的其他引用存活时间至少和我们的变量一样长，则没必要临时增加引用计数。一个典型的情形是，对象作为参数从 Python 中传递给被调用的扩展模块中的 C 函数时，调用机制会保证在调用期间持有对所有参数的引用。

但是，有一个常见的陷阱是从列表中提取一个对象，并将其持有一段时间，而不增加其引用计数。某些操作可能会从列表中删除某个对象，减少其引用计数，并有可能重新分配这个对象。真正的危险是，这个看似无害的操作可能会调用任意 Python 代码——也许有一个代码路径允许控制流从 @ref{397,,Py_DECREF()} 回到用户，因此在复合对象上的操作都存在潜在的风险。

一个安全的方式是始终使用泛型操作（名称以 @code{PyObject_} ， @code{PyNumber_} ， @code{PySequence_} 或 @code{PyMapping_} 开头的函数）。这些操作总是增加它们返回的对象的引用计数。这让调用者有责任在获得结果后调用 @ref{397,,Py_DECREF()} 。习惯这种方式很简单。

@menu
* 引用计数细节:: 

@end menu

@node 引用计数细节,,,引用计数<2>
@anchor{c-api/intro api-refcountdetails}@anchor{3e00}@anchor{c-api/intro reference-count-details}@anchor{3e01}
@subsubsection 引用计数细节


The reference count behavior of functions in the Python/C API is best  explained
in terms of @emph{ownership of references}.  Ownership pertains to references, never
to objects (objects are not owned: they are always shared).  "Owning a
reference" means being responsible for calling Py_DECREF on it when the
reference is no longer needed.  Ownership can also be transferred, meaning that
the code that receives ownership of the reference then becomes responsible for
eventually decref'ing it by calling @ref{397,,Py_DECREF()} or @ref{399,,Py_XDECREF()}
when it's no longer needed---or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a @emph{new} reference.  When no ownership is transferred,
the caller is said to @emph{borrow} the reference. Nothing needs to be done for a
borrowed reference.

相反地，当调用方函数传入一个对象的引用时，存在两种可能：该函数 @emph{窃取} 了一个对象的引用，或是没有窃取。 @emph{窃取引用} 意味着当你向一个函数传入引用时，该函数会假定它拥有该引用，而你将不再对它负有责任。

@geindex PyList_SetItem()
@geindex PyTuple_SetItem()

很少有函数会窃取引用；两个重要的例外是 @ref{3d79,,PyList_SetItem()} 和 @ref{3d78,,PyTuple_SetItem()}，它们会窃取对条目的引用（但不是条目所在的元组或列表！）。 这些函数被设计为会窃取引用是因为在使用新创建的对象来填充元组或列表时有一个通常的惯例；例如，创建元组 @code{(1, 2, "three")} 的代码看起来可以是这样的（暂时不要管错误处理；下面会显示更好的代码编写方式）:

@example
PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
@end example

在这里，@ref{3d5a,,PyLong_FromLong()} 返回了一个新的引用并且它立即被 @ref{3d78,,PyTuple_SetItem()} 所窃取。 当你想要继续使用一个对象而对它的引用将被窃取时，请在调用窃取引用的函数之前使用 @ref{396,,Py_INCREF()} 来抓取另一个引用。

顺便提一下，@ref{3d78,,PyTuple_SetItem()} 是设置元组条目的 @emph{唯一} 方式；@ref{11cd,,PySequence_SetItem()} 和 @ref{3e02,,PyObject_SetItem()} 会拒绝这样做因为元组是不可变数据类型。 你应当只对你自己创建的元组使用 @ref{3d78,,PyTuple_SetItem()}。

等价于填充一个列表的代码可以使用 @ref{3e03,,PyList_New()} 和 @ref{3d79,,PyList_SetItem()} 来编写。

然而，在实践中，你很少会使用这些创建和填充元组或列表的方式。 有一个通用的函数 @ref{3f9,,Py_BuildValue()} 可以根据 C 值来创建大多数常用对象，由一个 @emph{格式字符串} 来指明。 例如，上面的两个代码块可以用下面的代码来代替（还会负责错误检测）:

@example
PyObject *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");
list = Py_BuildValue("[iis]", 1, 2, "three");
@end example

使用 @ref{3e02,,PyObject_SetItem()} 等来处理那些你只是借入引用的条目是更为常见的，例如传给你正在编写的函数的参数。 在这种情况下，他们对于引用计数的行为会更为理智，因为你不需要递增引用计数以便你可以将引用计数转出去（“让它被窃取”）。 例如，这个函数将一个列表（实例上是任何可变序列）中的所有项设置为一个给定的条目:

@example
int
set_all(PyObject *target, PyObject *item)
@{
    Py_ssize_t i, n;

    n = PyObject_Length(target);
    if (n < 0)
        return -1;
    for (i = 0; i < n; i++) @{
        PyObject *index = PyLong_FromSsize_t(i);
        if (!index)
            return -1;
        if (PyObject_SetItem(target, index, item) < 0) @{
            Py_DECREF(index);
            return -1;
        @}
        Py_DECREF(index);
    @}
    return 0;
@}
@end example

@geindex set_all()

对于函数返回值的情况略有不同。 虽然向大多数函数传递一个引用不会改变你对该引用的所有权责任，但许多返回一个引用的函数会给你该引用的所有权。 原因很简单：在许多情况下，返回的对象是临时创建的，而你得到的引用是对该对象的唯一引用。 因此，返回对象引用的通用函数，如 @ref{3e04,,PyObject_GetItem()} 和 @ref{11cc,,PySequence_GetItem()}，将总是返回一个新的引用（调用方将成为该引用的所有者）。

一个需要了解的重点在于你是否拥有一个由函数返回的引用只取决于你所调用的函数 --- @emph{附带物} (作为参数传给函数的对象的类型) @emph{不会带来额外影响！} 因此，如果你使用 @ref{3d74,,PyList_GetItem()} 从一个列表提取条目，你并不会拥有其引用 --- 但是如果你使用 @ref{11cc,,PySequence_GetItem()} (它恰好接受完全相同的参数) 从同一个列表获取同样的条目，你就会拥有一个对所返回对象的引用。

@geindex PyList_GetItem()
@geindex PySequence_GetItem()

下面是说明你要如何编写一个函数来计算一个整数列表中条目的示例；一个是使用 @ref{3d74,,PyList_GetItem()}，而另一个是使用 @ref{11cc,,PySequence_GetItem()}。

@example
long
sum_list(PyObject *list)
@{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;

    n = PyList_Size(list);
    if (n < 0)
        return -1; /* Not a list */
    for (i = 0; i < n; i++) @{
        item = PyList_GetItem(list, i); /* Can't fail */
        if (!PyLong_Check(item)) continue; /* Skip non-integers */
        value = PyLong_AsLong(item);
        if (value == -1 && PyErr_Occurred())
            /* Integer too big to fit in a C long, bail out */
            return -1;
        total += value;
    @}
    return total;
@}
@end example

@geindex sum_list()

@example
long
sum_sequence(PyObject *sequence)
@{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;
    n = PySequence_Length(sequence);
    if (n < 0)
        return -1; /* Has no length */
    for (i = 0; i < n; i++) @{
        item = PySequence_GetItem(sequence, i);
        if (item == NULL)
            return -1; /* Not a sequence, or other failure */
        if (PyLong_Check(item)) @{
            value = PyLong_AsLong(item);
            Py_DECREF(item);
            if (value == -1 && PyErr_Occurred())
                /* Integer too big to fit in a C long, bail out */
                return -1;
            total += value;
        @}
        else @{
            Py_DECREF(item); /* Discard reference ownership */
        @}
    @}
    return total;
@}
@end example

@geindex sum_sequence()

@node 类型,,引用计数<2>,对象、类型和引用计数
@anchor{c-api/intro api-types}@anchor{3e05}@anchor{c-api/intro types}@anchor{3e06}
@subsubsection 类型


在 Python/C API 中扮演重要角色的其他数据类型很少；大多为简单 C 类型如 @code{int},  @code{long}, @code{double} 和 @code{char*}。 有一些结构类型被用来描述用于列出模块导出的函数或者某个新对象类型的静态表，还有一个结构类型被用来描述复数的值。 这些结构类型将与使用它们的函数一起讨论。

@geindex Py_ssize_t (C 类型)
@anchor{c-api/intro c Py_ssize_t}@anchor{391}
@deffn {C 类型} Py_ssize_t

一个使得 @code{sizeof(Py_ssize_t) == sizeof(size_t)} 的有符号整数类型。 C99 没有直接定义这样的东西（size_t 是一个无符号整数类型）。 请参阅 
@geindex Python 提高建议; PEP 353
PEP 353@footnote{https://www.python.org/dev/peps/pep-0353} 了解详情。 @code{PY_SSIZE_T_MAX} 是 @ref{391,,Py_ssize_t} 类型的最大正数值。
@end deffn

@node 异常<19>,嵌入Python<2>,对象、类型和引用计数,概述<15>
@anchor{c-api/intro api-exceptions}@anchor{3e07}@anchor{c-api/intro exceptions}@anchor{3e08}
@subsection 异常


Python程序员只需要处理特定需要处理的错误异常；未处理的异常会自动传递给调用者，然后传递给调用者的调用者，依此类推，直到他们到达顶级解释器，在那里将它们报告给用户并伴随堆栈回溯。

@geindex PyErr_Occurred()

然而，对于 C 程序员来说，错误检查必须总是显式进行的。 Python/C API 中的所有函数都可以引发异常，除非在函数的文档中另外显式声明。 一般来说，当一个函数遇到错误时，它会设置一个异常，丢弃它所拥有的任何对象引用，并返回一个错误标示。 如果没有说明例外的文档，这个标示将为 @code{NULL} 或 @code{-1}，具体取决于函数的返回类型。 有少量函数会返回一个布尔真/假结果值，其中假值表示错误。 有极少的函数没有显式的错误标示或是具有不明确的返回值，并需要用 @ref{3d58,,PyErr_Occurred()} 来进行显式的检测。 这些异常总是会被明确地记入文档中。

@geindex PyErr_SetString()
@geindex PyErr_Clear()

异常状态是在各个线程的存储中维护的（这相当于在一个无线程的应用中使用全局存储）。 一个线程可以处在两种状态之一：异常已经发生，或者没有发生。 函数 @ref{3d58,,PyErr_Occurred()} 可以被用来检查此状态：当异常发生时它将返回一个借入的异常类型对象的引用，在其他情况下则返回 @code{NULL}。 有多个函数可以设置异常状态: @ref{3d55,,PyErr_SetString()} 是最常见的（尽管不是最通用的）设置异常状态的函数，而 @ref{a55,,PyErr_Clear()} 可以清除异常状态。

完整的异常状态由三个对象组成  (它为都可以为 @code{NULL}): 异常类型、相应的异常值，以及回溯信息。 这些对象的含义与 Python 中 @code{sys.exc_info()} 的结果相同；然而，它们并不是一样的：Python 对象代表由 Python  @ref{e3f,,try} ... @ref{c19,,except} 语句所处理的最后一个异常，而 C 层级的异常状态只在异常被传入到 C 函数或在它们之间传递时存在直至其到达 Python 字节码解释器的主事件循环，该事件循环会负责将其转移至 @code{sys.exc_info()} 等处。

@geindex exc_info() (in module sys)

请注意自 Python 1.5 开始，从 Python 代码访问异常状态的首选的、线程安全的方式是调用函数 @ref{d2f,,sys.exc_info()}，它将返回 Python 代码的分线程异常状态。 此外，这两种访问异常状态的方式的语义都发生了变化因而捕获到异常的函数将保存并恢复其线程的异常状态以保留其调用方的异常状态。 这将防止异常处理代码中由一个看起来很无辜的函数覆盖了正在处理的异常所造成的常见错误；它还减少了在回溯由栈帧所引用的对象的往往不被需要的生命其延长。

作为一般的原则，一个调用另一个函数来执行某些任务的函数应当检查被调用的函数是否引发了异常，并在引发异常时将异常状态传递给其调用方。 它应当丢弃它所拥有的任何对象引用，并返回一个错误标示，但它 @emph{不应} 设置另一个异常 --- 那会覆盖刚引发的异常，并丢失有关错误确切原因的重要信息。

@geindex sum_sequence()

一个检测异常并传递它们的简单例子在上面的 @code{sum_sequence()} 示例中进行了演示。 这个例子恰好在检测到错误时不需要清理所拥有的任何引用。 下面的示例函数演示了一些错误清理操作。 首先，为了向你提示 Python 的优势，我们展示了等效的 Python 代码:

@example
def incr_item(dict, key):
    try:
        item = dict[key]
    except KeyError:
        item = 0
    dict[key] = item + 1
@end example

@geindex incr_item()

下面是对应的闪耀荣光的 C 代码：

@example
int
incr_item(PyObject *dict, PyObject *key)
@{
    /* Objects all initialized to NULL for Py_XDECREF */
    PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
    int rv = -1; /* Return value initialized to -1 (failure) */

    item = PyObject_GetItem(dict, key);
    if (item == NULL) @{
        /* Handle KeyError only: */
        if (!PyErr_ExceptionMatches(PyExc_KeyError))
            goto error;

        /* Clear the error and use zero: */
        PyErr_Clear();
        item = PyLong_FromLong(0L);
        if (item == NULL)
            goto error;
    @}
    const_one = PyLong_FromLong(1L);
    if (const_one == NULL)
        goto error;

    incremented_item = PyNumber_Add(item, const_one);
    if (incremented_item == NULL)
        goto error;

    if (PyObject_SetItem(dict, key, incremented_item) < 0)
        goto error;
    rv = 0; /* Success */
    /* Continue with cleanup code */

 error:
    /* Cleanup code, shared by success and failure path */

    /* Use Py_XDECREF() to ignore NULL references */
    Py_XDECREF(item);
    Py_XDECREF(const_one);
    Py_XDECREF(incremented_item);

    return rv; /* -1 for error, 0 for success */
@}
@end example

@geindex incr_item()

@geindex PyErr_ExceptionMatches()
@geindex PyErr_Clear()
@geindex Py_XDECREF()

这个例子代表了 C 语言中 @code{goto} 语句一种受到认可的用法！ 它说明了如何使用 @ref{3e09,,PyErr_ExceptionMatches()} 和 @ref{a55,,PyErr_Clear()} 来处理特定的异常，以及如何使用 @ref{399,,Py_XDECREF()} 来处理可能为 @code{NULL} 的自有引用（注意名称中的 @code{'X'}；@ref{397,,Py_DECREF()} 在遇到 @code{NULL} 引用时将会崩溃）。 重要的一点在于用来保存自有引用的变量要被初始化为 @code{NULL} 才能发挥作用；类似地，建议的返回值也要被初始化为 @code{-1} (失败) 并且只有在最终执行的调用成功后才会被设置为成功。

@node 嵌入Python<2>,调试构建,异常<19>,概述<15>
@anchor{c-api/intro api-embedding}@anchor{3e0a}@anchor{c-api/intro embedding-python}@anchor{3e0b}
@subsection 嵌入Python


只有 Python 解释器的嵌入方（相对于扩展编写者而言）才需要担心的一项重要任务是它的初始化，可能还有它的最终化。 解释器的大多数功能只有在解释器被初始化之后才能被使用。

@geindex Py_Initialize()
@geindex 模块; builtins
@geindex 模块; __main__
@geindex 模块; sys
@geindex module; search; path
@geindex path (in module sys)

基本的初始化函数是 @ref{210,,Py_Initialize()}。 此函数将初始化已加载模块表，并创建基本模块 @ref{12,,builtins}, @ref{1,,__main__} 和 @ref{fd,,sys}。 它还将初始化模块搜索路径 (@code{sys.path})。

@geindex PySys_SetArgvEx()

@ref{210,,Py_Initialize()} 不会设置 "脚本参数列表"  (@code{sys.argv})。 如果随后将要执行的 Python 代码需要此变量，则必须在调用 @ref{210,,Py_Initialize()} 之后通过调用  @code{PySys_SetArgvEx(argc, argv, updatepath)} 来显式地设置它。

在大多数系统上（特别是 Unix 和 Windows，虽然在细节上有所不同），@ref{210,,Py_Initialize()} 将根据对标准 Python 解释器可执行文件的位置的最佳猜测来计算模块搜索路径，并设定 Python 库可在相对于 Python 解释器可执行文件的固定位置上找到。 特别地，它将相对于在 shell 命令搜索路径 (环境变量 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH}) 上找到的名为 @code{python} 的可执行文件所在父目录中查找名为 @code{lib/python@emph{X.Y}} 的目录。

举例来说，如果 Python 可执行文件位于 @code{/usr/local/bin/python}，它将假定库位于 @code{/usr/local/lib/python@emph{X.Y}}。 （实际上，这个特定路径还将成为“回退”位置，会在当无法在 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 中找到名为 @code{python} 的可执行文件时被使用。） 用户可以通过设置环境变量 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME}，或通过设置 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 在标准路径之前插入额外的目录来覆盖此行为。

@geindex Py_SetProgramName()
@geindex Py_GetPath()
@geindex Py_GetPrefix()
@geindex Py_GetExecPrefix()
@geindex Py_GetProgramFullPath()

嵌入的应用程序可以通过在调用 @ref{210,,Py_Initialize()} @emph{之前} 调用 @code{Py_SetProgramName(file)} 来改变搜索次序。 请注意 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} 仍然会覆盖此设置并且 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 仍然会被插入到标准路径之前。 需要完全控制权的应用程序必须提供它自己的 @ref{3e0c,,Py_GetPath()}, @ref{3e0d,,Py_GetPrefix()}, @ref{3e0e,,Py_GetExecPrefix()} 和 @ref{3a6,,Py_GetProgramFullPath()} 实现（这些函数均在 @code{Modules/getpath.c} 中定义）。

@geindex Py_IsInitialized()

有时，还需要对 Python 进行“反初始化”。 例如，应用程序可能想要重新启动 (再次调用 @ref{210,,Py_Initialize()}) 或者应用程序对 Python 的使用已经完成并想要释放 Python 所分配的内存。 这可以通过调用 @ref{6ca,,Py_FinalizeEx()} 来实现。 如果当前 Python 处于已初始化状态则 @ref{3e0f,,Py_IsInitialized()} 函数将返回真值。 有关这些函数的更多信息将在之后的章节中给出。 请注意 @ref{6ca,,Py_FinalizeEx()} @emph{不会} 释放所有由 Python 解释器所分配的内存，例如由扩展模块所分配的内存目前是不会被释放的。

@node 调试构建,,嵌入Python<2>,概述<15>
@anchor{c-api/intro api-debugging}@anchor{3e10}@anchor{c-api/intro debugging-builds}@anchor{3e11}
@subsection 调试构建


Python 可以附带某些宏来编译以启用对解释器和扩展模块的额外检查。 这些检查会给运行时增加大量额外开销因此它们默认未被启用。

A full list of the various types of debugging builds is in the file
@code{Misc/SpecialBuilds.txt} in the Python source distribution. Builds are
available that support tracing of reference counts, debugging the memory
allocator, or low-level profiling of the main interpreter loop.  Only the most
frequently-used builds will be described in the remainder of this section.

Compiling the interpreter with the @code{Py_DEBUG} macro defined produces
what is generally meant by "a debug build" of Python. @code{Py_DEBUG} is
enabled in the Unix build by adding @code{--with-pydebug} to the
@code{./configure} command.  It is also implied by the presence of the
not-Python-specific @code{_DEBUG} macro.  When @code{Py_DEBUG} is enabled
in the Unix build, compiler optimization is disabled.

除了前面描述的引用计数调试之外，还执行以下额外检查：


@itemize *

@item 
额外检查将添加到对象分配器。

@item 
额外的检查将添加到解析器和编译器中。

@item 
检查从宽类型向窄类型的向下强转是否损失了信息。

@item 
许多断言被添加到字典和集合实现中。另外，集合对象需要 @code{test_c_api()} 方法。

@item 
输入参数的完整性检查被添加到框架创建中。

@item 
使用已知的无效模式初始化整型的存储，以捕获对未初始化数字的引用。

@item 
添加底层跟踪和额外的异常检查到虚拟机的运行时中。

@item 
添加额外的检查到 arena 内存实现。

@item 
添加额外调试到线程模块。
@end itemize

这里可能没有提到的额外的检查。

Defining @code{Py_TRACE_REFS} enables reference tracing.  When defined, a
circular doubly linked list of active objects is maintained by adding two extra
fields to every @ref{5bd,,PyObject}.  Total allocations are tracked as well.  Upon
exit, all existing references are printed.  (In interactive mode this happens
after every statement run by the interpreter.)  Implied by @code{Py_DEBUG}.

有关更多详细信息，请参阅Python源代码中的 @code{Misc/SpecialBuilds.txt} 。

@node 稳定的应用程序二进制接口,极高层级,概述<15>,Python/C API 参考手册
@anchor{c-api/stable doc}@anchor{3e12}@anchor{c-api/stable stable}@anchor{3e13}@anchor{c-api/stable stable-application-binary-interface}@anchor{3e14}
@section 稳定的应用程序二进制接口


传统上，Python的C API将随每个版本而变化。大多数更改都与源代码兼容，通常只添加API，而不是更改现有API或删除API（尽管某些接口会首先弃用然后再删除）。

不幸的是，API兼容性没有扩展到二进制兼容性（ABI）。原因主要是结构定义的演变，在这里添加新字段或更改字段类型可能不会破坏API，但可能会破坏ABI。因此，每个Python版本都需要重新编译扩展模块（即使在未使用任何受影响的接口的情况下，Unix上也可能会出现异常）。此外，在Windows上，扩展模块与特定的pythonXY.dll链接，需要重新编译才能与新的pythonXY.dll链接。

从Python3.2起，已经声明了一个API的子集，以确保稳定的ABI。如果使用此API（也被称为“受限API”）的扩展模块需要定义`@w{`}Py_LIMITED_API`@w{`}。许多解释器细节将从扩展模块中隐藏;  反过来，在任何3.x版本（x>=2）上构建的模块都不需要重新编译

在某些情况下，需要添加新函数来扩展稳定版 ABI。希望使用这些新 API 的扩展模块需要将 @code{Py_LIMITED_API} 设置为他们想要支持的最低 Python 版本的 @code{PY_VERSION_HEX} 值（例如： Python 3.3 为 @code{0x03030000}）（参见 @ref{36bf,,API 和 ABI 版本管理}）。此类模块将适用于所有后续 Python版本，但无法在旧版本上加载（因为缺少符号）。

从Python 3.2开始，受限API可用的函数集记录在 
@geindex Python 提高建议; PEP 384
PEP 384@footnote{https://www.python.org/dev/peps/pep-0384} 。在C API文档中，不属于受限API的API元素标记为 “不属于受限API” 。

@node 极高层级,引用计数<3>,稳定的应用程序二进制接口,Python/C API 参考手册
@anchor{c-api/veryhigh doc}@anchor{3e15}@anchor{c-api/veryhigh the-very-high-level-layer}@anchor{3e16}@anchor{c-api/veryhigh veryhigh}@anchor{3e17}
@section 极高层级


本章节的函数将允许你执行在文件或缓冲区中提供的 Python 源代码，但它们将不允许你在更细节化的方式与解释器进行交互。

这些函数中有几个接受特定的前缀语法符号作为形参。 可用的前缀符号有 @code{Py_eval_input}, @code{Py_file_input} 以及 @code{Py_single_input}。 这些符号会在接受它们作为形参的函数文档中加以说明。

还要注意这些函数中有几个可以接受 @code{FILE*} 形参。 有一个需要小心处理的特别问题是针对不同 C 库的 @code{FILE} 结构体可能是不相同而且不兼容的。 （至少是）在 Windows 中，动态链接的扩展有可能会使用不同的库，所以应当特别注意只有在确定这些函数是由 Python 运行时所使用的相同的库创建的情况下才将 @code{FILE*} 形参传给它们。

@geindex Py_Main (C 函数)
@anchor{c-api/veryhigh c Py_Main}@anchor{5ba}
@deffn {C 函数} int Py_Main (int@w{ }argc, wchar_t@w{ }**argv)

针对标准解释器的主程序。 嵌入了 Python 的程序将可使用此程序。 所提供的 @emph{argc} 和 @emph{argv} 形参应当与传给 C 程序的 @code{main()} 函数的形参相同（将根据用户的语言区域转换为）。 一个重要的注意事项是参数列表可能会被修改（但参数列表中字符串所指向的内容不会被修改）。 如果解释器正常退出（即未引发异常）则返回值将为 @code{0}，如果解释器因引发异常而退出则返回 @code{1}，或者如果形参列表不能表示有效的 Python 命令行则返回 @code{2}。

请注意如果引发了一个在其他场合下未处理的 @ref{6fd,,SystemExit}，此函数将不会返回 @code{1}，而是退出进程，只要 @code{Py_InspectFlag} 还未被设置。
@end deffn

@geindex Py_BytesMain (C 函数)
@anchor{c-api/veryhigh c Py_BytesMain}@anchor{2b6}
@deffn {C 函数} int Py_BytesMain (int@w{ }argc, char@w{ }**argv)

类似于 @ref{5ba,,Py_Main()} 但 @emph{argv} 是一个包含字节串的数组。


3.8 新版功能.

@end deffn

@geindex PyRun_AnyFile (C 函数)
@anchor{c-api/veryhigh c PyRun_AnyFile}@anchor{3e18}
@deffn {C 函数} int PyRun_AnyFile (FILE@w{ }*fp, const char@w{ }*filename)

这是针对下面 @ref{3e19,,PyRun_AnyFileExFlags()} 的简化版接口，将 @emph{closeit} 设为 @code{0} 而将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_AnyFileFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_AnyFileFlags}@anchor{3e1a}
@deffn {C 函数} int PyRun_AnyFileFlags (FILE@w{ }*fp, const char@w{ }*filename, PyCompilerFlags@w{ }*flags)

这是针对下面 @ref{3e19,,PyRun_AnyFileExFlags()} 的简化版接口，将 @emph{closeit} 参数设为 @code{0}。
@end deffn

@geindex PyRun_AnyFileEx (C 函数)
@anchor{c-api/veryhigh c PyRun_AnyFileEx}@anchor{3e1b}
@deffn {C 函数} int PyRun_AnyFileEx (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }closeit)

这是针对下面 @ref{3e19,,PyRun_AnyFileExFlags()} 的简化版接口，将 @emph{flags} 参数设为 @code{NULL}。
@end deffn

@geindex PyRun_AnyFileExFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_AnyFileExFlags}@anchor{3e19}
@deffn {C 函数} int PyRun_AnyFileExFlags (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }closeit, PyCompilerFlags@w{ }*flags)

如果 @emph{fp} 指向一个关联到交互设备（控制台或终端输入或 Unix 伪终端）的文件，则返回 @ref{3e1c,,PyRun_InteractiveLoop()} 的值，否则返回 @ref{3dda,,PyRun_SimpleFile()} 的结果。 @emph{filename} 会使用文件系统的编码格式 (@ref{5f8,,sys.getfilesystemencoding()}) 来解码。 如果 @emph{filename} 为 @code{NULL}，此函数会使用 @code{"???"} 作为文件名。 如果 @emph{closeit} 为真值，文件会在 @code{PyRun_SimpleFileExFlags()} 返回之前被关闭。
@end deffn

@geindex PyRun_SimpleString (C 函数)
@anchor{c-api/veryhigh c PyRun_SimpleString}@anchor{3dd9}
@deffn {C 函数} int PyRun_SimpleString (const char@w{ }*command)

这是针对下面 @ref{3e1d,,PyRun_SimpleStringFlags()} 的简化版接口，将 @ref{3f7,,PyCompilerFlags}* 参数设为 @code{NULL}。
@end deffn

@geindex PyRun_SimpleStringFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_SimpleStringFlags}@anchor{3e1d}
@deffn {C 函数} int PyRun_SimpleStringFlags (const char@w{ }*command, PyCompilerFlags@w{ }*flags)

根据 @emph{flags} 参数，在 @ref{1,,__main__} 模块中执行 Python 源代码。 如果 @ref{1,,__main__} 尚不存在，它将被创建。 成功时返回 @code{0}，如果引发异常则返回 @code{-1}。 如果发生错误，则将无法获得异常信息。 对于 @emph{flags} 的含义，请参阅下文。

请注意如果引发了一个在其他场合下未处理的 @ref{6fd,,SystemExit}，此函数将不会返回 @code{-1}，而是退出进程，只要 @code{Py_InspectFlag} 还未被设置。
@end deffn

@geindex PyRun_SimpleFile (C 函数)
@anchor{c-api/veryhigh c PyRun_SimpleFile}@anchor{3dda}
@deffn {C 函数} int PyRun_SimpleFile (FILE@w{ }*fp, const char@w{ }*filename)

这是针对下面 @ref{1012,,PyRun_SimpleFileExFlags()} 的简化版接口，将 @emph{closeit} 设为 @code{0} 而将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_SimpleFileEx (C 函数)
@anchor{c-api/veryhigh c PyRun_SimpleFileEx}@anchor{3e1e}
@deffn {C 函数} int PyRun_SimpleFileEx (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }closeit)

这是针对下面 @ref{1012,,PyRun_SimpleFileExFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_SimpleFileExFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_SimpleFileExFlags}@anchor{1012}
@deffn {C 函数} int PyRun_SimpleFileExFlags (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }closeit, PyCompilerFlags@w{ }*flags)

Similar to @ref{3e1d,,PyRun_SimpleStringFlags()}, but the Python source code is read
from @emph{fp} instead of an in-memory string. @emph{filename} should be the name of
the file, it is decoded from the filesystem encoding
(@ref{5f8,,sys.getfilesystemencoding()}).  If @emph{closeit} is true, the file is
closed before PyRun_SimpleFileExFlags returns.

@cartouche
@quotation 注解 
在 Windows 上，@emph{fp} 应当以二进制模式打开 (即 @code{fopen(filename, "rb")})。 否则，Python 可能无法正确地处理使用 LF 行结束符的脚本文件。
@end quotation
@end cartouche
@end deffn

@geindex PyRun_InteractiveOne (C 函数)
@anchor{c-api/veryhigh c PyRun_InteractiveOne}@anchor{3e1f}
@deffn {C 函数} int PyRun_InteractiveOne (FILE@w{ }*fp, const char@w{ }*filename)

这是针对下面 @ref{3e20,,PyRun_InteractiveOneFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_InteractiveOneFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_InteractiveOneFlags}@anchor{3e20}
@deffn {C 函数} int PyRun_InteractiveOneFlags (FILE@w{ }*fp, const char@w{ }*filename, PyCompilerFlags@w{ }*flags)

Read and execute a single statement from a file associated with an
interactive device according to the @emph{flags} argument.  The user will be
prompted using @code{sys.ps1} and @code{sys.ps2}.  @emph{filename} is decoded from the
filesystem encoding (@ref{5f8,,sys.getfilesystemencoding()}).

当输入被成功执行时返回 @code{0}，如果引发异常则返回 @code{-1}，或者如果存在解析错误则返回来自作为 Python 的组成部分发布的 @code{errcode.h} 包括文件的错误代码。 （请注意 @code{errcode.h} 并未被 @code{Python.h} 所包括，因此如果需要则必须专门地包括。）
@end deffn

@geindex PyRun_InteractiveLoop (C 函数)
@anchor{c-api/veryhigh c PyRun_InteractiveLoop}@anchor{3e1c}
@deffn {C 函数} int PyRun_InteractiveLoop (FILE@w{ }*fp, const char@w{ }*filename)

这是针对下面 @ref{3e21,,PyRun_InteractiveLoopFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_InteractiveLoopFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_InteractiveLoopFlags}@anchor{3e21}
@deffn {C 函数} int PyRun_InteractiveLoopFlags (FILE@w{ }*fp, const char@w{ }*filename, PyCompilerFlags@w{ }*flags)

Read and execute statements from a file associated with an interactive device
until EOF is reached.  The user will be prompted using @code{sys.ps1} and
@code{sys.ps2}.  @emph{filename} is decoded from the filesystem encoding
(@ref{5f8,,sys.getfilesystemencoding()}).  Returns @code{0} at EOF or a negative
number upon failure.
@end deffn

@geindex PyOS_InputHook (C 变量)
@anchor{c-api/veryhigh c PyOS_InputHook}@anchor{3e22}
@deffn {C 变量} int (*PyOS_InputHook) (void)

可以被设为指向一个原型为 @code{int func(void)} 的函数。 该函数将在Python 的解释器提示符即将空闲并等待用户从终端输入时被调用。 返回值会被忽略。 重载这个钩子可被用来将解释器的提示符集成到其他事件循环中，就像 Python 码中 @code{Modules/_tkinter.c} 所做的那样。
@end deffn

@geindex PyOS_ReadlineFunctionPointer (C 变量)
@anchor{c-api/veryhigh c PyOS_ReadlineFunctionPointer}@anchor{a56}
@deffn {C 变量} char* (*PyOS_ReadlineFunctionPointer) (FILE@w{ }*, FILE@w{ }*, const char@w{ }*)

可以被设为指向一个原型为 @code{char *func(FILE *stdin, FILE *stdout, char *prompt)} 的函数，重载被用来读取解释器提示符的一行输入的默认函数。 该函数被预期为如果字符串 @emph{prompt} 不为 @code{NULL} 就输出它，然后从所提供的标准输入文件读取一行输入，并返回结果字符串。 例如，@ref{de,,readline} 模块将这个钩子设置为提供行编辑和 tab 键补全等功能。

结果必须是一个由 @ref{a57,,PyMem_RawMalloc()} 或 @ref{a58,,PyMem_RawRealloc()} 分配的字符串，或者如果发生错误则为 @code{NULL}。


在 3.4 版更改: 结果必须由 @ref{a57,,PyMem_RawMalloc()} 或 @ref{a58,,PyMem_RawRealloc()} 分配，而不是由 @ref{607,,PyMem_Malloc()} 或 @ref{a59,,PyMem_Realloc()} 分配。

@end deffn

@geindex PyParser_SimpleParseString (C 函数)
@anchor{c-api/veryhigh c PyParser_SimpleParseString}@anchor{3e23}
@deffn {C 函数} struct _node* PyParser_SimpleParseString (const char@w{ }*str, int@w{ }start)

This is a simplified interface to
@ref{201,,PyParser_SimpleParseStringFlagsFilename()} below, leaving  @emph{filename} set
to @code{NULL} and @emph{flags} set to @code{0}.


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex PyParser_SimpleParseStringFlags (C 函数)
@anchor{c-api/veryhigh c PyParser_SimpleParseStringFlags}@anchor{200}
@deffn {C 函数} struct _node* PyParser_SimpleParseStringFlags (const char@w{ }*str, int@w{ }start, int@w{ }flags)

This is a simplified interface to
@ref{201,,PyParser_SimpleParseStringFlagsFilename()} below, leaving  @emph{filename} set
to @code{NULL}.


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex PyParser_SimpleParseStringFlagsFilename (C 函数)
@anchor{c-api/veryhigh c PyParser_SimpleParseStringFlagsFilename}@anchor{201}
@deffn {C 函数} struct _node* PyParser_SimpleParseStringFlagsFilename (const char@w{ }*str, const char@w{ }*filename, int@w{ }start, int@w{ }flags)

Parse Python source code from @emph{str} using the start token @emph{start} according to
the @emph{flags} argument.  The result can be used to create a code object which can
be evaluated efficiently. This is useful if a code fragment must be evaluated
many times. @emph{filename} is decoded from the filesystem encoding
(@ref{5f8,,sys.getfilesystemencoding()}).


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex PyParser_SimpleParseFile (C 函数)
@anchor{c-api/veryhigh c PyParser_SimpleParseFile}@anchor{3e24}
@deffn {C 函数} struct _node* PyParser_SimpleParseFile (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start)

This is a simplified interface to @ref{202,,PyParser_SimpleParseFileFlags()} below,
leaving @emph{flags} set to @code{0}.


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex PyParser_SimpleParseFileFlags (C 函数)
@anchor{c-api/veryhigh c PyParser_SimpleParseFileFlags}@anchor{202}
@deffn {C 函数} struct _node* PyParser_SimpleParseFileFlags (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start, int@w{ }flags)

Similar to @ref{201,,PyParser_SimpleParseStringFlagsFilename()}, but the Python
source code is read from @emph{fp} instead of an in-memory string.


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn

@geindex PyRun_String (C 函数)
@anchor{c-api/veryhigh c PyRun_String}@anchor{1130}
@deffn {C 函数} PyObject* PyRun_String (const char@w{ }*str, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals)
@emph{Return value: New reference.}
这是针对下面 @ref{3e25,,PyRun_StringFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_StringFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_StringFlags}@anchor{3e25}
@deffn {C 函数} PyObject* PyRun_StringFlags (const char@w{ }*str, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals, PyCompilerFlags@w{ }*flags)
@emph{Return value: New reference.}
在由对象 @emph{globals} 和 @emph{locals} 指定的上下文中执行来自 @emph{str} 的 Python 源代码，并使用以 @emph{flags} 指定的编译器旗标。 @emph{globals} 必须是一个字典；@emph{locals} 可以是任何实现了映射协议的对象。 形参 @emph{start} 指定了应当被用来解析源代码的起始形符。

返回将代码作为 Python 对象执行的结果，或者如果引发了异常则返回 @code{NULL}。
@end deffn

@geindex PyRun_File (C 函数)
@anchor{c-api/veryhigh c PyRun_File}@anchor{3e26}
@deffn {C 函数} PyObject* PyRun_File (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals)
@emph{Return value: New reference.}
这是针对下面 @ref{3e27,,PyRun_FileExFlags()} 的简化版接口，将 @emph{closeit} 设为 @code{0} 并将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_FileEx (C 函数)
@anchor{c-api/veryhigh c PyRun_FileEx}@anchor{3e28}
@deffn {C 函数} PyObject* PyRun_FileEx (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals, int@w{ }closeit)
@emph{Return value: New reference.}
这是针对下面 @ref{3e27,,PyRun_FileExFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex PyRun_FileFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_FileFlags}@anchor{3e29}
@deffn {C 函数} PyObject* PyRun_FileFlags (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals, PyCompilerFlags@w{ }*flags)
@emph{Return value: New reference.}
这是针对下面 @ref{3e27,,PyRun_FileExFlags()} 的简化版接口，将 @emph{closeit} 设为 @code{0}。
@end deffn

@geindex PyRun_FileExFlags (C 函数)
@anchor{c-api/veryhigh c PyRun_FileExFlags}@anchor{3e27}
@deffn {C 函数} PyObject* PyRun_FileExFlags (FILE@w{ }*fp, const char@w{ }*filename, int@w{ }start, PyObject@w{ }*globals, PyObject@w{ }*locals, int@w{ }closeit, PyCompilerFlags@w{ }*flags)
@emph{Return value: New reference.}
Similar to @ref{3e25,,PyRun_StringFlags()}, but the Python source code is read from
@emph{fp} instead of an in-memory string. @emph{filename} should be the name of the file,
it is decoded from the filesystem encoding (@ref{5f8,,sys.getfilesystemencoding()}).
If @emph{closeit} is true, the file is closed before @ref{3e27,,PyRun_FileExFlags()}
returns.
@end deffn

@geindex Py_CompileString (C 函数)
@anchor{c-api/veryhigh c Py_CompileString}@anchor{3e2a}
@deffn {C 函数} PyObject* Py_CompileString (const char@w{ }*str, const char@w{ }*filename, int@w{ }start)
@emph{Return value: New reference.}
这是针对下面 @ref{3e2b,,Py_CompileStringFlags()} 的简化版接口，将 @emph{flags} 设为 @code{NULL}。
@end deffn

@geindex Py_CompileStringFlags (C 函数)
@anchor{c-api/veryhigh c Py_CompileStringFlags}@anchor{3e2b}
@deffn {C 函数} PyObject* Py_CompileStringFlags (const char@w{ }*str, const char@w{ }*filename, int@w{ }start, PyCompilerFlags@w{ }*flags)
@emph{Return value: New reference.}
这是针对下面 @ref{3e2c,,Py_CompileStringExFlags()} 的简化版接口，将 @emph{optimize} 设为 @code{-1}。
@end deffn

@geindex Py_CompileStringObject (C 函数)
@anchor{c-api/veryhigh c Py_CompileStringObject}@anchor{3e2d}
@deffn {C 函数} PyObject* Py_CompileStringObject (const char@w{ }*str, PyObject@w{ }*filename, int@w{ }start, PyCompilerFlags@w{ }*flags, int@w{ }optimize)
@emph{Return value: New reference.}
解析并编译 @emph{str} 中的 Python 源代码，返回结果代码对象。 开始形符由 @emph{start} 给出；这可被用来限制可被编译的代码并且应为 @code{Py_eval_input}, @code{Py_file_input} 或 @code{Py_single_input}。 由 @emph{filename} 指定的文件名会被用来构造代码对象并可能出现在回溯信息或 @ref{562,,SyntaxError} 异常消息中。 如果代码无法被解析或编译则此函数将返回 @code{NULL}。

整数 @emph{optimize} 指定编译器的优化级别；值 @code{-1} 将选择与 @ref{788,,-O} 选项相同的解释器优化级别。 显式级别为 @code{0} (无优化；@code{__debug__} 为真值)、@code{1} (断言被移除，@code{__debug__} 为假值) 或 @code{2} (文档字符串也被移除)。


3.4 新版功能.

@end deffn

@geindex Py_CompileStringExFlags (C 函数)
@anchor{c-api/veryhigh c Py_CompileStringExFlags}@anchor{3e2c}
@deffn {C 函数} PyObject* Py_CompileStringExFlags (const char@w{ }*str, const char@w{ }*filename, int@w{ }start, PyCompilerFlags@w{ }*flags, int@w{ }optimize)
@emph{Return value: New reference.}
Like @ref{3e2d,,Py_CompileStringObject()}, but @emph{filename} is a byte string
decoded from the filesystem encoding (@ref{5f1,,os.fsdecode()}).


3.2 新版功能.

@end deffn

@geindex PyEval_EvalCode (C 函数)
@anchor{c-api/veryhigh c PyEval_EvalCode}@anchor{3e2e}
@deffn {C 函数} PyObject* PyEval_EvalCode (PyObject@w{ }*co, PyObject@w{ }*globals, PyObject@w{ }*locals)
@emph{Return value: New reference.}
这是针对 @ref{3e2f,,PyEval_EvalCodeEx()} 的简化版接口，只附带代码对象，以及全局和局部变量。 其他参数均设为 @code{NULL}。
@end deffn

@geindex PyEval_EvalCodeEx (C 函数)
@anchor{c-api/veryhigh c PyEval_EvalCodeEx}@anchor{3e2f}
@deffn {C 函数} PyObject* PyEval_EvalCodeEx (PyObject@w{ }*co, PyObject@w{ }*globals, PyObject@w{ }*locals, PyObject *const@w{ }*args, int@w{ }argcount, PyObject *const@w{ }*kws, int@w{ }kwcount, PyObject *const@w{ }*defs, int@w{ }defcount, PyObject@w{ }*kwdefs, PyObject@w{ }*closure)
@emph{Return value: New reference.}
对一个预编译的代码对象求值，为其求值给出特定的环境。 此环境由全局变量的字典，局部变量映射对象，参数、关键字和默认值的数组，@ref{3d6,,仅限关键字} 参数的默认值的字典和单元的封闭元组构成。
@end deffn

@geindex PyFrameObject (C 类型)
@anchor{c-api/veryhigh c PyFrameObject}@anchor{a5b}
@deffn {C 类型} PyFrameObject

用于描述帧对象的 C 对象结构体。 此类型的字段可能在任何时候被改变。
@end deffn

@geindex PyEval_EvalFrame (C 函数)
@anchor{c-api/veryhigh c PyEval_EvalFrame}@anchor{3e30}
@deffn {C 函数} PyObject* PyEval_EvalFrame (PyFrameObject@w{ }*f)
@emph{Return value: New reference.}
对一个执行帧求值。 这是针对 @ref{a51,,PyEval_EvalFrameEx()} 的简化版接口，用于保持向下兼容性。
@end deffn

@geindex PyEval_EvalFrameEx (C 函数)
@anchor{c-api/veryhigh c PyEval_EvalFrameEx}@anchor{a51}
@deffn {C 函数} PyObject* PyEval_EvalFrameEx (PyFrameObject@w{ }*f, int@w{ }throwflag)
@emph{Return value: New reference.}
这是 Python 解释运行不带修饰的主函数。 与执行帧 @emph{f} 相关联的代码对象将被执行，解释字节码并根据需要执行调用。 额外的 @emph{throwflag} 形参基本可以被忽略 —— 如果为真值，则会导致立即抛出一个异常；这会被用于生成器对象的 @ref{1042,,throw()} 方法。


在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动的异常。

@end deffn

@geindex PyEval_MergeCompilerFlags (C 函数)
@anchor{c-api/veryhigh c PyEval_MergeCompilerFlags}@anchor{3e31}
@deffn {C 函数} int PyEval_MergeCompilerFlags (PyCompilerFlags@w{ }*cf)

此函数会修改当前求值帧的旗标，并在成功时返回真值，失败时返回假值。
@end deffn

@geindex Py_eval_input (C 变量)
@anchor{c-api/veryhigh c Py_eval_input}@anchor{3e32}
@deffn {C 变量} int Py_eval_input

@geindex Py_CompileString()

Python 语法中用于孤立表达式的开始符号；应当与 @ref{3e2a,,Py_CompileString()} 一起使用。
@end deffn

@geindex Py_file_input (C 变量)
@anchor{c-api/veryhigh c Py_file_input}@anchor{3e33}
@deffn {C 变量} int Py_file_input

@geindex Py_CompileString()

Python 语法中用于从文件或其他源读取语句序列的起始符号；配合 @ref{3e2a,,Py_CompileString()} 使用。 这是在编译任意长的 Python 源代码时要使用的符号。
@end deffn

@geindex Py_single_input (C 变量)
@anchor{c-api/veryhigh c Py_single_input}@anchor{3e34}
@deffn {C 变量} int Py_single_input

@geindex Py_CompileString()

Python 语法中用于单独语句的起始符号；配合 @ref{3e2a,,Py_CompileString()} 使用。 这是用于交互式解释器循环的符号。
@end deffn

@geindex PyCompilerFlags (C 类型)
@anchor{c-api/veryhigh c PyCompilerFlags}@anchor{3f7}
@deffn {C 类型} struct PyCompilerFlags

这是用来存放编译器旗标的结构体。 对于代码仅被编译的情况，它将作为 @code{int flags} 传入，而对于代码要被执行的情况，它将作为 @code{PyCompilerFlags *flags} 传入。 在这种情况下，@code{from __future__ import} 可以修改 @emph{flags}。

当 @code{PyCompilerFlags *flags} 为 @code{NULL} 时，@code{cf_flags} 将被当作等于 @code{0} 来处理，而任何 @code{from __future__ import} 所导致的修改都会被丢弃。

@geindex PyCompilerFlags.cf_flags (C 成员)
@anchor{c-api/veryhigh c PyCompilerFlags cf_flags}@anchor{3e35}
@deffn {C 成员} int cf_flags

编译器旗标。
@end deffn

@geindex PyCompilerFlags.cf_feature_version (C 成员)
@anchor{c-api/veryhigh c PyCompilerFlags cf_feature_version}@anchor{3e36}
@deffn {C 成员} int cf_feature_version

@emph{cf_feature_version} 是 Python 的小版本号。 它应当被初始化为 @code{PY_MINOR_VERSION}。

此字段默认会被忽略，当且仅当在 @emph{cf_flags} 中设置了 @code{PyCF_ONLY_AST} 旗标它才会被使用。
@end deffn


在 3.8 版更改: 增加了 @emph{cf_feature_version} 字段。

@end deffn

@geindex CO_FUTURE_DIVISION (C 变量)
@anchor{c-api/veryhigh c CO_FUTURE_DIVISION}@anchor{3e37}
@deffn {C 变量} int CO_FUTURE_DIVISION

这个标志位可在 @emph{flags} 中设置以使得除法运算符 @code{/} 被解读为 
@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238} 所规定的“真除法”。
@end deffn

@node 引用计数<3>,异常处理,极高层级,Python/C API 参考手册
@anchor{c-api/refcounting doc}@anchor{3e38}@anchor{c-api/refcounting countingrefs}@anchor{3e39}@anchor{c-api/refcounting reference-counting}@anchor{3e3a}
@section 引用计数


本节介绍的宏被用于管理 Python 对象的引用计数。

@geindex Py_INCREF (C 函数)
@anchor{c-api/refcounting c Py_INCREF}@anchor{396}
@deffn {C 函数} void Py_INCREF (PyObject@w{ }*o)

增加对象 @emph{o} 的引用计数。 对象必须不为 @code{NULL}；如果你不确定它不为 @code{NULL}，可使用 @ref{398,,Py_XINCREF()}。
@end deffn

@geindex Py_XINCREF (C 函数)
@anchor{c-api/refcounting c Py_XINCREF}@anchor{398}
@deffn {C 函数} void Py_XINCREF (PyObject@w{ }*o)

增加对象 @emph{o} 的引用计数。 对象可以为 @code{NULL}，在此情况下该宏不产生任何效果。
@end deffn

@geindex Py_DECREF (C 函数)
@anchor{c-api/refcounting c Py_DECREF}@anchor{397}
@deffn {C 函数} void Py_DECREF (PyObject@w{ }*o)

减少对象 @emph{o} 的引用计数。 对象必须不为 @code{NULL}；如果你不确定它不为 @code{NULL}，可使用 @ref{399,,Py_XDECREF()}。 如果引用计数降为零，将发起调用对象所属类型的释放函数 (它必须不为 @code{NULL})。

@cartouche
@quotation 警告 
释放函数可导致任意 Python 代码被发起调用（例如当一个带有 @ref{a0d,,__del__()} 方法的类实例被释放时就是如此）。 虽然此类代码中的异常不会被传播，但被执行的代码能够自由访问所有 Python 全局变量。 这意味着任何可通过全局变量获取的对象在  @ref{397,,Py_DECREF()} 被发起调用之前都应当处于完好状态。 例如，从一个列表中删除对象的代码应当将被删除对象的引用拷贝到一个临时变量中，更新列表数据结构，然后再为临时变量调用 @ref{397,,Py_DECREF()}。
@end quotation
@end cartouche
@end deffn

@geindex Py_XDECREF (C 函数)
@anchor{c-api/refcounting c Py_XDECREF}@anchor{399}
@deffn {C 函数} void Py_XDECREF (PyObject@w{ }*o)

减少对象 @emph{o} 的引用计数。 对象可以为 @code{NULL}，在此情况下该宏不产生任何效果；在其他情况下其效果与 @ref{397,,Py_DECREF()} 相同，并会应用同样的警告。
@end deffn

@geindex Py_CLEAR (C 函数)
@anchor{c-api/refcounting c Py_CLEAR}@anchor{3da0}
@deffn {C 函数} void Py_CLEAR (PyObject@w{ }*o)

减少对象 @emph{o} 的引用计数。 对象可以为 @code{NULL}，在此情况下该宏不产生任何效果；在其他情况下其效果与 @ref{397,,Py_DECREF()} 相同，区别在于其参数也会被设为 @code{NULL}。 针对 @ref{397,,Py_DECREF()} 的警告不适用于所传递的对象，因为该宏会细心地使用一个临时变量并在减少其引用计数之前将参数设为 @code{NULL}。

每当要减少在垃圾回收期间可能会被遍历的对象的引用计数时，使用该宏是一个好主意。
@end deffn

以下函数适用于 Python 的运行时动态嵌入: @code{Py_IncRef(PyObject *o)}, @code{Py_DecRef(PyObject *o)}。 它们分别只是 @ref{398,,Py_XINCREF()} 和 @ref{399,,Py_XDECREF()} 的简单导出函数版本。

以下函数或宏仅可在解释器核心内部使用: @code{_Py_Dealloc()}, @code{_Py_ForgetReference()}, @code{_Py_NewReference()} 以及全局变量 @code{_Py_RefTotal}。

@node 异常处理,工具<2>,引用计数<3>,Python/C API 参考手册
@anchor{c-api/exceptions doc}@anchor{3e3b}@anchor{c-api/exceptions exception-handling}@anchor{3e3c}@anchor{c-api/exceptions exceptionhandling}@anchor{36d8}
@section 异常处理


本章描述的函数将让你处理和触发 Python 异常。了解一些 Python 异常处理的基本知识是很重要的。 它的工作原理有点像 POSIX 的 @code{errno} 变量：（每个线程）有一个全局指示器显示最近发生的错误。 大多数 C API 函数不会在成功时理会它，但会在失败时设置它来指示错误的原因。 多数 C API 函数也返回一个错误指示器，如果它们应该返回一个指针，通常返回 @code{NULL}，如果返回一个整数，则返回 @code{-1} (例外: @code{PyArg_*()} 函数成功时返回 @code{1} 而失败时返回 @code{0})。

具体地说，错误指示器由三个对象指针组成：异常的类型，异常的值，和回溯对象。如果没有错误被设置，这些指针都可以是 @code{NULL} （尽管一些组合使禁止的，例如，如果异常类型是 @code{NULL} ，你不能有一个非 @code{NULL} 的回溯）。

当一个函数由于它调用的某个函数失败而必须失败时，通常不会设置错误指示器；它调用的那个函数已经设置了它。而它负责处理错误和清理异常，或在清除其拥有的所有资源后返回（如对象应用或内存分配）。如果不准备处理异常，则 @emph{不} 应该正常地继续。如果是由于一个错误返回，那么一定要向调用者表明已经设置了错误。如果错误没有得到处理或小心传播，对 Python/C API的其它调用可能不会有预期的行为，并且可能会以某种神秘的方式失败。

@cartouche
@quotation 注解 
错误指示器 @strong{不是} @ref{d2f,,sys.exc_info()} 的执行结果。前者对应尚未捕获的异常（异常还在传播），而后者在捕获异常后返回这个异常（异常已经停止传播）。
@end quotation
@end cartouche

@menu
* 打印和清理:: 
* 抛出异常:: 
* 发出警告:: 
* 查询错误指示器:: 
* 信号处理: 信号处理<2>. 
* Exception 类: Exception 类<2>. 
* 异常对象:: 
* Unicode 异常对象:: 
* 递归控制:: 
* 标准异常:: 
* 标准警告类别:: 

@end menu

@node 打印和清理,抛出异常,,异常处理
@anchor{c-api/exceptions printing-and-clearing}@anchor{3e3d}
@subsection 打印和清理


@geindex PyErr_Clear (C 函数)
@anchor{c-api/exceptions c PyErr_Clear}@anchor{a55}
@deffn {C 函数} void PyErr_Clear ()

清除错误指示器。如果没有设置错误指示器，则不会有作用。
@end deffn

@geindex PyErr_PrintEx (C 函数)
@anchor{c-api/exceptions c PyErr_PrintEx}@anchor{3e3e}
@deffn {C 函数} void PyErr_PrintEx (int@w{ }set_sys_last_vars)

将标准回溯打印到 @code{sys.stderr} 并清除错误指示器。@strong{除非} 错误是 @code{SystemExit}，这种情况下不会打印回溯进程，且会退出 Python 进程，并显示 @code{SystemExit} 实例指定的错误代码。

只有在错误指示器被设置时才需要调用这个函数，否则这会导致错误！

如果 @emph{set_sys_last_vars} 非零，则变量 @ref{d2a,,sys.last_type}，@ref{36c0,,sys.last_value} 和 @ref{35bc,,sys.last_traceback} 将分别设置为打印异常的类型，值和回溯。
@end deffn

@geindex PyErr_Print (C 函数)
@anchor{c-api/exceptions c PyErr_Print}@anchor{1079}
@deffn {C 函数} void PyErr_Print ()

@code{PyErr_PrintEx(1)} 的别名。
@end deffn

@geindex PyErr_WriteUnraisable (C 函数)
@anchor{c-api/exceptions c PyErr_WriteUnraisable}@anchor{1142}
@deffn {C 函数} void PyErr_WriteUnraisable (PyObject@w{ }*obj)

使用当前异常和 @emph{obj} 参数调用 @ref{361,,sys.unraisablehook()}。

当设置了异常，但解释器不可能实际地触发异常时，这个实用函数向 @code{sys.stderr} 打印一个警告信息。例如，当 @ref{a0d,,__del__()} 方法中发生异常时使用这个函数。

该函数使用单个参数 @emph{obj} 进行调用，该参数标识发生不可触发异常的上下文。如果可能，@emph{obj} 的报告将打印在警告消息中。

调用此函数时必须设置一个异常。
@end deffn

@node 抛出异常,发出警告,打印和清理,异常处理
@anchor{c-api/exceptions raising-exceptions}@anchor{3e3f}
@subsection 抛出异常


这些函数可帮助你设置当前线程的错误指示器。为了方便起见，一些函数将始终返回 @code{NULL} 指针，以便用于 @code{return} 语句。

@geindex PyErr_SetString (C 函数)
@anchor{c-api/exceptions c PyErr_SetString}@anchor{3d55}
@deffn {C 函数} void PyErr_SetString (PyObject@w{ }*type, const char@w{ }*message)

这是设置错误标记最常用的方式。 第一个参数指定异常类型；它通常为某个标准异常，例如 @code{PyExc_RuntimeError}。 你不需要增加它的引用计数。 第二个参数是错误消息；它是用 @code{'utf-8'} 解码的。
@end deffn

@geindex PyErr_SetObject (C 函数)
@anchor{c-api/exceptions c PyErr_SetObject}@anchor{3d57}
@deffn {C 函数} void PyErr_SetObject (PyObject@w{ }*type, PyObject@w{ }*value)

此函数类似于 @ref{3d55,,PyErr_SetString()}，但是允许你为异常的“值”指定任意一个 Python 对象。
@end deffn

@geindex PyErr_Format (C 函数)
@anchor{c-api/exceptions c PyErr_Format}@anchor{8a2}
@deffn {C 函数} PyObject* PyErr_Format (PyObject@w{ }*exception, const char@w{ }*format, ...)
@emph{Return value: Always NULL.}
这个函数设置了一个错误指示器并且返回了 @code{NULL}，@emph{exception} 应当是一个 Python 中的异常类。@emph{format} 和随后的形参会帮助格式化这个错误的信息；它们与 @ref{8c2,,PyUnicode_FromFormat()} 有着相同的含义和值。@emph{format} 是一个ASCII编码的字符串。
@end deffn

@geindex PyErr_FormatV (C 函数)
@anchor{c-api/exceptions c PyErr_FormatV}@anchor{8a1}
@deffn {C 函数} PyObject* PyErr_FormatV (PyObject@w{ }*exception, const char@w{ }*format, va_list@w{ }vargs)
@emph{Return value: Always NULL.}
和 @ref{8a2,,PyErr_Format()} 相同，但它接受一个 @code{va_list} 类型的参数而不是可变数量的参数集。


3.5 新版功能.

@end deffn

@geindex PyErr_SetNone (C 函数)
@anchor{c-api/exceptions c PyErr_SetNone}@anchor{3e40}
@deffn {C 函数} void PyErr_SetNone (PyObject@w{ }*type)

这是 @code{PyErr_SetObject(type, Py_None)} 的简写。
@end deffn

@geindex PyErr_BadArgument (C 函数)
@anchor{c-api/exceptions c PyErr_BadArgument}@anchor{3e41}
@deffn {C 函数} int PyErr_BadArgument ()

这是 @code{PyErr_SetString(PyExc_TypeError, message)} 的简写，其中 @emph{message} 指出使用了非法参数调用内置操作。它主要用于内部使用。
@end deffn

@geindex PyErr_NoMemory (C 函数)
@anchor{c-api/exceptions c PyErr_NoMemory}@anchor{3d59}
@deffn {C 函数} PyObject* PyErr_NoMemory ()
@emph{Return value: Always NULL.}
这是 @code{PyErr_SetNone(PyExc_MemoryError)} 的简写；它返回 @code{NULL} ，以便当内存耗尽时，对象分配函数可以写 @code{return PyErr_NoMemory();} 。
@end deffn

@geindex PyErr_SetFromErrno (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromErrno}@anchor{3d56}
@deffn {C 函数} PyObject* PyErr_SetFromErrno (PyObject@w{ }*type)
@emph{Return value: Always NULL.}
@geindex strerror()

这是个便捷函数，当 C 库函数返回错误并设置 @code{errno} 时，这个函数会触发异常。它构造一个元组对象，其第一项是整数值 @code{errno}，第二项是相应的错误消息（从 @code{strerror()} 获取），然后调用 @code{PyErr_SetObject(type, object)}。在 Unix 上，当 @code{errno} 值是 @code{EINTR} ，即中断的系统调用时，这个函数会调用 @ref{3e42,,PyErr_CheckSignals()} ，如果设置了错误指示器，则将其设置为该值。该函数永远返回 @code{NULL} ，因此当系统调用返回错误时，围绕系统调用的包装函数可以写成 @code{return PyErr_SetFromErrno(type);}。
@end deffn

@geindex PyErr_SetFromErrnoWithFilenameObject (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilenameObject}@anchor{3e43}
@deffn {C 函数} PyObject* PyErr_SetFromErrnoWithFilenameObject (PyObject@w{ }*type, PyObject@w{ }*filenameObject)
@emph{Return value: Always NULL.}
类似于 @ref{3d56,,PyErr_SetFromErrno()} ，附加的行为是如果 @emph{filenameObject} 不为 @code{NULL} ，它将作为第三个参数传递给 @emph{type} 的构造函数。举个例子，在 @ref{30b,,OSError} 异常中，@emph{filenameObject} 将用来定义异常实例的 @code{filename} 属性。
@end deffn

@geindex PyErr_SetFromErrnoWithFilenameObjects (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilenameObjects}@anchor{3e44}
@deffn {C 函数} PyObject* PyErr_SetFromErrnoWithFilenameObjects (PyObject@w{ }*type, PyObject@w{ }*filenameObject, PyObject@w{ }*filenameObject2)
@emph{Return value: Always NULL.}
类似于 @ref{3e43,,PyErr_SetFromErrnoWithFilenameObject()} ，但接受第二个 filename 对象，用于当一个接受两个 filename 的函数失败时触发错误。


3.4 新版功能.

@end deffn

@geindex PyErr_SetFromErrnoWithFilename (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromErrnoWithFilename}@anchor{3e45}
@deffn {C 函数} PyObject* PyErr_SetFromErrnoWithFilename (PyObject@w{ }*type, const char@w{ }*filename)
@emph{Return value: Always NULL.}
类似于 @ref{3e43,,PyErr_SetFromErrnoWithFilenameObject()} ，但文件名以 C 字符串形式给出。 @emph{filename} 是从文件系统编码（@ref{5f1,,os.fsdecode()}）解码出来的。
@end deffn

@geindex PyErr_SetFromWindowsErr (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromWindowsErr}@anchor{3e46}
@deffn {C 函数} PyObject* PyErr_SetFromWindowsErr (int@w{ }ierr)
@emph{Return value: Always NULL.}
这是触发 @ref{a7e,,WindowsError} 的便捷函数。如果 @emph{lerr} 为 @code{0} ，则改用调用 @code{GetLastError()} 返回的错误代码。它调用 Win32 函数 @code{FormatMessage()} 来检索 @emph{ierr} 或 @code{GetLastError()} 给定的错误代码的 Windows 描述，然后构造一个元组对象，其第一项是 @emph{ierr} 值，第二项是相应的错误信息（从 @code{FormatMessage()} 获取），然后调用 @code{PyErr_SetObject(PyExc_WindowsError, object)} 。该函数永远返回 @code{NULL} 。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex PyErr_SetExcFromWindowsErr (C 函数)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErr}@anchor{3e47}
@deffn {C 函数} PyObject* PyErr_SetExcFromWindowsErr (PyObject@w{ }*type, int@w{ }ierr)
@emph{Return value: Always NULL.}
类似于 @ref{3e46,,PyErr_SetFromWindowsErr()} ，额外的参数指定要触发的异常类型。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex PyErr_SetFromWindowsErrWithFilename (C 函数)
@anchor{c-api/exceptions c PyErr_SetFromWindowsErrWithFilename}@anchor{3e48}
@deffn {C 函数} PyObject* PyErr_SetFromWindowsErrWithFilename (int@w{ }ierr, const char@w{ }*filename)
@emph{Return value: Always NULL.}
类似于 @code{PyErr_SetFromWindowsErrWithFilenameObject()} ，但是 filename 是以 C 字符串形式给出的。 @emph{filename} 是从文件系统编码（@ref{5f1,,os.fsdecode()}）解码出来的。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilenameObject (C 函数)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObject}@anchor{3e49}
@deffn {C 函数} PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject (PyObject@w{ }*type, int@w{ }ierr, PyObject@w{ }*filename)
@emph{Return value: Always NULL.}
类似于 @code{PyErr_SetFromWindowsErrWithFilenameObject()} ，额外参数指定要触发的异常类型。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilenameObjects (C 函数)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObjects}@anchor{3e4a}
@deffn {C 函数} PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects (PyObject@w{ }*type, int@w{ }ierr, PyObject@w{ }*filename, PyObject@w{ }*filename2)
@emph{Return value: Always NULL.}
类似于 @ref{3e49,,PyErr_SetExcFromWindowsErrWithFilenameObject()} ，但是接受第二个 filename 对象。

@ref{14c1,,可用性}: Windows。


3.4 新版功能.

@end deffn

@geindex PyErr_SetExcFromWindowsErrWithFilename (C 函数)
@anchor{c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilename}@anchor{3e4b}
@deffn {C 函数} PyObject* PyErr_SetExcFromWindowsErrWithFilename (PyObject@w{ }*type, int@w{ }ierr, const char@w{ }*filename)
@emph{Return value: Always NULL.}
类似于 @ref{3e48,,PyErr_SetFromWindowsErrWithFilename()} ，额外参数指定要触发的异常类型。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex PyErr_SetImportError (C 函数)
@anchor{c-api/exceptions c PyErr_SetImportError}@anchor{6f9}
@deffn {C 函数} PyObject* PyErr_SetImportError (PyObject@w{ }*msg, PyObject@w{ }*name, PyObject@w{ }*path)
@emph{Return value: Always NULL.}
这是触发 @ref{16c,,ImportError} 的便捷函数。 @emph{msg} 将被设为异常的消息字符串。 @emph{name} 和 @emph{path} ，（都可以为 @code{NULL} ），将用来被设置 @ref{16c,,ImportError} 对应的属性 @code{name} 和 @code{path}。


3.3 新版功能.

@end deffn

@geindex PyErr_SetImportErrorSubclass (C 函数)
@anchor{c-api/exceptions c PyErr_SetImportErrorSubclass}@anchor{6cc}
@deffn {C 函数} PyObject* PyErr_SetImportErrorSubclass (PyObject@w{ }*exception, PyObject@w{ }*msg, PyObject@w{ }*name, PyObject@w{ }*path)
@emph{Return value: Always NULL.}
和 @ref{6f9,,PyErr_SetImportError()} 很类似，但这个函数允许指定一个 @ref{16c,,ImportError} 的子类来触发。


3.6 新版功能.

@end deffn

@geindex PyErr_SyntaxLocationObject (C 函数)
@anchor{c-api/exceptions c PyErr_SyntaxLocationObject}@anchor{3e4c}
@deffn {C 函数} void PyErr_SyntaxLocationObject (PyObject@w{ }*filename, int@w{ }lineno, int@w{ }col_offset)

设置当前异常的文件，行和偏移信息。如果当前异常不是 @ref{562,,SyntaxError} ，则它设置额外的属性，使异常打印子系统认为异常是 @ref{562,,SyntaxError}。


3.4 新版功能.

@end deffn

@geindex PyErr_SyntaxLocationEx (C 函数)
@anchor{c-api/exceptions c PyErr_SyntaxLocationEx}@anchor{3e4d}
@deffn {C 函数} void PyErr_SyntaxLocationEx (const char@w{ }*filename, int@w{ }lineno, int@w{ }col_offset)

与 @ref{3e4c,,PyErr_SyntaxLocationObject()} 类似，只是 @emph{filename} 是从文件系统编码（ @ref{5f1,,os.fsdecode()} ）解码出的一个字节字符串。


3.2 新版功能.

@end deffn

@geindex PyErr_SyntaxLocation (C 函数)
@anchor{c-api/exceptions c PyErr_SyntaxLocation}@anchor{3e4e}
@deffn {C 函数} void PyErr_SyntaxLocation (const char@w{ }*filename, int@w{ }lineno)

类似于 @ref{3e4d,,PyErr_SyntaxLocationEx()}，但省略了 @emph{col_offset} parameter 形参。
@end deffn

@geindex PyErr_BadInternalCall (C 函数)
@anchor{c-api/exceptions c PyErr_BadInternalCall}@anchor{3e4f}
@deffn {C 函数} void PyErr_BadInternalCall ()

这是 @code{PyErr_SetString(PyExc_SystemError, message)} 的缩写，其中 @emph{message} 表示使用了非法参数调用内部操作（例如，Python/C API 函数）。它主要用于内部使用。
@end deffn

@node 发出警告,查询错误指示器,抛出异常,异常处理
@anchor{c-api/exceptions issuing-warnings}@anchor{3e50}
@subsection 发出警告


这些函数可以从 C 代码中发出警告。它们仿照了由 Python 模块 @ref{12f,,warnings} 导出的那些函数。它们通常向 @emph{sys.stderr} 打印一条警告信息；当然，用户也有可能已经指定将警告转换为错误，在这种情况下，它们将触发异常。也有可能由于警告机制出现问题，使得函数触发异常。如果没有触发异常，返回值为 @code{0} ；如果触发异常，返回值为 @code{-1}。（无法确定是否实际打印了警告信息，也无法确定异常触发的原因。这是故意为之）。如果触发了异常，调用者应该进行正常的异常处理（例如，@ref{397,,Py_DECREF()} 持有引用并返回一个错误值）。

@geindex PyErr_WarnEx (C 函数)
@anchor{c-api/exceptions c PyErr_WarnEx}@anchor{e7e}
@deffn {C 函数} int PyErr_WarnEx (PyObject@w{ }*category, const char@w{ }*message, Py_ssize_t@w{ }stack_level)

发出一个警告信息。参数 @emph{category} 是一个警告类别（见下面）或 @code{NULL} ； @emph{message} 是一个 UTF-8 编码的字符串。 @emph{stack_level} 是一个给出栈帧数量的正数；警告将从该栈帧中当前正在执行的代码行发出。 @emph{stack_level} 为 1 的是调用 @ref{e7e,,PyErr_WarnEx()} 的函数，2 是在此之上的函数，以此类推。

警告类别必须是 @code{PyExc_Warning} 的子类， @code{PyExc_Warning} 是 @code{PyExc_Exception} 的子类；默认警告类别是 @code{PyExc_RuntimeWarning} 。标准 Python 警告类别作为全局变量可用，所有其名称见 @ref{3e51,,标准警告类别} 。

有关警告控制的信息，参见模块文档 @ref{12f,,warnings} 和命令行文档中的 @ref{15b,,-W} 选项。没有用于警告控制的 C API。
@end deffn

@geindex PyErr_WarnExplicitObject (C 函数)
@anchor{c-api/exceptions c PyErr_WarnExplicitObject}@anchor{3e52}
@deffn {C 函数} int PyErr_WarnExplicitObject (PyObject@w{ }*category, PyObject@w{ }*message, PyObject@w{ }*filename, int@w{ }lineno, PyObject@w{ }*module, PyObject@w{ }*registry)

发出一个对所有警告属性进行显式控制的警告消息。 这是位于 Python 函数 @ref{6b1,,warnings.warn_explicit()} 外层的直接包装；请查看其文档了解详情。 @emph{module} 和 @emph{registry} 参数可被设为 @code{NULL} 以得到相关文档所描述的默认效果。


3.4 新版功能.

@end deffn

@geindex PyErr_WarnExplicit (C 函数)
@anchor{c-api/exceptions c PyErr_WarnExplicit}@anchor{3e53}
@deffn {C 函数} int PyErr_WarnExplicit (PyObject@w{ }*category, const char@w{ }*message, const char@w{ }*filename, int@w{ }lineno, const char@w{ }*module, PyObject@w{ }*registry)

Similar to @ref{3e52,,PyErr_WarnExplicitObject()} except that @emph{message} and
@emph{module} are UTF-8 encoded strings, and @emph{filename} is decoded from the
filesystem encoding (@ref{5f1,,os.fsdecode()}).
@end deffn

@geindex PyErr_WarnFormat (C 函数)
@anchor{c-api/exceptions c PyErr_WarnFormat}@anchor{3e54}
@deffn {C 函数} int PyErr_WarnFormat (PyObject@w{ }*category, Py_ssize_t@w{ }stack_level, const char@w{ }*format, ...)

类似于 @ref{e7e,,PyErr_WarnEx()} 的函数，但使用 @ref{8c2,,PyUnicode_FromFormat()} 来格式化警告消息。 @emph{format} 是使用 ASCII 编码的字符串。


3.2 新版功能.

@end deffn

@geindex PyErr_ResourceWarning (C 函数)
@anchor{c-api/exceptions c PyErr_ResourceWarning}@anchor{6cd}
@deffn {C 函数} int PyErr_ResourceWarning (PyObject@w{ }*source, Py_ssize_t@w{ }stack_level, const char@w{ }*format, ...)

类似于 @ref{3e54,,PyErr_WarnFormat()} 的函数，但 @emph{category} 是 @ref{5d3,,ResourceWarning} 并且它会将 @emph{source} 传给 @code{warnings.WarningMessage()}。


3.6 新版功能.

@end deffn

@node 查询错误指示器,信号处理<2>,发出警告,异常处理
@anchor{c-api/exceptions querying-the-error-indicator}@anchor{3e55}
@subsection 查询错误指示器


@geindex PyErr_Occurred (C 函数)
@anchor{c-api/exceptions c PyErr_Occurred}@anchor{3d58}
@deffn {C 函数} PyObject* PyErr_Occurred ()
@emph{Return value: Borrowed reference.}
检测是否设置了错误指示器。 如已设置，则返回异常 @emph{type} (传给最近一次对某个 @code{PyErr_Set*()} 函数或 @ref{3daa,,PyErr_Restore()} 的调用的第一个参数)。 如未设置，则返回 @code{NULL}。 你并不拥有对返回值的引用，因此你不需要对它执行 @ref{397,,Py_DECREF()}。

呼叫者必须持有GIL。

@cartouche
@quotation 注解 
不要将返回值与特定的异常进行比较；请改为使用 @ref{3e09,,PyErr_ExceptionMatches()}，如下所示。 （比较很容易失败因为对于类异常来说，异常可能是一个实例而不是类，或者它可能是预期的异常的一个子类。）
@end quotation
@end cartouche
@end deffn

@geindex PyErr_ExceptionMatches (C 函数)
@anchor{c-api/exceptions c PyErr_ExceptionMatches}@anchor{3e09}
@deffn {C 函数} int PyErr_ExceptionMatches (PyObject@w{ }*exc)

等价于 @code{PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)}。 此函数应当只在实际设置了异常时才被调用；如果没有任何异常被引发则将发生非法内存访问。
@end deffn

@geindex PyErr_GivenExceptionMatches (C 函数)
@anchor{c-api/exceptions c PyErr_GivenExceptionMatches}@anchor{3e56}
@deffn {C 函数} int PyErr_GivenExceptionMatches (PyObject@w{ }*given, PyObject@w{ }*exc)

如果 @emph{given} 异常与 @emph{exc} 中的异常类型相匹配则返回真值。 如果 @emph{exc} 是一个类对象，则当 @emph{given} 是一个子类的实例时也将返回真值。 如果 @emph{exc} 是一个元组，则该元组（以及递归的子元组）中的所有异常类型都将被搜索进行匹配。
@end deffn

@geindex PyErr_Fetch (C 函数)
@anchor{c-api/exceptions c PyErr_Fetch}@anchor{a54}
@deffn {C 函数} void PyErr_Fetch (PyObject@w{ }**ptype, PyObject@w{ }**pvalue, PyObject@w{ }**ptraceback)

将错误指示符提取到三个变量中并传递其地址。 如果未设置错误指示符，则将三个变量都设为 @code{NULL}。 如果已设置，则将其清除并且你将得到对所提取的每个对象的引用。 值和回溯对象可以为 @code{NULL} 即使类型对象不为空。

@cartouche
@quotation 注解 
此函数通常只被需要捕获异常的代码或需要临时保存和恢复错误指示符的代码所使用，例如:

@example
@{
   PyObject *type, *value, *traceback;
   PyErr_Fetch(&type, &value, &traceback);

   /* ... code that might produce other errors ... */

   PyErr_Restore(type, value, traceback);
@}
@end example
@end quotation
@end cartouche
@end deffn

@geindex PyErr_Restore (C 函数)
@anchor{c-api/exceptions c PyErr_Restore}@anchor{3daa}
@deffn {C 函数} void PyErr_Restore (PyObject@w{ }*type, PyObject@w{ }*value, PyObject@w{ }*traceback)

基于三个对象设置错误指示符。 如果错误指示符已设置，它将首先被清除。 如果三个对象均为 @code{NULL}，错误指示器将被清除。 请不要传入 @code{NULL} 类型和非 @code{NULL} 值或回溯。 异常类型应当是一个类。 请不要传入无效的异常类型或值。 （违反这些规则将导致微妙的后续问题。） 此调用会带走对每个对象的引用：你必须在调用之前拥有对每个对象的引用且在调用之后你将不再拥有这些引用。 （如果你不理解这一点，就不要使用此函数。 勿谓言之不预。）

@cartouche
@quotation 注解 
此函数通常只被需要临时保存和恢复错误指示符的代码所使用。 请使用 @ref{a54,,PyErr_Fetch()} 来保存当前的错误指示符。
@end quotation
@end cartouche
@end deffn

@geindex PyErr_NormalizeException (C 函数)
@anchor{c-api/exceptions c PyErr_NormalizeException}@anchor{1143}
@deffn {C 函数} void PyErr_NormalizeException (PyObject@w{ }**exc, PyObject@w{ }**val, PyObject@w{ }**tb)

在特定情况下，下面 @ref{a54,,PyErr_Fetch()} 所返回的值可以是“非正规化的”，即 @code{*exc} 是一个类对象而 @code{*val} 不是同一个类的实例。 在这种情况下此函数可以被用来实例化类。 如果值已经是正规化的，则不做任何操作。 实现这种延迟正规化是为了提升性能。

@cartouche
@quotation 注解 
此函数 @emph{不会} 显式地在异常值上设置 @code{__traceback__} 属性。 如果想要适当地设置回溯，还需要以下附加代码片段:

@example
if (tb != NULL) @{
  PyException_SetTraceback(val, tb);
@}
@end example
@end quotation
@end cartouche
@end deffn

@geindex PyErr_GetExcInfo (C 函数)
@anchor{c-api/exceptions c PyErr_GetExcInfo}@anchor{3e57}
@deffn {C 函数} void PyErr_GetExcInfo (PyObject@w{ }**ptype, PyObject@w{ }**pvalue, PyObject@w{ }**ptraceback)

提取异常信息，即从 @code{sys.exc_info()} 所得到的。 这是指一个 @emph{已被捕获} 的异常，而不是刚被引发的异常。 返回分别指向三个对象的新引用，其中任何一个均可以为 @code{NULL}。 不会修改异常信息的状态。

@cartouche
@quotation 注解 
此函数通常不会被需要处理异常的代码所使用。 它被使用的场合是在代码需要临时保存并恢复异常状态的时候。 请使用 @ref{3e58,,PyErr_SetExcInfo()} 来恢复或清除异常状态。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@geindex PyErr_SetExcInfo (C 函数)
@anchor{c-api/exceptions c PyErr_SetExcInfo}@anchor{3e58}
@deffn {C 函数} void PyErr_SetExcInfo (PyObject@w{ }*type, PyObject@w{ }*value, PyObject@w{ }*traceback)

设置异常信息，即从 @code{sys.exc_info()} 所得到的。 这是指一个 @emph{已被捕获} 的异常，而不是刚被引发的异常。 此函数会偷取对参数的引用。 要清空异常状态，请为所有三个参数传入 @code{NULL}。 对于有关三个参数的一般规则，请参阅 @ref{3daa,,PyErr_Restore()}。

@cartouche
@quotation 注解 
此函数通常不会被需要处理异常的代码所使用。 它被使用的场合是在代码需要临时保存并恢复异常状态的情况。 请使用 @ref{3e57,,PyErr_GetExcInfo()} 来读取异常状态。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@node 信号处理<2>,Exception 类<2>,查询错误指示器,异常处理
@anchor{c-api/exceptions signal-handling}@anchor{3e59}
@subsection 信号处理


@geindex PyErr_CheckSignals (C 函数)
@anchor{c-api/exceptions c PyErr_CheckSignals}@anchor{3e42}
@deffn {C 函数} int PyErr_CheckSignals ()

@geindex 模块; signal
@geindex SIGINT
@geindex KeyboardInterrupt (built-in exception)

This function interacts with Python's signal handling.  It checks whether a
signal has been sent to the processes and if so, invokes the corresponding
signal handler.  If the @ref{ea,,signal} module is supported, this can invoke a
signal handler written in Python.  In all cases, the default effect for
@code{SIGINT} is to raise the  @ref{2d3,,KeyboardInterrupt} exception.  If an
exception is raised the error indicator is set and the function returns @code{-1};
otherwise the function returns @code{0}.  The error indicator may or may not be
cleared if it was previously set.
@end deffn

@geindex PyErr_SetInterrupt (C 函数)
@anchor{c-api/exceptions c PyErr_SetInterrupt}@anchor{3e5a}
@deffn {C 函数} void PyErr_SetInterrupt ()

@geindex SIGINT
@geindex KeyboardInterrupt (built-in exception)

Simulate the effect of a @code{SIGINT} signal arriving. The next time
@ref{3e42,,PyErr_CheckSignals()} is called,  the Python signal handler for
@code{SIGINT} will be called.

如果 Python 没有处理 @ref{263c,,signal.SIGINT} (将它设为 @ref{263d,,signal.SIG_DFL} 或 @ref{263e,,signal.SIG_IGN})，此函数将不做任何事。
@end deffn

@geindex PySignal_SetWakeupFd (C 函数)
@anchor{c-api/exceptions c PySignal_SetWakeupFd}@anchor{e13}
@deffn {C 函数} int PySignal_SetWakeupFd (int@w{ }fd)

这个工具函数指定了一个每当收到信号时将被作为以单个字节的形式写入信号编号的目标的文件描述符。 @emph{fd} 必须是非阻塞的。 它将返回前一个这样的文件描述符。

设置值 @code{-1} 将禁用该特性；这是初始状态。 这等价于 Python 中的 @ref{4dd,,signal.set_wakeup_fd()}，但是没有任何错误检查。 @emph{fd} 应当是一个有效的文件描述符。 此函数应当只从主线程来调用。


在 3.5 版更改: 在 Windows 上，此函数现在也支持套接字处理。

@end deffn

@node Exception 类<2>,异常对象,信号处理<2>,异常处理
@anchor{c-api/exceptions exception-classes}@anchor{3e5b}
@subsection Exception 类


@geindex PyErr_NewException (C 函数)
@anchor{c-api/exceptions c PyErr_NewException}@anchor{cd3}
@deffn {C 函数} PyObject* PyErr_NewException (const char@w{ }*name, PyObject@w{ }*base, PyObject@w{ }*dict)
@emph{Return value: New reference.}
这个工具函数会创建并返回一个新的异常类。 @emph{name} 参数必须为新异常的名称，是 @code{module.classname} 形式的 C 字符串。 @emph{base} 和 @emph{dict} 参数通常为 @code{NULL}。 这将创建一个派生自 @ref{2e3,,Exception} 的类对象（在 C 中可以通过 @code{PyExc_Exception} 访问）。

新类的 @code{__module__} 属性将被设为 @emph{name} 参数的前半部分（最后一个点号之前），而类名将被设为后半部分（最后一个点号之后）。 @emph{base} 参数可被用来指定替代基类；它可以是一个类或是一个由类组成的元组。 @emph{dict} 参数可被用来指定一个由类变量和方法组成的字典。
@end deffn

@geindex PyErr_NewExceptionWithDoc (C 函数)
@anchor{c-api/exceptions c PyErr_NewExceptionWithDoc}@anchor{cd2}
@deffn {C 函数} PyObject* PyErr_NewExceptionWithDoc (const char@w{ }*name, const char@w{ }*doc, PyObject@w{ }*base, PyObject@w{ }*dict)
@emph{Return value: New reference.}
和 @ref{cd3,,PyErr_NewException()} 一样，除了可以轻松地给新的异常类一个文档字符串：如果 @emph{doc} 属性非空，它将用作异常类的文档字符串。


3.2 新版功能.

@end deffn

@node 异常对象,Unicode 异常对象,Exception 类<2>,异常处理
@anchor{c-api/exceptions exception-objects}@anchor{3e5c}
@subsection 异常对象


@geindex PyException_GetTraceback (C 函数)
@anchor{c-api/exceptions c PyException_GetTraceback}@anchor{3e5d}
@deffn {C 函数} PyObject* PyException_GetTraceback (PyObject@w{ }*ex)
@emph{Return value: New reference.}
将与异常相关联的回溯作为一个新引用返回，可以通过 @code{__traceback__} 在 Python 中访问。 如果没有已关联的回溯，则返回 @code{NULL}。
@end deffn

@geindex PyException_SetTraceback (C 函数)
@anchor{c-api/exceptions c PyException_SetTraceback}@anchor{1144}
@deffn {C 函数} int PyException_SetTraceback (PyObject@w{ }*ex, PyObject@w{ }*tb)

将异常关联的回溯设置为 @emph{tb} 。使用`@w{`}Py_None`@w{`}清除它。
@end deffn

@geindex PyException_GetContext (C 函数)
@anchor{c-api/exceptions c PyException_GetContext}@anchor{3e5e}
@deffn {C 函数} PyObject* PyException_GetContext (PyObject@w{ }*ex)
@emph{Return value: New reference.}
将与异常相关联的上下文（在处理 @emph{ex} 的过程中引发的另一个异常实例）作为一个新引用返回，可以通过 @code{__context__} 在 Python 中访问。 如果没有已关联的上下文，则返回 @code{NULL}。
@end deffn

@geindex PyException_SetContext (C 函数)
@anchor{c-api/exceptions c PyException_SetContext}@anchor{3e5f}
@deffn {C 函数} void PyException_SetContext (PyObject@w{ }*ex, PyObject@w{ }*ctx)

将与异常相关联的上下文设置为 @emph{ctx}。 使用 @code{NULL} 来清空它。 没有用来确保 @emph{ctx} 是一个异常实例的类型检查。 这将窃取一个指向 @emph{ctx} 的引用。
@end deffn

@geindex PyException_GetCause (C 函数)
@anchor{c-api/exceptions c PyException_GetCause}@anchor{3e60}
@deffn {C 函数} PyObject* PyException_GetCause (PyObject@w{ }*ex)
@emph{Return value: New reference.}
将关联到异常的原因（一个异常实例，或是 @ref{204,,None}，由 @code{raise ... from ...} 设置）作为一个新引用返回，可在 Python 中通过 @code{__cause__} 来访问。
@end deffn

@geindex PyException_SetCause (C 函数)
@anchor{c-api/exceptions c PyException_SetCause}@anchor{3e61}
@deffn {C 函数} void PyException_SetCause (PyObject@w{ }*ex, PyObject@w{ }*cause)

将与异常相关联的原因设置为 @emph{cause}。 使用 @code{NULL} 来清空它。 它没有用来确保 @emph{cause} 是一个异常实例或 @ref{204,,None} 的类型检查。 这将偷取一个指向 @emph{cause} 的引用。

@code{__suppress_context__} 会被此函数隐式地设为 @code{True}。
@end deffn

@node Unicode 异常对象,递归控制,异常对象,异常处理
@anchor{c-api/exceptions unicode-exception-objects}@anchor{3e62}@anchor{c-api/exceptions unicodeexceptions}@anchor{3e63}
@subsection Unicode 异常对象


下列函数被用于创建和修改来自 C 的 Unicode 异常。

@geindex PyUnicodeDecodeError_Create (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_Create}@anchor{3e64}
@deffn {C 函数} PyObject* PyUnicodeDecodeError_Create (const char@w{ }*encoding, const char@w{ }*object, Py_ssize_t@w{ }length, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, const char@w{ }*reason)
@emph{Return value: New reference.}
创建一个 @ref{332,,UnicodeDecodeError} 对象并附带 @emph{encoding}, @emph{object}, @emph{length}, @emph{start}, @emph{end} 和 @emph{reason} 等属性。 @emph{encoding} 和 @emph{reason} 为 UTF-8 编码的字符串。
@end deffn

@geindex PyUnicodeEncodeError_Create (C 函数)
@anchor{c-api/exceptions c PyUnicodeEncodeError_Create}@anchor{3e65}
@deffn {C 函数} PyObject* PyUnicodeEncodeError_Create (const char@w{ }*encoding, const Py_UNICODE@w{ }*object, Py_ssize_t@w{ }length, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, const char@w{ }*reason)
@emph{Return value: New reference.}
创建一个 @ref{331,,UnicodeEncodeError} 对象并附带 @emph{encoding}, @emph{object}, @emph{length}, @emph{start}, @emph{end} 和 @emph{reason}。 @emph{encoding} 和 @emph{reason} 都是以 UTF-8 编码的字符串。


3.3 版后已移除: 3.11

@code{Py_UNICODE} 自 Python 3.3 起已被弃用。 请迁移至 @code{PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...)}。

@end deffn

@geindex PyUnicodeTranslateError_Create (C 函数)
@anchor{c-api/exceptions c PyUnicodeTranslateError_Create}@anchor{3e66}
@deffn {C 函数} PyObject* PyUnicodeTranslateError_Create (const Py_UNICODE@w{ }*object, Py_ssize_t@w{ }length, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, const char@w{ }*reason)
@emph{Return value: New reference.}
创建一个 @ref{1896,,UnicodeTranslateError} 对象并附带 @emph{object}, @emph{length}, @emph{start}, @emph{end} 和 @emph{reason}。 @emph{reason} 是一个以 UTF-8 编码的字符串。


3.3 版后已移除: 3.11

@code{Py_UNICODE} 自 Python 3.3 起已被弃用。 请迁移至 @code{PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...)}。

@end deffn

@geindex PyUnicodeDecodeError_GetEncoding (C 函数)
@geindex PyUnicodeEncodeError_GetEncoding (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetEncoding}@anchor{3e67}
@deffn {C 函数} PyObject* PyUnicodeDecodeError_GetEncoding (PyObject@w{ }*exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetEncoding}@anchor{3e68}
@deffnx {C 函数} PyObject* PyUnicodeEncodeError_GetEncoding (PyObject@w{ }*exc)
@emph{Return value: New reference.}
返回给定异常对象的 @emph{encoding} 属性
@end deffn

@geindex PyUnicodeDecodeError_GetObject (C 函数)
@geindex PyUnicodeEncodeError_GetObject (C 函数)
@geindex PyUnicodeTranslateError_GetObject (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetObject}@anchor{3e69}
@deffn {C 函数} PyObject* PyUnicodeDecodeError_GetObject (PyObject@w{ }*exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetObject}@anchor{3e6a}
@deffnx {C 函数} PyObject* PyUnicodeEncodeError_GetObject (PyObject@w{ }*exc)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetObject}@anchor{3e6b}
@deffnx {C 函数} PyObject* PyUnicodeTranslateError_GetObject (PyObject@w{ }*exc)
@emph{Return value: New reference.}
返回给定异常对象的 @emph{object} 属性
@end deffn

@geindex PyUnicodeDecodeError_GetStart (C 函数)
@geindex PyUnicodeEncodeError_GetStart (C 函数)
@geindex PyUnicodeTranslateError_GetStart (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetStart}@anchor{3e6c}
@deffn {C 函数} int PyUnicodeDecodeError_GetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }*start)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetStart}@anchor{3e6d}
@deffnx {C 函数} int PyUnicodeEncodeError_GetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }*start)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetStart}@anchor{3e6e}
@deffnx {C 函数} int PyUnicodeTranslateError_GetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }*start)

获取给定异常对象的 @emph{start} 属性并将其放入 @emph{*start}。 @emph{start} 必须不为 @code{NULL}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyUnicodeDecodeError_SetStart (C 函数)
@geindex PyUnicodeEncodeError_SetStart (C 函数)
@geindex PyUnicodeTranslateError_SetStart (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetStart}@anchor{3e6f}
@deffn {C 函数} int PyUnicodeDecodeError_SetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }start)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetStart}@anchor{3e70}
@deffnx {C 函数} int PyUnicodeEncodeError_SetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }start)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetStart}@anchor{3e71}
@deffnx {C 函数} int PyUnicodeTranslateError_SetStart (PyObject@w{ }*exc, Py_ssize_t@w{ }start)

将给定异常对象的 @emph{start} 属性设为 @emph{start}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyUnicodeDecodeError_GetEnd (C 函数)
@geindex PyUnicodeEncodeError_GetEnd (C 函数)
@geindex PyUnicodeTranslateError_GetEnd (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetEnd}@anchor{3e72}
@deffn {C 函数} int PyUnicodeDecodeError_GetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }*end)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetEnd}@anchor{3e73}
@deffnx {C 函数} int PyUnicodeEncodeError_GetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }*end)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetEnd}@anchor{3e74}
@deffnx {C 函数} int PyUnicodeTranslateError_GetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }*end)

获取给定异常对象的 @emph{end} 属性并将其放入 @emph{*end}。 @emph{end} 必须不为 @code{NULL}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyUnicodeDecodeError_SetEnd (C 函数)
@geindex PyUnicodeEncodeError_SetEnd (C 函数)
@geindex PyUnicodeTranslateError_SetEnd (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetEnd}@anchor{3e75}
@deffn {C 函数} int PyUnicodeDecodeError_SetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }end)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetEnd}@anchor{3e76}
@deffnx {C 函数} int PyUnicodeEncodeError_SetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }end)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetEnd}@anchor{3e77}
@deffnx {C 函数} int PyUnicodeTranslateError_SetEnd (PyObject@w{ }*exc, Py_ssize_t@w{ }end)

将给定异常对象的 @emph{end} 属性设为 @emph{end}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyUnicodeDecodeError_GetReason (C 函数)
@geindex PyUnicodeEncodeError_GetReason (C 函数)
@geindex PyUnicodeTranslateError_GetReason (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_GetReason}@anchor{3e78}
@deffn {C 函数} PyObject* PyUnicodeDecodeError_GetReason (PyObject@w{ }*exc)
@anchor{c-api/exceptions c PyUnicodeEncodeError_GetReason}@anchor{3e79}
@deffnx {C 函数} PyObject* PyUnicodeEncodeError_GetReason (PyObject@w{ }*exc)
@anchor{c-api/exceptions c PyUnicodeTranslateError_GetReason}@anchor{3e7a}
@deffnx {C 函数} PyObject* PyUnicodeTranslateError_GetReason (PyObject@w{ }*exc)
@emph{Return value: New reference.}
返回给定异常对象的 @emph{reason} 属性
@end deffn

@geindex PyUnicodeDecodeError_SetReason (C 函数)
@geindex PyUnicodeEncodeError_SetReason (C 函数)
@geindex PyUnicodeTranslateError_SetReason (C 函数)
@anchor{c-api/exceptions c PyUnicodeDecodeError_SetReason}@anchor{3e7b}
@deffn {C 函数} int PyUnicodeDecodeError_SetReason (PyObject@w{ }*exc, const char@w{ }*reason)
@anchor{c-api/exceptions c PyUnicodeEncodeError_SetReason}@anchor{3e7c}
@deffnx {C 函数} int PyUnicodeEncodeError_SetReason (PyObject@w{ }*exc, const char@w{ }*reason)
@anchor{c-api/exceptions c PyUnicodeTranslateError_SetReason}@anchor{3e7d}
@deffnx {C 函数} int PyUnicodeTranslateError_SetReason (PyObject@w{ }*exc, const char@w{ }*reason)

将给定异常对象的 @emph{reason} 属性设为 @emph{reason}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@node 递归控制,标准异常,Unicode 异常对象,异常处理
@anchor{c-api/exceptions recursion}@anchor{3e7e}@anchor{c-api/exceptions recursion-control}@anchor{3e7f}
@subsection 递归控制


这两个函数提供了一种在 C 层级上进行安全的递归调用的方式，在核心模块与扩展模块中均适用。 当递归代码不一定会发起调用 Python 代码（后者会自动跟踪其递归深度）时就需要用到它们。 它们对于 @emph{tp_call} 实现来说也无必要因为 @ref{3e80,,调用协议} 会负责递归处理。

@geindex Py_EnterRecursiveCall (C 函数)
@anchor{c-api/exceptions c Py_EnterRecursiveCall}@anchor{252}
@deffn {C 函数} int Py_EnterRecursiveCall (const char@w{ }*where)

标记一个递归的 C 层级调用即将被执行的点位。

如果定义了 @code{USE_STACKCHECK}，此函数会使用 @ref{3e81,,PyOS_CheckStack()} 来检查操作系统堆栈是否溢出。 在这种情况下，它将设置一个 @ref{fb5,,MemoryError} 并返回非零值。

随后此函数将检查是否达到递归限制。 如果是的话，将设置一个 @ref{731,,RecursionError} 并返回一个非零值。 在其他情况下，则返回零。

@emph{where} 应为一个 UTF-8 编码的字符串如 @code{" in instance check"}，它将与由递归深度限制所导致的 @ref{731,,RecursionError} 消息相拼接。


在 3.9 版更改: 此函数现在也在受限 API 中可用。

@end deffn

@geindex Py_LeaveRecursiveCall (C 函数)
@anchor{c-api/exceptions c Py_LeaveRecursiveCall}@anchor{253}
@deffn {C 函数} void Py_LeaveRecursiveCall (void)

结束一个 @ref{252,,Py_EnterRecursiveCall()}。 必须针对 @ref{252,,Py_EnterRecursiveCall()} 的每个 @emph{成功的} 发起调用操作执行一次调用。


在 3.9 版更改: 此函数现在也在受限 API 中可用。

@end deffn

正确地针对容器类型实现 @ref{3dad,,tp_repr} 需要特别的递归处理。 在保护栈之外，@ref{3dad,,tp_repr} 还需要追踪对象以防止出现循环。 以下两个函数将帮助完成此功能。 从实际效果来说，这两个函数是 C 中对应 @ref{c4a,,reprlib.recursive_repr()} 的等价物。

@geindex Py_ReprEnter (C 函数)
@anchor{c-api/exceptions c Py_ReprEnter}@anchor{3e82}
@deffn {C 函数} int Py_ReprEnter (PyObject@w{ }*object)

在 @ref{3dad,,tp_repr} 实现的开头被调用以检测循环。

如果对象已经被处理，此函数将返回一个正整数。 在此情况下 @ref{3dad,,tp_repr} 实现应当返回一个指明发生循环的字符串对象。 例如，@ref{164,,dict} 对象将返回 @code{@{...@}} 而 @ref{1f9,,list} 对象将返回 @code{[...]}。

如果已达到递归限制则此函数将返回一个负正数。 在此情况下 @ref{3dad,,tp_repr} 实现通常应当返回 @code{NULL}。

在其他情况下，此函数将返回零而 @ref{3dad,,tp_repr} 实现将可正常继续。
@end deffn

@geindex Py_ReprLeave (C 函数)
@anchor{c-api/exceptions c Py_ReprLeave}@anchor{3e83}
@deffn {C 函数} void Py_ReprLeave (PyObject@w{ }*object)

结束一个 @ref{3e82,,Py_ReprEnter()}。 必须针对每个返回零的 @ref{3e82,,Py_ReprEnter()} 的发起调用操作调用一次。
@end deffn

@node 标准异常,标准警告类别,递归控制,异常处理
@anchor{c-api/exceptions standard-exceptions}@anchor{3e84}@anchor{c-api/exceptions standardexceptions}@anchor{3e85}
@subsection 标准异常


所有的 Python 标准异常都可用作全局变量，其名称为 @code{PyExc_} 跟上 Python 异常名称。这些变量是 @ref{5bd,,PyObject*} 类型；都是类对象。下面列出了全部这些用作标准异常的变量：

@geindex PyExc_BaseException
@geindex PyExc_Exception
@geindex PyExc_ArithmeticError
@geindex PyExc_AssertionError
@geindex PyExc_AttributeError
@geindex PyExc_BlockingIOError
@geindex PyExc_BrokenPipeError
@geindex PyExc_BufferError
@geindex PyExc_ChildProcessError
@geindex PyExc_ConnectionAbortedError
@geindex PyExc_ConnectionError
@geindex PyExc_ConnectionRefusedError
@geindex PyExc_ConnectionResetError
@geindex PyExc_EOFError
@geindex PyExc_FileExistsError
@geindex PyExc_FileNotFoundError
@geindex PyExc_FloatingPointError
@geindex PyExc_GeneratorExit
@geindex PyExc_ImportError
@geindex PyExc_IndentationError
@geindex PyExc_IndexError
@geindex PyExc_InterruptedError
@geindex PyExc_IsADirectoryError
@geindex PyExc_KeyError
@geindex PyExc_KeyboardInterrupt
@geindex PyExc_LookupError
@geindex PyExc_MemoryError
@geindex PyExc_ModuleNotFoundError
@geindex PyExc_NameError
@geindex PyExc_NotADirectoryError
@geindex PyExc_NotImplementedError
@geindex PyExc_OSError
@geindex PyExc_OverflowError
@geindex PyExc_PermissionError
@geindex PyExc_ProcessLookupError
@geindex PyExc_RecursionError
@geindex PyExc_ReferenceError
@geindex PyExc_RuntimeError
@geindex PyExc_StopAsyncIteration
@geindex PyExc_StopIteration
@geindex PyExc_SyntaxError
@geindex PyExc_SystemError
@geindex PyExc_SystemExit
@geindex PyExc_TabError
@geindex PyExc_TimeoutError
@geindex PyExc_TypeError
@geindex PyExc_UnboundLocalError
@geindex PyExc_UnicodeDecodeError
@geindex PyExc_UnicodeEncodeError
@geindex PyExc_UnicodeError
@geindex PyExc_UnicodeTranslateError
@geindex PyExc_ValueError
@geindex PyExc_ZeroDivisionError


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

C 名称

@tab

Python 名称

@tab

注释

@item

@code{PyExc_BaseException}

@tab

@ref{2e2,,BaseException}

@tab

@footnote{@w{(1)} 
这是其他标准异常的基类。
}

@item

@code{PyExc_Exception}

@tab

@ref{2e3,,Exception}

@tab

@footnote{@w{(1)} 
这是其他标准异常的基类。
}

@item

@code{PyExc_ArithmeticError}

@tab

@ref{187f,,ArithmeticError}

@tab

@footnote{@w{(1)} 
这是其他标准异常的基类。
}

@item

@code{PyExc_AssertionError}

@tab

@ref{241,,AssertionError}

@tab

@item

@code{PyExc_AttributeError}

@tab

@ref{4aa,,AttributeError}

@tab

@item

@code{PyExc_BlockingIOError}

@tab

@ref{a81,,BlockingIOError}

@tab

@item

@code{PyExc_BrokenPipeError}

@tab

@ref{a87,,BrokenPipeError}

@tab

@item

@code{PyExc_BufferError}

@tab

@ref{1881,,BufferError}

@tab

@item

@code{PyExc_ChildProcessError}

@tab

@ref{a82,,ChildProcessError}

@tab

@item

@code{PyExc_ConnectionAbortedError}

@tab

@ref{a88,,ConnectionAbortedError}

@tab

@item

@code{PyExc_ConnectionError}

@tab

@ref{7e1,,ConnectionError}

@tab

@item

@code{PyExc_ConnectionRefusedError}

@tab

@ref{a89,,ConnectionRefusedError}

@tab

@item

@code{PyExc_ConnectionResetError}

@tab

@ref{a8a,,ConnectionResetError}

@tab

@item

@code{PyExc_EOFError}

@tab

@ref{d3c,,EOFError}

@tab

@item

@code{PyExc_FileExistsError}

@tab

@ref{a42,,FileExistsError}

@tab

@item

@code{PyExc_FileNotFoundError}

@tab

@ref{8b7,,FileNotFoundError}

@tab

@item

@code{PyExc_FloatingPointError}

@tab

@ref{1880,,FloatingPointError}

@tab

@item

@code{PyExc_GeneratorExit}

@tab

@ref{e00,,GeneratorExit}

@tab

@item

@code{PyExc_ImportError}

@tab

@ref{16c,,ImportError}

@tab

@item

@code{PyExc_IndentationError}

@tab

@ref{f40,,IndentationError}

@tab

@item

@code{PyExc_IndexError}

@tab

@ref{f3d,,IndexError}

@tab

@item

@code{PyExc_InterruptedError}

@tab

@ref{756,,InterruptedError}

@tab

@item

@code{PyExc_IsADirectoryError}

@tab

@ref{a83,,IsADirectoryError}

@tab

@item

@code{PyExc_KeyError}

@tab

@ref{3f1,,KeyError}

@tab

@item

@code{PyExc_KeyboardInterrupt}

@tab

@ref{2d3,,KeyboardInterrupt}

@tab

@item

@code{PyExc_LookupError}

@tab

@ref{17c1,,LookupError}

@tab

@footnote{@w{(1)} 
这是其他标准异常的基类。
}

@item

@code{PyExc_MemoryError}

@tab

@ref{fb5,,MemoryError}

@tab

@item

@code{PyExc_ModuleNotFoundError}

@tab

@ref{4a9,,ModuleNotFoundError}

@tab

@item

@code{PyExc_NameError}

@tab

@ref{e48,,NameError}

@tab

@item

@code{PyExc_NotADirectoryError}

@tab

@ref{a84,,NotADirectoryError}

@tab

@item

@code{PyExc_NotImplementedError}

@tab

@ref{70e,,NotImplementedError}

@tab

@item

@code{PyExc_OSError}

@tab

@ref{30b,,OSError}

@tab

@footnote{@w{(1)} 
这是其他标准异常的基类。
}

@item

@code{PyExc_OverflowError}

@tab

@ref{a4a,,OverflowError}

@tab

@item

@code{PyExc_PermissionError}

@tab

@ref{700,,PermissionError}

@tab

@item

@code{PyExc_ProcessLookupError}

@tab

@ref{a85,,ProcessLookupError}

@tab

@item

@code{PyExc_RecursionError}

@tab

@ref{731,,RecursionError}

@tab

@item

@code{PyExc_ReferenceError}

@tab

@ref{f17,,ReferenceError}

@tab

@item

@code{PyExc_RuntimeError}

@tab

@ref{3e4,,RuntimeError}

@tab

@item

@code{PyExc_StopAsyncIteration}

@tab

@ref{1193,,StopAsyncIteration}

@tab

@item

@code{PyExc_StopIteration}

@tab

@ref{58a,,StopIteration}

@tab

@item

@code{PyExc_SyntaxError}

@tab

@ref{562,,SyntaxError}

@tab

@item

@code{PyExc_SystemError}

@tab

@ref{6fc,,SystemError}

@tab

@item

@code{PyExc_SystemExit}

@tab

@ref{6fd,,SystemExit}

@tab

@item

@code{PyExc_TabError}

@tab

@ref{f3f,,TabError}

@tab

@item

@code{PyExc_TimeoutError}

@tab

@ref{a86,,TimeoutError}

@tab

@item

@code{PyExc_TypeError}

@tab

@ref{1ff,,TypeError}

@tab

@item

@code{PyExc_UnboundLocalError}

@tab

@ref{f3e,,UnboundLocalError}

@tab

@item

@code{PyExc_UnicodeDecodeError}

@tab

@ref{332,,UnicodeDecodeError}

@tab

@item

@code{PyExc_UnicodeEncodeError}

@tab

@ref{331,,UnicodeEncodeError}

@tab

@item

@code{PyExc_UnicodeError}

@tab

@ref{d0b,,UnicodeError}

@tab

@item

@code{PyExc_UnicodeTranslateError}

@tab

@ref{1896,,UnicodeTranslateError}

@tab

@item

@code{PyExc_ValueError}

@tab

@ref{16d,,ValueError}

@tab

@item

@code{PyExc_ZeroDivisionError}

@tab

@ref{1fb,,ZeroDivisionError}

@tab

@end multitable



3.3 新版功能: @code{PyExc_BlockingIOError}, @code{PyExc_BrokenPipeError}, @code{PyExc_ChildProcessError}, @code{PyExc_ConnectionError}, @code{PyExc_ConnectionAbortedError}, @code{PyExc_ConnectionRefusedError}, @code{PyExc_ConnectionResetError}, @code{PyExc_FileExistsError}, @code{PyExc_FileNotFoundError}, @code{PyExc_InterruptedError}, @code{PyExc_IsADirectoryError}, @code{PyExc_NotADirectoryError}, @code{PyExc_PermissionError}, @code{PyExc_ProcessLookupError} and @code{PyExc_TimeoutError} 介绍如下 
@geindex Python 提高建议; PEP 3151
PEP 3151@footnote{https://www.python.org/dev/peps/pep-3151}.



3.5 新版功能: @code{PyExc_StopAsyncIteration} 和 @code{PyExc_RecursionError}.



3.6 新版功能: @code{PyExc_ModuleNotFoundError}.


这些是兼容性别名 @code{PyExc_OSError}:

@geindex PyExc_EnvironmentError
@geindex PyExc_IOError
@geindex PyExc_WindowsError


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

C 名称

@tab

注释

@item

@code{PyExc_EnvironmentError}

@tab

@item

@code{PyExc_IOError}

@tab

@item

@code{PyExc_WindowsError}

@tab

@footnote{@w{(2)} 
仅在 Windows 中定义；检测是否定义了预处理程序宏 @code{MS_WINDOWS} ，以便保护用到它的代码。
}

@end multitable



在 3.3 版更改: 这些别名曾经是单独的异常类型。


注释:

@node 标准警告类别,,标准异常,异常处理
@anchor{c-api/exceptions standard-warning-categories}@anchor{3e86}@anchor{c-api/exceptions standardwarningcategories}@anchor{3e51}
@subsection 标准警告类别


所有的标准 Python 警告类别都可以用作全局变量，其名称为`@w{`}PyExc_`@w{`} 跟上 Python 异常名称。这些变量是 @ref{5bd,,PyObject*} 类型；都是类对象。以下列出了所有用作警告的变量：

@geindex PyExc_Warning
@geindex PyExc_BytesWarning
@geindex PyExc_DeprecationWarning
@geindex PyExc_FutureWarning
@geindex PyExc_ImportWarning
@geindex PyExc_PendingDeprecationWarning
@geindex PyExc_ResourceWarning
@geindex PyExc_RuntimeWarning
@geindex PyExc_SyntaxWarning
@geindex PyExc_UnicodeWarning
@geindex PyExc_UserWarning


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxx} 
@headitem

C 名称

@tab

Python 名称

@tab

注释

@item

@code{PyExc_Warning}

@tab

@ref{18ad,,Warning}

@tab

@footnote{@w{(3)} 
这是其他标准警告类别的基类。
}

@item

@code{PyExc_BytesWarning}

@tab

@ref{5b8,,BytesWarning}

@tab

@item

@code{PyExc_DeprecationWarning}

@tab

@ref{15a,,DeprecationWarning}

@tab

@item

@code{PyExc_FutureWarning}

@tab

@ref{43e,,FutureWarning}

@tab

@item

@code{PyExc_ImportWarning}

@tab

@ref{6d9,,ImportWarning}

@tab

@item

@code{PyExc_PendingDeprecationWarning}

@tab

@ref{15c,,PendingDeprecationWarning}

@tab

@item

@code{PyExc_ResourceWarning}

@tab

@ref{5d3,,ResourceWarning}

@tab

@item

@code{PyExc_RuntimeWarning}

@tab

@ref{3ea,,RuntimeWarning}

@tab

@item

@code{PyExc_SyntaxWarning}

@tab

@ref{2d0,,SyntaxWarning}

@tab

@item

@code{PyExc_UnicodeWarning}

@tab

@ref{e54,,UnicodeWarning}

@tab

@item

@code{PyExc_UserWarning}

@tab

@ref{18ae,,UserWarning}

@tab

@end multitable



3.2 新版功能: @code{PyExc_ResourceWarning}.


注释:

@node 工具<2>,抽象对象层,异常处理,Python/C API 参考手册
@anchor{c-api/utilities doc}@anchor{3e87}@anchor{c-api/utilities id1}@anchor{3e88}@anchor{c-api/utilities utilities}@anchor{3e89}
@section 工具


本章中的函数执行各种实用工具任务，包括帮助 C 代码提升跨平台可移植性，在 C 中使用 Python 模块，以及解析函数参数并根据 C 中的值构建 Python 中的值等等。

@menu
* 操作系统实用程序:: 
* 系统功能:: 
* 过程控制:: 
* 导入模块: 导入模块<2>. 
* 数据 marshal 操作支持:: 
* 语句解释及变量编译:: 
* 字符串转换与格式化:: 
* 反射:: 
* 编解码器注册与支持功能:: 

@end menu

@node 操作系统实用程序,系统功能,,工具<2>
@anchor{c-api/sys doc}@anchor{3e8a}@anchor{c-api/sys operating-system-utilities}@anchor{3e8b}@anchor{c-api/sys os}@anchor{3e8c}
@subsection 操作系统实用程序


@geindex PyOS_FSPath (C 函数)
@anchor{c-api/sys c PyOS_FSPath}@anchor{6ce}
@deffn {C 函数} PyObject* PyOS_FSPath (PyObject@w{ }*path)
@emph{Return value: New reference.}
返回 @emph{path} 在文件系统中的表示形式。 如果该对象是一个 @ref{206,,str} 或 @ref{172,,bytes} 对象，则它的引用计数将会增加。 如果该对象实现了 @ref{5ee,,os.PathLike} 接口，则只要它是一个 @ref{206,,str} 或 @ref{172,,bytes} 对象就将返回 @ref{5ef,,__fspath__()}。 在其他情况下将引发 @ref{1ff,,TypeError} 并返回 @code{NULL}。


3.6 新版功能.

@end deffn

@geindex Py_FdIsInteractive (C 函数)
@anchor{c-api/sys c Py_FdIsInteractive}@anchor{3e8d}
@deffn {C 函数} int Py_FdIsInteractive (FILE@w{ }*fp, const char@w{ }*filename)

如果名称为 @emph{filename} 的标准 I/O 文件 @emph{fp} 被确认为可交互的则返回真（非零）值。 @code{isatty(fileno(fp))} 为真值的文件均属于这种情况。 如果全局旗标 @ref{3e8e,,Py_InteractiveFlag} 为真值，此函数在 @emph{filename} 指针为 @code{NULL} 或者其名称等于字符串 @code{'<stdin>'} 或 @code{'???'} 时也将返回真值。
@end deffn

@geindex PyOS_BeforeFork (C 函数)
@anchor{c-api/sys c PyOS_BeforeFork}@anchor{53e}
@deffn {C 函数} void PyOS_BeforeFork ()

在进程分叉之前准备某些内部状态的函数。 此函数应当在调用 @code{fork()} 或者任何类似的克隆当前进程的函数之前被调用。 只适用于定义了 @code{fork()} 的系统。

@cartouche
@quotation 警告 
C @code{fork()} 调用应当只在 @ref{3e8f,,"main" 线程} (位于 @ref{3e90,,"main" 解释器}) 中进行。 对于 @code{PyOS_BeforeFork()} 来说也是如此。
@end quotation
@end cartouche


3.7 新版功能.

@end deffn

@geindex PyOS_AfterFork_Parent (C 函数)
@anchor{c-api/sys c PyOS_AfterFork_Parent}@anchor{53f}
@deffn {C 函数} void PyOS_AfterFork_Parent ()

在进程分叉之后更新某些内部状态的函数。 此函数应当在调用 @code{fork()} 或任何类似的克隆当前进程的函数之后被调用，无论进程克隆是否成功。 只适用于定义了 @code{fork()} 的系统。

@cartouche
@quotation 警告 
C @code{fork()} 调用应当只在 @ref{3e8f,,"main" 线程} (位于 @ref{3e90,,"main" 解释器}) 中进行。 对于 @code{PyOS_AfterFork_Parent()} 来说也是如此。
@end quotation
@end cartouche


3.7 新版功能.

@end deffn

@geindex PyOS_AfterFork_Child (C 函数)
@anchor{c-api/sys c PyOS_AfterFork_Child}@anchor{3f8}
@deffn {C 函数} void PyOS_AfterFork_Child ()

在进程分叉之后更新内部解释器状态的函数。 此函数必须在调用 @code{fork()} 或任何类似的克隆当前进程的函数之后在子进程中被调用，如果该进程有机会回调到 Python 解释器的话。 只适用于定义了 @code{fork()} 的系统。

@cartouche
@quotation 警告 
C @code{fork()} 调用应当只在 @ref{3e8f,,"main" 线程} (位于 @ref{3e90,,"main" 解释器}) 中进行。 对于 @code{PyOS_AfterFork_Child()} 来说也是如此。
@end quotation
@end cartouche


3.7 新版功能.



@subsubheading 参见


@ref{4c5,,os.register_at_fork()} 允许注册可被 @ref{53e,,PyOS_BeforeFork()}, @ref{53f,,PyOS_AfterFork_Parent()} 和 @ref{3f8,,PyOS_AfterFork_Child()} 调用的自定义 Python 函数。

@end deffn

@geindex PyOS_AfterFork (C 函数)
@anchor{c-api/sys c PyOS_AfterFork}@anchor{53d}
@deffn {C 函数} void PyOS_AfterFork ()

在进程分叉之后更新某些内部状态的函数；如果要继续使用 Python 解释器则此函数应当在新进程中被调用。 如果已将一个新的可执行文件载入到新进程中，则不需要调用此函数。


3.7 版后已移除: 此函数已被 @ref{3f8,,PyOS_AfterFork_Child()} 取代。

@end deffn

@geindex PyOS_CheckStack (C 函数)
@anchor{c-api/sys c PyOS_CheckStack}@anchor{3e81}
@deffn {C 函数} int PyOS_CheckStack ()

当解释器的栈空间耗尽时返回真值。 这是一个可靠的检查，但仅在定义了 @code{USE_STACKCHECK} 时可用（目前在 Windows 上使用 Microsoft Visual C++ 编译器）。 @code{USE_STACKCHECK} 将被自动定义；你绝不应该在你自己的代码中改变此定义。
@end deffn

@geindex PyOS_getsig (C 函数)
@anchor{c-api/sys c PyOS_getsig}@anchor{3e91}
@deffn {C 函数} PyOS_sighandler_t PyOS_getsig (int@w{ }i)

返回当前用于信号 @emph{i} 的信号处理句柄。 这是一个对 @code{sigaction()} 或 @code{signal()} 简单包装器。 请不要直接调用那两个函数！ @code{PyOS_sighandler_t} 是对应于 @code{void (*)(int)} 的 typedef 别名。
@end deffn

@geindex PyOS_setsig (C 函数)
@anchor{c-api/sys c PyOS_setsig}@anchor{3e92}
@deffn {C 函数} PyOS_sighandler_t PyOS_setsig (int@w{ }i, PyOS_sighandler_t@w{ }h)

将用于信号 @emph{i} 的信号处理句柄设为 @emph{h}；返回旧的信号处理句柄。 这是一个对 @code{sigaction()} 或 @code{signal()} 的简单包装器。 请不要直接调用那两个函数！  @code{PyOS_sighandler_t} 是对应于 @code{void (*)(int)} 的 typedef 别名。
@end deffn

@geindex Py_DecodeLocale (C 函数)
@anchor{c-api/sys c Py_DecodeLocale}@anchor{547}
@deffn {C 函数} wchar_t* Py_DecodeLocale (const char*@w{ }arg, size_t@w{ }*size)

Decode a byte string from the locale encoding with the @ref{19d5,,surrogateescape error handler}: undecodable bytes are decoded as
characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a
surrogate character, escape the bytes using the surrogateescape error
handler instead of decoding them.

Encoding, highest priority to lowest priority:


@itemize *

@item 
@code{UTF-8} on macOS, Android, and VxWorks;

@item 
@code{UTF-8} on Windows if @ref{3e93,,Py_LegacyWindowsFSEncodingFlag} is zero;

@item 
@code{UTF-8} if the Python UTF-8 mode is enabled;

@item 
@code{ASCII} if the @code{LC_CTYPE} locale is @code{"C"},
@code{nl_langinfo(CODESET)} returns the @code{ASCII} encoding (or an alias),
and @code{mbstowcs()} and @code{wcstombs()} functions uses the
@code{ISO-8859-1} encoding.

@item 
the current locale encoding.
@end itemize

返回一个指向新分配的由宽字符组成的字符串的指针，使用 @ref{3e94,,PyMem_RawFree()} 来释放内存。 如果 size 不为 @code{NULL}，则将排除了 null 字符的宽字符数量写入到 @code{*size}

在解码错误或内存分配错误时返回 @code{NULL}。 如果 @emph{size} 不为 @code{NULL}，则 @code{*size} 将在内存错误时设为 @code{(size_t)-1} 或在解码错误时设为 @code{(size_t)-2}。

解码错误绝对不应当发生，除非 C 库有程序缺陷。

请使用 @ref{548,,Py_EncodeLocale()} 函数来将字符串编码回字节串。


@subsubheading 参见


@ref{3e95,,PyUnicode_DecodeFSDefaultAndSize()} 和 @ref{549,,PyUnicode_DecodeLocaleAndSize()} 函数。



3.5 新版功能.



在 3.7 版更改: The function now uses the UTF-8 encoding in the UTF-8 mode.



在 3.8 版更改: 现在如果在 Windows 上 @ref{3e93,,Py_LegacyWindowsFSEncodingFlag} 为零则此函数将使用 UTF-8 编码格式；

@end deffn

@geindex Py_EncodeLocale (C 函数)
@anchor{c-api/sys c Py_EncodeLocale}@anchor{548}
@deffn {C 函数} char* Py_EncodeLocale (const wchar_t@w{ }*text, size_t@w{ }*error_pos)

Encode a wide character string to the locale encoding with the
@ref{19d5,,surrogateescape error handler}: surrogate characters
in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

Encoding, highest priority to lowest priority:


@itemize *

@item 
@code{UTF-8} on macOS, Android, and VxWorks;

@item 
@code{UTF-8} on Windows if @ref{3e93,,Py_LegacyWindowsFSEncodingFlag} is zero;

@item 
@code{UTF-8} if the Python UTF-8 mode is enabled;

@item 
@code{ASCII} if the @code{LC_CTYPE} locale is @code{"C"},
@code{nl_langinfo(CODESET)} returns the @code{ASCII} encoding (or an alias),
and @code{mbstowcs()} and @code{wcstombs()} functions uses the
@code{ISO-8859-1} encoding.

@item 
the current locale encoding.
@end itemize

The function uses the UTF-8 encoding in the Python UTF-8 mode.

返回一个指向新分配的字节串的指针，使用 @ref{e76,,PyMem_Free()} 来释放内存。 当发生编码错误或内存分配错误时返回 @code{NULL}。

如果 error_pos 不为 @code{NULL}，则成功时会将 @code{*error_pos} 设为 @code{(size_t)-1}，或是在发生编码错误时设为无效字符的索引号。

请使用 @ref{547,,Py_DecodeLocale()} 函数来将字节串解码回由宽字符组成的字符串。


@subsubheading 参见


@ref{11c9,,PyUnicode_EncodeFSDefault()} 和 @ref{54a,,PyUnicode_EncodeLocale()} 函数。



3.5 新版功能.



在 3.7 版更改: The function now uses the UTF-8 encoding in the UTF-8 mode.



在 3.8 版更改: 现在如果在 Windows 上 @ref{3e93,,Py_LegacyWindowsFSEncodingFlag} 为零则此函数将使用 UTF-8 编码格式。

@end deffn

@node 系统功能,过程控制,操作系统实用程序,工具<2>
@anchor{c-api/sys system-functions}@anchor{3e96}@anchor{c-api/sys systemfunctions}@anchor{3e97}
@subsection 系统功能


这些是使来自 @ref{fd,,sys} 模块的功能可以让 C 代码访问的工具函数。 它们都可用于当前解释器线程的 @ref{fd,,sys} 模块的字典，该字典包含在内部线程状态结构体中。

@geindex PySys_GetObject (C 函数)
@anchor{c-api/sys c PySys_GetObject}@anchor{3e98}
@deffn {C 函数} PyObject *PySys_GetObject (const char@w{ }*name)
@emph{Return value: Borrowed reference.}
返回来自 @ref{fd,,sys} 模块的对象 @emph{name} 或者如果它不存在则返回 @code{NULL}，并且不会设置异常。
@end deffn

@geindex PySys_SetObject (C 函数)
@anchor{c-api/sys c PySys_SetObject}@anchor{3e99}
@deffn {C 函数} int PySys_SetObject (const char@w{ }*name, PyObject@w{ }*v)

将 @ref{fd,,sys} 模块中的 @emph{name} 设为 @emph{v} 除非 @emph{v} 为 @code{NULL}，在此情况下 @emph{name} 将从 sys 模块中被删除。 成功时返回 @code{0}，发生错误时返回 @code{-1}。
@end deffn

@geindex PySys_ResetWarnOptions (C 函数)
@anchor{c-api/sys c PySys_ResetWarnOptions}@anchor{3e9a}
@deffn {C 函数} void PySys_ResetWarnOptions ()

将 @ref{523,,sys.warnoptions} 重置为空列表。 此函数可在 @ref{210,,Py_Initialize()} 之前被调用。
@end deffn

@geindex PySys_AddWarnOption (C 函数)
@anchor{c-api/sys c PySys_AddWarnOption}@anchor{5b6}
@deffn {C 函数} void PySys_AddWarnOption (const wchar_t@w{ }*s)

将 @emph{s} 添加到 @ref{523,,sys.warnoptions}。 此函数必须在 @ref{210,,Py_Initialize()} 之前被调用以便影响警告过滤器列表。
@end deffn

@geindex PySys_AddWarnOptionUnicode (C 函数)
@anchor{c-api/sys c PySys_AddWarnOptionUnicode}@anchor{5b5}
@deffn {C 函数} void PySys_AddWarnOptionUnicode (PyObject@w{ }*unicode)

将 @emph{unicode} 添加到 @ref{523,,sys.warnoptions}。

注意：目前此函数不可在 CPython 实现之外使用，因为它必须在 @ref{210,,Py_Initialize()} 中的 @ref{12f,,warnings} 显式导入之前被调用，但是要等运行时已初始化到足以允许创建 Unicode 对象时才能被调用。
@end deffn

@geindex PySys_SetPath (C 函数)
@anchor{c-api/sys c PySys_SetPath}@anchor{3e9b}
@deffn {C 函数} void PySys_SetPath (const wchar_t@w{ }*path)

将 @ref{262,,sys.path} 设为由在 @emph{path} 中找到的路径组成的列表对象，该参数应为使用特定平台的搜索路径分隔符 (在 Unix 上为 @code{:}，在 Windows 上为 @code{;}) 分隔的路径的列表。
@end deffn

@geindex PySys_WriteStdout (C 函数)
@anchor{c-api/sys c PySys_WriteStdout}@anchor{3e9c}
@deffn {C 函数} void PySys_WriteStdout (const char@w{ }*format, ...)

将以 @emph{format} 描述的输出字符串写入到 @ref{428,,sys.stdout}。 不会引发任何异常，即使发生了截断（见下文）。

@emph{format} 应当将已格式化的输出字符串的总大小限制在 1000 字节以下 -- 超过 1000 字节后，输出字符串会被截断。 特别地，这意味着不应出现不受限制的 "%s" 格式；它们应当使用 "%.<N>s" 来限制，其中 <N> 是一个经计算使得 <N> 与其他已格式化文本的最大尺寸之和不会超过 1000 字节的十进制数字。 还要注意 "%f"，它可能为非常大的数字打印出数以百计的数位。

如果发生了错误，@ref{428,,sys.stdout} 会被清空，已格式化的消息将被写入到真正的 (C 层级) @emph{stdout}。
@end deffn

@geindex PySys_WriteStderr (C 函数)
@anchor{c-api/sys c PySys_WriteStderr}@anchor{3e9d}
@deffn {C 函数} void PySys_WriteStderr (const char@w{ }*format, ...)

类似 @ref{3e9c,,PySys_WriteStdout()}，但改为写入到 @ref{1eb,,sys.stderr} 或 @emph{stderr}。
@end deffn

@geindex PySys_FormatStdout (C 函数)
@anchor{c-api/sys c PySys_FormatStdout}@anchor{3e9e}
@deffn {C 函数} void PySys_FormatStdout (const char@w{ }*format, ...)

类似 PySys_WriteStdout() 的函数将会使用 @ref{3e9f,,PyUnicode_FromFormatV()} 来格式化消息并且不会将消息截短至任意长度。


3.2 新版功能.

@end deffn

@geindex PySys_FormatStderr (C 函数)
@anchor{c-api/sys c PySys_FormatStderr}@anchor{3ea0}
@deffn {C 函数} void PySys_FormatStderr (const char@w{ }*format, ...)

类似 @ref{3e9e,,PySys_FormatStdout()}，但改为写入到 @ref{1eb,,sys.stderr} 或 @emph{stderr}。


3.2 新版功能.

@end deffn

@geindex PySys_AddXOption (C 函数)
@anchor{c-api/sys c PySys_AddXOption}@anchor{3ea1}
@deffn {C 函数} void PySys_AddXOption (const wchar_t@w{ }*s)

将 @emph{s} 解析为一个由 @ref{297,,-X} 选项组成的集合并将它们添加到 @ref{3ea2,,PySys_GetXOptions()} 所返回的当前选项映射。 此函数可以在 @ref{210,,Py_Initialize()} 之前被调用。


3.2 新版功能.

@end deffn

@geindex PySys_GetXOptions (C 函数)
@anchor{c-api/sys c PySys_GetXOptions}@anchor{3ea2}
@deffn {C 函数} PyObject *PySys_GetXOptions ()
@emph{Return value: Borrowed reference.}
返回当前 @ref{297,,-X} 选项的字典，类似于 @ref{14b2,,sys._xoptions}。 发生错误时，将返回 @code{NULL} 并设置一个异常。


3.2 新版功能.

@end deffn

@geindex PySys_Audit (C 函数)
@anchor{c-api/sys c PySys_Audit}@anchor{10b1}
@deffn {C 函数} int PySys_Audit (const char@w{ }*event, const char@w{ }*format, ...)

引发一个审计事件并附带任何激活的钩子。 成功时返回零值或在失败时返回非零值并设置一个异常。

如果已添加了任何钩子，则将使用 @emph{format} 和其他参数来构造一个用入传入的元组。 除 @code{N} 以外，在 @ref{3f9,,Py_BuildValue()} 中使用的格式字符均可使用。 如果构建的值不是一个元组，它将被添加到一个单元素元组中。 （格式选项 @code{N} 会消耗一个引用，但是由于没有办法知道此函数的参数是否将被消耗，因此使用它可能导致引用泄漏。）

请注意 @code{#} 格式字符应当总是被当作 @ref{391,,Py_ssize_t} 来处理，无论是否定义了 @code{PY_SSIZE_T_CLEAN}。

@ref{109f,,sys.audit()} 会执行与来自 Python 代码的函数相同的操作。


3.8 新版功能.



在 3.8.2 版更改: 要求 @ref{391,,Py_ssize_t} 用于 @code{#} 格式字符。 在此之前，会引发一个不可避免的弃用警告。

@end deffn

@geindex PySys_AddAuditHook (C 函数)
@anchor{c-api/sys c PySys_AddAuditHook}@anchor{3550}
@deffn {C 函数} int PySys_AddAuditHook (Py_AuditHookFunction@w{ }hook, void@w{ }*userData)

将可调用对象 @emph{hook} 添加到激活的审计钩子列表。 在成功时返回零而在失败时返回非零值。 如果运行时已经被初始化，还会在失败时设置一个错误。 通过此 API 添加的钩子会针对在运行时创建的所有解释器被调用。

@emph{userData} 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调用，该指针不应直接指向 Python 状态。

此函数可在 @ref{210,,Py_Initialize()} 之前被安全地调用。 如果在运行时初始化之后被调用，现有的审计钩子将得到通知并可能通过引发一个从 @ref{2e3,,Exception} 子类化的错误静默地放弃操作（其他错误将不会被静默）。

钩子函数的类型为 @code{int (*)(const char *event, PyObject *args, void *userData)}，其中 @emph{args} 保证是一个 @ref{3ea3,,PyTupleObject}。 钩子函数调用时总是附带引发该事件的 Python 解释器所持有的 GIL。

请参阅 
@geindex Python 提高建议; PEP 578
PEP 578@footnote{https://www.python.org/dev/peps/pep-0578} 了解有关审计的详细描述。 在运行时和标准库中会引发审计事件的函数清单见 @ref{354c,,审计事件表}。 更多细节见每个函数的文档。

引发一个 @ref{fec,,审计事件} @code{sys.addaudithook}，没有附带参数。


3.8 新版功能.

@end deffn

@node 过程控制,导入模块<2>,系统功能,工具<2>
@anchor{c-api/sys process-control}@anchor{3ea4}@anchor{c-api/sys processcontrol}@anchor{3ea5}
@subsection 过程控制


@geindex Py_FatalError (C 函数)
@anchor{c-api/sys c Py_FatalError}@anchor{267}
@deffn {C 函数} void Py_FatalError (const char@w{ }*message)

@geindex abort()

打印一个致命错误消息并杀掉进程。 不会执行任何清理。 此函数应当仅在检测到可能令继续使用 Python 解释器变得危险的条件时被发起调用；例如，当对象管理已被破坏的时候。 在 Unix 上，标准 C 库函数 @code{abort()} 会被调用并将由它来尝试产生一个 @code{core} 文件。

The @code{Py_FatalError()} function is replaced with a macro which logs
automatically the name of the current function, unless the
@code{Py_LIMITED_API} macro is defined.


在 3.9 版更改: 自动记录函数名称。

@end deffn

@geindex Py_Exit (C 函数)
@anchor{c-api/sys c Py_Exit}@anchor{711}
@deffn {C 函数} void Py_Exit (int@w{ }status)

@geindex Py_FinalizeEx()
@geindex exit()

退出当前进程。 这将调用 @ref{6ca,,Py_FinalizeEx()} 然后再调用标准 C 库函数 @code{exit(status)}。 如果 @ref{6ca,,Py_FinalizeEx()} 提示错误，退出状态将被设为 120.


在 3.6 版更改: 来自最终化的错误不会再被忽略。

@end deffn

@geindex Py_AtExit (C 函数)
@anchor{c-api/sys c Py_AtExit}@anchor{3ea6}
@deffn {C 函数} int Py_AtExit (void (*func)())

@geindex Py_FinalizeEx()
@geindex cleanup functions

注册一个由 @ref{6ca,,Py_FinalizeEx()} 调用的清理函数。 调用清理函数将不传入任何参数且不应返回任何值。 最多可以注册32 个清理函数。 当注册成功时，@ref{3ea6,,Py_AtExit()} 将返回 @code{0}；失败时，它将返回 @code{-1}。 最后注册的清理函数会最先被调用。 每个清理函数将至多被调用一次。 由于 Python 的内部最终化将在清理函数之前完成，因此 Python API 不应被 @emph{func} 调用。
@end deffn

@node 导入模块<2>,数据 marshal 操作支持,过程控制,工具<2>
@anchor{c-api/import doc}@anchor{3ea7}@anchor{c-api/import importing}@anchor{3ea8}@anchor{c-api/import importing-modules}@anchor{3ea9}
@subsection 导入模块


@geindex PyImport_ImportModule (C 函数)
@anchor{c-api/import c PyImport_ImportModule}@anchor{d43}
@deffn {C 函数} PyObject* PyImport_ImportModule (const char@w{ }*name)
@emph{Return value: New reference.}
@geindex package variable; __all__
@geindex __all__ (package variable)
@geindex modules (in module sys)

这是下面 @ref{bfd,,PyImport_ImportModuleEx()} 的简化版接口，将 @emph{globals} 和 @emph{locals} 参数设为 @code{NULL} 并将 @emph{level} 设为 0。 当 @emph{name} 参数包含一个点号（即指定了一个包的子模块）时，@emph{fromlist} 参数会被设为列表 @code{['*']} 这样返回值将为所指定的模块而不像在其他情况下那样为包含模块的最高层级包。 （不幸的是，这在 @emph{name} 实际上是指定一个子包而非子模块时将有一个额外的副作用：在包的 @code{__all__} 变量中指定的子模块会被加载。） 返回一个对所导入模块的新引用，或是在导入失败时返回 @code{NULL} 并设置一个异常。 模块导入失败同模块不会留 在 @ref{109a,,sys.modules} 中。

该函数总是使用绝对路径导入。
@end deffn

@geindex PyImport_ImportModuleNoBlock (C 函数)
@anchor{c-api/import c PyImport_ImportModuleNoBlock}@anchor{aa9}
@deffn {C 函数} PyObject* PyImport_ImportModuleNoBlock (const char@w{ }*name)
@emph{Return value: New reference.}
该函数是 @ref{d43,,PyImport_ImportModule()} 的一个被弃用的别名。


在 3.3 版更改: 在导入锁被另一线程掌控时此函数会立即失败。 但是从 Python 3.3 起，锁方案在大多数情况下都已切换为针对每个模块加锁，所以此函数的特殊行为已无必要。

@end deffn

@geindex PyImport_ImportModuleEx (C 函数)
@anchor{c-api/import c PyImport_ImportModuleEx}@anchor{bfd}
@deffn {C 函数} PyObject* PyImport_ImportModuleEx (const char@w{ }*name, PyObject@w{ }*globals, PyObject@w{ }*locals, PyObject@w{ }*fromlist)
@emph{Return value: New reference.}
@geindex 內置函数; __import__

导入一个模块。 请参阅内置 Python 函数 @ref{16b,,__import__()} 获取完善的相关描述。

返回值是一个对所导入模块或最高层级包的新引用，或是在导入失败时则为 @code{NULL} 并设置一个异常。 与 @ref{16b,,__import__()} 类似，当请求一个包的子模块时返回值通常为该最高层级包，除非给出了一个非空的 @emph{fromlist}。

导入失败将移动不完整的模块对象，就像 @ref{d43,,PyImport_ImportModule()} 那样。
@end deffn

@geindex PyImport_ImportModuleLevelObject (C 函数)
@anchor{c-api/import c PyImport_ImportModuleLevelObject}@anchor{3eaa}
@deffn {C 函数} PyObject* PyImport_ImportModuleLevelObject (PyObject@w{ }*name, PyObject@w{ }*globals, PyObject@w{ }*locals, PyObject@w{ }*fromlist, int@w{ }level)
@emph{Return value: New reference.}
导入一个模块。 关于此函数的最佳说明请参考内置 Python 函数 @ref{16b,,__import__()}，因为标准 @ref{16b,,__import__()} 函数会直接调用此函数。

返回值是一个对所导入模块或最高层级包的新引用，或是在导入失败时则为 @code{NULL} 并设置一个异常。 与 @ref{16b,,__import__()} 类似，当请求一个包的子模块时返回值通常为该最高层级包，除非给出了一个非空的 @emph{fromlist}。


3.3 新版功能.

@end deffn

@geindex PyImport_ImportModuleLevel (C 函数)
@anchor{c-api/import c PyImport_ImportModuleLevel}@anchor{bfc}
@deffn {C 函数} PyObject* PyImport_ImportModuleLevel (const char@w{ }*name, PyObject@w{ }*globals, PyObject@w{ }*locals, PyObject@w{ }*fromlist, int@w{ }level)
@emph{Return value: New reference.}
类似于 @ref{3eaa,,PyImport_ImportModuleLevelObject()}，但其名称为 UTF-8 编码的字符串而不是 Unicode 对象。


在 3.3 版更改: 不再接受 @emph{level} 为负数值。

@end deffn

@geindex PyImport_Import (C 函数)
@anchor{c-api/import c PyImport_Import}@anchor{e2c}
@deffn {C 函数} PyObject* PyImport_Import (PyObject@w{ }*name)
@emph{Return value: New reference.}
这是一个调用了当前“导入钩子函数”的更高层级接口（显式指定 @emph{level} 为 0，表示绝对导入）。 它将发起调用当前全局作用域下 @code{__builtins__} 中的 @ref{16b,,__import__()} 函数。 这意味着将使用当前环境下安装的任何导入钩子来完成导入。

该函数总是使用绝对路径导入。
@end deffn

@geindex PyImport_ReloadModule (C 函数)
@anchor{c-api/import c PyImport_ReloadModule}@anchor{3eab}
@deffn {C 函数} PyObject* PyImport_ReloadModule (PyObject@w{ }*m)
@emph{Return value: New reference.}
重载一个模块。 返回一个指向被重载模块的新引用，或者在失败时返回 @code{NULL} 并设置一个异常（在此情况下模块仍然会存在）。
@end deffn

@geindex PyImport_AddModuleObject (C 函数)
@anchor{c-api/import c PyImport_AddModuleObject}@anchor{3eac}
@deffn {C 函数} PyObject* PyImport_AddModuleObject (PyObject@w{ }*name)
@emph{Return value: Borrowed reference.}
返回对应于某个模块名称的模块对象。 @emph{name} 参数的形式可以为 @code{package.module}。 如果存在 modules 字典则首先检查该字典，如果找不到，则创建一个新模块并将其插入到 modules 字典。 在失败时返回 @code{NULL} 并设置一个异常。

@cartouche
@quotation 注解 
此函数不会加载或导入指定模块；如果模块还未被加载，你将得到一个空的模块对象。 请使用 @ref{d43,,PyImport_ImportModule()} 或它的某个变体形式来导入模块。 @emph{name} 使用带点号名称的包结构如果尚不存在则不会被创建。
@end quotation
@end cartouche


3.3 新版功能.

@end deffn

@geindex PyImport_AddModule (C 函数)
@anchor{c-api/import c PyImport_AddModule}@anchor{3d77}
@deffn {C 函数} PyObject* PyImport_AddModule (const char@w{ }*name)
@emph{Return value: Borrowed reference.}
类似于 @ref{3eac,,PyImport_AddModuleObject()}，但其名称为 UTF-8 编码的字符串而不是 Unicode 对象。object.
@end deffn

@geindex PyImport_ExecCodeModule (C 函数)
@anchor{c-api/import c PyImport_ExecCodeModule}@anchor{3ead}
@deffn {C 函数} PyObject* PyImport_ExecCodeModule (const char@w{ }*name, PyObject@w{ }*co)
@emph{Return value: New reference.}
@geindex 內置函数; compile

给定一个模块名称（可能为 @code{package.module} 形式）和一个从 Pyhon 字节码文件读取或从内置函数 @ref{2ee,,compile()} 获取的代码对象，加载该模块。 返回对该模块对象的新引用，或者如果发生错误则返回 @code{NULL} 并设置一个异常。 在发生错误的情况下 @emph{name} 会从 @ref{109a,,sys.modules} 中被移除，即使 @emph{name} 在进入 @ref{3ead,,PyImport_ExecCodeModule()} 时已存在于 @ref{109a,,sys.modules} 中。 在 @ref{109a,,sys.modules} 中保留未完全初始化的模块是危险的，因为导入这样的模块没有办法知道模块对象是否处于一种未知的（对于模块作业的意图来说可能是已损坏的）状态。

模块的 @ref{1632,,__spec__} 和 @ref{a40,,__loader__} 如果尚未设置的话，将被设置为适当的值。 相应 spec 的加载器（如果已设置）将被设为模块的 @code{__loader__} 而在其他情况下设为 @code{SourceFileLoader} 的实例。

模块的 @ref{1591,,__file__} 属性将被设为代码对象的 @code{co_filename}。 如果适用，@ref{c0d,,__cached__} 也将被设置。

如果模块已被导入则此函数将重载它。 请参阅 @ref{3eab,,PyImport_ReloadModule()} 了解重载模块的预定方式。

如果 @emph{name} 指向一个形式为 @code{package.module} 的带点号的名称，则任何尚未创建的包结构仍然不会被创建。

另请参阅 @ref{3eae,,PyImport_ExecCodeModuleEx()} 和 @ref{3eaf,,PyImport_ExecCodeModuleWithPathnames()}。
@end deffn

@geindex PyImport_ExecCodeModuleEx (C 函数)
@anchor{c-api/import c PyImport_ExecCodeModuleEx}@anchor{3eae}
@deffn {C 函数} PyObject* PyImport_ExecCodeModuleEx (const char@w{ }*name, PyObject@w{ }*co, const char@w{ }*pathname)
@emph{Return value: New reference.}
类似于 @ref{3ead,,PyImport_ExecCodeModule()}，但如果 @emph{pathname} 不为 @code{NULL} 则会被设为模块对象的 @ref{1591,,__file__} 属性的值。

参见 @ref{3eaf,,PyImport_ExecCodeModuleWithPathnames()}。
@end deffn

@geindex PyImport_ExecCodeModuleObject (C 函数)
@anchor{c-api/import c PyImport_ExecCodeModuleObject}@anchor{3eb0}
@deffn {C 函数} PyObject* PyImport_ExecCodeModuleObject (PyObject@w{ }*name, PyObject@w{ }*co, PyObject@w{ }*pathname, PyObject@w{ }*cpathname)
@emph{Return value: New reference.}
类似于 @ref{3eae,,PyImport_ExecCodeModuleEx()}，但如果 @emph{cpathname} 不为 @code{NULL} 则会被设为模块对象的 @ref{c0d,,__cached__} 值。 在三个函数中，这是推荐使用的一个。


3.3 新版功能.

@end deffn

@geindex PyImport_ExecCodeModuleWithPathnames (C 函数)
@anchor{c-api/import c PyImport_ExecCodeModuleWithPathnames}@anchor{3eaf}
@deffn {C 函数} PyObject* PyImport_ExecCodeModuleWithPathnames (const char@w{ }*name, PyObject@w{ }*co, const char@w{ }*pathname, const char@w{ }*cpathname)
@emph{Return value: New reference.}
类似于 @ref{3eb0,,PyImport_ExecCodeModuleObject()}，但 @emph{name}, @emph{pathname} 和 @emph{cpathname} 为 UTF-8 编码的字符串。如果 @emph{pathname} 也被设为 @code{NULL} 则还会尝试根据 @emph{cpathname} 推断出前者的值。


3.2 新版功能.



在 3.3 版更改: 如果只提供了字节码路径则会使用 @ref{3b9f,,imp.source_from_cache()} 来计算源路径。

@end deffn

@geindex PyImport_GetMagicNumber (C 函数)
@anchor{c-api/import c PyImport_GetMagicNumber}@anchor{bfb}
@deffn {C 函数} long PyImport_GetMagicNumber ()

返回 Python 字节码文件（即 @code{.pyc} 文件）的魔数。 此魔数应当存在于字节码文件的开头四个字节中，按照小端字节序。 出错时返回 @code{-1}。


在 3.3 版更改: 失败时返回值 @code{-1}。

@end deffn

@geindex PyImport_GetMagicTag (C 函数)
@anchor{c-api/import c PyImport_GetMagicTag}@anchor{3eb1}
@deffn {C 函数} const char * PyImport_GetMagicTag ()

针对 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} 格式的 Python 字节码文件名返回魔术标签字符串。 请记住在 @code{sys.implementation.cache_tag} 上的值是应当被用来代替此函数的更权威的值。


3.2 新版功能.

@end deffn

@geindex PyImport_GetModuleDict (C 函数)
@anchor{c-api/import c PyImport_GetModuleDict}@anchor{3eb2}
@deffn {C 函数} PyObject* PyImport_GetModuleDict ()
@emph{Return value: Borrowed reference.}
返回用于模块管理的字典 (即 @code{sys.modules})。 请注意这是针对每个解释器的变量。
@end deffn

@geindex PyImport_GetModule (C 函数)
@anchor{c-api/import c PyImport_GetModule}@anchor{52d}
@deffn {C 函数} PyObject* PyImport_GetModule (PyObject@w{ }*name)
@emph{Return value: New reference.}
返回给定名称的已导入模块。 如果模块尚未导入则返回 @code{NULL} 但不会设置错误。 如果查找失败则返回 @code{NULL} 并设置错误。


3.7 新版功能.

@end deffn

@geindex PyImport_GetImporter (C 函数)
@anchor{c-api/import c PyImport_GetImporter}@anchor{3eb3}
@deffn {C 函数} PyObject* PyImport_GetImporter (PyObject@w{ }*path)
@emph{Return value: New reference.}
返回针对一个 @ref{262,,sys.path}/@code{pkg.__path__} 中条目 @emph{path} 的查找器对象，可能会通过 @ref{5a0,,sys.path_importer_cache} 字典来获取。 如果它尚未被缓存，则会遍历 @ref{a46,,sys.path_hooks} 直至找到一个能处理该 path 条目的钩子。 如果没有可用的钩子则返回 @code{None}；这将告知调用方 @ref{162a,,path based finder} 无法为该 path 条目找到查找器。 结果将缓存到 @ref{5a0,,sys.path_importer_cache}。 返回一个指向查找器对象的新引用。
@end deffn

@geindex PyImport_ImportFrozenModuleObject (C 函数)
@anchor{c-api/import c PyImport_ImportFrozenModuleObject}@anchor{3eb4}
@deffn {C 函数} int PyImport_ImportFrozenModuleObject (PyObject@w{ }*name)
@emph{Return value: New reference.}
加载名称为 @emph{name} 的已冻结模块。 成功时返回 @code{1}，如果未找到模块则返回 @code{0}，如果初始化失败则返回 @code{-1} 并设置一个异常。 要在加载成功后访问被导入的模块，请使用 @ref{d43,,PyImport_ImportModule()}。 （请注意此名称有误导性 --- 如果模块已被导入此函数将重载它。）


3.3 新版功能.



在 3.4 版更改: @code{__file__} 属性将不再在模块上设置。

@end deffn

@geindex PyImport_ImportFrozenModule (C 函数)
@anchor{c-api/import c PyImport_ImportFrozenModule}@anchor{3eb5}
@deffn {C 函数} int PyImport_ImportFrozenModule (const char@w{ }*name)

类似于 @ref{3eb4,,PyImport_ImportFrozenModuleObject()}，但其名称为 UTF-8 编码的字符串而不是 Unicode 对象。
@end deffn

@geindex _frozen (C 类型)
@anchor{c-api/import c _frozen}@anchor{3eb6}
@deffn {C 类型} struct _frozen

@geindex freeze utility

这是针对已冻结模块描述器的结构类型定义，与由 @code{freeze} 工具所生成的一致 (请参看 Python 源代码发行版中的 @code{Tools/freeze/})。 其定义可在 @code{Include/import.h} 中找到:

@example
struct _frozen @{
    const char *name;
    const unsigned char *code;
    int size;
@};
@end example
@end deffn

@geindex PyImport_FrozenModules (C 变量)
@anchor{c-api/import c PyImport_FrozenModules}@anchor{246e}
@deffn {C 变量} const struct _frozen* PyImport_FrozenModules

该指针被初始化为指向 @code{struct _frozen} 数组，以 @code{NULL} 或者 0 作为结束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以此来提供动态创建的冻结模块集合。
@end deffn

@geindex PyImport_AppendInittab (C 函数)
@anchor{c-api/import c PyImport_AppendInittab}@anchor{fe7}
@deffn {C 函数} int PyImport_AppendInittab (const char@w{ }*name, PyObject* (*initfunc)(void))

向现有的内置模块表添加一个模块。 这是对 @ref{fe8,,PyImport_ExtendInittab()} 的便捷包装，如果无法扩展表则返回 @code{-1}。 新的模块可使用名称 @emph{name} 来导入，并使用函数 @emph{initfunc} 作为在第一次尝试导入时调用的初始化函数。 此函数应当在 @ref{210,,Py_Initialize()} 之前调用。
@end deffn

@geindex _inittab (C 类型)
@anchor{c-api/import c _inittab}@anchor{3eb7}
@deffn {C 类型} struct _inittab

描述内置模块列表中的一个条目的结构体。 每个结构体都给出了内置在解释器中的某个模块的名称和初始化函数。 名称是一个 ASCII 编码的字符串。 嵌入了 Python 的程序可以使用该结构体的数组来与 @ref{fe8,,PyImport_ExtendInittab()} 相结合以提供额外的内置模块。 该结构体在 @code{Include/import.h} 中被定义为:

@example
struct _inittab @{
    const char *name;           /* ASCII encoded string */
    PyObject* (*initfunc)(void);
@};
@end example
@end deffn

@geindex PyImport_ExtendInittab (C 函数)
@anchor{c-api/import c PyImport_ExtendInittab}@anchor{fe8}
@deffn {C 函数} int PyImport_ExtendInittab (struct _inittab@w{ }*newtab)

将内置模块表添加一组模块。 @emph{newtab} 数组必须以一个包含以 @code{NULL} 作为 @code{name} 字段的岗哨条目结束；未能提供岗哨值会导致内存错误。 成功时返回 @code{0} 或者如果无法分配足够内存来扩展内部表则返回 @code{-1}。 当发生失败时，将不会添加模块到内部表。 此函数必须在 @ref{210,,Py_Initialize()} 之前调用。

如果 Python 要被多次初始化，则 @ref{fe7,,PyImport_AppendInittab()} 或 @ref{fe8,,PyImport_ExtendInittab()} 必须在每次 Python 初始化之前调用。
@end deffn

@node 数据 marshal 操作支持,语句解释及变量编译,导入模块<2>,工具<2>
@anchor{c-api/marshal doc}@anchor{3eb8}@anchor{c-api/marshal data-marshalling-support}@anchor{3eb9}@anchor{c-api/marshal marshalling-utils}@anchor{3eba}
@subsection 数据 marshal 操作支持


这些例程允许 C 代码处理与 @ref{b0,,marshal} 模块所用相同数据格式的序列化对象。 其中有些函数可用来将数据写入这种序列化格式，另一些函数则可用来读取并恢复数据。 用于存储 marshal 数据的文件必须以二进制模式打开。

数字值在存储时会将最低位字节放在开头。

此模块支持两种数据格式版本：第 0 版为历史版本，第 1 版本会在文件和 marshal 反序列化中共享固化的字符串。 第 2 版本会对浮点数使用二进制格式。 @code{Py_MARSHAL_VERSION} 指明了当前文件的格式（当前取值为 2）。

@geindex PyMarshal_WriteLongToFile (C 函数)
@anchor{c-api/marshal c PyMarshal_WriteLongToFile}@anchor{3ebb}
@deffn {C 函数} void PyMarshal_WriteLongToFile (long@w{ }value, FILE@w{ }*file, int@w{ }version)

将一个 @code{long} 整数 @emph{value} 以 marshal 格式写入 @emph{file}。 这将只写入 @emph{value} 最低的 32 位；无论本机 @code{long} 类型的长度如何。 @emph{version} 指明文件格式的版本。

This function can fail, in which case it sets the error indicator.
Use @ref{3d58,,PyErr_Occurred()} to check for that.
@end deffn

@geindex PyMarshal_WriteObjectToFile (C 函数)
@anchor{c-api/marshal c PyMarshal_WriteObjectToFile}@anchor{3ebc}
@deffn {C 函数} void PyMarshal_WriteObjectToFile (PyObject@w{ }*value, FILE@w{ }*file, int@w{ }version)

将一个 Python 对象 @emph{value} 以 marshal 格式写入 @emph{file}。 @emph{version} 指明文件格式的版本。

This function can fail, in which case it sets the error indicator.
Use @ref{3d58,,PyErr_Occurred()} to check for that.
@end deffn

@geindex PyMarshal_WriteObjectToString (C 函数)
@anchor{c-api/marshal c PyMarshal_WriteObjectToString}@anchor{3ebd}
@deffn {C 函数} PyObject* PyMarshal_WriteObjectToString (PyObject@w{ }*value, int@w{ }version)
@emph{Return value: New reference.}
返回一个包含 @emph{value} 的 marshal 表示形式的字节串对象。 @emph{version} 指明文件格式的版本。
@end deffn

以下函数允许读取并恢复存储为 marshal 格式的值。

@geindex PyMarshal_ReadLongFromFile (C 函数)
@anchor{c-api/marshal c PyMarshal_ReadLongFromFile}@anchor{3ebe}
@deffn {C 函数} long PyMarshal_ReadLongFromFile (FILE@w{ }*file)

从打开用于读取的 @code{FILE*} 的对应数据流返回一个 C @code{long}。 使用只函数只能读取 32 位的值，无论本机 @code{long} 类型的长度为何。

发生错误时，将设置适当的异常 (@ref{d3c,,EOFError}) 并返回 @code{-1}。
@end deffn

@geindex PyMarshal_ReadShortFromFile (C 函数)
@anchor{c-api/marshal c PyMarshal_ReadShortFromFile}@anchor{3ebf}
@deffn {C 函数} int PyMarshal_ReadShortFromFile (FILE@w{ }*file)

从打开用于读取的 @code{FILE*} 的对应数据流返回一个 C @code{short}。 使用此函数只能读取 16 位的值，无论本机 @code{short} 类型的长度为何。

发生错误时，将设置适当的异常 (@ref{d3c,,EOFError}) 并返回 @code{-1}。
@end deffn

@geindex PyMarshal_ReadObjectFromFile (C 函数)
@anchor{c-api/marshal c PyMarshal_ReadObjectFromFile}@anchor{3ec0}
@deffn {C 函数} PyObject* PyMarshal_ReadObjectFromFile (FILE@w{ }*file)
@emph{Return value: New reference.}
从打开用于读取的 @code{FILE*} 的对应数据流返回一个 Python 对象。

发生错误时，将设置适当的异常 (@ref{d3c,,EOFError}, @ref{16d,,ValueError} 或 @ref{1ff,,TypeError}) 并返回 @code{NULL}。
@end deffn

@geindex PyMarshal_ReadLastObjectFromFile (C 函数)
@anchor{c-api/marshal c PyMarshal_ReadLastObjectFromFile}@anchor{3ec1}
@deffn {C 函数} PyObject* PyMarshal_ReadLastObjectFromFile (FILE@w{ }*file)
@emph{Return value: New reference.}
从打开用于读取的 @code{FILE*} 的对应数据流返回一个 Python 对象。 不同于 @ref{3ec0,,PyMarshal_ReadObjectFromFile()}，此函数假定将不再从该文件读取更多的对象，允许其将文件数据积极地载入内存，以便反序列化过程可以在内存中的数据上操作而不是每次从文件读取一个字节。 只有当你确定不会再从文件读取任何内容时方可使用此形式。

发生错误时，将设置适当的异常 (@ref{d3c,,EOFError}, @ref{16d,,ValueError} 或 @ref{1ff,,TypeError}) 并返回 @code{NULL}。
@end deffn

@geindex PyMarshal_ReadObjectFromString (C 函数)
@anchor{c-api/marshal c PyMarshal_ReadObjectFromString}@anchor{3ec2}
@deffn {C 函数} PyObject* PyMarshal_ReadObjectFromString (const char@w{ }*data, Py_ssize_t@w{ }len)
@emph{Return value: New reference.}
从包含指向 @emph{data} 的 @emph{len} 个字节的字节缓冲区对应的数据流返回一个 Python 对象。

发生错误时，将设置适当的异常 (@ref{d3c,,EOFError}, @ref{16d,,ValueError} 或 @ref{1ff,,TypeError}) 并返回 @code{NULL}。
@end deffn

@node 语句解释及变量编译,字符串转换与格式化,数据 marshal 操作支持,工具<2>
@anchor{c-api/arg doc}@anchor{3ec3}@anchor{c-api/arg arg-parsing}@anchor{3fb}@anchor{c-api/arg parsing-arguments-and-building-values}@anchor{3ec4}
@subsection 语句解释及变量编译


这些函数在创建你自己的函数时帮助很大。更多说明以及实例可参考说明文档中的 @ref{1361,,扩展和嵌入 Python 解释器} 小节。

这些函数描述的前三个，@ref{39b,,PyArg_ParseTuple()}，@ref{6cb,,PyArg_ParseTupleAndKeywords()}，以及 @ref{1139,,PyArg_Parse()}，它们都使用 @emph{格式化字符串} 来将函数期待的参数告知函数。这些函数都使用相同语法规则的格式化字符串。

@menu
* 解析参数: 解析参数<3>. 
* 创建变量:: 

@end menu

@node 解析参数<3>,创建变量,,语句解释及变量编译
@anchor{c-api/arg parsing-arguments}@anchor{3ec5}
@subsubsection 解析参数


一个格式化字符串包含 0 或者更多的格式单元。一个格式单元用来描述一个 Python 对象；它通常是一个字符或者由括号括起来的格式单元序列。除了少数例外，一个非括号序列的格式单元通常对应这些函数的具有单一地址的参数。在接下来的描述中，双引号内的表达式是格式单元；圆括号 () 内的是对应这个格式单元的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)类型。

@menu
* 字符串和缓存区:: 
* 数字: 数字<2>. 
* 其他对象:: 
* API 函数:: 

@end menu

@node 字符串和缓存区,数字<2>,,解析参数<3>
@anchor{c-api/arg strings-and-buffers}@anchor{3ec6}
@subsubsection 字符串和缓存区


这些格式允许将对象按照连续的内存块形式进行访问。你没必要提供返回的 unicode 字符或者字节区的原始数据存储。

一般的，当一个表达式设置一个指针指向一个缓冲区，这个缓冲区可以被相应的 Python 对象管理，并且这个缓冲区共享这个对象的生存周期。你不需要人为的释放任何内存空间。除了这些 @code{es}, @code{es#}, @code{et} and @code{et#}.

然而，当一个 @ref{bf7,,Py_buffer} 结构被赋值，其包含的缓冲区被锁住，所以调用者在随后使用这个缓冲区，即使在 @ref{3d7d,,Py_BEGIN_ALLOW_THREADS} 块中，可以避免可变数据因为调整大小或者被销毁所带来的风险。因此，@strong{你不得不调用} @ref{e21,,PyBuffer_Release()} 在你结束数据的处理时(或者在之前任何中断事件中)

除非另有说明，缓冲区是不会以空终止的。

某些格式需要只读的 @ref{6e9,,bytes-like object}，并设置指针而不是缓冲区结构。 他们通过检查对象的 @ref{3ec7,,PyBufferProcs.bf_releasebuffer} 字段是否为 @code{NULL} 来发挥作用，该字段不允许为 @ref{173,,bytearray} 这样的可变对象。

@cartouche
@quotation 注解 
所有 @code{#} 表达式的变式(@code{s#}，@code{y#}，等等)，长度参数的类型(整型或者 @ref{391,,Py_ssize_t})在包含 @code{Python.h} 头文件之前由 @code{PY_SSIZE_T_CLEAN} 宏的定义控制。如果这个宏被定义，长度是一个 @ref{391,,Py_ssize_t} Python 元大小类型而不是一个 @code{int} 整型。在未来的 Python 版本中将会改变，只支持 @ref{391,,Py_ssize_t} 而放弃支持 @code{int} 整型。最好一直定义 @code{PY_SSIZE_T_CLEAN} 这个宏。
@end quotation
@end cartouche


@table @asis

@item @code{s} (@ref{206,,str}) [const char *]

将一个 Unicode 对象转换成一个指向字符串的 C 指针。一个指针指向一个已经存在的字符串，这个字符串存储的是传如的字符指针变量。C 字符串是已空结束的。Python 字符串不能包含嵌入的无效的代码点；如果由，一个 @ref{16d,,ValueError} 异常会被引发。Unicode 对象被转化成 @code{'utf-8'} 编码的 C 字符串。如果转换失败，一个 @ref{d0b,,UnicodeError} 异常被引发。

@cartouche
@quotation 注解 
这个表达式不接受 @ref{6e9,,bytes-like objects}。如果你想接受文件系统路径并将它们转化成 C 字符串，建议使用 @code{O&} 表达式配合 @ref{6cf,,PyUnicode_FSConverter()} 作为 @emph{转化函数}。
@end quotation
@end cartouche


在 3.5 版更改: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引发 @ref{1ff,,TypeError} 。


@item @code{s*} (@ref{206,,str} or @ref{6e9,,bytes-like object}) [Py_buffer]

这个表达式既接受 Unicode 对象也接受类字节类型对象。它为由调用者提供的 @ref{bf7,,Py_buffer} 结构赋值。这里结果的 C 字符串可能包含嵌入的 NUL 字节。Unicode 对象通过 @code{'utf-8'} 编码转化成 C 字符串。

@item @code{s#} (@ref{206,,str}, 只读 @ref{6e9,,bytes-like object}) [const char *, int or @ref{391,,Py_ssize_t}]

像 @code{s*}，除了它不接受易变的对象。结果存储在两个 C 变量中，第一个是指向 C 字符串的指针，第二个是它的长度。字符串可能包含嵌入的 null 字节。Unicode 对象都被通过 @code{'utf-8'} 编码转化成 C 字符串。

@item @code{z} (@ref{206,,str} or @code{None}) [const char *]

与 @code{s} 类似，但 Python 对象也可能为 @code{None}，在这种情况下，C 指针设置为 @code{NULL}。

@item @code{z*} (@ref{206,,str}, @ref{6e9,,bytes-like object} or @code{None}) [Py_buffer]

与 @code{s*} 类似，但 Python 对象也可能为 @code{None}，在这种情况下，@ref{bf7,,Py_buffer} 结构的 @code{buf} 成员设置为 @code{NULL}。

@item @code{z#} (@ref{206,,str}, 只读 @ref{6e9,,bytes-like object} 或 @code{None}) [const char *, int 或 @ref{391,,Py_ssize_t}]

与 @code{s#} 类似，但 Python 对象也可能为 @code{None}，在这种情况下，C 指针设置为 @code{NULL}。

@item @code{y} (read-only @ref{6e9,,bytes-like object}) [const char *]

这个表达式将一个类字节类型对象转化成一个指向字符串的 C 指针；它不接受 Unicode 对象。字节缓存区必须不包含嵌入的 null 字节；如果包含了 null 字节，会引发一个 @ref{16d,,ValueError} 异常。


在 3.5 版更改: 以前，当字节缓冲区中遇到了嵌入的 null 字节会引发 @ref{1ff,,TypeError} 。


@item @code{y*} (@ref{6e9,,bytes-like object}) [Py_buffer]

@code{s*} 的变式，不接受 Unicode 对象，只接受类字节类型变量。@strong{这是接受二进制数据的推荐方法。}

@item @code{y#} (只读 @ref{6e9,,bytes-like object}) [const char *, int 或 @ref{391,,Py_ssize_t}]

@code{s#} 的变式，不接受 Unicode 对象，只接受类字节类型变量。

@item @code{S} (@ref{172,,bytes}) [PyBytesObject *]

要求 Python 对象为 @ref{172,,bytes} 对象，不尝试进行任何转换。 如果该对象不为 bytes 对象则会引发 @ref{1ff,,TypeError}。 C 变量也可被声明为 @ref{5bd,,PyObject*} 类型。

@item @code{Y} (@ref{173,,bytearray}) [PyByteArrayObject *]

要求 Python 对象为 @ref{173,,bytearray} 对象，不尝试进行任何转换。 如果该对象不为 @ref{173,,bytearray} 对象则会引发 @ref{1ff,,TypeError}。 C 变量也可被声明为 @ref{5bd,,PyObject*} 类型。

@item @code{u} (@ref{206,,str}) [const Py_UNICODE *]

将一个 Python Unicode 对象转化成指向一个以空终止的 Unicode 字符缓冲区的指针。你必须传入一个 @ref{bce,,Py_UNICODE} 指针变量的地址，存储了一个指向已经存在的 Unicode 缓冲区的指针。请注意一个 @ref{bce,,Py_UNICODE} 类型的字符宽度取决于编译选项(16 位或者 32 位)。Python 字符串必须不能包含嵌入的 null 代码点；如果有，引发一个 @ref{16d,,ValueError} 异常。


在 3.5 版更改: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引发 @ref{1ff,,TypeError} 。



Deprecated since version 3.3, will be removed in version 3.12: 这是旧版样式 @ref{bce,,Py_UNICODE} API; 请迁移至 @ref{544,,PyUnicode_AsWideCharString()}.


@item @code{u#} (@ref{206,,str}) [const Py_UNICODE *, int 或 @ref{391,,Py_ssize_t}]

@code{u} 的变式，存储两个 C 变量，第一个指针指向一个 Unicode 数据缓存区，第二个是它的长度。它允许 null 代码点。


Deprecated since version 3.3, will be removed in version 3.12: 这是旧版样式 @ref{bce,,Py_UNICODE} API; 请迁移至 @ref{544,,PyUnicode_AsWideCharString()}.


@item @code{Z} (@ref{206,,str} 或 @code{None}) [const Py_UNICODE *]

与 @code{u} 类似，但 Python 对象也可能为 @code{None}，在这种情况下 @ref{bce,,Py_UNICODE} 指针设置为 @code{NULL}。


Deprecated since version 3.3, will be removed in version 3.12: 这是旧版样式 @ref{bce,,Py_UNICODE} API; 请迁移至 @ref{544,,PyUnicode_AsWideCharString()}.


@item @code{Z#} (@ref{206,,str} 或 @code{None}) [const Py_UNICODE *, int 或 @ref{391,,Py_ssize_t}]

与 @code{u#} 类似，但 Python 对象也可能为 @code{None}，在这种情况下 @ref{bce,,Py_UNICODE} 指针设置为 @code{NULL}。


Deprecated since version 3.3, will be removed in version 3.12: 这是旧版样式 @ref{bce,,Py_UNICODE} API; 请迁移至 @ref{544,,PyUnicode_AsWideCharString()}.


@item @code{U} (@ref{206,,str}) [PyObject *]

要求 Python 对象为 Unicode 对象，不尝试进行任何转换。 如果该对象不为 Unicode 对象则会引发 @ref{1ff,,TypeError}。 C 变量也可被声明为 @ref{5bd,,PyObject*}。

@item @code{w*} (可读写 @ref{6e9,,bytes-like object}) [Py_buffer]

这个表达式接受任何实现可读写缓存区接口的对象。它为调用者提供的 @ref{bf7,,Py_buffer} 结构赋值。缓冲区可能存在嵌入的 null 字节。当缓冲区使用完后调用者需要调用 @ref{e21,,PyBuffer_Release()}。

@item @code{es} (@ref{206,,str}) [const char *encoding, char **buffer]

@code{s} 的变式，它将编码后的 Unicode 字符存入字符缓冲区。它只处理没有嵌 NUL 字节的已编码数据。

此格式需要两个参数。 第一个仅用作输入，并且必须为 @code{const char*}，它指向一个以 NUL 结束的字符串表示的编码格式名称，或者为 @code{NULL}，这表示使用 @code{'utf-8'} 编码格式。 如果为 Python 无法识别的编码格式名称则会引发异常。 第二个参数必须为 @code{char**}；它所引用的指针值将被设为带有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码。

@ref{39b,,PyArg_ParseTuple()} 会分配一个足够大小的缓冲区，将编码后的数据拷贝进这个缓冲区并且设置 @emph{*buffer} 引用这个新分配的内存空间。调用者有责任在使用后调用 @ref{e76,,PyMem_Free()} 去释放已经分配的缓冲区。

@item @code{et} (@ref{206,,str}, @ref{172,,bytes} or @ref{173,,bytearray}) [const char *encoding, char **buffer]

和 @code{es} 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参数是编码后的字符串类型。

@item @code{es#} (@ref{206,,str}) [const char *encoding, char **buffer, int 或 @ref{391,,Py_ssize_t} *buffer_length]

@code{s#} 的变式，它将已编码的 Unicode 字符存入字符缓冲区。不像 @code{es} 表达式，它允许传入的数据包含 NUL 字符。

它需要三个参数。 第一个仅用作输入，并且必须为 @code{const char*}，它指向一个编码格式名称，形式为以 NUL 结束的字符串或 @code{NULL}，在后一种情况下将使用 @code{'utf-8'} 编码格式。 如果编码格式名称无法被 Python 识别则会引发异常。 第二个参数必须为 @code{char**}；它所引用的指针值将被设为带有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码。 第三个参数必须为指向一个整数的指针；被引用的整数将被设为输出缓冲区中的字节数。

有两种操作方式：

如果 @emph{*buffer} 指向 @code{NULL} 指针，则函数将分配所需大小的缓冲区，将编码的数据复制到此缓冲区，并设置 @emph{*buffer} 以引用新分配的存储。 呼叫者负责调用 @ref{e76,,PyMem_Free()} 以在使用后释放分配的缓冲区。

如果 @emph{*buffer} 指向非 @code{NULL} 指针（已分配的缓冲区），则 @ref{39b,,PyArg_ParseTuple()} 将使用此位置作为缓冲区，并将 @emph{*buffer_length} 的初始值解释为缓冲区大小。 然后，它将将编码的数据复制到缓冲区，并终止它。 如果缓冲区不够大，将设置一个 @ref{16d,,ValueError}。

在这两个例子中，@emph{*buffer_length} 被设置为编码后结尾不为 NUL 的数据的长度。

@item @code{et#} (@ref{206,,str}, @ref{172,,bytes} 或 @ref{173,,bytearray}) [const char *encoding, char **buffer, int 或 @ref{391,,Py_ssize_t} *buffer_length]

和 @code{es#} 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参数是编码后的字符串类型。
@end table

@node 数字<2>,其他对象,字符串和缓存区,解析参数<3>
@anchor{c-api/arg numbers}@anchor{3ec8}
@subsubsection 数字



@table @asis

@item @code{b} (@ref{205,,int}) [unsigned char]

将一个非负的 Python 整型转化成一个无符号的微整型，存储在一个 C @code{unsigned char} 类型中。

@item @code{B} (@ref{205,,int}) [unsigned char]

将一个 Python 整型转化成一个微整型并不检查溢出问题，存储在一个 C @code{unsigned char} 类型中。

@item @code{h} (@ref{205,,int}) [short int]

将一个 Python 整型转化成一个 C @code{short int} 短整型。

@item @code{H} (@ref{205,,int}) [unsigned short int]

将一个 Python 整型转化成一个 C @code{unsigned short int} 无符号短整型，并不检查溢出问题。

@item @code{i} (@ref{205,,int}) [int]

将一个 Python 整型转化成一个 C @code{int} 整型。

@item @code{I} (@ref{205,,int}) [unsigned int]

将一个 Python 整型转化成一个 C @code{unsigned int} 无符号整型，并不检查溢出问题。

@item @code{l} (@ref{205,,int}) [long int]

将一个 Python 整型转化成一个 C @code{long int} 长整型。

@item @code{k} (@ref{205,,int}) [unsigned long]

将一个Python整型转化成一个C @code{unsigned long int} 无符号长整型，并不检查溢出问题。

@item @code{L} (@ref{205,,int}) [long long]

将一个 Python 整型转化成一个 C @code{long long} 长长整型。

@item @code{K} (@ref{205,,int}) [unsigned long long]

将一个 Python 整型转化成一个 C @code{unsigned long long} 无符号长长整型，并不检查溢出问题。

@item @code{n} (@ref{205,,int}) [@ref{391,,Py_ssize_t}]

将一个 Python 整型转化成一个 C @ref{391,,Py_ssize_t} Python 元大小类型。

@item @code{c} (@ref{172,,bytes} 或者 @ref{173,,bytearray} 长度为 1) [char]

将一个 Python 字节类型，如一个长度为 1 的 @ref{172,,bytes} 或者 @ref{173,,bytearray} 对象，转化成一个 C @code{char} 字符类型。


在 3.3 版更改: 允许 @ref{173,,bytearray} 类型的对象。


@item @code{C} (@ref{206,,str} 长度为 1) [int]

将一个 Python 字符，如一个长度为 1 的 @ref{206,,str} 字符串对象，转化成一个 C @code{int} 整型类型。

@item @code{f} (@ref{1fe,,float}) [float]

将一个 Python 浮点数转化成一个 C @code{float} 浮点数。

@item @code{d} (@ref{1fe,,float}) [double]

将一个Python浮点数转化成一个C @code{double} 双精度浮点数。

@item @code{D} (@ref{2c8,,complex}) [Py_complex]

将一个 Python 复数类型转化成一个 C @ref{3ec9,,Py_complex} Python 复数类型。
@end table

@node 其他对象,API 函数,数字<2>,解析参数<3>
@anchor{c-api/arg other-objects}@anchor{3eca}
@subsubsection 其他对象



@table @asis

@item @code{O} (object) [PyObject *]

将 Python 对象（不进行任何转换）存储在 C 对象指针中。 因此，C 程序接收已传递的实际对象。 对象的引用计数不会增加。 存储的指针不是 @code{NULL}。

@item @code{O!} (object) [@emph{typeobject}, PyObject *]

将一个 Python 对象存入一个 C 对象指针。 这类似于 @code{O}，但是接受两个 C 参数：第一个是 Python 类型对象的地址，第二个是存储对象指针的 C 变量 (类型为 @ref{5bd,,PyObject*}) 的地址。 如果 Python 对象不具有所要求的类型，则会引发 @ref{1ff,,TypeError}。
@end table
@anchor{c-api/arg o-ampersand}@anchor{3ecb}

@table @asis

@item @code{O&} (object) [@emph{converter}, @emph{anything}]

通过一个 @emph{converter} 函数将一个 Python 对象转换为一个 C 变量。 此函数接受两个参数：第一个是函数，第二个是 C 变量 (类型任意) 的地址，转换为 @code{void *} 类型。 @emph{converter} 函数将以如下方式被调用:

@example
status = converter(object, address);
@end example

其中 @emph{object} 是待转换的 Python 对象而 @emph{address} 为传给 @ref{1139,,PyArg_Parse*()} 函数的 @code{void*} 参数。 返回的 @emph{status} 应当以 @code{1} 代表转换成功而以 @code{0} 代表转换失败。 当转换失败时，@emph{converter} 函数应当引发异常并且会让 @emph{address} 的内容保持未修改状态。

如果 @emph{converter} 返回 @code{Py_CLEANUP_SUPPORTED}，则如果参数解析最终失败，它可能会再次调用该函数，从而使转换器有机会释放已分配的任何内存。在第二个调用中，@emph{object} 参数将为 @code{NULL};因此，该参数将为 @code{NULL};因此，该参数将为 @code{NULL}，因此，该参数将为 @code{NULL`@w{`}（如果值）为 `@w{`}NULL} @emph{address} 的值与原始呼叫中的值相同。


在 3.1 版更改: @code{Py_CLEANUP_SUPPORTED} 被添加。


@item @code{p} (@ref{2c4,,bool}) [int]

测试传入的值是否为真(一个布尔判断)并且将结果转化为相对应的 C true/false 整型值。如果表达式为真置 @code{1}，假则置 @code{0}。它接受任何合法的 Python 值。参见 @ref{1748,,逻辑值检测} 获取更多关于 Python 如何测试值为真的信息。


3.3 新版功能.


@item @code{(items)} (@ref{1a2,,tuple}) [@emph{matching-items}]

对象必须是 Python 序列，它的长度是 @emph{items} 中格式单元的数量。C 参数必须对应 @emph{items} 中每一个独立的格式单元。序列中的格式单元可能有嵌套。
@end table

传递 "long" 整型(整型的值超过了平台的 @code{LONG_MAX} 限制)是可能的，然而没有进行适当的范围检测——当接收字段太小而接收不到值时，最重要的位被静默地截断(实际上，C 语言会在语义继承的基础上强制类型转换——期望的值可能会发生变化)。

格式化字符串中还有一些其他的字符具有特殊的涵义。这些可能并不嵌套在圆括号中。它们是：


@table @asis

@item @code{|}

表明在 Python 参数列表中剩下的参数都是可选的。C 变量对应的可选参数需要初始化为默认值——当一个可选参数没有指定时， @ref{39b,,PyArg_ParseTuple()}  不能访问相应的 C 变量(变量集)的内容。

@item @code{$}

@ref{6cb,,PyArg_ParseTupleAndKeywords()} only：表明在 Python 参数列表中剩下的参数都是强制关键字参数。当前，所有强制关键字参数都必须也是可选参数，所以格式化字符串中  @code{|} 必须一直在 @code{$} 前面。


3.3 新版功能.


@item @code{:}

格式单元的列表结束标志；冒号后的字符串被用来作为错误消息中的函数名(@ref{39b,,PyArg_ParseTuple()} 函数引发的“关联值”异常)。

@item @code{;}

格式单元的列表结束标志；分号后的字符串被用来作为错误消息取代默认的错误消息。 @code{:} 和 @code{;} 相互排斥。
@end table

注意任何由调用者提供的 Python 对象引用是 @emph{借来的} 引用；不要递减它们的引用计数！

传递给这些函数的附加参数必须是由格式化字符串确定的变量的地址；这些都是用来存储输入元组的值。有一些情况，如上面的格式单元列表中所描述的，这些参数作为输入值使用；在这种情况下，它们应该匹配指定的相应的格式单元。

为了转换成功，@emph{arg} 对象必须匹配格式并且格式必须用尽。成功的话，@ref{1139,,PyArg_Parse*()} 函数返回 true，反之它们返回 false 并且引发一个合适的异常。当 @ref{1139,,PyArg_Parse*()} 函数因为某一个格式单元转化失败而失败时，对应的以及后续的格式单元地址内的变量都不会被使用。

@node API 函数,,其他对象,解析参数<3>
@anchor{c-api/arg api-functions}@anchor{3ecc}
@subsubsection API 函数


@geindex PyArg_ParseTuple (C 函数)
@anchor{c-api/arg c PyArg_ParseTuple}@anchor{39b}
@deffn {C 函数} int PyArg_ParseTuple (PyObject@w{ }*args, const char@w{ }*format, ...)

解析一个函数的参数，表达式中的参数按参数位置顺序存入局部变量中。成功返回 true；失败返回 false 并且引发相应的异常。
@end deffn

@geindex PyArg_VaParse (C 函数)
@anchor{c-api/arg c PyArg_VaParse}@anchor{3ecd}
@deffn {C 函数} int PyArg_VaParse (PyObject@w{ }*args, const char@w{ }*format, va_list@w{ }vargs)

和 @ref{39b,,PyArg_ParseTuple()} 相同，然而它接受一个 va_list 类型的参数而不是可变数量的参数集。
@end deffn

@geindex PyArg_ParseTupleAndKeywords (C 函数)
@anchor{c-api/arg c PyArg_ParseTupleAndKeywords}@anchor{6cb}
@deffn {C 函数} int PyArg_ParseTupleAndKeywords (PyObject@w{ }*args, PyObject@w{ }*kw, const char@w{ }*format, char@w{ }*keywords[], ...)

分析将位置参数和关键字参数同时转换为局部变量的函数的参数。 @emph{keywords} 参数是关键字参数名称的 @code{NULL} 终止数组。 空名称表示 @ref{3d1,,positional-only parameters}。成功时返回 true;发生故障时，它将返回 false 并引发相应的异常。


在 3.6 版更改: 添加了 @ref{3d1,,positional-only parameters} 的支持。

@end deffn

@geindex PyArg_VaParseTupleAndKeywords (C 函数)
@anchor{c-api/arg c PyArg_VaParseTupleAndKeywords}@anchor{ea6}
@deffn {C 函数} int PyArg_VaParseTupleAndKeywords (PyObject@w{ }*args, PyObject@w{ }*kw, const char@w{ }*format, char@w{ }*keywords[], va_list@w{ }vargs)

和 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 相同，然而它接受一个va_list类型的参数而不是可变数量的参数集。
@end deffn

@geindex PyArg_ValidateKeywordArguments (C 函数)
@anchor{c-api/arg c PyArg_ValidateKeywordArguments}@anchor{3ece}
@deffn {C 函数} int PyArg_ValidateKeywordArguments (PyObject@w{ }*)

确保字典中的关键字参数都是字符串。这个函数只被使用于 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 不被使用的情况下，后者已经不再做这样的检查。


3.2 新版功能.

@end deffn

@c XXX deprecated, will be removed

@geindex PyArg_Parse (C 函数)
@anchor{c-api/arg c PyArg_Parse}@anchor{1139}
@deffn {C 函数} int PyArg_Parse (PyObject@w{ }*args, const char@w{ }*format, ...)

函数被用来析构“旧类型”函数的参数列表——这些函数使用的 @code{METH_OLDARGS} 参数解析方法已从 Python 3 中移除。这不被推荐用于新代码的参数解析，并且在标准解释器中的大多数代码已被修改，已不再用于该目的。它仍然方便于分解其他元组，然而可能因为这个目的被继续使用。
@end deffn

@geindex PyArg_UnpackTuple (C 函数)
@anchor{c-api/arg c PyArg_UnpackTuple}@anchor{f10}
@deffn {C 函数} int PyArg_UnpackTuple (PyObject@w{ }*args, const char@w{ }*name, Py_ssize_t@w{ }min, Py_ssize_t@w{ }max, ...)

一个更简单的参数提取方式，它不使用格式字符串来指定参数类型。 使用这种方法来提取参数的函数应当在函数或方法表中被声明为 @ref{f12,,METH_VARARGS}。 包含实际参数的元组应当作为 @emph{args} 传入；它必须确实是一个元组。 元组的长度必须至少为 @emph{min} 并且不超过 @emph{max}；@emph{min} 和 @emph{max} 可能相等。 额外的参数必须被传入函数，每个参数必须是一个指向 @ref{5bd,,PyObject*} 变量的指针；它们将以来自 @emph{args} 的值填充；它们将包含暂借的引用。 对应于可选参数的变量不会由 @emph{args} 给出的值填充；它们将由调用者来初始化。 此函数执行成功时返回真值，如果 @emph{args} 不是元组或者包含错误数量的元素则返回假值；如果执行失败则将设置一个异常。

这是一个使用此函数的示例，取自 @code{_weakref} 帮助模块用来弱化引用的源代码：

@example
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
@{
    PyObject *object;
    PyObject *callback = NULL;
    PyObject *result = NULL;

    if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) @{
        result = PyWeakref_NewRef(object, callback);
    @}
    return result;
@}
@end example

这个例子中调用 @ref{f10,,PyArg_UnpackTuple()} 完全等价于调用 @ref{39b,,PyArg_ParseTuple()}:

@example
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
@end example
@end deffn

@node 创建变量,,解析参数<3>,语句解释及变量编译
@anchor{c-api/arg building-values}@anchor{3ecf}
@subsubsection 创建变量


@geindex Py_BuildValue (C 函数)
@anchor{c-api/arg c Py_BuildValue}@anchor{3f9}
@deffn {C 函数} PyObject* Py_BuildValue (const char@w{ }*format, ...)
@emph{Return value: New reference.}
基于类似于 @ref{1139,,PyArg_Parse*()} 函数系列和一系列值的格式字符串创建新值。 在出现错误时返回值或 @code{NULL};如果返回 @code{NULL}，将引发异常。

@ref{3f9,,Py_BuildValue()} 并不一直创建一个元组。只有当它的格式化字符串包含两个或更多的格式单元才会创建一个元组。如果格式化字符串是空，它返回 @code{None}；如果它包含一个格式单元，它返回由格式单元描述的的任一对象。用圆括号包裹格式化字符串可以强制它返回一个大小为 0 或者 1 的元组。

当内存缓存区的数据以参数形式传递用来构建对象时，如 @code{s} 和 @code{s#} 格式单元，会拷贝需要的数据。调用者提供的缓冲区从来都不会被由 @ref{3f9,,Py_BuildValue()} 创建的对象来引用。换句话说，如果你的代码调用 @code{malloc()} 并且将分配的内存空间传递给 @ref{3f9,,Py_BuildValue()}，你的代码就有责任在 @ref{3f9,,Py_BuildValue()} 返回时调用 @code{free()} 。

在下面的描述中，双引号的表达式使格式单元；圆括号 () 内的是格式单元将要返回的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)的类型。

字符例如空格，制表符，冒号和逗号在格式化字符串中会被忽略(但是不包括格式单元，如 @code{s#})。这可以使很长的格式化字符串具有更好的可读性。


@table @asis

@item @code{s} (@ref{206,,str} 或 @code{None}) [const char *]

使用 @code{'utf-8'} 编码将空终止的 C 字符串转换为 Python @ref{206,,str} 对象。如果 C 字符串指针为 @code{NULL}，则使用 @code{None}。

@item @code{s#} (@ref{206,,str} 或 @code{None}) [const char *, int 或 @ref{391,,Py_ssize_t}]

使用 @code{'utf-8'} 编码将 C 字符串及其长度转换为 Python @ref{206,,str} 对象。如果 C 字符串指针为 @code{NULL}，则长度将被忽略，并返回 @code{None}。

@item @code{y} (@ref{172,,bytes}) [const char *]

这将 C 字符串转换为 Python @ref{172,,bytes} 对象。 如果 C 字符串指针为 @code{NULL}，则返回 @code{None}。

@item @code{y#} (@ref{172,,bytes}) [const char *, int 或 @ref{391,,Py_ssize_t}]

这会将 C 字符串及其长度转换为一个 Python 对象。 如果该 C 字符串指针为 @code{NULL}，则返回 @code{None}。

@item @code{z} (@ref{206,,str} or @code{None}) [const char *]

和 @code{s} 一样。

@item @code{z#} (@ref{206,,str} 或 @code{None}) [const char *, int 或 @ref{391,,Py_ssize_t}]

和 @code{s#} 一样。

@item @code{u} (@ref{206,,str}) [const wchar_t *]

将空终止的 @code{wchar_t} 的 Unicode （UTF-16 或 UCS-4） 数据缓冲区转换为 Python Unicode 对象。 如果 Unicode 缓冲区指针为 @code{NULL}，则返回 @code{None}。

@item @code{u#} (@ref{206,,str}) [const wchar_t *, int 或 @ref{391,,Py_ssize_t}]

将 Unicode （UTF-16 或 UCS-4） 数据缓冲区及其长度转换为 Python Unicode 对象。  如果 Unicode 缓冲区指针为 @code{NULL}，则长度将被忽略，并返回 @code{None}。

@item @code{U} (@ref{206,,str} 或 @code{None}) [const char *]

和 @code{s} 一样。

@item @code{U#} (@ref{206,,str} 或 @code{None}) [const char *, int 或 @ref{391,,Py_ssize_t}]

和 @code{s#} 一样。

@item @code{i} (@ref{205,,int}) [int]

将一个 C @code{int} 整型转化成 Python 整型对象。

@item @code{b} (@ref{205,,int}) [char]

将一个 C @code{char} 字符型转化成 Python 整型对象。

@item @code{h} (@ref{205,,int}) [short int]

将一个 C @code{short int} 短整型转化成 Python 整型对象。

@item @code{l} (@ref{205,,int}) [long int]

将一个 C @code{long int} 长整型转化成 Python 整型对象。

@item @code{B} (@ref{205,,int}) [unsigned char]

将一个 C @code{unsigned char} 无符号字符型转化成 Python 整型对象。

@item @code{H} (@ref{205,,int}) [unsigned short int]

将一个 C @code{unsigned long} 无符号短整型转化成 Python 整型对象。

@item @code{I} (@ref{205,,int}) [unsigned int]

将一个 C @code{unsigned long} 无符号整型转化成 Python 整型对象。

@item @code{k} (@ref{205,,int}) [unsigned long]

将一个 C @code{unsigned long} 无符号长整型转化成 Python 整型对象。

@item @code{L} (@ref{205,,int}) [long long]

将一个 C @code{long long} 长长整形转化成 Python 整形对象。

@item @code{K} (@ref{205,,int}) [unsigned long long]

将一个 C @code{unsigned long long} 无符号长长整型转化成 Python 整型对象。

@item @code{n} (@ref{205,,int}) [@ref{391,,Py_ssize_t}]

将一个 C @ref{391,,Py_ssize_t} 类型转化为 Python 整型。

@item @code{c} (@ref{172,,bytes} 长度为1 ) [char]

将一个 C @code{int} 整型代表的字符转化为 Python @ref{172,,bytes} 长度为 1 的字节对象。

@item @code{C} (@ref{206,,str} 长度为 1) [int]

将一个 C @code{int} 整型代表的字符转化为 Python @ref{206,,str} 长度为 1 的字符串对象。

@item @code{d} (@ref{1fe,,float}) [double]

将一个 C @code{double} 双精度浮点数转化为 Python 浮点数类型数字。

@item @code{f} (@ref{1fe,,float}) [float]

将一个 C @code{float} 单精度浮点数转化为 Python 浮点数类型数字。

@item @code{D} (@ref{2c8,,complex}) [Py_complex *]

将一个 C @ref{3ec9,,Py_complex} 类型的结构转化为 Python 复数类型。

@item @code{O} (object) [PyObject *]

将 Python 对象传递不变（其引用计数除外，该计数由 1 递增）。 如果传入的对象是 @code{NULL} 指针，则假定这是由于生成参数的调用发现错误并设置异常而引起的。因此，@ref{3f9,,Py_BuildValue()} 将返回 @code{NULL}，但不会引发异常。 如果尚未引发异常，则设置 @ref{6fc,,SystemError}。

@item @code{S} (object) [PyObject *]

和 @code{O} 相同。

@item @code{N} (object) [PyObject *]

和 @code{O} 相同，然而它并不增加对象的引用计数。当通过调用参数列表中的对象构造器创建对象时很实用。

@item @code{O&} (object) [@emph{converter}, @emph{anything}]

通过 @emph{converter} 函数将 @emph{anything} 转换为 Python 对象。 该函数调用时会传入 @emph{anything} (应与 @code{void*} 兼容) 作为参数并且应当返回一个“新的”Python 对象，或者当发生错误时返回 @code{NULL}。

@item @code{(items)} (@ref{1a2,,tuple}) [@emph{matching-items}]

将一个 C 变量序列转换成 Python 元组并保持相同的元素数量。

@item @code{[items]} (@ref{1f9,,list}) [@emph{相关的元素}]

将一个 C 变量序列转换成 Python 列表并保持相同的元素数量。

@item @code{@{items@}} (@ref{164,,dict}) [@emph{相关的元素}]

将一个C变量序列转换成 Python 字典。每一对连续的 C 变量对作为一个元素插入字典中，分别作为关键字和值。
@end table

如果格式字符串中出现错误，则设置 @ref{6fc,,SystemError} 异常并返回 @code{NULL}。
@end deffn

@geindex Py_VaBuildValue (C 函数)
@anchor{c-api/arg c Py_VaBuildValue}@anchor{3ed0}
@deffn {C 函数} PyObject* Py_VaBuildValue (const char@w{ }*format, va_list@w{ }vargs)
@emph{Return value: New reference.}
和 @ref{3f9,,Py_BuildValue()} 相同，然而它接受一个 va_list 类型的参数而不是可变数量的参数集。
@end deffn

@node 字符串转换与格式化,反射,语句解释及变量编译,工具<2>
@anchor{c-api/conversion doc}@anchor{3ed1}@anchor{c-api/conversion string-conversion}@anchor{3ed2}@anchor{c-api/conversion string-conversion-and-formatting}@anchor{3ed3}
@subsection 字符串转换与格式化


用于数字转换和格式化字符串输出的函数

@geindex PyOS_snprintf (C 函数)
@anchor{c-api/conversion c PyOS_snprintf}@anchor{f13}
@deffn {C 函数} int PyOS_snprintf (char@w{ }*str, size_t@w{ }size, const char@w{ }*format, ...)

根据格式字符串 @emph{format} 和额外参数，输出不超过 @emph{size} 个字节到 @emph{str}。 参见 Unix 手册页面 @code{snprintf(3)}。
@end deffn

@geindex PyOS_vsnprintf (C 函数)
@anchor{c-api/conversion c PyOS_vsnprintf}@anchor{f14}
@deffn {C 函数} int PyOS_vsnprintf (char@w{ }*str, size_t@w{ }size, const char@w{ }*format, va_list@w{ }va)

根据格式字符串 @emph{format} 和变量参数列表 @emph{va}，输出不超过 @emph{size} 个字节到 @emph{str}。 参见 Unix 手册页面 @code{vsnprintf(3)}。
@end deffn

@ref{f13,,PyOS_snprintf()} 和 @ref{f14,,PyOS_vsnprintf()} 包装 C 标准库函数 @code{snprintf()} 和 @code{vsnprintf()} 。它们的目的是保证在极端情况下的一致行为，而标准 C 的函数则不然。

包装器会确保 @code{str[size-1]} 在返回时始终为 @code{'\0'}。 它们从不写入超过 @emph{size} 个字节 (包括末尾的 @code{'\0'}) 到字符串。 两个函数都要求 @code{str != NULL}, @code{size > 0} 和 @code{format != NULL}。

如果平台没有 @code{vsnprintf()} 而且缓冲区大小需要避免截断超出 @emph{size} 512 字节以上，Python 会以一个 @ref{267,,Py_FatalError()} 来中止。

这些函数的返回值（ @emph{rv} ）应按照以下规则被解释：


@itemize *

@item 
当 @code{0 <= rv < size} 时，输出转换即成功并将 @emph{rv} 个字符写入到 @emph{str} (不包括末尾 @code{str[rv]} 位置的 @code{'\0'} 字节)。

@item 
当 @code{rv >= size} 时，输出转换会被截断并且需要一个具有 @code{rv + 1} 字节的缓冲区才能成功执行。 在此情况下 @code{str[size-1]} 为 @code{'\0'}。

@item 
当 @code{rv < 0} 时，"会发生不好的事情。" 在此情况下 @code{str[size-1]} 也为 @code{'\0'}，但 @emph{str} 的其余部分是未定义的。 错误的确切原因取决于底层平台。
@end itemize

以下函数提供与语言环境无关的字符串到数字转换。

@geindex PyOS_string_to_double (C 函数)
@anchor{c-api/conversion c PyOS_string_to_double}@anchor{cf5}
@deffn {C 函数} double PyOS_string_to_double (const char@w{ }*s, char@w{ }**endptr, PyObject@w{ }*overflow_exception)

将字符串 @code{s} 转换为 @code{double} 类型，失败时引发Python异常。接受的字符串的集合对应于被 Python 的 @ref{1fe,,float()} 构造函数接受的字符串的集合，除了 @code{s} 必须没有前导或尾随空格。转换必须独立于当前的区域。

如果 @code{endptr} 是 @code{NULL} ，转换整个字符串。引发 @ref{16d,,ValueError} 并且 返回 @code{-1.0} 如果字符串不是浮点数的有效的表达方式。

如果 @code{endptr} 不是 @code{NULL} ，尽可能多的转换字符串并将 @code{*endptr} 设置为指向第一个未转换的字符。如果字符串的初始段不是浮点数的有效的表达方式，将 @code{*endptr} 设置为指向字符串的开头，引发 ValueError 异常，并且返回 @code{-1.0} 。

如果 @code{s} 表示一个太大而不能存储在一个浮点数中的值（比方说， @code{"1e500"} 在许多平台上是一个字符串）然后如果 @code{overflow_exception} 是 @code{NULL} 返回 @code{Py_HUGE_VAL} （用适当的符号）并且不设置任何异常。 在其他方面， @code{overflow_exception} 必须指向一个 Python 异常对象；引发异常并返回 @code{-1.0} 。在这两种情况下，设置 @code{*endptr} 指向转换值之后的第一个字符。

如果在转换期间发生任何其他错误（比如一个内存不足的错误），设置适当的 Python 异常并且返回 @code{-1.0} 。


3.1 新版功能.

@end deffn

@geindex PyOS_double_to_string (C 函数)
@anchor{c-api/conversion c PyOS_double_to_string}@anchor{3ed4}
@deffn {C 函数} char* PyOS_double_to_string (double@w{ }val, char@w{ }format_code, int@w{ }precision, int@w{ }flags, int@w{ }*ptype)

转换 @code{double} @emph{val} 为一个使用 @emph{format_code}， @emph{precision} 和 @emph{flags} 的字符串

@emph{格式码} 必须是以下其中之一, @code{'e'}, @code{'E'}, @code{'f'}, @code{'F'}, @code{'g'}, @code{'G'} 或者 @code{'r'}。对于 @code{'r'} , 提供的 @emph{精度} 必须是0。@code{'r'} 格式码指定了标准函数 @ref{8c3,,repr()} 格式。

@emph{flags} 可以为零或者其他值 @code{Py_DTSF_SIGN}, @code{Py_DTSF_ADD_DOT_0} 或 @code{Py_DTSF_ALT} 或其组合：


@itemize *

@item 
@code{Py_DTSF_SIGN} 表示总是在返回的字符串前附加一个符号字符，即使 @emph{val} 为非负数。

@item 
@code{Py_DTSF_ADD_DOT_0} 表示确保返回的字符串看起来不像是一个整数。

@item 
@code{Py_DTSF_ALT} 表示应用 "替代的" 格式化规则。 相关细节请参阅 @ref{f13,,PyOS_snprintf()} @code{'#'} 定义文档。
@end itemize

如果 @emph{ptype} 不为 @code{NULL}，则它指向的值将被设为 @code{Py_DTST_FINITE}, @code{Py_DTST_INFINITE} 或 @code{Py_DTST_NAN} 中的一个，分别表示 @emph{val} 是一个有限数字、无限数字或非数字。

返回值是一个指向包含转换后字符串的 @emph{buffer} 的指针，如果转换失败则为 @code{NULL}。 调用方要负责调用 @ref{e76,,PyMem_Free()} 来释放返回的字符串。


3.1 新版功能.

@end deffn

@geindex PyOS_stricmp (C 函数)
@anchor{c-api/conversion c PyOS_stricmp}@anchor{3ed5}
@deffn {C 函数} int PyOS_stricmp (const char@w{ }*s1, const char@w{ }*s2)

字符串不区分大小写。该函数几乎与 @code{strcmp()} 的工作方式相同，只是它忽略了大小写。
@end deffn

@geindex PyOS_strnicmp (C 函数)
@anchor{c-api/conversion c PyOS_strnicmp}@anchor{3ed6}
@deffn {C 函数} int PyOS_strnicmp (const char@w{ }*s1, const char@w{ }*s2, Py_ssize_t @w{ }size)

字符串不区分大小写。该函数几乎与 @code{strncmp()} 的工作方式相同，只是它忽略了大小写。
@end deffn

@node 反射,编解码器注册与支持功能,字符串转换与格式化,工具<2>
@anchor{c-api/reflection doc}@anchor{3ed7}@anchor{c-api/reflection id1}@anchor{3ed8}@anchor{c-api/reflection reflection}@anchor{3ed9}
@subsection 反射


@geindex PyEval_GetBuiltins (C 函数)
@anchor{c-api/reflection c PyEval_GetBuiltins}@anchor{3eda}
@deffn {C 函数} PyObject* PyEval_GetBuiltins (void)
@emph{Return value: Borrowed reference.}
返回当前执行帧中内置函数的字典，如果当前没有帧正在执行，则返回线程状态的解释器。
@end deffn

@geindex PyEval_GetLocals (C 函数)
@anchor{c-api/reflection c PyEval_GetLocals}@anchor{3edb}
@deffn {C 函数} PyObject* PyEval_GetLocals (void)
@emph{Return value: Borrowed reference.}
返回当前执行帧中局部变量的字典，如果没有当前执行的帧则返回 @code{NULL}。
@end deffn

@geindex PyEval_GetGlobals (C 函数)
@anchor{c-api/reflection c PyEval_GetGlobals}@anchor{3edc}
@deffn {C 函数} PyObject* PyEval_GetGlobals (void)
@emph{Return value: Borrowed reference.}
返回当前执行帧中全局变量的字典，如果没有当前执行的帧则返回 @code{NULL}。
@end deffn

@geindex PyEval_GetFrame (C 函数)
@anchor{c-api/reflection c PyEval_GetFrame}@anchor{3edd}
@deffn {C 函数} PyFrameObject* PyEval_GetFrame (void)
@emph{Return value: Borrowed reference.}
返回当前线程状态的帧，如果没有当前执行的帧则返回 @code{NULL}。

另请参阅 @ref{24f,,PyThreadState_GetFrame()}。
@end deffn

@geindex PyFrame_GetBack (C 函数)
@anchor{c-api/reflection c PyFrame_GetBack}@anchor{24b}
@deffn {C 函数} PyFrameObject* PyFrame_GetBack (PyFrameObject@w{ }*frame)

获取 @emph{frame} 为下一个外部帧。

返回一个强引用，如果 @emph{frame} 没有外部帧则返回 @code{NULL}。

@emph{frame} 必须不为 @code{NULL}。


3.9 新版功能.

@end deffn

@geindex PyFrame_GetCode (C 函数)
@anchor{c-api/reflection c PyFrame_GetCode}@anchor{24a}
@deffn {C 函数} PyCodeObject* PyFrame_GetCode (PyFrameObject@w{ }*frame)

获取 @emph{frame} 的代码。

返回一个强引用。

@emph{frame} 必须不为 @code{NULL}。 结果（帧的代码）不能为 @code{NULL}。


3.9 新版功能.

@end deffn

@geindex PyFrame_GetLineNumber (C 函数)
@anchor{c-api/reflection c PyFrame_GetLineNumber}@anchor{24c}
@deffn {C 函数} int PyFrame_GetLineNumber (PyFrameObject@w{ }*frame)

返回 @emph{frame} 当前正在执行的行号。

@emph{frame} 必须不为 @code{NULL}。
@end deffn

@geindex PyEval_GetFuncName (C 函数)
@anchor{c-api/reflection c PyEval_GetFuncName}@anchor{3ede}
@deffn {C 函数} const char* PyEval_GetFuncName (PyObject@w{ }*func)

如果 @emph{func} 是函数、类或实例对象，则返回它的名称，否则返回 @emph{func} 的类型的名称。
@end deffn

@geindex PyEval_GetFuncDesc (C 函数)
@anchor{c-api/reflection c PyEval_GetFuncDesc}@anchor{3edf}
@deffn {C 函数} const char* PyEval_GetFuncDesc (PyObject@w{ }*func)

根据 @emph{func} 的类型返回描述字符串。 返回值包括函数和方法的 "()", " constructor", " instance" 和 " object"。 与 @ref{3ede,,PyEval_GetFuncName()} 的结果连接，结果将是 @emph{func} 的描述。
@end deffn

@node 编解码器注册与支持功能,,反射,工具<2>
@anchor{c-api/codec doc}@anchor{3ee0}@anchor{c-api/codec codec-registry}@anchor{6ef}@anchor{c-api/codec codec-registry-and-support-functions}@anchor{3ee1}
@subsection 编解码器注册与支持功能


@geindex PyCodec_Register (C 函数)
@anchor{c-api/codec c PyCodec_Register}@anchor{3ee2}
@deffn {C 函数} int PyCodec_Register (PyObject@w{ }*search_function)

注册一个新的编解码器搜索函数。

作为副作用，其尝试加载 @code{encodings} 包，如果尚未完成，请确保它始终位于搜索函数列表的第一位。
@end deffn

@geindex PyCodec_KnownEncoding (C 函数)
@anchor{c-api/codec c PyCodec_KnownEncoding}@anchor{3ee3}
@deffn {C 函数} int PyCodec_KnownEncoding (const char@w{ }*encoding)

根据注册的给定 @emph{encoding} 的编解码器是否已存在而返回 @code{1} 或 @code{0}。此函数总能成功。
@end deffn

@geindex PyCodec_Encode (C 函数)
@anchor{c-api/codec c PyCodec_Encode}@anchor{3ee4}
@deffn {C 函数} PyObject* PyCodec_Encode (PyObject@w{ }*object, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
泛型编解码器基本编码 API。

@emph{object} 使用由 @emph{errors} 所定义的错误处理方法传递给定 @emph{encoding} 的编码器函数。 @emph{errors} 可以为 @code{NULL} 表示使用为编码器所定义的默认方法。 如果找不到编码器则会引发 @ref{17c1,,LookupError}。
@end deffn

@geindex PyCodec_Decode (C 函数)
@anchor{c-api/codec c PyCodec_Decode}@anchor{3ee5}
@deffn {C 函数} PyObject* PyCodec_Decode (PyObject@w{ }*object, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
泛型编解码器基本解码 API。

@emph{object} 使用由 @emph{errors} 所定义的错误处理方法传递给定 @emph{encoding} 的解码器函数。 @emph{errors} 可以为 @code{NULL} 表示使用为编解码器所定义的默认方法。 如果找不到编解码器则会引发 @ref{17c1,,LookupError}。
@end deffn

@menu
* Codec 查找API:: 
* 用于Unicode编码错误处理程序的注册表API:: 

@end menu

@node Codec 查找API,用于Unicode编码错误处理程序的注册表API,,编解码器注册与支持功能
@anchor{c-api/codec codec-lookup-api}@anchor{3ee6}
@subsubsection Codec 查找API


在下列函数中，@emph{encoding} 字符串会被查找并转换为小写字母形式，这使得通过此机制查找编码格式实际上对大小写不敏感。 如果未找到任何编解码器，则将设置 @ref{3f1,,KeyError} 并返回 @code{NULL}。

@geindex PyCodec_Encoder (C 函数)
@anchor{c-api/codec c PyCodec_Encoder}@anchor{3ee7}
@deffn {C 函数} PyObject* PyCodec_Encoder (const char@w{ }*encoding)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个编码器函数。
@end deffn

@geindex PyCodec_Decoder (C 函数)
@anchor{c-api/codec c PyCodec_Decoder}@anchor{3ee8}
@deffn {C 函数} PyObject* PyCodec_Decoder (const char@w{ }*encoding)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个解码器函数。
@end deffn

@geindex PyCodec_IncrementalEncoder (C 函数)
@anchor{c-api/codec c PyCodec_IncrementalEncoder}@anchor{3ee9}
@deffn {C 函数} PyObject* PyCodec_IncrementalEncoder (const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个 @ref{19b9,,IncrementalEncoder} 对象。
@end deffn

@geindex PyCodec_IncrementalDecoder (C 函数)
@anchor{c-api/codec c PyCodec_IncrementalDecoder}@anchor{3eea}
@deffn {C 函数} PyObject* PyCodec_IncrementalDecoder (const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个 @ref{19ba,,IncrementalDecoder} 对象。
@end deffn

@geindex PyCodec_StreamReader (C 函数)
@anchor{c-api/codec c PyCodec_StreamReader}@anchor{3eeb}
@deffn {C 函数} PyObject* PyCodec_StreamReader (const char@w{ }*encoding, PyObject@w{ }*stream, const char@w{ }*errors)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个 @ref{19be,,StreamReader} 工厂函数。
@end deffn

@geindex PyCodec_StreamWriter (C 函数)
@anchor{c-api/codec c PyCodec_StreamWriter}@anchor{3eec}
@deffn {C 函数} PyObject* PyCodec_StreamWriter (const char@w{ }*encoding, PyObject@w{ }*stream, const char@w{ }*errors)
@emph{Return value: New reference.}
为给定的 @emph{encoding} 获取一个 @ref{19bd,,StreamWriter} 工厂函数。
@end deffn

@node 用于Unicode编码错误处理程序的注册表API,,Codec 查找API,编解码器注册与支持功能
@anchor{c-api/codec registry-api-for-unicode-encoding-error-handlers}@anchor{3eed}
@subsubsection 用于Unicode编码错误处理程序的注册表API


@geindex PyCodec_RegisterError (C 函数)
@anchor{c-api/codec c PyCodec_RegisterError}@anchor{3eee}
@deffn {C 函数} int PyCodec_RegisterError (const char@w{ }*name, PyObject@w{ }*error)

在给定的 @emph{name} 之下注册错误处理回调函数 @emph{error}。 该回调函数将在一个编解码器遇到无法编码的字符/无法解码的字节数据并且 @emph{name} 被指定为 encode/decode 函数调用的 error 形参时由该编解码器来调用。

该回调函数会接受一个 @ref{331,,UnicodeEncodeError}, @ref{332,,UnicodeDecodeError} 或 @ref{1896,,UnicodeTranslateError} 的实例作为单独参数，其中包含关于有问题字符或字节序列及其在原始序列的偏移量信息（请参阅 @ref{3e63,,Unicode 异常对象} 了解提取此信息的函数详情）。 该回调函数必须引发给定的异常，或者返回一个包含有问题序列及相应替换序列的二元组，以及一个表示偏移量的整数，该整数指明应在什么位置上恢复编码/解码操作。

成功则返回`@w{`}0`@w{`} ，失败则返回`@w{`}-1`@w{`}
@end deffn

@geindex PyCodec_LookupError (C 函数)
@anchor{c-api/codec c PyCodec_LookupError}@anchor{3eef}
@deffn {C 函数} PyObject* PyCodec_LookupError (const char@w{ }*name)
@emph{Return value: New reference.}
查找在 @emph{name} 之下注册的错误处理回调函数。 作为特例还可以传入 @code{NULL}，在此情况下将返回针对 "strict" 的错误处理回调函数。
@end deffn

@geindex PyCodec_StrictErrors (C 函数)
@anchor{c-api/codec c PyCodec_StrictErrors}@anchor{3ef0}
@deffn {C 函数} PyObject* PyCodec_StrictErrors (PyObject@w{ }*exc)
@emph{Return value: Always NULL.}
引发 @emph{exc} 作为异常。
@end deffn

@geindex PyCodec_IgnoreErrors (C 函数)
@anchor{c-api/codec c PyCodec_IgnoreErrors}@anchor{3ef1}
@deffn {C 函数} PyObject* PyCodec_IgnoreErrors (PyObject@w{ }*exc)
@emph{Return value: New reference.}
忽略 unicode 错误，跳过错误的输入。
@end deffn

@geindex PyCodec_ReplaceErrors (C 函数)
@anchor{c-api/codec c PyCodec_ReplaceErrors}@anchor{3ef2}
@deffn {C 函数} PyObject* PyCodec_ReplaceErrors (PyObject@w{ }*exc)
@emph{Return value: New reference.}
使用 @code{?} 或 @code{U+FFFD} 替换 unicode 编码错误。
@end deffn

@geindex PyCodec_XMLCharRefReplaceErrors (C 函数)
@anchor{c-api/codec c PyCodec_XMLCharRefReplaceErrors}@anchor{3ef3}
@deffn {C 函数} PyObject* PyCodec_XMLCharRefReplaceErrors (PyObject@w{ }*exc)
@emph{Return value: New reference.}
使用 XML 字符引用替换 unicode 编码错误。
@end deffn

@geindex PyCodec_BackslashReplaceErrors (C 函数)
@anchor{c-api/codec c PyCodec_BackslashReplaceErrors}@anchor{3ef4}
@deffn {C 函数} PyObject* PyCodec_BackslashReplaceErrors (PyObject@w{ }*exc)
@emph{Return value: New reference.}
使用反斜杠转义符 (@code{\x}, @code{\u} 和 @code{\U}) 替换 unicode 编码错误。
@end deffn

@geindex PyCodec_NameReplaceErrors (C 函数)
@anchor{c-api/codec c PyCodec_NameReplaceErrors}@anchor{8a0}
@deffn {C 函数} PyObject* PyCodec_NameReplaceErrors (PyObject@w{ }*exc)
@emph{Return value: New reference.}
使用 @code{\N@{...@}} 转义符替换 unicode 编码错误。


3.5 新版功能.

@end deffn

@node 抽象对象层,具体的对象层,工具<2>,Python/C API 参考手册
@anchor{c-api/abstract doc}@anchor{3ef5}@anchor{c-api/abstract abstract}@anchor{3dbb}@anchor{c-api/abstract abstract-objects-layer}@anchor{3ef6}
@section 抽象对象层


本章中的函数与 Python对象交互，无论其类型，或具有广泛类的对象类型（例如，所有数值类型，或所有序列类型）。当使用对象类型并不适用时，他们会产生一个 Python 异常。

这些函数是不可能用于未正确初始化的对象的，如一个列表对象被 @ref{3e03,,PyList_New()} 创建，但其中的项目没有被设置为一些非`@w{`}NULL`@w{`}的值。

@menu
* 对象协议:: 
* 调用协议:: 
* 数字协议:: 
* 序列协议:: 
* 映射协议:: 
* 迭代器协议:: 
* 缓冲协议:: 
* 旧缓冲协议:: 

@end menu

@node 对象协议,调用协议,,抽象对象层
@anchor{c-api/object doc}@anchor{3ef7}@anchor{c-api/object object}@anchor{3ef8}@anchor{c-api/object object-protocol}@anchor{3ef9}
@subsection 对象协议


@geindex Py_NotImplemented (C 变量)
@anchor{c-api/object c Py_NotImplemented}@anchor{3efa}
@deffn {C 变量} PyObject* Py_NotImplemented

@code{NotImplemented} 单例，用于标记某个操作没有针对给定类型组合的实现。
@end deffn

@geindex Py_RETURN_NOTIMPLEMENTED (C 宏)
@anchor{c-api/object c Py_RETURN_NOTIMPLEMENTED}@anchor{3efb}
@deffn {C 宏} Py_RETURN_NOTIMPLEMENTED

C 函数内部应正确处理 @ref{3efa,,Py_NotImplemented} 的返回过程（即增加 NotImplemented 的引用计数并返回之）。
@end deffn

@geindex PyObject_Print (C 函数)
@anchor{c-api/object c PyObject_Print}@anchor{11ca}
@deffn {C 函数} int PyObject_Print (PyObject@w{ }*o, FILE@w{ }*fp, int@w{ }flags)

将对象 @emph{o} 写入到文件 @emph{fp}。 出错时返回 @code{-1} 。 旗标参数被用于启用特定的输出选项。 目前唯一支持的选项是 @code{Py_PRINT_RAW}；如果给出该选项，则将写入对象的 @ref{206,,str()} 而不是 @ref{8c3,,repr()}。
@end deffn

@geindex PyObject_HasAttr (C 函数)
@anchor{c-api/object c PyObject_HasAttr}@anchor{3efc}
@deffn {C 函数} int PyObject_HasAttr (PyObject@w{ }*o, PyObject@w{ }*attr_name)

如果 @emph{o} 带有属性 @emph{attr_name}，则返回 @code{1}，否则返回 @code{0}。这相当于 Python 表达式 @code{hasattr(o, attr_name)}。 此函数总是成功。

注意，在调用 @ref{433,,__getattr__()} 和 @ref{552,,__getattribute__()} 方法时发生的异常将被抑制。若要获得错误报告，请换用 @ref{3efd,,PyObject_GetAttr()} 。
@end deffn

@geindex PyObject_HasAttrString (C 函数)
@anchor{c-api/object c PyObject_HasAttrString}@anchor{3efe}
@deffn {C 函数} int PyObject_HasAttrString (PyObject@w{ }*o, const char@w{ }*attr_name)

如果 @emph{o} 带有属性 @emph{attr_name}，则返回 @code{1}，否则返回 @code{0}。这相当于 Python 表达式 @code{hasattr(o, attr_name)}。 此函数总是成功。

注意，在调用 @ref{433,,__getattr__()} 和 @ref{552,,__getattribute__()} 方法并创建一个临时字符串对象时，异常将被抑制。若要获得错误报告，请换用 @ref{3d72,,PyObject_GetAttrString()} 。
@end deffn

@geindex PyObject_GetAttr (C 函数)
@anchor{c-api/object c PyObject_GetAttr}@anchor{3efd}
@deffn {C 函数} PyObject* PyObject_GetAttr (PyObject@w{ }*o, PyObject@w{ }*attr_name)
@emph{Return value: New reference.}
从对象 @emph{o} 中读取名为 @emph{attr_name} 的属性。成功返回属性值，失败则返回  @code{NULL}。 这相当于 Python 表达式 @code{o.attr_name}。
@end deffn

@geindex PyObject_GetAttrString (C 函数)
@anchor{c-api/object c PyObject_GetAttrString}@anchor{3d72}
@deffn {C 函数} PyObject* PyObject_GetAttrString (PyObject@w{ }*o, const char@w{ }*attr_name)
@emph{Return value: New reference.}
从对象 @emph{o} 中读取一个名为 @emph{attr_name} 的属性。成功时返回属性值，失败则返回 @code{NULL}。这相当于 Python 表达式 @code{o.attr_name}。
@end deffn

@geindex PyObject_GenericGetAttr (C 函数)
@anchor{c-api/object c PyObject_GenericGetAttr}@anchor{3eff}
@deffn {C 函数} PyObject* PyObject_GenericGetAttr (PyObject@w{ }*o, PyObject@w{ }*name)
@emph{Return value: New reference.}
通用的属性获取函数，用于放入类型对象的 @code{tp_getattro} 槽中。它在类的字典中（位于对象的 MRO 中）查找某个描述符，并在对象的 @ref{5fe,,__dict__} 中查找某个属性。正如 @ref{5ec,,实现描述器} 所述，数据描述符优先于实例属性，而非数据描述符则不优先。失败则会触发 @ref{4aa,,AttributeError} 。
@end deffn

@geindex PyObject_SetAttr (C 函数)
@anchor{c-api/object c PyObject_SetAttr}@anchor{3f00}
@deffn {C 函数} int PyObject_SetAttr (PyObject@w{ }*o, PyObject@w{ }*attr_name, PyObject@w{ }*v)

将对象 @emph{o} 中名为 @emph{attr_name} 的属性值设为 @emph{v} 。失败时引发异常并返回 @code{-1}；成功时返 回`@w{`}0`@w{`} 。这相当于 Python 语句 @code{o.attr_name = v}。

如果 @emph{v} 为 @code{NULL}，该属性将被删除。 此行为已被弃用而应改用 @ref{3f01,,PyObject_DelAttr()}，但目前还没有移除它的计划。
@end deffn

@geindex PyObject_SetAttrString (C 函数)
@anchor{c-api/object c PyObject_SetAttrString}@anchor{3f02}
@deffn {C 函数} int PyObject_SetAttrString (PyObject@w{ }*o, const char@w{ }*attr_name, PyObject@w{ }*v)

将对象 @emph{o} 中名为 @emph{attr_name} 的属性值设为 @emph{v} 。失败时引发异常并返回 @code{-1}；成功时返 回`@w{`}0`@w{`} 。这相当于 Python 语句 @code{o.attr_name = v}。

如果 @emph{v} 为 @code{NULL}，该属性将被删除，但是此功能已被弃用而应改用 @ref{3f03,,PyObject_DelAttrString()}。
@end deffn

@geindex PyObject_GenericSetAttr (C 函数)
@anchor{c-api/object c PyObject_GenericSetAttr}@anchor{3f04}
@deffn {C 函数} int PyObject_GenericSetAttr (PyObject@w{ }*o, PyObject@w{ }*name, PyObject@w{ }*value)

通用的属性设置和删除函数，用于放入类型对象的 @ref{3db3,,tp_setattro} 槽。它在类的字典中（位于对象的MRO中）查找数据描述器，如果找到，则将比在实例字典中设置或删除属性优先执行。否则，该属性将在对象的 @ref{5fe,,__dict__} 中设置或删除。如果成功将返回 @code{0}，否则将引发 @ref{4aa,,AttributeError} 并返回 @code{-1}。
@end deffn

@geindex PyObject_DelAttr (C 函数)
@anchor{c-api/object c PyObject_DelAttr}@anchor{3f01}
@deffn {C 函数} int PyObject_DelAttr (PyObject@w{ }*o, PyObject@w{ }*attr_name)

删除对象 @emph{o} 中名为 @emph{attr_name} 的属性。失败时返回 @code{-1}。这相当于 Python 语句 @code{del o.attr_name}。
@end deffn

@geindex PyObject_DelAttrString (C 函数)
@anchor{c-api/object c PyObject_DelAttrString}@anchor{3f03}
@deffn {C 函数} int PyObject_DelAttrString (PyObject@w{ }*o, const char@w{ }*attr_name)

删除对象 @emph{o} 中名为 @emph{attr_name} 的属性。失败时返回 @code{-1}。这相当于 Python 语句 @code{del o.attr_name}。
@end deffn

@geindex PyObject_GenericGetDict (C 函数)
@anchor{c-api/object c PyObject_GenericGetDict}@anchor{3f05}
@deffn {C 函数} PyObject* PyObject_GenericGetDict (PyObject@w{ }*o, void@w{ }*context)
@emph{Return value: New reference.}
@code{__dict__} 描述符的获取函数的一种通用实现。必要时会创建字典。


3.3 新版功能.

@end deffn

@geindex PyObject_GenericSetDict (C 函数)
@anchor{c-api/object c PyObject_GenericSetDict}@anchor{3f06}
@deffn {C 函数} int PyObject_GenericSetDict (PyObject@w{ }*o, PyObject@w{ }*value, void@w{ }*context)

@code{__dict__} 描述符设置函数的一种通用实现。这里不允许删除字典。


3.3 新版功能.

@end deffn

@geindex PyObject_RichCompare (C 函数)
@anchor{c-api/object c PyObject_RichCompare}@anchor{3db9}
@deffn {C 函数} PyObject* PyObject_RichCompare (PyObject@w{ }*o1, PyObject@w{ }*o2, int@w{ }opid)
@emph{Return value: New reference.}
用 @emph{opid} 指定的操作比较 @emph{o1} 和 @emph{o2} 的值，必须是 @code{Py_LT} 、 @code{Py_LE} 、 @code{Py_EQ} 、 @code{Py_NE} 、 @code{Py_GT} 或 @code{Py_GE} 之一，分别对应于`@w{`}<=`@w{`} 、@code{==} 、 @code{!=} 、@code{>} 或 @code{>=}。这相当于 Python 表达式 @code{o1 op o2}，其中 @code{op} 是对应于 @emph{opid} 的操作符。成功时返回比较值，失败时返回 @code{NULL}。
@end deffn

@geindex PyObject_RichCompareBool (C 函数)
@anchor{c-api/object c PyObject_RichCompareBool}@anchor{10e5}
@deffn {C 函数} int PyObject_RichCompareBool (PyObject@w{ }*o1, PyObject@w{ }*o2, int@w{ }opid)

用 @emph{opid} 指定的操作比较 @emph{o1} 和 @emph{o2} 的值，必须是 @code{Py_LT} 、 @code{Py_LE} 、 @code{Py_EQ} 、 @code{Py_NE} 、 @code{Py_GT} 或 @code{Py_GE} 之一，分别对应于 @code{<} 、@code{<=}、 @code{==} 、@code{!=} 、@code{>} 或 @code{>=}。错误时返回 @code{-1}，若结果为 false 则返回 @code{0}，否则返回 @code{1}。这相当于 Python 表达式 @code{o1 op o2}，其中 @code{op} 是对应于 @emph{opid} 的操作符。
@end deffn

@cartouche
@quotation 注解 
如果 @emph{o1} 和 @emph{o2} 是同一个对象，@ref{10e5,,PyObject_RichCompareBool()} 为 @code{Py_EQ} 则返回 @code{1} ，为 @code{Py_NE} 则返回 @code{0}。
@end quotation
@end cartouche

@geindex PyObject_Repr (C 函数)
@anchor{c-api/object c PyObject_Repr}@anchor{a52}
@deffn {C 函数} PyObject* PyObject_Repr (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; repr

计算对象 @emph{o} 的字符串形式。 成功时返回字符串，失败时返回 @code{NULL}。 这相当于 Python 表达式 @code{repr(o)}。 由内置函数 @ref{8c3,,repr()}  调用。


在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动的异常。

@end deffn

@geindex PyObject_ASCII (C 函数)
@anchor{c-api/object c PyObject_ASCII}@anchor{3f07}
@deffn {C 函数} PyObject* PyObject_ASCII (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; ascii

与 @ref{a52,,PyObject_Repr()} 一样，计算对象 @emph{o} 的字符串形式，但在 @ref{a52,,PyObject_Repr()} 返回的字符串中用 @code{\x}、@code{\u} 或 @code{\U} 转义非 ASCII 字符。这将生成一个类似于 Python 2 中由 @ref{a52,,PyObject_Repr()} 返回的字符串。由内置函数 @ref{e19,,ascii()} 调用。

@geindex string; PyObject_Str (C function)
@end deffn

@geindex PyObject_Str (C 函数)
@anchor{c-api/object c PyObject_Str}@anchor{a53}
@deffn {C 函数} PyObject* PyObject_Str (PyObject@w{ }*o)
@emph{Return value: New reference.}
计算对象 @emph{o} 的字符串形式。 成功时返回字符串，失败时返回 @code{NULL}。 这相当于 Python 表达式 @code{str(o)}。由内置函数 @ref{206,,str()} 调用，因此也由 @ref{97a,,print()} 函数调用。


在 3.4 版更改: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动的异常。

@end deffn

@geindex PyObject_Bytes (C 函数)
@anchor{c-api/object c PyObject_Bytes}@anchor{3f08}
@deffn {C 函数} PyObject* PyObject_Bytes (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; bytes

计算对象 @emph{o} 的字节形式。失败时返回 @code{NULL}，成功时返回一个字节串对象。这相当于 @emph{o} 不是整数时的 Python 表达式 @code{bytes(o)} 。与 @code{bytes(o)} 不同的是，当 @emph{o} 是整数而不是初始为 0 的字节串对象时，会触发 TypeError。
@end deffn

@geindex PyObject_IsSubclass (C 函数)
@anchor{c-api/object c PyObject_IsSubclass}@anchor{897}
@deffn {C 函数} int PyObject_IsSubclass (PyObject@w{ }*derived, PyObject@w{ }*cls)

如果 @emph{derived} 类与 @emph{cls} 类相同或为其派生类，则返回 @code{1}，否则返回 @code{0}。 如果出错则返回 @code{-1}。

如果 @emph{cls} 是元组，则会对 @emph{cls} 进行逐项检测。如果至少有一次检测返回 @code{1}，结果将为 @code{1}，否则将是 @code{0}。

正如 
@geindex Python 提高建议; PEP 3119
PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119} 所述，如果 @emph{cls} 带有 @ref{15b4,,__subclasscheck__()} 方法，将会被调用以确定子类的状态。 否则，如果 @emph{derived} 是个直接或间接子类，即包含在 @code{cls.__mro__} 中，那么它就是 @emph{cls} 的一个子类。

通常只有类对象才会被视为类，即 @ref{709,,type} 或派生类的实例。然而，对象可以通过拥有 @code{__bases__} 属性（必须是基类的元组）来覆盖这一点。
@end deffn

@geindex PyObject_IsInstance (C 函数)
@anchor{c-api/object c PyObject_IsInstance}@anchor{896}
@deffn {C 函数} int PyObject_IsInstance (PyObject@w{ }*inst, PyObject@w{ }*cls)

如果 @emph{inst} 是 @emph{cls} 类或其子类的实例，则返回 @code{1}，如果不是则返回`@w{`}0`@w{`}。 如果出错则返回 @code{-1} 并设置一个异常。

如果 @emph{cls} 是元组，则会对 @emph{cls} 进行逐项检测。如果至少有一次检测返回 @code{1}，结果将为 @code{1}，否则将是 @code{0}。

正如 
@geindex Python 提高建议; PEP 3119
PEP 3119@footnote{https://www.python.org/dev/peps/pep-3119} 所述，如果 @emph{cls} 带有 @ref{15b4,,__subclasscheck__()} 方法，将会被调用以确定子类的状态。 否则，如果 @emph{derived} 是 @emph{cls} 的子类，那么它就是 @emph{cls} 的一个实例。

实例 @emph{inst} 可以通过 @code{__class__} 属性来覆盖其所属类。

对象 @emph{cls} 可以通过 @code{__bases__} 属性（必须是基类的元组）来覆盖它是否被认作类的状态，及其基类。
@end deffn

@geindex PyObject_Hash (C 函数)
@anchor{c-api/object c PyObject_Hash}@anchor{3f09}
@deffn {C 函数} Py_hash_t PyObject_Hash (PyObject@w{ }*o)

@geindex 內置函数; hash

计算并返回对象的哈希值 @emph{o}。 失败时返回 @code{-1}。这相当于 Python 表达式 @code{hash(o)}。


在 3.2 版更改: 现在的返回类型是 Py_hash_t。 这是一个大小与 @ref{391,,Py_ssize_t} 相同的有符号整数。

@end deffn

@geindex PyObject_HashNotImplemented (C 函数)
@anchor{c-api/object c PyObject_HashNotImplemented}@anchor{dff}
@deffn {C 函数} Py_hash_t PyObject_HashNotImplemented (PyObject@w{ }*o)

设置一个 @ref{1ff,,TypeError} 表示 @code{type(o)} 是不可哈希的，并返回 @code{-1} 。该函数保存在 @code{tp_hash} 槽中时会受到特别对待，允许某个类型向解释器显式表明它不可散列。
@end deffn

@geindex PyObject_IsTrue (C 函数)
@anchor{c-api/object c PyObject_IsTrue}@anchor{3f0a}
@deffn {C 函数} int PyObject_IsTrue (PyObject@w{ }*o)

如果对象 @emph{o} 被认为是 true，则返回 @code{1}，否则返回 @code{0}。这相当于 Python 表达式 @code{not not o}。 失败则返回 @code{-1}。
@end deffn

@geindex PyObject_Not (C 函数)
@anchor{c-api/object c PyObject_Not}@anchor{3f0b}
@deffn {C 函数} int PyObject_Not (PyObject@w{ }*o)

如果对象 @emph{o} 被认为是 true，则返回 @code{1}，否则返回 @code{0}。这相当于 Python 表达式 @code{not not o}。 失败则返回 @code{-1}。
@end deffn

@geindex PyObject_Type (C 函数)
@anchor{c-api/object c PyObject_Type}@anchor{3f0c}
@deffn {C 函数} PyObject* PyObject_Type (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; type

当 @emph{o} 不为 @code{NULL} 时，返回一个与对象 @emph{o} 的类型相对应的类型对象。 当失败时，将引发 @ref{6fc,,SystemError} 并返回 @code{NULL}。 这等同于 Python 表达式 @code{type(o)}。 该函数会增加返回值的引用计数。 实际上没有理由不去用普通的表达式 @ref{3d8b,,Py_TYPE()} 函数而使用该函数，它将返回一个 @ref{3fe,,PyTypeObject*} 类型的指针，除非是需要增强引用计数的时候。
@end deffn

@geindex PyObject_TypeCheck (C 函数)
@anchor{c-api/object c PyObject_TypeCheck}@anchor{3dc2}
@deffn {C 函数} int PyObject_TypeCheck (PyObject@w{ }*o, PyTypeObject@w{ }*type)

如果对象 @emph{o} 为 @emph{type} 类型或 @emph{type} 的子类型则返回真值。 两个参数都必须非 @code{NULL}。
@end deffn

@geindex PyObject_Size (C 函数)
@geindex PyObject_Length (C 函数)
@anchor{c-api/object c PyObject_Size}@anchor{3f0d}
@deffn {C 函数} Py_ssize_t PyObject_Size (PyObject@w{ }*o)
@anchor{c-api/object c PyObject_Length}@anchor{3f0e}
@deffnx {C 函数} Py_ssize_t PyObject_Length (PyObject@w{ }*o)

@geindex 內置函数; len

返回对象 @emph{o} 的长度。 如果对象 @emph{o} 支持序列和映射协议，则返回序列长度。 出错时返回 @code{-1}。这等同于 Python 表达式 @code{len(o)}。
@end deffn

@geindex PyObject_LengthHint (C 函数)
@anchor{c-api/object c PyObject_LengthHint}@anchor{a16}
@deffn {C 函数} Py_ssize_t PyObject_LengthHint (PyObject@w{ }*o, Py_ssize_t@w{ }defaultvalue)

返回对象 @emph{o} 的估计长度。首先尝试返回实际长度，然后用  @ref{903,,__length_hint__()} 进行估计，最后返回默认值。出错时返回`@w{`}-1`@w{`}。这等同于 Python 表达式 @code{operator.length_hint(o, defaultvalue)}。


3.4 新版功能.

@end deffn

@geindex PyObject_GetItem (C 函数)
@anchor{c-api/object c PyObject_GetItem}@anchor{3e04}
@deffn {C 函数} PyObject* PyObject_GetItem (PyObject@w{ }*o, PyObject@w{ }*key)
@emph{Return value: New reference.}
返回对象 @emph{key} 对应的 @emph{o} 元素，或在失败时返回 @code{NULL}。这等同于 Python 表达式 @code{o[key]}。
@end deffn

@geindex PyObject_SetItem (C 函数)
@anchor{c-api/object c PyObject_SetItem}@anchor{3e02}
@deffn {C 函数} int PyObject_SetItem (PyObject@w{ }*o, PyObject@w{ }*key, PyObject@w{ }*v)

将对象 @emph{key} 映射到值 @emph{v}。 失败时引发异常并返回 @code{-1}；成功时返回 @code{0}。 这相当于 Python 语句 @code{o[key] = v}。该函数 @emph{不会} 偷取 @emph{v} 的引用。
@end deffn

@geindex PyObject_DelItem (C 函数)
@anchor{c-api/object c PyObject_DelItem}@anchor{3f0f}
@deffn {C 函数} int PyObject_DelItem (PyObject@w{ }*o, PyObject@w{ }*key)

从对象 @emph{o} 中移除对象 @emph{key} 的映射。失败时返回 @code{-1}。 这相当于 Python 语句 @code{del o[key]}。
@end deffn

@geindex PyObject_Dir (C 函数)
@anchor{c-api/object c PyObject_Dir}@anchor{3f10}
@deffn {C 函数} PyObject* PyObject_Dir (PyObject@w{ }*o)
@emph{Return value: New reference.}
相当于 Python 表达式 @code{dir(o)}，返回一个（可能为空）适合对象参数的字符串列表，如果出错则返回 @code{NULL}。 如果参数为 @code{NULL}，类似 Python 的 @code{dir()}，则返回当前 locals 的名字；这时如果没有活动的执行框架，则返回 @code{NULL}，但 @ref{3d58,,PyErr_Occurred()} 将返回 false。
@end deffn

@geindex PyObject_GetIter (C 函数)
@anchor{c-api/object c PyObject_GetIter}@anchor{3f11}
@deffn {C 函数} PyObject* PyObject_GetIter (PyObject@w{ }*o)
@emph{Return value: New reference.}
等同于 Python 表达式 @code{iter(o)}。为对象参数返回一个新的迭代器，如果该对象已经是一个迭代器，则返回对象本身。如果对象不能被迭代，会引发  @ref{1ff,,TypeError} ，并返回  @code{NULL}。
@end deffn

@node 调用协议,数字协议,对象协议,抽象对象层
@anchor{c-api/call doc}@anchor{3f12}@anchor{c-api/call call}@anchor{3e80}@anchor{c-api/call call-protocol}@anchor{3f13}
@subsection 调用协议


CPython 支持两种不同的调用协议：@emph{tp_call} 和矢量调用。

@menu
* tp_call 协议:: 
* Vectorcall 协议:: 
* 调用对象的 API:: 
* 调用支持 API:: 

@end menu

@node tp_call 协议,Vectorcall 协议,,调用协议
@anchor{c-api/call the-tp-call-protocol}@anchor{3f14}
@subsubsection @emph{tp_call} 协议


设置 @ref{3dbf,,tp_call} 的类的实例都是可调用的。 槽位的签名为:

@example
PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);
@end example

一个调用是用一个元组表示位置参数，用一个dict表示关键字参数，类似于Python代码中的`@w{`}callable(@emph{args, **kwargs)`@w{`}。*args*必须是非空的（如果没有参数，会使用一个空元组），但如果没有关键字参数，*kwargs*可以是*NULL}。

这个约定不仅被*tp_call*使用： @ref{3d90,,tp_new} 和 @ref{3d97,,tp_init} 也这样传递参数。

要调用一个对象，请使用 @ref{23d,,PyObject_Call()} 或者其他的 @ref{3f15,,调用 API}。

@node Vectorcall 协议,调用对象的 API,tp_call 协议,调用协议
@anchor{c-api/call the-vectorcall-protocol}@anchor{3f16}@anchor{c-api/call vectorcall}@anchor{2bf}
@subsubsection Vectorcall 协议



3.9 新版功能.


vectorcall 协议是在 
@geindex Python 提高建议; PEP 590
PEP 590@footnote{https://www.python.org/dev/peps/pep-0590} 被引入的，它是使调用函数更加有效的附加协议。

作为经验法则，如果可调用程序支持 vectorcall，CPython 会更倾向于内联调用。 然而，这并不是一个硬性规定。 此外，一些第三方扩展直接使用 @emph{tp_call} (而不是使用 @ref{23d,,PyObject_Call()})。 因此，一个支持 vectorcall 的类也必须实现 @ref{3dbf,,tp_call}。 此外，无论使用哪种协议，可调对象的行为都必须是相同的。 推荐的方法是将 @ref{3dbf,,tp_call} 设置为 @ref{3f17,,PyVectorcall_Call()}。值得一提的是:

@cartouche
@quotation 警告 
一个支持 Vectorcall 的类 @strong{必须} 也实现具有相同语义的 @ref{3dbf,,tp_call}。
@end quotation
@end cartouche

如果一个类的vectorcall比*tp_call*慢，就不应该实现vectorcall。例如，如果被调用者需要将参数转换为args 元组和kwargs dict，那么实现vectorcall就没有意义。

类可以通过启用 @ref{3f18,,Py_TPFLAGS_HAVE_VECTORCALL} 标志并将 @ref{3f19,,tp_vectorcall_offset} 设置为对象结构中的 @emph{vectorcallfunc} 的 offset 来实现 vectorcall 协议。这是一个指向具有以下签名的函数的指针:

@geindex vectorcallfunc (C 类型)
@anchor{c-api/call c vectorcallfunc}@anchor{3f1a}
@deffn {C 类型} PyObject *(*vectorcallfunc) (PyObject@w{ }*callable, PyObject *const@w{ }*args, size_t@w{ }nargsf, PyObject@w{ }*kwnames)
@end deffn


@itemize -

@item 
@emph{callable} 是指被调用的对象。

@item 

@table @asis

@item @emph{args} 是一个C语言数组，由位置参数和后面的

关键字参数的值。如果没有参数，这个值可以是 @emph{NULL} 。
@end table

@item 

@table @asis

@item @emph{nargsf} 是位置参数的数量加上可能的

@code{PY_VECTORCALL_ARGUMENTS_OFFSET} 标志。 要从 @emph{nargsf} 获得实际的位置参数数，请使用 @ref{3f1b,,PyVectorcall_NARGS()}。
@end table

@item 

@table @asis

@item @emph{kwnames} 是一包含所有关键字名称的元组。

换句话说，就是 kwargs 字典的键。 这些名字必须是字符串 (@code{str} 或其子类的实例)，并且它们必须是唯一的。 如果没有关键字参数，那么 @emph{kwnames} 可以用 @emph{NULL} 代替。
@end table
@end itemize

@geindex PY_VECTORCALL_ARGUMENTS_OFFSET (C 宏)
@anchor{c-api/call c PY_VECTORCALL_ARGUMENTS_OFFSET}@anchor{3f1c}
@deffn {C 宏} PY_VECTORCALL_ARGUMENTS_OFFSET

如果在 vectorcall 的 @emph{nargsf} 参数中设置了此标志，则允许被调用者临时更改 @code{args[-1]} 的值。换句话说， @emph{args} 指向分配向量中的参数 1（不是 0 ）。被调用方必须在返回之前还原 @code{args[-1]} 的值。

对于 @ref{3f1d,,PyObject_VectorcallMethod()} ，这个标志的改变意味着`@w{`}args[0]`@w{`} 可能改变了。

当调用方可以以几乎无代价的方式（无额外的内存申请），那么调用者被推荐适用： @code{PY_VECTORCALL_ARGUMENTS_OFFSET}。这样做将允许诸如绑定方法之类的可调用函数非常有效地进行向前调用（其中包括一个带前缀的 @emph{self} 参数）。
@end deffn

要调用一个实现了 vectorcall 的对象，请使用某个 @ref{3f15,,call API} 函数，就像其他可调对象一样。  @ref{3f1e,,PyObject_Vectorcall()} 通常是最有效的。

@cartouche
@quotation 注解 
在 CPython 3.8 中，vectorcall API 和相关的函数暂定以带开头下划线的名称提供: @code{_PyObject_Vectorcall}, @code{_Py_TPFLAGS_HAVE_VECTORCALL}, @code{_PyObject_VectorcallMethod}, @code{_PyVectorcall_Function}, @code{_PyObject_CallOneArg}, @code{_PyObject_CallMethodNoArgs}, @code{_PyObject_CallMethodOneArg}。 此外， @code{PyObject_VectorcallDict} 以 @code{_PyObject_FastCallDict} 的名称提供。 旧名称仍然被定义为不带下划线的新名称的别名。
@end quotation
@end cartouche

@menu
* 递归控制: 递归控制<2>. 
* Vectorcall 支持 API:: 

@end menu

@node 递归控制<2>,Vectorcall 支持 API,,Vectorcall 协议
@anchor{c-api/call recursion-control}@anchor{3f1f}
@subsubsection 递归控制


在使用 @emph{tp_call} 时，被调用者不必担心 @ref{3e7e,,递归}: CPython 对于使用 @emph{tp_call} 进行的调用会使用 @ref{252,,Py_EnterRecursiveCall()} 和 @ref{253,,Py_LeaveRecursiveCall()}。

为保证效率，这不适用于使用 vectorcall 的调用：被调用方在需要时应当使用 @emph{Py_EnterRecursiveCall} 和 @emph{Py_LeaveRecursiveCall}。

@node Vectorcall 支持 API,,递归控制<2>,Vectorcall 协议
@anchor{c-api/call vectorcall-support-api}@anchor{3f20}
@subsubsection Vectorcall 支持 API


@geindex PyVectorcall_NARGS (C 函数)
@anchor{c-api/call c PyVectorcall_NARGS}@anchor{3f1b}
@deffn {C 函数} Py_ssize_t PyVectorcall_NARGS (size_t@w{ }nargsf)

给定一个 vectorcall @emph{nargsf} 实参，返回参数的实际数量。 目前等同于:

@example
(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)
@end example

然而，应使用 @code{PyVectorcall_NARGS} 函数以便将来扩展。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.8 新版功能.

@end deffn

@geindex PyVectorcall_Function (C 函数)
@anchor{c-api/call c PyVectorcall_Function}@anchor{3f21}
@deffn {C 函数} vectorcallfunc PyVectorcall_Function (PyObject@w{ }*op)

如果*op*不支持vectorcall协议（要么是因为类型不支持，要么是因为具体实例不支持），返回*NULL*。否则，返回存储在*op*中的vectorcall函数指针。这个函数从不触发异常。

这在检查 @emph{op} 是否支持 vectorcall 时最有用处，可以通过检查 @code{PyVectorcall_Function(op) != NULL} 来实现。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.8 新版功能.

@end deffn

@geindex PyVectorcall_Call (C 函数)
@anchor{c-api/call c PyVectorcall_Call}@anchor{3f17}
@deffn {C 函数} PyObject* PyVectorcall_Call (PyObject@w{ }*callable, PyObject@w{ }*tuple, PyObject@w{ }*dict)

调用*可调对象*的 @ref{3f1a,,vectorcallfunc}，其位置参数和关键字参数分别以元组和dict形式给出。

这是一个专门函数，其目的是被放入 @ref{3dbf,,tp_call} 槽位或是用于 @code{tp_call} 的实现。 它不会检查 @ref{3f18,,Py_TPFLAGS_HAVE_VECTORCALL} 旗标并且它不会回退到 @code{tp_call}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.8 新版功能.

@end deffn

@node 调用对象的 API,调用支持 API,Vectorcall 协议,调用协议
@anchor{c-api/call capi-call}@anchor{3f15}@anchor{c-api/call object-calling-api}@anchor{3f22}
@subsubsection 调用对象的 API


有多个函数可被用来调用 Python 对象。 各个函数会将其参数转换为被调用对象所支持的惯例 – 可以是 @emph{tp_call} 或 vectorcall。 为了尽可能少地进行转换，请选择一个适合你所拥有的数据格式的函数。

下表总结了可用的功能； 请参阅各个文档以了解详细信息。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

函数

@tab

可调用对象（Callable）

@tab

args

@tab

kwargs

@item

@ref{23d,,PyObject_Call()}

@tab

@code{PyObject *}

@tab

元组

@tab

dict/@code{NULL}

@item

@ref{251,,PyObject_CallNoArgs()}

@tab

@code{PyObject *}

@tab

---

@tab

---

@item

@ref{257,,PyObject_CallOneArg()}

@tab

@code{PyObject *}

@tab

1个对象

@tab

---

@item

@ref{3d67,,PyObject_CallObject()}

@tab

@code{PyObject *}

@tab

元组/@code{NULL}

@tab

---

@item

@ref{3fa,,PyObject_CallFunction()}

@tab

@code{PyObject *}

@tab

format

@tab

---

@item

@ref{3f23,,PyObject_CallMethod()}

@tab

对象 + @code{char*}

@tab

format

@tab

---

@item

@ref{3f24,,PyObject_CallFunctionObjArgs()}

@tab

@code{PyObject *}

@tab

可变参数

@tab

---

@item

@ref{115d,,PyObject_CallMethodObjArgs()}

@tab

对象 + 名称

@tab

可变参数

@tab

---

@item

@ref{3f25,,PyObject_CallMethodNoArgs()}

@tab

对象 + 名称

@tab

---

@tab

---

@item

@ref{3f26,,PyObject_CallMethodOneArg()}

@tab

对象 + 名称

@tab

1个对象

@tab

---

@item

@ref{3f1e,,PyObject_Vectorcall()}

@tab

@code{PyObject *}

@tab

vectorcall

@tab

vectorcall

@item

@ref{3f27,,PyObject_VectorcallDict()}

@tab

@code{PyObject *}

@tab

vectorcall

@tab

dict/@code{NULL}

@item

@ref{3f1d,,PyObject_VectorcallMethod()}

@tab

参数 + 名称

@tab

vectorcall

@tab

vectorcall

@end multitable


@geindex PyObject_Call (C 函数)
@anchor{c-api/call c PyObject_Call}@anchor{23d}
@deffn {C 函数} PyObject* PyObject_Call (PyObject@w{ }*callable, PyObject@w{ }*args, PyObject@w{ }*kwargs)
@emph{Return value: New reference.}
调用一个可调用的 Python 对象 @emph{callable}，附带由元组 @emph{args} 所给出的参数，以及由字典 @emph{kwargs} 所给出的关键字参数。

@emph{args} 必须不为 @emph{NULL}；如果不想要参数请使用一个空元组。 如果不想要关键字参数，则 @emph{kwargs} 可以为 @emph{NULL}。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这等价于 Python 表达式 @code{callable(*args, **kwargs)}。
@end deffn

@geindex PyObject_CallNoArgs (C 函数)
@anchor{c-api/call c PyObject_CallNoArgs}@anchor{251}
@deffn {C 函数} PyObject* PyObject_CallNoArgs (PyObject@w{ }*callable)

调用一个可调用的 Python 对象 @emph{callable} 并不附带任何参数。 这是不带参数调用 Python 可调用对象的最有效方式。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。


3.9 新版功能.

@end deffn

@geindex PyObject_CallOneArg (C 函数)
@anchor{c-api/call c PyObject_CallOneArg}@anchor{257}
@deffn {C 函数} PyObject* PyObject_CallOneArg (PyObject@w{ }*callable, PyObject@w{ }*arg)

调用一个可调用的 Python 对象 @emph{callable} 并附带恰好 1 个位置参数 @emph{arg} 而没有关键字参数。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@geindex PyObject_CallObject (C 函数)
@anchor{c-api/call c PyObject_CallObject}@anchor{3d67}
@deffn {C 函数} PyObject* PyObject_CallObject (PyObject@w{ }*callable, PyObject@w{ }*args)
@emph{Return value: New reference.}
调用一个可调用的 Python 对象 @emph{callable}，附带由元组 @emph{args} 所给出的参数。 如果不想要传入参数，则 @emph{args} 可以为 @emph{NULL}。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这等价于 Python 表达式 @code{callable(*args)}。
@end deffn

@geindex PyObject_CallFunction (C 函数)
@anchor{c-api/call c PyObject_CallFunction}@anchor{3fa}
@deffn {C 函数} PyObject* PyObject_CallFunction (PyObject@w{ }*callable, const char@w{ }*format, ...)
@emph{Return value: New reference.}
调用一个可调用的 Python 对象 @emph{callable}，附带可变数量的 C 参数。 这些 C 参数使用 @ref{3f9,,Py_BuildValue()} 风格的格式化字符串来描述。 format 可以为 @emph{NULL}，表示没有提供任何参数。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这等价于 Python 表达式 @code{callable(*args)}。

请注意如果你只传入 @ref{5bd,,PyObject *} 参数，则 @ref{3f24,,PyObject_CallFunctionObjArgs()} 是更快速的选择。


在 3.4 版更改: 这个 @emph{format} 类型已从 @code{char *} 更改。

@end deffn

@geindex PyObject_CallMethod (C 函数)
@anchor{c-api/call c PyObject_CallMethod}@anchor{3f23}
@deffn {C 函数} PyObject* PyObject_CallMethod (PyObject@w{ }*obj, const char@w{ }*name, const char@w{ }*format, ...)
@emph{Return value: New reference.}
调用 @emph{obj} 对象中名为 @emph{name} 的方法并附带可变数量的 C 参数。 这些 C 参数由 @ref{3f9,,Py_BuildValue()} 格式字符串来描述并应当生成一个元组。

格式可以为 @emph{NULL} ，表示未提供任何参数。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这和Python表达式`@w{`}obj.name(arg1, arg2, ...)`@w{`}是一样的。

请注意如果你只传入 @ref{5bd,,PyObject *} 参数，则  @ref{115d,,PyObject_CallMethodObjArgs()} 是更快速的选择。


在 3.4 版更改: The types of @emph{name} and @emph{format} were changed from @code{char *}.

@end deffn

@geindex PyObject_CallFunctionObjArgs (C 函数)
@anchor{c-api/call c PyObject_CallFunctionObjArgs}@anchor{3f24}
@deffn {C 函数} PyObject* PyObject_CallFunctionObjArgs (PyObject@w{ }*callable, ...)
@emph{Return value: New reference.}
调用一个可调用的 Python 对象 @emph{callable}，附带可变数量的 @ref{5bd,,PyObject *} 参数。 这些参数是以 @emph{NULL} 之后可变数量的形参的形式提供的。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这和Python表达式`@w{`}callable(arg1, arg2, ...)`@w{`}是一样的。
@end deffn

@geindex PyObject_CallMethodObjArgs (C 函数)
@anchor{c-api/call c PyObject_CallMethodObjArgs}@anchor{115d}
@deffn {C 函数} PyObject* PyObject_CallMethodObjArgs (PyObject@w{ }*obj, PyObject@w{ }*name, ...)
@emph{Return value: New reference.}
调用 Python 对象 @emph{obj} 中的一个方法，其中方法名称由 @emph{name} 中的 Python 字符串对象给出。 它将附带可变数量的 @ref{5bd,,PyObject *} 参数被调用。 这些参数是以 @emph{NULL} 之后可变数量的形参的形式提供的。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。
@end deffn

@geindex PyObject_CallMethodNoArgs (C 函数)
@anchor{c-api/call c PyObject_CallMethodNoArgs}@anchor{3f25}
@deffn {C 函数} PyObject* PyObject_CallMethodNoArgs (PyObject@w{ }*obj, PyObject@w{ }*name)

调用 Python 对象 @emph{obj} 中的一个方法并不附带任何参数，其中方法名称由 @emph{name} 中的 Python 字符串对象给出。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@geindex PyObject_CallMethodOneArg (C 函数)
@anchor{c-api/call c PyObject_CallMethodOneArg}@anchor{3f26}
@deffn {C 函数} PyObject* PyObject_CallMethodOneArg (PyObject@w{ }*obj, PyObject@w{ }*name, PyObject@w{ }*arg)

调用Call a method of the Python 对象 @emph{obj} 中的一个方法并附带单个位置参数 @emph{arg}，其中方法名称由 @emph{name} 中的 Python 字符串对象给出。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@geindex PyObject_Vectorcall (C 函数)
@anchor{c-api/call c PyObject_Vectorcall}@anchor{3f1e}
@deffn {C 函数} PyObject* PyObject_Vectorcall (PyObject@w{ }*callable, PyObject *const@w{ }*args, size_t@w{ }nargsf, PyObject@w{ }*kwnames)

调用一个可调用的 Python 对象 @emph{callable}。 附带的参数与 @ref{3f1a,,vectorcallfunc} 相同。 如果 @emph{callable} 支持 @ref{2bf,,vectorcall}，则它会直接调用存放在 @emph{callable} 中的 vectorcall 函数。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@geindex PyObject_VectorcallDict (C 函数)
@anchor{c-api/call c PyObject_VectorcallDict}@anchor{3f27}
@deffn {C 函数} PyObject* PyObject_VectorcallDict (PyObject@w{ }*callable, PyObject *const@w{ }*args, size_t@w{ }nargsf, PyObject@w{ }*kwdict)

调用 @emph{callable} 并附带与在 @ref{2bf,,vectorcall} 协议中传入的完全相同的位置参数，但会加上以字典 @emph{kwdict} 形式传入的关键字参数。 @emph{args} 数组将只包含位置参数。

无论在内部使用哪种协议，都需要进行参数的转换。 因此，此函数应当仅在调用方已经拥有作为关键字参数的字典，但没有作为位置参数的元组时才被使用。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@geindex PyObject_VectorcallMethod (C 函数)
@anchor{c-api/call c PyObject_VectorcallMethod}@anchor{3f1d}
@deffn {C 函数} PyObject* PyObject_VectorcallMethod (PyObject@w{ }*name, PyObject *const@w{ }*args, size_t@w{ }nargsf, PyObject@w{ }*kwnames)

使用 vectorcall 调用惯例来调用一个方法。 方法的名称以 Python 字符串 @emph{name} 的形式给出。 调用方法的对象为 @emph{args[0]}，而 @emph{args} 数组从 @emph{args[1]} 开始的部分则代表调用的参数。 必须传入至少一个位置参数。 @emph{nargsf} 为包括 @emph{args[0]} 在内的位置参数的数量，如果 @code{args[0]} 的值可能被临时改变则要再加上 @code{PY_VECTORCALL_ARGUMENTS_OFFSET}。 关键字参数可以像在 @ref{3f1e,,PyObject_Vectorcall()} 中一样被传入。

如果对象具有 @ref{3f28,,Py_TPFLAGS_METHOD_DESCRIPTOR} 特性，此函数将调用调用未绑定的方法对象并附带完整的 @emph{args} vector 作为参数。

成功时返回结果，在失败时抛出一个异常并返回 @emph{NULL}。

这个函数不是 @ref{3e13,,limited API} 的一部分。


3.9 新版功能.

@end deffn

@node 调用支持 API,,调用对象的 API,调用协议
@anchor{c-api/call call-support-api}@anchor{3f29}
@subsubsection 调用支持 API


@geindex PyCallable_Check (C 函数)
@anchor{c-api/call c PyCallable_Check}@anchor{3f2a}
@deffn {C 函数} int PyCallable_Check (PyObject@w{ }*o)

确定对象 @emph{o} 是可调对象。如果对象是可调对象则返回 @code{1} ，其他情况返回 @code{0} 。这个函数不会调用失败。
@end deffn

@node 数字协议,序列协议,调用协议,抽象对象层
@anchor{c-api/number doc}@anchor{3f2b}@anchor{c-api/number number}@anchor{3f2c}@anchor{c-api/number number-protocol}@anchor{3f2d}
@subsection 数字协议


@geindex PyNumber_Check (C 函数)
@anchor{c-api/number c PyNumber_Check}@anchor{39c}
@deffn {C 函数} int PyNumber_Check (PyObject@w{ }*o)

如果对象 @emph{o} 提供数字的协议，返回真 @code{1}，否则返回假。这个函数不会调用失败。


在 3.8 版更改: 如果 @emph{o} 是一个索引整数则返回 @code{1}。

@end deffn

@geindex PyNumber_Add (C 函数)
@anchor{c-api/number c PyNumber_Add}@anchor{3f2e}
@deffn {C 函数} PyObject* PyNumber_Add (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2} 相加的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 + o2}。
@end deffn

@geindex PyNumber_Subtract (C 函数)
@anchor{c-api/number c PyNumber_Subtract}@anchor{3f2f}
@deffn {C 函数} PyObject* PyNumber_Subtract (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 减去 @emph{o2} 的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 - o2}。
@end deffn

@geindex PyNumber_Multiply (C 函数)
@anchor{c-api/number c PyNumber_Multiply}@anchor{3f30}
@deffn {C 函数} PyObject* PyNumber_Multiply (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1}  、 @emph{o2} 相乘的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 * o2}。
@end deffn

@geindex PyNumber_MatrixMultiply (C 函数)
@anchor{c-api/number c PyNumber_MatrixMultiply}@anchor{8a6}
@deffn {C 函数} PyObject* PyNumber_MatrixMultiply (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2} 做矩阵乘法的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 @@ o2}。


3.5 新版功能.

@end deffn

@geindex PyNumber_FloorDivide (C 函数)
@anchor{c-api/number c PyNumber_FloorDivide}@anchor{3f31}
@deffn {C 函数} PyObject* PyNumber_FloorDivide (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 向下取整的值，失败时返回 @code{NULL}。 这等价于 Python 表达式 @code{o1 // o2}。
@end deffn

@geindex PyNumber_TrueDivide (C 函数)
@anchor{c-api/number c PyNumber_TrueDivide}@anchor{3f32}
@deffn {C 函数} PyObject* PyNumber_TrueDivide (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 的数学值的合理近似值，或失败时返回 @code{NULL}。 返回的是 "近似值" 因为二进制浮点数本身就是近似值；不可能以二进制精确表示所有实数。 此函数可以在传入两个整数时返回一个浮点值。 此函数等价于 Python 表达式 @code{o1 / o2}。
@end deffn

@geindex PyNumber_Remainder (C 函数)
@anchor{c-api/number c PyNumber_Remainder}@anchor{3f33}
@deffn {C 函数} PyObject* PyNumber_Remainder (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 得到的余数，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 % o2}。
@end deffn

@geindex PyNumber_Divmod (C 函数)
@anchor{c-api/number c PyNumber_Divmod}@anchor{3f34}
@deffn {C 函数} PyObject* PyNumber_Divmod (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
@geindex 內置函数; divmod

参考内置函数 @ref{294,,divmod()}。如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{divmod(o1, o2)}。
@end deffn

@geindex PyNumber_Power (C 函数)
@anchor{c-api/number c PyNumber_Power}@anchor{3f35}
@deffn {C 函数} PyObject* PyNumber_Power (PyObject@w{ }*o1, PyObject@w{ }*o2, PyObject@w{ }*o3)
@emph{Return value: New reference.}
@geindex 內置函数; pow

请参阅内置函数 @ref{2d6,,pow()}。 如果失败，返回 @code{NULL}。 等价于 Python 中的表达式 @code{pow(o1, o2, o3)}，其中 @emph{o3} 是可选的。如果要忽略 @emph{o3}，则需传入 @ref{3d5d,,Py_None} 作为代替（如果传入 @code{NULL} 会导致非法内存访问）。
@end deffn

@geindex PyNumber_Negative (C 函数)
@anchor{c-api/number c PyNumber_Negative}@anchor{3f36}
@deffn {C 函数} PyObject* PyNumber_Negative (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回 @emph{o} 的负值，如果失败，返回 @code{NULL} 。等价于 Python 表达式 @code{-o}。
@end deffn

@geindex PyNumber_Positive (C 函数)
@anchor{c-api/number c PyNumber_Positive}@anchor{3f37}
@deffn {C 函数} PyObject* PyNumber_Positive (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回 @emph{o}，如果失败，返回 @code{NULL} 。等价于 Python 表达式 @code{+o}。
@end deffn

@geindex PyNumber_Absolute (C 函数)
@anchor{c-api/number c PyNumber_Absolute}@anchor{3f38}
@deffn {C 函数} PyObject* PyNumber_Absolute (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; abs

返回 @emph{o} 的绝对值，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{abs(o)}。
@end deffn

@geindex PyNumber_Invert (C 函数)
@anchor{c-api/number c PyNumber_Invert}@anchor{3f39}
@deffn {C 函数} PyObject* PyNumber_Invert (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回 @emph{o} 的按位取反后的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{~o}。
@end deffn

@geindex PyNumber_Lshift (C 函数)
@anchor{c-api/number c PyNumber_Lshift}@anchor{3f3a}
@deffn {C 函数} PyObject* PyNumber_Lshift (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 左移 @emph{o2} 个比特后的结果，如果失败，返回 @code{NULL}。等价于 Python 表达式 @code{o1 << o2}。
@end deffn

@geindex PyNumber_Rshift (C 函数)
@anchor{c-api/number c PyNumber_Rshift}@anchor{3f3b}
@deffn {C 函数} PyObject* PyNumber_Rshift (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 右移 @emph{o2} 个比特后的结果，如果失败，返回  @code{NULL} 。等价于 Python 表达式 @code{o1 >> o2}。
@end deffn

@geindex PyNumber_And (C 函数)
@anchor{c-api/number c PyNumber_And}@anchor{3f3c}
@deffn {C 函数} PyObject* PyNumber_And (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 和 @emph{o2} “按位与”的结果，如果失败，返回 @code{NULL} 。等价于 Python 表达式 @code{o1 & o2}。
@end deffn

@geindex PyNumber_Xor (C 函数)
@anchor{c-api/number c PyNumber_Xor}@anchor{3f3d}
@deffn {C 函数} PyObject* PyNumber_Xor (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 和 @emph{o2} “按位异或”的结果，如果失败，返回 @code{NULL} 。等价于 Python 表达式 @code{o1 ^ o2}。
@end deffn

@geindex PyNumber_Or (C 函数)
@anchor{c-api/number c PyNumber_Or}@anchor{3f3e}
@deffn {C 函数} PyObject* PyNumber_Or (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 和 @emph{o2} “按位或”的结果，如果失败，返回 @code{NULL} 。等价于 Python 表达式 @code{o1 | o2}。
@end deffn

@geindex PyNumber_InPlaceAdd (C 函数)
@anchor{c-api/number c PyNumber_InPlaceAdd}@anchor{3f3f}
@deffn {C 函数} PyObject* PyNumber_InPlaceAdd (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2} 相加的结果，如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 += o2}。
@end deffn

@geindex PyNumber_InPlaceSubtract (C 函数)
@anchor{c-api/number c PyNumber_InPlaceSubtract}@anchor{3f40}
@deffn {C 函数} PyObject* PyNumber_InPlaceSubtract (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2} 相减的结果，如果失败，返回 @code{NULL} 。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 -= o2}。
@end deffn

@geindex PyNumber_InPlaceMultiply (C 函数)
@anchor{c-api/number c PyNumber_InPlaceMultiply}@anchor{3f41}
@deffn {C 函数} PyObject* PyNumber_InPlaceMultiply (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2*相乘的结果，如果失败，返回 `@w{`}NULL`@w{`} 。当 *o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 *= o2}。
@end deffn

@geindex PyNumber_InPlaceMatrixMultiply (C 函数)
@anchor{c-api/number c PyNumber_InPlaceMatrixMultiply}@anchor{8a7}
@deffn {C 函数} PyObject* PyNumber_InPlaceMatrixMultiply (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 、@emph{o2} 做矩阵乘法后的结果，如果失败，返回 @code{NULL} 。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 @@= o2}。


3.5 新版功能.

@end deffn

@geindex PyNumber_InPlaceFloorDivide (C 函数)
@anchor{c-api/number c PyNumber_InPlaceFloorDivide}@anchor{3f42}
@deffn {C 函数} PyObject* PyNumber_InPlaceFloorDivide (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 后向下取整的结果，如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 //= o2}。
@end deffn

@geindex PyNumber_InPlaceTrueDivide (C 函数)
@anchor{c-api/number c PyNumber_InPlaceTrueDivide}@anchor{3f43}
@deffn {C 函数} PyObject* PyNumber_InPlaceTrueDivide (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 的数学值的合理近似值，或失败时返回 @code{NULL}。 返回的是 "近似值" 因为二进制浮点数本身就是近似值；不可能以二进制精确表示所有实数。 此函数可以在传入两个整数时返回一个浮点数。 此运算在 @emph{o1} 支持的时候会 @emph{原地} 执行。此函数等价于 Python 语句 @code{o1 /= o2}。
@end deffn

@geindex PyNumber_InPlaceRemainder (C 函数)
@anchor{c-api/number c PyNumber_InPlaceRemainder}@anchor{3f44}
@deffn {C 函数} PyObject* PyNumber_InPlaceRemainder (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 除以 @emph{o2} 得到的余数，如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 %= o2}。
@end deffn

@geindex PyNumber_InPlacePower (C 函数)
@anchor{c-api/number c PyNumber_InPlacePower}@anchor{3f45}
@deffn {C 函数} PyObject* PyNumber_InPlacePower (PyObject@w{ }*o1, PyObject@w{ }*o2, PyObject@w{ }*o3)
@emph{Return value: New reference.}
@geindex 內置函数; pow

请参阅内置函数 @ref{2d6,,pow()}。 如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。当 @emph{o3} 是 @ref{3d5d,,Py_None} 时，等价于 Python 语句  @code{o1 **= o2}；否则等价于在原来位置储存结果的 @code{pow(o1, o2, o3)} 。如果要忽略 @emph{o3}，则需传入 @ref{3d5d,,Py_None}  （传入 @code{NULL} 会导致非法内存访问）。
@end deffn

@geindex PyNumber_InPlaceLshift (C 函数)
@anchor{c-api/number c PyNumber_InPlaceLshift}@anchor{3f46}
@deffn {C 函数} PyObject* PyNumber_InPlaceLshift (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 左移 @emph{o2} 个比特后的结果，如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 <<= o2}。
@end deffn

@geindex PyNumber_InPlaceRshift (C 函数)
@anchor{c-api/number c PyNumber_InPlaceRshift}@anchor{3f47}
@deffn {C 函数} PyObject* PyNumber_InPlaceRshift (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
返回 @emph{o1} 右移 @emph{o2} 个比特后的结果，如果失败，返回 @code{NULL}。当 @emph{o1} 支持时，这个运算直接使用它储存结果。 等价于 Python 语句 @code{o1 >>= o2}。
@end deffn

@geindex PyNumber_InPlaceAnd (C 函数)
@anchor{c-api/number c PyNumber_InPlaceAnd}@anchor{3f48}
@deffn {C 函数} PyObject* PyNumber_InPlaceAnd (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
成功时返回 @emph{o1} 和 @emph{o2} "按位与" 的结果，失败时返回 @code{NULL}。 在 @emph{o1} 支持的前提下该操作将 @emph{原地} 执行。 等价与 Python 语句 @code{o1 &= o2}。
@end deffn

@geindex PyNumber_InPlaceXor (C 函数)
@anchor{c-api/number c PyNumber_InPlaceXor}@anchor{3f49}
@deffn {C 函数} PyObject* PyNumber_InPlaceXor (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
成功时返回 @emph{o1} 和 @emph{o2} "按位异或的结果，失败时返回 @code{NULL}。 在 @emph{o1} 支持的前提下该操作将 @emph{原地} 执行。 等价与 Python 语句 @code{o1 ^= o2}。
@end deffn

@geindex PyNumber_InPlaceOr (C 函数)
@anchor{c-api/number c PyNumber_InPlaceOr}@anchor{3f4a}
@deffn {C 函数} PyObject* PyNumber_InPlaceOr (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
成功时返回 @emph{o1} 和 @emph{o2} "按位或" 的结果，失败时返回 @code{NULL}。 在 @emph{o1} 支持的前提下该操作将 @emph{原地} 执行。 等价于 Python 语句 @code{o1 |= o2}。
@end deffn

@geindex PyNumber_Long (C 函数)
@anchor{c-api/number c PyNumber_Long}@anchor{39d}
@deffn {C 函数} PyObject* PyNumber_Long (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; int

成功时返回 @emph{o} 转换为整数对象后的结果，失败时返回 @code{NULL}。 等价于 Python 表达式 @code{int(o)}。
@end deffn

@geindex PyNumber_Float (C 函数)
@anchor{c-api/number c PyNumber_Float}@anchor{39e}
@deffn {C 函数} PyObject* PyNumber_Float (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; float

成功时返回 @emph{o} 转换为浮点对象后的结果，失败时返回 @code{NULL}。 等价于 Python 表达式 @code{float(o)}。
@end deffn

@geindex PyNumber_Index (C 函数)
@anchor{c-api/number c PyNumber_Index}@anchor{3f4b}
@deffn {C 函数} PyObject* PyNumber_Index (PyObject@w{ }*o)
@emph{Return value: New reference.}
成功时返回 @emph{o} 转换为 Python int 类型后的结果，失败时返回 @code{NULL} 并引发 @ref{1ff,,TypeError} 异常。
@end deffn

@geindex PyNumber_ToBase (C 函数)
@anchor{c-api/number c PyNumber_ToBase}@anchor{10c0}
@deffn {C 函数} PyObject* PyNumber_ToBase (PyObject@w{ }*n, int@w{ }base)
@emph{Return value: New reference.}
返回整数 @emph{n} 转换成以 @emph{base} 为基数的字符串后的结果。这个 @emph{base} 参数必须是 2，8，10 或者 16 。对于基数 2，8，或 16 ，返回的字符串将分别加上基数标识 @code{'0b'}, @code{'0o'}, or @code{'0x'}。如果 @emph{n} 不是 Python 中的整数 @emph{int} 类型，就先通过 @ref{3f4b,,PyNumber_Index()} 将它转换成整数类型。
@end deffn

@geindex PyNumber_AsSsize_t (C 函数)
@anchor{c-api/number c PyNumber_AsSsize_t}@anchor{3f4c}
@deffn {C 函数} Py_ssize_t PyNumber_AsSsize_t (PyObject@w{ }*o, PyObject@w{ }*exc)

如果 @emph{o} 可以被解读为一个整数则返回 @emph{o} 转换成的 @ref{391,,Py_ssize_t} 值。 如果调用失败，则会引发一个异常并返回 @code{-1}。

如果 @emph{o} 可以被转换为 Python 的 int 值但尝试转换为 @ref{391,,Py_ssize_t} 值则会引发 @ref{a4a,,OverflowError}，则 @emph{exc} 参数将为所引发的异常类型 (通常为 @ref{f3d,,IndexError} 或 @ref{a4a,,OverflowError})。 如果 @emph{exc} 为 @code{NULL}，则异常会被清除并且值会在为负整数时被裁剪为 @code{PY_SSIZE_T_MIN} 而在为正整数时被裁剪为 @code{PY_SSIZE_T_MAX}。
@end deffn

@geindex PyIndex_Check (C 函数)
@anchor{c-api/number c PyIndex_Check}@anchor{26f}
@deffn {C 函数} int PyIndex_Check (PyObject@w{ }*o)

返回 @code{1} 如果 @emph{o} 是一个索引整数（将 @code{nb_index} 槽位填充到 @code{tp_as_number} 结构体），或者在其他情况下返回 @code{0}。 此函数总是会成功执行。
@end deffn

@node 序列协议,映射协议,数字协议,抽象对象层
@anchor{c-api/sequence doc}@anchor{3f4d}@anchor{c-api/sequence sequence}@anchor{3f4e}@anchor{c-api/sequence sequence-protocol}@anchor{3f4f}
@subsection 序列协议


@geindex PySequence_Check (C 函数)
@anchor{c-api/sequence c PySequence_Check}@anchor{3f50}
@deffn {C 函数} int PySequence_Check (PyObject@w{ }*o)

如果对象提供了序列协议则返回 @code{1}，否则返回 @code{0}。 请注意它将为具有 @ref{3ad,,__getitem__()} 方法的 Python 类返回 @code{1}，除非它们是 @ref{164,,dict} 的子类，因为在通常情况下无法确定这种类支持哪种键类型。 此函数总是会成功执行。
@end deffn

@geindex PySequence_Size (C 函数)
@geindex PySequence_Length (C 函数)
@anchor{c-api/sequence c PySequence_Size}@anchor{11cb}
@deffn {C 函数} Py_ssize_t PySequence_Size (PyObject@w{ }*o)
@anchor{c-api/sequence c PySequence_Length}@anchor{3f51}
@deffnx {C 函数} Py_ssize_t PySequence_Length (PyObject@w{ }*o)

@geindex 內置函数; len

到哪里积分返回序列 @emph{o} 中对象的数量，失败时返回 @code{-1}。 这相当于 Python 表达式 @code{len(o)}。
@end deffn

@geindex PySequence_Concat (C 函数)
@anchor{c-api/sequence c PySequence_Concat}@anchor{3f52}
@deffn {C 函数} PyObject* PySequence_Concat (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
成功时返回 @emph{o1} 和 @emph{o2} 的拼接，失败时返回 @code{NULL}。 这等价于 Python 表达式 @code{o1 + o2}。
@end deffn

@geindex PySequence_Repeat (C 函数)
@anchor{c-api/sequence c PySequence_Repeat}@anchor{3f53}
@deffn {C 函数} PyObject* PySequence_Repeat (PyObject@w{ }*o, Py_ssize_t@w{ }count)
@emph{Return value: New reference.}
返回序列对象 @emph{o} 重复 @emph{count} 次的结果，失败时返回 @code{NULL}。 这等价于 Python 表达式 @code{o * count}。
@end deffn

@geindex PySequence_InPlaceConcat (C 函数)
@anchor{c-api/sequence c PySequence_InPlaceConcat}@anchor{3f54}
@deffn {C 函数} PyObject* PySequence_InPlaceConcat (PyObject@w{ }*o1, PyObject@w{ }*o2)
@emph{Return value: New reference.}
成功时返回 @emph{o1} 和 @emph{o2} 的拼接，失败时返回 @code{NULL}。 在 @emph{o1} 支持的情况下操作将 @emph{原地} 完成。 这等价于 Python 表达式 @code{o1 += o2}。
@end deffn

@geindex PySequence_InPlaceRepeat (C 函数)
@anchor{c-api/sequence c PySequence_InPlaceRepeat}@anchor{3f55}
@deffn {C 函数} PyObject* PySequence_InPlaceRepeat (PyObject@w{ }*o, Py_ssize_t@w{ }count)
@emph{Return value: New reference.}
Return the result of repeating sequence object返回序列对象 @emph{o} 重复 @emph{count} 次的结果，失败时返回 @code{NULL}。 在 @emph{o} 支持的情况下该操作会 @emph{原地} 完成。 这等价于 Python 表达式 @code{o *= count}。
@end deffn

@geindex PySequence_GetItem (C 函数)
@anchor{c-api/sequence c PySequence_GetItem}@anchor{11cc}
@deffn {C 函数} PyObject* PySequence_GetItem (PyObject@w{ }*o, Py_ssize_t@w{ }i)
@emph{Return value: New reference.}
返回 @emph{o} 中的第 @emph{i} 号元素，失败时返回 @code{NULL}。 这等价于 Python 表达式 @code{o[i]}。
@end deffn

@geindex PySequence_GetSlice (C 函数)
@anchor{c-api/sequence c PySequence_GetSlice}@anchor{3f56}
@deffn {C 函数} PyObject* PySequence_GetSlice (PyObject@w{ }*o, Py_ssize_t@w{ }i1, Py_ssize_t@w{ }i2)
@emph{Return value: New reference.}
返回序列对象 @emph{o} 的 @emph{i1} 到 @emph{i2} 的切片，失败时返回 @code{NULL}。 这等价于 Python 表达式 @code{o[i1:i2]}。
@end deffn

@geindex PySequence_SetItem (C 函数)
@anchor{c-api/sequence c PySequence_SetItem}@anchor{11cd}
@deffn {C 函数} int PySequence_SetItem (PyObject@w{ }*o, Py_ssize_t@w{ }i, PyObject@w{ }*v)

将对象 @emph{v} 赋值给 @emph{o} 的第 @emph{i} 号元素。 失败时会引发异常并返回 @code{-1}；成功时返回 @code{0}。 这相当于 Python 语句 @code{o[i] = v}。 此函数 @emph{不会} 改变对 @emph{v} 的引用。

如果 @emph{v} 为 @code{NULL}，元素将被删除，但是此特性已被弃用而应改用 @ref{11ce,,PySequence_DelItem()}。
@end deffn

@geindex PySequence_DelItem (C 函数)
@anchor{c-api/sequence c PySequence_DelItem}@anchor{11ce}
@deffn {C 函数} int PySequence_DelItem (PyObject@w{ }*o, Py_ssize_t@w{ }i)

删除对象 @emph{o} 的第 @emph{i} 号元素。 失败时返回 @code{-1}。 这相当于 Python 语句 @code{del o[i]}。
@end deffn

@geindex PySequence_SetSlice (C 函数)
@anchor{c-api/sequence c PySequence_SetSlice}@anchor{3f57}
@deffn {C 函数} int PySequence_SetSlice (PyObject@w{ }*o, Py_ssize_t@w{ }i1, Py_ssize_t@w{ }i2, PyObject@w{ }*v)

将序列对象 @emph{v} 赋值给序列对象 @emph{o} 的从 @emph{i1} 到 @emph{i2} 切片。 这相当于 Python 语句 @code{o[i1:i2] = v}。
@end deffn

@geindex PySequence_DelSlice (C 函数)
@anchor{c-api/sequence c PySequence_DelSlice}@anchor{3f58}
@deffn {C 函数} int PySequence_DelSlice (PyObject@w{ }*o, Py_ssize_t@w{ }i1, Py_ssize_t@w{ }i2)

删除序列对象 @emph{o} 的从 @emph{i1} 到 @emph{i2} 的切片。 失败时返回 @code{-1}。 这相当于 Python 语句 @code{del o[i1:i2]}。
@end deffn

@geindex PySequence_Count (C 函数)
@anchor{c-api/sequence c PySequence_Count}@anchor{3f59}
@deffn {C 函数} Py_ssize_t PySequence_Count (PyObject@w{ }*o, PyObject@w{ }*value)

返回 @emph{value} 在 @emph{o} 中出现的次数，即返回使得 @code{o[key] == value} 的键的数量。 失败时返回 @code{-1}。 这相当于 Python 表达式 @code{o.count(value)}。
@end deffn

@geindex PySequence_Contains (C 函数)
@anchor{c-api/sequence c PySequence_Contains}@anchor{3f5a}
@deffn {C 函数} int PySequence_Contains (PyObject@w{ }*o, PyObject@w{ }*value)

确定 @emph{o} 是否包含 @emph{value}。 如果 @emph{o} 中的某一项等于 @emph{value}，则返回 @code{1}，否则返回 @code{0}。 出错时，返回 @code{-1}。 这相当于 Python 表达式 @code{value in o}。
@end deffn

@geindex PySequence_Index (C 函数)
@anchor{c-api/sequence c PySequence_Index}@anchor{3f5b}
@deffn {C 函数} Py_ssize_t PySequence_Index (PyObject@w{ }*o, PyObject@w{ }*value)

返回第一个索引*i*,其中 @code{o[i] == value}.出错时,返回“-1”.相当于Python的`@w{`}o.index(value)`@w{`}表达式.
@end deffn

@geindex PySequence_List (C 函数)
@anchor{c-api/sequence c PySequence_List}@anchor{3f5c}
@deffn {C 函数} PyObject* PySequence_List (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回一个列表对象，其内容与序列或可迭代对象 @emph{o} 相同，失败时返回 @code{NULL}。 返回的列表保证是一个新对象。 这等价于 Python 表达式 @code{list(o)}。
@end deffn

@geindex PySequence_Tuple (C 函数)
@anchor{c-api/sequence c PySequence_Tuple}@anchor{3f5d}
@deffn {C 函数} PyObject* PySequence_Tuple (PyObject@w{ }*o)
@emph{Return value: New reference.}
@geindex 內置函数; tuple

返回一个元组对象，其内容与序列或可迭代对象 @emph{o} 相同，失败时返回 @code{NULL}。 如果 @emph{o} 为元组，则将返回一个新的引用，在其他情况下将使用适当的内容构造一个元组。 这等价于 Python 表达式 @code{tuple(o)}。
@end deffn

@geindex PySequence_Fast (C 函数)
@anchor{c-api/sequence c PySequence_Fast}@anchor{3f5e}
@deffn {C 函数} PyObject* PySequence_Fast (PyObject@w{ }*o, const char@w{ }*m)
@emph{Return value: New reference.}
将序列或可迭代对象 @emph{o} 作为其他 @code{PySequence_Fast*} 函数族可用的对象返回。 如果该对象不是序列或可迭代对象，则会引发 @ref{1ff,,TypeError} 并将 @emph{m} 作为消息文本。 失败时返回 @code{NULL}。

@code{PySequence_Fast*} 函数之所以这样命名，是因为它们会假定 @emph{o} 是一个 @ref{3ea3,,PyTupleObject} 或 @ref{3f5f,,PyListObject} 并直接访问 @emph{o} 的数据字段。

作为 CPython 的实现细节，如果 @emph{o} 已经是一个序列或列表，它将被直接返回。
@end deffn

@geindex PySequence_Fast_GET_SIZE (C 函数)
@anchor{c-api/sequence c PySequence_Fast_GET_SIZE}@anchor{3f60}
@deffn {C 函数} Py_ssize_t PySequence_Fast_GET_SIZE (PyObject@w{ }*o)

在 @emph{o} 由 @ref{3f5e,,PySequence_Fast()} 返回且 @emph{o} 不为 @code{NULL} 的情况下返回 @emph{o} 长度。 也可以通过在  @emph{o} 上调用 @ref{11cb,,PySequence_Size()} 来获取大小，但是 @ref{3f60,,PySequence_Fast_GET_SIZE()} 的速度更快因为它可以假定 @emph{o} 为列表或元组。
@end deffn

@geindex PySequence_Fast_GET_ITEM (C 函数)
@anchor{c-api/sequence c PySequence_Fast_GET_ITEM}@anchor{3f61}
@deffn {C 函数} PyObject* PySequence_Fast_GET_ITEM (PyObject@w{ }*o, Py_ssize_t@w{ }i)
@emph{Return value: Borrowed reference.}
在 @emph{o} 由 @ref{3f5e,,PySequence_Fast()} 返回且 @emph{o} 不 @code{NULL}，并且 @emph{i} d在索引范围内的情况下返回 @emph{o} 的第 @emph{i} 号元素。
@end deffn

@geindex PySequence_Fast_ITEMS (C 函数)
@anchor{c-api/sequence c PySequence_Fast_ITEMS}@anchor{3f62}
@deffn {C 函数} PyObject** PySequence_Fast_ITEMS (PyObject@w{ }*o)

返回 PyObject 指针的底层数组。 假设 @emph{o} 由 @ref{3f5e,,PySequence_Fast()} 返回且 @emph{o} 不为 @code{NULL}。

请注意,如果列表调整大小,重新分配可能会重新定位items数组.因此,仅在序列无法更改的上下文中使用基础数组指针.
@end deffn

@geindex PySequence_ITEM (C 函数)
@anchor{c-api/sequence c PySequence_ITEM}@anchor{3f63}
@deffn {C 函数} PyObject* PySequence_ITEM (PyObject@w{ }*o, Py_ssize_t@w{ }i)
@emph{Return value: New reference.}
返回 @emph{o} 的第 @emph{i} 个元素或在失败时返回 @code{NULL}。 此形式比 @ref{11cc,,PySequence_GetItem()} 理馔，但不会检查 @emph{o} 上的 @ref{3f50,,PySequence_Check()} 是否为真值，也不会对负序号进行调整。
@end deffn

@node 映射协议,迭代器协议,序列协议,抽象对象层
@anchor{c-api/mapping doc}@anchor{3f64}@anchor{c-api/mapping mapping}@anchor{3f65}@anchor{c-api/mapping mapping-protocol}@anchor{3f66}
@subsection 映射协议


参见 @ref{3e04,,PyObject_GetItem()}、@ref{3e02,,PyObject_SetItem()} 与 @ref{3f0f,,PyObject_DelItem()}。

@geindex PyMapping_Check (C 函数)
@anchor{c-api/mapping c PyMapping_Check}@anchor{3f67}
@deffn {C 函数} int PyMapping_Check (PyObject@w{ }*o)

如果对象提供了映射协议或是支持切片则返回 @code{1}，否则返回 @code{0}。 请注意它将为具有 @ref{3ad,,__getitem__()} 方法的 Python 类返回 @code{1}，因为在通常情况下无法确定该类所支持的键类型。 此函数总是会成功执行。
@end deffn

@geindex PyMapping_Size (C 函数)
@geindex PyMapping_Length (C 函数)
@anchor{c-api/mapping c PyMapping_Size}@anchor{11cf}
@deffn {C 函数} Py_ssize_t PyMapping_Size (PyObject@w{ }*o)
@anchor{c-api/mapping c PyMapping_Length}@anchor{3f68}
@deffnx {C 函数} Py_ssize_t PyMapping_Length (PyObject@w{ }*o)

@geindex 內置函数; len

成功时返回对象 @emph{o} 中键的数量，失败时返回 @code{-1}。 这相当于 Python 表达式 @code{len(o)}。
@end deffn

@geindex PyMapping_GetItemString (C 函数)
@anchor{c-api/mapping c PyMapping_GetItemString}@anchor{3f69}
@deffn {C 函数} PyObject* PyMapping_GetItemString (PyObject@w{ }*o, const char@w{ }*key)
@emph{Return value: New reference.}
返回 @emph{o} 中对应于字符串 @emph{key} 的元素，或者失败时返回 @code{NULL}。 这相当于 Python 表达式 @code{o[key]}。 另请参见 also @ref{3e04,,PyObject_GetItem()}。
@end deffn

@geindex PyMapping_SetItemString (C 函数)
@anchor{c-api/mapping c PyMapping_SetItemString}@anchor{3f6a}
@deffn {C 函数} int PyMapping_SetItemString (PyObject@w{ }*o, const char@w{ }*key, PyObject@w{ }*v)

在对象 @emph{o} 中将字符串 @emph{key} 映射到值 @emph{v}。 失败时返回 @code{-1}。 这相当于 Python 语句 @code{o[key] = v}。 另请参见 @ref{3e02,,PyObject_SetItem()}。 此函数 @emph{不会} 增加对 @emph{v} 的引用。
@end deffn

@geindex PyMapping_DelItem (C 函数)
@anchor{c-api/mapping c PyMapping_DelItem}@anchor{3f6b}
@deffn {C 函数} int PyMapping_DelItem (PyObject@w{ }*o, PyObject@w{ }*key)

从对象 @emph{o} 中移除对象 @emph{key} 的映射。 失败时返回 @code{-1}。 这相当于 Python 语句 @code{del o[key]}。 这是 @ref{3f0f,,PyObject_DelItem()} 的一个别名。
@end deffn

@geindex PyMapping_DelItemString (C 函数)
@anchor{c-api/mapping c PyMapping_DelItemString}@anchor{3f6c}
@deffn {C 函数} int PyMapping_DelItemString (PyObject@w{ }*o, const char@w{ }*key)

从对象 @emph{o} 中移除字符串 @emph{key} 的映射。 失败时返回 @code{-1}。 这相当于 Python 语句 @code{del o[key]}。
@end deffn

@geindex PyMapping_HasKey (C 函数)
@anchor{c-api/mapping c PyMapping_HasKey}@anchor{3f6d}
@deffn {C 函数} int PyMapping_HasKey (PyObject@w{ }*o, PyObject@w{ }*key)

如果映射对象具有键 @emph{key} 则返回 @code{1}，否则返回 @code{0}。 这相当于 Python 表达式 @code{key in o}。 此函数总是会成功执行。

请注意在调用 @ref{3ad,,__getitem__()} 方法期间发生的异常将会被屏蔽。 要获取错误报告请改用 @ref{3e04,,PyObject_GetItem()}。
@end deffn

@geindex PyMapping_HasKeyString (C 函数)
@anchor{c-api/mapping c PyMapping_HasKeyString}@anchor{3f6e}
@deffn {C 函数} int PyMapping_HasKeyString (PyObject@w{ }*o, const char@w{ }*key)

如果映射对象具有键 @emph{key} 则返回 @code{1}，否则返回 @code{0}。 这相当于 Python 表达式 @code{key in o}。 此函数总是会成功执行。

请注意在调用 @ref{3ad,,__getitem__()} 方法期间发生的异常将会被屏蔽。 要获取错误报告请改用 @ref{3f69,,PyMapping_GetItemString()}。
@end deffn

@geindex PyMapping_Keys (C 函数)
@anchor{c-api/mapping c PyMapping_Keys}@anchor{538}
@deffn {C 函数} PyObject* PyMapping_Keys (PyObject@w{ }*o)
@emph{Return value: New reference.}
成功时，返回对象 @emph{o} 中的键的列表。 失败时，返回 @code{NULL}。


在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。

@end deffn

@geindex PyMapping_Values (C 函数)
@anchor{c-api/mapping c PyMapping_Values}@anchor{539}
@deffn {C 函数} PyObject* PyMapping_Values (PyObject@w{ }*o)
@emph{Return value: New reference.}
成功时，返回对象 @emph{o} 中的值的列表。 失败时，返回 @code{NULL}。


在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。

@end deffn

@geindex PyMapping_Items (C 函数)
@anchor{c-api/mapping c PyMapping_Items}@anchor{53a}
@deffn {C 函数} PyObject* PyMapping_Items (PyObject@w{ }*o)
@emph{Return value: New reference.}
成功时，返回对象 @emph{o} 中条目的列表，其中每个条目是一个包含键值对的元组。 失败时，返回 @code{NULL}。


在 3.7 版更改: 在之前版本中，此函数返回一个列表或元组。

@end deffn

@node 迭代器协议,缓冲协议,映射协议,抽象对象层
@anchor{c-api/iter doc}@anchor{3f6f}@anchor{c-api/iter iterator}@anchor{3f70}@anchor{c-api/iter iterator-protocol}@anchor{3f71}
@subsection 迭代器协议


迭代器有两个函数。

@geindex PyIter_Check (C 函数)
@anchor{c-api/iter c PyIter_Check}@anchor{1192}
@deffn {C 函数} int PyIter_Check (PyObject@w{ }*o)

如果对象 @emph{o} 支持迭代器协议则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyIter_Next (C 函数)
@anchor{c-api/iter c PyIter_Next}@anchor{3f72}
@deffn {C 函数} PyObject* PyIter_Next (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回迭代 @emph{o} 的下一个值。 对象必须是一个迭代器（这应由调用者来判断）。 如果没有余下的值，则返回 @code{NULL} 并且不设置异常。 如果在获取条目时发生了错误，则返回 @code{NULL} 并且传递异常。
@end deffn

要为迭代器编写一个一个循环，C代码应该看起来像这样

@example
PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;

if (iterator == NULL) @{
    /* propagate error */
@}

while ((item = PyIter_Next(iterator))) @{
    /* do something with item */
    ...
    /* release reference when done */
    Py_DECREF(item);
@}

Py_DECREF(iterator);

if (PyErr_Occurred()) @{
    /* propagate error */
@}
else @{
    /* continue doing useful work */
@}
@end example

@geindex buffer protocol
@geindex buffer interface; (see buffer protocol)
@geindex buffer object; (see buffer protocol)

@node 缓冲协议,旧缓冲协议,迭代器协议,抽象对象层
@anchor{c-api/buffer doc}@anchor{3f73}@anchor{c-api/buffer buffer-protocol}@anchor{3f74}@anchor{c-api/buffer bufferobjects}@anchor{174c}
@subsection 缓冲协议


在 Python 中可使用一些对象来包装对底层内存数组或称 @emph{缓冲} 的访问。此类对象包括内置的 @ref{172,,bytes} 和 @ref{173,,bytearray} 以及一些如 @ref{217,,array.array} 这样的扩展类型。第三方库也可能会为了特殊的目的而定义它们自己的类型，例如用于图像处理和数值分析等。

虽然这些类型中的每一种都有自己的语义，但它们具有由可能较大的内存缓冲区支持的共同特征。 在某些情况下，希望直接访问该缓冲区而无需中间复制。

Python 以 @ref{174c,,缓冲协议} 的形式在 C 层级上提供这样的功能。 此协议包括两个方面:

@geindex PyBufferProcs


@itemize -

@item 
在生产者这一方面，该类型的协议可以导出一个“缓冲区接口”，允许公开它的底层缓冲区信息。该接口的描述信息在 @ref{3f75,,Buffer Object Structures} 一节中；

@item 
在消费者一侧，有几种方法可用于获得指向对象的原始底层数据的指针（例如一个方法的形参）。
@end itemize

一些简单的对象例如 @ref{172,,bytes} 和 @ref{173,,bytearray} 会以面向字节的形式公开它们的底层缓冲区。 也可能会用其他形式；例如 @ref{217,,array.array} 所公开的元素可以是多字节值。

缓冲区接口的消费者的一个例子是文件对象的 @ref{68a,,write()} 方法：任何可以输出为一系列字节流的对象可以被写入文件。然而 @code{write()} 方法只需要对于传入对象的只读权限，其他的方法，如 @ref{2180,,readinto()} 需要参数内容的写入权限。缓冲区接口使得对象可以选择性地允许或拒绝读写或只读缓冲区的导出。

对于缓冲接口的消费者而言，有两种方式来获取一个目的对象的缓冲：


@itemize *

@item 
使用正确的参数来调用 @ref{df3,,PyObject_GetBuffer()} 函数；

@item 
调用 @ref{39b,,PyArg_ParseTuple()} (或其同级对象之一) 并传入 @code{y*}, @code{w*} or @code{s*} @ref{3fb,,格式代码} 中的一个。
@end itemize

在这两种情况下，当不再需要缓冲区时必须调用 @ref{e21,,PyBuffer_Release()} 。如果此操作失败，可能会导致各种问题，例如资源泄漏。

@menu
* 缓冲区结构:: 
* 缓冲区请求的类型:: 
* 复杂数组:: 
* 缓冲区相关函数:: 

@end menu

@node 缓冲区结构,缓冲区请求的类型,,缓冲协议
@anchor{c-api/buffer buffer-structure}@anchor{3f76}@anchor{c-api/buffer id1}@anchor{3f77}
@subsubsection 缓冲区结构


缓冲区结构(或者简单地称为“buffers”)对于将二进制数据从另一个对象公开给 Python 程序员非常有用。它们还可以用作零拷贝切片机制。使用它们引用内存块的能力，可以很容易地将任何数据公开给 Python 程序员。内存可以是 C 扩展中的一个大的常量数组，也可以是在传递到操作系统库之前用于操作的原始内存块，或者可以用来传递本机内存格式的结构化数据。

与 Python 解释器公开的大多部数据类型不同，缓冲区不是 @ref{5bd,,PyObject} 指针而是简单的 C 结构。 这使得它们可以非常简单地创建和复制。 当需要为缓冲区加上泛型包装器时，可以创建一个 @ref{3f78,,内存视图} 对象。

有关如何编写并导出对象的简短说明，请参阅 @ref{3f75,,缓冲区对象结构}。 要获取缓冲区对象，请参阅 @ref{df3,,PyObject_GetBuffer()}。

@geindex Py_buffer (C 类型)
@anchor{c-api/buffer c Py_buffer}@anchor{bf7}
@deffn {C 类型} Py_buffer

@geindex Py_buffer.buf (C 成员)
@anchor{c-api/buffer c Py_buffer buf}@anchor{3f79}
@deffn {C 成员} void *buf

指向由缓冲区字段描述的逻辑结构开始的指针。 这可以是导出程序底层物理内存块中的任何位置。 例如，使用负的 @ref{3f7a,,strides} 值可能指向内存块的末尾。

对于 @ref{181d,,contiguous} ，‘邻接’数组，值指向内存块的开头。
@end deffn

@geindex Py_buffer.obj (C 成员)
@anchor{c-api/buffer c Py_buffer obj}@anchor{3f7b}
@deffn {C 成员} void *obj

对导出对象的新引用。 该引用归使用者所有，并由 @ref{e21,,PyBuffer_Release()} 自动递减并设置为 @code{NULL}。 该字段等于任何标准 C-API 函数的返回值。

作为一种特殊情况，对于由 @ref{3f7c,,PyMemoryView_FromBuffer()} 或 @ref{3f7d,,PyBuffer_FillInfo()} 包装的 @emph{temporary} 缓冲区，此字段为 @code{NULL}。 通常，导出对象不得使用此方案。
@end deffn

@geindex Py_buffer.len (C 成员)
@anchor{c-api/buffer c Py_buffer len}@anchor{3f7e}
@deffn {C 成员} Py_ssize_t len

@code{product(shape) * itemsize}。对于连续数组，这是基础内存块的长度。对于非连续数组，如果逻辑结构复制到连续表示形式，则该长度将具有该长度。

仅当缓冲区是通过保证连续性的请求获取时，才访问 @code{((char *)buf)[0] up to ((char *)buf)[len-1]} 时才有效。在大多数情况下，此类请求将为 @ref{3f7f,,PyBUF_SIMPLE} 或 @ref{3f80,,PyBUF_WRITABLE}。
@end deffn

@geindex Py_buffer.readonly (C 成员)
@anchor{c-api/buffer c Py_buffer readonly}@anchor{3f81}
@deffn {C 成员} int readonly

缓冲区是否为只读的指示器。此字段由 @ref{3f80,,PyBUF_WRITABLE} 标志控制。
@end deffn

@geindex Py_buffer.itemsize (C 成员)
@anchor{c-api/buffer c Py_buffer itemsize}@anchor{3f82}
@deffn {C 成员} Py_ssize_t itemsize

单个元素的项大小（以字节为单位）。与 @ref{110e,,struct.calcsize()} 调用非 @code{NULL} @ref{3f83,,format} 的值相同。

重要例外：如果使用者请求的缓冲区没有 @ref{3f84,,PyBUF_FORMAT} 标志，@ref{3f83,,format} 将设置为 @code{NULL}，但 @ref{3f82,,itemsize} 仍具有原始格式的值。

如果 @ref{3f85,,shape} 存在，则相等的 @code{product(shape) * itemsize == len} 仍然存在，使用者可以使用 @ref{3f82,,itemsize} 来导航缓冲区。

如果 @ref{3f85,,shape} 是 @code{NULL}，因为结果为 @ref{3f7f,,PyBUF_SIMPLE} 或 @ref{3f80,,PyBUF_WRITABLE} 请求，则使用者必须忽略 @ref{3f82,,itemsize}，并假设 @code{itemsize == 1}。
@end deffn

@geindex Py_buffer.format (C 成员)
@anchor{c-api/buffer c Py_buffer format}@anchor{3f83}
@deffn {C 成员} const char *format

在 @ref{f8,,struct} 模块样式语法中 @emph{NUL} 字符串，描述单个项的内容。如果这是 @code{NULL}，则假定为`@w{`}"B"`@w{`} (无符号字节) 。

此字段由 @ref{3f84,,PyBUF_FORMAT} 标志控制。
@end deffn

@geindex Py_buffer.ndim (C 成员)
@anchor{c-api/buffer c Py_buffer ndim}@anchor{3f86}
@deffn {C 成员} int ndim

内存表示为 n 维数组的维数。 如果是`@w{`}0`@w{`}， @ref{3f79,,buf} 指向表示标量的单个项目。 在这种情况下，@ref{3f85,,shape}、@ref{3f7a,,strides} 和 @ref{3f87,,suboffsets} 必须是`@w{`}NULL`@w{`} 。

宏 @code{PyBUF_MAX_NDIM} 将最大维度数限制为 64。 导出程序必须遵守这个限制，多维缓冲区的使用者应该能够处理最多 @code{PyBUF_MAX_NDIM} 维度。
@end deffn

@geindex Py_buffer.shape (C 成员)
@anchor{c-api/buffer c Py_buffer shape}@anchor{3f85}
@deffn {C 成员} Py_ssize_t *shape

一个长度为 @ref{391,,Py_ssize_t} 的数组 @ref{3f86,,ndim} 表示作为 n 维数组的内存形状。 请注意，@code{shape[0] * ... * shape[ndim-1] * itemsize} 必须等于 @ref{3f7e,,len}。

Shape 形状数组中的值被限定在 @code{shape[n] >= 0} 。 @code{shape[n] == 0} 这一情形需要特别注意。更多信息请参阅 @ref{3f88,,complex arrays} 。

shape 数组对于使用者来说是只读的。
@end deffn

@geindex Py_buffer.strides (C 成员)
@anchor{c-api/buffer c Py_buffer strides}@anchor{3f7a}
@deffn {C 成员} Py_ssize_t *strides

一个长度为 @ref{391,,Py_ssize_t} 的数组 @ref{3f86,,ndim} 给出要跳过的字节数以获取每个尺寸中的新元素。

Stride 步幅数组中的值可以为任何整数。对于常规数组，步幅通常为正数，但是使用者必须能够处理 @code{strides[n] <= 0} 的情况。更多信息请参阅 @ref{3f88,,complex arrays} 。

strides数组对用户来说是只读的。
@end deffn

@geindex Py_buffer.suboffsets (C 成员)
@anchor{c-api/buffer c Py_buffer suboffsets}@anchor{3f87}
@deffn {C 成员} Py_ssize_t *suboffsets

一个长度为 @ref{3f86,,ndim} 类型为 @ref{391,,Py_ssize_t} 的数组 。如果 @code{suboffsets[n] >= 0}，则第 n 维存储的是指针，suboffset 值决定了解除引用时要给指针增加多少字节的偏移。suboffset 为负值，则表示不应解除引用（在连续内存块中移动）。

如果所有子偏移均为负（即无需取消引用），则此字段必须为 @code{NULL} （默认值）。

Python Imaging Library (PIL) 中使用了这种类型的数组表达方式。请参阅 @ref{3f88,,complex arrays} 来了解如何从这样一个数组中访问元素。

suboffsets 数组对于使用者来说是只读的。
@end deffn

@geindex Py_buffer.internal (C 成员)
@anchor{c-api/buffer c Py_buffer internal}@anchor{3f89}
@deffn {C 成员} void *internal

供输出对象内部使用。比如可能被导出器重组为一个整数，用于存储一个标志，标明在缓冲区释放时是否必须释放 shape、strides 和 suboffsets 数组。缓冲区用户 @emph{不得} 修改该值。
@end deffn
@end deffn

@node 缓冲区请求的类型,复杂数组,缓冲区结构,缓冲协议
@anchor{c-api/buffer buffer-request-types}@anchor{3f8a}@anchor{c-api/buffer id2}@anchor{3f8b}
@subsubsection 缓冲区请求的类型


通常，通过 @ref{df3,,PyObject_GetBuffer()} 向输出对象发送缓冲区请求，即可获得缓冲区。由于内存的逻辑结构复杂，可能会有很大差异，缓冲区使用者可用 @emph{flags} 参数指定其能够处理的缓冲区具体类型。

所有 @ref{bf7,,Py_buffer} 字段均由请求类型明确定义。

@menu
* 与请求无关的字段:: 
* 只读，格式:: 
* 形状，步幅，子偏移量:: 
* 连续性的请求:: 
* 复合请求:: 

@end menu

@node 与请求无关的字段,只读，格式,,缓冲区请求的类型
@anchor{c-api/buffer request-independent-fields}@anchor{3f8c}
@subsubsection 与请求无关的字段


以下字段不会被 @emph{flags} 影响，并且必须总是用正确的值填充：@ref{3f7b,,obj}, @ref{3f79,,buf}，@ref{3f7e,,len}，@ref{3f82,,itemsize}，@ref{3f86,,ndim}。

@node 只读，格式,形状，步幅，子偏移量,与请求无关的字段,缓冲区请求的类型
@anchor{c-api/buffer readonly-format}@anchor{3f8d}
@subsubsection 只读，格式


@quotation

@geindex PyBUF_WRITABLE (C 宏)
@anchor{c-api/buffer c PyBUF_WRITABLE}@anchor{3f80}
@deffn {C 宏} PyBUF_WRITABLE

控制 @ref{3f81,,readonly} 字段。如果设置了，输出程序 @emph{必须} 提供一个可写的缓冲区，否则报告失败。若未设置，输出程序 @emph{可以} 提供只读或可写的缓冲区，但对所有消费者程序 @emph{必须} 保持一致。
@end deffn

@geindex PyBUF_FORMAT (C 宏)
@anchor{c-api/buffer c PyBUF_FORMAT}@anchor{3f84}
@deffn {C 宏} PyBUF_FORMAT

控制 @ref{3f83,,format} 字段。 如果设置，则必须正确填写此字段。其他情况下，此字段必须为`@w{`}NULL`@w{`}。
@end deffn
@end quotation

@ref{3f80,,PyBUF_WRITABLE} 可以和下一节的所有标志联用。由于 @ref{3f7f,,PyBUF_SIMPLE} 定义为 0，所以 @ref{3f80,,PyBUF_WRITABLE} 可以作为一个独立的标志，用于请求一个简单的可写缓冲区。

@ref{3f84,,PyBUF_FORMAT} 可以被设为除了 @ref{3f7f,,PyBUF_SIMPLE} 之外的任何标志。 后者已经按暗示了`@w{`}B`@w{`}(无符号字节串)格式。

@node 形状，步幅，子偏移量,连续性的请求,只读，格式,缓冲区请求的类型
@anchor{c-api/buffer shape-strides-suboffsets}@anchor{3f8e}
@subsubsection 形状，步幅，子偏移量


控制内存逻辑结构的标志按照复杂度的递减顺序列出。注意，每个标志包含它下面的所有标志。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

请求

@tab

形状

@tab

步幅

@tab

子偏移量

@item

@geindex PyBUF_INDIRECT (C 宏)
@anchor{c-api/buffer c PyBUF_INDIRECT}@anchor{3f8f}
@deffn {C 宏} PyBUF_INDIRECT
@end deffn

@tab

是

@tab

是

@tab

如果需要的话

@item

@geindex PyBUF_STRIDES (C 宏)
@anchor{c-api/buffer c PyBUF_STRIDES}@anchor{3f90}
@deffn {C 宏} PyBUF_STRIDES
@end deffn

@tab

是

@tab

是

@tab

NULL

@item

@geindex PyBUF_ND (C 宏)
@anchor{c-api/buffer c PyBUF_ND}@anchor{3f91}
@deffn {C 宏} PyBUF_ND
@end deffn

@tab

是

@tab

NULL

@tab

NULL

@item

@geindex PyBUF_SIMPLE (C 宏)
@anchor{c-api/buffer c PyBUF_SIMPLE}@anchor{3f7f}
@deffn {C 宏} PyBUF_SIMPLE
@end deffn

@tab

NULL

@tab

NULL

@tab

NULL

@end multitable


@geindex contiguous
@geindex C-contiguous
@geindex Fortran contiguous

@node 连续性的请求,复合请求,形状，步幅，子偏移量,缓冲区请求的类型
@anchor{c-api/buffer contiguity-requests}@anchor{3f92}
@subsubsection 连续性的请求


可以显式地请求C 或 Fortran @ref{181d,,连续} ，不管有没有步幅信息。若没有步幅信息，则缓冲区必须是 C-连续的。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxx} 
@headitem

请求

@tab

形状

@tab

步幅

@tab

子偏移量

@tab

邻接

@item

@geindex PyBUF_C_CONTIGUOUS (C 宏)
@anchor{c-api/buffer c PyBUF_C_CONTIGUOUS}@anchor{3f93}
@deffn {C 宏} PyBUF_C_CONTIGUOUS
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

C

@item

@geindex PyBUF_F_CONTIGUOUS (C 宏)
@anchor{c-api/buffer c PyBUF_F_CONTIGUOUS}@anchor{3f94}
@deffn {C 宏} PyBUF_F_CONTIGUOUS
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

F

@item

@geindex PyBUF_ANY_CONTIGUOUS (C 宏)
@anchor{c-api/buffer c PyBUF_ANY_CONTIGUOUS}@anchor{3f95}
@deffn {C 宏} PyBUF_ANY_CONTIGUOUS
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

C 或 F

@item

@ref{3f91,,PyBUF_ND}

@tab

是

@tab

NULL

@tab

NULL

@tab

C

@end multitable


@node 复合请求,,连续性的请求,缓冲区请求的类型
@anchor{c-api/buffer compound-requests}@anchor{3f96}
@subsubsection 复合请求


所有可能的请求都由上一节中某些标志的组合完全定义。为方便起见，缓冲区协议提供常用的组合作为单个标志。

在下表中，@emph{U} 代表连续性未定义。消费者程序必须调用  @ref{3f97,,PyBuffer_IsContiguous()} 以确定连续性。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} {xxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxx} {xxxxxxxxxx} 
@headitem

请求

@tab

形状

@tab

步幅

@tab

子偏移量

@tab

邻接

@tab

只读

@tab

格式

@item

@geindex PyBUF_FULL (C 宏)
@anchor{c-api/buffer c PyBUF_FULL}@anchor{3f98}
@deffn {C 宏} PyBUF_FULL
@end deffn

@tab

是

@tab

是

@tab

如果需要的话

@tab

U

@tab

0

@tab

是

@item

@geindex PyBUF_FULL_RO (C 宏)
@anchor{c-api/buffer c PyBUF_FULL_RO}@anchor{3f99}
@deffn {C 宏} PyBUF_FULL_RO
@end deffn

@tab

是

@tab

是

@tab

如果需要的话

@tab

U

@tab

1 或 0

@tab

是

@item

@geindex PyBUF_RECORDS (C 宏)
@anchor{c-api/buffer c PyBUF_RECORDS}@anchor{3f9a}
@deffn {C 宏} PyBUF_RECORDS
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

U

@tab

0

@tab

是

@item

@geindex PyBUF_RECORDS_RO (C 宏)
@anchor{c-api/buffer c PyBUF_RECORDS_RO}@anchor{3f9b}
@deffn {C 宏} PyBUF_RECORDS_RO
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

U

@tab

1 或 0

@tab

是

@item

@geindex PyBUF_STRIDED (C 宏)
@anchor{c-api/buffer c PyBUF_STRIDED}@anchor{3f9c}
@deffn {C 宏} PyBUF_STRIDED
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

U

@tab

0

@tab

NULL

@item

@geindex PyBUF_STRIDED_RO (C 宏)
@anchor{c-api/buffer c PyBUF_STRIDED_RO}@anchor{3f9d}
@deffn {C 宏} PyBUF_STRIDED_RO
@end deffn

@tab

是

@tab

是

@tab

NULL

@tab

U

@tab

1 或 0

@tab

NULL

@item

@geindex PyBUF_CONTIG (C 宏)
@anchor{c-api/buffer c PyBUF_CONTIG}@anchor{3f9e}
@deffn {C 宏} PyBUF_CONTIG
@end deffn

@tab

是

@tab

NULL

@tab

NULL

@tab

C

@tab

0

@tab

NULL

@item

@geindex PyBUF_CONTIG_RO (C 宏)
@anchor{c-api/buffer c PyBUF_CONTIG_RO}@anchor{3f9f}
@deffn {C 宏} PyBUF_CONTIG_RO
@end deffn

@tab

是

@tab

NULL

@tab

NULL

@tab

C

@tab

1 或 0

@tab

NULL

@end multitable


@node 复杂数组,缓冲区相关函数,缓冲区请求的类型,缓冲协议
@anchor{c-api/buffer complex-arrays}@anchor{3f88}
@subsubsection 复杂数组


@menu
* NumPy-风格：形状和步幅:: 
* PIL-风格：形状，步幅和子偏移量:: 

@end menu

@node NumPy-风格：形状和步幅,PIL-风格：形状，步幅和子偏移量,,复杂数组
@anchor{c-api/buffer numpy-style-shape-and-strides}@anchor{3fa0}
@subsubsection NumPy-风格：形状和步幅


NumPy 风格数组的逻辑结构由 @ref{3f82,,itemsize} 、 @ref{3f86,,ndim} 、 @ref{3f85,,shape} 和 @ref{3f7a,,strides} 定义。

如果 @code{ndim == 0} ， @ref{3f79,,buf} 指向的内存位置被解释为大小为 @ref{3f82,,itemsize} 的标量。这时， @ref{3f85,,shape} 和 @ref{3f7a,,strides} 都为 @code{NULL}。

如果 @ref{3f7a,,strides} 为 @code{NULL}，则数组将被解释为一个标准的 n 维 C 语言数组。否则，消费者程序必须按如下方式访问 n 维数组：

@example
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);
@end example

如上所述，@ref{3f79,,buf} 可以指向实际内存块中的任意位置。输出者程序可以用该函数检查缓冲区的有效性。

@example
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
    """Verify that the parameters represent a valid array within
       the bounds of the allocated memory:
           char *mem: start of the physical memory block
           memlen: length of the physical memory block
           offset: (char *)buf - mem
    """
    if offset % itemsize:
        return False
    if offset < 0 or offset+itemsize > memlen:
        return False
    if any(v % itemsize for v in strides):
        return False

    if ndim <= 0:
        return ndim == 0 and not shape and not strides
    if 0 in shape:
        return True

    imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] <= 0)
    imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] > 0)

    return 0 <= offset+imin and offset+imax+itemsize <= memlen
@end example

@node PIL-风格：形状，步幅和子偏移量,,NumPy-风格：形状和步幅,复杂数组
@anchor{c-api/buffer pil-style-shape-strides-and-suboffsets}@anchor{3fa1}
@subsubsection PIL-风格：形状，步幅和子偏移量


除了常规项之外， PIL 风格的数组还可以包含指针，必须跟随这些指针才能到达维度的下一个元素。例如，常规的三维 C 语言数组 @code{char v[2][2][3]} 可以看作是一个指向 2 个二维数组的 2 个指针：@code{char (*v[2])[2][3]}。在子偏移表示中，这两个指针可以嵌入在 @ref{3f79,,buf} 的开头，指向两个可以位于内存任何位置的 @code{char x[2][3]} 数组。

这是一个函数，当n维索引所指向的N-D数组中有`@w{`}NULL`@w{`}步长和子偏移量时，它返回一个指针

@example
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
                       Py_ssize_t *suboffsets, Py_ssize_t *indices) @{
    char *pointer = (char*)buf;
    int i;
    for (i = 0; i < ndim; i++) @{
        pointer += strides[i] * indices[i];
        if (suboffsets[i] >=0 ) @{
            pointer = *((char**)pointer) + suboffsets[i];
        @}
    @}
    return (void*)pointer;
@}
@end example

@node 缓冲区相关函数,,复杂数组,缓冲协议
@anchor{c-api/buffer buffer-related-functions}@anchor{3fa2}
@subsubsection 缓冲区相关函数


@geindex PyObject_CheckBuffer (C 函数)
@anchor{c-api/buffer c PyObject_CheckBuffer}@anchor{26d}
@deffn {C 函数} int PyObject_CheckBuffer (PyObject@w{ }*obj)

如果 @emph{obj} 支持缓冲区接口，则返回 @code{1}，否则返回 @code{0}。 返回 @code{1} 时不保证 @ref{df3,,PyObject_GetBuffer()} 一定成功。本函数一定调用成功。
@end deffn

@geindex PyObject_GetBuffer (C 函数)
@anchor{c-api/buffer c PyObject_GetBuffer}@anchor{df3}
@deffn {C 函数} int PyObject_GetBuffer (PyObject@w{ }*exporter, Py_buffer@w{ }*view, int@w{ }flags)

向 @emph{输出器程序} 发送请求，按照 @emph{flags} 指定的内容填充 @emph{view}。如果 输出器程序不能提供准确类型的缓冲区，@emph{必须} 触发 @code{PyExc_BufferError}，设置 @code{view->obj} 为 @code{NULL} 并返回 @code{-1}。

成功时，填充 @emph{view}，将 @code{view->obj} 设为对 @emph{exporter} 的新引用，并返回 0。 当链式缓冲区提供程序将请求重定向到一个对象时，@code{view->obj}  可以引用该对象而不是 @emph{exporter} (参见 @ref{3f75,,缓冲区对象结构})。

@ref{df3,,PyObject_GetBuffer()} 必须与 @ref{e21,,PyBuffer_Release()} 同时调用成功，类似于 @code{malloc()} 和 @code{free()}。因此，消费者程序用完缓冲区后， @ref{e21,,PyBuffer_Release()} 必须保证被调用一次。
@end deffn

@geindex PyBuffer_Release (C 函数)
@anchor{c-api/buffer c PyBuffer_Release}@anchor{e21}
@deffn {C 函数} void PyBuffer_Release (Py_buffer@w{ }*view)

释放缓冲区 @emph{view} 并递减 @code{view->obj} 的引用计数。该函数必须在缓冲区不再使用时才能调用，否则可能会发生引用泄漏。

若该函数针对的缓冲区不是通过 @ref{df3,,PyObject_GetBuffer()} 获得的，将会出错。
@end deffn

@geindex PyBuffer_SizeFromFormat (C 函数)
@anchor{c-api/buffer c PyBuffer_SizeFromFormat}@anchor{110d}
@deffn {C 函数} Py_ssize_t PyBuffer_SizeFromFormat (const char@w{ }*format)

返回 @ref{3f82,,itemsize} 中隐含的 @ref{3f83,,format} 。如果出错，会触发异常并返回 -1。


3.9 新版功能.

@end deffn

@geindex PyBuffer_IsContiguous (C 函数)
@anchor{c-api/buffer c PyBuffer_IsContiguous}@anchor{3f97}
@deffn {C 函数} int PyBuffer_IsContiguous (Py_buffer@w{ }*view, char@w{ }order)

如果 @emph{view} 定义的内存是 C 风格（@emph{order} 为 @code{'C'}）或 Fortran 风格（@emph{order} 为 @code{'F'}） @ref{181d,,contiguous} 或其中之一（@emph{order} 是 @code{'A'}），则返回 @code{1}。否则返回 @code{0}。该函数总会成功。
@end deffn

@geindex PyBuffer_GetPointer (C 函数)
@anchor{c-api/buffer c PyBuffer_GetPointer}@anchor{3fa3}
@deffn {C 函数} void* PyBuffer_GetPointer (Py_buffer@w{ }*view, Py_ssize_t@w{ }*indices)

获取给定 @emph{view} 内的 @emph{indices} 所指向的内存区域。@emph{indices} 必须指向一个 @code{view->ndim} 索引的数组。
@end deffn

@geindex PyBuffer_FromContiguous (C 函数)
@anchor{c-api/buffer c PyBuffer_FromContiguous}@anchor{3fa4}
@deffn {C 函数} int PyBuffer_FromContiguous (Py_buffer@w{ }*view, void@w{ }*buf, Py_ssize_t@w{ }len, char@w{ }fort)

从 @emph{buf} 复制连续的 @emph{len} 字节到 @emph{view} 。@emph{fort} 可以是 @code{'C'} 或 @code{'F'`@w{`}（对应于 C 风格或 Fortran 风格的顺序）。成功时返回  `@w{`}0}，错误时返回  @code{-1}。
@end deffn

@geindex PyBuffer_ToContiguous (C 函数)
@anchor{c-api/buffer c PyBuffer_ToContiguous}@anchor{3fa5}
@deffn {C 函数} int PyBuffer_ToContiguous (void@w{ }*buf, Py_buffer@w{ }*src, Py_ssize_t@w{ }len, char@w{ }order)

从 @emph{src} 复制 @emph{len} 字节到 @emph{buf} ，成为连续字节串的形式。@emph{order} 可以是 @code{'C'} 或 @code{'F'} 或 @code{'A'`@w{`}（对应于 C 风格、Fortran 风格的顺序或其中任意一种）。成功时返回 `@w{`}0}，出错时返回 @code{-1}。

如果 @emph{len} != @emph{src->len} 则此函数将报错。
@end deffn

@geindex PyBuffer_FillContiguousStrides (C 函数)
@anchor{c-api/buffer c PyBuffer_FillContiguousStrides}@anchor{3fa6}
@deffn {C 函数} void PyBuffer_FillContiguousStrides (int@w{ }ndims, Py_ssize_t@w{ }*shape, Py_ssize_t@w{ }*strides, int@w{ }itemsize, char@w{ }order)

用给定形状的 @ref{181d,,contiguous} 字节串数组 (如果 @emph{order} 为 @code{'C'} 则为 C 风格，如果 @emph{order} 为 @code{'F'} 则为 Fortran 风格) 来填充 @emph{strides} 数组，每个元素具有给定的字节数。
@end deffn

@geindex PyBuffer_FillInfo (C 函数)
@anchor{c-api/buffer c PyBuffer_FillInfo}@anchor{3f7d}
@deffn {C 函数} int PyBuffer_FillInfo (Py_buffer@w{ }*view, PyObject@w{ }*exporter, void@w{ }*buf, Py_ssize_t@w{ }len, int@w{ }readonly, int@w{ }flags)

处理导出程序的缓冲区请求，该导出程序要公开大小为 @emph{len} 的 @emph{buf} ，并根据 @emph{readonly} 设置可写性。@emph{bug} 被解释为一个无符号字节序列。

参数 @emph{flags} 表示请求的类型。该函数总是按照 flag 指定的内容填入 @emph{view}，除非 @emph{buf} 设为只读，并且 @emph{flag} 中设置了 @ref{3f80,,PyBUF_WRITABLE} 标志。

成功时，将 @code{view->obj} 设为 @emph{exporter} 的新引用，并返回 0。否则，引发 @code{PyExc_BufferError} ，将 @code{view->obj} 设为 @code{NULL}，并返回 @code{-1}。

如果此函数用作 @ref{3f75,,getbufferproc} 的一部分，则 @emph{exporter} 必须设置为导出对象，并且必须在未修改的情况下传递 @emph{flags}。否则，@emph{exporter} 必须是 @code{NULL}。
@end deffn

@node 旧缓冲协议,,缓冲协议,抽象对象层
@anchor{c-api/objbuffer doc}@anchor{3fa7}@anchor{c-api/objbuffer old-buffer-protocol}@anchor{3fa8}
@subsection 旧缓冲协议



3.0 版后已移除.


这些函数是 Python 2 中“旧缓冲协议”API 的组成部分。 在 Python 3 中，此协议已不复存在，但这些函数仍然被公开以便移植 2.x 的代码。 它们被用作 @ref{174c,,新缓冲协议} 的兼容性包装器，但它们并不会在缓冲被导出时向你提供对所获资源的生命周期控制。

因此，推荐你调用 @ref{df3,,PyObject_GetBuffer()} (或者配合 @ref{39b,,PyArg_ParseTuple()} 函数族使用 @code{y*} 或 @code{w*} @ref{3fb,,格式码}) 来获取一个对象的缓冲视图，并在缓冲视图可被释放时调用 @ref{e21,,PyBuffer_Release()}。

@geindex PyObject_AsCharBuffer (C 函数)
@anchor{c-api/objbuffer c PyObject_AsCharBuffer}@anchor{3fa9}
@deffn {C 函数} int PyObject_AsCharBuffer (PyObject@w{ }*obj, const char@w{ }**buffer, Py_ssize_t@w{ }*buffer_len)

返回一个指向可用作基于字符的输入的只读内存地址的指针。 @emph{obj} 参数必须支持单段字符缓冲接口。 成功时返回 @code{0}，将 @emph{buffer} 设为内存地址并将 @emph{buffer_len} 设为缓冲区长度。 出错时返回 @code{-1} 并设置一个 @ref{1ff,,TypeError}。
@end deffn

@geindex PyObject_AsReadBuffer (C 函数)
@anchor{c-api/objbuffer c PyObject_AsReadBuffer}@anchor{3faa}
@deffn {C 函数} int PyObject_AsReadBuffer (PyObject@w{ }*obj, const void@w{ }**buffer, Py_ssize_t@w{ }*buffer_len)

返回一个指向包含任意数据的只读内存地址的指针。 @emph{obj} 参数必须支持单段可读缓冲接口。 成功时返回 @code{0}，将 @emph{buffer} 设为内存地址并将 @emph{buffer_len} 设为缓冲区长度。 出错时返回 @code{-1} 并设置一个 @ref{1ff,,TypeError}。
@end deffn

@geindex PyObject_CheckReadBuffer (C 函数)
@anchor{c-api/objbuffer c PyObject_CheckReadBuffer}@anchor{3fab}
@deffn {C 函数} int PyObject_CheckReadBuffer (PyObject@w{ }*o)

如果 @emph{o} 支持单段可读缓冲接口则返回 @code{1}。 否则返回 @code{0}。 此函数总是会成功执行。

请注意此函数会尝试获取并释放一个缓冲区，并且在调用对应函数期间发生的异常会被屏蔽。 要获取错误报告则应改用 @ref{df3,,PyObject_GetBuffer()}。
@end deffn

@geindex PyObject_AsWriteBuffer (C 函数)
@anchor{c-api/objbuffer c PyObject_AsWriteBuffer}@anchor{3fac}
@deffn {C 函数} int PyObject_AsWriteBuffer (PyObject@w{ }*obj, void@w{ }**buffer, Py_ssize_t@w{ }*buffer_len)

返回一个指向可写内存地址的指针。 @emph{obj} 必须支持单段字符缓冲接口。 成功时返回 @code{0}，将 @emph{buffer} 设为内存地址并将 @emph{buffer_len} 设为缓冲区长度。 出错时返回 @code{-1} 并设置一个 @ref{1ff,,TypeError}。
@end deffn

@node 具体的对象层,初始化，终结和线程,抽象对象层,Python/C API 参考手册
@anchor{c-api/concrete doc}@anchor{3fad}@anchor{c-api/concrete concrete}@anchor{3fae}@anchor{c-api/concrete concrete-objects-layer}@anchor{3faf}
@section 具体的对象层


本章中的函数特定于某些 Python 对象类型。 将错误类型的对象传递给它们并不是一个好主意；如果您从 Python 程序接收到一个对象，但不确定它是否具有正确的类型，则必须首先执行类型检查；例如，要检查对象是否为字典，请使用 @ref{3fb0,,PyDict_Check()}。 本章的结构类似于 Python 对象类型的“家族树”。

@cartouche
@quotation 警告 
虽然本章所描述的函数会仔细检查传入对象的类型，但是其中许多函数不会检查传入的对象是否为 @code{NULL}。 允许传入 @code{NULL} 可能导致内存访问冲突和解释器的立即终止。
@end quotation
@end cartouche

@menu
* 基本对象:: 
* 数值对象:: 
* 序列对象:: 
* 容器对象:: 
* 函数对象:: 
* 其他对象: 其他对象<2>. 

@end menu

@node 基本对象,数值对象,,具体的对象层
@anchor{c-api/concrete fundamental}@anchor{3fb1}@anchor{c-api/concrete fundamental-objects}@anchor{3fb2}
@subsection 基本对象


本节描述Python类型对象和单一实例对象 象None。

@menu
* Type 对象:: 
* None 对象:: 

@end menu

@node Type 对象,None 对象,,基本对象
@anchor{c-api/type doc}@anchor{3fb3}@anchor{c-api/type type-objects}@anchor{3fb4}@anchor{c-api/type typeobjects}@anchor{3fb5}
@subsubsection Type 对象


@geindex 对象; type

@geindex PyTypeObject (C 类型)
@anchor{c-api/type c PyTypeObject}@anchor{3fe}
@deffn {C 类型} PyTypeObject

对象的 C 结构用于描述 built-in 类型。
@end deffn

@geindex PyType_Type (C 变量)
@anchor{c-api/type c PyType_Type}@anchor{3fb6}
@deffn {C 变量} PyTypeObject PyType_Type

这是属于 type 对象的 type object，它在 Python 层面和 @ref{709,,type} 是相同的对象。
@end deffn

@geindex PyType_Check (C 函数)
@anchor{c-api/type c PyType_Check}@anchor{10dd}
@deffn {C 函数} int PyType_Check (PyObject@w{ }*o)

如果对象 @emph{o} 是一个类型对象，包括派生自标准类型对象的类型实例则返回非零值。 在所有其它情况下都返回 0。 此函数将总是成功执行。
@end deffn

@geindex PyType_CheckExact (C 函数)
@anchor{c-api/type c PyType_CheckExact}@anchor{10de}
@deffn {C 函数} int PyType_CheckExact (PyObject@w{ }*o)

如果对象 @emph{o} 是一个类型对象，但不是标准类型对象的子类型则返回非零值。 在所有其它情况下都返回 0。 此函数将总是成功执行。
@end deffn

@geindex PyType_ClearCache (C 函数)
@anchor{c-api/type c PyType_ClearCache}@anchor{3fb7}
@deffn {C 函数} unsigned int PyType_ClearCache ()

清空内部查找缓存。 返回当前版本标签。
@end deffn

@geindex PyType_GetFlags (C 函数)
@anchor{c-api/type c PyType_GetFlags}@anchor{105c}
@deffn {C 函数} unsigned long PyType_GetFlags (PyTypeObject*@w{ }type)

返回 @emph{type} 的 @ref{105b,,tp_flags} 成员。 此函数主要是配合 @cite{Py_LIMITED_API} 使用；单独的旗标位会确保在各个 Python 发行版之间保持稳定，但对 @ref{105b,,tp_flags} 本身的访问并不是受限 API 的一部分。


3.2 新版功能.



在 3.4 版更改: 返回类型现在是 @code{unsigned long} 而不是 @code{long}。

@end deffn

@geindex PyType_Modified (C 函数)
@anchor{c-api/type c PyType_Modified}@anchor{3fb8}
@deffn {C 函数} void PyType_Modified (PyTypeObject@w{ }*type)

使该类型及其所有子类型的内部查找缓存失效。 此函数必须在对该类型的属性或基类进行任何手动修改之后调用。
@end deffn

@geindex PyType_HasFeature (C 函数)
@anchor{c-api/type c PyType_HasFeature}@anchor{105a}
@deffn {C 函数} int PyType_HasFeature (PyTypeObject@w{ }*o, int@w{ }feature)

如果类型对象 @emph{o} 设置了特性 @emph{feature} 则返回非零值。 类型特性是用单个比特位旗标来表示的。
@end deffn

@geindex PyType_IS_GC (C 函数)
@anchor{c-api/type c PyType_IS_GC}@anchor{3fb9}
@deffn {C 函数} int PyType_IS_GC (PyTypeObject@w{ }*o)

如果类型对象包括对循环检测器的支持则返回真值；这会测试类型旗标 @ref{3da1,,Py_TPFLAGS_HAVE_GC}。
@end deffn

@geindex PyType_IsSubtype (C 函数)
@anchor{c-api/type c PyType_IsSubtype}@anchor{3fba}
@deffn {C 函数} int PyType_IsSubtype (PyTypeObject@w{ }*a, PyTypeObject@w{ }*b)

如果 @emph{a} 是 @emph{b} 的子类型则返回真值。

此函数只检查实际的子类型，这意味着 @ref{15b4,,__subclasscheck__()} 不会在 @emph{b} 上被调用。 请调用 @ref{897,,PyObject_IsSubclass()} 来执行与 @ref{55b,,issubclass()} 所做的相同检查。
@end deffn

@geindex PyType_GenericAlloc (C 函数)
@anchor{c-api/type c PyType_GenericAlloc}@anchor{3a1}
@deffn {C 函数} PyObject* PyType_GenericAlloc (PyTypeObject@w{ }*type, Py_ssize_t@w{ }nitems)
@emph{Return value: New reference.}
类型对象的 @ref{3d95,,tp_alloc} 槽位的通用处理句柄。 请使用 Python 的默认内存分配机制来分配一个新的实例并将其所有内容初始化为 @code{NULL}。
@end deffn

@geindex PyType_GenericNew (C 函数)
@anchor{c-api/type c PyType_GenericNew}@anchor{3d91}
@deffn {C 函数} PyObject* PyType_GenericNew (PyTypeObject@w{ }*type, PyObject@w{ }*args, PyObject@w{ }*kwds)
@emph{Return value: New reference.}
类型对象的 @ref{3d90,,tp_new} 槽位的通用处理句柄。 请使用类型的 @ref{3d95,,tp_alloc} 槽位来创建一个新的实例。
@end deffn

@geindex PyType_Ready (C 函数)
@anchor{c-api/type c PyType_Ready}@anchor{3d96}
@deffn {C 函数} int PyType_Ready (PyTypeObject@w{ }*type)

最终化一个类型对象。 这应当在所有类型对象上调用以完成它们的初始化。 此函数会负责从一个类型的基类添加被继承的槽位。 成功时返回 @code{0}，或是在出错时返回 @code{-1} 并设置一个异常。

@cartouche
@quotation 注解 
如果某些基类实现了 GC 协议并且所提供的类型的旗标中未包括 @ref{3da1,,Py_TPFLAGS_HAVE_GC}，则将自动从其父类实现 GC 协议。 相反地，如果被创建的类型的旗标中未包括 @ref{3da1,,Py_TPFLAGS_HAVE_GC} 则它 @strong{必须} 自己通过实现 @ref{23c,,tp_traverse} 句柄来实现 GC 协议。
@end quotation
@end cartouche
@end deffn

@geindex PyType_GetSlot (C 函数)
@anchor{c-api/type c PyType_GetSlot}@anchor{a12}
@deffn {C 函数} void* PyType_GetSlot (PyTypeObject@w{ }*type, int@w{ }slot)

返回存储在给定槽位中的函数指针。 如果结果为 @code{NULL}，则表示或者该槽位为 @code{NULL}，或者该函数调用传入了无效的形参。 调用方通常要将结果指针转换到适当的函数类型。

请参阅 @code{PyType_Slot.slot} 查看可用的 @emph{slot} 参数值。

An exception is raised if @emph{type} is not a heap type.


3.4 新版功能.

@end deffn

@geindex PyType_GetModule (C 函数)
@anchor{c-api/type c PyType_GetModule}@anchor{247}
@deffn {C 函数} PyObject* PyType_GetModule (PyTypeObject@w{ }*type)

返回当使用 @ref{246,,PyType_FromModuleAndSpec()} 创建类型时关联到给定类型的模块对象。

如果没有关联到给定类型的模块，则设置 @ref{1ff,,TypeError} 并返回 @code{NULL}。

此函数通常被用于获取方法定义所在的模块。 请注意在这样的方法中，@code{PyType_GetModule(Py_TYPE(self))} 可能不会返回预期的结果。 @code{Py_TYPE(self)} 可以是目标类的一个 @emph{子类}，而子类并不一定是在与其上级类相同的模块中定义的。 请参阅 @ref{249,,PyCMethod} 了解如何获取方法定义所在的类。


3.9 新版功能.

@end deffn

@geindex PyType_GetModuleState (C 函数)
@anchor{c-api/type c PyType_GetModuleState}@anchor{248}
@deffn {C 函数} void* PyType_GetModuleState (PyTypeObject@w{ }*type)

返回关联到给定类型的模块对象的状态。 这是一个在 @ref{247,,PyType_GetModule()} 的结果上调用 @ref{25f,,PyModule_GetState()} 的快捷方式。

如果没有关联到给定类型的模块，则设置 @ref{1ff,,TypeError} 并返回 @code{NULL}。

如果 @emph{type} 有关联的模块但其状态为 @code{NULL}，则返回 @code{NULL} 且不设置异常。


3.9 新版功能.

@end deffn

@menu
* 创建堆分配类型:: 

@end menu

@node 创建堆分配类型,,,Type 对象
@anchor{c-api/type creating-heap-allocated-types}@anchor{3fbb}
@subsubsection 创建堆分配类型


下列函数和结构体可被用来创建 @ref{3fbc,,堆类型}。

@geindex PyType_FromModuleAndSpec (C 函数)
@anchor{c-api/type c PyType_FromModuleAndSpec}@anchor{246}
@deffn {C 函数} PyObject* PyType_FromModuleAndSpec (PyObject@w{ }*module, PyType_Spec@w{ }*spec, PyObject@w{ }*bases)
@emph{Return value: New reference.}
Creates and returns a heap type object from the @emph{spec}
(@ref{3fbd,,Py_TPFLAGS_HEAPTYPE}).

If @emph{bases} is a tuple, the created heap type contains all types contained
in it as base types.

If @emph{bases} is @code{NULL}, the @emph{Py_tp_bases} slot is used instead.
If that also is @code{NULL}, the @emph{Py_tp_base} slot is used instead.
If that also is @code{NULL}, the new type derives from @ref{3da,,object}.

@emph{module} 参数可被用来记录新类定义所在的模块。 它必须是一个模块对象或为 @code{NULL}。 如果不为 @code{NULL}，则该模块会被关联到新类型并且可在之后通过 @ref{247,,PyType_GetModule()} 来获取。 这个关联模块不可被子类继承；它必须为每个类单独指定。

此函数会在新类型上调用 @ref{3d96,,PyType_Ready()}。


3.9 新版功能.

@end deffn

@geindex PyType_FromSpecWithBases (C 函数)
@anchor{c-api/type c PyType_FromSpecWithBases}@anchor{1077}
@deffn {C 函数} PyObject* PyType_FromSpecWithBases (PyType_Spec@w{ }*spec, PyObject@w{ }*bases)
@emph{Return value: New reference.}
等价于 @code{PyType_FromModuleAndSpec(NULL, spec, bases)}。


3.3 新版功能.

@end deffn

@geindex PyType_FromSpec (C 函数)
@anchor{c-api/type c PyType_FromSpec}@anchor{23b}
@deffn {C 函数} PyObject* PyType_FromSpec (PyType_Spec@w{ }*spec)
@emph{Return value: New reference.}
等价于 @code{PyType_FromSpecWithBases(spec, NULL)}。
@end deffn

@geindex PyType_Spec (C 类型)
@anchor{c-api/type c PyType_Spec}@anchor{3fbe}
@deffn {C 类型} PyType_Spec

定义一个类型的行为的结构体。

@geindex PyType_Spec.PyType_Spec.name (C 成员)
@anchor{c-api/type c PyType_Spec PyType_Spec name}@anchor{3fbf}
@deffn {C 成员} const char* PyType_Spec.name

类型的名称，用来设置 @ref{3dae,,PyTypeObject.tp_name}。
@end deffn

@geindex PyType_Spec.PyType_Spec.basicsize (C 成员)
@anchor{c-api/type c PyType_Spec PyType_Spec basicsize}@anchor{3fc0}
@deffn {C 成员} int PyType_Spec.basicsize
@end deffn

@geindex PyType_Spec.PyType_Spec.itemsize (C 成员)
@anchor{c-api/type c PyType_Spec PyType_Spec itemsize}@anchor{3fc1}
@deffn {C 成员} int PyType_Spec.itemsize

以字节数表示的实例大小，用来设置 @ref{26b,,PyTypeObject.tp_basicsize} 和 @ref{3d8d,,PyTypeObject.tp_itemsize}。
@end deffn

@geindex PyType_Spec.PyType_Spec.flags (C 成员)
@anchor{c-api/type c PyType_Spec PyType_Spec flags}@anchor{3fc2}
@deffn {C 成员} int PyType_Spec.flags

类型旗标，用来设置 @ref{105b,,PyTypeObject.tp_flags}。

如果未设置 @code{Py_TPFLAGS_HEAPTYPE} 旗标，则 @ref{1077,,PyType_FromSpecWithBases()} 会自动设置它。
@end deffn

@geindex PyType_Spec.PyType_Spec.slots (C 成员)
@anchor{c-api/type c PyType_Spec PyType_Spec slots}@anchor{3fc3}
@deffn {C 成员} PyType_Slot *PyType_Spec.slots

@ref{3fc4,,PyType_Slot} 结构体的数组。 以特殊槽位值 @code{@{0, NULL@}} 来结束。
@end deffn
@end deffn

@geindex PyType_Slot (C 类型)
@anchor{c-api/type c PyType_Slot}@anchor{3fc4}
@deffn {C 类型} PyType_Slot

定义一个类型的可选功能的结构体，包含一个槽位 ID 和一个值指针。

@geindex PyType_Slot.PyType_Slot.slot (C 成员)
@anchor{c-api/type c PyType_Slot PyType_Slot slot}@anchor{3fc5}
@deffn {C 成员} int PyType_Slot.slot

@quotation

槽位 ID。

槽位 ID 的类名像是结构体 @ref{3fe,,PyTypeObject}, @ref{e4e,,PyNumberMethods}, @ref{3dbc,,PySequenceMethods}, @ref{3dbd,,PyMappingMethods} 和 @ref{3fc6,,PyAsyncMethods} 的字段名附加一个 @code{Py_} 前缀。 举例来说，使用:


@itemize *

@item 
@code{Py_tp_dealloc} 设置 @ref{3d93,,PyTypeObject.tp_dealloc}

@item 
@code{Py_nb_add} 设置 @ref{3fc7,,PyNumberMethods.nb_add}

@item 
@code{Py_sq_length} 设置 @ref{3fc8,,PySequenceMethods.sq_length}
@end itemize

下列字段完全无法使得 @ref{3fbe,,PyType_Spec} 和 @ref{3fc4,,PyType_Slot} 来设置:


@itemize *

@item 
@ref{3fc9,,tp_dict}

@item 
@ref{3fca,,tp_mro}

@item 
@ref{3fcb,,tp_cache}

@item 
@ref{3fcc,,tp_subclasses}

@item 
@ref{3fcd,,tp_weaklist}

@item 
@ref{3fce,,tp_vectorcall}

@item 
@ref{26c,,tp_weaklistoffset} (参见 @ref{3fcf,,PyMemberDef})

@item 
@ref{3fd0,,tp_dictoffset} (参见 @ref{3fcf,,PyMemberDef})

@item 
@ref{3f19,,tp_vectorcall_offset} (参见 @ref{3fcf,,PyMemberDef})
@end itemize

下列字段在受限 API 下无法使用 @ref{3fbe,,PyType_Spec} 和 @ref{3fc4,,PyType_Slot} 来设置:


@itemize *

@item 
@ref{3fd1,,bf_getbuffer}

@item 
@ref{3ec7,,bf_releasebuffer}
@end itemize

设置 @code{Py_tp_bases} 或 @code{Py_tp_base} 在某些平台上可能会有问题。 为了避免问题，请改用 @code{PyType_FromSpecWithBases()} 的 @emph{bases} 参数。
@end quotation


在 3.9 版更改: @ref{3fd2,,PyBufferProcs} 中的槽位可能会在不受限 API 中被设置。

@end deffn

@geindex PyType_Slot.PyType_Slot.pfunc (C 成员)
@anchor{c-api/type c PyType_Slot PyType_Slot pfunc}@anchor{3fd3}
@deffn {C 成员} void *PyType_Slot.pfunc

该槽位的预期值。 在大多数情况下，这将是一个指向函数的指针。

May not be @code{NULL}.
@end deffn
@end deffn

@node None 对象,,Type 对象,基本对象
@anchor{c-api/none doc}@anchor{3fd4}@anchor{c-api/none noneobject}@anchor{3fd5}@anchor{c-api/none the-none-object}@anchor{3fd6}
@subsubsection @code{None} 对象


@geindex 对象; None

请注意， @code{None} 的 @ref{3fe,,PyTypeObject} 不会直接在 Python / C API 中公开。 由于 @code{None} 是单例，测试对象标识（在C中使用 @code{==} ）就足够了。 由于同样的原因，没有 @code{PyNone_Check()} 函数。

@geindex Py_None (C 变量)
@anchor{c-api/none c Py_None}@anchor{3d5d}
@deffn {C 变量} PyObject* Py_None

Python @code{None} 对象，表示缺乏值。 这个对象没有方法。 它需要像引用计数一样处理任何其他对象。
@end deffn

@geindex Py_RETURN_NONE (C 宏)
@anchor{c-api/none c Py_RETURN_NONE}@anchor{ea3}
@deffn {C 宏} Py_RETURN_NONE

正确处理来自C函数内的 @ref{3d5d,,Py_None} 返回（也就是说，增加 @code{None} 的引用计数并返回它。）
@end deffn

@node 数值对象,序列对象,基本对象,具体的对象层
@anchor{c-api/concrete numeric-objects}@anchor{3fd7}@anchor{c-api/concrete numericobjects}@anchor{3fd8}
@subsection 数值对象


@geindex 对象; numeric

@menu
* 整数型对象:: 
* 布尔对象:: 
* 浮点数对象:: 
* 复数对象:: 

@end menu

@node 整数型对象,布尔对象,,数值对象
@anchor{c-api/long doc}@anchor{3fd9}@anchor{c-api/long integer-objects}@anchor{3fda}@anchor{c-api/long longobjects}@anchor{3fdb}
@subsubsection 整数型对象


@geindex 对象; long integer
@geindex 对象; integer

所有整数都使用以任意大小的长整数对象表示。

在出错时，大多数 @code{PyLong_As*} API返回 @code{(返回类型)-1} ，无法与一般的数字区分开来。请使用 @ref{3d58,,PyErr_Occurred()} 来区分。

@geindex PyLongObject (C 类型)
@anchor{c-api/long c PyLongObject}@anchor{3fdc}
@deffn {C 类型} PyLongObject

表示 Python 整数对象的 @ref{5bd,,PyObject} 子类型。
@end deffn

@geindex PyLong_Type (C 变量)
@anchor{c-api/long c PyLong_Type}@anchor{3fdd}
@deffn {C 变量} PyTypeObject PyLong_Type

这个 @ref{3fe,,PyTypeObject} 的实例表示 Python 的整数类型。与Python层中的 @ref{205,,int} 相同。
@end deffn

@geindex PyLong_Check (C 函数)
@anchor{c-api/long c PyLong_Check}@anchor{3fde}
@deffn {C 函数} int PyLong_Check (PyObject@w{ }*p)

如果它的参数是 @ref{3fdc,,PyLongObject} 或 @ref{3fdc,,PyLongObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyLong_CheckExact (C 函数)
@anchor{c-api/long c PyLong_CheckExact}@anchor{3fdf}
@deffn {C 函数} int PyLong_CheckExact (PyObject@w{ }*p)

如果其参数属于 @ref{3fdc,,PyLongObject}，但不是 @ref{3fdc,,PyLongObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyLong_FromLong (C 函数)
@anchor{c-api/long c PyLong_FromLong}@anchor{3d5a}
@deffn {C 函数} PyObject* PyLong_FromLong (long@w{ }v)
@emph{Return value: New reference.}
由 @emph{v} 返回一个新的 @ref{3fdc,,PyLongObject} 对象，失败时返回 @code{NULL} 。

当前的实现维护着一个整数对象数组，包含 @code{-5} 和 @code{256} 之间的所有整数对象。 若创建一个位于该区间的 int 时，实际得到的将是对已有对象的引用。
@end deffn

@geindex PyLong_FromUnsignedLong (C 函数)
@anchor{c-api/long c PyLong_FromUnsignedLong}@anchor{1109}
@deffn {C 函数} PyObject* PyLong_FromUnsignedLong (unsigned long@w{ }v)
@emph{Return value: New reference.}
由 C @code{unsigned long} 类型返回一个新的 @ref{3fdc,,PyLongObject} 对象，失败时返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromSsize_t (C 函数)
@anchor{c-api/long c PyLong_FromSsize_t}@anchor{3fe0}
@deffn {C 函数} PyObject* PyLong_FromSsize_t (Py_ssize_t@w{ }v)
@emph{Return value: New reference.}
从 C @ref{391,,Py_ssize_t} 类型返回一个新的 @ref{3fdc,,PyLongObject} 对象，如果失败则返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromSize_t (C 函数)
@anchor{c-api/long c PyLong_FromSize_t}@anchor{110b}
@deffn {C 函数} PyObject* PyLong_FromSize_t (size_t@w{ }v)
@emph{Return value: New reference.}
从 C @code{size_t} 返回一个新的 @ref{3fdc,,PyLongObject} 对象，如果失败则返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromLongLong (C 函数)
@anchor{c-api/long c PyLong_FromLongLong}@anchor{3fe1}
@deffn {C 函数} PyObject* PyLong_FromLongLong (long long@w{ }v)
@emph{Return value: New reference.}
从 C @code{long long} 返回一个新的 @ref{3fdc,,PyLongObject} 对象，失败时返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromUnsignedLongLong (C 函数)
@anchor{c-api/long c PyLong_FromUnsignedLongLong}@anchor{110a}
@deffn {C 函数} PyObject* PyLong_FromUnsignedLongLong (unsigned long long@w{ }v)
@emph{Return value: New reference.}
从 C @code{unsigned long long} 返回一个新的 @ref{3fdc,,PyLongObject} 对象，失败时返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromDouble (C 函数)
@anchor{c-api/long c PyLong_FromDouble}@anchor{1f5}
@deffn {C 函数} PyObject* PyLong_FromDouble (double@w{ }v)
@emph{Return value: New reference.}
从 @emph{v} 的整数部分返回一个新的 @ref{3fdc,,PyLongObject} 对象，如果失败则返回 @code{NULL} 。
@end deffn

@geindex PyLong_FromString (C 函数)
@anchor{c-api/long c PyLong_FromString}@anchor{3fe2}
@deffn {C 函数} PyObject* PyLong_FromString (const char@w{ }*str, char@w{ }**pend, int@w{ }base)
@emph{Return value: New reference.}
根据 @emph{str} 字符串值返回一个新的 @ref{3fdc,,PyLongObject} ，@emph{base} 指定基数。如果 @emph{pend} 不是 @code{NULL} ， @emph{/*pend} 将指向 @emph{str} 中表示这个数字部分的后面的第一个字符。如果 @emph{base} 是 @code{0} ， @emph{str} 将使用 @ref{1562,,整数字面值} 定义来解释；在这种情况下，一个非零的十进制数中的前导零会引发一个 @ref{16d,,ValueError} 。如果 @emph{base} 不是 @code{0} ，它必须在 @code{2} 和 @code{36} 之间，包括2和36。基数说明符后以及数字之间的前导空格、单下划线将被忽略。如果没有数字，将引发 @ref{16d,,ValueError}。
@end deffn

@geindex PyLong_FromUnicode (C 函数)
@anchor{c-api/long c PyLong_FromUnicode}@anchor{3fe3}
@deffn {C 函数} PyObject* PyLong_FromUnicode (Py_UNICODE@w{ }*u, Py_ssize_t@w{ }length, int@w{ }base)
@emph{Return value: New reference.}
将 Unicode 数字序列转换为 Python 整数值。


Deprecated since version 3.3, will be removed in version 3.10: 旧的 @ref{bce,,Py_UNICODE} API的一部分;请迁移到使用 @ref{3fe4,,PyLong_FromUnicodeObject()} 。

@end deffn

@geindex PyLong_FromUnicodeObject (C 函数)
@anchor{c-api/long c PyLong_FromUnicodeObject}@anchor{3fe4}
@deffn {C 函数} PyObject* PyLong_FromUnicodeObject (PyObject@w{ }*u, int@w{ }base)
@emph{Return value: New reference.}
将字符串 @emph{u} 中的 Unicode 数字序列转换为 Python 整数值。


3.3 新版功能.

@end deffn

@geindex PyLong_FromVoidPtr (C 函数)
@anchor{c-api/long c PyLong_FromVoidPtr}@anchor{3fe5}
@deffn {C 函数} PyObject* PyLong_FromVoidPtr (void@w{ }*p)
@emph{Return value: New reference.}
从指针 @emph{p} 创建一个 Python 整数。可以使用 @ref{3fe6,,PyLong_AsVoidPtr()} 返回的指针值。
@end deffn

@c XXX alias PyLong_AS_LONG (for now)

@geindex PyLong_AsLong (C 函数)
@anchor{c-api/long c PyLong_AsLong}@anchor{39a}
@deffn {C 函数} long PyLong_AsLong (PyObject@w{ }*obj)

@geindex LONG_MAX
@geindex OverflowError (built-in exception)

返回 @emph{obj} 的 C @code{long} 表达方式。 如果 @emph{obj} 不是 @ref{3fdc,,PyLongObject} 的实例，先调用它的 @ref{2c9,,__index__()} 或 @ref{2ca,,__int__()} 方法(如果有)将其转换为 @ref{3fdc,,PyLongObject} 。

如果 @emph{obj} 的值溢出了 @code{long} 的范围，会引发 @ref{a4a,,OverflowError}。

发生错误时返回 @code{-1} 。使用 @ref{3d58,,PyErr_Occurred()} 来消歧义。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsLongAndOverflow (C 函数)
@anchor{c-api/long c PyLong_AsLongAndOverflow}@anchor{cd0}
@deffn {C 函数} long PyLong_AsLongAndOverflow (PyObject@w{ }*obj, int@w{ }*overflow)

返回 @emph{obj} 的 C @code{long} 表达方式。 如果 @emph{obj} 不是 @ref{3fdc,,PyLongObject} 的实例，先调用它的 @ref{2c9,,__index__()} 或 @ref{2ca,,__int__()} 方法(如果有)将其转换为 @ref{3fdc,,PyLongObject} 。

如果 @emph{obj} 的值大于 @code{LONG_MAX} 或小于 @code{LONG_MIN}，则会把 @emph{*overflow} 分别置为`@w{`}1`@w{`} 或 @code{-1}，并返回 @code{1}；否则，将 @emph{*overflow}  置为 @cite{0}。如果发生其他异常，则会按常规把 @emph{*overflow} 置为 @code{0}，并返回 @code{-1}。

发生错误时返回 @code{-1} 。使用 @ref{3d58,,PyErr_Occurred()} 来消歧义。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsLongLong (C 函数)
@anchor{c-api/long c PyLong_AsLongLong}@anchor{3fe7}
@deffn {C 函数} long long PyLong_AsLongLong (PyObject@w{ }*obj)

@geindex OverflowError (built-in exception)

Return a C @code{long long} representation of @emph{obj}.  If @emph{obj} is not an
instance of @ref{3fdc,,PyLongObject}, first call its @ref{2c9,,__index__()} or
@ref{2ca,,__int__()} method (if present) to convert it to a
@ref{3fdc,,PyLongObject}.

如果 @emph{obj} 值超出 @code{long long} ，触发 @ref{a4a,,OverflowError}

发生错误时返回 @code{-1} 。使用 @ref{3d58,,PyErr_Occurred()} 来消歧义。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsLongLongAndOverflow (C 函数)
@anchor{c-api/long c PyLong_AsLongLongAndOverflow}@anchor{ccf}
@deffn {C 函数} long long PyLong_AsLongLongAndOverflow (PyObject@w{ }*obj, int@w{ }*overflow)

Return a C @code{long long} representation of @emph{obj}.  If @emph{obj} is not an
instance of @ref{3fdc,,PyLongObject}, first call its @ref{2c9,,__index__()} or
@ref{2ca,,__int__()} method (if present) to convert it to a
@ref{3fdc,,PyLongObject}.

如果 @emph{obj} 的值大于 @code{LLONG_MAX} 或小于 @code{LLONG_MIN}，则按常规将 @emph{*overflow} 分别置为 @code{1} 或 @code{-1}，并返回 -1，否则将 @emph{*overflow} 置为 0。如果触发其他异常则 @emph{*overflow} 置为 0 并返回 -1。

发生错误时返回 @code{-1} 。使用 @ref{3d58,,PyErr_Occurred()} 来消歧义。


3.2 新版功能.



在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsSsize_t (C 函数)
@anchor{c-api/long c PyLong_AsSsize_t}@anchor{3fe8}
@deffn {C 函数} Py_ssize_t PyLong_AsSsize_t (PyObject@w{ }*pylong)

@geindex PY_SSIZE_T_MAX
@geindex OverflowError (built-in exception)

返回 @emph{pylong} 的 C 语言 @ref{391,,Py_ssize_t} 形式。@emph{pylong} 必须是 @ref{3fdc,,PyLongObject} 的实例。

如果 @emph{pylong} 的值超出了 @ref{391,,Py_ssize_t} 的取值范围则会引发 @ref{a4a,,OverflowError}。

发生错误时返回 @code{-1} 。使用 @ref{3d58,,PyErr_Occurred()} 来消歧义。
@end deffn

@geindex PyLong_AsUnsignedLong (C 函数)
@anchor{c-api/long c PyLong_AsUnsignedLong}@anchor{3fe9}
@deffn {C 函数} unsigned long PyLong_AsUnsignedLong (PyObject@w{ }*pylong)

@geindex ULONG_MAX
@geindex OverflowError (built-in exception)

返回 @emph{pylong} 的 C @code{unsigned long} 形式。 @emph{pylong} 必须是 @ref{3fdc,,PyLongObject} 的实例。

如果 @emph{pylong} 的值超出了 @code{unsigned long} 的取值范围则会引发 @ref{a4a,,OverflowError}。

出错时返回 @code{(unsigned long)-1} ，请利用 @ref{3d58,,PyErr_Occurred()} 获取详细信息。
@end deffn

@geindex PyLong_AsSize_t (C 函数)
@anchor{c-api/long c PyLong_AsSize_t}@anchor{3fea}
@deffn {C 函数} size_t PyLong_AsSize_t (PyObject@w{ }*pylong)

@geindex SIZE_MAX
@geindex OverflowError (built-in exception)

返回 @emph{pylong} 的 C 语言 @code{size_t} 形式。@emph{pylong} 必须是 @ref{3fdc,,PyLongObject} 的实例。

如果 @emph{pylong} 的值超出了 @code{size_t} 的取值范围则会引发 @ref{a4a,,OverflowError}。

出错时返回  @code{(size_t)-1} ，请利用 @ref{3d58,,PyErr_Occurred()} 获取详细信息。
@end deffn

@geindex PyLong_AsUnsignedLongLong (C 函数)
@anchor{c-api/long c PyLong_AsUnsignedLongLong}@anchor{cf4}
@deffn {C 函数} unsigned long long PyLong_AsUnsignedLongLong (PyObject@w{ }*pylong)

@geindex OverflowError (built-in exception)

返回 @emph{pylong} 的 C 语言 @code{unsigned long long}  形式。@emph{pylong} 必须是 @ref{3fdc,,PyLongObject} 的实例。

如果 @emph{pylong} 的值超出了 @code{unsigned long long} 的取值范围则会引发 @ref{a4a,,OverflowError}。

出错时返回 @code{(unsigned long long)-1}，请利用 @ref{3d58,,PyErr_Occurred()} 获取详细信息。


在 3.1 版更改: 现在 @emph{pylong} 为负值会触发  @ref{a4a,,OverflowError}，而不是 @ref{1ff,,TypeError}。

@end deffn

@geindex PyLong_AsUnsignedLongMask (C 函数)
@anchor{c-api/long c PyLong_AsUnsignedLongMask}@anchor{3feb}
@deffn {C 函数} unsigned long PyLong_AsUnsignedLongMask (PyObject@w{ }*obj)

返回 @emph{obj} 的 C @code{unsigned long} 表示形式。 如果 @emph{obj} 不是 @ref{3fdc,,PyLongObject} 的实例，则会先调用其 @ref{2c9,,__index__()} 或 @ref{2ca,,__int__()} 方法（如果有的话）将其转为 @ref{3fdc,,PyLongObject}。

如果 @emph{obj} 的值超出了 @code{unsigned long} 的范围，则返回该值对 @code{ULONG_MAX + 1} 求模的差值。

出错时返回 @code{(unsigned long)-1}，请利用 @ref{3d58,,PyErr_Occurred()} 辨别具体问题。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsUnsignedLongLongMask (C 函数)
@anchor{c-api/long c PyLong_AsUnsignedLongLongMask}@anchor{113d}
@deffn {C 函数} unsigned long long PyLong_AsUnsignedLongLongMask (PyObject@w{ }*obj)

返回 @emph{obj} 的 C @code{unsigned long long} 表示形式。 如果 @emph{obj} 不是 @ref{3fdc,,PyLongObject} 的实例，则会先调用其 @ref{2c9,,__index__()} 或 @ref{2ca,,__int__()} 方法（如果有的话）将其转为 @ref{3fdc,,PyLongObject}。

如果 @emph{obj} 的值超出了 @code{unsigned long long} 的范围，则返回该值对 @code{ULLONG_MAX + 1} 求模的差值。

出错时返回 @code{(unsigned long long)-1}，请利用 @ref{3d58,,PyErr_Occurred()} 辨别具体问题。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。



3.8 版后已移除: @ref{2ca,,__int__()} 已被弃用。

@end deffn

@geindex PyLong_AsDouble (C 函数)
@anchor{c-api/long c PyLong_AsDouble}@anchor{3fec}
@deffn {C 函数} double PyLong_AsDouble (PyObject@w{ }*pylong)

返回 @emph{pylong} 的 C 语言 @code{double} 形式。@emph{pylong} 必须是 @ref{3fdc,,PyLongObject} 的实例。

如果 @emph{pylong} 的值超出了 @code{double} 的取值范围则会引发 @ref{a4a,,OverflowError}。

出错时返回  @code{-1.0} ，请利用 @ref{3d58,,PyErr_Occurred()} 辨别具体问题。
@end deffn

@geindex PyLong_AsVoidPtr (C 函数)
@anchor{c-api/long c PyLong_AsVoidPtr}@anchor{3fe6}
@deffn {C 函数} void* PyLong_AsVoidPtr (PyObject@w{ }*pylong)

将一个 Python 整数 @emph{pylong} 转换为 C 语言的 @code{void} 指针。 如果 @emph{pylong} 无法转换，则会触发 @ref{a4a,,OverflowError}。 这只是保证为 @ref{3fe5,,PyLong_FromVoidPtr()} 创建的值产生一个合法的  @code{void} 指针。

出错时返回  @code{NULL}，请利用 @ref{3d58,,PyErr_Occurred()} 辨别具体问题。
@end deffn

@node 布尔对象,浮点数对象,整数型对象,数值对象
@anchor{c-api/bool doc}@anchor{3fed}@anchor{c-api/bool boolean-objects}@anchor{3fee}@anchor{c-api/bool boolobjects}@anchor{3fef}
@subsubsection 布尔对象


Python 中的布尔值是作为整数的子类实现的。只有 @code{Py_False} 和 @code{Py_True} 两个布尔值。因此，正常的创建和删除功能不适用于布尔值。但是，下列宏可用。

@geindex PyBool_Check (C 函数)
@anchor{c-api/bool c PyBool_Check}@anchor{3ff0}
@deffn {C 函数} int PyBool_Check (PyObject@w{ }*o)

如果 @emph{o} 的类型为 @code{PyBool_Type} 则返回真值。 此函数总是会成功执行。
@end deffn

@geindex Py_False (C 变量)
@anchor{c-api/bool c Py_False}@anchor{3ff1}
@deffn {C 变量} PyObject* Py_False

Python 的  @code{False} 对象没有任何方法，它需要和其他对象一样遵循引用计数。
@end deffn

@geindex Py_True (C 变量)
@anchor{c-api/bool c Py_True}@anchor{3ff2}
@deffn {C 变量} PyObject* Py_True

Python 的 @code{True} 对象没有任何方法，它需要和其他对象一样遵循引用计数。
@end deffn

@geindex Py_RETURN_FALSE (C 宏)
@anchor{c-api/bool c Py_RETURN_FALSE}@anchor{ea5}
@deffn {C 宏} Py_RETURN_FALSE

从函数返回 @code{Py_False} 时，需要增加它的引用计数。
@end deffn

@geindex Py_RETURN_TRUE (C 宏)
@anchor{c-api/bool c Py_RETURN_TRUE}@anchor{ea4}
@deffn {C 宏} Py_RETURN_TRUE

从函数返回 @code{Py_True} 时，需要增加它的引用计数。
@end deffn

@geindex PyBool_FromLong (C 函数)
@anchor{c-api/bool c PyBool_FromLong}@anchor{3ff3}
@deffn {C 函数} PyObject* PyBool_FromLong (long@w{ }v)
@emph{Return value: New reference.}
根据 @emph{v} 的实际值，返回一个 @code{Py_True} 或者 @code{Py_False} 的新引用。
@end deffn

@node 浮点数对象,复数对象,布尔对象,数值对象
@anchor{c-api/float doc}@anchor{3ff4}@anchor{c-api/float floating-point-objects}@anchor{3ff5}@anchor{c-api/float floatobjects}@anchor{3ff6}
@subsubsection 浮点数对象


@geindex 对象; floating point

@geindex PyFloatObject (C 类型)
@anchor{c-api/float c PyFloatObject}@anchor{3ff7}
@deffn {C 类型} PyFloatObject

这个C类型 @ref{5bd,,PyObject} 的子类型代表一个Python浮点数对象。
@end deffn

@geindex PyFloat_Type (C 变量)
@anchor{c-api/float c PyFloat_Type}@anchor{3ff8}
@deffn {C 变量} PyTypeObject PyFloat_Type

这是个属于C类型 @ref{3fe,,PyTypeObject} 的代表Python浮点类型的实例。在Python层面的类型 @ref{1fe,,float} 是同一个对象。
@end deffn

@geindex PyFloat_Check (C 函数)
@anchor{c-api/float c PyFloat_Check}@anchor{3ff9}
@deffn {C 函数} int PyFloat_Check (PyObject@w{ }*p)

如果它的参数是一个 @ref{3ff7,,PyFloatObject} 或者 @ref{3ff7,,PyFloatObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyFloat_CheckExact (C 函数)
@anchor{c-api/float c PyFloat_CheckExact}@anchor{3ffa}
@deffn {C 函数} int PyFloat_CheckExact (PyObject@w{ }*p)

如果它的参数是一个 @ref{3ff7,,PyFloatObject} 但不是 @ref{3ff7,,PyFloatObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyFloat_FromString (C 函数)
@anchor{c-api/float c PyFloat_FromString}@anchor{3ffb}
@deffn {C 函数} PyObject* PyFloat_FromString (PyObject@w{ }*str)
@emph{Return value: New reference.}
根据字符串 @emph{str} 的值创建一个 @ref{3ff7,,PyFloatObject}，失败时返回 @code{NULL}。
@end deffn

@geindex PyFloat_FromDouble (C 函数)
@anchor{c-api/float c PyFloat_FromDouble}@anchor{3ffc}
@deffn {C 函数} PyObject* PyFloat_FromDouble (double@w{ }v)
@emph{Return value: New reference.}
根据 @emph{v} 创建一个 @ref{3ff7,,PyFloatObject} 对象，失败时返回 @code{NULL}。
@end deffn

@geindex PyFloat_AsDouble (C 函数)
@anchor{c-api/float c PyFloat_AsDouble}@anchor{39f}
@deffn {C 函数} double PyFloat_AsDouble (PyObject@w{ }*pyfloat)

返回一个 C @code{double} 代表 @emph{pyfloat} 的内容。 如果 @emph{pyfloat} 不是一个 Python 浮点数对象但是具有 @ref{2cb,,__float__()} 方法，此方法将首先被调用，将 @emph{pyfloat} 转换成一个数点数。 如果 @code{__float__()} 未定义则将回退至 @ref{2c9,,__index__()}。 如果失败，此方法将返回 @code{-1.0}，因此开发者应当调用 @ref{3d58,,PyErr_Occurred()} 来检查错误。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。

@end deffn

@geindex PyFloat_AS_DOUBLE (C 函数)
@anchor{c-api/float c PyFloat_AS_DOUBLE}@anchor{3ffd}
@deffn {C 函数} double PyFloat_AS_DOUBLE (PyObject@w{ }*pyfloat)

返回一个 @emph{pyfloat} 内容的 C @code{double} 表示，但没有错误检查。
@end deffn

@geindex PyFloat_GetInfo (C 函数)
@anchor{c-api/float c PyFloat_GetInfo}@anchor{e24}
@deffn {C 函数} PyObject* PyFloat_GetInfo (void)
@emph{Return value: New reference.}
返回一个 structseq 实例，其中包含有关 float 的精度、最小值和最大值的信息。 它是头文件 @code{float.h} 的一个简单包装。
@end deffn

@geindex PyFloat_GetMax (C 函数)
@anchor{c-api/float c PyFloat_GetMax}@anchor{e22}
@deffn {C 函数} double PyFloat_GetMax ()

返回最大可表示的有限浮点数 @emph{DBL_MAX} 为 C @code{double} 。
@end deffn

@geindex PyFloat_GetMin (C 函数)
@anchor{c-api/float c PyFloat_GetMin}@anchor{e23}
@deffn {C 函数} double PyFloat_GetMin ()

返回最小可表示归一化正浮点数 @emph{DBL_MIN} 为 C @code{double} 。
@end deffn

@node 复数对象,,浮点数对象,数值对象
@anchor{c-api/complex doc}@anchor{3ffe}@anchor{c-api/complex complex-number-objects}@anchor{3fff}@anchor{c-api/complex complexobjects}@anchor{4000}
@subsubsection 复数对象


@geindex 对象; complex number

从C API看，Python的复数对象由两个不同的部分实现：一个是在Python程序使用的Python对象，另外的是一个代表真正复数值的C结构体。API提供了函数共同操作两者。

@menu
* 表示复数的C结构体:: 
* 表示复数的Python对象:: 

@end menu

@node 表示复数的C结构体,表示复数的Python对象,,复数对象
@anchor{c-api/complex complex-numbers-as-c-structures}@anchor{4001}
@subsubsection 表示复数的C结构体


需要注意的是接受这些结构体的作为参数并当做结果返回的函数，都是传递“值”而不是引用指针。此规则适用于整个API。

@geindex Py_complex (C 类型)
@anchor{c-api/complex c Py_complex}@anchor{3ec9}
@deffn {C 类型} Py_complex

这是一个对应Python复数对象的值部分的C结构体。绝大部分处理复数对象的函数都用这类型的结构体作为输入或者输出值，它可近似地定义为：

@example
typedef struct @{
   double real;
   double imag;
@} Py_complex;
@end example
@end deffn

@geindex _Py_c_sum (C 函数)
@anchor{c-api/complex c _Py_c_sum}@anchor{4002}
@deffn {C 函数} Py_complex _Py_c_sum (Py_complex@w{ }left, Py_complex@w{ }right)

返回两个复数的和，用 C 类型 @ref{3ec9,,Py_complex} 表示。
@end deffn

@geindex _Py_c_diff (C 函数)
@anchor{c-api/complex c _Py_c_diff}@anchor{4003}
@deffn {C 函数} Py_complex _Py_c_diff (Py_complex@w{ }left, Py_complex@w{ }right)

返回两个复数的差，用 C 类型 @ref{3ec9,,Py_complex} 表示。
@end deffn

@geindex _Py_c_neg (C 函数)
@anchor{c-api/complex c _Py_c_neg}@anchor{4004}
@deffn {C 函数} Py_complex _Py_c_neg (Py_complex@w{ }num)

返回复数 @emph{num} 的负值，用 C @ref{3ec9,,Py_complex} 表示。
@end deffn

@geindex _Py_c_prod (C 函数)
@anchor{c-api/complex c _Py_c_prod}@anchor{4005}
@deffn {C 函数} Py_complex _Py_c_prod (Py_complex@w{ }left, Py_complex@w{ }right)

返回两个复数的乘积，用 C 类型 @ref{3ec9,,Py_complex} 表示。
@end deffn

@geindex _Py_c_quot (C 函数)
@anchor{c-api/complex c _Py_c_quot}@anchor{4006}
@deffn {C 函数} Py_complex _Py_c_quot (Py_complex@w{ }dividend, Py_complex@w{ }divisor)

返回两个复数的商，用 C 类型 @ref{3ec9,,Py_complex} 表示。

如果 @emph{divisor} 为空，这个方法返回零并设置 @code{errno} 为 @code{EDOM}。
@end deffn

@geindex _Py_c_pow (C 函数)
@anchor{c-api/complex c _Py_c_pow}@anchor{4007}
@deffn {C 函数} Py_complex _Py_c_pow (Py_complex@w{ }num, Py_complex@w{ }exp)

返回 @emph{num} 的 @emph{exp} 次幂，用 C 类型 @ref{3ec9,,Py_complex} 表示。

如果 @emph{num} 为空且 @emph{exp} 不是正实数，这个方法返回零并设置 @code{errno} 为 @code{EDOM}。
@end deffn

@node 表示复数的Python对象,,表示复数的C结构体,复数对象
@anchor{c-api/complex complex-numbers-as-python-objects}@anchor{4008}
@subsubsection 表示复数的Python对象


@geindex PyComplexObject (C 类型)
@anchor{c-api/complex c PyComplexObject}@anchor{4009}
@deffn {C 类型} PyComplexObject

这个C类型 @ref{5bd,,PyObject} 的子类型代表一个 Python 复数对象。
@end deffn

@geindex PyComplex_Type (C 变量)
@anchor{c-api/complex c PyComplex_Type}@anchor{400a}
@deffn {C 变量} PyTypeObject PyComplex_Type

这是个属于C类型 @ref{3fe,,PyTypeObject} 的代表 Python 复数类型的实例。 和 Python 层面的类 @ref{2c8,,complex} 是同一个对象。
@end deffn

@geindex PyComplex_Check (C 函数)
@anchor{c-api/complex c PyComplex_Check}@anchor{400b}
@deffn {C 函数} int PyComplex_Check (PyObject@w{ }*p)

如果它的参数是一个 @ref{4009,,PyComplexObject} 或者 @ref{4009,,PyComplexObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyComplex_CheckExact (C 函数)
@anchor{c-api/complex c PyComplex_CheckExact}@anchor{400c}
@deffn {C 函数} int PyComplex_CheckExact (PyObject@w{ }*p)

如果它的参数是一个 @ref{4009,,PyComplexObject} 但不是 @ref{4009,,PyComplexObject} 的子类型则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyComplex_FromCComplex (C 函数)
@anchor{c-api/complex c PyComplex_FromCComplex}@anchor{400d}
@deffn {C 函数} PyObject* PyComplex_FromCComplex (Py_complex@w{ }v)
@emph{Return value: New reference.}
根据C类型 @ref{3ec9,,Py_complex} 的值生成一个新的Python复数对象。
@end deffn

@geindex PyComplex_FromDoubles (C 函数)
@anchor{c-api/complex c PyComplex_FromDoubles}@anchor{400e}
@deffn {C 函数} PyObject* PyComplex_FromDoubles (double@w{ }real, double@w{ }imag)
@emph{Return value: New reference.}
根据 @emph{real} 和 @emph{imag} 返回一个新的C类型 @ref{4009,,PyComplexObject} 对象。
@end deffn

@geindex PyComplex_RealAsDouble (C 函数)
@anchor{c-api/complex c PyComplex_RealAsDouble}@anchor{400f}
@deffn {C 函数} double PyComplex_RealAsDouble (PyObject@w{ }*op)

以C类型 @code{double} 返回 @emph{op} 的实部。
@end deffn

@geindex PyComplex_ImagAsDouble (C 函数)
@anchor{c-api/complex c PyComplex_ImagAsDouble}@anchor{4010}
@deffn {C 函数} double PyComplex_ImagAsDouble (PyObject@w{ }*op)

以C类型 @code{double} 返回 @emph{op} 的虚部。
@end deffn

@geindex PyComplex_AsCComplex (C 函数)
@anchor{c-api/complex c PyComplex_AsCComplex}@anchor{e25}
@deffn {C 函数} Py_complex PyComplex_AsCComplex (PyObject@w{ }*op)

返回复数 @emph{op} 的C类型 @ref{3ec9,,Py_complex} 值。

如果 @emph{op} 不是一个 Python 复数对象，但是具有 @ref{2cc,,__complex__()} 方法，此方法将首先被调用，将 @emph{op} 转换为一个 Python 复数对象。 如果 @code{__complex__()} 未定义则将回退至 @ref{2cb,,__float__()}，如果 @code{__float__()} 未定义则将回退至 @ref{2c9,,__index__()}。 如果失败，此方法将返回 @code{-1.0} 作为实数值。


在 3.8 版更改: 如果可用将使用 @ref{2c9,,__index__()}。

@end deffn

@node 序列对象,容器对象,数值对象,具体的对象层
@anchor{c-api/concrete sequence-objects}@anchor{4011}@anchor{c-api/concrete sequenceobjects}@anchor{4012}
@subsection 序列对象


@geindex 对象; sequence

序列对象的一般操作在前一章中讨论过;本节介绍Python语言固有的特定类型的序列对象。

@c XXX sort out unicode, str, bytes and bytearray

@menu
* 字节对象:: 
* 字节数组对象:: 
* Unicode对象和编码解码器:: 
* 元组对象:: 
* 结构序列对象:: 
* 列表对象:: 

@end menu

@node 字节对象,字节数组对象,,序列对象
@anchor{c-api/bytes doc}@anchor{4013}@anchor{c-api/bytes bytes-objects}@anchor{4014}@anchor{c-api/bytes bytesobjects}@anchor{4015}
@subsubsection 字节对象


这些函数在期望附带一个字节串形参但却附带了一个非字节串形参被调用时会引发 @ref{1ff,,TypeError}。

@geindex 对象; bytes

@geindex PyBytesObject (C 类型)
@anchor{c-api/bytes c PyBytesObject}@anchor{dec}
@deffn {C 类型} PyBytesObject

这种 @ref{5bd,,PyObject} 的子类型表示一个 Python 字节对象。
@end deffn

@geindex PyBytes_Type (C 变量)
@anchor{c-api/bytes c PyBytes_Type}@anchor{4016}
@deffn {C 变量} PyTypeObject PyBytes_Type

@ref{3fe,,PyTypeObject} 的实例代表一个 Python 字节类型，在 Python 层面它与 @ref{172,,bytes} 是相同的对象。
@end deffn

@geindex PyBytes_Check (C 函数)
@anchor{c-api/bytes c PyBytes_Check}@anchor{ded}
@deffn {C 函数} int PyBytes_Check (PyObject@w{ }*o)

如果对象 @emph{o} 是一个 bytes 对象或者 bytes 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyBytes_CheckExact (C 函数)
@anchor{c-api/bytes c PyBytes_CheckExact}@anchor{4017}
@deffn {C 函数} int PyBytes_CheckExact (PyObject@w{ }*o)

如果对象 @emph{o} 是一个 bytes 对象但不是 bytes 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyBytes_FromString (C 函数)
@anchor{c-api/bytes c PyBytes_FromString}@anchor{4018}
@deffn {C 函数} PyObject* PyBytes_FromString (const char@w{ }*v)
@emph{Return value: New reference.}
成功时返回一个以字符串 @emph{v} 的副本为值的新字节串对象，失败时返回 @code{NULL}。 形参 @emph{v} 不可为 @code{NULL}；它不会被检查。
@end deffn

@geindex PyBytes_FromStringAndSize (C 函数)
@anchor{c-api/bytes c PyBytes_FromStringAndSize}@anchor{dee}
@deffn {C 函数} PyObject* PyBytes_FromStringAndSize (const char@w{ }*v, Py_ssize_t@w{ }len)
@emph{Return value: New reference.}
成功时返回一个以字符串 @emph{v} 的副本为值且长度为 @emph{len} 的新字节串对象，失败时返回 @code{NULL}。 如果 @emph{v} 为 @code{NULL}，则不初始化字节串对象的内容。
@end deffn

@geindex PyBytes_FromFormat (C 函数)
@anchor{c-api/bytes c PyBytes_FromFormat}@anchor{118d}
@deffn {C 函数} PyObject* PyBytes_FromFormat (const char@w{ }*format, ...)
@emph{Return value: New reference.}
接受一个 C @code{printf()} 风格的 @emph{format} 字符串和可变数量的参数，计算结果 Python 字节串对象的大小并返回参数值经格式化后的字节串对象。 可变数量的参数必须均为 C 类型并且必须恰好与 @emph{format} 字符串中的格式字符相对应。 允许使用下列格式字符串:

@c % XXX: This should be exactly the same as the table in PyErr_Format.

@c % One should just refer to the other.

@c % XXX: The descriptions for %zd and %zu are wrong, but the truth is complicated

@c % because not all compilers support the %z width modifier -- we fake it

@c % when necessary via interpolating PY_FORMAT_SIZE_T.


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

格式字符

@tab

类型

@tab

注释

@item

@code{%%}

@tab

@emph{不适用}

@tab

文字%字符。

@item

@code{%c}

@tab

int

@tab

一个字节，被表示为一个 C 语言的整型

@item

@code{%d}

@tab

int

@tab

相当于 @code{printf("%d")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%u}

@tab

无符号整型

@tab

相当于 @code{printf("%u")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%ld}

@tab

长整型

@tab

相当于 @code{printf("%ld")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%lu}

@tab

无符号长整型

@tab

相当于 @code{printf("%lu")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%zd}

@tab

@ref{391,,Py_ssize_t}

@tab

相当于 @code{printf("%zd")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%zu}

@tab

size_t

@tab

相当于 @code{printf("%zu")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%i}

@tab

int

@tab

相当于 @code{printf("%i")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%x}

@tab

int

@tab

相当于 @code{printf("%x")}. @footnote{@w{(1)} 
对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0 转换标志是有效的。
}

@item

@code{%s}

@tab

const char*

@tab

以 null 为终止符的 C 字符数组。

@item

@code{%p}

@tab

const void*

@tab

一个 C 指针的十六进制表示形式。 基本等价于 @code{printf("%p")} 但它会确保以字面值 @code{0x} 开头，不论系统平台上 @code{printf} 的输出是什么。

@end multitable


无法识别的格式字符会导致将格式字符串的其余所有内容原样复制到结果对象，并丢弃所有多余的参数。
@end deffn

@geindex PyBytes_FromFormatV (C 函数)
@anchor{c-api/bytes c PyBytes_FromFormatV}@anchor{4019}
@deffn {C 函数} PyObject* PyBytes_FromFormatV (const char@w{ }*format, va_list@w{ }vargs)
@emph{Return value: New reference.}
与 @ref{118d,,PyBytes_FromFormat()} 完全相同，除了它需要两个参数。
@end deffn

@geindex PyBytes_FromObject (C 函数)
@anchor{c-api/bytes c PyBytes_FromObject}@anchor{401a}
@deffn {C 函数} PyObject* PyBytes_FromObject (PyObject@w{ }*o)
@emph{Return value: New reference.}
返回字节表示实现缓冲区协议的对象*o*。
@end deffn

@geindex PyBytes_Size (C 函数)
@anchor{c-api/bytes c PyBytes_Size}@anchor{401b}
@deffn {C 函数} Py_ssize_t PyBytes_Size (PyObject@w{ }*o)

返回字节对象*o*中字节的长度。
@end deffn

@geindex PyBytes_GET_SIZE (C 函数)
@anchor{c-api/bytes c PyBytes_GET_SIZE}@anchor{401c}
@deffn {C 函数} Py_ssize_t PyBytes_GET_SIZE (PyObject@w{ }*o)

宏版本的 @ref{401b,,PyBytes_Size()} 但是不带错误检测。
@end deffn

@geindex PyBytes_AsString (C 函数)
@anchor{c-api/bytes c PyBytes_AsString}@anchor{401d}
@deffn {C 函数} char* PyBytes_AsString (PyObject@w{ }*o)

返回对应 @emph{o} 的内容的指针。 该指针指向 @emph{o} 的内部缓冲区，其中包含 @code{len(o) + 1} 个字节。 缓冲区的最后一个字节总是为空，不论是否存在其他空字节。 该数据不可通过任何形式来修改，除非是刚使用 @code{PyBytes_FromStringAndSize(NULL, size)} 创建该对象。 它不可被撤销分配。 如果 @emph{o} 根本不是一个字节串对象，则 @ref{401d,,PyBytes_AsString()} 将返回 @code{NULL} 并引发 @ref{1ff,,TypeError}。
@end deffn

@geindex PyBytes_AS_STRING (C 函数)
@anchor{c-api/bytes c PyBytes_AS_STRING}@anchor{401e}
@deffn {C 函数} char* PyBytes_AS_STRING (PyObject@w{ }*string)

宏版本的 @ref{401d,,PyBytes_AsString()} 但是不带错误检测。
@end deffn

@geindex PyBytes_AsStringAndSize (C 函数)
@anchor{c-api/bytes c PyBytes_AsStringAndSize}@anchor{401f}
@deffn {C 函数} int PyBytes_AsStringAndSize (PyObject@w{ }*obj, char@w{ }**buffer, Py_ssize_t@w{ }*length)

通过输出变量 @emph{buffer} 和 @emph{length} 返回以 null 为终止符的对象 @emph{obj} 的内容。

如果 @emph{length} 为 @code{NULL}，字节串对象就不包含嵌入的空字节；如果包含，则该函数将返回 @code{-1} 并引发 @ref{16d,,ValueError}。

该缓冲区指向 @emph{obj} 的内部缓冲，它的末尾包含一个额外的空字节（不算在 @emph{length} 当中）。 该数据不可通过任何方式来修改，除非是刚使用 @code{PyBytes_FromStringAndSize(NULL, size)} 创建该对象。 它不可被撤销分配。 如果 @emph{obj} 根本不是一个字节串对象，则 @ref{401f,,PyBytes_AsStringAndSize()} 将返回 @code{-1} 并引发 @ref{1ff,,TypeError}。


在 3.5 版更改: 以前，当字节串对象中出现嵌入的空字节时将引发 @ref{1ff,,TypeError}。

@end deffn

@geindex PyBytes_Concat (C 函数)
@anchor{c-api/bytes c PyBytes_Concat}@anchor{4020}
@deffn {C 函数} void PyBytes_Concat (PyObject@w{ }**bytes, PyObject@w{ }*newpart)

在 @emph{*bytes} 中创建新的字节串对象，其中包含添加到 @emph{bytes} 的 @emph{newpart} 的内容；调用者将获得新的引用。 对 @emph{bytes} 原值的引用将被收回。 如果无法创建新对象，对 @emph{bytes} 的旧引用仍将被丢弃且 @emph{*bytes} 的值将被设为 @code{NULL}；并将设置适当的异常。
@end deffn

@geindex PyBytes_ConcatAndDel (C 函数)
@anchor{c-api/bytes c PyBytes_ConcatAndDel}@anchor{4021}
@deffn {C 函数} void PyBytes_ConcatAndDel (PyObject@w{ }**bytes, PyObject@w{ }*newpart)

在 @emph{*bytes} 中创建新的字节串对象，其中包含添加到 @emph{bytes} 的 @emph{newpart} 的内容。 此版本会减少 @emph{newpart} 的引用计数。
@end deffn

@geindex _PyBytes_Resize (C 函数)
@anchor{c-api/bytes c _PyBytes_Resize}@anchor{11c8}
@deffn {C 函数} int _PyBytes_Resize (PyObject@w{ }**bytes, Py_ssize_t@w{ }newsize)

改变字节串大小的一种方式，即使其为“不可变对象”。 此方式仅用于创建全新的字节串对象；如果字节串在代码的其他部分已知则不可使用此方式。 如果输入字节串对象的引用计数不为一则调用此函数将报错。 传入一个现有字节串对象的地址作为 lvalue（它可能会被写入），并传入希望的新大小。 当成功时，@emph{*bytes} 将存放改变大小后的字节串对象并返回 @code{0}；@emph{*bytes} 中的地址可能与其输入值不同。 如果重新分配失败，则 @emph{*bytes} 上的原字节串对象将被撤销分配，@emph{*bytes} 会被设为 @code{NULL}，同时设置 @ref{fb5,,MemoryError} 并返回 @code{-1}。
@end deffn

@node 字节数组对象,Unicode对象和编码解码器,字节对象,序列对象
@anchor{c-api/bytearray doc}@anchor{4022}@anchor{c-api/bytearray byte-array-objects}@anchor{4023}@anchor{c-api/bytearray bytearrayobjects}@anchor{4024}
@subsubsection 字节数组对象


@geindex 对象; bytearray

@geindex PyByteArrayObject (C 类型)
@anchor{c-api/bytearray c PyByteArrayObject}@anchor{4025}
@deffn {C 类型} PyByteArrayObject

这个 @ref{5bd,,PyObject} 的子类型表示一个 Python 字节数组对象。
@end deffn

@geindex PyByteArray_Type (C 变量)
@anchor{c-api/bytearray c PyByteArray_Type}@anchor{4026}
@deffn {C 变量} PyTypeObject PyByteArray_Type

Python bytearray 类型表示为 @ref{3fe,,PyTypeObject} 的实例；这与Python层面的 @ref{173,,bytearray} 是相同的对象。
@end deffn

@menu
* 类型检查宏:: 
* 直接 API 函数:: 
* 宏:: 

@end menu

@node 类型检查宏,直接 API 函数,,字节数组对象
@anchor{c-api/bytearray type-check-macros}@anchor{4027}
@subsubsection 类型检查宏


@geindex PyByteArray_Check (C 函数)
@anchor{c-api/bytearray c PyByteArray_Check}@anchor{4028}
@deffn {C 函数} int PyByteArray_Check (PyObject@w{ }*o)

如果对象 @emph{o} 是一个 bytearray 对象或者 bytearray 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyByteArray_CheckExact (C 函数)
@anchor{c-api/bytearray c PyByteArray_CheckExact}@anchor{4029}
@deffn {C 函数} int PyByteArray_CheckExact (PyObject@w{ }*o)

如果对象 @emph{o} 是一个 bytearray 对象但不是 bytearray 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@node 直接 API 函数,宏,类型检查宏,字节数组对象
@anchor{c-api/bytearray direct-api-functions}@anchor{402a}
@subsubsection 直接 API 函数


@geindex PyByteArray_FromObject (C 函数)
@anchor{c-api/bytearray c PyByteArray_FromObject}@anchor{def}
@deffn {C 函数} PyObject* PyByteArray_FromObject (PyObject@w{ }*o)
@emph{Return value: New reference.}
根据任何实现了 @ref{174c,,缓冲区协议} 的对象 @emph{o}，返回一个新的字节数组对象。
@end deffn

@geindex PyByteArray_FromStringAndSize (C 函数)
@anchor{c-api/bytearray c PyByteArray_FromStringAndSize}@anchor{df0}
@deffn {C 函数} PyObject* PyByteArray_FromStringAndSize (const char@w{ }*string, Py_ssize_t@w{ }len)
@emph{Return value: New reference.}
根据 @emph{string} 及其长度 @emph{len} 创建一个新的 bytearray 对象。 当失败时返回 @code{NULL}。
@end deffn

@geindex PyByteArray_Concat (C 函数)
@anchor{c-api/bytearray c PyByteArray_Concat}@anchor{402b}
@deffn {C 函数} PyObject* PyByteArray_Concat (PyObject@w{ }*a, PyObject@w{ }*b)
@emph{Return value: New reference.}
连接字节数组 @emph{a} 和 @emph{b} 并返回一个带有结果的新的字节数组。
@end deffn

@geindex PyByteArray_Size (C 函数)
@anchor{c-api/bytearray c PyByteArray_Size}@anchor{402c}
@deffn {C 函数} Py_ssize_t PyByteArray_Size (PyObject@w{ }*bytearray)

在检查 @code{NULL} 指针后返回 @emph{bytearray} 的大小。
@end deffn

@geindex PyByteArray_AsString (C 函数)
@anchor{c-api/bytearray c PyByteArray_AsString}@anchor{402d}
@deffn {C 函数} char* PyByteArray_AsString (PyObject@w{ }*bytearray)

在检查 @code{NULL} 指针后返回将 @emph{bytearray} 返回为一个字符数组。 返回的数组总是会附加一个额外的空字节。
@end deffn

@geindex PyByteArray_Resize (C 函数)
@anchor{c-api/bytearray c PyByteArray_Resize}@anchor{402e}
@deffn {C 函数} int PyByteArray_Resize (PyObject@w{ }*bytearray, Py_ssize_t@w{ }len)

将 @emph{bytearray} 的内部缓冲区的大小调整为 @emph{len}。
@end deffn

@node 宏,,直接 API 函数,字节数组对象
@anchor{c-api/bytearray macros}@anchor{402f}
@subsubsection 宏


这些宏减低安全性以换取性能，它们不检查指针。

@geindex PyByteArray_AS_STRING (C 函数)
@anchor{c-api/bytearray c PyByteArray_AS_STRING}@anchor{4030}
@deffn {C 函数} char* PyByteArray_AS_STRING (PyObject@w{ }*bytearray)

C函数 @ref{402d,,PyByteArray_AsString()} 的宏版本。
@end deffn

@geindex PyByteArray_GET_SIZE (C 函数)
@anchor{c-api/bytearray c PyByteArray_GET_SIZE}@anchor{4031}
@deffn {C 函数} Py_ssize_t PyByteArray_GET_SIZE (PyObject@w{ }*bytearray)

C函数 @ref{402c,,PyByteArray_Size()} 的宏版本。
@end deffn

@node Unicode对象和编码解码器,元组对象,字节数组对象,序列对象
@anchor{c-api/unicode doc}@anchor{bf8}@anchor{c-api/unicode unicode-objects-and-codecs}@anchor{4032}@anchor{c-api/unicode unicodeobjects}@anchor{4033}
@subsubsection Unicode对象和编码解码器


@menu
* Unicode对象:: 
* Built-in Codecs:: 
* 方法与槽位函数:: 

@end menu

@node Unicode对象,Built-in Codecs,,Unicode对象和编码解码器
@anchor{c-api/unicode unicode-objects}@anchor{4034}
@subsubsection Unicode对象


自从python3.3中实现了 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393} 以来，Unicode对象在内部使用各种表示形式，以便在保持内存效率的同时处理完整范围的Unicode字符。对于所有代码点都低于128、256或65536的字符串，有一些特殊情况；否则，代码点必须低于1114112（这是完整的Unicode范围）。

@ref{bce,,Py_UNICODE*} and UTF-8 representations are created on demand and cached
in the Unicode object.  The @ref{bce,,Py_UNICODE*} representation is deprecated
and inefficient.

Due to the transition between the old APIs and the new APIs, Unicode objects
can internally be in two states depending on how they were created:


@itemize *

@item 
"canonical" Unicode objects are all objects created by a non-deprecated
Unicode API.  They use the most efficient representation allowed by the
implementation.

@item 
"legacy" Unicode objects have been created through one of the deprecated
APIs (typically @ref{264,,PyUnicode_FromUnicode()}) and only bear the
@ref{bce,,Py_UNICODE*} representation; you will have to call
@ref{bb6,,PyUnicode_READY()} on them before calling any other API.
@end itemize

@cartouche
@quotation 注解 
The "legacy" Unicode object will be removed in Python 3.12 with deprecated
APIs. All Unicode objects will be "canonical" since then. See 
@geindex Python 提高建议; PEP 623
PEP 623@footnote{https://www.python.org/dev/peps/pep-0623}
for more information.
@end quotation
@end cartouche

@menu
* Unicode类型:: 
* Unicode字符属性:: 
* Creating and accessing Unicode strings:: 
* Deprecated Py_UNICODE APIs:: 
* Locale Encoding:: 
* 文件系统编码格式:: 
* wchar_t Support:: 

@end menu

@node Unicode类型,Unicode字符属性,,Unicode对象
@anchor{c-api/unicode unicode-type}@anchor{4035}
@subsubsection Unicode类型


These are the basic Unicode object types used for the Unicode implementation in
Python:

@geindex Py_UCS4 (C 类型)
@geindex Py_UCS2 (C 类型)
@geindex Py_UCS1 (C 类型)
@anchor{c-api/unicode c Py_UCS4}@anchor{bb3}
@deffn {C 类型} Py_UCS4
@anchor{c-api/unicode c Py_UCS2}@anchor{bb2}
@deffnx {C 类型} Py_UCS2
@anchor{c-api/unicode c Py_UCS1}@anchor{bb1}
@deffnx {C 类型} Py_UCS1

These types are typedefs for unsigned integer types wide enough to contain
characters of 32 bits, 16 bits and 8 bits, respectively.  When dealing with
single Unicode characters, use @ref{bb3,,Py_UCS4}.


3.3 新版功能.

@end deffn

@geindex Py_UNICODE (C 类型)
@anchor{c-api/unicode c Py_UNICODE}@anchor{bce}
@deffn {C 类型} Py_UNICODE

This is a typedef of @code{wchar_t}, which is a 16-bit type or 32-bit type
depending on the platform.


在 3.3 版更改: In previous versions, this was a 16-bit type or a 32-bit type depending on
whether you selected a "narrow" or "wide" Unicode version of Python at
build time.

@end deffn

@geindex PyASCIIObject (C 类型)
@geindex PyCompactUnicodeObject (C 类型)
@geindex PyUnicodeObject (C 类型)
@anchor{c-api/unicode c PyASCIIObject}@anchor{bb4}
@deffn {C 类型} PyASCIIObject
@anchor{c-api/unicode c PyCompactUnicodeObject}@anchor{bb5}
@deffnx {C 类型} PyCompactUnicodeObject
@anchor{c-api/unicode c PyUnicodeObject}@anchor{4036}
@deffnx {C 类型} PyUnicodeObject

These subtypes of @ref{5bd,,PyObject} represent a Python Unicode object.  In
almost all cases, they shouldn't be used directly, since all API functions
that deal with Unicode objects take and return @ref{5bd,,PyObject} pointers.


3.3 新版功能.

@end deffn

@geindex PyUnicode_Type (C 变量)
@anchor{c-api/unicode c PyUnicode_Type}@anchor{4037}
@deffn {C 变量} PyTypeObject PyUnicode_Type

This instance of @ref{3fe,,PyTypeObject} represents the Python Unicode type.  It
is exposed to Python code as @code{str}.
@end deffn

The following APIs are really C macros and can be used to do fast checks and to
access internal read-only data of Unicode objects:

@geindex PyUnicode_Check (C 函数)
@anchor{c-api/unicode c PyUnicode_Check}@anchor{4038}
@deffn {C 函数} int PyUnicode_Check (PyObject@w{ }*o)

Return true if the object @emph{o} is a Unicode object or an instance of a Unicode
subtype.  This function always succeeds.
@end deffn

@geindex PyUnicode_CheckExact (C 函数)
@anchor{c-api/unicode c PyUnicode_CheckExact}@anchor{4039}
@deffn {C 函数} int PyUnicode_CheckExact (PyObject@w{ }*o)

Return true if the object @emph{o} is a Unicode object, but not an instance of a
subtype.  This function always succeeds.
@end deffn

@geindex PyUnicode_READY (C 函数)
@anchor{c-api/unicode c PyUnicode_READY}@anchor{bb6}
@deffn {C 函数} int PyUnicode_READY (PyObject@w{ }*o)

Ensure the string object @emph{o} is in the "canonical" representation.  This is
required before using any of the access macros described below.

@c XXX expand on when it is not required

Returns @code{0} on success and @code{-1} with an exception set on failure, which in
particular happens if memory allocation fails.


3.3 新版功能.



Deprecated since version 3.10, will be removed in version 3.12: This API will be removed with @ref{264,,PyUnicode_FromUnicode()}.

@end deffn

@geindex PyUnicode_GET_LENGTH (C 函数)
@anchor{c-api/unicode c PyUnicode_GET_LENGTH}@anchor{bac}
@deffn {C 函数} Py_ssize_t PyUnicode_GET_LENGTH (PyObject@w{ }*o)

Return the length of the Unicode string, in code points.  @emph{o} has to be a
Unicode object in the "canonical" representation (not checked).


3.3 新版功能.

@end deffn

@geindex PyUnicode_1BYTE_DATA (C 函数)
@geindex PyUnicode_2BYTE_DATA (C 函数)
@geindex PyUnicode_4BYTE_DATA (C 函数)
@anchor{c-api/unicode c PyUnicode_1BYTE_DATA}@anchor{bbb}
@deffn {C 函数} Py_UCS1* PyUnicode_1BYTE_DATA (PyObject@w{ }*o)
@anchor{c-api/unicode c PyUnicode_2BYTE_DATA}@anchor{bbc}
@deffnx {C 函数} Py_UCS2* PyUnicode_2BYTE_DATA (PyObject@w{ }*o)
@anchor{c-api/unicode c PyUnicode_4BYTE_DATA}@anchor{bbd}
@deffnx {C 函数} Py_UCS4* PyUnicode_4BYTE_DATA (PyObject@w{ }*o)

Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4
integer types for direct character access.  No checks are performed if the
canonical representation has the correct character size; use
@ref{bbe,,PyUnicode_KIND()} to select the right macro.  Make sure
@ref{bb6,,PyUnicode_READY()} has been called before accessing this.


3.3 新版功能.

@end deffn

@geindex PyUnicode_WCHAR_KIND (C 宏)
@geindex PyUnicode_1BYTE_KIND (C 宏)
@geindex PyUnicode_2BYTE_KIND (C 宏)
@geindex PyUnicode_4BYTE_KIND (C 宏)
@anchor{c-api/unicode c PyUnicode_WCHAR_KIND}@anchor{bbf}
@deffn {C 宏} PyUnicode_WCHAR_KIND
@anchor{c-api/unicode c PyUnicode_1BYTE_KIND}@anchor{bc0}
@deffnx {C 宏} PyUnicode_1BYTE_KIND
@anchor{c-api/unicode c PyUnicode_2BYTE_KIND}@anchor{bc1}
@deffnx {C 宏} PyUnicode_2BYTE_KIND
@anchor{c-api/unicode c PyUnicode_4BYTE_KIND}@anchor{bc2}
@deffnx {C 宏} PyUnicode_4BYTE_KIND

返回 @ref{bbe,,PyUnicode_KIND()} 宏的值。


3.3 新版功能.



Deprecated since version 3.10, will be removed in version 3.12: @code{PyUnicode_WCHAR_KIND} 已被弃用。

@end deffn

@geindex PyUnicode_KIND (C 函数)
@anchor{c-api/unicode c PyUnicode_KIND}@anchor{bbe}
@deffn {C 函数} unsigned int PyUnicode_KIND (PyObject@w{ }*o)

Return one of the PyUnicode kind constants (see above) that indicate how many
bytes per character this Unicode object uses to store its data.  @emph{o} has to
be a Unicode object in the "canonical" representation (not checked).

@c XXX document "0" return value?


3.3 新版功能.

@end deffn

@geindex PyUnicode_DATA (C 函数)
@anchor{c-api/unicode c PyUnicode_DATA}@anchor{bba}
@deffn {C 函数} void* PyUnicode_DATA (PyObject@w{ }*o)

Return a void pointer to the raw Unicode buffer.  @emph{o} has to be a Unicode
object in the "canonical" representation (not checked).


3.3 新版功能.

@end deffn

@geindex PyUnicode_WRITE (C 函数)
@anchor{c-api/unicode c PyUnicode_WRITE}@anchor{bc5}
@deffn {C 函数} void PyUnicode_WRITE (int@w{ }kind, void@w{ }*data, Py_ssize_t@w{ }index, Py_UCS4@w{ }value)

Write into a canonical representation @emph{data} (as obtained with
@ref{bba,,PyUnicode_DATA()}).  This macro does not do any sanity checks and is
intended for usage in loops.  The caller should cache the @emph{kind} value and
@emph{data} pointer as obtained from other macro calls.  @emph{index} is the index in
the string (starts at 0) and @emph{value} is the new code point value which should
be written to that location.


3.3 新版功能.

@end deffn

@geindex PyUnicode_READ (C 函数)
@anchor{c-api/unicode c PyUnicode_READ}@anchor{bc3}
@deffn {C 函数} Py_UCS4 PyUnicode_READ (int@w{ }kind, void@w{ }*data, Py_ssize_t@w{ }index)

Read a code point from a canonical representation @emph{data} (as obtained with
@ref{bba,,PyUnicode_DATA()}).  No checks or ready calls are performed.


3.3 新版功能.

@end deffn

@geindex PyUnicode_READ_CHAR (C 函数)
@anchor{c-api/unicode c PyUnicode_READ_CHAR}@anchor{bc4}
@deffn {C 函数} Py_UCS4 PyUnicode_READ_CHAR (PyObject@w{ }*o, Py_ssize_t@w{ }index)

Read a character from a Unicode object @emph{o}, which must be in the "canonical"
representation.  This is less efficient than @ref{bc3,,PyUnicode_READ()} if you
do multiple consecutive reads.


3.3 新版功能.

@end deffn

@geindex PyUnicode_MAX_CHAR_VALUE (C 宏)
@anchor{c-api/unicode c PyUnicode_MAX_CHAR_VALUE}@anchor{bc6}
@deffn {C 宏} PyUnicode_MAX_CHAR_VALUE (o)

Return the maximum code point that is suitable for creating another string
based on @emph{o}, which must be in the "canonical" representation.  This is
always an approximation but more efficient than iterating over the string.


3.3 新版功能.

@end deffn

@geindex PyUnicode_GET_SIZE (C 函数)
@anchor{c-api/unicode c PyUnicode_GET_SIZE}@anchor{bd2}
@deffn {C 函数} Py_ssize_t PyUnicode_GET_SIZE (PyObject@w{ }*o)

Return the size of the deprecated @ref{bce,,Py_UNICODE} representation, in
code units (this includes surrogate pairs as 2 units).  @emph{o} has to be a
Unicode object (not checked).


Deprecated since version 3.3, will be removed in version 3.12: 旧式 Unicode API 的一部分，请迁移到使用 @ref{bac,,PyUnicode_GET_LENGTH()}。

@end deffn

@geindex PyUnicode_GET_DATA_SIZE (C 函数)
@anchor{c-api/unicode c PyUnicode_GET_DATA_SIZE}@anchor{bd4}
@deffn {C 函数} Py_ssize_t PyUnicode_GET_DATA_SIZE (PyObject@w{ }*o)

Return the size of the deprecated @ref{bce,,Py_UNICODE} representation in
bytes.  @emph{o} has to be a Unicode object (not checked).


Deprecated since version 3.3, will be removed in version 3.12: 旧式 Unicode API 的一部分，请迁移到使用 @ref{bac,,PyUnicode_GET_LENGTH()}。

@end deffn

@geindex PyUnicode_AS_UNICODE (C 函数)
@geindex PyUnicode_AS_DATA (C 函数)
@anchor{c-api/unicode c PyUnicode_AS_UNICODE}@anchor{bd0}
@deffn {C 函数} Py_UNICODE* PyUnicode_AS_UNICODE (PyObject@w{ }*o)
@anchor{c-api/unicode c PyUnicode_AS_DATA}@anchor{bd1}
@deffnx {C 函数} const char* PyUnicode_AS_DATA (PyObject@w{ }*o)

Return a pointer to a @ref{bce,,Py_UNICODE} representation of the object.  The
returned buffer is always terminated with an extra null code point.  It
may also contain embedded null code points, which would cause the string
to be truncated when used in most C functions.  The @code{AS_DATA} form
casts the pointer to @code{const char *}.  The @emph{o} argument has to be
a Unicode object (not checked).


在 3.3 版更改: This macro is now inefficient -- because in many cases the
@ref{bce,,Py_UNICODE} representation does not exist and needs to be created
-- and can fail (return @code{NULL} with an exception set).  Try to port the
code to use the new @code{PyUnicode_nBYTE_DATA()} macros or use
@ref{bc5,,PyUnicode_WRITE()} or @ref{bc3,,PyUnicode_READ()}.



Deprecated since version 3.3, will be removed in version 3.12: 旧式 Unicode API 的一部分，请迁移到使用 @code{PyUnicode_nBYTE_DATA()} 宏族。

@end deffn

@geindex PyUnicode_IsIdentifier (C 函数)
@anchor{c-api/unicode c PyUnicode_IsIdentifier}@anchor{10da}
@deffn {C 函数} int PyUnicode_IsIdentifier (PyObject@w{ }*o)

Return @code{1} if the string is a valid identifier according to the language
definition, section @ref{1533,,标识符和关键字}. Return @code{0} otherwise.


在 3.9 版更改: The function does not call @ref{267,,Py_FatalError()} anymore if the string
is not ready.

@end deffn

@node Unicode字符属性,Creating and accessing Unicode strings,Unicode类型,Unicode对象
@anchor{c-api/unicode unicode-character-properties}@anchor{403a}
@subsubsection Unicode字符属性


Unicode provides many different character properties. The most often needed ones
are available through these macros which are mapped to C functions depending on
the Python configuration.

@geindex Py_UNICODE_ISSPACE (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISSPACE}@anchor{1021}
@deffn {C 函数} int Py_UNICODE_ISSPACE (Py_UCS4@w{ }ch)

根据 @emph{ch} 是否为空白字符返回 @code{1} 或 @code{0}。
@end deffn

@geindex Py_UNICODE_ISLOWER (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISLOWER}@anchor{403b}
@deffn {C 函数} int Py_UNICODE_ISLOWER (Py_UCS4@w{ }ch)

根据 @emph{ch} 是否为小写字符返回 @code{1} 或 @code{0}。
@end deffn

@geindex Py_UNICODE_ISUPPER (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISUPPER}@anchor{403c}
@deffn {C 函数} int Py_UNICODE_ISUPPER (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is an uppercase character.
@end deffn

@geindex Py_UNICODE_ISTITLE (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISTITLE}@anchor{403d}
@deffn {C 函数} int Py_UNICODE_ISTITLE (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a titlecase character.
@end deffn

@geindex Py_UNICODE_ISLINEBREAK (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISLINEBREAK}@anchor{403e}
@deffn {C 函数} int Py_UNICODE_ISLINEBREAK (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a linebreak character.
@end deffn

@geindex Py_UNICODE_ISDECIMAL (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISDECIMAL}@anchor{403f}
@deffn {C 函数} int Py_UNICODE_ISDECIMAL (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a decimal character.
@end deffn

@geindex Py_UNICODE_ISDIGIT (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISDIGIT}@anchor{4040}
@deffn {C 函数} int Py_UNICODE_ISDIGIT (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a digit character.
@end deffn

@geindex Py_UNICODE_ISNUMERIC (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISNUMERIC}@anchor{4041}
@deffn {C 函数} int Py_UNICODE_ISNUMERIC (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a numeric character.
@end deffn

@geindex Py_UNICODE_ISALPHA (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISALPHA}@anchor{4042}
@deffn {C 函数} int Py_UNICODE_ISALPHA (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is an alphabetic character.
@end deffn

@geindex Py_UNICODE_ISALNUM (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISALNUM}@anchor{4043}
@deffn {C 函数} int Py_UNICODE_ISALNUM (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is an alphanumeric character.
@end deffn

@geindex Py_UNICODE_ISPRINTABLE (C 函数)
@anchor{c-api/unicode c Py_UNICODE_ISPRINTABLE}@anchor{4044}
@deffn {C 函数} int Py_UNICODE_ISPRINTABLE (Py_UCS4@w{ }ch)

Return @code{1} or @code{0} depending on whether @emph{ch} is a printable character.
Nonprintable characters are those characters defined in the Unicode character
database as "Other" or "Separator", excepting the ASCII space (0x20) which is
considered printable.  (Note that printable characters in this context are
those which should not be escaped when @ref{8c3,,repr()} is invoked on a string.
It has no bearing on the handling of strings written to @ref{428,,sys.stdout} or
@ref{1eb,,sys.stderr}.)
@end deffn

These APIs can be used for fast direct character conversions:

@geindex Py_UNICODE_TOLOWER (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TOLOWER}@anchor{4045}
@deffn {C 函数} Py_UCS4 Py_UNICODE_TOLOWER (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to lower case.


3.3 版后已移除: This function uses simple case mappings.

@end deffn

@geindex Py_UNICODE_TOUPPER (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TOUPPER}@anchor{4046}
@deffn {C 函数} Py_UCS4 Py_UNICODE_TOUPPER (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to upper case.


3.3 版后已移除: This function uses simple case mappings.

@end deffn

@geindex Py_UNICODE_TOTITLE (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TOTITLE}@anchor{4047}
@deffn {C 函数} Py_UCS4 Py_UNICODE_TOTITLE (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to title case.


3.3 版后已移除: This function uses simple case mappings.

@end deffn

@geindex Py_UNICODE_TODECIMAL (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TODECIMAL}@anchor{4048}
@deffn {C 函数} int Py_UNICODE_TODECIMAL (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to a decimal positive integer.  Return
@code{-1} if this is not possible.  This macro does not raise exceptions.
@end deffn

@geindex Py_UNICODE_TODIGIT (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TODIGIT}@anchor{4049}
@deffn {C 函数} int Py_UNICODE_TODIGIT (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to a single digit integer. Return @code{-1} if
this is not possible.  This macro does not raise exceptions.
@end deffn

@geindex Py_UNICODE_TONUMERIC (C 函数)
@anchor{c-api/unicode c Py_UNICODE_TONUMERIC}@anchor{404a}
@deffn {C 函数} double Py_UNICODE_TONUMERIC (Py_UCS4@w{ }ch)

Return the character @emph{ch} converted to a double. Return @code{-1.0} if this is not
possible.  This macro does not raise exceptions.
@end deffn

These APIs can be used to work with surrogates:

@geindex Py_UNICODE_IS_SURROGATE (C 宏)
@anchor{c-api/unicode c Py_UNICODE_IS_SURROGATE}@anchor{404b}
@deffn {C 宏} Py_UNICODE_IS_SURROGATE (ch)

Check if @emph{ch} is a surrogate (@code{0xD800 <= ch <= 0xDFFF}).
@end deffn

@geindex Py_UNICODE_IS_HIGH_SURROGATE (C 宏)
@anchor{c-api/unicode c Py_UNICODE_IS_HIGH_SURROGATE}@anchor{404c}
@deffn {C 宏} Py_UNICODE_IS_HIGH_SURROGATE (ch)

Check if @emph{ch} is a high surrogate (@code{0xD800 <= ch <= 0xDBFF}).
@end deffn

@geindex Py_UNICODE_IS_LOW_SURROGATE (C 宏)
@anchor{c-api/unicode c Py_UNICODE_IS_LOW_SURROGATE}@anchor{404d}
@deffn {C 宏} Py_UNICODE_IS_LOW_SURROGATE (ch)

Check if @emph{ch} is a low surrogate (@code{0xDC00 <= ch <= 0xDFFF}).
@end deffn

@geindex Py_UNICODE_JOIN_SURROGATES (C 宏)
@anchor{c-api/unicode c Py_UNICODE_JOIN_SURROGATES}@anchor{404e}
@deffn {C 宏} Py_UNICODE_JOIN_SURROGATES (high, low)

Join two surrogate characters and return a single Py_UCS4 value.
@emph{high} and @emph{low} are respectively the leading and trailing surrogates in a
surrogate pair.
@end deffn

@node Creating and accessing Unicode strings,Deprecated Py_UNICODE APIs,Unicode字符属性,Unicode对象
@anchor{c-api/unicode creating-and-accessing-unicode-strings}@anchor{404f}
@subsubsection Creating and accessing Unicode strings


To create Unicode objects and access their basic sequence properties, use these
APIs:

@geindex PyUnicode_New (C 函数)
@anchor{c-api/unicode c PyUnicode_New}@anchor{bad}
@deffn {C 函数} PyObject* PyUnicode_New (Py_ssize_t@w{ }size, Py_UCS4@w{ }maxchar)
@emph{Return value: New reference.}
Create a new Unicode object.  @emph{maxchar} should be the true maximum code point
to be placed in the string.  As an approximation, it can be rounded up to the
nearest value in the sequence 127, 255, 65535, 1114111.

This is the recommended way to allocate a new Unicode object.  Objects
created using this function are not resizable.


3.3 新版功能.

@end deffn

@geindex PyUnicode_FromKindAndData (C 函数)
@anchor{c-api/unicode c PyUnicode_FromKindAndData}@anchor{bb7}
@deffn {C 函数} PyObject* PyUnicode_FromKindAndData (int@w{ }kind, const void@w{ }*buffer, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Create a new Unicode object with the given @emph{kind} (possible values are
@ref{bc0,,PyUnicode_1BYTE_KIND} etc., as returned by
@ref{bbe,,PyUnicode_KIND()}).  The @emph{buffer} must point to an array of @emph{size}
units of 1, 2 or 4 bytes per character, as given by the kind.


3.3 新版功能.

@end deffn

@geindex PyUnicode_FromStringAndSize (C 函数)
@anchor{c-api/unicode c PyUnicode_FromStringAndSize}@anchor{4050}
@deffn {C 函数} PyObject* PyUnicode_FromStringAndSize (const char@w{ }*u, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Create a Unicode object from the char buffer @emph{u}.  The bytes will be
interpreted as being UTF-8 encoded.  The buffer is copied into the new
object. If the buffer is not @code{NULL}, the return value might be a shared
object, i.e. modification of the data is not allowed.

If @emph{u} is @code{NULL}, this function behaves like @ref{264,,PyUnicode_FromUnicode()}
with the buffer set to @code{NULL}.  This usage is deprecated in favor of
@ref{bad,,PyUnicode_New()}, and will be removed in Python 3.12.
@end deffn

@geindex PyUnicode_FromString (C 函数)
@anchor{c-api/unicode c PyUnicode_FromString}@anchor{3de2}
@deffn {C 函数} PyObject *PyUnicode_FromString (const char@w{ }*u)
@emph{Return value: New reference.}
Create a Unicode object from a UTF-8 encoded null-terminated char buffer
@emph{u}.
@end deffn

@geindex PyUnicode_FromFormat (C 函数)
@anchor{c-api/unicode c PyUnicode_FromFormat}@anchor{8c2}
@deffn {C 函数} PyObject* PyUnicode_FromFormat (const char@w{ }*format, ...)
@emph{Return value: New reference.}
Take a C @code{printf()}-style @emph{format} string and a variable number of
arguments, calculate the size of the resulting Python Unicode string and return
a string with the values formatted into it.  The variable arguments must be C
types and must correspond exactly to the format characters in the @emph{format}
ASCII-encoded string. The following format characters are allowed:

@c % This should be exactly the same as the table in PyErr_Format.

@c % The descriptions for %zd and %zu are wrong, but the truth is complicated

@c % because not all compilers support the %z width modifier -- we fake it

@c % when necessary via interpolating PY_FORMAT_SIZE_T.

@c % Similar comments apply to the %ll width modifier and


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

格式字符

@tab

类型

@tab

注释

@item

@code{%%}

@tab

@emph{不适用}

@tab

文字%字符。

@item

@code{%c}

@tab

整型

@tab

单个字符，表示为C 语言的整型。

@item

@code{%d}

@tab

整型

@tab

相当于 @code{printf("%d")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%u}

@tab

无符号整型

@tab

相当于 @code{printf("%u")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%ld}

@tab

长整型

@tab

相当于 @code{printf("%ld")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%li}

@tab

长整型

@tab

相当于 @code{printf("%li")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%lu}

@tab

无符号长整型

@tab

相当于 @code{printf("%lu")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%lld}

@tab

long long

@tab

相当于 @code{printf("%lld")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%lli}

@tab

long long

@tab

相当于 @code{printf("%lli")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%llu}

@tab

无符号 long long

@tab

相当于 @code{printf("%llu")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%zd}

@tab

@ref{391,,Py_ssize_t}

@tab

相当于 @code{printf("%zd")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%zi}

@tab

@ref{391,,Py_ssize_t}

@tab

相当于 @code{printf("%zi")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%zu}

@tab

size_t

@tab

相当于 @code{printf("%zu")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%i}

@tab

整型

@tab

相当于 @code{printf("%i")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%x}

@tab

整型

@tab

相当于 @code{printf("%x")}. @footnote{@w{(1)} 
For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi,
zu, i, x): the 0-conversion flag has effect even when a precision is given.
}

@item

@code{%s}

@tab

const char*

@tab

以 null 为终止符的 C 字符数组。

@item

@code{%p}

@tab

const void*

@tab

一个 C 指针的十六进制表示形式。 基本等价于 @code{printf("%p")} 但它会确保以字面值 @code{0x} 开头，不论系统平台上 @code{printf} 的输出是什么。

@item

@code{%A}

@tab

PyObject*

@tab

@ref{e19,,ascii()} 调用的结果。

@item

@code{%U}

@tab

PyObject*

@tab

A Unicode object.

@item

@code{%V}

@tab

PyObject*,
const char*

@tab

A Unicode object (which may be
@code{NULL}) and a null-terminated
C character array as a second
parameter (which will be used,
if the first parameter is
@code{NULL}).

@item

@code{%S}

@tab

PyObject*

@tab

The result of calling
@ref{a53,,PyObject_Str()}.

@item

@code{%R}

@tab

PyObject*

@tab

The result of calling
@ref{a52,,PyObject_Repr()}.

@end multitable


An unrecognized format character causes all the rest of the format string to be
copied as-is to the result string, and any extra arguments discarded.

@cartouche
@quotation 注解 
The width formatter unit is number of characters rather than bytes.
The precision formatter unit is number of bytes for @code{"%s"} and
@code{"%V"} (if the @code{PyObject*} argument is @code{NULL}), and a number of
characters for @code{"%A"}, @code{"%U"}, @code{"%S"}, @code{"%R"} and @code{"%V"}
(if the @code{PyObject*} argument is not @code{NULL}).
@end quotation
@end cartouche


在 3.2 版更改: Support for @code{"%lld"} and @code{"%llu"} added.



在 3.3 版更改: Support for @code{"%li"}, @code{"%lli"} and @code{"%zi"} added.



在 3.4 版更改: Support width and precision formatter for @code{"%s"}, @code{"%A"}, @code{"%U"},
@code{"%V"}, @code{"%S"}, @code{"%R"} added.

@end deffn

@geindex PyUnicode_FromFormatV (C 函数)
@anchor{c-api/unicode c PyUnicode_FromFormatV}@anchor{3e9f}
@deffn {C 函数} PyObject* PyUnicode_FromFormatV (const char@w{ }*format, va_list@w{ }vargs)
@emph{Return value: New reference.}
Identical to @ref{8c2,,PyUnicode_FromFormat()} except that it takes exactly two
arguments.
@end deffn

@geindex PyUnicode_FromEncodedObject (C 函数)
@anchor{c-api/unicode c PyUnicode_FromEncodedObject}@anchor{4051}
@deffn {C 函数} PyObject* PyUnicode_FromEncodedObject (PyObject@w{ }*obj, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
Decode an encoded object @emph{obj} to a Unicode object.

@ref{172,,bytes}, @ref{173,,bytearray} and other
@ref{6e9,,bytes-like objects}
are decoded according to the given @emph{encoding} and using the error handling
defined by @emph{errors}. Both can be @code{NULL} to have the interface use the default
values (see @ref{4052,,Built-in Codecs} for details).

All other objects, including Unicode objects, cause a @ref{1ff,,TypeError} to be
set.

The API returns @code{NULL} if there was an error.  The caller is responsible for
decref'ing the returned objects.
@end deffn

@geindex PyUnicode_GetLength (C 函数)
@anchor{c-api/unicode c PyUnicode_GetLength}@anchor{bab}
@deffn {C 函数} Py_ssize_t PyUnicode_GetLength (PyObject@w{ }*unicode)

Return the length of the Unicode object, in code points.


3.3 新版功能.

@end deffn

@geindex PyUnicode_CopyCharacters (C 函数)
@anchor{c-api/unicode c PyUnicode_CopyCharacters}@anchor{baa}
@deffn {C 函数} Py_ssize_t PyUnicode_CopyCharacters (PyObject@w{ }*to, Py_ssize_t@w{ }to_start, PyObject@w{ }*from, Py_ssize_t@w{ }from_start, Py_ssize_t@w{ }how_many)

Copy characters from one Unicode object into another.  This function performs
character conversion when necessary and falls back to @code{memcpy()} if
possible.  Returns @code{-1} and sets an exception on error, otherwise returns
the number of copied characters.


3.3 新版功能.

@end deffn

@geindex PyUnicode_Fill (C 函数)
@anchor{c-api/unicode c PyUnicode_Fill}@anchor{bd7}
@deffn {C 函数} Py_ssize_t PyUnicode_Fill (PyObject@w{ }*unicode, Py_ssize_t@w{ }start, Py_ssize_t@w{ }length, Py_UCS4@w{ }fill_char)

Fill a string with a character: write @emph{fill_char} into
@code{unicode[start:start+length]}.

Fail if @emph{fill_char} is bigger than the string maximum character, or if the
string has more than 1 reference.

Return the number of written character, or return @code{-1} and raise an
exception on error.


3.3 新版功能.

@end deffn

@geindex PyUnicode_WriteChar (C 函数)
@anchor{c-api/unicode c PyUnicode_WriteChar}@anchor{bb0}
@deffn {C 函数} int PyUnicode_WriteChar (PyObject@w{ }*unicode, Py_ssize_t@w{ }index, Py_UCS4@w{ }character)

Write a character to a string.  The string must have been created through
@ref{bad,,PyUnicode_New()}.  Since Unicode strings are supposed to be immutable,
the string must not be shared, or have been hashed yet.

This function checks that @emph{unicode} is a Unicode object, that the index is
not out of bounds, and that the object can be modified safely (i.e. that it
its reference count is one).


3.3 新版功能.

@end deffn

@geindex PyUnicode_ReadChar (C 函数)
@anchor{c-api/unicode c PyUnicode_ReadChar}@anchor{baf}
@deffn {C 函数} Py_UCS4 PyUnicode_ReadChar (PyObject@w{ }*unicode, Py_ssize_t@w{ }index)

Read a character from a string.  This function checks that @emph{unicode} is a
Unicode object and the index is not out of bounds, in contrast to the macro
version @ref{bc4,,PyUnicode_READ_CHAR()}.


3.3 新版功能.

@end deffn

@geindex PyUnicode_Substring (C 函数)
@anchor{c-api/unicode c PyUnicode_Substring}@anchor{bae}
@deffn {C 函数} PyObject* PyUnicode_Substring (PyObject@w{ }*str, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end)
@emph{Return value: New reference.}
Return a substring of @emph{str}, from character index @emph{start} (included) to
character index @emph{end} (excluded).  Negative indices are not supported.


3.3 新版功能.

@end deffn

@geindex PyUnicode_AsUCS4 (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUCS4}@anchor{bb8}
@deffn {C 函数} Py_UCS4* PyUnicode_AsUCS4 (PyObject@w{ }*u, Py_UCS4@w{ }*buffer, Py_ssize_t@w{ }buflen, int@w{ }copy_null)

Copy the string @emph{u} into a UCS4 buffer, including a null character, if
@emph{copy_null} is set.  Returns @code{NULL} and sets an exception on error (in
particular, a @ref{6fc,,SystemError} if @emph{buflen} is smaller than the length of
@emph{u}).  @emph{buffer} is returned on success.


3.3 新版功能.

@end deffn

@geindex PyUnicode_AsUCS4Copy (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUCS4Copy}@anchor{bb9}
@deffn {C 函数} Py_UCS4* PyUnicode_AsUCS4Copy (PyObject@w{ }*u)

Copy the string @emph{u} into a new UCS4 buffer that is allocated using
@ref{607,,PyMem_Malloc()}.  If this fails, @code{NULL} is returned with a
@ref{fb5,,MemoryError} set.  The returned buffer always has an extra
null code point appended.


3.3 新版功能.

@end deffn

@node Deprecated Py_UNICODE APIs,Locale Encoding,Creating and accessing Unicode strings,Unicode对象
@anchor{c-api/unicode deprecated-py-unicode-apis}@anchor{4053}
@subsubsection Deprecated Py_UNICODE APIs



Deprecated since version 3.3, will be removed in version 3.12.


These API functions are deprecated with the implementation of 
@geindex Python 提高建议; PEP 393
PEP 393@footnote{https://www.python.org/dev/peps/pep-0393}.
Extension modules can continue using them, as they will not be removed in Python
3.x, but need to be aware that their use can now cause performance and memory hits.

@geindex PyUnicode_FromUnicode (C 函数)
@anchor{c-api/unicode c PyUnicode_FromUnicode}@anchor{264}
@deffn {C 函数} PyObject* PyUnicode_FromUnicode (const Py_UNICODE@w{ }*u, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Create a Unicode object from the Py_UNICODE buffer @emph{u} of the given size. @emph{u}
may be @code{NULL} which causes the contents to be undefined. It is the user's
responsibility to fill in the needed data.  The buffer is copied into the new
object.

If the buffer is not @code{NULL}, the return value might be a shared object.
Therefore, modification of the resulting Unicode object is only allowed when
@emph{u} is @code{NULL}.

If the buffer is @code{NULL}, @ref{bb6,,PyUnicode_READY()} must be called once the
string content has been filled before using any of the access macros such as
@ref{bbe,,PyUnicode_KIND()}.


Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using
@ref{bb7,,PyUnicode_FromKindAndData()}, @ref{bcf,,PyUnicode_FromWideChar()}, or
@ref{bad,,PyUnicode_New()}.

@end deffn

@geindex PyUnicode_AsUnicode (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUnicode}@anchor{265}
@deffn {C 函数} Py_UNICODE* PyUnicode_AsUnicode (PyObject@w{ }*unicode)

Return a read-only pointer to the Unicode object's internal
@ref{bce,,Py_UNICODE} buffer, or @code{NULL} on error. This will create the
@ref{bce,,Py_UNICODE*} representation of the object if it is not yet
available. The buffer is always terminated with an extra null code point.
Note that the resulting @ref{bce,,Py_UNICODE} string may also contain
embedded null code points, which would cause the string to be truncated when
used in most C functions.


Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using
@ref{bb8,,PyUnicode_AsUCS4()}, @ref{11d0,,PyUnicode_AsWideChar()},
@ref{baf,,PyUnicode_ReadChar()} or similar new APIs.



Deprecated since version 3.3, will be removed in version 3.10.

@end deffn

@geindex PyUnicode_TransformDecimalToASCII (C 函数)
@anchor{c-api/unicode c PyUnicode_TransformDecimalToASCII}@anchor{beb}
@deffn {C 函数} PyObject* PyUnicode_TransformDecimalToASCII (Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Create a Unicode object by replacing all decimal digits in
@ref{bce,,Py_UNICODE} buffer of the given @emph{size} by ASCII digits 0--9
according to their decimal value.  Return @code{NULL} if an exception occurs.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{4048,,Py_UNICODE_TODECIMAL()}.

@end deffn

@geindex PyUnicode_AsUnicodeAndSize (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUnicodeAndSize}@anchor{266}
@deffn {C 函数} Py_UNICODE* PyUnicode_AsUnicodeAndSize (PyObject@w{ }*unicode, Py_ssize_t@w{ }*size)

Like @ref{265,,PyUnicode_AsUnicode()}, but also saves the @ref{bce,,Py_UNICODE()}
array length (excluding the extra null terminator) in @emph{size}.
Note that the resulting @ref{bce,,Py_UNICODE*} string
may contain embedded null code points, which would cause the string to be
truncated when used in most C functions.


3.3 新版功能.



Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using
@ref{bb8,,PyUnicode_AsUCS4()}, @ref{11d0,,PyUnicode_AsWideChar()},
@ref{baf,,PyUnicode_ReadChar()} or similar new APIs.

@end deffn

@geindex PyUnicode_AsUnicodeCopy (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUnicodeCopy}@anchor{bd5}
@deffn {C 函数} Py_UNICODE* PyUnicode_AsUnicodeCopy (PyObject@w{ }*unicode)

Create a copy of a Unicode string ending with a null code point. Return @code{NULL}
and raise a @ref{fb5,,MemoryError} exception on memory allocation failure,
otherwise return a new allocated buffer (use @ref{e76,,PyMem_Free()} to free
the buffer). Note that the resulting @ref{bce,,Py_UNICODE*} string may
contain embedded null code points, which would cause the string to be
truncated when used in most C functions.


3.2 新版功能.


Please migrate to using @ref{bb9,,PyUnicode_AsUCS4Copy()} or similar new APIs.
@end deffn

@geindex PyUnicode_GetSize (C 函数)
@anchor{c-api/unicode c PyUnicode_GetSize}@anchor{bd3}
@deffn {C 函数} Py_ssize_t PyUnicode_GetSize (PyObject@w{ }*unicode)

Return the size of the deprecated @ref{bce,,Py_UNICODE} representation, in
code units (this includes surrogate pairs as 2 units).


Deprecated since version 3.3, will be removed in version 3.12: 旧式 Unicode API 的一部分，请迁移到使用 @ref{bac,,PyUnicode_GET_LENGTH()}。

@end deffn

@geindex PyUnicode_FromObject (C 函数)
@anchor{c-api/unicode c PyUnicode_FromObject}@anchor{4054}
@deffn {C 函数} PyObject* PyUnicode_FromObject (PyObject@w{ }*obj)
@emph{Return value: New reference.}
Copy an instance of a Unicode subtype to a new true Unicode object if
necessary. If @emph{obj} is already a true Unicode object (not a subtype),
return the reference with incremented refcount.

Objects other than Unicode or its subtypes will cause a @ref{1ff,,TypeError}.
@end deffn

@node Locale Encoding,文件系统编码格式,Deprecated Py_UNICODE APIs,Unicode对象
@anchor{c-api/unicode locale-encoding}@anchor{4055}
@subsubsection Locale Encoding


The current locale encoding can be used to decode text from the operating
system.

@geindex PyUnicode_DecodeLocaleAndSize (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeLocaleAndSize}@anchor{549}
@deffn {C 函数} PyObject* PyUnicode_DecodeLocaleAndSize (const char@w{ }*str, Py_ssize_t@w{ }len, const char@w{ }*errors)
@emph{Return value: New reference.}
Decode a string from UTF-8 on Android and VxWorks, or from the current
locale encoding on other platforms. The supported
error handlers are @code{"strict"} and @code{"surrogateescape"}
(
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383}). The decoder uses @code{"strict"} error handler if
@emph{errors} is @code{NULL}.  @emph{str} must end with a null character but
cannot contain embedded null characters.

Use @ref{3e95,,PyUnicode_DecodeFSDefaultAndSize()} to decode a string from
@code{Py_FileSystemDefaultEncoding} (the locale encoding read at
Python startup).

This function ignores the Python UTF-8 mode.


@subsubheading 参见


The @ref{547,,Py_DecodeLocale()} 函数。



3.3 新版功能.



在 3.7 版更改: The function now also uses the current locale encoding for the
@code{surrogateescape} error handler, except on Android. Previously, @ref{547,,Py_DecodeLocale()}
was used for the @code{surrogateescape}, and the current locale encoding was
used for @code{strict}.

@end deffn

@geindex PyUnicode_DecodeLocale (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeLocale}@anchor{4056}
@deffn {C 函数} PyObject* PyUnicode_DecodeLocale (const char@w{ }*str, const char@w{ }*errors)
@emph{Return value: New reference.}
Similar to @ref{549,,PyUnicode_DecodeLocaleAndSize()}, but compute the string
length using @code{strlen()}.


3.3 新版功能.

@end deffn

@geindex PyUnicode_EncodeLocale (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeLocale}@anchor{54a}
@deffn {C 函数} PyObject* PyUnicode_EncodeLocale (PyObject@w{ }*unicode, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current
locale encoding on other platforms. The
supported error handlers are @code{"strict"} and @code{"surrogateescape"}
(
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383}). The encoder uses @code{"strict"} error handler if
@emph{errors} is @code{NULL}. Return a @ref{172,,bytes} object. @emph{unicode} cannot
contain embedded null characters.

Use @ref{11c9,,PyUnicode_EncodeFSDefault()} to encode a string to
@code{Py_FileSystemDefaultEncoding} (the locale encoding read at
Python startup).

This function ignores the Python UTF-8 mode.


@subsubheading 参见


The @ref{548,,Py_EncodeLocale()} function.



3.3 新版功能.



在 3.7 版更改: The function now also uses the current locale encoding for the
@code{surrogateescape} error handler, except on Android. Previously,
@ref{548,,Py_EncodeLocale()}
was used for the @code{surrogateescape}, and the current locale encoding was
used for @code{strict}.

@end deffn

@node 文件系统编码格式,wchar_t Support,Locale Encoding,Unicode对象
@anchor{c-api/unicode file-system-encoding}@anchor{4057}
@subsubsection 文件系统编码格式


To encode and decode file names and other environment strings,
@code{Py_FileSystemDefaultEncoding} should be used as the encoding, and
@code{Py_FileSystemDefaultEncodeErrors} should be used as the error handler
(
@geindex Python 提高建议; PEP 383
PEP 383@footnote{https://www.python.org/dev/peps/pep-0383} and 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529}). To encode file names to @ref{172,,bytes} during
argument parsing, the @code{"O&"} converter should be used, passing
@ref{6cf,,PyUnicode_FSConverter()} as the conversion function:

@geindex PyUnicode_FSConverter (C 函数)
@anchor{c-api/unicode c PyUnicode_FSConverter}@anchor{6cf}
@deffn {C 函数} int PyUnicode_FSConverter (PyObject*@w{ }obj, void*@w{ }result)

ParseTuple converter: encode @ref{206,,str} objects -- obtained directly or
through the @ref{5ee,,os.PathLike} interface -- to @ref{172,,bytes} using
@ref{11c9,,PyUnicode_EncodeFSDefault()}; @ref{172,,bytes} objects are output as-is.
@emph{result} must be a @ref{dec,,PyBytesObject*} which must be released when it is
no longer used.


3.1 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

To decode file names to @ref{206,,str} during argument parsing, the @code{"O&"}
converter should be used, passing @ref{6d0,,PyUnicode_FSDecoder()} as the
conversion function:

@geindex PyUnicode_FSDecoder (C 函数)
@anchor{c-api/unicode c PyUnicode_FSDecoder}@anchor{6d0}
@deffn {C 函数} int PyUnicode_FSDecoder (PyObject*@w{ }obj, void*@w{ }result)

ParseTuple converter: decode @ref{172,,bytes} objects -- obtained either
directly or indirectly through the @ref{5ee,,os.PathLike} interface -- to
@ref{206,,str} using @ref{3e95,,PyUnicode_DecodeFSDefaultAndSize()}; @ref{206,,str}
objects are output as-is. @emph{result} must be a @ref{4036,,PyUnicodeObject*} which
must be released when it is no longer used.


3.2 新版功能.



在 3.6 版更改: 接受一个 @ref{47b,,类路径对象}。

@end deffn

@geindex PyUnicode_DecodeFSDefaultAndSize (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeFSDefaultAndSize}@anchor{3e95}
@deffn {C 函数} PyObject* PyUnicode_DecodeFSDefaultAndSize (const char@w{ }*s, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Decode a string using @code{Py_FileSystemDefaultEncoding} and the
@code{Py_FileSystemDefaultEncodeErrors} error handler.

If @code{Py_FileSystemDefaultEncoding} is not set, fall back to the
locale encoding.

@code{Py_FileSystemDefaultEncoding} is initialized at startup from the
locale encoding and cannot be modified later. If you need to decode a string
from the current locale encoding, use
@ref{549,,PyUnicode_DecodeLocaleAndSize()}.


@subsubheading 参见


The @ref{547,,Py_DecodeLocale()} 函数。



在 3.6 版更改: Use @code{Py_FileSystemDefaultEncodeErrors} error handler.

@end deffn

@geindex PyUnicode_DecodeFSDefault (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeFSDefault}@anchor{4058}
@deffn {C 函数} PyObject* PyUnicode_DecodeFSDefault (const char@w{ }*s)
@emph{Return value: New reference.}
Decode a null-terminated string using @code{Py_FileSystemDefaultEncoding}
and the @code{Py_FileSystemDefaultEncodeErrors} error handler.

If @code{Py_FileSystemDefaultEncoding} is not set, fall back to the
locale encoding.

Use @ref{3e95,,PyUnicode_DecodeFSDefaultAndSize()} if you know the string length.


在 3.6 版更改: Use @code{Py_FileSystemDefaultEncodeErrors} error handler.

@end deffn

@geindex PyUnicode_EncodeFSDefault (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeFSDefault}@anchor{11c9}
@deffn {C 函数} PyObject* PyUnicode_EncodeFSDefault (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object to @code{Py_FileSystemDefaultEncoding} with the
@code{Py_FileSystemDefaultEncodeErrors} error handler, and return
@ref{172,,bytes}. Note that the resulting @ref{172,,bytes} object may contain
null bytes.

If @code{Py_FileSystemDefaultEncoding} is not set, fall back to the
locale encoding.

@code{Py_FileSystemDefaultEncoding} is initialized at startup from the
locale encoding and cannot be modified later. If you need to encode a string
to the current locale encoding, use @ref{54a,,PyUnicode_EncodeLocale()}.


@subsubheading 参见


The @ref{548,,Py_EncodeLocale()} function.



3.2 新版功能.



在 3.6 版更改: Use @code{Py_FileSystemDefaultEncodeErrors} error handler.

@end deffn

@node wchar_t Support,,文件系统编码格式,Unicode对象
@anchor{c-api/unicode wchar-t-support}@anchor{4059}
@subsubsection wchar_t Support


@code{wchar_t} support for platforms which support it:

@geindex PyUnicode_FromWideChar (C 函数)
@anchor{c-api/unicode c PyUnicode_FromWideChar}@anchor{bcf}
@deffn {C 函数} PyObject* PyUnicode_FromWideChar (const wchar_t@w{ }*w, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Create a Unicode object from the @code{wchar_t} buffer @emph{w} of the given @emph{size}.
Passing @code{-1} as the @emph{size} indicates that the function must itself compute the length,
using wcslen.
Return @code{NULL} on failure.
@end deffn

@geindex PyUnicode_AsWideChar (C 函数)
@anchor{c-api/unicode c PyUnicode_AsWideChar}@anchor{11d0}
@deffn {C 函数} Py_ssize_t PyUnicode_AsWideChar (PyObject@w{ }*unicode, wchar_t@w{ }*w, Py_ssize_t@w{ }size)

Copy the Unicode object contents into the @code{wchar_t} buffer @emph{w}.  At most
@emph{size} @code{wchar_t} characters are copied (excluding a possibly trailing
null termination character).  Return the number of @code{wchar_t} characters
copied or @code{-1} in case of an error.  Note that the resulting @code{wchar_t*}
string may or may not be null-terminated.  It is the responsibility of the caller
to make sure that the @code{wchar_t*} string is null-terminated in case this is
required by the application. Also, note that the @code{wchar_t*} string
might contain null characters, which would cause the string to be truncated
when used with most C functions.
@end deffn

@geindex PyUnicode_AsWideCharString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsWideCharString}@anchor{544}
@deffn {C 函数} wchar_t* PyUnicode_AsWideCharString (PyObject@w{ }*unicode, Py_ssize_t@w{ }*size)

Convert the Unicode object to a wide character string. The output string
always ends with a null character. If @emph{size} is not @code{NULL}, write the number
of wide characters (excluding the trailing null termination character) into
@emph{*size}. Note that the resulting @code{wchar_t} string might contain
null characters, which would cause the string to be truncated when used with
most C functions. If @emph{size} is @code{NULL} and the @code{wchar_t*} string
contains null characters a @ref{16d,,ValueError} is raised.

Returns a buffer allocated by @code{PyMem_Alloc()} (use
@ref{e76,,PyMem_Free()} to free it) on success. On error, returns @code{NULL}
and @emph{*size} is undefined. Raises a @ref{fb5,,MemoryError} if memory allocation
is failed.


3.2 新版功能.



在 3.7 版更改: Raises a @ref{16d,,ValueError} if @emph{size} is @code{NULL} and the @code{wchar_t*}
string contains null characters.

@end deffn

@node Built-in Codecs,方法与槽位函数,Unicode对象,Unicode对象和编码解码器
@anchor{c-api/unicode built-in-codecs}@anchor{405a}@anchor{c-api/unicode builtincodecs}@anchor{4052}
@subsubsection Built-in Codecs


Python provides a set of built-in codecs which are written in C for speed. All of
these codecs are directly usable via the following functions.

Many of the following APIs take two arguments encoding and errors, and they
have the same semantics as the ones of the built-in @ref{206,,str()} string object
constructor.

Setting encoding to @code{NULL} causes the default encoding to be used
which is UTF-8.  The file system calls should use
@ref{6cf,,PyUnicode_FSConverter()} for encoding file names. This uses the
variable @code{Py_FileSystemDefaultEncoding} internally. This
variable should be treated as read-only: on some systems, it will be a
pointer to a static string, on others, it will change at run-time
(such as when the application invokes setlocale).

Error handling is set by errors which may also be set to @code{NULL} meaning to use
the default handling defined for the codec.  Default error handling for all
built-in codecs is "strict" (@ref{16d,,ValueError} is raised).

The codecs all use a similar interface.  Only deviations from the following
generic ones are documented for simplicity.

@menu
* Generic Codecs:: 
* UTF-8 编解码器:: 
* UTF-32 Codecs:: 
* UTF-16 Codecs:: 
* UTF-7 Codecs:: 
* Unicode-Escape 编解码器:: 
* Raw-Unicode-Escape Codecs:: 
* Latin-1 Codecs:: 
* ASCII Codecs:: 
* Character Map Codecs:: 
* MBCS codecs for Windows:: 
* Methods & Slots:: 

@end menu

@node Generic Codecs,UTF-8 编解码器,,Built-in Codecs
@anchor{c-api/unicode generic-codecs}@anchor{405b}
@subsubsection Generic Codecs


These are the generic codec APIs:

@geindex PyUnicode_Decode (C 函数)
@anchor{c-api/unicode c PyUnicode_Decode}@anchor{1137}
@deffn {C 函数} PyObject* PyUnicode_Decode (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the encoded string @emph{s}.
@emph{encoding} and @emph{errors} have the same meaning as the parameters of the same name
in the @ref{206,,str()} built-in function.  The codec to be used is looked up
using the Python codec registry.  Return @code{NULL} if an exception was raised by
the codec.
@end deffn

@geindex PyUnicode_AsEncodedString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsEncodedString}@anchor{405c}
@deffn {C 函数} PyObject* PyUnicode_AsEncodedString (PyObject@w{ }*unicode, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode a Unicode object and return the result as Python bytes object.
@emph{encoding} and @emph{errors} have the same meaning as the parameters of the same
name in the Unicode @ref{170,,encode()} method. The codec to be used is looked up
using the Python codec registry. Return @code{NULL} if an exception was raised by
the codec.
@end deffn

@geindex PyUnicode_Encode (C 函数)
@anchor{c-api/unicode c PyUnicode_Encode}@anchor{bd8}
@deffn {C 函数} PyObject* PyUnicode_Encode (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*encoding, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer @emph{s} of the given @emph{size} and return a Python
bytes object.  @emph{encoding} and @emph{errors} have the same meaning as the
parameters of the same name in the Unicode @ref{170,,encode()} method.  The codec
to be used is looked up using the Python codec registry.  Return @code{NULL} if an
exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node UTF-8 编解码器,UTF-32 Codecs,Generic Codecs,Built-in Codecs
@anchor{c-api/unicode utf-8-codecs}@anchor{405d}
@subsubsection UTF-8 编解码器


以下是 UTF-8 编解码器 API:

@geindex PyUnicode_DecodeUTF8 (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF8}@anchor{405e}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF8 (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the UTF-8 encoded string
@emph{s}. Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeUTF8Stateful (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF8Stateful}@anchor{405f}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF8Stateful (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, Py_ssize_t@w{ }*consumed)
@emph{Return value: New reference.}
If @emph{consumed} is @code{NULL}, behave like @ref{405e,,PyUnicode_DecodeUTF8()}. If
@emph{consumed} is not @code{NULL}, trailing incomplete UTF-8 byte sequences will not be
treated as an error. Those bytes will not be decoded and the number of bytes
that have been decoded will be stored in @emph{consumed}.
@end deffn

@geindex PyUnicode_AsUTF8String (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUTF8String}@anchor{bdb}
@deffn {C 函数} PyObject* PyUnicode_AsUTF8String (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using UTF-8 and return the result as Python bytes
object.  Error handling is "strict".  Return @code{NULL} if an exception was
raised by the codec.
@end deffn

@geindex PyUnicode_AsUTF8AndSize (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUTF8AndSize}@anchor{536}
@deffn {C 函数} const char* PyUnicode_AsUTF8AndSize (PyObject@w{ }*unicode, Py_ssize_t@w{ }*size)

Return a pointer to the UTF-8 encoding of the Unicode object, and
store the size of the encoded representation (in bytes) in @emph{size}.  The
@emph{size} argument can be @code{NULL}; in this case no size will be stored.  The
returned buffer always has an extra null byte appended (not included in
@emph{size}), regardless of whether there are any other null code points.

In the case of an error, @code{NULL} is returned with an exception set and no
@emph{size} is stored.

This caches the UTF-8 representation of the string in the Unicode object, and
subsequent calls will return a pointer to the same buffer.  The caller is not
responsible for deallocating the buffer. The buffer is deallocated and
pointers to it become invalid when the Unicode object is garbage collected.


3.3 新版功能.



在 3.7 版更改: The return type is now @code{const char *} rather of @code{char *}.

@end deffn

@geindex PyUnicode_AsUTF8 (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUTF8}@anchor{537}
@deffn {C 函数} const char* PyUnicode_AsUTF8 (PyObject@w{ }*unicode)

As @ref{536,,PyUnicode_AsUTF8AndSize()}, but does not store the size.


3.3 新版功能.



在 3.7 版更改: The return type is now @code{const char *} rather of @code{char *}.

@end deffn

@geindex PyUnicode_EncodeUTF8 (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeUTF8}@anchor{bda}
@deffn {C 函数} PyObject* PyUnicode_EncodeUTF8 (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer @emph{s} of the given @emph{size} using UTF-8 and
return a Python bytes object.  Return @code{NULL} if an exception was raised by
the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{bdb,,PyUnicode_AsUTF8String()}, @ref{536,,PyUnicode_AsUTF8AndSize()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node UTF-32 Codecs,UTF-16 Codecs,UTF-8 编解码器,Built-in Codecs
@anchor{c-api/unicode utf-32-codecs}@anchor{4060}
@subsubsection UTF-32 Codecs


These are the UTF-32 codec APIs:

@geindex PyUnicode_DecodeUTF32 (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF32}@anchor{4061}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF32 (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }*byteorder)
@emph{Return value: New reference.}
Decode @emph{size} bytes from a UTF-32 encoded buffer string and return the
corresponding Unicode object.  @emph{errors} (if non-@code{NULL}) defines the error
handling. It defaults to "strict".

If @emph{byteorder} is non-@code{NULL}, the decoder starts decoding using the given byte
order:

@example
*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian
@end example

If @code{*byteorder} is zero, and the first four bytes of the input data are a
byte order mark (BOM), the decoder switches to this byte order and the BOM is
not copied into the resulting Unicode string.  If @code{*byteorder} is @code{-1} or
@code{1}, any byte order mark is copied to the output.

After completion, @emph{*byteorder} is set to the current byte order at the end
of input data.

If @emph{byteorder} is @code{NULL}, the codec starts in native order mode.

Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeUTF32Stateful (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF32Stateful}@anchor{4062}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF32Stateful (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }*byteorder, Py_ssize_t@w{ }*consumed)
@emph{Return value: New reference.}
If @emph{consumed} is @code{NULL}, behave like @ref{4061,,PyUnicode_DecodeUTF32()}. If
@emph{consumed} is not @code{NULL}, @ref{4062,,PyUnicode_DecodeUTF32Stateful()} will not treat
trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
by four) as an error. Those bytes will not be decoded and the number of bytes
that have been decoded will be stored in @emph{consumed}.
@end deffn

@geindex PyUnicode_AsUTF32String (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUTF32String}@anchor{4063}
@deffn {C 函数} PyObject* PyUnicode_AsUTF32String (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Return a Python byte string using the UTF-32 encoding in native byte
order. The string always starts with a BOM mark.  Error handling is "strict".
Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_EncodeUTF32 (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeUTF32}@anchor{bdc}
@deffn {C 函数} PyObject* PyUnicode_EncodeUTF32 (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }byteorder)
@emph{Return value: New reference.}
Return a Python bytes object holding the UTF-32 encoded value of the Unicode
data in @emph{s}.  Output is written according to the following byte order:

@example
byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian
@end example

If byteorder is @code{0}, the output string will always start with the Unicode BOM
mark (U+FEFF). In the other two modes, no BOM mark is prepended.

If @code{Py_UNICODE_WIDE} is not defined, surrogate pairs will be output
as a single code point.

Return @code{NULL} if an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{4063,,PyUnicode_AsUTF32String()} or @ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node UTF-16 Codecs,UTF-7 Codecs,UTF-32 Codecs,Built-in Codecs
@anchor{c-api/unicode utf-16-codecs}@anchor{4064}
@subsubsection UTF-16 Codecs


These are the UTF-16 codec APIs:

@geindex PyUnicode_DecodeUTF16 (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF16}@anchor{4065}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF16 (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }*byteorder)
@emph{Return value: New reference.}
Decode @emph{size} bytes from a UTF-16 encoded buffer string and return the
corresponding Unicode object.  @emph{errors} (if non-@code{NULL}) defines the error
handling. It defaults to "strict".

If @emph{byteorder} is non-@code{NULL}, the decoder starts decoding using the given byte
order:

@example
*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian
@end example

If @code{*byteorder} is zero, and the first two bytes of the input data are a
byte order mark (BOM), the decoder switches to this byte order and the BOM is
not copied into the resulting Unicode string.  If @code{*byteorder} is @code{-1} or
@code{1}, any byte order mark is copied to the output (where it will result in
either a @code{\ufeff} or a @code{\ufffe} character).

After completion, @code{*byteorder} is set to the current byte order at the end
of input data.

If @emph{byteorder} is @code{NULL}, the codec starts in native order mode.

Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeUTF16Stateful (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF16Stateful}@anchor{4066}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF16Stateful (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }*byteorder, Py_ssize_t@w{ }*consumed)
@emph{Return value: New reference.}
If @emph{consumed} is @code{NULL}, behave like @ref{4065,,PyUnicode_DecodeUTF16()}. If
@emph{consumed} is not @code{NULL}, @ref{4066,,PyUnicode_DecodeUTF16Stateful()} will not treat
trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
split surrogate pair) as an error. Those bytes will not be decoded and the
number of bytes that have been decoded will be stored in @emph{consumed}.
@end deffn

@geindex PyUnicode_AsUTF16String (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUTF16String}@anchor{4067}
@deffn {C 函数} PyObject* PyUnicode_AsUTF16String (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Return a Python byte string using the UTF-16 encoding in native byte
order. The string always starts with a BOM mark.  Error handling is "strict".
Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_EncodeUTF16 (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeUTF16}@anchor{bdd}
@deffn {C 函数} PyObject* PyUnicode_EncodeUTF16 (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, int@w{ }byteorder)
@emph{Return value: New reference.}
Return a Python bytes object holding the UTF-16 encoded value of the Unicode
data in @emph{s}.  Output is written according to the following byte order:

@example
byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian
@end example

If byteorder is @code{0}, the output string will always start with the Unicode BOM
mark (U+FEFF). In the other two modes, no BOM mark is prepended.

If @code{Py_UNICODE_WIDE} is defined, a single @ref{bce,,Py_UNICODE} value may get
represented as a surrogate pair. If it is not defined, each @ref{bce,,Py_UNICODE}
values is interpreted as a UCS-2 character.

Return @code{NULL} if an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{4067,,PyUnicode_AsUTF16String()} or @ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node UTF-7 Codecs,Unicode-Escape 编解码器,UTF-16 Codecs,Built-in Codecs
@anchor{c-api/unicode utf-7-codecs}@anchor{4068}
@subsubsection UTF-7 Codecs


These are the UTF-7 codec APIs:

@geindex PyUnicode_DecodeUTF7 (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF7}@anchor{4069}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF7 (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the UTF-7 encoded string
@emph{s}.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeUTF7Stateful (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUTF7Stateful}@anchor{406a}
@deffn {C 函数} PyObject* PyUnicode_DecodeUTF7Stateful (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, Py_ssize_t@w{ }*consumed)
@emph{Return value: New reference.}
If @emph{consumed} is @code{NULL}, behave like @ref{4069,,PyUnicode_DecodeUTF7()}.  If
@emph{consumed} is not @code{NULL}, trailing incomplete UTF-7 base-64 sections will not
be treated as an error.  Those bytes will not be decoded and the number of
bytes that have been decoded will be stored in @emph{consumed}.
@end deffn

@geindex PyUnicode_EncodeUTF7 (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeUTF7}@anchor{bd9}
@deffn {C 函数} PyObject* PyUnicode_EncodeUTF7 (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, int@w{ }base64SetO, int@w{ }base64WhiteSpace, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given size using UTF-7 and
return a Python bytes object.  Return @code{NULL} if an exception was raised by
the codec.

If @emph{base64SetO} is nonzero, "Set O" (punctuation that has no otherwise
special meaning) will be encoded in base-64.  If @emph{base64WhiteSpace} is
nonzero, whitespace will be encoded in base-64.  Both are set to zero for the
Python "utf-7" codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node Unicode-Escape 编解码器,Raw-Unicode-Escape Codecs,UTF-7 Codecs,Built-in Codecs
@anchor{c-api/unicode unicode-escape-codecs}@anchor{406b}
@subsubsection Unicode-Escape 编解码器


These are the "Unicode Escape" codec APIs:

@geindex PyUnicode_DecodeUnicodeEscape (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeUnicodeEscape}@anchor{406c}
@deffn {C 函数} PyObject* PyUnicode_DecodeUnicodeEscape (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the Unicode-Escape encoded
string @emph{s}.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsUnicodeEscapeString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsUnicodeEscapeString}@anchor{bdf}
@deffn {C 函数} PyObject* PyUnicode_AsUnicodeEscapeString (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using Unicode-Escape and return the result as a
bytes object.  Error handling is "strict".  Return @code{NULL} if an exception was
raised by the codec.
@end deffn

@geindex PyUnicode_EncodeUnicodeEscape (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeUnicodeEscape}@anchor{bde}
@deffn {C 函数} PyObject* PyUnicode_EncodeUnicodeEscape (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using Unicode-Escape and
return a bytes object.  Return @code{NULL} if an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{bdf,,PyUnicode_AsUnicodeEscapeString()}.

@end deffn

@node Raw-Unicode-Escape Codecs,Latin-1 Codecs,Unicode-Escape 编解码器,Built-in Codecs
@anchor{c-api/unicode raw-unicode-escape-codecs}@anchor{406d}
@subsubsection Raw-Unicode-Escape Codecs


These are the "Raw Unicode Escape" codec APIs:

@geindex PyUnicode_DecodeRawUnicodeEscape (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeRawUnicodeEscape}@anchor{406e}
@deffn {C 函数} PyObject* PyUnicode_DecodeRawUnicodeEscape (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the Raw-Unicode-Escape
encoded string @emph{s}.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsRawUnicodeEscapeString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsRawUnicodeEscapeString}@anchor{be1}
@deffn {C 函数} PyObject* PyUnicode_AsRawUnicodeEscapeString (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using Raw-Unicode-Escape and return the result as
a bytes object.  Error handling is "strict".  Return @code{NULL} if an exception
was raised by the codec.
@end deffn

@geindex PyUnicode_EncodeRawUnicodeEscape (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeRawUnicodeEscape}@anchor{be0}
@deffn {C 函数} PyObject* PyUnicode_EncodeRawUnicodeEscape (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using Raw-Unicode-Escape
and return a bytes object.  Return @code{NULL} if an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{be1,,PyUnicode_AsRawUnicodeEscapeString()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node Latin-1 Codecs,ASCII Codecs,Raw-Unicode-Escape Codecs,Built-in Codecs
@anchor{c-api/unicode latin-1-codecs}@anchor{406f}
@subsubsection Latin-1 Codecs


These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
ordinals and only these are accepted by the codecs during encoding.

@geindex PyUnicode_DecodeLatin1 (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeLatin1}@anchor{4070}
@deffn {C 函数} PyObject* PyUnicode_DecodeLatin1 (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the Latin-1 encoded string
@emph{s}.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsLatin1String (C 函数)
@anchor{c-api/unicode c PyUnicode_AsLatin1String}@anchor{be3}
@deffn {C 函数} PyObject* PyUnicode_AsLatin1String (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using Latin-1 and return the result as Python bytes
object.  Error handling is "strict".  Return @code{NULL} if an exception was
raised by the codec.
@end deffn

@geindex PyUnicode_EncodeLatin1 (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeLatin1}@anchor{be2}
@deffn {C 函数} PyObject* PyUnicode_EncodeLatin1 (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using Latin-1 and
return a Python bytes object.  Return @code{NULL} if an exception was raised by
the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{be3,,PyUnicode_AsLatin1String()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node ASCII Codecs,Character Map Codecs,Latin-1 Codecs,Built-in Codecs
@anchor{c-api/unicode ascii-codecs}@anchor{4071}
@subsubsection ASCII Codecs


These are the ASCII codec APIs.  Only 7-bit ASCII data is accepted. All other
codes generate errors.

@geindex PyUnicode_DecodeASCII (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeASCII}@anchor{4072}
@deffn {C 函数} PyObject* PyUnicode_DecodeASCII (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the ASCII encoded string
@emph{s}.  Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_AsASCIIString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsASCIIString}@anchor{be5}
@deffn {C 函数} PyObject* PyUnicode_AsASCIIString (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using ASCII and return the result as Python bytes
object.  Error handling is "strict".  Return @code{NULL} if an exception was
raised by the codec.
@end deffn

@geindex PyUnicode_EncodeASCII (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeASCII}@anchor{be4}
@deffn {C 函数} PyObject* PyUnicode_EncodeASCII (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using ASCII and
return a Python bytes object.  Return @code{NULL} if an exception was raised by
the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{be5,,PyUnicode_AsASCIIString()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node Character Map Codecs,MBCS codecs for Windows,ASCII Codecs,Built-in Codecs
@anchor{c-api/unicode character-map-codecs}@anchor{4073}
@subsubsection Character Map Codecs


This codec is special in that it can be used to implement many different codecs
(and this is in fact what was done to obtain most of the standard codecs
included in the @code{encodings} package). The codec uses mappings to encode and
decode characters.  The mapping objects provided must support the
@ref{3ad,,__getitem__()} mapping interface; dictionaries and sequences work well.

These are the mapping codec APIs:

@geindex PyUnicode_DecodeCharmap (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeCharmap}@anchor{4074}
@deffn {C 函数} PyObject* PyUnicode_DecodeCharmap (const char@w{ }*data, Py_ssize_t@w{ }size, PyObject@w{ }*mapping, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the encoded string @emph{s}
using the given @emph{mapping} object.  Return @code{NULL} if an exception was raised
by the codec.

If @emph{mapping} is @code{NULL}, Latin-1 decoding will be applied.  Else
@emph{mapping} must map bytes ordinals (integers in the range from 0 to 255)
to Unicode strings, integers (which are then interpreted as Unicode
ordinals) or @code{None}.  Unmapped data bytes -- ones which cause a
@ref{17c1,,LookupError}, as well as ones which get mapped to @code{None},
@code{0xFFFE} or @code{'\ufffe'}, are treated as undefined mappings and cause
an error.
@end deffn

@geindex PyUnicode_AsCharmapString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsCharmapString}@anchor{4075}
@deffn {C 函数} PyObject* PyUnicode_AsCharmapString (PyObject@w{ }*unicode, PyObject@w{ }*mapping)
@emph{Return value: New reference.}
Encode a Unicode object using the given @emph{mapping} object and return the
result as a bytes object.  Error handling is "strict".  Return @code{NULL} if an
exception was raised by the codec.

The @emph{mapping} object must map Unicode ordinal integers to bytes objects,
integers in the range from 0 to 255 or @code{None}.  Unmapped character
ordinals (ones which cause a @ref{17c1,,LookupError}) as well as mapped to
@code{None} are treated as "undefined mapping" and cause an error.
@end deffn

@geindex PyUnicode_EncodeCharmap (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeCharmap}@anchor{be6}
@deffn {C 函数} PyObject* PyUnicode_EncodeCharmap (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, PyObject@w{ }*mapping, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using the given
@emph{mapping} object and return the result as a bytes object.  Return @code{NULL} if
an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{4075,,PyUnicode_AsCharmapString()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

The following codec API is special in that maps Unicode to Unicode.

@geindex PyUnicode_Translate (C 函数)
@anchor{c-api/unicode c PyUnicode_Translate}@anchor{4076}
@deffn {C 函数} PyObject* PyUnicode_Translate (PyObject@w{ }*str, PyObject@w{ }*table, const char@w{ }*errors)
@emph{Return value: New reference.}
Translate a string by applying a character mapping table to it and return the
resulting Unicode object. Return @code{NULL} if an exception was raised by the
codec.

The mapping table must map Unicode ordinal integers to Unicode ordinal integers
or @code{None} (causing deletion of the character).

Mapping tables need only provide the @ref{3ad,,__getitem__()} interface; dictionaries
and sequences work well.  Unmapped character ordinals (ones which cause a
@ref{17c1,,LookupError}) are left untouched and are copied as-is.

@emph{errors} has the usual meaning for codecs. It may be @code{NULL} which indicates to
use the default error handling.
@end deffn

@geindex PyUnicode_TranslateCharmap (C 函数)
@anchor{c-api/unicode c PyUnicode_TranslateCharmap}@anchor{be7}
@deffn {C 函数} PyObject* PyUnicode_TranslateCharmap (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, PyObject@w{ }*mapping, const char@w{ }*errors)
@emph{Return value: New reference.}
Translate a @ref{bce,,Py_UNICODE} buffer of the given @emph{size} by applying a
character @emph{mapping} table to it and return the resulting Unicode object.
Return @code{NULL} when an exception was raised by the codec.


Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{4076,,PyUnicode_Translate()}. or @ref{6ef,,generic codec based API}

@end deffn

@node MBCS codecs for Windows,Methods & Slots,Character Map Codecs,Built-in Codecs
@anchor{c-api/unicode mbcs-codecs-for-windows}@anchor{4077}
@subsubsection MBCS codecs for Windows


These are the MBCS codec APIs. They are currently only available on Windows and
use the Win32 MBCS converters to implement the conversions.  Note that MBCS (or
DBCS) is a class of encodings, not just one.  The target encoding is defined by
the user settings on the machine running the codec.

@geindex PyUnicode_DecodeMBCS (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeMBCS}@anchor{4078}
@deffn {C 函数} PyObject* PyUnicode_DecodeMBCS (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Create a Unicode object by decoding @emph{size} bytes of the MBCS encoded string @emph{s}.
Return @code{NULL} if an exception was raised by the codec.
@end deffn

@geindex PyUnicode_DecodeMBCSStateful (C 函数)
@anchor{c-api/unicode c PyUnicode_DecodeMBCSStateful}@anchor{4079}
@deffn {C 函数} PyObject* PyUnicode_DecodeMBCSStateful (const char@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors, Py_ssize_t@w{ }*consumed)
@emph{Return value: New reference.}
If @emph{consumed} is @code{NULL}, behave like @ref{4078,,PyUnicode_DecodeMBCS()}. If
@emph{consumed} is not @code{NULL}, @ref{4079,,PyUnicode_DecodeMBCSStateful()} will not decode
trailing lead byte and the number of bytes that have been decoded will be stored
in @emph{consumed}.
@end deffn

@geindex PyUnicode_AsMBCSString (C 函数)
@anchor{c-api/unicode c PyUnicode_AsMBCSString}@anchor{be9}
@deffn {C 函数} PyObject* PyUnicode_AsMBCSString (PyObject@w{ }*unicode)
@emph{Return value: New reference.}
Encode a Unicode object using MBCS and return the result as Python bytes
object.  Error handling is "strict".  Return @code{NULL} if an exception was
raised by the codec.
@end deffn

@geindex PyUnicode_EncodeCodePage (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeCodePage}@anchor{bea}
@deffn {C 函数} PyObject* PyUnicode_EncodeCodePage (int@w{ }code_page, PyObject@w{ }*unicode, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the Unicode object using the specified code page and return a Python
bytes object.  Return @code{NULL} if an exception was raised by the codec. Use
@code{CP_ACP} code page to get the MBCS encoder.


3.3 新版功能.

@end deffn

@geindex PyUnicode_EncodeMBCS (C 函数)
@anchor{c-api/unicode c PyUnicode_EncodeMBCS}@anchor{be8}
@deffn {C 函数} PyObject* PyUnicode_EncodeMBCS (const Py_UNICODE@w{ }*s, Py_ssize_t@w{ }size, const char@w{ }*errors)
@emph{Return value: New reference.}
Encode the @ref{bce,,Py_UNICODE} buffer of the given @emph{size} using MBCS and return
a Python bytes object.  Return @code{NULL} if an exception was raised by the
codec.


Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style @ref{bce,,Py_UNICODE} API; please migrate to using
@ref{be9,,PyUnicode_AsMBCSString()}, @ref{bea,,PyUnicode_EncodeCodePage()} or
@ref{405c,,PyUnicode_AsEncodedString()}.

@end deffn

@node Methods & Slots,,MBCS codecs for Windows,Built-in Codecs
@anchor{c-api/unicode methods-slots}@anchor{407a}
@subsubsection Methods & Slots


@node 方法与槽位函数,,Built-in Codecs,Unicode对象和编码解码器
@anchor{c-api/unicode methods-and-slot-functions}@anchor{407b}@anchor{c-api/unicode unicodemethodsandslots}@anchor{407c}
@subsubsection 方法与槽位函数


The following APIs are capable of handling Unicode objects and strings on input
(we refer to them as strings in the descriptions) and return Unicode objects or
integers as appropriate.

They all return @code{NULL} or @code{-1} if an exception occurs.

@geindex PyUnicode_Concat (C 函数)
@anchor{c-api/unicode c PyUnicode_Concat}@anchor{bf9}
@deffn {C 函数} PyObject* PyUnicode_Concat (PyObject@w{ }*left, PyObject@w{ }*right)
@emph{Return value: New reference.}
Concat two strings giving a new Unicode string.
@end deffn

@geindex PyUnicode_Split (C 函数)
@anchor{c-api/unicode c PyUnicode_Split}@anchor{407d}
@deffn {C 函数} PyObject* PyUnicode_Split (PyObject@w{ }*s, PyObject@w{ }*sep, Py_ssize_t@w{ }maxsplit)
@emph{Return value: New reference.}
Split a string giving a list of Unicode strings.  If @emph{sep} is @code{NULL}, splitting
will be done at all whitespace substrings.  Otherwise, splits occur at the given
separator.  At most @emph{maxsplit} splits will be done.  If negative, no limit is
set.  Separators are not included in the resulting list.
@end deffn

@geindex PyUnicode_Splitlines (C 函数)
@anchor{c-api/unicode c PyUnicode_Splitlines}@anchor{407e}
@deffn {C 函数} PyObject* PyUnicode_Splitlines (PyObject@w{ }*s, int@w{ }keepend)
@emph{Return value: New reference.}
Split a Unicode string at line breaks, returning a list of Unicode strings.
CRLF is considered to be one line break.  If @emph{keepend} is @code{0}, the line break
characters are not included in the resulting strings.
@end deffn

@geindex PyUnicode_Join (C 函数)
@anchor{c-api/unicode c PyUnicode_Join}@anchor{bfa}
@deffn {C 函数} PyObject* PyUnicode_Join (PyObject@w{ }*separator, PyObject@w{ }*seq)
@emph{Return value: New reference.}
Join a sequence of strings using the given @emph{separator} and return the resulting
Unicode string.
@end deffn

@geindex PyUnicode_Tailmatch (C 函数)
@anchor{c-api/unicode c PyUnicode_Tailmatch}@anchor{273}
@deffn {C 函数} Py_ssize_t PyUnicode_Tailmatch (PyObject@w{ }*str, PyObject@w{ }*substr, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, int@w{ }direction)

Return @code{1} if @emph{substr} matches @code{str[start:end]} at the given tail end
(@emph{direction} == @code{-1} means to do a prefix match, @emph{direction} == @code{1} a suffix match),
@code{0} otherwise. Return @code{-1} if an error occurred.
@end deffn

@geindex PyUnicode_Find (C 函数)
@anchor{c-api/unicode c PyUnicode_Find}@anchor{407f}
@deffn {C 函数} Py_ssize_t PyUnicode_Find (PyObject@w{ }*str, PyObject@w{ }*substr, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, int@w{ }direction)

Return the first position of @emph{substr} in @code{str[start:end]} using the given
@emph{direction} (@emph{direction} == @code{1} means to do a forward search, @emph{direction} == @code{-1} a
backward search).  The return value is the index of the first match; a value of
@code{-1} indicates that no match was found, and @code{-2} indicates that an error
occurred and an exception has been set.
@end deffn

@geindex PyUnicode_FindChar (C 函数)
@anchor{c-api/unicode c PyUnicode_FindChar}@anchor{54b}
@deffn {C 函数} Py_ssize_t PyUnicode_FindChar (PyObject@w{ }*str, Py_UCS4@w{ }ch, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end, int@w{ }direction)

Return the first position of the character @emph{ch} in @code{str[start:end]} using
the given @emph{direction} (@emph{direction} == @code{1} means to do a forward search,
@emph{direction} == @code{-1} a backward search).  The return value is the index of the
first match; a value of @code{-1} indicates that no match was found, and @code{-2}
indicates that an error occurred and an exception has been set.


3.3 新版功能.



在 3.7 版更改: @emph{start} and @emph{end} are now adjusted to behave like @code{str[start:end]}.

@end deffn

@geindex PyUnicode_Count (C 函数)
@anchor{c-api/unicode c PyUnicode_Count}@anchor{4080}
@deffn {C 函数} Py_ssize_t PyUnicode_Count (PyObject@w{ }*str, PyObject@w{ }*substr, Py_ssize_t@w{ }start, Py_ssize_t@w{ }end)

Return the number of non-overlapping occurrences of @emph{substr} in
@code{str[start:end]}.  Return @code{-1} if an error occurred.
@end deffn

@geindex PyUnicode_Replace (C 函数)
@anchor{c-api/unicode c PyUnicode_Replace}@anchor{4081}
@deffn {C 函数} PyObject* PyUnicode_Replace (PyObject@w{ }*str, PyObject@w{ }*substr, PyObject@w{ }*replstr, Py_ssize_t@w{ }maxcount)
@emph{Return value: New reference.}
Replace at most @emph{maxcount} occurrences of @emph{substr} in @emph{str} with @emph{replstr} and
return the resulting Unicode object. @emph{maxcount} == @code{-1} means replace all
occurrences.
@end deffn

@geindex PyUnicode_Compare (C 函数)
@anchor{c-api/unicode c PyUnicode_Compare}@anchor{bd6}
@deffn {C 函数} int PyUnicode_Compare (PyObject@w{ }*left, PyObject@w{ }*right)

Compare two strings and return @code{-1}, @code{0}, @code{1} for less than, equal, and greater than,
respectively.

This function returns @code{-1} upon failure, so one should call
@ref{3d58,,PyErr_Occurred()} to check for errors.
@end deffn

@geindex PyUnicode_CompareWithASCIIString (C 函数)
@anchor{c-api/unicode c PyUnicode_CompareWithASCIIString}@anchor{cd1}
@deffn {C 函数} int PyUnicode_CompareWithASCIIString (PyObject@w{ }*uni, const char@w{ }*string)

Compare a Unicode object, @emph{uni}, with @emph{string} and return @code{-1}, @code{0}, @code{1} for less
than, equal, and greater than, respectively. It is best to pass only
ASCII-encoded strings, but the function interprets the input string as
ISO-8859-1 if it contains non-ASCII characters.

This function does not raise exceptions.
@end deffn

@geindex PyUnicode_RichCompare (C 函数)
@anchor{c-api/unicode c PyUnicode_RichCompare}@anchor{4082}
@deffn {C 函数} PyObject* PyUnicode_RichCompare (PyObject@w{ }*left, PyObject@w{ }*right, int@w{ }op)
@emph{Return value: New reference.}
对两个 Unicode 字符串执行富比较并返回以下值之一:


@itemize *

@item 
@code{NULL} in case an exception was raised

@item 
@code{Py_True} or @code{Py_False} for successful comparisons

@item 
@code{Py_NotImplemented} in case the type combination is unknown
@end itemize

Possible values for @emph{op} are @code{Py_GT}, @code{Py_GE}, @code{Py_EQ},
@code{Py_NE}, @code{Py_LT}, and @code{Py_LE}.
@end deffn

@geindex PyUnicode_Format (C 函数)
@anchor{c-api/unicode c PyUnicode_Format}@anchor{4083}
@deffn {C 函数} PyObject* PyUnicode_Format (PyObject@w{ }*format, PyObject@w{ }*args)
@emph{Return value: New reference.}
Return a new string object from @emph{format} and @emph{args}; this is analogous to
@code{format % args}.
@end deffn

@geindex PyUnicode_Contains (C 函数)
@anchor{c-api/unicode c PyUnicode_Contains}@anchor{4084}
@deffn {C 函数} int PyUnicode_Contains (PyObject@w{ }*container, PyObject@w{ }*element)

Check whether @emph{element} is contained in @emph{container} and return true or false
accordingly.

@emph{element} has to coerce to a one element Unicode string. @code{-1} is returned
if there was an error.
@end deffn

@geindex PyUnicode_InternInPlace (C 函数)
@anchor{c-api/unicode c PyUnicode_InternInPlace}@anchor{4085}
@deffn {C 函数} void PyUnicode_InternInPlace (PyObject@w{ }**string)

Intern the argument @emph{*string} in place.  The argument must be the address of a
pointer variable pointing to a Python Unicode string object.  If there is an
existing interned string that is the same as @emph{*string}, it sets @emph{*string} to
it (decrementing the reference count of the old string object and incrementing
the reference count of the interned string object), otherwise it leaves
@emph{*string} alone and interns it (incrementing its reference count).
(Clarification: even though there is a lot of talk about reference counts, think
of this function as reference-count-neutral; you own the object after the call
if and only if you owned it before the call.)
@end deffn

@geindex PyUnicode_InternFromString (C 函数)
@anchor{c-api/unicode c PyUnicode_InternFromString}@anchor{4086}
@deffn {C 函数} PyObject* PyUnicode_InternFromString (const char@w{ }*v)
@emph{Return value: New reference.}
A combination of @ref{3de2,,PyUnicode_FromString()} and
@ref{4085,,PyUnicode_InternInPlace()}, returning either a new Unicode string
object that has been interned, or a new ("owned") reference to an earlier
interned string object with the same value.
@end deffn

@node 元组对象,结构序列对象,Unicode对象和编码解码器,序列对象
@anchor{c-api/tuple doc}@anchor{4087}@anchor{c-api/tuple tuple-objects}@anchor{4088}@anchor{c-api/tuple tupleobjects}@anchor{4089}
@subsubsection 元组对象


@geindex 对象; tuple

@geindex PyTupleObject (C 类型)
@anchor{c-api/tuple c PyTupleObject}@anchor{3ea3}
@deffn {C 类型} PyTupleObject

这个 @ref{5bd,,PyObject} 的子类型代表一个 Python 的元组对象。
@end deffn

@geindex PyTuple_Type (C 变量)
@anchor{c-api/tuple c PyTuple_Type}@anchor{408a}
@deffn {C 变量} PyTypeObject PyTuple_Type

@ref{3fe,,PyTypeObject} 的实例代表一个 Python 元组类型，这与 Python 层面的 @ref{1a2,,tuple} 是相同的对象。
@end deffn

@geindex PyTuple_Check (C 函数)
@anchor{c-api/tuple c PyTuple_Check}@anchor{408b}
@deffn {C 函数} int PyTuple_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 tuple 对象或者 tuple 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyTuple_CheckExact (C 函数)
@anchor{c-api/tuple c PyTuple_CheckExact}@anchor{408c}
@deffn {C 函数} int PyTuple_CheckExact (PyObject@w{ }*p)

如果 @emph{p} 是一个 tuple 对象但不是 tuple 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyTuple_New (C 函数)
@anchor{c-api/tuple c PyTuple_New}@anchor{408d}
@deffn {C 函数} PyObject* PyTuple_New (Py_ssize_t@w{ }len)
@emph{Return value: New reference.}
成功时返回一个新的元组对象，长度为 @emph{len}，失败时返回`@w{`}NULL`@w{`}。
@end deffn

@geindex PyTuple_Pack (C 函数)
@anchor{c-api/tuple c PyTuple_Pack}@anchor{408e}
@deffn {C 函数} PyObject* PyTuple_Pack (Py_ssize_t@w{ }n, ...)
@emph{Return value: New reference.}
成功时返回一个新的元组对象，大小为 @emph{n} ，失败时返回 @code{NULL}。 元组值初始化为指向 Python 对象的后续 @emph{n} 个 C 参数。 @code{PyTuple_Pack(2, a, b)} 和 @code{Py_BuildValue("(OO)", a, b)} 相等。
@end deffn

@geindex PyTuple_Size (C 函数)
@anchor{c-api/tuple c PyTuple_Size}@anchor{408f}
@deffn {C 函数} Py_ssize_t PyTuple_Size (PyObject@w{ }*p)

获取指向元组对象的指针，并返回该元组的大小。
@end deffn

@geindex PyTuple_GET_SIZE (C 函数)
@anchor{c-api/tuple c PyTuple_GET_SIZE}@anchor{4090}
@deffn {C 函数} Py_ssize_t PyTuple_GET_SIZE (PyObject@w{ }*p)

返回元组 @emph{p} 的大小，它必须为非 @code{NULL} 并且指向一个元组；不执行错误检查。
@end deffn

@geindex PyTuple_GetItem (C 函数)
@anchor{c-api/tuple c PyTuple_GetItem}@anchor{3d73}
@deffn {C 函数} PyObject* PyTuple_GetItem (PyObject@w{ }*p, Py_ssize_t@w{ }pos)
@emph{Return value: Borrowed reference.}
返回 @emph{p} 所指向的元组中，位于 @emph{pos} 处的对象。 如果 @emph{pos} 超出界限，返回 @code{NULL}，并抛出一个 @ref{f3d,,IndexError} 异常。
@end deffn

@geindex PyTuple_GET_ITEM (C 函数)
@anchor{c-api/tuple c PyTuple_GET_ITEM}@anchor{4091}
@deffn {C 函数} PyObject* PyTuple_GET_ITEM (PyObject@w{ }*p, Py_ssize_t@w{ }pos)
@emph{Return value: Borrowed reference.}
类似于 @ref{3d73,,PyTuple_GetItem()}，但不检查其参数。
@end deffn

@geindex PyTuple_GetSlice (C 函数)
@anchor{c-api/tuple c PyTuple_GetSlice}@anchor{4092}
@deffn {C 函数} PyObject* PyTuple_GetSlice (PyObject@w{ }*p, Py_ssize_t@w{ }low, Py_ssize_t@w{ }high)
@emph{Return value: New reference.}
返回 @emph{p} 所指向的元组的切片，在 @emph{low} 和 @emph{high} 之间，或者在失败时返回 @code{NULL}。 这等同于 Python 表达式 @code{p[low:high]}。 不支持从列表末尾索引。
@end deffn

@geindex PyTuple_SetItem (C 函数)
@anchor{c-api/tuple c PyTuple_SetItem}@anchor{3d78}
@deffn {C 函数} int PyTuple_SetItem (PyObject@w{ }*p, Py_ssize_t@w{ }pos, PyObject@w{ }*o)

在 @emph{p} 指向的元组的 @emph{pos} 位置插入对对象 @emph{o} 的引用。 成功时返回 @code{0}；如果 @emph{pos} 越界，则返回 @code{-1}，并抛出一个 @ref{f3d,,IndexError} 异常。

@cartouche
@quotation 注解 
此函数会“窃取”对 @emph{o} 的引用，并丢弃对元组中已在受影响位置的条目的引用。
@end quotation
@end cartouche
@end deffn

@geindex PyTuple_SET_ITEM (C 函数)
@anchor{c-api/tuple c PyTuple_SET_ITEM}@anchor{4093}
@deffn {C 函数} void PyTuple_SET_ITEM (PyObject@w{ }*p, Py_ssize_t@w{ }pos, PyObject@w{ }*o)

类似于 @ref{3d78,,PyTuple_SetItem()}，但不进行错误检查，并且应该 @emph{只是} 被用来填充全新的元组。

@cartouche
@quotation 注解 
这个宏会“偷走”一个对 @emph{o} 的引用，但与 @ref{3d78,,PyTuple_SetItem()} 不同，它 @emph{不会} 丢弃对任何被替换项的引用；元组中位于 @emph{pos} 位置的任何引用都将被泄漏。
@end quotation
@end cartouche
@end deffn

@geindex _PyTuple_Resize (C 函数)
@anchor{c-api/tuple c _PyTuple_Resize}@anchor{f15}
@deffn {C 函数} int _PyTuple_Resize (PyObject@w{ }**p, Py_ssize_t@w{ }newsize)

可以用于调整元组的大小。 @emph{newsize} 将是元组的新长度。 因为元组 @emph{被认为} 是不可变的，所以只有在对象仅有一个引用时，才应该使用它。 如果元组已经被代码的其他部分所引用，请不要使用此项。 元组在最后总是会增长或缩小。 把它看作是销毁旧元组并创建一个新元组，只会更有效。 成功时返回 @code{0} 。 客户端代码不应假定 @code{*p} 的结果值将与调用此函数之前的值相同。 如果替换了 @code{*p} 引用的对象，则原始的 @code{*p} 将被销毁。 失败时，返回`@w{`}-1`@w{`}，将 @code{*p} 设置为 @code{NULL}，并引发 @ref{fb5,,MemoryError} 或者 @ref{6fc,,SystemError}。
@end deffn

@node 结构序列对象,列表对象,元组对象,序列对象
@anchor{c-api/tuple struct-sequence-objects}@anchor{4094}
@subsubsection 结构序列对象


结构序列对象是等价于 @ref{1a1,,namedtuple()} 的 C 对象，即一个序列，其中的条目也可以通过属性访问。 要创建结构序列，你首先必须创建特定的结构序列类型。

@geindex PyStructSequence_NewType (C 函数)
@anchor{c-api/tuple c PyStructSequence_NewType}@anchor{fe9}
@deffn {C 函数} PyTypeObject* PyStructSequence_NewType (PyStructSequence_Desc@w{ }*desc)
@emph{Return value: New reference.}
根据 @emph{desc} 中的数据创建一个新的结构序列类型，如下所述。 可以使用 @ref{4095,,PyStructSequence_New()} 创建结果类型的实例。
@end deffn

@geindex PyStructSequence_InitType (C 函数)
@anchor{c-api/tuple c PyStructSequence_InitType}@anchor{a15}
@deffn {C 函数} void PyStructSequence_InitType (PyTypeObject@w{ }*type, PyStructSequence_Desc@w{ }*desc)

从 @emph{desc} 就地初始化结构序列类型 @emph{type}。
@end deffn

@geindex PyStructSequence_InitType2 (C 函数)
@anchor{c-api/tuple c PyStructSequence_InitType2}@anchor{a14}
@deffn {C 函数} int PyStructSequence_InitType2 (PyTypeObject@w{ }*type, PyStructSequence_Desc@w{ }*desc)

与 @code{PyStructSequence_InitType} 相同，但成功时返回 @code{0} ，失败时返回 @code{-1} 。


3.4 新版功能.

@end deffn

@geindex PyStructSequence_Desc (C 类型)
@anchor{c-api/tuple c PyStructSequence_Desc}@anchor{535}
@deffn {C 类型} PyStructSequence_Desc

包含要创建的结构序列类型的元信息。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

C 类型

@tab

意义

@item

@code{name}

@tab

@code{const char *}

@tab

结构序列类型的名称

@item

@code{doc}

@tab

@code{const char *}

@tab

指向要忽略类型的文档字符串或 @code{NULL} 的指针

@item

@code{fields}

@tab

@code{PyStructSequence_Field *}

@tab

指向以 @code{NULL} 结尾的数组的指针，其字段名称为新类型

@item

@code{n_in_sequence}

@tab

@code{int}

@tab

Python侧可见的字段数（如果用作元组）

@end multitable

@end deffn

@geindex PyStructSequence_Field (C 类型)
@anchor{c-api/tuple c PyStructSequence_Field}@anchor{534}
@deffn {C 类型} PyStructSequence_Field

描述结构序列的一个字段。 当结构序列被建模为元组时，所有字段的类型都是 @ref{5bd,,PyObject*}。 在 @ref{535,,PyStructSequence_Desc} 的 @code{fields} 数组中的索引确定了结构序列描述的是哪个字段。


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

C 类型

@tab

意义

@item

@code{name}

@tab

@code{const char *}

@tab

字段的名称或 @code{NULL} ，若要结束命名字段的列表，请设置为 @ref{263,,PyStructSequence_UnnamedField} 以保留未命名字段

@item

@code{doc}

@tab

@code{const char *}

@tab

要忽略的字段文档字符串或 @code{NULL}

@end multitable

@end deffn

@geindex PyStructSequence_UnnamedField (C 变量)
@anchor{c-api/tuple c PyStructSequence_UnnamedField}@anchor{263}
@deffn {C 变量} const char * const PyStructSequence_UnnamedField

字段名的特殊值将保持未命名状态。


在 3.9 版更改: 这个类型已从 @code{char *} 更改。

@end deffn

@geindex PyStructSequence_New (C 函数)
@anchor{c-api/tuple c PyStructSequence_New}@anchor{4095}
@deffn {C 函数} PyObject* PyStructSequence_New (PyTypeObject@w{ }*type)
@emph{Return value: New reference.}
创建 @emph{type} 的实例，该实例必须使用 @ref{fe9,,PyStructSequence_NewType()} 创建。
@end deffn

@geindex PyStructSequence_GetItem (C 函数)
@anchor{c-api/tuple c PyStructSequence_GetItem}@anchor{4096}
@deffn {C 函数} PyObject* PyStructSequence_GetItem (PyObject@w{ }*p, Py_ssize_t@w{ }pos)
@emph{Return value: Borrowed reference.}
返回 @emph{p} 所指向的结构序列中，位于 @emph{pos} 处的对象。不需要进行边界检查。
@end deffn

@geindex PyStructSequence_GET_ITEM (C 函数)
@anchor{c-api/tuple c PyStructSequence_GET_ITEM}@anchor{4097}
@deffn {C 函数} PyObject* PyStructSequence_GET_ITEM (PyObject@w{ }*p, Py_ssize_t@w{ }pos)
@emph{Return value: Borrowed reference.}
@ref{4096,,PyStructSequence_GetItem()} 的宏版本。
@end deffn

@geindex PyStructSequence_SetItem (C 函数)
@anchor{c-api/tuple c PyStructSequence_SetItem}@anchor{4098}
@deffn {C 函数} void PyStructSequence_SetItem (PyObject@w{ }*p, Py_ssize_t@w{ }pos, PyObject@w{ }*o)

将结构序列 @emph{p} 的索引 @emph{pos} 处的字段设置为值 @emph{o}。 与 @ref{4093,,PyTuple_SET_ITEM()} 一样，它应该只用于填充全新的实例。

@cartouche
@quotation 注解 
这个函数“窃取”了指向 @emph{o} 的一个引用。
@end quotation
@end cartouche
@end deffn

@geindex PyStructSequence_SET_ITEM (C 函数)
@anchor{c-api/tuple c PyStructSequence_SET_ITEM}@anchor{4099}
@deffn {C 函数} void PyStructSequence_SET_ITEM (PyObject@w{ }*p, Py_ssize_t@w{ }*pos, PyObject@w{ }*o)

@ref{4098,,PyStructSequence_SetItem()} 的宏版本。

@cartouche
@quotation 注解 
这个函数“窃取”了指向 @emph{o} 的一个引用。
@end quotation
@end cartouche
@end deffn

@node 列表对象,,结构序列对象,序列对象
@anchor{c-api/list doc}@anchor{409a}@anchor{c-api/list list-objects}@anchor{409b}@anchor{c-api/list listobjects}@anchor{409c}
@subsubsection 列表对象


@geindex 对象; list

@geindex PyListObject (C 类型)
@anchor{c-api/list c PyListObject}@anchor{3f5f}
@deffn {C 类型} PyListObject

这个C类型 @ref{5bd,,PyObject} 的子类型代表一个Python列表对象。
@end deffn

@geindex PyList_Type (C 变量)
@anchor{c-api/list c PyList_Type}@anchor{3da4}
@deffn {C 变量} PyTypeObject PyList_Type

这是个属于 @ref{3fe,,PyTypeObject} 的代表Python列表类型的实例。在Python层面和类型 @ref{1f9,,list} 是同一个对象。
@end deffn

@geindex PyList_Check (C 函数)
@anchor{c-api/list c PyList_Check}@anchor{409d}
@deffn {C 函数} int PyList_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 list 对象或者 list 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyList_CheckExact (C 函数)
@anchor{c-api/list c PyList_CheckExact}@anchor{409e}
@deffn {C 函数} int PyList_CheckExact (PyObject@w{ }*p)

如果 @emph{p} 是一个 list 对象但不是 list 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyList_New (C 函数)
@anchor{c-api/list c PyList_New}@anchor{3e03}
@deffn {C 函数} PyObject* PyList_New (Py_ssize_t@w{ }len)
@emph{Return value: New reference.}
成功时返回一个长度为 @emph{len} 的新列表，失败时返回 @code{NULL}。

@cartouche
@quotation 注解 
当 @emph{len} 大于零时，被返回的列表对象项目被设成 @code{NULL}。因此你不能用类似C函数 @ref{11cd,,PySequence_SetItem()} 的抽象API或者用C函数 @ref{3d79,,PyList_SetItem()} 将所有项目设置成真实对象前对Python代码公开这个对象。
@end quotation
@end cartouche
@end deffn

@geindex PyList_Size (C 函数)
@anchor{c-api/list c PyList_Size}@anchor{e4b}
@deffn {C 函数} Py_ssize_t PyList_Size (PyObject@w{ }*list)

@geindex 內置函数; len

返回 @emph{list} 中列表对象的长度；这等于在列表对象调用 @code{len(list)} 。
@end deffn

@geindex PyList_GET_SIZE (C 函数)
@anchor{c-api/list c PyList_GET_SIZE}@anchor{409f}
@deffn {C 函数} Py_ssize_t PyList_GET_SIZE (PyObject@w{ }*list)

宏版本的C函数 @ref{e4b,,PyList_Size()} ，没有错误检测。
@end deffn

@geindex PyList_GetItem (C 函数)
@anchor{c-api/list c PyList_GetItem}@anchor{3d74}
@deffn {C 函数} PyObject* PyList_GetItem (PyObject@w{ }*list, Py_ssize_t@w{ }index)
@emph{Return value: Borrowed reference.}
返回 @emph{list} 所指向列表中 @emph{index} 位置上的对象。 位置值必须为非负数；不支持从列表末尾进行索引。 如果 @emph{index} 超出边界 (<0 or >=len(list))，则返回 @code{NULL} 并设置 @ref{f3d,,IndexError} 异常。
@end deffn

@geindex PyList_GET_ITEM (C 函数)
@anchor{c-api/list c PyList_GET_ITEM}@anchor{40a0}
@deffn {C 函数} PyObject* PyList_GET_ITEM (PyObject@w{ }*list, Py_ssize_t@w{ }i)
@emph{Return value: Borrowed reference.}
宏版本的C函数 @ref{3d74,,PyList_GetItem()} ，没有错误检测。
@end deffn

@geindex PyList_SetItem (C 函数)
@anchor{c-api/list c PyList_SetItem}@anchor{3d79}
@deffn {C 函数} int PyList_SetItem (PyObject@w{ }*list, Py_ssize_t@w{ }index, PyObject@w{ }*item)

将列表中索引为 @emph{index} 的项设为 @emph{item}。 成功时返回 @code{0}。 如果 @emph{index} 超出范围则返回 @code{-1} 并设定 @ref{f3d,,IndexError} 异常。

@cartouche
@quotation 注解 
此函数会“偷走”一个对 @emph{item} 的引用并丢弃一个对列表中受影响位置上的已有条目的引用。
@end quotation
@end cartouche
@end deffn

@geindex PyList_SET_ITEM (C 函数)
@anchor{c-api/list c PyList_SET_ITEM}@anchor{40a1}
@deffn {C 函数} void PyList_SET_ITEM (PyObject@w{ }*list, Py_ssize_t@w{ }i, PyObject@w{ }*o)

不带错误检测的宏版本 @ref{3d79,,PyList_SetItem()}。 这通常只被用于新列表中之前没有内容的位置进行填充。

@cartouche
@quotation 注解 
该宏会“偷走”一个对 @emph{item} 的引用，但与 @ref{3d79,,PyList_SetItem()} 不同的是它 @emph{不会} 丢弃对任何被替换条目的引用；在 @emph{list} 的 @emph{i} 位置上的任何引用都将被泄露。
@end quotation
@end cartouche
@end deffn

@geindex PyList_Insert (C 函数)
@anchor{c-api/list c PyList_Insert}@anchor{40a2}
@deffn {C 函数} int PyList_Insert (PyObject@w{ }*list, Py_ssize_t@w{ }index, PyObject@w{ }*item)

将条目 @emph{item} 插入到列表 @emph{list} 索引号 @emph{index} 之前的位置。 如果成功将返回 @code{0}；如果不成功则返回 @code{-1} 并设置一个异常。 相当于 @code{list.insert(index, item)}。
@end deffn

@geindex PyList_Append (C 函数)
@anchor{c-api/list c PyList_Append}@anchor{40a3}
@deffn {C 函数} int PyList_Append (PyObject@w{ }*list, PyObject@w{ }*item)

将对象 @emph{item} 添加到列表 @emph{list} 的末尾。 如果成功将返回 @code{0}；如果不成功则返回 @code{-1} 并设置一个异常。 相当于 @code{list.append(item)}。
@end deffn

@geindex PyList_GetSlice (C 函数)
@anchor{c-api/list c PyList_GetSlice}@anchor{40a4}
@deffn {C 函数} PyObject* PyList_GetSlice (PyObject@w{ }*list, Py_ssize_t@w{ }low, Py_ssize_t@w{ }high)
@emph{Return value: New reference.}
返回一个对象列表，包含 @emph{list} 当中位于 @emph{low} 和 @emph{high} @emph{之间} 的对象。 如果不成功则返回 @code{NULL} 并设置异常。 相当于 @code{list[low:high]}。 不支持从列表末尾进行索引。
@end deffn

@geindex PyList_SetSlice (C 函数)
@anchor{c-api/list c PyList_SetSlice}@anchor{40a5}
@deffn {C 函数} int PyList_SetSlice (PyObject@w{ }*list, Py_ssize_t@w{ }low, Py_ssize_t@w{ }high, PyObject@w{ }*itemlist)

将 @emph{list} 当中 @emph{low} 与 @emph{high} 之间的切片设为 @emph{itemlist} 的内容。 相当于 @code{list[low:high] = itemlist}。 @emph{itemlist} 可以为 @code{NULL}，表示赋值为一个空列表（删除切片）。 成功时返回 @code{0}，失败时返回 @code{-1}。 这里不支持从列表末尾进行索引。
@end deffn

@geindex PyList_Sort (C 函数)
@anchor{c-api/list c PyList_Sort}@anchor{40a6}
@deffn {C 函数} int PyList_Sort (PyObject@w{ }*list)

对 @emph{list} 中的条目进行原地排序。 成功时返回 @code{0}，失败时返回 @code{-1}。 这等价于 @code{list.sort()}。
@end deffn

@geindex PyList_Reverse (C 函数)
@anchor{c-api/list c PyList_Reverse}@anchor{40a7}
@deffn {C 函数} int PyList_Reverse (PyObject@w{ }*list)

对 @emph{list} 中的条目进行原地反转。 成功时返回 @code{0}，失败时返回 @code{-1}。 这等价于 @code{list.reverse()}。
@end deffn

@geindex PyList_AsTuple (C 函数)
@anchor{c-api/list c PyList_AsTuple}@anchor{40a8}
@deffn {C 函数} PyObject* PyList_AsTuple (PyObject@w{ }*list)
@emph{Return value: New reference.}
@geindex 內置函数; tuple

返回一个新的元组对象，其中包含 @emph{list} 的内容；等价于 @code{tuple(list)}。
@end deffn

@node 容器对象,函数对象,序列对象,具体的对象层
@anchor{c-api/concrete container-objects}@anchor{40a9}@anchor{c-api/concrete mapobjects}@anchor{40aa}
@subsection 容器对象


@geindex 对象; mapping

@menu
* 字典对象:: 
* 集合对象:: 

@end menu

@node 字典对象,集合对象,,容器对象
@anchor{c-api/dict doc}@anchor{40ab}@anchor{c-api/dict dictionary-objects}@anchor{40ac}@anchor{c-api/dict dictobjects}@anchor{40ad}
@subsubsection 字典对象


@geindex 对象; dictionary

@geindex PyDictObject (C 类型)
@anchor{c-api/dict c PyDictObject}@anchor{40ae}
@deffn {C 类型} PyDictObject

这个 @ref{5bd,,PyObject} 的子类型代表一个Python字典对象。
@end deffn

@geindex PyDict_Type (C 变量)
@anchor{c-api/dict c PyDict_Type}@anchor{40af}
@deffn {C 变量} PyTypeObject PyDict_Type

Python字典类型表示为 @ref{3fe,,PyTypeObject} 的实例。这与Python层面的 @ref{164,,dict} 是相同的对象。
@end deffn

@geindex PyDict_Check (C 函数)
@anchor{c-api/dict c PyDict_Check}@anchor{3fb0}
@deffn {C 函数} int PyDict_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 dict 对象或者 dict 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyDict_CheckExact (C 函数)
@anchor{c-api/dict c PyDict_CheckExact}@anchor{40b0}
@deffn {C 函数} int PyDict_CheckExact (PyObject@w{ }*p)

如果 @emph{p} 是一个 dict 对象但不是 dict 类型的子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyDict_New (C 函数)
@anchor{c-api/dict c PyDict_New}@anchor{40b1}
@deffn {C 函数} PyObject* PyDict_New ()
@emph{Return value: New reference.}
返回一个新的空字典，失败时返回 @code{NULL}。
@end deffn

@geindex PyDictProxy_New (C 函数)
@anchor{c-api/dict c PyDictProxy_New}@anchor{40b2}
@deffn {C 函数} PyObject* PyDictProxy_New (PyObject@w{ }*mapping)
@emph{Return value: New reference.}
返回 @ref{b97,,types.MappingProxyType} 对象，用于强制执行只读行为的映射。这通常用于创建视图以防止修改非动态类类型的字典。
@end deffn

@geindex PyDict_Clear (C 函数)
@anchor{c-api/dict c PyDict_Clear}@anchor{40b3}
@deffn {C 函数} void PyDict_Clear (PyObject@w{ }*p)

清空现有字典的所有键值对。
@end deffn

@geindex PyDict_Contains (C 函数)
@anchor{c-api/dict c PyDict_Contains}@anchor{40b4}
@deffn {C 函数} int PyDict_Contains (PyObject@w{ }*p, PyObject@w{ }*key)

确定 @emph{key} 是否包含在字典 @emph{p} 中。如果 @emph{key} 匹配上 @emph{p} 的某一项，则返回 @code{1} ，否则返回 @code{0} 。返回 @code{-1} 表示出错。这等同于Python表达式 @code{key in p} 。
@end deffn

@geindex PyDict_Copy (C 函数)
@anchor{c-api/dict c PyDict_Copy}@anchor{40b5}
@deffn {C 函数} PyObject* PyDict_Copy (PyObject@w{ }*p)
@emph{Return value: New reference.}
返回与 @emph{p} 包含相同键值对的新字典。
@end deffn

@geindex PyDict_SetItem (C 函数)
@anchor{c-api/dict c PyDict_SetItem}@anchor{3d7a}
@deffn {C 函数} int PyDict_SetItem (PyObject@w{ }*p, PyObject@w{ }*key, PyObject@w{ }*val)

使用 @emph{key} 作为键将 @emph{val} 插入字典 @emph{p}。 @emph{key} 必须为 @ref{277,,hashable}；如果不是，则将引发 @ref{1ff,,TypeError}。 成功时返回 @code{0}，失败时返回 @code{-1}。 此函数 @emph{不会} 附带对 @emph{val} 的引用。
@end deffn

@geindex PyDict_SetItemString (C 函数)
@anchor{c-api/dict c PyDict_SetItemString}@anchor{40b6}
@deffn {C 函数} int PyDict_SetItemString (PyObject@w{ }*p, const char@w{ }*key, PyObject@w{ }*val)

@geindex PyUnicode_FromString()

使用 @emph{key} 作为键将 @emph{val} 插入到字典 @emph{p}。 @emph{key} 应当为 @code{const char*}。 键对象是使用 @code{PyUnicode_FromString(key)} 创建的。 成功时返回 @code{0}，失败时返回 @code{-1}。 此函数 @emph{不会} 附带对 @emph{val} 的引用。
@end deffn

@geindex PyDict_DelItem (C 函数)
@anchor{c-api/dict c PyDict_DelItem}@anchor{40b7}
@deffn {C 函数} int PyDict_DelItem (PyObject@w{ }*p, PyObject@w{ }*key)

移除字典 @emph{p} 中键为 @emph{key} 的条目。 @emph{key} 必须是可哈希的；如果不是，则会引发 @ref{1ff,,TypeError}。 如果字典中没有 @emph{key}，则会引发 @ref{3f1,,KeyError}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyDict_DelItemString (C 函数)
@anchor{c-api/dict c PyDict_DelItemString}@anchor{40b8}
@deffn {C 函数} int PyDict_DelItemString (PyObject@w{ }*p, const char@w{ }*key)

移除字典 @emph{p} 中由字符串 @emph{key} 指定的键的条目。 如果字典中没有 @emph{key}，则会引发 @ref{3f1,,KeyError}。 成功时返回 @code{0}，失败时返回 @code{-1}。
@end deffn

@geindex PyDict_GetItem (C 函数)
@anchor{c-api/dict c PyDict_GetItem}@anchor{3d75}
@deffn {C 函数} PyObject* PyDict_GetItem (PyObject@w{ }*p, PyObject@w{ }*key)
@emph{Return value: Borrowed reference.}
从字典 @emph{p} 中返回以 @emph{key} 为键的对象。 如果键名 @emph{key} 不存在但 @emph{没有} 设置一个异常则返回 @code{NULL}。

需要注意的是，调用 @ref{455,,__hash__()} 和 @ref{454,,__eq__()} 方法产生的异常不会被抛出。改用 @ref{40b9,,PyDict_GetItemWithError()} 获得错误报告。
@end deffn

@geindex PyDict_GetItemWithError (C 函数)
@anchor{c-api/dict c PyDict_GetItemWithError}@anchor{40b9}
@deffn {C 函数} PyObject* PyDict_GetItemWithError (PyObject@w{ }*p, PyObject@w{ }*key)
@emph{Return value: Borrowed reference.}
@ref{3d75,,PyDict_GetItem()} 的变种，它不会屏蔽异常。 当异常发生时将返回 @code{NULL} @strong{并且} 设置一个异常。 如果键不存在则返回 @code{NULL} @strong{并且不会} 设置一个异常。
@end deffn

@geindex PyDict_GetItemString (C 函数)
@anchor{c-api/dict c PyDict_GetItemString}@anchor{3d76}
@deffn {C 函数} PyObject* PyDict_GetItemString (PyObject@w{ }*p, const char@w{ }*key)
@emph{Return value: Borrowed reference.}
这与 @ref{3d75,,PyDict_GetItem()} 一样，但是 @emph{key} 被指定为 @code{const char*}，而不是 @ref{5bd,,PyObject*}。

需要注意的是，调用 @ref{455,,__hash__()} 、 @ref{454,,__eq__()} 方法和创建一个临时的字符串对象时产生的异常不会被抛出。改用 @ref{40b9,,PyDict_GetItemWithError()} 获得错误报告。
@end deffn

@geindex PyDict_SetDefault (C 函数)
@anchor{c-api/dict c PyDict_SetDefault}@anchor{40ba}
@deffn {C 函数} PyObject* PyDict_SetDefault (PyObject@w{ }*p, PyObject@w{ }*key, PyObject@w{ }*defaultobj)
@emph{Return value: Borrowed reference.}
这跟Python层面的 @ref{aa7,,dict.setdefault()} 一样。如果键 @emph{key} 存在，它返回在字典 @emph{p} 里面对应的值。如果键不存在，它会和值 @emph{defaultobj} 一起插入并返回 @emph{defaultobj} 。这个函数只计算 @emph{key} 的哈希函数一次，而不是在查找和插入时分别计算它。


3.4 新版功能.

@end deffn

@geindex PyDict_Items (C 函数)
@anchor{c-api/dict c PyDict_Items}@anchor{40bb}
@deffn {C 函数} PyObject* PyDict_Items (PyObject@w{ }*p)
@emph{Return value: New reference.}
返回一个包含字典中所有键值项的 @ref{3f5f,,PyListObject}。
@end deffn

@geindex PyDict_Keys (C 函数)
@anchor{c-api/dict c PyDict_Keys}@anchor{40bc}
@deffn {C 函数} PyObject* PyDict_Keys (PyObject@w{ }*p)
@emph{Return value: New reference.}
返回一个包含字典中所有键(keys)的 @ref{3f5f,,PyListObject}。
@end deffn

@geindex PyDict_Values (C 函数)
@anchor{c-api/dict c PyDict_Values}@anchor{40bd}
@deffn {C 函数} PyObject* PyDict_Values (PyObject@w{ }*p)
@emph{Return value: New reference.}
返回一个包含字典中所有值(values)的 @ref{3f5f,,PyListObject}。
@end deffn

@geindex PyDict_Size (C 函数)
@anchor{c-api/dict c PyDict_Size}@anchor{40be}
@deffn {C 函数} Py_ssize_t PyDict_Size (PyObject@w{ }*p)

@geindex 內置函数; len

返回字典中项目数，等价于对字典 @emph{p} 使用 @code{len(p)}。
@end deffn

@geindex PyDict_Next (C 函数)
@anchor{c-api/dict c PyDict_Next}@anchor{40bf}
@deffn {C 函数} int PyDict_Next (PyObject@w{ }*p, Py_ssize_t@w{ }*ppos, PyObject@w{ }**pkey, PyObject@w{ }**pvalue)

迭代字典 @emph{p} 中的所有键值对。 在第一次调用此函数开始迭代之前，由 @emph{ppos} 所引用的 @ref{391,,Py_ssize_t} 必须被初始化为 @code{0}；该函数将为字典中的每个键值对返回真值，一旦所有键值对都报告完毕则返回假值。 形参 @emph{pkey} 和 @emph{pvalue} 应当指向 @ref{5bd,,PyObject*} 变量，它们将分别使用每个键和值来填充，或者也可以为 @code{NULL}。 通过它们返回的任何引用都是暂借的。 @emph{ppos} 在迭代期间不应被更改。 它的值表示内部字典结构中的偏移量，并且由于结构是稀疏的，因此偏移量并不连续。

例如:

@example
PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) @{
    /* do something interesting with the values... */
    ...
@}
@end example

字典 @emph{p} 不应该在遍历期间发生改变。在遍历字典时，改变键中的值是安全的，但仅限于键的集合不发生改变。例如:

@example
PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) @{
    long i = PyLong_AsLong(value);
    if (i == -1 && PyErr_Occurred()) @{
        return -1;
    @}
    PyObject *o = PyLong_FromLong(i + 1);
    if (o == NULL)
        return -1;
    if (PyDict_SetItem(self->dict, key, o) < 0) @{
        Py_DECREF(o);
        return -1;
    @}
    Py_DECREF(o);
@}
@end example
@end deffn

@geindex PyDict_Merge (C 函数)
@anchor{c-api/dict c PyDict_Merge}@anchor{40c0}
@deffn {C 函数} int PyDict_Merge (PyObject@w{ }*a, PyObject@w{ }*b, int@w{ }override)

对映射对象 @emph{b} 进行迭代，将键值对添加到字典 @emph{a}。 @emph{b} 可以是一个字典，或任何支持 @ref{538,,PyMapping_Keys()} 和 @ref{3e04,,PyObject_GetItem()} 的对象。 如果 @emph{override} 为真值，则如果在 @emph{b} 中找到相同的键则 @emph{a} 中已存在的相应键值对将被替换，否则如果在 @emph{a} 中没有相同的键则只是添加键值对。 当成功时返回 @code{0} 或者当引发异常时返回 @code{-1}。
@end deffn

@geindex PyDict_Update (C 函数)
@anchor{c-api/dict c PyDict_Update}@anchor{40c1}
@deffn {C 函数} int PyDict_Update (PyObject@w{ }*a, PyObject@w{ }*b)

这与 C 中的 @code{PyDict_Merge(a, b, 1)} 一样，也类似于 Python 中的 @code{a.update(b)}，差别在于 @ref{40c1,,PyDict_Update()} 在第二个参数没有 "keys" 属性时不会回退到迭代键值对的序列。 当成功时返回 @code{0} 或者当引发异常时返回 @code{-1}。
@end deffn

@geindex PyDict_MergeFromSeq2 (C 函数)
@anchor{c-api/dict c PyDict_MergeFromSeq2}@anchor{40c2}
@deffn {C 函数} int PyDict_MergeFromSeq2 (PyObject@w{ }*a, PyObject@w{ }*seq2, int@w{ }override)

将 @emph{seq2} 中的键值对更新或合并到字典 @emph{a}。 @emph{seq2} 必须为产生长度为 2 的用作键值对的元素的可迭代对象。 当存在重复的键时，如果 @emph{override} 真值则最后出现的键胜出。 当成功时返回 @code{0} 或者当引发异常时返回 @code{-1}。 等价的 Python 代码（返回值除外）:

@example
def PyDict_MergeFromSeq2(a, seq2, override):
    for key, value in seq2:
        if override or key not in a:
            a[key] = value
@end example
@end deffn

@node 集合对象,,字典对象,容器对象
@anchor{c-api/set doc}@anchor{40c3}@anchor{c-api/set set-objects}@anchor{40c4}@anchor{c-api/set setobjects}@anchor{40c5}
@subsubsection 集合对象


@geindex 对象; set
@geindex 对象; frozenset

这一节详细介绍了针对 @ref{1f7,,set} 和 @ref{1f8,,frozenset} 对象的公共 API。 任何未在下面列出的功能最好是使用抽象对象协议 (包括 @ref{3f23,,PyObject_CallMethod()}, @ref{10e5,,PyObject_RichCompareBool()}, @ref{3f09,,PyObject_Hash()}, @ref{a52,,PyObject_Repr()}, @ref{3f0a,,PyObject_IsTrue()}, @ref{11ca,,PyObject_Print()} 以及 @ref{3f11,,PyObject_GetIter()}) 或者抽象数字协议 (包括 @ref{3f3c,,PyNumber_And()}, @ref{3f2f,,PyNumber_Subtract()}, @ref{3f3e,,PyNumber_Or()}, @ref{3f3d,,PyNumber_Xor()}, @ref{3f48,,PyNumber_InPlaceAnd()}, @ref{3f40,,PyNumber_InPlaceSubtract()}, @ref{3f4a,,PyNumber_InPlaceOr()} 以及 @ref{3f49,,PyNumber_InPlaceXor()})。

@geindex PySetObject (C 类型)
@anchor{c-api/set c PySetObject}@anchor{40c6}
@deffn {C 类型} PySetObject

这个 @ref{5bd,,PyObject} 的子类型被用来保存 @ref{1f7,,set} 和 @ref{1f8,,frozenset} 对象的内部数据。 它类似于 @ref{40ae,,PyDictObject} 的地方在于对小尺寸集合来说它是固定大小的（很像元组的存储方式），而对于中等和大尺寸集合来说它将指向单独的可变大小的内存块（很像列表的存储方式）。 此结构体的字段不应被视为公有并且可能发生改变。 所有访问都应当通过已写入文档的 API 来进行而不可通过直接操纵结构体中的值。
@end deffn

@geindex PySet_Type (C 变量)
@anchor{c-api/set c PySet_Type}@anchor{40c7}
@deffn {C 变量} PyTypeObject PySet_Type

这是一个 @ref{3fe,,PyTypeObject} 实例，表示 Python @ref{1f7,,set} 类型。
@end deffn

@geindex PyFrozenSet_Type (C 变量)
@anchor{c-api/set c PyFrozenSet_Type}@anchor{40c8}
@deffn {C 变量} PyTypeObject PyFrozenSet_Type

这是一个 @ref{3fe,,PyTypeObject} 实例，表示 Python @ref{1f8,,frozenset} 类型。
@end deffn

下列类型检查宏适用于指向任意 Python 对象的指针。 类似地，这些构造函数也适用于任意可迭代的 Python 对象。

@geindex PySet_Check (C 函数)
@anchor{c-api/set c PySet_Check}@anchor{40c9}
@deffn {C 函数} int PySet_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 @ref{1f7,,set} 对象或者是其子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyFrozenSet_Check (C 函数)
@anchor{c-api/set c PyFrozenSet_Check}@anchor{40ca}
@deffn {C 函数} int PyFrozenSet_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 @ref{1f8,,frozenset} 对象或者是其子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyAnySet_Check (C 函数)
@anchor{c-api/set c PyAnySet_Check}@anchor{40cb}
@deffn {C 函数} int PyAnySet_Check (PyObject@w{ }*p)

如果 @emph{p} 是一个 @ref{1f7,,set} 对象、@ref{1f8,,frozenset} 对象或者是其子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyAnySet_CheckExact (C 函数)
@anchor{c-api/set c PyAnySet_CheckExact}@anchor{40cc}
@deffn {C 函数} int PyAnySet_CheckExact (PyObject@w{ }*p)

如果 @emph{p} 是一个 @ref{1f7,,set} 或 @ref{1f8,,frozenset} 对象但不是其子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyFrozenSet_CheckExact (C 函数)
@anchor{c-api/set c PyFrozenSet_CheckExact}@anchor{40cd}
@deffn {C 函数} int PyFrozenSet_CheckExact (PyObject@w{ }*p)

如果 @emph{p} 是一个 @ref{1f8,,frozenset} 对象但不是其子类型的实例则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PySet_New (C 函数)
@anchor{c-api/set c PySet_New}@anchor{e78}
@deffn {C 函数} PyObject* PySet_New (PyObject@w{ }*iterable)
@emph{Return value: New reference.}
返回一个新的 @ref{1f7,,set}，其中包含 @emph{iterable} 所返回的对象。 @emph{iterable} 可以为 @code{NULL} 表示创建一个新的空集合。 成功时返回新的集合，失败时返回 @code{NULL}。 如果 @emph{iterable} 实际上不是可迭代对象则引发 @ref{1ff,,TypeError}。 该构造器也适用于拷贝集合 (@code{c=set(s)})。
@end deffn

@geindex PyFrozenSet_New (C 函数)
@anchor{c-api/set c PyFrozenSet_New}@anchor{e79}
@deffn {C 函数} PyObject* PyFrozenSet_New (PyObject@w{ }*iterable)
@emph{Return value: New reference.}
返回一个新的 @ref{1f8,,frozenset}，其中包含 @emph{iterable} 所返回的对象。 @emph{iterable} 可以为 @code{NULL} 表示创建一个新的空冻结集合。 成功时返回新的冻结集合，失败时返回 @code{NULL}。 如果 @emph{iterable} 实际上不是可迭代对象则引发 @ref{1ff,,TypeError}。
@end deffn

下列函数和宏适用于 @ref{1f7,,set} 或 @ref{1f8,,frozenset} 的实例或是其子类型的实例。

@geindex PySet_Size (C 函数)
@anchor{c-api/set c PySet_Size}@anchor{e7d}
@deffn {C 函数} Py_ssize_t PySet_Size (PyObject@w{ }*anyset)

@geindex 內置函数; len

返回 @ref{1f7,,set} 或 @ref{1f8,,frozenset} 对象的长度。 等价于 @code{len(anyset)}。 如果 @emph{anyset} 不是 @ref{1f7,,set}, @ref{1f8,,frozenset} 或其子类型的实例则会引发 @code{PyExc_SystemError}。
@end deffn

@geindex PySet_GET_SIZE (C 函数)
@anchor{c-api/set c PySet_GET_SIZE}@anchor{40ce}
@deffn {C 函数} Py_ssize_t PySet_GET_SIZE (PyObject@w{ }*anyset)

宏版本的 @ref{e7d,,PySet_Size()}，不带错误检测。
@end deffn

@geindex PySet_Contains (C 函数)
@anchor{c-api/set c PySet_Contains}@anchor{e7c}
@deffn {C 函数} int PySet_Contains (PyObject@w{ }*anyset, PyObject@w{ }*key)

如果找到返回 @code{1}，如果未找到返回 @code{0}，如果遇到错误则返回 @code{-1}。 不同于 Python @ref{df6,,__contains__()} 方法，此函数不会自动将不可哈希的集合转换为临时的冻结集合。 如果 @emph{key} 为不可哈希对象则会引发 @ref{1ff,,TypeError}。 如果 @emph{anyset} 不是 @ref{1f7,,set}, @ref{1f8,,frozenset} 或其子类型的实例则会引发 @code{PyExc_SystemError}。
@end deffn

@geindex PySet_Add (C 函数)
@anchor{c-api/set c PySet_Add}@anchor{e7a}
@deffn {C 函数} int PySet_Add (PyObject@w{ }*set, PyObject@w{ }*key)

添加 @emph{key} 到一个 @ref{1f7,,set} 实例。 也可用于 @ref{1f8,,frozenset} 实例（与 @ref{3d78,,PyTuple_SetItem()} 的类似之处是它也可被用来为全新的冻结集合在公开给其他代码之前填充全新的值）。 成功时返回 @code{0} 而失败时返回 @code{-1}。 如果 @emph{key} 为不可哈希对象则会引发 @ref{1ff,,TypeError}。 如果没有增长空间则会引发 @ref{fb5,,MemoryError}。 如果 @emph{set} 不是 @ref{1f7,,set} 或其子类型的实例则会引发 @ref{6fc,,SystemError}。
@end deffn

下列函数适用于 @ref{1f7,,set} 或其子类型的实例，但不可用于 @ref{1f8,,frozenset} 或其子类型的实例。

@geindex PySet_Discard (C 函数)
@anchor{c-api/set c PySet_Discard}@anchor{e7b}
@deffn {C 函数} int PySet_Discard (PyObject@w{ }*set, PyObject@w{ }*key)

如果找到并移除返回 @code{1}，如果未找到（无操作）返回 @code{0}，如果遇到错误则返回 @code{-1}。 对于不存在的键不会引发 @ref{3f1,,KeyError}。 如果 @emph{key} 为不可哈希对象则会引发 @ref{1ff,,TypeError}。 不同于 Python @code{discard()} 方法，此函数不会自动将不可哈希的集合转换为临时的冻结集合。 如果 @emph{set} 不是 @ref{1f7,,set} 或其子类型的实例则会引发 @code{PyExc_SystemError}。
@end deffn

@geindex PySet_Pop (C 函数)
@anchor{c-api/set c PySet_Pop}@anchor{40cf}
@deffn {C 函数} PyObject* PySet_Pop (PyObject@w{ }*set)
@emph{Return value: New reference.}
返回 @emph{set} 中任意对象的新引用，并从 @emph{set} 中移除该对象。 失败时返回 @code{NULL}。 如果集合为空则会引发 @ref{3f1,,KeyError}。 如果 @emph{set} 不是 @ref{1f7,,set} 或其子类型的实例则会引发 @ref{6fc,,SystemError}。
@end deffn

@geindex PySet_Clear (C 函数)
@anchor{c-api/set c PySet_Clear}@anchor{40d0}
@deffn {C 函数} int PySet_Clear (PyObject@w{ }*set)

清空现有字典的所有键值对。
@end deffn

@node 函数对象,其他对象<2>,容器对象,具体的对象层
@anchor{c-api/concrete function-objects}@anchor{40d1}@anchor{c-api/concrete otherobjects}@anchor{40d2}
@subsection 函数对象


@menu
* 函数对象: 函数对象<2>. 
* 实例方法对象:: 
* 方法对象: 方法对象<2>. 
* Cell 对象:: 
* 代码对象: 代码对象<2>. 

@end menu

@node 函数对象<2>,实例方法对象,,函数对象
@anchor{c-api/function doc}@anchor{40d3}@anchor{c-api/function function-objects}@anchor{40d4}@anchor{c-api/function id1}@anchor{40d5}
@subsubsection 函数对象


@geindex 对象; function

有一些特定于 Python 函数的函数。

@geindex PyFunctionObject (C 类型)
@anchor{c-api/function c PyFunctionObject}@anchor{40d6}
@deffn {C 类型} PyFunctionObject

用于函数的 C 结构体。
@end deffn

@geindex PyFunction_Type (C 变量)
@anchor{c-api/function c PyFunction_Type}@anchor{40d7}
@deffn {C 变量} PyTypeObject PyFunction_Type

@geindex MethodType (in module types)

这是一个 @ref{3fe,,PyTypeObject} 实例并表示 Python 函数类型。 它作为 @code{types.FunctionType} 向 Python 程序员公开。
@end deffn

@geindex PyFunction_Check (C 函数)
@anchor{c-api/function c PyFunction_Check}@anchor{40d8}
@deffn {C 函数} int PyFunction_Check (PyObject@w{ }*o)

如果 @emph{o} 是一个函数对象 (类型为 @ref{40d7,,PyFunction_Type}) 则返回真值。 形参必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyFunction_New (C 函数)
@anchor{c-api/function c PyFunction_New}@anchor{40d9}
@deffn {C 函数} PyObject* PyFunction_New (PyObject@w{ }*code, PyObject@w{ }*globals)
@emph{Return value: New reference.}
返回与代码对象 @emph{code} 关联的新函数对象。 @emph{globals} 必须是一个字典，该函数可以访问全局变量。

从代码对象中提取函数的文档字符串和名称。 @emph{__module__} 会从 @emph{globals} 中提取。 参数 defaults, annotations 和 closure 设为 @code{NULL}。 @emph{__qualname__} 设为与函数名称相同的值。
@end deffn

@geindex PyFunction_NewWithQualName (C 函数)
@anchor{c-api/function c PyFunction_NewWithQualName}@anchor{40da}
@deffn {C 函数} PyObject* PyFunction_NewWithQualName (PyObject@w{ }*code, PyObject@w{ }*globals, PyObject@w{ }*qualname)
@emph{Return value: New reference.}
类似 @ref{40d9,,PyFunction_New()}，但还允许设置函数对象的 @code{__qualname__} 属性。 @emph{qualname} 应当是 unicode 对象或 @code{NULL}；如果是 @code{NULL} 则 @code{__qualname__} 属性设为与其 @code{__name__} 属性相同的值。


3.3 新版功能.

@end deffn

@geindex PyFunction_GetCode (C 函数)
@anchor{c-api/function c PyFunction_GetCode}@anchor{40db}
@deffn {C 函数} PyObject* PyFunction_GetCode (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回与函数对象 @emph{op} 关联的代码对象。
@end deffn

@geindex PyFunction_GetGlobals (C 函数)
@anchor{c-api/function c PyFunction_GetGlobals}@anchor{40dc}
@deffn {C 函数} PyObject* PyFunction_GetGlobals (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回与函数对象*op*相关联的全局字典。
@end deffn

@geindex PyFunction_GetModule (C 函数)
@anchor{c-api/function c PyFunction_GetModule}@anchor{40dd}
@deffn {C 函数} PyObject* PyFunction_GetModule (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回函数对象 @emph{op} 的 @emph{__module__} 属性，通常为一个包含了模块名称的字符串，但可以通过 Python 代码设为返回其他任意对象。
@end deffn

@geindex PyFunction_GetDefaults (C 函数)
@anchor{c-api/function c PyFunction_GetDefaults}@anchor{40de}
@deffn {C 函数} PyObject* PyFunction_GetDefaults (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回函数对象 @emph{op} 的参数默认值。 这可以是一个参数元组或 @code{NULL}。
@end deffn

@geindex PyFunction_SetDefaults (C 函数)
@anchor{c-api/function c PyFunction_SetDefaults}@anchor{40df}
@deffn {C 函数} int PyFunction_SetDefaults (PyObject@w{ }*op, PyObject@w{ }*defaults)

为函数对象 @emph{op} 设置参数默认值。 @emph{defaults} 必须为 @code{Py_None} 或一个元组。

失败时引发 @ref{6fc,,SystemError} 异常并返回 @code{-1} 。
@end deffn

@geindex PyFunction_GetClosure (C 函数)
@anchor{c-api/function c PyFunction_GetClosure}@anchor{40e0}
@deffn {C 函数} PyObject* PyFunction_GetClosure (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回关联到函数对象 @emph{op} 的闭包。 这可以是 @code{NULL} 或 cell 对象的元组。
@end deffn

@geindex PyFunction_SetClosure (C 函数)
@anchor{c-api/function c PyFunction_SetClosure}@anchor{40e1}
@deffn {C 函数} int PyFunction_SetClosure (PyObject@w{ }*op, PyObject@w{ }*closure)

设置关联到函数对象 @emph{op} 的闭包。 @emph{closure} 必须为 @code{Py_None} 或 cell 对象的元组。

失败时引发 @ref{6fc,,SystemError} 异常并返回 @code{-1} 。
@end deffn

@geindex PyFunction_GetAnnotations (C 函数)
@anchor{c-api/function c PyFunction_GetAnnotations}@anchor{40e2}
@deffn {C 函数} PyObject *PyFunction_GetAnnotations (PyObject@w{ }*op)
@emph{Return value: Borrowed reference.}
返回函数对象 @emph{op} 的标注。 这可以是一个可变字典或 @code{NULL}。
@end deffn

@geindex PyFunction_SetAnnotations (C 函数)
@anchor{c-api/function c PyFunction_SetAnnotations}@anchor{40e3}
@deffn {C 函数} int PyFunction_SetAnnotations (PyObject@w{ }*op, PyObject@w{ }*annotations)

设置函数对象 @emph{op} 的标注。 @emph{annotations} 必须为一个字典或 @code{Py_None}。

失败时引发 @ref{6fc,,SystemError} 异常并返回 @code{-1} 。
@end deffn

@node 实例方法对象,方法对象<2>,函数对象<2>,函数对象
@anchor{c-api/method doc}@anchor{40e4}@anchor{c-api/method instance-method-objects}@anchor{40e5}@anchor{c-api/method instancemethod-objects}@anchor{40e6}
@subsubsection 实例方法对象


@geindex 对象; instancemethod

实例方法是 @ref{ea7,,PyCFunction} 的包装器，也是将 @ref{ea7,,PyCFunction} 绑定到类对象的一种新方式。 它替代了原先的调用 @code{PyMethod_New(func, NULL, class)}。

@geindex PyInstanceMethod_Type (C 变量)
@anchor{c-api/method c PyInstanceMethod_Type}@anchor{40e7}
@deffn {C 变量} PyTypeObject PyInstanceMethod_Type

这个 @ref{3fe,,PyTypeObject} 实例代表 Python 实例方法类型。 它并不对 Python 程序公开。
@end deffn

@geindex PyInstanceMethod_Check (C 函数)
@anchor{c-api/method c PyInstanceMethod_Check}@anchor{40e8}
@deffn {C 函数} int PyInstanceMethod_Check (PyObject@w{ }*o)

如果 @emph{o} 是一个实例方法对象 (类型为 @ref{40e7,,PyInstanceMethod_Type}) 则返回真值。 形参必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyInstanceMethod_New (C 函数)
@anchor{c-api/method c PyInstanceMethod_New}@anchor{40e9}
@deffn {C 函数} PyObject* PyInstanceMethod_New (PyObject@w{ }*func)
@emph{Return value: New reference.}
返回一个新的实例方法对象，@emph{func} 应为任意可调用对象。 @emph{func} 将在实例方法被调用时作为函数被调用。
@end deffn

@geindex PyInstanceMethod_Function (C 函数)
@anchor{c-api/method c PyInstanceMethod_Function}@anchor{40ea}
@deffn {C 函数} PyObject* PyInstanceMethod_Function (PyObject@w{ }*im)
@emph{Return value: Borrowed reference.}
返回关联到实例方法 @emph{im} 的函数对象。
@end deffn

@geindex PyInstanceMethod_GET_FUNCTION (C 函数)
@anchor{c-api/method c PyInstanceMethod_GET_FUNCTION}@anchor{40eb}
@deffn {C 函数} PyObject* PyInstanceMethod_GET_FUNCTION (PyObject@w{ }*im)
@emph{Return value: Borrowed reference.}
宏版本的 @ref{40ea,,PyInstanceMethod_Function()}，略去了错误检测。
@end deffn

@node 方法对象<2>,Cell 对象,实例方法对象,函数对象
@anchor{c-api/method id1}@anchor{40ec}@anchor{c-api/method method-objects}@anchor{40ed}
@subsubsection 方法对象


@geindex 对象; method

方法是绑定的函数对象。 方法总是会被绑定到一个用户自定义类的实例。 未绑定方法（绑定到一个类的方法）已不再可用。

@geindex PyMethod_Type (C 变量)
@anchor{c-api/method c PyMethod_Type}@anchor{40ee}
@deffn {C 变量} PyTypeObject PyMethod_Type

@geindex MethodType (in module types)

这个 @ref{3fe,,PyTypeObject} 实例代表 Python 方法类型。 它作为 @code{types.MethodType} 向 Python 程序公开。
@end deffn

@geindex PyMethod_Check (C 函数)
@anchor{c-api/method c PyMethod_Check}@anchor{40ef}
@deffn {C 函数} int PyMethod_Check (PyObject@w{ }*o)

如果 @emph{o} 是一个方法对象 (类型为 @ref{40ee,,PyMethod_Type}) 则返回真值。 形参必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyMethod_New (C 函数)
@anchor{c-api/method c PyMethod_New}@anchor{40f0}
@deffn {C 函数} PyObject* PyMethod_New (PyObject@w{ }*func, PyObject@w{ }*self)
@emph{Return value: New reference.}
返回一个新的方法对象，@emph{func} 应为任意可调用对象，@emph{self} 为该方法应绑定的实例。 在方法被调用时 @emph{func} 将作为函数被调用。 @emph{self} 必须不为 @code{NULL}。
@end deffn

@geindex PyMethod_Function (C 函数)
@anchor{c-api/method c PyMethod_Function}@anchor{40f1}
@deffn {C 函数} PyObject* PyMethod_Function (PyObject@w{ }*meth)
@emph{Return value: Borrowed reference.}
返回关联到方法 @emph{meth} 的函数对象。
@end deffn

@geindex PyMethod_GET_FUNCTION (C 函数)
@anchor{c-api/method c PyMethod_GET_FUNCTION}@anchor{40f2}
@deffn {C 函数} PyObject* PyMethod_GET_FUNCTION (PyObject@w{ }*meth)
@emph{Return value: Borrowed reference.}
宏版本的 @ref{40f1,,PyMethod_Function()}，略去了错误检测。
@end deffn

@geindex PyMethod_Self (C 函数)
@anchor{c-api/method c PyMethod_Self}@anchor{40f3}
@deffn {C 函数} PyObject* PyMethod_Self (PyObject@w{ }*meth)
@emph{Return value: Borrowed reference.}
返回关联到方法 @emph{meth} 的实例。
@end deffn

@geindex PyMethod_GET_SELF (C 函数)
@anchor{c-api/method c PyMethod_GET_SELF}@anchor{40f4}
@deffn {C 函数} PyObject* PyMethod_GET_SELF (PyObject@w{ }*meth)
@emph{Return value: Borrowed reference.}
宏版本的 @ref{40f3,,PyMethod_Self()}，略去了错误检测。
@end deffn

@node Cell 对象,代码对象<2>,方法对象<2>,函数对象
@anchor{c-api/cell doc}@anchor{40f5}@anchor{c-api/cell cell-objects}@anchor{40f6}@anchor{c-api/cell id1}@anchor{40f7}
@subsubsection Cell 对象


“Cell”对象用于实现由多个作用域引用的变量。 对于每个这样的变量，一个“Cell”对象为了存储该值而被创建；引用该值的每个堆栈框架的局部变量包含同样使用该变量的对外部作用域的“Cell”引用。 访问该值时，将使用“Cell”中包含的值而不是单元格对象本身。 这种对“Cell”对象的非关联化的引用需要支持生成的字节码；访问时不会自动非关联化这些内容。 “Cell”对象在其他地方可能不太有用。

@geindex PyCellObject (C 类型)
@anchor{c-api/cell c PyCellObject}@anchor{40f8}
@deffn {C 类型} PyCellObject

用于Cell对象的C结构体。
@end deffn

@geindex PyCell_Type (C 变量)
@anchor{c-api/cell c PyCell_Type}@anchor{40f9}
@deffn {C 变量} PyTypeObject PyCell_Type

与 Cell 对象对应的类型对​​象。
@end deffn

@geindex PyCell_Check (C 函数)
@anchor{c-api/cell c PyCell_Check}@anchor{40fa}
@deffn {C 函数} int PyCell_Check (ob)

如果 @emph{ob} 是一个 cell 对象则返回真值；@emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyCell_New (C 函数)
@anchor{c-api/cell c PyCell_New}@anchor{40fb}
@deffn {C 函数} PyObject* PyCell_New (PyObject@w{ }*ob)
@emph{Return value: New reference.}
创建并返回一个包含值 @emph{ob} 的新 cell 对象。形参可以为 @code{NULL}。
@end deffn

@geindex PyCell_Get (C 函数)
@anchor{c-api/cell c PyCell_Get}@anchor{40fc}
@deffn {C 函数} PyObject* PyCell_Get (PyObject@w{ }*cell)
@emph{Return value: New reference.}
返回 cell 对象 @emph{cell} 的内容。
@end deffn

@geindex PyCell_GET (C 函数)
@anchor{c-api/cell c PyCell_GET}@anchor{40fd}
@deffn {C 函数} PyObject* PyCell_GET (PyObject@w{ }*cell)
@emph{Return value: Borrowed reference.}
返回 cell 对象 @emph{cell} 的内容，但是不检测 @emph{cell} 是否非 @code{NULL} 并且为一个 cell 对象。
@end deffn

@geindex PyCell_Set (C 函数)
@anchor{c-api/cell c PyCell_Set}@anchor{40fe}
@deffn {C 函数} int PyCell_Set (PyObject@w{ }*cell, PyObject@w{ }*value)

将 cell 对象 @emph{cell} 的内容设为 @emph{value}。 这将释放任何对 cell 对象当前内容的引用。 @emph{value} 可以为 @code{NULL}。 @emph{cell} 必须为非 @code{NULL}；如果它不是一个 cell 对象则将返回 @code{-1}。 如果设置成功则将返回 @code{0}。
@end deffn

@geindex PyCell_SET (C 函数)
@anchor{c-api/cell c PyCell_SET}@anchor{40ff}
@deffn {C 函数} void PyCell_SET (PyObject@w{ }*cell, PyObject@w{ }*value)

将 cell 对象 @emph{cell} 的值设为 @emph{value}。 不会调整引用计数，并且不会进行检测以保证安全；@emph{cell} 必须为非 @code{NULL} 并且为一个 cell 对象。
@end deffn
@anchor{c-api/code codeobjects}@anchor{4100}
@geindex object; code
@geindex code object

@node 代码对象<2>,,Cell 对象,函数对象
@anchor{c-api/code doc}@anchor{4101}@anchor{c-api/code code-objects}@anchor{4102}
@subsubsection 代码对象


代码对象是 CPython 实现的低级细节。 每个代表一块尚未绑定到函数中的可执行代码。

@geindex PyCodeObject (C 类型)
@anchor{c-api/code c PyCodeObject}@anchor{4103}
@deffn {C 类型} PyCodeObject

用于描述代码对象的对象的 C 结构。 此类型字段可随时更改。
@end deffn

@geindex PyCode_Type (C 变量)
@anchor{c-api/code c PyCode_Type}@anchor{4104}
@deffn {C 变量} PyTypeObject PyCode_Type

这是一个 @ref{3fe,,PyTypeObject} 实例，其表示Python的 @ref{1a,,code} 类型。
@end deffn

@geindex PyCode_Check (C 函数)
@anchor{c-api/code c PyCode_Check}@anchor{4105}
@deffn {C 函数} int PyCode_Check (PyObject@w{ }*co)

如果 @emph{co} 是一个 @ref{1a,,code} 对象则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyCode_GetNumFree (C 函数)
@anchor{c-api/code c PyCode_GetNumFree}@anchor{4106}
@deffn {C 函数} int PyCode_GetNumFree (PyCodeObject@w{ }*co)

返回 @emph{co} 中的自由变量数。
@end deffn

@geindex PyCode_New (C 函数)
@anchor{c-api/code c PyCode_New}@anchor{3a3}
@deffn {C 函数} PyCodeObject* PyCode_New (int@w{ }argcount, int@w{ }kwonlyargcount, int@w{ }nlocals, int@w{ }stacksize, int@w{ }flags, PyObject@w{ }*code, PyObject@w{ }*consts, PyObject@w{ }*names, PyObject@w{ }*varnames, PyObject@w{ }*freevars, PyObject@w{ }*cellvars, PyObject@w{ }*filename, PyObject@w{ }*name, int@w{ }firstlineno, PyObject@w{ }*lnotab)
@emph{Return value: New reference.}
返回一个新的代码对象。 如果你需要一个虚拟代码对象来创建一个代码帧，请使用 @ref{db9,,PyCode_NewEmpty()}。 调用 @ref{3a3,,PyCode_New()} 直接可以绑定到准确的 Python 版本，因为字节码的定义经常变化。
@end deffn

@geindex PyCode_NewWithPosOnlyArgs (C 函数)
@anchor{c-api/code c PyCode_NewWithPosOnlyArgs}@anchor{3a2}
@deffn {C 函数} PyCodeObject* PyCode_NewWithPosOnlyArgs (int@w{ }argcount, int@w{ }posonlyargcount, int@w{ }kwonlyargcount, int@w{ }nlocals, int@w{ }stacksize, int@w{ }flags, PyObject@w{ }*code, PyObject@w{ }*consts, PyObject@w{ }*names, PyObject@w{ }*varnames, PyObject@w{ }*freevars, PyObject@w{ }*cellvars, PyObject@w{ }*filename, PyObject@w{ }*name, int@w{ }firstlineno, PyObject@w{ }*lnotab)
@emph{Return value: New reference.}
类似于 @ref{3a3,,PyCode_New()}，但带有一个额外的 "posonlyargcount" 用于仅限位置参数。


3.8 新版功能.

@end deffn

@geindex PyCode_NewEmpty (C 函数)
@anchor{c-api/code c PyCode_NewEmpty}@anchor{db9}
@deffn {C 函数} PyCodeObject* PyCode_NewEmpty (const char@w{ }*filename, const char@w{ }*funcname, int@w{ }firstlineno)
@emph{Return value: New reference.}
返回具有指定文件名、函数名和第一行号的新空代码对象。 对于 @ref{d14,,exec()} 或 @ref{c6a,,eval()} 生成的代码对象是非法的。
@end deffn

@node 其他对象<2>,,函数对象,具体的对象层
@anchor{c-api/concrete other-objects}@anchor{4107}
@subsection 其他对象


@menu
* 文件对象:: 
* 模块对象:: 
* 迭代器对象:: 
* 描述符对象:: 
* 切片对象:: 
* Ellipsis 对象:: 
* MemoryView 对象:: 
* 弱引用对象: 弱引用对象<2>. 
* Capsule 对象:: 
* 生成器对象:: 
* 协程对象: 协程对象<2>. 
* 上下文变量对象:: 
* DateTime 对象: DateTime 对象<2>. 
* 类型注解对象:: 

@end menu

@node 文件对象,模块对象,,其他对象<2>
@anchor{c-api/file doc}@anchor{4108}@anchor{c-api/file file-objects}@anchor{4109}@anchor{c-api/file fileobjects}@anchor{410a}
@subsubsection 文件对象


@geindex 对象; file

这此 API 是对内置文件对象的 Python 2 C API 的最小仿真，它过去依赖于 C 标准库的缓冲 I/O (@code{FILE*}) 支持。 在 Python 3 中，文件和流使用新的 @ref{a1,,io} 模块，该模块在操作系统的低层级无缓冲  I/O 之上定义了几个层。 下面所描述的函数是针对这些新 API 的便捷 C 包装器，主要用于解释器的内部错误报告；建议第三方代码改为访问 @ref{a1,,io} API。

@geindex PyFile_FromFd (C 函数)
@anchor{c-api/file c PyFile_FromFd}@anchor{410b}
@deffn {C 函数} PyObject* PyFile_FromFd (int@w{ }fd, const char@w{ }*name, const char@w{ }*mode, int@w{ }buffering, const char@w{ }*encoding, const char@w{ }*errors, const char@w{ }*newline, int@w{ }closefd)
@emph{Return value: New reference.}
根据已打开文件 @emph{fd} 的文件描述符创建一个 Python 文件对象。 参数 @emph{name}, @emph{encoding}, @emph{errors} 和 @emph{newline} 可以为 @code{NULL} 表示使用默认值；@emph{buffering} 可以为 @emph{-1} 表示使用默认值。 @emph{name} 会被忽略仅保留用于向下兼容。 失败时返回 @code{NULL}。 有关参数的更全面描述，请参阅 @ref{757,,io.open()} 函数的文档。

@cartouche
@quotation 警告 
由于Python流具有自己的缓冲层，因此将它们与 OS 级文件描述符混合会产生各种问题（例如数据的意外排序）。
@end quotation
@end cartouche


在 3.2 版更改: 忽略 @emph{name} 属性。

@end deffn

@geindex PyObject_AsFileDescriptor (C 函数)
@anchor{c-api/file c PyObject_AsFileDescriptor}@anchor{410c}
@deffn {C 函数} int PyObject_AsFileDescriptor (PyObject@w{ }*p)

将与 @emph{p} 关联的文件描述器返回为 @code{int} 。 如果对象是整数，则返回其值。 如果没有，则调用对象的 @ref{209a,,fileno()} 方法（如果存在）; 该方法必须返回一个整数，该整数作为文件描述器值返回。 设置异常并在失败时返回 @code{-1}。
@end deffn

@geindex PyFile_GetLine (C 函数)
@anchor{c-api/file c PyFile_GetLine}@anchor{410d}
@deffn {C 函数} PyObject* PyFile_GetLine (PyObject@w{ }*p, int@w{ }n)
@emph{Return value: New reference.}
@geindex EOFError (built-in exception)

等价于 @code{p.readline([n])} ，这个函数从对象 @emph{p} 中读取一行。 @emph{p} 可以是文件对象或具有 @ref{1883,,readline()} 方法的任何对象。 如果 @emph{n} 是 @code{0} ，则无论该行的长度如何，都会读取一行。 如果 @emph{n} 大于`@w{`}0`@w{`}，则从文件中读取不超过 @emph{n} 个字节；可以返回行的一部分。 在这两种情况下，如果立即到达文件末尾，则返回空字符串。 但是，如果 @emph{n} 小于 @code{0} ，则无论长度如何都会读取一行，但是如果立即到达文件末尾，则引发 @ref{d3c,,EOFError}。
@end deffn

@geindex PyFile_SetOpenCodeHook (C 函数)
@anchor{c-api/file c PyFile_SetOpenCodeHook}@anchor{2174}
@deffn {C 函数} int PyFile_SetOpenCodeHook (Py_OpenCodeHookFunction@w{ }handler)

重载 @ref{f59,,io.open_code()} 的正常行为，将其形参通过所提供的处理程序来传递。

处理程序是一个类型为 @code{PyObject *(*)(PyObject *path, void *userData)} 的函数，其中 @emph{path} 确保为 @ref{4036,,PyUnicodeObject}。

@emph{userData} 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调用，该指针不应直接指向 Python 状态。

鉴于这个钩子专门在导入期间使用的，请避免在新模块执行期间进行导入操作，除非已知它们为冻结状态或者是在 @code{sys.modules} 中可用。

一旦钩子被设定，它就不能被移除或替换，之后对 @ref{2174,,PyFile_SetOpenCodeHook()} 的调用也将失败，如果解释器已经被初始化，函数将返回 -1 并设置一个异常。

此函数可以安全地在 @ref{210,,Py_Initialize()} 之前调用。

引发一个 @ref{fec,,审计事件} @code{setopencodehook}，不附带任何参数。


3.8 新版功能.

@end deffn

@geindex PyFile_WriteObject (C 函数)
@anchor{c-api/file c PyFile_WriteObject}@anchor{410e}
@deffn {C 函数} int PyFile_WriteObject (PyObject@w{ }*obj, PyObject@w{ }*p, int@w{ }flags)

@geindex Py_PRINT_RAW

将对象 @emph{obj} 写入文件对象 @emph{p} 。 @emph{flags} 唯一支持的标志是 @code{Py_PRINT_RAW}；如果给定，则写入对象的 @ref{206,,str()} 而不是 @ref{8c3,,repr()}。成功时返回 @code{0}，失败时返回 @code{-1}。 将设置适当的例外。
@end deffn

@geindex PyFile_WriteString (C 函数)
@anchor{c-api/file c PyFile_WriteString}@anchor{410f}
@deffn {C 函数} int PyFile_WriteString (const char@w{ }*s, PyObject@w{ }*p)

将字符串 @emph{s} 写入文件对象 @emph{p}。 成功返回 @code{0} 失败返回 @code{-1}；将设定相应的异常。
@end deffn

@node 模块对象,迭代器对象,文件对象,其他对象<2>
@anchor{c-api/module doc}@anchor{4110}@anchor{c-api/module module-objects}@anchor{4111}@anchor{c-api/module moduleobjects}@anchor{4112}
@subsubsection 模块对象


@geindex 对象; module

@geindex PyModule_Type (C 变量)
@anchor{c-api/module c PyModule_Type}@anchor{4113}
@deffn {C 变量} PyTypeObject PyModule_Type

@geindex ModuleType (in module types)

这个 @ref{3fe,,PyTypeObject} 的实例代表 Python 模块类型。 它以 @code{types.ModuleType} 的形式暴露给 Python 程序。
@end deffn

@geindex PyModule_Check (C 函数)
@anchor{c-api/module c PyModule_Check}@anchor{4114}
@deffn {C 函数} int PyModule_Check (PyObject@w{ }*p)

当 @emph{p} 为模块类型的对象，或是模块子类型的对象时返回真。该函数永远有返回。
@end deffn

@geindex PyModule_CheckExact (C 函数)
@anchor{c-api/module c PyModule_CheckExact}@anchor{4115}
@deffn {C 函数} int PyModule_CheckExact (PyObject@w{ }*p)

当 @emph{p} 为模块对象且不是 @ref{4113,,PyModule_Type} 的子类型的对象时返回真值。该函数永远有返回值。
@end deffn

@geindex PyModule_NewObject (C 函数)
@anchor{c-api/module c PyModule_NewObject}@anchor{4116}
@deffn {C 函数} PyObject* PyModule_NewObject (PyObject@w{ }*name)
@emph{Return value: New reference.}
@geindex __name__ (module attribute)
@geindex __doc__ (module attribute)
@geindex __file__ (module attribute)
@geindex __package__ (module attribute)
@geindex __loader__ (module attribute)

返回新的模块对象，其属性 @ref{de0,,__name__}  为 @emph{name} 。模块的这些属性 @ref{de0,,__name__}, @code{__doc__}, @ref{a3f,,__package__}, and @ref{a40,,__loader__} （所有属性除了 @ref{de0,,__name__} 都被设为`@w{`}None`@w{`}）。调用时应当提供 @ref{1591,,__file__} 属性。


3.3 新版功能.



在 3.4 版更改: 属性 @ref{a3f,,__package__} 和 @ref{a40,,__loader__} 被设为`@w{`}None`@w{`}。

@end deffn

@geindex PyModule_New (C 函数)
@anchor{c-api/module c PyModule_New}@anchor{4117}
@deffn {C 函数} PyObject* PyModule_New (const char@w{ }*name)
@emph{Return value: New reference.}
这类似于 @ref{4116,,PyModule_NewObject()}， 但其名称为 UTF-8 编码的字符串而不是 Unicode 对象。
@end deffn

@geindex PyModule_GetDict (C 函数)
@anchor{c-api/module c PyModule_GetDict}@anchor{4118}
@deffn {C 函数} PyObject* PyModule_GetDict (PyObject@w{ }*module)
@emph{Return value: Borrowed reference.}
@geindex __dict__ (module attribute)

返回实现 @emph{module} 的命名空间的字典对象；此对象与模块对象的 @ref{5fe,,__dict__} 属性相同。 如果 @emph{module} 不是一个模块对象（或模块对象的子类型），则会引发 @ref{6fc,,SystemError} 并返回 @code{NULL}。

建议扩展使用其他 @code{PyModule_*()} and @code{PyObject_*()} 函数而不是直接操纵模块的 @ref{5fe,,__dict__}。
@end deffn

@geindex PyModule_GetNameObject (C 函数)
@anchor{c-api/module c PyModule_GetNameObject}@anchor{4119}
@deffn {C 函数} PyObject* PyModule_GetNameObject (PyObject@w{ }*module)
@emph{Return value: New reference.}
@geindex __name__ (module attribute)
@geindex SystemError (built-in exception)

返回 @emph{module} 的 @ref{de0,,__name__} 值。 如果模块未提供该值，或者如果它不是一个字符串，则会引发 @ref{6fc,,SystemError} 并返回 @code{NULL}。


3.3 新版功能.

@end deffn

@geindex PyModule_GetName (C 函数)
@anchor{c-api/module c PyModule_GetName}@anchor{411a}
@deffn {C 函数} const char* PyModule_GetName (PyObject@w{ }*module)

类似于 @ref{4119,,PyModule_GetNameObject()} 但返回 @code{'utf-8'} 编码的名称。
@end deffn

@geindex PyModule_GetState (C 函数)
@anchor{c-api/module c PyModule_GetState}@anchor{25f}
@deffn {C 函数} void* PyModule_GetState (PyObject@w{ }*module)

返回模块的“状态”，也就是说，返回指向在模块创建时分配的内存块的指针，或者 @code{NULL}。 参见 @ref{25e,,PyModuleDef.m_size}。
@end deffn

@geindex PyModule_GetDef (C 函数)
@anchor{c-api/module c PyModule_GetDef}@anchor{411b}
@deffn {C 函数} PyModuleDef* PyModule_GetDef (PyObject@w{ }*module)

返回指向模块创建所使用的 @ref{259,,PyModuleDef} 结构体的指针，或者如果模块不是使用结构体定义创建的则返回 @code{NULL}。
@end deffn

@geindex PyModule_GetFilenameObject (C 函数)
@anchor{c-api/module c PyModule_GetFilenameObject}@anchor{411c}
@deffn {C 函数} PyObject* PyModule_GetFilenameObject (PyObject@w{ }*module)
@emph{Return value: New reference.}
@geindex __file__ (module attribute)
@geindex SystemError (built-in exception)

返回使用 @emph{module} 的 @ref{1591,,__file__} 属性所加载的 @emph{模块} 的文件名。 如果属性未定义，或者如果它不是一个 Unicode 字符串，则会引发 @ref{6fc,,SystemError} 并返回 @code{NULL}；在其他情况下将返回一个指向 Unicode 对象的引用。


3.2 新版功能.

@end deffn

@geindex PyModule_GetFilename (C 函数)
@anchor{c-api/module c PyModule_GetFilename}@anchor{411d}
@deffn {C 函数} const char* PyModule_GetFilename (PyObject@w{ }*module)

Similar to @ref{411c,,PyModule_GetFilenameObject()} but return the filename
encoded to 'utf-8'.


3.2 版后已移除: @ref{411d,,PyModule_GetFilename()} raises @code{UnicodeEncodeError} on
unencodable filenames, use @ref{411c,,PyModule_GetFilenameObject()} instead.

@end deffn

@menu
* 初始化 C 模块:: 
* Module lookup:: 

@end menu

@node 初始化 C 模块,Module lookup,,模块对象
@anchor{c-api/module initializing-c-modules}@anchor{411e}@anchor{c-api/module initializing-modules}@anchor{3dc6}
@subsubsection 初始化 C 模块


Modules objects are usually created from extension modules (shared libraries
which export an initialization function), or compiled-in modules
(where the initialization function is added using @ref{fe7,,PyImport_AppendInittab()}).
See @ref{3d63,,构建C/C++扩展} or @ref{3de4,,对嵌入 Python 功能进行扩展} for details.

The initialization function can either pass a module definition instance
to @ref{3d60,,PyModule_Create()}, and return the resulting module object,
or request "multi-phase initialization" by returning the definition struct itself.

@geindex PyModuleDef (C 类型)
@anchor{c-api/module c PyModuleDef}@anchor{259}
@deffn {C 类型} PyModuleDef

The module definition struct, which holds all information needed to create
a module object. There is usually only one statically initialized variable
of this type for each module.

@geindex PyModuleDef.m_base (C 成员)
@anchor{c-api/module c PyModuleDef m_base}@anchor{411f}
@deffn {C 成员} PyModuleDef_Base m_base

Always initialize this member to @code{PyModuleDef_HEAD_INIT}.
@end deffn

@geindex PyModuleDef.m_name (C 成员)
@anchor{c-api/module c PyModuleDef m_name}@anchor{4120}
@deffn {C 成员} const char *m_name

新模块的名称。
@end deffn

@geindex PyModuleDef.m_doc (C 成员)
@anchor{c-api/module c PyModuleDef m_doc}@anchor{4121}
@deffn {C 成员} const char *m_doc

Docstring for the module; usually a docstring variable created with
@ref{10a3,,PyDoc_STRVAR} is used.
@end deffn

@geindex PyModuleDef.m_size (C 成员)
@anchor{c-api/module c PyModuleDef m_size}@anchor{25e}
@deffn {C 成员} Py_ssize_t m_size

Module state may be kept in a per-module memory area that can be
retrieved with @ref{25f,,PyModule_GetState()}, rather than in static globals.
This makes modules safe for use in multiple sub-interpreters.

This memory area is allocated based on @emph{m_size} on module creation,
and freed when the module object is deallocated, after the
@code{m_free} function has been called, if present.

Setting @code{m_size} to @code{-1} means that the module does not support
sub-interpreters, because it has global state.

Setting it to a non-negative value means that the module can be
re-initialized and specifies the additional amount of memory it requires
for its state. Non-negative @code{m_size} is required for multi-phase
initialization.

请参阅 
@geindex Python 提高建议; PEP 3121
PEP 3121@footnote{https://www.python.org/dev/peps/pep-3121} 了解详情。
@end deffn

@geindex PyModuleDef.m_methods (C 成员)
@anchor{c-api/module c PyModuleDef m_methods}@anchor{4122}
@deffn {C 成员} PyMethodDef* m_methods

A pointer to a table of module-level functions, described by
@ref{ee5,,PyMethodDef} values.  Can be @code{NULL} if no functions are present.
@end deffn

@geindex PyModuleDef.m_slots (C 成员)
@anchor{c-api/module c PyModuleDef m_slots}@anchor{4123}
@deffn {C 成员} PyModuleDef_Slot* m_slots

An array of slot definitions for multi-phase initialization, terminated by
a @code{@{0, NULL@}} entry.
When using single-phase initialization, @emph{m_slots} must be @code{NULL}.


在 3.5 版更改: Prior to version 3.5, this member was always set to @code{NULL},
and was defined as:

@quotation

@geindex PyModuleDef.m_reload (C 成员)
@anchor{c-api/module c PyModuleDef m_reload}@anchor{4124}
@deffn {C 成员} inquiry m_reload
@end deffn
@end quotation

@end deffn

@geindex PyModuleDef.m_traverse (C 成员)
@anchor{c-api/module c PyModuleDef m_traverse}@anchor{25a}
@deffn {C 成员} traverseproc m_traverse

A traversal function to call during GC traversal of the module object, or
@code{NULL} if not needed.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{25d,,Py_mod_exec} function). More
precisely, this function is not called if @code{m_size} is greater
than 0 and the module state (as returned by @ref{25f,,PyModule_GetState()})
is @code{NULL}.


在 3.9 版更改: No longer called before the module state is allocated.

@end deffn

@geindex PyModuleDef.m_clear (C 成员)
@anchor{c-api/module c PyModuleDef m_clear}@anchor{25b}
@deffn {C 成员} inquiry m_clear

A clear function to call during GC clearing of the module object, or
@code{NULL} if not needed.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{25d,,Py_mod_exec} function). More
precisely, this function is not called if @code{m_size} is greater
than 0 and the module state (as returned by @ref{25f,,PyModule_GetState()})
is @code{NULL}.

Like @ref{3dab,,PyTypeObject.tp_clear}, this function is not @emph{always}
called before a module is deallocated. For example, when reference
counting is enough to determine that an object is no longer used,
the cyclic garbage collector is not involved and
@ref{25c,,m_free} is called directly.


在 3.9 版更改: No longer called before the module state is allocated.

@end deffn

@geindex PyModuleDef.m_free (C 成员)
@anchor{c-api/module c PyModuleDef m_free}@anchor{25c}
@deffn {C 成员} freefunc m_free

A function to call during deallocation of the module object, or @code{NULL}
if not needed.

This function is not called if the module state was requested but is not
allocated yet. This is the case immediately after the module is created
and before the module is executed (@ref{25d,,Py_mod_exec} function). More
precisely, this function is not called if @code{m_size} is greater
than 0 and the module state (as returned by @ref{25f,,PyModule_GetState()})
is @code{NULL}.


在 3.9 版更改: No longer called before the module state is allocated.

@end deffn
@end deffn

@menu
* Single-phase initialization:: 
* Multi-phase initialization:: 
* Low-level module creation functions:: 
* Support functions:: 

@end menu

@node Single-phase initialization,Multi-phase initialization,,初始化 C 模块
@anchor{c-api/module single-phase-initialization}@anchor{4125}
@subsubsection Single-phase initialization


The module initialization function may create and return the module object
directly. This is referred to as "single-phase initialization", and uses one
of the following two module creation functions:

@geindex PyModule_Create (C 函数)
@anchor{c-api/module c PyModule_Create}@anchor{3d60}
@deffn {C 函数} PyObject* PyModule_Create (PyModuleDef@w{ }*def)
@emph{Return value: New reference.}
Create a new module object, given the definition in @emph{def}.  This behaves
like @ref{4126,,PyModule_Create2()} with @emph{module_api_version} set to
@code{PYTHON_API_VERSION}.
@end deffn

@geindex PyModule_Create2 (C 函数)
@anchor{c-api/module c PyModule_Create2}@anchor{4126}
@deffn {C 函数} PyObject* PyModule_Create2 (PyModuleDef@w{ }*def, int@w{ }module_api_version)
@emph{Return value: New reference.}
Create a new module object, given the definition in @emph{def}, assuming the
API version @emph{module_api_version}.  If that version does not match the version
of the running interpreter, a @ref{3ea,,RuntimeWarning} is emitted.

@cartouche
@quotation 注解 
Most uses of this function should be using @ref{3d60,,PyModule_Create()}
instead; only use this if you are sure you need it.
@end quotation
@end cartouche
@end deffn

Before it is returned from in the initialization function, the resulting module
object is typically populated using functions like @ref{1126,,PyModule_AddObject()}.

@node Multi-phase initialization,Low-level module creation functions,Single-phase initialization,初始化 C 模块
@anchor{c-api/module id1}@anchor{4127}@anchor{c-api/module multi-phase-initialization}@anchor{3dc7}
@subsubsection Multi-phase initialization


An alternate way to specify extensions is to request "multi-phase initialization".
Extension modules created this way behave more like Python modules: the
initialization is split between the @emph{creation phase}, when the module object
is created, and the @emph{execution phase}, when it is populated.
The distinction is similar to the @ref{97d,,__new__()} and @ref{e2b,,__init__()} methods
of classes.

Unlike modules created using single-phase initialization, these modules are not
singletons: if the @emph{sys.modules} entry is removed and the module is re-imported,
a new module object is created, and the old module is subject to normal garbage
collection -- as with Python modules.
By default, multiple modules created from the same definition should be
independent: changes to one should not affect the others.
This means that all state should be specific to the module object (using e.g.
using @ref{25f,,PyModule_GetState()}), or its contents (such as the module's
@ref{5fe,,__dict__} or individual classes created with @ref{23b,,PyType_FromSpec()}).

All modules created using multi-phase initialization are expected to support
@ref{3e90,,sub-interpreters}. Making sure multiple modules
are independent is typically enough to achieve this.

To request multi-phase initialization, the initialization function
(PyInit_modulename) returns a @ref{259,,PyModuleDef} instance with non-empty
@ref{4123,,m_slots}. Before it is returned, the @code{PyModuleDef}
instance must be initialized with the following function:

@geindex PyModuleDef_Init (C 函数)
@anchor{c-api/module c PyModuleDef_Init}@anchor{4128}
@deffn {C 函数} PyObject* PyModuleDef_Init (PyModuleDef@w{ }*def)
@emph{Return value: Borrowed reference.}
Ensures a module definition is a properly initialized Python object that
correctly reports its type and reference count.

Returns @emph{def} cast to @code{PyObject*}, or @code{NULL} if an error occurred.


3.5 新版功能.

@end deffn

The @emph{m_slots} member of the module definition must point to an array of
@code{PyModuleDef_Slot} structures:

@geindex PyModuleDef_Slot (C 类型)
@anchor{c-api/module c PyModuleDef_Slot}@anchor{4129}
@deffn {C 类型} PyModuleDef_Slot

@geindex PyModuleDef_Slot.slot (C 成员)
@anchor{c-api/module c PyModuleDef_Slot slot}@anchor{412a}
@deffn {C 成员} int slot

A slot ID, chosen from the available values explained below.
@end deffn

@geindex PyModuleDef_Slot.value (C 成员)
@anchor{c-api/module c PyModuleDef_Slot value}@anchor{412b}
@deffn {C 成员} void* value

Value of the slot, whose meaning depends on the slot ID.
@end deffn


3.5 新版功能.

@end deffn

The @emph{m_slots} array must be terminated by a slot with id 0.

The available slot types are:

@geindex Py_mod_create (C 宏)
@anchor{c-api/module c Py_mod_create}@anchor{412c}
@deffn {C 宏} Py_mod_create

Specifies a function that is called to create the module object itself.
The @emph{value} pointer of this slot must point to a function of the signature:

@geindex create_module (C 函数)
@anchor{c-api/module c create_module}@anchor{412d}
@deffn {C 函数} PyObject* create_module (PyObject@w{ }*spec, PyModuleDef@w{ }*def)
@end deffn

The function receives a @ref{1630,,ModuleSpec}
instance, as defined in 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451}, and the module definition.
It should return a new module object, or set an error
and return @code{NULL}.

This function should be kept minimal. In particular, it should not
call arbitrary Python code, as trying to import the same module again may
result in an infinite loop.

Multiple @code{Py_mod_create} slots may not be specified in one module
definition.

If @code{Py_mod_create} is not specified, the import machinery will create
a normal module object using @ref{4117,,PyModule_New()}. The name is taken from
@emph{spec}, not the definition, to allow extension modules to dynamically adjust
to their place in the module hierarchy and be imported under different
names through symlinks, all while sharing a single module definition.

There is no requirement for the returned object to be an instance of
@ref{4113,,PyModule_Type}. Any type can be used, as long as it supports
setting and getting import-related attributes.
However, only @code{PyModule_Type} instances may be returned if the
@code{PyModuleDef} has non-@code{NULL} @code{m_traverse}, @code{m_clear},
@code{m_free}; non-zero @code{m_size}; or slots other than @code{Py_mod_create}.
@end deffn

@geindex Py_mod_exec (C 宏)
@anchor{c-api/module c Py_mod_exec}@anchor{25d}
@deffn {C 宏} Py_mod_exec

Specifies a function that is called to @emph{execute} the module.
This is equivalent to executing the code of a Python module: typically,
this function adds classes and constants to the module.
The signature of the function is:

@geindex exec_module (C 函数)
@anchor{c-api/module c exec_module}@anchor{412e}
@deffn {C 函数} int exec_module (PyObject*@w{ }module)
@end deffn

If multiple @code{Py_mod_exec} slots are specified, they are processed in the
order they appear in the @emph{m_slots} array.
@end deffn

See 
@geindex Python 提高建议; PEP 489
PEP 489@footnote{https://www.python.org/dev/peps/pep-0489} for more details on multi-phase initialization.

@node Low-level module creation functions,Support functions,Multi-phase initialization,初始化 C 模块
@anchor{c-api/module low-level-module-creation-functions}@anchor{412f}
@subsubsection Low-level module creation functions


The following functions are called under the hood when using multi-phase
initialization. They can be used directly, for example when creating module
objects dynamically. Note that both @code{PyModule_FromDefAndSpec} and
@code{PyModule_ExecDef} must be called to fully initialize a module.

@geindex PyModule_FromDefAndSpec (C 函数)
@anchor{c-api/module c PyModule_FromDefAndSpec}@anchor{8a3}
@deffn {C 函数} PyObject * PyModule_FromDefAndSpec (PyModuleDef@w{ }*def, PyObject@w{ }*spec)
@emph{Return value: New reference.}
Create a new module object, given the definition in @emph{module} and the
ModuleSpec @emph{spec}.  This behaves like @ref{8a4,,PyModule_FromDefAndSpec2()}
with @emph{module_api_version} set to @code{PYTHON_API_VERSION}.


3.5 新版功能.

@end deffn

@geindex PyModule_FromDefAndSpec2 (C 函数)
@anchor{c-api/module c PyModule_FromDefAndSpec2}@anchor{8a4}
@deffn {C 函数} PyObject * PyModule_FromDefAndSpec2 (PyModuleDef@w{ }*def, PyObject@w{ }*spec, int@w{ }module_api_version)
@emph{Return value: New reference.}
Create a new module object, given the definition in @emph{module} and the
ModuleSpec @emph{spec}, assuming the API version @emph{module_api_version}.
If that version does not match the version of the running interpreter,
a @ref{3ea,,RuntimeWarning} is emitted.

@cartouche
@quotation 注解 
Most uses of this function should be using @ref{8a3,,PyModule_FromDefAndSpec()}
instead; only use this if you are sure you need it.
@end quotation
@end cartouche


3.5 新版功能.

@end deffn

@geindex PyModule_ExecDef (C 函数)
@anchor{c-api/module c PyModule_ExecDef}@anchor{8a5}
@deffn {C 函数} int PyModule_ExecDef (PyObject@w{ }*module, PyModuleDef@w{ }*def)

Process any execution slots (@ref{25d,,Py_mod_exec}) given in @emph{def}.


3.5 新版功能.

@end deffn

@geindex PyModule_SetDocString (C 函数)
@anchor{c-api/module c PyModule_SetDocString}@anchor{4130}
@deffn {C 函数} int PyModule_SetDocString (PyObject@w{ }*module, const char@w{ }*docstring)

Set the docstring for @emph{module} to @emph{docstring}.
This function is called automatically when creating a module from
@code{PyModuleDef}, using either @code{PyModule_Create} or
@code{PyModule_FromDefAndSpec}.


3.5 新版功能.

@end deffn

@geindex PyModule_AddFunctions (C 函数)
@anchor{c-api/module c PyModule_AddFunctions}@anchor{4131}
@deffn {C 函数} int PyModule_AddFunctions (PyObject@w{ }*module, PyMethodDef@w{ }*functions)

Add the functions from the @code{NULL} terminated @emph{functions} array to @emph{module}.
Refer to the @ref{ee5,,PyMethodDef} documentation for details on individual
entries (due to the lack of a shared module namespace, module level
"functions" implemented in C typically receive the module as their first
parameter, making them similar to instance methods on Python classes).
This function is called automatically when creating a module from
@code{PyModuleDef}, using either @code{PyModule_Create} or
@code{PyModule_FromDefAndSpec}.


3.5 新版功能.

@end deffn

@node Support functions,,Low-level module creation functions,初始化 C 模块
@anchor{c-api/module support-functions}@anchor{4132}
@subsubsection Support functions


The module initialization function (if using single phase initialization) or
a function called from a module execution slot (if using multi-phase
initialization), can use the following functions to help initialize the module
state:

@geindex PyModule_AddObject (C 函数)
@anchor{c-api/module c PyModule_AddObject}@anchor{1126}
@deffn {C 函数} int PyModule_AddObject (PyObject@w{ }*module, const char@w{ }*name, PyObject@w{ }*value)

Add an object to @emph{module} as @emph{name}.  This is a convenience function which can
be used from the module's initialization function.  This steals a reference to
@emph{value} on success. Return @code{-1} on error, @code{0} on success.

@cartouche
@quotation 注解 
Unlike other functions that steal references, @code{PyModule_AddObject()} only
decrements the reference count of @emph{value} @strong{on success}.

This means that its return value must be checked, and calling code must
@ref{397,,Py_DECREF()} @emph{value} manually on error. Example usage:

@example
Py_INCREF(spam);
if (PyModule_AddObject(module, "spam", spam) < 0) @{
    Py_DECREF(module);
    Py_DECREF(spam);
    return NULL;
@}
@end example
@end quotation
@end cartouche
@end deffn

@geindex PyModule_AddIntConstant (C 函数)
@anchor{c-api/module c PyModule_AddIntConstant}@anchor{4133}
@deffn {C 函数} int PyModule_AddIntConstant (PyObject@w{ }*module, const char@w{ }*name, long@w{ }value)

Add an integer constant to @emph{module} as @emph{name}.  This convenience function can be
used from the module's initialization function. Return @code{-1} on error, @code{0} on
success.
@end deffn

@geindex PyModule_AddStringConstant (C 函数)
@anchor{c-api/module c PyModule_AddStringConstant}@anchor{4134}
@deffn {C 函数} int PyModule_AddStringConstant (PyObject@w{ }*module, const char@w{ }*name, const char@w{ }*value)

Add a string constant to @emph{module} as @emph{name}.  This convenience function can be
used from the module's initialization function.  The string @emph{value} must be
@code{NULL}-terminated.  Return @code{-1} on error, @code{0} on success.
@end deffn

@geindex PyModule_AddIntMacro (C 函数)
@anchor{c-api/module c PyModule_AddIntMacro}@anchor{4135}
@deffn {C 函数} int PyModule_AddIntMacro (PyObject@w{ }*module, macro)

Add an int constant to @emph{module}. The name and the value are taken from
@emph{macro}. For example @code{PyModule_AddIntMacro(module, AF_INET)} adds the int
constant @emph{AF_INET} with the value of @emph{AF_INET} to @emph{module}.
Return @code{-1} on error, @code{0} on success.
@end deffn

@geindex PyModule_AddStringMacro (C 函数)
@anchor{c-api/module c PyModule_AddStringMacro}@anchor{e26}
@deffn {C 函数} int PyModule_AddStringMacro (PyObject@w{ }*module, macro)

Add a string constant to @emph{module}.
@end deffn

@geindex PyModule_AddType (C 函数)
@anchor{c-api/module c PyModule_AddType}@anchor{254}
@deffn {C 函数} int PyModule_AddType (PyObject@w{ }*module, PyTypeObject@w{ }*type)

Add a type object to @emph{module}.
The type object is finalized by calling internally @ref{3d96,,PyType_Ready()}.
The name of the type object is taken from the last component of
@ref{3dae,,tp_name} after dot.
Return @code{-1} on error, @code{0} on success.


3.9 新版功能.

@end deffn

@node Module lookup,,初始化 C 模块,模块对象
@anchor{c-api/module module-lookup}@anchor{4136}
@subsubsection Module lookup


Single-phase initialization creates singleton modules that can be looked up
in the context of the current interpreter. This allows the module object to be
retrieved later with only a reference to the module definition.

These functions will not work on modules created using multi-phase initialization,
since multiple such modules can be created from a single definition.

@geindex PyState_FindModule (C 函数)
@anchor{c-api/module c PyState_FindModule}@anchor{4137}
@deffn {C 函数} PyObject* PyState_FindModule (PyModuleDef@w{ }*def)
@emph{Return value: Borrowed reference.}
Returns the module object that was created from @emph{def} for the current interpreter.
This method requires that the module object has been attached to the interpreter state with
@ref{4138,,PyState_AddModule()} beforehand. In case the corresponding module object is not
found or has not been attached to the interpreter state yet, it returns @code{NULL}.
@end deffn

@geindex PyState_AddModule (C 函数)
@anchor{c-api/module c PyState_AddModule}@anchor{4138}
@deffn {C 函数} int PyState_AddModule (PyObject@w{ }*module, PyModuleDef@w{ }*def)

Attaches the module object passed to the function to the interpreter state. This allows
the module object to be accessible via @ref{4137,,PyState_FindModule()}.

Only effective on modules created using single-phase initialization.

Python calls @code{PyState_AddModule} automatically after importing a module,
so it is unnecessary (but harmless) to call it from module initialization
code. An explicit call is needed only if the module's own init code
subsequently calls @code{PyState_FindModule}.
The function is mainly intended for implementing alternative import
mechanisms (either by calling it directly, or by referring to its
implementation for details of the required state updates).

呼叫者必须持有GIL。

Return 0 on success or -1 on failure.


3.3 新版功能.

@end deffn

@geindex PyState_RemoveModule (C 函数)
@anchor{c-api/module c PyState_RemoveModule}@anchor{4139}
@deffn {C 函数} int PyState_RemoveModule (PyModuleDef@w{ }*def)

Removes the module object created from @emph{def} from the interpreter state.
Return 0 on success or -1 on failure.

呼叫者必须持有GIL。


3.3 新版功能.

@end deffn

@node 迭代器对象,描述符对象,模块对象,其他对象<2>
@anchor{c-api/iterator doc}@anchor{413a}@anchor{c-api/iterator id1}@anchor{413b}@anchor{c-api/iterator iterator-objects}@anchor{413c}
@subsubsection 迭代器对象


Python 提供了两个通用迭代器对象。 第一个是序列迭代器，它使用支持 @ref{3ad,,__getitem__()} 方法的任意序列。 第二个使用可调用对象和一个 sentinel 值，为序列中的每个项调用可调用对象，并在返回 sentinel 值时结束迭代。

@geindex PySeqIter_Type (C 变量)
@anchor{c-api/iterator c PySeqIter_Type}@anchor{413d}
@deffn {C 变量} PyTypeObject PySeqIter_Type

@ref{413e,,PySeqIter_New()} 返回迭代器对象的类型对象和内置序列类型内置函数 @ref{df5,,iter()} 的单参数形式。
@end deffn

@geindex PySeqIter_Check (C 函数)
@anchor{c-api/iterator c PySeqIter_Check}@anchor{413f}
@deffn {C 函数} int PySeqIter_Check (op)

如果 @emph{op} 的类型为 @ref{413d,,PySeqIter_Type} 则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PySeqIter_New (C 函数)
@anchor{c-api/iterator c PySeqIter_New}@anchor{413e}
@deffn {C 函数} PyObject* PySeqIter_New (PyObject@w{ }*seq)
@emph{Return value: New reference.}
返回一个与常规序列对象一起使用的迭代器 @emph{seq}。 当序列订阅操作引发 @ref{f3d,,IndexError} 时，迭代结束。
@end deffn

@geindex PyCallIter_Type (C 变量)
@anchor{c-api/iterator c PyCallIter_Type}@anchor{4140}
@deffn {C 变量} PyTypeObject PyCallIter_Type

由函数 @ref{4141,,PyCallIter_New()} 和 @ref{df5,,iter()} 内置函数的双参数形式返回的迭代器对象类型对象。
@end deffn

@geindex PyCallIter_Check (C 函数)
@anchor{c-api/iterator c PyCallIter_Check}@anchor{4142}
@deffn {C 函数} int PyCallIter_Check (op)

如果 @emph{op} 的类型为 @ref{4140,,PyCallIter_Type} 则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyCallIter_New (C 函数)
@anchor{c-api/iterator c PyCallIter_New}@anchor{4141}
@deffn {C 函数} PyObject* PyCallIter_New (PyObject@w{ }*callable, PyObject@w{ }*sentinel)
@emph{Return value: New reference.}
返回一个新的迭代器。 第一个参数 @emph{callable} 可以是任何可以在没有参数的情况下调用的 Python 可调用对象；每次调用都应该返回迭代中的下一个项目。 当 @emph{callable} 返回等于 @emph{sentinel} 的值时，迭代将终止。
@end deffn

@node 描述符对象,切片对象,迭代器对象,其他对象<2>
@anchor{c-api/descriptor doc}@anchor{4143}@anchor{c-api/descriptor descriptor-objects}@anchor{4144}@anchor{c-api/descriptor id1}@anchor{4145}
@subsubsection 描述符对象


“描述符”是描述对象的某些属性的对象。它们存在于类型对象的字典中。

@c XXX document these!

@geindex PyProperty_Type (C 变量)
@anchor{c-api/descriptor c PyProperty_Type}@anchor{4146}
@deffn {C 变量} PyTypeObject PyProperty_Type

内建描述符类型的类型对象。
@end deffn

@geindex PyDescr_NewGetSet (C 函数)
@anchor{c-api/descriptor c PyDescr_NewGetSet}@anchor{4147}
@deffn {C 函数} PyObject* PyDescr_NewGetSet (PyTypeObject@w{ }*type, struct PyGetSetDef@w{ }*getset)
@emph{Return value: New reference.}
@end deffn

@geindex PyDescr_NewMember (C 函数)
@anchor{c-api/descriptor c PyDescr_NewMember}@anchor{4148}
@deffn {C 函数} PyObject* PyDescr_NewMember (PyTypeObject@w{ }*type, struct PyMemberDef@w{ }*meth)
@emph{Return value: New reference.}
@end deffn

@geindex PyDescr_NewMethod (C 函数)
@anchor{c-api/descriptor c PyDescr_NewMethod}@anchor{10bf}
@deffn {C 函数} PyObject* PyDescr_NewMethod (PyTypeObject@w{ }*type, struct PyMethodDef@w{ }*meth)
@emph{Return value: New reference.}
@end deffn

@geindex PyDescr_NewWrapper (C 函数)
@anchor{c-api/descriptor c PyDescr_NewWrapper}@anchor{4149}
@deffn {C 函数} PyObject* PyDescr_NewWrapper (PyTypeObject@w{ }*type, struct wrapperbase@w{ }*wrapper, void@w{ }*wrapped)
@emph{Return value: New reference.}
@end deffn

@geindex PyDescr_NewClassMethod (C 函数)
@anchor{c-api/descriptor c PyDescr_NewClassMethod}@anchor{414a}
@deffn {C 函数} PyObject* PyDescr_NewClassMethod (PyTypeObject@w{ }*type, PyMethodDef@w{ }*method)
@emph{Return value: New reference.}
@end deffn

@geindex PyDescr_IsData (C 函数)
@anchor{c-api/descriptor c PyDescr_IsData}@anchor{414b}
@deffn {C 函数} int PyDescr_IsData (PyObject@w{ }*descr)

如果描述符对象 @emph{descr} 描述数据属性，则返回true；如果描述方法，则返回false。 @emph{descr} 必须是描述符对象；没有错误检查。
@end deffn

@geindex PyWrapper_New (C 函数)
@anchor{c-api/descriptor c PyWrapper_New}@anchor{414c}
@deffn {C 函数} PyObject* PyWrapper_New (PyObject@w{ }*, PyObject@w{ }*)
@emph{Return value: New reference.}
@end deffn

@node 切片对象,Ellipsis 对象,描述符对象,其他对象<2>
@anchor{c-api/slice doc}@anchor{414d}@anchor{c-api/slice id1}@anchor{414e}@anchor{c-api/slice slice-objects}@anchor{414f}
@subsubsection 切片对象


@geindex PySlice_Type (C 变量)
@anchor{c-api/slice c PySlice_Type}@anchor{4150}
@deffn {C 变量} PyTypeObject PySlice_Type

切片对象的类型对象。 它与 Python 层面的 @ref{ed0,,slice} 是相同的对象。
@end deffn

@geindex PySlice_Check (C 函数)
@anchor{c-api/slice c PySlice_Check}@anchor{4151}
@deffn {C 函数} int PySlice_Check (PyObject@w{ }*ob)

如果 @emph{ob} 是一个 slice 对象则返回真值；@emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PySlice_New (C 函数)
@anchor{c-api/slice c PySlice_New}@anchor{4152}
@deffn {C 函数} PyObject* PySlice_New (PyObject@w{ }*start, PyObject@w{ }*stop, PyObject@w{ }*step)
@emph{Return value: New reference.}
返回一个具有给定值的新切片对象。 @emph{start}, @emph{stop} 和 @emph{step} 形参会被用作 slice 对象相应名称的属性的值。 这些值中的任何一个都可以为 @code{NULL}，在这种情况下将使用 @code{None} 作为对应属性的值。 如果新对象无法被分配则返回 @code{NULL}。
@end deffn

@geindex PySlice_GetIndices (C 函数)
@anchor{c-api/slice c PySlice_GetIndices}@anchor{4153}
@deffn {C 函数} int PySlice_GetIndices (PyObject@w{ }*slice, Py_ssize_t@w{ }length, Py_ssize_t@w{ }*start, Py_ssize_t@w{ }*stop, Py_ssize_t@w{ }*step)

从切片对象 @emph{slice} 提取 start, stop 和 step 索引号，将序列长度视为 @emph{length}。 大于 @emph{length} 的序列号将被当作错误。

成功时返回 @code{0}，出错时返回 @code{-1} 并且不设置异常（除非某个序列号不为 @ref{204,,None} 且无法被转换为整数，在这种情况下会返回 @code{-1} 并且设置一个异常）。

你可能不会打算使用此函数。


在 3.2 版更改: 之前 @emph{slice} 形参的形参类型是 @code{PySliceObject*}。

@end deffn

@geindex PySlice_GetIndicesEx (C 函数)
@anchor{c-api/slice c PySlice_GetIndicesEx}@anchor{57f}
@deffn {C 函数} int PySlice_GetIndicesEx (PyObject@w{ }*slice, Py_ssize_t@w{ }length, Py_ssize_t@w{ }*start, Py_ssize_t@w{ }*stop, Py_ssize_t@w{ }*step, Py_ssize_t@w{ }*slicelength)

@ref{4153,,PySlice_GetIndices()} 的可用替代。 从切片对象 @emph{slice} 提取 start, stop 和 step 索引号，将序列长度视为 @emph{length}，并将切片的长度保存在 @emph{slicelength} 中，超出范围的索引号会以与普通切片一致的方式进行剪切。

成功时返回 @code{0}，出错时返回 @code{-1} 并且不设置异常。

@cartouche
@quotation 注解 
此函数对于可变大小序列来说是不安全的。 对它的调用应被替换为 @ref{53b,,PySlice_Unpack()} 和 @ref{53c,,PySlice_AdjustIndices()} 的组合，其中

@example
if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) @{
    // return error
@}
@end example

会被替换为

@example
if (PySlice_Unpack(slice, &start, &stop, &step) < 0) @{
    // return error
@}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
@end example
@end quotation
@end cartouche


在 3.2 版更改: 之前 @emph{slice} 形参的形参类型是 @code{PySliceObject*}。



在 3.6.1 版更改: 如果 @code{Py_LIMITED_API} 未设置或设置为 @code{0x03050400} 与 @code{0x03060000} 之间的值（不包括边界）或 @code{0x03060100} 或更大则 @code{PySlice_GetIndicesEx()} 会被实现为一个使用 @code{PySlice_Unpack()} 和 @code{PySlice_AdjustIndices()} 的宏。 参数 @emph{start}, @emph{stop} 和 @emph{step} 会被多被求值。



3.6.1 版后已移除: 如果 @code{Py_LIMITED_API} 设置为小于 @code{0x03050400} 或 @code{0x03060000} 与 @code{0x03060100} 之间的值（不包括边界）则 @code{PySlice_GetIndicesEx()} 为已弃用的函数。

@end deffn

@geindex PySlice_Unpack (C 函数)
@anchor{c-api/slice c PySlice_Unpack}@anchor{53b}
@deffn {C 函数} int PySlice_Unpack (PyObject@w{ }*slice, Py_ssize_t@w{ }*start, Py_ssize_t@w{ }*stop, Py_ssize_t@w{ }*step)

从切片对象中将 start, stop 和 step 数据成员提取为 C 整数。 会静默地将大于 @code{PY_SSIZE_T_MAX} 的值减小为 @code{PY_SSIZE_T_MAX}，静默地将小于 @code{PY_SSIZE_T_MIN} 的 start 和 stop 值增大为 @code{PY_SSIZE_T_MIN}，并静默地将小于 @code{-PY_SSIZE_T_MAX} 的 step 值增大为 @code{-PY_SSIZE_T_MAX}。

出错时返回 @code{-1}，成功时返回 @code{0}。


3.6.1 新版功能.

@end deffn

@geindex PySlice_AdjustIndices (C 函数)
@anchor{c-api/slice c PySlice_AdjustIndices}@anchor{53c}
@deffn {C 函数} Py_ssize_t PySlice_AdjustIndices (Py_ssize_t@w{ }length, Py_ssize_t@w{ }*start, Py_ssize_t@w{ }*stop, Py_ssize_t@w{ }step)

将 start/end 切片索引号根据指定的序列长度进行调整。 超出范围的索引号会以与普通切片一致的方式进行剪切。

返回切片的长度。 此操作总是会成功。 不会调用 Python 代码。


3.6.1 新版功能.

@end deffn

@node Ellipsis 对象,MemoryView 对象,切片对象,其他对象<2>
@anchor{c-api/slice ellipsis-object}@anchor{4154}
@subsubsection Ellipsis 对象


@geindex Py_Ellipsis (C 变量)
@anchor{c-api/slice c Py_Ellipsis}@anchor{4155}
@deffn {C 变量} PyObject *Py_Ellipsis

Python 的 @code{Ellipsis} 对象。 该对象没有任何方法。 它必须以与任何其他对象一样的方式遵循引用计数。 它与 @ref{3d5d,,Py_None} 一样属于单例对象。
@end deffn
@anchor{c-api/memoryview memoryview-objects}@anchor{3f78}
@geindex 对象; memoryview

@node MemoryView 对象,弱引用对象<2>,Ellipsis 对象,其他对象<2>
@anchor{c-api/memoryview doc}@anchor{4156}@anchor{c-api/memoryview id1}@anchor{4157}
@subsubsection MemoryView 对象


一个 @ref{38d,,memoryview} 对象C级别的 @ref{174c,,缓冲区接口} 暴露为一个可以像任何其他对象一样传递的 Python 对象。

@geindex PyMemoryView_FromObject (C 函数)
@anchor{c-api/memoryview c PyMemoryView_FromObject}@anchor{4158}
@deffn {C 函数} PyObject *PyMemoryView_FromObject (PyObject@w{ }*obj)
@emph{Return value: New reference.}
从提供缓冲区接口的对象创建 memoryview 对象。 如果 @emph{obj} 支持可写缓冲区导出，则 memoryview 对象将可以被读/写，否则它可能是只读的，也可以是导出器自行决定的读/写。
@end deffn

@geindex PyMemoryView_FromMemory (C 函数)
@anchor{c-api/memoryview c PyMemoryView_FromMemory}@anchor{ba9}
@deffn {C 函数} PyObject *PyMemoryView_FromMemory (char@w{ }*mem, Py_ssize_t@w{ }size, int@w{ }flags)
@emph{Return value: New reference.}
使用 @emph{mem} 作为底层缓冲区创建一个 memoryview 对象。 @emph{flags} 可以是 @code{PyBUF_READ} 或者 @code{PyBUF_WRITE} 之一.


3.3 新版功能.

@end deffn

@geindex PyMemoryView_FromBuffer (C 函数)
@anchor{c-api/memoryview c PyMemoryView_FromBuffer}@anchor{3f7c}
@deffn {C 函数} PyObject *PyMemoryView_FromBuffer (Py_buffer@w{ }*view)
@emph{Return value: New reference.}
创建一个包含给定缓冲区结构 @emph{view} 的 memoryview 对象。 对于简单的字节缓冲区，@ref{ba9,,PyMemoryView_FromMemory()} 是首选函数。
@end deffn

@geindex PyMemoryView_GetContiguous (C 函数)
@anchor{c-api/memoryview c PyMemoryView_GetContiguous}@anchor{4159}
@deffn {C 函数} PyObject *PyMemoryView_GetContiguous (PyObject@w{ }*obj, int@w{ }buffertype, char@w{ }order)
@emph{Return value: New reference.}
从定义缓冲区接口的对象创建一个 memoryview 对象 @ref{181d,,contiguous} 内存块（在 'C' 或 'F'ortran @emph{order} 中）。 如果内存是连续的，则 memoryview 对象指向原始内存。 否则，复制并且 memoryview 指向新的 bytes 对象。
@end deffn

@geindex PyMemoryView_Check (C 函数)
@anchor{c-api/memoryview c PyMemoryView_Check}@anchor{415a}
@deffn {C 函数} int PyMemoryView_Check (PyObject@w{ }*obj)

如果 @emph{obj} 是一个 memoryview 对象则返回真值。 目前不允许创建 @ref{38d,,memoryview} 的子类。 此函数总是会成功执行。
@end deffn

@geindex PyMemoryView_GET_BUFFER (C 函数)
@anchor{c-api/memoryview c PyMemoryView_GET_BUFFER}@anchor{415b}
@deffn {C 函数} Py_buffer *PyMemoryView_GET_BUFFER (PyObject@w{ }*mview)

返回指向 memoryview 的导出缓冲区私有副本的指针。 @emph{mview} @strong{必须} 是一个 memoryview 实例；这个宏不检查它的类型，你必须自己检查，否则你将面临崩溃风险。
@end deffn

@geindex PyMemoryView_GET_BASE (C 函数)
@anchor{c-api/memoryview c PyMemoryView_GET_BASE}@anchor{415c}
@deffn {C 函数} Py_buffer *PyMemoryView_GET_BASE (PyObject@w{ }*mview)

返回 memoryview 所基于的导出对象的指针，或者如果 memoryview 已由函数 @ref{ba9,,PyMemoryView_FromMemory()} 或 @ref{3f7c,,PyMemoryView_FromBuffer()} 创建则返回 @code{NULL}。 @emph{mview} @strong{必须} 是一个 memoryview 实例。
@end deffn

@node 弱引用对象<2>,Capsule 对象,MemoryView 对象,其他对象<2>
@anchor{c-api/weakref doc}@anchor{415d}@anchor{c-api/weakref weak-reference-objects}@anchor{415e}@anchor{c-api/weakref weakrefobjects}@anchor{415f}
@subsubsection 弱引用对象


Python 支持 “弱引用” 作为一类对象。具体来说，有两种直接实现弱引用的对象。第一种就是简单的引用对象，第二种尽可能地作用为一个原对象的代理。

@geindex PyWeakref_Check (C 函数)
@anchor{c-api/weakref c PyWeakref_Check}@anchor{4160}
@deffn {C 函数} int PyWeakref_Check (ob)

如果 @emph{ob} 是一个引用或代理对象则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyWeakref_CheckRef (C 函数)
@anchor{c-api/weakref c PyWeakref_CheckRef}@anchor{4161}
@deffn {C 函数} int PyWeakref_CheckRef (ob)

如果 @emph{ob} 是一个引用对象则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyWeakref_CheckProxy (C 函数)
@anchor{c-api/weakref c PyWeakref_CheckProxy}@anchor{4162}
@deffn {C 函数} int PyWeakref_CheckProxy (ob)

如果 @emph{ob} 是一个代理对象则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyWeakref_NewRef (C 函数)
@anchor{c-api/weakref c PyWeakref_NewRef}@anchor{f8b}
@deffn {C 函数} PyObject* PyWeakref_NewRef (PyObject@w{ }*ob, PyObject@w{ }*callback)
@emph{Return value: New reference.}
返回对象 @emph{ob} 的一个弱引用对象。 该函数总是会返回一个新引用，但不保证创建一个新的对象；它有可能返回一个现有的引用对象。 第二个形参 @emph{callback} 为一个可调用对象，它会在 @emph{ob} 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用对象本身。 @emph{callback} 也可以为 @code{None} 或 @code{NULL}。 如果 @emph{ob} 不是一个弱引用对象，或者如果 @emph{callback} 不是可调用对象，@code{None} 或 @code{NULL}，该函数将返回 @code{NULL} 并且引发 @ref{1ff,,TypeError}。
@end deffn

@geindex PyWeakref_NewProxy (C 函数)
@anchor{c-api/weakref c PyWeakref_NewProxy}@anchor{4163}
@deffn {C 函数} PyObject* PyWeakref_NewProxy (PyObject@w{ }*ob, PyObject@w{ }*callback)
@emph{Return value: New reference.}
返回对象 @emph{ob} 的一个弱引用代理对象。 该函数将总是返回一个新的引用，但不保证创建一个新的对象；它有可能返回一个现有的代理对象。 第二个形参 @emph{callback} 为一个可调用对象，它会在 @emph{ob} 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用对象本身。 @emph{callback} 也可以为 @code{None} 或 @code{NULL}。 如果 @emph{ob} 不是一个弱引用对象，或者如果 @emph{callback} 不是可调用对象，@code{None} 或 @code{NULL}，该函数将返回 @code{NULL} 并且引发 @ref{1ff,,TypeError}。
@end deffn

@geindex PyWeakref_GetObject (C 函数)
@anchor{c-api/weakref c PyWeakref_GetObject}@anchor{4164}
@deffn {C 函数} PyObject* PyWeakref_GetObject (PyObject@w{ }*ref)
@emph{Return value: Borrowed reference.}
返回弱引用对象 ref 的被引用对象。如果被引用对象不再存在，则返回 @code{Py_None}。

@cartouche
@quotation 注解 
该函数返回被引用对象的一个**借来的引用**。这意味着除非你很清楚在你使用期间这个对象不可能被销毁，否则你应该始终对该对象调用 @ref{396,,Py_INCREF()}。
@end quotation
@end cartouche
@end deffn

@geindex PyWeakref_GET_OBJECT (C 函数)
@anchor{c-api/weakref c PyWeakref_GET_OBJECT}@anchor{4165}
@deffn {C 函数} PyObject* PyWeakref_GET_OBJECT (PyObject@w{ }*ref)
@emph{Return value: Borrowed reference.}
类似 @ref{4164,,PyWeakref_GetObject()}，但实现为一个不做类型检查的宏。
@end deffn

@node Capsule 对象,生成器对象,弱引用对象<2>,其他对象<2>
@anchor{c-api/capsule doc}@anchor{4166}@anchor{c-api/capsule capsules}@anchor{3d85}@anchor{c-api/capsule id1}@anchor{4167}
@subsubsection Capsule 对象


@geindex 对象; Capsule

有关使用这些对象的更多信息请参阅 @ref{dbf,,给扩展模块提供C API}。


3.1 新版功能.


@geindex PyCapsule (C 类型)
@anchor{c-api/capsule c PyCapsule}@anchor{cda}
@deffn {C 类型} PyCapsule

这个 @ref{5bd,,PyObject} 的子类型代表一个隐藏的值，适用于需要将隐藏值（作为 @code{void*} 指针）通过 Python 代码传递到其他 C 代码的 C 扩展模块。 它常常被用来让在一个模块中定义的 C 函数指针在其他模块中可用，这样就可以使用常规导入机制来访问在动态加载的模块中定义的 C API。
@end deffn

@geindex PyCapsule_Destructor (C 类型)
@anchor{c-api/capsule c PyCapsule_Destructor}@anchor{4168}
@deffn {C 类型} PyCapsule_Destructor

Capsule 的析构器回调的类型。 定义如下：

@example
typedef void (*PyCapsule_Destructor)(PyObject *);
@end example

参阅 @ref{3d83,,PyCapsule_New()} 来获取 PyCapsule_Destructor 返回值的语义。
@end deffn

@geindex PyCapsule_CheckExact (C 函数)
@anchor{c-api/capsule c PyCapsule_CheckExact}@anchor{4169}
@deffn {C 函数} int PyCapsule_CheckExact (PyObject@w{ }*p)

如果参数是一个 @ref{cda,,PyCapsule} 则返回真值。 此函数总是会成功执行。
@end deffn

@geindex PyCapsule_New (C 函数)
@anchor{c-api/capsule c PyCapsule_New}@anchor{3d83}
@deffn {C 函数} PyObject* PyCapsule_New (void@w{ }*pointer, const char@w{ }*name, PyCapsule_Destructor@w{ }destructor)
@emph{Return value: New reference.}
创建一个封装了 @emph{pointer} 的 @ref{cda,,PyCapsule}。 @emph{pointer} 参考可以不为 @code{NULL}。

在失败时设置一个异常并返回 @code{NULL}。

字符串 @emph{name} 可以是 @code{NULL} 或是一个指向有效的 C 字符串的指针。 如果不为 @code{NULL}，则此字符串必须比 capsule 长（虽然也允许在 @emph{destructor} 中释放它。）

如果 @emph{destructor} 参数不为 @code{NULL}，则当它被销毁时将附带 capsule 作为参数来调用。

如果此 capsule 将被保存为一个模块的属性，则 @emph{name} 应当被指定为 @code{modulename.attributename}。 这将允许其他模块使用 @ref{3d84,,PyCapsule_Import()} 来导入此 capsule。
@end deffn

@geindex PyCapsule_GetPointer (C 函数)
@anchor{c-api/capsule c PyCapsule_GetPointer}@anchor{416a}
@deffn {C 函数} void* PyCapsule_GetPointer (PyObject@w{ }*capsule, const char@w{ }*name)

提取保存在 capsule 中的 @emph{pointer}。 在失败时设置一个异常并返回 @code{NULL}。

@emph{name} 形参必须与保存在 capsule 中的名称进行精确比较。 如果保存在 capsule 中的名称为 @code{NULL}，则传入的 @emph{name} 也必须为 @code{NULL}。 Python 会使用 C 函数 @code{strcmp()} 来比较 capsule 名称。
@end deffn

@geindex PyCapsule_GetDestructor (C 函数)
@anchor{c-api/capsule c PyCapsule_GetDestructor}@anchor{416b}
@deffn {C 函数} PyCapsule_Destructor PyCapsule_GetDestructor (PyObject@w{ }*capsule)

返回保存在 capsule 中的当前析构器。 在失败时设置一个异常并返回 @code{NULL}。

capsule 具有 @code{NULL} 析构器是合法的。 这会使得 @code{NULL} 返回码有些歧义；请使用 @ref{dbe,,PyCapsule_IsValid()} 或 @ref{3d58,,PyErr_Occurred()} 来消除歧义。
@end deffn

@geindex PyCapsule_GetContext (C 函数)
@anchor{c-api/capsule c PyCapsule_GetContext}@anchor{416c}
@deffn {C 函数} void* PyCapsule_GetContext (PyObject@w{ }*capsule)

返回保存在 capsule 中的当前上下文。 在失败时设置一个异常并返回 @code{NULL}。

capsule 具有 @code{NULL} 上下文是全法的。 这会使得 @code{NULL} 返回码有些歧义；请使用 @ref{dbe,,PyCapsule_IsValid()} 或 @ref{3d58,,PyErr_Occurred()} 来消除歧义。
@end deffn

@geindex PyCapsule_GetName (C 函数)
@anchor{c-api/capsule c PyCapsule_GetName}@anchor{416d}
@deffn {C 函数} const char* PyCapsule_GetName (PyObject@w{ }*capsule)

返回保存在 capsule 中的当前名称。 在失败时设置一个异常并返回 @code{NULL}。

capsule 具有 @code{NULL} 名称是合法的。 这会使得 @code{NULL} 返回码有些歧义；请使用 @ref{dbe,,PyCapsule_IsValid()} 或 @ref{3d58,,PyErr_Occurred()} 来消除歧义。
@end deffn

@geindex PyCapsule_Import (C 函数)
@anchor{c-api/capsule c PyCapsule_Import}@anchor{3d84}
@deffn {C 函数} void* PyCapsule_Import (const char@w{ }*name, int@w{ }no_block)

从一个模块的 capsule 属性导入指向 C 对象的指针。 @emph{name} 形参应当指定属性的完整名称，与 @code{module.attribute} 中的一致。 保存在 capsule 中的 @emph{name} 必须完全匹配此字符串。 如果 @emph{no_block} 为真值，则以无阻塞模式导入模块 (使用 @ref{aa9,,PyImport_ImportModuleNoBlock()})。 如果 @emph{no_block} 为假值，则以传统模式导入模块 (使用 @ref{d43,,PyImport_ImportModule()})。

成功时返回 capsule 的内部 @emph{指针}。  在失败时设置一个异常并返回 @code{NULL}。
@end deffn

@geindex PyCapsule_IsValid (C 函数)
@anchor{c-api/capsule c PyCapsule_IsValid}@anchor{dbe}
@deffn {C 函数} int PyCapsule_IsValid (PyObject@w{ }*capsule, const char@w{ }*name)

确定 @emph{capsule} 是否是一个有效的。 有效的 capsule 必须不为 @code{NULL}，传递 @ref{4169,,PyCapsule_CheckExact()}，在其中存储一个不为 @code{NULL} 的指针，并且其内部名称与 @emph{name} 形参相匹配。 （请参阅 @ref{416a,,PyCapsule_GetPointer()} 了解如何对 capsule 名称进行比较的有关信息。）

换句话说，如果 @ref{dbe,,PyCapsule_IsValid()} 返回真值，则任何对访问器（以 @code{PyCapsule_Get()} 开头的任何函数）的调用都保证会成功。

如果对象有效并且匹配传入的名称则返回非零值。 否则返回 @code{0}。 此函数一定不会失败。
@end deffn

@geindex PyCapsule_SetContext (C 函数)
@anchor{c-api/capsule c PyCapsule_SetContext}@anchor{416e}
@deffn {C 函数} int PyCapsule_SetContext (PyObject@w{ }*capsule, void@w{ }*context)

将 @emph{capsule} 内部的上下文指针设为 @emph{context}。

成功时返回 @code{0}。 失败时返回非零值并设置一个异常。
@end deffn

@geindex PyCapsule_SetDestructor (C 函数)
@anchor{c-api/capsule c PyCapsule_SetDestructor}@anchor{416f}
@deffn {C 函数} int PyCapsule_SetDestructor (PyObject@w{ }*capsule, PyCapsule_Destructor@w{ }destructor)

将 @emph{capsule} 内部的析构器设为 @emph{destructor}。

成功时返回 @code{0}。 失败时返回非零值并设置一个异常。
@end deffn

@geindex PyCapsule_SetName (C 函数)
@anchor{c-api/capsule c PyCapsule_SetName}@anchor{4170}
@deffn {C 函数} int PyCapsule_SetName (PyObject@w{ }*capsule, const char@w{ }*name)

将 @emph{capsule} 内部的名称设为 @emph{name}。 如果不为 @code{NULL}，则名称的存在期必须比 capsule 更长。 如果之前保存在 capsule 中的 @emph{name} 不为 @code{NULL}，则不会尝试释放它。

成功时返回 @code{0}。 失败时返回非零值并设置一个异常。
@end deffn

@geindex PyCapsule_SetPointer (C 函数)
@anchor{c-api/capsule c PyCapsule_SetPointer}@anchor{4171}
@deffn {C 函数} int PyCapsule_SetPointer (PyObject@w{ }*capsule, void@w{ }*pointer)

将 @emph{capsule} 内部的空指针设为 @emph{pointer}。 指针不可为 @code{NULL}。

成功时返回 @code{0}。 失败时返回非零值并设置一个异常。
@end deffn

@node 生成器对象,协程对象<2>,Capsule 对象,其他对象<2>
@anchor{c-api/gen doc}@anchor{4172}@anchor{c-api/gen gen-objects}@anchor{4173}@anchor{c-api/gen generator-objects}@anchor{4174}
@subsubsection 生成器对象


生成器对象是Python用来实现生成器迭代器的对象。它们通常通过迭代产生值的函数来创建，而不是显式调用 @ref{4175,,PyGen_New()} 或 @ref{4176,,PyGen_NewWithQualName()}。

@geindex PyGenObject (C 类型)
@anchor{c-api/gen c PyGenObject}@anchor{4177}
@deffn {C 类型} PyGenObject

用于生成器对象的C结构体。
@end deffn

@geindex PyGen_Type (C 变量)
@anchor{c-api/gen c PyGen_Type}@anchor{4178}
@deffn {C 变量} PyTypeObject PyGen_Type

与生成器对象对应的类型对​​象。
@end deffn

@geindex PyGen_Check (C 函数)
@anchor{c-api/gen c PyGen_Check}@anchor{4179}
@deffn {C 函数} int PyGen_Check (PyObject@w{ }*ob)

如果 @emph{ob} 是一个 generator 对象则返回真值；@emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyGen_CheckExact (C 函数)
@anchor{c-api/gen c PyGen_CheckExact}@anchor{417a}
@deffn {C 函数} int PyGen_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 的类型是 @ref{4178,,PyGen_Type} 则返回真值；@emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyGen_New (C 函数)
@anchor{c-api/gen c PyGen_New}@anchor{4175}
@deffn {C 函数} PyObject* PyGen_New (PyFrameObject@w{ }*frame)
@emph{Return value: New reference.}
基于 @emph{frame} 对象创建并返回一个新的生成器对象。 此函数会取走一个对 @emph{frame} 的引用。 参数必须不为 @code{NULL}。
@end deffn

@geindex PyGen_NewWithQualName (C 函数)
@anchor{c-api/gen c PyGen_NewWithQualName}@anchor{4176}
@deffn {C 函数} PyObject* PyGen_NewWithQualName (PyFrameObject@w{ }*frame, PyObject@w{ }*name, PyObject@w{ }*qualname)
@emph{Return value: New reference.}
基于 @emph{frame} 对象创建并返回一个新的生成器对象，其中 @code{__name__} 和 @code{__qualname__} 设为 @emph{name} 和 @emph{qualname}。 此函数会取走一个对 @emph{frame} 的引用。 @emph{frame} 参数必须不为 @code{NULL}。
@end deffn

@node 协程对象<2>,上下文变量对象,生成器对象,其他对象<2>
@anchor{c-api/coro doc}@anchor{417b}@anchor{c-api/coro coro-objects}@anchor{8c4}@anchor{c-api/coro coroutine-objects}@anchor{417c}
@subsubsection 协程对象



3.5 新版功能.


协程对象是使用 @code{async} 关键字声明的函数返回的。

@geindex PyCoroObject (C 类型)
@anchor{c-api/coro c PyCoroObject}@anchor{417d}
@deffn {C 类型} PyCoroObject

用于协程对象的C结构体。
@end deffn

@geindex PyCoro_Type (C 变量)
@anchor{c-api/coro c PyCoro_Type}@anchor{417e}
@deffn {C 变量} PyTypeObject PyCoro_Type

与协程对象对应的类型对​​象。
@end deffn

@geindex PyCoro_CheckExact (C 函数)
@anchor{c-api/coro c PyCoro_CheckExact}@anchor{417f}
@deffn {C 函数} int PyCoro_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 的类型是 @ref{417e,,PyCoro_Type} 则返回真值；@emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyCoro_New (C 函数)
@anchor{c-api/coro c PyCoro_New}@anchor{4180}
@deffn {C 函数} PyObject* PyCoro_New (PyFrameObject@w{ }*frame, PyObject@w{ }*name, PyObject@w{ }*qualname)
@emph{Return value: New reference.}
基于 @emph{frame} 对象创建并返回一个新的协程对象，其中 @code{__name__} 和 @code{__qualname__} 设为 @emph{name} 和 @emph{qualname}。 此函数会取得一个对 @emph{frame} 的引用。 @emph{frame} 参数必须不为 @code{NULL}。
@end deffn

@node 上下文变量对象,DateTime 对象<2>,协程对象<2>,其他对象<2>
@anchor{c-api/contextvars doc}@anchor{4181}@anchor{c-api/contextvars context-variables-objects}@anchor{4182}@anchor{c-api/contextvars contextvarsobjects}@anchor{450}
@subsubsection 上下文变量对象

@anchor{c-api/contextvars contextvarsobjects-pointertype-change}@anchor{5bc}

@cartouche
@quotation 注解 在 3.7.1 版更改: 
在 Python 3.7.1 中，所有上下文变量 C API 的签名被 @strong{更改} 为使用 @ref{5bd,,PyObject} 指针而不是 @ref{4183,,PyContext}, @ref{4184,,PyContextVar} 以及 @ref{4185,,PyContextToken}，例如:

@example
// in 3.7.0:
PyContext *PyContext_New(void);

// in 3.7.1+:
PyObject *PyContext_New(void);
@end example

请参阅 bpo-34762@footnote{https://bugs.python.org/issue?@@action=redirect&bpo=34762} 了解详情。
@end quotation
@end cartouche



3.7 新版功能.


本节深入介绍了 @ref{24,,contextvars} 模块的公用 C API。

@geindex PyContext (C 类型)
@anchor{c-api/contextvars c PyContext}@anchor{4183}
@deffn {C 类型} PyContext

用于表示 @ref{2625,,contextvars.Context} 对象的 C 结构体。
@end deffn

@geindex PyContextVar (C 类型)
@anchor{c-api/contextvars c PyContextVar}@anchor{4184}
@deffn {C 类型} PyContextVar

用于表示 @ref{2623,,contextvars.ContextVar} 对象的 C 结构体。
@end deffn

@geindex PyContextToken (C 类型)
@anchor{c-api/contextvars c PyContextToken}@anchor{4185}
@deffn {C 类型} PyContextToken

用于表示 @ref{262a,,contextvars.Token} 对象的 C 结构体。
@end deffn

@geindex PyContext_Type (C 变量)
@anchor{c-api/contextvars c PyContext_Type}@anchor{4186}
@deffn {C 变量} PyTypeObject PyContext_Type

表示 @emph{context} 类型的类型对象。
@end deffn

@geindex PyContextVar_Type (C 变量)
@anchor{c-api/contextvars c PyContextVar_Type}@anchor{4187}
@deffn {C 变量} PyTypeObject PyContextVar_Type

表示 @emph{context variable} 类型的类型对象。
@end deffn

@geindex PyContextToken_Type (C 变量)
@anchor{c-api/contextvars c PyContextToken_Type}@anchor{4188}
@deffn {C 变量} PyTypeObject PyContextToken_Type

表示 @emph{context variable token} 类型的类型对象。
@end deffn

类型检查宏：

@geindex PyContext_CheckExact (C 函数)
@anchor{c-api/contextvars c PyContext_CheckExact}@anchor{4189}
@deffn {C 函数} int PyContext_CheckExact (PyObject@w{ }*o)

如果 @emph{o} 的类型为 @ref{4186,,PyContext_Type} 则返回真值。 @emph{o} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyContextVar_CheckExact (C 函数)
@anchor{c-api/contextvars c PyContextVar_CheckExact}@anchor{418a}
@deffn {C 函数} int PyContextVar_CheckExact (PyObject@w{ }*o)

如果 @emph{o} 的类型为 @ref{4187,,PyContextVar_Type} 则返回真值。 @emph{o} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyContextToken_CheckExact (C 函数)
@anchor{c-api/contextvars c PyContextToken_CheckExact}@anchor{418b}
@deffn {C 函数} int PyContextToken_CheckExact (PyObject@w{ }*o)

如果 @emph{o} 的类型为 @ref{4188,,PyContextToken_Type} 则返回真值。 @emph{o} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

上下文对象管理函数:

@geindex PyContext_New (C 函数)
@anchor{c-api/contextvars c PyContext_New}@anchor{418c}
@deffn {C 函数} PyObject *PyContext_New (void)
@emph{Return value: New reference.}
创建一个新的空上下文对象。 如果发生错误则返回 @code{NULL}。
@end deffn

@geindex PyContext_Copy (C 函数)
@anchor{c-api/contextvars c PyContext_Copy}@anchor{418d}
@deffn {C 函数} PyObject *PyContext_Copy (PyObject@w{ }*ctx)
@emph{Return value: New reference.}
创建所传入的 @emph{ctx} 上下文对象的浅拷贝。 如果发生错误则返回 @code{NULL}。
@end deffn

@geindex PyContext_CopyCurrent (C 函数)
@anchor{c-api/contextvars c PyContext_CopyCurrent}@anchor{418e}
@deffn {C 函数} PyObject *PyContext_CopyCurrent (void)
@emph{Return value: New reference.}
创建当前线程上下文的浅拷贝。 如果发生错误则返回 @code{NULL}。
@end deffn

@geindex PyContext_Enter (C 函数)
@anchor{c-api/contextvars c PyContext_Enter}@anchor{418f}
@deffn {C 函数} int PyContext_Enter (PyObject@w{ }*ctx)

将 @emph{ctx} 设为当前线程的当前上下文。 成功时返回 @code{0}，出错时返回 @code{-1}。
@end deffn

@geindex PyContext_Exit (C 函数)
@anchor{c-api/contextvars c PyContext_Exit}@anchor{4190}
@deffn {C 函数} int PyContext_Exit (PyObject@w{ }*ctx)

取消激活 @emph{ctx} 上下文并将之前的上下文恢复为当前线程的当前上下文。 成功时返回 @code{0}，出错时返回 @code{-1}。
@end deffn

上下文变量函数:

@geindex PyContextVar_New (C 函数)
@anchor{c-api/contextvars c PyContextVar_New}@anchor{4191}
@deffn {C 函数} PyObject *PyContextVar_New (const char@w{ }*name, PyObject@w{ }*def)
@emph{Return value: New reference.}
创建一个新的 @code{ContextVar} 对象。 形参 @emph{name} 用于自我检查和调试目的。 形参 @emph{def} 为上下文变量指定默认值，或为 @code{NULL} 表示无默认值。 如果发生错误，这个函数会返回 @code{NULL}。
@end deffn

@geindex PyContextVar_Get (C 函数)
@anchor{c-api/contextvars c PyContextVar_Get}@anchor{4192}
@deffn {C 函数} int PyContextVar_Get (PyObject@w{ }*var, PyObject@w{ }*default_value, PyObject@w{ }**value)

获取上下文变量的值。如果在查找过程中发生错误，返回' ' -1 ' '，如果没有发生错误，无论是否找到值，都返回' ' 0 ' '，

如果找到上下文变量，@emph{value} 将是指向它的指针。 如果上下文变量 @emph{没有} 找到，@emph{value} 将指向：


@itemize -

@item 
@emph{default_value}，如果非`@w{`}NULL`@w{`};

@item 
@emph{var} 的默认值，如果不是 @code{NULL}；

@item 
@code{NULL}
@end itemize

除了返回 @code{NULL}，这个函数会返回一个新的引用。
@end deffn

@geindex PyContextVar_Set (C 函数)
@anchor{c-api/contextvars c PyContextVar_Set}@anchor{4193}
@deffn {C 函数} PyObject *PyContextVar_Set (PyObject@w{ }*var, PyObject@w{ }*value)
@emph{Return value: New reference.}
在当前上下文中将 @emph{var} 设为 @emph{value}。 返回针对此修改的新凭据对象，或者如果发生错误则返回 @code{NULL}。
@end deffn

@geindex PyContextVar_Reset (C 函数)
@anchor{c-api/contextvars c PyContextVar_Reset}@anchor{4194}
@deffn {C 函数} int PyContextVar_Reset (PyObject@w{ }*var, PyObject@w{ }*token)

将上下文变量 @emph{var} 的状态重置为它在返回 @emph{token} 的 @ref{4193,,PyContextVar_Set()} 被调用之前的状态。 此函数成功时返回 @code{0}，出错时返回 @code{-1}。
@end deffn

@node DateTime 对象<2>,类型注解对象,上下文变量对象,其他对象<2>
@anchor{c-api/datetime doc}@anchor{4195}@anchor{c-api/datetime datetime-objects}@anchor{4196}@anchor{c-api/datetime datetimeobjects}@anchor{4197}
@subsubsection DateTime 对象


@ref{30,,datetime} 模块提供了各种日期和时间对象。 在使用任何这些函数之前，必须在你的源码中包含头文件 @code{datetime.h} (请注意此文件并未包含在 @code{Python.h} 中)，并且宏 @code{PyDateTime_IMPORT} 必须被发起调用，通常是作为模块初始化函数的一部分。 这个宏会将指向特定 C 结构的指针放入一个静态变量 @code{PyDateTimeAPI} 中，它会由下面的宏来使用。

宏访问UTC单例:

@geindex PyDateTime_TimeZone_UTC (C 变量)
@anchor{c-api/datetime c PyDateTime_TimeZone_UTC}@anchor{542}
@deffn {C 变量} PyObject* PyDateTime_TimeZone_UTC

返回表示 UTC 的时区单例，与 @ref{1a70,,datetime.timezone.utc} 为同一对象。


3.7 新版功能.

@end deffn

类型检查宏：

@geindex PyDate_Check (C 函数)
@anchor{c-api/datetime c PyDate_Check}@anchor{4198}
@deffn {C 函数} int PyDate_Check (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DateType} 类型或 @code{PyDateTime_DateType} 的某个子类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyDate_CheckExact (C 函数)
@anchor{c-api/datetime c PyDate_CheckExact}@anchor{4199}
@deffn {C 函数} int PyDate_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DateType} 类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyDateTime_Check (C 函数)
@anchor{c-api/datetime c PyDateTime_Check}@anchor{419a}
@deffn {C 函数} int PyDateTime_Check (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DateTimeType} 类型或 @code{PyDateTime_DateTimeType} 的某个子类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyDateTime_CheckExact (C 函数)
@anchor{c-api/datetime c PyDateTime_CheckExact}@anchor{419b}
@deffn {C 函数} int PyDateTime_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DateTimeType} 类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyTime_Check (C 函数)
@anchor{c-api/datetime c PyTime_Check}@anchor{419c}
@deffn {C 函数} int PyTime_Check (PyObject@w{ }*ob)

如果 @emph{ob} 的类型是 @code{PyDateTime_TimeType} 或是 @code{PyDateTime_TimeType} 的子类型则返回真值。 @emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyTime_CheckExact (C 函数)
@anchor{c-api/datetime c PyTime_CheckExact}@anchor{419d}
@deffn {C 函数} int PyTime_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_TimeType} 类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyDelta_Check (C 函数)
@anchor{c-api/datetime c PyDelta_Check}@anchor{419e}
@deffn {C 函数} int PyDelta_Check (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DeltaType} 类型或 @code{PyDateTime_DeltaType} 的某个子类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyDelta_CheckExact (C 函数)
@anchor{c-api/datetime c PyDelta_CheckExact}@anchor{419f}
@deffn {C 函数} int PyDelta_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_DeltaType} 类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyTZInfo_Check (C 函数)
@anchor{c-api/datetime c PyTZInfo_Check}@anchor{41a0}
@deffn {C 函数} int PyTZInfo_Check (PyObject@w{ }*ob)

如果 @emph{ob} 的类型是 @code{PyDateTime_TZInfoType} 或是 @code{PyDateTime_TZInfoType} 的子类型则返回真值。 @emph{ob} 必须不为 @code{NULL}。 此函数总是会成功执行。
@end deffn

@geindex PyTZInfo_CheckExact (C 函数)
@anchor{c-api/datetime c PyTZInfo_CheckExact}@anchor{41a1}
@deffn {C 函数} int PyTZInfo_CheckExact (PyObject@w{ }*ob)

如果 @emph{ob} 为 @code{PyDateTime_TZInfoType} 类型则返回真值。 @emph{ob} 不能为 @code{NULL}。 此函数总是会成功执行。
@end deffn

用于创建对象的宏：

@geindex PyDate_FromDate (C 函数)
@anchor{c-api/datetime c PyDate_FromDate}@anchor{41a2}
@deffn {C 函数} PyObject* PyDate_FromDate (int@w{ }year, int@w{ }month, int@w{ }day)
@emph{Return value: New reference.}
返回指定年、月、日的 @ref{19d,,datetime.date} 对象。
@end deffn

@geindex PyDateTime_FromDateAndTime (C 函数)
@anchor{c-api/datetime c PyDateTime_FromDateAndTime}@anchor{41a3}
@deffn {C 函数} PyObject* PyDateTime_FromDateAndTime (int@w{ }year, int@w{ }month, int@w{ }day, int@w{ }hour, int@w{ }minute, int@w{ }second, int@w{ }usecond)
@emph{Return value: New reference.}
返回具有指定 year, month, day, hour, minute, second 和 microsecond 属性的 @ref{19f,,datetime.datetime} 对象。
@end deffn

@geindex PyDateTime_FromDateAndTimeAndFold (C 函数)
@anchor{c-api/datetime c PyDateTime_FromDateAndTimeAndFold}@anchor{41a4}
@deffn {C 函数} PyObject* PyDateTime_FromDateAndTimeAndFold (int@w{ }year, int@w{ }month, int@w{ }day, int@w{ }hour, int@w{ }minute, int@w{ }second, int@w{ }usecond, int@w{ }fold)
@emph{Return value: New reference.}
返回具有指定 year, month, day, hour, minute, second, microsecond 和 fold 属性的 @ref{19f,,datetime.datetime} 对象。


3.6 新版功能.

@end deffn

@geindex PyTime_FromTime (C 函数)
@anchor{c-api/datetime c PyTime_FromTime}@anchor{41a5}
@deffn {C 函数} PyObject* PyTime_FromTime (int@w{ }hour, int@w{ }minute, int@w{ }second, int@w{ }usecond)
@emph{Return value: New reference.}
返回具有指定 hour, minute, second and microsecond 属性的 @ref{5f5,,datetime.time} 对象。
@end deffn

@geindex PyTime_FromTimeAndFold (C 函数)
@anchor{c-api/datetime c PyTime_FromTimeAndFold}@anchor{41a6}
@deffn {C 函数} PyObject* PyTime_FromTimeAndFold (int@w{ }hour, int@w{ }minute, int@w{ }second, int@w{ }usecond, int@w{ }fold)
@emph{Return value: New reference.}
返回具有指定 hour, minute, second, microsecond 和 fold 属性的 @ref{5f5,,datetime.time} 对象。


3.6 新版功能.

@end deffn

@geindex PyDelta_FromDSU (C 函数)
@anchor{c-api/datetime c PyDelta_FromDSU}@anchor{41a7}
@deffn {C 函数} PyObject* PyDelta_FromDSU (int@w{ }days, int@w{ }seconds, int@w{ }useconds)
@emph{Return value: New reference.}
返回代表给定天、秒和微秒数的 @ref{2d1,,datetime.timedelta} 对象。 将执行正规化操作以使最终的微秒和秒数处在 @ref{2d1,,datetime.timedelta} 对象的文档指明的区间之内。
@end deffn

@geindex PyTimeZone_FromOffset (C 函数)
@anchor{c-api/datetime c PyTimeZone_FromOffset}@anchor{540}
@deffn {C 函数} PyObject* PyTimeZone_FromOffset (PyDateTime_DeltaType*@w{ }offset)
@emph{Return value: New reference.}
返回一个 @ref{ae9,,datetime.timezone} 对象，该对象具有以 @emph{offset} 参数表示 的未命名固定时差。


3.7 新版功能.

@end deffn

@geindex PyTimeZone_FromOffsetAndName (C 函数)
@anchor{c-api/datetime c PyTimeZone_FromOffsetAndName}@anchor{541}
@deffn {C 函数} PyObject* PyTimeZone_FromOffsetAndName (PyDateTime_DeltaType*@w{ }offset, PyUnicode*@w{ }name)
@emph{Return value: New reference.}
返回一个 @ref{ae9,,datetime.timezone} 对象，该对象具有以 @emph{offset} 参数表示的固定时差和时区名称 @emph{name}。


3.7 新版功能.

@end deffn

一些用来从 date 对象中提取字段的宏。 参数必须是 @code{PyDateTime_Date} 包括其子类 (例如 @code{PyDateTime_DateTime}) 的实例。 参数必须不为 @code{NULL}，并且类型不被会检查:

@geindex PyDateTime_GET_YEAR (C 函数)
@anchor{c-api/datetime c PyDateTime_GET_YEAR}@anchor{41a8}
@deffn {C 函数} int PyDateTime_GET_YEAR (PyDateTime_Date@w{ }*o)

以正整数的形式返回年份值。
@end deffn

@geindex PyDateTime_GET_MONTH (C 函数)
@anchor{c-api/datetime c PyDateTime_GET_MONTH}@anchor{41a9}
@deffn {C 函数} int PyDateTime_GET_MONTH (PyDateTime_Date@w{ }*o)

返回月，从0到12的整数。
@end deffn

@geindex PyDateTime_GET_DAY (C 函数)
@anchor{c-api/datetime c PyDateTime_GET_DAY}@anchor{41aa}
@deffn {C 函数} int PyDateTime_GET_DAY (PyDateTime_Date@w{ }*o)

返回日期，从0到31的整数。
@end deffn

一些用来从 datetime 对象中提取字段的宏。 参数必须是 @code{PyDateTime_DateTime} 包括其子类的实例。 参数必须不为 @code{NULL}，并且类型不会被检查:

@geindex PyDateTime_DATE_GET_HOUR (C 函数)
@anchor{c-api/datetime c PyDateTime_DATE_GET_HOUR}@anchor{41ab}
@deffn {C 函数} int PyDateTime_DATE_GET_HOUR (PyDateTime_DateTime@w{ }*o)

返回小时，从0到23的整数。
@end deffn

@geindex PyDateTime_DATE_GET_MINUTE (C 函数)
@anchor{c-api/datetime c PyDateTime_DATE_GET_MINUTE}@anchor{41ac}
@deffn {C 函数} int PyDateTime_DATE_GET_MINUTE (PyDateTime_DateTime@w{ }*o)

返回分钟，从0到59的整数。
@end deffn

@geindex PyDateTime_DATE_GET_SECOND (C 函数)
@anchor{c-api/datetime c PyDateTime_DATE_GET_SECOND}@anchor{41ad}
@deffn {C 函数} int PyDateTime_DATE_GET_SECOND (PyDateTime_DateTime@w{ }*o)

返回秒，从0到59的整数。
@end deffn

@geindex PyDateTime_DATE_GET_MICROSECOND (C 函数)
@anchor{c-api/datetime c PyDateTime_DATE_GET_MICROSECOND}@anchor{41ae}
@deffn {C 函数} int PyDateTime_DATE_GET_MICROSECOND (PyDateTime_DateTime@w{ }*o)

返回微秒，从0到999999的整数。
@end deffn

@geindex PyDateTime_DATE_GET_FOLD (C 函数)
@anchor{c-api/datetime c PyDateTime_DATE_GET_FOLD}@anchor{41af}
@deffn {C 函数} int PyDateTime_DATE_GET_FOLD (PyDateTime_DateTime@w{ }*o)

Return the fold, as an int from 0 through 1.


3.6 新版功能.

@end deffn

一些用来从 time 对象中提取字段的宏。 参数必须是 @code{PyDateTime_Time} 包括其子类的实例。 参数必须不为 @code{NULL}，并且类型不会被检查:

@geindex PyDateTime_TIME_GET_HOUR (C 函数)
@anchor{c-api/datetime c PyDateTime_TIME_GET_HOUR}@anchor{41b0}
@deffn {C 函数} int PyDateTime_TIME_GET_HOUR (PyDateTime_Time@w{ }*o)

返回小时，从0到23的整数。
@end deffn

@geindex PyDateTime_TIME_GET_MINUTE (C 函数)
@anchor{c-api/datetime c PyDateTime_TIME_GET_MINUTE}@anchor{41b1}
@deffn {C 函数} int PyDateTime_TIME_GET_MINUTE (PyDateTime_Time@w{ }*o)

返回分钟，从0到59的整数。
@end deffn

@geindex PyDateTime_TIME_GET_SECOND (C 函数)
@anchor{c-api/datetime c PyDateTime_TIME_GET_SECOND}@anchor{41b2}
@deffn {C 函数} int PyDateTime_TIME_GET_SECOND (PyDateTime_Time@w{ }*o)

返回秒，从0到59的整数。
@end deffn

@geindex PyDateTime_TIME_GET_MICROSECOND (C 函数)
@anchor{c-api/datetime c PyDateTime_TIME_GET_MICROSECOND}@anchor{41b3}
@deffn {C 函数} int PyDateTime_TIME_GET_MICROSECOND (PyDateTime_Time@w{ }*o)

返回微秒，从0到999999的整数。
@end deffn

@geindex PyDateTime_TIME_GET_FOLD (C 函数)
@anchor{c-api/datetime c PyDateTime_TIME_GET_FOLD}@anchor{41b4}
@deffn {C 函数} int PyDateTime_TIME_GET_FOLD (PyDateTime_Time@w{ }*o)

Return the fold, as an int from 0 through 1.


3.6 新版功能.

@end deffn

一些用来从 timedelta 对象中提取字段的宏。 参数必须是 @code{PyDateTime_Delta} 包括其子类的实例。 参数必须不为 @code{NULL}，并且类型不会被检查:

@geindex PyDateTime_DELTA_GET_DAYS (C 函数)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_DAYS}@anchor{41b5}
@deffn {C 函数} int PyDateTime_DELTA_GET_DAYS (PyDateTime_Delta@w{ }*o)

返回天数，从-999999999到999999999的整数。


3.3 新版功能.

@end deffn

@geindex PyDateTime_DELTA_GET_SECONDS (C 函数)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_SECONDS}@anchor{41b6}
@deffn {C 函数} int PyDateTime_DELTA_GET_SECONDS (PyDateTime_Delta@w{ }*o)

返回秒数，从0到86399的整数。


3.3 新版功能.

@end deffn

@geindex PyDateTime_DELTA_GET_MICROSECONDS (C 函数)
@anchor{c-api/datetime c PyDateTime_DELTA_GET_MICROSECONDS}@anchor{41b7}
@deffn {C 函数} int PyDateTime_DELTA_GET_MICROSECONDS (PyDateTime_Delta@w{ }*o)

返回微秒数，从0到999999的整数。


3.3 新版功能.

@end deffn

一些便于模块实现 DB API 的宏:

@geindex PyDateTime_FromTimestamp (C 函数)
@anchor{c-api/datetime c PyDateTime_FromTimestamp}@anchor{41b8}
@deffn {C 函数} PyObject* PyDateTime_FromTimestamp (PyObject@w{ }*args)
@emph{Return value: New reference.}
创建并返回一个给定元组参数的新 @ref{19f,,datetime.datetime} 对象，适合传给 @ref{f75,,datetime.datetime.fromtimestamp()}。
@end deffn

@geindex PyDate_FromTimestamp (C 函数)
@anchor{c-api/datetime c PyDate_FromTimestamp}@anchor{116f}
@deffn {C 函数} PyObject* PyDate_FromTimestamp (PyObject@w{ }*args)
@emph{Return value: New reference.}
创建并返回一个给定元组参数的新 @ref{19d,,datetime.date} 对象，适合传给 @ref{1a33,,datetime.date.fromtimestamp()}。
@end deffn

@node 类型注解对象,,DateTime 对象<2>,其他对象<2>
@anchor{c-api/typehints doc}@anchor{41b9}@anchor{c-api/typehints objects-for-type-hinting}@anchor{41ba}@anchor{c-api/typehints typehintobjects}@anchor{41bb}
@subsubsection 类型注解对象


Python 提供了多种内置类型用于类型注解，但只有 @ref{1030,,GenericAlias} 暴露给了 C。

@geindex Py_GenericAlias (C 函数)
@anchor{c-api/typehints c Py_GenericAlias}@anchor{41bc}
@deffn {C 函数} PyObject* Py_GenericAlias (PyObject@w{ }*origin, PyObject@w{ }*args)

创建一个 @ref{1030,,GenericAlias} 对象。相当于调用 Python 类 @ref{27d,,types.GenericAlias} 。参数 @emph{origin} 和 @emph{args} 分别设置 @code{GenericAlias}'s @code{__origin__} 属性和 @code{__args__} 属性。 @emph{origin} 应该是 @ref{3fe,,PyTypeObject*} 类型， @emph{args} 可以是 @ref{3ea3,,PyTupleObject*} 类型或者任意 @code{PyObject*} 类型。如果传递的 @emph{args} 不是一个元组，则自动构建一个 1 元元组，并将 @code{__args__} 设置为 @code{(args,)} 。对参数进行了最小限度的检查，因此即使 @emph{origin} 不是类型，函数也会成功。@code{GenericAlias} 的 @code{__parameters__} 属性是通过 @code{__args__} 懒加载的。如果失败，则触发异常并返回 @code{NULL} 。

下面是一个如何创建一个扩展类型泛型的例子:

@example
...
static PyMethodDef my_obj_methods[] = @{
    // Other methods.
    ...
    @{"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"@}
    ...
@}
@end example


@subsubheading 参见


数据模型的方法 @ref{440,,__class_getitem__()} 。



3.9 新版功能.

@end deffn

@geindex Py_GenericAliasType (C 变量)
@anchor{c-api/typehints c Py_GenericAliasType}@anchor{41bd}
@deffn {C 变量} PyTypeObject Py_GenericAliasType

由 @ref{41bc,,Py_GenericAlias()} 所返回的对象的 C 类型。等价于 Python 中的 @ref{27d,,types.GenericAlias} 。


3.9 新版功能.

@end deffn

@node 初始化，终结和线程,Python初始化配置,具体的对象层,Python/C API 参考手册
@anchor{c-api/init doc}@anchor{41be}@anchor{c-api/init initialization}@anchor{41bf}@anchor{c-api/init initialization-finalization-and-threads}@anchor{41c0}
@section 初始化，终结和线程


请参阅 @ref{2bd,,Python 初始化配置} 。

@menu
* 在Python初始化之前:: 
* 全局配置变量:: 
* Initializing and finalizing the interpreter:: 
* Process-wide parameters:: 
* 线程状态和全局解释器锁:: 
* 子解释器支持:: 
* 异步通知:: 
* 分析和跟踪:: 
* 高级调试器支持:: 
* 线程本地存储支持:: 

@end menu

@node 在Python初始化之前,全局配置变量,,初始化，终结和线程
@anchor{c-api/init before-python-initialization}@anchor{41c1}@anchor{c-api/init pre-init-safe}@anchor{545}
@subsection 在Python初始化之前


在一个植入了 Python 的应用程序中，@ref{210,,Py_Initialize()} 函数必须在任何其他 Python/C API 函数之前被调用；例外的只有个别函数和 @ref{41c2,,全局配置变量}。

在初始化Python之前，可以安全地调用以下函数：


@itemize *

@item 
配置函数：


@itemize *

@item 
@ref{fe7,,PyImport_AppendInittab()}

@item 
@ref{fe8,,PyImport_ExtendInittab()}

@item 
@code{PyInitFrozenExtensions()}

@item 
@ref{41c3,,PyMem_SetAllocator()}

@item 
@ref{60c,,PyMem_SetupDebugHooks()}

@item 
@ref{41c4,,PyObject_SetArenaAllocator()}

@item 
@ref{3a4,,Py_SetPath()}

@item 
@ref{113b,,Py_SetProgramName()}

@item 
@ref{113a,,Py_SetPythonHome()}

@item 
@ref{a13,,Py_SetStandardStreamEncoding()}

@item 
@ref{5b6,,PySys_AddWarnOption()}

@item 
@ref{3ea1,,PySys_AddXOption()}

@item 
@ref{3e9a,,PySys_ResetWarnOptions()}
@end itemize

@item 
信息函数：


@itemize *

@item 
@ref{3e0f,,Py_IsInitialized()}

@item 
@ref{41c5,,PyMem_GetAllocator()}

@item 
@ref{41c6,,PyObject_GetArenaAllocator()}

@item 
@ref{e67,,Py_GetBuildInfo()}

@item 
@ref{41c7,,Py_GetCompiler()}

@item 
@ref{41c8,,Py_GetCopyright()}

@item 
@ref{41c9,,Py_GetPlatform()}

@item 
@ref{41ca,,Py_GetVersion()}
@end itemize

@item 
工具


@itemize *

@item 
@ref{547,,Py_DecodeLocale()}
@end itemize

@item 
内存分配器：


@itemize *

@item 
@ref{a57,,PyMem_RawMalloc()}

@item 
@ref{a58,,PyMem_RawRealloc()}

@item 
@ref{89d,,PyMem_RawCalloc()}

@item 
@ref{3e94,,PyMem_RawFree()}
@end itemize
@end itemize

@cartouche
@quotation 注解 
以下函数 @strong{不应该} 在 @ref{210,,Py_Initialize()}: @ref{548,,Py_EncodeLocale()}, @ref{3e0c,,Py_GetPath()}, @ref{3e0d,,Py_GetPrefix()}, @ref{3e0e,,Py_GetExecPrefix()}, @ref{3a6,,Py_GetProgramFullPath()}, @ref{41cb,,Py_GetPythonHome()}, @ref{3a7,,Py_GetProgramName()} 和 @ref{20d,,PyEval_InitThreads()} 前调用。
@end quotation
@end cartouche

@node 全局配置变量,Initializing and finalizing the interpreter,在Python初始化之前,初始化，终结和线程
@anchor{c-api/init global-conf-vars}@anchor{41c2}@anchor{c-api/init global-configuration-variables}@anchor{41cc}
@subsection 全局配置变量


Python 有负责控制全局配置中不同特性和选项的变量。这些标志默认被 @ref{149f,,命令行选项}。

当一个选项设置一个旗标时，该旗标的值将是设置选项的次数。 例如，@code{-b} 会将 @ref{5b7,,Py_BytesWarningFlag} 设为 1 而 @code{-bb} 会将 @ref{5b7,,Py_BytesWarningFlag} 设为 2.

@geindex Py_BytesWarningFlag (C 变量)
@anchor{c-api/init c Py_BytesWarningFlag}@anchor{5b7}
@deffn {C 变量} int Py_BytesWarningFlag

Issue a warning when comparing @ref{172,,bytes} or @ref{173,,bytearray} with
@ref{206,,str} or @ref{172,,bytes} with @ref{205,,int}.  Issue an error if greater
or equal to @code{2}.

由 @ref{522,,-b} 选项设置。
@end deffn

@geindex Py_DebugFlag (C 变量)
@anchor{c-api/init c Py_DebugFlag}@anchor{41cd}
@deffn {C 变量} int Py_DebugFlag

开启解析器调试输出（限专家使用，依赖于编译选项）。

由 @ref{14a6,,-d} 选项和 
@geindex PYTHONDEBUG
@geindex 环境变量; PYTHONDEBUG
@ref{14a7,,PYTHONDEBUG} 环境变量设置。
@end deffn

@geindex Py_DontWriteBytecodeFlag (C 变量)
@anchor{c-api/init c Py_DontWriteBytecodeFlag}@anchor{41ce}
@deffn {C 变量} int Py_DontWriteBytecodeFlag

如果设置为非零, Python 不会在导入源代码时尝试写入 @code{.pyc} 文件

由 @ref{e06,,-B} 选项和 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE} 环境变量设置。
@end deffn

@geindex Py_FrozenFlag (C 变量)
@anchor{c-api/init c Py_FrozenFlag}@anchor{41cf}
@deffn {C 变量} int Py_FrozenFlag

Suppress error messages when calculating the module search path in
@ref{3e0c,,Py_GetPath()}.

Private flag used by @code{_freeze_importlib} and @code{frozenmain} programs.
@end deffn

@geindex Py_HashRandomizationFlag (C 变量)
@anchor{c-api/init c Py_HashRandomizationFlag}@anchor{41d0}
@deffn {C 变量} int Py_HashRandomizationFlag

Set to @code{1} if the 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} environment variable is set to
a non-empty string.

If the flag is non-zero, read the 
@geindex PYTHONHASHSEED
@geindex 环境变量; PYTHONHASHSEED
@ref{aad,,PYTHONHASHSEED} environment
variable to initialize the secret hash seed.
@end deffn

@geindex Py_IgnoreEnvironmentFlag (C 变量)
@anchor{c-api/init c Py_IgnoreEnvironmentFlag}@anchor{5bb}
@deffn {C 变量} int Py_IgnoreEnvironmentFlag

忽略所有 
@geindex PYTHON*
@geindex 环境变量; PYTHON*
@code{PYTHON*} 环境变量，例如可能已设置的 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} 和 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME}。

由 @ref{231,,-E}  和 @ref{232,,-I} 选项设置。
@end deffn

@geindex Py_InspectFlag (C 变量)
@anchor{c-api/init c Py_InspectFlag}@anchor{41d1}
@deffn {C 变量} int Py_InspectFlag

When a script is passed as first argument or the @ref{136f,,-c} option is used,
enter interactive mode after executing the script or the command, even when
@ref{427,,sys.stdin} does not appear to be a terminal.

Set by the @ref{ee9,,-i} option and the 
@geindex PYTHONINSPECT
@geindex 环境变量; PYTHONINSPECT
@ref{ee8,,PYTHONINSPECT} environment
variable.
@end deffn

@geindex Py_InteractiveFlag (C 变量)
@anchor{c-api/init c Py_InteractiveFlag}@anchor{3e8e}
@deffn {C 变量} int Py_InteractiveFlag

由 @ref{ee9,,-i} 选项设置。
@end deffn

@geindex Py_IsolatedFlag (C 变量)
@anchor{c-api/init c Py_IsolatedFlag}@anchor{41d2}
@deffn {C 变量} int Py_IsolatedFlag

Run Python in isolated mode. In isolated mode @ref{262,,sys.path} contains
neither the script's directory nor the user's site-packages directory.

由 @ref{232,,-I} 选项设置。


3.4 新版功能.

@end deffn

@geindex Py_LegacyWindowsFSEncodingFlag (C 变量)
@anchor{c-api/init c Py_LegacyWindowsFSEncodingFlag}@anchor{3e93}
@deffn {C 变量} int Py_LegacyWindowsFSEncodingFlag

If the flag is non-zero, use the @code{mbcs} encoding instead of the UTF-8
encoding for the filesystem encoding.

Set to @code{1} if the 
@geindex PYTHONLEGACYWINDOWSFSENCODING
@geindex 环境变量; PYTHONLEGACYWINDOWSFSENCODING
@ref{5f9,,PYTHONLEGACYWINDOWSFSENCODING} environment
variable is set to a non-empty string.

有关更多详细信息，请参阅 
@geindex Python 提高建议; PEP 529
PEP 529@footnote{https://www.python.org/dev/peps/pep-0529}。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex Py_LegacyWindowsStdioFlag (C 变量)
@anchor{c-api/init c Py_LegacyWindowsStdioFlag}@anchor{41d3}
@deffn {C 变量} int Py_LegacyWindowsStdioFlag

If the flag is non-zero, use @ref{d74,,io.FileIO} instead of
@code{WindowsConsoleIO} for @ref{fd,,sys} standard streams.

Set to @code{1} if the 
@geindex PYTHONLEGACYWINDOWSSTDIO
@geindex 环境变量; PYTHONLEGACYWINDOWSSTDIO
@ref{5fc,,PYTHONLEGACYWINDOWSSTDIO} environment
variable is set to a non-empty string.

有关更多详细信息，请参阅 
@geindex Python 提高建议; PEP 528
PEP 528@footnote{https://www.python.org/dev/peps/pep-0528}。

@ref{14c1,,可用性}: Windows。
@end deffn

@geindex Py_NoSiteFlag (C 变量)
@anchor{c-api/init c Py_NoSiteFlag}@anchor{41d4}
@deffn {C 变量} int Py_NoSiteFlag

禁用 @ref{eb,,site} 的导入及其所附带的基于站点对 @ref{262,,sys.path} 的操作。 如果 @ref{eb,,site} 会在稍后被显式地导入也会禁用这些操作 (如果你希望触发它们则应调用 @ref{14ab,,site.main()})。

由 @ref{c00,,-S} 选项设置。
@end deffn

@geindex Py_NoUserSiteDirectory (C 变量)
@anchor{c-api/init c Py_NoUserSiteDirectory}@anchor{41d5}
@deffn {C 变量} int Py_NoUserSiteDirectory

不要将 @ref{14aa,,用户 site-packages 目录} 添加到 @ref{262,,sys.path}。

Set by the @ref{de3,,-s} and @ref{232,,-I} options, and the
@geindex PYTHONNOUSERSITE
@geindex 环境变量; PYTHONNOUSERSITE
@ref{de4,,PYTHONNOUSERSITE} environment variable.
@end deffn

@geindex Py_OptimizeFlag (C 变量)
@anchor{c-api/init c Py_OptimizeFlag}@anchor{246d}
@deffn {C 变量} int Py_OptimizeFlag

Set by the @ref{788,,-O} option and the 
@geindex PYTHONOPTIMIZE
@geindex 环境变量; PYTHONOPTIMIZE
@ref{14a8,,PYTHONOPTIMIZE} environment
variable.
@end deffn

@geindex Py_QuietFlag (C 变量)
@anchor{c-api/init c Py_QuietFlag}@anchor{41d6}
@deffn {C 变量} int Py_QuietFlag

即使在交互模式下也不显示版权和版本信息。

由 @ref{14a9,,-q} 选项设置。


3.2 新版功能.

@end deffn

@geindex Py_UnbufferedStdioFlag (C 变量)
@anchor{c-api/init c Py_UnbufferedStdioFlag}@anchor{41d7}
@deffn {C 变量} int Py_UnbufferedStdioFlag

强制 stdout 和 stderr 流不带缓冲。

Set by the @ref{10e6,,-u} option and the 
@geindex PYTHONUNBUFFERED
@geindex 环境变量; PYTHONUNBUFFERED
@ref{10e7,,PYTHONUNBUFFERED}
environment variable.
@end deffn

@geindex Py_VerboseFlag (C 变量)
@anchor{c-api/init c Py_VerboseFlag}@anchor{41d8}
@deffn {C 变量} int Py_VerboseFlag

Print a message each time a module is initialized, showing the place
(filename or built-in module) from which it is loaded.  If greater or equal
to @code{2}, print a message for each file that is checked for when
searching for a module. Also provides information on module cleanup at exit.

Set by the @ref{e55,,-v} option and the 
@geindex PYTHONVERBOSE
@geindex 环境变量; PYTHONVERBOSE
@ref{14ac,,PYTHONVERBOSE} environment
variable.
@end deffn

@node Initializing and finalizing the interpreter,Process-wide parameters,全局配置变量,初始化，终结和线程
@anchor{c-api/init initializing-and-finalizing-the-interpreter}@anchor{41d9}
@subsection Initializing and finalizing the interpreter


@geindex Py_Initialize (C 函数)
@anchor{c-api/init c Py_Initialize}@anchor{210}
@deffn {C 函数} void Py_Initialize ()

@geindex Py_SetProgramName()
@geindex PyEval_InitThreads()
@geindex modules (in module sys)
@geindex path (in module sys)
@geindex 模块; builtins
@geindex 模块; __main__
@geindex 模块; sys
@geindex module; search; path
@geindex PySys_SetArgv()
@geindex PySys_SetArgvEx()
@geindex Py_FinalizeEx()

Initialize the Python interpreter.  In an application embedding  Python,
this should be called before using any other Python/C API functions; see
@ref{545,,Before Python Initialization} for the few exceptions.

This initializes
the table of loaded modules (@code{sys.modules}), and creates the fundamental
modules @ref{12,,builtins}, @ref{1,,__main__} and @ref{fd,,sys}.  It also initializes
the module search path (@code{sys.path}). It does not set @code{sys.argv}; use
@ref{ccd,,PySys_SetArgvEx()} for that.  This is a no-op when called for a second time
(without calling @ref{6ca,,Py_FinalizeEx()} first).  There is no return value; it is a
fatal error if the initialization fails.

@cartouche
@quotation 注解 
在 Windows 上，将控制台模式从 @code{O_TEXT} 改为 @code{O_BINARY}，这还将影响使用 C 运行时的非 Python 的控制台使用。
@end quotation
@end cartouche
@end deffn

@geindex Py_InitializeEx (C 函数)
@anchor{c-api/init c Py_InitializeEx}@anchor{41da}
@deffn {C 函数} void Py_InitializeEx (int@w{ }initsigs)

This function works like @ref{210,,Py_Initialize()} if @emph{initsigs} is @code{1}. If
@emph{initsigs} is @code{0}, it skips initialization registration of signal handlers, which
might be useful when Python is embedded.
@end deffn

@geindex Py_IsInitialized (C 函数)
@anchor{c-api/init c Py_IsInitialized}@anchor{3e0f}
@deffn {C 函数} int Py_IsInitialized ()

Return true (nonzero) when the Python interpreter has been initialized, false
(zero) if not.  After @ref{6ca,,Py_FinalizeEx()} is called, this returns false until
@ref{210,,Py_Initialize()} is called again.
@end deffn

@geindex Py_FinalizeEx (C 函数)
@anchor{c-api/init c Py_FinalizeEx}@anchor{6ca}
@deffn {C 函数} int Py_FinalizeEx ()

Undo all initializations made by @ref{210,,Py_Initialize()} and subsequent use of
Python/C API functions, and destroy all sub-interpreters (see
@ref{41db,,Py_NewInterpreter()} below) that were created and not yet destroyed since
the last call to @ref{210,,Py_Initialize()}.  Ideally, this frees all memory
allocated by the Python interpreter.  This is a no-op when called for a second
time (without calling @ref{210,,Py_Initialize()} again first).  Normally the
return value is @code{0}.  If there were errors during finalization
(flushing buffered data), @code{-1} is returned.

This function is provided for a number of reasons.  An embedding application
might want to restart Python without having to restart the application itself.
An application that has loaded the Python interpreter from a dynamically
loadable library (or DLL) might want to free all memory allocated by Python
before unloading the DLL. During a hunt for memory leaks in an application a
developer might want to free all memory allocated by Python before exiting from
the application.

@strong{Bugs and caveats:} The destruction of modules and objects in modules is done
in random order; this may cause destructors (@ref{a0d,,__del__()} methods) to fail
when they depend on other objects (even functions) or modules.  Dynamically
loaded extension modules loaded by Python are not unloaded.  Small amounts of
memory allocated by the Python interpreter may not be freed (if you find a leak,
please report it).  Memory tied up in circular references between objects is not
freed.  Some memory allocated by extension modules may not be freed.  Some
extensions may not work properly if their initialization routine is called more
than once; this can happen if an application calls @ref{210,,Py_Initialize()} and
@ref{6ca,,Py_FinalizeEx()} more than once.

Raises an @ref{fec,,auditing event} @code{cpython._PySys_ClearAuditHooks} with no arguments.


3.6 新版功能.

@end deffn

@geindex Py_Finalize (C 函数)
@anchor{c-api/init c Py_Finalize}@anchor{dbb}
@deffn {C 函数} void Py_Finalize ()

This is a backwards-compatible version of @ref{6ca,,Py_FinalizeEx()} that
disregards the return value.
@end deffn

@node Process-wide parameters,线程状态和全局解释器锁,Initializing and finalizing the interpreter,初始化，终结和线程
@anchor{c-api/init process-wide-parameters}@anchor{41dc}
@subsection Process-wide parameters


@geindex Py_SetStandardStreamEncoding (C 函数)
@anchor{c-api/init c Py_SetStandardStreamEncoding}@anchor{a13}
@deffn {C 函数} int Py_SetStandardStreamEncoding (const char@w{ }*encoding, const char@w{ }*errors)

@geindex Py_Initialize()
@geindex main()
@geindex stdin; stdout; sdterr

This function should be called before @ref{210,,Py_Initialize()}, if it is
called at all. It specifies which encoding and error handling to use
with standard IO, with the same meanings as in @ref{170,,str.encode()}.

It overrides 
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} values, and allows embedding code
to control IO encoding when the environment variable does not work.

@emph{encoding} and/or @emph{errors} may be @code{NULL} to use
@geindex PYTHONIOENCODING
@geindex 环境变量; PYTHONIOENCODING
@ref{a1d,,PYTHONIOENCODING} and/or default values (depending on other
settings).

Note that @ref{1eb,,sys.stderr} always uses the "backslashreplace" error
handler, regardless of this (or any other) setting.

If @ref{6ca,,Py_FinalizeEx()} is called, this function will need to be called
again in order to affect subsequent calls to @ref{210,,Py_Initialize()}.

Returns @code{0} if successful, a nonzero value on error (e.g. calling after the
interpreter has already been initialized).


3.4 新版功能.

@end deffn

@geindex Py_SetProgramName (C 函数)
@anchor{c-api/init c Py_SetProgramName}@anchor{113b}
@deffn {C 函数} void Py_SetProgramName (const wchar_t@w{ }*name)

@geindex Py_Initialize()
@geindex main()
@geindex Py_GetPath()

This function should be called before @ref{210,,Py_Initialize()} is called for
the first time, if it is called at all.  It tells the interpreter the value
of the @code{argv[0]} argument to the @code{main()} function of the program
(converted to wide characters).
This is used by @ref{3e0c,,Py_GetPath()} and some other functions below to find
the Python run-time libraries relative to the interpreter executable.  The
default value is @code{'python'}.  The argument should point to a
zero-terminated wide character string in static storage whose contents will not
change for the duration of the program's execution.  No code in the Python
interpreter will change the contents of this storage.

Use @ref{547,,Py_DecodeLocale()} to decode a bytes string to get a
@code{wchar_*} string.
@end deffn

@geindex Py_GetProgramName (C 函数)
@anchor{c-api/init c Py_GetProgramName}@anchor{3a7}
@deffn {C 函数} wchar* Py_GetProgramName ()

@geindex Py_SetProgramName()

Return the program name set with @ref{113b,,Py_SetProgramName()}, or the default.
The returned string points into static storage; the caller should not modify its
value.
@end deffn

@geindex Py_GetPrefix (C 函数)
@anchor{c-api/init c Py_GetPrefix}@anchor{3e0d}
@deffn {C 函数} wchar_t* Py_GetPrefix ()

Return the @emph{prefix} for installed platform-independent files. This is derived
through a number of complicated rules from the program name set with
@ref{113b,,Py_SetProgramName()} and some environment variables; for example, if the
program name is @code{'/usr/local/bin/python'}, the prefix is @code{'/usr/local'}. The
returned string points into static storage; the caller should not modify its
value.  This corresponds to the @code{prefix} variable in the top-level
@code{Makefile} and the @code{--prefix} argument to the @code{configure}
script at build time.  The value is available to Python code as @code{sys.prefix}.
It is only useful on Unix.  See also the next function.
@end deffn

@geindex Py_GetExecPrefix (C 函数)
@anchor{c-api/init c Py_GetExecPrefix}@anchor{3e0e}
@deffn {C 函数} wchar_t* Py_GetExecPrefix ()

Return the @emph{exec-prefix} for installed platform-@emph{dependent} files.  This is
derived through a number of complicated rules from the program name set with
@ref{113b,,Py_SetProgramName()} and some environment variables; for example, if the
program name is @code{'/usr/local/bin/python'}, the exec-prefix is
@code{'/usr/local'}.  The returned string points into static storage; the caller
should not modify its value.  This corresponds to the @code{exec_prefix}
variable in the top-level @code{Makefile} and the @code{--exec-prefix}
argument to the @code{configure} script at build  time.  The value is
available to Python code as @code{sys.exec_prefix}.  It is only useful on Unix.

Background: The exec-prefix differs from the prefix when platform dependent
files (such as executables and shared libraries) are installed in a different
directory tree.  In a typical installation, platform dependent files may be
installed in the @code{/usr/local/plat} subtree while platform independent may
be installed in @code{/usr/local}.

Generally speaking, a platform is a combination of hardware and software
families, e.g.  Sparc machines running the Solaris 2.x operating system are
considered the same platform, but Intel machines running Solaris 2.x are another
platform, and Intel machines running Linux are yet another platform.  Different
major revisions of the same operating system generally also form different
platforms.  Non-Unix operating systems are a different story; the installation
strategies on those systems are so different that the prefix and exec-prefix are
meaningless, and set to the empty string. Note that compiled Python bytecode
files are platform independent (but not independent from the Python version by
which they were compiled!).

System administrators will know how to configure the @code{mount} or
@code{automount} programs to share @code{/usr/local} between platforms
while having @code{/usr/local/plat} be a different filesystem for each
platform.
@end deffn

@geindex Py_GetProgramFullPath (C 函数)
@anchor{c-api/init c Py_GetProgramFullPath}@anchor{3a6}
@deffn {C 函数} wchar_t* Py_GetProgramFullPath ()

@geindex Py_SetProgramName()
@geindex executable (in module sys)

Return the full program name of the Python executable; this is  computed as a
side-effect of deriving the default module search path  from the program name
(set by @ref{113b,,Py_SetProgramName()} above). The returned string points into
static storage; the caller should not modify its value.  The value is available
to Python code as @code{sys.executable}.
@end deffn

@geindex Py_GetPath (C 函数)
@anchor{c-api/init c Py_GetPath}@anchor{3e0c}
@deffn {C 函数} wchar_t* Py_GetPath ()

@geindex module; search; path
@geindex path (in module sys)
@geindex Py_SetPath()

Return the default module search path; this is computed from the program name
(set by @ref{113b,,Py_SetProgramName()} above) and some environment variables.
The returned string consists of a series of directory names separated by a
platform dependent delimiter character.  The delimiter character is @code{':'}
on Unix and macOS, @code{';'} on Windows.  The returned string points into
static storage; the caller should not modify its value.  The list
@ref{262,,sys.path} is initialized with this value on interpreter startup; it
can be (and usually is) modified later to change the search path for loading
modules.

@c XXX should give the exact rules
@end deffn

@geindex Py_SetPath (C 函数)
@anchor{c-api/init c Py_SetPath}@anchor{3a4}
@deffn {C 函数} void Py_SetPath (const wchar_t@w{ }*)

@geindex module; search; path
@geindex path (in module sys)
@geindex Py_GetPath()

Set the default module search path.  If this function is called before
@ref{210,,Py_Initialize()}, then @ref{3e0c,,Py_GetPath()} won't attempt to compute a
default search path but uses the one provided instead.  This is useful if
Python is embedded by an application that has full knowledge of the location
of all modules.  The path components should be separated by the platform
dependent delimiter character, which is @code{':'} on Unix and macOS, @code{';'}
on Windows.

This also causes @ref{3a5,,sys.executable} to be set to the program
full path (see @ref{3a6,,Py_GetProgramFullPath()}) and for @ref{3686,,sys.prefix} and
@ref{3687,,sys.exec_prefix} to be empty.  It is up to the caller to modify these
if required after calling @ref{210,,Py_Initialize()}.

Use @ref{547,,Py_DecodeLocale()} to decode a bytes string to get a
@code{wchar_*} string.

The path argument is copied internally, so the caller may free it after the
call completes.


在 3.8 版更改: The program full path is now used for @ref{3a5,,sys.executable}, instead
of the program name.

@end deffn

@geindex Py_GetVersion (C 函数)
@anchor{c-api/init c Py_GetVersion}@anchor{41ca}
@deffn {C 函数} const char* Py_GetVersion ()

Return the version of this Python interpreter.  This is a string that looks
something like

@example
"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
@end example

@geindex version (in module sys)

The first word (up to the first space character) is the current Python version;
the first characters are the major and minor version separated by a
period.  The returned string points into static storage; the caller should not
modify its value.  The value is available to Python code as @ref{6d4,,sys.version}.
@end deffn

@geindex Py_GetPlatform (C 函数)
@anchor{c-api/init c Py_GetPlatform}@anchor{41c9}
@deffn {C 函数} const char* Py_GetPlatform ()

@geindex platform (in module sys)

Return the platform identifier for the current platform.  On Unix, this is
formed from the "official" name of the operating system, converted to lower
case, followed by the major revision number; e.g., for Solaris 2.x, which is
also known as SunOS 5.x, the value is @code{'sunos5'}.  On macOS, it is
@code{'darwin'}.  On Windows, it is @code{'win'}.  The returned string points into
static storage; the caller should not modify its value.  The value is available
to Python code as @code{sys.platform}.
@end deffn

@geindex Py_GetCopyright (C 函数)
@anchor{c-api/init c Py_GetCopyright}@anchor{41c8}
@deffn {C 函数} const char* Py_GetCopyright ()

Return the official copyright string for the current Python version, for example

@code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}

@geindex copyright (in module sys)

The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as @code{sys.copyright}.
@end deffn

@geindex Py_GetCompiler (C 函数)
@anchor{c-api/init c Py_GetCompiler}@anchor{41c7}
@deffn {C 函数} const char* Py_GetCompiler ()

Return an indication of the compiler used to build the current Python version,
in square brackets, for example:

@example
"[GCC 2.7.2.2]"
@end example

@geindex version (in module sys)

The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as part of the variable
@code{sys.version}.
@end deffn

@geindex Py_GetBuildInfo (C 函数)
@anchor{c-api/init c Py_GetBuildInfo}@anchor{e67}
@deffn {C 函数} const char* Py_GetBuildInfo ()

Return information about the sequence number and build date and time  of the
current Python interpreter instance, for example

@example
"#67, Aug  1 1997, 22:34:28"
@end example

@geindex version (in module sys)

The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as part of the variable
@code{sys.version}.
@end deffn

@geindex PySys_SetArgvEx (C 函数)
@anchor{c-api/init c PySys_SetArgvEx}@anchor{ccd}
@deffn {C 函数} void PySys_SetArgvEx (int@w{ }argc, wchar_t@w{ }**argv, int@w{ }updatepath)

@geindex main()
@geindex Py_FatalError()
@geindex argv (in module sys)

Set @ref{cce,,sys.argv} based on @emph{argc} and @emph{argv}.  These parameters are
similar to those passed to the program's @code{main()} function with the
difference that the first entry should refer to the script file to be
executed rather than the executable hosting the Python interpreter.  If there
isn't a script that will be run, the first entry in @emph{argv} can be an empty
string.  If this function fails to initialize @ref{cce,,sys.argv}, a fatal
condition is signalled using @ref{267,,Py_FatalError()}.

If @emph{updatepath} is zero, this is all the function does.  If @emph{updatepath}
is non-zero, the function also modifies @ref{262,,sys.path} according to the
following algorithm:


@itemize -

@item 
If the name of an existing script is passed in @code{argv[0]}, the absolute
path of the directory where the script is located is prepended to
@ref{262,,sys.path}.

@item 
Otherwise (that is, if @emph{argc} is @code{0} or @code{argv[0]} doesn't point
to an existing file name), an empty string is prepended to
@ref{262,,sys.path}, which is the same as prepending the current working
directory (@code{"."}).
@end itemize

Use @ref{547,,Py_DecodeLocale()} to decode a bytes string to get a
@code{wchar_*} string.

@cartouche
@quotation 注解 
It is recommended that applications embedding the Python interpreter
for purposes other than executing a single script pass @code{0} as @emph{updatepath},
and update @ref{262,,sys.path} themselves if desired.
See CVE-2008-5983@footnote{https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983}.

On versions before 3.1.3, you can achieve the same effect by manually
popping the first @ref{262,,sys.path} element after having called
@ref{dba,,PySys_SetArgv()}, for example using:

@example
PyRun_SimpleString("import sys; sys.path.pop(0)\n");
@end example
@end quotation
@end cartouche


3.1.3 新版功能.


@c XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
@c check w/ Guido.
@end deffn

@geindex PySys_SetArgv (C 函数)
@anchor{c-api/init c PySys_SetArgv}@anchor{dba}
@deffn {C 函数} void PySys_SetArgv (int@w{ }argc, wchar_t@w{ }**argv)

This function works like @ref{ccd,,PySys_SetArgvEx()} with @emph{updatepath} set
to @code{1} unless the @code{python} interpreter was started with the
@ref{232,,-I}.

Use @ref{547,,Py_DecodeLocale()} to decode a bytes string to get a
@code{wchar_*} string.


在 3.4 版更改: The @emph{updatepath} value depends on @ref{232,,-I}.

@end deffn

@geindex Py_SetPythonHome (C 函数)
@anchor{c-api/init c Py_SetPythonHome}@anchor{113a}
@deffn {C 函数} void Py_SetPythonHome (const wchar_t@w{ }*home)

Set the default "home" directory, that is, the location of the standard
Python libraries.  See 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} for the meaning of the
argument string.

The argument should point to a zero-terminated character string in static
storage whose contents will not change for the duration of the program's
execution.  No code in the Python interpreter will change the contents of
this storage.

Use @ref{547,,Py_DecodeLocale()} to decode a bytes string to get a
@code{wchar_*} string.
@end deffn

@geindex Py_GetPythonHome (C 函数)
@anchor{c-api/init c Py_GetPythonHome}@anchor{41cb}
@deffn {C 函数} w_char* Py_GetPythonHome ()

Return the default "home", that is, the value set by a previous call to
@ref{113a,,Py_SetPythonHome()}, or the value of the 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME}
environment variable if it is set.
@end deffn

@node 线程状态和全局解释器锁,子解释器支持,Process-wide parameters,初始化，终结和线程
@anchor{c-api/init thread-state-and-the-global-interpreter-lock}@anchor{41dd}@anchor{c-api/init threads}@anchor{41de}
@subsection 线程状态和全局解释器锁


@geindex global interpreter lock
@geindex interpreter lock
@geindex lock@comma{} interpreter

The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there's a global lock, called the @ref{60b,,global interpreter lock} or @ref{20f,,GIL}, that must be held by the current thread before
it can safely access Python objects. Without the lock, even the simplest
operations could cause problems in a multi-threaded program: for example, when
two threads simultaneously increment the reference count of the same object, the
reference count could end up being incremented only once instead of twice.

@geindex setswitchinterval() (in module sys)

Therefore, the rule exists that only the thread that has acquired the
@ref{20f,,GIL} may operate on Python objects or call Python/C API functions.
In order to emulate concurrency of execution, the interpreter regularly
tries to switch threads (see @ref{219,,sys.setswitchinterval()}).  The lock is also
released around potentially blocking I/O operations like reading or writing
a file, so that other Python threads can run in the meantime.

@geindex PyThreadState
@geindex PyThreadState

The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called @ref{41df,,PyThreadState}.  There's also one
global variable pointing to the current @ref{41df,,PyThreadState}: it can
be retrieved using @ref{41e0,,PyThreadState_Get()}.

@menu
* Releasing the GIL from extension code:: 
* 非Python创建的线程:: 
* Cautions about fork(): Cautions about fork. 
* 高阶 API:: 
* Low-level API:: 

@end menu

@node Releasing the GIL from extension code,非Python创建的线程,,线程状态和全局解释器锁
@anchor{c-api/init releasing-the-gil-from-extension-code}@anchor{41e1}
@subsubsection Releasing the GIL from extension code


Most extension code manipulating the @ref{20f,,GIL} has the following simple
structure:

@example
Save the thread state in a local variable.
Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.
@end example

This is so common that a pair of macros exists to simplify it:

@example
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
@end example

@geindex Py_BEGIN_ALLOW_THREADS
@geindex Py_END_ALLOW_THREADS

The @ref{3d7d,,Py_BEGIN_ALLOW_THREADS} macro opens a new block and declares a
hidden local variable; the @ref{3df,,Py_END_ALLOW_THREADS} macro closes the
block.

上面的代码块可扩展为下面的代码:

@example
PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
@end example

@geindex PyEval_RestoreThread()
@geindex PyEval_SaveThread()

Here is how these functions work: the global interpreter lock is used to protect the pointer to the
current thread state.  When releasing the lock and saving the thread state,
the current thread state pointer must be retrieved before the lock is released
(since another thread could immediately acquire the lock and store its own thread
state in the global variable). Conversely, when acquiring the lock and restoring
the thread state, the lock must be acquired before storing the thread state
pointer.

@cartouche
@quotation 注解 
Calling system I/O functions is the most common use case for releasing
the GIL, but it can also be useful before calling long-running computations
which don't need access to Python objects, such as compression or
cryptographic functions operating over memory buffers.  For example, the
standard @ref{14d,,zlib} and @ref{8c,,hashlib} modules release the GIL when
compressing or hashing data.
@end quotation
@end cartouche

@node 非Python创建的线程,Cautions about fork,Releasing the GIL from extension code,线程状态和全局解释器锁
@anchor{c-api/init gilstate}@anchor{41e2}@anchor{c-api/init non-python-created-threads}@anchor{41e3}
@subsubsection 非Python创建的线程


When threads are created using the dedicated Python APIs (such as the
@ref{10b,,threading} module), a thread state is automatically associated to them
and the code showed above is therefore correct.  However, when threads are
created from C (for example by a third-party library with its own thread
management), they don't hold the GIL, nor is there a thread state structure
for them.

If you need to call Python code from these threads (often this will be part
of a callback API provided by the aforementioned third-party library),
you must first register these threads with the interpreter by
creating a thread state data structure, then acquiring the GIL, and finally
storing their thread state pointer, before you can start using the Python/C
API.  When you are done, you should reset the thread state pointer, release
the GIL, and finally free the thread state data structure.

The @ref{3e0,,PyGILState_Ensure()} and @ref{41e4,,PyGILState_Release()} functions do
all of the above automatically.  The typical idiom for calling into Python
from a C thread is:

@example
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);
@end example

Note that the @code{PyGILState_*()} functions assume there is only one global
interpreter (created automatically by @ref{210,,Py_Initialize()}).  Python
supports the creation of additional interpreters (using
@ref{41db,,Py_NewInterpreter()}), but mixing multiple interpreters and the
@code{PyGILState_*()} API is unsupported.

@node Cautions about fork,高阶 API,非Python创建的线程,线程状态和全局解释器锁
@anchor{c-api/init cautions-about-fork}@anchor{41e5}@anchor{c-api/init fork-and-threads}@anchor{3e8f}
@subsubsection Cautions about fork()


Another important thing to note about threads is their behaviour in the face
of the C @code{fork()} call. On most systems with @code{fork()}, after a
process forks only the thread that issued the fork will exist.  This has a
concrete impact both on how locks must be handled and on all stored state
in CPython's runtime.

The fact that only the "current" thread remains
means any locks held by other threads will never be released. Python solves
this for @ref{a4b,,os.fork()} by acquiring the locks it uses internally before
the fork, and releasing them afterwards. In addition, it resets any
@ref{24d5,,锁对象} in the child. When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as
@code{pthread_atfork()} would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling @code{fork()}
directly rather than through @ref{a4b,,os.fork()} (and returning to or calling
into Python) may result in a deadlock by one of Python's internal locks
being held by a thread that is defunct after the fork.
@ref{3f8,,PyOS_AfterFork_Child()} tries to reset the necessary locks, but is not
always able to.

The fact that all other threads go away also means that CPython's
runtime state there must be cleaned up properly, which @ref{a4b,,os.fork()}
does.  This means finalizing all other @ref{41df,,PyThreadState} objects
belonging to the current interpreter and all other
@ref{3ec,,PyInterpreterState} objects.  Due to this and the special
nature of the @ref{3e90,,"main" interpreter},
@code{fork()} should only be called in that interpreter's "main"
thread, where the CPython global runtime was originally initialized.
The only exception is if @code{exec()} will be called immediately
after.

@node 高阶 API,Low-level API,Cautions about fork,线程状态和全局解释器锁
@anchor{c-api/init high-level-api}@anchor{41e6}
@subsubsection 高阶 API


These are the most commonly used types and functions when writing C extension
code, or when embedding the Python interpreter:

@geindex PyInterpreterState (C 类型)
@anchor{c-api/init c PyInterpreterState}@anchor{3ec}
@deffn {C 类型} PyInterpreterState

This data structure represents the state shared by a number of cooperating
threads.  Threads belonging to the same interpreter share their module
administration and a few other internal items. There are no public members in
this structure.

Threads belonging to different interpreters initially share nothing, except
process state like available memory, open file descriptors and such.  The global
interpreter lock is also shared by all threads, regardless of to which
interpreter they belong.
@end deffn

@geindex PyThreadState (C 类型)
@anchor{c-api/init c PyThreadState}@anchor{41df}
@deffn {C 类型} PyThreadState

This data structure represents the state of a single thread.  The only public
data member is @code{interp} (@ref{3ec,,PyInterpreterState *}), which points to
this thread's interpreter state.
@end deffn

@geindex PyEval_InitThreads (C 函数)
@anchor{c-api/init c PyEval_InitThreads}@anchor{20d}
@deffn {C 函数} void PyEval_InitThreads ()

@geindex PyEval_AcquireThread()
@geindex PyEval_ReleaseThread()
@geindex PyEval_SaveThread()
@geindex PyEval_RestoreThread()

Deprecated function which does nothing.

在 Python 3.6 及更老的版本中，此函数会在 GIL 不存在时创建它。


在 3.9 版更改: The function now does nothing.



在 3.7 版更改: This function is now called by @ref{210,,Py_Initialize()}, so you don't
have to call it yourself anymore.



在 3.2 版更改: This function cannot be called before @ref{210,,Py_Initialize()} anymore.



Deprecated since version 3.9, will be removed in version 3.11.


@geindex 模块; _thread
@end deffn

@geindex PyEval_ThreadsInitialized (C 函数)
@anchor{c-api/init c PyEval_ThreadsInitialized}@anchor{20e}
@deffn {C 函数} int PyEval_ThreadsInitialized ()

Returns a non-zero value if @ref{20d,,PyEval_InitThreads()} has been called.  This
function can be called without holding the GIL, and therefore can be used to
avoid calls to the locking API when running single-threaded.


在 3.7 版更改: The @ref{20f,,GIL} is now initialized by @ref{210,,Py_Initialize()}.



Deprecated since version 3.9, will be removed in version 3.11.

@end deffn

@geindex PyEval_SaveThread (C 函数)
@anchor{c-api/init c PyEval_SaveThread}@anchor{ce4}
@deffn {C 函数} PyThreadState* PyEval_SaveThread ()

Release the global interpreter lock (if it has been created) and reset the
thread state to @code{NULL}, returning the previous thread state (which is not
@code{NULL}).  If the lock has been created, the current thread must have
acquired it.
@end deffn

@geindex PyEval_RestoreThread (C 函数)
@anchor{c-api/init c PyEval_RestoreThread}@anchor{3de}
@deffn {C 函数} void PyEval_RestoreThread (PyThreadState@w{ }*tstate)

Acquire the global interpreter lock (if it has been created) and set the
thread state to @emph{tstate}, which must not be @code{NULL}.  If the lock has been
created, the current thread must not have acquired it, otherwise deadlock
ensues.

@cartouche
@quotation 注解 
Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python.
You can use @code{_Py_IsFinalizing()} or @ref{85b,,sys.is_finalizing()} to
check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination.
@end quotation
@end cartouche
@end deffn

@geindex PyThreadState_Get (C 函数)
@anchor{c-api/init c PyThreadState_Get}@anchor{41e0}
@deffn {C 函数} PyThreadState* PyThreadState_Get ()

Return the current thread state.  The global interpreter lock must be held.
When the current thread state is @code{NULL}, this issues a fatal error (so that
the caller needn't check for @code{NULL}).
@end deffn

@geindex PyThreadState_Swap (C 函数)
@anchor{c-api/init c PyThreadState_Swap}@anchor{41e7}
@deffn {C 函数} PyThreadState* PyThreadState_Swap (PyThreadState@w{ }*tstate)

Swap the current thread state with the thread state given by the argument
@emph{tstate}, which may be @code{NULL}.  The global interpreter lock must be held
and is not released.
@end deffn

The following functions use thread-local storage, and are not compatible
with sub-interpreters:

@geindex PyGILState_Ensure (C 函数)
@anchor{c-api/init c PyGILState_Ensure}@anchor{3e0}
@deffn {C 函数} PyGILState_STATE PyGILState_Ensure ()

Ensure that the current thread is ready to call the Python C API regardless
of the current state of Python, or of the global interpreter lock. This may
be called as many times as desired by a thread as long as each call is
matched with a call to @ref{41e4,,PyGILState_Release()}. In general, other
thread-related APIs may be used between @ref{3e0,,PyGILState_Ensure()} and
@ref{41e4,,PyGILState_Release()} calls as long as the thread state is restored to
its previous state before the Release().  For example, normal usage of the
@ref{3d7d,,Py_BEGIN_ALLOW_THREADS} and @ref{3df,,Py_END_ALLOW_THREADS} macros is
acceptable.

The return value is an opaque "handle" to the thread state when
@ref{3e0,,PyGILState_Ensure()} was called, and must be passed to
@ref{41e4,,PyGILState_Release()} to ensure Python is left in the same state. Even
though recursive calls are allowed, these handles @emph{cannot} be shared - each
unique call to @ref{3e0,,PyGILState_Ensure()} must save the handle for its call
to @ref{41e4,,PyGILState_Release()}.

When the function returns, the current thread will hold the GIL and be able
to call arbitrary Python code.  Failure is a fatal error.

@cartouche
@quotation 注解 
Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python.
You can use @code{_Py_IsFinalizing()} or @ref{85b,,sys.is_finalizing()} to
check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination.
@end quotation
@end cartouche
@end deffn

@geindex PyGILState_Release (C 函数)
@anchor{c-api/init c PyGILState_Release}@anchor{41e4}
@deffn {C 函数} void PyGILState_Release (PyGILState_STATE)

Release any resources previously acquired.  After this call, Python's state will
be the same as it was prior to the corresponding @ref{3e0,,PyGILState_Ensure()} call
(but generally this state will be unknown to the caller, hence the use of the
GILState API).

Every call to @ref{3e0,,PyGILState_Ensure()} must be matched by a call to
@ref{41e4,,PyGILState_Release()} on the same thread.
@end deffn

@geindex PyGILState_GetThisThreadState (C 函数)
@anchor{c-api/init c PyGILState_GetThisThreadState}@anchor{41e8}
@deffn {C 函数} PyThreadState* PyGILState_GetThisThreadState ()

Get the current thread state for this thread.  May return @code{NULL} if no
GILState API has been used on the current thread.  Note that the main thread
always has such a thread-state, even if no auto-thread-state call has been
made on the main thread.  This is mainly a helper/diagnostic function.
@end deffn

@geindex PyGILState_Check (C 函数)
@anchor{c-api/init c PyGILState_Check}@anchor{41e9}
@deffn {C 函数} int PyGILState_Check ()

Return @code{1} if the current thread is holding the GIL and @code{0} otherwise.
This function can be called from any thread at any time.
Only if it has had its Python thread state initialized and currently is
holding the GIL will it return @code{1}.
This is mainly a helper/diagnostic function.  It can be useful
for example in callback contexts or memory allocation functions when
knowing that the GIL is locked can allow the caller to perform sensitive
actions or otherwise behave differently.


3.4 新版功能.

@end deffn

The following macros are normally used without a trailing semicolon; look for
example usage in the Python source distribution.

@geindex Py_BEGIN_ALLOW_THREADS (C 宏)
@anchor{c-api/init c Py_BEGIN_ALLOW_THREADS}@anchor{3d7d}
@deffn {C 宏} Py_BEGIN_ALLOW_THREADS

This macro expands to @code{@{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Note that it contains an opening brace; it must be matched with a following
@ref{3df,,Py_END_ALLOW_THREADS} macro.  See above for further discussion of this
macro.
@end deffn

@geindex Py_END_ALLOW_THREADS (C 宏)
@anchor{c-api/init c Py_END_ALLOW_THREADS}@anchor{3df}
@deffn {C 宏} Py_END_ALLOW_THREADS

此宏扩展为 @code{PyEval_RestoreThread(_save); @}}。 注意它包含一个右花括号；它必须与之前的 @ref{3d7d,,Py_BEGIN_ALLOW_THREADS} 宏匹配。 请参阅上文以进一步讨论此宏。
@end deffn

@geindex Py_BLOCK_THREADS (C 宏)
@anchor{c-api/init c Py_BLOCK_THREADS}@anchor{41ea}
@deffn {C 宏} Py_BLOCK_THREADS

This macro expands to @code{PyEval_RestoreThread(_save);}: it is equivalent to
@ref{3df,,Py_END_ALLOW_THREADS} without the closing brace.
@end deffn

@geindex Py_UNBLOCK_THREADS (C 宏)
@anchor{c-api/init c Py_UNBLOCK_THREADS}@anchor{41eb}
@deffn {C 宏} Py_UNBLOCK_THREADS

This macro expands to @code{_save = PyEval_SaveThread();}: it is equivalent to
@ref{3d7d,,Py_BEGIN_ALLOW_THREADS} without the opening brace and variable
declaration.
@end deffn

@node Low-level API,,高阶 API,线程状态和全局解释器锁
@anchor{c-api/init low-level-api}@anchor{41ec}
@subsubsection Low-level API


All of the following functions must be called after @ref{210,,Py_Initialize()}.


在 3.7 版更改: @ref{210,,Py_Initialize()} now initializes the @ref{20f,,GIL}.


@geindex PyInterpreterState_New (C 函数)
@anchor{c-api/init c PyInterpreterState_New}@anchor{3552}
@deffn {C 函数} PyInterpreterState* PyInterpreterState_New ()

Create a new interpreter state object.  The global interpreter lock need not
be held, but may be held if it is necessary to serialize calls to this
function.

Raises an @ref{fec,,auditing event} @code{cpython.PyInterpreterState_New} with no arguments.
@end deffn

@geindex PyInterpreterState_Clear (C 函数)
@anchor{c-api/init c PyInterpreterState_Clear}@anchor{3551}
@deffn {C 函数} void PyInterpreterState_Clear (PyInterpreterState@w{ }*interp)

Reset all information in an interpreter state object.  The global interpreter
lock must be held.

Raises an @ref{fec,,auditing event} @code{cpython.PyInterpreterState_Clear} with no arguments.
@end deffn

@geindex PyInterpreterState_Delete (C 函数)
@anchor{c-api/init c PyInterpreterState_Delete}@anchor{41ed}
@deffn {C 函数} void PyInterpreterState_Delete (PyInterpreterState@w{ }*interp)

Destroy an interpreter state object.  The global interpreter lock need not be
held.  The interpreter state must have been reset with a previous call to
@ref{3551,,PyInterpreterState_Clear()}.
@end deffn

@geindex PyThreadState_New (C 函数)
@anchor{c-api/init c PyThreadState_New}@anchor{41ee}
@deffn {C 函数} PyThreadState* PyThreadState_New (PyInterpreterState@w{ }*interp)

Create a new thread state object belonging to the given interpreter object.
The global interpreter lock need not be held, but may be held if it is
necessary to serialize calls to this function.
@end deffn

@geindex PyThreadState_Clear (C 函数)
@anchor{c-api/init c PyThreadState_Clear}@anchor{1096}
@deffn {C 函数} void PyThreadState_Clear (PyThreadState@w{ }*tstate)

Reset all information in a thread state object.  The global interpreter lock
must be held.


在 3.9 版更改: This function now calls the @code{PyThreadState.on_delete} callback.
Previously, that happened in @ref{10e0,,PyThreadState_Delete()}.

@end deffn

@geindex PyThreadState_Delete (C 函数)
@anchor{c-api/init c PyThreadState_Delete}@anchor{10e0}
@deffn {C 函数} void PyThreadState_Delete (PyThreadState@w{ }*tstate)

Destroy a thread state object.  The global interpreter lock need not be held.
The thread state must have been reset with a previous call to
@ref{1096,,PyThreadState_Clear()}.
@end deffn

@geindex PyThreadState_DeleteCurrent (C 函数)
@anchor{c-api/init c PyThreadState_DeleteCurrent}@anchor{1127}
@deffn {C 函数} void PyThreadState_DeleteCurrent (void)

Destroy the current thread state and release the global interpreter lock.
Like @ref{10e0,,PyThreadState_Delete()}, the global interpreter lock need not
be held. The thread state must have been reset with a previous call
to @ref{1096,,PyThreadState_Clear()}.
@end deffn

@geindex PyThreadState_GetFrame (C 函数)
@anchor{c-api/init c PyThreadState_GetFrame}@anchor{24f}
@deffn {C 函数} PyFrameObject* PyThreadState_GetFrame (PyThreadState@w{ }*tstate)

Get the current frame of the Python thread state @emph{tstate}.

Return a strong reference. Return @code{NULL} if no frame is currently
executing.

See also @ref{3edd,,PyEval_GetFrame()}.

@emph{tstate} must not be @code{NULL}.


3.9 新版功能.

@end deffn

@geindex PyThreadState_GetID (C 函数)
@anchor{c-api/init c PyThreadState_GetID}@anchor{250}
@deffn {C 函数} uint64_t PyThreadState_GetID (PyThreadState@w{ }*tstate)

Get the unique thread state identifier of the Python thread state @emph{tstate}.

@emph{tstate} must not be @code{NULL}.


3.9 新版功能.

@end deffn

@geindex PyThreadState_GetInterpreter (C 函数)
@anchor{c-api/init c PyThreadState_GetInterpreter}@anchor{24d}
@deffn {C 函数} PyInterpreterState* PyThreadState_GetInterpreter (PyThreadState@w{ }*tstate)

Get the interpreter of the Python thread state @emph{tstate}.

@emph{tstate} must not be @code{NULL}.


3.9 新版功能.

@end deffn

@geindex PyInterpreterState_Get (C 函数)
@anchor{c-api/init c PyInterpreterState_Get}@anchor{24e}
@deffn {C 函数} PyInterpreterState* PyInterpreterState_Get (void)

获取当前解释器。

Issue a fatal error if there no current Python thread state or no current
interpreter. It cannot return NULL.

呼叫者必须持有GIL。


3.9 新版功能.

@end deffn

@geindex PyInterpreterState_GetID (C 函数)
@anchor{c-api/init c PyInterpreterState_GetID}@anchor{546}
@deffn {C 函数} int64_t PyInterpreterState_GetID (PyInterpreterState@w{ }*interp)

Return the interpreter's unique ID.  If there was any error in doing
so then @code{-1} is returned and an error is set.

呼叫者必须持有GIL。


3.7 新版功能.

@end deffn

@geindex PyInterpreterState_GetDict (C 函数)
@anchor{c-api/init c PyInterpreterState_GetDict}@anchor{41ef}
@deffn {C 函数} PyObject* PyInterpreterState_GetDict (PyInterpreterState@w{ }*interp)

Return a dictionary in which interpreter-specific data may be stored.
If this function returns @code{NULL} then no exception has been raised and
the caller should assume no interpreter-specific dict is available.

This is not a replacement for @ref{25f,,PyModule_GetState()}, which
extensions should use to store interpreter-specific state information.


3.8 新版功能.

@end deffn

@geindex _PyFrameEvalFunction (C 类型)
@anchor{c-api/init c _PyFrameEvalFunction}@anchor{10c3}
@deffn {C 类型} PyObject* (*_PyFrameEvalFunction) (PyThreadState@w{ }*tstate, PyFrameObject@w{ }*frame, int@w{ }throwflag)

Type of a frame evaluation function.

The @emph{throwflag} parameter is used by the @code{throw()} method of generators:
if non-zero, handle the current exception.


在 3.9 版更改: 此函数现在可接受一个 @emph{tstate} 形参。

@end deffn

@geindex _PyInterpreterState_GetEvalFrameFunc (C 函数)
@anchor{c-api/init c _PyInterpreterState_GetEvalFrameFunc}@anchor{10c1}
@deffn {C 函数} _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc (PyInterpreterState@w{ }*interp)

Get the frame evaluation function.

See the 
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} "Adding a frame evaluation API to CPython".


3.9 新版功能.

@end deffn

@geindex _PyInterpreterState_SetEvalFrameFunc (C 函数)
@anchor{c-api/init c _PyInterpreterState_SetEvalFrameFunc}@anchor{10c2}
@deffn {C 函数} void _PyInterpreterState_SetEvalFrameFunc (PyInterpreterState@w{ }*interp, _PyFrameEvalFunction@w{ }eval_frame)

Set the frame evaluation function.

See the 
@geindex Python 提高建议; PEP 523
PEP 523@footnote{https://www.python.org/dev/peps/pep-0523} "Adding a frame evaluation API to CPython".


3.9 新版功能.

@end deffn

@geindex PyThreadState_GetDict (C 函数)
@anchor{c-api/init c PyThreadState_GetDict}@anchor{41f0}
@deffn {C 函数} PyObject* PyThreadState_GetDict ()
@emph{Return value: Borrowed reference.}
Return a dictionary in which extensions can store thread-specific state
information.  Each extension should use a unique key to use to store state in
the dictionary.  It is okay to call this function when no current thread state
is available. If this function returns @code{NULL}, no exception has been raised and
the caller should assume no current thread state is available.
@end deffn

@geindex PyThreadState_SetAsyncExc (C 函数)
@anchor{c-api/init c PyThreadState_SetAsyncExc}@anchor{543}
@deffn {C 函数} int PyThreadState_SetAsyncExc (unsigned long@w{ }id, PyObject@w{ }*exc)

Asynchronously raise an exception in a thread. The @emph{id} argument is the thread
id of the target thread; @emph{exc} is the exception object to be raised. This
function does not steal any references to @emph{exc}. To prevent naive misuse, you
must write your own C extension to call this.  Must be called with the GIL held.
Returns the number of thread states modified; this is normally one, but will be
zero if the thread id isn't found.  If @emph{exc} is @code{NULL}, the pending
exception (if any) for the thread is cleared. This raises no exceptions.


在 3.7 版更改: The type of the @emph{id} parameter changed from @code{long} to
@code{unsigned long}.

@end deffn

@geindex PyEval_AcquireThread (C 函数)
@anchor{c-api/init c PyEval_AcquireThread}@anchor{3dd}
@deffn {C 函数} void PyEval_AcquireThread (PyThreadState@w{ }*tstate)

Acquire the global interpreter lock and set the current thread state to
@emph{tstate}, which must not be @code{NULL}.  The lock must have been created earlier.
If this thread already has the lock, deadlock ensues.

@cartouche
@quotation 注解 
Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python.
You can use @code{_Py_IsFinalizing()} or @ref{85b,,sys.is_finalizing()} to
check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination.
@end quotation
@end cartouche


在 3.8 版更改: Updated to be consistent with @ref{3de,,PyEval_RestoreThread()},
@ref{3df,,Py_END_ALLOW_THREADS()}, and @ref{3e0,,PyGILState_Ensure()},
and terminate the current thread if called while the interpreter is finalizing.


@ref{3de,,PyEval_RestoreThread()} is a higher-level function which is always
available (even when threads have not been initialized).
@end deffn

@geindex PyEval_ReleaseThread (C 函数)
@anchor{c-api/init c PyEval_ReleaseThread}@anchor{41f1}
@deffn {C 函数} void PyEval_ReleaseThread (PyThreadState@w{ }*tstate)

Reset the current thread state to @code{NULL} and release the global interpreter
lock.  The lock must have been created earlier and must be held by the current
thread.  The @emph{tstate} argument, which must not be @code{NULL}, is only used to check
that it represents the current thread state --- if it isn't, a fatal error is
reported.

@ref{ce4,,PyEval_SaveThread()} is a higher-level function which is always
available (even when threads have not been initialized).
@end deffn

@geindex PyEval_AcquireLock (C 函数)
@anchor{c-api/init c PyEval_AcquireLock}@anchor{3dc}
@deffn {C 函数} void PyEval_AcquireLock ()

Acquire the global interpreter lock.  The lock must have been created earlier.
If this thread already has the lock, a deadlock ensues.


3.2 版后已移除: This function does not update the current thread state.  Please use
@ref{3de,,PyEval_RestoreThread()} or @ref{3dd,,PyEval_AcquireThread()}
instead.


@cartouche
@quotation 注解 
Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python.
You can use @code{_Py_IsFinalizing()} or @ref{85b,,sys.is_finalizing()} to
check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination.
@end quotation
@end cartouche


在 3.8 版更改: Updated to be consistent with @ref{3de,,PyEval_RestoreThread()},
@ref{3df,,Py_END_ALLOW_THREADS()}, and @ref{3e0,,PyGILState_Ensure()},
and terminate the current thread if called while the interpreter is finalizing.

@end deffn

@geindex PyEval_ReleaseLock (C 函数)
@anchor{c-api/init c PyEval_ReleaseLock}@anchor{ce3}
@deffn {C 函数} void PyEval_ReleaseLock ()

Release the global interpreter lock.  The lock must have been created earlier.


3.2 版后已移除: This function does not update the current thread state.  Please use
@ref{ce4,,PyEval_SaveThread()} or @ref{41f1,,PyEval_ReleaseThread()}
instead.

@end deffn

@node 子解释器支持,异步通知,线程状态和全局解释器锁,初始化，终结和线程
@anchor{c-api/init id1}@anchor{41f2}@anchor{c-api/init sub-interpreter-support}@anchor{3e90}
@subsection 子解释器支持


While in most uses, you will only embed a single Python interpreter, there
are cases where you need to create several independent interpreters in the
same process and perhaps even in the same thread. Sub-interpreters allow
you to do that.

The "main" interpreter is the first one created when the runtime initializes.
It is usually the only Python interpreter in a process.  Unlike sub-interpreters,
the main interpreter has unique process-global responsibilities like signal
handling.  It is also responsible for execution during runtime initialization and
is usually the active interpreter during runtime finalization.  The
@ref{41f3,,PyInterpreterState_Main()} function returns a pointer to its state.

You can switch between sub-interpreters using the @ref{41e7,,PyThreadState_Swap()}
function. You can create and destroy them using the following functions:

@geindex Py_NewInterpreter (C 函数)
@anchor{c-api/init c Py_NewInterpreter}@anchor{41db}
@deffn {C 函数} PyThreadState* Py_NewInterpreter ()

@geindex 模块; builtins
@geindex 模块; __main__
@geindex 模块; sys
@geindex stdout (in module sys)
@geindex stderr (in module sys)
@geindex stdin (in module sys)

Create a new sub-interpreter.  This is an (almost) totally separate environment
for the execution of Python code.  In particular, the new interpreter has
separate, independent versions of all imported modules, including the
fundamental modules @ref{12,,builtins}, @ref{1,,__main__} and @ref{fd,,sys}.  The
table of loaded modules (@code{sys.modules}) and the module search path
(@code{sys.path}) are also separate.  The new environment has no @code{sys.argv}
variable.  It has new standard I/O stream file objects @code{sys.stdin},
@code{sys.stdout} and @code{sys.stderr} (however these refer to the same underlying
file descriptors).

The return value points to the first thread state created in the new
sub-interpreter.  This thread state is made in the current thread state.
Note that no actual thread is created; see the discussion of thread states
below.  If creation of the new interpreter is unsuccessful, @code{NULL} is
returned; no exception is set since the exception state is stored in the
current thread state and there may not be a current thread state.  (Like all
other Python/C API functions, the global interpreter lock must be held before
calling this function and is still held when it returns; however, unlike most
other Python/C API functions, there needn't be a current thread state on
entry.)

@geindex Py_FinalizeEx()
@geindex Py_Initialize()

Extension modules are shared between (sub-)interpreters as follows:


@itemize *

@item 
For modules using multi-phase initialization,
e.g. @ref{8a3,,PyModule_FromDefAndSpec()}, a separate module object is
created and initialized for each interpreter.
Only C-level static and global variables are shared between these
module objects.

@item 
For modules using single-phase initialization,
e.g. @ref{3d60,,PyModule_Create()}, the first time a particular extension
is imported, it is initialized normally, and a (shallow) copy of its
module's dictionary is squirreled away.
When the same extension is imported by another (sub-)interpreter, a new
module is initialized and filled with the contents of this copy; the
extension's @code{init} function is not called.
Objects in the module's dictionary thus end up shared across
(sub-)interpreters, which might cause unwanted behavior (see
@ref{41f4,,Bugs and caveats} below).

Note that this is different from what happens when an extension is
imported after the interpreter has been completely re-initialized by
calling @ref{6ca,,Py_FinalizeEx()} and @ref{210,,Py_Initialize()}; in that
case, the extension's @code{initmodule} function @emph{is} called again.
As with multi-phase initialization, this means that only C-level static
and global variables are shared between these modules.
@end itemize

@geindex close() (in module os)
@end deffn

@geindex Py_EndInterpreter (C 函数)
@anchor{c-api/init c Py_EndInterpreter}@anchor{f9a}
@deffn {C 函数} void Py_EndInterpreter (PyThreadState@w{ }*tstate)

@geindex Py_FinalizeEx()

Destroy the (sub-)interpreter represented by the given thread state. The given
thread state must be the current thread state.  See the discussion of thread
states below.  When the call returns, the current thread state is @code{NULL}.  All
thread states associated with this interpreter are destroyed.  (The global
interpreter lock must be held before calling this function and is still held
when it returns.)  @ref{6ca,,Py_FinalizeEx()} will destroy all sub-interpreters that
haven't been explicitly destroyed at that point.
@end deffn

@menu
* 错误和警告:: 

@end menu

@node 错误和警告,,,子解释器支持
@anchor{c-api/init bugs-and-caveats}@anchor{41f4}
@subsubsection 错误和警告


Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn't perfect --- for example, using
low-level file operations like  @ref{4e1,,os.close()} they can
(accidentally or maliciously) affect each other's open files.  Because of the
way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when using single-phase initialization
or (static) global variables.
It is possible to insert objects created in one sub-interpreter into
a namespace of another (sub-)interpreter; this should be avoided if possible.

Special care should be taken to avoid sharing user-defined functions,
methods, instances or classes between sub-interpreters, since import
operations executed by such objects may affect the wrong (sub-)interpreter's
dictionary of loaded modules. It is equally important to avoid sharing
objects from which the above are reachable.

Also note that combining this functionality with @code{PyGILState_*()} APIs
is delicate, because these APIs assume a bijection between Python thread states
and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don't switch sub-interpreters between a pair
of matching @ref{3e0,,PyGILState_Ensure()} and @ref{41e4,,PyGILState_Release()} calls.
Furthermore, extensions (such as @ref{2a,,ctypes}) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using
sub-interpreters.

@node 异步通知,分析和跟踪,子解释器支持,初始化，终结和线程
@anchor{c-api/init asynchronous-notifications}@anchor{41f5}
@subsection 异步通知


A mechanism is provided to make asynchronous notifications to the main
interpreter thread.  These notifications take the form of a function
pointer and a void pointer argument.

@geindex Py_AddPendingCall (C 函数)
@anchor{c-api/init c Py_AddPendingCall}@anchor{260}
@deffn {C 函数} int Py_AddPendingCall (int (*func)(void *), void@w{ }*arg)

@geindex Py_AddPendingCall()

Schedule a function to be called from the main interpreter thread.  On
success, @code{0} is returned and @emph{func} is queued for being called in the
main thread.  On failure, @code{-1} is returned without setting any exception.

When successfully queued, @emph{func} will be @emph{eventually} called from the
main interpreter thread with the argument @emph{arg}.  It will be called
asynchronously with respect to normally running Python code, but with
both these conditions met:


@itemize *

@item 
on a @ref{713,,bytecode} boundary;

@item 
with the main thread holding the @ref{60b,,global interpreter lock}
(@emph{func} can therefore use the full C API).
@end itemize

@emph{func} must return @code{0} on success, or @code{-1} on failure with an exception
set.  @emph{func} won't be interrupted to perform another asynchronous
notification recursively, but it can still be interrupted to switch
threads if the global interpreter lock is released.

This function doesn't need a current thread state to run, and it doesn't
need the global interpreter lock.

To call this function in a subinterpreter, the caller must hold the GIL.
Otherwise, the function @emph{func} can be scheduled to be called from the wrong
interpreter.

@cartouche
@quotation 警告 
This is a low-level function, only useful for very special cases.
There is no guarantee that @emph{func} will be called as quick as
possible.  If the main thread is busy executing a system call,
@emph{func} won't be called before the system call returns.  This
function is generally @strong{not} suitable for calling Python code from
arbitrary C threads.  Instead, use the @ref{41e2,,PyGILState API}.
@end quotation
@end cartouche


在 3.9 版更改: If this function is called in a subinterpreter, the function @emph{func} is
now scheduled to be called from the subinterpreter, rather than being
called from the main interpreter. Each subinterpreter now has its own
list of scheduled calls.



3.1 新版功能.

@end deffn

@node 分析和跟踪,高级调试器支持,异步通知,初始化，终结和线程
@anchor{c-api/init profiling}@anchor{41f6}@anchor{c-api/init profiling-and-tracing}@anchor{41f7}
@subsection 分析和跟踪


The Python interpreter provides some low-level support for attaching profiling
and execution tracing facilities.  These are used for profiling, debugging, and
coverage analysis tools.

This C interface allows the profiling or tracing code to avoid the overhead of
calling through Python-level callable objects, making a direct C function call
instead.  The essential attributes of the facility have not changed; the
interface allows trace functions to be installed per-thread, and the basic
events reported to the trace function are the same as had been reported to the
Python-level trace functions in previous versions.

@geindex Py_tracefunc (C 类型)
@anchor{c-api/init c Py_tracefunc}@anchor{41f8}
@deffn {C 类型} int (*Py_tracefunc) (PyObject@w{ }*obj, PyFrameObject@w{ }*frame, int@w{ }what, PyObject@w{ }*arg)

The type of the trace function registered using @ref{f05,,PyEval_SetProfile()} and
@ref{f06,,PyEval_SetTrace()}. The first parameter is the object passed to the
registration function as @emph{obj}, @emph{frame} is the frame object to which the event
pertains, @emph{what} is one of the constants @code{PyTrace_CALL},
@code{PyTrace_EXCEPTION}, @code{PyTrace_LINE}, @code{PyTrace_RETURN},
@code{PyTrace_C_CALL}, @code{PyTrace_C_EXCEPTION}, @code{PyTrace_C_RETURN},
or @code{PyTrace_OPCODE}, and @emph{arg} depends on the value of @emph{what}:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

@emph{what} 的值

@tab

@emph{arg} 的含义

@item

@code{PyTrace_CALL}

@tab

总是 @ref{3d5d,,Py_None}.

@item

@code{PyTrace_EXCEPTION}

@tab

@ref{d2f,,sys.exc_info()} 返回的异常信息。

@item

@code{PyTrace_LINE}

@tab

总是 @ref{3d5d,,Py_None}.

@item

@code{PyTrace_RETURN}

@tab

返回给调用方的值，或者如果是由异常导致的则返回 @code{NULL}。

@item

@code{PyTrace_C_CALL}

@tab

正在调用函数对象。

@item

@code{PyTrace_C_EXCEPTION}

@tab

正在调用函数对象。

@item

@code{PyTrace_C_RETURN}

@tab

正在调用函数对象。

@item

@code{PyTrace_OPCODE}

@tab

总是 @ref{3d5d,,Py_None}.

@end multitable

@end deffn

@geindex PyTrace_CALL (C 变量)
@anchor{c-api/init c PyTrace_CALL}@anchor{41f9}
@deffn {C 变量} int PyTrace_CALL

The value of the @emph{what} parameter to a @ref{41f8,,Py_tracefunc} function when a new
call to a function or method is being reported, or a new entry into a generator.
Note that the creation of the iterator for a generator function is not reported
as there is no control transfer to the Python bytecode in the corresponding
frame.
@end deffn

@geindex PyTrace_EXCEPTION (C 变量)
@anchor{c-api/init c PyTrace_EXCEPTION}@anchor{41fa}
@deffn {C 变量} int PyTrace_EXCEPTION

The value of the @emph{what} parameter to a @ref{41f8,,Py_tracefunc} function when an
exception has been raised.  The callback function is called with this value for
@emph{what} when after any bytecode is processed after which the exception becomes
set within the frame being executed.  The effect of this is that as exception
propagation causes the Python stack to unwind, the callback is called upon
return to each frame as the exception propagates.  Only trace functions receives
these events; they are not needed by the profiler.
@end deffn

@geindex PyTrace_LINE (C 变量)
@anchor{c-api/init c PyTrace_LINE}@anchor{41fb}
@deffn {C 变量} int PyTrace_LINE

The value passed as the @emph{what} parameter to a @ref{41f8,,Py_tracefunc} function
(but not a profiling function) when a line-number event is being reported.
It may be disabled for a frame by setting @code{f_trace_lines} to @emph{0} on that frame.
@end deffn

@geindex PyTrace_RETURN (C 变量)
@anchor{c-api/init c PyTrace_RETURN}@anchor{41fc}
@deffn {C 变量} int PyTrace_RETURN

The value for the @emph{what} parameter to @ref{41f8,,Py_tracefunc} functions when a
call is about to return.
@end deffn

@geindex PyTrace_C_CALL (C 变量)
@anchor{c-api/init c PyTrace_C_CALL}@anchor{41fd}
@deffn {C 变量} int PyTrace_C_CALL

The value for the @emph{what} parameter to @ref{41f8,,Py_tracefunc} functions when a C
function is about to be called.
@end deffn

@geindex PyTrace_C_EXCEPTION (C 变量)
@anchor{c-api/init c PyTrace_C_EXCEPTION}@anchor{41fe}
@deffn {C 变量} int PyTrace_C_EXCEPTION

The value for the @emph{what} parameter to @ref{41f8,,Py_tracefunc} functions when a C
function has raised an exception.
@end deffn

@geindex PyTrace_C_RETURN (C 变量)
@anchor{c-api/init c PyTrace_C_RETURN}@anchor{41ff}
@deffn {C 变量} int PyTrace_C_RETURN

The value for the @emph{what} parameter to @ref{41f8,,Py_tracefunc} functions when a C
function has returned.
@end deffn

@geindex PyTrace_OPCODE (C 变量)
@anchor{c-api/init c PyTrace_OPCODE}@anchor{4200}
@deffn {C 变量} int PyTrace_OPCODE

The value for the @emph{what} parameter to @ref{41f8,,Py_tracefunc} functions (but not
profiling functions) when a new opcode is about to be executed.  This event is
not emitted by default: it must be explicitly requested by setting
@code{f_trace_opcodes} to @emph{1} on the frame.
@end deffn

@geindex PyEval_SetProfile (C 函数)
@anchor{c-api/init c PyEval_SetProfile}@anchor{f05}
@deffn {C 函数} void PyEval_SetProfile (Py_tracefunc@w{ }func, PyObject@w{ }*obj)

Set the profiler function to @emph{func}.  The @emph{obj} parameter is passed to the
function as its first parameter, and may be any Python object, or @code{NULL}.  If
the profile function needs to maintain state, using a different value for @emph{obj}
for each thread provides a convenient and thread-safe place to store it.  The
profile function is called for all monitored events except @code{PyTrace_LINE}
@code{PyTrace_OPCODE} and @code{PyTrace_EXCEPTION}.

The caller must hold the @ref{20f,,GIL}.
@end deffn

@geindex PyEval_SetTrace (C 函数)
@anchor{c-api/init c PyEval_SetTrace}@anchor{f06}
@deffn {C 函数} void PyEval_SetTrace (Py_tracefunc@w{ }func, PyObject@w{ }*obj)

Set the tracing function to @emph{func}.  This is similar to
@ref{f05,,PyEval_SetProfile()}, except the tracing function does receive line-number
events and per-opcode events, but does not receive any event related to C function
objects being called.  Any trace function registered using @ref{f06,,PyEval_SetTrace()}
will not receive @code{PyTrace_C_CALL}, @code{PyTrace_C_EXCEPTION} or
@code{PyTrace_C_RETURN} as a value for the @emph{what} parameter.

The caller must hold the @ref{20f,,GIL}.
@end deffn

@node 高级调试器支持,线程本地存储支持,分析和跟踪,初始化，终结和线程
@anchor{c-api/init advanced-debugger-support}@anchor{4201}@anchor{c-api/init advanced-debugging}@anchor{4202}
@subsection 高级调试器支持


These functions are only intended to be used by advanced debugging tools.

@geindex PyInterpreterState_Head (C 函数)
@anchor{c-api/init c PyInterpreterState_Head}@anchor{f09}
@deffn {C 函数} PyInterpreterState* PyInterpreterState_Head ()

Return the interpreter state object at the head of the list of all such objects.
@end deffn

@geindex PyInterpreterState_Main (C 函数)
@anchor{c-api/init c PyInterpreterState_Main}@anchor{41f3}
@deffn {C 函数} PyInterpreterState* PyInterpreterState_Main ()

Return the main interpreter state object.
@end deffn

@geindex PyInterpreterState_Next (C 函数)
@anchor{c-api/init c PyInterpreterState_Next}@anchor{f0a}
@deffn {C 函数} PyInterpreterState* PyInterpreterState_Next (PyInterpreterState@w{ }*interp)

Return the next interpreter state object after @emph{interp} from the list of all
such objects.
@end deffn

@geindex PyInterpreterState_ThreadHead (C 函数)
@anchor{c-api/init c PyInterpreterState_ThreadHead}@anchor{f0b}
@deffn {C 函数} PyThreadState * PyInterpreterState_ThreadHead (PyInterpreterState@w{ }*interp)

Return the pointer to the first @ref{41df,,PyThreadState} object in the list of
threads associated with the interpreter @emph{interp}.
@end deffn

@geindex PyThreadState_Next (C 函数)
@anchor{c-api/init c PyThreadState_Next}@anchor{f0c}
@deffn {C 函数} PyThreadState* PyThreadState_Next (PyThreadState@w{ }*tstate)

Return the next thread state object after @emph{tstate} from the list of all such
objects belonging to the same @ref{3ec,,PyInterpreterState} object.
@end deffn

@node 线程本地存储支持,,高级调试器支持,初始化，终结和线程
@anchor{c-api/init thread-local-storage}@anchor{4203}@anchor{c-api/init thread-local-storage-support}@anchor{4204}
@subsection 线程本地存储支持


The Python interpreter provides low-level support for thread-local storage
(TLS) which wraps the underlying native TLS implementation to support the
Python-level thread local storage API (@ref{f57,,threading.local}).  The
CPython C level APIs are similar to those offered by pthreads and Windows:
use a thread key and functions to associate a @code{void*} value per
thread.

The GIL does @emph{not} need to be held when calling these functions; they supply
their own locking.

Note that @code{Python.h} does not include the declaration of the TLS APIs,
you need to include @code{pythread.h} to use thread-local storage.

@cartouche
@quotation 注解 
None of these API functions handle memory management on behalf of the
@code{void*} values.  You need to allocate and deallocate them yourself.
If the @code{void*} values happen to be @ref{5bd,,PyObject*}, these
functions don't do refcount operations on them either.
@end quotation
@end cartouche

@menu
* Thread Specific Storage (TSS) API: Thread Specific Storage TSS API. 
* Thread Local Storage (TLS) API: Thread Local Storage TLS API. 

@end menu

@node Thread Specific Storage TSS API,Thread Local Storage TLS API,,线程本地存储支持
@anchor{c-api/init thread-specific-storage-api}@anchor{430}@anchor{c-api/init thread-specific-storage-tss-api}@anchor{4205}
@subsubsection Thread Specific Storage (TSS) API


TSS API is introduced to supersede the use of the existing TLS API within the
CPython interpreter.  This API uses a new type @ref{431,,Py_tss_t} instead of
@code{int} to represent thread keys.


3.7 新版功能.



@subsubheading 参见


"A New C-API for Thread-Local Storage in CPython" (
@geindex Python 提高建议; PEP 539
PEP 539@footnote{https://www.python.org/dev/peps/pep-0539})


@geindex Py_tss_t (C 类型)
@anchor{c-api/init c Py_tss_t}@anchor{431}
@deffn {C 类型} Py_tss_t

This data structure represents the state of a thread key, the definition of
which may depend on the underlying TLS implementation, and it has an
internal field representing the key's initialization state.  There are no
public members in this structure.

When @ref{3e13,,Py_LIMITED_API} is not defined, static allocation of
this type by @ref{4206,,Py_tss_NEEDS_INIT} is allowed.
@end deffn

@geindex Py_tss_NEEDS_INIT (C 宏)
@anchor{c-api/init c Py_tss_NEEDS_INIT}@anchor{4206}
@deffn {C 宏} Py_tss_NEEDS_INIT

This macro expands to the initializer for @ref{431,,Py_tss_t} variables.
Note that this macro won't be defined with @ref{3e13,,Py_LIMITED_API}.
@end deffn

@menu
* Dynamic Allocation:: 
* 方法: 方法<4>. 

@end menu

@node Dynamic Allocation,方法<4>,,Thread Specific Storage TSS API
@anchor{c-api/init dynamic-allocation}@anchor{4207}
@subsubsection Dynamic Allocation


Dynamic allocation of the @ref{431,,Py_tss_t}, required in extension modules
built with @ref{3e13,,Py_LIMITED_API}, where static allocation of this type
is not possible due to its implementation being opaque at build time.

@geindex PyThread_tss_alloc (C 函数)
@anchor{c-api/init c PyThread_tss_alloc}@anchor{4208}
@deffn {C 函数} Py_tss_t* PyThread_tss_alloc ()

Return a value which is the same state as a value initialized with
@ref{4206,,Py_tss_NEEDS_INIT}, or @code{NULL} in the case of dynamic allocation
failure.
@end deffn

@geindex PyThread_tss_free (C 函数)
@anchor{c-api/init c PyThread_tss_free}@anchor{4209}
@deffn {C 函数} void PyThread_tss_free (Py_tss_t@w{ }*key)

Free the given @emph{key} allocated by @ref{4208,,PyThread_tss_alloc()}, after
first calling @ref{420a,,PyThread_tss_delete()} to ensure any associated
thread locals have been unassigned. This is a no-op if the @emph{key}
argument is @cite{NULL}.

@cartouche
@quotation 注解 
A freed key becomes a dangling pointer. You should reset the key to
@cite{NULL}.
@end quotation
@end cartouche
@end deffn

@node 方法<4>,,Dynamic Allocation,Thread Specific Storage TSS API
@anchor{c-api/init methods}@anchor{420b}
@subsubsection 方法


The parameter @emph{key} of these functions must not be @code{NULL}.  Moreover, the
behaviors of @ref{420c,,PyThread_tss_set()} and @ref{420d,,PyThread_tss_get()} are
undefined if the given @ref{431,,Py_tss_t} has not been initialized by
@ref{420e,,PyThread_tss_create()}.

@geindex PyThread_tss_is_created (C 函数)
@anchor{c-api/init c PyThread_tss_is_created}@anchor{420f}
@deffn {C 函数} int PyThread_tss_is_created (Py_tss_t@w{ }*key)

Return a non-zero value if the given @ref{431,,Py_tss_t} has been initialized
by @ref{420e,,PyThread_tss_create()}.
@end deffn

@geindex PyThread_tss_create (C 函数)
@anchor{c-api/init c PyThread_tss_create}@anchor{420e}
@deffn {C 函数} int PyThread_tss_create (Py_tss_t@w{ }*key)

Return a zero value on successful initialization of a TSS key.  The behavior
is undefined if the value pointed to by the @emph{key} argument is not
initialized by @ref{4206,,Py_tss_NEEDS_INIT}.  This function can be called
repeatedly on the same key -- calling it on an already initialized key is a
no-op and immediately returns success.
@end deffn

@geindex PyThread_tss_delete (C 函数)
@anchor{c-api/init c PyThread_tss_delete}@anchor{420a}
@deffn {C 函数} void PyThread_tss_delete (Py_tss_t@w{ }*key)

Destroy a TSS key to forget the values associated with the key across all
threads, and change the key's initialization state to uninitialized.  A
destroyed key is able to be initialized again by
@ref{420e,,PyThread_tss_create()}. This function can be called repeatedly on
the same key -- calling it on an already destroyed key is a no-op.
@end deffn

@geindex PyThread_tss_set (C 函数)
@anchor{c-api/init c PyThread_tss_set}@anchor{420c}
@deffn {C 函数} int PyThread_tss_set (Py_tss_t@w{ }*key, void@w{ }*value)

Return a zero value to indicate successfully associating a @code{void*}
value with a TSS key in the current thread.  Each thread has a distinct
mapping of the key to a @code{void*} value.
@end deffn

@geindex PyThread_tss_get (C 函数)
@anchor{c-api/init c PyThread_tss_get}@anchor{420d}
@deffn {C 函数} void* PyThread_tss_get (Py_tss_t@w{ }*key)

Return the @code{void*} value associated with a TSS key in the current
thread.  This returns @code{NULL} if no value is associated with the key in the
current thread.
@end deffn

@node Thread Local Storage TLS API,,Thread Specific Storage TSS API,线程本地存储支持
@anchor{c-api/init thread-local-storage-api}@anchor{42f}@anchor{c-api/init thread-local-storage-tls-api}@anchor{4210}
@subsubsection Thread Local Storage (TLS) API



3.7 版后已移除: This API is superseded by
@ref{430,,Thread Specific Storage (TSS) API}.


@cartouche
@quotation 注解 
This version of the API does not support platforms where the native TLS key
is defined in a way that cannot be safely cast to @code{int}.  On such platforms,
@ref{4211,,PyThread_create_key()} will return immediately with a failure status,
and the other TLS functions will all be no-ops on such platforms.
@end quotation
@end cartouche

由于上面提到的兼容性问题，不应在新代码中使用此版本的API。

@geindex PyThread_create_key (C 函数)
@anchor{c-api/init c PyThread_create_key}@anchor{4211}
@deffn {C 函数} int PyThread_create_key ()
@end deffn

@geindex PyThread_delete_key (C 函数)
@anchor{c-api/init c PyThread_delete_key}@anchor{4212}
@deffn {C 函数} void PyThread_delete_key (int@w{ }key)
@end deffn

@geindex PyThread_set_key_value (C 函数)
@anchor{c-api/init c PyThread_set_key_value}@anchor{a5a}
@deffn {C 函数} int PyThread_set_key_value (int@w{ }key, void@w{ }*value)
@end deffn

@geindex PyThread_get_key_value (C 函数)
@anchor{c-api/init c PyThread_get_key_value}@anchor{4213}
@deffn {C 函数} void* PyThread_get_key_value (int@w{ }key)
@end deffn

@geindex PyThread_delete_key_value (C 函数)
@anchor{c-api/init c PyThread_delete_key_value}@anchor{4214}
@deffn {C 函数} void PyThread_delete_key_value (int@w{ }key)
@end deffn

@geindex PyThread_ReInitTLS (C 函数)
@anchor{c-api/init c PyThread_ReInitTLS}@anchor{4215}
@deffn {C 函数} void PyThread_ReInitTLS ()
@end deffn

@node Python初始化配置,内存管理,初始化，终结和线程,Python/C API 参考手册
@anchor{c-api/init_config doc}@anchor{4216}@anchor{c-api/init_config init-config}@anchor{2bd}@anchor{c-api/init_config python-initialization-configuration}@anchor{4217}
@section Python初始化配置



3.8 新版功能.


结构


@itemize *

@item 
@ref{227,,PyConfig}

@item 
@ref{2a0,,PyPreConfig}

@item 
@ref{2a1,,PyStatus}

@item 
@ref{2a2,,PyWideStringList}
@end itemize

函数


@itemize *

@item 
@ref{2a3,,PyConfig_Clear()}

@item 
@ref{2a4,,PyConfig_InitIsolatedConfig()}

@item 
@ref{2a5,,PyConfig_InitPythonConfig()}

@item 
@ref{2a6,,PyConfig_Read()}

@item 
@ref{2a7,,PyConfig_SetArgv()}

@item 
@ref{2a8,,PyConfig_SetBytesArgv()}

@item 
@ref{2a9,,PyConfig_SetBytesString()}

@item 
@ref{2aa,,PyConfig_SetString()}

@item 
@ref{4218,,PyConfig_SetWideStringList()}

@item 
@ref{2ab,,PyPreConfig_InitIsolatedConfig()}

@item 
@ref{2ac,,PyPreConfig_InitPythonConfig()}

@item 
@ref{2ad,,PyStatus_Error()}

@item 
@ref{2ae,,PyStatus_Exception()}

@item 
@ref{2af,,PyStatus_Exit()}

@item 
@ref{2b0,,PyStatus_IsError()}

@item 
@ref{2b1,,PyStatus_IsExit()}

@item 
@ref{2b2,,PyStatus_NoMemory()}

@item 
@ref{2b3,,PyStatus_Ok()}

@item 
@ref{2b4,,PyWideStringList_Append()}

@item 
@ref{2b5,,PyWideStringList_Insert()}

@item 
@ref{2b7,,Py_ExitStatusException()}

@item 
@ref{2b8,,Py_InitializeFromConfig()}

@item 
@ref{2b9,,Py_PreInitialize()}

@item 
@ref{2ba,,Py_PreInitializeFromArgs()}

@item 
@ref{2bb,,Py_PreInitializeFromBytesArgs()}

@item 
@ref{2bc,,Py_RunMain()}

@item 
@ref{1081,,Py_GetArgcArgv()}
@end itemize

The preconfiguration (@code{PyPreConfig} type) is stored in
@code{_PyRuntime.preconfig} and the configuration (@code{PyConfig} type) is stored in
@code{PyInterpreterState.config}.

参见 @ref{41bf,,Initialization@comma{} Finalization@comma{} and Threads}.


@subsubheading 参见


@geindex Python 提高建议; PEP 587
PEP 587@footnote{https://www.python.org/dev/peps/pep-0587} "Python 初始化配置".


@menu
* PyWideStringList:: 
* PyStatus:: 
* PyPreConfig:: 
* Preinitialization with PyPreConfig:: 
* PyConfig:: 
* Initialization with PyConfig:: 
* Isolated Configuration:: 
* Python Configuration:: 
* 路径配置:: 
* Py_RunMain(): Py_RunMain. 
* Py_GetArgcArgv(): Py_GetArgcArgv. 
* Multi-Phase Initialization Private Provisional API:: 

@end menu

@node PyWideStringList,PyStatus,,Python初始化配置
@anchor{c-api/init_config pywidestringlist}@anchor{4219}
@subsection PyWideStringList


@geindex PyWideStringList (C 类型)
@anchor{c-api/init_config c PyWideStringList}@anchor{2a2}
@deffn {C 类型} PyWideStringList

由 @code{wchar_t*} 字符串组成的列表。

如果 @emph{length} 为非零值，则 @emph{items} 必须不为 @code{NULL} 并且所有字符串均必须不为 @code{NULL}。

方法

@geindex PyWideStringList_Append (C 函数)
@anchor{c-api/init_config c PyWideStringList_Append}@anchor{2b4}
@deffn {C 函数} PyStatus PyWideStringList_Append (PyWideStringList@w{ }*list, const wchar_t@w{ }*item)

将 @emph{item} 添加到 @emph{list}。

Python 必须被预初始化以便调用此函数。
@end deffn

@geindex PyWideStringList_Insert (C 函数)
@anchor{c-api/init_config c PyWideStringList_Insert}@anchor{2b5}
@deffn {C 函数} PyStatus PyWideStringList_Insert (PyWideStringList@w{ }*list, Py_ssize_t@w{ }index, const wchar_t@w{ }*item)

将 @emph{item} 插入到 @emph{list} 的 @emph{index} 位置上。

如果 @emph{index} 大于等于 @emph{list} 的长度，则将 @emph{item} 添加到 @emph{list}。

@emph{index} must be greater than or equal to 0.

Python 必须被预初始化以便调用此函数。
@end deffn

Structure fields:

@geindex PyWideStringList.length (C 成员)
@anchor{c-api/init_config c PyWideStringList length}@anchor{421a}
@deffn {C 成员} Py_ssize_t length

List 长度。
@end deffn

@geindex PyWideStringList.items (C 成员)
@anchor{c-api/init_config c PyWideStringList items}@anchor{421b}
@deffn {C 成员} wchar_t** items

列表项目。
@end deffn
@end deffn

@node PyStatus,PyPreConfig,PyWideStringList,Python初始化配置
@anchor{c-api/init_config pystatus}@anchor{421c}
@subsection PyStatus


@geindex PyStatus (C 类型)
@anchor{c-api/init_config c PyStatus}@anchor{2a1}
@deffn {C 类型} PyStatus

Structure to store an initialization function status: success, error
or exit.

For an error, it can store the C function name which created the error.

Structure fields:

@geindex PyStatus.exitcode (C 成员)
@anchor{c-api/init_config c PyStatus exitcode}@anchor{421d}
@deffn {C 成员} int exitcode

Exit code. Argument passed to @code{exit()}.
@end deffn

@geindex PyStatus.err_msg (C 成员)
@anchor{c-api/init_config c PyStatus err_msg}@anchor{421e}
@deffn {C 成员} const char *err_msg

错误信息
@end deffn

@geindex PyStatus.func (C 成员)
@anchor{c-api/init_config c PyStatus func}@anchor{421f}
@deffn {C 成员} const char *func

Name of the function which created an error, can be @code{NULL}.
@end deffn

Functions to create a status:

@geindex PyStatus_Ok (C 函数)
@anchor{c-api/init_config c PyStatus_Ok}@anchor{2b3}
@deffn {C 函数} PyStatus PyStatus_Ok (void)

完成。
@end deffn

@geindex PyStatus_Error (C 函数)
@anchor{c-api/init_config c PyStatus_Error}@anchor{2ad}
@deffn {C 函数} PyStatus PyStatus_Error (const char@w{ }*err_msg)

Initialization error with a message.
@end deffn

@geindex PyStatus_NoMemory (C 函数)
@anchor{c-api/init_config c PyStatus_NoMemory}@anchor{2b2}
@deffn {C 函数} PyStatus PyStatus_NoMemory (void)

Memory allocation failure (out of memory).
@end deffn

@geindex PyStatus_Exit (C 函数)
@anchor{c-api/init_config c PyStatus_Exit}@anchor{2af}
@deffn {C 函数} PyStatus PyStatus_Exit (int@w{ }exitcode)

以指定的退出代码退出 Python。
@end deffn

Functions to handle a status:

@geindex PyStatus_Exception (C 函数)
@anchor{c-api/init_config c PyStatus_Exception}@anchor{2ae}
@deffn {C 函数} int PyStatus_Exception (PyStatus@w{ }status)

Is the status an error or an exit? If true, the exception must be
handled; by calling @ref{2b7,,Py_ExitStatusException()} for example.
@end deffn

@geindex PyStatus_IsError (C 函数)
@anchor{c-api/init_config c PyStatus_IsError}@anchor{2b0}
@deffn {C 函数} int PyStatus_IsError (PyStatus@w{ }status)

结果错误吗？
@end deffn

@geindex PyStatus_IsExit (C 函数)
@anchor{c-api/init_config c PyStatus_IsExit}@anchor{2b1}
@deffn {C 函数} int PyStatus_IsExit (PyStatus@w{ }status)

结果是否退出？
@end deffn

@geindex Py_ExitStatusException (C 函数)
@anchor{c-api/init_config c Py_ExitStatusException}@anchor{2b7}
@deffn {C 函数} void Py_ExitStatusException (PyStatus@w{ }status)

Call @code{exit(exitcode)} if @emph{status} is an exit. Print the error
message and exit with a non-zero exit code if @emph{status} is an error.  Must
only be called if @code{PyStatus_Exception(status)} is non-zero.
@end deffn
@end deffn

@cartouche
@quotation 注解 
Internally, Python uses macros which set @code{PyStatus.func},
whereas functions to create a status set @code{func} to @code{NULL}.
@end quotation
@end cartouche

示例:

@example
PyStatus alloc(void **ptr, size_t size)
@{
    *ptr = PyMem_RawMalloc(size);
    if (*ptr == NULL) @{
        return PyStatus_NoMemory();
    @}
    return PyStatus_Ok();
@}

int main(int argc, char **argv)
@{
    void *ptr;
    PyStatus status = alloc(&ptr, 16);
    if (PyStatus_Exception(status)) @{
        Py_ExitStatusException(status);
    @}
    PyMem_Free(ptr);
    return 0;
@}
@end example

@node PyPreConfig,Preinitialization with PyPreConfig,PyStatus,Python初始化配置
@anchor{c-api/init_config pypreconfig}@anchor{4220}
@subsection PyPreConfig


@geindex PyPreConfig (C 类型)
@anchor{c-api/init_config c PyPreConfig}@anchor{2a0}
@deffn {C 类型} PyPreConfig

Structure used to preinitialize Python:


@itemize *

@item 
Set the Python memory allocator

@item 
Configure the LC_CTYPE locale

@item 
设置为 UTF-8 模式
@end itemize

Function to initialize a preconfiguration:

@geindex PyPreConfig_InitPythonConfig (C 函数)
@anchor{c-api/init_config c PyPreConfig_InitPythonConfig}@anchor{2ac}
@deffn {C 函数} void PyPreConfig_InitPythonConfig (PyPreConfig@w{ }*preconfig)

Initialize the preconfiguration with @ref{4221,,Python Configuration}.
@end deffn

@geindex PyPreConfig_InitIsolatedConfig (C 函数)
@anchor{c-api/init_config c PyPreConfig_InitIsolatedConfig}@anchor{2ab}
@deffn {C 函数} void PyPreConfig_InitIsolatedConfig (PyPreConfig@w{ }*preconfig)

Initialize the preconfiguration with @ref{4222,,Isolated Configuration}.
@end deffn

Structure fields:

@geindex PyPreConfig.allocator (C 成员)
@anchor{c-api/init_config c PyPreConfig allocator}@anchor{4223}
@deffn {C 成员} int allocator

Name of the memory allocator:


@itemize *

@item 
@code{PYMEM_ALLOCATOR_NOT_SET} (@code{0}): don't change memory allocators
(use defaults)

@item 
@code{PYMEM_ALLOCATOR_DEFAULT} (@code{1}): default memory allocators

@item 
@code{PYMEM_ALLOCATOR_DEBUG} (@code{2}): default memory allocators with
debug hooks

@item 
@code{PYMEM_ALLOCATOR_MALLOC} (@code{3}): force usage of @code{malloc()}

@item 
@code{PYMEM_ALLOCATOR_MALLOC_DEBUG} (@code{4}): force usage of
@code{malloc()} with debug hooks

@item 
@code{PYMEM_ALLOCATOR_PYMALLOC} (@code{5}): @ref{6c2,,Python pymalloc memory allocator}

@item 
@code{PYMEM_ALLOCATOR_PYMALLOC_DEBUG} (@code{6}): @ref{6c2,,Python pymalloc memory allocator} with debug hooks
@end itemize

@code{PYMEM_ALLOCATOR_PYMALLOC} and @code{PYMEM_ALLOCATOR_PYMALLOC_DEBUG}
are not supported if Python is configured using @code{--without-pymalloc}

参见 @ref{4224,,Memory Management}.
@end deffn

@geindex PyPreConfig.configure_locale (C 成员)
@anchor{c-api/init_config c PyPreConfig configure_locale}@anchor{4225}
@deffn {C 成员} int configure_locale

Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set
@code{coerce_c_locale} and @code{coerce_c_locale_warn} to 0.
@end deffn

@geindex PyPreConfig.coerce_c_locale (C 成员)
@anchor{c-api/init_config c PyPreConfig coerce_c_locale}@anchor{4226}
@deffn {C 成员} int coerce_c_locale

If equals to 2, coerce the C locale; if equals to 1, read the LC_CTYPE
locale to decide if it should be coerced.
@end deffn

@geindex PyPreConfig.coerce_c_locale_warn (C 成员)
@anchor{c-api/init_config c PyPreConfig coerce_c_locale_warn}@anchor{4227}
@deffn {C 成员} int coerce_c_locale_warn

If non-zero, emit a warning if the C locale is coerced.
@end deffn

@geindex PyPreConfig.dev_mode (C 成员)
@anchor{c-api/init_config c PyPreConfig dev_mode}@anchor{4228}
@deffn {C 成员} int dev_mode

参见 @ref{4229,,PyConfig.dev_mode}.
@end deffn

@geindex PyPreConfig.isolated (C 成员)
@anchor{c-api/init_config c PyPreConfig isolated}@anchor{422a}
@deffn {C 成员} int isolated

参见 @ref{422b,,PyConfig.isolated}.
@end deffn

@geindex PyPreConfig.legacy_windows_fs_encoding (C 成员)
@anchor{c-api/init_config c PyPreConfig legacy_windows_fs_encoding}@anchor{422c}
@deffn {C 成员} int legacy_windows_fs_encoding (Windows@w{ }only)

If non-zero, disable UTF-8 Mode, set the Python filesystem encoding to
@code{mbcs}, set the filesystem error handler to @code{replace}.

Only available on Windows. @code{#ifdef MS_WINDOWS} macro can be used for
Windows specific code.
@end deffn

@geindex PyPreConfig.parse_argv (C 成员)
@anchor{c-api/init_config c PyPreConfig parse_argv}@anchor{422d}
@deffn {C 成员} int parse_argv

If non-zero, @ref{2ba,,Py_PreInitializeFromArgs()} and
@ref{2bb,,Py_PreInitializeFromBytesArgs()} parse their @code{argv} argument the
same way the regular Python parses command line arguments: see
@ref{a19,,Command Line Arguments}.
@end deffn

@geindex PyPreConfig.use_environment (C 成员)
@anchor{c-api/init_config c PyPreConfig use_environment}@anchor{422e}
@deffn {C 成员} int use_environment

参见 @ref{261,,PyConfig.use_environment}.
@end deffn

@geindex PyPreConfig.utf8_mode (C 成员)
@anchor{c-api/init_config c PyPreConfig utf8_mode}@anchor{422f}
@deffn {C 成员} int utf8_mode

If non-zero, enable the UTF-8 mode.
@end deffn
@end deffn

@node Preinitialization with PyPreConfig,PyConfig,PyPreConfig,Python初始化配置
@anchor{c-api/init_config preinitialization-with-pypreconfig}@anchor{4230}
@subsection Preinitialization with PyPreConfig


Functions to preinitialize Python:

@geindex Py_PreInitialize (C 函数)
@anchor{c-api/init_config c Py_PreInitialize}@anchor{2b9}
@deffn {C 函数} PyStatus Py_PreInitialize (const PyPreConfig@w{ }*preconfig)

Preinitialize Python from @emph{preconfig} preconfiguration.
@end deffn

@geindex Py_PreInitializeFromBytesArgs (C 函数)
@anchor{c-api/init_config c Py_PreInitializeFromBytesArgs}@anchor{2bb}
@deffn {C 函数} PyStatus Py_PreInitializeFromBytesArgs (const PyPreConfig@w{ }*preconfig, int@w{ }argc, char * const@w{ }*argv)

Preinitialize Python from @emph{preconfig} preconfiguration and command line
arguments (bytes strings).
@end deffn

@geindex Py_PreInitializeFromArgs (C 函数)
@anchor{c-api/init_config c Py_PreInitializeFromArgs}@anchor{2ba}
@deffn {C 函数} PyStatus Py_PreInitializeFromArgs (const PyPreConfig@w{ }*preconfig, int@w{ }argc, wchar_t * const *@w{ }argv)

Preinitialize Python from @emph{preconfig} preconfiguration and command line
arguments (wide strings).
@end deffn

The caller is responsible to handle exceptions (error or exit) using
@ref{2ae,,PyStatus_Exception()} and @ref{2b7,,Py_ExitStatusException()}.

For @ref{4221,,Python Configuration}
(@ref{2ac,,PyPreConfig_InitPythonConfig()}), if Python is initialized with
command line arguments, the command line arguments must also be passed to
preinitialize Python, since they have an effect on the pre-configuration
like encodings. For example, the @ref{297,,-X utf8} command line option
enables the UTF-8 Mode.

@code{PyMem_SetAllocator()} can be called after @ref{2b9,,Py_PreInitialize()} and
before @ref{2b8,,Py_InitializeFromConfig()} to install a custom memory allocator.
It can be called before @ref{2b9,,Py_PreInitialize()} if
@ref{4223,,PyPreConfig.allocator} is set to @code{PYMEM_ALLOCATOR_NOT_SET}.

Python memory allocation functions like @ref{a57,,PyMem_RawMalloc()} must not be
used before Python preinitialization, whereas calling directly @code{malloc()} and
@code{free()} is always safe. @ref{547,,Py_DecodeLocale()} must not be called before
the preinitialization.

Example using the preinitialization to enable the UTF-8 Mode:

@example
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);

preconfig.utf8_mode = 1;

status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) @{
    Py_ExitStatusException(status);
@}

/* at this point, Python will speak UTF-8 */

Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
@end example

@node PyConfig,Initialization with PyConfig,Preinitialization with PyPreConfig,Python初始化配置
@anchor{c-api/init_config pyconfig}@anchor{4231}
@subsection PyConfig


@geindex PyConfig (C 类型)
@anchor{c-api/init_config c PyConfig}@anchor{227}
@deffn {C 类型} PyConfig

Structure containing most parameters to configure Python.

Structure methods:

@geindex PyConfig_InitPythonConfig (C 函数)
@anchor{c-api/init_config c PyConfig_InitPythonConfig}@anchor{2a5}
@deffn {C 函数} void PyConfig_InitPythonConfig (PyConfig@w{ }*config)

Initialize configuration with @ref{4221,,Python Configuration}.
@end deffn

@geindex PyConfig_InitIsolatedConfig (C 函数)
@anchor{c-api/init_config c PyConfig_InitIsolatedConfig}@anchor{2a4}
@deffn {C 函数} void PyConfig_InitIsolatedConfig (PyConfig@w{ }*config)

Initialize configuration with @ref{4222,,Isolated Configuration}.
@end deffn

@geindex PyConfig_SetString (C 函数)
@anchor{c-api/init_config c PyConfig_SetString}@anchor{2aa}
@deffn {C 函数} PyStatus PyConfig_SetString (PyConfig@w{ }*config, wchar_t * const@w{ }*config_str, const wchar_t@w{ }*str)

Copy the wide character string @emph{str} into @code{*config_str}.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_SetBytesString (C 函数)
@anchor{c-api/init_config c PyConfig_SetBytesString}@anchor{2a9}
@deffn {C 函数} PyStatus PyConfig_SetBytesString (PyConfig@w{ }*config, wchar_t * const@w{ }*config_str, const char@w{ }*str)

Decode @emph{str} using @code{Py_DecodeLocale()} and set the result into @code{*config_str}.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_SetArgv (C 函数)
@anchor{c-api/init_config c PyConfig_SetArgv}@anchor{2a7}
@deffn {C 函数} PyStatus PyConfig_SetArgv (PyConfig@w{ }*config, int@w{ }argc, wchar_t * const@w{ }*argv)

Set command line arguments from wide character strings.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_SetBytesArgv (C 函数)
@anchor{c-api/init_config c PyConfig_SetBytesArgv}@anchor{2a8}
@deffn {C 函数} PyStatus PyConfig_SetBytesArgv (PyConfig@w{ }*config, int@w{ }argc, char * const@w{ }*argv)

Set command line arguments: decode bytes using @ref{547,,Py_DecodeLocale()}.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_SetWideStringList (C 函数)
@anchor{c-api/init_config c PyConfig_SetWideStringList}@anchor{4218}
@deffn {C 函数} PyStatus PyConfig_SetWideStringList (PyConfig@w{ }*config, PyWideStringList@w{ }*list, Py_ssize_t@w{ }length, wchar_t@w{ }**items)

Set the list of wide strings @emph{list} to @emph{length} and @emph{items}.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_Read (C 函数)
@anchor{c-api/init_config c PyConfig_Read}@anchor{2a6}
@deffn {C 函数} PyStatus PyConfig_Read (PyConfig@w{ }*config)

Read all Python configuration.

Fields which are already initialized are left unchanged.

Preinitialize Python if needed.
@end deffn

@geindex PyConfig_Clear (C 函数)
@anchor{c-api/init_config c PyConfig_Clear}@anchor{2a3}
@deffn {C 函数} void PyConfig_Clear (PyConfig@w{ }*config)

Release configuration memory.
@end deffn

Most @code{PyConfig} methods preinitialize Python if needed. In that case, the
Python preinitialization configuration in based on the @ref{227,,PyConfig}.
If configuration fields which are in common with @ref{2a0,,PyPreConfig} are
tuned, they must be set before calling a @ref{227,,PyConfig} method:


@itemize *

@item 
@ref{4229,,dev_mode}

@item 
@ref{422b,,isolated}

@item 
@ref{4232,,parse_argv}

@item 
@ref{261,,use_environment}
@end itemize

Moreover, if @ref{2a7,,PyConfig_SetArgv()} or @ref{2a8,,PyConfig_SetBytesArgv()}
is used, this method must be called first, before other methods, since the
preinitialization configuration depends on command line arguments (if
@code{parse_argv} is non-zero).

The caller of these methods is responsible to handle exceptions (error or
exit) using @code{PyStatus_Exception()} and @code{Py_ExitStatusException()}.

Structure fields:

@geindex PyConfig.argv (C 成员)
@anchor{c-api/init_config c PyConfig argv}@anchor{4233}
@deffn {C 成员} PyWideStringList argv

Command line arguments, @ref{cce,,sys.argv}. See
@ref{4232,,parse_argv} to parse @ref{4233,,argv} the
same way the regular Python parses Python command line arguments. If
@ref{4233,,argv} is empty, an empty string is added to ensure
that @ref{cce,,sys.argv} always exists and is never empty.
@end deffn

@geindex PyConfig.base_exec_prefix (C 成员)
@anchor{c-api/init_config c PyConfig base_exec_prefix}@anchor{4234}
@deffn {C 成员} wchar_t* base_exec_prefix

@ref{3688,,sys.base_exec_prefix}.
@end deffn

@geindex PyConfig.base_executable (C 成员)
@anchor{c-api/init_config c PyConfig base_executable}@anchor{4235}
@deffn {C 成员} wchar_t* base_executable

@code{sys._base_executable}: @code{__PYVENV_LAUNCHER__} environment
variable value, or copy of @ref{4236,,PyConfig.executable}.
@end deffn

@geindex PyConfig.base_prefix (C 成员)
@anchor{c-api/init_config c PyConfig base_prefix}@anchor{4237}
@deffn {C 成员} wchar_t* base_prefix

@ref{305e,,sys.base_prefix}.
@end deffn

@geindex PyConfig.platlibdir (C 成员)
@anchor{c-api/init_config c PyConfig platlibdir}@anchor{1061}
@deffn {C 成员} wchar_t* platlibdir

@ref{1ea,,sys.platlibdir}: platform library directory name, set at configure time
by @code{--with-platlibdir}, overrideable by the @code{PYTHONPLATLIBDIR}
environment variable.


3.9 新版功能.

@end deffn

@geindex PyConfig.buffered_stdio (C 成员)
@anchor{c-api/init_config c PyConfig buffered_stdio}@anchor{4238}
@deffn {C 成员} int buffered_stdio

If equals to 0, enable unbuffered mode, making the stdout and stderr
streams unbuffered.

stdin is always opened in buffered mode.
@end deffn

@geindex PyConfig.bytes_warning (C 成员)
@anchor{c-api/init_config c PyConfig bytes_warning}@anchor{4239}
@deffn {C 成员} int bytes_warning

If equals to 1, issue a warning when comparing @ref{172,,bytes} or
@ref{173,,bytearray} with @ref{206,,str}, or comparing @ref{172,,bytes} with
@ref{205,,int}. If equal or greater to 2, raise a @ref{5b8,,BytesWarning}
exception.
@end deffn

@geindex PyConfig.check_hash_pycs_mode (C 成员)
@anchor{c-api/init_config c PyConfig check_hash_pycs_mode}@anchor{423a}
@deffn {C 成员} wchar_t* check_hash_pycs_mode

Control the validation behavior of hash-based @code{.pyc} files (see
@geindex Python 提高建议; PEP 552
PEP 552@footnote{https://www.python.org/dev/peps/pep-0552}): @ref{14a5,,--check-hash-based-pycs} command line option value.

Valid values: @code{always}, @code{never} and @code{default}.

默认值为: @code{default}.
@end deffn

@geindex PyConfig.configure_c_stdio (C 成员)
@anchor{c-api/init_config c PyConfig configure_c_stdio}@anchor{423b}
@deffn {C 成员} int configure_c_stdio

If non-zero, configure C standard streams (@code{stdio}, @code{stdout},
@code{stdout}). For example, set their mode to @code{O_BINARY} on Windows.
@end deffn

@geindex PyConfig.dev_mode (C 成员)
@anchor{c-api/init_config c PyConfig dev_mode}@anchor{4229}
@deffn {C 成员} int dev_mode

If non-zero, enable the @ref{160,,Python Development Mode}.
@end deffn

@geindex PyConfig.dump_refs (C 成员)
@anchor{c-api/init_config c PyConfig dump_refs}@anchor{423c}
@deffn {C 成员} int dump_refs

If non-zero, dump all objects which are still alive at exit.

@code{Py_TRACE_REFS} macro must be defined in build.
@end deffn

@geindex PyConfig.exec_prefix (C 成员)
@anchor{c-api/init_config c PyConfig exec_prefix}@anchor{423d}
@deffn {C 成员} wchar_t* exec_prefix

@ref{3687,,sys.exec_prefix}.
@end deffn

@geindex PyConfig.executable (C 成员)
@anchor{c-api/init_config c PyConfig executable}@anchor{4236}
@deffn {C 成员} wchar_t* executable

@ref{3a5,,sys.executable}.
@end deffn

@geindex PyConfig.faulthandler (C 成员)
@anchor{c-api/init_config c PyConfig faulthandler}@anchor{423e}
@deffn {C 成员} int faulthandler

If non-zero, call @ref{64b,,faulthandler.enable()} at startup.
@end deffn

@geindex PyConfig.filesystem_encoding (C 成员)
@anchor{c-api/init_config c PyConfig filesystem_encoding}@anchor{423f}
@deffn {C 成员} wchar_t* filesystem_encoding

Filesystem encoding, @ref{5f8,,sys.getfilesystemencoding()}.
@end deffn

@geindex PyConfig.filesystem_errors (C 成员)
@anchor{c-api/init_config c PyConfig filesystem_errors}@anchor{4240}
@deffn {C 成员} wchar_t* filesystem_errors

Filesystem encoding errors, @ref{695,,sys.getfilesystemencodeerrors()}.
@end deffn

@geindex PyConfig.hash_seed (C 成员)
@anchor{c-api/init_config c PyConfig hash_seed}@anchor{4241}
@deffn {C 成员} unsigned long hash_seed
@end deffn

@geindex PyConfig.use_hash_seed (C 成员)
@anchor{c-api/init_config c PyConfig use_hash_seed}@anchor{4242}
@deffn {C 成员} int use_hash_seed

Randomized hash function seed.

If @ref{4242,,use_hash_seed} is zero, a seed is chosen randomly
at Pythonstartup, and @ref{4241,,hash_seed} is ignored.
@end deffn

@geindex PyConfig.home (C 成员)
@anchor{c-api/init_config c PyConfig home}@anchor{4243}
@deffn {C 成员} wchar_t* home

Python home directory.

Initialized from 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} environment variable value by
default.
@end deffn

@geindex PyConfig.import_time (C 成员)
@anchor{c-api/init_config c PyConfig import_time}@anchor{4244}
@deffn {C 成员} int import_time

If non-zero, profile import time.
@end deffn

@geindex PyConfig.inspect (C 成员)
@anchor{c-api/init_config c PyConfig inspect}@anchor{4245}
@deffn {C 成员} int inspect

Enter interactive mode after executing a script or a command.
@end deffn

@geindex PyConfig.install_signal_handlers (C 成员)
@anchor{c-api/init_config c PyConfig install_signal_handlers}@anchor{102d}
@deffn {C 成员} int install_signal_handlers

Install signal handlers?
@end deffn

@geindex PyConfig.interactive (C 成员)
@anchor{c-api/init_config c PyConfig interactive}@anchor{4246}
@deffn {C 成员} int interactive

交互模式
@end deffn

@geindex PyConfig.isolated (C 成员)
@anchor{c-api/init_config c PyConfig isolated}@anchor{422b}
@deffn {C 成员} int isolated

If greater than 0, enable isolated mode:


@itemize *

@item 
@ref{262,,sys.path} contains neither the script's directory (computed from
@code{argv[0]} or the current directory) nor the user's site-packages
directory.

@item 
Python REPL doesn't import @ref{de,,readline} nor enable default readline
configuration on interactive prompts.

@item 
Set @ref{261,,use_environment} and
@ref{4247,,user_site_directory} to 0.
@end itemize
@end deffn

@geindex PyConfig.legacy_windows_stdio (C 成员)
@anchor{c-api/init_config c PyConfig legacy_windows_stdio}@anchor{4248}
@deffn {C 成员} int legacy_windows_stdio

If non-zero, use @ref{d74,,io.FileIO} instead of
@code{io.WindowsConsoleIO} for @ref{427,,sys.stdin}, @ref{428,,sys.stdout}
and @ref{1eb,,sys.stderr}.

Only available on Windows. @code{#ifdef MS_WINDOWS} macro can be used for
Windows specific code.
@end deffn

@geindex PyConfig.malloc_stats (C 成员)
@anchor{c-api/init_config c PyConfig malloc_stats}@anchor{4249}
@deffn {C 成员} int malloc_stats

If non-zero, dump statistics on @ref{6c2,,Python pymalloc memory allocator} at exit.

The option is ignored if Python is built using @code{--without-pymalloc}.
@end deffn

@geindex PyConfig.pythonpath_env (C 成员)
@anchor{c-api/init_config c PyConfig pythonpath_env}@anchor{424a}
@deffn {C 成员} wchar_t* pythonpath_env

Module search paths as a string separated by @code{DELIM}
(@code{os.path.pathsep}).

Initialized from 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} environment variable value by
default.
@end deffn

@geindex PyConfig.module_search_paths (C 成员)
@anchor{c-api/init_config c PyConfig module_search_paths}@anchor{424b}
@deffn {C 成员} PyWideStringList module_search_paths
@end deffn

@geindex PyConfig.module_search_paths_set (C 成员)
@anchor{c-api/init_config c PyConfig module_search_paths_set}@anchor{424c}
@deffn {C 成员} int module_search_paths_set

@ref{262,,sys.path}. If @ref{424c,,module_search_paths_set} is
equal to 0, the @ref{424b,,module_search_paths} is overridden
by the function calculating the @ref{1060,,Path Configuration}.
@end deffn

@geindex PyConfig.optimization_level (C 成员)
@anchor{c-api/init_config c PyConfig optimization_level}@anchor{424d}
@deffn {C 成员} int optimization_level

Compilation optimization level:


@itemize *

@item 
0: Peephole optimizer (and @code{__debug__} is set to @code{True})

@item 
1: Remove assertions, set @code{__debug__} to @code{False}

@item 
2: Strip docstrings
@end itemize
@end deffn

@geindex PyConfig.parse_argv (C 成员)
@anchor{c-api/init_config c PyConfig parse_argv}@anchor{4232}
@deffn {C 成员} int parse_argv

If non-zero, parse @ref{4233,,argv} the same way the regular
Python command line arguments, and strip Python arguments from
@ref{4233,,argv}: see @ref{a19,,Command Line Arguments}.
@end deffn

@geindex PyConfig.parser_debug (C 成员)
@anchor{c-api/init_config c PyConfig parser_debug}@anchor{424e}
@deffn {C 成员} int parser_debug

If non-zero, turn on parser debugging output (for expert only, depending
on compilation options).
@end deffn

@geindex PyConfig.pathconfig_warnings (C 成员)
@anchor{c-api/init_config c PyConfig pathconfig_warnings}@anchor{424f}
@deffn {C 成员} int pathconfig_warnings

If equal to 0, suppress warnings when calculating the @ref{1060,,Path Configuration} (Unix only, Windows does not log any
warning). Otherwise, warnings are written into @code{stderr}.
@end deffn

@geindex PyConfig.prefix (C 成员)
@anchor{c-api/init_config c PyConfig prefix}@anchor{4250}
@deffn {C 成员} wchar_t* prefix

@ref{3686,,sys.prefix}.
@end deffn

@geindex PyConfig.program_name (C 成员)
@anchor{c-api/init_config c PyConfig program_name}@anchor{4251}
@deffn {C 成员} wchar_t* program_name

Program name. Used to initialize @ref{4236,,executable}, and in
early error messages.
@end deffn

@geindex PyConfig.pycache_prefix (C 成员)
@anchor{c-api/init_config c PyConfig pycache_prefix}@anchor{4252}
@deffn {C 成员} wchar_t* pycache_prefix

@ref{298,,sys.pycache_prefix}: @code{.pyc} cache prefix.

If @code{NULL}, @ref{298,,sys.pycache_prefix} is set to @code{None}.
@end deffn

@geindex PyConfig.quiet (C 成员)
@anchor{c-api/init_config c PyConfig quiet}@anchor{4253}
@deffn {C 成员} int quiet

Quiet mode. For example, don't display the copyright and version messages
in interactive mode.
@end deffn

@geindex PyConfig.run_command (C 成员)
@anchor{c-api/init_config c PyConfig run_command}@anchor{4254}
@deffn {C 成员} wchar_t* run_command

@code{python3 -c COMMAND} argument. Used by @ref{2bc,,Py_RunMain()}.
@end deffn

@geindex PyConfig.run_filename (C 成员)
@anchor{c-api/init_config c PyConfig run_filename}@anchor{4255}
@deffn {C 成员} wchar_t* run_filename

@code{python3 FILENAME} argument. Used by @ref{2bc,,Py_RunMain()}.
@end deffn

@geindex PyConfig.run_module (C 成员)
@anchor{c-api/init_config c PyConfig run_module}@anchor{4256}
@deffn {C 成员} wchar_t* run_module

@code{python3 -m MODULE} argument. Used by @ref{2bc,,Py_RunMain()}.
@end deffn

@geindex PyConfig.show_ref_count (C 成员)
@anchor{c-api/init_config c PyConfig show_ref_count}@anchor{4257}
@deffn {C 成员} int show_ref_count

Show total reference count at exit?

Set to 1 by @ref{297,,-X showrefcount} command line option.

Need a debug build of Python (@code{Py_REF_DEBUG} macro must be defined).
@end deffn

@geindex PyConfig.site_import (C 成员)
@anchor{c-api/init_config c PyConfig site_import}@anchor{4258}
@deffn {C 成员} int site_import

Import the @ref{eb,,site} module at startup?
@end deffn

@geindex PyConfig.skip_source_first_line (C 成员)
@anchor{c-api/init_config c PyConfig skip_source_first_line}@anchor{4259}
@deffn {C 成员} int skip_source_first_line

Skip the first line of the source?
@end deffn

@geindex PyConfig.stdio_encoding (C 成员)
@anchor{c-api/init_config c PyConfig stdio_encoding}@anchor{425a}
@deffn {C 成员} wchar_t* stdio_encoding
@end deffn

@geindex PyConfig.stdio_errors (C 成员)
@anchor{c-api/init_config c PyConfig stdio_errors}@anchor{425b}
@deffn {C 成员} wchar_t* stdio_errors

Encoding and encoding errors of @ref{427,,sys.stdin}, @ref{428,,sys.stdout} and
@ref{1eb,,sys.stderr}.
@end deffn

@geindex PyConfig.tracemalloc (C 成员)
@anchor{c-api/init_config c PyConfig tracemalloc}@anchor{425c}
@deffn {C 成员} int tracemalloc

If non-zero, call @ref{14b1,,tracemalloc.start()} at startup.
@end deffn

@geindex PyConfig.use_environment (C 成员)
@anchor{c-api/init_config c PyConfig use_environment}@anchor{261}
@deffn {C 成员} int use_environment

If greater than 0, use @ref{14b5,,environment variables}.
@end deffn

@geindex PyConfig.user_site_directory (C 成员)
@anchor{c-api/init_config c PyConfig user_site_directory}@anchor{4247}
@deffn {C 成员} int user_site_directory

If non-zero, add user site directory to @ref{262,,sys.path}.
@end deffn

@geindex PyConfig.verbose (C 成员)
@anchor{c-api/init_config c PyConfig verbose}@anchor{425d}
@deffn {C 成员} int verbose

If non-zero, enable verbose mode.
@end deffn

@geindex PyConfig.warnoptions (C 成员)
@anchor{c-api/init_config c PyConfig warnoptions}@anchor{425e}
@deffn {C 成员} PyWideStringList warnoptions

@ref{523,,sys.warnoptions}: options of the @ref{12f,,warnings} module to build
warnings filters: lowest to highest priority.

The @ref{12f,,warnings} module adds @ref{523,,sys.warnoptions} in the reverse
order: the last @ref{425e,,PyConfig.warnoptions} item becomes the first
item of @code{warnings.filters} which is checked first (highest
priority).
@end deffn

@geindex PyConfig.write_bytecode (C 成员)
@anchor{c-api/init_config c PyConfig write_bytecode}@anchor{425f}
@deffn {C 成员} int write_bytecode

If non-zero, write @code{.pyc} files.

@ref{36b4,,sys.dont_write_bytecode} is initialized to the inverted value of
@ref{425f,,write_bytecode}.
@end deffn

@geindex PyConfig.xoptions (C 成员)
@anchor{c-api/init_config c PyConfig xoptions}@anchor{4260}
@deffn {C 成员} PyWideStringList xoptions

@ref{14b2,,sys._xoptions}.
@end deffn

@geindex PyConfig._use_peg_parser (C 成员)
@anchor{c-api/init_config c PyConfig _use_peg_parser}@anchor{4261}
@deffn {C 成员} int _use_peg_parser

Enable PEG parser? Default: 1.

Set to 0 by @ref{297,,-X oldparser} and 
@geindex PYTHONOLDPARSER
@geindex 环境变量; PYTHONOLDPARSER
@ref{14b0,,PYTHONOLDPARSER}.

参见 
@geindex Python 提高建议; PEP 617
PEP 617@footnote{https://www.python.org/dev/peps/pep-0617}。


Deprecated since version 3.9, will be removed in version 3.10.

@end deffn
@end deffn

If @code{parse_argv} is non-zero, @code{argv} arguments are parsed the same
way the regular Python parses command line arguments, and Python
arguments are stripped from @code{argv}: see @ref{a19,,Command Line Arguments}.

The @code{xoptions} options are parsed to set other options: see @ref{297,,-X}
option.


在 3.9 版更改: The @code{show_alloc_count} field has been removed.


@node Initialization with PyConfig,Isolated Configuration,PyConfig,Python初始化配置
@anchor{c-api/init_config initialization-with-pyconfig}@anchor{4262}
@subsection Initialization with PyConfig


Function to initialize Python:

@geindex Py_InitializeFromConfig (C 函数)
@anchor{c-api/init_config c Py_InitializeFromConfig}@anchor{2b8}
@deffn {C 函数} PyStatus Py_InitializeFromConfig (const PyConfig@w{ }*config)

Initialize Python from @emph{config} configuration.
@end deffn

The caller is responsible to handle exceptions (error or exit) using
@ref{2ae,,PyStatus_Exception()} and @ref{2b7,,Py_ExitStatusException()}.

If @ref{246e,,PyImport_FrozenModules()}, @ref{fe7,,PyImport_AppendInittab()} or
@ref{fe8,,PyImport_ExtendInittab()} are used, they must be set or called after
Python preinitialization and before the Python initialization. If Python is
initialized multiple times, @ref{fe7,,PyImport_AppendInittab()} or
@ref{fe8,,PyImport_ExtendInittab()} must be called before each Python
initialization.

Example setting the program name:

@example
void init_python(void)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name. Implicitly preinitialize Python. */
    status = PyConfig_SetString(&config, &config.program_name,
                                L"/path/to/my_program");
    if (PyStatus_Exception(status)) @{
        goto fail;
    @}

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto fail;
    @}
    PyConfig_Clear(&config);
    return;

fail:
    PyConfig_Clear(&config);
    Py_ExitStatusException(status);
@}
@end example

More complete example modifying the default configuration, read the
configuration, and then override some parameters:

@example
PyStatus init_python(const char *program_name)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    /* Set the program name before reading the configuration
       (decode byte string from the locale encoding).

       Implicitly preinitialize Python. */
    status = PyConfig_SetBytesString(&config, &config.program_name,
                                  program_name);
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Read all configuration at once */
    status = PyConfig_Read(&config);
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Append our custom search path to sys.path */
    status = PyWideStringList_Append(&config.module_search_paths,
                                     L"/path/to/more/modules");
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    /* Override executable computed by PyConfig_Read() */
    status = PyConfig_SetString(&config, &config.executable,
                                L"/path/to/my_executable");
    if (PyStatus_Exception(status)) @{
        goto done;
    @}

    status = Py_InitializeFromConfig(&config);

done:
    PyConfig_Clear(&config);
    return status;
@}
@end example

@node Isolated Configuration,Python Configuration,Initialization with PyConfig,Python初始化配置
@anchor{c-api/init_config init-isolated-conf}@anchor{4222}@anchor{c-api/init_config isolated-configuration}@anchor{4263}
@subsection Isolated Configuration


@ref{2ab,,PyPreConfig_InitIsolatedConfig()} and
@ref{2a4,,PyConfig_InitIsolatedConfig()} functions create a configuration to
isolate Python from the system. For example, to embed Python into an
application.

This configuration ignores global configuration variables, environment
variables, command line arguments (@ref{4233,,PyConfig.argv} is not parsed)
and user site directory. The C standard streams (ex: @code{stdout}) and the
LC_CTYPE locale are left unchanged. Signal handlers are not installed.

Configuration files are still used with this configuration. Set the
@ref{1060,,Path Configuration} ("output fields") to ignore these
configuration files and avoid the function computing the default path
configuration.

@node Python Configuration,路径配置,Isolated Configuration,Python初始化配置
@anchor{c-api/init_config init-python-config}@anchor{4221}@anchor{c-api/init_config python-configuration}@anchor{4264}
@subsection Python Configuration


@ref{2ac,,PyPreConfig_InitPythonConfig()} and @ref{2a5,,PyConfig_InitPythonConfig()}
functions create a configuration to build a customized Python which behaves as
the regular Python.

Environments variables and command line arguments are used to configure
Python, whereas global configuration variables are ignored.

This function enables C locale coercion (
@geindex Python 提高建议; PEP 538
PEP 538@footnote{https://www.python.org/dev/peps/pep-0538}) and UTF-8 Mode
(
@geindex Python 提高建议; PEP 540
PEP 540@footnote{https://www.python.org/dev/peps/pep-0540}) depending on the LC_CTYPE locale, 
@geindex PYTHONUTF8
@geindex 环境变量; PYTHONUTF8
@ref{42a,,PYTHONUTF8} and
@geindex PYTHONCOERCECLOCALE
@geindex 环境变量; PYTHONCOERCECLOCALE
@ref{426,,PYTHONCOERCECLOCALE} environment variables.

定制的 Python 的示例总是会以隔离模式运行:

@example
int main(int argc, char **argv)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    config.isolated = 1;

    /* Decode command line arguments.
       Implicitly preinitialize Python (in isolated mode). */
    status = PyConfig_SetBytesArgv(&config, argc, argv);
    if (PyStatus_Exception(status)) @{
        goto fail;
    @}

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) @{
        goto fail;
    @}
    PyConfig_Clear(&config);

    return Py_RunMain();

fail:
    PyConfig_Clear(&config);
    if (PyStatus_IsExit(status)) @{
        return status.exitcode;
    @}
    /* Display the error message and exit the process with
       non-zero exit code */
    Py_ExitStatusException(status);
@}
@end example

@node 路径配置,Py_RunMain,Python Configuration,Python初始化配置
@anchor{c-api/init_config init-path-config}@anchor{1060}@anchor{c-api/init_config path-configuration}@anchor{4265}
@subsection 路径配置


@ref{227,,PyConfig} contains multiple fields for the path configuration:


@itemize *

@item 
路径配置输入：


@itemize *

@item 
@ref{4243,,PyConfig.home}

@item 
@ref{1061,,PyConfig.platlibdir}

@item 
@ref{424f,,PyConfig.pathconfig_warnings}

@item 
@ref{4251,,PyConfig.program_name}

@item 
@ref{424a,,PyConfig.pythonpath_env}

@item 
current working directory: to get absolute paths

@item 
@code{PATH} environment variable to get the program full path
(from @ref{4251,,PyConfig.program_name})

@item 
@code{__PYVENV_LAUNCHER__} environment variable

@item 
(Windows only) Application paths in the registry under
"SoftwarePythonPythonCoreX.YPythonPath" of HKEY_CURRENT_USER and
HKEY_LOCAL_MACHINE (where X.Y is the Python version).
@end itemize

@item 
Path configuration output fields:


@itemize *

@item 
@ref{4234,,PyConfig.base_exec_prefix}

@item 
@ref{4235,,PyConfig.base_executable}

@item 
@ref{4237,,PyConfig.base_prefix}

@item 
@ref{423d,,PyConfig.exec_prefix}

@item 
@ref{4236,,PyConfig.executable}

@item 
@ref{424c,,PyConfig.module_search_paths_set},
@ref{424b,,PyConfig.module_search_paths}

@item 
@ref{4250,,PyConfig.prefix}
@end itemize
@end itemize

If at least one "output field" is not set, Python calculates the path
configuration to fill unset fields. If
@ref{424c,,module_search_paths_set} is equal to 0,
@ref{424b,,module_search_paths} is overridden and
@ref{424c,,module_search_paths_set} is set to 1.

It is possible to completely ignore the function calculating the default
path configuration by setting explicitly all path configuration output
fields listed above. A string is considered as set even if it is non-empty.
@code{module_search_paths} is considered as set if
@code{module_search_paths_set} is set to 1. In this case, path
configuration input fields are ignored as well.

Set @ref{424f,,pathconfig_warnings} to 0 to suppress warnings when
calculating the path configuration (Unix only, Windows does not log any warning).

If @ref{4237,,base_prefix} or @ref{4234,,base_exec_prefix}
fields are not set, they inherit their value from @ref{4250,,prefix}
and @ref{423d,,exec_prefix} respectively.

@ref{2bc,,Py_RunMain()} and @ref{5ba,,Py_Main()} modify @ref{262,,sys.path}:


@itemize *

@item 
If @ref{4255,,run_filename} is set and is a directory which contains a
@code{__main__.py} script, prepend @ref{4255,,run_filename} to
@ref{262,,sys.path}.

@item 
If @ref{422b,,isolated} is zero:


@itemize *

@item 
If @ref{4256,,run_module} is set, prepend the current directory
to @ref{262,,sys.path}. Do nothing if the current directory cannot be read.

@item 
If @ref{4255,,run_filename} is set, prepend the directory of the
filename to @ref{262,,sys.path}.

@item 
Otherwise, prepend an empty string to @ref{262,,sys.path}.
@end itemize
@end itemize

If @ref{4258,,site_import} is non-zero, @ref{262,,sys.path} can be
modified by the @ref{eb,,site} module. If
@ref{4247,,user_site_directory} is non-zero and the user's
site-package directory exists, the @ref{eb,,site} module appends the user's
site-package directory to @ref{262,,sys.path}.

The following configuration files are used by the path configuration:


@itemize *

@item 
@code{pyvenv.cfg}

@item 
@code{python._pth} (仅Windows)

@item 
@code{pybuilddir.txt} (仅Unix)
@end itemize

The @code{__PYVENV_LAUNCHER__} environment variable is used to set
@ref{4235,,PyConfig.base_executable}

@node Py_RunMain,Py_GetArgcArgv,路径配置,Python初始化配置
@anchor{c-api/init_config py-runmain}@anchor{4266}
@subsection Py_RunMain()


@geindex Py_RunMain (C 函数)
@anchor{c-api/init_config c Py_RunMain}@anchor{2bc}
@deffn {C 函数} int Py_RunMain (void)

Execute the command (@ref{4254,,PyConfig.run_command}), the script
(@ref{4255,,PyConfig.run_filename}) or the module
(@ref{4256,,PyConfig.run_module}) specified on the command line or in the
configuration.

By default and when if @ref{ee9,,-i} option is used, run the REPL.

Finally, finalizes Python and returns an exit status that can be passed to
the @code{exit()} function.
@end deffn

See @ref{4221,,Python Configuration} for an example of
customized Python always running in isolated mode using
@ref{2bc,,Py_RunMain()}.

@node Py_GetArgcArgv,Multi-Phase Initialization Private Provisional API,Py_RunMain,Python初始化配置
@anchor{c-api/init_config py-getargcargv}@anchor{4267}
@subsection Py_GetArgcArgv()


@geindex Py_GetArgcArgv (C 函数)
@anchor{c-api/init_config c Py_GetArgcArgv}@anchor{1081}
@deffn {C 函数} void Py_GetArgcArgv (int@w{ }*argc, wchar_t@w{ }***argv)

Get the original command line arguments, before Python modified them.
@end deffn

@node Multi-Phase Initialization Private Provisional API,,Py_GetArgcArgv,Python初始化配置
@anchor{c-api/init_config multi-phase-initialization-private-provisional-api}@anchor{4268}
@subsection Multi-Phase Initialization Private Provisional API


This section is a private provisional API introducing multi-phase
initialization, the core feature of 
@geindex Python 提高建议; PEP 432
PEP 432@footnote{https://www.python.org/dev/peps/pep-0432}:


@itemize *

@item 
"Core" initialization phase, "bare minimum Python":


@itemize *

@item 
Builtin types;

@item 
Builtin exceptions;

@item 
Builtin and frozen modules;

@item 
The @ref{fd,,sys} module is only partially initialized
(ex: @ref{262,,sys.path} doesn't exist yet).
@end itemize

@item 
"Main" initialization phase, Python is fully initialized:


@itemize *

@item 
Install and configure @ref{9a,,importlib};

@item 
Apply the @ref{1060,,Path Configuration};

@item 
Install signal handlers;

@item 
Finish @ref{fd,,sys} module initialization (ex: create @ref{428,,sys.stdout}
and @ref{262,,sys.path});

@item 
Enable optional features like @ref{7b,,faulthandler} and @ref{11d,,tracemalloc};

@item 
Import the @ref{eb,,site} module;

@item 
等等.
@end itemize
@end itemize

私有临时API：


@itemize *

@item 
@code{PyConfig._init_main}: if set to 0,
@ref{2b8,,Py_InitializeFromConfig()} stops at the "Core" initialization phase.

@item 
@code{PyConfig._isolated_interpreter}: if non-zero,
disallow threads, subprocesses and fork.
@end itemize

@geindex _Py_InitializeMain (C 函数)
@anchor{c-api/init_config c _Py_InitializeMain}@anchor{4269}
@deffn {C 函数} PyStatus _Py_InitializeMain (void)

Move to the "Main" initialization phase, finish the Python initialization.
@end deffn

No module is imported during the "Core" phase and the @code{importlib} module is
not configured: the @ref{1060,,Path Configuration} is only
applied during the "Main" phase. It may allow to customize Python in Python to
override or tune the @ref{1060,,Path Configuration}, maybe
install a custom @ref{6e7,,sys.meta_path} importer or an import hook, etc.

It may become possible to calculatin the @ref{1060,,Path Configuration} in Python, after the Core phase and before the Main phase,
which is one of the 
@geindex Python 提高建议; PEP 432
PEP 432@footnote{https://www.python.org/dev/peps/pep-0432} motivation.

The "Core" phase is not properly defined: what should be and what should
not be available at this phase is not specified yet. The API is marked
as private and provisional: the API can be modified or even be removed
anytime until a proper public API is designed.

Example running Python code between "Core" and "Main" initialization
phases:

@example
void init_python(void)
@{
    PyStatus status;

    PyConfig config;
    PyConfig_InitPythonConfig(&config);
    config._init_main = 0;

    /* ... customize 'config' configuration ... */

    status = Py_InitializeFromConfig(&config);
    PyConfig_Clear(&config);
    if (PyStatus_Exception(status)) @{
        Py_ExitStatusException(status);
    @}

    /* Use sys.stderr because sys.stdout is only created
       by _Py_InitializeMain() */
    int res = PyRun_SimpleString(
        "import sys; "
        "print('Run Python code before _Py_InitializeMain', "
               "file=sys.stderr)");
    if (res < 0) @{
        exit(1);
    @}

    /* ... put more configuration code here ... */

    status = _Py_InitializeMain();
    if (PyStatus_Exception(status)) @{
        Py_ExitStatusException(status);
    @}
@}
@end example

@node 内存管理,对象实现支持,Python初始化配置,Python/C API 参考手册
@anchor{c-api/memory doc}@anchor{426a}@anchor{c-api/memory memory}@anchor{4224}@anchor{c-api/memory memory-management}@anchor{426b}
@section 内存管理


@menu
* 概述: 概述<16>. 
* 原始内存接口:: 
* 内存接口:: 
* 对象分配器:: 
* 默认内存分配器:: 
* 自定义内存分配器:: 
* pymalloc 分配器:: 
* tracemalloc C API:: 
* 示例: 示例<51>. 

@end menu

@node 概述<16>,原始内存接口,,内存管理
@anchor{c-api/memory memoryoverview}@anchor{426c}@anchor{c-api/memory overview}@anchor{426d}
@subsection 概述


在 Python 中，内存管理涉及到一个包含所有 Python 对象和数据结构的私有堆（heap）。这个私有堆的管理由内部的 @emph{Python 内存管理器（Python memory manager）} 保证。Python 内存管理器有不同的组件来处理各种动态存储管理方面的问题，如共享、分割、预分配或缓存。

在最底层，一个原始内存分配器通过与操作系统的内存管理器交互，确保私有堆中有足够的空间来存储所有与 Python 相关的数据。在原始内存分配器的基础上，几个对象特定的分配器在同一堆上运行，并根据每种对象类型的特点实现不同的内存管理策略。例如，整数对象在堆内的管理方式不同于字符串、元组或字典，因为整数需要不同的存储需求和速度与空间的权衡。因此，Python 内存管理器将一些工作分配给对象特定分配器，但确保后者在私有堆的范围内运行。

Python 堆内存的管理是由解释器来执行，用户对它没有控制权，即使他们经常操作指向堆内内存块的对象指针，理解这一点十分重要。Python 对象和其他内部缓冲区的堆空间分配是由 Python 内存管理器按需通过本文档中列出的 Python/C API 函数进行的。

@geindex malloc()
@geindex calloc()
@geindex realloc()
@geindex free()

为了避免内存破坏，扩展的作者永远不应该试图用 C 库函数导出的函数来对 Python 对象进行操作，这些函数包括： @code{malloc()}, @code{calloc()}, @code{realloc()} 和 @code{free()}。这将导致 C 分配器和 Python 内存管理器之间的混用，引发严重后果，这是由于它们实现了不同的算法，并在不同的堆上操作。但是，我们可以安全地使用 C 库分配器为单独的目的分配和释放内存块，如下例所示：

@example
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;
@end example

在这个例子中，I/O 缓冲区的内存请求是由 C 库分配器处理的。Python 内存管理器只参与了分配作为结果返回的字节对象。

然而，在大多数情况下，建议专门从 Python 堆中分配内存，因为后者由 Python 内存管理器控制。例如，当解释器扩展了用 C 写的新对象类型时，就必须这样做。使用 Python 堆的另一个原因是希望*通知* Python 内存管理器关于扩展模块的内存需求。即使所请求的内存全部只用于内部的、高度特定的目的，将所有的内存请求交给 Python 内存管理器能让解释器对其内存占用的整体情况有更准确的了解。因此，在某些情况下，Python 内存管理器可能会触发或不触发适当的操作，如垃圾回收、内存压缩或其他预防性操作。请注意，通过使用前面例子中所示的 C 库分配器，为 I/O 缓冲区分配的内存会完全不受 Python 内存管理器管理。


@subsubheading 参见


环境变量 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 可被用来配置 Python 所使用的内存分配器。

环境变量 
@geindex PYTHONMALLOCSTATS
@geindex 环境变量; PYTHONMALLOCSTATS
@ref{12d8,,PYTHONMALLOCSTATS} 可以用来在每次创建和关闭新的 pymalloc 对象区域时打印 @ref{6c2,,pymalloc 内存分配器} 的统计数据。


@node 原始内存接口,内存接口,概述<16>,内存管理
@anchor{c-api/memory raw-memory-interface}@anchor{426e}
@subsection 原始内存接口


以下函数集封装了系统分配器。这些函数是线程安全的，不需要持有 @ref{60b,,全局解释器锁}。

@ref{14bf,,default raw memory allocator} 使用这些函数：@code{malloc()}、 @code{calloc()}、 @code{realloc()} 和 @code{free()}；申请零字节时则调用 @code{malloc(1)} （或 @code{calloc(1, 1)}）


3.4 新版功能.


@geindex PyMem_RawMalloc (C 函数)
@anchor{c-api/memory c PyMem_RawMalloc}@anchor{a57}
@deffn {C 函数} void* PyMem_RawMalloc (size_t@w{ }n)

分配 @emph{n} 个字节并返回一个指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyMem_RawMalloc(1)} 一样。但是内存不会以任何方式被初始化。
@end deffn

@geindex PyMem_RawCalloc (C 函数)
@anchor{c-api/memory c PyMem_RawCalloc}@anchor{89d}
@deffn {C 函数} void* PyMem_RawCalloc (size_t@w{ }nelem, size_t@w{ }elsize)

分配 @emph{nelem} 个元素，每个元素的大小为 @emph{elsize} 字节，并返回指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。 内存会被初始化为零。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyMem_RawCalloc(1, 1)} 一样。


3.5 新版功能.

@end deffn

@geindex PyMem_RawRealloc (C 函数)
@anchor{c-api/memory c PyMem_RawRealloc}@anchor{a58}
@deffn {C 函数} void* PyMem_RawRealloc (void@w{ }*p, size_t@w{ }n)

将 @emph{p} 指向的内存块大小调整为 @emph{n} 字节。以新旧内存块大小中的最小值为准，其中内容保持不变，

如果 @emph{p} 是 @code{NULL} ，则相当于调用 @code{PyMem_RawMalloc(n)} ；如果 @emph{n} 等于 0，则内存块大小会被调整，但不会被释放，返回非 @code{NULL} 指针。

除非 @emph{p} 是 @code{NULL} ，否则它必须是之前调用 @ref{a57,,PyMem_RawMalloc()} 、 @ref{a58,,PyMem_RawRealloc()} 或 @ref{89d,,PyMem_RawCalloc()} 所返回的。

如果请求失败，@ref{a58,,PyMem_RawRealloc()} 返回 @code{NULL} ， @emph{p} 仍然是指向先前内存区域的有效指针。
@end deffn

@geindex PyMem_RawFree (C 函数)
@anchor{c-api/memory c PyMem_RawFree}@anchor{3e94}
@deffn {C 函数} void PyMem_RawFree (void@w{ }*p)

释放 @emph{p} 指向的内存块。 @emph{p} 必须是之前调用 @ref{a57,,PyMem_RawMalloc()} 、 @ref{a58,,PyMem_RawRealloc()} 或 @ref{89d,,PyMem_RawCalloc()} 所返回的指针。否则，或在 @code{PyMem_RawFree(p)} 之前已经调用过的情况下，未定义的行为会发生。

如果 @emph{p} 是 @code{NULL}, 那么什么操作也不会进行。
@end deffn

@node 内存接口,对象分配器,原始内存接口,内存管理
@anchor{c-api/memory memory-interface}@anchor{426f}@anchor{c-api/memory memoryinterface}@anchor{4270}
@subsection 内存接口


以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从Python堆分配和释放内存。

@ref{14bf,,默认内存分配器} 使用了 @ref{6c2,,pymalloc 内存分配器}.

@cartouche
@quotation 警告 
在使用这些函数时，必须持有 @ref{60b,,全局解释器锁（GIL）} 。
@end quotation
@end cartouche


在 3.6 版更改: 现在默认的分配器是 pymalloc 而非系统的 @code{malloc()} 。


@geindex PyMem_Malloc (C 函数)
@anchor{c-api/memory c PyMem_Malloc}@anchor{607}
@deffn {C 函数} void* PyMem_Malloc (size_t@w{ }n)

分配 @emph{n} 个字节并返回一个指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyMem_Malloc(1)} 一样。但是内存不会以任何方式被初始化。
@end deffn

@geindex PyMem_Calloc (C 函数)
@anchor{c-api/memory c PyMem_Calloc}@anchor{89e}
@deffn {C 函数} void* PyMem_Calloc (size_t@w{ }nelem, size_t@w{ }elsize)

分配 @emph{nelem} 个元素，每个元素的大小为 @emph{elsize} 字节，并返回指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。 内存会被初始化为零。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyMem_Calloc(1, 1)} 一样。


3.5 新版功能.

@end deffn

@geindex PyMem_Realloc (C 函数)
@anchor{c-api/memory c PyMem_Realloc}@anchor{a59}
@deffn {C 函数} void* PyMem_Realloc (void@w{ }*p, size_t@w{ }n)

将 @emph{p} 指向的内存块大小调整为 @emph{n} 字节。以新旧内存块大小中的最小值为准，其中内容保持不变，

如果 @emph{p} 是 @code{NULL} ，则相当于调用 @code{PyMem_Malloc(n)} ；如果 @emph{n} 等于 0，则内存块大小会被调整，但不会被释放，返回非 @code{NULL} 指针。

除非 @emph{p} 是 @code{NULL} ，否则它必须是之前调用 @ref{607,,PyMem_Malloc()} 、 @ref{a59,,PyMem_Realloc()} 或 @ref{89e,,PyMem_Calloc()} 所返回的。

如果请求失败，@ref{a59,,PyMem_Realloc()} 返回 @code{NULL} ， @emph{p} 仍然是指向先前内存区域的有效指针。
@end deffn

@geindex PyMem_Free (C 函数)
@anchor{c-api/memory c PyMem_Free}@anchor{e76}
@deffn {C 函数} void PyMem_Free (void@w{ }*p)

释放 @emph{p} 指向的内存块。 @emph{p} 必须是之前调用 @ref{607,,PyMem_Malloc()} 、 @ref{a59,,PyMem_Realloc()} 或 @ref{89e,,PyMem_Calloc()} 所返回的指针。否则，或在 @code{PyMem_Free(p)} 之前已经调用过的情况下，未定义的行为会发生。

如果 @emph{p} 是 @code{NULL}, 那么什么操作也不会进行。
@end deffn

以下面向类型的宏为方便而提供。 注意 @emph{TYPE} 可以指任何 C 类型。

@geindex PyMem_New (C 函数)
@anchor{c-api/memory c PyMem_New}@anchor{4271}
@deffn {C 函数} TYPE* PyMem_New (TYPE, size_t@w{ }n)

与 @ref{607,,PyMem_Malloc()} 相同，但会分配 @code{(n * sizeof(TYPE))} 字节的内存。 返回一个转换为 @code{TYPE*} 的指针。 内存将不会以任何方式被初始化。
@end deffn

@geindex PyMem_Resize (C 函数)
@anchor{c-api/memory c PyMem_Resize}@anchor{4272}
@deffn {C 函数} TYPE* PyMem_Resize (void@w{ }*p, TYPE, size_t@w{ }n)

与 @ref{a59,,PyMem_Realloc()} 相同，但内存块的大小被调整为 @code{(n * sizeof(TYPE))} 字节。 返回一个转换为 @code{TYPE*} 类型的指针。 返回时，@emph{p} 将为指向新内存区域的指针，如果失败则返回 @code{NULL}。

这是一个 C 预处理宏， @emph{p} 总是被重新赋值。请保存 @emph{p} 的原始值，以避免在处理错误时丢失内存。
@end deffn

@geindex PyMem_Del (C 函数)
@anchor{c-api/memory c PyMem_Del}@anchor{4273}
@deffn {C 函数} void PyMem_Del (void@w{ }*p)

与 @ref{e76,,PyMem_Free()} 相同
@end deffn

此外，我们还提供了以下宏集用于直接调用 Python 内存分配器，而不涉及上面列出的 C API 函数。但是请注意，使用它们并不能保证跨 Python 版本的二进制兼容性，因此在扩展模块被弃用。


@itemize *

@item 
@code{PyMem_MALLOC(size)}

@item 
@code{PyMem_NEW(type, size)}

@item 
@code{PyMem_REALLOC(ptr, size)}

@item 
@code{PyMem_RESIZE(ptr, type, size)}

@item 
@code{PyMem_FREE(ptr)}

@item 
@code{PyMem_DEL(ptr)}
@end itemize

@node 对象分配器,默认内存分配器,内存接口,内存管理
@anchor{c-api/memory object-allocators}@anchor{4274}
@subsection 对象分配器


以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从Python堆分配和释放内存。

@ref{14bf,,默认对象分配器} 使用 @ref{6c2,,pymalloc 内存分配器}.

@cartouche
@quotation 警告 
在使用这些函数时，必须持有 @ref{60b,,全局解释器锁（GIL）} 。
@end quotation
@end cartouche

@geindex PyObject_Malloc (C 函数)
@anchor{c-api/memory c PyObject_Malloc}@anchor{609}
@deffn {C 函数} void* PyObject_Malloc (size_t@w{ }n)

分配 @emph{n} 个字节并返回一个指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyObject_Malloc(1)} 一样。但是内存不会以任何方式被初始化。
@end deffn

@geindex PyObject_Calloc (C 函数)
@anchor{c-api/memory c PyObject_Calloc}@anchor{89f}
@deffn {C 函数} void* PyObject_Calloc (size_t@w{ }nelem, size_t@w{ }elsize)

分配 @emph{nelem} 个元素，每个元素的大小为 @emph{elsize} 字节，并返回指向分配的内存的 @code{void*} 类型指针，如果请求失败则返回 @code{NULL}。 内存会被初始化为零。

请求零字节可能返回一个独特的非 @code{NULL} 指针，就像调用了 @code{PyObject_Calloc(1, 1)} 一样。


3.5 新版功能.

@end deffn

@geindex PyObject_Realloc (C 函数)
@anchor{c-api/memory c PyObject_Realloc}@anchor{e77}
@deffn {C 函数} void* PyObject_Realloc (void@w{ }*p, size_t@w{ }n)

将 @emph{p} 指向的内存块大小调整为 @emph{n} 字节。以新旧内存块大小中的最小值为准，其中内容保持不变，

如果*p*是`@w{`}NULL`@w{`}，则相当于调用 @code{PyObject_Malloc(n)} ；如果 @emph{n} 等于 0，则内存块大小会被调整，但不会被释放，返回非 @code{NULL} 指针。

除非 @emph{p} 是 @code{NULL} ，否则它必须是之前调用 @ref{609,,PyObject_Malloc()} 、 @ref{e77,,PyObject_Realloc()} 或 @ref{89f,,PyObject_Calloc()} 所返回的。

如果请求失败，@ref{e77,,PyObject_Realloc()} 返回 @code{NULL} ， @emph{p} 仍然是指向先前内存区域的有效指针。
@end deffn

@geindex PyObject_Free (C 函数)
@anchor{c-api/memory c PyObject_Free}@anchor{606}
@deffn {C 函数} void PyObject_Free (void@w{ }*p)

释放 @emph{p} 指向的内存块。 @emph{p} 必须是之前调用 @ref{609,,PyObject_Malloc()} 、 @ref{e77,,PyObject_Realloc()} 或 @ref{89f,,PyObject_Calloc()} 所返回的指针。否则，或在 @code{PyObject_Free(p)} 之前已经调用过的情况下，未定义行为会发生。

如果 @emph{p} 是 @code{NULL}, 那么什么操作也不会进行。
@end deffn

@node 默认内存分配器,自定义内存分配器,对象分配器,内存管理
@anchor{c-api/memory default-memory-allocators}@anchor{14bf}@anchor{c-api/memory id1}@anchor{4275}
@subsection 默认内存分配器


默认内存分配器：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxx} 
@headitem

配置

@tab

名称

@tab

PyMem_RawMalloc

@tab

PyMem_Malloc

@tab

PyObject_Malloc

@item

发布版本

@tab

@code{"pymalloc"}

@tab

@code{malloc}

@tab

@code{pymalloc}

@tab

@code{pymalloc}

@item

调试构建

@tab

@code{"pymalloc_debug"}

@tab

@code{malloc} + debug

@tab

@code{pymalloc} + debug

@tab

@code{pymalloc} + debug

@item

没有 pymalloc 的发布版本

@tab

@code{"malloc"}

@tab

@code{malloc}

@tab

@code{malloc}

@tab

@code{malloc}

@item

没有 pymalloc 的调试构建

@tab

@code{"malloc_debug"}

@tab

@code{malloc} + debug

@tab

@code{malloc} + debug

@tab

@code{malloc} + debug

@end multitable


说明：


@itemize *

@item 
名称: 环境变量 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 的值

@item 
@code{malloc}: 来自 C 标准库的系统分配, C 函数 @code{malloc()}, @code{calloc()}, @code{realloc()} and @code{free()}

@item 
@code{pymalloc}: @ref{6c2,,pymalloc 内存分配器}

@item 
"+ debug": 带有 @ref{60c,,PyMem_SetupDebugHooks()} 安装的调试钩子
@end itemize

@node 自定义内存分配器,pymalloc 分配器,默认内存分配器,内存管理
@anchor{c-api/memory customize-memory-allocators}@anchor{4276}
@subsection 自定义内存分配器



3.4 新版功能.


@geindex PyMemAllocatorEx (C 类型)
@anchor{c-api/memory c PyMemAllocatorEx}@anchor{8c1}
@deffn {C 类型} PyMemAllocatorEx

用于描述内存块分配器的结构体。 该结构体下列字段:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

含义

@item

@code{void *ctx}

@tab

作为第一个参数传入的用户上下文

@item

@code{void* malloc(void *ctx, size_t size)}

@tab

分配一个内存块

@item

@code{void* calloc(void *ctx, size_t nelem, size_t elsize)}

@tab

分配一个初始化为 0 的内存块

@item

@code{void* realloc(void *ctx, void *ptr, size_t new_size)}

@tab

分配一个内存块或调整其大小

@item

@code{void free(void *ctx, void *ptr)}

@tab

释放一个内存块

@end multitable



在 3.5 版更改: The @code{PyMemAllocator} structure was renamed to
@ref{8c1,,PyMemAllocatorEx} and a new @code{calloc} field was added.

@end deffn

@geindex PyMemAllocatorDomain (C 类型)
@anchor{c-api/memory c PyMemAllocatorDomain}@anchor{4277}
@deffn {C 类型} PyMemAllocatorDomain

用来识别分配器域的枚举类。域有：

@geindex PYMEM_DOMAIN_RAW (C 宏)
@anchor{c-api/memory c PYMEM_DOMAIN_RAW}@anchor{14c0}
@deffn {C 宏} PYMEM_DOMAIN_RAW

函数


@itemize *

@item 
@ref{a57,,PyMem_RawMalloc()}

@item 
@ref{a58,,PyMem_RawRealloc()}

@item 
@ref{89d,,PyMem_RawCalloc()}

@item 
@ref{3e94,,PyMem_RawFree()}
@end itemize
@end deffn

@geindex PYMEM_DOMAIN_MEM (C 宏)
@anchor{c-api/memory c PYMEM_DOMAIN_MEM}@anchor{60a}
@deffn {C 宏} PYMEM_DOMAIN_MEM

函数


@itemize *

@item 
@ref{607,,PyMem_Malloc()},

@item 
@ref{a59,,PyMem_Realloc()}

@item 
@ref{89e,,PyMem_Calloc()}

@item 
@ref{e76,,PyMem_Free()}
@end itemize
@end deffn

@geindex PYMEM_DOMAIN_OBJ (C 宏)
@anchor{c-api/memory c PYMEM_DOMAIN_OBJ}@anchor{608}
@deffn {C 宏} PYMEM_DOMAIN_OBJ

函数


@itemize *

@item 
@ref{609,,PyObject_Malloc()}

@item 
@ref{e77,,PyObject_Realloc()}

@item 
@ref{89f,,PyObject_Calloc()}

@item 
@ref{606,,PyObject_Free()}
@end itemize
@end deffn
@end deffn

@geindex PyMem_GetAllocator (C 函数)
@anchor{c-api/memory c PyMem_GetAllocator}@anchor{41c5}
@deffn {C 函数} void PyMem_GetAllocator (PyMemAllocatorDomain@w{ }domain, PyMemAllocatorEx@w{ }*allocator)

获取指定域的内存块分配器。
@end deffn

@geindex PyMem_SetAllocator (C 函数)
@anchor{c-api/memory c PyMem_SetAllocator}@anchor{41c3}
@deffn {C 函数} void PyMem_SetAllocator (PyMemAllocatorDomain@w{ }domain, PyMemAllocatorEx@w{ }*allocator)

设置指定域的内存块分配器。

当请求零字节时，新的分配器必须返回一个独特的非 @code{NULL} 指针。

对于 @ref{14c0,,PYMEM_DOMAIN_RAW} 域，分配器必须是线程安全的：当分配器被调用时，不持有 @ref{60b,,全局解释器锁} 。

如果新的分配器不是钩子（不调用之前的分配器），必须调用 @ref{60c,,PyMem_SetupDebugHooks()} 函数在新分配器上重新安装调试钩子。
@end deffn

@geindex PyMem_SetupDebugHooks (C 函数)
@anchor{c-api/memory c PyMem_SetupDebugHooks}@anchor{60c}
@deffn {C 函数} void PyMem_SetupDebugHooks (void)

设置检测 Python 内存分配器函数中错误的钩子。

新分配的内存由字节 @code{0xCD} ( @code{CLEANBYTE} ) 填充，释放的内存由字节 @code{0xDD} ( @code{DEADBYTE} )填充。内存块被 "禁止字节" 包围（ @code{FORBIDDENBYTE} ：字节 @code{0xFD} ）。

运行时检查：


@itemize -

@item 
检测对 API 的违反，例如：对用 @ref{607,,PyMem_Malloc()} 分配的缓冲区调用 @ref{606,,PyObject_Free()} 。

@item 
检测缓冲区起始位置前的写入（缓冲区下溢）。

@item 
检测缓冲区终止位置后的写入（缓冲区溢出）。

@item 
检测当调用 @ref{608,,PYMEM_DOMAIN_OBJ} (如: @ref{609,,PyObject_Malloc()}) 和 @ref{60a,,PYMEM_DOMAIN_MEM} (如: @ref{607,,PyMem_Malloc()}) 域的分配器函数时 @ref{60b,,GIL} 已被保持。
@end itemize

在出错时，调试钩子使用 @ref{11d,,tracemalloc} 模块来回溯内存块被分配的位置。只有当 @ref{11d,,tracemalloc} 正在追踪 Python 内存分配，并且内存块被追踪时，才会显示回溯。

如果 Python 是在调试模式下编译的，这些钩子是 @ref{14bf,,installed by default} 。环境变量 
@geindex PYTHONMALLOC
@geindex 环境变量; PYTHONMALLOC
@ref{605,,PYTHONMALLOC} 可以用来在发布模式编译的 Python 上安装调试钩子。


在 3.6 版更改: 这个函数现在也适用于以 发布模式编译的 Python。在出错时，调试钩子现在使用 @ref{11d,,tracemalloc} 来回溯内存块被分配的位置。调试钩子现在也检查当 @ref{608,,PYMEM_DOMAIN_OBJ} 和 @ref{60a,,PYMEM_DOMAIN_MEM} 域的函数被调用时，全局解释器锁是否被持有。



在 3.8 版更改: 字节模式 @code{0xCB} (@code{CLEANBYTE})、 @code{0xDB} (@code{DEADBYTE}) 和 @code{0xFB} (@code{FORBIDDENBYTE}) 已被 @code{0xCD} 、 @code{0xDD} 和 @code{0xFD} 替代以使用与 Windows CRT 调试 @code{malloc()} 和 @code{free()} 相同的值。

@end deffn

@node pymalloc 分配器,tracemalloc C API,自定义内存分配器,内存管理
@anchor{c-api/memory pymalloc}@anchor{6c2}@anchor{c-api/memory the-pymalloc-allocator}@anchor{4278}
@subsection pymalloc 分配器


Python 有为具有短生命周期的小对象（小于或等于 512 字节）优化的 @emph{pymalloc} 分配器。它使用固定大小为 256 KiB 的称为 "arenas" 的内存映射。对于大于512字节的分配，它回到使用 @ref{a57,,PyMem_RawMalloc()} 和 @ref{a58,,PyMem_RawRealloc()} 。

@emph{pymalloc} 是 @ref{60a,,PYMEM_DOMAIN_MEM} (例如: @ref{607,,PyMem_Malloc()}) 和 @ref{608,,PYMEM_DOMAIN_OBJ} (例如: @ref{609,,PyObject_Malloc()}) 域的 @ref{14bf,,默认分配器} 。

arena 分配器使用以下函数：


@itemize *

@item 
Windows 上的 @code{VirtualAlloc()} 和 @code{VirtualFree()} ,

@item 
@code{mmap()} 和 @code{munmap()} ，如果可用，

@item 
否则， @code{malloc()} 和 @code{free()} 。
@end itemize

@menu
* 自定义 pymalloc Arena 分配器:: 

@end menu

@node 自定义 pymalloc Arena 分配器,,,pymalloc 分配器
@anchor{c-api/memory customize-pymalloc-arena-allocator}@anchor{4279}
@subsubsection 自定义 pymalloc Arena 分配器



3.4 新版功能.


@geindex PyObjectArenaAllocator (C 类型)
@anchor{c-api/memory c PyObjectArenaAllocator}@anchor{427a}
@deffn {C 类型} PyObjectArenaAllocator

用来描述一个 arena 分配器的结构体。这个结构体有三个字段：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

含义

@item

@code{void *ctx}

@tab

作为第一个参数传入的用户上下文

@item

@code{void* alloc(void *ctx, size_t size)}

@tab

分配一块 size 字节的区域

@item

@code{void free(void *ctx, void *ptr, size_t size)}

@tab

释放一块区域

@end multitable

@end deffn

@geindex PyObject_GetArenaAllocator (C 函数)
@anchor{c-api/memory c PyObject_GetArenaAllocator}@anchor{41c6}
@deffn {C 函数} void PyObject_GetArenaAllocator (PyObjectArenaAllocator@w{ }*allocator)

获取 arena 分配器
@end deffn

@geindex PyObject_SetArenaAllocator (C 函数)
@anchor{c-api/memory c PyObject_SetArenaAllocator}@anchor{41c4}
@deffn {C 函数} void PyObject_SetArenaAllocator (PyObjectArenaAllocator@w{ }*allocator)

设置 arena 分配器
@end deffn

@node tracemalloc C API,示例<51>,pymalloc 分配器,内存管理
@anchor{c-api/memory tracemalloc-c-api}@anchor{427b}
@subsection tracemalloc C API



3.7 新版功能.


@geindex PyTraceMalloc_Track (C 函数)
@anchor{c-api/memory c PyTraceMalloc_Track}@anchor{530}
@deffn {C 函数} int PyTraceMalloc_Track (unsigned int@w{ }domain, uintptr_t@w{ }ptr, size_t@w{ }size)

在 @ref{11d,,tracemalloc} 模块中跟踪一个已分配的内存块。

成功时返回 @code{0}，出错时返回 @code{-1} (无法分配内存来保存跟踪信息)。 如果禁用了 tracemalloc 则返回 @code{-2}。

如果内存块已被跟踪，则更新现有跟踪信息。
@end deffn

@geindex PyTraceMalloc_Untrack (C 函数)
@anchor{c-api/memory c PyTraceMalloc_Untrack}@anchor{531}
@deffn {C 函数} int PyTraceMalloc_Untrack (unsigned int@w{ }domain, uintptr_t@w{ }ptr)

在 @ref{11d,,tracemalloc} 模块中取消跟踪一个已分配的内存块。 如果内存块未被跟踪则不执行任何操作。

如果 tracemalloc 被禁用则返回 @code{-2}，否则返回 @code{0}。
@end deffn

@node 示例<51>,,tracemalloc C API,内存管理
@anchor{c-api/memory examples}@anchor{427c}@anchor{c-api/memory memoryexamples}@anchor{427d}
@subsection 示例


以下是来自 @ref{426c,,概述} 小节的示例，经过重写以使 I/O 缓冲区是通过使用第一个函数集从 Python 堆中分配的:

@example
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
@end example

使用面向类型函数集的相同代码:

@example
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
@end example

请注意在以上两个示例中，缓冲区总是通过归属于相同集的函数来操纵的。 事实上，对于一个给定的内存块必须使用相同的内存 API 族，以便使得混合不同分配器的风险减至最低。 以下代码序列包含两处错误，其中一个被标记为 @emph{fatal} 因为它混合了两种在不同堆上操作的不同分配器。

@example
char *buf1 = PyMem_New(char, BUFSIZ);
char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
free(buf2);       /* Right -- allocated via malloc() */
free(buf1);       /* Fatal -- should be PyMem_Del()  */
@end example

除了旨在处理来自 Python 堆的原始内存块的函数之外， Python 中的对象是通过 @ref{269,,PyObject_New()}, @ref{26a,,PyObject_NewVar()} 和 @ref{ee0,,PyObject_Del()} 来分配和释放的。

这些将在有关如何在 C 中定义和实现新对象类型的下一章中讲解。

@node 对象实现支持,API 和 ABI 版本管理,内存管理,Python/C API 参考手册
@anchor{c-api/objimpl doc}@anchor{427e}@anchor{c-api/objimpl newtypes}@anchor{427f}@anchor{c-api/objimpl object-implementation-support}@anchor{4280}
@section 对象实现支持


本章描述了定义新对象类型时所使用的函数、类型和宏。

@menu
* 在堆中分配对象:: 
* 公用对象的结构:: 
* Type 对象: Type 对象<2>. 
* Number Object Structures:: 
* Mapping Object Structures:: 
* Sequence Object Structures:: 
* Buffer Object Structures:: 
* Async Object Structures:: 
* Slot Type typedefs:: 
* 例子: 例子<2>. 
* 使对象类型支持循环垃圾回收:: 

@end menu

@node 在堆中分配对象,公用对象的结构,,对象实现支持
@anchor{c-api/allocation doc}@anchor{4281}@anchor{c-api/allocation allocating-objects}@anchor{4282}@anchor{c-api/allocation allocating-objects-on-the-heap}@anchor{4283}
@subsection 在堆中分配对象


@geindex _PyObject_New (C 函数)
@anchor{c-api/allocation c _PyObject_New}@anchor{4284}
@deffn {C 函数} PyObject* _PyObject_New (PyTypeObject@w{ }*type)
@emph{Return value: New reference.}
@end deffn

@geindex _PyObject_NewVar (C 函数)
@anchor{c-api/allocation c _PyObject_NewVar}@anchor{4285}
@deffn {C 函数} PyVarObject* _PyObject_NewVar (PyTypeObject@w{ }*type, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
@end deffn

@geindex PyObject_Init (C 函数)
@anchor{c-api/allocation c PyObject_Init}@anchor{3a0}
@deffn {C 函数} PyObject* PyObject_Init (PyObject@w{ }*op, PyTypeObject@w{ }*type)
@emph{Return value: Borrowed reference.}
为新分配的对象 @emph{op} 初始化它的类型和引用。返回初始化后的对象。如果 @emph{type} 声明这个对象参与循环垃圾检测，那么这个对象会被添加进垃圾检测的对象集中。这个对象的其他字段不会被影响。
@end deffn

@geindex PyObject_InitVar (C 函数)
@anchor{c-api/allocation c PyObject_InitVar}@anchor{10df}
@deffn {C 函数} PyVarObject* PyObject_InitVar (PyVarObject@w{ }*op, PyTypeObject@w{ }*type, Py_ssize_t@w{ }size)
@emph{Return value: Borrowed reference.}
它的功能和 @ref{3a0,,PyObject_Init()} 一样，并且初始化变量大小的对象的长度。
@end deffn

@geindex PyObject_New (C 函数)
@anchor{c-api/allocation c PyObject_New}@anchor{269}
@deffn {C 函数} TYPE* PyObject_New (TYPE, PyTypeObject@w{ }*type)
@emph{Return value: New reference.}
使用 C 结构类型 @emph{TYPE} 和 Python 类型对象 @emph{type} 分配一个新的 Python 对象。 未在该 Python 对象头中定义的字段不会被初始化；对象的引用计数将为一。 内存分配大小由 type 对象的 @ref{26b,,tp_basicsize} 字段来确定。
@end deffn

@geindex PyObject_NewVar (C 函数)
@anchor{c-api/allocation c PyObject_NewVar}@anchor{26a}
@deffn {C 函数} TYPE* PyObject_NewVar (TYPE, PyTypeObject@w{ }*type, Py_ssize_t@w{ }size)
@emph{Return value: New reference.}
使用C的数据结构类型 @emph{TYPE} 和Python的类型对象 @emph{type} 分配一个新的Python对象。Python对象头文件中没有定义的字段不会被初始化。被分配的内存空间预留了 @emph{TYPE} 结构加 @emph{type} 对象中 @ref{3d8d,,tp_itemsize} 字段提供的 @emph{size} 字段的值。这对于实现类似元组这种能够在构造期决定自己大小的对象是很实用的。将字段的数组嵌入到相同的内存分配中可以减少内存分配的次数，这提高了内存分配的效率。
@end deffn

@geindex PyObject_Del (C 函数)
@anchor{c-api/allocation c PyObject_Del}@anchor{ee0}
@deffn {C 函数} void PyObject_Del (void@w{ }*op)

释放由 @ref{269,,PyObject_New()} 或者 @ref{26a,,PyObject_NewVar()} 分配内存的对象。这通常由对象的type字段定义的 @ref{3d93,,tp_dealloc} 处理函数来调用。调用这个函数以后op对象中的字段都不可以被访问，因为原分配的内存空间已不再是一个有效的Python对象。
@end deffn

@geindex _Py_NoneStruct (C 变量)
@anchor{c-api/allocation c _Py_NoneStruct}@anchor{4286}
@deffn {C 变量} PyObject _Py_NoneStruct

像 @code{None} 一样的Python对象。这个对象仅可以使用 @ref{3d5d,,Py_None} 宏访问，这个宏取得指向这个对象的指针。
@end deffn


@subsubheading 参见



@table @asis

@item @ref{3d60,,PyModule_Create()}

分配内存和创建扩展模块。
@end table


@node 公用对象的结构,Type 对象<2>,在堆中分配对象,对象实现支持
@anchor{c-api/structures doc}@anchor{4287}@anchor{c-api/structures common-object-structures}@anchor{4288}@anchor{c-api/structures common-structs}@anchor{4289}
@subsection 公用对象的结构


大量的结构体被用于定义Python的对象类型。这一节描述了这些的结构体和它们的使用方法。

@menu
* 基本的对象类型和宏:: 
* Implementing functions and methods:: 
* Accessing attributes of extension types:: 

@end menu

@node 基本的对象类型和宏,Implementing functions and methods,,公用对象的结构
@anchor{c-api/structures base-object-types-and-macros}@anchor{428a}
@subsubsection 基本的对象类型和宏


所有的 Python 对象都在对象的内存表示的开始部分共享少量的字段。 这些字段用 @ref{5bd,,PyObject} 或 @ref{428b,,PyVarObject} 类型来表示，这些类型又由一些宏定义，这些宏也直接或间接地用于所有其他 Python 对象的定义。

@geindex PyObject (C 类型)
@anchor{c-api/structures c PyObject}@anchor{5bd}
@deffn {C 类型} PyObject

All object types are extensions of this type.  This is a type which
contains the information Python needs to treat a pointer to an object as an
object.  In a normal "release" build, it contains only the object's
reference count and a pointer to the corresponding type object.
Nothing is actually declared to be a @ref{5bd,,PyObject}, but every pointer
to a Python object can be cast to a @ref{5bd,,PyObject*}.  Access to the
members must be done by using the macros @ref{3d8c,,Py_REFCNT} and
@ref{3d8b,,Py_TYPE}.
@end deffn

@geindex PyVarObject (C 类型)
@anchor{c-api/structures c PyVarObject}@anchor{428b}
@deffn {C 类型} PyVarObject

This is an extension of @ref{5bd,,PyObject} that adds the @code{ob_size}
field.  This is only used for objects that have some notion of @emph{length}.
This type does not often appear in the Python/C API.
Access to the members must be done by using the macros
@ref{3d8c,,Py_REFCNT}, @ref{3d8b,,Py_TYPE}, and @ref{428c,,Py_SIZE}.
@end deffn

@geindex PyObject_HEAD (C 宏)
@anchor{c-api/structures c PyObject_HEAD}@anchor{d42}
@deffn {C 宏} PyObject_HEAD

This is a macro used when declaring new types which represent objects
without a varying length.  The PyObject_HEAD macro expands to:

@example
PyObject ob_base;
@end example

See documentation of @ref{5bd,,PyObject} above.
@end deffn

@geindex PyObject_VAR_HEAD (C 宏)
@anchor{c-api/structures c PyObject_VAR_HEAD}@anchor{428d}
@deffn {C 宏} PyObject_VAR_HEAD

This is a macro used when declaring new types which represent objects
with a length that varies from instance to instance.
The PyObject_VAR_HEAD macro expands to:

@example
PyVarObject ob_base;
@end example

参见上面 @ref{428b,,PyVarObject} 的文档。
@end deffn

@geindex Py_TYPE (C 宏)
@anchor{c-api/structures c Py_TYPE}@anchor{3d8b}
@deffn {C 宏} Py_TYPE (o)

This macro is used to access the @code{ob_type} member of a Python object.
It expands to:

@example
(((PyObject*)(o))->ob_type)
@end example
@end deffn

@geindex Py_IS_TYPE (C 函数)
@anchor{c-api/structures c Py_IS_TYPE}@anchor{10c7}
@deffn {C 函数} int Py_IS_TYPE (PyObject@w{ }*o, PyTypeObject@w{ }*type)

Return non-zero if the object @emph{o} type is @emph{type}. Return zero otherwise.
Equivalent to: @code{Py_TYPE(o) == type}.


3.9 新版功能.

@end deffn

@geindex Py_SET_TYPE (C 函数)
@anchor{c-api/structures c Py_SET_TYPE}@anchor{10db}
@deffn {C 函数} void Py_SET_TYPE (PyObject@w{ }*o, PyTypeObject@w{ }*type)

Set the object @emph{o} type to @emph{type}.


3.9 新版功能.

@end deffn

@geindex Py_REFCNT (C 宏)
@anchor{c-api/structures c Py_REFCNT}@anchor{3d8c}
@deffn {C 宏} Py_REFCNT (o)

This macro is used to access the @code{ob_refcnt} member of a Python
object.
It expands to:

@example
(((PyObject*)(o))->ob_refcnt)
@end example
@end deffn

@geindex Py_SET_REFCNT (C 函数)
@anchor{c-api/structures c Py_SET_REFCNT}@anchor{10dc}
@deffn {C 函数} void Py_SET_REFCNT (PyObject@w{ }*o, Py_ssize_t@w{ }refcnt)

Set the object @emph{o} reference counter to @emph{refcnt}.


3.9 新版功能.

@end deffn

@geindex Py_SIZE (C 宏)
@anchor{c-api/structures c Py_SIZE}@anchor{428c}
@deffn {C 宏} Py_SIZE (o)

This macro is used to access the @code{ob_size} member of a Python object.
It expands to:

@example
(((PyVarObject*)(o))->ob_size)
@end example
@end deffn

@geindex Py_SET_SIZE (C 函数)
@anchor{c-api/structures c Py_SET_SIZE}@anchor{10d9}
@deffn {C 函数} void Py_SET_SIZE (PyVarObject@w{ }*o, Py_ssize_t@w{ }size)

Set the object @emph{o} size to @emph{size}.


3.9 新版功能.

@end deffn

@geindex PyObject_HEAD_INIT (C 宏)
@anchor{c-api/structures c PyObject_HEAD_INIT}@anchor{428e}
@deffn {C 宏} PyObject_HEAD_INIT (type)

This is a macro which expands to initialization values for a new
@ref{5bd,,PyObject} type.  This macro expands to:

@example
_PyObject_EXTRA_INIT
1, type,
@end example
@end deffn

@geindex PyVarObject_HEAD_INIT (C 宏)
@anchor{c-api/structures c PyVarObject_HEAD_INIT}@anchor{428f}
@deffn {C 宏} PyVarObject_HEAD_INIT (type, size)

This is a macro which expands to initialization values for a new
@ref{428b,,PyVarObject} type, including the @code{ob_size} field.
This macro expands to:

@example
_PyObject_EXTRA_INIT
1, type, size,
@end example
@end deffn

@node Implementing functions and methods,Accessing attributes of extension types,基本的对象类型和宏,公用对象的结构
@anchor{c-api/structures implementing-functions-and-methods}@anchor{4290}
@subsubsection Implementing functions and methods


@geindex PyCFunction (C 类型)
@anchor{c-api/structures c PyCFunction}@anchor{ea7}
@deffn {C 类型} PyCFunction

Type of the functions used to implement most Python callables in C.
Functions of this type take two @ref{5bd,,PyObject*} parameters and return
one such value.  If the return value is @code{NULL}, an exception shall have
been set.  If not @code{NULL}, the return value is interpreted as the return
value of the function as exposed in Python.  The function must return a new
reference.

The function signature is:

@example
PyObject *PyCFunction(PyObject *self,
                      PyObject *args);
@end example
@end deffn

@geindex PyCFunctionWithKeywords (C 类型)
@anchor{c-api/structures c PyCFunctionWithKeywords}@anchor{4291}
@deffn {C 类型} PyCFunctionWithKeywords

Type of the functions used to implement Python callables in C
with signature @code{METH_VARARGS | METH_KEYWORDS}.
The function signature is:

@example
PyObject *PyCFunctionWithKeywords(PyObject *self,
                                  PyObject *args,
                                  PyObject *kwargs);
@end example
@end deffn

@geindex _PyCFunctionFast (C 类型)
@anchor{c-api/structures c _PyCFunctionFast}@anchor{4292}
@deffn {C 类型} _PyCFunctionFast

Type of the functions used to implement Python callables in C
with signature @ref{113c,,METH_FASTCALL}.
The function signature is:

@example
PyObject *_PyCFunctionFast(PyObject *self,
                           PyObject *const *args,
                           Py_ssize_t nargs);
@end example
@end deffn

@geindex _PyCFunctionFastWithKeywords (C 类型)
@anchor{c-api/structures c _PyCFunctionFastWithKeywords}@anchor{4293}
@deffn {C 类型} _PyCFunctionFastWithKeywords

Type of the functions used to implement Python callables in C
with signature @code{METH_FASTCALL | METH_KEYWORDS}.
The function signature is:

@example
PyObject *_PyCFunctionFastWithKeywords(PyObject *self,
                                       PyObject *const *args,
                                       Py_ssize_t nargs,
                                       PyObject *kwnames);
@end example
@end deffn

@geindex PyCMethod (C 类型)
@anchor{c-api/structures c PyCMethod}@anchor{249}
@deffn {C 类型} PyCMethod

Type of the functions used to implement Python callables in C
with signature @code{METH_METHOD | METH_FASTCALL | METH_KEYWORDS}.
The function signature is:

@example
PyObject *PyCMethod(PyObject *self,
                    PyTypeObject *defining_class,
                    PyObject *const *args,
                    Py_ssize_t nargs,
                    PyObject *kwnames)
@end example


3.9 新版功能.

@end deffn

@geindex PyMethodDef (C 类型)
@anchor{c-api/structures c PyMethodDef}@anchor{ee5}
@deffn {C 类型} PyMethodDef

Structure used to describe a method of an extension type.  This structure has
four fields:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

C 类型

@tab

意义

@item

@code{ml_name}

@tab

const char *

@tab

name of the method

@item

@code{ml_meth}

@tab

PyCFunction

@tab

pointer to the C
implementation

@item

@code{ml_flags}

@tab

int

@tab

flag bits indicating how the
call should be constructed

@item

@code{ml_doc}

@tab

const char *

@tab

points to the contents of the
docstring

@end multitable

@end deffn

The @code{ml_meth} is a C function pointer.  The functions may be of different
types, but they always return @ref{5bd,,PyObject*}.  If the function is not of
the @ref{ea7,,PyCFunction}, the compiler will require a cast in the method table.
Even though @ref{ea7,,PyCFunction} defines the first parameter as
@ref{5bd,,PyObject*}, it is common that the method implementation uses the
specific C type of the @emph{self} object.

The @code{ml_flags} field is a bitfield which can include the following flags.
The individual flags indicate either a calling convention or a binding
convention.

There are these calling conventions:

@geindex METH_VARARGS (內置变量)
@anchor{c-api/structures METH_VARARGS}@anchor{f12}
@deffn {数据} METH_VARARGS

This is the typical calling convention, where the methods have the type
@ref{ea7,,PyCFunction}. The function expects two @ref{5bd,,PyObject*} values.
The first one is the @emph{self} object for methods; for module functions, it is
the module object.  The second parameter (often called @emph{args}) is a tuple
object representing all arguments. This parameter is typically processed
using @ref{39b,,PyArg_ParseTuple()} or @ref{f10,,PyArg_UnpackTuple()}.
@end deffn


@deffn {数据} METH_VARARGS | METH_KEYWORDS

Methods with these flags must be of type @ref{4291,,PyCFunctionWithKeywords}.
The function expects three parameters: @emph{self}, @emph{args}, @emph{kwargs} where
@emph{kwargs} is a dictionary of all the keyword arguments or possibly @code{NULL}
if there are no keyword arguments.  The parameters are typically processed
using @ref{6cb,,PyArg_ParseTupleAndKeywords()}.
@end deffn

@geindex METH_FASTCALL (內置变量)
@anchor{c-api/structures METH_FASTCALL}@anchor{113c}
@deffn {数据} METH_FASTCALL

Fast calling convention supporting only positional arguments.
The methods have the type @ref{4292,,_PyCFunctionFast}.
The first parameter is @emph{self}, the second parameter is a C array
of @ref{5bd,,PyObject*} values indicating the arguments and the third
parameter is the number of arguments (the length of the array).

This is not part of the @ref{3e13,,limited API}.


3.7 新版功能.

@end deffn


@deffn {数据} METH_FASTCALL | METH_KEYWORDS

Extension of @ref{113c,,METH_FASTCALL} supporting also keyword arguments,
with methods of type @ref{4293,,_PyCFunctionFastWithKeywords}.
Keyword arguments are passed the same way as in the
@ref{2bf,,vectorcall protocol}:
there is an additional fourth @ref{5bd,,PyObject*} parameter
which is a tuple representing the names of the keyword arguments
(which are guaranteed to be strings)
or possibly @code{NULL} if there are no keywords.  The values of the keyword
arguments are stored in the @emph{args} array, after the positional arguments.

This is not part of the @ref{3e13,,limited API}.


3.7 新版功能.

@end deffn


@deffn {数据} METH_METHOD | METH_FASTCALL | METH_KEYWORDS

Extension of @code{METH_FASTCALL | METH_KEYWORDS} supporting the @emph{defining
class}, that is, the class that contains the method in question.
The defining class might be a superclass of @code{Py_TYPE(self)}.

The method needs to be of type @ref{249,,PyCMethod}, the same as for
@code{METH_FASTCALL | METH_KEYWORDS} with @code{defining_class} argument added after
@code{self}.


3.9 新版功能.

@end deffn

@geindex METH_NOARGS (內置变量)
@anchor{c-api/structures METH_NOARGS}@anchor{ee2}
@deffn {数据} METH_NOARGS

Methods without parameters don't need to check whether arguments are given if
they are listed with the @ref{ee2,,METH_NOARGS} flag.  They need to be of type
@ref{ea7,,PyCFunction}.  The first parameter is typically named @emph{self} and will
hold a reference to the module or object instance.  In all cases the second
parameter will be @code{NULL}.
@end deffn

@geindex METH_O (內置变量)
@anchor{c-api/structures METH_O}@anchor{f11}
@deffn {数据} METH_O

Methods with a single object argument can be listed with the @ref{f11,,METH_O}
flag, instead of invoking @ref{39b,,PyArg_ParseTuple()} with a @code{"O"} argument.
They have the type @ref{ea7,,PyCFunction}, with the @emph{self} parameter, and a
@ref{5bd,,PyObject*} parameter representing the single argument.
@end deffn

These two constants are not used to indicate the calling convention but the
binding when use with methods of classes.  These may not be used for functions
defined for modules.  At most one of these flags may be set for any given
method.

@geindex METH_CLASS (內置变量)
@anchor{c-api/structures METH_CLASS}@anchor{ee3}
@deffn {数据} METH_CLASS

@geindex 內置函数; classmethod

The method will be passed the type object as the first parameter rather
than an instance of the type.  This is used to create @emph{class methods},
similar to what is created when using the @ref{310,,classmethod()} built-in
function.
@end deffn

@geindex METH_STATIC (內置变量)
@anchor{c-api/structures METH_STATIC}@anchor{ee4}
@deffn {数据} METH_STATIC

@geindex 內置函数; staticmethod

The method will be passed @code{NULL} as the first parameter rather than an
instance of the type.  This is used to create @emph{static methods}, similar to
what is created when using the @ref{311,,staticmethod()} built-in function.
@end deffn

One other constant controls whether a method is loaded in place of another
definition with the same method name.

@geindex METH_COEXIST (內置变量)
@anchor{c-api/structures METH_COEXIST}@anchor{4294}
@deffn {数据} METH_COEXIST

The method will be loaded in place of existing definitions.  Without
@emph{METH_COEXIST}, the default is to skip repeated definitions.  Since slot
wrappers are loaded before the method table, the existence of a
@emph{sq_contains} slot, for example, would generate a wrapped method named
@ref{df6,,__contains__()} and preclude the loading of a corresponding
PyCFunction with the same name.  With the flag defined, the PyCFunction
will be loaded in place of the wrapper object and will co-exist with the
slot.  This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.
@end deffn

@node Accessing attributes of extension types,,Implementing functions and methods,公用对象的结构
@anchor{c-api/structures accessing-attributes-of-extension-types}@anchor{4295}
@subsubsection Accessing attributes of extension types


@geindex PyMemberDef (C 类型)
@anchor{c-api/structures c PyMemberDef}@anchor{532}
@deffn {C 类型} PyMemberDef

Structure which describes an attribute of a type which corresponds to a C
struct member.  Its fields are:


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

C 类型

@tab

意义

@item

@code{name}

@tab

const char *

@tab

name of the member

@item

@code{type}

@tab

int

@tab

the type of the member in the
C struct

@item

@code{offset}

@tab

Py_ssize_t

@tab

the offset in bytes that the
member is located on the
type's object struct

@item

@code{flags}

@tab

int

@tab

flag bits indicating if the
field should be read-only or
writable

@item

@code{doc}

@tab

const char *

@tab

points to the contents of the
docstring

@end multitable


@code{type} can be one of many @code{T_} macros corresponding to various C
types.  When the member is accessed in Python, it will be converted to the
equivalent Python type.


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

Macro name

@tab

C数据类型

@item

T_SHORT

@tab

short

@item

T_INT

@tab

int

@item

T_LONG

@tab

长整型

@item

T_FLOAT

@tab

float

@item

T_DOUBLE

@tab

double

@item

T_STRING

@tab

const char *

@item

T_OBJECT

@tab

PyObject *

@item

T_OBJECT_EX

@tab

PyObject *

@item

T_CHAR

@tab

字符

@item

T_BYTE

@tab

字符

@item

T_UBYTE

@tab

unsigned char

@item

T_UINT

@tab

无符号整型

@item

T_USHORT

@tab

unsigned short

@item

T_ULONG

@tab

无符号长整型

@item

T_BOOL

@tab

字符

@item

T_LONGLONG

@tab

long long

@item

T_ULONGLONG

@tab

无符号 long long

@item

T_PYSSIZET

@tab

Py_ssize_t

@end multitable


@code{T_OBJECT} and @code{T_OBJECT_EX} differ in that
@code{T_OBJECT} returns @code{None} if the member is @code{NULL} and
@code{T_OBJECT_EX} raises an @ref{4aa,,AttributeError}.  Try to use
@code{T_OBJECT_EX} over @code{T_OBJECT} because @code{T_OBJECT_EX}
handles use of the @ref{13d1,,del} statement on that attribute more correctly
than @code{T_OBJECT}.

@code{flags} can be @code{0} for write and read access or @code{READONLY} for
read-only access.  Using @code{T_STRING} for @ref{709,,type} implies
@code{READONLY}.  @code{T_STRING} data is interpreted as UTF-8.
Only @code{T_OBJECT} and @code{T_OBJECT_EX}
members can be deleted.  (They are set to @code{NULL}).
@anchor{c-api/structures pymemberdef-offsets}@anchor{3fcf}
Heap allocated types (created using @ref{23b,,PyType_FromSpec()} or similar),
@code{PyMemberDef} may contain definitions for the special members
@code{__dictoffset__}, @code{__weaklistoffset__} and @code{__vectorcalloffset__},
corresponding to
@ref{3fd0,,tp_dictoffset},
@ref{26c,,tp_weaklistoffset} and
@ref{3f19,,tp_vectorcall_offset} in type objects.
These must be defined with @code{T_PYSSIZET} and @code{READONLY}, for example:

@example
static PyMemberDef spam_type_members[] = @{
    @{"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY@},
    @{NULL@}  /* Sentinel */
@};
@end example
@end deffn

@geindex PyMember_GetOne (C 函数)
@anchor{c-api/structures c PyMember_GetOne}@anchor{4296}
@deffn {C 函数} PyObject* PyMember_GetOne (const char@w{ }*obj_addr, struct PyMemberDef@w{ }*m)

Get an attribute belonging to the object at address @emph{obj_addr}.  The
attribute is described by @code{PyMemberDef} @emph{m}.  Returns @code{NULL}
on error.
@end deffn

@geindex PyMember_SetOne (C 函数)
@anchor{c-api/structures c PyMember_SetOne}@anchor{4297}
@deffn {C 函数} int PyMember_SetOne (char@w{ }*obj_addr, struct PyMemberDef@w{ }*m, PyObject@w{ }*o)

Set an attribute belonging to the object at address @emph{obj_addr} to object @emph{o}.
The attribute to set is described by @code{PyMemberDef} @emph{m}.  Returns @code{0}
if successful and a negative value on failure.
@end deffn

@geindex PyGetSetDef (C 类型)
@anchor{c-api/structures c PyGetSetDef}@anchor{533}
@deffn {C 类型} PyGetSetDef

Structure to define property-like access for a type. See also description of
the @ref{3d9d,,PyTypeObject.tp_getset} slot.


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

域

@tab

C 类型

@tab

意义

@item

name

@tab

const char *

@tab

attribute name

@item

get

@tab

getter

@tab

C function to get the attribute

@item

set

@tab

setter

@tab

optional C function to set or
delete the attribute, if omitted
the attribute is readonly

@item

doc

@tab

const char *

@tab

optional docstring

@item

closure

@tab

void *

@tab

optional function pointer,
providing additional data for
getter and setter

@end multitable


The @code{get} function takes one @ref{5bd,,PyObject*} parameter (the
instance) and a function pointer (the associated @code{closure}):

@example
typedef PyObject *(*getter)(PyObject *, void *);
@end example

It should return a new reference on success or @code{NULL} with a set exception
on failure.

@code{set} functions take two @ref{5bd,,PyObject*} parameters (the instance and
the value to be set) and a function pointer (the associated @code{closure}):

@example
typedef int (*setter)(PyObject *, PyObject *, void *);
@end example

In case the attribute should be deleted the second parameter is @code{NULL}.
Should return @code{0} on success or @code{-1} with a set exception on failure.
@end deffn

@node Type 对象<2>,Number Object Structures,公用对象的结构,对象实现支持
@anchor{c-api/typeobj doc}@anchor{4298}@anchor{c-api/typeobj type-objects}@anchor{4299}@anchor{c-api/typeobj type-structs}@anchor{272}
@subsection Type 对象


也许 Python 对象系统中最重要的结构之一就是定义新类型的结构: @ref{3fe,,PyTypeObject} 结构。 类型对象可以使用任何 @code{PyObject_*()} 或 @code{PyType_*()} 函数来处理，但不能提供大多数 Python 应用程序所感兴趣的内容。 这些对象是对象行为的基础，所以它们对解释器本身或任何实现新类型的扩展模块都非常重要。

与大多数标准类型相比，类型对象相当大。这么大的原因是每个类型对象存储了大量的值，大部分是C函数指针，每个指针实现了类型功能的一小部分。本节将详细描述类型对象的字段。这些字段将按照它们在结构中出现的顺序进行描述。

除了下面的快速参考，@ref{429a,,例子} 小节提供了快速了解 @ref{3fe,,PyTypeObject} 的含义和用法的例子。

@menu
* 快速参考: 快速参考<2>. 
* PyTypeObject 定义:: 
* PyObject 槽位:: 
* PyVarObject 槽位:: 
* PyTypeObject 槽:: 
* Heap Types:: 

@end menu

@node 快速参考<2>,PyTypeObject 定义,,Type 对象<2>
@anchor{c-api/typeobj quick-reference}@anchor{429b}
@subsubsection 快速参考


@menu
* "tp 槽":: 
* 子方法槽（方法域）:: 
* 槽位 typedef:: 

@end menu

@node "tp 槽",子方法槽（方法域）,,快速参考<2>
@anchor{c-api/typeobj tp-slots}@anchor{429c}@anchor{c-api/typeobj tp-slots-table}@anchor{429d}
@subsubsection "tp 槽"



@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} {xxx} {xxx} {xxx} {xxx} 
@headitem

PyTypeObject 槽 @footnote{@w{(1)} 
小括号中的槽名表示它(实际上)已弃用。尖括号中的名称应该被视为只读的。方括号中的名称仅供内部使用。"<R>"(作为前缀)表示该字段是必需的(必须是非null)。
}

@tab

@ref{429e,,Type}

@tab

特殊方法/属性

@tab

信息 @footnote{@w{(2)} 
列：

@strong{"O"}:  @code{PyBaseObject_Type} 必须设置

@strong{"T"}: @ref{3fb6,,PyType_Type} 必须设置

@strong{"D"}: 默认设置(如果方法槽被设置为NULL)

@example
X - PyType_Ready sets this value if it is NULL
~ - PyType_Ready always sets this value (it should be NULL)
? - PyType_Ready may set this value depending on other slots

Also see the inheritance column ("I").
@end example

@strong{"I"}: 继承

@example
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
% - the slots of the sub-struct are inherited individually
G - inherited, but only in combination with other slots; see the slot's description
? - it's complicated; see the slot's description
@end example

注意，有些方法槽是通过普通属性查找链有效继承的。
}

@tab

@tab

@tab

@item

O

@tab

T

@tab

D

@tab

I

@item

<R> @ref{3dae,,tp_name}

@tab

const char *

@tab

__name__

@tab

X

@tab

X

@tab

@tab

@item

@ref{26b,,tp_basicsize}

@tab

@ref{391,,Py_ssize_t}

@tab

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{3d8d,,tp_itemsize}

@tab

@ref{391,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

X

@item

@ref{3d93,,tp_dealloc}

@tab

@ref{429f,,destructor}

@tab

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{3f19,,tp_vectorcall_offset}

@tab

@ref{391,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

X

@item

(@ref{3db5,,tp_getattr})

@tab

@ref{42a0,,getattrfunc}

@tab

__getattribute__,
__getattr__

@tab

@tab

@tab

@tab

G

@item

(@ref{3db6,,tp_setattr})

@tab

@ref{42a1,,setattrfunc}

@tab

__setattr__,
__delattr__

@tab

@tab

@tab

@tab

G

@item

@ref{42a2,,tp_as_async}

@tab

@ref{3fc6,,PyAsyncMethods} *

@tab

@ref{42a3,,子方法槽（方法域）}

@tab

@tab

@tab

@tab

%

@item

@ref{3dad,,tp_repr}

@tab

@ref{42a4,,reprfunc}

@tab

__repr__

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{270,,tp_as_number}

@tab

@ref{e4e,,PyNumberMethods} *

@tab

@ref{42a3,,子方法槽（方法域）}

@tab

@tab

@tab

@tab

%

@item

@ref{42a5,,tp_as_sequence}

@tab

@ref{3dbc,,PySequenceMethods} *

@tab

@ref{42a3,,子方法槽（方法域）}

@tab

@tab

@tab

@tab

%

@item

@ref{42a6,,tp_as_mapping}

@tab

@ref{3dbd,,PyMappingMethods} *

@tab

@ref{42a3,,子方法槽（方法域）}

@tab

@tab

@tab

@tab

%

@item

@ref{3dbe,,tp_hash}

@tab

@ref{42a7,,hashfunc}

@tab

__hash__

@tab

X

@tab

@tab

@tab

G

@item

@ref{3dbf,,tp_call}

@tab

@ref{42a8,,ternaryfunc}

@tab

__call__

@tab

@tab

X

@tab

@tab

X

@item

@ref{3daf,,tp_str}

@tab

@ref{42a4,,reprfunc}

@tab

__str__

@tab

X

@tab

@tab

@tab

X

@item

@ref{3db2,,tp_getattro}

@tab

@ref{42a9,,getattrofunc}

@tab

__getattribute__,
__getattr__

@tab

X

@tab

X

@tab

@tab

G

@item

@ref{3db3,,tp_setattro}

@tab

@ref{42aa,,setattrofunc}

@tab

__setattr__,
__delattr__

@tab

X

@tab

X

@tab

@tab

G

@item

@ref{26e,,tp_as_buffer}

@tab

@ref{3fd2,,PyBufferProcs} *

@tab

@tab

@tab

@tab

@tab

%

@item

@ref{105b,,tp_flags}

@tab

无符号长整型

@tab

@tab

X

@tab

X

@tab

@tab

?

@item

@ref{3d8f,,tp_doc}

@tab

const char *

@tab

__doc__

@tab

X

@tab

X

@tab

@tab

@item

@ref{23c,,tp_traverse}

@tab

@ref{42ab,,traverseproc}

@tab

@tab

@tab

X

@tab

@tab

G

@item

@ref{3dab,,tp_clear}

@tab

@ref{42ac,,inquiry}

@tab

@tab

@tab

X

@tab

@tab

G

@item

@ref{3db8,,tp_richcompare}

@tab

@ref{42ad,,richcmpfunc}

@tab

__lt__,
__le__,
__eq__,
__ne__,
__gt__,
__ge__

@tab

X

@tab

@tab

@tab

G

@item

@ref{26c,,tp_weaklistoffset}

@tab

@ref{391,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

?

@item

@ref{efa,,tp_iter}

@tab

@ref{42ae,,getiterfunc}

@tab

__iter__

@tab

@tab

@tab

@tab

X

@item

@ref{efb,,tp_iternext}

@tab

@ref{42af,,iternextfunc}

@tab

__next__

@tab

@tab

@tab

@tab

X

@item

@ref{3d9a,,tp_methods}

@tab

@ref{ee5,,PyMethodDef} []

@tab

@tab

X

@tab

X

@tab

@tab

@item

@ref{3d98,,tp_members}

@tab

@ref{532,,PyMemberDef} []

@tab

@tab

@tab

X

@tab

@tab

@item

@ref{3d9d,,tp_getset}

@tab

@ref{533,,PyGetSetDef} []

@tab

@tab

X

@tab

X

@tab

@tab

@item

@ref{3da3,,tp_base}

@tab

@ref{3fe,,PyTypeObject} *

@tab

__base__

@tab

@tab

@tab

X

@tab

@item

@ref{3fc9,,tp_dict}

@tab

@ref{5bd,,PyObject} *

@tab

__dict__

@tab

@tab

@tab

?

@tab

@item

@ref{42b0,,tp_descr_get}

@tab

@ref{42b1,,descrgetfunc}

@tab

__get__

@tab

@tab

@tab

@tab

X

@item

@ref{42b2,,tp_descr_set}

@tab

@ref{42b3,,descrsetfunc}

@tab

__set__,
__delete__

@tab

@tab

@tab

@tab

X

@item

@ref{3fd0,,tp_dictoffset}

@tab

@ref{391,,Py_ssize_t}

@tab

@tab

@tab

X

@tab

@tab

?

@item

@ref{3d97,,tp_init}

@tab

@ref{42b4,,initproc}

@tab

__init__

@tab

X

@tab

X

@tab

@tab

X

@item

@ref{3d95,,tp_alloc}

@tab

@ref{42b5,,allocfunc}

@tab

@tab

X

@tab

@tab

?

@tab

?

@item

@ref{3d90,,tp_new}

@tab

@ref{42b6,,newfunc}

@tab

__new__

@tab

X

@tab

X

@tab

?

@tab

?

@item

@ref{3d94,,tp_free}

@tab

@ref{42b7,,freefunc}

@tab

@tab

X

@tab

X

@tab

?

@tab

?

@item

@ref{42b8,,tp_is_gc}

@tab

@ref{42ac,,inquiry}

@tab

@tab

@tab

X

@tab

@tab

X

@item

<@ref{42b9,,tp_bases}>

@tab

@ref{5bd,,PyObject} *

@tab

__bases__

@tab

@tab

@tab

~

@tab

@item

<@ref{3fca,,tp_mro}>

@tab

@ref{5bd,,PyObject} *

@tab

__mro__

@tab

@tab

@tab

~

@tab

@item

[@ref{3fcb,,tp_cache}]

@tab

@ref{5bd,,PyObject} *

@tab

@tab

@tab

@tab

@tab

@item

[@ref{3fcc,,tp_subclasses}]

@tab

@ref{5bd,,PyObject} *

@tab

__subclasses__

@tab

@tab

@tab

@tab

@item

[@ref{3fcd,,tp_weaklist}]

@tab

@ref{5bd,,PyObject} *

@tab

@tab

@tab

@tab

@tab

@item

(@ref{42ba,,tp_del})

@tab

@ref{429f,,destructor}

@tab

@tab

@tab

@tab

@tab

@item

[@ref{42bb,,tp_version_tag}]

@tab

无符号整型

@tab

@tab

@tab

@tab

@tab

@item

@ref{3ff,,tp_finalize}

@tab

@ref{429f,,destructor}

@tab

__del__

@tab

@tab

@tab

@tab

X

@item

@ref{3fce,,tp_vectorcall}

@tab

@ref{3f1a,,vectorcallfunc}

@tab

@tab

@tab

@tab

@tab

@end multitable


@node 子方法槽（方法域）,槽位 typedef,"tp 槽",快速参考<2>
@anchor{c-api/typeobj id3}@anchor{42bc}@anchor{c-api/typeobj sub-slots}@anchor{42a3}
@subsubsection 子方法槽（方法域）



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

槽

@tab

@ref{429e,,Type}

@tab

特殊方法

@item

@ref{42bd,,am_await}

@tab

@ref{42be,,unaryfunc}

@tab

__await__

@item

@ref{42bf,,am_aiter}

@tab

@ref{42be,,unaryfunc}

@tab

__aiter__

@item

@ref{42c0,,am_anext}

@tab

@ref{42be,,unaryfunc}

@tab

__anext__

@item

@tab

@tab

@item

@ref{3fc7,,nb_add}

@tab

@ref{42c1,,binaryfunc}

@tab

__add__
__radd__

@item

@ref{42c2,,nb_inplace_add}

@tab

@ref{42c1,,binaryfunc}

@tab

__iadd__

@item

@ref{42c3,,nb_subtract}

@tab

@ref{42c1,,binaryfunc}

@tab

__sub__
__rsub__

@item

@ref{42c4,,nb_inplace_subtract}

@tab

@ref{42c1,,binaryfunc}

@tab

__isub__

@item

@ref{42c5,,nb_multiply}

@tab

@ref{42c1,,binaryfunc}

@tab

__mul__
__rmul__

@item

@ref{42c6,,nb_inplace_multiply}

@tab

@ref{42c1,,binaryfunc}

@tab

__imul__

@item

@ref{42c7,,nb_remainder}

@tab

@ref{42c1,,binaryfunc}

@tab

__mod__
__rmod__

@item

@ref{42c8,,nb_inplace_remainder}

@tab

@ref{42c1,,binaryfunc}

@tab

__imod__

@item

@ref{42c9,,nb_divmod}

@tab

@ref{42c1,,binaryfunc}

@tab

__divmod__
__rdivmod__

@item

@ref{42ca,,nb_power}

@tab

@ref{42a8,,ternaryfunc}

@tab

__pow__
__rpow__

@item

@ref{42cb,,nb_inplace_power}

@tab

@ref{42a8,,ternaryfunc}

@tab

__ipow__

@item

@ref{42cc,,nb_negative}

@tab

@ref{42be,,unaryfunc}

@tab

__neg__

@item

@ref{42cd,,nb_positive}

@tab

@ref{42be,,unaryfunc}

@tab

__pos__

@item

@ref{42ce,,nb_absolute}

@tab

@ref{42be,,unaryfunc}

@tab

__abs__

@item

@ref{42cf,,nb_bool}

@tab

@ref{42ac,,inquiry}

@tab

__bool__

@item

@ref{42d0,,nb_invert}

@tab

@ref{42be,,unaryfunc}

@tab

__invert__

@item

@ref{42d1,,nb_lshift}

@tab

@ref{42c1,,binaryfunc}

@tab

__lshift__
__rlshift__

@item

@ref{42d2,,nb_inplace_lshift}

@tab

@ref{42c1,,binaryfunc}

@tab

__ilshift__

@item

@ref{42d3,,nb_rshift}

@tab

@ref{42c1,,binaryfunc}

@tab

__rshift__
__rrshift__

@item

@ref{42d4,,nb_inplace_rshift}

@tab

@ref{42c1,,binaryfunc}

@tab

__irshift__

@item

@ref{42d5,,nb_and}

@tab

@ref{42c1,,binaryfunc}

@tab

__and__
__rand__

@item

@ref{42d6,,nb_inplace_and}

@tab

@ref{42c1,,binaryfunc}

@tab

__iand__

@item

@ref{42d7,,nb_xor}

@tab

@ref{42c1,,binaryfunc}

@tab

__xor__
__rxor__

@item

@ref{42d8,,nb_inplace_xor}

@tab

@ref{42c1,,binaryfunc}

@tab

__ixor__

@item

@ref{42d9,,nb_or}

@tab

@ref{42c1,,binaryfunc}

@tab

__or__
__ror__

@item

@ref{42da,,nb_inplace_or}

@tab

@ref{42c1,,binaryfunc}

@tab

__ior__

@item

@ref{42db,,nb_int}

@tab

@ref{42be,,unaryfunc}

@tab

__int__

@item

@ref{42dc,,nb_reserved}

@tab

void *

@tab

@item

@ref{42dd,,nb_float}

@tab

@ref{42be,,unaryfunc}

@tab

__float__

@item

@ref{42de,,nb_floor_divide}

@tab

@ref{42c1,,binaryfunc}

@tab

__floordiv__

@item

@ref{42df,,nb_inplace_floor_divide}

@tab

@ref{42c1,,binaryfunc}

@tab

__ifloordiv__

@item

@ref{42e0,,nb_true_divide}

@tab

@ref{42c1,,binaryfunc}

@tab

__truediv__

@item

@ref{42e1,,nb_inplace_true_divide}

@tab

@ref{42c1,,binaryfunc}

@tab

__itruediv__

@item

@ref{42e2,,nb_index}

@tab

@ref{42be,,unaryfunc}

@tab

__index__

@item

@ref{42e3,,nb_matrix_multiply}

@tab

@ref{42c1,,binaryfunc}

@tab

__matmul__
__rmatmul__

@item

@ref{42e4,,nb_inplace_matrix_multiply}

@tab

@ref{42c1,,binaryfunc}

@tab

__imatmul__

@item

@tab

@tab

@item

@ref{42e5,,mp_length}

@tab

@ref{42e6,,lenfunc}

@tab

__len__

@item

@ref{42e7,,mp_subscript}

@tab

@ref{42c1,,binaryfunc}

@tab

__getitem__

@item

@ref{42e8,,mp_ass_subscript}

@tab

@ref{42e9,,objobjargproc}

@tab

__setitem__,
__delitem__

@item

@tab

@tab

@item

@ref{3fc8,,sq_length}

@tab

@ref{42e6,,lenfunc}

@tab

__len__

@item

@ref{42ea,,sq_concat}

@tab

@ref{42c1,,binaryfunc}

@tab

__add__

@item

@ref{42eb,,sq_repeat}

@tab

@ref{42ec,,ssizeargfunc}

@tab

__mul__

@item

@ref{1108,,sq_item}

@tab

@ref{42ec,,ssizeargfunc}

@tab

__getitem__

@item

@ref{42ed,,sq_ass_item}

@tab

@ref{42ee,,ssizeobjargproc}

@tab

__setitem__
__delitem__

@item

@ref{42ef,,sq_contains}

@tab

@ref{42f0,,objobjproc}

@tab

__contains__

@item

@ref{42f1,,sq_inplace_concat}

@tab

@ref{42c1,,binaryfunc}

@tab

__iadd__

@item

@ref{42f2,,sq_inplace_repeat}

@tab

@ref{42ec,,ssizeargfunc}

@tab

__imul__

@item

@tab

@tab

@item

@ref{3fd1,,bf_getbuffer}

@tab

@ref{42f3,,getbufferproc()}

@tab

@item

@ref{3ec7,,bf_releasebuffer}

@tab

@ref{42f4,,releasebufferproc()}

@tab

@end multitable


@node 槽位 typedef,,子方法槽（方法域）,快速参考<2>
@anchor{c-api/typeobj slot-typedefs}@anchor{42f5}@anchor{c-api/typeobj slot-typedefs-table}@anchor{429e}
@subsubsection 槽位 typedef



@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

typedef

@tab

参数类型

@tab

返回类型

@item

@ref{42b5,,allocfunc}

@tab


@display
@ref{3fe,,PyTypeObject} *@w{ }
@ref{391,,Py_ssize_t}@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{429f,,destructor}

@tab

void *

@tab

void

@item

@ref{42b7,,freefunc}

@tab

void *

@tab

void

@item

@ref{42ab,,traverseproc}

@tab


@display
void *@w{ }
@ref{42f6,,visitproc}@w{ }
void *@w{ }
@end display



@tab

整型

@item

@ref{42b6,,newfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42b4,,initproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@item

@ref{42a4,,reprfunc}

@tab

@ref{5bd,,PyObject} *

@tab

@ref{5bd,,PyObject} *

@item

@ref{42a0,,getattrfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
const char *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42a1,,setattrfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
const char *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@item

@ref{42a9,,getattrofunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42aa,,setattrofunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@item

@ref{42b1,,descrgetfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42b3,,descrsetfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@item

@ref{42a7,,hashfunc}

@tab

@ref{5bd,,PyObject} *

@tab

Py_hash_t

@item

@ref{42ad,,richcmpfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
整型@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42ae,,getiterfunc}

@tab

@ref{5bd,,PyObject} *

@tab

@ref{5bd,,PyObject} *

@item

@ref{42af,,iternextfunc}

@tab

@ref{5bd,,PyObject} *

@tab

@ref{5bd,,PyObject} *

@item

@ref{42e6,,lenfunc}

@tab

@ref{5bd,,PyObject} *

@tab

@ref{391,,Py_ssize_t}

@item

@ref{42f3,,getbufferproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{bf7,,Py_buffer} *@w{ }
整型@w{ }
@end display



@tab

整型

@item

@ref{42f4,,releasebufferproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{bf7,,Py_buffer} *@w{ }
@end display



@tab

void

@item

@ref{42ac,,inquiry}

@tab

void *

@tab

整型

@item

@ref{42be,,unaryfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42c1,,binaryfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42a8,,ternaryfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42ec,,ssizeargfunc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{391,,Py_ssize_t}@w{ }
@end display



@tab

@ref{5bd,,PyObject} *

@item

@ref{42ee,,ssizeobjargproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{391,,Py_ssize_t}@w{ }
@end display



@tab

整型

@item

@ref{42f0,,objobjproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@item

@ref{42e9,,objobjargproc}

@tab


@display
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@ref{5bd,,PyObject} *@w{ }
@end display



@tab

整型

@end multitable


请参阅 @ref{42f7,,Slot Type typedefs} 里有更多详细信息。

@node PyTypeObject 定义,PyObject 槽位,快速参考<2>,Type 对象<2>
@anchor{c-api/typeobj pytypeobject-definition}@anchor{42f8}
@subsubsection PyTypeObject 定义


@ref{3fe,,PyTypeObject} 的结构定义可以在 @code{Include/object.h} 中找到。 为了方便参考，此处复述了其中的定义:

@c XXX Drop this?

@example
typedef struct _typeobject @{
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;

@} PyTypeObject;
@end example

@node PyObject 槽位,PyVarObject 槽位,PyTypeObject 定义,Type 对象<2>
@anchor{c-api/typeobj pyobject-slots}@anchor{42f9}
@subsubsection PyObject 槽位


类型对象结构扩展了 @ref{428b,,PyVarObject} 结构。 @code{ob_size} 字段用于动态类型 (由 @code{type_new()} 创建，通常通过 类 语句来调用)。 注意 @ref{3fb6,,PyType_Type} (元类型) 会初始化 @ref{3d8d,,tp_itemsize}，这意味着它的实例 (即类型对象) @emph{必须} 具有 @code{ob_size} 字段。

@geindex PyObject._ob_next (C 成员)
@geindex PyObject._ob_prev (C 成员)
@anchor{c-api/typeobj c PyObject _ob_next}@anchor{42fa}
@deffn {C 成员} PyObject* PyObject._ob_next
@anchor{c-api/typeobj c PyObject _ob_prev}@anchor{42fb}
@deffnx {C 成员} PyObject* PyObject._ob_prev

These fields are only present when the macro @code{Py_TRACE_REFS} is defined.
Their initialization to @code{NULL} is taken care of by the @code{PyObject_HEAD_INIT}
macro.  For statically allocated objects, these fields always remain @code{NULL}.
For dynamically allocated objects, these two fields are used to link the object
into a doubly-linked list of @emph{all} live objects on the heap.  This could be used
for various debugging purposes; currently the only use is to print the objects
that are still alive at the end of a run when the environment variable
@geindex PYTHONDUMPREFS
@geindex 环境变量; PYTHONDUMPREFS
@ref{29a,,PYTHONDUMPREFS} is set.

@strong{继承：}

这些字段不会被子类型继承。
@end deffn

@geindex PyObject.ob_refcnt (C 成员)
@anchor{c-api/typeobj c PyObject ob_refcnt}@anchor{42fc}
@deffn {C 成员} Py_ssize_t PyObject.ob_refcnt

这是类型对象的引用计数，由 @code{PyObject_HEAD_INIT} 宏初始化为 @code{1}。 请注意对于静态分配的类型对象 (对象的 @code{ob_type} 指回该类型) @emph{不会} 被加入引用计数。 但对于动态分配的类型对象，实例 @emph{确实} 会被算作引用。

@strong{继承：}

子类型不继承此字段。
@end deffn

@geindex PyObject.ob_type (C 成员)
@anchor{c-api/typeobj c PyObject ob_type}@anchor{42fd}
@deffn {C 成员} PyTypeObject* PyObject.ob_type

This is the type's type, in other words its metatype.  It is initialized by the
argument to the @code{PyObject_HEAD_INIT} macro, and its value should normally be
@code{&PyType_Type}.  However, for dynamically loadable extension modules that must
be usable on Windows (at least), the compiler complains that this is not a valid
initializer.  Therefore, the convention is to pass @code{NULL} to the
@code{PyObject_HEAD_INIT} macro and to initialize this field explicitly at the
start of the module's initialization function, before doing anything else.  This
is typically done like this:

@example
Foo_Type.ob_type = &PyType_Type;
@end example

This should be done before any instances of the type are created.
@ref{3d96,,PyType_Ready()} checks if @code{ob_type} is @code{NULL}, and if so,
initializes it to the @code{ob_type} field of the base class.
@ref{3d96,,PyType_Ready()} will not change this field if it is non-zero.

@strong{继承：}

此字段会被子类型继承。
@end deffn

@node PyVarObject 槽位,PyTypeObject 槽,PyObject 槽位,Type 对象<2>
@anchor{c-api/typeobj pyvarobject-slots}@anchor{42fe}
@subsubsection PyVarObject 槽位


@geindex PyVarObject.ob_size (C 成员)
@anchor{c-api/typeobj c PyVarObject ob_size}@anchor{42ff}
@deffn {C 成员} Py_ssize_t PyVarObject.ob_size

For statically allocated type objects, this should be initialized to zero.  For
dynamically allocated type objects, this field has a special internal meaning.

@strong{继承：}

子类型不继承此字段。
@end deffn

@node PyTypeObject 槽,Heap Types,PyVarObject 槽位,Type 对象<2>
@anchor{c-api/typeobj pytypeobject-slots}@anchor{4300}
@subsubsection PyTypeObject 槽


Each slot has a section describing inheritance.  If @ref{3d96,,PyType_Ready()}
may set a value when the field is set to @code{NULL} then there will also be
a "Default" section.  (Note that many fields set on @code{PyBaseObject_Type}
and @ref{3fb6,,PyType_Type} effectively act as defaults.)

@geindex PyTypeObject.tp_name (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_name}@anchor{3dae}
@deffn {C 成员} const char* PyTypeObject.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types
that are accessible as module globals, the string should be the full module
name, followed by a dot, followed by the type name; for built-in types, it
should be just the type name.  If the module is a submodule of a package, the
full package name is part of the full module name.  For example, a type named
@code{T} defined in module @code{M} in subpackage @code{Q} in package @code{P}
should have the @ref{3dae,,tp_name} initializer @code{"P.Q.M.T"}.

For dynamically allocated type objects, this should just be the type name, and
the module name explicitly stored in the type dict as the value for key
@code{'__module__'}.

For statically allocated type objects, the tp_name field should contain a dot.
Everything before the last dot is made accessible as the @code{__module__}
attribute, and everything after the last dot is made accessible as the
@ref{d37,,__name__} attribute.

If no dot is present, the entire @ref{3dae,,tp_name} field is made accessible as the
@ref{d37,,__name__} attribute, and the @code{__module__} attribute is undefined
(unless explicitly set in the dictionary, as explained above).  This means your
type will be impossible to pickle.  Additionally, it will not be listed in
module documentations created with pydoc.

This field must not be @code{NULL}.  It is the only required field
in @ref{3fe,,PyTypeObject()} (other than potentially
@ref{3d8d,,tp_itemsize}).

@strong{继承：}

子类型不继承此字段。
@end deffn

@geindex PyTypeObject.tp_basicsize (C 成员)
@geindex PyTypeObject.tp_itemsize (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_basicsize}@anchor{26b}
@deffn {C 成员} Py_ssize_t PyTypeObject.tp_basicsize
@anchor{c-api/typeobj c PyTypeObject tp_itemsize}@anchor{3d8d}
@deffnx {C 成员} Py_ssize_t PyTypeObject.tp_itemsize

These fields allow calculating the size in bytes of instances of the type.

There are two kinds of types: types with fixed-length instances have a zero
@ref{3d8d,,tp_itemsize} field, types with variable-length instances have a non-zero
@ref{3d8d,,tp_itemsize} field.  For a type with fixed-length instances, all
instances have the same size, given in @ref{26b,,tp_basicsize}.

For a type with variable-length instances, the instances must have an
@code{ob_size} field, and the instance size is @ref{26b,,tp_basicsize} plus N
times @ref{3d8d,,tp_itemsize}, where N is the "length" of the object.  The value of
N is typically stored in the instance's @code{ob_size} field.  There are
exceptions:  for example, ints use a negative @code{ob_size} to indicate a
negative number, and N is @code{abs(ob_size)} there.  Also, the presence of an
@code{ob_size} field in the instance layout doesn't mean that the instance
structure is variable-length (for example, the structure for the list type has
fixed-length instances, yet those instances have a meaningful @code{ob_size}
field).

The basic size includes the fields in the instance declared by the macro
@ref{d42,,PyObject_HEAD} or @ref{428d,,PyObject_VAR_HEAD} (whichever is used to
declare the instance struct) and this in turn includes the @code{_ob_prev} and
@code{_ob_next} fields if they are present.  This means that the only correct
way to get an initializer for the @ref{26b,,tp_basicsize} is to use the
@code{sizeof} operator on the struct used to declare the instance layout.
The basic size does not include the GC header size.

A note about alignment: if the variable items require a particular alignment,
this should be taken care of by the value of @ref{26b,,tp_basicsize}.  Example:
suppose a type implements an array of @code{double}. @ref{3d8d,,tp_itemsize} is
@code{sizeof(double)}. It is the programmer's responsibility that
@ref{26b,,tp_basicsize} is a multiple of @code{sizeof(double)} (assuming this is the
alignment requirement for @code{double}).

For any type with variable-length instances, this field must not be @code{NULL}.

@strong{继承：}

These fields are inherited separately by subtypes.  If the base type has a
non-zero @ref{3d8d,,tp_itemsize}, it is generally not safe to set
@ref{3d8d,,tp_itemsize} to a different non-zero value in a subtype (though this
depends on the implementation of the base type).
@end deffn

@geindex PyTypeObject.tp_dealloc (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_dealloc}@anchor{3d93}
@deffn {C 成员} destructor PyTypeObject.tp_dealloc

A pointer to the instance destructor function.  This function must be defined
unless the type guarantees that its instances will never be deallocated (as is
the case for the singletons @code{None} and @code{Ellipsis}).  The function signature is:

@example
void tp_dealloc(PyObject *self);
@end example

The destructor function is called by the @ref{397,,Py_DECREF()} and
@ref{399,,Py_XDECREF()} macros when the new reference count is zero.  At this point,
the instance is still in existence, but there are no references to it.  The
destructor function should free all references which the instance owns, free all
memory buffers owned by the instance (using the freeing function corresponding
to the allocation function used to allocate the buffer), and call the type's
@ref{3d94,,tp_free} function.  If the type is not subtypable
(doesn't have the @ref{3d9b,,Py_TPFLAGS_BASETYPE} flag bit set), it is
permissible to call the object deallocator directly instead of via
@ref{3d94,,tp_free}.  The object deallocator should be the one used to allocate the
instance; this is normally @ref{ee0,,PyObject_Del()} if the instance was allocated
using @ref{269,,PyObject_New()} or @code{PyObject_VarNew()}, or
@ref{f0d,,PyObject_GC_Del()} if the instance was allocated using
@ref{3fc,,PyObject_GC_New()} or @ref{3fd,,PyObject_GC_NewVar()}.

If the type supports garbage collection (has the @ref{3da1,,Py_TPFLAGS_HAVE_GC}
flag bit set), the destructor should call @ref{f0f,,PyObject_GC_UnTrack()}
before clearing any member fields.

@example
static void foo_dealloc(foo_object *self) @{
    PyObject_GC_UnTrack(self);
    Py_CLEAR(self->ref);
    Py_TYPE(self)->tp_free((PyObject *)self);
@}
@end example

Finally, if the type is heap allocated (@ref{3fbd,,Py_TPFLAGS_HEAPTYPE}), the
deallocator should decrement the reference count for its type object after
calling the type deallocator. In order to avoid dangling pointers, the
recommended way to achieve this is:

@example
static void foo_dealloc(foo_object *self) @{
    PyTypeObject *tp = Py_TYPE(self);
    // free references and buffers here
    tp->tp_free(self);
    Py_DECREF(tp);
@}
@end example

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_vectorcall_offset (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_vectorcall_offset}@anchor{3f19}
@deffn {C 成员} Py_ssize_t PyTypeObject.tp_vectorcall_offset

An optional offset to a per-instance function that implements calling
the object using the @ref{2bf,,vectorcall protocol},
a more efficient alternative
of the simpler @ref{3dbf,,tp_call}.

This field is only used if the flag @ref{3f18,,Py_TPFLAGS_HAVE_VECTORCALL}
is set. If so, this must be a positive integer containing the offset in the
instance of a @ref{3f1a,,vectorcallfunc} pointer.

The @emph{vectorcallfunc} pointer may be @code{NULL}, in which case the instance behaves
as if @ref{3f18,,Py_TPFLAGS_HAVE_VECTORCALL} was not set: calling the instance
falls back to @ref{3dbf,,tp_call}.

Any class that sets @code{Py_TPFLAGS_HAVE_VECTORCALL} must also set
@ref{3dbf,,tp_call} and make sure its behaviour is consistent
with the @emph{vectorcallfunc} function.
This can be done by setting @emph{tp_call} to @ref{3f17,,PyVectorcall_Call()}.

@cartouche
@quotation 警告 
It is not recommended for @ref{3fbc,,heap types} to implement
the vectorcall protocol.
When a user sets @ref{158f,,__call__} in Python code, only @emph{tp_call} is updated,
likely making it inconsistent with the vectorcall function.
@end quotation
@end cartouche

@cartouche
@quotation 注解 
The semantics of the @code{tp_vectorcall_offset} slot are provisional and
expected to be finalized in Python 3.9.
If you use vectorcall, plan for updating your code for Python 3.9.
@end quotation
@end cartouche


在 3.8 版更改: Before version 3.8, this slot was named @code{tp_print}.
In Python 2.x, it was used for printing to a file.
In Python 3.0 to 3.7, it was unused.


@strong{继承：}

This field is always inherited.
However, the @ref{3f18,,Py_TPFLAGS_HAVE_VECTORCALL} flag is not
always inherited. If it's not, then the subclass won't use
@ref{2bf,,vectorcall}, except when
@ref{3f17,,PyVectorcall_Call()} is explicitly called.
This is in particular the case for @ref{4301,,heap types}
(including subclasses defined in Python).
@end deffn

@geindex PyTypeObject.tp_getattr (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_getattr}@anchor{3db5}
@deffn {C 成员} getattrfunc PyTypeObject.tp_getattr

An optional pointer to the get-attribute-string function.

This field is deprecated.  When it is defined, it should point to a function
that acts the same as the @ref{3db2,,tp_getattro} function, but taking a C string
instead of a Python string object to give the attribute name.

@strong{继承：}

分组: @code{tp_getattr}, @code{tp_getattro}

This field is inherited by subtypes together with @ref{3db2,,tp_getattro}: a subtype
inherits both @ref{3db5,,tp_getattr} and @ref{3db2,,tp_getattro} from its base type when
the subtype's @ref{3db5,,tp_getattr} and @ref{3db2,,tp_getattro} are both @code{NULL}.
@end deffn

@geindex PyTypeObject.tp_setattr (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_setattr}@anchor{3db6}
@deffn {C 成员} setattrfunc PyTypeObject.tp_setattr

An optional pointer to the function for setting and deleting attributes.

This field is deprecated.  When it is defined, it should point to a function
that acts the same as the @ref{3db3,,tp_setattro} function, but taking a C string
instead of a Python string object to give the attribute name.

@strong{继承：}

Group: @code{tp_setattr}, @code{tp_setattro}

This field is inherited by subtypes together with @ref{3db3,,tp_setattro}: a subtype
inherits both @ref{3db6,,tp_setattr} and @ref{3db3,,tp_setattro} from its base type when
the subtype's @ref{3db6,,tp_setattr} and @ref{3db3,,tp_setattro} are both @code{NULL}.
@end deffn

@geindex PyTypeObject.tp_as_async (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_as_async}@anchor{42a2}
@deffn {C 成员} PyAsyncMethods* PyTypeObject.tp_as_async

Pointer to an additional structure that contains fields relevant only to
objects which implement @ref{61b,,awaitable} and @ref{742,,asynchronous iterator}
protocols at the C-level.  See @ref{4302,,Async Object Structures} for details.


3.5 新版功能: Formerly known as @code{tp_compare} and @code{tp_reserved}.


@strong{继承：}

The @ref{42a2,,tp_as_async} field is not inherited,
but the contained fields are inherited individually.
@end deffn

@geindex PyTypeObject.tp_repr (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_repr}@anchor{3dad}
@deffn {C 成员} reprfunc PyTypeObject.tp_repr

@geindex 內置函数; repr

An optional pointer to a function that implements the built-in function
@ref{8c3,,repr()}.

The signature is the same as for @ref{a52,,PyObject_Repr()}:

@example
PyObject *tp_repr(PyObject *self);
@end example

The function must return a string or a Unicode object.  Ideally,
this function should return a string that, when passed to
@ref{c6a,,eval()}, given a suitable environment, returns an object with the
same value.  If this is not feasible, it should return a string starting with
@code{'<'} and ending with @code{'>'} from which both the type and the value of the
object can be deduced.

@strong{继承：}

此字段会被子类型继承。

@strong{默认：}

When this field is not set, a string of the form @code{<%s object at %p>} is
returned, where @code{%s} is replaced by the type name, and @code{%p} by the object's
memory address.
@end deffn

@geindex PyTypeObject.tp_as_number (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_as_number}@anchor{270}
@deffn {C 成员} PyNumberMethods* PyTypeObject.tp_as_number

Pointer to an additional structure that contains fields relevant only to
objects which implement the number protocol.  These fields are documented in
@ref{4303,,Number Object Structures}.

@strong{继承：}

The @ref{270,,tp_as_number} field is not inherited, but the contained fields are
inherited individually.
@end deffn

@geindex PyTypeObject.tp_as_sequence (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_as_sequence}@anchor{42a5}
@deffn {C 成员} PySequenceMethods* PyTypeObject.tp_as_sequence

Pointer to an additional structure that contains fields relevant only to
objects which implement the sequence protocol.  These fields are documented
in @ref{4304,,Sequence Object Structures}.

@strong{继承：}

The @ref{42a5,,tp_as_sequence} field is not inherited, but the contained fields
are inherited individually.
@end deffn

@geindex PyTypeObject.tp_as_mapping (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_as_mapping}@anchor{42a6}
@deffn {C 成员} PyMappingMethods* PyTypeObject.tp_as_mapping

Pointer to an additional structure that contains fields relevant only to
objects which implement the mapping protocol.  These fields are documented in
@ref{4305,,Mapping Object Structures}.

@strong{继承：}

The @ref{42a6,,tp_as_mapping} field is not inherited, but the contained fields
are inherited individually.
@end deffn

@geindex PyTypeObject.tp_hash (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_hash}@anchor{3dbe}
@deffn {C 成员} hashfunc PyTypeObject.tp_hash

@geindex 內置函数; hash

An optional pointer to a function that implements the built-in function
@ref{aac,,hash()}.

The signature is the same as for @ref{3f09,,PyObject_Hash()}:

@example
Py_hash_t tp_hash(PyObject *);
@end example

The value @code{-1} should not be returned as a
normal return value; when an error occurs during the computation of the hash
value, the function should set an exception and return @code{-1}.

When this field is not set (@emph{and} @code{tp_richcompare} is not set),
an attempt to take the hash of the object raises @ref{1ff,,TypeError}.
This is the same as setting it to @ref{dff,,PyObject_HashNotImplemented()}.

This field can be set explicitly to @ref{dff,,PyObject_HashNotImplemented()} to
block inheritance of the hash method from a parent type. This is interpreted
as the equivalent of @code{__hash__ = None} at the Python level, causing
@code{isinstance(o, collections.Hashable)} to correctly return @code{False}. Note
that the converse is also true - setting @code{__hash__ = None} on a class at
the Python level will result in the @code{tp_hash} slot being set to
@ref{dff,,PyObject_HashNotImplemented()}.

@strong{继承：}

Group: @code{tp_hash}, @code{tp_richcompare}

This field is inherited by subtypes together with
@ref{3db8,,tp_richcompare}: a subtype inherits both of
@ref{3db8,,tp_richcompare} and @ref{3dbe,,tp_hash}, when the subtype's
@ref{3db8,,tp_richcompare} and @ref{3dbe,,tp_hash} are both @code{NULL}.
@end deffn

@geindex PyTypeObject.tp_call (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_call}@anchor{3dbf}
@deffn {C 成员} ternaryfunc PyTypeObject.tp_call

An optional pointer to a function that implements calling the object.  This
should be @code{NULL} if the object is not callable.  The signature is the same as
for @ref{23d,,PyObject_Call()}:

@example
PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);
@end example

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_str (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_str}@anchor{3daf}
@deffn {C 成员} reprfunc PyTypeObject.tp_str

An optional pointer to a function that implements the built-in operation
@ref{206,,str()}.  (Note that @ref{206,,str} is a type now, and @ref{206,,str()} calls the
constructor for that type.  This constructor calls @ref{a53,,PyObject_Str()} to do
the actual work, and @ref{a53,,PyObject_Str()} will call this handler.)

The signature is the same as for @ref{a53,,PyObject_Str()}:

@example
PyObject *tp_str(PyObject *self);
@end example

The function must return a string or a Unicode object.  It should be a "friendly" string
representation of the object, as this is the representation that will be used,
among other things, by the @ref{97a,,print()} function.

@strong{继承：}

此字段会被子类型继承。

@strong{默认：}

When this field is not set, @ref{a52,,PyObject_Repr()} is called to return a string
representation.
@end deffn

@geindex PyTypeObject.tp_getattro (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_getattro}@anchor{3db2}
@deffn {C 成员} getattrofunc PyTypeObject.tp_getattro

An optional pointer to the get-attribute function.

The signature is the same as for @ref{3efd,,PyObject_GetAttr()}:

@example
PyObject *tp_getattro(PyObject *self, PyObject *attr);
@end example

It is usually convenient to set this field to @ref{3eff,,PyObject_GenericGetAttr()},
which implements the normal way of looking for object attributes.

@strong{继承：}

分组: @code{tp_getattr}, @code{tp_getattro}

This field is inherited by subtypes together with @ref{3db5,,tp_getattr}: a subtype
inherits both @ref{3db5,,tp_getattr} and @ref{3db2,,tp_getattro} from its base type when
the subtype's @ref{3db5,,tp_getattr} and @ref{3db2,,tp_getattro} are both @code{NULL}.

@strong{默认：}

@code{PyBaseObject_Type} uses @ref{3eff,,PyObject_GenericGetAttr()}.
@end deffn

@geindex PyTypeObject.tp_setattro (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_setattro}@anchor{3db3}
@deffn {C 成员} setattrofunc PyTypeObject.tp_setattro

An optional pointer to the function for setting and deleting attributes.

The signature is the same as for @ref{3f00,,PyObject_SetAttr()}:

@example
int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
@end example

In addition, setting @emph{value} to @code{NULL} to delete an attribute must be
supported.  It is usually convenient to set this field to
@ref{3f04,,PyObject_GenericSetAttr()}, which implements the normal
way of setting object attributes.

@strong{继承：}

Group: @code{tp_setattr}, @code{tp_setattro}

This field is inherited by subtypes together with @ref{3db6,,tp_setattr}: a subtype
inherits both @ref{3db6,,tp_setattr} and @ref{3db3,,tp_setattro} from its base type when
the subtype's @ref{3db6,,tp_setattr} and @ref{3db3,,tp_setattro} are both @code{NULL}.

@strong{默认：}

@code{PyBaseObject_Type} 使用 @ref{3f04,,PyObject_GenericSetAttr()}.
@end deffn

@geindex PyTypeObject.tp_as_buffer (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_as_buffer}@anchor{26e}
@deffn {C 成员} PyBufferProcs* PyTypeObject.tp_as_buffer

Pointer to an additional structure that contains fields relevant only to objects
which implement the buffer interface.  These fields are documented in
@ref{3f75,,Buffer Object Structures}.

@strong{继承：}

The @ref{26e,,tp_as_buffer} field is not inherited,
but the contained fields are inherited individually.
@end deffn

@geindex PyTypeObject.tp_flags (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_flags}@anchor{105b}
@deffn {C 成员} unsigned long PyTypeObject.tp_flags

This field is a bit mask of various flags.  Some flags indicate variant
semantics for certain situations; others are used to indicate that certain
fields in the type object (or in the extension structures referenced via
@ref{270,,tp_as_number}, @ref{42a5,,tp_as_sequence}, @ref{42a6,,tp_as_mapping}, and
@ref{26e,,tp_as_buffer}) that were historically not always present are valid; if
such a flag bit is clear, the type fields it guards must not be accessed and
must be considered to have a zero or @code{NULL} value instead.

@strong{继承：}

Inheritance of this field is complicated.  Most flag bits are inherited
individually, i.e. if the base type has a flag bit set, the subtype inherits
this flag bit.  The flag bits that pertain to extension structures are strictly
inherited if the extension structure is inherited, i.e. the base type's value of
the flag bit is copied into the subtype together with a pointer to the extension
structure.  The @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is inherited together with
the @ref{23c,,tp_traverse} and @ref{3dab,,tp_clear} fields, i.e. if the
@ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is clear in the subtype and the
@ref{23c,,tp_traverse} and @ref{3dab,,tp_clear} fields in the subtype exist and have
@code{NULL} values.

@c XXX are most flag bits *really* inherited individually?

@strong{默认：}

@code{PyBaseObject_Type} uses
@code{Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE}.

@strong{Bit Masks:}

The following bit masks are currently defined; these can be ORed together using
the @code{|} operator to form the value of the @ref{105b,,tp_flags} field.  The macro
@ref{105a,,PyType_HasFeature()} takes a type and a flags value, @emph{tp} and @emph{f}, and
checks whether @code{tp->tp_flags & f} is non-zero.

@geindex Py_TPFLAGS_HEAPTYPE (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_HEAPTYPE}@anchor{3fbd}
@deffn {数据} Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap, for
example, types created dynamically using @ref{23b,,PyType_FromSpec()}.  In this
case, the @code{ob_type} field of its instances is considered a reference to
the type, and the type object is INCREF'ed when a new instance is created, and
DECREF'ed when an instance is destroyed (this does not apply to instances of
subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
DECREF'ed).

@strong{继承：}

？？？
@end deffn

@geindex Py_TPFLAGS_BASETYPE (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_BASETYPE}@anchor{3d9b}
@deffn {数据} Py_TPFLAGS_BASETYPE

This bit is set when the type can be used as the base type of another type.  If
this bit is clear, the type cannot be subtyped (similar to a "final" class in
Java).

@strong{继承：}

？？？
@end deffn

@geindex Py_TPFLAGS_READY (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_READY}@anchor{4306}
@deffn {数据} Py_TPFLAGS_READY

This bit is set when the type object has been fully initialized by
@ref{3d96,,PyType_Ready()}.

@strong{继承：}

？？？
@end deffn

@geindex Py_TPFLAGS_READYING (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_READYING}@anchor{4307}
@deffn {数据} Py_TPFLAGS_READYING

This bit is set while @ref{3d96,,PyType_Ready()} is in the process of initializing
the type object.

@strong{继承：}

？？？
@end deffn

@geindex Py_TPFLAGS_HAVE_GC (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_HAVE_GC}@anchor{3da1}
@deffn {数据} Py_TPFLAGS_HAVE_GC

This bit is set when the object supports garbage collection.  If this bit
is set, instances must be created using @ref{3fc,,PyObject_GC_New()} and
destroyed using @ref{f0d,,PyObject_GC_Del()}.  More information in section
@ref{4308,,使对象类型支持循环垃圾回收}.  This bit also implies that the
GC-related fields @ref{23c,,tp_traverse} and @ref{3dab,,tp_clear} are present in
the type object.

@strong{继承：}

Group: @ref{3da1,,Py_TPFLAGS_HAVE_GC}, @code{tp_traverse}, @code{tp_clear}

The @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is inherited
together with the @code{tp_traverse} and @code{tp_clear}
fields, i.e.  if the @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is
clear in the subtype and the @code{tp_traverse} and
@code{tp_clear} fields in the subtype exist and have @code{NULL}
values.
@end deffn

@geindex Py_TPFLAGS_DEFAULT (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_DEFAULT}@anchor{3d8e}
@deffn {数据} Py_TPFLAGS_DEFAULT

This is a bitmask of all the bits that pertain to the existence of certain
fields in the type object and its extension structures. Currently, it includes
the following bits: @code{Py_TPFLAGS_HAVE_STACKLESS_EXTENSION},
@code{Py_TPFLAGS_HAVE_VERSION_TAG}.

@strong{继承：}

？？？
@end deffn

@geindex Py_TPFLAGS_METHOD_DESCRIPTOR (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_METHOD_DESCRIPTOR}@anchor{3f28}
@deffn {数据} Py_TPFLAGS_METHOD_DESCRIPTOR

This bit indicates that objects behave like unbound methods.

If this flag is set for @code{type(meth)}, then:


@itemize -

@item 
@code{meth.__get__(obj, cls)(*args, **kwds)} (with @code{obj} not None)
must be equivalent to @code{meth(obj, *args, **kwds)}.

@item 
@code{meth.__get__(None, cls)(*args, **kwds)}
must be equivalent to @code{meth(*args, **kwds)}.
@end itemize

This flag enables an optimization for typical method calls like
@code{obj.meth()}: it avoids creating a temporary "bound method" object for
@code{obj.meth}.


3.8 新版功能.


@strong{继承：}

This flag is never inherited by heap types.
For extension types, it is inherited whenever
@ref{42b0,,tp_descr_get} is inherited.
@end deffn

@c XXX Document more flags here?

@geindex Py_TPFLAGS_LONG_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_LONG_SUBCLASS}@anchor{4309}
@deffn {数据} Py_TPFLAGS_LONG_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_LIST_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_LIST_SUBCLASS}@anchor{430a}
@deffn {数据} Py_TPFLAGS_LIST_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_TUPLE_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_TUPLE_SUBCLASS}@anchor{430b}
@deffn {数据} Py_TPFLAGS_TUPLE_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_BYTES_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_BYTES_SUBCLASS}@anchor{430c}
@deffn {数据} Py_TPFLAGS_BYTES_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_UNICODE_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_UNICODE_SUBCLASS}@anchor{430d}
@deffn {数据} Py_TPFLAGS_UNICODE_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_DICT_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_DICT_SUBCLASS}@anchor{430e}
@deffn {数据} Py_TPFLAGS_DICT_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_BASE_EXC_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_BASE_EXC_SUBCLASS}@anchor{430f}
@deffn {数据} Py_TPFLAGS_BASE_EXC_SUBCLASS
@end deffn

@geindex Py_TPFLAGS_TYPE_SUBCLASS (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_TYPE_SUBCLASS}@anchor{4310}
@deffn {数据} Py_TPFLAGS_TYPE_SUBCLASS

These flags are used by functions such as
@ref{3fde,,PyLong_Check()} to quickly determine if a type is a subclass
of a built-in type; such specific checks are faster than a generic
check, like @ref{896,,PyObject_IsInstance()}. Custom types that inherit
from built-ins should have their @ref{105b,,tp_flags}
set appropriately, or the code that interacts with such types
will behave differently depending on what kind of check is used.
@end deffn

@geindex Py_TPFLAGS_HAVE_FINALIZE (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_HAVE_FINALIZE}@anchor{400}
@deffn {数据} Py_TPFLAGS_HAVE_FINALIZE

This bit is set when the @ref{3ff,,tp_finalize} slot is present in the
type structure.


3.4 新版功能.



3.8 版后已移除: This flag isn't necessary anymore, as the interpreter assumes the
@ref{3ff,,tp_finalize} slot is always present in the
type structure.

@end deffn

@geindex Py_TPFLAGS_HAVE_VECTORCALL (內置变量)
@anchor{c-api/typeobj Py_TPFLAGS_HAVE_VECTORCALL}@anchor{3f18}
@deffn {数据} Py_TPFLAGS_HAVE_VECTORCALL

This bit is set when the class implements
the @ref{2bf,,vectorcall protocol}.
See @ref{3f19,,tp_vectorcall_offset} for details.

@strong{继承：}

This bit is inherited for @emph{static} subtypes if
@ref{3dbf,,tp_call} is also inherited.
@ref{4301,,Heap types} do not inherit @code{Py_TPFLAGS_HAVE_VECTORCALL}.


3.9 新版功能.

@end deffn
@end deffn

@geindex PyTypeObject.tp_doc (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_doc}@anchor{3d8f}
@deffn {C 成员} const char* PyTypeObject.tp_doc

An optional pointer to a NUL-terminated C string giving the docstring for this
type object.  This is exposed as the @code{__doc__} attribute on the type and
instances of the type.

@strong{继承：}

This field is @emph{not} inherited by subtypes.
@end deffn

@geindex PyTypeObject.tp_traverse (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_traverse}@anchor{23c}
@deffn {C 成员} traverseproc PyTypeObject.tp_traverse

An optional pointer to a traversal function for the garbage collector.  This is
only used if the @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is set.  The signature is:

@example
int tp_traverse(PyObject *self, visitproc visit, void *arg);
@end example

More information about Python's garbage collection scheme can be found
in section @ref{4308,,使对象类型支持循环垃圾回收}.

The @ref{23c,,tp_traverse} pointer is used by the garbage collector to detect
reference cycles. A typical implementation of a @ref{23c,,tp_traverse} function
simply calls @ref{3d9f,,Py_VISIT()} on each of the instance's members that are Python
objects that the instance owns. For example, this is function @code{local_traverse()} from the
@ref{2,,_thread} extension module:

@example
static int
local_traverse(localobject *self, visitproc visit, void *arg)
@{
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
@}
@end example

Note that @ref{3d9f,,Py_VISIT()} is called only on those members that can participate
in reference cycles.  Although there is also a @code{self->key} member, it can only
be @code{NULL} or a Python string and therefore cannot be part of a reference cycle.

On the other hand, even if you know a member can never be part of a cycle, as a
debugging aid you may want to visit it anyway just so the @ref{84,,gc} module's
@ref{1002,,get_referents()} function will include it.

@cartouche
@quotation 警告 
When implementing @ref{23c,,tp_traverse}, only the members
that the instance @emph{owns} (by having strong references to them) must be
visited. For instance, if an object supports weak references via the
@ref{3fcd,,tp_weaklist} slot, the pointer supporting
the linked list (what @emph{tp_weaklist} points to) must @strong{not} be
visited as the instance does not directly own the weak references to itself
(the weakreference list is there to support the weak reference machinery,
but the instance has no strong reference to the elements inside it, as they
are allowed to be removed even if the instance is still alive).
@end quotation
@end cartouche

Note that @ref{3d9f,,Py_VISIT()} requires the @emph{visit} and @emph{arg} parameters to
@code{local_traverse()} to have these specific names; don't name them just
anything.

Heap-allocated types (@ref{3fbd,,Py_TPFLAGS_HEAPTYPE}, such as those created
with @ref{23b,,PyType_FromSpec()} and similar APIs) hold a reference to their
type. Their traversal function must therefore either visit
@ref{3d8b,,Py_TYPE(self)}, or delegate this responsibility by
calling @code{tp_traverse} of another heap-allocated type (such as a
heap-allocated superclass).
If they do not, the type object may not be garbage-collected.


在 3.9 版更改: Heap-allocated types are expected to visit @code{Py_TYPE(self)} in
@code{tp_traverse}.  In earlier versions of Python, due to
bug 40217@footnote{https://bugs.python.org/issue40217}, doing this
may lead to crashes in subclasses.


@strong{继承：}

Group: @ref{3da1,,Py_TPFLAGS_HAVE_GC}, @code{tp_traverse}, @code{tp_clear}

This field is inherited by subtypes together with @ref{3dab,,tp_clear} and the
@ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit: the flag bit, @ref{23c,,tp_traverse}, and
@ref{3dab,,tp_clear} are all inherited from the base type if they are all zero in
the subtype.
@end deffn

@geindex PyTypeObject.tp_clear (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_clear}@anchor{3dab}
@deffn {C 成员} inquiry PyTypeObject.tp_clear

An optional pointer to a clear function for the garbage collector. This is only
used if the @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit is set.  The signature is:

@example
int tp_clear(PyObject *);
@end example

The @ref{3dab,,tp_clear} member function is used to break reference cycles in cyclic
garbage detected by the garbage collector.  Taken together, all @ref{3dab,,tp_clear}
functions in the system must combine to break all reference cycles.  This is
subtle, and if in any doubt supply a @ref{3dab,,tp_clear} function.  For example,
the tuple type does not implement a @ref{3dab,,tp_clear} function, because it's
possible to prove that no reference cycle can be composed entirely of tuples.
Therefore the @ref{3dab,,tp_clear} functions of other types must be sufficient to
break any cycle containing a tuple.  This isn't immediately obvious, and there's
rarely a good reason to avoid implementing @ref{3dab,,tp_clear}.

Implementations of @ref{3dab,,tp_clear} should drop the instance's references to
those of its members that may be Python objects, and set its pointers to those
members to @code{NULL}, as in the following example:

@example
static int
local_clear(localobject *self)
@{
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
@}
@end example

The @ref{3da0,,Py_CLEAR()} macro should be used, because clearing references is
delicate:  the reference to the contained object must not be decremented until
after the pointer to the contained object is set to @code{NULL}.  This is because
decrementing the reference count may cause the contained object to become trash,
triggering a chain of reclamation activity that may include invoking arbitrary
Python code (due to finalizers, or weakref callbacks, associated with the
contained object). If it's possible for such code to reference @emph{self} again,
it's important that the pointer to the contained object be @code{NULL} at that time,
so that @emph{self} knows the contained object can no longer be used.  The
@ref{3da0,,Py_CLEAR()} macro performs the operations in a safe order.

Note that @ref{3dab,,tp_clear} is not @emph{always} called
before an instance is deallocated. For example, when reference counting
is enough to determine that an object is no longer used, the cyclic garbage
collector is not involved and @ref{3d93,,tp_dealloc} is
called directly.

Because the goal of @ref{3dab,,tp_clear} functions is to break reference cycles,
it's not necessary to clear contained objects like Python strings or Python
integers, which can't participate in reference cycles. On the other hand, it may
be convenient to clear all contained Python objects, and write the type's
@ref{3d93,,tp_dealloc} function to invoke @ref{3dab,,tp_clear}.

More information about Python's garbage collection scheme can be found in
section @ref{4308,,使对象类型支持循环垃圾回收}.

@strong{继承：}

Group: @ref{3da1,,Py_TPFLAGS_HAVE_GC}, @code{tp_traverse}, @code{tp_clear}

This field is inherited by subtypes together with @ref{23c,,tp_traverse} and the
@ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit: the flag bit, @ref{23c,,tp_traverse}, and
@ref{3dab,,tp_clear} are all inherited from the base type if they are all zero in
the subtype.
@end deffn

@geindex PyTypeObject.tp_richcompare (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_richcompare}@anchor{3db8}
@deffn {C 成员} richcmpfunc PyTypeObject.tp_richcompare

An optional pointer to the rich comparison function, whose signature is:

@example
PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
@end example

The first parameter is guaranteed to be an instance of the type
that is defined by @ref{3fe,,PyTypeObject}.

The function should return the result of the comparison (usually @code{Py_True}
or @code{Py_False}).  If the comparison is undefined, it must return
@code{Py_NotImplemented}, if another error occurred it must return @code{NULL} and
set an exception condition.

The following constants are defined to be used as the third argument for
@ref{3db8,,tp_richcompare} and for @ref{3db9,,PyObject_RichCompare()}:


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
@headitem

常数

@tab

对照

@item

@code{Py_LT}

@tab

@code{<}

@item

@code{Py_LE}

@tab

@code{<=}

@item

@code{Py_EQ}

@tab

@code{==}

@item

@code{Py_NE}

@tab

@code{!=}

@item

@code{Py_GT}

@tab

@code{>}

@item

@code{Py_GE}

@tab

@code{>=}

@end multitable


定义以下宏是为了简化编写丰富的比较函数：

@geindex Py_RETURN_RICHCOMPARE (C 宏)
@anchor{c-api/typeobj c Py_RETURN_RICHCOMPARE}@anchor{52e}
@deffn {C 宏} Py_RETURN_RICHCOMPARE (VAL_A, VAL_B, op)

Return @code{Py_True} or @code{Py_False} from the function, depending on the
result of a comparison.
VAL_A and VAL_B must be orderable by C comparison operators (for example,
they may be C ints or floats). The third argument specifies the requested
operation, as for @ref{3db9,,PyObject_RichCompare()}.

The return value's reference count is properly incremented.

On error, sets an exception and returns @code{NULL} from the function.


3.7 新版功能.

@end deffn

@strong{继承：}

Group: @code{tp_hash}, @code{tp_richcompare}

This field is inherited by subtypes together with @ref{3dbe,,tp_hash}:
a subtype inherits @ref{3db8,,tp_richcompare} and @ref{3dbe,,tp_hash} when
the subtype's @ref{3db8,,tp_richcompare} and @ref{3dbe,,tp_hash} are both
@code{NULL}.

@strong{默认：}

@code{PyBaseObject_Type} provides a @code{tp_richcompare}
implementation, which may be inherited.  However, if only
@code{tp_hash} is defined, not even the inherited function is used
and instances of the type will not be able to participate in any
comparisons.
@end deffn

@geindex PyTypeObject.tp_weaklistoffset (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_weaklistoffset}@anchor{26c}
@deffn {C 成员} Py_ssize_t PyTypeObject.tp_weaklistoffset

If the instances of this type are weakly referenceable, this field is greater
than zero and contains the offset in the instance structure of the weak
reference list head (ignoring the GC header, if present); this offset is used by
@code{PyObject_ClearWeakRefs()} and the @code{PyWeakref_*()} functions.  The
instance structure needs to include a field of type @ref{5bd,,PyObject*} which is
initialized to @code{NULL}.

Do not confuse this field with @ref{3fcd,,tp_weaklist}; that is the list head for
weak references to the type object itself.

@strong{继承：}

This field is inherited by subtypes, but see the rules listed below. A subtype
may override this offset; this means that the subtype uses a different weak
reference list head than the base type.  Since the list head is always found via
@ref{26c,,tp_weaklistoffset}, this should not be a problem.

When a type defined by a class statement has no @ref{ef7,,__slots__} declaration,
and none of its base types are weakly referenceable, the type is made weakly
referenceable by adding a weak reference list head slot to the instance layout
and setting the @ref{26c,,tp_weaklistoffset} of that slot's offset.

When a type's @ref{ef7,,__slots__} declaration contains a slot named
@code{__weakref__}, that slot becomes the weak reference list head for
instances of the type, and the slot's offset is stored in the type's
@ref{26c,,tp_weaklistoffset}.

When a type's @ref{ef7,,__slots__} declaration does not contain a slot named
@code{__weakref__}, the type inherits its @ref{26c,,tp_weaklistoffset} from its
base type.
@end deffn

@geindex PyTypeObject.tp_iter (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_iter}@anchor{efa}
@deffn {C 成员} getiterfunc PyTypeObject.tp_iter

An optional pointer to a function that returns an iterator for the object.  Its
presence normally signals that the instances of this type are iterable (although
sequences may be iterable without this function).

This function has the same signature as @ref{3f11,,PyObject_GetIter()}:

@example
PyObject *tp_iter(PyObject *self);
@end example

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_iternext (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_iternext}@anchor{efb}
@deffn {C 成员} iternextfunc PyTypeObject.tp_iternext

An optional pointer to a function that returns the next item in an iterator.
The signature is:

@example
PyObject *tp_iternext(PyObject *self);
@end example

When the iterator is exhausted, it must return @code{NULL}; a @ref{58a,,StopIteration}
exception may or may not be set.  When another error occurs, it must return
@code{NULL} too.  Its presence signals that the instances of this type are
iterators.

Iterator types should also define the @ref{efa,,tp_iter} function, and that
function should return the iterator instance itself (not a new iterator
instance).

This function has the same signature as @ref{3f72,,PyIter_Next()}.

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_methods (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_methods}@anchor{3d9a}
@deffn {C 成员} struct PyMethodDef* PyTypeObject.tp_methods

An optional pointer to a static @code{NULL}-terminated array of @ref{ee5,,PyMethodDef}
structures, declaring regular methods of this type.

For each entry in the array, an entry is added to the type's dictionary (see
@ref{3fc9,,tp_dict} below) containing a method descriptor.

@strong{继承：}

This field is not inherited by subtypes (methods are inherited through a
different mechanism).
@end deffn

@geindex PyTypeObject.tp_members (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_members}@anchor{3d98}
@deffn {C 成员} struct PyMemberDef* PyTypeObject.tp_members

An optional pointer to a static @code{NULL}-terminated array of @ref{532,,PyMemberDef}
structures, declaring regular data members (fields or slots) of instances of
this type.

For each entry in the array, an entry is added to the type's dictionary (see
@ref{3fc9,,tp_dict} below) containing a member descriptor.

@strong{继承：}

This field is not inherited by subtypes (members are inherited through a
different mechanism).
@end deffn

@geindex PyTypeObject.tp_getset (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_getset}@anchor{3d9d}
@deffn {C 成员} struct PyGetSetDef* PyTypeObject.tp_getset

An optional pointer to a static @code{NULL}-terminated array of @ref{533,,PyGetSetDef}
structures, declaring computed attributes of instances of this type.

For each entry in the array, an entry is added to the type's dictionary (see
@ref{3fc9,,tp_dict} below) containing a getset descriptor.

@strong{继承：}

This field is not inherited by subtypes (computed attributes are inherited
through a different mechanism).
@end deffn

@geindex PyTypeObject.tp_base (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_base}@anchor{3da3}
@deffn {C 成员} PyTypeObject* PyTypeObject.tp_base

An optional pointer to a base type from which type properties are inherited.  At
this level, only single inheritance is supported; multiple inheritance require
dynamically creating a type object by calling the metatype.

@cartouche
@quotation 注解 
@c from Modules/xxmodule.c

Slot initialization is subject to the rules of initializing globals.
C99 requires the initializers to be "address constants".  Function
designators like @ref{3d91,,PyType_GenericNew()}, with implicit conversion
to a pointer, are valid C99 address constants.

However, the unary '&' operator applied to a non-static variable
like @code{PyBaseObject_Type()} is not required to produce an address
constant.  Compilers may support this (gcc does), MSVC does not.
Both compilers are strictly standard conforming in this particular
behavior.

Consequently, @ref{3da3,,tp_base} should be set in
the extension module's init function.
@end quotation
@end cartouche

@strong{继承：}

This field is not inherited by subtypes (obviously).

@strong{默认：}

This field defaults to @code{&PyBaseObject_Type} (which to Python
programmers is known as the type @ref{3da,,object}).
@end deffn

@geindex PyTypeObject.tp_dict (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_dict}@anchor{3fc9}
@deffn {C 成员} PyObject* PyTypeObject.tp_dict

The type's dictionary is stored here by @ref{3d96,,PyType_Ready()}.

This field should normally be initialized to @code{NULL} before PyType_Ready is
called; it may also be initialized to a dictionary containing initial attributes
for the type.  Once @ref{3d96,,PyType_Ready()} has initialized the type, extra
attributes for the type may be added to this dictionary only if they don't
correspond to overloaded operations (like @ref{15c4,,__add__()}).

@strong{继承：}

This field is not inherited by subtypes (though the attributes defined in here
are inherited through a different mechanism).

@strong{默认：}

If this field is @code{NULL}, @ref{3d96,,PyType_Ready()} will assign a new
dictionary to it.

@cartouche
@quotation 警告 
It is not safe to use @ref{3d7a,,PyDict_SetItem()} on or otherwise modify
@ref{3fc9,,tp_dict} with the dictionary C-API.
@end quotation
@end cartouche
@end deffn

@geindex PyTypeObject.tp_descr_get (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_descr_get}@anchor{42b0}
@deffn {C 成员} descrgetfunc PyTypeObject.tp_descr_get

An optional pointer to a "descriptor get" function.

The function signature is:

@example
PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
@end example

@c XXX explain more?

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_descr_set (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_descr_set}@anchor{42b2}
@deffn {C 成员} descrsetfunc PyTypeObject.tp_descr_set

An optional pointer to a function for setting and deleting
a descriptor's value.

The function signature is:

@example
int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
@end example

The @emph{value} argument is set to @code{NULL} to delete the value.

@c XXX explain more?

@strong{继承：}

此字段会被子类型继承。
@end deffn

@geindex PyTypeObject.tp_dictoffset (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_dictoffset}@anchor{3fd0}
@deffn {C 成员} Py_ssize_t PyTypeObject.tp_dictoffset

If the instances of this type have a dictionary containing instance variables,
this field is non-zero and contains the offset in the instances of the type of
the instance variable dictionary; this offset is used by
@ref{3eff,,PyObject_GenericGetAttr()}.

Do not confuse this field with @ref{3fc9,,tp_dict}; that is the dictionary for
attributes of the type object itself.

If the value of this field is greater than zero, it specifies the offset from
the start of the instance structure.  If the value is less than zero, it
specifies the offset from the @emph{end} of the instance structure.  A negative
offset is more expensive to use, and should only be used when the instance
structure contains a variable-length part.  This is used for example to add an
instance variable dictionary to subtypes of @ref{206,,str} or @ref{1a2,,tuple}. Note
that the @ref{26b,,tp_basicsize} field should account for the dictionary added to
the end in that case, even though the dictionary is not included in the basic
object layout.  On a system with a pointer size of 4 bytes,
@ref{3fd0,,tp_dictoffset} should be set to @code{-4} to indicate that the dictionary is
at the very end of the structure.

The real dictionary offset in an instance can be computed from a negative
@ref{3fd0,,tp_dictoffset} as follows:

@example
dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
if dictoffset is not aligned on sizeof(void*):
    round up to sizeof(void*)
@end example

where @ref{26b,,tp_basicsize}, @ref{3d8d,,tp_itemsize} and @ref{3fd0,,tp_dictoffset} are
taken from the type object, and @code{ob_size} is taken from the instance.  The
absolute value is taken because ints use the sign of @code{ob_size} to
store the sign of the number.  (There's never a need to do this calculation
yourself; it is done for you by @code{_PyObject_GetDictPtr()}.)

@strong{继承：}

This field is inherited by subtypes, but see the rules listed below. A subtype
may override this offset; this means that the subtype instances store the
dictionary at a difference offset than the base type.  Since the dictionary is
always found via @ref{3fd0,,tp_dictoffset}, this should not be a problem.

When a type defined by a class statement has no @ref{ef7,,__slots__} declaration,
and none of its base types has an instance variable dictionary, a dictionary
slot is added to the instance layout and the @ref{3fd0,,tp_dictoffset} is set to
that slot's offset.

When a type defined by a class statement has a @ref{ef7,,__slots__} declaration,
the type inherits its @ref{3fd0,,tp_dictoffset} from its base type.

(Adding a slot named @ref{5fe,,__dict__} to the @ref{ef7,,__slots__} declaration does
not have the expected effect, it just causes confusion.  Maybe this should be
added as a feature just like @code{__weakref__} though.)

@strong{默认：}

This slot has no default.  For static types, if the field is
@code{NULL} then no @ref{5fe,,__dict__} gets created for instances.
@end deffn

@geindex PyTypeObject.tp_init (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_init}@anchor{3d97}
@deffn {C 成员} initproc PyTypeObject.tp_init

An optional pointer to an instance initialization function.

This function corresponds to the @ref{e2b,,__init__()} method of classes.  Like
@ref{e2b,,__init__()}, it is possible to create an instance without calling
@ref{e2b,,__init__()}, and it is possible to reinitialize an instance by calling its
@ref{e2b,,__init__()} method again.

The function signature is:

@example
int tp_init(PyObject *self, PyObject *args, PyObject *kwds);
@end example

The self argument is the instance to be initialized; the @emph{args} and @emph{kwds}
arguments represent positional and keyword arguments of the call to
@ref{e2b,,__init__()}.

The @ref{3d97,,tp_init} function, if not @code{NULL}, is called when an instance is
created normally by calling its type, after the type's @ref{3d90,,tp_new} function
has returned an instance of the type.  If the @ref{3d90,,tp_new} function returns an
instance of some other type that is not a subtype of the original type, no
@ref{3d97,,tp_init} function is called; if @ref{3d90,,tp_new} returns an instance of a
subtype of the original type, the subtype's @ref{3d97,,tp_init} is called.

Returns @code{0} on success, @code{-1} and sets an exception on error.

@strong{继承：}

此字段会被子类型继承。

@strong{默认：}

For static types this field does not have a default.
@end deffn

@geindex PyTypeObject.tp_alloc (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_alloc}@anchor{3d95}
@deffn {C 成员} allocfunc PyTypeObject.tp_alloc

An optional pointer to an instance allocation function.

The function signature is:

@example
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
@end example

@strong{继承：}

This field is inherited by static subtypes, but not by dynamic
subtypes (subtypes created by a class statement).

@strong{默认：}

For dynamic subtypes, this field is always set to
@ref{3a1,,PyType_GenericAlloc()}, to force a standard heap
allocation strategy.

For static subtypes, @code{PyBaseObject_Type} uses
@ref{3a1,,PyType_GenericAlloc()}.  That is the recommended value
for all statically defined types.
@end deffn

@geindex PyTypeObject.tp_new (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_new}@anchor{3d90}
@deffn {C 成员} newfunc PyTypeObject.tp_new

An optional pointer to an instance creation function.

The function signature is:

@example
PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
@end example

The @emph{subtype} argument is the type of the object being created; the @emph{args} and
@emph{kwds} arguments represent positional and keyword arguments of the call to the
type.  Note that @emph{subtype} doesn't have to equal the type whose @ref{3d90,,tp_new}
function is called; it may be a subtype of that type (but not an unrelated
type).

The @ref{3d90,,tp_new} function should call @code{subtype->tp_alloc(subtype, nitems)}
to allocate space for the object, and then do only as much further
initialization as is absolutely necessary.  Initialization that can safely be
ignored or repeated should be placed in the @ref{3d97,,tp_init} handler.  A good
rule of thumb is that for immutable types, all initialization should take place
in @ref{3d90,,tp_new}, while for mutable types, most initialization should be
deferred to @ref{3d97,,tp_init}.

@strong{继承：}

This field is inherited by subtypes, except it is not inherited by static types
whose @ref{3da3,,tp_base} is @code{NULL} or @code{&PyBaseObject_Type}.

@strong{默认：}

For static types this field has no default.  This means if the
slot is defined as @code{NULL}, the type cannot be called to create new
instances; presumably there is some other way to create
instances, like a factory function.
@end deffn

@geindex PyTypeObject.tp_free (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_free}@anchor{3d94}
@deffn {C 成员} freefunc PyTypeObject.tp_free

An optional pointer to an instance deallocation function.  Its signature is:

@example
void tp_free(void *self);
@end example

An initializer that is compatible with this signature is @ref{606,,PyObject_Free()}.

@strong{继承：}

This field is inherited by static subtypes, but not by dynamic
subtypes (subtypes created by a class statement)

@strong{默认：}

In dynamic subtypes, this field is set to a deallocator suitable to
match @ref{3a1,,PyType_GenericAlloc()} and the value of the
@ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit.

For static subtypes, @code{PyBaseObject_Type} uses PyObject_Del.
@end deffn

@geindex PyTypeObject.tp_is_gc (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_is_gc}@anchor{42b8}
@deffn {C 成员} inquiry PyTypeObject.tp_is_gc

An optional pointer to a function called by the garbage collector.

The garbage collector needs to know whether a particular object is collectible
or not.  Normally, it is sufficient to look at the object's type's
@ref{105b,,tp_flags} field, and check the @ref{3da1,,Py_TPFLAGS_HAVE_GC} flag bit.  But
some types have a mixture of statically and dynamically allocated instances, and
the statically allocated instances are not collectible.  Such types should
define this function; it should return @code{1} for a collectible instance, and
@code{0} for a non-collectible instance. The signature is:

@example
int tp_is_gc(PyObject *self);
@end example

(The only example of this are types themselves.  The metatype,
@ref{3fb6,,PyType_Type}, defines this function to distinguish between statically
and dynamically allocated types.)

@strong{继承：}

此字段会被子类型继承。

@strong{默认：}

This slot has no default.  If this field is @code{NULL},
@ref{3da1,,Py_TPFLAGS_HAVE_GC} is used as the functional equivalent.
@end deffn

@geindex PyTypeObject.tp_bases (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_bases}@anchor{42b9}
@deffn {C 成员} PyObject* PyTypeObject.tp_bases

Tuple of base types.

This is set for types created by a class statement.  It should be @code{NULL} for
statically defined types.

@strong{继承：}

This field is not inherited.
@end deffn

@geindex PyTypeObject.tp_mro (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_mro}@anchor{3fca}
@deffn {C 成员} PyObject* PyTypeObject.tp_mro

Tuple containing the expanded set of base types, starting with the type itself
and ending with @ref{3da,,object}, in Method Resolution Order.

@strong{继承：}

This field is not inherited; it is calculated fresh by
@ref{3d96,,PyType_Ready()}.
@end deffn

@geindex PyTypeObject.tp_cache (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_cache}@anchor{3fcb}
@deffn {C 成员} PyObject* PyTypeObject.tp_cache

Unused.  Internal use only.

@strong{继承：}

This field is not inherited.
@end deffn

@geindex PyTypeObject.tp_subclasses (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_subclasses}@anchor{3fcc}
@deffn {C 成员} PyObject* PyTypeObject.tp_subclasses

List of weak references to subclasses.  Internal use only.

@strong{继承：}

This field is not inherited.
@end deffn

@geindex PyTypeObject.tp_weaklist (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_weaklist}@anchor{3fcd}
@deffn {C 成员} PyObject* PyTypeObject.tp_weaklist

Weak reference list head, for weak references to this type object.  Not
inherited.  Internal use only.

@strong{继承：}

This field is not inherited.
@end deffn

@geindex PyTypeObject.tp_del (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_del}@anchor{42ba}
@deffn {C 成员} destructor PyTypeObject.tp_del

This field is deprecated.  Use @ref{3ff,,tp_finalize} instead.
@end deffn

@geindex PyTypeObject.tp_version_tag (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_version_tag}@anchor{42bb}
@deffn {C 成员} unsigned int PyTypeObject.tp_version_tag

Used to index into the method cache.  Internal use only.

@strong{继承：}

This field is not inherited.
@end deffn

@geindex PyTypeObject.tp_finalize (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_finalize}@anchor{3ff}
@deffn {C 成员} destructor PyTypeObject.tp_finalize

An optional pointer to an instance finalization function.  Its signature is:

@example
void tp_finalize(PyObject *self);
@end example

If @ref{3ff,,tp_finalize} is set, the interpreter calls it once when
finalizing an instance.  It is called either from the garbage
collector (if the instance is part of an isolated reference cycle) or
just before the object is deallocated.  Either way, it is guaranteed
to be called before attempting to break reference cycles, ensuring
that it finds the object in a sane state.

@ref{3ff,,tp_finalize} should not mutate the current exception status;
therefore, a recommended way to write a non-trivial finalizer is:

@example
static void
local_finalize(PyObject *self)
@{
    PyObject *error_type, *error_value, *error_traceback;

    /* Save the current exception, if any. */
    PyErr_Fetch(&error_type, &error_value, &error_traceback);

    /* ... */

    /* Restore the saved exception. */
    PyErr_Restore(error_type, error_value, error_traceback);
@}
@end example

For this field to be taken into account (even through inheritance),
you must also set the @ref{400,,Py_TPFLAGS_HAVE_FINALIZE} flags bit.

Also, note that, in a garbage collected Python,
@ref{3d93,,tp_dealloc} may be called from
any Python thread, not just the thread which created the object (if the object
becomes part of a refcount cycle, that cycle might be collected by a garbage
collection on any thread).  This is not a problem for Python API calls, since
the thread on which tp_dealloc is called will own the Global Interpreter Lock
(GIL). However, if the object being destroyed in turn destroys objects from some
other C or C++ library, care should be taken to ensure that destroying those
objects on the thread which called tp_dealloc will not violate any assumptions
of the library.

@strong{继承：}

此字段会被子类型继承。


3.4 新版功能.



@subsubheading 参见


"Safe object finalization" (
@geindex Python 提高建议; PEP 442
PEP 442@footnote{https://www.python.org/dev/peps/pep-0442})

@end deffn

@geindex PyTypeObject.tp_vectorcall (C 成员)
@anchor{c-api/typeobj c PyTypeObject tp_vectorcall}@anchor{3fce}
@deffn {C 成员} vectorcallfunc PyTypeObject.tp_vectorcall

Vectorcall function to use for calls of this type object.
In other words, it is used to implement
@ref{2bf,,vectorcall} for @code{type.__call__}.
If @code{tp_vectorcall} is @code{NULL}, the default call implementation
using @ref{97d,,__new__} and @ref{e2b,,__init__} is used.

@strong{继承：}

This field is never inherited.


3.9 新版功能: (the field exists since 3.8 but it's only used since 3.9)

@end deffn

@node Heap Types,,PyTypeObject 槽,Type 对象<2>
@anchor{c-api/typeobj heap-types}@anchor{3fbc}@anchor{c-api/typeobj id4}@anchor{4301}
@subsubsection Heap Types


Traditionally, types defined in C code are @emph{static}, that is,
a static @ref{3fe,,PyTypeObject} structure is defined directly in code
and initialized using @ref{3d96,,PyType_Ready()}.

This results in types that are limited relative to types defined in Python:


@itemize *

@item 
Static types are limited to one base, i.e. they cannot use multiple
inheritance.

@item 
Static type objects (but not necessarily their instances) are immutable.
It is not possible to add or modify the type object's attributes from Python.

@item 
Static type objects are shared across
@ref{3e90,,sub-interpreters}, so they should not
include any subinterpreter-specific state.
@end itemize

Also, since @ref{3fe,,PyTypeObject} is not part of the @ref{3e13,,stable ABI},
any extension modules using static types must be compiled for a specific
Python minor version.

An alternative to static types is @emph{heap-allocated types}, or @emph{heap types}
for short, which correspond closely to classes created by Python's
@code{class} statement.

This is done by filling a @ref{3fbe,,PyType_Spec} structure and calling
@ref{1077,,PyType_FromSpecWithBases()}.

@node Number Object Structures,Mapping Object Structures,Type 对象<2>,对象实现支持
@anchor{c-api/typeobj number-object-structures}@anchor{4311}@anchor{c-api/typeobj number-structs}@anchor{4303}
@subsection Number Object Structures


@geindex PyNumberMethods (C 类型)
@anchor{c-api/typeobj c PyNumberMethods}@anchor{e4e}
@deffn {C 类型} PyNumberMethods

This structure holds pointers to the functions which an object uses to
implement the number protocol.  Each function is used by the function of
similar name documented in the @ref{3f2c,,数字协议} section.

@c XXX Drop the definition?

Here is the structure definition:

@example
typedef struct @{
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
@} PyNumberMethods;
@end example

@cartouche
@quotation 注解 
Binary and ternary functions must check the type of all their operands,
and implement the necessary conversions (at least one of the operands is
an instance of the defined type).  If the operation is not defined for the
given operands, binary and ternary functions must return
@code{Py_NotImplemented}, if another error occurred they must return @code{NULL}
and set an exception.
@end quotation
@end cartouche

@cartouche
@quotation 注解 
The @code{nb_reserved} field should always be @code{NULL}.  It
was previously called @code{nb_long}, and was renamed in
Python 3.0.1.
@end quotation
@end cartouche
@end deffn

@geindex PyNumberMethods.nb_add (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_add}@anchor{3fc7}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_add
@end deffn

@geindex PyNumberMethods.nb_subtract (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_subtract}@anchor{42c3}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_subtract
@end deffn

@geindex PyNumberMethods.nb_multiply (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_multiply}@anchor{42c5}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_multiply
@end deffn

@geindex PyNumberMethods.nb_remainder (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_remainder}@anchor{42c7}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_remainder
@end deffn

@geindex PyNumberMethods.nb_divmod (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_divmod}@anchor{42c9}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_divmod
@end deffn

@geindex PyNumberMethods.nb_power (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_power}@anchor{42ca}
@deffn {C 成员} ternaryfunc PyNumberMethods.nb_power
@end deffn

@geindex PyNumberMethods.nb_negative (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_negative}@anchor{42cc}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_negative
@end deffn

@geindex PyNumberMethods.nb_positive (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_positive}@anchor{42cd}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_positive
@end deffn

@geindex PyNumberMethods.nb_absolute (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_absolute}@anchor{42ce}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_absolute
@end deffn

@geindex PyNumberMethods.nb_bool (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_bool}@anchor{42cf}
@deffn {C 成员} inquiry PyNumberMethods.nb_bool
@end deffn

@geindex PyNumberMethods.nb_invert (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_invert}@anchor{42d0}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_invert
@end deffn

@geindex PyNumberMethods.nb_lshift (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_lshift}@anchor{42d1}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_lshift
@end deffn

@geindex PyNumberMethods.nb_rshift (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_rshift}@anchor{42d3}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_rshift
@end deffn

@geindex PyNumberMethods.nb_and (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_and}@anchor{42d5}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_and
@end deffn

@geindex PyNumberMethods.nb_xor (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_xor}@anchor{42d7}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_xor
@end deffn

@geindex PyNumberMethods.nb_or (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_or}@anchor{42d9}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_or
@end deffn

@geindex PyNumberMethods.nb_int (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_int}@anchor{42db}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_int
@end deffn

@geindex PyNumberMethods.nb_reserved (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_reserved}@anchor{42dc}
@deffn {C 成员} void *PyNumberMethods.nb_reserved
@end deffn

@geindex PyNumberMethods.nb_float (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_float}@anchor{42dd}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_float
@end deffn

@geindex PyNumberMethods.nb_inplace_add (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_add}@anchor{42c2}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_add
@end deffn

@geindex PyNumberMethods.nb_inplace_subtract (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_subtract}@anchor{42c4}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_subtract
@end deffn

@geindex PyNumberMethods.nb_inplace_multiply (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_multiply}@anchor{42c6}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_multiply
@end deffn

@geindex PyNumberMethods.nb_inplace_remainder (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_remainder}@anchor{42c8}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_remainder
@end deffn

@geindex PyNumberMethods.nb_inplace_power (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_power}@anchor{42cb}
@deffn {C 成员} ternaryfunc PyNumberMethods.nb_inplace_power
@end deffn

@geindex PyNumberMethods.nb_inplace_lshift (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_lshift}@anchor{42d2}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_lshift
@end deffn

@geindex PyNumberMethods.nb_inplace_rshift (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_rshift}@anchor{42d4}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_rshift
@end deffn

@geindex PyNumberMethods.nb_inplace_and (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_and}@anchor{42d6}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_and
@end deffn

@geindex PyNumberMethods.nb_inplace_xor (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_xor}@anchor{42d8}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_xor
@end deffn

@geindex PyNumberMethods.nb_inplace_or (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_or}@anchor{42da}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_or
@end deffn

@geindex PyNumberMethods.nb_floor_divide (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_floor_divide}@anchor{42de}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_floor_divide
@end deffn

@geindex PyNumberMethods.nb_true_divide (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_true_divide}@anchor{42e0}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_true_divide
@end deffn

@geindex PyNumberMethods.nb_inplace_floor_divide (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_floor_divide}@anchor{42df}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_floor_divide
@end deffn

@geindex PyNumberMethods.nb_inplace_true_divide (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_true_divide}@anchor{42e1}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_true_divide
@end deffn

@geindex PyNumberMethods.nb_index (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_index}@anchor{42e2}
@deffn {C 成员} unaryfunc PyNumberMethods.nb_index
@end deffn

@geindex PyNumberMethods.nb_matrix_multiply (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_matrix_multiply}@anchor{42e3}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_matrix_multiply
@end deffn

@geindex PyNumberMethods.nb_inplace_matrix_multiply (C 成员)
@anchor{c-api/typeobj c PyNumberMethods nb_inplace_matrix_multiply}@anchor{42e4}
@deffn {C 成员} binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
@end deffn

@node Mapping Object Structures,Sequence Object Structures,Number Object Structures,对象实现支持
@anchor{c-api/typeobj mapping-object-structures}@anchor{4312}@anchor{c-api/typeobj mapping-structs}@anchor{4305}
@subsection Mapping Object Structures


@geindex PyMappingMethods (C 类型)
@anchor{c-api/typeobj c PyMappingMethods}@anchor{3dbd}
@deffn {C 类型} PyMappingMethods

This structure holds pointers to the functions which an object uses to
implement the mapping protocol.  It has three members:
@end deffn

@geindex PyMappingMethods.mp_length (C 成员)
@anchor{c-api/typeobj c PyMappingMethods mp_length}@anchor{42e5}
@deffn {C 成员} lenfunc PyMappingMethods.mp_length

This function is used by @ref{11cf,,PyMapping_Size()} and
@ref{3f0d,,PyObject_Size()}, and has the same signature.  This slot may be set to
@code{NULL} if the object has no defined length.
@end deffn

@geindex PyMappingMethods.mp_subscript (C 成员)
@anchor{c-api/typeobj c PyMappingMethods mp_subscript}@anchor{42e7}
@deffn {C 成员} binaryfunc PyMappingMethods.mp_subscript

This function is used by @ref{3e04,,PyObject_GetItem()} and
@ref{3f56,,PySequence_GetSlice()}, and has the same signature as
@code{PyObject_GetItem()}.  This slot must be filled for the
@ref{3f67,,PyMapping_Check()} function to return @code{1}, it can be @code{NULL}
otherwise.
@end deffn

@geindex PyMappingMethods.mp_ass_subscript (C 成员)
@anchor{c-api/typeobj c PyMappingMethods mp_ass_subscript}@anchor{42e8}
@deffn {C 成员} objobjargproc PyMappingMethods.mp_ass_subscript

This function is used by @ref{3e02,,PyObject_SetItem()},
@ref{3f0f,,PyObject_DelItem()}, @code{PyObject_SetSlice()} and
@code{PyObject_DelSlice()}.  It has the same signature as
@code{PyObject_SetItem()}, but @emph{v} can also be set to @code{NULL} to delete
an item.  If this slot is @code{NULL}, the object does not support item
assignment and deletion.
@end deffn

@node Sequence Object Structures,Buffer Object Structures,Mapping Object Structures,对象实现支持
@anchor{c-api/typeobj sequence-object-structures}@anchor{4313}@anchor{c-api/typeobj sequence-structs}@anchor{4304}
@subsection Sequence Object Structures


@geindex PySequenceMethods (C 类型)
@anchor{c-api/typeobj c PySequenceMethods}@anchor{3dbc}
@deffn {C 类型} PySequenceMethods

This structure holds pointers to the functions which an object uses to
implement the sequence protocol.
@end deffn

@geindex PySequenceMethods.sq_length (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_length}@anchor{3fc8}
@deffn {C 成员} lenfunc PySequenceMethods.sq_length

This function is used by @ref{11cb,,PySequence_Size()} and
@ref{3f0d,,PyObject_Size()}, and has the same signature.  It is also used for
handling negative indices via the @ref{1108,,sq_item}
and the @ref{42ed,,sq_ass_item} slots.
@end deffn

@geindex PySequenceMethods.sq_concat (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_concat}@anchor{42ea}
@deffn {C 成员} binaryfunc PySequenceMethods.sq_concat

This function is used by @ref{3f52,,PySequence_Concat()} and has the same
signature.  It is also used by the @code{+} operator, after trying the numeric
addition via the @ref{3fc7,,nb_add} slot.
@end deffn

@geindex PySequenceMethods.sq_repeat (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_repeat}@anchor{42eb}
@deffn {C 成员} ssizeargfunc PySequenceMethods.sq_repeat

This function is used by @ref{3f53,,PySequence_Repeat()} and has the same
signature.  It is also used by the @code{*} operator, after trying numeric
multiplication via the @ref{42c5,,nb_multiply} slot.
@end deffn

@geindex PySequenceMethods.sq_item (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_item}@anchor{1108}
@deffn {C 成员} ssizeargfunc PySequenceMethods.sq_item

This function is used by @ref{11cc,,PySequence_GetItem()} and has the same
signature.  It is also used by @ref{3e04,,PyObject_GetItem()}, after trying
the subscription via the @ref{42e7,,mp_subscript} slot.
This slot must be filled for the @ref{3f50,,PySequence_Check()}
function to return @code{1}, it can be @code{NULL} otherwise.

Negative indexes are handled as follows: if the @code{sq_length} slot is
filled, it is called and the sequence length is used to compute a positive
index which is passed to @code{sq_item}.  If @code{sq_length} is @code{NULL},
the index is passed as is to the function.
@end deffn

@geindex PySequenceMethods.sq_ass_item (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_ass_item}@anchor{42ed}
@deffn {C 成员} ssizeobjargproc PySequenceMethods.sq_ass_item

This function is used by @ref{11cd,,PySequence_SetItem()} and has the same
signature.  It is also used by @ref{3e02,,PyObject_SetItem()} and
@ref{3f0f,,PyObject_DelItem()}, after trying the item assignment and deletion
via the @ref{42e8,,mp_ass_subscript} slot.
This slot may be left to @code{NULL} if the object does not support
item assignment and deletion.
@end deffn

@geindex PySequenceMethods.sq_contains (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_contains}@anchor{42ef}
@deffn {C 成员} objobjproc PySequenceMethods.sq_contains

This function may be used by @ref{3f5a,,PySequence_Contains()} and has the same
signature.  This slot may be left to @code{NULL}, in this case
@code{PySequence_Contains()} simply traverses the sequence until it
finds a match.
@end deffn

@geindex PySequenceMethods.sq_inplace_concat (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_inplace_concat}@anchor{42f1}
@deffn {C 成员} binaryfunc PySequenceMethods.sq_inplace_concat

This function is used by @ref{3f54,,PySequence_InPlaceConcat()} and has the same
signature.  It should modify its first operand, and return it.  This slot
may be left to @code{NULL}, in this case @code{PySequence_InPlaceConcat()}
will fall back to @ref{3f52,,PySequence_Concat()}.  It is also used by the
augmented assignment @code{+=}, after trying numeric in-place addition
via the @ref{42c2,,nb_inplace_add} slot.
@end deffn

@geindex PySequenceMethods.sq_inplace_repeat (C 成员)
@anchor{c-api/typeobj c PySequenceMethods sq_inplace_repeat}@anchor{42f2}
@deffn {C 成员} ssizeargfunc PySequenceMethods.sq_inplace_repeat

This function is used by @ref{3f55,,PySequence_InPlaceRepeat()} and has the same
signature.  It should modify its first operand, and return it.  This slot
may be left to @code{NULL}, in this case @code{PySequence_InPlaceRepeat()}
will fall back to @ref{3f53,,PySequence_Repeat()}.  It is also used by the
augmented assignment @code{*=}, after trying numeric in-place multiplication
via the @ref{42c6,,nb_inplace_multiply} slot.
@end deffn

@node Buffer Object Structures,Async Object Structures,Sequence Object Structures,对象实现支持
@anchor{c-api/typeobj buffer-object-structures}@anchor{4314}@anchor{c-api/typeobj buffer-structs}@anchor{3f75}
@subsection Buffer Object Structures


@geindex PyBufferProcs (C 类型)
@anchor{c-api/typeobj c PyBufferProcs}@anchor{3fd2}
@deffn {C 类型} PyBufferProcs

This structure holds pointers to the functions required by the
@ref{174c,,Buffer protocol}. The protocol defines how
an exporter object can expose its internal data to consumer objects.
@end deffn

@geindex PyBufferProcs.bf_getbuffer (C 成员)
@anchor{c-api/typeobj c PyBufferProcs bf_getbuffer}@anchor{3fd1}
@deffn {C 成员} getbufferproc PyBufferProcs.bf_getbuffer

The signature of this function is:

@example
int (PyObject *exporter, Py_buffer *view, int flags);
@end example

Handle a request to @emph{exporter} to fill in @emph{view} as specified by @emph{flags}.
Except for point (3), an implementation of this function MUST take these
steps:


@enumerate 

@item 
Check if the request can be met. If not, raise @code{PyExc_BufferError},
set @code{view->obj} to @code{NULL} and return @code{-1}.

@item 
Fill in the requested fields.

@item 
Increment an internal counter for the number of exports.

@item 
Set @code{view->obj} to @emph{exporter} and increment @code{view->obj}.

@item 
Return @code{0}.
@end enumerate

If @emph{exporter} is part of a chain or tree of buffer providers, two main
schemes can be used:


@itemize *

@item 
Re-export: Each member of the tree acts as the exporting object and
sets @code{view->obj} to a new reference to itself.

@item 
Redirect: The buffer request is redirected to the root object of the
tree. Here, @code{view->obj} will be a new reference to the root
object.
@end itemize

The individual fields of @emph{view} are described in section
@ref{3f76,,Buffer structure}, the rules how an exporter
must react to specific requests are in section
@ref{3f8a,,Buffer request types}.

All memory pointed to in the @ref{bf7,,Py_buffer} structure belongs to
the exporter and must remain valid until there are no consumers left.
@ref{3f83,,format}, @ref{3f85,,shape},
@ref{3f7a,,strides}, @ref{3f87,,suboffsets}
and @ref{3f89,,internal}
are read-only for the consumer.

@ref{3f7d,,PyBuffer_FillInfo()} provides an easy way of exposing a simple
bytes buffer while dealing correctly with all request types.

@ref{df3,,PyObject_GetBuffer()} is the interface for the consumer that
wraps this function.
@end deffn

@geindex PyBufferProcs.bf_releasebuffer (C 成员)
@anchor{c-api/typeobj c PyBufferProcs bf_releasebuffer}@anchor{3ec7}
@deffn {C 成员} releasebufferproc PyBufferProcs.bf_releasebuffer

The signature of this function is:

@example
void (PyObject *exporter, Py_buffer *view);
@end example

Handle a request to release the resources of the buffer. If no resources
need to be released, @ref{3ec7,,PyBufferProcs.bf_releasebuffer} may be
@code{NULL}. Otherwise, a standard implementation of this function will take
these optional steps:


@enumerate 

@item 
Decrement an internal counter for the number of exports.

@item 
If the counter is @code{0}, free all memory associated with @emph{view}.
@end enumerate

The exporter MUST use the @ref{3f89,,internal} field to keep
track of buffer-specific resources. This field is guaranteed to remain
constant, while a consumer MAY pass a copy of the original buffer as the
@emph{view} argument.

This function MUST NOT decrement @code{view->obj}, since that is
done automatically in @ref{e21,,PyBuffer_Release()} (this scheme is
useful for breaking reference cycles).

@ref{e21,,PyBuffer_Release()} is the interface for the consumer that
wraps this function.
@end deffn

@node Async Object Structures,Slot Type typedefs,Buffer Object Structures,对象实现支持
@anchor{c-api/typeobj async-object-structures}@anchor{4315}@anchor{c-api/typeobj async-structs}@anchor{4302}
@subsection Async Object Structures



3.5 新版功能.


@geindex PyAsyncMethods (C 类型)
@anchor{c-api/typeobj c PyAsyncMethods}@anchor{3fc6}
@deffn {C 类型} PyAsyncMethods

This structure holds pointers to the functions required to implement
@ref{61b,,awaitable} and @ref{742,,asynchronous iterator} objects.

Here is the structure definition:

@example
typedef struct @{
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
@} PyAsyncMethods;
@end example
@end deffn

@geindex PyAsyncMethods.am_await (C 成员)
@anchor{c-api/typeobj c PyAsyncMethods am_await}@anchor{42bd}
@deffn {C 成员} unaryfunc PyAsyncMethods.am_await

The signature of this function is:

@example
PyObject *am_await(PyObject *self);
@end example

The returned object must be an iterator, i.e. @ref{1192,,PyIter_Check()} must
return @code{1} for it.

This slot may be set to @code{NULL} if an object is not an @ref{61b,,awaitable}.
@end deffn

@geindex PyAsyncMethods.am_aiter (C 成员)
@anchor{c-api/typeobj c PyAsyncMethods am_aiter}@anchor{42bf}
@deffn {C 成员} unaryfunc PyAsyncMethods.am_aiter

The signature of this function is:

@example
PyObject *am_aiter(PyObject *self);
@end example

必须返回一个 @ref{742,,asynchronous iterator} 对象。 请参阅 @ref{158e,,__anext__()} 了解详情。

This slot may be set to @code{NULL} if an object does not implement
asynchronous iteration protocol.
@end deffn

@geindex PyAsyncMethods.am_anext (C 成员)
@anchor{c-api/typeobj c PyAsyncMethods am_anext}@anchor{42c0}
@deffn {C 成员} unaryfunc PyAsyncMethods.am_anext

The signature of this function is:

@example
PyObject *am_anext(PyObject *self);
@end example

Must return an @ref{61b,,awaitable} object.  See @ref{158e,,__anext__()} for details.
This slot may be set to @code{NULL}.
@end deffn

@node Slot Type typedefs,例子<2>,Async Object Structures,对象实现支持
@anchor{c-api/typeobj id5}@anchor{42f7}@anchor{c-api/typeobj slot-type-typedefs}@anchor{4316}
@subsection Slot Type typedefs


@geindex allocfunc (C 类型)
@anchor{c-api/typeobj c allocfunc}@anchor{42b5}
@deffn {C 类型} PyObject *(*allocfunc) (PyTypeObject@w{ }*cls, Py_ssize_t@w{ }nitems)

The purpose of this function is to separate memory allocation from memory
initialization.  It should return a pointer to a block of memory of adequate
length for the instance, suitably aligned, and initialized to zeros, but with
@code{ob_refcnt} set to @code{1} and @code{ob_type} set to the type argument.  If
the type's @ref{3d8d,,tp_itemsize} is non-zero, the object's @code{ob_size} field
should be initialized to @emph{nitems} and the length of the allocated memory block
should be @code{tp_basicsize + nitems*tp_itemsize}, rounded up to a multiple of
@code{sizeof(void*)}; otherwise, @emph{nitems} is not used and the length of the block
should be @ref{26b,,tp_basicsize}.

This function should not do any other instance initialization, not even to
allocate additional memory; that should be done by @ref{3d90,,tp_new}.
@end deffn

@geindex destructor (C 类型)
@anchor{c-api/typeobj c destructor}@anchor{429f}
@deffn {C 类型} void (*destructor) (PyObject@w{ }*)
@end deffn

@geindex freefunc (C 类型)
@anchor{c-api/typeobj c freefunc}@anchor{42b7}
@deffn {C 类型} void (*freefunc) (void@w{ }*)

See @ref{3d94,,tp_free}.
@end deffn

@geindex newfunc (C 类型)
@anchor{c-api/typeobj c newfunc}@anchor{42b6}
@deffn {C 类型} PyObject *(*newfunc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)

See @ref{3d90,,tp_new}.
@end deffn

@geindex initproc (C 类型)
@anchor{c-api/typeobj c initproc}@anchor{42b4}
@deffn {C 类型} int (*initproc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)

See @ref{3d97,,tp_init}.
@end deffn

@geindex reprfunc (C 类型)
@anchor{c-api/typeobj c reprfunc}@anchor{42a4}
@deffn {C 类型} PyObject *(*reprfunc) (PyObject@w{ }*)

See @ref{3dad,,tp_repr}.
@end deffn

@geindex getattrfunc (C 类型)
@anchor{c-api/typeobj c getattrfunc}@anchor{42a0}
@deffn {C 类型} PyObject *(*getattrfunc) (PyObject@w{ }*self, char@w{ }*attr)

Return the value of the named attribute for the object.
@end deffn

@geindex setattrfunc (C 类型)
@anchor{c-api/typeobj c setattrfunc}@anchor{42a1}
@deffn {C 类型} int (*setattrfunc) (PyObject@w{ }*self, char@w{ }*attr, PyObject@w{ }*value)

Set the value of the named attribute for the object.
The value argument is set to @code{NULL} to delete the attribute.
@end deffn

@geindex getattrofunc (C 类型)
@anchor{c-api/typeobj c getattrofunc}@anchor{42a9}
@deffn {C 类型} PyObject *(*getattrofunc) (PyObject@w{ }*self, PyObject@w{ }*attr)

Return the value of the named attribute for the object.

See @ref{3db2,,tp_getattro}.
@end deffn

@geindex setattrofunc (C 类型)
@anchor{c-api/typeobj c setattrofunc}@anchor{42aa}
@deffn {C 类型} int (*setattrofunc) (PyObject@w{ }*self, PyObject@w{ }*attr, PyObject@w{ }*value)

Set the value of the named attribute for the object.
The value argument is set to @code{NULL} to delete the attribute.

See @ref{3db3,,tp_setattro}.
@end deffn

@geindex descrgetfunc (C 类型)
@anchor{c-api/typeobj c descrgetfunc}@anchor{42b1}
@deffn {C 类型} PyObject *(*descrgetfunc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)

See @code{tp_descrget}.
@end deffn

@geindex descrsetfunc (C 类型)
@anchor{c-api/typeobj c descrsetfunc}@anchor{42b3}
@deffn {C 类型} int (*descrsetfunc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)

See @code{tp_descrset}.
@end deffn

@geindex hashfunc (C 类型)
@anchor{c-api/typeobj c hashfunc}@anchor{42a7}
@deffn {C 类型} Py_hash_t (*hashfunc) (PyObject@w{ }*)

See @ref{3dbe,,tp_hash}.
@end deffn

@geindex richcmpfunc (C 类型)
@anchor{c-api/typeobj c richcmpfunc}@anchor{42ad}
@deffn {C 类型} PyObject *(*richcmpfunc) (PyObject@w{ }*, PyObject@w{ }*, int)

See @ref{3db8,,tp_richcompare}.
@end deffn

@geindex getiterfunc (C 类型)
@anchor{c-api/typeobj c getiterfunc}@anchor{42ae}
@deffn {C 类型} PyObject *(*getiterfunc) (PyObject@w{ }*)

See @ref{efa,,tp_iter}.
@end deffn

@geindex iternextfunc (C 类型)
@anchor{c-api/typeobj c iternextfunc}@anchor{42af}
@deffn {C 类型} PyObject *(*iternextfunc) (PyObject@w{ }*)

See @ref{efb,,tp_iternext}.
@end deffn

@geindex lenfunc (C 类型)
@anchor{c-api/typeobj c lenfunc}@anchor{42e6}
@deffn {C 类型} Py_ssize_t (*lenfunc) (PyObject@w{ }*)
@end deffn

@geindex getbufferproc (C 类型)
@anchor{c-api/typeobj c getbufferproc}@anchor{42f3}
@deffn {C 类型} int (*getbufferproc) (PyObject@w{ }*, Py_buffer@w{ }*, int)
@end deffn

@geindex releasebufferproc (C 类型)
@anchor{c-api/typeobj c releasebufferproc}@anchor{42f4}
@deffn {C 类型} void (*releasebufferproc) (PyObject@w{ }*, Py_buffer@w{ }*)
@end deffn

@geindex unaryfunc (C 类型)
@anchor{c-api/typeobj c unaryfunc}@anchor{42be}
@deffn {C 类型} PyObject *(*unaryfunc) (PyObject@w{ }*)
@end deffn

@geindex binaryfunc (C 类型)
@anchor{c-api/typeobj c binaryfunc}@anchor{42c1}
@deffn {C 类型} PyObject *(*binaryfunc) (PyObject@w{ }*, PyObject@w{ }*)
@end deffn

@geindex ternaryfunc (C 类型)
@anchor{c-api/typeobj c ternaryfunc}@anchor{42a8}
@deffn {C 类型} PyObject *(*ternaryfunc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)
@end deffn

@geindex ssizeargfunc (C 类型)
@anchor{c-api/typeobj c ssizeargfunc}@anchor{42ec}
@deffn {C 类型} PyObject *(*ssizeargfunc) (PyObject@w{ }*, Py_ssize_t)
@end deffn

@geindex ssizeobjargproc (C 类型)
@anchor{c-api/typeobj c ssizeobjargproc}@anchor{42ee}
@deffn {C 类型} int (*ssizeobjargproc) (PyObject@w{ }*, Py_ssize_t)
@end deffn

@geindex objobjproc (C 类型)
@anchor{c-api/typeobj c objobjproc}@anchor{42f0}
@deffn {C 类型} int (*objobjproc) (PyObject@w{ }*, PyObject@w{ }*)
@end deffn

@geindex objobjargproc (C 类型)
@anchor{c-api/typeobj c objobjargproc}@anchor{42e9}
@deffn {C 类型} int (*objobjargproc) (PyObject@w{ }*, PyObject@w{ }*, PyObject@w{ }*)
@end deffn

@node 例子<2>,使对象类型支持循环垃圾回收,Slot Type typedefs,对象实现支持
@anchor{c-api/typeobj examples}@anchor{4317}@anchor{c-api/typeobj typedef-examples}@anchor{429a}
@subsection 例子


The following are simple examples of Python type definitions.  They
include common usage you may encounter.  Some demonstrate tricky corner
cases.  For more examples, practical info, and a tutorial, see
@ref{3d87,,自定义扩展类型：教程} and @ref{3da7,,定义扩展类型：已分类主题}.

A basic static type:

@example
typedef struct @{
    PyObject_HEAD
    const char *data;
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_new = myobj_new,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
@};
@end example

You may also find older code (especially in the CPython code base)
with a more verbose initializer:

@example
static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    "mymod.MyObject",               /* tp_name */
    sizeof(MyObject),               /* tp_basicsize */
    0,                              /* tp_itemsize */
    (destructor)myobj_dealloc,      /* tp_dealloc */
    0,                              /* tp_vectorcall_offset */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)myobj_repr,           /* tp_repr */
    0,                              /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    0,                              /* tp_hash */
    0,                              /* tp_call */
    0,                              /* tp_str */
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    0,                              /* tp_flags */
    PyDoc_STR("My objects"),        /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    0,                              /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    myobj_new,                      /* tp_new */
@};
@end example

A type that supports weakrefs, instance dicts, and hashing:

@example
typedef struct @{
    PyObject_HEAD
    const char *data;
    PyObject *inst_dict;
    PyObject *weakreflist;
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_weaklistoffset = offsetof(MyObject, weakreflist),
    .tp_dictoffset = offsetof(MyObject, inst_dict),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    .tp_new = myobj_new,
    .tp_traverse = (traverseproc)myobj_traverse,
    .tp_clear = (inquiry)myobj_clear,
    .tp_alloc = PyType_GenericNew,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
    .tp_hash = (hashfunc)myobj_hash,
    .tp_richcompare = PyBaseObject_Type.tp_richcompare,
@};
@end example

A str subclass that cannot be subclassed and cannot be called
to create instances (e.g. uses a separate factory func):

@example
typedef struct @{
    PyUnicodeObject raw;
    char *extra;
@} MyStr;

static PyTypeObject MyStr_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyStr",
    .tp_basicsize = sizeof(MyStr),
    .tp_base = NULL,  // set to &PyUnicode_Type in module init
    .tp_doc = PyDoc_STR("my custom str"),
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = NULL,
    .tp_repr = (reprfunc)myobj_repr,
@};
@end example

The simplest static type (with fixed-length instances):

@example
typedef struct @{
    PyObject_HEAD
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
@};
@end example

The simplest static type (with variable-length instances):

@example
typedef struct @{
    PyObject_VAR_HEAD
    const char *data[1];
@} MyObject;

static PyTypeObject MyObject_Type = @{
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject) - sizeof(char *),
    .tp_itemsize = sizeof(char *),
@};
@end example

@node 使对象类型支持循环垃圾回收,,例子<2>,对象实现支持
@anchor{c-api/gcsupport doc}@anchor{4318}@anchor{c-api/gcsupport supporting-cycle-detection}@anchor{4308}@anchor{c-api/gcsupport supporting-cyclic-garbage-collection}@anchor{4319}
@subsection 使对象类型支持循环垃圾回收


Python 对循环引用的垃圾检测与回收需要“容器”对象类型的支持，此类型的容器对象中可能包含其它容器对象。不保存其它对象的引用的类型，或者只保存原子类型（如数字或字符串）的引用的类型，不需要显式提供垃圾回收的支持。

若要创建一个容器类，类型对象的 @ref{105b,,tp_flags} 字段必须包含 @ref{3da1,,Py_TPFLAGS_HAVE_GC} 并提供一个 @ref{23c,,tp_traverse} 处理的实现。如果该类型的实例是可变的，还需要实现 @ref{3dab,,tp_clear} 。


@deffn {数据} Py_TPFLAGS_HAVE_GC

设置了此标志位的类型的对象必须符合此处记录的规则。为方便起见，下文把这些对象称为容器对象。
@end deffn

容器类型的构造函数必须符合两个规则：


@enumerate 

@item 
必须使用 @ref{3fc,,PyObject_GC_New()} 或 @ref{3fd,,PyObject_GC_NewVar()} 为这些对象分配内存。

@item 
初始化了所有可能包含其他容器的引用的字段后，它必须调用 @ref{f0e,,PyObject_GC_Track()} 。
@end enumerate

同样的，对象的释放器必须符合两个类似的规则：


@enumerate 

@item 
在引用其它容器的字段失效前，必须调用 @ref{f0f,,PyObject_GC_UnTrack()} 。

@item 
必须使用 @ref{f0d,,PyObject_GC_Del()} 释放对象的内存。

@cartouche
@quotation 警告 
如果一个类型添加了 Py_TPFLAGS_HAVE_GC，则它 @emph{必须} 实现至少一个 @ref{23c,,tp_traverse} 句柄或显式地使用来自其一个或多个子类的句柄。

当调用 @ref{3d96,,PyType_Ready()} 或者 API 中某些间接调用它的函数例如 @ref{1077,,PyType_FromSpecWithBases()} 或 @ref{23b,,PyType_FromSpec()} 时解释器就自动填充 @ref{105b,,tp_flags}, @ref{23c,,tp_traverse} 和 @ref{3dab,,tp_clear} 字段，如果该类型是继承自实现了垃圾回收器协议的类并且该子类 @emph{没有} 包括 @ref{3da1,,Py_TPFLAGS_HAVE_GC} 旗标的话。
@end quotation
@end cartouche
@end enumerate

@geindex PyObject_GC_New (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_New}@anchor{3fc}
@deffn {C 函数} TYPE* PyObject_GC_New (TYPE, PyTypeObject@w{ }*type)

类似于 @ref{269,,PyObject_New()} ，适用于设置了 @ref{3da1,,Py_TPFLAGS_HAVE_GC} 标签的容器对象。
@end deffn

@geindex PyObject_GC_NewVar (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_NewVar}@anchor{3fd}
@deffn {C 函数} TYPE* PyObject_GC_NewVar (TYPE, PyTypeObject@w{ }*type, Py_ssize_t@w{ }size)

类似于 @ref{26a,,PyObject_NewVar()} ，适用于设置了 @ref{3da1,,Py_TPFLAGS_HAVE_GC} 标签的容器对象。
@end deffn

@geindex PyObject_GC_Resize (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_Resize}@anchor{431a}
@deffn {C 函数} TYPE* PyObject_GC_Resize (TYPE, PyVarObject@w{ }*op, Py_ssize_t@w{ }newsize)

为 @ref{26a,,PyObject_NewVar()} 所分配对象重新调整大小。 返回调整大小后的对象或在失败时返回 @code{NULL}。 @emph{op} 必须尚未被垃圾回收器追踪。
@end deffn

@geindex PyObject_GC_Track (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_Track}@anchor{f0e}
@deffn {C 函数} void PyObject_GC_Track (PyObject@w{ }*op)

把对象 @emph{op} 加入到垃圾回收器跟踪的容器对象中。对象在被回收器跟踪时必须保持有效的，因为回收器可能在任何时候开始运行。在 @ref{23c,,tp_traverse} 处理前的所有字段变为有效后，必须调用此函数，通常在靠近构造函数末尾的位置。
@end deffn

@geindex PyObject_IS_GC (C 函数)
@anchor{c-api/gcsupport c PyObject_IS_GC}@anchor{268}
@deffn {C 函数} int PyObject_IS_GC (PyObject@w{ }*obj)

如果对象实现了垃圾回收器协议则返回非零值，否则返回 0。

如果此函数返回 0 则对象无法被垃圾回收器追踪。
@end deffn

@geindex PyObject_GC_IsTracked (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_IsTracked}@anchor{255}
@deffn {C 函数} int PyObject_GC_IsTracked (PyObject@w{ }*op)

如果 @emph{op} 对象的类型实现了 GC 协议且 @emph{op} 目前正被垃圾回收器追踪则返回 1， 否则返回 0。

这类似于 Python 函数 @ref{d73,,gc.is_tracked()}。


3.9 新版功能.

@end deffn

@geindex PyObject_GC_IsFinalized (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_IsFinalized}@anchor{256}
@deffn {C 函数} int PyObject_GC_IsFinalized (PyObject@w{ }*op)

如果 @emph{op} 对象的类型实现了 GC 协议且 @emph{op} 已经被垃圾回收器终结则返回 1， 否则返回 0。

这类似于 Python 函数 @ref{1a9,,gc.is_finalized()}。


3.9 新版功能.

@end deffn

@geindex PyObject_GC_Del (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_Del}@anchor{f0d}
@deffn {C 函数} void PyObject_GC_Del (void@w{ }*op)

释放对象的内存，该对象初始化时由 @ref{3fc,,PyObject_GC_New()} 或 @ref{3fd,,PyObject_GC_NewVar()} 分配内存。
@end deffn

@geindex PyObject_GC_UnTrack (C 函数)
@anchor{c-api/gcsupport c PyObject_GC_UnTrack}@anchor{f0f}
@deffn {C 函数} void PyObject_GC_UnTrack (void@w{ }*op)

从回收器跟踪的容器对象集合中移除 @emph{op} 对象。 请注意可以在此对象上再次调用 @ref{f0e,,PyObject_GC_Track()} 以将其加回到被跟踪对象集合。 释放器 (@ref{3d93,,tp_dealloc} 句柄) 应当在 @ref{23c,,tp_traverse} 句柄所使用的任何字段失效之前为对象调用此函数。
@end deffn


在 3.8 版更改: @code{_PyObject_GC_TRACK()} 和 @code{_PyObject_GC_UNTRACK()} 宏已从公有 C API 中移除。


@ref{23c,,tp_traverse} 处理接收以下类型的函数形参。

@geindex visitproc (C 类型)
@anchor{c-api/gcsupport c visitproc}@anchor{42f6}
@deffn {C 类型} int (*visitproc) (PyObject@w{ }*object, void@w{ }*arg)

传给 @ref{23c,,tp_traverse} 处理的访问函数的类型。@emph{object} 是容器中需要被遍历的一个对象，第三个形参对应于 @ref{23c,,tp_traverse} 处理的 @emph{arg} 。Python核心使用多个访问者函数实现循环引用的垃圾检测，不需要用户自行实现访问者函数。
@end deffn

@ref{23c,,tp_traverse} 处理必须是以下类型：

@geindex traverseproc (C 类型)
@anchor{c-api/gcsupport c traverseproc}@anchor{42ab}
@deffn {C 类型} int (*traverseproc) (PyObject@w{ }*self, visitproc@w{ }visit, void@w{ }*arg)

用于容器对象的遍历函数。 它的实现必须对 @emph{self} 所直接包含的每个对象调用 @emph{visit} 函数，@emph{visit} 的形参为所包含对象和传给处理程序的 @emph{arg} 值。 @emph{visit} 函数调用不可附带 @code{NULL} 对象作为参数。 如果 @emph{visit} 返回非零值，则该值应当被立即返回。
@end deffn

为了简化 @ref{23c,,tp_traverse} 处理的实现，Python提供了一个 @ref{3d9f,,Py_VISIT()} 宏。若要使用这个宏，必须把 @ref{23c,,tp_traverse} 的参数命名为 @emph{visit} 和 @emph{arg} 。

@geindex Py_VISIT (C 函数)
@anchor{c-api/gcsupport c Py_VISIT}@anchor{3d9f}
@deffn {C 函数} void Py_VISIT (PyObject@w{ }*o)

如果 @emph{o} 不为 @code{NULL}，则调用 @emph{visit} 回调函数，附带参数 @emph{o} 和 @emph{arg}。 如果 @emph{visit} 返回一个非零值，则返回该值。 使用此宏之后，@ref{23c,,tp_traverse} 处理程序的形式如下:

@example
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
@{
    Py_VISIT(self->foo);
    Py_VISIT(self->bar);
    return 0;
@}
@end example
@end deffn

@ref{3dab,,tp_clear} 处理程序必须为 @ref{42ac,,inquiry} 类型，如果对象不可变则为 @code{NULL}。

@geindex inquiry (C 类型)
@anchor{c-api/gcsupport c inquiry}@anchor{42ac}
@deffn {C 类型} int (*inquiry) (PyObject@w{ }*self)

丢弃产生循环引用的引用。不可变对象不需要声明此方法，因为他们不可能直接产生循环引用。需要注意的是，对象在调用此方法后必须仍是有效的（不能对引用只调用 @ref{397,,Py_DECREF()} 方法）。当垃圾回收器检测到该对象在循环引用中时，此方法会被调用。
@end deffn

@node API 和 ABI 版本管理,,对象实现支持,Python/C API 参考手册
@anchor{c-api/apiabiversion doc}@anchor{431b}@anchor{c-api/apiabiversion api-and-abi-versioning}@anchor{431c}@anchor{c-api/apiabiversion apiabiversion}@anchor{36bf}
@section API 和 ABI 版本管理


@code{PY_VERSION_HEX} 是Python的版本号的整数形式。

例如，如果 @code{PY_VERSION_HEX} 被置为 @code{0x030401a2}, 其包含的版本信息可以通过以下方式将其作为一个32位数字来处理：

@quotation


@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

字节

@tab

位数（大端字节序）

@tab

意义

@item

@code{1}

@tab

@code{1-8}

@tab

@code{PY_MAJOR_VERSION} （@code{3.4.1a2} 中的 @code{3} ）

@item

@code{2}

@tab

@code{9-16}

@tab

@code{PY_MINOR_VERSION} （@code{3.4.1a2} 中的 @code{4} ）

@item

@code{3}

@tab

@code{17-24}

@tab

@code{PY_MICRO_VERSION} （@code{3.4.1a2} 中的 @code{1} ）

@item

@code{4}

@tab

@code{25-28}

@tab

@code{PY_RELEASE_LEVEL} (@code{0xA} 是 alpha版本, @code{0xB} 是 beta版本, @code{0xC} 发布的候选版本并且 @code{0xF} 是最终版本)，在这个例子中这个版本是alpha版本。

@item

@tab

@code{29-32}

@tab

@code{PY_RELEASE_SERIAL} （ @code{3.4.1a2} 中的 @code{2} ，最终版本用0)

@end multitable

@end quotation

因此 @code{3.4.1a2} 的16进制版本号是 @code{0x030401a2} 。

所有提到的宏都定义在 Include/patchlevel.h@footnote{https://github.com/python/cpython/tree/3.9/Include/patchlevel.h}。

@node 分发 Python 模块,安装 Python 模块,Python/C API 参考手册,Top
@anchor{distributing/index doc}@anchor{431d}@anchor{distributing/index distributing-index}@anchor{8ed}@anchor{distributing/index distributing-python-modules}@anchor{431e}
@chapter 分发 Python 模块


@*电子邮箱: 
@email{distutils-sig@@python.org}


作为一个流行的开源开发项目，Python拥有一个活跃的贡献者和用户支持社区，这些社区也可以让他们的软件可供其他Python开发人员在开源许可条款下使用。

这允许Python用户有效地共享和协作，从其他人已经创建的解决方案中受益于常见（有时甚至是罕见的）问题，以及可以提供他们自己的解决方案。

本指南涵盖了分发部分的流程。有关安装其他Python项目的指南，请参阅 @ref{8ec,,安装指南}。

@cartouche
@quotation 注解 
对于企业和其他机构用户，请注意许多组织都有自己的政策来使用和贡献开源软件。在使用Python提供的分发和安装工具时，请考虑这些政策。
@end quotation
@end cartouche

@menu
* 关键术语:: 
* 开源许可与协作:: 
* 安装相关工具:: 
* 阅读 Python 打包用户指南:: 
* 我该如何...？: 我该如何 ？. 

@end menu

@node 关键术语,开源许可与协作,,分发 Python 模块
@anchor{distributing/index key-terms}@anchor{431f}
@section 关键术语



@itemize *

@item 
Python Package Index@footnote{https://pypi.org} 是一个开源许可的软件包公共存储库，可供所有 Python 用户使用。

@item 
Python Packaging Authority@footnote{https://www.pypa.io/} 是负责标准打包工具以及相关元数据和文件格式标准维护与改进的开发人员和文档作者团队。 他们基于 GitHub@footnote{https://github.com/pypa} 和 Bitbucket@footnote{https://bitbucket.org/pypa/} 这两个平台维护着各种工具、文档和问题追踪系统。

@item 
@ref{38,,distutils} 是 1998 年首次添加到 Python 标准库的原始构建和分发系统。 虽然直接使用 @ref{38,,distutils} 正在逐步淘汰，但它仍然为当前的打包和分发基础架构奠定了基础它不仅仍然是标准库的一部分，而且它的名称还以其他方式存在（例如用于协调 Python 打包标准开发的邮件列表的名称）。

@item 
setuptools@footnote{https://setuptools.readthedocs.io/en/latest/} （在很大程度上）是作为 @ref{38,,distutils} 的取代者，于 2004 年首次发布。 它对未经修改的 @ref{38,,distutils} 工具最重要的补充是能够声明对其他包的依赖。 目前它被推荐用来替代 @ref{38,,distutils}，其更新更为频繁，在更为多样的 Python 版本之上为最新的打包标准提供持续支持。

@item 
wheel@footnote{https://wheel.readthedocs.io/} （在此上下文中）是一个将 @code{bdist_wheel} 命令添加到 @ref{38,,distutils}/setuptools@footnote{https://setuptools.readthedocs.io/en/latest/} 的项目。这产生了一个跨平台的二进制打包格式（称为“轮子”或“轮子文件”，并在 
@geindex Python 提高建议; PEP 427
PEP 427@footnote{https://www.python.org/dev/peps/pep-0427} 中定义），它允许在系统上安装Python库，甚至包括二进制扩展的库，而不需在本地进行构建。
@end itemize

@node 开源许可与协作,安装相关工具,关键术语,分发 Python 模块
@anchor{distributing/index open-source-licensing-and-collaboration}@anchor{4320}@anchor{distributing/index wheel}@anchor{4321}
@section 开源许可与协作


在世界上大多数地方，软件自动受版权保护。这意味着其他开发人员需要明确的权限来复制，使用，修改和重新分发软件。

开源许可是一种以相对一致的方式明确授予此类权限的方式，允许开发人员通过为各种问题免费提供通用解决方案来有效地共享和协作。这使得许多开发人员可以将更多时间用于关注他们特定情况相对独特的问题。

Python提供的分发工具旨在使开发人员选择开源时，可以合理地直接将其自己的贡献回馈到该公共软件池。

无论该软件是否作为开源软件发布，相同的分发工具也可用于在组织内分发软件。

@node 安装相关工具,阅读 Python 打包用户指南,开源许可与协作,分发 Python 模块
@anchor{distributing/index installing-the-tools}@anchor{4322}
@section 安装相关工具


标准库不包括支持现代Python打包标准的构建工具，因为核心开发团队已经发现，即使在旧版本的Python上，使用一致工作的标准工具也很重要。

可以通过在命令行调用 @code{pip} 模块来安装当前推荐的构建和分发工具:

@example
python -m pip install setuptools wheel twine
@end example

@cartouche
@quotation 注解 
对于 POSIX 用户（包括 macOS 和 Linux 用户），这些说明假定使用了 @ref{1477,,virtual environment} 。

对于Windows用户，这些说明假定在安装Python时选择了调整系统PATH环境变量的选项。
@end quotation
@end cartouche

Python 打包用户指南包含有关 当前推荐工具的@footnote{https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations} 的更多详细信息。

@geindex Python Package Index (PyPI)
@geindex PyPI; (see Python Package Index (PyPI))

@node 阅读 Python 打包用户指南,我该如何 ？,安装相关工具,分发 Python 模块
@anchor{distributing/index publishing-python-packages}@anchor{4323}@anchor{distributing/index reading-the-python-packaging-user-guide}@anchor{4324}
@section 阅读 Python 打包用户指南


“Python 打包用户指南”介绍了创建和发布项目所涉及的各个关键步骤和元素：


@itemize *

@item 
项目的结构@footnote{https://packaging.python.org/tutorials/packaging-projects/#packaging-python-projects}

@item 
项目的构建与打包@footnote{https://packaging.python.org/tutorials/packaging-projects/#creating-the-package-files}

@item 
Uploading the project to the Python Package Index@footnote{https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives}

@item 
The .pypirc file@footnote{https://packaging.python.org/specifications/pypirc/}
@end itemize

@node 我该如何 ？,,阅读 Python 打包用户指南,分发 Python 模块
@anchor{distributing/index how-do-i}@anchor{4325}@anchor{distributing/index the-pypirc-file}@anchor{4326}
@section 我该如何...？


这是一些常见任务的快速解答或相关链接。

@menu
* ...为我的项目选择一个名字？: 为我的项目选择一个名字？. 
* ...创建和分发二进制扩展？: 创建和分发二进制扩展？. 

@end menu

@node 为我的项目选择一个名字？,创建和分发二进制扩展？,,我该如何 ？
@anchor{distributing/index choose-a-name-for-my-project}@anchor{4327}
@subsection ...为我的项目选择一个名字？


这不是一个简单的主题，但这里有一些提示：


@itemize *

@item 
检查 Python Package Index 以查看该名称是否已被使用

@item 
检查流行的托管网站如 GitHub，Bitbucket 等等，看是否已有一个该名称的项目

@item 
检查您正在考虑的名称在网络搜索中出现的内容

@item 
避免使用特别常见的单词，尤其是具有多重含义的单词，因为它们会使用户在搜索时难以找到您的软件
@end itemize

@node 创建和分发二进制扩展？,,为我的项目选择一个名字？,我该如何 ？
@anchor{distributing/index create-and-distribute-binary-extensions}@anchor{4328}
@subsection ...创建和分发二进制扩展？


这实际上是一个非常复杂的主题，根据您的目标，可以提供各种替代方案。 有关更多信息和建议，请参阅 Python 打包用户指南。


@subsubheading 参见


Python 打包用户指南：二进制扩展@footnote{https://packaging.python.org/guides/packaging-binary-extensions/}


@c other topics:
@c 
@c Once the Development & Deployment part of PPUG is fleshed out, some of
@c those sections should be linked from new questions here (most notably,
@c we should have a question about avoiding depending on PyPI that links to
@c https://packaging.python.org/en/latest/mirrors/)

@node 安装 Python 模块,Python 常用指引,分发 Python 模块,Top
@anchor{installing/index doc}@anchor{4329}@anchor{installing/index installing-index}@anchor{8ec}@anchor{installing/index installing-python-modules}@anchor{432a}
@chapter 安装 Python 模块


@*电子邮箱: 
@email{distutils-sig@@python.org}


作为一个流行的开源开发项目，Python拥有一个活跃的贡献者和用户支持社区，这些社区也可以让他们的软件可供其他Python开发人员在开源许可条款下使用。

这允许Python用户有效地共享和协作，从其他人已经创建的解决方案中受益于常见（有时甚至是罕见的）问题，以及可以提供他们自己的解决方案。

本指南涵盖了分发部分的流程。有关安装其他Python项目的指南，请参阅 @ref{8ed,,安装指南}。

@cartouche
@quotation 注解 
对于企业和其他机构用户，请注意许多组织都有自己的政策来使用和贡献开源软件。在使用Python提供的分发和安装工具时，请考虑这些政策。
@end quotation
@end cartouche

@menu
* 关键术语: 关键术语<2>. 
* 基本使用: 基本使用<2>. 
* 我应如何 ...？: 我应如何 ？. 
* 常见的安装问题:: 

@end menu

@node 关键术语<2>,基本使用<2>,,安装 Python 模块
@anchor{installing/index key-terms}@anchor{432b}
@section 关键术语



@itemize *

@item 
@code{pip} 是首选的安装程序。从Python 3.4开始，它默认包含在Python二进制安装程序中。

@item 
@emph{virtual environment} 是一种半隔离的 Python 环境，允许为特定的应用安装各自的包，而不是安装到整个系统。

@item 
@code{venv} 是创建虚拟环境的标准工具，从 Python 3.3 开始成为 Python 的组成部分。 从 Python 3.4 开始，它会默认安装 @code{pip} 到所创建的全部虚拟环境。

@item 
@code{virtualenv} 是 @code{venv} 的第三方替代（及其前身）。 它允许在 Python 3.4 之前的版本中使用虚拟环境，那些版本或是完全不提供 @code{venv}，或是不会自动安装 @code{pip} 到所创建的虚拟环境。

@item 
Python Package Index@footnote{https://pypi.org} 是一个开源许可的软件包公共存储库，可供所有 Python 用户使用。

@item 
Python Packaging Authority@footnote{https://www.pypa.io/} 是负责标准打包工具以及相关元数据和文件格式标准维护与改进的开发人员和文档作者团队。 他们基于 GitHub@footnote{https://github.com/pypa} 和 Bitbucket@footnote{https://bitbucket.org/pypa/} 这两个平台维护着各种工具、文档和问题追踪系统。

@item 
@code{distutils} 是最初的构建和分发系统，于 1998 年首次加入 Python 标准库。 虽然直接使用 @code{distutils} 的方式已被淘汰，它仍然是当前打包和分发架构的基础，而且它不仅仍然是标准库的一部分，这个名称还以其他方式存在（例如用于协调 Python 打包标准开发流程的邮件列表就以此命名）。
@end itemize


在 3.5 版更改: 现在推荐使用 @code{venv} 来创建虚拟环境。



@subsubheading 参见


Python 软件包用户指南：创建和使用虚拟环境@footnote{https://packaging.python.org/installing/#creating-virtual-environments}


@node 基本使用<2>,我应如何 ？,关键术语<2>,安装 Python 模块
@anchor{installing/index basic-usage}@anchor{432c}
@section 基本使用


标准打包工具完全是针对命令行使用方式来设计的。

以下命令将从 Python Package Index 安装一个模块的最新版本及其依赖项:

@example
python -m pip install SomePackage
@end example

@cartouche
@quotation 注解 
对于 POSIX 用户（包括 macOS 和 Linux 用户）本指南中的示例假定使用了 @ref{1477,,virtual environment}。

对于 Windows 用户，本指南中的示例假定在安装 Python 时选择了修改系统 PATH 环境变量。
@end quotation
@end cartouche

在命令行中指定一个准确或最小版本也是可以的。 当使用比较运算符例如 @code{>}, @code{<} 或其他某些可以被终端所解析的特殊字符时，包名称与版本号应当用双引号括起来:

@example
python -m pip install SomePackage==1.0.4    # specific version
python -m pip install "SomePackage>=1.0.4"  # minimum version
@end example

通常，如果一个匹配的模块已安装，尝试再次安装将不会有任何效果。 要升级现有模块必须显式地发出请求:

@example
python -m pip install --upgrade SomePackage
@end example

更多有关 @code{pip} 及其功能的信息和资源可以在 Python 软件包用户指南@footnote{https://packaging.python.org} 中找到。

虚拟环境的创建可使用 @ref{12e,,venv} 模块来完成。 向已激活虚拟环境安装软件包可使用上文所介绍的命令。


@subsubheading 参见


Python 软件包用户指南：安装 Python 分发包@footnote{https://packaging.python.org/installing/}


@node 我应如何 ？,常见的安装问题,基本使用<2>,安装 Python 模块
@anchor{installing/index how-do-i}@anchor{432d}
@section 我应如何 ...？


这是一些常见任务的快速解答或相关链接。

@menu
* ... 在 Python 3.4 之前的 Python 版本中安装 pip ？: 在 Python 3 4 之前的 Python 版本中安装 pip ？. 
* ... 只为当前用户安装软件包？: 只为当前用户安装软件包？. 
* ... 安装科学计算类 Python 软件包？: 安装科学计算类 Python 软件包？. 
* ... 使用并行安装的多个 Python 版本？: 使用并行安装的多个 Python 版本？. 

@end menu

@node 在 Python 3 4 之前的 Python 版本中安装 pip ？,只为当前用户安装软件包？,,我应如何 ？
@anchor{installing/index install-pip-in-versions-of-python-prior-to-python-3-4}@anchor{432e}
@subsection ... 在 Python 3.4 之前的 Python 版本中安装 @code{pip} ？


Python 捆绑 @code{pip} 是从 Python 3.4 才开始的。 对于更早的版本，@code{pip} 需要“引导安装”，具体说明参见 Python 软件包用户指南。


@subsubheading 参见


Python 软件包用户指南：安装软件包的前提要求@footnote{https://packaging.python.org/installing/#requirements-for-installing-packages}


@c installing-per-user-installation:

@node 只为当前用户安装软件包？,安装科学计算类 Python 软件包？,在 Python 3 4 之前的 Python 版本中安装 pip ？,我应如何 ？
@anchor{installing/index install-packages-just-for-the-current-user}@anchor{432f}
@subsection ... 只为当前用户安装软件包？


将 @code{--user} 选项传入 @code{python -m pip install} 将只为当前用户而非为系统中的所有用户安装软件包。

@node 安装科学计算类 Python 软件包？,使用并行安装的多个 Python 版本？,只为当前用户安装软件包？,我应如何 ？
@anchor{installing/index install-scientific-python-packages}@anchor{4330}
@subsection ... 安装科学计算类 Python 软件包？


许多科学计算类 Python 软件包都有复杂的二进制编译文件依赖，直接使用 @code{pip} 安装目前并不太容易。 在当前情况下，通过 其他方式@footnote{https://packaging.python.org/science/} 而非尝试用 @code{pip} 安装这些软件包对用户来说通常会更容易。


@subsubheading 参见


Python 软件包用户指南：安装科学计算类软件包@footnote{https://packaging.python.org/science/}


@node 使用并行安装的多个 Python 版本？,,安装科学计算类 Python 软件包？,我应如何 ？
@anchor{installing/index work-with-multiple-versions-of-python-installed-in-parallel}@anchor{4331}
@subsection ... 使用并行安装的多个 Python 版本？


在 Linux, macOS 以及其他 POSIX 系统中，使用带版本号的 Python 命令配合 @code{-m} 开关选项来运行特定版本的 @code{pip}:

@example
python2   -m pip install SomePackage  # default Python 2
python2.7 -m pip install SomePackage  # specifically Python 2.7
python3   -m pip install SomePackage  # default Python 3
python3.4 -m pip install SomePackage  # specifically Python 3.4
@end example

也可以使用带特定版本号的 @code{pip} 命令。

在 Windows 中，使用 @code{py} Python 启动器命令配合 @code{-m} 开关选项:

@example
py -2   -m pip install SomePackage  # default Python 2
py -2.7 -m pip install SomePackage  # specifically Python 2.7
py -3   -m pip install SomePackage  # default Python 3
py -3.4 -m pip install SomePackage  # specifically Python 3.4
@end example

@c other questions:
@c 
@c Once the Development & Deployment part of PPUG is fleshed out, some of
@c those sections should be linked from new questions here (most notably,
@c we should have a question about avoiding depending on PyPI that links to
@c https://packaging.python.org/en/latest/mirrors/)

@node 常见的安装问题,,我应如何 ？,安装 Python 模块
@anchor{installing/index common-installation-issues}@anchor{4332}
@section 常见的安装问题


@menu
* 在 Linux 的系统 Python 版本上安装:: 
* 未安装 pip:: 
* 安装二进制编译扩展:: 

@end menu

@node 在 Linux 的系统 Python 版本上安装,未安装 pip,,常见的安装问题
@anchor{installing/index installing-into-the-system-python-on-linux}@anchor{4333}
@subsection 在 Linux 的系统 Python 版本上安装


Linux 系统通常会将某个 Python 版本作为发行版的一部分包含在内。 将软件包安装到这个 Python 版本上需要系统 root 权限，并可能会干扰到系统包管理器和其他系统组件的运作，如果这些组件在使用 @code{pip} 时被意外升级的话。

在这样的系统上，通过 @code{pip} 安装软件包通常最好是使用虚拟环境或分用户安装。

@node 未安装 pip,安装二进制编译扩展,在 Linux 的系统 Python 版本上安装,常见的安装问题
@anchor{installing/index pip-not-installed}@anchor{4334}
@subsection 未安装 pip


默认情况下可能未安装 @code{pip}，一种可选解决方案是:

@example
python -m ensurepip --default-pip
@end example

还有其他资源可用来 安装 pip@footnote{https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel}

@node 安装二进制编译扩展,,未安装 pip,常见的安装问题
@anchor{installing/index installing-binary-extensions}@anchor{4335}
@subsection 安装二进制编译扩展


Python 通常非常依赖基于源代码的发布方式，也就是期望最终用户在安装过程中使用源码来编译生成扩展模块。

随着对二进制码 @code{wheel} 格式支持的引入，以及通过 Python Package Index 至少发布 Windows 和 macOS 版的 wheel 文件，预计此问题将逐步得到解决，因为用户将能够更频繁地安装预编译扩展，而不再需要自己编译它们。

某些用来安装 科学计算类软件包@footnote{https://packaging.python.org/science/} 的解决方案对于尚未提供预编译 @code{wheel} 文件的那些扩展模块来说，也有助于用户在无需进行本机编译的情况下获取二进制码扩展模块。


@subsubheading 参见


Python 软件包用户指南：二进制码扩展@footnote{https://packaging.python.org/extensions/}


@node Python 常用指引,Python 常见问题,安装 Python 模块,Top
@anchor{howto/index doc}@anchor{4336}@anchor{howto/index python-howtos}@anchor{4337}
@chapter Python 常用指引


Python常用指引的形式来源于Linux文档项目的常用指引章节，是一系列独立、指定主题并尝试完全覆盖该主题的文章集合。致力于提供比Python库参考帮助更详尽的文档。

目前，提供了如下指引：

@menu
* 将 Python 2 代码迁移到 Python 3:: 
* 将扩展模块移植到 Python 3:: 
* 用 Python 进行 Curses 编程:: 
* 描述器使用指南:: 
* 函数式编程指引:: 
* 日志 HOWTO:: 
* 日志操作手册:: 
* 正则表达式HOWTO:: 
* 套接字编程指南:: 
* 排序指南:: 
* Unicode 指南:: 
* 如何利用 urllib 包获取网络资源:: 
* Argparse 教程:: 
* ipaddress模块介绍:: 
* Argument Clinic 的用法:: 
* 使用 DTrace 和 SystemTap 检测CPython:: 

@end menu

@node 将 Python 2 代码迁移到 Python 3,将扩展模块移植到 Python 3,,Python 常用指引
@anchor{howto/pyporting doc}@anchor{4338}@anchor{howto/pyporting porting-python-2-code-to-python-3}@anchor{4339}@anchor{howto/pyporting pyporting-howto}@anchor{d4d}
@section 将 Python 2 代码迁移到 Python 3


@*作者: 
Brett Cannon


@subsubheading 摘要



Python 3 是 Python 的未来，但 Python 2 仍处于活跃使用阶段，最好让您的项目在两个主要版本的Python 上都可用。本指南旨在帮助您了解如何最好地同时支持 Python 2 和 3。

如果您希望迁移扩展模块而不是纯 Python 代码，请参阅 @ref{d47,,将扩展模块移植到 Python 3}。

如果你想了解核心 Python 开发者对于 Python 3 的出现有何看法，你可以阅读 Nick Coghlan 的 Python 3 Q & A@footnote{https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html} 或 Brett Cannon 的 为什么要有 Python 3@footnote{https://snarky.ca/why-python-3-exists}.

关于迁移的帮助，你可以查看存档的 python-porting@footnote{https://mail.python.org/pipermail/python-porting/} 邮件列表。

@menu
* 简要说明:: 
* 详情:: 

@end menu

@node 简要说明,详情,,将 Python 2 代码迁移到 Python 3
@anchor{howto/pyporting the-short-explanation}@anchor{433a}
@subsection 简要说明


为了使你的项目与单源Python 2/3兼容，基本步骤如下:


@enumerate 

@item 
只担心支持Python 2.7的问题

@item 
确保你有良好的测试覆盖率（可以用 coverage.py@footnote{https://pypi.org/project/coverage}；@code{python -m pip install coverage}）。

@item 
了解Python 2 和 3之间的区别

@item 
使用 Futurize@footnote{http://python-future.org/automatic_conversion.html} (或Modernize@footnote{https://python-modernize.readthedocs.io/}) 来更新你的代码 (例如`@w{`}python -m pip install future`@w{`})。

@item 
使用 Pylint@footnote{https://pypi.org/project/pylint} 来帮助确保你在Python 3支持上不倒退(@code{python -m pip install pylint})

@item 
使用 caniusepython3@footnote{https://pypi.org/project/caniusepython3} 来找出你的哪些依赖关系阻碍了你对 Python 3 的使用 (@code{python -m pip install caniusepython3})

@item 
一旦你的依赖性不再阻碍你，使用持续集成来确保你与 Python 2 和 3 保持兼容 (tox@footnote{https://pypi.org/project/tox} 可以帮助对多个版本的 Python 进行测试；@code{python -m pip install tox})

@item 
考虑使用可选的静态类型检查，以确保你的类型用法在 Python 2 和 3 中都适用 (例如，使用 mypy@footnote{http://mypy-lang.org/} 来检查你在 Python 2 和 Python 3 中的类型；@code{python -m pip install mypy})。
@end enumerate

@cartouche
@quotation 注解 
注意：使用 @code{python -m pip install} 来确保你发起调用的 @code{pip} 就是当前使用的 Python 所安装的那一个，无论它是系统级的 @code{pip} 还是安装在 @ref{1474,,虚拟环境} 中的。
@end quotation
@end cartouche

@node 详情,,简要说明,将 Python 2 代码迁移到 Python 3
@anchor{howto/pyporting details}@anchor{433b}
@subsection 详情


同时支持Python 2和3的一个关键点是，你可以从**今天**开始！即使你的依赖关系还不支持Python 3，也不意味着你不能现在就对你的代码进行现代化改造以支持Python 3。支持Python 3所需的大多数变化都会使代码更干净，甚至在Python 2的代码中也会使用更新的做法。

另一个关键点是，使你的Python 2代码现代化以支持Python 3在很大程度上是为你自动化的。虽然由于Python 3清晰区分了文本数据与二进制数据，你可能必须做出一些API决定。但现在已经为你完成了大部分低级别的工作，因此至少可以立即从自动化变化中受益。

当你继续阅读关于迁移你的代码以同时支持Python 2和3的细节时，请牢记这些关键点。

@menu
* 删除对Python 2.6及更早版本的支持: 删除对Python 2 6及更早版本的支持. 
* 确保你在你的`@w{`}setup.py`@w{`}文件中指定适当的版本支持: 确保你在你的`@w{`}setup py`@w{`}文件中指定适当的版本支持. 
* 良好的测试覆盖率:: 
* 了解Python 2 和 3之间的区别:: 
* 更新代码:: 
* 防止兼容性退步:: 
* 检查哪些依赖性会阻碍你的过渡:: 
* 更新你的`@w{`}setup.py`@w{`}文件以表示对Python 3的兼容: 更新你的`@w{`}setup py`@w{`}文件以表示对Python 3的兼容. 
* 使用持续集成以保持兼容:: 
* 考虑使用可选的静态类型检查:: 

@end menu

@node 删除对Python 2 6及更早版本的支持,确保你在你的`@w{`}setup py`@w{`}文件中指定适当的版本支持,,详情
@anchor{howto/pyporting drop-support-for-python-2-6-and-older}@anchor{433c}
@subsubsection 删除对Python 2.6及更早版本的支持


虽然你可以让 Python 2.5 与 Python 3 一起工作，但如果你只需要与 Python 2.7 一起工作，那就会 @strong{更加容易}。 如果放弃 Python 2.5 不是一种选择，那么 six@footnote{https://pypi.org/project/six} 项目可以帮助你同时支持 Python 2.5 和 3 (@code{python -m pip install six})。 不过请注意，本 HOWTO 中列出的几乎所有项目都有可能会不再可用。

如果你能够跳过Python 2.5和更早的版本，那么对你的代码所做的必要修改应该看起来和感觉上都是你已经习惯的Python代码。在最坏的情况下，你将不得不使用一个函数而不是一个实例方法，或者不得不导入一个函数而不是使用一个内置的函数，但除此之外，整体的转变应该不会让你感到陌生。

但你的目标应该是只支持 Python 2.7。Python 2.6 不再被免费支持，因此也就没有得到错误修复。这意味着**你**必须解决你在Python 2.6上遇到的任何问题。本HOWTO中提到的一些工具也不支持Python 2.6 (例如，Pylint@footnote{https://pypi.org/project/pylint})，随着时间的推移，这将变得越来越普遍。如果你只支持你必须支持的Python版本，那么对你来说会更容易。

@node 确保你在你的`@w{`}setup py`@w{`}文件中指定适当的版本支持,良好的测试覆盖率,删除对Python 2 6及更早版本的支持,详情
@anchor{howto/pyporting make-sure-you-specify-the-proper-version-support-in-your-setup-py-file}@anchor{433d}
@subsubsection 确保你在你的`@w{`}setup.py`@w{`}文件中指定适当的版本支持


在你的`@w{`}setup.py`@w{`}文件中，你应该有适当的 trove classifier@footnote{https://pypi.org/classifiers} 指定你支持哪些版本的 Python。由于你的项目还不支持 Python 3，你至少应该指定`@w{`}Programming Language :: Python :: 2 :: Only`@w{`}。理想情况下，你还应该指定你所支持的Python的每个主要/次要版本，例如：@code{Programming Language :: Python :: 2.7}。.

@node 良好的测试覆盖率,了解Python 2 和 3之间的区别,确保你在你的`@w{`}setup py`@w{`}文件中指定适当的版本支持,详情
@anchor{howto/pyporting have-good-test-coverage}@anchor{433e}
@subsubsection 良好的测试覆盖率


一旦你的代码支持了你希望的Python 2的最老版本，你将希望确保你的测试套件有良好的覆盖率。一个好的经验法则是，如果你想对你的测试套件有足够的信心，在让工具重写你的代码后出现的任何故障都是工具中的实际错误，而不是你的代码中的错误。如果你想要一个目标数字，试着获得超过80%的覆盖率（如果你发现很难获得好于90%的覆盖率，也不要感到遗憾）。如果你还没有一个测量测试覆盖率的工具，那么推荐使用coverage.py@footnote{https://pypi.org/project/coverage}。

@node 了解Python 2 和 3之间的区别,更新代码,良好的测试覆盖率,详情
@anchor{howto/pyporting learn-the-differences-between-python-2-3}@anchor{433f}
@subsubsection 了解Python 2 和 3之间的区别


一旦你的代码经过了很好的测试，你就可以开始把你的代码移植到 Python 3 上了！ 但是为了充分了解你的代码将发生怎样的变化，以及你在编码时要注意什么，你将会想要了解 Python 3 相比 Python 2 的变化。 通常来说，两个最好的方法是阅读 Python 3 每个版本的 @ref{153,,"What's New"} 文档和 Porting to Python 3@footnote{http://python3porting.com/} 书（在线免费版本）。还有一个来自 Python-Future 项目的便利 cheat sheet@footnote{http://python-future.org/compatible_idioms.html}。

@node 更新代码,防止兼容性退步,了解Python 2 和 3之间的区别,详情
@anchor{howto/pyporting update-your-code}@anchor{4340}
@subsubsection 更新代码


一旦你觉得你知道了 Python 3 与 Python 2 相比有什么不同，就是时候更新你的代码了！ 你可以选择两种工具来自动移植你的代码: Futurize@footnote{http://python-future.org/automatic_conversion.html} 和 Modernize@footnote{https://python-modernize.readthedocs.io/}。 你选择哪个工具将取决于你希望你的代码有多像 Python 3。 Futurize@footnote{http://python-future.org/automatic_conversion.html} 尽力使 Python 3 的习性和做法在 Python 2 中存在，例如，从 Python 3 中回传 @code{bytes} 类型，这样你就可以在 Python 的主要版本之间实现语义上的平等。 另一方面，Modernize@footnote{https://python-modernize.readthedocs.io/} 更加保守，它针对的是 Python 2/3 的子集，直接依靠 six@footnote{https://pypi.org/project/six} 来帮助提供兼容性。 由于 Python 3 是未来，最好考虑 Futurize，以开始适应 Python 3 所引入的、你还不习惯的任何新做法。

无论你选择哪种工具，它们都会更新你的代码，使之在Python 3下运行，同时与你开始使用的Python 2版本保持兼容。根据你想要的保守程度，你可能想先在你的测试套件上运行该工具，并目测差异以确保转换的准确性。在你转换了你的测试套件并验证了所有的测试仍然如期通过后，你就可以转换你的应用程序代码了，因为你知道任何测试失败都是转译的错误。

不幸的是，这些工具不能自动地使你的代码在Python 3下工作，因此有一些东西你需要手动更新以获得对Python 3的完全支持（这些步骤在不同的工具中是必要的）。阅读你选择使用的工具的文档，看看它默认修复了什么，以及它可以选择做什么，以了解哪些将（不）为你修复，哪些你可能必须自己修复（例如，在Modernize中使用`@w{`}io.open()`@w{`}覆写内置的`@w{`}open()`@w{`}函数默认是关闭的）。不过幸运的是，只有几件需要注意的事情，可以说是大问题，如果不注意的话，可能很难调试。

@menu
* 除法:: 
* 文本与二进制数据:: 
* 使用特征检测而不是版本检测:: 

@end menu

@node 除法,文本与二进制数据,,更新代码
@anchor{howto/pyporting division}@anchor{4341}
@subsubsection 除法


在Python 3中，@code{5 / 2 == 2.5`@w{`}而不是`@w{`}2}；所有`@w{`}int`@w{`}数值之间的除法都会产生一个`@w{`}float`@w{`}、这个变化实际上从2002年发布的Python 2.2开始就已经计划好了。从那时起，我们就鼓励用户在所有使用`@w{`}/@code{和}//@code{运算符的文件中添加`@w{`}from __future__ import division}，或者在运行解释器时使用`@w{`}-Q`@w{`}标志。如果你没有这样做，那么你需要检查你的代码并做两件事。


@enumerate 

@item 
添加 @code{from __future__ import division} 到你的文件。

@item 
根据需要更新任何除法运算符，要么使用 @code{//} 来使用向下取整除法，要么继续使用 @code{/} 并得到一个浮点数
@end enumerate

之所以没有简单地将 @code{/} 自动翻译成 @code{//}，是因为如果一个对象定义了一个 @code{__truediv__} 方法，但没有定义 @code{__floordiv__}，那么你的代码就会运行失败（例如，一个用户定义的类用 @code{/} 来表示一些操作，但没有用 @code{//} 来表示同样的事情或根本没有定义）。

@node 文本与二进制数据,使用特征检测而不是版本检测,除法,更新代码
@anchor{howto/pyporting text-versus-binary-data}@anchor{4342}
@subsubsection 文本与二进制数据


在Python 2中，你可以对文本和二进制数据都使用`@w{`}str`@w{`}类型。不幸的是，这两个不同概念的融合可能会导致脆弱的代码，有时对任何一种数据都有效，有时则无效。如果人们没有明确说明某种接受`@w{`}str`@w{`}东西可以接受文本或二进制数据，而不是一种特定的类型，这也会导致API的混乱。这使情况变得复杂，特别是对于任何支持多种语言的人来说，因为API在声称支持文本数据时不会显式支持`@w{`}unicode`@w{`}。

为了使文本和二进制数据之间的区别更加清晰和明显，Python 3做了大多数在互联网时代创建的语言所做的事情，使文本和二进制数据成为不能盲目混合在一起的不同类型（Python早于互联网的广泛使用）。对于任何只处理文本或只处理二进制数据的代码，这种分离并不构成问题。但是对于必须处理这两种数据的代码来说，这确实意味着你现在可能必须关心你何时使用文本或二进制数据，这就是为什么这不能完全自动化迁移。

首先，你需要决定哪些 API 接受文本，哪些接受二进制（由于保持代码工作的难度，@strong{强烈} 建议你不要设计同时接受两种数据的 API；如前所述，这很难做得好）。在 Python 2 中，这意味着要确保处理文本的 API 能够与 @code{unicode} 一起工作，而处理二进制数据的 API 能够与 Python 3 中的 @code{bytes} 类型一起工作（在 Python 2 中是 @code{str} 的一个子集，在 Python 2 中作为 @code{bytes} 类型的别名）。通常最大的问题是意识到哪些方法同时存在于 Python 2 和 3 的哪些类型上 (对于文本来说，Python 2 中是 @code{unicode}，Python 3 中是 @code{str}，对于二进制来说，Python 2 中是 @code{str}/@code{bytes}，Python 3 中是`@w{`}bytes`@w{`})。 下表列出了每个数据类型在 Python 2 和 3 中的 @strong{独特} 的方法 (例如，@code{decode()} 方法在 Python 2 或 3 中的等价二进制数据类型上是可用的，但是它不能在 Python 2 和 3 之间被文本数据类型一致使用，因为 Python 3 中的 @code{str} 没有这个方法)。 请注意，从 Python 3.5 开始，@code{__mod__} 方法被添加到 bytes 类型中。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxx} 
@item

@strong{文本数据}

@tab

@strong{二进制数据}

@item



@tab

decode

@item

encode

@tab

@item

format

@tab

@item

isdecimal

@tab

@item

isnumeric

@tab

@end multitable


通过在你的代码边缘对二进制数据和文本进行编码和解码，可以使这种区分更容易处理。这意味着，当你收到二进制数据的文本时，你应该立即对其进行解码。而如果你的代码需要将文本作为二进制数据发送，那么就尽可能晚地对其进行编码。这使得你的代码在内部只与文本打交道，从而不必再去跟踪你所处理的数据类型。

下一个问题是确保你知道你的代码中的字符串字头是代表文本还是二进制数据。你应该给任何呈现二进制数据的字面符号添加一个`@w{`}b`@w{`}前缀。对于文本，你应该给文本字面添加一个`@w{`}u`@w{`}前缀。（有一个 @ref{0,,__future__} 导入来强制所有未指定的字头为Unicode，但实际使用情况表明它并不像给所有字头显式添加一个`@w{`}b`@w{`}或`@w{`}u`@w{`}前缀那样有效）

作为这种二分法的一部分，你还需要小心打开文件。除非你一直在 Windows 上工作，否则你有可能在打开二进制文件时没有一直费心地添加`@w{`}b`@w{`}模式 （例如，用`@w{`}rb`@w{`}进行二进制读取）。 在 Python 3 下，二进制文件和文本文件显然是不同的，而且是相互不兼容的；详见 @ref{a1,,io} 模块。因此，你必须**决定**一个文件是用于二进制访问（允许读取和/或写入二进制数据）还是文本访问（允许读取和/或写入文本数据）。你还应该使用 @ref{757,,io.open()} 来打开文件，而不是内置的 @ref{16f,,open()} 函数，因为 @ref{a1,,io} 模块从 Python 2 到 3 是一致的，而内置的 @ref{16f,,open()} 函数则不是 (在 Python 3 中它实际上是 @ref{757,,io.open()})。不要理会使用 @ref{110c,,codecs.open()} 的过时做法，因为这只是为了保持与 Python 2.5 的兼容性。

在Python 2和3中，@code{str`@w{`}和`@w{`}bytes`@w{`}的构造函数对相同的参数有不同的语义。在Python 2中，传递一个整数给`@w{`}bytes}，你将得到整数的字符串表示：@code{bytes(3) == '3'}。但是在Python 3中，一个整数参数传递给`@w{`}bytes`@w{`}将给你一个与指定的整数一样长的bytes对象，其中充满了空字节：@code{bytes(3) == b'\x00\x00\x00'}。当把bytes对象传给`@w{`}str`@w{`}时，类似的担心是必要的。 在Python 2中，你只是又得到了该bytes对象：@code{str(b'3') == b'3'}。但是在Python 3中，你得到bytes对象的字符串表示：@code{str(b'3') == "b'3'"}。

最后，二进制数据的索引需要仔细处理（切片 @strong{不需要} 任何特殊处理）。在 Python 2 中 @code{b'123'[1] == b'2'}，而在 Python 3 中`@w{`}b'123'[1] == 50`@w{`}。 因为二进制数据只是二进制数的集合，Python 3 会返回你索引的字节的整数值。 但是在 Python 2 中，因为 @code{bytes == str}，索引会返回一个单项的字节片断。 six@footnote{https://pypi.org/project/six} 项目有一个名为 @code{six.indexbytes()} 的函数，它将像在 Python 3 中一样返回一个整数: @code{six.indexbytes(b'123', 1)}。

总结一下：


@enumerate 

@item 
决定你的API中哪些采用文本，哪些采用二进制数据

@item 
确保你对文本工作的代码也能对`@w{`}unicode`@w{`}工作，对二进制数据的代码在Python 2中能对`@w{`}bytes`@w{`}工作（关于每种类型不能使用的方法，见上表）。

@item 
用`@w{`}b`@w{`}前缀标记所有二进制字词，用`@w{`}u`@w{`}前缀标记文本字词

@item 
尽快将二进制数据解码为文本，尽可能晚地将文本编码为二进制数据

@item 
使用 @ref{757,,io.open()} 打开文件，并确保在适当时候指定 @code{b} 模式。

@item 
在对二进制数据进行索引时要小心
@end enumerate

@node 使用特征检测而不是版本检测,,文本与二进制数据,更新代码
@anchor{howto/pyporting use-feature-detection-instead-of-version-detection}@anchor{4343}
@subsubsection 使用特征检测而不是版本检测


你不可避免地会有一些代码需要根据运行的 Python 版本来选择要做什么。做到这一点的最好方法是对你运行的 Python 版本是否支持你所需要的东西进行特征检测。如果由于某种原因这不起作用，那么你应该让版本检测针对 Python 2 而不是 Python 3。为了帮助解释这个问题，让我们看一个例子。

假设你需要访问 @ref{9a,,importlib} 的一个功能，该功能自Python 3.3开始在Python的标准库中提供，并且通过PyPI上的 importlib2@footnote{https://pypi.org/project/importlib2} 提供给Python 2。你可能会想写代码来访问例如 @ref{9b,,importlib.abc} 模块，方法如下:

@example
import sys

if sys.version_info[0] == 3:
    from importlib import abc
else:
    from importlib2 import abc
@end example

这段代码的问题是，当Python 4出来的时候会发生什么？最好是将Python 2作为例外情况，而不是Python 3，并假设未来的Python版本与Python 3的兼容性比Python 2更强:

@example
import sys

if sys.version_info[0] > 2:
    from importlib import abc
else:
    from importlib2 import abc
@end example

不过，最好的解决办法是根本不做版本检测，而是依靠特征检测。这就避免了任何潜在的版本检测错误的问题，并有助于保持你对未来的兼容:

@example
try:
    from importlib import abc
except ImportError:
    from importlib2 import abc
@end example

@node 防止兼容性退步,检查哪些依赖性会阻碍你的过渡,更新代码,详情
@anchor{howto/pyporting prevent-compatibility-regressions}@anchor{4344}
@subsubsection 防止兼容性退步


一旦你完全翻译了你的代码，使之与 Python 3 兼容，你将希望确保你的代码不会退步，不会在 Python 3上停止工作。如果你有一个依赖关系阻碍了你目前在Python 3上的实际运行，那就更是如此了。

为了帮助保持兼容，你创建的任何新模块都应该在其顶部至少有以下代码块:

@example
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
@end example

你也可以在运行Python 2时使用`@w{`}-3`@w{`}标志，对你的代码在执行过程中引发的各种兼容性问题进行警告。如果你用`@w{`}-Werror`@w{`}把警告变成错误，那么你可以确保你不会意外地错过一个警告。

你也可以使用 Pylint@footnote{https://pypi.org/project/pylint} 项目和它的`@w{`}--py3k`@w{`}标志来提示你的代码，当你的代码开始偏离 Python 3 的兼容性时，就会收到警告。这也避免了你不得不定期在你的代码上运行 Modernize@footnote{https://python-modernize.readthedocs.io/} 或 Futurize@footnote{http://python-future.org/automatic_conversion.html} 来捕捉兼容性的退步。这确实要求你只支持Python 2.7和Python 3.4或更新的版本，因为这是Pylint支持的最小Python版本。

@node 检查哪些依赖性会阻碍你的过渡,更新你的`@w{`}setup py`@w{`}文件以表示对Python 3的兼容,防止兼容性退步,详情
@anchor{howto/pyporting check-which-dependencies-block-your-transition}@anchor{4345}
@subsubsection 检查哪些依赖性会阻碍你的过渡


在你使你的代码与 Python 3 兼容**之后**，你应该开始关心你的依赖关系是否也被移植了。 caniusepython3@footnote{https://pypi.org/project/caniusepython3} 项目的建立是为了帮助你确定哪些项目——直接或间接地——阻碍了你对Python 3的支持。它既有一个命令行工具，也有一个在https://caniusepython3.com的网页界面。

该项目还提供了一些代码，你可以将其集成到你的测试套件中，这样，当你不再有依赖关系阻碍你使用Python 3时，你将有一个失败的测试。这使你不必手动检查你的依赖性，并在你可以开始在Python 3上运行时迅速得到通知。

@node 更新你的`@w{`}setup py`@w{`}文件以表示对Python 3的兼容,使用持续集成以保持兼容,检查哪些依赖性会阻碍你的过渡,详情
@anchor{howto/pyporting update-your-setup-py-file-to-denote-python-3-compatibility}@anchor{4346}
@subsubsection 更新你的`@w{`}setup.py`@w{`}文件以表示对Python 3的兼容


一旦你的代码在 Python 3 下工作，你应该更新你`@w{`}setup.py`@w{`}中的分类器，使其包含`@w{`}Programming Language :: Python :: 3`@w{`}并不指定单独的 Python 2 支持。这将告诉使用你的代码的人，你支持Python 2 @strong{和} 3。理想情况下，你也希望为你现在支持的Python的每个主要/次要版本添加分类器。

@node 使用持续集成以保持兼容,考虑使用可选的静态类型检查,更新你的`@w{`}setup py`@w{`}文件以表示对Python 3的兼容,详情
@anchor{howto/pyporting use-continuous-integration-to-stay-compatible}@anchor{4347}
@subsubsection 使用持续集成以保持兼容


一旦你能够完全在Python 3下运行，你将希望确保你的代码总是在Python 2和3下工作。在多个Python解释器下运行测试的最好工具可能是 tox@footnote{https://pypi.org/project/tox} 。然后你可以将 tox 与你的持续集成系统集成，这样你就不会意外地破坏对 Python 2 或 3 的支持。

你可能还想在 Python 3 解释器中使用`@w{`}-bb`@w{`}标志，以便在你将bytes与string或bytes与int进行比较时触发一个异常（后者从 Python 3.5 开始可用）。默认情况下，类型不同的比较只是简单地返回`@w{`}False`@w{`}，但是如果你在文本/二进制数据处理或字节的索引分离中犯了一个错误，你就不容易发现这个错误。当这些类型的比较发生时，这个标志会触发一个异常，使错误更容易被发现。

基本上就是这样了! 在这一点上，你的代码库同时与 Python 2 和 3 兼容。你的测试也将被设置为不会意外地破坏 Python 2 或 3 的兼容性，无论你在开发时通常在哪个版本下运行测试。

@node 考虑使用可选的静态类型检查,,使用持续集成以保持兼容,详情
@anchor{howto/pyporting consider-using-optional-static-type-checking}@anchor{4348}
@subsubsection 考虑使用可选的静态类型检查


另一个帮助移植你的代码的方法是在你的代码上使用静态类型检查器，如 mypy@footnote{http://mypy-lang.org/} 或 pytype@footnote{https://github.com/google/pytype}。这些工具可以用来分析你的代码，就像它在Python 2下运行一样，然后你可以第二次运行这个工具，就像你的代码在Python 3下运行一样。通过像这样两次运行静态类型检查器，你可以发现你是否错误地使用了二进制数据类型，例如在Python的一个版本中与另一个版本相比。如果你在你的代码中添加了可选的类型提示，你也可以明确说明你的API是使用文本数据还是二进制数据，这有助于确保在两个版本的Python中所有的功能都符合预期。

@node 将扩展模块移植到 Python 3,用 Python 进行 Curses 编程,将 Python 2 代码迁移到 Python 3,Python 常用指引
@anchor{howto/cporting doc}@anchor{4349}@anchor{howto/cporting cporting-howto}@anchor{d47}@anchor{howto/cporting porting-extension-modules-to-python-3}@anchor{434a}@anchor{howto/cporting why-python-3-exists}@anchor{434b}
@section 将扩展模块移植到 Python 3


对于将扩展模块移植到 Python 3，我们推荐下列资源：


@itemize *

@item 
@emph{Supporting Python 3: An in-depth guide} 中的 Migrating C extensions@footnote{http://python3porting.com/cextensions.html} 这一章，这本书介绍了如何从 Python 2 迁移到 Python 3，包括指导读者如何移植扩展模块。

@item 
@emph{py3c} 项目中的 Porting guide@footnote{https://py3c.readthedocs.io/en/latest/guide.html} 提供了有关支持代码的指导性建议。

@item 
Cython@footnote{http://cython.org/} 和 CFFI@footnote{https://cffi.readthedocs.io/en/latest/} 库提供了对于 Python 的 C API 的抽象。 扩展大都需要进行重写以使用两者中的一个，然后就可以通过库来处理各种 Python 版本和实现之间的差异。
@end itemize

@node 用 Python 进行 Curses 编程,描述器使用指南,将扩展模块移植到 Python 3,Python 常用指引
@anchor{howto/curses doc}@anchor{434c}@anchor{howto/curses cffi}@anchor{434d}@anchor{howto/curses curses-howto}@anchor{22db}@anchor{howto/curses curses-programming-with-python}@anchor{434e}
@section 用 Python 进行 Curses 编程


@*作者: 
A.M. Kuchling, Eric S. Raymond


@*发布版本: 
2.04


@subsubheading 摘要



本文档介绍了如何使用 @ref{2b,,curses} 扩展模块控制文本模式的显示。

@menu
* curses 是什么？:: 
* 开始和结束 curses 应用程序:: 
* 窗口和面板:: 
* 显示文字:: 
* 用户输入:: 
* 更多的信息:: 

@end menu

@node curses 是什么？,开始和结束 curses 应用程序,,用 Python 进行 Curses 编程
@anchor{howto/curses what-is-curses}@anchor{434f}
@subsection curses 是什么？


curses 库为基于文本的终端提供了独立于终端的屏幕绘制和键盘处理功能；这些终端包括 VT100，Linux 控制台以及各种程序提供的模拟终端。显示终端支持各种控制代码以执行常见的操作，例如移动光标，滚动屏幕和擦除区域。不同的终端使用相差很大的代码，并且往往有自己的小怪癖。

在普遍使用图形显示的世界中，人们可能会问“为什么自找要麻烦”？毕竟字符单元显示终端确实是一种过时的技术，但是在某些领域中，能够用它们做花哨的事情仍然很有价值。一个小众市场是在不运行 X server 的小型或嵌入式 Unix 上。另一个是在提供图形支持之前，可能需要运行的工具，例如操作系统安装程序和内核配置程序。

curses 库提供了相当基础的功能，为程序员提供了包含多个非重叠文本窗口的显示的抽象。窗口的内容可以通过多种方式更改---添加文本，擦除文本，更改其外观---以及curses库将确定需要向终端发送哪些控制代码以产生正确的输出。 curses并没有提供诸多用户界面概念，例如按钮，复选框或对话框。如果需要这些功能，请考虑用户界面库，例如 Urwid@footnote{https://pypi.org/project/urwid/} 。

curses 库最初是为BSD Unix 编写的。 后来 AT&T 的Unix System V 版本加入了许多增强功能和新功能。如今BSD curses已不再维护，被ncurses取代，ncurses是 AT&T 接口的开源实现。如果使用的是 Linux 或 FreeBSD 等开源Unix系统，则几乎肯定会使用ncurses。由于大多数当前的商业Unix版本都基于System V代码，因此这里描述的所有功能可能都可用。但是，某些专有Unix所带来的较早版本的curses可能无法支持所有功能。

Python 的 Windows 版不包括 @ref{2b,,curses} 模块。 一个可用的移植版本是 UniCurses@footnote{https://pypi.org/project/UniCurses}。

@menu
* Python 的 curses 模块:: 

@end menu

@node Python 的 curses 模块,,,curses 是什么？
@anchor{howto/curses the-python-curses-module}@anchor{4350}
@subsubsection Python 的 curses 模块


此 Python 模块相当简单地封装了 curses 提供的 C 函数；如果你已经熟悉在 C 语言中使用 curses 编程，把这些知识转移的 Python 是非常容易的。最大的差异在于 Python 中的接口通过把不同的 C 函数合并来让事情变得更简单，比如 @code{addstr()}、@code{mvaddstr()} 和 @code{mvwaddstr()} 三个 C 函数被并入 @ref{22ee,,addstr()} 这一个方法。下文中会描述更多的细节。

本 HOWTO 是关于使用 curses 和 Python 编写文本模式程序的概述。它并不被设计为一个 curses API 的完整指南；如需完整指南，请参见 ncurses 的 Python 库指南章节和 ncurses 的 C 手册页。相对地，本 HOWTO 将会给你一些基本思路。

@node 开始和结束 curses 应用程序,窗口和面板,curses 是什么？,用 Python 进行 Curses 编程
@anchor{howto/curses starting-and-ending-a-curses-application}@anchor{4351}
@subsection 开始和结束 curses 应用程序


在做任何事情之前，curses 必须先被初始化。可以通过调用函数 @ref{22f5,,initscr()} 来实现，它将查明终端的类型，向终端发送任何必须的设置代码，并创建多种内部数据结构。如果此操作成功，@code{initscr()} 将会返回一个代表整个屏幕的窗口对象；它通常会遵循对应的 C 变量名被称作 @code{stdscr}：

@example
import curses
stdscr = curses.initscr()
@end example

使用 curses 的应用程序通常会关闭按键自动上屏，目的是读取按键并只在特定情况下展示它们。这需要调用函数 @ref{2314,,noecho()}：

@example
curses.noecho()
@end example

应用程序也会广泛地需要立即响应按键，而不需要按下回车键；这被称为 “cbreak” 模式，与通常的缓冲输入模式相对：

@example
curses.cbreak()
@end example

终端通常会以多字节转义序列的形式返回特殊按键，比如光标键和导航键比如 Page Up 键和 Home 键。尽管你可以编写你的程序来应对这些序列，curses 能够代替你做到这件事，返回一个特殊值比如 @code{curses.KEY_LEFT}。为了让 curses 做这项工作，你需要启用 keypad 模式：

@example
stdscr.keypad(True)
@end example

终止一个 curses 应用程序比建立一个容易得多，你只需要调用：

@example
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
@end example

来还原对终端作出的 curses 友好设置。然后，调用函数 @ref{22f2,,endwin()} 来将终端还原到它的原始操作模式：

@example
curses.endwin()
@end example

调试一个 curses 应用程序时常会发生，一个应用程序还未能还原终端到原本的状态就意外退出了，这会搅乱你的终端。在 Python 中这常常会发生在你的代码中有 bug 并引发了一个未捕获的异常。当你尝试输入时按键不会上屏，这使得使用终端变得困难。

在 Python 中你可以避免这些复杂问题并让调试变得更简单，只需要导入 @ref{3cc,,curses.wrapper()} 函数并像这样使用它：

@example
from curses import wrapper

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # This raises ZeroDivisionError when i == 10.
    for i in range(0, 11):
        v = i-10
        stdscr.addstr(i, 0, '10 divided by @{@} is @{@}'.format(v, 10/v))

    stdscr.refresh()
    stdscr.getkey()

wrapper(main)
@end example

函数 @ref{3cc,,wrapper()} 接受一个可调用对象并首先进行上述初始化过程，在终端支持着色时还会初始化颜色。接着 @code{wrapper()} 运行你提供的可调用对象。当该可调用对象返回时，@code{wrapper()} 会还原终端到初始状态。该可调用对象会在 @ref{e3f,,try}...@ref{c19,,except} 这样的结构内被调用，当它捕获到异常时，会先还原终端再重新引发这个异常。所以你的终端不会因为异常而被留在一个搞笑的状态，你也可以正常阅读异常消息和回溯信息。

@node 窗口和面板,显示文字,开始和结束 curses 应用程序,用 Python 进行 Curses 编程
@anchor{howto/curses windows-and-pads}@anchor{4352}
@subsection 窗口和面板


窗口是 curses 中的基本抽象。一个窗口对象表示了屏幕上的一个矩形区域，并且提供方法来显示文本、擦除文本、允许用户输入字符串等等。

函数 @ref{22f5,,initscr()} 返回的 @code{stdscr} 对象覆盖整个屏幕。许多程序可能只需要这一个窗口，但你可能希望把屏幕分割为多个更小的窗口，来分别重绘或者清除它们。函数 @ref{2312,,newwin()} 根据给定的尺寸创建一个新窗口，并返回这个新的窗口对象：

@example
begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
@end example

注意 curses 使用的坐标系统与寻常的不同。坐标始终是以 @emph{y,x} 的顺序传递，并且左上角是坐标 (0,0)。这打破了正常的坐标处理约定，即 @emph{x} 坐标在前。这是一个与其他计算机应用程序糟糕的差异，但这从 curses 最初被编写出来就已是它的一部分，现在想要修改它已为时已晚。

你的应用程序能够查明屏幕的尺寸，@code{curses.LINES} 和 @code{curses.COLS} 分别代表了 @emph{y} 和 @emph{x} 方向上的尺寸。合理的坐标应位于 @code{(0,0)} 到 @code{(curses.LINES - 1, curses.COLS - 1)} 范围内。

当你调用一个方法来显示或擦除文本时，效果并不会立即显示。相反，你必须调用窗口对象的 @ref{22f0,,refresh()} 方法来更新屏幕。

这是因为 curses 最初是为 300 波特的龟速终端连接编写的；在这些终端上，压制重绘屏幕的时间就非常重要。相对地，当你调用 @code{refresh()} 时，curses 会累积屏幕的修改并以效率最高的方式显示它们。打个比方，如果你的程序在一个窗口内显示一些文本然后清楚了这个窗口，那么这些原始文本不需要被发送，因为它们甚至不曾能被看见。

在实践中，显式地告诉 curses 来重绘一个窗口并不会太复杂化 curses 编程。大部分程序会显示一堆内容然后等待按键或者其他某些用户侧动作。你要做的事情就是，保证屏幕在暂停并等待用户输入前被重绘，只需要先调用 @code{stdscr.refresh()} 或者其他相关窗口的 @code{refresh()} 方法。

一个面板是一种特殊的窗口，它可以比实际的显示屏幕更大，并且能只显示它的一部分。创建面板需要指定面板的高度和宽度，但刷新一个面板需要给出屏幕坐标和面板的需要显示的局部。

@example
pad = curses.newpad(100, 100)
# These loops fill the pad with letters; addch() is
# explained in the next section
for y in range(0, 99):
    for x in range(0, 99):
        pad.addch(y,x, ord('a') + (x*x+y*y) % 26)

# Displays a section of the pad in the middle of the screen.
# (0,0) : coordinate of upper-left corner of pad area to display.
# (5,5) : coordinate of upper-left corner of window area to be filled
#         with pad content.
# (20, 75) : coordinate of lower-right corner of window area to be
#          : filled with pad content.
pad.refresh( 0,0, 5,5, 20,75)
@end example

此 @code{refresh()} 调用会在屏幕坐标 (5,5) 到坐标 (20,75) 的矩形范围内显示面板的一个部分，被显示的部分在面板上的坐标是 (0,0)。除了上述差异，面板与常规的窗口相同，也支持相同的方法。

如果你在屏幕上有多个窗口和面板，有一个更有效率的方法来更新窗口，避免每个部分单独更新时烦人的屏幕闪烁。@code{refresh()} 实际上做了两件事：


@enumerate 

@item 
调用每个窗口的  @ref{22ef,,noutrefresh()} 方法来更新一个表达屏幕期望状态的底层的数据结构。

@item 
调用函数 @ref{22ed,,doupdate()} 来改变物理屏幕来符合这个数据结构中记录的期望状态。
@end enumerate

你可以改为调用在多个窗口上 @code{noutrefresh()} 方法来更新该数据结构，然后调用函数 @code{doupdate()} 来更新屏幕。

@node 显示文字,用户输入,窗口和面板,用 Python 进行 Curses 编程
@anchor{howto/curses displaying-text}@anchor{4353}
@subsection 显示文字


从一名 C 语言程序员的视角来看，curses 有时看起来就像是一堆略有差异的函数组成的扭曲迷宫。举个例子，@code{addstr()} 在 @code{stdscr} 窗口的当前光标位置显示一个字符串，而 @code{mvaddstr()} 则是先移动到一个给定的 y,x 坐标再显示字符串。@code{waddstr()} 与 @code{addstr()} 类似，但允许指定一个窗口而非默认的 @code{stdscr}。@code{mvwaddstr()} 允许同时指定一个窗口和一个坐标。

幸运的是，Python 接口隐藏了所有这些细节。@code{stdscr} 和其他任何窗口一样是一个窗口对象，并且诸如 @ref{22ee,,addstr()} 之类的方法接受多种参数形式。通常有四种形式。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

形式

@tab

描述

@item

@emph{str} 或 @emph{ch}

@tab

在当前位置显示字符串 @emph{str} 或字符 @emph{ch}

@item

@emph{str} 或 @emph{ch}, @emph{attr}

@tab

在当前位置使用 @emph{attr} 属性显示字符串 @emph{str} 或字符 @emph{ch}

@item

@emph{y}, @emph{x}, @emph{str} 或 @emph{ch}

@tab

移动到窗口内的 @emph{y,x} 位置，并显示 @emph{str} 或 @emph{ch}

@item

@emph{y}, @emph{x}, @emph{str} 或 @emph{ch}, @emph{attr}

@tab

移至窗口内的 @emph{y,x} 位置，并使用 @emph{attr} 属性显示 @emph{str} 或 @emph{ch}

@end multitable


属性允许以突出显示形态显示文本，比如加粗、下划线、反相或添加颜色。这些属性将来下一小节细说。

方法 @ref{22ee,,addstr()} 接受一个 Python 字符串或字节串作为用于显示的值。字节串的内容会被原样发送到终端。字符串会使用窗口的 @code{encoding} 属性值编码为字节，它默认为 @ref{4b4,,locale.getpreferredencoding()} 返回的系统默认编码。

方法 @ref{232d,,addch()} 接受一个字符，可以是长度为 1 的字符串，长度为 1 的字节串或者一个整数。

对于特殊扩展字符有一些常量，这些常量是大于 255 的整数。比如，@code{ACS_PLMINUS} 是一个 “加减” 符号，@code{ACS_ULCORNER} 是一个框的左上角（方便绘制边界）。你也可以使用正确的 Unicode 字符。

窗口会记住上次操作之后光标所在位置，所以如果你忽略 @emph{y,x} 坐标，字符串和字符会出现在上次操作结束的位置。你也可以通过 @code{move(y,x)} 的方法来移动光标。因为一些终端始终会显示一个闪烁的光标，你可能会想要保证光标处于一些不会让人感到分心的位置。在看似随机的位置出现一个闪烁的光标会令人非常迷惑。

如果你的应用程序完全不需要一个闪烁的光标，你可以调用 @code{curs_set(False)} 来使它隐形。为与旧版本 curses 的兼容性的关系，有函数 @code{leaveok(bool)} 作为 @ref{22e7,,curs_set()} 的等价替换。如果 @emph{bool} 是真值，curses 库会尝试移除闪烁光标，并且你也不必担心它会留在一些奇怪的位置。

@menu
* 属性和颜色:: 

@end menu

@node 属性和颜色,,,显示文字
@anchor{howto/curses attributes-and-color}@anchor{4354}
@subsubsection 属性和颜色


字符可以以不同的方式显示。基于文本的应用程序常常以反相显示状态行，一个文本查看器可能需要突出显示某些单词。为了支持这种用法，curses 允许你为屏幕上的每个单元指定一个属性值。

属性值是一个整数，它的每一个二进制位代表一个不同的属性。你可以尝试以多种不属性位组合来显示文本，但 curses 不保证所有的组合都是有效的，或者看上去有明显不同。这一点取决于用户终端的能力，所以最稳妥的方式是只采用最常见的有效属性，见下表。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

描述

@item

@code{A_BLINK}

@tab

闪烁文本

@item

@code{A_BOLD}

@tab

超亮或粗体文本

@item

@code{A_DIM}

@tab

半明亮文本

@item

@code{A_REVERSE}

@tab

反相显示文本

@item

@code{A_STANDOUT}

@tab

可用的最佳突出显示模式

@item

@code{A_UNDERLINE}

@tab

带下划线的文本

@end multitable


所以，为了在屏幕顶部显示一个反相的状态行，你可以这么编写：

@example
stdscr.addstr(0, 0, "Current mode: Typing mode",
              curses.A_REVERSE)
stdscr.refresh()
@end example

curses 库还支持在提供了颜色功能的终端上显示颜色的功能。最常见的提供颜色的终端很可能是 Linux 控制台，采用了 xterms 配色方案。

为了使用颜色，你必须在调用完函数 @ref{22f5,,initscr()} 后尽快调用函数 @ref{2320,,start_color()}，来初始化默认颜色集 (@ref{3cc,,curses.wrapper()} 函数自动完成了这一点)。 当它完成后，如果使用中的终端支持显示颜色， @ref{22fd,,has_colors()} 会返回真值。 （注意：curses 使用美式拼写 “color”，而不是英式／加拿大拼写 “colour”。如果你习惯了英式拼写，你需要避免自己在这些函数上拼写错误。）

curses 库维护一个有限数量的颜色对，包括一个前景（文本）色和一个背景色。你可以使用函数  @ref{22e5,,color_pair()} 获得一个颜色对对应的属性值。它可以通过按位或运算与其他属性，比如 @code{A_REVERSE} 组合。但再说明一遍，这种组合并不保证在所有终端上都有效。

一个样例，用 1 号颜色对显示一行文本：

@example
stdscr.addstr("Pretty text", curses.color_pair(1))
stdscr.refresh()
@end example

如前所述， 颜色对由前景色和背景色组成。  @code{init_pair(n, f, b)} 函数可改变颜色对 @emph{n} 的定义 为前景色 f 和背景色 b。 颜色对 0 硬编码为黑底白字，不能改变。

颜色已经被编号，并且当其激活 color 模式时 @code{start_color()} 会初始化 8 种基本颜色。 它们是: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan 和 7:white。 @ref{2b,,curses} 模块为这些颜色定义了相应的名称常量: @code{curses.COLOR_BLACK}, @code{curses.COLOR_RED} 等等。

让我们来做个综合练习。 要将颜色 1 改为红色文本白色背景，你应当调用:

@example
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
@end example

当你改变一个颜色对时，任何已经使用该颜色对来显示的文本将会更改为新的颜色。 你还可以这样来显示新颜色的文本:

@example
stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))
@end example

某些非常花哨的终端可以将实际颜色定义修改为给定的 RGB 值。 这允许你将通常为红色的 1 号颜色改成紫色或蓝色或者任何你喜欢的颜色。 不幸的是，Linux 控制台不支持此特性，所以我无法尝试它，也无法提供任何示例。 想要检查你的终端是否能做到你可以调用 @ref{22e1,,can_change_color()}，如果有此功能则它将返回 @code{True}。 如果你幸运地拥有一个如此优秀的终端，请查询你的系统的帮助页面来了解详情。

@node 用户输入,更多的信息,显示文字,用 Python 进行 Curses 编程
@anchor{howto/curses user-input}@anchor{4355}
@subsection 用户输入


C curses 库提供了非常简单的输入机制。 Python 的 @ref{2b,,curses} 模块添加了一个基本的文本输入控件。 （其他的库例如 Urwid@footnote{https://pypi.org/project/urwid/} 拥有更丰富的控件集。）

有两个方法可以从窗口获取输入:


@itemize *

@item 
@ref{22f9,,getch()} 会刷新屏幕然后等待用户按键，如果之前调用过 @ref{22f1,,echo()} 还会显示所按的键。 你还可以选择指定一个坐标以便在暂停之前让光标移动到那里。

@item 
@ref{2346,,getkey()} 将做同样的事但是会把整数转换为字符串。 每个字符将返回为长度为 1 个字符的字符串，特殊键例如函数键将返回包含键名的较长字符串例如 @code{KEY_UP} 或 @code{^G}。
@end itemize

使用 @ref{235c,,nodelay()} 窗口方法可以做到不等待用户。 在 @code{nodelay(True)} 之后，窗口的 @code{getch()} 和 @code{getkey()} 将成为非阻塞的。 为表明输入未就绪，@code{getch()} 会返回 @code{curses.ERR} (值为 -1) 而 @code{getkey()} 会引发异常。 此外还有 @ref{2301,,halfdelay()} 函数，它可被用来（实际地）在每个 @code{getch()} 上设置一个计时器；如果在指定的延迟内没有输入可用（以十分之一秒为单位），curses 将引发异常。

@code{getch()} 方法返回一个整数；如果数值在 0 到 255 之间，它代表所按下键的 ASCII 码。 大于 255 的值为特殊键例如 Page Up, Home 或方向键等。 你可以将返回的值与 @code{curses.KEY_PPAGE}, @code{curses.KEY_HOME} 或 @code{curses.KEY_LEFT} 等常量做比较。 你的程序主循环看起来可能是这样:

@example
while True:
    c = stdscr.getch()
    if c == ord('p'):
        PrintDocument()
    elif c == ord('q'):
        break  # Exit the while loop
    elif c == curses.KEY_HOME:
        x = y = 0
@end example

@ref{2c,,curses.ascii} 模块提供了一些 ASCII 类成员函数，它们接受整数或长度为 1 个字符的字符串参数；这些函数在为这样的循环编写更具可读性的测试时可能会很有用。 它还提供了一些转换函数，它们接受整数或长度为 1 个字符的字符串参数并返回同样的类型。 例如，@ref{2390,,curses.ascii.ctrl()} 返回与其参数相对应的控制字符。

还有一个可以提取整个字符串的方法 @ref{2349,,getstr()}。 它并不经常被使用，因为它的功能相当受限；可用的编辑键只有 Backspace 和 Enter 键，它们会结束字符串。 也可以选择限制为固定数量的字符。

@example
curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line
s = stdscr.getstr(0,0, 15)
@end example

@ref{2e,,curses.textpad} 模块提供了一个文本框，它支持类似 Emacs 的键绑定集。 @ref{2376,,Textbox} 类的各种方法支持带输入验证的编辑及包含或不包含末尾空格地收集编辑结果。 下面是一个例子:

@example
import curses
from curses.textpad import Textbox, rectangle

def main(stdscr):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

    editwin = curses.newwin(5,30, 2,1)
    rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
    stdscr.refresh()

    box = Textbox(editwin)

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()
@end example

请查看 @ref{2e,,curses.textpad} 的库文档了解更多细节。

@node 更多的信息,,用户输入,用 Python 进行 Curses 编程
@anchor{howto/curses for-more-information}@anchor{4356}
@subsection 更多的信息


本 HOWTO 没有涵盖一些进阶主题，例如读取屏幕的内容或从 xterm 实例捕获鼠标事件等，但是 @ref{2b,,curses} 模块的 Python 库文档页面现在已相当完善。 接下来你应当去浏览一下其中的内容。

如果你对 curses 函数的细节行为有疑问，请查看你的 curses 实现版本的说明页面，不论它是 ncurses 还是特定 Unix 厂商的版本。 说明页面将记录任何具体问题，并提供所有函数、属性以及可用 @code{ACS_*} 字符的完整列表。

由于 curses API 是如此的庞大，某些函数并不被 Python 接口所支持。 这往往不是因为它们难以实现，而是因为还没有人需要它们。 此外，Python 尚不支持与 ncurses 相关联的菜单库。 欢迎提供添加这些功能的补丁；请参阅 Python 开发者指南@footnote{https://devguide.python.org/} 了解有关为 Python 提交补丁的详情。


@itemize *

@item 
使用 NCURSES 编写程序@footnote{http://invisible-island.net/ncurses/ncurses-intro.html}: 一篇面向 C 程序员的详细教程。

@item 
ncurses 手册主页 <@indicateurl{https://linux.die.net/man/3/ncurses}>`_

@item 
ncurses 常见问题 <@indicateurl{http://invisible-island.net/ncurses/ncurses.faq.html}>`_

@item 
"使用 curses... 请勿爆粗"@footnote{https://www.youtube.com/watch?v=eN1eZtjLEnU}: 一场有关使用 curses 或 Urwid 来控制终端的 PyCon 2013 演讲的视频。

@item 
"使用 Urwid 的控制台应用程序"@footnote{http://www.pyvideo.org/video/1568/console-applications-with-urwid}: 一场演示使用 Urwid 编写应用程序的 PyCon CA 2012 演讲的视频。
@end itemize

@node 描述器使用指南,函数式编程指引,用 Python 进行 Curses 编程,Python 常用指引
@anchor{howto/descriptor doc}@anchor{4357}@anchor{howto/descriptor descriptor-howto-guide}@anchor{4358}@anchor{howto/descriptor descriptorhowto}@anchor{4359}
@section 描述器使用指南


@*作者: 
Raymond Hettinger（译者：wh2099 at outlook dot com）


@*联系方式: 
<python at rcn dot com>


@ref{15a8,,描述器} 让对象能够自定义属性查找、存储和删除的操作。

本指南主要分为四个部分：


@enumerate 

@item 
“入门” 部分从简单的示例着手，逐步添加特性，从而给出基本的概述。如果你是刚接触到描述器，请从这里开始。

@item 
第二部分展示了完整的、实用的描述器示例。如果您已经掌握了基础知识，请从此处开始。

@item 
第三部分提供了更多技术教程，详细介绍了描述器如何工作。大多数人并不需要深入到这种程度。

@item 
最后一部分有对内置描述器（用 C 编写）的纯 Python 等价实现。如果您想了解函数如何变成绑定方法或对 @ref{310,,classmethod()}， @ref{311,,staticmethod()}，@ref{30f,,property()} 和 @ref{3822,,__slots__} 这类常见工具的实现感兴趣，请阅读此部分。
@end enumerate

@menu
* 入门: 入门<2>. 
* 完整的实际例子:: 
* 技术教程:: 
* 纯 Python 等价实现:: 

@end menu

@node 入门<2>,完整的实际例子,,描述器使用指南
@anchor{howto/descriptor primer}@anchor{435a}
@subsection 入门


现在，让我们从最基本的示例开始，然后逐步添加新功能。

@menu
* 简单示例：返回常量的描述器:: 
* 动态查找:: 
* 托管属性:: 
* 定制名称:: 
* 结束语:: 

@end menu

@node 简单示例：返回常量的描述器,动态查找,,入门<2>
@anchor{howto/descriptor simple-example-a-descriptor-that-returns-a-constant}@anchor{435b}
@subsubsection 简单示例：返回常量的描述器


类 @code{Ten} 是一个描述器，它的 @ref{159d,,__get__()} 方法总是返回常量 @code{10}：

@example
class Ten:
    def __get__(self, obj, objtype=None):
        return 10
@end example

要使用描述器，它必须作为一个类变量存储在另一个类中：

@example
class A:
    x = 5                       # Regular class attribute
    y = Ten()                   # Descriptor instance
@end example

用交互式会话查看普通属性查找和描述器查找之间的区别：

@example
>>> a = A()                     # Make an instance of class A
>>> a.x                         # Normal attribute lookup
5
>>> a.y                         # Descriptor lookup
10
@end example

在 @code{a.x} 属性查找中，点运算符会找到存储在类字典中的键 @code{x} 及对应的值 @code{5} 。 在 @code{a.y} 查找中，点运算符会根据描述器实例的 @code{__get__} 方法将其识别出来，调用该方法并返回 @code{10} 。

请注意，值 @code{10} 既不存储在类字典中也不存储在实例字典中。相反，值 @code{10} 是在调用时才取到的。

这个简单的例子展示了一个描述器是如何工作的，但它不是很有用。在查找常量时，用常规属性查找会更好。

在下一节中，我们将创建更有用的东西，即动态查找。

@node 动态查找,托管属性,简单示例：返回常量的描述器,入门<2>
@anchor{howto/descriptor dynamic-lookups}@anchor{435c}
@subsubsection 动态查找


有趣的描述器通常运行计算而不是返回常量：

@example
import os

class DirectorySize:

    def __get__(self, obj, objtype=None):
        return len(os.listdir(obj.dirname))

class Directory:

    size = DirectorySize()              # Descriptor instance

    def __init__(self, dirname):
        self.dirname = dirname          # Regular instance attribute
@end example

交互式会话显示查找是动态的，每次都会计算不同的，经过更新的返回值:

@example
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size                              # The songs directory has twenty files
20
>>> g.size                              # The games directory has three files
3
>>> os.remove('games/chess')            # Delete a game
>>> g.size                              # File count is automatically updated
2
@end example

除了说明描述器如何运行计算，这个例子也揭示了 @ref{159d,,__get__()} 参数的目的。形参 @emph{self} 接收的实参是 @emph{size}，即 @emph{DirectorySize} 的一个实例。形参 @emph{obj} 接收的实参是 @emph{g} 或 @emph{s}，即 @emph{Directory} 的一个实例。而正是 @emph{obj} 让 @ref{159d,,__get__()} 方法获得了作为目标的目录。形参 @emph{objtype} 接收的实参是 @emph{Directory} 类。

@node 托管属性,定制名称,动态查找,入门<2>
@anchor{howto/descriptor managed-attributes}@anchor{435d}
@subsubsection 托管属性


描述器的一种流行用法是托管对实例数据的访问。描述器被分配给类字典中的公开属性，而实际数据作为私有属性存储在实例字典中。当访问公开属性时，会触发描述器的  @ref{159d,,__get__()} 和 @ref{15a1,,__set__()} 方法。

在下面的例子中，@emph{age} 是公开属性，@emph{_age} 是私有属性。当访问公开属性时，描述器会记录下查找或更新的日志：

@example
import logging

logging.basicConfig(level=logging.INFO)

class LoggedAgeAccess:

    def __get__(self, obj, objtype=None):
        value = obj._age
        logging.info('Accessing %r giving %r', 'age', value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', 'age', value)
        obj._age = value

class Person:

    age = LoggedAgeAccess()             # Descriptor instance

    def __init__(self, name, age):
        self.name = name                # Regular instance attribute
        self.age = age                  # Calls __set__()

    def birthday(self):
        self.age += 1                   # Calls both __get__() and __set__()
@end example

交互式会话展示中，对托管属性 @emph{age} 的所有访问都被记录了下来，但常规属性 @emph{name} 则未被记录：

@c import logging, sys
@c logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)

@example
>>> mary = Person('Mary M', 30)         # The initial age update is logged
INFO:root:Updating 'age' to 30
>>> dave = Person('David D', 40)
INFO:root:Updating 'age' to 40

>>> vars(mary)                          # The actual data is in a private attribute
@{'name': 'Mary M', '_age': 30@}
>>> vars(dave)
@{'name': 'David D', '_age': 40@}

>>> mary.age                            # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday()                     # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO:root:Updating 'age' to 31

>>> dave.name                           # Regular attribute lookup isn't logged
'David D'
>>> dave.age                            # Only the managed attribute is logged
INFO:root:Accessing 'age' giving 40
40
@end example

此示例的一个主要问题是私有名称 @emph{_age} 在类 @emph{LoggedAgeAccess} 中是硬耦合的。这意味着每个实例只能有一个用于记录的属性，并且其名称不可更改。

@node 定制名称,结束语,托管属性,入门<2>
@anchor{howto/descriptor customized-names}@anchor{435e}
@subsubsection 定制名称


当一个类使用描述器时，它可以告知每个描述器使用了什么变量名。

在此示例中， @code{Person}  类具有两个描述器实例 @emph{name} 和 @emph{age}。当类  @code{Person} 被定义的时候，他回调了 @emph{LoggedAccess} 中的 @ref{5eb,,__set_name__()} 来记录字段名称，让每个描述器拥有自己的 @emph{public_name} 和 @emph{private_name}：

@example
import logging

logging.basicConfig(level=logging.INFO)

class LoggedAccess:

    def __set_name__(self, owner, name):
        self.public_name = name
        self.private_name = '_' + name

    def __get__(self, obj, objtype=None):
        value = getattr(obj, self.private_name)
        logging.info('Accessing %r giving %r', self.public_name, value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', self.public_name, value)
        setattr(obj, self.private_name, value)

class Person:

    name = LoggedAccess()                # First descriptor instance
    age = LoggedAccess()                 # Second descriptor instance

    def __init__(self, name, age):
        self.name = name                 # Calls the first descriptor
        self.age = age                   # Calls the second descriptor

    def birthday(self):
        self.age += 1
@end example

交互交互式会话显示类 @code{Person} 调用了 @ref{5eb,,__set_name__()} 方法来记录字段的名称。在这里，我们调用 @ref{11b6,,vars()} 来查找描述器而不触发它：

@example
>>> vars(vars(Person)['name'])
@{'public_name': 'name', 'private_name': '_name'@}
>>> vars(vars(Person)['age'])
@{'public_name': 'age', 'private_name': '_age'@}
@end example

现在，新类会记录对 @emph{name} 和 @emph{age} 二者的访问：

@c import logging, sys
@c logging.basicConfig(level=logging.INFO, stream=sys.stdout, force=True)

@example
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20
@end example

这两个 @emph{Person} 实例仅包含私有名称:

@example
>>> vars(pete)
@{'_name': 'Peter P', '_age': 10@}
>>> vars(kate)
@{'_name': 'Catherine C', '_age': 20@}
@end example

@node 结束语,,定制名称,入门<2>
@anchor{howto/descriptor closing-thoughts}@anchor{435f}
@subsubsection 结束语


@ref{15a8,,descriptor} 就是任何一个定义了 @ref{159d,,__get__()}，@ref{15a1,,__set__()} 或 @ref{15a2,,__delete__()} 的对象。

可选地，描述器可以具有 @ref{5eb,,__set_name__()} 方法。这仅在描述器需要知道创建它的类或分配给它的类变量名称时使用。（即使该类不是描述器，只要此方法存在就会调用。）

在属性查找期间，描述器由点运算符调用。如果使用 @code{vars(some_class)[descriptor_name]} 间接访问描述器，则返回描述器实例而不调用它。

描述器仅在用作类变量时起作用。放入实例时，它们将失效。

描述器的主要目的是提供一个挂钩，允许存储在类变量中的对象控制在属性查找期间发生的情况。

传统上，调用类控制查找过程中发生的事情。描述器反转了这种关系，并允许正在被查询的数据对此进行干涉。

描述器的使用贯穿了整个语言。就是它让函数变成绑定方法。常见工具诸如 @ref{310,,classmethod()}， @ref{311,,staticmethod()}，@ref{30f,,property()} 和 @ref{300,,functools.cached_property()} 都作为描述器实现。

@node 完整的实际例子,技术教程,入门<2>,描述器使用指南
@anchor{howto/descriptor complete-practical-example}@anchor{4360}
@subsection 完整的实际例子


在此示例中，我们创建了一个实用而强大的工具来查找难以发现的数据损坏错误。

@menu
* 验证器类:: 
* 自定义验证器:: 
* 实际应用:: 

@end menu

@node 验证器类,自定义验证器,,完整的实际例子
@anchor{howto/descriptor validator-class}@anchor{4361}
@subsubsection 验证器类


验证器是一个用于托管属性访问的描述器。在存储任何数据之前，它会验证新值是否满足各种类型和范围限制。如果不满足这些限制，它将引发异常，从源头上防止数据损坏。

这个 @code{Validator} 类既是一个 @ref{c0e,,abstract base class} 也是一个托管属性描述器。

@example
from abc import ABC, abstractmethod

class Validator(ABC):

    def __set_name__(self, owner, name):
        self.private_name = '_' + name

    def __get__(self, obj, objtype=None):
        return getattr(obj, self.private_name)

    def __set__(self, obj, value):
        self.validate(value)
        setattr(obj, self.private_name, value)

    @@abstractmethod
    def validate(self, value):
        pass
@end example

自定义验证器需要从 @code{Validator} 继承，并且必须提供 @code{validate()} 方法以根据需要测试各种约束。

@node 自定义验证器,实际应用,验证器类,完整的实际例子
@anchor{howto/descriptor custom-validators}@anchor{4362}
@subsubsection 自定义验证器


这是三个实用的数据验证工具：


@enumerate 

@item 
@code{OneOf} 验证值是一组受约束的选项之一。

@item 
@code{Number} 验证值是否为 @ref{205,,int} 或 @ref{1fe,,float}。根据可选参数，它还可以验证值在给定的最小值或最大值之间。

@item 
@code{String} 验证值是否为 @ref{206,,str}。根据可选参数，它可以验证给定的最小或最大长度。它还可以验证用户定义的 predicate@footnote{https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)}。
@end enumerate

@example
class OneOf(Validator):

    def __init__(self, *options):
        self.options = set(options)

    def validate(self, value):
        if value not in self.options:
            raise ValueError(f'Expected @{value!r@} to be one of @{self.options!r@}')

class Number(Validator):

    def __init__(self, minvalue=None, maxvalue=None):
        self.minvalue = minvalue
        self.maxvalue = maxvalue

    def validate(self, value):
        if not isinstance(value, (int, float)):
            raise TypeError(f'Expected @{value!r@} to be an int or float')
        if self.minvalue is not None and value < self.minvalue:
            raise ValueError(
                f'Expected @{value!r@} to be at least @{self.minvalue!r@}'
            )
        if self.maxvalue is not None and value > self.maxvalue:
            raise ValueError(
                f'Expected @{value!r@} to be no more than @{self.maxvalue!r@}'
            )

class String(Validator):

    def __init__(self, minsize=None, maxsize=None, predicate=None):
        self.minsize = minsize
        self.maxsize = maxsize
        self.predicate = predicate

    def validate(self, value):
        if not isinstance(value, str):
            raise TypeError(f'Expected @{value!r@} to be an str')
        if self.minsize is not None and len(value) < self.minsize:
            raise ValueError(
                f'Expected @{value!r@} to be no smaller than @{self.minsize!r@}'
            )
        if self.maxsize is not None and len(value) > self.maxsize:
            raise ValueError(
                f'Expected @{value!r@} to be no bigger than @{self.maxsize!r@}'
            )
        if self.predicate is not None and not self.predicate(value):
            raise ValueError(
                f'Expected @{self.predicate@} to be true for @{value!r@}'
            )
@end example

@node 实际应用,,自定义验证器,完整的实际例子
@anchor{howto/descriptor practical-application}@anchor{4363}
@subsubsection 实际应用


这是在真实类中使用数据验证器的方法：

@example
class Component:

    name = String(minsize=3, maxsize=10, predicate=str.isupper)
    kind = OneOf('wood', 'metal', 'plastic')
    quantity = Number(minvalue=0)

    def __init__(self, name, kind, quantity):
        self.name = name
        self.kind = kind
        self.quantity = quantity
@end example

描述器阻止无效实例的创建：

@example
>>> Component('Widget', 'metal', 5)      # Blocked: 'Widget' is not all uppercase
Traceback (most recent call last):
    ...
ValueError: Expected <method 'isupper' of 'str' objects> to be true for 'Widget'

>>> Component('WIDGET', 'metle', 5)      # Blocked: 'metle' is misspelled
Traceback (most recent call last):
    ...
ValueError: Expected 'metle' to be one of @{'metal', 'plastic', 'wood'@}

>>> Component('WIDGET', 'metal', -5)     # Blocked: -5 is negative
Traceback (most recent call last):
    ...
ValueError: Expected -5 to be at least 0
>>> Component('WIDGET', 'metal', 'V')    # Blocked: 'V' isn't a number
Traceback (most recent call last):
    ...
TypeError: Expected 'V' to be an int or float

>>> c = Component('WIDGET', 'metal', 5)  # Allowed:  The inputs are valid
@end example

@node 技术教程,纯 Python 等价实现,完整的实际例子,描述器使用指南
@anchor{howto/descriptor technical-tutorial}@anchor{4364}
@subsection 技术教程


接下来是专业性更强的技术教程，以及描述器工作原理的详细信息。

@menu
* 摘要:: 
* 定义与介绍:: 
* 描述器协议:: 
* 描述器调用概述:: 
* 通过实例调用:: 
* 通过类调用:: 
* 通过 super 调用:: 
* 调用逻辑总结:: 
* 自动名称通知:: 
* ORM （对象关系映射）示例:: 

@end menu

@node 摘要,定义与介绍,,技术教程
@anchor{howto/descriptor abstract}@anchor{4365}
@subsubsection 摘要


定义描述器，总结协议，并说明如何调用描述器。提供一个展示对象关系映射如何工作的示例。

学习描述器不仅能提供接触到更多工具集的途径，还能更深地理解 Python 工作的原理。

@node 定义与介绍,描述器协议,摘要,技术教程
@anchor{howto/descriptor definition-and-introduction}@anchor{4366}
@subsubsection 定义与介绍


一般而言，描述器是一个包含了描述器协议中的方法的属性值。 这些方法有 @ref{159d,,__get__()}, @ref{15a1,,__set__()} 和 @ref{15a2,,__delete__()}。 如果为某个属性定义了这些方法中的任意一个，它就可以被称为 @ref{15a8,,descriptor}。

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。对于实例来说，@code{a.x} 的查找顺序会从 @code{a.__dict__['x']} 开始，然后是 @code{type(a).__dict__['x']}，接下来依次查找 @code{type(a)} 的方法解析顺序（MRO）。 如果找到的值是定义了某个描述器方法的对象，则 Python 可能会重写默认行为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定义的描述器方法及其被调用的方式来决定。

描述器是一个强大而通用的协议。 它们是属性、方法、静态方法、类方法和 @ref{5e6,,super()} 背后的实现机制。 它们在 Python 内部被广泛使用。 描述器简化了底层的 C 代码并为 Python 的日常程序提供了一组灵活的新工具。

@node 描述器协议,描述器调用概述,定义与介绍,技术教程
@anchor{howto/descriptor descriptor-protocol}@anchor{4367}
@subsubsection 描述器协议


@code{descr.__get__(self, obj, type=None) -> value}

@code{descr.__set__(self, obj, value) -> None}

@code{descr.__delete__(self, obj) -> None}

描述器的方法就这些。一个对象只要定义了以上方法中的任何一个，就被视为描述器，并在被作为属性时覆盖其默认行为。

如果一个对象定义了 @ref{15a1,,__set__()} 或 @ref{15a2,,__delete__()}，则它会被视为数据描述器。 仅定义了 @ref{159d,,__get__()} 的描述器称为非数据描述器（它们经常被用于方法，但也可以有其他用途）。

数据和非数据描述器的不同之处在于，如何计算实例字典中条目的替代值。如果实例的字典具有与数据描述器同名的条目，则数据描述器优先。如果实例的字典具有与非数据描述器同名的条目，则该字典条目优先。

为了使数据描述器成为只读的，应该同时定义 @ref{159d,,__get__()} 和 @ref{15a1,,__set__()} ，并在 @ref{15a1,,__set__()} 中引发 @ref{4aa,,AttributeError} 。用引发异常的占位符定义 @ref{15a1,,__set__()}  方法使其成为数据描述器。

@node 描述器调用概述,通过实例调用,描述器协议,技术教程
@anchor{howto/descriptor overview-of-descriptor-invocation}@anchor{4368}
@subsubsection 描述器调用概述


描述器可以通过 @code{d.__get__(obj)} 或 @code{desc.__get__(None, cls)} 直接调用。

但更常见的是通过属性访问自动调用描述器。

表达式 @code{obj.x} 在命名空间的链中查找`@w{`}obj`@w{`} 的属性 @code{x}。如果搜索在实例 @code{__dict__} 之外找到描述器，则根据下面列出的优先级规则调用其 @ref{159d,,__get__()} 方法。

调用的细节取决于 @code{obj} 是对象、类还是超类的实例。

@node 通过实例调用,通过类调用,描述器调用概述,技术教程
@anchor{howto/descriptor invocation-from-an-instance}@anchor{4369}
@subsubsection 通过实例调用


实例查找通过命名空间链进行扫描，数据描述器的优先级最高，其次是实例变量、非数据描述器、类变量，最后是 @ref{433,,__getattr__()} （如果存在的话）。

如果 @code{a.x} 找到了一个描述器，那么将通过 @code{desc.__get__(a, type(a))} 调用它。

点运算符的查找逻辑在 @ref{552,,object.__getattribute__()} 中。这里是一个等价的纯 Python 实现：

@example
def object_getattribute(obj, name):
    "Emulate PyObject_GenericGetAttr() in Objects/object.c"
    null = object()
    objtype = type(obj)
    cls_var = getattr(objtype, name, null)
    descr_get = getattr(type(cls_var), '__get__', null)
    if descr_get is not null:
        if (hasattr(type(cls_var), '__set__')
            or hasattr(type(cls_var), '__delete__')):
            return descr_get(cls_var, obj, objtype)     # data descriptor
    if hasattr(obj, '__dict__') and name in vars(obj):
        return vars(obj)[name]                          # instance variable
    if descr_get is not null:
        return descr_get(cls_var, obj, objtype)         # non-data descriptor
    if cls_var is not null:
        return cls_var                                  # class variable
    raise AttributeError(name)
@end example

@c # Test the fidelity of object_getattribute() by comparing it with the
@c # normal object.__getattribute__().  The former will be accessed by
@c # square brackets and the latter by the dot operator.
@c 
@c class Object:
@c 
@c     def __getitem__(obj, name):
@c         try:
@c             return object_getattribute(obj, name)
@c         except AttributeError:
@c             if not hasattr(type(obj), '__getattr__'):
@c                 raise
@c         return type(obj).__getattr__(obj, name)             # __getattr__
@c 
@c class DualOperator(Object):
@c 
@c     x = 10
@c 
@c     def __init__(self, z):
@c         self.z = z
@c 
@c     @property
@c     def p2(self):
@c         return 2 * self.x
@c 
@c     @property
@c     def p3(self):
@c         return 3 * self.x
@c 
@c     def m5(self, y):
@c         return 5 * y
@c 
@c     def m7(self, y):
@c         return 7 * y
@c 
@c     def __getattr__(self, name):
@c         return ('getattr_hook', self, name)
@c 
@c class DualOperatorWithSlots:
@c 
@c     __getitem__ = Object.__getitem__
@c 
@c     __slots__ = ['z']
@c 
@c     x = 15
@c 
@c     def __init__(self, z):
@c         self.z = z
@c 
@c     @property
@c     def p2(self):
@c         return 2 * self.x
@c 
@c     def m5(self, y):
@c         return 5 * y
@c 
@c     def __getattr__(self, name):
@c         return ('getattr_hook', self, name)

@c >>> a = DualOperator(11)
@c >>> vars(a).update(p3 = '_p3', m7 = '_m7')
@c >>> a.x == a['x'] == 10
@c True
@c >>> a.z == a['z'] == 11
@c True
@c >>> a.p2 == a['p2'] == 20
@c True
@c >>> a.p3 == a['p3'] == 30
@c True
@c >>> a.m5(100) == a.m5(100) == 500
@c True
@c >>> a.m7 == a['m7'] == '_m7'
@c True
@c >>> a.g == a['g'] == ('getattr_hook', a, 'g')
@c True
@c 
@c >>> b = DualOperatorWithSlots(22)
@c >>> b.x == b['x'] == 15
@c True
@c >>> b.z == b['z'] == 22
@c True
@c >>> b.p2 == b['p2'] == 30
@c True
@c >>> b.m5(200) == b['m5'](200) == 1000
@c True
@c >>> b.g == b['g'] == ('getattr_hook', b, 'g')
@c True

请注意，在 @ref{552,,__getattribute__()} 方法的代码中没有调用 @ref{433,,__getattr__()} 的钩子。这就是直接调用 @ref{552,,__getattribute__()} 或调用 @code{super().__getattribute__} 会彻底绕过 @ref{433,,__getattr__()} 的原因。

相反，当 @ref{552,,__getattribute__()} 引发 @ref{4aa,,AttributeError} 时，点运算符和 @ref{554,,getattr()} 函数负责调用 @ref{433,,__getattr__()}。它们的逻辑封装在一个辅助函数中：

@example
def getattr_hook(obj, name):
    "Emulate slot_tp_getattr_hook() in Objects/typeobject.c"
    try:
        return obj.__getattribute__(name)
    except AttributeError:
        if not hasattr(type(obj), '__getattr__'):
            raise
    return type(obj).__getattr__(obj, name)             # __getattr__
@end example

@c >>> class ClassWithGetAttr:
@c ...     x = 123
@c ...     def __getattr__(self, attr):
@c ...         return attr.upper()
@c ...
@c >>> cw = ClassWithGetAttr()
@c >>> cw.y = 456
@c >>> getattr_hook(cw, 'x')
@c 123
@c >>> getattr_hook(cw, 'y')
@c 456
@c >>> getattr_hook(cw, 'z')
@c 'Z'
@c 
@c >>> class ClassWithoutGetAttr:
@c ...     x = 123
@c ...
@c >>> cwo = ClassWithoutGetAttr()
@c >>> cwo.y = 456
@c >>> getattr_hook(cwo, 'x')
@c 123
@c >>> getattr_hook(cwo, 'y')
@c 456
@c >>> getattr_hook(cwo, 'z')
@c Traceback (most recent call last):
@c     ...
@c AttributeError: 'ClassWithoutGetAttr' object has no attribute 'z'

@node 通过类调用,通过 super 调用,通过实例调用,技术教程
@anchor{howto/descriptor invocation-from-a-class}@anchor{436a}
@subsubsection 通过类调用


像 @code{A.x} 这样的点操作符查找的逻辑在 @code{type.__getattribute__()} 中。步骤与 @ref{552,,object.__getattribute__()} 相似，但是实例字典查找改为搜索类的 @ref{1769,,method resolution order}。

如果找到了一个描述器，那么将通过 @code{desc.__get__(None, A)} 调用它。

完整的 C 实现可在 Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.9/Objects/typeobject.c} 中的 @code{type_getattro()} 和 @code{_PyType_Lookup()} 找到。

@node 通过 super 调用,调用逻辑总结,通过类调用,技术教程
@anchor{howto/descriptor invocation-from-super}@anchor{436b}
@subsubsection 通过 super 调用


super 的点操作符查找的逻辑在 @ref{5e6,,super()} 返回的对象的 @ref{552,,__getattribute__()} 方法中。

类似 @code{super(A, obj).m} 形式的点分查找将在 @code{obj.__class__.__mro__} 中搜索紧接在 @code{A} 之后的基类 @code{B}，然后返回 @code{B.__dict__['m'].__get__(obj, A)}。如果 @code{m} 不是描述器，则直接返回其值。

完整的 C 实现可以在 Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.9/Objects/typeobject.c} 的 @code{super_getattro()} 中找到。纯 Python 等价实现可以在 Guido's Tutorial@footnote{https://www.python.org/download/releases/2.2.3/descrintro/#cooperation} 中找到。

@node 调用逻辑总结,自动名称通知,通过 super 调用,技术教程
@anchor{howto/descriptor summary-of-invocation-logic}@anchor{436c}
@subsubsection 调用逻辑总结


描述器的机制嵌入在 @ref{3da,,object}，@ref{709,,type} 和 @ref{5e6,,super()} 的 @ref{552,,__getattribute__()} 方法中。

要记住的重要点是：


@itemize *

@item 
描述器由 @ref{552,,__getattribute__()} 方法调用。

@item 
类从 @ref{3da,,object}，@ref{709,,type} 或 @ref{5e6,,super()} 继承此机制。

@item 
由于描述器的逻辑在 @ref{552,,__getattribute__()} 中，因而重写该方法会阻止描述器的自动调用。

@item 
@ref{552,,object.__getattribute__()} 和 @code{type.__getattribute__()} 会用不同的方式调用 @ref{159d,,__get__()}。前一个会传入实例，也可以包括类。后一个传入的实例为 @code{None} ，并且总是包括类。

@item 
数据描述器始终会覆盖实例字典。

@item 
非数据描述器会被实例字典覆盖。
@end itemize

@node 自动名称通知,ORM （对象关系映射）示例,调用逻辑总结,技术教程
@anchor{howto/descriptor automatic-name-notification}@anchor{436d}
@subsubsection 自动名称通知


有时，描述器想知道它分配到的具体类变量名。创建新类时，元类 @ref{709,,type} 将扫描新类的字典。如果有描述器，并且它们定义了 @ref{5eb,,__set_name__()}，则使用两个参数调用该方法。@emph{owner} 是使用描述器的类，@emph{name} 是分配给描述器的类变量名。

实现的细节在 Objects/typeobject.c@footnote{https://github.com/python/cpython/tree/3.9/Objects/typeobject.c} 中的 @code{type_new()} 和 @code{set_names()} 。

由于更新逻辑在 @code{type.__new__()} 中，因此通知仅在创建类时发生。之后如果将描述器添加到类中，则需要手动调用 @ref{5eb,,__set_name__()} 。

@node ORM （对象关系映射）示例,,自动名称通知,技术教程
@anchor{howto/descriptor orm-example}@anchor{436e}
@subsubsection ORM （对象关系映射）示例


以下代码展示了如何使用数据描述器来实现简单 object relational mapping@footnote{https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping} 框架。

其核心思路是将数据存储在外部数据库中，Python 实例仅持有数据库表中对应的的键。描述器负责对值进行查找或更新：

@example
class Field:

    def __set_name__(self, owner, name):
        self.fetch = f'SELECT @{name@} FROM @{owner.table@} WHERE @{owner.key@}=?;'
        self.store = f'UPDATE @{owner.table@} SET @{name@}=? WHERE @{owner.key@}=?;'

    def __get__(self, obj, objtype=None):
        return conn.execute(self.fetch, [obj.key]).fetchone()[0]

    def __set__(self, obj, value):
        conn.execute(self.store, [value, obj.key])
        conn.commit()
@end example

我们可以用 @code{Field} 类来定义描述了数据库中每张表的模式的 models@footnote{https://en.wikipedia.org/wiki/Database_model}。

@example
class Movie:
    table = 'Movies'                    # Table name
    key = 'title'                       # Primary key
    director = Field()
    year = Field()

    def __init__(self, key):
        self.key = key

class Song:
    table = 'Music'
    key = 'title'
    artist = Field()
    year = Field()
    genre = Field()

    def __init__(self, key):
        self.key = key
@end example

要使用模型，首先要连接到数据库：

@example
>>> import sqlite3
>>> conn = sqlite3.connect('entertainment.db')
@end example

交互式会话显示了如何从数据库中检索数据及如何对其进行更新：

@c song_data = [
@c     ('Country Roads', 'John Denver', 1972),
@c     ('Me and Bobby McGee', 'Janice Joplin', 1971),
@c     ('Coal Miners Daughter', 'Loretta Lynn', 1970),
@c ]
@c 
@c movie_data = [
@c     ('Star Wars', 'George Lucas', 1977),
@c     ('Jaws', 'Steven Spielberg', 1975),
@c     ('Aliens', 'James Cameron', 1986),
@c ]
@c 
@c import sqlite3
@c 
@c conn = sqlite3.connect(':memory:')
@c conn.execute('CREATE TABLE Music (title text, artist text, year integer);')
@c conn.execute('CREATE INDEX MusicNdx ON Music (title);')
@c conn.executemany('INSERT INTO Music VALUES (?, ?, ?);', song_data)
@c conn.execute('CREATE TABLE Movies (title text, director text, year integer);')
@c conn.execute('CREATE INDEX MovieNdx ON Music (title);')
@c conn.executemany('INSERT INTO Movies VALUES (?, ?, ?);', movie_data)
@c conn.commit()

@example
>>> Movie('Star Wars').director
'George Lucas'
>>> jaws = Movie('Jaws')
>>> f'Released in @{jaws.year@} by @{jaws.director@}'
'Released in 1975 by Steven Spielberg'

>>> Song('Country Roads').artist
'John Denver'

>>> Movie('Star Wars').director = 'J.J. Abrams'
>>> Movie('Star Wars').director
'J.J. Abrams'
@end example

@node 纯 Python 等价实现,,技术教程,描述器使用指南
@anchor{howto/descriptor pure-python-equivalents}@anchor{436f}
@subsection 纯 Python 等价实现


描述器协议很简单，但它提供了令人兴奋的可能性。有几个用例非常通用，以至于它们已预先打包到内置工具中。属性、绑定方法、静态方法、类方法和 __slots__ 均基于描述器协议。

@menu
* 属性: 属性<2>. 
* 函数和方法:: 
* 方法的种类:: 
* 静态方法:: 
* 类方法:: 
* 成员对象和 __slots__:: 

@end menu

@node 属性<2>,函数和方法,,纯 Python 等价实现
@anchor{howto/descriptor properties}@anchor{4370}
@subsubsection 属性


调用 @ref{30f,,property()} 是构建数据描述器的简洁方式，该数据描述器在访问属性时触发函数调用。它的签名是：

@example
property(fget=None, fset=None, fdel=None, doc=None) -> property
@end example

该文档显示了定义托管属性 @code{x} 的典型用法：

@example
class C:
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I'm the 'x' property.")
@end example

@c >>> C.x.__doc__
@c "I'm the 'x' property."
@c >>> c.x = 2.71828
@c >>> c.x
@c 2.71828
@c >>> del c.x
@c >>> c.x
@c Traceback (most recent call last):
@c   ...
@c AttributeError: 'C' object has no attribute '_C__x'

要了解 @ref{30f,,property()} 如何根据描述器协议实现，这里是一个纯 Python 的等价实现：

@example
class Property:
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)
@end example

@c # Verify the Property() emulation
@c 
@c class CC:
@c     def getx(self):
@c         return self.__x
@c     def setx(self, value):
@c         self.__x = value
@c     def delx(self):
@c         del self.__x
@c     x = Property(getx, setx, delx, "I'm the 'x' property.")
@c 
@c # Now do it again but use the decorator style
@c 
@c class CCC:
@c     @Property
@c     def x(self):
@c         return self.__x
@c     @x.setter
@c     def x(self, value):
@c         self.__x = value
@c     @x.deleter
@c     def x(self):
@c         del self.__x

@c >>> cc = CC()
@c >>> hasattr(cc, 'x')
@c False
@c >>> cc.x = 33
@c >>> cc.x
@c 33
@c >>> del cc.x
@c >>> hasattr(cc, 'x')
@c False
@c 
@c >>> ccc = CCC()
@c >>> hasattr(ccc, 'x')
@c False
@c >>> ccc.x = 333
@c >>> ccc.x == 333
@c True
@c >>> del ccc.x
@c >>> hasattr(ccc, 'x')
@c False

这个内置的 @ref{30f,,property()} 每当用户访问属性时生效，随后的变化需要一个方法的参与。

例如，一个电子表格类可以通过 @code{Cell('b10').value} 授予对单元格值的访问权限。对程序的后续改进要求每次访问都要重新计算单元格；但是，程序员不希望影响直接访问该属性的现有客户端代码。解决方案是将对 value 属性的访问包装在属性数据描述器中:

@example
class Cell:
    ...

    @@property
    def value(self):
        "Recalculate the cell before returning value"
        self.recalc()
        return self._value
@end example

在此示例中，内置的 @ref{30f,,property()} 或我们实现的的 @code{Property()} 均适用。

@node 函数和方法,方法的种类,属性<2>,纯 Python 等价实现
@anchor{howto/descriptor functions-and-methods}@anchor{4371}
@subsubsection 函数和方法


Python 的面向对象功能是在基于函数的环境构建的。通过使用非数据描述器，这两方面完成了无缝融合。

在调用时，存储在类词典中的函数将被转换为方法。方法与常规函数的不同之处仅在于对象实例被置于其他参数之前。方法与常规函数的不同之处仅在于第一个参数是为对象实例保留的。按照惯例，实例引用称为 @emph{self} ，但也可以称为 @emph{this} 或任何其他变量名称。

可以使用 @ref{1b40,,types.MethodType} 手动创建方法，其行为基本等价于：

@example
class MethodType:
    "Emulate PyMethod_Type in Objects/classobject.c"

    def __init__(self, func, obj):
        self.__func__ = func
        self.__self__ = obj

    def __call__(self, *args, **kwargs):
        func = self.__func__
        obj = self.__self__
        return func(obj, *args, **kwargs)
@end example

为了支持自动创建方法，函数包含 @ref{159d,,__get__()} 方法以便在属性访问时绑定其为方法。这意味着函数其是非数据描述器，它在通过实例进行点查找时返回绑定方法，其运作方式如下：

@example
class Function:
    ...

    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        if obj is None:
            return self
        return MethodType(self, obj)
@end example

在解释器中运行以下类，这显示了函数描述器的实际工作方式：

@example
class D:
    def f(self, x):
         return x
@end example

该函数具有 @ref{158b,,qualified name} 属性以支持自省：

@example
>>> D.f.__qualname__
'D.f'
@end example

通过类字典访问函数不会调用 @ref{159d,,__get__()}。相反，它只返回基础函数对象：

@example
>>> D.__dict__['f']
<function D.f at 0x00C45070>
@end example

来自类的点运算符访问会调用 @ref{159d,,__get__()}，直接返回底层的函数。

@example
>>> D.f
<function D.f at 0x00C45070>
@end example

有趣的行为发生在从实例进行点访问期间。点运算符查找调用 @ref{159d,,__get__()}，返回绑定的方法对象：

@example
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>>
@end example

绑定方法在内部存储了底层函数和绑定的实例：

@example
>>> d.f.__func__
<function D.f at 0x00C45070>

>>> d.f.__self__
<__main__.D object at 0x1012e1f98>
@end example

如果你曾好奇常规方法中的 @emph{self} 或类方法中的 @emph{cls} 是从什么地方来的，就是这里了！

@node 方法的种类,静态方法,函数和方法,纯 Python 等价实现
@anchor{howto/descriptor kinds-of-methods}@anchor{4372}
@subsubsection 方法的种类


非数据描述器为把函数绑定为方法的通常模式提供了一种简单的机制。

概括地说，函数对象具有 @ref{159d,,__get__()} 方法，以便在作为属性访问时可以将其转换为方法。非数据描述器将 @code{obj.f(*args)} 的调用会被转换为 @code{f(obj, *args)} 。调用 @cite{klass.f(*args)`} 因而变成 @code{f(*args)} 。

下表总结了绑定及其两个最有用的变体：

@quotation


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

转换形式

@tab

通过对象调用

@tab

通过类调用

@item

函数

@tab

f(obj, *args)

@tab

f(*args)

@item

静态方法

@tab

f(*args)

@tab

f(*args)

@item

类方法

@tab

f(type(obj), *args)

@tab

f(cls, *args)

@end multitable

@end quotation

@node 静态方法,类方法,方法的种类,纯 Python 等价实现
@anchor{howto/descriptor static-methods}@anchor{4373}
@subsubsection 静态方法


静态方法返回底层函数，不做任何更改。调用 @code{c.f} 或 @code{C.f} 等效于通过 @code{object.__getattribute__(c, "f")} 或 @code{object.__getattribute__(C, "f")} 查找。这样该函数就可以从对象或类中进行相同的访问。

适合作为静态方法的是那些不引用 @code{self} 变量的方法。

例如，一个统计用的包可能包含一个实验数据的容器类。该容器类提供了用于计算数据的平均值，均值，中位数和其他描述性统计信息的常规方法。但是，可能有在概念上相关但不依赖于数据的函数。例如， @code{erf(x)} 是在统计中的便捷转换，但并不直接依赖于特定的数据集。可以从对象或类中调用它： @code{s.erf(1.5) --> .9332} 或 @code{Sample.erf(1.5) --> .9332}。

由于静态方法返回的底层函数没有任何变化，因此示例调用也是意料之中：

@example
class E:
    @@staticmethod
    def f(x):
        return x * 10
@end example

@example
>>> E.f(3)
30
>>> E().f(3)
30
@end example

使用非数据描述器，纯 Python 版本的 @ref{311,,staticmethod()} 如下所示：

@example
class StaticMethod:
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f
@end example

@c class E_sim:
@c     @StaticMethod
@c     def f(x):
@c         return x * 10

@c >>> E_sim.f(3)
@c 30
@c >>> E_sim().f(3)
@c 30

@node 类方法,成员对象和 __slots__,静态方法,纯 Python 等价实现
@anchor{howto/descriptor class-methods}@anchor{4374}
@subsubsection 类方法


与静态方法不同，类方法在调用函数之前将类引用放在参数列表的最前。无论调用方是对象还是类，此格式相同：

@example
class F:
    @@classmethod
    def f(cls, x):
        return cls.__name__, x
@end example

@example
>>> F.f(3)
('F', 3)
>>> F().f(3)
('F', 3)
@end example

当方法仅需要具有类引用并且确实依赖于存储在特定实例中的数据时，此行为就很有用。类方法的一种用途是创建备用类构造函数。例如，类方法  @ref{183b,,dict.fromkeys()} 从键列表创建一个新字典。纯 Python 的等价实现是：

@example
class Dict(dict):
    @@classmethod
    def fromkeys(cls, iterable, value=None):
        "Emulate dict_fromkeys() in Objects/dictobject.c"
        d = cls()
        for key in iterable:
            d[key] = value
        return d
@end example

现在可以这样构造一个新的唯一键字典：

@example
>>> d = Dict.fromkeys('abracadabra')
>>> type(d) is Dict
True
>>> d
@{'a': None, 'b': None, 'r': None, 'c': None, 'd': None@}
@end example

使用非数据描述器协议，纯 Python 版本的 @ref{310,,classmethod()} 如下：

@example
class ClassMethod:
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, cls=None):
        if cls is None:
            cls = type(obj)
        if hasattr(type(self.f), '__get__'):
            return self.f.__get__(cls)
        return MethodType(self.f, cls)
@end example

@c # Verify the emulation works
@c class T:
@c     @ClassMethod
@c     def cm(cls, x, y):
@c         return (cls, x, y)
@c 
@c     @ClassMethod
@c     @property
@c     def __doc__(cls):
@c         return f'A doc for {cls.__name__!r}'

@c >>> T.cm(11, 22)
@c (<class 'T'>, 11, 22)
@c 
@c # Also call it from an instance
@c >>> t = T()
@c >>> t.cm(11, 22)
@c (<class 'T'>, 11, 22)
@c 
@c # Check the alternate path for chained descriptors
@c >>> T.__doc__
@c "A doc for 'T'"

@code{hasattr(type(self.f), '__get__')} 的代码路径在 Python 3.9 中被加入并让 @ref{310,,classmethod()} 可以支持链式装饰器。 例如，一个类方法和特征属性可以被链接在一起:

@example
class G:
    @@classmethod
    @@property
    def __doc__(cls):
        return f'A doc for @{cls.__name__!r@}'
@end example

@example
>>> G.__doc__
"A doc for 'G'"
@end example

@node 成员对象和 __slots__,,类方法,纯 Python 等价实现
@anchor{howto/descriptor member-objects-and-slots}@anchor{4375}
@subsubsection 成员对象和 __slots__


当一个类定义了 @code{__slots__}，它会用一个固定长度的 slot 值数组来替换实例字典。 从用户的视角看，效果是这样的：

1. Provides immediate detection of bugs due to misspelled attribute
assignments.  Only attribute names specified in @code{__slots__} are allowed:

@example
class Vehicle:
    __slots__ = ('id_number', 'make', 'model')
@end example

@example
>>> auto = Vehicle()
>>> auto.id_nubmer = 'VYE483814LQEX'
Traceback (most recent call last):
    ...
AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
@end example

2. Helps create immutable objects where descriptors manage access to private
attributes stored in @code{__slots__}:

@example
class Immutable:

    __slots__ = ('_dept', '_name')          # Replace the instance dictionary

    def __init__(self, dept, name):
        self._dept = dept                   # Store to private attribute
        self._name = name                   # Store to private attribute

    @@property                               # Read-only descriptor
    def dept(self):
        return self._dept

    @@property
    def name(self):                         # Read-only descriptor
        return self._name
@end example

@example
>>> mark = Immutable('Botany', 'Mark Watney')
>>> mark.dept
'Botany'
>>> mark.dept = 'Space Pirate'
Traceback (most recent call last):
    ...
AttributeError: can't set attribute
>>> mark.location = 'Mars'
Traceback (most recent call last):
    ...
AttributeError: 'Immutable' object has no attribute 'location'
@end example

3. Saves memory.  On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with @code{__slots__} and 152 bytes without.  This flyweight design pattern@footnote{https://en.wikipedia.org/wiki/Flyweight_pattern} likely only
matters when a large number of instances are going to be created.

4. Blocks tools like @ref{300,,functools.cached_property()} which require an
instance dictionary to function correctly:

@example
from functools import cached_property

class CP:
    __slots__ = ()                          # Eliminates the instance dict

    @@cached_property                        # Requires an instance dict
    def pi(self):
        return 4 * sum((-1.0)**n / (2.0*n + 1.0)
                       for n in reversed(range(100_000)))
@end example

@example
>>> CP().pi
Traceback (most recent call last):
  ...
TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
@end example

要创建一个一模一样的纯 Python 版的 @code{__slots__} 是不可能的，因为它需要直接访问 C 结构体并控制对象内存分配。 但是，我们可以构建一个非常相似的模拟版，其中作为 slot 的实际 C 结构体由一个私有的 @code{_slotvalues} 列表来模拟。 对该私有结构体的读写操作将由成员描述器来管理：

@example
null = object()

class Member:

    def __init__(self, name, clsname, offset):
        'Emulate PyMemberDef in Include/structmember.h'
        # Also see descr_new() in Objects/descrobject.c
        self.name = name
        self.clsname = clsname
        self.offset = offset

    def __get__(self, obj, objtype=None):
        'Emulate member_get() in Objects/descrobject.c'
        # Also see PyMember_GetOne() in Python/structmember.c
        value = obj._slotvalues[self.offset]
        if value is null:
            raise AttributeError(self.name)
        return value

    def __set__(self, obj, value):
        'Emulate member_set() in Objects/descrobject.c'
        obj._slotvalues[self.offset] = value

    def __delete__(self, obj):
        'Emulate member_delete() in Objects/descrobject.c'
        value = obj._slotvalues[self.offset]
        if value is null:
            raise AttributeError(self.name)
        obj._slotvalues[self.offset] = null

    def __repr__(self):
        'Emulate member_repr() in Objects/descrobject.c'
        return f'<Member @{self.name!r@} of @{self.clsname!r@}>'
@end example

@code{type.__new__()} 方法负责将成员对象添加到类变量：

@example
class Type(type):
    'Simulate how the type metaclass adds member objects for slots'

    def __new__(mcls, clsname, bases, mapping):
        'Emuluate type_new() in Objects/typeobject.c'
        # type_new() calls PyTypeReady() which calls add_methods()
        slot_names = mapping.get('slot_names', [])
        for offset, name in enumerate(slot_names):
            mapping[name] = Member(name, clsname, offset)
        return type.__new__(mcls, clsname, bases, mapping)
@end example

@ref{97d,,object.__new__()} 方法负责创建具有 slot 而非实例字典的实例。 以下是一个纯 Python 的粗略模拟版：

@example
class Object:
    'Simulate how object.__new__() allocates memory for __slots__'

    def __new__(cls, *args):
        'Emulate object_new() in Objects/typeobject.c'
        inst = super().__new__(cls)
        if hasattr(cls, 'slot_names'):
            empty_slots = [null] * len(cls.slot_names)
            object.__setattr__(inst, '_slotvalues', empty_slots)
        return inst

    def __setattr__(self, name, value):
        'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'
        cls = type(self)
        if hasattr(cls, 'slot_names') and name not in cls.slot_names:
            raise AttributeError(
                f'@{type(self).__name__!r@} object has no attribute @{name!r@}'
            )
        super().__setattr__(name, value)

    def __delattr__(self, name):
        'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'
        cls = type(self)
        if hasattr(cls, 'slot_names') and name not in cls.slot_names:
            raise AttributeError(
                f'@{type(self).__name__!r@} object has no attribute @{name!r@}'
            )
        super().__delattr__(name)
@end example

要在真实的类中使用这个模拟版，只需从 @code{Object} 继承并将 @ref{15bf,,metaclass} 设为 @code{Type}：

@example
class H(Object, metaclass=Type):
    'Instance variables stored in slots'

    slot_names = ['x', 'y']

    def __init__(self, x, y):
        self.x = x
        self.y = y
@end example

这时，metaclass 已经为 @emph{x} 和 @emph{y} 加载了成员对象：

@example
>>> from pprint import pp
>>> pp(dict(vars(H)))
@{'__module__': '__main__',
 '__doc__': 'Instance variables stored in slots',
 'slot_names': ['x', 'y'],
 '__init__': <function H.__init__ at 0x7fb5d302f9d0>,
 'x': <Member 'x' of 'H'>,
 'y': <Member 'y' of 'H'>@}
@end example

@c # We test this separately because the preceding section is not
@c # doctestable due to the hex memory address for the __init__ function
@c >>> isinstance(vars(H)['x'], Member)
@c True
@c >>> isinstance(vars(H)['y'], Member)
@c True

当实例被创建时，它们将拥有一个用于存放属性的 @code{slot_values} 列表：

@example
>>> h = H(10, 20)
>>> vars(h)
@{'_slotvalues': [10, 20]@}
>>> h.x = 55
>>> vars(h)
@{'_slotvalues': [55, 20]@}
@end example

错误拼写或未赋值的属性将引发一个异常：

@example
>>> h.xz
Traceback (most recent call last):
    ...
AttributeError: 'H' object has no attribute 'xz'
@end example

@c  # Examples for deleted attributes are not shown because this section
@c  # is already a bit lengthy.  We still test that code here.
@c  >>> del h.x
@c  >>> hasattr(h, 'x')
@c  False
@c 
@c  # Also test the code for uninitialized slots
@c  >>> class HU(Object, metaclass=Type):
@c  ...     slot_names = ['x', 'y']
@c  ...
@c  >>> hu = HU()
@c  >>> hasattr(hu, 'x')
@c  False
@c  >>> hasattr(hu, 'y')
@c  False

@node 函数式编程指引,日志 HOWTO,描述器使用指南,Python 常用指引
@anchor{howto/functional doc}@anchor{4376}@anchor{howto/functional functional-programming-howto}@anchor{4377}
@section 函数式编程指引


@*作者: 
A. M. Kuchling


@*发布版本: 
0.32


本文档提供恰当的 Python 函数式编程范例，在函数式编程简单的介绍之后，将简单介绍Python中关于函数式编程的特性如 @ref{11ba,,iterator} 和 @ref{a8c,,generator} 以及相关库模块如 @ref{a3,,itertools} 和 @ref{83,,functools} 等。

@menu
* 概述: 概述<17>. 
* 迭代器: 迭代器<2>. 
* 生成器表达式和列表推导式:: 
* 生成器: 生成器<2>. 
* 内置函数: 内置函数<2>. 
* itertools 模块:: 
* functools 模块:: 
* 小函数和 lambda 表达式:: 
* 修订记录和致谢:: 
* 引用文献:: 

@end menu

@node 概述<17>,迭代器<2>,,函数式编程指引
@anchor{howto/functional introduction}@anchor{4378}
@subsection 概述


本章介绍函数式编程的基本概念。如您仅想学习 Python 语言的特性，可跳过本章直接查看 @ref{4379,,迭代器}.

编程语言支持通过以下几种方式来解构具体问题：


@itemize *

@item 
大多数的编程语言都是 @strong{过程式} 的，所谓程序就是一连串告诉计算机怎样处理程序输入的指令。C、Pascal 甚至 Unix shells 都是过程式语言。

@item 
在 @strong{声明式} 语言中，你编写一个用来描述待解决问题的说明，并且这个语言的具体实现会指明怎样高效的进行计算。 SQL 可能是你最熟悉的声明式语言了。 一个 SQL 查询语句描述了你想要检索的数据集，并且 SQL 引擎会决定是扫描整张表还是使用索引，应该先执行哪些子句等等。

@item 
@strong{面向对象} 程序会操作一组对象。 对象拥有内部状态，并能够以某种方式支持请求和修改这个内部状态的方法。Smalltalk 和 Java 都是面向对象的语言。 C++ 和 Python 支持面向对象编程，但并不强制使用面向对象特性。

@item 
@strong{函数式} 编程则将一个问题分解成一系列函数。 理想情况下，函数只接受输入并输出结果，对一个给定的输入也不会有影响输出的内部状态。 著名的函数式语言有 ML 家族（Standard ML，Ocaml 以及其他变种）和 Haskell。
@end itemize

一些语言的设计者选择强调一种特定的编程方式。 这通常会让以不同的方式来编写程序变得困难。其他多范式语言则支持几种不同的编程方式。Lisp，C++ 和 Python 都是多范式语言；使用这些语言，你可以编写主要为过程式，面向对象或者函数式的程序和函数库。在大型程序中，不同的部分可能会采用不同的方式编写；比如 GUI 可能是面向对象的而处理逻辑则是过程式或者函数式。

在函数式程序里，输入会流经一系列函数。每个函数接受输入并输出结果。函数式风格反对使用带有副作用的函数，这些副作用会修改内部状态，或者引起一些无法体现在函数的返回值中的变化。完全不产生副作用的函数被称作“纯函数”。消除副作用意味着不能使用随程序运行而更新的数据结构；每个函数的输出必须只依赖于输入。

有些语言对纯洁性要求非常严格，甚至没有诸如`@w{`}a=3`@w{`}或`@w{`}c = a + b`@w{`}之类的赋值语句，但很难避免所有的副作用，如打印到屏幕上或写到磁盘文件之类的副作用。另一个例子是调用 @ref{97a,,print()} 或 @ref{77d,,time.sleep()} 函数，它们都没有返回一个有用的值。这两个函数被调用只是为了它们的副作用，即向屏幕发送一些文本或暂停执行一秒钟。

函数式风格的 Python 程序并不会极端到消除所有 I/O 或者赋值的程度；相反，他们会提供像函数式一样的接口，但会在内部使用非函数式的特性。比如，函数的实现仍然会使用局部变量，但不会修改全局变量或者有其他副作用。

函数式编程可以被认为是面向对象编程的对立面。对象就像是颗小胶囊，包裹着内部状态和随之而来的能让你修改这个内部状态的一组调用方法，以及由正确的状态变化所构成的程序。函数式编程希望尽可能地消除状态变化，只和流经函数的数据打交道。在 Python 里你可以把两种编程方式结合起来，在你的应用（电子邮件信息，事务处理）中编写接受和返回对象实例的函数。

函数式设计在工作中看起来是个奇怪的约束。为什么你要消除对象和副作用呢？不过函数式风格有其理论和实践上的优点：


@itemize *

@item 
形式证明。

@item 
模块化。

@item 
组合性。

@item 
易于调试和测试。
@end itemize

@menu
* 形式证明:: 
* 模块化:: 
* 易于调试和测试:: 
* 组合性:: 

@end menu

@node 形式证明,模块化,,概述<17>
@anchor{howto/functional formal-provability}@anchor{437a}
@subsubsection 形式证明


一个理论上的优点是，构造数学证明来说明函数式程序是正确的相对更容易些。

很长时间，研究者们对寻找证明程序正确的数学方法都很感兴趣。这和通过大量输入来测试，并得出程序的输出基本正确，或者阅读一个程序的源代码然后得出代码看起来没问题不同；相反，这里的目标是一个严格的证明，证明程序对所有可能的输入都能给出正确的结果。

证明程序正确性所用到的技术是写出 @strong{不变量}，也就是对于输入数据和程序中的变量永远为真的特性。然后对每行代码，你说明这行代码执行前的不变量 X 和 Y 以及执行后稍有不同的不变量 X' 和 Y' 为真。如此一直到程序结束，这时候在程序的输出上，不变量应该会与期望的状态一致。

函数式编程之所以要消除赋值，是因为赋值在这个技术中难以处理；赋值可能会破坏赋值前为真的不变量，却并不产生任何可以传递下去的新的不变量。

不幸的是，证明程序的正确性很大程度上是经验性质的，而且和 Python 软件无关。即使是微不足道的程序都需要几页长的证明；一个中等复杂的程序的正确性证明会非常庞大，而且，极少甚至没有你日常所使用的程序（Python 解释器，XML 解析器，浏览器）的正确性能够被证明。即使你写出或者生成一个证明，验证证明也会是一个问题；里面可能出了差错，而你错误地相信你证明了程序的正确性。

@node 模块化,易于调试和测试,形式证明,概述<17>
@anchor{howto/functional modularity}@anchor{437b}
@subsubsection 模块化


函数式编程的一个更实用的优点是，它强制你把问题分解成小的方面。因此程序会更加模块化。相对于一个进行了复杂变换的大型函数，一个小的函数更明确，更易于编写, 也更易于阅读和检查错误。

@node 易于调试和测试,组合性,模块化,概述<17>
@anchor{howto/functional ease-of-debugging-and-testing}@anchor{437c}
@subsubsection 易于调试和测试


测试和调试函数式程序相对来说更容易。

调试很简单是因为函数通常都很小而且清晰明确。当程序无法工作的时候，每个函数都是一个可以检查数据是否正确的接入点。你可以通过查看中间输入和输出迅速找到出错的函数。

测试更容易是因为每个函数都是单元测试的潜在目标。在执行测试前，函数并不依赖于需要重现的系统状态；相反，你只需要给出正确的输入，然后检查输出是否和期望的结果一致。

@node 组合性,,易于调试和测试,概述<17>
@anchor{howto/functional composability}@anchor{437d}
@subsubsection 组合性


当你编写函数式风格的程序时，你会写出很多带有不同输入和输出的函数。其中一些不可避免地会局限于特定的应用，但其他的却可以广泛的用在程序中。举例来说，一个接受文件夹目录返回所有文件夹中的 XML 文件的函数； 或是一个接受文件名，然后返回文件内容的函数，都可以应用在很多不同的场合。

久而久之你会形成一个个人工具库。通常你可以重新组织已有的函数来组成新的程序，然后为当前的工作写一些特殊的函数。

@node 迭代器<2>,生成器表达式和列表推导式,概述<17>,函数式编程指引
@anchor{howto/functional functional-howto-iterators}@anchor{4379}@anchor{howto/functional iterators}@anchor{437e}
@subsection 迭代器


我会从 Python 的一个语言特性， 编写函数式风格程序的重要基石开始说起：迭代器。

迭代器是一个表示数据流的对象；这个对象每次只返回一个元素。Python 迭代器必须支持 @ref{d34,,__next__()} 方法；这个方法不接受参数，并总是返回数据流中的下一个元素。如果数据流中没有元素，@ref{d34,,__next__()} 会抛出 @ref{58a,,StopIteration} 异常。迭代器未必是有限的；完全有理由构造一个输出无限数据流的迭代器。

内置的 @ref{df5,,iter()} 函数接受任意对象并试图返回一个迭代器来输出对象的内容或元素，并会在对象不支持迭代的时候抛出 @ref{1ff,,TypeError} 异常。Python 有几种内置数据类型支持迭代，最常见的就是列表和字典。如果一个对象能生成迭代器，那么它就会被称作 @ref{c84,,iterable}。

你可以手动试验迭代器的接口。

@example
>>> L = [1, 2, 3]
>>> it = iter(L)
>>> it  
<...iterator object at ...>
>>> it.__next__()  # same as next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
@end example

Python 有不少要求使用可迭代的对象的地方，其中最重要的就是 @ref{d02,,for} 表达式。在表达式 @code{for X in Y}，Y 要么自身是一个迭代器，要么能够由 @ref{df5,,iter()} 创建一个迭代器。以下两种表达是等价的:

@example
for i in iter(obj):
    print(i)

for i in obj:
    print(i)
@end example

可以用 @ref{1f9,,list()} 或 @ref{1a2,,tuple()} 这样的构造函数把迭代器具体化成列表或元组:

@example
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> t = tuple(iterator)
>>> t
(1, 2, 3)
@end example

序列的解压操作也支持迭代器：如果你知道一个迭代器能够返回 N 个元素，你可以把他们解压到有 N 个元素的元组:

@example
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> a, b, c = iterator
>>> a, b, c
(1, 2, 3)
@end example

像 @ref{901,,max()} 和 @ref{900,,min()} 这样的内置函数可以接受单个迭代器参数，然后返回其中最大或者最小的元素。@code{"in"} 和 @code{"not in"} 操作也支持迭代器：如果能够在迭代器 iterator 返回的数据流中找到 X 的话，则`@w{`}X in iterator`@w{`} 为真。很显然，如果迭代器是无限的，这么做你就会遇到问题；@ref{901,,max()} 和 @ref{900,,min()} 永远也不会返回；如果元素 X 也不出现在数据流中，@code{"in"} 和 @code{"not in"} 操作同样也永远不会返回。

注意你只能在迭代器中顺序前进；没有获取前一个元素的方法，除非重置迭代器，或者重新复制一份。迭代器对象可以提供这些额外的功能，但迭代器协议只明确了 @ref{d34,,__next__()} 方法。函数可能因此而耗尽迭代器的输出，如果你要对同样的数据流做不同的操作，你必须重新创建一个迭代器。

@menu
* 支持迭代器的数据类型:: 

@end menu

@node 支持迭代器的数据类型,,,迭代器<2>
@anchor{howto/functional data-types-that-support-iterators}@anchor{437f}
@subsubsection 支持迭代器的数据类型


我们已经知道列表和元组支持迭代器。实际上，Python 中的任何序列类型，比如字符串，都自动支持创建迭代器。

对字典调用 @ref{df5,,iter()} 会返回一个遍历字典的键的迭代器:

@example
>>> m = @{'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12@}
>>> for key in m:
...     print(key, m[key])
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
@end example

注意从 Python 3.7 开始，字典的遍历顺序一定和输入顺序一样。先前的版本并没有明确这一点，所以不同的实现可能不一致。

对字典使用 @ref{df5,,iter()} 总是会遍历键，但字典也有返回其他迭代器的方法。如果你只遍历值或者键/值对，你可以明确地调用 @ref{cfe,,values()} 或 @ref{cfd,,items()} 方法得到合适的迭代器。

@ref{164,,dict()} 构造函数可以接受一个迭代器，然后返回一个有限的 @code{(key, value)} 元组的数据流:

@example
>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
@{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'@}
@end example

文件也可以通过调用 @ref{1da3,,readline()} 来遍历，直到穷尽文件中所有的行。这意味着你可以像这样读取文件中的每一行:

@example
for line in file:
    # do something for each line
    ...
@end example

集合可以从可遍历的对象获取内容，也可以让你遍历集合的元素:

@example
S = @{2, 3, 5, 7, 11, 13@}
for i in S:
    print(i)
@end example

@node 生成器表达式和列表推导式,生成器<2>,迭代器<2>,函数式编程指引
@anchor{howto/functional generator-expressions-and-list-comprehensions}@anchor{4380}
@subsection 生成器表达式和列表推导式


迭代器的输出有两个很常见的使用方式，1) 对每一个元素执行操作，2) 选择一个符合条件的元素子集。比如，给定一个字符串列表，你可能想去掉每个字符串尾部的空白字符，或是选出所有包含给定子串的字符串。

列表推导式和生成器表达时（简写："listcomps" 和 "genexps"）让这些操作更加简明，这个形式借鉴自函数式程序语言 Haskell（@indicateurl{https://www.haskell.org/}）。你可以用以下代码去掉一个字符串流中的所有空白字符:

@example
line_list = ['  line 1\n', 'line 2  \n', ...]

# Generator expression -- returns iterator
stripped_iter = (line.strip() for line in line_list)

# List comprehension -- returns list
stripped_list = [line.strip() for line in line_list]
@end example

你可以加上条件语句 @code{"if"} 来选取特定的元素:

@example
stripped_list = [line.strip() for line in line_list
                 if line != ""]
@end example

通过列表推导式，你会获得一个 Python 列表；@code{stripped_list} 就是一个包含所有结果行的列表，并不是迭代器。 生成器表达式会返回一个迭代器，它在必要的时候计算结果，避免一次性生成所有的值。 这意味着，如果迭代器返回一个无限数据流或者大量的数据，列表推导式就不太好用了。 这种情况下生成器表达式会更受青睐。

生成器表达式两边使用圆括号 ("()") ，而列表推导式则使用方括号 ("[]")。生成器表达式的形式为:

@example
( expression for expr in sequence1
             if condition1
             for expr2 in sequence2
             if condition2
             for expr3 in sequence3 ...
             if condition3
             for exprN in sequenceN
             if conditionN )
@end example

再次说明，列表推导式只有两边的括号不一样（方括号而不是圆括号）。

这些生成用于输出的元素会成为 @code{expression} 的后继值。其中 @code{if} 语句是可选的；如果给定的话 @code{expression} 只会在符合条件时计算并加入到结果中。

生成器表达式总是写在圆括号里面，不过也可以算上调用函数时用的括号。如果你想即时创建一个传递给函数的迭代器，可以这么写:

@example
obj_total = sum(obj.count for obj in list_all_objects())
@end example

其中 @code{for...in} 语句包含了将要遍历的序列。这些序列并不必须同样长，因为它们会从左往右开始遍历，而 @strong{不是} 同时执行。对每个 @code{sequence1} 中的元素，@code{sequence2} 会从头开始遍历。@code{sequence3} 会对每个 @code{sequence1} 和 @code{sequence2} 的元素对开始遍历。

换句话说，列表推导式器是和下面的 Python 代码等价:

@example
for expr1 in sequence1:
    if not (condition1):
        continue   # Skip this element
    for expr2 in sequence2:
        if not (condition2):
            continue   # Skip this element
        ...
        for exprN in sequenceN:
            if not (conditionN):
                continue   # Skip this element

            # Output the value of
            # the expression.
@end example

这说明，如果有多个 @code{for...in} 语句而没有 @code{if} 语句，输出结果的长度就是所有序列长度的乘积。如果你的两个列表长度为3，那么输出的列表长度就是9:

@example
>>> seq1 = 'abc'
>>> seq2 = (1, 2, 3)
>>> [(x, y) for x in seq1 for y in seq2]  
[('a', 1), ('a', 2), ('a', 3),
 ('b', 1), ('b', 2), ('b', 3),
 ('c', 1), ('c', 2), ('c', 3)]
@end example

为了不让 Python 语法变得含糊，如果 @code{expression} 会生成元组，那这个元组必须要用括号括起来。下面第一个列表推导式语法错误，第二个则是正确的:

@example
# Syntax error
[x, y for x in seq1 for y in seq2]
# Correct
[(x, y) for x in seq1 for y in seq2]
@end example

@node 生成器<2>,内置函数<2>,生成器表达式和列表推导式,函数式编程指引
@anchor{howto/functional generators}@anchor{4381}
@subsection 生成器


生成器是一类用来简化编写迭代器工作的特殊函数。普通的函数计算并返回一个值，而生成器返回一个能返回数据流的迭代器。

毫无疑问，你已经对如何在 Python 和 C 中调用普通函数很熟悉了，这时候函数会获得一个创建局部变量的私有命名空间。当函数到达 @code{return} 表达式时，局部变量会被销毁然后把返回给调用者。之后调用同样的函数时会创建一个新的私有命名空间和一组全新的局部变量。但是，如果在退出一个函数时不扔掉局部变量会如何呢？如果稍后你能够从退出函数的地方重新恢复又如何呢？这就是生成器所提供的；他们可以被看成可恢复的函数。

这里有简单的生成器函数示例:

@example
>>> def generate_ints(N):
...    for i in range(N):
...        yield i
@end example

任何包含了 @ref{2ce,,yield} 关键字的函数都是生成器函数；Python 的 @ref{713,,bytecode} 编译器会在编译的时候检测到并因此而特殊处理。

当你调用一个生成器函数，它并不会返回单独的值，而是返回一个支持生成器协议的生成器对象。当执行 @code{yield} 表达式时，生成器会输出 @code{i} 的值，就像 @code{return} 表达式一样。@code{yield} 和 @code{return} 最大的区别在于，到达 @code{yield} 的时候生成器的执行状态会挂起并保留局部变量。在下一次调用生成器 @ref{143f,,__next__()} 方法的时候，函数会恢复执行。

这里有一个 @code{generate_ints()} 生成器的示例:

@example
>>> gen = generate_ints(3)
>>> gen  
<generator object generate_ints at ...>
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
  File "stdin", line 1, in <module>
  File "stdin", line 2, in generate_ints
StopIteration
@end example

同样，你可以写出 @code{for i in generate_ints(5)}，或者 @code{a, b, c = generate_ints(3)}。

在生成器函数里面，@code{return value} 会触发从 @ref{143f,,__next__()} 方法抛出 @code{StopIteration(value)} 异常。一旦抛出这个异常，或者函数结束，处理数据的过程就会停止，生成器也不会再生成新的值。

你可以手动编写自己的类来达到生成器的效果，把生成器的所有局部变量作为实例的成员变量存储起来。比如，可以这么返回一个整数列表：把 @code{self.count} 设为0，然后通过 @code{count`()}。然而，对于一个中等复杂程度的生成器，写出一个相应的类可能会相当繁杂。

包含在 Python 库中的测试套件 Lib/test/test_generators.py@footnote{https://github.com/python/cpython/tree/3.9/Lib/test/test_generators.py} 里有很多非常有趣的例子。这里是一个用生成器实现树的递归中序遍历示例。:

@example
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x
@end example

另外两个 @code{test_generators.py} 中的例子给出了 N 皇后问题（在 NxN 的棋盘上放置 N 个皇后，任何一个都不能吃掉另一个），以及马的遍历路线（在NxN 的棋盘上给马找出一条不重复的走过所有格子的路线）的解。

@menu
* 向生成器传递值:: 

@end menu

@node 向生成器传递值,,,生成器<2>
@anchor{howto/functional passing-values-into-a-generator}@anchor{4382}
@subsubsection 向生成器传递值


在 Python 2.4 及之前的版本中，生成器只产生输出。一旦调用生成器的代码创建一个迭代器，就没有办法在函数恢复执行的时候向它传递新的信息。你可以设法实现这个功能，让生成器引用一个全局变量或者一个调用者可以修改的可变对象，但是这些方法都很繁杂。

在 Python 2.5 里有一个简单的将值传递给生成器的方法。@ref{2ce,,yield} 变成了一个表达式，返回一个可以赋给变量或执行操作的值:

@example
val = (yield i)
@end example

我建议你在处理 @code{yield} 表达式返回值的时候， @strong{总是} 两边写上括号，就像上面的例子一样。括号并不总是必须的，但是比起记住什么时候需要括号，写出来会更容易一点。

（
@geindex Python 提高建议; PEP 342
PEP 342@footnote{https://www.python.org/dev/peps/pep-0342} 解释了具体的规则，也就是 @code{yield} 表达式必须括起来，除非是出现在最顶级的赋值表达式的右边。这意味着你可以写 @code{val = yield i}，但是必须在操作的时候加上括号，就像`@w{`}val = (yield i) + 12`@w{`}）

可以调用 @code{send(value)()} <generator.send> 方法向生成器发送值。这个方法会恢复执行生成器的代码，然后 @code{yield} 表达式返回特定的值。如果调用普通的 @code{__next__`方法，`@w{`}yield`()} 会返回 @code{None}.

这里有一个简单的每次加1的计数器，并允许改变内部计数器的值。

@example
def counter(maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1
@end example

这是改变计数器的一个示例

@example
>>> it = counter(10)  
>>> next(it)  
0
>>> next(it)  
1
>>> it.send(8)  
8
>>> next(it)  
9
>>> next(it)  
Traceback (most recent call last):
  File "t.py", line 15, in <module>
    it.next()
StopIteration
@end example

因为 @code{yield} 很多时候会返回 @code{None}，所以你应该总是检查这个情况。不要在表达式中使用 @code{yield} 的值，除非你确定 @ref{15fc,,send()} 是唯一的用来恢复你的生成器函数的方法。

除了 @ref{15fc,,send()} 之外，生成器还有两个其他的方法:


@itemize *

@item 
@ref{1042,,throw(value)} 用于在生成器内部抛出异常；这个异常会在生成器暂停执行的时候由 @code{yield} 表达式抛出。

@item 
@ref{15ff,,generator.close()} 会在生成器内部抛出 @ref{e00,,GeneratorExit} 异常来结束迭代。当接收到这个异常时，生成器的代码会抛出 @ref{e00,,GeneratorExit} 或者 @ref{58a,,StopIteration}；捕捉这个异常作其他处理是非法的，并会出发 @ref{3e4,,RuntimeError}。@ref{15ff,,close()} 也会在 Python 垃圾回收器回收生成器的时候调用。

如果你要在 @ref{e00,,GeneratorExit} 发生的时候清理代码，我建议使用 @code{try: ... finally:} 组合来代替 @ref{e00,,GeneratorExit}。
@end itemize

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消费者。

生成器也可以成为 @strong{协程} ，一种更广义的子过程形式。子过程可以从一个地方进入，然后从另一个地方退出（从函数的顶端进入，从 @code{return} 语句退出），而协程可以进入，退出，然后在很多不同的地方恢复（@code{yield} 语句）。

@node 内置函数<2>,itertools 模块,生成器<2>,函数式编程指引
@anchor{howto/functional built-in-functions}@anchor{4383}
@subsection 内置函数


我们可以看看迭代器常常用到的函数的更多细节。

Python 内置的两个函数 @ref{cff,,map()} 和 @ref{d00,,filter()} 复制了生成器表达式的两个特性:


@table @asis

@item @ref{cff,,map(f@comma{} iterA@comma{} iterB@comma{} ...)} 返回一个遍历序列的迭代器

@code{f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...}.

@example
>>> def upper(s):
...     return s.upper()
@end example

@example
>>> list(map(upper, ['sentence', 'fragment']))
['SENTENCE', 'FRAGMENT']
>>> [upper(s) for s in ['sentence', 'fragment']]
['SENTENCE', 'FRAGMENT']
@end example
@end table

你当然也可以用列表推导式达到同样的效果。

@ref{d00,,filter(predicate@comma{} iter)} 返回一个遍历序列中满足指定条件的元素的迭代器，和列表推导式的功能相似。 @strong{predicate} （谓词）是一个在特定条件下返回真值的函数；要使用函数 @ref{d00,,filter()}，谓词函数必须只能接受一个参数。

@example
>>> def is_even(x):
...     return (x % 2) == 0
@end example

@example
>>> list(filter(is_even, range(10)))
[0, 2, 4, 6, 8]
@end example

这也可以写成列表推导式:

@example
>>> list(x for x in range(10) if is_even(x))
[0, 2, 4, 6, 8]
@end example

@ref{eaf,,enumerate(iter@comma{} start=0)} 计数可迭代对象中的元素，然后返回包含每个计数（从 @strong{start} 开始）和元素两个值的元组。:

@example
>>> for item in enumerate(['subject', 'verb', 'object']):
...     print(item)
(0, 'subject')
(1, 'verb')
(2, 'object')
@end example

@ref{eaf,,enumerate()} 常常用于遍历列表并记录达到特定条件时的下标:

@example
f = open('data.txt', 'r')
for i, line in enumerate(f):
    if line.strip() == '@w{'}:
        print('Blank line at line #%i' % i)
@end example

@ref{54f,,sorted(iterable@comma{} key=None@comma{} reverse=False)} 会将 iterable 中的元素收集到一个列表中，然后排序并返回结果。其中 @emph{key} 和 @emph{reverse} 参数会传递给所创建列表的 @ref{550,,sort()} 方法。:

@example
>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list  
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)  
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)  
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
@end example

（对排序更详细的讨论可参见 @ref{1767,,排序指南}。）

内置函数 @ref{e51,,any(iter)} 和 @ref{e52,,all(iter)} 会查看一个可迭代对象内容的逻辑值。@ref{e51,,any()} 在可迭代对象中任意一个元素为真时返回 @code{True}，而 @ref{e52,,all()} 在所有元素为真时返回 @code{True}:

@example
>>> any([0, 1, 0])
True
>>> any([0, 0, 0])
False
>>> any([1, 1, 1])
True
>>> all([0, 1, 0])
False
>>> all([0, 0, 0])
False
>>> all([1, 1, 1])
True
@end example

@ref{d04,,zip(iterA@comma{} iterB@comma{} ...)} 从每个可迭代对象中选取单个元素组成列表并返回:

@example
zip(['a', 'b', 'c'], (1, 2, 3)) =>
  ('a', 1), ('b', 2), ('c', 3)
@end example

它并不会在内存创建一个列表并因此在返回前而耗尽输入的迭代器；相反，只有在被请求的时候元组才会创建并返回。（这种行为的技术术语叫惰性计算，参见 lazy evaluation@footnote{https://en.wikipedia.org/wiki/Lazy_evaluation}.）

这个迭代器设计用于长度相同的可迭代对象。如果可迭代对象的长度不一致，返回的数据流的长度会和最短的可迭代对象相同

@example
zip(['a', 'b'], (1, 2, 3)) =>
  ('a', 1), ('b', 2)
@end example

然而，你应该避免这种情况，因为所有从更长的迭代器中取出的元素都会被丢弃。这意味着之后你也无法冒着跳过被丢弃元素的风险来继续使用这个迭代器。

@node itertools 模块,functools 模块,内置函数<2>,函数式编程指引
@anchor{howto/functional the-itertools-module}@anchor{4384}
@subsection itertools 模块


@ref{a3,,itertools} 模块包含很多常用的迭代器以及用来组合迭代器的函数。本节会用些小的例子来介绍这个模块的内容。

这个模块里的函数大致可以分为几类：


@itemize *

@item 
从已有的迭代器创建新的迭代器的函数。

@item 
接受迭代器元素作为参数的函数。

@item 
选取部分迭代器输出的函数。

@item 
给迭代器输出分组的函数。
@end itemize

@menu
* 创建新的迭代器:: 
* 对元素使用函数:: 
* 选择元素:: 
* 组合函数:: 
* 为元素分组:: 

@end menu

@node 创建新的迭代器,对元素使用函数,,itertools 模块
@anchor{howto/functional creating-new-iterators}@anchor{4385}
@subsubsection 创建新的迭代器


@ref{ced,,itertools.count(start@comma{} step)} 返回一个等分的无限数据流。初始值默认为0，间隔默认为1，你也选择可以指定初始值和间隔:

@example
itertools.count() =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
itertools.count(10) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.count(10, 5) =>
  10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
@end example

@ref{1ce2,,itertools.cycle(iter)} 保存一份所提供的可迭代对象的副本，并返回一个能产生整个可迭代对象序列的新迭代器。新迭代器会无限重复这些元素。:

@example
itertools.cycle([1, 2, 3, 4, 5]) =>
  1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
@end example

@ref{122f,,itertools.repeat(elem@comma{} [n])} 返回 @emph{n} 次所提供的元素，当 @emph{n} 不存在时，返回无数次所提供的元素。

@example
itertools.repeat('abc') =>
  abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
itertools.repeat('abc', 5) =>
  abc, abc, abc, abc, abc
@end example

@ref{1768,,itertools.chain(iterA@comma{} iterB@comma{} ...)} 接受任意数量的可迭代对象作为输入，首先返回第一个迭代器的所有元素，然后是第二个的所有元素，如此一直进行下去，直到消耗掉所有输入的可迭代对象。

@example
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
  a, b, c, 1, 2, 3
@end example

@ref{4b1,,itertools.islice(iter@comma{} [start]@comma{} stop@comma{} [step])} 返回一个所输入的迭代器切片的数据流。如果只单独给定 @emph{stop} 参数的话，它会返回从起始算起 @emph{stop} 个数量的元素。如果你提供了起始下标 @emph{start}，你会得到 @emph{stop-start} 个元素；如果你给定了 @emph{step} 参数，数据流会跳过相应的元素。和 Python 里的字符串和列表切片不同，你不能在 @emph{start}, @emph{stop} 或者 @emph{step} 这些参数中使用负数。:

@example
itertools.islice(range(10), 8) =>
  0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
  2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
  2, 4, 6
@end example

@ref{1ce7,,itertools.tee(iter@comma{} [n])} 可以复制一个迭代器；它返回 @emph{n} 个能够返回源迭代器内容的独立迭代器。如果你不提供参数 @emph{n}，默认值为 2。复制迭代器需要保存源迭代器的一部分内容，因此在源迭代器比较大的时候会显著地占用内存；同时，在所有新迭代器中，有一个迭代器会比其他迭代器占用更多的内存。

@example
itertools.tee( itertools.count() ) =>
   iterA, iterB

where iterA ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

and   iterB ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
@end example

@node 对元素使用函数,选择元素,创建新的迭代器,itertools 模块
@anchor{howto/functional calling-functions-on-elements}@anchor{4386}
@subsubsection 对元素使用函数


@ref{c2,,operator} 模块包含一组对应于 Python 操作符的函数。比如 @ref{1d0a,,operator.add(a@comma{} b)} （把两个数加起来），@ref{1cfa,,operator.ne(a@comma{} b)} （和 @code{a != b} 相同），以及 @ref{814,,operator.attrgetter('id')} （返回获取 @code{.id} 属性的可调用对象）。

@ref{b0e,,itertools.starmap(func@comma{} iter)} 假定可迭代对象能够返回一个元组的流，并且利用这些元组作为参数来调用 @emph{func}:

@example
itertools.starmap(os.path.join,
                  [('/bin', 'python'), ('/usr', 'bin', 'java'),
                   ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
=>
  /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
@end example

@node 选择元素,组合函数,对元素使用函数,itertools 模块
@anchor{howto/functional selecting-elements}@anchor{4387}
@subsubsection 选择元素


另外一系列函数根据谓词选取一个迭代器中元素的子集。

@ref{1752,,itertools.filterfalse(predicate@comma{} iter)} 和  @ref{d00,,filter()} 相反，返回所有让 predicate 返回 false 的元素:

@example
itertools.filterfalse(is_even, itertools.count()) =>
  1, 3, 5, 7, 9, 11, 13, 15, ...
@end example

@ref{1ce6,,itertools.takewhile(predicate@comma{} iter)} 返回一直让 predicate 返回 true 的元素。一旦 predicate 返回 false，迭代器就会发出终止结果的信号。:

@example
def less_than_10(x):
    return x < 10

itertools.takewhile(less_than_10, itertools.count()) =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9

itertools.takewhile(is_even, itertools.count()) =>
  0
@end example

@ref{1ce4,,itertools.dropwhile(predicate@comma{} iter)} 在 predicate 返回 true 的时候丢弃元素，并且返回可迭代对象的剩余结果。:

@example
itertools.dropwhile(less_than_10, itertools.count()) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

itertools.dropwhile(is_even, itertools.count()) =>
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
@end example

@ref{cec,,itertools.compress(data@comma{} selectors)} 接受两个迭代器，然后返回 @emph{data} 中使相应地 @emph{selector} 中的元素为真的元素；它会在任一个迭代器耗尽的时候停止:

@example
itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
   1, 2, 5
@end example

@node 组合函数,为元素分组,选择元素,itertools 模块
@anchor{howto/functional combinatoric-functions}@anchor{4388}
@subsubsection 组合函数


@ref{d76,,itertools.combinations(iterable@comma{} r)} 返回一个迭代器，它能给出输入迭代器中所包含的元素的所有可能的 @emph{r} 元元组的组合。:

@example
itertools.combinations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 3), (2, 4), (2, 5),
  (3, 4), (3, 5),
  (4, 5)

itertools.combinations([1, 2, 3, 4, 5], 3) =>
  (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
  (2, 3, 4), (2, 3, 5), (2, 4, 5),
  (3, 4, 5)
@end example

每个元组中的元素保持着 @emph{可迭代对象} 返回他们的顺序。例如，在上面的例子中数字 1 总是会在 2, 3, 4 或 5 前面。一个类似的函数，@ref{1014,,itertools.permutations(iterable@comma{} r=None)}，取消了保持顺序的限制，返回所有可能的长度为 @emph{r} 的排列:

@example
itertools.permutations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 1), (2, 3), (2, 4), (2, 5),
  (3, 1), (3, 2), (3, 4), (3, 5),
  (4, 1), (4, 2), (4, 3), (4, 5),
  (5, 1), (5, 2), (5, 3), (5, 4)

itertools.permutations([1, 2, 3, 4, 5]) =>
  (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
  ...
  (5, 4, 3, 2, 1)
@end example

如果你不提供 @emph{r} 参数的值，它会使用可迭代对象的长度，也就是说会排列所有的元素。

注意这些函数会输出所有可能的位置组合，并不要求 @emph{可迭代对象} 的内容不重复:

@example
itertools.permutations('aba', 3) =>
  ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
  ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
@end example

同一个元组 @code{('a', 'a', 'b')} 出现了两次，但是两个 'a' 字符来自不同的位置。

@ref{ceb,,itertools.combinations_with_replacement(iterable@comma{} r)} 函数放松了一个不同的限制：元组中的元素可以重复。从概念讲，为每个元组第一个位置选取一个元素，然后在选择第二个元素前替换掉它。:

@example
itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
  (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 2), (2, 3), (2, 4), (2, 5),
  (3, 3), (3, 4), (3, 5),
  (4, 4), (4, 5),
  (5, 5)
@end example

@node 为元素分组,,组合函数,itertools 模块
@anchor{howto/functional grouping-elements}@anchor{4389}
@subsubsection 为元素分组


我要讨论的最后一个函数，@ref{1ce5,,itertools.groupby(iter@comma{}key_func=None)}，是最复杂的函数。 @code{key_func(elem)} 是一个可以对迭代器返回的每个元素计算键值的函数。 如果你不提供这个键值函数，它就会简化成每个元素自身。

@ref{1ce5,,groupby()} 从所依据的可迭代对象中连续地收集具有相同值的元素，然后返回一个长度为2的元组的数据流, 每个元组包含键值以及对应这个键值的元素所组成的迭代器。

@example
city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
             ('Anchorage', 'AK'), ('Nome', 'AK'),
             ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
             ...
            ]

def get_state(city_state):
    return city_state[1]

itertools.groupby(city_list, get_state) =>
  ('AL', iterator-1),
  ('AK', iterator-2),
  ('AZ', iterator-3), ...

where
iterator-1 =>
  ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
  ('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
  ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
@end example

@ref{1ce5,,groupby()} 假定了所依据的可迭代对象的内容已经根据键值排序。注意，返回的迭代器也会使用所依据的可迭代对象，所以在请求迭代器 2和相应的键之前你必须先消耗迭代器 1 的结果。

@node functools 模块,小函数和 lambda 表达式,itertools 模块,函数式编程指引
@anchor{howto/functional the-functools-module}@anchor{438a}
@subsection functools 模块


Python 2.5 中的 @ref{83,,functools} 模块包含了一些高阶函数。 @strong{高阶函数} 接受一个或多个函数作为输入，返回新的函数。 这个模块中最有用的工具是 @ref{8bf,,functools.partial()} 函数。

对于用函数式风格编写的程序，有时你会希望通过给定部分参数，将已有的函数构变形称新的函数。考虑一个 Python 函数 @code{f(a, b, c)}；你希望创建一个和 @code{f(1, b, c)} 等价的新函数 @code{g(b, c)}；也就是说你给定了 @code{f()} 的一个参数的值。这就是所谓的“部分函数应用”。

@ref{8bf,,partial()} 接受参数 @code{(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)}。它会返回一个可调用的对象，所以你能够直接调用这个结果以使用给定参数的 @code{function}。

这里有一个很小但很现实的例子:

@example
import functools

def log(message, subsystem):
    """Write the contents of 'message' to the specified subsystem."""
    print('%s: %s' % (subsystem, message))
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
@end example

@ref{d3f,,functools.reduce(func@comma{} iter@comma{} [initial_value])} 持续地在可迭代对象的所有元素上执行操作，因此它不能够用在无限的可迭代对象上。@emph{func} 必须是一个接受两个元素并返回一个值的函数。@ref{d3f,,functools.reduce()} 接受迭代器返回的前两个元素 A 和 B 并计算 @code{func(A, B)} 。然后它会请求第三个元素，C，计算 @code{func(func(A, B), C)}，然后把这个结果再和第四个元素组合并返回，如此继续下去直到消耗整个可迭代对象。如果输入的可迭代对象完全不返回任何值，@ref{1ff,,TypeError} 异常就会抛出。如果提供了初值(initial value)，它会被用作起始值，也就是先计算 @code{func(initial_value, A)} 。:

@example
>>> import operator, functools
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> functools.reduce(operator.concat, [])
Traceback (most recent call last):
  ...
TypeError: reduce() of empty sequence with no initial value
>>> functools.reduce(operator.mul, [1, 2, 3], 1)
6
>>> functools.reduce(operator.mul, [], 1)
1
@end example

如果你在 @ref{d3f,,functools.reduce()} 中使用 @ref{1d0a,,operator.add()}，你就会把可迭代对象中的所有元素加起来.这种情况非常常见, 所以 Python 有一个特殊的内置函数 @ref{31d,,sum()}:

@example
>>> import functools, operator
>>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
10
>>> sum([1, 2, 3, 4])
10
>>> sum([])
0
@end example

不过, 对于很多使用 @ref{d3f,,functools.reduce()} 的情形, 使用明显的 @ref{d02,,for} 循环会更清晰:

@example
import functools
# Instead of:
product = functools.reduce(operator.mul, [1, 2, 3], 1)

# You can write:
product = 1
for i in [1, 2, 3]:
    product *= i
@end example

一个相关的函数是 @ref{315,,itertools.accumulate(iterable@comma{} func=operator.add)} 。它执行同样的计算, 不过相对于只返回最终结果，@code{accumulate()} 会返回一个迭代器来输出所有中间结果:

@example
itertools.accumulate([1, 2, 3, 4, 5]) =>
  1, 3, 6, 10, 15

itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
  1, 2, 6, 24, 120
@end example

@menu
* operator 模块:: 

@end menu

@node operator 模块,,,functools 模块
@anchor{howto/functional the-operator-module}@anchor{438b}
@subsubsection operator 模块


前面已经提到了 @ref{c2,,operator} 模块。它包含一系列对应于 Python 操作符的函数。在函数式风格的代码中，这些函数通常很有用，可以帮你省下不少时间，避免写一些琐碎的仅仅执行一个简单操作的函数。

这个模块里的一些函数：


@itemize *

@item 
数学运算： @code{add()}，@code{sub()}，@code{mul()}，@code{floordiv()}，@code{abs()}， ...

@item 
逻辑运算： @code{not_()}，@code{truth()}。

@item 
位运算： @code{and_()}，@code{or_()}，@code{invert()}。

@item 
比较： @code{eq()}，@code{ne()}，@code{lt()}，@code{le()}，@code{gt()}，和 @code{ge()}。

@item 
确认对象： @code{is_()}，@code{is_not()}。
@end itemize

全部函数列表可以参考 operator 模块的文档。

@node 小函数和 lambda 表达式,修订记录和致谢,functools 模块,函数式编程指引
@anchor{howto/functional small-functions-and-the-lambda-expression}@anchor{438c}
@subsection 小函数和 lambda 表达式


编写函数式风格程序时，你会经常需要很小的函数，作为谓词函数或者以某种方式来组合元素。

如果合适的 Python 内置的或者其他模块中的函数，你就一点也不需要定义新的函数:

@example
stripped_lines = [line.strip() for line in lines]
existing_files = filter(os.path.exists, file_list)
@end example

如果不存在你需要的函数，你就必须自己编写。一个编写小函数的方式是使用 @ref{d01,,lambda} 表达式。@code{lambda} 接受一组参数以及组合这些参数的表达式，它会创建一个返回表达式值的匿名函数:

@example
adder = lambda x, y: x+y

print_assign = lambda name, value: name + '=' + str(value)
@end example

另一种替代方案就是通常的使用 @code{def} 语句来定义函数:

@example
def adder(x, y):
    return x + y

def print_assign(name, value):
    return name + '=' + str(value)
@end example

哪一种更受青睐呢？这是一个风格问题；我通常的做法是避免使用 @code{lambda}。

我这么偏好的一个原因是，@code{lambda} 能够定义的函数非常受限。函数的结果必须能够作为单独的表达式来计算，这意味着你不能使用多路 @code{if... elif... else} 比较，或者 @code{try... except} 语句。如果你尝试在 @code{lambda} 语句中做太多事情，你最终会把表达式过于复杂以至于难以阅读。你能快速的说出下面的代码做了什么事情吗？:

@example
import functools
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
@end example

你可以弄明白，不过要花上时间来理清表达式来搞清楚发生了什么。使用一个简短的嵌套的 @code{def} 语句可以让情况变得更好:

@example
import functools
def combine(a, b):
    return 0, a[1] + b[1]

total = functools.reduce(combine, items)[1]
@end example

如果我仅仅使用一个 @code{for} 循环会更好:

@example
total = 0
for a, b in items:
    total += b
@end example

或者使用内置的 @ref{31d,,sum()} 和一个生成器表达式:

@example
total = sum(b for a, b in items)
@end example

许多使用 @ref{d3f,,functools.reduce()} 的情形可以更清晰地写成 @code{for} 循环的形式。

Fredrik Lundh 曾经建议以下一组规则来重构 @code{lambda} 的使用:


@enumerate 

@item 
写一个 lambda 函数。

@item 
写一句注释来说明这个 lambda 究竟干了什么。

@item 
研究一会这个注释，然后想出一个抓住注释本质的名字。

@item 
用这个名字，把这个 lambda 改写成 def 语句。

@item 
把注释去掉。
@end enumerate

我非常喜欢这些规则，不过你完全有权利争辩这种消除 lambda 的风格是不是更好。

@node 修订记录和致谢,引用文献,小函数和 lambda 表达式,函数式编程指引
@anchor{howto/functional revision-history-and-acknowledgements}@anchor{438d}
@subsection 修订记录和致谢


作者要感谢以下人员对本文各种草稿给予的建议，更正和协助：Ian Bicking,Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell,Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton。

0.1 版: 2006 年 6 月 30 日发布。

0.11 版: 2006 年 7 月 1 日发布。 修正拼写错误。

0.2 版: 2006 年 7 月 10 日发布。 将 genexp 与 listcomp 两节合二为一。 修正拼写错误。

0.21 版: 加入了 tutor 邮件列表中建议的更多参考文件。

0.30 版: 添加了有关 @code{functional} 模块的小节，由 Collin Winter 撰写；添加了有关 operator 模块的简短小节；其他少量修改。

@node 引用文献,,修订记录和致谢,函数式编程指引
@anchor{howto/functional references}@anchor{438e}
@subsection 引用文献


@menu
* 通用文献:: 
* Python 相关:: 
* Python 文档:: 

@end menu

@node 通用文献,Python 相关,,引用文献
@anchor{howto/functional general}@anchor{438f}
@subsubsection 通用文献


@strong{Structure and Interpretation of Computer Programs}, Harold Abelson, Gerald Jay Sussman 和 Julie Sussman 著。全文可见 @indicateurl{https://mitpress.mit.edu/sicp/} 。在这部计算机科学的经典教科书中，第二和第三章讨论了使用序列和流来组织程序内部的数据传递。书中的示例采用 Scheme 语言，但其中这些章节中描述的很多设计方法同样适用于函数式风格的 Python 代码。

@indicateurl{http://www.defmacro.org/ramblings/fp.html}: 一个使用 Java 示例的函数式编程的总体介绍，有很长的历史说明。

@indicateurl{https://en.wikipedia.org/wiki/Functional_programming}: 一般性的函数式编程的 Wikipedia 条目。

@indicateurl{https://en.wikipedia.org/wiki/Coroutine}: 协程条目。

@indicateurl{https://en.wikipedia.org/wiki/Currying}: 函数柯里化条目。

@node Python 相关,Python 文档,通用文献,引用文献
@anchor{howto/functional python-specific}@anchor{4390}
@subsubsection Python 相关


@indicateurl{http://gnosis.cx/TPiP/}：David Mertz 书中的第一章 @cite{Text Processing in Python}，"Utilizing Higher-Order Functions in Text Processing" 标题部分讨论了文本处理的函数式编程。

Mertz 还在 IBM 的 DeveloperWorks 站点上针对函数式编程撰写了一系列共 3 篇文章；参见 part 1@footnote{https://developer.ibm.com/articles/l-prog/}, part 2@footnote{https://developer.ibm.com/tutorials/l-prog2/} 和 part 3@footnote{https://developer.ibm.com/tutorials/l-prog3/},

@node Python 文档,,Python 相关,引用文献
@anchor{howto/functional python-documentation}@anchor{4391}
@subsubsection Python 文档


@ref{a3,,itertools} 模块文档。

@ref{83,,functools} 模块文档。

@ref{c2,,operator} 模块文档。

@geindex Python 提高建议; PEP 289
PEP 289@footnote{https://www.python.org/dev/peps/pep-0289}: "Generator Expressions"

@geindex Python 提高建议; PEP 342
PEP 342@footnote{https://www.python.org/dev/peps/pep-0342}: "Coroutines via Enhanced Generators" 描述了 Python 2.5 中新的生成器特性。

@c comment
@c 
@c Handy little function for printing part of an iterator -- used
@c while writing this document.
@c 
@c import itertools
@c def print_iter(it):
@c      slice = itertools.islice(it, 10)
@c      for elem in slice[:-1]:
@c          sys.stdout.write(str(elem))
@c          sys.stdout.write(', ')
@c     print(elem[-1])

@node 日志 HOWTO,日志操作手册,函数式编程指引,Python 常用指引
@anchor{howto/logging doc}@anchor{4392}@anchor{howto/logging logging-howto}@anchor{4393}
@section 日志 HOWTO


@*作者: 
Vinay Sajip <vinay_sajip at red-dove dot com>


@menu
* 日志基础教程:: 
* 进阶日志教程:: 
* 日志级别: 日志级别<2>. 
* 有用的处理器:: 
* 记录日志时引发的异常:: 
* 使用任意对象作为消息:: 
* 优化:: 

@end menu

@node 日志基础教程,进阶日志教程,,日志 HOWTO
@anchor{howto/logging basic-logging-tutorial}@anchor{4394}@anchor{howto/logging logging-basic-tutorial}@anchor{c4c}
@subsection 日志基础教程


日志是对软件执行时所发生事件的一种追踪方式。软件开发人员对他们的代码添加日志调用，借此来指示某事件的发生。一个事件通过一些包含变量数据的描述信息来描述（比如：每个事件发生时的数据都是不同的）。开发者还会区分事件的重要性，重要性也被称为 @emph{等级} 或 @emph{严重性}。

@menu
* 什么时候使用日志:: 
* 一个简单的例子: 一个简单的例子<2>. 
* 记录日志到文件:: 
* 从多个模块记录日志:: 
* 记录变量数据:: 
* 更改显示消息的格式:: 
* 在消息中显示日期/时间:: 
* 后续步骤:: 

@end menu

@node 什么时候使用日志,一个简单的例子<2>,,日志基础教程
@anchor{howto/logging when-to-use-logging}@anchor{4395}
@subsubsection 什么时候使用日志


对于简单的日志使用来说日志功能提供了一系列便利的函数。它们是 @ref{220f,,debug()}，@ref{223a,,info()}，@ref{224c,,warning()}，@ref{224d,,error()} 和 @ref{224e,,critical()}。想要决定何时使用日志，请看下表，其中显示了对于每个通用任务集合来说最好的工具。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

你想要执行的任务

@tab

此任务的最好的工具

@item

对于命令行或程序的应用，结果显示在控制台。

@tab

@ref{97a,,print()}

@item

在对程序的普通操作发生时提交事件报告(比如：状态监控和错误调查)

@tab

@ref{223a,,logging.info()} 函数(当有诊断目的需要详细输出信息时使用 @ref{220f,,logging.debug()} 函数)

@item

提出一个警告信息基于一个特殊的运行时事件

@tab

@ref{f22,,warnings.warn()} 位于代码库中，该事件是可以避免的，需要修改客户端应用以消除告警

@ref{224c,,logging.warning()} 不需要修改客户端应用，但是该事件还是需要引起关注

@item

对一个特殊的运行时事件报告错误

@tab

引发异常

@item

报告错误而不引发异常(如在长时间运行中的服务端进程的错误处理)

@tab

@ref{224d,,logging.error()}, @ref{224f,,logging.exception()} 或 @ref{224e,,logging.critical()} 分别适用于特定的错误及应用领域

@end multitable


日志功能应以所追踪事件级别或严重性而定。各级别适用性如下（以严重性递增）：


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

级别

@tab

何时使用

@item

@code{DEBUG}

@tab

细节信息，仅当诊断问题时适用。

@item

@code{INFO}

@tab

确认程序按预期运行。

@item

@code{WARNING}

@tab

表明有已经或即将发生的意外（例如：磁盘空间不足）。程序仍按预期进行。

@item

@code{ERROR}

@tab

由于严重的问题，程序的某些功能已经不能正常执行

@item

@code{CRITICAL}

@tab

严重的错误，表明程序已不能继续执行

@end multitable


默认的级别是 @code{WARNING}，意味着只会追踪该级别及以上的事件，除非更改日志配置。

所追踪事件可以以不同形式处理。最简单的方式是输出到控制台。另一种常用的方式是写入磁盘文件。

@node 一个简单的例子<2>,记录日志到文件,什么时候使用日志,日志基础教程
@anchor{howto/logging a-simple-example}@anchor{4396}@anchor{howto/logging howto-minimal-example}@anchor{4397}
@subsubsection 一个简单的例子


一个非常简单的例子:

@example
import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything
@end example

如果你在命令行中输入这些代码并运行，你将会看到：

@example
WARNING:root:Watch out!
@end example

输出到命令行。@code{INFO} 消息并没有出现，因为默认级别是 @code{WARNING} 。打印的信息包含事件的级别以及在日志调用中的对于事件的描述，例如 “Watch out!”。暂时不用担心 “root” 部分：之后会作出解释。输出格式可按需要进行调整，格式化选项同样会在之后作出解释。

@node 记录日志到文件,从多个模块记录日志,一个简单的例子<2>,日志基础教程
@anchor{howto/logging logging-to-a-file}@anchor{4398}
@subsubsection 记录日志到文件


一种非常常见的情况是将日志事件记录到文件，让我们继续往下看。请确认启动新的Python 解释器，不要在上一个环境中继续操作:

@example
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
@end example


在 3.9 版更改: 增加了 @emph{encoding} 参数。在更早的 Python 版本中或没有指定时，编码会用 @ref{16f,,open()} 使用的默认值。尽管在上面的例子中没有展示，但也可以传入一个决定如何处理编码错误的 @emph{errors} 参数。可使用的值和默认值，请参照 @ref{16f,,open()} 的文档。


现在，如果我们打开日志文件，我们应当能看到日志信息：

@example
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö
@end example

该示例同样展示了如何设置日志追踪级别的阈值。该示例中，由于我们设置的阈值是 @code{DEBUG}，所有信息都将被打印。

如果你想从命令行设置日志级别，例如：

@example
--log=INFO
@end example

并且在一些 @emph{loglevel} 变量中你可以获得 @code{--log} 命令的参数，你可以使用:

@example
getattr(logging, loglevel.upper())
@end example

通过 @emph{level} 参数获得你将传递给 @ref{318,,basicConfig()} 的值。你需要对用户输入数据进行错误排查，可如下例:

@example
# assuming loglevel is bound to the string value obtained from the
# command line argument. Convert to upper case to allow the user to
# specify --log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)
@end example

对 @ref{318,,basicConfig()} 的调用应该在  @ref{220f,,debug()} ， @ref{223a,,info()} 等的前面。因为它被设计为一次性的配置，只有第一次调用会进行操作，随后的调用不会产生有效操作。

如果多次运行上述脚本，则连续运行的消息将追加到文件 @emph{example.log} 。 如果你希望每次运行重新开始，而不是记住先前运行的消息，则可以通过将上例中的调用更改为来指定 @emph{filemode} 参数:

@example
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
@end example

输出将与之前相同，但不再追加进日志文件，因此早期运行的消息将丢失。

@node 从多个模块记录日志,记录变量数据,记录日志到文件,日志基础教程
@anchor{howto/logging logging-from-multiple-modules}@anchor{4399}
@subsubsection 从多个模块记录日志


如果你的程序包含多个模块，这里有一个如何组织日志记录的示例:

@example
# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()
@end example

@example
# mylib.py
import logging

def do_something():
    logging.info('Doing something')
@end example

如果你运行 @emph{myapp.py} ，你应该在 @emph{myapp.log} 中看到：

@example
INFO:root:Started
INFO:root:Doing something
INFO:root:Finished
@end example

这是你期待看到的。 你可以使用 @emph{mylib.py} 中的模式将此概括为多个模块。 请注意，对于这种简单的使用模式，除了查看事件描述之外，你不能通过查看日志文件来了解应用程序中消息的 @emph{来源} 。 如果要跟踪消息的位置，则需要参考教程级别以外的文档 —— 请参阅 @ref{c4d,,进阶日志教程} 。

@node 记录变量数据,更改显示消息的格式,从多个模块记录日志,日志基础教程
@anchor{howto/logging logging-variable-data}@anchor{439a}
@subsubsection 记录变量数据


要记录变量数据，请使用格式字符串作为事件描述消息，并附加传入变量数据作为参数。 例如:

@example
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
@end example

将显示：

@example
WARNING:root:Look before you leap!
@end example

如你所见，将可变数据合并到事件描述消息中使用旧的 %-s形式的字符串格式化。 这是为了向后兼容：logging 包的出现时间早于较新的格式化选项例如 @ref{5dd,,str.format()} 和 @ref{4f9,,string.Template}。 这些较新格式化选项 @emph{是} 受支持的，但探索它们超出了本教程的范围：有关详细信息，请参阅 @ref{2232,,生效于整个应用程序的格式化样式}。

@node 更改显示消息的格式,在消息中显示日期/时间,记录变量数据,日志基础教程
@anchor{howto/logging changing-the-format-of-displayed-messages}@anchor{439b}
@subsubsection 更改显示消息的格式


要更改用于显示消息的格式，你需要指定要使用的格式:

@example
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
@end example

这将输出：

@example
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
@end example

请注意，前面示例中出现的 “root” 已消失。 对于可以出现在格式字符串中的全部内容，你可以参考以下文档 @ref{2230,,LogRecord 属性} ，但为了简单使用，你只需要 @emph{levelname} （严重性）， @emph{message} （事件描述，包括可变数据），也许在事件发生时显示。 这将在下一节中介绍。

@node 在消息中显示日期/时间,后续步骤,更改显示消息的格式,日志基础教程
@anchor{howto/logging displaying-the-date-time-in-messages}@anchor{439c}
@subsubsection 在消息中显示日期/时间


要显示事件的日期和时间，你可以在格式字符串中放置 '%(asctime)s'

@example
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
@end example

应该打印这样的东西：

@example
2010-12-12 11:41:42,612 is when this event was logged.
@end example

日期/时间显示的默认格式（如上所示）类似于 ISO8601 或 
@geindex RFC; RFC 3339
RFC 3339@footnote{https://tools.ietf.org/html/rfc3339.html} 。 如果你需要更多地控制日期/时间的格式，请为 @code{basicConfig} 提供 @emph{datefmt} 参数，如下例所示:

@example
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
@end example

这会显示如下内容：

@example
12/12/2010 11:46:36 AM is when this event was logged.
@end example

@emph{datefmt} 参数的格式与 @ref{c40,,time.strftime()} 支持的格式相同。

@node 后续步骤,,在消息中显示日期/时间,日志基础教程
@anchor{howto/logging next-steps}@anchor{439d}
@subsubsection 后续步骤


基本教程到此结束。 它应该足以让你启动并运行日志记录。 logging 包提供了更多功能，但为了充分利用它，你需要花更多的时间来阅读以下部分。 如果你准备好了，可以拿一些你最喜欢的饮料然后继续。

如果你的日志记录需求很简单，那么使用上面的示例将日志记录合并到你自己的脚本中，如果你遇到问题或者不理解某些内容，请在 comp.lang.python Usenet 组上发布一个问题（在 @indicateurl{https://groups.google.com/forum/#!forum/comp.lang.python} ） ，你将在短时间内得到帮助。

还不够？ 你可以继续阅读接下来的几个部分，这些部分提供了比上面基本部分更高级或深入的教程。 之后，你可以看一下 @ref{c4e,,日志操作手册} 。

@node 进阶日志教程,日志级别<2>,日志基础教程,日志 HOWTO
@anchor{howto/logging advanced-logging-tutorial}@anchor{439e}@anchor{howto/logging logging-advanced-tutorial}@anchor{c4d}
@subsection 进阶日志教程


日志库采用模块化方法，并提供几类组件：记录器、处理器、过滤器和格式器。


@itemize *

@item 
记录器暴露了应用程序代码直接使用的接口。

@item 
处理器将日志记录（由记录器创建）发送到适当的目标。

@item 
过滤器提供了更精细的附加功能，用于确定要输出的日志记录。

@item 
格式器指定最终输出中日志记录的样式。
@end itemize

日志事件信息在 @ref{9f5,,LogRecord} 实例中的记录器、处理器、过滤器和格式器之间传递。

通过调用 @ref{4b6,,Logger} 类（以下称为 @emph{loggers}  ， 记录器）的实例来执行日志记录。 每个实例都有一个名称，它们在概念上以点（句点）作为分隔符排列在命名空间的层次结构中。 例如，名为 'scan' 的记录器是记录器 'scan.text' ，'scan.html' 和 'scan.pdf' 的父级。 记录器名称可以是你想要的任何名称，并指示记录消息源自的应用程序区域。

在命名记录器时使用的一个好习惯是在每个使用日志记录的模块中使用模块级记录器，命名如下:

@example
logger = logging.getLogger(__name__)
@end example

这意味着记录器名称跟踪包或模块的层次结构，并且直观地从记录器名称显示记录事件的位置。

记录器层次结构的根称为根记录器。 这是函数 @ref{220f,,debug()} 、 @ref{223a,,info()} 、 @ref{224c,,warning()} 、 @ref{224d,,error()} 和 @ref{224e,,critical()} 使用的记录器，它们就是调用了根记录器的同名方法。 函数和方法具有相同的签名。 根记录器的名称在输出中打印为 'root' 。

当然，可以将消息记录到不同的地方。 软件包中的支持包含，用于将日志消息写入文件、 HTTP GET/POST 位置、通过 SMTP 发送电子邮件、通用套接字、队列或特定于操作系统的日志记录机制（如 syslog 或 Windows NT 事件日志）。 目标由 @emph{handler} 类提供。 如果你有任何内置处理器类未满足的特殊要求，则可以创建自己的日志目标类。

默认情况下，没有为任何日志消息设置目标。 你可以使用 @ref{318,,basicConfig()} 指定目标（例如控制台或文件），如教程示例中所示。 如果你调用函数 @ref{220f,,debug()} 、 @ref{223a,,info()} 、 @ref{224c,,warning()} 、 @ref{224d,,error()} 和 @ref{224e,,critical()} ，它们将检查是否有设置目标；如果没有设置，将在委托给根记录器进行实际的消息输出之前设置目标为控制台（ @code{sys.stderr} ）并设置显示消息的默认格式。

由 @ref{318,,basicConfig()} 设置的消息默认格式为：

@example
severity:logger name:message
@end example

你可以通过使用 @emph{format} 参数将格式字符串传递给 @ref{318,,basicConfig()} 来更改此设置。有关如何构造格式字符串的所有选项，请参阅 @ref{222e,,格式器对象} 。

@menu
* 记录流程:: 
* 记录器:: 
* 处理器:: 
* 格式器:: 
* 配置日志记录:: 
* 如果没有提供配置会发生什么:: 
* 配置库的日志记录:: 

@end menu

@node 记录流程,记录器,,进阶日志教程
@anchor{howto/logging logging-flow}@anchor{439f}
@subsubsection 记录流程


记录器和处理器中的日志事件信息流程如下图所示。

@image{python-figures/logging_flow,,,,png}

@node 记录器,处理器,记录流程,进阶日志教程
@anchor{howto/logging loggers}@anchor{43a0}
@subsubsection 记录器


@ref{4b6,,Logger} 对象有三重任务。首先，它们向应用程序代码公开了几种方法，以便应用程序可以在运行时记录消息。其次，记录器对象根据严重性（默认过滤工具）或过滤器对象确定要处理的日志消息。第三，记录器对象将相关的日志消息传递给所有感兴趣的日志处理器。

记录器对象上使用最广泛的方法分为两类：配置和消息发送。

这些是最常见的配置方法：


@itemize *

@item 
@ref{2208,,Logger.setLevel()} 指定记录器将处理的最低严重性日志消息，其中 debug 是最低内置严重性级别， critical 是最高内置严重性级别。 例如，如果严重性级别为 INFO ，则记录器将仅处理 INFO 、 WARNING 、 ERROR 和 CRITICAL 消息，并将忽略 DEBUG 消息。

@item 
@ref{2215,,Logger.addHandler()} 和 @ref{2216,,Logger.removeHandler()} 从记录器对象中添加和删除处理器对象。处理器在以下内容中有更详细的介绍 @ref{43a1,,处理器} 。

@item 
@ref{2212,,Logger.addFilter()} 和 @ref{2213,,Logger.removeFilter()} 可以添加或移除记录器对象中的过滤器。 @ref{2237,,过滤器对象} 包含更多的过滤器细节。
@end itemize

你不需要总是在你创建的每个记录器上都调用这些方法。 请参阅本节的最后两段。

配置记录器对象后，以下方法将创建日志消息：


@itemize *

@item 
@ref{80b,,Logger.debug()} 、 @ref{220e,,Logger.info()} 、 @ref{2210,,Logger.warning()} 、 @ref{2211,,Logger.error()} 和 @ref{80a,,Logger.critical()} 都创建日志记录，包含消息和与其各自方法名称对应的级别。该消息实际上是一个格式化字符串，它可能包含标题字符串替换语法 @code{%s} 、 @code{%d} 、 @code{%f} 等等。其余参数是与消息中的替换字段对应的对象列表。关于 @code{**kwargs} ，日志记录方法只关注 @code{exc_info} 的关键字，并用它来确定是否记录异常信息。

@item 
@ref{809,,Logger.exception()} 创建与 @ref{2211,,Logger.error()} 相似的日志信息。 不同之处是， @ref{809,,Logger.exception()} 同时还记录当前的堆栈追踪。仅从异常处理程序调用此方法。

@item 
@ref{808,,Logger.log()} 将日志级别作为显式参数。对于记录消息而言，这比使用上面列出的日志级别便利方法更加冗长，但这是使用自定义日志级别的方法。
@end itemize

@ref{235,,getLogger()} 返回对具有指定名称的记录器实例的引用（如果已提供），或者如果没有则返回 @code{root} 。名称是以句点分隔的层次结构。多次调用 @ref{235,,getLogger()} 具有相同的名称将返回对同一记录器对象的引用。在分层列表中较低的记录器是列表中较高的记录器的子项。例如，给定一个名为 @code{foo} 的记录器，名称为 @code{foo.bar} 、 @code{foo.bar.baz} 和 @code{foo.bam} 的记录器都是 @code{foo} 子项。

记录器具有 @emph{有效等级} 的概念。如果未在记录器上显式设置级别，则使用其父记录器的级别作为其有效级别。如果父记录器没有明确的级别设置，则检查 @emph{其} 父级。依此类推，搜索所有上级元素，直到找到明确设置的级别。根记录器始终具有显式级别集（默认情况下为 @code{WARNING} ）。在决定是否处理事件时，记录器的有效级别用于确定事件是否传递给记录器相关的处理器。

子记录器将消息传播到与其父级记录器关联的处理器。因此，不必为应用程序使用的所有记录器定义和配置处理器。一般为顶级记录器配置处理器，再根据需要创建子记录器就足够了。（但是，你可以通过将记录器的 @emph{propagate} 属性设置为 @code{False} 来关闭传播。）

@node 处理器,格式器,记录器,进阶日志教程
@anchor{howto/logging handler-basic}@anchor{43a1}@anchor{howto/logging handlers}@anchor{43a2}
@subsubsection 处理器


@ref{220d,,Handler} 对象负责将适当的日志消息（基于日志消息的严重性）分派给处理器的指定目标。 @ref{4b6,,Logger} 对象可以使用 @ref{2215,,addHandler()} 方法向自己添加零个或多个处理器对象。作为示例场景，应用程序可能希望将所有日志消息发送到日志文件，将错误或更高的所有日志消息发送到标准输出，以及将所有关键消息发送至一个邮件地址。 此方案需要三个单独的处理器，其中每个处理器负责将特定严重性的消息发送到特定位置。

标准库包含很多处理器类型（参见 @ref{43a3,,有用的处理器} ）；教程主要使用 @ref{c4f,,StreamHandler} 和 @ref{2273,,FileHandler} 。

处理器中很少有方法可供应用程序开发人员使用。使用内置处理器对象（即不创建自定义处理器）的应用程序开发人员能用到的仅有以下配置方法：


@itemize *

@item 
@code{setLevel()} 方法，就像在记录器对象中一样，指定将被分派到适当目标的最低严重性。为什么有两个 @code{setLevel()} 方法？记录器中设置的级别确定将传递给其处理器的消息的严重性。每个处理器中设置的级别确定该处理器将发送哪些消息。

@item 
@ref{2223,,setFormatter()} 选择一个该处理器使用的 Formatter 对象。

@item 
@ref{2224,,addFilter()} 和 @ref{2225,,removeFilter()} 分别在处理器上配置和取消配置过滤器对象。
@end itemize

应用程序代码不应直接实例化并使用 @ref{220d,,Handler} 的实例。 相反， @ref{220d,,Handler} 类是一个基类，它定义了所有处理器应该具有的接口，并建立了子类可以使用（或覆盖）的一些默认行为。

@node 格式器,配置日志记录,处理器,进阶日志教程
@anchor{howto/logging formatters}@anchor{43a4}
@subsubsection 格式器


格式化器对象配置日志消息的最终顺序、结构和内容。 与 @ref{220d,,logging.Handler} 类不同，应用程序代码可以实例化格式器类，但如果应用程序需要特殊行为，则可能会对格式化器进行子类化定制。构造函数有三个可选参数 —— 消息格式字符串、日期格式字符串和样式指示符。

@geindex __init__() (logging.logging.Formatter 方法)
@anchor{howto/logging logging logging Formatter __init__}@anchor{43a5}
@deffn {方法} logging.Formatter.__init__ (fmt=None, datefmt=None, style='%')
@end deffn

如果没有消息格式字符串，则默认使用原始消息。如果没有日期格式字符串，则默认日期格式为：

@example
%Y-%m-%d %H:%M:%S
@end example

最后加上毫秒数。 @code{style} 是 @cite{％}，'@{ ' 或 '$' 之一。 如果未指定，则将使用 '％'。

如果 @code{style} 是 '％'，则消息格式字符串使用 @code{%(<dictionary key>)s} 样式字符串替换；可能的键值在 @ref{2230,,LogRecord 属性} 中。 如果样式为 '@{'，则假定消息格式字符串与 @ref{5dd,,str.format()} （使用关键字参数）兼容，而如果样式为 '$' ，则消息格式字符串应符合 @ref{1464,,string.Template.substitute()} 。


在 3.2 版更改: 添加 @code{style} 形参。


以下消息格式字符串将以人类可读的格式记录时间、消息的严重性以及消息的内容，按此顺序:

@example
'%(asctime)s - %(levelname)s - %(message)s'
@end example

格式器通过用户可配置的函数将记录的创建时间转换为元组。 默认情况下，使用 @ref{10c9,,time.localtime()} ；要为特定格式器实例更改此项，请将实例的 @code{converter} 属性设置为与 @ref{10c9,,time.localtime()} 或 @ref{c1a,,time.gmtime()} 具有相同签名的函数。 要为所有格式器更改它，例如，如果你希望所有记录时间都以 GMT 显示，请在格式器类中设置 @code{converter} 属性（对于 GMT 显示，设置为 @code{time.gmtime} ）。

@node 配置日志记录,如果没有提供配置会发生什么,格式器,进阶日志教程
@anchor{howto/logging configuring-logging}@anchor{43a6}
@subsubsection 配置日志记录


开发者可以通过三种方式配置日志记录：


@enumerate 

@item 
使用调用上面列出的配置方法的 Python 代码显式创建记录器、处理器和格式器。

@item 
创建日志配置文件并使用 @ref{4b8,,fileConfig()} 函数读取它。

@item 
创建配置信息字典并将其传递给 @ref{c07,,dictConfig()} 函数。
@end enumerate

有关最后两个选项的参考文档，请参阅 @ref{d58,,配置函数} 。 以下示例使用 Python 代码配置一个非常简单的记录器、一个控制台处理器和一个简单的格式器:

@example
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

从命令行运行此模块将生成以下输出：

@example
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
@end example

以下 Python 模块创建的记录器、处理器和格式器几乎与上面列出的示例中的相同，唯一的区别是对象的名称:

@example
import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

这是 logging.conf 文件：

@example
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
@end example

其输出与不基于配置文件的示例几乎相同：

@example
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
@end example

你可以看到配置文件方法相较于 Python 代码方法有一些优势，主要是配置和代码的分离以及非开发者轻松修改日志记录属性的能力。

@cartouche
@quotation 警告 
@ref{4b8,,fileConfig()} 函数接受一个默认参数 @code{disable_existing_loggers} ，出于向后兼容的原因，默认为 @code{True} 。这可能与您的期望不同，因为除非在配置中明确命名它们（或其父级），否则它将导致在 @ref{4b8,,fileConfig()} 调用之前存在的任何非 root 记录器被禁用。有关更多信息，请参阅参考文档，如果需要，请将此参数指定为 @code{False} 。

传递给 @ref{c07,,dictConfig()} 的字典也可以用键 @code{disable_existing_loggers} 指定一个布尔值，如果没有在字典中明确指定，也默认被解释为 @code{True} 。这会导致上面描述的记录器禁用行为，这可能与你的期望不同——在这种情况下，请明确地为其提供 @code{False} 值。
@end quotation
@end cartouche

请注意，配置文件中引用的类名称需要相对于日志记录模块，或者可以使用常规导入机制解析的绝对值。因此，你可以使用 @ref{2285,,WatchedFileHandler} （相对于日志记录模块）或 @code{mypackage.mymodule.MyHandler} （对于在 @code{mypackage} 包中定义的类和模块 @code{mymodule} ，其中 @code{mypackage} 在 Python 导入路径上可用）。

在 Python 3.2 中，引入了一种新的配置日志记录的方法，使用字典来保存配置信息。 这提供了上述基于配置文件方法的功能的超集，并且是新应用程序和部署的推荐配置方法。 因为 Python 字典用于保存配置信息，并且由于你可以使用不同的方式填充该字典，因此你有更多的配置选项。 例如，你可以使用 JSON 格式的配置文件，或者如果你有权访问 YAML 处理功能，则可以使用 YAML 格式的文件来填充配置字典。当然，你可以在 Python 代码中构造字典，通过套接字以 pickle 形式接收它，或者使用对你的应用程序合理的任何方法。

以下是与上述相同配置的示例，采用 YAML 格式，用于新的基于字典的方法：

@example
version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]
@end example

有关使用字典进行日志记录的更多信息，请参阅 @ref{d58,,配置函数}。

@node 如果没有提供配置会发生什么,配置库的日志记录,配置日志记录,进阶日志教程
@anchor{howto/logging what-happens-if-no-configuration-is-provided}@anchor{43a7}
@subsubsection 如果没有提供配置会发生什么


如果未提供日志记录配置，则可能出现需要输出日志记录事件但无法找到输出事件的处理器的情况。 在这些情况下，logging 包的行为取决于 Python 版本。

对于 3.2 之前的 Python 版本，行为如下：


@itemize *

@item 
如果 @emph{logging.raiseExceptions} 为 @code{False} （生产模式），则会以静默方式丢弃该事件。

@item 
如果 @emph{logging.raiseExceptions} 为 @code{True} （开发模式），则会打印一条消息 'No handlers could be found for logger X.Y.Z'。
@end itemize

在 Python 3.2 及更高版本中，行为如下：


@itemize *

@item 
事件使用 “最后的处理器” 输出，存储在 @code{logging.lastResort} 中。 这个内部处理器与任何记录器都没有关联，它的作用类似于 @ref{c4f,,StreamHandler} ，它将事件描述消息写入 @code{sys.stderr} 的当前值（因此服从任何可能的重定向影响）。 没有对消息进行格式化——只打印裸事件描述消息。处理器的级别设置为 @code{WARNING}，因此将输出此级别和更高级别的所有事件。
@end itemize

要获得 3.2 之前的行为，可以设置 @code{logging.lastResort} 为 @code{None}。

@node 配置库的日志记录,,如果没有提供配置会发生什么,进阶日志教程
@anchor{howto/logging configuring-logging-for-a-library}@anchor{43a8}@anchor{howto/logging library-config}@anchor{2282}
@subsubsection 配置库的日志记录


在开发使用日志记录的库时，你应该注意记录库如何使用日志记录——例如，使用的记录器的名称。还需要考虑其日志记录配置。如果应用程序不使用日志记录，并且库代码进行日志记录调用，那么（如上一节所述）严重性为 @code{WARNING} 及更高级别的事件将打印到 @code{sys.stderr} 。这被认为是最好的默认行为。

如果由于某种原因，你 @emph{不} 希望在没有任何日志记录配置的情况下打印这些消息，则可以将无操作处理器附加到库的顶级记录器。这样可以避免打印消息，因为将始终为库的事件找到处理器：它不会产生任何输出。如果库用户配置应用程序使用的日志记录，可能是配置将添加一些处理器，如果级别已适当配置，则在库代码中进行的日志记录调用将正常地将输出发送给这些处理器。

日志包中包含一个不做任何事情的处理器： @ref{cee,,NullHandler} （自 Python 3.1 起）。可以将此处理器的实例添加到库使用的日志记录命名空间的顶级记录器中（ @emph{如果} 你希望在没有日志记录配置的情况下阻止库的记录事件输出到 @code{sys.stderr} ）。如果库 @emph{foo} 的所有日志记录都是使用名称匹配 'foo.x' ， 'foo.x.y' 等的记录器完成的，那么代码:

@example
import logging
logging.getLogger('foo').addHandler(logging.NullHandler())
@end example

应该有预计的效果。如果一个组织生成了许多库，则指定的记录器名称可以是 “orgname.foo” 而不仅仅是 “foo” 。

@cartouche
@quotation 注解 
强烈建议你 @emph{不要将} @ref{cee,,NullHandler} @emph{以外的任何处理器添加到库的记录器中} 。这是因为处理器的配置是使用你的库的应用程序开发人员的权利。应用程序开发人员了解他们的目标受众以及哪些处理器最适合他们的应用程序：如果你在“底层”添加处理器，则可能会干扰他们执行单元测试和提供符合其要求的日志的能力。
@end quotation
@end cartouche

@node 日志级别<2>,有用的处理器,进阶日志教程,日志 HOWTO
@anchor{howto/logging logging-levels}@anchor{43a9}
@subsection 日志级别


日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具有相对于预定义级别的特定值，那么你可能对一下内容感兴趣。如果你定义具有相同数值的级别，它将覆盖预定义的值; 预定义的名称失效。


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} 
@headitem

级别

@tab

数值

@item

@code{CRITICAL}

@tab

50

@item

@code{ERROR}

@tab

40

@item

@code{WARNING}

@tab

30

@item

@code{INFO}

@tab

20

@item

@code{DEBUG}

@tab

10

@item

@code{NOTSET}

@tab

0

@end multitable


级别也可以与记录器相关联，由开发人员设置或通过加载已保存的日志记录配置。在记录器上调用日志记录方法时，记录器会将其自己的级别与与方法调用关联的级别进行比较。如果记录器的级别高于方法调用的级别，则实际上不会生成任何记录消息。这是控制日志记录输出详细程度的基本机制。

记录消息被编码为 @ref{9f5,,LogRecord} 类的实例。当记录器决定实际记录事件时，将用记录消息创建 @ref{9f5,,LogRecord} 实例。

记录消息受 @emph{handlers} 建立的调度机制控制，它们是 @ref{220d,,Handler} 类的子类实例。处理器负责确保记录的消息（以 @ref{9f5,,LogRecord} 的形式）最终位于对该消息的目标受众（例如最终用户、 支持服务台员工、系统管理员、开发人员）有用的特定位置（或一组位置）上。处理器传递适用于特定目标的 @ref{9f5,,LogRecord} 实例。 每个记录器可以有零个、一个或多个与之关联的处理器（通过 @ref{4b6,,Logger} 的 @ref{2215,,addHandler()} 方法）。除了与记录器直接关联的所有处理器之外，还调用与记录器的 @emph{所有祖先关联的处理器来分派消息（除非记录器的 *propagate} 标志设置为 false 值，这将停止传递到上级处理器）。

就像记录器一样，处理器可以具有与它们相关联的级别。处理器的级别作为过滤器，其方式与记录器级别相同。如果处理器决定调度一个事件，则使用 @code{emit()} 方法将消息发送到其目标。大多数用户定义的 @ref{220d,,Handler} 子类都需要重载 @code{emit()} 。

@menu
* 自定义级别:: 

@end menu

@node 自定义级别,,,日志级别<2>
@anchor{howto/logging custom-levels}@anchor{2252}@anchor{howto/logging id1}@anchor{43aa}
@subsubsection 自定义级别


定义你自己的级别是可能的，但不一定是必要的，因为现有级别是根据实践经验选择的。但是，如果你确信需要自定义级别，那么在执行此操作时应特别小心，如果你正在开发库，则 @emph{定义自定义级别可能是一个非常糟糕的主意} 。 这是因为如果多个库作者都定义了他们自己的自定义级别，那么使用开发人员很难控制和解释这些多个库的日志记录输出，因为给定的数值对于不同的库可能意味着不同的东西。

@node 有用的处理器,记录日志时引发的异常,日志级别<2>,日志 HOWTO
@anchor{howto/logging id2}@anchor{43ab}@anchor{howto/logging useful-handlers}@anchor{43a3}
@subsection 有用的处理器


作为 @ref{220d,,Handler} 基类的补充，提供了很多有用的子类：


@enumerate 

@item 
@ref{c4f,,StreamHandler} 实例发送消息到流（类似文件对象）。

@item 
@ref{2273,,FileHandler} 实例将消息发送到硬盘文件。

@item 
@ref{2289,,BaseRotatingHandler} 是轮换日志文件的处理器的基类。它并不应该直接实例化。而应该使用 @ref{2264,,RotatingFileHandler} 或 @ref{962,,TimedRotatingFileHandler} 代替它。

@item 
@ref{2264,,RotatingFileHandler} 实例将消息发送到硬盘文件，支持最大日志文件大小和日志文件轮换。

@item 
@ref{962,,TimedRotatingFileHandler} 实例将消息发送到硬盘文件，以特定的时间间隔轮换日志文件。

@item 
@ref{963,,SocketHandler} 实例将消息发送到 TCP/IP 套接字。从 3.4 开始，也支持 Unix 域套接字。

@item 
@ref{964,,DatagramHandler} 实例将消息发送到 UDP 套接字。从 3.4 开始，也支持 Unix 域套接字。

@item 
@ref{22b6,,SMTPHandler} 实例将消息发送到指定的电子邮件地址。

@item 
@ref{b04,,SysLogHandler} 实例将消息发送到 Unix syslog 守护程序，可能在远程计算机上。

@item 
@ref{22ae,,NTEventLogHandler} 实例将消息发送到 Windows NT/2000/XP 事件日志。

@item 
@ref{226d,,MemoryHandler} 实例将消息发送到内存中的缓冲区，只要满足特定条件，缓冲区就会刷新。

@item 
@ref{80c,,HTTPHandler} 实例使用 @code{GET} 或 @code{POST} 方法将消息发送到 HTTP 服务器。

@item 
@ref{2285,,WatchedFileHandler} 实例会监视他们要写入日志的文件。如果文件发生更改，则会关闭该文件并使用文件名重新打开。此处理器仅在类 Unix 系统上有用； Windows 不支持依赖的基础机制。

@item 
@ref{22c9,,QueueHandler} 实例将消息发送到队列，例如在 @ref{da,,queue} 或 @ref{b7,,multiprocessing} 模块中实现的队列。

@item 
@ref{cee,,NullHandler} 实例对错误消息不执行任何操作。它们由想要使用日志记录的库开发人员使用，但是想要避免如果库用户没有配置日志记录，则显示 'No handlers could be found for logger XXX' 消息的情况。更多有关信息，请参阅 @ref{2282,,配置库的日志记录} 。
@end enumerate


3.1 新版功能: @ref{cee,,NullHandler} 类。



3.2 新版功能: @ref{22c9,,QueueHandler} 类。


The @ref{cee,,NullHandler} 、 @ref{c4f,,StreamHandler} 和 @ref{2273,,FileHandler} 类在核心日志包中定义。其他处理器定义在 @ref{ac,,logging.handlers} 中。（还有另一个子模块 @ref{ab,,logging.config} ，用于配置功能）

记录的消息通过 @ref{220c,,Formatter} 类的实例进行格式化后呈现。 它们使用能与 ％ 运算符一起使用的格式字符串和字典进行初始化。

要批量格式化多个消息，可以使用 @code{BufferingFormatter} 的实例。除了格式字符串（应用于批处理中的每个消息）之外，还提供了标题和尾部格式字符串。

当基于记录器级别和处理器级别的过滤不够时，可以将 @ref{c51,,Filter} 的实例添加到 @ref{4b6,,Logger} 和 @ref{220d,,Handler} 实例（通过它们的 @ref{2224,,addFilter()} 方法）。在决定进一步处理消息之前，记录器和处理器都会查询其所有过滤器以获得许可。如果任何过滤器返回 false 值，则不会进一步处理该消息。

基本 @ref{c51,,Filter} 的功能允许按特定的记录器名称进行过滤。如果使用此功能，则允许通过过滤器发送到指定记录器及其子项的消息，并丢弃其他所有消息。

@node 记录日志时引发的异常,使用任意对象作为消息,有用的处理器,日志 HOWTO
@anchor{howto/logging exceptions-raised-during-logging}@anchor{43ac}@anchor{howto/logging logging-exceptions}@anchor{43ad}
@subsection 记录日志时引发的异常


logging 包设计为忽略记录日志生产时发生的异常。这样，处理日志记录事件时发生的错误（例如日志记录错误配置、网络或其他类似错误）不会导致使用日志记录的应用程序过早终止。

@ref{6fd,,SystemExit} 和 @ref{2d3,,KeyboardInterrupt} 异常永远不会被忽略。 在 @ref{220d,,Handler} 子类的 @code{emit()} 方法中发生的其他异常被传递给它的 @code{handleError()} 方法。

@ref{220d,,Handler} 中默认实现的 @code{handleError()} 检查是否设置了模块级变量 @code{raiseExceptions} 。如果有设置，则会将回溯打印到 @ref{1eb,,sys.stderr} 。如果未设置，则忽略异常。

@cartouche
@quotation 注解 
@code{raiseExceptions} 默认值是 @code{True}。 这是因为在开发期间，你通常希望收到任何发生异常的通知。建议你将 @code{raiseExceptions} 设置为 @code{False} 以供生产环境使用。
@end quotation
@end cartouche

@node 使用任意对象作为消息,优化,记录日志时引发的异常,日志 HOWTO
@anchor{howto/logging arbitrary-object-messages}@anchor{2243}@anchor{howto/logging using-arbitrary-objects-as-messages}@anchor{43ae}
@subsection 使用任意对象作为消息


在前面的部分和示例中，都假设记录事件时传递的消息是字符串。 但是，这不是唯一的可能性。你可以将任意对象作为消息传递，并且当日志记录系统需要将其转换为字符串表示时，将调用其 @code{__ str__()} 方法。实际上，如果你愿意，你可以完全避免计算字符串表示。例如， @ref{963,,SocketHandler} 用 pickle 处理事件后，通过网络发送。

@node 优化,,使用任意对象作为消息,日志 HOWTO
@anchor{howto/logging optimization}@anchor{43af}
@subsection 优化


消息参数的格式化将被推迟，直到无法避免。但是，计算传递给日志记录方法的参数也可能很消耗资源，如果记录器只是丢弃你的事件，你可能希望避免这样做。要决定做什么，可以调用 @ref{220b,,isEnabledFor()} 方法，该方法接受一个 level 参数，如果记录器为该级别的调用创建了该事件，则返回 true 。 你可以写这样的代码:

@example
if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())
@end example

因此，如果记录器的阈值设置在“DEBUG”以上，则永远不会调用 @code{expensive_func1()} 和 @code{expensive_func2()} 。

@cartouche
@quotation 注解 
在某些情况下， @ref{220b,,isEnabledFor()} 本身可能比你想要的更消耗资源（例如，对于深度嵌套的记录器，其中仅在记录器层次结构中设置了显式级别）。在这种情况下（或者如果你想避免在紧密循环中调用方法），你可以在本地或实例变量中将调用的结果缓存到 @ref{220b,,isEnabledFor()} ，并使用它而不是每次调用方法。在日志记录配置在应用程序运行时动态更改（这不常见）时，只需要重新计算这样的缓存值即可。
@end quotation
@end cartouche

对于需要对收集的日志信息进行更精确控制的特定应用程序，还可以进行其他优化。以下列出了在日志记录过程中您可以避免的非必须处理操作：


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

你不想收集的内容

@tab

如何避免收集它

@item

有关调用来源的信息

@tab

将 @code{logging._srcfile} 设置为 @code{None} 。这避免了调用 @ref{f2c,,sys._getframe()} ，如果 PyPy 支持 Python 3.x ，这可能有助于加速 PyPy （无法加速使用 @ref{f2c,,sys._getframe()} 的代码）等环境中的代码。

@item

线程信息

@tab

将 @code{logging.logThreads} 置为 @code{0} 。

@item

进程信息

@tab

将 @code{logging.logProcesses} 置为 @code{0} 。

@end multitable


另请注意，核心日志记录模块仅包含基本处理器。如果你不导入 @ref{ac,,logging.handlers} 和 @ref{ab,,logging.config} ，它们将不会占用任何内存。


@subsubheading 参见



@table @asis

@item 模块 @ref{aa,,logging}

日志记录模块的 API 参考。

@item 模块 @ref{ab,,logging.config}

日志记录模块的配置 API 。

@item 模块 @ref{ac,,logging.handlers}

日志记录模块附带的有用处理器。
@end table

@ref{c4e,,日志操作手册}


@node 日志操作手册,正则表达式HOWTO,日志 HOWTO,Python 常用指引
@anchor{howto/logging-cookbook doc}@anchor{43b0}@anchor{howto/logging-cookbook id1}@anchor{43b1}@anchor{howto/logging-cookbook logging-cookbook}@anchor{c4e}
@section 日志操作手册


@*作者: 
Vinay Sajip <vinay_sajip at red-dove dot com>


本页包含了许多日志记录相关的概念，这些概念在过去一直被认为很有用。

@menu
* 在多个模块中使用日志:: 
* 在多个线程中记录日志:: 
* 多个 handler 和多种 formatter:: 
* 在多个地方记录日志:: 
* 日志配置服务器示例:: 
* 处理日志 handler 的阻塞:: 
* 通过网络收发日志事件:: 
* 在自己的输出日志中添加上下文信息:: 
* 在单个文件中记录多个进程的日志:: 
* 利用日志文件轮换机制:: 
* 日志的其他格式:: 
* 自定义 LogRecord:: 
* 子类化 QueueHandler - ZeroMQ 示例:: 
* 子类化 QueueListener —— ZeroMQ 示例:: 
* 基于字典进行日志配置的示例:: 
* 利用 rotator 和 namer 自定义日志轮换操作:: 
* 更详细的多进程日志示例:: 
* 在发送给 SysLogHandler 的信息中插入一个 BOM。:: 
* 结构化日志的实现代码:: 
* 利用 dictConfig() 自定义 handler: 利用 dictConfig 自定义 handler. 
* 生效于整个应用程序的格式化样式:: 
* 用 dictConfig() 配置过滤器: 用 dictConfig 配置过滤器. 
* 异常信息的自定义格式化:: 
* 语音播报日志信息:: 
* 缓冲日志信息并按条件输出:: 
* 通过配置将时间格式化为 UTC（GMT）格式:: 
* 用上下文管理器选择性记录日志:: 
* 命令行日志应用起步:: 
* 用作日志的 Qt GUI 程序:: 
* 理应避免的用法:: 

@end menu

@node 在多个模块中使用日志,在多个线程中记录日志,,日志操作手册
@anchor{howto/logging-cookbook using-logging-in-multiple-modules}@anchor{43b2}
@subsection 在多个模块中使用日志


无论对 @code{logging.getLogger('someLogger')} 进行多少次调用，都会返回同一个 logger 对象的引用。不仅在同一个模块内如此，只要是在同一个 Python 解释器进程中，跨模块调用也是一样。同样是引用同一个对象，应用程序也可以在一个模块中定义和配置一个父 logger，而在另一个单独的模块中创建（但不配置）子 logger，对于子 logger 的所有调用都会传给父 logger。以下是主模块：

@example
import logging
import auxiliary_module

# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
logger.info('created an instance of auxiliary_module.Auxiliary')
logger.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
logger.info('finished auxiliary_module.Auxiliary.do_something')
logger.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
logger.info('done with auxiliary_module.some_function()')
@end example

以下是辅助模块：

@example
import logging

# create logger
module_logger = logging.getLogger('spam_application.auxiliary')

class Auxiliary:
    def __init__(self):
        self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
        self.logger.info('creating an instance of Auxiliary')

    def do_something(self):
        self.logger.info('doing something')
        a = 1 + 1
        self.logger.info('done doing something')

def some_function():
    module_logger.info('received a call to "some_function"')
@end example

输出结果会像这样:

@example
2005-03-23 23:47:11,663 - spam_application - INFO -
   creating an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
   creating an instance of Auxiliary
2005-03-23 23:47:11,665 - spam_application - INFO -
   created an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,668 - spam_application - INFO -
   calling auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
   doing something
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
   done doing something
2005-03-23 23:47:11,670 - spam_application - INFO -
   finished auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,671 - spam_application - INFO -
   calling auxiliary_module.some_function()
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
   received a call to 'some_function'
2005-03-23 23:47:11,673 - spam_application - INFO -
   done with auxiliary_module.some_function()
@end example

@node 在多个线程中记录日志,多个 handler 和多种 formatter,在多个模块中使用日志,日志操作手册
@anchor{howto/logging-cookbook logging-from-multiple-threads}@anchor{43b3}
@subsection 在多个线程中记录日志


多线程记录日志并不需要特殊处理，以下示例演示了在主线程（起始线程）和其他线程中记录日志的过程：

@example
import logging
import threading
import time

def worker(arg):
    while not arg['stop']:
        logging.debug('Hi from myfunc')
        time.sleep(0.5)

def main():
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
    info = @{'stop': False@}
    thread = threading.Thread(target=worker, args=(info,))
    thread.start()
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(0.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    thread.join()

if __name__ == '__main__':
    main()
@end example

运行结果会像如下这样:

@example
   0 Thread-1 Hi from myfunc
   3 MainThread Hello from main
 505 Thread-1 Hi from myfunc
 755 MainThread Hello from main
1007 Thread-1 Hi from myfunc
1507 MainThread Hello from main
1508 Thread-1 Hi from myfunc
2010 Thread-1 Hi from myfunc
2258 MainThread Hello from main
2512 Thread-1 Hi from myfunc
3009 MainThread Hello from main
3013 Thread-1 Hi from myfunc
3515 Thread-1 Hi from myfunc
3761 MainThread Hello from main
4017 Thread-1 Hi from myfunc
4513 MainThread Hello from main
4518 Thread-1 Hi from myfunc
@end example

以上如期显示了不同线程的日志是交替输出的。当然更多的线程也会如此。

@node 多个 handler 和多种 formatter,在多个地方记录日志,在多个线程中记录日志,日志操作手册
@anchor{howto/logging-cookbook multiple-handlers-and-formatters}@anchor{43b4}
@subsection 多个 handler 和多种 formatter


日志是个普通的 Python 对象。 @ref{2215,,addHandler()} 方法可加入不限数量的日志 handler。有时候，应用程序需把严重错误信息记入文本文件，而将一般错误或其他级别的信息输出到控制台。若要进行这样的设定，只需多配置几个日志 handler 即可，应用程序的日志调用代码可以保持不变。下面对之前的分模块日志示例略做修改：

@example
import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
@end example

需要注意的是，“应用程序”内的代码并不关心是否存在多个日志 handler。示例中所做的改变，只是新加入并配置了一个名为 @emph{fh} 的 handler。

在编写和测试应用程序时，若能创建日志 handler 对不同严重级别的日志信息进行过滤，这将十分有用。调试时无需用多条 @code{print} 语句，而是采用 @code{logger.debug} ：print 语句以后还得注释或删掉，而 logger.debug  语句可以原样留在源码中保持静默。当需要再次调试时，只要改变日志对象或  handler 的严重级别即可。

@node 在多个地方记录日志,日志配置服务器示例,多个 handler 和多种 formatter,日志操作手册
@anchor{howto/logging-cookbook logging-to-multiple-destinations}@anchor{43b5}@anchor{howto/logging-cookbook multiple-destinations}@anchor{43b6}
@subsection 在多个地方记录日志


假定要根据不同的情况将日志以不同的格式写入控制台和文件。比如把 DEBUG 以上级别的日志信息写于文件，并且把 INFO 以上的日志信息输出到控制台。再假设日志文件需要包含时间戳，控制台信息则不需要。以下演示了做法：

@example
import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('@w{'}).addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
@end example

当运行后，你会看到控制台如下所示

@example
root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO     How quickly daft jumping zebras vex.
myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR    The five boxing wizards jump quickly.
@end example

而日志文件将如下所示：

@example
10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.
@end example

如您所见，DEBUG 级别的日志信息只出现在了文件中，而其他信息则两个地方都会输出。

上述示例只用到了控制台和文件 handler，当然还可以自由组合任意数量的日志 handler。

@node 日志配置服务器示例,处理日志 handler 的阻塞,在多个地方记录日志,日志操作手册
@anchor{howto/logging-cookbook configuration-server-example}@anchor{43b7}
@subsection 日志配置服务器示例


以下是一个用到了日志配置服务器的模块示例：

@example
import logging
import logging.config
import time
import os

# read initial config file
logging.config.fileConfig('logging.conf')

# create and start listener on port 9999
t = logging.config.listen(9999)
t.start()

logger = logging.getLogger('simpleExample')

try:
    # loop through logging calls to see the difference
    # new configurations make, until Ctrl+C is pressed
    while True:
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warn message')
        logger.error('error message')
        logger.critical('critical message')
        time.sleep(5)
except KeyboardInterrupt:
    # cleanup
    logging.config.stopListening()
    t.join()
@end example

以下脚本将接受文件名作为参数，然后将此文件发送到服务器，前面加上文件的二进制编码长度，做为新的日志配置：

@example
#!/usr/bin/env python
import socket, sys, struct

with open(sys.argv[1], 'rb') as f:
    data_to_send = f.read()

HOST = 'localhost'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('connecting...')
s.connect((HOST, PORT))
print('sending config...')
s.send(struct.pack('>L', len(data_to_send)))
s.send(data_to_send)
s.close()
print('complete')
@end example

@node 处理日志 handler 的阻塞,通过网络收发日志事件,日志配置服务器示例,日志操作手册
@anchor{howto/logging-cookbook dealing-with-handlers-that-block}@anchor{43b8}
@subsection 处理日志 handler 的阻塞


有时需让日志 handler 不要阻塞当前的线程。这在 Web 应用程序中比较常见，当然在其他场景中也会发生。

有一种原因往往会让程序表现迟钝，这就是 @ref{22b6,,SMTPHandler}：由于很多因素是开发人员无法控制的（例如邮件或网络基础设施的性能不佳），发送电子邮件可能需要很长时间。不过几乎所有网络  handler 都可能会发生阻塞：即使是 @ref{963,,SocketHandler} 操作也可能在后台执行 DNS 查询，而这种查询实在太慢了（并且 DNS 查询还可能在很底层的套接字库代码中，位于 Python 层之下，超出了可控范围）。

有一种解决方案是分成两部分实现。第一部分，针对那些对性能有要求的关键线程，只为日志对象连接一个 @ref{22c9,,QueueHandler}。日志对象只需简单地写入队列即可，可为队列设置足够大的容量，或者可以在初始化时不设置容量上限。尽管为以防万一，可能需要在代码中捕获 @ref{2526,,queue.Full} 异常,不过队列写入操作通常会很快得以处理。如果要开发库代码，包含性能要求较高的线程，为了让使用该库的开发人员受益，请务必在开发文档中进行标明（包括建议仅连接 @code{QueueHandlers} ）。

解决方案的另一部分就是 @ref{80d,,QueueListener}，它被设计为 @ref{22c9,,QueueHandler} 的对应部分。@ref{80d,,QueueListener} 非常简单：传入一个队列和一些 handler，并启动一个内部线程，用于侦听 @code{QueueHandlers`@w{`}（或其他 `@w{`}LogRecords} 源）发送的 LogRecord 队列。@code{LogRecords} 会从队列中移除并传给 handler 处理。

@ref{80d,,QueueListener} 作为单独的类，好处就是可以用同一个实例为多个 @code{QueueHandlers} 服务。这比把现有 handler 类线程化更加资源友好，后者会每个 handler 会占用一个线程，却没有特别的好处。

以下是这两个类的运用示例（省略了 import 语句）：

@example
que = queue.Queue(-1)  # no limit on size
queue_handler = QueueHandler(que)
handler = logging.StreamHandler()
listener = QueueListener(que, handler)
root = logging.getLogger()
root.addHandler(queue_handler)
formatter = logging.Formatter('%(threadName)s: %(message)s')
handler.setFormatter(formatter)
listener.start()
# The log output will display the thread which generated
# the event (the main thread) rather than the internal
# thread which monitors the internal queue. This is what
# you want to happen.
root.warning('Look out!')
listener.stop()
@end example

在运行后会产生:

@example
MainThread: Look out!
@end example


在 3.5 版更改: 在 Python 3.5 之前，@ref{80d,,QueueListener} 总会把由队列接收到的每条信息都传递给已初始化的每个处理程序。（因为这里假定级别过滤操作已在写入队列时完成了。）从 3.5 版开始，可以修改这种处理方式，只要将关键字参数 @code{respect_handler_level=True} 传给侦听器的构造函数即可。这样侦听器将会把每条信息的级别与 handler 的级别进行比较，只在适配时才会将信息传给 handler 。


@node 通过网络收发日志事件,在自己的输出日志中添加上下文信息,处理日志 handler 的阻塞,日志操作手册
@anchor{howto/logging-cookbook network-logging}@anchor{43b9}@anchor{howto/logging-cookbook sending-and-receiving-logging-events-across-a-network}@anchor{43ba}
@subsection 通过网络收发日志事件


假定现在要通过网络发送日志事件，并在接收端进行处理。有一种简单的方案，就是在发送端的根日志对象连接一个 @ref{963,,SocketHandler} 实例：

@example
import logging, logging.handlers

rootLogger = logging.getLogger('@w{'})
rootLogger.setLevel(logging.DEBUG)
socketHandler = logging.handlers.SocketHandler('localhost',
                    logging.handlers.DEFAULT_TCP_LOGGING_PORT)
# don't bother with a formatter, since a socket handler sends the event as
# an unformatted pickle
rootLogger.addHandler(socketHandler)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
@end example

在接收端，可以用 @ref{f0,,socketserver} 模块设置一个接收器。简要示例如下：

@example
import pickle
import logging
import logging.handlers
import socketserver
import struct


class LogRecordStreamHandler(socketserver.StreamRequestHandler):
    """Handler for a streaming logging request.

    This basically logs the record using whatever logging policy is
    configured locally.
    """

    def handle(self):
        """
        Handle multiple requests - each expected to be a 4-byte length,
        followed by the LogRecord in pickle format. Logs the record
        according to whatever policy is configured locally.
        """
        while True:
            chunk = self.connection.recv(4)
            if len(chunk) < 4:
                break
            slen = struct.unpack('>L', chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            obj = self.unPickle(chunk)
            record = logging.makeLogRecord(obj)
            self.handleLogRecord(record)

    def unPickle(self, data):
        return pickle.loads(data)

    def handleLogRecord(self, record):
        # if a name is specified, we use the named logger rather than the one
        # implied by the record.
        if self.server.logname is not None:
            name = self.server.logname
        else:
            name = record.name
        logger = logging.getLogger(name)
        # N.B. EVERY record gets logged. This is because Logger.handle
        # is normally called AFTER logger-level filtering. If you want
        # to do filtering, do it at the client end to save wasting
        # cycles and network bandwidth!
        logger.handle(record)

class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
    """
    Simple TCP socket-based logging receiver suitable for testing.
    """

    allow_reuse_address = True

    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort

def main():
    logging.basicConfig(
        format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
    tcpserver = LogRecordSocketReceiver()
    print('About to start TCP server...')
    tcpserver.serve_until_stopped()

if __name__ == '__main__':
    main()
@end example

先运行服务端，再运行客户端。客户端控制台不会显示什么信息；在服务端应该会看到如下内容：

@example
About to start TCP server...
   59 root            INFO     Jackdaws love my big sphinx of quartz.
   59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
   69 myapp.area1     INFO     How quickly daft jumping zebras vex.
   69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
   69 myapp.area2     ERROR    The five boxing wizards jump quickly.
@end example

请注意，某些时候 pickle 会存在一些安全问题。若有问题可换用自己的序列化方案，只要覆盖 @code{makePickle()} 方法即可，并调整上述脚本以采用自己的序列化方案。

@menu
* 在生产中运行日志套接字侦听器:: 

@end menu

@node 在生产中运行日志套接字侦听器,,,通过网络收发日志事件
@anchor{howto/logging-cookbook running-a-logging-socket-listener-in-production}@anchor{43bb}
@subsubsection 在生产中运行日志套接字侦听器


要在生产环境中运行日志记录监听器，你可能需要使用一个进程管理工具例如 Supervisor@footnote{http://supervisord.org/}。 这里@footnote{https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b} 是一个提供使用 Supervisor 来运行上述功能的基本框架文件的 Gist：你将需要修改 Gist 中的 @cite{/path/to/} 以反映你想要使用的实际路径。

@node 在自己的输出日志中添加上下文信息,在单个文件中记录多个进程的日志,通过网络收发日志事件,日志操作手册
@anchor{howto/logging-cookbook adding-contextual-information-to-your-logging-output}@anchor{43bc}@anchor{howto/logging-cookbook context-info}@anchor{2246}
@subsection 在自己的输出日志中添加上下文信息


有时，除了调用日志对象时传入的参数之外，还希望日志输出中能包含上下文信息。 比如在网络应用程序中，可能需要在日志中记录某客户端专属的信息（如远程客户端的用户名或 IP 地址）。 这虽然可以用 @emph{extra} 参数实现，但传递起来并不总是很方便。 虽然为每个网络连接都创建 @code{Logger}  实例貌似不错，但并不是个好主意，因为这些实例不会被垃圾回收。 虽然在实践中不是问题，但当 @code{Logger} 实例的数量取决于应用程序要采用的日志粒度时，如果 @code{Logger} 实例的数量实际上是无限的，则有可能难以管理。

@menu
* 利用 LoggerAdapter 传递上下文信息:: 
* 利用 Filter 传递上下文信息:: 

@end menu

@node 利用 LoggerAdapter 传递上下文信息,利用 Filter 传递上下文信息,,在自己的输出日志中添加上下文信息
@anchor{howto/logging-cookbook using-loggeradapters-to-impart-contextual-information}@anchor{43bd}
@subsubsection 利用 LoggerAdapter 传递上下文信息


要传递上下文信息和日志事件信息，有一种简单方案是利用 @code{LoggerAdapter} 类。这个类设计得类似 @code{Logger}，所以可以直接调用 @code{debug()}、@code{info()}、 @code{warning()}、 @code{error()}、@code{exception()}、 @code{critical()} 和 @code{log()}。这些方法的签名与 @code{Logger} 对应的方法相同，所以这两类实例可以交换使用。

若要创建 @code{LoggerAdapter} 的实例，需传入一个 @code{Logger} 的实例和一个包含了上下文信息的字典类对象。当在 @code{LoggerAdapter} 实例上调用某个日志方法时，会将调用委托给传入构造函数的底层 @code{Logger} 实例，并在调用中传入上下文信息。以下是 @code{LoggerAdapter} 的一段代码：

@example
def debug(self, msg, /, *args, **kwargs):
    """
    Delegate a debug call to the underlying logger, after adding
    contextual information from this adapter instance.
    """
    msg, kwargs = self.process(msg, kwargs)
    self.logger.debug(msg, *args, **kwargs)
@end example

@code{LoggerAdapter} 的 @code{process()} 方法用于将上下文信息添加到日志的输出中去。其入参为日志调用的信息和关键字参数，并将（可能）修改后的入参值传回，以供底层的日志对象调用。该方法的默认实现代码不会对信息做改动，而只是在关键字参数中增加一个键为“extra”的字段，其值即为传入构造函数的字典类对象。当然，若是在调用时传入了一个名为“extra”的关键字参数，则传入值会被悄无声息地覆盖掉。

使用“extra”的好处，就是字典类对象中的值会被并入 @code{LogRecord} 实例的 __dict__ 中，这样就能利用 @code{Formatter} 实例使用自定义字符串了，Formatter 知道该如何使用字典类对象的键。若要用到其他方法，比如想在信息字符串中预置或追加上下文信息，只需继承 @code{LoggerAdapter} 并覆盖 @code{process()} 方法即可完成处理。下面给出一个简单的示例：

@example
class CustomAdapter(logging.LoggerAdapter):
    """
    This example adapter expects the passed in dict-like object to have a
    'connid' key, whose value in brackets is prepended to the log message.
    """
    def process(self, msg, kwargs):
        return '[%s] %s' % (self.extra['connid'], msg), kwargs
@end example

用法可如下所示：

@example
logger = logging.getLogger(__name__)
adapter = CustomAdapter(logger, @{'connid': some_conn_id@})
@end example

这样，只要是该 Adapter 处理的任何日志事件，消息前都会加上`@w{`}some_conn_id`@w{`} 的值。

@menu
* 利用非字典对象传入上下文信息:: 

@end menu

@node 利用非字典对象传入上下文信息,,,利用 LoggerAdapter 传递上下文信息
@anchor{howto/logging-cookbook using-objects-other-than-dicts-to-pass-contextual-information}@anchor{43be}
@subsubsection 利用非字典对象传入上下文信息


传给 @code{LoggerAdapter} 的不一定要是真正的字典对象，也可以传入一个实现了 @code{__getitem__} 和`@w{`}__iter__`@w{`} 方法的类实例，类似要写入日志的字典对象。若要动态生成值（而字典中的值应为常量），这就会很有用。

@node 利用 Filter 传递上下文信息,,利用 LoggerAdapter 传递上下文信息,在自己的输出日志中添加上下文信息
@anchor{howto/logging-cookbook filters-contextual}@anchor{223b}@anchor{howto/logging-cookbook using-filters-to-impart-contextual-information}@anchor{43bf}
@subsubsection 利用 Filter 传递上下文信息


还可以利用用户定义类 @code{Filter} 在日志输出中添加上下文信息。@code{Filter} 实例可以修改传入的 @code{LogRecords}，包括添加额外的属性，然后可以采用合适的格式化字符串对这些属性进行输出，必要时还可采用自定义类 @code{Formatter}。

例如在某 web 应用程序中，正在处理的请求（或至少是当前关注的部分），可存储于线程本地 (@ref{f57,,threading.local}) 变量中，然后从`@w{`}Filter`@w{`} 中去访问，把请求中的一些信息添加进去，比如在 @code{LogRecord} 中写入远程 IP 地址和远程用户名，可利用以上 @code{LoggerAdapter} 示例中的“ip”和“user”属性名。这时可采用与上例相同的格式化字符串来得到类似的输出结果。以下是一段示例代码：

@example
import logging
from random import choice

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.

    Rather than use actual contextual information, we just use random
    data in this demo.
    """

    USERS = ['jim', 'fred', 'sheila']
    IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

    def filter(self, record):

        record.ip = choice(ContextFilter.IPS)
        record.user = choice(ContextFilter.USERS)
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
    a1 = logging.getLogger('a.b.c')
    a2 = logging.getLogger('d.e.f')

    f = ContextFilter()
    a1.addFilter(f)
    a2.addFilter(f)
    a1.debug('A debug message')
    a1.info('An info message with %s', 'some parameters')
    for x in range(10):
        lvl = choice(levels)
        lvlname = logging.getLevelName(lvl)
        a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
@end example

在运行时，产生如下内容:

@example
2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters
@end example

@node 在单个文件中记录多个进程的日志,利用日志文件轮换机制,在自己的输出日志中添加上下文信息,日志操作手册
@anchor{howto/logging-cookbook logging-to-a-single-file-from-multiple-processes}@anchor{43c0}@anchor{howto/logging-cookbook multiple-processes}@anchor{43c1}
@subsection 在单个文件中记录多个进程的日志


尽管日志对象是线程安全的，也确实 @emph{支持} 将一个进程中的多个线程日志记入单个文件，但 @emph{不} 支持将 @emph{多进程} 日志记入单个文件，因为 Python 没有标准方案来实现由多个进程串行访问单个文件。若要将多个进程的日志记入单个文件，一种方案是让所有进程都用一个 @code{SocketHandler} 处理日志，然后用一个单独的进程实现套接字服务器，一边从套接字读取数据一边向文件中写入日志。（当然可在某个现有进程中指定一个线程来执行此项功能。） @ref{43b9,,此部分} 更详细地介绍了这种做法，包含了一个套接字接收器，可以此为起点建立适合自己应用程序的代码。

编写自己的 handler 也是可以的，可利用 @ref{b7,,multiprocessing} 模块中的 @ref{2507,,Lock} 类实现多个进程串行访问文件。现有的 @code{FileHandler} 及其子类目前没有用到 @ref{b7,,multiprocessing}，或许将来有可能会吧。请注意，目前 @ref{b7,,multiprocessing} 模块并未在所有平台上都提供可用的同步锁功能（参见 @indicateurl{https://bugs.python.org/issue3770}）。

或者，还可以利用 @code{Queue} 和 @ref{22c9,,QueueHandler} 将所有的日志事件发送给自己的多进程应用中的某个进程。以下例程演示了这种做法，这里有一个单独的监听进程负责监听其他进程发来的日志事件，并根据自己的日志配置记入日志。尽管本例程只演示了一种实现方案（比如可能想用单独的监听线程而非进程 —— 实现方式其实类似），但确实可以为应用程序的监听进程和其他进程采用不同的配置，作为满足特定需求代码的基础：

@example
# You'll need these imports in your own code
import logging
import logging.handlers
import multiprocessing

# Next two import lines for this demo only
from random import choice, random
import time

#
# Because you'll want to define the logging configurations for listener and workers, the
# listener and worker process functions take a configurer parameter which is a callable
# for configuring logging for that process. These functions are also passed the queue,
# which they use for communication.
#
# In practice, you can configure the listener however you want, but note that in this
# simple example, the listener does not apply level or filter logic to received records.
# In practice, you would probably want to do this logic in the worker processes, to avoid
# sending events which would be filtered out between processes.
#
# The size of the rotated files is made small so you can see the results easily.
def listener_configurer():
    root = logging.getLogger()
    h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
    f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
    h.setFormatter(f)
    root.addHandler(h)

# This is the listener process top-level loop: wait for logging events
# (LogRecords)on the queue and handle them, quit when you get a None for a
# LogRecord.
def listener_process(queue, configurer):
    configurer()
    while True:
        try:
            record = queue.get()
            if record is None:  # We send this as a sentinel to tell the listener to quit.
                break
            logger = logging.getLogger(record.name)
            logger.handle(record)  # No level or filter logic applied - just do it!
        except Exception:
            import sys, traceback
            print('Whoops! Problem:', file=sys.stderr)
            traceback.print_exc(file=sys.stderr)

# Arrays used for random selections in this demo

LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
          logging.ERROR, logging.CRITICAL]

LOGGERS = ['a.b.c', 'd.e.f']

MESSAGES = [
    'Random message #1',
    'Random message #2',
    'Random message #3',
]

# The worker configuration is done at the start of the worker process run.
# Note that on Windows you can't rely on fork semantics, so each process
# will run the logging configuration code when it starts.
def worker_configurer(queue):
    h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
    root = logging.getLogger()
    root.addHandler(h)
    # send all messages, for demo; no other level or filter logic applied.
    root.setLevel(logging.DEBUG)

# This is the worker process top-level loop, which just logs ten events with
# random intervening delays before terminating.
# The print messages are just so you know it's doing something!
def worker_process(queue, configurer):
    configurer(queue)
    name = multiprocessing.current_process().name
    print('Worker started: %s' % name)
    for i in range(10):
        time.sleep(random())
        logger = logging.getLogger(choice(LOGGERS))
        level = choice(LEVELS)
        message = choice(MESSAGES)
        logger.log(level, message)
    print('Worker finished: %s' % name)

# Here's where the demo gets orchestrated. Create the queue, create and start
# the listener, create ten workers and start them, wait for them to finish,
# then send a None to the queue to tell the listener to finish.
def main():
    queue = multiprocessing.Queue(-1)
    listener = multiprocessing.Process(target=listener_process,
                                       args=(queue, listener_configurer))
    listener.start()
    workers = []
    for i in range(10):
        worker = multiprocessing.Process(target=worker_process,
                                         args=(queue, worker_configurer))
        workers.append(worker)
        worker.start()
    for w in workers:
        w.join()
    queue.put_nowait(None)
    listener.join()

if __name__ == '__main__':
    main()
@end example

上述代码可做个变化，在主进程中用单独的线程记录日志：

@example
import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue
import random
import threading
import time

def logger_thread(q):
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger(record.name)
        logger.handle(record)


def worker_process(q):
    qh = logging.handlers.QueueHandler(q)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(qh)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)

if __name__ == '__main__':
    q = Queue()
    d = @{
        'version': 1,
        'formatters': @{
            'detailed': @{
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @}
        @},
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            @},
            'file': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            @},
            'foofile': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed',
            @},
            'errors': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'level': 'ERROR',
                'formatter': 'detailed',
            @},
        @},
        'loggers': @{
            'foo': @{
                'handlers': ['foofile']
            @}
        @},
        'root': @{
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
        @},
    @}
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
        workers.append(wp)
        wp.start()
    logging.config.dictConfig(d)
    lp = threading.Thread(target=logger_thread, args=(q,))
    lp.start()
    # At this point, the main process could do some useful work of its own
    # Once it's done that, it can wait for the workers to terminate...
    for wp in workers:
        wp.join()
    # And now tell the logging thread to finish up, too
    q.put(None)
    lp.join()
@end example

这段改过的代码展示了如何为某日志对象应用指定配置 —— 比如 @code{foo} 日志对象有个特别的 handler，将 @code{foo} 子系统的所有事件保存至文件 @code{mplog-foo.log} 中。主进程的日志机制将会用到这段代码（即便日志事件是在其他的工作进程中产生的），将信息定向输出到指定的地方。

@menu
* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法. 
* 使用 Gunicorn 和 uWSGI 来部署 Web 应用程序:: 

@end menu

@node concurrent futures ProcessPoolExecutor 的用法,使用 Gunicorn 和 uWSGI 来部署 Web 应用程序,,在单个文件中记录多个进程的日志
@anchor{howto/logging-cookbook using-concurrent-futures-processpoolexecutor}@anchor{43c2}
@subsubsection concurrent.futures.ProcessPoolExecutor 的用法


若要利用 @ref{196,,concurrent.futures.ProcessPoolExecutor} 启动工作进程，创建队列的方式应稍有不同。不能是：

@example
queue = multiprocessing.Queue(-1)
@end example

而应是：

@example
queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above
@end example

然后就可以将以下工作进程的创建过程：

@example
workers = []
for i in range(10):
    worker = multiprocessing.Process(target=worker_process,
                                     args=(queue, worker_configurer))
    workers.append(worker)
    worker.start()
for w in workers:
    w.join()
@end example

改为 (记得要先导入 @ref{21,,concurrent.futures}):

@example
with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(worker_process, queue, worker_configurer)
@end example

@node 使用 Gunicorn 和 uWSGI 来部署 Web 应用程序,,concurrent futures ProcessPoolExecutor 的用法,在单个文件中记录多个进程的日志
@anchor{howto/logging-cookbook deploying-web-applications-using-gunicorn-and-uwsgi}@anchor{43c3}
@subsubsection 使用 Gunicorn 和 uWSGI 来部署 Web 应用程序


当使用 Gunicorn@footnote{https://gunicorn.org/} 或 uWSGI@footnote{https://uwsgi-docs.readthedocs.io/en/latest/} (或其他类似工具) 来部署 Web 应用时，会创建多个工作进程来处理客户端请求。 在这种环境下，要避免在你的 Web 应用中直接创建基于文件的处理句柄。 而应改为使用一个 @ref{963,,SocketHandler} 将来自 Web 应用的日志发送到在单独进程中运行的监听器。 这可以通过使用一个进程管理工具例如 Supervisor 来进行设置 —— 请参阅 @ref{43bb,,Running a logging socket listener in production} 了解详情。

@node 利用日志文件轮换机制,日志的其他格式,在单个文件中记录多个进程的日志,日志操作手册
@anchor{howto/logging-cookbook using-file-rotation}@anchor{43c4}
@subsection 利用日志文件轮换机制


@c (see <https://pymotw.com/3/logging/>)

有时需要让日志文件增长到指定大小，然后打开一个新文件并记入日志。或许还需要只保留一定数量的日志文件，当创建了指定数量的文件后，就轮换使用这些文件，以便让文件数量和大小都维持上限。logging 包为这种使用模式提供了 @code{RotatingFileHandler} ：

@example
import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)
@end example

结果应该是6个单独的文件，每个文件都包含了应用程序的部分历史日志:

@example
logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5
@end example

最新的文件始终是 @code{logging_rotatingfile_example.out}，每次达到大小限制时，都会用后缀 @code{.1} 重新命名。已有的备份文件全都会被重命名，将后缀递增（如 @code{.1} 变为 @code{.2} ），而 @code{.6} 文件则会被删除。

显然，这个例子将日志长度设置得太小，这是一个极端的例子。 你可能希望将 @emph{maxBytes} 设置为一个合适的值。

@node 日志的其他格式,自定义 LogRecord,利用日志文件轮换机制,日志操作手册
@anchor{howto/logging-cookbook format-styles}@anchor{43c5}@anchor{howto/logging-cookbook use-of-alternative-formatting-styles}@anchor{43c6}
@subsection 日志的其他格式


当日志模块刚加入 Python 标准库时，想要格式化输出带有可变内容的日志信息，只有一种 %-f 方法。后来 Python 又有了两种格式化方法： @ref{4f9,,string.Template} （Python 2.4 加入）和 @ref{5dd,,str.format()} （Python 2.6 加入）。

从 Python 3.2 开始，日志模块为后加入的两种格式化方式提供了更多支持。@code{Formatter} 得以增强，可以接受名为 @code{style} 的可选关键字参数。其默认值为 @code{'%'} ，其他还可以是 @code{'@{'} 和  @code{'@{TX-PL-LABEL@}#x27;}，对应于另外两种格式化的样式。如您所料，默认保持向下兼容，而通过显式指定样式参数，能够设置用于 @ref{5dd,,str.format()} 或 @ref{4f9,,string.Template} 的格式串。下面是个控制台会话示例，演示一下功能：

@example
>>> import logging
>>> root = logging.getLogger()
>>> root.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler()
>>> bf = logging.Formatter('@{asctime@} @{name@} @{levelname:8s@} @{message@}',
...                        style='@{')
>>> handler.setFormatter(bf)
>>> root.addHandler(handler)
>>> logger = logging.getLogger('foo.bar')
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:11:55,341 foo.bar DEBUG    This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
>>> df = logging.Formatter('$asctime $name $@{levelname@} $message',
...                        style='$')
>>> handler.setFormatter(df)
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
>>>
@end example

请注意，最终输出到日志的信息格式与某一条信息的构造方式完全独立。单条信息仍然可以采用 %-f 格式，如下所示：

@example
>>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
>>>
@end example

日志调用（@code{logger.debug()} 、@code{logger.info()} 等）接受的位置参数只会用于日志信息本身，而关键字参数仅用于日志调用的可选处理参数（如关键字参数 @code{exc_info} 表示应记录跟踪信息， @code{extra} 则标识了需要加入日志的额外上下文信息）。所以不能直接用 @ref{5dd,,str.format()} 或 @ref{4f9,,string.Template} 语法进行日志调用，因为日志包在内部使用 %-f 格式来合并格式串和参数变量。在保持向下兼容性时，这一点不会改变，因为已有代码中的所有日志调用都会使用%-f 格式串。

还有一种方法可以构建自己的日志信息，就是利用 @{@}- 和 $- 格式。回想一下，任意对象都可用为日志信息的格式串，日志包将会调用该对象的 @code{str()} 方法，以获取最终的格式串。不妨看下一下两个类：

@example
class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
@end example

上述两个类均可代替格式串，使得能用 @{@}- 或 $-formatting 构建最终的“日志信息”部分，这些信息将出现在格式化后的日志输出中，替换 %(message)s 或“@{message@}”或“$message”。每次写入日志时都要使用类名，有点不大实用，但如果用上 __ 之类的别名就相当合适了（双下划线 --- 不要与 _ 混淆，单下划线用作 @ref{e9a,,gettext.gettext()} 或相关函数的同义词/别名 ）。

Python 并没有上述两个类，当然复制粘贴到自己的代码中也很容易。用法可如下所示（假定在名为 @code{wherever} 的模块中声明）：

@example
>>> from wherever import BraceMessage as __
>>> print(__('Message with @{0@} @{name@}', 2, name='placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: (@{point.x:.2f@}, @{point.y:.2f@})',
...       point=p))
Message with coordinates: (0.50, 0.50)
>>> from wherever import DollarMessage as __
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>
@end example

上述示例用了 @code{print()} 演示格式化输出的过程，实际记录日志时当然会用类似 @code{logger.debug()} 的方法来加以应用。

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志记录调用时发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可能让人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式串。因为 __ 符号只是对 XXXMessage 类的构造函数调用的语法糖。

只要愿意，上述类似的效果即可用 @code{LoggerAdapter} 实现，如下例所示：

@example
import logging

class Message:
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)

class StyleAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra=None):
        super().__init__(logger, extra or @{@})

    def log(self, level, msg, /, *args, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger._log(level, Message(msg, args), (), **kwargs)

logger = StyleAdapter(logging.getLogger(__name__))

def main():
    logger.debug('Hello, @{@}', 'world!')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()
@end example

在用 Python 3.2 以上版本运行时，上述代码应该会把 @code{Hello, world!} 写入日志。

@node 自定义 LogRecord,子类化 QueueHandler - ZeroMQ 示例,日志的其他格式,日志操作手册
@anchor{howto/logging-cookbook custom-logrecord}@anchor{43c7}@anchor{howto/logging-cookbook customizing-logrecord}@anchor{43c8}
@subsection 自定义 @code{LogRecord}


每条日志事件都由一个  @ref{9f5,,LogRecord} 实例表示。当某事件要记入日志并且没有被某级别过滤掉时，就会创建一个 @ref{9f5,,LogRecord} 对象，并将有关事件的信息填入，传给该日志对象的 handler（及其祖先，直至对象禁止向上传播为止）。在 Python 3.2 之前，只有两个地方会进行事件的创建：


@itemize *

@item 
@ref{2219,,Logger.makeRecord()}，在事件正常记入日志的过程中调用。这会直接调用 @ref{9f5,,LogRecord} 来创建一个实例。

@item 
@ref{223e,,makeLogRecord()}，调用时会带上一个字典参数，其中存放着要加入 LogRecord 的属性。这通常在通过网络接收到合适的字典时调用（如通过 @ref{963,,SocketHandler} 以 pickle 形式，或通过 @ref{80c,,HTTPHandler} 以 JSON 形式）。
@end itemize

于是这意味着若要对 @ref{9f5,,LogRecord} 进行定制，必须进行下述某种操作。


@itemize *

@item 
创建 @ref{4b6,,Logger}  自定义子类，重写 @ref{2219,,Logger.makeRecord()}，并在实例化所需日志对象之前用 @ref{224b,,setLoggerClass()} 进行设置。

@item 
为日志对象添加 @ref{c51,,Filter} 或 handler，当其 @ref{2239,,filter()} 方法被调用时，会执行必要的定制操作。
@end itemize

比如说在有多个不同库要完成不同操作的场景下，第一种方式会有点笨拙。 每次都要尝试设置自己的 @ref{4b6,,Logger} 子类，而起作用的是最后一次尝试。

第二种方式在多数情况下效果都比较良好，但不允许你使用特殊化的 @ref{9f5,,LogRecord} 子类。 库开发者可以为他们的日志记录器设置合适的过滤器，但他们应当要记得每次引入新的日志记录器时都需如此（他们只需通过添加新的包或模块并执行以下操作即可）:

@example
logger = logging.getLogger(__name__)
@end example

或许这样要顾及太多事情。开发人员还可以将过滤器附加到其顶级日志对象的 @ref{cee,,NullHandler} 中，但如果应用程序开发人员将 handler 附加到较底层库的日志对象，则不会调用该过滤器 --- 所以 handler 输出的内容不会符合库开发人员的预期。

在 Python 3.2 以上版本中，@ref{9f5,,LogRecord} 的创建是通过工厂对象完成的，工厂对象可以指定。工厂对象只是一个可调用对象，可以用 @ref{2241,,setLogRecordFactory()} 进行设置，并用 @ref{2240,,getLogRecordFactory()} 进行查询。工厂对象的调用参数与 @ref{9f5,,LogRecord} 的构造函数相同，因为 @ref{9f5,,LogRecord} 是工厂对象的默认设置。

这种方式可以让自定义工厂对象完全控制 LogRecord 的创建过程。比如可以返回一个子类，或者在创建的日志对象中加入一些额外的属性，使用方式如下所示：

@example
old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)
@end example

这种模式允许不同的库将多个工厂对象链在一起，只要不会覆盖彼此的属性或标准属性，就不会出现意外。但应记住，工厂链中的每个节点都会增加日志操作的运行开销，本技术仅在采用 @ref{c51,,Filter} 无法达到目标时才应使用。

@node 子类化 QueueHandler - ZeroMQ 示例,子类化 QueueListener —— ZeroMQ 示例,自定义 LogRecord,日志操作手册
@anchor{howto/logging-cookbook subclassing-queuehandler-a-zeromq-example}@anchor{43c9}@anchor{howto/logging-cookbook zeromq-handlers}@anchor{43ca}
@subsection 子类化 QueueHandler - ZeroMQ 示例


你可以使用 @code{QueueHandler} 子类将消息发送给其他类型的队列 ，比如 ZeroMQ 'publish' 套接字。 在以下示例中，套接字将单独创建并传给处理句柄 (作为它的 'queue'):

@example
import zmq   # using pyzmq, the Python binding for ZeroMQ
import json  # for serializing records portably

ctx = zmq.Context()
sock = zmq.Socket(ctx, zmq.PUB)  # or zmq.PUSH, or other suitable value
sock.bind('tcp://*:5556')        # or wherever

class ZeroMQSocketHandler(QueueHandler):
    def enqueue(self, record):
        self.queue.send_json(record.__dict__)


handler = ZeroMQSocketHandler(sock)
@end example

当然还有其他方案，比如通过 hander 传入所需数据，以创建 socket：

@example
class ZeroMQSocketHandler(QueueHandler):
    def __init__(self, uri, socktype=zmq.PUB, ctx=None):
        self.ctx = ctx or zmq.Context()
        socket = zmq.Socket(self.ctx, socktype)
        socket.bind(uri)
        super().__init__(socket)

    def enqueue(self, record):
        self.queue.send_json(record.__dict__)

    def close(self):
        self.queue.close()
@end example

@node 子类化 QueueListener —— ZeroMQ 示例,基于字典进行日志配置的示例,子类化 QueueHandler - ZeroMQ 示例,日志操作手册
@anchor{howto/logging-cookbook subclassing-queuelistener-a-zeromq-example}@anchor{43cb}
@subsection 子类化 QueueListener —— ZeroMQ 示例


你还可以子类化 @code{QueueListener} 来从其他类型的队列中获取消息，比如从 ZeroMQ 'subscribe' 套接字。 下面是一个例子:

@example
class ZeroMQSocketListener(QueueListener):
    def __init__(self, uri, /, *handlers, **kwargs):
        self.ctx = kwargs.get('ctx') or zmq.Context()
        socket = zmq.Socket(self.ctx, zmq.SUB)
        socket.setsockopt_string(zmq.SUBSCRIBE, '@w{'})  # subscribe to everything
        socket.connect(uri)
        super().__init__(socket, *handlers, **kwargs)

    def dequeue(self):
        msg = self.queue.recv_json()
        return logging.makeLogRecord(msg)
@end example


@subsubheading 参见



@table @asis

@item 模块 @ref{aa,,logging}

日志记录模块的 API 参考。

@item 模块 @ref{ab,,logging.config}

日志记录模块的配置 API 。

@item 模块 @ref{ac,,logging.handlers}

日志记录模块中的常用 handler。
@end table

@ref{c4c,,日志操作基础教程}

@ref{c4d,,日志操作的高级教程}


@node 基于字典进行日志配置的示例,利用 rotator 和 namer 自定义日志轮换操作,子类化 QueueListener —— ZeroMQ 示例,日志操作手册
@anchor{howto/logging-cookbook an-example-dictionary-based-configuration}@anchor{43cc}
@subsection 基于字典进行日志配置的示例


以下是日志配置字典的一个示例——它取自 Django 项目的`文档<@indicateurl{https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging}>`_。此字典将被传给 @ref{c07,,dictConfig()} 以使配置生效：

@example
LOGGING = @{
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': @{
        'verbose': @{
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        @},
        'simple': @{
            'format': '%(levelname)s %(message)s'
        @},
    @},
    'filters': @{
        'special': @{
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        @}
    @},
    'handlers': @{
        'null': @{
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        @},
        'console':@{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'simple'
        @},
        'mail_admins': @{
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
        @}
    @},
    'loggers': @{
        'django': @{
            'handlers':['null'],
            'propagate': True,
            'level':'INFO',
        @},
        'django.request': @{
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        @},
        'myproject.custom': @{
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'filters': ['special']
        @}
    @}
@}
@end example

有关本配置的更多信息，请参阅 Django 文档的  有关章节@footnote{https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging} 。

@node 利用 rotator 和 namer 自定义日志轮换操作,更详细的多进程日志示例,基于字典进行日志配置的示例,日志操作手册
@anchor{howto/logging-cookbook cookbook-rotator-namer}@anchor{228f}@anchor{howto/logging-cookbook using-a-rotator-and-namer-to-customize-log-rotation-processing}@anchor{43cd}
@subsection 利用 rotator 和 namer 自定义日志轮换操作


以下代码给出了定义 namer 和 rotator 的示例，其中演示了基于 zlib 的日志文件压缩过程：

@example
def namer(name):
    return name + ".gz"

def rotator(source, dest):
    with open(source, "rb") as sf:
        data = sf.read()
        compressed = zlib.compress(data, 9)
        with open(dest, "wb") as df:
            df.write(compressed)
    os.remove(source)

rh = logging.handlers.RotatingFileHandler(...)
rh.rotator = rotator
rh.namer = namer
@end example

这些不是“真正的” .gz 文件，因为他们只是纯压缩数据，缺少真正 gzip 文件中的“容器”。此段代码只是用于演示。

@node 更详细的多进程日志示例,在发送给 SysLogHandler 的信息中插入一个 BOM。,利用 rotator 和 namer 自定义日志轮换操作,日志操作手册
@anchor{howto/logging-cookbook a-more-elaborate-multiprocessing-example}@anchor{43ce}
@subsection 更详细的多进程日志示例


以下可运行的示例显示了如何利用配置文件在多进程中应用日志。这些配置相当简单，但足以说明如何在真实的多进程场景中实现较为复杂的配置。

在此示例中，主进程产生一个侦听器进程和一些工作进程。每个主进程、侦听器进程和工作进程都有三种独立的日志配置（工作进程共享同一套配置）。大家可以看到主进程的日志记录过程、工作线程向 QueueHandler 写入日志的过程，以及侦听器实现 QueueListener 和较为复杂的日志配置，如何将由队列接收到的事件分发给配置指定的 handler。请注意，这些配置纯粹用于演示，但应该能调整代码以适用于自己的场景。

以下是代码——但愿文档字符串和注释能有助于理解其工作原理：

@example
import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue, Event, current_process
import os
import random
import time

class MyHandler:
    """
    A simple handler for logging events. It runs in the listener process and
    dispatches events to loggers based on the name in the received record,
    which then get dispatched, by the logging system, to the handlers
    configured for those loggers.
    """

    def handle(self, record):
        if record.name == "root":
            logger = logging.getLogger()
        else:
            logger = logging.getLogger(record.name)

        if logger.isEnabledFor(record.levelno):
            # The process name is transformed just to show that it's the listener
            # doing the logging to files and console
            record.processName = '%s (for %s)' % (current_process().name, record.processName)
            logger.handle(record)

def listener_process(q, stop_event, config):
    """
    This could be done in the main process, but is just done in a separate
    process for illustrative purposes.

    This initialises logging according to the specified configuration,
    starts the listener and waits for the main process to signal completion
    via the event. The listener is then stopped, and the process exits.
    """
    logging.config.dictConfig(config)
    listener = logging.handlers.QueueListener(q, MyHandler())
    listener.start()
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    stop_event.wait()
    listener.stop()

def worker_process(config):
    """
    A number of these are spawned for the purpose of illustration. In
    practice, they could be a heterogeneous bunch of processes rather than
    ones which are identical to each other.

    This initialises logging according to the specified configuration,
    and logs a hundred messages with random levels to randomly selected
    loggers.

    A small sleep is added to allow other processes a chance to run. This
    is not strictly needed, but it mixes the output from the different
    processes a bit more than if it's left out.
    """
    logging.config.dictConfig(config)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)
        time.sleep(0.01)

def main():
    q = Queue()
    # The main process gets a simple configuration which prints to the console.
    config_initial = @{
        'version': 1,
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'level': 'INFO'
            @}
        @},
        'root': @{
            'handlers': ['console'],
            'level': 'DEBUG'
        @}
    @}
    # The worker process configuration is just a QueueHandler attached to the
    # root logger, which allows all messages to be sent to the queue.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_worker = @{
        'version': 1,
        'disable_existing_loggers': True,
        'handlers': @{
            'queue': @{
                'class': 'logging.handlers.QueueHandler',
                'queue': q
            @}
        @},
        'root': @{
            'handlers': ['queue'],
            'level': 'DEBUG'
        @}
    @}
    # The listener process configuration shows that the full flexibility of
    # logging configuration is available to dispatch events to handlers however
    # you want.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_listener = @{
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': @{
            'detailed': @{
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @},
            'simple': @{
                'class': 'logging.Formatter',
                'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            @}
        @},
        'handlers': @{
            'console': @{
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
                'level': 'INFO'
            @},
            'file': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed'
            @},
            'foofile': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed'
            @},
            'errors': @{
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'formatter': 'detailed',
                'level': 'ERROR'
            @}
        @},
        'loggers': @{
            'foo': @{
                'handlers': ['foofile']
            @}
        @},
        'root': @{
            'handlers': ['console', 'file', 'errors'],
            'level': 'DEBUG'
        @}
    @}
    # Log some initial events, just to show that logging in the parent works
    # normally.
    logging.config.dictConfig(config_initial)
    logger = logging.getLogger('setup')
    logger.info('About to create workers ...')
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1),
                     args=(config_worker,))
        workers.append(wp)
        wp.start()
        logger.info('Started worker: %s', wp.name)
    logger.info('About to create listener ...')
    stop_event = Event()
    lp = Process(target=listener_process, name='listener',
                 args=(q, stop_event, config_listener))
    lp.start()
    logger.info('Started listener')
    # We now hang around for the workers to finish their work.
    for wp in workers:
        wp.join()
    # Workers all done, listening can now stop.
    # Logging in the parent still works normally.
    logger.info('Telling listener to stop ...')
    stop_event.set()
    lp.join()
    logger.info('All done.')

if __name__ == '__main__':
    main()
@end example

@node 在发送给 SysLogHandler 的信息中插入一个 BOM。,结构化日志的实现代码,更详细的多进程日志示例,日志操作手册
@anchor{howto/logging-cookbook inserting-a-bom-into-messages-sent-to-a-sysloghandler}@anchor{43cf}
@subsection 在发送给 SysLogHandler 的信息中插入一个  BOM。


@geindex RFC; RFC 5424
RFC 5424@footnote{https://tools.ietf.org/html/rfc5424.html} 要求，Unicode 信息应采用字节流形式发送到系统 syslog 守护程序，字节流结构如下所示：可选的纯 ASCII部分，后跟 UTF-8 字节序标记（BOM），然后是采用 UTF-8 编码的 Unicode。（参见 
@geindex RFC; RFC 5424#section-6
相关规范@footnote{https://tools.ietf.org/html/rfc5424.html#section-6} 。）

在 Python 3.1 的 @ref{b04,,SysLogHandler} 中，已加入了在日志信息中插入 BOM 的代码，但不幸的是，代码并不正确，BOM 出现在了日志信息的开头，因此在它之前就不允许出现纯 ASCII 内容了。

由于无法正常工作， Python 3.2.4 以上版本已删除了出错的插入 BOM 代码。但已有版本的代码不会被替换，若要生成与 
@geindex RFC; RFC 5424
RFC 5424@footnote{https://tools.ietf.org/html/rfc5424.html} 兼容的日志信息，包括一个 BOM 符，前面有可选的纯 ASCII 字节流，后面为 UTF-8 编码的任意 Unicode，那么 需要执行以下操作：


@enumerate 

@item 
为 @ref{b04,,SysLogHandler} 实例串上一个 @ref{220c,,Formatter} 实例，格式串可如下：

@example
'ASCII section\ufeffUnicode section'
@end example

用 UTF-8 编码时，Unicode 码位 U+FEFF 将会编码为 UTF-8 BOM——字节串 @code{b'\xef\xbb\xbf'} 。

@item 
ASCII 部分可替换为任意字符，但要保证替换后的数据一定是 ASCII 码（这样在 UTF-8 编码后就会维持不变）。

@item 
Unicode 部分可替换为任意字符；如果替换后的数据包含超出 ASCII 范围的字符，没问题——他们将用 UTF-8 进行编码。
@end enumerate

@code{SysLogHandler} @emph{将} 对格式化后的日志信息进行 UTF-8 编码。如果遵循上述规则，应能生成符合 
@geindex RFC; RFC 5424
RFC 5424@footnote{https://tools.ietf.org/html/rfc5424.html} 的日志信息。否则，日志记录过程可能不会有什么反馈，但日志信息将不与 RFC 5424 兼容，syslog 守护程序可能会有出错反应。

@node 结构化日志的实现代码,利用 dictConfig 自定义 handler,在发送给 SysLogHandler 的信息中插入一个 BOM。,日志操作手册
@anchor{howto/logging-cookbook implementing-structured-logging}@anchor{43d0}
@subsection 结构化日志的实现代码


大多数日志信息是供人阅读的，所以机器解析起来并不容易，但某些时候可能希望以结构化的格式输出，以 @emph{能够} 被程序解析（无需用到复杂的正则表达式）。这可以直接用 logging 包实现。实现方式有很多，以下是一种比较简单的方案，利用 JSON 以机器可解析的方式对事件信息进行序列化：

@example
import json
import logging

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))
@end example

上述代码运行后的结果是：

@example
message 1 >>> @{"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"@}
@end example

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。

若需进行更为定制化的处理，可以使用自定义 JSON 编码对象，下面给出完整示例：

@example
from __future__ import unicode_literals

import json
import logging

# This next bit is to ensure the script runs unchanged on 2.x and 3.x
try:
    unicode
except NameError:
    unicode = str

class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return tuple(o)
        elif isinstance(o, unicode):
            return o.encode('unicode_escape').decode('ascii')
        return super().default(o)

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        s = Encoder().encode(self.kwargs)
        return '%s >>> %s' % (self.message, s)

_ = StructuredMessage   # optional, to improve readability

def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(_('message 1', set_value=@{1, 2, 3@}, snowman='\u2603'))

if __name__ == '__main__':
    main()
@end example

上述代码运行后的结果是：

@example
message 1 >>> @{"snowman": "\u2603", "set_value": [1, 2, 3]@}
@end example

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。

@node 利用 dictConfig 自定义 handler,生效于整个应用程序的格式化样式,结构化日志的实现代码,日志操作手册
@anchor{howto/logging-cookbook custom-handlers}@anchor{43d1}@anchor{howto/logging-cookbook customizing-handlers-with-dictconfig}@anchor{43d2}
@subsection 利用 @code{dictConfig()} 自定义 handler


有时需要以特定方式自定义日志 handler，如果采用 @ref{c07,,dictConfig()}，可能无需生成子类就可以做到。比如要设置日志文件的所有权。在 POSIX 上，可以利用 @ref{b5a,,shutil.chown()} 轻松完成，但 stdlib 中的文件 handler 并不提供内置支持。于是可以用普通函数自定义 handler 的创建，例如：

@example
def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)
@end example

然后，你可以在传给 @ref{c07,,dictConfig()} 的日志配置中指定通过调用此函数来创建日志处理程序:

@example
LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'default': @{
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        @},
    @},
    'handlers': @{
        'file':@{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        @},
    @},
    'root': @{
        'handlers': ['file'],
        'level': 'DEBUG',
    @},
@}
@end example

出于演示目的，以下示例设置用户和用户组为 @code{pulse}。代码置于一个可运行的脚本文件 @code{chowntest.py} 中：

@example
import logging, logging.config, os, shutil

def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)

LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'default': @{
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        @},
    @},
    'handlers': @{
        'file':@{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        @},
    @},
    'root': @{
        'handlers': ['file'],
        'level': 'DEBUG',
    @},
@}

logging.config.dictConfig(LOGGING)
logger = logging.getLogger('mylogger')
logger.debug('A debug message')
@end example

可能需要 @code{root} 权限才能运行：

@example
$ sudo python3.3 chowntest.py
$ cat chowntest.log
2013-11-05 09:34:51,128 DEBUG mylogger A debug message
$ ls -l chowntest.log
-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log
@end example

请注意此示例用的是 Python 3.3，因为 @ref{b5a,,shutil.chown()} 是从此版本开始出现的。 此方式应当适用于任何支持 @ref{c07,,dictConfig()} 的 Python 版本 —— 例如 Python 2.7, 3.2 或更新的版本。 对于 3.3 之前的版本，你应当使用 @ref{b19,,os.chown()} 之类的函数来实现实际的所有权修改。

实际应用中，handler 的创建函数可能位于项目的工具模块中。以下配置：

@example
'()': owned_file_handler,
@end example

应使用：

@example
'()': 'ext://project.util.owned_file_handler',
@end example

这里的 @code{project.util} 可以换成函数所在包的实际名称。 在上述的可用脚本中，应该可以使用 @code{'ext://__main__.owned_file_handler'}。 在这里，实际的可调用对象是由 @ref{c07,,dictConfig()} 从 @code{ext://} 说明中解析出来的。

上述示例还指明了其他的文件修改类型的实现方案 —— 比如同样利用 @ref{b18,,os.chmod()} 设置 POSIX 访问权限位。

当然，以上做法也可以扩展到 @ref{2273,,FileHandler} 之外的其他类型的 handler ——比如某个轮换文件 handler，或类型完全不同的其他 handler。

@node 生效于整个应用程序的格式化样式,用 dictConfig 配置过滤器,利用 dictConfig 自定义 handler,日志操作手册
@anchor{howto/logging-cookbook formatting-styles}@anchor{2232}@anchor{howto/logging-cookbook using-particular-formatting-styles-throughout-your-application}@anchor{43d3}
@subsection 生效于整个应用程序的格式化样式


在 Python 3.2 中，@ref{220c,,Formatter} 增加了一个 @code{style} 关键字形参，它默认为 @code{%} 以便向下兼容，但是允许采用 @code{@{} 或 @code{@{TX-PL-LABEL@}#x60;} 来支持 @ref{5dd,,str.format()} 和 @ref{4f9,,string.Template} 所支持的格式化方式。 请注意此形参控制着用用于最终输出到日志的日志消息格式，并且与单独日志消息的构造方式完全无关。

日志函数（@ref{80b,,debug()}, @ref{220e,,info()} 等）只会读取位置参数获取日志信息本身，而关键字参数仅用于确定日志函数的工作选项（比如关键字参数 @code{exc_info} 表示应将跟踪信息记入日志，关键字参数 @code{extra} 则给出了需加入日志的额外上下文信息）。所以不能直接使用 @ref{5dd,,str.format()} 或 @ref{4f9,,string.Template} 这种语法进行日志调用，因为日志包在内部使用 %-f 格式来合并格式串和可变参数。因为尚需保持向下兼容，这一点不会改变，已有代码中的所有日志调用都将采用 %-f 格式串。

有人建议将格式化样式与特定的日志对象进行关联，但其实也会遇到向下兼容的问题，因为已有代码可能用到了某日志对象并采用了 %-f 格式串。

为了让第三方库和自编代码都能够交互使用日志功能，需要决定在单次日志记录调用级别采用什么格式。于是就出现了其他几种格式化样式方案。

@menu
* LogRecord 工厂的用法:: 
* 自定义日志信息对象的使用:: 

@end menu

@node LogRecord 工厂的用法,自定义日志信息对象的使用,,生效于整个应用程序的格式化样式
@anchor{howto/logging-cookbook using-logrecord-factories}@anchor{43d4}
@subsubsection LogRecord 工厂的用法


在 Python 3.2 中，伴随着 @ref{220c,,Formatter} 的上述变化，logging 包增加了允许用户使用 @ref{2241,,setLogRecordFactory()} 函数来。设置自己的 @ref{9f5,,LogRecord} 子类的功能。 你可以使用此功能来设置自己的 @ref{9f5,,LogRecord} 子类，它会通过重载 @ref{223f,,getMessage()} 方法来完成适当的操作。 @code{msg % args} 格式化是在此方法的基类实现中进行的，你可以在那里用你自己的格式化操作来替换；但是，你应当注意要支持全部的格式化样式并允许将 %-formatting 作为默认样式，以确保与其他代码进行配合。 还应当注意调用 @code{str(self.msg)}，正如基类实现所做的一样。

更多信息请参阅 @ref{2241,,setLogRecordFactory()} 和 @ref{9f5,,LogRecord} 的参考文档。

@node 自定义日志信息对象的使用,,LogRecord 工厂的用法,生效于整个应用程序的格式化样式
@anchor{howto/logging-cookbook using-custom-message-objects}@anchor{43d5}
@subsubsection 自定义日志信息对象的使用


另一种方案可能更为简单，可以利用 @{@}- 和 $- 格式构建自己的日志消息。大家或许还记得（来自 @ref{2243,,使用任意对象作为消息}），可以用任意对象作为日志信息的格式串，日志包将调用该对象上 @ref{206,,str()} 获取实际的格式串。看下以下两个类：

@example
class BraceMessage:
    def __init__(self, fmt, /, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, /, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)
@end example

以上两个类均都可用于替代格式串，以便用 @{@}- 或 $-formatting 构建实际的“日志信息”部分，此部分将出现在格式化后的日志输出中，替换 %(message)s 、“@{message@}”或“$message”。每次要写入日志时都使用类名，如果觉得使用不便，可以采用 @code{M} 或 @code{_} 之类的别名（如果将 @code{_} 用于本地化操作，则可用 @code{__}）。

下面给出示例。 首先用 @ref{5dd,,str.format()} 进行格式化：

@example
>>> __ = BraceMessage
>>> print(__('Message with @{0@} @{1@}', 2, 'placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: (@{point.x:.2f@}, @{point.y:.2f@})', point=p))
Message with coordinates: (0.50, 0.50)
@end example

然后，用 @ref{4f9,,string.Template} 格式化：

@example
>>> __ = DollarMessage
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>
@end example

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志调用时发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可能让人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式串。因为 __ 符号只是对 @code{XXXMessage} 类的构造函数调用的语法糖。

@node 用 dictConfig 配置过滤器,异常信息的自定义格式化,生效于整个应用程序的格式化样式,日志操作手册
@anchor{howto/logging-cookbook configuring-filters-with-dictconfig}@anchor{43d6}@anchor{howto/logging-cookbook filters-dictconfig}@anchor{43d7}
@subsection 用 @code{dictConfig()} 配置过滤器


用 @ref{c07,,dictConfig()} @emph{可以} 对日志过滤器进行设置，尽管乍一看做法并不明显（所以才需要本秘籍）。 由于 @ref{c51,,Filter} 是标准库中唯一的日志过滤器类，不太可能满足众多的要求（它只是作为基类存在），通常需要定义自己的 @ref{c51,,Filter} 子类，并重写 @ref{2239,,filter()} 方法。为此，请在过滤器的配置字典中设置 @code{()} 键，指定要用于创建过滤器的可调用对象（最明显可用的就是给出一个类，但也可以提供任何一个可调用对象，只要能返回 @ref{c51,,Filter} 实例即可）。下面是一个完整的例子：

@example
import logging
import logging.config
import sys

class MyFilter(logging.Filter):
    def __init__(self, param=None):
        self.param = param

    def filter(self, record):
        if self.param is None:
            allow = True
        else:
            allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg
        return allow

LOGGING = @{
    'version': 1,
    'filters': @{
        'myfilter': @{
            '()': MyFilter,
            'param': 'noshow',
        @}
    @},
    'handlers': @{
        'console': @{
            'class': 'logging.StreamHandler',
            'filters': ['myfilter']
        @}
    @},
    'root': @{
        'level': 'DEBUG',
        'handlers': ['console']
    @},
@}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.debug('hello')
    logging.debug('hello - noshow')
@end example

以上示例展示了将配置数据传给构造实例的可调用对象，形式是关键字参数。运行后将会输出：

@example
changed: hello
@end example

这说明过滤器按照配置的参数生效了。

需要额外注意的地方：


@itemize *

@item 
如果在配置中无法直接引用可调用对象（比如位于不同的模块中，并且不能在配置字典所在的位置直接导入），则可以采用 @code{ext://...} 的形式，正如 @ref{226a,,访问外部对象} 所述。例如，在上述示例中可以使用文本 @code{'ext://__main__.MyFilter'} 而不是 @code{MyFilter} 对象。

@item 
与过滤器一样，上述技术还可用于配置自定义 handler 和格式化对象。有关如何在日志配置中使用用户自定义对象的更多信息，请参阅 @ref{2260,,用户定义对象}，以及上述 @ref{43d1,,利用 dictConfig() 自定义 handler} 的其他指南。
@end itemize

@node 异常信息的自定义格式化,语音播报日志信息,用 dictConfig 配置过滤器,日志操作手册
@anchor{howto/logging-cookbook custom-format-exception}@anchor{43d8}@anchor{howto/logging-cookbook customized-exception-formatting}@anchor{43d9}
@subsection 异常信息的自定义格式化


有时可能需要设置自定义的异常信息格式——考虑到会用到参数，假定要让每条日志事件只占一行，即便存在异常信息也一样。这可以用自定义格式化类来实现，如下所示：

@example
import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        """
        Format an exception so that it prints on a single line.
        """
        result = super().formatException(exc_info)
        return repr(result)  # or format into one line however you want to

    def format(self, record):
        s = super().format(record)
        if record.exc_text:
            s = s.replace('\n', '@w{'}) + '|'
        return s

def configure_logging():
    fh = logging.FileHandler('output.txt', 'w')
    f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                  '%d/%m/%Y %H:%M:%S')
    fh.setFormatter(f)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(fh)

def main():
    configure_logging()
    logging.info('Sample message')
    try:
        x = 1 / 0
    except ZeroDivisionError as e:
        logging.exception('ZeroDivisionError: %s', e)

if __name__ == '__main__':
    main()
@end example

运行后将会生成只有两行信息的文件：

@example
28/01/2015 07:21:23|INFO|Sample message|
28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|
@end example

虽然上述处理方式很简单，但也给出了根据喜好对异常信息进行格式化输出的方案。或许 @ref{11c,,traceback} 模块能满足更专门的需求。

@node 语音播报日志信息,缓冲日志信息并按条件输出,异常信息的自定义格式化,日志操作手册
@anchor{howto/logging-cookbook speaking-logging-messages}@anchor{43da}@anchor{howto/logging-cookbook spoken-messages}@anchor{43db}
@subsection 语音播报日志信息


有时可能需要以声音的形式呈现日志消息。如果系统自带了文本转语音 （TTS）功能，即便没与 Python 关联也很容易做到。大多数 TTS 系统都有一个可运行的命令行程序，在 handler 中可以用 @ref{f9,,subprocess} 进行调用。这里假定 TTS 命令行程序不会与用户交互，或需要很长时间才会执行完毕，写入日志的信息也不会多到影响用户查看，并且可以接受每次播报一条信息，以下示例实现了等一条信息播完再处理下一条，可能会导致其他 handler 的等待。这个简短示例仅供演示，假定 @code{espeak} TTS 包已就绪：

@example
import logging
import subprocess
import sys

class TTSHandler(logging.Handler):
    def emit(self, record):
        msg = self.format(record)
        # Speak slowly in a female English voice
        cmd = ['espeak', '-s150', '-ven+f3', msg]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # wait for the program to finish
        p.communicate()

def configure_logging():
    h = TTSHandler()
    root = logging.getLogger()
    root.addHandler(h)
    # the default formatter just returns the message
    root.setLevel(logging.DEBUG)

def main():
    logging.info('Hello')
    logging.debug('Goodbye')

if __name__ == '__main__':
    configure_logging()
    sys.exit(main())
@end example

运行后将会以女声播报“Hello”和“Goodbye”。

当然，上述方案也适用于其他 TTS 系统，甚至可以利用命令行运行的外部程序来处理日志信息。

@node 缓冲日志信息并按条件输出,通过配置将时间格式化为 UTC（GMT）格式,语音播报日志信息,日志操作手册
@anchor{howto/logging-cookbook buffered-logging}@anchor{43dc}@anchor{howto/logging-cookbook buffering-logging-messages-and-outputting-them-conditionally}@anchor{43dd}
@subsection 缓冲日志信息并按条件输出


有时可能需要将日志信息写入临时位置，仅在特定情况下才进行输出。比如在函数中记录调试事件，若函数执行完成且没有错误，收集到的调试信息就无需输出，以免造成日志混乱，但在出现错误时则需要输出全部的调试和错误信息。

以下例子展示了如何在日志函数上使用装饰器，以实现上述功能。这里用到了 @ref{226d,,logging.handlers.MemoryHandler} ，将日志事件缓存下来，直至发生某些状况时，缓存的事件才会被送出（@code{flushed}）——传给另一个 handler（ @code{target}）进行处理。默认情况下， @code{MemoryHandler} 在缓冲区满时，或者事件级别大于等于指定阈值的，会将数据刷出。若需自定义刷新行为，可以利用定制 @code{MemoryHandler} 子类来实现。

以下例程包含一个简单的 @code{foo} 函数 ，它只是循环运行于全部日志级别上，写入 @code{sys.stderr} ，输出信息包括日志级别和日志消息。可为 @code{foo} 传入一个参数，true 则在 ERROR 和 CRITICAL 级别记录日志，否则只在DEBUG、INFO 和 WARNING 级别记录日志。

这里只是为 @code{foo} 加了个装饰器 ，进行有条件的日志记录。该装饰器以日志对象为参数，并在调用被装饰函数期间增加一个内存处理 handler。该装饰器的参数还可以加上目标 handler、日志级别和缓冲区的容量（可缓存的日志条数量）。这些参数的默认值分别是写入 @code{sys.stderr} 的 @ref{c4f,,StreamHandler} 、 @code{logging.ERROR} 和 @code{100}。

以下是脚本：

@example
import logging
from logging.handlers import MemoryHandler
import sys

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
    if target_handler is None:
        target_handler = logging.StreamHandler()
    if flush_level is None:
        flush_level = logging.ERROR
    if capacity is None:
        capacity = 100
    handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

    def decorator(fn):
        def wrapper(*args, **kwargs):
            logger.addHandler(handler)
            try:
                return fn(*args, **kwargs)
            except Exception:
                logger.exception('call failed')
                raise
            finally:
                super(MemoryHandler, handler).flush()
                logger.removeHandler(handler)
        return wrapper

    return decorator

def write_line(s):
    sys.stderr.write('%s\n' % s)

def foo(fail=False):
    write_line('about to log at DEBUG ...')
    logger.debug('Actually logged at DEBUG')
    write_line('about to log at INFO ...')
    logger.info('Actually logged at INFO')
    write_line('about to log at WARNING ...')
    logger.warning('Actually logged at WARNING')
    if fail:
        write_line('about to log at ERROR ...')
        logger.error('Actually logged at ERROR')
        write_line('about to log at CRITICAL ...')
        logger.critical('Actually logged at CRITICAL')
    return fail

decorated_foo = log_if_errors(logger)(foo)

if __name__ == '__main__':
    logger.setLevel(logging.DEBUG)
    write_line('Calling undecorated foo with False')
    assert not foo(False)
    write_line('Calling undecorated foo with True')
    assert foo(True)
    write_line('Calling decorated foo with False')
    assert not decorated_foo(False)
    write_line('Calling decorated foo with True')
    assert decorated_foo(True)
@end example

运行此脚本时，应看到以下输出：

@example
Calling undecorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling undecorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
about to log at CRITICAL ...
Calling decorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling decorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
Actually logged at DEBUG
Actually logged at INFO
Actually logged at WARNING
Actually logged at ERROR
about to log at CRITICAL ...
Actually logged at CRITICAL
@end example

由上可见，只有发生 ERROR 以上级别的事件时才会实际输出日志，但之前发生的低等级事件还是会被记入日志。

当然采用传统的装饰方法也是可以的：

@example
@@log_if_errors(logger)
def foo(fail=False):
    ...
@end example

@node 通过配置将时间格式化为 UTC（GMT）格式,用上下文管理器选择性记录日志,缓冲日志信息并按条件输出,日志操作手册
@anchor{howto/logging-cookbook formatting-times-using-utc-gmt-via-configuration}@anchor{43de}@anchor{howto/logging-cookbook utc-formatting}@anchor{43df}
@subsection 通过配置将时间格式化为 UTC（GMT）格式


有时需要将时间格式化为 UTC 格式，可以用类似 @cite{UTCFormatter} 的类来完成，如下所示：

@example
import logging
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime
@end example

然后自己的代码中即可采用 @code{UTCFormatter} 了，而不用 @ref{220c,,Formatter} 了。若要通过配置来实现，可以用 @ref{c07,,dictConfig()} API 来完成，以下完整示例中将会演示这种方案：

@example
import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = @{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': @{
        'utc': @{
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        @},
        'local': @{
            'format': '%(asctime)s %(message)s',
        @}
    @},
    'handlers': @{
        'console1': @{
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        @},
        'console2': @{
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        @},
    @},
    'root': @{
        'handlers': ['console1', 'console2'],
   @}
@}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())
@end example

脚本会运行输出类似下面的内容:

@example
2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015
@end example

以上将时间格式化为本地时间和 UTC 两种形式，每种形式对应一个 handler。

@node 用上下文管理器选择性记录日志,命令行日志应用起步,通过配置将时间格式化为 UTC（GMT）格式,日志操作手册
@anchor{howto/logging-cookbook context-manager}@anchor{43e0}@anchor{howto/logging-cookbook using-a-context-manager-for-selective-logging}@anchor{43e1}
@subsection 用上下文管理器选择性记录日志


有时需要临时更改日志配置，并在执行某些操作后还原配置。这时，上下文管理器正是最明显的方案，可以实现日志上下文的保存和恢复。以下是一个上下文管理器的简单示例，只在上下文管理器的作用域内更改日志等级和增加日志 handler：

@example
import logging
import sys

class LoggingContext:
    def __init__(self, logger, level=None, handler=None, close=True):
        self.logger = logger
        self.level = level
        self.handler = handler
        self.close = close

    def __enter__(self):
        if self.level is not None:
            self.old_level = self.logger.level
            self.logger.setLevel(self.level)
        if self.handler:
            self.logger.addHandler(self.handler)

    def __exit__(self, et, ev, tb):
        if self.level is not None:
            self.logger.setLevel(self.old_level)
        if self.handler:
            self.logger.removeHandler(self.handler)
        if self.handler and self.close:
            self.handler.close()
        # implicit return of None => don't swallow exceptions
@end example

如果给出了 level 值，则在上下文管理器 with 语句覆盖的作用域内，日志记录级别将设置为 level 值。如果给出了 handler 值，则在进入作用域时将会将其加入，离开时将会移除。如果后续用不到该 handler 了，则可在离开作用域时让上下文管理器将其关闭。

为了演示上述过程，可加入以下代码：

@example
if __name__ == '__main__':
    logger = logging.getLogger('foo')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.INFO)
    logger.info('1. This should appear just once on stderr.')
    logger.debug('2. This should not appear.')
    with LoggingContext(logger, level=logging.DEBUG):
        logger.debug('3. This should appear once on stderr.')
    logger.debug('4. This should not appear.')
    h = logging.StreamHandler(sys.stdout)
    with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
        logger.debug('5. This should appear twice - once on stderr and once on stdout.')
    logger.info('6. This should appear just once on stderr.')
    logger.debug('7. This should not appear.')
@end example

最开始日志级别设为 @code{INFO}，因此会显示 #1 信息，而 #2 信息则没有出现。接下来的 @code{with} 代码块中，暂时将日志级别变为 @code{DEBUG}，于是 #3 信息出现了。在离开该代码块后，日志记录器的级别恢复为 @code{INFO}，从而 #4 信息没有出现。在下一个 @code{with} 代码块中，再次将日志级别设为 @code{DEBUG}，并且加入一个写入 @code{sys.stdout} 的日志 handler。因此，#5 信息在控制台出现了两次（分别由 @code{stderr} 和 @code{stdout} 显示）。在 @code{with} 语句执行完毕后，状态复原，因此显示了 #6 信息（类似 #1），而 #7 信息没有出现（类似 #2）。

运行结果如下：

@example
$ python logctx.py
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
@end example

但若将 @code{stderr} 重定向到 @code{/dev/null}，再次运行一下，写入 @code{stdout} 的将只有以下信息：

@example
$ python logctx.py 2>/dev/null
5. This should appear twice - once on stderr and once on stdout.
@end example

再把 @code{stdout} 重定向到 @code{/dev/null}，结果将如下所示：

@example
$ python logctx.py >/dev/null
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.
@end example

这符合预期，输出到 @code{stdout} 的 #5 信息不会显示出来。

当然，上述做法可以推广到其他应用，比如临时加入日志过滤器。请注意，上述代码对 Python 2 和 3 均适用。

@node 命令行日志应用起步,用作日志的 Qt GUI 程序,用上下文管理器选择性记录日志,日志操作手册
@anchor{howto/logging-cookbook a-cli-application-starter-template}@anchor{43e2}@anchor{howto/logging-cookbook starter-template}@anchor{43e3}
@subsection 命令行日志应用起步


下面的示例提供了如下功能：


@itemize *

@item 
根据命令行参数确定日志级别

@item 
在单独的文件中分发多条子命令，同一级别的日志子命令均以一致的方式记录。

@item 
最简单的配置用法
@end itemize

假定有一个命令行应用程序，用于停止、启动或重新启动某些服务。为了便于演示，不妨将 @code{app.py} 作为应用程序的主代码文件，并在  @code{start.py}、 @code{stop.py`@w{`}和 `@w{`}restart.py} 中实现单独的命令。再假定要通过命令行参数控制应用程序的日志粒度，默认为 @code{logging.INFO} 。以下是 @code{app.py} 的一个示例：

@example
import argparse
import importlib
import logging
import os
import sys

def main(args=None):
    scriptname = os.path.basename(__file__)
    parser = argparse.ArgumentParser(scriptname)
    levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
    parser.add_argument('--log-level', default='INFO', choices=levels)
    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands:')
    start_cmd = subparsers.add_parser('start', help='Start a service')
    start_cmd.add_argument('name', metavar='NAME',
                           help='Name of service to start')
    stop_cmd = subparsers.add_parser('stop',
                                     help='Stop one or more services')
    stop_cmd.add_argument('names', metavar='NAME', nargs='+',
                          help='Name of service to stop')
    restart_cmd = subparsers.add_parser('restart',
                                        help='Restart one or more services')
    restart_cmd.add_argument('names', metavar='NAME', nargs='+',
                             help='Name of service to restart')
    options = parser.parse_args()
    # the code to dispatch commands could all be in this file. For the purposes
    # of illustration only, we implement each command in a separate module.
    try:
        mod = importlib.import_module(options.command)
        cmd = getattr(mod, 'command')
    except (ImportError, AttributeError):
        print('Unable to find the code for command \'%s\'@w{'} % options.command)
        return 1
    # Could get fancy here and load configuration from file or dictionary
    logging.basicConfig(level=options.log_level,
                        format='%(levelname)s %(name)s %(message)s')
    cmd(options)

if __name__ == '__main__':
    sys.exit(main())
@end example

@code{start}、@code{stop} 和 @code{restart} 命令可以在单独的模块中实现，启动命令的代码可如下：

@example
# start.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    logger.debug('About to start %s', options.name)
    # actually do the command processing here ...
    logger.info('Started the \'%s\' service.', options.name)
@end example

然后是停止命令的代码：

@example
# stop.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = '@w{'}
        services = '\'%s\'@w{'} % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'@w{'} % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to stop %s', services)
    # actually do the command processing here ...
    logger.info('Stopped the %s service%s.', services, plural)
@end example

重启命令类似：

@example
# restart.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = '@w{'}
        services = '\'%s\'@w{'} % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'@w{'} % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to restart %s', services)
    # actually do the command processing here ...
    logger.info('Restarted the %s service%s.', services, plural)
@end example

如果以默认日志级别运行该程序，会得到以下结果：

@example
$ python app.py start foo
INFO start Started the 'foo' service.

$ python app.py stop foo bar
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py restart foo bar baz
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
@end example

第一个单词是日志级别，第二个单词是日志事件所在的模块或包的名称。

如果修改了日志级别，发送给日志的信息就能得以改变。如要显示更多信息，则可：

@example
$ python app.py --log-level DEBUG start foo
DEBUG start About to start foo
INFO start Started the 'foo' service.

$ python app.py --log-level DEBUG stop foo bar
DEBUG stop About to stop 'foo' and 'bar'
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py --log-level DEBUG restart foo bar baz
DEBUG restart About to restart 'foo', 'bar' and 'baz'
INFO restart Restarted the 'foo', 'bar' and 'baz' services.
@end example

若要显示的信息少一些，则：

@example
$ python app.py --log-level WARNING start foo
$ python app.py --log-level WARNING stop foo bar
$ python app.py --log-level WARNING restart foo bar baz
@end example

这里的命令不会向控制台输出任何信息，因为没有记录 @code{WARNING} 以上级别的日志。

@node 用作日志的 Qt GUI 程序,理应避免的用法,命令行日志应用起步,日志操作手册
@anchor{howto/logging-cookbook a-qt-gui-for-logging}@anchor{43e4}@anchor{howto/logging-cookbook qt-gui}@anchor{43e5}
@subsection 用作日志的 Qt GUI 程序


如何将日志写入某个 GUI 应用程序，这是个常见的问题。 Qt@footnote{https://www.qt.io/} 框架是一个流行的跨平台 UI 框架，采用的是 PySide2@footnote{https://pypi.org/project/PySide2/} 或 PyQt5@footnote{https://pypi.org/project/PyQt5/} 库。

下面的例子演示了将日志写入 Qt GUI 程序的过程。这里引入了一个简单的 @code{QtHandler} 类，参数是一个可调用对象，其应为嵌入主线程某个“槽位”中运行的，因为GUI 的更新由主线程完成。这里还创建了一个工作线程，以便演示由 UI（通过人工点击日志按钮）和后台工作线程（此处只是记录级别和时间间隔均随机生成的日志信息）将日志写入 GUI 的过程。

该工作线程是用 Qt 的 @code{QThread} 类实现的，而不是 @ref{10b,,threading} 模块，因为某些情况下只能采用 @code{`QThread}，它与其他 @code{Qt} 组件的集成性更好一些。

以下代码应能适用于最新版的 @code{PySide2} 或 @code{PyQt5}。对于低版本的 Qt 应该也能适用。更多详情，请参阅代码注释。

@example
import datetime
import logging
import random
import sys
import time

# Deal with minor differences between PySide2 and PyQt5
try:
    from PySide2 import QtCore, QtGui, QtWidgets
    Signal = QtCore.Signal
    Slot = QtCore.Slot
except ImportError:
    from PyQt5 import QtCore, QtGui, QtWidgets
    Signal = QtCore.pyqtSignal
    Slot = QtCore.pyqtSlot


logger = logging.getLogger(__name__)


#
# Signals need to be contained in a QObject or subclass in order to be correctly
# initialized.
#
class Signaller(QtCore.QObject):
    signal = Signal(str, logging.LogRecord)

#
# Output to a Qt GUI is only supposed to happen on the main thread. So, this
# handler is designed to take a slot function which is set up to run in the main
# thread. In this example, the function takes a string argument which is a
# formatted log message, and the log record which generated it. The formatted
# string is just a convenience - you could format a string for output any way
# you like in the slot function itself.
#
# You specify the slot function to do whatever GUI updates you want. The handler
# doesn't know or care about specific UI elements.
#
class QtHandler(logging.Handler):
    def __init__(self, slotfunc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.signaller = Signaller()
        self.signaller.signal.connect(slotfunc)

    def emit(self, record):
        s = self.format(record)
        self.signaller.signal.emit(s, record)

#
# This example uses QThreads, which means that the threads at the Python level
# are named something like "Dummy-1". The function below gets the Qt name of the
# current thread.
#
def ctname():
    return QtCore.QThread.currentThread().objectName()


#
# Used to generate random levels for logging.
#
LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
          logging.CRITICAL)

#
# This worker class represents work that is done in a thread separate to the
# main thread. The way the thread is kicked off to do work is via a button press
# that connects to a slot in the worker.
#
# Because the default threadName value in the LogRecord isn't much use, we add
# a qThreadName which contains the QThread name as computed above, and pass that
# value in an "extra" dictionary which is used to update the LogRecord with the
# QThread name.
#
# This example worker just outputs messages sequentially, interspersed with
# random delays of the order of a few seconds.
#
class Worker(QtCore.QObject):
    @@Slot()
    def start(self):
        extra = @{'qThreadName': ctname() @}
        logger.debug('Started work', extra=extra)
        i = 1
        # Let the thread run until interrupted. This allows reasonably clean
        # thread termination.
        while not QtCore.QThread.currentThread().isInterruptionRequested():
            delay = 0.5 + random.random() * 2
            time.sleep(delay)
            level = random.choice(LEVELS)
            logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
            i += 1

#
# Implement a simple UI for this cookbook example. This contains:
#
# * A read-only text edit window which holds formatted log messages
# * A button to start work and log stuff in a separate thread
# * A button to log something from the main thread
# * A button to clear the log window
#
class Window(QtWidgets.QWidget):

    COLORS = @{
        logging.DEBUG: 'black',
        logging.INFO: 'blue',
        logging.WARNING: 'orange',
        logging.ERROR: 'red',
        logging.CRITICAL: 'purple',
    @}

    def __init__(self, app):
        super().__init__()
        self.app = app
        self.textedit = te = QtWidgets.QPlainTextEdit(self)
        # Set whatever the default monospace font is for the platform
        f = QtGui.QFont('nosuchfont')
        f.setStyleHint(f.Monospace)
        te.setFont(f)
        te.setReadOnly(True)
        PB = QtWidgets.QPushButton
        self.work_button = PB('Start background work', self)
        self.log_button = PB('Log a message at a random level', self)
        self.clear_button = PB('Clear log window', self)
        self.handler = h = QtHandler(self.update_status)
        # Remember to use qThreadName rather than threadName in the format string.
        fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'
        formatter = logging.Formatter(fs)
        h.setFormatter(formatter)
        logger.addHandler(h)
        # Set up to terminate the QThread when we exit
        app.aboutToQuit.connect(self.force_quit)

        # Lay out all the widgets
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(te)
        layout.addWidget(self.work_button)
        layout.addWidget(self.log_button)
        layout.addWidget(self.clear_button)
        self.setFixedSize(900, 400)

        # Connect the non-worker slots and signals
        self.log_button.clicked.connect(self.manual_update)
        self.clear_button.clicked.connect(self.clear_display)

        # Start a new worker thread and connect the slots for the worker
        self.start_thread()
        self.work_button.clicked.connect(self.worker.start)
        # Once started, the button should be disabled
        self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False))

    def start_thread(self):
        self.worker = Worker()
        self.worker_thread = QtCore.QThread()
        self.worker.setObjectName('Worker')
        self.worker_thread.setObjectName('WorkerThread')  # for qThreadName
        self.worker.moveToThread(self.worker_thread)
        # This will start an event loop in the worker thread
        self.worker_thread.start()

    def kill_thread(self):
        # Just tell the worker to stop, then tell it to quit and wait for that
        # to happen
        self.worker_thread.requestInterruption()
        if self.worker_thread.isRunning():
            self.worker_thread.quit()
            self.worker_thread.wait()
        else:
            print('worker has already exited.')

    def force_quit(self):
        # For use when the window is closed
        if self.worker_thread.isRunning():
            self.kill_thread()

    # The functions below update the UI and run in the main thread because
    # that's where the slots are set up

    @@Slot(str, logging.LogRecord)
    def update_status(self, status, record):
        color = self.COLORS.get(record.levelno, 'black')
        s = '<pre><font color="%s">%s</font></pre>' % (color, status)
        self.textedit.appendHtml(s)

    @@Slot()
    def manual_update(self):
        # This function uses the formatted message passed in, but also uses
        # information from the record to format the message in an appropriate
        # color according to its severity (level).
        level = random.choice(LEVELS)
        extra = @{'qThreadName': ctname() @}
        logger.log(level, 'Manually logged!', extra=extra)

    @@Slot()
    def clear_display(self):
        self.textedit.clear()


def main():
    QtCore.QThread.currentThread().setObjectName('MainThread')
    logging.getLogger().setLevel(logging.DEBUG)
    app = QtWidgets.QApplication(sys.argv)
    example = Window(app)
    example.show()
    sys.exit(app.exec_())

if __name__=='__main__':
    main()
@end example

@c patterns-to-avoid:

@node 理应避免的用法,,用作日志的 Qt GUI 程序,日志操作手册
@anchor{howto/logging-cookbook patterns-to-avoid}@anchor{43e6}
@subsection 理应避免的用法


前几节虽介绍了几种方案，描述了可能需要处理的操作，但值得一提的是，有些用法是 @emph{没有好处} 的，大多数情况下应该避免使用。下面几节的顺序不分先后。

@menu
* 多次打开同一个日志文件:: 
* 将日志对象用作属性或传递参数:: 
* 给日志库代码添加 NullHandler 之外的其他 handler:: 
* 创建大量的日志对象:: 

@end menu

@node 多次打开同一个日志文件,将日志对象用作属性或传递参数,,理应避免的用法
@anchor{howto/logging-cookbook opening-the-same-log-file-multiple-times}@anchor{43e7}
@subsubsection 多次打开同一个日志文件


因会导致 "文件被其他进程占用 "错误，所以在 Windows 中一般无法多次打开同一个文件。但在 POSIX 平台中，多次打开同一个文件不会报任何错误。这种操作可能是意外发生的，比如：


@itemize *

@item 
多次添加指向同一文件的 handler（比如通过复制/粘贴，或忘记修改）。

@item 
打开两个貌似不同（文件名不一样）的文件，但一个是另一个的符号链接，所以其实是同一个文件。

@item 
进程 fork，然后父进程和子进程都有对同一文件的引用。 例如，这可能是通过使用 @ref{b7,,multiprocessing} 模块实现的。
@end itemize

在大多数情况下，多次打开同一个文件 @emph{貌似} 一切正常，但实际会导致很多问题。


@itemize *

@item 
由于多个线程或进程会尝试写入同一个文件，日志输出可能会出现乱码。尽管日志对象可以防止多个线程同时使用同一个 handler 实例，但如果两个不同的线程使用不同的 handler 实例同时写入文件，而这两个 handler 又恰好指向同一个文件，那么就失去了这种防护。

@item 
删除文件（例如在轮换日志文件时）会静默失败，因为有另一个引用指向这个文件。这可能导致混乱并浪费调试时间——日志项最后会出现在意想不到的地方，或者干脆丢失。
@end itemize

请用 @ref{43c1,,在单个文件中记录多个进程的日志} 中介绍的技术来避免上述问题。

@node 将日志对象用作属性或传递参数,给日志库代码添加 NullHandler 之外的其他 handler,多次打开同一个日志文件,理应避免的用法
@anchor{howto/logging-cookbook using-loggers-as-attributes-in-a-class-or-passing-them-as-parameters}@anchor{43e8}
@subsubsection 将日志对象用作属性或传递参数


虽然特殊情况下可能有必要如此，但一般来说没有意义，因为日志是单实例对象。代码总是可以通过 @code{logging.getLogger(name)} 用名称访问一个已有的日志对象实例，因此将实例作为参数来传递，或作为属性留存，都是毫无意义的。请注意，在其他语言中，如 Java 和 C#，日志对象通常是静态类属性。但在 Python 中是没有意义的，因为软件拆分的单位是模块（而不是类）。

@node 给日志库代码添加 NullHandler 之外的其他 handler,创建大量的日志对象,将日志对象用作属性或传递参数,理应避免的用法
@anchor{howto/logging-cookbook adding-handlers-other-than-nullhandler-to-a-logger-in-a-library}@anchor{43e9}
@subsubsection 给日志库代码添加 @code{NullHandler} 之外的其他 handler


通过添加 handler、formatter 和 filter 来配置日志，这是应用程序开发人员的责任，而不是库开发人员该做的。如果正在维护一个库，请确保不要向任何日志对象添加 @ref{cee,,NullHandler} 实例以外的 handler。

@node 创建大量的日志对象,,给日志库代码添加 NullHandler 之外的其他 handler,理应避免的用法
@anchor{howto/logging-cookbook creating-a-lot-of-loggers}@anchor{43ea}
@subsubsection 创建大量的日志对象


日志是单实例对象，在代码执行过程中不会被释放，因此创建大量的日志对象会占用很多内存，而这些内存又不能被释放。与其为每个文件或网络连接创建一个日志，还不如利用 @ref{2246,,已有机制} 将上下文信息传给自定义日志对象，并将创建的日志对象限制在应用程序内的指定区域（通常是模块，但偶尔会再精细些）使用。

@node 正则表达式HOWTO,套接字编程指南,日志操作手册,Python 常用指引
@anchor{howto/regex doc}@anchor{43eb}@anchor{howto/regex regex-howto}@anchor{18e2}@anchor{howto/regex regular-expression-howto}@anchor{43ec}
@section 正则表达式HOWTO


@*作者: 
A.M. Kuchling <@email{amk@@amk.ca}>


@c TODO:
@c Document lookbehind assertions
@c Better way of displaying a RE, a string, and what it matches
@c Mention optional argument to match.groups()
@c Unicode (at least a reference)

@subsubheading 摘要



本文档是在Python中使用 @ref{dd,,re} 模块使用正则表达式的入门教程。 它提供了比“标准库参考”中相应部分更平和的介绍。

@menu
* 概述: 概述<18>. 
* 简单模式:: 
* 使用正则表达式:: 
* 更多模式能力:: 
* 修改字符串:: 
* 常见问题:: 
* 反馈:: 

@end menu

@node 概述<18>,简单模式,,正则表达式HOWTO
@anchor{howto/regex introduction}@anchor{43ed}
@subsection 概述


正则表达式（称为RE，或正则，或正则表达式模式）本质上是嵌入在Python中的一种微小的、高度专业化的编程语言，可通过 @ref{dd,,re} 模块获得。 使用这种小语言，你可以为要匹配的可能字符串集指定规则；此集可能包含英语句子，电子邮件地址，TeX命令或你喜欢的任何内容。 然后，您可以询问诸如“此字符串是否与模式匹配？”或“此字符串中的模式是否匹配？”等问题。 你还可以使用正则修改字符串或以各种方式将其拆分。

正则表达式模式被编译成一系列字节码，然后由用 C 编写的匹配引擎执行。对于高级用途，可能需要特别注意引擎如何执行给定的正则，并将正则写入以某种方式生成运行速度更快的字节码。 本文档未涉及优化，因为它要求你充分了解匹配引擎的内部结构。

正则表达式语言相对较小且受限制，因此并非所有可能的字符串处理任务都可以使用正则表达式完成。 还有一些任务 @emph{可以} 用正则表达式完成，但表达式变得非常复杂。 在这些情况下，你最好编写 Python 代码来进行处理；虽然 Python 代码比精心设计的正则表达式慢，但它也可能更容易理解。

@node 简单模式,使用正则表达式,概述<18>,正则表达式HOWTO
@anchor{howto/regex simple-patterns}@anchor{43ee}
@subsection 简单模式


我们首先要了解最简单的正则表达式。 由于正则表达式用于对字符串进行操作，因此我们将从最常见的任务开始：匹配字符。

有关正则表达式（确定性和非确定性有限自动机）的计算机科学的详细解释，你可以参考几乎所有有关编写编译器的教科书。

@menu
* 匹配字符:: 
* 重复:: 

@end menu

@node 匹配字符,重复,,简单模式
@anchor{howto/regex matching-characters}@anchor{43ef}
@subsubsection 匹配字符


大多数字母和字符只会匹配自己。 例如，正则表达式 @code{test} 将完全匹配字符串 @code{test} 。 （你可以启用一个不区分大小写的模式，让这个正则匹配 @code{Test} 或 @code{TEST}，稍后会详细介绍。）

这条规则有例外；一些字符是特殊的 @emph{metacharacters} ，并且不匹配自己。 相反，它们表示应该匹配一些与众不同的东西，或者通过重复它们或改变它们的含义来影响正则的其他部分。 本文档的大部分内容都致力于讨论各种元字符及其功能。

这是元字符的完整列表；它们的意思将在本HOWTO的其余部分讨论。

@example
. ^ $ * + ? @{ @} [ ] \ | ( )
@end example

我们将看到的第一个元字符是 @code{[} 和 @code{]} 。 它们用于指定字符类，它是你希望匹配的一组字符。 可以单独列出字符，也可以通过给出两个字符并用 @code{'-'} 标记将它们分开来表示一系列字符。 例如， @code{[abc]} 将匹配任何字符 @code{a}、 @code{b} 或 @code{c} ；这与 @code{[a-c]} 相同，它使用一个范围来表示同一组字符。 如果你只想匹配小写字母，你的正则是 @code{[a-z]} 。

元字符（除了 @code{\}）在字符类中是不起作用的。 例如，@code{[akm$]} 将会匹配以下任一字符 @code{'a'}, @code{'k'}, @code{'m'} 或 @cite{$} 。@cite{$} 通常是一个元字符，但在一个字符类中它的特殊性被消除了。

你可以通过以下方式匹配 @emph{complementing} 设置的字符类中未列出的字符。这通过包含一个 @code{'^'} 作为该类的第一个字符来表示。 例如，@code{[^5]} 将匹配除 @code{'5'} 之外的任何字符。 如果插入符出现在字符类的其他位置，则它没有特殊含义。 例如：@code{[5^]} 将匹配 @code{'5'} 或 @code{'^'}。

也许最重要的元字符是反斜杠，@code{\}。 与 Python 字符串文字一样，反斜杠后面可以跟各种字符，以指示各种特殊序列。它也用于转义所有元字符，因此您仍然可以在模式中匹配它们；例如，如果你需要匹配 @code{[} 或 @code{\}，你可以在它们前面加一个反斜杠来移除它们的特殊含义：@code{\[} 或 @code{\\}。

一些以 @code{'\'} 开头的特殊序列表示通常有用的预定义字符集，例如数字集、字母集或任何非空格的集合。

让我们举一个例子：@code{\w} 匹配任何字母数字字符。 如果正则表达式模式以字节类表示，这相当于类 @code{[a-zA-Z0-9_]}。如果正则表达式是一个字符串，@code{\w} 将匹配由 @ref{123,,unicodedata} 模块提供的 Unicode 数据库中标记为字母的所有字符。 通过在编译正则表达式时提供 @ref{4d7,,re.ASCII} 标志，可以在字符串模式中使用更为受限制的 @code{\w} 定义。

以下特殊序列列表不完整。 有关 Unicode 字符串模式的序列和扩展类定义的完整列表，请参阅标准库参考中的最后一部分 @ref{18df,,正则表达式语法} 。通常，Unicode 版本匹配 Unicode 数据库中相应类别中的任何字符。


@table @asis

@item @code{\d}

匹配任何十进制数字；这等价于类 @code{[0-9]}。

@item @code{\D}

匹配任何非数字字符；这等价于类 @code{[^0-9]}。

@item @code{\s}

匹配任何空白字符；这等价于类 @code{[ \t\n\r\f\v]}。

@item @code{\S}

匹配任何非空白字符；这相当于类 @code{[^ \t\n\r\f\v]}。

@item @code{\w}

匹配任何字母与数字字符；这相当于类 @code{[a-zA-Z0-9_]}。

@item @code{\W}

匹配任何非字母与数字字符；这相当于类 @code{[^a-zA-Z0-9_]}。
@end table

这些序列可以包含在字符类中。 例如，@code{[\s,.]} 是一个匹配任何空格字符的字符类或者 @code{','} ，或 @code{'.'}。

本节的最后一个元字符是 @code{.} 。 它匹配除换行符之外的任何内容，并且有一个可选模式（ @ref{18e3,,re.DOTALL} ）甚至可以匹配换行符。 @code{.} 常用于你想匹配“任何字符”的地方。

@node 重复,,匹配字符,简单模式
@anchor{howto/regex repeating-things}@anchor{43f0}
@subsubsection 重复


能够匹配不同的字符集合是正则表达式可以做的第一件事，这对于字符串可用方法来说是不可能的。 但是，如果这是正则表达式的唯一额外功能，那么它们就不会有太大的优势。 另一个功能是你可以指定正则的某些部分必须重复一定次数。

重复中我们要了解的第一个元字符是 @code{*}。 @code{*} 与字面字符 @code{'*'} 不匹配；相反，它指定前一个字符可以匹配零次或多次，而不是恰好一次。

例如，@code{ca*t} 将匹配 @code{'ct'} (0个 @code{'a'} 字符)，@code{'cat'} (1个 @code{'a'} )， @code{'caaat'} (3个 @code{'a'} 字符)，等等。

类似 @code{*} 这样的重复是 @emph{贪婪的}；当重复正则时，匹配引擎将尝试尽可能多地重复它。 如果模式的后续部分不匹配，则匹配引擎将回退并以较少的重复次数再次尝试。

一个逐步的例子将使这更加明显。 让我们考虑表达式 @code{a[bcd]*b}。 这个正则匹配字母 @code{'a'}，类 @code{[bcd]} 中的零或多个字母，最后以 @code{'b'} 结尾。 现在想象一下这个正则与字符串 @code{'abcbd'} 匹配。


@multitable {xxxxxxxx} {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

步骤

@tab

匹配

@tab

解释

@item

1

@tab

@code{a}

@tab

正则中的 @code{a} 匹配。

@item

2

@tab

@code{abcbd}

@tab

引擎尽可能多地匹配 @code{[bcd]*} ，直到字符串结束。

@item

3

@tab

@emph{失败}

@tab

引擎尝试匹配 @code{b} ，但是当前位置位于字符串结束，所以匹配失败。

@item

4

@tab

@code{abcb}

@tab

回退一次，@code{[bcd]*} 少匹配一个字符。

@item

5

@tab

@emph{失败}

@tab

再次尝试匹配 @code{b} ， 但是当前位置是最后一个字符 @code{'d'} 。

@item

6

@tab

@code{abc}

@tab

再次回退，所以 @code{[bcd]*} 只匹配 @code{bc} 。

@item

6

@tab

@code{abcb}

@tab

再试一次 @code{b} 。 这次当前位置的字符是 @code{'b'} ，所以它成功了。

@end multitable


正则现在已经结束了，它已经匹配了 @code{'abcb'}。 这演示了匹配引擎最初如何进行，如果没有找到匹配，它将逐步回退并一次又一次地重试正则的其余部分。 它将回退，直到它为 @code{[bcd]*} 尝试零匹配，如果随后失败，引擎将断定该字符串与正则完全不匹配。

另一个重复的元字符是 @code{+}，它匹配一次或多次。 要特别注意 @code{*} 和 @code{+} 之间的区别；@code{*} 匹配 @emph{零次} 或更多次，因此重复的任何东西都可能根本不存在，而 @code{+} 至少需要 @emph{一次}。 使用类似的例子，@code{ca+t} 将匹配 @code{'cat'} (1 个 @code{'a'})，@code{'caaat'} (3 个 @code{'a'})，但不会匹配 @code{'ct'}。

还有两个重复限定符。 问号字符 @code{?} 匹配一次或零次；你可以把它想象成是可选的。 例如，@code{home-?brew} 匹配 @code{'homebrew'} 或 @code{'home-brew'}。

最复杂的重复限定符是 @code{@{m,n@}}，其中 @emph{m} 和 @emph{n} 是十进制整数。 这个限定符意味着必须至少重复 @emph{m} 次，最多重复 @emph{n} 次。 例如，@code{a/@{1,3@}b} 将匹配 @code{'a/b'} ，@code{'a//b'} 和 @code{'a///b'} 。 它不匹配没有斜线的 @code{'ab'}，或者有四个的 @code{'a////b'}。

你可以省略 @emph{m} 或 @emph{n}; 在这种情况下，将假定缺失值的合理值。 省略 @emph{m} 被解释为 0 下限，而省略 @emph{n} 则为无穷大的上限。

还原论者的读者可能会注意到其他三个限定符都可以用这种表示法表达。 @code{@{0,@}} 与 @code{*} 相同， @code{@{1,@}} 相当于 @code{+} ， @code{@{0,1@}} 和 @code{?} 相同。 最好使用 @code{*} ， @code{+} 或 @code{?} ，只要因为它们更短更容易阅读。

@node 使用正则表达式,更多模式能力,简单模式,正则表达式HOWTO
@anchor{howto/regex using-regular-expressions}@anchor{43f1}
@subsection 使用正则表达式


现在我们已经看了一些简单的正则表达式，我们如何在 Python 中实际使用它们？ @ref{dd,,re} 模块提供了正则表达式引擎的接口，允许你将正则编译为对象，然后用它们进行匹配。

@menu
* 编译正则表达式:: 
* 反斜杠灾难:: 
* 应用匹配:: 
* 模块级别函数:: 
* 编译标志:: 

@end menu

@node 编译正则表达式,反斜杠灾难,,使用正则表达式
@anchor{howto/regex compiling-regular-expressions}@anchor{43f2}
@subsubsection 编译正则表达式


正则表达式被编译成模式对象，模式对象具有各种操作的方法，例如搜索模式匹配或执行字符串替换。:

@example
>>> import re
>>> p = re.compile('ab*')
>>> p
re.compile('ab*')
@end example

@ref{555,,re.compile()} 也接受一个可选的 @emph{flags} 参数，用于启用各种特殊功能和语法变体。 我们稍后将介绍可用的设置，但现在只需一个例子

@example
>>> p = re.compile('ab*', re.IGNORECASE)
@end example

正则作为字符串传递给 @ref{555,,re.compile()} 。 正则被处理为字符串，因为正则表达式不是核心Python语言的一部分，并且没有创建用于表达它们的特殊语法。 （有些应用程序根本不需要正则，因此不需要通过包含它们来扩展语言规范。）相反，@ref{dd,,re} 模块只是Python附带的C扩展模块，就类似于 @ref{ef,,socket} 或 @ref{14d,,zlib} 模块。

将正则放在字符串中可以使 Python 语言更简单，但有一个缺点是下一节的主题。

@node 反斜杠灾难,应用匹配,编译正则表达式,使用正则表达式
@anchor{howto/regex id1}@anchor{43f3}@anchor{howto/regex the-backslash-plague}@anchor{43f4}
@subsubsection 反斜杠灾难


如前所述，正则表达式使用反斜杠字符 (@code{'\'}) 来表示特殊形式或允许使用特殊字符而不调用它们的特殊含义。 这与 Python 在字符串文字中用于相同目的的相同字符的使用相冲突。

假设你想要编写一个与字符串 @code{\section} 相匹配的正则，它可以在 LaTeX 文件中找到。 要找出在程序代码中写入的内容，请从要匹配的字符串开始。 接下来，您必须通过在反斜杠前面添加反斜杠和其他元字符，从而产生字符串 @code{\\section}。 必须传递给 @ref{555,,re.compile()} 的结果字符串必须是 @code{\\section}。 但是，要将其表示为 Python 字符串文字，必须 @emph{再次} 转义两个反斜杠。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

字符

@tab

阶段

@item

@code{\section}

@tab

被匹配的字符串

@item

@code{\\section}

@tab

为 @ref{555,,re.compile()} 转义的反斜杠

@item

@code{"\\\\section"}

@tab

为字符串字面转义的反斜杠

@end multitable


简而言之，要匹配文字反斜杠，必须将 @code{'\\\\'} 写为正则字符串，因为正则表达式必须是 @code{\\}，并且每个反斜杠必须表示为 @code{\\} 在常规Python字符串字面中。 在反复使用反斜杠的正则中，这会导致大量重复的反斜杠，并使得生成的字符串难以理解。

解决方案是使用 Python 的原始字符串表示法来表示正则表达式；反斜杠不以任何特殊的方式处理前缀为 @code{'r'} 的字符串字面，因此 @code{r"\n"} 是一个包含 @code{'\'} 和 @code{'n'} 的双字符字符串，而 @code{"\n"} 是一个包含换行符的单字符字符串。 正则表达式通常使用这种原始字符串表示法用 Python 代码编写。

此外，在正则表达式中有效但在 Python 字符串文字中无效的特殊转义序列现在导致 @ref{15a,,DeprecationWarning} 并最终变为 @ref{562,,SyntaxError}。 这意味着如果未使用原始字符串表示法或转义反斜杠，序列将无效。


@multitable {xxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxx} 
@headitem

常规字符串

@tab

原始字符串

@item

@code{"ab*"}

@tab

@code{r"ab*"}

@item

@code{"\\\\section"}

@tab

@code{r"\\section"}

@item

@code{"\\w+\\s+\\1"}

@tab

@code{r"\w+\s+\1"}

@end multitable


@node 应用匹配,模块级别函数,反斜杠灾难,使用正则表达式
@anchor{howto/regex performing-matches}@anchor{43f5}
@subsubsection 应用匹配


一旦你有一个表示编译正则表达式的对象，你用它做什么？ 模式对象有几种方法和属性。 这里只介绍最重要的内容；请参阅 @ref{dd,,re} 文档获取完整列表。


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

方法 / 属性

@tab

目的

@item

@code{match()}

@tab

确定正则是否从字符串的开头匹配。

@item

@code{search()}

@tab

扫描字符串，查找此正则匹配的任何位置。

@item

@code{findall()}

@tab

找到正则匹配的所有子字符串，并将它们作为列表返回。

@item

@code{finditer()}

@tab

找到正则匹配的所有子字符串，并将它们返回为一个 @ref{11ba,,iterator}。

@end multitable


如果没有找到匹配， @ref{18ee,,match()} 和 @ref{18ef,,search()} 返回 @code{None} 。如果它们成功， 一个 @ref{98d,,匹配对象} 实例将被返回，包含匹配相关的信息：起始和终结位置、匹配的子串以及其它。

你可以通过交互式实验 @ref{dd,,re} 模块来了解这一点。 如果你有 @ref{10e,,tkinter}，你可能还想查看 Tools/demo/redemo.py@footnote{https://github.com/python/cpython/tree/3.9/Tools/demo/redemo.py}，这是 Python 发行附带的演示程序。 它允许你输入正则和字符串，并显示RE是匹配还是失败。  @code{redemo.py} 在尝试调试复杂的正则时非常有用。

本 HOWTO 使用标准 Python 解释器作为示例。 首先，运行 Python 解释器，导入 @ref{dd,,re} 模块，然后编译一个正则

@example
>>> import re
>>> p = re.compile('[a-z]+')
>>> p
re.compile('[a-z]+')
@end example

现在，你可以尝试匹配正则 @code{[a-z]+} 的各种字符串。 空字符串根本不匹配，因为 @code{+} 表示“一次或多次重复”。 @ref{18ee,,match()} 在这种情况下应返回 @code{None}，这将导致解释器不打印输出。 你可以显式打印 @code{match()} 的结果，使其清晰。:

@example
>>> p.match("")
>>> print(p.match(""))
None
@end example

现在，让我们尝试一下它应该匹配的字符串，例如 @code{tempo}。在这个例子中 @ref{18ee,,match()} 将返回一个 @ref{98d,,匹配对象}，因此你应该将结果储存到一个变量中以供稍后使用。

@example
>>> m = p.match('tempo')
>>> m
<re.Match object; span=(0, 5), match='tempo'>
@end example

现在你可以检查 @ref{98d,,匹配对象} 以获取有关匹配字符串的信息。 匹配对象实例也有几个方法和属性；最重要的是：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

方法 / 属性

@tab

目的

@item

@code{group()}

@tab

返回正则匹配的字符串

@item

@code{start()}

@tab

返回匹配的开始位置

@item

@code{end()}

@tab

返回匹配的结束位置

@item

@code{span()}

@tab

返回包含匹配 (start, end) 位置的元组

@end multitable


尝试这些方法很快就会清楚它们的含义:

@example
>>> m.group()
'tempo'
>>> m.start(), m.end()
(0, 5)
>>> m.span()
(0, 5)
@end example

@ref{1902,,group()} 返回正则匹配的子字符串。 @ref{1906,,start()} 和 @ref{1907,,end()} 返回匹配的起始和结束索引。 @ref{1908,,span()} 在单个元组中返回开始和结束索引。 由于 @ref{18ee,,match()} 方法只检查正则是否在字符串的开头匹配，所以 @code{start()} 将始终为零。 但是，模式的 @ref{18ef,,search()} 方法会扫描字符串，因此在这种情况下匹配可能不会从零开始。:

@example
>>> print(p.match('::: message'))
None
>>> m = p.search('::: message'); print(m)
<re.Match object; span=(4, 11), match='message'>
>>> m.group()
'message'
>>> m.span()
(4, 11)
@end example

在实际程序中，最常见的样式是在变量中存储 @ref{98d,,匹配对象}，然后检查它是否为 @code{None}。 这通常看起来像:

@example
p = re.compile( ... )
m = p.match( 'string goes here' )
if m:
    print('Match found: ', m.group())
else:
    print('No match')
@end example

两种模式方法返回模式的所有匹配项。 @ref{18f8,,findall()} 返回匹配字符串的列表:

@example
>>> p = re.compile(r'\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']
@end example

在这个例子中需要 @code{r} 前缀，使字面为原始字符串字面，因为普通的“加工”字符串字面中的转义序列不能被 Python 识别为正则表达式，导致 @ref{15a,,DeprecationWarning} 并最终产生 @ref{562,,SyntaxError}。 请参阅 @ref{43f4,,反斜杠灾难}。

@ref{18f8,,findall()} 必须先创建整个列表才能返回结果。 @ref{18f9,,finditer()} 方法将一个 @ref{98d,,匹配对象} 的序列返回为一个 @ref{11ba,,iterator}

@example
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator  
<callable_iterator object at 0x...>
>>> for match in iterator:
...     print(match.span())
...
(0, 2)
(22, 24)
(29, 31)
@end example

@node 模块级别函数,编译标志,应用匹配,使用正则表达式
@anchor{howto/regex module-level-functions}@anchor{43f6}
@subsubsection 模块级别函数


你不必创建模式对象并调用其方法；@ref{dd,,re} 模块还提供了顶级函数 @ref{c8b,,match()}，@ref{c8a,,search()}，@ref{a4d,,findall()}，@ref{582,,sub()} 等等。 这些函数采用与相应模式方法相同的参数，并将正则字符串作为第一个参数添加，并仍然返回 @code{None} 或  @ref{98d,,匹配对象} 实例。:

@example
>>> print(re.match(r'From\s+', 'Fromage amk'))
None
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')  
<re.Match object; span=(0, 5), match='From '>
@end example

本质上，这些函数只是为你创建一个模式对象，并在其上调用适当的方法。 它们还将编译对象存储在缓存中，因此使用相同的未来调用将不需要一次又一次地解析该模式。

你是否应该使用这些模块级函数，还是应该自己获取模式并调用其方法？ 如果你正在循环中访问正则表达式，预编译它将节省一些函数调用。 在循环之外，由于有内部缓存，没有太大区别。

@node 编译标志,,模块级别函数,使用正则表达式
@anchor{howto/regex compilation-flags}@anchor{43f7}
@subsubsection 编译标志


编译标志允许你修改正则表达式的工作方式。 标志在 @ref{dd,,re} 模块中有两个名称，长名称如 @code{IGNORECASE} 和一个简短的单字母形式，例如 @code{I}。 （如果你熟悉 Perl 的模式修饰符，则单字母形式使用和其相同的字母；例如， @ref{18f2,,re.VERBOSE} 的缩写形式为 @ref{18ea,,re.X}。）多个标志可以 通过按位或运算来指定它们；例如，@code{re.I | re.M} 设置 @code{I} 和 @code{M} 标志。

这是一个可用标志表，以及每个标志的更详细说明。


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

标志

@tab

意义

@item

@code{ASCII}, @code{A}

@tab

使几个转义如 @code{\w}、@code{\b}、@code{\s} 和 @code{\d} 匹配仅与具有相应特征属性的 ASCII 字符匹配。

@item

@code{DOTALL}, @code{S}

@tab

使 @code{.} 匹配任何字符，包括换行符。

@item

@code{IGNORECASE}, @code{I}

@tab

进行大小写不敏感匹配。

@item

@code{LOCALE}, @code{L}

@tab

进行区域设置感知匹配。

@item

@code{MULTILINE}, @code{M}

@tab

多行匹配，影响 @code{^} 和 @code{$}。

@item

@code{VERBOSE}, @code{X} （为 '扩展'）

@tab

启用详细的正则，可以更清晰，更容易理解。

@end multitable



@deffn {数据} I

@deffnx {数据} IGNORECASE

执行不区分大小写的匹配；字符类和字面字符串将通过忽略大小写来匹配字母。 例如，@code{[A-Z]} 也匹配小写字母。 除非使用 @code{ASCII} 标志来禁用非ASCII匹配，否则完全 Unicode 匹配也有效。 当 Unicode 模式 @code{[a-z]} 或 @code{[A-Z]} 与 @code{IGNORECASE} 标志结合使用时，它们将匹配 52 个 ASCII 字母和 4 个额外的非 ASCII 字母：'İ' (U+0130，拉丁大写字母 I，带上面的点)，'ı' (U+0131，拉丁文小写字母无点 i)，'s' (U+017F，拉丁文小写字母长 s) 和'K' (U+212A，开尔文符号)。 @code{Spam} 将匹配 @code{'Spam'}，@code{'spam'}，@code{'spAM'} 或 @code{'ſpam'} (后者仅在 Unicode 模式下匹配)。 此小写不考虑当前区域设置；如果你还设置了 @code{LOCALE} 标志，则将考虑。
@end deffn


@deffn {数据} L

@deffnx {数据} LOCALE

使 @code{\w}、@code{\W}、@code{\b}、@code{\B} 和大小写敏感匹配依赖于当前区域而不是 Unicode 数据库。

区域设置是 C 库的一个功能，旨在帮助编写考虑到语言差异的程序。例如，如果你正在处理编码的法语文本，那么你希望能够编写 @code{\w+} 来匹配单词，但 @code{\w} 只匹配字符类 @code{[A-Za-z]} 字节模式；它不会匹配对应于 @code{é} 或 @code{ç} 的字节。如果你的系统配置正确并且选择了法语区域设置，某些C函数将告诉程序对应于 @code{é} 的字节也应该被视为字母。在编译正则表达式时设置 @code{LOCALE} 标志将导致生成的编译对象将这些C函数用于 @code{\w}；这比较慢，但也可以使 @code{\w+} 匹配你所期望的法语单词。在 Python 3 中不鼓励使用此标志，因为语言环境机制非常不可靠，它一次只处理一个“文化”，它只适用于 8 位语言环境。默认情况下，Python 3 中已经为 Unicode（str）模式启用了 Unicode 匹配，并且它能够处理不同的区域/语言。
@end deffn


@deffn {数据} M

@deffnx {数据} MULTILINE

(@code{^} 和 @code{$} 还没有解释；它们将在以下部分介绍 @ref{43f8,,更多元字符}。)

通常 @code{^} 只匹配字符串的开头，而 @code{$} 只匹配字符串的结尾，紧接在字符串末尾的换行符（如果有的话）之前。 当指定了这个标志时，@code{^} 匹配字符串的开头和字符串中每一行的开头，紧跟在每个换行符之后。 类似地，@code{$} 元字符匹配字符串的结尾和每行的结尾（紧接在每个换行符之前）。
@end deffn


@deffn {数据} S

@deffnx {数据} DOTALL

使 @code{'.'} 特殊字符匹配任何字符，包括换行符；没有这个标志，@code{'.'} 将匹配任何字符 @emph{除了} 换行符。
@end deffn


@deffn {数据} A

@deffnx {数据} ASCII

使 @code{\w}、@code{\W}、@code{\b}、@code{\B}、@code{\s} 和 @code{\S} 执行仅 ASCII 匹配而不是完整匹配 Unicode 匹配。 这仅对 Unicode 模式有意义，并且对于字节模式将被忽略。
@end deffn


@deffn {数据} X

@deffnx {数据} VERBOSE

此标志允许你编写更易读的正则表达式，方法是为您提供更灵活的格式化方式。 指定此标志后，将忽略正则字符串中的空格，除非空格位于字符类中或前面带有未转义的反斜杠；这使你可以更清楚地组织和缩进正则。 此标志还允许你将注释放在正则中，引擎将忽略该注释；注释标记为 @code{'#'} 既不是在字符类中，也不是在未转义的反斜杠之前。

例如，这里的正则使用 @ref{18f2,,re.VERBOSE}；看看阅读有多容易？:

@example
charref = re.compile(r"""
 &[#]                # Start of a numeric entity reference
 (
     0[0-7]+         # Octal form
   | [0-9]+          # Decimal form
   | x[0-9a-fA-F]+   # Hexadecimal form
 )
 ;                   # Trailing semicolon
""", re.VERBOSE)
@end example

如果没有详细设置，正则将如下所示:

@example
charref = re.compile("&#(0[0-7]+"
                     "|[0-9]+"
                     "|x[0-9a-fA-F]+);")
@end example

在上面的例子中，Python的字符串文字的自动连接已被用于将正则分解为更小的部分，但它仍然比以下使用 @ref{18f2,,re.VERBOSE} 版本更难理解。
@end deffn

@node 更多模式能力,修改字符串,使用正则表达式,正则表达式HOWTO
@anchor{howto/regex more-pattern-power}@anchor{43f9}
@subsection 更多模式能力


到目前为止，我们只介绍了正则表达式的一部分功能。 在本节中，我们将介绍一些新的元字符，以及如何使用组来检索匹配的文本部分。

@menu
* 更多元字符:: 
* 分组:: 
* 非捕获和命名组:: 
* 前向断言:: 

@end menu

@node 更多元字符,分组,,更多模式能力
@anchor{howto/regex id2}@anchor{43fa}@anchor{howto/regex more-metacharacters}@anchor{43f8}
@subsubsection 更多元字符


我们还没有涉及到一些元字符。 其中大部分内容将在本节中介绍。

要讨论的其余一些元字符是 @emph{零宽度断言} 。 它们不会使解析引擎在字符串中前进一个字符；相反，它们根本不占用任何字符，只是成功或失败。例如，@code{\b} 是一个断言，指明当前位置位于字边界；这个位置根本不会被 @code{\b} 改变。这意味着永远不应重复零宽度断言，因为如果它们在给定位置匹配一次，它们显然可以无限次匹配。


@table @asis

@item @code{|}

或者“or”运算符。 如果 @emph{A} 和 @emph{B} 是正则表达式，@code{A|B} 将匹配任何与 @emph{A} 或 @emph{B} 匹配的字符串。 @code{|} 具有非常低的优先级，以便在交替使用多字符字符串时使其合理地工作。 @code{Crow|Servo} 将匹配 @code{'Crow'} 或 @code{'Servo'}，而不是 @code{'Cro'}、@code{'w'} 或 @code{'S'} 和 @code{'ervo'}。

要匹配字面 @code{'|'}，请使用 @code{\|}，或将其括在字符类中，如 @code{[|]}。

@item @code{^}

在行的开头匹配。 除非设置了 @code{MULTILINE} 标志，否则只会在字符串的开头匹配。 在 @code{MULTILINE} 模式下，这也在字符串中的每个换行符后立即匹配。

例如，如果你希望仅在行的开头匹配单词 @code{From}，则要使用的正则 @code{^From}。:

@example
>>> print(re.search('^From', 'From Here to Eternity'))  
<re.Match object; span=(0, 4), match='From'>
>>> print(re.search('^From', 'Reciting From Memory'))
None
@end example

要匹配字面 @code{'^'}，使用 @code{\^}。

@item @code{$}

匹配行的末尾，定义为字符串的结尾，或者后跟换行符的任何位置。:

@example
>>> print(re.search('@}$', '@{block@}'))  
<re.Match object; span=(6, 7), match='@}'>
>>> print(re.search('@}$', '@{block@} '))
None
>>> print(re.search('@}$', '@{block@}\n'))  
<re.Match object; span=(6, 7), match='@}'>
@end example

以匹配字面 @code{'$'}，使用 @code{\$} 或者将其包裹在一个字符类中，例如 @code{[$]}。

@item @code{\A}

仅匹配字符串的开头。 当不在 @code{MULTILINE} 模式时，@code{\A} 和 @code{^} 实际上是相同的。 在 @code{MULTILINE} 模式中，它们是不同的: @code{\A} 仍然只在字符串的开头匹配，但 @code{^} 可以匹配在换行符之后的字符串内的任何位置。

@item @code{\Z}

只匹配字符串尾。

@item @code{\b}

字边界。 这是一个零宽度断言，仅在单词的开头或结尾处匹配。 单词被定义为一个字母数字字符序列，因此单词的结尾由空格或非字母数字字符表示。

以下示例仅当它是一个完整的单词时匹配 @code{class}；当它包含在另一个单词中时将不会匹配。

@example
>>> p = re.compile(r'\bclass\b')
>>> print(p.search('no class at all'))
<re.Match object; span=(3, 8), match='class'>
>>> print(p.search('the declassified algorithm'))
None
>>> print(p.search('one subclass is'))
None
@end example

使用这个特殊序列时，你应该记住两个细微之处。 首先，这是 Python 的字符串文字和正则表达式序列之间最严重的冲突。 在 Python 的字符串文字中，@code{\b} 是退格字符，ASCII 值为8。 如果你没有使用原始字符串，那么 Python 会将 @code{\b} 转换为退格，你的正则不会按照你的预期匹配。 以下示例与我们之前的正则看起来相同，但省略了正则字符串前面的 @code{'r'}。:

@example
>>> p = re.compile('\bclass\b')
>>> print(p.search('no class at all'))
None
>>> print(p.search('\b' + 'class' + '\b'))
<re.Match object; span=(0, 7), match='\x08class\x08'>
@end example

其次，在一个字符类中，这个断言没有用处，@code{\b} 表示退格字符，以便与 Python 的字符串文字兼容。

@item @code{\B}

另一个零宽度断言，这与 @code{\b} 相反，仅在当前位置不在字边界时才匹配。
@end table

@node 分组,非捕获和命名组,更多元字符,更多模式能力
@anchor{howto/regex grouping}@anchor{43fb}
@subsubsection 分组


通常，你需要获取更多信息，而不仅仅是正则是否匹配。 正则表达式通常用于通过将正则分成几个子组来解析字符串，这些子组匹配不同的感兴趣组件。 例如，RFC-822 标题行分为标题名称和值，用 @code{':'} 分隔，如下所示：

@example
From: author@@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@@example.com
@end example

这可以通过编写与整个标题行匹配的正则表达式来处理，并且具有与标题名称匹配的一个组，以及与标题的值匹配的另一个组。

组由 @code{'('}，@code{')'} 元字符标记。 @code{'('} 和 @code{')'} 与数学表达式的含义大致相同；它们将包含在其中的表达式组合在一起，你可以使用重复限定符重复组的内容，例如 @code{*}，@code{+}，@code{?} 或 @code{@{m,n@}}。 例如，@code{(ab)*} 将匹配 @code{ab} 的零次或多次重复。:

@example
>>> p = re.compile('(ab)*')
>>> print(p.match('ababababab').span())
(0, 10)
@end example

用 @code{'('}，@code{')'} 表示的组也捕获它们匹配的文本的起始和结束索引；这可以通过将参数传递给 @ref{1902,,group()}、@ref{1906,,start()}、@ref{1907,,end()} 以及 @ref{1908,,span()}。 组从 0 开始编号。组 0 始终存在；它表示整个正则，所以 @ref{98d,,匹配对象} 方法都将组 0 作为默认参数。 稍后我们将看到如何表达不捕获它们匹配的文本范围的组。:

@example
>>> p = re.compile('(a)b')
>>> m = p.match('ab')
>>> m.group()
'ab'
>>> m.group(0)
'ab'
@end example

子组从左到右编号，从 1 向上编号。 组可以嵌套；要确定编号，只需计算从左到右的左括号字符。:

@example
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.group(0)
'abcd'
>>> m.group(1)
'abc'
>>> m.group(2)
'b'
@end example

@ref{1902,,group()} 可以一次传递多个组号，在这种情况下，它将返回一个包含这些组的相应值的元组。:

@example
>>> m.group(2,1,2)
('b', 'abc', 'b')
@end example

@ref{1904,,groups()} 方法返回一个元组，其中包含所有子组的字符串，从1到最后一个子组。:

@example
>>> m.groups()
('abc', 'b')
@end example

模式中的后向引用允许你指定还必须在字符串中的当前位置找到先前捕获组的内容。 例如，如果可以在当前位置找到组 1 的确切内容，则 @code{\1} 将成功，否则将失败。 请记住，Python 的字符串文字也使用反斜杠后跟数字以允许在字符串中包含任意字符，因此正则中引入反向引用时务必使用原始字符串。

例如，以下正则检测字符串中的双字。:

@example
>>> p = re.compile(r'\b(\w+)\s+\1\b')
>>> p.search('Paris in the the spring').group()
'the the'
@end example

像这样的后向引用通常不仅仅用于搜索字符串 —— 很少有文本格式以这种方式重复数据 —— 但是你很快就会发现它们在执行字符串替换时 @emph{非常} 有用。

@node 非捕获和命名组,前向断言,分组,更多模式能力
@anchor{howto/regex non-capturing-and-named-groups}@anchor{43fc}
@subsubsection 非捕获和命名组


精心设计的正则可以使用许多组，既可以捕获感兴趣的子串，也可以对正则本身进行分组和构建。 在复杂的正则中，很难跟踪组号。 有两个功能可以帮助解决这个问题。 它们都使用常用语法进行正则表达式扩展，因此我们首先看一下。

Perl 5 以其对标准正则表达式的强大补充而闻名。 对于这些新功能，Perl 开发人员无法选择新的单键击元字符或以 @code{\} 开头的新特殊序列，否则 Perl 的正则表达式与标准正则容易混淆。 例如，如果他们选择 @code{&} 作为一个新的元字符，旧的表达式将假设 @code{&} 是一个普通字符，并且不会编写 @code{\&} 或 @code{[&]}。

Perl 开发人员选择的解决方案是使用 @code{(?...)} 作为扩展语法。 括号后面的 @code{?} 是一个语法错误，因为 @code{?} 没有什么可重复的，所以这并没有引入任何兼容性问题。 紧跟在 @code{?} 之后的字符表示正在使用什么扩展名，所以 @code{(?=foo)} 是一个东西（一个正向的先行断言）和 @code{(?:foo)} 是其它东西（ 包含子表达式 @code{foo} 的非捕获组）。

Python 支持一些 Perl 的扩展，并增加了新的扩展语法用于 Perl 的扩展语法。 如果在问号之后的第一个字符为 @code{P}，即表明其为 Python 专属的扩展。

现在我们已经了解了一般的扩展语法，我们可以回到简化复杂正则中组处理的功能。

有时你会想要使用组来表示正则表达式的一部分，但是对检索组的内容不感兴趣。 你可以通过使用非捕获组来显式表达这个事实: @code{(?:...)}，你可以用任何其他正则表达式替换 @code{...}。:

@example
>>> m = re.match("([abc])+", "abc")
>>> m.groups()
('c',)
>>> m = re.match("(?:[abc])+", "abc")
>>> m.groups()
()
@end example

除了你无法检索组匹配内容的事实外，非捕获组的行为与捕获组完全相同；你可以在里面放任何东西，用重复元字符重复它，比如 @code{*}，然后把它嵌入其他组（捕获或不捕获）。 @code{(?:...)} 在修改现有模式时特别有用，因为你可以添加新组而不更改所有其他组的编号方式。 值得一提的是，捕获和非捕获组之间的搜索没有性能差异；两种形式没有一种更快。

更重要的功能是命名组：不是通过数字引用它们，而是可以通过名称引用组。

命名组的语法是Python特定的扩展之一: @code{(?P<name>...)}。 @emph{name} 显然是该组的名称。 命名组的行为与捕获组完全相同，并且还将名称与组关联。 处理捕获组的 @ref{98d,,匹配对象} 方法都接受按编号引用组的整数或包含所需组名的字符串。 命名组仍然是给定的数字，因此你可以通过两种方式检索有关组的信息:

@example
>>> p = re.compile(r'(?P<word>\b\w+\b)')
>>> m = p.search( '(((( Lots of punctuation )))' )
>>> m.group('word')
'Lots'
>>> m.group(1)
'Lots'
@end example

此外，你可以通过 @ref{1905,,groupdict()} 将命名分组提取为一个字典:

@example
>>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
>>> m.groupdict()
@{'first': 'Jane', 'last': 'Doe'@}
@end example

命名组很有用，因为它们允许你使用容易记住的名称，而不必记住数字。 这是来自 @ref{97,,imaplib} 模块的示例正则

@example
InternalDate = re.compile(r'INTERNALDATE "'
        r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
        r'(?P<year>[0-9][0-9][0-9][0-9])'
        r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
        r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
        r'"')
@end example

检索 @code{m.group('zonem')} 显然要容易得多，而不必记住检索第 9 组。

表达式中的后向引用语法，例如 @code{(...)\1}，指的是组的编号。 当然有一种变体使用组名而不是数字。 这是另一个 Python 扩展: @code{(?P=name)} 表示在当前点再次匹配名为 @emph{name} 的组的内容。 用于查找双字的正则表达式，@code{\b(\w+)\s+\1\b} 也可以写为 @code{\b(?P<word>\w+)\s+(?P=word)\b}:

@example
>>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
>>> p.search('Paris in the the spring').group()
'the the'
@end example

@node 前向断言,,非捕获和命名组,更多模式能力
@anchor{howto/regex lookahead-assertions}@anchor{43fd}
@subsubsection 前向断言


另一个零宽断言是前视断言。 前视断言有肯定型和否定型两种形式，如下所示：


@table @asis

@item @code{(?=…)}

正向前向断言。 如果包含的正则表达式，由 @code{...} 表示，在当前位置成功匹配，则成功，否则失败。 但是，一旦尝试了包含的表达式，匹配的引擎就不会前进；模式其余的部分会在在断言开始的地方尝试。

@item @code{(?!…)}

否定型前视断言。 与肯定型断言正好相反，如果内部表达式在字符串中的当前位置 @strong{不} 匹配，则成功。
@end table

更具体一些，让我们看看前向是有用的情况。 考虑一个简单的模式来匹配文件名并将其拆分为基本名称和扩展名，用 @code{.} 分隔。 例如，在 @code{news.rc} 中，@code{news} 是基本名称，@code{rc} 是文件名的扩展名。

与此匹配的模式非常简单：

@code{.*[.].*$}

请注意，@code{.} 需要特别处理，因为它是元字符，所以它在字符类中只能匹配特定字符。 还要注意尾随的 @code{$}；添加此项以确保扩展名中的所有其余字符串都必须包含在扩展名中。 这个正则表达式匹配 @code{foo.bar}、@code{autoexec.bat}、@code{sendmail.cf} 和 @code{printers.conf}。

现在，考虑使更复杂一点的问题；如果你想匹配扩展名不是 @code{bat} 的文件名怎么办？ 一些错误的尝试：

@code{.*[.][^b].*$} 上面的第一次尝试试图通过要求扩展名的第一个字符不是 @code{b} 来排除 @code{bat}。 这是错误的，因为模式也与 @code{foo.bar} 不匹配。

@code{.*[.]([^b]..|.[^a].|..[^t])$}

当你尝试通过要求以下一种情况匹配来修补第一个解决方案时，表达式变得更加混乱：扩展的第一个字符不是 @code{b}。 第二个字符不 @code{a}；或者第三个字符不是 @code{t}。 这接受 @code{foo.bar} 并拒绝 @code{autoexec.bat}，但它需要三个字母的扩展名，并且不接受带有两个字母扩展名的文件名，例如 @code{sendmail.cf}。 为了解决这个问题，我们会再次使模式复杂化。

@code{.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$}

在第三次尝试中，第二个和第三个字母都是可选的，以便允许匹配的扩展名短于三个字符，例如 @code{sendmail.cf}。

模式现在变得非常复杂，这使得它难以阅读和理解。 更糟糕的是，如果问题发生变化并且你想要将 @code{bat} 和 @code{exe} 排除为扩展，那么该模式将变得更加复杂和混乱。

负面前向消除了所有这些困扰：

@code{.*[.](?!bat$)[^.]*$} 负向前向意味着：如果表达式 @code{bat} 此时不匹配，请尝试其余的模式；如果 @code{bat$} 匹配，整个模式将失败。 尾随的 @code{$} 是必需的，以确保允许像 @code{sample.batch} 这样的扩展只以 @code{bat} 开头的文件能通过。 @code{[^.]*} 确保当文件名中有多个点时，模式有效。

现在很容易排除另一个文件扩展名；只需在断言中添加它作为替代。  以下模块排除以 @code{bat} 或 @code{exe}:

@code{.*[.](?!bat$|exe$)[^.]*$}

@node 修改字符串,常见问题,更多模式能力,正则表达式HOWTO
@anchor{howto/regex modifying-strings}@anchor{43fe}
@subsection 修改字符串


到目前为止，我们只是针对静态字符串执行搜索。 正则表达式通常也用于以各种方式修改字符串，使用以下模式方法：


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

方法 / 属性

@tab

目的

@item

@code{split()}

@tab

将字符串拆分为一个列表，在正则匹配的任何地方将其拆分

@item

@code{sub()}

@tab

找到正则匹配的所有子字符串，并用不同的字符串替换它们

@item

@code{subn()}

@tab

与 @code{sub()} 相同，但返回新字符串和替换次数

@end multitable


@menu
* 分割字符串:: 
* 搜索和替换:: 

@end menu

@node 分割字符串,搜索和替换,,修改字符串
@anchor{howto/regex splitting-strings}@anchor{43ff}
@subsubsection 分割字符串


模式的 @ref{18f7,,split()} 方法在正则匹配的任何地方拆分字符串，返回一个片段列表。 它类似于 @ref{89a,,split()} 字符串方法，但在分隔符的分隔符中提供了更多的通用性；字符串的 @code{split()} 仅支持按空格或固定字符串进行拆分。 正如你所期望的那样，还有一个模块级 @ref{4d9,,re.split()} 函数。


@deffn {方法} .split (string[, maxsplit=0])

通过正则表达式的匹配拆分 @emph{字符串}。 如果在正则中使用捕获括号，则它们的内容也将作为结果列表的一部分返回。 如果 @emph{maxsplit} 非零，则最多执行 @emph{maxsplit} 次拆分。
@end deffn

你可以通过传递 @emph{maxsplit} 的值来限制分割的数量。 当 @emph{maxsplit} 非零时，将最多进行 @emph{maxsplit} 次拆分，并且字符串的其余部分将作为列表的最后一个元素返回。 在以下示例中，分隔符是任何非字母数字字符序列。:

@example
>>> p = re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '@w{'}]
>>> p.split('This is a test, short and sweet, of split().', 3)
['This', 'is', 'a', 'test, short and sweet, of split().']
@end example

有时你不仅对分隔符之间的文本感兴趣，而且还需要知道分隔符是什么。 如果在正则中使用捕获括号，则它们的值也将作为列表的一部分返回。 比较以下调用:

@example
>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '@w{'}]
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '@w{'}]
@end example

模块级函数 @ref{4d9,,re.split()} 添加要正则作为第一个参数，但在其他方面是相同的。:

@example
>>> re.split(r'[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '@w{'}]
>>> re.split(r'([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '@w{'}]
>>> re.split(r'[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']
@end example

@node 搜索和替换,,分割字符串,修改字符串
@anchor{howto/regex search-and-replace}@anchor{4400}
@subsubsection 搜索和替换


另一个常见任务是找到模式的所有匹配项，并用不同的字符串替换它们。 @ref{18fa,,sub()} 方法接受一个替换值，可以是字符串或函数，也可以是要处理的字符串。


@deffn {方法} .sub (replacement, string[, count=0])

返回通过替换 @emph{replacement} 替换 @emph{string} 中正则的最左边非重叠出现而获得的字符串。 如果未找到模式，则 @emph{string} 将保持不变。

可选参数 @emph{count} 是要替换的模式最大的出现次数；@emph{count} 必须是非负整数。 默认值 0 表示替换所有。
@end deffn

这是一个使用 @ref{18fa,,sub()} 方法的简单示例。 它用 @code{colour} 这个词取代颜色名称:

@example
>>> p = re.compile('(blue|white|red)')
>>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub('colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
@end example

@ref{18fb,,subn()} 方法完成相同的工作，但返回一个包含新字符串值和已执行的替换次数的 2 元组:

@example
>>> p = re.compile('(blue|white|red)')
>>> p.subn('colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn('colour', 'no colours at all')
('no colours at all', 0)
@end example

仅当空匹配与前一个空匹配不相邻时，才会替换空匹配。:

@example
>>> p = re.compile('x*')
>>> p.sub('-', 'abxd')
'-a-b--d-'
@end example

如果 @emph{replacement} 是一个字符串，则处理其中的任何反斜杠转义。 也就是说，@code{\n} 被转换为单个换行符，@code{\r} 被转换为回车符，依此类推。 诸如 @code{\&} 之类的未知转义是孤立的。 后向引用，例如 @code{\6}，被替换为正则中相应组匹配的子字符串。 这使你可以在生成的替换字符串中合并原始文本的部分内容。

这个例子匹配单词 @code{section} 后跟一个用 @code{@{}，@code{@}} 括起来的字符串，并将 @code{section} 改为 @code{subsection}

@example
>>> p = re.compile('section@{ ( [^@}]* ) @}', re.VERBOSE)
>>> p.sub(r'subsection@{\1@}','section@{First@} section@{second@}')
'subsection@{First@} subsection@{second@}'
@end example

还有一种语法用于引用由 @code{(?P<name>...)} 语法定义的命名组。 @code{\g<name>} 将使用名为 @code{name} 的组匹配的子字符串，@code{\g<number>} 使用相应的组号。 因此 @code{\g<2>} 等同于 @code{\2}，但在诸如 @code{\g<2>0} 之类的替换字符串中并不模糊。 (@code{\20} 将被解释为对组 20 的引用，而不是对组 2 的引用，后跟字面字符 @code{'0'}。) 以下替换都是等效的，但使用所有三种变体替换字符串。:

@example
>>> p = re.compile('section@{ (?P<name> [^@}]* ) @}', re.VERBOSE)
>>> p.sub(r'subsection@{\1@}','section@{First@}')
'subsection@{First@}'
>>> p.sub(r'subsection@{\g<1>@}','section@{First@}')
'subsection@{First@}'
>>> p.sub(r'subsection@{\g<name>@}','section@{First@}')
'subsection@{First@}'
@end example

@emph{replacement} 也可以是一个函数，它可以为你提供更多控制。 如果 @emph{replacement} 是一个函数，则为 @emph{pattern} 的每次非重叠出现将调用该函数。 在每次调用时，函数都会传递一个匹配的 @ref{98d,,匹配对象} 参数，并可以使用此信息计算所需的替换字符串并将其返回。

在以下示例中，替换函数将小数转换为十六进制:

@example
>>> def hexrepl(match):
...     "Return the hex string for a decimal number"
...     value = int(match.group())
...     return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'
@end example

使用模块级别 @ref{582,,re.sub()} 函数时，模式作为第一个参数传递。 图案可以作为对象或字符串提供；如果需要指定正则表达式标志，则必须使用模式对象作为第一个参数，或者在模式字符串中使用嵌入式修饰符，例如: @code{sub("(?i)b+", "x", "bbbb BBBB")} 返回 @code{'x x'}。

@node 常见问题,反馈,修改字符串,正则表达式HOWTO
@anchor{howto/regex common-problems}@anchor{4401}
@subsection 常见问题


正则表达式对于某些应用程序来说是一个强大的工具，但在某些方面，它们的行为并不直观，有时它们的行为方式与你的预期不同。 本节将指出一些最常见的陷阱。

@menu
* 使用字符串方法:: 
* match() 和 search(): match 和 search. 
* 贪婪与非贪婪:: 
* 使用 re.VERBOSE: 使用 re VERBOSE. 

@end menu

@node 使用字符串方法,match 和 search,,常见问题
@anchor{howto/regex use-string-methods}@anchor{4402}
@subsubsection 使用字符串方法


有时使用 @ref{dd,,re} 模块是一个错误。 如果你匹配固定字符串或单个字符类，并且你没有使用任何 @ref{dd,,re} 功能，例如 @ref{18f1,,IGNORECASE} 标志，那么正则表达式的全部功能可能不是必需的。 字符串有几种方法可以使用固定字符串执行操作，它们通常要快得多，因为实现是一个针对此目的而优化的单个小 C 循环，而不是大型、更通用的正则表达式引擎。

一个例子可能是用另一个固定字符串替换一个固定字符串；例如，你可以用 @code{deed} 替换 @code{word} 。 @ref{582,,re.sub()} 看起来像是用于此的函数，但请考虑 @ref{17b7,,replace()} 方法。 注意 @code{replace()} 也会替换单词里面的 @code{word} ，把 @code{swordfish} 变成 @code{sdeedfish} ，但简单的正则 @code{word} 也会这样做。 （为了避免对单词的部分进行替换，模式必须是 @code{\bword\b}，以便要求 @code{word} 在任何一方都有一个单词边界。这使得工作超出了 @code{replace()} 的能力。）

另一个常见任务是从字符串中删除单个字符的每个匹配项或将其替换为另一个字符。 你可以用 @code{re.sub('\n', ' ', S)} 之类的东西来做这件事，但是 @ref{17b6,,translate()} 能够完成这两项任务，并且比任何正则表达式都快。

简而言之，在转向 @ref{dd,,re} 模块之前，请考虑是否可以使用更快更简单的字符串方法解决问题。

@node match 和 search,贪婪与非贪婪,使用字符串方法,常见问题
@anchor{howto/regex match-versus-search}@anchor{4403}
@subsubsection match() 和 search()


The @ref{c8b,,match()} function only checks if the RE matches at the beginning of the
string while @ref{c8a,,search()} will scan forward through the string for a match.
It's important to keep this distinction in mind.  Remember,  @code{match()} will
only report a successful match which will start at 0; if the match wouldn't
start at zero,  @code{match()} will @emph{not} report it.

@example
>>> print(re.match('super', 'superstition').span())
(0, 5)
>>> print(re.match('super', 'insuperable'))
None
@end example

另一方面， @ref{c8a,,search()} 将向前扫描字符串，报告它找到的第一个匹配项。:

@example
>>> print(re.search('super', 'superstition').span())
(0, 5)
>>> print(re.search('super', 'insuperable').span())
(2, 7)
@end example

有时你会被诱惑继续使用 @ref{c8b,,re.match()} ，只需在你的正则前面添加 @code{.*} 。抵制这种诱惑并使用 @ref{c8a,,re.search()} 代替。 正则表达式编译器对正则进行一些分析，以加快寻找匹配的过程。 其中一个分析可以确定匹配的第一个特征必须是什么；例如，以 @code{Crow} 开头的模式必须与 @code{'C'} 匹配。 分析让引擎快速扫描字符串，寻找起始字符，只在找到 @code{'C'} 时尝试完全匹配。

添加 @code{.*} 会使这个优化失效，需要扫描到字符串的末尾，然后回溯以找到正则的其余部分的匹配。 使用 @ref{c8a,,re.search()} 代替。

@node 贪婪与非贪婪,使用 re VERBOSE,match 和 search,常见问题
@anchor{howto/regex greedy-versus-non-greedy}@anchor{4404}
@subsubsection 贪婪与非贪婪


当重复一个正则表达式时，就像在 @code{a*} 中一样，最终的动作就是消耗尽可能多的模式。 当你尝试匹配一对对称分隔符，例如 HTML 标记周围的尖括号时，这个事实经常会让你感到困惑。因为 @code{.*} 的贪婪性质， 用于匹配单个 HTML 标记的简单模式不起作用。

@example
>>> s = '<html><head><title>Title</title>'
>>> len(s)
32
>>> print(re.match('<.*>', s).span())
(0, 32)
>>> print(re.match('<.*>', s).group())
<html><head><title>Title</title>
@end example

正则匹配 @code{'<'} 中的 @code{'<html>'} 和 @code{.*} 消耗字符串的其余部分。 正则中还有更多的剩余东西，并且 @code{>} 在字符串的末尾不能匹配，所以正则表达式引擎必须逐个字符地回溯，直到它找到匹配 @code{>} 。最终匹配从 @code{'<html>'} 中的 @code{'<'} 扩展到 @code{'</title>'} 中的 @code{'>'} ，而这并不是你想要的结果。

在这种情况下，解决方案是使用非贪婪的限定符 @code{*?} 、 @code{+?} 、 @code{??} 或 @code{@{m,n@}?} ，匹配为尽可能 @emph{少} 的文字。 在上面的例子中，在第一次 @code{'<'} 匹配后立即尝试 @code{'>'} ，当它失败时，引擎一次前进一个字符，每一步都重试 @code{'>'} 。 这产生了正确的结果:

@example
>>> print(re.match('<.*?>', s).group())
<html>
@end example

（请注意，使用正则表达式解析 HTML 或 XML 很痛苦。快而脏的模式将处理常见情况，但 HTML 和 XML 有特殊情况会破坏明显的正则表达式；当你编写正则表达式处理所有可能的情况时，模式将非常复杂。使用 HTML 或 XML 解析器模块来执行此类任务。）

@node 使用 re VERBOSE,,贪婪与非贪婪,常见问题
@anchor{howto/regex using-re-verbose}@anchor{4405}
@subsubsection 使用 re.VERBOSE


到目前为止，你可能已经注意到正则表达式是一种非常紧凑的表示法，但它们并不是非常易读。 具有中等复杂度的正则可能会成为反斜杠、括号和元字符的冗长集合，使其难以阅读和理解。

对于这样的正则，在编译正则表达式时指定 @ref{18f2,,re.VERBOSE} 标志可能会有所帮助，因为它允许你更清楚地格式化正则表达式。

@code{re.VERBOSE} 标志有几种效果。 正则表达式中的 @emph{不是} 在字符类中的空格将被忽略。 这意味着表达式如 @code{dog | cat} 等同于不太可读的 @code{dog|cat} ，但 @code{[a b]} 仍将匹配字符 @code{'a'} 、 @code{'b'} 或空格。 此外，你还可以在正则中放置注释；注释从 @code{#} 字符扩展到下一个换行符。 当与三引号字符串一起使用时，这使正则的格式更加整齐:

@example
pat = re.compile(r"""
 \s*                 # Skip leading whitespace
 (?P<header>[^:]+)   # Header name
 \s* :               # Whitespace, and a colon
 (?P<value>.*?)      # The header's value -- *? used to
                     # lose the following trailing whitespace
 \s*$                # Trailing whitespace to end-of-line
""", re.VERBOSE)
@end example

这更具有可读性:

@example
pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
@end example

@node 反馈,,常见问题,正则表达式HOWTO
@anchor{howto/regex feedback}@anchor{4406}
@subsection 反馈


正则表达式是一个复杂的主题。 这份文档是否有助于你理解它们？ 是否存在不清楚的部分，或者你遇到的问题未在此处涉及？ 如果是，请向作者发送改进建议。

关于正则表达式的最完整的书几乎肯定是由 O'Reilly 出版的 Jeffrey Friedl 的 Mastering Regular Expressions 。 不幸的是，它专注于 Perl 和 Java 的正则表达式，并且根本不包含任何 Python 材料，因此它不能用作 Python 编程的参考。 （第一版涵盖了 Python 现在删除的 @code{regex} 模块，这对你没有多大帮助。）考虑从你的图书馆中查找它。

@node 套接字编程指南,排序指南,正则表达式HOWTO,Python 常用指引
@anchor{howto/sockets doc}@anchor{4407}@anchor{howto/sockets socket-howto}@anchor{27fb}@anchor{howto/sockets socket-programming-howto}@anchor{4408}
@section 套接字编程指南


@*作者: 
Gordon McMillan


@subsubheading 摘要



套接字几乎无处不在，但是它却是被误解最严重的技术之一。这是一篇简单的套接字概述。并不是一篇真正的教程 —— 你需要做更多的事情才能让它工作起来。其中也并没有涵盖细节（细节会有很多），但是我希望它能提供足够的背景知识，让你像模像样的开始使用套接字

@menu
* 套接字:: 
* 创建套接字: 创建套接字<2>. 
* 使用一个套接字:: 
* 断开连接:: 
* 非阻塞的套接字:: 

@end menu

@node 套接字,创建套接字<2>,,套接字编程指南
@anchor{howto/sockets sockets}@anchor{4409}
@subsection 套接字


我将只讨论关于 INET（比如：IPv4 地址族）的套接字，但是它将覆盖几乎 99% 的套接字使用场景。并且我将仅讨论 STREAM（比如：TCP）类型的套接字 - 除非你真的知道你在做什么（那么这篇 HOWTO 可能并不适合你），使用 STREAM 类型的套接字将会得到比其它类型更好的表现与性能。我将尝试揭开套接字的神秘面纱，也会讲到一些阻塞与非阻塞套接字的使用。但是我将以阻塞套接字为起点开始讨论。只有你了解它是如何工作的以后才能处理非阻塞套接字。

理解这些东西的难点之一在于「套接字」可以表示很多微妙差异的东西，这取决于上下文。所以首先，让我们先分清楚「客户端」套接字和「服务端」套接字之间的不同，客户端套接字表示对话的一端，服务端套接字更像是总机接线员。客户端程序只能（比如：你的浏览器）使用「客户端」套接字；网络服务器则可以使用「服务端」套接字和「客户端」套接字来会话

@menu
* 历史:: 

@end menu

@node 历史,,,套接字
@anchor{howto/sockets history}@anchor{440a}
@subsubsection 历史


目前为止，在各种形式的 @abbr{IPC,进程间通信} 中，套接字是最流行的。在任何指定的平台上，可能会有其它更快的 IPC 形式，但是就跨平台通信来说，套接字大概是唯一的玩法

套接字做为 BSD Unix 操作系统的一部分在伯克利诞生，像野火一样在因特网传播。有一个很好的原因 —— 套接字与 INET 的结合使得与世界各地的任意机器间通信变得令人难以置信的简单（至少对比与其他方案来说）

@node 创建套接字<2>,使用一个套接字,套接字,套接字编程指南
@anchor{howto/sockets creating-a-socket}@anchor{440b}
@subsection 创建套接字


简略地说，当你点击带你来到这个页面的链接时，你的浏览器就已经做了下面这几件事情:

@example
# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
s.connect(("www.python.org", 80))
@end example

当连接完成，套接字可以用来发送请求来接收页面上显示的文字。同样是这个套接字也会用来读取响应，最后再被销毁。是的，被销毁了。客户端套接字通常用来做一次交换（或者说一小组序列的交换）。

网络服务器发生了什么这个问题就有点复杂了。首页，服务器创建一个「服务端套接字」:

@example
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), 80))
# become a server socket
serversocket.listen(5)
@end example

有几件事需要注意：我们使用了 @code{socket.gethostname()}，所以套接字将外网可见。如果我们使用的是 @code{s.bind(('localhost', 80))} 或者 @code{s.bind(('127.0.0.1', 80))}，也会得到一个「服务端」套接字，但是后者只在同一机器上可见。@code{s.bind(('@w{'}, 80))} 则指定套接字可以被机器上的任何地址碰巧连接

第二个需要注点是：低端口号通常被一些「常用的」服务（HTTP, SNMP 等）所保留。如果你想把程序跑起来，最好使用一个高位端口号（通常是4位的数字）。

最后，@code{listen} 方法的参数会告诉套接字库，我们希望在队列中累积多达 5 个（通常的最大值）连接请求后再拒绝外部连接。 如果所有其他代码都准确无误，这个队列长度应该是足够的。

现在我们已经有一个「服务端」套接字，监听了 80 端口，我们可以进入网络服务器的主循环了:

@example
while True:
    # accept connections from outside
    (clientsocket, address) = serversocket.accept()
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread(clientsocket)
    ct.run()
@end example

事际上，通常有 3 种方法可以让这个循环工作起来 - 调度一个线程来处理 @code{客户端套接字}，或者把这个应用改成使用非阻塞模式套接字，亦或是使用 @code{select} 库来实现「服务端」套接字与任意活动 @code{客户端套接字} 之间的多路复用。稍后会详细介绍。现在最重要的是理解：这就是一个 @emph{服务端} 套接字做的 @emph{所有} 事情。它并没有发送任何数据。也没有接收任何数据。它只创建「客户端」套接字。每个 @code{客户端套接字} 都是为了响应某些其它客户端套接字 @code{connect()} 到我们绑定的主机。一旦创建 @code{客户端套接字} 完成，就会返回并监听更多的连接请求。现个客户端可以随意通信 - 它们使用了一些动态分配的端口，会话结束时端口才会被回收

@menu
* 进程间通信:: 

@end menu

@node 进程间通信,,,创建套接字<2>
@anchor{howto/sockets ipc}@anchor{440c}
@subsubsection 进程间通信


如果你需要在同一台机器上进行两个进程间的快速 IPC 通信，你应该了解管道或者共享内存。如果你决定使用 AF_INET 类型的套接字，绑定「服务端」套接字到 @code{'localhost'} 。在大多数平台，这将会使用一个许多网络层间的通用快捷方式（本地回环地址）并且速度会快很多


@subsubheading 参见


@ref{b7,,multiprocessing} 模块使跨平台 IPC 通信成为一个高层的 API


@node 使用一个套接字,断开连接,创建套接字<2>,套接字编程指南
@anchor{howto/sockets using-a-socket}@anchor{440d}
@subsection 使用一个套接字


首先需要注意，浏览器的「客户端」套接字和网络服务器的「客户端」套接字是极为相似的。即这种会话是「点对点」的。或者也可以说 @emph{你作为设计师需要自行决定会话的规则和礼节} 。通常情况下，@code{连接} 套接字通过发送一个请求或者信号来开始一次会话。但这属于设计决定，并不是套接字规则。

现在有两组用于通信的动词。你可以使用 @code{send} 和 @code{recv} ，或者你可以把客户端套接字改成文件类型的形式来使用  @code{read} 和 @code{write} 方法。后者是 Java 语言中表示套接字的方法，我将不会在这儿讨论这个，但是要提醒你需要调用套接字的 @code{flush} 方法。这些是“缓冲”的文件，一个经常出现的错误是 @code{write} 一些东西，然后就直接开始 @code{read} 一个响应。如果不调用 @code{flush} ，你可能会一直等待这个响应，因为请求可能还在你的输出缓冲中。

现在我来到了套接字的两个主要的绊脚石 - @code{send} 和 @code{recv} 操作网络缓冲区。它们并不一定可以处理所有你想要（期望）的字节，因为它们主要关注点是处理网络缓冲。通常，它们在关联的网络缓冲区 @code{send} 或者清空 @code{recv} 时返回。然后告诉你处理了多少个字节。@emph{你} 的责任是一直调用它们直到你所有的消息处理完成。

当 @code{recv} 方法返回 0 字节时，就表示另一端已经关闭（或者它所在的进程关闭）了连接。你再也不能从这个连接上获取到任何数据了。你可以成功的发送数据；我将在后面讨论这一点。

像 HTTP 这样的协议只使用一个套接字进行一次传输。客户端发送一个请求，然后读取响应。就这么简单。套接字会被销毁。 表示客户端可以通过接收 0 字节序列表示检测到响应的结束。

但是如果你打算在随后来的传输中复用套接字的话，你需要明白 @emph{套接字里面是不存在 :abbr:`EOT (传输结束)`} 的。重复一下：套接字 @code{send} 或者 @code{recv} 完 0 字节后返回，连接会中断。如果连接没有被断开，你可能会永远处于等待 @code{recv} 的状态，因为（就目前来说）套接字 @emph{不会} 告诉你不用再读取了。现在如果你细心一点，你可能会意识到套接字基本事实：@emph{消息必须要么具有固定长度，要么可以界定，要么指定了长度（比较好的做法），要么以关闭连接为结束}。选择完全由你而定（这比让别人定更合理）。

假定你不希望结束连接，那么最简单的解决方案就是使用定长消息:

@example
class MySocket:
    """demonstration class only
      - coded for clarity, not efficiency
    """

    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        self.sock.connect((host, port))

    def mysend(self, msg):
        totalsent = 0
        while totalsent < MSGLEN:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            totalsent = totalsent + sent

    def myreceive(self):
        chunks = []
        bytes_recd = 0
        while bytes_recd < MSGLEN:
            chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
            if chunk == b'@w{'}:
                raise RuntimeError("socket connection broken")
            chunks.append(chunk)
            bytes_recd = bytes_recd + len(chunk)
        return b'@w{'}.join(chunks)
@end example

发送分部代码几乎可用于任何消息传递方案 —— 在 Python 中你发送字符串，可以使用 @code{len()} 方法来确定它的长度（即使它嵌入了 @code{\0} 字符），主要是接收代码变得更复杂。（在 C 语言中，并没有更糟糕，除非消息嵌入了 @code{\0} 字符而且你又无法使用 @code{strlen} ）

最简单的改进是让消息的第一个字符表示消息类型，由类型决定长度。现在你需要两次 @code{recv}- 第一次取（至少）第一个字符来知晓长度，第二次在循环中获取剩余所有的消息。如果你决定到分界线，你将收到一些任意大小的块，（4096 或者 8192 通常是比较合适的网络缓冲区大小），扫描你接收到的分界符

一个需要意识到的复杂情况是：如果你的会话协议允许多个消息被发送回来（没有响应），调用 @code{recv} 传入任意大小的块，你可能会因为读到后续接收的消息而停止读取。你需要将它放在一边并保存，直到它需要为止。

以其长度（例如，作为5个数字字符）作为消息前缀时会变得更复杂，因为（信不信由你）你可能无法在一个 @code{recv} 中获得所有5个字符。在一般使用时，你会侥幸避免该状况；但是在高网络负载中，除非你使用两个 @code{recv} 循环，否则你的代码将很快中断 —— 第一个用于确定长度，第二个用于获取消息的数据部分。这很讨厌。当你发现 @code{send} 并不总是设法在支持搞定一切时，你也会有这种感觉。 尽管已经阅读过这篇文章，但最终还是会有所了解！

限于篇幅，建立你的角色，（保持与我的竞争位置），这些改进将留给读者做为练习。现在让我们继续。

@menu
* 二进制数据:: 

@end menu

@node 二进制数据,,,使用一个套接字
@anchor{howto/sockets binary-data}@anchor{440e}
@subsubsection 二进制数据


通过套接字传送二进制数据是可行的。主要问题在于并非所有机器都用同样的二进制数据格式。比如 Motorola 芯片用两个十六进制字节 00 01 来表示一个 16 位整数值 1。而 Intel 和 DEC 则会做字节反转 —— 即用 01 00 来表示 1。套接字库要求转换 16 位和 32 位整数 —— @code{ntohl, htonl, ntohs, htons} 其中的「n」表示 @emph{network}，「h」表示 @emph{host}，「s」表示 @emph{short}，「l」表示 @emph{long}。在网络序列就是主机序列时它们什么都不做，但是如果机器是字节反转的则会适当地交换字节序。

在现今的 32 位机器中，二进制数据的 ascii 表示往往比二进制表示要小。这是因为在非常多的时候所有 long 的值均为 0 或者 1。字符串形式的 "0" 为两个字节，而二进制形式则为四个。当然这不适用于固定长度的信息。自行决定，请自行决定。

@node 断开连接,非阻塞的套接字,使用一个套接字,套接字编程指南
@anchor{howto/sockets disconnecting}@anchor{440f}
@subsection 断开连接


严格地讲，你应该在 @code{close} 它之前将套接字 @code{shutdown} 。 @code{shutdown} 是发送给套接字另一端的一种建议。调用时参数不同意义也不一样，它可能意味着「我不会再发送了，但我仍然会监听」，或者「我没有监听了，真棒！」。然而，大多数套接字库或者程序员都习惯了忽略使用这种礼节，因为通常情况下 @code{close} 与 @code{shutdown(); close()} 是一样的。所以在大多数情况下，不需要显式的 @code{shutdown} 。

高效使用 @code{shutdown} 的一种方法是在类似 HTTP 的交换中。客户端发送请求，然后执行 @code{shutdown(1)} 。 这告诉服务器“此客户端已完成发送，但仍可以接收”。服务器可以通过接收 0 字节来检测 “EOF” 。它可以假设它有完整的请求。服务器发送回复。如果 @code{send} 成功完成，那么客户端仍在接收。

Python 进一步自动关闭，并说当一个套接字被垃圾收集时，如果需要它会自动执行 @code{close} 。但依靠这个机制是一个非常坏的习惯。如果你的套接字在没有 @code{close} 的情况下就消失了，那么另一端的套接字可能会无限期地挂起，以为你只是慢了一步。完成后 @emph{请} @code{close} 你的套接字。

@menu
* 套接字何时销毁:: 

@end menu

@node 套接字何时销毁,,,断开连接
@anchor{howto/sockets when-sockets-die}@anchor{4410}
@subsubsection 套接字何时销毁


使用阻塞套接字最糟糕的事情可能就是当另一边下线时（没有 @code{close} ）会发生什么。你的套接字可能会挂起。 TCP 是一种可靠的协议，它会在放弃连接之前等待很长时间。如果你正在使用线程，那么整个线程基本上已经死了。你无能为力。只要你没有做一些愚蠢的事情，比如在进行阻塞读取时持有一个锁，那么线程并没有真正消耗掉资源。 @emph{不要} 尝试杀死线程 —— 线程比进程更有效的部分原因是它们避免了与自动回收资源相关的开销。换句话说，如果你设法杀死线程，你的整个进程很可能被搞坏。

@node 非阻塞的套接字,,断开连接,套接字编程指南
@anchor{howto/sockets non-blocking-sockets}@anchor{4411}
@subsection 非阻塞的套接字


如果你已理解上述内容，那么你已经了解了使用套接字的机制所需了解的大部分内容。你仍将以相同的方式使用相同的函数调用。 只是，如果你做得对，你的应用程序几乎是由内到外的。

在 Python 中是使用 @code{socket.setblocking(False)} 来设置非阻塞。 在 C 中的做法更为复杂（例如，你需要在 BSD 风格的 @code{O_NONBLOCK} 和几乎无区别的 POSIX 风格的 @code{O_NDELAY} 之间作出选择，这与 @code{TCP_NODELAY} 完全不一样），但其思路实际上是相同的。 你要在创建套接字之后但在使用它之前执行此操作。 （实际上，如果你是疯子的话也可以反复进行切换。）

主要的机制差异是 @code{send} 、 @code{recv} 、 @code{connect} 和 @code{accept} 可以在没有做任何事情的情况下返回。 你（当然）有很多选择。你可以检查返回代码和错误代码，通常会让自己发疯。如果你不相信我，请尝试一下。你的应用程序将变得越来越大、越来越 Bug 、吸干 CPU。因此，让我们跳过脑死亡的解决方案并做正确的事。

使用 @code{select} 库

在 C 中，编码 @code{select} 相当复杂。 在 Python 中，它是很简单，但它与 C 版本足够接近，如果你在 Python 中理解 @code{select} ，那么在 C 中你会几乎不会遇到麻烦:

@example
ready_to_read, ready_to_write, in_error = \
               select.select(
                  potential_readers,
                  potential_writers,
                  potential_errs,
                  timeout)
@end example

你传递给 @code{select} 三个列表：第一个包含你可能想要尝试读取的所有套接字；第二个是你可能想要尝试写入的所有套接字，以及要检查错误的最后一个（通常为空）。你应该注意，套接字可以进入多个列表。 @code{select} 调用是阻塞的，但你可以给它一个超时。这通常是一件明智的事情 —— 给它一个很长的超时（比如一分钟），除非你有充分的理由不这样做。

作为返回，你将获得三个列表。它们包含实际可读、可写和有错误的套接字。 这些列表中的每一个都是你传入的相应列表的子集（可能为空）。

如果一个套接字在输出可读列表中，那么你可以像我们一样接近这个业务，那个套接字上的 @code{recv} 将返回 @emph{一些内容} 。可写列表的也相同，你将能够发送 @emph{一些内容} 。 也许不是你想要的全部，但 @emph{有些东西} 比没有东西更好。 （实际上，任何合理健康的套接字都将以可写方式返回 —— 它只是意味着出站网络缓冲区空间可用。）

如果你有一个“服务器”套接字，请将其放在 potential_readers 列表中。如果它出现在可读列表中，那么你的 @code{accept} （几乎肯定）会起作用。如果你已经创建了一个新的套接字 @code{connect} 其他人，请将它放在 potential_writers 列表中。如果它出现在可写列表中，那么它有可能已连接。

实际上，即使使用阻塞套接字， @code{select} 也很方便。这是确定是否阻塞的一种方法 —— 当缓冲区中存在某些内容时，套接字返回为可读。然而，这仍然无助于确定另一端是否完成或者只是忙于其他事情的问题。

@strong{可移植性警告} ：在 Unix 上， @code{select} 适用于套接字和文件。 不要在 Windows 上尝试。在 Windows 上， @code{select} 仅适用于套接字。另请注意，在 C 中，许多更高级的套接字选项在 Windows 上的执行方式不同。事实上，在 Windows 上我通常在使用我的套接字使用线程（非常非常好）。

@node 排序指南,Unicode 指南,套接字编程指南,Python 常用指引
@anchor{howto/sorting doc}@anchor{4412}@anchor{howto/sorting sorting-how-to}@anchor{4413}@anchor{howto/sorting sortinghowto}@anchor{1767}
@section 排序指南


@*作者: 
Andrew Dalke 和 Raymond Hettinger


@*发布版本: 
0.1


Python 列表有一个内置的 @ref{550,,list.sort()} 方法可以直接修改列表。还有一个 @ref{54f,,sorted()} 内置函数，它会从一个可迭代对象构建一个新的排序列表。

在本文档中，我们将探索使用Python对数据进行排序的各种技术。

@menu
* 基本排序:: 
* 关键函数:: 
* Operator 模块函数:: 
* 升序和降序:: 
* 排序稳定性和排序复杂度:: 
* 使用装饰-排序-去装饰的旧方法:: 
* 使用 cmp 参数的旧方法:: 
* 其它:: 

@end menu

@node 基本排序,关键函数,,排序指南
@anchor{howto/sorting sorting-basics}@anchor{4414}
@subsection 基本排序


简单的升序排序非常简单：只需调用 @ref{54f,,sorted()} 函数即可。它会返回一个新的已排序列表。

@example
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
@end example

你也可以使用 @ref{550,,list.sort()} 方法，它会直接修改原列表（并返回 @code{None} 以避免混淆），通常来说它不如 @ref{54f,,sorted()} 方便 ——— 但如果你不需要原列表，它会更有效率。

@example
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
@end example

另外一个区别是， @ref{550,,list.sort()} 方法只是为列表定义的，而 @ref{54f,,sorted()} 函数可以接受任何可迭代对象。

@example
>>> sorted(@{1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'@})
[1, 2, 3, 4, 5]
@end example

@node 关键函数,Operator 模块函数,基本排序,排序指南
@anchor{howto/sorting key-functions}@anchor{4415}
@subsection 关键函数


@ref{550,,list.sort()} 和 @ref{54f,,sorted()} 都有一个 @emph{key} 形参用来指定在进行比较前要在每个列表元素上调用的函数（或其他可调用对象）。

例如，下面是一个不区分大小写的字符串比较：

@example
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
@end example

@emph{key} 形参的值应该是个函数（或其他可调用对象），它接受一个参数并返回一个用于排序的键。 这种机制速度很快，因为对于每个输入记录只会调用一次键函数。

一种常见的模式是使用对象的一些索引作为键对复杂对象进行排序。例如：

@example
>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

同样的技术也适用于具有命名属性的对象。例如：

@example
>>> class Student:
...     def __init__(self, name, grade, age):
...         self.name = name
...         self.grade = grade
...         self.age = age
...     def __repr__(self):
...         return repr((self.name, self.grade, self.age))
@end example

@example
>>> student_objects = [
...     Student('john', 'A', 15),
...     Student('jane', 'B', 12),
...     Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

@node Operator 模块函数,升序和降序,关键函数,排序指南
@anchor{howto/sorting operator-module-functions}@anchor{4416}
@subsection Operator 模块函数


上面显示的键函数模式非常常见，因此 Python 提供了便利功能，使访问器功能更容易，更快捷。  @ref{c2,,operator} 模块有 @ref{393,,itemgetter()} 、 @ref{814,,attrgetter()} 和 @ref{815,,methodcaller()} 函数。

使用这些函数，上述示例变得更简单，更快捷：

@example
>>> from operator import itemgetter, attrgetter
@end example

@example
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

@example
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

Operator 模块功能允许多级排序。 例如，按 @emph{grade} 排序，然后按 @emph{age} 排序：

@example
>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
@end example

@example
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
@end example

@node 升序和降序,排序稳定性和排序复杂度,Operator 模块函数,排序指南
@anchor{howto/sorting ascending-and-descending}@anchor{4417}
@subsection 升序和降序


@ref{550,,list.sort()} 和 @ref{54f,,sorted()} 接受布尔值的 @emph{reverse} 参数。这用于标记降序排序。 例如，要以反向 @emph{age} 顺序获取学生数据：

@example
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
@end example

@example
>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
@end example

@node 排序稳定性和排序复杂度,使用装饰-排序-去装饰的旧方法,升序和降序,排序指南
@anchor{howto/sorting sort-stability-and-complex-sorts}@anchor{4418}
@subsection 排序稳定性和排序复杂度


排序保证是 稳定@footnote{https://en.wikipedia.org/wiki/Sorting_algorithm#Stability} 的。 这意味着当多个记录具有相同的键值时，将保留其原始顺序。

@example
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
@end example

注意 @emph{blue} 的两个记录如何保留它们的原始顺序，以便 @code{('blue', 1)} 保证在 @code{('blue', 2)} 之前。

这个美妙的属性允许你在一系列排序步骤中构建复杂的排序。例如，要按 @emph{grade} 降序然后 @emph{age} 升序对学生数据进行排序，请先 @emph{age} 排序，然后再使用 @emph{grade} 排序：

@example
>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

这可以被抽象为一个包装函数，该函数能接受一个列表以及字段和顺序的元组，以对它们进行多重排序。

@example
>>> def multisort(xs, specs):
...     for key, reverse in reversed(specs):
...         xs.sort(key=attrgetter(key), reverse=reverse)
...     return xs
@end example

@example
>>> multisort(list(student_objects), (('grade', True), ('age', False)))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

Python 中使用的 Timsort@footnote{https://en.wikipedia.org/wiki/Timsort} 算法可以有效地进行多种排序，因为它可以利用数据集中已存在的任何排序。

@node 使用装饰-排序-去装饰的旧方法,使用 cmp 参数的旧方法,排序稳定性和排序复杂度,排序指南
@anchor{howto/sorting the-old-way-using-decorate-sort-undecorate}@anchor{4419}
@subsection 使用装饰-排序-去装饰的旧方法


这个三个步骤被称为 Decorate-Sort-Undecorate ：


@itemize *

@item 
首先，初始列表使用控制排序顺序的新值进行修饰。

@item 
然后，装饰列表已排序。

@item 
最后，删除装饰，创建一个仅包含新排序中初始值的列表。
@end itemize

例如，要使用DSU方法按 @emph{grade} 对学生数据进行排序：

@example
>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated]               # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
@end example

这方法语有效是因为元组按字典顺序进行比较，先比较第一项；如果它们相同则比较第二个项目，依此类推。

不一定在所有情况下都要在装饰列表中包含索引 @emph{i} ，但包含它有两个好处：


@itemize *

@item 
排序是稳定的——如果两个项具有相同的键，它们的顺序将保留在排序列表中。

@item 
原始项目不必具有可比性，因为装饰元组的排序最多由前两项决定。 因此，例如原始列表可能包含无法直接排序的复数。
@end itemize

这个方法的另一个名字是 Randal L. Schwartz 在 Perl 程序员中推广的 Schwartzian transform@footnote{https://en.wikipedia.org/wiki/Schwartzian_transform}。

既然 Python 排序提供了键函数，那么通常不需要这种技术。

@node 使用 cmp 参数的旧方法,其它,使用装饰-排序-去装饰的旧方法,排序指南
@anchor{howto/sorting the-old-way-using-the-cmp-parameter}@anchor{441a}
@subsection 使用 @emph{cmp} 参数的旧方法


本 HOWTO 中给出的许多结构都假定为 Python 2.4 或更高版本。在此之前，没有内置 @ref{54f,,sorted()} ， @ref{550,,list.sort()} 也没有关键字参数。相反，所有 Py2.x 版本都支持 @emph{cmp} 参数来处理用户指定的比较函数。

在 Py3.0 中， @emph{cmp} 参数被完全删除（作为简化和统一语言努力的一部分，消除了丰富的比较与 @code{__cmp__()} 魔术方法之间的冲突）。

在 Py2.x 中， sort 允许一个可选函数，可以调用它来进行比较。该函数应该采用两个参数进行比较，然后返回负值为小于，如果它们相等则返回零，或者返回大于大于的正值。例如，我们可以这样做：

@example
>>> def numeric_compare(x, y):
...     return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) 
[1, 2, 3, 4, 5]
@end example

或者你可反转比较的顺序：

@example
>>> def reverse_numeric(x, y):
...     return y - x
>>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) 
[5, 4, 3, 2, 1]
@end example

将代码从 Python 2.x 移植到 3.x 时，如果用户提供比较功能并且需要将其转换为键函数，则会出现这种情况。 以下包装器使这很容易：

@example
def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K
@end example

要转换为键函数，只需包装旧的比较函数：

@c from functools import cmp_to_key

@example
>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
[5, 4, 3, 2, 1]
@end example

在 Python 3.2 中， @ref{c31,,functools.cmp_to_key()} 函数被添加到标准库中的 @ref{83,,functools} 模块中。

@node 其它,,使用 cmp 参数的旧方法,排序指南
@anchor{howto/sorting odd-and-ends}@anchor{441b}
@subsection 其它



@itemize *

@item 
对于区域相关的排序，请使用 @ref{30a1,,locale.strxfrm()} 作为键函数，或者 @ref{309f,,locale.strcoll()} 作为比较函数。

@item 
@emph{reverse} 参数仍然保持排序稳定性（因此具有相等键的记录保留原始顺序）。 有趣的是，通过使用内置的 @ref{2cd,,reversed()} 函数两次，可以在没有参数的情况下模拟该效果：

@example
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
>>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
>>> assert standard_way == double_reversed
>>> standard_way
[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]
@end example

@item 
The sort routines use @code{<} when making comparisons
between two objects. So, it is easy to add a standard sort order to a class by
defining an @ref{d06,,__lt__()} method:

@example
>>> Student.__lt__ = lambda self, other: self.age < other.age
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
@end example

然而，请注意，如果 @ref{d71,,__gt__()} 没有实现，@code{<} 可以退回到使用 @ref{d06,,__lt__()} （见 @ref{d06,,object.__lt__()} ）。

@item 
键函数不需要直接依赖于被排序的对象。键函数还可以访问外部资源。例如，如果学生成绩存储在字典中，则可以使用它们对单独的学生姓名列表进行排序：

@example
>>> students = ['dave', 'john', 'jane']
>>> newgrades = @{'john': 'F', 'jane':'A', 'dave': 'C'@}
>>> sorted(students, key=newgrades.__getitem__)
['jane', 'dave', 'john']
@end example
@end itemize

@node Unicode 指南,如何利用 urllib 包获取网络资源,排序指南,Python 常用指引
@anchor{howto/unicode doc}@anchor{441c}@anchor{howto/unicode id1}@anchor{441d}@anchor{howto/unicode unicode-howto}@anchor{d0c}
@section Unicode 指南


@*发布版本: 
1.12


本文介绍了 Python 对表示文本数据的 Unicode 规范的支持，并对各种 Unicode 常见使用问题做了解释。

@menu
* Unicode 概述:: 
* Python对Unicode的支持:: 
* Unicode 数据的读写:: 
* 致谢: 致谢<10>. 

@end menu

@node Unicode 概述,Python对Unicode的支持,,Unicode 指南
@anchor{howto/unicode introduction-to-unicode}@anchor{441e}
@subsection Unicode 概述


@menu
* 定义:: 
* 编码:: 
* 引用文献: 引用文献<2>. 

@end menu

@node 定义,编码,,Unicode 概述
@anchor{howto/unicode definitions}@anchor{441f}
@subsubsection 定义


如今的程序需要能够处理各种各样的字符。应用程序通常做了国际化处理，用户可以选择不同的语言显示信息和输出数据。同一个程序可能需要以英语、法语、日语、希伯来语或俄语输出错误信息。网页内容可能由这些语言书写，并且可能包含不同的表情符号。Python 的字符串类型采用 Unicode 标准来表示字符，使得 Python 程序能够正常处理所有这些不同的字符。

Unicode 规范（@indicateurl{https://www.unicode.org/}）旨在罗列人类语言所用到的所有字符，并赋予每个字符唯一的编码。该规范一直在进行修订和更新，不断加入新的语种和符号。

一个 @strong{字符} 是文本的最小组件。‘A’、‘B’、‘C’ 等都是不同的字符。‘È’ 和 ‘Í’ 也一样。字符会随着语言或者上下文的变化而变化。比如，‘Ⅰ’ 是一个表示 “罗马数字 1” 的字符，它与大写字母 ‘I’ 不同。他们往往看起来相同，但这是两个有着不同含义的字符。

Unicode 标准描述了字符是如何用 @strong{码位（code point）} 表示的。码位的取值范围是 0 到 0x10FFFF 的整数（大约 110 万个值，实际分配的数字@footnote{https://www.unicode.org/versions/latest/#Summary} 没有那么多）。在 Unicode 标准和本文中，码位采用 @code{U+265E} 的形式，表示值为 @code{0x265e} 的字符（十进制为 9822）。

Unicode 标准中包含了许多表格，列出了很多字符及其对应的码位。

@example
0061    'a'; LATIN SMALL LETTER A
0062    'b'; LATIN SMALL LETTER B
0063    'c'; LATIN SMALL LETTER C
...
007B    '@{'; LEFT CURLY BRACKET
...
2167    'Ⅷ'; ROMAN NUMERAL EIGHT
2168    'Ⅸ'; ROMAN NUMERAL NINE
...
265E    '♞'; BLACK CHESS KNIGHT
265F    '♟'; BLACK CHESS PAWN
...
1F600   '😀'; GRINNING FACE
1F609   '😉'; WINKING FACE
...
@end example

严格地说，上述定义暗示了以下说法是没有意义的：“这是字符 @code{U+265E}”。@code{U+265E} 只是一个码位，代表某个特定的字符；这里它代表了字符 “国际象棋黑骑士” '♞'。在非正式的上下文中，有时会忽略码位和字符的区别。

一个字符在屏幕或纸上被表示为一组图形元素，被称为 @strong{字形（glyph）} 。比如，大写字母 A 的字形，是两笔斜线和一笔横线，而具体的细节取决于所使用的字体。大部分 Python 代码不必担心字形，找到正确的显示字形通常是交给 GUI 工具包或终端的字体渲染程序来完成。

@node 编码,引用文献<2>,定义,Unicode 概述
@anchor{howto/unicode encodings}@anchor{4420}
@subsubsection 编码


上一段可以归结为：一个 Unicode 字符串是一系列码位（从 0 到 @code{0x10FFFF} 或者说十进制的 1,114,111 的数字）组成的序列。这一序列在内存中需被表示为一组 @strong{码元（code unit）} ， @strong{码元} 会映射成包含八个二进制位的字节。将 Unicode 字符串翻译成字节序列的规则称为 @strong{字符编码} ，或者 @strong{编码} 。

大家首先会想到的编码可能是用 32 位的整数作为代码位，然后采用 CPU 对 32 位整数的表示法。字符串 “Python” 用这种表示法可能会如下所示：

@example
   P           y           t           h           o           n
0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
@end example

这种表示法非常直白，但也存在 一些问题。


@enumerate 

@item 
不具可移植性；不同的处理器的字节序不同。

@item 
非常浪费空间。 在大多数文本中，大部分码位都小于 127 或 255，因此字节 @code{0x00} 占用了大量空间。相较于 ASCII 表示法所需的 6 个字节，以上字符串需要占用 24 个字节。RAM 用量的增加没那么要紧（台式计算机有成 GB 的 RAM，而字符串通常不会有那么大），但要把磁盘和网络带宽的用量增加 4 倍是无法忍受的。

@item 
与现有的 C 函数（如 @code{strlen()} ）不兼容，因此需要采用一套新的宽字符串函数。
@end enumerate

因此这种编码用得不多，人们转而选择其他更高效、更方便的编码，比如 UTF-8。

UTF-8 是最常用的编码之一，Python 往往默认会采用它。UTF 代表“Unicode Transformation Format”，'8' 表示编码采用 8 位数。（UTF-16 和 UTF-32 编码也是存在的，但其使用频率不如 UTF-8。）UTF-8 的规则如下：


@enumerate 

@item 
如果码位 < 128，则直接用对应的字节值表示。

@item 
如果码位  >= 128，则转换为 2、3、4 个字节的序列，每个字节值都位于 128 和 255 之间。
@end enumerate

UTF-8 有几个很方便的特性：


@enumerate 

@item 
可以处理任何 Unicode 码位。

@item 
Unicode 字符串被转换为一个字节序列，仅在表示空（null ）字符（U+0000）时才会包含零值的字节。这意味着 @code{strcpy()} 之类的C 函数可以处理 UTF-8 字符串，而且用那些不能处理字符串结束符之外的零值字节的协议也能发送。

@item 
ASCII 字符串也是也是也是合法的 UTF-8 文本。

@item 
UTF-8 相当紧凑；大多数常用字符均可用一两个字节表示。

@item 
如果字节数据被损坏或丢失，则可以找出下一个 UTF-8 码点的开始位置并重新开始同步。随机的 8 位数据也不太可能像是有效的 UTF-8 编码。

@item 
UTF-8 是一种面向字节的编码。编码规定了每个字符由一个或多个字节的序列表示。这避免了整数和双字节编码（如 UTF-16 和 UTF-32）可能出现的字节顺序问题，那时的字节序列会因执行编码的硬件而异。
@end enumerate

@node 引用文献<2>,,编码,Unicode 概述
@anchor{howto/unicode references}@anchor{4421}
@subsubsection 引用文献


Unicode Consortium 站点@footnote{https://www.unicode.org} 包含 Unicode 规范的字符图表、词汇表和 PDF 版本。请做好准备，有些内容读起来有点难度。该网站上还提供了 Unicode 起源和发展的`年表 <@indicateurl{https://www.unicode.org/history/}>`_ 。

在 Computerphile 的 Youtube 频道上，Tom Scott 简要地`讨论了 Unicode 和 UTF-8 <@indicateurl{https://www.youtube.com/watch?v=MijmeoH9LT4}>`_（9 分 36 秒）的历史。

为了帮助理解该标准，Jukka Korpela 编写了阅读 Unicode 字符表的`介绍性指南 <@indicateurl{http://jkorpela.fi/unicode/guide.html}>`_ 。

Joel Spolsky 撰写了另一篇不错的介绍性文章 <@indicateurl{https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character}- set-no-excuses/>`_ 。如果本文没让您弄清楚，那应在继续之前先试着读读这篇文章。

Wikipedia 条目通常也有帮助；请参阅“字符编码@footnote{https://en.wikipedia.org/wiki/Character_encoding}”和 UTF-8@footnote{https://en.wikipedia.org/wiki/UTF-8} 的条目，例如：

@node Python对Unicode的支持,Unicode 数据的读写,Unicode 概述,Unicode 指南
@anchor{howto/unicode python-s-unicode-support}@anchor{4422}
@subsection Python对Unicode的支持


现在您已经了解了 Unicode 的基础知识，可以看下 Python 的 Unicode 特性。

@menu
* 字符串类型:: 
* 转换为字节:: 
* Python 源代码中的 Unicode 文字:: 
* Unicode属性:: 
* 字符串比较:: 
* Unicode 正则表达式:: 
* 引用文献: 引用文献<3>. 

@end menu

@node 字符串类型,转换为字节,,Python对Unicode的支持
@anchor{howto/unicode the-string-type}@anchor{4423}
@subsubsection 字符串类型


从 Python 3.0 开始， @ref{206,,str} 类型包含了 Unicode 字符，这意味着用`@w{`}"unicode rocks!"@code{、}'unicode rocks!'`@w{`} 或三重引号字符串语法创建的任何字符串都会存储为 Unicode。

Python 源代码的默认编码是 UTF-8，因此可以直接在字符串中包含 Unicode 字符：

@example
try:
    with open('/tmp/input.txt', 'r') as f:
        ...
except OSError:
    # 'File not found' error message.
    print("Fichier non trouvé")
@end example

旁注：Python 3 还支持在标识符中使用 Unicode 字符：

@example
répertoire = "/tmp/records.log"
with open(répertoire, "w") as f:
    f.write("test\n")
@end example

如果无法在编辑器中输入某个字符，或出于某种原因想只保留 ASCII 编码的源代码，则还可以在字符串中使用转义序列。（根据系统的不同，可能会看到真的大写 Delta 字体而不是 u 转义符。）：

@example
>>> "\N@{GREEK CAPITAL LETTER DELTA@}"  # Using the character name
'\u0394'
>>> "\u0394"                          # Using a 16-bit hex value
'\u0394'
>>> "\U00000394"                      # Using a 32-bit hex value
'\u0394'
@end example

此外，可以用 @ref{172,,bytes} 的 @ref{171,,decode()} 方法创建一个字符串。 该方法可以接受 @emph{encoding} 参数，比如可以为 @code{UTF-8} ，以及可选的 @emph{errors} 参数。

若无法根据编码规则对输入字符串进行编码，@emph{errors} 参数指定了响应策略。 该参数的合法值可以是 @code{'strict'} (触发 @ref{332,,UnicodeDecodeError} 异常)、@code{'replace'} (用 @code{U+FFFD}、@code{REPLACEMENT CHARACTER})、@code{'ignore'} (只是将字符从 Unicode 结果中去掉)，或 @code{'backslashreplace'} (插入一个 @code{\xNN} 转义序列)。 以下示例演示了这些不同的参数:

@example
>>> b'\x80abc'.decode("utf-8", "strict")  
Traceback (most recent call last):
    ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
  invalid start byte
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "ignore")
'abc'
@end example

编码格式以包含编码格式名称的字符串来指明。 Python 有大约 100 种不同的编码格式；清单详见 Python 库参考文档 @ref{78c,,标准编码}。 一些编码格式有多个名称，比如 @code{'latin-1'}、@code{'iso_8859_1'} 和 @code{'8859} 都是指同一种编码。

利用内置函数 @ref{1589,,chr()} 还可以创建单字符的 Unicode 字符串，该函数可接受整数参数，并返回包含对应码位的长度为 1 的 Unicode 字符串。内置函数 @ref{1588,,ord()} 是其逆操作，参数为单个字符的 Unicode 字符串，并返回码位值：

@example
>>> chr(57344)
'\ue000'
>>> ord('\ue000')
57344
@end example

@node 转换为字节,Python 源代码中的 Unicode 文字,字符串类型,Python对Unicode的支持
@anchor{howto/unicode converting-to-bytes}@anchor{4424}
@subsubsection 转换为字节


@ref{171,,bytes.decode()} 的逆方法是 @ref{170,,str.encode()} ，它会返回 Unicode 字符串的 @ref{172,,bytes} 形式，已按要求的 @emph{encoding} 进行了编码。

参数 @emph{errors} 的意义与 @ref{171,,decode()} 方法相同，但支持更多可能的handler。除了 @code{'strict'} 、 @code{'ignore'} 和 @code{'replace'} （这时会插入问号替换掉无法编码的字符），还有 @code{'xmlcharrefreplace'} （插入一个 XML 字符引用）、 @code{backslashreplace} （插入一个 @code{\uNNNN} 转义序列）和  @code{namereplace} （插入一个 @code{\N@{...@}} 转义序列 ）。

以下例子演示了各种不同的结果：

@example
>>> u = chr(40960) + 'abcd' + chr(1972)
>>> u.encode('utf-8')
b'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')  
Traceback (most recent call last):
    ...
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
  position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
b'abcd'
>>> u.encode('ascii', 'replace')
b'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
b'&#40960;abcd&#1972;'
>>> u.encode('ascii', 'backslashreplace')
b'\\ua000abcd\\u07b4'
>>> u.encode('ascii', 'namereplace')
b'\\N@{YI SYLLABLE IT@}abcd\\u07b4'
@end example

用于注册和访问可用编码格式的底层函数，位于 @ref{1b,,codecs} 模块中。 若要实现新的编码格式，则还需要了解 @ref{1b,,codecs} 模块。 不过该模块返回的编码和解码函数通常更为底层一些，不大好用，编写新的编码格式是一项专业的任务，因此本文不会涉及该模块。

@node Python 源代码中的 Unicode 文字,Unicode属性,转换为字节,Python对Unicode的支持
@anchor{howto/unicode unicode-literals-in-python-source-code}@anchor{4425}
@subsubsection Python 源代码中的 Unicode 文字


在 Python 源代码中，可以用 @code{\u} 转义序列书写特定的 Unicode 码位，该序列后跟 4 个代表码位的十六进制数字。@code{\U} 转义序列用法类似，但要用8 个十六进制数字，而不是 4 个：

@example
>>> s = "a\xac\u1234\u20ac\U00008000"
... #     ^^^^ two-digit hex escape
... #         ^^^^^^ four-digit Unicode escape
... #                     ^^^^^^^^^^ eight-digit Unicode escape
>>> [ord(c) for c in s]
[97, 172, 4660, 8364, 32768]
@end example

对大于 127 的码位使用转义序列，数量不多时没什么问题，但如果要用到很多重音字符，这会变得很烦人，类似于程序中的信息是用法语或其他使用重音的语言写的。也可以用内置函数 @ref{1589,,chr()} 拼装字符串，但会更加乏味。

理想情况下，都希望能用母语的编码书写文本。还能用喜好的编辑器编辑 Python 源代码，编辑器要能自然地显示重音符，并在运行时使用正确的字符。

默认情况下，Python 支持以 UTF-8 格式编写源代码，但如果声明要用的编码，则几乎可以使用任何编码。只要在源文件的第一行或第二行包含一个特殊注释即可：

@example
#!/usr/bin/env python
# -*- coding: latin-1 -*-

u = 'abcdé'
print(ord(u[-1]))
@end example

上述语法的灵感来自于 Emacs 用于指定文件局部变量的符号。Emacs 支持许多不同的变量，但 Python 仅支持“编码”。 @code{-*-} 符号向 Emacs 标明该注释是特殊的；这对 Python 没有什么意义，只是一种约定。Python 会在注释中查找 @code{coding: name} 或 @code{coding=name} 。

如果没有这种注释，则默认编码将会是前面提到的 UTF-8。更多信息请参阅 
@geindex Python 提高建议; PEP 263
PEP 263@footnote{https://www.python.org/dev/peps/pep-0263} 。

@node Unicode属性,字符串比较,Python 源代码中的 Unicode 文字,Python对Unicode的支持
@anchor{howto/unicode unicode-properties}@anchor{4426}
@subsubsection Unicode属性


Unicode 规范包含了一个码位信息数据库。对于定义的每一个码位，都包含了字符的名称、类别、数值（对于表示数字概念的字符，如罗马数字、分数如三分之一和五分之四等）。还有有关显示的属性，比如如何在双向文本中使用码位。

以下程序显示了几个字符的信息，并打印一个字符的数值：

@example
import unicodedata

u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)

for i, c in enumerate(u):
    print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
    print(unicodedata.name(c))

# Get numeric value of second character
print(unicodedata.numeric(u[1]))
@end example

当运行时，这将打印出：

@example
0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
1 0bf2 No TAMIL NUMBER ONE THOUSAND
2 0f84 Mn TIBETAN MARK HALANTA
3 1770 Lo TAGBANWA LETTER SA
4 33af So SQUARE RAD OVER S SQUARED
1000.0
@end example

类别代码是描述字符性质的一个缩写。分为“字母”、“数字”、“标点符号”或“符号”等类别，而这些类别又分为子类别。就以上输出的代码而言，@code{'Ll'} 表示“字母，小写”，@code{'No'} 表示“数字，其他”，@code{'Mn'} 表示“标记，非空白符” ,  @code{'So'} 是“符号，其他”。有关类别代码的清单，请参阅 Unicode 字符库文档 <@indicateurl{https://www.unicode.org/reports/tr44/#General_Category_Values}>`_ 的“通用类别值”部分。

@node 字符串比较,Unicode 正则表达式,Unicode属性,Python对Unicode的支持
@anchor{howto/unicode comparing-strings}@anchor{4427}
@subsubsection 字符串比较


Unicode 让字符串的比较变得复杂了一些，因为同一组字符可能由不同的码位序列组成。例如，像“ê”这样的字母可以表示为单码位 U+00EA，或是 U+0065 U+0302，即“e”的码位后跟“COMBINING CIRCUMFLEX ACCENT”的码位。虽然在打印时会产生同样的输出，但一个是长度为 1 的字符串，另一个是长度为 2 的字符串。

一种不区分大小写比较的工具是字符串方法 @ref{7ad,,casefold()} ，将按照 Unicode 标准描述的算法将字符串转换为不区分大小写的形式。该算法对诸如德语字母“ß”（代码点 U+00DF）之类的字符进行了特殊处理，变为一对小写字母“ss”。

@example
>>> street = 'Gürzenichstraße'
>>> street.casefold()
'gürzenichstrasse'
@end example

第二个工具是 @ref{123,,unicodedata} 模块的 @ref{122c,,normalize()} 函数，将字符串转换为几种规范化形式之一，其中后跟组合字符的字母将被替换为单个字符。 @code{normalize()} 可用于执行字符串比较，即便两个字符串采用不同的字符组合，也不会错误地报告两者不相等：

@example
import unicodedata

def compare_strs(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(s1) == NFD(s2)

single_char = 'ê'
multiple_chars = '\N@{LATIN SMALL LETTER E@}\N@{COMBINING CIRCUMFLEX ACCENT@}'
print('length of first string=', len(single_char))
print('length of second string=', len(multiple_chars))
print(compare_strs(single_char, multiple_chars))
@end example

当运行时，这将输出：

@example
$ python3 compare-strs.py
length of first string= 1
length of second string= 2
True
@end example

@ref{122c,,normalize()} 函数的第一个参数是个字符串，给出所需的规范化形式，可以是“NFC”、“NFKC”、“NFD”和“NFKD”之一。

Unicode 标准还设定了如何进行不区分大小写的比较：

@example
import unicodedata

def compare_caseless(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())

# Example usage
single_char = 'ê'
multiple_chars = '\N@{LATIN CAPITAL LETTER E@}\N@{COMBINING CIRCUMFLEX ACCENT@}'

print(compare_caseless(single_char, multiple_chars))
@end example

这将打印 @code{True} 。（为什么 @code{NFD()} 会被调用两次？因为有几个字符让 @code{casefold()} 返回非规范化的字符串，所以结果需要再次进行规范化。参见 Unicode 标准的 3.13 节 的一个讨论和示例。）

@node Unicode 正则表达式,引用文献<3>,字符串比较,Python对Unicode的支持
@anchor{howto/unicode unicode-regular-expressions}@anchor{4428}
@subsubsection Unicode 正则表达式


@ref{dd,,re} 模块支持的正则表达式可以用字节串或字符串的形式提供。有一些特殊字符序列，比如 @code{\d} 和 @code{\w} 具有不同的含义，具体取决于匹配模式是以字节串还是字符串形式提供的。例如，@code{\d} 将匹配字节串中的字符 @code{[0-9]} ，但对于字符串将会匹配 @code{'Nd'} 类别中的任何字符。

上述示例中的字符串包含了泰语和阿拉伯数字书写的数字 57：

@example
import re
p = re.compile(r'\d+')

s = "Over \u0e55\u0e57 57 flavours"
m = p.search(s)
print(repr(m.group()))
@end example

执行时，@code{\d+} 将匹配上泰语数字并打印出来。如果向  @ref{555,,compile()} 提供的是 @ref{4d7,,re.ASCII} 标志，@code{\d+} 则会匹配子串 "57"。

类似地，@code{\w}  将匹配多种 Unicode 字符，但对于字节串则只会匹配 @code{[a-zA-Z0-9_]} ，如果指定 @ref{4d7,,re.ASCII}， @code{\s `@w{`} 将匹配 Unicode 空白符或 `@w{`}[ \t\n\r\f\v]}。

@node 引用文献<3>,,Unicode 正则表达式,Python对Unicode的支持
@anchor{howto/unicode id2}@anchor{4429}
@subsubsection 引用文献


@c comment should these be mentioned earlier, e.g. at the start of the "introduction to Unicode" first section?

关于 Python 的 Unicode 支持，其他还有一些很好的讨论：


@itemize *

@item 
用 Python 3 处理文本文件@footnote{http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html} ，作者 Nick Coghlan。

@item 
实用的 Unicode@footnote{https://nedbatchelder.com/text/unipain.html}，Ned Batchelder 在 PyCon 2012 上的演示。
@end itemize

@ref{206,,str} 类型在 Python 库参考文档 @ref{1386,,文本序列类型 --- str} 中有介绍。

@ref{123,,unicodedata} 模块的文档

@ref{1b,,codecs} 模块的文档

Marc-André Lemburg 在 EuroPython 2002 上做了一个题为“Python 和 Unicode”（PDF 幻灯片）<@indicateurl{https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf}>`_ 的演示文稿。该幻灯片很好地概括了 Python 2 的 Unicode 功能设计（其中 Unicode 字符串类型称为 @code{unicode}，文字以 @code{u} 开头）。

@node Unicode 数据的读写,致谢<10>,Python对Unicode的支持,Unicode 指南
@anchor{howto/unicode reading-and-writing-unicode-data}@anchor{442a}
@subsection Unicode 数据的读写


既然处理 Unicode 数据的代码写好了，下一个问题就是输入/输出了。如何将 Unicode 字符串读入程序，如何将 Unicode 转换为适于存储或传输的形式呢？

根据输入源和输出目标的不同，或许什么都不用干；请检查一下应用程序用到的库是否原生支持 Unicode。例如，XML 解析器往往会返回 Unicode 数据。许多关系数据库的字段也支持 Unicode 值，并且 SQL 查询也能返回 Unicode 值。

在写入磁盘或通过套接字发送之前，Unicode 数据通常要转换为特定的编码。可以自己完成所有工作：打开一个文件，从中读取一个 8 位字节对象，然后用 @code{bytes.decode(encoding)} 对字节串进行转换。但是，不推荐采用这种全人工的方案。

编码的多字节特性就是一个难题； 一个 Unicode 字符可以用几个字节表示。 如果要以任意大小的块（例如 1024 或 4096 字节）读取文件，那么在块的末尾可能只读到某个 Unicode 字符的部分字节，这就需要编写错误处理代码。 有一种解决方案是将整个文件读入内存，然后进行解码，但这样就没法处理很大的文件了；若要读取 2 GB 的文件，就需要 2 GB 的 RAM。（其实需要的内存会更多些，因为至少有一段时间需要在内存中同时存放已编码字符串及其 Unicode 版本。）

解决方案是利用底层解码接口去捕获编码序列不完整的情况。这部分代码已经是现成的：内置函数 @ref{16f,,open()} 可以返回一个文件类的对象，该对象认为文件的内容采用指定的编码，@ref{2192,,read()} 和 @ref{2195,,write()} 等方法接受 Unicode 参数。只要用 @ref{16f,,open()} 的 @emph{encoding} 和 @emph{errors} 参数即可，参数释义同 @ref{170,,str.encode()} 和 @ref{171,,bytes.decode()} 。

因此从文件读取 Unicode 就比较简单了：

@example
with open('unicode.txt', encoding='utf-8') as f:
    for line in f:
        print(repr(line))
@end example

也可以在更新模式下打开文件，以便同时读取和写入：

@example
with open('test', encoding='utf-8', mode='w+') as f:
    f.write('\u4500 blah blah blah\n')
    f.seek(0)
    print(repr(f.readline()[:1]))
@end example

Unicode 字符 @code{U+FEFF} 用作字节顺序标记（BOM），通常作为文件的第一个字符写入，以帮助自动检测文件的字节顺序。某些编码（例如 UTF-16）期望在文件开头出现 BOM；当采用这种编码时，BOM 将自动作为第一个字符写入，并在读取文件时会静默删除。这些编码有多种变体，例如用于 little-endian 和 big-endian 编码的 “utf-16-le” 和 “utf-16-be”，会指定一种特定的字节顺序并且不会忽略 BOM。

在某些地区，习惯在 UTF-8 编码文件的开头用上“BOM”；此名称具有误导性，因为 UTF-8 与字节顺序无关。此标记只是声明该文件以 UTF-8 编码。要读取此类文件，请使用“utf-8-sig”编解码器自动忽略此标记。

@menu
* Unicode 文件名:: 
* 识别 Unicode 的编程技巧:: 
* 引用文献: 引用文献<4>. 

@end menu

@node Unicode 文件名,识别 Unicode 的编程技巧,,Unicode 数据的读写
@anchor{howto/unicode unicode-filenames}@anchor{442b}
@subsubsection Unicode 文件名


当今大多数操作系统的文件名都支持包含任意 Unicode 字符。通常这是通过将 Unicode 字符串转换为某系统的编码来实现的。如今的 Python 趋向于采用 UTF-8 编码：MacOS 上的 Python 已经在多个版本中采用了 UTF-8，而 Python 3.6 在 Windows 上也改用了 UTF-8。在 Unix 系统中，只有设置了 @code{LANG} 或 @code{LC_CTYPE} 环境变量，才会采用某个文件系统编码；否则默认编码还是 UTF-8。

@ref{5f8,,sys.getfilesystemencoding()} 函数将返回要在当前系统采用的编码，若想手动进行编码时即可用到，但无需多虑。在打开文件进行读写时，通常只需提供 Unicode 字符串作为文件名，会自动转换为合适的编码格式：

@example
filename = 'filename\u4500abc'
with open(filename, 'w') as f:
    f.write('blah\n')
@end example

@ref{c4,,os} 模块中的函数也能接受 Unicode 文件名，如 @ref{328,,os.stat()} 。

@ref{b25,,os.listdir()} 函数将返回文件名，这会引发一个难题：到底应返回文件名的 Unicode 版本，还是应返回已编码的字节串呢？这两种操作 @ref{b25,,os.listdir()} 均可执行，具体取决于给出的目录路径是字节串形式还是 Unicode 字符串。若传入一个 Unicode 字符串作为路径，文件名将用当前文件系统的编码进行解码并返回一个 Unicode 字符串列表，而若传入一个字节串路径则会返回字节串格式的文件名。以下假定默认文件系统编码为 UTF-8，运行以下程序：

@example
fn = 'filename\u4500abc'
f = open(fn, 'w')
f.close()

import os
print(os.listdir(b'.'))
print(os.listdir('.'))
@end example

将产生以下输出：

@example
$ python listdir-test.py
[b'filename\xe4\x94\x80abc', ...]
['filename\u4500abc', ...]
@end example

第一个列表包含 UTF-8 编码的文件名，第二个列表则包含 Unicode 版本的。

请注意，大多时候应该坚持用这些 API 处理 Unicode。字节串 API 应该仅用于可能存在不可解码文件名的系统；现在几乎仅剩 Unix 系统了。

@node 识别 Unicode 的编程技巧,引用文献<4>,Unicode 文件名,Unicode 数据的读写
@anchor{howto/unicode tips-for-writing-unicode-aware-programs}@anchor{442c}
@subsubsection 识别 Unicode 的编程技巧


本节提供了一些关于编写 Unicode 处理软件的建议。

最重要的技巧如下：

@quotation

程序应只在内部处理 Unicode 字符串，尽快对输入数据进行解码，并只在最后对输出进行编码。
@end quotation

如果尝试编写的处理函数对 Unicode 和字节串形式的字符串都能接受，就会发现组合使用两种不同类型的字符串时，容易产生差错。没办法做到自动编码或解码：如果执行 @code{str + bytes}，则会触发 @ref{1ff,,TypeError}。

当要使用的数据来自 Web 浏览器或其他不受信来源时，常用技术是在用该字符串生成命令行之前，或要存入数据库之前，先检查字符串中是否包含非法字符。请仔细检查解码后的字符串，而不是编码格式的字节串数据；有些编码可能具备一些有趣的特性，例如与 ASCII 不是一一对应或不完全兼容。如果输入数据还指定了编码格式，则尤其如此，因为攻击者可以选择一种巧妙的方式将恶意文本隐藏在经过编码的字节流中。

@menu
* 在文件编码格式之间进行转换:: 
* 编码格式未知的文件:: 

@end menu

@node 在文件编码格式之间进行转换,编码格式未知的文件,,识别 Unicode 的编程技巧
@anchor{howto/unicode converting-between-file-encodings}@anchor{442d}
@subsubsection 在文件编码格式之间进行转换


@ref{1151,,StreamRecoder} 类可以在两种编码之间透明地进行转换，参数为编码格式为 #1 的数据流，表现行为则是编码格式为 #2 的数据流。

假设输入文件 @emph{f} 采用 Latin-1 编码格式，即可用 @ref{1151,,StreamRecoder} 包装后返回 UTF-8 编码的字节串：

@example
new_f = codecs.StreamRecoder(f,
    # en/decoder: used by read() to encode its results and
    # by write() to decode its input.
    codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),

    # reader/writer: used to read and write to the stream.
    codecs.getreader('latin-1'), codecs.getwriter('latin-1') )
@end example

@node 编码格式未知的文件,,在文件编码格式之间进行转换,识别 Unicode 的编程技巧
@anchor{howto/unicode files-in-an-unknown-encoding}@anchor{442e}
@subsubsection 编码格式未知的文件


若需对文件进行修改，但不知道文件的编码，那该怎么办呢？如果已知编码格式与 ASCII 兼容，并且只想查看或修改 ASCII 部分，则可利用 @code{surrogateescape} 错误处理 handler 打开文件：

@example
with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

# make changes to the string 'data'

with open(fname + '.new', 'w',
          encoding="ascii", errors="surrogateescape") as f:
    f.write(data)
@end example

@code{surrogateescape} 错误处理 handler 会把所有非 ASCII 字节解码为 U+DC80 至 U+DCFF 这一特殊范围的码位。当 @code{surrogateescape} 错误处理 handler用于数据编码并回写时，这些码位将转换回原样。

@node 引用文献<4>,,识别 Unicode 的编程技巧,Unicode 数据的读写
@anchor{howto/unicode id3}@anchor{442f}
@subsubsection 引用文献


David Beazley 在 PyCon 2010 上的演讲 掌握 Python 3 输入/输出@footnote{http://pyvideo.org/video/289/pycon-2010--mastering-python-3-io} 中，有一节讨论了文本和二进制数据的处理。

Marc-André Lemburg 演示的PDF 幻灯片“在 Python 中编写支持 Unicode 的应用程序”@footnote{https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf} ，讨论了字符编码问题以及如何国际化和本地化应用程序。这些幻灯片仅涵盖 Python 2.x。

Python Unicode 实质@footnote{http://pyvideo.org/video/1768/the-guts-of-unicode-in-python} 是 Benjamin Peterson 在 PyCon 2013 上的演讲，讨论了 Unicode  在 Python 3.3 中的内部表示。

@node 致谢<10>,,Unicode 数据的读写,Unicode 指南
@anchor{howto/unicode acknowledgements}@anchor{4430}
@subsection 致谢


本文初稿由 Andrew Kuchling 撰写。此后，Alexander Belopolsky、Georg Brandl、Andrew Kuchling 和 Ezio Melotti 作了进一步修订。

感谢以下各位指出本文错误或提出建议：Éric Araujo、Nicholas Bastin、Nick Coghlan、Marius Gedminas、Kent Johnson、Ken Krugler、Marc-André Lemburg、Martin von Löwis、Terry J. Reedy、Serhiy Storchaka , Eryk Sun, Chad Whitacre, Graham Wideman。

@node 如何利用 urllib 包获取网络资源,Argparse 教程,Unicode 指南,Python 常用指引
@anchor{howto/urllib2 doc}@anchor{4431}@anchor{howto/urllib2 howto-fetch-internet-resources-using-the-urllib-package}@anchor{4432}@anchor{howto/urllib2 urllib-howto}@anchor{2daf}
@section 如何利用 urllib 包获取网络资源


@*作者: 
Michael Foord@footnote{http://www.voidspace.org.uk/python/index.shtml}


@cartouche
@quotation 注解 
这份 HOWTO 文档的早期版本有一份法语的译文，可在 urllib2 - Le Manuel manquant@footnote{http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml} 处查阅。
@end quotation
@end cartouche

@menu
* 概述: 概述<19>. 
* 获取 URL 资源:: 
* 异常的处理:: 
* info 和 geturl 方法:: 
* Opener 和 Handler:: 
* 基本认证:: 
* 代理:: 
* 套接字与分层:: 
* 脚注:: 

@end menu

@node 概述<19>,获取 URL 资源,,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 introduction}@anchor{4433}
@subsection 概述


@subsubheading Related Articles



关于如何用 Python 获取 web 资源，以下文章或许也很有用：


@itemize *

@item 
基础的身份认证@footnote{http://www.voidspace.org.uk/python/articles/authentication.shtml}

@quotation

@emph{基本认证} 的教程，带有一些 Python 示例。
@end quotation
@end itemize

@strong{urllib.request} 是用于获取 URL （统一资源定位符）的 Python 模块。它以 @emph{urlopen} 函数的形式提供了一个非常简单的接口，能用不同的协议获取 URL。同时它还为处理各种常见情形提供了一个稍微复杂一些的接口——比如：基础身份认证、cookies、代理等等。这些功能是由名为 handlers 和 opener 的对象提供的。

urllib.request 支持多种  "URL 方案" （通过 URL中 @code{":"} 之前的字符串加以区分——如 @code{"ftp://python.org/"` 中的 `@w{`}"ftp"`}）即为采用其关联网络协议（FTP、HTTP 之类）的 URL 方案 。本教程重点关注最常用的 HTTP 场景。

对于简单场景而言， @emph{urlopen} 用起来十分容易。但只要在打开 HTTP URL 时遇到错误或非常情况，就需要对超文本传输协议有所了解才行。最全面、最权威的 HTTP 参考是 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 。那是一份技术文档，并没有追求可读性。本 文旨在说明 @emph{urllib} 的用法，为了便于阅读也附带了足够详细的 HTTP 信息。本文并不是为了替代 @ref{129,,urllib.request} 文档，只是其补充说明而已。

@node 获取 URL 资源,异常的处理,概述<19>,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 fetching-urls}@anchor{4434}
@subsection 获取 URL 资源


urllib.request 最简单的使用方式如下所示：

@example
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()
@end example

如果想通过 URL 获取资源并临时存储一下，可以采用 @ref{38e,,shutil.copyfileobj()} 和 @ref{e16,,tempfile.NamedTemporaryFile()} 函数：

@example
import shutil
import tempfile
import urllib.request

with urllib.request.urlopen('http://python.org/') as response:
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        shutil.copyfileobj(response, tmp_file)

with open(tmp_file.name) as html:
    pass
@end example

urllib 的很多用法就是这么简单（注意 URL 不仅可以 http: 开头，还可以是 ftp: 、file: 等）。不过本教程的目的是介绍更加复杂的应用场景，重点还是关注 HTTP。

HTTP 以请求和响应为基础——客户端生成请求，服务器发送响应。urllib.request 用 @code{Request} 对象来表示要生成的 HTTP 请求。最简单的形式就是创建一个 Request 对象，指定了想要获取的 URL。用这个 Request 对象作为参数调用`@w{`}urlopen`@w{`} ，将会返回该 URL 的响应对象。响应对象类似于文件对象，就是说可以对其调用 @code{.read()} 之类的命令：

@example
import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

请注意，urllib.request 用同一个 Request 接口处理所有 URL 方案。比如可生成 FTP 请求如下：

@example
req = urllib.request.Request('ftp://example.com/')
@end example

就 HTTP 而言，Request 对象能够做两件额外的事情：首先可以把数据传给服务器。其次，可以将 @emph{有关} 数据或请求本身的额外信息（metadata）传给服务器——这些信息将会作为 HTTP “头部”数据发送。下面依次看下。

@menu
* 数据:: 
* HTTP 头部信息:: 

@end menu

@node 数据,HTTP 头部信息,,获取 URL 资源
@anchor{howto/urllib2 data}@anchor{4435}
@subsubsection 数据


有时需要向某个 URL 发送数据，通常此 URL 会指向某个CGI（通用网关接口）脚本或其他 web 应用。对于 HTTP 而言，这通常会用所谓的 @strong{POST} 请求来完成。当要把 Web 页填写的 HTML 表单提交时，浏览器通常会执行此操作。但并不是所有的 POST 都来自表单：可以用 POST 方式传输任何数据到自己的应用上。对于通常的 HTML 表单，数据需要以标准的方式编码，然后作为 @code{data} 参数传给 Request 对象。编码过程是用 @ref{128,,urllib.parse} 库的函数完成的：

@example
import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = @{'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' @}

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

请注意，有时还需要采用其他编码，比如由 HTML 表单上传文件——更多细节请参见 HTML 规范，提交表单@footnote{https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13} 。

如果不传递 @code{data} 参数，urllib 将采用 @strong{GET} 请求。GET 和 POST 请求有一点不同，POST 请求往往具有“副作用”，他们会以某种方式改变系统的状态。例如，从网站下一个订单，购买一大堆罐装垃圾并运送到家。 尽管 HTTP 标准明确指出 POST @emph{总是} 要导致副作用，而 GET 请求 @emph{从来不会} 导致副作用。但没有什么办法能阻止 GET 和 POST 请求的副作用。数据也可以在 HTTP GET 请求中传递，只要把数据编码到 URL 中即可。

做法如下所示：

@example
>>> import urllib.request
>>> import urllib.parse
>>> data = @{@}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.  
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)
@end example

请注意，完整的 URL 是通过在其中添加 @code{?} 创建的，后面跟着经过编码的数据。

@node HTTP 头部信息,,数据,获取 URL 资源
@anchor{howto/urllib2 headers}@anchor{4436}
@subsubsection HTTP 头部信息


下面介绍一个具体的 HTTP 头部信息，以此说明如何在 HTTP 请求加入头部信息。

有些网站 @footnote{@w{(1)} 
例如 Google。
} 不愿被程序浏览到，或者要向不同的浏览器发送不同版本 @footnote{@w{(2)} 
对于网站设计而言，探测不同的浏览器是非常糟糕的做法——更为明智的做法是采用 web 标准构建网站。不幸的是，很多网站依然向不同的浏览器发送不同版本的网页。
} 的网页。默认情况下，urllib 将自身标识为“Python-urllib/xy”（其中 @code{x} 、 @code{y} 是 Python 版本的主、次版本号，例如  @code{Python-urllib/2.5}），这可能会让网站不知所措，或者干脆就使其无法正常工作。浏览器是通过头部信息 @code{User-Agent} @footnote{@w{(3)} 
MSIE 6 的 user-agent 信息是 @emph{“Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)”}
} 来标识自己的。在创建 Request 对象时，可以传入字典形式的头部信息。以下示例将生成与之前相同的请求，只是将自身标识为某个版本的 Internet Explorer @footnote{@w{(4)} 
有关 HTTP 请求的头部信息，详情请参阅 @ref{4437,,Quick Reference to HTTP Headers}。
} ：

@example
import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = @{'name': 'Michael Foord',
          'location': 'Northampton',
          'language': 'Python' @}
headers = @{'User-Agent': user_agent@}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
   the_page = response.read()
@end example

响应对象也有两个很有用的方法。请参阅有关 @ref{4438,,info 和 geturl} 部分，了解出现问题时会发生什么。

@node 异常的处理,info 和 geturl 方法,获取 URL 资源,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 handling-exceptions}@anchor{4439}
@subsection 异常的处理


如果 @emph{urlopen} 无法处理响应信息，就会触发 @code{URLError} 。尽管与通常的 Python API 一样，也可能触发 @ref{16d,,ValueError} 、 @ref{1ff,,TypeError} 等内置异常。

@code{HTTPError} 是 @code{URLError} 的子类，当 URL 是 HTTP 的情况时将会触发。

上述异常类是从 @ref{127,,urllib.error} 模块中导出的。

@menu
* URLError:: 
* HTTPError:: 
* 总之:: 

@end menu

@node URLError,HTTPError,,异常的处理
@anchor{howto/urllib2 urlerror}@anchor{443a}
@subsubsection URLError


触发 URLError 的原因，通常是网络不通（或者没有到指定服务器的路由），或者指定的服务器不存在。这时触发的异常会带有一个 reason 属性，是一个包含错误代码和文本错误信息的元组。

例如：

@example
>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...     print(e.reason)      
...
(4, 'getaddrinfo failed')
@end example

@node HTTPError,总之,URLError,异常的处理
@anchor{howto/urllib2 httperror}@anchor{443b}
@subsubsection HTTPError


从服务器返回的每个 HTTP 响应都包含一个数字的 “状态码”。有时该状态码表明服务器无法完成该请求。默认的处理函数将会处理这其中的一部分响应。如若响应是“redirection”，这是要求客户端从另一 URL 处获取数据，urllib 将会自行处理。对于那些无法处理的状况，urlopen 将会引发  @code{HTTPError} 。典型的错误包括：“404”（页面无法找到）、“403”（请求遭拒绝）和“401”（需要身份认证）。

全部的 HTTP 错误码请参阅 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 。

@code{HTTPError} 实例将包含一个整数型的“code”属性，对应于服务器发来的错误。

@menu
* 错误代码:: 

@end menu

@node 错误代码,,,HTTPError
@anchor{howto/urllib2 error-codes}@anchor{443c}
@subsubsection 错误代码


由于默认处理函数会自行处理重定向（300 以内的错误码），而且 100--299 的状态码表示成功，因此通常只会出现 400--599 的错误码。

@ref{2ddb,,http.server.BaseHTTPRequestHandler.responses} 是很有用的响应码字典，其中给出了 
@geindex RFC; RFC 2616
RFC 2616@footnote{https://tools.ietf.org/html/rfc2616.html} 用到的所有响应代码。为方便起见，将此字典转载如下：

@example
# Table mapping response codes to messages; entries have the
# form @{code: (shortmessage, longmessage)@}.
responses = @{
    100: ('Continue', 'Request received, please continue'),
    101: ('Switching Protocols',
          'Switching to new protocol; obey Upgrade header'),

    200: ('OK', 'Request fulfilled, document follows'),
    201: ('Created', 'Document created, URL follows'),
    202: ('Accepted',
          'Request accepted, processing continues off-line'),
    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
    204: ('No Content', 'Request fulfilled, nothing follows'),
    205: ('Reset Content', 'Clear input form for further input.'),
    206: ('Partial Content', 'Partial content follows.'),

    300: ('Multiple Choices',
          'Object has several resources -- see URI list'),
    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
    302: ('Found', 'Object moved temporarily -- see URI list'),
    303: ('See Other', 'Object moved -- see Method and URL list'),
    304: ('Not Modified',
          'Document has not changed since given time'),
    305: ('Use Proxy',
          'You must use proxy specified in Location to access this '
          'resource.'),
    307: ('Temporary Redirect',
          'Object moved temporarily -- see URI list'),

    400: ('Bad Request',
          'Bad request syntax or unsupported method'),
    401: ('Unauthorized',
          'No permission -- see authorization schemes'),
    402: ('Payment Required',
          'No payment -- see charging schemes'),
    403: ('Forbidden',
          'Request forbidden -- authorization will not help'),
    404: ('Not Found', 'Nothing matches the given URI'),
    405: ('Method Not Allowed',
          'Specified method is invalid for this server.'),
    406: ('Not Acceptable', 'URI not available in preferred format.'),
    407: ('Proxy Authentication Required', 'You must authenticate with '
          'this proxy before proceeding.'),
    408: ('Request Timeout', 'Request timed out; try again later.'),
    409: ('Conflict', 'Request conflict.'),
    410: ('Gone',
          'URI no longer exists and has been permanently removed.'),
    411: ('Length Required', 'Client must specify Content-Length.'),
    412: ('Precondition Failed', 'Precondition in headers is false.'),
    413: ('Request Entity Too Large', 'Entity is too large.'),
    414: ('Request-URI Too Long', 'URI is too long.'),
    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
    416: ('Requested Range Not Satisfiable',
          'Cannot satisfy request range.'),
    417: ('Expectation Failed',
          'Expect condition could not be satisfied.'),

    500: ('Internal Server Error', 'Server got itself in trouble'),
    501: ('Not Implemented',
          'Server does not support this operation'),
    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
    503: ('Service Unavailable',
          'The server cannot process the request due to a high load'),
    504: ('Gateway Timeout',
          'The gateway server did not receive a timely response'),
    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
    @}
@end example

当触发错误时，服务器通过返回 HTTP 错误码 @emph{和} 错误页面进行响应。可以将 @code{HTTPError} 实例用作返回页面的响应。这意味着除了 code 属性之外，错误对象还像 @code{urllib.response} 模块返回的那样具有 read、geturl 和 info 方法：

@example
>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())  
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
  ...
  <title>Page Not Found</title>\n
  ...
@end example

@node 总之,,HTTPError,异常的处理
@anchor{howto/urllib2 wrapping-it-up}@anchor{443d}
@subsubsection 总之


若要准备处理 @code{HTTPError}  @emph{或} @code{URLError} ，有两种简单的方案。推荐使用第二种方案。

@menu
* 第一种方案:: 
* 第二种方案:: 

@end menu

@node 第一种方案,第二种方案,,总之
@anchor{howto/urllib2 number-1}@anchor{443e}
@subsubsection 第一种方案


@example
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # everything is fine
@end example

@cartouche
@quotation 注解 
@code{except HTTPError} @emph{必须} 首先处理，否则 @code{except URLError} 将会 @emph{同时} 捕获  @code{HTTPError} 。
@end quotation
@end cartouche

@node 第二种方案,,第一种方案,总之
@anchor{howto/urllib2 number-2}@anchor{443f}
@subsubsection 第二种方案


@example
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
else:
    # everything is fine
@end example

@node info 和 geturl 方法,Opener 和 Handler,异常的处理,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 info-and-geturl}@anchor{4438}
@subsection info 和 geturl 方法


由 urlopen （或者 @code{HTTPError} 实例）所返回的响应包含两个有用的方法： @code{info()} 和 @code{geturl()}，该响应由模块 @ref{12a,,urllib.response} 定义。

@strong{geturl} ——返回所获取页面的真实 URL。该方法很有用，因为 @code{urlopen} （或 opener 对象）可能已经经过了一次重定向。已获取页面的 URL 未必就是所请求的 URL 。

@strong{info} - 该方法返回一个类似字典的对象，描述了所获取的页面，特别是由服务器送出的头部信息（headers） 。目前它是一个 @code{http.client.HTTPMessage} 实例。

典型的 HTTP  头部信息包括“Content-length”、“Content-type”等。有关 HTTP 头部信息的清单，包括含义和用途的简要说明，请参阅 HTTP Header 快速参考@footnote{http://jkorpela.fi/http.html} 。

@node Opener 和 Handler,基本认证,info 和 geturl 方法,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 openers-and-handlers}@anchor{4440}
@subsection Opener 和 Handler


当获取 URL 时，会用到了一个 opener（一个类名可能经过混淆的 @ref{2d38,,urllib.request.OpenerDirector} 的实例）。通常一直会用默认的 opener   ——通过 @code{urlopen} ——但也可以创建自定义的 opener 。opener 会用到 handler。所有的“繁重工作”都由 handler 完成。每种 handler 知道某种 URL 方案（http、ftp 等）的 URL 的打开方式，或是某方面 URL 的打开方式，例如 HTTP 重定向或 HTTP cookie。

若要用已安装的某个 handler 获取 URL，需要创建一个 opener 对象，例如处理 cookie 的 opener，或对重定向不做处理的 opener。

若要创建 opener，请实例化一个 @code{OpenerDirector} ，然后重复调用 @code{.add_handler(some_handler_instance)} 。

或者也可以用 @code{build_opener} ，这是个用单次调用创建 opener 对象的便捷函数。@code{build_opener} 默认会添加几个  handler，不过还提供了一种快速添加和/或覆盖默认 handler 的方法。

可能还需要其他类型的 handler，以便处理代理、身份认证和其他常见但稍微特殊的情况。

@code{install_opener} 可用于让 @code{opener} 对象成为（全局）默认 opener。这意味着调用 @code{urlopen} 时会采用已安装的 opener。

opener 对象带有一个 @code{`open} 方法，可供直接调用以获取 url，方式与 @code{urlopen} 函数相同。除非是为了调用方便，否则没必要去调用 @code{install_opener} 。

@node 基本认证,代理,Opener 和 Handler,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 id5}@anchor{4441}
@subsection 基本认证


为了说明 handler 的创建和安装过程，会用到 @code{HTTPBasicAuthHandler} 。有关该主题的更详细的介绍——包括基本身份认证的工作原理——请参阅 Basic Authentication Tutorial@footnote{http://www.voidspace.org.uk/python/articles/authentication.shtml} 。

如果需要身份认证，服务器会发送一条请求身份认证的头部信息（以及 401 错误代码）。这条信息中指明了身份认证方式和“安全区域（realm）”。格式如下所示：@code{WWW-Authenticate: SCHEME realm="REALM"} 。

例如

@example
WWW-Authenticate: Basic realm="cPanel Users"
@end example

然后，客户端应重试发起请求，请求数据中的头部信息应包含安全区域对应的用户名和密码。这就是“基本身份认证”。为了简化此过程，可以创建 @code{HTTPBasicAuthHandler} 的一个实例及使用它的 opener。

@code{HTTPBasicAuthHandler} 用一个名为密码管理器的对象来管理 URL、安全区域与密码、用户名之间的映射关系。如果知道确切的安全区域（来自服务器发送的身份认证头部信息），那就可以用到 @code{HTTPPasswordMgr} 。通常人们并不关心安全区域是什么，这时用`@w{`}HTTPPasswordMgrWithDefaultRealm`@w{`} 就很方便，允许为 URL 指定默认的用户名和密码。当没有为某个安全区域提供用户名和密码时，就会用到默认值。下面用 @code{None} 作为 @code{add_password} 方法的安全区域参数，表明采用默认用户名和密码。

首先需要身份认证的是顶级 URL。比传给 .add_password() 的 URL 级别“更深”的 URL 也会得以匹配：

@example
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
@end example

@cartouche
@quotation 注解 
在以上例子中，只向 @code{build_opener} 给出了 @code{HTTPBasicAuthHandler} 。默认情况下，opener 会有用于处理常见状况的 handler ——@code{ProxyHandler} （如果设置代理的话，比如设置了环境变量 
@geindex http_proxy
@geindex 环境变量; http_proxy
@code{http_proxy} ），@code{UnknownHandler} 、@code{HTTPHandler} 、 @code{HTTPDefaultErrorHandler} 、 @code{HTTPRedirectHandler} 、 @code{FTPHandler} 、 @code{FileHandler} 、 @code{DataHandler} 、 @code{HTTPErrorProcessor} 。
@end quotation
@end cartouche

@code{top_level_url} 其实 @emph{要么} 是一条完整的 URL（包括 “http:” 部分和主机名及可选的端口号），比如 @code{"http://example.com/"} ， @emph{要么} 是一条“访问权限”（即主机名，及可选的端口号），比如 @code{"example.com"} 或 @code{"example.com:8080"} （后一个示例包含了端口号）。访问权限 @strong{不得} 包含“用户信息”部分——比如 @code{"joe:password@@example.com"} 就不正确。

@node 代理,套接字与分层,基本认证,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 proxies}@anchor{4442}
@subsection 代理


@strong{urllib} 将自动检测并使用代理设置。 这是通过 @code{ProxyHandler} 实现的，当检测到代理设置时，是正常 handler 链中的一部分。通常这是一件好事，但有时也可能会无效 @footnote{@w{(5)} 
本人必须使用代理才能在工作中访问互联网。如果尝试通过代理获取 @emph{localhost} URL，将会遭到阻止。IE 设置为代理模式，urllib 就会获取到配置信息。为了用 localhost 服务器测试脚本，我必须阻止 urllib 使用代理。
}。 一种方案是配置自己的 @code{ProxyHandler} ，不要定义代理。 设置的步骤与 @ref{4443,,Basic Authentication} handler 类似:

@example
>>> proxy_support = urllib.request.ProxyHandler(@{@})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)
@end example

@cartouche
@quotation 注解 
目前 @code{urllib.request} @emph{尚不} 支持通过代理抓取 @code{https} 链接地址。 但此功能可以通过扩展 urllib.request 来启用，如以下例程所示 @footnote{@w{(6)} 
urllib 的 SSL 代理 opener（CONNECT  方法）： @uref{https://code.activestate.com/recipes/456195/,ASPN Cookbook Recipe} 。
}。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
如果设置了 @code{REQUEST_METHOD} 变量，则会忽略 @code{HTTP_PROXY} ；参阅 @ref{2d45,,getproxies()} 文档。
@end quotation
@end cartouche

@node 套接字与分层,脚注,代理,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 sockets-and-layers}@anchor{4444}
@subsection 套接字与分层


Python 获取 Web 资源的能力是分层的。urllib 用到的是 @ref{93,,http.client} 库，而后者又用到了套接字库。

从 Python 2.3 开始，可以指定套接字等待响应的超时时间。这对必须要读到网页数据的应用程序会很有用。默认情况下，套接字模块 @emph{不会超时} 并且可以挂起。目前，套接字超时机制未暴露给 http.client 或 urllib.request 层使用。不过可以为所有套接字应用设置默认的全局超时。

@example
import socket
import urllib.request

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)
@end example


__________________________________________________________________


@node 脚注,,套接字与分层,如何利用 urllib 包获取网络资源
@anchor{howto/urllib2 footnotes}@anchor{4445}
@subsection 脚注


这篇文档由 John Lee 审订。

@node Argparse 教程,ipaddress模块介绍,如何利用 urllib 包获取网络资源,Python 常用指引
@anchor{howto/argparse doc}@anchor{4446}@anchor{howto/argparse argparse-tutorial}@anchor{4447}
@section Argparse 教程


@*作者: 
Tshepang Lekhonkhobe

@anchor{howto/argparse id1}@anchor{21b4}
这篇教程旨在作为 @ref{5,,argparse} 的入门介绍，此模块是 Python 标准库中推荐的命令行解析模块。

@cartouche
@quotation 注解 
还有另外两个模块可以完成同样的任务，称为 @ref{85,,getopt} (对应于 C 语言中的 @code{getopt()} 函数) 和被弃用的 @ref{c3,,optparse}。还要注意 @ref{5,,argparse} 是基于 @ref{c3,,optparse} 的，因此用法与其非常相似。
@end quotation
@end cartouche

@menu
* 概念:: 
* 基础: 基础<2>. 
* 位置参数介绍:: 
* 可选参数介绍:: 
* 结合位置参数和可选参数:: 
* 进行一些小小的改进:: 
* 后记:: 

@end menu

@node 概念,基础<2>,,Argparse 教程
@anchor{howto/argparse concepts}@anchor{4448}
@subsection 概念


让我们利用 @code{ls} 命令来展示我们将要在这篇入门教程中探索的功能：

@example
$ ls
cpython  devguide  prog.py  pypy  rm-unused-function.patch
$ ls pypy
ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
$ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
-rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
-rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
...
@end example

我们可以从这四个命令中学到几个概念：


@itemize *

@item 
@code{ls} 是一个即使在运行的时候没有提供任何选项，也非常有用的命令。在默认情况下他会输出当前文件夹包含的文件和文件夹。

@item 
如果我们想要使用比它默认提供的更多功能，我们需要告诉该命令更多信息。在这个例子里，我们想要查看一个不同的目录，@code{pypy}。我们所做的是指定所谓的位置参数。之所以这样命名，是因为程序应该如何处理该参数值，完全取决于它在命令行出现的位置。更能体现这个概念的命令如 @code{cp}，它最基本的用法是 @code{cp SRC DEST}。第一个位置参数指的是*你想要复制的*，第二个位置参数指的是*你想要复制到的位置*。

@item 
现在假设我们想要改变这个程序的行为。在我们的例子中，我们不仅仅只是输出每个文件的文件名，还输出了更多信息。在这个例子中，@code{-l} 被称为可选参数。

@item 
这是一段帮助文档的文字。它是非常有用的，因为当你遇到一个你从未使用过的程序时，你可以通过阅读它的帮助文档来弄清楚它是如何运行的。
@end itemize

@node 基础<2>,位置参数介绍,概念,Argparse 教程
@anchor{howto/argparse the-basics}@anchor{4449}
@subsection 基础


让我们从一个简单到（几乎）什么也做不了的例子开始：

@example
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
@end example

以下是该代码的运行结果：

@example
$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python3 prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
@end example

程序运行情况如下：


@itemize *

@item 
在没有任何选项的情况下运行脚本不会在标准输出显示任何内容。这没有什么用处。

@item 
第二行代码开始展现出 @ref{5,,argparse} 模块的作用。我们几乎什么也没有做，但已经得到一条很好的帮助信息。

@item 
@code{--help} 选项，也可缩写为 @code{-h}，是唯一一个可以直接使用的选项（即不需要指定该选项的内容）。指定任何内容都会导致错误。即便如此，我们也能直接得到一条有用的用法信息。
@end itemize

@node 位置参数介绍,可选参数介绍,基础<2>,Argparse 教程
@anchor{howto/argparse introducing-positional-arguments}@anchor{444a}
@subsection 位置参数介绍


举个例子：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)
@end example

运行此程序：

@example
$ python3 prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python3 prog.py --help
usage: prog.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit
$ python3 prog.py foo
foo
@end example

程序运行情况如下：


@itemize *

@item 
我们增加了 @code{add_argument()} 方法，该方法用于指定程序能够接受哪些命令行选项。在这个例子中，我将选项命名为 @code{echo}，与其功能一致。

@item 
现在调用我们的程序必须要指定一个选项。

@item 
The @code{parse_args()} method actually returns some data from the
options specified, in this case, @code{echo}.

@item 
这一变量是 @ref{5,,argparse} 免费施放的某种 “魔法”（即是说，不需要指定哪个变量是存储哪个值的）。你也可以注意到，这一名称与传递给方法的字符串参数一致，都是  @code{echo}。
@end itemize

然而请注意，尽管显示的帮助看起来清楚完整，但它可以比现在更有帮助。比如我们可以知道 @code{echo} 是一个位置参数，但我们除了靠猜或者看源代码，没法知道它是用来干什么的。所以，我们可以把它改造得更有用：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)
@end example

然后我们得到：

@example
$ python3 prog.py -h
usage: prog.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit
@end example

现在，来做一些更有用的事情：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
@end example

以下是该代码的运行结果：

@example
$ python3 prog.py 4
Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
@end example

进展不太顺利。那是因为 @ref{5,,argparse} 会把我们传递给它的选项视作为字符串，除非我们告诉它别这样。所以，让我们来告诉 @ref{5,,argparse} 来把这一输入视为整数：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print(args.square**2)
@end example

以下是该代码的运行结果：

@example
$ python3 prog.py 4
16
$ python3 prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'
@end example

做得不错。当这个程序在收到错误的无效的输入时，它甚至能在执行计算之前先退出，还能显示很有帮助的错误信息。

@node 可选参数介绍,结合位置参数和可选参数,位置参数介绍,Argparse 教程
@anchor{howto/argparse introducing-optional-arguments}@anchor{444b}
@subsection 可选参数介绍


到目前为止，我们一直在研究位置参数。让我们看看如何添加可选的：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")
@end example

和输出：

@example
$ python3 prog.py --verbosity 1
verbosity turned on
$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity
$ python3 prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument
@end example

程序运行情况如下：


@itemize *

@item 
这一程序被设计为当指定 @code{--verbosity} 选项时显示某些东西，否则不显示。

@item 
不添加这一选项时程序没有提示任何错误而退出，表明这一选项确实是可选的。注意，如果一个可选参数没有被使用时，相关变量被赋值为 @code{None}，在此例中是 @code{args.verbosity}，这也就是为什么它在 @ref{eb3,,if} 语句中被当作逻辑假。

@item 
帮助信息有点不同。

@item 
使用 @code{--verbosity} 选项时，必须指定一个值，但可以是任何值。
@end itemize

上述例子接受任何整数值作为 @code{--verbosity} 的参数，但对于我们的简单程序而言，只有两个值有实际意义：@code{True} 或者 @code{False}。让我们据此修改代码：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")
@end example

和输出：

@example
$ python3 prog.py --verbose
verbosity turned on
$ python3 prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python3 prog.py --help
usage: prog.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity
@end example

程序运行情况如下：


@itemize *

@item 
现在，这一选项更多地是一个标志，而非需要接受一个值的什么东西。我们甚至改变了选项的名字来符合这一思路。注意我们现在指定了一个新的关键词 @code{action}，并赋值为 @code{"store_true"}。这意味着，当这一选项存在时，为 @code{args.verbose} 赋值为 @code{True}。没有指定时则隐含地赋值为 @code{False}。

@item 
当你为其指定一个值时，它会报错，符合作为标志的真正的精神。

@item 
留意不同的帮助文字。
@end itemize

@menu
* 短选项:: 

@end menu

@node 短选项,,,可选参数介绍
@anchor{howto/argparse short-options}@anchor{444c}
@subsubsection 短选项


如果你熟悉命令行的用法，你会发现我还没讲到这一选项的短版本。这也很简单：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")
@end example

效果就像这样：

@example
$ python3 prog.py -v
verbosity turned on
$ python3 prog.py --help
usage: prog.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity
@end example

可以注意到，这一新的能力也反映在帮助文本里。

@node 结合位置参数和可选参数,进行一些小小的改进,可选参数介绍,Argparse 教程
@anchor{howto/argparse combining-positional-and-optional-arguments}@anchor{444d}
@subsection 结合位置参数和可选参数


我们的程序变得越来越复杂了：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print("the square of @{@} equals @{@}".format(args.square, answer))
else:
    print(answer)
@end example

接着是输出：

@example
$ python3 prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python3 prog.py 4
16
$ python3 prog.py 4 --verbose
the square of 4 equals 16
$ python3 prog.py --verbose 4
the square of 4 equals 16
@end example


@itemize *

@item 
我们带回了一个位置参数，结果发生了报错。

@item 
注意顺序无关紧要。
@end itemize

给我们的程序加上接受多个冗长度的值，然后实际来用用：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of @{@} equals @{@}".format(args.square, answer))
elif args.verbosity == 1:
    print("@{@}^2 == @{@}".format(args.square, answer))
else:
    print(answer)
@end example

和输出：

@example
$ python3 prog.py 4
16
$ python3 prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python3 prog.py 4 -v 1
4^2 == 16
$ python3 prog.py 4 -v 2
the square of 4 equals 16
$ python3 prog.py 4 -v 3
16
@end example

除了最后一个，看上去都不错。最后一个暴露了我们的程序中有一个 bug。我们可以通过限制 @code{--verbosity} 选项可以接受的值来修复它：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of @{@} equals @{@}".format(args.square, answer))
elif args.verbosity == 1:
    print("@{@}^2 == @{@}".format(args.square, answer))
else:
    print(answer)
@end example

和输出：

@example
$ python3 prog.py 4 -v 3
usage: prog.py [-h] [-v @{0,1,2@}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
$ python3 prog.py 4 -h
usage: prog.py [-h] [-v @{0,1,2@}] square

positional arguments:
  square                display a square of a given number

optional arguments:
  -h, --help            show this help message and exit
  -v @{0,1,2@}, --verbosity @{0,1,2@}
                        increase output verbosity
@end example

注意这一改变同时反应在错误信息和帮助信息里。

现在，让我们使用另一种的方式来改变冗长度。这种方式更常见，也和 CPython 的可执行文件处理它自己的冗长度参数的方式一致（参考 @code{python --help} 的输出）：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of @{@} equals @{@}".format(args.square, answer))
elif args.verbosity == 1:
    print("@{@}^2 == @{@}".format(args.square, answer))
else:
    print(answer)
@end example

我们引入了另一种动作 @code{count}，来数某一个可选参数出现了几次：

@example
$ python3 prog.py 4
16
$ python3 prog.py 4 -v
4^2 == 16
$ python3 prog.py 4 -vv
the square of 4 equals 16
$ python3 prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python3 prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python3 prog.py 4 -h
usage: prog.py [-h] [-v] square

positional arguments:
  square           display a square of a given number

optional arguments:
  -h, --help       show this help message and exit
  -v, --verbosity  increase output verbosity
$ python3 prog.py 4 -vvv
16
@end example


@itemize *

@item 
是的，它现在比前一版本更像是一个标志（和 @code{action="store_true"} 相似）。这能解释它为什么报错。

@item 
它也表现得与 “store_true” 的行为相似。

@item 
这给出了一个关于 @code{count} 动作的效果的演示。你之前很可能应该已经看过这种用法。

@item 
如果你不添加 @code{-v} 标志，这一标志的值会是 @code{None}。

@item 
如期望的那样，添加该标志的长形态能够获得相同的输出。

@item 
可惜的是，对于我们的脚本获得的新能力，我们的帮助输出并没有提供很多信息，但我们总是可以通过改善文档来修复这一问题（比如通过 @code{help} 关键字参数）。

@item 
最后一个输出暴露了我们程序中的一个 bug。
@end itemize

让我们修复一下：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2

# bugfix: replace == with >=
if args.verbosity >= 2:
    print("the square of @{@} equals @{@}".format(args.square, answer))
elif args.verbosity >= 1:
    print("@{@}^2 == @{@}".format(args.square, answer))
else:
    print(answer)
@end example

这是它给我们的输出：

@example
$ python3 prog.py 4 -vvv
the square of 4 equals 16
$ python3 prog.py 4 -vvvv
the square of 4 equals 16
$ python3 prog.py 4
Traceback (most recent call last):
  File "prog.py", line 11, in <module>
    if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and 'int'
@end example


@itemize *

@item 
第一组输出很好，修复了之前的 bug。也就是说，我们希望任何 >= 2 的值尽可能详尽。

@item 
第三组输出并不理想。
@end itemize

让我们修复那个 bug：

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
    print("the square of @{@} equals @{@}".format(args.square, answer))
elif args.verbosity >= 1:
    print("@{@}^2 == @{@}".format(args.square, answer))
else:
    print(answer)
@end example

我们刚刚引入了又一个新的关键字 @code{default}。我们把它设置为 @code{0} 来让它可以与其他整数值相互比较。记住，默认情况下如果一个可选参数没有被指定，它的值会是 @code{None}，并且它不能和整数值相比较（所以产生了 @ref{1ff,,TypeError} 异常）。

然后：

@example
$ python3 prog.py 4
16
@end example

凭借我们目前已学的东西你就可以做到许多事情，而我们还仅仅学了一些皮毛而已。 @ref{5,,argparse} 模块是非常强大的，在结束篇教程之前我们将再探索更多一些内容。

@node 进行一些小小的改进,后记,结合位置参数和可选参数,Argparse 教程
@anchor{howto/argparse getting-a-little-more-advanced}@anchor{444e}
@subsection 进行一些小小的改进


如果我们想扩展我们的简短程序来执行其他幂次的运算，而不仅是乘方:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print("@{@} to the power @{@} equals @{@}".format(args.x, args.y, answer))
elif args.verbosity >= 1:
    print("@{@}^@{@} == @{@}".format(args.x, args.y, answer))
else:
    print(answer)
@end example

输出：

@example
$ python3 prog.py
usage: prog.py [-h] [-v] x y
prog.py: error: the following arguments are required: x, y
$ python3 prog.py -h
usage: prog.py [-h] [-v] x y

positional arguments:
  x                the base
  y                the exponent

optional arguments:
  -h, --help       show this help message and exit
  -v, --verbosity
$ python3 prog.py 4 2 -v
4^2 == 16
@end example

请注意到目前为止我们一直在使用详细级别来 @emph{更改} 所显示的文本。 以下示例则使用详细级别来显示 @emph{更多的} 文本:

@example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print("Running '@{@}'".format(__file__))
if args.verbosity >= 1:
    print("@{@}^@{@} == ".format(args.x, args.y), end="")
print(answer)
@end example

输出：

@example
$ python3 prog.py 4 2
16
$ python3 prog.py 4 2 -v
4^2 == 16
$ python3 prog.py 4 2 -vv
Running 'prog.py'
4^2 == 16
@end example

@menu
* 矛盾的选项:: 

@end menu

@node 矛盾的选项,,,进行一些小小的改进
@anchor{howto/argparse conflicting-options}@anchor{444f}
@subsubsection 矛盾的选项


到目前为止，我们一直在使用 @ref{792,,argparse.ArgumentParser} 实例的两个方法。 让我们再介绍第三个方法 @code{add_mutually_exclusive_group()}。 它允许我们指定彼此相互冲突的选项。 让我们再更改程序的其余部分以便使用新功能更有意义：我们将引入 @code{--quiet} 选项，它将与 @code{--verbose} 正好相反:

@example
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("@{@} to the power @{@} equals @{@}".format(args.x, args.y, answer))
else:
    print("@{@}^@{@} == @{@}".format(args.x, args.y, answer))
@end example

我们的程序现在变得更简洁了，我们出于演示需要略去了一些功能。 无论如何，输出是这样的:

@example
$ python3 prog.py 4 2
4^2 == 16
$ python3 prog.py 4 2 -q
16
$ python3 prog.py 4 2 -v
4 to the power 2 equals 16
$ python3 prog.py 4 2 -vq
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
$ python3 prog.py 4 2 -v --quiet
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
@end example

这应该很容易理解。 我添加了末尾的输出这样你就可以看到其所达到的灵活性，即混合使用长和短两种形式的选项。

在我们收尾之前，你也许希望告诉你的用户这个程序的主要目标，以免他们还不清楚:

@example
import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("@{@} to the power @{@} equals @{@}".format(args.x, args.y, answer))
else:
    print("@{@}^@{@} == @{@}".format(args.x, args.y, answer))
@end example

请注意用法文本中有细微的差异。 注意 @code{[-v | -q]}，它的意思是说我们可以使用 @code{-v} 或 @code{-q}，但不能同时使用两者：

@example
$ python3 prog.py --help
usage: prog.py [-h] [-v | -q] x y

calculate X to the power of Y

positional arguments:
  x              the base
  y              the exponent

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose
  -q, --quiet
@end example

@node 后记,,进行一些小小的改进,Argparse 教程
@anchor{howto/argparse conclusion}@anchor{4450}
@subsection 后记


除了这里显示的内容，@ref{5,,argparse} 模块还提供了更多功能。 它的文档相当详细和完整，包含大量示例。 完成这个教程之后，你应该能毫不困难地阅读该文档。

@c import ipaddress

@node ipaddress模块介绍,Argument Clinic 的用法,Argparse 教程,Python 常用指引
@anchor{howto/ipaddress doc}@anchor{4451}@anchor{howto/ipaddress an-introduction-to-the-ipaddress-module}@anchor{4452}@anchor{howto/ipaddress ipaddress-howto}@anchor{2fb5}
@section ipaddress模块介绍


@*作者: 
Peter Moody


@*作者: 
Nick Coghlan


@subsubheading 概述



本文档旨在简要介绍 @ref{a2,,ipaddress} 模块。 它主要针对那些不熟悉 IP 网络术语的用户，但也可能对想要速览 @ref{a2,,ipaddress} 如何代表IP网络寻址概念的网络工程师有用。

@menu
* 创建 Address/Network/Interface 对象:: 
* 审查 Address/Network/Interface 对象:: 
* Network 作为 Address 列表:: 
* 比较: 比较<3>. 
* 将IP地址与其他模块一起使用:: 
* 实例创建失败时获取更多详细信息:: 

@end menu

@node 创建 Address/Network/Interface 对象,审查 Address/Network/Interface 对象,,ipaddress模块介绍
@anchor{howto/ipaddress creating-address-network-interface-objects}@anchor{4453}
@subsection 创建 Address/Network/Interface 对象


因为 @ref{a2,,ipaddress} 是一个用于检查和操作 IP 地址的模块，你要做的第一件事就是创建一些对象。 您可以使用 @ref{a2,,ipaddress} 从字符串和整数创建对象。

@menu
* 关于IP版本的说明:: 
* IP主机地址:: 
* 定义网络:: 
* 主机接口:: 

@end menu

@node 关于IP版本的说明,IP主机地址,,创建 Address/Network/Interface 对象
@anchor{howto/ipaddress a-note-on-ip-versions}@anchor{4454}
@subsubsection 关于IP版本的说明


对于不太熟悉 IP 寻址的读者，重要的是要知道 Internet 协议当前正在从协议的版本4转移到版本6。转换很大程度上是因为协议的版本4没有提供足够的地址来满足整个世界的需求，特别是考虑到越来越多的设备直接连接到互联网。

解释协议的两个版本之间的差异的细节超出了本介绍的范围，但读者需要至少知道存在这两个版本，并且有时需要强制使用一个版本或其他版本。

@node IP主机地址,定义网络,关于IP版本的说明,创建 Address/Network/Interface 对象
@anchor{howto/ipaddress ip-host-addresses}@anchor{4455}
@subsubsection IP主机地址


通常称为“主机地址”的地址是使用IP寻址时最基本的单元。 创建地址的最简单方法是使用 @ref{2fb7,,ipaddress.ip_address()} 工厂函数，该函数根据传入的值自动确定是创建 IPv4 还是 IPv6 地址：

@example
>>> ipaddress.ip_address('192.0.2.1')
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address('2001:DB8::1')
IPv6Address('2001:db8::1')
@end example

地址也可以直接从整数创建，适配32位的值并假定为IPv4地址:

@example
>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address(42540766411282592856903984951653826561)
IPv6Address('2001:db8::1')
@end example

要强制使用IPv4或IPv6地址，可以直接调用相关的类。 这对于强制为小整数创建IPv6地址特别有用:

@example
>>> ipaddress.ip_address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv4Address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv6Address(1)
IPv6Address('::1')
@end example

@node 定义网络,主机接口,IP主机地址,创建 Address/Network/Interface 对象
@anchor{howto/ipaddress defining-networks}@anchor{4456}
@subsubsection 定义网络


主机地址通常组合在一起形成IP网络，因此 @ref{a2,,ipaddress} 提供了一种创建、检查和操作网络定义的方法。 IP网络对象由字符串构成，这些字符串定义作为该网络一部分的主机地址范围。 该信息的最简单形式是“网络地址/网络前缀”对，其中前缀定义了比较的前导比特数，以确定地址是否是网络的一部分，并且网络地址定义了那些位的预期值。

对于地址，提供了一个自动确定正确IP版本的工厂函数:

@example
>>> ipaddress.ip_network('192.0.2.0/24')
IPv4Network('192.0.2.0/24')
>>> ipaddress.ip_network('2001:db8::0/96')
IPv6Network('2001:db8::/96')
@end example

网络对象不能设置任何主机位。 这样做的实际效果是`@w{`}192.0.2.1/24`@w{`}没有描述网络。 这种定义被称为接口对象，因为网络上IP表示法通常用于描述给定网络上的计算机的网络接口，并在下一节中进一步描述。

默认情况下，尝试创建一个设置了主机位的网络对象将导致 @ref{16d,,ValueError} 被引发。 要请求将附加位强制为零，可以将标志`@w{`}strict=False`@w{`} 传递给构造函数:

@example
>>> ipaddress.ip_network('192.0.2.1/24')
Traceback (most recent call last):
   ...
ValueError: 192.0.2.1/24 has host bits set
>>> ipaddress.ip_network('192.0.2.1/24', strict=False)
IPv4Network('192.0.2.0/24')
@end example

虽然字符串形式提供了更大的灵活性，但网络也可以用整数定义，就像主机地址一样。 在这种情况下，网络被认为只包含由整数标识的单个地址，因此网络前缀包括整个网络地址:

@example
>>> ipaddress.ip_network(3221225984)
IPv4Network('192.0.2.0/32')
>>> ipaddress.ip_network(42540766411282592856903984951653826560)
IPv6Network('2001:db8::/128')
@end example

与地址一样，可以通过直接调用类构造函数而不是使用工厂函数来强制创建特定类型的网络。

@node 主机接口,,定义网络,创建 Address/Network/Interface 对象
@anchor{howto/ipaddress host-interfaces}@anchor{4457}
@subsubsection 主机接口


如上所述，如果您需要描述特定网络上的地址，则地址和网络类都不够。 像 @code{192.0.2.1/24} 这样的表示法通常被网络工程师和为防火墙和路由器编写工具的人用作“ @code{192.0.2.0/24} 网络上的主机 @code{192.0.2.1} ”的简写。因此，@ref{a2,,ipaddress} 提供了一组将地址与特定网络相关联的混合类。用于创建的接口与用于定义网络对象的接口相同，除了地址部分不限于是网络地址。

@example
>>> ipaddress.ip_interface('192.0.2.1/24')
IPv4Interface('192.0.2.1/24')
>>> ipaddress.ip_interface('2001:db8::1/96')
IPv6Interface('2001:db8::1/96')
@end example

接受整数输入（与网络一样），并且可以通过直接调用相关构造函数来强制使用特定IP版本。

@node 审查 Address/Network/Interface 对象,Network 作为 Address 列表,创建 Address/Network/Interface 对象,ipaddress模块介绍
@anchor{howto/ipaddress inspecting-address-network-interface-objects}@anchor{4458}
@subsection 审查 Address/Network/Interface 对象


你已经遇到了创建IPv(4|6)(Address|Network|Interface) 对象的麻烦，因此你可能希望获得有关它的信息。 @ref{a2,,ipaddress} 试图让这个过程变得简单直观。

提取 IP 版本:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr6 = ipaddress.ip_address('2001:db8::1')
>>> addr6.version
6
>>> addr4.version
4
@end example

从接口获取网络:

@example
>>> host4 = ipaddress.ip_interface('192.0.2.1/24')
>>> host4.network
IPv4Network('192.0.2.0/24')
>>> host6 = ipaddress.ip_interface('2001:db8::1/96')
>>> host6.network
IPv6Network('2001:db8::/96')
@end example

找出网络中有多少独立地址:

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.num_addresses
256
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.num_addresses
4294967296
@end example

迭代网络上的“可用”地址:

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> for x in net4.hosts():
...     print(x)  
192.0.2.1
192.0.2.2
192.0.2.3
192.0.2.4
...
192.0.2.252
192.0.2.253
192.0.2.254
@end example

获取网络掩码（即对应于网络前缀的设置位）或主机掩码（不属于网络掩码的任何位）：

@example
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.netmask
IPv4Address('255.255.255.0')
>>> net4.hostmask
IPv4Address('0.0.0.255')
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.netmask
IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
>>> net6.hostmask
IPv6Address('::ffff:ffff')
@end example

展开或压缩地址:

@example
>>> addr6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0001'
>>> addr6.compressed
'2001:db8::1'
>>> net6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0000/96'
>>> net6.compressed
'2001:db8::/96'
@end example

虽然IPv4不支持展开或压缩，但关联对象仍提供相关属性，因此版本中性代码可以轻松确保最简洁或最详细的形式用于IPv6地址，同时仍能正确处理IPv4地址。

@node Network 作为 Address 列表,比较<3>,审查 Address/Network/Interface 对象,ipaddress模块介绍
@anchor{howto/ipaddress networks-as-lists-of-addresses}@anchor{4459}
@subsection Network 作为 Address 列表


将网络视为列表有时很有用。 这意味着它可以像这样索引它们:

@example
>>> net4[1]
IPv4Address('192.0.2.1')
>>> net4[-1]
IPv4Address('192.0.2.255')
>>> net6[1]
IPv6Address('2001:db8::1')
>>> net6[-1]
IPv6Address('2001:db8::ffff:ffff')
@end example

它还意味着网络对象可以使用像这样的列表成员测试语法:

@example
if address in network:
    # do something
@end example

根据网络前缀有效地完成包含性测试:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr4 in ipaddress.ip_network('192.0.2.0/24')
True
>>> addr4 in ipaddress.ip_network('192.0.3.0/24')
False
@end example

@node 比较<3>,将IP地址与其他模块一起使用,Network 作为 Address 列表,ipaddress模块介绍
@anchor{howto/ipaddress comparisons}@anchor{445a}
@subsection 比较


@ref{a2,,ipaddress} 有意义地提供了一些简单、希望直观的比较对象的方法:

@example
>>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
True
@end example

如果你尝试比较不同版本或不同类型的对象，则会引发 @ref{1ff,,TypeError} 异常。

@node 将IP地址与其他模块一起使用,实例创建失败时获取更多详细信息,比较<3>,ipaddress模块介绍
@anchor{howto/ipaddress using-ip-addresses-with-other-modules}@anchor{445b}
@subsection 将IP地址与其他模块一起使用


其他使用IP地址的模块（例如 @ref{ef,,socket} ）通常不会直接接受来自该模块的对象。 相反，它们必须被强制转换为另一个模块可接受的整数或字符串:

@example
>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> str(addr4)
'192.0.2.1'
>>> int(addr4)
3221225985
@end example

@node 实例创建失败时获取更多详细信息,,将IP地址与其他模块一起使用,ipaddress模块介绍
@anchor{howto/ipaddress getting-more-detail-when-instance-creation-fails}@anchor{445c}
@subsection 实例创建失败时获取更多详细信息


使用与版本无关的工厂函数创建 address/network/interface 对象时，任何错误都将报告为 @ref{16d,,ValueError} ，带有一般错误消息，只是说传入的值未被识别为该类型的对象。 缺少特定错误是因为有必要知道该值是*假设*是IPv4还是IPv6，以便提供有关其被拒绝原因的更多详细信息。

为了支持访问这些额外细节的用例，各个类构造函数实际上引发了 @ref{16d,,ValueError} 子类 @ref{2fbd,,ipaddress.AddressValueError} 和 @ref{2fe4,,ipaddress.NetmaskValueError} 以准确指示定义的哪一部分无法正确解析。

直接使用类构造函数时，错误消息更加详细。 例如:

@example
>>> ipaddress.ip_address("192.168.0.256")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.IPv4Address("192.168.0.256")
Traceback (most recent call last):
  ...
ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'

>>> ipaddress.ip_network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
>>> ipaddress.IPv4Network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ipaddress.NetmaskValueError: '64' is not a valid netmask
@end example

但是，两个模块特定的异常都有 @ref{16d,,ValueError} 作为它们的父类，所以如果你不关心特定类型的错误，你仍然可以编写如下代码:

@example
try:
    network = ipaddress.IPv4Network(address)
except ValueError:
    print('address/netmask is invalid for IPv4:', address)
@end example

@node Argument Clinic 的用法,使用 DTrace 和 SystemTap 检测CPython,ipaddress模块介绍,Python 常用指引
@anchor{howto/clinic doc}@anchor{445d}@anchor{howto/clinic argument-clinic-how-to}@anchor{445e}
@section Argument Clinic 的用法


@*作者: 
Larry Hastings


@subsubheading 摘要



Argument Clinic 是 CPython 的一个 C 文件预处理器。旨在自动处理所有与“内置”参数解析有关的代码。本文展示了将 C 函数转换为配合 Argument Clinic 工作的做法，还介绍了一些关于 Argument Clinic 用法的进阶内容。

目前 Argument Clinic 视作仅供 CPython 内部使用。不支持在 CPython 之外的文件中使用，也不保证未来版本会向下兼容。换句话说：如果维护的是 CPython 的外部 C 语言扩展，欢迎在自己的代码中试用 Argument Clinic。但 Argument Clinic 与新版 CPython 中的版本 @emph{可能} 完全不兼容，且会打乱全部代码。

@menu
* Argument Clinic 的设计目标:: 
* 基本概念和用法:: 
* 函数的转换:: 
* 进阶:: 

@end menu

@node Argument Clinic 的设计目标,基本概念和用法,,Argument Clinic 的用法
@anchor{howto/clinic the-goals-of-argument-clinic}@anchor{445f}
@subsection Argument Clinic 的设计目标


Argument Clinic 的主要目标，是接管 CPython 中的所有参数解析代码。这意味着，如果要把某个函数转换为配合 Argument Clinic一起工作，则该函数不应再作任何参数解析工作——Argument Clinic 生成的代码应该是个“黑盒”，CPython 会在顶部发起调用，底部则调用自己的代码， @code{PyObject *args} （也许还有 @code{PyObject *kwargs} ）会神奇地转换成所需的 C 变量和类型。

Argument Clinic 为了能完成主要目标，用起来必须方便。目前，使用 CPython 的参数解析库是一件苦差事，需要在很多地方维护冗余信息。如果使用 Argument Clinic，则不必再重复代码了。

显然，除非 Argument Clinic 解决了自身的问题，且没有产生新的问题，否则没有人会愿意用它。所以，Argument Clinic 最重要的事情就是生成正确的代码。如果能加速代码的运行当然更好，但至少不应引入明显的减速。（最终 Argument Clinic @emph{应该} 可以实现较大的速度提升——代码生成器可以重写一下，以产生量身定做的参数解析代码，而不是调用通用的 CPython 参数解析库。 这会让参数解析达到最佳速度！）

此外，Argument Clinic 必须足够灵活，能够与任何参数解析的方法一起工作。Python 有一些函数具备一些非常奇怪的解析行为；Argument Clinic 的目标是支持所有这些函数。

最后，Argument Clinic 的初衷是为 CPython 内置程序提供内省“签名”。以前如果传入一个内置函数，内省查询函数会抛出异常。有了 Argument Clinic，再不会发生这种问题了！

在与 Argument Clinic 合作时，应该牢记一个理念：给它的信息越多，它做得就会越好。诚然，Argument Clinic 现在还比较简单。但会演变得越来越复杂，应该能够利用给出的全部信息干很多聪明而有趣的事情。

@node 基本概念和用法,函数的转换,Argument Clinic 的设计目标,Argument Clinic 的用法
@anchor{howto/clinic basic-concepts-and-usage}@anchor{4460}
@subsection 基本概念和用法


Argument Clinic 与 CPython 一起提供，位于 @code{Tools/clinic/clinic.py} 。若要运行它，请指定一个 C 文件作为参数。

@example
$ python3 Tools/clinic/clinic.py foo.c
@end example

Argument Clinic 会扫描 C 文件，精确查找以下代码：

@example
/*[clinic input]
@end example

一旦找到一条后，就会读取所有内容，直至遇到以下代码：

@example
[clinic start generated code]*/
@end example

这两行之间的所有内容都是 Argument Clinic 的输入。所有行，包括开始和结束的注释行，统称为 Argument Clinic “块”。

Argument Clinic 在解析某一块时，会生成输出信息。输出信息会紧跟着该块写入 C 文件中，后面还会跟着包含校验和的注释。现在 Argument Clinic 块看起来应如下所示：

@example
/*[clinic input]
... clinic input goes here ...
[clinic start generated code]*/
... clinic output goes here ...
/*[clinic end generated code: checksum=...]*/
@end example

如果对同一文件第二次运行 Argument Clinic，则它会丢弃之前的输出信息，并写入带有新校验行的输出信息。不过如果输入没有变化，则输出也不会后变化。

不应去改动 Argument Clinic 块的输出部分。而应去修改输入，直到生成所需的输出信息。（这就是校验和的用途——检测是否有人改动了输出信息，因为在 Argument Clinic 下次写入新的输出时，这些改动都会丢失）。

为了清晰起见，下面列出了 Argument Clinic 用到的术语：


@itemize *

@item 
注释的第一行 @code{/*[clinic input]} 是 @emph{起始行} 。

@item 
注释（@code{[clinic start generated code]*/}）的最后一行是 @emph{结束行}。

@item 
最后一行（@code{/*[clinic end generated code: checksum=...]*/}）是 @emph{校验和行} 。

@item 
在起始行和结束行之间是 @emph{输入数据}。

@item 
在结束行和校验和行之间是 @emph{输出数据} 。

@item 
从开始行到校验和行的所有文本，都是 @emph{块}。（Argument Clinic 尚未处理成功的块，没有输出或校验和行，但仍视作一个块）。
@end itemize

@node 函数的转换,进阶,基本概念和用法,Argument Clinic 的用法
@anchor{howto/clinic converting-your-first-function}@anchor{4461}
@subsection 函数的转换


要想了解 Argument Clinic 是如何工作的，最好的方式就是转换一个函数与之合作。下面介绍需遵循的最基本步骤。请注意，若真的准备在 CPython 中进行检查，则应进行更深入的转换，使用一些本文后续会介绍到的高级概念（比如 “返回转换” 和 “自转换”）。但以下例子将维持简单，以供学习。

就此开始


@enumerate 0

@item 
请确保 CPython 是最新的已签出版本。

@item 
找到一个调用 @ref{39b,,PyArg_ParseTuple()} 或 @ref{6cb,,PyArg_ParseTupleAndKeywords()} ，且未被转换为采用 Argument Clinic 的 Python 内置程序。这里用了 @code{_pickle.Pickler.dump()}。

@item 
如果对 @code{PyArg_Parse} 函数的调用采用了以下格式：

@example
O&
O!
es
es#
et
et#
@end example

或者多次调用 @ref{39b,,PyArg_ParseTuple()}，则应再选一个函数。Argument Clinic @emph{确实} 支持上述这些状况。 但这些都是高阶内容——第一次使用就简单一些吧。

此外，如果多次调用 @ref{39b,,PyArg_ParseTuple()} 或 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 且同一参数需支持不同的类型，或者用到 PyArg_Parse 以外的函数来解析参数，则可能不适合转换为 Argument Clinic。 Argument Clinic 不支持通用函数或多态参数。

@item 
在函数上方添加以下模板，创建块：

@example
/*[clinic input]
[clinic start generated code]*/
@end example

@item 
剪下文档字符串并粘贴到 @code{[clinic]} 行之间，去除所有的无用字符，使其成为一个正确引用的 C 字符串。最有应该只留下带有左侧缩进的文本，且行宽不大于 80 个字符。（参数 Clinic 将保留文档字符串中的缩进。）

如果文档字符串的第一行看起来像是函数的签名，就把这一行去掉吧。（(文档串不再需要用到它——将来对内置函数调用 @code{help()} 时，第一行将根据函数的签名自动建立。）

示例：

@example
/*[clinic input]
Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
如果文档字符串中没有“摘要”行，Argument Clinic 会报错。所以应确保带有摘要行。 “摘要”行应为在文档字符串开头的一个段落，由一个80列的单行构成。

（示例的文档字符串只包括一个摘要行，所以示例代码这一步不需改动）。

@item 
在文档字符串上方，输入函数的名称，后面是空行。这应是函数的 Python 名称，而且应是句点分隔的完整路径——以模块的名称开始，包含所有子模块名，若函数为类方法则还应包含类名。

示例：

@example
/*[clinic input]
_pickle.Pickler.dump

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
如果是第一次在此 C 文件中用到 Argument Clinic 的模块或类，必须对其进行声明。清晰的 Argument Clinic 写法应于 C 文件顶部附近的某个单独块中声明这些，就像 include 文件和 statics 放在顶部一样。（在这里的示例代码中，将这两个块相邻给出。)

类和模块的名称应与暴露给 Python 的相同。请适时检查 @ref{259,,PyModuleDef} 或 @ref{3fe,,PyTypeObject} 中定义的名称。

在声明某个类时，还必须指定其 C 语言类型的两个部分：用于指向该类实例的指针的类型声明，和指向该类的 @ref{3fe,,PyTypeObject} 指针。

示例：

@example
/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
声明函数的所有参数。每个参数都应另起一行。所有的参数行都应对齐函数名和文档字符串进行缩进。

这些参数行的常规形式如下：

@example
name_of_parameter: converter
@end example

如果参数带有默认值，请加在转换器之后：

@example
name_of_parameter: converter = default_value
@end example

Argument Clinic 对 “缺省值” 的支持方式相当复杂；更多信息请参见 @ref{4462,,关于缺省值的部分} 。

在参数行下面添加一个空行。

What's a "converter"?  It establishes both the type
of the variable used in C, and the method to convert the Python
value into a C value at runtime.
For now you're going to use what's called a "legacy converter"—a
convenience syntax intended to make porting old code into Argument
Clinic easier.

每个参数都要从`@w{`}PyArg_Parse()`@w{`} 格式参数中复制其 “格式单元”，并以带引号字符串的形式指定其转换器。（“格式单元”是 @code{format} 参数的1-3个字符的正式名称，用于让参数解析函数知晓该变量的类型及转换方法。关于格式单位的更多信息，请参阅 @ref{3fb,,语句解释及变量编译} ）。

对于像 @code{z#} 这样的多字符格式单元，要使用2-3个字符组成的整个字符串。

示例：

@example
 /*[clinic input]
 module _pickle
 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
 [clinic start generated code]*/

 /*[clinic input]
 _pickle.Pickler.dump

    obj: 'O'

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
如果函数的格式字符串包含 @code{|}，意味着有些参数带有缺省值，这可以忽略。Argument Clinic 根据参数是否有缺省值来推断哪些参数是可选的。

如果函数的格式字符串中包含 $，意味着只接受关键字参数，请在第一个关键字参数之前单独给出一行 @code{*}，缩进与参数行对齐。

（@code{_pickle.Pickler.dump} 两种格式字符串都没有，所以这里的示例不用改动。）

@item 
如果 C 函数调用的是 @ref{39b,,PyArg_ParseTuple()} (而不是 @ref{6cb,,PyArg_ParseTupleAndKeywords()})，那么其所有参数均是仅限位置参数。

若要在 Argument Clinic 中把所有参数都标记为只认位置，请在最后一个参数后面一行加入一个 @code{/}，缩进程度与参数行对齐。

目前这个标记是全体生效；要么所有参数都是只认位置，要么都不是。（以后 Argument Clinic 可能会放宽这一限制。）

示例：

@example
/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
为每个参数都编写一个文档字符串，这很有意义。但这是可选项；可以跳过这一步。

下面介绍如何添加逐参数的文档字符串。逐参数文档字符串的第一行必须比参数定义多缩进一层。第一行的左边距即确定了所有逐参数文档字符串的左边距；所有文档字符串文本都要同等缩进。文本可以用多行编写。

示例：

@example
/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

@item 
保存并关闭该文件，然后运行 @code{Tools/clinic/clinic.py} 。 运气好的话就万事大吉——程序块现在有了输出信息，并且生成了一个 @code{.c.h} 文件！在文本编辑器中重新打开该文件，可以看到：

@example
/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

static PyObject *
_pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
/*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/
@end example

显然，如果 Argument Clinic 未产生任何输出，那是因为在输入信息中发现了错误。继续修正错误并重试，直至 Argument Clinic 正确地处理好文件。

为了便于阅读，大部分“胶水”代码已写入 @code{.c.h} 文件中。需在原 @code{.c} 文件中包含这个文件，通常是在 clinic  模块之后：

@example
#include "clinic/_pickle.c.h"
@end example

@item 
请仔细检查 Argument Clinic 生成的参数解析代码，是否与现有代码基本相同。

首先，确保两种代码使用相同的参数解析函数。已有代码必须调用  @ref{39b,,PyArg_ParseTuple()} 或 @ref{6cb,,PyArg_ParseTupleAndKeywords()} ；确保 Argument Clinic 生成的代码调用 @emph{完全} 相同的函数。

其次，传给 @ref{39b,,PyArg_ParseTuple()} 或 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 的格式字符串应该 @emph{完全} 与原有函数中的相同，直到冒号或分号为止。

（Argument Clinic 生成的格式串一定是函数名后跟着 @code{:}。如果现有代码的格式串以 @code{;} 结尾，这种改动不回影响使用，因此不必担心。）

第三，如果格式串需要指定两个参数（比如长度、编码字符串或指向转换函数的指针），请确保第二个参数在两次调用时 @emph{完全} 相同。

第四，在输出部分会有一个预处理器宏，为该内置函数定义合适的静态 @ref{ee5,,PyMethodDef} 结构：

@example
#define __PICKLE_PICKLER_DUMP_METHODDEF    \
@{"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__@},
@end example

此静态结构应与本内置函数现有的静态结构 @ref{ee5,,PyMethodDef} @emph{完全} 相同。

只要上述这几点存在不一致，请调整 Argument Clinic 函数定义，并重新运行 @code{Tools/clinic/clinic.py} ，直至 @emph{完全} 相同。

@item 
注意，输出部分的最后一行是“导入”函数的声明。也就是该内置函数的实现代码所在。删除需要修改的函数的现有原型，但保留开头的大括号。再删除其参数解析代码和输入变量的所有声明。注意现在 Python 所见的参数即为此导入函数的参数；如果实现代码给这些变量采用了不同的命名，请进行修正。

因为稍显怪异，所以还是重申一下。现在的代码应该如下所示：

@example
static return_type
your_function_impl(...)
/*[clinic end generated code: checksum=...]*/
@{
...
@end example

上面是 Argument Clinic 生成的校验值和函数原型。函数应该带有闭合的大括号，里面包含实现代码。

示例：

@example
/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/
/*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
"Write a pickled representation of obj to the open file.\n"
"\n"
...
static PyObject *
_pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
/*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
@{
    /* Check whether the Pickler was initialized correctly (issue3664).
       Developers often forget to call __init__() in their subclasses, which
       would trigger a segfault without this check. */
    if (self->write == NULL) @{
        PyErr_Format(PicklingError,
                     "Pickler.__init__() was not called by %s.__init__()",
                     Py_TYPE(self)->tp_name);
        return NULL;
    @}

    if (_Pickler_ClearBuffer(self) < 0)
        return NULL;

    ...
@end example

@item 
还记得用到 @ref{ee5,,PyMethodDef} 结构的宏吧？找到函数中已有的  @ref{ee5,,PyMethodDef} 结构，并替换为宏的引用。（如果函数是模块级的，可能会在文件的末尾附近；如果函数是个类方法，则可能会在靠近实现代码的下方。)

注意，宏尾部带有一个逗号。所以若用宏替换已有的静态结构  @ref{ee5,,PyMethodDef} 时，@emph{请勿} 在结尾添加逗号了。

示例：

@example
static struct PyMethodDef Pickler_methods[] = @{
    __PICKLE_PICKLER_DUMP_METHODDEF
    __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
    @{NULL, NULL@}                /* sentinel */
@};
@end example

@item 
编译，然后运行回归测试套件中的有关测试程序。不应引入新的编译警告或错误，且对 Python 也不应有外部可见的变化。

差别只有一个，即 @code{inspect.signature()} 运行于新的函数上，现在应该新提供一个有效的签名！

祝贺你，现在已经用 Argument Clinic 移植了第一个函数。
@end enumerate

@node 进阶,,函数的转换,Argument Clinic 的用法
@anchor{howto/clinic advanced-topics}@anchor{4463}
@subsection 进阶


现在 Argument Clinic 的使用经验已具备了一些，该介绍一些高级内容了。

@menu
* 符号化默认值:: 
* 对 Argument Clinic 生成的 C 函数和变量进行重命名:: 
* 利用 PyArg_UnpackTuple 对函数进行转换:: 
* 可选参数组:: 
* 采用真正的 Argument Clinic 转换器，而不是 “传统转换器”:: 
* Py_buffer:: 
* 高级转换器:: 
* 参数的默认值:: 
* 默认值 NULL:: 
* 设为默认值的表达式:: 
* 返回转换器:: 
* 复制已有的函数:: 
* 调用 Python 代码:: 
* 参数 self 转换器的用法:: 
* 编写自定义转换器:: 
* 编写自定义的返回转换器:: 
* METH_O 和 METH_NOARGS:: 
* tp_new 和 tp_init functions:: 
* 改变和重定向 Clinic 的输出:: 
* #ifdef 使用技巧:: 
* 在 Python 文件中使用 Argument Clinic:: 

@end menu

@node 符号化默认值,对 Argument Clinic 生成的 C 函数和变量进行重命名,,进阶
@anchor{howto/clinic symbolic-default-values}@anchor{4464}
@subsubsection 符号化默认值


提供给参数的默认值不能是表达式。目前明确支持以下形式：


@itemize *

@item 
数值型常数（整数和浮点数）。

@item 
字符串常量

@item 
@code{True} 、 @code{False} 和 @code{None} 。

@item 
以模块名开头的简单符号常量，如 @code{sys.maxsize}。
@end itemize

如果你感到好奇，这是在  @code{from_builtin()} ( @code{Lib/inspect.py}) 中实现的。

（未来可能需要加以细化，以便可以采用 @code{CONSTANT - 1} 之类的完整表达式。）

@node 对 Argument Clinic 生成的 C 函数和变量进行重命名,利用 PyArg_UnpackTuple 对函数进行转换,符号化默认值,进阶
@anchor{howto/clinic renaming-the-c-functions-and-variables-generated-by-argument-clinic}@anchor{4465}
@subsubsection 对 Argument Clinic 生成的 C 函数和变量进行重命名


Argument Clinic 会自动为其生成的函数命名。如果生成的名称与现有的 C 函数冲突，这偶尔可能会造成问题，有一个简单的解决方案：覆盖 C 函数的名称。只要在函数声明中加入关键字 @code{"as"} ，然后再加上要使用的函数名。Argument Clinic 将以该函数名为基础作为（生成的）函数名，然后在后面加上 @code{"_impl"}，并用作导入函数的名称。

例如，若对 @code{pickle.Pickler.dump} 生成的 C 函数进行重命名，应如下所示：

@example
/*[clinic input]
pickle.Pickler.dump as pickler_dumper

...
@end example

原函数会被命名为 @code{pickler_dumper()}，而实现函数现在被命名为`@w{`}pickler_dumper_impl()`@w{`}。

同样的问题依然会出现：想给某个参数取个 Python 用名，但在 C 语言中可能用不了。Argument Clinic 允许在 Python 和 C 中为同一个参数取不同的名字，语法依然是利用 @code{"as"} ：

@example
/*[clinic input]
pickle.Pickler.dump

    obj: object
    file as file_obj: object
    protocol: object = NULL
    *
    fix_imports: bool = True
@end example

这里 Python（签名和 @code{keywords} 数组中）中用的名称是 @code{file}，而 C 语言中的变量命名为 @code{file_obj}。

@code{self} 参数也可以进行重命名。

@node 利用 PyArg_UnpackTuple 对函数进行转换,可选参数组,对 Argument Clinic 生成的 C 函数和变量进行重命名,进阶
@anchor{howto/clinic converting-functions-using-pyarg-unpacktuple}@anchor{4466}
@subsubsection 利用 PyArg_UnpackTuple 对函数进行转换


若要将函数转换为采用 @ref{f10,,PyArg_UnpackTuple()} 解析其参数，只需写出所有参数，并将每个参数定义为 @code{object}。可以指定 @code{type} 参数，以便能转换为合适的类型。所有参数都应标记为只认位置（在最后一个参数后面加上 @code{/}）。

目前，所生成的代码将会用到 @ref{39b,,PyArg_ParseTuple()} ，但很快会做出改动。

@node 可选参数组,采用真正的 Argument Clinic 转换器，而不是 “传统转换器”,利用 PyArg_UnpackTuple 对函数进行转换,进阶
@anchor{howto/clinic optional-groups}@anchor{4467}
@subsubsection 可选参数组


有些过时的函数用到了一种让人头疼的函数解析方式：计算位置参数的数量，据此用 @code{switch} 语句进行各个不同的 @ref{39b,,PyArg_ParseTuple()} 调用。（这些函数不能接受只认关键字的参数。）在没有 @ref{6cb,,PyArg_ParseTupleAndKeywords()} 之前，这种方式曾被用于模拟可选参数。

虽然这种函数通常可以转换为采用  @ref{6cb,,PyArg_ParseTupleAndKeywords()} 、可选参数和默认值的方式，但并不是全都可以做到。这些过时函数中， @ref{6cb,,PyArg_ParseTupleAndKeywords()} 并不能直接支持某些功能。最明显的例子是内置函数 @code{range()}，它的必需参数的 @emph{左} 边存在一个可选参数！另一个例子是 @code{curses.window.addch()}，它的两个参数是一组，必须同时指定。（参数名为 @code{x} 和 @code{y}；如果调用函数时传入了 @code{x}，则必须同时传入`@w{`}y`@w{`}；如果未传入 @code{x} ，则也不能传入 @code{y}）。

不管怎么说，Argument Clinic 的目标就是在不改变语义的情况下支持所有现有 CPython 内置参数的解析。因此，Argument Clinic 采用所谓的 @emph{可选组} 方案来支持这种解析方式。可选组是必须一起传入的参数组。他们可以在必需参数的左边或右边，@emph{只能} 用于只认位置的参数。

@cartouche
@quotation 注解 
可选组 @emph{仅} 适用于多次调用 @ref{39b,,PyArg_ParseTuple()} 的函数！采用 @emph{任何} 其他方式解析参数的函数，应该 @emph{几乎不} 采用可选组转换为 Argument Clinic 解析。目前，采用可选组的函数在 Python 中无法获得准确的签名，因为 Python 不能理解这个概念。请尽可能避免使用可选组。
@end quotation
@end cartouche

若要定义可选组，可在要分组的参数前面加上 @code{[}，在这些参数后加上`@w{`}]`@w{`} ，要在同一行上。举个例子，下面是 @code{curses.window.addch} 采用可选组的用法，前两个参数和最后一个参数可选：

@example
/*[clinic input]

curses.window.addch

    [
    x: int
      X-coordinate.
    y: int
      Y-coordinate.
    ]

    ch: object
      Character to add.

    [
    attr: long
      Attributes for the character.
    ]
    /

...
@end example

注释:


@itemize *

@item 
每一个可选组，都会额外传入一个代表分组的参数。 参数为 int 型，名为 @code{group_@{direction@}_@{number@}}，其中 @code{@{direction@}} 取决于此参数组位于必需参数 @code{right} 还是 @code{left}，而 @code{@{number@}} 是一个递增数字（从 1 开始），表示此参数组与必需参数之间的距离。 在调用函数时，若未用到此参数组则此参数将设为零，若用到了参数组则该参数为非零。 所谓的用到或未用到，是指在本次调用中形参是否收到了实参。

@item 
如果不存在必需参数，可选组的行为等同于出现在必需参数的右侧。

@item 
在模棱两可的情况下，参数解析代码更倾向于参数左侧（在必需参数之前）。

@item 
可选组只能包含只认位置的参数。

@item 
可选组 @emph{仅限} 用于过时代码。请勿在新的代码中使用可选组。
@end itemize

@node 采用真正的 Argument Clinic 转换器，而不是 “传统转换器”,Py_buffer,可选参数组,进阶
@anchor{howto/clinic using-real-argument-clinic-converters-instead-of-legacy-converters}@anchor{4468}
@subsubsection 采用真正的 Argument Clinic 转换器，而不是 “传统转换器”


为了节省时间，尽量减少要学习的内容，实现第一次适用 Argument Clinic 的移植，上述练习简述的是“传统转换器”的用法。“传统转换器”只是一种简便用法，目的就是更容易地让现有代码移植为适用于 Argument Clinic 。说白了，在移植 Python 3.4 的代码时，可以考虑采用。

不过从长远来看，可能希望所有代码块都采用真正的 Argument Clinic 转换器语法。原因如下：


@itemize *

@item 
合适的转换器可读性更好，意图也更清晰。

@item 
有些格式符是“传统转换器”无法支持的，因为这些格式需要带上参数，而传统转换器的语法不支持指定参数。

@item 
后续可能会有新版的参数解析库，提供超过 @ref{39b,,PyArg_ParseTuple()} 支持的功能；而这种灵活性将无法适用于传统转换器转换的参数。
@end itemize

因此，若是不介意多花一点精力，请使用正常的转换器，而不是传统转换器。

简而言之，Argument Clinic（非传统）转换器的语法看起来像是 Python 函数调用。但如果函数没有明确的参数（所有函数都取默认值），则可以省略括号。因此 @code{bool} 和 @code{bool()} 是完全相同的转换器。

Argument Clinic 转换器的所有参数都只认关键字。所有 Argument Clinic 转换器均可接受以下参数：

@quotation


@table @asis

@item @code{c_default}

该参数在 C 语言中的默认值。具体来说，将是在“解析函数”中声明的变量的初始化器。用法参见 @ref{4462,,the section on default values} 。定义为字符串。

@item @code{annotation}

参数的注解值。目前尚不支持，因为 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 规定 Python 库不得使用注解。
@end table
@end quotation

此外，某些转换器还可接受额外的参数。下面列出了这些额外参数及其含义：

@quotation


@table @asis

@item @code{accept}

一组 Python 类型（可能还有伪类型）；用于限制只接受这些类型的 Python 参数。（并非通用特性；只支持传统转换器列表中给出的类型）。

若要能接受 @code{None}，请在集合中添加 @code{NoneType}。

@item @code{bitwise}

只支持无符号整数。写入形参的将是 Python 实参的原生整数值，不做任何越界检查，即便是负值也一样。

@item @code{converter}

只有 @code{object} 转换器才支持。为某个 @ref{3ecb,,C 转换函数} 指定名称，用于将对象转换为原生类型。

@item @code{encoding}

只支持字符串。指定将 Python str(Unicode) 转换为 C 语言的 @code{char *} 时要使用的编码。

@item @code{subclass_of}

只有 @code{object} 转换器才支持。要求 Python 值是 Python 类型的子类，用 C 语言表示。

@item @code{type}

只有 @code{object} 和 @code{self} 转换器才支持。指定用于声明变量的 C 类型。 默认值是 @code{"PyObject *"}。

@item @code{zeroes}

仅用于字符串。如果为 True，则允许在值中嵌入 NUL 字节（@code{'\\0'}）。字符串的长度将通过名为 @code{<parameter_name>_length} 的参数传入，跟在字符串参数的后面。
@end table
@end quotation

请注意，并不是所有参数的组合都能正常生效。通常这些参数是由相应的 @code{PyArg_ParseTuple} @emph{格式化单元} 实现的，行为是固定的。比如目前不能不指定 @code{bitwise=True} 就去调用 @code{unsigned_short}。虽然完全有理由认为这样可行，但这些语义并没有映射到任何现有的格式化单元。所以 Argument Clinic 并不支持。（或者说，至少目前还不支持。）

下表显示了传统转换器映射到实参转换器的情况。左边是传统转换器，右边是要替换它的文本。


@multitable {xxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@item

@code{'B'}

@tab

@code{unsigned_char(bitwise=True)}

@item

@code{'b'}

@tab

@code{unsigned_char}

@item

@code{'c'}

@tab

@code{char}

@item

@code{'C'}

@tab

@code{int(accept=@{str@})}

@item

@code{'d'}

@tab

@code{double}

@item

@code{'D'}

@tab

@code{Py_complex}

@item

@code{'es'}

@tab

@code{str(encoding='name_of_encoding')}

@item

@code{'es#'}

@tab

@code{str(encoding='name_of_encoding', zeroes=True)}

@item

@code{'et'}

@tab

@code{str(encoding='name_of_encoding', accept=@{bytes, bytearray, str@})}

@item

@code{'et#'}

@tab

@code{str(encoding='name_of_encoding', accept=@{bytes, bytearray, str@}, zeroes=True)}

@item

@code{'f'}

@tab

@code{float}

@item

@code{'h'}

@tab

@code{short}

@item

@code{'H'}

@tab

@code{unsigned_short(bitwise=True)}

@item

@code{'i'}

@tab

@code{int}

@item

@code{'I'}

@tab

@code{unsigned_int(bitwise=True)}

@item

@code{'k'}

@tab

@code{unsigned_long(bitwise=True)}

@item

@code{'K'}

@tab

@code{unsigned_long_long(bitwise=True)}

@item

@code{'l'}

@tab

@code{long}

@item

@code{'L'}

@tab

@code{long long}

@item

@code{'n'}

@tab

@code{Py_ssize_t}

@item

@code{'O'}

@tab

@code{object}

@item

@code{'O!'}

@tab

@code{object(subclass_of='&PySomething_Type')}

@item

@code{'O&'}

@tab

@code{object(converter='name_of_c_function')}

@item

@code{'p'}

@tab

@code{bool}

@item

@code{'S'}

@tab

@code{PyBytesObject}

@item

@code{'s'}

@tab

@code{str}

@item

@code{'s#'}

@tab

@code{str(zeroes=True)}

@item

@code{'s*'}

@tab

@code{Py_buffer(accept=@{buffer, str@})}

@item

@code{'U'}

@tab

@code{unicode}

@item

@code{'u'}

@tab

@code{Py_UNICODE}

@item

@code{'u#'}

@tab

@code{Py_UNICODE(zeroes=True)}

@item

@code{'w*'}

@tab

@code{Py_buffer(accept=@{rwbuffer@})}

@item

@code{'Y'}

@tab

@code{PyByteArrayObject}

@item

@code{'y'}

@tab

@code{str(accept=@{bytes@})}

@item

@code{'y#'}

@tab

@code{str(accept=@{robuffer@}, zeroes=True)}

@item

@code{'y*'}

@tab

@code{Py_buffer}

@item

@code{'Z'}

@tab

@code{Py_UNICODE(accept=@{str, NoneType@})}

@item

@code{'Z#'}

@tab

@code{Py_UNICODE(accept=@{str, NoneType@}, zeroes=True)}

@item

@code{'z'}

@tab

@code{str(accept=@{str, NoneType@})}

@item

@code{'z#'}

@tab

@code{str(accept=@{str, NoneType@}, zeroes=True)}

@item

@code{'z*'}

@tab

@code{Py_buffer(accept=@{buffer, str, NoneType@})}

@end multitable


举个例子，下面是采用合适的转换器的例子 @code{pickle.Pickler.dump}：。

@example
/*[clinic input]
pickle.Pickler.dump

    obj: object
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/
@end example

真正的转换器有一个优点，就是比传统的转换器更加灵活。例如，@code{unsigned_int} 转换器（以及所有 @code{unsigned_} 转换器）可以不设置 @code{bitwise=True} 。 他们默认会对数值进行范围检查，而且不会接受负数。 用传统转换器就做不到这一点。

Argument Clinic 会列明其全部转换器。每个转换器都会给出可接受的全部参数，以及每个参数的默认值。只要运行 @code{Tools/clinic/clinic.py --converters} 就能得到完整的列表。

@node Py_buffer,高级转换器,采用真正的 Argument Clinic 转换器，而不是 “传统转换器”,进阶
@anchor{howto/clinic py-buffer}@anchor{4469}
@subsubsection Py_buffer


在使用 @code{Py_buffer} 转换器（或者 @code{'s*'}、@code{'w*'}、@code{'*y'} 或 @code{'z*'} 传统转换器）时，@emph{不可} 在所提供的缓冲区上调用 @ref{e21,,PyBuffer_Release()}。 Argument Clinic 生成的代码会自动完成此操作（在解析函数中）。

@node 高级转换器,参数的默认值,Py_buffer,进阶
@anchor{howto/clinic advanced-converters}@anchor{446a}
@subsubsection 高级转换器


还记得初次尝试时跳过的那些格式单元吗，因为他们是高级内容？下面就来介绍这些内容。

其实诀窍在于，这些格式单元都需要给出参数——要么是转换函数，要么是类型，要么是指定编码的字符串。（但 “传统转换器”不支持参数。这就是为什么第一个函数要跳过这些内容）。为格式单元指定的参数于是就成了转换器的参数；参数可以是 @code{converter`@w{`}（对于 `@w{`}O&}）、@code{subclass_of`@w{`}（对于 `@w{`}O!}），或者是 @code{encoding} （对于 @code{e} 开头的格式单元）。

在使用 @code{subclass_of} 时，可能还需要用到 @code{object()} 的另一个自定义参数：@code{type}，用于设置参数的实际类型。例如，为了确保对象是 @code{PyUnicode_Type} 的子类，可能想采用转换器 @code{object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type')}。

Argument Clinic 用起来可能存在一个问题：丧失了 @code{e} 开头的格式单位的一些灵活性。在手工编写 @code{PyArg_Parse} 调用时，理论上可以在运行时决定传给 @ref{39b,,PyArg_ParseTuple()} 的编码字符串。但现在这个字符串必须在 Argument-Clinic 预处理时进行硬编码。这个限制是故意设置的；以便简化对这种格式单元的支持，并允许以后进行优化。这个限制似乎并不合理；CPython 本身总是为 @code{e} 开头的格式单位参数传入静态的硬编码字符串。

@node 参数的默认值,默认值 NULL,高级转换器,进阶
@anchor{howto/clinic default-values}@anchor{4462}@anchor{howto/clinic parameter-default-values}@anchor{446b}
@subsubsection 参数的默认值


参数的默认值可以是多个值中的一个。最简单的可以是字符串、int 或 float 字面量。

@example
foo: str = "abc"
bar: int = 123
bat: float = 45.6
@end example

还可以使用 Python 的任何内置常量。

@example
yep:  bool = True
nope: bool = False
nada: object = None
@end example

对默认值 @code{NULL} 和简单表达式还提供特别的支持，后续章节中将会介绍。

@node 默认值 NULL,设为默认值的表达式,参数的默认值,进阶
@anchor{howto/clinic the-null-default-value}@anchor{446c}
@subsubsection 默认值 @code{NULL}


对于字符串和对象参数而言，可以设为 @code{None}，表示没有默认值。但这意味着会将 C 变量初始化为 @code{Py_None}。为了方便起见，提供了一个特殊值`@w{`}NULL`@w{`}，目的就是为了让 Python 认为默认值就是 @code{None}，而 C 变量则会初始化为 @code{NULL}。

@node 设为默认值的表达式,返回转换器,默认值 NULL,进阶
@anchor{howto/clinic expressions-specified-as-default-values}@anchor{446d}
@subsubsection 设为默认值的表达式


参数的默认值不仅可以是字面量。还可以是一个完整的表达式，可采用数学运算符及对象的属性。但这种支持并没有那么简单，因为存在一些不明显的语义。

请考虑以下例子：

@example
foo: Py_ssize_t = sys.maxsize - 1
@end example

@code{sys.maxsize} 在不同的系统平台可能有不同的值。因此，Argument Clinic 不能简单地在本底环境对表达式求值并用 C 语言硬编码。所以默认值将用表达式的方式存储下来，运行的时候在请求函数签名时会被求值。

在对表达式进行求值时，可以使用什么命名空间呢？求值过程运行于内置模块的上下文中。 因此，如果模块带有名为 @code{max_widgets} 的属性，直接引用即可。

@example
foo: Py_ssize_t = max_widgets
@end example

如果表达式不在当前模块中，就会去 @code{sys.modules} 查找。比如 @code{sys.maxsize} 就是如此找到的。（因为事先不知道用户会加载哪些模块到解释器中，所以最好只用到 Python 会预加载的模块。）

仅当运行时才对缺省值求值，意味着 Argument Clinic 无法计算出正确的 C 缺省值。所以需显式给出。在使用表达式时，必须同时用转换器的`@w{`}c_default`@w{`} 参数指定 C 语言中的等价表达式。

@example
foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1
@end example

还有一个问题也比较复杂。Argument Clinic 无法事先知道表达式是否有效。 解析只能保证看起来是有效值，但无法 @emph{实际} 知晓。在用表达式时须十分小心，确保在运行时能得到有效值。

最后一点，由于表达式必须能表示为静态的 C 语言值，所以存在许多限制。 以下列出了不得使用的 Python 特性：


@itemize *

@item 
功能调用

@item 
行内 if 语句（@code{3 if foo else 5} ）

@item 
序列自动解包（@code{*[1, 2, 3]}）

@item 
列表/集合/字典的解析和生成器表达式。

@item 
元组、列表、集合、字典的字面量
@end itemize

@node 返回转换器,复制已有的函数,设为默认值的表达式,进阶
@anchor{howto/clinic using-a-return-converter}@anchor{446e}
@subsubsection 返回转换器


Argument Clinic 生成的植入函数默认会返回 @code{PyObject *}。但是通常 C 函数的任务是要对某些 C 类型进行计算，然后将其转换为 @code{PyObject *} 作为结果。Argument Clinic 可以将输入参数由 Python 类型转换为本地 C 类型——为什么不让它将返回值由本地 C 类型转换为 Python 类型呢？

这就是“返回转换器”的用途。它将植入函数修改成返回某种 C 语言类型，然后在生成的（非植入）函数中添加代码，以便将 C 语言值转换为合适的 @code{PyObject *}。

返回值转换器的语法与参数转换器的类似。返回值转换器的定义方式，类似于函数返回值的注解。返回值转换器的行为与参数转换器基本相同，接受参数，参数只认关键字，如果不修改默认参数则可省略括号。

（如果函数同时用到了 @code{"as"} 和返回值转换器， @code{"as"} 应位于返回值转换器之前。）

返回值转换器还存在一个复杂的问题：出错信息如何表示？通常函数在执行成功时会返回一个有效（非 @code{NULL}）指针，失败则返回 @code{NULL}。但如果使用了整数的返回值转换器，所有整数都是有效值。Argument Clinic 怎么检测错误呢？解决方案是：返回值转换器会隐含寻找一个代表错误的特殊值。如果返回该特殊值，且设置了出错标记（ @code{PyErr_Occurred()} 返回 True），那么生成的代码会传递该错误。否则，会对返回值进行正常编码。

目前 Argument Clinic 只支持少数几种返回值转换器。

@example
bool
int
unsigned int
long
unsigned int
size_t
Py_ssize_t
float
double
DecodeFSDefault
@end example

这些转换器都不需要参数。前3个转换器如果返回 -1 则表示出错。@code{DecodeFSDefault} 的返回值类型是 @code{const char *}；若返回 @code{NULL} 指针则表示出错。

（还有一个 @code{NoneType} 转换器是实验性质的，成功时返回 @code{Py_None} ，失败则返回 @code{NULL}，且不会增加 @code{Py_None} 的引用计数。此转换器是否值得适用，尚不明确）。

只要运行 @code{Tools/clinic/clinic.py --converters} ，即可查看 Argument Clinic 支持的所有返回值转换器，包括其参数。

@node 复制已有的函数,调用 Python 代码,返回转换器,进阶
@anchor{howto/clinic cloning-existing-functions}@anchor{446f}
@subsubsection 复制已有的函数


如果已有一些函数比较相似，或许可以采用 Clinic 的“克隆”功能。 克隆之后能够复用以下内容：


@itemize *

@item 
参数，包括：


@itemize *

@item 
名称

@item 
转换器（带有全部参数）

@item 
默认值

@item 
参数前的文档字符串

@item 
@emph{类别} （只认位置、位置或关键字、只认关键字）
@end itemize

@item 
返回值转换器
@end itemize

唯一不从原函数中复制的是文档字符串；这样就能指定一个新的文档串。

下面是函数的克隆方法：

@example
/*[clinic input]
module.class.new_function [as c_basename] = module.class.existing_function

Docstring for new_function goes here.
[clinic start generated code]*/
@end example

（原函数可以位于不同的模块或类中。示例中的 @code{module.class} 只是为了说明，@emph{两个} 函数都必须使用全路径）。

对不起，没有什么语法可对函数进行部分克隆或克隆后进行修改。克隆要么全有要么全无。

另外，要克隆的函数必须在当前文件中已有定义。

@node 调用 Python 代码,参数 self 转换器的用法,复制已有的函数,进阶
@anchor{howto/clinic calling-python-code}@anchor{4470}
@subsubsection 调用 Python 代码


下面的高级内容需要编写 Python 代码，存于 C 文件中，并修改 Argument Clinic 的运行状态。其实很简单：只需定义一个 Python 块。

Python 块的分隔线与 Argument Clinic 函数块不同。如下所示：

@example
/*[python input]
# python code goes here
[python start generated code]*/
@end example

Python 块内的所有代码都会在解析时执行。块内写入 stdout 的所有文本都被重定向到块后的“输出”部分。

以下例子包含了 Python 块，用于在 C 代码中添加一个静态整数变量：

@example
/*[python input]
print('static int __ignored_unused_variable__ = 0;')
[python start generated code]*/
static int __ignored_unused_variable__ = 0;
/*[python checksum:...]*/
@end example

@node 参数 self 转换器的用法,编写自定义转换器,调用 Python 代码,进阶
@anchor{howto/clinic using-a-self-converter}@anchor{4471}
@subsubsection 参数 self 转换器的用法


Argument Clinic 用一个默认的转换器自动添加一个“self”参数。自动将 self 参数的 @code{type} 设为声明类型时指定的“指向实例的指针”。不过 Argument Clinic 的转换器可被覆盖，也即自己指定一个转换器。只要将自己的 @code{self} 参数作为块的第一个参数即可，并确保其转换器是 @code{self_converter} 的实例或其子类。

这有什么用呢？可用于覆盖 @code{self} 的类型，或为其给个不同的默认名称。

如何指定 @code{self} 对应的自定义类型呢？如果只有 @code{self} 类型相同的一两个函数，可以直接使用 Argument Clinic 现有的 @code{self} 转换器，把要用的类型作为 @code{type} 参数传入：

@example
/*[clinic input]

_pickle.Pickler.dump

  self: self(type="PicklerObject *")
  obj: object
  /

Write a pickled representation of the given object to the open file.
[clinic start generated code]*/
@end example

如果有很多函数将使用同一类型的 @code{self}，则最好创建自己的转换器，继承自 @code{self_converter} 类但要覆盖其 @code{type} 成员：

@example
/*[python input]
class PicklerObject_converter(self_converter):
    type = "PicklerObject *"
[python start generated code]*/

/*[clinic input]

_pickle.Pickler.dump

  self: PicklerObject
  obj: object
  /

Write a pickled representation of the given object to the open file.
[clinic start generated code]*/
@end example

@node 编写自定义转换器,编写自定义的返回转换器,参数 self 转换器的用法,进阶
@anchor{howto/clinic writing-a-custom-converter}@anchor{4472}
@subsubsection 编写自定义转换器


上一节中已有提及……可以编写自己的转换器！转换器就是一个继承自`@w{`}CConverter`@w{`} 的 Python 类。假如有个参数采用了 @code{O&} 格式，对此参数进行解析就会去调用某个“转换器函数” @ref{39b,,PyArg_ParseTuple()} ，也就会用到自定义转换器。

自定义转换器类应命名为 @code{*something*_converter}。只要按此规则命名，自定义转换器类就会在 Argument Clinic 中自动注册；转换器的名称就是去除了 @code{_converter} 后缀的类名。（通过元类完成）。

不得由 @code{CConverter.__init__} 派生子类。而应编写一个 @code{converter_init()} 函数。@code{converter_init()} 必须能接受一个 @code{self} 参数；所有后续的其他参数 @emph{必须} 是只认关键字的参数。传给 Argument Clinic 转换器的所有参数都会传入自定义 @code{converter_init()} 函数。

@code{CConverter} 的其他一些成员，可能需要在自定义子类中定义。下面列出了目前的成员：


@table @asis

@item @code{type}

变量要采用的 C 语言数据类型。@code{type} 应为 @code{int} 之类的 Python 字符串，用于指定变量的类型。若为指针类型，则字符串应以 @code{' *'} 结尾。

@item @code{default}

该参数的缺省值，为 Python 数据类型。若无缺省值，则为 @code{unspecified}。

@item @code{py_default}

用 Python 代码表示的 @code{default} ，为字符串类型。若无缺省值，则为 @code{None} 。

@item @code{c_default}

用 C 代码表示的 @code{default}， 为字符串类型。若无缺省值，则为 @code{None} 。

@item @code{c_ignored_default}

在无缺省值时用于初始化 C 变量的缺省值，因为不指定缺省值可能会引发“变量未初始化”的警告。在用到多组可选项的时候很容易发生这种情况，尽管好的代码实际不会用到这个值，但确实会给 impl 传入本值，而 C 编译器则会认为“用到”了未初始化的值。应确保本值为非空字符串。

@item @code{converter}

C 转换器的名称，字符串类型。

@item @code{impl_by_reference}

布尔值。如果为 True，则 Argument Clinic 在将变量传入 impl 函数时，会在其名称前加上一个 @code{&}。

@item @code{parse_by_reference}

布尔值。如果为真，则 Argument Clinic 在将变量传入  @code{PyArg_ParseTuple' 时，会在变量名前加上一个 `@w{`}&`()}。
@end table

下面是最简单的自定义转换器示例，取自 @code{Modules/zlibmodule.c} ：

@example
/*[python input]

class ssize_t_converter(CConverter):
    type = 'Py_ssize_t'
    converter = 'ssize_t_converter'

[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
@end example

这个代码块为 Argument Clinic 添加了一个名为 @code{ssize_t} 的转换器。 声明为 @code{ssize_t} 的形参将被声明为 @ref{391,,Py_ssize_t} 类型，并将由 @code{'O&'} 格式单元来解析，它将调用 @code{ssize_t_converter} 转换器函数。 @code{ssize_t} 变量会自动支持默认值。

更复杂些的自定义转换器，可以插入自定义 C 代码来进行初始化和清理工作。可以在 CPython 源码中看到自定义转换器的更多例子；只要在 C 文件中搜索字符串 @code{CConverter} 即可。

@node 编写自定义的返回转换器,METH_O 和 METH_NOARGS,编写自定义转换器,进阶
@anchor{howto/clinic writing-a-custom-return-converter}@anchor{4473}
@subsubsection 编写自定义的返回转换器


自定义的返回值转换器的写法，与自定义的转换器十分类似。因为返回值转换器本身就很简单，编写起来就简单一些。

返回值转换器必须是 @code{CReturnConverter} 的子类。因为自定义的返回值转换器还没有广泛应用，目前还没有示例。若要编写返回值转换器，请阅读`@w{`}Tools/clinic/clinic.py`@w{`} ，特别是 @code{CReturnConverter} 及其所有子类的实现代码。

@node METH_O 和 METH_NOARGS,tp_new 和 tp_init functions,编写自定义的返回转换器,进阶
@anchor{howto/clinic meth-o-and-meth-noargs}@anchor{4474}
@subsubsection METH_O 和 METH_NOARGS


若要用 @code{METH_O} 对函数进行转换，请确保对该函数的单个参数使用 @code{object} 转换器，并将参数标为只认位置的：

@example
/*[clinic input]
meth_o_sample

     argument: object
     /
[clinic start generated code]*/
@end example

若要用 @code{METH_NOARGS} 对函数进行转换，只需不定义参数即可。

依然可以采用一个 self 转换器、一个返回值转换器，并为 @code{METH_O} 的对象转换器指定一个 @code{type} 参数。

@node tp_new 和 tp_init functions,改变和重定向 Clinic 的输出,METH_O 和 METH_NOARGS,进阶
@anchor{howto/clinic tp-new-and-tp-init-functions}@anchor{4475}
@subsubsection tp_new 和 tp_init functions


@code{tp_new} 和 @code{tp_init} 函数也可以转换。只要命名为 @code{__new__} 或 @code{__init__} 即可。注意：


@itemize *

@item 
为转换 @code{__new__} 而生成的函数名不会以其默认名称结尾。只会是转换为合法 C 标识符的类名。

@item 
转换这些函数不会生成 @code{PyMethodDef} 、@code{#define}。

@item 
@code{__init__} 函数将返回 @code{int} ，而不是 @code{PyObject *} 。

@item 
将文档字符串用作类文档字符串。

@item 
虽然 @code{__new__} 和 @code{__init__} 函数必须以 @code{args`@w{`}和 `@w{`}kwargs} 对象作为参数，但在转换时可按个人喜好定义函数签名。（如果原函数不支持关键字参数，则生成的解析函数在收到关键字参数时会抛出异常）。
@end itemize

@node 改变和重定向 Clinic 的输出,#ifdef 使用技巧,tp_new 和 tp_init functions,进阶
@anchor{howto/clinic changing-and-redirecting-clinic-s-output}@anchor{4476}
@subsubsection 改变和重定向 Clinic 的输出


若是让 Clinic 的输出与传统的手写 C 代码交织在一起，可能会不方便使用。 幸好可以对 Clinic 进行配置：可以将输出结果缓存起来以供打印，或将输出结果写入文件中。针对 Clinic 生成的输出结果，还可以为每一行都加上前缀或后缀。

虽然修改 Clinic 的输出提升了可读性，但可能会导致 Clinic 代码使用了未经定义的类型，或者会提前用到 Clinic 生成的代码。通过重新安排声明在代码文件的位置，或将 Clinic 生成的代码移个位置，即可轻松解决上述问题。（这就是 Clinic 默认是全部输出到当前代码块的原因；虽然许多人认为降低了可读性，但这样就根本不用重新编排代码来解决提前引用的问题）。

就从定义一些术语开始吧：


@table @asis

@item @emph{field}

在当前上下文中，区块是指 Clinic 输出的一个小节。例如，@code{PyMethodDef} 结构的 @code{#define} 是一个区块，名为 @code{methoddef_define}。Clinic 在每个函数定义中可以输出7个区块。

@example
docstring_prototype
docstring_definition
methoddef_define
impl_prototype
parser_prototype
parser_definition
impl_definition
@end example

区块均以 @code{"<a>_<b>"} 形式命名，其中 @code{"<a>"} 是所代表的语义对象（解析函数、impl 函数、文档字符串或 methoddef 结构），@code{"<b>"} 表示该区块的类别。以 @code{"_prototype"} 结尾的区块名表示这只是个前向声明，没有实际的函数体或数据；以 @code{"_definition"} 结尾的区块名则表示这是实际的函数定义，包含了函数体和数据。（@code{"methoddef"} 比较特殊，是唯一一个以 @code{"_define"} 结尾的区块名，表明这是一个预处理器 #define。）

@item @emph{目的地（destination）}

目的地是 Clinic 可以进行输出的地方。内置的输出目的地有5种：


@table @asis

@item @code{block}

默认目的地：在 Clinic 当前代码块的输出区域进行输出。

@item @code{buffer}

文本缓冲区，可将文本保存起来以便后续使用。输出的文本会加入现有文本的末尾。如果 Clinic 处理完文件后缓冲区中还留有文本，则会报错。

@item @code{file}

单独的 “Clinic 文件”，由 Clinic 自动创建。文件名会是`@w{`}@{basename@}.clinic@{extension@}`@w{`} ，这里的 @code{basename} 和 @code{extension} 即为对当前文件运行 @code{os.path.splitext()} 后的结果。（比如：@code{_pickle.c} 的 @code{file} 目的地将会是 @code{_pickle.clinic.c})。

@strong{重点：若要使用 ** `@w{`}file`@w{`} ** 作为输出目标，你 ** *必须签入* ** 生成的文件！}

@item @code{two-pass}

类似于 @code{buffer} 的缓冲区。不过 two-pass 缓冲区只能转储一次，将会输出处理过程中发送给它的所有文本，甚至包括转储点**之后**的 Clinic 块。

@item @code{suppress}

禁止输出文本——抛弃输出。
@end table
@end table

Clinic 定义了5个新的指令，以便修改输出方式。

第一个新指令是 @code{dump}。

@example
dump <destination>
@end example

将指定输出目标的当前内容转储到当前块的输出中，并清空输出目标。仅适用于 @code{buffer} 和 @code{two-pass} 目标。

第二个新指令是 @code{output}。@code{output} 最简单的格式如下所示：

@example
output <field> <destination>
@end example

这会通知 Clinic 将指定**field**输出到指定**destination**中去。@code{output} 还支持一个特殊的元目标 @code{everything}，通知 Clinic 将**所有**区块都输出到该**目标**。

@code{output} 还包含一些函数：

@example
output push
output pop
output preset <preset>
@end example

@code{output push} 和 @code{output pop} 能在内部的配置栈中压入和弹出配置，这样就可以临时修改输出配置，然后再轻松恢复之前的配置。只需在修改前入栈保存当前配置，在恢复配置时再弹出即可。

@code{output preset} 将 Clinic 的输出目标设为内置预设目标之一，如下所示：

@quotation


@table @asis

@item @code{block}

Clinic 的初始设置。输入块后面紧接着写入所有内容。

关闭 @code{parser_prototype} 和 @code{docstring_prototype}，并将其他所有内容写入 @code{block}。

@item @code{file}

目的是全部输出至 “Clinic 文件”中。然后在文件顶部附近 @code{#include} 该文件。可能需要重新调整代码顺序才能正常运行，通常只要为  @code{typedef`@w{`}和`@w{`}PyTypeObject} 定义创建前向声明即可。

关闭 @code{parser_prototype} 和 @code{docstring_prototype} ，将 @code{impl_definition} 写入 @code{block}，其他内容写入 @code{file} 。

默认文件名为 @code{"@{dirname@}/clinic/@{basename@}.h"} 。

@item @code{buffer}

将 Clinic 的大部分输出保存起来，在快结束时写入文件。如果 Python 文件存放的是编写模块或内置类型的代码，建议紧挨着模块或内置类型的静态结构之前对缓冲区进行转储；这些结构通常位于结尾附近。如果在文件的中间位置定义了静态 @code{PyMethodDef} 数组，采用 @code{buffer} 输出所需的代码编辑工作可能比用 @code{file} 要多些。

关闭 @code{parser_prototype} 、@code{impl_prototype} 和 @code{docstring_prototype}，将 @code{impl_definition} 写入 @code{block}，其他输出都写入 @code{file}。

@item @code{two-pass}

类似于预设的  @code{buffer} 输出，但会把前向声明写入`@w{`}two-pass`@w{`} 缓冲区，将函数定义写入 @code{buffer}。这与预设的 @code{buffer} 类似，但所需的代码编辑工作可能会减少。将 @code{two-pass} 缓冲区转储到文件的顶部，将 @code{buffer} 转储到文件末尾，就像预设的 @code{buffer} 一样。

关闭 @code{impl_prototype} ，将 @code{impl_definition} 写入 @code{block} ，将 @code{docstring_prototype} 、@code{methoddef_define} 和 @code{parser_prototype} 写入`@w{`}two-pass`@w{`}，其他输出都写入 @code{buffer} 。

@item @code{partial-buffer}

与预设的 @code{buffer} 类似，但会向 @code{block} 写入更多内容，而只向 @code{buffer} 写入真正大块的生成代码。这样能完全避免 @code{buffer} 的提前引用问题，代价是输出到代码块中的内容会稍有增加。在快结束时会转储 @code{buffer}，就像采用预设的 @code{buffer} 配置一样。

关闭 @code{impl_prototype}，将 @code{docstring_definition} 和 @code{parser_definition} 写入 @code{buffer}，其他输出都写入 @code{block}。
@end table
@end quotation

第三个新指令是 @code{destination}：

@example
destination <name> <command> [...]
@end example

向名为 @code{name} 的目标执行输出。

定义了两个子命令：@code{new} 和 @code{clear}。

子命令 @code{new} 工作方式如下：

@example
destination <name> new <type>
@end example

新建一个目标，名称为 @code{<name>}，类型为`@w{`}<type>`@w{`} 。

输出目标的类型有5种：

@quotation


@table @asis

@item @code{suppress}

忽略文本。

@item @code{block}

将文本写入当前代码块中。 这就是 Clinic 原来的做法。

@item @code{buffer}

简单的文本缓冲区，就像上述的内置 “buffer” 目标。

@item @code{file}

文本文件。文件目标需要多一个参数，用于生成文件名的模板，类似于：

@quotation

destination <name> new <type> <file_template>
@end quotation

模版可以引用3个内部字符串，将会用文件名的对应部分替代：

@quotation


@table @asis

@item @{path@}

文件的全路径，包含文件夹和完整的文件名。

@item @{dirname@}

文件所在文件夹名。

@item @{basename@}

只有文件名，不含文件夹。

@item @{basename_root@}

去除了扩展名后的文件名（不含最后一个“.”）。

@item @{basename_extension@}

包含最后一个“.”及后面的字符。如果文件名中不含句点，则为空字符串。
@end table
@end quotation

如果文件名中不含句点符，@{basename@} 和 @{basename_root@} 是一样的，而 @{basename_extension@} 则为空。“@{basename_root@}@{basename_extension@}” 与“@{basename@}”一定是完全相同的。（英文原文貌似有误）

@item @code{two-pass}

two-pass 缓冲区，类似于上述的内置“two-pass”输出目标。
@end table
@end quotation

子命令 @code{clear} 的工作方式如下：

@example
destination <name> clear
@end example

清空输出目标中所有文本。（不知用途何在，但也许做实验时会有用吧。)

第4个新指令是 @code{set} ：

@example
set line_prefix "string"
set line_suffix "string"
@end example

@cite{set' 能设置 Clinic 的两个内部变量值。`@w{`}line_prefix`} 是 Clinic 每行输出的前缀字符串；@code{line_suffix} 是 Clinic 每行输出的后缀字符串。

两者都支持两种格式字符串：

@quotation


@table @asis

@item @code{@{block comment start@}}

转成字符串 @code{/*}，是 C 文件的注释起始标记。

@item @code{@{block comment end@}}

转成字符串 @code{*/}，是 C 文件的注释结束标记。
@end table
@end quotation

最后一个新指令是无需直接使用的 @code{preserve}。

@example
preserve
@end example

通知 Clinic 输出内容应保持原样。这是在转储至 @code{file} 文件中时，供 Clinic 内部使用的；以便 Clinic 能利用已有的校验函数，确保文件在被覆盖之前没进行人工修改过。

@node #ifdef 使用技巧,在 Python 文件中使用 Argument Clinic,改变和重定向 Clinic 的输出,进阶
@anchor{howto/clinic the-ifdef-trick}@anchor{4477}
@subsubsection #ifdef 使用技巧


若要转换的函数并非通用于所有平台，可以采用一个技巧。当前代码可能如下所示：

@example
#ifdef HAVE_FUNCTIONNAME
static module_functionname(...)
@{
...
@}
#endif /* HAVE_FUNCTIONNAME */
@end example

在底部的 @code{PyMethodDef} 结构中，当前代码如下：

@example
#ifdef HAVE_FUNCTIONNAME
@{'functionname', ... @},
#endif /* HAVE_FUNCTIONNAME */
@end example

这时应将 impl 函数体用 @code{#ifdef} 包裹起来，如下所示：

@example
#ifdef HAVE_FUNCTIONNAME
/*[clinic input]
module.functionname
...
[clinic start generated code]*/
static module_functionname(...)
@{
...
@}
#endif /* HAVE_FUNCTIONNAME */
@end example

然后，从 @code{PyMethodDef} 结构中删除以下3行，替换成 Argument Clinic 生成的宏：

@example
MODULE_FUNCTIONNAME_METHODDEF
@end example

（在生成的代码中可找到宏的真实名称。或者可以自行求一下值：块的第一行定义的函数名，句点改为下划线，全部大写，并在末尾加上 @code{"_METHODDEF"} ）

如果 @code{HAVE_FUNCTIONNAME} 未定义怎么办？ 那么`@w{`}MODULE_FUNCTIONNAME_METHODDEF`@w{`} 宏也不会定义。

这正是 Argument Clinic 变聪明的地方。它其实能检测到 @code{#ifdef} 屏蔽了Argument Clinic 块。于是会额外生成一小段代码，如下所示：

@example
#ifndef MODULE_FUNCTIONNAME_METHODDEF
    #define MODULE_FUNCTIONNAME_METHODDEF
#endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */
@end example

这样宏总是会生效。如果定义了函数，则会转换为正确的结构，包括尾部的逗号。如果函数未定义，就不做什么转换。

不过，这导致了一个棘手的问题：当使用 "block" 输出预设时 Argument Clinic 应该把额外的代码放到哪里呢？ 它不能放在输出代码块中，因为它可能会被 @code{#ifdef} 停用。 （它的作用就是这个！）

在此情况下，Argument Clinic 会将额外的代码的写入目标设为 "buffer"。 这意味着你可能会收到来自 Argument Clinic 的抱怨:

@example
Warning in file "Modules/posixmodule.c" on line 12357:
Destination buffer 'buffer' not empty at end of file, emptying.
@end example

当发生这种问题时，只需打开你的文件，找到由 Argument Clinic 添加到你的文件的 @code{dump buffer} 代码块（它将位于文件末尾），并将其移到使用了那个宏的 @code{PyMethodDef} 结构体之上。

@node 在 Python 文件中使用 Argument Clinic,,#ifdef 使用技巧,进阶
@anchor{howto/clinic using-argument-clinic-in-python-files}@anchor{4478}
@subsubsection 在 Python 文件中使用 Argument Clinic


实际上使用 Argument Clinic 来预处理 Python 文件也是可行的。 当然使用 Argument Clinic 代码块并没有什么意义，因为其输出对于 Python 解释器来说是没有意义的。 但是使用 Argument Clinic 来运行 Python 代码块可以让你将 Python 当作 Python 预处理器来使用！

由于 Python 注释不同于 C 注释，嵌入到 Python 文件的 Argument Clinic 代码块看起来会有一点不同。 它们看起来像是这样:

@example
#/*[python input]
#print("def foo(): pass")
#[python start generated code]*/
def foo(): pass
#/*[python checksum:...]*/
@end example

@node 使用 DTrace 和 SystemTap 检测CPython,,Argument Clinic 的用法,Python 常用指引
@anchor{howto/instrumentation doc}@anchor{4479}@anchor{howto/instrumentation instrumentation}@anchor{60e}@anchor{howto/instrumentation instrumenting-cpython-with-dtrace-and-systemtap}@anchor{447a}
@section 使用 DTrace 和 SystemTap 检测CPython


@*作者: 
David Malcolm


@*作者: 
Łukasz Langa


DTrace和SystemTap是监控工具，它们都提供了一种检查计算机系统上的进程的方法。 它们都使用特定领域的语言，允许用户编写脚本，其中：

@quotation


@itemize -

@item 
进程监视的过滤器

@item 
从感兴趣的进程中收集数据

@item 
生成有关数据的报告
@end itemize
@end quotation

从Python 3.6开始，CPython可以使用嵌入式“标记”构建，也称为“探测器”，可以通过DTrace或SystemTap脚本观察，从而更容易监视系统上的CPython进程正在做什么。

@strong{CPython implementation detail:} DTrace标记是CPython解释器的实现细节。 不保证CPython版本之间的探针兼容性。 更改CPython版本时，DTrace脚本可能会停止工作或无法正常工作而不会发出警告。

@menu
* 启用静态标记:: 
* 静态DTrace探针:: 
* 静态SystemTap标记:: 
* 可用的静态标记:: 
* SystemTap Tapsets:: 
* 示例: 示例<52>. 

@end menu

@node 启用静态标记,静态DTrace探针,,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation enabling-the-static-markers}@anchor{447b}
@subsection 启用静态标记


macOS内置了对DTrace的支持。 在Linux上，为了使用SystemTap的嵌入式标记构建CPython，必须安装SystemTap开发工具。

在Linux机器上，这可以通过：

@example
$ yum install systemtap-sdt-devel
@end example

或者：

@example
$ sudo apt-get install systemtap-sdt-dev
@end example

然后必须将CPython配置为`@w{`}--with-dtrace`@w{`}：

@example
checking for --with-dtrace... yes
@end example

在macOS上，您可以通过在后台运行Python进程列出可用的DTrace探测器，并列出Python程序提供的所有探测器：

@example
$ python3.6 -q &
$ sudo dtrace -l -P python$!  # or: dtrace -l -m python3.6

   ID   PROVIDER            MODULE                          FUNCTION NAME
29564 python18035        python3.6          _PyEval_EvalFrameDefault function-entry
29565 python18035        python3.6             dtrace_function_entry function-entry
29566 python18035        python3.6          _PyEval_EvalFrameDefault function-return
29567 python18035        python3.6            dtrace_function_return function-return
29568 python18035        python3.6                           collect gc-done
29569 python18035        python3.6                           collect gc-start
29570 python18035        python3.6          _PyEval_EvalFrameDefault line
29571 python18035        python3.6                 maybe_dtrace_line line
@end example

在Linux上，您可以通过查看是否包含“.note.stapsdt”部分来验证构建的二进制文件中是否存在SystemTap静态标记。

@example
$ readelf -S ./python | grep .note.stapsdt
[30] .note.stapsdt        NOTE         0000000000000000 00308d78
@end example

如果您已将Python构建为共享库（使用--enable-shared），则需要在共享库中查找。 例如：

@example
$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
[29] .note.stapsdt        NOTE         0000000000000000 00365b68
@end example

足够现代的readelf命令可以打印元数据：

@example
$ readelf -n ./python

Displaying notes found at file offset 0x00000254 with length 0x00000020:
    Owner                 Data size          Description
    GNU                  0x00000010          NT_GNU_ABI_TAG (ABI version tag)
        OS: Linux, ABI: 2.6.32

Displaying notes found at file offset 0x00000274 with length 0x00000024:
    Owner                 Data size          Description
    GNU                  0x00000014          NT_GNU_BUILD_ID (unique build ID bitstring)
        Build ID: df924a2b08a7e89f6e11251d4602022977af2670

Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
    Owner                 Data size          Description
    stapsdt              0x00000031          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__start
        Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
        Arguments: -4@@%ebx
    stapsdt              0x00000030          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__done
        Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
        Arguments: -8@@%rax
    stapsdt              0x00000045          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__entry
        Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
        Arguments: 8@@%rbp 8@@%r12 -4@@%eax
    stapsdt              0x00000046          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__return
        Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
        Arguments: 8@@%rbp 8@@%r12 -4@@%eax
@end example

上述元数据包含SystemTap的信息，描述如何修补策略性放置的机器代码指令以启用SystemTap脚本使用的跟踪钩子。

@node 静态DTrace探针,静态SystemTap标记,启用静态标记,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation static-dtrace-probes}@anchor{447c}
@subsection 静态DTrace探针


下面的 DTrace 脚本示例可以用来显示一个 Python 脚本的调用/返回层次结构，只在调用名为 "start" 的函数内进行跟踪。换句话说，导入时的函数调用不会被列出。

@example
self int indent;

python$target:::function-entry
/copyinstr(arg1) == "start"/
@{
        self->trace = 1;
@}

python$target:::function-entry
/self->trace/
@{
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
        self->indent++;
@}

python$target:::function-return
/self->trace/
@{
        self->indent--;
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
@}

python$target:::function-return
/copyinstr(arg1) == "start"/
@{
        self->trace = 0;
@}
@end example

它可以这样调用:

@example
$ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"
@end example

输出结果会像这样:

@example
156641360502280  function-entry:call_stack.py:start:23
156641360518804  function-entry: call_stack.py:function_1:1
156641360532797  function-entry:  call_stack.py:function_3:9
156641360546807 function-return:  call_stack.py:function_3:10
156641360563367 function-return: call_stack.py:function_1:2
156641360578365  function-entry: call_stack.py:function_2:5
156641360591757  function-entry:  call_stack.py:function_1:1
156641360605556  function-entry:   call_stack.py:function_3:9
156641360617482 function-return:   call_stack.py:function_3:10
156641360629814 function-return:  call_stack.py:function_1:2
156641360642285 function-return: call_stack.py:function_2:6
156641360656770  function-entry: call_stack.py:function_3:9
156641360669707 function-return: call_stack.py:function_3:10
156641360687853  function-entry: call_stack.py:function_4:13
156641360700719 function-return: call_stack.py:function_4:14
156641360719640  function-entry: call_stack.py:function_5:18
156641360732567 function-return: call_stack.py:function_5:21
156641360747370 function-return:call_stack.py:start:28
@end example

@node 静态SystemTap标记,可用的静态标记,静态DTrace探针,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation static-systemtap-markers}@anchor{447d}
@subsection 静态SystemTap标记


使用 SystemTap 集成的底层方法是直接使用静态标记。 这需要你显式地说明包含它们的二进制文件。

例如，这个SystemTap脚本可以用来显示Python脚本的调用/返回层次结构：

@example
probe process("python").mark("function__entry") @{
     filename = user_string($arg1);
     funcname = user_string($arg2);
     lineno = $arg3;

     printf("%s => %s in %s:%d\\n",
            thread_indent(1), funcname, filename, lineno);
@}

probe process("python").mark("function__return") @{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;

    printf("%s <= %s in %s:%d\\n",
           thread_indent(-1), funcname, filename, lineno);
@}
@end example

它可以这样调用:

@example
$ stap \
  show-call-hierarchy.stp \
  -c "./python test.py"
@end example

输出结果会像这样:

@example
11408 python(8274):        => __contains__ in Lib/_abcoll.py:362
11414 python(8274):         => __getitem__ in Lib/os.py:425
11418 python(8274):          => encode in Lib/os.py:490
11424 python(8274):          <= encode in Lib/os.py:493
11428 python(8274):         <= __getitem__ in Lib/os.py:426
11433 python(8274):        <= __contains__ in Lib/_abcoll.py:366
@end example

其中的列是：

@quotation


@itemize -

@item 
脚本开始后经过的微秒数

@item 
可执行文件的名字

@item 
进程的PID
@end itemize
@end quotation

其余部分则表示脚本执行时的调用/返回层次结构。

对于 @cite{--enable-shared} 构建的CPython来说，这些标记是包含在libpython共享库中的，探针的点状路径需要反映这一点。比如上面例子中的这一行：

@example
probe process("python").mark("function__entry") @{
@end example

应改为：

@example
probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") @{
@end example

（假设是 CPython 3.6 的调试构建）

@node 可用的静态标记,SystemTap Tapsets,静态SystemTap标记,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation available-static-markers}@anchor{447e}
@subsection 可用的静态标记



@deffn {Object} function__entry(str filename, str funcname, int lineno)

这个标记表示一个Python函数的执行已经开始。它只对纯 Python （字节码）函数触发。

文件名、函数名和行号作为位置参数提供给跟踪脚本，必须使用 @code{$arg1}, @code{$arg2}, @code{$arg3} 访问：

@quotation


@itemize *

@item 
@code{$arg1} : @code{(const char *)} 文件名，使用  @code{user_string($arg1)} 访问

@item 
@code{$arg2} : @code{(const char *)} 函数名，使用 @code{user_string($arg2)} 访问

@item 
@code{$arg3} : @code{int} 行号
@end itemize
@end quotation
@end deffn


@deffn {Object} function__return(str filename, str funcname, int lineno)

这个标记与 @code{function__entry()} 相反，表示Python函数的执行已经结束 (通过 @code{return} 或者异常)。 它只对纯Python (字节码) 函数触发。

参数和 @code{function__entry()} 相同
@end deffn


@deffn {Object} line(str filename, str funcname, int lineno)

这个标记表示一个 Python 行即将被执行。它相当于用 Python 分析器逐行追踪。它不会在C函数中触发。

参数和 @code{function__entry()} 相同
@end deffn


@deffn {Object} gc__start(int generation)

当Python解释器启动一个垃圾回收循环时被触发。 @code{arg0} 是要扫描的生成器，如 @ref{362,,gc.collect()}。
@end deffn


@deffn {Object} gc__done(long collected)

当Python解释器完成一个垃圾回收循环时被触发。@code{arg0} 是收集到的对象的数量。
@end deffn


@deffn {Object} import__find__load__start(str modulename)

在 @ref{9a,,importlib} 试图查找并加载模块之前被触发。@code{arg0} 是模块名称。


3.7 新版功能.

@end deffn


@deffn {Object} import__find__load__done(str modulename, int found)

在 @ref{9a,,importlib} 的 find_and_load 函数被调用后被触发。 @code{arg0} 是模块名称， @code{arg1} 表示模块是否成功加载。


3.7 新版功能.

@end deffn


@deffn {Object} audit(str event, void *tuple)

当 @ref{109f,,sys.audit()} 或 @ref{10b1,,PySys_Audit()} 被调用时启动。 @code{arg0} 是事件名称的 C 字符串，@code{arg1} 是一个指向元组对象的 @ref{5bd,,PyObject} 指针。


3.8 新版功能.

@end deffn

@node SystemTap Tapsets,示例<52>,可用的静态标记,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation systemtap-tapsets}@anchor{447f}
@subsection SystemTap Tapsets


使用SystemTap集成的更高层次的方法是使用 "tapset" 。SystemTap 的等效库，它隐藏了静态标记的一些底层细节。

这里是一个基于 CPython 的非共享构建的 tapset 文件。

@example
/*
   Provide a higher-level wrapping around the function__entry and
   function__return markers:
 \*/
probe python.function.entry = process("python").mark("function__entry")
@{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
@}
probe python.function.return = process("python").mark("function__return")
@{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
@}
@end example

如果这个文件安装在 SystemTap 的 tapset 目录下（例如`@w{`}/usr/share/systemtap/tapset`@w{`} ），那么这些额外的探测点就会变得可用。


@deffn {Object} python.function.entry(str filename, str funcname, int lineno, frameptr)

这个探针点表示一个Python函数的执行已经开始。它只对纯Python （字节码）函数触发。
@end deffn


@deffn {Object} python.function.return(str filename, str funcname, int lineno, frameptr)

这个探针点是 @code{python.function.return} 的反义操作，表示一个 Python 函数的执行已经结束（或是通过 @code{return}，或是通过异常）。 它只会针对纯 Python（字节码）函数触发。
@end deffn

@node 示例<52>,,SystemTap Tapsets,使用 DTrace 和 SystemTap 检测CPython
@anchor{howto/instrumentation examples}@anchor{4480}
@subsection 示例


这个SystemTap脚本使用上面的tapset来更清晰地实现上面给出的跟踪Python函数调用层次结构的例子，而不需要直接命名静态标记。

@example
probe python.function.entry
@{
  printf("%s => %s in %s:%d\n",
         thread_indent(1), funcname, filename, lineno);
@}

probe python.function.return
@{
  printf("%s <= %s in %s:%d\n",
         thread_indent(-1), funcname, filename, lineno);
@}
@end example

下面的脚本使用上面的tapset提供了所有运行中的CPython代码的顶部视图，显示了整个系统中每一秒钟最频繁输入的前20个字节码帧。

@example
global fn_calls;

probe python.function.entry
@{
    fn_calls[pid(), filename, funcname, lineno] += 1;
@}

probe timer.ms(1000) @{
    printf("\033[2J\033[1;1H") /* clear screen \*/
    printf("%6s %80s %6s %30s %6s\n",
           "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
    foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) @{
        printf("%6d %80s %6d %30s %6d\n",
            pid, filename, lineno, funcname,
            fn_calls[pid, filename, funcname, lineno]);
    @}
    delete fn_calls;
@}
@end example

@node Python 常见问题,术语对照表,Python 常用指引,Top
@anchor{faq/index doc}@anchor{4481}@anchor{faq/index faq-index}@anchor{147d}@anchor{faq/index python-frequently-asked-questions}@anchor{4482}
@chapter Python 常见问题


@menu
* Python常见问题:: 
* 编程常见问题:: 
* 设计和历史常见问题:: 
* 代码库和插件 FAQ:: 
* 扩展/嵌入常见问题:: 
* Python在Windows上的常见问题:: 
* 图形用户界面（GUI）常见问题:: 
* “为什么我的电脑上安装了 Python ？”:: 

@end menu

@node Python常见问题,编程常见问题,,Python 常见问题
@anchor{faq/general doc}@anchor{4483}@anchor{faq/general general-python-faq}@anchor{4484}
@section Python常见问题



@menu
* 一般信息:: 
* 现实世界中的 Python:: 

@end menu

@node 一般信息,现实世界中的 Python,,Python常见问题
@anchor{faq/general general-information}@anchor{4485}
@subsection 一般信息


@menu
* 什么是 Python？:: 
* 什么是 Python 软件基金会？:: 
* 使用 Python 是否存在版权限制？:: 
* 创造 Python 的最初理由是什么？:: 
* Python 适合做什么？:: 
* Python 版本的编号形式是怎样的？:: 
* 我应如何获取一份 Python 源代码的副本？:: 
* 我应如何获取 Python 的文档？:: 
* 我之前从未接触过编程。 哪里有 Python 的教程？:: 
* 是否有专门针对 Python 的新闻组或邮件列表？:: 
* 我应如何获取 Python 的公开测试版本？:: 
* 我应如何为 Python 提交错误报告和补丁？:: 
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？:: 
* 是否有任何 Python 相关的书籍？:: 
* www.python.org 具体位于世界上的哪个地点？: www python org 具体位于世界上的哪个地点？. 
* 为何命名为 Python？:: 
* 我必须喜欢 "Monty Python 的飞行马戏团" 吗？:: 

@end menu

@node 什么是 Python？,什么是 Python 软件基金会？,,一般信息
@anchor{faq/general what-is-python}@anchor{4486}
@subsubsection 什么是 Python？


Python 是一种解释型、交互式、面向对象的编程语言。 它包含了模块、异常、动态类型、高层级动态数据类型以及类等特性。 在面向对象编程以外它还支持多种编程范式，例如过程式和函数式编程等。 Python 结合了超强的功能和极清晰的语法。 它带有许多系统调用和库以及多种窗口系统的接口，并且能用 C 或 C++ 来进行扩展。 它还可用作需要可编程接口的应用程序的扩展语言。 最后，Python 非常易于移植：它可以在包括 Linux 和 macOS 在内的许多 Unix 变种以及 Windows 上运行。

要了解更多详情，请先查看 @ref{135e,,Python 教程}。 Python 新手指南@footnote{https://wiki.python.org/moin/BeginnersGuide} 提供了学习 Python 的其他入门教程及资源的链接。

@node 什么是 Python 软件基金会？,使用 Python 是否存在版权限制？,什么是 Python？,一般信息
@anchor{faq/general what-is-the-python-software-foundation}@anchor{4487}
@subsubsection 什么是 Python 软件基金会？


Python 软件基金会（Python Software Foundation，简称 PSF）是一个独立的非盈利组织，它拥有 Python 2.1 及以上各版本的版权。 PSF 的使命是推进与 Python 编程语言相关的开源技术，并推广 Python 的使用。 PSF 的主页是 @indicateurl{https://www.python.org/psf/}。

向 PSF 提供捐助在美国是免税的。 如果你在使用 Python 并且感觉它对你很有帮助，可以通过 PSF 捐助页@footnote{https://www.python.org/psf/donations/} 进行捐助。

@node 使用 Python 是否存在版权限制？,创造 Python 的最初理由是什么？,什么是 Python 软件基金会？,一般信息
@anchor{faq/general are-there-copyright-restrictions-on-the-use-of-python}@anchor{4488}
@subsubsection 使用 Python 是否存在版权限制？


你可以任意使用源码，只要你保留版权信息并在你基于 Python 的产品文档中显示该版权信息。 如果你遵守此版权规则，就可以将 Python 用于商业领域，以源码或二进制码的形式（不论是否经过修改）销售 Python 的副本，或是以某种形式包含了 Python 的产品。 当然，我们仍然希望获知所有对 Python 的商业使用。

请参阅 PSF 许可页@footnote{https://www.python.org/psf/license/} 以查看进一步的说明以及许可的完整文本内容的链接。

Python 的徽标是注册商标，在某些情况下需要获得允许方可使用。 请参阅 商标使用政策@footnote{https://www.python.org/psf/trademarks/} 了解详情。

@node 创造 Python 的最初理由是什么？,Python 适合做什么？,使用 Python 是否存在版权限制？,一般信息
@anchor{faq/general why-was-python-created-in-the-first-place}@anchor{4489}
@subsubsection 创造 Python 的最初理由是什么？


以下是有关最初缘起的一份 @emph{非常} 简短的摘要，由 Guido van Rossum 本人撰写:

@quotation

我在 CWI 的 ABC 部门时在实现解释型语言方面积累了丰富经验，通过与这个部门成员的协同工作，我学到了大量有关语言设计的知识。 这是许多 Python 特性的最初来源，包括使用缩进来组织语句以及包含非常高层级的数据结构（虽然在 Python 中具体的实现细节完全不同）。

我对 ABC 语言有过许多抱怨，但同时也很喜欢它的许多特性。 没有可能通过扩展 ABC 语言（或它的实现）来弥补我的不满 —— 实际上缺乏可扩展性就是它最大的问题之一。 我也有一些使用 Modula-2+ 的经验，并曾与 Modula-3 的设计者进行交流，还阅读了 Modula-3 的报告。 Modula-3 是 Python 中异常机制所用语法和语义，以及其他一些语言特性的最初来源。

我还曾在 CWI 的 Amoeba 分布式操作系统部门工作。 当时我们需要有一种比编写 C 程序或 Bash 脚本更好的方式来进行系统管理，因为 Amoeba 有它自己的系统调用接口，并且无法方便地通过 Bash 来访问。 我在 Amoeba 中处理错误的经验令我深刻地意识到异常处理在编程语言特性当中的重要地位。

我发现，某种具有 ABC 式的语法而又能访问 Amoeba 系统调用的脚本语言将可满足需求。 我意识到编写一种 Amoeba 专属的语言是愚蠢的，所以我决定编写一种具有全面可扩展性的语言。

在 1989 年的圣诞假期中，我手头的时间非常充裕，因此我决定开始尝试一下。 在接下来的一年里，虽然我仍然主要用我的业余时间来做这件事，但 Python 在 Amoeba 项目中的使用获得了很大的成功，来自同事的反馈让我得以增加了许多早期的改进。

到 1991 年 2 月，经过一年多的开发，我决定将其发布到 USENET。 之后的事情就都可以在 @code{Misc/HISTORY} 文件里面看了。
@end quotation

@node Python 适合做什么？,Python 版本的编号形式是怎样的？,创造 Python 的最初理由是什么？,一般信息
@anchor{faq/general what-is-python-good-for}@anchor{448a}
@subsubsection Python 适合做什么？


Python 是一种高层级的多用途编程语言，可用于解决许多不同门类的问题。

该语言附带一个庞大的标准库，涵盖了字符串处理（正则表达式，Unicode，比较文件间的差异等），因特网协议（HTTP，FTP，SMTP，XML-RPC，POP，IMAP，CGI 编程等），软件工程（单元测试，日志记录，性能分析，Python 代码解析等），以及操作系统接口（系统调用，文件系统，TCP/IP 套接字等）。 请查看 @ref{135f,,Python 标准库} 的目录以了解所有可用的内容。 此外还可以获取到各种各样的第三方扩展。 请访问 Python 包索引@footnote{https://pypi.org} 来查找你感兴趣的软件包。

@node Python 版本的编号形式是怎样的？,我应如何获取一份 Python 源代码的副本？,Python 适合做什么？,一般信息
@anchor{faq/general how-does-the-python-version-numbering-scheme-work}@anchor{448b}
@subsubsection Python 版本的编号形式是怎样的？


Python 版本的编号形式是 A.B.C 或 A.B。 A 称为大版本号 —— 它仅在对语言特性进行非常重大改变时才会递增。 B 称为小版本号，它会在语言特性发生较小改变时递增。 C 称为微版本号 —— 它会在每次发布问题修正时递增。 请参阅 
@geindex Python 提高建议; PEP 6
PEP 6@footnote{https://www.python.org/dev/peps/pep-0006} 了解有关问题修正发布版的详情。

发布版本并非都是问题修正版本。 在新的主要发布版本开发过程中，还会发布一系列的开发版，它们以 alpha (a), beta (b) 或 release candidate (rc) 来标示。 其中 alpha 版是早期发布的测试版，它的接口并未最终确定；在两个 alpha 发布版本间出现接口的改变并不意外。 而 beta 版更为稳定，它会保留现有的接口，但也可能增加新的模块，release candidate 版则会保持冻结状态不会再进行改变，除非有重大问题需要修正。

以上 alpha, beta 和 release candidate 版本会附加一个后缀。 用于 alpha 版本的后缀是带有一个小数字 N 的“aN”，beta 版本的后缀是带有一个小数字 N 的“bN”，而 release candidate 版本的后缀是带有一个小数字 N 的“rcN”。 换句话说，所有标记为 2.0aN 的版本都早于标记为 2.0bN 的版本，后者又都早于标记为 2.0rcN 的版本，而 @emph{它们} 全都早于 2.0。

你还可能看到带有“+”后缀的版本号，例如“2.2+”。 这表示未发布版本，直接基于 CPython 开发代码仓库构建。 在实际操作中，当一个小版本最终发布后，未发布版本号会递增到下一个小版本号，成为“a0”版本，例如“2.4a0”。

另请参阅 @ref{6d4,,sys.version}, @ref{36be,,sys.hexversion} 以及 @ref{bf6,,sys.version_info} 的文档。

@node 我应如何获取一份 Python 源代码的副本？,我应如何获取 Python 的文档？,Python 版本的编号形式是怎样的？,一般信息
@anchor{faq/general how-do-i-obtain-a-copy-of-the-python-source}@anchor{448c}
@subsubsection 我应如何获取一份 Python 源代码的副本？


最新的 Python 发布版源代码总能从 python.org 获取，下载页链接为 @indicateurl{https://www.python.org/downloads/}。 最新的开发版源代码可以在 @indicateurl{https://github.com/python/cpython/} 获取。

发布版源代码是一个以 gzip 压缩的 tar 文件，其中包含完整的 C 源代码、Sphinx 格式的文档、Python 库模块、示例程序以及一些有用的自由分发软件。 该源代码将可在大多数 UNIX 类平台上直接编译并运行。

请参阅 Python 开发者指南的初步上手部分@footnote{https://devguide.python.org/setup/} 了解有关获取源代码并进行编译的更多信息。

@node 我应如何获取 Python 的文档？,我之前从未接触过编程。 哪里有 Python 的教程？,我应如何获取一份 Python 源代码的副本？,一般信息
@anchor{faq/general how-do-i-get-documentation-on-python}@anchor{448d}
@subsubsection 我应如何获取 Python 的文档？


@c XXX mention py3k

当前的 Python 稳定版本的标准文档可在 @indicateurl{https://docs.python.org/3/} 查看。 也可在 @indicateurl{https://docs.python.org/3/download.html} 获取PDF、纯文本以及可下载的 HTML 版本。

文档以 reStructuredText 格式撰写，并使用 Sphinx 文档工具@footnote{http://sphinx-doc.org/} 生成。 文档的 reStructuredText 源文件是 Python 源代码发布版的一部分。

@node 我之前从未接触过编程。 哪里有 Python 的教程？,是否有专门针对 Python 的新闻组或邮件列表？,我应如何获取 Python 的文档？,一般信息
@anchor{faq/general i-ve-never-programmed-before-is-there-a-python-tutorial}@anchor{448e}
@subsubsection 我之前从未接触过编程。 哪里有 Python 的教程？


有许多可选择的教程和书籍。 标准文档中也包含有 @ref{135e,,Python 教程}。

请参阅 新手指南@footnote{https://wiki.python.org/moin/BeginnersGuide} 以获取针对 Python 编程初学者的信息，包括教程的清单。

@node 是否有专门针对 Python 的新闻组或邮件列表？,我应如何获取 Python 的公开测试版本？,我之前从未接触过编程。 哪里有 Python 的教程？,一般信息
@anchor{faq/general is-there-a-newsgroup-or-mailing-list-devoted-to-python}@anchor{448f}
@subsubsection 是否有专门针对 Python 的新闻组或邮件列表？


有一个新闻组 @code{comp.lang.python} 和一个邮件列表 python-list@footnote{https://mail.python.org/mailman/listinfo/python-list}。 新闻组和邮件列表是彼此互通的 —— 如果你可以阅读新闻就不必再订阅邮件列表。 @code{comp.lang.python} 的流量很大，每天会收到数以百计的发帖，Usenet 使用者通常更擅长处理这样大的流量。

有关新软件发布和活动的公告可以在 comp.lang.python.announce 中找到，这是个严格管理的低流量列表，每天会收到五个左右的发帖。 可以在 Python 公告邮件列表@footnote{https://mail.python.org/mailman/listinfo/python-announce-list} 页面进行订阅。

有关其他邮件列表和新闻组的更多信息可以在 @indicateurl{https://www.python.org/community/lists/} 找到。

@node 我应如何获取 Python 的公开测试版本？,我应如何为 Python 提交错误报告和补丁？,是否有专门针对 Python 的新闻组或邮件列表？,一般信息
@anchor{faq/general how-do-i-get-a-beta-test-version-of-python}@anchor{4490}
@subsubsection 我应如何获取 Python 的公开测试版本？


可以从 @indicateurl{https://www.python.org/downloads/} 下载 alpha 和 beta 发布版。 所有发布版都会在 comp.lang.python 和 comp.lang.python.announce 新闻组以及 Python 主页 @indicateurl{https://www.python.org/} 上进行公告；并会推送到 RSS 新闻源。

你还可以通过 Git 访问 Python 的开发版。 请参阅 Python 开发者指南@footnote{https://devguide.python.org/} 了解详情。

@node 我应如何为 Python 提交错误报告和补丁？,是否有任何公开发表的 Python 相关文章可以供我参考引用？,我应如何获取 Python 的公开测试版本？,一般信息
@anchor{faq/general how-do-i-submit-bug-reports-and-patches-for-python}@anchor{4491}
@subsubsection 我应如何为 Python 提交错误报告和补丁？


要报告错误或提交补丁，请使用安装于 @indicateurl{https://bugs.python.org/} 上的 Roundup。

你必须拥有一个 Roundup 账号才能报告错误；这样我们就可以在有后续问题时与你联系。 这也使得 Roundup 能在我们处理所报告的错误时向你发送更新消息。 如果你之前使用过 SourceForge 向 Python 报告错误，你可以通过 Roundup 的 密码重置操作@footnote{https://bugs.python.org/user?@@template=forgotten} 来获取你的 Roundup 密码。

有关 Python 开发流程的更多信息，请参阅 Python 开发者指南@footnote{https://devguide.python.org/}。

@node 是否有任何公开发表的 Python 相关文章可以供我参考引用？,是否有任何 Python 相关的书籍？,我应如何为 Python 提交错误报告和补丁？,一般信息
@anchor{faq/general are-there-any-published-articles-about-python-that-i-can-reference}@anchor{4492}
@subsubsection 是否有任何公开发表的 Python 相关文章可以供我参考引用？


可能作为参考文献的最好方式还是引用你喜欢的 Python 相关书籍。

第一篇有关 Python 的文章写于 1991 年，现在其内容已经相当过时了。

@quotation

Guido van Rossum 与 Jelke de Boer, "使用 Python 编程语言交互式地测试远程服务器", CWI 季刊, 第 4 卷, 第 4 期 (1991 年 12 月), 阿姆斯特丹, 第 283--303 页。
@end quotation

@node 是否有任何 Python 相关的书籍？,www python org 具体位于世界上的哪个地点？,是否有任何公开发表的 Python 相关文章可以供我参考引用？,一般信息
@anchor{faq/general are-there-any-books-on-python}@anchor{4493}
@subsubsection 是否有任何 Python 相关的书籍？


是的，相关的书籍很多，还有更多即将发行。 请访问 python.org 的 wiki 页面 @indicateurl{https://wiki.python.org/moin/PythonBooks} 获取一份清单。

你也可以到各大在线书店搜索 "Python" 并过滤掉对 Monty Python 的引用；或者也可以搜索 "Python" 加 "language"。

@node www python org 具体位于世界上的哪个地点？,为何命名为 Python？,是否有任何 Python 相关的书籍？,一般信息
@anchor{faq/general where-in-the-world-is-www-python-org-located}@anchor{4494}
@subsubsection www.python.org 具体位于世界上的哪个地点？


Python 项目的基础架构分布于世界各地并由 Python 基础架构团队负责管理。 详情请访问 这里@footnote{http://infra.psf.io}。

@node 为何命名为 Python？,我必须喜欢 "Monty Python 的飞行马戏团" 吗？,www python org 具体位于世界上的哪个地点？,一般信息
@anchor{faq/general why-is-it-called-python}@anchor{4495}
@subsubsection 为何命名为 Python？


在着手编写 Python 实现的时候，Guido van Rossum 同时还阅读了刚出版的 "Monty Python 的飞行马戏团"@footnote{https://en.wikipedia.org/wiki/Monty_Python} 剧本，这是一部自 1970 年代开始播出的 BBC 系列喜剧。 Van Rossum 觉得他需要选择一个简短、独特而又略显神秘的名字，于是他决定将这个新语言命名为 Python。

@node 我必须喜欢 "Monty Python 的飞行马戏团" 吗？,,为何命名为 Python？,一般信息
@anchor{faq/general do-i-have-to-like-monty-python-s-flying-circus}@anchor{4496}
@subsubsection 我必须喜欢 "Monty Python 的飞行马戏团" 吗？


不必，但这对学习会有帮助。 :)

@node 现实世界中的 Python,,一般信息,Python常见问题
@anchor{faq/general python-in-the-real-world}@anchor{4497}
@subsection 现实世界中的 Python


@menu
* Python 有多稳定？:: 
* 有多少人在使用 Python？:: 
* 有哪些重要的项目是用 Python 开发的？:: 
* 在未来可以期待 Python 将有什么新进展？:: 
* 提议对 Python 加入不兼容的更改是否合理？:: 
* Python 是一种对编程初学者友好的语言吗？:: 

@end menu

@node Python 有多稳定？,有多少人在使用 Python？,,现实世界中的 Python
@anchor{faq/general how-stable-is-python}@anchor{4498}
@subsubsection Python 有多稳定？


非常稳定。 自 1991 年起大约每隔 6 到 18 个月就会推出新的稳定发布版，这种状态看来还还持续。 从 3.9 版开始，Python 将会每隔 12 个月推出一个新的主要发布版 (
@geindex Python 提高建议; PEP 602
PEP 602@footnote{https://www.python.org/dev/peps/pep-0602})。

开发者也会推出旧版本的“问题修正”发布版，因此现有发布版的稳定性还会逐步提升。 问题修正发布版会以版本号第三部分的数字来标示（例如 3.5.3, 3.6.2），用于稳定性的管理；只有对已知问题的修正会包含在问题修正发布版中，同一系列的问题修正发布版中的接口确定将会始终保持一致。

最后的稳定版本总是可以在 Python 下载页@footnote{https://www.python.org/downloads/} 中找到。 有两个生产环境可用的 Python　版本：2.x 和 3.x。 推荐的版本是 3.x，大多数被广泛使用的库都支持它。 虽然 2.x 也仍然被广泛使用，但是 它已经停止维护@footnote{https://www.python.org/dev/peps/pep-0373/}。

@node 有多少人在使用 Python？,有哪些重要的项目是用 Python 开发的？,Python 有多稳定？,现实世界中的 Python
@anchor{faq/general how-many-people-are-using-python}@anchor{4499}
@subsubsection 有多少人在使用 Python？


使用者应该数以百万计，但很难获得一个精确的数字。

Python 可以免费下载，因此并不存在销量数据，此外它也可以从许多不同网站获取，并且包含于许多 Linux 发行版之中，因此下载量统计同样无法完全说明问题。

comp.lang.python 新闻组非常活跃，但不是所有 Python 用户都会在新闻组发帖，许多人甚至不会阅读新闻组。

@node 有哪些重要的项目是用 Python 开发的？,在未来可以期待 Python 将有什么新进展？,有多少人在使用 Python？,现实世界中的 Python
@anchor{faq/general have-any-significant-projects-been-done-in-python}@anchor{449a}
@subsubsection 有哪些重要的项目是用 Python 开发的？


请访问 @indicateurl{https://www.python.org/about/success} 查看使用了 Python 的项目列表。 阅览 历次 Python 会议@footnote{https://www.python.org/community/workshops/} 的日程纪要可以看到许多不同公司和组织所做的贡献。

高水准的 Python 项目包括 Mailman 邮件列表管理器@footnote{http://www.list.org} 和 Zope 应用服务器@footnote{http://www.zope.org}。 多个 Linux 发行版，其中最著名的有 Red Hat@footnote{https://www.redhat.com} 均已使用 Python 来编写部分或全部的安装程序和系统管理软件。 在内部使用 Python 的大公司包括了 Google, Yahoo 以及 Lucasfilm 等。

@node 在未来可以期待 Python 将有什么新进展？,提议对 Python 加入不兼容的更改是否合理？,有哪些重要的项目是用 Python 开发的？,现实世界中的 Python
@anchor{faq/general what-new-developments-are-expected-for-python-in-the-future}@anchor{449b}
@subsubsection 在未来可以期待 Python 将有什么新进展？


请访问 @indicateurl{https://www.python.org/dev/peps/} 查看 Python 增强提议（PEP）。 PEP  是为 Python 加入某种新特性的提议进行描述的设计文档，其中会提供简明的技术规格说明与基本原理。 可以查找标题为“Python X.Y Release Schedule”的 PEP，其中 X.Y 是某个尚未公开发布的版本。

新版本的开发会在 python-dev 邮件列表@footnote{https://mail.python.org/mailman/listinfo/python-dev/} 中进行讨论。

@node 提议对 Python 加入不兼容的更改是否合理？,Python 是一种对编程初学者友好的语言吗？,在未来可以期待 Python 将有什么新进展？,现实世界中的 Python
@anchor{faq/general is-it-reasonable-to-propose-incompatible-changes-to-python}@anchor{449c}
@subsubsection 提议对 Python 加入不兼容的更改是否合理？


通常来说是不合理的。 世界上已存在的 Python 代码数以亿计，因此，任何对该语言的更改即便仅会使得现有程序中极少的一部分失效也是难以令人接受的。 就算你可以提供一个转换程序，也仍然存在需要更新全部文档的问题；另外还有大量已出版的 Python 书籍，我们不希望让它们在一瞬间全部变成废纸。

如果必须更改某个特性，则应该提供渐进式的升级路径。 
@geindex Python 提高建议; PEP 5
PEP 5@footnote{https://www.python.org/dev/peps/pep-0005} 描述了引入向后不兼容的更改所需遵循的流程，以尽可能减少对用户的干扰。

@node Python 是一种对编程初学者友好的语言吗？,,提议对 Python 加入不兼容的更改是否合理？,现实世界中的 Python
@anchor{faq/general is-python-a-good-language-for-beginning-programmers}@anchor{449d}
@subsubsection Python 是一种对编程初学者友好的语言吗？


是的。

从过程式、静态类型的编程语言例如 Pascal, C 或者 C++ 以及 Java 的某一子集开始引导学生入门仍然是常见的做法。 但以  Python 作为第一种编程语言进行学习对学生可能更有利。Python 具有非常简单和一致的语法和庞大的标准库，而且最重要的是，在编程入门教学中使用 Python 可以让学生专注于更重要的编程技能，例如问题分解与数据类型设计。 使用 Python，可以快速向学生介绍基本概念例如循环与过程等。 他们甚至有可能在第一次课里就开始接触用户自定义对象。

对于之前从未接触过编程的学生来说，使用静态类型语言会感觉不够自然。 这会给学生带来必须掌握的额外复杂性，并减慢教学的进度。 学生需要尝试像计算机一样思考，分解问题，设计一致的接口并封装数据。 虽然从长远来看，学习和使用一种静态类型语言是很重要的，但这并不是最适宜在学生的第一次编程课上就进行探讨的主题。

还有许多其他方面的特点使得 Python 成为很好的入门语言。 像 Java 一样，Python 拥有一个庞大的标准库，因此可以在课程非常早期的阶段就给学生布置一些 @emph{实用} 的编程项目。 编程作业不必仅限于标准四则运算和账目检查程序。 通过使用标准库，学生可以在学习编程基础知识的同时开发真正的应用，从而获得更大的满足感。 使用标准库还能使学生了解代码重用的概念。 而像 PyGame 这样的第三方模块同样有助于扩大学生的接触领域。

Python 的解释器使学生能够在编程时测试语言特性。 他们可以在一个窗口中输入程序源代码的同时开启一个解释器运行窗口。 如果他们不记得列表有哪些方法，他们这以这样做:

@example
>>> L = []
>>> dir(L) 
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> [d for d in dir(L) if '__' not in d]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> help(L.append)
Help on built-in function append:

append(...)
    L.append(object) -> None -- append object to end

>>> L.append(1)
>>> L
[1]
@end example

通过使用解释器，学生编写程序时参考文档总是能伴随在他们身边。

Python 还拥有很好的 IDE。 IDLE 是一个跨平台的 Python IDE，它基于 Tkinter 库，使用 Python 语言编写。  PythonWin 是一个 Windows 专属的 IDE。 Emacs 用户将高兴地了解到 Emacs 具有非常好的 Python 模式。  所有这些编程环境都提供语法高亮，自动缩进以及在编写代码时使用交互式解释器等功能。 请访问 Python wiki@footnote{https://wiki.python.org/moin/PythonEditors} 查看 Python 编程环境的完整列表。

如果你想要讨论 Python 在教育中的使用，你可能会有兴趣加入 edu-sig 邮件列表@footnote{https://www.python.org/community/sigs/current/edu-sig}。

@node 编程常见问题,设计和历史常见问题,Python常见问题,Python 常见问题
@anchor{faq/programming doc}@anchor{449e}@anchor{faq/programming programming-faq}@anchor{449f}
@section 编程常见问题



@menu
* 一般问题:: 
* 语言核心内容:: 
* 数字和字符串:: 
* 性能: 性能<4>. 
* 序列（元组/列表）:: 
* 对象:: 
* 模块: 模块<3>. 

@end menu

@node 一般问题,语言核心内容,,编程常见问题
@anchor{faq/programming general-questions}@anchor{44a0}
@subsection 一般问题


@menu
* Python 有没有提供带有断点、单步调试等功能的源码级调试器？:: 
* 是否有能帮助寻找漏洞或执行静态分析的工具？:: 
* 如何由 Python 脚本创建能独立运行的二进制程序？:: 
* 是否有 Python 编码标准或风格指南？:: 

@end menu

@node Python 有没有提供带有断点、单步调试等功能的源码级调试器？,是否有能帮助寻找漏洞或执行静态分析的工具？,,一般问题
@anchor{faq/programming is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc}@anchor{44a1}
@subsubsection Python 有没有提供带有断点、单步调试等功能的源码级调试器？


有的。

以下介绍了一些 Python 的调试器，用内置函数 @ref{414,,breakpoint()} 即可切入这些调试器中。

pdb 模块是一个简单但是够用的控制台模式 Python 调试器。 它是标准 Python 库的一部分，并且 @ref{c9,,已收录于库参考手册}。 你也可以通过使用 pdb 代码作为样例来编写你自己的调试器。

作为标准 Python 发行版附带组件的 IDLE 交互式环境（通常位于 Tools/scripts/idle）中包含一个图形化的调试器。

PythonWin 是一种 Python IDE，其中包含了一个基于 pdb 的 GUI 调试器。PythonWin 的调试器会为断点着色，并提供了相当多的超酷特性，例如调试非 PythonWin 程序等。PythonWin 是 pywin32@footnote{https://github.com/mhammond/pywin32} 项目的组成部分，也是 ActivePython@footnote{https://www.activestate.com/products/python/} 发行版的组成部分。

Eric@footnote{http://eric-ide.python-projects.org/} 是一个基于PyQt和Scintilla编辑组件构建的IDE。

trepan3k@footnote{https://github.com/rocky/python3-trepan/} 是一个类似 gdb 的调试器。

Visual Studio Code@footnote{https://code.visualstudio.com/} 是包含了调试工具的 IDE，并集成了版本控制软件。

有许多商业 Python IDE 都包含了图形化调试器。包括：


@itemize *

@item 
Wing IDE@footnote{https://wingware.com/}

@item 
Komodo IDE@footnote{https://www.activestate.com/products/komodo-ide/}

@item 
PyCharm@footnote{https://www.jetbrains.com/pycharm/}
@end itemize

@node 是否有能帮助寻找漏洞或执行静态分析的工具？,如何由 Python 脚本创建能独立运行的二进制程序？,Python 有没有提供带有断点、单步调试等功能的源码级调试器？,一般问题
@anchor{faq/programming are-there-tools-to-help-find-bugs-or-perform-static-analysis}@anchor{44a2}
@subsubsection 是否有能帮助寻找漏洞或执行静态分析的工具？


有的。

Pylint@footnote{https://www.pylint.org/} 和 Pyflakes@footnote{https://github.com/PyCQA/pyflakes} 可进行基本检查来帮助你尽早捕捉漏洞。

静态类型检查器，例如 Mypy@footnote{http://mypy-lang.org/} 、 Pyre@footnote{https://pyre-check.org/} 和 Pytype@footnote{https://github.com/google/pytype} 可以检查Python源代码中的类型提示。

@node 如何由 Python 脚本创建能独立运行的二进制程序？,是否有 Python 编码标准或风格指南？,是否有能帮助寻找漏洞或执行静态分析的工具？,一般问题
@anchor{faq/programming faq-create-standalone-binary}@anchor{44a3}@anchor{faq/programming how-can-i-create-a-stand-alone-binary-from-a-python-script}@anchor{44a4}
@subsubsection 如何由 Python 脚本创建能独立运行的二进制程序？


如果只是想要一个独立的程序，以便用户不必预先安装 Python 即可下载和运行它，则不需要将 Python 编译成 C 代码。有许多工具可以检测程序所需的模块，并将这些模块与 Python 二进制程序捆绑在一起生成单个可执行文件。

一种方案是使用 freeze 工具，它以 @code{Tools/freeze} 的形式包含在 Python 源代码树中。它将 Python 的字节码转换为 C 语言的数组；用 C 语言编译器可以将你的所有模块嵌入到一个新的程序中，然后与标准的 Python 模块连接。

它的工作原理是递归扫描源代码，获取两种格式的 import 语句，并在标准 Python 路径和源码目录（用于内置模块）检索这些模块。然后，把这些模块的 Python 字节码转换为 C 代码（可以利用 marshal 模块转换为代码对象的数组初始化器），并创建一个定制的配置文件，该文件仅包含程序实际用到的内置模块。然后，编译生成的 C 代码并将其与 Python 解释器的其余部分链接，形成一个自给自足的二进制文件，其功能与 Python 脚本代码完全相同。

下列包可以用于帮助创建控制台和 GUI 的可执行文件:


@itemize *

@item 
Nuitka@footnote{https://nuitka.net/} （跨平台）

@item 
PyInstaller@footnote{http://www.pyinstaller.org/}  （跨平台）

@item 
PyOxidizer@footnote{https://pyoxidizer.readthedocs.io/en/stable/} （跨平台）

@item 
cx_Freeze@footnote{https://marcelotduarte.github.io/cx_Freeze/} （跨平台）

@item 
py2app@footnote{https://github.com/ronaldoussoren/py2app} （仅限 macOS）

@item 
py2exe@footnote{http://www.py2exe.org/} （仅限 Windows）
@end itemize

@node 是否有 Python 编码标准或风格指南？,,如何由 Python 脚本创建能独立运行的二进制程序？,一般问题
@anchor{faq/programming are-there-coding-standards-or-a-style-guide-for-python-programs}@anchor{44a5}
@subsubsection 是否有 Python 编码标准或风格指南？


有的。 标准库模块所要求的编码风格记录于 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 之中。

@node 语言核心内容,数字和字符串,一般问题,编程常见问题
@anchor{faq/programming core-language}@anchor{44a6}
@subsection 语言核心内容


@menu
* 变量明明有值，为什么还会出现 UnboundLocalError？:: 
* Python 的局部变量和全局变量有哪些规则？:: 
* 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？:: 
* 如何跨模块共享全局变量？:: 
* 导入模块的“最佳实践”是什么？:: 
* 为什么对象之间会共享默认值？:: 
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？:: 
* 形参和实参之间有什么区别？:: 
* 为什么修改列表 'y' 也会更改列表 'x'？:: 
* 如何编写带有输出参数的函数（按照引用调用）？:: 
* 如何在 Python 中创建高阶函数？:: 
* 如何复制 Python 对象？:: 
* 如何找到对象的方法或属性？:: 
* 如何用代码获取对象的名称？:: 
* 逗号运算符的优先级是什么？:: 
* 是否提供等价于 C 语言 "?;" 三目运算符的东西？: 是否提供等价于 C 语言 "? " 三目运算符的东西？. 
* 是否可以用 Python 编写让人眼晕的单行程序?:: 
* 函数形参列表中的斜杠（/）是什么意思？:: 

@end menu

@node 变量明明有值，为什么还会出现 UnboundLocalError？,Python 的局部变量和全局变量有哪些规则？,,语言核心内容
@anchor{faq/programming why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value}@anchor{44a7}
@subsubsection 变量明明有值，为什么还会出现 UnboundLocalError？


因为在函数内部某处添加了一条赋值语句，导致之前正常工作的代码报出 UnboundLocalError 错误，这可能是有点令人惊讶。

以下代码：

@example
>>> x = 10
>>> def bar():
...     print(x)
>>> bar()
10
@end example

正常工作，但是以下代码

@example
>>> x = 10
>>> def foo():
...     print(x)
...     x += 1
@end example

会得到一个 UnboundLocalError ：

@example
>>> foo()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment
@end example

原因就是，当对某作用域内的变量进行赋值时，该变量将成为该作用域内的局部变量，并覆盖外部作用域中的同名变量。由于 foo 的最后一条语句为 @code{x} 分配了一个新值，编译器会将其识别为局部变量。因此，前面的 @code{print(x)} 试图输出未初始化的局部变量，就会引发错误。

在上面的示例中，可以将外部作用域的变量声明为全局变量以便访问：

@example
>>> x = 10
>>> def foobar():
...     global x
...     print(x)
...     x += 1
>>> foobar()
10
@end example

与类和实例变量貌似但不一样，其实以上是在修改外部作用域的变量值，为了提示这一点，这里需要显式声明一下。

@example
>>> print(x)
11
@end example

你可以使用 @ref{d0f,,nonlocal} 关键字在嵌套作用域中执行类似的操作：

@example
>>> def foo():
...    x = 10
...    def bar():
...        nonlocal x
...        print(x)
...        x += 1
...    bar()
...    print(x)
>>> foo()
10
11
@end example

@node Python 的局部变量和全局变量有哪些规则？,为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,变量明明有值，为什么还会出现 UnboundLocalError？,语言核心内容
@anchor{faq/programming what-are-the-rules-for-local-and-global-variables-in-python}@anchor{44a8}
@subsubsection Python 的局部变量和全局变量有哪些规则？


函数内部只作引用的 Python 变量隐式视为全局变量。如果在函数内部任何位置为变量赋值，则除非明确声明为全局变量，否则均将其视为局部变量。

起初尽管有点令人惊讶，不过考虑片刻即可释然。一方面，已分配的变量要求加上 @ref{13a7,,global} 可以防止意外的副作用发生。另一方面，如果所有全局引用都要加上 @code{global} ，那处处都得用上 @code{global} 了。那么每次对内置函数或导入模块中的组件进行引用时，都得声明为全局变量。这种杂乱会破坏 @code{global} 声明用于警示副作用的有效性。

@node 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,如何跨模块共享全局变量？,Python 的局部变量和全局变量有哪些规则？,语言核心内容
@anchor{faq/programming why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result}@anchor{44a9}
@subsubsection 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？


假设用 for 循环来定义几个取值各异的 lambda（即便是普通函数也一样）：

@example
>>> squares = []
>>> for x in range(5):
...     squares.append(lambda: x**2)
@end example

以上会得到一个包含5个 lambda 函数的列表，这些函数将计算 @code{x**2}。大家或许期望，调用这些函数会分别返回 @code{0} 、@code{1} 、 @code{4} 、 @code{9} 和 @code{16}。然而，真的试过就会发现，他们都会返回 @code{16} ：

@example
>>> squares[2]()
16
>>> squares[4]()
16
@end example

这是因为 @code{x} 不是 lambda 函数的内部变量，而是定义于外部作用域中的，并且 @code{x} 是在调用 lambda 时访问的——而不是在定义时访问。循环结束时 @code{x} 的值是 @code{4} ，所以此时所有的函数都将返回 @code{4**2} ，即 @code{16} 。通过改变 @code{x} 的值并查看 lambda 的结果变化，也可以验证这一点。

@example
>>> x = 8
>>> squares[2]()
64
@end example

为了避免发生上述情况，需要将值保存在 lambda 局部变量，以使其不依赖于全局 @code{x} 的值：

@example
>>> squares = []
>>> for x in range(5):
...     squares.append(lambda n=x: n**2)
@end example

以上 @code{n=x} 创建了一个新的 lambda 本地变量 @code{n}，并在定义 lambda 时计算其值，使其与循环当前时点的 @code{x} 值相同。这意味着 @code{n} 的值在第 1 个 lambda 中为 @code{0} ，在第 2 个 lambda 中为 @code{1} ，在第 3 个中为 @code{2}，依此类推。因此现在每个 lambda 都会返回正确结果：

@example
>>> squares[2]()
4
>>> squares[4]()
16
@end example

请注意，上述表现并不是 lambda 所特有的，常规的函数也同样适用。

@node 如何跨模块共享全局变量？,导入模块的“最佳实践”是什么？,为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,语言核心内容
@anchor{faq/programming how-do-i-share-global-variables-across-modules}@anchor{44aa}
@subsubsection 如何跨模块共享全局变量？


在单个程序中跨模块共享信息的规范方法是创建一个特殊模块（通常称为 config 或 cfg）。只需在应用程序的所有模块中导入该 config 模块；然后该模块就可当作全局名称使用了。因为每个模块只有一个实例，所以对该模块对象所做的任何更改将会在所有地方得以体现。 例如：

config.py：

@example
x = 0   # Default value of the 'x' configuration setting
@end example

mod.py：

@example
import config
config.x = 1
@end example

main.py：

@example
import config
import mod
print(config.x)
@end example

请注意，出于同样的原因，采用模块也是实现单例设计模式的基础。

@node 导入模块的“最佳实践”是什么？,为什么对象之间会共享默认值？,如何跨模块共享全局变量？,语言核心内容
@anchor{faq/programming what-are-the-best-practices-for-using-import-in-a-module}@anchor{44ab}
@subsubsection 导入模块的“最佳实践”是什么？


通常请勿使用 @code{from modulename import *} 。因为这会扰乱 importer 的命名空间，且会造成未定义名称更难以被 Linter 检查出来。

请在代码文件的首部就导入模块。这样代码所需的模块就一目了然了，也不用考虑模块名是否在作用域内的问题。每行导入一个模块则增删起来会比较容易，每行导入多个模块则更节省屏幕空间。

按如下顺序导入模块就是一种好做法：


@enumerate 

@item 
标准库模块——比如： @code{sys} 、 @code{os} 、 @code{getopt} 、 @code{re} 等。

@item 
第三方库模块（安装于 Python site-packages 目录中的内容）——如 mx.DateTime、ZODB、PIL.Image 等。

@item 
本地开发的模块
@end enumerate

为了避免循环导入引发的问题，有时需要将模块导入语句移入函数或类的内部。Gordon McMillan 的说法如下：

@quotation

当两个模块都采用  "import <module>" 的导入形式时，循环导入是没有问题的。但如果第 2 个模块想从第 1 个模块中取出一个名称（"from module import name"）并且导入处于代码的最顶层，那导入就会失败。原因是第 1 个模块中的名称还不可用，这时第 1 个模块正忙于导入第 2 个模块呢。
@end quotation

如果只是在一个函数中用到第 2 个模块，那这时将导入语句移入该函数内部即可。当调用到导入语句时，第 1 个模块将已经完成初始化，第 2 个模块就可以进行导入了。

如果某些模块是平台相关的，可能还需要把导入语句移出最顶级代码。这种情况下，甚至有可能无法导入文件首部的所有模块。于是在对应的平台相关代码中导入正确的模块，就是一种不错的选择。

只有为了避免循环导入问题，或有必要减少模块初始化时间时，才把导入语句移入类似函数定义内部的局部作用域。如果根据程序的执行方式，许多导入操作不是必需的，那么这种技术尤其有用。如果模块仅在某个函数中用到，可能还要将导入操作移入该函数内部。请注意，因为模块有一次初始化过程，所以第一次加载模块的代价可能会比较高，但多次加载几乎没有什么花费，代价只是进行几次字典检索而已。即使模块名超出了作用域，模块在 @ref{109a,,sys.modules} 中也是可用的。

@node 为什么对象之间会共享默认值？,如何将可选参数或关键字参数从一个函数传递到另一个函数？,导入模块的“最佳实践”是什么？,语言核心内容
@anchor{faq/programming why-are-default-values-shared-between-objects}@anchor{44ac}
@subsubsection 为什么对象之间会共享默认值？


新手程序员常常中招这类 Bug。请看以下函数：

@example
def foo(mydict=@{@}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict
@end example

第一次调用此函数时， @code{mydict}  中只有一个数据项。第二次调用 @code{mydict} 则会包含两个数据项，因为 @code{foo()} 开始执行时， @code{mydict} 中已经带有一个数据项了。

大家往往希望，函数调用会为默认值创建新的对象。但事实并非如此。默认值只会在函数定义时创建一次。如果对象发生改变，就如上例中的字典那样，则后续调用该函数时将会引用这个改动的对象。

按照定义，不可变对象改动起来是安全的，诸如数字、字符串、元组和 @code{None} 之类。而可变对象的改动则可能引起困惑，例如字典、列表和类实例等。

因此，不把可变对象用作默认值是一种良好的编程做法。而应采用 @code{None} 作为默认值，然后在函数中检查参数是否为 @code{None} 并新建列表、字典或其他对象。例如，代码不应如下所示：

@example
def foo(mydict=@{@}):
    ...
@end example

而应这么写：

@example
def foo(mydict=None):
    if mydict is None:
        mydict = @{@}  # create a new dict for local namespace
@end example

参数默认值的特性有时会很有用处。 如果有个函数的计算过程会比较耗时，有一种常见技巧是将每次函数调用的参数和结果缓存起来，并在同样的值被再次请求时返回缓存的值。这种技巧被称为“memoize”，实现代码可如下所示：

@example
# Callers can only provide two parameters and optionally pass _cache by keyword
def expensive(arg1, arg2, *, _cache=@{@}):
    if (arg1, arg2) in _cache:
        return _cache[(arg1, arg2)]

    # Calculate the value
    result = ... expensive computation ...
    _cache[(arg1, arg2)] = result           # Store result in the cache
    return result
@end example

也可以不用参数默认值来实现，而是采用全局的字典变量；这取决于个人偏好。

@node 如何将可选参数或关键字参数从一个函数传递到另一个函数？,形参和实参之间有什么区别？,为什么对象之间会共享默认值？,语言核心内容
@anchor{faq/programming how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another}@anchor{44ad}
@subsubsection 如何将可选参数或关键字参数从一个函数传递到另一个函数？


请利用函数参数列表中的标识符 @code{*} 和 @code{**} 归集实参；结果会是元组形式的位置实参和字典形式的关键字实参。然后就可利用 @code{*} 和 @code{**} 在调用其他函数时传入这些实参：

@example
def f(x, *args, **kwargs):
    ...
    kwargs['width'] = '14.3c'
    ...
    g(x, *args, **kwargs)
@end example

@geindex argument; difference from parameter
@geindex parameter; difference from argument

@node 形参和实参之间有什么区别？,为什么修改列表 'y' 也会更改列表 'x'？,如何将可选参数或关键字参数从一个函数传递到另一个函数？,语言核心内容
@anchor{faq/programming faq-argument-vs-parameter}@anchor{44ae}@anchor{faq/programming what-is-the-difference-between-arguments-and-parameters}@anchor{44af}
@subsubsection 形参和实参之间有什么区别？


@ref{1693,,形参} 是指出现在函数定义中的名称，而 @ref{168a,,实参} 则是在调用函数时实际传入的值。 形参定义了一个函数能接受何种类型的实参。 例如，对于以下函数定义:

@example
def func(foo, bar=None, **kwargs):
    pass
@end example

@emph{foo} 、 @emph{bar} 和 @emph{kwargs} 是 @code{func} 的形参。 不过在调用 @code{func} 时，例如：

@example
func(42, bar=314, extra=somevar)
@end example

@code{42} 、 @code{314} 和 @code{somevar} 则是实参。

@node 为什么修改列表 'y' 也会更改列表 'x'？,如何编写带有输出参数的函数（按照引用调用）？,形参和实参之间有什么区别？,语言核心内容
@anchor{faq/programming why-did-changing-list-y-also-change-list-x}@anchor{44b0}
@subsubsection 为什么修改列表 'y' 也会更改列表 'x'？


如果代码编写如下：

@example
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
@end example

或许大家很想知道，为什么在 y 中添加一个元素时， x 也会改变。

产生这种结果有两个因素：


@enumerate 

@item 
变量只是指向对象的一个名称。执行 @code{y = x} 并不会创建列表的副本——而只是创建了一个新变量 @code{y}，并指向 @code{x} 所指的同一对象。这就意味着只存在一个列表对象，@code{x} 和 @code{y} 都是对它的引用。

@item 
列表属于 @ref{138d,,mutable} 对象，这意味着它的内容是可以修改的。
@end enumerate

在调用 @code{append()} 之后，该可变对象的内容由 @code{[]} 变为 @code{[10]}。由于 x 和 y 这两个变量引用了同一对象，因此用其中任意一个名称所访问到的都是修改后的值 @code{[10]}。

如果把赋给 @code{x} 的对象换成一个不可变对象：

@example
>>> x = 5  # ints are immutable
>>> y = x
>>> x = x + 1  # 5 can't be mutated, we are creating a new object here
>>> x
6
>>> y
5
@end example

可见这时 @code{x} 和 @code{y} 就不再相等了。因为整数是 @ref{1385,,immutable} 对象，在执行 @code{x = x + 1} 时，并不会修改整数对象 @code{5}，给它加上 1；而是创建了一个新的对象（整数对象 @code{6} ）并将其赋给 @code{x} （也就是改变了 @code{x} 所指向的对象）。在赋值完成后，就有了两个对象（整数对象 @code{6} 和 @code{5} ）和分别指向他俩的两个变量（ @code{x} 现在指向 @code{6} 而 @code{y} 仍然指向 @code{5} ）。

某些操作（例如 @code{y.append(10)} 和 @code{y.sort()} ）会直接修改原对象，而看上去相似的另一些操作（例如 @code{y = y + [10]} 和 @code{sorted(y)} ）则会创建新的对象。通常在 Python 中（以及所有标准库），直接修改原对象的方法将会返回 @code{None} ，以助避免混淆这两种不同类型的操作。因此如果误用了 @code{y.sort()} 并期望返回 @code{y} 的有序副本，则结果只会是 @code{None} ，这可能就能让程序引发一条容易诊断的错误。

不过还存在一类操作，用不同的类型执行相同的操作有时会发生不同的行为：即增量赋值运算符。例如，@code{+=} 会修改列表，但不会修改元组或整数（@code{a_list += [1, 2, 3]} 与 @code{a_list.extend([1, 2, 3])} 同样都会改变 @code{a_list}，而 @code{some_tuple += (1, 2, 3)} 和 @code{some_int += 1} 则会创建新的对象）。

换而言之：


@itemize *

@item 
对于一个可变对象（ @ref{1f9,,list} 、 @ref{164,,dict} 、 @ref{1f7,,set} 等等），可以利用某些特定的操作进行修改，所有引用它的变量都会反映出改动情况。

@item 
对于一个不可变对象（ @ref{206,,str} 、 @ref{205,,int} 、 @ref{1a2,,tuple} 等），所有引用它的变量都会给出相同的值，但所有改变其值的操作都将返回一个新的对象。
@end itemize

如要知道两个变量是否指向同一个对象，可以利用 @ref{1580,,is} 运算符或内置函数 @ref{e53,,id()}。

@node 如何编写带有输出参数的函数（按照引用调用）？,如何在 Python 中创建高阶函数？,为什么修改列表 'y' 也会更改列表 'x'？,语言核心内容
@anchor{faq/programming how-do-i-write-a-function-with-output-parameters-call-by-reference}@anchor{44b1}
@subsubsection 如何编写带有输出参数的函数（按照引用调用）？


请记住，Python 中的实参是通过赋值传递的。由于赋值只是创建了对象的引用，所以调用方和被调用方的参数名都不存在别名，本质上也就不存在按引用调用的方式。通过以下几种方式，可以得到所需的效果。


@enumerate 

@item 
返回一个元组：

@example
>>> def func1(a, b):
...     a = 'new-value'        # a and b are local names
...     b = b + 1              # assigned to new objects
...     return a, b            # return new values
...
>>> x, y = 'old-value', 99
>>> func1(x, y)
('new-value', 100)
@end example

这差不多是最明晰的解决方案了。

@item 
使用全局变量。这不是线程安全的方案，不推荐使用。

@item 
传递一个可变（即可原地修改的） 对象：

@example
>>> def func2(a):
...     a[0] = 'new-value'     # 'a' references a mutable list
...     a[1] = a[1] + 1        # changes a shared object
...
>>> args = ['old-value', 99]
>>> func2(args)
>>> args
['new-value', 100]
@end example

@item 
传入一个接收可变对象的字典:

@example
>>> def func3(args):
...     args['a'] = 'new-value'     # args is a mutable dictionary
...     args['b'] = args['b'] + 1   # change it in-place
...
>>> args = @{'a': 'old-value', 'b': 99@}
>>> func3(args)
>>> args
@{'a': 'new-value', 'b': 100@}
@end example

@item 
或者把值用类实例封装起来：

@example
>>> class Namespace:
...     def __init__(self, /, **args):
...         for key, value in args.items():
...             setattr(self, key, value)
...
>>> def func4(args):
...     args.a = 'new-value'        # args is a mutable Namespace
...     args.b = args.b + 1         # change object in-place
...
>>> args = Namespace(a='old-value', b=99)
>>> func4(args)
>>> vars(args)
@{'a': 'new-value', 'b': 100@}
@end example

没有什么理由要把问题搞得这么复杂。
@end enumerate

最佳选择就是返回一个包含多个结果值的元组。

@node 如何在 Python 中创建高阶函数？,如何复制 Python 对象？,如何编写带有输出参数的函数（按照引用调用）？,语言核心内容
@anchor{faq/programming how-do-you-make-a-higher-order-function-in-python}@anchor{44b2}
@subsubsection 如何在 Python 中创建高阶函数？


有两种选择：嵌套作用域、可调用对象。假定需要定义 @code{linear(a,b)} ，其返回结果是一个计算出 @code{a*x+b} 的函数 @code{f(x)}。 采用嵌套作用域的方案如下：

@example
def linear(a, b):
    def result(x):
        return a * x + b
    return result
@end example

或者可采用可调用对象：

@example
class linear:

    def __init__(self, a, b):
        self.a, self.b = a, b

    def __call__(self, x):
        return self.a * x + self.b
@end example

采用这两种方案时：

@example
taxes = linear(0.3, 2)
@end example

都会得到一个可调用对象，可实现 @code{taxes(10e6) == 0.3 * 10e6 + 2} 。

可调用对象的方案有个缺点，就是速度稍慢且生成的代码略长。不过值得注意的是，同一组可调用对象能够通过继承来共享签名（类声明）：

@example
class exponential(linear):
    # __init__ inherited
    def __call__(self, x):
        return self.a * (x ** self.b)
@end example

对象可以为多个方法的运行状态进行封装：

@example
class counter:

    value = 0

    def set(self, x):
        self.value = x

    def up(self):
        self.value = self.value + 1

    def down(self):
        self.value = self.value - 1

count = counter()
inc, dec, reset = count.up, count.down, count.set
@end example

以上 @code{inc()} 、 @code{dec()} 和 @code{reset()} 的表现，就如同共享了同一计数变量一样。

@node 如何复制 Python 对象？,如何找到对象的方法或属性？,如何在 Python 中创建高阶函数？,语言核心内容
@anchor{faq/programming how-do-i-copy-an-object-in-python}@anchor{44b3}
@subsubsection 如何复制 Python 对象？


一般情况下，用 @ref{4da,,copy.copy()} 或 @ref{4db,,copy.deepcopy()} 基本就可以了。并不是所有对象都支持复制，但多数是可以的。

某些对象可以用更简便的方法进行复制。比如字典对象就提供了 @ref{551,,copy()} 方法：

@example
newdict = olddict.copy()
@end example

序列可以用切片操作进行复制：

@example
new_l = l[:]
@end example

@node 如何找到对象的方法或属性？,如何用代码获取对象的名称？,如何复制 Python 对象？,语言核心内容
@anchor{faq/programming how-can-i-find-the-methods-or-attributes-of-an-object}@anchor{44b4}
@subsubsection 如何找到对象的方法或属性？


假定 x 是一个用户自定义类的实例，@code{dir(x)} 将返回一个按字母排序的名称列表，其中包含了实例的属性及由类定义的方法和属性。

@node 如何用代码获取对象的名称？,逗号运算符的优先级是什么？,如何找到对象的方法或属性？,语言核心内容
@anchor{faq/programming how-can-my-code-discover-the-name-of-an-object}@anchor{44b5}
@subsubsection 如何用代码获取对象的名称？


一般而言这是无法实现的，因为对象并不存在真正的名称。赋值本质上是把某个名称绑定到某个值上；@code{def} 和 @code{class} 语句同样如此，只是值换成了某个可调用对象。比如以下代码：

@example
>>> class A:
...     pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x16D07CC>
>>> print(a)
<__main__.A object at 0x16D07CC>
@end example

可以不太严谨地说，上述类具有一个名称：即便它绑定了两个名称并通过名称 B 发起调用，可是创建出来的实例仍被视为是类 A 的实例。但无法说出实例的名称是 a 还是 b，因为这两个名称都被绑定到同一个值上了。

代码一般没有必要去“知晓”某个值的名称。通常这种需求预示着还是改变方案为好，除非真的是要编写内审程序。

在 comp.lang.python 中，Fredrik Lundh 在回答这样的问题时曾经给出过一个绝佳的类比：

@quotation

这就像要知道家门口的那只猫的名字一样：猫（对象）自己不会说出它的名字，它根本就不在乎自己叫什么——所以唯一方法就是问一遍你所有的邻居（命名空间），这是不是他们家的猫（对象）……

……并且如果你发现它有很多名字或根本没有名字，那也不必惊讶！
@end quotation

@node 逗号运算符的优先级是什么？,是否提供等价于 C 语言 "? " 三目运算符的东西？,如何用代码获取对象的名称？,语言核心内容
@anchor{faq/programming what-s-up-with-the-comma-operator-s-precedence}@anchor{44b6}
@subsubsection 逗号运算符的优先级是什么？


逗号不是 Python 的运算符。 请看以下例子：

@example
>>> "a" in "b", "a"
(False, 'a')
@end example

由于逗号不是运算符，而只是表达式之间的分隔符，因此上述代码就相当于：

@example
("a" in "b"), "a"
@end example

而不是：

@example
"a" in ("b", "a")
@end example

对于各种赋值运算符（ @code{=} 、 @code{+=} 等）来说同样如此。他们并不是真正的运算符，而只是赋值语句中的语法分隔符。

@node 是否提供等价于 C 语言 "? " 三目运算符的东西？,是否可以用 Python 编写让人眼晕的单行程序?,逗号运算符的优先级是什么？,语言核心内容
@anchor{faq/programming is-there-an-equivalent-of-c-s-ternary-operator}@anchor{44b7}
@subsubsection 是否提供等价于 C 语言 "?:" 三目运算符的东西？


有的。语法如下：

@example
[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y
@end example

在 Python 2.5 引入上述语法之前，通常的做法是使用逻辑运算符：

@example
[expression] and [on_true] or [on_false]
@end example

然而这种做法并不保险，因为当 @emph{on_true} 为布尔值“假”时，结果将会出错。所以肯定还是采用 @code{... if ... else ...} 形式为妙。

@node 是否可以用 Python 编写让人眼晕的单行程序?,函数形参列表中的斜杠（/）是什么意思？,是否提供等价于 C 语言 "? " 三目运算符的东西？,语言核心内容
@anchor{faq/programming is-it-possible-to-write-obfuscated-one-liners-in-python}@anchor{44b8}
@subsubsection 是否可以用 Python 编写让人眼晕的单行程序?


可以。通常是在 @ref{d01,,lambda} 中嵌套 @code{lambda} 来实现的。请参阅以下三个来自 Ulf Bartelt 的示例代码：

@example
from functools import reduce

# Primes < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

# First 10 Fibonacci numbers
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))

# Mandelbrot set
print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
#    \___ ___/  \___ ___/  |   |   |__ lines on screen
#        V          V      |   |______ columns on screen
#        |          |      |__________ maximum of "iterations"
#        |          |_________________ range on y axis
#        |____________________________ range on x axis
@end example

请不要在家里尝试，骚年！

@node 函数形参列表中的斜杠（/）是什么意思？,,是否可以用 Python 编写让人眼晕的单行程序?,语言核心内容
@anchor{faq/programming faq-positional-only-arguments}@anchor{1759}@anchor{faq/programming what-does-the-slash-in-the-parameter-list-of-a-function-mean}@anchor{44b9}
@subsubsection 函数形参列表中的斜杠（/）是什么意思？


函数参数列表中的斜杠表示在它之前的形参全都仅限位置形参。仅限位置形参没有可供外部使用的名称。在调用仅接受位置形参的函数时，实参只会根据位置映射到形参上。假定 @ref{294,,divmod()} 是一个仅接受位置形参的函数。 它的帮助文档如下所示：

@example
>>> help(divmod)
Help on built-in function divmod in module builtins:

divmod(x, y, /)
    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
@end example

形参列表尾部的斜杠说明，两个形参都是仅限位置形参。因此，用关键字参数调用 @ref{294,,divmod()} 将会引发错误：

@example
>>> divmod(x=3, y=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: divmod() takes no keyword arguments
@end example

@node 数字和字符串,性能<4>,语言核心内容,编程常见问题
@anchor{faq/programming numbers-and-strings}@anchor{44ba}
@subsection 数字和字符串


@menu
* 如何给出十六进制和八进制整数？:: 
* 为什么 -22 // 10 会返回 -3 ？:: 
* 我如何获得 int 字面属性而不是 SyntaxError ？:: 
* 如何将字符串转换为数字？:: 
* 如何将数字转换为字符串？:: 
* 如何修改字符串？:: 
* 如何使用字符串调用函数/方法？:: 
* 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？. 
* 是否有 scanf() 或 sscanf() 的等价函数？: 是否有 scanf 或 sscanf 的等价函数？. 
* 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？:: 

@end menu

@node 如何给出十六进制和八进制整数？,为什么 -22 // 10 会返回 -3 ？,,数字和字符串
@anchor{faq/programming how-do-i-specify-hexadecimal-and-octal-integers}@anchor{44bb}
@subsubsection 如何给出十六进制和八进制整数？


要给出八进制数，需在八进制数值前面加上一个零和一个小写或大写字母 "o" 作为前缀。例如，要将变量 "a" 设为八进制的 "10" （十进制的 8），写法如下：

@example
>>> a = 0o10
>>> a
8
@end example

十六进制数也很简单。只要在十六进制数前面加上一个零和一个小写或大写的字母 "x"。十六进制数中的字母可以为大写或小写。比如在 Python 解释器中输入：

@example
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
@end example

@node 为什么 -22 // 10 会返回 -3 ？,我如何获得 int 字面属性而不是 SyntaxError ？,如何给出十六进制和八进制整数？,数字和字符串
@anchor{faq/programming why-does-22-10-return-3}@anchor{44bc}
@subsubsection 为什么 -22 // 10 会返回 -3 ？


这主要是为了让 @code{i % j} 的正负与 @code{j} 一致，如果期望如此，且期望如下等式成立：

@example
i == (i // j) * j + (i % j)
@end example

那么整除就必须返回向下取整的结果。C 语言同样要求保持这种一致性，于是编译器在截断 @code{i // j} 的结果时需要让 @code{i % j} 的正负与 @code{i} 一致。

对于 @code{i % j} 来说 @code{j} 为负值的应用场景实际上是非常少的。 而 @code{j} 为正值的情况则非常多，并且实际上在所有情况下让 @code{i % j} 的结果为 @code{>= 0} 会更有用处。 如果现在时间为 10 时，那么 200 小时前应是几时？ @code{-190 % 12 == 2} 是有用处的；@code{-190 % 12 == -10} 则是会导致意外的漏洞。

@node 我如何获得 int 字面属性而不是 SyntaxError ？,如何将字符串转换为数字？,为什么 -22 // 10 会返回 -3 ？,数字和字符串
@anchor{faq/programming how-do-i-get-int-literal-attribute-instead-of-syntaxerror}@anchor{44bd}
@subsubsection 我如何获得 int 字面属性而不是 SyntaxError ？


试图以正常方式查询一个 @code{int} 字头的属性，会出现语法错误，因为句号被看成是小数点:

@example
>>> 1.__class__
  File "<stdin>", line 1
  1.__class__
   ^
SyntaxError: invalid decimal literal
@end example

解决办法是用空格或括号将字词与句号分开。

@example
>>> 1 .__class__
<class 'int'>
>>> (1).__class__
<class 'int'>
@end example

@node 如何将字符串转换为数字？,如何将数字转换为字符串？,我如何获得 int 字面属性而不是 SyntaxError ？,数字和字符串
@anchor{faq/programming how-do-i-convert-a-string-to-a-number}@anchor{44be}
@subsubsection 如何将字符串转换为数字？


对于整数，可使用内置的 @ref{205,,int()} 类型构造器，例如 @code{int('144') == 144}。 类似地，可使用 @ref{1fe,,float()} 转换为浮点数，例如 @code{float('144') == 144.0}。

默认情况下，这些操作会将数字按十进制来解读，因此 @code{int('0144') == 144} 为真值，而 @code{int('0x144')} 会引发 @ref{16d,,ValueError}。 @code{int(string, base)} 接受第二个可选参数指定转换的基数，例如 @code{int( '0x144', 16) == 324}。 如果指定基数为 0，则按 Python 规则解读数字：前缀 '0o' 表示八进制，而 '0x' 表示十六进制。

如果只是想把字符串转为数字，请不要使用内置函数 @ref{c6a,,eval()}。 @ref{c6a,,eval()} 的速度慢很多且存在安全风险：别人可能会传入带有不良副作用的 Python 表达式。比如可能会传入 @code{__import__('os').system("rm -rf $HOME")} ，这会把 home 目录给删了。

@ref{c6a,,eval()} 还有把数字解析为 Python 表达式的后果，因此如 @code{eval('09')} 将会导致语法错误，因为 Python 不允许十进制数带有前导 '0'（'0' 除外）。

@node 如何将数字转换为字符串？,如何修改字符串？,如何将字符串转换为数字？,数字和字符串
@anchor{faq/programming how-do-i-convert-a-number-to-a-string}@anchor{44bf}
@subsubsection 如何将数字转换为字符串？


比如要把数字 144 转换为字符串 '144'，可使用内置类型构造器 @ref{206,,str()}。如果要表示为十六进制或八进制数格式，可使用内置函数 @ref{d36,,hex()} 或 @ref{d35,,oct()}。更复杂的格式化方法请参阅 @ref{29d,,格式字符串字面值} 和 @ref{de8,,格式字符串语法} 等章节，比如 @code{"@{:04d@}".format(144)} 会生成 @code{'0144'} ， @code{"@{:.3f@}".format(1.0/3.0)} 则会生成 @code{'0.333'}。

@node 如何修改字符串？,如何使用字符串调用函数/方法？,如何将数字转换为字符串？,数字和字符串
@anchor{faq/programming how-do-i-modify-a-string-in-place}@anchor{44c0}
@subsubsection 如何修改字符串？


无法修改，因为字符串是不可变对象。 在大多数情况下，只要将各个部分组合起来构造出一个新字符串即可。如果需要一个能原地修改 Unicode 数据的对象，可以试试 @ref{924,,io.StringIO} 对象或 @ref{6,,array} 模块：

@example
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'

>>> import array
>>> a = array.array('u', s)
>>> print(a)
array('u', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('u', 'yello, world')
>>> a.tounicode()
'yello, world'
@end example

@node 如何使用字符串调用函数/方法？,是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,如何修改字符串？,数字和字符串
@anchor{faq/programming how-do-i-use-strings-to-call-functions-methods}@anchor{44c1}
@subsubsection 如何使用字符串调用函数/方法？


有多种技巧可供选择。


@itemize *

@item 
最好的做法是采用一个字典，将字符串映射为函数。其主要优势就是字符串不必与函数名一样。这也是用来模拟 case 结构的主要技巧：

@example
def a():
    pass

def b():
    pass

dispatch = @{'go': a, 'stop': b@}  # Note lack of parens for funcs

dispatch[get_input()]()  # Note trailing parens to call function
@end example

@item 
利用内置函数 @ref{554,,getattr()} ：

@example
import foo
getattr(foo, 'bar')()
@end example

请注意 @ref{554,,getattr()} 可用于任何对象，包括类、类实例、模块等等。

标准库就多次使用了这个技巧，例如：

@example
class Foo:
    def do_foo(self):
        ...

    def do_bar(self):
        ...

f = getattr(foo_instance, 'do_' + opname)
f()
@end example

@item 
用 @ref{55f,,locals()} 解析出函数名：

@example
def myFunc():
    print("hello")

fname = "myFunc"

f = locals()[fname]
f()
@end example
@end itemize

@node 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,是否有 scanf 或 sscanf 的等价函数？,如何使用字符串调用函数/方法？,数字和字符串
@anchor{faq/programming is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings}@anchor{44c2}
@subsubsection 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？


可以使用 @code{S.rstrip("\r\n")} 从字符串 @code{S} 的末尾删除所有的换行符，而不删除其他尾随空格。如果字符串 @code{S} 表示多行，且末尾有几个空行，则将删除所有空行的换行符：

@example
>>> lines = ("line 1 \r\n"
...          "\r\n"
...          "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '
@end example

由于通常只在一次读取一行文本时才需要这样做，所以使用 @code{S.rstrip()} 这种方式工作得很好。

@node 是否有 scanf 或 sscanf 的等价函数？,'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,数字和字符串
@anchor{faq/programming is-there-a-scanf-or-sscanf-equivalent}@anchor{44c3}
@subsubsection 是否有 scanf() 或 sscanf() 的等价函数？


没有。

如果要对简单的输入进行解析，最容易的做法通常是利用字符串对象的 @ref{89a,,split()} 方法将一行按空白符分隔拆分为多个单词，然后用 @ref{205,,int()} 或 @ref{1fe,,float()} 将十进制数字符串转换为数字值。 @code{split()} 支持可选的 "sep" 形参，适用于分隔符不用空白符的情况。

如果要对更复杂的输入进行解析，那么正则表达式要比 C 语言的 @code{sscanf()} 更强大，也更合适。

@node 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,,是否有 scanf 或 sscanf 的等价函数？,数字和字符串
@anchor{faq/programming what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean}@anchor{44c4}
@subsubsection 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？


见 @ref{d0c,,Unicode 指南}

@node 性能<4>,序列（元组/列表）,数字和字符串,编程常见问题
@anchor{faq/programming performance}@anchor{44c5}
@subsection 性能


@menu
* 我的程序太慢了。该如何加快速度？:: 
* 将多个字符串连接在一起的最有效方法是什么？:: 

@end menu

@node 我的程序太慢了。该如何加快速度？,将多个字符串连接在一起的最有效方法是什么？,,性能<4>
@anchor{faq/programming my-program-is-too-slow-how-do-i-speed-it-up}@anchor{44c6}
@subsubsection 我的程序太慢了。该如何加快速度？


总的来说，这是个棘手的问题。在进一步讨论之前，首先应该记住以下几件事：


@itemize *

@item 
不同的 Python 实现具有不同的性能特点。 本 FAQ 着重解答的是 @ref{1598,,CPython}。

@item 
不同操作系统可能会有不同表现，尤其是涉及 I/O 和多线程时。

@item 
在尝试优化代码 @emph{之前} ，务必要先找出程序中的热点（请参阅 @ref{d3,,profile} 模块）。

@item 
编写基准测试脚本，在寻求性能提升的过程中就能实现快速迭代（请参阅 @ref{10d,,timeit} 模块）。

@item 
强烈建议首先要保证足够高的代码测试覆盖率（通过单元测试或其他技术），因为复杂的优化有可能会导致代码回退。
@end itemize

话虽如此，Python 代码的提速还是有很多技巧的。以下列出了一些普适性的原则，对于让性能达到可接受的水平会有很大帮助：


@itemize *

@item 
相较于试图对全部代码铺开做微观优化，优化算法（或换用更快的算法）可以产出更大的收益。

@item 
使用正确的数据结构。参考 @ref{1778,,内置类型} 和 @ref{1d,,collections} 模块的文档。

@item 
如果标准库已为某些操作提供了基础函数，则可能（当然不能保证）比所有自编的函数都要快。对于用 C 语言编写的基础函数则更是如此，比如内置函数和一些扩展类型。例如，一定要用内置方法 @ref{550,,list.sort()} 或 @ref{54f,,sorted()} 函数进行排序（某些高级用法的示例请参阅 @ref{1767,,排序指南} ）。

@item 
抽象往往会造成中间层，并会迫使解释器执行更多的操作。如果抽象出来的中间层级太多，工作量超过了要完成的有效任务，那么程序就会被拖慢。应该避免过度的抽象，而且往往也会对可读性产生不利影响，特别是当函数或方法比较小的时候。
@end itemize

如果你已经达到纯 Python 允许的限制，那么有一些工具可以让你走得更远。 例如， Cython@footnote{http://cython.org} 可以将稍微修改的 Python 代码版本编译为 C 扩展，并且可以在许多不同的平台上使用。 Cython 可以利用编译（和可选的类型注释）来使代码明显快于解释运行时的速度。 如果您对 C 编程技能有信心，也可以自己 @ref{1361,,编写 C 扩展模块} 。


@subsubheading 参见


专门介绍 性能提示@footnote{https://wiki.python.org/moin/PythonSpeed/PerformanceTips} 的wiki页面。


@node 将多个字符串连接在一起的最有效方法是什么？,,我的程序太慢了。该如何加快速度？,性能<4>
@anchor{faq/programming efficient-string-concatenation}@anchor{44c7}@anchor{faq/programming what-is-the-most-efficient-way-to-concatenate-many-strings-together}@anchor{44c8}
@subsubsection 将多个字符串连接在一起的最有效方法是什么？


@ref{206,,str} 和 @ref{172,,bytes} 对象是不可变的，因此连接多个字符串的效率会很低，因为每次连接都会创建一个新的对象。一般情况下，总耗时与字符串总长是二次方的关系。

如果要连接多个 @ref{206,,str} 对象，通常推荐的方案是先全部放入列表，最后再调用 @ref{1796,,str.join()} ：

@example
chunks = []
for s in my_strings:
    chunks.append(s)
result = '@w{'}.join(chunks)
@end example

（还有一种合理高效的习惯做法，就是利用 @ref{924,,io.StringIO} ）

如果要连接多个 @ref{172,,bytes} 对象，推荐做法是用 @ref{173,,bytearray} 对象的原地连接操作（ @code{+=} 运算符）追加数据：

@example
result = bytearray()
for b in my_bytes_objects:
    result += b
@end example

@node 序列（元组/列表）,对象,性能<4>,编程常见问题
@anchor{faq/programming sequences-tuples-lists}@anchor{44c9}
@subsection 序列（元组/列表）


@menu
* 如何在元组和列表之间进行转换？:: 
* 什么是负数索引？:: 
* 序列如何以逆序遍历？:: 
* 如何从列表中删除重复项？:: 
* 如何从列表中删除多个项？:: 
* 如何在 Python 中创建数组？:: 
* 如何创建多维列表？:: 
* 如何将方法应用于一系列对象？:: 
* 为什么 a_tuple[i] += ['item'] 会引发异常？:: 
* 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？:: 
* 如何根据另一个列表的值对某列表进行排序？:: 

@end menu

@node 如何在元组和列表之间进行转换？,什么是负数索引？,,序列（元组/列表）
@anchor{faq/programming how-do-i-convert-between-tuples-and-lists}@anchor{44ca}
@subsubsection 如何在元组和列表之间进行转换？


类型构造器 @code{tuple(seq)} 可将任意序列（实际上是任意可迭代对象）转换为数据项和顺序均不变的元组。

例如，@code{tuple([1, 2, 3])} 会生成 @code{(1, 2, 3)} ， @code{tuple('abc')} 则会生成 @code{('a', 'b', 'c')} 。 如果参数就是元组，则不会创建副本而是返回同一对象，因此如果无法确定某个对象是否为元组时，直接调用 @ref{1a2,,tuple()} 也没什么代价。

类型构造器 @code{list(seq)} 可将任意序列或可迭代对象转换为数据项和顺序均不变的列表。例如，@code{list((1, 2, 3))} 会生成 @code{[1, 2, 3]} 而 @code{list('abc')} 则会生成 @code{['a', 'b', 'c']}。如果参数即为列表，则会像 @code{seq[:]} 那样创建一个副本。

@node 什么是负数索引？,序列如何以逆序遍历？,如何在元组和列表之间进行转换？,序列（元组/列表）
@anchor{faq/programming what-s-a-negative-index}@anchor{44cb}
@subsubsection 什么是负数索引？


Python 序列的索引可以是正数或负数。索引为正数时，0 是第一个索引值， 1 为第二个，依此类推。索引为负数时，-1 为倒数第一个索引值，-2 为倒数第二个，依此类推。可以认为 @code{seq[-n]} 就相当于 @code{seq[len(seq)-n]}。

使用负数序号有时会很方便。 例如 @code{S[:-1]} 就是原字符串去掉最后一个字符，这可以用来移除某个字符串末尾的换行符。

@node 序列如何以逆序遍历？,如何从列表中删除重复项？,什么是负数索引？,序列（元组/列表）
@anchor{faq/programming how-do-i-iterate-over-a-sequence-in-reverse-order}@anchor{44cc}
@subsubsection 序列如何以逆序遍历？


使用内置函数 @ref{2cd,,reversed()} ：

@example
for x in reversed(sequence):
    ...  # do something with x ...
@end example

原序列不会变化，而是构建一个逆序的新副本以供遍历。

@node 如何从列表中删除重复项？,如何从列表中删除多个项？,序列如何以逆序遍历？,序列（元组/列表）
@anchor{faq/programming how-do-you-remove-duplicates-from-a-list}@anchor{44cd}
@subsubsection 如何从列表中删除重复项？


许多完成此操作的的详细介绍，可参阅 Python Cookbook：

@quotation

@indicateurl{https://code.activestate.com/recipes/52560/}
@end quotation

如果列表允许重新排序，不妨先对其排序，然后从列表末尾开始扫描，依次删除重复项：

@example
if mylist:
    mylist.sort()
    last = mylist[-1]
    for i in range(len(mylist)-2, -1, -1):
        if last == mylist[i]:
            del mylist[i]
        else:
            last = mylist[i]
@end example

如果列表的所有元素都能用作集合的键（即都是 @ref{277,,hashable} ），以下做法速度往往更快：

@example
mylist = list(set(mylist))
@end example

以上操作会将列表转换为集合，从而删除重复项，然后返回成列表。

@node 如何从列表中删除多个项？,如何在 Python 中创建数组？,如何从列表中删除重复项？,序列（元组/列表）
@anchor{faq/programming how-do-you-remove-multiple-items-from-a-list}@anchor{44ce}
@subsubsection 如何从列表中删除多个项？


类似于删除重复项，一种做法是反向遍历并根据条件删除。不过更简单快速的做法就是切片替换操作，采用隐式或显式的正向迭代遍历。以下是三种变体写法：

@example
mylist[:] = filter(keep_function, mylist)
mylist[:] = (x for x in mylist if keep_condition)
mylist[:] = [x for x in mylist if keep_condition]
@end example

列表推导式可能是最快的。

@node 如何在 Python 中创建数组？,如何创建多维列表？,如何从列表中删除多个项？,序列（元组/列表）
@anchor{faq/programming how-do-you-make-an-array-in-python}@anchor{44cf}
@subsubsection 如何在 Python 中创建数组？


用列表：

@example
["this", 1, "is", "an", "array"]
@end example

列表在时间复杂度方面相当于 C 或 Pascal 的数组；主要区别在于，Python 列表可以包含多种不同类型的对象。

@code{array} 模块也提供了一些创建具有紧凑格式的固定类型数组的方法，但其索引访问速度比列表慢。 并请注意 NumPy 和其他一些第三方包也定义了一些各具特色的数组类结构。

若要得到 Lisp 风格的列表，可以用元组模拟 cons 元素：

@example
lisp_list = ("like",  ("this",  ("example", None) ) )
@end example

若要具备可变性，可以不用元组而是用列表。模拟 lisp car 函数的是 @code{lisp_list[0]} ，模拟 cdr 函数的是 @code{lisp_list[1]} 。仅当真正必要时才会这么用，因为通常这种用法要比 Python 列表慢得多。

@node 如何创建多维列表？,如何将方法应用于一系列对象？,如何在 Python 中创建数组？,序列（元组/列表）
@anchor{faq/programming faq-multidimensional-list}@anchor{1795}@anchor{faq/programming how-do-i-create-a-multidimensional-list}@anchor{44d0}
@subsubsection 如何创建多维列表？


多维数组或许会用以下方式建立：

@example
>>> A = [[None] * 2] * 3
@end example

打印出来貌似没错：

@c A = [[None] * 2] * 3

@example
>>> A
[[None, None], [None, None], [None, None]]
@end example

但如果给某一项赋值，结果会同时在多个位置体现出来：

@c A = [[None] * 2] * 3

@example
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
@end example

原因在于用 @code{*} 对列表执行重复操作并不会创建副本，而只是创建现有对象的引用。 @code{*3} 创建的是包含 3 个引用的列表，每个引用指向的是同一个长度为 2 的列表。1 处改动会体现在所有地方，这一定不是应有的方案。

推荐做法是先创建一个所需长度的列表，然后将每个元素都填充为一个新建列表。

@example
A = [None] * 3
for i in range(3):
    A[i] = [None] * 2
@end example

以上生成了一个包含 3 个列表的列表，每个子列表的长度为 2。也可以采用列表推导式：

@example
w, h = 2, 3
A = [[None] * w for i in range(h)]
@end example

或者你还可以使用提供矩阵类型的扩展包；其中最著名的是 NumPy@footnote{http://www.numpy.org/}。

@node 如何将方法应用于一系列对象？,为什么 a_tuple[i] += ['item'] 会引发异常？,如何创建多维列表？,序列（元组/列表）
@anchor{faq/programming how-do-i-apply-a-method-to-a-sequence-of-objects}@anchor{44d1}
@subsubsection 如何将方法应用于一系列对象？


可以使用列表推导式：

@example
result = [obj.method() for obj in mylist]
@end example

@node 为什么 a_tuple[i] += ['item'] 会引发异常？,我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,如何将方法应用于一系列对象？,序列（元组/列表）
@anchor{faq/programming faq-augmented-assignment-tuple-error}@anchor{15e9}@anchor{faq/programming why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works}@anchor{44d2}
@subsubsection 为什么 a_tuple[i] += ['item'] 会引发异常？


这是由两个因素共同导致的，一是增强赋值运算符属于 @emph{赋值} 运算符，二是 Python 可变和不可变对象之间的差别。

只要元组的元素指向可变对象，这时对元素进行增强赋值，那么这里介绍的内容都是适用的。在此只以 @code{list} 和 @code{+=} 举例。

如果你写成这样:

@example
>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
   ...
TypeError: 'tuple' object does not support item assignment
@end example

触发异常的原因显而易见： @code{1} 会与指向（@code{1}）的对象 @code{a_tuple[0]} 相加，生成结果对象 @code{2}，但在试图将运算结果 @code{2} 赋值给元组的 @code{0} 号元素时就会报错，因为元组元素的指向无法更改。

其实在幕后，上述增强赋值语句的执行过程大致如下：

@example
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

由于元组是不可变的，因此赋值这步会引发错误。

如果写成以下这样：

@example
>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

这时触发异常会令人略感惊讶，更让人吃惊的是虽有报错，但加法操作却生效了：

@example
>>> a_tuple[0]
['foo', 'item']
@end example

要明白为何会这样，需要知道 (a) 如果一个对象实现了 @code{__iadd__} 魔法方法，在执行 @code{+=} 增强赋值时就会调用它，并采纳其返回值；(b) 对于列表而言，@code{__iadd__} 相当于在列表上调用 @code{extend} 并返回该列表。因此对于列表可以说 @code{+=} 就是 @code{list.extend} 的“快捷方式”：

@example
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
@end example

这相当于：

@example
>>> result = a_list.__iadd__([1])
>>> a_list = result
@end example

a_list 所引用的对象已被修改，而引用被修改对象的指针又重新被赋值给 @code{a_list}。 赋值的最终结果没有变化，因为它是引用 @code{a_list} 之前所引用的同一对象的指针，但仍然发生了赋值操作。

因此，在此元组示例中，发生的事情等同于：

@example
>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment
@end example

@code{__iadd__} 成功执行，因此列表得到了扩充，但是虽然 @code{result} 指向了 @code{a_tuple[0]} 已经指向的同一对象，最后的赋值仍然导致了报错，因为元组是不可变的。

@node 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,如何根据另一个列表的值对某列表进行排序？,为什么 a_tuple[i] += ['item'] 会引发异常？,序列（元组/列表）
@anchor{faq/programming i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python}@anchor{44d3}
@subsubsection 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？


归功于 Perl 社区的 Randal Schwartz，该技术根据度量值对列表进行排序，该度量值将每个元素映射为“顺序值”。在 Python 中，请利用 @ref{550,,list.sort()} 方法的 @code{key} 参数：

@example
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
@end example

@node 如何根据另一个列表的值对某列表进行排序？,,我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,序列（元组/列表）
@anchor{faq/programming how-can-i-sort-one-list-by-values-from-another-list}@anchor{44d4}
@subsubsection 如何根据另一个列表的值对某列表进行排序？


将它们合并到元组的迭代器中，对结果列表进行排序，然后选择所需的元素。

@example
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']
@end example

@node 对象,模块<3>,序列（元组/列表）,编程常见问题
@anchor{faq/programming objects}@anchor{44d5}
@subsection 对象


@menu
* 什么是类？:: 
* 什么是方法？:: 
* 什么是 self ？:: 
* 如何检查对象是否为给定类或其子类的一个实例？:: 
* 什么是委托？:: 
* 如何在派生类中调用被重载的基类方法?:: 
* 如何让代码更容易对基类进行修改？:: 
* 如何创建静态类数据和静态类方法？:: 
* 在 Python 中如何重载构造函数（或方法）？:: 
* 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。:: 
* 类定义了 __del__ 方法，但是删除对象时没有调用它。:: 
* 如何获取给定类的所有实例的列表？:: 
* 为什么 id() 的结果看起来不是唯一的？: 为什么 id 的结果看起来不是唯一的？. 
* 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？:: 
* 一个子类如何控制哪些数据被存储在一个不可变的实例中？:: 

@end menu

@node 什么是类？,什么是方法？,,对象
@anchor{faq/programming what-is-a-class}@anchor{44d6}
@subsubsection 什么是类？


类是通过执行 class 语句创建的某种对象的类型。创建实例对象时，用 Class 对象作为模板，实例对象既包含了数据（属性），又包含了数据类型特有的代码（方法）。

类可以基于一个或多个其他类（称之为基类）进行创建。基类的属性和方法都得以继承。这样对象模型就可以通过继承不断地进行细化。比如通用的 @code{Mailbox} 类提供了邮箱的基本访问方法.，它的子类 @code{MboxMailbox}、 @code{MaildirMailbox}、 @code{OutlookMailbox} 则能够处理各种特定的邮箱格式。

@node 什么是方法？,什么是 self ？,什么是类？,对象
@anchor{faq/programming what-is-a-method}@anchor{44d7}
@subsubsection 什么是方法？


方法是属于对象的函数，对于对象 @code{x} ，通常以 @code{x.name(arguments...)} 的形式调用。方法以函数的形式给出定义，位于类的定义内：

@example
class C:
    def meth(self, arg):
        return arg * 2 + self.attribute
@end example

@node 什么是 self ？,如何检查对象是否为给定类或其子类的一个实例？,什么是方法？,对象
@anchor{faq/programming what-is-self}@anchor{44d8}
@subsubsection 什么是 self ？


Self 只是方法的第一个参数的习惯性名称。假定某个类中有个方法定义为 @code{meth(self, a, b, c)} ，则其实例 @code{x} 应以 @code{x.meth(a, b, c)} 的形式进行调用；而被调用的方法则应视其为做了 @code{meth(x, a, b, c)} 形式的调用。

另请参阅 @ref{44d9,,为什么必须在方法定义和调用中显式使用“self”？} 。

@node 如何检查对象是否为给定类或其子类的一个实例？,什么是委托？,什么是 self ？,对象
@anchor{faq/programming how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it}@anchor{44da}
@subsubsection 如何检查对象是否为给定类或其子类的一个实例？


可使用内置函数 @code{isinstance(obj, cls)}。可以检测对象是否属于多个类中某一个的实例，只要把单个类换成元组即可，比如 @code{isinstance(obj, (class1, class2, ...))}，还可以检查对象是否属于某个 Python 内置类型，例如 @code{isinstance(obj, str)} 或 @code{isinstance(obj, (int, float, complex))}。

请注意 @ref{55a,,isinstance()} 还会检测派生自 @ref{c0e,,abstract base class} 的虚继承。 因此对于已注册的类，即便没有直接或间接继承自抽象基类，对抽象基类的检测都将返回 @code{True} 。要想检测“真正的继承”，请扫描类的 @ref{29b3,,MRO}:

@example
from collections.abc import Mapping

class P:
     pass

class C(P):
    pass

Mapping.register(P)
@end example

@example
>>> c = C()
>>> isinstance(c, C)        # direct
True
>>> isinstance(c, P)        # indirect
True
>>> isinstance(c, Mapping)  # virtual
True

# Actual inheritance chain
>>> type(c).__mro__
(<class 'C'>, <class 'P'>, <class 'object'>)

# Test for "true inheritance"
>>> Mapping in type(c).__mro__
False
@end example

请注意，大多数程序不会经常用 @ref{55a,,isinstance()} 对用户自定义类进行检测。 如果是自已开发的类，更合适的面向对象编程风格应该是在类中定义多种方法，以封装特定的行为，而不是检查对象属于什么类再据此干不同的事。假定有如下执行某些操作的函数:

@example
def search(obj):
    if isinstance(obj, Mailbox):
        ...  # code to search a mailbox
    elif isinstance(obj, Document):
        ...  # code to search a document
    elif ...
@end example

更好的方法是在所有类上定义一个 @code{search()} 方法，然后调用它：

@example
class Mailbox:
    def search(self):
        ...  # code to search a mailbox

class Document:
    def search(self):
        ...  # code to search a document

obj.search()
@end example

@node 什么是委托？,如何在派生类中调用被重载的基类方法?,如何检查对象是否为给定类或其子类的一个实例？,对象
@anchor{faq/programming what-is-delegation}@anchor{44db}
@subsubsection 什么是委托？


委托是一种面向对象的技术（也称为设计模式）。假设对象 @code{x} 已经存在，现在想要改变其某个方法的行为。可以创建一个新类，其中提供了所需修改方法的新实现，而将所有其他方法都委托给 @code{x} 的对应方法。

Python 程序员可以轻松实现委托。比如以下实现了一个类似于文件的类，只是会把所有写入的数据转换为大写：

@example
class UpperOut:

    def __init__(self, outfile):
        self._outfile = outfile

    def write(self, s):
        self._outfile.write(s.upper())

    def __getattr__(self, name):
        return getattr(self._outfile, name)
@end example

这里 @code{UpperOut} 类重新定义了 @code{write()} 方法，在调用下层的 @code{self._outfile.write()} 方法之前，会将参数字符串转换为大写。其他所有方法则都被委托给下层的 @code{self._outfile} 对象。委托是通过 @code{__getattr__} 方法完成的；请参阅 @ref{159b,,语言参考} 了解有关控制属性访问的更多信息。

请注意，更常见情况下，委托可能会变得比较棘手。如果属性既需要写入又需要读取，那么类还必须定义 @ref{ef6,,__setattr__()} 方法，而这时就必须十分的小心。基础的 @ref{ef6,,__setattr__()} 实现代码大致如下：

@example
class X:
    ...
    def __setattr__(self, name, value):
        self.__dict__[name] = value
    ...
@end example

大多数 @ref{ef6,,__setattr__()} 实现必须修改 @code{self.__dict__} 来为自身保存局部状态，而不至于引起无限递归。

@node 如何在派生类中调用被重载的基类方法?,如何让代码更容易对基类进行修改？,什么是委托？,对象
@anchor{faq/programming how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it}@anchor{44dc}
@subsubsection 如何在派生类中调用被重载的基类方法?


使用内置的 @ref{5e6,,super()} 函数：

@example
class Derived(Base):
    def meth(self):
        super(Derived, self).meth()
@end example

如果是 Python 3.0 之前的版本，可能用的还是传统类：对于诸如 @code{class Derived(Base): ...} 之类的类定义，可以用 @code{Base.meth(self, arguments...)} 的形式调用 @code{Base} (或 @code{Base} 的某个基类）中定义的方法 @code{meth()} 。这里， @code{Base.meth} 是一个未绑定的方法，因此需要给出 @code{self} 参数。

@node 如何让代码更容易对基类进行修改？,如何创建静态类数据和静态类方法？,如何在派生类中调用被重载的基类方法?,对象
@anchor{faq/programming how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class}@anchor{44dd}
@subsubsection 如何让代码更容易对基类进行修改？


可以为基类赋一个别名并基于该别名进行派生。这样只要修改赋给该别名的值即可。顺便提一下，如要动态地确定（例如根据可用的资源）该使用哪个基类，这个技巧也非常方便。例如：

@example
class Base:
    ...

BaseAlias = Base

class Derived(BaseAlias):
    ...
@end example

@node 如何创建静态类数据和静态类方法？,在 Python 中如何重载构造函数（或方法）？,如何让代码更容易对基类进行修改？,对象
@anchor{faq/programming how-do-i-create-static-class-data-and-static-class-methods}@anchor{44de}
@subsubsection 如何创建静态类数据和静态类方法？


Python 支持静态数据和静态方法（以 C++ 或 Java 的定义而言）。

静态数据只需定义一个类属性即可。若要为属性赋新值，则必须在赋值时显式使用类名：

@example
class C:
    count = 0   # number of times C.__init__ called

    def __init__(self):
        C.count = C.count + 1

    def getcount(self):
        return C.count  # or return self.count
@end example

对于所有符合 @code{isinstance(c, C)} 的 @code{c}， @code{c.count} 也同样指向 @code{C.count} ，除非被 @code{c} 自身重载，或者被从 @code{c.__class__} 回溯到基类 @code{C} 的搜索路径上的某个类所重载。

注意：在 C 的某个方法内部，像 @code{self.count = 42} 这样的赋值将在 @code{self} 自身的字典中新建一个名为 "count" 的不相关实例。 想要重新绑定类静态数据名称就必须总是指明类名，无论是在方法内部还是外部:

@example
C.count = 314
@end example

Python 支持静态方法：

@example
class C:
    @@staticmethod
    def static(arg1, arg2, arg3):
        # No 'self' parameter!
        ...
@end example

不过为了获得静态方法的效果，还有一种做法直接得多，也即使用模块级函数即可：

@example
def getcount():
    return C.count
@end example

如果代码的结构化比较充分，每个模块只定义了一个类（或者多个类的层次关系密切相关），那就具备了应有的封装。

@node 在 Python 中如何重载构造函数（或方法）？,在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,如何创建静态类数据和静态类方法？,对象
@anchor{faq/programming how-can-i-overload-constructors-or-methods-in-python}@anchor{44df}
@subsubsection 在 Python 中如何重载构造函数（或方法）？


这个答案实际上适用于所有方法，但问题通常首先出现于构造函数的应用场景中。

在 C++ 中，代码会如下所示：

@example
class C @{
    C() @{ cout << "No arguments\n"; @}
    C(int i) @{ cout << "Argument is " << i << "\n"; @}
@}
@end example

在 Python 中，只能编写一个构造函数，并用默认参数捕获所有情况。例如：

@example
class C:
    def __init__(self, i=None):
        if i is None:
            print("No arguments")
        else:
            print("Argument is", i)
@end example

这不完全等同，但在实践中足够接近。

也可以试试采用变长参数列表，例如：

@example
def __init__(self, *args):
    ...
@end example

上述做法同样适用于所有方法定义。

@node 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,类定义了 __del__ 方法，但是删除对象时没有调用它。,在 Python 中如何重载构造函数（或方法）？,对象
@anchor{faq/programming i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam}@anchor{44e0}
@subsubsection 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。


以双下划线打头的变量名会被“破坏”，以便以一种简单高效的方式定义类私有变量。任何形式为 @code{__spam} 的标识符（至少前缀两个下划线，至多后缀一个下划线）文本均会被替换为 @code{_classname__spam}，其中 @code{classname} 为去除了全部前缀下划线的当前类名称。

这并不能保证私密性：外部用户仍然可以访问 "_classname__spam" 属性，私有变量值也在对象的 @code{__dict__} 中可见。 许多 Python 程序员根本不操心要去使用私有变量名。

@node 类定义了 __del__ 方法，但是删除对象时没有调用它。,如何获取给定类的所有实例的列表？,在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,对象
@anchor{faq/programming my-class-defines-del-but-it-is-not-called-when-i-delete-the-object}@anchor{44e1}
@subsubsection 类定义了 __del__ 方法，但是删除对象时没有调用它。


这有几个可能的原因。

del 语句不一定调用 @ref{a0d,,__del__()} —— 它只是减少对象的引用计数，如果（引用计数）达到零，才会调用 @ref{a0d,,__del__()}。

如果数据结构包含循环链接（比如树的每个子节点都带有父节点的引用，而每个父节点也带有子节点的列表），则引用计数永远不会回零。尽管 Python 偶尔会用某种算法检测这种循环引用，但在数据结构的最后一条引用消失之后，垃圾收集器可能还要过段时间才会运行，因此 @ref{a0d,,__del__()} 方法可能会在不方便和随机的时刻被调用。这对于重现一个问题，是非常不方便的。更糟糕的是，各个对象的 @ref{a0d,,__del__()} 方法是以随机顺序执行的。虽然可以运行 @ref{362,,gc.collect()} 来强制执行垃圾回收工作，但 @emph{仍会存在}  一些对象永远不会被回收的失控情况。

尽管有垃圾回收器的存在，但为对象定义显式的 @code{close()} 方法，只要一用完即可供调用，这依然是一个好主意。这样 @code{close()} 方法即可删除引用子对象的属性。请勿直接调用 @ref{a0d,,__del__()} —— 而 @ref{a0d,,__del__()} 应该调用 @code{close()}，并且应能确保可以对同一对象多次调用 @code{close()} 。

另一种避免循环引用的做法是利用 @ref{131,,weakref} 模块，该模块允许指向对象但不增加其引用计数。例如，树状数据结构应该对父节点和同级节点使用弱引用（如果真要用的话！）

@c XXX relevant for Python 3?
@c 
@c If the object has ever been a local variable in a function that caught an
@c expression in an except clause, chances are that a reference to the object
@c still exists in that function's stack frame as contained in the stack trace.
@c Normally, calling :func:`sys.exc_clear` will take care of this by clearing
@c the last recorded exception.

最后提一下，如果 @ref{a0d,,__del__()} 方法引发了异常，会将警告消息打印到 @ref{1eb,,sys.stderr} 。

@node 如何获取给定类的所有实例的列表？,为什么 id 的结果看起来不是唯一的？,类定义了 __del__ 方法，但是删除对象时没有调用它。,对象
@anchor{faq/programming how-do-i-get-a-list-of-all-instances-of-a-given-class}@anchor{44e2}
@subsubsection 如何获取给定类的所有实例的列表？


Python 不会记录类（或内置类型）的实例。可以在类的构造函数中编写代码，通过保留每个实例的弱引用列表来跟踪所有实例。

@node 为什么 id 的结果看起来不是唯一的？,什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,如何获取给定类的所有实例的列表？,对象
@anchor{faq/programming why-does-the-result-of-id-appear-to-be-not-unique}@anchor{44e3}
@subsubsection 为什么 @code{id()} 的结果看起来不是唯一的？


@ref{e53,,id()} 返回一个整数，该整数在对象的生命周期内保证是唯一的。 因为在 CPython 中，这是对象的内存地址，所以经常发生在从内存中删除对象之后，下一个新创建的对象被分配在内存中的相同位置。 这个例子说明了这一点：

@example
>>> id(1000) 
13901272
>>> id(2000) 
13901272
@end example

这两个 id 属于不同的整数对象，之前先创建了对象，执行 @code{id()} 调用后又立即被删除了。若要确保检测 id 时的对象仍处于活动状态，请再创建一个对该对象的引用：

@example
>>> a = 1000; b = 2000
>>> id(a) 
13901272
>>> id(b) 
13891296
@end example

@node 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,一个子类如何控制哪些数据被存储在一个不可变的实例中？,为什么 id 的结果看起来不是唯一的？,对象
@anchor{faq/programming when-can-i-rely-on-identity-tests-with-the-is-operator}@anchor{44e4}
@subsubsection 什么情况下可以依靠 @emph{is} 运算符进行对象的身份相等性测试？


@code{is} 运算符可用于测试对象的身份相等性。@code{a is b} 等价于 @code{id(a) == id(b)}。

身份相等性最重要的特性就是对象总是等同于自身，@code{a is a} 一定返回 @code{True}。身份相等性测试的速度通常比相等性测试要快。而且与相等性测试不一样，身份相等性测试会确保返回布尔值 @code{True} 或 @code{False}。

但是，身份相等性测试 @emph{只能} 在对象身份确定的场景下才可替代相等性测试。一般来说，有以下3种情况对象身份是可以确定的：

1） 赋值操作创建了新的名称但没有改变对象身份。 在赋值操作 @code{new = old} 之后，可以保证 @code{new is old}。

2） 将对象置入存放对象引用的容器，对象身份不会改变。在列表赋值操作 @code{s[0] = x} 之后，可以保证 @code{s[0] is x}。

3） 单例对象，也即该对象只能存在一个实例。在赋值操作 @code{a = None} 和 @code{b = None} 之后，可以保证 @code{a is b}，因为 @code{None} 是单例对象。

其他大多数情况下，都不建议使用身份相等性测试，而应采用相等性测试。尤其是不应将身份相等性测试用于检测常量值，例如 @ref{205,,int} 和 @ref{206,,str}，因为他们并不一定是单例对象：

@example
>>> a = 1000
>>> b = 500
>>> c = b + 500
>>> a is c
False

>>> a = 'Python'
>>> b = 'Py'
>>> c = b + 'thon'
>>> a is c
False
@end example

同样地，可变容器的新实例，对象身份一定不同：

@example
>>> a = []
>>> b = []
>>> a is b
False
@end example

在标准库代码中，给出了一些正确使用对象身份测试的常见模式：

1） 正如 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} 所推荐的，对象身份测试是 @code{None} 值的推荐检测方式。这样的代码读起来就像自然的英文，并可以避免与其他可能为布尔值且计算结果为 False 的对象相混淆。

2) Detecting optional arguments can be tricky when @code{None} is a valid input
value.  In those situations, you can create a singleton sentinel object
guaranteed to be distinct from other objects.  For example, here is how
to implement a method that behaves like @ref{183e,,dict.pop()}:

@example
_sentinel = object()

def pop(self, key, default=_sentinel):
    if key in self:
        value = self[key]
        del self[key]
        return value
    if default is _sentinel:
        raise KeyError(key)
    return default
@end example

3） 编写容器的实现代码时，有时需要用对象身份测试来加强相等性检测。这样代码就不会被 @code{float('NaN')} 这类与自身不相等的对象所干扰。

例如，以下是 @code{collections.abc.Sequence.__contains__()} 的实现代码：

@example
def __contains__(self, value):
    for v in self:
        if v is value or v == value:
            return True
    return False
@end example

@node 一个子类如何控制哪些数据被存储在一个不可变的实例中？,,什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,对象
@anchor{faq/programming how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance}@anchor{44e5}
@subsubsection 一个子类如何控制哪些数据被存储在一个不可变的实例中？


当子类化一个不可变的类型时，重写 @ref{97d,,__new__()} 方法，而不是 @ref{e2b,,__init__()} 方法。 后者只在一个实例被创建之后运行，这对于改变一个不可变的实例中的数据来说太晚了。

所有这些不可变的类都有一个与它们的父类不同的签名:

@example
from datetime import date

class FirstOfMonthDate(date):
    "Always choose the first day of the month"
    def __new__(cls, year, month, day):
        return super().__new__(cls, year, month, 1)

class NamedInt(int):
    "Allow text names for some numbers"
    xlat = @{'zero': 0, 'one': 1, 'ten': 10@}
    def __new__(cls, value):
        value = cls.xlat.get(value, value)
        return super().__new__(cls, value)

class TitleStr(str):
    "Convert str to name suitable for a URL path"
    def __new__(cls, s):
        s = s.lower().replace(' ', '-')
        s = '@w{'}.join([c for c in s if c.isalnum() or c == '-'])
        return super().__new__(cls, s)
@end example

这些类可以这样使用:

@example
>>> FirstOfMonthDate(2012, 2, 14)
FirstOfMonthDate(2012, 2, 1)
>>> NamedInt('ten')
10
>>> NamedInt(20)
20
>>> TitleStr('Blog: Why Python Rocks')
'blog-why-python-rocks'
@end example

@node 模块<3>,,对象,编程常见问题
@anchor{faq/programming modules}@anchor{44e6}
@subsection 模块


@menu
* 如何创建 .pyc 文件？: 如何创建 pyc 文件？. 
* 如何找到当前模块名称？:: 
* 如何让模块相互导入？:: 
* __import__('x.y.z') 返回的是 <module 'x'> ；该如何得到 z 呢？: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？. 
* 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？:: 

@end menu

@node 如何创建 pyc 文件？,如何找到当前模块名称？,,模块<3>
@anchor{faq/programming how-do-i-create-a-pyc-file}@anchor{44e7}
@subsubsection 如何创建 .pyc 文件？


当首次导入模块时（或当前已编译文件创建之后源文件发生了改动），在 @code{.py} 文件所在目录的 @code{__pycache__} 子目录下会创建一个包含已编译代码的 @code{.pyc} 文件。该 @code{.pyc} 文件的名称开头部分将与 @code{.py} 文件名相同，并以 @code{.pyc} 为后缀，中间部分则依据创建它的 @code{python} 版本而各不相同。（详见 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147}。）

@code{.pyc} 文件有可能会无法创建，原因之一是源码文件所在的目录存在权限问题，这样就无法创建 @code{__pycache__} 子目录。假如以某个用户开发程序而以另一用户运行程序，就有可能发生权限问题，测试 Web 服务器就属于这种情况。

除非设置了 
@geindex PYTHONDONTWRITEBYTECODE
@geindex 环境变量; PYTHONDONTWRITEBYTECODE
@ref{e07,,PYTHONDONTWRITEBYTECODE} 环境变量，否则导入模块并且 Python 能够创建`@w{`}__pycache__`@w{`}子目录并把已编译模块写入该子目录（权限、存储空间等等）时，.pyc 文件就将自动创建。

在最高层级运行的 Python 脚本不会被视为经过了导入操作，因此不会创建 @code{.pyc} 文件。假定有一个最高层级的模块文件 @code{foo.py}，它导入了另一个模块 @code{xyz.py}，当运行 @code{foo} 模块（通过输入 shell 命令 @code{python foo.py} ），则会为 @code{xyz} 创建一个 @code{.pyc}，因为 @code{xyz} 是被导入的，但不会为 @code{foo} 创建 @code{.pyc} 文件，因为 @code{foo.py} 不是被导入的。

若要为 @code{foo} 创建 @code{.pyc} 文件 —— 即为未做导入的模块创建 @code{.pyc} 文件 —— 可以利用 @ref{d7,,py_compile} 和 @ref{20,,compileall} 模块。

@ref{d7,,py_compile} 模块能够手动编译任意模块。 一种做法是交互式地使用该模块中的 @code{compile()} 函数:

@example
>>> import py_compile
>>> py_compile.compile('foo.py')                 
@end example

这将会将  @code{.pyc} 文件写入与 @code{foo.py} 相同位置下的 @code{__pycache__} 子目录（或者你也可以通过可选参数 @code{cfile} 来重载该行为）。

还可以用 @ref{20,,compileall} 模块自动编译一个或多个目录下的所有文件。只要在命令行提示符中运行 @code{compileall.py} 并给出要编译的 Python 文件所在目录路径即可：

@example
python -m compileall .
@end example

@node 如何找到当前模块名称？,如何让模块相互导入？,如何创建 pyc 文件？,模块<3>
@anchor{faq/programming how-do-i-find-the-current-module-name}@anchor{44e8}
@subsubsection 如何找到当前模块名称？


模块可以查看预定义的全局变量 @code{__name__} 获悉自己的名称。如其值为 @code{'__main__'} ，程序将作为脚本运行。通常，许多通过导入使用的模块同时也提供命令行接口或自检代码，这些代码只在检测到处于 @code{__name__} 之后才会执行：

@example
def main():
    print('Running test...')
    ...

if __name__ == '__main__':
    main()
@end example

@node 如何让模块相互导入？,__import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,如何找到当前模块名称？,模块<3>
@anchor{faq/programming how-can-i-have-modules-that-mutually-import-each-other}@anchor{44e9}
@subsubsection 如何让模块相互导入？


假设有以下模块：

foo.py：

@example
from bar import bar_var
foo_var = 1
@end example

bar.py：

@example
from foo import foo_var
bar_var = 2
@end example

问题是解释器将执行以下步骤：


@itemize *

@item 
首先导入foo

@item 
创建用于foo的空全局变量

@item 
foo被编译并开始执行

@item 
foo 导入 bar

@item 
创建了用于bar 的空全局变量

@item 
bar被编译并开始执行

@item 
bar 导入 foo（这是一个空操作，因为已经有一个名为 foo 的模块）。

@item 
bar.foo_var = foo.foo_var
@end itemize

最后一步失败了，因为 Python 还没有完成对 foo 的解释，foo 的全局符号字典仍然是空的。

当你使用 @code{import foo} ，然后尝试在全局代码中访问 @code{foo.foo_var} 时，会发生同样的事情。

这个问题有（至少）三种可能的解决方法。

Guido van Rossum 建议完全避免使用 @code{from <module> import ...} ，并将所有代码放在函数中。全局变量和类变量的初始化只应使用常量或内置函数。这意味着导入模块中的所有内容都以 @code{<module>.<name>} 的形式引用。

Jim Roskind 建议每个模块都应遵循以下顺序：


@itemize *

@item 
导出（全局变量、函数和不需要导入基类的类）

@item 
@code{import} 语句

@item 
本模块的功能代码（包括根据导入值进行初始化的全局变量）。
@end itemize

Van Rossum 不太喜欢这种方法，因为import出现在一个奇怪的地方，但它确实有效。

Matthias Urlichs 建议对代码进行重构，使得递归导入根本就没必要发生。

这些解决方案并不相互排斥。

@node __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？,如何让模块相互导入？,模块<3>
@anchor{faq/programming import-x-y-z-returns-module-x-how-do-i-get-z}@anchor{44ea}
@subsubsection __import__('x.y.z') 返回的是 <module 'x'> ；该如何得到 z 呢？


不妨考虑换用 @ref{9a,,importlib} 中的函数 @ref{bef,,import_module()} ：

@example
z = importlib.import_module('x.y.z')
@end example

@node 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？,,__import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,模块<3>
@anchor{faq/programming when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen}@anchor{44eb}
@subsubsection 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？


出于效率和一致性的原因，Python 仅在第一次导入模块时读取模块文件。否则，在一个多模块的程序中，每个模块都会导入相同的基础模块，那么基础模块将会被一而再、再而三地解析。如果要强行重新读取已更改的模块，请执行以下操作：

@example
import importlib
import modname
importlib.reload(modname)
@end example

警告：这种技术并非万无一失。尤其是模块包含了以下语句时：

@example
from modname import some_objects
@end example

仍将继续使用前一版的导入对象。如果模块包含了类的定义，并 @emph{不会} 用新的类定义更新现有的类实例。这样可能会导致以下矛盾的行为：

@example
>>> import importlib
>>> import cls
>>> c = cls.C()                # Create an instance of C
>>> importlib.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C)       # isinstance is false?!?
False
@end example

只要把类对象的 id 打印出来，问题的性质就会一目了然：

@example
>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'
@end example

@node 设计和历史常见问题,代码库和插件 FAQ,编程常见问题,Python 常见问题
@anchor{faq/design doc}@anchor{44ec}@anchor{faq/design design-and-history-faq}@anchor{44ed}
@section 设计和历史常见问题



@menu
* 为什么Python使用缩进来分组语句？:: 
* 为什么简单的算术运算得到奇怪的结果？:: 
* 为什么浮点计算不准确？:: 
* 为什么Python字符串是不可变的？:: 
* 为什么必须在方法定义和调用中显式使用“self”？:: 
* 为什么不能在表达式中赋值？:: 
* 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？. 
* 为什么 join()是一个字符串方法而不是列表或元组方法？: 为什么 join 是一个字符串方法而不是列表或元组方法？. 
* 异常有多快？:: 
* 为什么Python中没有switch或case语句？:: 
* 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？:: 
* 为什么lambda表达式不能包含语句？:: 
* 可以将Python编译为机器代码，C或其他语言吗？:: 
* Python如何管理内存？:: 
* 为什么CPython不使用更传统的垃圾回收方案？:: 
* CPython退出时为什么不释放所有内存？:: 
* 为什么有单独的元组和列表数据类型？:: 
* 列表是如何在CPython中实现的？:: 
* 字典是如何在CPython中实现的？:: 
* 为什么字典key必须是不可变的？:: 
* 为什么 list.sort() 没有返回排序列表？: 为什么 list sort 没有返回排序列表？. 
* 如何在Python中指定和实施接口规范？:: 
* 为什么没有goto？:: 
* 为什么原始字符串（r-strings）不能以反斜杠结尾？:: 
* 为什么Python没有属性赋值的“with”语句？:: 
* 生成器为什么不支持 with 语句？:: 
* 为什么 if/while/def/class语句需要冒号？:: 
* 为什么Python在列表和元组的末尾允许使用逗号？:: 

@end menu

@node 为什么Python使用缩进来分组语句？,为什么简单的算术运算得到奇怪的结果？,,设计和历史常见问题
@anchor{faq/design why-does-python-use-indentation-for-grouping-of-statements}@anchor{44ee}
@subsection 为什么Python使用缩进来分组语句？


Guido van Rossum 认为使用缩进进行分组非常优雅，并且大大提高了普通Python程序的清晰度。大多数人在一段时间后就学会并喜欢上这个功能。

由于没有开始/结束括号，因此解析器感知的分组与人类读者之间不会存在分歧。偶尔C程序员会遇到像这样的代码片段:

@example
if (x <= y)
        x++;
        y--;
z++;
@end example

如果条件为真，则只执行 @code{x++} 语句，但缩进会使你认为情况并非如此。 即使是经验丰富的 C 程序员有时也会长久地盯着它发呆，不明白为什么在 @code{x > y`@w{`}时 `@w{`}y} 也会减少。

因为没有开始/结束花括号，所以 Python 更不容易发生编码风格冲突。 在 C 中有许多不同的放置花括号的方式。 在习惯了阅读和编写某种特定风格的代码之后，当阅读（或被要求编写）另一种风格的代码时通常都会令人感觉有点不舒服）。

许多编码风格将开始/结束括号单独放在一行上。这使得程序相当长，浪费了宝贵的屏幕空间，使得更难以对程序进行全面的了解。理想情况下，函数应该适合一个屏幕（例如，20--30行）。 20行Python可以完成比20行C更多的工作。这不仅仅是由于缺少开始/结束括号 -- 缺少声明和高级数据类型也是其中的原因  -- 但缩进基于语法肯定有帮助。

@node 为什么简单的算术运算得到奇怪的结果？,为什么浮点计算不准确？,为什么Python使用缩进来分组语句？,设计和历史常见问题
@anchor{faq/design why-am-i-getting-strange-results-with-simple-arithmetic-operations}@anchor{44ef}
@subsection 为什么简单的算术运算得到奇怪的结果？


请看下一个问题。

@node 为什么浮点计算不准确？,为什么Python字符串是不可变的？,为什么简单的算术运算得到奇怪的结果？,设计和历史常见问题
@anchor{faq/design why-are-floating-point-calculations-so-inaccurate}@anchor{44f0}
@subsection 为什么浮点计算不准确？


用户经常对这样的结果感到惊讶:

@example
>>> 1.2 - 1.0
0.19999999999999996
@end example

并且认为这是 Python中的一个 bug。其实不是这样。这与 Python 关系不大，而与底层平台如何处理浮点数字关系更大。

CPython 中的 @ref{1fe,,float} 类型使用C语言的 @code{double} 类型进行存储。 @ref{1fe,,float} 对象的值是以固定的精度（通常为 53 位）存储的二进制浮点数，由于 Python 使用 C 操作，而后者依赖于处理器中的硬件实现来执行浮点运算。 这意味着就浮点运算而言，Python 的行为类似于许多流行的语言，包括 C 和 Java。

许多可以轻松地用十进制表示的数字不能用二进制浮点表示。例如，在输入以下语句后:

@example
>>> x = 1.2
@end example

为 @code{x} 存储的值是与十进制的值 @code{1.2} (非常接近) 的近似值，但不完全等于它。 在典型的机器上，实际存储的值是：

@example
1.0011001100110011001100110011001100110011001100110011 (binary)
@end example

它对应于十进制数值:

@example
1.1999999999999999555910790149937383830547332763671875 (decimal)
@end example

典型的 53 位精度为 Python 浮点数提供了 15-16 位小数的精度。

要获得更完整的解释，请参阅 Python 教程中的 @ref{1487,,浮点算术}  一章。

@node 为什么Python字符串是不可变的？,为什么必须在方法定义和调用中显式使用“self”？,为什么浮点计算不准确？,设计和历史常见问题
@anchor{faq/design why-are-python-strings-immutable}@anchor{44f1}
@subsection 为什么Python字符串是不可变的？


有几个优点。

一个是性能：知道字符串是不可变的，意味着我们可以在创建时为它分配空间，并且存储需求是固定不变的。这也是元组和列表之间区别的原因之一。

另一个优点是，Python 中的字符串被视为与数字一样“基本”。 任何动作都不会将值 8 更改为其他值，在 Python 中，任何动作都不会将字符串 "8" 更改为其他值。

@node 为什么必须在方法定义和调用中显式使用“self”？,为什么不能在表达式中赋值？,为什么Python字符串是不可变的？,设计和历史常见问题
@anchor{faq/design why-must-self-be-used-explicitly-in-method-definitions-and-calls}@anchor{44f2}@anchor{faq/design why-self}@anchor{44d9}
@subsection 为什么必须在方法定义和调用中显式使用“self”？


这个想法借鉴了 Modula-3 语言。 出于多种原因它被证明是非常有用的。

首先，更明显的显示出，使用的是方法或实例属性而不是局部变量。 阅读 @code{self.x} 或 @code{self.meth()} 可以清楚地表明，即使您不知道类的定义，也会使用实例变量或方法。在 C++ 中，可以通过缺少局部变量声明来判断（假设全局变量很少见或容易识别） —— 但是在 Python 中没有局部变量声明，所以必须查找类定义才能确定。 一些 C++ 和 Java 编码标准要求实例属性具有 @code{m_} 前缀，因此这种显式性在这些语言中仍然有用。

其次，这意味着如果要显式引用或从特定类调用该方法，不需要特殊语法。 在 C++ 中，如果你想使用在派生类中重写基类中的方法，你必须使用 @code{::} 运算符 -- 在 Python 中你可以编写 @code{baseclass.methodname(self, <argument list>)}。 这对于 @ref{e2b,,__init__()} 方法非常有用，特别是在派生类方法想要扩展同名的基类方法，而必须以某种方式调用基类方法时。

最后，它解决了变量赋值的语法问题：为了 Python 中的局部变量（根据定义！）在函数体中赋值的那些变量（并且没有明确声明为全局）赋值，就必须以某种方式告诉解释器一个赋值是为了分配一个实例变量而不是一个局部变量，它最好是通过语法实现的（出于效率原因）。 C++ 通过声明来做到这一点，但是 Python 没有声明，仅仅为了这个目的而引入它们会很可惜。 使用显式的 @code{self.var} 很好地解决了这个问题。 类似地，对于使用实例变量，必须编写 @code{self.var} 意味着对方法内部的非限定名称的引用不必搜索实例的目录。 换句话说，局部变量和实例变量存在于两个不同的命名空间中，您需要告诉 Python 使用哪个命名空间。

@node 为什么不能在表达式中赋值？,为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,为什么必须在方法定义和调用中显式使用“self”？,设计和历史常见问题
@anchor{faq/design id2}@anchor{44f3}@anchor{faq/design why-can-t-i-use-an-assignment-in-an-expression}@anchor{13db}
@subsection 为什么不能在表达式中赋值？


自 Python 3.8 开始，你能做到的！

赋值表达式使用海象运算符 @cite{:=} 在表达式中为变量赋值:

@example
while chunk := fp.read(200):
   print(chunk)
@end example

请参阅 
@geindex Python 提高建议; PEP 572
PEP 572@footnote{https://www.python.org/dev/peps/pep-0572} 了解详情。

@node 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,为什么 join 是一个字符串方法而不是列表或元组方法？,为什么不能在表达式中赋值？,设计和历史常见问题
@anchor{faq/design why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list}@anchor{44f4}
@subsection 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？


正如Guido所说：

@quotation

(a) 对于某些操作，前缀表示法比后缀更容易阅读 -- 前缀（和中缀！）运算在数学中有着悠久的传统，就像在视觉上帮助数学家思考问题的记法。比较一下我们将 x*(a+b) 这样的公式改写为 x*a+x*b 的容易程度，以及使用原始OO符号做相同事情的笨拙程度。

(b)  当读到写有len(X)的代码时，就知道它要求的是某件东西的长度。这告诉我们两件事：结果是一个整数，参数是某种容器。相反，当阅读x.len()时，必须已经知道x是某种实现接口的容器，或者是从具有标准len()的类继承的容器。当没有实现映射的类有get()或key()方法，或者不是文件的类有write()方法时，我们偶尔会感到困惑。


@center --- @indicateurl{https://mail.python.org/pipermail/python-3000/2006-November/004643.html}

@end quotation

@node 为什么 join 是一个字符串方法而不是列表或元组方法？,异常有多快？,为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,设计和历史常见问题
@anchor{faq/design why-is-join-a-string-method-instead-of-a-list-or-tuple-method}@anchor{44f5}
@subsection 为什么 join()是一个字符串方法而不是列表或元组方法？


从Python 1.6开始，字符串变得更像其他标准类型，当添加方法时，这些方法提供的功能与始终使用String模块的函数时提供的功能相同。这些新方法中的大多数已被广泛接受，但似乎让一些程序员感到不舒服的一种方法是：

@example
", ".join(['1', '2', '4', '8', '16'])
@end example

结果如下:

@example
"1, 2, 4, 8, 16"
@end example

反对这种用法有两个常见的论点。

第一条是这样的：“使用字符串文本(String Constant)的方法看起来真的很难看”，答案是也许吧，但是字符串文本只是一个固定值。如果在绑定到字符串的名称上允许使用这些方法，则没有逻辑上的理由使其在文字上不可用。

第二个异议通常是这样的：“我实际上是在告诉序列使用字符串常量将其成员连接在一起”。遗憾的是并非如此。出于某种原因，把 @ref{89a,,split()} 作为一个字符串方法似乎要容易得多，因为在这种情况下，很容易看到:

@example
"1, 2, 4, 8, 16".split(", ")
@end example

是对字符串文本的指令，用于返回由给定分隔符分隔的子字符串（或在默认情况下，返回任意空格）。

@ref{1796,,join()} 是字符串方法，因为在使用该方法时，您告诉分隔符字符串去迭代一个字符串序列，并在相邻元素之间插入自身。此方法的参数可以是任何遵循序列规则的对象，包括您自己定义的任何新的类。对于字节和字节数组对象也有类似的方法。

@node 异常有多快？,为什么Python中没有switch或case语句？,为什么 join 是一个字符串方法而不是列表或元组方法？,设计和历史常见问题
@anchor{faq/design how-fast-are-exceptions}@anchor{44f6}
@subsection 异常有多快？


如果没有引发异常，则try/except块的效率极高。实际上捕获异常是昂贵的。在2.0之前的Python版本中，通常使用这个习惯用法:

@example
try:
    value = mydict[key]
except KeyError:
    mydict[key] = getvalue(key)
    value = mydict[key]
@end example

只有当你期望dict在任何时候都有key时，这才有意义。如果不是这样的话，你就是应该这样编码：

@example
if key in mydict:
    value = mydict[key]
else:
    value = mydict[key] = getvalue(key)
@end example

对于这种特定的情况，您还可以使用 @code{value = dict.setdefault(key, getvalue(key))}，但前提是调用 @code{getvalue()} 足够便宜，因为在所有情况下都会对其进行评估。

@node 为什么Python中没有switch或case语句？,难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,异常有多快？,设计和历史常见问题
@anchor{faq/design why-isn-t-there-a-switch-or-case-statement-in-python}@anchor{44f7}
@subsection 为什么Python中没有switch或case语句？


你可以通过一系列 @code{if... elif... elif... else}.轻松完成这项工作。对于switch语句语法已经有了一些建议，但尚未就是否以及如何进行范围测试达成共识。有关完整的详细信息和当前状态，请参阅 
@geindex Python 提高建议; PEP 275
PEP 275@footnote{https://www.python.org/dev/peps/pep-0275} 。

对于需要从大量可能性中进行选择的情况，可以创建一个字典，将case 值映射到要调用的函数。例如：

@example
functions = @{'a': function_1,
             'b': function_2,
             'c': self.method_1@}

func = functions[value]
func()
@end example

对于对象调用方法，可以通过使用 @ref{554,,getattr()} 内置检索具有特定名称的方法来进一步简化：

@example
class MyVisitor:
    def visit_a(self):
        ...

    def dispatch(self, value):
        method_name = 'visit_' + str(value)
        method = getattr(self, method_name)
        method()
@end example

建议对方法名使用前缀，例如本例中的 @code{visit_} 。如果没有这样的前缀，如果值来自不受信任的源，攻击者将能够调用对象上的任何方法。

@node 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,为什么lambda表达式不能包含语句？,为什么Python中没有switch或case语句？,设计和历史常见问题
@anchor{faq/design can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation}@anchor{44f8}
@subsection 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？


答案1： 不幸的是，解释器为每个Python堆栈帧推送至少一个C堆栈帧。此外，扩展可以随时回调Python。因此，一个完整的线程实现需要对C的线程支持。

答案2： 幸运的是， Stackless Python@footnote{https://github.com/stackless-dev/stackless/wiki} 有一个完全重新设计的解释器循环，可以避免C堆栈。

@node 为什么lambda表达式不能包含语句？,可以将Python编译为机器代码，C或其他语言吗？,难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,设计和历史常见问题
@anchor{faq/design why-can-t-lambda-expressions-contain-statements}@anchor{44f9}
@subsection 为什么lambda表达式不能包含语句？


Python的 lambda表达式不能包含语句，因为Python的语法框架不能处理嵌套在表达式内部的语句。然而，在Python中，这并不是一个严重的问题。与其他语言中添加功能的lambda表单不同，Python的 lambdas只是一种速记符号，如果您懒得定义函数的话。

函数已经是Python中的第一类对象，可以在本地范围内声明。 因此，使用lambda而不是本地定义的函数的唯一优点是你不需要为函数创建一个名称 -- 这只是一个分配了函数对象(与lambda表达式生成的对象类型完全相同)的局部变量！

@node 可以将Python编译为机器代码，C或其他语言吗？,Python如何管理内存？,为什么lambda表达式不能包含语句？,设计和历史常见问题
@anchor{faq/design can-python-be-compiled-to-machine-code-c-or-some-other-language}@anchor{44fa}
@subsection 可以将Python编译为机器代码，C或其他语言吗？


Cython@footnote{http://cython.org/} 将带有可选注释的Python修改版本编译到C扩展中。 Nuitka@footnote{http://www.nuitka.net/} 是一个将Python编译成 C++ 代码的新兴编译器，旨在支持完整的Python语言。要编译成Java，可以考虑 VOC@footnote{https://voc.readthedocs.io} 。

@node Python如何管理内存？,为什么CPython不使用更传统的垃圾回收方案？,可以将Python编译为机器代码，C或其他语言吗？,设计和历史常见问题
@anchor{faq/design how-does-python-manage-memory}@anchor{44fb}
@subsection Python如何管理内存？


Python 内存管理的细节取决于实现。 Python 的标准实现 @ref{1598,,CPython} 使用引用计数来检测不可访问的对象，并使用另一种机制来收集引用循环，定期执行循环检测算法来查找不可访问的循环并删除所涉及的对象。 @ref{84,,gc} 模块提供了执行垃圾回收、获取调试统计信息和优化收集器参数的函数。

但是，其他实现(如  Jython@footnote{http://www.jython.org}  或  PyPy@footnote{http://www.pypy.org} )，)可以依赖不同的机制，如完全的垃圾回收器 。如果你的Python代码依赖于引用计数实现的行为，则这种差异可能会导致一些微妙的移植问题。

在一些Python实现中，以下代码（在CPython中工作的很好）可能会耗尽文件描述符:

@example
for file in very_long_list_of_files:
    f = open(file)
    c = f.read(1)
@end example

实际上，使用CPython的引用计数和析构函数方案， 每个新赋值的 @emph{f} 都会关闭前一个文件。然而，对于传统的GC，这些文件对象只能以不同的时间间隔（可能很长的时间间隔）被收集（和关闭）。

如果要编写可用于任何python实现的代码，则应显式关闭该文件或使用  @ref{7e4,,with} 语句；无论内存管理方案如何，这都有效：

@example
for file in very_long_list_of_files:
    with open(file) as f:
        c = f.read(1)
@end example

@node 为什么CPython不使用更传统的垃圾回收方案？,CPython退出时为什么不释放所有内存？,Python如何管理内存？,设计和历史常见问题
@anchor{faq/design why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme}@anchor{44fc}
@subsection 为什么CPython不使用更传统的垃圾回收方案？


首先，这不是C标准特性，因此不能移植。(是的，我们知道Boehm GC库。它包含了 @emph{大多数} 常见平台（但不是所有平台）的汇编代码，尽管它基本上是透明的，但也不是完全透明的; 要让Python使用它，需要使用补丁。)

当Python嵌入到其他应用程序中时，传统的GC也成为一个问题。在独立的Python中，可以用GC库提供的版本替换标准的malloc()和free()，嵌入Python的应用程序可能希望用 @emph{它自己} 替代malloc()和free()，而可能不需要Python的。现在，CPython可以正确地实现malloc()和free()。

@node CPython退出时为什么不释放所有内存？,为什么有单独的元组和列表数据类型？,为什么CPython不使用更传统的垃圾回收方案？,设计和历史常见问题
@anchor{faq/design why-isn-t-all-memory-freed-when-cpython-exits}@anchor{44fd}
@subsection CPython退出时为什么不释放所有内存？


当Python退出时，从全局命名空间或Python模块引用的对象并不总是被释放。 如果存在循环引用，则可能发生这种情况 C库分配的某些内存也是不可能释放的（例如像Purify这样的工具会抱怨这些内容）。 但是，Python在退出时清理内存并尝试销毁每个对象。

如果要强制 Python 在释放时删除某些内容，请使用 @ref{b,,atexit} 模块运行一个函数，强制删除这些内容。

@node 为什么有单独的元组和列表数据类型？,列表是如何在CPython中实现的？,CPython退出时为什么不释放所有内存？,设计和历史常见问题
@anchor{faq/design why-are-there-separate-tuple-and-list-data-types}@anchor{44fe}
@subsection 为什么有单独的元组和列表数据类型？


虽然列表和元组在许多方面是相似的，但它们的使用方式通常是完全不同的。可以认为元组类似于Pascal记录或C结构；它们是相关数据的小集合，可以是不同类型的数据，可以作为一个组进行操作。例如，笛卡尔坐标适当地表示为两个或三个数字的元组。

另一方面，列表更像其他语言中的数组。它们倾向于持有不同数量的对象，所有对象都具有相同的类型，并且逐个操作。例如， @code{os.listdir('.')} 返回表示当前目录中的文件的字符串列表。如果向目录中添加了一两个文件，对此输出进行操作的函数通常不会中断。

元组是不可变的，这意味着一旦创建了元组，就不能用新值替换它的任何元素。列表是可变的，这意味着您始终可以更改列表的元素。只有不变元素可以用作字典的key，因此只能将元组和非列表用作key。

@node 列表是如何在CPython中实现的？,字典是如何在CPython中实现的？,为什么有单独的元组和列表数据类型？,设计和历史常见问题
@anchor{faq/design how-are-lists-implemented-in-cpython}@anchor{44ff}
@subsection 列表是如何在CPython中实现的？


CPython的列表实际上是可变长度的数组，而不是lisp风格的链表。该实现使用对其他对象的引用的连续数组，并在列表头结构中保留指向该数组和数组长度的指针。

这使得索引列表 @code{a[i]} 的操作成本与列表的大小或索引的值无关。

当添加或插入项时，将调整引用数组的大小。并采用了一些巧妙的方法来提高重复添加项的性能; 当数组必须增长时，会分配一些额外的空间，以便在接下来的几次中不需要实际调整大小。

@node 字典是如何在CPython中实现的？,为什么字典key必须是不可变的？,列表是如何在CPython中实现的？,设计和历史常见问题
@anchor{faq/design how-are-dictionaries-implemented-in-cpython}@anchor{4500}
@subsection 字典是如何在CPython中实现的？


CPython的字典实现为可调整大小的哈希表。与B-树相比，这在大多数情况下为查找（目前最常见的操作）提供了更好的性能，并且实现更简单。

字典的工作方式是使用 @ref{aac,,hash()} 内置函数计算字典中存储的每个键的hash代码。hash代码根据键和每个进程的种子而变化很大；例如，"Python" 的hash值为-539294296，而"python"(一个按位不同的字符串)的hash值为1142331976。然后，hash代码用于计算内部数组中将存储该值的位置。假设您存储的键都具有不同的hash值，这意味着字典需要恒定的时间 -- O(1)，用Big-O表示法 -- 来检索一个键。

@node 为什么字典key必须是不可变的？,为什么 list sort 没有返回排序列表？,字典是如何在CPython中实现的？,设计和历史常见问题
@anchor{faq/design why-must-dictionary-keys-be-immutable}@anchor{4501}
@subsection 为什么字典key必须是不可变的？


字典的哈希表实现使用从键值计算的哈希值来查找键。如果键是可变对象，则其值可能会发生变化，因此其哈希值也会发生变化。但是，由于无论谁更改键对象都无法判断它是否被用作字典键值，因此无法在字典中修改条目。然后，当你尝试在字典中查找相同的对象时，将无法找到它，因为其哈希值不同。如果你尝试查找旧值，也不会找到它，因为在该哈希表中找到的对象的值会有所不同。

如果你想要一个用列表索引的字典，只需先将列表转换为元组；用函数 @code{tuple(L)} 创建一个元组，其条目与列表 @code{L} 相同。 元组是不可变的，因此可以用作字典键。

已经提出的一些不可接受的解决方案：


@itemize -

@item 
哈希按其地址（对象ID）列出。这不起作用，因为如果你构造一个具有相同值的新列表，它将无法找到；例如:

@example
mydict = @{[1, 2]: '12'@}
print(mydict[[1, 2]])
@end example

会引发一个 @ref{3f1,,KeyError} 异常，因为第二行中使用的 @code{[1, 2]} 的 id 与第一行中的 id 不同。换句话说，应该使用 @code{==} 来比较字典键，而不是使用 @ref{1580,,is} 。

@item 
使用列表作为键时进行复制。这没有用的，因为作为可变对象的列表可以包含对自身的引用，然后复制代码将进入无限循环。

@item 
允许列表作为键，但告诉用户不要修改它们。当你意外忘记或修改列表时，这将产生程序中的一类难以跟踪的错误。它还使一个重要的字典不变量无效： @code{d.keys()} 中的每个值都可用作字典的键。

@item 
将列表用作字典键后，应标记为其只读。问题是，它不仅仅是可以改变其值的顶级对象；你可以使用包含列表作为键的元组。将任何内容作为键关联到字典中都需要将从那里可到达的所有对象标记为只读 —— 并且自引用对象可能会导致无限循环。
@end itemize

如果需要，可以使用以下方法来解决这个问题，但使用它需要你自担风险：你可以将一个可变结构包装在一个类实例中，该实例同时具有 @ref{454,,__eq__()} 和 @ref{455,,__hash__()} 方法。然后，你必须确保驻留在字典（或其他基于 hash 的结构）中的所有此类包装器对象的哈希值在对象位于字典（或其他结构）中时保持固定。:

@example
class ListWrapper:
    def __init__(self, the_list):
        self.the_list = the_list

    def __eq__(self, other):
        return self.the_list == other.the_list

    def __hash__(self):
        l = self.the_list
        result = 98767 - len(l)*555
        for i, el in enumerate(l):
            try:
                result = result + (hash(el) % 9999999) * 1001 + i
            except Exception:
                result = (result % 7777777) + i * 333
        return result
@end example

注意，哈希计算由于列表的某些成员可能不可用以及算术溢出的可能性而变得复杂。

此外，必须始终如此，如果 @code{o1 == o2} （即 @code{o1.__eq__(o2) is True} ）则 @code{hash(o1) == hash(o2)`@w{`}（即 `@w{`}o1.__hash__() == o2.__hash__()} ），无论对象是否在字典中。 如果你不能满足这些限制，字典和其他基于 hash 的结构将会出错。

对于 ListWrapper ，只要包装器对象在字典中，包装列表就不能更改以避免异常。除非你准备好认真考虑需求以及不正确地满足这些需求的后果，否则不要这样做。请留意。

@node 为什么 list sort 没有返回排序列表？,如何在Python中指定和实施接口规范？,为什么字典key必须是不可变的？,设计和历史常见问题
@anchor{faq/design why-doesn-t-list-sort-return-the-sorted-list}@anchor{4502}
@subsection 为什么 list.sort() 没有返回排序列表？


在性能很重要的情况下，仅仅为了排序而复制一份列表将是一种浪费。因此， @ref{550,,list.sort()} 对列表进行了适当的排序。为了提醒您这一事实，它不会返回已排序的列表。这样，当您需要排序的副本，但也需要保留未排序的版本时，就不会意外地覆盖列表。

如果要返回新列表，请使用内置 @ref{54f,,sorted()} 函数。此函数从提供的可迭代列表中创建新列表，对其进行排序并返回。例如，下面是如何迭代遍历字典并按keys排序:

@example
for key in sorted(mydict):
    ...  # do whatever with mydict[key]...
@end example

@node 如何在Python中指定和实施接口规范？,为什么没有goto？,为什么 list sort 没有返回排序列表？,设计和历史常见问题
@anchor{faq/design how-do-you-specify-and-enforce-an-interface-spec-in-python}@anchor{4503}
@subsection 如何在Python中指定和实施接口规范？


由C++和Java等语言提供的模块接口规范描述了模块的方法和函数的原型。许多人认为接口规范的编译时强制执行有助于构建大型程序。

Python 2.6添加了一个 @ref{3,,abc} 模块，允许定义抽象基类 (ABCs)。然后可以使用 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 来检查实例或类是否实现了特定的ABC。 @ref{1e,,collections.abc} 模块定义了一组有用的ABCs 例如 @ref{1849,,Iterable} ， @ref{184b,,Container} , 和 @ref{ad7,,MutableMapping}

对于 Python，接口规范的许多好处可以通过组件的适当测试规程来获得。

一个好的模块测试套件既可以提供回归测试，也可以作为模块接口规范和一组示例。许多Python模块可以作为脚本运行，以提供简单的“自我测试”。即使是使用复杂外部接口的模块，也常常可以使用外部接口的简单“桩代码（stub）”模拟进行隔离测试。可以使用 @ref{66,,doctest} 和 @ref{124,,unittest} 模块或第三方测试框架来构造详尽的测试套件，以运行模块中的每一行代码。

适当的测试规程可以帮助在Python中构建大型的、复杂的应用程序以及接口规范。事实上，它可能会更好，因为接口规范不能测试程序的某些属性。例如， @code{append()} 方法将向一些内部列表的末尾添加新元素；接口规范不能测试您的 @code{append()} 实现是否能够正确执行此操作，但是在测试套件中检查这个属性是很简单的。

编写测试套件非常有用，并且你可能希望将你的代码设计为易于测试。 一种日益流行的技术是面向测试的开发，它要求在编写任何实际代码之前首先编写测试套件的各个部分。 当然 Python 也允许你采用更粗率的方式，不必编写任何测试用例。

@node 为什么没有goto？,为什么原始字符串（r-strings）不能以反斜杠结尾？,如何在Python中指定和实施接口规范？,设计和历史常见问题
@anchor{faq/design why-is-there-no-goto}@anchor{4504}
@subsection 为什么没有goto？


在 1970 年代人们了解到不受限制的 goto 可能导致混乱得像“意大利面”那样难以理解和修改的代码。 在高级语言中，它也是不必要的，只需有实现分支 (在 Python 中是使用 @code{if} 语句以及 @code{or}, @code{and} 和 @code{if-else} 表达式) 和循环 (使用 @code{while} 和 @code{for} 语句，并可能包含 @code{continue} 和 @code{break}) 的手段就足够了。

人们还可以使用异常捕获来提供甚至能跨函数调用的“结构化 goto”。 许多人认为异常可以方便地模拟 C, Fortran 和其他语言中所有合理使用的“go”或“goto”构造。 例如:

@example
class label(Exception): pass  # declare a label

try:
    ...
    if condition: raise label()  # goto label
    ...
except label:  # where to goto
    pass
...
@end example

但是不允许你跳到循环的中间，这通常被认为是滥用goto。谨慎使用。

@node 为什么原始字符串（r-strings）不能以反斜杠结尾？,为什么Python没有属性赋值的“with”语句？,为什么没有goto？,设计和历史常见问题
@anchor{faq/design why-can-t-raw-strings-r-strings-end-with-a-backslash}@anchor{4505}
@subsection 为什么原始字符串（r-strings）不能以反斜杠结尾？


更准确地说，它们不能以奇数个反斜杠结束：结尾处的不成对反斜杠会转义结束引号字符，留下未结束的字符串。

原始字符串的设计是为了方便想要执行自己的反斜杠转义处理的处理器(主要是正则表达式引擎)创建输入。此类处理器将不匹配的尾随反斜杠视为错误，因此原始字符串不允许这样做。反过来，允许通过使用引号字符转义反斜杠转义字符串。当r-string用于它们的预期目的时，这些规则工作的很好。

如果您正在尝试构建Windows路径名，请注意所有Windows系统调用都使用正斜杠:

@example
f = open("/mydir/file.txt")  # works fine!
@end example

如果您正在尝试为DOS命令构建路径名，请尝试以下示例

@example
dir = r"\this\is\my\dos\dir" "\\"
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"
@end example

@node 为什么Python没有属性赋值的“with”语句？,生成器为什么不支持 with 语句？,为什么原始字符串（r-strings）不能以反斜杠结尾？,设计和历史常见问题
@anchor{faq/design why-doesn-t-python-have-a-with-statement-for-attribute-assignments}@anchor{4506}
@subsection 为什么Python没有属性赋值的“with”语句？


Python 具有 'with' 语句，它能将一个代码块的执行包装起来，在进入和退出代码块时调用特定的代码。 有些语言具有这样的结构:

@example
with obj:
    a = 1               # equivalent to obj.a = 1
    total = total + 1   # obj.total = obj.total + 1
@end example

在Python中，这样的结构是不明确的。

其他语言，如ObjectPascal、Delphi和C++ 使用静态类型，因此可以毫不含糊地知道分配给什么成员。这是静态类型的要点 -- 编译器 @emph{总是} 在编译时知道每个变量的作用域。

Python使用动态类型。事先不可能知道在运行时引用哪个属性。可以动态地在对象中添加或删除成员属性。这使得无法通过简单的阅读就知道引用的是什么属性：局部属性、全局属性还是成员属性？

例如，采用以下不完整的代码段:

@example
def foo(a):
    with a:
        print(x)
@end example

该代码段假设 "a" 必须有一个名为 "x" 的成员属性。然而，Python中并没有告诉解释器这一点。假设 "a" 是整数，会发生什么？如果有一个名为 "x" 的全局变量，它是否会在with块中使用？如您所见，Python的动态特性使得这样的选择更加困难。

然而，Python 可以通过赋值轻松实现 "with" 和类似语言特性（减少代码量）的主要好处。代替:

@example
function(args).mydict[index][index].a = 21
function(args).mydict[index][index].b = 42
function(args).mydict[index][index].c = 63
@end example

写成这样:

@example
ref = function(args).mydict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63
@end example

这也具有提高执行速度的副作用，因为Python在运行时解析名称绑定，而第二个版本只需要执行一次解析。

@node 生成器为什么不支持 with 语句？,为什么 if/while/def/class语句需要冒号？,为什么Python没有属性赋值的“with”语句？,设计和历史常见问题
@anchor{faq/design why-don-t-generators-support-the-with-statement}@anchor{4507}
@subsection 生成器为什么不支持 with 语句？


由于技术原因，直接作为上下文管理器使用的生成器将无法正常工作。最常见的情况是，当生成器被用作迭代器运行到完成时，不需要手动关闭。如果需要，在 'with' 语句中把它包装成 "contextlib.closing(generator)" 。

@node 为什么 if/while/def/class语句需要冒号？,为什么Python在列表和元组的末尾允许使用逗号？,生成器为什么不支持 with 语句？,设计和历史常见问题
@anchor{faq/design why-are-colons-required-for-the-if-while-def-class-statements}@anchor{4508}
@subsection 为什么 if/while/def/class语句需要冒号？


冒号主要用于增强可读性(ABC语言实验的结果之一)。考虑一下这个:

@example
if a == b
    print(a)
@end example

与

@example
if a == b:
    print(a)
@end example

注意第二种方法稍微容易一些。请进一步注意，在这个FAQ解答的示例中，冒号是如何设置的；这是英语中的标准用法。

另一个次要原因是冒号使带有语法突出显示的编辑器更容易工作；他们可以寻找冒号来决定何时需要增加缩进，而不必对程序文本进行更精细的解析。

@node 为什么Python在列表和元组的末尾允许使用逗号？,,为什么 if/while/def/class语句需要冒号？,设计和历史常见问题
@anchor{faq/design why-does-python-allow-commas-at-the-end-of-lists-and-tuples}@anchor{4509}
@subsection 为什么Python在列表和元组的末尾允许使用逗号？


Python 允许您在列表，元组和字典的末尾添加一个尾随逗号:

@example
[1, 2, 3,]
('a', 'b', 'c',)
d = @{
    "A": [1, 5],
    "B": [6, 7],  # last trailing comma is optional but good style
@}
@end example

有几个理由允许这样做。

如果列表，元组或字典的字面值分布在多行中，则更容易添加更多元素，因为不必记住在上一行中添加逗号。这些行也可以重新排序，而不会产生语法错误。

不小心省略逗号会导致难以诊断的错误。例如:

@example
x = [
  "fee",
  "fie"
  "foo",
  "fum"
]
@end example

这个列表看起来有四个元素，但实际上包含三个 : "fee", "fiefoo" 和 "fum" 。总是加上逗号可以避免这个错误的来源。

允许尾随逗号也可以使编程代码更容易生成。

@node 代码库和插件 FAQ,扩展/嵌入常见问题,设计和历史常见问题,Python 常见问题
@anchor{faq/library doc}@anchor{450a}@anchor{faq/library library-and-extension-faq}@anchor{450b}
@section 代码库和插件 FAQ



@menu
* 通用的代码库问题:: 
* 通用任务:: 
* 线程相关:: 
* 输入输出:: 
* 网络 / Internet 编程:: 
* 数据库:: 
* 数学和数字:: 

@end menu

@node 通用的代码库问题,通用任务,,代码库和插件 FAQ
@anchor{faq/library general-library-questions}@anchor{450c}
@subsection 通用的代码库问题


@menu
* 如何找到可以用来做 XXX 的模块或应用？:: 
* math.py（socket.py，regex.py 等）的源文件在哪？: math py（socket py，regex py 等）的源文件在哪？. 
* 在 Unix 中怎样让 Python 脚本可执行？:: 
* Python 中有 curses/termcap 包吗？:: 
* Python 中存在类似 C 的 onexit() 函数的东西吗？: Python 中存在类似 C 的 onexit 函数的东西吗？. 
* 为什么我的信号处理函数不能工作？:: 

@end menu

@node 如何找到可以用来做 XXX 的模块或应用？,math py（socket py，regex py 等）的源文件在哪？,,通用的代码库问题
@anchor{faq/library how-do-i-find-a-module-or-application-to-perform-task-x}@anchor{450d}
@subsubsection 如何找到可以用来做 XXX 的模块或应用？


在 @ref{135f,,代码库参考} 中查找是否有适合的标准库模块。（如果你已经了解标准库的内容，可以跳过这一步）

对于第三方软件包，请搜索 Python Package Index@footnote{https://pypi.org} 或是 Google@footnote{https://www.google.com} 等其他搜索引擎。用“Python”加上一两个你需要的关键字通常会找到有用的东西。

@node math py（socket py，regex py 等）的源文件在哪？,在 Unix 中怎样让 Python 脚本可执行？,如何找到可以用来做 XXX 的模块或应用？,通用的代码库问题
@anchor{faq/library where-is-the-math-py-socket-py-regex-py-etc-source-file}@anchor{450e}
@subsubsection math.py（socket.py，regex.py 等）的源文件在哪？


如果找不到模块的源文件，可能它是一个内建的模块，或是使用 C，C++ 或其他编译型语言实现的动态加载模块。这种情况下可能是没有源码文件的，类似 @code{mathmodule.c} 这样的文件会存放在 C 代码目录中（但不在 Python 目录中）。

Python 中（至少）有三类模块：


@enumerate 

@item 
使用 Python 编写的模块（.py)；

@item 
使用 C 编写的动态加载模块（.dll，.pyd，.so，.sl 等）；

@item 
使用 C 编写并链接到解释器的模块，要获取此列表，输入：

@example
import sys
print(sys.builtin_module_names)
@end example
@end enumerate

@node 在 Unix 中怎样让 Python 脚本可执行？,Python 中有 curses/termcap 包吗？,math py（socket py，regex py 等）的源文件在哪？,通用的代码库问题
@anchor{faq/library how-do-i-make-a-python-script-executable-on-unix}@anchor{450f}
@subsubsection 在 Unix 中怎样让 Python 脚本可执行？


你需要做两件事：文件必须是可执行的，并且第一行需要以 @code{#!} 开头，后面跟上 Python 解释器的路径。

第一点可以用执行 @code{chmod +x scriptfile} 或是 @code{chmod 755 scriptfile} 做到。

第二点有很多种做法，最直接的方式是：

@example
#!/usr/local/bin/python
@end example

在文件第一行，使用你所在平台上的 Python 解释器的路径。

如果你希望脚本不依赖 Python 解释器的具体路径，你也可以使用 @code{env} 程序。假设你的 Python 解释器所在目录已经添加到了 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量中，几乎所有的类 Unix 系统都支持下面的写法：

@example
#!/usr/bin/env python
@end example

@emph{不要} 在 CGI 脚本中这样做。CGI 脚本的 
@geindex PATH
@geindex 环境变量; PATH
@code{PATH} 环境变量通常会非常精简，所以你必须使用解释器的完整绝对路径。

有时候，用户的环境变量如果太长，可能会导致 @code{/usr/bin/env} 执行失败；又或者甚至根本就不存在 env 程序。在这种情况下，你可以尝试使用下面的 hack 方法（来自 Alex Rezinsky）：

@example
#! /bin/sh
""":"
exec python $0 $@{1+"$@@"@}
"""
@end example

这样做有一个小小的缺点，它会定义脚本的 __doc__ 字符串。不过可以这样修复：

@example
__doc__ = """...Whatever..."""
@end example

@node Python 中有 curses/termcap 包吗？,Python 中存在类似 C 的 onexit 函数的东西吗？,在 Unix 中怎样让 Python 脚本可执行？,通用的代码库问题
@anchor{faq/library is-there-a-curses-termcap-package-for-python}@anchor{4510}
@subsubsection Python 中有 curses/termcap 包吗？


@c XXX curses *is* built by default, isn't it?

对于类 Unix 系统：标准 Python 源码发行版会在 Modules@footnote{https://github.com/python/cpython/tree/3.9/Modules} 子目录中附带 curses 模块，但默认并不会编译。（注意：在 Windows 平台下不可用 —— Windows 中没有 curses 模块。）

@ref{2b,,curses} 模块支持基本的 curses 特性，同时也支持 ncurses 和 SYSV curses 中的很多额外功能，比如颜色、不同的字符集支持、填充和鼠标支持。这意味着这个模块不兼容只有 BSD curses 模块的操作系统，但是目前仍在维护的系统应该都不会存在这种情况。

@node Python 中存在类似 C 的 onexit 函数的东西吗？,为什么我的信号处理函数不能工作？,Python 中有 curses/termcap 包吗？,通用的代码库问题
@anchor{faq/library is-there-an-equivalent-to-c-s-onexit-in-python}@anchor{4511}
@subsubsection Python 中存在类似 C 的 onexit() 函数的东西吗？


@ref{b,,atexit} 模块提供了一个与 C 的 @code{onexit()} 函数类似的注册函数。

@node 为什么我的信号处理函数不能工作？,,Python 中存在类似 C 的 onexit 函数的东西吗？,通用的代码库问题
@anchor{faq/library why-don-t-my-signal-handlers-work}@anchor{4512}
@subsubsection 为什么我的信号处理函数不能工作？


最常见的问题是信号处理函数没有正确定义参数列表。它会被这样调用：

@example
handler(signum, frame)
@end example

因此它应当声明为带有两个形参:

@example
def handler(signum, frame):
    ...
@end example

@node 通用任务,线程相关,通用的代码库问题,代码库和插件 FAQ
@anchor{faq/library common-tasks}@anchor{4513}
@subsection 通用任务


@menu
* 怎样测试 Python 程序或组件？:: 
* 怎样用 docstring 创建文档？:: 
* 怎样一次只获取一个按键？:: 

@end menu

@node 怎样测试 Python 程序或组件？,怎样用 docstring 创建文档？,,通用任务
@anchor{faq/library how-do-i-test-a-python-program-or-component}@anchor{4514}
@subsubsection 怎样测试 Python 程序或组件？


Python 带有两个测试框架。@ref{66,,doctest} 模块从模块的 docstring 中寻找示例并执行，对比输出是否与 docstring 中给出的是否一致。

@ref{124,,unittest} 模块是一个模仿 Java 和 Smalltalk 测试框架的更棒的测试框架。

为了使测试更容易，你应该在程序中使用良好的模块化设计。程序中的绝大多数功能都应该用函数或类方法封装 —— 有时这样做会有额外惊喜，程序会运行得更快（因为局部变量比全局变量访问要快）。除此之外，程序应该避免依赖可变的局部变量，这会使得测试困难许多。

程序的“全局主逻辑”应该尽量简单：

@example
if __name__ == "__main__":
    main_logic()
@end example

并放置在程序主模块的最后面。

一旦你的程序已经组织为一个函数和类行为的有完整集合，你就应该编写测试函数来检测这些行为。 可以将自动执行一系列测试的测试集关联到每个模块。 这听起来似乎需要大量的工作，但是由于 Python 是如此简洁灵活因此它会极其容易。 你可以通过与“生产代码”同步编写测试函数使编程更为愉快和有趣，因为这将更容易并更早发现代码问题甚至设计缺陷。

程序主模块之外的其他“辅助模块”中可以增加自测试的入口。

@example
if __name__ == "__main__":
    self_test()
@end example

通过使用 Python 实现的“假”接口，即使是需要与复杂的外部接口交互的程序也可以在外部接口不可用时进行测试。

@node 怎样用 docstring 创建文档？,怎样一次只获取一个按键？,怎样测试 Python 程序或组件？,通用任务
@anchor{faq/library how-do-i-create-documentation-from-doc-strings}@anchor{4515}
@subsubsection 怎样用 docstring 创建文档？


@ref{d9,,pydoc} 模块可以用 Python 源码中的 docstring 创建 HTML 文件。也可以使用 epydoc@footnote{http://epydoc.sourceforge.net/} 来只通过 docstring 创建 API 文档。Sphinx@footnote{http://sphinx-doc.org} 也可以引入 docstring 的内容。

@node 怎样一次只获取一个按键？,,怎样用 docstring 创建文档？,通用任务
@anchor{faq/library how-do-i-get-a-single-keypress-at-a-time}@anchor{4516}
@subsubsection 怎样一次只获取一个按键？


在类 Unix 系统中有多种方案。最直接的方法是使用 curses，但是 curses 模块太大了，难以学习。

@c XXX this doesn't work out of the box, some IO expert needs to check why
@c 
@c Here's a solution without curses::
@c 
@c import termios, fcntl, sys, os
@c fd = sys.stdin.fileno()
@c 
@c oldterm = termios.tcgetattr(fd)
@c newattr = termios.tcgetattr(fd)
@c newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
@c termios.tcsetattr(fd, termios.TCSANOW, newattr)
@c 
@c oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
@c fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
@c 
@c try:
@c     while True:
@c         try:
@c             c = sys.stdin.read(1)
@c             print("Got character", repr(c))
@c         except OSError:
@c             pass
@c finally:
@c     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
@c     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
@c 
@c You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
@c work, and I've only tried it on Linux, though it should work elsewhere.  In
@c this code, characters are read and printed one at a time.
@c 
@c :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
@c mode.  :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
@c and modify them for non-blocking mode.  Since reading stdin when it is empty
@c results in an :exc:`OSError`, this error is caught and ignored.
@c 
@c .. versionchanged:: 3.3
@c    *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
@c    :exc:`IOError` is alias for :exc:`OSError`.

@node 线程相关,输入输出,通用任务,代码库和插件 FAQ
@anchor{faq/library threads}@anchor{4517}
@subsection 线程相关


@menu
* 程序中怎样使用线程？:: 
* 我的线程都没有运行，为什么？:: 
* 如何将任务分配给多个工作线程？:: 
* 怎样修改全局变量是线程安全的？:: 
* 不能删除全局解释器锁吗？:: 

@end menu

@node 程序中怎样使用线程？,我的线程都没有运行，为什么？,,线程相关
@anchor{faq/library how-do-i-program-using-threads}@anchor{4518}
@subsubsection 程序中怎样使用线程？


一定要使用 @ref{10b,,threading} 模块，不要使用 @ref{2,,_thread} 模块。@ref{10b,,threading} 模块对 @ref{2,,_thread} 模块提供的底层线程原语做了更易用的抽象。

@node 我的线程都没有运行，为什么？,如何将任务分配给多个工作线程？,程序中怎样使用线程？,线程相关
@anchor{faq/library none-of-my-threads-seem-to-run-why}@anchor{4519}
@subsubsection 我的线程都没有运行，为什么？


一旦主线程退出，所有的子线程都会被杀掉。你的主线程运行得太快了，子线程还没来得及工作。

简单的解决方法是在程序中加一个时间足够长的 sleep，让子线程能够完成运行。

@example
import threading, time

def thread_task(name, n):
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)  # <---------------------------!
@end example

但目前（在许多平台上）线程不是并行运行的，而是按顺序依次执行！原因是系统线程调度器在前一个线程阻塞之前不会启动新线程。

简单的解决方法是在运行函数的开始处加一个时间很短的 sleep。

@example
def thread_task(name, n):
    time.sleep(0.001)  # <--------------------!
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)
@end example

比起用 @ref{77d,,time.sleep()} 猜一个合适的等待时间，使用信号量机制会更好些。有一个办法是使用 @ref{da,,queue} 模块创建一个 queue 对象，让每一个线程在运行结束时 append 一个令牌到 queue 对象中，主线程中从 queue 对象中读取与线程数量一致的令牌数量即可。

@node 如何将任务分配给多个工作线程？,怎样修改全局变量是线程安全的？,我的线程都没有运行，为什么？,线程相关
@anchor{faq/library how-do-i-parcel-out-work-among-a-bunch-of-worker-threads}@anchor{451a}
@subsubsection 如何将任务分配给多个工作线程？


最简单的方式是使用 @ref{21,,concurrent.futures} 模块，特别是其中的 @ref{18c,,ThreadPoolExecutor} 类。

或者，如果你想更好地控制分发算法，你也可以自己写逻辑实现。使用 @ref{da,,queue} 模块来创建任务列表队列。@ref{de6,,Queue} 类维护一个了一个存有对象的列表，提供了 @code{.put(obj)} 方法添加元素，并且可以用 @code{.get()} 方法获取元素。这个类会使用必要的加锁操作，以此确保每个任务只会执行一次。

这是一个简单的例子：

@example
import threading, queue, time

# The worker thread gets jobs off the queue.  When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
    print('Running worker')
    time.sleep(0.1)
    while True:
        try:
            arg = q.get(block=False)
        except queue.Empty:
            print('Worker', threading.currentThread(), end=' ')
            print('queue empty')
            break
        else:
            print('Worker', threading.currentThread(), end=' ')
            print('running with argument', arg)
            time.sleep(0.5)

# Create queue
q = queue.Queue()

# Start a pool of 5 workers
for i in range(5):
    t = threading.Thread(target=worker, name='worker %i' % (i+1))
    t.start()

# Begin adding work to the queue
for i in range(50):
    q.put(i)

# Give threads time to run
print('Main thread sleeping')
time.sleep(5)
@end example

运行时会产生如下输出：

@example
Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
...
@end example

查看模块的文档以获取更多信息；@ref{de6,,Queue} 类提供了多种接口。

@node 怎样修改全局变量是线程安全的？,不能删除全局解释器锁吗？,如何将任务分配给多个工作线程？,线程相关
@anchor{faq/library what-kinds-of-global-value-mutation-are-thread-safe}@anchor{451b}
@subsubsection 怎样修改全局变量是线程安全的？


Python VM 内部会使用 @ref{60b,,global interpreter lock} （GIL）来确保同一时间只有一个线程运行。通常 Python 只会在字节码指令之间切换线程；切换的频率可以通过设置 @ref{219,,sys.setswitchinterval()} 指定。从 Python 程序的角度来看，每一条字节码指令以及每一条指令对应的 C 代码实现都是原子的。

理论上说，具体的结果要看具体的 PVM 字节码实现对指令的解释。而实际上，对内建类型（int，list，dict 等）的共享变量的“类原子”操作都是原子的。

举例来说，下面的操作是原子的（L、L1、L2 是列表，D、D1、D2 是字典，x、y 是对象，i，j 是 int 变量）：

@example
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
@end example

这些不是原子的：

@example
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
@end example

覆盖其他对象的操作会在其他对象的引用计数变成 0 时触发其 @ref{a0d,,__del__()} 方法，这可能会产生一些影响。对字典和列表进行大量操作时尤其如此。如果有疑问的话，使用互斥锁！

@node 不能删除全局解释器锁吗？,,怎样修改全局变量是线程安全的？,线程相关
@anchor{faq/library can-t-we-get-rid-of-the-global-interpreter-lock}@anchor{451c}
@subsubsection 不能删除全局解释器锁吗？


@c XXX link to dbeazley's talk about GIL?

@ref{60b,,global interpreter lock} （GIL）通常被视为 Python 在高端多核服务器上开发时的阻力，因为（几乎）所有 Python 代码只有在获取到 GIL 时才能运行，所以多线程的 Python 程序只能有效地使用一个 CPU。

在 Python 1.5 时代，Greg Stein 开发了一个完整的补丁包（“free threadings” 补丁），移除了 GIL，并用粒度更合适的锁来代替。Adam Olsen 最近也在他的 python-safethread@footnote{https://code.google.com/archive/p/python-safethread} 项目里做了类似的实验。不幸的是，由于为了移除 GIL 而使用了大量细粒度的锁，这两个实验在单线程测试中的性能都有明显的下降（至少慢 30%）。

但这并意味着你不能在多核机器上很好地使用 Python！你只需将任务划分为多*进程*，而不是多*线程*。新的 @ref{21,,concurrent.futures} 模块中的 @ref{196,,ProcessPoolExecutor} 类提供了一个简单的方法；如果你想对任务分发做更多控制，可以使用 @ref{b7,,multiprocessing} 模块提供的底层 API。

恰当地使用 C 拓展也很有用；使用 C 拓展处理耗时较久的任务时，拓展可以在线程执行 C 代码时释放 GIL，让其他线程执行。@ref{14d,,zlib} 和 @ref{8c,,hashlib} 等标准库模块已经这样做了。

也有建议说 GIL 应该是解释器状态锁，而不是完全的全局锁；解释器不应该共享对象。不幸的是，这也不可能发生。由于目前许多对象的实现都有全局的状态，因此这是一个艰巨的工作。举例来说，小整型数和短字符串会缓存起来，这些缓存将不得不移动到解释器状态中。其他对象类型都有自己的自由变量列表，这些自由变量列表也必须移动到解释器状态中。等等。

我甚至怀疑这些工作是否可能在有限的时间内完成，因为同样的问题在第三方拓展中也会存在。第三方拓展编写的速度可比你将它们转换为把全局状态存入解释器状态中的速度快得多。

最后，假设多个解释器不共享任何状态，那么这样做比每个进程一个解释器好在哪里呢？

@node 输入输出,网络 / Internet 编程,线程相关,代码库和插件 FAQ
@anchor{faq/library input-and-output}@anchor{451d}
@subsection 输入输出


@menu
* 怎样删除文件？（以及其他文件相关的问题……）:: 
* 怎样复制文件？:: 
* 怎样读取（或写入）二进制数据？:: 
* 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？. 
* 怎样访问（RS232）串口？:: 
* 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？. 

@end menu

@node 怎样删除文件？（以及其他文件相关的问题……）,怎样复制文件？,,输入输出
@anchor{faq/library how-do-i-delete-a-file-and-other-file-questions}@anchor{451e}
@subsubsection 怎样删除文件？（以及其他文件相关的问题……）


使用 @code{os.remove(filename)} 或 @code{os.unlink(filename)}。查看 @ref{c4,,os} 模块以获取更多文档。这两个函数是一样的，@ref{b21,,unlink()} 是这个函数在 Unix 系统调用中的名字。

如果要删除目录，应该使用 @ref{b1f,,os.rmdir()}；使用 @ref{b1b,,os.mkdir()} 创建目录。@code{os.makedirs(path)} 会创建 @code{path} 中任何不存在的目录。@code{os.removedirs(path)} 则会删除其中的目录，只要它们都是空的；如果你想删除整个目录以及其中的内容，可以使用 @ref{350,,shutil.rmtree()}。

重命名文件可以使用 @code{os.rename(old_path, new_path)}。

如果需要截断文件，使用 @code{f = open(filename, "rb+")} 打开文件，然后使用 @code{f.truncate(offset)}；offset 默认是当前的搜索位置。也可以对使用 @ref{762,,os.open()} 打开的文件使用 @code{os.ftruncate(fd, offset)}，其中 @emph{fd} 是文件描述符（一个小的整型数）。

@ref{e9,,shutil} 模块也包含了一些处理文件的函数，包括 @ref{389,,copyfile()}，@ref{34e,,copytree()} 和 @ref{350,,rmtree()}。

@node 怎样复制文件？,怎样读取（或写入）二进制数据？,怎样删除文件？（以及其他文件相关的问题……）,输入输出
@anchor{faq/library how-do-i-copy-a-file}@anchor{451f}
@subsubsection 怎样复制文件？


@ref{e9,,shutil} 模块有一个 @ref{389,,copyfile()} 函数。注意在 MacOS 9  中不会复制 resource fork 和 Finder info。

@node 怎样读取（或写入）二进制数据？,似乎 os popen 创建的管道不能使用 os read ，这是为什么？,怎样复制文件？,输入输出
@anchor{faq/library how-do-i-read-or-write-binary-data}@anchor{4520}
@subsubsection 怎样读取（或写入）二进制数据？


要读写复杂的二进制数据格式，最好使用 @ref{f8,,struct} 模块。该模块可以读取包含二进制数据（通常是数字）的字符串并转换为 Python 对象，反之亦然。

举例来说，下面的代码会从文件中以大端序格式读取一个 2 字节的整型和一个 4 字节的整型：

@example
import struct

with open(filename, "rb") as f:
    s = f.read(8)
    x, y, z = struct.unpack(">hhl", s)
@end example

格式字符串中的 ‘>’ 强制以大端序读取数据；字母 ‘h’ 从字符串中读取一个“短整型”（2 字节），字母 ‘l’ 读取一个“长整型”（4 字节）。

对于更常规的数据（例如整型或浮点类型的列表），你也可以使用 @ref{6,,array} 模块。

@cartouche
@quotation 注解 
要读写二进制数据的话，需要强制以二进制模式打开文件（这里为 @ref{16f,,open()} 函数传入 @code{"rb"}）。如果（默认）传入 @code{"r"} 的话，文件会以文本模式打开，@code{f.read()} 会返回 @ref{206,,str} 对象，而不是 @ref{172,,bytes} 对象。
@end quotation
@end cartouche

@node 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,怎样访问（RS232）串口？,怎样读取（或写入）二进制数据？,输入输出
@anchor{faq/library i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why}@anchor{4521}
@subsubsection 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？


@ref{765,,os.read()} 是一个底层函数，它接收的是文件描述符 —— 用小整型数表示的打开的文件。@ref{3d3,,os.popen()} 创建的是一个高级文件对象，和内建的 @ref{16f,,open()} 方法返回的类型一样。因此，如果要从 @ref{3d3,,os.popen()} 创建的管道 @emph{p} 中读取 @emph{n} 个字节的话，你应该使用 @code{p.read(n)}。

@c XXX update to use subprocess. See the :ref:`subprocess-replacements` section.
@c 
@c How do I run a subprocess with pipes connected to both input and output?
@c ------------------------------------------------------------------------
@c 
@c Use the :mod:`popen2` module.  For example::
@c 
@c    import popen2
@c    fromchild, tochild = popen2.popen2("command")
@c    tochild.write("input\n")
@c    tochild.flush()
@c    output = fromchild.readline()
@c 
@c Warning: in general it is unwise to do this because you can easily cause a
@c deadlock where your process is blocked waiting for output from the child
@c while the child is blocked waiting for input from you.  This can be caused
@c by the parent expecting the child to output more text than it does or
@c by data being stuck in stdio buffers due to lack of flushing.
@c The Python parent can of course explicitly flush the data it sends to the
@c child before it reads any output, but if the child is a naive C program it
@c may have been written to never explicitly flush its output, even if it is
@c interactive, since flushing is normally automatic.
@c 
@c Note that a deadlock is also possible if you use :func:`popen3` to read
@c stdout and stderr. If one of the two is too large for the internal buffer
@c (increasing the buffer size does not help) and you ``read()`` the other one
@c first, there is a deadlock, too.
@c 
@c Note on a bug in popen2: unless your program calls ``wait()`` or
@c ``waitpid()``, finished child processes are never removed, and eventually
@c calls to popen2 will fail because of a limit on the number of child
@c processes.  Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can
@c prevent this; a good place to insert such a call would be before calling
@c ``popen2`` again.
@c 
@c In many cases, all you really need is to run some data through a command and
@c get the result back.  Unless the amount of data is very large, the easiest
@c way to do this is to write it to a temporary file and run the command with
@c that temporary file as input.  The standard module :mod:`tempfile` exports a
@c :func:`~tempfile.mktemp` function to generate unique temporary file names. ::
@c 
@c    import tempfile
@c    import os
@c 
@c    class Popen3:
@c        """
@c        This is a deadlock-safe version of popen that returns
@c        an object with errorlevel, out (a string) and err (a string).
@c        (capturestderr may not work under windows.)
@c        Example: print(Popen3('grep spam','\n\nhere spam\n\n').out)
@c        """
@c        def __init__(self,command,input=None,capturestderr=None):
@c            outfile=tempfile.mktemp()
@c            command="( %s ) > %s" % (command,outfile)
@c            if input:
@c                infile=tempfile.mktemp()
@c                open(infile,"w").write(input)
@c                command=command+" <"+infile
@c            if capturestderr:
@c                errfile=tempfile.mktemp()
@c                command=command+" 2>"+errfile
@c            self.errorlevel=os.system(command) >> 8
@c            self.out=open(outfile,"r").read()
@c            os.remove(outfile)
@c            if input:
@c                os.remove(infile)
@c            if capturestderr:
@c                self.err=open(errfile,"r").read()
@c                os.remove(errfile)
@c 
@c Note that many interactive programs (e.g. vi) don't work well with pipes
@c substituted for standard input and output.  You will have to use pseudo ttys
@c ("ptys") instead of pipes. Or you can use a Python interface to Don Libes'
@c "expect" library.  A Python extension that interfaces to expect is called
@c "expy" and available from http://expectpy.sourceforge.net.  A pure Python
@c solution that works like expect is `pexpect
@c <https://pypi.org/project/pexpect/>`_.

@node 怎样访问（RS232）串口？,为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,似乎 os popen 创建的管道不能使用 os read ，这是为什么？,输入输出
@anchor{faq/library how-do-i-access-the-serial-rs232-port}@anchor{4522}
@subsubsection 怎样访问（RS232）串口？


对于 Win32, OSX, Linux, BSD, Jython, IronPython:

@quotation

@indicateurl{https://pypi.org/project/pyserial/}
@end quotation

对于 Unix，查看 Mitch Chapman 发布的帖子：

@quotation

@indicateurl{https://groups.google.com/groups?selm=34A04430.CF9@@ohioee.com}
@end quotation

@node 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,,怎样访问（RS232）串口？,输入输出
@anchor{faq/library why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it}@anchor{4523}
@subsubsection 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？


Python @ref{c1d,,文件对象} 是一个对底层 C 文件描述符的高层抽象。

对于在 Python 中通过内建的 @ref{16f,,open()} 函数创建的多数文件对象来说，@code{f.close()} 从 Python 的角度将其标记为已关闭，并且会关闭底层的 C 文件描述符。在 @code{f} 被垃圾回收的时候，析构函数中也会自动处理。

但由于 stdin，stdout 和 stderr 在 C 中的特殊地位，在 Python 中也会对它们做特殊处理。运行 @code{sys.stdout.close()} 会将 Python 的文件对象标记为已关闭，但是*不会*关闭与之关联的文件描述符。

要关闭这三者的 C 文件描述符的话，首先你应该确认确实需要关闭它（比如，这可能会影响到处理 I/O 的拓展）。如果确实需要这么做的话，使用 @ref{4e1,,os.close()}：

@example
os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())
@end example

或者也可以使用常量 0，1，2 代替。

@node 网络 / Internet 编程,数据库,输入输出,代码库和插件 FAQ
@anchor{faq/library network-internet-programming}@anchor{4524}
@subsection 网络 / Internet 编程


@menu
* Python 中的 WWW 工具是什么？:: 
* 怎样模拟发送 CGI 表单（METHOD=POST）？:: 
* 生成 HTML 需要使用什么模块？:: 
* 怎样使用 Python 脚本发送邮件？:: 
* socket 的 connect() 方法怎样避免阻塞？: socket 的 connect 方法怎样避免阻塞？. 

@end menu

@node Python 中的 WWW 工具是什么？,怎样模拟发送 CGI 表单（METHOD=POST）？,,网络 / Internet 编程
@anchor{faq/library what-www-tools-are-there-for-python}@anchor{4525}
@subsubsection Python 中的 WWW 工具是什么？


参阅代码库参考手册中 @ref{2cea,,互联网协议和支持} 和 @ref{2908,,互联网数据处理} 这两章的内容。Python 有大量模块来帮助你构建服务端和客户端 web 系统。

@c XXX check if wiki page is still up to date

Paul Boddie 维护了一份可用框架的概览，见 @indicateurl{https://wiki.python.org/moin/WebProgramming} 。

Cameron Laird 维护了一份关于 Python web 技术的实用网页的集合，见 @indicateurl{http://phaseit.net/claird/comp.lang.python/web_python} 。

@node 怎样模拟发送 CGI 表单（METHOD=POST）？,生成 HTML 需要使用什么模块？,Python 中的 WWW 工具是什么？,网络 / Internet 编程
@anchor{faq/library how-can-i-mimic-cgi-form-submission-method-post}@anchor{4526}
@subsubsection 怎样模拟发送 CGI 表单（METHOD=POST）？


我需要通过 POST 表单获取网页，有什么代码能简单做到吗？

是的。 这里是一个使用 @ref{129,,urllib.request} 的简单例子:

@example
#!/usr/local/bin/python

import urllib.request

# build the query string
qs = "First=Josephine&MI=Q&Last=Public"

# connect and send the server a path
req = urllib.request.urlopen('http://www.some-server.out-there'
                             '/cgi-bin/some-cgi-script', data=qs)
with req:
    msg, hdrs = req.read(), req.info()
@end example

注意，通常在百分号编码的 POST 操作中，查询字符串必须使用 @ref{884,,urllib.parse.urlencode()} 处理一下。举个例子，如果要发送 @code{name=Guy Steele, Jr.} 的话：

@example
>>> import urllib.parse
>>> urllib.parse.urlencode(@{'name': 'Guy Steele, Jr.'@})
'name=Guy+Steele%2C+Jr.'
@end example


@subsubheading 参见


查看 @ref{2daf,,如何利用 urllib 包获取网络资源} 获取更多示例。


@node 生成 HTML 需要使用什么模块？,怎样使用 Python 脚本发送邮件？,怎样模拟发送 CGI 表单（METHOD=POST）？,网络 / Internet 编程
@anchor{faq/library what-module-should-i-use-to-help-with-generating-html}@anchor{4527}
@subsubsection 生成 HTML 需要使用什么模块？


@c XXX add modern template languages

你可以在 Web 编程 wiki 页面@footnote{https://wiki.python.org/moin/WebProgramming} 找到许多有用的链接。

@node 怎样使用 Python 脚本发送邮件？,socket 的 connect 方法怎样避免阻塞？,生成 HTML 需要使用什么模块？,网络 / Internet 编程
@anchor{faq/library how-do-i-send-mail-from-a-python-script}@anchor{4528}
@subsubsection 怎样使用 Python 脚本发送邮件？


使用 @ref{ed,,smtplib} 标准库模块。

下面是一个很简单的交互式发送邮件的代码。这个方法适用于任何支持 SMTP 协议的主机。

@example
import sys, smtplib

fromaddr = input("From: ")
toaddrs  = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = '@w{'}
while True:
    line = sys.stdin.readline()
    if not line:
        break
    msg += line

# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
@end example

在 Unix 系统中还可以使用 sendmail。sendmail 程序的位置在不同系统中不一样，有时是在 @code{/usr/lib/sendmail}，有时是在 @code{/usr/sbin/sendmail}。sendmail 手册页面会对你有所帮助。以下是示例代码：

@example
import os

SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@@example.com\n")
p.write("Subject: test\n")
p.write("\n")  # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
    print("Sendmail exit status", sts)
@end example

@node socket 的 connect 方法怎样避免阻塞？,,怎样使用 Python 脚本发送邮件？,网络 / Internet 编程
@anchor{faq/library how-do-i-avoid-blocking-in-the-connect-method-of-a-socket}@anchor{4529}
@subsubsection socket 的 connect() 方法怎样避免阻塞？


通常会用 @ref{e5,,select} 模块处理 socket 异步 I/O。

要防止 TCP 连接发生阻塞，你可以将 socket 设为非阻塞模式。 这样当你执行 @code{socket.connect()} 时，你将或是立即完成连接（不大可能）或是收到一个包含 @code{.errno} 错误码的异常。 @code{errno.EINPROGRESS} 表示连接正在进行但还没有完成。 不同的操作系统将返回不同的值，因此你需要确认你的系统会返回什么值。

你可以使用 @code{socket.connect_ex()} 方法来避免生成异常。 它将只返回 errno 值。 要进行轮询，你可以稍后再次调用 @code{socket.connect_ex()} -- @code{0} 或 @code{errno.EISCONN} 表示连接已完成 -- 或者你也可以将此 socket 传给 @ref{770,,select.select()} 来检查它是否可写。

@cartouche
@quotation 注解 
@ref{9,,asyncio} 模块提供了通用的单线程并发异步库，它可被用来编写非阻塞的网络代码。 第三方的 Twisted@footnote{https://twistedmatrix.com/trac/} 库是一个热门且功能丰富的替代选择。
@end quotation
@end cartouche

@node 数据库,数学和数字,网络 / Internet 编程,代码库和插件 FAQ
@anchor{faq/library databases}@anchor{452a}
@subsection 数据库


@menu
* Python 中有数据库包的接口吗？:: 
* 在 Python 中如何实现持久化对象？:: 

@end menu

@node Python 中有数据库包的接口吗？,在 Python 中如何实现持久化对象？,,数据库
@anchor{faq/library are-there-any-interfaces-to-database-packages-in-python}@anchor{452b}
@subsubsection Python 中有数据库包的接口吗？


当然。

标准 Python 还包含了基于磁盘的哈希接口例如 @ref{34,,DBM} 和 @ref{33,,GDBM} 。除此之外还有 @ref{f2,,sqlite3} 模块，该模块提供了一个轻量级的基于磁盘的关系型数据库。

大多数关系型数据库都已经支持。查看 数据库编程 wiki 页面@footnote{https://wiki.python.org/moin/DatabaseProgramming} 获取更多信息。

@node 在 Python 中如何实现持久化对象？,,Python 中有数据库包的接口吗？,数据库
@anchor{faq/library how-do-you-implement-persistent-objects-in-python}@anchor{452c}
@subsubsection 在 Python 中如何实现持久化对象？


@ref{ca,,pickle} 库模块以一种非常通用的方式解决了这个问题（虽然你依然不能用它保存打开的文件、套接字或窗口之类的东西），此外 @ref{e7,,shelve} 库模块可使用 pickle 和 (g)dbm 来创建包含任意 Python 对象的持久化映射。

@node 数学和数字,,数据库,代码库和插件 FAQ
@anchor{faq/library mathematics-and-numerics}@anchor{452d}
@subsection 数学和数字


@menu
* Python 中怎样生成随机数？:: 

@end menu

@node Python 中怎样生成随机数？,,,数学和数字
@anchor{faq/library how-do-i-generate-random-numbers-in-python}@anchor{452e}
@subsubsection Python 中怎样生成随机数？


@ref{dc,,random} 标准库模块实现了随机数生成器，使用起来非常简单：

@example
import random
random.random()
@end example

这个函数会返回 [0, 1) 之间的随机浮点数。

该模块中还有许多其他的专门的生成器，例如：


@itemize *

@item 
@code{randrange(a, b)} 返回 [a, b) 区间内的一个整型数。

@item 
@code{uniform(a, b)} 返回 [a, b) 区间之间的浮点数。

@item 
@code{normalvariate(mean, sdev)} 使用正态（高斯）分布采样。
@end itemize

还有一些高级函数直接对序列进行操作，例如：


@itemize *

@item 
@code{choice(S)} 从给定的序列中随机选择一个元素。

@item 
@code{shuffle(L)} 会对列表执行原地重排，即将其随机地打乱。
@end itemize

还有 @code{Random} 类，你可以将其实例化，用来创建多个独立的随机数生成器。

@node 扩展/嵌入常见问题,Python在Windows上的常见问题,代码库和插件 FAQ,Python 常见问题
@anchor{faq/extending doc}@anchor{452f}@anchor{faq/extending extending-embedding-faq}@anchor{4530}
@section 扩展/嵌入常见问题



@c XXX need review for Python 3.

@menu
* 可以使用 C 语言创建自己的函数吗？:: 
* 可以使用 C++ 语言创建自己的函数吗？:: 
* C很难写，有没有其他选择？:: 
* 如何在 C 中执行任意 Python 语句？:: 
* 如何在 C 中对任意 Python 表达式求值？:: 
* 如何从Python对象中提取C的值？:: 
* 如何使用Py_BuildValue()创建任意长度的元组？: 如何使用Py_BuildValue 创建任意长度的元组？. 
* 如何从C调用对象的方法？:: 
* 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？. 
* 如何从C访问用Python编写的模块？:: 
* 如何在 Python 中对接 C ++ 对象？:: 
* 我使用Setup文件添加了一个模块，为什么make失败了？:: 
* 如何调试扩展？:: 
* 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?:: 
* 如何区分“输入不完整”和“输入无效”？:: 
* 如何找到未定义的g++符号__builtin_new或__pure_virtual？:: 
* 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？:: 

@end menu

@node 可以使用 C 语言创建自己的函数吗？,可以使用 C++ 语言创建自己的函数吗？,,扩展/嵌入常见问题
@anchor{faq/extending can-i-create-my-own-functions-in-c}@anchor{4531}
@subsection 可以使用 C 语言创建自己的函数吗？


是的，您可以在C中创建包含函数、变量、异常甚至新类型的内置模块。在文档 @ref{1361,,扩展和嵌入 Python 解释器} 中有说明。

大多数中级或高级的Python书籍也涵盖这个主题。

@node 可以使用 C++ 语言创建自己的函数吗？,C很难写，有没有其他选择？,可以使用 C 语言创建自己的函数吗？,扩展/嵌入常见问题
@anchor{faq/extending id2}@anchor{4532}
@subsection 可以使用 C++ 语言创建自己的函数吗？


是的，可以使用C ++中兼容C的功能。 在Python include文件周围放置` @cite{extern“C”@{...@}`} ，并在Python解释器调用的每个函数之前放置 @code{extern“C”} 。 具有构造函数的全局或静态C ++对象可能不是一个好主意。

@node C很难写，有没有其他选择？,如何在 C 中执行任意 Python 语句？,可以使用 C++ 语言创建自己的函数吗？,扩展/嵌入常见问题
@anchor{faq/extending c-wrapper-software}@anchor{4533}@anchor{faq/extending writing-c-is-hard-are-there-any-alternatives}@anchor{4534}
@subsection C很难写，有没有其他选择？


编写自己的C扩展有很多选择，具体取决于您要做的事情。

@c XXX make sure these all work

Cython@footnote{http://cython.org} 及其相关的 Pyrex@footnote{https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/} 是接受稍微修改过的Python形式并生成相应C代码的编译器。 Cython和Pyrex可以编写扩展而无需学习Python的C API。

如果需要连接到某些当前不存在Python扩展的C或C ++库，可以尝试使用 SWIG@footnote{http://www.swig.org} 等工具包装库的数据类型和函数。  SIP@footnote{https://riverbankcomputing.com/software/sip/intro} ， CXX@footnote{http://cxx.sourceforge.net/} Boost@footnote{http://www.boost.org/libs/python/doc/index.html} , 或 Weave@footnote{https://github.com/scipy/weave} 也是包装C ++库的替代方案。

@node 如何在 C 中执行任意 Python 语句？,如何在 C 中对任意 Python 表达式求值？,C很难写，有没有其他选择？,扩展/嵌入常见问题
@anchor{faq/extending how-can-i-execute-arbitrary-python-statements-from-c}@anchor{4535}
@subsection 如何在 C 中执行任意 Python 语句？


执行此操作的最高层级函数为 @ref{3dd9,,PyRun_SimpleString()}，它接受单个字符串参数用于在模块 @code{__main__} 的上下文中执行并在成功时返回 @code{0} 而在发生异常 (包括 @ref{562,,SyntaxError}) 时返回 @code{-1}。 如果你想要更多可控性，可以使用 @ref{1130,,PyRun_String()}；请在 @code{Python/pythonrun.c} 中查看 @ref{3dd9,,PyRun_SimpleString()} 的源码。

@node 如何在 C 中对任意 Python 表达式求值？,如何从Python对象中提取C的值？,如何在 C 中执行任意 Python 语句？,扩展/嵌入常见问题
@anchor{faq/extending how-can-i-evaluate-an-arbitrary-python-expression-from-c}@anchor{4536}
@subsection 如何在 C 中对任意 Python 表达式求值？


可以调用前一问题中介绍的函数 @ref{1130,,PyRun_String()} 并附带起始标记符 @ref{3e32,,Py_eval_input}；它会解析表达式，对其求值并返回结果值。

@node 如何从Python对象中提取C的值？,如何使用Py_BuildValue 创建任意长度的元组？,如何在 C 中对任意 Python 表达式求值？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-extract-c-values-from-a-python-object}@anchor{4537}
@subsection 如何从Python对象中提取C的值？


这取决于对象的类型。 如果是元组，@ref{408f,,PyTuple_Size()} 可返回其长度而 @ref{3d73,,PyTuple_GetItem()} 可返回指定序号上的项。 对于列表也有类似的函数 @code{PyListSize()} 和 @ref{3d74,,PyList_GetItem()}。

对于字节串，@ref{401b,,PyBytes_Size()} 可返回其长度而 @ref{401f,,PyBytes_AsStringAndSize()} 提供一个指向其值和长度的指针。 请注意 Python 字节串可能为空，因此 C 的 @code{strlen()} 不应被使用。

要检测一个对象的类型，首先要确保它不为 @code{NULL}，然后使用 @ref{ded,,PyBytes_Check()}, @ref{408b,,PyTuple_Check()}, @ref{409d,,PyList_Check()} 等等。

还有一个针对 Python 对象的高层级 API，通过所谓的‘抽象’接口提供 —— 请参阅 @code{Include/abstract.h} 了解详情。 它允许使用 @ref{3f51,,PySequence_Length()}, @ref{11cc,,PySequence_GetItem()} 这样的调用来与任意种类的 Python 序列进行对接，此外还可使用许多其他有用的协议例如数字 (@ref{3f4b,,PyNumber_Index()} 等) 以及 PyMapping API 中的各种映射等等。

@node 如何使用Py_BuildValue 创建任意长度的元组？,如何从C调用对象的方法？,如何从Python对象中提取C的值？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length}@anchor{4538}
@subsection 如何使用Py_BuildValue()创建任意长度的元组？


不可以。应该使用 @ref{408e,,PyTuple_Pack()} 。

@node 如何从C调用对象的方法？,如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,如何使用Py_BuildValue 创建任意长度的元组？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-call-an-object-s-method-from-c}@anchor{4539}
@subsection 如何从C调用对象的方法？


可以使用 @ref{3f23,,PyObject_CallMethod()} 函数来调用某个对象的任意方法。 形参为该对象、要调用的方法名、类似 @ref{3f9,,Py_BuildValue()} 所用的格式字符串以及要传给方法的参数值:

@example
PyObject *
PyObject_CallMethod(PyObject *object, const char *method_name,
                    const char *arg_format, ...);
@end example

这适用于任何具有方法的对象 —— 不论是内置方法还是用户自定义方法。 你需要负责对返回值进行最终的 @ref{397,,Py_DECREF()} 处理。

例如调用某个文件对象的 "seek" 方法并传入参数 10, 0 (假定文件对象的指针为 "f"):

@example
res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
if (res == NULL) @{
        ... an exception occurred ...
@}
else @{
        Py_DECREF(res);
@}
@end example

请注意由于 @ref{3d67,,PyObject_CallObject()} @emph{总是} 接受一个元组作为参数列表，要调用不带参数的函数，则传入格式为 "()"，要调用只带一个参数的函数，则应将参数包含于圆括号中，例如 "(i)"。

@node 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,如何从C访问用Python编写的模块？,如何从C调用对象的方法？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr}@anchor{453a}
@subsection 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？


在 Python 代码中，定义一个支持 @code{write()} 方法的对象。 将此对象赋值给 @ref{428,,sys.stdout} 和 @ref{1eb,,sys.stderr}。 调用 print_error 或者只是允许标准回溯机制生效。 在此之后，输出将转往你的 @code{write()} 方法所指向的任何地方。

做到这一点的最简单方式是使用 @ref{924,,io.StringIO} 类：

@example
>>> import io, sys
>>> sys.stdout = io.StringIO()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write(sys.stdout.getvalue())
foo
hello world!
@end example

实现同样效果的自定义对象看起来是这样的：

@example
>>> import io, sys
>>> class StdoutCatcher(io.TextIOBase):
...     def __init__(self):
...         self.data = []
...     def write(self, stuff):
...         self.data.append(stuff)
...
>>> import sys
>>> sys.stdout = StdoutCatcher()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write('@w{'}.join(sys.stdout.data))
foo
hello world!
@end example

@node 如何从C访问用Python编写的模块？,如何在 Python 中对接 C ++ 对象？,如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-access-a-module-written-in-python-from-c}@anchor{453b}
@subsection 如何从C访问用Python编写的模块？


你可以通过如下方式获得一个指向模块对象的指针:

@example
module = PyImport_ImportModule("<modulename>");
@end example

如果模块尚未被导入（即它还不存在于 @ref{109a,,sys.modules} 中），这会初始化该模块；否则它只是简单地返回 @code{sys.modules["<modulename>"]} 的值。 请注意它并不会将模块加入任何命名空间 —— 它只是确保模块被初始化并存在于 @ref{109a,,sys.modules} 中。

之后你就可以通过如下方式来访问模块的属性（即模块中定义的任何名称）:

@example
attr = PyObject_GetAttrString(module, "<attrname>");
@end example

调用 @ref{3f02,,PyObject_SetAttrString()} 为模块中的变量赋值也是可以的。

@node 如何在 Python 中对接 C ++ 对象？,我使用Setup文件添加了一个模块，为什么make失败了？,如何从C访问用Python编写的模块？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-interface-to-c-objects-from-python}@anchor{453c}
@subsection 如何在 Python 中对接 C ++ 对象？


根据你的需求，可以选择许多方式。 手动的实现方式请查阅 @ref{1361,,"扩展与嵌入" 文档} 来入门。 需要知道的是对于 Python 运行时系统来说，C 和 C++ 并不没有太大的区别 —— 因此围绕一个 C 结构（指针）类型构建新 Python 对象的策略同样适用于 C++ 对象。

有关C ++库，请参阅 @ref{4533,,C很难写，有没有其他选择？}

@node 我使用Setup文件添加了一个模块，为什么make失败了？,如何调试扩展？,如何在 Python 中对接 C ++ 对象？,扩展/嵌入常见问题
@anchor{faq/extending i-added-a-module-using-the-setup-file-and-the-make-fails-why}@anchor{453d}
@subsection 我使用Setup文件添加了一个模块，为什么make失败了？


安装程序必须以换行符结束，如果没有换行符，则构建过程将失败。 （修复这个需要一些丑陋的shell脚本编程，而且这个bug很小，看起来不值得花这么大力气。)

@node 如何调试扩展？,我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,我使用Setup文件添加了一个模块，为什么make失败了？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-debug-an-extension}@anchor{453e}
@subsection 如何调试扩展？


将GDB与动态加载的扩展名一起使用时，在加载扩展名之前，不能在扩展名中设置断点。

在您的 @code{.gdbinit} 文件中（或交互式）添加命令：

@example
br _PyImport_LoadDynamicModule
@end example

然后运行GDB：

@example
$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish   # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue
@end example

@node 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,如何区分“输入不完整”和“输入无效”？,如何调试扩展？,扩展/嵌入常见问题
@anchor{faq/extending i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why}@anchor{453f}
@subsection 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?


大多数打包的Python版本不包含 @code{/usr/lib/python2.@emph{x}/config/} 目录，该目录中包含编译Python扩展所需的各种文件。

对于Red Hat，安装python-devel RPM以获取必要的文件。

对于Debian，运行 @code{apt-get install python-dev} 。

@node 如何区分“输入不完整”和“输入无效”？,如何找到未定义的g++符号__builtin_new或__pure_virtual？,我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-tell-incomplete-input-from-invalid-input}@anchor{4540}
@subsection 如何区分“输入不完整”和“输入无效”？


有时，希望模仿Python交互式解释器的行为，在输入不完整时(例如，您键入了“if”语句的开头，或者没有关闭括号或三个字符串引号)，给出一个延续提示，但当输入无效时，立即给出一条语法错误消息。

在Python中，您可以使用 @ref{1c,,codeop} 模块，该模块非常接近解析器的行为。例如，IDLE就使用了这个。

在C中执行此操作的最简单方法是调用 @ref{3e1c,,PyRun_InteractiveLoop()} （可能在单独的线程中）并让Python解释器为您处理输入。您还可以设置 @ref{a56,,PyOS_ReadlineFunctionPointer()} 指向您的自定义输入函数。有关更多提示，请参阅 @code{Modules/readline.c} 和 @code{Parser/myreadline.c} 。

@node 如何找到未定义的g++符号__builtin_new或__pure_virtual？,能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,如何区分“输入不完整”和“输入无效”？,扩展/嵌入常见问题
@anchor{faq/extending how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual}@anchor{4541}
@subsection 如何找到未定义的g++符号__builtin_new或__pure_virtual？


要动态加载g ++扩展模块，必须重新编译Python，要使用g ++重新链接（在Python Modules Makefile中更改LINKCC），及链接扩展模块（例如： @code{g++ -shared -o mymodule.so mymodule.o} ）。

@node 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,,如何找到未定义的g++符号__builtin_new或__pure_virtual？,扩展/嵌入常见问题
@anchor{faq/extending can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance}@anchor{4542}
@subsection 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？


是的，您可以继承内置类，例如 @ref{205,,int} ， @ref{1f9,,list} ， @ref{164,,dict} 等。

Boost Python库（BPL，http：//www.boost.org/libs/python/doc/index.html）提供了一种从C ++执行此操作的方法（即，您可以使用BPL继承自C ++编写的扩展类 ）。

@node Python在Windows上的常见问题,图形用户界面（GUI）常见问题,扩展/嵌入常见问题,Python 常见问题
@anchor{faq/windows doc}@anchor{4543}@anchor{faq/windows python-on-windows-faq}@anchor{4544}@anchor{faq/windows windows-faq}@anchor{4545}
@section Python在Windows上的常见问题



@c XXX need review for Python 3.
@c XXX need review for Windows Vista/Seven?

@menu
* 我怎样在Windows下运行一个Python程序？:: 
* 我怎么让 Python 脚本可执行？:: 
* 为什么有时候 Python 程序会启动缓慢？:: 
* 我怎样使用 Python 脚本制作可执行文件？:: 
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？. 
* 我怎样将 Python 嵌入一个 Windows 程序？:: 
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？:: 
* 如何在不阻塞的情况下检查按键？:: 

@end menu

@node 我怎样在Windows下运行一个Python程序？,我怎么让 Python 脚本可执行？,,Python在Windows上的常见问题
@anchor{faq/windows faq-run-program-under-windows}@anchor{4546}@anchor{faq/windows how-do-i-run-a-python-program-under-windows}@anchor{4547}
@subsection 我怎样在Windows下运行一个Python程序？


这不一定是一个简单的问题。如果你已经熟悉在Windows的命令行中运行程序的方法，一切都显而易见；不然的话，你也许需要额外获得些许指导。

除非你使用某种集成开发环境，否则你最终会在所谓的 "命令提示窗口 "中 @emph{输入} Windows命令。 通常情况下，你可以在搜索栏中搜索 @code{cmd} 来创建这样一个窗口。你应该能够发现你已经启动了这样一个窗口，因为你会看到一个 Windows "命令提示符"，它通常看起来像这样。

@example
C:\>
@end example

前面的字母可能会不同，而且后面有可能会有其他东西，所以你也许会看到类似这样的东西：

@example
D:\YourName\Projects\Python>
@end example

出现的内容具体取决与你的电脑如何设置和你最近用它做的事。 当你启动了这样一个窗口后，就可以开始运行Python程序了。

Python 脚本需要被另外一个叫做 Python @emph{解释器} 的程序来处理。 解释器读取脚本，把它编译成字节码，然后执行字节码来运行你的程序。 所以怎样安排解释器来处理你的 Python 脚本呢？

首先，确保命令窗口能够将“py”识别为指令来开启解释器。 如果你打开过一个命令窗口， 尝试输入命令 @code{py} 然后按回车：

@example
C:\Users\YourName> py
@end example

然后你应当看见类似类似这样的东西：

@example
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
@end example

解释器已经以“交互模式”打开。这意味着你可以交互输入Python语句或表达式，并在等待时执行或评估它们。这是Python最强大的功能之一。输入几个表达式并看看结果：

@example
>>> print("Hello")
Hello
>>> "Hello" * 3
'HelloHelloHello'
@end example

许多人把交互模式当作方便和高度可编程的计算器。 想结束交互式Python会话时，调用 @ref{1773,,exit()} 函数，或者按住 @code{Ctrl} 键时输入 @code{Z}  ，之后按 @code{Enter} 键返回Windows命令提示符。

你可能发现在开始菜单有这样一个条目 开始 ‣ 所有程序 ‣ Python 3.x ‣ Python (命令行)， 运行它后会出现一个有着 @code{>>>} 提示的新窗口。 在此之后，如果调用 @ref{1773,,exit()} 函数或按 @code{Ctrl-Z} 组合键后窗口将会消失。 Windows 会在这个窗口中运行一个“python”命令，并且在你终止解释器的时候关闭它。

现在我们知道 @code{py} 命令已经被识别，可以输入 Python 脚本了。 你需要提供 Python 脚本的绝对路径或相对路径。 假设 Python 脚本位于桌面上并命名为 @code{hello.py}，并且命令提示符在用户主目录打开，那么可以看到类似于这样的东西:

@example
C:\Users\YourName>
@end example

那么现在可以让`@w{`}py`@w{`}命令执行你的脚本，只需要输入`@w{`}py`@w{`} 和脚本路径:

@example
C:\Users\YourName> py Desktop\hello.py
hello
@end example

@node 我怎么让 Python 脚本可执行？,为什么有时候 Python 程序会启动缓慢？,我怎样在Windows下运行一个Python程序？,Python在Windows上的常见问题
@anchor{faq/windows how-do-i-make-python-scripts-executable}@anchor{4548}
@subsection 我怎么让 Python 脚本可执行？


在 Windows 上，标准 Python 安装程序已将 .py 扩展名与文件类型 (Python.File) 相关联，并为该文件类型提供运行解释器的打开命令 (@code{D:\Program Files\Python\python.exe "%1" %*}) 。 这足以使脚本在命令提示符下作为“foo.py”命令被执行。 如果希望通过简单地键入“foo”而无需输入文件扩展名来执行脚本，则需要将 .py 添加到 PATHEXT 环境变量中。

@node 为什么有时候 Python 程序会启动缓慢？,我怎样使用 Python 脚本制作可执行文件？,我怎么让 Python 脚本可执行？,Python在Windows上的常见问题
@anchor{faq/windows why-does-python-sometimes-take-so-long-to-start}@anchor{4549}
@subsection 为什么有时候 Python 程序会启动缓慢？


通常，Python 在 Windows 上启动得很快，但偶尔会有错误报告说 Python 突然需要很长时间才能启动。更令人费解的是，在其他配置相同的 Windows 系统上，Python 却可以工作得很好。

该问题可能是由于计算机上的杀毒软件配置错误造成的。当将病毒扫描配置为监视文件系统中所有读取行为时，一些杀毒扫描程序会导致两个数量级的启动开销。请检查你系统安装的杀毒扫描程序的配置，确保两台机它们是同样的配置。已知的， McAfee 杀毒软件在将它设置为扫描所有文件系统访问时，会产生这个问题。

@node 我怎样使用 Python 脚本制作可执行文件？,* pyd 文件和 DLL 文件相同吗？,为什么有时候 Python 程序会启动缓慢？,Python在Windows上的常见问题
@anchor{faq/windows how-do-i-make-an-executable-from-a-python-script}@anchor{454a}
@subsection 我怎样使用 Python 脚本制作可执行文件？


请参阅 @ref{44a3,,如何由 Python 脚本创建能独立运行的二进制程序？} 查看可用来生成可执行文件的工具清单。

@node * pyd 文件和 DLL 文件相同吗？,我怎样将 Python 嵌入一个 Windows 程序？,我怎样使用 Python 脚本制作可执行文件？,Python在Windows上的常见问题
@anchor{faq/windows is-a-pyd-file-the-same-as-a-dll}@anchor{454b}
@subsection @code{*.pyd} 文件和 DLL 文件相同吗？


是的， .pyd 文件也是 dll ，但有一些差异。如果你有一个名为 @code{foo.pyd} 的DLL，那么它必须有一个函数 @code{PyInit_foo()} 。 然后你可以编写 Python 代码 “import foo” ，Python 将搜索 foo.pyd （以及 foo.py 、 foo.pyc ）。如果找到它，将尝试调用 @code{PyInit_foo()} 来初始化它。你不应将 .exe 与 foo.lib 链接，因为这会导致 Windows 要求存在 DLL 。

请注意， foo.pyd 的搜索路径是 PYTHONPATH ，与 Windows 用于搜索 foo.dll 的路径不同。此外， foo.pyd 不需要存在来运行你的程序，而如果你将程序与 dll 链接，则需要 dll 。 当然，如果你想 @code{import foo} ，则需要 foo.pyd 。在 DLL 中，链接在源代码中用 @code{__declspec(dllexport)} 声明。 在 .pyd 中，链接在可用函数列表中定义。

@node 我怎样将 Python 嵌入一个 Windows 程序？,如何让编辑器不要在我的 Python 源代码中插入 tab ？,* pyd 文件和 DLL 文件相同吗？,Python在Windows上的常见问题
@anchor{faq/windows how-can-i-embed-python-into-a-windows-application}@anchor{454c}
@subsection 我怎样将 Python 嵌入一个 Windows 程序？


在 Windows 应用程序中嵌入 Python 解释器可以总结如下：


@enumerate 

@item 
请 _不要_ 直接在你的 .exe 文件中内置 Python 。在 Windows 上， Python 必须是一个 DLL ，这样才可以处理导入的本身就是 DLL 的模块。（这是第一个未记录的关键事实。）相反，链接到 @code{python@emph{NN}.dll} ；它通常安装在 @code{C:\Windows\System} 中。 @emph{NN} 是 Python 版本，如数字“33”代表 Python 3.3 。

你可以通过两种不同的方式链接到 Python 。加载时链接意味着链接到 @code{python@emph{NN}.lib} ，而运行时链接意味着链接 @code{python@emph{NN}.dll} 。（一般说明： @code{python @emph{NN}.lib} 是所谓的“import lib”，对应于 @code{python@emph{NN}.dll} 。它只定义了链接器的符号。）

运行时链接极大地简化了链接选项，一切都在运行时发生。你的代码必须使用 Windows 的 @code{LoadLibraryEx()} 程序加载 @code{python@emph{NN}.dll} 。代码还必须使用使用 Windows 的 @code{GetProcAddress()} 例程获得的指针访问 @code{python@emph{NN}.dll} 中程序和数据（即 Python 的 C API ）。宏可以使这些指针对任何调用 Python C API 中的例程的 C 代码都是透明的。

@c XXX what about static linking?

@item 
如果你使用 SWIG ，很容易创建一个 Python “扩展模块”，它将使应用程序的数据和方法可供 Python 使用。SWIG将为你处理所有蹩脚的细节。结果是你将链接到 .exe 文件 @emph{中} 的C代码 (!) 你不必创建 DLL 文件，这也简化了链接。

@item 
SWIG 将创建一个 init 函数（一个 C 函数），其名称取决于扩展模块的名称。例如，如果模块的名称是 leo ，则 init 函数将被称为 initleo() 。 如果您使用 SWIG 阴影类，则 init 函数将被称为 initleoc() 。这初始化了一个由阴影类使用的隐藏辅助类。

你可以将步骤 2 中的 C 代码链接到 .exe 文件的原因是调用初始化函数等同于将模块导入 Python ！ （这是第二个关键的未记载事实。）

@item 
简而言之，你可以用以下代码使用扩展模块初始化 Python 解释器。

@example
#include "python.h"
...
Py_Initialize();  // Initialize Python.
initmyAppc();  // Initialize (import) the helper class.
PyRun_SimpleString("import myApp");  // Import the shadow class.
@end example

@item 
Python C API 存在两个问题，如果你使用除 MSVC 之外的编译器用于构建 python.dll ，这将会变得明显。

问题1：采用 FILE* 参数的所谓“极高级”函数在多编译器环境中不起作用，因为每个编译器的FILE结构体概念都不同。从实现的角度来看，这些是非常 _低_ 级的功能。

问题2：在为 void 函数生成包装器时，SWIG 会生成以下代码：

@example
Py_INCREF(Py_None);
_resultobj = Py_None;
return _resultobj;
@end example

Py_None 是一个宏，它扩展为对 pythonNN.dll 中名为 _Py_NoneStruct 的复杂数据结构的引用。同样，此代码将在多编译器环境中失败。将此类代码替换为：

@example
return Py_BuildValue("");
@end example

有可能使用 SWIG 的 @code{%typemap} 命令自动进行更改，但我无法使其工作（我是一个完全的SWIG新手）。

@item 
使用 Python shell 脚本从 Windows 应用程序内部建立 Python 解释器窗口并不是一个好主意；生成的窗口将独立于应用程序的窗口系统。相反，你（或 wxPythonWindow 类）应该创建一个“本机”解释器窗口。将该窗口连接到Python解释器很容易。你可以将 Python的 i/o 重定向到支持读写的 _任意_ 对象，因此你只需要一个包含 read() 和 write() 方法的 Python 对象（在扩展模块中定义）。
@end enumerate

@node 如何让编辑器不要在我的 Python 源代码中插入 tab ？,如何在不阻塞的情况下检查按键？,我怎样将 Python 嵌入一个 Windows 程序？,Python在Windows上的常见问题
@anchor{faq/windows how-do-i-keep-editors-from-inserting-tabs-into-my-python-source}@anchor{454d}
@subsection 如何让编辑器不要在我的 Python 源代码中插入 tab ？


本 FAQ 不建议使用制表符， Python 样式指南 
@geindex Python 提高建议; PEP 8
PEP 8@footnote{https://www.python.org/dev/peps/pep-0008} ，为发行的 Python 代码推荐 4 个空格；这也是 Emacs python-mode 默认值。

在任何编辑器下，混合制表符和空格都是一个坏主意。 MSVC 在这方面没有什么不同，并且很容易配置为使用空格： 点击 Tools ‣ Options ‣ Tabs，对于文件类型“Default”，设置“Tab size”和“Indent size”为 4 ，并选择“插入空格”单选按钮。

如果混合制表符和空格导致前导空格出现问题， Python 会引发 @ref{f40,,IndentationError} 或 @ref{f3f,,TabError} 。你还可以运行 @ref{100,,tabnanny} 模块以批处理模式检查目录树。

@node 如何在不阻塞的情况下检查按键？,,如何让编辑器不要在我的 Python 源代码中插入 tab ？,Python在Windows上的常见问题
@anchor{faq/windows how-do-i-check-for-a-keypress-without-blocking}@anchor{454e}
@subsection 如何在不阻塞的情况下检查按键？


使用 @ref{b6,,msvcrt} 模块。 这是一个标准的 Windows 专属扩展模块。 它定义了一个函数 @code{kbhit()} 用于检查是否有键盘中的某个键被按下，以及 @code{getch()} 用于获取一个字符而不将其回显。

@node 图形用户界面（GUI）常见问题,“为什么我的电脑上安装了 Python ？”,Python在Windows上的常见问题,Python 常见问题
@anchor{faq/gui doc}@anchor{454f}@anchor{faq/gui graphic-user-interface-faq}@anchor{4550}
@section 图形用户界面（GUI）常见问题



@c XXX need review for Python 3.

@menu
* 图形界面常见问题:: 
* Python 有哪些 GUI 工具包？:: 
* 有关Tkinter的问题:: 

@end menu

@node 图形界面常见问题,Python 有哪些 GUI 工具包？,,图形用户界面（GUI）常见问题
@anchor{faq/gui general-gui-questions}@anchor{4551}
@subsection 图形界面常见问题


@node Python 有哪些 GUI 工具包？,有关Tkinter的问题,图形界面常见问题,图形用户界面（GUI）常见问题
@anchor{faq/gui what-gui-toolkits-exist-for-python}@anchor{4552}
@subsection Python 有哪些 GUI 工具包？


Python 的标准构建包括一个指向 Tcl/Tk 部件集的面向对象的接口，称为 @ref{318a,,tkinter} 。 这可能是最容易安装（因为它包含在大多数 Python 的 二进制发行版@footnote{https://www.python.org/downloads/} 中）和使用的。关于 Tk 的更多信息，包括指向源代码的信息，见 Tcl/Tk 主页@footnote{https://www.tcl.tk} 。 Tcl/Tk 可以完全移植到 macOS 、 Windows 和 Unix 平台。

存在多种选项，具体取决于你的目标平台。 Python Wiki 上提供了一个 跨平台@footnote{https://wiki.python.org/moin/GuiProgramming#Cross-Platform_Frameworks} 和 平台专属@footnote{https://wiki.python.org/moin/GuiProgramming#Platform-specific_Frameworks} 的 GUI 框架列表。

@node 有关Tkinter的问题,,Python 有哪些 GUI 工具包？,图形用户界面（GUI）常见问题
@anchor{faq/gui tkinter-questions}@anchor{4553}
@subsection 有关Tkinter的问题


@menu
* 我怎样“冻结”Tkinter程序？:: 
* 在等待 I/O 操作时能够处理 Tk 事件吗？:: 
* 在Tkinter中键绑定不工作：为什么？:: 

@end menu

@node 我怎样“冻结”Tkinter程序？,在等待 I/O 操作时能够处理 Tk 事件吗？,,有关Tkinter的问题
@anchor{faq/gui how-do-i-freeze-tkinter-applications}@anchor{4554}
@subsubsection 我怎样“冻结”Tkinter程序？


Freeze是一个用来创建独立应用程序的工具。 当冻结(freeze) Tkinter程序时，程序并不是真的能够独立运行，因为程序仍然需要Tcl和Tk库。

一种解决方法是将程序与 Tcl 和 Tk 库一同发布，并且在运行时使用环境变量 
@geindex TCL_LIBRARY
@geindex 环境变量; TCL_LIBRARY
@code{TCL_LIBRARY} 和 
@geindex TK_LIBRARY
@geindex 环境变量; TK_LIBRARY
@code{TK_LIBRARY} 指向他们的位置。

为了获得真正能独立运行的应用程序，来自库里的 Tcl 脚本也需要被整合进应用程序。 一个做这种事情的工具叫 SAM (stand-alone modules，独立模块) ，它是 Tix distribution (@indicateurl{http://tix.sourceforge.net/}) 的一部分。

在启用 SAM 时编译 Tix ，在 Python 文件  @code{Modules/tkappinit.c} 中执行对 @code{Tclsam_init()} 等的适当调用，并且将程序与 libtclsam 和 libtksam 相链接（可能也要包括 Tix 的库）。

@node 在等待 I/O 操作时能够处理 Tk 事件吗？,在Tkinter中键绑定不工作：为什么？,我怎样“冻结”Tkinter程序？,有关Tkinter的问题
@anchor{faq/gui can-i-have-tk-events-handled-while-waiting-for-i-o}@anchor{4555}
@subsubsection 在等待 I/O 操作时能够处理 Tk 事件吗？


在 Windows 以外的其他平台上可以，你甚至不需要使用线程！ 但是你必须稍微修改一下你的 I/O 代码。 Tk 有与 Xt 的 @code{XtAddInput()} 对应的调用，它允许你注册一个回调函数，当一个文件描述符可以进行 I/O 操作的时候，Tk 主循环将会调用这个回调函数。 参见 @ref{31a7,,文件句柄}。

@node 在Tkinter中键绑定不工作：为什么？,,在等待 I/O 操作时能够处理 Tk 事件吗？,有关Tkinter的问题
@anchor{faq/gui i-can-t-get-key-bindings-to-work-in-tkinter-why}@anchor{4556}
@subsubsection 在Tkinter中键绑定不工作：为什么？


经常听到的抱怨是：已经通过  @code{bind()} 方法绑定了事件的处理程序，但是，当按下相关的按键后，这个处理程序却没有执行。

最常见的原因是，那个绑定的控件没有“键盘焦点”。请在 Tk 文档中查找 focus 指令。通常一个控件要获得“键盘焦点”，需要点击那个控件（而不是标签；请查看 takefocus 选项）。

@node “为什么我的电脑上安装了 Python ？”,,图形用户界面（GUI）常见问题,Python 常见问题
@anchor{faq/installed doc}@anchor{4557}@anchor{faq/installed why-is-python-installed-on-my-computer-faq}@anchor{4558}
@section “为什么我的电脑上安装了 Python ？”


@menu
* 什么是Python？:: 
* 为什么我的电脑上安装了 Python ？:: 
* 我能删除 Python 吗？:: 

@end menu

@node 什么是Python？,为什么我的电脑上安装了 Python ？,,“为什么我的电脑上安装了 Python ？”
@anchor{faq/installed what-is-python}@anchor{4559}
@subsection 什么是Python？


Python 是一种程序语言，被许多应用程序使用。它不仅因易学而在许多高校用于编程入门，还被工作于 Google、NASA 和卢卡斯影业等公司的软件开发人员使用。

如果你想学习更多 Python，看看 Beginner's Guide to Python@footnote{https://wiki.python.org/moin/BeginnersGuide}.

@node 为什么我的电脑上安装了 Python ？,我能删除 Python 吗？,什么是Python？,“为什么我的电脑上安装了 Python ？”
@anchor{faq/installed why-is-python-installed-on-my-machine}@anchor{455a}
@subsection 为什么我的电脑上安装了 Python ？


如果你不记得你曾主动安装过 Python，但它却出现在了你的电脑上，这里有一些可能的原因。


@itemize *

@item 
可能是这台电脑的其他用户因想学习编程而安装了它，你得琢磨一下谁用过这台电脑并安装了 Python。

@item 
电脑上安装的第三方应用程序可能由 Python 写成并附带了一份 Python。这样的应用程序有很多，例如GUI程序、网络服务器、管理脚本等。

@item 
一些 Windows 可能预装了 Python。在撰写本文时，我们了解到 Hewlett-Packard 和 Compaq 的计算机包含Python。显然，HP/Compaq 的一些管理工具是用 Python 编写的。

@item 
许多与Unix兼容的操作系统，如macOS和一些Linux发行版，都默认安装了Python；它包含在基本安装中。
@end itemize

@node 我能删除 Python 吗？,,为什么我的电脑上安装了 Python ？,“为什么我的电脑上安装了 Python ？”
@anchor{faq/installed can-i-delete-python}@anchor{455b}
@subsection 我能删除 Python 吗？


这取决于所安装 Python 的来源

如果有人主动安装了 Python，你可以在不影响其它程序的情况下安全移除它。在 Windows 中，可使用“控制面板”中的“添加/删除程序”卸载。

如果 Python 来源于第三方应用程序，你也能删除它，但那些程序将不能正常工作。你应该使用那些应用程序的卸载器而不是直接删除 Python。

如果 Python 来自于你的操作系统，不推荐删除！如果删除了它，任何用 Python 写成的工具将无法工作，其中某些工具对于你来说可能十分重要。你甚至可能需要重装整个系统来修复因删除 Python 留下的烂摊子。

@node 术语对照表,文档说明,Python 常见问题,Top
@anchor{glossary doc}@anchor{455c}@anchor{glossary glossary}@anchor{1363}@anchor{glossary id1}@anchor{455d}
@chapter 术语对照表


@c if you add new entries, keep the alphabetical sorting!


@table @asis
@anchor{glossary term-0}@anchor{137c}
@geindex >>>

@item @code{>>>}

交互式终端中默认的 Python 提示符。往往会显示于能以交互方式在解释器里执行的样例代码之前。
@anchor{glossary term-1}@anchor{137d}
@geindex ...

@item @code{...}

具有以下含义：


@itemize *

@item 
交互式终端中输入特殊代码行时默认的 Python 提示符，包括：缩进的代码块，成对的分隔符之内（圆括号、方括号、花括号或三重引号），或是指定一个装饰器之后。

@item 
@ref{1770,,Ellipsis} 内置常量。
@end itemize
@anchor{glossary term-2to3}@anchor{11a3}
@geindex 2to3

@item 2to3

把 Python 2.x 代码转换为 Python 3.x 代码的工具，通过解析源码，遍历解析树，处理绝大多数检测到的不兼容问题。

2to3 包含在标准库中，模块名为 @ref{a7,,lib2to3}；提供了独立入口点 @code{Tools/scripts/2to3}。详见 @ref{d46,,2to3 - 自动将 Python 2 代码转为 Python 3 代码}。
@anchor{glossary term-abstract-base-class}@anchor{c0e}
@geindex abstract base class -- 抽象基类

@item abstract base class -- 抽象基类

抽象基类简称 ABC，是对 @ref{455e,,duck-typing} 的补充，它提供了一种定义接口的新方式，相比之下其他技巧例如 @ref{553,,hasattr()} 显得过于笨拙或有微妙错误（例如使用 @ref{159e,,魔术方法}）。ABC 引入了虚拟子类，这种类并非继承自其他类，但却仍能被 @ref{55a,,isinstance()} 和 @ref{55b,,issubclass()} 所认可；详见 @ref{3,,abc} 模块文档。Python 自带许多内置的 ABC 用于实现数据结构（在 @ref{1e,,collections.abc} 模块中）、数字（在 @ref{c1,,numbers} 模块中）、流（在 @ref{a1,,io} 模块中）、导入查找器和加载器（在 @ref{9b,,importlib.abc} 模块中）。你可以使用 @ref{3,,abc} 模块来创建自己的 ABC。
@anchor{glossary term-annotation}@anchor{15b6}
@geindex annotation -- 注解

@item annotation -- 注解

关联到某个变量、类属性、函数形参或返回值的标签，被约定作为 @ref{15ba,,type hint} 来使用。

局部变量的标注在运行时不可访问，但全局变量、类属性和函数的标注会分别存放模块、类和函数的 @code{__annotations__} 特殊属性中。

参见 @ref{71c,,variable annotation}、@ref{13c0,,function annotation}、
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526}，对此功能均有介绍。
@anchor{glossary term-argument}@anchor{168a}
@geindex argument -- 参数

@item argument -- 参数

在调用函数时传给 @ref{168b,,function} （或 @ref{455f,,method} ）的值。参数分为两种：


@itemize *

@item 
@emph{关键字参数}: 在函数调用中前面带有标识符（例如 @code{name=}）或者作为包含在前面带有 @code{**} 的字典里的值传入。举例来说，@code{3} 和 @code{5} 在以下对 @ref{2c8,,complex()} 的调用中均属于关键字参数:

@example
complex(real=3, imag=5)
complex(**@{'real': 3, 'imag': 5@})
@end example

@item 
@emph{位置参数}: 不属于关键字参数的参数。位置参数可出现于参数列表的开头以及/或者作为前面带有 @code{*} 的 @ref{c84,,iterable} 里的元素被传入。举例来说，@code{3} 和 @code{5} 在以下调用中均属于位置参数:

@example
complex(3, 5)
complex(*(3, 5))
@end example
@end itemize

参数会被赋值给函数体中对应的局部变量。有关赋值规则参见 @ref{749,,调用} 一节。根据语法，任何表达式都可用来表示一个参数；最终算出的值会被赋给对应的局部变量。

另参见 @ref{1693,,parameter} 术语表条目，常见问题中 @ref{44ae,,参数与形参的区别} 以及 
@geindex Python 提高建议; PEP 362
PEP 362@footnote{https://www.python.org/dev/peps/pep-0362}。
@anchor{glossary term-asynchronous-context-manager}@anchor{73e}
@geindex asynchronous context manager -- 异步上下文管理器

@item asynchronous context manager -- 异步上下文管理器

此种对象通过定义 @ref{10e3,,__aenter__()} 和 @ref{10e4,,__aexit__()} 方法来对 @ref{740,,async with} 语句中的环境进行控制。由 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 引入。
@anchor{glossary term-asynchronous-generator}@anchor{166f}
@geindex asynchronous generator -- 异步生成器

@item asynchronous generator -- 异步生成器

返回值为 @ref{36bd,,asynchronous generator iterator} 的函数。它与使用 @ref{3b1,,async def} 定义的协程函数很相似，不同之处在于它包含 @ref{2ce,,yield} 表达式以产生一系列可在 @ref{406,,async for} 循环中使用的值。

此术语通常是指异步生成器函数，但在某些情况下则可能是指 @emph{异步生成器迭代器}。如果需要清楚表达具体含义，请使用全称以避免歧义。

一个异步生成器函数可能包含 @ref{2df,,await} 表达式或者 @ref{406,,async for} 以及 @ref{740,,async with} 语句。
@anchor{glossary term-asynchronous-generator-iterator}@anchor{36bd}
@geindex asynchronous generator iterator -- 异步生成器迭代器

@item asynchronous generator iterator -- 异步生成器迭代器

@ref{166f,,asynchronous generator} 函数所创建的对象。

此对象属于 @ref{742,,asynchronous iterator}，当使用 @ref{158e,,__anext__()} 方法调用时会返回一个可等待对象来执行异步生成器函数的代码直到下一个 @ref{2ce,,yield} 表达式。

每个 @ref{2ce,,yield} 会临时暂停处理，记住当前位置执行状态 (包括局部变量和挂起的 try 语句)。当该 @emph{异步生成器迭代器} 与其他 @ref{158e,,__anext__()} 返回的可等待对象有效恢复时，它会从离开位置继续执行。参见 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 和 
@geindex Python 提高建议; PEP 525
PEP 525@footnote{https://www.python.org/dev/peps/pep-0525}。
@anchor{glossary term-asynchronous-iterable}@anchor{73d}
@geindex asynchronous iterable -- 异步可迭代对象

@item asynchronous iterable -- 异步可迭代对象

可在 @ref{406,,async for} 语句中被使用的对象。必须通过它的 @ref{58b,,__aiter__()} 方法返回一个 @ref{742,,asynchronous iterator}。由 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 引入。
@anchor{glossary term-asynchronous-iterator}@anchor{742}
@geindex asynchronous iterator -- 异步迭代器

@item asynchronous iterator -- 异步迭代器

实现了 @ref{58b,,__aiter__()} 和 @ref{158e,,__anext__()} 方法的对象。@code{__anext__} 必须返回一个 @ref{61b,,awaitable} 对象。@ref{406,,async for} 会处理异步迭代器的 @ref{158e,,__anext__()} 方法所返回的可等待对象，直到其引发一个 @ref{1193,,StopAsyncIteration} 异常。由 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 引入。
@anchor{glossary term-attribute}@anchor{1a92}
@geindex attribute -- 属性

@item attribute -- 属性

关联到一个对象的值，可以使用点号表达式通过其名称来引用。例如，如果一个对象 @emph{o} 具有一个属性 @emph{a}，就可以用 @emph{o.a} 来引用它。
@anchor{glossary term-awaitable}@anchor{61b}
@geindex awaitable -- 可等待对象

@item awaitable -- 可等待对象

能在 @ref{2df,,await} 表达式中使用的对象。可以是 @ref{18a,,coroutine} 或是具有 @ref{73f,,__await__()} 方法的对象。参见 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492}。
@anchor{glossary term-bdfl}@anchor{4560}
@geindex BDFL

@item BDFL

“终身仁慈独裁者”的英文缩写，即 Guido van Rossum@footnote{https://gvanrossum.github.io/}，Python 的创造者。
@anchor{glossary term-binary-file}@anchor{140a}
@geindex binary file -- 二进制文件

@item binary file -- 二进制文件

@ref{c1d,,file object} 能够读写 @ref{6e9,,字节类对象}。二进制文件的例子包括以二进制模式（@code{'rb'}, @code{'wb'} or @code{'rb+'}）打开的文件、@code{sys.stdin.buffer}、@code{sys.stdout.buffer} 以及 @ref{894,,io.BytesIO} 和 @ref{207,,gzip.GzipFile} 的实例。

另请参见 @ref{1409,,text file} 了解能够读写 @ref{206,,str} 对象的文件对象。
@anchor{glossary term-bytes-like-object}@anchor{6e9}
@geindex bytes-like object -- 字节类对象

@item bytes-like object -- 字节类对象

支持 @ref{174c,,缓冲协议} 并且能导出 C-@ref{181d,,contiguous} 缓冲的对象。这包括所有 @ref{172,,bytes}、@ref{173,,bytearray} 和 @ref{217,,array.array} 对象，以及许多普通 @ref{38d,,memoryview} 对象。字节类对象可在多种二进制数据操作中使用；这些操作包括压缩、保存为二进制文件以及通过套接字发送等。

某些操作需要可变的二进制数据。这种对象在文档中常被称为“可读写字节类对象”。可变缓冲对象的例子包括 @ref{173,,bytearray} 以及 @ref{173,,bytearray} 的 @ref{38d,,memoryview}。其他操作要求二进制数据存放于不可变对象 ("只读字节类对象")；这种对象的例子包括 @ref{172,,bytes} 以及 @ref{172,,bytes} 对象的 @ref{38d,,memoryview}。
@anchor{glossary term-bytecode}@anchor{713}
@geindex bytecode -- 字节码

@item bytecode -- 字节码

Python 源代码会被编译为字节码，即 CPython 解释器中表示 Python 程序的内部代码。字节码还会缓存在 @code{.pyc} 文件中，这样第二次执行同一文件时速度更快（可以免去将源码重新编译为字节码）。这种 "中间语言" 运行在根据字节码执行相应机器码的 @ref{28bb,,virtual machine} 之上。请注意不同 Python 虚拟机上的字节码不一定通用，也不一定能在不同 Python 版本上兼容。

字节码指令列表可以在 @ref{39a3,,dis 模块} 的文档中查看。
@anchor{glossary term-callback}@anchor{2707}
@geindex callback -- 回调

@item callback -- 回调

一个作为参数被传入以用以在未来的某个时刻被调用的子例程函数。
@anchor{glossary term-class}@anchor{1033}
@geindex class -- 类

@item class -- 类

用来创建用户定义对象的模板。类定义通常包含对该类的实例进行操作的方法定义。
@anchor{glossary term-class-variable}@anchor{4561}
@geindex class variable -- 类变量

@item class variable -- 类变量

在类中定义的变量，并且仅限在类的层级上修改 (而不是在类的实例中修改)。
@anchor{glossary term-coercion}@anchor{4562}
@geindex coercion -- 强制类型转换

@item coercion -- 强制类型转换

在包含两个相同类型参数的操作中，一种类型的实例隐式地转换为另一种类型。例如，@code{int(3.15)} 是将原浮点数转换为整型数 @code{3}，但在 @code{3+4.5} 中，参数的类型不一致（一个是 int, 一个是 float），两者必须转换为相同类型才能相加，否则将引发 @ref{1ff,,TypeError}。如果没有强制类型转换机制，程序员必须将所有可兼容参数归一化为相同类型，例如要写成 @code{float(3)+4.5} 而不是 @code{3+4.5}。
@anchor{glossary term-complex-number}@anchor{4563}
@geindex complex number -- 复数

@item complex number -- 复数

对普通实数系统的扩展，其中所有数字都被表示为一个实部和一个虚部的和。虚数是虚数单位（@code{-1} 的平方根）的实倍数，通常在数学中写为 @code{i}，在工程学中写为 @code{j}。Python 内置了对复数的支持，采用工程学标记方式；虚部带有一个 @code{j} 后缀，例如 @code{3+1j}。如果需要 @ref{b1,,math} 模块内对象的对应复数版本，请使用 @ref{18,,cmath}，复数的使用是一个比较高级的数学特性。如果你感觉没有必要，忽略它们也几乎不会有任何问题。
@anchor{glossary term-context-manager}@anchor{66b}
@geindex context manager -- 上下文管理器

@item context manager -- 上下文管理器

在 @ref{7e4,,with} 语句中使用，通过定义 @ref{d65,,__enter__()} 和 @ref{d66,,__exit__()} 方法来控制环境状态的对象。参见 
@geindex Python 提高建议; PEP 343
PEP 343@footnote{https://www.python.org/dev/peps/pep-0343}。
@anchor{glossary term-context-variable}@anchor{4564}
@geindex context variable -- 上下文变量

@item context variable -- 上下文变量

一种根据其所属的上下文可以具有不同的值的变量。 这类似于在线程局部存储中每个执行线程可以具有不同的变量值。 不过，对于上下文变量来说，一个执行线程中可能会有多个上下文，而上下文变量的主要用途是对并发异步任务中变量进行追踪。 参见 @ref{24,,contextvars}。
@anchor{glossary term-contiguous}@anchor{181d}
@geindex contiguous -- 连续

@item contiguous -- 连续

@geindex C-contiguous
@geindex Fortran contiguous

一个缓冲如果是 @emph{C 连续} 或 @emph{Fortran 连续} 就会被认为是连续的。零维缓冲是 C 和 Fortran 连续的。在一维数组中，所有条目必须在内存中彼此相邻地排列，采用从零开始的递增索引顺序。在多维 C-连续数组中，当按内存地址排列时用最后一个索引访问条目时速度最快。但是在 Fortran 连续数组中则是用第一个索引最快。
@anchor{glossary term-coroutine}@anchor{18a}
@geindex coroutine -- 协程

@item coroutine -- 协程

协程是子例程的更一般形式。  子例程可以在某一点进入并在另一点退出。 协程则可以在许多不同的点上进入、退出和恢复。 它们可通过 @ref{3b1,,async def} 语句来实现。 参见 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492}。
@anchor{glossary term-coroutine-function}@anchor{73c}
@geindex coroutine function -- 协程函数

@item coroutine function -- 协程函数

返回一个 @ref{18a,,coroutine} 对象的函数。协程函数可通过 @ref{3b1,,async def} 语句来定义，并可能包含 @ref{2df,,await}、@ref{406,,async for} 和 @ref{740,,async with} 关键字。这些特性是由 
@geindex Python 提高建议; PEP 492
PEP 492@footnote{https://www.python.org/dev/peps/pep-0492} 引入的。
@anchor{glossary term-cpython}@anchor{1598}
@geindex CPython

@item CPython

Python 编程语言的规范实现，在 python.org@footnote{https://www.python.org} 上发布。"CPython" 一词用于在必要时将此实现与其他实现例如 Jython 或 IronPython 相区别。
@anchor{glossary term-decorator}@anchor{174}
@geindex decorator -- 装饰器

@item decorator -- 装饰器

返回值为另一个函数的函数，通常使用 @code{@@wrapper} 语法形式来进行函数变换。 装饰器的常见例子包括 @ref{310,,classmethod()} 和 @ref{311,,staticmethod()}。

装饰器语法只是一种语法糖，以下两个函数定义在语义上完全等价:

@example
def f(arg):
    ...
f = staticmethod(f)

@@staticmethod
def f(arg):
    ...
@end example

同的样概念也适用于类，但通常较少这样使用。有关装饰器的详情可参见 @ref{13bf,,函数定义} 和 @ref{d3a,,类定义} 的文档。
@anchor{glossary term-descriptor}@anchor{15a8}
@geindex descriptor -- 描述器

@item descriptor -- 描述器

任何定义了 @ref{159d,,__get__()}, @ref{15a1,,__set__()} 或 @ref{15a2,,__delete__()} 方法的对象。当一个类属性为描述器时，它的特殊绑定行为就会在属性查找时被触发。通常情况下，使用 @emph{a.b} 来获取、设置或删除一个属性时会在 @emph{a} 的类字典中查找名称为 @emph{b} 的对象，但如果 @emph{b} 是一个描述器，则会调用对应的描述器方法。理解描述器的概念是更深层次理解 Python 的关键，因为这是许多重要特性的基础，包括函数、方法、属性、类方法、静态方法以及对超类的引用等等。

有关描述器的方法的更多信息，请参阅 @ref{5ec,,实现描述器} 或 @ref{4359,,描述器使用指南}。
@anchor{glossary term-dictionary}@anchor{4565}
@geindex dictionary -- 字典

@item dictionary -- 字典

一个关联数组，其中的任意键都映射到相应的值。键可以是任何具有 @ref{455,,__hash__()} 和 @ref{454,,__eq__()} 方法的对象。在 Perl 语言中称为 hash。
@anchor{glossary term-dictionary-comprehension}@anchor{4566}
@geindex dictionary comprehension -- 字典推导式

@item dictionary comprehension -- 字典推导式

处理一个可迭代对象中的所有或部分元素并返回结果字典的一种紧凑写法。 @code{results = @{n: n ** 2 for n in range(10)@}} 将生成一个由键 @code{n} 到值 @code{n ** 2} 的映射构成的字典。 参见 @ref{1657,,列表、集合与字典的显示}。
@anchor{glossary term-dictionary-view}@anchor{1ae6}
@geindex dictionary view -- 字典视图

@item dictionary view -- 字典视图

从 @ref{cfc,,dict.keys()}, @ref{cfe,,dict.values()} 和 @ref{cfd,,dict.items()} 返回的对象被称为字典视图。它们提供了字典条目的一个动态视图，这意味着当字典改变时，视图也会相应改变。要将字典视图强制转换为真正的列表，可使用 @code{list(dictview)}。参见 @ref{183d,,字典视图对象}。
@anchor{glossary term-docstring}@anchor{171b}
@geindex docstring -- 文档字符串

@item docstring -- 文档字符串

作为类、函数或模块之内的第一个表达式出现的字符串字面值。它在代码执行时会被忽略，但会被解释器识别并放入所在类、函数或模块的 @code{__doc__} 属性中。由于它可用于代码内省，因此是对象存放文档的规范位置。
@anchor{glossary term-duck-typing}@anchor{455e}
@geindex duck-typing -- 鸭子类型

@item duck-typing -- 鸭子类型

指一种编程风格，它并不依靠查找对象类型来确定其是否具有正确的接口，而是直接调用或使用其方法或属性（“看起来像鸭子，叫起来也像鸭子，那么肯定就是鸭子。”）由于强调接口而非特定类型，设计良好的代码可通过允许多态替代来提升灵活性。鸭子类型避免使用 @ref{709,,type()} 或 @ref{55a,,isinstance()} 检测。(但要注意鸭子类型可以使用 @ref{c0e,,抽象基类} 作为补充。)  而往往会采用 @ref{553,,hasattr()} 检测或是 @ref{20d9,,EAFP} 编程。
@anchor{glossary term-eafp}@anchor{20d9}
@geindex EAFP

@item EAFP

“求原谅比求许可更容易”的英文缩写。这种 Python 常用代码编写风格会假定所需的键或属性存在，并在假定错误时捕获异常。这种简洁快速风格的特点就是大量运用 @ref{e3f,,try} 和 @ref{c19,,except} 语句。于其相对的则是所谓 @ref{4567,,LBYL} 风格，常见于 C 等许多其他语言。
@anchor{glossary term-expression}@anchor{15be}
@geindex expression -- 表达式

@item expression -- 表达式

可以求出某个值的语法单元。 换句话说，一个表达式就是表达元素例如字面值、名称、属性访问、运算符或函数调用的汇总，它们最终都会返回一个值。 与许多其他语言不同，并非所有语言构件都是表达式。 还存在不能被用作表达式的 @ref{1d37,,statement}，例如 @ref{1390,,while}。 赋值也是属于语句而非表达式。
@anchor{glossary term-extension-module}@anchor{4568}
@geindex extension module -- 扩展模块

@item extension module -- 扩展模块

以 C 或 C++ 编写的模块，使用 Python 的 C API 来与语言核心以及用户代码进行交互。
@anchor{glossary term-f-string}@anchor{29c}
@geindex f-string -- f-字符串

@item f-string -- f-字符串

带有 @code{'f'} 或 @code{'F'} 前缀的字符串字面值通常被称为“f-字符串”即 @ref{29d,,格式化字符串字面值} 的简写。参见 
@geindex Python 提高建议; PEP 498
PEP 498@footnote{https://www.python.org/dev/peps/pep-0498}。
@anchor{glossary term-file-object}@anchor{c1d}
@geindex file object -- 文件对象

@item file object -- 文件对象

对外提供面向文件 API 以使用下层资源的对象（带有 @code{read()} 或 @code{write()} 这样的方法）。根据其创建方式的不同，文件对象可以处理对真实磁盘文件，对其他类型存储，或是对通讯设备的访问（例如标准输入/输出、内存缓冲区、套接字、管道等等）。文件对象也被称为 @emph{文件类对象} 或 @emph{流}。

实际上共有三种类别的文件对象: 原始 @ref{140a,,二进制文件}, 缓冲 @ref{140a,,二进制文件} 以及 @ref{1409,,文本文件}。它们的接口定义均在 @ref{a1,,io} 模块中。创建文件对象的规范方式是使用 @ref{16f,,open()} 函数。
@anchor{glossary term-file-like-object}@anchor{1e0e}
@geindex file-like object -- 文件类对象

@item file-like object -- 文件类对象

@ref{c1d,,file object} 的同义词。
@anchor{glossary term-finder}@anchor{1624}
@geindex finder -- 查找器

@item finder -- 查找器

一种会尝试查找被导入模块的 @ref{1625,,loader} 的对象。

从 Python 3.3 起存在两种类型的查找器: @ref{a9a,,元路径查找器} 配合 @ref{6e7,,sys.meta_path} 使用，以及 @ref{a9b,,path entry finders} 配合 @ref{a46,,sys.path_hooks} 使用。

更多详情可参见 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}, 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 和 
@geindex Python 提高建议; PEP 451
PEP 451@footnote{https://www.python.org/dev/peps/pep-0451}。
@anchor{glossary term-floor-division}@anchor{1fa}
@geindex floor division -- 向下取整除法

@item floor division -- 向下取整除法

向下舍入到最接近的整数的数学除法。向下取整除法的运算符是 @code{//} 。例如，表达式 @code{11 // 4} 的计算结果是 @code{2} ，而与之相反的是浮点数的真正除法返回 @code{2.75} 。注意 @code{(-11) // 4} 会返回 @code{-3} 因为这是 @code{-2.75} @emph{向下} 舍入得到的结果。见 
@geindex Python 提高建议; PEP 238
PEP 238@footnote{https://www.python.org/dev/peps/pep-0238} 。
@anchor{glossary term-function}@anchor{168b}
@geindex function -- 函数

@item function -- 函数

可以向调用者返回某个值的一组语句。还可以向其传入零个或多个 @ref{168a,,参数} 并在函数体执行中被使用。另见 @ref{1693,,parameter}, @ref{455f,,method} 和 @ref{13bf,,函数定义} 等节。
@anchor{glossary term-function-annotation}@anchor{13c0}
@geindex function annotation -- 函数标注

@item function annotation -- 函数标注

即针对函数形参或返回值的 @ref{15b6,,annotation} 。

函数标注通常用于 @ref{15ba,,类型提示}：例如以下函数预期接受两个 @ref{205,,int} 参数并预期返回一个 @ref{205,,int} 值:

@example
def sum_two_numbers(a: int, b: int) -> int:
   return a + b
@end example

函数标注语法的详解见 @ref{13bf,,函数定义} 一节。

请参看 @ref{71c,,variable annotation} 和 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 对此功能的描述。
@anchor{glossary term-future}@anchor{780}
@geindex __future__

@item __future__

@ref{16f4,,future 语句}, @code{from __future__ import <feature>} 指示编译器使用将在未来的 Python 发布版中成为标准的语法和语义来编译当前模块。 @ref{0,,__future__} 模块文档记录了可能 的 @emph{feature} 取值。 通过导入此模块并对其变量求值，你可以看到每项新特性在何时被首次加入到该语言中以及它将（或已）在何时成为默认:

@example
>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
@end example
@anchor{glossary term-garbage-collection}@anchor{1013}
@geindex garbage collection -- 垃圾回收

@item garbage collection -- 垃圾回收

释放不再被使用的内存空间的过程。Python 是通过引用计数和一个能够检测和打破循环引用的循环垃圾回收器来执行垃圾回收的。可以使用 @ref{84,,gc} 模块来控制垃圾回收器。

@geindex generator
@anchor{glossary term-generator}@anchor{a8c}
@geindex generator -- 生成器

@item generator -- 生成器

返回一个 @ref{561,,generator iterator} 的函数。它看起来很像普通函数，不同点在于其包含 @ref{2ce,,yield} 表达式以便产生一系列值供给 for-循环使用或是通过 @ref{77f,,next()} 函数逐一获取。

通常是指生成器函数，但在某些情况下也可能是指 @emph{生成器迭代器}。如果需要清楚表达具体含义，请使用全称以避免歧义。
@anchor{glossary term-generator-iterator}@anchor{561}
@geindex generator iterator -- 生成器迭代器

@item generator iterator -- 生成器迭代器

@ref{a8c,,generator} 函数所创建的对象。

每个 @ref{2ce,,yield} 会临时暂停处理，记住当前位置执行状态（包括局部变量和挂起的 try 语句）。当该 @emph{生成器迭代器} 恢复时，它会从离开位置继续执行（这与每次调用都从新开始的普通函数差别很大）。

@geindex generator expression
@anchor{glossary term-generator-expression}@anchor{4569}
@geindex generator expression -- 生成器表达式

@item generator expression -- 生成器表达式

返回一个迭代器的表达式。 它看起来很像普通表达式后面带有定义了一个循环变量、范围的 @code{for} 子句，以及一个可选的 @code{if} 子句。 以下复合表达式会为外层函数生成一系列值:

@example
>>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
285
@end example
@anchor{glossary term-generic-function}@anchor{303}
@geindex generic function -- 泛型函数

@item generic function -- 泛型函数

为不同的类型实现相同操作的多个函数所组成的函数。在调用时会由调度算法来确定应该使用哪个实现。

另请参见 @ref{302,,single dispatch} 术语表条目、@ref{499,,functools.singledispatch()} 装饰器以及 
@geindex Python 提高建议; PEP 443
PEP 443@footnote{https://www.python.org/dev/peps/pep-0443}。
@anchor{glossary term-generic-type}@anchor{1035}
@geindex generic type -- 泛型类型

@item generic type -- 泛型类型

可被形参化的 @ref{1034,,type}；通常为诸如 @ref{1f9,,list} 和 @ref{164,,dict} 的 @ref{15c3,,container class}。 可用于 @ref{15ba,,类型注解} 和 @ref{15b6,,标注}。

更多细节，请参见 @ref{1030,,通用别名类型}, 
@geindex Python 提高建议; PEP 483
PEP 483@footnote{https://www.python.org/dev/peps/pep-0483} , 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} , 
@geindex Python 提高建议; PEP 585
PEP 585@footnote{https://www.python.org/dev/peps/pep-0585} , 和 @ref{122,,typing} 模块。
@anchor{glossary term-gil}@anchor{20f}
@geindex GIL

@item GIL

参见 @ref{60b,,global interpreter lock}。
@anchor{glossary term-global-interpreter-lock}@anchor{60b}
@geindex global interpreter lock -- 全局解释器锁

@item global interpreter lock -- 全局解释器锁

@ref{1598,,CPython} 解释器所采用的一种机制，它确保同一时刻只有一个线程在执行 Python @ref{713,,bytecode}。此机制通过设置对象模型（包括 @ref{164,,dict} 等重要内置类型）针对并发访问的隐式安全简化了 CPython 实现。给整个解释器加锁使得解释器多线程运行更方便，其代价则是牺牲了在多处理器上的并行性。

不过，某些标准库或第三方库的扩展模块被设计为在执行计算密集型任务如压缩或哈希时释放 GIL。此外，在执行 I/O 操作时也总是会释放 GIL。

创建一个（以更精细粒度来锁定共享数据的）“自由线程”解释器的努力从未获得成功，因为这会牺牲在普通单处理器情况下的性能。据信克服这种性能问题的措施将导致实现变得更复杂，从而更难以维护。
@anchor{glossary term-hash-based-pyc}@anchor{456a}
@geindex hash-based pyc -- 基于哈希的 pyc

@item hash-based pyc -- 基于哈希的 pyc

使用对应源文件的哈希值而非最后修改时间来确定其有效性的字节码缓存文件。 参见 @ref{442,,已缓存字节码的失效}。
@anchor{glossary term-hashable}@anchor{277}
@geindex hashable -- 可哈希

@item hashable -- 可哈希

一个对象的哈希值如果在其生命周期内绝不改变，就被称为 @emph{可哈希} （它需要具有 @ref{455,,__hash__()} 方法），并可以同其他对象进行比较（它需要具有 @ref{454,,__eq__()} 方法）。可哈希对象必须具有相同的哈希值比较结果才会相同。

可哈希性使得对象能够作为字典键或集合成员使用，因为这些数据结构要在内部使用哈希值。

大多数 Python 中的不可变内置对象都是可哈希的；可变容器（例如列表或字典）都不可哈希；不可变容器（例如元组和 frozenset）仅当它们的元素均为可哈希时才是可哈希的。 用户定义类的实例对象默认是可哈希的。 它们在比较时一定不相同（除非是与自己比较），它们的哈希值的生成是基于它们的 @ref{e53,,id()}。
@anchor{glossary term-idle}@anchor{456b}
@geindex IDLE

@item IDLE

Python 的 IDE，“集成开发与学习环境”的英文缩写。是 Python 标准发行版附带的基本编辑器和解释器环境。
@anchor{glossary term-immutable}@anchor{1385}
@geindex immutable -- 不可变

@item immutable -- 不可变

具有固定值的对象。不可变对象包括数字、字符串和元组。这样的对象不能被改变。如果必须存储一个不同的值，则必须创建新的对象。它们在需要常量哈希值的地方起着重要作用，例如作为字典中的键。
@anchor{glossary term-import-path}@anchor{1627}
@geindex import path -- 导入路径

@item import path -- 导入路径

由多个位置（或 @ref{163a,,路径条目}）组成的列表，会被模块的 @ref{162a,,path based finder} 用来查找导入目标。在导入时，此位置列表通常来自 @ref{262,,sys.path}，但对次级包来说也可能来自上级包的 @code{__path__} 属性。
@anchor{glossary term-importing}@anchor{1617}
@geindex importing -- 导入

@item importing -- 导入

令一个模块中的 Python 代码能为另一个模块中的 Python 代码所使用的过程。
@anchor{glossary term-importer}@anchor{1626}
@geindex importer -- 导入器

@item importer -- 导入器

查找并加载模块的对象；此对象既属于 @ref{1624,,finder} 又属于 @ref{1625,,loader}。
@anchor{glossary term-interactive}@anchor{456c}
@geindex interactive -- 交互

@item interactive -- 交互

Python 带有一个交互式解释器，即你可以在解释器提示符后输入语句和表达式，立即执行并查看其结果。只需不带参数地启动 @code{python} 命令（也可以在你的计算机开始菜单中选择相应菜单项）。在测试新想法或检验模块和包的时候用这种方式会非常方便（请记得使用 @code{help(x)}）。
@anchor{glossary term-interpreted}@anchor{456d}
@geindex interpreted -- 解释型

@item interpreted -- 解释型

Python 一是种解释型语言，与之相对的是编译型语言，虽然两者的区别由于字节码编译器的存在而会有所模糊。这意味着源文件可以直接运行而不必显式地创建可执行文件再运行。解释型语言通常具有比编译型语言更短的开发/调试周期，但是其程序往往运行得更慢。参见 @ref{456c,,interactive}。
@anchor{glossary term-interpreter-shutdown}@anchor{85c}
@geindex interpreter shutdown -- 解释器关闭

@item interpreter shutdown -- 解释器关闭

当被要求关闭时，Python 解释器将进入一个特殊运行阶段并逐步释放所有已分配资源，例如模块和各种关键内部结构等。它还会多次调用 @ref{1013,,垃圾回收器}。这会触发用户定义析构器或弱引用回调中的代码执行。在关闭阶段执行的代码可能会遇到各种异常，因为其所依赖的资源已不再有效（常见的例子有库模块或警告机制等）。

解释器需要关闭的主要原因有 @code{__main__} 模块或所运行的脚本已完成执行。
@anchor{glossary term-iterable}@anchor{c84}
@geindex iterable -- 可迭代对象

@item iterable -- 可迭代对象

能够逐一返回其成员项的对象。 可迭代对象的例子包括所有序列类型 (例如 @ref{1f9,,list}, @ref{206,,str} 和 @ref{1a2,,tuple}) 以及某些非序列类型例如 @ref{164,,dict}, @ref{c1d,,文件对象} 以及定义了 @ref{611,,__iter__()} 方法或是实现了 @ref{138b,,序列} 语义的 @ref{3ad,,__getitem__()} 方法的任意自定义类对象。

可迭代对象被可用于 @ref{d02,,for} 循环以及许多其他需要一个序列的地方（@ref{d04,,zip()}、@ref{cff,,map()} ...）。当一个可迭代对象作为参数传给内置函数 @ref{df5,,iter()} 时，它会返回该对象的迭代器。这种迭代器适用于对值集合的一次性遍历。在使用可迭代对象时，你通常不需要调用 @ref{df5,,iter()} 或者自己处理迭代器对象。@code{for} 语句会为你自动处理那些操作，创建一个临时的未命名变量用来在循环期间保存迭代器。参见 @ref{11ba,,iterator}、@ref{138b,,sequence} 以及 @ref{a8c,,generator}。
@anchor{glossary term-iterator}@anchor{11ba}
@geindex iterator -- 迭代器

@item iterator -- 迭代器

用来表示一连串数据流的对象。重复调用迭代器的 @ref{d34,,__next__()} 方法（或将其传给内置函数 @ref{77f,,next()}）将逐个返回流中的项。当没有数据可用时则将引发 @ref{58a,,StopIteration} 异常。到这时迭代器对象中的数据项已耗尽，继续调用其 @code{__next__()} 方法只会再次引发 @ref{58a,,StopIteration} 异常。迭代器必须具有 @ref{611,,__iter__()} 方法用来返回该迭代器对象自身，因此迭代器必定也是可迭代对象，可被用于其他可迭代对象适用的大部分场合。一个显著的例外是那些会多次重复访问迭代项的代码。容器对象（例如 @ref{1f9,,list}）在你每次向其传入 @ref{df5,,iter()} 函数或是在 @ref{d02,,for} 循环中使用它时都会产生一个新的迭代器。如果在此情况下你尝试用迭代器则会返回在之前迭代过程中被耗尽的同一迭代器对象，使其看起来就像是一个空容器。

更多信息可查看 @ref{15c9,,迭代器类型}。
@anchor{glossary term-key-function}@anchor{7dc}
@geindex key function -- 键函数

@item key function -- 键函数

键函数或称整理函数，是能够返回用于排序或排位的值的可调用对象。例如，@ref{30a1,,locale.strxfrm()} 可用于生成一个符合特定区域排序约定的排序键。

Python 中有许多工具都允许用键函数来控制元素的排位或分组方式。其中包括 @ref{900,,min()}, @ref{901,,max()}, @ref{54f,,sorted()}, @ref{550,,list.sort()}, @ref{7db,,heapq.merge()}, @ref{1afb,,heapq.nsmallest()}, @ref{1afa,,heapq.nlargest()} 以及 @ref{1ce5,,itertools.groupby()}。

要创建一个键函数有多种方式。例如，@ref{17a7,,str.lower()} 方法可以用作忽略大小写排序的键函数。另外，键函数也可通过 @ref{d01,,lambda} 表达式来创建，例如 @code{lambda r: (r[0], r[2])}。还有 @ref{c2,,operator} 模块提供了三个键函数构造器：@ref{814,,attrgetter()}、@ref{393,,itemgetter()} 和 @ref{815,,methodcaller()}。请查看 @ref{1767,,如何排序} 一节以获取创建和使用键函数的示例。
@anchor{glossary term-keyword-argument}@anchor{6c5}
@geindex keyword argument -- 关键字参数

@item keyword argument -- 关键字参数

参见 @ref{168a,,argument}。
@anchor{glossary term-lambda}@anchor{1cf0}
@geindex lambda

@item lambda

由一个单独 @ref{15be,,expression} 构成的匿名内联函数，表达式会在调用时被求值。创建 lambda 函数的句法为 @code{lambda [parameters]: expression}
@anchor{glossary term-lbyl}@anchor{4567}
@geindex LBYL

@item LBYL

“先查看后跳跃”的英文缩写。这种代码编写风格会在进行调用或查找之前显式地检查前提条件。此风格与 @ref{20d9,,EAFP} 方式恰成对比，其特点是大量使用 @ref{eb3,,if} 语句。

在多线程环境中，LBYL 方式会导致“查看”和“跳跃”之间发生条件竞争风险。例如，以下代码 @code{if key in mapping: return mapping[key]} 可能由于在检查操作之后其他线程从 @emph{mapping} 中移除了 @emph{key} 而出错。这种问题可通过加锁或使用 EAFP 方式来解决。
@anchor{glossary term-list}@anchor{456e}
@geindex list -- 列表

@item list -- 列表

Python 内置的一种 @ref{138b,,sequence}。虽然名为列表，但更类似于其他语言中的数组而非链接列表，因为访问元素的时间复杂度为 O(1)。
@anchor{glossary term-list-comprehension}@anchor{456f}
@geindex list comprehension -- 列表推导式

@item list comprehension -- 列表推导式

处理一个序列中的所有或部分元素并返回结果列表的一种紧凑写法。@code{result = ['@{:#04x@}'.format(x) for x in range(256) if x % 2 == 0]} 将生成一个 0 到 255 范围内的十六进制偶数对应字符串（0x..）的列表。其中 @ref{eb3,,if} 子句是可选的，如果省略则 @code{range(256)} 中的所有元素都会被处理。
@anchor{glossary term-loader}@anchor{1625}
@geindex loader -- 加载器

@item loader -- 加载器

负责加载模块的对象。它必须定义名为 @code{load_module()} 的方法。加载器通常由一个 @ref{1624,,finder} 返回。详情参见 
@geindex Python 提高建议; PEP 302
PEP 302@footnote{https://www.python.org/dev/peps/pep-0302}，对于 @ref{c0e,,abstract base class} 可参见 @ref{8b9,,importlib.abc.Loader}。
@anchor{glossary term-magic-method}@anchor{4570}
@geindex magic method -- 魔术方法

@item magic method -- 魔术方法

@geindex magic; method

@ref{36ec,,special method} 的非正式同义词 。
@anchor{glossary term-mapping}@anchor{c14}
@geindex mapping -- 映射

@item mapping -- 映射

一种支持任意键查找并实现了 @ref{15f,,Mapping} 或 @ref{ad7,,MutableMapping} @ref{15e,,抽象基类} 中所规定方法的容器对象。 此类对象的例子包括 @ref{164,,dict}, @ref{c15,,collections.defaultdict}, @ref{2f1,,collections.OrderedDict} 以及 @ref{ac2,,collections.Counter}。
@anchor{glossary term-meta-path-finder}@anchor{a9a}
@geindex meta path finder -- 元路径查找器

@item meta path finder -- 元路径查找器

@ref{6e7,,sys.meta_path} 的搜索所返回的 @ref{1624,,finder}。元路径查找器与 @ref{a9b,,path entry finders} 存在关联但并不相同。

请查看 @ref{a9c,,importlib.abc.MetaPathFinder} 了解元路径查找器所实现的方法。
@anchor{glossary term-metaclass}@anchor{15bf}
@geindex metaclass -- 元类

@item metaclass -- 元类

一种用于创建类的类。类定义包含类名、类字典和基类列表。元类负责接受上述三个参数并创建相应的类。大部分面向对象的编程语言都会提供一个默认实现。Python 的特别之处在于可以创建自定义元类。大部分用户永远不需要这个工具，但当需要出现时，元类可提供强大而优雅的解决方案。它们已被用于记录属性访问日志、添加线程安全性、跟踪对象创建、实现单例，以及其他许多任务。

更多详情参见 @ref{15ab,,元类}。
@anchor{glossary term-method}@anchor{455f}
@geindex method -- 方法

@item method -- 方法

在类内部定义的函数。如果作为该类的实例的一个属性来调用，方法将会获取实例对象作为其第一个 @ref{168a,,argument} (通常命名为 @code{self})。参见 @ref{168b,,function} 和 @ref{1751,,nested scope}。
@anchor{glossary term-method-resolution-order}@anchor{1769}
@geindex method resolution order -- 方法解析顺序

@item method resolution order -- 方法解析顺序

方法解析顺序就是在查找成员时搜索全部基类所用的先后顺序。请查看 Python 2.3 方法解析顺序@footnote{https://www.python.org/download/releases/2.3/mro/} 了解自 2.3 版起 Python 解析器所用相关算法的详情。
@anchor{glossary term-module}@anchor{1616}
@geindex module -- 模块

@item module -- 模块

此对象是 Python 代码的一种组织单位。各模块具有独立的命名空间，可包含任意 Python 对象。模块可通过 @ref{1617,,importing} 操作被加载到 Python 中。

另见 @ref{161a,,package}。
@anchor{glossary term-module-spec}@anchor{36c1}
@geindex module spec -- 模块规格

@item module spec -- 模块规格

一个命名空间，其中包含用于加载模块的相关导入信息。是 @ref{1630,,importlib.machinery.ModuleSpec} 的实例。
@anchor{glossary term-mro}@anchor{29b3}
@geindex MRO

@item MRO

参见 @ref{1769,,method resolution order}。
@anchor{glossary term-mutable}@anchor{138d}
@geindex mutable -- 可变对象

@item mutable -- 可变对象

可变对象可以在其 @ref{e53,,id()} 保持固定的情况下改变其取值。另请参见 @ref{1385,,immutable}。
@anchor{glossary term-named-tuple}@anchor{b84}
@geindex named tuple -- 具名元组

@item named tuple -- 具名元组

术语“具名元组”可用于任何继承自元组，并且其中的可索引元素还能使用名称属性来访问的类型或类。 这样的类型或类还可能拥有其他特性。

有些内置类型属于具名元组，包括 @ref{10c9,,time.localtime()} 和 @ref{328,,os.stat()} 的返回值。 另一个例子是 @ref{1145,,sys.float_info}:

@example
>>> sys.float_info[1]                   # indexed access
1024
>>> sys.float_info.max_exp              # named field access
1024
>>> isinstance(sys.float_info, tuple)   # kind of tuple
True
@end example

有些具名元组是内置类型（例如上面的例子）。 此外，具名元组还可通过常规类定义从 @ref{1a2,,tuple} 继承并定义名称字段的方式来创建。 这样的类可以手工编写，或者使用工厂函数 @ref{1a1,,collections.namedtuple()} 创建。 后一种方式还会添加一些手工编写或内置具名元组所没有的额外方法。
@anchor{glossary term-namespace}@anchor{4571}
@geindex namespace -- 命名空间

@item namespace -- 命名空间

命名空间是存放变量的场所。命名空间有局部、全局和内置的，还有对象中的嵌套命名空间（在方法之内）。命名空间通过防止命名冲突来支持模块化。例如，函数 @ref{16f,,builtins.open} 与 @ref{762,,os.open()} 可通过各自的命名空间来区分。命名空间还通过明确哪个模块实现那个函数来帮助提高可读性和可维护性。例如，@ref{cdb,,random.seed()} 或 @ref{4b1,,itertools.islice()} 这种写法明确了这些函数是由 @ref{dc,,random} 与 @ref{a3,,itertools} 模块分别实现的。
@anchor{glossary term-namespace-package}@anchor{161d}
@geindex namespace package -- 命名空间包

@item namespace package -- 命名空间包

@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420} 所引入的一种仅被用作子包的容器的 @ref{161a,,package}，命名空间包可以没有实体表示物，其描述方式与 @ref{161c,,regular package} 不同，因为它们没有 @code{__init__.py} 文件。

另可参见 @ref{1616,,module}。
@anchor{glossary term-nested-scope}@anchor{1751}
@geindex nested scope -- 嵌套作用域

@item nested scope -- 嵌套作用域

在一个定义范围内引用变量的能力。例如，在另一函数之内定义的函数可以引用前者的变量。请注意嵌套作用域默认只对引用有效而对赋值无效。局部变量的读写都受限于最内层作用域。类似的，全局变量的读写则作用于全局命名空间。通过 @ref{d0f,,nonlocal} 关键字可允许写入外层作用域。
@anchor{glossary term-new-style-class}@anchor{1e50}
@geindex new-style class -- 新式类

@item new-style class -- 新式类

对于目前已被应于所有类对象的类形式的旧称谓。在早先的 Python 版本中，只有新式类能够使用 Python 新增的更灵活特性，例如 @ref{ef7,,__slots__}、描述符、特征属性、@ref{552,,__getattribute__()}、类方法和静态方法等。
@anchor{glossary term-object}@anchor{4572}
@geindex object -- 对象

@item object -- 对象

任何具有状态（属性或值）以及预定义行为（方法）的数据。object 也是任何 @ref{1e50,,new-style class} 的最顶层基类名。
@anchor{glossary term-package}@anchor{161a}
@geindex package -- 包

@item package -- 包

一种可包含子模块或递归地包含子包的 Python @ref{1616,,module}。从技术上说，包是带有 @code{__path__} 属性的 Python 模块。

另参见 @ref{161c,,regular package} 和 @ref{161d,,namespace package}。
@anchor{glossary term-parameter}@anchor{1693}
@geindex parameter -- 形参

@item parameter -- 形参

@ref{168b,,function} （或方法）定义中的命名实体，它指定函数可以接受的一个 @ref{168a,,argument} （或在某些情况下，多个实参）。有五种形参：


@itemize *

@item 
@emph{positional-or-keyword}：位置或关键字，指定一个可以作为 @ref{168a,,位置参数} 传入也可以作为 @ref{168a,,关键字参数} 传入的实参。这是默认的形参类型，例如下面的 @emph{foo} 和 @emph{bar}:

@example
def func(foo, bar=None): ...
@end example
@end itemize
@anchor{glossary positional-only-parameter}@anchor{3d1}

@itemize *

@item 
@emph{positional-only}：仅限位置，指定一个只能通过位置传入的参数。 仅限位置形参可通过在函数定义的形参列表中它们之后包含一个 @code{/} 字符来定义，例如下面的 @emph{posonly1} 和 @emph{posonly2}:

@example
def func(posonly1, posonly2, /, positional_or_keyword): ...
@end example
@end itemize
@anchor{glossary keyword-only-parameter}@anchor{3d6}

@itemize *

@item 
@emph{keyword-only}：仅限关键字，指定一个只能通过关键字传入的参数。仅限关键字形参可通过在函数定义的形参列表中包含单个可变位置形参或者在多个可变位置形参之前放一个 @code{*} 来定义，例如下面的 @emph{kw_only1} 和 @emph{kw_only2}:

@example
def func(arg, *, kw_only1, kw_only2): ...
@end example

@item 
@emph{var-positional}：可变位置，指定可以提供由一个任意数量的位置参数构成的序列（附加在其他形参已接受的位置参数之后）。这种形参可通过在形参名称前加缀 @code{*} 来定义，例如下面的 @emph{args}:

@example
def func(*args, **kwargs): ...
@end example

@item 
@emph{var-keyword}：可变关键字，指定可以提供任意数量的关键字参数（附加在其他形参已接受的关键字参数之后）。这种形参可通过在形参名称前加缀 @code{**} 来定义，例如上面的 @emph{kwargs}。
@end itemize

形参可以同时指定可选和必选参数，也可以为某些可选参数指定默认值。

另参见 @ref{168a,,argument} 术语表条目、@ref{44ae,,参数与形参的区别} 中的常见问题、@ref{7ef,,inspect.Parameter} 类、@ref{13bf,,函数定义} 一节以及 
@geindex Python 提高建议; PEP 362
PEP 362@footnote{https://www.python.org/dev/peps/pep-0362}。
@anchor{glossary term-path-entry}@anchor{163a}
@geindex path entry -- 路径入口

@item path entry -- 路径入口

@ref{1627,,import path} 中的一个单独位置，会被 @ref{162a,,path based finder} 用来查找要导入的模块。
@anchor{glossary term-path-entry-finder}@anchor{a9b}
@geindex path entry finder -- 路径入口查找器

@item path entry finder -- 路径入口查找器

任一可调用对象使用 @ref{a46,,sys.path_hooks} (即 @ref{163c,,path entry hook}) 返回的 @ref{1624,,finder}，此种对象能通过 @ref{163a,,path entry} 来定位模块。

请参看 @ref{a9d,,importlib.abc.PathEntryFinder} 以了解路径入口查找器所实现的各个方法。
@anchor{glossary term-path-entry-hook}@anchor{163c}
@geindex path entry hook -- 路径入口钩子

@item path entry hook -- 路径入口钩子

一种可调用对象，在知道如何查找特定 @ref{163a,,path entry} 中的模块的情况下能够使用 @code{sys.path_hook} 列表返回一个 @ref{a9b,,path entry finder}。
@anchor{glossary term-path-based-finder}@anchor{162a}
@geindex path based finder -- 基于路径的查找器

@item path based finder -- 基于路径的查找器

默认的一种 @ref{a9a,,元路径查找器}，可在一个 @ref{1627,,import path} 中查找模块。
@anchor{glossary term-path-like-object}@anchor{47b}
@geindex path-like object -- 路径类对象

@item path-like object -- 路径类对象

代表一个文件系统路径的对象。类路径对象可以是一个表示路径的 @ref{206,,str} 或者 @ref{172,,bytes} 对象，还可以是一个实现了 @ref{5ee,,os.PathLike} 协议的对象。一个支持 @ref{5ee,,os.PathLike} 协议的对象可通过调用 @ref{5f0,,os.fspath()} 函数转换为 @ref{206,,str} 或者 @ref{172,,bytes} 类型的文件系统路径；@ref{5f1,,os.fsdecode()} 和 @ref{5f2,,os.fsencode()} 可被分别用来确保获得 @ref{206,,str} 或 @ref{172,,bytes} 类型的结果。此对象是由 
@geindex Python 提高建议; PEP 519
PEP 519@footnote{https://www.python.org/dev/peps/pep-0519} 引入的。
@anchor{glossary term-pep}@anchor{4573}
@geindex PEP

@item PEP

“Python 增强提议”的英文缩写。一个 PEP 就是一份设计文档，用来向 Python 社区提供信息，或描述一个 Python 的新增特性及其进度或环境。PEP 应当提供精确的技术规格和所提议特性的原理说明。

PEP 应被作为提出主要新特性建议、收集社区对特定问题反馈以及为必须加入 Python 的设计决策编写文档的首选机制。PEP 的作者有责任在社区内部建立共识，并应将不同意见也记入文档。

参见 
@geindex Python 提高建议; PEP 1
PEP 1@footnote{https://www.python.org/dev/peps/pep-0001}。
@anchor{glossary term-portion}@anchor{161f}
@geindex portion -- 部分

@item portion -- 部分

构成一个命名空间包的单个目录内文件集合（也可能存放于一个 zip 文件内），具体定义见 
@geindex Python 提高建议; PEP 420
PEP 420@footnote{https://www.python.org/dev/peps/pep-0420}。
@anchor{glossary term-positional-argument}@anchor{6c6}
@geindex positional argument -- 位置参数

@item positional argument -- 位置参数

参见 @ref{168a,,argument}。
@anchor{glossary term-provisional-api}@anchor{45d}
@geindex provisional API -- 暂定 API

@item provisional API -- 暂定 API

暂定 API 是指被有意排除在标准库的向后兼容性保证之外的应用编程接口。虽然此类接口通常不会再有重大改变，但只要其被标记为暂定，就可能在核心开发者确定有必要的情况下进行向后不兼容的更改（甚至包括移除该接口）。此种更改并不会随意进行 -- 仅在 API 被加入之前未考虑到的严重基础性缺陷被发现时才可能会这样做。

即便是对暂定 API 来说，向后不兼容的更改也会被视为“最后的解决方案” —— 任何问题被确认时都会尽可能先尝试找到一种向后兼容的解决方案。

这种处理过程允许标准库持续不断地演进，不至于被有问题的长期性设计缺陷所困。详情见 
@geindex Python 提高建议; PEP 411
PEP 411@footnote{https://www.python.org/dev/peps/pep-0411}。
@anchor{glossary term-provisional-package}@anchor{a6a}
@geindex provisional package -- 暂定包

@item provisional package -- 暂定包

参见 @ref{45d,,provisional API}。
@anchor{glossary term-python-3000}@anchor{4574}
@geindex Python 3000

@item Python 3000

Python 3.x 发布路线的昵称（这个名字在版本 3 的发布还遥遥无期的时候就已出现了）。有时也被缩写为“Py3k”。
@anchor{glossary term-pythonic}@anchor{4575}
@geindex Pythonic

@item Pythonic

指一个思路或一段代码紧密遵循了 Python 语言最常用的风格和理念，而不是使用其他语言中通用的概念来实现代码。例如，Python 的常用风格是使用 @ref{d02,,for} 语句循环来遍历一个可迭代对象中的所有元素。许多其他语言没有这样的结构，因此不熟悉 Python 的人有时会选择使用一个数字计数器:

@example
for i in range(len(food)):
    print(food[i])
@end example

而相应的更简洁更 Pythonic 的方法是这样的:

@example
for piece in food:
    print(piece)
@end example
@anchor{glossary term-qualified-name}@anchor{158b}
@geindex qualified name -- 限定名称

@item qualified name -- 限定名称

一个以点号分隔的名称，显示从模块的全局作用域到该模块中定义的某个类、函数或方法的“路径”，相关定义见 
@geindex Python 提高建议; PEP 3155
PEP 3155@footnote{https://www.python.org/dev/peps/pep-3155}。对于最高层级的函数和类，限定名称与对象名称一致:

@example
>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
@end example

当被用于引用模块时，@emph{完整限定名称} 意为标示该模块的以点号分隔的整个路径，其中包含其所有的父包，例如 @code{email.mime.text}:

@example
>>> import email.mime.text
>>> email.mime.text.__name__
'email.mime.text'
@end example
@anchor{glossary term-reference-count}@anchor{3d8a}
@geindex reference count -- 引用计数

@item reference count -- 引用计数

对特定对象的引用的数量。当一个对象的引用计数降为零时，所分配资源将被释放。引用计数对 Python 代码来说通常是不可见的，但它是 @ref{1598,,CPython} 实现的一个关键元素。@ref{fd,,sys} 模块定义了一个 @ref{36bb,,getrefcount()} 函数，程序员可调用它来返回特定对象的引用计数。
@anchor{glossary term-regular-package}@anchor{161c}
@geindex regular package -- 常规包

@item regular package -- 常规包

传统型的 @ref{161a,,package}，例如包含有一个 @code{__init__.py} 文件的目录。

另参见 @ref{161d,,namespace package}。
@anchor{glossary term-slots}@anchor{3822}
@geindex __slots__

@item __slots__

一种写在类内部的声明，通过预先声明实例属性等对象并移除实例字典来节省内存。虽然这种技巧很流行，但想要用好却并不容易，最好是只保留在少数情况下采用，例如极耗内存的应用程序，并且其中包含大量实例。
@anchor{glossary term-sequence}@anchor{138b}
@geindex sequence -- 序列

@item sequence -- 序列

一种 @ref{c84,,iterable}，它支持通过 @ref{3ad,,__getitem__()} 特殊方法来使用整数索引进行高效的元素访问，并定义了一个返回序列长度的 @ref{e98,,__len__()} 方法。内置的序列类型有 @ref{1f9,,list}、@ref{206,,str}、@ref{1a2,,tuple} 和 @ref{172,,bytes}。注意虽然 @ref{164,,dict} 也支持 @ref{3ad,,__getitem__()} 和 @ref{e98,,__len__()}，但它被认为属于映射而非序列，因为它查找时使用任意的 @ref{1385,,immutable} 键而非整数。

@ref{1794,,collections.abc.Sequence} 抽象基类定义了一个更丰富的接口，它在 @ref{3ad,,__getitem__()} 和 @ref{e98,,__len__()} 之外又添加了 @code{count()}, @code{index()}, @ref{df6,,__contains__()} 和 @ref{631,,__reversed__()}。 实现此扩展接口的类型可以使用 @ref{ab9,,register()} 来显式地注册。
@anchor{glossary term-set-comprehension}@anchor{4576}
@geindex set comprehension -- 集合推导式

@item set comprehension -- 集合推导式

处理一个可迭代对象中的所有或部分元素并返回结果集合的一种紧凑写法。 @code{results = @{c for c in 'abracadabra' if c not in 'abc'@}} 将生成字符串集合 @code{@{'r', 'd'@}}。 参见 @ref{1657,,列表、集合与字典的显示}。
@anchor{glossary term-single-dispatch}@anchor{302}
@geindex single dispatch -- 单分派

@item single dispatch -- 单分派

一种 @ref{303,,generic function} 分派形式，其实现是基于单个参数的类型来选择的。
@anchor{glossary term-slice}@anchor{1766}
@geindex slice -- 切片

@item slice -- 切片

通常只包含了特定 @ref{138b,,sequence} 的一部分的对象。切片是通过使用下标标记来创建的，在 @code{[]} 中给出几个以冒号分隔的数字，例如 @code{variable_name[1:3:5]}。方括号（下标）标记在内部使用 @ref{ed0,,slice} 对象。
@anchor{glossary term-special-method}@anchor{36ec}
@geindex special method -- 特殊方法

@item special method -- 特殊方法

@geindex special; method

一种由 Python 隐式调用的方法，用来对某个类型执行特定操作例如相加等等。这种方法的名称的首尾都为双下划线。特殊方法的文档参见 @ref{610,,特殊方法名称}。
@anchor{glossary term-statement}@anchor{1d37}
@geindex statement -- 语句

@item statement -- 语句

语句是程序段（一个代码“块”）的组成单位。一条语句可以是一个 @ref{15be,,expression} 或某个带有关键字的结构，例如 @ref{eb3,,if}、@ref{1390,,while} 或 @ref{d02,,for}。
@anchor{glossary term-text-encoding}@anchor{1761}
@geindex text encoding -- 文本编码

@item text encoding -- 文本编码

在Python中，一个字符串是一串 Unicode 代码点（范围为`@w{`}U+0000`@w{`}--@code{U+10FFFF}）。为了存储或传输一个字符串，它需要被序列化为一串字节。

将一个字符串序列化为一个字节序列被称为 "编码"，而从字节序列中重新创建字符串被称为 "解码"。

有各种不同的文本序列化 @ref{78c,,编码器} ，它们被统称为 "文本编码"。
@anchor{glossary term-text-file}@anchor{1409}
@geindex text file -- 文本文件

@item text file -- 文本文件

一种能够读写 @ref{206,,str} 对象的 @ref{c1d,,file object}。通常一个文本文件实际是访问一个面向字节的数据流并自动处理 @ref{1761,,text encoding}。文本文件的例子包括以文本模式（@code{'r'} 或 @code{'w'}）打开的文件、@ref{427,,sys.stdin}、@ref{428,,sys.stdout} 以及 @ref{924,,io.StringIO} 的实例。

另请参看 @ref{140a,,binary file} 了解能够读写 @ref{6e9,,字节类对象} 的文件对象。
@anchor{glossary term-triple-quoted-string}@anchor{4577}
@geindex triple-quoted string -- 三引号字符串

@item triple-quoted string -- 三引号字符串

首尾各带三个连续双引号（"）或者单引号（'）的字符串。它们在功能上与首尾各用一个引号标注的字符串没有什么不同，但是有多种用处。它们允许你在字符串内包含未经转义的单引号和双引号，并且可以跨越多行而无需使用连接符，在编写文档字符串时特别好用。
@anchor{glossary term-type}@anchor{1034}
@geindex type -- 类型

@item type -- 类型

类型决定一个 Python 对象属于什么种类；每个对象都具有一种类型。要知道对象的类型，可以访问它的 @ref{ed4,,__class__} 属性，或是通过 @code{type(obj)} 来获取。
@anchor{glossary term-type-alias}@anchor{4578}
@geindex type alias -- 类型别名

@item type alias -- 类型别名

一个类型的同义词，创建方式是把类型赋值给特定的标识符。

类型别名的作用是简化 @ref{15ba,,类型提示}。例如:

@example
def remove_gray_shades(
        colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
    pass
@end example

可以这样提高可读性:

@example
Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:
    pass
@end example

参见 @ref{122,,typing} 和 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484}，其中有对此功能的详细描述。
@anchor{glossary term-type-hint}@anchor{15ba}
@geindex type hint -- 类型提示

@item type hint -- 类型提示

@ref{15b6,,annotation} 为变量、类属性、函数的形参或返回值指定预期的类型。

类型提示属于可选项，Python 不要求提供，但其可对静态类型分析工具起作用，并可协助 IDE 实现代码补全与重构。

全局变量、类属性和函数的类型提示可以使用 @ref{1f0,,typing.get_type_hints()} 来访问，但局部变量则不可以。

参见 @ref{122,,typing} 和 
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484}，其中有对此功能的详细描述。
@anchor{glossary term-universal-newlines}@anchor{6f5}
@geindex universal newlines -- 通用换行

@item universal newlines -- 通用换行

一种解读文本流的方式，将以下所有符号都识别为行结束标志：Unix 的行结束约定 @code{'\n'}、Windows 的约定 @code{'\r\n'} 以及旧版 Macintosh 的约定 @code{'\r'}。参见 
@geindex Python 提高建议; PEP 278
PEP 278@footnote{https://www.python.org/dev/peps/pep-0278} 和 
@geindex Python 提高建议; PEP 3116
PEP 3116@footnote{https://www.python.org/dev/peps/pep-3116} 和 @ref{180b,,bytes.splitlines()} 了解更多用法说明。
@anchor{glossary term-variable-annotation}@anchor{71c}
@geindex variable annotation -- 变量注解

@item variable annotation -- 变量注解

对变量或类属性的 @ref{15b6,,annotation}。

在标注变量或类属性时，还可选择为其赋值:

@example
class C:
    field: 'annotation'
@end example

变量标注通常被用作 @ref{15ba,,类型提示}：例如以下变量预期接受 @ref{205,,int} 类型的值:

@example
count: int = 0
@end example

变量标注语法的详细解释见 @ref{16dc,,带标注的赋值语句} 一节。

请参看 @ref{13c0,,function annotation}、
@geindex Python 提高建议; PEP 484
PEP 484@footnote{https://www.python.org/dev/peps/pep-0484} 和 
@geindex Python 提高建议; PEP 526
PEP 526@footnote{https://www.python.org/dev/peps/pep-0526}，其中对此功能有详细描述。
@anchor{glossary term-virtual-environment}@anchor{1477}
@geindex virtual environment -- 虚拟环境

@item virtual environment -- 虚拟环境

一种采用协作式隔离的运行时环境，允许 Python 用户和应用程序在安装和升级 Python 分发包时不会干扰到同一系统上运行的其他 Python 应用程序的行为。

另参见 @ref{12e,,venv}。
@anchor{glossary term-virtual-machine}@anchor{28bb}
@geindex virtual machine -- 虚拟机

@item virtual machine -- 虚拟机

一台完全通过软件定义的计算机。Python 虚拟机可执行字节码编译器所生成的 @ref{713,,bytecode}。
@anchor{glossary term-zen-of-python}@anchor{4579}
@geindex Zen of Python -- Python 之禅

@item Zen of Python -- Python 之禅

列出 Python 设计的原则与哲学，有助于理解与使用这种语言。查看其具体内容可在交互模式提示符中输入 "@code{import this}"。
@end table

@node 文档说明,解决 Bug,术语对照表,Top
@anchor{about doc}@anchor{457a}@anchor{about about-these-documents}@anchor{457b}
@chapter 文档说明


这些文档生成自 reStructuredText@footnote{http://docutils.sourceforge.net/rst.html} 原文档，由 Sphinx@footnote{http://sphinx-doc.org/} （一个专门为 Python 文档写的文档生成器）创建。

@c In the online version of these documents, you can submit comments and suggest
@c changes directly on the documentation pages.

本文档和它所用工具链的开发完全是由志愿者完成的，这和 Python 本身一样。如果您想参与进来，请阅读 @ref{3de8,,解决 Bug} 了解如何参与。我们随时欢迎新的志愿者！

非常感谢：


@itemize *

@item 
Fred L. Drake, Jr.，创造了用于早期 Python 文档的工具链，以及撰写了非常多的文档；

@item 
Docutils软件包@footnote{http://docutils.sourceforge.net/} 项目，创建了 reStructuredText 文本格式和 Docutils 软件套件；

@item 
Fredrik Lundh 的 Alternative Python Reference 项目， Sphinx 从中得到了许多好的想法。
@end itemize

@menu
* Python 文档贡献者:: 

@end menu

@node Python 文档贡献者,,,文档说明
@anchor{about contributors-to-the-python-documentation}@anchor{457c}
@section Python 文档贡献者


有很多对 Python 语言，Python 标准库和 Python 文档有贡献的人，随 Python 源代码发布的 Misc/ACKS@footnote{https://github.com/python/cpython/tree/3.9/Misc/ACKS} 文件列出了部分贡献者。

有了 Python 社区的输入和贡献，Python 才有了如此出色的文档 - 谢谢你们！

@node 解决 Bug,版权,文档说明,Top
@anchor{bugs doc}@anchor{457d}@anchor{bugs dealing-with-bugs}@anchor{457e}@anchor{bugs reporting-bugs}@anchor{3de8}
@chapter 解决 Bug


Python 是一门以稳定著称的编程语言。为了保持它的稳定性，开发者们想了解您在 Python 中发现的任何缺陷。

有时候自己修复漏洞并将补丁提交给 Python 能更快地解决问题，因为它简化了流程并且减少了参与的人力。 请参阅如何 @ref{457f,,提交补丁}。

@menu
* 文档错误:: 
* 使用 Python 的问题追踪系统:: 
* 开始为 Python 贡献您的知识:: 

@end menu

@node 文档错误,使用 Python 的问题追踪系统,,解决 Bug
@anchor{bugs documentation-bugs}@anchor{4580}
@section 文档错误


如果您在本文档中发现了错误并打算帮助我们改进，请将错误提交到 @ref{4581,,追踪系统}。 如果您有相应的修正建议，请一并提交。 （译者注：如果是中文文档翻译相关的错误，请务必提交到 @indicateurl{https://github.com/python/python-docs-zh-cn/issues}。如果将翻译问题反馈到了其他地方，可能会因为语言不通而不能及时处理。）

如果您时间有限，还可以通过电子邮件将文档的错误报告发送至 @email{docs@@python}.org（代码运行错误请发送至 @email{python-list@@python.org}）。“docs@@”是一个由志愿者运作的邮件列表；您的请求会得到关注，但可能需要一些时间才会被处理。


@subsubheading 参见



@table @asis

@item Documentation bugs@footnote{https://github.com/python/cpython/issues?q=is%3Aissue+is%3Aopen+label%3Adocs}

已提交给 Python 问题追踪系统的文档错误列表。

@item 问题跟踪@footnote{https://devguide.python.org/tracker/}

在追踪系统上参与问题改进的过程概述。

@item 改进文档@footnote{https://devguide.python.org/docquality/#helping-with-documentation}

给有兴趣为 Python 文档做出贡献的人。

@item 文档翻译@footnote{https://devguide.python.org/documenting/#translating}

文档翻译的 GitHub 页面及其主要联系人的列表
@end table


@node 使用 Python 的问题追踪系统,开始为 Python 贡献您的知识,文档错误,解决 Bug
@anchor{bugs using-the-python-issue-tracker}@anchor{4582}@anchor{bugs using-the-tracker}@anchor{4581}
@section 使用 Python 的问题追踪系统


Issue reports for Python itself should be submitted via the GitHub issues
tracker (@indicateurl{https://github.com/python/cpython/issues}).
The GitHub issues tracker offers a web form which allows pertinent information
to be entered and submitted to the developers.

The first step in filing a report is to determine whether the problem has
already been reported.  The advantage in doing so, aside from saving the
developers' time, is that you learn what has been done to fix it; it may be that
the problem has already been fixed for the next release, or additional
information is needed (in which case you are welcome to provide it if you can!).
To do this, search the tracker using the search box at the top of the page.

If the problem you're reporting is not already in the list, log in to GitHub.
If you don't already have a GitHub account, create a new account using the
"Sign up" link.
It is not possible to submit a bug report anonymously.

Being now logged in, you can submit an issue.
Click on the "New issue" button in the top bar to report a new issue.

The submission form has two fields, "Title" and "Comment".

For the "Title" field, enter a @emph{very} short description of the problem;
less than ten words is good.

在“说明（Comment）”栏，请详细描述问题，包括您预期的情况和实际的情况。请确保包含任何涉及的拓展模块，以及您当时所使用的硬件和软件平台（如果可能，请附上版本信息）。

Each issue report will be reviewed by a developer who will determine what needs to
be done to correct the problem. You will receive an update each time an action is
taken on the issue.


@subsubheading 参见



@table @asis

@item 如何有效地报告错误@footnote{https://www.chiark.greenend.org.uk/~sgtatham/bugs.html}

该文章详细介绍了如何创建一份有用的错误报告。它描述了什么样的信息是有用的，以及为什么是有用的。

@item Bug Writing Guidelines@footnote{https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html}

关于写一份好的错误报告。部分仅针对 Mozilla 项目，不过其描述了通用的恰当做法。
@end table


@node 开始为 Python 贡献您的知识,,使用 Python 的问题追踪系统,解决 Bug
@anchor{bugs contributing-to-python}@anchor{457f}@anchor{bugs getting-started-contributing-to-python-yourself}@anchor{4583}
@section 开始为 Python 贡献您的知识


除了仅仅报告您所发现的错误之外，同样欢迎您提交修复它们的补丁。您可以在 Python 开发者指引@footnote{https://devguide.python.org/} 中找到更多为 Python 打补丁的信息。如果您有任何问题，核心导师邮件列表@footnote{https://mail.python.org/mailman3/lists/core-mentorship.python.org/} 是一个友好的去处，在那里， 你可以寻求修复 Python 相关问题的答案。

@node 版权,历史和许可证,解决 Bug,Top
@anchor{copyright doc}@anchor{4584}@anchor{copyright copyright}@anchor{4585}@anchor{copyright core-mentorship-mailing-list}@anchor{4586}
@chapter 版权


Python 与这份文档：

Copyright © 2001-2023 Python Software Foundation. All rights reserved.

版权所有 © 2000 BeOpen.com。保留所有权利。

版权所有 © 1995-2000 Corporation for National Research Initiatives。保留所有权利。

版权所有 © 1991-1995 Stichting Mathematisch Centrum。保留所有权利。


__________________________________________________________________


有关完整的许可证和许可信息，参见 @ref{4587,,历史和许可证}。

@node 历史和许可证,分发 Python 模块（遗留版本）,版权,Top
@anchor{license doc}@anchor{4588}@anchor{license history-and-license}@anchor{4587}@anchor{license id1}@anchor{4589}
@chapter 历史和许可证


@menu
* 该软件的历史:: 
* 获取或以其他方式使用 Python 的条款和条件:: 
* 被收录软件的许可证与鸣谢:: 

@end menu

@node 该软件的历史,获取或以其他方式使用 Python 的条款和条件,,历史和许可证
@anchor{license history-of-the-software}@anchor{458a}
@section 该软件的历史


Python 由荷兰数学和计算机科学研究学会（CWI，见 @indicateurl{https://www.cwi.nl/} ）的 Guido van Rossum 于 1990 年代初设计，作为一门叫做 ABC 的语言的替代品。尽管 Python 包含了许多来自其他人的贡献，Guido 仍是其主要作者。

1995 年，Guido 在弗吉尼亚州的国家创新研究公司（CNRI，见 @indicateurl{https://www.cnri.reston.va.us/} ）继续他在 Python 上的工作，并在那里发布了该软件的多个版本。

2000 年五月，Guido 和 Python 核心开发团队转到 BeOpen.com 并组建了 BeOpen PythonLabs 团队。 同年十月，PythonLabs 团队转到 Digital Creations (现为 Zope Corporation；见 @indicateurl{https://www.zope.org/})。 2001 年，Python 软件基金会 (PSF，见 @indicateurl{https://www.python.org/psf/}) 成立，这是一个专为拥有 Python 相关知识产权而创建的非营利组织。 Zope Corporation 现在是 PSF 的赞助成员。

所有的 Python 版本都是开源的（有关开源的定义参阅 @indicateurl{https://opensource.org/} ）。历史上，绝大多数 Python 版本是 GPL 兼容的；下表总结了各个版本情况。


@multitable {xxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} 
@headitem

发布版本

@tab

源自

@tab

年份

@tab

所有者

@tab

GPL 兼容？

@item

0.9.0 至 1.2

@tab

n/a

@tab

1991-1995

@tab

CWI

@tab

是

@item

1.3 至 1.5.2

@tab

1.2

@tab

1995-1999

@tab

CNRI

@tab

是

@item

1.6

@tab

1.5.2

@tab

2000

@tab

CNRI

@tab

否

@item

2.0

@tab

1.6

@tab

2000

@tab

BeOpen.com

@tab

否

@item

1.6.1

@tab

1.6

@tab

2001

@tab

CNRI

@tab

否

@item

2.1

@tab

2.0+1.6.1

@tab

2001

@tab

PSF

@tab

否

@item

2.0.1

@tab

2.0+1.6.1

@tab

2001

@tab

PSF

@tab

是

@item

2.1.1

@tab

2.1+2.0.1

@tab

2001

@tab

PSF

@tab

是

@item

2.1.2

@tab

2.1.1

@tab

2002

@tab

PSF

@tab

是

@item

2.1.3

@tab

2.1.2

@tab

2002

@tab

PSF

@tab

是

@item

2.2 及更高

@tab

2.1.1

@tab

2001 至今

@tab

PSF

@tab

是

@end multitable


@cartouche
@quotation 注解 
GPL 兼容并不意味着 Python 在 GPL 下发布。与 GPL 不同，所有 Python 许可证都允许您分发修改后的版本，而无需开源所做的更改。GPL 兼容的许可证使得 Python 可以与其它在 GPL 下发布的软件结合使用；但其它的许可证则不行。
@end quotation
@end cartouche

感谢众多在 Guido 指导下工作的外部志愿者，使得这些发布成为可能。

@node 获取或以其他方式使用 Python 的条款和条件,被收录软件的许可证与鸣谢,该软件的历史,历史和许可证
@anchor{license terms-and-conditions-for-accessing-or-otherwise-using-python}@anchor{458b}
@section 获取或以其他方式使用 Python 的条款和条件


Python 软件和文档的使用许可均基于 @ref{458c,,PSF 许可协议}。

从 Python 3.8.6 开始，文档中的示例、操作指导和其他代码采用的是 PSF 许可协议和 @ref{458d,,零条款 BSD 许可} 的双重使用许可。

某些包含在 Python 中的软件是基于不同的许可。 这些许可会与相应许可之下的代码一同列出。 有关这些许可的不完整列表请参阅 @ref{458e,,被收录软件的许可证与鸣谢}。

@menu
* 用于 PYTHON 3.9.17 的 PSF 许可协议: 用于 PYTHON 3 9 17 的 PSF 许可协议. 
* 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议: 用于 PYTHON 2 0 的 BEOPEN COM 许可协议. 
* 用于 PYTHON 1.6.1 的 CNRI 许可协议: 用于 PYTHON 1 6 1 的 CNRI 许可协议. 
* 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议: 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议. 
* ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.17 DOCUMENTATION: ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 9 17 DOCUMENTATION. 

@end menu

@node 用于 PYTHON 3 9 17 的 PSF 许可协议,用于 PYTHON 2 0 的 BEOPEN COM 许可协议,,获取或以其他方式使用 Python 的条款和条件
@anchor{license psf-license}@anchor{458c}@anchor{license psf-license-agreement-for-python-release}@anchor{458f}
@subsection 用于 PYTHON 3.9.17 的 PSF 许可协议


@example
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using Python
   3.9.17 software in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 3.9.17 alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001-2023 Python Software Foundation; All Rights
   Reserved" are retained in Python 3.9.17 alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 3.9.17 or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python
   3.9.17.

4. PSF is making Python 3.9.17 available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON 3.9.17 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.9.17
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.9.17, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python 3.9.17, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.
@end example

@node 用于 PYTHON 2 0 的 BEOPEN COM 许可协议,用于 PYTHON 1 6 1 的 CNRI 许可协议,用于 PYTHON 3 9 17 的 PSF 许可协议,获取或以其他方式使用 Python 的条款和条件
@anchor{license beopen-com-license-agreement-for-python-2-0}@anchor{4590}
@subsection 用于 PYTHON 2.0 的 BEOPEN.COM 许可协议


BEOPEN PYTHON 开源许可协议第 1 版

@example
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
   160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
   ("Licensee") accessing and otherwise using this software in source or binary
   form and its associated documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License Agreement,
   BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
   to reproduce, analyze, test, perform and/or display publicly, prepare derivative
   works, distribute, and otherwise use the Software alone or in any derivative
   version, provided, however, that the BeOpen Python License is retained in the
   Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
   BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
   MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
   ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects
   by the law of the State of California, excluding conflict of law provisions.
   Nothing in this License Agreement shall be deemed to create any relationship of
   agency, partnership, or joint venture between BeOpen and Licensee.  This License
   Agreement does not grant permission to use BeOpen trademarks or trade names in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.  As an exception, the "BeOpen Python" logos available at
   @indicateurl{http://www.pythonlabs.com/logos.html} may be used according to the permissions
   granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be
   bound by the terms and conditions of this License Agreement.
@end example

@node 用于 PYTHON 1 6 1 的 CNRI 许可协议,用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,用于 PYTHON 2 0 的 BEOPEN COM 许可协议,获取或以其他方式使用 Python 的条款和条件
@anchor{license cnri-license-agreement-for-python-1-6-1}@anchor{4591}
@subsection 用于 PYTHON 1.6.1 的 CNRI 许可协议


@example
1. This LICENSE AGREEMENT is between the Corporation for National Research
   Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
   ("CNRI"), and the Individual or Organization ("Licensee") accessing and
   otherwise using Python 1.6.1 software in source or binary form and its
   associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
   provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
   i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
   Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
   prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
   Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
   is made available subject to the terms and conditions in CNRI's License
   Agreement.  This Agreement together with Python 1.6.1 may be located on the
   Internet using the following unique, persistent identifier (known as a handle):
   1895.22/1013.  This Agreement may also be obtained from a proxy server on the
   Internet using the following URL: @indicateurl{http://hdl.handle.net/1895.22/1013}."

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
   work available to others as provided herein, then Licensee hereby agrees to
   include in any such work a brief summary of the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
   MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
   BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
   OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
   PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property
   law of the United States, including without limitation the federal copyright
   law, and, to the extent such U.S. federal law does not apply, by the law of the
   Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
   Notwithstanding the foregoing, with regard to derivative works based on Python
   1.6.1 that incorporate non-separable material that was previously distributed
   under the GNU General Public License (GPL), the law of the Commonwealth of
   Virginia shall govern this License Agreement only as to issues arising under or
   with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
   this License Agreement shall be deemed to create any relationship of agency,
   partnership, or joint venture between CNRI and Licensee.  This License Agreement
   does not grant permission to use CNRI trademarks or trade name in a trademark
   sense to endorse or promote products or services of Licensee, or any third
   party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
   or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
   conditions of this License Agreement.
@end example

@node 用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 9 17 DOCUMENTATION,用于 PYTHON 1 6 1 的 CNRI 许可协议,获取或以其他方式使用 Python 的条款和条件
@anchor{license cwi-license-agreement-for-python-0-9-0-through-1-2}@anchor{4592}
@subsection 用于 PYTHON 0.9.0 至 1.2 的 CWI 许可协议


@example
Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
@end example

@node ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3 9 17 DOCUMENTATION,,用于 PYTHON 0 9 0 至 1 2 的 CWI 许可协议,获取或以其他方式使用 Python 的条款和条件
@anchor{license bsd0}@anchor{458d}@anchor{license zero-clause-bsd-license-for-code-in-the-python-release-documentation}@anchor{4593}
@subsection ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON 3.9.17 DOCUMENTATION


@example
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@end example

@node 被收录软件的许可证与鸣谢,,获取或以其他方式使用 Python 的条款和条件,历史和许可证
@anchor{license licenses-and-acknowledgements-for-incorporated-software}@anchor{4594}@anchor{license otherlicenses}@anchor{458e}
@section 被收录软件的许可证与鸣谢


本节是Python发行版中收录的第三方软件的许可和致谢清单，该清单是不完整且不断增长的。

@menu
* Mersenne Twister:: 
* 套接字: 套接字<2>. 
* 异步套接字服务:: 
* Cookie 管理:: 
* 执行追踪:: 
* UUencode 与 UUdecode 函数:: 
* XML 远程过程调用:: 
* test_epoll:: 
* Select kqueue:: 
* SipHash24:: 
* strtod 和 dtoa:: 
* OpenSSL:: 
* expat:: 
* libffi:: 
* zlib: zlib<3>. 
* cfuhash:: 
* libmpdec:: 
* W3C C14N 测试套件:: 

@end menu

@node Mersenne Twister,套接字<2>,,被收录软件的许可证与鸣谢
@anchor{license mersenne-twister}@anchor{4595}
@subsection Mersenne Twister


@code{_random} 模块包含基于 @indicateurl{http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html} 下载的代码。以下是原始代码的完整注释（声明）：

@example
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. The names of its contributors may not be used to endorse or promote
    products derived from this software without specific prior written
    permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @@ math.sci.hiroshima-u.ac.jp (remove space)
@end example

@node 套接字<2>,异步套接字服务,Mersenne Twister,被收录软件的许可证与鸣谢
@anchor{license sockets}@anchor{4596}
@subsection 套接字


@ref{ef,,socket} 模块使用 @code{getaddrinfo()} 和 @code{getnameinfo()} 函数，这些函数源代码在WIDE项目（@indicateurl{http://www.wide.ad.jp/}）的单独源文件中。

@example
Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS `@w{`}AS IS'@w{'} AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
@end example

@node 异步套接字服务,Cookie 管理,套接字<2>,被收录软件的许可证与鸣谢
@anchor{license asynchronous-socket-services}@anchor{4597}
@subsection 异步套接字服务


@ref{8,,asynchat} 和 @ref{a,,asyncore} 模块包含以下声明:

@example
Copyright 1996 by Sam Rushing

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@end example

@node Cookie 管理,执行追踪,异步套接字服务,被收录软件的许可证与鸣谢
@anchor{license cookie-management}@anchor{4598}
@subsection Cookie 管理


@ref{95,,http.cookies} 模块包含以下声明:

@example
Copyright 2000 by Timothy O'Malley <timo@@alum.mit.edu>

               All Rights Reserved

Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O'Malley  not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@end example

@node 执行追踪,UUencode 与 UUdecode 函数,Cookie 管理,被收录软件的许可证与鸣谢
@anchor{license execution-tracing}@anchor{4599}
@subsection 执行追踪


@ref{11b,,trace} 模块包含以下声明:

@example
portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
err...  reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:zooko@@zooko.com

Copyright 2000, Mojam Media, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.
Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.


Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
@end example

@node UUencode 与 UUdecode 函数,XML 远程过程调用,执行追踪,被收录软件的许可证与鸣谢
@anchor{license uuencode-and-uudecode-functions}@anchor{459a}
@subsection UUencode 与 UUdecode 函数


@ref{12c,,uu} 模块包含以下声明:

@example
Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
                       All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
  between ascii and binary. This results in a 1000-fold speedup. The C
  version is still 5 times faster, though.
- Arguments more compliant with Python standard
@end example

@node XML 远程过程调用,test_epoll,UUencode 与 UUdecode 函数,被收录软件的许可证与鸣谢
@anchor{license xml-remote-procedure-calls}@anchor{459b}
@subsection XML 远程过程调用


@ref{148,,xmlrpc.client} 模块包含以下声明:

@example
    The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and
its associated documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice appears in
all copies, and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
@end example

@node test_epoll,Select kqueue,XML 远程过程调用,被收录软件的许可证与鸣谢
@anchor{license test-epoll}@anchor{459c}
@subsection test_epoll


@code{test_epoll} 模块包含以下声明:

@example
Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end example

@node Select kqueue,SipHash24,test_epoll,被收录软件的许可证与鸣谢
@anchor{license select-kqueue}@anchor{459d}
@subsection Select kqueue


@ref{e5,,select} 模块关于 kqueue 的接口包含以下声明:

@example
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS `@w{`}AS IS'@w{'} AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
@end example

@node SipHash24,strtod 和 dtoa,Select kqueue,被收录软件的许可证与鸣谢
@anchor{license siphash24}@anchor{459e}
@subsection SipHash24


@code{Python/pyhash.c} 文件包含 Marek Majkowski' 对 Dan Bernstein 的SipHash24 算法的实现。它包含以下声明:

@example
<MIT License>
Copyright (c) 2013  Marek Majkowski <marek@@popcount.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>

Original location:
   https://github.com/majek/csiphash/

Solution inspired by code from:
   Samuel Neves (supercop/crypto_auth/siphash24/little)
   djb (supercop/crypto_auth/siphash24/little2)
   Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)
@end example

@node strtod 和 dtoa,OpenSSL,SipHash24,被收录软件的许可证与鸣谢
@anchor{license strtod-and-dtoa}@anchor{459f}
@subsection strtod 和 dtoa


@code{Python/dtoa.c} 文件提供了C语言的 dtoa 和 strtod 函数，用于将C语言的 双精度型和字符串进行转换，由David M. Gay的同名文件派生而来，该文件当前可从http://www.netlib.org/fp/ 下载。2009年3月16日检索到的原始文件包含以下版权和许可声明:

@example
/****************************************************************
 *
 * The author of this software is David M. Gay.
 *
 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose without fee is hereby granted, provided that this entire notice
 * is included in all copies of any software which is or includes a copy
 * or modification of this software and in all copies of the supporting
 * documentation for such software.
 *
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 *
 ***************************************************************/
@end example

@node OpenSSL,expat,strtod 和 dtoa,被收录软件的许可证与鸣谢
@anchor{license openssl}@anchor{45a0}
@subsection OpenSSL


如果操作系统可用，则 @ref{8c,,hashlib}、@ref{d1,,posix}、@ref{f3,,ssl}、@ref{28,,crypt} 模块使用 OpenSSL 库来提高性能。此外，适用于 Python 的 Windows 和 macoS 安装程序可能包括 OpenSSL 库的拷贝，所以在此处也列出了 OpenSSL 许可证的拷贝:

@example
 LICENSE ISSUES
 ==============

 The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
 the OpenSSL License and the original SSLeay license apply to the toolkit.
 See below for the actual license texts. Actually both licenses are BSD-style
 Open Source licenses. In case of any license issues related to OpenSSL
 please contact openssl-core@@openssl.org.

 OpenSSL License
 ---------------

   /* ====================================================================
    * Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *
    * 1. Redistributions of source code must retain the above copyright
    *    notice, this list of conditions and the following disclaimer.
    *
    * 2. Redistributions in binary form must reproduce the above copyright
    *    notice, this list of conditions and the following disclaimer in
    *    the documentation and/or other materials provided with the
    *    distribution.
    *
    * 3. All advertising materials mentioning features or use of this
    *    software must display the following acknowledgment:
    *    "This product includes software developed by the OpenSSL Project
    *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
    *
    * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
    *    endorse or promote products derived from this software without
    *    prior written permission. For written permission, please contact
    *    openssl-core@@openssl.org.
    *
    * 5. Products derived from this software may not be called "OpenSSL"
    *    nor may "OpenSSL" appear in their names without prior written
    *    permission of the OpenSSL Project.
    *
    * 6. Redistributions of any form whatsoever must retain the following
    *    acknowledgment:
    *    "This product includes software developed by the OpenSSL Project
    *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
    *
    * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT `@w{`}AS IS'@w{'} AND ANY
    * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
    * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    * OF THE POSSIBILITY OF SUCH DAMAGE.
    * ====================================================================
    *
    * This product includes cryptographic software written by Eric Young
    * (eay@@cryptsoft.com).  This product includes software written by Tim
    * Hudson (tjh@@cryptsoft.com).
    *
    */

Original SSLeay License
-----------------------

   /* Copyright (C) 1995-1998 Eric Young (eay@@cryptsoft.com)
    * All rights reserved.
    *
    * This package is an SSL implementation written
    * by Eric Young (eay@@cryptsoft.com).
    * The implementation was written so as to conform with Netscapes SSL.
    *
    * This library is free for commercial and non-commercial use as long as
    * the following conditions are aheared to.  The following conditions
    * apply to all code found in this distribution, be it the RC4, RSA,
    * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
    * included with this distribution is covered by the same copyright terms
    * except that the holder is Tim Hudson (tjh@@cryptsoft.com).
    *
    * Copyright remains Eric Young's, and as such any Copyright notices in
    * the code are not to be removed.
    * If this package is used in a product, Eric Young should be given attribution
    * as the author of the parts of the library used.
    * This can be in the form of a textual message at program startup or
    * in documentation (online or textual) provided with the package.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * 1. Redistributions of source code must retain the copyright
    *    notice, this list of conditions and the following disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    *    notice, this list of conditions and the following disclaimer in the
    *    documentation and/or other materials provided with the distribution.
    * 3. All advertising materials mentioning features or use of this software
    *    must display the following acknowledgement:
    *    "This product includes cryptographic software written by
    *     Eric Young (eay@@cryptsoft.com)"
    *    The word 'cryptographic' can be left out if the rouines from the library
    *    being used are not cryptographic related :-).
    * 4. If you include any Windows specific code (or a derivative thereof) from
    *    the apps directory (application code) you must include an acknowledgement:
    *    "This product includes software written by Tim Hudson (tjh@@cryptsoft.com)"
    *
    * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG `@w{`}AS IS'@w{'} AND
    * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
    * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    * SUCH DAMAGE.
    *
    * The licence and distribution terms for any publically available version or
    * derivative of this code cannot be changed.  i.e. this code cannot simply be
    * copied and put under another distribution licence
    * [including the GNU Public Licence.]
    */
@end example

@node expat,libffi,OpenSSL,被收录软件的许可证与鸣谢
@anchor{license expat}@anchor{45a1}
@subsection expat


除非使用 @code{--with-system-expat} 配置了构建，否则 @code{pyexpat} 扩展都是用包含 expat源的拷贝构建的:

@example
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                               and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end example

@node libffi,zlib<3>,expat,被收录软件的许可证与鸣谢
@anchor{license libffi}@anchor{45a2}
@subsection libffi


除非使用 @code{--with-system-libffi} 配置了构建，否则 @code{_ctypes} 扩展都是包含 libffi源的拷贝构建的:

@example
Copyright (c) 1996-2008  Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
`@w{`}Software'@w{'}), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED `@w{`}AS IS'@w{'}, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@end example

@node zlib<3>,cfuhash,libffi,被收录软件的许可证与鸣谢
@anchor{license zlib}@anchor{45a3}
@subsection zlib


如果系统上找到的zlib版本太旧而无法用于构建，则使用包含 zlib源代码的拷贝来构建 @ref{14d,,zlib} 扩展:

@example
Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly        Mark Adler
jloup@@gzip.org          madler@@alumni.caltech.edu
@end example

@node cfuhash,libmpdec,zlib<3>,被收录软件的许可证与鸣谢
@anchor{license cfuhash}@anchor{45a4}
@subsection cfuhash


@ref{11d,,tracemalloc} 使用的哈希表的实现基于 cfuhash项目:

@example
Copyright (c) 2005 Don Owens
All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.

  * Neither the name of the author nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@node libmpdec,W3C C14N 测试套件,cfuhash,被收录软件的许可证与鸣谢
@anchor{license libmpdec}@anchor{45a5}
@subsection libmpdec


除非使用 @code{--with-system-libmpdec} 配置了构建，否则 @code{_decimal} 模块都是用包含 libmpdec 库的拷贝构建的。

@example
Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
@end example

@node W3C C14N 测试套件,,libmpdec,被收录软件的许可证与鸣谢
@anchor{license w3c-c14n-test-suite}@anchor{45a6}
@subsection W3C C14N 测试套件


@ref{105,,test} 包中的 C14N 2.0 测试集 (@code{Lib/test/xmltestdata/c14n-20/}) 提取自 W3C 网站 @indicateurl{https://www.w3.org/TR/xml-c14n2-testcases/} 并根据 3 条款版 BSD 许可证发行:

@example
Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of works must retain the original copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
  used to endorse or promote products derived from this work without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@end example

@c to include legacy packaging docs in build

@node 分发 Python 模块（遗留版本）,安装Python模块（旧版）,历史和许可证,Top
@anchor{distutils/index doc}@anchor{45a7}@anchor{distutils/index distributing-python-modules-legacy-version}@anchor{45a8}@anchor{distutils/index distutils-index}@anchor{8ef}
@chapter 分发 Python 模块（遗留版本）


@*作者: 
Greg Ward ， Anthony Baxter


@*电子邮箱: 
@email{distutils-sig@@python.org}



@subsubheading 参见



@table @asis

@item @ref{8ed,,分发 Python 模块}

最新的模块分发文档
@end table


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分@footnote{https://packaging.python.org/guides/tool-recommendations/} 。
@end quotation
@end cartouche

本文档从模块开发人员的角度描述了 Python Distribution Utilities ("Distutils")。 描述了 @code{setuptools} 构建所依赖的下层功能，以允许 Python 开发者方便地为更广泛的受众编写 Python 模块和扩展。

@menu
* Distutils 模块介绍:: 
* 编写安装脚本:: 
* 编写设置脚本的配置文件:: 
* 创建源代码分发包:: 
* 创建构建分布:: 
* Distutils 示例:: 
* 扩展 Distutils:: 
* 命令参考:: 
* API参考引用:: 

@end menu

@node Distutils 模块介绍,编写安装脚本,,分发 Python 模块（遗留版本）
@anchor{distutils/introduction doc}@anchor{45a9}@anchor{distutils/introduction an-introduction-to-distutils}@anchor{45aa}@anchor{distutils/introduction distutils-intro}@anchor{45ab}
@section Distutils 模块介绍


@cartouche
@quotation 注解 
这篇文档是历史遗留文档，在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之后，将不再单独作为正式文档保留。
@end quotation
@end cartouche

本文档介绍了使用 Distutils 模块分发你的 Python 模块，主要是针对开发者/分发者的使用的——如果你想了解如何安装 Python 模块，你应该参考这个章节： @ref{8ee,,安装Python模块（旧版）}。

@menu
* 概念和术语:: 
* 一个简单的例子: 一个简单的例子<3>. 
* 通用的 Python 术语:: 
* Distutils 特定的术语:: 

@end menu

@node 概念和术语,一个简单的例子<3>,,Distutils 模块介绍
@anchor{distutils/introduction concepts-terminology}@anchor{45ac}@anchor{distutils/introduction distutils-concepts}@anchor{45ad}
@subsection 概念和术语


Distutils 用起来非常简单，对于模块开发者或安装第三方模块的用户/管理员均是如此。开发者的责任（当然还有编写可靠、良好文档和经过良好测试的代码！）就是：


@itemize *

@item 
编写一个设置脚本 (@code{setup.py} by convention)

@item 
(可选)编写设置脚本的配置文件

@item 
创建源码的发行版

@item 
（可选）创建一个或多个编译好（二进制）的发行版
@end itemize

这些操作在此文档均有讲解。

并非所有的模块开发者都能接触到众多的平台，所以期望他们创造众多的内置发行版不是总是可行的。最好是有一类名为 @emph{打包者} 的中介，以满足这一需求。打包者将读取模块开发者发布的源代码，在一个或多个平台上进行编译，并发布构建出来的发行版。这样，最流行平台的用户就能以最自然的方式安装最流行的 Python 模块发行版，不必运行什么设置脚本或编译代码了。

@node 一个简单的例子<3>,通用的 Python 术语,概念和术语,Distutils 模块介绍
@anchor{distutils/introduction a-simple-example}@anchor{45ae}@anchor{distutils/introduction distutils-simple-example}@anchor{45af}
@subsection 一个简单的例子


setup 脚本通常很简单，尽管是用 Python 编写的，它能干的事情没有限制，当然应小心别在 setup 脚本中加入什么运行缓慢的操作。与 Autoconf 风格的 configure 脚本不同，在构建和安装模块的过程中 setup 脚本可能会被多次运行。

如果只想发布一个名为 @code{foo} 的模块，位于 @code{foo.py} 文件中，那么 setup 脚本可以如此简单：

@example
from distutils.core import setup
setup(name='foo',
      version='1.0',
      py_modules=['foo'],
      )
@end example

注意要点：


@itemize *

@item 
提供给 Distutils 的大部分信息将作为关键字参数发给 @code{setup()} 函数。

@item 
这些关键字参数分为两类：包的元数据（名称、版本号）和包中内容的描述信息（本例中是纯 Python 模块的列表）。

@item 
模块由模块名指定，而不是文件名（包和扩展也是如此）。

@item 
建议多提供一些元数据，特别是开发者姓名、电子邮件地址和项目的URL（参见 @ref{45b0,,编写安装脚本} 中的例子）。
@end itemize

要为该模块创建一个源码发布版本，需要创建一段 setup 脚本 @code{setup.py}，包含上述代码，然后从终端运行以下命令：

@example
python setup.py sdist
@end example

对于 Windows 用户来说，打开命令行窗口（Start ‣ Accessories）并且写上如下命令:

@example
setup.py sdist
@end example

@code{sdist} 将创建一个归档文件（例如在 Unix 中为 tarball，在 Windows 中为 ZIP 文件），其中包含你的配置脚本 @code{setup.py} 以及你的模块 @code{foo.py}。 此归档文件将被命名为 @code{foo-1.0.tar.gz} (或 @code{.zip})，并将解包到目录 @code{foo-1.0} 当中。

如果最终用户希望安装 @code{foo} 模块，只需下载 @code{foo-1.0.tar.gz} （或 @code{.zip} ）并解压，进入 @code{foo-1.0} 目录运行：

@example
python setup.py install
@end example

这会把 @code{foo.py} 复制到 Python 安装环境的第三方模块目录中。

上述简单例子展示了 Distutils 的一些基本概念。首先，开发者和安装者拥有相同的基本用户界面，即 setup 脚本。区别在于使用哪种 Distutils @emph{命令} ： @code{sdist} 命令几乎只适用于模块开发者，而 @code{install} 则更适用于安装者（当然大多数开发者偶尔也想要安装自己的代码）。

If you want to make things really easy for your users, you can create one or
more built distributions for them.  For instance, if you are running on a
Windows machine, and want to make things easy for other Windows users, you can
create an executable installer (the most appropriate type of built distribution
for this platform) with the @code{bdist_wininst} command.  For example:

@example
python setup.py bdist_wininst
@end example

will create an executable installer, @code{foo-1.0.win32.exe}, in the current
directory.

其他有用的内置分发格式是 RPM，可由 @code{bdist_rpm} 、Solaris @code{pkgtool`（:command:`bdist_pkgtool}）和 HP-UX @code{swinstall`（:command:`bdist_sdux}）实现。比如，以下命令将创建一个名为 @code{foo-1.0.noarch.rpm} 的RPM文件：

@example
python setup.py bdist_rpm
@end example

（@code{bdist_rpm} 命令用到了 @code{rpm} 可执行文件，因此必须运行在基于 RPM 的系统中，如 Red Hat Linux 、 SuSE Linux 或 Mandrake Linux）。

可以随时运行以下命令，以便了解当前可用的分发格式：

@example
python setup.py bdist --help-formats
@end example

@node 通用的 Python 术语,Distutils 特定的术语,一个简单的例子<3>,Distutils 模块介绍
@anchor{distutils/introduction general-python-terminology}@anchor{45b1}@anchor{distutils/introduction python-terms}@anchor{45b2}
@subsection 通用的 Python 术语


本文读者可能对模块、扩展等已有了很好的理解。但为确保所有人都站在同一起点上，下面提供了 Python 常用术语表：


@table @asis

@item 模块

实现 Python 代码重用的基本单位：可被其他代码导入的一段代码。有三种类型的模块与本文有关：纯 Python 模块、扩展模块和包。

@item 纯 Python 模块

用 Python 编写的模块，包含在某 @code{.py} 文件中（可能还会有相关的 @code{.pyc} 文件）。有时被称为 "纯模块"。

@item 扩展模块

用低级语言编写的  Python 模块。Python 用 C/C++ ，而 Jython 则用Java。通常包含在一个可动态加载的预编译文件中，比如 Unix 中的 Python 扩展是一个共享对象（@code{.so}）文件，Windows 中的 Python 扩展则是一个 DLL （扩展名为 @code{.pyd} )，而 Jython 的扩展是个 Java class 文件。（注意，目前，Distutils 只能处理 Python 的 C/C++ 扩展。）

@item 包

包含其他模块的模块；通常位于文件系统的某个目录中，区别于其他目录的标记就是存在一个  @code{__init__.py} 文件。

@item 根包

包的层次结构的根。（其并非一个真正的包，因为没有 @code{__init__.py} 文件。但总得给它起个名字）。 绝大多数标准库都在根包中，还有许多不属于任何大型模块的小型、独立的第三方模块。与普通的包不同，根包中的模块可能会在很多目录中出现：事实上，@code{sys.path} 列出的每个目录都会为根包提供模块。
@end table

@node Distutils 特定的术语,,通用的 Python 术语,Distutils 模块介绍
@anchor{distutils/introduction distutils-specific-terminology}@anchor{45b3}@anchor{distutils/introduction distutils-term}@anchor{45b4}
@subsection Distutils 特定的术语


以下属于更加特别地用于 Distutils 发布 Python 模块。


@table @asis

@item 模块的发布

一组 Python 模块，作为可下载的资源组团发布，以便 @emph{大规模} 安装。模块发布版的著名例子是 NumPy 、 SciPy 、 Pillow 或 mxBase。（这些会被称为 @emph{package}，这个词在 Python 的语境中也使用过：一个模块发行版可能包含零个、一个或多个 Python 包。)

@item 纯模块发行版

只包含纯 Python 模块和软件包的模块发布版。有时被称为“纯发行版”。

@item 非纯模块发行版

至少包含一个扩展模块的模块发行版。 有时被称为“非纯发行版”。

@item 根发行版

源代码树（或源代码发行版）的顶级目录；即 @code{setup.py} 所在的目录。 一般来说，@code{setup.py} 会在该目录下运行。
@end table

@node 编写安装脚本,编写设置脚本的配置文件,Distutils 模块介绍,分发 Python 模块（遗留版本）
@anchor{distutils/setupscript doc}@anchor{45b5}@anchor{distutils/setupscript setup-script}@anchor{45b0}@anchor{distutils/setupscript writing-the-setup-script}@anchor{45b6}
@section 编写安装脚本


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

安装脚本是使用 Distutils 进行构建、分发和安装模块的的入口。设置脚本的主要目的是向 Distutils 描述如何分发您的模块，以便对您的模块进行操作的各种命令正确运行。正如我们在上面的 @ref{45af,,一个简单的例子} 部分中看到的，安装脚本主要包含对 @code{setup()} 的调用，并且模块开发人员提供给 Distutils 的大部分信息都作为关键字参数提供给 @code{setup()}。

Here's a slightly more involved example, which we'll follow for the next couple
of sections: the Distutils' own setup script.  (Keep in mind that although the
Distutils are included with Python 1.6 and later, they also have an independent
existence so that Python 1.5.2 users can use them to install other module
distributions.  The Distutils' own setup script, shown here, is used to install
the package into Python 1.5.2.)

@example
#!/usr/bin/env python

from distutils.core import setup

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
     )
@end example

There are only two differences between this and the trivial one-file
distribution presented in section @ref{45af,,一个简单的例子}: more metadata, and the
specification of pure Python modules by package, rather than by module.  This is
important since the Distutils consist of a couple of dozen modules split into
(so far) two packages; an explicit list of every module would be tedious to
generate and difficult to maintain.  For more information on the additional
meta-data, see section @ref{45b7,,Additional meta-data}.

Note that any pathnames (files or directories) supplied in the setup script
should be written using the Unix convention, i.e. slash-separated.  The
Distutils will take care of converting this platform-neutral representation into
whatever is appropriate on your current platform before actually using the
pathname.  This makes your setup script portable across operating systems, which
of course is one of the major goals of the Distutils.  In this spirit, all
pathnames in this document are slash-separated.

This, of course, only applies to pathnames given to Distutils functions.  If
you, for example, use standard Python functions such as @ref{6c7,,glob.glob()} or
@ref{b25,,os.listdir()} to specify files, you should be careful to write portable
code instead of hardcoding path separators:

@example
glob.glob(os.path.join('mydir', 'subdir', '*.html'))
os.listdir(os.path.join('mydir', 'subdir'))
@end example

@menu
* 列出全部的包:: 
* 列出单独的模块:: 
* 描述扩展模块:: 
* Relationships between Distributions and Packages:: 
* Installing Scripts:: 
* Installing Package Data:: 
* Installing Additional Files:: 
* Additional meta-data:: 
* Debugging the setup script:: 

@end menu

@node 列出全部的包,列出单独的模块,,编写安装脚本
@anchor{distutils/setupscript listing-packages}@anchor{45b8}@anchor{distutils/setupscript listing-whole-packages}@anchor{45b9}
@subsection 列出全部的包


The @code{packages} option tells the Distutils to process (build, distribute,
install, etc.) all pure Python modules found in each package mentioned in the
@code{packages} list.  In order to do this, of course, there has to be a
correspondence between package names and directories in the filesystem.  The
default correspondence is the most obvious one, i.e. package @ref{38,,distutils} is
found in the directory @code{distutils} relative to the distribution root.
Thus, when you say @code{packages = ['foo']} in your setup script, you are
promising that the Distutils will find a file @code{foo/__init__.py} (which
might be spelled differently on your system, but you get the idea) relative to
the directory where your setup script lives.  If you break this promise, the
Distutils will issue a warning but still process the broken package anyway.

If you use a different convention to lay out your source directory, that's no
problem: you just have to supply the @code{package_dir} option to tell the
Distutils about your convention.  For example, say you keep all Python source
under @code{lib}, so that modules in the "root package" (i.e., not in any
package at all) are in @code{lib}, modules in the @code{foo} package are in
@code{lib/foo}, and so forth.  Then you would put

@example
package_dir = @{'@w{'}: 'lib'@}
@end example

in your setup script.  The keys to this dictionary are package names, and an
empty package name stands for the root package.  The values are directory names
relative to your distribution root.  In this case, when you say @code{packages =
['foo']}, you are promising that the file @code{lib/foo/__init__.py} exists.

Another possible convention is to put the @code{foo} package right in
@code{lib}, the @code{foo.bar} package in @code{lib/bar}, etc.  This would be
written in the setup script as

@example
package_dir = @{'foo': 'lib'@}
@end example

A @code{package: dir} entry in the @code{package_dir} dictionary implicitly
applies to all packages below @emph{package}, so the @code{foo.bar} case is
automatically handled here.  In this example, having @code{packages = ['foo',
'foo.bar']} tells the Distutils to look for @code{lib/__init__.py} and
@code{lib/bar/__init__.py}.  (Keep in mind that although @code{package_dir}
applies recursively, you must explicitly list all packages in
@code{packages}: the Distutils will @emph{not} recursively scan your source tree
looking for any directory with an @code{__init__.py} file.)

@node 列出单独的模块,描述扩展模块,列出全部的包,编写安装脚本
@anchor{distutils/setupscript listing-individual-modules}@anchor{45ba}@anchor{distutils/setupscript listing-modules}@anchor{45bb}
@subsection 列出单独的模块


For a small module distribution, you might prefer to list all modules rather
than listing packages---especially the case of a single module that goes in the
"root package" (i.e., no package at all).  This simplest case was shown in
section @ref{45af,,一个简单的例子}; here is a slightly more involved example:

@example
py_modules = ['mod1', 'pkg.mod2']
@end example

This describes two modules, one of them in the "root" package, the other in the
@code{pkg} package.  Again, the default package/directory layout implies that
these two modules can be found in @code{mod1.py} and @code{pkg/mod2.py}, and
that @code{pkg/__init__.py} exists as well. And again, you can override the
package/directory correspondence using the @code{package_dir} option.

@node 描述扩展模块,Relationships between Distributions and Packages,列出单独的模块,编写安装脚本
@anchor{distutils/setupscript describing-extension-modules}@anchor{45bc}@anchor{distutils/setupscript describing-extensions}@anchor{45bd}
@subsection 描述扩展模块


Just as writing Python extension modules is a bit more complicated than writing
pure Python modules, describing them to the Distutils is a bit more complicated.
Unlike pure modules, it's not enough just to list modules or packages and expect
the Distutils to go out and find the right files; you have to specify the
extension name, source file(s), and any compile/link requirements (include
directories, libraries to link with, etc.).

@c XXX read over this section

All of this is done through another keyword argument to @code{setup()}, the
@code{ext_modules} option.  @code{ext_modules} is just a list of
@ref{45be,,Extension} instances, each of which describes a
single extension module.
Suppose your distribution includes a single extension, called @code{foo} and
implemented by @code{foo.c}.  If no additional instructions to the
compiler/linker are needed, describing this extension is quite simple:

@example
Extension('foo', ['foo.c'])
@end example

The @code{Extension} class can be imported from @ref{53,,distutils.core} along
with @code{setup()}.  Thus, the setup script for a module distribution that
contains only this one extension and nothing else might be:

@example
from distutils.core import setup, Extension
setup(name='foo',
      version='1.0',
      ext_modules=[Extension('foo', ['foo.c'])],
      )
@end example

The @code{Extension} class (actually, the underlying extension-building
machinery implemented by the @code{build_ext} command) supports a great deal
of flexibility in describing Python extensions, which is explained in the
following sections.

@menu
* 扩展名和软件包:: 
* 扩展资源文件:: 
* 预处理器选项:: 
* 库选项:: 
* 其他选项: 其他选项<2>. 

@end menu

@node 扩展名和软件包,扩展资源文件,,描述扩展模块
@anchor{distutils/setupscript extension-names-and-packages}@anchor{45bf}
@subsubsection 扩展名和软件包


The first argument to the @ref{45be,,Extension} constructor is
always the name of the extension, including any package names.  For example,

@example
Extension('foo', ['src/foo1.c', 'src/foo2.c'])
@end example

describes an extension that lives in the root package, while

@example
Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])
@end example

describes the same extension in the @code{pkg} package.  The source files and
resulting object code are identical in both cases; the only difference is where
in the filesystem (and therefore where in Python's namespace hierarchy) the
resulting extension lives.

If you have a number of extensions all in the same package (or all under the
same base package), use the @code{ext_package} keyword argument to
@code{setup()}.  For example,

@example
setup(...,
      ext_package='pkg',
      ext_modules=[Extension('foo', ['foo.c']),
                   Extension('subpkg.bar', ['bar.c'])],
     )
@end example

will compile @code{foo.c} to the extension @code{pkg.foo}, and @code{bar.c} to
@code{pkg.subpkg.bar}.

@node 扩展资源文件,预处理器选项,扩展名和软件包,描述扩展模块
@anchor{distutils/setupscript extension-source-files}@anchor{45c0}
@subsubsection 扩展资源文件


The second argument to the @ref{45be,,Extension} constructor is
a list of source
files.  Since the Distutils currently only support C, C++, and Objective-C
extensions, these are normally C/C++/Objective-C source files.  (Be sure to use
appropriate extensions to distinguish C++ source files: @code{.cc} and
@code{.cpp} seem to be recognized by both Unix and Windows compilers.)

However, you can also include SWIG interface (@code{.i}) files in the list; the
@code{build_ext} command knows how to deal with SWIG extensions: it will run
SWIG on the interface file and compile the resulting C/C++ file into your
extension.

@c XXX SWIG support is rough around the edges and largely untested!

This warning notwithstanding, options to SWIG can be currently passed like
this:

@example
setup(...,
      ext_modules=[Extension('_foo', ['foo.i'],
                             swig_opts=['-modern', '-I../include'])],
      py_modules=['foo'],
     )
@end example

Or on the commandline like this:

@example
> python setup.py build_ext --swig-opts="-modern -I../include"
@end example

On some platforms, you can include non-source files that are processed by the
compiler and included in your extension.  Currently, this just means Windows
message text (@code{.mc}) files and resource definition (@code{.rc}) files for
Visual C++. These will be compiled to binary resource (@code{.res}) files and
linked into the executable.

@node 预处理器选项,库选项,扩展资源文件,描述扩展模块
@anchor{distutils/setupscript preprocessor-options}@anchor{45c1}
@subsubsection 预处理器选项


Three optional arguments to @ref{45be,,Extension} will help if
you need to specify include directories to search or preprocessor macros to
define/undefine: @code{include_dirs}, @code{define_macros}, and @code{undef_macros}.

For example, if your extension requires header files in the @code{include}
directory under your distribution root, use the @code{include_dirs} option:

@example
Extension('foo', ['foo.c'], include_dirs=['include'])
@end example

You can specify absolute directories there; if you know that your extension will
only be built on Unix systems with X11R6 installed to @code{/usr}, you can get
away with

@example
Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11'])
@end example

You should avoid this sort of non-portable usage if you plan to distribute your
code: it's probably better to write C code like

@example
#include <X11/Xlib.h>
@end example

If you need to include header files from some other Python extension, you can
take advantage of the fact that header files are installed in a consistent way
by the Distutils @code{install_headers} command.  For example, the Numerical
Python header files are installed (on a standard Unix installation) to
@code{/usr/local/include/python1.5/Numerical}. (The exact location will differ
according to your platform and Python installation.)  Since the Python include
directory---@code{/usr/local/include/python1.5} in this case---is always
included in the search path when building Python extensions, the best approach
is to write C code like

@example
#include <Numerical/arrayobject.h>
@end example

If you must put the @code{Numerical} include directory right into your header
search path, though, you can find that directory using the Distutils
@ref{61,,distutils.sysconfig} module:

@example
from distutils.sysconfig import get_python_inc
incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical')
setup(...,
      Extension(..., include_dirs=[incdir]),
      )
@end example

Even though this is quite portable---it will work on any Python installation,
regardless of platform---it's probably easier to just write your C code in the
sensible way.

You can define and undefine pre-processor macros with the @code{define_macros} and
@code{undef_macros} options. @code{define_macros} takes a list of @code{(name, value)}
tuples, where @code{name} is the name of the macro to define (a string) and
@code{value} is its value: either a string or @code{None}.  (Defining a macro @code{FOO}
to @code{None} is the equivalent of a bare @code{#define FOO} in your C source: with
most compilers, this sets @code{FOO} to the string @code{1}.)  @code{undef_macros} is
just a list of macros to undefine.

例如:

@example
Extension(...,
          define_macros=[('NDEBUG', '1'),
                         ('HAVE_STRFTIME', None)],
          undef_macros=['HAVE_FOO', 'HAVE_BAR'])
@end example

is the equivalent of having this at the top of every C source file:

@example
#define NDEBUG 1
#define HAVE_STRFTIME
#undef HAVE_FOO
#undef HAVE_BAR
@end example

@node 库选项,其他选项<2>,预处理器选项,描述扩展模块
@anchor{distutils/setupscript library-options}@anchor{45c2}
@subsubsection 库选项


You can also specify the libraries to link against when building your extension,
and the directories to search for those libraries.  The @code{libraries} option is
a list of libraries to link against, @code{library_dirs} is a list of directories
to search for libraries at  link-time, and @code{runtime_library_dirs} is a list of
directories to  search for shared (dynamically loaded) libraries at run-time.

For example, if you need to link against libraries known to be in the standard
library search path on target systems

@example
Extension(...,
          libraries=['gdbm', 'readline'])
@end example

If you need to link with libraries in a non-standard location, you'll have to
include the location in @code{library_dirs}:

@example
Extension(...,
          library_dirs=['/usr/X11R6/lib'],
          libraries=['X11', 'Xt'])
@end example

(Again, this sort of non-portable construct should be avoided if you intend to
distribute your code.)

@c XXX Should mention clib libraries here or somewhere else!

@node 其他选项<2>,,库选项,描述扩展模块
@anchor{distutils/setupscript other-options}@anchor{45c3}
@subsubsection 其他选项


There are still some other options which can be used to handle special cases.

The @code{optional} option is a boolean; if it is true,
a build failure in the extension will not abort the build process, but
instead simply not install the failing extension.

The @code{extra_objects} option is a list of object files to be passed to the
linker. These files must not have extensions, as the default extension for the
compiler is used.

@code{extra_compile_args} and @code{extra_link_args} can be used to
specify additional command line options for the respective compiler and linker
command lines.

@code{export_symbols} is only useful on Windows.  It can contain a list of
symbols (functions or variables) to be exported. This option is not needed when
building compiled extensions: Distutils  will automatically add @code{initmodule}
to the list of exported symbols.

The @code{depends} option is a list of files that the extension depends on
(for example header files). The build command will call the compiler on the
sources to rebuild extension if any on this files has been modified since the
previous build.

@node Relationships between Distributions and Packages,Installing Scripts,描述扩展模块,编写安装脚本
@anchor{distutils/setupscript relationships-between-distributions-and-packages}@anchor{45c4}
@subsection Relationships between Distributions and Packages


A distribution may relate to packages in three specific ways:


@enumerate 

@item 
它可以要求包或模块。

@item 
它可以提供包或模块。

@item 
It can obsolete packages or modules.
@end enumerate

These relationships can be specified using keyword arguments to the
@ref{3dc9,,distutils.core.setup()} function.

Dependencies on other Python modules and packages can be specified by supplying
the @emph{requires} keyword argument to @code{setup()}. The value must be a list of
strings.  Each string specifies a package that is required, and optionally what
versions are sufficient.

To specify that any version of a module or package is required, the string
should consist entirely of the module or package name. Examples include
@code{'mymodule'} and @code{'xml.parsers.expat'}.

If specific versions are required, a sequence of qualifiers can be supplied in
parentheses.  Each qualifier may consist of a comparison operator and a version
number.  The accepted comparison operators are:

@example
<    >    ==
<=   >=   !=
@end example

These can be combined by using multiple qualifiers separated by commas (and
optional whitespace).  In this case, all of the qualifiers must be matched; a
logical AND is used to combine the evaluations.

Let's look at a bunch of examples:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Requires Expression

@tab

解释

@item

@code{==1.0}

@tab

Only version @code{1.0} is compatible

@item

@code{>1.0, !=1.5.1, <2.0}

@tab

Any version after @code{1.0} and before @code{2.0}
is compatible, except @code{1.5.1}

@end multitable


Now that we can specify dependencies, we also need to be able to specify what we
provide that other distributions can require.  This is done using the @emph{provides}
keyword argument to @code{setup()}. The value for this keyword is a list of
strings, each of which names a Python module or package, and optionally
identifies the version.  If the version is not specified, it is assumed to match
that of the distribution.

Some examples:


@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

Provides Expression

@tab

解释

@item

@code{mypkg}

@tab

Provide @code{mypkg}, using the distribution
version

@item

@code{mypkg (1.1)}

@tab

Provide @code{mypkg} version 1.1, regardless of
the distribution version

@end multitable


A package can declare that it obsoletes other packages using the @emph{obsoletes}
keyword argument.  The value for this is similar to that of the @emph{requires}
keyword: a list of strings giving module or package specifiers.  Each specifier
consists of a module or package name optionally followed by one or more version
qualifiers.  Version qualifiers are given in parentheses after the module or
package name.

The versions identified by the qualifiers are those that are obsoleted by the
distribution being described.  If no qualifiers are given, all versions of the
named module or package are understood to be obsoleted.

@node Installing Scripts,Installing Package Data,Relationships between Distributions and Packages,编写安装脚本
@anchor{distutils/setupscript distutils-installing-scripts}@anchor{45c5}@anchor{distutils/setupscript installing-scripts}@anchor{45c6}
@subsection Installing Scripts


So far we have been dealing with pure and non-pure Python modules, which are
usually not run by themselves but imported by scripts.

Scripts are files containing Python source code, intended to be started from the
command line.  Scripts don't require Distutils to do anything very complicated.
The only clever feature is that if the first line of the script starts with
@code{#!} and contains the word "python", the Distutils will adjust the first line
to refer to the current interpreter location. By default, it is replaced with
the current interpreter location.  The @code{--executable} (or @code{-e})
option will allow the interpreter path to be explicitly overridden.

The @code{scripts} option simply is a list of files to be handled in this
way.  From the PyXML setup script:

@example
setup(...,
      scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
      )
@end example


在 3.1 版更改: All the scripts will also be added to the @code{MANIFEST} file if no template is
provided.  See @ref{3dcc,,指定要分发的文件}.


@node Installing Package Data,Installing Additional Files,Installing Scripts,编写安装脚本
@anchor{distutils/setupscript distutils-installing-package-data}@anchor{45c7}@anchor{distutils/setupscript installing-package-data}@anchor{45c8}
@subsection Installing Package Data


Often, additional files need to be installed into a package.  These files are
often data that's closely related to the package's implementation, or text files
containing documentation that might be of interest to programmers using the
package.  These files are called @emph{package data}.

Package data can be added to packages using the @code{package_data} keyword
argument to the @code{setup()} function.  The value must be a mapping from
package name to a list of relative path names that should be copied into the
package.  The paths are interpreted as relative to the directory containing the
package (information from the @code{package_dir} mapping is used if appropriate);
that is, the files are expected to be part of the package in the source
directories. They may contain glob patterns as well.

The path names may contain directory portions; any necessary directories will be
created in the installation.

For example, if a package should contain a subdirectory with several data files,
the files can be arranged like this in the source tree:

@example
setup.py
src/
    mypkg/
        __init__.py
        module.py
        data/
            tables.dat
            spoons.dat
            forks.dat
@end example

The corresponding call to @code{setup()} might be:

@example
setup(...,
      packages=['mypkg'],
      package_dir=@{'mypkg': 'src/mypkg'@},
      package_data=@{'mypkg': ['data/*.dat']@},
      )
@end example


在 3.1 版更改: All the files that match @code{package_data} will be added to the @code{MANIFEST}
file if no template is provided.  See @ref{3dcc,,指定要分发的文件}.


@node Installing Additional Files,Additional meta-data,Installing Package Data,编写安装脚本
@anchor{distutils/setupscript distutils-additional-files}@anchor{45c9}@anchor{distutils/setupscript installing-additional-files}@anchor{45ca}
@subsection Installing Additional Files


The @code{data_files} option can be used to specify additional files needed
by the module distribution: configuration files, message catalogs, data files,
anything which doesn't fit in the previous categories.

@code{data_files} specifies a sequence of (@emph{directory}, @emph{files}) pairs in the
following way:

@example
setup(...,
      data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                  ('config', ['cfg/data.cfg'])],
     )
@end example

Each (@emph{directory}, @emph{files}) pair in the sequence specifies the installation
directory and the files to install there.

Each file name in @emph{files} is interpreted relative to the @code{setup.py}
script at the top of the package source distribution. Note that you can
specify the directory where the data files will be installed, but you cannot
rename the data files themselves.

The @emph{directory} should be a relative path. It is interpreted relative to the
installation prefix (Python's @code{sys.prefix} for system installations;
@code{site.USER_BASE} for user installations). Distutils allows @emph{directory} to be
an absolute installation path, but this is discouraged since it is
incompatible with the wheel packaging format. No directory information from
@emph{files} is used to determine the final location of the installed file; only
the name of the file is used.

You can specify the @code{data_files} options as a simple sequence of files
without specifying a target directory, but this is not recommended, and the
@code{install} command will print a warning in this case. To install data
files directly in the target directory, an empty string should be given as the
directory.


在 3.1 版更改: All the files that match @code{data_files} will be added to the @code{MANIFEST}
file if no template is provided.  See @ref{3dcc,,指定要分发的文件}.


@node Additional meta-data,Debugging the setup script,Installing Additional Files,编写安装脚本
@anchor{distutils/setupscript additional-meta-data}@anchor{45cb}@anchor{distutils/setupscript meta-data}@anchor{45b7}
@subsection Additional meta-data


The setup script may include additional meta-data beyond the name and version.
This information includes:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxx} 
@headitem

元数据

@tab

描述

@tab

值

@tab

注释

@item

@code{name}

@tab

包名称

@tab

短字符串

@tab

(1)

@item

@code{version}

@tab

此发布的版本

@tab

短字符串

@tab

(1)(2)

@item

@code{author}

@tab

软件包作者的姓名

@tab

短字符串

@tab

(3)

@item

@code{author_email}

@tab

软件包的作者的电子邮件地址

@tab

电子邮件地址

@tab

(3)

@item

@code{maintainer}

@tab

软件包维护者的名字

@tab

短字符串

@tab

(3)

@item

@code{maintainer_email}

@tab

软件包维护者的电子邮件地址

@tab

电子邮件地址

@tab

(3)

@item

@code{url}

@tab

软件包的网址

@tab

网址

@tab

(1)

@item

@code{description}

@tab

软件包的简短摘要说明

@tab

短字符串

@tab

@item

@code{long_description}

@tab

软件包的详细说明

@tab

长字符串

@tab

(4)

@item

@code{download_url}

@tab

可以下载软件包的网址

@tab

网址

@tab

@item

@code{classifiers}

@tab

分类列表

@tab

字符串列表

@tab

(6)(7)

@item

@code{platforms}

@tab

平台清单

@tab

字符串列表

@tab

(6)(8)

@item

@code{keywords}

@tab

关键字列表

@tab

字符串列表

@tab

(6)(8)

@item

@code{license}

@tab

软件包许可证

@tab

短字符串

@tab

(5)

@end multitable


注释:


@enumerate 

@item 
These fields are required.

@item 
It is recommended that versions take the form @emph{major.minor[.patch[.sub]]}.

@item 
Either the author or the maintainer must be identified. If maintainer is
provided, distutils lists it as the author in @code{PKG-INFO}.

@item 
The @code{long_description} field is used by PyPI when you publish a package,
to build its project page.

@item 
The @code{license} field is a text indicating the license covering the
package where the license is not a selection from the "License" Trove
classifiers. See the @code{Classifier} field. Notice that
there's a @code{licence} distribution option which is deprecated but still
acts as an alias for @code{license}.

@item 
This field must be a list.

@item 
The valid classifiers are listed on
PyPI@footnote{https://pypi.org/classifiers}.

@item 
To preserve backward compatibility, this field also accepts a string. If
you pass a comma-separated string @code{'foo, bar'}, it will be converted to
@code{['foo', 'bar']}, Otherwise, it will be converted to a list of one
string.
@end enumerate


@table @asis

@item 'short string'

A single line of text, not more than 200 characters.

@item 'long string'

Multiple lines of plain text in reStructuredText format (see
@indicateurl{http://docutils.sourceforge.net/}).

@item 'list of strings'

See below.
@end table

Encoding the version information is an art in itself. Python packages generally
adhere to the version format @emph{major.minor[.patch][sub]}. The major number is 0
for initial, experimental releases of software. It is incremented for releases
that represent major milestones in a package. The minor number is incremented
when important new features are added to the package. The patch number
increments when bug-fix releases are made. Additional trailing version
information is sometimes used to indicate sub-releases.  These are
"a1,a2,...,aN" (for alpha releases, where functionality and API may change),
"b1,b2,...,bN" (for beta releases, which only fix bugs) and "pr1,pr2,...,prN"
(for final pre-release release testing). Some examples:


@table @asis

@item 0.1.0

the first, experimental release of a package

@item 1.0.1a2

the second alpha release of the first patch version of 1.0
@end table

@code{classifiers} must be specified in a list:

@example
setup(...,
      classifiers=[
          'Development Status :: 4 - Beta',
          'Environment :: Console',
          'Environment :: Web Environment',
          'Intended Audience :: End Users/Desktop',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: Python Software Foundation License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Microsoft :: Windows',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Topic :: Communications :: Email',
          'Topic :: Office/Business',
          'Topic :: Software Development :: Bug Tracking',
          ],
      )
@end example


在 3.7 版更改: @ref{3dc9,,setup} now warns when @code{classifiers}, @code{keywords}
or @code{platforms} fields are not specified as a list or a string.


@node Debugging the setup script,,Additional meta-data,编写安装脚本
@anchor{distutils/setupscript debug-setup-script}@anchor{45cc}@anchor{distutils/setupscript debugging-the-setup-script}@anchor{45cd}
@subsection Debugging the setup script


Sometimes things go wrong, and the setup script doesn't do what the developer
wants.

Distutils catches any exceptions when running the setup script, and print a
simple error message before the script is terminated.  The motivation for this
behaviour is to not confuse administrators who don't know much about Python and
are trying to install a package.  If they get a big long traceback from deep
inside the guts of Distutils, they may think the package or the Python
installation is broken because they don't read all the way down to the bottom
and see that it's a permission problem.

On the other hand, this doesn't help the developer to find the cause of the
failure. For this purpose, the 
@geindex DISTUTILS_DEBUG
@geindex 环境变量; DISTUTILS_DEBUG
@code{DISTUTILS_DEBUG} environment variable can be set
to anything except an empty string, and distutils will now print detailed
information about what it is doing, dump the full traceback when an exception
occurs, and print the whole command line when an external program (like a C
compiler) fails.

@node 编写设置脚本的配置文件,创建源代码分发包,编写安装脚本,分发 Python 模块（遗留版本）
@anchor{distutils/configfile doc}@anchor{45ce}@anchor{distutils/configfile setup-config}@anchor{45cf}@anchor{distutils/configfile writing-the-setup-configuration-file}@anchor{45d0}
@section 编写设置脚本的配置文件


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

通常，在 @emph{事前} 就写出构建发布包所需的一切是不可能的：你可能需要从用户或者用户的系统获取一些信息，才能继续下去。 只要这些信息相当简单 —— 例如一个用于搜索 C 头文件或库的目录列表 —— 那么提供配置文件 @code{setup.cfg} 供用户配置就是一个低成本且方便的解决方式。 配置文件还允许你为任何命令选项提供默认值，而安装器可以通过命令行或编辑配置文件来覆盖这些默认值。

安装配置文件是在安装脚本和安装脚本命令行之间一个适当的折衷方式 --- 安装脚本在理想情况下应当不受安装者的控制 @footnote{@w{(1)} 
在 Distutils 完全支持自动配置之前，这一理想可能是无法实现的。
} --- 而安装脚本命令行则在你的控制范围之外且完全取决于安装者的选择。 实际上，@code{setup.cfg} (以及目标系统上的其他任何 Distutils 配置文件) 是在配置脚本之后、命令行之前被处理。 这导致了几个有用的后果:

@c % (If you have more advanced needs, such as determining which extensions

@c % to build based on what capabilities are present on the target system,

@c % then you need the Distutils ``auto-configuration'' facility.  This

@c % started to appear in Distutils 0.9 but, as of this writing, isn't mature

@c % or stable enough yet for real-world use.)


@itemize *

@item 
安装者可以通过编辑 @code{setup.cfg} 来覆盖你放在 @code{setup.py} 中的配置

@item 
你可以为无法在 @code{setup.py} 中方便设置的选项提供非标准的默认值

@item 
安装者可以使用 @code{setup.py} 的命令行选项来覆盖 @code{setup.cfg} 中的一切
@end itemize

配置文件的基本语法很简单:

@example
[command]
option=value
...
@end example

其中 @emph{command} 是一个 Distutils 命令 (例如 @code{build_py}, @code{install})，而 @emph{option} 是该命令所支持的某个选项。 可以为每个命令提供任意数量的选项，并且可以在文件中包括任意数量的命令组。 空白行会被忽略，以一个 @code{'#'} 开始的注释行也是如此。 长选项值可以简单地通过缩进后续行的方式被拆分为多行。

你可以用通用的 @code{--help} 选项找出特定命令所支持的选项列表，例如

@example
$ python setup.py --help build_ext
[...]
Options for 'build_ext' command:
  --build-lib (-b)     directory for compiled extension modules
  --build-temp (-t)    directory for temporary files (build by-products)
  --inplace (-i)       ignore build-lib and put compiled extensions into the
                       source directory alongside your pure Python modules
  --include-dirs (-I)  list of directories to search for header files
  --define (-D)        C preprocessor macros to define
  --undef (-U)         C preprocessor macros to undefine
  --swig-opts          list of SWIG command line options
[...]
@end example

请注意在命令行中拼写为 @code{--foo-bar} 的选项在配置文件中会拼写为 @code{foo_bar}。
@anchor{distutils/configfile distutils-build-ext-inplace}@anchor{45d1}
例如，假设你希望你的扩展在“原地”构建 --- 就是说你有一个扩展 @code{pkg.ext}，你希望编译出的扩展文件 (例如在 Unix 上为 @code{ext.so}) 放在与你的纯 Python 模块 @code{pkg.mod1} 和 @code{pkg.mod2} 相同的源目录中。 你总是可以在命令行中使用 @code{--inplace} 选项来确保这一点:

@example
python setup.py build_ext --inplace
@end example

但是这要求你总是显式地指定 @code{build_ext} 命令，并且记得提供 @code{--inplace}。 一个更容易的方式是通过将其编码在此发布包的配置文件 @code{setup.cfg} 中，“设置并忘记”该选项。

@example
[build_ext]
inplace=1
@end example

这将影响此模块发布包的所有构建，不论你是否显式指定 @code{build_ext}。 如果你在你的源发布包中包括了 @code{setup.cfg}，它还将影响最终用户的构建 --- 对此选项来说这可能不是个好主意，因为总是原地构建扩展会破坏模块发布包的安装。 不过在某些特殊情况下，模块是在其安装目录中被构建的，因此这可能会是个有用的功能。 （但是，发布预期在其安装目录中被构建的扩展几乎总是一个坏主意。）

另一个例子：特定的命令会接受许多在多次运行中都不发生变化的选项；例如，@code{bdist_rpm} 需要知道为创建 RPM 发布包生成 "spec" 文件所要求的所有信息。 这些信息有的来自安装脚本，有的由 Distutils 自动生成（例如已安装文件列表）。 但有的则必须作为 @code{bdist_rpm} 的选项提供，每次运行时都在命令行中完成将会非常繁琐。 因此，这里提供 Distutils 本身的 @code{setup.cfg} 中的一段代码:

@example
[bdist_rpm]
release = 1
packager = Greg Ward <gward@@python.net>
doc_files = CHANGES.txt
            README.txt
            USAGE.txt
            doc/
            examples/
@end example

请注意 @code{doc_files} 选项只是一个空格分隔以提高可读性的多行字符串。


@subsubheading 参见



@table @asis

@item "安装 Python 模块" 中的 @ref{45d2,,Syntax of config files}

有关配置文件的更多信息可在系统管理员手册中查看。
@end table


@node 创建源代码分发包,创建构建分布,编写设置脚本的配置文件,分发 Python 模块（遗留版本）
@anchor{distutils/sourcedist doc}@anchor{45d3}@anchor{distutils/sourcedist creating-a-source-distribution}@anchor{45d4}@anchor{distutils/sourcedist source-dist}@anchor{45d5}
@section 创建源代码分发包


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

如 @ref{45af,,一个简单的例子} 一节所示，可以使用 @code{sdist} 命令来创建一个源代码分发包。 在最简单的场景下，:

@example
python setup.py sdist
@end example

（假定你没有在设置脚本或配置文件中指定任何 @code{sdist} 选项），@code{sdist} 将创建基于当前平台的默认格式的归档。 在 Unix 上默认格式为 gzip 的 tar 文件，而在 Windows 上则为 ZIP 文件。

你可以使用 @code{--formats} 选项来指定任何你想要的格式，例如:

@example
python setup.py sdist --formats=gztar,zip
@end example

创建一个 gzip 的 tar 文件和一个 zip 文件。 可用的格式有:


@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxx} 
@headitem

文件格式

@tab

描述

@tab

注释

@item

@code{zip}

@tab

zip 文件 (@code{.zip})

@tab

(1),(3)

@item

@code{gztar}

@tab

gzip'ed tar 文件 (@code{.tar.gz})

@tab

(2)

@item

@code{bztar}

@tab

bzip2'ed tar 文件 (@code{.tar.bz2})

@tab

(5)

@item

@code{xztar}

@tab

xz'ed tar 文件 (@code{.tar.xz})

@tab

(5)

@item

@code{ztar}

@tab

压缩 tar 文件 (@code{.tar.Z})

@tab

(4),(5)

@item

@code{tar}

@tab

tar 文件 (@code{.tar})

@tab

(5)

@end multitable



在 3.5 版更改: 添加了对 @code{xztar} 格式的支持


注释:


@enumerate 

@item 
默认Windows

@item 
默认 Unix

@item 
需要有外部 @code{zip} 工具或 @ref{14b,,zipfile} 模块（自 Python 1.6 起是标准 Python 库的一部分）

@item 
需要有 @code{compress} 程序。 请注意此格式计划要弃用并将在未来的 Python 版本中被移除。

@item 
已被 PEP 527@footnote{https://www.python.org/dev/peps/pep-0527/} 弃用; PyPI@footnote{https://pypi.org} 只接受 @code{.zip} 和 @code{.tar.gz} 文件。
@end enumerate

当使用任意 @code{tar} 格式 (@code{gztar}, @code{bztar}, @code{xztar}, @code{ztar} 或 @code{tar}) 时，在 Unix 中你可以指定将为每个归档成员设置的 @code{owner} 和 @code{group} 名称。

举例来说，如果你希望归档中所有文件均为 root 所有:

@example
python setup.py sdist --owner=root --group=root
@end example

@menu
* 指定要分发的文件:: 
* 声明相关选项:: 

@end menu

@node 指定要分发的文件,声明相关选项,,创建源代码分发包
@anchor{distutils/sourcedist manifest}@anchor{3dcc}@anchor{distutils/sourcedist specifying-the-files-to-distribute}@anchor{45d6}
@subsection 指定要分发的文件


如果你没有显式提供文件列表（或如何生成该列表的说明），则 @code{sdist} 命令会将一个最小化默认集加入源代码分发版:


@itemize *

@item 
通过 @code{py_modules} 和 @code{packages} 选项指明的所有 Python 源文件

@item 
在 @code{ext_modules} 在 @code{libraries} 选项提及的所有 C 源代码文件

@c XXX getting C library sources currently broken---no
@c :meth:`get_source_files` method in :file:`build_clib.py`!

@item 
通过 @code{scripts} 选项标识的脚本，参见 @ref{45c5,,Installing Scripts}。

@item 
任何看起来像是测试脚本的文件: @code{test/test*.py} (目前，Distutils 不会对测试脚本做除了将它们包括到源代码分发版以外的任何操作，但是在未来将会有一个测试 Python 模块分发版的标准)

@item 
任何标准的 README 文件 (@code{README}, @code{README.txt} 或 @code{README.rst}), @code{setup.py} (或任何你指定的安装脚本) 以及 @code{setup.cfg}。

@item 
所有匹配 @code{package_data} 元数据的文件。 参见 @ref{45c7,,Installing Package Data}。

@item 
所有匹配 @code{data_files} 元数据的文件。 参见 @ref{45c9,,Installing Additional Files}。
@end itemize

有时这就足够了，但通常你还会希望指定要分发的额外文件。 实现这一点的通常方式是编写一个 @emph{声明模板}，默认名称为 @code{MANIFEST.in}。 声明模板就是一个有关如何生成你的声明文件 @code{MANIFEST} 的指令列表，也就是要实际包括在你的源代码分发版中的文件的列表。 @code{sdist} 命令会处理这个模板并基于其指令及其在文件系统中的查找结果生成一个声明文件。

如果你想要制作你自己的声明文件，格式很简单：每行一个文件名，仅限常规文件。 如果你提供你自己的 @code{MANIFEST}，你必须指明一切：上面描述的默认集将不适用于这种情况。


在 3.1 版更改: 现有的已生成 @code{MANIFEST} 将被生成而无需 @code{sdist} 来将其修改时间与 @code{MANIFEST.in} 或 @code{setup.py} 的修改时间进行比较。



在 3.1.3 版更改: @code{MANIFEST} 文件以一个表明它们已生成的注释开始。 没有这条注释的文件不会被覆盖或移除。



在 3.2.2 版更改: @code{sdist} 将在不存在 @code{MANIFEST.in} 时读取一个 @code{MANIFEST} 文件，如它以前所做的一样。



在 3.7 版更改: @code{README.rst} 现在已被包括在 distutils 标准 README 列表中。


声明模板每行都有一个命令，其中每个命令指定了一组源代码发布版中要包括或排除的文件。 举例来说，我们再次关注 Distutils 自己的声明模板:

@example
include *.txt
recursive-include examples *.txt *.py
prune examples/sample?/build
@end example

其含义应当很清楚：包括发布在根目录中所有匹配 @code{*.txt} 的文件，在 @code{examples} 目录下任何位置上匹配 @code{*.txt} 或 @code{*.py} 的所有文件，并排除匹配 @code{examples/sample?/build} 的所有目录。 所有这些操作都将在标准的包括集 @emph{之后} 执行，因此你可以通过在声明模板中的显式指令来排除标准集中的文件。 （或者，你也可以使用 @code{--no-defaults} 选项来完全禁用标准集。） 在声明模板迷你语言中还有一些其他的可用命令；参见 @ref{45d7,,创建源码发行包; sdist 命令} 小节。

声明模板中命令的顺序是很重要的：在初始状态下，我们有如上所述的默认文件列表，而模板中的每个命令将在该文件列表中添加或移除条目。 一旦我们完全处理好声明模板，我们将再移除不应包括在源代码发布版中的文件:


@itemize *

@item 
Distutils "构建" 目录树中的所有文件 (默认值:file:@cite{build/})

@item 
目录中所有名为 @code{RCS}, @code{CVS}, @code{.svn}, @code{.hg}, @code{.git}, @code{.bzr} 或 @code{_darcs} 的文件
@end itemize

现在我们有了完整的文件列表，它已被写入声明以供将来引用，并随后用于构建源代码分发压缩 包。

你可以通过 @code{--no-defaults} 选项禁用默认的包括文件集，你还可以通过 @code{--no-prune} 禁用默认的排除文件集。

跟随 Distutils 自己的声明模板，让我们追踪' own manifest template, let's trace how the @code{sdist} 命令是如何构建要包括在 Distutils 源代码分发版中的文件列表的:


@enumerate 

@item 
包括 @code{distutils} 和 @code{distutils/command} 子目录中的所有 Python 源代码文件（因为与这两个目录对应的包在 setup 脚本的 @code{packages} 选项中被提及 --- 参见 @ref{45b0,,编写安装脚本} 一节）

@item 
包括 @code{README.txt}, @code{setup.py} 和 @code{setup.cfg} (标准文件)

@item 
包括 @code{test/test*.py} (标准文件)

@item 
包括分发根目录下的 @code{*.txt} (这将第二次找到 @code{README.txt}，但这样的冗余随后会被清除)

@item 
包括 @code{examples} 下所有子目录树中匹配 @code{*.txt} 或 @code{*.py} 的任何文件，

@item 
排除从匹配 @code{examples/sample?/build} 的目录开始的子目录树中的所有文件 --- 这可能会排除之前两个步骤所包括的文件，因此重要的一点是声明模板中的 @code{prune} 命令应放在 @code{recursive-include} 命令之后

@item 
排除整个 @code{build} 目录树，以及任何 @code{RCS}, @code{CVS}, @code{.svn}, @code{.hg}, @code{.git}, @code{.bzr} and @code{_darcs} 目录
@end enumerate

就像在设置脚本中一样，声明模板中的文件和目录名应当总是以斜杠分隔；Distutils 将会负责把它们转化为你的系统平台上的标准表示形式。 通过这种方式，声明模板将可跨操作系统移植。

@node 声明相关选项,,指定要分发的文件,创建源代码分发包
@anchor{distutils/sourcedist manifest-options}@anchor{45d8}@anchor{distutils/sourcedist manifest-related-options}@anchor{45d9}
@subsection 声明相关选项


针对 @code{sdist} 命令的正常操作过程如下:


@itemize *

@item 
如果声明文件 (默认为 @code{MANIFEST}) 存在且第一行不为表示它是由 @code{MANIFEST.in} 生成的注释，则它会被不加修改地原样使用

@item 
如果声明文件不存在或是在此之前被自动生成的，则读取 @code{MANIFEST.in} 并创建声明文件

@item 
如果 @code{MANIFEST} 或 @code{MANIFEST.in} 均不存在，则使用默认文件集创建声明文件

@item 
使用当前 @code{MANIFEST} (刚生成的或读入的) 中的文件列表创建源代码分发压缩包
@end itemize

有数个选项可以修改此行为。 首先，使用 @code{--no-defaults} 和 @code{--no-prune} 来禁用标准的 "包括" 和 "排除" 集。

第二，你可能只是想要（重）生成声明文件，但不想要创建源代码分发包:

@example
python setup.py sdist --manifest-only
@end example

@code{-o} 是 @code{--manifest-only} 的缩写。

@node 创建构建分布,Distutils 示例,创建源代码分发包,分发 Python 模块（遗留版本）
@anchor{distutils/builtdist doc}@anchor{45da}@anchor{distutils/builtdist built-dist}@anchor{45db}@anchor{distutils/builtdist creating-built-distributions}@anchor{45dc}
@section 创建构建分布


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

“构建分发版”即你通常所认为的“二进制包”或“安装程序”（取决于你的技术背景）。 但它并不一定是二进制的，因为它可能只包含 Python 源代码和/或字节码；并且我们也不将其称为包，因为这个词在 Python 中已经被使用。 （而“安装程序”是主流桌面系统领域的一个专有术语。）

分发版可以让你的模块分发安装器尽可能地方便易用：对于基于 RPM 的 Linux 系统的用户，它将为二进制 RPM；对于 Windows 的用户，它将为可执行文件安装器；对于基于 Debian 的 Linux 用户，它将为 Debian 安装包；诸如此类。 显然，没有人能为世界上所有的系统平台都构建分发版，因此 Distutils 被设计用来让模块开发者能够专注于他们的专长 --- 编写代码并创建源代码分发版 --- 而让另一群作为中介的 @emph{打包者} 负责在尽可能多的受支持系统平台上将源代码分发版转换为构建分发版。

当然，模块开发者可以是自己模块的打包者；或者打包者也可以是住在别处的“某一位”能够接触到原始开发者接触不到的特定系统平台的志愿者；或者还可以是一个定期抓取新的源代码分发版并在尽可能多的受支持系统平台上将其转换为构建分发版的软件。 无论他们属于哪一种，打包者都会使用设置脚本和 @code{bdist} 命令族来生成构建分发版。

作为一个简单示例，如果我在 Distutils 源代码树中运行以下命令:

@example
python setup.py bdist
@end example

则 Distutils 将构建我的模块分发版（在此情况下即 Distutils 本身），执行“模拟”安装（同样是在 @code{build} 目录中），并为我的系统平台创建默认类型的构建分发版。 构建分发版的默认格式在 Unix 上是一个“非自动” tar 文件，而在 Windows 上则是一个简单的可执行文件安装器。 （此 tar 文件被称为“非自动”是因为它必须在指定的位置上解包方可使用。）

这样，上述命令在 Unix 系统上将会创建 @code{Distutils-1.0.@emph{plat}.tar.gz}；在正确的位置上解包这个 tar 文件将会装好 Distutils，就像是你下载了源代码分发版并运行 @code{python setup.py install} 一样。 （这个“正确的位置”可能是文件系统根目录或 Python 的 @code{@emph{prefix}} 目录，具体取决于提供给 @code{bdist_dumb} 命令的选项；在默认情况下是相对于 @code{@emph{prefix}} 创建非自动颁发版。）

显然，对于纯粹的 Python 分发版来说，这并不比运行 @code{python setup.py install} 更简单 --- 但是对于包括需要被编译的扩展的非纯粹的分发版来说，就可能是有人能使用你的扩展而有人不能使用的差别。 而创建“自动”构建分发版，例如 RPM 包或 Windows 的可执行文件安装器，对于用户来说就会更加方便，即使你的分发版不包括任何扩展。

@code{bdist} 命令有一个 @code{--formats} 选项，与 @code{sdist} 命令类似，你可以用该选项来选择要生成的构建分发版类型：例如，:

@example
python setup.py bdist --format=zip
@end example

当在 Unix 系统上运行时，会再次创建 @code{Distutils-1.0.@emph{plat}.zip}，这个归档文件将从根目录被解包以安装 Distutils。

构建分发版的可用格式有:


@multitable {xxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
@headitem

文件格式

@tab

描述

@tab

注释

@item

@code{gztar}

@tab

gzipped tar 文件 (@code{.tar.gz})

@tab

(1)

@item

@code{bztar}

@tab

bzipped tar 文件 (@code{.tar.bz2})

@tab

@item

@code{xztar}

@tab

xzipped tar 文件 (@code{.tar.xz})

@tab

@item

@code{ztar}

@tab

压缩 tar 文件 (@code{.tar.Z})

@tab

(3)

@item

@code{tar}

@tab

tar 文件 (@code{.tar})

@tab

@item

@code{zip}

@tab

zip 文件 (@code{.zip})

@tab

(2),(4)

@item

@code{rpm}

@tab

RPM

@tab

(5)

@item

@code{pkgtool}

@tab

Solaris @code{pkgtool}

@tab

@item

@code{sdux}

@tab

HP-UX @code{swinstall}

@tab

@item

@code{wininst}

@tab

Windows的自解压ZIP文件

@tab

(4)

@item

@code{msi}

@tab

Microsoft安装程序。

@tab

@end multitable



在 3.5 版更改: 添加了对 @code{xztar} 格式的支持


注释:


@enumerate 

@item 
默认 Unix

@item 
默认Windows

@item 
需要外部 @code{compress} 工具。

@item 
需要有外部 @code{zip} 工具或 @ref{14b,,zipfile} 模块（自 Python 1.6 起是标准 Python 库的一部分）

@item 
需要有外部 @code{rpm} 工具，版本号为 3.0.4 或以上（可使用 @code{rpm --version} 查看你所使用的版本）
@end enumerate

你不必附带 @code{--formats} 来使用 @code{bdist} 命令；你还可以使用直接实现了你想要的特定格式的命令。 某些这样的 @code{bdist} "子命令" 实际上会生成几种相似的格式；例如，@code{bdist_dumb} 命令将生成所有 "非自动" 归档格式 (@code{tar}, @code{gztar}, @code{bztar}, @code{xztar}, @code{ztar} 和 @code{zip})，而 @code{bdist_rpm} 将同时生成二进制和源代码 RPM。 @code{bdist} 子命令以及每个子命令所生成的格式如下:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

命令

@tab

格式

@item

@code{bdist_dumb}

@tab

tar, gztar, bztar, xztar, ztar, zip

@item

@code{bdist_rpm}

@tab

rpm, srpm

@item

@code{bdist_wininst}

@tab

wininst

@item

@code{bdist_msi}

@tab

msi

@end multitable


@cartouche
@quotation 注解 
从Python 3.8开始不推荐使用 bdist_wininst
@end quotation
@end cartouche

@cartouche
@quotation 注解 
bdist_msi 从 Python 3.9 起被弃用。
@end quotation
@end cartouche

以下小节提供了每个 @code{bdist_*} 命令的详情。

@c .. _creating-dumb:

@c Creating dumb built distributions

@c =================================

@c XXX Need to document absolute vs. prefix-relative packages here, but first
@c I have to implement it!

@menu
* 创建RPM软件包:: 
* Creating Windows Installers:: 
* 在 Windows 上的交叉编译:: 
* Vista User Access Control (UAC): Vista User Access Control UAC. 

@end menu

@node 创建RPM软件包,Creating Windows Installers,,创建构建分布
@anchor{distutils/builtdist creating-rpm-packages}@anchor{45dd}@anchor{distutils/builtdist creating-rpms}@anchor{45de}
@subsection 创建RPM软件包


RPM 格式被许多流行的 Linux 发行版所使用，包括 Red Hat, SuSE 和 Mandrake。 如果其中（或任何其他基于 RPM 的 Linux 发行版）的某一个是你的常用环境，那么为相同发行版的其他用户创建 RPM 包是很容易的。 根据你的模块分发版的复杂度以及 Linux 发行版之间的差异性，你还可能创建适用于多个基于 RPM 的发行版的 RPM 包。

为你的模块分发版创建 RPM 的通常方式是运行 @code{bdist_rpm} 命令:

@example
python setup.py bdist_rpm
@end example

或者 @code{bdist} 命令附带 @code{--format} 选项:

@example
python setup.py bdist --formats=rpm
@end example

前者允许你指定 RPM 专属的选项；后者允许你方便地一次性指定多种格式。 如果这两样你全都要，你可以显式地指定多个 @code{bdist_*} 命令及其选项:

@example
python setup.py bdist_rpm --packager="John Doe <jdoe@@example.org>" \
                bdist_wininst --target-version="2.0"
@end example

创建 RPM 包的操作是由 @code{.spec} 文件驱动的，就像 Distutils 的使用是由 setup 脚本驱动的一样。 为了让你更方便，@code{bdist_rpm} 命令通常会根据你在 setup 脚本、命令行和任意 Distutils 配置文件中提供的信息创建一个 @code{.spec} 文件。 @code{.spec} 文件中的各种选项和小节从 setup 脚本中派生的情况如下:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

RPM @code{.spec} 文件配置或选项

@tab

Distutils安装脚本选项

@item

名称

@tab

@code{name}

@item

摘要（在序言中）

@tab

@code{description}

@item

版本

@tab

@code{version}

@item

供应商

@tab

@code{author} 和 @code{author_email}, 或 --- & @code{maintainer} 和 @code{maintainer_email}

@item

版权

@tab

@code{license}

@item

Url

@tab

@code{url}

@item

%d描述（部分）

@tab

@code{long_description}

@end multitable


此外，在 @code{.spec} 文件中还有许多选项在 setup 脚本中没有对应的选项。 这些选项大多是通过传给 @code{bdist_rpm} 命令的选项来处理的，如下所示:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

RPM @code{.spec} 文件配置或选项

@tab

@code{bdist_rpm} 选项

@tab

默认值

@item

发布版本

@tab

@code{release}

@tab

"1"

@item

组织

@tab

@code{group}

@tab

"Development/Libraries"

@item

供应商

@tab

@code{vendor}

@tab

（同上）

@item

打包

@tab

@code{packager}

@tab

(none)

@item

提供

@tab

@code{provides}

@tab

(none)

@item

需求

@tab

@code{requires}

@tab

(none)

@item

冲突

@tab

@code{conflicts}

@tab

(none)

@item

淘汰

@tab

@code{obsoletes}

@tab

(none)

@item

Distribution

@tab

@code{distribution_name}

@tab

(none)

@item

构建要求

@tab

@code{build_requires}

@tab

(none)

@item

Icon

@tab

@code{icon}

@tab

(none)

@end multitable


显然，即使是在命令行中提供少量的此类选项也是很繁琐易出错的，因此通常最好是将它们放在 setup 配置文件 @code{setup.cfg} 中，参见 @ref{45cf,,编写设置脚本的配置文件} 一节。 如果你要分发或打包许多 Python 模块分发版，你可能会需要将适用于所有这些分发版的选项放在你私人的 Distutils 配置文件中 (@code{~/.pydistutils.cfg})。 如果你想要临时禁用此文件，你可以将 @code{--no-user-cfg} 选项传给 @code{setup.py}。

构建一个二进制 RPM 包有三个步骤，它们全都是由 Distutils 自动处理的:


@enumerate 

@item 
创建一个 @code{.spec} 文件，该文件对包进行了描述（类似于 Distutils setup 脚本；实际上 setup 脚本中的许多信息都会出现在 @code{.spec} 文件中）

@item 
创建源 RPM

@item 
创建“二进制”RPM（其中可能包含二进制代码也可能不包含，具体取决于你的模块分发版是否包含 Python 扩展）
@end enumerate

通常，RPM 会将后两个步骤捆绑在一起；当你使用 Distutils 时，三个步骤通常都会捆绑在一起。

如果你愿意，你也可以将这三个步骤分开。 你可以使用 @code{--spec-only} 选项来让 @code{bdist_rpm} 只创建 @code{.spec} 文件并退出；在这种情况下，@code{.spec} 文件将被写到“分发目录” --- 通常为 @code{dist/}，但可通过 @code{--dist-dir} 选项来自定义。 （通常，@code{.spec} 文件会位于“构建树”的深处，在 @code{bdist_rpm} 所创建的一个临时目录中。）

@c % \XXX{this isn't implemented yet---is it needed?!}

@c % You can also specify a custom \file{.spec} file with the

@c % \longprogramopt{spec-file} option; used in conjunction with

@c % \longprogramopt{spec-only}, this gives you an opportunity to customize

@c % the \file{.spec} file manually:

@c %

@c % \ begin{verbatim}

@c % > python setup.py bdist_rpm --spec-only

@c % # ...edit dist/FooBar-1.0.spec

@c % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec

@c % \ end{verbatim}

@c %

@c % (Although a better way to do this is probably to override the standard

@c % \command{bdist\_rpm} command with one that writes whatever else you want

@c % to the \file{.spec} file.)

@node Creating Windows Installers,在 Windows 上的交叉编译,创建RPM软件包,创建构建分布
@anchor{distutils/builtdist creating-windows-installers}@anchor{45df}@anchor{distutils/builtdist creating-wininst}@anchor{45e0}
@subsection Creating Windows Installers


@cartouche
@quotation 警告 
从Python 3.8开始不推荐使用 bdist_wininst
@end quotation
@end cartouche

@cartouche
@quotation 警告 
bdist_msi 从 Python 3.9 起被弃用。
@end quotation
@end cartouche

Executable installers are the natural format for binary distributions on
Windows.  They display a nice graphical user interface, display some information
about the module distribution to be installed taken from the metadata in the
setup script, let the user select a few options, and start or cancel the
installation.

Since the metadata is taken from the setup script, creating Windows installers
is usually as easy as running:

@example
python setup.py bdist_wininst
@end example

or the @code{bdist} command with the @code{--formats} option:

@example
python setup.py bdist --formats=wininst
@end example

If you have a pure module distribution (only containing pure Python modules and
packages), the resulting installer will be version independent and have a name
like @code{foo-1.0.win32.exe}. Note that creating @code{wininst} binary
distributions in only supported on Windows systems.

If you have a non-pure distribution, the extensions can only be created on a
Windows platform, and will be Python version dependent. The installer filename
will reflect this and now has the form @code{foo-1.0.win32-py2.0.exe}.  You
have to create a separate installer for every Python version you want to
support.

The installer will try to compile pure modules into @ref{713,,bytecode} after installation
on the target system in normal and optimizing mode.  If you don't want this to
happen for some reason, you can run the @code{bdist_wininst} command with
the @code{--no-target-compile} and/or the @code{--no-target-optimize}
option.

By default the installer will display the cool "Python Powered" logo when it is
run, but you can also supply your own 152x261 bitmap which must be a Windows
@code{.bmp} file with the @code{--bitmap} option.

The installer will also display a large title on the desktop background window
when it is run, which is constructed from the name of your distribution and the
version number.  This can be changed to another text by using the
@code{--title} option.

The installer file will be written to the "distribution directory" --- normally
@code{dist/}, but customizable with the @code{--dist-dir} option.

@node 在 Windows 上的交叉编译,Vista User Access Control UAC,Creating Windows Installers,创建构建分布
@anchor{distutils/builtdist cross-compile-windows}@anchor{45e1}@anchor{distutils/builtdist cross-compiling-on-windows}@anchor{45e2}
@subsection 在 Windows 上的交叉编译


从 Python 2.6 开始，distutils 能够在不同 Windows 平台之间执行交叉编译。 实际上，这意味着只要安装了正确的工具，你可以使用 32 位版 Windows 来创建 64 位的扩展或是反向操作。

要针对替代平台进行编译，请为构建命令指定 @code{--plat-name} 选项。 目前的有效值为 'win32' 和d  'win-amd64'。 例如，在 32 位版 Windows 上，你可以执行:

@example
python setup.py build --plat-name=win-amd64
@end example

to build a 64bit version of your extension.  The Windows Installers also
support this option, so the command:

@example
python setup.py build --plat-name=win-amd64 bdist_wininst
@end example

将在你的 32 位版 Windows 上创建一个 64 位版的安装程序可执行文件。

要进行交叉编译，你必须下载 Python 源代码并针对你的目标平台交叉编译 Python 本身 —— 使用 Python 的二进制安装版是无法做到的（因为其中不包括针对其他平台的 .lib 等文件。） 实际上，这意味着 32 位操作系统的用户将需要使用 Visual Studio 2008 来打开 Python 源代码目录树下的 @code{PCbuild/PCbuild.sln} 解决方案并构建 'pythoncore' 项目的 "x64" 配置之后才能进行扩展的交叉编译。

请注意在默认情况下，Visual Studio 2008 并不会安装 64 位编译器或工具。 你可能需要重新执行 Visual Studio 安装过程并选择这些工具（使用控制面板 -> [添加/移除] 程序是检查或修改你的现有安装的一个便捷方式。）

@menu
* 安装后脚本:: 

@end menu

@node 安装后脚本,,,在 Windows 上的交叉编译
@anchor{distutils/builtdist postinstallation-script}@anchor{45e3}@anchor{distutils/builtdist the-postinstallation-script}@anchor{45e4}
@subsubsection 安装后脚本


从 Python 2.3 开始，可以通过 @code{--install-script} 选项指定一个安装后脚本。 必须要指定脚本的主文件名，并且该脚本文件名还必须在传给 setup 函数的参数中列出。

在安装时当所有文件拷贝完毕后该脚本将会在目标系统上运行，并将 @code{argv[1]} 设为 @code{-install}，而在卸载时当文件被移除前会再次运行并将 @code{argv[1]} 设为 @code{-remove}。

安装脚本嵌入在 Windows 安装程序中运行，每个输出 (@code{sys.stdout}, @code{sys.stderr}) 都会被重定向到一个缓冲区并将在脚本完成后显示到 GUI 中。

一些在此上下文中特别有用的功能在安装脚本中作为附加内置函数被提供。

@geindex directory_created() (內置函数)
@geindex file_created() (內置函数)
@anchor{distutils/builtdist directory_created}@anchor{45e5}
@deffn {函数} directory_created (path)
@anchor{distutils/builtdist file_created}@anchor{45e6}
@deffnx {函数} file_created (path)

这些函数应当在安装时的安装后脚本创建某个目录或文件时被调用。 它会将 @emph{path} 注册到卸载程序，这样当分发版被卸载时它将被移除。 安全起见，目录只有在为空时才会被移除。
@end deffn

@geindex get_special_folder_path() (內置函数)
@anchor{distutils/builtdist get_special_folder_path}@anchor{45e7}
@deffn {函数} get_special_folder_path (csidl_string)

此函数可被用来获取 Windows 中的特殊文件夹位置如 Start Menu 或 Desktop。 它将返回相应文件夹的完整路径。 @emph{csidl_string} 必须为下列字符串之一:

@example
"CSIDL_APPDATA"

"CSIDL_COMMON_STARTMENU"
"CSIDL_STARTMENU"

"CSIDL_COMMON_DESKTOPDIRECTORY"
"CSIDL_DESKTOPDIRECTORY"

"CSIDL_COMMON_STARTUP"
"CSIDL_STARTUP"

"CSIDL_COMMON_PROGRAMS"
"CSIDL_PROGRAMS"

"CSIDL_FONTS"
@end example

如果文件夹不能被检索到，会触发 @ref{30b,,OSError} 。

有哪些可用的文件夹取决于的 Windows 的具体版本，并可能受特定配置的影响。 更多细节请参考 Microsoft 的 @code{SHGetSpecialFolderPath()} 函数的文档。
@end deffn

@geindex create_shortcut() (內置函数)
@anchor{distutils/builtdist create_shortcut}@anchor{45e8}
@deffn {函数} create_shortcut (target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])

此函数会创建一个快捷方式。 @emph{target} 是此快捷方式要启动的程序的路径。 @emph{description} 是快捷方式的描述文本。 @emph{filename} 是用户将看到的快捷方式的标题。 @emph{arguments} 指定命令行参数，如果有的话。 @emph{workdir} 是程序的工作目录。 @emph{iconpath} 是包含快捷方式的图标的文件，而 @emph{iconindex} 是 @emph{iconpath} 文件中图标的索引号。 同样地，更多细节请参考 Microsoft 有关 @code{IShellLink} 接口的文档。
@end deffn

@node Vista User Access Control UAC,,在 Windows 上的交叉编译,创建构建分布
@anchor{distutils/builtdist vista-user-access-control-uac}@anchor{45e9}
@subsection Vista User Access Control (UAC)


Starting with Python 2.6, bdist_wininst supports a @code{--user-access-control}
option.  The default is 'none' (meaning no UAC handling is done), and other
valid values are 'auto' (meaning prompt for UAC elevation if Python was
installed for all users) and 'force' (meaning always prompt for elevation).

@cartouche
@quotation 注解 
从Python 3.8开始不推荐使用 bdist_wininst
@end quotation
@end cartouche

@cartouche
@quotation 注解 
bdist_msi 从 Python 3.9 起被弃用。
@end quotation
@end cartouche

@node Distutils 示例,扩展 Distutils,创建构建分布,分发 Python 模块（遗留版本）
@anchor{distutils/examples doc}@anchor{45ea}@anchor{distutils/examples distutils-examples}@anchor{45eb}@anchor{distutils/examples id1}@anchor{45ec}
@section Distutils 示例


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

本章节提供几个基础示例，来帮助用户入门 distutils。关于使用 distutils 的额外信息可以参考 Distutils Cookbook。


@subsubheading 参见



@table @asis

@item Distutils Cookbook@footnote{https://wiki.python.org/moin/Distutils/Cookbook}

一套展示如何更好地控制和使用 distutils 的方法。
@end table


@menu
* 纯 Python 分发（通过 module）:: 
* 纯 Python 分发（通过 包）:: 
* 单个扩展模块:: 
* 检查一个包:: 
* 读取元数据:: 

@end menu

@node 纯 Python 分发（通过 module）,纯 Python 分发（通过 包）,,Distutils 示例
@anchor{distutils/examples pure-mod}@anchor{45ed}@anchor{distutils/examples pure-python-distribution-by-module}@anchor{45ee}
@subsection 纯 Python 分发（通过 module）


如果你要分发一组模块，特别是它们不在特定的包中，你可以在配置脚本中使用 @code{py_modules} 选项单独指定它们。

最简单的情况下，你只用关心两个文件：一个配置脚本，和单个你要分发的模块，这个示例中的 @code{foo.py}: ：

@example
<root>/
        setup.py
        foo.py
@end example

（在本章节的所有图中，@emph{<root>} 表示分发根目录。）这种情况下的一个最小配置脚本是：

@example
from distutils.core import setup
setup(name='foo',
      version='1.0',
      py_modules=['foo'],
      )
@end example

注意分发的包名用 @code{name} 选项单独指定，没有规定它必须和包中单独的模块同名（虽然这也是个可以遵循的好习惯）。然而，分发名用来生成文件名，所以你应该坚持用字母、数字、下划线和连词号。

因为 @code{py_modules} 是个列表，你当然可以指定多个模块，比如，如果你要分发模块 @code{foo} 和 @code{bar}，你的配置可能是这样：

@example
<root>/
        setup.py
        foo.py
        bar.py
@end example

并且配置脚本是：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      py_modules=['foo', 'bar'],
      )
@end example

你可以把模块源文件放进另一个目录，但是如果你有足够的模块，也许用包指定模块更简单，而不是单独列出它们。

@node 纯 Python 分发（通过 包）,单个扩展模块,纯 Python 分发（通过 module）,Distutils 示例
@anchor{distutils/examples pure-pkg}@anchor{45ef}@anchor{distutils/examples pure-python-distribution-by-package}@anchor{45f0}
@subsection 纯 Python 分发（通过 包）


如果你有超过一组模块要分发，特别是它们在不同的包中，也许指定整个包更简单，而不是指定单独的模块。这样即使你的模块不在一个包中也有效；你可以直接令 Distutils 来从根包来处理模块，并且这样对任何其他包也有效（除非你不需要 @code{__init__.py} 文件）。

上一个示例的配置脚本也可以写成：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=['@w{'}],
      )
@end example

（空字符串表示根包。）

如果两个文件移动到子目录，但是依然在根包中，如：

@example
<root>/
        setup.py
        src/      foo.py
                  bar.py
@end example

那么你依然需要指定根包，但是你还需要告诉 Distutils 根包中的源文件在哪：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir=@{'@w{'}: 'src'@},
      packages=['@w{'}],
      )
@end example

更一般地，你要分发多个在同一个包（或者子包）中的模块。举个例子，假设 @code{foo} 和 @code{bar} 模块属于 @code{foobar} 包，排布源文件树的一种方式是：

@example
<root>/
        setup.py
        foobar/
                 __init__.py
                 foo.py
                 bar.py
@end example

这其实是 Distutils 默认的排布，也是你的配置脚本中需要的工作量最小的。

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=['foobar'],
      )
@end example

如果你要把模块放到没有按照它们的包名命名的目录里，那你需要再次使用 @code{package_dir} 选项。比如，如果 @code{src} 目录包含包 @code{foobar} 中的模块：

@example
<root>/
        setup.py
        src/
                 __init__.py
                 foo.py
                 bar.py
@end example

一个合适的配置脚本可以是：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir=@{'foobar': 'src'@},
      packages=['foobar'],
      )
@end example

或者，你可以把主包中的模块直接放到分发根目录：

@example
<root>/
        setup.py
        __init__.py
        foo.py
        bar.py
@end example

这样你的配置文件是：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir=@{'foobar': '@w{'}@},
      packages=['foobar'],
      )
@end example

（空字符串同样表示当前目录。）

如果你有子包，则它们必须显式列在 @code{packages} 中，但是 @code{package_dir} 中的任何条目会自动扩展到子包。（也就是说，Distutils @emph{不会} 扫描你的源码树，而是尝试通过查找 @code{__init__.py} 文件，来弄清哪些目录与 Python 包关联。）这样，如果默认排布产生一个子包：

@example
<root>/
        setup.py
        foobar/
                 __init__.py
                 foo.py
                 bar.py
                 subfoo/
                           __init__.py
                           blah.py
@end example

则相应的配置脚本是：

@example
from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=['foobar', 'foobar.subfoo'],
      )
@end example

@node 单个扩展模块,检查一个包,纯 Python 分发（通过 包）,Distutils 示例
@anchor{distutils/examples single-ext}@anchor{45f1}@anchor{distutils/examples single-extension-module}@anchor{45f2}
@subsection 单个扩展模块


扩展模块用 @code{ext_modules} 选项指定。@code{package_dir} 对在哪寻找扩展源文件无效；它只对纯 Python 模块的源文件有效。最简单的，一个用单个C源文件写的单扩展模块是：

@example
<root>/
        setup.py
        foo.c
@end example

如果 @code{foo} 扩展属于根包，则配置脚本可以是：

@example
from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      ext_modules=[Extension('foo', ['foo.c'])],
      )
@end example

如果扩展在包中，比如 @code{foopkg}，那么

使用完全相同的源文件树排布，通过改变扩展的名字，这个扩展很容易放入 @code{foopkg} 包中：

@example
from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      ext_modules=[Extension('foopkg.foo', ['foo.c'])],
      )
@end example

@node 检查一个包,读取元数据,单个扩展模块,Distutils 示例
@anchor{distutils/examples checking-a-package}@anchor{45f3}
@subsection 检查一个包


@code{check} 命令允许你校验你的包的元数据是否满足生成分发的最低要求。

直接使用你的 @code{setup.py} 脚本来运行它。如果缺了一些东西，@code{check} 会显示警告。

我们来用单个脚本举例：

@example
from distutils.core import setup

setup(name='foobar')
@end example

运行 @code{check} 命令会显示一些警告：

@example
$ python setup.py check
running check
warning: check: missing required meta-data: version, url
warning: check: missing meta-data: either (author and author_email) or
         (maintainer and maintainer_email) should be supplied
@end example

如果你在 @code{long_description} 域中使用 reStructuredText 语法，并且安装了 docutils@footnote{http://docutils.sourceforge.net} ，你可以用 @code{check} 命令，和 @code{restructuredtext} 选项检查语法是否正确。

比如，如果 @code{setup.py} 脚本改成：

@example
from distutils.core import setup

desc = """\
My description
==============

This is the description of the `@w{`}foobar`@w{`} package.
"""

setup(name='foobar', version='1', author='tarek',
    author_email='tarek@@ziade.org',
    url='http://example.com', long_description=desc)
@end example

长描述中有问题的地方，通过使用 @code{docutils} 解析器，@code{check} 能进行删除：

@example
$ python setup.py check --restructuredtext
running check
warning: check: Title underline too short. (line 2)
warning: check: Could not finish the parsing.
@end example

@node 读取元数据,,检查一个包,Distutils 示例
@anchor{distutils/examples reading-the-metadata}@anchor{45f4}
@subsection 读取元数据


@ref{3dc9,,distutils.core.setup()} 函数提供一个通过项目的 @code{setup.py}  脚本，来查询项目的元数据的域的命令行接口：

@example
$ python setup.py --name
distribute
@end example

这个调用通过运行 @ref{3dc9,,distutils.core.setup()} 函数读取 @code{name} 元数据。然而，当源文件或者二进制分发用 Distutils 创建时，元数据域写入一个名为 @code{PKG-INFO} 的静态文件。当一个基于Distutils的项目安装在 Python 中时，@code{PKG-INFO} 文件随着分发的模块和包一起复制到 @code{NAME-VERSION-pyX.X.egg-info} 中，其中 @code{NAME} 是项目的名字，@code{VERSION} 是元数据中定义的版本， @code{pyX.X} 则是 Python 的大版本和小版本，如 @code{2.7} 或者 @code{3.2}。

你可以读回静态文件，使用 @code{distutils.dist.DistributionMetadata} 类和它的 @code{read_pkg_file()} 方法：

@example
>>> from distutils.dist import DistributionMetadata
>>> metadata = DistributionMetadata()
>>> metadata.read_pkg_file(open('distribute-0.6.8-py2.7.egg-info'))
>>> metadata.name
'distribute'
>>> metadata.version
'0.6.8'
>>> metadata.description
'Easily download, build, install, upgrade, and uninstall Python packages'
@end example

注意类也可以用元数据文件载入值来实例化：

@example
>>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info'
>>> DistributionMetadata(pkg_info_path).name
'distribute'
@end example

@c % \section{Multiple extension modules}

@c % \label{multiple-ext}

@c % \section{Putting it all together}

@node 扩展 Distutils,命令参考,Distutils 示例,分发 Python 模块（遗留版本）
@anchor{distutils/extending doc}@anchor{45f5}@anchor{distutils/extending docutils}@anchor{45f6}@anchor{distutils/extending extending-distutils}@anchor{14f9}@anchor{distutils/extending id1}@anchor{45f7}
@section 扩展 Distutils


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

Distutils 可以通过各种方式扩展。 大多数扩展都采用新命令或现有命令的替换形式。 例如，可以编写新命令以支持新的特定于平台的包格式，但是可以修改现有命令的替换，以修改命令在包上的操作细节。

distutils 的大多数扩展都在想要修改现有命令的 @code{setup.py} 脚本中编写；其中许多只是简单地在 @code{.py} 文件以外添加了一些应当被拷贝到包中的文件后缀以便使用。

大多部 distutils 命令的实现都是 @ref{45f8,,distutils.cmd.Command} 类的子类。 新增命令可直接继承自 @code{Command}，而替换命令往往间接派生自 @code{Command}， 直接子类化它们所替换的命令。 所有命令都要求自 @code{Command} 派生。

@c % \section{Extending existing commands}

@c % \label{extend-existing}

@c % \section{Writing new commands}

@c % \label{new-commands}

@c % \XXX{Would an uninstall command be a good example here?}

@menu
* 集成新的命令:: 
* 添加新的发布类型:: 

@end menu

@node 集成新的命令,添加新的发布类型,,扩展 Distutils
@anchor{distutils/extending integrating-new-commands}@anchor{45f9}
@subsection 集成新的命令


有多种方法可将新的命令实现集成到 distutils 中。 最困难的一种是鼓动在 distutils 自身内部包含新特性，并等待（以及要求）某个 Python 版本提供该支持。 出于多种原因，这确实是相当难的。

对于大多数需求来说最为常见并且可能最为合理的一种则是通过你自己的 @code{setup.py} 脚本来包含新的实现，然后让 @ref{3dc9,,distutils.core.setup()} 函数使用它们:

@example
from distutils.command.build_py import build_py as _build_py
from distutils.core import setup

class build_py(_build_py):
    """Specialized Python source builder."""

    # implement whatever needs to be different...

setup(cmdclass=@{'build_py': build_py@},
      ...)
@end example

如果新的实现必须通过特定的包来使用则此方式最为适宜，因为每个对这个包感兴趣的人都将会需要有新的命令实现。

从 Python 2.4 开始，还有第三个选项可用，其目标是允许添加支持现有 @code{setup.py} 脚本的新命令，而不需要修改 Python 安装包。 这预计可允许第三方扩展提供对附加打包系统的支持，而相应命令又可用于任何 distutils 命令可被使用的地方。 新的配置选项 @code{command_packages} (命令行选项为 @code{--command-packages}) 可用来指定附加包，以在其中查找实现新增命令的模块。 像所有 distutils 选项一样，这可以通过命令行或配置文件来指定。 此选项只能在配置文件的 @code{[global]} 小节之中或在命令行的任何命令之前设置。 如果是设置在配置文件中，则它可被命令行设置重载；如果在命令行中将其设为空字符串则将会使用默认值。 此选项绝不应当在随特定包提供的配置文件中设置。

这个新选项可被用来添加任意数量的包到查找命令实现的包列表；多个包名应当以逗号分隔。 当未指明时，查找将只在 @ref{3d,,distutils.command} 包中进行。 但是当 @code{setup.py} 附带 @code{--command-packages distcmds,buildcmds} 选项运行时，@ref{3d,,distutils.command}, @code{distcmds} 和 @code{buildcmds} 包将按此顺序被查找。 新的命令应当在与命名同名的模块中由同名的类来实现。 给定上述示例命令行选项，则命令 @code{bdist_openpkg} 可由类 @code{distcmds.bdist_openpkg.bdist_openpkg} 或 @code{buildcmds.bdist_openpkg.bdist_openpkg} 来实现。

@node 添加新的发布类型,,集成新的命令,扩展 Distutils
@anchor{distutils/extending adding-new-distribution-types}@anchor{45fa}
@subsection 添加新的发布类型


创建发布（在 @code{dist/} 目录中的文件）的命令需要将 @code{(command, filename)} 二元组添加到 @code{self.distribution.dist_files} 以便 @code{upload} 可以将其上传到 PyPI。 二元组中的 @emph{filename} 不包含路径信息而只有文件名本身。 在 dry-run 模式下，二元组仍然应当被添加以表示必须创建的内容。

@node 命令参考,API参考引用,扩展 Distutils,分发 Python 模块（遗留版本）
@anchor{distutils/commandref doc}@anchor{45fb}@anchor{distutils/commandref command-reference}@anchor{45fc}@anchor{distutils/commandref reference}@anchor{45fd}
@section 命令参考


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

@c % \section{Building modules: the \protect\command{build} command family}

@c % \label{build-cmds}

@c % \subsubsection{\protect\command{build}}

@c % \label{build-cmd}

@c % \subsubsection{\protect\command{build\_py}}

@c % \label{build-py-cmd}

@c % \subsubsection{\protect\command{build\_ext}}

@c % \label{build-ext-cmd}

@c % \subsubsection{\protect\command{build\_clib}}

@c % \label{build-clib-cmd}

@menu
* 安装模块; install 命令族: 安装模块 install 命令族. 
* 创建源码发行包; sdist 命令: 创建源码发行包 sdist 命令. 

@end menu

@node 安装模块 install 命令族,创建源码发行包 sdist 命令,,命令参考
@anchor{distutils/commandref install-cmd}@anchor{45fe}@anchor{distutils/commandref installing-modules-the-install-command-family}@anchor{45ff}
@subsection 安装模块: @code{install} 命令族


install 命令会确保 build 命令已经运行，然后运行子命令 @code{install_lib}, @code{install_data} 和 @code{install_scripts}。

@c % \subsubsection{\protect\command{install\_lib}}

@c % \label{install-lib-cmd}

@menu
* install_data:: 
* install_scripts:: 

@end menu

@node install_data,install_scripts,,安装模块 install 命令族
@anchor{distutils/commandref install-data}@anchor{4600}@anchor{distutils/commandref install-data-cmd}@anchor{4601}
@subsubsection @code{install_data}


此命令会安装随发行包一同提供的所有数据文件。

@node install_scripts,,install_data,安装模块 install 命令族
@anchor{distutils/commandref install-scripts}@anchor{4602}@anchor{distutils/commandref install-scripts-cmd}@anchor{4603}
@subsubsection @code{install_scripts}


此命令会安装发行包中的所有（Python）脚本。

@c % \subsection{Cleaning up: the \protect\command{clean} command}

@c % \label{clean-cmd}

@node 创建源码发行包 sdist 命令,,安装模块 install 命令族,命令参考
@anchor{distutils/commandref creating-a-source-distribution-the-sdist-command}@anchor{4604}@anchor{distutils/commandref sdist-cmd}@anchor{45d7}
@subsection 创建源码发行包: @code{sdist} 命令


@c XXX fragment moved down from above: needs context!

列出的模板命令有:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

命令

@tab

描述

@item

@code{include pat1 pat2 ...}

@tab

包括与列出的模式匹配的所有文件

@item

@code{exclude pat1 pat2 ...}

@tab

排除与列出的模式匹配的所有文件

@item

@code{recursive-include dir pat1 pat2
...}

@tab

包括 @emph{dir} 下与列出的模式匹配的所有文件

@item

@code{recursive-exclude dir pat1 pat2
...}

@tab

排除 @emph{dir} 下与列出的模式匹配的所有文件

@item

@code{global-include pat1 pat2 ...}

@tab

包括与源树匹配的所有文件---和任何列出的模式

@item

@code{global-exclude pat1 pat2 ...}

@tab

排除与源树匹配的所有文件---和任何列出的模式

@item

@code{prune dir}

@tab

排除 @emph{dir} 下的所有文件

@item

@code{graft dir}

@tab

包括 @emph{dir} 下的所有文件

@end multitable


此处的模式是 Unix 风格的 "glob" 模式: @code{*} 匹配任意的常规文件名字符序列，@code{?} 匹配任意单个常规文件名字符，而 @code{[range]} 匹配 @emph{range} 范围内的任意字符 (例如 @code{a-z}, @code{a-zA-Z}, @code{a-f0-9_.})。 “常规文件名字符”的定义取决于具体平台：在 Unix 上是指正斜杠以外的任何字符；在 Windows 则是指反斜杠或冒号以外的任何字符。

@c XXX Windows support not there yet

@c % \section{Creating a built distribution: the

@c % \protect\command{bdist} command family}

@c % \label{bdist-cmds}

@c % \subsection{\protect\command{bdist}}

@c % \subsection{\protect\command{bdist\_dumb}}

@c % \subsection{\protect\command{bdist\_rpm}}

@c % \subsection{\protect\command{bdist\_wininst}}

@node API参考引用,,命令参考,分发 Python 模块（遗留版本）
@anchor{distutils/apiref doc}@anchor{4605}@anchor{distutils/apiref api-reference}@anchor{4606}@anchor{distutils/apiref id1}@anchor{4607}
@section API参考引用



@subsubheading 参见



@table @asis

@item New and changed setup.py arguments in setuptools@footnote{https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords}

The @code{setuptools} project adds new capabilities to the @code{setup} function
and other APIs, makes the API consistent across different Python versions,
and is hence recommended over using @code{distutils} directly.
@end table


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

@menu
* distutils.core: distutils core --- 分发包功能的核心. 分发包功能的核心
* distutils.ccompiler: distutils ccompiler --- CCompiler基类. CCompiler基类
* distutils.unixccompiler: distutils unixccompiler --- Unix C Compiler. Unix C Compiler
* distutils.msvccompiler: distutils msvccompiler --- Microsoft Compiler. Microsoft Compiler
* distutils.bcppcompiler: distutils bcppcompiler --- Borland Compiler. Borland Compiler
* distutils.cygwincompiler: distutils cygwincompiler --- Cygwin Compiler. Cygwin Compiler
* distutils.archive_util: distutils archive_util --- Archiving utilities. Archiving utilities
* distutils.dep_util: distutils dep_util --- Dependency checking. Dependency checking
* distutils.dir_util: distutils dir_util --- Directory tree operations. Directory tree operations
* distutils.file_util: distutils file_util --- Single file operations. Single file operations
* distutils.util: distutils util --- Miscellaneous other utility functions. Miscellaneous other utility functions
* distutils.dist: distutils dist --- The Distribution class. The Distribution class
* distutils.extension: distutils extension --- The Extension class. The Extension class
* distutils.debug: distutils debug --- Distutils debug mode. Distutils debug mode
* distutils.errors: distutils errors --- Distutils exceptions. Distutils exceptions
* distutils.fancy_getopt: distutils fancy_getopt --- Wrapper around the standard getopt module. Wrapper around the standard getopt module
* distutils.filelist: distutils filelist --- The FileList class. The FileList class
* distutils.log: distutils log --- Simple PEP 282-style logging. Simple PEP 282-style logging
* distutils.spawn: distutils spawn --- Spawn a sub-process. Spawn a sub-process
* distutils.sysconfig: distutils sysconfig --- System configuration information. System configuration information
* distutils.text_file: distutils text_file --- The TextFile class. The TextFile class
* distutils.version: distutils version --- Version number classes. Version number classes
* distutils.cmd: distutils cmd --- Abstract base class for Distutils commands. Abstract base class for Distutils commands
* Creating a new Distutils command:: 
* distutils.command: distutils command --- Individual Distutils commands. Individual Distutils commands
* distutils.command.bdist: distutils command bdist --- Build a binary installer. Build a binary installer
* distutils.command.bdist_packager: distutils command bdist_packager --- Abstract base class for packagers. Abstract base class for packagers
* distutils.command.bdist_dumb: distutils command bdist_dumb --- Build a "dumb" installer. Build a "dumb" installer
* distutils.command.bdist_msi: distutils command bdist_msi --- Build a Microsoft Installer binary package. Build a Microsoft Installer binary package
* distutils.command.bdist_rpm: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: distutils command bdist_wininst --- Build a Windows installer. Build a Windows installer
* distutils.command.sdist: distutils command sdist --- Build a source distribution. Build a source distribution
* distutils.command.build: distutils command build --- Build all files of a package. Build all files of a package
* distutils.command.build_clib: distutils command build_clib --- Build any C libraries in a package. Build any C libraries in a package
* distutils.command.build_ext: distutils command build_ext --- Build any extensions in a package. Build any extensions in a package
* distutils.command.build_py: distutils command build_py --- Build the py/ pyc files of a package. Build the .py/.pyc files of a package
* distutils.command.build_scripts: distutils command build_scripts --- Build the scripts of a package. Build the scripts of a package
* distutils.command.clean: distutils command clean --- Clean a package build area. Clean a package build area
* distutils.command.config: distutils command config --- Perform package configuration. Perform package configuration
* distutils.command.install: distutils command install --- Install a package. Install a package
* distutils.command.install_data: distutils command install_data --- Install data files from a package. Install data files from a package
* distutils.command.install_headers: distutils command install_headers --- Install C/C++ header files from a package. Install C/C++ header files from a package
* distutils.command.install_lib: distutils command install_lib --- Install library files from a package. Install library files from a package
* distutils.command.install_scripts: distutils command install_scripts --- Install script files from a package. Install script files from a package
* distutils.command.register: distutils command register --- Register a module with the Python Package Index. Register a module with the Python Package Index
* distutils.command.check: distutils command check --- Check the meta-data of a package. Check the meta-data of a package

@end menu

@node distutils core --- 分发包功能的核心,distutils ccompiler --- CCompiler基类,,API参考引用
@anchor{distutils/apiref distutils-core-core-distutils-functionality}@anchor{4608}@anchor{distutils/apiref module-distutils core}@anchor{53}
@subsection @code{distutils.core} --- 分发包功能的核心


@geindex distutils.core (模块)

The @ref{53,,distutils.core} 是为了使用 Distutils 工具唯一要安装的模块。它提供函数 @ref{3dc9,,setup()} （该函数被 setup 脚本调用）。间接提供了类  @code{distutils.dist.Distribution} 和 @ref{45f8,,distutils.cmd.Command}.

@geindex setup() (在 distutils.core 模块中)
@anchor{distutils/apiref distutils core setup}@anchor{3dc9}
@deffn {函数} distutils.core.setup (arguments)

The basic do-everything function that does most everything you could ever ask
for from a Distutils method.

The setup function takes a large number of arguments. These are laid out in the
following table.


@multitable {xxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

参数名称

@tab

值

@tab

类型

@item

@emph{name}

@tab

包的名字

@tab

字符串

@item

@emph{version}

@tab

包的版本号；参见 @ref{65,,distutils.version}

@tab

字符串

@item

@emph{description}

@tab

单行的包的描述

@tab

字符串

@item

@emph{long_description}

@tab

更长的包描述

@tab

字符串

@item

@emph{author}

@tab

包的作者

@tab

字符串

@item

@emph{author_email}

@tab

包的作者的电子邮件

@tab

字符串

@item

@emph{maintainer}

@tab

The name of the current
maintainer, if different from
the author. Note that if
the maintainer is provided,
distutils will use it as the
author in @code{PKG-INFO}

@tab

字符串

@item

@emph{maintainer_email}

@tab

当前维护者的电子邮件地址，如果不同与作者

@tab

字符串

@item

@emph{url}

@tab

包的URL（主页）

@tab

字符串

@item

@emph{download_url}

@tab

包的下载地址

@tab

字符串

@item

@emph{packages}

@tab

A list of Python packages that
distutils will manipulate

@tab

字符串列表

@item

@emph{py_modules}

@tab

distutils 会操作的 Python 模块列表

@tab

字符串列表

@item

@emph{scripts}

@tab

要构建和安装的独立脚本文件的列表

@tab

字符串列表

@item

@emph{ext_modules}

@tab

要构建的 Python 扩展的列表

@tab

类 @ref{45be,,distutils.core.Extension} 的实例的列表

@item

@emph{classifiers}

@tab

包的类别列表

@tab

a list of strings; valid classifiers are listed on PyPI@footnote{https://pypi.org/classifiers}.

@item

@emph{distclass}

@tab

要使用的类 @ref{4609,,Distribution} 类

@tab

@ref{4609,,distutils.core.Distribution} 的子类

@item

@emph{script_name}

@tab

setup.py 脚本名称 —— 默认为 @code{sys.argv[0]}

@tab

字符串

@item

@emph{script_args}

@tab

提供给安装脚本的参数

@tab

字符串列表

@item

@emph{options}

@tab

安装脚本的默认选项

@tab

字典

@item

@emph{license}

@tab

包的许可证

@tab

字符串

@item

@emph{keywords}

@tab

描述性的元数据，参见 
@geindex Python 提高建议; PEP 314
PEP 314@footnote{https://www.python.org/dev/peps/pep-0314}

@tab

字符串列表或逗号分隔的字符串

@item

@emph{platforms}

@tab

@tab

字符串列表或逗号分隔的字符串

@item

@emph{cmdclass}

@tab

一个从命令名称到 @ref{460a,,Command} 子类的映射

@tab

字典

@item

@emph{data_files}

@tab

要安装的数据文件列表

@tab

列表

@item

@emph{package_dir}

@tab

一个从包到目录名称的映射

@tab

字典

@end multitable

@end deffn

@geindex run_setup() (在 distutils.core 模块中)
@anchor{distutils/apiref distutils core run_setup}@anchor{460b}
@deffn {函数} distutils.core.run_setup (script_name[, script_args=None, stop_after='run'])

Run a setup script in a somewhat controlled environment, and return  the
@code{distutils.dist.Distribution} instance that drives things.   This is
useful if you need to find out the distribution meta-data  (passed as keyword
args from @emph{script} to @ref{3dc9,,setup()}), or  the contents of the config files or
command-line.

@emph{script_name} is a file that will be read and run with @ref{d14,,exec()}.  @code{sys.argv[0]}
will be replaced with @emph{script} for the duration of the call.  @emph{script_args} is a
list of strings; if supplied, @code{sys.argv[1:]} will be replaced by @emph{script_args}
for the duration  of the call.

@emph{stop_after} tells @ref{3dc9,,setup()} when to stop processing; possible  values:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

值

@tab

描述

@item

@emph{init}

@tab

Stop after the @ref{4609,,Distribution}
instance has been created  and populated
with the keyword arguments to @ref{3dc9,,setup()}

@item

@emph{config}

@tab

Stop after config files have been parsed
(and their data stored in the
@ref{4609,,Distribution} instance)

@item

@emph{commandline}

@tab

Stop after the command-line
(@code{sys.argv[1:]} or  @emph{script_args}) have
been parsed (and the data stored in the
@ref{4609,,Distribution} instance.)

@item

@emph{run}

@tab

Stop after all commands have been run (the
same as  if @ref{3dc9,,setup()} had been called
in the usual way). This is the default
value.

@end multitable

@end deffn

In addition, the @ref{53,,distutils.core} module exposed a number of  classes that
live elsewhere.


@itemize *

@item 
@code{Extension} from @ref{5a,,distutils.extension}

@item 
@ref{45f8,,Command} from @ref{3c,,distutils.cmd}

@item 
@code{Distribution} from @ref{58,,distutils.dist}
@end itemize

A short description of each of these follows, but see the relevant module for
the full reference.

@geindex Extension (distutils.core 中的类)
@anchor{distutils/apiref distutils core Extension}@anchor{45be}
@deffn {类} distutils.core.Extension

The Extension class describes a single C or C++ extension module in a setup
script. It accepts the following keyword arguments in its constructor:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

参数名称

@tab

值

@tab

类型

@item

@emph{name}

@tab

the full name of the
extension, including any
packages --- ie. @emph{not} a
filename or pathname, but
Python dotted name

@tab

字符串

@item

@emph{sources}

@tab

list of source filenames,
relative to the distribution
root (where the setup script
lives), in Unix form
(slash-separated) for
portability.
Source files may be C, C++,
SWIG (.i), platform-specific
resource files, or whatever
else is recognized by the
@code{build_ext} command
as source for a Python
extension.

@tab

字符串列表

@item

@emph{include_dirs}

@tab

list of directories to search
for C/C++ header files (in
Unix form for portability)

@tab

字符串列表

@item

@emph{define_macros}

@tab

list of macros to define; each
macro is defined using a
2-tuple @code{(name, value)},
where @emph{value} is
either the string to define it
to or @code{None} to define it
without a particular value
(equivalent of @code{#define FOO}
in source or @code{-DFOO}
on Unix C compiler command
line)

@tab

元组列表

@item

@emph{undef_macros}

@tab

要明确取消定义的宏列表

@tab

字符串列表

@item

@emph{library_dirs}

@tab

list of directories to search
for C/C++ libraries at link
time

@tab

字符串列表

@item

@emph{libraries}

@tab

要链接的库名列表（不是文件名或路径）

@tab

字符串列表

@item

@emph{runtime_library_dirs}

@tab

list of directories to search
for C/C++ libraries at run
time (for shared extensions,
this is when the extension is
loaded)

@tab

字符串列表

@item

@emph{extra_objects}

@tab

list of extra files to link
with (eg. object files not
implied by 'sources', static
library that must be
explicitly specified, binary
resource files, etc.)

@tab

字符串列表

@item

@emph{extra_compile_args}

@tab

any extra platform- and
compiler-specific information
to use when compiling the
source files in 'sources'. For
platforms and compilers where
a command line makes sense,
this is typically a list of
command-line arguments, but
for other platforms it could
be anything.

@tab

字符串列表

@item

@emph{extra_link_args}

@tab

any extra platform- and
compiler-specific information
to use when linking object
files together to create the
extension (or to create a new
static Python interpreter).
Similar interpretation as for
'extra_compile_args'.

@tab

字符串列表

@item

@emph{export_symbols}

@tab

list of symbols to be exported
from a shared extension. Not
used on all platforms, and not
generally necessary for Python
extensions, which typically
export exactly one symbol:
@code{init} + extension_name.

@tab

字符串列表

@item

@emph{depends}

@tab

扩展名依赖的文件列表

@tab

字符串列表

@item

@emph{language}

@tab

extension language (i.e.
@code{'c'}, @code{'c++'},
@code{'objc'}). Will be detected
from the source extensions if
not provided.

@tab

字符串

@item

@emph{optional}

@tab

指定扩展中的构建失败不应中止构建过程，而只是跳过扩展。

@tab

布尔

@end multitable



在 3.8 版更改: On Unix, C extensions are no longer linked to libpython except on
Android and Cygwin.

@end deffn

@geindex Distribution (distutils.core 中的类)
@anchor{distutils/apiref distutils core Distribution}@anchor{4609}
@deffn {类} distutils.core.Distribution

A @ref{4609,,Distribution} describes how to build, install and package up a Python
software package.

See the @ref{3dc9,,setup()} function for a list of keyword arguments accepted  by the
Distribution constructor. @ref{3dc9,,setup()} creates a Distribution instance.


在 3.7 版更改: @ref{4609,,Distribution} now warns if @code{classifiers},
@code{keywords} and @code{platforms} fields are not specified as a list or
a string.

@end deffn

@geindex Command (distutils.core 中的类)
@anchor{distutils/apiref distutils core Command}@anchor{460a}
@deffn {类} distutils.core.Command

A @ref{460a,,Command} class (or rather, an instance of one of its subclasses)
implement a single distutils command.
@end deffn

@node distutils ccompiler --- CCompiler基类,distutils unixccompiler --- Unix C Compiler,distutils core --- 分发包功能的核心,API参考引用
@anchor{distutils/apiref distutils-ccompiler-ccompiler-base-class}@anchor{460c}@anchor{distutils/apiref module-distutils ccompiler}@anchor{3b}
@subsection @code{distutils.ccompiler} --- CCompiler基类


@geindex distutils.ccompiler (模块)

This module provides the abstract base class for the @ref{460d,,CCompiler}
classes.  A @ref{460d,,CCompiler} instance can be used for all the compile  and
link steps needed to build a single project. Methods are provided to  set
options for the compiler --- macro definitions, include directories,  link path,
libraries and the like.

This module provides the following functions.

@geindex gen_lib_options() (在 distutils.ccompiler 模块中)
@anchor{distutils/apiref distutils ccompiler gen_lib_options}@anchor{460e}
@deffn {函数} distutils.ccompiler.gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries)

Generate linker options for searching library directories and linking with
specific libraries.  @emph{libraries} and @emph{library_dirs} are, respectively, lists of
library names (not filenames!) and search directories.  Returns a list of
command-line options suitable for use with some compiler (depending on the two
format strings passed in).
@end deffn

@geindex gen_preprocess_options() (在 distutils.ccompiler 模块中)
@anchor{distutils/apiref distutils ccompiler gen_preprocess_options}@anchor{460f}
@deffn {函数} distutils.ccompiler.gen_preprocess_options (macros, include_dirs)

Generate C pre-processor options (@code{-D}, @code{-U}, @code{-I}) as
used by at least two types of compilers: the typical Unix compiler and Visual
C++. @emph{macros} is the usual thing, a list of 1- or 2-tuples, where @code{(name,)}
means undefine (@code{-U}) macro @emph{name}, and @code{(name, value)} means define
(@code{-D}) macro @emph{name} to @emph{value}.  @emph{include_dirs} is just a list of
directory names to be added to the header file search path (@code{-I}).
Returns a list of command-line options suitable for either Unix compilers or
Visual C++.
@end deffn

@geindex get_default_compiler() (在 distutils.ccompiler 模块中)
@anchor{distutils/apiref distutils ccompiler get_default_compiler}@anchor{4610}
@deffn {函数} distutils.ccompiler.get_default_compiler (osname, platform)

Determine the default compiler to use for the given platform.

@emph{osname} should be one of the standard Python OS names (i.e. the ones returned
by @code{os.name}) and @emph{platform} the common value returned by @code{sys.platform} for
the platform in question.

The default values are @code{os.name} and @code{sys.platform} in case the parameters
are not given.
@end deffn

@geindex new_compiler() (在 distutils.ccompiler 模块中)
@anchor{distutils/apiref distutils ccompiler new_compiler}@anchor{4611}
@deffn {函数} distutils.ccompiler.new_compiler (plat=None, compiler=None, verbose=0, dry_run=0, force=0)

Factory function to generate an instance of some CCompiler subclass for the
supplied platform/compiler combination. @emph{plat} defaults to @code{os.name} (eg.
@code{'posix'}, @code{'nt'}), and @emph{compiler}  defaults to the default compiler for
that platform. Currently only @code{'posix'} and @code{'nt'} are supported, and the
default compilers are "traditional Unix interface" (@code{UnixCCompiler}
class) and Visual C++ (@code{MSVCCompiler} class).  Note that it's perfectly
possible to ask for a Unix compiler object under Windows, and a Microsoft
compiler object under Unix---if you supply a value for @emph{compiler}, @emph{plat} is
ignored.

@c % Is the posix/nt only thing still true? macOS seems to work, and

@c % returns a UnixCCompiler instance. How to document this... hmm.
@end deffn

@geindex show_compilers() (在 distutils.ccompiler 模块中)
@anchor{distutils/apiref distutils ccompiler show_compilers}@anchor{4612}
@deffn {函数} distutils.ccompiler.show_compilers ()

Print list of available compilers (used by the @code{--help-compiler} options
to @code{build}, @code{build_ext}, @code{build_clib}).
@end deffn

@geindex CCompiler (distutils.ccompiler 中的类)
@anchor{distutils/apiref distutils ccompiler CCompiler}@anchor{460d}
@deffn {类} distutils.ccompiler.CCompiler ([verbose=0, dry_run=0, force=0])

The abstract base class @ref{460d,,CCompiler} defines the interface that  must be
implemented by real compiler classes.  The class also has  some utility methods
used by several compiler classes.

The basic idea behind a compiler abstraction class is that each instance can be
used for all the compile/link steps in building a single project.  Thus,
attributes common to all of those compile and link steps --- include
directories, macros to define, libraries to link against, etc. --- are
attributes of the compiler instance.  To allow for variability in how individual
files are treated, most of those attributes may be varied on a per-compilation
or per-link basis.

The constructor for each subclass creates an instance of the Compiler object.
Flags are @emph{verbose} (show verbose output), @emph{dry_run} (don't actually execute the
steps) and @emph{force} (rebuild everything, regardless of dependencies). All of
these flags default to @code{0} (off). Note that you probably don't want to
instantiate @ref{460d,,CCompiler} or one of its subclasses directly - use the
@code{distutils.CCompiler.new_compiler()} factory function instead.

The following methods allow you to manually alter compiler options for  the
instance of the Compiler class.

@geindex add_include_dir() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler add_include_dir}@anchor{4613}
@deffn {方法} add_include_dir (dir)

Add @emph{dir} to the list of directories that will be searched for header files.
The compiler is instructed to search directories in the order in which they are
supplied by successive calls to @ref{4613,,add_include_dir()}.
@end deffn

@geindex set_include_dirs() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_include_dirs}@anchor{4614}
@deffn {方法} set_include_dirs (dirs)

Set the list of directories that will be searched to @emph{dirs} (a list of strings).
Overrides any preceding calls to @ref{4613,,add_include_dir()}; subsequent calls to
@ref{4613,,add_include_dir()} add to the list passed to @ref{4614,,set_include_dirs()}.
This does not affect any list of standard include directories that the compiler
may search by default.
@end deffn

@geindex add_library() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler add_library}@anchor{4615}
@deffn {方法} add_library (libname)

Add @emph{libname} to the list of libraries that will be included in all links driven
by this compiler object.  Note that @emph{libname} should *not* be the name of a
file containing a library, but the name of the library itself: the actual
filename will be inferred by the linker, the compiler, or the compiler class
(depending on the platform).

The linker will be instructed to link against libraries in the order they were
supplied to @ref{4615,,add_library()} and/or @ref{4616,,set_libraries()}.  It is perfectly
valid to duplicate library names; the linker will be instructed to link against
libraries as many times as they are mentioned.
@end deffn

@geindex set_libraries() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_libraries}@anchor{4616}
@deffn {方法} set_libraries (libnames)

Set the list of libraries to be included in all links driven by this compiler
object to @emph{libnames} (a list of strings).  This does not affect any standard
system libraries that the linker may include by default.
@end deffn

@geindex add_library_dir() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler add_library_dir}@anchor{4617}
@deffn {方法} add_library_dir (dir)

Add @emph{dir} to the list of directories that will be searched for libraries
specified to @ref{4615,,add_library()} and @ref{4616,,set_libraries()}.  The linker will be
instructed to search for libraries in the order they are supplied to
@ref{4617,,add_library_dir()} and/or @ref{4618,,set_library_dirs()}.
@end deffn

@geindex set_library_dirs() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_library_dirs}@anchor{4618}
@deffn {方法} set_library_dirs (dirs)

Set the list of library search directories to @emph{dirs} (a list of strings).  This
does not affect any standard library search path that the linker may search by
default.
@end deffn

@geindex add_runtime_library_dir() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler add_runtime_library_dir}@anchor{4619}
@deffn {方法} add_runtime_library_dir (dir)

Add @emph{dir} to the list of directories that will be searched for shared libraries
at runtime.
@end deffn

@geindex set_runtime_library_dirs() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_runtime_library_dirs}@anchor{461a}
@deffn {方法} set_runtime_library_dirs (dirs)

Set the list of directories to search for shared libraries at runtime to @emph{dirs}
(a list of strings).  This does not affect any standard search path that the
runtime linker may search by default.
@end deffn

@geindex define_macro() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler define_macro}@anchor{461b}
@deffn {方法} define_macro (name[, value=None])

Define a preprocessor macro for all compilations driven by this compiler object.
The optional parameter @emph{value} should be a string; if it is not supplied, then
the macro will be defined without an explicit value and the exact outcome
depends on the compiler used.

@c XXX true? does ANSI say anything about this?
@end deffn

@geindex undefine_macro() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler undefine_macro}@anchor{461c}
@deffn {方法} undefine_macro (name)

Undefine a preprocessor macro for all compilations driven by this compiler
object.  If the same macro is defined by @ref{461b,,define_macro()} and
undefined by @ref{461c,,undefine_macro()} the last call takes precedence
(including multiple redefinitions or undefinitions).  If the macro is
redefined/undefined on a per-compilation basis (ie. in the call to
@ref{2ee,,compile()}), then that takes precedence.
@end deffn

@geindex add_link_object() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler add_link_object}@anchor{461d}
@deffn {方法} add_link_object (object)

Add @emph{object} to the list of object files (or analogues, such as explicitly named
library files or the output of "resource compilers") to be included in every
link driven by this compiler object.
@end deffn

@geindex set_link_objects() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_link_objects}@anchor{461e}
@deffn {方法} set_link_objects (objects)

Set the list of object files (or analogues) to be included in every link to
@emph{objects}.  This does not affect any standard object files that the linker may
include by default (such as system libraries).
@end deffn

The following methods implement methods for autodetection of compiler  options,
providing some functionality similar to GNU @code{autoconf}.

@geindex detect_language() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler detect_language}@anchor{461f}
@deffn {方法} detect_language (sources)

Detect the language of a given file, or list of files. Uses the  instance
attributes @code{language_map} (a dictionary), and  @code{language_order} (a
list) to do the job.
@end deffn

@geindex find_library_file() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler find_library_file}@anchor{4620}
@deffn {方法} find_library_file (dirs, lib[, debug=0])

Search the specified list of directories for a static or shared library file
@emph{lib} and return the full path to that file.  If @emph{debug} is true, look for a
debugging version (if that makes sense on the current platform).  Return
@code{None} if @emph{lib} wasn't found in any of the specified directories.
@end deffn

@geindex has_function() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler has_function}@anchor{4621}
@deffn {方法} has_function (funcname[, includes=None, include_dirs=None, libraries=None, library_dirs=None])

Return a boolean indicating whether @emph{funcname} is supported on the current
platform.  The optional arguments can be used to augment the compilation
environment by providing additional include files and paths and libraries and
paths.
@end deffn

@geindex library_dir_option() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler library_dir_option}@anchor{4622}
@deffn {方法} library_dir_option (dir)

Return the compiler option to add @emph{dir} to the list of directories searched for
libraries.
@end deffn

@geindex library_option() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler library_option}@anchor{4623}
@deffn {方法} library_option (lib)

Return the compiler option to add @emph{lib} to the list of libraries linked into the
shared library or executable.
@end deffn

@geindex runtime_library_dir_option() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler runtime_library_dir_option}@anchor{4624}
@deffn {方法} runtime_library_dir_option (dir)

Return the compiler option to add @emph{dir} to the list of directories searched for
runtime libraries.
@end deffn

@geindex set_executables() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler set_executables}@anchor{4625}
@deffn {方法} set_executables (**args)

Define the executables (and options for them) that will be run to perform the
various stages of compilation.  The exact set of executables that may be
specified here depends on the compiler class (via the 'executables' class
attribute), but most will have:


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

属性

@tab

描述

@item

@emph{compiler}

@tab

C/C++ 编译器

@item

@emph{linker_so}

@tab

用于创建共享对象和库的链接器

@item

@emph{linker_exe}

@tab

用于创建二进制可执行文件的链接器

@item

@emph{archiver}

@tab

静态库创建者

@end multitable


On platforms with a command-line (Unix, DOS/Windows), each of these is a string
that will be split into executable name and (optional) list of arguments.
(Splitting the string is done similarly to how Unix shells operate: words are
delimited by spaces, but quotes and backslashes can override this.  See
@ref{4626,,distutils.util.split_quoted()}.)
@end deffn

The following methods invoke stages in the build process.

@geindex compile() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler compile}@anchor{4627}
@deffn {方法} compile (sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None])

Compile one or more source files. Generates object files (e.g.  transforms a
@code{.c} file to a @code{.o} file.)

@emph{sources} must be a list of filenames, most likely C/C++ files, but in reality
anything that can be handled by a particular compiler and compiler class (eg.
@code{MSVCCompiler} can handle resource files in @emph{sources}).  Return a list of
object filenames, one per source filename in @emph{sources}.  Depending on the
implementation, not all source files will necessarily be compiled, but all
corresponding object filenames will be returned.

If @emph{output_dir} is given, object files will be put under it, while retaining
their original path component.  That is, @code{foo/bar.c} normally compiles to
@code{foo/bar.o} (for a Unix implementation); if @emph{output_dir} is @emph{build}, then
it would compile to @code{build/foo/bar.o}.

@emph{macros}, if given, must be a list of macro definitions.  A macro definition is
either a @code{(name, value)} 2-tuple or a @code{(name,)} 1-tuple. The former defines
a macro; if the value is @code{None}, the macro is defined without an explicit
value.  The 1-tuple case undefines a macro.  Later
definitions/redefinitions/undefinitions take precedence.

@emph{include_dirs}, if given, must be a list of strings, the directories to add to
the default include file search path for this compilation only.

@emph{debug} is a boolean; if true, the compiler will be instructed to output debug
symbols in (or alongside) the object file(s).

@emph{extra_preargs} and @emph{extra_postargs} are implementation-dependent. On platforms
that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most
likely lists of strings: extra command-line arguments to prepend/append to the
compiler command line.  On other platforms, consult the implementation class
documentation.  In any event, they are intended as an escape hatch for those
occasions when the abstract compiler framework doesn't cut the mustard.

@emph{depends}, if given, is a list of filenames that all targets depend on.  If a
source file is older than any file in depends, then the source file will be
recompiled.  This supports dependency tracking, but only at a coarse
granularity.

Raises @code{CompileError} on failure.
@end deffn

@geindex create_static_lib() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler create_static_lib}@anchor{4628}
@deffn {方法} create_static_lib (objects, output_libname[, output_dir=None, debug=0, target_lang=None])

Link a bunch of stuff together to create a static library file. The "bunch of
stuff" consists of the list of object files supplied as @emph{objects}, the extra
object files supplied to @ref{461d,,add_link_object()} and/or
@ref{461e,,set_link_objects()}, the libraries supplied to @ref{4615,,add_library()} and/or
@ref{4616,,set_libraries()}, and the libraries supplied as @emph{libraries} (if any).

@emph{output_libname} should be a library name, not a filename; the filename will be
inferred from the library name.  @emph{output_dir} is the directory where the library
file will be put.

@c XXX defaults to what?

@emph{debug} is a boolean; if true, debugging information will be included in the
library (note that on most platforms, it is the compile step where this matters:
the @emph{debug} flag is included here just for consistency).

@emph{target_lang} is the target language for which the given objects are being
compiled. This allows specific linkage time treatment of certain languages.

Raises @code{LibError} on failure.
@end deffn

@geindex link() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler link}@anchor{4629}
@deffn {方法} link (target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a bunch of stuff together to create an executable or shared library file.

The "bunch of stuff" consists of the list of object files supplied as @emph{objects}.
@emph{output_filename} should be a filename.  If @emph{output_dir} is supplied,
@emph{output_filename} is relative to it (i.e. @emph{output_filename} can provide
directory components if needed).

@emph{libraries} is a list of libraries to link against.  These are library names,
not filenames, since they're translated into filenames in a platform-specific
way (eg. @emph{foo} becomes @code{libfoo.a} on Unix and @code{foo.lib} on
DOS/Windows).  However, they can include a directory component, which means the
linker will look in that specific directory rather than searching all the normal
locations.

@emph{library_dirs}, if supplied, should be a list of directories to search for
libraries that were specified as bare library names (ie. no directory
component).  These are on top of the system default and those supplied to
@ref{4617,,add_library_dir()} and/or @ref{4618,,set_library_dirs()}.  @emph{runtime_library_dirs}
is a list of directories that will be embedded into the shared library and used
to search for other shared libraries that *it* depends on at run-time.  (This
may only be relevant on Unix.)

@emph{export_symbols} is a list of symbols that the shared library will export.
(This appears to be relevant only on Windows.)

@emph{debug} is as for @ref{2ee,,compile()} and @ref{4628,,create_static_lib()},  with the
slight distinction that it actually matters on most platforms (as opposed to
@ref{4628,,create_static_lib()}, which includes a @emph{debug} flag mostly for form's
sake).

@emph{extra_preargs} and @emph{extra_postargs} are as for @ref{2ee,,compile()}  (except of
course that they supply command-line arguments for the particular linker being
used).

@emph{target_lang} is the target language for which the given objects are being
compiled. This allows specific linkage time treatment of certain languages.

Raises @code{LinkError} on failure.
@end deffn

@geindex link_executable() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler link_executable}@anchor{462a}
@deffn {方法} link_executable (objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None])

Link an executable.  @emph{output_progname} is the name of the file executable, while
@emph{objects} are a list of object filenames to link in. Other arguments  are as for
the @ref{4629,,link()} method.
@end deffn

@geindex link_shared_lib() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler link_shared_lib}@anchor{462b}
@deffn {方法} link_shared_lib (objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a shared library. @emph{output_libname} is the name of the output  library,
while @emph{objects} is a list of object filenames to link in.  Other arguments are
as for the @ref{4629,,link()} method.
@end deffn

@geindex link_shared_object() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler link_shared_object}@anchor{462c}
@deffn {方法} link_shared_object (objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a shared object. @emph{output_filename} is the name of the shared object that
will be created, while @emph{objects} is a list of object filenames  to link in.
Other arguments are as for the @ref{4629,,link()} method.
@end deffn

@geindex preprocess() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler preprocess}@anchor{462d}
@deffn {方法} preprocess (source[, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None])

Preprocess a single C/C++ source file, named in @emph{source}. Output will be written
to file named @emph{output_file}, or @emph{stdout} if @emph{output_file} not supplied.
@emph{macros} is a list of macro definitions as for @ref{2ee,,compile()}, which will
augment the macros set with @ref{461b,,define_macro()} and @ref{461c,,undefine_macro()}.
@emph{include_dirs} is a list of directory names that will be added to the  default
list, in the same way as @ref{4613,,add_include_dir()}.

Raises @code{PreprocessError} on failure.
@end deffn

The following utility methods are defined by the @ref{460d,,CCompiler} class, for
use by the various concrete subclasses.

@geindex executable_filename() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler executable_filename}@anchor{462e}
@deffn {方法} executable_filename (basename[, strip_dir=0, output_dir='@w{'}])

Returns the filename of the executable for the given @emph{basename}.  Typically for
non-Windows platforms this is the same as the basename,  while Windows will get
a @code{.exe} added.
@end deffn

@geindex library_filename() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler library_filename}@anchor{462f}
@deffn {方法} library_filename (libname[, lib_type='static', strip_dir=0, output_dir='@w{'}])

Returns the filename for the given library name on the current platform. On Unix
a library with @emph{lib_type} of @code{'static'} will typically  be of the form
@code{liblibname.a}, while a @emph{lib_type} of @code{'dynamic'}  will be of the form
@code{liblibname.so}.
@end deffn

@geindex object_filenames() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler object_filenames}@anchor{4630}
@deffn {方法} object_filenames (source_filenames[, strip_dir=0, output_dir='@w{'}])

Returns the name of the object files for the given source files.
@emph{source_filenames} should be a list of filenames.
@end deffn

@geindex shared_object_filename() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler shared_object_filename}@anchor{4631}
@deffn {方法} shared_object_filename (basename[, strip_dir=0, output_dir='@w{'}])

Returns the name of a shared object file for the given file name @emph{basename}.
@end deffn

@geindex execute() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler execute}@anchor{4632}
@deffn {方法} execute (func, args[, msg=None, level=1])

Invokes @ref{4633,,distutils.util.execute()}. This method invokes a  Python function
@emph{func} with the given arguments @emph{args}, after  logging and taking into account
the @emph{dry_run} flag.
@end deffn

@geindex spawn() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler spawn}@anchor{4634}
@deffn {方法} spawn (cmd)

Invokes @code{distutils.util.spawn()}. This invokes an external  process to run
the given command.
@end deffn

@geindex mkpath() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler mkpath}@anchor{4635}
@deffn {方法} mkpath (name[, mode=511])

Invokes @ref{4636,,distutils.dir_util.mkpath()}. This creates a directory  and any
missing ancestor directories.
@end deffn

@geindex move_file() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler move_file}@anchor{4637}
@deffn {方法} move_file (src, dst)

Invokes @ref{4638,,distutils.file_util.move_file()}. Renames @emph{src} to  @emph{dst}.
@end deffn

@geindex announce() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler announce}@anchor{4639}
@deffn {方法} announce (msg[, level=1])

Write a message using @code{distutils.log.debug()}.
@end deffn

@geindex warn() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler warn}@anchor{463a}
@deffn {方法} warn (msg)

Write a warning message @emph{msg} to standard error.
@end deffn

@geindex debug_print() (distutils.ccompiler.CCompiler 方法)
@anchor{distutils/apiref distutils ccompiler CCompiler debug_print}@anchor{463b}
@deffn {方法} debug_print (msg)

If the @emph{debug} flag is set on this @ref{460d,,CCompiler} instance, print  @emph{msg} to
standard output, otherwise do nothing.
@end deffn
@end deffn

@c % \subsection{Compiler-specific modules}

@c %

@c % The following modules implement concrete subclasses of the abstract

@c % \class{CCompiler} class. They should not be instantiated directly, but should

@c % be created using \function{distutils.ccompiler.new_compiler()} factory

@c % function.

@node distutils unixccompiler --- Unix C Compiler,distutils msvccompiler --- Microsoft Compiler,distutils ccompiler --- CCompiler基类,API参考引用
@anchor{distutils/apiref distutils-unixccompiler-unix-c-compiler}@anchor{463c}@anchor{distutils/apiref module-distutils unixccompiler}@anchor{63}
@subsection @code{distutils.unixccompiler} --- Unix C Compiler


@geindex distutils.unixccompiler (模块)

This module provides the @code{UnixCCompiler} class, a subclass of
@code{CCompiler} that handles the typical Unix-style command-line  C compiler:


@itemize *

@item 
macros defined with @code{-Dname[=value]}

@item 
macros undefined with @code{-Uname}

@item 
include search directories specified with @code{-Idir}

@item 
libraries specified with @code{-llib}

@item 
library search directories specified with @code{-Ldir}

@item 
compile handled by @code{cc} (or similar) executable with @code{-c}
option: compiles @code{.c} to @code{.o}

@item 
link static library handled by @code{ar} command (possibly with
@code{ranlib})

@item 
link shared library handled by @code{cc} @code{-shared}
@end itemize

@node distutils msvccompiler --- Microsoft Compiler,distutils bcppcompiler --- Borland Compiler,distutils unixccompiler --- Unix C Compiler,API参考引用
@anchor{distutils/apiref distutils-msvccompiler-microsoft-compiler}@anchor{463d}@anchor{distutils/apiref module-distutils msvccompiler}@anchor{5f}
@subsection @code{distutils.msvccompiler} --- Microsoft Compiler


@geindex distutils.msvccompiler (模块)

@c XXX: This is *waaaaay* out of date!

This module provides @code{MSVCCompiler}, an implementation of the abstract
@code{CCompiler} class for Microsoft Visual Studio. Typically, extension
modules need to be compiled with the same compiler that was used to compile
Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python
2.4 and 2.5, the compiler is Visual Studio .NET 2003.

@code{MSVCCompiler} will normally choose the right compiler, linker etc. on
its own. To override this choice, the environment variables @emph{DISTUTILS_USE_SDK}
and @emph{MSSdk} must be both set. @emph{MSSdk} indicates that the current environment has
been setup by the SDK's @code{SetEnv.Cmd} script, or that the environment variables
had been registered when the SDK was installed; @emph{DISTUTILS_USE_SDK} indicates
that the distutils user has made an explicit choice to override the compiler
selection by @code{MSVCCompiler}.

@node distutils bcppcompiler --- Borland Compiler,distutils cygwincompiler --- Cygwin Compiler,distutils msvccompiler --- Microsoft Compiler,API参考引用
@anchor{distutils/apiref distutils-bcppcompiler-borland-compiler}@anchor{463e}@anchor{distutils/apiref module-distutils bcppcompiler}@anchor{3a}
@subsection @code{distutils.bcppcompiler} --- Borland Compiler


@geindex distutils.bcppcompiler (模块)

This module provides @code{BorlandCCompiler}, a subclass of the abstract
@code{CCompiler} class for the Borland C++ compiler.

@node distutils cygwincompiler --- Cygwin Compiler,distutils archive_util --- Archiving utilities,distutils bcppcompiler --- Borland Compiler,API参考引用
@anchor{distutils/apiref distutils-cygwincompiler-cygwin-compiler}@anchor{463f}@anchor{distutils/apiref module-distutils cygwinccompiler}@anchor{54}
@subsection @code{distutils.cygwincompiler} --- Cygwin Compiler


@geindex distutils.cygwinccompiler (模块)

This module provides the @code{CygwinCCompiler} class, a subclass of
@code{UnixCCompiler} that handles the Cygwin port of the GNU C compiler to
Windows.  It also contains the Mingw32CCompiler class which handles the mingw32
port of GCC (same as cygwin in no-cygwin mode).

@node distutils archive_util --- Archiving utilities,distutils dep_util --- Dependency checking,distutils cygwincompiler --- Cygwin Compiler,API参考引用
@anchor{distutils/apiref distutils-archive-util-archiving-utilities}@anchor{4640}@anchor{distutils/apiref module-distutils archive_util}@anchor{39}
@subsection @code{distutils.archive_util} ---  Archiving utilities


@geindex distutils.archive_util (模块)

This module provides a few functions for creating archive files, such as
tarballs or zipfiles.

@geindex make_archive() (在 distutils.archive_util 模块中)
@anchor{distutils/apiref distutils archive_util make_archive}@anchor{4641}
@deffn {函数} distutils.archive_util.make_archive (base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0])

Create an archive file (eg. @code{zip} or @code{tar}).  @emph{base_name}  is the name of
the file to create, minus any format-specific extension;  @emph{format} is the
archive format: one of @code{zip}, @code{tar}, @code{gztar}, @code{bztar}, @code{xztar}, or
@code{ztar}. @emph{root_dir} is a directory that will be the root directory of the
archive; ie. we typically @code{chdir} into @emph{root_dir} before  creating the
archive.  @emph{base_dir} is the directory where we start  archiving from; ie.
@emph{base_dir} will be the common prefix of all files and directories in the
archive.  @emph{root_dir} and @emph{base_dir} both default to the current directory.
Returns the name of the archive file.


在 3.5 版更改: 添加了对 @code{xztar} 格式的支持

@end deffn

@geindex make_tarball() (在 distutils.archive_util 模块中)
@anchor{distutils/apiref distutils archive_util make_tarball}@anchor{4642}
@deffn {函数} distutils.archive_util.make_tarball (base_name, base_dir[, compress='gzip', verbose=0, dry_run=0])

'Create an (optional compressed) archive as a tar file from all files in and
under @emph{base_dir}. @emph{compress} must be @code{'gzip'} (the default),
@code{'bzip2'}, @code{'xz'}, @code{'compress'}, or @code{None}.  For the @code{'compress'}
method the compression utility named by @code{compress} must be on the
default program search path, so this is probably Unix-specific.  The output
tar file will be named @code{base_dir.tar}, possibly plus the appropriate
compression extension (@code{.gz}, @code{.bz2}, @code{.xz} or @code{.Z}).  Return the
output filename.


在 3.5 版更改: Added support for the @code{xz} compression.

@end deffn

@geindex make_zipfile() (在 distutils.archive_util 模块中)
@anchor{distutils/apiref distutils archive_util make_zipfile}@anchor{4643}
@deffn {函数} distutils.archive_util.make_zipfile (base_name, base_dir[, verbose=0, dry_run=0])

Create a zip file from all files in and under @emph{base_dir}.  The output zip file
will be named @emph{base_name} + @code{.zip}.  Uses either the  @ref{14b,,zipfile} Python
module (if available) or the InfoZIP @code{zip}  utility (if installed and
found on the default search path).  If neither  tool is available, raises
@code{DistutilsExecError}.   Returns the name of the output zip file.
@end deffn

@node distutils dep_util --- Dependency checking,distutils dir_util --- Directory tree operations,distutils archive_util --- Archiving utilities,API参考引用
@anchor{distutils/apiref distutils-dep-util-dependency-checking}@anchor{4644}@anchor{distutils/apiref module-distutils dep_util}@anchor{56}
@subsection @code{distutils.dep_util} --- Dependency checking


@geindex distutils.dep_util (模块)

This module provides functions for performing simple, timestamp-based
dependency of files and groups of files; also, functions based entirely  on such
timestamp dependency analysis.

@geindex newer() (在 distutils.dep_util 模块中)
@anchor{distutils/apiref distutils dep_util newer}@anchor{4645}
@deffn {函数} distutils.dep_util.newer (source, target)

Return true if @emph{source} exists and is more recently modified than @emph{target}, or
if @emph{source} exists and @emph{target} doesn't. Return false if both exist and @emph{target}
is the same age or newer  than @emph{source}. Raise @code{DistutilsFileError} if
@emph{source} does not exist.
@end deffn

@geindex newer_pairwise() (在 distutils.dep_util 模块中)
@anchor{distutils/apiref distutils dep_util newer_pairwise}@anchor{4646}
@deffn {函数} distutils.dep_util.newer_pairwise (sources, targets)

Walk two filename lists in parallel, testing if each source is newer than its
corresponding target.  Return a pair of lists (@emph{sources}, @emph{targets}) where
source is newer than target, according to the semantics of @ref{4645,,newer()}.

@c % % equivalent to a listcomp...
@end deffn

@geindex newer_group() (在 distutils.dep_util 模块中)
@anchor{distutils/apiref distutils dep_util newer_group}@anchor{4647}
@deffn {函数} distutils.dep_util.newer_group (sources, target[, missing='error'])

Return true if @emph{target} is out-of-date with respect to any file listed in
@emph{sources}.  In other words, if @emph{target} exists and is newer than every file in
@emph{sources}, return false; otherwise return true. @emph{missing} controls what we do
when a source file is missing; the default (@code{'error'}) is to blow up with an
@ref{30b,,OSError} from  inside @ref{328,,os.stat()}; if it is @code{'ignore'}, we silently
drop any missing source files; if it is @code{'newer'}, any missing source files
make us assume that @emph{target} is out-of-date (this is handy in "dry-run" mode:
it'll make you pretend to carry out commands that wouldn't work because inputs
are missing, but that doesn't matter because you're not actually going to run
the commands).
@end deffn

@node distutils dir_util --- Directory tree operations,distutils file_util --- Single file operations,distutils dep_util --- Dependency checking,API参考引用
@anchor{distutils/apiref distutils-dir-util-directory-tree-operations}@anchor{4648}@anchor{distutils/apiref module-distutils dir_util}@anchor{57}
@subsection @code{distutils.dir_util} --- Directory tree operations


@geindex distutils.dir_util (模块)

This module provides functions for operating on directories and trees of
directories.

@geindex mkpath() (在 distutils.dir_util 模块中)
@anchor{distutils/apiref distutils dir_util mkpath}@anchor{4636}
@deffn {函数} distutils.dir_util.mkpath (name[, mode=0o777, verbose=0, dry_run=0])

Create a directory and any missing ancestor directories.  If the directory
already exists (or if @emph{name} is the empty string, which means the current
directory, which of course exists), then do nothing.  Raise
@code{DistutilsFileError} if unable to create some directory along the way (eg.
some sub-path exists, but is a file rather than a directory).  If @emph{verbose} is
true, print a one-line summary of each mkdir to stdout.  Return the list of
directories actually created.
@end deffn

@geindex create_tree() (在 distutils.dir_util 模块中)
@anchor{distutils/apiref distutils dir_util create_tree}@anchor{4649}
@deffn {函数} distutils.dir_util.create_tree (base_dir, files[, mode=0o777, verbose=0, dry_run=0])

Create all the empty directories under @emph{base_dir} needed to put @emph{files} there.
@emph{base_dir} is just the name of a directory which doesn't necessarily exist
yet; @emph{files} is a list of filenames to be interpreted relative to @emph{base_dir}.
@emph{base_dir} + the directory portion of every file in @emph{files} will be created if
it doesn't already exist.  @emph{mode}, @emph{verbose} and @emph{dry_run} flags  are as for
@ref{4636,,mkpath()}.
@end deffn

@geindex copy_tree() (在 distutils.dir_util 模块中)
@anchor{distutils/apiref distutils dir_util copy_tree}@anchor{464a}
@deffn {函数} distutils.dir_util.copy_tree (src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0])

Copy an entire directory tree @emph{src} to a new location @emph{dst}.  Both @emph{src} and
@emph{dst} must be directory names.  If @emph{src} is not a directory, raise
@code{DistutilsFileError}.  If @emph{dst} does  not exist, it is created with
@ref{4636,,mkpath()}.  The end result of the  copy is that every file in @emph{src} is
copied to @emph{dst}, and  directories under @emph{src} are recursively copied to @emph{dst}.
Return the list of files that were copied or might have been copied, using their
output name. The return value is unaffected by @emph{update} or @emph{dry_run}: it is
simply the list of all files under @emph{src}, with the names changed to be under
@emph{dst}.

@emph{preserve_mode} and @emph{preserve_times} are the same as for
@ref{464b,,distutils.file_util.copy_file()}; note that they only apply to
regular files, not to
directories.  If @emph{preserve_symlinks} is true, symlinks will be copied as
symlinks (on platforms that support them!); otherwise (the default), the
destination of the symlink will be copied.  @emph{update} and @emph{verbose} are the same
as for @code{copy_file()}.

Files in @emph{src} that begin with @code{.nfs} are skipped (more information on
these files is available in answer D2 of the NFS FAQ page@footnote{http://nfs.sourceforge.net/#section_d}).


在 3.3.1 版更改: NFS files are ignored.

@end deffn

@geindex remove_tree() (在 distutils.dir_util 模块中)
@anchor{distutils/apiref distutils dir_util remove_tree}@anchor{464c}
@deffn {函数} distutils.dir_util.remove_tree (directory[, verbose=0, dry_run=0])

Recursively remove @emph{directory} and all files and directories underneath it. Any
errors are ignored (apart from being reported to @code{sys.stdout} if @emph{verbose} is
true).
@end deffn

@node distutils file_util --- Single file operations,distutils util --- Miscellaneous other utility functions,distutils dir_util --- Directory tree operations,API参考引用
@anchor{distutils/apiref distutils-file-util-single-file-operations}@anchor{464d}@anchor{distutils/apiref module-distutils file_util}@anchor{5c}
@subsection @code{distutils.file_util} --- Single file operations


@geindex distutils.file_util (模块)

This module contains some utility functions for operating on individual files.

@geindex copy_file() (在 distutils.file_util 模块中)
@anchor{distutils/apiref distutils file_util copy_file}@anchor{464b}
@deffn {函数} distutils.file_util.copy_file (src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0])

Copy file @emph{src} to @emph{dst}. If @emph{dst} is a directory, then @emph{src} is copied there
with the same name; otherwise, it must be a filename. (If the file exists, it
will be ruthlessly clobbered.) If @emph{preserve_mode} is true (the default), the
file's mode (type and permission bits, or whatever is analogous on the
current platform) is copied. If @emph{preserve_times} is true (the default), the
last-modified and last-access times are copied as well. If @emph{update} is true,
@emph{src} will only be copied if @emph{dst} does not exist, or if @emph{dst} does exist but
is older than @emph{src}.

@emph{link} allows you to make hard links (using @ref{b1a,,os.link()}) or symbolic links
(using @ref{b20,,os.symlink()}) instead of copying: set it to @code{'hard'} or
@code{'sym'}; if it is @code{None} (the default), files are copied. Don't set @emph{link}
on systems that don't support it: @ref{464b,,copy_file()} doesn't check if hard or
symbolic linking is available.  It uses @code{_copy_file_contents()} to copy file
contents.

Return a tuple @code{(dest_name, copied)}: @emph{dest_name} is the actual  name of the
output file, and @emph{copied} is true if the file was copied  (or would have been
copied, if @emph{dry_run} true).

@c % XXX if the destination file already exists, we clobber it if

@c % copying, but blow up if linking.  Hmmm.  And I don't know what

@c % macostools.copyfile() does.  Should definitely be consistent, and

@c % should probably blow up if destination exists and we would be

@c % changing it (ie. it's not already a hard/soft link to src OR

@c % (not update) and (src newer than dst)).
@end deffn

@geindex move_file() (在 distutils.file_util 模块中)
@anchor{distutils/apiref distutils file_util move_file}@anchor{4638}
@deffn {函数} distutils.file_util.move_file (src, dst[, verbose, dry_run])

Move file @emph{src} to @emph{dst}. If @emph{dst} is a directory, the file will be moved into
it with the same name; otherwise, @emph{src} is just renamed to @emph{dst}.  Returns the
new full name of the file.

@cartouche
@quotation 警告 
Handles cross-device moves on Unix using @ref{464b,,copy_file()}.  What about
other systems?
@end quotation
@end cartouche
@end deffn

@geindex write_file() (在 distutils.file_util 模块中)
@anchor{distutils/apiref distutils file_util write_file}@anchor{464e}
@deffn {函数} distutils.file_util.write_file (filename, contents)

Create a file called @emph{filename} and write @emph{contents} (a sequence of strings
without line terminators) to it.
@end deffn

@node distutils util --- Miscellaneous other utility functions,distutils dist --- The Distribution class,distutils file_util --- Single file operations,API参考引用
@anchor{distutils/apiref distutils-util-miscellaneous-other-utility-functions}@anchor{464f}@anchor{distutils/apiref module-distutils util}@anchor{64}
@subsection @code{distutils.util} --- Miscellaneous other utility functions


@geindex distutils.util (模块)

This module contains other assorted bits and pieces that don't fit into  any
other utility module.

@geindex get_platform() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util get_platform}@anchor{4650}
@deffn {函数} distutils.util.get_platform ()

Return a string that identifies the current platform.  This is used mainly to
distinguish platform-specific build directories and platform-specific built
distributions.  Typically includes the OS name and version and the
architecture (as supplied by 'os.uname()'), although the exact information
included depends on the OS; e.g., on Linux, the kernel version isn't
particularly important.

返回值的示例：


@itemize *

@item 
@code{linux-i586}

@item 
@code{linux-alpha}

@item 
@code{solaris-2.6-sun4u}
@end itemize

For non-POSIX platforms, currently just returns @code{sys.platform}.

For macOS systems the OS version reflects the minimal version on which
binaries will run (that is, the value of @code{MACOSX_DEPLOYMENT_TARGET}
during the build of Python), not the OS version of the current system.

For universal binary builds on macOS the architecture value reflects
the universal binary status instead of the architecture of the current
processor. For 32-bit universal binaries the architecture is @code{fat},
for 64-bit universal binaries the architecture is @code{fat64}, and
for 4-way universal binaries the architecture is @code{universal}. Starting
from Python 2.7 and Python 3.2 the architecture @code{fat3} is used for
a 3-way universal build (ppc, i386, x86_64) and @code{intel} is used for
a universal build with the i386 and x86_64 architectures

macOS 上的返回值示例:


@itemize *

@item 
@code{macosx-10.3-ppc}

@item 
@code{macosx-10.3-fat}

@item 
@code{macosx-10.5-universal}

@item 
@code{macosx-10.6-intel}
@end itemize

For AIX, Python 3.9 and later return a string starting with "aix", followed
by additional fields (separated by @code{'-'}) that represent the combined
values of AIX Version, Release and Technology Level (first field), Build Date
(second field), and bit-size (third field). Python 3.8 and earlier returned
only a single additional field with the AIX Version and Release.

Examples of returned values on AIX:


@itemize *

@item 
@code{aix-5307-0747-32} # 32-bit build on AIX @code{oslevel -s}: 5300-07-00-0000

@item 
@code{aix-7105-1731-64} # 64-bit build on AIX @code{oslevel -s}: 7100-05-01-1731

@item 
@code{aix-7.2}          # Legacy form reported in Python 3.8 and earlier
@end itemize


在 3.9 版更改: The AIX platform string format now also includes the technology level,
build date, and ABI bit-size.

@end deffn

@geindex convert_path() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util convert_path}@anchor{4651}
@deffn {函数} distutils.util.convert_path (pathname)

Return 'pathname' as a name that will work on the native filesystem, i.e. split
it on '/' and put it back together again using the current directory separator.
Needed because filenames in the setup script are always supplied in Unix style,
and have to be converted to the local convention before we can actually use them
in the filesystem.  Raises @ref{16d,,ValueError} on non-Unix-ish systems if
@emph{pathname} either  starts or ends with a slash.
@end deffn

@geindex change_root() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util change_root}@anchor{4652}
@deffn {函数} distutils.util.change_root (new_root, pathname)

Return @emph{pathname} with @emph{new_root} prepended.  If @emph{pathname} is relative, this is
equivalent to @code{os.path.join(new_root,pathname)} Otherwise, it requires making
@emph{pathname} relative and then joining the two, which is tricky on DOS/Windows.
@end deffn

@geindex check_environ() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util check_environ}@anchor{4653}
@deffn {函数} distutils.util.check_environ ()

Ensure that 'os.environ' has all the environment variables we guarantee that
users can use in config files, command-line options, etc.  Currently this
includes:


@itemize *

@item 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} - user's home directory (Unix only)

@item 
@geindex PLAT
@geindex 环境变量; PLAT
@code{PLAT} - description of the current platform, including hardware and
OS (see @ref{4650,,get_platform()})
@end itemize
@end deffn

@geindex subst_vars() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util subst_vars}@anchor{4654}
@deffn {函数} distutils.util.subst_vars (s, local_vars)

Perform shell/Perl-style variable substitution on @emph{s}.  Every occurrence of
@code{$} followed by a name is considered a variable, and variable is substituted
by the value found in the @emph{local_vars} dictionary, or in @code{os.environ} if it's
not in @emph{local_vars}. @emph{os.environ} is first checked/augmented to guarantee that
it contains certain values: see @ref{4653,,check_environ()}.  Raise @ref{16d,,ValueError}
for any variables not found in either @emph{local_vars} or @code{os.environ}.

Note that this is not a fully-fledged string interpolation function. A valid
@code{$variable} can consist only of upper and lower case letters, numbers and an
underscore. No @{ @} or ( ) style quoting is available.
@end deffn

@geindex split_quoted() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util split_quoted}@anchor{4626}
@deffn {函数} distutils.util.split_quoted (s)

Split a string up according to Unix shell-like rules for quotes and backslashes.
In short: words are delimited by spaces, as long as those spaces are not escaped
by a backslash, or inside a quoted string. Single and double quotes are
equivalent, and the quote characters can be backslash-escaped.  The backslash is
stripped from any two-character escape sequence, leaving only the escaped
character.  The quote characters are stripped from any quoted string.  Returns a
list of words.

@c % Should probably be moved into the standard library.
@end deffn

@geindex execute() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util execute}@anchor{4633}
@deffn {函数} distutils.util.execute (func, args[, msg=None, verbose=0, dry_run=0])

Perform some action that affects the outside world (for instance, writing to the
filesystem).  Such actions are special because they are disabled by the
@emph{dry_run} flag.  This method takes  care of all that bureaucracy for you; all
you have to do is supply the function to call and an argument tuple for it (to
embody the "external action" being performed), and an optional message to print.
@end deffn

@geindex strtobool() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util strtobool}@anchor{4655}
@deffn {函数} distutils.util.strtobool (val)

Convert a string representation of truth to true (1) or false (0).

True values are @code{y}, @code{yes}, @code{t}, @code{true}, @code{on}  and @code{1}; false values
are @code{n}, @code{no}, @code{f}, @code{false},  @code{off} and @code{0}.  Raises
@ref{16d,,ValueError} if @emph{val}  is anything else.
@end deffn

@geindex byte_compile() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util byte_compile}@anchor{4656}
@deffn {函数} distutils.util.byte_compile (py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None])

Byte-compile a collection of Python source files to @code{.pyc} files in a
@code{__pycache__} subdirectory (see 
@geindex Python 提高建议; PEP 3147
PEP 3147@footnote{https://www.python.org/dev/peps/pep-3147} and 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488}).
@emph{py_files} is a list of files to compile; any files that don't end in
@code{.py} are silently skipped.  @emph{optimize} must be one of the following:


@itemize *

@item 
@code{0} - don't optimize

@item 
@code{1} - normal optimization (like @code{python -O})

@item 
@code{2} - extra optimization (like @code{python -OO})
@end itemize

If @emph{force} is true, all files are recompiled regardless of timestamps.

The source filename encoded in each @ref{713,,bytecode} file defaults to the filenames
listed in @emph{py_files}; you can modify these with @emph{prefix} and @emph{basedir}.
@emph{prefix} is a string that will be stripped off of each source filename, and
@emph{base_dir} is a directory name that will be prepended (after @emph{prefix} is
stripped).  You can supply either or both (or neither) of @emph{prefix} and
@emph{base_dir}, as you wish.

If @emph{dry_run} is true, doesn't actually do anything that would affect the
filesystem.

Byte-compilation is either done directly in this interpreter process with the
standard @ref{d7,,py_compile} module, or indirectly by writing a temporary script
and executing it.  Normally, you should let @ref{4656,,byte_compile()} figure out to
use direct compilation or not (see the source for details).  The @emph{direct} flag
is used by the script generated in indirect mode; unless you know what you're
doing, leave it set to @code{None}.


在 3.2.3 版更改: Create @code{.pyc} files with an @ref{3b9e,,import magic tag} in their name, in a @code{__pycache__} subdirectory
instead of files without tag in the current directory.



在 3.5 版更改: Create @code{.pyc} files according to 
@geindex Python 提高建议; PEP 488
PEP 488@footnote{https://www.python.org/dev/peps/pep-0488}.

@end deffn

@geindex rfc822_escape() (在 distutils.util 模块中)
@anchor{distutils/apiref distutils util rfc822_escape}@anchor{4657}
@deffn {函数} distutils.util.rfc822_escape (header)

Return a version of @emph{header} escaped for inclusion in an 
@geindex RFC; RFC 822
RFC 822@footnote{https://tools.ietf.org/html/rfc822.html} header, by
ensuring there are 8 spaces space after each newline. Note that it does no other
modification of the string.

@c % this _can_ be replaced
@end deffn

@c % \subsection{Distutils objects}

@node distutils dist --- The Distribution class,distutils extension --- The Extension class,distutils util --- Miscellaneous other utility functions,API参考引用
@anchor{distutils/apiref distutils-dist-the-distribution-class}@anchor{4658}@anchor{distutils/apiref module-distutils dist}@anchor{58}
@subsection @code{distutils.dist} --- The Distribution class


@geindex distutils.dist (模块)

This module provides the @ref{4609,,Distribution} class, which
represents the module distribution being built/installed/distributed.

@node distutils extension --- The Extension class,distutils debug --- Distutils debug mode,distutils dist --- The Distribution class,API参考引用
@anchor{distutils/apiref distutils-extension-the-extension-class}@anchor{4659}@anchor{distutils/apiref module-distutils extension}@anchor{5a}
@subsection @code{distutils.extension} --- The Extension class


@geindex distutils.extension (模块)

This module provides the @code{Extension} class, used to describe C/C++
extension modules in setup scripts.

@c % \subsection{Ungrouped modules}

@c % The following haven't been moved into a more appropriate section yet.

@node distutils debug --- Distutils debug mode,distutils errors --- Distutils exceptions,distutils extension --- The Extension class,API参考引用
@anchor{distutils/apiref distutils-debug-distutils-debug-mode}@anchor{465a}@anchor{distutils/apiref module-distutils debug}@anchor{55}
@subsection @code{distutils.debug} --- Distutils debug mode


@geindex distutils.debug (模块)

本模块提供DEBUG标识。

@node distutils errors --- Distutils exceptions,distutils fancy_getopt --- Wrapper around the standard getopt module,distutils debug --- Distutils debug mode,API参考引用
@anchor{distutils/apiref distutils-errors-distutils-exceptions}@anchor{465b}@anchor{distutils/apiref module-distutils errors}@anchor{59}
@subsection @code{distutils.errors} --- Distutils exceptions


@geindex distutils.errors (模块)

Provides exceptions used by the Distutils modules.  Note that Distutils modules
may raise standard exceptions; in particular, SystemExit is usually raised for
errors that are obviously the end-user's fault (eg. bad command-line arguments).

This module is safe to use in @code{from ... import *} mode; it only exports
symbols whose names start with @code{Distutils} and end with @code{Error}.

@node distutils fancy_getopt --- Wrapper around the standard getopt module,distutils filelist --- The FileList class,distutils errors --- Distutils exceptions,API参考引用
@anchor{distutils/apiref distutils-fancy-getopt-wrapper-around-the-standard-getopt-module}@anchor{465c}@anchor{distutils/apiref module-distutils fancy_getopt}@anchor{5b}
@subsection @code{distutils.fancy_getopt} --- Wrapper around the standard getopt module


@geindex distutils.fancy_getopt (模块)

This module provides a wrapper around the standard @ref{85,,getopt}  module that
provides the following additional features:


@itemize *

@item 
short and long options are tied together

@item 
options have help strings, so @ref{465d,,fancy_getopt()} could potentially  create a
complete usage summary

@item 
options set attributes of a passed-in object

@item 
boolean options can have "negative aliases" --- eg. if @code{--quiet} is
the "negative alias" of @code{--verbose}, then @code{--quiet} on the
command line sets @emph{verbose} to false.
@end itemize

@geindex fancy_getopt() (在 distutils.fancy_getopt 模块中)
@anchor{distutils/apiref distutils fancy_getopt fancy_getopt}@anchor{465d}
@deffn {函数} distutils.fancy_getopt.fancy_getopt (options, negative_opt, object, args)

Wrapper function. @emph{options} is a list of @code{(long_option, short_option,
help_string)} 3-tuples as described in the constructor for
@ref{465e,,FancyGetopt}. @emph{negative_opt} should be a dictionary mapping option names
to option names, both the key and value should be in the @emph{options} list.
@emph{object} is an object which will be used to store values (see the @ref{85,,getopt()}
method of the @ref{465e,,FancyGetopt} class). @emph{args} is the argument list. Will use
@code{sys.argv[1:]} if you  pass @code{None} as @emph{args}.
@end deffn

@geindex wrap_text() (在 distutils.fancy_getopt 模块中)
@anchor{distutils/apiref distutils fancy_getopt wrap_text}@anchor{465f}
@deffn {函数} distutils.fancy_getopt.wrap_text (text, width)

Wraps @emph{text} to less than @emph{width} wide.
@end deffn

@geindex FancyGetopt (distutils.fancy_getopt 中的类)
@anchor{distutils/apiref distutils fancy_getopt FancyGetopt}@anchor{465e}
@deffn {类} distutils.fancy_getopt.FancyGetopt ([option_table=None])

The option_table is a list of 3-tuples: @code{(long_option, short_option,
help_string)}

If an option takes an argument, its @emph{long_option} should have @code{'='} appended;
@emph{short_option} should just be a single character, no @code{':'} in any case.
@emph{short_option} should be @code{None} if a @emph{long_option}  doesn't have a
corresponding @emph{short_option}. All option tuples must have long options.
@end deffn

The @ref{465e,,FancyGetopt} class provides the following methods:

@geindex getopt() (distutils.fancy_getopt.FancyGetopt 方法)
@anchor{distutils/apiref distutils fancy_getopt FancyGetopt getopt}@anchor{4660}
@deffn {方法} FancyGetopt.getopt ([args=None, object=None])

Parse command-line options in args. Store as attributes on @emph{object}.

If @emph{args} is @code{None} or not supplied, uses @code{sys.argv[1:]}.  If @emph{object} is
@code{None} or not supplied, creates a new @code{OptionDummy} instance, stores
option values there, and returns a tuple @code{(args, object)}.  If @emph{object} is
supplied, it is modified in place and @ref{85,,getopt()} just returns @emph{args}; in
both cases, the returned @emph{args} is a modified copy of the passed-in @emph{args} list,
which is left untouched.

@c % and args returned are?
@end deffn

@geindex get_option_order() (distutils.fancy_getopt.FancyGetopt 方法)
@anchor{distutils/apiref distutils fancy_getopt FancyGetopt get_option_order}@anchor{4661}
@deffn {方法} FancyGetopt.get_option_order ()

Returns the list of @code{(option, value)} tuples processed by the previous run of
@ref{85,,getopt()}  Raises @ref{3e4,,RuntimeError} if @ref{85,,getopt()} hasn't been called
yet.
@end deffn

@geindex generate_help() (distutils.fancy_getopt.FancyGetopt 方法)
@anchor{distutils/apiref distutils fancy_getopt FancyGetopt generate_help}@anchor{4662}
@deffn {方法} FancyGetopt.generate_help ([header=None])

Generate help text (a list of strings, one per suggested line of output) from
the option table for this @ref{465e,,FancyGetopt} object.

If supplied, prints the supplied @emph{header} at the top of the help.
@end deffn

@node distutils filelist --- The FileList class,distutils log --- Simple PEP 282-style logging,distutils fancy_getopt --- Wrapper around the standard getopt module,API参考引用
@anchor{distutils/apiref distutils-filelist-the-filelist-class}@anchor{4663}@anchor{distutils/apiref module-distutils filelist}@anchor{5d}
@subsection @code{distutils.filelist} --- The FileList class


@geindex distutils.filelist (模块)

This module provides the @code{FileList} class, used for poking about the
filesystem and building lists of files.

@node distutils log --- Simple PEP 282-style logging,distutils spawn --- Spawn a sub-process,distutils filelist --- The FileList class,API参考引用
@anchor{distutils/apiref distutils-log-simple-pep-282-style-logging}@anchor{4664}@anchor{distutils/apiref module-distutils log}@anchor{5e}
@subsection @code{distutils.log} --- Simple @strong{PEP 282}-style logging


@geindex Python 提高建议; PEP 282

@geindex distutils.log (模块)

@node distutils spawn --- Spawn a sub-process,distutils sysconfig --- System configuration information,distutils log --- Simple PEP 282-style logging,API参考引用
@anchor{distutils/apiref distutils-spawn-spawn-a-sub-process}@anchor{4665}@anchor{distutils/apiref module-distutils spawn}@anchor{60}
@subsection @code{distutils.spawn} --- Spawn a sub-process


@geindex distutils.spawn (模块)

This module provides the @code{spawn()} function, a front-end to  various
platform-specific functions for launching another program in a  sub-process.
Also provides @code{find_executable()} to search the path for a given executable
name.

@node distutils sysconfig --- System configuration information,distutils text_file --- The TextFile class,distutils spawn --- Spawn a sub-process,API参考引用
@anchor{distutils/apiref distutils-sysconfig-system-configuration-information}@anchor{4666}@anchor{distutils/apiref module-distutils sysconfig}@anchor{61}
@subsection @code{distutils.sysconfig} --- System configuration information


@geindex distutils.sysconfig (模块)

The @ref{61,,distutils.sysconfig} module provides access to Python's low-level
configuration information.  The specific configuration variables available
depend heavily on the platform and configuration. The specific variables depend
on the build process for the specific version of Python being run; the variables
are those found in the @code{Makefile} and configuration header that are
installed with Python on Unix systems.  The configuration header is called
@code{pyconfig.h} for Python versions starting with 2.2, and @code{config.h}
for earlier versions of Python.

Some additional functions are provided which perform some useful manipulations
for other parts of the @ref{38,,distutils} package.

@geindex PREFIX() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig PREFIX}@anchor{4667}
@deffn {数据} distutils.sysconfig.PREFIX

The result of @code{os.path.normpath(sys.prefix)}.
@end deffn

@geindex EXEC_PREFIX() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig EXEC_PREFIX}@anchor{4668}
@deffn {数据} distutils.sysconfig.EXEC_PREFIX

The result of @code{os.path.normpath(sys.exec_prefix)}.
@end deffn

@geindex get_config_var() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_config_var}@anchor{4669}
@deffn {函数} distutils.sysconfig.get_config_var (name)

Return the value of a single variable.  This is equivalent to
@code{get_config_vars().get(name)}.
@end deffn

@geindex get_config_vars() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_config_vars}@anchor{466a}
@deffn {函数} distutils.sysconfig.get_config_vars (...)

Return a set of variable definitions.  If there are no arguments, this returns a
dictionary mapping names of configuration variables to values.  If arguments are
provided, they should be strings, and the return value will be a sequence giving
the associated values. If a given name does not have a corresponding value,
@code{None} will be included for that variable.
@end deffn

@geindex get_config_h_filename() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_config_h_filename}@anchor{466b}
@deffn {函数} distutils.sysconfig.get_config_h_filename ()

Return the full path name of the configuration header.  For Unix, this will be
the header generated by the @code{configure} script; for other platforms the
header will have been supplied directly by the Python source distribution.  The
file is a platform-specific text file.
@end deffn

@geindex get_makefile_filename() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_makefile_filename}@anchor{466c}
@deffn {函数} distutils.sysconfig.get_makefile_filename ()

Return the full path name of the @code{Makefile} used to build Python.  For
Unix, this will be a file generated by the @code{configure} script; the
meaning for other platforms will vary.  The file is a platform-specific text
file, if it exists. This function is only useful on POSIX platforms.
@end deffn

@geindex get_python_inc() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_python_inc}@anchor{466d}
@deffn {函数} distutils.sysconfig.get_python_inc ([plat_specific[, prefix]])

Return the directory for either the general or platform-dependent C include
files.  If @emph{plat_specific} is true, the platform-dependent include directory is
returned; if false or omitted, the platform-independent directory is returned.
If @emph{prefix} is given, it is used as either the prefix instead of
@ref{4667,,PREFIX}, or as the exec-prefix instead of @ref{4668,,EXEC_PREFIX} if
@emph{plat_specific} is true.
@end deffn

@geindex get_python_lib() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig get_python_lib}@anchor{466e}
@deffn {函数} distutils.sysconfig.get_python_lib ([plat_specific[, standard_lib[, prefix]]])

Return the directory for either the general or platform-dependent library
installation.  If @emph{plat_specific} is true, the platform-dependent include
directory is returned; if false or omitted, the platform-independent directory
is returned.  If @emph{prefix} is given, it is used as either the prefix instead of
@ref{4667,,PREFIX}, or as the exec-prefix instead of @ref{4668,,EXEC_PREFIX} if
@emph{plat_specific} is true.  If @emph{standard_lib} is true, the directory for the
standard library is returned rather than the directory for the installation of
third-party extensions.
@end deffn

The following function is only intended for use within the @ref{38,,distutils}
package.

@geindex customize_compiler() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig customize_compiler}@anchor{466f}
@deffn {函数} distutils.sysconfig.customize_compiler (compiler)

Do any platform-specific customization of a
@ref{460d,,distutils.ccompiler.CCompiler} instance.

This function is only needed on Unix at this time, but should be called
consistently to support forward-compatibility.  It inserts the information that
varies across Unix flavors and is stored in Python's @code{Makefile}.  This
information includes the selected compiler, compiler and linker options, and the
extension used by the linker for shared objects.
@end deffn

This function is even more special-purpose, and should only be used from
Python's own build procedures.

@geindex set_python_build() (在 distutils.sysconfig 模块中)
@anchor{distutils/apiref distutils sysconfig set_python_build}@anchor{4670}
@deffn {函数} distutils.sysconfig.set_python_build ()

Inform the @ref{61,,distutils.sysconfig} module that it is being used as part of
the build process for Python.  This changes a lot of relative locations for
files, allowing them to be located in the build area rather than in an installed
Python.
@end deffn

@node distutils text_file --- The TextFile class,distutils version --- Version number classes,distutils sysconfig --- System configuration information,API参考引用
@anchor{distutils/apiref distutils-text-file-the-textfile-class}@anchor{4671}@anchor{distutils/apiref module-distutils text_file}@anchor{62}
@subsection @code{distutils.text_file} --- The TextFile class


@geindex distutils.text_file (模块)

This module provides the @ref{4672,,TextFile} class, which gives an interface  to
text files that (optionally) takes care of stripping comments, ignoring  blank
lines, and joining lines with backslashes.

@geindex TextFile (distutils.text_file 中的类)
@anchor{distutils/apiref distutils text_file TextFile}@anchor{4672}
@deffn {类} distutils.text_file.TextFile ([filename=None, file=None, **options])

This class provides a file-like object that takes care of all  the things you
commonly want to do when processing a text file  that has some line-by-line
syntax: strip comments (as long as @code{#}  is your comment character), skip blank
lines, join adjacent lines by escaping the newline (ie. backslash at end of
line), strip leading and/or trailing whitespace.  All of these are optional and
independently controllable.

The class provides a @ref{4673,,warn()} method so you can generate  warning messages
that report physical line number, even if the  logical line in question spans
multiple physical lines.  Also  provides @ref{4674,,unreadline()} for implementing
line-at-a-time lookahead.

@ref{4672,,TextFile} instances are create with either @emph{filename}, @emph{file}, or both.
@ref{3e4,,RuntimeError} is raised if both are @code{None}. @emph{filename} should be a
string, and @emph{file} a file object (or something that provides @ref{de,,readline()}
and @ref{4675,,close()}  methods).  It is recommended that you supply at least
@emph{filename},  so that @ref{4672,,TextFile} can include it in warning messages.  If
@emph{file} is not supplied, @ref{4672,,TextFile} creates its own using the
@ref{16f,,open()} built-in function.

The options are all boolean, and affect the values returned by @ref{de,,readline()}


@multitable {xxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
@headitem

选项名称

@tab

描述

@tab

默认值

@item

@emph{strip_comments}

@tab

strip from @code{'#'} to
end-of-line, as well as any
whitespace leading up to the
@code{'#'}---unless it is
escaped by a backslash

@tab

true

@item

@emph{lstrip_ws}

@tab

strip leading whitespace from
each line before returning it

@tab

false

@item

@emph{rstrip_ws}

@tab

strip trailing whitespace
(including line terminator!)
from each line before
returning it.

@tab

true

@item

@emph{skip_blanks}

@tab

skip lines that are empty
*after* stripping comments
and whitespace.  (If both
lstrip_ws and rstrip_ws are
false, then some lines may
consist of solely whitespace:
these will *not* be skipped,
even if @emph{skip_blanks} is
true.)

@tab

true

@item

@emph{join_lines}

@tab

if a backslash is the last
non-newline character on a
line after stripping comments
and whitespace, join the
following line to it to form
one logical line; if N
consecutive lines end with a
backslash, then N+1 physical
lines will be joined to form
one logical line.

@tab

false

@item

@emph{collapse_join}

@tab

strip leading whitespace from
lines that are joined to their
predecessor; only matters if
@code{(join_lines and not
lstrip_ws)}

@tab

false

@end multitable


Note that since @emph{rstrip_ws} can strip the trailing newline, the semantics of
@ref{de,,readline()} must differ from those of the built-in file object's
@ref{de,,readline()} method!  In particular, @ref{de,,readline()}  returns @code{None} for
end-of-file: an empty string might just be a  blank line (or an all-whitespace
line), if @emph{rstrip_ws} is true  but @emph{skip_blanks} is not.

@geindex open() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile open}@anchor{4676}
@deffn {方法} open (filename)

Open a new file @emph{filename}.  This overrides any @emph{file} or @emph{filename}
constructor arguments.
@end deffn

@geindex close() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile close}@anchor{4675}
@deffn {方法} close ()

Close the current file and forget everything we know about it (including the
filename and the current line number).
@end deffn

@geindex warn() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile warn}@anchor{4673}
@deffn {方法} warn (msg[, line=None])

Print (to stderr) a warning message tied to the current logical line in the
current file.  If the current logical line in the file spans multiple physical
lines, the warning refers to the whole range, such as @code{"lines 3-5"}.  If
@emph{line} is supplied,  it overrides the current line number; it may be a list or
tuple  to indicate a range of physical lines, or an integer for a  single
physical line.
@end deffn

@geindex readline() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile readline}@anchor{4677}
@deffn {方法} readline ()

Read and return a single logical line from the current file (or from an internal
buffer if lines have previously been "unread" with @ref{4674,,unreadline()}).  If the
@emph{join_lines} option  is true, this may involve reading multiple physical lines
concatenated into a single string.  Updates the current line number,  so calling
@ref{4673,,warn()} after @ref{de,,readline()} emits a warning  about the physical line(s)
just read.  Returns @code{None} on end-of-file,  since the empty string can occur
if @emph{rstrip_ws} is true but  @emph{strip_blanks} is not.
@end deffn

@geindex readlines() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile readlines}@anchor{4678}
@deffn {方法} readlines ()

Read and return the list of all logical lines remaining in the current file.
This updates the current line number to the last line of the file.
@end deffn

@geindex unreadline() (distutils.text_file.TextFile 方法)
@anchor{distutils/apiref distutils text_file TextFile unreadline}@anchor{4674}
@deffn {方法} unreadline (line)

Push @emph{line} (a string) onto an internal buffer that will be checked by future
@ref{de,,readline()} calls.  Handy for implementing a parser with line-at-a-time
lookahead. Note that lines that are "unread" with @ref{4674,,unreadline()} are not
subsequently re-cleansed (whitespace  stripped, or whatever) when read with
@ref{de,,readline()}. If multiple calls are made to @ref{4674,,unreadline()} before a call
to @ref{de,,readline()}, the lines will be returned most in most recent first order.
@end deffn
@end deffn

@node distutils version --- Version number classes,distutils cmd --- Abstract base class for Distutils commands,distutils text_file --- The TextFile class,API参考引用
@anchor{distutils/apiref distutils-version-version-number-classes}@anchor{4679}@anchor{distutils/apiref module-distutils version}@anchor{65}
@subsection @code{distutils.version} --- Version number classes


@geindex distutils.version (模块)

@c % todo

@c % \section{Distutils Commands}

@c %

@c % This part of Distutils implements the various Distutils commands, such

@c % as \code{build}, \code{install} \&c. Each command is implemented as a

@c % separate module, with the command name as the name of the module.

@node distutils cmd --- Abstract base class for Distutils commands,Creating a new Distutils command,distutils version --- Version number classes,API参考引用
@anchor{distutils/apiref distutils-cmd-abstract-base-class-for-distutils-commands}@anchor{467a}@anchor{distutils/apiref module-distutils cmd}@anchor{3c}
@subsection @code{distutils.cmd} --- Abstract base class for Distutils commands


@geindex distutils.cmd (模块)

This module supplies the abstract base class @ref{45f8,,Command}.

@geindex Command (distutils.cmd 中的类)
@anchor{distutils/apiref distutils cmd Command}@anchor{45f8}
@deffn {类} distutils.cmd.Command (dist)

Abstract base class for defining command classes, the "worker bees" of the
Distutils.  A useful analogy for command classes is to think of them as
subroutines with local variables called @emph{options}.  The options are declared
in @ref{467b,,initialize_options()} and defined (given their final values) in
@ref{467c,,finalize_options()}, both of which must be defined by every command
class.  The distinction between the two is necessary because option values
might come from the outside world (command line, config file, ...), and any
options dependent on other options must be computed after these outside
influences have been processed --- hence @ref{467c,,finalize_options()}.  The body
of the subroutine, where it does all its work based on the values of its
options, is the @ref{467d,,run()} method, which must also be implemented by every
command class.

The class constructor takes a single argument @emph{dist}, a
@ref{4609,,Distribution} instance.
@end deffn

@node Creating a new Distutils command,distutils command --- Individual Distutils commands,distutils cmd --- Abstract base class for Distutils commands,API参考引用
@anchor{distutils/apiref creating-a-new-distutils-command}@anchor{467e}
@subsection Creating a new Distutils command


This section outlines the steps to create a new Distutils command.

A new command lives in a module in the @ref{3d,,distutils.command} package. There
is a sample template in that directory called @code{command_template}.  Copy
this file to a new module with the same name as the new command you're
implementing.  This module should implement a class with the same name as the
module (and the command).  So, for instance, to create the command
@code{peel_banana} (so that users can run @code{setup.py peel_banana}), you'd copy
@code{command_template} to @code{distutils/command/peel_banana.py}, then edit
it so that it's implementing the class @code{peel_banana}, a subclass of
@ref{45f8,,distutils.cmd.Command}.

Subclasses of @ref{45f8,,Command} must define the following methods.

@geindex initialize_options() (distutils.cmd.Command 方法)
@anchor{distutils/apiref distutils cmd Command initialize_options}@anchor{467b}
@deffn {方法} Command.initialize_options ()

Set default values for all the options that this command supports.  Note that
these defaults may be overridden by other commands, by the setup script, by
config files, or by the command-line.  Thus, this is not the place to code
dependencies between options; generally, @ref{467b,,initialize_options()}
implementations are just a bunch of @code{self.foo = None} assignments.
@end deffn

@geindex finalize_options() (distutils.cmd.Command 方法)
@anchor{distutils/apiref distutils cmd Command finalize_options}@anchor{467c}
@deffn {方法} Command.finalize_options ()

Set final values for all the options that this command supports. This is
always called as late as possible, ie.  after any option assignments from the
command-line or from other commands have been done.  Thus, this is the place
to code option dependencies: if @emph{foo} depends on @emph{bar}, then it is safe to
set @emph{foo} from @emph{bar} as long as @emph{foo} still has the same value it was
assigned in @ref{467b,,initialize_options()}.
@end deffn

@geindex run() (distutils.cmd.Command 方法)
@anchor{distutils/apiref distutils cmd Command run}@anchor{467d}
@deffn {方法} Command.run ()

A command's raison d'etre: carry out the action it exists to perform, controlled
by the options initialized in @ref{467b,,initialize_options()}, customized by other
commands, the setup script, the command-line, and config files, and finalized in
@ref{467c,,finalize_options()}.  All terminal output and filesystem interaction should
be done by @ref{467d,,run()}.
@end deffn

@geindex sub_commands (distutils.cmd.Command 属性)
@anchor{distutils/apiref distutils cmd Command sub_commands}@anchor{467f}
@deffn {属性} Command.sub_commands

@emph{sub_commands} formalizes the notion of a "family" of commands,
e.g. @code{install} as the parent with sub-commands @code{install_lib},
@code{install_headers}, etc.  The parent of a family of commands defines
@emph{sub_commands} as a class attribute; it's a list of 2-tuples @code{(command_name,
predicate)}, with @emph{command_name} a string and @emph{predicate} a function, a
string or @code{None}.  @emph{predicate} is a method of the parent command that
determines whether the corresponding command is applicable in the current
situation.  (E.g. @code{install_headers} is only applicable if we have any C
header files to install.)  If @emph{predicate} is @code{None}, that command is always
applicable.

@emph{sub_commands} is usually defined at the @emph{end} of a class, because
predicates can be methods of the class, so they must already have been
defined.  The canonical example is the @code{install} command.
@end deffn

@node distutils command --- Individual Distutils commands,distutils command bdist --- Build a binary installer,Creating a new Distutils command,API参考引用
@anchor{distutils/apiref distutils-command-individual-distutils-commands}@anchor{4680}@anchor{distutils/apiref module-distutils command}@anchor{3d}
@subsection @code{distutils.command} --- Individual Distutils commands


@geindex distutils.command (模块)

@c % \subsubsection{Individual Distutils commands}

@c % todo

@node distutils command bdist --- Build a binary installer,distutils command bdist_packager --- Abstract base class for packagers,distutils command --- Individual Distutils commands,API参考引用
@anchor{distutils/apiref distutils-command-bdist-build-a-binary-installer}@anchor{4681}@anchor{distutils/apiref module-distutils command bdist}@anchor{3e}
@subsection @code{distutils.command.bdist} --- Build a binary installer


@geindex distutils.command.bdist (模块)

@c % todo

@node distutils command bdist_packager --- Abstract base class for packagers,distutils command bdist_dumb --- Build a "dumb" installer,distutils command bdist --- Build a binary installer,API参考引用
@anchor{distutils/apiref distutils-command-bdist-packager-abstract-base-class-for-packagers}@anchor{4682}@anchor{distutils/apiref module-distutils command bdist_packager}@anchor{41}
@subsection @code{distutils.command.bdist_packager} --- Abstract base class for packagers


@geindex distutils.command.bdist_packager (模块)

@c % todo

@node distutils command bdist_dumb --- Build a "dumb" installer,distutils command bdist_msi --- Build a Microsoft Installer binary package,distutils command bdist_packager --- Abstract base class for packagers,API参考引用
@anchor{distutils/apiref distutils-command-bdist-dumb-build-a-dumb-installer}@anchor{4683}@anchor{distutils/apiref module-distutils command bdist_dumb}@anchor{3f}
@subsection @code{distutils.command.bdist_dumb} --- Build a "dumb" installer


@geindex distutils.command.bdist_dumb (模块)

@c % todo

@node distutils command bdist_msi --- Build a Microsoft Installer binary package,distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,distutils command bdist_dumb --- Build a "dumb" installer,API参考引用
@anchor{distutils/apiref distutils-command-bdist-msi-build-a-microsoft-installer-binary-package}@anchor{4684}@anchor{distutils/apiref module-distutils command bdist_msi}@anchor{40}
@subsection @code{distutils.command.bdist_msi} --- Build a Microsoft Installer binary package


@geindex distutils.command.bdist_msi (模块)

@geindex bdist_msi (distutils.command.bdist_msi 中的类)
@anchor{distutils/apiref distutils command bdist_msi bdist_msi}@anchor{4685}
@deffn {类} distutils.command.bdist_msi.bdist_msi
@end deffn


3.9 版后已移除: Use bdist_wheel (wheel packages) instead.

Builds a Windows Installer@footnote{https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx} (.msi) binary package.

In most cases, the @code{bdist_msi} installer is a better choice than the
@code{bdist_wininst} installer, because it provides better support for
Win64 platforms, allows administrators to perform non-interactive
installations, and allows installation through group policies.


@node distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,distutils command bdist_wininst --- Build a Windows installer,distutils command bdist_msi --- Build a Microsoft Installer binary package,API参考引用
@anchor{distutils/apiref distutils-command-bdist-rpm-build-a-binary-distribution-as-a-redhat-rpm-and-srpm}@anchor{4686}@anchor{distutils/apiref module-distutils command bdist_rpm}@anchor{42}
@subsection @code{distutils.command.bdist_rpm} --- Build a binary distribution as a Redhat RPM and SRPM


@geindex distutils.command.bdist_rpm (模块)

@c % todo

@node distutils command bdist_wininst --- Build a Windows installer,distutils command sdist --- Build a source distribution,distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,API参考引用
@anchor{distutils/apiref distutils-command-bdist-wininst-build-a-windows-installer}@anchor{4687}@anchor{distutils/apiref module-distutils command bdist_wininst}@anchor{43}
@subsection @code{distutils.command.bdist_wininst} --- Build a Windows installer


@geindex distutils.command.bdist_wininst (模块)


3.8 版后已移除: Use bdist_wheel (wheel packages) instead.


@c % todo

@node distutils command sdist --- Build a source distribution,distutils command build --- Build all files of a package,distutils command bdist_wininst --- Build a Windows installer,API参考引用
@anchor{distutils/apiref distutils-command-sdist-build-a-source-distribution}@anchor{4688}@anchor{distutils/apiref module-distutils command sdist}@anchor{52}
@subsection @code{distutils.command.sdist} --- Build a source distribution


@geindex distutils.command.sdist (模块)

@c % todo

@node distutils command build --- Build all files of a package,distutils command build_clib --- Build any C libraries in a package,distutils command sdist --- Build a source distribution,API参考引用
@anchor{distutils/apiref distutils-command-build-build-all-files-of-a-package}@anchor{4689}@anchor{distutils/apiref module-distutils command build}@anchor{44}
@subsection @code{distutils.command.build} --- Build all files of a package


@geindex distutils.command.build (模块)

@c % todo

@node distutils command build_clib --- Build any C libraries in a package,distutils command build_ext --- Build any extensions in a package,distutils command build --- Build all files of a package,API参考引用
@anchor{distutils/apiref distutils-command-build-clib-build-any-c-libraries-in-a-package}@anchor{468a}@anchor{distutils/apiref module-distutils command build_clib}@anchor{45}
@subsection @code{distutils.command.build_clib} --- Build any C libraries in a package


@geindex distutils.command.build_clib (模块)

@c % todo

@node distutils command build_ext --- Build any extensions in a package,distutils command build_py --- Build the py/ pyc files of a package,distutils command build_clib --- Build any C libraries in a package,API参考引用
@anchor{distutils/apiref distutils-command-build-ext-build-any-extensions-in-a-package}@anchor{468b}@anchor{distutils/apiref module-distutils command build_ext}@anchor{46}
@subsection @code{distutils.command.build_ext} --- Build any extensions in a package


@geindex distutils.command.build_ext (模块)

@c % todo

@node distutils command build_py --- Build the py/ pyc files of a package,distutils command build_scripts --- Build the scripts of a package,distutils command build_ext --- Build any extensions in a package,API参考引用
@anchor{distutils/apiref distutils-command-build-py-build-the-py-pyc-files-of-a-package}@anchor{468c}@anchor{distutils/apiref module-distutils command build_py}@anchor{47}
@subsection @code{distutils.command.build_py} --- Build the .py/.pyc files of a package


@geindex distutils.command.build_py (模块)

@geindex build_py (distutils.command.build_py 中的类)
@anchor{distutils/apiref distutils command build_py build_py}@anchor{468d}
@deffn {类} distutils.command.build_py.build_py
@end deffn

@geindex build_py_2to3 (distutils.command.build_py 中的类)
@anchor{distutils/apiref distutils command build_py build_py_2to3}@anchor{468e}
@deffn {类} distutils.command.build_py.build_py_2to3

Alternative implementation of build_py which also runs the
2to3 conversion library on each .py file that is going to be
installed. To use this in a setup.py file for a distribution
that is designed to run with both Python 2.x and 3.x, add:

@example
try:
    from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
    from distutils.command.build_py import build_py
@end example

to your setup.py, and later:

@example
cmdclass = @{'build_py': build_py@}
@end example

to the invocation of setup().
@end deffn

@node distutils command build_scripts --- Build the scripts of a package,distutils command clean --- Clean a package build area,distutils command build_py --- Build the py/ pyc files of a package,API参考引用
@anchor{distutils/apiref distutils-command-build-scripts-build-the-scripts-of-a-package}@anchor{468f}@anchor{distutils/apiref module-distutils command build_scripts}@anchor{48}
@subsection @code{distutils.command.build_scripts} --- Build the scripts of a package


@geindex distutils.command.build_scripts (模块)

@c % todo

@node distutils command clean --- Clean a package build area,distutils command config --- Perform package configuration,distutils command build_scripts --- Build the scripts of a package,API参考引用
@anchor{distutils/apiref distutils-command-clean-clean-a-package-build-area}@anchor{4690}@anchor{distutils/apiref module-distutils command clean}@anchor{4a}
@subsection @code{distutils.command.clean} --- Clean a package build area


@geindex distutils.command.clean (模块)

This command removes the temporary files created by @code{build}
and its subcommands, like intermediary compiled object files.  With
the @code{--all} option, the complete build directory will be removed.

Extension modules built @ref{45d1,,in place}
will not be cleaned, as they are not in the build directory.

@node distutils command config --- Perform package configuration,distutils command install --- Install a package,distutils command clean --- Clean a package build area,API参考引用
@anchor{distutils/apiref distutils-command-config-perform-package-configuration}@anchor{4691}@anchor{distutils/apiref module-distutils command config}@anchor{4b}
@subsection @code{distutils.command.config} --- Perform package configuration


@geindex distutils.command.config (模块)

@c % todo

@node distutils command install --- Install a package,distutils command install_data --- Install data files from a package,distutils command config --- Perform package configuration,API参考引用
@anchor{distutils/apiref distutils-command-install-install-a-package}@anchor{4692}@anchor{distutils/apiref module-distutils command install}@anchor{4c}
@subsection @code{distutils.command.install} --- Install a package


@geindex distutils.command.install (模块)

@c % todo

@node distutils command install_data --- Install data files from a package,distutils command install_headers --- Install C/C++ header files from a package,distutils command install --- Install a package,API参考引用
@anchor{distutils/apiref distutils-command-install-data-install-data-files-from-a-package}@anchor{4693}@anchor{distutils/apiref module-distutils command install_data}@anchor{4d}
@subsection @code{distutils.command.install_data} --- Install data files from a package


@geindex distutils.command.install_data (模块)

@c % todo

@node distutils command install_headers --- Install C/C++ header files from a package,distutils command install_lib --- Install library files from a package,distutils command install_data --- Install data files from a package,API参考引用
@anchor{distutils/apiref distutils-command-install-headers-install-c-c-header-files-from-a-package}@anchor{4694}@anchor{distutils/apiref module-distutils command install_headers}@anchor{4e}
@subsection @code{distutils.command.install_headers} --- Install C/C++ header files from a package


@geindex distutils.command.install_headers (模块)

@c % todo

@node distutils command install_lib --- Install library files from a package,distutils command install_scripts --- Install script files from a package,distutils command install_headers --- Install C/C++ header files from a package,API参考引用
@anchor{distutils/apiref distutils-command-install-lib-install-library-files-from-a-package}@anchor{4695}@anchor{distutils/apiref module-distutils command install_lib}@anchor{4f}
@subsection @code{distutils.command.install_lib} --- Install library files from a package


@geindex distutils.command.install_lib (模块)

@c % todo

@node distutils command install_scripts --- Install script files from a package,distutils command register --- Register a module with the Python Package Index,distutils command install_lib --- Install library files from a package,API参考引用
@anchor{distutils/apiref distutils-command-install-scripts-install-script-files-from-a-package}@anchor{4696}@anchor{distutils/apiref module-distutils command install_scripts}@anchor{50}
@subsection @code{distutils.command.install_scripts} --- Install script files from a package


@geindex distutils.command.install_scripts (模块)

@c % todo

@node distutils command register --- Register a module with the Python Package Index,distutils command check --- Check the meta-data of a package,distutils command install_scripts --- Install script files from a package,API参考引用
@anchor{distutils/apiref distutils-command-register-register-a-module-with-the-python-package-index}@anchor{4697}@anchor{distutils/apiref module-distutils command register}@anchor{51}
@subsection @code{distutils.command.register} --- Register a module with the Python Package Index


@geindex distutils.command.register (模块)

The @code{register} command registers the package with the Python Package  Index.
This is described in more detail in 
@geindex Python 提高建议; PEP 301
PEP 301@footnote{https://www.python.org/dev/peps/pep-0301}.

@c % todo

@node distutils command check --- Check the meta-data of a package,,distutils command register --- Register a module with the Python Package Index,API参考引用
@anchor{distutils/apiref distutils-command-check-check-the-meta-data-of-a-package}@anchor{4698}@anchor{distutils/apiref module-distutils command check}@anchor{49}
@subsection @code{distutils.command.check} --- Check the meta-data of a package


@geindex distutils.command.check (模块)

The @code{check} command performs some tests on the meta-data of a package.
For example, it verifies that all required meta-data are provided as
the arguments passed to the @code{setup()} function.

@c % todo

@node 安装Python模块（旧版）,Python 模块索引,分发 Python 模块（遗留版本）,Top
@anchor{install/index doc}@anchor{4699}@anchor{install/index install-index}@anchor{8ee}@anchor{install/index installing-python-modules-legacy-version}@anchor{469a}
@chapter 安装Python模块（旧版）


@*作者: 
Greg Ward


@c TODO: Fill in XXX comments


@subsubheading 参见



@table @asis

@item @ref{8ec,,安装 Python 模块}

最新的模块安装文档。对于常规Python使用，你几乎肯定像使用该文档而非这个。
@end table


@cartouche
@quotation 注解 
这篇文档只有在 @indicateurl{https://setuptools.readthedocs.io/en/latest/setuptools.html} 上的 @code{setuptools} 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。
@end quotation
@end cartouche

@cartouche
@quotation 注解 
本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分@footnote{https://packaging.python.org/guides/tool-recommendations/} 。
@end quotation
@end cartouche

@menu
* 概述: 概述<20>. 
* 标准构建及安装:: 
* Alternate Installation:: 
* 自定义安装:: 
* Distutils 配置文件Configuration Files:: 
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks. 

@end menu

@node 概述<20>,标准构建及安装,,安装Python模块（旧版）
@anchor{install/index inst-intro}@anchor{469b}@anchor{install/index introduction}@anchor{469c}
@section 概述


在Python 2.0中，@code{distutils} API 首次被添加到标准库中。这向Linux发行版维护者提供了一个将Python项目转换为发行版软件包的标准方法，以及向系统管理员们提供了直接将这些软件包安装到目标系统的标准方法。

自从很多年前 Python 2.0 发布，将构建系统和包安装器与语言运行时的释放循环紧密连接在一起产生了很多问题。现在推荐做法是在项目中使用 @code{pip} 包安装器和 @code{setuptools} 构建系统，而不是直接使用 @code{distutils}。

请参阅 @ref{8ec,,安装 Python 模块} 和 @ref{8ed,,分发 Python 模块} 了解更多细节。

这个旧文档将被保留，至到我们相信 @code{setuptools} 覆盖了所有内容。

@menu
* 基于分布式系统的源代码分发:: 

@end menu

@node 基于分布式系统的源代码分发,,,概述<20>
@anchor{install/index distutils-based-source-distributions}@anchor{469d}@anchor{install/index inst-new-standard}@anchor{469e}
@subsection 基于分布式系统的源代码分发


If you download a module source distribution, you can tell pretty quickly if it
was packaged and distributed in the standard way, i.e. using the Distutils.
First, the distribution's name and version number will be featured prominently
in the name of the downloaded archive, e.g. @code{foo-1.0.tar.gz} or
@code{widget-0.9.7.zip}.  Next, the archive will unpack into a similarly-named
directory: @code{foo-1.0} or @code{widget-0.9.7}.  Additionally, the
distribution will contain a setup script @code{setup.py}, and a file named
@code{README.txt} or possibly just @code{README}, which should explain that
building and installing the module distribution is a simple matter of running
one command from a terminal:

@example
python setup.py install
@end example

Windows 用户应该使用命令提示符来运行命令(Start ‣ Accessories):

@example
setup.py install
@end example

如果这些事情都属实，那么您已经了解了如何构建和安装您已经下载的模块：只需运行如上的命令。除非您需要以非常规方式安装或者定制构建过程，您其实不需要本文档。更进一步说，以上命令就是您可以从文档中获得的全部。

@node 标准构建及安装,Alternate Installation,概述<20>,安装Python模块（旧版）
@anchor{install/index inst-standard-install}@anchor{469f}@anchor{install/index standard-build-and-install}@anchor{46a0}
@section 标准构建及安装


正如 @ref{469e,,基于分布式系统的源代码分发} 中所描述的那样，通过 Distutils 构建和安装发行的模块常常只需要在终端执行一个简单的命令。

@example
python setup.py install
@end example

@menu
* 平台差异:: 
* 拆分任务:: 
* How building works:: 
* How installation works:: 

@end menu

@node 平台差异,拆分任务,,标准构建及安装
@anchor{install/index inst-platform-variations}@anchor{46a1}@anchor{install/index platform-variations}@anchor{46a2}
@subsection 平台差异


您应当总是在分发文件的根目录处运行设置的命令，比如，模块分发的源代码最高的子目录。例如，如果您刚刚在 Unix 操作系统上下载了一个模块分发的源代码，您需要做的事：

@example
gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
cd foo-1.0
python setup.py install
@end example

On Windows, you'd probably download @code{foo-1.0.zip}.  If you downloaded the
archive file to @code{C:\Temp}, then it would unpack into
@code{C:\Temp\foo-1.0}; you can use either an archive manipulator with a
graphical user interface (such as WinZip) or a command-line tool (such as
@code{unzip} or @code{pkunzip}) to unpack the archive.  Then, open a
command prompt window and run:

@example
cd c:\Temp\foo-1.0
python setup.py install
@end example

@node 拆分任务,How building works,平台差异,标准构建及安装
@anchor{install/index inst-splitting-up}@anchor{46a3}@anchor{install/index splitting-the-job-up}@anchor{46a4}
@subsection 拆分任务


Running @code{setup.py install} builds and installs all modules in one run.  If you
prefer to work incrementally---especially useful if you want to customize the
build process, or if things are going wrong---you can use the setup script to do
one thing at a time.  This is particularly helpful when the build and install
will be done by different users---for example, you might want to build a module
distribution and hand it off to a system administrator for installation (or do
it yourself, with super-user privileges).

For example, you can build everything in one step, and then install everything
in a second step, by invoking the setup script twice:

@example
python setup.py build
python setup.py install
@end example

If you do this, you will notice that running the @code{install} command
first runs the @code{build} command, which---in this case---quickly notices
that it has nothing to do, since everything in the @code{build} directory is
up-to-date.

You may not need this ability to break things down often if all you do is
install modules downloaded off the 'net, but it's very handy for more advanced
tasks.  If you get into distributing your own Python modules and extensions,
you'll run lots of individual Distutils commands on their own.

@node How building works,How installation works,拆分任务,标准构建及安装
@anchor{install/index how-building-works}@anchor{46a5}@anchor{install/index inst-how-build-works}@anchor{46a6}
@subsection How building works


As implied above, the @code{build} command is responsible for putting the
files to install into a @emph{build directory}.  By default, this is @code{build}
under the distribution root; if you're excessively concerned with speed, or want
to keep the source tree pristine, you can change the build directory with the
@code{--build-base} option. For example:

@example
python setup.py build --build-base=/path/to/pybuild/foo-1.0
@end example

(Or you could do this permanently with a directive in your system or personal
Distutils configuration file; see section @ref{46a7,,Distutils 配置文件Configuration Files}.)  Normally, this
isn't necessary.

The default layout for the build tree is as follows:

@example
--- build/ --- lib/
or
--- build/ --- lib.<plat>/
               temp.<plat>/
@end example

where @code{<plat>} expands to a brief description of the current OS/hardware
platform and Python version.  The first form, with just a @code{lib} directory,
is used for "pure module distributions"---that is, module distributions that
include only pure Python modules.  If a module distribution contains any
extensions (modules written in C/C++), then the second form, with two @code{<plat>}
directories, is used.  In that case, the @code{temp.@emph{plat}} directory holds
temporary files generated by the compile/link process that don't actually get
installed.  In either case, the @code{lib} (or @code{lib.@emph{plat}}) directory
contains all Python modules (pure Python and extensions) that will be installed.

In the future, more directories will be added to handle Python scripts,
documentation, binary executables, and whatever else is needed to handle the job
of installing Python modules and applications.

@node How installation works,,How building works,标准构建及安装
@anchor{install/index how-installation-works}@anchor{46a8}@anchor{install/index inst-how-install-works}@anchor{46a9}
@subsection How installation works


After the @code{build} command runs (whether you run it explicitly, or the
@code{install} command does it for you), the work of the @code{install}
command is relatively simple: all it has to do is copy everything under
@code{build/lib} (or @code{build/lib.@emph{plat}}) to your chosen installation
directory.

If you don't choose an installation directory---i.e., if you just run @code{setup.py
install}---then the @code{install} command installs to the standard
location for third-party Python modules.  This location varies by platform and
by how you built/installed Python itself.  On Unix (and macOS, which is also
Unix-based), it also depends on whether the module distribution being installed
is pure Python or contains extensions ("non-pure"):


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

平台

@tab

标准安装位置

@tab

默认值

@tab

注释

@item

（单一）Unix

@tab

@code{@emph{prefix}/lib/python@emph{X.Y}/site-packages}

@tab

@code{/usr/local/lib/python@emph{X.Y}/site-packages}

@tab

(1)

@item

（类）Unix

@tab

@code{@emph{exec-prefix}/lib/python@emph{X.Y}/site-packages}

@tab

@code{/usr/local/lib/python@emph{X.Y}/site-packages}

@tab

(1)

@item

Windows

@tab

@code{@emph{prefix}\Lib\site-packages}

@tab

@code{C:\Python@emph{XY}\Lib\site-packages}

@tab

(2)

@end multitable


注释:


@enumerate 

@item 
Most Linux distributions include Python as a standard part of the system, so
@code{@emph{prefix}} and @code{@emph{exec-prefix}} are usually both @code{/usr} on
Linux.  If you build Python yourself on Linux (or any Unix-like system), the
default @code{@emph{prefix}} and @code{@emph{exec-prefix}} are @code{/usr/local}.

@item 
The default installation directory on Windows was @code{C:\Program
Files\Python} under Python 1.6a1, 1.5.2, and earlier.
@end enumerate

@code{@emph{prefix}} and @code{@emph{exec-prefix}} stand for the directories that Python
is installed to, and where it finds its libraries at run-time.  They are always
the same under Windows, and very often the same under Unix and macOS.  You
can find out what your Python installation uses for @code{@emph{prefix}} and
@code{@emph{exec-prefix}} by running Python in interactive mode and typing a few
simple commands. Under Unix, just type @code{python} at the shell prompt.  Under
Windows, choose Start ‣ Programs ‣ Python X.Y ‣
Python (command line).   Once the interpreter is started, you type Python code
at the prompt.  For example, on my Linux system, I type the three Python
statements shown below, and get the output as shown, to find out my
@code{@emph{prefix}} and @code{@emph{exec-prefix}}:

@example
Python 2.4 (#26, Aug  7 2004, 17:19:02)
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.prefix
'/usr'
>>> sys.exec_prefix
'/usr'
@end example

A few other placeholders are used in this document: @code{@emph{X.Y}} stands for the
version of Python, for example @code{3.2}; @code{@emph{abiflags}} will be replaced by
the value of @ref{395,,sys.abiflags} or the empty string for platforms which don't
define ABI flags; @code{@emph{distname}} will be replaced by the name of the module
distribution being installed.  Dots and capitalization are important in the
paths; for example, a value that uses @code{python3.2} on UNIX will typically use
@code{Python32} on Windows.

If you don't want to install modules to the standard location, or if you don't
have permission to write there, then you need to read about alternate
installations in section @ref{46aa,,Alternate Installation}.  If you want to customize your
installation directories more heavily, see section @ref{46ab,,自定义安装} on
custom installations.

@node Alternate Installation,自定义安装,标准构建及安装,安装Python模块（旧版）
@anchor{install/index alternate-installation}@anchor{46ac}@anchor{install/index inst-alt-install}@anchor{46aa}
@section Alternate Installation


Often, it is necessary or desirable to install modules to a location other than
the standard location for third-party Python modules.  For example, on a Unix
system you might not have permission to write to the standard third-party module
directory.  Or you might wish to try out a module before making it a standard
part of your local Python installation.  This is especially true when upgrading
a distribution already present: you want to make sure your existing base of
scripts still works with the new version before actually upgrading.

The Distutils @code{install} command is designed to make installing module
distributions to an alternate location simple and painless.  The basic idea is
that you supply a base directory for the installation, and the
@code{install} command picks a set of directories (called an @emph{installation
scheme}) under this base directory in which to install files.  The details
differ across platforms, so read whichever of the following sections applies to
you.

Note that the various alternate installation schemes are mutually exclusive: you
can pass @code{--user}, or @code{--home}, or @code{--prefix} and @code{--exec-prefix}, or
@code{--install-base} and @code{--install-platbase}, but you can't mix from these
groups.

@menu
* Alternate installation; the user scheme: Alternate installation the user scheme. 
* Alternate installation; the home scheme: Alternate installation the home scheme. 
* Alternate installation; Unix (the prefix scheme): Alternate installation Unix the prefix scheme. 
* Alternate installation; Windows (the prefix scheme): Alternate installation Windows the prefix scheme. 

@end menu

@node Alternate installation the user scheme,Alternate installation the home scheme,,Alternate Installation
@anchor{install/index alternate-installation-the-user-scheme}@anchor{46ad}@anchor{install/index inst-alt-install-user}@anchor{14ba}
@subsection Alternate installation: the user scheme


This scheme is designed to be the most convenient solution for users that don't
have write permission to the global site-packages directory or don't want to
install into it.  It is enabled with a simple option:

@example
python setup.py install --user
@end example

Files will be installed into subdirectories of @ref{14b9,,site.USER_BASE} (written
as @code{@emph{userbase}} hereafter).  This scheme installs pure Python modules and
extension modules in the same location (also known as @ref{14aa,,site.USER_SITE}).
Here are the values for UNIX, including macOS:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

安装目录

@item

模块

@tab

@code{@emph{userbase}/lib/python@emph{X.Y}/site-packages}

@item

脚本

@tab

@code{@emph{userbase}/bin}

@item

数据

@tab

@code{@emph{userbase}}

@item

C 头文件

@tab

@code{@emph{userbase}/include/python@emph{X.Y}@emph{abiflags}/@emph{distname}}

@end multitable


以下是Windows上使用的值：


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

安装目录

@item

模块

@tab

@code{@emph{userbase}\Python@emph{XY}\site-packages}

@item

脚本

@tab

@code{@emph{userbase}\Python@emph{XY}\Scripts}

@item

数据

@tab

@code{@emph{userbase}}

@item

C 头文件

@tab

@code{@emph{userbase}\Python@emph{XY}\Include@{distname@}}

@end multitable


The advantage of using this scheme compared to the other ones described below is
that the user site-packages directory is under normal conditions always included
in @ref{262,,sys.path} (see @ref{eb,,site} for more information), which means that
there is no additional step to perform after running the @code{setup.py} script
to finalize the installation.

The @code{build_ext} command also has a @code{--user} option to add
@code{@emph{userbase}/include} to the compiler search path for header files and
@code{@emph{userbase}/lib} to the compiler search path for libraries as well as to
the runtime search path for shared C libraries (rpath).

@node Alternate installation the home scheme,Alternate installation Unix the prefix scheme,Alternate installation the user scheme,Alternate Installation
@anchor{install/index alternate-installation-the-home-scheme}@anchor{46ae}@anchor{install/index inst-alt-install-home}@anchor{46af}
@subsection Alternate installation: the home scheme


The idea behind the "home scheme" is that you build and maintain a personal
stash of Python modules.  This scheme's name is derived from the idea of a
"home" directory on Unix, since it's not unusual for a Unix user to make their
home directory have a layout similar to @code{/usr/} or @code{/usr/local/}.
This scheme can be used by anyone, regardless of the operating system they
are installing for.

Installing a new module distribution is as simple as

@example
python setup.py install --home=<dir>
@end example

where you can supply any directory you like for the @code{--home} option.  On
Unix, lazy typists can just type a tilde (@code{~}); the @code{install} command
will expand this to your home directory:

@example
python setup.py install --home=~
@end example

To make Python find the distributions installed with this scheme, you may have
to @ref{46b0,,modify Python's search path} or edit
@code{sitecustomize} (see @ref{eb,,site}) to call @ref{3791,,site.addsitedir()} or edit
@ref{262,,sys.path}.

The @code{--home} option defines the installation base directory.  Files are
installed to the following directories under the installation base as follows:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

安装目录

@item

模块

@tab

@code{@emph{home}/lib/python}

@item

脚本

@tab

@code{@emph{home}/bin}

@item

数据

@tab

@code{@emph{home}}

@item

C 头文件

@tab

@code{@emph{home}/include/python/@emph{distname}}

@end multitable


（如果你是使用 Windows 请将斜杠替换为反斜杠。）

@node Alternate installation Unix the prefix scheme,Alternate installation Windows the prefix scheme,Alternate installation the home scheme,Alternate Installation
@anchor{install/index alternate-installation-unix-the-prefix-scheme}@anchor{46b1}@anchor{install/index inst-alt-install-prefix-unix}@anchor{46b2}
@subsection Alternate installation: Unix (the prefix scheme)


The "prefix scheme" is useful when you wish to use one Python installation to
perform the build/install (i.e., to run the setup script), but install modules
into the third-party module directory of a different Python installation (or
something that looks like a different Python installation).  If this sounds a
trifle unusual, it is---that's why the user and home schemes come before.  However,
there are at least two known cases where the prefix scheme will be useful.

First, consider that many Linux distributions put Python in @code{/usr}, rather
than the more traditional @code{/usr/local}.  This is entirely appropriate,
since in those cases Python is part of "the system" rather than a local add-on.
However, if you are installing Python modules from source, you probably want
them to go in @code{/usr/local/lib/python2.@emph{X}} rather than
@code{/usr/lib/python2.@emph{X}}.  This can be done with

@example
/usr/bin/python setup.py install --prefix=/usr/local
@end example

Another possibility is a network filesystem where the name used to write to a
remote directory is different from the name used to read it: for example, the
Python interpreter accessed as @code{/usr/local/bin/python} might search for
modules in @code{/usr/local/lib/python2.@emph{X}}, but those modules would have to
be installed to, say, @code{/mnt/@emph{@@server}/export/lib/python2.@emph{X}}.  This could
be done with

@example
/usr/local/bin/python setup.py install --prefix=/mnt/@@server/export
@end example

In either case, the @code{--prefix} option defines the installation base, and
the @code{--exec-prefix} option defines the platform-specific installation
base, which is used for platform-specific files.  (Currently, this just means
non-pure module distributions, but could be expanded to C libraries, binary
executables, etc.)  If @code{--exec-prefix} is not supplied, it defaults to
@code{--prefix}.  Files are installed as follows:


@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

安装目录

@item

Python 模块

@tab

@code{@emph{prefix}/lib/python@emph{X.Y}/site-packages}

@item

扩展模块

@tab

@code{@emph{exec-prefix}/lib/python@emph{X.Y}/site-packages}

@item

脚本

@tab

@code{@emph{prefix}/bin}

@item

数据

@tab

@code{@emph{prefix}}

@item

C 头文件

@tab

@code{@emph{prefix}/include/python@emph{X.Y}@emph{abiflags}/@emph{distname}}

@end multitable


There is no requirement that @code{--prefix} or @code{--exec-prefix}
actually point to an alternate Python installation; if the directories listed
above do not already exist, they are created at installation time.

Incidentally, the real reason the prefix scheme is important is simply that a
standard Unix installation uses the prefix scheme, but with @code{--prefix}
and @code{--exec-prefix} supplied by Python itself as @code{sys.prefix} and
@code{sys.exec_prefix}.  Thus, you might think you'll never use the prefix scheme,
but every time you run @code{python setup.py install} without any other options,
you're using it.

Note that installing extensions to an alternate Python installation has no
effect on how those extensions are built: in particular, the Python header files
(@code{Python.h} and friends) installed with the Python interpreter used to run
the setup script will be used in compiling extensions.  It is your
responsibility to ensure that the interpreter used to run extensions installed
in this way is compatible with the interpreter used to build them.  The best way
to do this is to ensure that the two interpreters are the same version of Python
(possibly different builds, or possibly copies of the same build).  (Of course,
if your @code{--prefix} and @code{--exec-prefix} don't even point to an
alternate Python installation, this is immaterial.)

@node Alternate installation Windows the prefix scheme,,Alternate installation Unix the prefix scheme,Alternate Installation
@anchor{install/index alternate-installation-windows-the-prefix-scheme}@anchor{46b3}@anchor{install/index inst-alt-install-prefix-windows}@anchor{46b4}
@subsection Alternate installation: Windows (the prefix scheme)


Windows has no concept of a user's home directory, and since the standard Python
installation under Windows is simpler than under Unix, the @code{--prefix}
option has traditionally been used to install additional packages in separate
locations on Windows.

@example
python setup.py install --prefix="\Temp\Python"
@end example

to install modules to the @code{\Temp\Python} directory on the current drive.

The installation base is defined by the @code{--prefix} option; the
@code{--exec-prefix} option is not supported under Windows, which means that
pure Python modules and extension modules are installed into the same location.
Files are installed as follows:


@multitable {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

安装目录

@item

模块

@tab

@code{@emph{prefix}\Lib\site-packages}

@item

脚本

@tab

@code{@emph{prefix}\Scripts}

@item

数据

@tab

@code{@emph{prefix}}

@item

C 头文件

@tab

@code{@emph{prefix}\Include@{distname@}}

@end multitable


@node 自定义安装,Distutils 配置文件Configuration Files,Alternate Installation,安装Python模块（旧版）
@anchor{install/index custom-installation}@anchor{46b5}@anchor{install/index inst-custom-install}@anchor{46ab}
@section 自定义安装


Sometimes, the alternate installation schemes described in section
@ref{46aa,,Alternate Installation} just don't do what you want.  You might want to tweak just
one or two directories while keeping everything under the same base directory,
or you might want to completely redefine the installation scheme.  In either
case, you're creating a @emph{custom installation scheme}.

To create a custom installation scheme, you start with one of the alternate
schemes and override some of the installation directories used for the various
types of files, using these options:


@multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} 
@headitem

文件类型

@tab

覆盖选项

@item

Python 模块

@tab

@code{--install-purelib}

@item

扩展模块

@tab

@code{--install-platlib}

@item

所有模块

@tab

@code{--install-lib}

@item

脚本

@tab

@code{--install-scripts}

@item

数据

@tab

@code{--install-data}

@item

C 头文件

@tab

@code{--install-headers}

@end multitable


These override options can be relative, absolute,
or explicitly defined in terms of one of the installation base directories.
(There are two installation base directories, and they are normally the
same---they only differ when you use the Unix "prefix scheme" and supply
different @code{--prefix} and @code{--exec-prefix} options; using @code{--install-lib}
will override values computed or given for @code{--install-purelib} and
@code{--install-platlib}, and is recommended for schemes that don't make a
difference between Python and extension modules.)

For example, say you're installing a module distribution to your home directory
under Unix---but you want scripts to go in @code{~/scripts} rather than
@code{~/bin}. As you might expect, you can override this directory with the
@code{--install-scripts} option; in this case, it makes most sense to supply
a relative path, which will be interpreted relative to the installation base
directory (your home directory, in this case):

@example
python setup.py install --home=~ --install-scripts=scripts
@end example

Another Unix example: suppose your Python installation was built and installed
with a prefix of @code{/usr/local/python}, so under a standard  installation
scripts will wind up in @code{/usr/local/python/bin}.  If you want them in
@code{/usr/local/bin} instead, you would supply this absolute directory for the
@code{--install-scripts} option:

@example
python setup.py install --install-scripts=/usr/local/bin
@end example

(This performs an installation using the "prefix scheme", where the prefix is
whatever your Python interpreter was installed with--- @code{/usr/local/python}
in this case.)

If you maintain Python on Windows, you might want third-party modules to live in
a subdirectory of @code{@emph{prefix}}, rather than right in @code{@emph{prefix}}
itself.  This is almost as easy as customizing the script installation
directory---you just have to remember that there are two types of modules
to worry about, Python and extension modules, which can conveniently be both
controlled by one option:

@example
python setup.py install --install-lib=Site
@end example

The specified installation directory is relative to @code{@emph{prefix}}.  Of
course, you also have to ensure that this directory is in Python's module
search path, such as by putting a @code{.pth} file in a site directory (see
@ref{eb,,site}).  See section @ref{46b0,,修改 Python 的搜索路径} to find out how to modify
Python's search path.

If you want to define an entire installation scheme, you just have to supply all
of the installation directory options.  The recommended way to do this is to
supply relative paths; for example, if you want to maintain all Python
module-related files under @code{python} in your home directory, and you want a
separate directory for each platform that you use your home directory from, you
might define the following installation scheme:

@example
python setup.py install --home=~ \
                        --install-purelib=python/lib \
                        --install-platlib=python/lib.$PLAT \
                        --install-scripts=python/scripts
                        --install-data=python/data
@end example

或者，等价于

@example
python setup.py install --home=~/python \
                        --install-purelib=lib \
                        --install-platlib='lib.$PLAT' \
                        --install-scripts=scripts
                        --install-data=data
@end example

@code{$PLAT} is not (necessarily) an environment variable---it will be expanded by
the Distutils as it parses your command line options, just as it does when
parsing your configuration file(s).

Obviously, specifying the entire installation scheme every time you install a
new module distribution would be very tedious.  Thus, you can put these options
into your Distutils config file (see section @ref{46a7,,Distutils 配置文件Configuration Files}):

@example
[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data
@end example

或者，等价于，

@example
[install]
install-base=$HOME/python
install-purelib=lib
install-platlib=lib.$PLAT
install-scripts=scripts
install-data=data
@end example

Note that these two are @emph{not} equivalent if you supply a different installation
base directory when you run the setup script.  For example,

@example
python setup.py install --install-base=/tmp
@end example

would install pure modules to @code{/tmp/python/lib} in the first case, and
to @code{/tmp/lib} in the second case.  (For the second case, you probably
want to supply an installation base of @code{/tmp/python}.)

You probably noticed the use of @code{$HOME} and @code{$PLAT} in the sample
configuration file input.  These are Distutils configuration variables, which
bear a strong resemblance to environment variables. In fact, you can use
environment variables in config files on platforms that have such a notion but
the Distutils additionally define a few extra variables that may not be in your
environment, such as @code{$PLAT}.  (And of course, on systems that don't have
environment variables, such as Mac OS 9, the configuration variables supplied by
the Distutils are the only ones you can use.) See section @ref{46a7,,Distutils 配置文件Configuration Files}
for details.

@cartouche
@quotation 注解 
When a @ref{3685,,virtual environment} is activated, any options
that change the installation path will be ignored from all distutils configuration
files to prevent inadvertently installing projects outside of the virtual
environment.
@end quotation
@end cartouche

@c XXX need some Windows examples---when would custom installation schemes be
@c needed on those platforms?

@c XXX Move this to Doc/using

@menu
* 修改 Python 的搜索路径:: 

@end menu

@node 修改 Python 的搜索路径,,,自定义安装
@anchor{install/index inst-search-path}@anchor{46b0}@anchor{install/index modifying-python-s-search-path}@anchor{46b6}
@subsection 修改 Python 的搜索路径


When the Python interpreter executes an @ref{cef,,import} statement, it searches
for both Python code and extension modules along a search path.  A default value
for the path is configured into the Python binary when the interpreter is built.
You can determine the path by importing the @ref{fd,,sys} module and printing the
value of @code{sys.path}.

@example
$ python
Python 2.2 (#11, Oct  3 2002, 13:31:27)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['@w{'}, '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
 '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
 '/usr/local/lib/python2.3/site-packages']
>>>
@end example

The null string in @code{sys.path} represents the current working directory.

The expected convention for locally installed packages is to put them in the
@code{@emph{...}/site-packages/} directory, but you may want to install Python
modules into some arbitrary directory.  For example, your site may have a
convention of keeping all software related to the web server under @code{/www}.
Add-on Python modules might then belong in @code{/www/python}, and in order to
import them, this directory must be added to @code{sys.path}.  There are several
different ways to add the directory.

The most convenient way is to add a path configuration file to a directory
that's already on Python's path, usually to the @code{.../site-packages/}
directory.  Path configuration files have an extension of @code{.pth}, and each
line must contain a single path that will be appended to @code{sys.path}.  (Because
the new paths are appended to @code{sys.path}, modules in the added directories
will not override standard modules.  This means you can't use this mechanism for
installing fixed versions of standard modules.)

Paths can be absolute or relative, in which case they're relative to the
directory containing the @code{.pth} file.  See the documentation of
the @ref{eb,,site} module for more information.

A slightly less convenient way is to edit the @code{site.py} file in Python's
standard library, and modify @code{sys.path}.  @code{site.py} is automatically
imported when the Python interpreter is executed, unless the @ref{c00,,-S} switch
is supplied to suppress this behaviour.  So you could simply edit
@code{site.py} and add two lines to it:

@example
import sys
sys.path.append('/www/python/')
@end example

However, if you reinstall the same major version of Python (perhaps when
upgrading from 2.2 to 2.2.2, for example) @code{site.py} will be overwritten by
the stock version.  You'd have to remember that it was modified and save a copy
before doing the installation.

There are two environment variables that can modify @code{sys.path}.
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} sets an alternate value for the prefix of the Python
installation.  For example, if 
@geindex PYTHONHOME
@geindex 环境变量; PYTHONHOME
@ref{5d9,,PYTHONHOME} is set to @code{/www/python},
the search path will be set to @code{['@w{'}, '/www/python/lib/pythonX.Y/',
'/www/python/lib/pythonX.Y/plat-linux2', ...]}.

The 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} variable can be set to a list of paths that will be
added to the beginning of @code{sys.path}.  For example, if 
@geindex PYTHONPATH
@geindex 环境变量; PYTHONPATH
@ref{a3d,,PYTHONPATH} is
set to @code{/www/python:/opt/py}, the search path will begin with
@code{['/www/python', '/opt/py']}.  (Note that directories must exist in order to
be added to @code{sys.path}; the @ref{eb,,site} module removes paths that don't
exist.)

Finally, @code{sys.path} is just a regular Python list, so any Python application
can modify it by adding or removing entries.

@node Distutils 配置文件Configuration Files,Building Extensions Tips and Tricks,自定义安装,安装Python模块（旧版）
@anchor{install/index distutils-configuration-files}@anchor{46b7}@anchor{install/index inst-config-files}@anchor{46a7}
@section Distutils 配置文件Configuration Files


As mentioned above, you can use Distutils configuration files to record personal
or site preferences for any Distutils options.  That is, any option to any
command can be stored in one of two or three (depending on your platform)
configuration files, which will be consulted before the command-line is parsed.
This means that configuration files will override default values, and the
command-line will in turn override configuration files.  Furthermore, if
multiple configuration files apply, values from "earlier" files are overridden
by "later" files.

@menu
* Location and names of config files:: 
* Syntax of config files:: 

@end menu

@node Location and names of config files,Syntax of config files,,Distutils 配置文件Configuration Files
@anchor{install/index inst-config-filenames}@anchor{46b8}@anchor{install/index location-and-names-of-config-files}@anchor{46b9}
@subsection Location and names of config files


The names and locations of the configuration files vary slightly across
platforms.  On Unix and macOS, the three configuration files (in the order
they are processed) are:


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

文件类型

@tab

位置和文件名

@tab

注释

@item

system

@tab

@code{@emph{prefix}/lib/python@emph{ver}/distutils/distutils.cfg}

@tab

(1)

@item

personal

@tab

@code{$HOME/.pydistutils.cfg}

@tab

(2)

@item

local

@tab

@code{setup.cfg}

@tab

(3)

@end multitable


And on Windows, the configuration files are:


@multitable {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxx} 
@headitem

文件类型

@tab

位置和文件名

@tab

注释

@item

system

@tab

@code{@emph{prefix}\Lib\distutils\distutils.cfg}

@tab

(4)

@item

personal

@tab

@code{%HOME%\pydistutils.cfg}

@tab

(5)

@item

local

@tab

@code{setup.cfg}

@tab

(3)

@end multitable


On all platforms, the "personal" file can be temporarily disabled by
passing the @cite{--no-user-cfg} option.

注释:


@enumerate 

@item 
Strictly speaking, the system-wide configuration file lives in the directory
where the Distutils are installed; under Python 1.6 and later on Unix, this is
as shown. For Python 1.5.2, the Distutils will normally be installed to
@code{@emph{prefix}/lib/python1.5/site-packages/distutils}, so the system
configuration file should be put there under Python 1.5.2.

@item 
On Unix, if the 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} environment variable is not defined, the user's
home directory will be determined with the @code{getpwuid()} function from the
standard @ref{d6,,pwd} module. This is done by the @ref{333,,os.path.expanduser()}
function used by Distutils.

@item 
I.e., in the current directory (usually the location of the setup script).

@item 
(See also note (1).)  Under Python 1.6 and later, Python's default "installation
prefix" is @code{C:\Python}, so the system configuration file is normally
@code{C:\Python\Lib\distutils\distutils.cfg}. Under Python 1.5.2, the
default prefix was @code{C:\Program Files\Python}, and the Distutils were not
part of the standard library---so the system configuration file would be
@code{C:\Program Files\Python\distutils\distutils.cfg} in a standard Python
1.5.2 installation under Windows.

@item 
On Windows, if the 
@geindex HOME
@geindex 环境变量; HOME
@code{HOME} environment variable is not defined,
@geindex USERPROFILE
@geindex 环境变量; USERPROFILE
@code{USERPROFILE} then 
@geindex HOMEDRIVE
@geindex 环境变量; HOMEDRIVE
@code{HOMEDRIVE} and 
@geindex HOMEPATH
@geindex 环境变量; HOMEPATH
@code{HOMEPATH} will
be tried. This is done by the @ref{333,,os.path.expanduser()} function used
by Distutils.
@end enumerate

@node Syntax of config files,,Location and names of config files,Distutils 配置文件Configuration Files
@anchor{install/index inst-config-syntax}@anchor{45d2}@anchor{install/index syntax-of-config-files}@anchor{46ba}
@subsection Syntax of config files


The Distutils configuration files all have the same syntax.  The config files
are grouped into sections.  There is one section for each Distutils command,
plus a @code{global} section for global options that affect every command.  Each
section consists of one option per line, specified as @code{option=value}.

For example, the following is a complete config file that just forces all
commands to run quietly by default:

@example
[global]
verbose=0
@end example

If this is installed as the system config file, it will affect all processing of
any Python module distribution by any user on the current system.  If it is
installed as your personal config file (on systems that support them), it will
affect only module distributions processed by you.  And if it is used as the
@code{setup.cfg} for a particular module distribution, it affects only that
distribution.

You could override the default "build base" directory and make the
@code{build*} commands always forcibly rebuild all files with the
following:

@example
[build]
build-base=blib
force=1
@end example

which corresponds to the command-line arguments

@example
python setup.py build --build-base=blib --force
@end example

except that including the @code{build} command on the command-line means
that command will be run.  Including a particular command in config files has no
such implication; it only means that if the command is run, the options in the
config file will apply.  (Or if other commands that derive values from it are
run, they will use the values in the config file.)

You can find out the complete list of options for any command using the
@code{--help} option, e.g.:

@example
python setup.py build --help
@end example

and you can find out the complete list of global options by using
@code{--help} without a command:

@example
python setup.py --help
@end example

See also the "Reference" section of the "Distributing Python Modules" manual.

@node Building Extensions Tips and Tricks,,Distutils 配置文件Configuration Files,安装Python模块（旧版）
@anchor{install/index building-extensions-tips-and-tricks}@anchor{46bb}@anchor{install/index inst-building-ext}@anchor{46bc}
@section Building Extensions: Tips and Tricks


Whenever possible, the Distutils try to use the configuration information made
available by the Python interpreter used to run the @code{setup.py} script.
For example, the same compiler and linker flags used to compile Python will also
be used for compiling extensions.  Usually this will work well, but in
complicated situations this might be inappropriate.  This section discusses how
to override the usual Distutils behaviour.

@menu
* Tweaking compiler/linker flags:: 
* Using non-Microsoft compilers on Windows:: 

@end menu

@node Tweaking compiler/linker flags,Using non-Microsoft compilers on Windows,,Building Extensions Tips and Tricks
@anchor{install/index inst-tweak-flags}@anchor{46bd}@anchor{install/index tweaking-compiler-linker-flags}@anchor{46be}
@subsection Tweaking compiler/linker flags


Compiling a Python extension written in C or C++ will sometimes require
specifying custom flags for the compiler and linker in order to use a particular
library or produce a special kind of object code. This is especially true if the
extension hasn't been tested on your platform, or if you're trying to
cross-compile Python.

In the most general case, the extension author might have foreseen that
compiling the extensions would be complicated, and provided a @code{Setup} file
for you to edit.  This will likely only be done if the module distribution
contains many separate extension modules, or if they often require elaborate
sets of compiler flags in order to work.

A @code{Setup} file, if present, is parsed in order to get a list of extensions
to build.  Each line in a @code{Setup} describes a single module.  Lines have
the following structure:

@example
module ... [sourcefile ...] [cpparg ...] [library ...]
@end example

Let's examine each of the fields in turn.


@itemize *

@item 
@emph{module} is the name of the extension module to be built, and should be a
valid Python identifier.  You can't just change this in order to rename a module
(edits to the source code would also be needed), so this should be left alone.

@item 
@emph{sourcefile} is anything that's likely to be a source code file, at least
judging by the filename.  Filenames ending in @code{.c} are assumed to be
written in C, filenames ending in @code{.C}, @code{.cc}, and @code{.c++} are
assumed to be C++, and filenames ending in @code{.m} or @code{.mm} are assumed
to be in Objective C.

@item 
@emph{cpparg} is an argument for the C preprocessor,  and is anything starting with
@code{-I}, @code{-D}, @code{-U} or @code{-C}.

@item 
@emph{library} is anything ending in @code{.a} or beginning with @code{-l} or
@code{-L}.
@end itemize

If a particular platform requires a special library on your platform, you can
add it by editing the @code{Setup} file and running @code{python setup.py build}.
For example, if the module defined by the line

@example
foo foomodule.c
@end example

must be linked with the math library @code{libm.a} on your platform, simply add
@code{-lm} to the line:

@example
foo foomodule.c -lm
@end example

Arbitrary switches intended for the compiler or the linker can be supplied with
the @code{-Xcompiler} @emph{arg} and @code{-Xlinker} @emph{arg} options:

@example
foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm
@end example

The next option after @code{-Xcompiler} and @code{-Xlinker} will be
appended to the proper command line, so in the above example the compiler will
be passed the @code{-o32} option, and the linker will be passed
@code{-shared}.  If a compiler option requires an argument, you'll have to
supply multiple @code{-Xcompiler} options; for example, to pass @code{-x c++}
the @code{Setup} file would have to contain @code{-Xcompiler -x -Xcompiler c++}.

Compiler flags can also be supplied through setting the 
@geindex CFLAGS
@geindex 环境变量; CFLAGS
@code{CFLAGS}
environment variable.  If set, the contents of 
@geindex CFLAGS
@geindex 环境变量; CFLAGS
@code{CFLAGS} will be added to
the compiler flags specified in the  @code{Setup} file.

@node Using non-Microsoft compilers on Windows,,Tweaking compiler/linker flags,Building Extensions Tips and Tricks
@anchor{install/index inst-non-ms-compilers}@anchor{46bf}@anchor{install/index using-non-microsoft-compilers-on-windows}@anchor{46c0}
@subsection Using non-Microsoft compilers on Windows


@menu
* Borland/CodeGear C++:: 
* GNU C / Cygwin / MinGW:: 

@end menu

@node Borland/CodeGear C++,GNU C / Cygwin / MinGW,,Using non-Microsoft compilers on Windows
@anchor{install/index borland-codegear-c}@anchor{46c1}
@subsubsection Borland/CodeGear C++


This subsection describes the necessary steps to use Distutils with the Borland
C++ compiler version 5.5.  First you have to know that Borland's object file
format (OMF) is different from the format used by the Python version you can
download from the Python or ActiveState Web site.  (Python is built with
Microsoft Visual C++, which uses COFF as the object file format.) For this
reason you have to convert Python's library @code{python25.lib} into the
Borland format.  You can do this as follows:

@c Should we mention that users have to create cfg-files for the compiler?

@c see also http://community.borland.com/article/0,1410,21205,00.html

@example
coff2omf python25.lib python25_bcpp.lib
@end example

The @code{coff2omf} program comes with the Borland compiler.  The file
@code{python25.lib} is in the @code{Libs} directory of your Python
installation.  If your extension uses other libraries (zlib, ...) you have to
convert them too.

The converted files have to reside in the same directories as the normal
libraries.

How does Distutils manage to use these libraries with their changed names?  If
the extension needs a library (eg. @code{foo}) Distutils checks first if it
finds a library with suffix @code{_bcpp} (eg. @code{foo_bcpp.lib}) and then
uses this library.  In the case it doesn't find such a special library it uses
the default name (@code{foo.lib}.) @footnote{@w{(1)} 
This also means you could replace all existing COFF-libraries with OMF-libraries
of the same name.
}

To let Distutils compile your extension with Borland C++ you now have to type:

@example
python setup.py build --compiler=bcpp
@end example

If you want to use the Borland C++ compiler as the default, you could specify
this in your personal or system-wide configuration file for Distutils (see
section @ref{46a7,,Distutils 配置文件Configuration Files}.)


@subsubheading 参见



@table @asis

@item C++Builder Compiler@footnote{https://www.embarcadero.com/products}

Information about the free C++ compiler from Borland, including links to the
download pages.

@item Creating Python Extensions Using Borland's Free Compiler@footnote{http://www.cyberus.ca/~g_will/pyExtenDL.shtml}

Document describing how to use Borland's free command-line C++ compiler to build
Python.
@end table


@node GNU C / Cygwin / MinGW,,Borland/CodeGear C++,Using non-Microsoft compilers on Windows
@anchor{install/index gnu-c-cygwin-mingw}@anchor{46c2}
@subsubsection GNU C / Cygwin / MinGW


This section describes the necessary steps to use Distutils with the GNU C/C++
compilers in their Cygwin and MinGW distributions. @footnote{@w{(2)} 
Check @indicateurl{https://www.sourceware.org/cygwin/} for more information
} For a Python interpreter
that was built with Cygwin, everything should work without any of these
following steps.

Not all extensions can be built with MinGW or Cygwin, but many can.  Extensions
most likely to not work are those that use C++ or depend on Microsoft Visual C
extensions.

To let Distutils compile your extension with Cygwin you have to type:

@example
python setup.py build --compiler=cygwin
@end example

and for Cygwin in no-cygwin mode @footnote{@w{(3)} 
Then you have no POSIX emulation available, but you also don't need
@code{cygwin1.dll}.
} or for MinGW type:

@example
python setup.py build --compiler=mingw32
@end example

If you want to use any of these options/compilers as default, you should
consider writing it in your personal or system-wide configuration file for
Distutils (see section @ref{46a7,,Distutils 配置文件Configuration Files}.)

@menu
* Older Versions of Python and MinGW:: 

@end menu

@node Older Versions of Python and MinGW,,,GNU C / Cygwin / MinGW
@anchor{install/index older-versions-of-python-and-mingw}@anchor{46c3}
@subsubsection Older Versions of Python and MinGW


The following instructions only apply if you're using a version of Python
inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with
binutils-2.13.90-20030111-1).

These compilers require some special libraries.  This task is more complex than
for Borland's C++, because there is no program to convert the library.  First
you have to create a list of symbols which the Python DLL exports. (You can find
a good program for this task at
@indicateurl{https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/}).

@c I don't understand what the next line means. --amk

@c (inclusive the references on data structures.)

@example
pexports python25.dll >python25.def
@end example

The location of an installed @code{python25.dll} will depend on the
installation options and the version and language of Windows.  In a "just for
me" installation, it will appear in the root of the installation directory.  In
a shared installation, it will be located in the system directory.

Then you can create from these information an import library for gcc.

@example
/cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a
@end example

The resulting library has to be placed in the same directory as
@code{python25.lib}. (Should be the @code{libs} directory under your Python
installation directory.)

If your extension uses other libraries (zlib,...) you might  have to convert
them too. The converted files have to reside in the same directories as the
normal libraries do.


@subsubheading 参见



@table @asis

@item Building Python modules on MS Windows platform with MinGW@footnote{http://old.zope.org/Members/als/tips/win32_mingw_modules}

Information about building the required libraries for the MinGW environment.
@end table


@node Python 模块索引,索引,安装Python模块（旧版）,Top
@unnumbered Python 模块索引


@menu
* __future__: 0. Future statement definitions
* __main__: 1. The environment where the top-level script is run.
* _thread: 2. Low-level threading API.
* abc: 3. Abstract base classes according to :pep:`3119`.
* aifc: 4. Read and write audio files in AIFF or AIFC format.
* argparse: 5. Command-line option and argument parsing library.
* array: 6. Space efficient arrays of uniformly typed numeric
                        values.
* ast: 7. Abstract Syntax Tree classes and manipulation.
* asynchat: 8. Support for asynchronous command/response protocols.
* asyncio: 9. Asynchronous I/O.
* asyncore: a. A base class for developing asynchronous socket
                        handling services.
* atexit: b. Register and execute cleanup functions.
* audioop: c. Manipulate raw audio data.
* base64: d. RFC 3548: Base16@comma{} Base32@comma{} Base64 Data
                        Encodings; Base85 and Ascii85
* bdb: e. Debugger framework.
* binascii: f. Tools for converting between binary and various ASCII-
                        encoded binary representations.
* binhex: 10. Encode and decode files in binhex4 format.
* bisect: 11. Array bisection algorithms for binary searching.
* builtins: 12. The module that provides the built-in namespace.
* bz2: 13. Interfaces for bzip2 compression and decompression.
* calendar: 14. Functions for working with calendars@comma{} including
                        some emulation of the Unix cal program.
* cgi: 15. Helpers for running Python scripts via the Common
                        Gateway Interface.
* cgitb: 16. Configurable traceback handler for CGI scripts.
* chunk: 17. Module to read IFF chunks.
* cmath: 18. Mathematical functions for complex numbers.
* cmd: 19. Build line-oriented command interpreters.
* code: 1a. Facilities to implement read-eval-print loops.
* codecs: 1b. Encode and decode data and streams.
* codeop: 1c. Compile (possibly incomplete) Python code.
* collections: 1d. Container datatypes
* collections.abc: 1e. Abstract base classes for containers
* colorsys: 1f. Conversion functions between RGB and other color
                        systems.
* compileall: 20. Tools for byte-compiling all Python source files in a
                        directory tree.
* concurrent.futures: 21. Execute computations concurrently using threads or
                        processes.
* configparser: 22. Configuration file parser.
* contextlib: 23. Utilities for with-statement contexts.
* contextvars: 24. Context Variables
* copy: 25. Shallow and deep copy operations.
* copyreg: 26. Register pickle support functions.
* cProfile: 27. 
* crypt: 28. The crypt() function used to check Unix passwords.
* csv: 29. Write and read tabular data to and from delimited
                        files.
* ctypes: 2a. A foreign function library for Python.
* curses: 2b. An interface to the curses library@comma{} providing
                        portable terminal handling.
* curses.ascii: 2c. Constants and set-membership functions for ASCII
                        characters.
* curses.panel: 2d. A panel stack extension that adds depth to curses
                        windows.
* curses.textpad: 2e. Emacs-like input editing in a curses window.
* dataclasses: 2f. Generate special methods on user-defined classes.
* datetime: 30. Basic date and time types.
* dbm: 31. Interfaces to various Unix "database" formats.
* dbm.dumb: 32. Portable implementation of the simple DBM interface.
* dbm.gnu: 33. GNU's reinterpretation of dbm.
* dbm.ndbm: 34. The standard "database" interface@comma{} based on
                        ndbm.
* decimal: 35. Implementation of the General Decimal Arithmetic
                        Specification.
* difflib: 36. Helpers for computing differences between objects.
* dis: 37. Disassembler for Python bytecode.
* distutils: 38. Support for building and installing Python modules
                        into an existing Python installation.
* distutils.archive_util: 39. Utility functions for creating archive files
                          (tarballs@comma{} zip files@comma{} ...)
* distutils.bcppcompiler: 3a. 
* distutils.ccompiler: 3b. Abstract CCompiler class
* distutils.cmd: 3c. Provides the abstract base class
                        :class:`~distutils.cmd.Command`. This class is
                        subclassed by the modules in the distutils.command
                        subpackage.
* distutils.command: 3d. Contains one module for each standard Distutils
                        command.
* distutils.command.bdist: 3e. Build a binary installer for a package
* distutils.command.bdist_dumb: 3f. Build a "dumb" installer - a simple archive of
                                files
* distutils.command.bdist_msi: 40. Build a binary distribution as a Windows MSI
                               file
* distutils.command.bdist_packager: 41. Abstract base class for packagers
* distutils.command.bdist_rpm: 42. Build a binary distribution as a Redhat RPM and
                               SRPM
* distutils.command.bdist_wininst: 43. Build a Windows installer
* distutils.command.build: 44. Build all files of a package
* distutils.command.build_clib: 45. Build any C libraries in a package
* distutils.command.build_ext: 46. Build any extensions in a package
* distutils.command.build_py: 47. Build the .py/.pyc files of a package
* distutils.command.build_scripts: 48. Build the scripts of a package
* distutils.command.check: 49. Check the meta-data of a package
* distutils.command.clean: 4a. Clean a package build area
* distutils.command.config: 4b. Perform package configuration
* distutils.command.install: 4c. Install a package
* distutils.command.install_data: 4d. Install data files from a package
* distutils.command.install_headers: 4e. Install C/C++ header files from a package
* distutils.command.install_lib: 4f. Install library files from a package
* distutils.command.install_scripts: 50. Install script files from a package
* distutils.command.register: 51. Register a module with the Python Package Index
* distutils.command.sdist: 52. Build a source distribution
* distutils.core: 53. The core Distutils functionality
* distutils.cygwinccompiler: 54. 
* distutils.debug: 55. Provides the debug flag for distutils
* distutils.dep_util: 56. Utility functions for simple dependency checking
* distutils.dir_util: 57. Utility functions for operating on directories and
                        directory trees
* distutils.dist: 58. Provides the Distribution class@comma{} which
                        represents the module distribution being
                        built/installed/distributed
* distutils.errors: 59. Provides standard distutils exceptions
* distutils.extension: 5a. Provides the Extension class@comma{} used to describe
                        C/C++ extension modules in setup scripts
* distutils.fancy_getopt: 5b. Additional getopt functionality
* distutils.file_util: 5c. Utility functions for operating on single files
* distutils.filelist: 5d. The FileList class@comma{} used for poking about the
                        file system and building lists of files.
* distutils.log: 5e. A simple logging mechanism@comma{} :pep:`282`-style
* distutils.msvccompiler: 5f. Microsoft Compiler
* distutils.spawn: 60. Provides the spawn() function
* distutils.sysconfig: 61. Low-level access to configuration information of the
                        Python interpreter.
* distutils.text_file: 62. Provides the TextFile class@comma{} a simple interface
                        to text files
* distutils.unixccompiler: 63. UNIX C Compiler
* distutils.util: 64. Miscellaneous other utility functions
* distutils.version: 65. Implements classes that represent module version
                        numbers.
* doctest: 66. Test pieces of code within docstrings.
* email: 67. Package supporting the parsing@comma{}
                        manipulating@comma{} and generating email messages.
* email.charset: 68. Character Sets
* email.contentmanager: 69. Storing and Retrieving Content from MIME Parts
* email.encoders: 6a. Encoders for email message payloads.
* email.errors: 6b. The exception classes used by the email package.
* email.generator: 6c. Generate flat text email messages from a message
                        structure.
* email.header: 6d. Representing non-ASCII headers
* email.headerregistry: 6e. Automatic Parsing of headers based on the field name
* email.iterators: 6f. Iterate over a message object tree.
* email.message: 70. The base class representing email messages.
* email.mime: 71. Build MIME messages.
* email.parser: 72. Parse flat text email messages to produce a message
                        object structure.
* email.policy: 73. Controlling the parsing and generating of messages
* email.utils: 74. Miscellaneous email package utilities.
* encodings.idna: 75. Internationalized Domain Names implementation
* encodings.mbcs: 76. Windows ANSI codepage
* encodings.utf_8_sig: 77. UTF-8 codec with BOM signature
* ensurepip: 78. Bootstrapping the "pip" installer into an existing
                        Python installation or virtual environment.
* enum: 79. Implementation of an enumeration class.
* errno: 7a. Standard errno system symbols.
* faulthandler: 7b. Dump the Python traceback.
* fcntl: 7c. The fcntl() and ioctl() system calls.
* filecmp: 7d. Compare files efficiently.
* fileinput: 7e. Loop over standard input or a list of files.
* fnmatch: 7f. Unix shell style filename pattern matching.
* formatter: 80. Generic output formatter and device interface.
* fractions: 81. Rational numbers.
* ftplib: 82. FTP protocol client (requires sockets).
* functools: 83. Higher-order functions and operations on callable
                        objects.
* gc: 84. Interface to the cycle-detecting garbage collector.
* getopt: 85. Portable parser for command line options; support both
                        short and long option names.
* getpass: 86. Portable reading of passwords and retrieval of the
                        userid.
* gettext: 87. Multilingual internationalization services.
* glob: 88. Unix shell style pathname pattern expansion.
* graphlib: 89. Functionality to operate with graph-like structures
* grp: 8a. The group database (getgrnam() and friends).
* gzip: 8b. Interfaces for gzip compression and decompression
                        using file objects.
* hashlib: 8c. Secure hash and message digest algorithms.
* heapq: 8d. Heap queue algorithm (a.k.a. priority queue).
* hmac: 8e. Keyed-Hashing for Message Authentication (HMAC)
                        implementation
* html: 8f. Helpers for manipulating HTML.
* html.entities: 90. Definitions of HTML general entities.
* html.parser: 91. A simple parser that can handle HTML and XHTML.
* http: 92. HTTP status codes and messages
* http.client: 93. HTTP and HTTPS protocol client (requires sockets).
* http.cookiejar: 94. Classes for automatic handling of HTTP cookies.
* http.cookies: 95. Support for HTTP state management (cookies).
* http.server: 96. HTTP server and request handlers.
* imaplib: 97. IMAP4 protocol client (requires sockets).
* imghdr: 98. Determine the type of image contained in a file or
                        byte stream.
* imp: 99. Access the implementation of the import statement.
* importlib: 9a. The implementation of the import machinery.
* importlib.abc: 9b. Abstract base classes related to import
* importlib.machinery: 9c. Importers and path hooks
* importlib.metadata: 9d. The implementation of the importlib metadata.
* importlib.resources: 9e. Package resource reading@comma{} opening@comma{} and
                        access
* importlib.util: 9f. Utility code for importers
* inspect: a0. Extract information and source code from live objects.
* io: a1. Core tools for working with streams.
* ipaddress: a2. IPv4/IPv6 manipulation library.
* itertools: a3. Functions creating iterators for efficient looping.
* json: a4. Encode and decode the JSON format.
* json.tool: a5. A command line to validate and pretty-print JSON.
* keyword: a6. Test whether a string is a keyword in Python.
* lib2to3: a7. The 2to3 library
* linecache: a8. Provides random access to individual lines from text
                        files.
* locale: a9. Internationalization services.
* logging: aa. Flexible event logging system for applications.
* logging.config: ab. Configuration of the logging module.
* logging.handlers: ac. Handlers for the logging module.
* lzma: ad. A Python wrapper for the liblzma compression library.
* mailbox: ae. Manipulate mailboxes in various formats
* mailcap: af. Mailcap file handling.
* marshal: b0. Convert Python objects to streams of bytes and back
                        (with different constraints).
* math: b1. Mathematical functions (sin() etc.).
* mimetypes: b2. Mapping of filename extensions to MIME types.
* mmap: b3. Interface to memory-mapped files for Unix and Windows.
* modulefinder: b4. Find modules used by a script.
* msilib: b5. Creation of Microsoft Installer files@comma{} and CAB
                        files.
* msvcrt: b6. Miscellaneous useful routines from the MS VC++
                        runtime.
* multiprocessing: b7. Process-based parallelism.
* multiprocessing.connection: b8. API for dealing with sockets.
* multiprocessing.dummy: b9. Dumb wrapper around threading.
* multiprocessing.managers: ba. Share data between process with shared objects.
* multiprocessing.pool: bb. Create pools of processes.
* multiprocessing.shared_memory: bc. Provides shared memory for direct access
                                 across processes.
* multiprocessing.sharedctypes: bd. Allocate ctypes objects from shared memory.
* netrc: be. Loading of .netrc files.
* nis: bf. Interface to Sun's NIS (Yellow Pages) library.
* nntplib: c0. NNTP protocol client (requires sockets).
* numbers: c1. Numeric abstract base classes (Complex@comma{}
                        Real@comma{} Integral@comma{} etc.).
* operator: c2. Functions corresponding to the standard operators.
* optparse: c3. Command-line option parsing library.
* os: c4. Miscellaneous operating system interfaces.
* os.path: c5. Operations on pathnames.
* ossaudiodev: c6. Access to OSS-compatible audio devices.
* parser: c7. Access parse trees for Python source code.
* pathlib: c8. Object-oriented filesystem paths
* pdb: c9. The Python debugger for interactive interpreters.
* pickle: ca. Convert Python objects to streams of bytes and back.
* pickletools: cb. Contains extensive comments about the pickle protocols
                        and pickle-machine opcodes@comma{} as well as some
                        useful functions.
* pipes: cc. A Python interface to Unix shell pipelines.
* pkgutil: cd. Utilities for the import system.
* platform: ce. Retrieves as much platform identifying data as
                        possible.
* plistlib: cf. Generate and parse Apple plist files.
* poplib: d0. POP3 protocol client (requires sockets).
* posix: d1. The most common POSIX system calls (normally used via
                        module os).
* pprint: d2. Data pretty printer.
* profile: d3. Python source profiler.
* pstats: d4. Statistics object for use with the profiler.
* pty: d5. Pseudo-Terminal Handling for Linux.
* pwd: d6. The password database (getpwnam() and friends).
* py_compile: d7. Generate byte-code files from Python source files.
* pyclbr: d8. Supports information extraction for a Python module
                        browser.
* pydoc: d9. Documentation generator and online help system.
* queue: da. A synchronized queue class.
* quopri: db. Encode and decode files using the MIME quoted-
                        printable encoding.
* random: dc. Generate pseudo-random numbers with various common
                        distributions.
* re: dd. Regular expression operations.
* readline: de. GNU readline support for Python.
* reprlib: df. Alternate repr() implementation with size limits.
* resource: e0. An interface to provide resource usage information on
                        the current process.
* rlcompleter: e1. Python identifier completion@comma{} suitable for the
                        GNU readline library.
* runpy: e2. Locate and run Python modules without importing them
                        first.
* sched: e3. General purpose event scheduler.
* secrets: e4. Generate secure random numbers for managing secrets.
* select: e5. Wait for I/O completion on multiple streams.
* selectors: e6. High-level I/O multiplexing.
* shelve: e7. Python object persistence.
* shlex: e8. Simple lexical analysis for Unix shell-like languages.
* shutil: e9. High-level file operations@comma{} including copying.
* signal: ea. Set handlers for asynchronous events.
* site: eb. Module responsible for site-specific configuration.
* smtpd: ec. A SMTP server implementation in Python.
* smtplib: ed. SMTP protocol client (requires sockets).
* sndhdr: ee. Determine type of a sound file.
* socket: ef. Low-level networking interface.
* socketserver: f0. A framework for network servers.
* spwd: f1. The shadow password database (getspnam() and friends).
* sqlite3: f2. A DB-API 2.0 implementation using SQLite 3.x.
* ssl: f3. TLS/SSL wrapper for socket objects
* stat: f4. Utilities for interpreting the results of
                        os.stat()@comma{} os.lstat() and os.fstat().
* statistics: f5. Mathematical statistics functions
* string: f6. Common string operations.
* stringprep: f7. String preparation@comma{} as per RFC 3453
* struct: f8. Interpret bytes as packed binary data.
* subprocess: f9. Subprocess management.
* sunau: fa. Provide an interface to the Sun AU sound format.
* symbol: fb. Constants representing internal nodes of the parse
                        tree.
* symtable: fc. Interface to the compiler's internal symbol tables.
* sys: fd. Access system-specific parameters and functions.
* sysconfig: fe. Python's configuration information
* syslog: ff. An interface to the Unix syslog library routines.
* tabnanny: 100. Tool for detecting white space related problems in
                        Python source files in a directory tree.
* tarfile: 101. Read and write tar-format archive files.
* telnetlib: 102. Telnet client class.
* tempfile: 103. Generate temporary files and directories.
* termios: 104. POSIX style tty control.
* test: 105. Regression tests package containing the testing suite
                        for Python.
* test.support: 106. Support for Python's regression test suite.
* test.support.bytecode_helper: 107. Support tools for testing correct bytecode
                                generation.
* test.support.script_helper: 108. Support for Python's script execution tests.
* test.support.socket_helper: 109. Support for socket tests.
* textwrap: 10a. Text wrapping and filling
* threading: 10b. Thread-based parallelism.
* time: 10c. Time access and conversions.
* timeit: 10d. Measure the execution time of small code snippets.
* tkinter: 10e. Interface to Tcl/Tk for graphical user interfaces
* tkinter.colorchooser: 10f. Color choosing dialog
* tkinter.commondialog: 110. Tkinter base class for dialogs
* tkinter.dnd: 111. Tkinter drag-and-drop interface
* tkinter.filedialog: 112. Dialog classes for file selection
* tkinter.font: 113. Tkinter font-wrapping class
* tkinter.messagebox: 114. Various types of alert dialogs
* tkinter.scrolledtext: 115. Text widget with a vertical scroll bar.
* tkinter.simpledialog: 116. Simple dialog windows
* tkinter.tix: 117. Tk Extension Widgets for Tkinter
* tkinter.ttk: 118. Tk themed widget set
* token: 119. Constants representing terminal nodes of the parse
                        tree.
* tokenize: 11a. Lexical scanner for Python source code.
* trace: 11b. Trace or track Python statement execution.
* traceback: 11c. Print or retrieve a stack traceback.
* tracemalloc: 11d. Trace memory allocations.
* tty: 11e. Utility functions that perform common terminal control
                        operations.
* turtle: 11f. An educational framework for simple graphics
                        applications
* turtledemo: 120. A viewer for example turtle scripts
* types: 121. Names for built-in types.
* typing: 122. Support for type hints (see :pep:`484`).
* unicodedata: 123. Access the Unicode Database.
* unittest: 124. Unit testing framework for Python.
* unittest.mock: 125. Mock object library.
* urllib: 126. 
* urllib.error: 127. Exception classes raised by urllib.request.
* urllib.parse: 128. Parse URLs into or assemble them from components.
* urllib.request: 129. Extensible library for opening URLs.
* urllib.response: 12a. Response classes used by urllib.
* urllib.robotparser: 12b. Load a robots.txt file and answer questions about
                        fetchability of other URLs.
* uu: 12c. Encode and decode files in uuencode format.
* uuid: 12d. UUID objects (universally unique identifiers)
                        according to RFC 4122
* venv: 12e. Creation of virtual environments.
* warnings: 12f. Issue warning messages and control their disposition.
* wave: 130. Provide an interface to the WAV sound format.
* weakref: 131. Support for weak references and weak dictionaries.
* webbrowser: 132. Easy-to-use controller for Web browsers.
* winreg: 133. Routines and objects for manipulating the Windows
                        registry.
* winsound: 134. Access to the sound-playing machinery for Windows.
* wsgiref: 135. WSGI Utilities and Reference Implementation.
* wsgiref.handlers: 136. WSGI server/gateway base classes.
* wsgiref.headers: 137. WSGI response header tools.
* wsgiref.simple_server: 138. A simple WSGI HTTP server.
* wsgiref.util: 139. WSGI environment utilities.
* wsgiref.validate: 13a. WSGI conformance checker.
* xdrlib: 13b. Encoders and decoders for the External Data
                        Representation (XDR).
* xml: 13c. Package containing XML processing modules
* xml.dom: 13d. Document Object Model API for Python.
* xml.dom.minidom: 13e. Minimal Document Object Model (DOM) implementation.
* xml.dom.pulldom: 13f. Support for building partial DOM trees from SAX
                        events.
* xml.etree.ElementTree: 140. Implementation of the ElementTree API.
* xml.parsers.expat: 141. An interface to the Expat non-validating XML parser.
* xml.parsers.expat.errors: 142. 
* xml.parsers.expat.model: 143. 
* xml.sax: 144. Package containing SAX2 base classes and convenience
                        functions.
* xml.sax.handler: 145. Base classes for SAX event handlers.
* xml.sax.saxutils: 146. Convenience functions and classes for use with SAX.
* xml.sax.xmlreader: 147. Interface which SAX-compliant XML parsers must
                        implement.
* xmlrpc.client: 148. XML-RPC client access.
* xmlrpc.server: 149. Basic XML-RPC server implementations.
* zipapp: 14a. Manage executable Python zip archives
* zipfile: 14b. Read and write ZIP-format archive files.
* zipimport: 14c. Support for importing Python modules from ZIP
                        archives.
* zlib: 14d. Low-level interface to compression and decompression
                        routines compatible with gzip.
* zoneinfo: 14e. IANA time zone support
@end menu


@node 索引,,Python 模块索引,Top
@unnumbered 索引


@printindex ge

@anchor{using/cmdline audit_event_cpython_run_file_0}@w{                              }
@anchor{4437}@w{                              }
@anchor{howto/urllib2 basic-authentication}@w{                              }
@anchor{using/cmdline audit_event_cpython_run_stdin_0}@w{                              }
@anchor{4443}@w{                              }
@anchor{3553}@w{                              }
@anchor{howto/urllib2 quick-reference-to-http-headers}@w{                              }
@anchor{3554}@w{                              }

@c %**end of body
@bye
